Path: blob/main/website/GAUSS/js/paper-full.js
2941 views
/*!1* Paper.js v0.9.18 - The Swiss Army Knife of Vector Graphics Scripting.2* http://paperjs.org/3*4* Copyright (c) 2011 - 2014, Juerg Lehni & Jonathan Puckey5* http://scratchdisk.com/ & http://jonathanpuckey.com/6*7* Distributed under the MIT license. See LICENSE file for details.8*9* All rights reserved.10*11* Date: Mon Apr 7 11:24:38 2014 +020012*13***14*15* Straps.js - Class inheritance library with support for bean-style accessors16*17* Copyright (c) 2006 - 2013 Juerg Lehni18* http://scratchdisk.com/19*20* Distributed under the MIT license.21*22***23*24* Acorn.js25* http://marijnhaverbeke.nl/acorn/26*27* Acorn is a tiny, fast JavaScript parser written in JavaScript,28* created by Marijn Haverbeke and released under an MIT license.29*30*/3132var paper = new function(undefined) {3334var Base = new function() {35var hidden = /^(statics|enumerable|beans|preserve)$/,3637forEach = [].forEach || function(iter, bind) {38for (var i = 0, l = this.length; i < l; i++)39iter.call(bind, this[i], i, this);40},4142forIn = function(iter, bind) {43for (var i in this)44if (this.hasOwnProperty(i))45iter.call(bind, this[i], i, this);46},4748create = Object.create || function(proto) {49return { __proto__: proto };50},5152describe = Object.getOwnPropertyDescriptor || function(obj, name) {53var get = obj.__lookupGetter__ && obj.__lookupGetter__(name);54return get55? { get: get, set: obj.__lookupSetter__(name),56enumerable: true, configurable: true }57: obj.hasOwnProperty(name)58? { value: obj[name], enumerable: true,59configurable: true, writable: true }60: null;61},6263_define = Object.defineProperty || function(obj, name, desc) {64if ((desc.get || desc.set) && obj.__defineGetter__) {65if (desc.get)66obj.__defineGetter__(name, desc.get);67if (desc.set)68obj.__defineSetter__(name, desc.set);69} else {70obj[name] = desc.value;71}72return obj;73},7475define = function(obj, name, desc) {76delete obj[name];77return _define(obj, name, desc);78};7980function inject(dest, src, enumerable, beans, preserve) {81var beansNames = {};8283function field(name, val) {84val = val || (val = describe(src, name))85&& (val.get ? val : val.value);86if (typeof val === 'string' && val[0] === '#')87val = dest[val.substring(1)] || val;88var isFunc = typeof val === 'function',89res = val,90prev = preserve || isFunc91? (val && val.get ? name in dest : dest[name])92: null,93bean;94if (!preserve || !prev) {95if (isFunc && prev)96val.base = prev;97if (isFunc && beans !== false98&& (bean = name.match(/^([gs]et|is)(([A-Z])(.*))$/)))99beansNames[bean[3].toLowerCase() + bean[4]] = bean[2];100if (!res || isFunc || !res.get || typeof res.get !== 'function'101|| !Base.isPlainObject(res))102res = { value: res, writable: true };103if ((describe(dest, name)104|| { configurable: true }).configurable) {105res.configurable = true;106res.enumerable = enumerable;107}108define(dest, name, res);109}110}111if (src) {112for (var name in src) {113if (src.hasOwnProperty(name) && !hidden.test(name))114field(name);115}116for (var name in beansNames) {117var part = beansNames[name],118set = dest['set' + part],119get = dest['get' + part] || set && dest['is' + part];120if (get && (beans === true || get.length === 0))121field(name, { get: get, set: set });122}123}124return dest;125}126127function each(obj, iter, bind) {128if (obj)129('length' in obj && !obj.getLength130&& typeof obj.length === 'number'131? forEach132: forIn).call(obj, iter, bind = bind || obj);133return bind;134}135136function set(obj, props) {137for (var i in props)138if (props.hasOwnProperty(i))139obj[i] = props[i];140return obj;141}142143return inject(function Base() {144for (var i = 0, l = arguments.length; i < l; i++)145set(this, arguments[i]);146}, {147inject: function(src) {148if (src) {149var statics = src.statics === true ? src : src.statics,150beans = src.beans,151preserve = src.preserve;152if (statics !== src)153inject(this.prototype, src, src.enumerable, beans, preserve);154inject(this, statics, true, beans, preserve);155}156for (var i = 1, l = arguments.length; i < l; i++)157this.inject(arguments[i]);158return this;159},160161extend: function() {162var base = this,163ctor;164for (var i = 0, l = arguments.length; i < l; i++)165if (ctor = arguments[i].initialize)166break;167ctor = ctor || function() {168base.apply(this, arguments);169};170ctor.prototype = create(this.prototype);171ctor.base = base;172define(ctor.prototype, 'constructor',173{ value: ctor, writable: true, configurable: true });174inject(ctor, this, true);175return arguments.length ? this.inject.apply(ctor, arguments) : ctor;176}177}, true).inject({178inject: function() {179for (var i = 0, l = arguments.length; i < l; i++) {180var src = arguments[i];181if (src)182inject(this, src, src.enumerable, src.beans, src.preserve);183}184return this;185},186187extend: function() {188var res = create(this);189return res.inject.apply(res, arguments);190},191192each: function(iter, bind) {193return each(this, iter, bind);194},195196clone: function() {197return new this.constructor(this);198},199200statics: {201each: each,202create: create,203define: define,204describe: describe,205set: set,206207clone: function(obj) {208return set(new obj.constructor(), obj);209},210211isPlainObject: function(obj) {212var ctor = obj != null && obj.constructor;213return ctor && (ctor === Object || ctor === Base214|| ctor.name === 'Object');215},216217pick: function() {218for (var i = 0, l = arguments.length; i < l; i++)219if (arguments[i] !== undefined)220return arguments[i];221}222}223});224};225226if (typeof module !== 'undefined')227module.exports = Base;228229if (!Array.isArray) {230Array.isArray = function(obj) {231return Object.prototype.toString.call(obj) === '[object Array]';232};233}234235if (!document.head) {236document.head = document.getElementsByTagName('head')[0];237}238239Base.inject({240toString: function() {241return this._id != null242? (this._class || 'Object') + (this._name243? " '" + this._name + "'"244: ' @' + this._id)245: '{ ' + Base.each(this, function(value, key) {246if (!/^_/.test(key)) {247var type = typeof value;248this.push(key + ': ' + (type === 'number'249? Formatter.instance.number(value)250: type === 'string' ? "'" + value + "'" : value));251}252}, []).join(', ') + ' }';253},254255exportJSON: function(options) {256return Base.exportJSON(this, options);257},258259toJSON: function() {260return Base.serialize(this);261},262263_set: function(props, exclude) {264if (props && Base.isPlainObject(props)) {265var orig = props._filtering || props;266for (var key in orig) {267if (key in this && orig.hasOwnProperty(key)268&& (!exclude || !exclude[key])) {269var value = props[key];270if (value !== undefined)271this[key] = value;272}273}274return true;275}276},277278statics: {279280exports: {281enumerable: true282},283284extend: function extend() {285var res = extend.base.apply(this, arguments),286name = res.prototype._class;287if (name && !Base.exports[name])288Base.exports[name] = res;289return res;290},291292equals: function(obj1, obj2) {293function checkKeys(o1, o2) {294for (var i in o1)295if (o1.hasOwnProperty(i) && !o2.hasOwnProperty(i))296return false;297return true;298}299if (obj1 === obj2)300return true;301if (obj1 && obj1.equals)302return obj1.equals(obj2);303if (obj2 && obj2.equals)304return obj2.equals(obj1);305if (Array.isArray(obj1) && Array.isArray(obj2)) {306if (obj1.length !== obj2.length)307return false;308for (var i = 0, l = obj1.length; i < l; i++) {309if (!Base.equals(obj1[i], obj2[i]))310return false;311}312return true;313}314if (obj1 && typeof obj1 === 'object'315&& obj2 && typeof obj2 === 'object') {316if (!checkKeys(obj1, obj2) || !checkKeys(obj2, obj1))317return false;318for (var i in obj1) {319if (obj1.hasOwnProperty(i)320&& !Base.equals(obj1[i], obj2[i]))321return false;322}323return true;324}325return false;326},327328read: function(list, start, options, length) {329if (this === Base) {330var value = this.peek(list, start);331list.__index++;332return value;333}334var proto = this.prototype,335readIndex = proto._readIndex,336index = start || readIndex && list.__index || 0;337if (!length)338length = list.length - index;339var obj = list[index];340if (obj instanceof this341|| options && options.readNull && obj == null && length <= 1) {342if (readIndex)343list.__index = index + 1;344return obj && options && options.clone ? obj.clone() : obj;345}346obj = Base.create(this.prototype);347if (readIndex)348obj.__read = true;349obj = obj.initialize.apply(obj, index > 0 || length < list.length350? Array.prototype.slice.call(list, index, index + length)351: list) || obj;352if (readIndex) {353list.__index = index + obj.__read;354obj.__read = undefined;355}356return obj;357},358359peek: function(list, start) {360return list[list.__index = start || list.__index || 0];361},362363remain: function(list) {364return list.length - (list.__index || 0);365},366367readAll: function(list, start, options) {368var res = [],369entry;370for (var i = start || 0, l = list.length; i < l; i++) {371res.push(Array.isArray(entry = list[i])372? this.read(entry, 0, options)373: this.read(list, i, options, 1));374}375return res;376},377378readNamed: function(list, name, start, options, length) {379var value = this.getNamed(list, name),380hasObject = value !== undefined;381if (hasObject) {382var filtered = list._filtered;383if (!filtered) {384filtered = list._filtered = Base.create(list[0]);385filtered._filtering = list[0];386}387filtered[name] = undefined;388}389return this.read(hasObject ? [value] : list, start, options, length);390},391392getNamed: function(list, name) {393var arg = list[0];394if (list._hasObject === undefined)395list._hasObject = list.length === 1 && Base.isPlainObject(arg);396if (list._hasObject)397return name ? arg[name] : list._filtered || arg;398},399400hasNamed: function(list, name) {401return !!this.getNamed(list, name);402},403404isPlainValue: function(obj) {405return this.isPlainObject(obj) || Array.isArray(obj);406},407408serialize: function(obj, options, compact, dictionary) {409options = options || {};410411var root = !dictionary,412res;413if (root) {414options.formatter = new Formatter(options.precision);415dictionary = {416length: 0,417definitions: {},418references: {},419add: function(item, create) {420var id = '#' + item._id,421ref = this.references[id];422if (!ref) {423this.length++;424var res = create.call(item),425name = item._class;426if (name && res[0] !== name)427res.unshift(name);428this.definitions[id] = res;429ref = this.references[id] = [id];430}431return ref;432}433};434}435if (obj && obj._serialize) {436res = obj._serialize(options, dictionary);437var name = obj._class;438if (name && !compact && !res._compact && res[0] !== name)439res.unshift(name);440} else if (Array.isArray(obj)) {441res = [];442for (var i = 0, l = obj.length; i < l; i++)443res[i] = Base.serialize(obj[i], options, compact,444dictionary);445if (compact)446res._compact = true;447} else if (Base.isPlainObject(obj)) {448res = {};449for (var i in obj)450if (obj.hasOwnProperty(i))451res[i] = Base.serialize(obj[i], options, compact,452dictionary);453} else if (typeof obj === 'number') {454res = options.formatter.number(obj, options.precision);455} else {456res = obj;457}458return root && dictionary.length > 0459? [['dictionary', dictionary.definitions], res]460: res;461},462463deserialize: function(json, create, _data) {464var res = json,465isRoot = !_data;466_data = _data || {};467if (Array.isArray(json)) {468var type = json[0],469isDictionary = type === 'dictionary';470if (!isDictionary) {471if (_data.dictionary && json.length == 1 && /^#/.test(type))472return _data.dictionary[type];473type = Base.exports[type];474}475res = [];476for (var i = type ? 1 : 0, l = json.length; i < l; i++)477res.push(Base.deserialize(json[i], create, _data));478if (isDictionary) {479_data.dictionary = res[0];480} else if (type) {481var args = res;482if (create) {483res = create(type, args, isRoot);484} else {485res = Base.create(type.prototype);486type.apply(res, args);487}488}489} else if (Base.isPlainObject(json)) {490res = {};491for (var key in json)492res[key] = Base.deserialize(json[key], create, _data);493}494return res;495},496497exportJSON: function(obj, options) {498var json = Base.serialize(obj, options);499return options && options.asString === false500? json501: JSON.stringify(json);502},503504importJSON: function(json, target) {505return Base.deserialize(506typeof json === 'string' ? JSON.parse(json) : json,507function(type, args, isRoot) {508var obj = target && target.constructor === type509? target510: Base.create(type.prototype),511isTarget = obj === target;512if (!isRoot && args.length === 1 && obj instanceof Item513&& (!(obj instanceof Layer) || isTarget)) {514var arg = args[0];515if (Base.isPlainObject(arg))516arg.insert = false;517}518type.apply(obj, args);519if (isTarget)520target = null;521return obj;522});523},524525splice: function(list, items, index, remove) {526var amount = items && items.length,527append = index === undefined;528index = append ? list.length : index;529if (index > list.length)530index = list.length;531for (var i = 0; i < amount; i++)532items[i]._index = index + i;533if (append) {534list.push.apply(list, items);535return [];536} else {537var args = [index, remove];538if (items)539args.push.apply(args, items);540var removed = list.splice.apply(list, args);541for (var i = 0, l = removed.length; i < l; i++)542removed[i]._index = undefined;543for (var i = index + amount, l = list.length; i < l; i++)544list[i]._index = i;545return removed;546}547},548549capitalize: function(str) {550return str.replace(/\b[a-z]/g, function(match) {551return match.toUpperCase();552});553},554555camelize: function(str) {556return str.replace(/-(.)/g, function(all, chr) {557return chr.toUpperCase();558});559},560561hyphenate: function(str) {562return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();563}564}565});566567var Callback = {568attach: function(type, func) {569if (typeof type !== 'string') {570Base.each(type, function(value, key) {571this.attach(key, value);572}, this);573return;574}575var entry = this._eventTypes[type];576if (entry) {577var handlers = this._handlers = this._handlers || {};578handlers = handlers[type] = handlers[type] || [];579if (handlers.indexOf(func) == -1) {580handlers.push(func);581if (entry.install && handlers.length == 1)582entry.install.call(this, type);583}584}585},586587detach: function(type, func) {588if (typeof type !== 'string') {589Base.each(type, function(value, key) {590this.detach(key, value);591}, this);592return;593}594var entry = this._eventTypes[type],595handlers = this._handlers && this._handlers[type],596index;597if (entry && handlers) {598if (!func || (index = handlers.indexOf(func)) != -1599&& handlers.length == 1) {600if (entry.uninstall)601entry.uninstall.call(this, type);602delete this._handlers[type];603} else if (index != -1) {604handlers.splice(index, 1);605}606}607},608609once: function(type, func) {610this.attach(type, function() {611func.apply(this, arguments);612this.detach(type, func);613});614},615616fire: function(type, event) {617var handlers = this._handlers && this._handlers[type];618if (!handlers)619return false;620var args = [].slice.call(arguments, 1),621that = this;622for (var i = 0, l = handlers.length; i < l; i++) {623if (handlers[i].apply(that, args) === false624&& event && event.stop) {625event.stop();626break;627}628}629return true;630},631632responds: function(type) {633return !!(this._handlers && this._handlers[type]);634},635636on: '#attach',637off: '#detach',638trigger: '#fire',639640_installEvents: function(install) {641var handlers = this._handlers,642key = install ? 'install' : 'uninstall';643for (var type in handlers) {644if (handlers[type].length > 0) {645var entry = this._eventTypes[type],646func = entry[key];647if (func)648func.call(this, type);649}650}651},652653statics: {654inject: function inject() {655for (var i = 0, l = arguments.length; i < l; i++) {656var src = arguments[i],657events = src._events;658if (events) {659var types = {};660Base.each(events, function(entry, key) {661var isString = typeof entry === 'string',662name = isString ? entry : key,663part = Base.capitalize(name),664type = name.substring(2).toLowerCase();665types[type] = isString ? {} : entry;666name = '_' + name;667src['get' + part] = function() {668return this[name];669};670src['set' + part] = function(func) {671var prev = this[name];672if (prev)673this.detach(type, prev);674if (func)675this.attach(type, func);676this[name] = func;677};678});679src._eventTypes = types;680}681inject.base.call(this, src);682}683return this;684}685}686};687688var PaperScope = Base.extend({689_class: 'PaperScope',690691initialize: function PaperScope(script) {692paper = this;693this.settings = {694applyMatrix: true,695handleSize: 4,696hitTolerance: 0697};698this.project = null;699this.projects = [];700this.tools = [];701this.palettes = [];702this._id = script && (script.getAttribute('id') || script.src)703|| ('paperscope-' + (PaperScope._id++));704if (script)705script.setAttribute('id', this._id);706PaperScope._scopes[this._id] = this;707if (!this.support) {708var ctx = CanvasProvider.getContext(1, 1);709PaperScope.prototype.support = {710nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx,711nativeBlendModes: BlendMode.nativeModes712};713CanvasProvider.release(ctx);714}715},716717version: '0.9.18',718719getView: function() {720return this.project && this.project.getView();721},722723getPaper: function() {724return this;725},726727execute: function(code) {728paper.PaperScript.execute(code, this);729View.updateFocus();730},731732install: function(scope) {733var that = this;734Base.each(['project', 'view', 'tool'], function(key) {735Base.define(scope, key, {736configurable: true,737get: function() {738return that[key];739}740});741});742for (var key in this)743if (!/^_/.test(key) && this[key])744scope[key] = this[key];745},746747setup: function(canvas) {748paper = this;749this.project = new Project(canvas);750return this;751},752753activate: function() {754paper = this;755},756757clear: function() {758for (var i = this.projects.length - 1; i >= 0; i--)759this.projects[i].remove();760for (var i = this.tools.length - 1; i >= 0; i--)761this.tools[i].remove();762for (var i = this.palettes.length - 1; i >= 0; i--)763this.palettes[i].remove();764},765766remove: function() {767this.clear();768delete PaperScope._scopes[this._id];769},770771statics: new function() {772function handleAttribute(name) {773name += 'Attribute';774return function(el, attr) {775return el[name](attr) || el[name]('data-paper-' + attr);776};777}778779return {780_scopes: {},781_id: 0,782783get: function(id) {784if (id && id.getAttribute)785id = id.getAttribute('id');786return this._scopes[id] || null;787},788789getAttribute: handleAttribute('get'),790hasAttribute: handleAttribute('has')791};792}793});794795var PaperScopeItem = Base.extend(Callback, {796797initialize: function(activate) {798this._scope = paper;799this._index = this._scope[this._list].push(this) - 1;800if (activate || !this._scope[this._reference])801this.activate();802},803804activate: function() {805if (!this._scope)806return false;807var prev = this._scope[this._reference];808if (prev && prev !== this)809prev.fire('deactivate');810this._scope[this._reference] = this;811this.fire('activate', prev);812return true;813},814815isActive: function() {816return this._scope[this._reference] === this;817},818819remove: function() {820if (this._index == null)821return false;822Base.splice(this._scope[this._list], null, this._index, 1);823if (this._scope[this._reference] == this)824this._scope[this._reference] = null;825this._scope = null;826return true;827}828});829830var Formatter = Base.extend({831initialize: function(precision) {832this.precision = precision || 5;833this.multiplier = Math.pow(10, this.precision);834},835836number: function(val) {837return Math.round(val * this.multiplier) / this.multiplier;838},839840point: function(val, separator) {841return this.number(val.x) + (separator || ',') + this.number(val.y);842},843844size: function(val, separator) {845return this.number(val.width) + (separator || ',')846+ this.number(val.height);847},848849rectangle: function(val, separator) {850return this.point(val, separator) + (separator || ',')851+ this.size(val, separator);852}853});854855Formatter.instance = new Formatter();856857var Numerical = new function() {858859var abscissas = [860[ 0.5773502691896257645091488],861[0,0.7745966692414833770358531],862[ 0.3399810435848562648026658,0.8611363115940525752239465],863[0,0.5384693101056830910363144,0.9061798459386639927976269],864[ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],865[0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],866[ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],867[0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],868[ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],869[0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],870[ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],871[0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],872[ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],873[0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],874[ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]875];876877var weights = [878[1],879[0.8888888888888888888888889,0.5555555555555555555555556],880[0.6521451548625461426269361,0.3478548451374538573730639],881[0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],882[0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],883[0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],884[0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],885[0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],886[0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],887[0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],888[0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],889[0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],890[0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],891[0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],892[0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]893];894895var abs = Math.abs,896sqrt = Math.sqrt,897pow = Math.pow,898cos = Math.cos,899PI = Math.PI,900TOLERANCE = 10e-6,901EPSILON = 10e-12;902903function setupRoots(roots, min, max) {904var unbound = min === undefined,905minE = min - EPSILON,906maxE = max + EPSILON,907count = 0;908return function(root) {909if (unbound || root > minE && root < maxE)910roots[count++] = root < min ? min : root > max ? max : root;911return count;912};913}914915return {916TOLERANCE: TOLERANCE,917EPSILON: EPSILON,918KAPPA: 4 * (sqrt(2) - 1) / 3,919920isZero: function(val) {921return abs(val) <= EPSILON;922},923924integrate: function(f, a, b, n) {925var x = abscissas[n - 2],926w = weights[n - 2],927A = 0.5 * (b - a),928B = A + a,929i = 0,930m = (n + 1) >> 1,931sum = n & 1 ? w[i++] * f(B) : 0;932while (i < m) {933var Ax = A * x[i];934sum += w[i++] * (f(B + Ax) + f(B - Ax));935}936return A * sum;937},938939findRoot: function(f, df, x, a, b, n, tolerance) {940for (var i = 0; i < n; i++) {941var fx = f(x),942dx = fx / df(x),943nx = x - dx;944if (abs(dx) < tolerance)945return nx;946if (fx > 0) {947b = x;948x = nx <= a ? 0.5 * (a + b) : nx;949} else {950a = x;951x = nx >= b ? 0.5 * (a + b) : nx;952}953}954return x;955},956957solveQuadratic: function(a, b, c, roots, min, max) {958var add = setupRoots(roots, min, max);959960if (abs(a) < EPSILON) {961if (abs(b) >= EPSILON)962return add(-c / b);963return abs(c) < EPSILON ? -1 : 0;964}965var p = b / (2 * a);966var q = c / a;967var p2 = p * p;968if (p2 < q - EPSILON)969return 0;970var s = p2 > q ? sqrt(p2 - q) : 0,971count = add(s - p);972if (s > 0)973count = add(-s - p);974return count;975},976977solveCubic: function(a, b, c, d, roots, min, max) {978if (abs(a) < EPSILON)979return Numerical.solveQuadratic(b, c, d, roots, min, max);980981b /= a;982c /= a;983d /= a;984var add = setupRoots(roots, min, max),985bb = b * b,986p = (bb - 3 * c) / 9,987q = (2 * bb * b - 9 * b * c + 27 * d) / 54,988ppp = p * p * p,989D = q * q - ppp;990b /= 3;991if (abs(D) < EPSILON) {992if (abs(q) < EPSILON)993return add(-b);994var sqp = sqrt(p),995snq = q > 0 ? 1 : -1;996add(-snq * 2 * sqp - b);997return add(snq * sqp - b);998}999if (D < 0) {1000var sqp = sqrt(p),1001phi = Math.acos(q / (sqp * sqp * sqp)) / 3,1002t = -2 * sqp,1003o = 2 * PI / 3;1004add(t * cos(phi) - b);1005add(t * cos(phi + o) - b);1006return add(t * cos(phi - o) - b);1007}1008var A = (q > 0 ? -1 : 1) * pow(abs(q) + sqrt(D), 1 / 3);1009return add(A + p / A - b);1010}1011};1012};10131014var Point = Base.extend({1015_class: 'Point',1016_readIndex: true,10171018initialize: function Point(arg0, arg1) {1019var type = typeof arg0;1020if (type === 'number') {1021var hasY = typeof arg1 === 'number';1022this.x = arg0;1023this.y = hasY ? arg1 : arg0;1024if (this.__read)1025this.__read = hasY ? 2 : 1;1026} else if (type === 'undefined' || arg0 === null) {1027this.x = this.y = 0;1028if (this.__read)1029this.__read = arg0 === null ? 1 : 0;1030} else {1031if (Array.isArray(arg0)) {1032this.x = arg0[0];1033this.y = arg0.length > 1 ? arg0[1] : arg0[0];1034} else if (arg0.x != null) {1035this.x = arg0.x;1036this.y = arg0.y;1037} else if (arg0.width != null) {1038this.x = arg0.width;1039this.y = arg0.height;1040} else if (arg0.angle != null) {1041this.x = arg0.length;1042this.y = 0;1043this.setAngle(arg0.angle);1044} else {1045this.x = this.y = 0;1046if (this.__read)1047this.__read = 0;1048}1049if (this.__read)1050this.__read = 1;1051}1052},10531054set: function(x, y) {1055this.x = x;1056this.y = y;1057return this;1058},10591060equals: function(point) {1061return this === point || point1062&& (this.x === point.x && this.y === point.y1063|| Array.isArray(point)1064&& this.x === point[0] && this.y === point[1])1065|| false;1066},10671068clone: function() {1069return new Point(this.x, this.y);1070},10711072toString: function() {1073var f = Formatter.instance;1074return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';1075},10761077_serialize: function(options) {1078var f = options.formatter;1079return [f.number(this.x), f.number(this.y)];1080},10811082getLength: function() {1083return Math.sqrt(this.x * this.x + this.y * this.y);1084},10851086setLength: function(length) {1087if (this.isZero()) {1088var angle = this._angle || 0;1089this.set(1090Math.cos(angle) * length,1091Math.sin(angle) * length1092);1093} else {1094var scale = length / this.getLength();1095if (Numerical.isZero(scale))1096this.getAngle();1097this.set(1098this.x * scale,1099this.y * scale1100);1101}1102},1103getAngle: function() {1104return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI;1105},11061107setAngle: function(angle) {1108this.setAngleInRadians.call(this, angle * Math.PI / 180);1109},11101111getAngleInDegrees: '#getAngle',1112setAngleInDegrees: '#setAngle',11131114getAngleInRadians: function() {1115if (!arguments.length) {1116return this.isZero()1117? this._angle || 01118: this._angle = Math.atan2(this.y, this.x);1119} else {1120var point = Point.read(arguments),1121div = this.getLength() * point.getLength();1122if (Numerical.isZero(div)) {1123return NaN;1124} else {1125return Math.acos(this.dot(point) / div);1126}1127}1128},11291130setAngleInRadians: function(angle) {1131this._angle = angle;1132if (!this.isZero()) {1133var length = this.getLength();1134this.set(1135Math.cos(angle) * length,1136Math.sin(angle) * length1137);1138}1139},11401141getQuadrant: function() {1142return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;1143}1144}, {1145beans: false,11461147getDirectedAngle: function() {1148var point = Point.read(arguments);1149return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;1150},11511152getDistance: function() {1153var point = Point.read(arguments),1154x = point.x - this.x,1155y = point.y - this.y,1156d = x * x + y * y,1157squared = Base.read(arguments);1158return squared ? d : Math.sqrt(d);1159},11601161normalize: function(length) {1162if (length === undefined)1163length = 1;1164var current = this.getLength(),1165scale = current !== 0 ? length / current : 0,1166point = new Point(this.x * scale, this.y * scale);1167if (scale >= 0)1168point._angle = this._angle;1169return point;1170},11711172rotate: function(angle, center) {1173if (angle === 0)1174return this.clone();1175angle = angle * Math.PI / 180;1176var point = center ? this.subtract(center) : this,1177s = Math.sin(angle),1178c = Math.cos(angle);1179point = new Point(1180point.x * c - point.y * s,1181point.x * s + point.y * c1182);1183return center ? point.add(center) : point;1184},11851186transform: function(matrix) {1187return matrix ? matrix._transformPoint(this) : this;1188},11891190add: function() {1191var point = Point.read(arguments);1192return new Point(this.x + point.x, this.y + point.y);1193},11941195subtract: function() {1196var point = Point.read(arguments);1197return new Point(this.x - point.x, this.y - point.y);1198},11991200multiply: function() {1201var point = Point.read(arguments);1202return new Point(this.x * point.x, this.y * point.y);1203},12041205divide: function() {1206var point = Point.read(arguments);1207return new Point(this.x / point.x, this.y / point.y);1208},12091210modulo: function() {1211var point = Point.read(arguments);1212return new Point(this.x % point.x, this.y % point.y);1213},12141215negate: function() {1216return new Point(-this.x, -this.y);1217},12181219isInside: function(rect) {1220return rect.contains(this);1221},12221223isClose: function(point, tolerance) {1224return this.getDistance(point) < tolerance;1225},12261227isColinear: function(point) {1228return Math.abs(this.cross(point)) < 0.00001;1229},12301231isOrthogonal: function(point) {1232return Math.abs(this.dot(point)) < 0.00001;1233},12341235isZero: function() {1236return Numerical.isZero(this.x) && Numerical.isZero(this.y);1237},12381239isNaN: function() {1240return isNaN(this.x) || isNaN(this.y);1241},12421243dot: function() {1244var point = Point.read(arguments);1245return this.x * point.x + this.y * point.y;1246},12471248cross: function() {1249var point = Point.read(arguments);1250return this.x * point.y - this.y * point.x;1251},12521253project: function() {1254var point = Point.read(arguments);1255if (point.isZero()) {1256return new Point(0, 0);1257} else {1258var scale = this.dot(point) / point.dot(point);1259return new Point(1260point.x * scale,1261point.y * scale1262);1263}1264},12651266statics: {1267min: function() {1268var point1 = Point.read(arguments),1269point2 = Point.read(arguments);1270return new Point(1271Math.min(point1.x, point2.x),1272Math.min(point1.y, point2.y)1273);1274},12751276max: function() {1277var point1 = Point.read(arguments),1278point2 = Point.read(arguments);1279return new Point(1280Math.max(point1.x, point2.x),1281Math.max(point1.y, point2.y)1282);1283},12841285random: function() {1286return new Point(Math.random(), Math.random());1287}1288}1289}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {1290var op = Math[name];1291this[name] = function() {1292return new Point(op(this.x), op(this.y));1293};1294}, {}));12951296var LinkedPoint = Point.extend({1297initialize: function Point(x, y, owner, setter) {1298this._x = x;1299this._y = y;1300this._owner = owner;1301this._setter = setter;1302},13031304set: function(x, y, _dontNotify) {1305this._x = x;1306this._y = y;1307if (!_dontNotify)1308this._owner[this._setter](this);1309return this;1310},13111312getX: function() {1313return this._x;1314},13151316setX: function(x) {1317this._x = x;1318this._owner[this._setter](this);1319},13201321getY: function() {1322return this._y;1323},13241325setY: function(y) {1326this._y = y;1327this._owner[this._setter](this);1328}1329});13301331var Size = Base.extend({1332_class: 'Size',1333_readIndex: true,13341335initialize: function Size(arg0, arg1) {1336var type = typeof arg0;1337if (type === 'number') {1338var hasHeight = typeof arg1 === 'number';1339this.width = arg0;1340this.height = hasHeight ? arg1 : arg0;1341if (this.__read)1342this.__read = hasHeight ? 2 : 1;1343} else if (type === 'undefined' || arg0 === null) {1344this.width = this.height = 0;1345if (this.__read)1346this.__read = arg0 === null ? 1 : 0;1347} else {1348if (Array.isArray(arg0)) {1349this.width = arg0[0];1350this.height = arg0.length > 1 ? arg0[1] : arg0[0];1351} else if (arg0.width != null) {1352this.width = arg0.width;1353this.height = arg0.height;1354} else if (arg0.x != null) {1355this.width = arg0.x;1356this.height = arg0.y;1357} else {1358this.width = this.height = 0;1359if (this.__read)1360this.__read = 0;1361}1362if (this.__read)1363this.__read = 1;1364}1365},13661367set: function(width, height) {1368this.width = width;1369this.height = height;1370return this;1371},13721373equals: function(size) {1374return size === this || size && (this.width === size.width1375&& this.height === size.height1376|| Array.isArray(size) && this.width === size[0]1377&& this.height === size[1]) || false;1378},13791380clone: function() {1381return new Size(this.width, this.height);1382},13831384toString: function() {1385var f = Formatter.instance;1386return '{ width: ' + f.number(this.width)1387+ ', height: ' + f.number(this.height) + ' }';1388},13891390_serialize: function(options) {1391var f = options.formatter;1392return [f.number(this.width),1393f.number(this.height)];1394},13951396add: function() {1397var size = Size.read(arguments);1398return new Size(this.width + size.width, this.height + size.height);1399},14001401subtract: function() {1402var size = Size.read(arguments);1403return new Size(this.width - size.width, this.height - size.height);1404},14051406multiply: function() {1407var size = Size.read(arguments);1408return new Size(this.width * size.width, this.height * size.height);1409},14101411divide: function() {1412var size = Size.read(arguments);1413return new Size(this.width / size.width, this.height / size.height);1414},14151416modulo: function() {1417var size = Size.read(arguments);1418return new Size(this.width % size.width, this.height % size.height);1419},14201421negate: function() {1422return new Size(-this.width, -this.height);1423},14241425isZero: function() {1426return Numerical.isZero(this.width) && Numerical.isZero(this.height);1427},14281429isNaN: function() {1430return isNaN(this.width) || isNaN(this.height);1431},14321433statics: {1434min: function(size1, size2) {1435return new Size(1436Math.min(size1.width, size2.width),1437Math.min(size1.height, size2.height));1438},14391440max: function(size1, size2) {1441return new Size(1442Math.max(size1.width, size2.width),1443Math.max(size1.height, size2.height));1444},14451446random: function() {1447return new Size(Math.random(), Math.random());1448}1449}1450}, Base.each(['round', 'ceil', 'floor', 'abs'], function(name) {1451var op = Math[name];1452this[name] = function() {1453return new Size(op(this.width), op(this.height));1454};1455}, {}));14561457var LinkedSize = Size.extend({1458initialize: function Size(width, height, owner, setter) {1459this._width = width;1460this._height = height;1461this._owner = owner;1462this._setter = setter;1463},14641465set: function(width, height, _dontNotify) {1466this._width = width;1467this._height = height;1468if (!_dontNotify)1469this._owner[this._setter](this);1470return this;1471},14721473getWidth: function() {1474return this._width;1475},14761477setWidth: function(width) {1478this._width = width;1479this._owner[this._setter](this);1480},14811482getHeight: function() {1483return this._height;1484},14851486setHeight: function(height) {1487this._height = height;1488this._owner[this._setter](this);1489}1490});14911492var Rectangle = Base.extend({1493_class: 'Rectangle',1494_readIndex: true,1495beans: true,14961497initialize: function Rectangle(arg0, arg1, arg2, arg3) {1498var type = typeof arg0,1499read = 0;1500if (type === 'number') {1501this.x = arg0;1502this.y = arg1;1503this.width = arg2;1504this.height = arg3;1505read = 4;1506} else if (type === 'undefined' || arg0 === null) {1507this.x = this.y = this.width = this.height = 0;1508read = arg0 === null ? 1 : 0;1509} else if (arguments.length === 1) {1510if (Array.isArray(arg0)) {1511this.x = arg0[0];1512this.y = arg0[1];1513this.width = arg0[2];1514this.height = arg0[3];1515read = 1;1516} else if (arg0.x !== undefined || arg0.width !== undefined) {1517this.x = arg0.x || 0;1518this.y = arg0.y || 0;1519this.width = arg0.width || 0;1520this.height = arg0.height || 0;1521read = 1;1522} else if (arg0.from === undefined && arg0.to === undefined) {1523this.x = this.y = this.width = this.height = 0;1524this._set(arg0);1525read = 1;1526}1527}1528if (!read) {1529var point = Point.readNamed(arguments, 'from'),1530next = Base.peek(arguments);1531this.x = point.x;1532this.y = point.y;1533if (next && next.x !== undefined || Base.hasNamed(arguments, 'to')) {1534var to = Point.readNamed(arguments, 'to');1535this.width = to.x - point.x;1536this.height = to.y - point.y;1537if (this.width < 0) {1538this.x = to.x;1539this.width = -this.width;1540}1541if (this.height < 0) {1542this.y = to.y;1543this.height = -this.height;1544}1545} else {1546var size = Size.read(arguments);1547this.width = size.width;1548this.height = size.height;1549}1550read = arguments.__index;1551}1552if (this.__read)1553this.__read = read;1554},15551556set: function(x, y, width, height) {1557this.x = x;1558this.y = y;1559this.width = width;1560this.height = height;1561return this;1562},15631564clone: function() {1565return new Rectangle(this.x, this.y, this.width, this.height);1566},15671568equals: function(rect) {1569var rt = Base.isPlainValue(rect)1570? Rectangle.read(arguments)1571: rect;1572return rt === this1573|| rt && this.x === rt.x && this.y === rt.y1574&& this.width === rt.width && this.height === rt.height1575|| false;1576},15771578toString: function() {1579var f = Formatter.instance;1580return '{ x: ' + f.number(this.x)1581+ ', y: ' + f.number(this.y)1582+ ', width: ' + f.number(this.width)1583+ ', height: ' + f.number(this.height)1584+ ' }';1585},15861587_serialize: function(options) {1588var f = options.formatter;1589return [f.number(this.x),1590f.number(this.y),1591f.number(this.width),1592f.number(this.height)];1593},15941595getPoint: function(_dontLink) {1596var ctor = _dontLink ? Point : LinkedPoint;1597return new ctor(this.x, this.y, this, 'setPoint');1598},15991600setPoint: function() {1601var point = Point.read(arguments);1602this.x = point.x;1603this.y = point.y;1604},16051606getSize: function(_dontLink) {1607var ctor = _dontLink ? Size : LinkedSize;1608return new ctor(this.width, this.height, this, 'setSize');1609},16101611setSize: function() {1612var size = Size.read(arguments);1613if (this._fixX)1614this.x += (this.width - size.width) * this._fixX;1615if (this._fixY)1616this.y += (this.height - size.height) * this._fixY;1617this.width = size.width;1618this.height = size.height;1619this._fixW = 1;1620this._fixH = 1;1621},16221623getLeft: function() {1624return this.x;1625},16261627setLeft: function(left) {1628if (!this._fixW)1629this.width -= left - this.x;1630this.x = left;1631this._fixX = 0;1632},16331634getTop: function() {1635return this.y;1636},16371638setTop: function(top) {1639if (!this._fixH)1640this.height -= top - this.y;1641this.y = top;1642this._fixY = 0;1643},16441645getRight: function() {1646return this.x + this.width;1647},16481649setRight: function(right) {1650if (this._fixX !== undefined && this._fixX !== 1)1651this._fixW = 0;1652if (this._fixW)1653this.x = right - this.width;1654else1655this.width = right - this.x;1656this._fixX = 1;1657},16581659getBottom: function() {1660return this.y + this.height;1661},16621663setBottom: function(bottom) {1664if (this._fixY !== undefined && this._fixY !== 1)1665this._fixH = 0;1666if (this._fixH)1667this.y = bottom - this.height;1668else1669this.height = bottom - this.y;1670this._fixY = 1;1671},16721673getCenterX: function() {1674return this.x + this.width * 0.5;1675},16761677setCenterX: function(x) {1678this.x = x - this.width * 0.5;1679this._fixX = 0.5;1680},16811682getCenterY: function() {1683return this.y + this.height * 0.5;1684},16851686setCenterY: function(y) {1687this.y = y - this.height * 0.5;1688this._fixY = 0.5;1689},16901691getCenter: function(_dontLink) {1692var ctor = _dontLink ? Point : LinkedPoint;1693return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter');1694},16951696setCenter: function() {1697var point = Point.read(arguments);1698this.setCenterX(point.x);1699this.setCenterY(point.y);1700return this;1701},17021703getArea: function() {1704return this.width * this.height;1705},17061707isEmpty: function() {1708return this.width === 0 || this.height === 0;1709},17101711contains: function(arg) {1712return arg && arg.width !== undefined1713|| (Array.isArray(arg) ? arg : arguments).length == 41714? this._containsRectangle(Rectangle.read(arguments))1715: this._containsPoint(Point.read(arguments));1716},17171718_containsPoint: function(point) {1719var x = point.x,1720y = point.y;1721return x >= this.x && y >= this.y1722&& x <= this.x + this.width1723&& y <= this.y + this.height;1724},17251726_containsRectangle: function(rect) {1727var x = rect.x,1728y = rect.y;1729return x >= this.x && y >= this.y1730&& x + rect.width <= this.x + this.width1731&& y + rect.height <= this.y + this.height;1732},17331734intersects: function() {1735var rect = Rectangle.read(arguments);1736return rect.x + rect.width > this.x1737&& rect.y + rect.height > this.y1738&& rect.x < this.x + this.width1739&& rect.y < this.y + this.height;1740},17411742touches: function() {1743var rect = Rectangle.read(arguments);1744return rect.x + rect.width >= this.x1745&& rect.y + rect.height >= this.y1746&& rect.x <= this.x + this.width1747&& rect.y <= this.y + this.height;1748},17491750intersect: function() {1751var rect = Rectangle.read(arguments),1752x1 = Math.max(this.x, rect.x),1753y1 = Math.max(this.y, rect.y),1754x2 = Math.min(this.x + this.width, rect.x + rect.width),1755y2 = Math.min(this.y + this.height, rect.y + rect.height);1756return new Rectangle(x1, y1, x2 - x1, y2 - y1);1757},17581759unite: function() {1760var rect = Rectangle.read(arguments),1761x1 = Math.min(this.x, rect.x),1762y1 = Math.min(this.y, rect.y),1763x2 = Math.max(this.x + this.width, rect.x + rect.width),1764y2 = Math.max(this.y + this.height, rect.y + rect.height);1765return new Rectangle(x1, y1, x2 - x1, y2 - y1);1766},17671768include: function() {1769var point = Point.read(arguments);1770var x1 = Math.min(this.x, point.x),1771y1 = Math.min(this.y, point.y),1772x2 = Math.max(this.x + this.width, point.x),1773y2 = Math.max(this.y + this.height, point.y);1774return new Rectangle(x1, y1, x2 - x1, y2 - y1);1775},17761777expand: function() {1778var amount = Size.read(arguments),1779hor = amount.width,1780ver = amount.height;1781return new Rectangle(this.x - hor / 2, this.y - ver / 2,1782this.width + hor, this.height + ver);1783},17841785scale: function(hor, ver) {1786return this.expand(this.width * hor - this.width,1787this.height * (ver === undefined ? hor : ver) - this.height);1788}1789}, new function() {1790return Base.each([1791['Top', 'Left'], ['Top', 'Right'],1792['Bottom', 'Left'], ['Bottom', 'Right'],1793['Left', 'Center'], ['Top', 'Center'],1794['Right', 'Center'], ['Bottom', 'Center']1795],1796function(parts, index) {1797var part = parts.join('');1798var xFirst = /^[RL]/.test(part);1799if (index >= 4)1800parts[1] += xFirst ? 'Y' : 'X';1801var x = parts[xFirst ? 0 : 1],1802y = parts[xFirst ? 1 : 0],1803getX = 'get' + x,1804getY = 'get' + y,1805setX = 'set' + x,1806setY = 'set' + y,1807get = 'get' + part,1808set = 'set' + part;1809this[get] = function(_dontLink) {1810var ctor = _dontLink ? Point : LinkedPoint;1811return new ctor(this[getX](), this[getY](), this, set);1812};1813this[set] = function() {1814var point = Point.read(arguments);1815this[setX](point.x);1816this[setY](point.y);1817};1818}, {1819beans: true1820});1821});18221823var LinkedRectangle = Rectangle.extend({1824initialize: function Rectangle(x, y, width, height, owner, setter) {1825this.set(x, y, width, height, true);1826this._owner = owner;1827this._setter = setter;1828},18291830set: function(x, y, width, height, _dontNotify) {1831this._x = x;1832this._y = y;1833this._width = width;1834this._height = height;1835if (!_dontNotify)1836this._owner[this._setter](this);1837return this;1838}1839}, new function() {1840var proto = Rectangle.prototype;18411842return Base.each(['x', 'y', 'width', 'height'], function(key) {1843var part = Base.capitalize(key);1844var internal = '_' + key;1845this['get' + part] = function() {1846return this[internal];1847};18481849this['set' + part] = function(value) {1850this[internal] = value;1851if (!this._dontNotify)1852this._owner[this._setter](this);1853};1854}, Base.each(['Point', 'Size', 'Center',1855'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',1856'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',1857'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],1858function(key) {1859var name = 'set' + key;1860this[name] = function() {1861this._dontNotify = true;1862proto[name].apply(this, arguments);1863this._dontNotify = false;1864this._owner[this._setter](this);1865};1866}, {1867isSelected: function() {1868return this._owner._boundsSelected;1869},18701871setSelected: function(selected) {1872var owner = this._owner;1873if (owner.setSelected) {1874owner._boundsSelected = selected;1875owner.setSelected(selected || owner._selectedSegmentState > 0);1876}1877}1878})1879);1880});18811882var Matrix = Base.extend({1883_class: 'Matrix',18841885initialize: function Matrix(arg) {1886var count = arguments.length,1887ok = true;1888if (count === 6) {1889this.set.apply(this, arguments);1890} else if (count === 1) {1891if (arg instanceof Matrix) {1892this.set(arg._a, arg._c, arg._b, arg._d, arg._tx, arg._ty);1893} else if (Array.isArray(arg)) {1894this.set.apply(this, arg);1895} else {1896ok = false;1897}1898} else if (count === 0) {1899this.reset();1900} else {1901ok = false;1902}1903if (!ok)1904throw new Error('Unsupported matrix parameters');1905},19061907set: function(a, c, b, d, tx, ty, _dontNotify) {1908this._a = a;1909this._c = c;1910this._b = b;1911this._d = d;1912this._tx = tx;1913this._ty = ty;1914if (!_dontNotify)1915this._changed();1916return this;1917},19181919_serialize: function(options) {1920return Base.serialize(this.getValues(), options);1921},19221923_changed: function() {1924var owner = this._owner;1925if (owner) {1926if (owner._applyMatrix) {1927owner.transform(null, true);1928} else {1929owner._changed(9);1930}1931}1932},19331934clone: function() {1935return new Matrix(this._a, this._c, this._b, this._d,1936this._tx, this._ty);1937},19381939equals: function(mx) {1940return mx === this || mx && this._a === mx._a && this._b === mx._b1941&& this._c === mx._c && this._d === mx._d1942&& this._tx === mx._tx && this._ty === mx._ty1943|| false;1944},19451946toString: function() {1947var f = Formatter.instance;1948return '[[' + [f.number(this._a), f.number(this._b),1949f.number(this._tx)].join(', ') + '], ['1950+ [f.number(this._c), f.number(this._d),1951f.number(this._ty)].join(', ') + ']]';1952},19531954reset: function(_dontNotify) {1955this._a = this._d = 1;1956this._c = this._b = this._tx = this._ty = 0;1957if (!_dontNotify)1958this._changed();1959return this;1960},19611962apply: function() {1963var owner = this._owner;1964if (owner) {1965owner.transform(null, true);1966return this.isIdentity();1967}1968return false;1969},19701971translate: function() {1972var point = Point.read(arguments),1973x = point.x,1974y = point.y;1975this._tx += x * this._a + y * this._b;1976this._ty += x * this._c + y * this._d;1977this._changed();1978return this;1979},19801981scale: function() {1982var scale = Point.read(arguments),1983center = Point.read(arguments, 0, { readNull: true });1984if (center)1985this.translate(center);1986this._a *= scale.x;1987this._c *= scale.x;1988this._b *= scale.y;1989this._d *= scale.y;1990if (center)1991this.translate(center.negate());1992this._changed();1993return this;1994},19951996rotate: function(angle ) {1997angle *= Math.PI / 180;1998var center = Point.read(arguments, 1),1999x = center.x,2000y = center.y,2001cos = Math.cos(angle),2002sin = Math.sin(angle),2003tx = x - x * cos + y * sin,2004ty = y - x * sin - y * cos,2005a = this._a,2006b = this._b,2007c = this._c,2008d = this._d;2009this._a = cos * a + sin * b;2010this._b = -sin * a + cos * b;2011this._c = cos * c + sin * d;2012this._d = -sin * c + cos * d;2013this._tx += tx * a + ty * b;2014this._ty += tx * c + ty * d;2015this._changed();2016return this;2017},20182019shear: function() {2020var shear = Point.read(arguments),2021center = Point.read(arguments, 0, { readNull: true });2022if (center)2023this.translate(center);2024var a = this._a,2025c = this._c;2026this._a += shear.y * this._b;2027this._c += shear.y * this._d;2028this._b += shear.x * a;2029this._d += shear.x * c;2030if (center)2031this.translate(center.negate());2032this._changed();2033return this;2034},20352036skew: function() {2037var skew = Point.read(arguments),2038center = Point.read(arguments, 0, { readNull: true }),2039toRadians = Math.PI / 180,2040shear = new Point(Math.tan(skew.x * toRadians),2041Math.tan(skew.y * toRadians));2042return this.shear(shear, center);2043},20442045concatenate: function(mx) {2046var a = this._a,2047b = this._b,2048c = this._c,2049d = this._d;2050this._a = mx._a * a + mx._c * b;2051this._b = mx._b * a + mx._d * b;2052this._c = mx._a * c + mx._c * d;2053this._d = mx._b * c + mx._d * d;2054this._tx += mx._tx * a + mx._ty * b;2055this._ty += mx._tx * c + mx._ty * d;2056this._changed();2057return this;2058},20592060preConcatenate: function(mx) {2061var a = this._a,2062b = this._b,2063c = this._c,2064d = this._d,2065tx = this._tx,2066ty = this._ty;2067this._a = mx._a * a + mx._b * c;2068this._b = mx._a * b + mx._b * d;2069this._c = mx._c * a + mx._d * c;2070this._d = mx._c * b + mx._d * d;2071this._tx = mx._a * tx + mx._b * ty + mx._tx;2072this._ty = mx._c * tx + mx._d * ty + mx._ty;2073this._changed();2074return this;2075},20762077isIdentity: function() {2078return this._a === 1 && this._c === 0 && this._b === 0 && this._d === 12079&& this._tx === 0 && this._ty === 0;2080},20812082orNullIfIdentity: function() {2083return this.isIdentity() ? null : this;2084},20852086isInvertible: function() {2087return !!this._getDeterminant();2088},20892090isSingular: function() {2091return !this._getDeterminant();2092},20932094transform: function( src, srcOffset, dst, dstOffset, count) {2095return arguments.length < 52096? this._transformPoint(Point.read(arguments))2097: this._transformCoordinates(src, srcOffset, dst, dstOffset, count);2098},20992100_transformPoint: function(point, dest, _dontNotify) {2101var x = point.x,2102y = point.y;2103if (!dest)2104dest = new Point();2105return dest.set(2106x * this._a + y * this._b + this._tx,2107x * this._c + y * this._d + this._ty,2108_dontNotify2109);2110},21112112_transformCoordinates: function(src, srcOffset, dst, dstOffset, count) {2113var i = srcOffset,2114j = dstOffset,2115max = i + 2 * count;2116while (i < max) {2117var x = src[i++],2118y = src[i++];2119dst[j++] = x * this._a + y * this._b + this._tx;2120dst[j++] = x * this._c + y * this._d + this._ty;2121}2122return dst;2123},21242125_transformCorners: function(rect) {2126var x1 = rect.x,2127y1 = rect.y,2128x2 = x1 + rect.width,2129y2 = y1 + rect.height,2130coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];2131return this._transformCoordinates(coords, 0, coords, 0, 4);2132},21332134_transformBounds: function(bounds, dest, _dontNotify) {2135var coords = this._transformCorners(bounds),2136min = coords.slice(0, 2),2137max = coords.slice();2138for (var i = 2; i < 8; i++) {2139var val = coords[i],2140j = i & 1;2141if (val < min[j])2142min[j] = val;2143else if (val > max[j])2144max[j] = val;2145}2146if (!dest)2147dest = new Rectangle();2148return dest.set(min[0], min[1], max[0] - min[0], max[1] - min[1],2149_dontNotify);2150},21512152inverseTransform: function() {2153return this._inverseTransform(Point.read(arguments));2154},21552156_getDeterminant: function() {2157var det = this._a * this._d - this._b * this._c;2158return isFinite(det) && !Numerical.isZero(det)2159&& isFinite(this._tx) && isFinite(this._ty)2160? det : null;2161},21622163_inverseTransform: function(point, dest, _dontNotify) {2164var det = this._getDeterminant();2165if (!det)2166return null;2167var x = point.x - this._tx,2168y = point.y - this._ty;2169if (!dest)2170dest = new Point();2171return dest.set(2172(x * this._d - y * this._b) / det,2173(y * this._a - x * this._c) / det,2174_dontNotify2175);2176},21772178decompose: function() {2179var a = this._a, b = this._b, c = this._c, d = this._d;2180if (Numerical.isZero(a * d - b * c))2181return null;21822183var scaleX = Math.sqrt(a * a + b * b);2184a /= scaleX;2185b /= scaleX;21862187var shear = a * c + b * d;2188c -= a * shear;2189d -= b * shear;21902191var scaleY = Math.sqrt(c * c + d * d);2192c /= scaleY;2193d /= scaleY;2194shear /= scaleY;21952196if (a * d < b * c) {2197a = -a;2198b = -b;2199shear = -shear;2200scaleX = -scaleX;2201}22022203return {2204scaling: new Point(scaleX, scaleY),2205rotation: -Math.atan2(b, a) * 180 / Math.PI,2206shearing: shear2207};2208},22092210getValues: function() {2211return [ this._a, this._c, this._b, this._d, this._tx, this._ty ];2212},22132214getTranslation: function() {2215return new Point(this._tx, this._ty);2216},22172218getScaling: function() {2219return (this.decompose() || {}).scaling;2220},22212222getRotation: function() {2223return (this.decompose() || {}).rotation;2224},22252226inverted: function() {2227var det = this._getDeterminant();2228return det && new Matrix(2229this._d / det,2230-this._c / det,2231-this._b / det,2232this._a / det,2233(this._b * this._ty - this._d * this._tx) / det,2234(this._c * this._tx - this._a * this._ty) / det);2235},22362237shiftless: function() {2238return new Matrix(this._a, this._c, this._b, this._d, 0, 0);2239},22402241applyToContext: function(ctx) {2242ctx.transform(this._a, this._c, this._b, this._d, this._tx, this._ty);2243}2244}, Base.each(['a', 'c', 'b', 'd', 'tx', 'ty'], function(name) {2245var part = Base.capitalize(name),2246prop = '_' + name;2247this['get' + part] = function() {2248return this[prop];2249};2250this['set' + part] = function(value) {2251this[prop] = value;2252this._changed();2253};2254}, {}));22552256var Line = Base.extend({2257_class: 'Line',22582259initialize: function Line(arg0, arg1, arg2, arg3, arg4) {2260var asVector = false;2261if (arguments.length >= 4) {2262this._px = arg0;2263this._py = arg1;2264this._vx = arg2;2265this._vy = arg3;2266asVector = arg4;2267} else {2268this._px = arg0.x;2269this._py = arg0.y;2270this._vx = arg1.x;2271this._vy = arg1.y;2272asVector = arg2;2273}2274if (!asVector) {2275this._vx -= this._px;2276this._vy -= this._py;2277}2278},22792280getPoint: function() {2281return new Point(this._px, this._py);2282},22832284getVector: function() {2285return new Point(this._vx, this._vy);2286},22872288getLength: function() {2289return this.getVector().getLength();2290},22912292intersect: function(line, isInfinite) {2293return Line.intersect(2294this._px, this._py, this._vx, this._vy,2295line._px, line._py, line._vx, line._vy,2296true, isInfinite);2297},22982299getSide: function(point) {2300return Line.getSide(2301this._px, this._py, this._vx, this._vy,2302point.x, point.y, true);2303},23042305getDistance: function(point) {2306return Math.abs(Line.getSignedDistance(2307this._px, this._py, this._vx, this._vy,2308point.x, point.y, true));2309},23102311statics: {2312intersect: function(apx, apy, avx, avy, bpx, bpy, bvx, bvy, asVector,2313isInfinite) {2314if (!asVector) {2315avx -= apx;2316avy -= apy;2317bvx -= bpx;2318bvy -= bpy;2319}2320var cross = bvy * avx - bvx * avy;2321if (!Numerical.isZero(cross)) {2322var dx = apx - bpx,2323dy = apy - bpy,2324ta = (bvx * dy - bvy * dx) / cross,2325tb = (avx * dy - avy * dx) / cross;2326if ((isInfinite || 0 <= ta && ta <= 1)2327&& (isInfinite || 0 <= tb && tb <= 1))2328return new Point(2329apx + ta * avx,2330apy + ta * avy);2331}2332},23332334getSide: function(px, py, vx, vy, x, y, asVector) {2335if (!asVector) {2336vx -= px;2337vy -= py;2338}2339var v2x = x - px,2340v2y = y - py,2341ccw = v2x * vy - v2y * vx;2342if (ccw === 0) {2343ccw = v2x * vx + v2y * vy;2344if (ccw > 0) {2345v2x -= vx;2346v2y -= vy;2347ccw = v2x * vx + v2y * vy;2348if (ccw < 0)2349ccw = 0;2350}2351}2352return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;2353},23542355getSignedDistance: function(px, py, vx, vy, x, y, asVector) {2356if (!asVector) {2357vx -= px;2358vy -= py;2359}2360var m = vy / vx,2361b = py - m * px;2362return (y - (m * x) - b) / Math.sqrt(m * m + 1);2363}2364}2365});23662367var Project = PaperScopeItem.extend({2368_class: 'Project',2369_list: 'projects',2370_reference: 'project',23712372initialize: function Project(element) {2373PaperScopeItem.call(this, true);2374this.layers = [];2375this.symbols = [];2376this._currentStyle = new Style(null, null, this);2377this.activeLayer = new Layer();2378this._view = View.create(this,2379element || CanvasProvider.getCanvas(1, 1));2380this._selectedItems = {};2381this._selectedItemCount = 0;2382this._updateVersion = 0;2383},23842385_serialize: function(options, dictionary) {2386return Base.serialize(this.layers, options, true, dictionary);2387},23882389clear: function() {2390for (var i = this.layers.length - 1; i >= 0; i--)2391this.layers[i].remove();2392this.symbols = [];2393},23942395isEmpty: function() {2396return this.layers.length <= 12397&& (!this.activeLayer || this.activeLayer.isEmpty());2398},23992400remove: function remove() {2401if (!remove.base.call(this))2402return false;2403if (this._view)2404this._view.remove();2405return true;2406},24072408getView: function() {2409return this._view;2410},24112412getCurrentStyle: function() {2413return this._currentStyle;2414},24152416setCurrentStyle: function(style) {2417this._currentStyle.initialize(style);2418},24192420getIndex: function() {2421return this._index;2422},24232424addChild: function(child) {2425if (child instanceof Layer) {2426Base.splice(this.layers, [child]);2427if (!this.activeLayer)2428this.activeLayer = child;2429} else if (child instanceof Item) {2430(this.activeLayer2431|| this.addChild(new Layer(Item.NO_INSERT))).addChild(child);2432} else {2433child = null;2434}2435return child;2436},24372438getSelectedItems: function() {2439var items = [];2440for (var id in this._selectedItems) {2441var item = this._selectedItems[id];2442if (item.isInserted())2443items.push(item);2444}2445return items;2446},24472448getOptions: function() {2449return this._scope.settings;2450},24512452_updateSelection: function(item) {2453var id = item._id,2454selectedItems = this._selectedItems;2455if (item._selected) {2456if (selectedItems[id] !== item) {2457this._selectedItemCount++;2458selectedItems[id] = item;2459}2460} else if (selectedItems[id] === item) {2461this._selectedItemCount--;2462delete selectedItems[id];2463}2464},24652466selectAll: function() {2467var layers = this.layers;2468for (var i = 0, l = layers.length; i < l; i++)2469layers[i].setFullySelected(true);2470},24712472deselectAll: function() {2473var selectedItems = this._selectedItems;2474for (var i in selectedItems)2475selectedItems[i].setFullySelected(false);2476},24772478hitTest: function() {2479var point = Point.read(arguments),2480options = HitResult.getOptions(Base.read(arguments));2481for (var i = this.layers.length - 1; i >= 0; i--) {2482var res = this.layers[i].hitTest(point, options);2483if (res) return res;2484}2485return null;2486},24872488getItems: function(match) {2489return Item._getItems(this.layers, match, true);2490},24912492getItem: function(match) {2493return Item._getItems(this.layers, match, false);2494},24952496importJSON: function(json) {2497this.activate();2498var layer = this.activeLayer;2499return Base.importJSON(json, layer && layer.isEmpty() && layer);2500},25012502draw: function(ctx, matrix, pixelRatio) {2503this._updateVersion++;2504ctx.save();2505matrix.applyToContext(ctx);2506var param = new Base({2507offset: new Point(0, 0),2508pixelRatio: pixelRatio,2509trackTransforms: true,2510transforms: [matrix]2511});2512for (var i = 0, l = this.layers.length; i < l; i++)2513this.layers[i].draw(ctx, param);2514ctx.restore();25152516if (this._selectedItemCount > 0) {2517ctx.save();2518ctx.strokeWidth = 1;2519for (var id in this._selectedItems) {2520var item = this._selectedItems[id],2521globalMatrix = item._globalMatrix,2522size = this._scope.settings.handleSize,2523half = size / 2;2524if (item._updateVersion === this._updateVersion2525&& (item._drawSelected || item._boundsSelected)2526&& globalMatrix) {2527var color = item.getSelectedColor()2528|| item.getLayer().getSelectedColor();2529ctx.strokeStyle = ctx.fillStyle = color2530? color.toCanvasStyle(ctx) : '#009dec';2531if (item._drawSelected)2532item._drawSelected(ctx, globalMatrix);2533if (item._boundsSelected) {2534var coords = globalMatrix._transformCorners(2535item.getInternalBounds());2536ctx.beginPath();2537for (var i = 0; i < 8; i++)2538ctx[i === 0 ? 'moveTo' : 'lineTo'](2539coords[i], coords[++i]);2540ctx.closePath();2541ctx.stroke();2542for (var i = 0; i < 8; i++)2543ctx.fillRect(coords[i] - half, coords[++i] - half,2544size, size);2545}2546}2547}2548ctx.restore();2549}2550}2551});25522553var Symbol = Base.extend({2554_class: 'Symbol',25552556initialize: function Symbol(item, dontCenter) {2557this._id = Symbol._id = (Symbol._id || 0) + 1;2558this.project = paper.project;2559this.project.symbols.push(this);2560if (item)2561this.setDefinition(item, dontCenter);2562},25632564_serialize: function(options, dictionary) {2565return dictionary.add(this, function() {2566return Base.serialize([this._class, this._definition],2567options, false, dictionary);2568});2569},25702571_changed: function(flags) {2572if (flags & 8) {2573Item._clearBoundsCache(this);2574}2575if (flags & 1) {2576this.project._needsUpdate = true;2577}2578},25792580getDefinition: function() {2581return this._definition;2582},25832584setDefinition: function(item, _dontCenter) {2585if (item._parentSymbol)2586item = item.clone();2587if (this._definition)2588this._definition._parentSymbol = null;2589this._definition = item;2590item.remove();2591item.setSelected(false);2592if (!_dontCenter)2593item.setPosition(new Point());2594item._parentSymbol = this;2595this._changed(9);2596},25972598place: function(position) {2599return new PlacedSymbol(this, position);2600},26012602clone: function() {2603return new Symbol(this._definition.clone(false));2604}2605});26062607var Item = Base.extend(Callback, {2608statics: {2609extend: function extend(src) {2610if (src._serializeFields)2611src._serializeFields = new Base(2612this.prototype._serializeFields, src._serializeFields);2613return extend.base.apply(this, arguments);2614},26152616NO_INSERT: { insert: false }2617},26182619_class: 'Item',2620_applyMatrix: true,2621_canApplyMatrix: true,2622_boundsSelected: false,2623_selectChildren: false,2624_serializeFields: {2625name: null,2626matrix: new Matrix(),2627pivot: null,2628locked: false,2629visible: true,2630blendMode: 'normal',2631opacity: 1,2632guide: false,2633selected: false,2634clipMask: false,2635applyMatrix: null,2636data: {}2637},26382639initialize: function Item() {2640},26412642_initialize: function(props, point) {2643var internal = props && props.internal === true,2644matrix = this._matrix = new Matrix(),2645project = paper.project;2646if (!internal)2647this._id = Item._id = (Item._id || 0) + 1;2648this._applyMatrix = this._canApplyMatrix && paper.settings.applyMatrix;2649if (point)2650matrix.translate(point);2651matrix._owner = this;2652this._style = new Style(project._currentStyle, this, project);2653if (!this._project) {2654if (internal || props && props.insert === false) {2655this._setProject(project);2656} else {2657(project.activeLayer || new Layer()).addChild(this);2658}2659}2660return props && props !== Item.NO_INSERT2661? this._set(props, { insert: true })2662: true;2663},26642665_events: new function() {26662667var mouseFlags = {2668mousedown: {2669mousedown: 1,2670mousedrag: 1,2671click: 1,2672doubleclick: 12673},2674mouseup: {2675mouseup: 1,2676mousedrag: 1,2677click: 1,2678doubleclick: 12679},2680mousemove: {2681mousedrag: 1,2682mousemove: 1,2683mouseenter: 1,2684mouseleave: 12685}2686};26872688var mouseEvent = {2689install: function(type) {2690var counters = this.getView()._eventCounters;2691if (counters) {2692for (var key in mouseFlags) {2693counters[key] = (counters[key] || 0)2694+ (mouseFlags[key][type] || 0);2695}2696}2697},2698uninstall: function(type) {2699var counters = this.getView()._eventCounters;2700if (counters) {2701for (var key in mouseFlags)2702counters[key] -= mouseFlags[key][type] || 0;2703}2704}2705};27062707return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',2708'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'],2709function(name) {2710this[name] = mouseEvent;2711}, {2712onFrame: {2713install: function() {2714this._animateItem(true);2715},2716uninstall: function() {2717this._animateItem(false);2718}2719},27202721onLoad: {}2722}2723);2724},27252726_animateItem: function(animate) {2727this.getView()._animateItem(this, animate);2728},27292730_serialize: function(options, dictionary) {2731var props = {},2732that = this;27332734function serialize(fields) {2735for (var key in fields) {2736var value = that[key];2737if (!Base.equals(value, key === 'leading'2738? fields.fontSize * 1.2 : fields[key])) {2739props[key] = Base.serialize(value, options,2740key !== 'data', dictionary);2741}2742}2743}27442745serialize(this._serializeFields);2746if (!(this instanceof Group))2747serialize(this._style._defaults);2748return [ this._class, props ];2749},27502751_changed: function(flags) {2752var symbol = this._parentSymbol,2753cacheParent = this._parent || symbol,2754project = this._project;2755if (flags & 8) {2756this._bounds = this._position = this._decomposed =2757this._globalMatrix = this._currentPath = undefined;2758}2759if (cacheParent && (flags2760& (8 | 32))) {2761Item._clearBoundsCache(cacheParent);2762}2763if (flags & 2) {2764Item._clearBoundsCache(this);2765}2766if (project) {2767if (flags & 1) {2768project._needsUpdate = true;2769}2770if (project._changes) {2771var entry = project._changesById[this._id];2772if (entry) {2773entry.flags |= flags;2774} else {2775entry = { item: this, flags: flags };2776project._changesById[this._id] = entry;2777project._changes.push(entry);2778}2779}2780}2781if (symbol)2782symbol._changed(flags);2783},27842785set: function(props) {2786if (props)2787this._set(props, { insert: true });2788return this;2789},27902791getId: function() {2792return this._id;2793},27942795getClassName: function() {2796return this._class;2797},27982799getName: function() {2800return this._name;2801},28022803setName: function(name, unique) {28042805if (this._name)2806this._removeNamed();2807if (name === (+name) + '')2808throw new Error(2809'Names consisting only of numbers are not supported.');2810if (name && this._parent) {2811var children = this._parent._children,2812namedChildren = this._parent._namedChildren,2813orig = name,2814i = 1;2815while (unique && children[name])2816name = orig + ' ' + (i++);2817(namedChildren[name] = namedChildren[name] || []).push(this);2818children[name] = this;2819}2820this._name = name || undefined;2821this._changed(128);2822},28232824getStyle: function() {2825return this._style;2826},28272828setStyle: function(style) {2829this.getStyle().set(style);2830},28312832hasFill: function() {2833return this.getStyle().hasFill();2834},28352836hasStroke: function() {2837return this.getStyle().hasStroke();2838},28392840hasShadow: function() {2841return this.getStyle().hasShadow();2842}2843}, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],2844function(name) {2845var part = Base.capitalize(name),2846name = '_' + name;2847this['get' + part] = function() {2848return this[name];2849};2850this['set' + part] = function(value) {2851if (value != this[name]) {2852this[name] = value;2853this._changed(name === '_locked'2854? 128 : 129);2855}2856};2857}, {}), {2858beans: true,28592860_locked: false,28612862_visible: true,28632864_blendMode: 'normal',28652866_opacity: 1,28672868_guide: false,28692870isSelected: function() {2871if (this._selectChildren) {2872for (var i = 0, l = this._children.length; i < l; i++)2873if (this._children[i].isSelected())2874return true;2875}2876return this._selected;2877},28782879setSelected: function(selected, noChildren) {2880if (!noChildren && this._selectChildren) {2881for (var i = 0, l = this._children.length; i < l; i++)2882this._children[i].setSelected(selected);2883}2884if ((selected = !!selected) ^ this._selected) {2885this._selected = selected;2886this._project._updateSelection(this);2887this._changed(129);2888}2889},28902891_selected: false,28922893isFullySelected: function() {2894if (this._children && this._selected) {2895for (var i = 0, l = this._children.length; i < l; i++)2896if (!this._children[i].isFullySelected())2897return false;2898return true;2899}2900return this._selected;2901},29022903setFullySelected: function(selected) {2904if (this._children) {2905for (var i = 0, l = this._children.length; i < l; i++)2906this._children[i].setFullySelected(selected);2907}2908this.setSelected(selected, true);2909},29102911isClipMask: function() {2912return this._clipMask;2913},29142915setClipMask: function(clipMask) {2916if (this._clipMask != (clipMask = !!clipMask)) {2917this._clipMask = clipMask;2918if (clipMask) {2919this.setFillColor(null);2920this.setStrokeColor(null);2921}2922this._changed(129);2923if (this._parent)2924this._parent._changed(1024);2925}2926},29272928_clipMask: false,29292930getData: function() {2931if (!this._data)2932this._data = {};2933return this._data;2934},29352936setData: function(data) {2937this._data = data;2938},29392940getPosition: function(_dontLink) {2941var position = this._position,2942ctor = _dontLink ? Point : LinkedPoint;2943if (!position) {2944var pivot = this._pivot;2945position = this._position = pivot2946? this._matrix._transformPoint(pivot)2947: this.getBounds().getCenter(true);2948}2949return new ctor(position.x, position.y, this, 'setPosition');2950},29512952setPosition: function() {2953this.translate(Point.read(arguments).subtract(this.getPosition(true)));2954},29552956getPivot: function(_dontLink) {2957var pivot = this._pivot;2958if (pivot) {2959var ctor = _dontLink ? Point : LinkedPoint;2960pivot = new ctor(pivot.x, pivot.y, this, 'setAnchor');2961}2962return pivot;2963},29642965setPivot: function() {2966this._pivot = Point.read(arguments);2967this._position = undefined;2968},29692970_pivot: null,29712972getRegistration: '#getPivot',2973setRegistration: '#setPivot'2974}, Base.each(['bounds', 'strokeBounds', 'handleBounds', 'roughBounds',2975'internalBounds', 'internalRoughBounds'],2976function(key) {2977var getter = 'get' + Base.capitalize(key),2978match = key.match(/^internal(.*)$/),2979internalGetter = match ? 'get' + match[1] : null;2980this[getter] = function(_matrix) {2981var boundsGetter = this._boundsGetter,2982name = !internalGetter && (typeof boundsGetter === 'string'2983? boundsGetter : boundsGetter && boundsGetter[getter])2984|| getter,2985bounds = this._getCachedBounds(name, _matrix, null,2986internalGetter);2987return key === 'bounds'2988? new LinkedRectangle(bounds.x, bounds.y, bounds.width,2989bounds.height, this, 'setBounds')2990: bounds;2991};2992},2993{2994beans: true,29952996_getBounds: function(getter, matrix, cacheItem) {2997var children = this._children;2998if (!children || children.length == 0)2999return new Rectangle();3000var x1 = Infinity,3001x2 = -x1,3002y1 = x1,3003y2 = x2;3004for (var i = 0, l = children.length; i < l; i++) {3005var child = children[i];3006if (child._visible && !child.isEmpty()) {3007var rect = child._getCachedBounds(getter, matrix, cacheItem);3008x1 = Math.min(rect.x, x1);3009y1 = Math.min(rect.y, y1);3010x2 = Math.max(rect.x + rect.width, x2);3011y2 = Math.max(rect.y + rect.height, y2);3012}3013}3014return isFinite(x1)3015? new Rectangle(x1, y1, x2 - x1, y2 - y1)3016: new Rectangle();3017},30183019setBounds: function() {3020var rect = Rectangle.read(arguments),3021bounds = this.getBounds(),3022matrix = new Matrix(),3023center = rect.getCenter();3024matrix.translate(center);3025if (rect.width != bounds.width || rect.height != bounds.height) {3026matrix.scale(3027bounds.width != 0 ? rect.width / bounds.width : 1,3028bounds.height != 0 ? rect.height / bounds.height : 1);3029}3030center = bounds.getCenter();3031matrix.translate(-center.x, -center.y);3032this.transform(matrix);3033},30343035_getCachedBounds: function(getter, matrix, cacheItem, internalGetter) {3036matrix = matrix && matrix.orNullIfIdentity();3037var _matrix = internalGetter ? null : this._matrix.orNullIfIdentity(),3038cache = (!matrix || matrix.equals(_matrix)) && getter;3039var cacheParent = this._parent || this._parentSymbol;3040if (cacheItem && cacheParent) {3041var id = cacheItem._id,3042ref = cacheParent._boundsCache = cacheParent._boundsCache || {3043ids: {},3044list: []3045};3046if (!ref.ids[id]) {3047ref.list.push(cacheItem);3048ref.ids[id] = cacheItem;3049}3050}3051if (cache && this._bounds && this._bounds[cache])3052return this._bounds[cache].clone();3053matrix = !matrix3054? _matrix3055: _matrix3056? matrix.clone().concatenate(_matrix)3057: matrix;3058var bounds = this._getBounds(internalGetter || getter, matrix,3059cache ? this : cacheItem);3060if (cache) {3061if (!this._bounds)3062this._bounds = {};3063var cached = this._bounds[cache] = bounds.clone();3064cached._internal = !!internalGetter;3065}3066return bounds;3067},30683069statics: {3070_clearBoundsCache: function(item) {3071if (item._boundsCache) {3072for (var i = 0, list = item._boundsCache.list, l = list.length;3073i < l; i++) {3074var child = list[i];3075child._bounds = child._position = undefined;3076if (child !== item && child._boundsCache)3077Item._clearBoundsCache(child);3078}3079item._boundsCache = undefined;3080}3081}3082}30833084}), {3085beans: true,30863087_decompose: function() {3088return this._decomposed = this._matrix.decompose();3089},30903091getRotation: function() {3092var decomposed = this._decomposed || this._decompose();3093return decomposed && decomposed.rotation;3094},30953096setRotation: function(rotation) {3097var current = this.getRotation();3098if (current != null && rotation != null) {3099var decomposed = this._decomposed;3100this.rotate(rotation - current);3101decomposed.rotation = rotation;3102this._decomposed = decomposed;3103}3104},31053106getScaling: function() {3107var decomposed = this._decomposed || this._decompose();3108return decomposed && decomposed.scaling;3109},31103111setScaling: function() {3112var current = this.getScaling();3113if (current != null) {3114var scaling = Point.read(arguments, 0, { clone: true }),3115decomposed = this._decomposed;3116this.scale(scaling.x / current.x, scaling.y / current.y);3117decomposed.scaling = scaling;3118this._decomposed = decomposed;3119}3120},31213122getMatrix: function() {3123return this._matrix;3124},31253126setMatrix: function(matrix) {3127this._matrix.initialize(matrix);3128if (this._applyMatrix) {3129this.transform(null, true);3130} else {3131this._changed(9);3132}3133},31343135getGlobalMatrix: function(_internal) {3136var matrix = this._globalMatrix,3137updateVersion = this._project._updateVersion,3138viewMatrix = this.getView()._matrix;3139if (matrix && matrix._updateVersion !== updateVersion)3140matrix = null;3141if (!matrix) {3142matrix = this._globalMatrix = this._matrix.clone();3143matrix.preConcatenate(this._parent3144? this._parent.getGlobalMatrix(true)3145: viewMatrix);3146matrix._updateVersion = updateVersion;3147}3148return _internal ? matrix : viewMatrix.inverted().concatenate(matrix);3149},31503151getApplyMatrix: function() {3152return this._applyMatrix;3153},31543155setApplyMatrix: function(transform) {3156if (this._applyMatrix = this._canApplyMatrix && !!transform)3157this.transform(null, true);3158},31593160getTransformContent: '#getApplyMatrix',3161setTransformContent: '#setApplyMatrix',3162}, {3163getProject: function() {3164return this._project;3165},31663167_setProject: function(project, installEvents) {3168if (this._project !== project) {3169if (this._project)3170this._installEvents(false);3171this._project = project;3172var children = this._children;3173for (var i = 0, l = children && children.length; i < l; i++)3174children[i]._setProject(project);3175installEvents = true;3176}3177if (installEvents)3178this._installEvents(true);3179},31803181getView: function() {3182return this._project.getView();3183},31843185_installEvents: function _installEvents(install) {3186_installEvents.base.call(this, install);3187var children = this._children;3188for (var i = 0, l = children && children.length; i < l; i++)3189children[i]._installEvents(install);3190},31913192getLayer: function() {3193var parent = this;3194while (parent = parent._parent) {3195if (parent instanceof Layer)3196return parent;3197}3198return null;3199},32003201getParent: function() {3202return this._parent;3203},32043205setParent: function(item) {3206return item.addChild(this);3207},32083209getChildren: function() {3210return this._children;3211},32123213setChildren: function(items) {3214this.removeChildren();3215this.addChildren(items);3216},32173218getFirstChild: function() {3219return this._children && this._children[0] || null;3220},32213222getLastChild: function() {3223return this._children && this._children[this._children.length - 1]3224|| null;3225},32263227getNextSibling: function() {3228return this._parent && this._parent._children[this._index + 1] || null;3229},32303231getPreviousSibling: function() {3232return this._parent && this._parent._children[this._index - 1] || null;3233},32343235getIndex: function() {3236return this._index;3237},32383239isInserted: function() {3240return this._parent ? this._parent.isInserted() : false;3241},32423243equals: function(item) {3244return item === this || item && this._class === item._class3245&& this._style.equals(item._style)3246&& this._matrix.equals(item._matrix)3247&& this._locked === item._locked3248&& this._visible === item._visible3249&& this._blendMode === item._blendMode3250&& this._opacity === item._opacity3251&& this._clipMask === item._clipMask3252&& this._guide === item._guide3253&& this._equals(item)3254|| false;3255},32563257_equals: function(item) {3258return Base.equals(this._children, item._children);3259},32603261clone: function(insert) {3262return this._clone(new this.constructor(Item.NO_INSERT), insert);3263},32643265_clone: function(copy, insert) {3266copy.setStyle(this._style);3267if (this._children) {3268for (var i = 0, l = this._children.length; i < l; i++)3269copy.addChild(this._children[i].clone(false), true);3270}3271if (insert || insert === undefined)3272copy.insertAbove(this);3273var keys = ['_locked', '_visible', '_blendMode', '_opacity',3274'_clipMask', '_guide', '_applyMatrix'];3275for (var i = 0, l = keys.length; i < l; i++) {3276var key = keys[i];3277if (this.hasOwnProperty(key))3278copy[key] = this[key];3279}3280copy._matrix.initialize(this._matrix);3281copy._data = this._data ? Base.clone(this._data) : null;3282copy.setSelected(this._selected);3283if (this._name)3284copy.setName(this._name, true);3285return copy;3286},32873288copyTo: function(itemOrProject) {3289return itemOrProject.addChild(this.clone(false));3290},32913292rasterize: function(resolution) {3293var bounds = this.getStrokeBounds(),3294scale = (resolution || this.getView().getResolution()) / 72,3295topLeft = bounds.getTopLeft().floor(),3296bottomRight = bounds.getBottomRight().ceil(),3297size = new Size(bottomRight.subtract(topLeft)),3298canvas = CanvasProvider.getCanvas(size.multiply(scale)),3299ctx = canvas.getContext('2d'),3300matrix = new Matrix().scale(scale).translate(topLeft.negate());3301ctx.save();3302matrix.applyToContext(ctx);3303this.draw(ctx, new Base({ transforms: [matrix] }));3304ctx.restore();3305var raster = new Raster(Item.NO_INSERT);3306raster.setCanvas(canvas);3307raster.transform(new Matrix().translate(topLeft.add(size.divide(2)))3308.scale(1 / scale));3309raster.insertAbove(this);3310return raster;3311},33123313contains: function() {3314return !!this._contains(3315this._matrix._inverseTransform(Point.read(arguments)));3316},33173318_contains: function(point) {3319if (this._children) {3320for (var i = this._children.length - 1; i >= 0; i--) {3321if (this._children[i].contains(point))3322return true;3323}3324return false;3325}3326return point.isInside(this.getInternalBounds());3327},33283329hitTest: function(point, options) {3330point = Point.read(arguments);3331options = HitResult.getOptions(Base.read(arguments));3332if (this._locked || !this._visible || this._guide && !options.guides3333|| this.isEmpty())3334return null;33353336var matrix = this._matrix,3337parentTotalMatrix = options._totalMatrix,3338view = this.getView(),3339totalMatrix = options._totalMatrix = parentTotalMatrix3340? parentTotalMatrix.clone().concatenate(matrix)3341: this.getGlobalMatrix().clone().preConcatenate(3342view._matrix),3343tolerancePadding = options._tolerancePadding = new Size(3344Path._getPenPadding(1, totalMatrix.inverted())3345).multiply(3346Math.max(options.tolerance, 0.00001)3347);3348point = matrix._inverseTransform(point);33493350if (!this._children && !this.getInternalRoughBounds()3351.expand(tolerancePadding.multiply(2))._containsPoint(point))3352return null;3353var type,3354checkSelf = !(options.guides && !this._guide3355|| options.selected && !this._selected3356|| (type = options.type) && (typeof type === 'string'3357? type !== Base.hyphenate(this._class)3358: !(this instanceof type))),3359that = this,3360res;33613362function checkBounds(type, part) {3363var pt = bounds['get' + part]();3364if (point.subtract(pt).divide(tolerancePadding).length <= 1)3365return new HitResult(type, that,3366{ name: Base.hyphenate(part), point: pt });3367}33683369if (checkSelf && (options.center || options.bounds) && this._parent) {3370var bounds = this.getInternalBounds();3371if (options.center)3372res = checkBounds('center', 'Center');3373if (!res && options.bounds) {3374var points = [3375'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',3376'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'3377];3378for (var i = 0; i < 8 && !res; i++)3379res = checkBounds('bounds', points[i]);3380}3381}33823383var children = !res && this._children;3384if (children) {3385var opts = this._getChildHitTestOptions(options);3386for (var i = children.length - 1; i >= 0 && !res; i--)3387res = children[i].hitTest(point, opts);3388}3389if (!res && checkSelf)3390res = this._hitTest(point, options);3391if (res && res.point)3392res.point = matrix.transform(res.point);3393options._totalMatrix = parentTotalMatrix;3394return res;3395},33963397_getChildHitTestOptions: function(options) {3398return options;3399},34003401_hitTest: function(point, options) {3402if (options.fill && this.hasFill() && this._contains(point))3403return new HitResult('fill', this);3404}3405}, {3406matches: function(match) {3407function matchObject(obj1, obj2) {3408for (var i in obj1) {3409if (obj1.hasOwnProperty(i)) {3410var val1 = obj1[i],3411val2 = obj2[i];3412if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {3413if (!matchObject(val1, val2))3414return false;3415} else if (!Base.equals(val1, val2)) {3416return false;3417}3418}3419}3420return true;3421}3422for (var key in match) {3423if (match.hasOwnProperty(key)) {3424var value = this[key],3425compare = match[key];3426if (value === undefined && key === 'type')3427value = Base.hyphenate(this._class);3428if (/^(constructor|class)$/.test(key)) {3429if (!(this instanceof compare))3430return false;3431} else if (compare instanceof RegExp) {3432if (!compare.test(value))3433return false;3434} else if (typeof compare === 'function') {3435if (!compare(value))3436return false;3437} else if (Base.isPlainObject(compare)) {3438if (!matchObject(compare, value))3439return false;3440} else if (!Base.equals(value, compare)) {3441return false;3442}3443}3444}3445return true;3446},34473448getItems: function(match) {3449return Item._getItems(this._children, match, true);3450},34513452getItem: function(match) {3453return Item._getItems(this._children, match, false);3454},34553456statics: {3457_getItems: function _getItems(children, match, list) {3458var items = list && [];3459for (var i = 0, l = children && children.length; i < l; i++) {3460var child = children[i];3461if (child.matches(match)) {3462if (list) {3463items.push(child);3464} else {3465return child;3466}3467}3468var res = _getItems(child._children, match, list);3469if (list) {3470items.push.apply(items, res);3471} else if (res) {3472return res;3473}3474}3475return list ? items : null;3476}3477}3478}, {34793480importJSON: function(json) {3481var res = Base.importJSON(json, this);3482return res !== this3483? this.addChild(res)3484: res;3485},34863487addChild: function(item, _preserve) {3488return this.insertChild(undefined, item, _preserve);3489},34903491insertChild: function(index, item, _preserve) {3492var res = this.insertChildren(index, [item], _preserve);3493return res && res[0];3494},34953496addChildren: function(items, _preserve) {3497return this.insertChildren(this._children.length, items, _preserve);3498},34993500insertChildren: function(index, items, _preserve, _proto) {3501var children = this._children;3502if (children && items && items.length > 0) {3503items = Array.prototype.slice.apply(items);3504for (var i = items.length - 1; i >= 0; i--) {3505var item = items[i];3506if (_proto && !(item instanceof _proto)) {3507items.splice(i, 1);3508} else {3509item._remove(false, true);3510}3511}3512Base.splice(children, items, index, 0);3513var project = this._project,3514notifySelf = project && project._changes;3515for (var i = 0, l = items.length; i < l; i++) {3516var item = items[i];3517item._parent = this;3518item._setProject(this._project, true);3519if (item._name)3520item.setName(item._name);3521if (notifySelf)3522this._changed(5);3523}3524this._changed(11);3525} else {3526items = null;3527}3528return items;3529},35303531_insert: function(above, item, _preserve) {3532if (!item._parent)3533return null;3534var index = item._index + (above ? 1 : 0);3535if (item._parent === this._parent && index > this._index)3536index--;3537return item._parent.insertChild(index, this, _preserve);3538},35393540insertAbove: function(item, _preserve) {3541return this._insert(true, item, _preserve);3542},35433544insertBelow: function(item, _preserve) {3545return this._insert(false, item, _preserve);3546},35473548sendToBack: function() {3549return this._parent.insertChild(0, this);3550},35513552bringToFront: function() {3553return this._parent.addChild(this);3554},35553556appendTop: '#addChild',35573558appendBottom: function(item) {3559return this.insertChild(0, item);3560},35613562moveAbove: '#insertAbove',35633564moveBelow: '#insertBelow',35653566reduce: function() {3567if (this._children && this._children.length === 1) {3568var child = this._children[0].reduce();3569child.insertAbove(this);3570child.setStyle(this._style);3571this.remove();3572return child;3573}3574return this;3575},35763577_removeNamed: function() {3578var children = this._parent._children,3579namedChildren = this._parent._namedChildren,3580name = this._name,3581namedArray = namedChildren[name],3582index = namedArray ? namedArray.indexOf(this) : -1;3583if (index == -1)3584return;3585if (children[name] == this)3586delete children[name];3587namedArray.splice(index, 1);3588if (namedArray.length) {3589children[name] = namedArray[namedArray.length - 1];3590} else {3591delete namedChildren[name];3592}3593},35943595_remove: function(notifySelf, notifyParent) {3596var parent = this._parent;3597if (parent) {3598if (this._name)3599this._removeNamed();3600if (this._index != null)3601Base.splice(parent._children, null, this._index, 1);3602this._installEvents(false);3603if (notifySelf) {3604var project = this._project;3605if (project && project._changes)3606this._changed(5);3607}3608if (notifyParent)3609parent._changed(11);3610this._parent = null;3611return true;3612}3613return false;3614},36153616remove: function() {3617return this._remove(true, true);3618},36193620removeChildren: function(from, to) {3621if (!this._children)3622return null;3623from = from || 0;3624to = Base.pick(to, this._children.length);3625var removed = Base.splice(this._children, null, from, to - from);3626for (var i = removed.length - 1; i >= 0; i--) {3627removed[i]._remove(true, false);3628}3629if (removed.length > 0)3630this._changed(11);3631return removed;3632},36333634clear: '#removeChildren',36353636reverseChildren: function() {3637if (this._children) {3638this._children.reverse();3639for (var i = 0, l = this._children.length; i < l; i++)3640this._children[i]._index = i;3641this._changed(11);3642}3643},36443645isEmpty: function() {3646return !this._children || this._children.length == 0;3647},36483649isEditable: function() {3650var item = this;3651while (item) {3652if (!item._visible || item._locked)3653return false;3654item = item._parent;3655}3656return true;3657},36583659_getOrder: function(item) {3660function getList(item) {3661var list = [];3662do {3663list.unshift(item);3664} while (item = item._parent);3665return list;3666}3667var list1 = getList(this),3668list2 = getList(item);3669for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {3670if (list1[i] != list2[i]) {3671return list1[i]._index < list2[i]._index ? 1 : -1;3672}3673}3674return 0;3675},36763677hasChildren: function() {3678return this._children && this._children.length > 0;3679},36803681isAbove: function(item) {3682return this._getOrder(item) === -1;3683},36843685isBelow: function(item) {3686return this._getOrder(item) === 1;3687},36883689isParent: function(item) {3690return this._parent === item;3691},36923693isChild: function(item) {3694return item && item._parent === this;3695},36963697isDescendant: function(item) {3698var parent = this;3699while (parent = parent._parent) {3700if (parent == item)3701return true;3702}3703return false;3704},37053706isAncestor: function(item) {3707return item ? item.isDescendant(this) : false;3708},37093710isGroupedWith: function(item) {3711var parent = this._parent;3712while (parent) {3713if (parent._parent3714&& /^(Group|Layer|CompoundPath)$/.test(parent._class)3715&& item.isDescendant(parent))3716return true;3717parent = parent._parent;3718}3719return false;3720},37213722translate: function() {3723var mx = new Matrix();3724return this.transform(mx.translate.apply(mx, arguments));3725},37263727rotate: function(angle ) {3728return this.transform(new Matrix().rotate(angle,3729Point.read(arguments, 1, { readNull: true })3730|| this.getPosition(true)));3731}3732}, Base.each(['scale', 'shear', 'skew'], function(name) {3733this[name] = function() {3734var point = Point.read(arguments),3735center = Point.read(arguments, 0, { readNull: true });3736return this.transform(new Matrix()[name](point,3737center || this.getPosition(true)));3738};3739}, {37403741}), {3742transform: function(matrix, _applyMatrix) {3743if (matrix && matrix.isIdentity())3744matrix = null;3745var _matrix = this._matrix,3746applyMatrix = (_applyMatrix || this._applyMatrix)3747&& (!_matrix.isIdentity() || matrix);3748if (!matrix && !applyMatrix)3749return this;3750if (matrix)3751_matrix.preConcatenate(matrix);3752if (applyMatrix = applyMatrix && this._transformContent(_matrix)) {3753var pivot = this._pivot,3754style = this._style,3755fillColor = style.getFillColor(true),3756strokeColor = style.getStrokeColor(true);3757if (pivot)3758pivot.transform(_matrix);3759if (fillColor)3760fillColor.transform(_matrix);3761if (strokeColor)3762strokeColor.transform(_matrix);3763_matrix.reset(true);3764}3765var bounds = this._bounds,3766position = this._position;3767this._changed(9);3768var decomp = bounds && matrix && matrix.decompose();3769if (decomp && !decomp.shearing && decomp.rotation % 90 === 0) {3770for (var key in bounds) {3771var rect = bounds[key];3772if (applyMatrix || !rect._internal)3773matrix._transformBounds(rect, rect);3774}3775var getter = this._boundsGetter,3776rect = bounds[getter && getter.getBounds || getter || 'getBounds'];3777if (rect)3778this._position = rect.getCenter(true);3779this._bounds = bounds;3780} else if (matrix && position) {3781this._position = matrix._transformPoint(position, position);3782}3783return this;3784},37853786_transformContent: function(matrix) {3787var children = this._children;3788if (children) {3789for (var i = 0, l = children.length; i < l; i++)3790children[i].transform(matrix, true);3791return true;3792}3793},37943795globalToLocal: function() {3796var matrix = this.getGlobalMatrix();3797return matrix && matrix._inverseTransform(Point.read(arguments));3798},37993800localToGlobal: function() {3801var matrix = this.getGlobalMatrix();3802return matrix && matrix._transformPoint(Point.read(arguments));3803},38043805fitBounds: function(rectangle, fill) {3806rectangle = Rectangle.read(arguments);3807var bounds = this.getBounds(),3808itemRatio = bounds.height / bounds.width,3809rectRatio = rectangle.height / rectangle.width,3810scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)3811? rectangle.width / bounds.width3812: rectangle.height / bounds.height,3813newBounds = new Rectangle(new Point(),3814new Size(bounds.width * scale, bounds.height * scale));3815newBounds.setCenter(rectangle.getCenter());3816this.setBounds(newBounds);3817},38183819_setStyles: function(ctx) {3820var style = this._style,3821fillColor = style.getFillColor(),3822strokeColor = style.getStrokeColor(),3823shadowColor = style.getShadowColor();3824if (fillColor)3825ctx.fillStyle = fillColor.toCanvasStyle(ctx);3826if (strokeColor) {3827var strokeWidth = style.getStrokeWidth();3828if (strokeWidth > 0) {3829ctx.strokeStyle = strokeColor.toCanvasStyle(ctx);3830ctx.lineWidth = strokeWidth;3831var strokeJoin = style.getStrokeJoin(),3832strokeCap = style.getStrokeCap(),3833miterLimit = style.getMiterLimit();3834if (strokeJoin)3835ctx.lineJoin = strokeJoin;3836if (strokeCap)3837ctx.lineCap = strokeCap;3838if (miterLimit)3839ctx.miterLimit = miterLimit;3840if (paper.support.nativeDash) {3841var dashArray = style.getDashArray(),3842dashOffset = style.getDashOffset();3843if (dashArray && dashArray.length) {3844if ('setLineDash' in ctx) {3845ctx.setLineDash(dashArray);3846ctx.lineDashOffset = dashOffset;3847} else {3848ctx.mozDash = dashArray;3849ctx.mozDashOffset = dashOffset;3850}3851}3852}3853}3854}3855if (shadowColor) {3856var shadowBlur = style.getShadowBlur();3857if (shadowBlur > 0) {3858ctx.shadowColor = shadowColor.toCanvasStyle(ctx);3859ctx.shadowBlur = shadowBlur;3860var offset = this.getShadowOffset();3861ctx.shadowOffsetX = offset.x;3862ctx.shadowOffsetY = offset.y;3863}3864}3865},38663867draw: function(ctx, param) {3868if (!this._visible || this._opacity === 0)3869return;3870var updateVersion = this._updateVersion = this._project._updateVersion;3871var trackTransforms = param.trackTransforms,3872transforms = param.transforms,3873matrix = this._matrix,3874parentMatrix = transforms[transforms.length - 1],3875globalMatrix = parentMatrix.clone().concatenate(matrix);3876if (!globalMatrix.isInvertible())3877return;3878if (trackTransforms) {3879transforms.push(this._globalMatrix = globalMatrix);3880globalMatrix._updateVersion = updateVersion;3881}38823883var blendMode = this._blendMode,3884opacity = this._opacity,3885normalBlend = blendMode === 'normal',3886nativeBlend = BlendMode.nativeModes[blendMode],3887direct = normalBlend && opacity === 13888|| param.clip3889|| (nativeBlend || normalBlend && opacity < 1)3890&& this._canComposite(),3891mainCtx, itemOffset, prevOffset;3892if (!direct) {3893var bounds = this.getStrokeBounds(parentMatrix);3894if (!bounds.width || !bounds.height)3895return;3896prevOffset = param.offset;3897itemOffset = param.offset = bounds.getTopLeft().floor();3898mainCtx = ctx;3899ctx = CanvasProvider.getContext(3900bounds.getSize().ceil().add(new Size(1, 1)),3901param.pixelRatio);3902}3903ctx.save();3904if (direct) {3905ctx.globalAlpha = opacity;3906if (nativeBlend)3907ctx.globalCompositeOperation = blendMode;3908} else {3909ctx.translate(-itemOffset.x, -itemOffset.y);3910}3911(direct ? matrix : globalMatrix).applyToContext(ctx);3912if (!direct && param.clipItem)3913param.clipItem.draw(ctx, param.extend({ clip: true }));3914this._draw(ctx, param);3915ctx.restore();3916if (trackTransforms)3917transforms.pop();3918if (param.clip && !param.dontFinish)3919ctx.clip();3920if (!direct) {3921BlendMode.process(blendMode, ctx, mainCtx, opacity,3922itemOffset.subtract(prevOffset).multiply(param.pixelRatio));3923CanvasProvider.release(ctx);3924param.offset = prevOffset;3925}3926},39273928_canComposite: function() {3929return false;3930}3931}, Base.each(['down', 'drag', 'up', 'move'], function(name) {3932this['removeOn' + Base.capitalize(name)] = function() {3933var hash = {};3934hash[name] = true;3935return this.removeOn(hash);3936};3937}, {39383939removeOn: function(obj) {3940for (var name in obj) {3941if (obj[name]) {3942var key = 'mouse' + name,3943project = this._project,3944sets = project._removeSets = project._removeSets || {};3945sets[key] = sets[key] || {};3946sets[key][this._id] = this;3947}3948}3949return this;3950}3951}));39523953var Group = Item.extend({3954_class: 'Group',3955_selectChildren: true,3956_serializeFields: {3957children: []3958},39593960initialize: function Group(arg) {3961this._children = [];3962this._namedChildren = {};3963if (!this._initialize(arg))3964this.addChildren(Array.isArray(arg) ? arg : arguments);3965},39663967_changed: function _changed(flags) {3968_changed.base.call(this, flags);3969if (flags & (2 | 1024)) {3970this._clipItem = undefined;3971}3972},39733974_getClipItem: function() {3975var clipItem = this._clipItem;3976if (clipItem === undefined) {3977clipItem = null;3978for (var i = 0, l = this._children.length; i < l; i++) {3979var child = this._children[i];3980if (child._clipMask) {3981clipItem = child;3982break;3983}3984}3985this._clipItem = clipItem;3986}3987return clipItem;3988},39893990isClipped: function() {3991return !!this._getClipItem();3992},39933994setClipped: function(clipped) {3995var child = this.getFirstChild();3996if (child)3997child.setClipMask(clipped);3998},39994000_draw: function(ctx, param) {4001var clip = param.clip,4002clipItem = !clip && this._getClipItem(),4003draw = true;4004param = param.extend({ clipItem: clipItem, clip: false });4005if (clip) {4006if (this._currentPath) {4007ctx.currentPath = this._currentPath;4008draw = false;4009} else {4010ctx.beginPath();4011param.dontStart = param.dontFinish = true;4012}4013} else if (clipItem) {4014clipItem.draw(ctx, param.extend({ clip: true }));4015}4016if (draw) {4017for (var i = 0, l = this._children.length; i < l; i++) {4018var item = this._children[i];4019if (item !== clipItem)4020item.draw(ctx, param);4021}4022}4023if (clip) {4024this._currentPath = ctx.currentPath;4025}4026}4027});40284029var Layer = Group.extend({4030_class: 'Layer',40314032initialize: function Layer(arg) {4033var props = Base.isPlainObject(arg)4034? new Base(arg)4035: { children: Array.isArray(arg) ? arg : arguments },4036insert = props.insert;4037props.insert = false;4038Group.call(this, props);4039if (insert || insert === undefined) {4040this._project.addChild(this);4041this.activate();4042}4043},40444045_remove: function _remove(notify) {4046if (this._parent)4047return _remove.base.call(this, notify);4048if (this._index != null) {4049if (this._project.activeLayer === this)4050this._project.activeLayer = this.getNextSibling()4051|| this.getPreviousSibling();4052Base.splice(this._project.layers, null, this._index, 1);4053this._installEvents(false);4054this._project._needsUpdate = true;4055return true;4056}4057return false;4058},40594060getNextSibling: function getNextSibling() {4061return this._parent ? getNextSibling.base.call(this)4062: this._project.layers[this._index + 1] || null;4063},40644065getPreviousSibling: function getPreviousSibling() {4066return this._parent ? getPreviousSibling.base.call(this)4067: this._project.layers[this._index - 1] || null;4068},40694070isInserted: function isInserted() {4071return this._parent ? isInserted.base.call(this) : this._index != null;4072},40734074activate: function() {4075this._project.activeLayer = this;4076},40774078_insert: function _insert(above, item, _preserve) {4079if (item instanceof Layer && !item._parent) {4080this._remove(true, true);4081Base.splice(item._project.layers, [this],4082item._index + (above ? 1 : 0), 0);4083this._setProject(item._project, true);4084return this;4085}4086return _insert.base.call(this, above, item, _preserve);4087}4088});40894090var Shape = Item.extend({4091_class: 'Shape',4092_applyMatrix: false,4093_canApplyMatrix: false,4094_boundsSelected: true,4095_serializeFields: {4096type: null,4097size: null,4098radius: null4099},41004101initialize: function Shape(props) {4102this._initialize(props);4103},41044105_equals: function(item) {4106return this._type === item._type4107&& this._size.equals(item._size)4108&& Base.equals(this._radius, item._radius);4109},41104111clone: function(insert) {4112var copy = new Shape(Item.NO_INSERT);4113copy.setType(this._type);4114copy.setSize(this._size);4115copy.setRadius(this._radius);4116return this._clone(copy, insert);4117},41184119getType: function() {4120return this._type;4121},41224123setType: function(type) {4124this._type = type;4125},41264127getShape: '#getType',4128setShape: '#setType',41294130getSize: function() {4131var size = this._size;4132return new LinkedSize(size.width, size.height, this, 'setSize');4133},41344135setSize: function() {4136var size = Size.read(arguments);4137if (!this._size) {4138this._size = size.clone();4139} else if (!this._size.equals(size)) {4140var type = this._type,4141width = size.width,4142height = size.height;4143if (type === 'rectangle') {4144var radius = Size.min(this._radius, size.divide(2));4145this._radius.set(radius.width, radius.height);4146} else if (type === 'circle') {4147width = height = (width + height) / 2;4148this._radius = width / 2;4149} else if (type === 'ellipse') {4150this._radius.set(width / 2, height / 2);4151}4152this._size.set(width, height);4153this._changed(9);4154}4155},41564157getRadius: function() {4158var rad = this._radius;4159return this._type === 'circle'4160? rad4161: new LinkedSize(rad.width, rad.height, this, 'setRadius');4162},41634164setRadius: function(radius) {4165var type = this._type;4166if (type === 'circle') {4167if (radius === this._radius)4168return;4169var size = radius * 2;4170this._radius = radius;4171this._size.set(size, size);4172} else {4173radius = Size.read(arguments);4174if (!this._radius) {4175this._radius = radius.clone();4176} else {4177if (this._radius.equals(radius))4178return;4179this._radius.set(radius.width, radius.height);4180if (type === 'rectangle') {4181var size = Size.max(this._size, radius.multiply(2));4182this._size.set(size.width, size.height);4183} else if (type === 'ellipse') {4184this._size.set(radius.width * 2, radius.height * 2);4185}4186}4187}4188this._changed(9);4189},41904191isEmpty: function() {4192return false;4193},41944195toPath: function(insert) {4196var path = new Path[Base.capitalize(this._type)]({4197center: new Point(),4198size: this._size,4199radius: this._radius,4200insert: false4201});4202path.setStyle(this._style);4203path.transform(this._matrix);4204if (insert || insert === undefined)4205path.insertAbove(this);4206return path;4207},42084209_draw: function(ctx, param) {4210var style = this._style,4211hasFill = style.hasFill(),4212hasStroke = style.hasStroke(),4213dontPaint = param.dontFinish || param.clip;4214if (hasFill || hasStroke || dontPaint) {4215var radius = this._radius,4216type = this._type;4217if (!param.dontStart)4218ctx.beginPath();4219if (type === 'circle') {4220ctx.arc(0, 0, radius, 0, Math.PI * 2, true);4221} else {4222var rx = radius.width,4223ry = radius.height,4224kappa = 0.5522847498307936;4225if (type === 'ellipse') {4226var cx = rx * kappa,4227cy = ry * kappa;4228ctx.moveTo(-rx, 0);4229ctx.bezierCurveTo(-rx, -cy, -cx, -ry, 0, -ry);4230ctx.bezierCurveTo(cx, -ry, rx, -cy, rx, 0);4231ctx.bezierCurveTo(rx, cy, cx, ry, 0, ry);4232ctx.bezierCurveTo(-cx, ry, -rx, cy, -rx, 0);4233} else {4234var size = this._size,4235width = size.width,4236height = size.height;4237if (rx === 0 && ry === 0) {4238ctx.rect(-width / 2, -height / 2, width, height);4239} else {4240kappa = 1 - kappa;4241var x = width / 2,4242y = height / 2,4243cx = rx * kappa,4244cy = ry * kappa;4245ctx.moveTo(-x, -y + ry);4246ctx.bezierCurveTo(-x, -y + cy, -x + cx, -y, -x + rx, -y);4247ctx.lineTo(x - rx, -y);4248ctx.bezierCurveTo(x - cx, -y, x, -y + cy, x, -y + ry);4249ctx.lineTo(x, y - ry);4250ctx.bezierCurveTo(x, y - cy, x - cx, y, x - rx, y);4251ctx.lineTo(-x + rx, y);4252ctx.bezierCurveTo(-x + cx, y, -x, y - cy, -x, y - ry);4253}4254}4255}4256ctx.closePath();4257}4258if (!dontPaint && (hasFill || hasStroke)) {4259this._setStyles(ctx);4260if (hasFill) {4261ctx.fill(style.getWindingRule());4262ctx.shadowColor = 'rgba(0,0,0,0)';4263}4264if (hasStroke)4265ctx.stroke();4266}4267},42684269_canComposite: function() {4270return !(this.hasFill() && this.hasStroke());4271},42724273_getBounds: function(getter, matrix) {4274var rect = new Rectangle(this._size).setCenter(0, 0);4275if (getter !== 'getBounds' && this.hasStroke())4276rect = rect.expand(this.getStrokeWidth());4277return matrix ? matrix._transformBounds(rect) : rect;4278}4279},4280new function() {42814282function getCornerCenter(that, point, expand) {4283var radius = that._radius;4284if (!radius.isZero()) {4285var halfSize = that._size.divide(2);4286for (var i = 0; i < 4; i++) {4287var dir = new Point(i & 1 ? 1 : -1, i > 1 ? 1 : -1),4288corner = dir.multiply(halfSize),4289center = corner.subtract(dir.multiply(radius)),4290rect = new Rectangle(corner, center);4291if ((expand ? rect.expand(expand) : rect).contains(point))4292return center;4293}4294}4295}42964297function getEllipseRadius(point, radius) {4298var angle = point.getAngleInRadians(),4299width = radius.width * 2,4300height = radius.height * 2,4301x = width * Math.sin(angle),4302y = height * Math.cos(angle);4303return width * height / (2 * Math.sqrt(x * x + y * y));4304}43054306return {4307_contains: function _contains(point) {4308if (this._type === 'rectangle') {4309var center = getCornerCenter(this, point);4310return center4311? point.subtract(center).divide(this._radius)4312.getLength() <= 14313: _contains.base.call(this, point);4314} else {4315return point.divide(this.size).getLength() <= 0.5;4316}4317},43184319_hitTest: function _hitTest(point, options) {4320var hit = false;4321if (this.hasStroke()) {4322var type = this._type,4323radius = this._radius,4324strokeWidth = this.getStrokeWidth() + 2 * options.tolerance;4325if (type === 'rectangle') {4326var center = getCornerCenter(this, point, strokeWidth);4327if (center) {4328var pt = point.subtract(center);4329hit = 2 * Math.abs(pt.getLength()4330- getEllipseRadius(pt, radius)) <= strokeWidth;4331} else {4332var rect = new Rectangle(this._size).setCenter(0, 0),4333outer = rect.expand(strokeWidth),4334inner = rect.expand(-strokeWidth);4335hit = outer._containsPoint(point)4336&& !inner._containsPoint(point);4337}4338} else {4339if (type === 'ellipse')4340radius = getEllipseRadius(point, radius);4341hit = 2 * Math.abs(point.getLength() - radius)4342<= strokeWidth;4343}4344}4345return hit4346? new HitResult('stroke', this)4347: _hitTest.base.apply(this, arguments);4348}4349};4350}, {43514352statics: new function() {4353function createShape(type, point, size, radius, args) {4354var item = new Shape(Base.getNamed(args));4355item._type = type;4356item._size = size;4357item._radius = radius;4358return item.translate(point);4359}43604361return {4362Circle: function() {4363var center = Point.readNamed(arguments, 'center'),4364radius = Base.readNamed(arguments, 'radius');4365return createShape('circle', center, new Size(radius * 2), radius,4366arguments);4367},43684369Rectangle: function() {4370var rect = Rectangle.readNamed(arguments, 'rectangle'),4371radius = Size.min(Size.readNamed(arguments, 'radius'),4372rect.getSize(true).divide(2));4373return createShape('rectangle', rect.getCenter(true),4374rect.getSize(true), radius, arguments);4375},43764377Ellipse: function() {4378var ellipse = Shape._readEllipse(arguments),4379radius = ellipse.radius;4380return createShape('ellipse', ellipse.center, radius.multiply(2),4381radius, arguments);4382},43834384_readEllipse: function(args) {4385var center,4386radius;4387if (Base.hasNamed(args, 'radius')) {4388center = Point.readNamed(args, 'center');4389radius = Size.readNamed(args, 'radius');4390} else {4391var rect = Rectangle.readNamed(args, 'rectangle');4392center = rect.getCenter(true);4393radius = rect.getSize(true).divide(2);4394}4395return { center: center, radius: radius };4396}4397};4398}});43994400var Raster = Item.extend({4401_class: 'Raster',4402_applyMatrix: false,4403_canApplyMatrix: false,4404_boundsGetter: 'getBounds',4405_boundsSelected: true,4406_serializeFields: {4407source: null4408},44094410initialize: function Raster(object, position) {4411if (!this._initialize(object,4412position !== undefined && Point.read(arguments, 1))) {4413if (typeof object === 'string') {4414this.setSource(object);4415} else {4416this.setImage(object);4417}4418}4419if (!this._size)4420this._size = new Size();4421},44224423_equals: function(item) {4424return this.getSource() === item.getSource();4425},44264427clone: function(insert) {4428var copy = new Raster(Item.NO_INSERT),4429image = this._image,4430canvas = this._canvas;4431if (image) {4432copy.setImage(image);4433} else if (canvas) {4434var copyCanvas = CanvasProvider.getCanvas(this._size);4435copyCanvas.getContext('2d').drawImage(canvas, 0, 0);4436copy.setCanvas(copyCanvas);4437}4438return this._clone(copy, insert);4439},44404441getSize: function() {4442var size = this._size;4443return new LinkedSize(size.width, size.height, this, 'setSize');4444},44454446setSize: function() {4447var size = Size.read(arguments);4448if (!this._size.equals(size)) {4449var element = this.getElement();4450this.setCanvas(CanvasProvider.getCanvas(size));4451if (element)4452this.getContext(true).drawImage(element, 0, 0,4453size.width, size.height);4454}4455},44564457getWidth: function() {4458return this._size.width;4459},44604461getHeight: function() {4462return this._size.height;4463},44644465isEmpty: function() {4466return this._size.width == 0 && this._size.height == 0;4467},44684469getPpi: function() {4470var matrix = this._matrix,4471orig = new Point(0, 0).transform(matrix),4472u = new Point(1, 0).transform(matrix).subtract(orig),4473v = new Point(0, 1).transform(matrix).subtract(orig);4474return new Size(447572 / u.getLength(),447672 / v.getLength()4477);4478},44794480getImage: function() {4481return this._image;4482},44834484setImage: function(image) {4485if (this._canvas)4486CanvasProvider.release(this._canvas);4487if (image.getContext) {4488this._image = null;4489this._canvas = image;4490} else {4491this._image = image;4492this._canvas = null;4493}4494this._size = new Size(4495image.naturalWidth || image.width,4496image.naturalHeight || image.height);4497this._context = null;4498this._changed(9 | 513);4499},45004501getCanvas: function() {4502if (!this._canvas) {4503var ctx = CanvasProvider.getContext(this._size);4504try {4505if (this._image)4506ctx.drawImage(this._image, 0, 0);4507this._canvas = ctx.canvas;4508} catch (e) {4509CanvasProvider.release(ctx);4510}4511}4512return this._canvas;4513},45144515setCanvas: '#setImage',45164517getContext: function(modify) {4518if (!this._context)4519this._context = this.getCanvas().getContext('2d');4520if (modify) {4521this._image = null;4522this._changed(513);4523}4524return this._context;4525},45264527setContext: function(context) {4528this._context = context;4529},45304531getSource: function() {4532return this._image && this._image.src || this.toDataURL();4533},45344535setSource: function(src) {4536var that = this,4537image;45384539function loaded() {4540var view = that.getView();4541if (view) {4542paper = view._scope;4543that.setImage(image);4544that.fire('load');4545view.update();4546}4547}45484549image = document.getElementById(src) || new Image();45504551if (image.naturalWidth && image.naturalHeight) {4552setTimeout(loaded, 0);4553} else {4554DomEvent.add(image, {4555load: loaded4556});4557if (!image.src)4558image.src = src;4559}4560this.setImage(image);4561},45624563getElement: function() {4564return this._canvas || this._image;4565},45664567getSubCanvas: function(rect) {4568var rect = Rectangle.read(arguments),4569ctx = CanvasProvider.getContext(rect.getSize());4570ctx.drawImage(this.getCanvas(), rect.x, rect.y,4571rect.width, rect.height, 0, 0, rect.width, rect.height);4572return ctx.canvas;4573},45744575getSubRaster: function(rect) {4576var rect = Rectangle.read(arguments),4577raster = new Raster(Item.NO_INSERT);4578raster.setCanvas(this.getSubCanvas(rect));4579raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));4580raster._matrix.preConcatenate(this._matrix);4581raster.insertAbove(this);4582return raster;4583},45844585toDataURL: function() {4586var src = this._image && this._image.src;4587if (/^data:/.test(src))4588return src;4589var canvas = this.getCanvas();4590return canvas ? canvas.toDataURL() : null;4591},45924593drawImage: function(image ) {4594var point = Point.read(arguments, 1);4595this.getContext(true).drawImage(image, point.x, point.y);4596},45974598getAverageColor: function(object) {4599var bounds, path;4600if (!object) {4601bounds = this.getBounds();4602} else if (object instanceof PathItem) {4603path = object;4604bounds = object.getBounds();4605} else if (object.width) {4606bounds = new Rectangle(object);4607} else if (object.x) {4608bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);4609}4610var sampleSize = 32,4611width = Math.min(bounds.width, sampleSize),4612height = Math.min(bounds.height, sampleSize);4613var ctx = Raster._sampleContext;4614if (!ctx) {4615ctx = Raster._sampleContext = CanvasProvider.getContext(4616new Size(sampleSize));4617} else {4618ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);4619}4620ctx.save();4621var matrix = new Matrix()4622.scale(width / bounds.width, height / bounds.height)4623.translate(-bounds.x, -bounds.y);4624matrix.applyToContext(ctx);4625if (path)4626path.draw(ctx, new Base({ clip: true, transforms: [matrix] }));4627this._matrix.applyToContext(ctx);4628ctx.drawImage(this.getElement(),4629-this._size.width / 2, -this._size.height / 2);4630ctx.restore();4631var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),4632Math.ceil(height)).data,4633channels = [0, 0, 0],4634total = 0;4635for (var i = 0, l = pixels.length; i < l; i += 4) {4636var alpha = pixels[i + 3];4637total += alpha;4638alpha /= 255;4639channels[0] += pixels[i] * alpha;4640channels[1] += pixels[i + 1] * alpha;4641channels[2] += pixels[i + 2] * alpha;4642}4643for (var i = 0; i < 3; i++)4644channels[i] /= total;4645return total ? Color.read(channels) : null;4646},46474648getPixel: function(point) {4649var point = Point.read(arguments);4650var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;4651return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],4652data[3] / 255);4653},46544655setPixel: function() {4656var point = Point.read(arguments),4657color = Color.read(arguments),4658components = color._convert('rgb'),4659alpha = color._alpha,4660ctx = this.getContext(true),4661imageData = ctx.createImageData(1, 1),4662data = imageData.data;4663data[0] = components[0] * 255;4664data[1] = components[1] * 255;4665data[2] = components[2] * 255;4666data[3] = alpha != null ? alpha * 255 : 255;4667ctx.putImageData(imageData, point.x, point.y);4668},46694670createImageData: function() {4671var size = Size.read(arguments);4672return this.getContext().createImageData(size.width, size.height);4673},46744675getImageData: function(rect) {4676var rect = Rectangle.read(arguments);4677if (rect.isEmpty())4678rect = new Rectangle(this._size);4679return this.getContext().getImageData(rect.x, rect.y,4680rect.width, rect.height);4681},46824683setImageData: function(data ) {4684var point = Point.read(arguments, 1);4685this.getContext(true).putImageData(data, point.x, point.y);4686},46874688_getBounds: function(getter, matrix) {4689var rect = new Rectangle(this._size).setCenter(0, 0);4690return matrix ? matrix._transformBounds(rect) : rect;4691},46924693_hitTest: function(point) {4694if (this._contains(point)) {4695var that = this;4696return new HitResult('pixel', that, {4697offset: point.add(that._size.divide(2)).round(),4698color: {4699get: function() {4700return that.getPixel(this.offset);4701}4702}4703});4704}4705},47064707_draw: function(ctx) {4708var element = this.getElement();4709if (element) {4710ctx.globalAlpha = this._opacity;4711ctx.drawImage(element,4712-this._size.width / 2, -this._size.height / 2);4713}4714},47154716_canComposite: function() {4717return true;4718}4719});47204721var PlacedSymbol = Item.extend({4722_class: 'PlacedSymbol',4723_applyMatrix: false,4724_canApplyMatrix: false,4725_boundsGetter: { getBounds: 'getStrokeBounds' },4726_boundsSelected: true,4727_serializeFields: {4728symbol: null4729},47304731initialize: function PlacedSymbol(arg0, arg1) {4732if (!this._initialize(arg0,4733arg1 !== undefined && Point.read(arguments, 1)))4734this.setSymbol(arg0 instanceof Symbol ? arg0 : new Symbol(arg0));4735},47364737_equals: function(item) {4738return this._symbol === item._symbol;4739},47404741getSymbol: function() {4742return this._symbol;4743},47444745setSymbol: function(symbol) {4746this._symbol = symbol;4747this._changed(9);4748},47494750clone: function(insert) {4751var copy = new PlacedSymbol(Item.NO_INSERT);4752copy.setSymbol(this._symbol);4753return this._clone(copy, insert);4754},47554756isEmpty: function() {4757return this._symbol._definition.isEmpty();4758},47594760_getBounds: function(getter, matrix, cacheItem) {4761return this.symbol._definition._getCachedBounds(getter, matrix,4762cacheItem);4763},47644765_hitTest: function(point, options) {4766var res = this._symbol._definition.hitTest(point, options);4767if (res)4768res.item = this;4769return res;4770},47714772_draw: function(ctx, param) {4773this.symbol._definition.draw(ctx, param);4774}47754776});47774778var HitResult = Base.extend({4779_class: 'HitResult',47804781initialize: function HitResult(type, item, values) {4782this.type = type;4783this.item = item;4784if (values) {4785values.enumerable = true;4786this.inject(values);4787}4788},47894790statics: {4791getOptions: function(options) {4792return options && options._merged ? options : new Base({4793type: null,4794tolerance: paper.settings.hitTolerance,4795fill: !options,4796stroke: !options,4797segments: !options,4798handles: false,4799ends: false,4800center: false,4801bounds: false,4802guides: false,4803selected: false,4804_merged: true4805}, options);4806}4807}4808});48094810var Segment = Base.extend({4811_class: 'Segment',4812beans: true,48134814initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {4815var count = arguments.length,4816point, handleIn, handleOut;4817if (count === 0) {4818} else if (count === 1) {4819if (arg0.point) {4820point = arg0.point;4821handleIn = arg0.handleIn;4822handleOut = arg0.handleOut;4823} else {4824point = arg0;4825}4826} else if (count === 2 && typeof arg0 === 'number') {4827point = arguments;4828} else if (count <= 3) {4829point = arg0;4830handleIn = arg1;4831handleOut = arg2;4832} else {4833point = arg0 !== undefined ? [ arg0, arg1 ] : null;4834handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;4835handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;4836}4837new SegmentPoint(point, this, '_point');4838new SegmentPoint(handleIn, this, '_handleIn');4839new SegmentPoint(handleOut, this, '_handleOut');4840},48414842_serialize: function(options) {4843return Base.serialize(this.isLinear() ? this._point4844: [this._point, this._handleIn, this._handleOut],4845options, true);4846},48474848_changed: function(point) {4849var path = this._path;4850if (!path)4851return;4852var curves = path._curves,4853index = this._index,4854curveIn, curveOut;4855if (curves) {4856if ((!point || point === this._point || point === this._handleIn)4857&& (curveIn = curves[index - 1]4858|| path._closed && curves[curves.length - 1]))4859curveIn._changed();4860if ((!point || point === this._point || point === this._handleOut)4861&& (curveOut = curves[index]))4862curveOut._changed();4863}4864path._changed(25);4865},48664867getPoint: function() {4868return this._point;4869},48704871setPoint: function() {4872var point = Point.read(arguments);4873this._point.set(point.x, point.y);4874},48754876getHandleIn: function() {4877return this._handleIn;4878},48794880setHandleIn: function() {4881var point = Point.read(arguments);4882this._handleIn.set(point.x, point.y);4883},48844885getHandleOut: function() {4886return this._handleOut;4887},48884889setHandleOut: function() {4890var point = Point.read(arguments);4891this._handleOut.set(point.x, point.y);4892},48934894isLinear: function() {4895return this._handleIn.isZero() && this._handleOut.isZero();4896},48974898setLinear: function() {4899this._handleIn.set(0, 0);4900this._handleOut.set(0, 0);4901},49024903isColinear: function(segment) {4904var next1 = this.getNext(),4905next2 = segment.getNext();4906return this._handleOut.isZero() && next1._handleIn.isZero()4907&& segment._handleOut.isZero() && next2._handleIn.isZero()4908&& next1._point.subtract(this._point).isColinear(4909next2._point.subtract(segment._point));4910},49114912isOrthogonal: function() {4913var prev = this.getPrevious(),4914next = this.getNext();4915return prev._handleOut.isZero() && this._handleIn.isZero()4916&& this._handleOut.isZero() && next._handleIn.isZero()4917&& this._point.subtract(prev._point).isOrthogonal(4918next._point.subtract(this._point));4919},49204921isArc: function() {4922var next = this.getNext(),4923handle1 = this._handleOut,4924handle2 = next._handleIn,4925kappa = 0.5522847498307936;4926if (handle1.isOrthogonal(handle2)) {4927var from = this._point,4928to = next._point,4929corner = new Line(from, handle1, true).intersect(4930new Line(to, handle2, true), true);4931return corner && Numerical.isZero(handle1.getLength() /4932corner.subtract(from).getLength() - kappa)4933&& Numerical.isZero(handle2.getLength() /4934corner.subtract(to).getLength() - kappa);4935}4936return false;4937},49384939_selectionState: 0,49404941isSelected: function(_point) {4942var state = this._selectionState;4943return !_point ? !!(state & 7)4944: _point === this._point ? !!(state & 4)4945: _point === this._handleIn ? !!(state & 1)4946: _point === this._handleOut ? !!(state & 2)4947: false;4948},49494950setSelected: function(selected, _point) {4951var path = this._path,4952selected = !!selected,4953state = this._selectionState,4954oldState = state,4955flag = !_point ? 74956: _point === this._point ? 44957: _point === this._handleIn ? 14958: _point === this._handleOut ? 24959: 0;4960if (selected) {4961state |= flag;4962} else {4963state &= ~flag;4964}4965this._selectionState = state;4966if (path && state !== oldState) {4967path._updateSelection(this, oldState, state);4968path._changed(129);4969}4970},49714972getIndex: function() {4973return this._index !== undefined ? this._index : null;4974},49754976getPath: function() {4977return this._path || null;4978},49794980getCurve: function() {4981var path = this._path,4982index = this._index;4983if (path) {4984if (index > 0 && !path._closed4985&& index === path._segments.length - 1)4986index--;4987return path.getCurves()[index] || null;4988}4989return null;4990},49914992getLocation: function() {4993var curve = this.getCurve();4994return curve4995? new CurveLocation(curve, this === curve._segment1 ? 0 : 1)4996: null;4997},49984999getNext: function() {5000var segments = this._path && this._path._segments;5001return segments && (segments[this._index + 1]5002|| this._path._closed && segments[0]) || null;5003},50045005getPrevious: function() {5006var segments = this._path && this._path._segments;5007return segments && (segments[this._index - 1]5008|| this._path._closed && segments[segments.length - 1]) || null;5009},50105011reverse: function() {5012return new Segment(this._point, this._handleOut, this._handleIn);5013},50145015remove: function() {5016return this._path ? !!this._path.removeSegment(this._index) : false;5017},50185019clone: function() {5020return new Segment(this._point, this._handleIn, this._handleOut);5021},50225023equals: function(segment) {5024return segment === this || segment && this._class === segment._class5025&& this._point.equals(segment._point)5026&& this._handleIn.equals(segment._handleIn)5027&& this._handleOut.equals(segment._handleOut)5028|| false;5029},50305031toString: function() {5032var parts = [ 'point: ' + this._point ];5033if (!this._handleIn.isZero())5034parts.push('handleIn: ' + this._handleIn);5035if (!this._handleOut.isZero())5036parts.push('handleOut: ' + this._handleOut);5037return '{ ' + parts.join(', ') + ' }';5038},50395040transform: function(matrix) {5041this._transformCoordinates(matrix, new Array(6), true);5042this._changed();5043},50445045_transformCoordinates: function(matrix, coords, change) {5046var point = this._point,5047handleIn = !change || !this._handleIn.isZero()5048? this._handleIn : null,5049handleOut = !change || !this._handleOut.isZero()5050? this._handleOut : null,5051x = point._x,5052y = point._y,5053i = 2;5054coords[0] = x;5055coords[1] = y;5056if (handleIn) {5057coords[i++] = handleIn._x + x;5058coords[i++] = handleIn._y + y;5059}5060if (handleOut) {5061coords[i++] = handleOut._x + x;5062coords[i++] = handleOut._y + y;5063}5064if (matrix) {5065matrix._transformCoordinates(coords, 0, coords, 0, i / 2);5066x = coords[0];5067y = coords[1];5068if (change) {5069point._x = x;5070point._y = y;5071i = 2;5072if (handleIn) {5073handleIn._x = coords[i++] - x;5074handleIn._y = coords[i++] - y;5075}5076if (handleOut) {5077handleOut._x = coords[i++] - x;5078handleOut._y = coords[i++] - y;5079}5080} else {5081if (!handleIn) {5082coords[i++] = x;5083coords[i++] = y;5084}5085if (!handleOut) {5086coords[i++] = x;5087coords[i++] = y;5088}5089}5090}5091return coords;5092}5093});50945095var SegmentPoint = Point.extend({5096initialize: function SegmentPoint(point, owner, key) {5097var x, y, selected;5098if (!point) {5099x = y = 0;5100} else if ((x = point[0]) !== undefined) {5101y = point[1];5102} else {5103var pt = point;5104if ((x = pt.x) === undefined) {5105pt = Point.read(arguments);5106x = pt.x;5107}5108y = pt.y;5109selected = pt.selected;5110}5111this._x = x;5112this._y = y;5113this._owner = owner;5114owner[key] = this;5115if (selected)5116this.setSelected(true);5117},51185119set: function(x, y) {5120this._x = x;5121this._y = y;5122this._owner._changed(this);5123return this;5124},51255126_serialize: function(options) {5127var f = options.formatter,5128x = f.number(this._x),5129y = f.number(this._y);5130return this.isSelected()5131? { x: x, y: y, selected: true }5132: [x, y];5133},51345135getX: function() {5136return this._x;5137},51385139setX: function(x) {5140this._x = x;5141this._owner._changed(this);5142},51435144getY: function() {5145return this._y;5146},51475148setY: function(y) {5149this._y = y;5150this._owner._changed(this);5151},51525153isZero: function() {5154return Numerical.isZero(this._x) && Numerical.isZero(this._y);5155},51565157setSelected: function(selected) {5158this._owner.setSelected(selected, this);5159},51605161isSelected: function() {5162return this._owner.isSelected(this);5163}5164});51655166var Curve = Base.extend({5167_class: 'Curve',5168initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {5169var count = arguments.length;5170if (count === 3) {5171this._path = arg0;5172this._segment1 = arg1;5173this._segment2 = arg2;5174} else if (count === 0) {5175this._segment1 = new Segment();5176this._segment2 = new Segment();5177} else if (count === 1) {5178this._segment1 = new Segment(arg0.segment1);5179this._segment2 = new Segment(arg0.segment2);5180} else if (count === 2) {5181this._segment1 = new Segment(arg0);5182this._segment2 = new Segment(arg1);5183} else {5184var point1, handle1, handle2, point2;5185if (count === 4) {5186point1 = arg0;5187handle1 = arg1;5188handle2 = arg2;5189point2 = arg3;5190} else if (count === 8) {5191point1 = [arg0, arg1];5192point2 = [arg6, arg7];5193handle1 = [arg2 - arg0, arg3 - arg1];5194handle2 = [arg4 - arg6, arg5 - arg7];5195}5196this._segment1 = new Segment(point1, null, handle1);5197this._segment2 = new Segment(point2, handle2, null);5198}5199},52005201_changed: function() {5202this._length = this._bounds = undefined;5203},52045205getPoint1: function() {5206return this._segment1._point;5207},52085209setPoint1: function() {5210var point = Point.read(arguments);5211this._segment1._point.set(point.x, point.y);5212},52135214getPoint2: function() {5215return this._segment2._point;5216},52175218setPoint2: function() {5219var point = Point.read(arguments);5220this._segment2._point.set(point.x, point.y);5221},52225223getHandle1: function() {5224return this._segment1._handleOut;5225},52265227setHandle1: function() {5228var point = Point.read(arguments);5229this._segment1._handleOut.set(point.x, point.y);5230},52315232getHandle2: function() {5233return this._segment2._handleIn;5234},52355236setHandle2: function() {5237var point = Point.read(arguments);5238this._segment2._handleIn.set(point.x, point.y);5239},52405241getSegment1: function() {5242return this._segment1;5243},52445245getSegment2: function() {5246return this._segment2;5247},52485249getPath: function() {5250return this._path;5251},52525253getIndex: function() {5254return this._segment1._index;5255},52565257getNext: function() {5258var curves = this._path && this._path._curves;5259return curves && (curves[this._segment1._index + 1]5260|| this._path._closed && curves[0]) || null;5261},52625263getPrevious: function() {5264var curves = this._path && this._path._curves;5265return curves && (curves[this._segment1._index - 1]5266|| this._path._closed && curves[curves.length - 1]) || null;5267},52685269isSelected: function() {5270return this.getPoint1().isSelected()5271&& this.getHandle2().isSelected()5272&& this.getHandle2().isSelected()5273&& this.getPoint2().isSelected();5274},52755276setSelected: function(selected) {5277this.getPoint1().setSelected(selected);5278this.getHandle1().setSelected(selected);5279this.getHandle2().setSelected(selected);5280this.getPoint2().setSelected(selected);5281},52825283getValues: function(matrix) {5284return Curve.getValues(this._segment1, this._segment2, matrix);5285},52865287getPoints: function() {5288var coords = this.getValues(),5289points = [];5290for (var i = 0; i < 8; i += 2)5291points.push(new Point(coords[i], coords[i + 1]));5292return points;5293},52945295getLength: function() {5296if (this._length == null) {5297this._length = this.isLinear()5298? this._segment2._point.getDistance(this._segment1._point)5299: Curve.getLength(this.getValues(), 0, 1);5300}5301return this._length;5302},53035304getArea: function() {5305return Curve.getArea(this.getValues());5306},53075308getPart: function(from, to) {5309return new Curve(Curve.getPart(this.getValues(), from, to));5310},53115312getPartLength: function(from, to) {5313return Curve.getLength(this.getValues(), from, to);5314},53155316isLinear: function() {5317return this._segment1._handleOut.isZero()5318&& this._segment2._handleIn.isZero();5319},53205321isHorizontal: function() {5322return this.isLinear() && Numerical.isZero(5323this._segment1._point._y - this._segment2._point._y);5324},53255326getIntersections: function(curve) {5327return Curve.getIntersections(this.getValues(), curve.getValues(),5328this, curve, []);5329},53305331_getParameter: function(offset, isParameter) {5332return isParameter5333? offset5334: offset && offset.curve === this5335? offset.parameter5336: offset === undefined && isParameter === undefined5337? 0.55338: this.getParameterAt(offset, 0);5339},53405341divide: function(offset, isParameter, ignoreLinear) {5342var parameter = this._getParameter(offset, isParameter),5343tolerance = 0.00001,5344res = null;5345if (parameter > tolerance && parameter < 1 - tolerance) {5346var parts = Curve.subdivide(this.getValues(), parameter),5347isLinear = ignoreLinear ? false : this.isLinear(),5348left = parts[0],5349right = parts[1];53505351if (!isLinear) {5352this._segment1._handleOut.set(left[2] - left[0],5353left[3] - left[1]);5354this._segment2._handleIn.set(right[4] - right[6],5355right[5] - right[7]);5356}53575358var x = left[6], y = left[7],5359segment = new Segment(new Point(x, y),5360!isLinear && new Point(left[4] - x, left[5] - y),5361!isLinear && new Point(right[2] - x, right[3] - y));53625363if (this._path) {5364if (this._segment1._index > 0 && this._segment2._index === 0) {5365this._path.add(segment);5366} else {5367this._path.insert(this._segment2._index, segment);5368}5369res = this;5370} else {5371var end = this._segment2;5372this._segment2 = segment;5373res = new Curve(segment, end);5374}5375}5376return res;5377},53785379split: function(offset, isParameter) {5380return this._path5381? this._path.split(this._segment1._index,5382this._getParameter(offset, isParameter))5383: null;5384},53855386reverse: function() {5387return new Curve(this._segment2.reverse(), this._segment1.reverse());5388},53895390remove: function() {5391var removed = false;5392if (this._path) {5393var segment2 = this._segment2,5394handleOut = segment2._handleOut;5395removed = segment2.remove();5396if (removed)5397this._segment1._handleOut.set(handleOut.x, handleOut.y);5398}5399return removed;5400},54015402clone: function() {5403return new Curve(this._segment1, this._segment2);5404},54055406toString: function() {5407var parts = [ 'point1: ' + this._segment1._point ];5408if (!this._segment1._handleOut.isZero())5409parts.push('handle1: ' + this._segment1._handleOut);5410if (!this._segment2._handleIn.isZero())5411parts.push('handle2: ' + this._segment2._handleIn);5412parts.push('point2: ' + this._segment2._point);5413return '{ ' + parts.join(', ') + ' }';5414},54155416statics: {5417getValues: function(segment1, segment2, matrix) {5418var p1 = segment1._point,5419h1 = segment1._handleOut,5420h2 = segment2._handleIn,5421p2 = segment2._point,5422values = [5423p1._x, p1._y,5424p1._x + h1._x, p1._y + h1._y,5425p2._x + h2._x, p2._y + h2._y,5426p2._x, p2._y5427];5428if (matrix)5429matrix._transformCoordinates(values, 0, values, 0, 6);5430return values;5431},54325433evaluate: function(v, t, type) {5434var p1x = v[0], p1y = v[1],5435c1x = v[2], c1y = v[3],5436c2x = v[4], c2y = v[5],5437p2x = v[6], p2y = v[7],5438tolerance = 0.00001,5439x, y;54405441if (type === 0 && (t < tolerance || t > 1 - tolerance)) {5442var isZero = t < tolerance;5443x = isZero ? p1x : p2x;5444y = isZero ? p1y : p2y;5445} else {5446var cx = 3 * (c1x - p1x),5447bx = 3 * (c2x - c1x) - cx,5448ax = p2x - p1x - cx - bx,54495450cy = 3 * (c1y - p1y),5451by = 3 * (c2y - c1y) - cy,5452ay = p2y - p1y - cy - by;5453if (type === 0) {5454x = ((ax * t + bx) * t + cx) * t + p1x;5455y = ((ay * t + by) * t + cy) * t + p1y;5456} else {5457if (t < tolerance && c1x === p1x && c1y === p1y5458|| t > 1 - tolerance && c2x === p2x && c2y === p2y) {5459x = p2x - p1x;5460y = p2y - p1y;5461} else if (t < tolerance) {5462x = cx;5463y = cy;5464} else if (t > 1 - tolerance) {5465x = 3 * (p2x - c2x);5466y = 3 * (p2y - c2y);5467} else {5468x = (3 * ax * t + 2 * bx) * t + cx;5469y = (3 * ay * t + 2 * by) * t + cy;5470}5471if (type === 3) {5472var x2 = 6 * ax * t + 2 * bx,5473y2 = 6 * ay * t + 2 * by;5474return (x * y2 - y * x2) / Math.pow(x * x + y * y, 3 / 2);5475}5476}5477}5478return type === 2 ? new Point(y, -x) : new Point(x, y);5479},54805481subdivide: function(v, t) {5482var p1x = v[0], p1y = v[1],5483c1x = v[2], c1y = v[3],5484c2x = v[4], c2y = v[5],5485p2x = v[6], p2y = v[7];5486if (t === undefined)5487t = 0.5;5488var u = 1 - t,5489p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y,5490p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y,5491p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y,5492p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y,5493p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y,5494p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y;5495return [5496[p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y],5497[p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y]5498];5499},55005501solveCubic: function (v, coord, val, roots, min, max) {5502var p1 = v[coord],5503c1 = v[coord + 2],5504c2 = v[coord + 4],5505p2 = v[coord + 6],5506c = 3 * (c1 - p1),5507b = 3 * (c2 - c1) - c,5508a = p2 - p1 - c - b;5509return Numerical.solveCubic(a, b, c, p1 - val, roots, min, max);5510},55115512getParameterOf: function(v, x, y) {5513var tolerance = 0.00001;5514if (Math.abs(v[0] - x) < tolerance && Math.abs(v[1] - y) < tolerance)5515return 0;5516if (Math.abs(v[6] - x) < tolerance && Math.abs(v[7] - y) < tolerance)5517return 1;5518var txs = [],5519tys = [],5520sx = Curve.solveCubic(v, 0, x, txs),5521sy = Curve.solveCubic(v, 1, y, tys),5522tx, ty;5523for (var cx = 0; sx == -1 || cx < sx;) {5524if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) {5525for (var cy = 0; sy == -1 || cy < sy;) {5526if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) {5527if (sx == -1) tx = ty;5528else if (sy == -1) ty = tx;5529if (Math.abs(tx - ty) < tolerance)5530return (tx + ty) * 0.5;5531}5532}5533if (sx == -1)5534break;5535}5536}5537return null;5538},55395540getPart: function(v, from, to) {5541if (from > 0)5542v = Curve.subdivide(v, from)[1];5543if (to < 1)5544v = Curve.subdivide(v, (to - from) / (1 - from))[0];5545return v;5546},55475548isLinear: function(v) {5549var isZero = Numerical.isZero;5550return isZero(v[0] - v[2]) && isZero(v[1] - v[3])5551&& isZero(v[4] - v[6]) && isZero(v[5] - v[7]);5552},55535554isFlatEnough: function(v, tolerance) {5555var p1x = v[0], p1y = v[1],5556c1x = v[2], c1y = v[3],5557c2x = v[4], c2y = v[5],5558p2x = v[6], p2y = v[7],5559ux = 3 * c1x - 2 * p1x - p2x,5560uy = 3 * c1y - 2 * p1y - p2y,5561vx = 3 * c2x - 2 * p2x - p1x,5562vy = 3 * c2y - 2 * p2y - p1y;5563return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)5564< 10 * tolerance * tolerance;5565},55665567getArea: function(v) {5568var p1x = v[0], p1y = v[1],5569c1x = v[2], c1y = v[3],5570c2x = v[4], c2y = v[5],5571p2x = v[6], p2y = v[7];5572return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x5573- 1.5 * c1y * p2x - 3.0 * p1y * c1x5574- 1.5 * p1y * c2x - 0.5 * p1y * p2x5575+ 1.5 * c2y * p1x + 1.5 * c2y * c1x5576- 3.0 * c2y * p2x + 0.5 * p2y * p1x5577+ 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10;5578},55795580getBounds: function(v) {5581var min = v.slice(0, 2),5582max = min.slice(),5583roots = [0, 0];5584for (var i = 0; i < 2; i++)5585Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],5586i, 0, min, max, roots);5587return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);5588},55895590_addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {5591function add(value, padding) {5592var left = value - padding,5593right = value + padding;5594if (left < min[coord])5595min[coord] = left;5596if (right > max[coord])5597max[coord] = right;5598}5599var a = 3 * (v1 - v2) - v0 + v3,5600b = 2 * (v0 + v2) - 4 * v1,5601c = v1 - v0,5602count = Numerical.solveQuadratic(a, b, c, roots),5603tMin = 0.00001,5604tMax = 1 - tMin;5605add(v3, 0);5606for (var i = 0; i < count; i++) {5607var t = roots[i],5608u = 1 - t;5609if (tMin < t && t < tMax)5610add(u * u * u * v05611+ 3 * u * u * t * v15612+ 3 * u * t * t * v25613+ t * t * t * v3,5614padding);5615}5616}5617}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],5618function(name) {5619this[name] = function() {5620if (!this._bounds)5621this._bounds = {};5622var bounds = this._bounds[name];5623if (!bounds) {5624bounds = this._bounds[name] = Path[name]([this._segment1,5625this._segment2], false, this._path.getStyle());5626}5627return bounds.clone();5628};5629},5630{56315632}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvature'],5633function(name, index) {5634this[name + 'At'] = function(offset, isParameter) {5635var values = this.getValues();5636return Curve.evaluate(values, isParameter5637? offset : Curve.getParameterAt(values, offset, 0), index);5638};5639this[name] = function(parameter) {5640return Curve.evaluate(this.getValues(), parameter, index);5641};5642},5643{5644getParameterAt: function(offset, start) {5645return Curve.getParameterAt(this.getValues(), offset,5646start !== undefined ? start : offset < 0 ? 1 : 0);5647},56485649getParameterOf: function(point) {5650var point = Point.read(arguments);5651return Curve.getParameterOf(this.getValues(), point.x, point.y);5652},56535654getLocationAt: function(offset, isParameter) {5655if (!isParameter)5656offset = this.getParameterAt(offset);5657return new CurveLocation(this, offset);5658},56595660getLocationOf: function(point) {5661var point = Point.read(arguments),5662t = this.getParameterOf(point);5663return t != null ? new CurveLocation(this, t) : null;5664},56655666getNearestLocation: function(point) {5667var point = Point.read(arguments),5668values = this.getValues(),5669count = 100,5670minDist = Infinity,5671minT = 0;56725673function refine(t) {5674if (t >= 0 && t <= 1) {5675var dist = point.getDistance(5676Curve.evaluate(values, t, 0), true);5677if (dist < minDist) {5678minDist = dist;5679minT = t;5680return true;5681}5682}5683}56845685for (var i = 0; i <= count; i++)5686refine(i / count);56875688var step = 1 / (count * 2);5689while (step > 0.00001) {5690if (!refine(minT - step) && !refine(minT + step))5691step /= 2;5692}5693var pt = Curve.evaluate(values, minT, 0);5694return new CurveLocation(this, minT, pt, null, null, null,5695point.getDistance(pt));5696},56975698getNearestPoint: function(point) {5699var point = Point.read(arguments);5700return this.getNearestLocation(point).getPoint();5701}57025703}),5704new function() {57055706function getLengthIntegrand(v) {5707var p1x = v[0], p1y = v[1],5708c1x = v[2], c1y = v[3],5709c2x = v[4], c2y = v[5],5710p2x = v[6], p2y = v[7],57115712ax = 9 * (c1x - c2x) + 3 * (p2x - p1x),5713bx = 6 * (p1x + c2x) - 12 * c1x,5714cx = 3 * (c1x - p1x),57155716ay = 9 * (c1y - c2y) + 3 * (p2y - p1y),5717by = 6 * (p1y + c2y) - 12 * c1y,5718cy = 3 * (c1y - p1y);57195720return function(t) {5721var dx = (ax * t + bx) * t + cx,5722dy = (ay * t + by) * t + cy;5723return Math.sqrt(dx * dx + dy * dy);5724};5725}57265727function getIterations(a, b) {5728return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));5729}57305731return {5732statics: true,57335734getLength: function(v, a, b) {5735if (a === undefined)5736a = 0;5737if (b === undefined)5738b = 1;5739var isZero = Numerical.isZero;5740if (a === 0 && b === 15741&& isZero(v[0] - v[2]) && isZero(v[1] - v[3])5742&& isZero(v[6] - v[4]) && isZero(v[7] - v[5])) {5743var dx = v[6] - v[0],5744dy = v[7] - v[1];5745return Math.sqrt(dx * dx + dy * dy);5746}5747var ds = getLengthIntegrand(v);5748return Numerical.integrate(ds, a, b, getIterations(a, b));5749},57505751getParameterAt: function(v, offset, start) {5752if (offset === 0)5753return start;5754var forward = offset > 0,5755a = forward ? start : 0,5756b = forward ? 1 : start,5757offset = Math.abs(offset),5758ds = getLengthIntegrand(v),5759rangeLength = Numerical.integrate(ds, a, b,5760getIterations(a, b));5761if (offset >= rangeLength)5762return forward ? b : a;5763var guess = offset / rangeLength,5764length = 0;5765function f(t) {5766var count = getIterations(start, t);5767length += start < t5768? Numerical.integrate(ds, start, t, count)5769: -Numerical.integrate(ds, t, start, count);5770start = t;5771return length - offset;5772}5773return Numerical.findRoot(f, ds,5774forward ? a + guess : b - guess,5775a, b, 16, 0.00001);5776}5777};5778}, new function() {5779function addLocation(locations, include, curve1, t1, point1, curve2, t2,5780point2) {5781var loc = new CurveLocation(curve1, t1, point1, curve2, t2, point2);5782if (!include || include(loc))5783locations.push(loc);5784}57855786function addCurveIntersections(v1, v2, curve1, curve2, locations, include,5787tMin, tMax, uMin, uMax, oldTDiff, reverse, recursion) {5788if (recursion > 20)5789return;5790var q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7],5791tolerance = 0.00001,5792hullEpsilon = 1e-9,5793getSignedDistance = Line.getSignedDistance,5794d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]) || 0,5795d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]) || 0,5796factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,5797dMin = factor * Math.min(0, d1, d2),5798dMax = factor * Math.max(0, d1, d2),5799dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]),5800dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]),5801dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]),5802dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]),5803tMinNew, tMaxNew, tDiff;5804if (q0x === q3x && uMax - uMin <= hullEpsilon && recursion > 3) {5805tMinNew = (tMax + tMin) / 2;5806tMaxNew = tMinNew;5807tDiff = 0;5808} else {5809var hull = getConvexHull(dp0, dp1, dp2, dp3),5810top = hull[0],5811bottom = hull[1],5812tMinClip, tMaxClip;5813tMinClip = clipConvexHull(top, bottom, dMin, dMax);5814top.reverse();5815bottom.reverse();5816tMaxClip = clipConvexHull(top, bottom, dMin, dMax);5817if (tMinClip == null || tMaxClip == null)5818return false;5819v1 = Curve.getPart(v1, tMinClip, tMaxClip);5820tDiff = tMaxClip - tMinClip;5821tMinNew = tMax * tMinClip + tMin * (1 - tMinClip);5822tMaxNew = tMax * tMaxClip + tMin * (1 - tMaxClip);5823}5824if (oldTDiff > 0.8 && tDiff > 0.8) {5825if (tMaxNew - tMinNew > uMax - uMin) {5826var parts = Curve.subdivide(v1, 0.5),5827t = tMinNew + (tMaxNew - tMinNew) / 2;5828addCurveIntersections(5829v2, parts[0], curve2, curve1, locations, include,5830uMin, uMax, tMinNew, t, tDiff, !reverse, ++recursion);5831addCurveIntersections(5832v2, parts[1], curve2, curve1, locations, include,5833uMin, uMax, t, tMaxNew, tDiff, !reverse, recursion);5834} else {5835var parts = Curve.subdivide(v2, 0.5),5836t = uMin + (uMax - uMin) / 2;5837addCurveIntersections(5838parts[0], v1, curve2, curve1, locations, include,5839uMin, t, tMinNew, tMaxNew, tDiff, !reverse, ++recursion);5840addCurveIntersections(5841parts[1], v1, curve2, curve1, locations, include,5842t, uMax, tMinNew, tMaxNew, tDiff, !reverse, recursion);5843}5844} else if (Math.max(uMax - uMin, tMaxNew - tMinNew) < tolerance) {5845var t1 = tMinNew + (tMaxNew - tMinNew) / 2,5846t2 = uMin + (uMax - uMin) / 2;5847if (reverse) {5848addLocation(locations, include,5849curve2, t2, Curve.evaluate(v2, t2, 0),5850curve1, t1, Curve.evaluate(v1, t1, 0));5851} else {5852addLocation(locations, include,5853curve1, t1, Curve.evaluate(v1, t1, 0),5854curve2, t2, Curve.evaluate(v2, t2, 0));5855}5856} else {5857addCurveIntersections(v2, v1, curve2, curve1, locations, include,5858uMin, uMax, tMinNew, tMaxNew, tDiff, !reverse, ++recursion);5859}5860}58615862function getConvexHull(dq0, dq1, dq2, dq3) {5863var p0 = [ 0, dq0 ],5864p1 = [ 1 / 3, dq1 ],5865p2 = [ 2 / 3, dq2 ],5866p3 = [ 1, dq3 ],5867getSignedDistance = Line.getSignedDistance,5868dist1 = getSignedDistance(0, dq0, 1, dq3, 1 / 3, dq1),5869dist2 = getSignedDistance(0, dq0, 1, dq3, 2 / 3, dq2),5870flip = false,5871hull;5872if (dist1 * dist2 < 0) {5873hull = [[p0, p1, p3], [p0, p2, p3]];5874flip = dist1 < 0;5875} else {5876var pmax, cross = 0,5877distZero = dist1 === 0 || dist2 === 0;5878if (Math.abs(dist1) > Math.abs(dist2)) {5879pmax = p1;5880cross = (dq3 - dq2 - (dq3 - dq0) / 3)5881* (2 * (dq3 - dq2) - dq3 + dq1) / 3;5882} else {5883pmax = p2;5884cross = (dq1 - dq0 + (dq0 - dq3) / 3)5885* (-2 * (dq0 - dq1) + dq0 - dq2) / 3;5886}5887hull = cross < 0 || distZero5888? [[p0, pmax, p3], [p0, p3]]5889: [[p0, p1, p2, p3], [p0, p3]];5890flip = dist1 ? dist1 < 0 : dist2 < 0;5891}5892return flip ? hull.reverse() : hull;5893}58945895function clipConvexHull(hullTop, hullBottom, dMin, dMax) {5896var tProxy,5897tVal = null,5898px, py,5899qx, qy;5900for (var i = 0, l = hullBottom.length - 1; i < l; i++) {5901py = hullBottom[i][1];5902qy = hullBottom[i + 1][1];5903if (py < qy) {5904tProxy = null;5905} else if (qy <= dMax) {5906px = hullBottom[i][0];5907qx = hullBottom[i + 1][0];5908tProxy = px + (dMax - py) * (qx - px) / (qy - py);5909} else {5910continue;5911}5912break;5913}5914if (hullTop[0][1] <= dMax)5915tProxy = hullTop[0][0];5916for (var i = 0, l = hullTop.length - 1; i < l; i++) {5917py = hullTop[i][1];5918qy = hullTop[i + 1][1];5919if (py >= dMin) {5920tVal = tProxy;5921} else if (py > qy) {5922tVal = null;5923} else if (qy >= dMin) {5924px = hullTop[i][0];5925qx = hullTop[i + 1][0];5926tVal = px + (dMin - py) * (qx - px) / (qy - py);5927} else {5928continue;5929}5930break;5931}5932return tVal;5933}59345935function addCurveLineIntersections(v1, v2, curve1, curve2, locations,5936include) {5937var flip = Curve.isLinear(v1),5938vc = flip ? v2 : v1,5939vl = flip ? v1 : v2,5940lx1 = vl[0], ly1 = vl[1],5941lx2 = vl[6], ly2 = vl[7],5942ldx = lx2 - lx1,5943ldy = ly2 - ly1,5944angle = Math.atan2(-ldy, ldx),5945sin = Math.sin(angle),5946cos = Math.cos(angle),5947rlx2 = ldx * cos - ldy * sin,5948rvl = [0, 0, 0, 0, rlx2, 0, rlx2, 0],5949rvc = [];5950for(var i = 0; i < 8; i += 2) {5951var x = vc[i] - lx1,5952y = vc[i + 1] - ly1;5953rvc.push(5954x * cos - y * sin,5955y * cos + x * sin);5956}5957var roots = [],5958count = Curve.solveCubic(rvc, 1, 0, roots, 0, 1);5959for (var i = 0; i < count; i++) {5960var tc = roots[i],5961x = Curve.evaluate(rvc, tc, 0).x;5962if (x >= 0 && x <= rlx2) {5963var tl = Curve.getParameterOf(rvl, x, 0),5964t1 = flip ? tl : tc,5965t2 = flip ? tc : tl;5966addLocation(locations, include,5967curve1, t1, Curve.evaluate(v1, t1, 0),5968curve2, t2, Curve.evaluate(v2, t2, 0));5969}5970}5971}59725973function addLineIntersection(v1, v2, curve1, curve2, locations, include) {5974var point = Line.intersect(5975v1[0], v1[1], v1[6], v1[7],5976v2[0], v2[1], v2[6], v2[7]);5977if (point) {5978var x = point.x,5979y = point.y;5980addLocation(locations, include,5981curve1, Curve.getParameterOf(v1, x, y), point,5982curve2, Curve.getParameterOf(v2, x, y), point);5983}5984}59855986return { statics: {5987getIntersections: function(v1, v2, curve1, curve2, locations, include) {5988var linear1 = Curve.isLinear(v1),5989linear2 = Curve.isLinear(v2);5990(linear1 && linear25991? addLineIntersection5992: linear1 || linear25993? addCurveLineIntersections5994: addCurveIntersections)(5995v1, v2, curve1, curve2, locations, include,59960, 1, 0, 1, 0, false, 0);5997return locations;5998}5999}};6000});60016002var CurveLocation = Base.extend({6003_class: 'CurveLocation',6004beans: true,60056006initialize: function CurveLocation(curve, parameter, point, _curve2,6007_parameter2, _point2, _distance) {6008this._id = CurveLocation._id = (CurveLocation._id || 0) + 1;6009this._curve = curve;6010this._segment1 = curve._segment1;6011this._segment2 = curve._segment2;6012this._parameter = parameter;6013this._point = point;6014this._curve2 = _curve2;6015this._parameter2 = _parameter2;6016this._point2 = _point2;6017this._distance = _distance;6018},60196020getSegment: function(_preferFirst) {6021if (!this._segment) {6022var curve = this.getCurve(),6023parameter = this.getParameter();6024if (parameter === 1) {6025this._segment = curve._segment2;6026} else if (parameter === 0 || _preferFirst) {6027this._segment = curve._segment1;6028} else if (parameter == null) {6029return null;6030} else {6031this._segment = curve.getPartLength(0, parameter)6032< curve.getPartLength(parameter, 1)6033? curve._segment16034: curve._segment2;6035}6036}6037return this._segment;6038},60396040getCurve: function(_uncached) {6041if (!this._curve || _uncached) {6042this._curve = this._segment1.getCurve();6043if (this._curve.getParameterOf(this._point) == null)6044this._curve = this._segment2.getPrevious().getCurve();6045}6046return this._curve;6047},60486049getIntersection: function() {6050var intersection = this._intersection;6051if (!intersection && this._curve2) {6052var param = this._parameter2;6053this._intersection = intersection = new CurveLocation(6054this._curve2, param, this._point2 || this._point, this);6055intersection._intersection = this;6056}6057return intersection;6058},60596060getPath: function() {6061var curve = this.getCurve();6062return curve && curve._path;6063},60646065getIndex: function() {6066var curve = this.getCurve();6067return curve && curve.getIndex();6068},60696070getOffset: function() {6071var path = this.getPath();6072return path && path._getOffset(this);6073},60746075getCurveOffset: function() {6076var curve = this.getCurve(),6077parameter = this.getParameter();6078return parameter != null && curve && curve.getPartLength(0, parameter);6079},60806081getParameter: function(_uncached) {6082if ((this._parameter == null || _uncached) && this._point) {6083var curve = this.getCurve(_uncached && this._point);6084this._parameter = curve && curve.getParameterOf(this._point);6085}6086return this._parameter;6087},60886089getPoint: function(_uncached) {6090if ((!this._point || _uncached) && this._parameter != null) {6091var curve = this.getCurve();6092this._point = curve && curve.getPointAt(this._parameter, true);6093}6094return this._point;6095},60966097getTangent: function() {6098var parameter = this.getParameter(),6099curve = this.getCurve();6100return parameter != null && curve && curve.getTangentAt(parameter, true);6101},61026103getNormal: function() {6104var parameter = this.getParameter(),6105curve = this.getCurve();6106return parameter != null && curve && curve.getNormalAt(parameter, true);6107},61086109getDistance: function() {6110return this._distance;6111},61126113divide: function() {6114var curve = this.getCurve(true);6115return curve && curve.divide(this.getParameter(true), true);6116},61176118split: function() {6119var curve = this.getCurve(true);6120return curve && curve.split(this.getParameter(true), true);6121},61226123equals: function(loc) {6124var isZero = Numerical.isZero;6125return this === loc6126|| loc6127&& this._curve === loc._curve6128&& this._curve2 === loc._curve26129&& isZero(this._parameter - loc._parameter)6130&& isZero(this._parameter2 - loc._parameter2)6131|| false;6132},61336134toString: function() {6135var parts = [],6136point = this.getPoint(),6137f = Formatter.instance;6138if (point)6139parts.push('point: ' + point);6140var index = this.getIndex();6141if (index != null)6142parts.push('index: ' + index);6143var parameter = this.getParameter();6144if (parameter != null)6145parts.push('parameter: ' + f.number(parameter));6146if (this._distance != null)6147parts.push('distance: ' + f.number(this._distance));6148return '{ ' + parts.join(', ') + ' }';6149}6150});61516152var PathItem = Item.extend({6153_class: 'PathItem',61546155initialize: function PathItem() {6156},61576158getIntersections: function(path, _expand) {6159if (this === path)6160path = null;6161if (path && !this.getBounds().touches(path.getBounds()))6162return [];6163var locations = [],6164curves1 = this.getCurves(),6165curves2 = path ? path.getCurves() : curves1,6166matrix1 = this._matrix.orNullIfIdentity(),6167matrix2 = path ? path._matrix.orNullIfIdentity() : matrix1,6168length1 = curves1.length,6169length2 = path ? curves2.length : length1,6170values2 = [],6171MIN = 1e-11,6172MAX = 1 - 1e-11;6173for (var i = 0; i < length2; i++)6174values2[i] = curves2[i].getValues(matrix2);6175for (var i = 0; i < length1; i++) {6176var curve1 = curves1[i],6177values1 = path ? curve1.getValues(matrix1) : values2[i];6178if (!path) {6179var seg1 = curve1.getSegment1(),6180seg2 = curve1.getSegment2(),6181h1 = seg1._handleOut,6182h2 = seg2._handleIn;6183if (new Line(seg1._point.subtract(h1), h1.multiply(2), true)6184.intersect(new Line(seg2._point.subtract(h2),6185h2.multiply(2), true), false)) {6186var parts = Curve.subdivide(values1);6187Curve.getIntersections(6188parts[0], parts[1], curve1, curve1, locations,6189function(loc) {6190if (loc._parameter <= MAX) {6191loc._parameter /= 2;6192loc._parameter2 = 0.5 + loc._parameter2 / 2;6193return true;6194}6195}6196);6197}6198}6199for (var j = path ? 0 : i + 1; j < length2; j++) {6200Curve.getIntersections(6201values1, values2[j], curve1, curves2[j], locations,6202!path && (j === i + 1 || j === length2 - 1 && i === 0)6203&& function(loc) {6204var t = loc._parameter;6205return t >= MIN && t <= MAX;6206}6207);6208}6209}6210var last = locations.length - 1;6211for (var i = last; i >= 0; i--) {6212var loc = locations[i],6213next = loc._curve.getNext(),6214next2 = loc._curve2.getNext();6215if (next && loc._parameter >= MAX) {6216loc._parameter = 0;6217loc._curve = next;6218}6219if (next2 && loc._parameter2 >= MAX) {6220loc._parameter2 = 0;6221loc._curve2 = next2;6222}6223}62246225function compare(loc1, loc2) {6226var path1 = loc1.getPath(),6227path2 = loc2.getPath();6228return path1 === path26229? (loc1.getIndex() + loc1.getParameter())6230- (loc2.getIndex() + loc2.getParameter())6231: path1._id - path2._id;6232}62336234if (last > 0) {6235locations.sort(compare);6236for (var i = last; i >= 0; i--) {6237if (locations[i].equals(locations[i === 0 ? last : i - 1])) {6238locations.splice(i, 1);6239last--;6240}6241}6242}6243if (_expand) {6244for (var i = last; i >= 0; i--)6245locations.push(locations[i].getIntersection());6246locations.sort(compare);6247}6248return locations;6249},62506251setPathData: function(data) {62526253var parts = data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),6254coords,6255relative = false,6256previous,6257control,6258current = new Point(),6259start = new Point();62606261function getCoord(index, coord) {6262var val = +coords[index];6263if (relative)6264val += current[coord];6265return val;6266}62676268function getPoint(index) {6269return new Point(6270getCoord(index, 'x'),6271getCoord(index + 1, 'y')6272);6273}62746275this.clear();62766277for (var i = 0, l = parts.length; i < l; i++) {6278var part = parts[i],6279command = part[0],6280lower = command.toLowerCase();6281coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);6282var length = coords && coords.length;6283relative = command === lower;6284if (previous === 'z' && !/[mz]/.test(lower))6285this.moveTo(current = start);6286switch (lower) {6287case 'm':6288case 'l':6289var move = lower === 'm';6290if (move && previous && previous !== 'z')6291this.closePath(true);6292for (var j = 0; j < length; j += 2)6293this[j === 0 && move ? 'moveTo' : 'lineTo'](6294current = getPoint(j));6295control = current;6296if (move)6297start = current;6298break;6299case 'h':6300case 'v':6301var coord = lower === 'h' ? 'x' : 'y';6302for (var j = 0; j < length; j++) {6303current[coord] = getCoord(j, coord);6304this.lineTo(current);6305}6306control = current;6307break;6308case 'c':6309for (var j = 0; j < length; j += 6) {6310this.cubicCurveTo(6311getPoint(j),6312control = getPoint(j + 2),6313current = getPoint(j + 4));6314}6315break;6316case 's':6317for (var j = 0; j < length; j += 4) {6318this.cubicCurveTo(6319/[cs]/.test(previous)6320? current.multiply(2).subtract(control)6321: current,6322control = getPoint(j),6323current = getPoint(j + 2));6324previous = lower;6325}6326break;6327case 'q':6328for (var j = 0; j < length; j += 4) {6329this.quadraticCurveTo(6330control = getPoint(j),6331current = getPoint(j + 2));6332}6333break;6334case 't':6335for (var j = 0; j < length; j += 2) {6336this.quadraticCurveTo(6337control = (/[qt]/.test(previous)6338? current.multiply(2).subtract(control)6339: current),6340current = getPoint(j));6341previous = lower;6342}6343break;6344case 'a':6345for (var j = 0; j < length; j += 7) {6346this.arcTo(current = getPoint(j + 5),6347new Size(+coords[0], +coords[1]),6348+coords[2], +coords[4], +coords[3]);6349}6350break;6351case 'z':6352this.closePath(true);6353break;6354}6355previous = lower;6356}6357},63586359_canComposite: function() {6360return !(this.hasFill() && this.hasStroke());6361},63626363_contains: function(point) {6364var winding = this._getWinding(point, false, true);6365return !!(this.getWindingRule() === 'evenodd' ? winding & 1 : winding);6366}63676368});63696370var Path = PathItem.extend({6371_class: 'Path',6372_serializeFields: {6373segments: [],6374closed: false6375},63766377initialize: function Path(arg) {6378this._closed = false;6379this._segments = [];6380var segments = Array.isArray(arg)6381? typeof arg[0] === 'object'6382? arg6383: arguments6384: arg && (arg.size === undefined && (arg.x !== undefined6385|| arg.point !== undefined))6386? arguments6387: null;6388if (segments && segments.length > 0) {6389this.setSegments(segments);6390} else {6391this._curves = undefined;6392this._selectedSegmentState = 0;6393if (!segments && typeof arg === 'string') {6394this.setPathData(arg);6395arg = null;6396}6397}6398this._initialize(!segments && arg);6399},64006401_equals: function(item) {6402return Base.equals(this._segments, item._segments);6403},64046405clone: function(insert) {6406var copy = new Path(Item.NO_INSERT);6407copy.setSegments(this._segments);6408copy._closed = this._closed;6409if (this._clockwise !== undefined)6410copy._clockwise = this._clockwise;6411return this._clone(copy, insert);6412},64136414_changed: function _changed(flags) {6415_changed.base.call(this, flags);6416if (flags & 8) {6417var parent = this._parent;6418if (parent)6419parent._currentPath = undefined;6420this._length = this._clockwise = undefined;6421if (this._curves && !(flags & 16)) {6422for (var i = 0, l = this._curves.length; i < l; i++)6423this._curves[i]._changed();6424}6425this._monoCurves = undefined;6426} else if (flags & 32) {6427this._bounds = undefined;6428}6429},64306431getStyle: function() {6432var parent = this._parent;6433return (parent instanceof CompoundPath ? parent : this)._style;6434},64356436getSegments: function() {6437return this._segments;6438},64396440setSegments: function(segments) {6441var fullySelected = this.isFullySelected();6442this._segments.length = 0;6443this._selectedSegmentState = 0;6444this._curves = undefined;6445if (segments && segments.length > 0)6446this._add(Segment.readAll(segments));6447if (fullySelected)6448this.setFullySelected(true);6449},64506451getFirstSegment: function() {6452return this._segments[0];6453},64546455getLastSegment: function() {6456return this._segments[this._segments.length - 1];6457},64586459getCurves: function() {6460var curves = this._curves,6461segments = this._segments;6462if (!curves) {6463var length = this._countCurves();6464curves = this._curves = new Array(length);6465for (var i = 0; i < length; i++)6466curves[i] = new Curve(this, segments[i],6467segments[i + 1] || segments[0]);6468}6469return curves;6470},64716472getFirstCurve: function() {6473return this.getCurves()[0];6474},64756476getLastCurve: function() {6477var curves = this.getCurves();6478return curves[curves.length - 1];6479},64806481isClosed: function() {6482return this._closed;6483},64846485setClosed: function(closed) {6486if (this._closed != (closed = !!closed)) {6487this._closed = closed;6488if (this._curves) {6489var length = this._curves.length = this._countCurves();6490if (closed)6491this._curves[length - 1] = new Curve(this,6492this._segments[length - 1], this._segments[0]);6493}6494this._changed(25);6495}6496}6497}, {6498beans: true,64996500getPathData: function(_precision) {6501var segments = this._segments,6502f = Formatter.instance,6503parts = [];65046505function addCurve(seg1, seg2, skipLine) {6506var point1 = seg1._point,6507point2 = seg2._point,6508handle1 = seg1._handleOut,6509handle2 = seg2._handleIn;6510if (handle1.isZero() && handle2.isZero()) {6511if (!skipLine) {6512parts.push('L' + f.point(point2, _precision));6513}6514} else {6515var end = point2.subtract(point1);6516parts.push('c' + f.point(handle1, _precision)6517+ ' ' + f.point(end.add(handle2), _precision)6518+ ' ' + f.point(end, _precision));6519}6520}65216522if (segments.length === 0)6523return '';6524parts.push('M' + f.point(segments[0]._point));6525for (var i = 0, l = segments.length - 1; i < l; i++)6526addCurve(segments[i], segments[i + 1], false);6527if (this._closed) {6528addCurve(segments[segments.length - 1], segments[0], true);6529parts.push('z');6530}6531return parts.join('');6532}6533}, {65346535isEmpty: function() {6536return this._segments.length === 0;6537},65386539isPolygon: function() {6540for (var i = 0, l = this._segments.length; i < l; i++) {6541if (!this._segments[i].isLinear())6542return false;6543}6544return true;6545},65466547_transformContent: function(matrix) {6548var coords = new Array(6);6549for (var i = 0, l = this._segments.length; i < l; i++)6550this._segments[i]._transformCoordinates(matrix, coords, true);6551return true;6552},65536554_add: function(segs, index) {6555var segments = this._segments,6556curves = this._curves,6557amount = segs.length,6558append = index == null,6559index = append ? segments.length : index;6560for (var i = 0; i < amount; i++) {6561var segment = segs[i];6562if (segment._path)6563segment = segs[i] = segment.clone();6564segment._path = this;6565segment._index = index + i;6566if (segment._selectionState)6567this._updateSelection(segment, 0, segment._selectionState);6568}6569if (append) {6570segments.push.apply(segments, segs);6571} else {6572segments.splice.apply(segments, [index, 0].concat(segs));6573for (var i = index + amount, l = segments.length; i < l; i++)6574segments[i]._index = i;6575}6576if (curves || segs._curves) {6577if (!curves)6578curves = this._curves = [];6579var from = index > 0 ? index - 1 : index,6580start = from,6581to = Math.min(from + amount, this._countCurves());6582if (segs._curves) {6583curves.splice.apply(curves, [from, 0].concat(segs._curves));6584start += segs._curves.length;6585}6586for (var i = start; i < to; i++)6587curves.splice(i, 0, new Curve(this, null, null));6588this._adjustCurves(from, to);6589}6590this._changed(25);6591return segs;6592},65936594_adjustCurves: function(from, to) {6595var segments = this._segments,6596curves = this._curves,6597curve;6598for (var i = from; i < to; i++) {6599curve = curves[i];6600curve._path = this;6601curve._segment1 = segments[i];6602curve._segment2 = segments[i + 1] || segments[0];6603}6604if (curve = curves[this._closed && from === 0 ? segments.length - 16605: from - 1])6606curve._segment2 = segments[from] || segments[0];6607if (curve = curves[to])6608curve._segment1 = segments[to];6609},66106611_countCurves: function() {6612var length = this._segments.length;6613return !this._closed && length > 0 ? length - 1 : length;6614},66156616add: function(segment1 ) {6617return arguments.length > 1 && typeof segment1 !== 'number'6618? this._add(Segment.readAll(arguments))6619: this._add([ Segment.read(arguments) ])[0];6620},66216622insert: function(index, segment1 ) {6623return arguments.length > 2 && typeof segment1 !== 'number'6624? this._add(Segment.readAll(arguments, 1), index)6625: this._add([ Segment.read(arguments, 1) ], index)[0];6626},66276628addSegment: function() {6629return this._add([ Segment.read(arguments) ])[0];6630},66316632insertSegment: function(index ) {6633return this._add([ Segment.read(arguments, 1) ], index)[0];6634},66356636addSegments: function(segments) {6637return this._add(Segment.readAll(segments));6638},66396640insertSegments: function(index, segments) {6641return this._add(Segment.readAll(segments), index);6642},66436644removeSegment: function(index) {6645return this.removeSegments(index, index + 1)[0] || null;6646},66476648removeSegments: function(from, to, _includeCurves) {6649from = from || 0;6650to = Base.pick(to, this._segments.length);6651var segments = this._segments,6652curves = this._curves,6653count = segments.length,6654removed = segments.splice(from, to - from),6655amount = removed.length;6656if (!amount)6657return removed;6658for (var i = 0; i < amount; i++) {6659var segment = removed[i];6660if (segment._selectionState)6661this._updateSelection(segment, segment._selectionState, 0);6662segment._index = segment._path = null;6663}6664for (var i = from, l = segments.length; i < l; i++)6665segments[i]._index = i;6666if (curves) {6667var index = from > 0 && to === count + (this._closed ? 1 : 0)6668? from - 16669: from,6670curves = curves.splice(index, amount);6671if (_includeCurves)6672removed._curves = curves.slice(1);6673this._adjustCurves(index, index);6674}6675this._changed(25);6676return removed;6677},66786679clear: '#removeSegments',66806681isFullySelected: function() {6682var length = this._segments.length;6683return this._selected && length > 0 && this._selectedSegmentState6684=== length * 7;6685},66866687setFullySelected: function(selected) {6688if (selected)6689this._selectSegments(true);6690this.setSelected(selected);6691},66926693setSelected: function setSelected(selected) {6694if (!selected)6695this._selectSegments(false);6696setSelected.base.call(this, selected);6697},66986699_selectSegments: function(selected) {6700var length = this._segments.length;6701this._selectedSegmentState = selected6702? length * 7 : 0;6703for (var i = 0; i < length; i++)6704this._segments[i]._selectionState = selected6705? 7 : 0;6706},67076708_updateSelection: function(segment, oldState, newState) {6709segment._selectionState = newState;6710var total = this._selectedSegmentState += newState - oldState;6711if (total > 0)6712this.setSelected(true);6713},67146715flatten: function(maxDistance) {6716var flattener = new PathFlattener(this),6717pos = 0,6718step = flattener.length / Math.ceil(flattener.length / maxDistance),6719end = flattener.length + (this._closed ? -step : step) / 2;6720var segments = [];6721while (pos <= end) {6722segments.push(new Segment(flattener.evaluate(pos, 0)));6723pos += step;6724}6725this.setSegments(segments);6726},67276728reduce: function() {6729var curves = this.getCurves();6730for (var i = curves.length - 1; i >= 0; i--) {6731var curve = curves[i];6732if (curve.isLinear() && curve.getLength() === 0)6733curve.remove();6734}6735return this;6736},67376738simplify: function(tolerance) {6739if (this._segments.length > 2) {6740var fitter = new PathFitter(this, tolerance || 2.5);6741this.setSegments(fitter.fit());6742}6743},67446745split: function(index, parameter) {6746if (parameter === null)6747return;6748if (arguments.length === 1) {6749var arg = index;6750if (typeof arg === 'number')6751arg = this.getLocationAt(arg);6752index = arg.index;6753parameter = arg.parameter;6754}6755var tolerance = 0.00001;6756if (parameter >= 1 - tolerance) {6757index++;6758parameter--;6759}6760var curves = this.getCurves();6761if (index >= 0 && index < curves.length) {6762if (parameter > tolerance) {6763curves[index++].divide(parameter, true);6764}6765var segs = this.removeSegments(index, this._segments.length, true),6766path;6767if (this._closed) {6768this.setClosed(false);6769path = this;6770} else if (index > 0) {6771path = this._clone(new Path().insertAbove(this, true));6772}6773path._add(segs, 0);6774this.addSegment(segs[0]);6775return path;6776}6777return null;6778},67796780isClockwise: function() {6781if (this._clockwise !== undefined)6782return this._clockwise;6783return Path.isClockwise(this._segments);6784},67856786setClockwise: function(clockwise) {6787if (this.isClockwise() != (clockwise = !!clockwise))6788this.reverse();6789this._clockwise = clockwise;6790},67916792reverse: function() {6793this._segments.reverse();6794for (var i = 0, l = this._segments.length; i < l; i++) {6795var segment = this._segments[i];6796var handleIn = segment._handleIn;6797segment._handleIn = segment._handleOut;6798segment._handleOut = handleIn;6799segment._index = i;6800}6801this._curves = null;6802if (this._clockwise !== undefined)6803this._clockwise = !this._clockwise;6804},68056806join: function(path) {6807if (path) {6808var segments = path._segments,6809last1 = this.getLastSegment(),6810last2 = path.getLastSegment();6811if (last1._point.equals(last2._point))6812path.reverse();6813var first1,6814first2 = path.getFirstSegment();6815if (last1._point.equals(first2._point)) {6816last1.setHandleOut(first2._handleOut);6817this._add(segments.slice(1));6818} else {6819first1 = this.getFirstSegment();6820if (first1._point.equals(first2._point))6821path.reverse();6822last2 = path.getLastSegment();6823if (first1._point.equals(last2._point)) {6824first1.setHandleIn(last2._handleIn);6825this._add(segments.slice(0, segments.length - 1), 0);6826} else {6827this._add(segments.slice());6828}6829}6830if (path.closed)6831this._add([segments[0]]);6832path.remove();6833}6834var first = this.getFirstSegment(),6835last = this.getLastSegment();6836if (first !== last && first._point.equals(last._point)) {6837first.setHandleIn(last._handleIn);6838last.remove();6839this.setClosed(true);6840}6841},68426843getLength: function() {6844if (this._length == null) {6845var curves = this.getCurves();6846this._length = 0;6847for (var i = 0, l = curves.length; i < l; i++)6848this._length += curves[i].getLength();6849}6850return this._length;6851},68526853getArea: function() {6854var curves = this.getCurves();6855var area = 0;6856for (var i = 0, l = curves.length; i < l; i++)6857area += curves[i].getArea();6858return area;6859},68606861_getOffset: function(location) {6862var index = location && location.getIndex();6863if (index != null) {6864var curves = this.getCurves(),6865offset = 0;6866for (var i = 0; i < index; i++)6867offset += curves[i].getLength();6868var curve = curves[index],6869parameter = location.getParameter();6870if (parameter > 0)6871offset += curve.getPartLength(0, parameter);6872return offset;6873}6874return null;6875},68766877getLocationOf: function(point) {6878var point = Point.read(arguments),6879curves = this.getCurves();6880for (var i = 0, l = curves.length; i < l; i++) {6881var loc = curves[i].getLocationOf(point);6882if (loc)6883return loc;6884}6885return null;6886},68876888getLocationAt: function(offset, isParameter) {6889var curves = this.getCurves(),6890length = 0;6891if (isParameter) {6892var index = ~~offset;6893return curves[index].getLocationAt(offset - index, true);6894}6895for (var i = 0, l = curves.length; i < l; i++) {6896var start = length,6897curve = curves[i];6898length += curve.getLength();6899if (length > offset) {6900return curve.getLocationAt(offset - start);6901}6902}6903if (offset <= this.getLength())6904return new CurveLocation(curves[curves.length - 1], 1);6905return null;6906},69076908getPointAt: function(offset, isParameter) {6909var loc = this.getLocationAt(offset, isParameter);6910return loc && loc.getPoint();6911},69126913getTangentAt: function(offset, isParameter) {6914var loc = this.getLocationAt(offset, isParameter);6915return loc && loc.getTangent();6916},69176918getNormalAt: function(offset, isParameter) {6919var loc = this.getLocationAt(offset, isParameter);6920return loc && loc.getNormal();6921},69226923getNearestLocation: function(point) {6924var point = Point.read(arguments),6925curves = this.getCurves(),6926minDist = Infinity,6927minLoc = null;6928for (var i = 0, l = curves.length; i < l; i++) {6929var loc = curves[i].getNearestLocation(point);6930if (loc._distance < minDist) {6931minDist = loc._distance;6932minLoc = loc;6933}6934}6935return minLoc;6936},69376938getNearestPoint: function(point) {6939var point = Point.read(arguments);6940return this.getNearestLocation(point).getPoint();6941},69426943toShape: function(insert) {6944if (!this._closed)6945return null;69466947var segments = this._segments,6948type,6949size,6950radius,6951topCenter;69526953function isColinear(i, j) {6954return segments[i].isColinear(segments[j]);6955}69566957function isOrthogonal(i) {6958return segments[i].isOrthogonal();6959}69606961function isArc(i) {6962return segments[i].isArc();6963}69646965function getDistance(i, j) {6966return segments[i]._point.getDistance(segments[j]._point);6967}69686969if (this.isPolygon() && segments.length === 46970&& isColinear(0, 2) && isColinear(1, 3) && isOrthogonal(1)) {6971type = Shape.Rectangle;6972size = new Size(getDistance(0, 3), getDistance(0, 1));6973topCenter = segments[1]._point.add(segments[2]._point).divide(2);6974} else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)6975&& isArc(6) && isColinear(1, 5) && isColinear(3, 7)) {6976type = Shape.Rectangle;6977size = new Size(getDistance(1, 6), getDistance(0, 3));6978radius = size.subtract(new Size(getDistance(0, 7),6979getDistance(1, 2))).divide(2);6980topCenter = segments[3]._point.add(segments[4]._point).divide(2);6981} else if (segments.length === 46982&& isArc(0) && isArc(1) && isArc(2) && isArc(3)) {6983if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {6984type = Shape.Circle;6985radius = getDistance(0, 2) / 2;6986} else {6987type = Shape.Ellipse;6988radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);6989}6990topCenter = segments[1]._point;6991}69926993if (type) {6994var center = this.getPosition(true),6995shape = new type({6996center: center,6997size: size,6998radius: radius,6999insert: false7000});7001shape.rotate(topCenter.subtract(center).getAngle() + 90);7002shape.setStyle(this._style);7003if (insert || insert === undefined)7004shape.insertAbove(this);7005return shape;7006}7007return null;7008},70097010_hitTest: function(point, options) {7011var that = this,7012style = this.getStyle(),7013segments = this._segments,7014numSegments = segments.length,7015closed = this._closed,7016tolerancePadding = options._tolerancePadding,7017strokePadding = tolerancePadding,7018join, cap, miterLimit,7019area, loc, res,7020hasStroke = options.stroke && style.hasStroke(),7021hasFill = options.fill && style.hasFill(),7022radius = hasStroke ? style.getStrokeWidth() / 27023: hasFill ? 0 : null;7024if (radius != null) {7025if (radius > 0) {7026join = style.getStrokeJoin();7027cap = style.getStrokeCap();7028miterLimit = radius * style.getMiterLimit();7029strokePadding = tolerancePadding.add(new Point(radius, radius));7030} else {7031join = cap = 'round';7032}7033}70347035function isCloseEnough(pt, padding) {7036return point.subtract(pt).divide(padding).length <= 1;7037}70387039function checkSegmentPoint(seg, pt, name) {7040if (!options.selected || pt.isSelected()) {7041var anchor = seg._point;7042if (pt !== anchor)7043pt = pt.add(anchor);7044if (isCloseEnough(pt, strokePadding)) {7045return new HitResult(name, that, {7046segment: seg,7047point: pt7048});7049}7050}7051}70527053function checkSegmentPoints(seg, ends) {7054return (ends || options.segments)7055&& checkSegmentPoint(seg, seg._point, 'segment')7056|| (!ends && options.handles) && (7057checkSegmentPoint(seg, seg._handleIn, 'handle-in') ||7058checkSegmentPoint(seg, seg._handleOut, 'handle-out'));7059}70607061function addToArea(point) {7062area.add(point);7063}70647065function checkSegmentStroke(segment) {7066if (join !== 'round' || cap !== 'round') {7067area = new Path({ internal: true, closed: true });7068if (closed || segment._index > 07069&& segment._index < numSegments - 1) {7070if (join !== 'round' && (segment._handleIn.isZero()7071|| segment._handleOut.isZero()))7072Path._addBevelJoin(segment, join, radius, miterLimit,7073addToArea, true);7074} else if (cap !== 'round') {7075Path._addSquareCap(segment, cap, radius, addToArea, true);7076}7077if (!area.isEmpty()) {7078var loc;7079return area.contains(point)7080|| (loc = area.getNearestLocation(point))7081&& isCloseEnough(loc.getPoint(), tolerancePadding);7082}7083}7084return isCloseEnough(segment._point, strokePadding);7085}70867087if (options.ends && !options.segments && !closed) {7088if (res = checkSegmentPoints(segments[0], true)7089|| checkSegmentPoints(segments[numSegments - 1], true))7090return res;7091} else if (options.segments || options.handles) {7092for (var i = 0; i < numSegments; i++)7093if (res = checkSegmentPoints(segments[i]))7094return res;7095}7096if (radius != null) {7097loc = this.getNearestLocation(point);7098if (loc) {7099var parameter = loc.getParameter();7100if (parameter === 0 || parameter === 1 && numSegments > 1) {7101if (!checkSegmentStroke(loc.getSegment()))7102loc = null;7103} else if (!isCloseEnough(loc.getPoint(), strokePadding)) {7104loc = null;7105}7106}7107if (!loc && join === 'miter' && numSegments > 1) {7108for (var i = 0; i < numSegments; i++) {7109var segment = segments[i];7110if (point.getDistance(segment._point) <= miterLimit7111&& checkSegmentStroke(segment)) {7112loc = segment.getLocation();7113break;7114}7115}7116}7117}7118return !loc && hasFill && this._contains(point) || loc && !hasStroke7119? new HitResult('fill', this)7120: loc7121? new HitResult('stroke', this, {7122location: loc,7123point: loc.getPoint()7124})7125: null;7126}71277128}, new function() {71297130function drawHandles(ctx, segments, matrix, size) {7131var half = size / 2;71327133function drawHandle(index) {7134var hX = coords[index],7135hY = coords[index + 1];7136if (pX != hX || pY != hY) {7137ctx.beginPath();7138ctx.moveTo(pX, pY);7139ctx.lineTo(hX, hY);7140ctx.stroke();7141ctx.beginPath();7142ctx.arc(hX, hY, half, 0, Math.PI * 2, true);7143ctx.fill();7144}7145}71467147var coords = new Array(6);7148for (var i = 0, l = segments.length; i < l; i++) {7149var segment = segments[i];7150segment._transformCoordinates(matrix, coords, false);7151var state = segment._selectionState,7152pX = coords[0],7153pY = coords[1];7154if (state & 1)7155drawHandle(2);7156if (state & 2)7157drawHandle(4);7158ctx.fillRect(pX - half, pY - half, size, size);7159if (!(state & 4)) {7160var fillStyle = ctx.fillStyle;7161ctx.fillStyle = '#ffffff';7162ctx.fillRect(pX - half + 1, pY - half + 1, size - 2, size - 2);7163ctx.fillStyle = fillStyle;7164}7165}7166}71677168function drawSegments(ctx, path, matrix) {7169var segments = path._segments,7170length = segments.length,7171coords = new Array(6),7172first = true,7173curX, curY,7174prevX, prevY,7175inX, inY,7176outX, outY;71777178function drawSegment(i) {7179var segment = segments[i];7180if (matrix) {7181segment._transformCoordinates(matrix, coords, false);7182curX = coords[0];7183curY = coords[1];7184} else {7185var point = segment._point;7186curX = point._x;7187curY = point._y;7188}7189if (first) {7190ctx.moveTo(curX, curY);7191first = false;7192} else {7193if (matrix) {7194inX = coords[2];7195inY = coords[3];7196} else {7197var handle = segment._handleIn;7198inX = curX + handle._x;7199inY = curY + handle._y;7200}7201if (inX == curX && inY == curY && outX == prevX && outY == prevY) {7202ctx.lineTo(curX, curY);7203} else {7204ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);7205}7206}7207prevX = curX;7208prevY = curY;7209if (matrix) {7210outX = coords[4];7211outY = coords[5];7212} else {7213var handle = segment._handleOut;7214outX = prevX + handle._x;7215outY = prevY + handle._y;7216}7217}72187219for (var i = 0; i < length; i++)7220drawSegment(i);7221if (path._closed && length > 0)7222drawSegment(0);7223}72247225return {7226_draw: function(ctx, param) {7227var dontStart = param.dontStart,7228dontPaint = param.dontFinish || param.clip;7229if (!dontStart)7230ctx.beginPath();72317232var style = this.getStyle(),7233hasFill = style.hasFill(),7234hasStroke = style.hasStroke(),7235dashArray = style.getDashArray(),7236dashLength = !paper.support.nativeDash && hasStroke7237&& dashArray && dashArray.length;72387239function getOffset(i) {7240return dashArray[((i % dashLength) + dashLength) % dashLength];7241}72427243if (!dontStart && this._currentPath) {7244ctx.currentPath = this._currentPath;7245} else if (hasFill || hasStroke && !dashLength || dontPaint) {7246drawSegments(ctx, this);7247if (this._closed)7248ctx.closePath();7249if (!dontStart)7250this._currentPath = ctx.currentPath;7251}72527253if (!dontPaint && (hasFill || hasStroke)) {7254this._setStyles(ctx);7255if (hasFill) {7256ctx.fill(style.getWindingRule());7257ctx.shadowColor = 'rgba(0,0,0,0)';7258}7259if (hasStroke) {7260if (dashLength) {7261if (!dontStart)7262ctx.beginPath();7263var flattener = new PathFlattener(this),7264length = flattener.length,7265from = -style.getDashOffset(), to,7266i = 0;7267from = from % length;7268while (from > 0) {7269from -= getOffset(i--) + getOffset(i--);7270}7271while (from < length) {7272to = from + getOffset(i++);7273if (from > 0 || to > 0)7274flattener.drawPart(ctx,7275Math.max(from, 0), Math.max(to, 0));7276from = to + getOffset(i++);7277}7278}7279ctx.stroke();7280}7281}7282},72837284_drawSelected: function(ctx, matrix) {7285ctx.beginPath();7286drawSegments(ctx, this, matrix);7287ctx.stroke();7288drawHandles(ctx, this._segments, matrix, paper.settings.handleSize);7289}7290};7291}, new function() {72927293function getFirstControlPoints(rhs) {7294var n = rhs.length,7295x = [],7296tmp = [],7297b = 2;7298x[0] = rhs[0] / b;7299for (var i = 1; i < n; i++) {7300tmp[i] = 1 / b;7301b = (i < n - 1 ? 4 : 2) - tmp[i];7302x[i] = (rhs[i] - x[i - 1]) / b;7303}7304for (var i = 1; i < n; i++) {7305x[n - i - 1] -= tmp[n - i] * x[n - i];7306}7307return x;7308}73097310return {7311smooth: function() {7312var segments = this._segments,7313size = segments.length,7314closed = this._closed,7315n = size,7316overlap = 0;7317if (size <= 2)7318return;7319if (closed) {7320overlap = Math.min(size, 4);7321n += Math.min(size, overlap) * 2;7322}7323var knots = [];7324for (var i = 0; i < size; i++)7325knots[i + overlap] = segments[i]._point;7326if (closed) {7327for (var i = 0; i < overlap; i++) {7328knots[i] = segments[i + size - overlap]._point;7329knots[i + size + overlap] = segments[i]._point;7330}7331} else {7332n--;7333}7334var rhs = [];73357336for (var i = 1; i < n - 1; i++)7337rhs[i] = 4 * knots[i]._x + 2 * knots[i + 1]._x;7338rhs[0] = knots[0]._x + 2 * knots[1]._x;7339rhs[n - 1] = 3 * knots[n - 1]._x;7340var x = getFirstControlPoints(rhs);73417342for (var i = 1; i < n - 1; i++)7343rhs[i] = 4 * knots[i]._y + 2 * knots[i + 1]._y;7344rhs[0] = knots[0]._y + 2 * knots[1]._y;7345rhs[n - 1] = 3 * knots[n - 1]._y;7346var y = getFirstControlPoints(rhs);73477348if (closed) {7349for (var i = 0, j = size; i < overlap; i++, j++) {7350var f1 = i / overlap,7351f2 = 1 - f1,7352ie = i + overlap,7353je = j + overlap;7354x[j] = x[i] * f1 + x[j] * f2;7355y[j] = y[i] * f1 + y[j] * f2;7356x[je] = x[ie] * f2 + x[je] * f1;7357y[je] = y[ie] * f2 + y[je] * f1;7358}7359n--;7360}7361var handleIn = null;7362for (var i = overlap; i <= n - overlap; i++) {7363var segment = segments[i - overlap];7364if (handleIn)7365segment.setHandleIn(handleIn.subtract(segment._point));7366if (i < n) {7367segment.setHandleOut(7368new Point(x[i], y[i]).subtract(segment._point));7369handleIn = i < n - 17370? new Point(73712 * knots[i + 1]._x - x[i + 1],73722 * knots[i + 1]._y - y[i + 1])7373: new Point(7374(knots[n]._x + x[n - 1]) / 2,7375(knots[n]._y + y[n - 1]) / 2);7376}7377}7378if (closed && handleIn) {7379var segment = this._segments[0];7380segment.setHandleIn(handleIn.subtract(segment._point));7381}7382}7383};7384}, new function() {7385function getCurrentSegment(that) {7386var segments = that._segments;7387if (segments.length === 0)7388throw new Error('Use a moveTo() command first');7389return segments[segments.length - 1];7390}73917392return {7393moveTo: function() {7394var segments = this._segments;7395if (segments.length === 1)7396this.removeSegment(0);7397if (!segments.length)7398this._add([ new Segment(Point.read(arguments)) ]);7399},74007401moveBy: function() {7402throw new Error('moveBy() is unsupported on Path items.');7403},74047405lineTo: function() {7406this._add([ new Segment(Point.read(arguments)) ]);7407},74087409cubicCurveTo: function() {7410var handle1 = Point.read(arguments),7411handle2 = Point.read(arguments),7412to = Point.read(arguments),7413current = getCurrentSegment(this);7414current.setHandleOut(handle1.subtract(current._point));7415this._add([ new Segment(to, handle2.subtract(to)) ]);7416},74177418quadraticCurveTo: function() {7419var handle = Point.read(arguments),7420to = Point.read(arguments),7421current = getCurrentSegment(this)._point;7422this.cubicCurveTo(7423handle.add(current.subtract(handle).multiply(1 / 3)),7424handle.add(to.subtract(handle).multiply(1 / 3)),7425to7426);7427},74287429curveTo: function() {7430var through = Point.read(arguments),7431to = Point.read(arguments),7432t = Base.pick(Base.read(arguments), 0.5),7433t1 = 1 - t,7434current = getCurrentSegment(this)._point,7435handle = through.subtract(current.multiply(t1 * t1))7436.subtract(to.multiply(t * t)).divide(2 * t * t1);7437if (handle.isNaN())7438throw new Error(7439'Cannot put a curve through points with parameter = ' + t);7440this.quadraticCurveTo(handle, to);7441},74427443arcTo: function() {7444var current = getCurrentSegment(this),7445from = current._point,7446to = Point.read(arguments),7447through,7448peek = Base.peek(arguments),7449clockwise = Base.pick(peek, true),7450center, extent, vector, matrix;7451if (typeof clockwise === 'boolean') {7452var middle = from.add(to).divide(2),7453through = middle.add(middle.subtract(from).rotate(7454clockwise ? -90 : 90));7455} else if (Base.remain(arguments) <= 2) {7456through = to;7457to = Point.read(arguments);7458} else {7459var radius = Size.read(arguments);7460if (radius.isZero())7461return this.lineTo(to);7462var rotation = Base.read(arguments),7463clockwise = !!Base.read(arguments),7464large = !!Base.read(arguments),7465middle = from.add(to).divide(2),7466pt = from.subtract(middle).rotate(-rotation),7467x = pt.x,7468y = pt.y,7469abs = Math.abs,7470EPSILON = 1e-11,7471rx = abs(radius.width),7472ry = abs(radius.height),7473rxSq = rx * rx,7474rySq = ry * ry,7475xSq = x * x,7476ySq = y * y;7477var factor = Math.sqrt(xSq / rxSq + ySq / rySq);7478if (factor > 1) {7479rx *= factor;7480ry *= factor;7481rxSq = rx * rx;7482rySq = ry * ry;7483}7484factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) /7485(rxSq * ySq + rySq * xSq);7486if (abs(factor) < EPSILON)7487factor = 0;7488if (factor < 0)7489throw new Error(7490'Cannot create an arc with the given arguments');7491center = new Point(rx * y / ry, -ry * x / rx)7492.multiply((large === clockwise ? -1 : 1)7493* Math.sqrt(factor))7494.rotate(rotation).add(middle);7495matrix = new Matrix().translate(center).rotate(rotation)7496.scale(rx, ry);7497vector = matrix._inverseTransform(from);7498extent = vector.getDirectedAngle(matrix._inverseTransform(to));7499if (!clockwise && extent > 0)7500extent -= 360;7501else if (clockwise && extent < 0)7502extent += 360;7503}7504if (through) {7505var l1 = new Line(from.add(through).divide(2),7506through.subtract(from).rotate(90), true),7507l2 = new Line(through.add(to).divide(2),7508to.subtract(through).rotate(90), true),7509line = new Line(from, to),7510throughSide = line.getSide(through);7511center = l1.intersect(l2, true);7512if (!center) {7513if (!throughSide)7514return this.lineTo(to);7515throw new Error(7516'Cannot create an arc with the given arguments');7517}7518vector = from.subtract(center);7519extent = vector.getDirectedAngle(to.subtract(center));7520var centerSide = line.getSide(center);7521if (centerSide === 0) {7522extent = throughSide * Math.abs(extent);7523} else if (throughSide === centerSide) {7524extent += extent < 0 ? 360 : -360;7525}7526}7527var ext = Math.abs(extent),7528count = ext >= 360 ? 4 : Math.ceil(ext / 90),7529inc = extent / count,7530half = inc * Math.PI / 360,7531z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),7532segments = [];7533for (var i = 0; i <= count; i++) {7534var pt = to,7535out = null;7536if (i < count) {7537out = vector.rotate(90).multiply(z);7538if (matrix) {7539pt = matrix._transformPoint(vector);7540out = matrix._transformPoint(vector.add(out))7541.subtract(pt);7542} else {7543pt = center.add(vector);7544}7545}7546if (i === 0) {7547current.setHandleOut(out);7548} else {7549var _in = vector.rotate(-90).multiply(z);7550if (matrix) {7551_in = matrix._transformPoint(vector.add(_in))7552.subtract(pt);7553}7554segments.push(new Segment(pt, _in, out));7555}7556vector = vector.rotate(inc);7557}7558this._add(segments);7559},75607561lineBy: function() {7562var to = Point.read(arguments),7563current = getCurrentSegment(this)._point;7564this.lineTo(current.add(to));7565},75667567curveBy: function() {7568var through = Point.read(arguments),7569to = Point.read(arguments),7570parameter = Base.read(arguments),7571current = getCurrentSegment(this)._point;7572this.curveTo(current.add(through), current.add(to), parameter);7573},75747575cubicCurveBy: function() {7576var handle1 = Point.read(arguments),7577handle2 = Point.read(arguments),7578to = Point.read(arguments),7579current = getCurrentSegment(this)._point;7580this.cubicCurveTo(current.add(handle1), current.add(handle2),7581current.add(to));7582},75837584quadraticCurveBy: function() {7585var handle = Point.read(arguments),7586to = Point.read(arguments),7587current = getCurrentSegment(this)._point;7588this.quadraticCurveTo(current.add(handle), current.add(to));7589},75907591arcBy: function() {7592var current = getCurrentSegment(this)._point,7593point = current.add(Point.read(arguments)),7594clockwise = Base.pick(Base.peek(arguments), true);7595if (typeof clockwise === 'boolean') {7596this.arcTo(point, clockwise);7597} else {7598this.arcTo(point, current.add(Point.read(arguments)));7599}7600},76017602closePath: function(join) {7603this.setClosed(true);7604if (join)7605this.join();7606}7607};7608}, {76097610_getBounds: function(getter, matrix) {7611return Path[getter](this._segments, this._closed, this.getStyle(),7612matrix);7613},76147615statics: {7616isClockwise: function(segments) {7617var sum = 0;7618for (var i = 0, l = segments.length; i < l; i++) {7619var v = Curve.getValues(7620segments[i], segments[i + 1 < l ? i + 1 : 0]);7621for (var j = 2; j < 8; j += 2)7622sum += (v[j - 2] - v[j]) * (v[j + 1] + v[j - 1]);7623}7624return sum > 0;7625},76267627getBounds: function(segments, closed, style, matrix, strokePadding) {7628var first = segments[0];7629if (!first)7630return new Rectangle();7631var coords = new Array(6),7632prevCoords = first._transformCoordinates(matrix, new Array(6), false),7633min = prevCoords.slice(0, 2),7634max = min.slice(),7635roots = new Array(2);76367637function processSegment(segment) {7638segment._transformCoordinates(matrix, coords, false);7639for (var i = 0; i < 2; i++) {7640Curve._addBounds(7641prevCoords[i],7642prevCoords[i + 4],7643coords[i + 2],7644coords[i],7645i, strokePadding ? strokePadding[i] : 0, min, max, roots);7646}7647var tmp = prevCoords;7648prevCoords = coords;7649coords = tmp;7650}76517652for (var i = 1, l = segments.length; i < l; i++)7653processSegment(segments[i]);7654if (closed)7655processSegment(first);7656return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);7657},76587659getStrokeBounds: function(segments, closed, style, matrix) {7660if (!style.hasStroke())7661return Path.getBounds(segments, closed, style, matrix);7662var length = segments.length - (closed ? 0 : 1),7663radius = style.getStrokeWidth() / 2,7664padding = Path._getPenPadding(radius, matrix),7665bounds = Path.getBounds(segments, closed, style, matrix, padding),7666join = style.getStrokeJoin(),7667cap = style.getStrokeCap(),7668miterLimit = radius * style.getMiterLimit();7669var joinBounds = new Rectangle(new Size(padding).multiply(2));76707671function add(point) {7672bounds = bounds.include(matrix7673? matrix._transformPoint(point, point) : point);7674}76757676function addRound(segment) {7677bounds = bounds.unite(joinBounds.setCenter(matrix7678? matrix._transformPoint(segment._point) : segment._point));7679}76807681function addJoin(segment, join) {7682var handleIn = segment._handleIn,7683handleOut = segment._handleOut7684if (join === 'round' || !handleIn.isZero() && !handleOut.isZero()7685&& handleIn.isColinear(handleOut)) {7686addRound(segment);7687} else {7688Path._addBevelJoin(segment, join, radius, miterLimit, add);7689}7690}76917692function addCap(segment, cap) {7693if (cap === 'round') {7694addRound(segment);7695} else {7696Path._addSquareCap(segment, cap, radius, add);7697}7698}76997700for (var i = 1; i < length; i++)7701addJoin(segments[i], join);7702if (closed) {7703addJoin(segments[0], join);7704} else if (length > 0) {7705addCap(segments[0], cap);7706addCap(segments[segments.length - 1], cap);7707}7708return bounds;7709},77107711_getPenPadding: function(radius, matrix) {7712if (!matrix)7713return [radius, radius];7714var mx = matrix.shiftless(),7715hor = mx.transform(new Point(radius, 0)),7716ver = mx.transform(new Point(0, radius)),7717phi = hor.getAngleInRadians(),7718a = hor.getLength(),7719b = ver.getLength();7720var sin = Math.sin(phi),7721cos = Math.cos(phi),7722tan = Math.tan(phi),7723tx = -Math.atan(b * tan / a),7724ty = Math.atan(b / (tan * a));7725return [Math.abs(a * Math.cos(tx) * cos - b * Math.sin(tx) * sin),7726Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];7727},77287729_addBevelJoin: function(segment, join, radius, miterLimit, addPoint, area) {7730var curve2 = segment.getCurve(),7731curve1 = curve2.getPrevious(),7732point = curve2.getPointAt(0, true),7733normal1 = curve1.getNormalAt(1, true),7734normal2 = curve2.getNormalAt(0, true),7735step = normal1.getDirectedAngle(normal2) < 0 ? -radius : radius;7736normal1.setLength(step);7737normal2.setLength(step);7738if (area) {7739addPoint(point);7740addPoint(point.add(normal1));7741}7742if (join === 'miter') {7743var corner = new Line(7744point.add(normal1),7745new Point(-normal1.y, normal1.x), true7746).intersect(new Line(7747point.add(normal2),7748new Point(-normal2.y, normal2.x), true7749), true);7750if (corner && point.getDistance(corner) <= miterLimit) {7751addPoint(corner);7752if (!area)7753return;7754}7755}7756if (!area)7757addPoint(point.add(normal1));7758addPoint(point.add(normal2));7759},77607761_addSquareCap: function(segment, cap, radius, addPoint, area) {7762var point = segment._point,7763loc = segment.getLocation(),7764normal = loc.getNormal().normalize(radius);7765if (area) {7766addPoint(point.subtract(normal));7767addPoint(point.add(normal));7768}7769if (cap === 'square')7770point = point.add(normal.rotate(loc.getParameter() == 0 ? -90 : 90));7771addPoint(point.add(normal));7772addPoint(point.subtract(normal));7773},77747775getHandleBounds: function(segments, closed, style, matrix, strokePadding,7776joinPadding) {7777var coords = new Array(6),7778x1 = Infinity,7779x2 = -x1,7780y1 = x1,7781y2 = x2;7782for (var i = 0, l = segments.length; i < l; i++) {7783var segment = segments[i];7784segment._transformCoordinates(matrix, coords, false);7785for (var j = 0; j < 6; j += 2) {7786var padding = j == 0 ? joinPadding : strokePadding,7787paddingX = padding ? padding[0] : 0,7788paddingY = padding ? padding[1] : 0,7789x = coords[j],7790y = coords[j + 1],7791xn = x - paddingX,7792xx = x + paddingX,7793yn = y - paddingY,7794yx = y + paddingY;7795if (xn < x1) x1 = xn;7796if (xx > x2) x2 = xx;7797if (yn < y1) y1 = yn;7798if (yx > y2) y2 = yx;7799}7800}7801return new Rectangle(x1, y1, x2 - x1, y2 - y1);7802},78037804getRoughBounds: function(segments, closed, style, matrix) {7805var strokeRadius = style.hasStroke() ? style.getStrokeWidth() / 2 : 0,7806joinRadius = strokeRadius;7807if (strokeRadius > 0) {7808if (style.getStrokeJoin() === 'miter')7809joinRadius = strokeRadius * style.getMiterLimit();7810if (style.getStrokeCap() === 'square')7811joinRadius = Math.max(joinRadius, strokeRadius * Math.sqrt(2));7812}7813return Path.getHandleBounds(segments, closed, style, matrix,7814Path._getPenPadding(strokeRadius, matrix),7815Path._getPenPadding(joinRadius, matrix));7816}7817}});78187819Path.inject({ statics: new function() {78207821var kappa = 0.5522847498307936,7822ellipseSegments = [7823new Segment([-1, 0], [0, kappa ], [0, -kappa]),7824new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),7825new Segment([1, 0], [0, -kappa], [0, kappa ]),7826new Segment([0, 1], [kappa, 0 ], [-kappa, 0])7827];78287829function createPath(segments, closed, args) {7830var props = Base.getNamed(args),7831path = new Path(props && props.insert === false && Item.NO_INSERT);7832path._add(segments);7833path._closed = closed;7834return path.set(props);7835}78367837function createEllipse(center, radius, args) {7838var segments = new Array(4);7839for (var i = 0; i < 4; i++) {7840var segment = ellipseSegments[i];7841segments[i] = new Segment(7842segment._point.multiply(radius).add(center),7843segment._handleIn.multiply(radius),7844segment._handleOut.multiply(radius)7845);7846}7847return createPath(segments, true, args);7848}78497850return {7851Line: function() {7852return createPath([7853new Segment(Point.readNamed(arguments, 'from')),7854new Segment(Point.readNamed(arguments, 'to'))7855], false, arguments);7856},78577858Circle: function() {7859var center = Point.readNamed(arguments, 'center'),7860radius = Base.readNamed(arguments, 'radius');7861return createEllipse(center, new Size(radius), arguments);7862},78637864Rectangle: function() {7865var rect = Rectangle.readNamed(arguments, 'rectangle'),7866radius = Size.readNamed(arguments, 'radius', 0,7867{ readNull: true }),7868bl = rect.getBottomLeft(true),7869tl = rect.getTopLeft(true),7870tr = rect.getTopRight(true),7871br = rect.getBottomRight(true),7872segments;7873if (!radius || radius.isZero()) {7874segments = [7875new Segment(bl),7876new Segment(tl),7877new Segment(tr),7878new Segment(br)7879];7880} else {7881radius = Size.min(radius, rect.getSize(true).divide(2));7882var rx = radius.width,7883ry = radius.height,7884hx = rx * kappa,7885hy = ry * kappa;7886segments = [7887new Segment(bl.add(rx, 0), null, [-hx, 0]),7888new Segment(bl.subtract(0, ry), [0, hy]),7889new Segment(tl.add(0, ry), null, [0, -hy]),7890new Segment(tl.add(rx, 0), [-hx, 0], null),7891new Segment(tr.subtract(rx, 0), null, [hx, 0]),7892new Segment(tr.add(0, ry), [0, -hy], null),7893new Segment(br.subtract(0, ry), null, [0, hy]),7894new Segment(br.subtract(rx, 0), [hx, 0])7895];7896}7897return createPath(segments, true, arguments);7898},78997900RoundRectangle: '#Rectangle',79017902Ellipse: function() {7903var ellipse = Shape._readEllipse(arguments);7904return createEllipse(ellipse.center, ellipse.radius, arguments);7905},79067907Oval: '#Ellipse',79087909Arc: function() {7910var from = Point.readNamed(arguments, 'from'),7911through = Point.readNamed(arguments, 'through'),7912to = Point.readNamed(arguments, 'to'),7913props = Base.getNamed(arguments),7914path = new Path(props && props.insert === false7915&& Item.NO_INSERT);7916path.moveTo(from);7917path.arcTo(through, to);7918return path.set(props);7919},79207921RegularPolygon: function() {7922var center = Point.readNamed(arguments, 'center'),7923sides = Base.readNamed(arguments, 'sides'),7924radius = Base.readNamed(arguments, 'radius'),7925step = 360 / sides,7926three = !(sides % 3),7927vector = new Point(0, three ? -radius : radius),7928offset = three ? -1 : 0.5,7929segments = new Array(sides);7930for (var i = 0; i < sides; i++)7931segments[i] = new Segment(center.add(7932vector.rotate((i + offset) * step)));7933return createPath(segments, true, arguments);7934},79357936Star: function() {7937var center = Point.readNamed(arguments, 'center'),7938points = Base.readNamed(arguments, 'points') * 2,7939radius1 = Base.readNamed(arguments, 'radius1'),7940radius2 = Base.readNamed(arguments, 'radius2'),7941step = 360 / points,7942vector = new Point(0, -1),7943segments = new Array(points);7944for (var i = 0; i < points; i++)7945segments[i] = new Segment(center.add(vector.rotate(step * i)7946.multiply(i % 2 ? radius2 : radius1)));7947return createPath(segments, true, arguments);7948}7949};7950}});79517952var CompoundPath = PathItem.extend({7953_class: 'CompoundPath',7954_serializeFields: {7955children: []7956},79577958initialize: function CompoundPath(arg) {7959this._children = [];7960this._namedChildren = {};7961if (!this._initialize(arg)) {7962if (typeof arg === 'string') {7963this.setPathData(arg);7964} else {7965this.addChildren(Array.isArray(arg) ? arg : arguments);7966}7967}7968},79697970insertChildren: function insertChildren(index, items, _preserve) {7971items = insertChildren.base.call(this, index, items, _preserve, Path);7972for (var i = 0, l = !_preserve && items && items.length; i < l; i++) {7973var item = items[i];7974if (item._clockwise === undefined)7975item.setClockwise(item._index === 0);7976}7977return items;7978},79797980reverse: function() {7981var children = this._children;7982for (var i = 0, l = children.length; i < l; i++)7983children[i].reverse();7984},79857986smooth: function() {7987for (var i = 0, l = this._children.length; i < l; i++)7988this._children[i].smooth();7989},79907991isClockwise: function() {7992var child = this.getFirstChild();7993return child && child.isClockwise();7994},79957996setClockwise: function(clockwise) {7997if (this.isClockwise() !== !!clockwise)7998this.reverse();7999},80008001getFirstSegment: function() {8002var first = this.getFirstChild();8003return first && first.getFirstSegment();8004},80058006getLastSegment: function() {8007var last = this.getLastChild();8008return last && last.getLastSegment();8009},80108011getCurves: function() {8012var children = this._children,8013curves = [];8014for (var i = 0, l = children.length; i < l; i++)8015curves.push.apply(curves, children[i].getCurves());8016return curves;8017},80188019getFirstCurve: function() {8020var first = this.getFirstChild();8021return first && first.getFirstCurve();8022},80238024getLastCurve: function() {8025var last = this.getLastChild();8026return last && last.getFirstCurve();8027},80288029getArea: function() {8030var children = this._children,8031area = 0;8032for (var i = 0, l = children.length; i < l; i++)8033area += children[i].getArea();8034return area;8035}8036}, {8037beans: true,80388039getPathData: function(_precision) {8040var children = this._children,8041paths = [];8042for (var i = 0, l = children.length; i < l; i++)8043paths.push(children[i].getPathData(_precision));8044return paths.join(' ');8045}8046}, {8047_getChildHitTestOptions: function(options) {8048return options.type === 'path'8049? options8050: new Base(options, { fill: false });8051},80528053_draw: function(ctx, param) {8054var children = this._children;8055if (children.length === 0)8056return;80578058if (this._currentPath) {8059ctx.currentPath = this._currentPath;8060} else {8061param = param.extend({ dontStart: true, dontFinish: true });8062ctx.beginPath();8063for (var i = 0, l = children.length; i < l; i++)8064children[i].draw(ctx, param);8065this._currentPath = ctx.currentPath;8066}80678068if (!param.clip) {8069this._setStyles(ctx);8070var style = this._style;8071if (style.hasFill()) {8072ctx.fill(style.getWindingRule());8073ctx.shadowColor = 'rgba(0,0,0,0)';8074}8075if (style.hasStroke())8076ctx.stroke();8077}8078},80798080_drawSelected: function(ctx, matrix) {8081var children = this._children;8082for (var i = 0, l = children.length; i < l; i++) {8083var child = children[i],8084mx = child._matrix;8085child._drawSelected(ctx, mx.isIdentity() ? matrix8086: matrix.clone().concatenate(child._matrix));8087}8088}8089}, new function() {8090function getCurrentPath(that, check) {8091var children = that._children;8092if (check && children.length === 0)8093throw new Error('Use a moveTo() command first');8094return children[children.length - 1];8095}80968097var fields = {8098moveTo: function() {8099var current = getCurrentPath(this),8100path = current && current.isEmpty() ? current : new Path();8101if (path !== current)8102this.addChild(path);8103path.moveTo.apply(path, arguments);8104},81058106moveBy: function() {8107var current = getCurrentPath(this, true),8108last = current && current.getLastSegment(),8109point = Point.read(arguments);8110this.moveTo(last ? point.add(last._point) : point);8111},81128113closePath: function(join) {8114getCurrentPath(this, true).closePath(join);8115}8116};81178118Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', 'arcTo',8119'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy', 'arcBy'],8120function(key) {8121fields[key] = function() {8122var path = getCurrentPath(this, true);8123path[key].apply(path, arguments);8124};8125}8126);81278128return fields;8129});81308131PathItem.inject(new function() {8132function computeBoolean(path1, path2, operator, subtract) {8133function preparePath(path) {8134return path.clone(false).reduce().reorient().transform(null, true);8135}81368137var _path1 = preparePath(path1),8138_path2 = path2 && path1 !== path2 && preparePath(path2);8139if (!_path1.isClockwise())8140_path1.reverse();8141if (_path2 && !(subtract ^ _path2.isClockwise()))8142_path2.reverse();8143splitPath(_path1.getIntersections(_path2, true));81448145var chain = [],8146windings = [],8147lengths = [],8148segments = [],8149monoCurves = [];81508151function collect(paths) {8152for (var i = 0, l = paths.length; i < l; i++) {8153var path = paths[i];8154segments.push.apply(segments, path._segments);8155monoCurves.push.apply(monoCurves, path._getMonoCurves());8156}8157}81588159collect(_path1._children || [_path1]);8160if (_path2)8161collect(_path2._children || [_path2]);8162segments.sort(function(a, b) {8163var _a = a._intersection,8164_b = b._intersection;8165return !_a && !_b || _a && _b ? 0 : _a ? -1 : 1;8166});8167for (var i = 0, l = segments.length; i < l; i++) {8168var segment = segments[i];8169if (segment._winding != null)8170continue;8171chain.length = windings.length = lengths.length = 0;8172var totalLength = 0,8173startSeg = segment;8174do {8175chain.push(segment);8176lengths.push(totalLength += segment.getCurve().getLength());8177segment = segment.getNext();8178} while (segment && !segment._intersection && segment !== startSeg);8179for (var j = 0; j < 3; j++) {8180var length = totalLength * Math.random(),8181amount = lengths.length,8182k = 0;8183do {8184if (lengths[k] >= length) {8185if (k > 0)8186length -= lengths[k - 1];8187break;8188}8189} while (++k < amount);8190var curve = chain[k].getCurve(),8191point = curve.getPointAt(length),8192hor = curve.isHorizontal(),8193path = curve._path;8194if (path._parent instanceof CompoundPath)8195path = path._parent;8196windings[j] = subtract && _path28197&& (path === _path1 && _path2._getWinding(point, hor)8198|| path === _path2 && !_path1._getWinding(point, hor))8199? 08200: getWinding(point, monoCurves, hor);8201}8202windings.sort();8203var winding = windings[1];8204for (var j = chain.length - 1; j >= 0; j--)8205chain[j]._winding = winding;8206}8207var result = new CompoundPath();8208result.addChildren(tracePaths(segments, operator), true);8209_path1.remove();8210if (_path2)8211_path2.remove();8212return result.reduce();8213}82148215function splitPath(intersections) {8216var TOLERANCE = 0.00001,8217linearSegments;82188219function resetLinear() {8220for (var i = 0, l = linearSegments.length; i < l; i++) {8221var segment = linearSegments[i];8222segment._handleOut.set(0, 0);8223segment._handleIn.set(0, 0);8224}8225}82268227for (var i = intersections.length - 1, curve, prevLoc; i >= 0; i--) {8228var loc = intersections[i],8229t = loc._parameter;8230if (prevLoc && prevLoc._curve === loc._curve8231&& prevLoc._parameter > 0) {8232t /= prevLoc._parameter;8233} else {8234if (linearSegments)8235resetLinear();8236curve = loc._curve;8237linearSegments = curve.isLinear() && [];8238}8239var newCurve,8240segment;8241if (newCurve = curve.divide(t, true, true)) {8242segment = newCurve._segment1;8243curve = newCurve.getPrevious();8244} else {8245segment = t < TOLERANCE8246? curve._segment18247: t > 1 - TOLERANCE8248? curve._segment28249: curve.getPartLength(0, t) < curve.getPartLength(t, 1)8250? curve._segment18251: curve._segment2;8252}8253segment._intersection = loc.getIntersection();8254loc._segment = segment;8255if (linearSegments)8256linearSegments.push(segment);8257prevLoc = loc;8258}8259if (linearSegments)8260resetLinear();8261}82628263function getWinding(point, curves, horizontal, testContains) {8264var TOLERANCE = 0.00001,8265x = point.x,8266y = point.y,8267windLeft = 0,8268windRight = 0,8269roots = [],8270abs = Math.abs,8271MAX = 1 - TOLERANCE;8272if (horizontal) {8273var yTop = -Infinity,8274yBottom = Infinity,8275yBefore = y - TOLERANCE,8276yAfter = y + TOLERANCE;8277for (var i = 0, l = curves.length; i < l; i++) {8278var values = curves[i].values;8279if (Curve.solveCubic(values, 0, x, roots, 0, 1) > 0) {8280for (var j = roots.length - 1; j >= 0; j--) {8281var y0 = Curve.evaluate(values, roots[j], 0).y;8282if (y0 < yBefore && y0 > yTop) {8283yTop = y0;8284} else if (y0 > yAfter && y0 < yBottom) {8285yBottom = y0;8286}8287}8288}8289}8290yTop = (yTop + y) / 2;8291yBottom = (yBottom + y) / 2;8292if (yTop > -Infinity)8293windLeft = getWinding(new Point(x, yTop), curves);8294if (yBottom < Infinity)8295windRight = getWinding(new Point(x, yBottom), curves);8296} else {8297var xBefore = x - TOLERANCE,8298xAfter = x + TOLERANCE;8299for (var i = 0, l = curves.length; i < l; i++) {8300var curve = curves[i],8301values = curve.values,8302winding = curve.winding,8303next = curve.next;8304if (winding && (winding === 18305&& y >= values[1] && y <= values[7]8306|| y >= values[7] && y <= values[1])8307&& Curve.solveCubic(values, 1, y, roots, 0,8308!next.winding && next.values[1] === y ? 1 : MAX) === 1){8309var t = roots[0],8310x0 = Curve.evaluate(values, t, 0).x,8311slope = Curve.evaluate(values, t, 1).y;8312if (abs(slope) < TOLERANCE && !Curve.isLinear(values)8313|| t < TOLERANCE && slope * Curve.evaluate(8314curve.previous.values, t, 1).y < 0) {8315if (testContains && x0 >= xBefore && x0 <= xAfter) {8316++windLeft;8317++windRight;8318}8319} else if (x0 <= xBefore) {8320windLeft += winding;8321} else if (x0 >= xAfter) {8322windRight += winding;8323}8324}8325}8326}8327return Math.max(abs(windLeft), abs(windRight));8328}83298330function tracePaths(segments, operator, selfOp) {8331operator = operator || function() {8332return true;8333};8334var paths = [],8335ZERO = 1e-3,8336ONE = 1 - 1e-3;8337for (var i = 0, seg, startSeg, l = segments.length; i < l; i++) {8338seg = startSeg = segments[i];8339if (seg._visited || !operator(seg._winding))8340continue;8341var path = new Path(Item.NO_INSERT),8342inter = seg._intersection,8343startInterSeg = inter && inter._segment,8344added = false,8345dir = 1;8346do {8347var handleIn = dir > 0 ? seg._handleIn : seg._handleOut,8348handleOut = dir > 0 ? seg._handleOut : seg._handleIn,8349interSeg;8350if (added && (!operator(seg._winding) || selfOp)8351&& (inter = seg._intersection)8352&& (interSeg = inter._segment)8353&& interSeg !== startSeg) {8354if (selfOp) {8355seg._visited = interSeg._visited;8356seg = interSeg;8357dir = 1;8358} else {8359var c1 = seg.getCurve();8360if (dir > 0)8361c1 = c1.getPrevious();8362var t1 = c1.getTangentAt(dir < 1 ? ZERO : ONE, true),8363c4 = interSeg.getCurve(),8364c3 = c4.getPrevious(),8365t3 = c3.getTangentAt(ONE, true),8366t4 = c4.getTangentAt(ZERO, true),8367w3 = t1.cross(t3),8368w4 = t1.cross(t4);8369if (w3 * w4 !== 0) {8370var curve = w3 < w4 ? c3 : c4,8371nextCurve = operator(curve._segment1._winding)8372? curve8373: w3 < w4 ? c4 : c3,8374nextSeg = nextCurve._segment1;8375dir = nextCurve === c3 ? -1 : 1;8376if (nextSeg._visited && seg._path !== nextSeg._path8377|| !operator(nextSeg._winding)) {8378dir = 1;8379} else {8380seg._visited = interSeg._visited;8381seg = interSeg;8382if (nextSeg._visited)8383dir = 1;8384}8385} else {8386dir = 1;8387}8388}8389handleOut = dir > 0 ? seg._handleOut : seg._handleIn;8390}8391path.add(new Segment(seg._point, added && handleIn, handleOut));8392added = true;8393seg._visited = true;8394seg = dir > 0 ? seg.getNext() : seg. getPrevious();8395} while (seg && !seg._visited8396&& seg !== startSeg && seg !== startInterSeg8397&& (seg._intersection || operator(seg._winding)));8398if (seg && (seg === startSeg || seg === startInterSeg)) {8399path.firstSegment.setHandleIn((seg === startInterSeg8400? startInterSeg : seg)._handleIn);8401path.setClosed(true);8402} else {8403path.lastSegment._handleOut.set(0, 0);8404}8405if (path._segments.length >8406(path._closed ? path.isPolygon() ? 2 : 0 : 1))8407paths.push(path);8408}8409return paths;8410}84118412return {8413_getWinding: function(point, horizontal, testContains) {8414return getWinding(point, this._getMonoCurves(),8415horizontal, testContains);8416},84178418unite: function(path) {8419return computeBoolean(this, path, function(w) {8420return w === 1 || w === 0;8421}, false);8422},84238424intersect: function(path) {8425return computeBoolean(this, path, function(w) {8426return w === 2;8427}, false);8428},84298430subtract: function(path) {8431return computeBoolean(this, path, function(w) {8432return w === 1;8433}, true);8434},84358436exclude: function(path) {8437return new Group([this.subtract(path), path.subtract(this)]);8438},84398440divide: function(path) {8441return new Group([this.subtract(path), this.intersect(path)]);8442}8443};8444});84458446Path.inject({8447_getMonoCurves: function() {8448var monoCurves = this._monoCurves,8449prevCurve;84508451function insertCurve(v) {8452var y0 = v[1],8453y1 = v[7],8454curve = {8455values: v,8456winding: y0 === y18457? 08458: y0 > y18459? -18460: 1,8461previous: prevCurve,8462next: null8463};8464if (prevCurve)8465prevCurve.next = curve;8466monoCurves.push(curve);8467prevCurve = curve;8468}84698470function handleCurve(v) {8471if (Curve.getLength(v) === 0)8472return;8473var y0 = v[1],8474y1 = v[3],8475y2 = v[5],8476y3 = v[7];8477if (Curve.isLinear(v)) {8478insertCurve(v);8479} else {8480var a = 3 * (y1 - y2) - y0 + y3,8481b = 2 * (y0 + y2) - 4 * y1,8482c = y1 - y0,8483TOLERANCE = 0.00001,8484roots = [];8485var count = Numerical.solveQuadratic(a, b, c, roots, TOLERANCE,84861 - TOLERANCE);8487if (count === 0) {8488insertCurve(v);8489} else {8490roots.sort();8491var t = roots[0],8492parts = Curve.subdivide(v, t);8493insertCurve(parts[0]);8494if (count > 1) {8495t = (roots[1] - t) / (1 - t);8496parts = Curve.subdivide(parts[1], t);8497insertCurve(parts[0]);8498}8499insertCurve(parts[1]);8500}8501}8502}85038504if (!monoCurves) {8505monoCurves = this._monoCurves = [];8506var curves = this.getCurves(),8507segments = this._segments;8508for (var i = 0, l = curves.length; i < l; i++)8509handleCurve(curves[i].getValues());8510if (!this._closed && segments.length > 1) {8511var p1 = segments[segments.length - 1]._point,8512p2 = segments[0]._point,8513p1x = p1._x, p1y = p1._y,8514p2x = p2._x, p2y = p2._y;8515handleCurve([p1x, p1y, p1x, p1y, p2x, p2y, p2x, p2y]);8516}8517if (monoCurves.length > 0) {8518var first = monoCurves[0],8519last = monoCurves[monoCurves.length - 1];8520first.previous = last;8521last.next = first;8522}8523}8524return monoCurves;8525},85268527getInteriorPoint: function() {8528var bounds = this.getBounds(),8529point = bounds.getCenter(true);8530if (!this.contains(point)) {8531var curves = this._getMonoCurves(),8532roots = [],8533y = point.y,8534xIntercepts = [];8535for (var i = 0, l = curves.length; i < l; i++) {8536var values = curves[i].values;8537if ((curves[i].winding === 18538&& y >= values[1] && y <= values[7]8539|| y >= values[7] && y <= values[1])8540&& Curve.solveCubic(values, 1, y, roots, 0, 1) > 0) {8541for (var j = roots.length - 1; j >= 0; j--)8542xIntercepts.push(Curve.evaluate(values, roots[j], 0).x);8543}8544if (xIntercepts.length > 1)8545break;8546}8547point.x = (xIntercepts[0] + xIntercepts[1]) / 2;8548}8549return point;8550},85518552reorient: function() {8553this.setClockwise(true);8554return this;8555}8556});85578558CompoundPath.inject({8559_getMonoCurves: function() {8560var children = this._children,8561monoCurves = [];8562for (var i = 0, l = children.length; i < l; i++)8563monoCurves.push.apply(monoCurves, children[i]._getMonoCurves());8564return monoCurves;8565},85668567reorient: function() {8568var children = this.removeChildren().sort(function(a, b) {8569return b.getBounds().getArea() - a.getBounds().getArea();8570});8571this.addChildren(children);8572var clockwise = children[0].isClockwise();8573for (var i = 1, l = children.length; i < l; i++) {8574var point = children[i].getInteriorPoint(),8575counters = 0;8576for (var j = i - 1; j >= 0; j--) {8577if (children[j].contains(point))8578counters++;8579}8580children[i].setClockwise(counters % 2 === 0 && clockwise);8581}8582return this;8583}8584});85858586var PathFlattener = Base.extend({8587initialize: function(path) {8588this.curves = [];8589this.parts = [];8590this.length = 0;8591this.index = 0;85928593var segments = path._segments,8594segment1 = segments[0],8595segment2,8596that = this;85978598function addCurve(segment1, segment2) {8599var curve = Curve.getValues(segment1, segment2);8600that.curves.push(curve);8601that._computeParts(curve, segment1._index, 0, 1);8602}86038604for (var i = 1, l = segments.length; i < l; i++) {8605segment2 = segments[i];8606addCurve(segment1, segment2);8607segment1 = segment2;8608}8609if (path._closed)8610addCurve(segment2, segments[0]);8611},86128613_computeParts: function(curve, index, minT, maxT) {8614if ((maxT - minT) > 1 / 32 && !Curve.isFlatEnough(curve, 0.25)) {8615var curves = Curve.subdivide(curve);8616var halfT = (minT + maxT) / 2;8617this._computeParts(curves[0], index, minT, halfT);8618this._computeParts(curves[1], index, halfT, maxT);8619} else {8620var x = curve[6] - curve[0],8621y = curve[7] - curve[1],8622dist = Math.sqrt(x * x + y * y);8623if (dist > 0.00001) {8624this.length += dist;8625this.parts.push({8626offset: this.length,8627value: maxT,8628index: index8629});8630}8631}8632},86338634getParameterAt: function(offset) {8635var i, j = this.index;8636for (;;) {8637i = j;8638if (j == 0 || this.parts[--j].offset < offset)8639break;8640}8641for (var l = this.parts.length; i < l; i++) {8642var part = this.parts[i];8643if (part.offset >= offset) {8644this.index = i;8645var prev = this.parts[i - 1];8646var prevVal = prev && prev.index == part.index ? prev.value : 0,8647prevLen = prev ? prev.offset : 0;8648return {8649value: prevVal + (part.value - prevVal)8650* (offset - prevLen) / (part.offset - prevLen),8651index: part.index8652};8653}8654}8655var part = this.parts[this.parts.length - 1];8656return {8657value: 1,8658index: part.index8659};8660},86618662evaluate: function(offset, type) {8663var param = this.getParameterAt(offset);8664return Curve.evaluate(this.curves[param.index], param.value, type);8665},86668667drawPart: function(ctx, from, to) {8668from = this.getParameterAt(from);8669to = this.getParameterAt(to);8670for (var i = from.index; i <= to.index; i++) {8671var curve = Curve.getPart(this.curves[i],8672i == from.index ? from.value : 0,8673i == to.index ? to.value : 1);8674if (i == from.index)8675ctx.moveTo(curve[0], curve[1]);8676ctx.bezierCurveTo.apply(ctx, curve.slice(2));8677}8678}8679});86808681var PathFitter = Base.extend({8682initialize: function(path, error) {8683this.points = [];8684var segments = path._segments,8685prev;8686for (var i = 0, l = segments.length; i < l; i++) {8687var point = segments[i].point.clone();8688if (!prev || !prev.equals(point)) {8689this.points.push(point);8690prev = point;8691}8692}8693this.error = error;8694},86958696fit: function() {8697var points = this.points,8698length = points.length;8699this.segments = length > 0 ? [new Segment(points[0])] : [];8700if (length > 1)8701this.fitCubic(0, length - 1,8702points[1].subtract(points[0]).normalize(),8703points[length - 2].subtract(points[length - 1]).normalize());8704return this.segments;8705},87068707fitCubic: function(first, last, tan1, tan2) {8708if (last - first == 1) {8709var pt1 = this.points[first],8710pt2 = this.points[last],8711dist = pt1.getDistance(pt2) / 3;8712this.addCurve([pt1, pt1.add(tan1.normalize(dist)),8713pt2.add(tan2.normalize(dist)), pt2]);8714return;8715}8716var uPrime = this.chordLengthParameterize(first, last),8717maxError = Math.max(this.error, this.error * this.error),8718split;8719for (var i = 0; i <= 4; i++) {8720var curve = this.generateBezier(first, last, uPrime, tan1, tan2);8721var max = this.findMaxError(first, last, curve, uPrime);8722if (max.error < this.error) {8723this.addCurve(curve);8724return;8725}8726split = max.index;8727if (max.error >= maxError)8728break;8729this.reparameterize(first, last, uPrime, curve);8730maxError = max.error;8731}8732var V1 = this.points[split - 1].subtract(this.points[split]),8733V2 = this.points[split].subtract(this.points[split + 1]),8734tanCenter = V1.add(V2).divide(2).normalize();8735this.fitCubic(first, split, tan1, tanCenter);8736this.fitCubic(split, last, tanCenter.negate(), tan2);8737},87388739addCurve: function(curve) {8740var prev = this.segments[this.segments.length - 1];8741prev.setHandleOut(curve[1].subtract(curve[0]));8742this.segments.push(8743new Segment(curve[3], curve[2].subtract(curve[3])));8744},87458746generateBezier: function(first, last, uPrime, tan1, tan2) {8747var epsilon = 1e-11,8748pt1 = this.points[first],8749pt2 = this.points[last],8750C = [[0, 0], [0, 0]],8751X = [0, 0];87528753for (var i = 0, l = last - first + 1; i < l; i++) {8754var u = uPrime[i],8755t = 1 - u,8756b = 3 * u * t,8757b0 = t * t * t,8758b1 = b * t,8759b2 = b * u,8760b3 = u * u * u,8761a1 = tan1.normalize(b1),8762a2 = tan2.normalize(b2),8763tmp = this.points[first + i]8764.subtract(pt1.multiply(b0 + b1))8765.subtract(pt2.multiply(b2 + b3));8766C[0][0] += a1.dot(a1);8767C[0][1] += a1.dot(a2);8768C[1][0] = C[0][1];8769C[1][1] += a2.dot(a2);8770X[0] += a1.dot(tmp);8771X[1] += a2.dot(tmp);8772}87738774var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],8775alpha1, alpha2;8776if (Math.abs(detC0C1) > epsilon) {8777var detC0X = C[0][0] * X[1] - C[1][0] * X[0],8778detXC1 = X[0] * C[1][1] - X[1] * C[0][1];8779alpha1 = detXC1 / detC0C1;8780alpha2 = detC0X / detC0C1;8781} else {8782var c0 = C[0][0] + C[0][1],8783c1 = C[1][0] + C[1][1];8784if (Math.abs(c0) > epsilon) {8785alpha1 = alpha2 = X[0] / c0;8786} else if (Math.abs(c1) > epsilon) {8787alpha1 = alpha2 = X[1] / c1;8788} else {8789alpha1 = alpha2 = 0;8790}8791}87928793var segLength = pt2.getDistance(pt1);8794epsilon *= segLength;8795if (alpha1 < epsilon || alpha2 < epsilon) {8796alpha1 = alpha2 = segLength / 3;8797}87988799return [pt1, pt1.add(tan1.normalize(alpha1)),8800pt2.add(tan2.normalize(alpha2)), pt2];8801},88028803reparameterize: function(first, last, u, curve) {8804for (var i = first; i <= last; i++) {8805u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);8806}8807},88088809findRoot: function(curve, point, u) {8810var curve1 = [],8811curve2 = [];8812for (var i = 0; i <= 2; i++) {8813curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);8814}8815for (var i = 0; i <= 1; i++) {8816curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);8817}8818var pt = this.evaluate(3, curve, u),8819pt1 = this.evaluate(2, curve1, u),8820pt2 = this.evaluate(1, curve2, u),8821diff = pt.subtract(point),8822df = pt1.dot(pt1) + diff.dot(pt2);8823if (Math.abs(df) < 0.00001)8824return u;8825return u - diff.dot(pt1) / df;8826},88278828evaluate: function(degree, curve, t) {8829var tmp = curve.slice();8830for (var i = 1; i <= degree; i++) {8831for (var j = 0; j <= degree - i; j++) {8832tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));8833}8834}8835return tmp[0];8836},88378838chordLengthParameterize: function(first, last) {8839var u = [0];8840for (var i = first + 1; i <= last; i++) {8841u[i - first] = u[i - first - 1]8842+ this.points[i].getDistance(this.points[i - 1]);8843}8844for (var i = 1, m = last - first; i <= m; i++) {8845u[i] /= u[m];8846}8847return u;8848},88498850findMaxError: function(first, last, curve, u) {8851var index = Math.floor((last - first + 1) / 2),8852maxDist = 0;8853for (var i = first + 1; i < last; i++) {8854var P = this.evaluate(3, curve, u[i - first]);8855var v = P.subtract(this.points[i]);8856var dist = v.x * v.x + v.y * v.y;8857if (dist >= maxDist) {8858maxDist = dist;8859index = i;8860}8861}8862return {8863error: maxDist,8864index: index8865};8866}8867});88688869var TextItem = Item.extend({8870_class: 'TextItem',8871_boundsSelected: true,8872_applyMatrix: false,8873_canApplyMatrix: false,8874_serializeFields: {8875content: null8876},8877_boundsGetter: 'getBounds',88788879initialize: function TextItem(arg) {8880this._content = '';8881this._lines = [];8882var hasProps = arg && Base.isPlainObject(arg)8883&& arg.x === undefined && arg.y === undefined;8884this._initialize(hasProps && arg, !hasProps && Point.read(arguments));8885},88868887_equals: function(item) {8888return this._content === item._content;8889},88908891_clone: function _clone(copy) {8892copy.setContent(this._content);8893return _clone.base.call(this, copy);8894},88958896getContent: function() {8897return this._content;8898},88998900setContent: function(content) {8901this._content = '' + content;8902this._lines = this._content.split(/\r\n|\n|\r/mg);8903this._changed(265);8904},89058906isEmpty: function() {8907return !this._content;8908},89098910getCharacterStyle: '#getStyle',8911setCharacterStyle: '#setStyle',89128913getParagraphStyle: '#getStyle',8914setParagraphStyle: '#setStyle'8915});89168917var PointText = TextItem.extend({8918_class: 'PointText',89198920initialize: function PointText() {8921TextItem.apply(this, arguments);8922},89238924clone: function(insert) {8925return this._clone(new PointText(Item.NO_INSERT), insert);8926},89278928getPoint: function() {8929var point = this._matrix.getTranslation();8930return new LinkedPoint(point.x, point.y, this, 'setPoint');8931},89328933setPoint: function() {8934var point = Point.read(arguments);8935this.translate(point.subtract(this._matrix.getTranslation()));8936},89378938_draw: function(ctx) {8939if (!this._content)8940return;8941this._setStyles(ctx);8942var style = this._style,8943lines = this._lines,8944leading = style.getLeading(),8945shadowColor = ctx.shadowColor;8946ctx.font = style.getFontStyle();8947ctx.textAlign = style.getJustification();8948for (var i = 0, l = lines.length; i < l; i++) {8949ctx.shadowColor = shadowColor;8950var line = lines[i];8951if (style.hasFill()) {8952ctx.fillText(line, 0, 0);8953ctx.shadowColor = 'rgba(0,0,0,0)';8954}8955if (style.hasStroke())8956ctx.strokeText(line, 0, 0);8957ctx.translate(0, leading);8958}8959},89608961_getBounds: function(getter, matrix) {8962var style = this._style,8963lines = this._lines,8964numLines = lines.length,8965justification = style.getJustification(),8966leading = style.getLeading(),8967width = this.getView().getTextWidth(style.getFontStyle(), lines),8968x = 0;8969if (justification !== 'left')8970x -= width / (justification === 'center' ? 2: 1);8971var bounds = new Rectangle(x,8972numLines ? - 0.75 * leading : 0,8973width, numLines * leading);8974return matrix ? matrix._transformBounds(bounds, bounds) : bounds;8975}8976});89778978var Color = Base.extend(new function() {89798980var types = {8981gray: ['gray'],8982rgb: ['red', 'green', 'blue'],8983hsb: ['hue', 'saturation', 'brightness'],8984hsl: ['hue', 'saturation', 'lightness'],8985gradient: ['gradient', 'origin', 'destination', 'highlight']8986};89878988var componentParsers = {},8989colorCache = {},8990colorCtx;89918992function fromCSS(string) {8993var match = string.match(/^#(\w{1,2})(\w{1,2})(\w{1,2})$/),8994components;8995if (match) {8996components = [0, 0, 0];8997for (var i = 0; i < 3; i++) {8998var value = match[i + 1];8999components[i] = parseInt(value.length == 19000? value + value : value, 16) / 255;9001}9002} else if (match = string.match(/^rgba?\((.*)\)$/)) {9003components = match[1].split(',');9004for (var i = 0, l = components.length; i < l; i++) {9005var value = +components[i];9006components[i] = i < 3 ? value / 255 : value;9007}9008} else {9009var cached = colorCache[string];9010if (!cached) {9011if (!colorCtx) {9012colorCtx = CanvasProvider.getContext(1, 1);9013colorCtx.globalCompositeOperation = 'copy';9014}9015colorCtx.fillStyle = 'rgba(0,0,0,0)';9016colorCtx.fillStyle = string;9017colorCtx.fillRect(0, 0, 1, 1);9018var data = colorCtx.getImageData(0, 0, 1, 1).data;9019cached = colorCache[string] = [9020data[0] / 255,9021data[1] / 255,9022data[2] / 2559023];9024}9025components = cached.slice();9026}9027return components;9028}90299030var hsbIndices = [9031[0, 3, 1],9032[2, 0, 1],9033[1, 0, 3],9034[1, 2, 0],9035[3, 1, 0],9036[0, 1, 2]9037];90389039var converters = {9040'rgb-hsb': function(r, g, b) {9041var max = Math.max(r, g, b),9042min = Math.min(r, g, b),9043delta = max - min,9044h = delta === 0 ? 09045: ( max == r ? (g - b) / delta + (g < b ? 6 : 0)9046: max == g ? (b - r) / delta + 29047: (r - g) / delta + 4) * 60;9048return [h, max === 0 ? 0 : delta / max, max];9049},90509051'hsb-rgb': function(h, s, b) {9052h = (((h / 60) % 6) + 6) % 6;9053var i = Math.floor(h),9054f = h - i,9055i = hsbIndices[i],9056v = [9057b,9058b * (1 - s),9059b * (1 - s * f),9060b * (1 - s * (1 - f))9061];9062return [v[i[0]], v[i[1]], v[i[2]]];9063},90649065'rgb-hsl': function(r, g, b) {9066var max = Math.max(r, g, b),9067min = Math.min(r, g, b),9068delta = max - min,9069achromatic = delta === 0,9070h = achromatic ? 09071: ( max == r ? (g - b) / delta + (g < b ? 6 : 0)9072: max == g ? (b - r) / delta + 29073: (r - g) / delta + 4) * 60,9074l = (max + min) / 2,9075s = achromatic ? 0 : l < 0.59076? delta / (max + min)9077: delta / (2 - max - min);9078return [h, s, l];9079},90809081'hsl-rgb': function(h, s, l) {9082h = (((h / 360) % 1) + 1) % 1;9083if (s === 0)9084return [l, l, l];9085var t3s = [ h + 1 / 3, h, h - 1 / 3 ],9086t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,9087t1 = 2 * l - t2,9088c = [];9089for (var i = 0; i < 3; i++) {9090var t3 = t3s[i];9091if (t3 < 0) t3 += 1;9092if (t3 > 1) t3 -= 1;9093c[i] = 6 * t3 < 19094? t1 + (t2 - t1) * 6 * t39095: 2 * t3 < 19096? t29097: 3 * t3 < 29098? t1 + (t2 - t1) * ((2 / 3) - t3) * 69099: t1;9100}9101return c;9102},91039104'rgb-gray': function(r, g, b) {9105return [r * 0.2989 + g * 0.587 + b * 0.114];9106},91079108'gray-rgb': function(g) {9109return [g, g, g];9110},91119112'gray-hsb': function(g) {9113return [0, 0, g];9114},91159116'gray-hsl': function(g) {9117return [0, 0, g];9118},91199120'gradient-rgb': function() {9121return [];9122},91239124'rgb-gradient': function() {9125return [];9126}91279128};91299130return Base.each(types, function(properties, type) {9131componentParsers[type] = [];9132Base.each(properties, function(name, index) {9133var part = Base.capitalize(name),9134hasOverlap = /^(hue|saturation)$/.test(name),9135parser = componentParsers[type][index] = name === 'gradient'9136? function(value) {9137var current = this._components[0];9138value = Gradient.read(Array.isArray(value) ? value9139: arguments, 0, { readNull: true });9140if (current !== value) {9141if (current)9142current._removeOwner(this);9143if (value)9144value._addOwner(this);9145}9146return value;9147}9148: type === 'gradient'9149? function() {9150return Point.read(arguments, 0, {9151readNull: name === 'highlight',9152clone: true9153});9154}9155: function(value) {9156return value == null || isNaN(value) ? 0 : value;9157};91589159this['get' + part] = function() {9160return this._type === type9161|| hasOverlap && /^hs[bl]$/.test(this._type)9162? this._components[index]9163: this._convert(type)[index];9164};91659166this['set' + part] = function(value) {9167if (this._type !== type9168&& !(hasOverlap && /^hs[bl]$/.test(this._type))) {9169this._components = this._convert(type);9170this._properties = types[type];9171this._type = type;9172}9173value = parser.call(this, value);9174if (value != null) {9175this._components[index] = value;9176this._changed();9177}9178};9179}, this);9180}, {9181_class: 'Color',9182_readIndex: true,91839184initialize: function Color(arg) {9185var slice = Array.prototype.slice,9186args = arguments,9187read = 0,9188type,9189components,9190alpha,9191values;9192if (Array.isArray(arg)) {9193args = arg;9194arg = args[0];9195}9196var argType = arg != null && typeof arg;9197if (argType === 'string' && arg in types) {9198type = arg;9199arg = args[1];9200if (Array.isArray(arg)) {9201components = arg;9202alpha = args[2];9203} else {9204if (this.__read)9205read = 1;9206args = slice.call(args, 1);9207argType = typeof arg;9208}9209}9210if (!components) {9211values = argType === 'number'9212? args9213: argType === 'object' && arg.length != null9214? arg9215: null;9216if (values) {9217if (!type)9218type = values.length >= 39219? 'rgb'9220: 'gray';9221var length = types[type].length;9222alpha = values[length];9223if (this.__read)9224read += values === arguments9225? length + (alpha != null ? 1 : 0)9226: 1;9227if (values.length > length)9228values = slice.call(values, 0, length);9229} else if (argType === 'string') {9230type = 'rgb';9231components = fromCSS(arg);9232if (components.length === 4) {9233alpha = components[3];9234components.length--;9235}9236} else if (argType === 'object') {9237if (arg.constructor === Color) {9238type = arg._type;9239components = arg._components.slice();9240alpha = arg._alpha;9241if (type === 'gradient') {9242for (var i = 1, l = components.length; i < l; i++) {9243var point = components[i];9244if (point)9245components[i] = point.clone();9246}9247}9248} else if (arg.constructor === Gradient) {9249type = 'gradient';9250values = args;9251} else {9252type = 'hue' in arg9253? 'lightness' in arg9254? 'hsl'9255: 'hsb'9256: 'gradient' in arg || 'stops' in arg9257|| 'radial' in arg9258? 'gradient'9259: 'gray' in arg9260? 'gray'9261: 'rgb';9262var properties = types[type];9263parsers = componentParsers[type];9264this._components = components = [];9265for (var i = 0, l = properties.length; i < l; i++) {9266var value = arg[properties[i]];9267if (value == null && i === 0 && type === 'gradient'9268&& 'stops' in arg) {9269value = {9270stops: arg.stops,9271radial: arg.radial9272};9273}9274value = parsers[i].call(this, value);9275if (value != null)9276components[i] = value;9277}9278alpha = arg.alpha;9279}9280}9281if (this.__read && type)9282read = 1;9283}9284this._type = type || 'rgb';9285if (type === 'gradient')9286this._id = Color._id = (Color._id || 0) + 1;9287if (!components) {9288this._components = components = [];9289var parsers = componentParsers[this._type];9290for (var i = 0, l = parsers.length; i < l; i++) {9291var value = parsers[i].call(this, values && values[i]);9292if (value != null)9293components[i] = value;9294}9295}9296this._components = components;9297this._properties = types[this._type];9298this._alpha = alpha;9299if (this.__read)9300this.__read = read;9301},93029303_serialize: function(options, dictionary) {9304var components = this.getComponents();9305return Base.serialize(9306/^(gray|rgb)$/.test(this._type)9307? components9308: [this._type].concat(components),9309options, true, dictionary);9310},93119312_changed: function() {9313this._canvasStyle = null;9314if (this._owner)9315this._owner._changed(65);9316},93179318_convert: function(type) {9319var converter;9320return this._type === type9321? this._components.slice()9322: (converter = converters[this._type + '-' + type])9323? converter.apply(this, this._components)9324: converters['rgb-' + type].apply(this,9325converters[this._type + '-rgb'].apply(this,9326this._components));9327},93289329convert: function(type) {9330return new Color(type, this._convert(type), this._alpha);9331},93329333getType: function() {9334return this._type;9335},93369337setType: function(type) {9338this._components = this._convert(type);9339this._properties = types[type];9340this._type = type;9341},93429343getComponents: function() {9344var components = this._components.slice();9345if (this._alpha != null)9346components.push(this._alpha);9347return components;9348},93499350getAlpha: function() {9351return this._alpha != null ? this._alpha : 1;9352},93539354setAlpha: function(alpha) {9355this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);9356this._changed();9357},93589359hasAlpha: function() {9360return this._alpha != null;9361},93629363equals: function(color) {9364var col = Base.isPlainValue(color)9365? Color.read(arguments)9366: color;9367return col === this || col && this._class === col._class9368&& this._type === col._type9369&& this._alpha === col._alpha9370&& Base.equals(this._components, col._components)9371|| false;9372},93739374toString: function() {9375var properties = this._properties,9376parts = [],9377isGradient = this._type === 'gradient',9378f = Formatter.instance;9379for (var i = 0, l = properties.length; i < l; i++) {9380var value = this._components[i];9381if (value != null)9382parts.push(properties[i] + ': '9383+ (isGradient ? value : f.number(value)));9384}9385if (this._alpha != null)9386parts.push('alpha: ' + f.number(this._alpha));9387return '{ ' + parts.join(', ') + ' }';9388},93899390toCSS: function(hex) {9391var components = this._convert('rgb'),9392alpha = hex || this._alpha == null ? 1 : this._alpha;9393function convert(val) {9394return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255);9395}9396components = [9397convert(components[0]),9398convert(components[1]),9399convert(components[2])9400];9401if (alpha < 1)9402components.push(alpha < 0 ? 0 : alpha);9403return hex9404? '#' + ((1 << 24) + (components[0] << 16)9405+ (components[1] << 8)9406+ components[2]).toString(16).slice(1)9407: (components.length == 4 ? 'rgba(' : 'rgb(')9408+ components.join(',') + ')';9409},94109411toCanvasStyle: function(ctx) {9412if (this._canvasStyle)9413return this._canvasStyle;9414if (this._type !== 'gradient')9415return this._canvasStyle = this.toCSS();9416var components = this._components,9417gradient = components[0],9418stops = gradient._stops,9419origin = components[1],9420destination = components[2],9421canvasGradient;9422if (gradient._radial) {9423var radius = destination.getDistance(origin),9424highlight = components[3];9425if (highlight) {9426var vector = highlight.subtract(origin);9427if (vector.getLength() > radius)9428highlight = origin.add(vector.normalize(radius - 0.1));9429}9430var start = highlight || origin;9431canvasGradient = ctx.createRadialGradient(start.x, start.y,94320, origin.x, origin.y, radius);9433} else {9434canvasGradient = ctx.createLinearGradient(origin.x, origin.y,9435destination.x, destination.y);9436}9437for (var i = 0, l = stops.length; i < l; i++) {9438var stop = stops[i];9439canvasGradient.addColorStop(stop._rampPoint,9440stop._color.toCanvasStyle());9441}9442return this._canvasStyle = canvasGradient;9443},94449445transform: function(matrix) {9446if (this._type === 'gradient') {9447var components = this._components;9448for (var i = 1, l = components.length; i < l; i++) {9449var point = components[i];9450matrix._transformPoint(point, point, true);9451}9452this._changed();9453}9454},94559456statics: {9457_types: types,94589459random: function() {9460var random = Math.random;9461return new Color(random(), random(), random());9462}9463}9464});9465}, new function() {9466var operators = {9467add: function(a, b) {9468return a + b;9469},94709471subtract: function(a, b) {9472return a - b;9473},94749475multiply: function(a, b) {9476return a * b;9477},94789479divide: function(a, b) {9480return a / b;9481}9482};94839484return Base.each(operators, function(operator, name) {9485this[name] = function(color) {9486color = Color.read(arguments);9487var type = this._type,9488components1 = this._components,9489components2 = color._convert(type);9490for (var i = 0, l = components1.length; i < l; i++)9491components2[i] = operator(components1[i], components2[i]);9492return new Color(type, components2,9493this._alpha != null9494? operator(this._alpha, color.getAlpha())9495: null);9496};9497}, {9498});9499});95009501Base.each(Color._types, function(properties, type) {9502var ctor = this[Base.capitalize(type) + 'Color'] = function(arg) {9503var argType = arg != null && typeof arg,9504components = argType === 'object' && arg.length != null9505? arg9506: argType === 'string'9507? null9508: arguments;9509return components9510? new Color(type, components)9511: new Color(arg);9512};9513if (type.length == 3) {9514var acronym = type.toUpperCase();9515Color[acronym] = this[acronym + 'Color'] = ctor;9516}9517}, Base.exports);95189519var Gradient = Base.extend({9520_class: 'Gradient',95219522initialize: function Gradient(stops, radial) {9523this._id = Gradient._id = (Gradient._id || 0) + 1;9524if (stops && this._set(stops))9525stops = radial = null;9526if (!this._stops)9527this.setStops(stops || ['white', 'black']);9528if (this._radial == null)9529this.setRadial(typeof radial === 'string' && radial === 'radial'9530|| radial || false);9531},95329533_serialize: function(options, dictionary) {9534return dictionary.add(this, function() {9535return Base.serialize([this._stops, this._radial],9536options, true, dictionary);9537});9538},95399540_changed: function() {9541for (var i = 0, l = this._owners && this._owners.length; i < l; i++)9542this._owners[i]._changed();9543},95449545_addOwner: function(color) {9546if (!this._owners)9547this._owners = [];9548this._owners.push(color);9549},95509551_removeOwner: function(color) {9552var index = this._owners ? this._owners.indexOf(color) : -1;9553if (index != -1) {9554this._owners.splice(index, 1);9555if (this._owners.length === 0)9556this._owners = undefined;9557}9558},95599560clone: function() {9561var stops = [];9562for (var i = 0, l = this._stops.length; i < l; i++)9563stops[i] = this._stops[i].clone();9564return new Gradient(stops);9565},95669567getStops: function() {9568return this._stops;9569},95709571setStops: function(stops) {9572if (this.stops) {9573for (var i = 0, l = this._stops.length; i < l; i++)9574this._stops[i]._owner = undefined;9575}9576if (stops.length < 2)9577throw new Error(9578'Gradient stop list needs to contain at least two stops.');9579this._stops = GradientStop.readAll(stops, 0, { clone: true });9580for (var i = 0, l = this._stops.length; i < l; i++) {9581var stop = this._stops[i];9582stop._owner = this;9583if (stop._defaultRamp)9584stop.setRampPoint(i / (l - 1));9585}9586this._changed();9587},95889589getRadial: function() {9590return this._radial;9591},95929593setRadial: function(radial) {9594this._radial = radial;9595this._changed();9596},95979598equals: function(gradient) {9599if (gradient === this)9600return true;9601if (gradient && this._class === gradient._class9602&& this._stops.length === gradient._stops.length) {9603for (var i = 0, l = this._stops.length; i < l; i++) {9604if (!this._stops[i].equals(gradient._stops[i]))9605return false;9606}9607return true;9608}9609return false;9610}9611});96129613var GradientStop = Base.extend({9614_class: 'GradientStop',96159616initialize: function GradientStop(arg0, arg1) {9617if (arg0) {9618var color, rampPoint;9619if (arg1 === undefined && Array.isArray(arg0)) {9620color = arg0[0];9621rampPoint = arg0[1];9622} else if (arg0.color) {9623color = arg0.color;9624rampPoint = arg0.rampPoint;9625} else {9626color = arg0;9627rampPoint = arg1;9628}9629this.setColor(color);9630this.setRampPoint(rampPoint);9631}9632},96339634clone: function() {9635return new GradientStop(this._color.clone(), this._rampPoint);9636},96379638_serialize: function(options, dictionary) {9639return Base.serialize([this._color, this._rampPoint], options, true,9640dictionary);9641},96429643_changed: function() {9644if (this._owner)9645this._owner._changed(65);9646},96479648getRampPoint: function() {9649return this._rampPoint;9650},96519652setRampPoint: function(rampPoint) {9653this._defaultRamp = rampPoint == null;9654this._rampPoint = rampPoint || 0;9655this._changed();9656},96579658getColor: function() {9659return this._color;9660},96619662setColor: function(color) {9663this._color = Color.read(arguments);9664if (this._color === color)9665this._color = color.clone();9666this._color._owner = this;9667this._changed();9668},96699670equals: function(stop) {9671return stop === this || stop && this._class === stop._class9672&& this._color.equals(stop._color)9673&& this._rampPoint == stop._rampPoint9674|| false;9675}9676});96779678var Style = Base.extend(new function() {9679var defaults = {9680fillColor: undefined,9681strokeColor: undefined,9682strokeWidth: 1,9683strokeCap: 'butt',9684strokeJoin: 'miter',9685miterLimit: 10,9686dashOffset: 0,9687dashArray: [],9688windingRule: 'nonzero',9689shadowColor: undefined,9690shadowBlur: 0,9691shadowOffset: new Point(),9692selectedColor: undefined,9693fontFamily: 'sans-serif',9694fontWeight: 'normal',9695fontSize: 12,9696font: 'sans-serif',9697leading: null,9698justification: 'left'9699};97009701var flags = {9702strokeWidth: 97,9703strokeCap: 97,9704strokeJoin: 97,9705miterLimit: 97,9706fontFamily: 9,9707fontWeight: 9,9708fontSize: 9,9709font: 9,9710leading: 9,9711justification: 99712};97139714var item = {},9715fields = {9716_defaults: defaults,9717_textDefaults: new Base(defaults, {9718fillColor: new Color()9719}),9720beans: true9721};97229723Base.each(defaults, function(value, key) {9724var isColor = /Color$/.test(key),9725part = Base.capitalize(key),9726flag = flags[key],9727set = 'set' + part,9728get = 'get' + part;97299730fields[set] = function(value) {9731var owner = this._owner,9732children = owner && owner._children;9733if (children && children.length > 09734&& !(owner instanceof CompoundPath)) {9735for (var i = 0, l = children.length; i < l; i++)9736children[i]._style[set](value);9737} else {9738var old = this._values[key];9739if (old != value) {9740if (isColor) {9741if (old)9742old._owner = undefined;9743if (value && value.constructor === Color) {9744if (value._owner)9745value = value.clone();9746value._owner = owner;9747}9748}9749this._values[key] = value;9750if (owner)9751owner._changed(flag || 65);9752}9753}9754};97559756fields[get] = function(_dontMerge) {9757var owner = this._owner,9758children = owner && owner._children,9759value;9760if (!children || children.length === 0 || _dontMerge9761|| owner instanceof CompoundPath) {9762var value = this._values[key];9763if (value === undefined) {9764value = this._defaults[key];9765if (value && value.clone)9766value = value.clone();9767this._values[key] = value;9768} else if (isColor && !(value && value.constructor === Color)) {9769this._values[key] = value = Color.read([value], 0,9770{ readNull: true, clone: true });9771if (value)9772value._owner = owner;9773}9774return value;9775}9776for (var i = 0, l = children.length; i < l; i++) {9777var childValue = children[i]._style[get]();9778if (i === 0) {9779value = childValue;9780} else if (!Base.equals(value, childValue)) {9781return undefined;9782}9783}9784return value;9785};97869787item[get] = function() {9788return this._style[get]();9789};97909791item[set] = function(value) {9792this._style[set](value);9793};9794});97959796Item.inject(item);9797return fields;9798}, {9799_class: 'Style',98009801initialize: function Style(style, _owner, _project) {9802this._values = {};9803this._owner = _owner;9804this._project = _owner && _owner._project || _project || paper.project;9805if (_owner instanceof TextItem)9806this._defaults = this._textDefaults;9807if (style)9808this.set(style);9809},98109811set: function(style) {9812var isStyle = style instanceof Style,9813values = isStyle ? style._values : style;9814if (values) {9815for (var key in values) {9816if (key in this._defaults) {9817var value = values[key];9818this[key] = value && isStyle && value.clone9819? value.clone() : value;9820}9821}9822}9823},98249825equals: function(style) {9826return style === this || style && this._class === style._class9827&& Base.equals(this._values, style._values)9828|| false;9829},98309831hasFill: function() {9832return !!this.getFillColor();9833},98349835hasStroke: function() {9836return !!this.getStrokeColor() && this.getStrokeWidth() > 0;9837},98389839hasShadow: function() {9840return !!this.getShadowColor() && this.getShadowBlur() > 0;9841},98429843getView: function() {9844return this._project.getView();9845},98469847getFontStyle: function() {9848var fontSize = this.getFontSize();9849return this.getFontWeight()9850+ ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ')9851+ this.getFontFamily();9852},98539854getFont: '#getFontFamily',9855setFont: '#setFontFamily',98569857getLeading: function getLeading() {9858var leading = getLeading.base.call(this),9859fontSize = this.getFontSize();9860if (/pt|em|%|px/.test(fontSize))9861fontSize = this.getView().getPixelSize(fontSize);9862return leading != null ? leading : fontSize * 1.2;9863}98649865});98669867var DomElement = new function() {98689869var special = /^(checked|value|selected|disabled)$/i,9870translated = { text: 'textContent', html: 'innerHTML' },9871unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1 };98729873function create(nodes, parent) {9874var res = [];9875for (var i = 0, l = nodes && nodes.length; i < l;) {9876var el = nodes[i++];9877if (typeof el === 'string') {9878el = document.createElement(el);9879} else if (!el || !el.nodeType) {9880continue;9881}9882if (Base.isPlainObject(nodes[i]))9883DomElement.set(el, nodes[i++]);9884if (Array.isArray(nodes[i]))9885create(nodes[i++], el);9886if (parent)9887parent.appendChild(el);9888res.push(el);9889}9890return res;9891}98929893function handlePrefix(el, name, set, value) {9894var prefixes = ['webkit', 'moz', 'Moz', 'ms', 'o', ''],9895suffix = name[0].toUpperCase() + name.substring(1);9896for (var i = 0; i < 6; i++) {9897var prefix = prefixes[i],9898key = prefix ? prefix + suffix : name;9899if (key in el) {9900if (set) {9901el[key] = value;9902} else {9903return el[key];9904}9905break;9906}9907}9908}99099910return {9911create: function(nodes, parent) {9912var isArray = Array.isArray(nodes),9913res = create(isArray ? nodes : arguments, isArray ? parent : null);9914return res.length == 1 ? res[0] : res;9915},99169917find: function(selector, root) {9918return (root || document).querySelector(selector);9919},99209921findAll: function(selector, root) {9922return (root || document).querySelectorAll(selector);9923},99249925get: function(el, key) {9926return el9927? special.test(key)9928? key === 'value' || typeof el[key] !== 'string'9929? el[key]9930: true9931: key in translated9932? el[translated[key]]9933: el.getAttribute(key)9934: null;9935},99369937set: function(el, key, value) {9938if (typeof key !== 'string') {9939for (var name in key)9940if (key.hasOwnProperty(name))9941this.set(el, name, key[name]);9942} else if (!el || value === undefined) {9943return el;9944} else if (special.test(key)) {9945el[key] = value;9946} else if (key in translated) {9947el[translated[key]] = value;9948} else if (key === 'style') {9949this.setStyle(el, value);9950} else if (key === 'events') {9951DomEvent.add(el, value);9952} else {9953el.setAttribute(key, value);9954}9955return el;9956},99579958getStyles: function(el) {9959var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,9960view = doc && doc.defaultView;9961return view && view.getComputedStyle(el, '');9962},99639964getStyle: function(el, key) {9965return el && el.style[key] || this.getStyles(el)[key] || null;9966},99679968setStyle: function(el, key, value) {9969if (typeof key !== 'string') {9970for (var name in key)9971if (key.hasOwnProperty(name))9972this.setStyle(el, name, key[name]);9973} else {9974if (/^-?[\d\.]+$/.test(value) && !(key in unitless))9975value += 'px';9976el.style[key] = value;9977}9978return el;9979},99809981hasClass: function(el, cls) {9982return new RegExp('\\s*' + cls + '\\s*').test(el.className);9983},99849985addClass: function(el, cls) {9986el.className = (el.className + ' ' + cls).trim();9987},99889989removeClass: function(el, cls) {9990el.className = el.className.replace(9991new RegExp('\\s*' + cls + '\\s*'), ' ').trim();9992},99939994remove: function(el) {9995if (el.parentNode)9996el.parentNode.removeChild(el);9997},99989999removeChildren: function(el) {10000while (el.firstChild)10001el.removeChild(el.firstChild);10002},1000310004getBounds: function(el, viewport) {10005var doc = el.ownerDocument,10006body = doc.body,10007html = doc.documentElement,10008rect;10009try {10010rect = el.getBoundingClientRect();10011} catch (e) {10012rect = { left: 0, top: 0, width: 0, height: 0 };10013}10014var x = rect.left - (html.clientLeft || body.clientLeft || 0),10015y = rect.top - (html.clientTop || body.clientTop || 0);10016if (!viewport) {10017var view = doc.defaultView;10018x += view.pageXOffset || html.scrollLeft || body.scrollLeft;10019y += view.pageYOffset || html.scrollTop || body.scrollTop;10020}10021return new Rectangle(x, y, rect.width, rect.height);10022},1002310024getViewportBounds: function(el) {10025var doc = el.ownerDocument,10026view = doc.defaultView,10027html = doc.documentElement;10028return new Rectangle(0, 0,10029view.innerWidth || html.clientWidth,10030view.innerHeight || html.clientHeight10031);10032},1003310034getOffset: function(el, viewport) {10035return this.getBounds(el, viewport).getPoint();10036},1003710038getSize: function(el) {10039return this.getBounds(el, true).getSize();10040},1004110042isInvisible: function(el) {10043return this.getSize(el).equals(new Size(0, 0));10044},1004510046isInView: function(el) {10047return !this.isInvisible(el) && this.getViewportBounds(el).intersects(10048this.getBounds(el, true));10049},1005010051getPrefixed: function(el, name) {10052return handlePrefix(el, name);10053},1005410055setPrefixed: function(el, name, value) {10056if (typeof name === 'object') {10057for (var key in name)10058handlePrefix(el, key, true, name[key]);10059} else {10060handlePrefix(el, name, true, value);10061}10062}10063};10064};1006510066var DomEvent = {10067add: function(el, events) {10068for (var type in events) {10069var func = events[type],10070parts = type.split(/[\s,]+/g);10071for (var i = 0, l = parts.length; i < l; i++)10072el.addEventListener(parts[i], func, false);10073}10074},1007510076remove: function(el, events) {10077for (var type in events) {10078var func = events[type],10079parts = type.split(/[\s,]+/g);10080for (var i = 0, l = parts.length; i < l; i++)10081el.removeEventListener(parts[i], func, false);10082}10083},1008410085getPoint: function(event) {10086var pos = event.targetTouches10087? event.targetTouches.length10088? event.targetTouches[0]10089: event.changedTouches[0]10090: event;10091return new Point(10092pos.pageX || pos.clientX + document.documentElement.scrollLeft,10093pos.pageY || pos.clientY + document.documentElement.scrollTop10094);10095},1009610097getTarget: function(event) {10098return event.target || event.srcElement;10099},1010010101getRelatedTarget: function(event) {10102return event.relatedTarget || event.toElement;10103},1010410105getOffset: function(event, target) {10106return DomEvent.getPoint(event).subtract(DomElement.getOffset(10107target || DomEvent.getTarget(event)));10108},1010910110stop: function(event) {10111event.stopPropagation();10112event.preventDefault();10113}10114};1011510116DomEvent.requestAnimationFrame = new function() {10117var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'),10118requested = false,10119callbacks = [],10120focused = true,10121timer;1012210123DomEvent.add(window, {10124focus: function() {10125focused = true;10126},10127blur: function() {10128focused = false;10129}10130});1013110132function handleCallbacks() {10133for (var i = callbacks.length - 1; i >= 0; i--) {10134var entry = callbacks[i],10135func = entry[0],10136el = entry[1];10137if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true'10138|| focused) && DomElement.isInView(el)) {10139callbacks.splice(i, 1);10140func();10141}10142}10143if (nativeRequest) {10144if (callbacks.length) {10145nativeRequest(handleCallbacks);10146} else {10147requested = false;10148}10149}10150}1015110152return function(callback, element) {10153callbacks.push([callback, element]);10154if (nativeRequest) {10155if (!requested) {10156nativeRequest(handleCallbacks);10157requested = true;10158}10159} else if (!timer) {10160timer = setInterval(handleCallbacks, 1000 / 60);10161}10162};10163};1016410165var View = Base.extend(Callback, {10166_class: 'View',1016710168initialize: function View(project, element) {10169this._project = project;10170this._scope = project._scope;10171this._element = element;10172var size;10173if (!this._pixelRatio)10174this._pixelRatio = window.devicePixelRatio || 1;10175this._id = element.getAttribute('id');10176if (this._id == null)10177element.setAttribute('id', this._id = 'view-' + View._id++);10178DomEvent.add(element, this._viewEvents);10179var none = 'none';10180DomElement.setPrefixed(element.style, {10181userSelect: none,10182touchAction: none,10183touchCallout: none,10184contentZooming: none,10185userDrag: none,10186tapHighlightColor: 'rgba(0,0,0,0)'10187});10188if (PaperScope.hasAttribute(element, 'resize')) {10189var offset = DomElement.getOffset(element, true),10190that = this;10191size = DomElement.getViewportBounds(element)10192.getSize().subtract(offset);10193this._windowEvents = {10194resize: function() {10195if (!DomElement.isInvisible(element))10196offset = DomElement.getOffset(element, true);10197that.setViewSize(DomElement.getViewportBounds(element)10198.getSize().subtract(offset));10199}10200};10201DomEvent.add(window, this._windowEvents);10202} else {10203size = DomElement.getSize(element);10204if (size.isNaN() || size.isZero()) {10205var getSize = function(name) {10206return element[name]10207|| parseInt(element.getAttribute(name), 10);10208};10209size = new Size(getSize('width'), getSize('height'));10210}10211}10212this._setViewSize(size);10213if (PaperScope.hasAttribute(element, 'stats')10214&& typeof Stats !== 'undefined') {10215this._stats = new Stats();10216var stats = this._stats.domElement,10217style = stats.style,10218offset = DomElement.getOffset(element);10219style.position = 'absolute';10220style.left = offset.x + 'px';10221style.top = offset.y + 'px';10222document.body.appendChild(stats);10223}10224View._views.push(this);10225View._viewsById[this._id] = this;10226this._viewSize = size;10227(this._matrix = new Matrix())._owner = this;10228this._zoom = 1;10229if (!View._focused)10230View._focused = this;10231this._frameItems = {};10232this._frameItemCount = 0;10233},1023410235remove: function() {10236if (!this._project)10237return false;10238if (View._focused === this)10239View._focused = null;10240View._views.splice(View._views.indexOf(this), 1);10241delete View._viewsById[this._id];10242if (this._project._view === this)10243this._project._view = null;10244DomEvent.remove(this._element, this._viewEvents);10245DomEvent.remove(window, this._windowEvents);10246this._element = this._project = null;10247this.detach('frame');10248this._animate = false;10249this._frameItems = {};10250return true;10251},1025210253_events: {10254onFrame: {10255install: function() {10256this.play();10257},1025810259uninstall: function() {10260this.pause();10261}10262},1026310264onResize: {}10265},1026610267_animate: false,10268_time: 0,10269_count: 0,1027010271_requestFrame: function() {10272var that = this;10273DomEvent.requestAnimationFrame(function() {10274that._requested = false;10275if (!that._animate)10276return;10277that._requestFrame();10278that._handleFrame();10279}, this._element);10280this._requested = true;10281},1028210283_handleFrame: function() {10284paper = this._scope;10285var now = Date.now() / 1000,10286delta = this._before ? now - this._before : 0;10287this._before = now;10288this._handlingFrame = true;10289this.fire('frame', new Base({10290delta: delta,10291time: this._time += delta,10292count: this._count++10293}));10294if (this._stats)10295this._stats.update();10296this._handlingFrame = false;10297this.update();10298},1029910300_animateItem: function(item, animate) {10301var items = this._frameItems;10302if (animate) {10303items[item._id] = {10304item: item,10305time: 0,10306count: 010307};10308if (++this._frameItemCount === 1)10309this.attach('frame', this._handleFrameItems);10310} else {10311delete items[item._id];10312if (--this._frameItemCount === 0) {10313this.detach('frame', this._handleFrameItems);10314}10315}10316},1031710318_handleFrameItems: function(event) {10319for (var i in this._frameItems) {10320var entry = this._frameItems[i];10321entry.item.fire('frame', new Base(event, {10322time: entry.time += event.delta,10323count: entry.count++10324}));10325}10326},1032710328_update: function() {10329this._project._needsUpdate = true;10330if (this._handlingFrame)10331return;10332if (this._animate) {10333this._handleFrame();10334} else {10335this.update();10336}10337},1033810339_changed: function(flags) {10340if (flags & 1)10341this._project._needsUpdate = true;10342},1034310344_transform: function(matrix) {10345this._matrix.concatenate(matrix);10346this._bounds = null;10347this._update();10348},1034910350getElement: function() {10351return this._element;10352},1035310354getPixelRatio: function() {10355return this._pixelRatio;10356},1035710358getResolution: function() {10359return this._pixelRatio * 72;10360},1036110362getViewSize: function() {10363var size = this._viewSize;10364return new LinkedSize(size.width, size.height, this, 'setViewSize');10365},1036610367setViewSize: function() {10368var size = Size.read(arguments),10369delta = size.subtract(this._viewSize);10370if (delta.isZero())10371return;10372this._viewSize.set(size.width, size.height);10373this._setViewSize(size);10374this._bounds = null;10375this.fire('resize', {10376size: size,10377delta: delta10378});10379this._update();10380},1038110382_setViewSize: function(size) {10383var element = this._element;10384element.width = size.width;10385element.height = size.height;10386},1038710388getBounds: function() {10389if (!this._bounds)10390this._bounds = this._matrix.inverted()._transformBounds(10391new Rectangle(new Point(), this._viewSize));10392return this._bounds;10393},1039410395getSize: function() {10396return this.getBounds().getSize();10397},1039810399getCenter: function() {10400return this.getBounds().getCenter();10401},1040210403setCenter: function(center) {10404center = Point.read(arguments);10405this.scrollBy(center.subtract(this.getCenter()));10406},1040710408getZoom: function() {10409return this._zoom;10410},1041110412setZoom: function(zoom) {10413this._transform(new Matrix().scale(zoom / this._zoom,10414this.getCenter()));10415this._zoom = zoom;10416},1041710418isVisible: function() {10419return DomElement.isInView(this._element);10420},1042110422scrollBy: function() {10423this._transform(new Matrix().translate(Point.read(arguments).negate()));10424},1042510426play: function() {10427this._animate = true;10428if (!this._requested)10429this._requestFrame();10430},1043110432pause: function() {10433this._animate = false;10434},1043510436draw: function() {10437this.update();10438},1043910440projectToView: function() {10441return this._matrix._transformPoint(Point.read(arguments));10442},1044310444viewToProject: function() {10445return this._matrix._inverseTransform(Point.read(arguments));10446}1044710448}, {10449statics: {10450_views: [],10451_viewsById: {},10452_id: 0,1045310454create: function(project, element) {10455if (typeof element === 'string')10456element = document.getElementById(element);10457return new CanvasView(project, element);10458}10459}10460}, new function() {10461var tool,10462prevFocus,10463tempFocus,10464dragging = false;1046510466function getView(event) {10467var target = DomEvent.getTarget(event);10468return target.getAttribute && View._viewsById[target.getAttribute('id')];10469}1047010471function viewToProject(view, event) {10472return view.viewToProject(DomEvent.getOffset(event, view._element));10473}1047410475function updateFocus() {10476if (!View._focused || !View._focused.isVisible()) {10477for (var i = 0, l = View._views.length; i < l; i++) {10478var view = View._views[i];10479if (view && view.isVisible()) {10480View._focused = tempFocus = view;10481break;10482}10483}10484}10485}1048610487function handleMouseMove(view, point, event) {10488view._handleEvent('mousemove', point, event);10489var tool = view._scope.tool;10490if (tool) {10491tool._handleEvent(dragging && tool.responds('mousedrag')10492? 'mousedrag' : 'mousemove', point, event);10493}10494view.update();10495return tool;10496}1049710498var navigator = window.navigator,10499mousedown, mousemove, mouseup;10500if (navigator.pointerEnabled || navigator.msPointerEnabled) {10501mousedown = 'pointerdown MSPointerDown';10502mousemove = 'pointermove MSPointerMove';10503mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel';10504} else {10505mousedown = 'touchstart';10506mousemove = 'touchmove';10507mouseup = 'touchend touchcancel';10508if (!('ontouchstart' in window && navigator.userAgent.match(10509/mobile|tablet|ip(ad|hone|od)|android|silk/i))) {10510mousedown += ' mousedown';10511mousemove += ' mousemove';10512mouseup += ' mouseup';10513}10514}1051510516var viewEvents = {10517'selectstart dragstart': function(event) {10518if (dragging)10519event.preventDefault();10520}10521};1052210523var docEvents = {10524mouseout: function(event) {10525var view = View._focused,10526target = DomEvent.getRelatedTarget(event);10527if (view && (!target || target.nodeName === 'HTML'))10528handleMouseMove(view, viewToProject(view, event), event);10529},1053010531scroll: updateFocus10532};1053310534viewEvents[mousedown] = function(event) {10535var view = View._focused = getView(event),10536point = viewToProject(view, event);10537dragging = true;10538view._handleEvent('mousedown', point, event);10539if (tool = view._scope.tool)10540tool._handleEvent('mousedown', point, event);10541view.update();10542};1054310544docEvents[mousemove] = function(event) {10545var view = View._focused;10546if (!dragging) {10547var target = getView(event);10548if (target) {10549if (view !== target)10550handleMouseMove(view, viewToProject(view, event), event);10551prevFocus = view;10552view = View._focused = tempFocus = target;10553} else if (tempFocus && tempFocus === view) {10554view = View._focused = prevFocus;10555updateFocus();10556}10557}10558if (view) {10559var point = viewToProject(view, event);10560if (dragging || view.getBounds().contains(point))10561tool = handleMouseMove(view, point, event);10562}10563};1056410565docEvents[mouseup] = function(event) {10566var view = View._focused;10567if (!view || !dragging)10568return;10569var point = viewToProject(view, event);10570dragging = false;10571view._handleEvent('mouseup', point, event);10572if (tool)10573tool._handleEvent('mouseup', point, event);10574view.update();10575};1057610577DomEvent.add(document, docEvents);1057810579DomEvent.add(window, {10580load: updateFocus10581});1058210583return {10584_viewEvents: viewEvents,1058510586_handleEvent: function() {},1058710588statics: {10589updateFocus: updateFocus10590}10591};10592});1059310594var CanvasView = View.extend({10595_class: 'CanvasView',1059610597initialize: function CanvasView(project, canvas) {10598if (!(canvas instanceof HTMLCanvasElement)) {10599var size = Size.read(arguments);10600if (size.isZero())10601throw new Error(10602'Cannot create CanvasView with the provided argument: '10603+ canvas);10604canvas = CanvasProvider.getCanvas(size);10605}10606this._context = canvas.getContext('2d');10607this._eventCounters = {};10608this._pixelRatio = 1;10609if (PaperScope.getAttribute(canvas, 'hidpi') !== 'off') {10610var deviceRatio = window.devicePixelRatio || 1,10611backingStoreRatio = DomElement.getPrefixed(this._context,10612'backingStorePixelRatio') || 1;10613this._pixelRatio = deviceRatio / backingStoreRatio;10614}10615View.call(this, project, canvas);10616},1061710618_setViewSize: function(size) {10619var width = size.width,10620height = size.height,10621pixelRatio = this._pixelRatio,10622element = this._element,10623style = element.style;10624element.width = width * pixelRatio;10625element.height = height * pixelRatio;10626if (pixelRatio !== 1) {10627style.width = width + 'px';10628style.height = height + 'px';10629this._context.scale(pixelRatio, pixelRatio);10630}10631},1063210633getPixelSize: function(size) {10634var ctx = this._context,10635prevFont = ctx.font;10636ctx.font = size + ' serif';10637size = parseFloat(ctx.font);10638ctx.font = prevFont;10639return size;10640},1064110642getTextWidth: function(font, lines) {10643var ctx = this._context,10644prevFont = ctx.font,10645width = 0;10646ctx.font = font;10647for (var i = 0, l = lines.length; i < l; i++)10648width = Math.max(width, ctx.measureText(lines[i]).width);10649ctx.font = prevFont;10650return width;10651},1065210653update: function() {10654var project = this._project;10655if (!project || !project._needsUpdate)10656return false;10657var ctx = this._context,10658size = this._viewSize;10659ctx.clearRect(0, 0, size.width + 1, size.height + 1);10660project.draw(ctx, this._matrix, this._pixelRatio);10661project._needsUpdate = false;10662return true;10663}10664}, new function() {1066510666var downPoint,10667lastPoint,10668overPoint,10669downItem,10670lastItem,10671overItem,10672dragItem,10673dblClick,10674clickTime;1067510676function callEvent(view, type, event, point, target, lastPoint) {10677var item = target,10678mouseEvent;1067910680function call(obj) {10681if (obj.responds(type)) {10682if (!mouseEvent) {10683mouseEvent = new MouseEvent(type, event, point, target,10684lastPoint ? point.subtract(lastPoint) : null);10685}10686if (obj.fire(type, mouseEvent) && mouseEvent.isStopped) {10687event.preventDefault();10688return true;10689}10690}10691}1069210693while (item) {10694if (call(item))10695return true;10696item = item.getParent();10697}10698if (call(view))10699return true;10700return false;10701}1070210703return {10704_handleEvent: function(type, point, event) {10705if (!this._eventCounters[type])10706return;10707var project = this._project,10708hit = project.hitTest(point, {10709tolerance: this._scope.settings.hitTolerance,10710fill: true,10711stroke: true10712}),10713item = hit && hit.item,10714stopped = false;10715switch (type) {10716case 'mousedown':10717stopped = callEvent(this, type, event, point, item);10718dblClick = lastItem == item && (Date.now() - clickTime < 300);10719downItem = lastItem = item;10720downPoint = lastPoint = overPoint = point;10721dragItem = !stopped && item;10722while (dragItem && !dragItem.responds('mousedrag'))10723dragItem = dragItem._parent;10724break;10725case 'mouseup':10726stopped = callEvent(this, type, event, point, item, downPoint);10727if (dragItem) {10728if (lastPoint && !lastPoint.equals(point))10729callEvent(this, 'mousedrag', event, point, dragItem,10730lastPoint);10731if (item !== dragItem) {10732overPoint = point;10733callEvent(this, 'mousemove', event, point, item,10734overPoint);10735}10736}10737if (!stopped && item && item === downItem) {10738clickTime = Date.now();10739callEvent(this, dblClick && downItem.responds('doubleclick')10740? 'doubleclick' : 'click', event, downPoint, item);10741dblClick = false;10742}10743downItem = dragItem = null;10744break;10745case 'mousemove':10746if (dragItem)10747stopped = callEvent(this, 'mousedrag', event, point,10748dragItem, lastPoint);10749if (!stopped) {10750if (item !== overItem)10751overPoint = point;10752stopped = callEvent(this, type, event, point, item,10753overPoint);10754}10755lastPoint = overPoint = point;10756if (item !== overItem) {10757callEvent(this, 'mouseleave', event, point, overItem);10758overItem = item;10759callEvent(this, 'mouseenter', event, point, item);10760}10761break;10762}10763return stopped;10764}10765};10766});1076710768var Event = Base.extend({10769_class: 'Event',1077010771initialize: function Event(event) {10772this.event = event;10773},1077410775isPrevented: false,10776isStopped: false,1077710778preventDefault: function() {10779this.isPrevented = true;10780this.event.preventDefault();10781},1078210783stopPropagation: function() {10784this.isStopped = true;10785this.event.stopPropagation();10786},1078710788stop: function() {10789this.stopPropagation();10790this.preventDefault();10791},1079210793getModifiers: function() {10794return Key.modifiers;10795}10796});1079710798var KeyEvent = Event.extend({10799_class: 'KeyEvent',1080010801initialize: function KeyEvent(down, key, character, event) {10802Event.call(this, event);10803this.type = down ? 'keydown' : 'keyup';10804this.key = key;10805this.character = character;10806},1080710808toString: function() {10809return "{ type: '" + this.type10810+ "', key: '" + this.key10811+ "', character: '" + this.character10812+ "', modifiers: " + this.getModifiers()10813+ " }";10814}10815});1081610817var Key = new function() {1081810819var specialKeys = {108208: 'backspace',108219: 'tab',1082213: 'enter',1082316: 'shift',1082417: 'control',1082518: 'option',1082619: 'pause',1082720: 'caps-lock',1082827: 'escape',1082932: 'space',1083035: 'end',1083136: 'home',1083237: 'left',1083338: 'up',1083439: 'right',1083540: 'down',1083646: 'delete',1083791: 'command',1083893: 'command',10839224: 'command'10840},1084110842specialChars = {108439: true,1084413: true,1084532: true10846},1084710848modifiers = new Base({10849shift: false,10850control: false,10851option: false,10852command: false,10853capsLock: false,10854space: false10855}),1085610857charCodeMap = {},10858keyMap = {},10859downCode;1086010861function handleKey(down, keyCode, charCode, event) {10862var character = charCode ? String.fromCharCode(charCode) : '',10863specialKey = specialKeys[keyCode],10864key = specialKey || character.toLowerCase(),10865type = down ? 'keydown' : 'keyup',10866view = View._focused,10867scope = view && view.isVisible() && view._scope,10868tool = scope && scope.tool,10869name;10870keyMap[key] = down;10871if (specialKey && (name = Base.camelize(specialKey)) in modifiers)10872modifiers[name] = down;10873if (down) {10874charCodeMap[keyCode] = charCode;10875} else {10876delete charCodeMap[keyCode];10877}10878if (tool && tool.responds(type)) {10879paper = scope;10880tool.fire(type, new KeyEvent(down, key, character, event));10881if (view)10882view.update();10883}10884}1088510886DomEvent.add(document, {10887keydown: function(event) {10888var code = event.which || event.keyCode;10889if (code in specialKeys || modifiers.command) {10890handleKey(true, code,10891code in specialChars || modifiers.command ? code : 0,10892event);10893} else {10894downCode = code;10895}10896},1089710898keypress: function(event) {10899if (downCode != null) {10900handleKey(true, downCode, event.which || event.keyCode, event);10901downCode = null;10902}10903},1090410905keyup: function(event) {10906var code = event.which || event.keyCode;10907if (code in charCodeMap)10908handleKey(false, code, charCodeMap[code], event);10909}10910});1091110912DomEvent.add(window, {10913blur: function(event) {10914for (var code in charCodeMap)10915handleKey(false, code, charCodeMap[code], event);10916}10917});1091810919return {10920modifiers: modifiers,1092110922isDown: function(key) {10923return !!keyMap[key];10924}10925};10926};1092710928var MouseEvent = Event.extend({10929_class: 'MouseEvent',1093010931initialize: function MouseEvent(type, event, point, target, delta) {10932Event.call(this, event);10933this.type = type;10934this.point = point;10935this.target = target;10936this.delta = delta;10937},1093810939toString: function() {10940return "{ type: '" + this.type10941+ "', point: " + this.point10942+ ', target: ' + this.target10943+ (this.delta ? ', delta: ' + this.delta : '')10944+ ', modifiers: ' + this.getModifiers()10945+ ' }';10946}10947});1094810949Base.extend(Callback, {10950_class: 'Palette',10951_events: [ 'onChange' ],1095210953initialize: function Palette(title, components, values) {10954var parent = DomElement.find('.palettejs-panel')10955|| DomElement.find('body').appendChild(10956DomElement.create('div', { 'class': 'palettejs-panel' }));10957this._element = parent.appendChild(10958DomElement.create('table', { 'class': 'palettejs-pane' }));10959this._title = title;10960if (!values)10961values = {};10962for (var name in (this.components = components)) {10963var component = components[name];10964if (!(component instanceof Component)) {10965if (component.value == null)10966component.value = values[name];10967component.name = name;10968component = components[name] = new Component(component);10969}10970this._element.appendChild(component._element);10971component._palette = this;10972if (values[name] === undefined)10973values[name] = component.value;10974}10975this.values = Base.each(values, function(value, name) {10976var component = components[name];10977if (component) {10978Base.define(values, name, {10979enumerable: true,10980configurable: true,10981get: function() {10982return component._value;10983},10984set: function(val) {10985component.setValue(val);10986}10987});10988}10989});10990if (window.paper)10991paper.palettes.push(this);10992},1099310994reset: function() {10995for (var i in this.components)10996this.components[i].reset();10997},1099810999remove: function() {11000DomElement.remove(this._element);11001}11002});1100311004var Component = Base.extend(Callback, {11005_class: 'Component',11006_events: [ 'onChange', 'onClick' ],1100711008_types: {11009'boolean': {11010type: 'checkbox',11011value: 'checked'11012},1101311014string: {11015type: 'text'11016},1101711018number: {11019type: 'number',11020number: true11021},1102211023button: {11024type: 'button'11025},1102611027text: {11028tag: 'div',11029value: 'text'11030},1103111032slider: {11033type: 'range',11034number: true11035},1103611037list: {11038tag: 'select',1103911040setOptions: function() {11041DomElement.removeChildren(this._input);11042DomElement.create(Base.each(this._options, function(option) {11043this.push('option', { value: option, text: option });11044}, []), this._input);11045}11046},1104711048color: {11049type: 'color',1105011051getValue: function(value) {11052return new Color(value);11053},1105411055setValue: function(value) {11056return new Color(value).toCSS(11057DomElement.get(this._input, 'type') === 'color');11058}11059}11060},1106111062initialize: function Component(obj) {11063this._id = Component._id = (Component._id || 0) + 1;11064this._type = obj.type in this._types11065? obj.type11066: 'options' in obj11067? 'list'11068: 'onClick' in obj11069? 'button'11070: typeof obj.value;11071this._meta = this._types[this._type] || { type: this._type };11072var that = this,11073id = 'component-' + this._id;11074this._dontFire = true;11075this._input = DomElement.create(this._meta.tag || 'input', {11076id: id,11077type: this._meta.type,11078events: {11079change: function() {11080that.setValue(11081DomElement.get(this, that._meta.value || 'value'));11082},11083click: function() {11084that.fire('click');11085}11086}11087});11088this.attach('change', function(value) {11089if (!this._dontFire)11090this._palette.fire('change', this, this.name, value);11091});11092this._element = DomElement.create('tr', [11093'td', [this._label = DomElement.create('label', { 'for': id })],11094'td', [this._input]11095]);11096Base.each(obj, function(value, key) {11097this[key] = value;11098}, this);11099this._defaultValue = this._value;11100this._dontFire = false;11101},1110211103getType: function() {11104return this._type;11105},1110611107getLabel: function() {11108return this.__label;11109},1111011111setLabel: function(label) {11112this.__label = label;11113DomElement.set(this._label, 'text', label + ':');11114},1111511116getOptions: function() {11117return this._options;11118},1111911120setOptions: function(options) {11121this._options = options;11122var setOptions = this._meta.setOptions;11123if (setOptions)11124setOptions.call(this);11125},1112611127getValue: function() {11128var value = this._value,11129getValue = this._meta.getValue;11130return getValue ? getValue.call(this, value) : value;11131},1113211133setValue: function(value) {11134var key = this._meta.value || 'value',11135setValue = this._meta.setValue;11136if (setValue)11137value = setValue.call(this, value);11138DomElement.set(this._input, key, value);11139value = DomElement.get(this._input, key);11140if (this._meta.number)11141value = parseFloat(value, 10);11142if (this._value !== value) {11143this._value = value;11144if (!this._dontFire)11145this.fire('change', this.getValue());11146}11147},1114811149getRange: function() {11150return [parseFloat(DomElement.get(this._input, 'min')),11151parseFloat(DomElement.get(this._input, 'max'))];11152},1115311154setRange: function(min, max) {11155var range = Array.isArray(min) ? min : [min, max];11156DomElement.set(this._input, { min: range[0], max: range[1] });11157},1115811159getMin: function() {11160return this.getRange()[0];11161},1116211163setMin: function(min) {11164this.setRange(min, this.getMax());11165},1116611167getMax: function() {11168return this.getRange()[1];11169},1117011171setMax: function(max) {11172this.setRange(this.getMin(), max);11173},1117411175getStep: function() {11176return parseFloat(DomElement.get(this._input, 'step'));11177},1117811179setStep: function(step) {11180DomElement.set(this._input, 'step', step);11181},1118211183reset: function() {11184this.setValue(this._defaultValue);11185}11186});1118711188var ToolEvent = Event.extend({11189_class: 'ToolEvent',11190_item: null,1119111192initialize: function ToolEvent(tool, type, event) {11193this.tool = tool;11194this.type = type;11195this.event = event;11196},1119711198_choosePoint: function(point, toolPoint) {11199return point ? point : toolPoint ? toolPoint.clone() : null;11200},1120111202getPoint: function() {11203return this._choosePoint(this._point, this.tool._point);11204},1120511206setPoint: function(point) {11207this._point = point;11208},1120911210getLastPoint: function() {11211return this._choosePoint(this._lastPoint, this.tool._lastPoint);11212},1121311214setLastPoint: function(lastPoint) {11215this._lastPoint = lastPoint;11216},1121711218getDownPoint: function() {11219return this._choosePoint(this._downPoint, this.tool._downPoint);11220},1122111222setDownPoint: function(downPoint) {11223this._downPoint = downPoint;11224},1122511226getMiddlePoint: function() {11227if (!this._middlePoint && this.tool._lastPoint) {11228return this.tool._point.add(this.tool._lastPoint).divide(2);11229}11230return this._middlePoint;11231},1123211233setMiddlePoint: function(middlePoint) {11234this._middlePoint = middlePoint;11235},1123611237getDelta: function() {11238return !this._delta && this.tool._lastPoint11239? this.tool._point.subtract(this.tool._lastPoint)11240: this._delta;11241},1124211243setDelta: function(delta) {11244this._delta = delta;11245},1124611247getCount: function() {11248return /^mouse(down|up)$/.test(this.type)11249? this.tool._downCount11250: this.tool._count;11251},1125211253setCount: function(count) {11254this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']11255= count;11256},1125711258getItem: function() {11259if (!this._item) {11260var result = this.tool._scope.project.hitTest(this.getPoint());11261if (result) {11262var item = result.item,11263parent = item._parent;11264while (/^(Group|CompoundPath)$/.test(parent._class)) {11265item = parent;11266parent = parent._parent;11267}11268this._item = item;11269}11270}11271return this._item;11272},1127311274setItem: function(item) {11275this._item = item;11276},1127711278toString: function() {11279return '{ type: ' + this.type11280+ ', point: ' + this.getPoint()11281+ ', count: ' + this.getCount()11282+ ', modifiers: ' + this.getModifiers()11283+ ' }';11284}11285});1128611287var Tool = PaperScopeItem.extend({11288_class: 'Tool',11289_list: 'tools',11290_reference: 'tool',11291_events: [ 'onActivate', 'onDeactivate', 'onEditOptions',11292'onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',11293'onKeyDown', 'onKeyUp' ],1129411295initialize: function Tool(props) {11296PaperScopeItem.call(this);11297this._firstMove = true;11298this._count = 0;11299this._downCount = 0;11300this._set(props);11301},1130211303getMinDistance: function() {11304return this._minDistance;11305},1130611307setMinDistance: function(minDistance) {11308this._minDistance = minDistance;11309if (this._minDistance != null && this._maxDistance != null11310&& this._minDistance > this._maxDistance) {11311this._maxDistance = this._minDistance;11312}11313},1131411315getMaxDistance: function() {11316return this._maxDistance;11317},1131811319setMaxDistance: function(maxDistance) {11320this._maxDistance = maxDistance;11321if (this._minDistance != null && this._maxDistance != null11322&& this._maxDistance < this._minDistance) {11323this._minDistance = maxDistance;11324}11325},1132611327getFixedDistance: function() {11328return this._minDistance == this._maxDistance11329? this._minDistance : null;11330},1133111332setFixedDistance: function(distance) {11333this._minDistance = distance;11334this._maxDistance = distance;11335},1133611337_updateEvent: function(type, point, minDistance, maxDistance, start,11338needsChange, matchMaxDistance) {11339if (!start) {11340if (minDistance != null || maxDistance != null) {11341var minDist = minDistance != null ? minDistance : 0,11342vector = point.subtract(this._point),11343distance = vector.getLength();11344if (distance < minDist)11345return false;11346var maxDist = maxDistance != null ? maxDistance : 0;11347if (maxDist != 0) {11348if (distance > maxDist) {11349point = this._point.add(vector.normalize(maxDist));11350} else if (matchMaxDistance) {11351return false;11352}11353}11354}11355if (needsChange && point.equals(this._point))11356return false;11357}11358this._lastPoint = start && type == 'mousemove' ? point : this._point;11359this._point = point;11360switch (type) {11361case 'mousedown':11362this._lastPoint = this._downPoint;11363this._downPoint = this._point;11364this._downCount++;11365break;11366case 'mouseup':11367this._lastPoint = this._downPoint;11368break;11369}11370this._count = start ? 0 : this._count + 1;11371return true;11372},1137311374_fireEvent: function(type, event) {11375var sets = paper.project._removeSets;11376if (sets) {11377if (type === 'mouseup')11378sets.mousedrag = null;11379var set = sets[type];11380if (set) {11381for (var id in set) {11382var item = set[id];11383for (var key in sets) {11384var other = sets[key];11385if (other && other != set)11386delete other[item._id];11387}11388item.remove();11389}11390sets[type] = null;11391}11392}11393return this.responds(type)11394&& this.fire(type, new ToolEvent(this, type, event));11395},1139611397_handleEvent: function(type, point, event) {11398paper = this._scope;11399var called = false;11400switch (type) {11401case 'mousedown':11402this._updateEvent(type, point, null, null, true, false, false);11403called = this._fireEvent(type, event);11404break;11405case 'mousedrag':11406var needsChange = false,11407matchMaxDistance = false;11408while (this._updateEvent(type, point, this.minDistance,11409this.maxDistance, false, needsChange, matchMaxDistance)) {11410called = this._fireEvent(type, event) || called;11411needsChange = true;11412matchMaxDistance = true;11413}11414break;11415case 'mouseup':11416if (!point.equals(this._point)11417&& this._updateEvent('mousedrag', point, this.minDistance,11418this.maxDistance, false, false, false)) {11419called = this._fireEvent('mousedrag', event);11420}11421this._updateEvent(type, point, null, this.maxDistance, false,11422false, false);11423called = this._fireEvent(type, event) || called;11424this._updateEvent(type, point, null, null, true, false, false);11425this._firstMove = true;11426break;11427case 'mousemove':11428while (this._updateEvent(type, point, this.minDistance,11429this.maxDistance, this._firstMove, true, false)) {11430called = this._fireEvent(type, event) || called;11431this._firstMove = false;11432}11433break;11434}11435if (called)11436event.preventDefault();11437return called;11438}1143911440});1144111442var Http = {11443request: function(method, url, callback) {11444var xhr = new (window.ActiveXObject || XMLHttpRequest)(11445'Microsoft.XMLHTTP');11446xhr.open(method.toUpperCase(), url, true);11447if ('overrideMimeType' in xhr)11448xhr.overrideMimeType('text/plain');11449xhr.onreadystatechange = function() {11450if (xhr.readyState === 4) {11451var status = xhr.status;11452if (status === 0 || status === 200) {11453callback.call(xhr, xhr.responseText);11454} else {11455throw new Error('Could not load ' + url + ' (Error '11456+ status + ')');11457}11458}11459};11460return xhr.send(null);11461}11462};1146311464var CanvasProvider = {11465canvases: [],1146611467getCanvas: function(width, height, pixelRatio) {11468var canvas,11469init = true;11470if (typeof width === 'object') {11471pixelRatio = height;11472height = width.height;11473width = width.width;11474}11475if (!pixelRatio) {11476pixelRatio = 1;11477} else if (pixelRatio !== 1) {11478width *= pixelRatio;11479height *= pixelRatio;11480}11481if (this.canvases.length) {11482canvas = this.canvases.pop();11483} else {11484canvas = document.createElement('canvas');11485}11486var ctx = canvas.getContext('2d');11487if (canvas.width === width && canvas.height === height) {11488if (init)11489ctx.clearRect(0, 0, width + 1, height + 1);11490} else {11491canvas.width = width;11492canvas.height = height;11493}11494ctx.save();11495if (pixelRatio !== 1)11496ctx.scale(pixelRatio, pixelRatio);11497return canvas;11498},1149911500getContext: function(width, height, pixelRatio) {11501return this.getCanvas(width, height, pixelRatio).getContext('2d');11502},1150311504release: function(obj) {11505var canvas = obj.canvas ? obj.canvas : obj;11506canvas.getContext('2d').restore();11507this.canvases.push(canvas);11508}11509};1151011511var BlendMode = new function() {11512var min = Math.min,11513max = Math.max,11514abs = Math.abs,11515sr, sg, sb, sa,11516br, bg, bb, ba,11517dr, dg, db;1151811519function getLum(r, g, b) {11520return 0.2989 * r + 0.587 * g + 0.114 * b;11521}1152211523function setLum(r, g, b, l) {11524var d = l - getLum(r, g, b);11525dr = r + d;11526dg = g + d;11527db = b + d;11528var l = getLum(dr, dg, db),11529mn = min(dr, dg, db),11530mx = max(dr, dg, db);11531if (mn < 0) {11532var lmn = l - mn;11533dr = l + (dr - l) * l / lmn;11534dg = l + (dg - l) * l / lmn;11535db = l + (db - l) * l / lmn;11536}11537if (mx > 255) {11538var ln = 255 - l,11539mxl = mx - l;11540dr = l + (dr - l) * ln / mxl;11541dg = l + (dg - l) * ln / mxl;11542db = l + (db - l) * ln / mxl;11543}11544}1154511546function getSat(r, g, b) {11547return max(r, g, b) - min(r, g, b);11548}1154911550function setSat(r, g, b, s) {11551var col = [r, g, b],11552mx = max(r, g, b),11553mn = min(r, g, b),11554md;11555mn = mn === r ? 0 : mn === g ? 1 : 2;11556mx = mx === r ? 0 : mx === g ? 1 : 2;11557md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;11558if (col[mx] > col[mn]) {11559col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);11560col[mx] = s;11561} else {11562col[md] = col[mx] = 0;11563}11564col[mn] = 0;11565dr = col[0];11566dg = col[1];11567db = col[2];11568}1156911570var modes = {11571multiply: function() {11572dr = br * sr / 255;11573dg = bg * sg / 255;11574db = bb * sb / 255;11575},1157611577screen: function() {11578dr = br + sr - (br * sr / 255);11579dg = bg + sg - (bg * sg / 255);11580db = bb + sb - (bb * sb / 255);11581},1158211583overlay: function() {11584dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;11585dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;11586db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;11587},1158811589'soft-light': function() {11590var t = sr * br / 255;11591dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;11592t = sg * bg / 255;11593dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;11594t = sb * bb / 255;11595db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;11596},1159711598'hard-light': function() {11599dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;11600dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;11601db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;11602},1160311604'color-dodge': function() {11605dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));11606dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));11607db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));11608},1160911610'color-burn': function() {11611dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);11612dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);11613db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);11614},1161511616darken: function() {11617dr = br < sr ? br : sr;11618dg = bg < sg ? bg : sg;11619db = bb < sb ? bb : sb;11620},1162111622lighten: function() {11623dr = br > sr ? br : sr;11624dg = bg > sg ? bg : sg;11625db = bb > sb ? bb : sb;11626},1162711628difference: function() {11629dr = br - sr;11630if (dr < 0)11631dr = -dr;11632dg = bg - sg;11633if (dg < 0)11634dg = -dg;11635db = bb - sb;11636if (db < 0)11637db = -db;11638},1163911640exclusion: function() {11641dr = br + sr * (255 - br - br) / 255;11642dg = bg + sg * (255 - bg - bg) / 255;11643db = bb + sb * (255 - bb - bb) / 255;11644},1164511646hue: function() {11647setSat(sr, sg, sb, getSat(br, bg, bb));11648setLum(dr, dg, db, getLum(br, bg, bb));11649},1165011651saturation: function() {11652setSat(br, bg, bb, getSat(sr, sg, sb));11653setLum(dr, dg, db, getLum(br, bg, bb));11654},1165511656luminosity: function() {11657setLum(br, bg, bb, getLum(sr, sg, sb));11658},1165911660color: function() {11661setLum(sr, sg, sb, getLum(br, bg, bb));11662},1166311664add: function() {11665dr = min(br + sr, 255);11666dg = min(bg + sg, 255);11667db = min(bb + sb, 255);11668},1166911670subtract: function() {11671dr = max(br - sr, 0);11672dg = max(bg - sg, 0);11673db = max(bb - sb, 0);11674},1167511676average: function() {11677dr = (br + sr) / 2;11678dg = (bg + sg) / 2;11679db = (bb + sb) / 2;11680},1168111682negation: function() {11683dr = 255 - abs(255 - sr - br);11684dg = 255 - abs(255 - sg - bg);11685db = 255 - abs(255 - sb - bb);11686}11687};1168811689var nativeModes = this.nativeModes = Base.each([11690'source-over', 'source-in', 'source-out', 'source-atop',11691'destination-over', 'destination-in', 'destination-out',11692'destination-atop', 'lighter', 'darker', 'copy', 'xor'11693], function(mode) {11694this[mode] = true;11695}, {});1169611697var ctx = CanvasProvider.getContext(1, 1);11698Base.each(modes, function(func, mode) {11699var darken = mode === 'darken',11700ok = false;11701ctx.save();11702try {11703ctx.fillStyle = darken ? '#300' : '#a00';11704ctx.fillRect(0, 0, 1, 1);11705ctx.globalCompositeOperation = mode;11706if (ctx.globalCompositeOperation === mode) {11707ctx.fillStyle = darken ? '#a00' : '#300';11708ctx.fillRect(0, 0, 1, 1);11709ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken ? 170 : 51;11710}11711} catch (e) {}11712ctx.restore();11713nativeModes[mode] = ok;11714});11715CanvasProvider.release(ctx);1171611717this.process = function(mode, srcContext, dstContext, alpha, offset) {11718var srcCanvas = srcContext.canvas,11719normal = mode === 'normal';11720if (normal || nativeModes[mode]) {11721dstContext.save();11722dstContext.setTransform(1, 0, 0, 1, 0, 0);11723dstContext.globalAlpha = alpha;11724if (!normal)11725dstContext.globalCompositeOperation = mode;11726dstContext.drawImage(srcCanvas, offset.x, offset.y);11727dstContext.restore();11728} else {11729var process = modes[mode];11730if (!process)11731return;11732var dstData = dstContext.getImageData(offset.x, offset.y,11733srcCanvas.width, srcCanvas.height),11734dst = dstData.data,11735src = srcContext.getImageData(0, 0,11736srcCanvas.width, srcCanvas.height).data;11737for (var i = 0, l = dst.length; i < l; i += 4) {11738sr = src[i];11739br = dst[i];11740sg = src[i + 1];11741bg = dst[i + 1];11742sb = src[i + 2];11743bb = dst[i + 2];11744sa = src[i + 3];11745ba = dst[i + 3];11746process();11747var a1 = sa * alpha / 255,11748a2 = 1 - a1;11749dst[i] = a1 * dr + a2 * br;11750dst[i + 1] = a1 * dg + a2 * bg;11751dst[i + 2] = a1 * db + a2 * bb;11752dst[i + 3] = sa * alpha + a2 * ba;11753}11754dstContext.putImageData(dstData, offset.x, offset.y);11755}11756};11757};1175811759var SVGStyles = Base.each({11760fillColor: ['fill', 'color'],11761strokeColor: ['stroke', 'color'],11762strokeWidth: ['stroke-width', 'number'],11763strokeCap: ['stroke-linecap', 'string'],11764strokeJoin: ['stroke-linejoin', 'string'],11765miterLimit: ['stroke-miterlimit', 'number'],11766dashArray: ['stroke-dasharray', 'array'],11767dashOffset: ['stroke-dashoffset', 'number'],11768fontFamily: ['font-family', 'string'],11769fontWeight: ['font-weight', 'string'],11770fontSize: ['font-size', 'number'],11771justification: ['text-anchor', 'lookup', {11772left: 'start',11773center: 'middle',11774right: 'end'11775}],11776opacity: ['opacity', 'number'],11777blendMode: ['mix-blend-mode', 'string']11778}, function(entry, key) {11779var part = Base.capitalize(key),11780lookup = entry[2];11781this[key] = {11782type: entry[1],11783property: key,11784attribute: entry[0],11785toSVG: lookup,11786fromSVG: lookup && Base.each(lookup, function(value, name) {11787this[value] = name;11788}, {}),11789get: 'get' + part,11790set: 'set' + part11791};11792}, {});1179311794var SVGNamespaces = {11795href: 'http://www.w3.org/1999/xlink',11796xlink: 'http://www.w3.org/2000/xmlns'11797};1179811799new function() {11800var formatter;1180111802function setAttributes(node, attrs) {11803for (var key in attrs) {11804var val = attrs[key],11805namespace = SVGNamespaces[key];11806if (typeof val === 'number')11807val = formatter.number(val);11808if (namespace) {11809node.setAttributeNS(namespace, key, val);11810} else {11811node.setAttribute(key, val);11812}11813}11814return node;11815}1181611817function createElement(tag, attrs) {11818return setAttributes(11819document.createElementNS('http://www.w3.org/2000/svg', tag), attrs);11820}1182111822function getTransform(item, coordinates, center) {11823var matrix = item._matrix,11824trans = matrix.getTranslation(),11825attrs = {};11826if (coordinates) {11827matrix = matrix.shiftless();11828var point = matrix._inverseTransform(trans);11829attrs[center ? 'cx' : 'x'] = point.x;11830attrs[center ? 'cy' : 'y'] = point.y;11831trans = null;11832}11833if (!matrix.isIdentity()) {11834var decomposed = matrix.decompose();11835if (decomposed && !decomposed.shearing) {11836var parts = [],11837angle = decomposed.rotation,11838scale = decomposed.scaling;11839if (trans && !trans.isZero())11840parts.push('translate(' + formatter.point(trans) + ')');11841if (angle)11842parts.push('rotate(' + formatter.number(angle) + ')');11843if (!Numerical.isZero(scale.x - 1)11844|| !Numerical.isZero(scale.y - 1))11845parts.push('scale(' + formatter.point(scale) +')');11846attrs.transform = parts.join(' ');11847} else {11848attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';11849}11850}11851return attrs;11852}1185311854function exportGroup(item, options) {11855var attrs = getTransform(item),11856children = item._children;11857var node = createElement('g', attrs);11858for (var i = 0, l = children.length; i < l; i++) {11859var child = children[i];11860var childNode = exportSVG(child, options);11861if (childNode) {11862if (child.isClipMask()) {11863var clip = createElement('clipPath');11864clip.appendChild(childNode);11865setDefinition(child, clip, 'clip');11866setAttributes(node, {11867'clip-path': 'url(#' + clip.id + ')'11868});11869} else {11870node.appendChild(childNode);11871}11872}11873}11874return node;11875}1187611877function exportRaster(item) {11878var attrs = getTransform(item, true),11879size = item.getSize();11880attrs.x -= size.width / 2;11881attrs.y -= size.height / 2;11882attrs.width = size.width;11883attrs.height = size.height;11884attrs.href = item.toDataURL();11885return createElement('image', attrs);11886}1188711888function exportPath(item, options) {11889if (options.matchShapes) {11890var shape = item.toShape(false);11891if (shape)11892return exportShape(shape, options);11893}11894var segments = item._segments,11895type,11896attrs;11897if (segments.length === 0)11898return null;11899if (item.isPolygon()) {11900if (segments.length >= 3) {11901type = item._closed ? 'polygon' : 'polyline';11902var parts = [];11903for(i = 0, l = segments.length; i < l; i++)11904parts.push(formatter.point(segments[i]._point));11905attrs = {11906points: parts.join(' ')11907};11908} else {11909type = 'line';11910var first = segments[0]._point,11911last = segments[segments.length - 1]._point;11912attrs = {11913x1: first.x,11914y1: first.y,11915x2: last.x,11916y2: last.y11917};11918}11919} else {11920type = 'path';11921var data = item.getPathData();11922attrs = data && { d: data };11923}11924return createElement(type, attrs);11925}1192611927function exportShape(item) {11928var type = item._type,11929radius = item._radius,11930attrs = getTransform(item, true, type !== 'rectangle');11931if (type === 'rectangle') {11932type = 'rect';11933var size = item._size,11934width = size.width,11935height = size.height;11936attrs.x -= width / 2;11937attrs.y -= height / 2;11938attrs.width = width;11939attrs.height = height;11940if (radius.isZero())11941radius = null;11942}11943if (radius) {11944if (type === 'circle') {11945attrs.r = radius;11946} else {11947attrs.rx = radius.width;11948attrs.ry = radius.height;11949}11950}11951return createElement(type, attrs);11952}1195311954function exportCompoundPath(item) {11955var attrs = getTransform(item, true);11956var data = item.getPathData();11957if (data)11958attrs.d = data;11959return createElement('path', attrs);11960}1196111962function exportPlacedSymbol(item, options) {11963var attrs = getTransform(item, true),11964symbol = item.getSymbol(),11965symbolNode = getDefinition(symbol, 'symbol'),11966definition = symbol.getDefinition(),11967bounds = definition.getBounds();11968if (!symbolNode) {11969symbolNode = createElement('symbol', {11970viewBox: formatter.rectangle(bounds)11971});11972symbolNode.appendChild(exportSVG(definition, options));11973setDefinition(symbol, symbolNode, 'symbol');11974}11975attrs.href = '#' + symbolNode.id;11976attrs.x += bounds.x;11977attrs.y += bounds.y;11978attrs.width = formatter.number(bounds.width);11979attrs.height = formatter.number(bounds.height);11980return createElement('use', attrs);11981}1198211983function exportGradient(color) {11984var gradientNode = getDefinition(color, 'color');11985if (!gradientNode) {11986var gradient = color.getGradient(),11987radial = gradient._radial,11988origin = color.getOrigin().transform(),11989destination = color.getDestination().transform(),11990attrs;11991if (radial) {11992attrs = {11993cx: origin.x,11994cy: origin.y,11995r: origin.getDistance(destination)11996};11997var highlight = color.getHighlight();11998if (highlight) {11999highlight = highlight.transform();12000attrs.fx = highlight.x;12001attrs.fy = highlight.y;12002}12003} else {12004attrs = {12005x1: origin.x,12006y1: origin.y,12007x2: destination.x,12008y2: destination.y12009};12010}12011attrs.gradientUnits = 'userSpaceOnUse';12012gradientNode = createElement(12013(radial ? 'radial' : 'linear') + 'Gradient', attrs);12014var stops = gradient._stops;12015for (var i = 0, l = stops.length; i < l; i++) {12016var stop = stops[i],12017stopColor = stop._color,12018alpha = stopColor.getAlpha();12019attrs = {12020offset: stop._rampPoint,12021'stop-color': stopColor.toCSS(true)12022};12023if (alpha < 1)12024attrs['stop-opacity'] = alpha;12025gradientNode.appendChild(createElement('stop', attrs));12026}12027setDefinition(color, gradientNode, 'color');12028}12029return 'url(#' + gradientNode.id + ')';12030}1203112032function exportText(item) {12033var node = createElement('text', getTransform(item, true));12034node.textContent = item._content;12035return node;12036}1203712038var exporters = {12039Group: exportGroup,12040Layer: exportGroup,12041Raster: exportRaster,12042Path: exportPath,12043Shape: exportShape,12044CompoundPath: exportCompoundPath,12045PlacedSymbol: exportPlacedSymbol,12046PointText: exportText12047};1204812049function applyStyle(item, node) {12050var attrs = {},12051parent = item.getParent();1205212053if (item._name != null)12054attrs.id = item._name;1205512056Base.each(SVGStyles, function(entry) {12057var get = entry.get,12058type = entry.type,12059value = item[get]();12060if (!parent || !Base.equals(parent[get](), value)) {12061if (type === 'color' && value != null) {12062var alpha = value.getAlpha();12063if (alpha < 1)12064attrs[entry.attribute + '-opacity'] = alpha;12065}12066attrs[entry.attribute] = value == null12067? 'none'12068: type === 'number'12069? formatter.number(value)12070: type === 'color'12071? value.gradient12072? exportGradient(value, item)12073: value.toCSS(true)12074: type === 'array'12075? value.join(',')12076: type === 'lookup'12077? entry.toSVG[value]12078: value;12079}12080});1208112082if (attrs.opacity === 1)12083delete attrs.opacity;1208412085if (item._visibility != null && !item._visibility)12086attrs.visibility = 'hidden';1208712088return setAttributes(node, attrs);12089}1209012091var definitions;12092function getDefinition(item, type) {12093if (!definitions)12094definitions = { ids: {}, svgs: {} };12095return item && definitions.svgs[type + '-' + item._id];12096}1209712098function setDefinition(item, node, type) {12099if (!definitions)12100getDefinition();12101var id = definitions.ids[type] = (definitions.ids[type] || 0) + 1;12102node.id = type + '-' + id;12103definitions.svgs[type + '-' + item._id] = node;12104}1210512106function exportDefinitions(node, options) {12107var svg = node,12108defs = null;12109if (definitions) {12110svg = node.nodeName.toLowerCase() === 'svg' && node;12111for (var i in definitions.svgs) {12112if (!defs) {12113if (!svg) {12114svg = createElement('svg');12115svg.appendChild(node);12116}12117defs = svg.insertBefore(createElement('defs'),12118svg.firstChild);12119}12120defs.appendChild(definitions.svgs[i]);12121}12122definitions = null;12123}12124return options.asString12125? new XMLSerializer().serializeToString(svg)12126: svg;12127}1212812129function exportSVG(item, options) {12130var exporter = exporters[item._class],12131node = exporter && exporter(item, options);12132if (node && item._data) {12133var data = JSON.stringify(item._data);12134if (data !== '{}')12135node.setAttribute('data-paper-data', data);12136}12137return node && applyStyle(item, node);12138}1213912140function setOptions(options) {12141if (!options)12142options = {};12143formatter = new Formatter(options.precision);12144return options;12145}1214612147Item.inject({12148exportSVG: function(options) {12149options = setOptions(options);12150return exportDefinitions(exportSVG(this, options), options);12151}12152});1215312154Project.inject({12155exportSVG: function(options) {12156options = setOptions(options);12157var layers = this.layers,12158size = this.getView().getSize(),12159node = createElement('svg', {12160x: 0,12161y: 0,12162width: size.width,12163height: size.height,12164version: '1.1',12165xmlns: 'http://www.w3.org/2000/svg',12166'xmlns:xlink': 'http://www.w3.org/1999/xlink'12167});12168for (var i = 0, l = layers.length; i < l; i++)12169node.appendChild(exportSVG(layers[i], options));12170return exportDefinitions(node, options);12171}12172});12173};1217412175new function() {1217612177function getValue(node, name, isString, allowNull) {12178var namespace = SVGNamespaces[name],12179value = namespace12180? node.getAttributeNS(namespace, name)12181: node.getAttribute(name);12182if (value === 'null')12183value = null;12184return value == null12185? allowNull12186? null12187: isString12188? ''12189: 012190: isString12191? value12192: parseFloat(value);12193}1219412195function getPoint(node, x, y, allowNull) {12196x = getValue(node, x, false, allowNull);12197y = getValue(node, y, false, allowNull);12198return allowNull && (x == null || y == null) ? null12199: new Point(x, y);12200}1220112202function getSize(node, w, h, allowNull) {12203w = getValue(node, w, false, allowNull);12204h = getValue(node, h, false, allowNull);12205return allowNull && (w == null || h == null) ? null12206: new Size(w, h);12207}1220812209function convertValue(value, type, lookup) {12210return value === 'none'12211? null12212: type === 'number'12213? parseFloat(value)12214: type === 'array'12215? value ? value.split(/[\s,]+/g).map(parseFloat) : []12216: type === 'color'12217? getDefinition(value) || value12218: type === 'lookup'12219? lookup[value]12220: value;12221}1222212223function importGroup(node, type, isRoot, options) {12224var nodes = node.childNodes,12225isClip = type === 'clippath',12226item = new Group(),12227project = item._project,12228currentStyle = project._currentStyle,12229children = [];12230if (!isClip) {12231item = applyAttributes(item, node, isRoot);12232project._currentStyle = item._style.clone();12233}12234for (var i = 0, l = nodes.length; i < l; i++) {12235var childNode = nodes[i],12236child;12237if (childNode.nodeType === 112238&& (child = importSVG(childNode, false, options))12239&& !(child instanceof Symbol))12240children.push(child);12241}12242item.addChildren(children);12243if (isClip)12244item = applyAttributes(item.reduce(), node, isRoot);12245project._currentStyle = currentStyle;12246if (isClip || type === 'defs') {12247item.remove();12248item = null;12249}12250return item;12251}1225212253function importPoly(node, type) {12254var coords = node.getAttribute('points').match(12255/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g),12256points = [];12257for (var i = 0, l = coords.length; i < l; i += 2)12258points.push(new Point(12259parseFloat(coords[i]),12260parseFloat(coords[i + 1])));12261var path = new Path(points);12262if (type === 'polygon')12263path.closePath();12264return path;12265}1226612267function importPath(node) {12268var data = node.getAttribute('d'),12269param = { pathData: data };12270return data.match(/m/gi).length > 1 || /z\S+/i.test(data)12271? new CompoundPath(param)12272: new Path(param);12273}1227412275function importGradient(node, type) {12276var id = (getValue(node, 'href', true) || '').substring(1),12277isRadial = type === 'radialgradient',12278gradient;12279if (id) {12280gradient = definitions[id].getGradient();12281} else {12282var nodes = node.childNodes,12283stops = [];12284for (var i = 0, l = nodes.length; i < l; i++) {12285var child = nodes[i];12286if (child.nodeType === 1)12287stops.push(applyAttributes(new GradientStop(), child));12288}12289gradient = new Gradient(stops, isRadial);12290}12291var origin, destination, highlight;12292if (isRadial) {12293origin = getPoint(node, 'cx', 'cy');12294destination = origin.add(getValue(node, 'r'), 0);12295highlight = getPoint(node, 'fx', 'fy', true);12296} else {12297origin = getPoint(node, 'x1', 'y1');12298destination = getPoint(node, 'x2', 'y2');12299}12300applyAttributes(12301new Color(gradient, origin, destination, highlight), node);12302return null;12303}1230412305var importers = {12306'#document': function (node, type, isRoot, options) {12307var nodes = node.childNodes;12308for (var i = 0, l = nodes.length; i < l; i++) {12309var child = nodes[i];12310if (child.nodeType === 1) {12311var next = child.nextSibling;12312document.body.appendChild(child);12313var item = importSVG(child, isRoot, options);12314if (next) {12315node.insertBefore(child, next);12316} else {12317node.appendChild(child);12318}12319return item;12320}12321}12322},12323g: importGroup,12324svg: importGroup,12325clippath: importGroup,12326polygon: importPoly,12327polyline: importPoly,12328path: importPath,12329lineargradient: importGradient,12330radialgradient: importGradient,1233112332image: function (node) {12333var raster = new Raster(getValue(node, 'href', true));12334raster.attach('load', function() {12335var size = getSize(node, 'width', 'height');12336this.setSize(size);12337var center = this._matrix._transformPoint(12338getPoint(node, 'x', 'y').add(size.divide(2)));12339this.translate(center);12340});12341return raster;12342},1234312344symbol: function(node, type, isRoot, options) {12345return new Symbol(importGroup(node, type, isRoot, options), true);12346},1234712348defs: importGroup,1234912350use: function(node) {12351var id = (getValue(node, 'href', true) || '').substring(1),12352definition = definitions[id],12353point = getPoint(node, 'x', 'y');12354return definition12355? definition instanceof Symbol12356? definition.place(point)12357: definition.clone().translate(point)12358: null;12359},1236012361circle: function(node) {12362return new Shape.Circle(getPoint(node, 'cx', 'cy'),12363getValue(node, 'r'));12364},1236512366ellipse: function(node) {12367return new Shape.Ellipse({12368center: getPoint(node, 'cx', 'cy'),12369radius: getSize(node, 'rx', 'ry')12370});12371},1237212373rect: function(node) {12374var point = getPoint(node, 'x', 'y'),12375size = getSize(node, 'width', 'height'),12376radius = getSize(node, 'rx', 'ry');12377return new Shape.Rectangle(new Rectangle(point, size), radius);12378},1237912380line: function(node) {12381return new Path.Line(getPoint(node, 'x1', 'y1'),12382getPoint(node, 'x2', 'y2'));12383},1238412385text: function(node) {12386var text = new PointText(getPoint(node, 'x', 'y')12387.add(getPoint(node, 'dx', 'dy')));12388text.setContent(node.textContent.trim() || '');12389return text;12390}12391};1239212393function applyTransform(item, value, name, node) {12394var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),12395matrix = new Matrix();12396for (var i = 0, l = transforms.length; i < l; i++) {12397var transform = transforms[i];12398if (!transform)12399break;12400var parts = transform.split('('),12401command = parts[0],12402v = parts[1].split(/[\s,]+/g);12403for (var j = 0, m = v.length; j < m; j++)12404v[j] = parseFloat(v[j]);12405switch (command) {12406case 'matrix':12407matrix.concatenate(12408new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));12409break;12410case 'rotate':12411matrix.rotate(v[0], v[1], v[2]);12412break;12413case 'translate':12414matrix.translate(v[0], v[1]);12415break;12416case 'scale':12417matrix.scale(v);12418break;12419case 'skewX':12420matrix.skew(v[0], 0);12421break;12422case 'skewY':12423matrix.skew(0, v[0]);12424break;12425}12426}12427item.transform(matrix);12428}1242912430function applyOpacity(item, value, name) {12431var color = item[name === 'fill-opacity' ? 'getFillColor'12432: 'getStrokeColor']();12433if (color)12434color.setAlpha(parseFloat(value));12435}1243612437var attributes = Base.each(SVGStyles, function(entry) {12438this[entry.attribute] = function(item, value) {12439item[entry.set](convertValue(value, entry.type, entry.fromSVG));12440if (entry.type === 'color' && item instanceof Shape) {12441var color = item[entry.get]();12442if (color)12443color.transform(new Matrix().translate(12444item.getPosition(true).negate()));12445}12446};12447}, {12448id: function(item, value) {12449definitions[value] = item;12450if (item.setName)12451item.setName(value);12452},1245312454'clip-path': function(item, value) {12455var clip = getDefinition(value);12456if (clip) {12457clip = clip.clone();12458clip.setClipMask(true);12459if (item instanceof Group) {12460item.insertChild(0, clip);12461} else {12462return new Group(clip, item);12463}12464}12465},1246612467gradientTransform: applyTransform,12468transform: applyTransform,1246912470'fill-opacity': applyOpacity,12471'stroke-opacity': applyOpacity,1247212473visibility: function(item, value) {12474item.setVisible(value === 'visible');12475},1247612477'stop-color': function(item, value) {12478if (item.setColor)12479item.setColor(value);12480},1248112482'stop-opacity': function(item, value) {12483if (item._color)12484item._color.setAlpha(parseFloat(value));12485},1248612487offset: function(item, value) {12488var percentage = value.match(/(.*)%$/);12489item.setRampPoint(percentage12490? percentage[1] / 10012491: parseFloat(value));12492},1249312494viewBox: function(item, value, name, node, styles) {12495var rect = new Rectangle(convertValue(value, 'array')),12496size = getSize(node, 'width', 'height', true);12497if (item instanceof Group) {12498var scale = size ? rect.getSize().divide(size) : 1,12499matrix = new Matrix().translate(rect.getPoint()).scale(scale);12500item.transform(matrix.inverted());12501} else if (item instanceof Symbol) {12502if (size)12503rect.setSize(size);12504var clip = getAttribute(node, 'overflow', styles) != 'visible',12505group = item._definition;12506if (clip && !rect.contains(group.getBounds())) {12507clip = new Shape.Rectangle(rect).transform(group._matrix);12508clip.setClipMask(true);12509group.addChild(clip);12510}12511}12512}12513});1251412515function getAttribute(node, name, styles) {12516var attr = node.attributes[name],12517value = attr && attr.value;12518if (!value) {12519var style = Base.camelize(name);12520value = node.style[style];12521if (!value && styles.node[style] !== styles.parent[style])12522value = styles.node[style];12523}12524return !value12525? undefined12526: value === 'none'12527? null12528: value;12529}1253012531function applyAttributes(item, node, isRoot) {12532var styles = {12533node: DomElement.getStyles(node) || {},12534parent: !isRoot && DomElement.getStyles(node.parentNode) || {}12535};12536Base.each(attributes, function(apply, name) {12537var value = getAttribute(node, name, styles);12538if (value !== undefined)12539item = Base.pick(apply(item, value, name, node, styles), item);12540});12541return item;12542}1254312544var definitions = {};12545function getDefinition(value) {12546var match = value && value.match(/\((?:#|)([^)']+)/);12547return match && definitions[match[1]];12548}1254912550function importSVG(source, isRoot, options) {12551if (!source)12552return null;12553if (!options) {12554options = {};12555} else if (typeof options === 'function') {12556options = { onLoad: options };12557}1255812559var node = source,12560scope = paper;1256112562function onLoadCallback(svg) {12563paper = scope;12564var item = importSVG(svg, isRoot, options),12565onLoad = options.onLoad,12566view = scope.project && scope.getView();12567if (onLoad)12568onLoad.call(this, item);12569view.update();12570}1257112572if (isRoot) {12573if (typeof source === 'string' && !/^.*</.test(source)) {12574node = document.getElementById(source);12575if (node) {12576source = null;12577} else {12578return Http.request('get', source, onLoadCallback);12579}12580} else if (typeof File !== 'undefined' && source instanceof File) {12581var reader = new FileReader();12582reader.onload = function() {12583onLoadCallback(reader.result);12584};12585return reader.readAsText(source);12586}12587}1258812589if (typeof source === 'string')12590node = new DOMParser().parseFromString(source, 'image/svg+xml');12591if (!node.nodeName)12592throw new Error('Unsupported SVG source: ' + source);12593var type = node.nodeName.toLowerCase(),12594importer = importers[type],12595item,12596data = node.getAttribute && node.getAttribute('data-paper-data'),12597settings = scope.settings,12598prevApplyMatrix = settings.applyMatrix;12599settings.applyMatrix = false;12600item = importer && importer(node, type, isRoot, options) || null;12601settings.applyMatrix = prevApplyMatrix;12602if (item) {12603if (!(item instanceof Group))12604item = applyAttributes(item, node, isRoot);12605if (options.expandShapes && item instanceof Shape) {12606item.remove();12607item = item.toPath();12608}12609if (data)12610item._data = JSON.parse(data);12611}12612if (isRoot)12613definitions = {};12614return item;12615}1261612617Item.inject({12618importSVG: function(node, options) {12619return this.addChild(importSVG(node, true, options));12620}12621});1262212623Project.inject({12624importSVG: function(node, options) {12625this.activate();12626return importSVG(node, true, options);12627}12628});12629};1263012631Base.exports.PaperScript = (function() {12632var exports, define,12633scope = this;12634!function(e,r){return"object"==typeof exports&&"object"==typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):(r(e.acorn||(e.acorn={})),void 0)}(this,function(e){"use strict";function r(e){fr=e||{};for(var r in hr)Object.prototype.hasOwnProperty.call(fr,r)||(fr[r]=hr[r]);mr=fr.sourceFile||null}function t(e,r){var t=vr(pr,e);r+=" ("+t.line+":"+t.column+")";var n=new SyntaxError(r);throw n.pos=e,n.loc=t,n.raisedAt=br,n}function n(e){function r(e){if(1==e.length)return t+="return str === "+JSON.stringify(e[0])+";";t+="switch(str){";for(var r=0;r<e.length;++r)t+="case "+JSON.stringify(e[r])+":";t+="return true}return false;"}e=e.split(" ");var t="",n=[];e:for(var a=0;a<e.length;++a){for(var o=0;o<n.length;++o)if(n[o][0].length==e[a].length){n[o].push(e[a]);continue e}n.push([e[a]])}if(n.length>3){n.sort(function(e,r){return r.length-e.length}),t+="switch(str.length){";for(var a=0;a<n.length;++a){var i=n[a];t+="case "+i[0].length+":",r(i)}t+="}"}else r(e);return new Function("str",t)}function a(){this.line=Ar,this.column=br-Sr}function o(){Ar=1,br=Sr=0,Er=!0,u()}function i(e,r){gr=br,fr.locations&&(kr=new a),wr=e,u(),Cr=r,Er=e.beforeExpr}function s(){var e=fr.onComment&&fr.locations&&new a,r=br,n=pr.indexOf("*/",br+=2);if(-1===n&&t(br-2,"Unterminated comment"),br=n+2,fr.locations){Kt.lastIndex=r;for(var o;(o=Kt.exec(pr))&&o.index<br;)++Ar,Sr=o.index+o[0].length}fr.onComment&&fr.onComment(!0,pr.slice(r+2,n),r,br,e,fr.locations&&new a)}function c(){for(var e=br,r=fr.onComment&&fr.locations&&new a,t=pr.charCodeAt(br+=2);dr>br&&10!==t&&13!==t&&8232!==t&&8329!==t;)++br,t=pr.charCodeAt(br);fr.onComment&&fr.onComment(!1,pr.slice(e+2,br),e,br,r,fr.locations&&new a)}function u(){for(;dr>br;){var e=pr.charCodeAt(br);if(32===e)++br;else if(13===e){++br;var r=pr.charCodeAt(br);10===r&&++br,fr.locations&&(++Ar,Sr=br)}else if(10===e)++br,++Ar,Sr=br;else if(14>e&&e>8)++br;else if(47===e){var r=pr.charCodeAt(br+1);if(42===r)s();else{if(47!==r)break;c()}}else if(160===e)++br;else{if(!(e>=5760&&Jt.test(String.fromCharCode(e))))break;++br}}}function l(){var e=pr.charCodeAt(br+1);return e>=48&&57>=e?E(!0):(++br,i(xt))}function f(){var e=pr.charCodeAt(br+1);return Er?(++br,k()):61===e?x(Et,2):x(wt,1)}function p(){var e=pr.charCodeAt(br+1);return 61===e?x(Et,2):x(Ft,1)}function d(e){var r=pr.charCodeAt(br+1);return r===e?x(124===e?Lt:Ut,2):61===r?x(Et,2):x(124===e?Rt:Vt,1)}function m(){var e=pr.charCodeAt(br+1);return 61===e?x(Et,2):x(Tt,1)}function h(e){var r=pr.charCodeAt(br+1);return r===e?x(St,2):61===r?x(Et,2):x(At,1)}function v(e){var r=pr.charCodeAt(br+1),t=1;return r===e?(t=62===e&&62===pr.charCodeAt(br+2)?3:2,61===pr.charCodeAt(br+t)?x(Et,t+1):x(jt,t)):(61===r&&(t=61===pr.charCodeAt(br+2)?3:2),x(Ot,t))}function b(e){var r=pr.charCodeAt(br+1);return 61===r?x(qt,61===pr.charCodeAt(br+2)?3:2):x(61===e?Ct:It,1)}function y(e){switch(e){case 46:return l();case 40:return++br,i(ht);case 41:return++br,i(vt);case 59:return++br,i(yt);case 44:return++br,i(bt);case 91:return++br,i(ft);case 93:return++br,i(pt);case 123:return++br,i(dt);case 125:return++br,i(mt);case 58:return++br,i(gt);case 63:return++br,i(kt);case 48:var r=pr.charCodeAt(br+1);if(120===r||88===r)return C();case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return E(!1);case 34:case 39:return A(e);case 47:return f(e);case 37:case 42:return p();case 124:case 38:return d(e);case 94:return m();case 43:case 45:return h(e);case 60:case 62:return v(e);case 61:case 33:return b(e);case 126:return x(It,1)}return!1}function g(e){if(e?br=yr+1:yr=br,fr.locations&&(xr=new a),e)return k();if(br>=dr)return i(Br);var r=pr.charCodeAt(br);if(Qt(r)||92===r)return L();var n=y(r);if(n===!1){var o=String.fromCharCode(r);if("\\"===o||$t.test(o))return L();t(br,"Unexpected character '"+o+"'")}return n}function x(e,r){var t=pr.slice(br,br+r);br+=r,i(e,t)}function k(){for(var e,r,n="",a=br;;){br>=dr&&t(a,"Unterminated regular expression");var o=pr.charAt(br);if(Gt.test(o)&&t(a,"Unterminated regular expression"),e)e=!1;else{if("["===o)r=!0;else if("]"===o&&r)r=!1;else if("/"===o&&!r)break;e="\\"===o}++br}var n=pr.slice(a,br);++br;var s=I();return s&&!/^[gmsiy]*$/.test(s)&&t(a,"Invalid regexp flag"),i(jr,new RegExp(n,s))}function w(e,r){for(var t=br,n=0,a=0,o=null==r?1/0:r;o>a;++a){var i,s=pr.charCodeAt(br);if(i=s>=97?s-97+10:s>=65?s-65+10:s>=48&&57>=s?s-48:1/0,i>=e)break;++br,n=n*e+i}return br===t||null!=r&&br-t!==r?null:n}function C(){br+=2;var e=w(16);return null==e&&t(yr+2,"Expected hexadecimal number"),Qt(pr.charCodeAt(br))&&t(br,"Identifier directly after number"),i(Or,e)}function E(e){var r=br,n=!1,a=48===pr.charCodeAt(br);e||null!==w(10)||t(r,"Invalid number"),46===pr.charCodeAt(br)&&(++br,w(10),n=!0);var o=pr.charCodeAt(br);(69===o||101===o)&&(o=pr.charCodeAt(++br),(43===o||45===o)&&++br,null===w(10)&&t(r,"Invalid number"),n=!0),Qt(pr.charCodeAt(br))&&t(br,"Identifier directly after number");var s,c=pr.slice(r,br);return n?s=parseFloat(c):a&&1!==c.length?/[89]/.test(c)||Vr?t(r,"Invalid number"):s=parseInt(c,8):s=parseInt(c,10),i(Or,s)}function A(e){br++;for(var r="";;){br>=dr&&t(yr,"Unterminated string constant");var n=pr.charCodeAt(br);if(n===e)return++br,i(Fr,r);if(92===n){n=pr.charCodeAt(++br);var a=/^[0-7]+/.exec(pr.slice(br,br+3));for(a&&(a=a[0]);a&&parseInt(a,8)>255;)a=a.slice(0,a.length-1);if("0"===a&&(a=null),++br,a)Vr&&t(br-2,"Octal literal in strict mode"),r+=String.fromCharCode(parseInt(a,8)),br+=a.length-1;else switch(n){case 110:r+="\n";break;case 114:r+="\r";break;case 120:r+=String.fromCharCode(S(2));break;case 117:r+=String.fromCharCode(S(4));break;case 85:r+=String.fromCharCode(S(8));break;case 116:r+=" ";break;case 98:r+="\b";break;case 118:r+="";break;case 102:r+="\f";break;case 48:r+="\0";break;case 13:10===pr.charCodeAt(br)&&++br;case 10:fr.locations&&(Sr=br,++Ar);break;default:r+=String.fromCharCode(n)}}else(13===n||10===n||8232===n||8329===n)&&t(yr,"Unterminated string constant"),r+=String.fromCharCode(n),++br}}function S(e){var r=w(16,e);return null===r&&t(yr,"Bad character escape sequence"),r}function I(){Bt=!1;for(var e,r=!0,n=br;;){var a=pr.charCodeAt(br);if(Yt(a))Bt&&(e+=pr.charAt(br)),++br;else{if(92!==a)break;Bt||(e=pr.slice(n,br)),Bt=!0,117!=pr.charCodeAt(++br)&&t(br,"Expecting Unicode escape sequence \\uXXXX"),++br;var o=S(4),i=String.fromCharCode(o);i||t(br-1,"Invalid Unicode escape"),(r?Qt(o):Yt(o))||t(br-4,"Invalid Unicode escape"),e+=i}r=!1}return Bt?e:pr.slice(n,br)}function L(){var e=I(),r=Dr;return Bt||(Wt(e)?r=lt[e]:(fr.forbidReserved&&(3===fr.ecmaVersion?Mt:zt)(e)||Vr&&Xt(e))&&t(yr,"The keyword '"+e+"' is reserved")),i(r,e)}function U(){Ir=yr,Lr=gr,Ur=kr,g()}function R(e){for(Vr=e,br=Lr;Sr>br;)Sr=pr.lastIndexOf("\n",Sr-2)+1,--Ar;u(),g()}function T(){this.type=null,this.start=yr,this.end=null}function V(){this.start=xr,this.end=null,null!==mr&&(this.source=mr)}function q(){var e=new T;return fr.locations&&(e.loc=new V),fr.ranges&&(e.range=[yr,0]),e}function O(e){var r=new T;return r.start=e.start,fr.locations&&(r.loc=new V,r.loc.start=e.loc.start),fr.ranges&&(r.range=[e.range[0],0]),r}function j(e,r){return e.type=r,e.end=Lr,fr.locations&&(e.loc.end=Ur),fr.ranges&&(e.range[1]=Lr),e}function F(e){return fr.ecmaVersion>=5&&"ExpressionStatement"===e.type&&"Literal"===e.expression.type&&"use strict"===e.expression.value}function D(e){return wr===e?(U(),!0):void 0}function B(){return!fr.strictSemicolons&&(wr===Br||wr===mt||Gt.test(pr.slice(Lr,yr)))}function M(){D(yt)||B()||X()}function z(e){wr===e?U():X()}function X(){t(yr,"Unexpected token")}function N(e){"Identifier"!==e.type&&"MemberExpression"!==e.type&&t(e.start,"Assigning to rvalue"),Vr&&"Identifier"===e.type&&Nt(e.name)&&t(e.start,"Assigning to "+e.name+" in strict mode")}function W(e){Ir=Lr=br,fr.locations&&(Ur=new a),Rr=Vr=null,Tr=[],g();var r=e||q(),t=!0;for(e||(r.body=[]);wr!==Br;){var n=J();r.body.push(n),t&&F(n)&&R(!0),t=!1}return j(r,"Program")}function J(){wr===wt&&g(!0);var e=wr,r=q();switch(e){case Mr:case Nr:U();var n=e===Mr;D(yt)||B()?r.label=null:wr!==Dr?X():(r.label=lr(),M());for(var a=0;a<Tr.length;++a){var o=Tr[a];if(null==r.label||o.name===r.label.name){if(null!=o.kind&&(n||"loop"===o.kind))break;if(r.label&&n)break}}return a===Tr.length&&t(r.start,"Unsyntactic "+e.keyword),j(r,n?"BreakStatement":"ContinueStatement");case Wr:return U(),M(),j(r,"DebuggerStatement");case Pr:return U(),Tr.push(Zt),r.body=J(),Tr.pop(),z(tt),r.test=P(),M(),j(r,"DoWhileStatement");case _r:if(U(),Tr.push(Zt),z(ht),wr===yt)return $(r,null);if(wr===rt){var i=q();return U(),G(i,!0),1===i.declarations.length&&D(ut)?_(r,i):$(r,i)}var i=K(!1,!0);return D(ut)?(N(i),_(r,i)):$(r,i);case Gr:return U(),cr(r,!0);case Kr:return U(),r.test=P(),r.consequent=J(),r.alternate=D(Hr)?J():null,j(r,"IfStatement");case Qr:return Rr||t(yr,"'return' outside of function"),U(),D(yt)||B()?r.argument=null:(r.argument=K(),M()),j(r,"ReturnStatement");case Yr:U(),r.discriminant=P(),r.cases=[],z(dt),Tr.push(en);for(var s,c;wr!=mt;)if(wr===zr||wr===Jr){var u=wr===zr;s&&j(s,"SwitchCase"),r.cases.push(s=q()),s.consequent=[],U(),u?s.test=K():(c&&t(Ir,"Multiple default clauses"),c=!0,s.test=null),z(gt)}else s||X(),s.consequent.push(J());return s&&j(s,"SwitchCase"),U(),Tr.pop(),j(r,"SwitchStatement");case Zr:return U(),Gt.test(pr.slice(Lr,yr))&&t(Lr,"Illegal newline after throw"),r.argument=K(),M(),j(r,"ThrowStatement");case et:if(U(),r.block=H(),r.handler=null,wr===Xr){var l=q();U(),z(ht),l.param=lr(),Vr&&Nt(l.param.name)&&t(l.param.start,"Binding "+l.param.name+" in strict mode"),z(vt),l.guard=null,l.body=H(),r.handler=j(l,"CatchClause")}return r.guardedHandlers=qr,r.finalizer=D($r)?H():null,r.handler||r.finalizer||t(r.start,"Missing catch or finally clause"),j(r,"TryStatement");case rt:return U(),r=G(r),M(),r;case tt:return U(),r.test=P(),Tr.push(Zt),r.body=J(),Tr.pop(),j(r,"WhileStatement");case nt:return Vr&&t(yr,"'with' in strict mode"),U(),r.object=P(),r.body=J(),j(r,"WithStatement");case dt:return H();case yt:return U(),j(r,"EmptyStatement");default:var f=Cr,p=K();if(e===Dr&&"Identifier"===p.type&&D(gt)){for(var a=0;a<Tr.length;++a)Tr[a].name===f&&t(p.start,"Label '"+f+"' is already declared");var d=wr.isLoop?"loop":wr===Yr?"switch":null;return Tr.push({name:f,kind:d}),r.body=J(),Tr.pop(),r.label=p,j(r,"LabeledStatement")}return r.expression=p,M(),j(r,"ExpressionStatement")}}function P(){z(ht);var e=K();return z(vt),e}function H(e){var r,t=q(),n=!0,a=!1;for(t.body=[],z(dt);!D(mt);){var o=J();t.body.push(o),n&&e&&F(o)&&(r=a,R(a=!0)),n=!1}return a&&!r&&R(!1),j(t,"BlockStatement")}function $(e,r){return e.init=r,z(yt),e.test=wr===yt?null:K(),z(yt),e.update=wr===vt?null:K(),z(vt),e.body=J(),Tr.pop(),j(e,"ForStatement")}function _(e,r){return e.left=r,e.right=K(),z(vt),e.body=J(),Tr.pop(),j(e,"ForInStatement")}function G(e,r){for(e.declarations=[],e.kind="var";;){var n=q();if(n.id=lr(),Vr&&Nt(n.id.name)&&t(n.id.start,"Binding "+n.id.name+" in strict mode"),n.init=D(Ct)?K(!0,r):null,e.declarations.push(j(n,"VariableDeclarator")),!D(bt))break}return j(e,"VariableDeclaration")}function K(e,r){var t=Q(r);if(!e&&wr===bt){var n=O(t);for(n.expressions=[t];D(bt);)n.expressions.push(Q(r));return j(n,"SequenceExpression")}return t}function Q(e){var r=Y(e);if(wr.isAssign){var t=O(r);return t.operator=Cr,t.left=r,U(),t.right=Q(e),N(r),j(t,"AssignmentExpression")}return r}function Y(e){var r=Z(e);if(D(kt)){var t=O(r);return t.test=r,t.consequent=K(!0),z(gt),t.alternate=K(!0,e),j(t,"ConditionalExpression")}return r}function Z(e){return er(rr(),-1,e)}function er(e,r,t){var n=wr.binop;if(null!=n&&(!t||wr!==ut)&&n>r){var a=O(e);a.left=e,a.operator=Cr,U(),a.right=er(rr(),n,t);var a=j(a,/&&|\|\|/.test(a.operator)?"LogicalExpression":"BinaryExpression");return er(a,r,t)}return e}function rr(){if(wr.prefix){var e=q(),r=wr.isUpdate;return e.operator=Cr,e.prefix=!0,U(),e.argument=rr(),r?N(e.argument):Vr&&"delete"===e.operator&&"Identifier"===e.argument.type&&t(e.start,"Deleting local variable in strict mode"),j(e,r?"UpdateExpression":"UnaryExpression")}for(var n=tr();wr.postfix&&!B();){var e=O(n);e.operator=Cr,e.prefix=!1,e.argument=n,N(n),U(),n=j(e,"UpdateExpression")}return n}function tr(){return nr(ar())}function nr(e,r){if(D(xt)){var t=O(e);return t.object=e,t.property=lr(!0),t.computed=!1,nr(j(t,"MemberExpression"),r)}if(D(ft)){var t=O(e);return t.object=e,t.property=K(),t.computed=!0,z(pt),nr(j(t,"MemberExpression"),r)}if(!r&&D(ht)){var t=O(e);return t.callee=e,t.arguments=ur(vt,!1),nr(j(t,"CallExpression"),r)}return e}function ar(){switch(wr){case ot:var e=q();return U(),j(e,"ThisExpression");case Dr:return lr();case Or:case Fr:case jr:var e=q();return e.value=Cr,e.raw=pr.slice(yr,gr),U(),j(e,"Literal");case it:case st:case ct:var e=q();return e.value=wr.atomValue,e.raw=wr.keyword,U(),j(e,"Literal");case ht:var r=xr,t=yr;U();var n=K();return n.start=t,n.end=gr,fr.locations&&(n.loc.start=r,n.loc.end=kr),fr.ranges&&(n.range=[t,gr]),z(vt),n;case ft:var e=q();return U(),e.elements=ur(pt,!0,!0),j(e,"ArrayExpression");case dt:return ir();case Gr:var e=q();return U(),cr(e,!1);case at:return or();default:X()}}function or(){var e=q();return U(),e.callee=nr(ar(),!0),e.arguments=D(ht)?ur(vt,!1):qr,j(e,"NewExpression")}function ir(){var e=q(),r=!0,n=!1;for(e.properties=[],U();!D(mt);){if(r)r=!1;else if(z(bt),fr.allowTrailingCommas&&D(mt))break;var a,o={key:sr()},i=!1;if(D(gt)?(o.value=K(!0),a=o.kind="init"):fr.ecmaVersion>=5&&"Identifier"===o.key.type&&("get"===o.key.name||"set"===o.key.name)?(i=n=!0,a=o.kind=o.key.name,o.key=sr(),wr!==ht&&X(),o.value=cr(q(),!1)):X(),"Identifier"===o.key.type&&(Vr||n))for(var s=0;s<e.properties.length;++s){var c=e.properties[s];if(c.key.name===o.key.name){var u=a==c.kind||i&&"init"===c.kind||"init"===a&&("get"===c.kind||"set"===c.kind);u&&!Vr&&"init"===a&&"init"===c.kind&&(u=!1),u&&t(o.key.start,"Redefinition of property")}}e.properties.push(o)}return j(e,"ObjectExpression")}function sr(){return wr===Or||wr===Fr?ar():lr(!0)}function cr(e,r){wr===Dr?e.id=lr():r?X():e.id=null,e.params=[];var n=!0;for(z(ht);!D(vt);)n?n=!1:z(bt),e.params.push(lr());var a=Rr,o=Tr;if(Rr=!0,Tr=[],e.body=H(!0),Rr=a,Tr=o,Vr||e.body.body.length&&F(e.body.body[0]))for(var i=e.id?-1:0;i<e.params.length;++i){var s=0>i?e.id:e.params[i];if((Xt(s.name)||Nt(s.name))&&t(s.start,"Defining '"+s.name+"' in strict mode"),i>=0)for(var c=0;i>c;++c)s.name===e.params[c].name&&t(s.start,"Argument name clash in strict mode")}return j(e,r?"FunctionDeclaration":"FunctionExpression")}function ur(e,r,t){for(var n=[],a=!0;!D(e);){if(a)a=!1;else if(z(bt),r&&fr.allowTrailingCommas&&D(e))break;t&&wr===bt?n.push(null):n.push(K(!0))}return n}function lr(e){var r=q();return r.name=wr===Dr?Cr:e&&!fr.forbidReserved&&wr.keyword||X(),U(),j(r,"Identifier")}e.version="0.3.2";var fr,pr,dr,mr;e.parse=function(e,t){return pr=String(e),dr=pr.length,r(t),o(),W(fr.program)};var hr=e.defaultOptions={ecmaVersion:5,strictSemicolons:!1,allowTrailingCommas:!0,forbidReserved:!1,locations:!1,onComment:null,ranges:!1,program:null,sourceFile:null},vr=e.getLineInfo=function(e,r){for(var t=1,n=0;;){Kt.lastIndex=n;var a=Kt.exec(e);if(!(a&&a.index<r))break;++t,n=a.index+a[0].length}return{line:t,column:r-n}};e.tokenize=function(e,t){function n(e){return g(e),a.start=yr,a.end=gr,a.startLoc=xr,a.endLoc=kr,a.type=wr,a.value=Cr,a}pr=String(e),dr=pr.length,r(t),o();var a={};return n.jumpTo=function(e,r){if(br=e,fr.locations){Ar=1,Sr=Kt.lastIndex=0;for(var t;(t=Kt.exec(pr))&&t.index<e;)++Ar,Sr=t.index+t[0].length}Er=r,u()},n};var br,yr,gr,xr,kr,wr,Cr,Er,Ar,Sr,Ir,Lr,Ur,Rr,Tr,Vr,qr=[],Or={type:"num"},jr={type:"regexp"},Fr={type:"string"},Dr={type:"name"},Br={type:"eof"},Mr={keyword:"break"},zr={keyword:"case",beforeExpr:!0},Xr={keyword:"catch"},Nr={keyword:"continue"},Wr={keyword:"debugger"},Jr={keyword:"default"},Pr={keyword:"do",isLoop:!0},Hr={keyword:"else",beforeExpr:!0},$r={keyword:"finally"},_r={keyword:"for",isLoop:!0},Gr={keyword:"function"},Kr={keyword:"if"},Qr={keyword:"return",beforeExpr:!0},Yr={keyword:"switch"},Zr={keyword:"throw",beforeExpr:!0},et={keyword:"try"},rt={keyword:"var"},tt={keyword:"while",isLoop:!0},nt={keyword:"with"},at={keyword:"new",beforeExpr:!0},ot={keyword:"this"},it={keyword:"null",atomValue:null},st={keyword:"true",atomValue:!0},ct={keyword:"false",atomValue:!1},ut={keyword:"in",binop:7,beforeExpr:!0},lt={"break":Mr,"case":zr,"catch":Xr,"continue":Nr,"debugger":Wr,"default":Jr,"do":Pr,"else":Hr,"finally":$r,"for":_r,"function":Gr,"if":Kr,"return":Qr,"switch":Yr,"throw":Zr,"try":et,"var":rt,"while":tt,"with":nt,"null":it,"true":st,"false":ct,"new":at,"in":ut,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:!0},"this":ot,"typeof":{keyword:"typeof",prefix:!0,beforeExpr:!0},"void":{keyword:"void",prefix:!0,beforeExpr:!0},"delete":{keyword:"delete",prefix:!0,beforeExpr:!0}},ft={type:"[",beforeExpr:!0},pt={type:"]"},dt={type:"{",beforeExpr:!0},mt={type:"}"},ht={type:"(",beforeExpr:!0},vt={type:")"},bt={type:",",beforeExpr:!0},yt={type:";",beforeExpr:!0},gt={type:":",beforeExpr:!0},xt={type:"."},kt={type:"?",beforeExpr:!0},wt={binop:10,beforeExpr:!0},Ct={isAssign:!0,beforeExpr:!0},Et={isAssign:!0,beforeExpr:!0},At={binop:9,prefix:!0,beforeExpr:!0},St={postfix:!0,prefix:!0,isUpdate:!0},It={prefix:!0,beforeExpr:!0},Lt={binop:1,beforeExpr:!0},Ut={binop:2,beforeExpr:!0},Rt={binop:3,beforeExpr:!0},Tt={binop:4,beforeExpr:!0},Vt={binop:5,beforeExpr:!0},qt={binop:6,beforeExpr:!0},Ot={binop:7,beforeExpr:!0},jt={binop:8,beforeExpr:!0},Ft={binop:10,beforeExpr:!0};e.tokTypes={bracketL:ft,bracketR:pt,braceL:dt,braceR:mt,parenL:ht,parenR:vt,comma:bt,semi:yt,colon:gt,dot:xt,question:kt,slash:wt,eq:Ct,name:Dr,eof:Br,num:Or,regexp:jr,string:Fr};for(var Dt in lt)e.tokTypes["_"+Dt]=lt[Dt];var Bt,Mt=n("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile"),zt=n("class enum extends super const export import"),Xt=n("implements interface let package private protected public static yield"),Nt=n("eval arguments"),Wt=n("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this"),Jt=/[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/,Pt="\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc",Ht="\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f",$t=new RegExp("["+Pt+"]"),_t=new RegExp("["+Pt+Ht+"]"),Gt=/[\n\r\u2028\u2029]/,Kt=/\r\n|[\n\r\u2028\u2029]/g,Qt=e.isIdentifierStart=function(e){return 65>e?36===e:91>e?!0:97>e?95===e:123>e?!0:e>=170&&$t.test(String.fromCharCode(e))},Yt=e.isIdentifierChar=function(e){return 48>e?36===e:58>e?!0:65>e?!1:91>e?!0:97>e?95===e:123>e?!0:e>=170&&_t.test(String.fromCharCode(e))},Zt={kind:"loop"},en={kind:"switch"}});1263512636var binaryOperators = {12637'+': '__add',12638'-': '__subtract',12639'*': '__multiply',12640'/': '__divide',12641'%': '__modulo',12642'==': 'equals',12643'!=': 'equals'12644};1264512646var unaryOperators = {12647'-': '__negate',12648'+': null12649};1265012651var fields = Base.each(12652['add', 'subtract', 'multiply', 'divide', 'modulo', 'negate'],12653function(name) {12654this['__' + name] = '#' + name;12655},12656{}12657);12658Point.inject(fields);12659Size.inject(fields);12660Color.inject(fields);1266112662function _$_(left, operator, right) {12663var handler = binaryOperators[operator];12664if (left && left[handler]) {12665var res = left[handler](right);12666return operator === '!=' ? !res : res;12667}12668switch (operator) {12669case '+': return left + right;12670case '-': return left - right;12671case '*': return left * right;12672case '/': return left / right;12673case '%': return left % right;12674case '==': return left == right;12675case '!=': return left != right;12676}12677}1267812679function $_(operator, value) {12680var handler = unaryOperators[operator];12681if (handler && value && value[handler])12682return value[handler]();12683switch (operator) {12684case '+': return +value;12685case '-': return -value;12686}12687}1268812689function compile(code) {1269012691var insertions = [];1269212693function getOffset(offset) {12694for (var i = 0, l = insertions.length; i < l; i++) {12695var insertion = insertions[i];12696if (insertion[0] >= offset)12697break;12698offset += insertion[1];12699}12700return offset;12701}1270212703function getCode(node) {12704return code.substring(getOffset(node.range[0]),12705getOffset(node.range[1]));12706}1270712708function replaceCode(node, str) {12709var start = getOffset(node.range[0]),12710end = getOffset(node.range[1]),12711insert = 0;12712for (var i = insertions.length - 1; i >= 0; i--) {12713if (start > insertions[i][0]) {12714insert = i + 1;12715break;12716}12717}12718insertions.splice(insert, 0, [start, str.length - end + start]);12719code = code.substring(0, start) + str + code.substring(end);12720}1272112722function walkAST(node, parent) {12723if (!node)12724return;12725for (var key in node) {12726if (key === 'range')12727continue;12728var value = node[key];12729if (Array.isArray(value)) {12730for (var i = 0, l = value.length; i < l; i++)12731walkAST(value[i], node);12732} else if (value && typeof value === 'object') {12733walkAST(value, node);12734}12735}12736switch (node && node.type) {12737case 'UnaryExpression':12738if (node.operator in unaryOperators12739&& node.argument.type !== 'Literal') {12740var arg = getCode(node.argument);12741replaceCode(node, '$_("' + node.operator + '", '12742+ arg + ')');12743}12744break;12745case 'BinaryExpression':12746if (node.operator in binaryOperators12747&& node.left.type !== 'Literal') {12748var left = getCode(node.left),12749right = getCode(node.right);12750replaceCode(node, '_$_(' + left + ', "' + node.operator12751+ '", ' + right + ')');12752}12753break;12754case 'UpdateExpression':12755case 'AssignmentExpression':12756if (!(parent && (12757parent.type === 'ForStatement'12758|| parent.type === 'BinaryExpression'12759&& /^[=!<>]/.test(parent.operator)12760|| parent.type === 'MemberExpression'12761&& parent.computed))) {12762if (node.type === 'UpdateExpression') {12763if (!node.prefix) {12764var arg = getCode(node.argument);12765replaceCode(node, arg + ' = _$_(' + arg + ', "'12766+ node.operator[0] + '", 1)');12767}12768} else {12769if (/^.=$/.test(node.operator)12770&& node.left.type !== 'Literal') {12771var left = getCode(node.left),12772right = getCode(node.right);12773replaceCode(node, left + ' = _$_(' + left + ', "'12774+ node.operator[0] + '", ' + right + ')');12775}12776}12777}12778break;12779}12780}12781walkAST(scope.acorn.parse(code, { ranges: true }));12782return code;12783}1278412785function execute(code, scope) {12786paper = scope;12787var view = scope.getView(),12788tool = /\s+on(?:Key|Mouse)(?:Up|Down|Move|Drag)\b/.test(code)12789? new Tool()12790: null,12791toolHandlers = tool ? tool._events : [],12792handlers = ['onFrame', 'onResize'].concat(toolHandlers),12793params = [],12794args = [],12795func;12796code = compile(code);12797function expose(scope, hidden) {12798for (var key in scope) {12799if ((hidden || !/^_/.test(key)) && new RegExp(12800'\\b' + key.replace(/\$/g, '\\$') + '\\b').test(code)) {12801params.push(key);12802args.push(scope[key]);12803}12804}12805}12806expose({ _$_: _$_, $_: $_, view: view, tool: tool }, true);12807expose(scope);12808handlers = Base.each(handlers, function(key) {12809if (new RegExp('\\s+' + key + '\\b').test(code)) {12810params.push(key);12811this.push(key + ': ' + key);12812}12813}, []).join(', ');12814if (handlers)12815code += '\nreturn { ' + handlers + ' };';12816var firefox = window.InstallTrigger;12817if (firefox || window.chrome) {12818var script = document.createElement('script'),12819head = document.head;12820if (firefox)12821code = '\n' + code;12822script.appendChild(document.createTextNode(12823'paper._execute = function(' + params + ') {' + code + '\n}'12824));12825head.appendChild(script);12826func = paper._execute;12827delete paper._execute;12828head.removeChild(script);12829} else {12830func = Function(params, code);12831}12832var res = func.apply(scope, args) || {};12833Base.each(toolHandlers, function(key) {12834var value = res[key];12835if (value)12836tool[key] = value;12837});12838if (view) {12839if (res.onResize)12840view.setOnResize(res.onResize);12841view.fire('resize', {12842size: view.size,12843delta: new Point()12844});12845if (res.onFrame)12846view.setOnFrame(res.onFrame);12847view.update();12848}12849}1285012851function load() {12852Base.each(document.getElementsByTagName('script'), function(script) {12853if (/^text\/(?:x-|)paperscript$/.test(script.type)12854&& !script.getAttribute('data-paper-ignore')) {12855var canvas = PaperScope.getAttribute(script, 'canvas'),12856scope = PaperScope.get(canvas)12857|| new PaperScope(script).setup(canvas),12858src = script.src;12859if (src) {12860Http.request('get', src, function(code) {12861execute(code, scope);12862});12863} else {12864execute(script.innerHTML, scope);12865}12866script.setAttribute('data-paper-ignore', true);12867}12868}, this);12869}1287012871if (document.readyState === 'complete') {12872setTimeout(load);12873} else {12874DomEvent.add(window, { load: load });12875}1287612877return {12878compile: compile,12879execute: execute,12880load: load,12881lineNumberBase: 012882};1288312884}).call(this);1288512886paper = new (PaperScope.inject(Base.exports, {12887enumerable: true,12888Base: Base,12889Numerical: Numerical,12890DomElement: DomElement,12891DomEvent: DomEvent,12892Http: Http,12893Key: Key12894}))();1289512896if (typeof define === 'function' && define.amd)12897define('paper', paper);1289812899return paper;12900};129011290212903