From 3078d127a9cea2e1556de34b837d75a8c68deab7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=BCrg=20Lehni?= Date: Wed, 26 Jun 2013 19:42:24 -0700 Subject: [PATCH] Update version to v0.9.5. --- dist/paper-core.js | 11062 ++++++++++++++++++++++++++++++++++++++ dist/paper-core.min.js | 36 + dist/paper-full.js | 11274 +++++++++++++++++++++++++++++++++++++++ dist/paper-full.min.js | 37 + dist/paper.js | 2 +- package.json | 2 +- 6 files changed, 22411 insertions(+), 2 deletions(-) create mode 100644 dist/paper-core.js create mode 100644 dist/paper-core.min.js create mode 100644 dist/paper-full.js create mode 100644 dist/paper-full.min.js diff --git a/dist/paper-core.js b/dist/paper-core.js new file mode 100644 index 00000000..c09fdeaf --- /dev/null +++ b/dist/paper-core.js @@ -0,0 +1,11062 @@ +/*! + * Paper.js v0.9.5 - The Swiss Army Knife of Vector Graphics Scripting. + * http://paperjs.org/ + * + * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey + * http://lehni.org/ & http://jonathanpuckey.com/ + * + * Distributed under the MIT license. See LICENSE file for details. + * + * All rights reserved. + * + * Date: Wed Jun 26 19:42:04 2013 -0700 + * + *** + * + * straps.js - Class inheritance library with support for bean-style accessors + * + * Copyright (c) 2006 - 2013 Juerg Lehni + * http://lehni.org/ + * + * Distributed under the MIT license. + * + *** + * + * acorn.js + * http://marijnhaverbeke.nl/acorn/ + * + * Acorn is a tiny, fast JavaScript parser written in JavaScript, + * created by Marijn Haverbeke and released under an MIT license. + * + */ + +var paper = new function() { + +var Base = new function() { + var hidden = /^(statics|generics|preserve|enumerable|prototype|toString|valueOf)$/, + toString = Object.prototype.toString, + proto = Array.prototype, + slice = proto.slice, + + forEach = proto.forEach || function(iter, bind) { + for (var i = 0, l = this.length; i < l; i++) + iter.call(bind, this[i], i, this); + }, + + forIn = function(iter, bind) { + for (var i in this) + if (this.hasOwnProperty(i)) + iter.call(bind, this[i], i, this); + }, + + isArray = Array.isArray = Array.isArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }, + + create = Object.create || function(proto) { + return { __proto__: proto }; + }, + + describe = Object.getOwnPropertyDescriptor || function(obj, name) { + var get = obj.__lookupGetter__ && obj.__lookupGetter__(name); + return get + ? { get: get, set: obj.__lookupSetter__(name), + enumerable: true, configurable: true } + : obj.hasOwnProperty(name) + ? { value: obj[name], enumerable: true, + configurable: true, writable: true } + : null; + }, + + _define = Object.defineProperty || function(obj, name, desc) { + if ((desc.get || desc.set) && obj.__defineGetter__) { + if (desc.get) + obj.__defineGetter__(name, desc.get); + if (desc.set) + obj.__defineSetter__(name, desc.set); + } else { + obj[name] = desc.value; + } + return obj; + }, + + define = function(obj, name, desc) { + delete obj[name]; + return _define(obj, name, desc); + }; + + function inject(dest, src, enumerable, base, preserve, generics) { + var beans; + + function field(name, val, dontCheck, generics) { + var val = val || (val = describe(src, name)) + && (val.get ? val : val.value); + if (typeof val === 'string' && val[0] === '#') + val = src[val.substring(1)] || val; + var isFunc = typeof val === 'function', + res = val, + prev = preserve || isFunc + ? (val && val.get ? name in dest : dest[name]) : null, + bean; + if ((dontCheck || val !== undefined && src.hasOwnProperty(name)) + && (!preserve || !prev)) { + if (isFunc && prev) + val.base = prev; + if (isFunc && beans && val.length === 0 + && (bean = name.match(/^(get|is)(([A-Z])(.*))$/))) + beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]); + if (!res || isFunc || !res.get) + res = { value: res, writable: true }; + if ((describe(dest, name) + || { configurable: true }).configurable) { + res.configurable = true; + res.enumerable = enumerable; + } + define(dest, name, res); + } + if (generics && isFunc && (!preserve || !generics[name])) { + generics[name] = function(bind) { + return bind && dest[name].apply(bind, + slice.call(arguments, 1)); + }; + } + } + if (src) { + beans = []; + for (var name in src) + if (src.hasOwnProperty(name) && !hidden.test(name)) + field(name, null, true, generics); + field('toString'); + field('valueOf'); + for (var i = 0, l = beans && beans.length; i < l; i++) + try { + var bean = beans[i], + part = bean[1]; + field(bean[0], { + get: dest['get' + part] || dest['is' + part], + set: dest['set' + part] + }, true); + } catch (e) {} + } + return dest; + } + + function each(obj, iter, bind, asArray) { + try { + if (obj) + (asArray || typeof asArray === 'undefined' && isArray(obj) + ? forEach : forIn).call(obj, iter, bind = bind || obj); + } catch (e) { + if (e !== Base.stop) + throw e; + } + return bind; + } + + function clone(obj) { + return each(obj, function(val, i) { + this[i] = val; + }, new obj.constructor()); + } + + return inject(function Base() {}, { + inject: function(src) { + if (src) { + var proto = this.prototype, + base = Object.getPrototypeOf(proto).constructor, + statics = src.statics === true ? src : src.statics; + if (statics != src) + inject(proto, src, src.enumerable, base && base.prototype, + src.preserve, src.generics && this); + inject(this, statics, true, base, src.preserve); + } + for (var i = 1, l = arguments.length; i < l; i++) + this.inject(arguments[i]); + return this; + }, + + extend: function() { + var base = this, + ctor; + for (var i = 0, l = arguments.length; i < l; i++) + if (ctor = arguments[i].initialize) + break; + ctor = ctor || function() { + base.apply(this, arguments); + }; + ctor.prototype = create(this.prototype); + define(ctor.prototype, 'constructor', + { value: ctor, writable: true, configurable: true }); + inject(ctor, this, true); + return arguments.length ? this.inject.apply(ctor, arguments) : ctor; + } + }, true).inject({ + inject: function() { + for (var i = 0, l = arguments.length; i < l; i++) + inject(this, arguments[i], arguments[i].enumerable); + return this; + }, + + extend: function() { + var res = create(this); + return res.inject.apply(res, arguments); + }, + + each: function(iter, bind) { + return each(this, iter, bind); + }, + + clone: function() { + return clone(this); + }, + + statics: { + each: each, + clone: clone, + define: define, + describe: describe, + + create: function(ctor) { + return create(ctor.prototype); + }, + + isPlainObject: function(obj) { + var ctor = obj != null && obj.constructor; + return ctor && (ctor === Object || ctor === Base + || ctor.name === 'Object'); + }, + + check: function(obj) { + return !!(obj || obj === 0); + }, + + pick: function() { + for (var i = 0, l = arguments.length; i < l; i++) + if (arguments[i] !== undefined) + return arguments[i]; + return null; + }, + + stop: {} + } + }); +}; + +Base.inject({ + generics: true, + + clone: function() { + return new this.constructor(this); + }, + + toString: function() { + return this._id != null + ? (this._class || 'Object') + (this._name + ? " '" + this._name + "'" + : ' @' + this._id) + : '{ ' + Base.each(this, function(value, key) { + if (!/^_/.test(key)) { + var type = typeof value; + this.push(key + ': ' + (type === 'number' + ? Formatter.instance.number(value) + : type === 'string' ? "'" + value + "'" : value)); + } + }, []).join(', ') + ' }'; + }, + + exportJSON: function(options) { + return Base.exportJSON(this, options); + }, + + toJSON: function() { + return Base.serialize(this); + }, + + _set: function(props) { + if (props && Base.isPlainObject(props)) { + for (var key in props) + if (props.hasOwnProperty(key) && key in this) + this[key] = props[key]; + return true; + } + }, + + statics: { + + exports: {}, + + extend: function extend() { + var res = extend.base.apply(this, arguments), + name = res.prototype._class; + if (name && !Base.exports[name]) + Base.exports[name] = res; + return res; + }, + + equals: function(obj1, obj2) { + function checkKeys(o1, o2) { + for (var i in o1) + if (o1.hasOwnProperty(i) && typeof o2[i] === 'undefined') + return false; + return true; + } + if (obj1 === obj2) + return true; + if (obj1 && obj1.equals) + return obj1.equals(obj2); + if (obj2 && obj2.equals) + return obj2.equals(obj1); + if (Array.isArray(obj1) && Array.isArray(obj2)) { + if (obj1.length !== obj2.length) + return false; + for (var i = 0, l = obj1.length; i < l; i++) { + if (!Base.equals(obj1[i], obj2[i])) + return false; + } + return true; + } + if (obj1 && typeof obj1 === 'object' + && obj2 && typeof obj2 === 'object') { + if (!checkKeys(obj1, obj2) || !checkKeys(obj2, obj1)) + return false; + for (var i in obj1) { + if (obj1.hasOwnProperty(i) && !Base.equals(obj1[i], obj2[i])) + return false; + } + return true; + } + return false; + }, + + read: function(list, start, length, readNull, clone) { + if (this === Base) { + var value = this.peek(list, start); + list._index++; + list._read = 1; + return value; + } + var proto = this.prototype, + readIndex = proto._readIndex, + index = start || readIndex && list._index || 0; + if (!length) + length = list.length - index; + var obj = list[index]; + if (obj instanceof this || readNull && obj == null && length <= 1) { + if (readIndex) + list._index = index + 1; + return obj && clone ? obj.clone() : obj; + } + obj = Base.create(this); + if (readIndex) + obj._read = true; + obj = obj.initialize.apply(obj, index > 0 || length < list.length + ? Array.prototype.slice.call(list, index, index + length) + : list) || obj; + if (readIndex) { + list._index = index + obj._read; + list._read = obj._read; + delete obj._read; + } + return obj; + }, + + peek: function(list, start) { + return list[list._index = start || list._index || 0]; + }, + + readAll: function(list, start, readNull, clone) { + var res = [], entry; + for (var i = start || 0, l = list.length; i < l; i++) { + res.push(Array.isArray(entry = list[i]) + ? this.read(entry, 0, 0, readNull, clone) + : this.read(list, i, 1, readNull, clone)); + } + return res; + }, + + readNamed: function(list, name, start, length, readNull, clone) { + var value = this.getNamed(list, name); + return this.read(value != null ? [value] : list, start, length, + readNull, clone); + }, + + getNamed: function(list, name) { + var arg = list[0]; + if (list._hasObject === undefined) + list._hasObject = list.length === 1 && Base.isPlainObject(arg); + if (list._hasObject) + return name ? arg[name] : arg; + }, + + hasNamed: function(list, name) { + return !!this.getNamed(list, name); + }, + + isPlainValue: function(obj) { + return this.isPlainObject(obj) || Array.isArray(obj); + }, + + serialize: function(obj, options, compact, dictionary) { + options = options || {}; + + var root = !dictionary, + res; + if (root) { + options.formatter = new Formatter(options.precision); + dictionary = { + length: 0, + definitions: {}, + references: {}, + add: function(item, create) { + var id = '#' + item._id, + ref = this.references[id]; + if (!ref) { + this.length++; + var res = create.call(item), + name = item._class; + if (name && res[0] !== name) + res.unshift(name); + this.definitions[id] = res; + ref = this.references[id] = [id]; + } + return ref; + } + }; + } + if (obj && obj._serialize) { + res = obj._serialize(options, dictionary); + var name = obj._class; + if (name && !compact && !res._compact && res[0] !== name) + res.unshift(name); + } else if (Array.isArray(obj)) { + res = []; + for (var i = 0, l = obj.length; i < l; i++) + res[i] = Base.serialize(obj[i], options, compact, + dictionary); + if (compact) + res._compact = true; + } else if (Base.isPlainObject(obj)) { + res = {}; + for (var i in obj) + if (obj.hasOwnProperty(i)) + res[i] = Base.serialize(obj[i], options, compact, + dictionary); + } else if (typeof obj === 'number') { + res = options.formatter.number(obj, options.precision); + } else { + res = obj; + } + return root && dictionary.length > 0 + ? [['dictionary', dictionary.definitions], res] + : res; + }, + + deserialize: function(obj, data) { + var res = obj; + data = data || {}; + if (Array.isArray(obj)) { + var type = obj[0], + isDictionary = type === 'dictionary'; + if (!isDictionary) { + if (data.dictionary && obj.length == 1 && /^#/.test(type)) + return data.dictionary[type]; + type = Base.exports[type]; + } + res = []; + for (var i = type ? 1 : 0, l = obj.length; i < l; i++) + res.push(Base.deserialize(obj[i], data)); + if (isDictionary) { + data.dictionary = res[0]; + } else if (type) { + var args = res; + res = Base.create(type); + type.apply(res, args); + } + } else if (Base.isPlainObject(obj)) { + res = {}; + for (var key in obj) + res[key] = Base.deserialize(obj[key], data); + } + return res; + }, + + exportJSON: function(obj, options) { + return JSON.stringify(Base.serialize(obj, options)); + }, + + importJSON: function(json) { + return Base.deserialize( + typeof json === 'string' ? JSON.parse(json) : json); + }, + + splice: function(list, items, index, remove) { + var amount = items && items.length, + append = index === undefined; + index = append ? list.length : index; + if (index > list.length) + index = list.length; + for (var i = 0; i < amount; i++) + items[i]._index = index + i; + if (append) { + list.push.apply(list, items); + return []; + } else { + var args = [index, remove]; + if (items) + args.push.apply(args, items); + var removed = list.splice.apply(list, args); + for (var i = 0, l = removed.length; i < l; i++) + delete removed[i]._index; + for (var i = index + amount, l = list.length; i < l; i++) + list[i]._index = i; + return removed; + } + }, + + merge: function() { + return Base.each(arguments, function(hash) { + Base.each(hash, function(value, key) { + this[key] = value; + }, this); + }, new Base(), true); + }, + + capitalize: function(str) { + return str.replace(/\b[a-z]/g, function(match) { + return match.toUpperCase(); + }); + }, + + camelize: function(str) { + return str.replace(/-(.)/g, function(all, chr) { + return chr.toUpperCase(); + }); + }, + + hyphenate: function(str) { + return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); + } + } +}); + +var Callback = { + attach: function(type, func) { + if (typeof type !== 'string') { + Base.each(type, function(value, key) { + this.attach(key, value); + }, this); + return; + } + var entry = this._eventTypes[type]; + if (entry) { + var handlers = this._handlers = this._handlers || {}; + handlers = handlers[type] = handlers[type] || []; + if (handlers.indexOf(func) == -1) { + handlers.push(func); + if (entry.install && handlers.length == 1) + entry.install.call(this, type); + } + } + }, + + detach: function(type, func) { + if (typeof type !== 'string') { + Base.each(type, function(value, key) { + this.detach(key, value); + }, this); + return; + } + var entry = this._eventTypes[type], + handlers = this._handlers && this._handlers[type], + index; + if (entry && handlers) { + if (!func || (index = handlers.indexOf(func)) != -1 + && handlers.length == 1) { + if (entry.uninstall) + entry.uninstall.call(this, type); + delete this._handlers[type]; + } else if (index != -1) { + handlers.splice(index, 1); + } + } + }, + + once: function(type, func) { + this.attach(type, function() { + func.apply(this, arguments); + this.detach(type, func); + }); + }, + + fire: function(type, event) { + var handlers = this._handlers && this._handlers[type]; + if (!handlers) + return false; + var args = [].slice.call(arguments, 1); + Base.each(handlers, function(func) { + if (func.apply(this, args) === false && event && event.stop) + event.stop(); + }, this); + return true; + }, + + responds: function(type) { + return !!(this._handlers && this._handlers[type]); + }, + + on: '#attach', + off: '#detach', + trigger: '#fire', + + statics: { + inject: function inject() { + for (var i = 0, l = arguments.length; i < l; i++) { + var src = arguments[i], + events = src._events; + if (events) { + var types = {}; + Base.each(events, function(entry, key) { + var isString = typeof entry === 'string', + name = isString ? entry : key, + part = Base.capitalize(name), + type = name.substring(2).toLowerCase(); + types[type] = isString ? {} : entry; + name = '_' + name; + src['get' + part] = function() { + return this[name]; + }; + src['set' + part] = function(func) { + if (func) { + this.attach(type, func); + } else if (this[name]) { + this.detach(type, this[name]); + } + this[name] = func; + }; + }); + src._eventTypes = types; + } + inject.base.call(this, src); + } + return this; + } + } +}; + +var PaperScope = Base.extend({ + _class: 'PaperScope', + + initialize: function PaperScope(script) { + paper = this; + this.project = null; + this.projects = []; + this.tools = []; + this.palettes = []; + this._id = script && (script.getAttribute('id') || script.src) + || ('paperscope-' + (PaperScope._id++)); + if (script) + script.setAttribute('id', this._id); + PaperScope._scopes[this._id] = this; + if (!this.support) { + var ctx = CanvasProvider.getContext(1, 1); + PaperScope.prototype.support = { + nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx, + nativeBlendModes: BlendMode.nativeModes + }; + CanvasProvider.release(ctx); + } + }, + + version: '0.9.5', + + getView: function() { + return this.project && this.project.view; + }, + + getTool: function() { + if (!this._tool) + this._tool = new Tool(); + return this._tool; + }, + + evaluate: function(code) { + var res = paper.PaperScript.evaluate(code, this); + View.updateFocus(); + return res; + }, + + install: function(scope) { + var that = this; + Base.each(['project', 'view', 'tool'], function(key) { + Base.define(scope, key, { + configurable: true, + get: function() { + return that[key]; + } + }); + }); + for (var key in this) { + if (!/^(version|_id)/.test(key) && !(key in scope)) + scope[key] = this[key]; + } + }, + + setup: function(canvas) { + paper = this; + this.project = new Project(canvas); + return this; + }, + + clear: function() { + for (var i = this.projects.length - 1; i >= 0; i--) + this.projects[i].remove(); + for (var i = this.tools.length - 1; i >= 0; i--) + this.tools[i].remove(); + for (var i = this.palettes.length - 1; i >= 0; i--) + this.palettes[i].remove(); + }, + + remove: function() { + this.clear(); + delete PaperScope._scopes[this._id]; + }, + + statics: new function() { + function handleAttribute(name) { + name += 'Attribute'; + return function(el, attr) { + return el[name](attr) || el[name]('data-paper-' + attr); + }; + } + + return { + _scopes: {}, + _id: 0, + + get: function(id) { + if (typeof id === 'object') + id = id.getAttribute('id'); + return this._scopes[id] || null; + }, + + getAttribute: handleAttribute('get'), + hasAttribute: handleAttribute('has') + }; + } +}); + +var PaperScopeItem = Base.extend(Callback, { + + initialize: function(activate) { + this._scope = paper; + this._index = this._scope[this._list].push(this) - 1; + if (activate || !this._scope[this._reference]) + this.activate(); + }, + + activate: function() { + if (!this._scope) + return false; + var prev = this._scope[this._reference]; + if (prev && prev != this) + prev.fire('deactivate'); + this._scope[this._reference] = this; + this.fire('activate', prev); + return true; + }, + + isActive: function() { + return this._scope[this._reference] === this; + }, + + remove: function() { + if (this._index == null) + return false; + Base.splice(this._scope[this._list], null, this._index, 1); + if (this._scope[this._reference] == this) + this._scope[this._reference] = null; + this._scope = null; + return true; + } +}); + +var Formatter = Base.extend({ + initialize: function(precision) { + this.precision = precision || 5; + this.multiplier = Math.pow(10, this.precision); + }, + + number: function(val) { + return Math.round(val * this.multiplier) / this.multiplier; + }, + + point: function(val, separator) { + return this.number(val.x) + (separator || ',') + this.number(val.y); + }, + + size: function(val, separator) { + return this.number(val.width) + (separator || ',') + + this.number(val.height); + }, + + rectangle: function(val, separator) { + return this.point(val, separator) + (separator || ',') + + this.size(val, separator); + } +}); + +Formatter.instance = new Formatter(5); + +var Numerical = new function() { + + var abscissas = [ + [ 0.5773502691896257645091488], + [0,0.7745966692414833770358531], + [ 0.3399810435848562648026658,0.8611363115940525752239465], + [0,0.5384693101056830910363144,0.9061798459386639927976269], + [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016], + [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897], + [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609], + [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762], + [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640], + [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380], + [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491], + [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294], + [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973], + [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657], + [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542] + ]; + + var weights = [ + [1], + [0.8888888888888888888888889,0.5555555555555555555555556], + [0.6521451548625461426269361,0.3478548451374538573730639], + [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640], + [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961], + [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114], + [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314], + [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922], + [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688], + [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537], + [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160], + [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216], + [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329], + [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284], + [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806] + ]; + + var abs = Math.abs, + sqrt = Math.sqrt, + pow = Math.pow, + cos = Math.cos, + PI = Math.PI; + + return { + TOLERANCE: 10e-6, + EPSILON: 10e-12, + KAPPA: 4 * (sqrt(2) - 1) / 3, + + isZero: function(val) { + return abs(val) <= this.EPSILON; + }, + + integrate: function(f, a, b, n) { + var x = abscissas[n - 2], + w = weights[n - 2], + A = 0.5 * (b - a), + B = A + a, + i = 0, + m = (n + 1) >> 1, + sum = n & 1 ? w[i++] * f(B) : 0; + while (i < m) { + var Ax = A * x[i]; + sum += w[i++] * (f(B + Ax) + f(B - Ax)); + } + return A * sum; + }, + + findRoot: function(f, df, x, a, b, n, tolerance) { + for (var i = 0; i < n; i++) { + var fx = f(x), + dx = fx / df(x); + if (abs(dx) < tolerance) + return x; + var nx = x - dx; + if (fx > 0) { + b = x; + x = nx <= a ? 0.5 * (a + b) : nx; + } else { + a = x; + x = nx >= b ? 0.5 * (a + b) : nx; + } + } + }, + + solveQuadratic: function(a, b, c, roots) { + var epsilon = this.EPSILON; + if (abs(a) < epsilon) { + if (abs(b) >= epsilon) { + roots[0] = -c / b; + return 1; + } + return abs(c) < epsilon ? -1 : 0; + } + var q = b * b - 4 * a * c; + if (q < 0) + return 0; + q = sqrt(q); + a *= 2; + var n = 0; + roots[n++] = (-b - q) / a; + if (q > 0) + roots[n++] = (-b + q) / a; + return n; + }, + + solveCubic: function(a, b, c, d, roots) { + var epsilon = this.EPSILON; + if (abs(a) < epsilon) + return Numerical.solveQuadratic(b, c, d, roots); + b /= a; + c /= a; + d /= a; + var bb = b * b, + p = (bb - 3 * c) / 9, + q = (2 * bb * b - 9 * b * c + 27 * d) / 54, + ppp = p * p * p, + D = q * q - ppp; + b /= 3; + if (abs(D) < epsilon) { + if (abs(q) < epsilon) { + roots[0] = - b; + return 1; + } + var sqp = sqrt(p), + snq = q > 0 ? 1 : -1; + roots[0] = -snq * 2 * sqp - b; + roots[1] = snq * sqp - b; + return 2; + } + if (D < 0) { + var sqp = sqrt(p), + phi = Math.acos(q / (sqp * sqp * sqp)) / 3, + t = -2 * sqp, + o = 2 * PI / 3; + roots[0] = t * cos(phi) - b; + roots[1] = t * cos(phi + o) - b; + roots[2] = t * cos(phi - o) - b; + return 3; + } + var A = (q > 0 ? -1 : 1) * pow(abs(q) + sqrt(D), 1 / 3); + roots[0] = A + p / A - b; + return 1; + } + }; +}; + +var Point = Base.extend({ + _class: 'Point', + _readIndex: true, + + initialize: function Point(arg0, arg1) { + var type = typeof arg0; + if (type === 'number') { + var hasY = typeof arg1 === 'number'; + this.x = arg0; + this.y = hasY ? arg1 : arg0; + if (this._read) + this._read = hasY ? 2 : 1; + } else if (type === 'undefined' || arg0 === null) { + this.x = this.y = 0; + if (this._read) + this._read = arg0 === null ? 1 : 0; + } else { + if (Array.isArray(arg0)) { + this.x = arg0[0]; + this.y = arg0.length > 1 ? arg0[1] : arg0[0]; + } else if (arg0.x != null) { + this.x = arg0.x; + this.y = arg0.y; + } else if (arg0.width != null) { + this.x = arg0.width; + this.y = arg0.height; + } else if (arg0.angle != null) { + this.x = arg0.length; + this.y = 0; + this.setAngle(arg0.angle); + } else { + this.x = this.y = 0; + if (this._read) + this._read = 0; + } + if (this._read) + this._read = 1; + } + }, + + set: function(x, y) { + this.x = x; + this.y = y; + return this; + }, + + equals: function(point) { + return point === this || point && (this.x === point.x + && this.y === point.y + || Array.isArray(point) && this.x === point[0] + && this.y === point[1]) || false; + }, + + clone: function() { + return new Point(this.x, this.y); + }, + + toString: function() { + var f = Formatter.instance; + return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }'; + }, + + _serialize: function(options) { + var f = options.formatter; + return [f.number(this.x), + f.number(this.y)]; + }, + + add: function(point) { + point = Point.read(arguments); + return new Point(this.x + point.x, this.y + point.y); + }, + + subtract: function(point) { + point = Point.read(arguments); + return new Point(this.x - point.x, this.y - point.y); + }, + + multiply: function(point) { + point = Point.read(arguments); + return new Point(this.x * point.x, this.y * point.y); + }, + + divide: function(point) { + point = Point.read(arguments); + return new Point(this.x / point.x, this.y / point.y); + }, + + modulo: function(point) { + point = Point.read(arguments); + return new Point(this.x % point.x, this.y % point.y); + }, + + negate: function() { + return new Point(-this.x, -this.y); + }, + + transform: function(matrix) { + return matrix ? matrix._transformPoint(this) : this; + }, + + getDistance: function(point, squared) { + point = Point.read(arguments); + var x = point.x - this.x, + y = point.y - this.y, + d = x * x + y * y; + return squared ? d : Math.sqrt(d); + }, + + getLength: function() { + var length = this.x * this.x + this.y * this.y; + return arguments.length && arguments[0] ? length : Math.sqrt(length); + }, + + setLength: function(length) { + if (this.isZero()) { + var angle = this._angle || 0; + this.set( + Math.cos(angle) * length, + Math.sin(angle) * length + ); + } else { + var scale = length / this.getLength(); + if (Numerical.isZero(scale)) + this.getAngle(); + this.set( + this.x * scale, + this.y * scale + ); + } + return this; + }, + + normalize: function(length) { + if (length === undefined) + length = 1; + var current = this.getLength(), + scale = current !== 0 ? length / current : 0, + point = new Point(this.x * scale, this.y * scale); + point._angle = this._angle; + return point; + }, + + getAngle: function() { + return this.getAngleInRadians(arguments[0]) * 180 / Math.PI; + }, + + setAngle: function(angle) { + angle = this._angle = angle * Math.PI / 180; + if (!this.isZero()) { + var length = this.getLength(); + this.set( + Math.cos(angle) * length, + Math.sin(angle) * length + ); + } + return this; + }, + + getAngleInRadians: function() { + if (arguments[0] === undefined) { + if (this._angle == null) + this._angle = Math.atan2(this.y, this.x); + return this._angle; + } else { + var point = Point.read(arguments), + div = this.getLength() * point.getLength(); + if (Numerical.isZero(div)) { + return NaN; + } else { + return Math.acos(this.dot(point) / div); + } + } + }, + + getAngleInDegrees: function() { + return this.getAngle(arguments[0]); + }, + + getQuadrant: function() { + return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3; + }, + + getDirectedAngle: function(point) { + point = Point.read(arguments); + return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI; + }, + + rotate: function(angle, center) { + if (angle === 0) + return this.clone(); + angle = angle * Math.PI / 180; + var point = center ? this.subtract(center) : this, + s = Math.sin(angle), + c = Math.cos(angle); + point = new Point( + point.x * c - point.y * s, + point.y * c + point.x * s + ); + return center ? point.add(center) : point; + }, + + isInside: function(rect) { + return rect.contains(this); + }, + + isClose: function(point, tolerance) { + return this.getDistance(point) < tolerance; + }, + + isColinear: function(point) { + return this.cross(point) < 0.00001; + }, + + isOrthogonal: function(point) { + return this.dot(point) < 0.00001; + }, + + isZero: function() { + return Numerical.isZero(this.x) && Numerical.isZero(this.y); + }, + + isNaN: function() { + return isNaN(this.x) || isNaN(this.y); + }, + + dot: function(point) { + point = Point.read(arguments); + return this.x * point.x + this.y * point.y; + }, + + cross: function(point) { + point = Point.read(arguments); + return this.x * point.y - this.y * point.x; + }, + + project: function(point) { + point = Point.read(arguments); + if (point.isZero()) { + return new Point(0, 0); + } else { + var scale = this.dot(point) / point.dot(point); + return new Point( + point.x * scale, + point.y * scale + ); + } + }, + + statics: { + min: function() { + var point1 = Point.read(arguments); + point2 = Point.read(arguments); + return new Point( + Math.min(point1.x, point2.x), + Math.min(point1.y, point2.y) + ); + }, + + max: function() { + var point1 = Point.read(arguments); + point2 = Point.read(arguments); + return new Point( + Math.max(point1.x, point2.x), + Math.max(point1.y, point2.y) + ); + }, + + random: function() { + return new Point(Math.random(), Math.random()); + } + } +}, new function() { + + return Base.each(['round', 'ceil', 'floor', 'abs'], function(name) { + var op = Math[name]; + this[name] = function() { + return new Point(op(this.x), op(this.y)); + }; + }, {}); +}); + +var LinkedPoint = Point.extend({ + initialize: function Point(x, y, owner, setter) { + this._x = x; + this._y = y; + this._owner = owner; + this._setter = setter; + }, + + set: function(x, y, dontNotify) { + this._x = x; + this._y = y; + if (!dontNotify) + this._owner[this._setter](this); + return this; + }, + + getX: function() { + return this._x; + }, + + setX: function(x) { + this._x = x; + this._owner[this._setter](this); + }, + + getY: function() { + return this._y; + }, + + setY: function(y) { + this._y = y; + this._owner[this._setter](this); + } +}); + +var Size = Base.extend({ + _class: 'Size', + _readIndex: true, + + initialize: function Size(arg0, arg1) { + var type = typeof arg0; + if (type === 'number') { + var hasHeight = typeof arg1 === 'number'; + this.width = arg0; + this.height = hasHeight ? arg1 : arg0; + if (this._read) + this._read = hasHeight ? 2 : 1; + } else if (type === 'undefined' || arg0 === null) { + this.width = this.height = 0; + if (this._read) + this._read = arg0 === null ? 1 : 0; + } else { + if (Array.isArray(arg0)) { + this.width = arg0[0]; + this.height = arg0.length > 1 ? arg0[1] : arg0[0]; + } else if (arg0.width != null) { + this.width = arg0.width; + this.height = arg0.height; + } else if (arg0.x != null) { + this.width = arg0.x; + this.height = arg0.y; + } else { + this.width = this.height = 0; + if (this._read) + this._read = 0; + } + if (this._read) + this._read = 1; + } + }, + + set: function(width, height) { + this.width = width; + this.height = height; + return this; + }, + + equals: function(size) { + return size === this || size && (this.width === size.width + && this.height === size.height + || Array.isArray(size) && this.width === size[0] + && this.height === size[1]) || false; + }, + + clone: function() { + return new Size(this.width, this.height); + }, + + toString: function() { + var f = Formatter.instance; + return '{ width: ' + f.number(this.width) + + ', height: ' + f.number(this.height) + ' }'; + }, + + _serialize: function(options) { + var f = options.formatter; + return [f.number(this.width), + f.number(this.height)]; + }, + + add: function(size) { + size = Size.read(arguments); + return new Size(this.width + size.width, this.height + size.height); + }, + + subtract: function(size) { + size = Size.read(arguments); + return new Size(this.width - size.width, this.height - size.height); + }, + + multiply: function(size) { + size = Size.read(arguments); + return new Size(this.width * size.width, this.height * size.height); + }, + + divide: function(size) { + size = Size.read(arguments); + return new Size(this.width / size.width, this.height / size.height); + }, + + modulo: function(size) { + size = Size.read(arguments); + return new Size(this.width % size.width, this.height % size.height); + }, + + negate: function() { + return new Size(-this.width, -this.height); + }, + + isZero: function() { + return Numerical.isZero(this.width) && Numerical.isZero(this.height); + }, + + isNaN: function() { + return isNaN(this.width) || isNaN(this.height); + }, + + statics: { + min: function(size1, size2) { + return new Size( + Math.min(size1.width, size2.width), + Math.min(size1.height, size2.height)); + }, + + max: function(size1, size2) { + return new Size( + Math.max(size1.width, size2.width), + Math.max(size1.height, size2.height)); + }, + + random: function() { + return new Size(Math.random(), Math.random()); + } + } +}, new function() { + + return Base.each(['round', 'ceil', 'floor', 'abs'], function(name) { + var op = Math[name]; + this[name] = function() { + return new Size(op(this.width), op(this.height)); + }; + }, {}); +}); + +var LinkedSize = Size.extend({ + initialize: function Size(width, height, owner, setter) { + this._width = width; + this._height = height; + this._owner = owner; + this._setter = setter; + }, + + set: function(width, height, dontNotify) { + this._width = width; + this._height = height; + if (!dontNotify) + this._owner[this._setter](this); + return this; + }, + + getWidth: function() { + return this._width; + }, + + setWidth: function(width) { + this._width = width; + this._owner[this._setter](this); + }, + + getHeight: function() { + return this._height; + }, + + setHeight: function(height) { + this._height = height; + this._owner[this._setter](this); + } +}); + +var Rectangle = Base.extend({ + _class: 'Rectangle', + _readIndex: true, + + initialize: function Rectangle(arg0, arg1, arg2, arg3) { + var type = typeof arg0, + read = 0; + if (type === 'number') { + this.x = arg0; + this.y = arg1; + this.width = arg2; + this.height = arg3; + read = 4; + } else if (type === 'undefined' || arg0 === null) { + this.x = this.y = this.width = this.height = 0; + read = arg0 === null ? 1 : 0; + } else if (arguments.length === 1) { + if (Array.isArray(arg0)) { + this.x = arg0[0]; + this.y = arg0[1]; + this.width = arg0[2]; + this.height = arg0[3]; + read = 1; + } else if (arg0.x !== undefined || arg0.width !== undefined) { + this.x = arg0.x || 0; + this.y = arg0.y || 0; + this.width = arg0.width || 0; + this.height = arg0.height || 0; + read = 1; + } else if (arg0.from === undefined && arg0.to === undefined) { + this.x = this.y = this.width = this.height = 0; + this._set(arg0); + read = 1; + } + } + if (!read) { + var point = Point.readNamed(arguments, 'from'), + next = Base.peek(arguments); + this.x = point.x; + this.y = point.y; + if (next && next.x !== undefined || Base.hasNamed(arguments, 'to')) { + var to = Point.readNamed(arguments, 'to'); + this.width = to.x - point.x; + this.height = to.y - point.y; + if (this.width < 0) { + this.x = to.x; + this.width = -this.width; + } + if (this.height < 0) { + this.y = to.y; + this.height = -this.height; + } + } else { + var size = Size.read(arguments); + this.width = size.width; + this.height = size.height; + } + read = arguments._index; + } + if (this._read) + this._read = read; + }, + + set: function(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + return this; + }, + + clone: function() { + return new Rectangle(this.x, this.y, this.width, this.height); + }, + + equals: function(rect) { + if (Base.isPlainValue(rect)) + rect = Rectangle.read(arguments); + return rect === this + || rect && this.x === rect.x && this.y === rect.y + && this.width === rect.width && this.height=== rect.height + || false; + }, + + toString: function() { + var f = Formatter.instance; + return '{ x: ' + f.number(this.x) + + ', y: ' + f.number(this.y) + + ', width: ' + f.number(this.width) + + ', height: ' + f.number(this.height) + + ' }'; + }, + + _serialize: function(options) { + var f = options.formatter; + return [f.number(this.x), + f.number(this.y), + f.number(this.width), + f.number(this.height)]; + }, + + getPoint: function() { + return new (arguments[0] ? Point : LinkedPoint) + (this.x, this.y, this, 'setPoint'); + }, + + setPoint: function(point) { + point = Point.read(arguments); + this.x = point.x; + this.y = point.y; + }, + + getSize: function() { + return new (arguments[0] ? Size : LinkedSize) + (this.width, this.height, this, 'setSize'); + }, + + setSize: function(size) { + size = Size.read(arguments); + if (this._fixX) + this.x += (this.width - size.width) * this._fixX; + if (this._fixY) + this.y += (this.height - size.height) * this._fixY; + this.width = size.width; + this.height = size.height; + this._fixW = 1; + this._fixH = 1; + }, + + getLeft: function() { + return this.x; + }, + + setLeft: function(left) { + if (!this._fixW) + this.width -= left - this.x; + this.x = left; + this._fixX = 0; + }, + + getTop: function() { + return this.y; + }, + + setTop: function(top) { + if (!this._fixH) + this.height -= top - this.y; + this.y = top; + this._fixY = 0; + }, + + getRight: function() { + return this.x + this.width; + }, + + setRight: function(right) { + if (this._fixX !== undefined && this._fixX !== 1) + this._fixW = 0; + if (this._fixW) + this.x = right - this.width; + else + this.width = right - this.x; + this._fixX = 1; + }, + + getBottom: function() { + return this.y + this.height; + }, + + setBottom: function(bottom) { + if (this._fixY !== undefined && this._fixY !== 1) + this._fixH = 0; + if (this._fixH) + this.y = bottom - this.height; + else + this.height = bottom - this.y; + this._fixY = 1; + }, + + getCenterX: function() { + return this.x + this.width * 0.5; + }, + + setCenterX: function(x) { + this.x = x - this.width * 0.5; + this._fixX = 0.5; + }, + + getCenterY: function() { + return this.y + this.height * 0.5; + }, + + setCenterY: function(y) { + this.y = y - this.height * 0.5; + this._fixY = 0.5; + }, + + getCenter: function() { + return new (arguments[0] ? Point : LinkedPoint) + (this.getCenterX(), this.getCenterY(), this, 'setCenter'); + }, + + setCenter: function(point) { + point = Point.read(arguments); + this.setCenterX(point.x); + this.setCenterY(point.y); + return this; + }, + + isEmpty: function() { + return this.width == 0 || this.height == 0; + }, + + contains: function(arg) { + return arg && arg.width !== undefined + || (Array.isArray(arg) ? arg : arguments).length == 4 + ? this._containsRectangle(Rectangle.read(arguments)) + : this._containsPoint(Point.read(arguments)); + }, + + _containsPoint: function(point) { + var x = point.x, + y = point.y; + return x >= this.x && y >= this.y + && x <= this.x + this.width + && y <= this.y + this.height; + }, + + _containsRectangle: function(rect) { + var x = rect.x, + y = rect.y; + return x >= this.x && y >= this.y + && x + rect.width <= this.x + this.width + && y + rect.height <= this.y + this.height; + }, + + intersects: function(rect) { + rect = Rectangle.read(arguments); + return rect.x + rect.width > this.x + && rect.y + rect.height > this.y + && rect.x < this.x + this.width + && rect.y < this.y + this.height; + }, + + touches: function(rect) { + rect = Rectangle.read(arguments); + return rect.x + rect.width >= this.x + && rect.y + rect.height >= this.y + && rect.x <= this.x + this.width + && rect.y <= this.y + this.height; + }, + + intersect: function(rect) { + rect = Rectangle.read(arguments); + var x1 = Math.max(this.x, rect.x), + y1 = Math.max(this.y, rect.y), + x2 = Math.min(this.x + this.width, rect.x + rect.width), + y2 = Math.min(this.y + this.height, rect.y + rect.height); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + unite: function(rect) { + rect = Rectangle.read(arguments); + var x1 = Math.min(this.x, rect.x), + y1 = Math.min(this.y, rect.y), + x2 = Math.max(this.x + this.width, rect.x + rect.width), + y2 = Math.max(this.y + this.height, rect.y + rect.height); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + include: function(point) { + point = Point.read(arguments); + var x1 = Math.min(this.x, point.x), + y1 = Math.min(this.y, point.y), + x2 = Math.max(this.x + this.width, point.x), + y2 = Math.max(this.y + this.height, point.y); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + expand: function(hor, ver) { + if (ver === undefined) + ver = hor; + return new Rectangle(this.x - hor / 2, this.y - ver / 2, + this.width + hor, this.height + ver); + }, + + scale: function(hor, ver) { + return this.expand(this.width * hor - this.width, + this.height * (ver === undefined ? hor : ver) - this.height); + } +}, new function() { + return Base.each([ + ['Top', 'Left'], ['Top', 'Right'], + ['Bottom', 'Left'], ['Bottom', 'Right'], + ['Left', 'Center'], ['Top', 'Center'], + ['Right', 'Center'], ['Bottom', 'Center'] + ], + function(parts, index) { + var part = parts.join(''); + var xFirst = /^[RL]/.test(part); + if (index >= 4) + parts[1] += xFirst ? 'Y' : 'X'; + var x = parts[xFirst ? 0 : 1], + y = parts[xFirst ? 1 : 0], + getX = 'get' + x, + getY = 'get' + y, + setX = 'set' + x, + setY = 'set' + y, + get = 'get' + part, + set = 'set' + part; + this[get] = function() { + return new (arguments[0] ? Point : LinkedPoint) + (this[getX](), this[getY](), this, set); + }; + this[set] = function(point) { + point = Point.read(arguments); + this[setX](point.x); + this[setY](point.y); + }; + }, {}); +}); + +var LinkedRectangle = Rectangle.extend({ + initialize: function Rectangle(x, y, width, height, owner, setter) { + this.set(x, y, width, height, true); + this._owner = owner; + this._setter = setter; + }, + + set: function(x, y, width, height, dontNotify) { + this._x = x; + this._y = y; + this._width = width; + this._height = height; + if (!dontNotify) + this._owner[this._setter](this); + return this; + } +}, new function() { + var proto = Rectangle.prototype; + + return Base.each(['x', 'y', 'width', 'height'], function(key) { + var part = Base.capitalize(key); + var internal = '_' + key; + this['get' + part] = function() { + return this[internal]; + }; + + this['set' + part] = function(value) { + this[internal] = value; + if (!this._dontNotify) + this._owner[this._setter](this); + }; + }, Base.each(['Point', 'Size', 'Center', + 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY', + 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight', + 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'], + function(key) { + var name = 'set' + key; + this[name] = function() { + this._dontNotify = true; + proto[name].apply(this, arguments); + delete this._dontNotify; + this._owner[this._setter](this); + }; + }, { + isSelected: function() { + return this._owner._boundsSelected; + }, + + setSelected: function(selected) { + var owner = this._owner; + if (owner.setSelected) { + owner._boundsSelected = selected; + owner.setSelected(selected || owner._selectedSegmentState > 0); + } + } + }) + ); +}); + +var Matrix = Base.extend({ + _class: 'Matrix', + + initialize: function Matrix(arg) { + var count = arguments.length, + ok = true; + if (count == 6) { + this.set.apply(this, arguments); + } else if (count == 1) { + if (arg instanceof Matrix) { + this.set(arg._a, arg._c, arg._b, arg._d, arg._tx, arg._ty); + } else if (Array.isArray(arg)) { + this.set.apply(this, arg); + } else { + ok = false; + } + } else if (count == 0) { + this.reset(); + } else { + ok = false; + } + if (!ok) + throw new Error('Unsupported matrix parameters'); + }, + + set: function(a, c, b, d, tx, ty) { + this._a = a; + this._c = c; + this._b = b; + this._d = d; + this._tx = tx; + this._ty = ty; + return this; + }, + + _serialize: function(options) { + return Base.serialize(this.getValues(), options); + }, + + clone: function() { + return new Matrix(this._a, this._c, this._b, this._d, + this._tx, this._ty); + }, + + equals: function(mx) { + return mx === this || mx && this._a == mx._a && this._b == mx._b + && this._c == mx._c && this._d == mx._d && this._tx == mx._tx + && this._ty == mx._ty + || false; + }, + + toString: function() { + var f = Formatter.instance; + return '[[' + [f.number(this._a), f.number(this._b), + f.number(this._tx)].join(', ') + '], [' + + [f.number(this._c), f.number(this._d), + f.number(this._ty)].join(', ') + ']]'; + }, + + reset: function() { + this._a = this._d = 1; + this._c = this._b = this._tx = this._ty = 0; + return this; + }, + + scale: function() { + var scale = Point.read(arguments), + center = Point.read(arguments, 0, 0, true); + if (center) + this.translate(center); + this._a *= scale.x; + this._c *= scale.x; + this._b *= scale.y; + this._d *= scale.y; + if (center) + this.translate(center.negate()); + return this; + }, + + translate: function(point) { + point = Point.read(arguments); + var x = point.x, + y = point.y; + this._tx += x * this._a + y * this._b; + this._ty += x * this._c + y * this._d; + return this; + }, + + rotate: function(angle, center) { + center = Point.read(arguments, 1); + angle = angle * Math.PI / 180; + var x = center.x, + y = center.y, + cos = Math.cos(angle), + sin = Math.sin(angle), + tx = x - x * cos + y * sin, + ty = y - x * sin - y * cos, + a = this._a, + b = this._b, + c = this._c, + d = this._d; + this._a = cos * a + sin * b; + this._b = -sin * a + cos * b; + this._c = cos * c + sin * d; + this._d = -sin * c + cos * d; + this._tx += tx * a + ty * b; + this._ty += tx * c + ty * d; + return this; + }, + + shear: function() { + var point = Point.read(arguments), + center = Point.read(arguments, 0, 0, true); + if (center) + this.translate(center); + var a = this._a, + c = this._c; + this._a += point.y * this._b; + this._c += point.y * this._d; + this._b += point.x * a; + this._d += point.x * c; + if (center) + this.translate(center.negate()); + return this; + }, + + isIdentity: function() { + return this._a == 1 && this._c == 0 && this._b == 0 && this._d == 1 + && this._tx == 0 && this._ty == 0; + }, + + isInvertible: function() { + return !!this._getDeterminant(); + }, + + isSingular: function() { + return !this._getDeterminant(); + }, + + concatenate: function(mx) { + var a = this._a, + b = this._b, + c = this._c, + d = this._d; + this._a = mx._a * a + mx._c * b; + this._b = mx._b * a + mx._d * b; + this._c = mx._a * c + mx._c * d; + this._d = mx._b * c + mx._d * d; + this._tx += mx._tx * a + mx._ty * b; + this._ty += mx._tx * c + mx._ty * d; + return this; + }, + + preConcatenate: function(mx) { + var a = this._a, + b = this._b, + c = this._c, + d = this._d, + tx = this._tx, + ty = this._ty; + this._a = mx._a * a + mx._b * c; + this._b = mx._a * b + mx._b * d; + this._c = mx._c * a + mx._d * c; + this._d = mx._c * b + mx._d * d; + this._tx = mx._a * tx + mx._b * ty + mx._tx; + this._ty = mx._c * tx + mx._d * ty + mx._ty; + return this; + }, + + transform: function( src, srcOff, dst, dstOff, numPts) { + return arguments.length < 5 + ? this._transformPoint(Point.read(arguments)) + : this._transformCoordinates(src, srcOff, dst, dstOff, numPts); + }, + + _transformPoint: function(point, dest, dontNotify) { + var x = point.x, + y = point.y; + if (!dest) + dest = new Point(); + return dest.set( + x * this._a + y * this._b + this._tx, + x * this._c + y * this._d + this._ty, + dontNotify + ); + }, + + _transformCoordinates: function(src, srcOff, dst, dstOff, numPts) { + var i = srcOff, j = dstOff, + srcEnd = srcOff + 2 * numPts; + while (i < srcEnd) { + var x = src[i++], + y = src[i++]; + dst[j++] = x * this._a + y * this._b + this._tx; + dst[j++] = x * this._c + y * this._d + this._ty; + } + return dst; + }, + + _transformCorners: function(rect) { + var x1 = rect.x, + y1 = rect.y, + x2 = x1 + rect.width, + y2 = y1 + rect.height, + coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ]; + return this._transformCoordinates(coords, 0, coords, 0, 4); + }, + + _transformBounds: function(bounds, dest, dontNotify) { + var coords = this._transformCorners(bounds), + min = coords.slice(0, 2), + max = coords.slice(); + for (var i = 2; i < 8; i++) { + var val = coords[i], + j = i & 1; + if (val < min[j]) + min[j] = val; + else if (val > max[j]) + max[j] = val; + } + if (!dest) + dest = new Rectangle(); + return dest.set(min[0], min[1], max[0] - min[0], max[1] - min[1], + dontNotify); + }, + + inverseTransform: function() { + return this._inverseTransform(Point.read(arguments)); + }, + + _getDeterminant: function() { + var det = this._a * this._d - this._b * this._c; + return isFinite(det) && !Numerical.isZero(det) + && isFinite(this._tx) && isFinite(this._ty) + ? det : null; + }, + + _inverseTransform: function(point, dest, dontNotify) { + var det = this._getDeterminant(); + if (!det) + return null; + var x = point.x - this._tx, + y = point.y - this._ty; + if (!dest) + dest = new Point(); + return dest.set( + (x * this._d - y * this._b) / det, + (y * this._a - x * this._c) / det, + dontNotify + ); + }, + + decompose: function() { + var a = this._a, b = this._b, c = this._c, d = this._d; + if (Numerical.isZero(a * d - b * c)) + return null; + + var scaleX = Math.sqrt(a * a + b * b); + a /= scaleX; + b /= scaleX; + + var shear = a * c + b * d; + c -= a * shear; + d -= b * shear; + + var scaleY = Math.sqrt(c * c + d * d); + c /= scaleY; + d /= scaleY; + shear /= scaleY; + + if (a * d < b * c) { + a = -a; + b = -b; + shear = -shear; + scaleX = -scaleX; + } + + return { + translation: this.getTranslation(), + scaling: new Point(scaleX, scaleY), + rotation: -Math.atan2(b, a) * 180 / Math.PI, + shearing: shear + }; + }, + + getValues: function() { + return [ this._a, this._c, this._b, this._d, this._tx, this._ty ]; + }, + + getTranslation: function() { + return new Point(this._tx, this._ty); + }, + + getScaling: function() { + return (this.decompose() || {}).scaling; + }, + + getRotation: function() { + return (this.decompose() || {}).rotation; + }, + + inverted: function() { + var det = this._getDeterminant(); + return det && new Matrix( + this._d / det, + -this._c / det, + -this._b / det, + this._a / det, + (this._b * this._ty - this._d * this._tx) / det, + (this._c * this._tx - this._a * this._ty) / det); + }, + + shiftless: function() { + return new Matrix(this._a, this._c, this._b, this._d, 0, 0); + }, + + applyToContext: function(ctx) { + ctx.transform(this._a, this._c, this._b, this._d, this._tx, this._ty); + } +}, new function() { + return Base.each({ + scaleX: '_a', + scaleY: '_d', + translateX: '_tx', + translateY: '_ty', + shearX: '_b', + shearY: '_c' + }, function(prop, name) { + name = Base.capitalize(name); + this['get' + name] = function() { + return this[prop]; + }; + this['set' + name] = function(value) { + this[prop] = value; + }; + }, {}); +}); + +var Line = Base.extend({ + _class: 'Line', + + initialize: function Line(arg0, arg1, arg2, arg3, arg4) { + var asVector = false; + if (arguments.length >= 4) { + this._px = arg0; + this._py = arg1; + this._vx = arg2; + this._vy = arg3; + asVector = arg4; + } else { + this._px = arg0.x; + this._py = arg0.y; + this._vx = arg1.x; + this._vy = arg1.y; + asVector = arg2; + } + if (!asVector) { + this._vx -= this._px; + this._vy -= this._py; + } + }, + + getPoint: function() { + return new Point(this._px, this._py); + }, + + getVector: function() { + return new Point(this._vx, this._vy); + }, + + getLength: function() { + return this.getVector().getLength(); + }, + + intersect: function(line, isInfinite) { + return Line.intersect( + this._px, this._py, this._vx, this._vy, + line._px, line._py, line._vx, line._vy, + true, isInfinite); + }, + + getSide: function(point) { + return Line.getSide( + this._px, this._py, this._vx, this._vy, + point.x, point.y, true); + }, + + getDistance: function(point) { + return Math.abs(Line.getSignedDistance( + this._px, this._py, this._vx, this._vy, + point.x, point.y, true)); + }, + + statics: { + intersect: function(apx, apy, avx, avy, bpx, bpy, bvx, bvy, asVector, + isInfinite) { + if (!asVector) { + avx -= apx; + avy -= apy; + bvx -= bpx; + bvy -= bpy; + } + var cross = bvy * avx - bvx * avy; + if (!Numerical.isZero(cross)) { + var dx = apx - bpx, + dy = apy - bpy, + ta = (bvx * dy - bvy * dx) / cross, + tb = (avx * dy - avy * dx) / cross; + if ((isInfinite || 0 <= ta && ta <= 1) + && (isInfinite || 0 <= tb && tb <= 1)) + return new Point( + apx + ta * avx, + apy + ta * avy); + } + }, + + getSide: function(px, py, vx, vy, x, y, asVector) { + if (!asVector) { + vx -= px; + vy -= py; + } + var v2x = x - px, + v2y = y - py, + ccw = v2x * vy - v2y * vx; + if (ccw === 0) { + ccw = v2x * vx + v2y * vy; + if (ccw > 0) { + v2x -= vx; + v2y -= vy; + ccw = v2x * vx + v2y * vy; + if (ccw < 0) + ccw = 0; + } + } + return ccw < 0 ? -1 : ccw > 0 ? 1 : 0; + }, + + getSignedDistance: function(px, py, vx, vy, x, y, asVector) { + if (!asVector) { + vx -= px; + vy -= py; + } + var m = vy / vx, + b = py - m * px; + return (y - (m * x) - b) / Math.sqrt(m * m + 1); + } + } +}); + +var Project = PaperScopeItem.extend({ + _class: 'Project', + _list: 'projects', + _reference: 'project', + + initialize: function Project(view) { + PaperScopeItem.call(this, true); + this.layers = []; + this.symbols = []; + this._currentStyle = new Style(); + this.activeLayer = new Layer(); + if (view) + this.view = view instanceof View ? view : View.create(view); + this._selectedItems = {}; + this._selectedItemCount = 0; + this._drawCount = 0; + this.options = {}; + }, + + _serialize: function(options, dictionary) { + return Base.serialize(this.layers, options, true, dictionary); + }, + + clear: function() { + for (var i = this.layers.length - 1; i >= 0; i--) + this.layers[i].remove(); + this.symbols = []; + }, + + remove: function remove() { + if (!remove.base.call(this)) + return false; + if (this.view) + this.view.remove(); + return true; + }, + + getCurrentStyle: function() { + return this._currentStyle; + }, + + setCurrentStyle: function(style) { + this._currentStyle.initialize(style); + }, + + getIndex: function() { + return this._index; + }, + + getSelectedItems: function() { + var items = []; + for (var id in this._selectedItems) { + var item = this._selectedItems[id]; + if (item._drawCount === this._drawCount) + items.push(item); + } + return items; + }, + + _updateSelection: function(item) { + if (item._selected) { + this._selectedItemCount++; + this._selectedItems[item._id] = item; + if (item.isInserted()) + item._drawCount = this._drawCount; + } else { + this._selectedItemCount--; + delete this._selectedItems[item._id]; + } + }, + + selectAll: function() { + for (var i = 0, l = this.layers.length; i < l; i++) + this.layers[i].setSelected(true); + }, + + deselectAll: function() { + for (var i in this._selectedItems) + this._selectedItems[i].setSelected(false); + }, + + hitTest: function(point, options) { + point = Point.read(arguments); + options = HitResult.getOptions(Base.read(arguments)); + for (var i = this.layers.length - 1; i >= 0; i--) { + var res = this.layers[i].hitTest(point, options); + if (res) return res; + } + return null; + }, + + importJSON: function(json) { + this.activate(); + return Base.importJSON(json); + }, + + draw: function(ctx, matrix) { + this._drawCount++; + ctx.save(); + matrix.applyToContext(ctx); + var param = Base.merge({ + offset: new Point(0, 0), + transforms: [matrix] + }); + for (var i = 0, l = this.layers.length; i < l; i++) + this.layers[i].draw(ctx, param); + ctx.restore(); + + if (this._selectedItemCount > 0) { + ctx.save(); + ctx.strokeWidth = 1; + for (var id in this._selectedItems) { + var item = this._selectedItems[id]; + if (item._drawCount === this._drawCount + && (item._drawSelected || item._boundsSelected)) { + var color = item.getSelectedColor() + || item.getLayer().getSelectedColor(); + ctx.strokeStyle = ctx.fillStyle = color + ? color.toCanvasStyle(ctx) : '#009dec'; + var mx = item._globalMatrix; + if (item._drawSelected) + item._drawSelected(ctx, mx); + if (item._boundsSelected) { + var coords = mx._transformCorners( + item._getBounds('getBounds')); + ctx.beginPath(); + for (var i = 0; i < 8; i++) + ctx[i === 0 ? 'moveTo' : 'lineTo']( + coords[i], coords[++i]); + ctx.closePath(); + ctx.stroke(); + for (var i = 0; i < 8; i++) { + ctx.beginPath(); + ctx.rect(coords[i] - 2, coords[++i] - 2, 4, 4); + ctx.fill(); + } + } + } + } + ctx.restore(); + } + } +}); + +var Symbol = Base.extend({ + _class: 'Symbol', + + initialize: function Symbol(item, dontCenter) { + this._id = Symbol._id = (Symbol._id || 0) + 1; + this.project = paper.project; + this.project.symbols.push(this); + if (item) + this.setDefinition(item, dontCenter); + this._instances = {}; + }, + + _serialize: function(options, dictionary) { + return dictionary.add(this, function() { + return Base.serialize([this._class, this._definition], + options, false, dictionary); + }); + }, + + _changed: function(flags) { + Base.each(this._instances, function(item) { + item._changed(flags); + }); + }, + + getDefinition: function() { + return this._definition; + }, + + setDefinition: function(item ) { + if (item._parentSymbol) + item = item.clone(); + if (this._definition) + delete this._definition._parentSymbol; + this._definition = item; + item.remove(); + item.setSelected(false); + if (!arguments[1]) + item.setPosition(new Point()); + item._parentSymbol = this; + this._changed(5); + }, + + place: function(position) { + return new PlacedSymbol(this, position); + }, + + clone: function() { + return new Symbol(this._definition.clone()); + } +}); + +var Item = Base.extend(Callback, { + statics: { + extend: function extend(src) { + if (src._serializeFields) + src._serializeFields = Base.merge( + this.prototype._serializeFields, src._serializeFields); + var res = extend.base.apply(this, arguments), + proto = res.prototype, + name = proto._class; + if (name) + proto._type = Base.hyphenate(name); + return res; + } + }, + + _class: 'Item', + _transformContent: true, + _boundsSelected: false, + _serializeFields: { + name: null, + matrix: new Matrix(), + locked: false, + visible: true, + blendMode: 'normal', + opacity: 1, + guide: false, + clipMask: false, + data: {} + }, + + initialize: function Item(point) { + this._id = Item._id = (Item._id || 0) + 1; + if (!this._project) { + var project = paper.project, + layer = project.activeLayer; + if (layer) + layer.addChild(this); + else + this._setProject(project); + } + this._style = new Style(this._project._currentStyle, this); + this._matrix = new Matrix(); + if (point) + this._matrix.translate(point); + }, + + _events: new function() { + + var mouseFlags = { + mousedown: { + mousedown: 1, + mousedrag: 1, + click: 1, + doubleclick: 1 + }, + mouseup: { + mouseup: 1, + mousedrag: 1, + click: 1, + doubleclick: 1 + }, + mousemove: { + mousedrag: 1, + mousemove: 1, + mouseenter: 1, + mouseleave: 1 + } + }; + + var mouseEvent = { + install: function(type) { + var counters = this._project.view._eventCounters; + if (counters) { + for (var key in mouseFlags) { + counters[key] = (counters[key] || 0) + + (mouseFlags[key][type] || 0); + } + } + }, + uninstall: function(type) { + var counters = this._project.view._eventCounters; + if (counters) { + for (var key in mouseFlags) + counters[key] -= mouseFlags[key][type] || 0; + } + } + }; + + return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick', + 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'], + function(name) { + this[name] = mouseEvent; + }, { + onFrame: { + install: function() { + this._project.view._animateItem(this, true); + }, + uninstall: function() { + this._project.view._animateItem(this, false); + } + }, + + onLoad: {} + } + ); + }, + + _serialize: function(options, dictionary) { + var props = {}, + that = this; + + function serialize(fields) { + for (var key in fields) { + var value = that[key]; + if (!Base.equals(value, fields[key])) + props[key] = Base.serialize(value, options, + key !== 'data', dictionary); + } + } + + serialize(this._serializeFields); + if (!(this instanceof Group)) + serialize(this._style._defaults); + return [ this._class, props ]; + }, + + _changed: function(flags) { + if (flags & 4) { + delete this._bounds; + delete this._position; + } + if (this._parent + && (flags & (4 | 8))) { + this._parent._clearBoundsCache(); + } + if (flags & 2) { + this._clearBoundsCache(); + } + if (flags & 1) { + this._project._needsRedraw = true; + } + if (this._parentSymbol) + this._parentSymbol._changed(flags); + if (this._project._changes) { + var entry = this._project._changesById[this._id]; + if (entry) { + entry.flags |= flags; + } else { + entry = { item: this, flags: flags }; + this._project._changesById[this._id] = entry; + this._project._changes.push(entry); + } + } + }, + + set: function(props) { + if (props) + this._set(props); + return this; + }, + + getId: function() { + return this._id; + }, + + getType: function() { + return this._type; + }, + + getName: function() { + return this._name; + }, + + setName: function(name, unique) { + + if (this._name) + this._removeFromNamed(); + if (name && this._parent) { + var children = this._parent._children, + namedChildren = this._parent._namedChildren, + orig = name, + i = 1; + while (unique && children[name]) + name = orig + ' ' + (i++); + (namedChildren[name] = namedChildren[name] || []).push(this); + children[name] = this; + } + this._name = name || undefined; + this._changed(32); + }, + + getStyle: function() { + return this._style; + }, + + setStyle: function(style) { + this.getStyle().set(style); + }, + + hasFill: function() { + return !!this.getStyle().getFillColor(); + }, + + hasStroke: function() { + var style = this.getStyle(); + return !!style.getStrokeColor() && style.getStrokeWidth() > 0; + } +}, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'], + function(name) { + var part = Base.capitalize(name), + name = '_' + name; + this['get' + part] = function() { + return this[name]; + }; + this['set' + part] = function(value) { + if (value != this[name]) { + this[name] = value; + this._changed(name === '_locked' + ? 32 : 33); + } + }; +}, {}), { + + _locked: false, + + _visible: true, + + _blendMode: 'normal', + + _opacity: 1, + + _guide: false, + + isSelected: function() { + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) + if (this._children[i].isSelected()) + return true; + } + return this._selected; + }, + + setSelected: function(selected ) { + if (this._children && !arguments[1]) { + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i].setSelected(selected); + } + if ((selected = !!selected) != this._selected) { + this._selected = selected; + this._project._updateSelection(this); + this._changed(33); + } + }, + + _selected: false, + + isFullySelected: function() { + if (this._children && this._selected) { + for (var i = 0, l = this._children.length; i < l; i++) + if (!this._children[i].isFullySelected()) + return false; + return true; + } + return this._selected; + }, + + setFullySelected: function(selected) { + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i].setFullySelected(selected); + } + this.setSelected(selected, true); + }, + + isClipMask: function() { + return this._clipMask; + }, + + setClipMask: function(clipMask) { + if (this._clipMask != (clipMask = !!clipMask)) { + this._clipMask = clipMask; + if (clipMask) { + this.setFillColor(null); + this.setStrokeColor(null); + } + this._changed(33); + if (this._parent) + this._parent._changed(256); + } + }, + + _clipMask: false, + + getData: function() { + if (!this._data) + this._data = {}; + return this._data; + }, + + setData: function(data) { + this._data = data; + }, + + getPosition: function() { + var pos = this._position + || (this._position = this.getBounds().getCenter(true)); + return new (arguments[0] ? Point : LinkedPoint) + (pos.x, pos.y, this, 'setPosition'); + }, + + setPosition: function() { + this.translate(Point.read(arguments).subtract(this.getPosition(true))); + }, + + getMatrix: function() { + return this._matrix; + }, + + setMatrix: function(matrix) { + this._matrix.initialize(matrix); + this._changed(5); + }, + + isEmpty: function() { + return this._children.length == 0; + } +}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'], + function(name) { + this[name] = function() { + var getter = this._boundsGetter, + bounds = this._getCachedBounds(typeof getter == 'string' + ? getter : getter && getter[name] || name, arguments[0]); + return name === 'getBounds' + ? new LinkedRectangle(bounds.x, bounds.y, bounds.width, + bounds.height, this, 'setBounds') + : bounds; + }; + }, +{ + _getCachedBounds: function(getter, matrix, cacheItem) { + var cache = (!matrix || matrix.equals(this._matrix)) && getter; + if (cacheItem && this._parent) { + var id = cacheItem._id, + ref = this._parent._boundsCache + = this._parent._boundsCache || { + ids: {}, + list: [] + }; + if (!ref.ids[id]) { + ref.list.push(cacheItem); + ref.ids[id] = cacheItem; + } + } + if (cache && this._bounds && this._bounds[cache]) + return this._bounds[cache].clone(); + var identity = this._matrix.isIdentity(); + matrix = !matrix || matrix.isIdentity() + ? identity ? null : this._matrix + : identity ? matrix : matrix.clone().concatenate(this._matrix); + var bounds = this._getBounds(getter, matrix, cache ? this : cacheItem); + if (cache) { + if (!this._bounds) + this._bounds = {}; + this._bounds[cache] = bounds.clone(); + } + return bounds; + }, + + _clearBoundsCache: function() { + if (this._boundsCache) { + for (var i = 0, list = this._boundsCache.list, l = list.length; + i < l; i++) { + var item = list[i]; + delete item._bounds; + if (item != this && item._boundsCache) + item._clearBoundsCache(); + } + delete this._boundsCache; + } + }, + + _getBounds: function(getter, matrix, cacheItem) { + var children = this._children; + if (!children || children.length == 0) + return new Rectangle(); + var x1 = Infinity, + x2 = -x1, + y1 = x1, + y2 = x2; + for (var i = 0, l = children.length; i < l; i++) { + var child = children[i]; + if (child._visible && !child.isEmpty()) { + var rect = child._getCachedBounds(getter, matrix, cacheItem); + x1 = Math.min(rect.x, x1); + y1 = Math.min(rect.y, y1); + x2 = Math.max(rect.x + rect.width, x2); + y2 = Math.max(rect.y + rect.height, y2); + } + } + return isFinite(x1) + ? new Rectangle(x1, y1, x2 - x1, y2 - y1) + : new Rectangle(); + }, + + setBounds: function(rect) { + rect = Rectangle.read(arguments); + var bounds = this.getBounds(), + matrix = new Matrix(), + center = rect.getCenter(); + matrix.translate(center); + if (rect.width != bounds.width || rect.height != bounds.height) { + matrix.scale( + bounds.width != 0 ? rect.width / bounds.width : 1, + bounds.height != 0 ? rect.height / bounds.height : 1); + } + center = bounds.getCenter(); + matrix.translate(-center.x, -center.y); + this.transform(matrix); + } + +}), { + getProject: function() { + return this._project; + }, + + _setProject: function(project) { + if (this._project != project) { + this._project = project; + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) { + this._children[i]._setProject(project); + } + } + } + }, + + getLayer: function() { + var parent = this; + while (parent = parent._parent) { + if (parent instanceof Layer) + return parent; + } + return null; + }, + + getParent: function() { + return this._parent; + }, + + setParent: function(item) { + return item.addChild(this); + }, + + getChildren: function() { + return this._children; + }, + + setChildren: function(items) { + this.removeChildren(); + this.addChildren(items); + }, + + getFirstChild: function() { + return this._children && this._children[0] || null; + }, + + getLastChild: function() { + return this._children && this._children[this._children.length - 1] + || null; + }, + + getNextSibling: function() { + return this._parent && this._parent._children[this._index + 1] || null; + }, + + getPreviousSibling: function() { + return this._parent && this._parent._children[this._index - 1] || null; + }, + + getIndex: function() { + return this._index; + }, + + isInserted: function() { + return this._parent ? this._parent.isInserted() : false; + }, + + clone: function() { + return this._clone(new this.constructor()); + }, + + _clone: function(copy) { + copy.setStyle(this._style); + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) + copy.addChild(this._children[i].clone(), true); + } + var keys = ['_locked', '_visible', '_blendMode', '_opacity', + '_clipMask', '_guide']; + for (var i = 0, l = keys.length; i < l; i++) { + var key = keys[i]; + if (this.hasOwnProperty(key)) + copy[key] = this[key]; + } + copy._matrix.initialize(this._matrix); + copy.setSelected(this._selected); + if (this._name) + copy.setName(this._name, true); + return copy; + }, + + copyTo: function(itemOrProject) { + var copy = this.clone(); + if (itemOrProject.layers) { + itemOrProject.activeLayer.addChild(copy); + } else { + itemOrProject.addChild(copy); + } + return copy; + }, + + rasterize: function(resolution) { + var bounds = this.getStrokeBounds(), + scale = (resolution || 72) / 72, + canvas = CanvasProvider.getCanvas(bounds.getSize().multiply(scale)), + ctx = canvas.getContext('2d'), + matrix = new Matrix().scale(scale).translate(-bounds.x, -bounds.y); + ctx.save(); + matrix.applyToContext(ctx); + this.draw(ctx, Base.merge({ transforms: [matrix] })); + var raster = new Raster(canvas); + raster.setBounds(bounds); + ctx.restore(); + return raster; + }, + + contains: function() { + return !!this._contains( + this._matrix._inverseTransform(Point.read(arguments))); + }, + + _contains: function(point) { + if (this._children) { + for (var i = this._children.length - 1; i >= 0; i--) { + if (this._children[i].contains(point)) + return true; + } + return false; + } + return point.isInside(this._getBounds('getBounds')); + }, + + hitTest: function(point, options) { + point = Point.read(arguments); + options = HitResult.getOptions(Base.read(arguments)); + + if (this._locked || !this._visible || this._guide && !options.guides) + return null; + + if (!this._children && !this.getRoughBounds() + .expand(options.tolerance)._containsPoint(point)) + return null; + point = this._matrix._inverseTransform(point); + + var that = this, + res; + function checkBounds(type, part) { + var pt = bounds['get' + part](); + if (point.getDistance(pt) < options.tolerance) + return new HitResult(type, that, + { name: Base.hyphenate(part), point: pt }); + } + + if ((options.center || options.bounds) && + !(this instanceof Layer && !this._parent)) { + var bounds = this._getBounds('getBounds'); + if (options.center) + res = checkBounds('center', 'Center'); + if (!res && options.bounds) { + var points = [ + 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight', + 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter' + ]; + for (var i = 0; i < 8 && !res; i++) + res = checkBounds('bounds', points[i]); + } + } + + if ((res || (res = this._children || !(options.guides && !this._guide + || options.selected && !this._selected) + ? this._hitTest(point, options) : null)) + && res.point) { + res.point = that._matrix.transform(res.point); + } + return res; + }, + + _hitTest: function(point, options) { + if (this._children) { + for (var i = this._children.length - 1, res; i >= 0; i--) + if (res = this._children[i].hitTest(point, options)) + return res; + } else if (this.hasFill() && this._contains(point)) { + return new HitResult('fill', this); + } + }, + + addChild: function(item, _preserve) { + return this.insertChild(undefined, item, _preserve); + }, + + insertChild: function(index, item, _preserve) { + var res = this.insertChildren(index, [item], _preserve); + return res && res[0]; + }, + + addChildren: function(items, _preserve) { + return this.insertChildren(this._children.length, items, _preserve); + }, + + insertChildren: function(index, items, _preserve, _type) { + var children = this._children; + if (children && items && items.length > 0) { + items = Array.prototype.slice.apply(items); + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + if (_type && item._type !== _type) + items.splice(i, 1); + else + item._remove(true); + } + Base.splice(children, items, index, 0); + for (var i = 0, l = items.length; i < l; i++) { + var item = items[i]; + item._parent = this; + item._setProject(this._project); + if (item._name) + item.setName(item._name); + } + this._changed(7); + } else { + items = null; + } + return items; + }, + + insertAbove: function(item, _preserve) { + var index = item._index; + if (item._parent == this._parent && index < this._index) + index++; + return item._parent.insertChild(index, this, _preserve); + }, + + insertBelow: function(item, _preserve) { + var index = item._index; + if (item._parent == this._parent && index > this._index) + index--; + return item._parent.insertChild(index, this, _preserve); + }, + + sendToBack: function() { + return this._parent.insertChild(0, this); + }, + + bringToFront: function() { + return this._parent.addChild(this); + }, + + appendTop: '#addChild', + + appendBottom: function(item) { + return this.insertChild(0, item); + }, + + moveAbove: '#insertAbove', + + moveBelow: '#insertBelow', + + _removeFromNamed: function() { + var children = this._parent._children, + namedChildren = this._parent._namedChildren, + name = this._name, + namedArray = namedChildren[name], + index = namedArray ? namedArray.indexOf(this) : -1; + if (index == -1) + return; + if (children[name] == this) + delete children[name]; + namedArray.splice(index, 1); + if (namedArray.length) { + children[name] = namedArray[namedArray.length - 1]; + } else { + delete namedChildren[name]; + } + }, + + _remove: function(notify) { + if (this._parent) { + if (this._name) + this._removeFromNamed(); + if (this._index != null) + Base.splice(this._parent._children, null, this._index, 1); + if (notify) + this._parent._changed(7); + this._parent = null; + return true; + } + return false; + }, + + remove: function() { + return this._remove(true); + }, + + removeChildren: function(from, to) { + if (!this._children) + return null; + from = from || 0; + to = Base.pick(to, this._children.length); + var removed = Base.splice(this._children, null, from, to - from); + for (var i = removed.length - 1; i >= 0; i--) + removed[i]._remove(false); + if (removed.length > 0) + this._changed(7); + return removed; + }, + + reverseChildren: function() { + if (this._children) { + this._children.reverse(); + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i]._index = i; + this._changed(7); + } + }, + + isEditable: function() { + var item = this; + while (item) { + if (!item._visible || item._locked) + return false; + item = item._parent; + } + return true; + }, + + _getOrder: function(item) { + function getList(item) { + var list = []; + do { + list.unshift(item); + } while (item = item._parent); + return list; + } + var list1 = getList(this), + list2 = getList(item); + for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) { + if (list1[i] != list2[i]) { + return list1[i]._index < list2[i]._index ? 1 : -1; + } + } + return 0; + }, + + hasChildren: function() { + return this._children && this._children.length > 0; + }, + + isAbove: function(item) { + return this._getOrder(item) == -1; + }, + + isBelow: function(item) { + return this._getOrder(item) == 1; + }, + + isParent: function(item) { + return this._parent == item; + }, + + isChild: function(item) { + return item && item._parent == this; + }, + + isDescendant: function(item) { + var parent = this; + while (parent = parent._parent) { + if (parent == item) + return true; + } + return false; + }, + + isAncestor: function(item) { + return item ? item.isDescendant(this) : false; + }, + + isGroupedWith: function(item) { + var parent = this._parent; + while (parent) { + if (parent._parent + && /^(group|layer|compound-path)$/.test(parent._type) + && item.isDescendant(parent)) + return true; + parent = parent._parent; + } + return false; + }, + + scale: function(hor, ver , center) { + if (arguments.length < 2 || typeof ver === 'object') { + center = ver; + ver = hor; + } + return this.transform(new Matrix().scale(hor, ver, + center || this.getPosition(true))); + }, + + translate: function() { + var mx = new Matrix(); + return this.transform(mx.translate.apply(mx, arguments)); + }, + + rotate: function(angle, center) { + return this.transform(new Matrix().rotate(angle, + center || this.getPosition(true))); + }, + + shear: function(hor, ver, center) { + if (arguments.length < 2 || typeof ver === 'object') { + center = ver; + ver = hor; + } + return this.transform(new Matrix().shear(hor, ver, + center || this.getPosition(true))); + }, + + transform: function(matrix ) { + var bounds = this._bounds, + position = this._position; + this._matrix.preConcatenate(matrix); + if (this._transformContent || arguments[1]) + this.applyMatrix(true); + this._changed(5); + if (bounds && matrix.getRotation() % 90 === 0) { + for (var key in bounds) { + var rect = bounds[key]; + matrix._transformBounds(rect, rect); + } + var getter = this._boundsGetter, + rect = bounds[getter && getter.getBounds || getter || 'getBounds']; + if (rect) + this._position = rect.getCenter(true); + this._bounds = bounds; + } else if (position) { + this._position = matrix._transformPoint(position, position); + } + return this; + }, + + _applyMatrix: function(matrix, applyMatrix) { + var children = this._children; + if (children && children.length > 0) { + for (var i = 0, l = children.length; i < l; i++) + children[i].transform(matrix, applyMatrix); + return true; + } + }, + + applyMatrix: function(_dontNotify) { + var matrix = this._matrix; + if (this._applyMatrix(matrix, true)) { + var style = this._style, + fillColor = style.getFillColor(true), + strokeColor = style.getStrokeColor(true); + if (fillColor) + fillColor.transform(matrix); + if (strokeColor) + strokeColor.transform(matrix); + matrix.reset(); + } + if (!_dontNotify) + this._changed(5); + }, + + fitBounds: function(rectangle, fill) { + rectangle = Rectangle.read(arguments); + var bounds = this.getBounds(), + itemRatio = bounds.height / bounds.width, + rectRatio = rectangle.height / rectangle.width, + scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio) + ? rectangle.width / bounds.width + : rectangle.height / bounds.height, + newBounds = new Rectangle(new Point(), + new Size(bounds.width * scale, bounds.height * scale)); + newBounds.setCenter(rectangle.getCenter()); + this.setBounds(newBounds); + }, + + importJSON: function(json) { + return this.addChild(Base.importJSON(json)); + }, + + _setStyles: function(ctx) { + var style = this._style, + width = style.getStrokeWidth(), + join = style.getStrokeJoin(), + cap = style.getStrokeCap(), + limit = style.getMiterLimit(), + fillColor = style.getFillColor(), + strokeColor = style.getStrokeColor(), + dashArray = style.getDashArray(), + dashOffset = style.getDashOffset(); + if (width != null) + ctx.lineWidth = width; + if (join) + ctx.lineJoin = join; + if (cap) + ctx.lineCap = cap; + if (limit) + ctx.miterLimit = limit; + if (fillColor) + ctx.fillStyle = fillColor.toCanvasStyle(ctx); + if (strokeColor) { + ctx.strokeStyle = strokeColor.toCanvasStyle(ctx); + if (paper.support.nativeDash && dashArray && dashArray.length) { + if ('setLineDash' in ctx) { + ctx.setLineDash(dashArray); + ctx.lineDashOffset = dashOffset; + } else { + ctx.mozDash = dashArray; + ctx.mozDashOffset = dashOffset; + } + } + } + }, + + draw: function(ctx, param) { + if (!this._visible || this._opacity == 0) + return; + this._drawCount = this._project._drawCount; + var transforms = param.transforms, + parentMatrix = transforms[transforms.length - 1], + globalMatrix = parentMatrix.clone().concatenate(this._matrix); + transforms.push(this._globalMatrix = globalMatrix); + var blendMode = this._blendMode, + opacity = this._opacity, + nativeBlend = BlendMode.nativeModes[blendMode], + direct = blendMode === 'normal' && opacity === 1 + || (nativeBlend || opacity < 1) && this._canComposite(), + mainCtx, itemOffset, prevOffset; + if (!direct) { + var bounds = this.getStrokeBounds(parentMatrix); + if (!bounds.width || !bounds.height) + return; + prevOffset = param.offset; + itemOffset = param.offset = bounds.getTopLeft().floor(); + mainCtx = ctx; + ctx = CanvasProvider.getContext( + bounds.getSize().ceil().add(new Size(1, 1))); + } + ctx.save(); + if (direct) { + ctx.globalAlpha = opacity; + if (nativeBlend) + ctx.globalCompositeOperation = blendMode; + } else { + ctx.translate(-itemOffset.x, -itemOffset.y); + } + (direct ? this._matrix : globalMatrix).applyToContext(ctx); + if (!direct && param.clipItem) + param.clipItem.draw(ctx, param.extend({ clip: true })); + this._draw(ctx, param); + ctx.restore(); + transforms.pop(); + if (param.clip) + ctx.clip(); + if (!direct) { + BlendMode.process(blendMode, ctx, mainCtx, opacity, + itemOffset.subtract(prevOffset)); + CanvasProvider.release(ctx); + param.offset = prevOffset; + } + }, + + _canComposite: function() { + return false; + } +}, Base.each(['down', 'drag', 'up', 'move'], function(name) { + this['removeOn' + Base.capitalize(name)] = function() { + var hash = {}; + hash[name] = true; + return this.removeOn(hash); + }; +}, { + + removeOn: function(obj) { + for (var name in obj) { + if (obj[name]) { + var key = 'mouse' + name, + project = this._project, + sets = project._removeSets = project._removeSets || {}; + sets[key] = sets[key] || {}; + sets[key][this._id] = this; + } + } + return this; + } +})); + +var Group = Item.extend({ + _class: 'Group', + _serializeFields: { + children: [] + }, + + initialize: function Group(arg) { + Item.call(this); + this._children = []; + this._namedChildren = {}; + if (arg && !this._set(arg)) + this.addChildren(Array.isArray(arg) ? arg : arguments); + }, + + _changed: function _changed(flags) { + _changed.base.call(this, flags); + if (flags & 2 && this._transformContent + && !this._matrix.isIdentity()) { + this.applyMatrix(); + } + if (flags & (2 | 256)) { + delete this._clipItem; + } + }, + + _getClipItem: function() { + if (this._clipItem !== undefined) + return this._clipItem; + for (var i = 0, l = this._children.length; i < l; i++) { + var child = this._children[i]; + if (child._clipMask) + return this._clipItem = child; + } + return this._clipItem = null; + }, + + getTransformContent: function() { + return this._transformContent; + }, + + setTransformContent: function(transform) { + this._transformContent = transform; + if (transform) + this.applyMatrix(); + }, + + isClipped: function() { + return !!this._getClipItem(); + }, + + setClipped: function(clipped) { + var child = this.getFirstChild(); + if (child) + child.setClipMask(clipped); + }, + + _draw: function(ctx, param) { + var clipItem = param.clipItem = this._getClipItem(); + if (clipItem) + clipItem.draw(ctx, param.extend({ clip: true })); + for (var i = 0, l = this._children.length; i < l; i++) { + var item = this._children[i]; + if (item !== clipItem) + item.draw(ctx, param); + } + param.clipItem = null; + } +}); + +var Layer = Group.extend({ + _class: 'Layer', + + initialize: function Layer() { + this._project = paper.project; + this._index = this._project.layers.push(this) - 1; + Group.apply(this, arguments); + this.activate(); + }, + + _remove: function _remove(notify) { + if (this._parent) + return _remove.base.call(this, notify); + if (this._index != null) { + if (this._project.activeLayer === this) + this._project.activeLayer = this.getNextSibling() + || this.getPreviousSibling(); + Base.splice(this._project.layers, null, this._index, 1); + this._project._needsRedraw = true; + return true; + } + return false; + }, + + getNextSibling: function getNextSibling() { + return this._parent ? getNextSibling.base.call(this) + : this._project.layers[this._index + 1] || null; + }, + + getPreviousSibling: function getPreviousSibling() { + return this._parent ? getPreviousSibling.base.call(this) + : this._project.layers[this._index - 1] || null; + }, + + isInserted: function isInserted() { + return this._parent ? isInserted.base.call(this) : this._index != null; + }, + + activate: function() { + this._project.activeLayer = this; + } +}, new function () { + function insert(above) { + return function insert(item) { + if (item instanceof Layer && !item._parent + && this._remove(true)) { + Base.splice(item._project.layers, [this], + item._index + (above ? 1 : 0), 0); + this._setProject(item._project); + return true; + } + return insert.base.call(this, item); + }; + } + + return { + insertAbove: insert(true), + + insertBelow: insert(false) + }; +}); + +var Shape = Item.extend({ + _class: 'Shape', + _transformContent: false, + + initialize: function Shape(type, point, size) { + Item.call(this, point); + this._type = type; + this._size = size; + }, + + _draw: function(ctx, param) { + var style = this._style, + size = this._size, + width = size.width, + height = size.height, + fillColor = style.getFillColor(), + strokeColor = style.getStrokeColor(); + if (fillColor || strokeColor || param.clip) { + ctx.beginPath(); + switch (this._type) { + case 'rect': + ctx.rect(-width / 2, -height / 2, width, height); + break; + case 'circle': + ctx.arc(0, 0, (width + height) / 4, 0, Math.PI * 2, true); + break; + case 'ellipse': + var mx = width / 2, + my = height / 2, + kappa = Numerical.KAPPA, + cx = mx * kappa, + cy = my * kappa; + ctx.moveTo(-mx, 0); + ctx.bezierCurveTo(-mx, -cy, -cx, -my, 0, -my); + ctx.bezierCurveTo(cx, -my, mx, -cy, mx, 0); + ctx.bezierCurveTo(mx, cy, cx, my, 0, my); + ctx.bezierCurveTo(-cx, my, -mx, cy, -mx, 0); + break; + } + } + if (!param.clip && (fillColor || strokeColor)) { + this._setStyles(ctx); + if (fillColor) + ctx.fill(); + if (strokeColor) + ctx.stroke(); + } + }, + + _canComposite: function() { + return !(this.hasFill() && this.hasStroke()); + }, + + _getBounds: function(getter, matrix) { + var rect = new Rectangle(this._size).setCenter(0, 0); + if (getter !== 'getBounds' && this.hasStroke()) + rect = rect.expand(this.getStrokeWidth()); + return matrix ? matrix._transformBounds(rect) : rect; + }, + + _contains: function _contains(point) { + switch (this._type) { + case 'rect': + return _contains.base.call(this, point); + case 'circle': + case 'ellipse': + return point.divide(this._size).getLength() <= 0.5; + } + }, + + _hitTest: function _hitTest(point) { + if (this.hasStroke()) { + var type = this._type, + strokeWidth = this.getStrokeWidth(); + switch (type) { + case 'rect': + var rect = new Rectangle(this._size).setCenter(0, 0), + outer = rect.expand(strokeWidth), + inner = rect.expand(-strokeWidth); + if (outer._containsPoint(point) && !inner._containsPoint(point)) + return new HitResult('stroke', this); + break; + case 'circle': + case 'ellipse': + var size = this._size, + width = size.width, + height = size.height, + radius; + if (type === 'ellipse') { + var angle = point.getAngleInRadians(), + x = width * Math.sin(angle), + y = height * Math.cos(angle); + radius = width * height / (2 * Math.sqrt(x * x + y * y)); + } else { + radius = (width + height) / 4; + } + if (2 * Math.abs(point.getLength() - radius) <= strokeWidth) + return new HitResult('stroke', this); + break; + } + } + return _hitTest.base.apply(this, arguments); + }, + + statics: new function() { + function createShape(type, point, size, args) { + var shape = new Shape(type, point, size), + named = Base.getNamed(args); + if (named) + shape._set(named); + return shape; + } + + return { + Circle: function() { + var center = Point.readNamed(arguments, 'center'), + radius = Base.readNamed(arguments, 'radius'); + return createShape('circle', center, new Size(radius * 2), + arguments); + }, + + Rectangle: function() { + var rect = Rectangle.readNamed(arguments, 'rectangle'); + return createShape('rect', rect.getCenter(true), + rect.getSize(true), arguments); + }, + + Ellipse: function() { + var rect = Rectangle.readNamed(arguments, 'rectangle'); + return createShape('ellipse', rect.getCenter(true), + rect.getSize(true), arguments); + } + }; + } +}); + +var Raster = Item.extend({ + _class: 'Raster', + _transformContent: false, + _boundsGetter: 'getBounds', + _boundsSelected: true, + _serializeFields: { + source: null + }, + + initialize: function Raster(object, position) { + Item.call(this, position !== undefined && Point.read(arguments, 1)); + if (object && !this._set(object)) { + if (object.getContext) { + this.setCanvas(object); + } else if (typeof object === 'string') { + this.setSource(object); + } else { + this.setImage(object); + } + } + if (!this._size) + this._size = new Size(); + }, + + clone: function() { + var element = this._image; + if (!element) { + element = CanvasProvider.getCanvas(this._size); + element.getContext('2d').drawImage(this._canvas, 0, 0); + } + var copy = new Raster(element); + return this._clone(copy); + }, + + getSize: function() { + return this._size; + }, + + setSize: function() { + var size = Size.read(arguments); + if (!this._size.equals(size)) { + var element = this.getElement(); + this.setCanvas(CanvasProvider.getCanvas(size)); + if (element) + this.getContext(true).drawImage(element, 0, 0, + size.width, size.height); + } + }, + + getWidth: function() { + return this._size.width; + }, + + getHeight: function() { + return this._size.height; + }, + + isEmpty: function() { + return this._size.width == 0 && this._size.height == 0; + }, + + getPpi: function() { + var matrix = this._matrix, + orig = new Point(0, 0).transform(matrix), + u = new Point(1, 0).transform(matrix).subtract(orig), + v = new Point(0, 1).transform(matrix).subtract(orig); + return new Size( + 72 / u.getLength(), + 72 / v.getLength() + ); + }, + + getContext: function() { + if (!this._context) + this._context = this.getCanvas().getContext('2d'); + if (arguments[0]) { + this._image = null; + this._changed(129); + } + return this._context; + }, + + setContext: function(context) { + this._context = context; + }, + + getCanvas: function() { + if (!this._canvas) { + var ctx = CanvasProvider.getContext(this._size); + try { + if (this._image) + ctx.drawImage(this._image, 0, 0); + this._canvas = ctx.canvas; + } catch (e) { + CanvasProvider.release(ctx); + } + } + return this._canvas; + }, + + setCanvas: function(canvas) { + if (this._canvas) + CanvasProvider.release(this._canvas); + this._canvas = canvas; + this._size = new Size(canvas.width, canvas.height); + this._image = null; + this._context = null; + this._changed(5 | 129); + }, + + getImage: function() { + return this._image; + }, + + setImage: function(image) { + if (this._canvas) + CanvasProvider.release(this._canvas); + this._image = image; + this._size = new Size(image.naturalWidth, image.naturalHeight); + this._canvas = null; + this._context = null; + this._changed(5); + }, + + getSource: function() { + return this._image && this._image.src || this.toDataURL(); + }, + + setSource: function(src) { + var that = this, + image = document.getElementById(src) || new Image(); + function loaded() { + that.fire('load'); + if (that._project.view) + that._project.view.draw(true); + } + DomEvent.add(image, { + load: function() { + that.setImage(image); + loaded(); + } + }); + if (image.width && image.height) { + setTimeout(loaded, 0); + } else if (!image.src) { + image.src = src; + } + this.setImage(image); + }, + + getElement: function() { + return this._canvas || this._image; + }, + + getSubImage: function(rect) { + rect = Rectangle.read(arguments); + var ctx = CanvasProvider.getContext(rect.getSize()); + ctx.drawImage(this.getCanvas(), rect.x, rect.y, + rect.width, rect.height, 0, 0, rect.width, rect.height); + return ctx.canvas; + }, + + toDataURL: function() { + var src = this._image && this._image.src; + if (/^data:/.test(src)) + return src; + var canvas = this.getCanvas(); + return canvas ? canvas.toDataURL() : null; + }, + + drawImage: function(image, point) { + point = Point.read(arguments, 1); + this.getContext(true).drawImage(image, point.x, point.y); + }, + + getAverageColor: function(object) { + var bounds, path; + if (!object) { + bounds = this.getBounds(); + } else if (object instanceof PathItem) { + path = object; + bounds = object.getBounds(); + } else if (object.width) { + bounds = new Rectangle(object); + } else if (object.x) { + bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1); + } + var sampleSize = 32, + width = Math.min(bounds.width, sampleSize), + height = Math.min(bounds.height, sampleSize); + var ctx = Raster._sampleContext; + if (!ctx) { + ctx = Raster._sampleContext = CanvasProvider.getContext( + new Size(sampleSize)); + } else { + ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1); + } + ctx.save(); + var matrix = new Matrix() + .scale(width / bounds.width, height / bounds.height) + .translate(-bounds.x, -bounds.y); + matrix.applyToContext(ctx); + if (path) + path.draw(ctx, Base.merge({ clip: true, transforms: [matrix] })); + this._matrix.applyToContext(ctx); + ctx.drawImage(this.getElement(), + -this._size.width / 2, -this._size.height / 2); + ctx.restore(); + var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width), + Math.ceil(height)).data, + channels = [0, 0, 0], + total = 0; + for (var i = 0, l = pixels.length; i < l; i += 4) { + var alpha = pixels[i + 3]; + total += alpha; + alpha /= 255; + channels[0] += pixels[i] * alpha; + channels[1] += pixels[i + 1] * alpha; + channels[2] += pixels[i + 2] * alpha; + } + for (var i = 0; i < 3; i++) + channels[i] /= total; + return total ? Color.read(channels) : null; + }, + + getPixel: function(point) { + point = Point.read(arguments); + var data = this.getContext().getImageData(point.x, point.y, 1, 1).data; + return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255], + data[3] / 255); + }, + + setPixel: function() { + var point = Point.read(arguments), + color = Color.read(arguments), + components = color._convert('rgb'), + alpha = color._alpha, + ctx = this.getContext(true), + imageData = ctx.createImageData(1, 1), + data = imageData.data; + data[0] = components[0] * 255; + data[1] = components[1] * 255; + data[2] = components[2] * 255; + data[3] = alpha != null ? alpha * 255 : 255; + ctx.putImageData(imageData, point.x, point.y); + }, + + createImageData: function(size) { + size = Size.read(arguments); + return this.getContext().createImageData(size.width, size.height); + }, + + getImageData: function(rect) { + rect = Rectangle.read(arguments); + if (rect.isEmpty()) + rect = new Rectangle(this.getSize()); + return this.getContext().getImageData(rect.x, rect.y, + rect.width, rect.height); + }, + + setImageData: function(data, point) { + point = Point.read(arguments, 1); + this.getContext(true).putImageData(data, point.x, point.y); + }, + + _getBounds: function(getter, matrix) { + var rect = new Rectangle(this._size).setCenter(0, 0); + return matrix ? matrix._transformBounds(rect) : rect; + }, + + _hitTest: function(point) { + if (this._contains(point)) { + var that = this; + return new HitResult('pixel', that, { + offset: point.add(that._size.divide(2)).round(), + color: { + get: function() { + return that.getPixel(this.offset); + } + } + }); + } + }, + + _draw: function(ctx) { + var element = this.getElement(); + if (element) { + ctx.globalAlpha = this._opacity; + ctx.drawImage(element, + -this._size.width / 2, -this._size.height / 2); + } + }, + + _canComposite: function() { + return true; + } +}); + +var PlacedSymbol = Item.extend({ + _class: 'PlacedSymbol', + _transformContent: false, + _boundsGetter: { getBounds: 'getStrokeBounds' }, + _boundsSelected: true, + _serializeFields: { + symbol: null + }, + + initialize: function PlacedSymbol(arg0, arg1) { + Item.call(this, arg1 !== undefined && Point.read(arguments, 1)); + if (arg0 && !this._set(arg0)) + this.setSymbol(arg0 instanceof Symbol ? arg0 : new Symbol(arg0)); + }, + + getSymbol: function() { + return this._symbol; + }, + + setSymbol: function(symbol) { + if (this._symbol) + delete this._symbol._instances[this._id]; + this._symbol = symbol; + symbol._instances[this._id] = this; + }, + + clone: function() { + return this._clone(new PlacedSymbol(this.symbol)); + }, + + isEmpty: function() { + return this._symbol._definition.isEmpty(); + }, + + _getBounds: function(getter, matrix) { + return this.symbol._definition._getCachedBounds(getter, matrix); + }, + + _hitTest: function(point, options, matrix) { + var result = this._symbol._definition._hitTest(point, options, matrix); + if (result) + result.item = this; + return result; + }, + + _draw: function(ctx, param) { + this.symbol._definition.draw(ctx, param); + } + +}); + +var HitResult = Base.extend({ + _class: 'HitResult', + + initialize: function HitResult(type, item, values) { + this.type = type; + this.item = item; + if (values) { + values.enumerable = true; + this.inject(values); + } + }, + + statics: { + getOptions: function(options) { + return options && options._merged ? options : Base.merge({ + type: null, + tolerance: paper.project.options.hitTolerance || 2, + fill: !options, + stroke: !options, + segments: !options, + handles: false, + ends: false, + center: false, + bounds: false, + guides: false, + selected: false, + _merged: true + }, options); + } + } +}); + +var Segment = Base.extend({ + _class: 'Segment', + + initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) { + var count = arguments.length, + point, handleIn, handleOut; + if (count === 0) { + } else if (count === 1) { + if (arg0.point) { + point = arg0.point; + handleIn = arg0.handleIn; + handleOut = arg0.handleOut; + } else { + point = arg0; + } + } else if (count < 6) { + if (count == 2 && arg1.x === undefined) { + point = [ arg0, arg1 ]; + } else { + point = arg0; + handleIn = arg1; + handleOut = arg2; + } + } else if (count === 6) { + point = [ arg0, arg1 ]; + handleIn = [ arg2, arg3 ]; + handleOut = [ arg4, arg5 ]; + } + this._point = new SegmentPoint(point, this); + this._handleIn = new SegmentPoint(handleIn, this); + this._handleOut = new SegmentPoint(handleOut, this); + }, + + _serialize: function(options) { + return Base.serialize(this.isLinear() ? this._point + : [this._point, this._handleIn, this._handleOut], options, true); + }, + + _changed: function(point) { + if (!this._path) + return; + var curve = this._path._curves && this.getCurve(), + other; + if (curve) { + curve._changed(); + if (other = (curve[point == this._point + || point == this._handleIn && curve._segment1 == this + ? 'getPrevious' : 'getNext']())) { + other._changed(); + } + } + this._path._changed(5); + }, + + getPoint: function() { + return this._point; + }, + + setPoint: function(point) { + point = Point.read(arguments); + this._point.set(point.x, point.y); + }, + + getHandleIn: function() { + return this._handleIn; + }, + + setHandleIn: function(point) { + point = Point.read(arguments); + this._handleIn.set(point.x, point.y); + }, + + getHandleOut: function() { + return this._handleOut; + }, + + setHandleOut: function(point) { + point = Point.read(arguments); + this._handleOut.set(point.x, point.y); + }, + + isLinear: function() { + return this._handleIn.isZero() && this._handleOut.isZero(); + }, + + setLinear: function() { + this._handleIn.set(0, 0); + this._handleOut.set(0, 0); + }, + + _isSelected: function(point) { + var state = this._selectionState; + return point == this._point ? !!(state & 4) + : point == this._handleIn ? !!(state & 1) + : point == this._handleOut ? !!(state & 2) + : false; + }, + + _setSelected: function(point, selected) { + var path = this._path, + selected = !!selected, + state = this._selectionState || 0, + selection = [ + !!(state & 4), + !!(state & 1), + !!(state & 2) + ]; + if (point == this._point) { + if (selected) { + selection[1] = selection[2] = false; + } else { + var previous = this.getPrevious(), + next = this.getNext(); + selection[1] = previous && (previous._point.isSelected() + || previous._handleOut.isSelected()); + selection[2] = next && (next._point.isSelected() + || next._handleIn.isSelected()); + } + selection[0] = selected; + } else { + var index = point == this._handleIn ? 1 : 2; + if (selection[index] != selected) { + if (selected) + selection[0] = false; + selection[index] = selected; + } + } + this._selectionState = (selection[0] ? 4 : 0) + | (selection[1] ? 1 : 0) + | (selection[2] ? 2 : 0); + if (path && state != this._selectionState) { + path._updateSelection(this, state, this._selectionState); + path._changed(33); + } + }, + + isSelected: function() { + return this._isSelected(this._point); + }, + + setSelected: function(selected) { + this._setSelected(this._point, selected); + }, + + getIndex: function() { + return this._index !== undefined ? this._index : null; + }, + + getPath: function() { + return this._path || null; + }, + + getCurve: function() { + var path = this._path, + index = this._index; + if (path) { + if (!path._closed && index == path._segments.length - 1) + index--; + return path.getCurves()[index] || null; + } + return null; + }, + + getLocation: function() { + var curve = this.getCurve(); + return curve ? new CurveLocation(curve, curve.getNext() ? 0 : 1) : null; + }, + + getNext: function() { + var segments = this._path && this._path._segments; + return segments && (segments[this._index + 1] + || this._path._closed && segments[0]) || null; + }, + + getPrevious: function() { + var segments = this._path && this._path._segments; + return segments && (segments[this._index - 1] + || this._path._closed && segments[segments.length - 1]) || null; + }, + + reverse: function() { + return new Segment(this._point, this._handleOut, this._handleIn); + }, + + remove: function() { + return this._path ? !!this._path.removeSegment(this._index) : false; + }, + + clone: function() { + return new Segment(this._point, this._handleIn, this._handleOut); + }, + + equals: function(segment) { + return segment === this || segment + && this._point.equals(segment._point) + && this._handleIn.equals(segment._handleIn) + && this._handleOut.equals(segment._handleOut) + || false; + }, + + toString: function() { + var parts = [ 'point: ' + this._point ]; + if (!this._handleIn.isZero()) + parts.push('handleIn: ' + this._handleIn); + if (!this._handleOut.isZero()) + parts.push('handleOut: ' + this._handleOut); + return '{ ' + parts.join(', ') + ' }'; + }, + + _transformCoordinates: function(matrix, coords, change) { + var point = this._point, + handleIn = !change || !this._handleIn.isZero() + ? this._handleIn : null, + handleOut = !change || !this._handleOut.isZero() + ? this._handleOut : null, + x = point._x, + y = point._y, + i = 2; + coords[0] = x; + coords[1] = y; + if (handleIn) { + coords[i++] = handleIn._x + x; + coords[i++] = handleIn._y + y; + } + if (handleOut) { + coords[i++] = handleOut._x + x; + coords[i++] = handleOut._y + y; + } + if (matrix) { + matrix._transformCoordinates(coords, 0, coords, 0, i / 2); + x = coords[0]; + y = coords[1]; + if (change) { + point._x = x; + point._y = y; + i = 2; + if (handleIn) { + handleIn._x = coords[i++] - x; + handleIn._y = coords[i++] - y; + } + if (handleOut) { + handleOut._x = coords[i++] - x; + handleOut._y = coords[i++] - y; + } + } else { + if (!handleIn) { + coords[i++] = x; + coords[i++] = y; + } + if (!handleOut) { + coords[i++] = x; + coords[i++] = y; + } + } + } + return coords; + } +}); + +var SegmentPoint = Point.extend({ + initialize: function SegmentPoint(point, owner) { + var x, y, selected; + if (!point) { + x = y = 0; + } else if ((x = point[0]) !== undefined) { + y = point[1]; + } else { + if ((x = point.x) === undefined) { + point = Point.read(arguments); + x = point.x; + } + y = point.y; + selected = point.selected; + } + this._x = x; + this._y = y; + this._owner = owner; + if (selected) + this.setSelected(true); + }, + + set: function(x, y) { + this._x = x; + this._y = y; + this._owner._changed(this); + return this; + }, + + getX: function() { + return this._x; + }, + + setX: function(x) { + this._x = x; + this._owner._changed(this); + }, + + getY: function() { + return this._y; + }, + + setY: function(y) { + this._y = y; + this._owner._changed(this); + }, + + isZero: function() { + return Numerical.isZero(this._x) && Numerical.isZero(this._y); + }, + + setSelected: function(selected) { + this._owner._setSelected(this, selected); + }, + + isSelected: function() { + return this._owner._isSelected(this); + } +}); + +var Curve = Base.extend({ + _class: 'Curve', + initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) { + var count = arguments.length; + if (count === 3) { + this._path = arg0; + this._segment1 = arg1; + this._segment2 = arg2; + } else if (count === 0) { + this._segment1 = new Segment(); + this._segment2 = new Segment(); + } else if (count === 1) { + this._segment1 = new Segment(arg0.segment1); + this._segment2 = new Segment(arg0.segment2); + } else if (count === 2) { + this._segment1 = new Segment(arg0); + this._segment2 = new Segment(arg1); + } else { + var point1, handle1, handle2, point2; + if (count === 4) { + point1 = arg0; + handle1 = arg1; + handle2 = arg2; + point2 = arg3; + } else if (count === 8) { + point1 = [arg0, arg1]; + point2 = [arg6, arg7]; + handle1 = [arg2 - arg0, arg3 - arg1]; + handle2 = [arg4 - arg6, arg5 - arg7]; + } + this._segment1 = new Segment(point1, null, handle1); + this._segment2 = new Segment(point2, handle2, null); + } + }, + + _changed: function() { + delete this._length; + delete this._bounds; + }, + + getPoint1: function() { + return this._segment1._point; + }, + + setPoint1: function(point) { + point = Point.read(arguments); + this._segment1._point.set(point.x, point.y); + }, + + getPoint2: function() { + return this._segment2._point; + }, + + setPoint2: function(point) { + point = Point.read(arguments); + this._segment2._point.set(point.x, point.y); + }, + + getHandle1: function() { + return this._segment1._handleOut; + }, + + setHandle1: function(point) { + point = Point.read(arguments); + this._segment1._handleOut.set(point.x, point.y); + }, + + getHandle2: function() { + return this._segment2._handleIn; + }, + + setHandle2: function(point) { + point = Point.read(arguments); + this._segment2._handleIn.set(point.x, point.y); + }, + + getSegment1: function() { + return this._segment1; + }, + + getSegment2: function() { + return this._segment2; + }, + + getPath: function() { + return this._path; + }, + + getIndex: function() { + return this._segment1._index; + }, + + getNext: function() { + var curves = this._path && this._path._curves; + return curves && (curves[this._segment1._index + 1] + || this._path._closed && curves[0]) || null; + }, + + getPrevious: function() { + var curves = this._path && this._path._curves; + return curves && (curves[this._segment1._index - 1] + || this._path._closed && curves[curves.length - 1]) || null; + }, + + isSelected: function() { + return this.getHandle1().isSelected() && this.getHandle2().isSelected(); + }, + + setSelected: function(selected) { + this.getHandle1().setSelected(selected); + this.getHandle2().setSelected(selected); + }, + + getValues: function() { + return Curve.getValues(this._segment1, this._segment2); + }, + + getPoints: function() { + var coords = this.getValues(), + points = []; + for (var i = 0; i < 8; i += 2) + points.push(new Point(coords[i], coords[i + 1])); + return points; + }, + + getLength: function() { + var from = arguments[0], + to = arguments[1], + fullLength = arguments.length === 0 || from === 0 && to === 1; + if (fullLength && this._length != null) + return this._length; + var length = Curve.getLength(this.getValues(), from, to); + if (fullLength) + this._length = length; + return length; + }, + + getArea: function() { + return Curve.getArea(this.getValues()); + }, + + getPart: function(from, to) { + return new Curve(Curve.getPart(this.getValues(), from, to)); + }, + + isLinear: function() { + return this._segment1._handleOut.isZero() + && this._segment2._handleIn.isZero(); + }, + + getIntersections: function(curve) { + return Curve.getIntersections(this.getValues(), curve.getValues(), + this, curve, []); + }, + + reverse: function() { + return new Curve(this._segment2.reverse(), this._segment1.reverse()); + }, + + divide: function(parameter) { + var res = null; + if (parameter && parameter.curve === this) + parameter = parameter.parameter; + if (parameter > 0 && parameter < 1) { + var parts = Curve.subdivide(this.getValues(), parameter), + isLinear = this.isLinear(), + left = parts[0], + right = parts[1]; + + if (!isLinear) { + this._segment1._handleOut.set(left[2] - left[0], + left[3] - left[1]); + this._segment2._handleIn.set(right[4] - right[6], + right[5] - right[7]); + } + + var x = left[6], y = left[7], + segment = new Segment(new Point(x, y), + !isLinear && new Point(left[4] - x, left[5] - y), + !isLinear && new Point(right[2] - x, right[3] - y)); + + if (this._path) { + if (this._segment1._index > 0 && this._segment2._index === 0) { + this._path.add(segment); + } else { + this._path.insert(this._segment2._index, segment); + } + res = this; + } else { + var end = this._segment2; + this._segment2 = segment; + res = new Curve(segment, end); + } + } + return res; + }, + + split: function(parameter) { + return this._path + ? this._path.split(this._segment1._index, parameter) + : null; + }, + + clone: function() { + return new Curve(this._segment1, this._segment2); + }, + + toString: function() { + var parts = [ 'point1: ' + this._segment1._point ]; + if (!this._segment1._handleOut.isZero()) + parts.push('handle1: ' + this._segment1._handleOut); + if (!this._segment2._handleIn.isZero()) + parts.push('handle2: ' + this._segment2._handleIn); + parts.push('point2: ' + this._segment2._point); + return '{ ' + parts.join(', ') + ' }'; + }, + +statics: { + getValues: function(segment1, segment2) { + var p1 = segment1._point, + h1 = segment1._handleOut, + h2 = segment2._handleIn, + p2 = segment2._point; + return [ + p1._x, p1._y, + p1._x + h1._x, p1._y + h1._y, + p2._x + h2._x, p2._y + h2._y, + p2._x, p2._y + ]; + }, + + evaluate: function(v, offset, isParameter, type) { + var t = isParameter ? offset : Curve.getParameterAt(v, offset, 0), + p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7], + x, y; + + if (type === 0 && (t === 0 || t === 1)) { + x = t === 0 ? p1x : p2x; + y = t === 0 ? p1y : p2y; + } else { + var cx = 3 * (c1x - p1x), + bx = 3 * (c2x - c1x) - cx, + ax = p2x - p1x - cx - bx, + + cy = 3 * (c1y - p1y), + by = 3 * (c2y - c1y) - cy, + ay = p2y - p1y - cy - by; + if (type === 0) { + x = ((ax * t + bx) * t + cx) * t + p1x; + y = ((ay * t + by) * t + cy) * t + p1y; + } else { + var tMin = 0.00001; + if (t < tMin && c1x == p1x && c1y == p1y + || t > 1 - tMin && c2x == p2x && c2y == p2y) { + x = c2x - c1x; + y = c2y - c1y; + } else { + x = (3 * ax * t + 2 * bx) * t + cx; + y = (3 * ay * t + 2 * by) * t + cy; + } + if (type === 3) { + var x2 = 6 * ax * t + 2 * bx, + y2 = 6 * ay * t + 2 * by; + return (x * y2 - y * x2) / Math.pow(x * x + y * y, 3 / 2); + } + } + } + return type == 2 ? new Point(y, -x) : new Point(x, y); + }, + + subdivide: function(v, t) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7]; + if (t === undefined) + t = 0.5; + var u = 1 - t, + p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y, + p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y, + p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y, + p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y, + p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y, + p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y; + return [ + [p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y], + [p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y] + ]; + }, + + solveCubic: function (v, coord, val, roots) { + var p1 = v[coord], + c1 = v[coord + 2], + c2 = v[coord + 4], + p2 = v[coord + 6], + c = 3 * (c1 - p1), + b = 3 * (c2 - c1) - c, + a = p2 - p1 - c - b; + return Numerical.solveCubic(a, b, c, p1 - val, roots); + }, + + getParameterOf: function(v, x, y) { + if (Math.abs(v[0] - x) < 0.00001 + && Math.abs(v[1] - y) < 0.00001) + return 0; + if (Math.abs(v[6] - x) < 0.00001 + && Math.abs(v[7] - y) < 0.00001) + return 1; + var txs = [], + tys = [], + sx = Curve.solveCubic(v, 0, x, txs), + sy = Curve.solveCubic(v, 1, y, tys), + tx, ty; + for (var cx = 0; sx == -1 || cx < sx;) { + if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) { + for (var cy = 0; sy == -1 || cy < sy;) { + if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) { + if (sx == -1) tx = ty; + else if (sy == -1) ty = tx; + if (Math.abs(tx - ty) < 0.00001) + return (tx + ty) * 0.5; + } + } + if (sx == -1) + break; + } + } + return null; + }, + + getPart: function(v, from, to) { + if (from > 0) + v = Curve.subdivide(v, from)[1]; + if (to < 1) + v = Curve.subdivide(v, (to - from) / (1 - from))[0]; + return v; + }, + + isLinear: function(v) { + return v[0] === v[2] && v[1] === v[3] && v[4] === v[6] && v[5] === v[7]; + }, + + isFlatEnough: function(v, tolerance) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7], + ux = 3 * c1x - 2 * p1x - p2x, + uy = 3 * c1y - 2 * p1y - p2y, + vx = 3 * c2x - 2 * p2x - p1x, + vy = 3 * c2y - 2 * p2y - p1y; + return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy) + < 10 * tolerance * tolerance; + }, + + getArea: function(v) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7]; + return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x + - 1.5 * c1y * p2x - 3.0 * p1y * c1x + - 1.5 * p1y * c2x - 0.5 * p1y * p2x + + 1.5 * c2y * p1x + 1.5 * c2y * c1x + - 3.0 * c2y * p2x + 0.5 * p2y * p1x + + 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10; + }, + + getBounds: function(v) { + var min = v.slice(0, 2), + max = min.slice(), + roots = [0, 0]; + for (var i = 0; i < 2; i++) + Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6], + i, 0, min, max, roots); + return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]); + }, + + _getCrossings: function(v, prev, x, y, roots) { + var count = Curve.solveCubic(v, 1, y, roots), + crossings = 0, + tolerance = 0.00001, + abs = Math.abs; + + function changesOrientation(tangent) { + return Curve.evaluate(prev, 1, true, 1).y + * tangent.y > 0; + } + + if (count === -1) { + roots[0] = Curve.getParameterOf(v, x, y); + count = roots[0] !== null ? 1 : 0; + } + for (var i = 0; i < count; i++) { + var t = roots[i]; + if (t > -tolerance && t < 1 - tolerance) { + var pt = Curve.evaluate(v, t, true, 0); + if (x < pt.x + tolerance) { + var tan = Curve.evaluate(v, t, true, 1); + if (abs(pt.x - x) < tolerance) { + var angle = tan.getAngle(); + if (angle > -180 && angle < 0 + && (t > tolerance || changesOrientation(tan))) + continue; + } else { + if (abs(tan.y) < tolerance + || t < tolerance && !changesOrientation(tan)) + continue; + } + crossings++; + } + } + } + return crossings; + }, + + _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) { + function add(value, padding) { + var left = value - padding, + right = value + padding; + if (left < min[coord]) + min[coord] = left; + if (right > max[coord]) + max[coord] = right; + } + var a = 3 * (v1 - v2) - v0 + v3, + b = 2 * (v0 + v2) - 4 * v1, + c = v1 - v0, + count = Numerical.solveQuadratic(a, b, c, roots), + tMin = 0.00001, + tMax = 1 - tMin; + add(v3, 0); + for (var i = 0; i < count; i++) { + var t = roots[i], + u = 1 - t; + if (tMin < t && t < tMax) + add(u * u * u * v0 + + 3 * u * u * t * v1 + + 3 * u * t * t * v2 + + t * t * t * v3, + padding); + } + } +}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'], + function(name) { + this[name] = function() { + if (!this._bounds) + this._bounds = {}; + var bounds = this._bounds[name]; + if (!bounds) { + bounds = this._bounds[name] = Path[name]([this._segment1, + this._segment2], false, this._path.getStyle()); + } + return bounds.clone(); + }; + }, +{ + +}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvatureAt'], + function(name, index) { + this[name + 'At'] = function(offset, isParameter) { + return Curve.evaluate(this.getValues(), offset, isParameter, index); + }; + this[name] = function(parameter) { + return Curve.evaluate(this.getValues(), parameter, true, index); + }; + }, +{ + getParameterAt: function(offset, start) { + return Curve.getParameterAt(this.getValues(), offset, + start !== undefined ? start : offset < 0 ? 1 : 0); + }, + + getParameterOf: function(point) { + point = Point.read(arguments); + return Curve.getParameterOf(this.getValues(), point.x, point.y); + }, + + getLocationAt: function(offset, isParameter) { + if (!isParameter) + offset = this.getParameterAt(offset); + return new CurveLocation(this, offset); + }, + + getLocationOf: function(point) { + point = Point.read(arguments); + var t = this.getParameterOf(point); + return t != null ? new CurveLocation(this, t) : null; + }, + + getNearestLocation: function(point) { + point = Point.read(arguments); + var values = this.getValues(), + count = 100, + tolerance = Numerical.TOLERANCE, + minDist = Infinity, + minT = 0; + + function refine(t) { + if (t >= 0 && t <= 1) { + var dist = point.getDistance( + Curve.evaluate(values, t, true, 0), true); + if (dist < minDist) { + minDist = dist; + minT = t; + return true; + } + } + } + + for (var i = 0; i <= count; i++) + refine(i / count); + + var step = 1 / (count * 2); + while (step > tolerance) { + if (!refine(minT - step) && !refine(minT + step)) + step /= 2; + } + var pt = Curve.evaluate(values, minT, true, 0); + return new CurveLocation(this, minT, pt, null, null, null, + point.getDistance(pt)); + }, + + getNearestPoint: function(point) { + point = Point.read(arguments); + return this.getNearestLocation(point).getPoint(); + } + +}), +new function() { + + function getLengthIntegrand(v) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7], + + ax = 9 * (c1x - c2x) + 3 * (p2x - p1x), + bx = 6 * (p1x + c2x) - 12 * c1x, + cx = 3 * (c1x - p1x), + + ay = 9 * (c1y - c2y) + 3 * (p2y - p1y), + by = 6 * (p1y + c2y) - 12 * c1y, + cy = 3 * (c1y - p1y); + + return function(t) { + var dx = (ax * t + bx) * t + cx, + dy = (ay * t + by) * t + cy; + return Math.sqrt(dx * dx + dy * dy); + }; + } + + function getIterations(a, b) { + return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32))); + } + + return { + statics: true, + + getLength: function(v, a, b) { + if (a === undefined) + a = 0; + if (b === undefined) + b = 1; + if (v[0] == v[2] && v[1] == v[3] && v[6] == v[4] && v[7] == v[5]) { + var dx = v[6] - v[0], + dy = v[7] - v[1]; + return (b - a) * Math.sqrt(dx * dx + dy * dy); + } + var ds = getLengthIntegrand(v); + return Numerical.integrate(ds, a, b, getIterations(a, b)); + }, + + getParameterAt: function(v, offset, start) { + if (offset === 0) + return start; + var forward = offset > 0, + a = forward ? start : 0, + b = forward ? 1 : start, + offset = Math.abs(offset), + ds = getLengthIntegrand(v), + rangeLength = Numerical.integrate(ds, a, b, + getIterations(a, b)); + if (offset >= rangeLength) + return forward ? b : a; + var guess = offset / rangeLength, + length = 0; + function f(t) { + var count = getIterations(start, t); + length += start < t + ? Numerical.integrate(ds, start, t, count) + : -Numerical.integrate(ds, t, start, count); + start = t; + return length - offset; + } + return Numerical.findRoot(f, ds, + forward ? a + guess : b - guess, + a, b, 16, 0.00001); + } + }; +}, new function() { + function addLocation(locations, curve1, t1, point1, curve2, t2, point2) { + var first = locations[0], + last = locations[locations.length - 1]; + if ((!first || !point1.equals(first._point)) + && (!last || !point1.equals(last._point))) + locations.push( + new CurveLocation(curve1, t1, point1, curve2, t2, point2)); + } + + function addCurveIntersections(v1, v2, curve1, curve2, locations, + range1, range2, recursion) { + recursion = (recursion || 0) + 1; + if (recursion > 20) + return; + range1 = range1 || [ 0, 1 ]; + range2 = range2 || [ 0, 1 ]; + var part1 = Curve.getPart(v1, range1[0], range1[1]), + part2 = Curve.getPart(v2, range2[0], range2[1]), + iteration = 0; + while (iteration++ < 20) { + var range, + intersects1 = clipFatLine(part1, part2, range = range2.slice()), + intersects2 = 0; + if (intersects1 === 0) + break; + if (intersects1 > 0) { + range2 = range; + part2 = Curve.getPart(v2, range2[0], range2[1]); + intersects2 = clipFatLine(part2, part1, range = range1.slice()); + if (intersects2 === 0) + break; + if (intersects1 > 0) { + range1 = range; + part1 = Curve.getPart(v1, range1[0], range1[1]); + } + } + if (intersects1 < 0 || intersects2 < 0) { + if (range1[1] - range1[0] > range2[1] - range2[0]) { + var t = (range1[0] + range1[1]) / 2; + addCurveIntersections(v1, v2, curve1, curve2, locations, + [ range1[0], t ], range2, recursion); + addCurveIntersections(v1, v2, curve1, curve2, locations, + [ t, range1[1] ], range2, recursion); + break; + } else { + var t = (range2[0] + range2[1]) / 2; + addCurveIntersections(v1, v2, curve1, curve2, locations, + range1, [ range2[0], t ], recursion); + addCurveIntersections(v1, v2, curve1, curve2, locations, + range1, [ t, range2[1] ], recursion); + break; + } + } + if (Math.abs(range1[1] - range1[0]) <= 0.00001 && + Math.abs(range2[1] - range2[0]) <= 0.00001) { + var t1 = (range1[0] + range1[1]) / 2, + t2 = (range2[0] + range2[1]) / 2; + addLocation(locations, + curve1, t1, Curve.evaluate(v1, t1, true, 0), + curve2, t2, Curve.evaluate(v2, t2, true, 0)); + break; + } + } + } + + function clipFatLine(v1, v2, range2) { + var p0x = v1[0], p0y = v1[1], p1x = v1[2], p1y = v1[3], + p2x = v1[4], p2y = v1[5], p3x = v1[6], p3y = v1[7], + q0x = v2[0], q0y = v2[1], q1x = v2[2], q1y = v2[3], + q2x = v2[4], q2y = v2[5], q3x = v2[6], q3y = v2[7], + getSignedDistance = Line.getSignedDistance, + d1 = getSignedDistance(p0x, p0y, p3x, p3y, p1x, p1y) || 0, + d2 = getSignedDistance(p0x, p0y, p3x, p3y, p2x, p2y) || 0, + factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9, + dmin = factor * Math.min(0, d1, d2), + dmax = factor * Math.max(0, d1, d2), + dq0 = getSignedDistance(p0x, p0y, p3x, p3y, q0x, q0y), + dq1 = getSignedDistance(p0x, p0y, p3x, p3y, q1x, q1y), + dq2 = getSignedDistance(p0x, p0y, p3x, p3y, q2x, q2y), + dq3 = getSignedDistance(p0x, p0y, p3x, p3y, q3x, q3y); + if (dmin > Math.max(dq0, dq1, dq2, dq3) + || dmax < Math.min(dq0, dq1, dq2, dq3)) + return 0; + var hull = getConvexHull(dq0, dq1, dq2, dq3), + swap; + if (dq3 < dq0) { + swap = dmin; + dmin = dmax; + dmax = swap; + } + var tmaxdmin = -Infinity, + tmin = Infinity, + tmax = -Infinity; + for (var i = 0, l = hull.length; i < l; i++) { + var p1 = hull[i], + p2 = hull[(i + 1) % l]; + if (p2[1] < p1[1]) { + swap = p2; + p2 = p1; + p1 = swap; + } + var x1 = p1[0], + y1 = p1[1], + x2 = p2[0], + y2 = p2[1]; + var inv = (y2 - y1) / (x2 - x1); + if (dmin >= y1 && dmin <= y2) { + var ixdx = x1 + (dmin - y1) / inv; + if (ixdx < tmin) + tmin = ixdx; + if (ixdx > tmaxdmin) + tmaxdmin = ixdx; + } + if (dmax >= y1 && dmax <= y2) { + var ixdx = x1 + (dmax - y1) / inv; + if (ixdx > tmax) + tmax = ixdx; + if (ixdx < tmin) + tmin = 0; + } + } + if (tmin !== Infinity && tmax !== -Infinity) { + var min = Math.min(dmin, dmax), + max = Math.max(dmin, dmax); + if (dq3 > min && dq3 < max) + tmax = 1; + if (dq0 > min && dq0 < max) + tmin = 0; + if (tmaxdmin > tmax) + tmax = 1; + var v2tmin = range2[0], + tdiff = range2[1] - v2tmin; + range2[0] = v2tmin + tmin * tdiff; + range2[1] = v2tmin + tmax * tdiff; + if ((tdiff - (range2[1] - range2[0])) / tdiff >= 0.2) + return 1; + } + if (Curve.getBounds(v1).touches(Curve.getBounds(v2))) + return -1; + return 0; + } + + function getConvexHull(dq0, dq1, dq2, dq3) { + var p0 = [ 0, dq0 ], + p1 = [ 1 / 3, dq1 ], + p2 = [ 2 / 3, dq2 ], + p3 = [ 1, dq3 ], + getSignedDistance = Line.getSignedDistance, + dist1 = getSignedDistance(0, dq0, 1, dq3, 1 / 3, dq1), + dist2 = getSignedDistance(0, dq0, 1, dq3, 2 / 3, dq2); + if (dist1 * dist2 < 0) { + return [ p0, p1, p3, p2 ]; + } + var pmax, cross; + if (Math.abs(dist1) > Math.abs(dist2)) { + pmax = p1; + cross = (dq3 - dq2 - (dq3 - dq0) / 3) + * (2 * (dq3 - dq2) - dq3 + dq1) / 3; + } else { + pmax = p2; + cross = (dq1 - dq0 + (dq0 - dq3) / 3) + * (-2 * (dq0 - dq1) + dq0 - dq2) / 3; + } + return cross < 0 + ? [ p0, pmax, p3 ] + : [ p0, p1, p2, p3 ]; + } + + function addCurveLineIntersections(v1, v2, curve1, curve2, locations) { + var flip = Curve.isLinear(v1), + vc = flip ? v2 : v1, + vl = flip ? v1 : v2, + l1x = vl[0], l1y = vl[1], + l2x = vl[6], l2y = vl[7], + lvx = l2x - l1x, + lvy = l2y - l1y, + angle = Math.atan2(-lvy, lvx), + sin = Math.sin(angle), + cos = Math.cos(angle), + rl2x = lvx * cos - lvy * sin, + vcr = []; + + for(var i = 0; i < 8; i += 2) { + var x = vc[i] - l1x, + y = vc[i + 1] - l1y; + vcr.push( + x * cos - y * sin, + y * cos + x * sin); + } + var roots = [], + count = Curve.solveCubic(vcr, 1, 0, roots); + for (var i = 0; i < count; i++) { + var t = roots[i]; + if (t >= 0 && t <= 1) { + var point = Curve.evaluate(vcr, t, true, 0); + if (point.x >= 0 && point.x <= rl2x) + addLocation(locations, + flip ? curve2 : curve1, + t, Curve.evaluate(vc, t, true, 0), + flip ? curve1 : curve2); + } + } + } + + function addLineIntersection(v1, v2, curve1, curve2, locations) { + var point = Line.intersect( + v1[0], v1[1], v1[6], v1[7], + v2[0], v2[1], v2[6], v2[7]); + if (point) + addLocation(locations, curve1, null, point, curve2); + } + + return { statics: { + getIntersections: function(v1, v2, curve1, curve2, locations) { + var linear1 = Curve.isLinear(v1), + linear2 = Curve.isLinear(v2); + (linear1 && linear2 + ? addLineIntersection + : linear1 || linear2 + ? addCurveLineIntersections + : addCurveIntersections)(v1, v2, curve1, curve2, locations); + return locations; + } + }}; +}); + +var CurveLocation = Base.extend({ + _class: 'CurveLocation', + initialize: function CurveLocation(curve, parameter, point, _curve2, + _parameter2, _point2, _distance) { + this._id = CurveLocation._id = (CurveLocation._id || 0) + 1; + this._curve = curve; + this._segment1 = curve._segment1; + this._segment2 = curve._segment2; + this._parameter = parameter; + this._point = point; + this._curve2 = _curve2; + this._parameter2 = _parameter2; + this._point2 = _point2; + this._distance = _distance; + }, + + getSegment: function() { + if (!this._segment) { + var curve = this.getCurve(), + parameter = this.getParameter(); + if (parameter === 1) { + this._segment = curve._segment2; + } else if (parameter === 0 || arguments[0]) { + this._segment = curve._segment1; + } else if (parameter == null) { + return null; + } else { + this._segment = curve.getLength(0, parameter) + < curve.getLength(parameter, 1) + ? curve._segment1 + : curve._segment2; + } + } + return this._segment; + }, + + getCurve: function() { + if (!this._curve || arguments[0]) { + this._curve = this._segment1.getCurve(); + if (this._curve.getParameterOf(this._point) == null) + this._curve = this._segment2.getPrevious().getCurve(); + } + return this._curve; + }, + + getIntersection: function() { + var intersection = this._intersection; + if (!intersection && this._curve2) { + var param = this._parameter2; + this._intersection = intersection = new CurveLocation( + this._curve2, param, this._point2 || this._point, this); + intersection._intersection = this; + } + return intersection; + }, + + getPath: function() { + var curve = this.getCurve(); + return curve && curve._path; + }, + + getIndex: function() { + var curve = this.getCurve(); + return curve && curve.getIndex(); + }, + + getOffset: function() { + var path = this.getPath(); + return path && path._getOffset(this); + }, + + getCurveOffset: function() { + var curve = this.getCurve(), + parameter = this.getParameter(); + return parameter != null && curve && curve.getLength(0, parameter); + }, + + getParameter: function() { + if ((this._parameter == null || arguments[0]) && this._point) { + var curve = this.getCurve(arguments[0] && this._point); + this._parameter = curve && curve.getParameterOf(this._point); + } + return this._parameter; + }, + + getPoint: function() { + if ((!this._point || arguments[0]) && this._parameter != null) { + var curve = this.getCurve(); + this._point = curve && curve.getPointAt(this._parameter, true); + } + return this._point; + }, + + getTangent: function() { + var parameter = this.getParameter(), + curve = this.getCurve(); + return parameter != null && curve && curve.getTangentAt(parameter, true); + }, + + getNormal: function() { + var parameter = this.getParameter(), + curve = this.getCurve(); + return parameter != null && curve && curve.getNormalAt(parameter, true); + }, + + getDistance: function() { + return this._distance; + }, + + divide: function() { + var curve = this.getCurve(true); + return curve && curve.divide(this.getParameter(true)); + }, + + split: function() { + var curve = this.getCurve(true); + return curve && curve.split(this.getParameter(true)); + }, + + toString: function() { + var parts = [], + point = this.getPoint(), + f = Formatter.instance; + if (point) + parts.push('point: ' + point); + var index = this.getIndex(); + if (index != null) + parts.push('index: ' + index); + var parameter = this.getParameter(); + if (parameter != null) + parts.push('parameter: ' + f.number(parameter)); + if (this._distance != null) + parts.push('distance: ' + f.number(this._distance)); + return '{ ' + parts.join(', ') + ' }'; + } +}); + +var PathItem = Item.extend({ + _class: 'PathItem', + + initialize: function PathItem() { + Item.apply(this, arguments); + }, + + getIntersections: function(path) { + if (!this.getBounds().touches(path.getBounds())) + return []; + var locations = [], + curves1 = this.getCurves(), + curves2 = path.getCurves(), + length2 = curves2.length, + values2 = []; + for (var i = 0; i < length2; i++) + values2[i] = curves2[i].getValues(); + for (var i = 0, l = curves1.length; i < l; i++) { + var curve1 = curves1[i], + values1 = curve1.getValues(); + for (var j = 0; j < length2; j++) + Curve.getIntersections(values1, values2[j], curve1, curves2[j], + locations); + } + return locations; + }, + + setPathData: function(data) { + + var parts = data.match(/[a-z][^a-z]*/ig), + coords, + relative = false, + control, + current = new Point(); + + function getCoord(index, coord, update) { + var val = parseFloat(coords[index]); + if (relative) + val += current[coord]; + if (update) + current[coord] = val; + return val; + } + + function getPoint(index, update) { + return new Point( + getCoord(index, 'x', update), + getCoord(index + 1, 'y', update) + ); + } + + if (this._type === 'path') + this.removeSegments(); + else + this.removeChildren(); + + for (var i = 0, l = parts.length; i < l; i++) { + var part = parts[i], + cmd = part[0], + lower = cmd.toLowerCase(); + coords = part.slice(1).trim().split(/[\s,]+|(?=[+-])/); + relative = cmd === lower; + var length = coords.length; + switch (lower) { + case 'm': + case 'l': + for (var j = 0; j < length; j += 2) + this[j === 0 && lower === 'm' ? 'moveTo' : 'lineTo']( + getPoint(j, true)); + break; + case 'h': + case 'v': + var coord = lower == 'h' ? 'x' : 'y'; + for (var j = 0; j < length; j++) { + getCoord(j, coord, true); + this.lineTo(current); + } + break; + case 'c': + for (var j = 0; j < length; j += 6) { + this.cubicCurveTo( + getPoint(j), + control = getPoint(j + 2), + getPoint(j + 4, true)); + } + break; + case 's': + for (var j = 0; j < length; j += 4) { + this.cubicCurveTo( + current.multiply(2).subtract(control), + control = getPoint(j), + getPoint(j + 2, true)); + } + break; + case 'q': + for (var j = 0; j < length; j += 4) { + this.quadraticCurveTo( + control = getPoint(j), + getPoint(j + 2, true)); + } + break; + case 't': + for (var j = 0; j < length; j += 2) { + this.quadraticCurveTo( + control = current.multiply(2).subtract(control), + getPoint(j, true)); + } + break; + case 'a': + break; + case 'z': + this.closePath(); + break; + } + } + }, + + _canComposite: function() { + return !(this.hasFill() && this.hasStroke()); + } + +}); + +var Path = PathItem.extend({ + _class: 'Path', + _serializeFields: { + segments: [], + closed: false + }, + + initialize: function Path(arg) { + this._closed = false; + this._segments = []; + Item.call(this); + var segments = Array.isArray(arg) + ? typeof arg[0] === 'object' + ? arg + : arguments + : arg && (arg.point !== undefined || arg.x !== undefined) + ? arguments + : null; + this.setSegments(segments || []); + if (arg && !segments) + this._set(arg); + }, + + clone: function() { + var copy = this._clone(new Path(this._segments)); + copy._closed = this._closed; + if (this._clockwise !== undefined) + copy._clockwise = this._clockwise; + return copy; + }, + + _changed: function(flags) { + Item.prototype._changed.call(this, flags); + if (flags & 4) { + delete this._length; + delete this._clockwise; + if (this._curves) { + for (var i = 0, l = this._curves.length; i < l; i++) { + this._curves[i]._changed(5); + } + } + } else if (flags & 8) { + delete this._bounds; + } + }, + + getSegments: function() { + return this._segments; + }, + + setSegments: function(segments) { + this._selectedSegmentState = 0; + this._segments.length = 0; + delete this._curves; + this._add(Segment.readAll(segments)); + }, + + getFirstSegment: function() { + return this._segments[0]; + }, + + getLastSegment: function() { + return this._segments[this._segments.length - 1]; + }, + + getCurves: function() { + var curves = this._curves, + segments = this._segments; + if (!curves) { + var length = this._countCurves(); + curves = this._curves = new Array(length); + for (var i = 0; i < length; i++) + curves[i] = new Curve(this, segments[i], + segments[i + 1] || segments[0]); + } + return curves; + }, + + getFirstCurve: function() { + return this.getCurves()[0]; + }, + + getLastCurve: function() { + var curves = this.getCurves(); + return curves[curves.length - 1]; + }, + + getPathData: function() { + var segments = this._segments, + precision = arguments[0], + f = Formatter.instance, + parts = []; + + function addCurve(seg1, seg2, skipLine) { + var point1 = seg1._point, + point2 = seg2._point, + handle1 = seg1._handleOut, + handle2 = seg2._handleIn; + if (handle1.isZero() && handle2.isZero()) { + if (!skipLine) { + parts.push('L' + f.point(point2, precision)); + } + } else { + var end = point2.subtract(point1); + parts.push('c' + f.point(handle1, precision) + + ' ' + f.point(end.add(handle2), precision) + + ' ' + f.point(end, precision)); + } + } + + if (segments.length === 0) + return ''; + parts.push('M' + f.point(segments[0]._point)); + for (var i = 0, l = segments.length - 1; i < l; i++) + addCurve(segments[i], segments[i + 1], false); + if (this._closed) { + addCurve(segments[segments.length - 1], segments[0], true); + parts.push('z'); + } + return parts.join(''); + }, + + isClosed: function() { + return this._closed; + }, + + setClosed: function(closed) { + if (this._closed != (closed = !!closed)) { + this._closed = closed; + if (this._curves) { + var length = this._curves.length = this._countCurves(); + if (closed) + this._curves[length - 1] = new Curve(this, + this._segments[length - 1], this._segments[0]); + } + this._changed(5); + } + }, + + isEmpty: function() { + return this._segments.length === 0; + }, + + isPolygon: function() { + for (var i = 0, l = this._segments.length; i < l; i++) { + if (!this._segments[i].isLinear()) + return false; + } + return true; + }, + + _applyMatrix: function(matrix) { + var coords = new Array(6); + for (var i = 0, l = this._segments.length; i < l; i++) + this._segments[i]._transformCoordinates(matrix, coords, true); + return true; + }, + + _add: function(segs, index) { + var segments = this._segments, + curves = this._curves, + amount = segs.length, + append = index == null, + index = append ? segments.length : index, + fullySelected = this.isFullySelected(); + for (var i = 0; i < amount; i++) { + var segment = segs[i]; + if (segment._path) + segment = segs[i] = segment.clone(); + segment._path = this; + segment._index = index + i; + if (fullySelected) + segment._selectionState = 4; + if (segment._selectionState) + this._updateSelection(segment, 0, segment._selectionState); + } + if (append) { + segments.push.apply(segments, segs); + } else { + segments.splice.apply(segments, [index, 0].concat(segs)); + for (var i = index + amount, l = segments.length; i < l; i++) + segments[i]._index = i; + } + if (curves || segs._curves) { + if (!curves) + curves = this._curves = []; + var from = index > 0 ? index - 1 : index, + start = from, + to = Math.min(from + amount, this._countCurves()); + if (segs._curves) { + curves.splice.apply(curves, [from, 0].concat(segs._curves)); + start += segs._curves.length; + } + for (var i = start; i < to; i++) + curves.splice(i, 0, new Curve(this, null, null)); + this._adjustCurves(from, to); + } + this._changed(5); + return segs; + }, + + _adjustCurves: function(from, to) { + var segments = this._segments, + curves = this._curves, + curve; + for (var i = from; i < to; i++) { + curve = curves[i]; + curve._path = this; + curve._segment1 = segments[i]; + curve._segment2 = segments[i + 1] || segments[0]; + } + if (curve = curves[this._closed && from === 0 ? segments.length - 1 + : from - 1]) + curve._segment2 = segments[from] || segments[0]; + if (curve = curves[to]) + curve._segment1 = segments[to]; + }, + + _countCurves: function() { + var length = this._segments.length; + return !this._closed && length > 0 ? length - 1 : length; + }, + + add: function(segment1 ) { + return arguments.length > 1 && typeof segment1 !== 'number' + ? this._add(Segment.readAll(arguments)) + : this._add([ Segment.read(arguments) ])[0]; + }, + + insert: function(index, segment1 ) { + return arguments.length > 2 && typeof segment1 !== 'number' + ? this._add(Segment.readAll(arguments, 1), index) + : this._add([ Segment.read(arguments, 1) ], index)[0]; + }, + + addSegment: function() { + return this._add([ Segment.read(arguments) ])[0]; + }, + + insertSegment: function(index ) { + return this._add([ Segment.read(arguments, 1) ], index)[0]; + }, + + addSegments: function(segments) { + return this._add(Segment.readAll(segments)); + }, + + insertSegments: function(index, segments) { + return this._add(Segment.readAll(segments), index); + }, + + removeSegment: function(index) { + return this.removeSegments(index, index + 1)[0] || null; + }, + + removeSegments: function(from, to) { + from = from || 0; + to = Base.pick(to, this._segments.length); + var segments = this._segments, + curves = this._curves, + count = segments.length, + removed = segments.splice(from, to - from), + amount = removed.length; + if (!amount) + return removed; + for (var i = 0; i < amount; i++) { + var segment = removed[i]; + if (segment._selectionState) + this._updateSelection(segment, segment._selectionState, 0); + delete segment._index; + delete segment._path; + } + for (var i = from, l = segments.length; i < l; i++) + segments[i]._index = i; + if (curves) { + var index = from > 0 && to === count + (this._closed ? 1 : 0) + ? from - 1 + : from, + curves = curves.splice(index, amount); + if (arguments[2]) + removed._curves = curves.slice(1); + this._adjustCurves(index, index); + } + this._changed(5); + return removed; + }, + + isFullySelected: function() { + return this._selected && this._selectedSegmentState + == this._segments.length * 4; + }, + + setFullySelected: function(selected) { + if (selected) + this._selectSegments(true); + this.setSelected(selected); + }, + + setSelected: function setSelected(selected) { + if (!selected) + this._selectSegments(false); + setSelected.base.call(this, selected); + }, + + _selectSegments: function(selected) { + var length = this._segments.length; + this._selectedSegmentState = selected + ? length * 4 : 0; + for (var i = 0; i < length; i++) + this._segments[i]._selectionState = selected + ? 4 : 0; + }, + + _updateSelection: function(segment, oldState, newState) { + segment._selectionState = newState; + var total = this._selectedSegmentState += newState - oldState; + if (total > 0) + this.setSelected(true); + }, + + flatten: function(maxDistance) { + var flattener = new PathFlattener(this), + pos = 0, + step = flattener.length / Math.ceil(flattener.length / maxDistance), + end = flattener.length + (this._closed ? -step : step) / 2; + var segments = []; + while (pos <= end) { + segments.push(new Segment(flattener.evaluate(pos, 0))); + pos += step; + } + this.setSegments(segments); + }, + + simplify: function(tolerance) { + if (this._segments.length > 2) { + var fitter = new PathFitter(this, tolerance || 2.5); + this.setSegments(fitter.fit()); + } + }, + + split: function(index, parameter) { + if (parameter === null) + return; + if (arguments.length == 1) { + var arg = index; + if (typeof arg === 'number') + arg = this.getLocationAt(arg); + index = arg.index; + parameter = arg.parameter; + } + if (parameter >= 1) { + index++; + parameter--; + } + var curves = this.getCurves(); + if (index >= 0 && index < curves.length) { + if (parameter > 0) { + curves[index++].divide(parameter); + } + var segs = this.removeSegments(index, this._segments.length, true), + path; + if (this._closed) { + this.setClosed(false); + path = this; + } else if (index > 0) { + path = this._clone(new Path().insertAbove(this, true)); + } + path._add(segs, 0); + this.addSegment(segs[0]); + return path; + } + return null; + }, + + isClockwise: function() { + if (this._clockwise !== undefined) + return this._clockwise; + return Path.isClockwise(this._segments); + }, + + setClockwise: function(clockwise) { + if (this.isClockwise() != (clockwise = !!clockwise)) + this.reverse(); + this._clockwise = clockwise; + }, + + reverse: function() { + this._segments.reverse(); + for (var i = 0, l = this._segments.length; i < l; i++) { + var segment = this._segments[i]; + var handleIn = segment._handleIn; + segment._handleIn = segment._handleOut; + segment._handleOut = handleIn; + segment._index = i; + } + delete this._curves; + if (this._clockwise !== undefined) + this._clockwise = !this._clockwise; + }, + + join: function(path) { + if (path) { + var segments = path._segments, + last1 = this.getLastSegment(), + last2 = path.getLastSegment(); + if (last1._point.equals(last2._point)) + path.reverse(); + var first2 = path.getFirstSegment(); + if (last1._point.equals(first2._point)) { + last1.setHandleOut(first2._handleOut); + this._add(segments.slice(1)); + } else { + var first1 = this.getFirstSegment(); + if (first1._point.equals(first2._point)) + path.reverse(); + last2 = path.getLastSegment(); + if (first1._point.equals(last2._point)) { + first1.setHandleIn(last2._handleIn); + this._add(segments.slice(0, segments.length - 1), 0); + } else { + this._add(segments.slice()); + } + } + path.remove(); + var first1 = this.getFirstSegment(); + last1 = this.getLastSegment(); + if (last1._point.equals(first1._point)) { + first1.setHandleIn(last1._handleIn); + last1.remove(); + this.setClosed(true); + } + this._changed(5); + return true; + } + return false; + }, + + reduce: function() { + return this; + }, + + getLength: function() { + if (this._length == null) { + var curves = this.getCurves(); + this._length = 0; + for (var i = 0, l = curves.length; i < l; i++) + this._length += curves[i].getLength(); + } + return this._length; + }, + + getArea: function() { + var curves = this.getCurves(); + var area = 0; + for (var i = 0, l = curves.length; i < l; i++) + area += curves[i].getArea(); + return area; + }, + + _getOffset: function(location) { + var index = location && location.getIndex(); + if (index != null) { + var curves = this.getCurves(), + offset = 0; + for (var i = 0; i < index; i++) + offset += curves[i].getLength(); + var curve = curves[index]; + return offset + curve.getLength(0, location.getParameter()); + } + return null; + }, + + getLocationOf: function(point) { + point = Point.read(arguments); + var curves = this.getCurves(); + for (var i = 0, l = curves.length; i < l; i++) { + var loc = curves[i].getLocationOf(point); + if (loc) + return loc; + } + return null; + }, + + getLocationAt: function(offset, isParameter) { + var curves = this.getCurves(), + length = 0; + if (isParameter) { + var index = ~~offset; + return curves[index].getLocationAt(offset - index, true); + } + for (var i = 0, l = curves.length; i < l; i++) { + var start = length, + curve = curves[i]; + length += curve.getLength(); + if (length >= offset) { + return curve.getLocationAt(offset - start); + } + } + if (offset <= this.getLength()) + return new CurveLocation(curves[curves.length - 1], 1); + return null; + }, + + getPointAt: function(offset, isParameter) { + var loc = this.getLocationAt(offset, isParameter); + return loc && loc.getPoint(); + }, + + getTangentAt: function(offset, isParameter) { + var loc = this.getLocationAt(offset, isParameter); + return loc && loc.getTangent(); + }, + + getNormalAt: function(offset, isParameter) { + var loc = this.getLocationAt(offset, isParameter); + return loc && loc.getNormal(); + }, + + getNearestLocation: function(point) { + point = Point.read(arguments); + var curves = this.getCurves(), + minDist = Infinity, + minLoc = null; + for (var i = 0, l = curves.length; i < l; i++) { + var loc = curves[i].getNearestLocation(point); + if (loc._distance < minDist) { + minDist = loc._distance; + minLoc = loc; + } + } + return minLoc; + }, + + getNearestPoint: function(point) { + point = Point.read(arguments); + return this.getNearestLocation(point).getPoint(); + }, + + getStyle: function() { + var parent = this._parent; + return (parent && parent._type === 'compound-path' + ? parent : this)._style; + }, + + _contains: function(point) { + var closed = this._closed; + if (!closed && !this.hasFill() + || !this._getBounds('getRoughBounds')._containsPoint(point)) + return false; + var curves = this.getCurves(), + segments = this._segments, + crossings = 0, + roots = new Array(3), + last = (closed + ? curves[curves.length - 1] + : new Curve(segments[segments.length - 1]._point, + segments[0]._point)).getValues(), + previous = last; + for (var i = 0, l = curves.length; i < l; i++) { + var vals = curves[i].getValues(), + x = vals[0], + y = vals[1]; + if (!(x === vals[2] && y === vals[3] && x === vals[4] + && y === vals[5] && x === vals[6] && y === vals[7])) { + crossings += Curve._getCrossings(vals, previous, + point.x, point.y, roots); + previous = vals; + } + } + if (!closed) { + crossings += Curve._getCrossings(last, previous, point.x, point.y, + roots); + } + return (crossings & 1) === 1; + }, + + _hitTest: function(point, options) { + var style = this.getStyle(), + segments = this._segments, + closed = this._closed, + tolerance = options.tolerance || 0, + radius = 0, join, cap, miterLimit, + that = this, + area, loc, res; + + if (options.stroke && style.getStrokeColor()) { + join = style.getStrokeJoin(); + cap = style.getStrokeCap(); + radius = style.getStrokeWidth() / 2 + tolerance; + miterLimit = radius * style.getMiterLimit(); + } + + function checkPoint(seg, pt, name) { + if (point.getDistance(pt) < tolerance) + return new HitResult(name, that, { segment: seg, point: pt }); + } + + function checkSegmentPoints(seg, ends) { + var pt = seg._point; + return (ends || options.segments) && checkPoint(seg, pt, 'segment') + || (!ends && options.handles) && ( + checkPoint(seg, pt.add(seg._handleIn), 'handle-in') || + checkPoint(seg, pt.add(seg._handleOut), 'handle-out')); + } + + function addAreaPoint(point) { + area.push(point); + } + + function getAreaCurve(index) { + var p1 = area[index], + p2 = area[(index + 1) % area.length]; + return [p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p2.x ,p2.y]; + } + + function isInArea(point) { + var length = area.length, + previous = getAreaCurve(length - 1), + roots = new Array(3), + crossings = 0; + for (var i = 0; i < length; i++) { + var curve = getAreaCurve(i); + crossings += Curve._getCrossings(curve, previous, + point.x, point.y, roots); + previous = curve; + } + return (crossings & 1) === 1; + } + + function checkSegmentStroke(segment) { + if (join !== 'round' || cap !== 'round') { + area = []; + if (closed || segment._index > 0 + && segment._index < segments.length - 1) { + if (join !== 'round' && (segment._handleIn.isZero() + || segment._handleOut.isZero())) + Path._addSquareJoin(segment, join, radius, miterLimit, + addAreaPoint, true); + } else if (cap !== 'round') { + Path._addSquareCap(segment, cap, radius, addAreaPoint, true); + } + if (area.length > 0) + return isInArea(point); + } + return point.getDistance(segment._point) <= radius; + } + + if (options.ends && !options.segments && !closed) { + if (res = checkSegmentPoints(segments[0], true) + || checkSegmentPoints(segments[segments.length - 1], true)) + return res; + } else if (options.segments || options.handles) { + for (var i = 0, l = segments.length; i < l; i++) { + if (res = checkSegmentPoints(segments[i])) + return res; + } + } + if (radius > 0) { + loc = this.getNearestLocation(point); + if (loc) { + var parameter = loc.getParameter(); + if (parameter === 0 || parameter === 1) { + if (!checkSegmentStroke(loc.getSegment())) + loc = null; + } else if (loc._distance > radius) { + loc = null; + } + } + if (!loc && join === 'miter') { + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + if (point.getDistance(segment._point) <= miterLimit + && checkSegmentStroke(segment)) { + loc = segment.getLocation(); + break; + } + } + } + } + return !loc && options.fill && this.hasFill() && this.contains(point) + ? new HitResult('fill', this) + : loc + ? new HitResult('stroke', this, { location: loc }) + : null; + } + +}, new function() { + + function drawHandles(ctx, segments, matrix, size) { + var half = size / 2; + + function drawHandle(index) { + var hX = coords[index], + hY = coords[index + 1]; + if (pX != hX || pY != hY) { + ctx.beginPath(); + ctx.moveTo(pX, pY); + ctx.lineTo(hX, hY); + ctx.stroke(); + ctx.beginPath(); + ctx.arc(hX, hY, half, 0, Math.PI * 2, true); + ctx.fill(); + } + } + + var coords = new Array(6); + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + segment._transformCoordinates(matrix, coords, false); + var state = segment._selectionState, + selected = state & 4, + pX = coords[0], + pY = coords[1]; + if (selected || (state & 1)) + drawHandle(2); + if (selected || (state & 2)) + drawHandle(4); + ctx.save(); + ctx.beginPath(); + ctx.rect(pX - half, pY - half, size, size); + ctx.fill(); + if (!selected) { + ctx.beginPath(); + ctx.rect(pX - half + 1, pY - half + 1, size - 2, size - 2); + ctx.fillStyle = '#ffffff'; + ctx.fill(); + } + ctx.restore(); + } + } + + function drawSegments(ctx, path, matrix) { + var segments = path._segments, + length = segments.length, + coords = new Array(6), + first = true, + curX, curY, + prevX, prevY, + inX, inY, + outX, outY; + + function drawSegment(i) { + var segment = segments[i]; + if (matrix) { + segment._transformCoordinates(matrix, coords, false); + curX = coords[0]; + curY = coords[1]; + } else { + var point = segment._point; + curX = point._x; + curY = point._y; + } + if (first) { + ctx.moveTo(curX, curY); + first = false; + } else { + if (matrix) { + inX = coords[2]; + inY = coords[3]; + } else { + var handle = segment._handleIn; + inX = curX + handle._x; + inY = curY + handle._y; + } + if (inX == curX && inY == curY && outX == prevX && outY == prevY) { + ctx.lineTo(curX, curY); + } else { + ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY); + } + } + prevX = curX; + prevY = curY; + if (matrix) { + outX = coords[4]; + outY = coords[5]; + } else { + var handle = segment._handleOut; + outX = prevX + handle._x; + outY = prevY + handle._y; + } + } + + for (var i = 0; i < length; i++) + drawSegment(i); + if (path._closed && length > 1) + drawSegment(0); + } + + return { + _draw: function(ctx, param) { + var clip = param.clip, + compound = param.compound; + if (!compound) + ctx.beginPath(); + + var style = this.getStyle(), + fillColor = style.getFillColor(), + strokeColor = style.getStrokeColor(), + dashArray = style.getDashArray(), + drawDash = !paper.support.nativeDash && strokeColor + && dashArray && dashArray.length; + + if (fillColor || strokeColor && !drawDash || compound || clip) + drawSegments(ctx, this); + + if (this._closed) + ctx.closePath(); + + if (!clip && !compound && (fillColor || strokeColor)) { + this._setStyles(ctx); + if (fillColor) + ctx.fill(); + if (strokeColor) { + if (drawDash) { + ctx.beginPath(); + var flattener = new PathFlattener(this), + from = style.getDashOffset(), to, + i = 0; + while (from < flattener.length) { + to = from + dashArray[(i++) % dashArray.length]; + flattener.drawPart(ctx, from, to); + from = to + dashArray[(i++) % dashArray.length]; + } + } + ctx.stroke(); + } + } + }, + + _drawSelected: function(ctx, matrix) { + ctx.beginPath(); + drawSegments(ctx, this, matrix); + ctx.stroke(); + drawHandles(ctx, this._segments, matrix, + this._project.options.handleSize || 4); + } + }; +}, new function() { + + function getFirstControlPoints(rhs) { + var n = rhs.length, + x = [], + tmp = [], + b = 2; + x[0] = rhs[0] / b; + for (var i = 1; i < n; i++) { + tmp[i] = 1 / b; + b = (i < n - 1 ? 4 : 2) - tmp[i]; + x[i] = (rhs[i] - x[i - 1]) / b; + } + for (var i = 1; i < n; i++) { + x[n - i - 1] -= tmp[n - i] * x[n - i]; + } + return x; + } + + return { + smooth: function() { + var segments = this._segments, + size = segments.length, + n = size, + overlap; + + if (size <= 2) + return; + + if (this._closed) { + overlap = Math.min(size, 4); + n += Math.min(size, overlap) * 2; + } else { + overlap = 0; + } + var knots = []; + for (var i = 0; i < size; i++) + knots[i + overlap] = segments[i]._point; + if (this._closed) { + for (var i = 0; i < overlap; i++) { + knots[i] = segments[i + size - overlap]._point; + knots[i + size + overlap] = segments[i]._point; + } + } else { + n--; + } + var rhs = []; + + for (var i = 1; i < n - 1; i++) + rhs[i] = 4 * knots[i]._x + 2 * knots[i + 1]._x; + rhs[0] = knots[0]._x + 2 * knots[1]._x; + rhs[n - 1] = 3 * knots[n - 1]._x; + var x = getFirstControlPoints(rhs); + + for (var i = 1; i < n - 1; i++) + rhs[i] = 4 * knots[i]._y + 2 * knots[i + 1]._y; + rhs[0] = knots[0]._y + 2 * knots[1]._y; + rhs[n - 1] = 3 * knots[n - 1]._y; + var y = getFirstControlPoints(rhs); + + if (this._closed) { + for (var i = 0, j = size; i < overlap; i++, j++) { + var f1 = i / overlap, + f2 = 1 - f1, + ie = i + overlap, + je = j + overlap; + x[j] = x[i] * f1 + x[j] * f2; + y[j] = y[i] * f1 + y[j] * f2; + x[je] = x[ie] * f2 + x[je] * f1; + y[je] = y[ie] * f2 + y[je] * f1; + } + n--; + } + var handleIn = null; + for (var i = overlap; i <= n - overlap; i++) { + var segment = segments[i - overlap]; + if (handleIn) + segment.setHandleIn(handleIn.subtract(segment._point)); + if (i < n) { + segment.setHandleOut( + new Point(x[i], y[i]).subtract(segment._point)); + if (i < n - 1) + handleIn = new Point( + 2 * knots[i + 1]._x - x[i + 1], + 2 * knots[i + 1]._y - y[i + 1]); + else + handleIn = new Point( + (knots[n]._x + x[n - 1]) / 2, + (knots[n]._y + y[n - 1]) / 2); + } + } + if (this._closed && handleIn) { + var segment = this._segments[0]; + segment.setHandleIn(handleIn.subtract(segment._point)); + } + } + }; +}, new function() { + function getCurrentSegment(that) { + var segments = that._segments; + if (segments.length == 0) + throw new Error('Use a moveTo() command first'); + return segments[segments.length - 1]; + } + + return { + moveTo: function() { + if (this._segments.length === 1) + this.removeSegment(0); + if (!this._segments.length) + this._add([ new Segment(Point.read(arguments)) ]); + }, + + moveBy: function() { + throw new Error('moveBy() is unsupported on Path items.'); + }, + + lineTo: function() { + this._add([ new Segment(Point.read(arguments)) ]); + }, + + cubicCurveTo: function() { + var handle1 = Point.read(arguments), + handle2 = Point.read(arguments), + to = Point.read(arguments); + var current = getCurrentSegment(this); + current.setHandleOut(handle1.subtract(current._point)); + this._add([ new Segment(to, handle2.subtract(to)) ]); + }, + + quadraticCurveTo: function() { + var handle = Point.read(arguments), + to = Point.read(arguments); + var current = getCurrentSegment(this)._point; + this.cubicCurveTo( + handle.add(current.subtract(handle).multiply(1 / 3)), + handle.add(to.subtract(handle).multiply(1 / 3)), + to + ); + }, + + curveTo: function() { + var through = Point.read(arguments), + to = Point.read(arguments), + t = Base.pick(Base.read(arguments), 0.5), + t1 = 1 - t, + current = getCurrentSegment(this)._point, + handle = through.subtract(current.multiply(t1 * t1)) + .subtract(to.multiply(t * t)).divide(2 * t * t1); + if (handle.isNaN()) + throw new Error( + 'Cannot put a curve through points with parameter = ' + t); + this.quadraticCurveTo(handle, to); + }, + + arcTo: function(to, clockwise ) { + var current = getCurrentSegment(this), + from = current._point, + through, + point = Point.read(arguments), + next = Base.pick(Base.peek(arguments), true); + if (typeof next === 'boolean') { + to = point; + clockwise = next; + var middle = from.add(to).divide(2), + through = middle.add(middle.subtract(from).rotate( + clockwise ? -90 : 90)); + } else { + through = point; + to = Point.read(arguments); + } + var l1 = new Line(from.add(through).divide(2), + through.subtract(from).rotate(90), true), + l2 = new Line(through.add(to).divide(2), + to.subtract(through).rotate(90), true), + center = l1.intersect(l2, true), + line = new Line(from, to), + throughSide = line.getSide(through); + if (!center) { + if (!throughSide) + return this.lineTo(to); + throw new Error("Cannot put an arc through the given points: " + + [from, through, to]); + } + var vector = from.subtract(center), + extent = vector.getDirectedAngle(to.subtract(center)), + centerSide = line.getSide(center); + if (centerSide == 0) { + extent = throughSide * Math.abs(extent); + } else if (throughSide == centerSide) { + extent -= 360 * (extent < 0 ? -1 : 1); + } + var ext = Math.abs(extent), + count = ext >= 360 ? 4 : Math.ceil(ext / 90), + inc = extent / count, + half = inc * Math.PI / 360, + z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)), + segments = []; + for (var i = 0; i <= count; i++) { + var pt = i < count ? center.add(vector) : to; + var out = i < count ? vector.rotate(90).multiply(z) : null; + if (i == 0) { + current.setHandleOut(out); + } else { + segments.push( + new Segment(pt, vector.rotate(-90).multiply(z), out)); + } + vector = vector.rotate(inc); + } + this._add(segments); + }, + + lineBy: function(vector) { + vector = Point.read(arguments); + var current = getCurrentSegment(this); + this.lineTo(current._point.add(vector)); + }, + + curveBy: function(throughVector, toVector, parameter) { + throughVector = Point.read(throughVector); + toVector = Point.read(toVector); + var current = getCurrentSegment(this)._point; + this.curveTo(current.add(throughVector), current.add(toVector), + parameter); + }, + + arcBy: function(throughVector, toVector) { + throughVector = Point.read(throughVector); + toVector = Point.read(toVector); + var current = getCurrentSegment(this)._point; + this.arcTo(current.add(throughVector), current.add(toVector)); + }, + + closePath: function() { + var first = this.getFirstSegment(), + last = this.getLastSegment(); + if (first._point.equals(last._point)) { + first.setHandleIn(last._handleIn); + last.remove(); + } + this.setClosed(true); + } + }; +}, { + + _getBounds: function(getter, matrix) { + return Path[getter](this._segments, this._closed, this.getStyle(), + matrix); + }, + +statics: { + isClockwise: function(segments) { + var sum = 0, + xPre, yPre, + add = false; + function edge(x, y) { + if (add) + sum += (xPre - x) * (y + yPre); + xPre = x; + yPre = y; + add = true; + } + for (var i = 0, l = segments.length; i < l; i++) { + var seg1 = segments[i], + seg2 = segments[i + 1 < l ? i + 1 : 0], + point1 = seg1._point, + handle1 = seg1._handleOut, + handle2 = seg2._handleIn, + point2 = seg2._point; + edge(point1._x, point1._y); + edge(point1._x + handle1._x, point1._y + handle1._y); + edge(point2._x + handle2._x, point2._y + handle2._y); + edge(point2._x, point2._y); + } + return sum > 0; + }, + + getBounds: function(segments, closed, style, matrix, strokePadding) { + var first = segments[0]; + if (!first) + return new Rectangle(); + var coords = new Array(6), + prevCoords = first._transformCoordinates(matrix, new Array(6), false), + min = prevCoords.slice(0, 2), + max = min.slice(), + roots = new Array(2); + + function processSegment(segment) { + segment._transformCoordinates(matrix, coords, false); + for (var i = 0; i < 2; i++) { + Curve._addBounds( + prevCoords[i], + prevCoords[i + 4], + coords[i + 2], + coords[i], + i, strokePadding ? strokePadding[i] : 0, min, max, roots); + } + var tmp = prevCoords; + prevCoords = coords; + coords = tmp; + } + + for (var i = 1, l = segments.length; i < l; i++) + processSegment(segments[i]); + if (closed) + processSegment(first); + return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]); + }, + + getStrokeBounds: function(segments, closed, style, matrix) { + function getPenPadding(radius, matrix) { + if (!matrix) + return [radius, radius]; + var mx = matrix.shiftless(), + hor = mx.transform(new Point(radius, 0)), + ver = mx.transform(new Point(0, radius)), + phi = hor.getAngleInRadians(), + a = hor.getLength(), + b = ver.getLength(); + var sin = Math.sin(phi), + cos = Math.cos(phi), + tan = Math.tan(phi), + tx = -Math.atan(b * tan / a), + ty = Math.atan(b / (tan * a)); + return [Math.abs(a * Math.cos(tx) * cos - b * Math.sin(tx) * sin), + Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)]; + } + + if (!style.getStrokeColor() || !style.getStrokeWidth()) + return Path.getBounds(segments, closed, style, matrix); + var length = segments.length - (closed ? 0 : 1), + radius = style.getStrokeWidth() / 2, + padding = getPenPadding(radius, matrix), + bounds = Path.getBounds(segments, closed, style, matrix, padding), + join = style.getStrokeJoin(), + cap = style.getStrokeCap(), + miterLimit = radius * style.getMiterLimit(); + var joinBounds = new Rectangle(new Size(padding).multiply(2)); + + function add(point) { + bounds = bounds.include(matrix + ? matrix._transformPoint(point, point) : point); + } + + function addJoin(segment, join) { + if (join === 'round' || !segment._handleIn.isZero() + && !segment._handleOut.isZero()) { + bounds = bounds.unite(joinBounds.setCenter(matrix + ? matrix._transformPoint(segment._point) : segment._point)); + } else { + Path._addSquareJoin(segment, join, radius, miterLimit, add); + } + } + + function addCap(segment, cap) { + switch (cap) { + case 'round': + addJoin(segment, cap); + break; + case 'butt': + case 'square': + Path._addSquareCap(segment, cap, radius, add); + break; + } + } + + for (var i = 1; i < length; i++) + addJoin(segments[i], join); + if (closed) { + addJoin(segments[0], join); + } else { + addCap(segments[0], cap); + addCap(segments[segments.length - 1], cap); + } + return bounds; + }, + + _addSquareJoin: function(segment, join, radius, miterLimit, addPoint, area) { + var curve2 = segment.getCurve(), + curve1 = curve2.getPrevious(), + point = curve2.getPointAt(0, true), + normal1 = curve1.getNormalAt(1, true), + normal2 = curve2.getNormalAt(0, true), + step = normal1.getDirectedAngle(normal2) < 0 ? -radius : radius; + normal1.setLength(step); + normal2.setLength(step); + if (area) { + addPoint(point); + addPoint(point.add(normal1)); + } + if (join === 'miter') { + var corner = new Line( + point.add(normal1), + new Point(-normal1.y, normal1.x), true + ).intersect(new Line( + point.add(normal2), + new Point(-normal2.y, normal2.x), true + ), true); + if (corner && point.getDistance(corner) <= miterLimit) { + addPoint(corner); + if (!area) + return; + } + } + if (!area) + addPoint(point.add(normal1)); + addPoint(point.add(normal2)); + }, + + _addSquareCap: function(segment, cap, radius, addPoint, area) { + var point = segment._point, + loc = segment.getLocation(), + normal = loc.getNormal().normalize(radius); + if (area) { + addPoint(point.subtract(normal)); + addPoint(point.add(normal)); + } + if (cap === 'square') + point = point.add(normal.rotate(loc.getParameter() == 0 ? -90 : 90)); + addPoint(point.add(normal)); + addPoint(point.subtract(normal)); + }, + + getHandleBounds: function(segments, closed, style, matrix, strokePadding, + joinPadding) { + var coords = new Array(6), + x1 = Infinity, + x2 = -x1, + y1 = x1, + y2 = x2; + strokePadding = strokePadding / 2 || 0; + joinPadding = joinPadding / 2 || 0; + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + segment._transformCoordinates(matrix, coords, false); + for (var j = 0; j < 6; j += 2) { + var padding = j == 0 ? joinPadding : strokePadding, + x = coords[j], + y = coords[j + 1], + xn = x - padding, + xx = x + padding, + yn = y - padding, + yx = y + padding; + if (xn < x1) x1 = xn; + if (xx > x2) x2 = xx; + if (yn < y1) y1 = yn; + if (yx > y2) y2 = yx; + } + } + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + getRoughBounds: function(segments, closed, style, matrix) { + var strokeWidth = style.getStrokeColor() ? style.getStrokeWidth() : 0, + joinWidth = strokeWidth; + if (strokeWidth > 0) { + if (style.getStrokeJoin() === 'miter') + joinWidth = strokeWidth * style.getMiterLimit(); + if (style.getStrokeCap() === 'square') + joinWidth = Math.max(joinWidth, strokeWidth * Math.sqrt(2)); + } + return Path.getHandleBounds(segments, closed, style, matrix, + strokeWidth, joinWidth); + } +}}); + +Path.inject({ statics: new function() { + + function createPath(args) { + var path = new Path(), + named = Base.getNamed(args); + if (named) + path._set(named); + return path; + } + + function createRectangle() { + var rect = Rectangle.readNamed(arguments, 'rectangle'), + radius = Size.readNamed(arguments, 'radius', 0, 0, true), + bl = rect.getBottomLeft(true), + tl = rect.getTopLeft(true), + tr = rect.getTopRight(true), + br = rect.getBottomRight(true), + path = createPath(arguments); + if (!radius || radius.isZero()) { + path._add([ + new Segment(bl), + new Segment(tl), + new Segment(tr), + new Segment(br) + ]); + } else { + radius = Size.min(radius, rect.getSize(true).divide(2)); + var h = radius.multiply(kappa * 2); + path._add([ + new Segment(bl.add(radius.width, 0), null, [-h.width, 0]), + new Segment(bl.subtract(0, radius.height), [0, h.height], null), + + new Segment(tl.add(0, radius.height), null, [0, -h.height]), + new Segment(tl.add(radius.width, 0), [-h.width, 0], null), + + new Segment(tr.subtract(radius.width, 0), null, [h.width, 0]), + new Segment(tr.add(0, radius.height), [0, -h.height], null), + + new Segment(br.subtract(0, radius.height), null, [0, h.height]), + new Segment(br.subtract(radius.width, 0), [h.width, 0], null) + ]); + } + path._closed = true; + return path; + } + + var kappa = Numerical.KAPPA / 2; + + var ellipseSegments = [ + new Segment([0, 0.5], [0, kappa ], [0, -kappa]), + new Segment([0.5, 0], [-kappa, 0], [kappa, 0 ]), + new Segment([1, 0.5], [0, -kappa], [0, kappa ]), + new Segment([0.5, 1], [kappa, 0 ], [-kappa, 0]) + ]; + + function createEllipse() { + var rect = Rectangle.readNamed(arguments, 'rectangle'), + path = createPath(arguments), + point = rect.getPoint(true), + size = rect.getSize(true), + segments = new Array(4); + for (var i = 0; i < 4; i++) { + var segment = ellipseSegments[i]; + segments[i] = new Segment( + segment._point.multiply(size).add(point), + segment._handleIn.multiply(size), + segment._handleOut.multiply(size) + ); + } + path._add(segments); + path._closed = true; + return path; + } + + return { + Line: function() { + return new Path( + Point.readNamed(arguments, 'from'), + Point.readNamed(arguments, 'to') + ).set(Base.getNamed(arguments)); + }, + + Rectangle: createRectangle, + + RoundRectangle: createRectangle, + + Ellipse: createEllipse, + + Oval: createEllipse, + + Circle: function() { + var center = Point.readNamed(arguments, 'center'), + radius = Base.readNamed(arguments, 'radius'); + return createEllipse(new Rectangle(center.subtract(radius), + new Size(radius * 2, radius * 2))) + .set(Base.getNamed(arguments)); + }, + + Arc: function() { + var from = Point.readNamed(arguments, 'from'), + through = Point.readNamed(arguments, 'through'), + to = Point.readNamed(arguments, 'to'), + path = createPath(arguments); + path.moveTo(from); + path.arcTo(through, to); + return path; + }, + + RegularPolygon: function() { + var center = Point.readNamed(arguments, 'center'), + sides = Base.readNamed(arguments, 'sides'), + radius = Base.readNamed(arguments, 'radius'), + path = createPath(arguments), + step = 360 / sides, + three = !(sides % 3), + vector = new Point(0, three ? -radius : radius), + offset = three ? -1 : 0.5, + segments = new Array(sides); + for (var i = 0; i < sides; i++) { + segments[i] = new Segment(center.add( + vector.rotate((i + offset) * step))); + } + path._add(segments); + path._closed = true; + return path; + }, + + Star: function() { + var center = Point.readNamed(arguments, 'center'), + points = Base.readNamed(arguments, 'points') * 2, + radius1 = Base.readNamed(arguments, 'radius1'), + radius2 = Base.readNamed(arguments, 'radius2'), + path = createPath(arguments), + step = 360 / points, + vector = new Point(0, -1), + segments = new Array(points); + for (var i = 0; i < points; i++) { + segments[i] = new Segment(center.add( + vector.rotate(step * i).multiply(i % 2 ? radius2 : radius1))); + } + path._add(segments); + path._closed = true; + return path; + } + }; +}}); + +var CompoundPath = PathItem.extend({ + _class: 'CompoundPath', + _serializeFields: { + children: [] + }, + + initialize: function CompoundPath(arg) { + PathItem.call(this); + this._children = []; + this._namedChildren = {}; + if (arg && !this._set(arg)) + this.addChildren(Array.isArray(arg) ? arg : arguments); + }, + + insertChildren: function insertChildren(index, items, _preserve) { + items = insertChildren.base.call(this, index, items, _preserve, 'path'); + for (var i = 0, l = !_preserve && items && items.length; i < l; i++) { + var item = items[i]; + if (item._clockwise === undefined) + item.setClockwise(item._index === 0); + } + return items; + }, + + reduce: function() { + if (this._children.length == 1) { + var child = this._children[0]; + child.insertAbove(this); + this.remove(); + return child; + } + return this; + }, + + reverse: function() { + var children = this._children; + for (var i = 0, l = children.length; i < l; i++) + children[i].reverse(); + }, + + smooth: function() { + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i].smooth(); + }, + + isClockwise: function() { + var child = this.getFirstChild(); + return child && child.isClockwise(); + }, + + setClockwise: function(clockwise) { + if (this.isClockwise() != !!clockwise) + this.reverse(); + }, + + getFirstSegment: function() { + var first = this.getFirstChild(); + return first && first.getFirstSegment(); + }, + + getLastSegment: function() { + var last = this.getLastChild(); + return last && last.getLastSegment(); + }, + + getCurves: function() { + var children = this._children, + curves = []; + for (var i = 0, l = children.length; i < l; i++) + curves = curves.concat(children[i].getCurves()); + return curves; + }, + + getFirstCurve: function() { + var first = this.getFirstChild(); + return first && first.getFirstCurve(); + }, + + getLastCurve: function() { + var last = this.getLastChild(); + return last && last.getFirstCurve(); + }, + + getArea: function() { + var children = this._children, + area = 0; + for (var i = 0, l = children.length; i < l; i++) + area += children[i].getArea(); + return area; + }, + + getPathData: function() { + var children = this._children, + paths = []; + for (var i = 0, l = children.length; i < l; i++) + paths.push(children[i].getPathData(arguments[0])); + return paths.join(' '); + }, + + _contains: function(point) { + var children = []; + for (var i = 0, l = this._children.length; i < l; i++) { + var child = this._children[i]; + if (child.contains(point)) + children.push(child); + } + return (children.length & 1) == 1 && children; + }, + + _hitTest: function _hitTest(point, options) { + var res = _hitTest.base.call(this, point, + Base.merge(options, { fill: false })); + if (!res && options.fill && this.hasFill()) { + res = this._contains(point); + res = res ? new HitResult('fill', res[0]) : null; + } + return res; + }, + + _draw: function(ctx, param) { + var children = this._children, + style = this._style; + if (children.length === 0) + return; + ctx.beginPath(); + param = param.extend({ compound: true }); + for (var i = 0, l = children.length; i < l; i++) + children[i].draw(ctx, param); + if (!param.clip) { + this._setStyles(ctx); + if (style.getFillColor()) + ctx.fill(); + if (style.getStrokeColor()) + ctx.stroke(); + } + } +}, new function() { + function getCurrentPath(that) { + if (!that._children.length) + throw new Error('Use a moveTo() command first'); + return that._children[that._children.length - 1]; + } + + var fields = { + moveTo: function() { + var path = new Path(); + this.addChild(path); + path.moveTo.apply(path, arguments); + }, + + moveBy: function() { + this.moveTo(getCurrentPath(this).getLastSegment()._point.add( + Point.read(arguments))); + }, + + closePath: function() { + getCurrentPath(this).closePath(); + } + }; + + Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', + 'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) { + fields[key] = function() { + var path = getCurrentPath(this); + path[key].apply(path, arguments); + }; + }); + + return fields; +}); + +var PathFlattener = Base.extend({ + initialize: function(path) { + this.curves = []; + this.parts = []; + this.length = 0; + this.index = 0; + + var segments = path._segments, + segment1 = segments[0], + segment2, + that = this; + + function addCurve(segment1, segment2) { + var curve = Curve.getValues(segment1, segment2); + that.curves.push(curve); + that._computeParts(curve, segment1._index, 0, 1); + } + + for (var i = 1, l = segments.length; i < l; i++) { + segment2 = segments[i]; + addCurve(segment1, segment2); + segment1 = segment2; + } + if (path._closed) + addCurve(segment2, segments[0]); + }, + + _computeParts: function(curve, index, minT, maxT) { + if ((maxT - minT) > 1 / 32 && !Curve.isFlatEnough(curve, 0.25)) { + var curves = Curve.subdivide(curve); + var halfT = (minT + maxT) / 2; + this._computeParts(curves[0], index, minT, halfT); + this._computeParts(curves[1], index, halfT, maxT); + } else { + var x = curve[6] - curve[0], + y = curve[7] - curve[1], + dist = Math.sqrt(x * x + y * y); + if (dist > 0.00001) { + this.length += dist; + this.parts.push({ + offset: this.length, + value: maxT, + index: index + }); + } + } + }, + + getParameterAt: function(offset) { + var i, j = this.index; + for (;;) { + i = j; + if (j == 0 || this.parts[--j].offset < offset) + break; + } + for (var l = this.parts.length; i < l; i++) { + var part = this.parts[i]; + if (part.offset >= offset) { + this.index = i; + var prev = this.parts[i - 1]; + var prevVal = prev && prev.index == part.index ? prev.value : 0, + prevLen = prev ? prev.offset : 0; + return { + value: prevVal + (part.value - prevVal) + * (offset - prevLen) / (part.offset - prevLen), + index: part.index + }; + } + } + var part = this.parts[this.parts.length - 1]; + return { + value: 1, + index: part.index + }; + }, + + evaluate: function(offset, type) { + var param = this.getParameterAt(offset); + return Curve.evaluate(this.curves[param.index], param.value, true, type); + }, + + drawPart: function(ctx, from, to) { + from = this.getParameterAt(from); + to = this.getParameterAt(to); + for (var i = from.index; i <= to.index; i++) { + var curve = Curve.getPart(this.curves[i], + i == from.index ? from.value : 0, + i == to.index ? to.value : 1); + if (i == from.index) + ctx.moveTo(curve[0], curve[1]); + ctx.bezierCurveTo.apply(ctx, curve.slice(2)); + } + } +}); + +var PathFitter = Base.extend({ + initialize: function(path, error) { + this.points = []; + var segments = path._segments, + prev; + for (var i = 0, l = segments.length; i < l; i++) { + var point = segments[i].point.clone(); + if (!prev || !prev.equals(point)) { + this.points.push(point); + prev = point; + } + } + this.error = error; + }, + + fit: function() { + var points = this.points, + length = points.length; + this.segments = length > 0 ? [new Segment(points[0])] : []; + if (length > 1) + this.fitCubic(0, length - 1, + points[1].subtract(points[0]).normalize(), + points[length - 2].subtract(points[length - 1]).normalize()); + return this.segments; + }, + + fitCubic: function(first, last, tan1, tan2) { + if (last - first == 1) { + var pt1 = this.points[first], + pt2 = this.points[last], + dist = pt1.getDistance(pt2) / 3; + this.addCurve([pt1, pt1.add(tan1.normalize(dist)), + pt2.add(tan2.normalize(dist)), pt2]); + return; + } + var uPrime = this.chordLengthParameterize(first, last), + maxError = Math.max(this.error, this.error * this.error), + split; + for (var i = 0; i <= 4; i++) { + var curve = this.generateBezier(first, last, uPrime, tan1, tan2); + var max = this.findMaxError(first, last, curve, uPrime); + if (max.error < this.error) { + this.addCurve(curve); + return; + } + split = max.index; + if (max.error >= maxError) + break; + this.reparameterize(first, last, uPrime, curve); + maxError = max.error; + } + var V1 = this.points[split - 1].subtract(this.points[split]), + V2 = this.points[split].subtract(this.points[split + 1]), + tanCenter = V1.add(V2).divide(2).normalize(); + this.fitCubic(first, split, tan1, tanCenter); + this.fitCubic(split, last, tanCenter.negate(), tan2); + }, + + addCurve: function(curve) { + var prev = this.segments[this.segments.length - 1]; + prev.setHandleOut(curve[1].subtract(curve[0])); + this.segments.push( + new Segment(curve[3], curve[2].subtract(curve[3]))); + }, + + generateBezier: function(first, last, uPrime, tan1, tan2) { + var epsilon = 1e-11, + pt1 = this.points[first], + pt2 = this.points[last], + C = [[0, 0], [0, 0]], + X = [0, 0]; + + for (var i = 0, l = last - first + 1; i < l; i++) { + var u = uPrime[i], + t = 1 - u, + b = 3 * u * t, + b0 = t * t * t, + b1 = b * t, + b2 = b * u, + b3 = u * u * u, + a1 = tan1.normalize(b1), + a2 = tan2.normalize(b2), + tmp = this.points[first + i] + .subtract(pt1.multiply(b0 + b1)) + .subtract(pt2.multiply(b2 + b3)); + C[0][0] += a1.dot(a1); + C[0][1] += a1.dot(a2); + C[1][0] = C[0][1]; + C[1][1] += a2.dot(a2); + X[0] += a1.dot(tmp); + X[1] += a2.dot(tmp); + } + + var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1], + alpha1, alpha2; + if (Math.abs(detC0C1) > epsilon) { + var detC0X = C[0][0] * X[1] - C[1][0] * X[0], + detXC1 = X[0] * C[1][1] - X[1] * C[0][1]; + alpha1 = detXC1 / detC0C1; + alpha2 = detC0X / detC0C1; + } else { + var c0 = C[0][0] + C[0][1], + c1 = C[1][0] + C[1][1]; + if (Math.abs(c0) > epsilon) { + alpha1 = alpha2 = X[0] / c0; + } else if (Math.abs(c1) > epsilon) { + alpha1 = alpha2 = X[1] / c1; + } else { + alpha1 = alpha2 = 0; + } + } + + var segLength = pt2.getDistance(pt1); + epsilon *= segLength; + if (alpha1 < epsilon || alpha2 < epsilon) { + alpha1 = alpha2 = segLength / 3; + } + + return [pt1, pt1.add(tan1.normalize(alpha1)), + pt2.add(tan2.normalize(alpha2)), pt2]; + }, + + reparameterize: function(first, last, u, curve) { + for (var i = first; i <= last; i++) { + u[i - first] = this.findRoot(curve, this.points[i], u[i - first]); + } + }, + + findRoot: function(curve, point, u) { + var curve1 = [], + curve2 = []; + for (var i = 0; i <= 2; i++) { + curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3); + } + for (var i = 0; i <= 1; i++) { + curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2); + } + var pt = this.evaluate(3, curve, u), + pt1 = this.evaluate(2, curve1, u), + pt2 = this.evaluate(1, curve2, u), + diff = pt.subtract(point), + df = pt1.dot(pt1) + diff.dot(pt2); + if (Math.abs(df) < 0.00001) + return u; + return u - diff.dot(pt1) / df; + }, + + evaluate: function(degree, curve, t) { + var tmp = curve.slice(); + for (var i = 1; i <= degree; i++) { + for (var j = 0; j <= degree - i; j++) { + tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t)); + } + } + return tmp[0]; + }, + + chordLengthParameterize: function(first, last) { + var u = [0]; + for (var i = first + 1; i <= last; i++) { + u[i - first] = u[i - first - 1] + + this.points[i].getDistance(this.points[i - 1]); + } + for (var i = 1, m = last - first; i <= m; i++) { + u[i] /= u[m]; + } + return u; + }, + + findMaxError: function(first, last, curve, u) { + var index = Math.floor((last - first + 1) / 2), + maxDist = 0; + for (var i = first + 1; i < last; i++) { + var P = this.evaluate(3, curve, u[i - first]); + var v = P.subtract(this.points[i]); + var dist = v.x * v.x + v.y * v.y; + if (dist >= maxDist) { + maxDist = dist; + index = i; + } + } + return { + error: maxDist, + index: index + }; + } +}); + +PathItem.inject(new function() { + + function splitPath(intersections, collectOthers) { + intersections.sort(function(loc1, loc2) { + var path1 = loc1.getPath(), + path2 = loc2.getPath(); + return path1 === path2 + ? (loc1.getIndex() + loc1.getParameter()) + - (loc2.getIndex() + loc2.getParameter()) + : path1._id - path2._id; + }); + var others = collectOthers && []; + for (var i = intersections.length - 1; i >= 0; i--) { + var loc = intersections[i], + other = loc.getIntersection(), + curve = loc.divide(), + segment = curve && curve.getSegment1() || loc.getSegment(); + if (others) + others.push(other); + segment._intersection = other; + } + return others; + } + + function reorientPath(path) { + if (path instanceof CompoundPath) { + var children = path._children, + length = children.length, + bounds = new Array(length), + counters = new Array(length), + clockwise = children[0].isClockwise(); + for (var i = 0; i < length; i++) { + bounds[i] = children[i].getBounds(); + counters[i] = 0; + } + for (var i = 0; i < length; i++) { + for (var j = 1; j < length; j++) { + if (i !== j && bounds[i].contains(bounds[j])) + counters[j]++; + } + if (i > 0 && counters[i] % 2 === 0) + children[i].setClockwise(clockwise); + } + } + return path; + } + + function computeBoolean(path1, path2, operator, subtract) { + path1 = reorientPath(path1.clone()); + path2 = reorientPath(path2.clone()); + var path1Clockwise = path1.isClockwise(), + path2Clockwise = path2.isClockwise(), + intersections = path1.getIntersections(path2); + splitPath(splitPath(intersections, true)); + if (subtract) { + path2.reverse(); + path2Clockwise = !path2Clockwise; + } + var paths = [] + .concat(path1._children || [path1]) + .concat(path2._children || [path2]), + segments = [], + result = new CompoundPath(); + for (var i = 0, l = paths.length; i < l; i++) { + var path = paths[i], + parent = path._parent, + clockwise = path.isClockwise(), + segs = path._segments; + path = parent instanceof CompoundPath ? parent : path; + for (var j = segs.length - 1; j >= 0; j--) { + var segment = segs[j], + midPoint = segment.getCurve().getPoint(0.5), + insidePath1 = path !== path1 && path1.contains(midPoint) + && (clockwise === path1Clockwise || subtract + || !testOnCurve(path1, midPoint)), + insidePath2 = path !== path2 && path2.contains(midPoint) + && (clockwise === path2Clockwise + || !testOnCurve(path2, midPoint)); + if (operator(path === path1, insidePath1, insidePath2)) { + segment._invalid = true; + } else { + segments.push(segment); + } + } + } + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + if (segment._visited) + continue; + var path = new Path(), + loc = segment._intersection, + intersection = loc && loc.getSegment(true); + if (segment.getPrevious()._invalid) + segment.setHandleIn(intersection + ? intersection._handleIn + : new Point(0, 0)); + do { + segment._visited = true; + if (segment._invalid && segment._intersection) { + var inter = segment._intersection.getSegment(true); + path.add(new Segment(segment._point, segment._handleIn, + inter._handleOut)); + inter._visited = true; + segment = inter; + } else { + path.add(segment.clone()); + } + segment = segment.getNext(); + } while (segment && !segment._visited && segment !== intersection); + var amount = path._segments.length; + if (amount > 1 && (amount > 2 || !path.isPolygon())) { + path.setClosed(true); + result.addChild(path, true); + } else { + path.remove(); + } + } + path1.remove(); + path2.remove(); + return result.reduce(); + } + + function testOnCurve(path, point) { + var curves = path.getCurves(), + bounds = path.getBounds(); + if (bounds.contains(point)) { + for (var i = 0, l = curves.length; i < l; i++) { + var curve = curves[i]; + if (curve.getBounds().contains(point) + && curve.getParameterOf(point)) + return true; + } + } + return false; + } + + return { + unite: function(path) { + return computeBoolean(this, path, + function(isPath1, isInPath1, isInPath2) { + return isInPath1 || isInPath2; + }); + }, + + intersect: function(path) { + return computeBoolean(this, path, + function(isPath1, isInPath1, isInPath2) { + return !(isInPath1 || isInPath2); + }); + }, + + subtract: function(path) { + return computeBoolean(this, path, + function(isPath1, isInPath1, isInPath2) { + return isPath1 && isInPath2 || !isPath1 && !isInPath1; + }, true); + }, + + exclude: function(path) { + return new Group([this.subtract(path), path.subtract(this)]); + }, + + divide: function(path) { + return new Group([this.subtract(path), this.intersect(path)]); + } + }; +}); + +var TextItem = Item.extend({ + _class: 'TextItem', + _boundsSelected: true, + _serializeFields: { + content: null + }, + _boundsGetter: 'getBounds', + + initialize: function TextItem(arg) { + var hasProperties = arg && Base.isPlainObject(arg) + && arg.x === undefined && arg.y === undefined; + Item.call(this, hasProperties ? null : Point.read(arguments)); + this._content = ''; + this._lines = []; + if (hasProperties) + this._set(arg); + }, + + _clone: function _clone(copy) { + copy.setContent(this._content); + return _clone.base.call(this, copy); + }, + + getContent: function() { + return this._content; + }, + + setContent: function(content) { + this._content = '' + content; + this._lines = this._content.split(/\r\n|\n|\r/mg); + this._changed(69); + }, + + isEmpty: function() { + return !this._content; + }, + + getCharacterStyle: '#getStyle', + setCharacterStyle: '#setStyle', + + getParagraphStyle: '#getStyle', + setParagraphStyle: '#setStyle' +}); + +var PointText = TextItem.extend({ + _class: 'PointText', + + initialize: function PointText() { + TextItem.apply(this, arguments); + }, + + clone: function() { + return this._clone(new PointText()); + }, + + getPoint: function() { + var point = this._matrix.getTranslation(); + return new LinkedPoint(point.x, point.y, this, 'setPoint'); + }, + + setPoint: function(point) { + point = Point.read(arguments); + this.translate(point.subtract(this._matrix.getTranslation())); + }, + + _draw: function(ctx) { + if (!this._content) + return; + this._setStyles(ctx); + var style = this._style, + lines = this._lines, + leading = style.getLeading(); + ctx.font = style.getFontStyle(); + ctx.textAlign = style.getJustification(); + for (var i = 0, l = lines.length; i < l; i++) { + var line = lines[i]; + if (style.getFillColor()) + ctx.fillText(line, 0, 0); + if (style.getStrokeColor()) + ctx.strokeText(line, 0, 0); + ctx.translate(0, leading); + } + } +}, new function() { + var measureCtx = null; + + return { + _getBounds: function(getter, matrix) { + if (!measureCtx) + measureCtx = CanvasProvider.getContext(1, 1); + var style = this._style, + lines = this._lines, + count = lines.length, + justification = style.getJustification(), + leading = style.getLeading(), + x = 0; + measureCtx.font = style.getFontStyle(); + var width = 0; + for (var i = 0; i < count; i++) + width = Math.max(width, measureCtx.measureText(lines[i]).width); + if (justification !== 'left') + x -= width / (justification === 'center' ? 2: 1); + var bounds = new Rectangle(x, + count ? - 0.75 * leading : 0, + width, count * leading); + return matrix ? matrix._transformBounds(bounds, bounds) : bounds; + } + }; +}); + +var Color = Base.extend(new function() { + + var types = { + gray: ['gray'], + rgb: ['red', 'green', 'blue'], + hsb: ['hue', 'saturation', 'brightness'], + hsl: ['hue', 'saturation', 'lightness'], + gradient: ['gradient', 'origin', 'destination', 'highlight'] + }; + + var parsers = {}, + colorCache = {}, + colorCtx; + + function nameToRGB(name) { + var cached = colorCache[name]; + if (!cached) { + if (!colorCtx) { + colorCtx = CanvasProvider.getContext(1, 1); + colorCtx.globalCompositeOperation = 'copy'; + } + colorCtx.fillStyle = 'rgba(0,0,0,0)'; + colorCtx.fillStyle = name; + colorCtx.fillRect(0, 0, 1, 1); + var data = colorCtx.getImageData(0, 0, 1, 1).data; + cached = colorCache[name] = [ + data[0] / 255, + data[1] / 255, + data[2] / 255 + ]; + } + return cached.slice(); + } + + function hexToRGB(string) { + var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); + if (hex.length >= 4) { + var components = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + var value = hex[i + 1]; + components[i] = parseInt(value.length == 1 + ? value + value : value, 16) / 255; + } + return components; + } + } + + var hsbIndices = [ + [0, 3, 1], + [2, 0, 1], + [1, 0, 3], + [1, 2, 0], + [3, 1, 0], + [0, 1, 2] + ]; + + var converters = { + 'rgb-hsb': function(r, g, b) { + var max = Math.max(r, g, b), + min = Math.min(r, g, b), + delta = max - min, + h = delta === 0 ? 0 + : ( max == r ? (g - b) / delta + (g < b ? 6 : 0) + : max == g ? (b - r) / delta + 2 + : (r - g) / delta + 4) * 60; + return [h, max === 0 ? 0 : delta / max, max]; + }, + + 'hsb-rgb': function(h, s, b) { + var h = (h / 60) % 6, + i = Math.floor(h), + f = h - i, + i = hsbIndices[i], + v = [ + b, + b * (1 - s), + b * (1 - s * f), + b * (1 - s * (1 - f)) + ]; + return [v[i[0]], v[i[1]], v[i[2]]]; + }, + + 'rgb-hsl': function(r, g, b) { + var max = Math.max(r, g, b), + min = Math.min(r, g, b), + delta = max - min, + achromatic = delta === 0, + h = achromatic ? 0 + : ( max == r ? (g - b) / delta + (g < b ? 6 : 0) + : max == g ? (b - r) / delta + 2 + : (r - g) / delta + 4) * 60, + l = (max + min) / 2, + s = achromatic ? 0 : l < 0.5 + ? delta / (max + min) + : delta / (2 - max - min); + return [h, s, l]; + }, + + 'hsl-rgb': function(h, s, l) { + h /= 360; + if (s === 0) + return [l, l, l]; + var t3s = [ h + 1 / 3, h, h - 1 / 3 ], + t2 = l < 0.5 ? l * (1 + s) : l + s - l * s, + t1 = 2 * l - t2, + c = []; + for (var i = 0; i < 3; i++) { + var t3 = t3s[i]; + if (t3 < 0) t3 += 1; + if (t3 > 1) t3 -= 1; + c[i] = 6 * t3 < 1 + ? t1 + (t2 - t1) * 6 * t3 + : 2 * t3 < 1 + ? t2 + : 3 * t3 < 2 + ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6 + : t1; + } + return c; + }, + + 'rgb-gray': function(r, g, b) { + return [r * 0.2989 + g * 0.587 + b * 0.114]; + }, + + 'gray-rgb': function(g) { + return [g, g, g]; + }, + + 'gray-hsb': function(g) { + return [0, 0, g]; + }, + + 'gray-hsl': function(g) { + return [0, 0, g]; + }, + + 'gradient-rgb': function() { + return []; + }, + + 'rgb-gradient': function() { + return []; + } + + }; + + return Base.each(types, function(properties, type) { + parsers[type] = []; + Base.each(properties, function(name, index) { + var part = Base.capitalize(name), + hasOverlap = /^(hue|saturation)$/.test(name), + parser = parsers[type][index] = name === 'gradient' + ? function(value) { + var current = this._components[0]; + value = Gradient.read( + Array.isArray(value) ? value : arguments, + 0, 0, true); + if (current !== value) { + if (current) + current._removeOwner(this); + if (value) + value._addOwner(this); + } + return value; + } + : name === 'hue' + ? function(value) { + return isNaN(value) ? 0 + : ((value % 360) + 360) % 360; + } + : type === 'gradient' + ? function() { + return Point.read(arguments, 0, 0, + name === 'highlight', true); + } + : function(value) { + return isNaN(value) ? 0 + : Math.min(Math.max(value, 0), 1); + }; + + this['get' + part] = function() { + return this._type === type + || hasOverlap && /^hs[bl]$/.test(this._type) + ? this._components[index] + : this._convert(type)[index]; + }; + + this['set' + part] = function(value) { + if (this._type !== type + && !(hasOverlap && /^hs[bl]$/.test(this._type))) { + this._components = this._convert(type); + this._type = type; + } + value = parser.call(this, value); + if (value != null) { + this._components[index] = value; + this._changed(); + } + }; + }, this); + }, { + _class: 'Color', + _readIndex: true, + + initialize: function Color(arg) { + var slice = Array.prototype.slice, + args = arguments, + read = 0, + type, + components, + alpha, + values; + if (Array.isArray(arg)) { + args = arg; + arg = args[0]; + } + var argType = arg != null && typeof arg; + if (argType === 'string' && arg in types) { + type = arg; + arg = args[1]; + if (Array.isArray(arg)) { + components = arg; + alpha = args[2]; + } else { + if (this._read) + read = 1; + args = slice.call(args, 1); + argType = typeof arg; + } + } + if (!components) { + values = argType === 'number' + ? args + : argType === 'object' && arg.length != null + ? arg + : null; + if (values) { + if (!type) + type = values.length >= 3 + ? 'rgb' + : 'gray'; + var length = types[type].length; + alpha = values[length]; + if (this._read) + read += values === arguments + ? length + (alpha != null ? 1 : 0) + : 1; + if (values.length > length) + values = slice.call(values, 0, length); + } else if (argType === 'string') { + components = arg.match(/^#[0-9a-f]{3,6}$/i) + ? hexToRGB(arg) + : nameToRGB(arg); + type = 'rgb'; + } else if (argType === 'object') { + if (arg.constructor === Color) { + type = arg._type; + components = arg._components.slice(); + alpha = arg._alpha; + if (type === 'gradient') { + for (var i = 1, l = components.length; i < l; i++) { + var point = components[i]; + if (point) + components[i] = point.clone(); + } + } + } else if (arg.constructor === Gradient) { + type = 'gradient'; + values = args; + } else { + type = 'hue' in arg + ? 'lightness' in arg + ? 'hsl' + : 'hsb' + : 'gradient' in arg || 'stops' in arg + || 'radial' in arg + ? 'gradient' + : 'gray' in arg + ? 'gray' + : 'rgb'; + var properties = types[type]; + parse = parsers[type]; + this._components = components = []; + for (var i = 0, l = properties.length; i < l; i++) { + var value = arg[properties[i]]; + if (value == null && i === 0 && type === 'gradient' + && 'stops' in arg) { + value = { + stops: arg.stops, + radial: arg.radial + }; + } + value = parse[i].call(this, value); + if (value != null) + components[i] = value; + } + alpha = arg.alpha; + } + } + if (this._read && type) + read = 1; + } + this._type = type || 'rgb'; + if (type === 'gradient') + this._id = Color._id = (Color._id || 0) + 1; + if (!components) { + this._components = components = []; + var parse = parsers[this._type]; + for (var i = 0, l = parse.length; i < l; i++) { + var value = parse[i].call(this, values && values[i]); + if (value != null) + components[i] = value; + } + } + this._components = components; + this._alpha = alpha; + if (this._read) + this._read = read; + }, + + _serialize: function(options, dictionary) { + var components = this.getComponents(); + return Base.serialize( + /^(gray|rgb)$/.test(this._type) + ? components + : [this._type].concat(components), + options, true, dictionary); + }, + + _changed: function() { + this._canvasStyle = null; + if (this._owner) + this._owner._changed(17); + }, + + clone: function() { + return new Color(this._type, this._components.slice(), this._alpha); + }, + + _convert: function(type) { + var converter; + return this._type === type + ? this._components.slice() + : (converter = converters[this._type + '-' + type]) + ? converter.apply(this, this._components) + : converters['rgb-' + type].apply(this, + converters[this._type + '-rgb'].apply(this, + this._components)); + }, + + convert: function(type) { + return new Color(type, this._convert(type), this._alpha); + }, + + getType: function() { + return this._type; + }, + + setType: function(type) { + this._components = this._convert(type); + this._type = type; + }, + + getComponents: function() { + var components = this._components.slice(); + if (this._alpha != null) + components.push(this._alpha); + return components; + }, + + getAlpha: function() { + return this._alpha != null ? this._alpha : 1; + }, + + setAlpha: function(alpha) { + this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1); + this._changed(); + }, + + hasAlpha: function() { + return this._alpha != null; + }, + + equals: function(color) { + if (Base.isPlainValue(color)) + color = Color.read(arguments); + return color === this || color && this._type === color._type + && this._alpha === color._alpha + && Base.equals(this._components, color._components) + || false; + }, + + toString: function() { + var properties = types[this._type], + parts = [], + isGradient = this._type === 'gradient', + f = Formatter.instance; + for (var i = 0, l = properties.length; i < l; i++) { + var value = this._components[i]; + if (value != null) + parts.push(properties[i] + ': ' + + (isGradient ? value : f.number(value))); + } + if (this._alpha != null) + parts.push('alpha: ' + f.number(this._alpha)); + return '{ ' + parts.join(', ') + ' }'; + }, + + toCSS: function(noAlpha) { + var components = this._convert('rgb'), + alpha = noAlpha || this._alpha == null ? 1 : this._alpha; + components = [ + Math.round(components[0] * 255), + Math.round(components[1] * 255), + Math.round(components[2] * 255) + ]; + if (alpha < 1) + components.push(alpha); + return (components.length == 4 ? 'rgba(' : 'rgb(') + + components.join(',') + ')'; + }, + + toCanvasStyle: function(ctx) { + if (this._canvasStyle) + return this._canvasStyle; + if (this._type !== 'gradient') + return this._canvasStyle = this.toCSS(); + var components = this._components, + gradient = components[0], + stops = gradient._stops, + origin = components[1], + destination = components[2], + canvasGradient; + if (gradient._radial) { + var radius = destination.getDistance(origin), + highlight = components[3]; + if (highlight) { + var vector = highlight.subtract(origin); + if (vector.getLength() > radius) + highlight = origin.add(vector.normalize(radius - 0.1)); + } + var start = highlight || origin; + canvasGradient = ctx.createRadialGradient(start.x, start.y, + 0, origin.x, origin.y, radius); + } else { + canvasGradient = ctx.createLinearGradient(origin.x, origin.y, + destination.x, destination.y); + } + for (var i = 0, l = stops.length; i < l; i++) { + var stop = stops[i]; + canvasGradient.addColorStop(stop._rampPoint, + stop._color.toCanvasStyle()); + } + return this._canvasStyle = canvasGradient; + }, + + transform: function(matrix) { + if (this._type === 'gradient') { + var components = this._components; + for (var i = 1, l = components.length; i < l; i++) { + var point = components[i]; + matrix._transformPoint(point, point, true); + } + this._changed(); + } + }, + + statics: { + _types: types, + + random: function() { + var random = Math.random; + return new Color(random(), random(), random()); + } + } + }); +}); + +Base.each(Color._types, function(properties, type) { + var ctor = this[Base.capitalize(type) + 'Color'] = function(arg) { + var argType = arg != null && typeof arg, + components = argType === 'object' && arg.length != null + ? arg + : argType === 'string' + ? null + : arguments; + return components + ? new Color(type, components) + : new Color(arg); + }; + if (type.length == 3) { + var acronym = type.toUpperCase(); + Color[acronym] = this[acronym + 'Color'] = ctor; + } +}, this); + +var Gradient = Base.extend({ + _class: 'Gradient', + + initialize: function Gradient(stops, radial) { + this._id = Gradient._id = (Gradient._id || 0) + 1; + if (stops && this._set(stops)) + stops = radial = null; + if (!this._stops) + this.setStops(stops || ['white', 'black']); + if (this._radial == null) + this.setRadial(typeof radial === 'string' && radial === 'radial' + || radial || false); + }, + + _serialize: function(options, dictionary) { + return dictionary.add(this, function() { + return Base.serialize([this._stops, this._radial], + options, true, dictionary); + }); + }, + + _changed: function() { + for (var i = 0, l = this._owners && this._owners.length; i < l; i++) + this._owners[i]._changed(); + }, + + _addOwner: function(color) { + if (!this._owners) + this._owners = []; + this._owners.push(color); + }, + + _removeOwner: function(color) { + var index = this._owners ? this._owners.indexOf(color) : -1; + if (index != -1) { + this._owners.splice(index, 1); + if (this._owners.length === 0) + delete this._owners; + } + }, + + clone: function() { + var stops = []; + for (var i = 0, l = this._stops.length; i < l; i++) + stops[i] = this._stops[i].clone(); + return new this.constructor(stops); + }, + + getStops: function() { + return this._stops; + }, + + setStops: function(stops) { + if (this.stops) { + for (var i = 0, l = this._stops.length; i < l; i++) + delete this._stops[i]._owner; + } + if (stops.length < 2) + throw new Error( + 'Gradient stop list needs to contain at least two stops.'); + this._stops = GradientStop.readAll(stops, 0, false, true); + for (var i = 0, l = this._stops.length; i < l; i++) { + var stop = this._stops[i]; + stop._owner = this; + if (stop._defaultRamp) + stop.setRampPoint(i / (l - 1)); + } + this._changed(); + }, + + getRadial: function() { + return this._radial; + }, + + setRadial: function(radial) { + this._radial = radial; + this._changed(); + }, + + equals: function(gradient) { + if (gradient && gradient.constructor == this.constructor + && this._stops.length == gradient._stops.length) { + for (var i = 0, l = this._stops.length; i < l; i++) { + if (!this._stops[i].equals(gradient._stops[i])) + return false; + } + return true; + } + return false; + } +}); + +var GradientStop = Base.extend({ + _class: 'GradientStop', + + initialize: function GradientStop(arg0, arg1) { + if (arg0) { + var color, rampPoint; + if (arg1 === undefined && Array.isArray(arg0)) { + color = arg0[0]; + rampPoint = arg0[1]; + } else if (arg0.color) { + color = arg0.color; + rampPoint = arg0.rampPoint; + } else { + color = arg0; + rampPoint = arg1; + } + this.setColor(color); + this.setRampPoint(rampPoint); + } + }, + + clone: function() { + return new GradientStop(this._color.clone(), this._rampPoint); + }, + + _serialize: function(options, dictionary) { + return Base.serialize([this._color, this._rampPoint], options, true, + dictionary); + }, + + _changed: function() { + if (this._owner) + this._owner._changed(17); + }, + + getRampPoint: function() { + return this._rampPoint; + }, + + setRampPoint: function(rampPoint) { + this._defaultRamp = rampPoint == null; + this._rampPoint = rampPoint || 0; + this._changed(); + }, + + getColor: function() { + return this._color; + }, + + setColor: function(color) { + this._color = Color.read(arguments); + if (this._color === color) + this._color = color.clone(); + this._color._owner = this; + this._changed(); + }, + + equals: function(stop) { + return stop === this || stop instanceof GradientStop + && this._color.equals(stop._color) + && this._rampPoint == stop._rampPoint + || false; + } +}); + +var Style = Base.extend(new function() { + var defaults = { + fillColor: undefined, + strokeColor: undefined, + selectedColor: undefined, + strokeWidth: 1, + strokeCap: 'butt', + strokeJoin: 'miter', + miterLimit: 10, + dashOffset: 0, + dashArray: [], + font: 'sans-serif', + fontSize: 12, + leading: null, + justification: 'left' + }; + + var flags = { + strokeWidth: 25, + strokeCap: 25, + strokeJoin: 25, + miterLimit: 25, + font: 5, + fontSize: 5, + leading: 5, + justification: 5 + }; + + var item = {}, + fields = { + _defaults: defaults, + _textDefaults: Base.merge(defaults, { + fillColor: new Color() + }) + }; + + Base.each(defaults, function(value, key) { + var isColor = /Color$/.test(key), + part = Base.capitalize(key), + flag = flags[key], + set = 'set' + part, + get = 'get' + part; + + fields[set] = function(value) { + var children = this._item && this._item._children; + if (children && children.length > 0 + && this._item._type !== 'compound-path') { + for (var i = 0, l = children.length; i < l; i++) + children[i]._style[set](value); + } else { + var old = this._values[key]; + if (old != value) { + if (isColor) { + if (old) + delete old._owner; + if (value && value.constructor === Color) + value._owner = this._item; + } + this._values[key] = value; + if (this._item) + this._item._changed(flag || 17); + } + } + }; + + fields[get] = function() { + var value, + children = this._item && this._item._children; + if (!children || children.length === 0 || arguments[0] + || this._item._type === 'compound-path') { + var value = this._values[key]; + if (value === undefined) { + value = this._defaults[key]; + if (value && value.clone) + value = value.clone(); + this._values[key] = value; + } else if (isColor && !(value && value.constructor === Color)) { + this._values[key] = value = Color.read( + [value], 0, 0, true, true); + if (value) + value._owner = this._item; + } + return value; + } + for (var i = 0, l = children.length; i < l; i++) { + var childValue = children[i]._style[get](); + if (i === 0) { + value = childValue; + } else if (!Base.equals(value, childValue)) { + return undefined; + } + } + return value; + }; + + item[get] = function() { + return this._style[get](); + }; + + item[set] = function(value) { + this._style[set](value); + }; + }); + + Item.inject(item); + return fields; +}, { + _class: 'Style', + + initialize: function Style(style, _item) { + this._values = {}; + this._item = _item; + if (_item instanceof TextItem) + this._defaults = this._textDefaults; + if (style) + this.set(style); + }, + + set: function(style) { + var isStyle = style instanceof Style, + values = isStyle ? style._values : style; + if (values) { + for (var key in values) { + if (key in this._defaults) { + var value = values[key]; + this[key] = value && isStyle && value.clone + ? value.clone() : value; + } + } + } + }, + + getLeading: function getLeading() { + var leading = getLeading.base.call(this); + return leading != null ? leading : this.getFontSize() * 1.2; + }, + + getFontStyle: function() { + var size = this.getFontSize(); + return (/[a-z]/i.test(size) ? size + ' ' : size + 'px ') + + this.getFont(); + } + +}); + +var DomElement = new function() { + + var special = /^(checked|value|selected|disabled)$/i, + translated = { text: 'textContent', html: 'innerHTML' }, + unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1 }; + + function create(nodes, parent) { + var res = []; + for (var i = 0, l = nodes && nodes.length; i < l;) { + var el = nodes[i++]; + if (typeof el === 'string') { + el = document.createElement(el); + } else if (!el || !el.nodeType) { + continue; + } + if (Base.isPlainObject(nodes[i])) + DomElement.set(el, nodes[i++]); + if (Array.isArray(nodes[i])) + create(nodes[i++], el); + if (parent) + parent.appendChild(el); + res.push(el); + } + return res; + } + + return { + create: function(nodes, parent) { + var isArray = Array.isArray(nodes), + res = create(isArray ? nodes : arguments, isArray ? parent : null); + return res.length == 1 ? res[0] : res; + }, + + find: function(selector, root) { + return (root || document).querySelector(selector); + }, + + findAll: function(selector, root) { + return (root || document).querySelectorAll(selector); + }, + + get: function(el, key) { + return el + ? special.test(key) + ? key === 'value' || typeof el[key] !== 'string' + ? el[key] + : true + : key in translated + ? el[translated[key]] + : el.getAttribute(key) + : null; + }, + + set: function(el, key, value) { + if (typeof key !== 'string') { + for (var name in key) + if (key.hasOwnProperty(name)) + this.set(el, name, key[name]); + } else if (!el || value === undefined) { + return el; + } else if (special.test(key)) { + el[key] = value; + } else if (key in translated) { + el[translated[key]] = value; + } else if (key === 'style') { + this.setStyle(el, value); + } else if (key === 'events') { + DomEvent.add(el, value); + } else { + el.setAttribute(key, value); + } + return el; + }, + + getStyles: function(el) { + var view = el && el.ownerDocument.defaultView; + return view && view.getComputedStyle(el, ''); + }, + + getStyle: function(el, key) { + return el && el.style[key] || this.getStyles(el)[key] || null; + }, + + setStyle: function(el, key, value) { + if (typeof key !== 'string') { + for (var name in key) + if (key.hasOwnProperty(name)) + this.setStyle(el, name, key[name]); + } else { + if (/^-?[\d\.]+$/.test(value) && !(key in unitless)) + value += 'px'; + el.style[key] = value; + } + return el; + }, + + hasClass: function(el, cls) { + return new RegExp('\\s*' + cls + '\\s*').test(el.className); + }, + + addClass: function(el, cls) { + el.className = (el.className + ' ' + cls).trim(); + }, + + removeClass: function(el, cls) { + el.className = el.className.replace( + new RegExp('\\s*' + cls + '\\s*'), ' ').trim(); + }, + + remove: function(el) { + if (el.parentNode) + el.parentNode.removeChild(el); + }, + + removeChildren: function(el) { + while (el.firstChild) + el.removeChild(el.firstChild); + }, + + getBounds: function(el, viewport) { + var doc = el.ownerDocument, + body = doc.body, + html = doc.documentElement, + rect; + try { + rect = el.getBoundingClientRect(); + } catch (e) { + rect = { left: 0, top: 0, width: 0, height: 0 }; + } + var x = rect.left - (html.clientLeft || body.clientLeft || 0), + y = rect.top - (html.clientTop || body.clientTop || 0); + if (!viewport) { + var view = doc.defaultView; + x += view.pageXOffset || html.scrollLeft || body.scrollLeft; + y += view.pageYOffset || html.scrollTop || body.scrollTop; + } + return new Rectangle(x, y, rect.width, rect.height); + }, + + getViewportBounds: function(el) { + var doc = el.ownerDocument, + view = doc.defaultView, + html = doc.documentElement; + return new Rectangle(0, 0, + view.innerWidth || html.clientWidth, + view.innerHeight || html.clientHeight + ); + }, + + getOffset: function(el, viewport) { + return this.getBounds(el, viewport).getPoint(); + }, + + getSize: function(el) { + return this.getBounds(el, true).getSize(); + }, + + isInvisible: function(el) { + return this.getSize(el).equals(new Size(0, 0)); + }, + + isInView: function(el) { + return !this.isInvisible(el) && this.getViewportBounds(el).intersects( + this.getBounds(el, true)); + } + }; +}; + +var DomEvent = { + add: function(el, events) { + for (var type in events) { + var func = events[type]; + if (el.addEventListener) { + el.addEventListener(type, func, false); + } else if (el.attachEvent) { + el.attachEvent('on' + type, func.bound = function() { + func.call(el, window.event); + }); + } + } + }, + + remove: function(el, events) { + for (var type in events) { + var func = events[type]; + if (el.removeEventListener) { + el.removeEventListener(type, func, false); + } else if (el.detachEvent) { + el.detachEvent('on' + type, func.bound); + } + } + }, + + getPoint: function(event) { + var pos = event.targetTouches + ? event.targetTouches.length + ? event.targetTouches[0] + : event.changedTouches[0] + : event; + return new Point( + pos.pageX || pos.clientX + document.documentElement.scrollLeft, + pos.pageY || pos.clientY + document.documentElement.scrollTop + ); + }, + + getTarget: function(event) { + return event.target || event.srcElement; + }, + + getOffset: function(event, target) { + return DomEvent.getPoint(event).subtract(DomElement.getOffset( + target || DomEvent.getTarget(event))); + }, + + preventDefault: function(event) { + if (event.preventDefault) { + event.preventDefault(); + } else { + event.returnValue = false; + } + }, + + stopPropagation: function(event) { + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + }, + + stop: function(event) { + DomEvent.stopPropagation(event); + DomEvent.preventDefault(event); + } +}; + +DomEvent.requestAnimationFrame = new function() { + var part = 'equestAnimationFrame', + request = window['r' + part] || window['webkitR' + part] + || window['mozR' + part] || window['oR' + part] + || window['msR' + part]; + if (request) { + request(function(time) { + if (time == null) + request = null; + }); + } + + var callbacks = [], + focused = true, + timer; + + DomEvent.add(window, { + focus: function() { + focused = true; + }, + blur: function() { + focused = false; + } + }); + + return function(callback, element) { + if (request) + return request(callback, element); + callbacks.push([callback, element]); + if (timer) + return; + timer = setInterval(function() { + for (var i = callbacks.length - 1; i >= 0; i--) { + var entry = callbacks[i], + func = entry[0], + el = entry[1]; + if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true' + || focused) && DomElement.isInView(el)) { + callbacks.splice(i, 1); + func(Date.now()); + } + } + }, 1000 / 60); + }; +}; + +var View = Base.extend(Callback, { + _class: 'View', + + initialize: function View(element) { + this._scope = paper; + this._project = paper.project; + this._element = element; + var size; + this._id = element.getAttribute('id'); + if (this._id == null) + element.setAttribute('id', this._id = 'view-' + View._id++); + DomEvent.add(element, this._viewHandlers); + if (PaperScope.hasAttribute(element, 'resize')) { + var offset = DomElement.getOffset(element, true), + that = this; + size = DomElement.getViewportBounds(element) + .getSize().subtract(offset); + this._windowHandlers = { + resize: function() { + if (!DomElement.isInvisible(element)) + offset = DomElement.getOffset(element, true); + that.setViewSize(DomElement.getViewportBounds(element) + .getSize().subtract(offset)); + } + }; + DomEvent.add(window, this._windowHandlers); + } else { + size = new Size(parseInt(element.getAttribute('width'), 10), + parseInt(element.getAttribute('height'), 10)); + if (size.isNaN()) + size = DomElement.getSize(element); + } + element.width = size.width; + element.height = size.height; + if (PaperScope.hasAttribute(element, 'stats')) { + this._stats = new Stats(); + var stats = this._stats.domElement, + style = stats.style, + offset = DomElement.getOffset(element); + style.position = 'absolute'; + style.left = offset.x + 'px'; + style.top = offset.y + 'px'; + document.body.appendChild(stats); + } + View._views.push(this); + View._viewsById[this._id] = this; + this._viewSize = new LinkedSize(size.width, size.height, + this, 'setViewSize'); + this._matrix = new Matrix(); + this._zoom = 1; + if (!View._focused) + View._focused = this; + this._frameItems = {}; + this._frameItemCount = 0; + }, + + remove: function() { + if (!this._project) + return false; + if (View._focused == this) + View._focused = null; + View._views.splice(View._views.indexOf(this), 1); + delete View._viewsById[this._id]; + if (this._project.view == this) + this._project.view = null; + DomEvent.remove(this._element, this._viewHandlers); + DomEvent.remove(window, this._windowHandlers); + this._element = this._project = null; + this.detach('frame'); + this._frameItems = {}; + return true; + }, + + _events: { + onFrame: { + install: function() { + if (!this._requested) { + this._animate = true; + this._handleFrame(true); + } + }, + + uninstall: function() { + this._animate = false; + } + }, + + onResize: {} + }, + + _animate: false, + _time: 0, + _count: 0, + + _handleFrame: function(request) { + this._requested = false; + if (!this._animate) + return; + paper = this._scope; + if (request) { + this._requested = true; + var that = this; + DomEvent.requestAnimationFrame(function() { + that._handleFrame(true); + }, this._element); + } + var now = Date.now() / 1000, + delta = this._before ? now - this._before : 0; + this._before = now; + this._handlingFrame = true; + this.fire('frame', Base.merge({ + delta: delta, + time: this._time += delta, + count: this._count++ + })); + if (this._stats) + this._stats.update(); + this._handlingFrame = false; + this.draw(true); + }, + + _animateItem: function(item, animate) { + var items = this._frameItems; + if (animate) { + items[item._id] = { + item: item, + time: 0, + count: 0 + }; + if (++this._frameItemCount == 1) + this.attach('frame', this._handleFrameItems); + } else { + delete items[item._id]; + if (--this._frameItemCount == 0) { + this.detach('frame', this._handleFrameItems); + } + } + }, + + _handleFrameItems: function(event) { + for (var i in this._frameItems) { + var entry = this._frameItems[i]; + entry.item.fire('frame', Base.merge(event, { + time: entry.time += event.delta, + count: entry.count++ + })); + } + }, + + _redraw: function() { + this._project._needsRedraw = true; + if (this._handlingFrame) + return; + if (this._animate) { + this._handleFrame(); + } else { + this.draw(); + } + }, + + _transform: function(matrix) { + this._matrix.concatenate(matrix); + this._bounds = null; + this._inverse = null; + this._redraw(); + }, + + getElement: function() { + return this._element; + }, + + getViewSize: function() { + return this._viewSize; + }, + + setViewSize: function(size) { + size = Size.read(arguments); + var delta = size.subtract(this._viewSize); + if (delta.isZero()) + return; + this._element.width = size.width; + this._element.height = size.height; + this._viewSize.set(size.width, size.height, true); + this._bounds = null; + this.fire('resize', { + size: size, + delta: delta + }); + this._redraw(); + }, + + getBounds: function() { + if (!this._bounds) + this._bounds = this._getInverse()._transformBounds( + new Rectangle(new Point(), this._viewSize)); + return this._bounds; + }, + + getSize: function() { + return this.getBounds().getSize(arguments[0]); + }, + + getCenter: function() { + return this.getBounds().getCenter(arguments[0]); + }, + + setCenter: function(center) { + center = Point.read(arguments); + this.scrollBy(center.subtract(this.getCenter())); + }, + + getZoom: function() { + return this._zoom; + }, + + setZoom: function(zoom) { + this._transform(new Matrix().scale(zoom / this._zoom, + this.getCenter())); + this._zoom = zoom; + }, + + isVisible: function() { + return DomElement.isInView(this._element); + }, + + scrollBy: function() { + this._transform(new Matrix().translate(Point.read(arguments).negate())); + }, + + projectToView: function() { + return this._matrix._transformPoint(Point.read(arguments)); + }, + + viewToProject: function() { + return this._getInverse()._transformPoint(Point.read(arguments)); + }, + + _getInverse: function() { + if (!this._inverse) + this._inverse = this._matrix.inverted(); + return this._inverse; + } + +}, { + statics: { + _views: [], + _viewsById: {}, + _id: 0, + + create: function(element) { + if (typeof element === 'string') + element = document.getElementById(element); + return new CanvasView(element); + } + } +}, new function() { + var tool, + prevFocus, + tempFocus, + dragging = false; + + function getView(event) { + var target = DomEvent.getTarget(event); + return target.getAttribute && View._viewsById[target.getAttribute('id')]; + } + + function viewToProject(view, event) { + return view.viewToProject(DomEvent.getOffset(event, view._element)); + } + + function updateFocus() { + if (!View._focused || !View._focused.isVisible()) { + for (var i = 0, l = View._views.length; i < l; i++) { + var view = View._views[i]; + if (view && view.isVisible()) { + View._focused = tempFocus = view; + break; + } + } + } + } + + function mousedown(event) { + var view = View._focused = getView(event), + point = viewToProject(view, event); + dragging = true; + if (view._onMouseDown) + view._onMouseDown(event, point); + if (tool = view._scope._tool) + tool._onHandleEvent('mousedown', point, event); + view.draw(true); + } + + function mousemove(event) { + var view; + if (!dragging) { + view = getView(event); + if (view) { + prevFocus = View._focused; + View._focused = tempFocus = view; + } else if (tempFocus && tempFocus == View._focused) { + View._focused = prevFocus; + updateFocus(); + } + } + if (!(view = view || View._focused)) + return; + var point = event && viewToProject(view, event); + if (view._onMouseMove) + view._onMouseMove(event, point); + if (tool = view._scope._tool) { + if (tool._onHandleEvent(dragging && tool.responds('mousedrag') + ? 'mousedrag' : 'mousemove', point, event)) + DomEvent.stop(event); + } + view.draw(true); + } + + function mouseup(event) { + var view = View._focused; + if (!view || !dragging) + return; + var point = viewToProject(view, event); + curPoint = null; + dragging = false; + if (view._onMouseUp) + view._onMouseUp(event, point); + if (tool && tool._onHandleEvent('mouseup', point, event)) + DomEvent.stop(event); + view.draw(true); + } + + function selectstart(event) { + if (dragging) + DomEvent.stop(event); + } + + DomEvent.add(document, { + mousemove: mousemove, + mouseup: mouseup, + touchmove: mousemove, + touchend: mouseup, + selectstart: selectstart, + scroll: updateFocus + }); + + DomEvent.add(window, { + load: updateFocus + }); + + return { + _viewHandlers: { + mousedown: mousedown, + touchstart: mousedown, + selectstart: selectstart + }, + + statics: { + updateFocus: updateFocus + } + }; +}); + +var CanvasView = View.extend({ + _class: 'CanvasView', + + initialize: function CanvasView(canvas) { + if (!(canvas instanceof HTMLCanvasElement)) { + var size = Size.read(arguments, 1); + if (size.isZero()) + size = new Size(1024, 768); + canvas = CanvasProvider.getCanvas(size); + } + this._context = canvas.getContext('2d'); + this._eventCounters = {}; + View.call(this, canvas); + }, + + draw: function(checkRedraw) { + if (checkRedraw && !this._project._needsRedraw) + return false; + var ctx = this._context, + size = this._viewSize; + ctx.clearRect(0, 0, size._width + 1, size._height + 1); + this._project.draw(ctx, this._matrix); + this._project._needsRedraw = false; + return true; + } +}, new function() { + + var downPoint, + lastPoint, + overPoint, + downItem, + lastItem, + overItem, + hasDrag, + doubleClick, + clickTime; + + function callEvent(type, event, point, target, lastPoint, bubble) { + var item = target, + mouseEvent; + while (item) { + if (item.responds(type)) { + if (!mouseEvent) + mouseEvent = new MouseEvent(type, event, point, target, + lastPoint ? point.subtract(lastPoint) : null); + if (item.fire(type, mouseEvent) + && (!bubble || mouseEvent._stopped)) + return false; + } + item = item.getParent(); + } + return true; + } + + function handleEvent(view, type, event, point, lastPoint) { + if (view._eventCounters[type]) { + var project = view._project, + hit = project.hitTest(point, { + tolerance: project.options.hitTolerance || 0, + fill: true, + stroke: true + }), + item = hit && hit.item; + if (item) { + if (type === 'mousemove' && item != overItem) + lastPoint = point; + if (type !== 'mousemove' || !hasDrag) + callEvent(type, event, point, item, lastPoint); + return item; + } + } + } + + return { + _onMouseDown: function(event, point) { + var item = handleEvent(this, 'mousedown', event, point); + doubleClick = lastItem == item && (Date.now() - clickTime < 300); + downItem = lastItem = item; + downPoint = lastPoint = overPoint = point; + hasDrag = downItem && downItem.responds('mousedrag'); + }, + + _onMouseUp: function(event, point) { + var item = handleEvent(this, 'mouseup', event, point); + if (hasDrag) { + if (lastPoint && !lastPoint.equals(point)) + callEvent('mousedrag', event, point, downItem, lastPoint); + if (item != downItem) { + overPoint = point; + callEvent('mousemove', event, point, item, overPoint); + } + } + if (item === downItem) { + clickTime = Date.now(); + if (!doubleClick + || callEvent('doubleclick', event, downPoint, item)) + callEvent('click', event, downPoint, item); + doubleClick = false; + } + downItem = null; + hasDrag = false; + }, + + _onMouseMove: function(event, point) { + if (downItem) + callEvent('mousedrag', event, point, downItem, lastPoint); + var item = handleEvent(this, 'mousemove', event, point, overPoint); + lastPoint = overPoint = point; + if (item !== overItem) { + callEvent('mouseleave', event, point, overItem); + overItem = item; + callEvent('mouseenter', event, point, item); + } + } + }; +}); + +var Event = Base.extend({ + _class: 'Event', + + initialize: function Event(event) { + this.event = event; + }, + + preventDefault: function() { + this._prevented = true; + DomEvent.preventDefault(this.event); + }, + + stopPropagation: function() { + this._stopped = true; + DomEvent.stopPropagation(this.event); + }, + + stop: function() { + this.stopPropagation(); + this.preventDefault(); + }, + + getModifiers: function() { + return Key.modifiers; + } +}); + +var KeyEvent = Event.extend({ + _class: 'KeyEvent', + + initialize: function KeyEvent(down, key, character, event) { + Event.call(this, event); + this.type = down ? 'keydown' : 'keyup'; + this.key = key; + this.character = character; + }, + + toString: function() { + return "{ type: '" + this.type + + "', key: '" + this.key + + "', character: '" + this.character + + "', modifiers: " + this.getModifiers() + + " }"; + } +}); + +var Key = new function() { + + var keys = { + 8: 'backspace', + 9: 'tab', + 13: 'enter', + 16: 'shift', + 17: 'control', + 18: 'option', + 19: 'pause', + 20: 'caps-lock', + 27: 'escape', + 32: 'space', + 35: 'end', + 36: 'home', + 37: 'left', + 38: 'up', + 39: 'right', + 40: 'down', + 46: 'delete', + 91: 'command', + 93: 'command', + 224: 'command' + }, + + modifiers = Base.merge({ + shift: false, + control: false, + option: false, + command: false, + capsLock: false, + space: false + }), + + charCodeMap = {}, + keyMap = {}, + downCode; + + function handleKey(down, keyCode, charCode, event) { + var character = String.fromCharCode(charCode), + key = keys[keyCode] || character.toLowerCase(), + type = down ? 'keydown' : 'keyup', + view = View._focused, + scope = view && view.isVisible() && view._scope, + tool = scope && scope._tool; + keyMap[key] = down; + if (tool && tool.responds(type)) { + tool.fire(type, new KeyEvent(down, key, character, event)); + if (view) + view.draw(true); + } + } + + DomEvent.add(document, { + keydown: function(event) { + var code = event.which || event.keyCode; + var key = keys[code], name; + if (key) { + if ((name = Base.camelize(key)) in modifiers) + modifiers[name] = true; + charCodeMap[code] = 0; + handleKey(true, code, null, event); + } else { + downCode = code; + } + }, + + keypress: function(event) { + if (downCode != null) { + var code = event.which || event.keyCode; + charCodeMap[downCode] = code; + handleKey(true, downCode, code, event); + downCode = null; + } + }, + + keyup: function(event) { + var code = event.which || event.keyCode, + key = keys[code], name; + if (key && (name = Base.camelize(key)) in modifiers) + modifiers[name] = false; + if (charCodeMap[code] != null) { + handleKey(false, code, charCodeMap[code], event); + delete charCodeMap[code]; + } + } + }); + + return { + modifiers: modifiers, + + isDown: function(key) { + return !!keyMap[key]; + } + }; +}; + +var MouseEvent = Event.extend({ + _class: 'MouseEvent', + + initialize: function MouseEvent(type, event, point, target, delta) { + Event.call(this, event); + this.type = type; + this.point = point; + this.target = target; + this.delta = delta; + }, + + toString: function() { + return "{ type: '" + this.type + + "', point: " + this.point + + ', target: ' + this.target + + (this.delta ? ', delta: ' + this.delta : '') + + ', modifiers: ' + this.getModifiers() + + ' }'; + } +}); + + Base.extend(Callback, { + _class: 'Palette', + _events: [ 'onChange' ], + + initialize: function Palette(title, components, values) { + var parent = DomElement.find('.palettejs-panel') + || DomElement.find('body').appendChild( + DomElement.create('div', { 'class': 'palettejs-panel' })); + this._element = parent.appendChild( + DomElement.create('table', { 'class': 'palettejs-pane' })), + this._title = title; + if (!values) + values = {}; + for (var name in (this._components = components)) { + var component = components[name]; + if (!(component instanceof Component)) { + if (component.value == null) + component.value = values[name]; + component.name = name; + component = components[name] = new Component(component); + } + this._element.appendChild(component._element); + component._palette = this; + if (values[name] === undefined) + values[name] = component.value; + } + this._values = Base.each(values, function(value, name) { + var component = components[name]; + if (component) { + Base.define(values, name, { + enumerable: true, + configurable: true, + get: function() { + return component._value; + }, + set: function(val) { + component.setValue(val); + } + }); + } + }); + if (window.paper) + paper.palettes.push(this); + }, + + reset: function() { + for (var i in this._components) + this._components[i].reset(); + }, + + remove: function() { + DomElement.remove(this._element); + } +}); + +var Component = Base.extend(Callback, { + _class: 'Component', + _events: [ 'onChange', 'onClick' ], + + _types: { + 'boolean': { + type: 'checkbox', + value: 'checked' + }, + + string: { + type: 'text' + }, + + number: { + type: 'number', + number: true + }, + + button: { + type: 'button' + }, + + text: { + tag: 'div', + value: 'text' + }, + + slider: { + type: 'range', + number: true + }, + + list: { + tag: 'select', + + options: function() { + DomElement.removeChildren(this._inputItem); + DomElement.create(Base.each(this._options, function(option) { + this.push('option', { value: option, text: option }); + }, []), this._inputItem); + } + } + }, + + initialize: function Component(obj) { + this._type = obj.type in this._types + ? obj.type + : 'options' in obj + ? 'list' + : 'onClick' in obj + ? 'button' + : typeof obj.value; + this._info = this._types[this._type] || { type: this._type }; + var that = this, + fireChange = false; + this._inputItem = DomElement.create(this._info.tag || 'input', { + type: this._info.type, + events: { + change: function() { + that.setValue( + DomElement.get(this, that._info.value || 'value')); + if (fireChange) { + that._palette.fire('change', that, that.name, that._value); + that.fire('change', that._value); + } + }, + click: function() { + that.fire('click'); + } + } + }); + this._element = DomElement.create('tr', [ + this._labelItem = DomElement.create('td'), + 'td', [this._inputItem] + ]); + Base.each(obj, function(value, key) { + this[key] = value; + }, this); + this._defaultValue = this._value; + fireChange = true; + }, + + getType: function() { + return this._type; + }, + + getLabel: function() { + return this._label; + }, + + setLabel: function(label) { + this._label = label; + DomElement.set(this._labelItem, 'text', label + ':'); + }, + + getOptions: function() { + return this._options; + }, + + setOptions: function(options) { + this._options = options; + if (this._info.options) + this._info.options.call(this); + }, + + getValue: function() { + return this._value; + }, + + setValue: function(value) { + var key = this._info.value || 'value'; + DomElement.set(this._inputItem, key, value); + value = DomElement.get(this._inputItem, key); + this._value = this._info.number ? parseFloat(value, 10) : value; + }, + + getRange: function() { + return [parseFloat(DomElement.get(this._inputItem, 'min')), + parseFloat(DomElement.get(this._inputItem, 'max'))]; + }, + + setRange: function(min, max) { + var range = Array.isArray(min) ? min : [min, max]; + DomElement.set(this._inputItem, { min: range[0], max: range[1] }); + }, + + getMin: function() { + return this.getRange()[0]; + }, + + setMin: function(min) { + this.setRange(min, this.getMax()); + }, + + getMax: function() { + return this.getRange()[1]; + }, + + setMax: function(max) { + this.setRange(this.getMin(), max); + }, + + getStep: function() { + return parseFloat(DomElement.get(this._inputItem, 'step')); + }, + + setStep: function(step) { + DomElement.set(this._inputItem, 'step', step); + }, + + reset: function() { + this.setValue(this._defaultValue); + } +}); + +var ToolEvent = Event.extend({ + _class: 'ToolEvent', + _item: null, + + initialize: function ToolEvent(tool, type, event) { + this.tool = tool; + this.type = type; + this.event = event; + }, + + _choosePoint: function(point, toolPoint) { + return point ? point : toolPoint ? toolPoint.clone() : null; + }, + + getPoint: function() { + return this._choosePoint(this._point, this.tool._point); + }, + + setPoint: function(point) { + this._point = point; + }, + + getLastPoint: function() { + return this._choosePoint(this._lastPoint, this.tool._lastPoint); + }, + + setLastPoint: function(lastPoint) { + this._lastPoint = lastPoint; + }, + + getDownPoint: function() { + return this._choosePoint(this._downPoint, this.tool._downPoint); + }, + + setDownPoint: function(downPoint) { + this._downPoint = downPoint; + }, + + getMiddlePoint: function() { + if (!this._middlePoint && this.tool._lastPoint) { + return this.tool._point.add(this.tool._lastPoint).divide(2); + } + return this.middlePoint; + }, + + setMiddlePoint: function(middlePoint) { + this._middlePoint = middlePoint; + }, + + getDelta: function() { + return !this._delta && this.tool._lastPoint + ? this.tool._point.subtract(this.tool._lastPoint) + : this._delta; + }, + + setDelta: function(delta) { + this._delta = delta; + }, + + getCount: function() { + return /^mouse(down|up)$/.test(this.type) + ? this.tool._downCount + : this.tool._count; + }, + + setCount: function(count) { + this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count'] + = count; + }, + + getItem: function() { + if (!this._item) { + var result = this.tool._scope.project.hitTest(this.getPoint()); + if (result) { + var item = result.item, + parent = item._parent; + while (/^(group|compound-path)$/.test(parent._type)) { + item = parent; + parent = parent._parent; + } + this._item = item; + } + } + return this._item; + }, + setItem: function(item) { + this._item = item; + }, + + toString: function() { + return '{ type: ' + this.type + + ', point: ' + this.getPoint() + + ', count: ' + this.getCount() + + ', modifiers: ' + this.getModifiers() + + ' }'; + } +}); + +var Tool = PaperScopeItem.extend({ + _class: 'Tool', + _list: 'tools', + _reference: '_tool', + _events: [ 'onActivate', 'onDeactivate', 'onEditOptions', + 'onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove', + 'onKeyDown', 'onKeyUp' ], + + initialize: function Tool(props) { + PaperScopeItem.call(this); + this._firstMove = true; + this._count = 0; + this._downCount = 0; + this._set(props); + }, + + getMinDistance: function() { + return this._minDistance; + }, + + setMinDistance: function(minDistance) { + this._minDistance = minDistance; + if (this._minDistance != null && this._maxDistance != null + && this._minDistance > this._maxDistance) { + this._maxDistance = this._minDistance; + } + }, + + getMaxDistance: function() { + return this._maxDistance; + }, + + setMaxDistance: function(maxDistance) { + this._maxDistance = maxDistance; + if (this._minDistance != null && this._maxDistance != null + && this._maxDistance < this._minDistance) { + this._minDistance = maxDistance; + } + }, + + getFixedDistance: function() { + return this._minDistance == this._maxDistance + ? this._minDistance : null; + }, + + setFixedDistance: function(distance) { + this._minDistance = distance; + this._maxDistance = distance; + }, + + _updateEvent: function(type, point, minDistance, maxDistance, start, + needsChange, matchMaxDistance) { + if (!start) { + if (minDistance != null || maxDistance != null) { + var minDist = minDistance != null ? minDistance : 0, + vector = point.subtract(this._point), + distance = vector.getLength(); + if (distance < minDist) + return false; + var maxDist = maxDistance != null ? maxDistance : 0; + if (maxDist != 0) { + if (distance > maxDist) { + point = this._point.add(vector.normalize(maxDist)); + } else if (matchMaxDistance) { + return false; + } + } + } + if (needsChange && point.equals(this._point)) + return false; + } + this._lastPoint = start && type == 'mousemove' ? point : this._point; + this._point = point; + switch (type) { + case 'mousedown': + this._lastPoint = this._downPoint; + this._downPoint = this._point; + this._downCount++; + break; + case 'mouseup': + this._lastPoint = this._downPoint; + break; + } + this._count = start ? 0 : this._count + 1; + return true; + }, + + _fireEvent: function(type, event) { + var sets = paper.project._removeSets; + if (sets) { + if (type === 'mouseup') + sets.mousedrag = null; + var set = sets[type]; + if (set) { + for (var id in set) { + var item = set[id]; + for (var key in sets) { + var other = sets[key]; + if (other && other != set) + delete other[item._id]; + } + item.remove(); + } + sets[type] = null; + } + } + return this.responds(type) + && this.fire(type, new ToolEvent(this, type, event)); + }, + + _onHandleEvent: function(type, point, event) { + paper = this._scope; + var called = false; + switch (type) { + case 'mousedown': + this._updateEvent(type, point, null, null, true, false, false); + called = this._fireEvent(type, event); + break; + case 'mousedrag': + var needsChange = false, + matchMaxDistance = false; + while (this._updateEvent(type, point, this.minDistance, + this.maxDistance, false, needsChange, matchMaxDistance)) { + called = this._fireEvent(type, event) || called; + needsChange = true; + matchMaxDistance = true; + } + break; + case 'mouseup': + if (!point.equals(this._point) + && this._updateEvent('mousedrag', point, this.minDistance, + this.maxDistance, false, false, false)) { + called = this._fireEvent('mousedrag', event); + } + this._updateEvent(type, point, null, this.maxDistance, false, + false, false); + called = this._fireEvent(type, event) || called; + this._updateEvent(type, point, null, null, true, false, false); + this._firstMove = true; + break; + case 'mousemove': + while (this._updateEvent(type, point, this.minDistance, + this.maxDistance, this._firstMove, true, false)) { + called = this._fireEvent(type, event) || called; + this._firstMove = false; + } + break; + } + return called; + } + +}); + +var CanvasProvider = { + canvases: [], + + getCanvas: function(width, height) { + var size = height === undefined ? width : new Size(width, height), + canvas, + init = true; + if (this.canvases.length) { + canvas = this.canvases.pop(); + } else { + canvas = document.createElement('canvas'); + + } + var ctx = canvas.getContext('2d'); + ctx.save(); + if (canvas.width === size.width && canvas.height === size.height) { + if (init) + ctx.clearRect(0, 0, size.width + 1, size.height + 1); + } else { + canvas.width = size.width; + canvas.height = size.height; + } + return canvas; + }, + + getContext: function(width, height) { + return this.getCanvas(width, height).getContext('2d'); + }, + + release: function(obj) { + var canvas = obj.canvas ? obj.canvas : obj; + canvas.getContext('2d').restore(); + this.canvases.push(canvas); + } +}; + +var BlendMode = new function() { + var min = Math.min, + max = Math.max, + abs = Math.abs, + sr, sg, sb, sa, + br, bg, bb, ba, + dr, dg, db; + + function getLum(r, g, b) { + return 0.2989 * r + 0.587 * g + 0.114 * b; + } + + function setLum(r, g, b, l) { + var d = l - getLum(r, g, b); + dr = r + d; + dg = g + d; + db = b + d; + var l = getLum(dr, dg, db), + mn = min(dr, dg, db), + mx = max(dr, dg, db); + if (mn < 0) { + var lmn = l - mn; + dr = l + (dr - l) * l / lmn; + dg = l + (dg - l) * l / lmn; + db = l + (db - l) * l / lmn; + } + if (mx > 255) { + var ln = 255 - l, + mxl = mx - l; + dr = l + (dr - l) * ln / mxl; + dg = l + (dg - l) * ln / mxl; + db = l + (db - l) * ln / mxl; + } + } + + function getSat(r, g, b) { + return max(r, g, b) - min(r, g, b); + } + + function setSat(r, g, b, s) { + var col = [r, g, b], + mx = max(r, g, b), + mn = min(r, g, b), + md; + mn = mn === r ? 0 : mn === g ? 1 : 2; + mx = mx === r ? 0 : mx === g ? 1 : 2; + md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0; + if (col[mx] > col[mn]) { + col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]); + col[mx] = s; + } else { + col[md] = col[mx] = 0; + } + col[mn] = 0; + dr = col[0]; + dg = col[1]; + db = col[2]; + } + + var modes = { + multiply: function() { + dr = br * sr / 255; + dg = bg * sg / 255; + db = bb * sb / 255; + }, + + screen: function() { + dr = br + sr - (br * sr / 255); + dg = bg + sg - (bg * sg / 255); + db = bb + sb - (bb * sb / 255); + }, + + overlay: function() { + dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255; + dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255; + db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255; + }, + + 'soft-light': function() { + var t = sr * br / 255; + dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255; + t = sg * bg / 255; + dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255; + t = sb * bb / 255; + db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255; + }, + + 'hard-light': function() { + dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255; + dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255; + db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255; + }, + + 'color-dodge': function() { + dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr)); + dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg)); + db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb)); + }, + + 'color-burn': function() { + dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr); + dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg); + db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb); + }, + + darken: function() { + dr = br < sr ? br : sr; + dg = bg < sg ? bg : sg; + db = bb < sb ? bb : sb; + }, + + lighten: function() { + dr = br > sr ? br : sr; + dg = bg > sg ? bg : sg; + db = bb > sb ? bb : sb; + }, + + difference: function() { + dr = br - sr; + if (dr < 0) + dr = -dr; + dg = bg - sg; + if (dg < 0) + dg = -dg; + db = bb - sb; + if (db < 0) + db = -db; + }, + + exclusion: function() { + dr = br + sr * (255 - br - br) / 255; + dg = bg + sg * (255 - bg - bg) / 255; + db = bb + sb * (255 - bb - bb) / 255; + }, + + hue: function() { + setSat(sr, sg, sb, getSat(br, bg, bb)); + setLum(dr, dg, db, getLum(br, bg, bb)); + }, + + saturation: function() { + setSat(br, bg, bb, getSat(sr, sg, sb)); + setLum(dr, dg, db, getLum(br, bg, bb)); + }, + + luminosity: function() { + setLum(br, bg, bb, getLum(sr, sg, sb)); + }, + + color: function() { + setLum(sr, sg, sb, getLum(br, bg, bb)); + }, + + add: function() { + dr = min(br + sr, 255); + dg = min(bg + sg, 255); + db = min(bb + sb, 255); + }, + + subtract: function() { + dr = max(br - sr, 0); + dg = max(bg - sg, 0); + db = max(bb - sb, 0); + }, + + average: function() { + dr = (br + sr) / 2; + dg = (bg + sg) / 2; + db = (bb + sb) / 2; + }, + + negation: function() { + dr = 255 - abs(255 - sr - br); + dg = 255 - abs(255 - sg - bg); + db = 255 - abs(255 - sb - bb); + } + }; + + var ctx = CanvasProvider.getContext(1, 1); + function testMode(mode) { + ctx.save(); + var darken = mode === 'darken', + ok = false; + ctx.fillStyle = darken ? '#300' : '#a00'; + ctx.fillRect(0, 0, 1, 1); + ctx.globalCompositeOperation = mode; + if (ctx.globalCompositeOperation === mode) { + ctx.fillStyle = darken ? '#a00' : '#300'; + ctx.fillRect(0, 0, 1, 1); + ok = ctx.getImageData(0, 0, 1, 1).data[0] !== (darken ? 170 : 51); + } + ctx.restore(); + return ok; + } + this.nativeModes = testMode('multiply') && Base.each(modes, + function(func, mode) { + this[mode] = testMode(mode); + }, {}); + CanvasProvider.release(ctx); + + this.process = function(mode, srcContext, dstContext, alpha, offset) { + var srcCanvas = srcContext.canvas, + normal = mode === 'normal'; + if (normal || this.nativeModes[mode]) { + dstContext.save(); + dstContext.setTransform(1, 0, 0, 1, 0, 0); + dstContext.globalAlpha = alpha; + if (!normal) + dstContext.globalCompositeOperation = mode; + dstContext.drawImage(srcCanvas, offset.x, offset.y); + dstContext.restore(); + } else { + var process = modes[mode]; + if (!process) + return; + var dstData = dstContext.getImageData(offset.x, offset.y, + srcCanvas.width, srcCanvas.height), + dst = dstData.data, + src = srcContext.getImageData(0, 0, + srcCanvas.width, srcCanvas.height).data; + for (var i = 0, l = dst.length; i < l; i += 4) { + sr = src[i]; + br = dst[i]; + sg = src[i + 1]; + bg = dst[i + 1]; + sb = src[i + 2]; + bb = dst[i + 2]; + sa = src[i + 3]; + ba = dst[i + 3]; + process(); + var a1 = sa * alpha / 255, + a2 = 1 - a1; + dst[i] = a1 * dr + a2 * br; + dst[i + 1] = a1 * dg + a2 * bg; + dst[i + 2] = a1 * db + a2 * bb; + dst[i + 3] = sa * alpha + a2 * ba; + } + dstContext.putImageData(dstData, offset.x, offset.y); + } + }; +}; + +var SVGStyles = Base.each({ + fillColor: ['fill', 'color'], + strokeColor: ['stroke', 'color'], + strokeWidth: ['stroke-width', 'number'], + strokeCap: ['stroke-linecap', 'string'], + strokeJoin: ['stroke-linejoin', 'string'], + miterLimit: ['stroke-miterlimit', 'number'], + dashArray: ['stroke-dasharray', 'array'], + dashOffset: ['stroke-dashoffset', 'number'], + font: ['font-family', 'string'], + fontSize: ['font-size', 'number'], + justification: ['text-anchor', 'lookup', { + left: 'start', + center: 'middle', + right: 'end' + }], + opacity: ['opacity', 'number'], + blendMode: ['mix-blend-mode', 'string'] +}, function(entry, key) { + var part = Base.capitalize(key), + lookup = entry[2]; + this[key] = { + type: entry[1], + property: key, + attribute: entry[0], + toSVG: lookup, + fromSVG: lookup && Base.each(lookup, function(value, name) { + this[value] = name; + }, {}), + get: 'get' + part, + set: 'set' + part + }; +}, {}); + +var SVGNamespaces = { + href: 'http://www.w3.org/1999/xlink', + xlink: 'http://www.w3.org/2000/xmlns' +}; + +new function() { + var formatter = Formatter.instance; + + function setAttributes(node, attrs) { + for (var key in attrs) { + var val = attrs[key], + namespace = SVGNamespaces[key]; + if (typeof val === 'number') + val = formatter.number(val); + if (namespace) { + node.setAttributeNS(namespace, key, val); + } else { + node.setAttribute(key, val); + } + } + return node; + } + + function createElement(tag, attrs) { + return setAttributes( + document.createElementNS('http://www.w3.org/2000/svg', tag), attrs); + } + + function getDistance(segments, index1, index2) { + return segments[index1]._point.getDistance(segments[index2]._point); + } + + function getTransform(item, coordinates) { + var matrix = item._matrix, + trans = matrix.getTranslation(), + attrs = {}; + if (coordinates) { + matrix = matrix.shiftless(); + var point = matrix._inverseTransform(trans); + attrs.x = point.x; + attrs.y = point.y; + trans = null; + } + if (matrix.isIdentity()) + return attrs; + var decomposed = matrix.decompose(); + if (decomposed && !decomposed.shearing) { + var parts = [], + angle = decomposed.rotation, + scale = decomposed.scaling; + if (trans && !trans.isZero()) + parts.push('translate(' + formatter.point(trans) + ')'); + if (!Numerical.isZero(scale.x - 1) || !Numerical.isZero(scale.y - 1)) + parts.push('scale(' + formatter.point(scale) +')'); + if (angle) + parts.push('rotate(' + formatter.number(angle) + ')'); + attrs.transform = parts.join(' '); + } else { + attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')'; + } + return attrs; + } + + function determineAngle(path, segments, type, center) { + var topCenter = type === 'rect' + ? segments[1]._point.add(segments[2]._point).divide(2) + : type === 'roundrect' + ? segments[3]._point.add(segments[4]._point).divide(2) + : type === 'circle' || type === 'ellipse' + ? segments[1]._point + : null; + var angle = topCenter && topCenter.subtract(center).getAngle() + 90; + return Numerical.isZero(angle || 0) ? 0 : angle; + } + + function determineType(path, segments) { + function isColinear(i, j) { + var seg1 = segments[i], + seg2 = seg1.getNext(), + seg3 = segments[j], + seg4 = seg3.getNext(); + return seg1._handleOut.isZero() && seg2._handleIn.isZero() + && seg3._handleOut.isZero() && seg4._handleIn.isZero() + && seg2._point.subtract(seg1._point).isColinear( + seg4._point.subtract(seg3._point)); + } + + function isArc(i) { + var segment = segments[i], + next = segment.getNext(), + handle1 = segment._handleOut, + handle2 = next._handleIn, + kappa = Numerical.KAPPA; + if (handle1.isOrthogonal(handle2)) { + var from = segment._point, + to = next._point, + corner = new Line(from, handle1, true).intersect( + new Line(to, handle2, true), true); + return corner && Numerical.isZero(handle1.getLength() / + corner.subtract(from).getLength() - kappa) + && Numerical.isZero(handle2.getLength() / + corner.subtract(to).getLength() - kappa); + } + } + + if (path.isPolygon()) { + return segments.length === 4 && path._closed + && isColinear(0, 2) && isColinear(1, 3) + ? 'rect' + : segments.length === 0 + ? 'empty' + : segments.length >= 3 + ? path._closed ? 'polygon' : 'polyline' + : 'line'; + } else if (path._closed) { + if (segments.length === 8 + && isArc(0) && isArc(2) && isArc(4) && isArc(6) + && isColinear(1, 5) && isColinear(3, 7)) { + return 'roundrect'; + } else if (segments.length === 4 + && isArc(0) && isArc(1) && isArc(2) && isArc(3)) { + return Numerical.isZero(getDistance(segments, 0, 2) + - getDistance(segments, 1, 3)) + ? 'circle' + : 'ellipse'; + } + } + return 'path'; + } + + function exportGroup(item) { + var attrs = getTransform(item), + children = item._children; + var node = createElement('g', attrs); + for (var i = 0, l = children.length; i < l; i++) { + var child = children[i]; + var childNode = exportSVG(child); + if (childNode) { + if (child.isClipMask()) { + var clip = createElement('clipPath'); + clip.appendChild(childNode); + setDefinition(child, clip, 'clip'); + setAttributes(node, { + 'clip-path': 'url(#' + clip.id + ')' + }); + } else { + node.appendChild(childNode); + } + } + } + return node; + } + + function exportRaster(item) { + var attrs = getTransform(item, true), + size = item.getSize(); + attrs.x -= size.width / 2; + attrs.y -= size.height / 2; + attrs.width = size.width; + attrs.height = size.height; + attrs.href = item.toDataURL(); + return createElement('image', attrs); + } + + function exportPath(item) { + var segments = item._segments, + center = item.getPosition(true), + type = determineType(item, segments), + angle = determineAngle(item, segments, type, center), + attrs; + switch (type) { + case 'empty': + return null; + case 'path': + var data = item.getPathData(); + attrs = data && { d: data }; + break; + case 'polyline': + case 'polygon': + var parts = []; + for(i = 0, l = segments.length; i < l; i++) + parts.push(formatter.point(segments[i]._point)); + attrs = { + points: parts.join(' ') + }; + break; + case 'rect': + var width = getDistance(segments, 0, 3), + height = getDistance(segments, 0, 1), + point = segments[1]._point.rotate(-angle, center); + attrs = { + x: point.x, + y: point.y, + width: width, + height: height + }; + break; + case 'roundrect': + type = 'rect'; + var width = getDistance(segments, 1, 6), + height = getDistance(segments, 0, 3), + rx = (width - getDistance(segments, 0, 7)) / 2, + ry = (height - getDistance(segments, 1, 2)) / 2, + left = segments[3]._point, + right = segments[4]._point, + point = left.subtract(right.subtract(left).normalize(rx)) + .rotate(-angle, center); + attrs = { + x: point.x, + y: point.y, + width: width, + height: height, + rx: rx, + ry: ry + }; + break; + case'line': + var first = segments[0]._point, + last = segments[segments.length - 1]._point; + attrs = { + x1: first.x, + y1: first.y, + x2: last.x, + y2: last.y + }; + break; + case 'circle': + var radius = getDistance(segments, 0, 2) / 2; + attrs = { + cx: center.x, + cy: center.y, + r: radius + }; + break; + case 'ellipse': + var rx = getDistance(segments, 2, 0) / 2, + ry = getDistance(segments, 3, 1) / 2; + attrs = { + cx: center.x, + cy: center.y, + rx: rx, + ry: ry + }; + break; + } + if (angle) { + attrs.transform = 'rotate(' + formatter.number(angle) + ',' + + formatter.point(center) + ')'; + item._gradientMatrix = new Matrix().rotate(-angle, center); + } + return createElement(type, attrs); + } + + function exportCompoundPath(item) { + var attrs = getTransform(item, true); + var data = item.getPathData(); + if (data) + attrs.d = data; + return createElement('path', attrs); + } + + function exportPlacedSymbol(item) { + var attrs = getTransform(item, true), + symbol = item.getSymbol(), + symbolNode = getDefinition(symbol, 'symbol'); + definition = symbol.getDefinition(), + bounds = definition.getBounds(); + if (!symbolNode) { + symbolNode = createElement('symbol', { + viewBox: formatter.rectangle(bounds) + }); + symbolNode.appendChild(exportSVG(definition)); + setDefinition(symbol, symbolNode, 'symbol'); + } + attrs.href = '#' + symbolNode.id; + attrs.x += bounds.x; + attrs.y += bounds.y; + attrs.width = formatter.number(bounds.width); + attrs.height = formatter.number(bounds.height); + return createElement('use', attrs); + } + + function exportGradient(color, item) { + var gradientNode = getDefinition(color, 'color'); + if (!gradientNode) { + var gradient = color.getGradient(), + radial = gradient._radial, + matrix = item._gradientMatrix, + origin = color.getOrigin().transform(matrix), + destination = color.getDestination().transform(matrix), + attrs; + if (radial) { + attrs = { + cx: origin.x, + cy: origin.y, + r: origin.getDistance(destination) + }; + var highlight = color.getHighlight(); + if (highlight) { + highlight = highlight.transform(matrix); + attrs.fx = highlight.x; + attrs.fy = highlight.y; + } + } else { + attrs = { + x1: origin.x, + y1: origin.y, + x2: destination.x, + y2: destination.y + }; + } + attrs.gradientUnits = 'userSpaceOnUse'; + gradientNode = createElement( + (radial ? 'radial' : 'linear') + 'Gradient', attrs); + var stops = gradient._stops; + for (var i = 0, l = stops.length; i < l; i++) { + var stop = stops[i], + stopColor = stop._color, + alpha = stopColor.getAlpha(); + attrs = { + offset: stop._rampPoint, + 'stop-color': stopColor.toCSS(true) + }; + if (alpha < 1) + attrs['stop-opacity'] = alpha; + gradientNode.appendChild(createElement('stop', attrs)); + } + setDefinition(color, gradientNode, 'color'); + } + return 'url(#' + gradientNode.id + ')'; + } + + function exportText(item) { + var node = createElement('text', getTransform(item, true)); + node.textContent = item._content; + return node; + } + + var exporters = { + group: exportGroup, + layer: exportGroup, + raster: exportRaster, + path: exportPath, + 'compound-path': exportCompoundPath, + 'placed-symbol': exportPlacedSymbol, + 'point-text': exportText + }; + + function applyStyle(item, node) { + var attrs = {}, + parent = item.getParent(); + + if (item._name != null) + attrs.id = item._name; + + Base.each(SVGStyles, function(entry) { + var get = entry.get, + type = entry.type, + value = item[get](); + if (!parent || !Base.equals(parent[get](), value)) { + if (type === 'color' && value != null) { + var alpha = value.getAlpha(); + if (alpha < 1) + attrs[entry.attribute + '-opacity'] = alpha; + } + attrs[entry.attribute] = value == null + ? 'none' + : type === 'number' + ? formatter.number(value) + : type === 'color' + ? value.gradient + ? exportGradient(value, item) + : value.toCSS(true) + : type === 'array' + ? value.join(',') + : type === 'lookup' + ? entry.toSVG[value] + : value; + } + }); + + if (attrs.opacity === 1) + delete attrs.opacity; + + if (item._visibility != null && !item._visibility) + attrs.visibility = 'hidden'; + + delete item._gradientMatrix; + return setAttributes(node, attrs); + } + + var definitions; + function getDefinition(item, type) { + if (!definitions) + definitions = { ids: {}, svgs: {} }; + return item && definitions.svgs[type + '-' + item._id]; + } + + function setDefinition(item, node, type) { + if (!definitions) + getDefinition(); + var id = definitions.ids[type] = (definitions.ids[type] || 0) + 1; + node.id = type + '-' + id; + definitions.svgs[type + '-' + item._id] = node; + } + + function exportDefinitions(node) { + if (!definitions) + return node; + var svg = node.nodeName.toLowerCase() === 'svg' && node, + defs = null; + for (var i in definitions.svgs) { + if (!defs) { + if (!svg) { + svg = createElement('svg'); + svg.appendChild(node); + } + defs = svg.insertBefore(createElement('defs'), svg.firstChild); + } + defs.appendChild(definitions.svgs[i]); + } + definitions = null; + return svg; + } + + function exportSVG(item) { + var exporter = exporters[item._type], + node = exporter && exporter(item, item._type); + if (node && item._data) + node.setAttribute('data-paper-data', JSON.stringify(item._data)); + return node && applyStyle(item, node); + } + + Item.inject({ + exportSVG: function() { + return exportDefinitions(exportSVG(this)); + } + }); + + Project.inject({ + exportSVG: function() { + var layers = this.layers, + size = this.view.getSize(), + node = createElement('svg', { + x: 0, + y: 0, + width: size.width, + height: size.height, + version: '1.1', + xmlns: 'http://www.w3.org/2000/svg', + 'xmlns:xlink': 'http://www.w3.org/1999/xlink' + }); + for (var i = 0, l = layers.length; i < l; i++) + node.appendChild(exportSVG(layers[i])); + return exportDefinitions(node); + } + }); +}; + +new function() { + + function getValue(node, name, isString, allowNull) { + var namespace = SVGNamespaces[name], + value = namespace + ? node.getAttributeNS(namespace, name) + : node.getAttribute(name); + if (value === 'null') + value = null; + return value == null + ? allowNull + ? null + : isString + ? '' + : 0 + : isString + ? value + : parseFloat(value); + } + + function getPoint(node, x, y, allowNull) { + x = getValue(node, x, false, allowNull); + y = getValue(node, y, false, allowNull); + return allowNull && x == null && y == null ? null + : new Point(x || 0, y || 0); + } + + function getSize(node, w, h, allowNull) { + w = getValue(node, w, false, allowNull); + h = getValue(node, h, false, allowNull); + return allowNull && w == null && h == null ? null + : new Size(w || 0, h || 0); + } + + function convertValue(value, type, lookup) { + return value === 'none' + ? null + : type === 'number' + ? parseFloat(value) + : type === 'array' + ? value ? value.split(/[\s,]+/g).map(parseFloat) : [] + : type === 'color' + ? getDefinition(value) || value + : type === 'lookup' + ? lookup[value] + : value; + } + + function importGroup(node, type) { + var nodes = node.childNodes, + clip = type === 'clippath', + item = clip ? new CompoundPath() : new Group(), + project = item._project, + currentStyle = project._currentStyle, + children = []; + if (!clip) { + item._transformContent = false; + item = applyAttributes(item, node); + project._currentStyle = item._style.clone(); + } + for (var i = 0, l = nodes.length; i < l; i++) { + var childNode = nodes[i], + child; + if (childNode.nodeType == 1 && (child = importSVG(childNode))) { + if (clip && child instanceof CompoundPath) { + children.push.apply(children, child.removeChildren()); + child.remove(); + } else if (!(child instanceof Symbol)) { + children.push(child); + } + } + } + item.addChildren(children); + if (clip) + item = applyAttributes(item.reduce(), node); + project._currentStyle = currentStyle; + if (clip || type === 'defs') { + item.remove(); + item = null; + } + return item; + } + + function importPoly(node, type) { + var path = new Path(), + points = node.points; + path.moveTo(points.getItem(0)); + for (var i = 1, l = points.numberOfItems; i < l; i++) + path.lineTo(points.getItem(i)); + if (type === 'polygon') + path.closePath(); + return path; + } + + function importPath(node) { + var data = node.getAttribute('d'), + path = data.match(/m/gi).length > 1 + ? new CompoundPath() + : new Path(); + path.setPathData(data); + return path; + } + + function importGradient(node, type) { + var nodes = node.childNodes, + stops = []; + for (var i = 0, l = nodes.length; i < l; i++) { + var child = nodes[i]; + if (child.nodeType == 1) + stops.push(applyAttributes(new GradientStop(), child)); + } + var isRadial = type === 'radialgradient', + gradient = new Gradient(stops, isRadial), + origin, destination, highlight; + if (isRadial) { + origin = getPoint(node, 'cx', 'cy'); + destination = origin.add(getValue(node, 'r'), 0); + highlight = getPoint(node, 'fx', 'fy', true); + } else { + origin = getPoint(node, 'x1', 'y1'); + destination = getPoint(node, 'x2', 'y2'); + } + applyAttributes( + new Color(gradient, origin, destination, highlight), node); + return null; + } + + var importers = { + g: importGroup, + svg: importGroup, + clippath: importGroup, + polygon: importPoly, + polyline: importPoly, + path: importPath, + lineargradient: importGradient, + radialgradient: importGradient, + + image: function (node) { + var raster = new Raster(getValue(node, 'href', true)); + raster.attach('load', function() { + var size = getSize(node, 'width', 'height'); + this.setSize(size); + this.translate(getPoint(node, 'x', 'y').add(size.divide(2))); + }); + return raster; + }, + + symbol: function(node, type) { + return new Symbol(importGroup(node, type), true); + }, + + defs: importGroup, + + use: function(node) { + var id = (getValue(node, 'href', true) || '').substring(1), + definition = definitions[id], + point = getPoint(node, 'x', 'y'); + return definition + ? definition instanceof Symbol + ? definition.place(point) + : definition.clone().translate(point) + : null; + }, + + circle: function(node) { + return new Path.Circle(getPoint(node, 'cx', 'cy'), + getValue(node, 'r')); + }, + + ellipse: function(node) { + var center = getPoint(node, 'cx', 'cy'), + radius = getSize(node, 'rx', 'ry'); + return new Path.Ellipse(new Rectangle(center.subtract(radius), + center.add(radius))); + }, + + rect: function(node) { + var point = getPoint(node, 'x', 'y'), + size = getSize(node, 'width', 'height'), + radius = getSize(node, 'rx', 'ry'); + return new Path.Rectangle(new Rectangle(point, size), radius); + }, + + line: function(node) { + return new Path.Line(getPoint(node, 'x1', 'y1'), + getPoint(node, 'x2', 'y2')); + }, + + text: function(node) { + var text = new PointText(getPoint(node, 'x', 'y', false) + .add(getPoint(node, 'dx', 'dy', false))); + text.setContent(node.textContent.trim() || ''); + return text; + } + }; + + function applyTransform(item, value, name, node) { + var transforms = (node.getAttribute(name) || '').split(/\)\s*/g), + matrix = new Matrix(); + for (var i = 0, l = transforms.length; i < l; i++) { + var transform = transforms[i]; + if (!transform) + break; + var parts = transform.split('('), + command = parts[0], + v = parts[1].split(/[\s,]+/g); + for (var j = 0, m = v.length; j < m; j++) + v[j] = parseFloat(v[j]); + switch (command) { + case 'matrix': + matrix.concatenate( + new Matrix(v[0], v[2], v[1], v[3], v[4], v[5])); + break; + case 'rotate': + matrix.rotate(v[0], v[1], v[2]); + break; + case 'translate': + matrix.translate(v[0], v[1]); + break; + case 'scale': + matrix.scale(v); + break; + case 'skewX': + case 'skewY': + var value = Math.tan(v[0] * Math.PI / 180), + isX = command == 'skewX'; + matrix.shear(isX ? value : 0, isX ? 0 : value); + break; + } + } + item.transform(matrix); + } + + function applyOpacity(item, value, name) { + var color = item[name === 'fill-opacity' ? 'getFillColor' + : 'getStrokeColor'](); + if (color) + color.setAlpha(parseFloat(value)); + } + + var attributes = Base.merge(Base.each(SVGStyles, function(entry) { + this[entry.attribute] = function(item, value) { + item[entry.set]( + convertValue(value, entry.type, entry.fromSVG)); + }; + }, {}), { + id: function(item, value) { + definitions[value] = item; + if (item.setName) + item.setName(value); + }, + + 'clip-path': function(item, value) { + var clip = getDefinition(value); + if (clip) { + clip = clip.clone(); + clip.setClipMask(true); + if (item instanceof Group) { + item.insertChild(0, clip); + } else { + return new Group(clip, item); + } + } + }, + + gradientTransform: applyTransform, + transform: applyTransform, + + 'fill-opacity': applyOpacity, + 'stroke-opacity': applyOpacity, + + visibility: function(item, value) { + item.setVisible(value === 'visible'); + }, + + 'stop-color': function(item, value) { + if (item.setColor) + item.setColor(value); + }, + + 'stop-opacity': function(item, value) { + if (item._color) + item._color.setAlpha(parseFloat(value)); + }, + + offset: function(item, value) { + var percentage = value.match(/(.*)%$/); + item.setRampPoint(percentage + ? percentage[1] / 100 + : parseFloat(value)); + }, + + viewBox: function(item, value, name, node, styles) { + var rect = new Rectangle(convertValue(value, 'array')), + size = getSize(node, 'width', 'height', true); + if (item instanceof Group) { + var scale = size ? rect.getSize().divide(size) : 1, + matrix = new Matrix().translate(rect.getPoint()).scale(scale); + item.transform(matrix.inverted()); + } else if (item instanceof Symbol) { + if (size) + rect.setSize(size); + var clip = getAttribute(node, 'overflow', styles) != 'visible', + group = item._definition; + if (clip && !rect.contains(group.getBounds())) { + clip = new Path.Rectangle(rect).transform(group._matrix); + clip.setClipMask(true); + group.addChild(clip); + } + } + } + }); + + function getAttribute(node, name, styles) { + var attr = node.attributes[name], + value = attr && attr.value; + if (!value) { + var style = Base.camelize(name); + value = node.style[style]; + if (!value && styles.node[style] !== styles.parent[style]) + value = styles.node[style]; + } + return !value + ? undefined + : value === 'none' + ? null + : value; + } + + function applyAttributes(item, node) { + var styles = { + node: DomElement.getStyles(node) || {}, + parent: DomElement.getStyles(node.parentNode) || {} + }; + Base.each(attributes, function(apply, name) { + var value = getAttribute(node, name, styles); + if (value !== undefined) + item = Base.pick(apply(item, value, name, node, styles), item); + }); + return item; + } + + var definitions = {}; + function getDefinition(value) { + var match = value && value.match(/\((?:#|)([^)']+)/); + return match && definitions[match[1]]; + } + + function importSVG(node, clearDefs) { + if (typeof node === 'string') + node = new DOMParser().parseFromString(node, 'image/svg+xml'); + var type = node.nodeName.toLowerCase(), + importer = importers[type], + item = importer && importer(node, type), + data = node.getAttribute('data-paper-data'); + if (item && !(item instanceof Group)) + item = applyAttributes(item, node); + if (item && data) + item._data = JSON.parse(data); + if (clearDefs) + definitions = {}; + return item; + } + + Item.inject({ + importSVG: function(node) { + return this.addChild(importSVG(node, true)); + } + }); + + Project.inject({ + importSVG: function(node) { + this.activate(); + return importSVG(node, true); + } + }); +}; + +paper = new (PaperScope.inject(Base.merge(Base.exports, { + enumerable: true, + Base: Base, + Numerical: Numerical, + DomElement: DomElement, + DomEvent: DomEvent +})))(); + +if (typeof define === 'function' && define.amd) + define(paper); + +return paper; +}; + diff --git a/dist/paper-core.min.js b/dist/paper-core.min.js new file mode 100644 index 00000000..f2dca950 --- /dev/null +++ b/dist/paper-core.min.js @@ -0,0 +1,36 @@ +/*! + * Paper.js v0.9.5 - The Swiss Army Knife of Vector Graphics Scripting. + * http://paperjs.org/ + * + * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey + * http://lehni.org/ & http://jonathanpuckey.com/ + * + * Distributed under the MIT license. See LICENSE file for details. + * + * All rights reserved. + * + * Date: Wed Jun 26 19:42:04 2013 -0700 + * + *** + * + * straps.js - Class inheritance library with support for bean-style accessors + * + * Copyright (c) 2006 - 2013 Juerg Lehni + * http://lehni.org/ + * + * Distributed under the MIT license. + * + *** + * + * acorn.js + * http://marijnhaverbeke.nl/acorn/ + * + * Acorn is a tiny, fast JavaScript parser written in JavaScript, + * created by Marijn Haverbeke and released under an MIT license. + * + */ +var paper=new function(){var t=new function(){function e(t,e,n,i,r,a){function h(i,s,a,h){var s=s||(s=d(e,i))&&(s.get?s:s.value);"string"==typeof s&&"#"===s[0]&&(s=e[s.substring(1)]||s);var l,c="function"==typeof s,_=s,g=r||c?s&&s.get?i in t:t[i]:null;!(a||void 0!==s&&e.hasOwnProperty(i))||r&&g||(c&&g&&(s.base=g),c&&u&&0===s.length&&(l=i.match(/^(get|is)(([A-Z])(.*))$/))&&u.push([l[3].toLowerCase()+l[4],l[2]]),_&&!c&&_.get||(_={value:_,writable:!0}),(d(t,i)||{configurable:!0}).configurable&&(_.configurable=!0,_.enumerable=n),f(t,i,_)),!h||!c||r&&h[i]||(h[i]=function(e){return e&&t[i].apply(e,o.call(arguments,1))})}var u;if(e){u=[];for(var l in e)e.hasOwnProperty(l)&&!s.test(l)&&h(l,null,!0,a);h("toString"),h("valueOf");for(var c=0,_=u&&u.length;_>c;c++)try{var g=u[c],v=g[1];h(g[0],{get:t["get"+v]||t["is"+v],set:t["set"+v]},!0)}catch(m){}}return t}function n(e,n,i,s){try{e&&(s||void 0===s&&l(e)?h:u).call(e,n,i=i||e)}catch(r){if(r!==t.stop)throw r}return i}function i(t){return n(t,function(t,e){this[e]=t},new t.constructor)}var s=/^(statics|generics|preserve|enumerable|prototype|toString|valueOf)$/,r=Object.prototype.toString,a=Array.prototype,o=a.slice,h=a.forEach||function(t,e){for(var n=0,i=this.length;i>n;n++)t.call(e,this[n],n,this)},u=function(t,e){for(var n in this)this.hasOwnProperty(n)&&t.call(e,this[n],n,this)},l=Array.isArray=Array.isArray||function(t){return"[object Array]"===r.call(t)},c=Object.create||function(t){return{__proto__:t}},d=Object.getOwnPropertyDescriptor||function(t,e){var n=t.__lookupGetter__&&t.__lookupGetter__(e);return n?{get:n,set:t.__lookupSetter__(e),enumerable:!0,configurable:!0}:t.hasOwnProperty(e)?{value:t[e],enumerable:!0,configurable:!0,writable:!0}:null},_=Object.defineProperty||function(t,e,n){return(n.get||n.set)&&t.__defineGetter__?(n.get&&t.__defineGetter__(e,n.get),n.set&&t.__defineSetter__(e,n.set)):t[e]=n.value,t},f=function(t,e,n){return delete t[e],_(t,e,n)};return e(function(){},{inject:function(t){if(t){var n=this.prototype,i=Object.getPrototypeOf(n).constructor,s=t.statics===!0?t:t.statics;s!=t&&e(n,t,t.enumerable,i&&i.prototype,t.preserve,t.generics&&this),e(this,s,!0,i,t.preserve)}for(var r=1,a=arguments.length;a>r;r++)this.inject(arguments[r]);return this},extend:function(){for(var t,n=this,i=0,s=arguments.length;s>i&&!(t=arguments[i].initialize);i++);return t=t||function(){n.apply(this,arguments)},t.prototype=c(this.prototype),f(t.prototype,"constructor",{value:t,writable:!0,configurable:!0}),e(t,this,!0),arguments.length?this.inject.apply(t,arguments):t}},!0).inject({inject:function(){for(var t=0,n=arguments.length;n>t;t++)e(this,arguments[t],arguments[t].enumerable);return this},extend:function(){var t=c(this);return t.inject.apply(t,arguments)},each:function(t,e){return n(this,t,e)},clone:function(){return i(this)},statics:{each:n,clone:i,define:f,describe:d,create:function(t){return c(t.prototype)},isPlainObject:function(e){var n=null!=e&&e.constructor;return n&&(n===Object||n===t||"Object"===n.name)},check:function(t){return!(!t&&0!==t)},pick:function(){for(var t=0,e=arguments.length;e>t;t++)if(void 0!==arguments[t])return arguments[t];return null},stop:{}}})};t.inject({generics:!0,clone:function(){return new this.constructor(this)},toString:function(){return null!=this._id?(this._class||"Object")+(this._name?" '"+this._name+"'":" @"+this._id):"{ "+t.each(this,function(t,e){if(!/^_/.test(e)){var n=typeof t;this.push(e+": "+("number"===n?r.instance.number(t):"string"===n?"'"+t+"'":t))}},[]).join(", ")+" }"},exportJSON:function(e){return t.exportJSON(this,e)},toJSON:function(){return t.serialize(this)},_set:function(e){if(e&&t.isPlainObject(e)){for(var n in e)e.hasOwnProperty(n)&&n in this&&(this[n]=e[n]);return!0}},statics:{exports:{},extend:function ee(){var e=ee.base.apply(this,arguments),n=e.prototype._class;return n&&!t.exports[n]&&(t.exports[n]=e),e},equals:function(e,n){function i(t,e){for(var n in t)if(t.hasOwnProperty(n)&&void 0===e[n])return!1;return!0}if(e===n)return!0;if(e&&e.equals)return e.equals(n);if(n&&n.equals)return n.equals(e);if(Array.isArray(e)&&Array.isArray(n)){if(e.length!==n.length)return!1;for(var s=0,r=e.length;r>s;s++)if(!t.equals(e[s],n[s]))return!1;return!0}if(e&&"object"==typeof e&&n&&"object"==typeof n){if(!i(e,n)||!i(n,e))return!1;for(var s in e)if(e.hasOwnProperty(s)&&!t.equals(e[s],n[s]))return!1;return!0}return!1},read:function(e,n,i,s,r){if(this===t){var a=this.peek(e,n);return e._index++,e._read=1,a}var o=this.prototype,h=o._readIndex,u=n||h&&e._index||0;i||(i=e.length-u);var l=e[u];return l instanceof this||s&&null==l&&1>=i?(h&&(e._index=u+1),l&&r?l.clone():l):(l=t.create(this),h&&(l._read=!0),l=l.initialize.apply(l,u>0||ia;a++)r.push(Array.isArray(s=t[a])?this.read(s,0,0,n,i):this.read(t,a,1,n,i));return r},readNamed:function(t,e,n,i,s,r){var a=this.getNamed(t,e);return this.read(null!=a?[a]:t,n,i,s,r)},getNamed:function(e,n){var i=e[0];return void 0===e._hasObject&&(e._hasObject=1===e.length&&t.isPlainObject(i)),e._hasObject?n?i[n]:i:void 0},hasNamed:function(t,e){return!!this.getNamed(t,e)},isPlainValue:function(t){return this.isPlainObject(t)||Array.isArray(t)},serialize:function(e,n,i,s){n=n||{};var a,o=!s;if(o&&(n.formatter=new r(n.precision),s={length:0,definitions:{},references:{},add:function(t,e){var n="#"+t._id,i=this.references[n];if(!i){this.length++;var s=e.call(t),r=t._class;r&&s[0]!==r&&s.unshift(r),this.definitions[n]=s,i=this.references[n]=[n]}return i}}),e&&e._serialize){a=e._serialize(n,s);var h=e._class;!h||i||a._compact||a[0]===h||a.unshift(h)}else if(Array.isArray(e)){a=[];for(var u=0,l=e.length;l>u;u++)a[u]=t.serialize(e[u],n,i,s);i&&(a._compact=!0)}else if(t.isPlainObject(e)){a={};for(var u in e)e.hasOwnProperty(u)&&(a[u]=t.serialize(e[u],n,i,s))}else a="number"==typeof e?n.formatter.number(e,n.precision):e;return o&&s.length>0?[["dictionary",s.definitions],a]:a},deserialize:function(e,n){var i=e;if(n=n||{},Array.isArray(e)){var s=e[0],r="dictionary"===s;if(!r){if(n.dictionary&&1==e.length&&/^#/.test(s))return n.dictionary[s];s=t.exports[s]}i=[];for(var a=s?1:0,o=e.length;o>a;a++)i.push(t.deserialize(e[a],n));if(r)n.dictionary=i[0];else if(s){var h=i;i=t.create(s),s.apply(i,h)}}else if(t.isPlainObject(e)){i={};for(var u in e)i[u]=t.deserialize(e[u],n)}return i},exportJSON:function(e,n){return JSON.stringify(t.serialize(e,n))},importJSON:function(e){return t.deserialize("string"==typeof e?JSON.parse(e):e)},splice:function(t,e,n,i){var s=e&&e.length,r=void 0===n;n=r?t.length:n,n>t.length&&(n=t.length);for(var a=0;s>a;a++)e[a]._index=n+a;if(r)return t.push.apply(t,e),[];var o=[n,i];e&&o.push.apply(o,e);for(var h=t.splice.apply(t,o),a=0,u=h.length;u>a;a++)delete h[a]._index;for(var a=n+s,u=t.length;u>a;a++)t[a]._index=a;return h},merge:function(){return t.each(arguments,function(e){t.each(e,function(t,e){this[e]=t},this)},new t,!0)},capitalize:function(t){return t.replace(/\b[a-z]/g,function(t){return t.toUpperCase()})},camelize:function(t){return t.replace(/-(.)/g,function(t,e){return e.toUpperCase()})},hyphenate:function(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}});var e={attach:function(e,n){if("string"!=typeof e)return t.each(e,function(t,e){this.attach(e,t)},this),void 0;var i=this._eventTypes[e];if(i){var s=this._handlers=this._handlers||{};s=s[e]=s[e]||[],-1==s.indexOf(n)&&(s.push(n),i.install&&1==s.length&&i.install.call(this,e))}},detach:function(e,n){if("string"!=typeof e)return t.each(e,function(t,e){this.detach(e,t)},this),void 0;var i,s=this._eventTypes[e],r=this._handlers&&this._handlers[e];s&&r&&(!n||-1!=(i=r.indexOf(n))&&1==r.length?(s.uninstall&&s.uninstall.call(this,e),delete this._handlers[e]):-1!=i&&r.splice(i,1))},once:function(t,e){this.attach(t,function(){e.apply(this,arguments),this.detach(t,e)})},fire:function(e,n){var i=this._handlers&&this._handlers[e];if(!i)return!1;var s=[].slice.call(arguments,1);return t.each(i,function(t){t.apply(this,s)===!1&&n&&n.stop&&n.stop()},this),!0},responds:function(t){return!(!this._handlers||!this._handlers[t])},on:"#attach",off:"#detach",trigger:"#fire",statics:{inject:function ne(){for(var e=0,n=arguments.length;n>e;e++){var i=arguments[e],s=i._events;if(s){var r={};t.each(s,function(e,n){var s="string"==typeof e,a=s?e:n,o=t.capitalize(a),h=a.substring(2).toLowerCase();r[h]=s?{}:e,a="_"+a,i["get"+o]=function(){return this[a]},i["set"+o]=function(t){t?this.attach(h,t):this[a]&&this.detach(h,this[a]),this[a]=t}}),i._eventTypes=r}ne.base.call(this,i)}return this}}},n=t.extend({_class:"PaperScope",initialize:function ie(t){if(paper=this,this.project=null,this.projects=[],this.tools=[],this.palettes=[],this._id=t&&(t.getAttribute("id")||t.src)||"paperscope-"+ie._id++,t&&t.setAttribute("id",this._id),ie._scopes[this._id]=this,!this.support){var e=$.getContext(1,1);ie.prototype.support={nativeDash:"setLineDash"in e||"mozDash"in e,nativeBlendModes:K.nativeModes},$.release(e)}},version:"0.9.5",getView:function(){return this.project&&this.project.view},getTool:function(){return this._tool||(this._tool=new U),this._tool},evaluate:function(t){var e=paper.PaperScript.evaluate(t,this);return V.updateFocus(),e},install:function(e){var n=this;t.each(["project","view","tool"],function(i){t.define(e,i,{configurable:!0,get:function(){return n[i]}})});for(var i in this)/^(version|_id)/.test(i)||i in e||(e[i]=this[i])},setup:function(t){return paper=this,this.project=new v(t),this},clear:function(){for(var t=this.projects.length-1;t>=0;t--)this.projects[t].remove();for(var t=this.tools.length-1;t>=0;t--)this.tools[t].remove();for(var t=this.palettes.length-1;t>=0;t--)this.palettes[t].remove()},remove:function(){this.clear(),delete n._scopes[this._id]},statics:new function(){function t(t){return t+="Attribute",function(e,n){return e[t](n)||e[t]("data-paper-"+n)}}return{_scopes:{},_id:0,get:function(t){return"object"==typeof t&&(t=t.getAttribute("id")),this._scopes[t]||null},getAttribute:t("get"),hasAttribute:t("has")}}}),s=t.extend(e,{initialize:function(t){this._scope=paper,this._index=this._scope[this._list].push(this)-1,(t||!this._scope[this._reference])&&this.activate()},activate:function(){if(!this._scope)return!1;var t=this._scope[this._reference];return t&&t!=this&&t.fire("deactivate"),this._scope[this._reference]=this,this.fire("activate",t),!0},isActive:function(){return this._scope[this._reference]===this},remove:function(){return null==this._index?!1:(t.splice(this._scope[this._list],null,this._index,1),this._scope[this._reference]==this&&(this._scope[this._reference]=null),this._scope=null,!0)}}),r=t.extend({initialize:function(t){this.precision=t||5,this.multiplier=Math.pow(10,this.precision)},number:function(t){return Math.round(t*this.multiplier)/this.multiplier},point:function(t,e){return this.number(t.x)+(e||",")+this.number(t.y)},size:function(t,e){return this.number(t.width)+(e||",")+this.number(t.height)},rectangle:function(t,e){return this.point(t,e)+(e||",")+this.size(t,e)}});r.instance=new r(5);var a=new function(){var t=[[.5773502691896257],[0,.7745966692414834],[.33998104358485626,.8611363115940526],[0,.5384693101056831,.906179845938664],[.2386191860831969,.6612093864662645,.932469514203152],[0,.4058451513773972,.7415311855993945,.9491079123427585],[.1834346424956498,.525532409916329,.7966664774136267,.9602898564975363],[0,.3242534234038089,.6133714327005904,.8360311073266358,.9681602395076261],[.14887433898163122,.4333953941292472,.6794095682990244,.8650633666889845,.9739065285171717],[0,.26954315595234496,.5190961292068118,.7301520055740494,.8870625997680953,.978228658146057],[.1252334085114689,.3678314989981802,.5873179542866175,.7699026741943047,.9041172563704749,.9815606342467192],[0,.2304583159551348,.44849275103644687,.6423493394403402,.8015780907333099,.9175983992229779,.9841830547185881],[.10805494870734367,.31911236892788974,.5152486363581541,.6872929048116855,.827201315069765,.9284348836635735,.9862838086968123],[0,.20119409399743451,.3941513470775634,.5709721726085388,.7244177313601701,.8482065834104272,.937273392400706,.9879925180204854],[.09501250983763744,.2816035507792589,.45801677765722737,.6178762444026438,.755404408355003,.8656312023878318,.9445750230732326,.9894009349916499]],e=[[1],[.8888888888888888,.5555555555555556],[.6521451548625461,.34785484513745385],[.5688888888888889,.47862867049936647,.23692688505618908],[.46791393457269104,.3607615730481386,.17132449237917036],[.4179591836734694,.3818300505051189,.27970539148927664,.1294849661688697],[.362683783378362,.31370664587788727,.22238103445337448,.10122853629037626],[.3302393550012598,.31234707704000286,.26061069640293544,.1806481606948574,.08127438836157441],[.29552422471475287,.26926671930999635,.21908636251598204,.1494513491505806,.06667134430868814],[.2729250867779006,.26280454451024665,.23319376459199048,.18629021092773426,.1255803694649046,.05566856711617366],[.24914704581340277,.2334925365383548,.20316742672306592,.16007832854334622,.10693932599531843,.04717533638651183],[.2325515532308739,.22628318026289723,.2078160475368885,.17814598076194574,.13887351021978725,.09212149983772845,.04048400476531588],[.2152638534631578,.2051984637212956,.18553839747793782,.15720316715819355,.12151857068790319,.08015808715976021,.03511946033175186],[.2025782419255613,.19843148532711158,.1861610000155622,.16626920581699392,.13957067792615432,.10715922046717194,.07036604748810812,.03075324199611727],[.1894506104550685,.18260341504492358,.16915651939500254,.14959598881657674,.12462897125553388,.09515851168249279,.062253523938647894,.027152459411754096]],n=Math.abs,i=Math.sqrt,s=Math.pow,r=Math.cos,o=Math.PI;return{TOLERANCE:1e-5,EPSILON:1e-11,KAPPA:4*(i(2)-1)/3,isZero:function(t){return n(t)<=this.EPSILON},integrate:function(n,i,s,r){for(var a=t[r-2],o=e[r-2],h=.5*(s-i),u=h+i,l=0,c=r+1>>1,d=1&r?o[l++]*n(u):0;c>l;){var _=h*a[l];d+=o[l++]*(n(u+_)+n(u-_))}return h*d},findRoot:function(t,e,i,s,r,a,o){for(var h=0;a>h;h++){var u=t(i),l=u/e(i);if(n(l)0?(r=i,i=s>=c?.5*(s+r):c):(s=i,i=c>=r?.5*(s+r):c)}},solveQuadratic:function(t,e,s,r){var a=this.EPSILON;if(n(t)=a?(r[0]=-s/e,1):n(s)o)return 0;o=i(o),t*=2;var h=0;return r[h++]=(-e-o)/t,o>0&&(r[h++]=(-e+o)/t),h},solveCubic:function(t,e,h,u,l){var c=this.EPSILON;if(n(t)0?1:-1;return l[0]=2*-p*m-e,l[1]=p*m-e,2}if(0>v){var m=i(_),y=Math.acos(f/(m*m*m))/3,w=-2*m,x=2*o/3;return l[0]=w*r(y)-e,l[1]=w*r(y+x)-e,l[2]=w*r(y-x)-e,3}var b=(f>0?-1:1)*s(n(f)+i(v),1/3);return l[0]=b+_/b-e,1}}},o=t.extend({_class:"Point",_readIndex:!0,initialize:function(t,e){var n=typeof t;if("number"===n){var i="number"==typeof e;this.x=t,this.y=i?e:t,this._read&&(this._read=i?2:1)}else"undefined"===n||null===t?(this.x=this.y=0,this._read&&(this._read=null===t?1:0)):(Array.isArray(t)?(this.x=t[0],this.y=t.length>1?t[1]:t[0]):null!=t.x?(this.x=t.x,this.y=t.y):null!=t.width?(this.x=t.width,this.y=t.height):null!=t.angle?(this.x=t.length,this.y=0,this.setAngle(t.angle)):(this.x=this.y=0,this._read&&(this._read=0)),this._read&&(this._read=1))},set:function(t,e){return this.x=t,this.y=e,this},equals:function(t){return t===this||t&&(this.x===t.x&&this.y===t.y||Array.isArray(t)&&this.x===t[0]&&this.y===t[1])||!1},clone:function(){return new o(this.x,this.y)},toString:function(){var t=r.instance;return"{ x: "+t.number(this.x)+", y: "+t.number(this.y)+" }"},_serialize:function(t){var e=t.formatter;return[e.number(this.x),e.number(this.y)]},add:function(t){return t=o.read(arguments),new o(this.x+t.x,this.y+t.y)},subtract:function(t){return t=o.read(arguments),new o(this.x-t.x,this.y-t.y)},multiply:function(t){return t=o.read(arguments),new o(this.x*t.x,this.y*t.y)},divide:function(t){return t=o.read(arguments),new o(this.x/t.x,this.y/t.y)},modulo:function(t){return t=o.read(arguments),new o(this.x%t.x,this.y%t.y)},negate:function(){return new o(-this.x,-this.y)},transform:function(t){return t?t._transformPoint(this):this},getDistance:function(t,e){t=o.read(arguments);var n=t.x-this.x,i=t.y-this.y,s=n*n+i*i;return e?s:Math.sqrt(s)},getLength:function(){var t=this.x*this.x+this.y*this.y;return arguments.length&&arguments[0]?t:Math.sqrt(t)},setLength:function(t){if(this.isZero()){var e=this._angle||0;this.set(Math.cos(e)*t,Math.sin(e)*t)}else{var n=t/this.getLength();a.isZero(n)&&this.getAngle(),this.set(this.x*n,this.y*n)}return this},normalize:function(t){void 0===t&&(t=1);var e=this.getLength(),n=0!==e?t/e:0,i=new o(this.x*n,this.y*n);return i._angle=this._angle,i},getAngle:function(){return 180*this.getAngleInRadians(arguments[0])/Math.PI},setAngle:function(t){if(t=this._angle=t*Math.PI/180,!this.isZero()){var e=this.getLength();this.set(Math.cos(t)*e,Math.sin(t)*e)}return this},getAngleInRadians:function(){if(void 0===arguments[0])return null==this._angle&&(this._angle=Math.atan2(this.y,this.x)),this._angle;var t=o.read(arguments),e=this.getLength()*t.getLength();return a.isZero(e)?0/0:Math.acos(this.dot(t)/e)},getAngleInDegrees:function(){return this.getAngle(arguments[0])},getQuadrant:function(){return this.x>=0?this.y>=0?1:4:this.y>=0?2:3},getDirectedAngle:function(t){return t=o.read(arguments),180*Math.atan2(this.cross(t),this.dot(t))/Math.PI},rotate:function(t,e){if(0===t)return this.clone();t=t*Math.PI/180;var n=e?this.subtract(e):this,i=Math.sin(t),s=Math.cos(t);return n=new o(n.x*s-n.y*i,n.y*s+n.x*i),e?n.add(e):n},isInside:function(t){return t.contains(this)},isClose:function(t,e){return this.getDistance(t)1?t[1]:t[0]):null!=t.width?(this.width=t.width,this.height=t.height):null!=t.x?(this.width=t.x,this.height=t.y):(this.width=this.height=0,this._read&&(this._read=0)),this._read&&(this._read=1))},set:function(t,e){return this.width=t,this.height=e,this},equals:function(t){return t===this||t&&(this.width===t.width&&this.height===t.height||Array.isArray(t)&&this.width===t[0]&&this.height===t[1])||!1},clone:function(){return new u(this.width,this.height)},toString:function(){var t=r.instance;return"{ width: "+t.number(this.width)+", height: "+t.number(this.height)+" }"},_serialize:function(t){var e=t.formatter;return[e.number(this.width),e.number(this.height)]},add:function(t){return t=u.read(arguments),new u(this.width+t.width,this.height+t.height)},subtract:function(t){return t=u.read(arguments),new u(this.width-t.width,this.height-t.height)},multiply:function(t){return t=u.read(arguments),new u(this.width*t.width,this.height*t.height)},divide:function(t){return t=u.read(arguments),new u(this.width/t.width,this.height/t.height)},modulo:function(t){return t=u.read(arguments),new u(this.width%t.width,this.height%t.height)},negate:function(){return new u(-this.width,-this.height)},isZero:function(){return a.isZero(this.width)&&a.isZero(this.height)},isNaN:function(){return isNaN(this.width)||isNaN(this.height)},statics:{min:function(t,e){return new u(Math.min(t.width,e.width),Math.min(t.height,e.height))},max:function(t,e){return new u(Math.max(t.width,e.width),Math.max(t.height,e.height))},random:function(){return new u(Math.random(),Math.random())}}},new function(){return t.each(["round","ceil","floor","abs"],function(t){var e=Math[t];this[t]=function(){return new u(e(this.width),e(this.height))}},{})}),c=u.extend({initialize:function(t,e,n,i){this._width=t,this._height=e,this._owner=n,this._setter=i},set:function(t,e,n){return this._width=t,this._height=e,n||this._owner[this._setter](this),this},getWidth:function(){return this._width},setWidth:function(t){this._width=t,this._owner[this._setter](this)},getHeight:function(){return this._height},setHeight:function(t){this._height=t,this._owner[this._setter](this)}}),d=t.extend({_class:"Rectangle",_readIndex:!0,initialize:function(e,n,i,s){var r=typeof e,a=0;if("number"===r?(this.x=e,this.y=n,this.width=i,this.height=s,a=4):"undefined"===r||null===e?(this.x=this.y=this.width=this.height=0,a=null===e?1:0):1===arguments.length&&(Array.isArray(e)?(this.x=e[0],this.y=e[1],this.width=e[2],this.height=e[3],a=1):void 0!==e.x||void 0!==e.width?(this.x=e.x||0,this.y=e.y||0,this.width=e.width||0,this.height=e.height||0,a=1):void 0===e.from&&void 0===e.to&&(this.x=this.y=this.width=this.height=0,this._set(e),a=1)),!a){var h=o.readNamed(arguments,"from"),l=t.peek(arguments);if(this.x=h.x,this.y=h.y,l&&void 0!==l.x||t.hasNamed(arguments,"to")){var c=o.readNamed(arguments,"to");this.width=c.x-h.x,this.height=c.y-h.y,this.width<0&&(this.x=c.x,this.width=-this.width),this.height<0&&(this.y=c.y,this.height=-this.height)}else{var d=u.read(arguments);this.width=d.width,this.height=d.height}a=arguments._index}this._read&&(this._read=a)},set:function(t,e,n,i){return this.x=t,this.y=e,this.width=n,this.height=i,this},clone:function(){return new d(this.x,this.y,this.width,this.height)},equals:function(e){return t.isPlainValue(e)&&(e=d.read(arguments)),e===this||e&&this.x===e.x&&this.y===e.y&&this.width===e.width&&this.height===e.height||!1},toString:function(){var t=r.instance;return"{ x: "+t.number(this.x)+", y: "+t.number(this.y)+", width: "+t.number(this.width)+", height: "+t.number(this.height)+" }"},_serialize:function(t){var e=t.formatter;return[e.number(this.x),e.number(this.y),e.number(this.width),e.number(this.height)]},getPoint:function(){return new(arguments[0]?o:h)(this.x,this.y,this,"setPoint")},setPoint:function(t){t=o.read(arguments),this.x=t.x,this.y=t.y},getSize:function(){return new(arguments[0]?u:c)(this.width,this.height,this,"setSize")},setSize:function(t){t=u.read(arguments),this._fixX&&(this.x+=(this.width-t.width)*this._fixX),this._fixY&&(this.y+=(this.height-t.height)*this._fixY),this.width=t.width,this.height=t.height,this._fixW=1,this._fixH=1},getLeft:function(){return this.x},setLeft:function(t){this._fixW||(this.width-=t-this.x),this.x=t,this._fixX=0},getTop:function(){return this.y},setTop:function(t){this._fixH||(this.height-=t-this.y),this.y=t,this._fixY=0},getRight:function(){return this.x+this.width},setRight:function(t){void 0!==this._fixX&&1!==this._fixX&&(this._fixW=0),this._fixW?this.x=t-this.width:this.width=t-this.x,this._fixX=1},getBottom:function(){return this.y+this.height},setBottom:function(t){void 0!==this._fixY&&1!==this._fixY&&(this._fixH=0),this._fixH?this.y=t-this.height:this.height=t-this.y,this._fixY=1},getCenterX:function(){return this.x+.5*this.width},setCenterX:function(t){this.x=t-.5*this.width,this._fixX=.5},getCenterY:function(){return this.y+.5*this.height},setCenterY:function(t){this.y=t-.5*this.height,this._fixY=.5},getCenter:function(){return new(arguments[0]?o:h)(this.getCenterX(),this.getCenterY(),this,"setCenter")},setCenter:function(t){return t=o.read(arguments),this.setCenterX(t.x),this.setCenterY(t.y),this},isEmpty:function(){return 0==this.width||0==this.height},contains:function(t){return t&&void 0!==t.width||4==(Array.isArray(t)?t:arguments).length?this._containsRectangle(d.read(arguments)):this._containsPoint(o.read(arguments))},_containsPoint:function(t){var e=t.x,n=t.y;return e>=this.x&&n>=this.y&&e<=this.x+this.width&&n<=this.y+this.height},_containsRectangle:function(t){var e=t.x,n=t.y;return e>=this.x&&n>=this.y&&e+t.width<=this.x+this.width&&n+t.height<=this.y+this.height},intersects:function(t){return t=d.read(arguments),t.x+t.width>this.x&&t.y+t.height>this.y&&t.x=this.x&&t.y+t.height>=this.y&&t.x<=this.x+this.width&&t.y<=this.y+this.height},intersect:function(t){t=d.read(arguments);var e=Math.max(this.x,t.x),n=Math.max(this.y,t.y),i=Math.min(this.x+this.width,t.x+t.width),s=Math.min(this.y+this.height,t.y+t.height);return new d(e,n,i-e,s-n)},unite:function(t){t=d.read(arguments);var e=Math.min(this.x,t.x),n=Math.min(this.y,t.y),i=Math.max(this.x+this.width,t.x+t.width),s=Math.max(this.y+this.height,t.y+t.height);return new d(e,n,i-e,s-n)},include:function(t){t=o.read(arguments);var e=Math.min(this.x,t.x),n=Math.min(this.y,t.y),i=Math.max(this.x+this.width,t.x),s=Math.max(this.y+this.height,t.y);return new d(e,n,i-e,s-n)},expand:function(t,e){return void 0===e&&(e=t),new d(this.x-t/2,this.y-e/2,this.width+t,this.height+e)},scale:function(t,e){return this.expand(this.width*t-this.width,this.height*(void 0===e?t:e)-this.height)}},new function(){return t.each([["Top","Left"],["Top","Right"],["Bottom","Left"],["Bottom","Right"],["Left","Center"],["Top","Center"],["Right","Center"],["Bottom","Center"]],function(t,e){var n=t.join(""),i=/^[RL]/.test(n);e>=4&&(t[1]+=i?"Y":"X");var s=t[i?0:1],r=t[i?1:0],a="get"+s,u="get"+r,l="set"+s,c="set"+r,d="get"+n,_="set"+n;this[d]=function(){return new(arguments[0]?o:h)(this[a](),this[u](),this,_)},this[_]=function(t){t=o.read(arguments),this[l](t.x),this[c](t.y)}},{})}),_=d.extend({initialize:function(t,e,n,i,s,r){this.set(t,e,n,i,!0),this._owner=s,this._setter=r},set:function(t,e,n,i,s){return this._x=t,this._y=e,this._width=n,this._height=i,s||this._owner[this._setter](this),this}},new function(){var e=d.prototype;return t.each(["x","y","width","height"],function(e){var n=t.capitalize(e),i="_"+e;this["get"+n]=function(){return this[i]},this["set"+n]=function(t){this[i]=t,this._dontNotify||this._owner[this._setter](this)}},t.each(["Point","Size","Center","Left","Top","Right","Bottom","CenterX","CenterY","TopLeft","TopRight","BottomLeft","BottomRight","LeftCenter","TopCenter","RightCenter","BottomCenter"],function(t){var n="set"+t;this[n]=function(){this._dontNotify=!0,e[n].apply(this,arguments),delete this._dontNotify,this._owner[this._setter](this)}},{isSelected:function(){return this._owner._boundsSelected},setSelected:function(t){var e=this._owner;e.setSelected&&(e._boundsSelected=t,e.setSelected(t||e._selectedSegmentState>0))}}))}),f=t.extend({_class:"Matrix",initialize:function se(t){var e=arguments.length,n=!0;if(6==e?this.set.apply(this,arguments):1==e?t instanceof se?this.set(t._a,t._c,t._b,t._d,t._tx,t._ty):Array.isArray(t)?this.set.apply(this,t):n=!1:0==e?this.reset():n=!1,!n)throw Error("Unsupported matrix parameters")},set:function(t,e,n,i,s,r){return this._a=t,this._c=e,this._b=n,this._d=i,this._tx=s,this._ty=r,this},_serialize:function(e){return t.serialize(this.getValues(),e)},clone:function(){return new f(this._a,this._c,this._b,this._d,this._tx,this._ty)},equals:function(t){return t===this||t&&this._a==t._a&&this._b==t._b&&this._c==t._c&&this._d==t._d&&this._tx==t._tx&&this._ty==t._ty||!1},toString:function(){var t=r.instance;return"[["+[t.number(this._a),t.number(this._b),t.number(this._tx)].join(", ")+"], ["+[t.number(this._c),t.number(this._d),t.number(this._ty)].join(", ")+"]]"},reset:function(){return this._a=this._d=1,this._c=this._b=this._tx=this._ty=0,this},scale:function(){var t=o.read(arguments),e=o.read(arguments,0,0,!0);return e&&this.translate(e),this._a*=t.x,this._c*=t.x,this._b*=t.y,this._d*=t.y,e&&this.translate(e.negate()),this},translate:function(t){t=o.read(arguments);var e=t.x,n=t.y;return this._tx+=e*this._a+n*this._b,this._ty+=e*this._c+n*this._d,this},rotate:function(t,e){e=o.read(arguments,1),t=t*Math.PI/180;var n=e.x,i=e.y,s=Math.cos(t),r=Math.sin(t),a=n-n*s+i*r,h=i-n*r-i*s,u=this._a,l=this._b,c=this._c,d=this._d;return this._a=s*u+r*l,this._b=-r*u+s*l,this._c=s*c+r*d,this._d=-r*c+s*d,this._tx+=a*u+h*l,this._ty+=a*c+h*d,this},shear:function(){var t=o.read(arguments),e=o.read(arguments,0,0,!0);e&&this.translate(e);var n=this._a,i=this._c;return this._a+=t.y*this._b,this._c+=t.y*this._d,this._b+=t.x*n,this._d+=t.x*i,e&&this.translate(e.negate()),this},isIdentity:function(){return 1==this._a&&0==this._c&&0==this._b&&1==this._d&&0==this._tx&&0==this._ty},isInvertible:function(){return!!this._getDeterminant()},isSingular:function(){return!this._getDeterminant()},concatenate:function(t){var e=this._a,n=this._b,i=this._c,s=this._d;return this._a=t._a*e+t._c*n,this._b=t._b*e+t._d*n,this._c=t._a*i+t._c*s,this._d=t._b*i+t._d*s,this._tx+=t._tx*e+t._ty*n,this._ty+=t._tx*i+t._ty*s,this},preConcatenate:function(t){var e=this._a,n=this._b,i=this._c,s=this._d,r=this._tx,a=this._ty;return this._a=t._a*e+t._b*i,this._b=t._a*n+t._b*s,this._c=t._c*e+t._d*i,this._d=t._c*n+t._d*s,this._tx=t._a*r+t._b*a+t._tx,this._ty=t._c*r+t._d*a+t._ty,this},transform:function(t,e,n,i,s){return arguments.length<5?this._transformPoint(o.read(arguments)):this._transformCoordinates(t,e,n,i,s)},_transformPoint:function(t,e,n){var i=t.x,s=t.y;return e||(e=new o),e.set(i*this._a+s*this._b+this._tx,i*this._c+s*this._d+this._ty,n)},_transformCoordinates:function(t,e,n,i,s){for(var r=e,a=i,o=e+2*s;o>r;){var h=t[r++],u=t[r++];n[a++]=h*this._a+u*this._b+this._tx,n[a++]=h*this._c+u*this._d+this._ty}return n},_transformCorners:function(t){var e=t.x,n=t.y,i=e+t.width,s=n+t.height,r=[e,n,i,n,i,s,e,s];return this._transformCoordinates(r,0,r,0,4)},_transformBounds:function(t,e,n){for(var i=this._transformCorners(t),s=i.slice(0,2),r=i.slice(),a=2;8>a;a++){var o=i[a],h=1&a;or[h]&&(r[h]=o)}return e||(e=new d),e.set(s[0],s[1],r[0]-s[0],r[1]-s[1],n)},inverseTransform:function(){return this._inverseTransform(o.read(arguments))},_getDeterminant:function(){var t=this._a*this._d-this._b*this._c;return isFinite(t)&&!a.isZero(t)&&isFinite(this._tx)&&isFinite(this._ty)?t:null},_inverseTransform:function(t,e,n){var i=this._getDeterminant();if(!i)return null;var s=t.x-this._tx,r=t.y-this._ty;return e||(e=new o),e.set((s*this._d-r*this._b)/i,(r*this._a-s*this._c)/i,n)},decompose:function(){var t=this._a,e=this._b,n=this._c,i=this._d;if(a.isZero(t*i-e*n))return null;var s=Math.sqrt(t*t+e*e);t/=s,e/=s;var r=t*n+e*i;n-=t*r,i-=e*r;var h=Math.sqrt(n*n+i*i);return n/=h,i/=h,r/=h,e*n>t*i&&(t=-t,e=-e,r=-r,s=-s),{translation:this.getTranslation(),scaling:new o(s,h),rotation:180*-Math.atan2(e,t)/Math.PI,shearing:r}},getValues:function(){return[this._a,this._c,this._b,this._d,this._tx,this._ty]},getTranslation:function(){return new o(this._tx,this._ty)},getScaling:function(){return(this.decompose()||{}).scaling},getRotation:function(){return(this.decompose()||{}).rotation +},inverted:function(){var t=this._getDeterminant();return t&&new f(this._d/t,-this._c/t,-this._b/t,this._a/t,(this._b*this._ty-this._d*this._tx)/t,(this._c*this._tx-this._a*this._ty)/t)},shiftless:function(){return new f(this._a,this._c,this._b,this._d,0,0)},applyToContext:function(t){t.transform(this._a,this._c,this._b,this._d,this._tx,this._ty)}},new function(){return t.each({scaleX:"_a",scaleY:"_d",translateX:"_tx",translateY:"_ty",shearX:"_b",shearY:"_c"},function(e,n){n=t.capitalize(n),this["get"+n]=function(){return this[e]},this["set"+n]=function(t){this[e]=t}},{})}),g=t.extend({_class:"Line",initialize:function(t,e,n,i,s){var r=!1;arguments.length>=4?(this._px=t,this._py=e,this._vx=n,this._vy=i,r=s):(this._px=t.x,this._py=t.y,this._vx=e.x,this._vy=e.y,r=n),r||(this._vx-=this._px,this._vy-=this._py)},getPoint:function(){return new o(this._px,this._py)},getVector:function(){return new o(this._vx,this._vy)},getLength:function(){return this.getVector().getLength()},intersect:function(t,e){return g.intersect(this._px,this._py,this._vx,this._vy,t._px,t._py,t._vx,t._vy,!0,e)},getSide:function(t){return g.getSide(this._px,this._py,this._vx,this._vy,t.x,t.y,!0)},getDistance:function(t){return Math.abs(g.getSignedDistance(this._px,this._py,this._vx,this._vy,t.x,t.y,!0))},statics:{intersect:function(t,e,n,i,s,r,h,u,l,c){l||(n-=t,i-=e,h-=s,u-=r);var d=u*n-h*i;if(!a.isZero(d)){var _=t-s,f=e-r,g=(h*f-u*_)/d,v=(n*f-i*_)/d;if((c||g>=0&&1>=g)&&(c||v>=0&&1>=v))return new o(t+g*n,e+g*i)}},getSide:function(t,e,n,i,s,r,a){a||(n-=t,i-=e);var o=s-t,h=r-e,u=o*i-h*n;return 0===u&&(u=o*n+h*i,u>0&&(o-=n,h-=i,u=o*n+h*i,0>u&&(u=0))),0>u?-1:u>0?1:0},getSignedDistance:function(t,e,n,i,s,r,a){a||(n-=t,i-=e);var o=i/n,h=e-o*t;return(r-o*s-h)/Math.sqrt(o*o+1)}}}),v=s.extend({_class:"Project",_list:"projects",_reference:"project",initialize:function(t){s.call(this,!0),this.layers=[],this.symbols=[],this._currentStyle=new E,this.activeLayer=new w,t&&(this.view=t instanceof V?t:V.create(t)),this._selectedItems={},this._selectedItemCount=0,this._drawCount=0,this.options={}},_serialize:function(e,n){return t.serialize(this.layers,e,!0,n)},clear:function(){for(var t=this.layers.length-1;t>=0;t--)this.layers[t].remove();this.symbols=[]},remove:function re(){return re.base.call(this)?(this.view&&this.view.remove(),!0):!1},getCurrentStyle:function(){return this._currentStyle},setCurrentStyle:function(t){this._currentStyle.initialize(t)},getIndex:function(){return this._index},getSelectedItems:function(){var t=[];for(var e in this._selectedItems){var n=this._selectedItems[e];n._drawCount===this._drawCount&&t.push(n)}return t},_updateSelection:function(t){t._selected?(this._selectedItemCount++,this._selectedItems[t._id]=t,t.isInserted()&&(t._drawCount=this._drawCount)):(this._selectedItemCount--,delete this._selectedItems[t._id])},selectAll:function(){for(var t=0,e=this.layers.length;e>t;t++)this.layers[t].setSelected(!0)},deselectAll:function(){for(var t in this._selectedItems)this._selectedItems[t].setSelected(!1)},hitTest:function(e,n){e=o.read(arguments),n=S.getOptions(t.read(arguments));for(var i=this.layers.length-1;i>=0;i--){var s=this.layers[i].hitTest(e,n);if(s)return s}return null},importJSON:function(e){return this.activate(),t.importJSON(e)},draw:function(e,n){this._drawCount++,e.save(),n.applyToContext(e);for(var i=t.merge({offset:new o(0,0),transforms:[n]}),s=0,r=this.layers.length;r>s;s++)this.layers[s].draw(e,i);if(e.restore(),this._selectedItemCount>0){e.save(),e.strokeWidth=1;for(var a in this._selectedItems){var h=this._selectedItems[a];if(h._drawCount===this._drawCount&&(h._drawSelected||h._boundsSelected)){var u=h.getSelectedColor()||h.getLayer().getSelectedColor();e.strokeStyle=e.fillStyle=u?u.toCanvasStyle(e):"#009dec";var l=h._globalMatrix;if(h._drawSelected&&h._drawSelected(e,l),h._boundsSelected){var c=l._transformCorners(h._getBounds("getBounds"));e.beginPath();for(var s=0;8>s;s++)e[0===s?"moveTo":"lineTo"](c[s],c[++s]);e.closePath(),e.stroke();for(var s=0;8>s;s++)e.beginPath(),e.rect(c[s]-2,c[++s]-2,4,4),e.fill()}}}e.restore()}}}),m=t.extend({_class:"Symbol",initialize:function ae(t,e){this._id=ae._id=(ae._id||0)+1,this.project=paper.project,this.project.symbols.push(this),t&&this.setDefinition(t,e),this._instances={}},_serialize:function(e,n){return n.add(this,function(){return t.serialize([this._class,this._definition],e,!1,n)})},_changed:function(e){t.each(this._instances,function(t){t._changed(e)})},getDefinition:function(){return this._definition},setDefinition:function(t){t._parentSymbol&&(t=t.clone()),this._definition&&delete this._definition._parentSymbol,this._definition=t,t.remove(),t.setSelected(!1),arguments[1]||t.setPosition(new o),t._parentSymbol=this,this._changed(5)},place:function(t){return new C(this,t)},clone:function(){return new m(this._definition.clone())}}),p=t.extend(e,{statics:{extend:function oe(e){e._serializeFields&&(e._serializeFields=t.merge(this.prototype._serializeFields,e._serializeFields));var n=oe.base.apply(this,arguments),i=n.prototype,s=i._class;return s&&(i._type=t.hyphenate(s)),n}},_class:"Item",_transformContent:!0,_boundsSelected:!1,_serializeFields:{name:null,matrix:new f,locked:!1,visible:!0,blendMode:"normal",opacity:1,guide:!1,clipMask:!1,data:{}},initialize:function he(t){if(this._id=he._id=(he._id||0)+1,!this._project){var e=paper.project,n=e.activeLayer;n?n.addChild(this):this._setProject(e)}this._style=new E(this._project._currentStyle,this),this._matrix=new f,t&&this._matrix.translate(t)},_events:new function(){var e={mousedown:{mousedown:1,mousedrag:1,click:1,doubleclick:1},mouseup:{mouseup:1,mousedrag:1,click:1,doubleclick:1},mousemove:{mousedrag:1,mousemove:1,mouseenter:1,mouseleave:1}},n={install:function(t){var n=this._project.view._eventCounters;if(n)for(var i in e)n[i]=(n[i]||0)+(e[i][t]||0)},uninstall:function(t){var n=this._project.view._eventCounters;if(n)for(var i in e)n[i]-=e[i][t]||0}};return t.each(["onMouseDown","onMouseUp","onMouseDrag","onClick","onDoubleClick","onMouseMove","onMouseEnter","onMouseLeave"],function(t){this[t]=n},{onFrame:{install:function(){this._project.view._animateItem(this,!0)},uninstall:function(){this._project.view._animateItem(this,!1)}},onLoad:{}})},_serialize:function(e,n){function i(i){for(var a in i){var o=r[a];t.equals(o,i[a])||(s[a]=t.serialize(o,e,"data"!==a,n))}}var s={},r=this;return i(this._serializeFields),this instanceof y||i(this._style._defaults),[this._class,s]},_changed:function(t){if(4&t&&(delete this._bounds,delete this._position),this._parent&&12&t&&this._parent._clearBoundsCache(),2&t&&this._clearBoundsCache(),1&t&&(this._project._needsRedraw=!0),this._parentSymbol&&this._parentSymbol._changed(t),this._project._changes){var e=this._project._changesById[this._id];e?e.flags|=t:(e={item:this,flags:t},this._project._changesById[this._id]=e,this._project._changes.push(e))}},set:function(t){return t&&this._set(t),this},getId:function(){return this._id},getType:function(){return this._type},getName:function(){return this._name},setName:function(t,e){if(this._name&&this._removeFromNamed(),t&&this._parent){for(var n=this._parent._children,i=this._parent._namedChildren,s=t,r=1;e&&n[t];)t=s+" "+r++;(i[t]=i[t]||[]).push(this),n[t]=this}this._name=t||void 0,this._changed(32)},getStyle:function(){return this._style},setStyle:function(t){this.getStyle().set(t)},hasFill:function(){return!!this.getStyle().getFillColor()},hasStroke:function(){var t=this.getStyle();return!!t.getStrokeColor()&&t.getStrokeWidth()>0}},t.each(["locked","visible","blendMode","opacity","guide"],function(e){var n=t.capitalize(e),e="_"+e;this["get"+n]=function(){return this[e]},this["set"+n]=function(t){t!=this[e]&&(this[e]=t,this._changed("_locked"===e?32:33))}},{}),{_locked:!1,_visible:!0,_blendMode:"normal",_opacity:1,_guide:!1,isSelected:function(){if(this._children)for(var t=0,e=this._children.length;e>t;t++)if(this._children[t].isSelected())return!0;return this._selected},setSelected:function(t){if(this._children&&!arguments[1])for(var e=0,n=this._children.length;n>e;e++)this._children[e].setSelected(t);(t=!!t)!=this._selected&&(this._selected=t,this._project._updateSelection(this),this._changed(33))},_selected:!1,isFullySelected:function(){if(this._children&&this._selected){for(var t=0,e=this._children.length;e>t;t++)if(!this._children[t].isFullySelected())return!1;return!0}return this._selected},setFullySelected:function(t){if(this._children)for(var e=0,n=this._children.length;n>e;e++)this._children[e].setFullySelected(t);this.setSelected(t,!0)},isClipMask:function(){return this._clipMask},setClipMask:function(t){this._clipMask!=(t=!!t)&&(this._clipMask=t,t&&(this.setFillColor(null),this.setStrokeColor(null)),this._changed(33),this._parent&&this._parent._changed(256))},_clipMask:!1,getData:function(){return this._data||(this._data={}),this._data},setData:function(t){this._data=t},getPosition:function(){var t=this._position||(this._position=this.getBounds().getCenter(!0));return new(arguments[0]?o:h)(t.x,t.y,this,"setPosition")},setPosition:function(){this.translate(o.read(arguments).subtract(this.getPosition(!0)))},getMatrix:function(){return this._matrix},setMatrix:function(t){this._matrix.initialize(t),this._changed(5)},isEmpty:function(){return 0==this._children.length}},t.each(["getBounds","getStrokeBounds","getHandleBounds","getRoughBounds"],function(t){this[t]=function(){var e=this._boundsGetter,n=this._getCachedBounds("string"==typeof e?e:e&&e[t]||t,arguments[0]);return"getBounds"===t?new _(n.x,n.y,n.width,n.height,this,"setBounds"):n}},{_getCachedBounds:function(t,e,n){var i=(!e||e.equals(this._matrix))&&t;if(n&&this._parent){var s=n._id,r=this._parent._boundsCache=this._parent._boundsCache||{ids:{},list:[]};r.ids[s]||(r.list.push(n),r.ids[s]=n)}if(i&&this._bounds&&this._bounds[i])return this._bounds[i].clone();var a=this._matrix.isIdentity();e=!e||e.isIdentity()?a?null:this._matrix:a?e:e.clone().concatenate(this._matrix);var o=this._getBounds(t,e,i?this:n);return i&&(this._bounds||(this._bounds={}),this._bounds[i]=o.clone()),o},_clearBoundsCache:function(){if(this._boundsCache){for(var t=0,e=this._boundsCache.list,n=e.length;n>t;t++){var i=e[t];delete i._bounds,i!=this&&i._boundsCache&&i._clearBoundsCache()}delete this._boundsCache}},_getBounds:function(t,e,n){var i=this._children;if(!i||0==i.length)return new d;for(var s=1/0,r=-s,a=s,o=r,h=0,u=i.length;u>h;h++){var l=i[h];if(l._visible&&!l.isEmpty()){var c=l._getCachedBounds(t,e,n);s=Math.min(c.x,s),a=Math.min(c.y,a),r=Math.max(c.x+c.width,r),o=Math.max(c.y+c.height,o)}}return isFinite(s)?new d(s,a,r-s,o-a):new d},setBounds:function(t){t=d.read(arguments);var e=this.getBounds(),n=new f,i=t.getCenter();n.translate(i),(t.width!=e.width||t.height!=e.height)&&n.scale(0!=e.width?t.width/e.width:1,0!=e.height?t.height/e.height:1),i=e.getCenter(),n.translate(-i.x,-i.y),this.transform(n)}}),{getProject:function(){return this._project},_setProject:function(t){if(this._project!=t&&(this._project=t,this._children))for(var e=0,n=this._children.length;n>e;e++)this._children[e]._setProject(t)},getLayer:function(){for(var t=this;t=t._parent;)if(t instanceof w)return t;return null},getParent:function(){return this._parent},setParent:function(t){return t.addChild(this)},getChildren:function(){return this._children},setChildren:function(t){this.removeChildren(),this.addChildren(t)},getFirstChild:function(){return this._children&&this._children[0]||null},getLastChild:function(){return this._children&&this._children[this._children.length-1]||null},getNextSibling:function(){return this._parent&&this._parent._children[this._index+1]||null},getPreviousSibling:function(){return this._parent&&this._parent._children[this._index-1]||null},getIndex:function(){return this._index},isInserted:function(){return this._parent?this._parent.isInserted():!1},clone:function(){return this._clone(new this.constructor)},_clone:function(t){if(t.setStyle(this._style),this._children)for(var e=0,n=this._children.length;n>e;e++)t.addChild(this._children[e].clone(),!0);for(var i=["_locked","_visible","_blendMode","_opacity","_clipMask","_guide"],e=0,n=i.length;n>e;e++){var s=i[e];this.hasOwnProperty(s)&&(t[s]=this[s])}return t._matrix.initialize(this._matrix),t.setSelected(this._selected),this._name&&t.setName(this._name,!0),t},copyTo:function(t){var e=this.clone();return t.layers?t.activeLayer.addChild(e):t.addChild(e),e},rasterize:function(e){var n=this.getStrokeBounds(),i=(e||72)/72,s=$.getCanvas(n.getSize().multiply(i)),r=s.getContext("2d"),a=(new f).scale(i).translate(-n.x,-n.y);r.save(),a.applyToContext(r),this.draw(r,t.merge({transforms:[a]}));var o=new b(s);return o.setBounds(n),r.restore(),o},contains:function(){return!!this._contains(this._matrix._inverseTransform(o.read(arguments)))},_contains:function(t){if(this._children){for(var e=this._children.length-1;e>=0;e--)if(this._children[e].contains(t))return!0;return!1}return t.isInside(this._getBounds("getBounds"))},hitTest:function(e,n){function i(i,s){var o=a["get"+s]();return e.getDistance(o)u&&!s;u++)s=i("bounds",h[u])}return(s||(s=this._children||!(n.guides&&!this._guide||n.selected&&!this._selected)?this._hitTest(e,n):null))&&s.point&&(s.point=r._matrix.transform(s.point)),s},_hitTest:function(t,e){if(this._children){for(var n,i=this._children.length-1;i>=0;i--)if(n=this._children[i].hitTest(t,e))return n}else if(this.hasFill()&&this._contains(t))return new S("fill",this)},addChild:function(t,e){return this.insertChild(void 0,t,e)},insertChild:function(t,e,n){var i=this.insertChildren(t,[e],n);return i&&i[0]},addChildren:function(t,e){return this.insertChildren(this._children.length,t,e)},insertChildren:function(e,n,i,s){var r=this._children;if(r&&n&&n.length>0){n=Array.prototype.slice.apply(n);for(var a=n.length-1;a>=0;a--){var o=n[a];s&&o._type!==s?n.splice(a,1):o._remove(!0)}t.splice(r,n,e,0);for(var a=0,h=n.length;h>a;a++){var o=n[a];o._parent=this,o._setProject(this._project),o._name&&o.setName(o._name)}this._changed(7)}else n=null;return n},insertAbove:function(t,e){var n=t._index;return t._parent==this._parent&&nthis._index&&n--,t._parent.insertChild(n,this,e)},sendToBack:function(){return this._parent.insertChild(0,this)},bringToFront:function(){return this._parent.addChild(this)},appendTop:"#addChild",appendBottom:function(t){return this.insertChild(0,t)},moveAbove:"#insertAbove",moveBelow:"#insertBelow",_removeFromNamed:function(){var t=this._parent._children,e=this._parent._namedChildren,n=this._name,i=e[n],s=i?i.indexOf(this):-1;-1!=s&&(t[n]==this&&delete t[n],i.splice(s,1),i.length?t[n]=i[i.length-1]:delete e[n])},_remove:function(e){return this._parent?(this._name&&this._removeFromNamed(),null!=this._index&&t.splice(this._parent._children,null,this._index,1),e&&this._parent._changed(7),this._parent=null,!0):!1},remove:function(){return this._remove(!0)},removeChildren:function(e,n){if(!this._children)return null;e=e||0,n=t.pick(n,this._children.length);for(var i=t.splice(this._children,null,e,n-e),s=i.length-1;s>=0;s--)i[s]._remove(!1);return i.length>0&&this._changed(7),i},reverseChildren:function(){if(this._children){this._children.reverse();for(var t=0,e=this._children.length;e>t;t++)this._children[t]._index=t;this._changed(7)}},isEditable:function(){for(var t=this;t;){if(!t._visible||t._locked)return!1;t=t._parent}return!0},_getOrder:function(t){function e(t){var e=[];do e.unshift(t);while(t=t._parent);return e}for(var n=e(this),i=e(t),s=0,r=Math.min(n.length,i.length);r>s;s++)if(n[s]!=i[s])return n[s]._index0},isAbove:function(t){return-1==this._getOrder(t)},isBelow:function(t){return 1==this._getOrder(t)},isParent:function(t){return this._parent==t},isChild:function(t){return t&&t._parent==this},isDescendant:function(t){for(var e=this;e=e._parent;)if(e==t)return!0;return!1},isAncestor:function(t){return t?t.isDescendant(this):!1},isGroupedWith:function(t){for(var e=this._parent;e;){if(e._parent&&/^(group|layer|compound-path)$/.test(e._type)&&t.isDescendant(e))return!0;e=e._parent}return!1},scale:function(t,e,n){return(arguments.length<2||"object"==typeof e)&&(n=e,e=t),this.transform((new f).scale(t,e,n||this.getPosition(!0)))},translate:function(){var t=new f;return this.transform(t.translate.apply(t,arguments))},rotate:function(t,e){return this.transform((new f).rotate(t,e||this.getPosition(!0)))},shear:function(t,e,n){return(arguments.length<2||"object"==typeof e)&&(n=e,e=t),this.transform((new f).shear(t,e,n||this.getPosition(!0)))},transform:function(t){var e=this._bounds,n=this._position;if(this._matrix.preConcatenate(t),(this._transformContent||arguments[1])&&this.applyMatrix(!0),this._changed(5),e&&0===t.getRotation()%90){for(var i in e){var s=e[i];t._transformBounds(s,s)}var r=this._boundsGetter,s=e[r&&r.getBounds||r||"getBounds"];s&&(this._position=s.getCenter(!0)),this._bounds=e}else n&&(this._position=t._transformPoint(n,n));return this},_applyMatrix:function(t,e){var n=this._children;if(n&&n.length>0){for(var i=0,s=n.length;s>i;i++)n[i].transform(t,e);return!0}},applyMatrix:function(t){var e=this._matrix;if(this._applyMatrix(e,!0)){var n=this._style,i=n.getFillColor(!0),s=n.getStrokeColor(!0);i&&i.transform(e),s&&s.transform(e),e.reset()}t||this._changed(5)},fitBounds:function(t,e){t=d.read(arguments);var n=this.getBounds(),i=n.height/n.width,s=t.height/t.width,r=(e?i>s:s>i)?t.width/n.width:t.height/n.height,a=new d(new o,new u(n.width*r,n.height*r));a.setCenter(t.getCenter()),this.setBounds(a)},importJSON:function(e){return this.addChild(t.importJSON(e))},_setStyles:function(t){var e=this._style,n=e.getStrokeWidth(),i=e.getStrokeJoin(),s=e.getStrokeCap(),r=e.getMiterLimit(),a=e.getFillColor(),o=e.getStrokeColor(),h=e.getDashArray(),u=e.getDashOffset();null!=n&&(t.lineWidth=n),i&&(t.lineJoin=i),s&&(t.lineCap=s),r&&(t.miterLimit=r),a&&(t.fillStyle=a.toCanvasStyle(t)),o&&(t.strokeStyle=o.toCanvasStyle(t),paper.support.nativeDash&&h&&h.length&&("setLineDash"in t?(t.setLineDash(h),t.lineDashOffset=u):(t.mozDash=h,t.mozDashOffset=u)))},draw:function(t,e){if(this._visible&&0!=this._opacity){this._drawCount=this._project._drawCount;var n=e.transforms,i=n[n.length-1],s=i.clone().concatenate(this._matrix);n.push(this._globalMatrix=s);var r,a,o,h=this._blendMode,l=this._opacity,c=K.nativeModes[h],d="normal"===h&&1===l||(c||1>l)&&this._canComposite();if(!d){var _=this.getStrokeBounds(i);if(!_.width||!_.height)return;o=e.offset,a=e.offset=_.getTopLeft().floor(),r=t,t=$.getContext(_.getSize().ceil().add(new u(1,1)))}t.save(),d?(t.globalAlpha=l,c&&(t.globalCompositeOperation=h)):t.translate(-a.x,-a.y),(d?this._matrix:s).applyToContext(t),!d&&e.clipItem&&e.clipItem.draw(t,e.extend({clip:!0})),this._draw(t,e),t.restore(),n.pop(),e.clip&&t.clip(),d||(K.process(h,t,r,l,a.subtract(o)),$.release(t),e.offset=o)}},_canComposite:function(){return!1}},t.each(["down","drag","up","move"],function(e){this["removeOn"+t.capitalize(e)]=function(){var t={};return t[e]=!0,this.removeOn(t)}},{removeOn:function(t){for(var e in t)if(t[e]){var n="mouse"+e,i=this._project,s=i._removeSets=i._removeSets||{};s[n]=s[n]||{},s[n][this._id]=this}return this}})),y=p.extend({_class:"Group",_serializeFields:{children:[]},initialize:function(t){p.call(this),this._children=[],this._namedChildren={},t&&!this._set(t)&&this.addChildren(Array.isArray(t)?t:arguments)},_changed:function ue(t){ue.base.call(this,t),2&t&&this._transformContent&&!this._matrix.isIdentity()&&this.applyMatrix(),258&t&&delete this._clipItem},_getClipItem:function(){if(void 0!==this._clipItem)return this._clipItem;for(var t=0,e=this._children.length;e>t;t++){var n=this._children[t];if(n._clipMask)return this._clipItem=n}return this._clipItem=null},getTransformContent:function(){return this._transformContent},setTransformContent:function(t){this._transformContent=t,t&&this.applyMatrix()},isClipped:function(){return!!this._getClipItem()},setClipped:function(t){var e=this.getFirstChild();e&&e.setClipMask(t)},_draw:function(t,e){var n=e.clipItem=this._getClipItem();n&&n.draw(t,e.extend({clip:!0}));for(var i=0,s=this._children.length;s>i;i++){var r=this._children[i];r!==n&&r.draw(t,e)}e.clipItem=null}}),w=y.extend({_class:"Layer",initialize:function(){this._project=paper.project,this._index=this._project.layers.push(this)-1,y.apply(this,arguments),this.activate()},_remove:function le(e){return this._parent?le.base.call(this,e):null!=this._index?(this._project.activeLayer===this&&(this._project.activeLayer=this.getNextSibling()||this.getPreviousSibling()),t.splice(this._project.layers,null,this._index,1),this._project._needsRedraw=!0,!0):!1},getNextSibling:function ce(){return this._parent?ce.base.call(this):this._project.layers[this._index+1]||null},getPreviousSibling:function de(){return this._parent?de.base.call(this):this._project.layers[this._index-1]||null},isInserted:function _e(){return this._parent?_e.base.call(this):null!=this._index},activate:function(){this._project.activeLayer=this}},new function(){function e(e){return function n(i){return i instanceof w&&!i._parent&&this._remove(!0)?(t.splice(i._project.layers,[this],i._index+(e?1:0),0),this._setProject(i._project),!0):n.base.call(this,i)}}return{insertAbove:e(!0),insertBelow:e(!1)}}),x=p.extend({_class:"Shape",_transformContent:!1,initialize:function(t,e,n){p.call(this,e),this._type=t,this._size=n},_draw:function(t,e){var n=this._style,i=this._size,s=i.width,r=i.height,o=n.getFillColor(),h=n.getStrokeColor();if(o||h||e.clip)switch(t.beginPath(),this._type){case"rect":t.rect(-s/2,-r/2,s,r);break;case"circle":t.arc(0,0,(s+r)/4,0,2*Math.PI,!0);break;case"ellipse":var u=s/2,l=r/2,c=a.KAPPA,d=u*c,_=l*c;t.moveTo(-u,0),t.bezierCurveTo(-u,-_,-d,-l,0,-l),t.bezierCurveTo(d,-l,u,-_,u,0),t.bezierCurveTo(u,_,d,l,0,l),t.bezierCurveTo(-d,l,-u,_,-u,0)}e.clip||!o&&!h||(this._setStyles(t),o&&t.fill(),h&&t.stroke())},_canComposite:function(){return!(this.hasFill()&&this.hasStroke())},_getBounds:function(t,e){var n=new d(this._size).setCenter(0,0);return"getBounds"!==t&&this.hasStroke()&&(n=n.expand(this.getStrokeWidth())),e?e._transformBounds(n):n},_contains:function fe(t){switch(this._type){case"rect":return fe.base.call(this,t);case"circle":case"ellipse":return t.divide(this._size).getLength()<=.5}},_hitTest:function ge(t){if(this.hasStroke()){var e=this._type,n=this.getStrokeWidth();switch(e){case"rect":var i=new d(this._size).setCenter(0,0),s=i.expand(n),r=i.expand(-n);if(s._containsPoint(t)&&!r._containsPoint(t))return new S("stroke",this);break;case"circle":case"ellipse":var a,o=this._size,h=o.width,u=o.height;if("ellipse"===e){var l=t.getAngleInRadians(),c=h*Math.sin(l),_=u*Math.cos(l);a=h*u/(2*Math.sqrt(c*c+_*_))}else a=(h+u)/4;if(2*Math.abs(t.getLength()-a)<=n)return new S("stroke",this)}}return ge.base.apply(this,arguments)},statics:new function(){function e(e,n,i,s){var r=new x(e,n,i),a=t.getNamed(s);return a&&r._set(a),r}return{Circle:function(){var n=o.readNamed(arguments,"center"),i=t.readNamed(arguments,"radius");return e("circle",n,new u(2*i),arguments)},Rectangle:function(){var t=d.readNamed(arguments,"rectangle");return e("rect",t.getCenter(!0),t.getSize(!0),arguments)},Ellipse:function(){var t=d.readNamed(arguments,"rectangle");return e("ellipse",t.getCenter(!0),t.getSize(!0),arguments)}}}}),b=p.extend({_class:"Raster",_transformContent:!1,_boundsGetter:"getBounds",_boundsSelected:!0,_serializeFields:{source:null},initialize:function(t,e){p.call(this,void 0!==e&&o.read(arguments,1)),t&&!this._set(t)&&(t.getContext?this.setCanvas(t):"string"==typeof t?this.setSource(t):this.setImage(t)),this._size||(this._size=new u)},clone:function(){var t=this._image;t||(t=$.getCanvas(this._size),t.getContext("2d").drawImage(this._canvas,0,0));var e=new b(t);return this._clone(e)},getSize:function(){return this._size},setSize:function(){var t=u.read(arguments);if(!this._size.equals(t)){var e=this.getElement();this.setCanvas($.getCanvas(t)),e&&this.getContext(!0).drawImage(e,0,0,t.width,t.height)}},getWidth:function(){return this._size.width},getHeight:function(){return this._size.height},isEmpty:function(){return 0==this._size.width&&0==this._size.height},getPpi:function(){var t=this._matrix,e=new o(0,0).transform(t),n=new o(1,0).transform(t).subtract(e),i=new o(0,1).transform(t).subtract(e);return new u(72/n.getLength(),72/i.getLength())},getContext:function(){return this._context||(this._context=this.getCanvas().getContext("2d")),arguments[0]&&(this._image=null,this._changed(129)),this._context},setContext:function(t){this._context=t},getCanvas:function(){if(!this._canvas){var t=$.getContext(this._size);try{this._image&&t.drawImage(this._image,0,0),this._canvas=t.canvas}catch(e){$.release(t)}}return this._canvas},setCanvas:function(t){this._canvas&&$.release(this._canvas),this._canvas=t,this._size=new u(t.width,t.height),this._image=null,this._context=null,this._changed(133)},getImage:function(){return this._image},setImage:function(t){this._canvas&&$.release(this._canvas),this._image=t,this._size=new u(t.naturalWidth,t.naturalHeight),this._canvas=null,this._context=null,this._changed(5)},getSource:function(){return this._image&&this._image.src||this.toDataURL()},setSource:function(t){function e(){n.fire("load"),n._project.view&&n._project.view.draw(!0)}var n=this,i=document.getElementById(t)||new Image;q.add(i,{load:function(){n.setImage(i),e()}}),i.width&&i.height?setTimeout(e,0):i.src||(i.src=t),this.setImage(i)},getElement:function(){return this._canvas||this._image},getSubImage:function(t){t=d.read(arguments);var e=$.getContext(t.getSize());return e.drawImage(this.getCanvas(),t.x,t.y,t.width,t.height,0,0,t.width,t.height),e.canvas},toDataURL:function(){var t=this._image&&this._image.src;if(/^data:/.test(t))return t;var e=this.getCanvas();return e?e.toDataURL():null},drawImage:function(t,e){e=o.read(arguments,1),this.getContext(!0).drawImage(t,e.x,e.y)},getAverageColor:function(e){var n,i;e?e instanceof k?(i=e,n=e.getBounds()):e.width?n=new d(e):e.x&&(n=new d(e.x-.5,e.y-.5,1,1)):n=this.getBounds();var s=32,r=Math.min(n.width,s),a=Math.min(n.height,s),o=b._sampleContext;o?o.clearRect(0,0,s+1,s+1):o=b._sampleContext=$.getContext(new u(s)),o.save();var h=(new f).scale(r/n.width,a/n.height).translate(-n.x,-n.y);h.applyToContext(o),i&&i.draw(o,t.merge({clip:!0,transforms:[h]})),this._matrix.applyToContext(o),o.drawImage(this.getElement(),-this._size.width/2,-this._size.height/2),o.restore();for(var l=o.getImageData(.5,.5,Math.ceil(r),Math.ceil(a)).data,c=[0,0,0],_=0,g=0,v=l.length;v>g;g+=4){var m=l[g+3];_+=m,m/=255,c[0]+=l[g]*m,c[1]+=l[g+1]*m,c[2]+=l[g+2]*m}for(var g=0;3>g;g++)c[g]/=_;return _?B.read(c):null},getPixel:function(t){t=o.read(arguments);var e=this.getContext().getImageData(t.x,t.y,1,1).data;return new B("rgb",[e[0]/255,e[1]/255,e[2]/255],e[3]/255)},setPixel:function(){var t=o.read(arguments),e=B.read(arguments),n=e._convert("rgb"),i=e._alpha,s=this.getContext(!0),r=s.createImageData(1,1),a=r.data;a[0]=255*n[0],a[1]=255*n[1],a[2]=255*n[2],a[3]=null!=i?255*i:255,s.putImageData(r,t.x,t.y)},createImageData:function(t){return t=u.read(arguments),this.getContext().createImageData(t.width,t.height)},getImageData:function(t){return t=d.read(arguments),t.isEmpty()&&(t=new d(this.getSize())),this.getContext().getImageData(t.x,t.y,t.width,t.height)},setImageData:function(t,e){e=o.read(arguments,1),this.getContext(!0).putImageData(t,e.x,e.y)},_getBounds:function(t,e){var n=new d(this._size).setCenter(0,0);return e?e._transformBounds(n):n},_hitTest:function(t){if(this._contains(t)){var e=this;return new S("pixel",e,{offset:t.add(e._size.divide(2)).round(),color:{get:function(){return e.getPixel(this.offset)}}})}},_draw:function(t){var e=this.getElement();e&&(t.globalAlpha=this._opacity,t.drawImage(e,-this._size.width/2,-this._size.height/2))},_canComposite:function(){return!0}}),C=p.extend({_class:"PlacedSymbol",_transformContent:!1,_boundsGetter:{getBounds:"getStrokeBounds"},_boundsSelected:!0,_serializeFields:{symbol:null},initialize:function(t,e){p.call(this,void 0!==e&&o.read(arguments,1)),t&&!this._set(t)&&this.setSymbol(t instanceof m?t:new m(t))},getSymbol:function(){return this._symbol},setSymbol:function(t){this._symbol&&delete this._symbol._instances[this._id],this._symbol=t,t._instances[this._id]=this},clone:function(){return this._clone(new C(this.symbol))},isEmpty:function(){return this._symbol._definition.isEmpty()},_getBounds:function(t,e){return this.symbol._definition._getCachedBounds(t,e)},_hitTest:function(t,e,n){var i=this._symbol._definition._hitTest(t,e,n);return i&&(i.item=this),i},_draw:function(t,e){this.symbol._definition.draw(t,e)}}),S=t.extend({_class:"HitResult",initialize:function(t,e,n){this.type=t,this.item=e,n&&(n.enumerable=!0,this.inject(n))},statics:{getOptions:function(e){return e&&e._merged?e:t.merge({type:null,tolerance:paper.project.options.hitTolerance||2,fill:!e,stroke:!e,segments:!e,handles:!1,ends:!1,center:!1,bounds:!1,guides:!1,selected:!1,_merged:!0},e)}}}),P=t.extend({_class:"Segment",initialize:function(t,e,n,i,s,r){var a,o,h,u=arguments.length;0===u||(1===u?t.point?(a=t.point,o=t.handleIn,h=t.handleOut):a=t:6>u?2==u&&void 0===e.x?a=[t,e]:(a=t,o=e,h=n):6===u&&(a=[t,e],o=[n,i],h=[s,r])),this._point=new M(a,this),this._handleIn=new M(o,this),this._handleOut=new M(h,this)},_serialize:function(e){return t.serialize(this.isLinear()?this._point:[this._point,this._handleIn,this._handleOut],e,!0)},_changed:function(t){if(this._path){var e,n=this._path._curves&&this.getCurve();n&&(n._changed(),(e=n[t==this._point||t==this._handleIn&&n._segment1==this?"getPrevious":"getNext"]())&&e._changed()),this._path._changed(5)}},getPoint:function(){return this._point},setPoint:function(t){t=o.read(arguments),this._point.set(t.x,t.y)},getHandleIn:function(){return this._handleIn},setHandleIn:function(t){t=o.read(arguments),this._handleIn.set(t.x,t.y)},getHandleOut:function(){return this._handleOut},setHandleOut:function(t){t=o.read(arguments),this._handleOut.set(t.x,t.y)},isLinear:function(){return this._handleIn.isZero()&&this._handleOut.isZero()},setLinear:function(){this._handleIn.set(0,0),this._handleOut.set(0,0)},_isSelected:function(t){var e=this._selectionState;return t==this._point?!!(4&e):t==this._handleIn?!!(1&e):t==this._handleOut?!!(2&e):!1},_setSelected:function(t,e){var n=this._path,e=!!e,i=this._selectionState||0,s=[!!(4&i),!!(1&i),!!(2&i)];if(t==this._point){if(e)s[1]=s[2]=!1;else{var r=this.getPrevious(),a=this.getNext();s[1]=r&&(r._point.isSelected()||r._handleOut.isSelected()),s[2]=a&&(a._point.isSelected()||a._handleIn.isSelected())}s[0]=e}else{var o=t==this._handleIn?1:2;s[o]!=e&&(e&&(s[0]=!1),s[o]=e)}this._selectionState=(s[0]?4:0)|(s[1]?1:0)|(s[2]?2:0),n&&i!=this._selectionState&&(n._updateSelection(this,i,this._selectionState),n._changed(33))},isSelected:function(){return this._isSelected(this._point)},setSelected:function(t){this._setSelected(this._point,t)},getIndex:function(){return void 0!==this._index?this._index:null},getPath:function(){return this._path||null},getCurve:function(){var t=this._path,e=this._index;return t?(t._closed||e!=t._segments.length-1||e--,t.getCurves()[e]||null):null +},getLocation:function(){var t=this.getCurve();return t?new I(t,t.getNext()?0:1):null},getNext:function(){var t=this._path&&this._path._segments;return t&&(t[this._index+1]||this._path._closed&&t[0])||null},getPrevious:function(){var t=this._path&&this._path._segments;return t&&(t[this._index-1]||this._path._closed&&t[t.length-1])||null},reverse:function(){return new P(this._point,this._handleOut,this._handleIn)},remove:function(){return this._path?!!this._path.removeSegment(this._index):!1},clone:function(){return new P(this._point,this._handleIn,this._handleOut)},equals:function(t){return t===this||t&&this._point.equals(t._point)&&this._handleIn.equals(t._handleIn)&&this._handleOut.equals(t._handleOut)||!1},toString:function(){var t=["point: "+this._point];return this._handleIn.isZero()||t.push("handleIn: "+this._handleIn),this._handleOut.isZero()||t.push("handleOut: "+this._handleOut),"{ "+t.join(", ")+" }"},_transformCoordinates:function(t,e,n){var i=this._point,s=n&&this._handleIn.isZero()?null:this._handleIn,r=n&&this._handleOut.isZero()?null:this._handleOut,a=i._x,o=i._y,h=2;return e[0]=a,e[1]=o,s&&(e[h++]=s._x+a,e[h++]=s._y+o),r&&(e[h++]=r._x+a,e[h++]=r._y+o),t&&(t._transformCoordinates(e,0,e,0,h/2),a=e[0],o=e[1],n?(i._x=a,i._y=o,h=2,s&&(s._x=e[h++]-a,s._y=e[h++]-o),r&&(r._x=e[h++]-a,r._y=e[h++]-o)):(s||(e[h++]=a,e[h++]=o),r||(e[h++]=a,e[h++]=o))),e}}),M=o.extend({initialize:function(t,e){var n,i,s;t?void 0!==(n=t[0])?i=t[1]:(void 0===(n=t.x)&&(t=o.read(arguments),n=t.x),i=t.y,s=t.selected):n=i=0,this._x=n,this._y=i,this._owner=e,s&&this.setSelected(!0)},set:function(t,e){return this._x=t,this._y=e,this._owner._changed(this),this},getX:function(){return this._x},setX:function(t){this._x=t,this._owner._changed(this)},getY:function(){return this._y},setY:function(t){this._y=t,this._owner._changed(this)},isZero:function(){return a.isZero(this._x)&&a.isZero(this._y)},setSelected:function(t){this._owner._setSelected(this,t)},isSelected:function(){return this._owner._isSelected(this)}}),z=t.extend({_class:"Curve",initialize:function(t,e,n,i,s,r,a,o){var h=arguments.length;if(3===h)this._path=t,this._segment1=e,this._segment2=n;else if(0===h)this._segment1=new P,this._segment2=new P;else if(1===h)this._segment1=new P(t.segment1),this._segment2=new P(t.segment2);else if(2===h)this._segment1=new P(t),this._segment2=new P(e);else{var u,l,c,d;4===h?(u=t,l=e,c=n,d=i):8===h&&(u=[t,e],d=[a,o],l=[n-t,i-e],c=[s-a,r-o]),this._segment1=new P(u,null,l),this._segment2=new P(d,c,null)}},_changed:function(){delete this._length,delete this._bounds},getPoint1:function(){return this._segment1._point},setPoint1:function(t){t=o.read(arguments),this._segment1._point.set(t.x,t.y)},getPoint2:function(){return this._segment2._point},setPoint2:function(t){t=o.read(arguments),this._segment2._point.set(t.x,t.y)},getHandle1:function(){return this._segment1._handleOut},setHandle1:function(t){t=o.read(arguments),this._segment1._handleOut.set(t.x,t.y)},getHandle2:function(){return this._segment2._handleIn},setHandle2:function(t){t=o.read(arguments),this._segment2._handleIn.set(t.x,t.y)},getSegment1:function(){return this._segment1},getSegment2:function(){return this._segment2},getPath:function(){return this._path},getIndex:function(){return this._segment1._index},getNext:function(){var t=this._path&&this._path._curves;return t&&(t[this._segment1._index+1]||this._path._closed&&t[0])||null},getPrevious:function(){var t=this._path&&this._path._curves;return t&&(t[this._segment1._index-1]||this._path._closed&&t[t.length-1])||null},isSelected:function(){return this.getHandle1().isSelected()&&this.getHandle2().isSelected()},setSelected:function(t){this.getHandle1().setSelected(t),this.getHandle2().setSelected(t)},getValues:function(){return z.getValues(this._segment1,this._segment2)},getPoints:function(){for(var t=this.getValues(),e=[],n=0;8>n;n+=2)e.push(new o(t[n],t[n+1]));return e},getLength:function(){var t=arguments[0],e=arguments[1],n=0===arguments.length||0===t&&1===e;if(n&&null!=this._length)return this._length;var i=z.getLength(this.getValues(),t,e);return n&&(this._length=i),i},getArea:function(){return z.getArea(this.getValues())},getPart:function(t,e){return new z(z.getPart(this.getValues(),t,e))},isLinear:function(){return this._segment1._handleOut.isZero()&&this._segment2._handleIn.isZero()},getIntersections:function(t){return z.getIntersections(this.getValues(),t.getValues(),this,t,[])},reverse:function(){return new z(this._segment2.reverse(),this._segment1.reverse())},divide:function(t){var e=null;if(t&&t.curve===this&&(t=t.parameter),t>0&&1>t){var n=z.subdivide(this.getValues(),t),i=this.isLinear(),s=n[0],r=n[1];i||(this._segment1._handleOut.set(s[2]-s[0],s[3]-s[1]),this._segment2._handleIn.set(r[4]-r[6],r[5]-r[7]));var a=s[6],h=s[7],u=new P(new o(a,h),!i&&new o(s[4]-a,s[5]-h),!i&&new o(r[2]-a,r[3]-h));if(this._path)this._segment1._index>0&&0===this._segment2._index?this._path.add(u):this._path.insert(this._segment2._index,u),e=this;else{var l=this._segment2;this._segment2=u,e=new z(u,l)}}return e},split:function(t){return this._path?this._path.split(this._segment1._index,t):null},clone:function(){return new z(this._segment1,this._segment2)},toString:function(){var t=["point1: "+this._segment1._point];return this._segment1._handleOut.isZero()||t.push("handle1: "+this._segment1._handleOut),this._segment2._handleIn.isZero()||t.push("handle2: "+this._segment2._handleIn),t.push("point2: "+this._segment2._point),"{ "+t.join(", ")+" }"},statics:{getValues:function(t,e){var n=t._point,i=t._handleOut,s=e._handleIn,r=e._point;return[n._x,n._y,n._x+i._x,n._y+i._y,r._x+s._x,r._y+s._y,r._x,r._y]},evaluate:function(t,e,n,i){var s,r,a=n?e:z.getParameterAt(t,e,0),h=t[0],u=t[1],l=t[2],c=t[3],d=t[4],_=t[5],f=t[6],g=t[7];if(0!==i||0!==a&&1!==a){var v=3*(l-h),m=3*(d-l)-v,p=f-h-v-m,y=3*(c-u),w=3*(_-c)-y,x=g-u-y-w;if(0===i)s=((p*a+m)*a+v)*a+h,r=((x*a+w)*a+y)*a+u;else{var b=1e-5;if(b>a&&l==h&&c==u||a>1-b&&d==f&&_==g?(s=d-l,r=_-c):(s=(3*p*a+2*m)*a+v,r=(3*x*a+2*w)*a+y),3===i){var C=6*p*a+2*m,S=6*x*a+2*w;return(s*S-r*C)/Math.pow(s*s+r*r,1.5)}}}else s=0===a?h:f,r=0===a?u:g;return 2==i?new o(r,-s):new o(s,r)},subdivide:function(t,e){var n=t[0],i=t[1],s=t[2],r=t[3],a=t[4],o=t[5],h=t[6],u=t[7];void 0===e&&(e=.5);var l=1-e,c=l*n+e*s,d=l*i+e*r,_=l*s+e*a,f=l*r+e*o,g=l*a+e*h,v=l*o+e*u,m=l*c+e*_,p=l*d+e*f,y=l*_+e*g,w=l*f+e*v,x=l*m+e*y,b=l*p+e*w;return[[n,i,c,d,m,p,x,b],[x,b,y,w,g,v,h,u]]},solveCubic:function(t,e,n,i){var s=t[e],r=t[e+2],o=t[e+4],h=t[e+6],u=3*(r-s),l=3*(o-r)-u,c=h-s-u-l;return a.solveCubic(c,l,u,s-n,i)},getParameterOf:function(t,e,n){if(Math.abs(t[0]-e)<1e-5&&Math.abs(t[1]-n)<1e-5)return 0;if(Math.abs(t[6]-e)<1e-5&&Math.abs(t[7]-n)<1e-5)return 1;for(var i,s,r=[],a=[],o=z.solveCubic(t,0,e,r),h=z.solveCubic(t,1,n,a),u=0;-1==o||o>u;)if(-1==o||(i=r[u++])>=0&&1>=i){for(var l=0;-1==h||h>l;)if((-1==h||(s=a[l++])>=0&&1>=s)&&(-1==o?i=s:-1==h&&(s=i),Math.abs(i-s)<1e-5))return.5*(i+s);if(-1==o)break}return null},getPart:function(t,e,n){return e>0&&(t=z.subdivide(t,e)[1]),1>n&&(t=z.subdivide(t,(n-e)/(1-e))[0]),t},isLinear:function(t){return t[0]===t[2]&&t[1]===t[3]&&t[4]===t[6]&&t[5]===t[7]},isFlatEnough:function(t,e){var n=t[0],i=t[1],s=t[2],r=t[3],a=t[4],o=t[5],h=t[6],u=t[7],l=3*s-2*n-h,c=3*r-2*i-u,d=3*a-2*h-n,_=3*o-2*u-i;return Math.max(l*l,d*d)+Math.max(c*c,_*_)<10*e*e},getArea:function(t){var e=t[0],n=t[1],i=t[2],s=t[3],r=t[4],a=t[5],o=t[6],h=t[7];return(3*s*e-1.5*s*r-1.5*s*o-3*n*i-1.5*n*r-.5*n*o+1.5*a*e+1.5*a*i-3*a*o+.5*h*e+1.5*h*i+3*h*r)/10},getBounds:function(t){for(var e=t.slice(0,2),n=e.slice(),i=[0,0],s=0;2>s;s++)z._addBounds(t[s],t[s+2],t[s+4],t[s+6],s,0,e,n,i);return new d(e[0],e[1],n[0]-e[0],n[1]-e[1])},_getCrossings:function(t,e,n,i,s){function r(t){return z.evaluate(e,1,!0,1).y*t.y>0}var a=z.solveCubic(t,1,i,s),o=0,h=1e-5,u=Math.abs;-1===a&&(s[0]=z.getParameterOf(t,n,i),a=null!==s[0]?1:0);for(var l=0;a>l;l++){var c=s[l];if(c>-h&&1-h>c){var d=z.evaluate(t,c,!0,0);if(n-180&&0>f&&(c>h||r(_)))continue}else if(u(_.y)c&&!r(_))continue;o++}}}return o},_addBounds:function(t,e,n,i,s,r,o,h,u){function l(t,e){var n=t-e,i=t+e;nh[s]&&(h[s]=i)}var c=3*(e-n)-t+i,d=2*(t+n)-4*e,_=e-t,f=a.solveQuadratic(c,d,_,u),g=1e-5,v=1-g;l(i,0);for(var m=0;f>m;m++){var p=u[m],y=1-p;p>g&&v>p&&l(y*y*y*t+3*y*y*p*e+3*y*p*p*n+p*p*p*i,r)}}}},t.each(["getBounds","getStrokeBounds","getHandleBounds","getRoughBounds"],function(t){this[t]=function(){this._bounds||(this._bounds={});var e=this._bounds[t];return e||(e=this._bounds[t]=A[t]([this._segment1,this._segment2],!1,this._path.getStyle())),e.clone()}},{}),t.each(["getPoint","getTangent","getNormal","getCurvatureAt"],function(t,e){this[t+"At"]=function(t,n){return z.evaluate(this.getValues(),t,n,e)},this[t]=function(t){return z.evaluate(this.getValues(),t,!0,e)}},{getParameterAt:function(t,e){return z.getParameterAt(this.getValues(),t,void 0!==e?e:0>t?1:0)},getParameterOf:function(t){return t=o.read(arguments),z.getParameterOf(this.getValues(),t.x,t.y)},getLocationAt:function(t,e){return e||(t=this.getParameterAt(t)),new I(this,t)},getLocationOf:function(t){t=o.read(arguments);var e=this.getParameterOf(t);return null!=e?new I(this,e):null},getNearestLocation:function(t){function e(e){if(e>=0&&1>=e){var i=t.getDistance(z.evaluate(n,e,!0,0),!0);if(r>i)return r=i,h=e,!0}}t=o.read(arguments);for(var n=this.getValues(),i=100,s=a.TOLERANCE,r=1/0,h=0,u=0;i>=u;u++)e(u/i);for(var l=1/(2*i);l>s;)e(h-l)||e(h+l)||(l/=2);var c=z.evaluate(n,h,!0,0);return new I(this,h,c,null,null,null,t.getDistance(c))},getNearestPoint:function(t){return t=o.read(arguments),this.getNearestLocation(t).getPoint()}}),new function(){function t(t){var e=t[0],n=t[1],i=t[2],s=t[3],r=t[4],a=t[5],o=t[6],h=t[7],u=9*(i-r)+3*(o-e),l=6*(e+r)-12*i,c=3*(i-e),d=9*(s-a)+3*(h-n),_=6*(n+a)-12*s,f=3*(s-n);return function(t){var e=(u*t+l)*t+c,n=(d*t+_)*t+f;return Math.sqrt(e*e+n*n)}}function e(t,e){return Math.max(2,Math.min(16,Math.ceil(32*Math.abs(e-t))))}return{statics:!0,getLength:function(n,i,s){if(void 0===i&&(i=0),void 0===s&&(s=1),n[0]==n[2]&&n[1]==n[3]&&n[6]==n[4]&&n[7]==n[5]){var r=n[6]-n[0],o=n[7]-n[1];return(s-i)*Math.sqrt(r*r+o*o)}var h=t(n);return a.integrate(h,i,s,e(i,s))},getParameterAt:function(n,i,s){function r(t){var n=e(s,t);return _+=t>s?a.integrate(l,s,t,n):-a.integrate(l,t,s,n),s=t,_-i}if(0===i)return s;var o=i>0,h=o?s:0,u=o?1:s,i=Math.abs(i),l=t(n),c=a.integrate(l,h,u,e(h,u));if(i>=c)return o?u:h;var d=i/c,_=0;return a.findRoot(r,l,o?h+d:u-d,h,u,16,1e-5)}}},new function(){function t(t,e,n,i,s,r,a){var o=t[0],h=t[t.length-1];o&&i.equals(o._point)||h&&i.equals(h._point)||t.push(new I(e,n,i,s,r,a))}function e(i,s,r,a,o,h,u,l){if(l=(l||0)+1,!(l>20)){h=h||[0,1],u=u||[0,1];for(var c=z.getPart(i,h[0],h[1]),d=z.getPart(s,u[0],u[1]),_=0;_++<20;){var f,g=n(c,d,f=u.slice()),v=0;if(0===g)break;if(g>0){if(u=f,d=z.getPart(s,u[0],u[1]),v=n(d,c,f=h.slice()),0===v)break;g>0&&(h=f,c=z.getPart(i,h[0],h[1]))}if(0>g||0>v){if(h[1]-h[0]>u[1]-u[0]){var m=(h[0]+h[1])/2;e(i,s,r,a,o,[h[0],m],u,l),e(i,s,r,a,o,[m,h[1]],u,l);break}var m=(u[0]+u[1])/2;e(i,s,r,a,o,h,[u[0],m],l),e(i,s,r,a,o,h,[m,u[1]],l);break}if(Math.abs(h[1]-h[0])<=1e-5&&Math.abs(u[1]-u[0])<=1e-5){var p=(h[0]+h[1])/2,y=(u[0]+u[1])/2;t(o,r,p,z.evaluate(i,p,!0,0),a,y,z.evaluate(s,y,!0,0));break}}}}function n(t,e,n){var s=t[0],r=t[1],a=t[2],o=t[3],h=t[4],u=t[5],l=t[6],c=t[7],d=e[0],_=e[1],f=e[2],v=e[3],m=e[4],p=e[5],y=e[6],w=e[7],x=g.getSignedDistance,b=x(s,r,l,c,a,o)||0,C=x(s,r,l,c,h,u)||0,S=b*C>0?.75:4/9,P=S*Math.min(0,b,C),M=S*Math.max(0,b,C),I=x(s,r,l,c,d,_),k=x(s,r,l,c,f,v),A=x(s,r,l,c,m,p),O=x(s,r,l,c,y,w);if(P>Math.max(I,k,A,O)||MO&&(L=P,P=M,M=L);for(var T=-1/0,j=1/0,B=-1/0,N=0,F=D.length;F>N;N++){var E=D[N],R=D[(N+1)%F];R[1]=V&&Z>=P){var J=q+(P-V)/G;j>J&&(j=J),J>T&&(T=J)}if(M>=V&&Z>=M){var J=q+(M-V)/G;J>B&&(B=J),j>J&&(j=0)}}if(1/0!==j&&B!==-1/0){var X=Math.min(P,M),W=Math.max(P,M);O>X&&W>O&&(B=1),I>X&&W>I&&(j=0),T>B&&(B=1);var Y=n[0],U=n[1]-Y;if(n[0]=Y+j*U,n[1]=Y+B*U,(U-(n[1]-n[0]))/U>=.2)return 1}return z.getBounds(t).touches(z.getBounds(e))?-1:0}function i(t,e,n,i){var s=[0,t],r=[1/3,e],a=[2/3,n],o=[1,i],h=g.getSignedDistance,u=h(0,t,1,i,1/3,e),l=h(0,t,1,i,2/3,n);if(0>u*l)return[s,r,o,a];var c,d;return Math.abs(u)>Math.abs(l)?(c=r,d=(i-n-(i-t)/3)*(2*(i-n)-i+e)/3):(c=a,d=(e-t+(t-i)/3)*(-2*(t-e)+t-n)/3),0>d?[s,c,o]:[s,r,a,o]}function s(e,n,i,s,r){for(var a=z.isLinear(e),o=a?n:e,h=a?e:n,u=h[0],l=h[1],c=h[6],d=h[7],_=c-u,f=d-l,g=Math.atan2(-f,_),v=Math.sin(g),m=Math.cos(g),p=_*m-f*v,y=[],w=0;8>w;w+=2){var x=o[w]-u,b=o[w+1]-l;y.push(x*m-b*v,b*m+x*v)}for(var C=[],S=z.solveCubic(y,1,0,C),w=0;S>w;w++){var P=C[w];if(P>=0&&1>=P){var M=z.evaluate(y,P,!0,0);M.x>=0&&M.x<=p&&t(r,a?s:i,P,z.evaluate(o,P,!0,0),a?i:s)}}}function r(e,n,i,s,r){var a=g.intersect(e[0],e[1],e[6],e[7],n[0],n[1],n[6],n[7]);a&&t(r,i,null,a,s)}return{statics:{getIntersections:function(t,n,i,a,o){var h=z.isLinear(t),u=z.isLinear(n);return(h&&u?r:h||u?s:e)(t,n,i,a,o),o}}}}),I=t.extend({_class:"CurveLocation",initialize:function ve(t,e,n,i,s,r,a){this._id=ve._id=(ve._id||0)+1,this._curve=t,this._segment1=t._segment1,this._segment2=t._segment2,this._parameter=e,this._point=n,this._curve2=i,this._parameter2=s,this._point2=r,this._distance=a},getSegment:function(){if(!this._segment){var t=this.getCurve(),e=this.getParameter();if(1===e)this._segment=t._segment2;else if(0===e||arguments[0])this._segment=t._segment1;else{if(null==e)return null;this._segment=t.getLength(0,e)a;a++)r[a]=i[a].getValues();for(var a=0,o=n.length;o>a;a++)for(var h=n[a],u=h.getValues(),l=0;s>l;l++)z.getIntersections(u,r[l],h,i[l],e);return e},setPathData:function(t){function e(t,e,n){var s=parseFloat(i[t]);return a&&(s+=h[e]),n&&(h[e]=s),s}function n(t,n){return new o(e(t,"x",n),e(t+1,"y",n))}var i,s,r=t.match(/[a-z][^a-z]*/gi),a=!1,h=new o;"path"===this._type?this.removeSegments():this.removeChildren();for(var u=0,l=r.length;l>u;u++){var c=r[u],d=c[0],_=d.toLowerCase();i=c.slice(1).trim().split(/[\s,]+|(?=[+-])/),a=d===_;var f=i.length;switch(_){case"m":case"l":for(var g=0;f>g;g+=2)this[0===g&&"m"===_?"moveTo":"lineTo"](n(g,!0));break;case"h":case"v":for(var v="h"==_?"x":"y",g=0;f>g;g++)e(g,v,!0),this.lineTo(h);break;case"c":for(var g=0;f>g;g+=6)this.cubicCurveTo(n(g),s=n(g+2),n(g+4,!0));break;case"s":for(var g=0;f>g;g+=4)this.cubicCurveTo(h.multiply(2).subtract(s),s=n(g),n(g+2,!0));break;case"q":for(var g=0;f>g;g+=4)this.quadraticCurveTo(s=n(g),n(g+2,!0));break;case"t":for(var g=0;f>g;g+=2)this.quadraticCurveTo(s=h.multiply(2).subtract(s),n(g,!0));break;case"a":break;case"z":this.closePath()}}},_canComposite:function(){return!(this.hasFill()&&this.hasStroke())}}),A=k.extend({_class:"Path",_serializeFields:{segments:[],closed:!1},initialize:function(t){this._closed=!1,this._segments=[],p.call(this);var e=Array.isArray(t)?"object"==typeof t[0]?t:arguments:!t||void 0===t.point&&void 0===t.x?null:arguments;this.setSegments(e||[]),t&&!e&&this._set(t)},clone:function(){var t=this._clone(new A(this._segments));return t._closed=this._closed,void 0!==this._clockwise&&(t._clockwise=this._clockwise),t},_changed:function(t){if(p.prototype._changed.call(this,t),4&t){if(delete this._length,delete this._clockwise,this._curves)for(var e=0,n=this._curves.length;n>e;e++)this._curves[e]._changed(5)}else 8&t&&delete this._bounds},getSegments:function(){return this._segments},setSegments:function(t){this._selectedSegmentState=0,this._segments.length=0,delete this._curves,this._add(P.readAll(t))},getFirstSegment:function(){return this._segments[0]},getLastSegment:function(){return this._segments[this._segments.length-1]},getCurves:function(){var t=this._curves,e=this._segments;if(!t){var n=this._countCurves();t=this._curves=Array(n);for(var i=0;n>i;i++)t[i]=new z(this,e[i],e[i+1]||e[0])}return t},getFirstCurve:function(){return this.getCurves()[0]},getLastCurve:function(){var t=this.getCurves();return t[t.length-1]},getPathData:function(){function t(t,e,r){var a=t._point,o=e._point,h=t._handleOut,u=e._handleIn;if(h.isZero()&&u.isZero())r||s.push("L"+i.point(o,n));else{var l=o.subtract(a);s.push("c"+i.point(h,n)+" "+i.point(l.add(u),n)+" "+i.point(l,n))}}var e=this._segments,n=arguments[0],i=r.instance,s=[];if(0===e.length)return"";s.push("M"+i.point(e[0]._point));for(var a=0,o=e.length-1;o>a;a++)t(e[a],e[a+1],!1);return this._closed&&(t(e[e.length-1],e[0],!0),s.push("z")),s.join("")},isClosed:function(){return this._closed},setClosed:function(t){if(this._closed!=(t=!!t)){if(this._closed=t,this._curves){var e=this._curves.length=this._countCurves();t&&(this._curves[e-1]=new z(this,this._segments[e-1],this._segments[0]))}this._changed(5)}},isEmpty:function(){return 0===this._segments.length},isPolygon:function(){for(var t=0,e=this._segments.length;e>t;t++)if(!this._segments[t].isLinear())return!1;return!0},_applyMatrix:function(t){for(var e=Array(6),n=0,i=this._segments.length;i>n;n++)this._segments[n]._transformCoordinates(t,e,!0);return!0},_add:function(t,e){for(var n=this._segments,i=this._curves,s=t.length,r=null==e,e=r?n.length:e,a=this.isFullySelected(),o=0;s>o;o++){var h=t[o];h._path&&(h=t[o]=h.clone()),h._path=this,h._index=e+o,a&&(h._selectionState=4),h._selectionState&&this._updateSelection(h,0,h._selectionState)}if(r)n.push.apply(n,t);else{n.splice.apply(n,[e,0].concat(t));for(var o=e+s,u=n.length;u>o;o++)n[o]._index=o}if(i||t._curves){i||(i=this._curves=[]);var l=e>0?e-1:e,c=l,d=Math.min(l+s,this._countCurves());t._curves&&(i.splice.apply(i,[l,0].concat(t._curves)),c+=t._curves.length);for(var o=c;d>o;o++)i.splice(o,0,new z(this,null,null));this._adjustCurves(l,d)}return this._changed(5),t},_adjustCurves:function(t,e){for(var n,i=this._segments,s=this._curves,r=t;e>r;r++)n=s[r],n._path=this,n._segment1=i[r],n._segment2=i[r+1]||i[0];(n=s[this._closed&&0===t?i.length-1:t-1])&&(n._segment2=i[t]||i[0]),(n=s[e])&&(n._segment1=i[e])},_countCurves:function(){var t=this._segments.length;return!this._closed&&t>0?t-1:t},add:function(t){return arguments.length>1&&"number"!=typeof t?this._add(P.readAll(arguments)):this._add([P.read(arguments)])[0]},insert:function(t,e){return arguments.length>2&&"number"!=typeof e?this._add(P.readAll(arguments,1),t):this._add([P.read(arguments,1)],t)[0]},addSegment:function(){return this._add([P.read(arguments)])[0]},insertSegment:function(t){return this._add([P.read(arguments,1)],t)[0]},addSegments:function(t){return this._add(P.readAll(t))},insertSegments:function(t,e){return this._add(P.readAll(e),t)},removeSegment:function(t){return this.removeSegments(t,t+1)[0]||null},removeSegments:function(e,n){e=e||0,n=t.pick(n,this._segments.length);var i=this._segments,s=this._curves,r=i.length,a=i.splice(e,n-e),o=a.length;if(!o)return a;for(var h=0;o>h;h++){var u=a[h];u._selectionState&&this._updateSelection(u,u._selectionState,0),delete u._index,delete u._path}for(var h=e,l=i.length;l>h;h++)i[h]._index=h;if(s){var c=e>0&&n===r+(this._closed?1:0)?e-1:e,s=s.splice(c,o);arguments[2]&&(a._curves=s.slice(1)),this._adjustCurves(c,c)}return this._changed(5),a},isFullySelected:function(){return this._selected&&this._selectedSegmentState==4*this._segments.length},setFullySelected:function(t){t&&this._selectSegments(!0),this.setSelected(t)},setSelected:function me(t){t||this._selectSegments(!1),me.base.call(this,t)},_selectSegments:function(t){var e=this._segments.length;this._selectedSegmentState=t?4*e:0;for(var n=0;e>n;n++)this._segments[n]._selectionState=t?4:0},_updateSelection:function(t,e,n){t._selectionState=n;var i=this._selectedSegmentState+=n-e;i>0&&this.setSelected(!0)},flatten:function(t){for(var e=new L(this),n=0,i=e.length/Math.ceil(e.length/t),s=e.length+(this._closed?-i:i)/2,r=[];s>=n;)r.push(new P(e.evaluate(n,0))),n+=i;this.setSegments(r)},simplify:function(t){if(this._segments.length>2){var e=new D(this,t||2.5);this.setSegments(e.fit())}},split:function(t,e){if(null!==e){if(1==arguments.length){var n=t;"number"==typeof n&&(n=this.getLocationAt(n)),t=n.index,e=n.parameter}e>=1&&(t++,e--);var i=this.getCurves();if(t>=0&&t0&&i[t++].divide(e);var s,r=this.removeSegments(t,this._segments.length,!0);return this._closed?(this.setClosed(!1),s=this):t>0&&(s=this._clone((new A).insertAbove(this,!0))),s._add(r,0),this.addSegment(r[0]),s}return null}},isClockwise:function(){return void 0!==this._clockwise?this._clockwise:A.isClockwise(this._segments)},setClockwise:function(t){this.isClockwise()!=(t=!!t)&&this.reverse(),this._clockwise=t},reverse:function(){this._segments.reverse();for(var t=0,e=this._segments.length;e>t;t++){var n=this._segments[t],i=n._handleIn;n._handleIn=n._handleOut,n._handleOut=i,n._index=t}delete this._curves,void 0!==this._clockwise&&(this._clockwise=!this._clockwise)},join:function(t){if(t){var e=t._segments,n=this.getLastSegment(),i=t.getLastSegment();n._point.equals(i._point)&&t.reverse();var s=t.getFirstSegment();if(n._point.equals(s._point))n.setHandleOut(s._handleOut),this._add(e.slice(1));else{var r=this.getFirstSegment();r._point.equals(s._point)&&t.reverse(),i=t.getLastSegment(),r._point.equals(i._point)?(r.setHandleIn(i._handleIn),this._add(e.slice(0,e.length-1),0)):this._add(e.slice())}t.remove();var r=this.getFirstSegment();return n=this.getLastSegment(),n._point.equals(r._point)&&(r.setHandleIn(n._handleIn),n.remove(),this.setClosed(!0)),this._changed(5),!0}return!1},reduce:function(){return this},getLength:function(){if(null==this._length){var t=this.getCurves();this._length=0;for(var e=0,n=t.length;n>e;e++)this._length+=t[e].getLength()}return this._length},getArea:function(){for(var t=this.getCurves(),e=0,n=0,i=t.length;i>n;n++)e+=t[n].getArea();return e},_getOffset:function(t){var e=t&&t.getIndex();if(null!=e){for(var n=this.getCurves(),i=0,s=0;e>s;s++)i+=n[s].getLength();var r=n[e];return i+r.getLength(0,t.getParameter())}return null},getLocationOf:function(t){t=o.read(arguments);for(var e=this.getCurves(),n=0,i=e.length;i>n;n++){var s=e[n].getLocationOf(t);if(s)return s}return null},getLocationAt:function(t,e){var n=this.getCurves(),i=0;if(e){var s=~~t;return n[s].getLocationAt(t-s,!0)}for(var r=0,a=n.length;a>r;r++){var o=i,h=n[r];if(i+=h.getLength(),i>=t)return h.getLocationAt(t-o)}return t<=this.getLength()?new I(n[n.length-1],1):null},getPointAt:function(t,e){var n=this.getLocationAt(t,e);return n&&n.getPoint()},getTangentAt:function(t,e){var n=this.getLocationAt(t,e);return n&&n.getTangent()},getNormalAt:function(t,e){var n=this.getLocationAt(t,e);return n&&n.getNormal()},getNearestLocation:function(t){t=o.read(arguments);for(var e=this.getCurves(),n=1/0,i=null,s=0,r=e.length;r>s;s++){var a=e[s].getNearestLocation(t);a._distanceh;h++){var l=n[h].getValues(),c=l[0],d=l[1];(c!==l[2]||d!==l[3]||c!==l[4]||d!==l[5]||c!==l[6]||d!==l[7])&&(s+=z._getCrossings(l,o,t.x,t.y,r),o=l)}return e||(s+=z._getCrossings(a,o,t.x,t.y,r)),1===(1&s)},_hitTest:function(t,e){function n(e,n,i){return t.getDistance(n)a;a++){var o=r(a);s+=z._getCrossings(o,n,t.x,t.y,i),n=o}return 1===(1&s)}function o(e){return("round"!==h||"round"!==u)&&(c=[],v||e._index>0&&e._index0)?a(t):t.getDistance(e._point)<=p}var h,u,l,c,d,_,f=this.getStyle(),g=this._segments,v=this._closed,m=e.tolerance||0,p=0,y=this;if(e.stroke&&f.getStrokeColor()&&(h=f.getStrokeJoin(),u=f.getStrokeCap(),p=f.getStrokeWidth()/2+m,l=p*f.getMiterLimit()),!e.ends||e.segments||v){if(e.segments||e.handles)for(var w=0,x=g.length;x>w;w++)if(_=i(g[w]))return _}else if(_=i(g[0],!0)||i(g[g.length-1],!0))return _;if(p>0){if(d=this.getNearestLocation(t)){var b=d.getParameter();0===b||1===b?o(d.getSegment())||(d=null):d._distance>p&&(d=null)}if(!d&&"miter"===h)for(var w=0,x=g.length;x>w;w++){var C=g[w];if(t.getDistance(C._point)<=l&&o(C)){d=C.getLocation();break}}}return!d&&e.fill&&this.hasFill()&&this.contains(t)?new S("fill",this):d?new S("stroke",this,{location:d}):null}},new function(){function t(t,e,n,i){function s(e){var n=a[e],i=a[e+1];(d!=n||_!=i)&&(t.beginPath(),t.moveTo(d,_),t.lineTo(n,i),t.stroke(),t.beginPath(),t.arc(n,i,r,0,2*Math.PI,!0),t.fill())}for(var r=i/2,a=Array(6),o=0,h=e.length;h>o;o++){var u=e[o];u._transformCoordinates(n,a,!1);var l=u._selectionState,c=4&l,d=a[0],_=a[1];(c||1&l)&&s(2),(c||2&l)&&s(4),t.save(),t.beginPath(),t.rect(d-r,_-r,i,i),t.fill(),c||(t.beginPath(),t.rect(d-r+1,_-r+1,i-2,i-2),t.fillStyle="#ffffff",t.fill()),t.restore()}}function e(t,e,n){function i(e){var i=d[e];if(n)i._transformCoordinates(n,f,!1),s=f[0],r=f[1];else{var _=i._point;s=_._x,r=_._y}if(g)t.moveTo(s,r),g=!1;else{if(n)h=f[2],u=f[3];else{var v=i._handleIn;h=s+v._x,u=r+v._y}h==s&&u==r&&l==a&&c==o?t.lineTo(s,r):t.bezierCurveTo(l,c,h,u,s,r)}if(a=s,o=r,n)l=f[4],c=f[5];else{var v=i._handleOut;l=a+v._x,c=o+v._y}}for(var s,r,a,o,h,u,l,c,d=e._segments,_=d.length,f=Array(6),g=!0,v=0;_>v;v++)i(v);e._closed&&_>1&&i(0)}return{_draw:function(t,n){var i=n.clip,s=n.compound;s||t.beginPath();var r=this.getStyle(),a=r.getFillColor(),o=r.getStrokeColor(),h=r.getDashArray(),u=!paper.support.nativeDash&&o&&h&&h.length;if((a||o&&!u||s||i)&&e(t,this),this._closed&&t.closePath(),!i&&!s&&(a||o)&&(this._setStyles(t),a&&t.fill(),o)){if(u){t.beginPath();for(var l,c=new L(this),d=r.getDashOffset(),_=0;dr;r++)i[r]=1/s,s=(e-1>r?4:2)-i[r],n[r]=(t[r]-n[r-1])/s;for(var r=1;e>r;r++)n[e-r-1]-=i[e-r]*n[e-r];return n}return{smooth:function(){var e,n=this._segments,i=n.length,s=i;if(!(2>=i)){this._closed?(e=Math.min(i,4),s+=2*Math.min(i,e)):e=0;for(var r=[],a=0;i>a;a++)r[a+e]=n[a]._point;if(this._closed)for(var a=0;e>a;a++)r[a]=n[a+i-e]._point,r[a+i+e]=n[a]._point;else s--;for(var h=[],a=1;s-1>a;a++)h[a]=4*r[a]._x+2*r[a+1]._x;h[0]=r[0]._x+2*r[1]._x,h[s-1]=3*r[s-1]._x;for(var u=t(h),a=1;s-1>a;a++)h[a]=4*r[a]._y+2*r[a+1]._y;h[0]=r[0]._y+2*r[1]._y,h[s-1]=3*r[s-1]._y;var l=t(h);if(this._closed){for(var a=0,c=i;e>a;a++,c++){var d=a/e,_=1-d,f=a+e,g=c+e;u[c]=u[a]*d+u[c]*_,l[c]=l[a]*d+l[c]*_,u[g]=u[f]*_+u[g]*d,l[g]=l[f]*_+l[g]*d}s--}for(var v=null,a=e;s-e>=a;a++){var m=n[a-e];v&&m.setHandleIn(v.subtract(m._point)),s>a&&(m.setHandleOut(new o(u[a],l[a]).subtract(m._point)),v=s-1>a?new o(2*r[a+1]._x-u[a+1],2*r[a+1]._y-l[a+1]):new o((r[s]._x+u[s-1])/2,(r[s]._y+l[s-1])/2))}if(this._closed&&v){var m=this._segments[0];m.setHandleIn(v.subtract(m._point))}}}}},new function(){function e(t){var e=t._segments;if(0==e.length)throw Error("Use a moveTo() command first");return e[e.length-1]}return{moveTo:function(){1===this._segments.length&&this.removeSegment(0),this._segments.length||this._add([new P(o.read(arguments))])},moveBy:function(){throw Error("moveBy() is unsupported on Path items.")},lineTo:function(){this._add([new P(o.read(arguments))])},cubicCurveTo:function(){var t=o.read(arguments),n=o.read(arguments),i=o.read(arguments),s=e(this);s.setHandleOut(t.subtract(s._point)),this._add([new P(i,n.subtract(i))])},quadraticCurveTo:function(){var t=o.read(arguments),n=o.read(arguments),i=e(this)._point;this.cubicCurveTo(t.add(i.subtract(t).multiply(1/3)),t.add(n.subtract(t).multiply(1/3)),n)},curveTo:function(){var n=o.read(arguments),i=o.read(arguments),s=t.pick(t.read(arguments),.5),r=1-s,a=e(this)._point,h=n.subtract(a.multiply(r*r)).subtract(i.multiply(s*s)).divide(2*s*r);if(h.isNaN())throw Error("Cannot put a curve through points with parameter = "+s);this.quadraticCurveTo(h,i)},arcTo:function(n,i){var s,r=e(this),a=r._point,h=o.read(arguments),u=t.pick(t.peek(arguments),!0);if("boolean"==typeof u){n=h,i=u;var l=a.add(n).divide(2),s=l.add(l.subtract(a).rotate(i?-90:90))}else s=h,n=o.read(arguments);var c=new g(a.add(s).divide(2),s.subtract(a).rotate(90),!0),d=new g(s.add(n).divide(2),n.subtract(s).rotate(90),!0),_=c.intersect(d,!0),f=new g(a,n),v=f.getSide(s);if(!_){if(!v)return this.lineTo(n);throw Error("Cannot put an arc through the given points: "+[a,s,n])}var m=a.subtract(_),p=m.getDirectedAngle(n.subtract(_)),y=f.getSide(_);0==y?p=v*Math.abs(p):v==y&&(p-=360*(0>p?-1:1));for(var w=Math.abs(p),x=w>=360?4:Math.ceil(w/90),b=p/x,C=b*Math.PI/360,S=4/3*Math.sin(C)/(1+Math.cos(C)),M=[],z=0;x>=z;z++){var I=x>z?_.add(m):n,k=x>z?m.rotate(90).multiply(S):null;0==z?r.setHandleOut(k):M.push(new P(I,m.rotate(-90).multiply(S),k)),m=m.rotate(b)}this._add(M)},lineBy:function(t){t=o.read(arguments);var n=e(this);this.lineTo(n._point.add(t))},curveBy:function(t,n,i){t=o.read(t),n=o.read(n);var s=e(this)._point;this.curveTo(s.add(t),s.add(n),i)},arcBy:function(t,n){t=o.read(t),n=o.read(n); +var i=e(this)._point;this.arcTo(i.add(t),i.add(n))},closePath:function(){var t=this.getFirstSegment(),e=this.getLastSegment();t._point.equals(e._point)&&(t.setHandleIn(e._handleIn),e.remove()),this.setClosed(!0)}}},{_getBounds:function(t,e){return A[t](this._segments,this._closed,this.getStyle(),e)},statics:{isClockwise:function(t){function e(t,e){r&&(s+=(n-t)*(e+i)),n=t,i=e,r=!0}for(var n,i,s=0,r=!1,a=0,o=t.length;o>a;a++){var h=t[a],u=t[o>a+1?a+1:0],l=h._point,c=h._handleOut,d=u._handleIn,_=u._point;e(l._x,l._y),e(l._x+c._x,l._y+c._y),e(_._x+d._x,_._y+d._y),e(_._x,_._y)}return s>0},getBounds:function(t,e,n,i,s){function r(t){t._transformCoordinates(i,o,!1);for(var e=0;2>e;e++)z._addBounds(h[e],h[e+4],o[e+2],o[e],e,s?s[e]:0,u,l,c);var n=h;h=o,o=n}var a=t[0];if(!a)return new d;for(var o=Array(6),h=a._transformCoordinates(i,Array(6),!1),u=h.slice(0,2),l=u.slice(),c=Array(2),_=1,f=t.length;f>_;_++)r(t[_]);return e&&r(a),new d(u[0],u[1],l[0]-u[0],l[1]-u[1])},getStrokeBounds:function(t,e,n,i){function s(t,e){if(!e)return[t,t];var n=e.shiftless(),i=n.transform(new o(t,0)),s=n.transform(new o(0,t)),r=i.getAngleInRadians(),a=i.getLength(),h=s.getLength(),u=Math.sin(r),l=Math.cos(r),c=Math.tan(r),d=-Math.atan(h*c/a),_=Math.atan(h/(c*a));return[Math.abs(a*Math.cos(d)*l-h*Math.sin(d)*u),Math.abs(h*Math.sin(_)*l+a*Math.cos(_)*u)]}function r(t){f=f.include(i?i._transformPoint(t,t):t)}function a(t,e){"round"===e||!t._handleIn.isZero()&&!t._handleOut.isZero()?f=f.unite(p.setCenter(i?i._transformPoint(t._point):t._point)):A._addSquareJoin(t,e,c,m,r)}function h(t,e){switch(e){case"round":a(t,e);break;case"butt":case"square":A._addSquareCap(t,e,c,r)}}if(!n.getStrokeColor()||!n.getStrokeWidth())return A.getBounds(t,e,n,i);for(var l=t.length-(e?0:1),c=n.getStrokeWidth()/2,_=s(c,i),f=A.getBounds(t,e,n,i,_),g=n.getStrokeJoin(),v=n.getStrokeCap(),m=c*n.getMiterLimit(),p=new d(new u(_).multiply(2)),y=1;l>y;y++)a(t[y],g);return e?a(t[0],g):(h(t[0],v),h(t[t.length-1],v)),f},_addSquareJoin:function(t,e,n,i,s,r){var a=t.getCurve(),h=a.getPrevious(),u=a.getPointAt(0,!0),l=h.getNormalAt(1,!0),c=a.getNormalAt(0,!0),d=l.getDirectedAngle(c)<0?-n:n;if(l.setLength(d),c.setLength(d),r&&(s(u),s(u.add(l))),"miter"===e){var _=new g(u.add(l),new o(-l.y,l.x),!0).intersect(new g(u.add(c),new o(-c.y,c.x),!0),!0);if(_&&u.getDistance(_)<=i&&(s(_),!r))return}r||s(u.add(l)),s(u.add(c))},_addSquareCap:function(t,e,n,i,s){var r=t._point,a=t.getLocation(),o=a.getNormal().normalize(n);s&&(i(r.subtract(o)),i(r.add(o))),"square"===e&&(r=r.add(o.rotate(0==a.getParameter()?-90:90))),i(r.add(o)),i(r.subtract(o))},getHandleBounds:function(t,e,n,i,s,r){var a=Array(6),o=1/0,h=-o,u=o,l=h;s=s/2||0,r=r/2||0;for(var c=0,_=t.length;_>c;c++){var f=t[c];f._transformCoordinates(i,a,!1);for(var g=0;6>g;g+=2){var v=0==g?r:s,m=a[g],p=a[g+1],y=m-v,w=m+v,x=p-v,b=p+v;o>y&&(o=y),w>h&&(h=w),u>x&&(u=x),b>l&&(l=b)}}return new d(o,u,h-o,l-u)},getRoughBounds:function(t,e,n,i){var s=n.getStrokeColor()?n.getStrokeWidth():0,r=s;return s>0&&("miter"===n.getStrokeJoin()&&(r=s*n.getMiterLimit()),"square"===n.getStrokeCap()&&(r=Math.max(r,s*Math.sqrt(2)))),A.getHandleBounds(t,e,n,i,s,r)}}});A.inject({statics:new function(){function e(e){var n=new A,i=t.getNamed(e);return i&&n._set(i),n}function n(){var t=d.readNamed(arguments,"rectangle"),n=u.readNamed(arguments,"radius",0,0,!0),i=t.getBottomLeft(!0),r=t.getTopLeft(!0),a=t.getTopRight(!0),o=t.getBottomRight(!0),h=e(arguments);if(!n||n.isZero())h._add([new P(i),new P(r),new P(a),new P(o)]);else{n=u.min(n,t.getSize(!0).divide(2));var l=n.multiply(2*s);h._add([new P(i.add(n.width,0),null,[-l.width,0]),new P(i.subtract(0,n.height),[0,l.height],null),new P(r.add(0,n.height),null,[0,-l.height]),new P(r.add(n.width,0),[-l.width,0],null),new P(a.subtract(n.width,0),null,[l.width,0]),new P(a.add(0,n.height),[0,-l.height],null),new P(o.subtract(0,n.height),null,[0,l.height]),new P(o.subtract(n.width,0),[l.width,0],null)])}return h._closed=!0,h}function i(){for(var t=d.readNamed(arguments,"rectangle"),n=e(arguments),i=t.getPoint(!0),s=t.getSize(!0),a=Array(4),o=0;4>o;o++){var h=r[o];a[o]=new P(h._point.multiply(s).add(i),h._handleIn.multiply(s),h._handleOut.multiply(s))}return n._add(a),n._closed=!0,n}var s=a.KAPPA/2,r=[new P([0,.5],[0,s],[0,-s]),new P([.5,0],[-s,0],[s,0]),new P([1,.5],[0,-s],[0,s]),new P([.5,1],[s,0],[-s,0])];return{Line:function(){return new A(o.readNamed(arguments,"from"),o.readNamed(arguments,"to")).set(t.getNamed(arguments))},Rectangle:n,RoundRectangle:n,Ellipse:i,Oval:i,Circle:function(){var e=o.readNamed(arguments,"center"),n=t.readNamed(arguments,"radius");return i(new d(e.subtract(n),new u(2*n,2*n))).set(t.getNamed(arguments))},Arc:function(){var t=o.readNamed(arguments,"from"),n=o.readNamed(arguments,"through"),i=o.readNamed(arguments,"to"),s=e(arguments);return s.moveTo(t),s.arcTo(n,i),s},RegularPolygon:function(){for(var n=o.readNamed(arguments,"center"),i=t.readNamed(arguments,"sides"),s=t.readNamed(arguments,"radius"),r=e(arguments),a=360/i,h=!(i%3),u=new o(0,h?-s:s),l=h?-1:.5,c=Array(i),d=0;i>d;d++)c[d]=new P(n.add(u.rotate((d+l)*a)));return r._add(c),r._closed=!0,r},Star:function(){for(var n=o.readNamed(arguments,"center"),i=2*t.readNamed(arguments,"points"),s=t.readNamed(arguments,"radius1"),r=t.readNamed(arguments,"radius2"),a=e(arguments),h=360/i,u=new o(0,-1),l=Array(i),c=0;i>c;c++)l[c]=new P(n.add(u.rotate(h*c).multiply(c%2?r:s)));return a._add(l),a._closed=!0,a}}}});var O=k.extend({_class:"CompoundPath",_serializeFields:{children:[]},initialize:function(t){k.call(this),this._children=[],this._namedChildren={},t&&!this._set(t)&&this.addChildren(Array.isArray(t)?t:arguments)},insertChildren:function pe(t,e,n){e=pe.base.call(this,t,e,n,"path");for(var i=0,s=!n&&e&&e.length;s>i;i++){var r=e[i];void 0===r._clockwise&&r.setClockwise(0===r._index)}return e},reduce:function(){if(1==this._children.length){var t=this._children[0];return t.insertAbove(this),this.remove(),t}return this},reverse:function(){for(var t=this._children,e=0,n=t.length;n>e;e++)t[e].reverse()},smooth:function(){for(var t=0,e=this._children.length;e>t;t++)this._children[t].smooth()},isClockwise:function(){var t=this.getFirstChild();return t&&t.isClockwise()},setClockwise:function(t){this.isClockwise()!=!!t&&this.reverse()},getFirstSegment:function(){var t=this.getFirstChild();return t&&t.getFirstSegment()},getLastSegment:function(){var t=this.getLastChild();return t&&t.getLastSegment()},getCurves:function(){for(var t=this._children,e=[],n=0,i=t.length;i>n;n++)e=e.concat(t[n].getCurves());return e},getFirstCurve:function(){var t=this.getFirstChild();return t&&t.getFirstCurve()},getLastCurve:function(){var t=this.getLastChild();return t&&t.getFirstCurve()},getArea:function(){for(var t=this._children,e=0,n=0,i=t.length;i>n;n++)e+=t[n].getArea();return e},getPathData:function(){for(var t=this._children,e=[],n=0,i=t.length;i>n;n++)e.push(t[n].getPathData(arguments[0]));return e.join(" ")},_contains:function(t){for(var e=[],n=0,i=this._children.length;i>n;n++){var s=this._children[n];s.contains(t)&&e.push(s)}return 1==(1&e.length)&&e},_hitTest:function ye(e,n){var i=ye.base.call(this,e,t.merge(n,{fill:!1}));return!i&&n.fill&&this.hasFill()&&(i=this._contains(e),i=i?new S("fill",i[0]):null),i},_draw:function(t,e){var n=this._children,i=this._style;if(0!==n.length){t.beginPath(),e=e.extend({compound:!0});for(var s=0,r=n.length;r>s;s++)n[s].draw(t,e);e.clip||(this._setStyles(t),i.getFillColor()&&t.fill(),i.getStrokeColor()&&t.stroke())}}},new function(){function e(t){if(!t._children.length)throw Error("Use a moveTo() command first");return t._children[t._children.length-1]}var n={moveTo:function(){var t=new A;this.addChild(t),t.moveTo.apply(t,arguments)},moveBy:function(){this.moveTo(e(this).getLastSegment()._point.add(o.read(arguments)))},closePath:function(){e(this).closePath()}};return t.each(["lineTo","cubicCurveTo","quadraticCurveTo","curveTo","arcTo","lineBy","curveBy","arcBy"],function(t){n[t]=function(){var n=e(this);n[t].apply(n,arguments)}}),n}),L=t.extend({initialize:function(t){function e(t,e){var n=z.getValues(t,e);r.curves.push(n),r._computeParts(n,t._index,0,1)}this.curves=[],this.parts=[],this.length=0,this.index=0;for(var n,i=t._segments,s=i[0],r=this,a=1,o=i.length;o>a;a++)n=i[a],e(s,n),s=n;t._closed&&e(n,i[0])},_computeParts:function(t,e,n,i){if(i-n>1/32&&!z.isFlatEnough(t,.25)){var s=z.subdivide(t),r=(n+i)/2;this._computeParts(s[0],e,n,r),this._computeParts(s[1],e,r,i)}else{var a=t[6]-t[0],o=t[7]-t[1],h=Math.sqrt(a*a+o*o);h>1e-5&&(this.length+=h,this.parts.push({offset:this.length,value:i,index:e}))}},getParameterAt:function(t){for(var e,n=this.index;e=n,!(0==n||this.parts[--n].offsete;e++){var s=this.parts[e];if(s.offset>=t){this.index=e;var r=this.parts[e-1],a=r&&r.index==s.index?r.value:0,o=r?r.offset:0;return{value:a+(s.value-a)*(t-o)/(s.offset-o),index:s.index}}}var s=this.parts[this.parts.length-1];return{value:1,index:s.index}},evaluate:function(t,e){var n=this.getParameterAt(t);return z.evaluate(this.curves[n.index],n.value,!0,e)},drawPart:function(t,e,n){e=this.getParameterAt(e),n=this.getParameterAt(n);for(var i=e.index;i<=n.index;i++){var s=z.getPart(this.curves[i],i==e.index?e.value:0,i==n.index?n.value:1);i==e.index&&t.moveTo(s[0],s[1]),t.bezierCurveTo.apply(t,s.slice(2))}}}),D=t.extend({initialize:function(t,e){this.points=[];for(var n,i=t._segments,s=0,r=i.length;r>s;s++){var a=i[s].point.clone();n&&n.equals(a)||(this.points.push(a),n=a)}this.error=e},fit:function(){var t=this.points,e=t.length;return this.segments=e>0?[new P(t[0])]:[],e>1&&this.fitCubic(0,e-1,t[1].subtract(t[0]).normalize(),t[e-2].subtract(t[e-1]).normalize()),this.segments},fitCubic:function(t,e,n,i){if(1==e-t){var s=this.points[t],r=this.points[e],a=s.getDistance(r)/3;return this.addCurve([s,s.add(n.normalize(a)),r.add(i.normalize(a)),r]),void 0}for(var o,h=this.chordLengthParameterize(t,e),u=Math.max(this.error,this.error*this.error),l=0;4>=l;l++){var c=this.generateBezier(t,e,h,n,i),d=this.findMaxError(t,e,c,h);if(d.error=u)break;this.reparameterize(t,e,h,c),u=d.error}var _=this.points[o-1].subtract(this.points[o]),f=this.points[o].subtract(this.points[o+1]),g=_.add(f).divide(2).normalize();this.fitCubic(t,o,n,g),this.fitCubic(o,e,g.negate(),i)},addCurve:function(t){var e=this.segments[this.segments.length-1];e.setHandleOut(t[1].subtract(t[0])),this.segments.push(new P(t[3],t[2].subtract(t[3])))},generateBezier:function(t,e,n,i,s){for(var r=1e-11,a=this.points[t],o=this.points[e],h=[[0,0],[0,0]],u=[0,0],l=0,c=e-t+1;c>l;l++){var d=n[l],_=1-d,f=3*d*_,g=_*_*_,v=f*_,m=f*d,p=d*d*d,y=i.normalize(v),w=s.normalize(m),x=this.points[t+l].subtract(a.multiply(g+v)).subtract(o.multiply(m+p));h[0][0]+=y.dot(y),h[0][1]+=y.dot(w),h[1][0]=h[0][1],h[1][1]+=w.dot(w),u[0]+=y.dot(x),u[1]+=w.dot(x)}var b,C,S=h[0][0]*h[1][1]-h[1][0]*h[0][1];if(Math.abs(S)>r){var P=h[0][0]*u[1]-h[1][0]*u[0],M=u[0]*h[1][1]-u[1]*h[0][1];b=M/S,C=P/S}else{var z=h[0][0]+h[0][1],I=h[1][0]+h[1][1];b=C=Math.abs(z)>r?u[0]/z:Math.abs(I)>r?u[1]/I:0}var k=o.getDistance(a);return r*=k,(r>b||r>C)&&(b=C=k/3),[a,a.add(i.normalize(b)),o.add(s.normalize(C)),o]},reparameterize:function(t,e,n,i){for(var s=t;e>=s;s++)n[s-t]=this.findRoot(i,this.points[s],n[s-t])},findRoot:function(t,e,n){for(var i=[],s=[],r=0;2>=r;r++)i[r]=t[r+1].subtract(t[r]).multiply(3);for(var r=0;1>=r;r++)s[r]=i[r+1].subtract(i[r]).multiply(2);var a=this.evaluate(3,t,n),o=this.evaluate(2,i,n),h=this.evaluate(1,s,n),u=a.subtract(e),l=o.dot(o)+u.dot(h);return Math.abs(l)<1e-5?n:n-u.dot(o)/l},evaluate:function(t,e,n){for(var i=e.slice(),s=1;t>=s;s++)for(var r=0;t-s>=r;r++)i[r]=i[r].multiply(1-n).add(i[r+1].multiply(n));return i[0]},chordLengthParameterize:function(t,e){for(var n=[0],i=t+1;e>=i;i++)n[i-t]=n[i-t-1]+this.points[i].getDistance(this.points[i-1]);for(var i=1,s=e-t;s>=i;i++)n[i]/=n[s];return n},findMaxError:function(t,e,n,i){for(var s=Math.floor((e-t+1)/2),r=0,a=t+1;e>a;a++){var o=this.evaluate(3,n,i[a-t]),h=o.subtract(this.points[a]),u=h.x*h.x+h.y*h.y;u>=r&&(r=u,s=a)}return{error:r,index:s}}});k.inject(new function(){function t(t,e){t.sort(function(t,e){var n=t.getPath(),i=e.getPath();return n===i?t.getIndex()+t.getParameter()-(e.getIndex()+e.getParameter()):n._id-i._id});for(var n=e&&[],i=t.length-1;i>=0;i--){var s=t[i],r=s.getIntersection(),a=s.divide(),o=a&&a.getSegment1()||s.getSegment();n&&n.push(r),o._intersection=r}return n}function e(t){if(t instanceof O){for(var e=t._children,n=e.length,i=Array(n),s=Array(n),r=e[0].isClockwise(),a=0;n>a;a++)i[a]=e[a].getBounds(),s[a]=0;for(var a=0;n>a;a++){for(var o=1;n>o;o++)a!==o&&i[a].contains(i[o])&&s[o]++;a>0&&0===s[a]%2&&e[a].setClockwise(r)}}return t}function n(n,s,r,a){n=e(n.clone()),s=e(s.clone());var h=n.isClockwise(),u=s.isClockwise(),l=n.getIntersections(s);t(t(l,!0)),a&&(s.reverse(),u=!u);for(var c=[].concat(n._children||[n]).concat(s._children||[s]),d=[],_=new O,f=0,g=c.length;g>f;f++){var v=c[f],m=v._parent,p=v.isClockwise(),y=v._segments;v=m instanceof O?m:v;for(var w=y.length-1;w>=0;w--){var x=y[w],b=x.getCurve().getPoint(.5),C=v!==n&&n.contains(b)&&(p===h||a||!i(n,b)),S=v!==s&&s.contains(b)&&(p===u||!i(s,b));r(v===n,C,S)?x._invalid=!0:d.push(x)}}for(var f=0,g=d.length;g>f;f++){var x=d[f];if(!x._visited){var v=new A,M=x._intersection,z=M&&M.getSegment(!0);x.getPrevious()._invalid&&x.setHandleIn(z?z._handleIn:new o(0,0));do{if(x._visited=!0,x._invalid&&x._intersection){var I=x._intersection.getSegment(!0);v.add(new P(x._point,x._handleIn,I._handleOut)),I._visited=!0,x=I}else v.add(x.clone());x=x.getNext()}while(x&&!x._visited&&x!==z);var k=v._segments.length;k>1&&(k>2||!v.isPolygon())?(v.setClosed(!0),_.addChild(v,!0)):v.remove()}}return n.remove(),s.remove(),_.reduce()}function i(t,e){var n=t.getCurves(),i=t.getBounds();if(i.contains(e))for(var s=0,r=n.length;r>s;s++){var a=n[s];if(a.getBounds().contains(e)&&a.getParameterOf(e))return!0}return!1}return{unite:function(t){return n(this,t,function(t,e,n){return e||n})},intersect:function(t){return n(this,t,function(t,e,n){return!(e||n)})},subtract:function(t){return n(this,t,function(t,e,n){return t&&n||!t&&!e},!0)},exclude:function(t){return new y([this.subtract(t),t.subtract(this)])},divide:function(t){return new y([this.subtract(t),this.intersect(t)])}}});var T=p.extend({_class:"TextItem",_boundsSelected:!0,_serializeFields:{content:null},_boundsGetter:"getBounds",initialize:function(e){var n=e&&t.isPlainObject(e)&&void 0===e.x&&void 0===e.y;p.call(this,n?null:o.read(arguments)),this._content="",this._lines=[],n&&this._set(e)},_clone:function we(t){return t.setContent(this._content),we.base.call(this,t)},getContent:function(){return this._content},setContent:function(t){this._content=""+t,this._lines=this._content.split(/\r\n|\n|\r/gm),this._changed(69)},isEmpty:function(){return!this._content},getCharacterStyle:"#getStyle",setCharacterStyle:"#setStyle",getParagraphStyle:"#getStyle",setParagraphStyle:"#setStyle"}),j=T.extend({_class:"PointText",initialize:function(){T.apply(this,arguments)},clone:function(){return this._clone(new j)},getPoint:function(){var t=this._matrix.getTranslation();return new h(t.x,t.y,this,"setPoint")},setPoint:function(t){t=o.read(arguments),this.translate(t.subtract(this._matrix.getTranslation()))},_draw:function(t){if(this._content){this._setStyles(t);var e=this._style,n=this._lines,i=e.getLeading();t.font=e.getFontStyle(),t.textAlign=e.getJustification();for(var s=0,r=n.length;r>s;s++){var a=n[s];e.getFillColor()&&t.fillText(a,0,0),e.getStrokeColor()&&t.strokeText(a,0,0),t.translate(0,i)}}}},new function(){var t=null;return{_getBounds:function(e,n){t||(t=$.getContext(1,1));var i=this._style,s=this._lines,r=s.length,a=i.getJustification(),o=i.getLeading(),h=0;t.font=i.getFontStyle();for(var u=0,l=0;r>l;l++)u=Math.max(u,t.measureText(s[l]).width);"left"!==a&&(h-=u/("center"===a?2:1));var c=new d(h,r?-.75*o:0,u,r*o);return n?n._transformBounds(c,c):c}}}),B=t.extend(new function(){function e(t){var e=h[t];if(!e){i||(i=$.getContext(1,1),i.globalCompositeOperation="copy"),i.fillStyle="rgba(0,0,0,0)",i.fillStyle=t,i.fillRect(0,0,1,1);var n=i.getImageData(0,0,1,1).data;e=h[t]=[n[0]/255,n[1]/255,n[2]/255]}return e.slice()}function n(t){var e=t.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);if(e.length>=4){for(var n=[0,0,0],i=0;3>i;i++){var s=e[i+1];n[i]=parseInt(1==s.length?s+s:s,16)/255}return n}}var i,s={gray:["gray"],rgb:["red","green","blue"],hsb:["hue","saturation","brightness"],hsl:["hue","saturation","lightness"],gradient:["gradient","origin","destination","highlight"]},a={},h={},u=[[0,3,1],[2,0,1],[1,0,3],[1,2,0],[3,1,0],[0,1,2]],l={"rgb-hsb":function(t,e,n){var i=Math.max(t,e,n),s=Math.min(t,e,n),r=i-s,a=0===r?0:60*(i==t?(e-n)/r+(n>e?6:0):i==e?(n-t)/r+2:(t-e)/r+4);return[a,0===i?0:r/i,i]},"hsb-rgb":function(t,e,n){var t=t/60%6,i=Math.floor(t),s=t-i,i=u[i],r=[n,n*(1-e),n*(1-e*s),n*(1-e*(1-s))];return[r[i[0]],r[i[1]],r[i[2]]]},"rgb-hsl":function(t,e,n){var i=Math.max(t,e,n),s=Math.min(t,e,n),r=i-s,a=0===r,o=a?0:60*(i==t?(e-n)/r+(n>e?6:0):i==e?(n-t)/r+2:(t-e)/r+4),h=(i+s)/2,u=a?0:.5>h?r/(i+s):r/(2-i-s);return[o,u,h]},"hsl-rgb":function(t,e,n){if(t/=360,0===e)return[n,n,n];for(var i=[t+1/3,t,t-1/3],s=.5>n?n*(1+e):n+e-n*e,r=2*n-s,a=[],o=0;3>o;o++){var h=i[o];0>h&&(h+=1),h>1&&(h-=1),a[o]=1>6*h?r+6*(s-r)*h:1>2*h?s:2>3*h?r+6*(s-r)*(2/3-h):r}return a},"rgb-gray":function(t,e,n){return[.2989*t+.587*e+.114*n]},"gray-rgb":function(t){return[t,t,t]},"gray-hsb":function(t){return[0,0,t]},"gray-hsl":function(t){return[0,0,t]},"gradient-rgb":function(){return[]},"rgb-gradient":function(){return[]}};return t.each(s,function(e,n){a[n]=[],t.each(e,function(e,i){var s=t.capitalize(e),r=/^(hue|saturation)$/.test(e),h=a[n][i]="gradient"===e?function(t){var e=this._components[0];return t=N.read(Array.isArray(t)?t:arguments,0,0,!0),e!==t&&(e&&e._removeOwner(this),t&&t._addOwner(this)),t}:"hue"===e?function(t){return isNaN(t)?0:(t%360+360)%360}:"gradient"===n?function(){return o.read(arguments,0,0,"highlight"===e,!0)}:function(t){return isNaN(t)?0:Math.min(Math.max(t,0),1)};this["get"+s]=function(){return this._type===n||r&&/^hs[bl]$/.test(this._type)?this._components[i]:this._convert(n)[i]},this["set"+s]=function(t){this._type===n||r&&/^hs[bl]$/.test(this._type)||(this._components=this._convert(n),this._type=n),t=h.call(this,t),null!=t&&(this._components[i]=t,this._changed())}},this)},{_class:"Color",_readIndex:!0,initialize:function c(t){var i,r,o,h,u=Array.prototype.slice,l=arguments,d=0;Array.isArray(t)&&(l=t,t=l[0]);var _=null!=t&&typeof t;if("string"===_&&t in s&&(i=t,t=l[1],Array.isArray(t)?(r=t,o=l[2]):(this._read&&(d=1),l=u.call(l,1),_=typeof t)),!r){if(h="number"===_?l:"object"===_&&null!=t.length?t:null){i||(i=h.length>=3?"rgb":"gray");var f=s[i].length;o=h[f],this._read&&(d+=h===arguments?f+(null!=o?1:0):1),h.length>f&&(h=u.call(h,0,f))}else if("string"===_)r=t.match(/^#[0-9a-f]{3,6}$/i)?n(t):e(t),i="rgb";else if("object"===_)if(t.constructor===c){if(i=t._type,r=t._components.slice(),o=t._alpha,"gradient"===i)for(var g=1,v=r.length;v>g;g++){var m=r[g];m&&(r[g]=m.clone())}}else if(t.constructor===N)i="gradient",h=l;else{i="hue"in t?"lightness"in t?"hsl":"hsb":"gradient"in t||"stops"in t||"radial"in t?"gradient":"gray"in t?"gray":"rgb";var p=s[i];w=a[i],this._components=r=[];for(var g=0,v=p.length;v>g;g++){var y=t[p[g]];null==y&&0===g&&"gradient"===i&&"stops"in t&&(y={stops:t.stops,radial:t.radial}),y=w[g].call(this,y),null!=y&&(r[g]=y)}o=t.alpha}this._read&&i&&(d=1)}if(this._type=i||"rgb","gradient"===i&&(this._id=c._id=(c._id||0)+1),!r){this._components=r=[];for(var w=a[this._type],g=0,v=w.length;v>g;g++){var y=w[g].call(this,h&&h[g]);null!=y&&(r[g]=y)}}this._components=r,this._alpha=o,this._read&&(this._read=d)},_serialize:function(e,n){var i=this.getComponents();return t.serialize(/^(gray|rgb)$/.test(this._type)?i:[this._type].concat(i),e,!0,n)},_changed:function(){this._canvasStyle=null,this._owner&&this._owner._changed(17)},clone:function(){return new B(this._type,this._components.slice(),this._alpha)},_convert:function(t){var e;return this._type===t?this._components.slice():(e=l[this._type+"-"+t])?e.apply(this,this._components):l["rgb-"+t].apply(this,l[this._type+"-rgb"].apply(this,this._components))},convert:function(t){return new B(t,this._convert(t),this._alpha)},getType:function(){return this._type},setType:function(t){this._components=this._convert(t),this._type=t},getComponents:function(){var t=this._components.slice();return null!=this._alpha&&t.push(this._alpha),t},getAlpha:function(){return null!=this._alpha?this._alpha:1},setAlpha:function(t){this._alpha=null==t?null:Math.min(Math.max(t,0),1),this._changed()},hasAlpha:function(){return null!=this._alpha},equals:function(e){return t.isPlainValue(e)&&(e=B.read(arguments)),e===this||e&&this._type===e._type&&this._alpha===e._alpha&&t.equals(this._components,e._components)||!1},toString:function(){for(var t=s[this._type],e=[],n="gradient"===this._type,i=r.instance,a=0,o=t.length;o>a;a++){var h=this._components[a];null!=h&&e.push(t[a]+": "+(n?h:i.number(h)))}return null!=this._alpha&&e.push("alpha: "+i.number(this._alpha)),"{ "+e.join(", ")+" }"},toCSS:function(t){var e=this._convert("rgb"),n=t||null==this._alpha?1:this._alpha;return e=[Math.round(255*e[0]),Math.round(255*e[1]),Math.round(255*e[2])],1>n&&e.push(n),(4==e.length?"rgba(":"rgb(")+e.join(",")+")"},toCanvasStyle:function(t){if(this._canvasStyle)return this._canvasStyle;if("gradient"!==this._type)return this._canvasStyle=this.toCSS();var e,n=this._components,i=n[0],s=i._stops,r=n[1],a=n[2];if(i._radial){var o=a.getDistance(r),h=n[3];if(h){var u=h.subtract(r);u.getLength()>o&&(h=r.add(u.normalize(o-.1)))}var l=h||r;e=t.createRadialGradient(l.x,l.y,0,r.x,r.y,o)}else e=t.createLinearGradient(r.x,r.y,a.x,a.y);for(var c=0,d=s.length;d>c;c++){var _=s[c];e.addColorStop(_._rampPoint,_._color.toCanvasStyle())}return this._canvasStyle=e},transform:function(t){if("gradient"===this._type){for(var e=this._components,n=1,i=e.length;i>n;n++){var s=e[n];t._transformPoint(s,s,!0)}this._changed()}},statics:{_types:s,random:function(){var t=Math.random;return new B(t(),t(),t())}}})});t.each(B._types,function(e,n){var i=this[t.capitalize(n)+"Color"]=function(t){var e=null!=t&&typeof t,i="object"===e&&null!=t.length?t:"string"===e?null:arguments;return i?new B(n,i):new B(t)};if(3==n.length){var s=n.toUpperCase();B[s]=this[s+"Color"]=i}},this);var N=t.extend({_class:"Gradient",initialize:function xe(t,e){this._id=xe._id=(xe._id||0)+1,t&&this._set(t)&&(t=e=null),this._stops||this.setStops(t||["white","black"]),null==this._radial&&this.setRadial("string"==typeof e&&"radial"===e||e||!1)},_serialize:function(e,n){return n.add(this,function(){return t.serialize([this._stops,this._radial],e,!0,n)})},_changed:function(){for(var t=0,e=this._owners&&this._owners.length;e>t;t++)this._owners[t]._changed()},_addOwner:function(t){this._owners||(this._owners=[]),this._owners.push(t)},_removeOwner:function(t){var e=this._owners?this._owners.indexOf(t):-1;-1!=e&&(this._owners.splice(e,1),0===this._owners.length&&delete this._owners)},clone:function(){for(var t=[],e=0,n=this._stops.length;n>e;e++)t[e]=this._stops[e].clone();return new this.constructor(t)},getStops:function(){return this._stops},setStops:function(t){if(this.stops)for(var e=0,n=this._stops.length;n>e;e++)delete this._stops[e]._owner;if(t.length<2)throw Error("Gradient stop list needs to contain at least two stops.");this._stops=F.readAll(t,0,!1,!0);for(var e=0,n=this._stops.length;n>e;e++){var i=this._stops[e];i._owner=this,i._defaultRamp&&i.setRampPoint(e/(n-1))}this._changed()},getRadial:function(){return this._radial},setRadial:function(t){this._radial=t,this._changed()},equals:function(t){if(t&&t.constructor==this.constructor&&this._stops.length==t._stops.length){for(var e=0,n=this._stops.length;n>e;e++)if(!this._stops[e].equals(t._stops[e]))return!1;return!0}return!1}}),F=t.extend({_class:"GradientStop",initialize:function(t,e){if(t){var n,i;void 0===e&&Array.isArray(t)?(n=t[0],i=t[1]):t.color?(n=t.color,i=t.rampPoint):(n=t,i=e),this.setColor(n),this.setRampPoint(i)}},clone:function(){return new F(this._color.clone(),this._rampPoint)},_serialize:function(e,n){return t.serialize([this._color,this._rampPoint],e,!0,n)},_changed:function(){this._owner&&this._owner._changed(17)},getRampPoint:function(){return this._rampPoint},setRampPoint:function(t){this._defaultRamp=null==t,this._rampPoint=t||0,this._changed()},getColor:function(){return this._color},setColor:function(t){this._color=B.read(arguments),this._color===t&&(this._color=t.clone()),this._color._owner=this,this._changed()},equals:function(t){return t===this||t instanceof F&&this._color.equals(t._color)&&this._rampPoint==t._rampPoint||!1}}),E=t.extend(new function(){var e={fillColor:void 0,strokeColor:void 0,selectedColor:void 0,strokeWidth:1,strokeCap:"butt",strokeJoin:"miter",miterLimit:10,dashOffset:0,dashArray:[],font:"sans-serif",fontSize:12,leading:null,justification:"left"},n={strokeWidth:25,strokeCap:25,strokeJoin:25,miterLimit:25,font:5,fontSize:5,leading:5,justification:5},i={},s={_defaults:e,_textDefaults:t.merge(e,{fillColor:new B})};return t.each(e,function(e,r){var a=/Color$/.test(r),o=t.capitalize(r),h=n[r],u="set"+o,l="get"+o;s[u]=function(t){var e=this._item&&this._item._children;if(e&&e.length>0&&"compound-path"!==this._item._type)for(var n=0,i=e.length;i>n;n++)e[n]._style[u](t);else{var s=this._values[r];s!=t&&(a&&(s&&delete s._owner,t&&t.constructor===B&&(t._owner=this._item)),this._values[r]=t,this._item&&this._item._changed(h||17))}},s[l]=function(){var e,n=this._item&&this._item._children;if(!n||0===n.length||arguments[0]||"compound-path"===this._item._type){var e=this._values[r];return void 0===e?(e=this._defaults[r],e&&e.clone&&(e=e.clone()),this._values[r]=e):!a||e&&e.constructor===B||(this._values[r]=e=B.read([e],0,0,!0,!0),e&&(e._owner=this._item)),e}for(var i=0,s=n.length;s>i;i++){var o=n[i]._style[l]();if(0===i)e=o;else if(!t.equals(e,o))return void 0}return e},i[l]=function(){return this._style[l]()},i[u]=function(t){this._style[u](t)}}),p.inject(i),s},{_class:"Style",initialize:function(t,e){this._values={},this._item=e,e instanceof T&&(this._defaults=this._textDefaults),t&&this.set(t)},set:function(t){var e=t instanceof E,n=e?t._values:t;if(n)for(var i in n)if(i in this._defaults){var s=n[i];this[i]=s&&e&&s.clone?s.clone():s}},getLeading:function be(){var t=be.base.call(this);return null!=t?t:1.2*this.getFontSize()},getFontStyle:function(){var t=this.getFontSize();return(/[a-z]/i.test(t)?t+" ":t+"px ")+this.getFont()}}),R=new function(){function e(n,i){for(var s=[],r=0,a=n&&n.length;a>r;){var o=n[r++];if("string"==typeof o)o=document.createElement(o);else if(!o||!o.nodeType)continue;t.isPlainObject(n[r])&&R.set(o,n[r++]),Array.isArray(n[r])&&e(n[r++],o),i&&i.appendChild(o),s.push(o)}return s}var n=/^(checked|value|selected|disabled)$/i,i={text:"textContent",html:"innerHTML"},s={lineHeight:1,zoom:1,zIndex:1,opacity:1};return{create:function(t,n){var i=Array.isArray(t),s=e(i?t:arguments,i?n:null);return 1==s.length?s[0]:s},find:function(t,e){return(e||document).querySelector(t)},findAll:function(t,e){return(e||document).querySelectorAll(t)},get:function(t,e){return t?n.test(e)?"value"===e||"string"!=typeof t[e]?t[e]:!0:e in i?t[i[e]]:t.getAttribute(e):null},set:function(t,e,s){if("string"!=typeof e)for(var r in e)e.hasOwnProperty(r)&&this.set(t,r,e[r]);else{if(!t||void 0===s)return t;n.test(e)?t[e]=s:e in i?t[i[e]]=s:"style"===e?this.setStyle(t,s):"events"===e?q.add(t,s):t.setAttribute(e,s)}return t},getStyles:function(t){var e=t&&t.ownerDocument.defaultView;return e&&e.getComputedStyle(t,"")},getStyle:function(t,e){return t&&t.style[e]||this.getStyles(t)[e]||null},setStyle:function(t,e,n){if("string"!=typeof e)for(var i in e)e.hasOwnProperty(i)&&this.setStyle(t,i,e[i]);else!/^-?[\d\.]+$/.test(n)||e in s||(n+="px"),t.style[e]=n;return t},hasClass:function(t,e){return RegExp("\\s*"+e+"\\s*").test(t.className)},addClass:function(t,e){t.className=(t.className+" "+e).trim()},removeClass:function(t,e){t.className=t.className.replace(RegExp("\\s*"+e+"\\s*")," ").trim()},remove:function(t){t.parentNode&&t.parentNode.removeChild(t)},removeChildren:function(t){for(;t.firstChild;)t.removeChild(t.firstChild)},getBounds:function(t,e){var n,i=t.ownerDocument,s=i.body,r=i.documentElement;try{n=t.getBoundingClientRect()}catch(a){n={left:0,top:0,width:0,height:0}}var o=n.left-(r.clientLeft||s.clientLeft||0),h=n.top-(r.clientTop||s.clientTop||0);if(!e){var u=i.defaultView;o+=u.pageXOffset||r.scrollLeft||s.scrollLeft,h+=u.pageYOffset||r.scrollTop||s.scrollTop}return new d(o,h,n.width,n.height)},getViewportBounds:function(t){var e=t.ownerDocument,n=e.defaultView,i=e.documentElement;return new d(0,0,n.innerWidth||i.clientWidth,n.innerHeight||i.clientHeight)},getOffset:function(t,e){return this.getBounds(t,e).getPoint()},getSize:function(t){return this.getBounds(t,!0).getSize()},isInvisible:function(t){return this.getSize(t).equals(new u(0,0))},isInView:function(t){return!this.isInvisible(t)&&this.getViewportBounds(t).intersects(this.getBounds(t,!0))}}},q={add:function(t,e){for(var n in e){var i=e[n];t.addEventListener?t.addEventListener(n,i,!1):t.attachEvent&&t.attachEvent("on"+n,i.bound=function(){i.call(t,window.event)})}},remove:function(t,e){for(var n in e){var i=e[n];t.removeEventListener?t.removeEventListener(n,i,!1):t.detachEvent&&t.detachEvent("on"+n,i.bound)}},getPoint:function(t){var e=t.targetTouches?t.targetTouches.length?t.targetTouches[0]:t.changedTouches[0]:t;return new o(e.pageX||e.clientX+document.documentElement.scrollLeft,e.pageY||e.clientY+document.documentElement.scrollTop)},getTarget:function(t){return t.target||t.srcElement},getOffset:function(t,e){return q.getPoint(t).subtract(R.getOffset(e||q.getTarget(t)))},preventDefault:function(t){t.preventDefault?t.preventDefault():t.returnValue=!1},stopPropagation:function(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0},stop:function(t){q.stopPropagation(t),q.preventDefault(t)}};q.requestAnimationFrame=new function(){var t="equestAnimationFrame",e=window["r"+t]||window["webkitR"+t]||window["mozR"+t]||window["oR"+t]||window["msR"+t];e&&e(function(t){null==t&&(e=null)});var i,s=[],r=!0;return q.add(window,{focus:function(){r=!0},blur:function(){r=!1}}),function(t,a){return e?e(t,a):(s.push([t,a]),i||(i=setInterval(function(){for(var t=s.length-1;t>=0;t--){var e=s[t],i=e[0],a=e[1];(!a||("true"==n.getAttribute(a,"keepalive")||r)&&R.isInView(a))&&(s.splice(t,1),i(Date.now()))}},1e3/60)),void 0)}};var V=t.extend(e,{_class:"View",initialize:function Ce(t){this._scope=paper,this._project=paper.project,this._element=t;var e;if(this._id=t.getAttribute("id"),null==this._id&&t.setAttribute("id",this._id="view-"+Ce._id++),q.add(t,this._viewHandlers),n.hasAttribute(t,"resize")){var i=R.getOffset(t,!0),s=this;e=R.getViewportBounds(t).getSize().subtract(i),this._windowHandlers={resize:function(){R.isInvisible(t)||(i=R.getOffset(t,!0)),s.setViewSize(R.getViewportBounds(t).getSize().subtract(i))}},q.add(window,this._windowHandlers)}else e=new u(parseInt(t.getAttribute("width"),10),parseInt(t.getAttribute("height"),10)),e.isNaN()&&(e=R.getSize(t));if(t.width=e.width,t.height=e.height,n.hasAttribute(t,"stats")){this._stats=new Stats;var r=this._stats.domElement,a=r.style,i=R.getOffset(t);a.position="absolute",a.left=i.x+"px",a.top=i.y+"px",document.body.appendChild(r)}Ce._views.push(this),Ce._viewsById[this._id]=this,this._viewSize=new c(e.width,e.height,this,"setViewSize"),this._matrix=new f,this._zoom=1,Ce._focused||(Ce._focused=this),this._frameItems={},this._frameItemCount=0},remove:function(){return this._project?(V._focused==this&&(V._focused=null),V._views.splice(V._views.indexOf(this),1),delete V._viewsById[this._id],this._project.view==this&&(this._project.view=null),q.remove(this._element,this._viewHandlers),q.remove(window,this._windowHandlers),this._element=this._project=null,this.detach("frame"),this._frameItems={},!0):!1 +},_events:{onFrame:{install:function(){this._requested||(this._animate=!0,this._handleFrame(!0))},uninstall:function(){this._animate=!1}},onResize:{}},_animate:!1,_time:0,_count:0,_handleFrame:function(e){if(this._requested=!1,this._animate){if(paper=this._scope,e){this._requested=!0;var n=this;q.requestAnimationFrame(function(){n._handleFrame(!0)},this._element)}var i=Date.now()/1e3,s=this._before?i-this._before:0;this._before=i,this._handlingFrame=!0,this.fire("frame",t.merge({delta:s,time:this._time+=s,count:this._count++})),this._stats&&this._stats.update(),this._handlingFrame=!1,this.draw(!0)}},_animateItem:function(t,e){var n=this._frameItems;e?(n[t._id]={item:t,time:0,count:0},1==++this._frameItemCount&&this.attach("frame",this._handleFrameItems)):(delete n[t._id],0==--this._frameItemCount&&this.detach("frame",this._handleFrameItems))},_handleFrameItems:function(e){for(var n in this._frameItems){var i=this._frameItems[n];i.item.fire("frame",t.merge(e,{time:i.time+=e.delta,count:i.count++}))}},_redraw:function(){this._project._needsRedraw=!0,this._handlingFrame||(this._animate?this._handleFrame():this.draw())},_transform:function(t){this._matrix.concatenate(t),this._bounds=null,this._inverse=null,this._redraw()},getElement:function(){return this._element},getViewSize:function(){return this._viewSize},setViewSize:function(t){t=u.read(arguments);var e=t.subtract(this._viewSize);e.isZero()||(this._element.width=t.width,this._element.height=t.height,this._viewSize.set(t.width,t.height,!0),this._bounds=null,this.fire("resize",{size:t,delta:e}),this._redraw())},getBounds:function(){return this._bounds||(this._bounds=this._getInverse()._transformBounds(new d(new o,this._viewSize))),this._bounds},getSize:function(){return this.getBounds().getSize(arguments[0])},getCenter:function(){return this.getBounds().getCenter(arguments[0])},setCenter:function(t){t=o.read(arguments),this.scrollBy(t.subtract(this.getCenter()))},getZoom:function(){return this._zoom},setZoom:function(t){this._transform((new f).scale(t/this._zoom,this.getCenter())),this._zoom=t},isVisible:function(){return R.isInView(this._element)},scrollBy:function(){this._transform((new f).translate(o.read(arguments).negate()))},projectToView:function(){return this._matrix._transformPoint(o.read(arguments))},viewToProject:function(){return this._getInverse()._transformPoint(o.read(arguments))},_getInverse:function(){return this._inverse||(this._inverse=this._matrix.inverted()),this._inverse}},{statics:{_views:[],_viewsById:{},_id:0,create:function(t){return"string"==typeof t&&(t=document.getElementById(t)),new H(t)}}},new function(){function t(t){var e=q.getTarget(t);return e.getAttribute&&V._viewsById[e.getAttribute("id")]}function e(t,e){return t.viewToProject(q.getOffset(e,t._element))}function n(){if(!V._focused||!V._focused.isVisible())for(var t=0,e=V._views.length;e>t;t++){var n=V._views[t];if(n&&n.isVisible()){V._focused=u=n;break}}}function i(n){var i=V._focused=t(n),s=e(i,n);l=!0,i._onMouseDown&&i._onMouseDown(n,s),(o=i._scope._tool)&&o._onHandleEvent("mousedown",s,n),i.draw(!0)}function s(i){var s;if(l||(s=t(i),s?(h=V._focused,V._focused=u=s):u&&u==V._focused&&(V._focused=h,n())),s=s||V._focused){var r=i&&e(s,i);s._onMouseMove&&s._onMouseMove(i,r),(o=s._scope._tool)&&o._onHandleEvent(l&&o.responds("mousedrag")?"mousedrag":"mousemove",r,i)&&q.stop(i),s.draw(!0)}}function r(t){var n=V._focused;if(n&&l){var i=e(n,t);curPoint=null,l=!1,n._onMouseUp&&n._onMouseUp(t,i),o&&o._onHandleEvent("mouseup",i,t)&&q.stop(t),n.draw(!0)}}function a(t){l&&q.stop(t)}var o,h,u,l=!1;return q.add(document,{mousemove:s,mouseup:r,touchmove:s,touchend:r,selectstart:a,scroll:n}),q.add(window,{load:n}),{_viewHandlers:{mousedown:i,touchstart:i,selectstart:a},statics:{updateFocus:n}}}),H=V.extend({_class:"CanvasView",initialize:function(t){if(!(t instanceof HTMLCanvasElement)){var e=u.read(arguments,1);e.isZero()&&(e=new u(1024,768)),t=$.getCanvas(e)}this._context=t.getContext("2d"),this._eventCounters={},V.call(this,t)},draw:function(t){if(t&&!this._project._needsRedraw)return!1;var e=this._context,n=this._viewSize;return e.clearRect(0,0,n._width+1,n._height+1),this._project.draw(e,this._matrix),this._project._needsRedraw=!1,!0}},new function(){function t(t,e,n,i,s,r){for(var a,o=i;o;){if(o.responds(t)&&(a||(a=new X(t,e,n,i,s?n.subtract(s):null)),o.fire(t,a)&&(!r||a._stopped)))return!1;o=o.getParent()}return!0}function e(e,n,i,s,r){if(e._eventCounters[n]){var a=e._project,u=a.hitTest(s,{tolerance:a.options.hitTolerance||0,fill:!0,stroke:!0}),l=u&&u.item;if(l)return"mousemove"===n&&l!=o&&(r=s),"mousemove"===n&&h||t(n,i,s,l,r),l}}var n,i,s,r,a,o,h,u,l;return{_onMouseDown:function(t,o){var c=e(this,"mousedown",t,o);u=a==c&&Date.now()-l<300,r=a=c,n=i=s=o,h=r&&r.responds("mousedrag")},_onMouseUp:function(a,o){var c=e(this,"mouseup",a,o);h&&(i&&!i.equals(o)&&t("mousedrag",a,o,r,i),c!=r&&(s=o,t("mousemove",a,o,c,s))),c===r&&(l=Date.now(),(!u||t("doubleclick",a,n,c))&&t("click",a,n,c),u=!1),r=null,h=!1},_onMouseMove:function(n,a){r&&t("mousedrag",n,a,r,i);var h=e(this,"mousemove",n,a,s);i=s=a,h!==o&&(t("mouseleave",n,a,o),o=h,t("mouseenter",n,a,h))}}}),Z=t.extend({_class:"Event",initialize:function(t){this.event=t},preventDefault:function(){this._prevented=!0,q.preventDefault(this.event)},stopPropagation:function(){this._stopped=!0,q.stopPropagation(this.event)},stop:function(){this.stopPropagation(),this.preventDefault()},getModifiers:function(){return J.modifiers}}),G=Z.extend({_class:"KeyEvent",initialize:function(t,e,n,i){Z.call(this,i),this.type=t?"keydown":"keyup",this.key=e,this.character=n},toString:function(){return"{ type: '"+this.type+"', key: '"+this.key+"', character: '"+this.character+"', modifiers: "+this.getModifiers()+" }"}}),J=new function(){function e(t,e,n,s){var r=String.fromCharCode(n),o=i[e]||r.toLowerCase(),h=t?"keydown":"keyup",u=V._focused,l=u&&u.isVisible()&&u._scope,c=l&&l._tool;a[o]=t,c&&c.responds(h)&&(c.fire(h,new G(t,o,r,s)),u&&u.draw(!0))}var n,i={8:"backspace",9:"tab",13:"enter",16:"shift",17:"control",18:"option",19:"pause",20:"caps-lock",27:"escape",32:"space",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",46:"delete",91:"command",93:"command",224:"command"},s=t.merge({shift:!1,control:!1,option:!1,command:!1,capsLock:!1,space:!1}),r={},a={};return q.add(document,{keydown:function(a){var o,h=a.which||a.keyCode,u=i[h];u?((o=t.camelize(u))in s&&(s[o]=!0),r[h]=0,e(!0,h,null,a)):n=h},keypress:function(t){if(null!=n){var i=t.which||t.keyCode;r[n]=i,e(!0,n,i,t),n=null}},keyup:function(n){var a,o=n.which||n.keyCode,h=i[o];h&&(a=t.camelize(h))in s&&(s[a]=!1),null!=r[o]&&(e(!1,o,r[o],n),delete r[o])}}),{modifiers:s,isDown:function(t){return!!a[t]}}},X=Z.extend({_class:"MouseEvent",initialize:function(t,e,n,i,s){Z.call(this,e),this.type=t,this.point=n,this.target=i,this.delta=s},toString:function(){return"{ type: '"+this.type+"', point: "+this.point+", target: "+this.target+(this.delta?", delta: "+this.delta:"")+", modifiers: "+this.getModifiers()+" }"}});t.extend(e,{_class:"Palette",_events:["onChange"],initialize:function(e,n,i){var s=R.find(".palettejs-panel")||R.find("body").appendChild(R.create("div",{"class":"palettejs-panel"}));this._element=s.appendChild(R.create("table",{"class":"palettejs-pane"})),this._title=e,i||(i={});for(var r in this._components=n){var a=n[r];a instanceof W||(null==a.value&&(a.value=i[r]),a.name=r,a=n[r]=new W(a)),this._element.appendChild(a._element),a._palette=this,void 0===i[r]&&(i[r]=a.value)}this._values=t.each(i,function(e,s){var r=n[s];r&&t.define(i,s,{enumerable:!0,configurable:!0,get:function(){return r._value},set:function(t){r.setValue(t)}})}),window.paper&&paper.palettes.push(this)},reset:function(){for(var t in this._components)this._components[t].reset()},remove:function(){R.remove(this._element)}});var W=t.extend(e,{_class:"Component",_events:["onChange","onClick"],_types:{"boolean":{type:"checkbox",value:"checked"},string:{type:"text"},number:{type:"number",number:!0},button:{type:"button"},text:{tag:"div",value:"text"},slider:{type:"range",number:!0},list:{tag:"select",options:function(){R.removeChildren(this._inputItem),R.create(t.each(this._options,function(t){this.push("option",{value:t,text:t})},[]),this._inputItem)}}},initialize:function(e){this._type=e.type in this._types?e.type:"options"in e?"list":"onClick"in e?"button":typeof e.value,this._info=this._types[this._type]||{type:this._type};var n=this,i=!1;this._inputItem=R.create(this._info.tag||"input",{type:this._info.type,events:{change:function(){n.setValue(R.get(this,n._info.value||"value")),i&&(n._palette.fire("change",n,n.name,n._value),n.fire("change",n._value))},click:function(){n.fire("click")}}}),this._element=R.create("tr",[this._labelItem=R.create("td"),"td",[this._inputItem]]),t.each(e,function(t,e){this[e]=t},this),this._defaultValue=this._value,i=!0},getType:function(){return this._type},getLabel:function(){return this._label},setLabel:function(t){this._label=t,R.set(this._labelItem,"text",t+":")},getOptions:function(){return this._options},setOptions:function(t){this._options=t,this._info.options&&this._info.options.call(this)},getValue:function(){return this._value},setValue:function(t){var e=this._info.value||"value";R.set(this._inputItem,e,t),t=R.get(this._inputItem,e),this._value=this._info.number?parseFloat(t,10):t},getRange:function(){return[parseFloat(R.get(this._inputItem,"min")),parseFloat(R.get(this._inputItem,"max"))]},setRange:function(t,e){var n=Array.isArray(t)?t:[t,e];R.set(this._inputItem,{min:n[0],max:n[1]})},getMin:function(){return this.getRange()[0]},setMin:function(t){this.setRange(t,this.getMax())},getMax:function(){return this.getRange()[1]},setMax:function(t){this.setRange(this.getMin(),t)},getStep:function(){return parseFloat(R.get(this._inputItem,"step"))},setStep:function(t){R.set(this._inputItem,"step",t)},reset:function(){this.setValue(this._defaultValue)}}),Y=Z.extend({_class:"ToolEvent",_item:null,initialize:function(t,e,n){this.tool=t,this.type=e,this.event=n},_choosePoint:function(t,e){return t?t:e?e.clone():null},getPoint:function(){return this._choosePoint(this._point,this.tool._point)},setPoint:function(t){this._point=t},getLastPoint:function(){return this._choosePoint(this._lastPoint,this.tool._lastPoint)},setLastPoint:function(t){this._lastPoint=t},getDownPoint:function(){return this._choosePoint(this._downPoint,this.tool._downPoint)},setDownPoint:function(t){this._downPoint=t},getMiddlePoint:function(){return!this._middlePoint&&this.tool._lastPoint?this.tool._point.add(this.tool._lastPoint).divide(2):this.middlePoint},setMiddlePoint:function(t){this._middlePoint=t},getDelta:function(){return!this._delta&&this.tool._lastPoint?this.tool._point.subtract(this.tool._lastPoint):this._delta},setDelta:function(t){this._delta=t},getCount:function(){return/^mouse(down|up)$/.test(this.type)?this.tool._downCount:this.tool._count},setCount:function(t){this.tool[/^mouse(down|up)$/.test(this.type)?"downCount":"count"]=t},getItem:function(){if(!this._item){var t=this.tool._scope.project.hitTest(this.getPoint());if(t){for(var e=t.item,n=e._parent;/^(group|compound-path)$/.test(n._type);)e=n,n=n._parent;this._item=e}}return this._item},setItem:function(t){this._item=t},toString:function(){return"{ type: "+this.type+", point: "+this.getPoint()+", count: "+this.getCount()+", modifiers: "+this.getModifiers()+" }"}}),U=s.extend({_class:"Tool",_list:"tools",_reference:"_tool",_events:["onActivate","onDeactivate","onEditOptions","onMouseDown","onMouseUp","onMouseDrag","onMouseMove","onKeyDown","onKeyUp"],initialize:function(t){s.call(this),this._firstMove=!0,this._count=0,this._downCount=0,this._set(t)},getMinDistance:function(){return this._minDistance},setMinDistance:function(t){this._minDistance=t,null!=this._minDistance&&null!=this._maxDistance&&this._minDistance>this._maxDistance&&(this._maxDistance=this._minDistance)},getMaxDistance:function(){return this._maxDistance},setMaxDistance:function(t){this._maxDistance=t,null!=this._minDistance&&null!=this._maxDistance&&this._maxDistanceu)return!1;var l=null!=i?i:0;if(0!=l)if(u>l)e=this._point.add(h.normalize(l));else if(a)return!1}if(r&&e.equals(this._point))return!1}switch(this._lastPoint=s&&"mousemove"==t?e:this._point,this._point=e,t){case"mousedown":this._lastPoint=this._downPoint,this._downPoint=this._point,this._downCount++;break;case"mouseup":this._lastPoint=this._downPoint}return this._count=s?0:this._count+1,!0},_fireEvent:function(t,e){var n=paper.project._removeSets;if(n){"mouseup"===t&&(n.mousedrag=null);var i=n[t];if(i){for(var s in i){var r=i[s];for(var a in n){var o=n[a];o&&o!=i&&delete o[r._id]}r.remove()}n[t]=null}}return this.responds(t)&&this.fire(t,new Y(this,t,e))},_onHandleEvent:function(t,e,n){paper=this._scope;var i=!1;switch(t){case"mousedown":this._updateEvent(t,e,null,null,!0,!1,!1),i=this._fireEvent(t,n);break;case"mousedrag":for(var s=!1,r=!1;this._updateEvent(t,e,this.minDistance,this.maxDistance,!1,s,r);)i=this._fireEvent(t,n)||i,s=!0,r=!0;break;case"mouseup":!e.equals(this._point)&&this._updateEvent("mousedrag",e,this.minDistance,this.maxDistance,!1,!1,!1)&&(i=this._fireEvent("mousedrag",n)),this._updateEvent(t,e,null,this.maxDistance,!1,!1,!1),i=this._fireEvent(t,n)||i,this._updateEvent(t,e,null,null,!0,!1,!1),this._firstMove=!0;break;case"mousemove":for(;this._updateEvent(t,e,this.minDistance,this.maxDistance,this._firstMove,!0,!1);)i=this._fireEvent(t,n)||i,this._firstMove=!1}return i}}),$={canvases:[],getCanvas:function(t,e){var n,i=void 0===e?t:new u(t,e),s=!0;n=this.canvases.length?this.canvases.pop():document.createElement("canvas");var r=n.getContext("2d");return r.save(),n.width===i.width&&n.height===i.height?s&&r.clearRect(0,0,i.width+1,i.height+1):(n.width=i.width,n.height=i.height),n},getContext:function(t,e){return this.getCanvas(t,e).getContext("2d")},release:function(t){var e=t.canvas?t.canvas:t;e.getContext("2d").restore(),this.canvases.push(e)}},K=new function(){function e(t,e,n){return.2989*t+.587*e+.114*n}function n(t,n,i,s){var r=s-e(t,n,i);f=t+r,g=n+r,v=i+r;var s=e(f,g,v),a=m(f,g,v),o=p(f,g,v);if(0>a){var h=s-a;f=s+(f-s)*s/h,g=s+(g-s)*s/h,v=s+(v-s)*s/h}if(o>255){var u=255-s,l=o-s;f=s+(f-s)*u/l,g=s+(g-s)*u/l,v=s+(v-s)*u/l}}function i(t,e,n){return p(t,e,n)-m(t,e,n)}function s(t,e,n,i){var s,r=[t,e,n],a=p(t,e,n),o=m(t,e,n);o=o===t?0:o===e?1:2,a=a===t?0:a===e?1:2,s=0===m(o,a)?1===p(o,a)?2:1:0,r[a]>r[o]?(r[s]=(r[s]-r[o])*i/(r[a]-r[o]),r[a]=i):r[s]=r[a]=0,r[o]=0,f=r[0],g=r[1],v=r[2]}function r(t){x.save();var e="darken"===t,n=!1;return x.fillStyle=e?"#300":"#a00",x.fillRect(0,0,1,1),x.globalCompositeOperation=t,x.globalCompositeOperation===t&&(x.fillStyle=e?"#a00":"#300",x.fillRect(0,0,1,1),n=x.getImageData(0,0,1,1).data[0]!==(e?170:51)),x.restore(),n}var a,o,h,u,l,c,d,_,f,g,v,m=Math.min,p=Math.max,y=Math.abs,w={multiply:function(){f=l*a/255,g=c*o/255,v=d*h/255},screen:function(){f=l+a-l*a/255,g=c+o-c*o/255,v=d+h-d*h/255},overlay:function(){f=128>l?2*l*a/255:255-2*(255-l)*(255-a)/255,g=128>c?2*c*o/255:255-2*(255-c)*(255-o)/255,v=128>d?2*d*h/255:255-2*(255-d)*(255-h)/255},"soft-light":function(){var t=a*l/255;f=t+l*(255-(255-l)*(255-a)/255-t)/255,t=o*c/255,g=t+c*(255-(255-c)*(255-o)/255-t)/255,t=h*d/255,v=t+d*(255-(255-d)*(255-h)/255-t)/255},"hard-light":function(){f=128>a?2*a*l/255:255-2*(255-a)*(255-l)/255,g=128>o?2*o*c/255:255-2*(255-o)*(255-c)/255,v=128>h?2*h*d/255:255-2*(255-h)*(255-d)/255},"color-dodge":function(){f=0===l?0:255===a?255:m(255,255*l/(255-a)),g=0===c?0:255===o?255:m(255,255*c/(255-o)),v=0===d?0:255===h?255:m(255,255*d/(255-h))},"color-burn":function(){f=255===l?255:0===a?0:p(0,255-255*(255-l)/a),g=255===c?255:0===o?0:p(0,255-255*(255-c)/o),v=255===d?255:0===h?0:p(0,255-255*(255-d)/h)},darken:function(){f=a>l?l:a,g=o>c?c:o,v=h>d?d:h},lighten:function(){f=l>a?l:a,g=c>o?c:o,v=d>h?d:h},difference:function(){f=l-a,0>f&&(f=-f),g=c-o,0>g&&(g=-g),v=d-h,0>v&&(v=-v)},exclusion:function(){f=l+a*(255-l-l)/255,g=c+o*(255-c-c)/255,v=d+h*(255-d-d)/255},hue:function(){s(a,o,h,i(l,c,d)),n(f,g,v,e(l,c,d))},saturation:function(){s(l,c,d,i(a,o,h)),n(f,g,v,e(l,c,d))},luminosity:function(){n(l,c,d,e(a,o,h))},color:function(){n(a,o,h,e(l,c,d))},add:function(){f=m(l+a,255),g=m(c+o,255),v=m(d+h,255)},subtract:function(){f=p(l-a,0),g=p(c-o,0),v=p(d-h,0)},average:function(){f=(l+a)/2,g=(c+o)/2,v=(d+h)/2},negation:function(){f=255-y(255-a-l),g=255-y(255-o-c),v=255-y(255-h-d)}},x=$.getContext(1,1);this.nativeModes=r("multiply")&&t.each(w,function(t,e){this[e]=r(e)},{}),$.release(x),this.process=function(t,e,n,i,s){var r=e.canvas,m="normal"===t;if(m||this.nativeModes[t])n.save(),n.setTransform(1,0,0,1,0,0),n.globalAlpha=i,m||(n.globalCompositeOperation=t),n.drawImage(r,s.x,s.y),n.restore();else{var p=w[t];if(!p)return;for(var y=n.getImageData(s.x,s.y,r.width,r.height),x=y.data,b=e.getImageData(0,0,r.width,r.height).data,C=0,S=x.length;S>C;C+=4){a=b[C],l=x[C],o=b[C+1],c=x[C+1],h=b[C+2],d=x[C+2],u=b[C+3],_=x[C+3],p();var P=u*i/255,M=1-P;x[C]=P*f+M*l,x[C+1]=P*g+M*c,x[C+2]=P*v+M*d,x[C+3]=u*i+M*_}n.putImageData(y,s.x,s.y)}}},Q=t.each({fillColor:["fill","color"],strokeColor:["stroke","color"],strokeWidth:["stroke-width","number"],strokeCap:["stroke-linecap","string"],strokeJoin:["stroke-linejoin","string"],miterLimit:["stroke-miterlimit","number"],dashArray:["stroke-dasharray","array"],dashOffset:["stroke-dashoffset","number"],font:["font-family","string"],fontSize:["font-size","number"],justification:["text-anchor","lookup",{left:"start",center:"middle",right:"end"}],opacity:["opacity","number"],blendMode:["mix-blend-mode","string"]},function(e,n){var i=t.capitalize(n),s=e[2];this[n]={type:e[1],property:n,attribute:e[0],toSVG:s,fromSVG:s&&t.each(s,function(t,e){this[t]=e},{}),get:"get"+i,set:"set"+i}},{}),te={href:"http://www.w3.org/1999/xlink",xlink:"http://www.w3.org/2000/xmlns"};return new function(){function e(t,e){for(var n in e){var i=e[n],s=te[n];"number"==typeof i&&(i=I.number(i)),s?t.setAttributeNS(s,n,i):t.setAttribute(n,i)}return t}function n(t,n){return e(document.createElementNS("http://www.w3.org/2000/svg",t),n)}function s(t,e,n){return t[e]._point.getDistance(t[n]._point)}function o(t,e){var n=t._matrix,i=n.getTranslation(),s={};if(e){n=n.shiftless();var r=n._inverseTransform(i);s.x=r.x,s.y=r.y,i=null}if(n.isIdentity())return s;var o=n.decompose();if(o&&!o.shearing){var h=[],u=o.rotation,l=o.scaling;i&&!i.isZero()&&h.push("translate("+I.point(i)+")"),a.isZero(l.x-1)&&a.isZero(l.y-1)||h.push("scale("+I.point(l)+")"),u&&h.push("rotate("+I.number(u)+")"),s.transform=h.join(" ")}else s.transform="matrix("+n.getValues().join(",")+")";return s}function h(t,e,n,i){var s="rect"===n?e[1]._point.add(e[2]._point).divide(2):"roundrect"===n?e[3]._point.add(e[4]._point).divide(2):"circle"===n||"ellipse"===n?e[1]._point:null,r=s&&s.subtract(i).getAngle()+90;return a.isZero(r||0)?0:r}function u(t,e){function n(t,n){var i=e[t],s=i.getNext(),r=e[n],a=r.getNext();return i._handleOut.isZero()&&s._handleIn.isZero()&&r._handleOut.isZero()&&a._handleIn.isZero()&&s._point.subtract(i._point).isColinear(a._point.subtract(r._point))}function i(t){var n=e[t],i=n.getNext(),s=n._handleOut,r=i._handleIn,o=a.KAPPA;if(s.isOrthogonal(r)){var h=n._point,u=i._point,l=new g(h,s,!0).intersect(new g(u,r,!0),!0);return l&&a.isZero(s.getLength()/l.subtract(h).getLength()-o)&&a.isZero(r.getLength()/l.subtract(u).getLength()-o)}}if(t.isPolygon())return 4===e.length&&t._closed&&n(0,2)&&n(1,3)?"rect":0===e.length?"empty":e.length>=3?t._closed?"polygon":"polyline":"line";if(t._closed){if(8===e.length&&i(0)&&i(2)&&i(4)&&i(6)&&n(1,5)&&n(3,7))return"roundrect";if(4===e.length&&i(0)&&i(1)&&i(2)&&i(3))return a.isZero(s(e,0,2)-s(e,1,3))?"circle":"ellipse"}return"path"}function c(t){for(var i=o(t),s=t._children,r=n("g",i),a=0,h=s.length;h>a;a++){var u=s[a],l=M(u);if(l)if(u.isClipMask()){var c=n("clipPath");c.appendChild(l),S(u,c,"clip"),e(r,{"clip-path":"url(#"+c.id+")"})}else r.appendChild(l)}return r}function d(t){var e=o(t,!0),i=t.getSize();return e.x-=i.width/2,e.y-=i.height/2,e.width=i.width,e.height=i.height,e.href=t.toDataURL(),n("image",e)}function _(t){var e,r=t._segments,a=t.getPosition(!0),o=u(t,r),c=h(t,r,o,a);switch(o){case"empty":return null;case"path":var d=t.getPathData();e=d&&{d:d};break;case"polyline":case"polygon":var _=[];for(i=0,l=r.length;l>i;i++)_.push(I.point(r[i]._point));e={points:_.join(" ")};break;case"rect":var g=s(r,0,3),v=s(r,0,1),m=r[1]._point.rotate(-c,a);e={x:m.x,y:m.y,width:g,height:v};break;case"roundrect":o="rect";var g=s(r,1,6),v=s(r,0,3),p=(g-s(r,0,7))/2,y=(v-s(r,1,2))/2,w=r[3]._point,x=r[4]._point,m=w.subtract(x.subtract(w).normalize(p)).rotate(-c,a);e={x:m.x,y:m.y,width:g,height:v,rx:p,ry:y};break;case"line":var b=r[0]._point,C=r[r.length-1]._point;e={x1:b.x,y1:b.y,x2:C.x,y2:C.y};break;case"circle":var S=s(r,0,2)/2;e={cx:a.x,cy:a.y,r:S};break;case"ellipse":var p=s(r,2,0)/2,y=s(r,3,1)/2;e={cx:a.x,cy:a.y,rx:p,ry:y}}return c&&(e.transform="rotate("+I.number(c)+","+I.point(a)+")",t._gradientMatrix=(new f).rotate(-c,a)),n(o,e)}function m(t){var e=o(t,!0),i=t.getPathData();return i&&(e.d=i),n("path",e)}function y(t){var e=o(t,!0),i=t.getSymbol(),s=C(i,"symbol");return definition=i.getDefinition(),bounds=definition.getBounds(),s||(s=n("symbol",{viewBox:I.rectangle(bounds)}),s.appendChild(M(definition)),S(i,s,"symbol")),e.href="#"+s.id,e.x+=bounds.x,e.y+=bounds.y,e.width=I.number(bounds.width),e.height=I.number(bounds.height),n("use",e)}function w(t,e){var i=C(t,"color");if(!i){var s,r=t.getGradient(),a=r._radial,o=e._gradientMatrix,h=t.getOrigin().transform(o),u=t.getDestination().transform(o);if(a){s={cx:h.x,cy:h.y,r:h.getDistance(u)};var l=t.getHighlight();l&&(l=l.transform(o),s.fx=l.x,s.fy=l.y)}else s={x1:h.x,y1:h.y,x2:u.x,y2:u.y};s.gradientUnits="userSpaceOnUse",i=n((a?"radial":"linear")+"Gradient",s);for(var c=r._stops,d=0,_=c.length;_>d;d++){var f=c[d],g=f._color,v=g.getAlpha();s={offset:f._rampPoint,"stop-color":g.toCSS(!0)},1>v&&(s["stop-opacity"]=v),i.appendChild(n("stop",s))}S(t,i,"color")}return"url(#"+i.id+")"}function x(t){var e=n("text",o(t,!0));return e.textContent=t._content,e}function b(n,i){var s={},r=n.getParent();return null!=n._name&&(s.id=n._name),t.each(Q,function(e){var i=e.get,a=e.type,o=n[i]();if(!r||!t.equals(r[i](),o)){if("color"===a&&null!=o){var h=o.getAlpha();1>h&&(s[e.attribute+"-opacity"]=h)}s[e.attribute]=null==o?"none":"number"===a?I.number(o):"color"===a?o.gradient?w(o,n):o.toCSS(!0):"array"===a?o.join(","):"lookup"===a?e.toSVG[o]:o}}),1===s.opacity&&delete s.opacity,null==n._visibility||n._visibility||(s.visibility="hidden"),delete n._gradientMatrix,e(i,s)}function C(t,e){return z||(z={ids:{},svgs:{}}),t&&z.svgs[e+"-"+t._id]}function S(t,e,n){z||C();var i=z.ids[n]=(z.ids[n]||0)+1;e.id=n+"-"+i,z.svgs[n+"-"+t._id]=e}function P(t){if(!z)return t;var e="svg"===t.nodeName.toLowerCase()&&t,i=null;for(var s in z.svgs)i||(e||(e=n("svg"),e.appendChild(t)),i=e.insertBefore(n("defs"),e.firstChild)),i.appendChild(z.svgs[s]);return z=null,e}function M(t){var e=k[t._type],n=e&&e(t,t._type);return n&&t._data&&n.setAttribute("data-paper-data",JSON.stringify(t._data)),n&&b(t,n)}var z,I=r.instance,k={group:c,layer:c,raster:d,path:_,"compound-path":m,"placed-symbol":y,"point-text":x};p.inject({exportSVG:function(){return P(M(this))}}),v.inject({exportSVG:function(){for(var t=this.layers,e=this.view.getSize(),i=n("svg",{x:0,y:0,width:e.width,height:e.height,version:"1.1",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"}),s=0,r=t.length;r>s;s++)i.appendChild(M(t[s]));return P(i)}})},new function(){function e(t,e,n,i){var s=te[e],r=s?t.getAttributeNS(s,e):t.getAttribute(e);return"null"===r&&(r=null),null==r?i?null:n?"":0:n?r:parseFloat(r)}function n(t,n,i,s){return n=e(t,n,!1,s),i=e(t,i,!1,s),s&&null==n&&null==i?null:new o(n||0,i||0)}function i(t,n,i,s){return n=e(t,n,!1,s),i=e(t,i,!1,s),s&&null==n&&null==i?null:new u(n||0,i||0)}function s(t,e,n){return"none"===t?null:"number"===e?parseFloat(t):"array"===e?t?t.split(/[\s,]+/g).map(parseFloat):[]:"color"===e?x(t)||t:"lookup"===e?n[t]:t}function r(t,e){var n=t.childNodes,i="clippath"===e,s=i?new O:new y,r=s._project,a=r._currentStyle,o=[];i||(s._transformContent=!1,s=w(s,t),r._currentStyle=s._style.clone());for(var h=0,u=n.length;u>h;h++){var l,c=n[h];1==c.nodeType&&(l=C(c))&&(i&&l instanceof O?(o.push.apply(o,l.removeChildren()),l.remove()):l instanceof m||o.push(l))}return s.addChildren(o),i&&(s=w(s.reduce(),t)),r._currentStyle=a,(i||"defs"===e)&&(s.remove(),s=null),s}function a(t,e){var n=new A,i=t.points;n.moveTo(i.getItem(0));for(var s=1,r=i.numberOfItems;r>s;s++)n.lineTo(i.getItem(s));return"polygon"===e&&n.closePath(),n}function h(t){var e=t.getAttribute("d"),n=e.match(/m/gi).length>1?new O:new A;return n.setPathData(e),n}function l(t,i){for(var s=t.childNodes,r=[],a=0,o=s.length;o>a;a++){var h=s[a];1==h.nodeType&&r.push(w(new F,h))}var u,l,c,d="radialgradient"===i,_=new N(r,d);return d?(u=n(t,"cx","cy"),l=u.add(e(t,"r"),0),c=n(t,"fx","fy",!0)):(u=n(t,"x1","y1"),l=n(t,"x2","y2")),w(new B(_,u,l,c),t),null}function c(t,e,n,i){for(var s=(i.getAttribute(n)||"").split(/\)\s*/g),r=new f,a=0,o=s.length;o>a;a++){var h=s[a];if(!h)break;for(var u=h.split("("),l=u[0],c=u[1].split(/[\s,]+/g),d=0,_=c.length;_>d;d++)c[d]=parseFloat(c[d]);switch(l){case"matrix":r.concatenate(new f(c[0],c[2],c[1],c[3],c[4],c[5]));break;case"rotate":r.rotate(c[0],c[1],c[2]);break;case"translate":r.translate(c[0],c[1]);break;case"scale":r.scale(c);break;case"skewX":case"skewY":var e=Math.tan(c[0]*Math.PI/180),g="skewX"==l;r.shear(g?e:0,g?0:e)}}t.transform(r)}function _(t,e,n){var i=t["fill-opacity"===n?"getFillColor":"getStrokeColor"]();i&&i.setAlpha(parseFloat(e))}function g(e,n,i){var s=e.attributes[n],r=s&&s.value;if(!r){var a=t.camelize(n);r=e.style[a],r||i.node[a]===i.parent[a]||(r=i.node[a])}return r?"none"===r?null:r:void 0}function w(e,n){var i={node:R.getStyles(n)||{},parent:R.getStyles(n.parentNode)||{}};return t.each(P,function(s,r){var a=g(n,r,i);void 0!==a&&(e=t.pick(s(e,a,r,n,i),e))}),e}function x(t){var e=t&&t.match(/\((?:#|)([^)']+)/);return e&&M[e[1]]}function C(t,e){"string"==typeof t&&(t=(new DOMParser).parseFromString(t,"image/svg+xml"));var n=t.nodeName.toLowerCase(),i=S[n],s=i&&i(t,n),r=t.getAttribute("data-paper-data");return!s||s instanceof y||(s=w(s,t)),s&&r&&(s._data=JSON.parse(r)),e&&(M={}),s}var S={g:r,svg:r,clippath:r,polygon:a,polyline:a,path:h,lineargradient:l,radialgradient:l,image:function(t){var s=new b(e(t,"href",!0));return s.attach("load",function(){var e=i(t,"width","height");this.setSize(e),this.translate(n(t,"x","y").add(e.divide(2)))}),s},symbol:function(t,e){return new m(r(t,e),!0)},defs:r,use:function(t){var i=(e(t,"href",!0)||"").substring(1),s=M[i],r=n(t,"x","y");return s?s instanceof m?s.place(r):s.clone().translate(r):null},circle:function(t){return new A.Circle(n(t,"cx","cy"),e(t,"r"))},ellipse:function(t){var e=n(t,"cx","cy"),s=i(t,"rx","ry");return new A.Ellipse(new d(e.subtract(s),e.add(s)))},rect:function(t){var e=n(t,"x","y"),s=i(t,"width","height"),r=i(t,"rx","ry");return new A.Rectangle(new d(e,s),r)},line:function(t){return new A.Line(n(t,"x1","y1"),n(t,"x2","y2"))},text:function(t){var e=new j(n(t,"x","y",!1).add(n(t,"dx","dy",!1)));return e.setContent(t.textContent.trim()||""),e}},P=t.merge(t.each(Q,function(t){this[t.attribute]=function(e,n){e[t.set](s(n,t.type,t.fromSVG))}},{}),{id:function(t,e){M[e]=t,t.setName&&t.setName(e)},"clip-path":function(t,e){var n=x(e);if(n){if(n=n.clone(),n.setClipMask(!0),!(t instanceof y))return new y(n,t);t.insertChild(0,n)}},gradientTransform:c,transform:c,"fill-opacity":_,"stroke-opacity":_,visibility:function(t,e){t.setVisible("visible"===e)},"stop-color":function(t,e){t.setColor&&t.setColor(e)},"stop-opacity":function(t,e){t._color&&t._color.setAlpha(parseFloat(e))},offset:function(t,e){var n=e.match(/(.*)%$/);t.setRampPoint(n?n[1]/100:parseFloat(e))},viewBox:function(t,e,n,r,a){var o=new d(s(e,"array")),h=i(r,"width","height",!0);if(t instanceof y){var u=h?o.getSize().divide(h):1,l=(new f).translate(o.getPoint()).scale(u);t.transform(l.inverted())}else if(t instanceof m){h&&o.setSize(h);var c="visible"!=g(r,"overflow",a),_=t._definition;c&&!o.contains(_.getBounds())&&(c=new A.Rectangle(o).transform(_._matrix),c.setClipMask(!0),_.addChild(c))}}}),M={};p.inject({importSVG:function(t){return this.addChild(C(t,!0))}}),v.inject({importSVG:function(t){return this.activate(),C(t,!0)}})},paper=new(n.inject(t.merge(t.exports,{enumerable:!0,Base:t,Numerical:a,DomElement:R,DomEvent:q}))),"function"==typeof define&&define.amd&&define(paper),paper}; \ No newline at end of file diff --git a/dist/paper-full.js b/dist/paper-full.js new file mode 100644 index 00000000..dac999ad --- /dev/null +++ b/dist/paper-full.js @@ -0,0 +1,11274 @@ +/*! + * Paper.js v0.9.5 - The Swiss Army Knife of Vector Graphics Scripting. + * http://paperjs.org/ + * + * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey + * http://lehni.org/ & http://jonathanpuckey.com/ + * + * Distributed under the MIT license. See LICENSE file for details. + * + * All rights reserved. + * + * Date: Wed Jun 26 19:42:04 2013 -0700 + * + *** + * + * straps.js - Class inheritance library with support for bean-style accessors + * + * Copyright (c) 2006 - 2013 Juerg Lehni + * http://lehni.org/ + * + * Distributed under the MIT license. + * + *** + * + * acorn.js + * http://marijnhaverbeke.nl/acorn/ + * + * Acorn is a tiny, fast JavaScript parser written in JavaScript, + * created by Marijn Haverbeke and released under an MIT license. + * + */ + +var paper = new function() { + +var Base = new function() { + var hidden = /^(statics|generics|preserve|enumerable|prototype|toString|valueOf)$/, + toString = Object.prototype.toString, + proto = Array.prototype, + slice = proto.slice, + + forEach = proto.forEach || function(iter, bind) { + for (var i = 0, l = this.length; i < l; i++) + iter.call(bind, this[i], i, this); + }, + + forIn = function(iter, bind) { + for (var i in this) + if (this.hasOwnProperty(i)) + iter.call(bind, this[i], i, this); + }, + + isArray = Array.isArray = Array.isArray || function(obj) { + return toString.call(obj) === '[object Array]'; + }, + + create = Object.create || function(proto) { + return { __proto__: proto }; + }, + + describe = Object.getOwnPropertyDescriptor || function(obj, name) { + var get = obj.__lookupGetter__ && obj.__lookupGetter__(name); + return get + ? { get: get, set: obj.__lookupSetter__(name), + enumerable: true, configurable: true } + : obj.hasOwnProperty(name) + ? { value: obj[name], enumerable: true, + configurable: true, writable: true } + : null; + }, + + _define = Object.defineProperty || function(obj, name, desc) { + if ((desc.get || desc.set) && obj.__defineGetter__) { + if (desc.get) + obj.__defineGetter__(name, desc.get); + if (desc.set) + obj.__defineSetter__(name, desc.set); + } else { + obj[name] = desc.value; + } + return obj; + }, + + define = function(obj, name, desc) { + delete obj[name]; + return _define(obj, name, desc); + }; + + function inject(dest, src, enumerable, base, preserve, generics) { + var beans; + + function field(name, val, dontCheck, generics) { + var val = val || (val = describe(src, name)) + && (val.get ? val : val.value); + if (typeof val === 'string' && val[0] === '#') + val = src[val.substring(1)] || val; + var isFunc = typeof val === 'function', + res = val, + prev = preserve || isFunc + ? (val && val.get ? name in dest : dest[name]) : null, + bean; + if ((dontCheck || val !== undefined && src.hasOwnProperty(name)) + && (!preserve || !prev)) { + if (isFunc && prev) + val.base = prev; + if (isFunc && beans && val.length === 0 + && (bean = name.match(/^(get|is)(([A-Z])(.*))$/))) + beans.push([ bean[3].toLowerCase() + bean[4], bean[2] ]); + if (!res || isFunc || !res.get) + res = { value: res, writable: true }; + if ((describe(dest, name) + || { configurable: true }).configurable) { + res.configurable = true; + res.enumerable = enumerable; + } + define(dest, name, res); + } + if (generics && isFunc && (!preserve || !generics[name])) { + generics[name] = function(bind) { + return bind && dest[name].apply(bind, + slice.call(arguments, 1)); + }; + } + } + if (src) { + beans = []; + for (var name in src) + if (src.hasOwnProperty(name) && !hidden.test(name)) + field(name, null, true, generics); + field('toString'); + field('valueOf'); + for (var i = 0, l = beans && beans.length; i < l; i++) + try { + var bean = beans[i], + part = bean[1]; + field(bean[0], { + get: dest['get' + part] || dest['is' + part], + set: dest['set' + part] + }, true); + } catch (e) {} + } + return dest; + } + + function each(obj, iter, bind, asArray) { + try { + if (obj) + (asArray || typeof asArray === 'undefined' && isArray(obj) + ? forEach : forIn).call(obj, iter, bind = bind || obj); + } catch (e) { + if (e !== Base.stop) + throw e; + } + return bind; + } + + function clone(obj) { + return each(obj, function(val, i) { + this[i] = val; + }, new obj.constructor()); + } + + return inject(function Base() {}, { + inject: function(src) { + if (src) { + var proto = this.prototype, + base = Object.getPrototypeOf(proto).constructor, + statics = src.statics === true ? src : src.statics; + if (statics != src) + inject(proto, src, src.enumerable, base && base.prototype, + src.preserve, src.generics && this); + inject(this, statics, true, base, src.preserve); + } + for (var i = 1, l = arguments.length; i < l; i++) + this.inject(arguments[i]); + return this; + }, + + extend: function() { + var base = this, + ctor; + for (var i = 0, l = arguments.length; i < l; i++) + if (ctor = arguments[i].initialize) + break; + ctor = ctor || function() { + base.apply(this, arguments); + }; + ctor.prototype = create(this.prototype); + define(ctor.prototype, 'constructor', + { value: ctor, writable: true, configurable: true }); + inject(ctor, this, true); + return arguments.length ? this.inject.apply(ctor, arguments) : ctor; + } + }, true).inject({ + inject: function() { + for (var i = 0, l = arguments.length; i < l; i++) + inject(this, arguments[i], arguments[i].enumerable); + return this; + }, + + extend: function() { + var res = create(this); + return res.inject.apply(res, arguments); + }, + + each: function(iter, bind) { + return each(this, iter, bind); + }, + + clone: function() { + return clone(this); + }, + + statics: { + each: each, + clone: clone, + define: define, + describe: describe, + + create: function(ctor) { + return create(ctor.prototype); + }, + + isPlainObject: function(obj) { + var ctor = obj != null && obj.constructor; + return ctor && (ctor === Object || ctor === Base + || ctor.name === 'Object'); + }, + + check: function(obj) { + return !!(obj || obj === 0); + }, + + pick: function() { + for (var i = 0, l = arguments.length; i < l; i++) + if (arguments[i] !== undefined) + return arguments[i]; + return null; + }, + + stop: {} + } + }); +}; + +Base.inject({ + generics: true, + + clone: function() { + return new this.constructor(this); + }, + + toString: function() { + return this._id != null + ? (this._class || 'Object') + (this._name + ? " '" + this._name + "'" + : ' @' + this._id) + : '{ ' + Base.each(this, function(value, key) { + if (!/^_/.test(key)) { + var type = typeof value; + this.push(key + ': ' + (type === 'number' + ? Formatter.instance.number(value) + : type === 'string' ? "'" + value + "'" : value)); + } + }, []).join(', ') + ' }'; + }, + + exportJSON: function(options) { + return Base.exportJSON(this, options); + }, + + toJSON: function() { + return Base.serialize(this); + }, + + _set: function(props) { + if (props && Base.isPlainObject(props)) { + for (var key in props) + if (props.hasOwnProperty(key) && key in this) + this[key] = props[key]; + return true; + } + }, + + statics: { + + exports: {}, + + extend: function extend() { + var res = extend.base.apply(this, arguments), + name = res.prototype._class; + if (name && !Base.exports[name]) + Base.exports[name] = res; + return res; + }, + + equals: function(obj1, obj2) { + function checkKeys(o1, o2) { + for (var i in o1) + if (o1.hasOwnProperty(i) && typeof o2[i] === 'undefined') + return false; + return true; + } + if (obj1 === obj2) + return true; + if (obj1 && obj1.equals) + return obj1.equals(obj2); + if (obj2 && obj2.equals) + return obj2.equals(obj1); + if (Array.isArray(obj1) && Array.isArray(obj2)) { + if (obj1.length !== obj2.length) + return false; + for (var i = 0, l = obj1.length; i < l; i++) { + if (!Base.equals(obj1[i], obj2[i])) + return false; + } + return true; + } + if (obj1 && typeof obj1 === 'object' + && obj2 && typeof obj2 === 'object') { + if (!checkKeys(obj1, obj2) || !checkKeys(obj2, obj1)) + return false; + for (var i in obj1) { + if (obj1.hasOwnProperty(i) && !Base.equals(obj1[i], obj2[i])) + return false; + } + return true; + } + return false; + }, + + read: function(list, start, length, readNull, clone) { + if (this === Base) { + var value = this.peek(list, start); + list._index++; + list._read = 1; + return value; + } + var proto = this.prototype, + readIndex = proto._readIndex, + index = start || readIndex && list._index || 0; + if (!length) + length = list.length - index; + var obj = list[index]; + if (obj instanceof this || readNull && obj == null && length <= 1) { + if (readIndex) + list._index = index + 1; + return obj && clone ? obj.clone() : obj; + } + obj = Base.create(this); + if (readIndex) + obj._read = true; + obj = obj.initialize.apply(obj, index > 0 || length < list.length + ? Array.prototype.slice.call(list, index, index + length) + : list) || obj; + if (readIndex) { + list._index = index + obj._read; + list._read = obj._read; + delete obj._read; + } + return obj; + }, + + peek: function(list, start) { + return list[list._index = start || list._index || 0]; + }, + + readAll: function(list, start, readNull, clone) { + var res = [], entry; + for (var i = start || 0, l = list.length; i < l; i++) { + res.push(Array.isArray(entry = list[i]) + ? this.read(entry, 0, 0, readNull, clone) + : this.read(list, i, 1, readNull, clone)); + } + return res; + }, + + readNamed: function(list, name, start, length, readNull, clone) { + var value = this.getNamed(list, name); + return this.read(value != null ? [value] : list, start, length, + readNull, clone); + }, + + getNamed: function(list, name) { + var arg = list[0]; + if (list._hasObject === undefined) + list._hasObject = list.length === 1 && Base.isPlainObject(arg); + if (list._hasObject) + return name ? arg[name] : arg; + }, + + hasNamed: function(list, name) { + return !!this.getNamed(list, name); + }, + + isPlainValue: function(obj) { + return this.isPlainObject(obj) || Array.isArray(obj); + }, + + serialize: function(obj, options, compact, dictionary) { + options = options || {}; + + var root = !dictionary, + res; + if (root) { + options.formatter = new Formatter(options.precision); + dictionary = { + length: 0, + definitions: {}, + references: {}, + add: function(item, create) { + var id = '#' + item._id, + ref = this.references[id]; + if (!ref) { + this.length++; + var res = create.call(item), + name = item._class; + if (name && res[0] !== name) + res.unshift(name); + this.definitions[id] = res; + ref = this.references[id] = [id]; + } + return ref; + } + }; + } + if (obj && obj._serialize) { + res = obj._serialize(options, dictionary); + var name = obj._class; + if (name && !compact && !res._compact && res[0] !== name) + res.unshift(name); + } else if (Array.isArray(obj)) { + res = []; + for (var i = 0, l = obj.length; i < l; i++) + res[i] = Base.serialize(obj[i], options, compact, + dictionary); + if (compact) + res._compact = true; + } else if (Base.isPlainObject(obj)) { + res = {}; + for (var i in obj) + if (obj.hasOwnProperty(i)) + res[i] = Base.serialize(obj[i], options, compact, + dictionary); + } else if (typeof obj === 'number') { + res = options.formatter.number(obj, options.precision); + } else { + res = obj; + } + return root && dictionary.length > 0 + ? [['dictionary', dictionary.definitions], res] + : res; + }, + + deserialize: function(obj, data) { + var res = obj; + data = data || {}; + if (Array.isArray(obj)) { + var type = obj[0], + isDictionary = type === 'dictionary'; + if (!isDictionary) { + if (data.dictionary && obj.length == 1 && /^#/.test(type)) + return data.dictionary[type]; + type = Base.exports[type]; + } + res = []; + for (var i = type ? 1 : 0, l = obj.length; i < l; i++) + res.push(Base.deserialize(obj[i], data)); + if (isDictionary) { + data.dictionary = res[0]; + } else if (type) { + var args = res; + res = Base.create(type); + type.apply(res, args); + } + } else if (Base.isPlainObject(obj)) { + res = {}; + for (var key in obj) + res[key] = Base.deserialize(obj[key], data); + } + return res; + }, + + exportJSON: function(obj, options) { + return JSON.stringify(Base.serialize(obj, options)); + }, + + importJSON: function(json) { + return Base.deserialize( + typeof json === 'string' ? JSON.parse(json) : json); + }, + + splice: function(list, items, index, remove) { + var amount = items && items.length, + append = index === undefined; + index = append ? list.length : index; + if (index > list.length) + index = list.length; + for (var i = 0; i < amount; i++) + items[i]._index = index + i; + if (append) { + list.push.apply(list, items); + return []; + } else { + var args = [index, remove]; + if (items) + args.push.apply(args, items); + var removed = list.splice.apply(list, args); + for (var i = 0, l = removed.length; i < l; i++) + delete removed[i]._index; + for (var i = index + amount, l = list.length; i < l; i++) + list[i]._index = i; + return removed; + } + }, + + merge: function() { + return Base.each(arguments, function(hash) { + Base.each(hash, function(value, key) { + this[key] = value; + }, this); + }, new Base(), true); + }, + + capitalize: function(str) { + return str.replace(/\b[a-z]/g, function(match) { + return match.toUpperCase(); + }); + }, + + camelize: function(str) { + return str.replace(/-(.)/g, function(all, chr) { + return chr.toUpperCase(); + }); + }, + + hyphenate: function(str) { + return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); + } + } +}); + +var Callback = { + attach: function(type, func) { + if (typeof type !== 'string') { + Base.each(type, function(value, key) { + this.attach(key, value); + }, this); + return; + } + var entry = this._eventTypes[type]; + if (entry) { + var handlers = this._handlers = this._handlers || {}; + handlers = handlers[type] = handlers[type] || []; + if (handlers.indexOf(func) == -1) { + handlers.push(func); + if (entry.install && handlers.length == 1) + entry.install.call(this, type); + } + } + }, + + detach: function(type, func) { + if (typeof type !== 'string') { + Base.each(type, function(value, key) { + this.detach(key, value); + }, this); + return; + } + var entry = this._eventTypes[type], + handlers = this._handlers && this._handlers[type], + index; + if (entry && handlers) { + if (!func || (index = handlers.indexOf(func)) != -1 + && handlers.length == 1) { + if (entry.uninstall) + entry.uninstall.call(this, type); + delete this._handlers[type]; + } else if (index != -1) { + handlers.splice(index, 1); + } + } + }, + + once: function(type, func) { + this.attach(type, function() { + func.apply(this, arguments); + this.detach(type, func); + }); + }, + + fire: function(type, event) { + var handlers = this._handlers && this._handlers[type]; + if (!handlers) + return false; + var args = [].slice.call(arguments, 1); + Base.each(handlers, function(func) { + if (func.apply(this, args) === false && event && event.stop) + event.stop(); + }, this); + return true; + }, + + responds: function(type) { + return !!(this._handlers && this._handlers[type]); + }, + + on: '#attach', + off: '#detach', + trigger: '#fire', + + statics: { + inject: function inject() { + for (var i = 0, l = arguments.length; i < l; i++) { + var src = arguments[i], + events = src._events; + if (events) { + var types = {}; + Base.each(events, function(entry, key) { + var isString = typeof entry === 'string', + name = isString ? entry : key, + part = Base.capitalize(name), + type = name.substring(2).toLowerCase(); + types[type] = isString ? {} : entry; + name = '_' + name; + src['get' + part] = function() { + return this[name]; + }; + src['set' + part] = function(func) { + if (func) { + this.attach(type, func); + } else if (this[name]) { + this.detach(type, this[name]); + } + this[name] = func; + }; + }); + src._eventTypes = types; + } + inject.base.call(this, src); + } + return this; + } + } +}; + +var PaperScope = Base.extend({ + _class: 'PaperScope', + + initialize: function PaperScope(script) { + paper = this; + this.project = null; + this.projects = []; + this.tools = []; + this.palettes = []; + this._id = script && (script.getAttribute('id') || script.src) + || ('paperscope-' + (PaperScope._id++)); + if (script) + script.setAttribute('id', this._id); + PaperScope._scopes[this._id] = this; + if (!this.support) { + var ctx = CanvasProvider.getContext(1, 1); + PaperScope.prototype.support = { + nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx, + nativeBlendModes: BlendMode.nativeModes + }; + CanvasProvider.release(ctx); + } + }, + + version: '0.9.5', + + getView: function() { + return this.project && this.project.view; + }, + + getTool: function() { + if (!this._tool) + this._tool = new Tool(); + return this._tool; + }, + + evaluate: function(code) { + var res = paper.PaperScript.evaluate(code, this); + View.updateFocus(); + return res; + }, + + install: function(scope) { + var that = this; + Base.each(['project', 'view', 'tool'], function(key) { + Base.define(scope, key, { + configurable: true, + get: function() { + return that[key]; + } + }); + }); + for (var key in this) { + if (!/^(version|_id)/.test(key) && !(key in scope)) + scope[key] = this[key]; + } + }, + + setup: function(canvas) { + paper = this; + this.project = new Project(canvas); + return this; + }, + + clear: function() { + for (var i = this.projects.length - 1; i >= 0; i--) + this.projects[i].remove(); + for (var i = this.tools.length - 1; i >= 0; i--) + this.tools[i].remove(); + for (var i = this.palettes.length - 1; i >= 0; i--) + this.palettes[i].remove(); + }, + + remove: function() { + this.clear(); + delete PaperScope._scopes[this._id]; + }, + + statics: new function() { + function handleAttribute(name) { + name += 'Attribute'; + return function(el, attr) { + return el[name](attr) || el[name]('data-paper-' + attr); + }; + } + + return { + _scopes: {}, + _id: 0, + + get: function(id) { + if (typeof id === 'object') + id = id.getAttribute('id'); + return this._scopes[id] || null; + }, + + getAttribute: handleAttribute('get'), + hasAttribute: handleAttribute('has') + }; + } +}); + +var PaperScopeItem = Base.extend(Callback, { + + initialize: function(activate) { + this._scope = paper; + this._index = this._scope[this._list].push(this) - 1; + if (activate || !this._scope[this._reference]) + this.activate(); + }, + + activate: function() { + if (!this._scope) + return false; + var prev = this._scope[this._reference]; + if (prev && prev != this) + prev.fire('deactivate'); + this._scope[this._reference] = this; + this.fire('activate', prev); + return true; + }, + + isActive: function() { + return this._scope[this._reference] === this; + }, + + remove: function() { + if (this._index == null) + return false; + Base.splice(this._scope[this._list], null, this._index, 1); + if (this._scope[this._reference] == this) + this._scope[this._reference] = null; + this._scope = null; + return true; + } +}); + +var Formatter = Base.extend({ + initialize: function(precision) { + this.precision = precision || 5; + this.multiplier = Math.pow(10, this.precision); + }, + + number: function(val) { + return Math.round(val * this.multiplier) / this.multiplier; + }, + + point: function(val, separator) { + return this.number(val.x) + (separator || ',') + this.number(val.y); + }, + + size: function(val, separator) { + return this.number(val.width) + (separator || ',') + + this.number(val.height); + }, + + rectangle: function(val, separator) { + return this.point(val, separator) + (separator || ',') + + this.size(val, separator); + } +}); + +Formatter.instance = new Formatter(5); + +var Numerical = new function() { + + var abscissas = [ + [ 0.5773502691896257645091488], + [0,0.7745966692414833770358531], + [ 0.3399810435848562648026658,0.8611363115940525752239465], + [0,0.5384693101056830910363144,0.9061798459386639927976269], + [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016], + [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897], + [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609], + [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762], + [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640], + [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380], + [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491], + [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294], + [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973], + [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657], + [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542] + ]; + + var weights = [ + [1], + [0.8888888888888888888888889,0.5555555555555555555555556], + [0.6521451548625461426269361,0.3478548451374538573730639], + [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640], + [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961], + [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114], + [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314], + [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922], + [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688], + [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537], + [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160], + [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216], + [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329], + [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284], + [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806] + ]; + + var abs = Math.abs, + sqrt = Math.sqrt, + pow = Math.pow, + cos = Math.cos, + PI = Math.PI; + + return { + TOLERANCE: 10e-6, + EPSILON: 10e-12, + KAPPA: 4 * (sqrt(2) - 1) / 3, + + isZero: function(val) { + return abs(val) <= this.EPSILON; + }, + + integrate: function(f, a, b, n) { + var x = abscissas[n - 2], + w = weights[n - 2], + A = 0.5 * (b - a), + B = A + a, + i = 0, + m = (n + 1) >> 1, + sum = n & 1 ? w[i++] * f(B) : 0; + while (i < m) { + var Ax = A * x[i]; + sum += w[i++] * (f(B + Ax) + f(B - Ax)); + } + return A * sum; + }, + + findRoot: function(f, df, x, a, b, n, tolerance) { + for (var i = 0; i < n; i++) { + var fx = f(x), + dx = fx / df(x); + if (abs(dx) < tolerance) + return x; + var nx = x - dx; + if (fx > 0) { + b = x; + x = nx <= a ? 0.5 * (a + b) : nx; + } else { + a = x; + x = nx >= b ? 0.5 * (a + b) : nx; + } + } + }, + + solveQuadratic: function(a, b, c, roots) { + var epsilon = this.EPSILON; + if (abs(a) < epsilon) { + if (abs(b) >= epsilon) { + roots[0] = -c / b; + return 1; + } + return abs(c) < epsilon ? -1 : 0; + } + var q = b * b - 4 * a * c; + if (q < 0) + return 0; + q = sqrt(q); + a *= 2; + var n = 0; + roots[n++] = (-b - q) / a; + if (q > 0) + roots[n++] = (-b + q) / a; + return n; + }, + + solveCubic: function(a, b, c, d, roots) { + var epsilon = this.EPSILON; + if (abs(a) < epsilon) + return Numerical.solveQuadratic(b, c, d, roots); + b /= a; + c /= a; + d /= a; + var bb = b * b, + p = (bb - 3 * c) / 9, + q = (2 * bb * b - 9 * b * c + 27 * d) / 54, + ppp = p * p * p, + D = q * q - ppp; + b /= 3; + if (abs(D) < epsilon) { + if (abs(q) < epsilon) { + roots[0] = - b; + return 1; + } + var sqp = sqrt(p), + snq = q > 0 ? 1 : -1; + roots[0] = -snq * 2 * sqp - b; + roots[1] = snq * sqp - b; + return 2; + } + if (D < 0) { + var sqp = sqrt(p), + phi = Math.acos(q / (sqp * sqp * sqp)) / 3, + t = -2 * sqp, + o = 2 * PI / 3; + roots[0] = t * cos(phi) - b; + roots[1] = t * cos(phi + o) - b; + roots[2] = t * cos(phi - o) - b; + return 3; + } + var A = (q > 0 ? -1 : 1) * pow(abs(q) + sqrt(D), 1 / 3); + roots[0] = A + p / A - b; + return 1; + } + }; +}; + +var Point = Base.extend({ + _class: 'Point', + _readIndex: true, + + initialize: function Point(arg0, arg1) { + var type = typeof arg0; + if (type === 'number') { + var hasY = typeof arg1 === 'number'; + this.x = arg0; + this.y = hasY ? arg1 : arg0; + if (this._read) + this._read = hasY ? 2 : 1; + } else if (type === 'undefined' || arg0 === null) { + this.x = this.y = 0; + if (this._read) + this._read = arg0 === null ? 1 : 0; + } else { + if (Array.isArray(arg0)) { + this.x = arg0[0]; + this.y = arg0.length > 1 ? arg0[1] : arg0[0]; + } else if (arg0.x != null) { + this.x = arg0.x; + this.y = arg0.y; + } else if (arg0.width != null) { + this.x = arg0.width; + this.y = arg0.height; + } else if (arg0.angle != null) { + this.x = arg0.length; + this.y = 0; + this.setAngle(arg0.angle); + } else { + this.x = this.y = 0; + if (this._read) + this._read = 0; + } + if (this._read) + this._read = 1; + } + }, + + set: function(x, y) { + this.x = x; + this.y = y; + return this; + }, + + equals: function(point) { + return point === this || point && (this.x === point.x + && this.y === point.y + || Array.isArray(point) && this.x === point[0] + && this.y === point[1]) || false; + }, + + clone: function() { + return new Point(this.x, this.y); + }, + + toString: function() { + var f = Formatter.instance; + return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }'; + }, + + _serialize: function(options) { + var f = options.formatter; + return [f.number(this.x), + f.number(this.y)]; + }, + + add: function(point) { + point = Point.read(arguments); + return new Point(this.x + point.x, this.y + point.y); + }, + + subtract: function(point) { + point = Point.read(arguments); + return new Point(this.x - point.x, this.y - point.y); + }, + + multiply: function(point) { + point = Point.read(arguments); + return new Point(this.x * point.x, this.y * point.y); + }, + + divide: function(point) { + point = Point.read(arguments); + return new Point(this.x / point.x, this.y / point.y); + }, + + modulo: function(point) { + point = Point.read(arguments); + return new Point(this.x % point.x, this.y % point.y); + }, + + negate: function() { + return new Point(-this.x, -this.y); + }, + + transform: function(matrix) { + return matrix ? matrix._transformPoint(this) : this; + }, + + getDistance: function(point, squared) { + point = Point.read(arguments); + var x = point.x - this.x, + y = point.y - this.y, + d = x * x + y * y; + return squared ? d : Math.sqrt(d); + }, + + getLength: function() { + var length = this.x * this.x + this.y * this.y; + return arguments.length && arguments[0] ? length : Math.sqrt(length); + }, + + setLength: function(length) { + if (this.isZero()) { + var angle = this._angle || 0; + this.set( + Math.cos(angle) * length, + Math.sin(angle) * length + ); + } else { + var scale = length / this.getLength(); + if (Numerical.isZero(scale)) + this.getAngle(); + this.set( + this.x * scale, + this.y * scale + ); + } + return this; + }, + + normalize: function(length) { + if (length === undefined) + length = 1; + var current = this.getLength(), + scale = current !== 0 ? length / current : 0, + point = new Point(this.x * scale, this.y * scale); + point._angle = this._angle; + return point; + }, + + getAngle: function() { + return this.getAngleInRadians(arguments[0]) * 180 / Math.PI; + }, + + setAngle: function(angle) { + angle = this._angle = angle * Math.PI / 180; + if (!this.isZero()) { + var length = this.getLength(); + this.set( + Math.cos(angle) * length, + Math.sin(angle) * length + ); + } + return this; + }, + + getAngleInRadians: function() { + if (arguments[0] === undefined) { + if (this._angle == null) + this._angle = Math.atan2(this.y, this.x); + return this._angle; + } else { + var point = Point.read(arguments), + div = this.getLength() * point.getLength(); + if (Numerical.isZero(div)) { + return NaN; + } else { + return Math.acos(this.dot(point) / div); + } + } + }, + + getAngleInDegrees: function() { + return this.getAngle(arguments[0]); + }, + + getQuadrant: function() { + return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3; + }, + + getDirectedAngle: function(point) { + point = Point.read(arguments); + return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI; + }, + + rotate: function(angle, center) { + if (angle === 0) + return this.clone(); + angle = angle * Math.PI / 180; + var point = center ? this.subtract(center) : this, + s = Math.sin(angle), + c = Math.cos(angle); + point = new Point( + point.x * c - point.y * s, + point.y * c + point.x * s + ); + return center ? point.add(center) : point; + }, + + isInside: function(rect) { + return rect.contains(this); + }, + + isClose: function(point, tolerance) { + return this.getDistance(point) < tolerance; + }, + + isColinear: function(point) { + return this.cross(point) < 0.00001; + }, + + isOrthogonal: function(point) { + return this.dot(point) < 0.00001; + }, + + isZero: function() { + return Numerical.isZero(this.x) && Numerical.isZero(this.y); + }, + + isNaN: function() { + return isNaN(this.x) || isNaN(this.y); + }, + + dot: function(point) { + point = Point.read(arguments); + return this.x * point.x + this.y * point.y; + }, + + cross: function(point) { + point = Point.read(arguments); + return this.x * point.y - this.y * point.x; + }, + + project: function(point) { + point = Point.read(arguments); + if (point.isZero()) { + return new Point(0, 0); + } else { + var scale = this.dot(point) / point.dot(point); + return new Point( + point.x * scale, + point.y * scale + ); + } + }, + + statics: { + min: function() { + var point1 = Point.read(arguments); + point2 = Point.read(arguments); + return new Point( + Math.min(point1.x, point2.x), + Math.min(point1.y, point2.y) + ); + }, + + max: function() { + var point1 = Point.read(arguments); + point2 = Point.read(arguments); + return new Point( + Math.max(point1.x, point2.x), + Math.max(point1.y, point2.y) + ); + }, + + random: function() { + return new Point(Math.random(), Math.random()); + } + } +}, new function() { + + return Base.each(['round', 'ceil', 'floor', 'abs'], function(name) { + var op = Math[name]; + this[name] = function() { + return new Point(op(this.x), op(this.y)); + }; + }, {}); +}); + +var LinkedPoint = Point.extend({ + initialize: function Point(x, y, owner, setter) { + this._x = x; + this._y = y; + this._owner = owner; + this._setter = setter; + }, + + set: function(x, y, dontNotify) { + this._x = x; + this._y = y; + if (!dontNotify) + this._owner[this._setter](this); + return this; + }, + + getX: function() { + return this._x; + }, + + setX: function(x) { + this._x = x; + this._owner[this._setter](this); + }, + + getY: function() { + return this._y; + }, + + setY: function(y) { + this._y = y; + this._owner[this._setter](this); + } +}); + +var Size = Base.extend({ + _class: 'Size', + _readIndex: true, + + initialize: function Size(arg0, arg1) { + var type = typeof arg0; + if (type === 'number') { + var hasHeight = typeof arg1 === 'number'; + this.width = arg0; + this.height = hasHeight ? arg1 : arg0; + if (this._read) + this._read = hasHeight ? 2 : 1; + } else if (type === 'undefined' || arg0 === null) { + this.width = this.height = 0; + if (this._read) + this._read = arg0 === null ? 1 : 0; + } else { + if (Array.isArray(arg0)) { + this.width = arg0[0]; + this.height = arg0.length > 1 ? arg0[1] : arg0[0]; + } else if (arg0.width != null) { + this.width = arg0.width; + this.height = arg0.height; + } else if (arg0.x != null) { + this.width = arg0.x; + this.height = arg0.y; + } else { + this.width = this.height = 0; + if (this._read) + this._read = 0; + } + if (this._read) + this._read = 1; + } + }, + + set: function(width, height) { + this.width = width; + this.height = height; + return this; + }, + + equals: function(size) { + return size === this || size && (this.width === size.width + && this.height === size.height + || Array.isArray(size) && this.width === size[0] + && this.height === size[1]) || false; + }, + + clone: function() { + return new Size(this.width, this.height); + }, + + toString: function() { + var f = Formatter.instance; + return '{ width: ' + f.number(this.width) + + ', height: ' + f.number(this.height) + ' }'; + }, + + _serialize: function(options) { + var f = options.formatter; + return [f.number(this.width), + f.number(this.height)]; + }, + + add: function(size) { + size = Size.read(arguments); + return new Size(this.width + size.width, this.height + size.height); + }, + + subtract: function(size) { + size = Size.read(arguments); + return new Size(this.width - size.width, this.height - size.height); + }, + + multiply: function(size) { + size = Size.read(arguments); + return new Size(this.width * size.width, this.height * size.height); + }, + + divide: function(size) { + size = Size.read(arguments); + return new Size(this.width / size.width, this.height / size.height); + }, + + modulo: function(size) { + size = Size.read(arguments); + return new Size(this.width % size.width, this.height % size.height); + }, + + negate: function() { + return new Size(-this.width, -this.height); + }, + + isZero: function() { + return Numerical.isZero(this.width) && Numerical.isZero(this.height); + }, + + isNaN: function() { + return isNaN(this.width) || isNaN(this.height); + }, + + statics: { + min: function(size1, size2) { + return new Size( + Math.min(size1.width, size2.width), + Math.min(size1.height, size2.height)); + }, + + max: function(size1, size2) { + return new Size( + Math.max(size1.width, size2.width), + Math.max(size1.height, size2.height)); + }, + + random: function() { + return new Size(Math.random(), Math.random()); + } + } +}, new function() { + + return Base.each(['round', 'ceil', 'floor', 'abs'], function(name) { + var op = Math[name]; + this[name] = function() { + return new Size(op(this.width), op(this.height)); + }; + }, {}); +}); + +var LinkedSize = Size.extend({ + initialize: function Size(width, height, owner, setter) { + this._width = width; + this._height = height; + this._owner = owner; + this._setter = setter; + }, + + set: function(width, height, dontNotify) { + this._width = width; + this._height = height; + if (!dontNotify) + this._owner[this._setter](this); + return this; + }, + + getWidth: function() { + return this._width; + }, + + setWidth: function(width) { + this._width = width; + this._owner[this._setter](this); + }, + + getHeight: function() { + return this._height; + }, + + setHeight: function(height) { + this._height = height; + this._owner[this._setter](this); + } +}); + +var Rectangle = Base.extend({ + _class: 'Rectangle', + _readIndex: true, + + initialize: function Rectangle(arg0, arg1, arg2, arg3) { + var type = typeof arg0, + read = 0; + if (type === 'number') { + this.x = arg0; + this.y = arg1; + this.width = arg2; + this.height = arg3; + read = 4; + } else if (type === 'undefined' || arg0 === null) { + this.x = this.y = this.width = this.height = 0; + read = arg0 === null ? 1 : 0; + } else if (arguments.length === 1) { + if (Array.isArray(arg0)) { + this.x = arg0[0]; + this.y = arg0[1]; + this.width = arg0[2]; + this.height = arg0[3]; + read = 1; + } else if (arg0.x !== undefined || arg0.width !== undefined) { + this.x = arg0.x || 0; + this.y = arg0.y || 0; + this.width = arg0.width || 0; + this.height = arg0.height || 0; + read = 1; + } else if (arg0.from === undefined && arg0.to === undefined) { + this.x = this.y = this.width = this.height = 0; + this._set(arg0); + read = 1; + } + } + if (!read) { + var point = Point.readNamed(arguments, 'from'), + next = Base.peek(arguments); + this.x = point.x; + this.y = point.y; + if (next && next.x !== undefined || Base.hasNamed(arguments, 'to')) { + var to = Point.readNamed(arguments, 'to'); + this.width = to.x - point.x; + this.height = to.y - point.y; + if (this.width < 0) { + this.x = to.x; + this.width = -this.width; + } + if (this.height < 0) { + this.y = to.y; + this.height = -this.height; + } + } else { + var size = Size.read(arguments); + this.width = size.width; + this.height = size.height; + } + read = arguments._index; + } + if (this._read) + this._read = read; + }, + + set: function(x, y, width, height) { + this.x = x; + this.y = y; + this.width = width; + this.height = height; + return this; + }, + + clone: function() { + return new Rectangle(this.x, this.y, this.width, this.height); + }, + + equals: function(rect) { + if (Base.isPlainValue(rect)) + rect = Rectangle.read(arguments); + return rect === this + || rect && this.x === rect.x && this.y === rect.y + && this.width === rect.width && this.height=== rect.height + || false; + }, + + toString: function() { + var f = Formatter.instance; + return '{ x: ' + f.number(this.x) + + ', y: ' + f.number(this.y) + + ', width: ' + f.number(this.width) + + ', height: ' + f.number(this.height) + + ' }'; + }, + + _serialize: function(options) { + var f = options.formatter; + return [f.number(this.x), + f.number(this.y), + f.number(this.width), + f.number(this.height)]; + }, + + getPoint: function() { + return new (arguments[0] ? Point : LinkedPoint) + (this.x, this.y, this, 'setPoint'); + }, + + setPoint: function(point) { + point = Point.read(arguments); + this.x = point.x; + this.y = point.y; + }, + + getSize: function() { + return new (arguments[0] ? Size : LinkedSize) + (this.width, this.height, this, 'setSize'); + }, + + setSize: function(size) { + size = Size.read(arguments); + if (this._fixX) + this.x += (this.width - size.width) * this._fixX; + if (this._fixY) + this.y += (this.height - size.height) * this._fixY; + this.width = size.width; + this.height = size.height; + this._fixW = 1; + this._fixH = 1; + }, + + getLeft: function() { + return this.x; + }, + + setLeft: function(left) { + if (!this._fixW) + this.width -= left - this.x; + this.x = left; + this._fixX = 0; + }, + + getTop: function() { + return this.y; + }, + + setTop: function(top) { + if (!this._fixH) + this.height -= top - this.y; + this.y = top; + this._fixY = 0; + }, + + getRight: function() { + return this.x + this.width; + }, + + setRight: function(right) { + if (this._fixX !== undefined && this._fixX !== 1) + this._fixW = 0; + if (this._fixW) + this.x = right - this.width; + else + this.width = right - this.x; + this._fixX = 1; + }, + + getBottom: function() { + return this.y + this.height; + }, + + setBottom: function(bottom) { + if (this._fixY !== undefined && this._fixY !== 1) + this._fixH = 0; + if (this._fixH) + this.y = bottom - this.height; + else + this.height = bottom - this.y; + this._fixY = 1; + }, + + getCenterX: function() { + return this.x + this.width * 0.5; + }, + + setCenterX: function(x) { + this.x = x - this.width * 0.5; + this._fixX = 0.5; + }, + + getCenterY: function() { + return this.y + this.height * 0.5; + }, + + setCenterY: function(y) { + this.y = y - this.height * 0.5; + this._fixY = 0.5; + }, + + getCenter: function() { + return new (arguments[0] ? Point : LinkedPoint) + (this.getCenterX(), this.getCenterY(), this, 'setCenter'); + }, + + setCenter: function(point) { + point = Point.read(arguments); + this.setCenterX(point.x); + this.setCenterY(point.y); + return this; + }, + + isEmpty: function() { + return this.width == 0 || this.height == 0; + }, + + contains: function(arg) { + return arg && arg.width !== undefined + || (Array.isArray(arg) ? arg : arguments).length == 4 + ? this._containsRectangle(Rectangle.read(arguments)) + : this._containsPoint(Point.read(arguments)); + }, + + _containsPoint: function(point) { + var x = point.x, + y = point.y; + return x >= this.x && y >= this.y + && x <= this.x + this.width + && y <= this.y + this.height; + }, + + _containsRectangle: function(rect) { + var x = rect.x, + y = rect.y; + return x >= this.x && y >= this.y + && x + rect.width <= this.x + this.width + && y + rect.height <= this.y + this.height; + }, + + intersects: function(rect) { + rect = Rectangle.read(arguments); + return rect.x + rect.width > this.x + && rect.y + rect.height > this.y + && rect.x < this.x + this.width + && rect.y < this.y + this.height; + }, + + touches: function(rect) { + rect = Rectangle.read(arguments); + return rect.x + rect.width >= this.x + && rect.y + rect.height >= this.y + && rect.x <= this.x + this.width + && rect.y <= this.y + this.height; + }, + + intersect: function(rect) { + rect = Rectangle.read(arguments); + var x1 = Math.max(this.x, rect.x), + y1 = Math.max(this.y, rect.y), + x2 = Math.min(this.x + this.width, rect.x + rect.width), + y2 = Math.min(this.y + this.height, rect.y + rect.height); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + unite: function(rect) { + rect = Rectangle.read(arguments); + var x1 = Math.min(this.x, rect.x), + y1 = Math.min(this.y, rect.y), + x2 = Math.max(this.x + this.width, rect.x + rect.width), + y2 = Math.max(this.y + this.height, rect.y + rect.height); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + include: function(point) { + point = Point.read(arguments); + var x1 = Math.min(this.x, point.x), + y1 = Math.min(this.y, point.y), + x2 = Math.max(this.x + this.width, point.x), + y2 = Math.max(this.y + this.height, point.y); + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + expand: function(hor, ver) { + if (ver === undefined) + ver = hor; + return new Rectangle(this.x - hor / 2, this.y - ver / 2, + this.width + hor, this.height + ver); + }, + + scale: function(hor, ver) { + return this.expand(this.width * hor - this.width, + this.height * (ver === undefined ? hor : ver) - this.height); + } +}, new function() { + return Base.each([ + ['Top', 'Left'], ['Top', 'Right'], + ['Bottom', 'Left'], ['Bottom', 'Right'], + ['Left', 'Center'], ['Top', 'Center'], + ['Right', 'Center'], ['Bottom', 'Center'] + ], + function(parts, index) { + var part = parts.join(''); + var xFirst = /^[RL]/.test(part); + if (index >= 4) + parts[1] += xFirst ? 'Y' : 'X'; + var x = parts[xFirst ? 0 : 1], + y = parts[xFirst ? 1 : 0], + getX = 'get' + x, + getY = 'get' + y, + setX = 'set' + x, + setY = 'set' + y, + get = 'get' + part, + set = 'set' + part; + this[get] = function() { + return new (arguments[0] ? Point : LinkedPoint) + (this[getX](), this[getY](), this, set); + }; + this[set] = function(point) { + point = Point.read(arguments); + this[setX](point.x); + this[setY](point.y); + }; + }, {}); +}); + +var LinkedRectangle = Rectangle.extend({ + initialize: function Rectangle(x, y, width, height, owner, setter) { + this.set(x, y, width, height, true); + this._owner = owner; + this._setter = setter; + }, + + set: function(x, y, width, height, dontNotify) { + this._x = x; + this._y = y; + this._width = width; + this._height = height; + if (!dontNotify) + this._owner[this._setter](this); + return this; + } +}, new function() { + var proto = Rectangle.prototype; + + return Base.each(['x', 'y', 'width', 'height'], function(key) { + var part = Base.capitalize(key); + var internal = '_' + key; + this['get' + part] = function() { + return this[internal]; + }; + + this['set' + part] = function(value) { + this[internal] = value; + if (!this._dontNotify) + this._owner[this._setter](this); + }; + }, Base.each(['Point', 'Size', 'Center', + 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY', + 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight', + 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'], + function(key) { + var name = 'set' + key; + this[name] = function() { + this._dontNotify = true; + proto[name].apply(this, arguments); + delete this._dontNotify; + this._owner[this._setter](this); + }; + }, { + isSelected: function() { + return this._owner._boundsSelected; + }, + + setSelected: function(selected) { + var owner = this._owner; + if (owner.setSelected) { + owner._boundsSelected = selected; + owner.setSelected(selected || owner._selectedSegmentState > 0); + } + } + }) + ); +}); + +var Matrix = Base.extend({ + _class: 'Matrix', + + initialize: function Matrix(arg) { + var count = arguments.length, + ok = true; + if (count == 6) { + this.set.apply(this, arguments); + } else if (count == 1) { + if (arg instanceof Matrix) { + this.set(arg._a, arg._c, arg._b, arg._d, arg._tx, arg._ty); + } else if (Array.isArray(arg)) { + this.set.apply(this, arg); + } else { + ok = false; + } + } else if (count == 0) { + this.reset(); + } else { + ok = false; + } + if (!ok) + throw new Error('Unsupported matrix parameters'); + }, + + set: function(a, c, b, d, tx, ty) { + this._a = a; + this._c = c; + this._b = b; + this._d = d; + this._tx = tx; + this._ty = ty; + return this; + }, + + _serialize: function(options) { + return Base.serialize(this.getValues(), options); + }, + + clone: function() { + return new Matrix(this._a, this._c, this._b, this._d, + this._tx, this._ty); + }, + + equals: function(mx) { + return mx === this || mx && this._a == mx._a && this._b == mx._b + && this._c == mx._c && this._d == mx._d && this._tx == mx._tx + && this._ty == mx._ty + || false; + }, + + toString: function() { + var f = Formatter.instance; + return '[[' + [f.number(this._a), f.number(this._b), + f.number(this._tx)].join(', ') + '], [' + + [f.number(this._c), f.number(this._d), + f.number(this._ty)].join(', ') + ']]'; + }, + + reset: function() { + this._a = this._d = 1; + this._c = this._b = this._tx = this._ty = 0; + return this; + }, + + scale: function() { + var scale = Point.read(arguments), + center = Point.read(arguments, 0, 0, true); + if (center) + this.translate(center); + this._a *= scale.x; + this._c *= scale.x; + this._b *= scale.y; + this._d *= scale.y; + if (center) + this.translate(center.negate()); + return this; + }, + + translate: function(point) { + point = Point.read(arguments); + var x = point.x, + y = point.y; + this._tx += x * this._a + y * this._b; + this._ty += x * this._c + y * this._d; + return this; + }, + + rotate: function(angle, center) { + center = Point.read(arguments, 1); + angle = angle * Math.PI / 180; + var x = center.x, + y = center.y, + cos = Math.cos(angle), + sin = Math.sin(angle), + tx = x - x * cos + y * sin, + ty = y - x * sin - y * cos, + a = this._a, + b = this._b, + c = this._c, + d = this._d; + this._a = cos * a + sin * b; + this._b = -sin * a + cos * b; + this._c = cos * c + sin * d; + this._d = -sin * c + cos * d; + this._tx += tx * a + ty * b; + this._ty += tx * c + ty * d; + return this; + }, + + shear: function() { + var point = Point.read(arguments), + center = Point.read(arguments, 0, 0, true); + if (center) + this.translate(center); + var a = this._a, + c = this._c; + this._a += point.y * this._b; + this._c += point.y * this._d; + this._b += point.x * a; + this._d += point.x * c; + if (center) + this.translate(center.negate()); + return this; + }, + + isIdentity: function() { + return this._a == 1 && this._c == 0 && this._b == 0 && this._d == 1 + && this._tx == 0 && this._ty == 0; + }, + + isInvertible: function() { + return !!this._getDeterminant(); + }, + + isSingular: function() { + return !this._getDeterminant(); + }, + + concatenate: function(mx) { + var a = this._a, + b = this._b, + c = this._c, + d = this._d; + this._a = mx._a * a + mx._c * b; + this._b = mx._b * a + mx._d * b; + this._c = mx._a * c + mx._c * d; + this._d = mx._b * c + mx._d * d; + this._tx += mx._tx * a + mx._ty * b; + this._ty += mx._tx * c + mx._ty * d; + return this; + }, + + preConcatenate: function(mx) { + var a = this._a, + b = this._b, + c = this._c, + d = this._d, + tx = this._tx, + ty = this._ty; + this._a = mx._a * a + mx._b * c; + this._b = mx._a * b + mx._b * d; + this._c = mx._c * a + mx._d * c; + this._d = mx._c * b + mx._d * d; + this._tx = mx._a * tx + mx._b * ty + mx._tx; + this._ty = mx._c * tx + mx._d * ty + mx._ty; + return this; + }, + + transform: function( src, srcOff, dst, dstOff, numPts) { + return arguments.length < 5 + ? this._transformPoint(Point.read(arguments)) + : this._transformCoordinates(src, srcOff, dst, dstOff, numPts); + }, + + _transformPoint: function(point, dest, dontNotify) { + var x = point.x, + y = point.y; + if (!dest) + dest = new Point(); + return dest.set( + x * this._a + y * this._b + this._tx, + x * this._c + y * this._d + this._ty, + dontNotify + ); + }, + + _transformCoordinates: function(src, srcOff, dst, dstOff, numPts) { + var i = srcOff, j = dstOff, + srcEnd = srcOff + 2 * numPts; + while (i < srcEnd) { + var x = src[i++], + y = src[i++]; + dst[j++] = x * this._a + y * this._b + this._tx; + dst[j++] = x * this._c + y * this._d + this._ty; + } + return dst; + }, + + _transformCorners: function(rect) { + var x1 = rect.x, + y1 = rect.y, + x2 = x1 + rect.width, + y2 = y1 + rect.height, + coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ]; + return this._transformCoordinates(coords, 0, coords, 0, 4); + }, + + _transformBounds: function(bounds, dest, dontNotify) { + var coords = this._transformCorners(bounds), + min = coords.slice(0, 2), + max = coords.slice(); + for (var i = 2; i < 8; i++) { + var val = coords[i], + j = i & 1; + if (val < min[j]) + min[j] = val; + else if (val > max[j]) + max[j] = val; + } + if (!dest) + dest = new Rectangle(); + return dest.set(min[0], min[1], max[0] - min[0], max[1] - min[1], + dontNotify); + }, + + inverseTransform: function() { + return this._inverseTransform(Point.read(arguments)); + }, + + _getDeterminant: function() { + var det = this._a * this._d - this._b * this._c; + return isFinite(det) && !Numerical.isZero(det) + && isFinite(this._tx) && isFinite(this._ty) + ? det : null; + }, + + _inverseTransform: function(point, dest, dontNotify) { + var det = this._getDeterminant(); + if (!det) + return null; + var x = point.x - this._tx, + y = point.y - this._ty; + if (!dest) + dest = new Point(); + return dest.set( + (x * this._d - y * this._b) / det, + (y * this._a - x * this._c) / det, + dontNotify + ); + }, + + decompose: function() { + var a = this._a, b = this._b, c = this._c, d = this._d; + if (Numerical.isZero(a * d - b * c)) + return null; + + var scaleX = Math.sqrt(a * a + b * b); + a /= scaleX; + b /= scaleX; + + var shear = a * c + b * d; + c -= a * shear; + d -= b * shear; + + var scaleY = Math.sqrt(c * c + d * d); + c /= scaleY; + d /= scaleY; + shear /= scaleY; + + if (a * d < b * c) { + a = -a; + b = -b; + shear = -shear; + scaleX = -scaleX; + } + + return { + translation: this.getTranslation(), + scaling: new Point(scaleX, scaleY), + rotation: -Math.atan2(b, a) * 180 / Math.PI, + shearing: shear + }; + }, + + getValues: function() { + return [ this._a, this._c, this._b, this._d, this._tx, this._ty ]; + }, + + getTranslation: function() { + return new Point(this._tx, this._ty); + }, + + getScaling: function() { + return (this.decompose() || {}).scaling; + }, + + getRotation: function() { + return (this.decompose() || {}).rotation; + }, + + inverted: function() { + var det = this._getDeterminant(); + return det && new Matrix( + this._d / det, + -this._c / det, + -this._b / det, + this._a / det, + (this._b * this._ty - this._d * this._tx) / det, + (this._c * this._tx - this._a * this._ty) / det); + }, + + shiftless: function() { + return new Matrix(this._a, this._c, this._b, this._d, 0, 0); + }, + + applyToContext: function(ctx) { + ctx.transform(this._a, this._c, this._b, this._d, this._tx, this._ty); + } +}, new function() { + return Base.each({ + scaleX: '_a', + scaleY: '_d', + translateX: '_tx', + translateY: '_ty', + shearX: '_b', + shearY: '_c' + }, function(prop, name) { + name = Base.capitalize(name); + this['get' + name] = function() { + return this[prop]; + }; + this['set' + name] = function(value) { + this[prop] = value; + }; + }, {}); +}); + +var Line = Base.extend({ + _class: 'Line', + + initialize: function Line(arg0, arg1, arg2, arg3, arg4) { + var asVector = false; + if (arguments.length >= 4) { + this._px = arg0; + this._py = arg1; + this._vx = arg2; + this._vy = arg3; + asVector = arg4; + } else { + this._px = arg0.x; + this._py = arg0.y; + this._vx = arg1.x; + this._vy = arg1.y; + asVector = arg2; + } + if (!asVector) { + this._vx -= this._px; + this._vy -= this._py; + } + }, + + getPoint: function() { + return new Point(this._px, this._py); + }, + + getVector: function() { + return new Point(this._vx, this._vy); + }, + + getLength: function() { + return this.getVector().getLength(); + }, + + intersect: function(line, isInfinite) { + return Line.intersect( + this._px, this._py, this._vx, this._vy, + line._px, line._py, line._vx, line._vy, + true, isInfinite); + }, + + getSide: function(point) { + return Line.getSide( + this._px, this._py, this._vx, this._vy, + point.x, point.y, true); + }, + + getDistance: function(point) { + return Math.abs(Line.getSignedDistance( + this._px, this._py, this._vx, this._vy, + point.x, point.y, true)); + }, + + statics: { + intersect: function(apx, apy, avx, avy, bpx, bpy, bvx, bvy, asVector, + isInfinite) { + if (!asVector) { + avx -= apx; + avy -= apy; + bvx -= bpx; + bvy -= bpy; + } + var cross = bvy * avx - bvx * avy; + if (!Numerical.isZero(cross)) { + var dx = apx - bpx, + dy = apy - bpy, + ta = (bvx * dy - bvy * dx) / cross, + tb = (avx * dy - avy * dx) / cross; + if ((isInfinite || 0 <= ta && ta <= 1) + && (isInfinite || 0 <= tb && tb <= 1)) + return new Point( + apx + ta * avx, + apy + ta * avy); + } + }, + + getSide: function(px, py, vx, vy, x, y, asVector) { + if (!asVector) { + vx -= px; + vy -= py; + } + var v2x = x - px, + v2y = y - py, + ccw = v2x * vy - v2y * vx; + if (ccw === 0) { + ccw = v2x * vx + v2y * vy; + if (ccw > 0) { + v2x -= vx; + v2y -= vy; + ccw = v2x * vx + v2y * vy; + if (ccw < 0) + ccw = 0; + } + } + return ccw < 0 ? -1 : ccw > 0 ? 1 : 0; + }, + + getSignedDistance: function(px, py, vx, vy, x, y, asVector) { + if (!asVector) { + vx -= px; + vy -= py; + } + var m = vy / vx, + b = py - m * px; + return (y - (m * x) - b) / Math.sqrt(m * m + 1); + } + } +}); + +var Project = PaperScopeItem.extend({ + _class: 'Project', + _list: 'projects', + _reference: 'project', + + initialize: function Project(view) { + PaperScopeItem.call(this, true); + this.layers = []; + this.symbols = []; + this._currentStyle = new Style(); + this.activeLayer = new Layer(); + if (view) + this.view = view instanceof View ? view : View.create(view); + this._selectedItems = {}; + this._selectedItemCount = 0; + this._drawCount = 0; + this.options = {}; + }, + + _serialize: function(options, dictionary) { + return Base.serialize(this.layers, options, true, dictionary); + }, + + clear: function() { + for (var i = this.layers.length - 1; i >= 0; i--) + this.layers[i].remove(); + this.symbols = []; + }, + + remove: function remove() { + if (!remove.base.call(this)) + return false; + if (this.view) + this.view.remove(); + return true; + }, + + getCurrentStyle: function() { + return this._currentStyle; + }, + + setCurrentStyle: function(style) { + this._currentStyle.initialize(style); + }, + + getIndex: function() { + return this._index; + }, + + getSelectedItems: function() { + var items = []; + for (var id in this._selectedItems) { + var item = this._selectedItems[id]; + if (item._drawCount === this._drawCount) + items.push(item); + } + return items; + }, + + _updateSelection: function(item) { + if (item._selected) { + this._selectedItemCount++; + this._selectedItems[item._id] = item; + if (item.isInserted()) + item._drawCount = this._drawCount; + } else { + this._selectedItemCount--; + delete this._selectedItems[item._id]; + } + }, + + selectAll: function() { + for (var i = 0, l = this.layers.length; i < l; i++) + this.layers[i].setSelected(true); + }, + + deselectAll: function() { + for (var i in this._selectedItems) + this._selectedItems[i].setSelected(false); + }, + + hitTest: function(point, options) { + point = Point.read(arguments); + options = HitResult.getOptions(Base.read(arguments)); + for (var i = this.layers.length - 1; i >= 0; i--) { + var res = this.layers[i].hitTest(point, options); + if (res) return res; + } + return null; + }, + + importJSON: function(json) { + this.activate(); + return Base.importJSON(json); + }, + + draw: function(ctx, matrix) { + this._drawCount++; + ctx.save(); + matrix.applyToContext(ctx); + var param = Base.merge({ + offset: new Point(0, 0), + transforms: [matrix] + }); + for (var i = 0, l = this.layers.length; i < l; i++) + this.layers[i].draw(ctx, param); + ctx.restore(); + + if (this._selectedItemCount > 0) { + ctx.save(); + ctx.strokeWidth = 1; + for (var id in this._selectedItems) { + var item = this._selectedItems[id]; + if (item._drawCount === this._drawCount + && (item._drawSelected || item._boundsSelected)) { + var color = item.getSelectedColor() + || item.getLayer().getSelectedColor(); + ctx.strokeStyle = ctx.fillStyle = color + ? color.toCanvasStyle(ctx) : '#009dec'; + var mx = item._globalMatrix; + if (item._drawSelected) + item._drawSelected(ctx, mx); + if (item._boundsSelected) { + var coords = mx._transformCorners( + item._getBounds('getBounds')); + ctx.beginPath(); + for (var i = 0; i < 8; i++) + ctx[i === 0 ? 'moveTo' : 'lineTo']( + coords[i], coords[++i]); + ctx.closePath(); + ctx.stroke(); + for (var i = 0; i < 8; i++) { + ctx.beginPath(); + ctx.rect(coords[i] - 2, coords[++i] - 2, 4, 4); + ctx.fill(); + } + } + } + } + ctx.restore(); + } + } +}); + +var Symbol = Base.extend({ + _class: 'Symbol', + + initialize: function Symbol(item, dontCenter) { + this._id = Symbol._id = (Symbol._id || 0) + 1; + this.project = paper.project; + this.project.symbols.push(this); + if (item) + this.setDefinition(item, dontCenter); + this._instances = {}; + }, + + _serialize: function(options, dictionary) { + return dictionary.add(this, function() { + return Base.serialize([this._class, this._definition], + options, false, dictionary); + }); + }, + + _changed: function(flags) { + Base.each(this._instances, function(item) { + item._changed(flags); + }); + }, + + getDefinition: function() { + return this._definition; + }, + + setDefinition: function(item ) { + if (item._parentSymbol) + item = item.clone(); + if (this._definition) + delete this._definition._parentSymbol; + this._definition = item; + item.remove(); + item.setSelected(false); + if (!arguments[1]) + item.setPosition(new Point()); + item._parentSymbol = this; + this._changed(5); + }, + + place: function(position) { + return new PlacedSymbol(this, position); + }, + + clone: function() { + return new Symbol(this._definition.clone()); + } +}); + +var Item = Base.extend(Callback, { + statics: { + extend: function extend(src) { + if (src._serializeFields) + src._serializeFields = Base.merge( + this.prototype._serializeFields, src._serializeFields); + var res = extend.base.apply(this, arguments), + proto = res.prototype, + name = proto._class; + if (name) + proto._type = Base.hyphenate(name); + return res; + } + }, + + _class: 'Item', + _transformContent: true, + _boundsSelected: false, + _serializeFields: { + name: null, + matrix: new Matrix(), + locked: false, + visible: true, + blendMode: 'normal', + opacity: 1, + guide: false, + clipMask: false, + data: {} + }, + + initialize: function Item(point) { + this._id = Item._id = (Item._id || 0) + 1; + if (!this._project) { + var project = paper.project, + layer = project.activeLayer; + if (layer) + layer.addChild(this); + else + this._setProject(project); + } + this._style = new Style(this._project._currentStyle, this); + this._matrix = new Matrix(); + if (point) + this._matrix.translate(point); + }, + + _events: new function() { + + var mouseFlags = { + mousedown: { + mousedown: 1, + mousedrag: 1, + click: 1, + doubleclick: 1 + }, + mouseup: { + mouseup: 1, + mousedrag: 1, + click: 1, + doubleclick: 1 + }, + mousemove: { + mousedrag: 1, + mousemove: 1, + mouseenter: 1, + mouseleave: 1 + } + }; + + var mouseEvent = { + install: function(type) { + var counters = this._project.view._eventCounters; + if (counters) { + for (var key in mouseFlags) { + counters[key] = (counters[key] || 0) + + (mouseFlags[key][type] || 0); + } + } + }, + uninstall: function(type) { + var counters = this._project.view._eventCounters; + if (counters) { + for (var key in mouseFlags) + counters[key] -= mouseFlags[key][type] || 0; + } + } + }; + + return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick', + 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'], + function(name) { + this[name] = mouseEvent; + }, { + onFrame: { + install: function() { + this._project.view._animateItem(this, true); + }, + uninstall: function() { + this._project.view._animateItem(this, false); + } + }, + + onLoad: {} + } + ); + }, + + _serialize: function(options, dictionary) { + var props = {}, + that = this; + + function serialize(fields) { + for (var key in fields) { + var value = that[key]; + if (!Base.equals(value, fields[key])) + props[key] = Base.serialize(value, options, + key !== 'data', dictionary); + } + } + + serialize(this._serializeFields); + if (!(this instanceof Group)) + serialize(this._style._defaults); + return [ this._class, props ]; + }, + + _changed: function(flags) { + if (flags & 4) { + delete this._bounds; + delete this._position; + } + if (this._parent + && (flags & (4 | 8))) { + this._parent._clearBoundsCache(); + } + if (flags & 2) { + this._clearBoundsCache(); + } + if (flags & 1) { + this._project._needsRedraw = true; + } + if (this._parentSymbol) + this._parentSymbol._changed(flags); + if (this._project._changes) { + var entry = this._project._changesById[this._id]; + if (entry) { + entry.flags |= flags; + } else { + entry = { item: this, flags: flags }; + this._project._changesById[this._id] = entry; + this._project._changes.push(entry); + } + } + }, + + set: function(props) { + if (props) + this._set(props); + return this; + }, + + getId: function() { + return this._id; + }, + + getType: function() { + return this._type; + }, + + getName: function() { + return this._name; + }, + + setName: function(name, unique) { + + if (this._name) + this._removeFromNamed(); + if (name && this._parent) { + var children = this._parent._children, + namedChildren = this._parent._namedChildren, + orig = name, + i = 1; + while (unique && children[name]) + name = orig + ' ' + (i++); + (namedChildren[name] = namedChildren[name] || []).push(this); + children[name] = this; + } + this._name = name || undefined; + this._changed(32); + }, + + getStyle: function() { + return this._style; + }, + + setStyle: function(style) { + this.getStyle().set(style); + }, + + hasFill: function() { + return !!this.getStyle().getFillColor(); + }, + + hasStroke: function() { + var style = this.getStyle(); + return !!style.getStrokeColor() && style.getStrokeWidth() > 0; + } +}, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'], + function(name) { + var part = Base.capitalize(name), + name = '_' + name; + this['get' + part] = function() { + return this[name]; + }; + this['set' + part] = function(value) { + if (value != this[name]) { + this[name] = value; + this._changed(name === '_locked' + ? 32 : 33); + } + }; +}, {}), { + + _locked: false, + + _visible: true, + + _blendMode: 'normal', + + _opacity: 1, + + _guide: false, + + isSelected: function() { + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) + if (this._children[i].isSelected()) + return true; + } + return this._selected; + }, + + setSelected: function(selected ) { + if (this._children && !arguments[1]) { + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i].setSelected(selected); + } + if ((selected = !!selected) != this._selected) { + this._selected = selected; + this._project._updateSelection(this); + this._changed(33); + } + }, + + _selected: false, + + isFullySelected: function() { + if (this._children && this._selected) { + for (var i = 0, l = this._children.length; i < l; i++) + if (!this._children[i].isFullySelected()) + return false; + return true; + } + return this._selected; + }, + + setFullySelected: function(selected) { + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i].setFullySelected(selected); + } + this.setSelected(selected, true); + }, + + isClipMask: function() { + return this._clipMask; + }, + + setClipMask: function(clipMask) { + if (this._clipMask != (clipMask = !!clipMask)) { + this._clipMask = clipMask; + if (clipMask) { + this.setFillColor(null); + this.setStrokeColor(null); + } + this._changed(33); + if (this._parent) + this._parent._changed(256); + } + }, + + _clipMask: false, + + getData: function() { + if (!this._data) + this._data = {}; + return this._data; + }, + + setData: function(data) { + this._data = data; + }, + + getPosition: function() { + var pos = this._position + || (this._position = this.getBounds().getCenter(true)); + return new (arguments[0] ? Point : LinkedPoint) + (pos.x, pos.y, this, 'setPosition'); + }, + + setPosition: function() { + this.translate(Point.read(arguments).subtract(this.getPosition(true))); + }, + + getMatrix: function() { + return this._matrix; + }, + + setMatrix: function(matrix) { + this._matrix.initialize(matrix); + this._changed(5); + }, + + isEmpty: function() { + return this._children.length == 0; + } +}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'], + function(name) { + this[name] = function() { + var getter = this._boundsGetter, + bounds = this._getCachedBounds(typeof getter == 'string' + ? getter : getter && getter[name] || name, arguments[0]); + return name === 'getBounds' + ? new LinkedRectangle(bounds.x, bounds.y, bounds.width, + bounds.height, this, 'setBounds') + : bounds; + }; + }, +{ + _getCachedBounds: function(getter, matrix, cacheItem) { + var cache = (!matrix || matrix.equals(this._matrix)) && getter; + if (cacheItem && this._parent) { + var id = cacheItem._id, + ref = this._parent._boundsCache + = this._parent._boundsCache || { + ids: {}, + list: [] + }; + if (!ref.ids[id]) { + ref.list.push(cacheItem); + ref.ids[id] = cacheItem; + } + } + if (cache && this._bounds && this._bounds[cache]) + return this._bounds[cache].clone(); + var identity = this._matrix.isIdentity(); + matrix = !matrix || matrix.isIdentity() + ? identity ? null : this._matrix + : identity ? matrix : matrix.clone().concatenate(this._matrix); + var bounds = this._getBounds(getter, matrix, cache ? this : cacheItem); + if (cache) { + if (!this._bounds) + this._bounds = {}; + this._bounds[cache] = bounds.clone(); + } + return bounds; + }, + + _clearBoundsCache: function() { + if (this._boundsCache) { + for (var i = 0, list = this._boundsCache.list, l = list.length; + i < l; i++) { + var item = list[i]; + delete item._bounds; + if (item != this && item._boundsCache) + item._clearBoundsCache(); + } + delete this._boundsCache; + } + }, + + _getBounds: function(getter, matrix, cacheItem) { + var children = this._children; + if (!children || children.length == 0) + return new Rectangle(); + var x1 = Infinity, + x2 = -x1, + y1 = x1, + y2 = x2; + for (var i = 0, l = children.length; i < l; i++) { + var child = children[i]; + if (child._visible && !child.isEmpty()) { + var rect = child._getCachedBounds(getter, matrix, cacheItem); + x1 = Math.min(rect.x, x1); + y1 = Math.min(rect.y, y1); + x2 = Math.max(rect.x + rect.width, x2); + y2 = Math.max(rect.y + rect.height, y2); + } + } + return isFinite(x1) + ? new Rectangle(x1, y1, x2 - x1, y2 - y1) + : new Rectangle(); + }, + + setBounds: function(rect) { + rect = Rectangle.read(arguments); + var bounds = this.getBounds(), + matrix = new Matrix(), + center = rect.getCenter(); + matrix.translate(center); + if (rect.width != bounds.width || rect.height != bounds.height) { + matrix.scale( + bounds.width != 0 ? rect.width / bounds.width : 1, + bounds.height != 0 ? rect.height / bounds.height : 1); + } + center = bounds.getCenter(); + matrix.translate(-center.x, -center.y); + this.transform(matrix); + } + +}), { + getProject: function() { + return this._project; + }, + + _setProject: function(project) { + if (this._project != project) { + this._project = project; + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) { + this._children[i]._setProject(project); + } + } + } + }, + + getLayer: function() { + var parent = this; + while (parent = parent._parent) { + if (parent instanceof Layer) + return parent; + } + return null; + }, + + getParent: function() { + return this._parent; + }, + + setParent: function(item) { + return item.addChild(this); + }, + + getChildren: function() { + return this._children; + }, + + setChildren: function(items) { + this.removeChildren(); + this.addChildren(items); + }, + + getFirstChild: function() { + return this._children && this._children[0] || null; + }, + + getLastChild: function() { + return this._children && this._children[this._children.length - 1] + || null; + }, + + getNextSibling: function() { + return this._parent && this._parent._children[this._index + 1] || null; + }, + + getPreviousSibling: function() { + return this._parent && this._parent._children[this._index - 1] || null; + }, + + getIndex: function() { + return this._index; + }, + + isInserted: function() { + return this._parent ? this._parent.isInserted() : false; + }, + + clone: function() { + return this._clone(new this.constructor()); + }, + + _clone: function(copy) { + copy.setStyle(this._style); + if (this._children) { + for (var i = 0, l = this._children.length; i < l; i++) + copy.addChild(this._children[i].clone(), true); + } + var keys = ['_locked', '_visible', '_blendMode', '_opacity', + '_clipMask', '_guide']; + for (var i = 0, l = keys.length; i < l; i++) { + var key = keys[i]; + if (this.hasOwnProperty(key)) + copy[key] = this[key]; + } + copy._matrix.initialize(this._matrix); + copy.setSelected(this._selected); + if (this._name) + copy.setName(this._name, true); + return copy; + }, + + copyTo: function(itemOrProject) { + var copy = this.clone(); + if (itemOrProject.layers) { + itemOrProject.activeLayer.addChild(copy); + } else { + itemOrProject.addChild(copy); + } + return copy; + }, + + rasterize: function(resolution) { + var bounds = this.getStrokeBounds(), + scale = (resolution || 72) / 72, + canvas = CanvasProvider.getCanvas(bounds.getSize().multiply(scale)), + ctx = canvas.getContext('2d'), + matrix = new Matrix().scale(scale).translate(-bounds.x, -bounds.y); + ctx.save(); + matrix.applyToContext(ctx); + this.draw(ctx, Base.merge({ transforms: [matrix] })); + var raster = new Raster(canvas); + raster.setBounds(bounds); + ctx.restore(); + return raster; + }, + + contains: function() { + return !!this._contains( + this._matrix._inverseTransform(Point.read(arguments))); + }, + + _contains: function(point) { + if (this._children) { + for (var i = this._children.length - 1; i >= 0; i--) { + if (this._children[i].contains(point)) + return true; + } + return false; + } + return point.isInside(this._getBounds('getBounds')); + }, + + hitTest: function(point, options) { + point = Point.read(arguments); + options = HitResult.getOptions(Base.read(arguments)); + + if (this._locked || !this._visible || this._guide && !options.guides) + return null; + + if (!this._children && !this.getRoughBounds() + .expand(options.tolerance)._containsPoint(point)) + return null; + point = this._matrix._inverseTransform(point); + + var that = this, + res; + function checkBounds(type, part) { + var pt = bounds['get' + part](); + if (point.getDistance(pt) < options.tolerance) + return new HitResult(type, that, + { name: Base.hyphenate(part), point: pt }); + } + + if ((options.center || options.bounds) && + !(this instanceof Layer && !this._parent)) { + var bounds = this._getBounds('getBounds'); + if (options.center) + res = checkBounds('center', 'Center'); + if (!res && options.bounds) { + var points = [ + 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight', + 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter' + ]; + for (var i = 0; i < 8 && !res; i++) + res = checkBounds('bounds', points[i]); + } + } + + if ((res || (res = this._children || !(options.guides && !this._guide + || options.selected && !this._selected) + ? this._hitTest(point, options) : null)) + && res.point) { + res.point = that._matrix.transform(res.point); + } + return res; + }, + + _hitTest: function(point, options) { + if (this._children) { + for (var i = this._children.length - 1, res; i >= 0; i--) + if (res = this._children[i].hitTest(point, options)) + return res; + } else if (this.hasFill() && this._contains(point)) { + return new HitResult('fill', this); + } + }, + + addChild: function(item, _preserve) { + return this.insertChild(undefined, item, _preserve); + }, + + insertChild: function(index, item, _preserve) { + var res = this.insertChildren(index, [item], _preserve); + return res && res[0]; + }, + + addChildren: function(items, _preserve) { + return this.insertChildren(this._children.length, items, _preserve); + }, + + insertChildren: function(index, items, _preserve, _type) { + var children = this._children; + if (children && items && items.length > 0) { + items = Array.prototype.slice.apply(items); + for (var i = items.length - 1; i >= 0; i--) { + var item = items[i]; + if (_type && item._type !== _type) + items.splice(i, 1); + else + item._remove(true); + } + Base.splice(children, items, index, 0); + for (var i = 0, l = items.length; i < l; i++) { + var item = items[i]; + item._parent = this; + item._setProject(this._project); + if (item._name) + item.setName(item._name); + } + this._changed(7); + } else { + items = null; + } + return items; + }, + + insertAbove: function(item, _preserve) { + var index = item._index; + if (item._parent == this._parent && index < this._index) + index++; + return item._parent.insertChild(index, this, _preserve); + }, + + insertBelow: function(item, _preserve) { + var index = item._index; + if (item._parent == this._parent && index > this._index) + index--; + return item._parent.insertChild(index, this, _preserve); + }, + + sendToBack: function() { + return this._parent.insertChild(0, this); + }, + + bringToFront: function() { + return this._parent.addChild(this); + }, + + appendTop: '#addChild', + + appendBottom: function(item) { + return this.insertChild(0, item); + }, + + moveAbove: '#insertAbove', + + moveBelow: '#insertBelow', + + _removeFromNamed: function() { + var children = this._parent._children, + namedChildren = this._parent._namedChildren, + name = this._name, + namedArray = namedChildren[name], + index = namedArray ? namedArray.indexOf(this) : -1; + if (index == -1) + return; + if (children[name] == this) + delete children[name]; + namedArray.splice(index, 1); + if (namedArray.length) { + children[name] = namedArray[namedArray.length - 1]; + } else { + delete namedChildren[name]; + } + }, + + _remove: function(notify) { + if (this._parent) { + if (this._name) + this._removeFromNamed(); + if (this._index != null) + Base.splice(this._parent._children, null, this._index, 1); + if (notify) + this._parent._changed(7); + this._parent = null; + return true; + } + return false; + }, + + remove: function() { + return this._remove(true); + }, + + removeChildren: function(from, to) { + if (!this._children) + return null; + from = from || 0; + to = Base.pick(to, this._children.length); + var removed = Base.splice(this._children, null, from, to - from); + for (var i = removed.length - 1; i >= 0; i--) + removed[i]._remove(false); + if (removed.length > 0) + this._changed(7); + return removed; + }, + + reverseChildren: function() { + if (this._children) { + this._children.reverse(); + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i]._index = i; + this._changed(7); + } + }, + + isEditable: function() { + var item = this; + while (item) { + if (!item._visible || item._locked) + return false; + item = item._parent; + } + return true; + }, + + _getOrder: function(item) { + function getList(item) { + var list = []; + do { + list.unshift(item); + } while (item = item._parent); + return list; + } + var list1 = getList(this), + list2 = getList(item); + for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) { + if (list1[i] != list2[i]) { + return list1[i]._index < list2[i]._index ? 1 : -1; + } + } + return 0; + }, + + hasChildren: function() { + return this._children && this._children.length > 0; + }, + + isAbove: function(item) { + return this._getOrder(item) == -1; + }, + + isBelow: function(item) { + return this._getOrder(item) == 1; + }, + + isParent: function(item) { + return this._parent == item; + }, + + isChild: function(item) { + return item && item._parent == this; + }, + + isDescendant: function(item) { + var parent = this; + while (parent = parent._parent) { + if (parent == item) + return true; + } + return false; + }, + + isAncestor: function(item) { + return item ? item.isDescendant(this) : false; + }, + + isGroupedWith: function(item) { + var parent = this._parent; + while (parent) { + if (parent._parent + && /^(group|layer|compound-path)$/.test(parent._type) + && item.isDescendant(parent)) + return true; + parent = parent._parent; + } + return false; + }, + + scale: function(hor, ver , center) { + if (arguments.length < 2 || typeof ver === 'object') { + center = ver; + ver = hor; + } + return this.transform(new Matrix().scale(hor, ver, + center || this.getPosition(true))); + }, + + translate: function() { + var mx = new Matrix(); + return this.transform(mx.translate.apply(mx, arguments)); + }, + + rotate: function(angle, center) { + return this.transform(new Matrix().rotate(angle, + center || this.getPosition(true))); + }, + + shear: function(hor, ver, center) { + if (arguments.length < 2 || typeof ver === 'object') { + center = ver; + ver = hor; + } + return this.transform(new Matrix().shear(hor, ver, + center || this.getPosition(true))); + }, + + transform: function(matrix ) { + var bounds = this._bounds, + position = this._position; + this._matrix.preConcatenate(matrix); + if (this._transformContent || arguments[1]) + this.applyMatrix(true); + this._changed(5); + if (bounds && matrix.getRotation() % 90 === 0) { + for (var key in bounds) { + var rect = bounds[key]; + matrix._transformBounds(rect, rect); + } + var getter = this._boundsGetter, + rect = bounds[getter && getter.getBounds || getter || 'getBounds']; + if (rect) + this._position = rect.getCenter(true); + this._bounds = bounds; + } else if (position) { + this._position = matrix._transformPoint(position, position); + } + return this; + }, + + _applyMatrix: function(matrix, applyMatrix) { + var children = this._children; + if (children && children.length > 0) { + for (var i = 0, l = children.length; i < l; i++) + children[i].transform(matrix, applyMatrix); + return true; + } + }, + + applyMatrix: function(_dontNotify) { + var matrix = this._matrix; + if (this._applyMatrix(matrix, true)) { + var style = this._style, + fillColor = style.getFillColor(true), + strokeColor = style.getStrokeColor(true); + if (fillColor) + fillColor.transform(matrix); + if (strokeColor) + strokeColor.transform(matrix); + matrix.reset(); + } + if (!_dontNotify) + this._changed(5); + }, + + fitBounds: function(rectangle, fill) { + rectangle = Rectangle.read(arguments); + var bounds = this.getBounds(), + itemRatio = bounds.height / bounds.width, + rectRatio = rectangle.height / rectangle.width, + scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio) + ? rectangle.width / bounds.width + : rectangle.height / bounds.height, + newBounds = new Rectangle(new Point(), + new Size(bounds.width * scale, bounds.height * scale)); + newBounds.setCenter(rectangle.getCenter()); + this.setBounds(newBounds); + }, + + importJSON: function(json) { + return this.addChild(Base.importJSON(json)); + }, + + _setStyles: function(ctx) { + var style = this._style, + width = style.getStrokeWidth(), + join = style.getStrokeJoin(), + cap = style.getStrokeCap(), + limit = style.getMiterLimit(), + fillColor = style.getFillColor(), + strokeColor = style.getStrokeColor(), + dashArray = style.getDashArray(), + dashOffset = style.getDashOffset(); + if (width != null) + ctx.lineWidth = width; + if (join) + ctx.lineJoin = join; + if (cap) + ctx.lineCap = cap; + if (limit) + ctx.miterLimit = limit; + if (fillColor) + ctx.fillStyle = fillColor.toCanvasStyle(ctx); + if (strokeColor) { + ctx.strokeStyle = strokeColor.toCanvasStyle(ctx); + if (paper.support.nativeDash && dashArray && dashArray.length) { + if ('setLineDash' in ctx) { + ctx.setLineDash(dashArray); + ctx.lineDashOffset = dashOffset; + } else { + ctx.mozDash = dashArray; + ctx.mozDashOffset = dashOffset; + } + } + } + }, + + draw: function(ctx, param) { + if (!this._visible || this._opacity == 0) + return; + this._drawCount = this._project._drawCount; + var transforms = param.transforms, + parentMatrix = transforms[transforms.length - 1], + globalMatrix = parentMatrix.clone().concatenate(this._matrix); + transforms.push(this._globalMatrix = globalMatrix); + var blendMode = this._blendMode, + opacity = this._opacity, + nativeBlend = BlendMode.nativeModes[blendMode], + direct = blendMode === 'normal' && opacity === 1 + || (nativeBlend || opacity < 1) && this._canComposite(), + mainCtx, itemOffset, prevOffset; + if (!direct) { + var bounds = this.getStrokeBounds(parentMatrix); + if (!bounds.width || !bounds.height) + return; + prevOffset = param.offset; + itemOffset = param.offset = bounds.getTopLeft().floor(); + mainCtx = ctx; + ctx = CanvasProvider.getContext( + bounds.getSize().ceil().add(new Size(1, 1))); + } + ctx.save(); + if (direct) { + ctx.globalAlpha = opacity; + if (nativeBlend) + ctx.globalCompositeOperation = blendMode; + } else { + ctx.translate(-itemOffset.x, -itemOffset.y); + } + (direct ? this._matrix : globalMatrix).applyToContext(ctx); + if (!direct && param.clipItem) + param.clipItem.draw(ctx, param.extend({ clip: true })); + this._draw(ctx, param); + ctx.restore(); + transforms.pop(); + if (param.clip) + ctx.clip(); + if (!direct) { + BlendMode.process(blendMode, ctx, mainCtx, opacity, + itemOffset.subtract(prevOffset)); + CanvasProvider.release(ctx); + param.offset = prevOffset; + } + }, + + _canComposite: function() { + return false; + } +}, Base.each(['down', 'drag', 'up', 'move'], function(name) { + this['removeOn' + Base.capitalize(name)] = function() { + var hash = {}; + hash[name] = true; + return this.removeOn(hash); + }; +}, { + + removeOn: function(obj) { + for (var name in obj) { + if (obj[name]) { + var key = 'mouse' + name, + project = this._project, + sets = project._removeSets = project._removeSets || {}; + sets[key] = sets[key] || {}; + sets[key][this._id] = this; + } + } + return this; + } +})); + +var Group = Item.extend({ + _class: 'Group', + _serializeFields: { + children: [] + }, + + initialize: function Group(arg) { + Item.call(this); + this._children = []; + this._namedChildren = {}; + if (arg && !this._set(arg)) + this.addChildren(Array.isArray(arg) ? arg : arguments); + }, + + _changed: function _changed(flags) { + _changed.base.call(this, flags); + if (flags & 2 && this._transformContent + && !this._matrix.isIdentity()) { + this.applyMatrix(); + } + if (flags & (2 | 256)) { + delete this._clipItem; + } + }, + + _getClipItem: function() { + if (this._clipItem !== undefined) + return this._clipItem; + for (var i = 0, l = this._children.length; i < l; i++) { + var child = this._children[i]; + if (child._clipMask) + return this._clipItem = child; + } + return this._clipItem = null; + }, + + getTransformContent: function() { + return this._transformContent; + }, + + setTransformContent: function(transform) { + this._transformContent = transform; + if (transform) + this.applyMatrix(); + }, + + isClipped: function() { + return !!this._getClipItem(); + }, + + setClipped: function(clipped) { + var child = this.getFirstChild(); + if (child) + child.setClipMask(clipped); + }, + + _draw: function(ctx, param) { + var clipItem = param.clipItem = this._getClipItem(); + if (clipItem) + clipItem.draw(ctx, param.extend({ clip: true })); + for (var i = 0, l = this._children.length; i < l; i++) { + var item = this._children[i]; + if (item !== clipItem) + item.draw(ctx, param); + } + param.clipItem = null; + } +}); + +var Layer = Group.extend({ + _class: 'Layer', + + initialize: function Layer() { + this._project = paper.project; + this._index = this._project.layers.push(this) - 1; + Group.apply(this, arguments); + this.activate(); + }, + + _remove: function _remove(notify) { + if (this._parent) + return _remove.base.call(this, notify); + if (this._index != null) { + if (this._project.activeLayer === this) + this._project.activeLayer = this.getNextSibling() + || this.getPreviousSibling(); + Base.splice(this._project.layers, null, this._index, 1); + this._project._needsRedraw = true; + return true; + } + return false; + }, + + getNextSibling: function getNextSibling() { + return this._parent ? getNextSibling.base.call(this) + : this._project.layers[this._index + 1] || null; + }, + + getPreviousSibling: function getPreviousSibling() { + return this._parent ? getPreviousSibling.base.call(this) + : this._project.layers[this._index - 1] || null; + }, + + isInserted: function isInserted() { + return this._parent ? isInserted.base.call(this) : this._index != null; + }, + + activate: function() { + this._project.activeLayer = this; + } +}, new function () { + function insert(above) { + return function insert(item) { + if (item instanceof Layer && !item._parent + && this._remove(true)) { + Base.splice(item._project.layers, [this], + item._index + (above ? 1 : 0), 0); + this._setProject(item._project); + return true; + } + return insert.base.call(this, item); + }; + } + + return { + insertAbove: insert(true), + + insertBelow: insert(false) + }; +}); + +var Shape = Item.extend({ + _class: 'Shape', + _transformContent: false, + + initialize: function Shape(type, point, size) { + Item.call(this, point); + this._type = type; + this._size = size; + }, + + _draw: function(ctx, param) { + var style = this._style, + size = this._size, + width = size.width, + height = size.height, + fillColor = style.getFillColor(), + strokeColor = style.getStrokeColor(); + if (fillColor || strokeColor || param.clip) { + ctx.beginPath(); + switch (this._type) { + case 'rect': + ctx.rect(-width / 2, -height / 2, width, height); + break; + case 'circle': + ctx.arc(0, 0, (width + height) / 4, 0, Math.PI * 2, true); + break; + case 'ellipse': + var mx = width / 2, + my = height / 2, + kappa = Numerical.KAPPA, + cx = mx * kappa, + cy = my * kappa; + ctx.moveTo(-mx, 0); + ctx.bezierCurveTo(-mx, -cy, -cx, -my, 0, -my); + ctx.bezierCurveTo(cx, -my, mx, -cy, mx, 0); + ctx.bezierCurveTo(mx, cy, cx, my, 0, my); + ctx.bezierCurveTo(-cx, my, -mx, cy, -mx, 0); + break; + } + } + if (!param.clip && (fillColor || strokeColor)) { + this._setStyles(ctx); + if (fillColor) + ctx.fill(); + if (strokeColor) + ctx.stroke(); + } + }, + + _canComposite: function() { + return !(this.hasFill() && this.hasStroke()); + }, + + _getBounds: function(getter, matrix) { + var rect = new Rectangle(this._size).setCenter(0, 0); + if (getter !== 'getBounds' && this.hasStroke()) + rect = rect.expand(this.getStrokeWidth()); + return matrix ? matrix._transformBounds(rect) : rect; + }, + + _contains: function _contains(point) { + switch (this._type) { + case 'rect': + return _contains.base.call(this, point); + case 'circle': + case 'ellipse': + return point.divide(this._size).getLength() <= 0.5; + } + }, + + _hitTest: function _hitTest(point) { + if (this.hasStroke()) { + var type = this._type, + strokeWidth = this.getStrokeWidth(); + switch (type) { + case 'rect': + var rect = new Rectangle(this._size).setCenter(0, 0), + outer = rect.expand(strokeWidth), + inner = rect.expand(-strokeWidth); + if (outer._containsPoint(point) && !inner._containsPoint(point)) + return new HitResult('stroke', this); + break; + case 'circle': + case 'ellipse': + var size = this._size, + width = size.width, + height = size.height, + radius; + if (type === 'ellipse') { + var angle = point.getAngleInRadians(), + x = width * Math.sin(angle), + y = height * Math.cos(angle); + radius = width * height / (2 * Math.sqrt(x * x + y * y)); + } else { + radius = (width + height) / 4; + } + if (2 * Math.abs(point.getLength() - radius) <= strokeWidth) + return new HitResult('stroke', this); + break; + } + } + return _hitTest.base.apply(this, arguments); + }, + + statics: new function() { + function createShape(type, point, size, args) { + var shape = new Shape(type, point, size), + named = Base.getNamed(args); + if (named) + shape._set(named); + return shape; + } + + return { + Circle: function() { + var center = Point.readNamed(arguments, 'center'), + radius = Base.readNamed(arguments, 'radius'); + return createShape('circle', center, new Size(radius * 2), + arguments); + }, + + Rectangle: function() { + var rect = Rectangle.readNamed(arguments, 'rectangle'); + return createShape('rect', rect.getCenter(true), + rect.getSize(true), arguments); + }, + + Ellipse: function() { + var rect = Rectangle.readNamed(arguments, 'rectangle'); + return createShape('ellipse', rect.getCenter(true), + rect.getSize(true), arguments); + } + }; + } +}); + +var Raster = Item.extend({ + _class: 'Raster', + _transformContent: false, + _boundsGetter: 'getBounds', + _boundsSelected: true, + _serializeFields: { + source: null + }, + + initialize: function Raster(object, position) { + Item.call(this, position !== undefined && Point.read(arguments, 1)); + if (object && !this._set(object)) { + if (object.getContext) { + this.setCanvas(object); + } else if (typeof object === 'string') { + this.setSource(object); + } else { + this.setImage(object); + } + } + if (!this._size) + this._size = new Size(); + }, + + clone: function() { + var element = this._image; + if (!element) { + element = CanvasProvider.getCanvas(this._size); + element.getContext('2d').drawImage(this._canvas, 0, 0); + } + var copy = new Raster(element); + return this._clone(copy); + }, + + getSize: function() { + return this._size; + }, + + setSize: function() { + var size = Size.read(arguments); + if (!this._size.equals(size)) { + var element = this.getElement(); + this.setCanvas(CanvasProvider.getCanvas(size)); + if (element) + this.getContext(true).drawImage(element, 0, 0, + size.width, size.height); + } + }, + + getWidth: function() { + return this._size.width; + }, + + getHeight: function() { + return this._size.height; + }, + + isEmpty: function() { + return this._size.width == 0 && this._size.height == 0; + }, + + getPpi: function() { + var matrix = this._matrix, + orig = new Point(0, 0).transform(matrix), + u = new Point(1, 0).transform(matrix).subtract(orig), + v = new Point(0, 1).transform(matrix).subtract(orig); + return new Size( + 72 / u.getLength(), + 72 / v.getLength() + ); + }, + + getContext: function() { + if (!this._context) + this._context = this.getCanvas().getContext('2d'); + if (arguments[0]) { + this._image = null; + this._changed(129); + } + return this._context; + }, + + setContext: function(context) { + this._context = context; + }, + + getCanvas: function() { + if (!this._canvas) { + var ctx = CanvasProvider.getContext(this._size); + try { + if (this._image) + ctx.drawImage(this._image, 0, 0); + this._canvas = ctx.canvas; + } catch (e) { + CanvasProvider.release(ctx); + } + } + return this._canvas; + }, + + setCanvas: function(canvas) { + if (this._canvas) + CanvasProvider.release(this._canvas); + this._canvas = canvas; + this._size = new Size(canvas.width, canvas.height); + this._image = null; + this._context = null; + this._changed(5 | 129); + }, + + getImage: function() { + return this._image; + }, + + setImage: function(image) { + if (this._canvas) + CanvasProvider.release(this._canvas); + this._image = image; + this._size = new Size(image.naturalWidth, image.naturalHeight); + this._canvas = null; + this._context = null; + this._changed(5); + }, + + getSource: function() { + return this._image && this._image.src || this.toDataURL(); + }, + + setSource: function(src) { + var that = this, + image = document.getElementById(src) || new Image(); + function loaded() { + that.fire('load'); + if (that._project.view) + that._project.view.draw(true); + } + DomEvent.add(image, { + load: function() { + that.setImage(image); + loaded(); + } + }); + if (image.width && image.height) { + setTimeout(loaded, 0); + } else if (!image.src) { + image.src = src; + } + this.setImage(image); + }, + + getElement: function() { + return this._canvas || this._image; + }, + + getSubImage: function(rect) { + rect = Rectangle.read(arguments); + var ctx = CanvasProvider.getContext(rect.getSize()); + ctx.drawImage(this.getCanvas(), rect.x, rect.y, + rect.width, rect.height, 0, 0, rect.width, rect.height); + return ctx.canvas; + }, + + toDataURL: function() { + var src = this._image && this._image.src; + if (/^data:/.test(src)) + return src; + var canvas = this.getCanvas(); + return canvas ? canvas.toDataURL() : null; + }, + + drawImage: function(image, point) { + point = Point.read(arguments, 1); + this.getContext(true).drawImage(image, point.x, point.y); + }, + + getAverageColor: function(object) { + var bounds, path; + if (!object) { + bounds = this.getBounds(); + } else if (object instanceof PathItem) { + path = object; + bounds = object.getBounds(); + } else if (object.width) { + bounds = new Rectangle(object); + } else if (object.x) { + bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1); + } + var sampleSize = 32, + width = Math.min(bounds.width, sampleSize), + height = Math.min(bounds.height, sampleSize); + var ctx = Raster._sampleContext; + if (!ctx) { + ctx = Raster._sampleContext = CanvasProvider.getContext( + new Size(sampleSize)); + } else { + ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1); + } + ctx.save(); + var matrix = new Matrix() + .scale(width / bounds.width, height / bounds.height) + .translate(-bounds.x, -bounds.y); + matrix.applyToContext(ctx); + if (path) + path.draw(ctx, Base.merge({ clip: true, transforms: [matrix] })); + this._matrix.applyToContext(ctx); + ctx.drawImage(this.getElement(), + -this._size.width / 2, -this._size.height / 2); + ctx.restore(); + var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width), + Math.ceil(height)).data, + channels = [0, 0, 0], + total = 0; + for (var i = 0, l = pixels.length; i < l; i += 4) { + var alpha = pixels[i + 3]; + total += alpha; + alpha /= 255; + channels[0] += pixels[i] * alpha; + channels[1] += pixels[i + 1] * alpha; + channels[2] += pixels[i + 2] * alpha; + } + for (var i = 0; i < 3; i++) + channels[i] /= total; + return total ? Color.read(channels) : null; + }, + + getPixel: function(point) { + point = Point.read(arguments); + var data = this.getContext().getImageData(point.x, point.y, 1, 1).data; + return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255], + data[3] / 255); + }, + + setPixel: function() { + var point = Point.read(arguments), + color = Color.read(arguments), + components = color._convert('rgb'), + alpha = color._alpha, + ctx = this.getContext(true), + imageData = ctx.createImageData(1, 1), + data = imageData.data; + data[0] = components[0] * 255; + data[1] = components[1] * 255; + data[2] = components[2] * 255; + data[3] = alpha != null ? alpha * 255 : 255; + ctx.putImageData(imageData, point.x, point.y); + }, + + createImageData: function(size) { + size = Size.read(arguments); + return this.getContext().createImageData(size.width, size.height); + }, + + getImageData: function(rect) { + rect = Rectangle.read(arguments); + if (rect.isEmpty()) + rect = new Rectangle(this.getSize()); + return this.getContext().getImageData(rect.x, rect.y, + rect.width, rect.height); + }, + + setImageData: function(data, point) { + point = Point.read(arguments, 1); + this.getContext(true).putImageData(data, point.x, point.y); + }, + + _getBounds: function(getter, matrix) { + var rect = new Rectangle(this._size).setCenter(0, 0); + return matrix ? matrix._transformBounds(rect) : rect; + }, + + _hitTest: function(point) { + if (this._contains(point)) { + var that = this; + return new HitResult('pixel', that, { + offset: point.add(that._size.divide(2)).round(), + color: { + get: function() { + return that.getPixel(this.offset); + } + } + }); + } + }, + + _draw: function(ctx) { + var element = this.getElement(); + if (element) { + ctx.globalAlpha = this._opacity; + ctx.drawImage(element, + -this._size.width / 2, -this._size.height / 2); + } + }, + + _canComposite: function() { + return true; + } +}); + +var PlacedSymbol = Item.extend({ + _class: 'PlacedSymbol', + _transformContent: false, + _boundsGetter: { getBounds: 'getStrokeBounds' }, + _boundsSelected: true, + _serializeFields: { + symbol: null + }, + + initialize: function PlacedSymbol(arg0, arg1) { + Item.call(this, arg1 !== undefined && Point.read(arguments, 1)); + if (arg0 && !this._set(arg0)) + this.setSymbol(arg0 instanceof Symbol ? arg0 : new Symbol(arg0)); + }, + + getSymbol: function() { + return this._symbol; + }, + + setSymbol: function(symbol) { + if (this._symbol) + delete this._symbol._instances[this._id]; + this._symbol = symbol; + symbol._instances[this._id] = this; + }, + + clone: function() { + return this._clone(new PlacedSymbol(this.symbol)); + }, + + isEmpty: function() { + return this._symbol._definition.isEmpty(); + }, + + _getBounds: function(getter, matrix) { + return this.symbol._definition._getCachedBounds(getter, matrix); + }, + + _hitTest: function(point, options, matrix) { + var result = this._symbol._definition._hitTest(point, options, matrix); + if (result) + result.item = this; + return result; + }, + + _draw: function(ctx, param) { + this.symbol._definition.draw(ctx, param); + } + +}); + +var HitResult = Base.extend({ + _class: 'HitResult', + + initialize: function HitResult(type, item, values) { + this.type = type; + this.item = item; + if (values) { + values.enumerable = true; + this.inject(values); + } + }, + + statics: { + getOptions: function(options) { + return options && options._merged ? options : Base.merge({ + type: null, + tolerance: paper.project.options.hitTolerance || 2, + fill: !options, + stroke: !options, + segments: !options, + handles: false, + ends: false, + center: false, + bounds: false, + guides: false, + selected: false, + _merged: true + }, options); + } + } +}); + +var Segment = Base.extend({ + _class: 'Segment', + + initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) { + var count = arguments.length, + point, handleIn, handleOut; + if (count === 0) { + } else if (count === 1) { + if (arg0.point) { + point = arg0.point; + handleIn = arg0.handleIn; + handleOut = arg0.handleOut; + } else { + point = arg0; + } + } else if (count < 6) { + if (count == 2 && arg1.x === undefined) { + point = [ arg0, arg1 ]; + } else { + point = arg0; + handleIn = arg1; + handleOut = arg2; + } + } else if (count === 6) { + point = [ arg0, arg1 ]; + handleIn = [ arg2, arg3 ]; + handleOut = [ arg4, arg5 ]; + } + this._point = new SegmentPoint(point, this); + this._handleIn = new SegmentPoint(handleIn, this); + this._handleOut = new SegmentPoint(handleOut, this); + }, + + _serialize: function(options) { + return Base.serialize(this.isLinear() ? this._point + : [this._point, this._handleIn, this._handleOut], options, true); + }, + + _changed: function(point) { + if (!this._path) + return; + var curve = this._path._curves && this.getCurve(), + other; + if (curve) { + curve._changed(); + if (other = (curve[point == this._point + || point == this._handleIn && curve._segment1 == this + ? 'getPrevious' : 'getNext']())) { + other._changed(); + } + } + this._path._changed(5); + }, + + getPoint: function() { + return this._point; + }, + + setPoint: function(point) { + point = Point.read(arguments); + this._point.set(point.x, point.y); + }, + + getHandleIn: function() { + return this._handleIn; + }, + + setHandleIn: function(point) { + point = Point.read(arguments); + this._handleIn.set(point.x, point.y); + }, + + getHandleOut: function() { + return this._handleOut; + }, + + setHandleOut: function(point) { + point = Point.read(arguments); + this._handleOut.set(point.x, point.y); + }, + + isLinear: function() { + return this._handleIn.isZero() && this._handleOut.isZero(); + }, + + setLinear: function() { + this._handleIn.set(0, 0); + this._handleOut.set(0, 0); + }, + + _isSelected: function(point) { + var state = this._selectionState; + return point == this._point ? !!(state & 4) + : point == this._handleIn ? !!(state & 1) + : point == this._handleOut ? !!(state & 2) + : false; + }, + + _setSelected: function(point, selected) { + var path = this._path, + selected = !!selected, + state = this._selectionState || 0, + selection = [ + !!(state & 4), + !!(state & 1), + !!(state & 2) + ]; + if (point == this._point) { + if (selected) { + selection[1] = selection[2] = false; + } else { + var previous = this.getPrevious(), + next = this.getNext(); + selection[1] = previous && (previous._point.isSelected() + || previous._handleOut.isSelected()); + selection[2] = next && (next._point.isSelected() + || next._handleIn.isSelected()); + } + selection[0] = selected; + } else { + var index = point == this._handleIn ? 1 : 2; + if (selection[index] != selected) { + if (selected) + selection[0] = false; + selection[index] = selected; + } + } + this._selectionState = (selection[0] ? 4 : 0) + | (selection[1] ? 1 : 0) + | (selection[2] ? 2 : 0); + if (path && state != this._selectionState) { + path._updateSelection(this, state, this._selectionState); + path._changed(33); + } + }, + + isSelected: function() { + return this._isSelected(this._point); + }, + + setSelected: function(selected) { + this._setSelected(this._point, selected); + }, + + getIndex: function() { + return this._index !== undefined ? this._index : null; + }, + + getPath: function() { + return this._path || null; + }, + + getCurve: function() { + var path = this._path, + index = this._index; + if (path) { + if (!path._closed && index == path._segments.length - 1) + index--; + return path.getCurves()[index] || null; + } + return null; + }, + + getLocation: function() { + var curve = this.getCurve(); + return curve ? new CurveLocation(curve, curve.getNext() ? 0 : 1) : null; + }, + + getNext: function() { + var segments = this._path && this._path._segments; + return segments && (segments[this._index + 1] + || this._path._closed && segments[0]) || null; + }, + + getPrevious: function() { + var segments = this._path && this._path._segments; + return segments && (segments[this._index - 1] + || this._path._closed && segments[segments.length - 1]) || null; + }, + + reverse: function() { + return new Segment(this._point, this._handleOut, this._handleIn); + }, + + remove: function() { + return this._path ? !!this._path.removeSegment(this._index) : false; + }, + + clone: function() { + return new Segment(this._point, this._handleIn, this._handleOut); + }, + + equals: function(segment) { + return segment === this || segment + && this._point.equals(segment._point) + && this._handleIn.equals(segment._handleIn) + && this._handleOut.equals(segment._handleOut) + || false; + }, + + toString: function() { + var parts = [ 'point: ' + this._point ]; + if (!this._handleIn.isZero()) + parts.push('handleIn: ' + this._handleIn); + if (!this._handleOut.isZero()) + parts.push('handleOut: ' + this._handleOut); + return '{ ' + parts.join(', ') + ' }'; + }, + + _transformCoordinates: function(matrix, coords, change) { + var point = this._point, + handleIn = !change || !this._handleIn.isZero() + ? this._handleIn : null, + handleOut = !change || !this._handleOut.isZero() + ? this._handleOut : null, + x = point._x, + y = point._y, + i = 2; + coords[0] = x; + coords[1] = y; + if (handleIn) { + coords[i++] = handleIn._x + x; + coords[i++] = handleIn._y + y; + } + if (handleOut) { + coords[i++] = handleOut._x + x; + coords[i++] = handleOut._y + y; + } + if (matrix) { + matrix._transformCoordinates(coords, 0, coords, 0, i / 2); + x = coords[0]; + y = coords[1]; + if (change) { + point._x = x; + point._y = y; + i = 2; + if (handleIn) { + handleIn._x = coords[i++] - x; + handleIn._y = coords[i++] - y; + } + if (handleOut) { + handleOut._x = coords[i++] - x; + handleOut._y = coords[i++] - y; + } + } else { + if (!handleIn) { + coords[i++] = x; + coords[i++] = y; + } + if (!handleOut) { + coords[i++] = x; + coords[i++] = y; + } + } + } + return coords; + } +}); + +var SegmentPoint = Point.extend({ + initialize: function SegmentPoint(point, owner) { + var x, y, selected; + if (!point) { + x = y = 0; + } else if ((x = point[0]) !== undefined) { + y = point[1]; + } else { + if ((x = point.x) === undefined) { + point = Point.read(arguments); + x = point.x; + } + y = point.y; + selected = point.selected; + } + this._x = x; + this._y = y; + this._owner = owner; + if (selected) + this.setSelected(true); + }, + + set: function(x, y) { + this._x = x; + this._y = y; + this._owner._changed(this); + return this; + }, + + getX: function() { + return this._x; + }, + + setX: function(x) { + this._x = x; + this._owner._changed(this); + }, + + getY: function() { + return this._y; + }, + + setY: function(y) { + this._y = y; + this._owner._changed(this); + }, + + isZero: function() { + return Numerical.isZero(this._x) && Numerical.isZero(this._y); + }, + + setSelected: function(selected) { + this._owner._setSelected(this, selected); + }, + + isSelected: function() { + return this._owner._isSelected(this); + } +}); + +var Curve = Base.extend({ + _class: 'Curve', + initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) { + var count = arguments.length; + if (count === 3) { + this._path = arg0; + this._segment1 = arg1; + this._segment2 = arg2; + } else if (count === 0) { + this._segment1 = new Segment(); + this._segment2 = new Segment(); + } else if (count === 1) { + this._segment1 = new Segment(arg0.segment1); + this._segment2 = new Segment(arg0.segment2); + } else if (count === 2) { + this._segment1 = new Segment(arg0); + this._segment2 = new Segment(arg1); + } else { + var point1, handle1, handle2, point2; + if (count === 4) { + point1 = arg0; + handle1 = arg1; + handle2 = arg2; + point2 = arg3; + } else if (count === 8) { + point1 = [arg0, arg1]; + point2 = [arg6, arg7]; + handle1 = [arg2 - arg0, arg3 - arg1]; + handle2 = [arg4 - arg6, arg5 - arg7]; + } + this._segment1 = new Segment(point1, null, handle1); + this._segment2 = new Segment(point2, handle2, null); + } + }, + + _changed: function() { + delete this._length; + delete this._bounds; + }, + + getPoint1: function() { + return this._segment1._point; + }, + + setPoint1: function(point) { + point = Point.read(arguments); + this._segment1._point.set(point.x, point.y); + }, + + getPoint2: function() { + return this._segment2._point; + }, + + setPoint2: function(point) { + point = Point.read(arguments); + this._segment2._point.set(point.x, point.y); + }, + + getHandle1: function() { + return this._segment1._handleOut; + }, + + setHandle1: function(point) { + point = Point.read(arguments); + this._segment1._handleOut.set(point.x, point.y); + }, + + getHandle2: function() { + return this._segment2._handleIn; + }, + + setHandle2: function(point) { + point = Point.read(arguments); + this._segment2._handleIn.set(point.x, point.y); + }, + + getSegment1: function() { + return this._segment1; + }, + + getSegment2: function() { + return this._segment2; + }, + + getPath: function() { + return this._path; + }, + + getIndex: function() { + return this._segment1._index; + }, + + getNext: function() { + var curves = this._path && this._path._curves; + return curves && (curves[this._segment1._index + 1] + || this._path._closed && curves[0]) || null; + }, + + getPrevious: function() { + var curves = this._path && this._path._curves; + return curves && (curves[this._segment1._index - 1] + || this._path._closed && curves[curves.length - 1]) || null; + }, + + isSelected: function() { + return this.getHandle1().isSelected() && this.getHandle2().isSelected(); + }, + + setSelected: function(selected) { + this.getHandle1().setSelected(selected); + this.getHandle2().setSelected(selected); + }, + + getValues: function() { + return Curve.getValues(this._segment1, this._segment2); + }, + + getPoints: function() { + var coords = this.getValues(), + points = []; + for (var i = 0; i < 8; i += 2) + points.push(new Point(coords[i], coords[i + 1])); + return points; + }, + + getLength: function() { + var from = arguments[0], + to = arguments[1], + fullLength = arguments.length === 0 || from === 0 && to === 1; + if (fullLength && this._length != null) + return this._length; + var length = Curve.getLength(this.getValues(), from, to); + if (fullLength) + this._length = length; + return length; + }, + + getArea: function() { + return Curve.getArea(this.getValues()); + }, + + getPart: function(from, to) { + return new Curve(Curve.getPart(this.getValues(), from, to)); + }, + + isLinear: function() { + return this._segment1._handleOut.isZero() + && this._segment2._handleIn.isZero(); + }, + + getIntersections: function(curve) { + return Curve.getIntersections(this.getValues(), curve.getValues(), + this, curve, []); + }, + + reverse: function() { + return new Curve(this._segment2.reverse(), this._segment1.reverse()); + }, + + divide: function(parameter) { + var res = null; + if (parameter && parameter.curve === this) + parameter = parameter.parameter; + if (parameter > 0 && parameter < 1) { + var parts = Curve.subdivide(this.getValues(), parameter), + isLinear = this.isLinear(), + left = parts[0], + right = parts[1]; + + if (!isLinear) { + this._segment1._handleOut.set(left[2] - left[0], + left[3] - left[1]); + this._segment2._handleIn.set(right[4] - right[6], + right[5] - right[7]); + } + + var x = left[6], y = left[7], + segment = new Segment(new Point(x, y), + !isLinear && new Point(left[4] - x, left[5] - y), + !isLinear && new Point(right[2] - x, right[3] - y)); + + if (this._path) { + if (this._segment1._index > 0 && this._segment2._index === 0) { + this._path.add(segment); + } else { + this._path.insert(this._segment2._index, segment); + } + res = this; + } else { + var end = this._segment2; + this._segment2 = segment; + res = new Curve(segment, end); + } + } + return res; + }, + + split: function(parameter) { + return this._path + ? this._path.split(this._segment1._index, parameter) + : null; + }, + + clone: function() { + return new Curve(this._segment1, this._segment2); + }, + + toString: function() { + var parts = [ 'point1: ' + this._segment1._point ]; + if (!this._segment1._handleOut.isZero()) + parts.push('handle1: ' + this._segment1._handleOut); + if (!this._segment2._handleIn.isZero()) + parts.push('handle2: ' + this._segment2._handleIn); + parts.push('point2: ' + this._segment2._point); + return '{ ' + parts.join(', ') + ' }'; + }, + +statics: { + getValues: function(segment1, segment2) { + var p1 = segment1._point, + h1 = segment1._handleOut, + h2 = segment2._handleIn, + p2 = segment2._point; + return [ + p1._x, p1._y, + p1._x + h1._x, p1._y + h1._y, + p2._x + h2._x, p2._y + h2._y, + p2._x, p2._y + ]; + }, + + evaluate: function(v, offset, isParameter, type) { + var t = isParameter ? offset : Curve.getParameterAt(v, offset, 0), + p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7], + x, y; + + if (type === 0 && (t === 0 || t === 1)) { + x = t === 0 ? p1x : p2x; + y = t === 0 ? p1y : p2y; + } else { + var cx = 3 * (c1x - p1x), + bx = 3 * (c2x - c1x) - cx, + ax = p2x - p1x - cx - bx, + + cy = 3 * (c1y - p1y), + by = 3 * (c2y - c1y) - cy, + ay = p2y - p1y - cy - by; + if (type === 0) { + x = ((ax * t + bx) * t + cx) * t + p1x; + y = ((ay * t + by) * t + cy) * t + p1y; + } else { + var tMin = 0.00001; + if (t < tMin && c1x == p1x && c1y == p1y + || t > 1 - tMin && c2x == p2x && c2y == p2y) { + x = c2x - c1x; + y = c2y - c1y; + } else { + x = (3 * ax * t + 2 * bx) * t + cx; + y = (3 * ay * t + 2 * by) * t + cy; + } + if (type === 3) { + var x2 = 6 * ax * t + 2 * bx, + y2 = 6 * ay * t + 2 * by; + return (x * y2 - y * x2) / Math.pow(x * x + y * y, 3 / 2); + } + } + } + return type == 2 ? new Point(y, -x) : new Point(x, y); + }, + + subdivide: function(v, t) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7]; + if (t === undefined) + t = 0.5; + var u = 1 - t, + p3x = u * p1x + t * c1x, p3y = u * p1y + t * c1y, + p4x = u * c1x + t * c2x, p4y = u * c1y + t * c2y, + p5x = u * c2x + t * p2x, p5y = u * c2y + t * p2y, + p6x = u * p3x + t * p4x, p6y = u * p3y + t * p4y, + p7x = u * p4x + t * p5x, p7y = u * p4y + t * p5y, + p8x = u * p6x + t * p7x, p8y = u * p6y + t * p7y; + return [ + [p1x, p1y, p3x, p3y, p6x, p6y, p8x, p8y], + [p8x, p8y, p7x, p7y, p5x, p5y, p2x, p2y] + ]; + }, + + solveCubic: function (v, coord, val, roots) { + var p1 = v[coord], + c1 = v[coord + 2], + c2 = v[coord + 4], + p2 = v[coord + 6], + c = 3 * (c1 - p1), + b = 3 * (c2 - c1) - c, + a = p2 - p1 - c - b; + return Numerical.solveCubic(a, b, c, p1 - val, roots); + }, + + getParameterOf: function(v, x, y) { + if (Math.abs(v[0] - x) < 0.00001 + && Math.abs(v[1] - y) < 0.00001) + return 0; + if (Math.abs(v[6] - x) < 0.00001 + && Math.abs(v[7] - y) < 0.00001) + return 1; + var txs = [], + tys = [], + sx = Curve.solveCubic(v, 0, x, txs), + sy = Curve.solveCubic(v, 1, y, tys), + tx, ty; + for (var cx = 0; sx == -1 || cx < sx;) { + if (sx == -1 || (tx = txs[cx++]) >= 0 && tx <= 1) { + for (var cy = 0; sy == -1 || cy < sy;) { + if (sy == -1 || (ty = tys[cy++]) >= 0 && ty <= 1) { + if (sx == -1) tx = ty; + else if (sy == -1) ty = tx; + if (Math.abs(tx - ty) < 0.00001) + return (tx + ty) * 0.5; + } + } + if (sx == -1) + break; + } + } + return null; + }, + + getPart: function(v, from, to) { + if (from > 0) + v = Curve.subdivide(v, from)[1]; + if (to < 1) + v = Curve.subdivide(v, (to - from) / (1 - from))[0]; + return v; + }, + + isLinear: function(v) { + return v[0] === v[2] && v[1] === v[3] && v[4] === v[6] && v[5] === v[7]; + }, + + isFlatEnough: function(v, tolerance) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7], + ux = 3 * c1x - 2 * p1x - p2x, + uy = 3 * c1y - 2 * p1y - p2y, + vx = 3 * c2x - 2 * p2x - p1x, + vy = 3 * c2y - 2 * p2y - p1y; + return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy) + < 10 * tolerance * tolerance; + }, + + getArea: function(v) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7]; + return ( 3.0 * c1y * p1x - 1.5 * c1y * c2x + - 1.5 * c1y * p2x - 3.0 * p1y * c1x + - 1.5 * p1y * c2x - 0.5 * p1y * p2x + + 1.5 * c2y * p1x + 1.5 * c2y * c1x + - 3.0 * c2y * p2x + 0.5 * p2y * p1x + + 1.5 * p2y * c1x + 3.0 * p2y * c2x) / 10; + }, + + getBounds: function(v) { + var min = v.slice(0, 2), + max = min.slice(), + roots = [0, 0]; + for (var i = 0; i < 2; i++) + Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6], + i, 0, min, max, roots); + return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]); + }, + + _getCrossings: function(v, prev, x, y, roots) { + var count = Curve.solveCubic(v, 1, y, roots), + crossings = 0, + tolerance = 0.00001, + abs = Math.abs; + + function changesOrientation(tangent) { + return Curve.evaluate(prev, 1, true, 1).y + * tangent.y > 0; + } + + if (count === -1) { + roots[0] = Curve.getParameterOf(v, x, y); + count = roots[0] !== null ? 1 : 0; + } + for (var i = 0; i < count; i++) { + var t = roots[i]; + if (t > -tolerance && t < 1 - tolerance) { + var pt = Curve.evaluate(v, t, true, 0); + if (x < pt.x + tolerance) { + var tan = Curve.evaluate(v, t, true, 1); + if (abs(pt.x - x) < tolerance) { + var angle = tan.getAngle(); + if (angle > -180 && angle < 0 + && (t > tolerance || changesOrientation(tan))) + continue; + } else { + if (abs(tan.y) < tolerance + || t < tolerance && !changesOrientation(tan)) + continue; + } + crossings++; + } + } + } + return crossings; + }, + + _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) { + function add(value, padding) { + var left = value - padding, + right = value + padding; + if (left < min[coord]) + min[coord] = left; + if (right > max[coord]) + max[coord] = right; + } + var a = 3 * (v1 - v2) - v0 + v3, + b = 2 * (v0 + v2) - 4 * v1, + c = v1 - v0, + count = Numerical.solveQuadratic(a, b, c, roots), + tMin = 0.00001, + tMax = 1 - tMin; + add(v3, 0); + for (var i = 0; i < count; i++) { + var t = roots[i], + u = 1 - t; + if (tMin < t && t < tMax) + add(u * u * u * v0 + + 3 * u * u * t * v1 + + 3 * u * t * t * v2 + + t * t * t * v3, + padding); + } + } +}}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'], + function(name) { + this[name] = function() { + if (!this._bounds) + this._bounds = {}; + var bounds = this._bounds[name]; + if (!bounds) { + bounds = this._bounds[name] = Path[name]([this._segment1, + this._segment2], false, this._path.getStyle()); + } + return bounds.clone(); + }; + }, +{ + +}), Base.each(['getPoint', 'getTangent', 'getNormal', 'getCurvatureAt'], + function(name, index) { + this[name + 'At'] = function(offset, isParameter) { + return Curve.evaluate(this.getValues(), offset, isParameter, index); + }; + this[name] = function(parameter) { + return Curve.evaluate(this.getValues(), parameter, true, index); + }; + }, +{ + getParameterAt: function(offset, start) { + return Curve.getParameterAt(this.getValues(), offset, + start !== undefined ? start : offset < 0 ? 1 : 0); + }, + + getParameterOf: function(point) { + point = Point.read(arguments); + return Curve.getParameterOf(this.getValues(), point.x, point.y); + }, + + getLocationAt: function(offset, isParameter) { + if (!isParameter) + offset = this.getParameterAt(offset); + return new CurveLocation(this, offset); + }, + + getLocationOf: function(point) { + point = Point.read(arguments); + var t = this.getParameterOf(point); + return t != null ? new CurveLocation(this, t) : null; + }, + + getNearestLocation: function(point) { + point = Point.read(arguments); + var values = this.getValues(), + count = 100, + tolerance = Numerical.TOLERANCE, + minDist = Infinity, + minT = 0; + + function refine(t) { + if (t >= 0 && t <= 1) { + var dist = point.getDistance( + Curve.evaluate(values, t, true, 0), true); + if (dist < minDist) { + minDist = dist; + minT = t; + return true; + } + } + } + + for (var i = 0; i <= count; i++) + refine(i / count); + + var step = 1 / (count * 2); + while (step > tolerance) { + if (!refine(minT - step) && !refine(minT + step)) + step /= 2; + } + var pt = Curve.evaluate(values, minT, true, 0); + return new CurveLocation(this, minT, pt, null, null, null, + point.getDistance(pt)); + }, + + getNearestPoint: function(point) { + point = Point.read(arguments); + return this.getNearestLocation(point).getPoint(); + } + +}), +new function() { + + function getLengthIntegrand(v) { + var p1x = v[0], p1y = v[1], + c1x = v[2], c1y = v[3], + c2x = v[4], c2y = v[5], + p2x = v[6], p2y = v[7], + + ax = 9 * (c1x - c2x) + 3 * (p2x - p1x), + bx = 6 * (p1x + c2x) - 12 * c1x, + cx = 3 * (c1x - p1x), + + ay = 9 * (c1y - c2y) + 3 * (p2y - p1y), + by = 6 * (p1y + c2y) - 12 * c1y, + cy = 3 * (c1y - p1y); + + return function(t) { + var dx = (ax * t + bx) * t + cx, + dy = (ay * t + by) * t + cy; + return Math.sqrt(dx * dx + dy * dy); + }; + } + + function getIterations(a, b) { + return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32))); + } + + return { + statics: true, + + getLength: function(v, a, b) { + if (a === undefined) + a = 0; + if (b === undefined) + b = 1; + if (v[0] == v[2] && v[1] == v[3] && v[6] == v[4] && v[7] == v[5]) { + var dx = v[6] - v[0], + dy = v[7] - v[1]; + return (b - a) * Math.sqrt(dx * dx + dy * dy); + } + var ds = getLengthIntegrand(v); + return Numerical.integrate(ds, a, b, getIterations(a, b)); + }, + + getParameterAt: function(v, offset, start) { + if (offset === 0) + return start; + var forward = offset > 0, + a = forward ? start : 0, + b = forward ? 1 : start, + offset = Math.abs(offset), + ds = getLengthIntegrand(v), + rangeLength = Numerical.integrate(ds, a, b, + getIterations(a, b)); + if (offset >= rangeLength) + return forward ? b : a; + var guess = offset / rangeLength, + length = 0; + function f(t) { + var count = getIterations(start, t); + length += start < t + ? Numerical.integrate(ds, start, t, count) + : -Numerical.integrate(ds, t, start, count); + start = t; + return length - offset; + } + return Numerical.findRoot(f, ds, + forward ? a + guess : b - guess, + a, b, 16, 0.00001); + } + }; +}, new function() { + function addLocation(locations, curve1, t1, point1, curve2, t2, point2) { + var first = locations[0], + last = locations[locations.length - 1]; + if ((!first || !point1.equals(first._point)) + && (!last || !point1.equals(last._point))) + locations.push( + new CurveLocation(curve1, t1, point1, curve2, t2, point2)); + } + + function addCurveIntersections(v1, v2, curve1, curve2, locations, + range1, range2, recursion) { + recursion = (recursion || 0) + 1; + if (recursion > 20) + return; + range1 = range1 || [ 0, 1 ]; + range2 = range2 || [ 0, 1 ]; + var part1 = Curve.getPart(v1, range1[0], range1[1]), + part2 = Curve.getPart(v2, range2[0], range2[1]), + iteration = 0; + while (iteration++ < 20) { + var range, + intersects1 = clipFatLine(part1, part2, range = range2.slice()), + intersects2 = 0; + if (intersects1 === 0) + break; + if (intersects1 > 0) { + range2 = range; + part2 = Curve.getPart(v2, range2[0], range2[1]); + intersects2 = clipFatLine(part2, part1, range = range1.slice()); + if (intersects2 === 0) + break; + if (intersects1 > 0) { + range1 = range; + part1 = Curve.getPart(v1, range1[0], range1[1]); + } + } + if (intersects1 < 0 || intersects2 < 0) { + if (range1[1] - range1[0] > range2[1] - range2[0]) { + var t = (range1[0] + range1[1]) / 2; + addCurveIntersections(v1, v2, curve1, curve2, locations, + [ range1[0], t ], range2, recursion); + addCurveIntersections(v1, v2, curve1, curve2, locations, + [ t, range1[1] ], range2, recursion); + break; + } else { + var t = (range2[0] + range2[1]) / 2; + addCurveIntersections(v1, v2, curve1, curve2, locations, + range1, [ range2[0], t ], recursion); + addCurveIntersections(v1, v2, curve1, curve2, locations, + range1, [ t, range2[1] ], recursion); + break; + } + } + if (Math.abs(range1[1] - range1[0]) <= 0.00001 && + Math.abs(range2[1] - range2[0]) <= 0.00001) { + var t1 = (range1[0] + range1[1]) / 2, + t2 = (range2[0] + range2[1]) / 2; + addLocation(locations, + curve1, t1, Curve.evaluate(v1, t1, true, 0), + curve2, t2, Curve.evaluate(v2, t2, true, 0)); + break; + } + } + } + + function clipFatLine(v1, v2, range2) { + var p0x = v1[0], p0y = v1[1], p1x = v1[2], p1y = v1[3], + p2x = v1[4], p2y = v1[5], p3x = v1[6], p3y = v1[7], + q0x = v2[0], q0y = v2[1], q1x = v2[2], q1y = v2[3], + q2x = v2[4], q2y = v2[5], q3x = v2[6], q3y = v2[7], + getSignedDistance = Line.getSignedDistance, + d1 = getSignedDistance(p0x, p0y, p3x, p3y, p1x, p1y) || 0, + d2 = getSignedDistance(p0x, p0y, p3x, p3y, p2x, p2y) || 0, + factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9, + dmin = factor * Math.min(0, d1, d2), + dmax = factor * Math.max(0, d1, d2), + dq0 = getSignedDistance(p0x, p0y, p3x, p3y, q0x, q0y), + dq1 = getSignedDistance(p0x, p0y, p3x, p3y, q1x, q1y), + dq2 = getSignedDistance(p0x, p0y, p3x, p3y, q2x, q2y), + dq3 = getSignedDistance(p0x, p0y, p3x, p3y, q3x, q3y); + if (dmin > Math.max(dq0, dq1, dq2, dq3) + || dmax < Math.min(dq0, dq1, dq2, dq3)) + return 0; + var hull = getConvexHull(dq0, dq1, dq2, dq3), + swap; + if (dq3 < dq0) { + swap = dmin; + dmin = dmax; + dmax = swap; + } + var tmaxdmin = -Infinity, + tmin = Infinity, + tmax = -Infinity; + for (var i = 0, l = hull.length; i < l; i++) { + var p1 = hull[i], + p2 = hull[(i + 1) % l]; + if (p2[1] < p1[1]) { + swap = p2; + p2 = p1; + p1 = swap; + } + var x1 = p1[0], + y1 = p1[1], + x2 = p2[0], + y2 = p2[1]; + var inv = (y2 - y1) / (x2 - x1); + if (dmin >= y1 && dmin <= y2) { + var ixdx = x1 + (dmin - y1) / inv; + if (ixdx < tmin) + tmin = ixdx; + if (ixdx > tmaxdmin) + tmaxdmin = ixdx; + } + if (dmax >= y1 && dmax <= y2) { + var ixdx = x1 + (dmax - y1) / inv; + if (ixdx > tmax) + tmax = ixdx; + if (ixdx < tmin) + tmin = 0; + } + } + if (tmin !== Infinity && tmax !== -Infinity) { + var min = Math.min(dmin, dmax), + max = Math.max(dmin, dmax); + if (dq3 > min && dq3 < max) + tmax = 1; + if (dq0 > min && dq0 < max) + tmin = 0; + if (tmaxdmin > tmax) + tmax = 1; + var v2tmin = range2[0], + tdiff = range2[1] - v2tmin; + range2[0] = v2tmin + tmin * tdiff; + range2[1] = v2tmin + tmax * tdiff; + if ((tdiff - (range2[1] - range2[0])) / tdiff >= 0.2) + return 1; + } + if (Curve.getBounds(v1).touches(Curve.getBounds(v2))) + return -1; + return 0; + } + + function getConvexHull(dq0, dq1, dq2, dq3) { + var p0 = [ 0, dq0 ], + p1 = [ 1 / 3, dq1 ], + p2 = [ 2 / 3, dq2 ], + p3 = [ 1, dq3 ], + getSignedDistance = Line.getSignedDistance, + dist1 = getSignedDistance(0, dq0, 1, dq3, 1 / 3, dq1), + dist2 = getSignedDistance(0, dq0, 1, dq3, 2 / 3, dq2); + if (dist1 * dist2 < 0) { + return [ p0, p1, p3, p2 ]; + } + var pmax, cross; + if (Math.abs(dist1) > Math.abs(dist2)) { + pmax = p1; + cross = (dq3 - dq2 - (dq3 - dq0) / 3) + * (2 * (dq3 - dq2) - dq3 + dq1) / 3; + } else { + pmax = p2; + cross = (dq1 - dq0 + (dq0 - dq3) / 3) + * (-2 * (dq0 - dq1) + dq0 - dq2) / 3; + } + return cross < 0 + ? [ p0, pmax, p3 ] + : [ p0, p1, p2, p3 ]; + } + + function addCurveLineIntersections(v1, v2, curve1, curve2, locations) { + var flip = Curve.isLinear(v1), + vc = flip ? v2 : v1, + vl = flip ? v1 : v2, + l1x = vl[0], l1y = vl[1], + l2x = vl[6], l2y = vl[7], + lvx = l2x - l1x, + lvy = l2y - l1y, + angle = Math.atan2(-lvy, lvx), + sin = Math.sin(angle), + cos = Math.cos(angle), + rl2x = lvx * cos - lvy * sin, + vcr = []; + + for(var i = 0; i < 8; i += 2) { + var x = vc[i] - l1x, + y = vc[i + 1] - l1y; + vcr.push( + x * cos - y * sin, + y * cos + x * sin); + } + var roots = [], + count = Curve.solveCubic(vcr, 1, 0, roots); + for (var i = 0; i < count; i++) { + var t = roots[i]; + if (t >= 0 && t <= 1) { + var point = Curve.evaluate(vcr, t, true, 0); + if (point.x >= 0 && point.x <= rl2x) + addLocation(locations, + flip ? curve2 : curve1, + t, Curve.evaluate(vc, t, true, 0), + flip ? curve1 : curve2); + } + } + } + + function addLineIntersection(v1, v2, curve1, curve2, locations) { + var point = Line.intersect( + v1[0], v1[1], v1[6], v1[7], + v2[0], v2[1], v2[6], v2[7]); + if (point) + addLocation(locations, curve1, null, point, curve2); + } + + return { statics: { + getIntersections: function(v1, v2, curve1, curve2, locations) { + var linear1 = Curve.isLinear(v1), + linear2 = Curve.isLinear(v2); + (linear1 && linear2 + ? addLineIntersection + : linear1 || linear2 + ? addCurveLineIntersections + : addCurveIntersections)(v1, v2, curve1, curve2, locations); + return locations; + } + }}; +}); + +var CurveLocation = Base.extend({ + _class: 'CurveLocation', + initialize: function CurveLocation(curve, parameter, point, _curve2, + _parameter2, _point2, _distance) { + this._id = CurveLocation._id = (CurveLocation._id || 0) + 1; + this._curve = curve; + this._segment1 = curve._segment1; + this._segment2 = curve._segment2; + this._parameter = parameter; + this._point = point; + this._curve2 = _curve2; + this._parameter2 = _parameter2; + this._point2 = _point2; + this._distance = _distance; + }, + + getSegment: function() { + if (!this._segment) { + var curve = this.getCurve(), + parameter = this.getParameter(); + if (parameter === 1) { + this._segment = curve._segment2; + } else if (parameter === 0 || arguments[0]) { + this._segment = curve._segment1; + } else if (parameter == null) { + return null; + } else { + this._segment = curve.getLength(0, parameter) + < curve.getLength(parameter, 1) + ? curve._segment1 + : curve._segment2; + } + } + return this._segment; + }, + + getCurve: function() { + if (!this._curve || arguments[0]) { + this._curve = this._segment1.getCurve(); + if (this._curve.getParameterOf(this._point) == null) + this._curve = this._segment2.getPrevious().getCurve(); + } + return this._curve; + }, + + getIntersection: function() { + var intersection = this._intersection; + if (!intersection && this._curve2) { + var param = this._parameter2; + this._intersection = intersection = new CurveLocation( + this._curve2, param, this._point2 || this._point, this); + intersection._intersection = this; + } + return intersection; + }, + + getPath: function() { + var curve = this.getCurve(); + return curve && curve._path; + }, + + getIndex: function() { + var curve = this.getCurve(); + return curve && curve.getIndex(); + }, + + getOffset: function() { + var path = this.getPath(); + return path && path._getOffset(this); + }, + + getCurveOffset: function() { + var curve = this.getCurve(), + parameter = this.getParameter(); + return parameter != null && curve && curve.getLength(0, parameter); + }, + + getParameter: function() { + if ((this._parameter == null || arguments[0]) && this._point) { + var curve = this.getCurve(arguments[0] && this._point); + this._parameter = curve && curve.getParameterOf(this._point); + } + return this._parameter; + }, + + getPoint: function() { + if ((!this._point || arguments[0]) && this._parameter != null) { + var curve = this.getCurve(); + this._point = curve && curve.getPointAt(this._parameter, true); + } + return this._point; + }, + + getTangent: function() { + var parameter = this.getParameter(), + curve = this.getCurve(); + return parameter != null && curve && curve.getTangentAt(parameter, true); + }, + + getNormal: function() { + var parameter = this.getParameter(), + curve = this.getCurve(); + return parameter != null && curve && curve.getNormalAt(parameter, true); + }, + + getDistance: function() { + return this._distance; + }, + + divide: function() { + var curve = this.getCurve(true); + return curve && curve.divide(this.getParameter(true)); + }, + + split: function() { + var curve = this.getCurve(true); + return curve && curve.split(this.getParameter(true)); + }, + + toString: function() { + var parts = [], + point = this.getPoint(), + f = Formatter.instance; + if (point) + parts.push('point: ' + point); + var index = this.getIndex(); + if (index != null) + parts.push('index: ' + index); + var parameter = this.getParameter(); + if (parameter != null) + parts.push('parameter: ' + f.number(parameter)); + if (this._distance != null) + parts.push('distance: ' + f.number(this._distance)); + return '{ ' + parts.join(', ') + ' }'; + } +}); + +var PathItem = Item.extend({ + _class: 'PathItem', + + initialize: function PathItem() { + Item.apply(this, arguments); + }, + + getIntersections: function(path) { + if (!this.getBounds().touches(path.getBounds())) + return []; + var locations = [], + curves1 = this.getCurves(), + curves2 = path.getCurves(), + length2 = curves2.length, + values2 = []; + for (var i = 0; i < length2; i++) + values2[i] = curves2[i].getValues(); + for (var i = 0, l = curves1.length; i < l; i++) { + var curve1 = curves1[i], + values1 = curve1.getValues(); + for (var j = 0; j < length2; j++) + Curve.getIntersections(values1, values2[j], curve1, curves2[j], + locations); + } + return locations; + }, + + setPathData: function(data) { + + var parts = data.match(/[a-z][^a-z]*/ig), + coords, + relative = false, + control, + current = new Point(); + + function getCoord(index, coord, update) { + var val = parseFloat(coords[index]); + if (relative) + val += current[coord]; + if (update) + current[coord] = val; + return val; + } + + function getPoint(index, update) { + return new Point( + getCoord(index, 'x', update), + getCoord(index + 1, 'y', update) + ); + } + + if (this._type === 'path') + this.removeSegments(); + else + this.removeChildren(); + + for (var i = 0, l = parts.length; i < l; i++) { + var part = parts[i], + cmd = part[0], + lower = cmd.toLowerCase(); + coords = part.slice(1).trim().split(/[\s,]+|(?=[+-])/); + relative = cmd === lower; + var length = coords.length; + switch (lower) { + case 'm': + case 'l': + for (var j = 0; j < length; j += 2) + this[j === 0 && lower === 'm' ? 'moveTo' : 'lineTo']( + getPoint(j, true)); + break; + case 'h': + case 'v': + var coord = lower == 'h' ? 'x' : 'y'; + for (var j = 0; j < length; j++) { + getCoord(j, coord, true); + this.lineTo(current); + } + break; + case 'c': + for (var j = 0; j < length; j += 6) { + this.cubicCurveTo( + getPoint(j), + control = getPoint(j + 2), + getPoint(j + 4, true)); + } + break; + case 's': + for (var j = 0; j < length; j += 4) { + this.cubicCurveTo( + current.multiply(2).subtract(control), + control = getPoint(j), + getPoint(j + 2, true)); + } + break; + case 'q': + for (var j = 0; j < length; j += 4) { + this.quadraticCurveTo( + control = getPoint(j), + getPoint(j + 2, true)); + } + break; + case 't': + for (var j = 0; j < length; j += 2) { + this.quadraticCurveTo( + control = current.multiply(2).subtract(control), + getPoint(j, true)); + } + break; + case 'a': + break; + case 'z': + this.closePath(); + break; + } + } + }, + + _canComposite: function() { + return !(this.hasFill() && this.hasStroke()); + } + +}); + +var Path = PathItem.extend({ + _class: 'Path', + _serializeFields: { + segments: [], + closed: false + }, + + initialize: function Path(arg) { + this._closed = false; + this._segments = []; + Item.call(this); + var segments = Array.isArray(arg) + ? typeof arg[0] === 'object' + ? arg + : arguments + : arg && (arg.point !== undefined || arg.x !== undefined) + ? arguments + : null; + this.setSegments(segments || []); + if (arg && !segments) + this._set(arg); + }, + + clone: function() { + var copy = this._clone(new Path(this._segments)); + copy._closed = this._closed; + if (this._clockwise !== undefined) + copy._clockwise = this._clockwise; + return copy; + }, + + _changed: function(flags) { + Item.prototype._changed.call(this, flags); + if (flags & 4) { + delete this._length; + delete this._clockwise; + if (this._curves) { + for (var i = 0, l = this._curves.length; i < l; i++) { + this._curves[i]._changed(5); + } + } + } else if (flags & 8) { + delete this._bounds; + } + }, + + getSegments: function() { + return this._segments; + }, + + setSegments: function(segments) { + this._selectedSegmentState = 0; + this._segments.length = 0; + delete this._curves; + this._add(Segment.readAll(segments)); + }, + + getFirstSegment: function() { + return this._segments[0]; + }, + + getLastSegment: function() { + return this._segments[this._segments.length - 1]; + }, + + getCurves: function() { + var curves = this._curves, + segments = this._segments; + if (!curves) { + var length = this._countCurves(); + curves = this._curves = new Array(length); + for (var i = 0; i < length; i++) + curves[i] = new Curve(this, segments[i], + segments[i + 1] || segments[0]); + } + return curves; + }, + + getFirstCurve: function() { + return this.getCurves()[0]; + }, + + getLastCurve: function() { + var curves = this.getCurves(); + return curves[curves.length - 1]; + }, + + getPathData: function() { + var segments = this._segments, + precision = arguments[0], + f = Formatter.instance, + parts = []; + + function addCurve(seg1, seg2, skipLine) { + var point1 = seg1._point, + point2 = seg2._point, + handle1 = seg1._handleOut, + handle2 = seg2._handleIn; + if (handle1.isZero() && handle2.isZero()) { + if (!skipLine) { + parts.push('L' + f.point(point2, precision)); + } + } else { + var end = point2.subtract(point1); + parts.push('c' + f.point(handle1, precision) + + ' ' + f.point(end.add(handle2), precision) + + ' ' + f.point(end, precision)); + } + } + + if (segments.length === 0) + return ''; + parts.push('M' + f.point(segments[0]._point)); + for (var i = 0, l = segments.length - 1; i < l; i++) + addCurve(segments[i], segments[i + 1], false); + if (this._closed) { + addCurve(segments[segments.length - 1], segments[0], true); + parts.push('z'); + } + return parts.join(''); + }, + + isClosed: function() { + return this._closed; + }, + + setClosed: function(closed) { + if (this._closed != (closed = !!closed)) { + this._closed = closed; + if (this._curves) { + var length = this._curves.length = this._countCurves(); + if (closed) + this._curves[length - 1] = new Curve(this, + this._segments[length - 1], this._segments[0]); + } + this._changed(5); + } + }, + + isEmpty: function() { + return this._segments.length === 0; + }, + + isPolygon: function() { + for (var i = 0, l = this._segments.length; i < l; i++) { + if (!this._segments[i].isLinear()) + return false; + } + return true; + }, + + _applyMatrix: function(matrix) { + var coords = new Array(6); + for (var i = 0, l = this._segments.length; i < l; i++) + this._segments[i]._transformCoordinates(matrix, coords, true); + return true; + }, + + _add: function(segs, index) { + var segments = this._segments, + curves = this._curves, + amount = segs.length, + append = index == null, + index = append ? segments.length : index, + fullySelected = this.isFullySelected(); + for (var i = 0; i < amount; i++) { + var segment = segs[i]; + if (segment._path) + segment = segs[i] = segment.clone(); + segment._path = this; + segment._index = index + i; + if (fullySelected) + segment._selectionState = 4; + if (segment._selectionState) + this._updateSelection(segment, 0, segment._selectionState); + } + if (append) { + segments.push.apply(segments, segs); + } else { + segments.splice.apply(segments, [index, 0].concat(segs)); + for (var i = index + amount, l = segments.length; i < l; i++) + segments[i]._index = i; + } + if (curves || segs._curves) { + if (!curves) + curves = this._curves = []; + var from = index > 0 ? index - 1 : index, + start = from, + to = Math.min(from + amount, this._countCurves()); + if (segs._curves) { + curves.splice.apply(curves, [from, 0].concat(segs._curves)); + start += segs._curves.length; + } + for (var i = start; i < to; i++) + curves.splice(i, 0, new Curve(this, null, null)); + this._adjustCurves(from, to); + } + this._changed(5); + return segs; + }, + + _adjustCurves: function(from, to) { + var segments = this._segments, + curves = this._curves, + curve; + for (var i = from; i < to; i++) { + curve = curves[i]; + curve._path = this; + curve._segment1 = segments[i]; + curve._segment2 = segments[i + 1] || segments[0]; + } + if (curve = curves[this._closed && from === 0 ? segments.length - 1 + : from - 1]) + curve._segment2 = segments[from] || segments[0]; + if (curve = curves[to]) + curve._segment1 = segments[to]; + }, + + _countCurves: function() { + var length = this._segments.length; + return !this._closed && length > 0 ? length - 1 : length; + }, + + add: function(segment1 ) { + return arguments.length > 1 && typeof segment1 !== 'number' + ? this._add(Segment.readAll(arguments)) + : this._add([ Segment.read(arguments) ])[0]; + }, + + insert: function(index, segment1 ) { + return arguments.length > 2 && typeof segment1 !== 'number' + ? this._add(Segment.readAll(arguments, 1), index) + : this._add([ Segment.read(arguments, 1) ], index)[0]; + }, + + addSegment: function() { + return this._add([ Segment.read(arguments) ])[0]; + }, + + insertSegment: function(index ) { + return this._add([ Segment.read(arguments, 1) ], index)[0]; + }, + + addSegments: function(segments) { + return this._add(Segment.readAll(segments)); + }, + + insertSegments: function(index, segments) { + return this._add(Segment.readAll(segments), index); + }, + + removeSegment: function(index) { + return this.removeSegments(index, index + 1)[0] || null; + }, + + removeSegments: function(from, to) { + from = from || 0; + to = Base.pick(to, this._segments.length); + var segments = this._segments, + curves = this._curves, + count = segments.length, + removed = segments.splice(from, to - from), + amount = removed.length; + if (!amount) + return removed; + for (var i = 0; i < amount; i++) { + var segment = removed[i]; + if (segment._selectionState) + this._updateSelection(segment, segment._selectionState, 0); + delete segment._index; + delete segment._path; + } + for (var i = from, l = segments.length; i < l; i++) + segments[i]._index = i; + if (curves) { + var index = from > 0 && to === count + (this._closed ? 1 : 0) + ? from - 1 + : from, + curves = curves.splice(index, amount); + if (arguments[2]) + removed._curves = curves.slice(1); + this._adjustCurves(index, index); + } + this._changed(5); + return removed; + }, + + isFullySelected: function() { + return this._selected && this._selectedSegmentState + == this._segments.length * 4; + }, + + setFullySelected: function(selected) { + if (selected) + this._selectSegments(true); + this.setSelected(selected); + }, + + setSelected: function setSelected(selected) { + if (!selected) + this._selectSegments(false); + setSelected.base.call(this, selected); + }, + + _selectSegments: function(selected) { + var length = this._segments.length; + this._selectedSegmentState = selected + ? length * 4 : 0; + for (var i = 0; i < length; i++) + this._segments[i]._selectionState = selected + ? 4 : 0; + }, + + _updateSelection: function(segment, oldState, newState) { + segment._selectionState = newState; + var total = this._selectedSegmentState += newState - oldState; + if (total > 0) + this.setSelected(true); + }, + + flatten: function(maxDistance) { + var flattener = new PathFlattener(this), + pos = 0, + step = flattener.length / Math.ceil(flattener.length / maxDistance), + end = flattener.length + (this._closed ? -step : step) / 2; + var segments = []; + while (pos <= end) { + segments.push(new Segment(flattener.evaluate(pos, 0))); + pos += step; + } + this.setSegments(segments); + }, + + simplify: function(tolerance) { + if (this._segments.length > 2) { + var fitter = new PathFitter(this, tolerance || 2.5); + this.setSegments(fitter.fit()); + } + }, + + split: function(index, parameter) { + if (parameter === null) + return; + if (arguments.length == 1) { + var arg = index; + if (typeof arg === 'number') + arg = this.getLocationAt(arg); + index = arg.index; + parameter = arg.parameter; + } + if (parameter >= 1) { + index++; + parameter--; + } + var curves = this.getCurves(); + if (index >= 0 && index < curves.length) { + if (parameter > 0) { + curves[index++].divide(parameter); + } + var segs = this.removeSegments(index, this._segments.length, true), + path; + if (this._closed) { + this.setClosed(false); + path = this; + } else if (index > 0) { + path = this._clone(new Path().insertAbove(this, true)); + } + path._add(segs, 0); + this.addSegment(segs[0]); + return path; + } + return null; + }, + + isClockwise: function() { + if (this._clockwise !== undefined) + return this._clockwise; + return Path.isClockwise(this._segments); + }, + + setClockwise: function(clockwise) { + if (this.isClockwise() != (clockwise = !!clockwise)) + this.reverse(); + this._clockwise = clockwise; + }, + + reverse: function() { + this._segments.reverse(); + for (var i = 0, l = this._segments.length; i < l; i++) { + var segment = this._segments[i]; + var handleIn = segment._handleIn; + segment._handleIn = segment._handleOut; + segment._handleOut = handleIn; + segment._index = i; + } + delete this._curves; + if (this._clockwise !== undefined) + this._clockwise = !this._clockwise; + }, + + join: function(path) { + if (path) { + var segments = path._segments, + last1 = this.getLastSegment(), + last2 = path.getLastSegment(); + if (last1._point.equals(last2._point)) + path.reverse(); + var first2 = path.getFirstSegment(); + if (last1._point.equals(first2._point)) { + last1.setHandleOut(first2._handleOut); + this._add(segments.slice(1)); + } else { + var first1 = this.getFirstSegment(); + if (first1._point.equals(first2._point)) + path.reverse(); + last2 = path.getLastSegment(); + if (first1._point.equals(last2._point)) { + first1.setHandleIn(last2._handleIn); + this._add(segments.slice(0, segments.length - 1), 0); + } else { + this._add(segments.slice()); + } + } + path.remove(); + var first1 = this.getFirstSegment(); + last1 = this.getLastSegment(); + if (last1._point.equals(first1._point)) { + first1.setHandleIn(last1._handleIn); + last1.remove(); + this.setClosed(true); + } + this._changed(5); + return true; + } + return false; + }, + + reduce: function() { + return this; + }, + + getLength: function() { + if (this._length == null) { + var curves = this.getCurves(); + this._length = 0; + for (var i = 0, l = curves.length; i < l; i++) + this._length += curves[i].getLength(); + } + return this._length; + }, + + getArea: function() { + var curves = this.getCurves(); + var area = 0; + for (var i = 0, l = curves.length; i < l; i++) + area += curves[i].getArea(); + return area; + }, + + _getOffset: function(location) { + var index = location && location.getIndex(); + if (index != null) { + var curves = this.getCurves(), + offset = 0; + for (var i = 0; i < index; i++) + offset += curves[i].getLength(); + var curve = curves[index]; + return offset + curve.getLength(0, location.getParameter()); + } + return null; + }, + + getLocationOf: function(point) { + point = Point.read(arguments); + var curves = this.getCurves(); + for (var i = 0, l = curves.length; i < l; i++) { + var loc = curves[i].getLocationOf(point); + if (loc) + return loc; + } + return null; + }, + + getLocationAt: function(offset, isParameter) { + var curves = this.getCurves(), + length = 0; + if (isParameter) { + var index = ~~offset; + return curves[index].getLocationAt(offset - index, true); + } + for (var i = 0, l = curves.length; i < l; i++) { + var start = length, + curve = curves[i]; + length += curve.getLength(); + if (length >= offset) { + return curve.getLocationAt(offset - start); + } + } + if (offset <= this.getLength()) + return new CurveLocation(curves[curves.length - 1], 1); + return null; + }, + + getPointAt: function(offset, isParameter) { + var loc = this.getLocationAt(offset, isParameter); + return loc && loc.getPoint(); + }, + + getTangentAt: function(offset, isParameter) { + var loc = this.getLocationAt(offset, isParameter); + return loc && loc.getTangent(); + }, + + getNormalAt: function(offset, isParameter) { + var loc = this.getLocationAt(offset, isParameter); + return loc && loc.getNormal(); + }, + + getNearestLocation: function(point) { + point = Point.read(arguments); + var curves = this.getCurves(), + minDist = Infinity, + minLoc = null; + for (var i = 0, l = curves.length; i < l; i++) { + var loc = curves[i].getNearestLocation(point); + if (loc._distance < minDist) { + minDist = loc._distance; + minLoc = loc; + } + } + return minLoc; + }, + + getNearestPoint: function(point) { + point = Point.read(arguments); + return this.getNearestLocation(point).getPoint(); + }, + + getStyle: function() { + var parent = this._parent; + return (parent && parent._type === 'compound-path' + ? parent : this)._style; + }, + + _contains: function(point) { + var closed = this._closed; + if (!closed && !this.hasFill() + || !this._getBounds('getRoughBounds')._containsPoint(point)) + return false; + var curves = this.getCurves(), + segments = this._segments, + crossings = 0, + roots = new Array(3), + last = (closed + ? curves[curves.length - 1] + : new Curve(segments[segments.length - 1]._point, + segments[0]._point)).getValues(), + previous = last; + for (var i = 0, l = curves.length; i < l; i++) { + var vals = curves[i].getValues(), + x = vals[0], + y = vals[1]; + if (!(x === vals[2] && y === vals[3] && x === vals[4] + && y === vals[5] && x === vals[6] && y === vals[7])) { + crossings += Curve._getCrossings(vals, previous, + point.x, point.y, roots); + previous = vals; + } + } + if (!closed) { + crossings += Curve._getCrossings(last, previous, point.x, point.y, + roots); + } + return (crossings & 1) === 1; + }, + + _hitTest: function(point, options) { + var style = this.getStyle(), + segments = this._segments, + closed = this._closed, + tolerance = options.tolerance || 0, + radius = 0, join, cap, miterLimit, + that = this, + area, loc, res; + + if (options.stroke && style.getStrokeColor()) { + join = style.getStrokeJoin(); + cap = style.getStrokeCap(); + radius = style.getStrokeWidth() / 2 + tolerance; + miterLimit = radius * style.getMiterLimit(); + } + + function checkPoint(seg, pt, name) { + if (point.getDistance(pt) < tolerance) + return new HitResult(name, that, { segment: seg, point: pt }); + } + + function checkSegmentPoints(seg, ends) { + var pt = seg._point; + return (ends || options.segments) && checkPoint(seg, pt, 'segment') + || (!ends && options.handles) && ( + checkPoint(seg, pt.add(seg._handleIn), 'handle-in') || + checkPoint(seg, pt.add(seg._handleOut), 'handle-out')); + } + + function addAreaPoint(point) { + area.push(point); + } + + function getAreaCurve(index) { + var p1 = area[index], + p2 = area[(index + 1) % area.length]; + return [p1.x, p1.y, p1.x, p1.y, p2.x, p2.y, p2.x ,p2.y]; + } + + function isInArea(point) { + var length = area.length, + previous = getAreaCurve(length - 1), + roots = new Array(3), + crossings = 0; + for (var i = 0; i < length; i++) { + var curve = getAreaCurve(i); + crossings += Curve._getCrossings(curve, previous, + point.x, point.y, roots); + previous = curve; + } + return (crossings & 1) === 1; + } + + function checkSegmentStroke(segment) { + if (join !== 'round' || cap !== 'round') { + area = []; + if (closed || segment._index > 0 + && segment._index < segments.length - 1) { + if (join !== 'round' && (segment._handleIn.isZero() + || segment._handleOut.isZero())) + Path._addSquareJoin(segment, join, radius, miterLimit, + addAreaPoint, true); + } else if (cap !== 'round') { + Path._addSquareCap(segment, cap, radius, addAreaPoint, true); + } + if (area.length > 0) + return isInArea(point); + } + return point.getDistance(segment._point) <= radius; + } + + if (options.ends && !options.segments && !closed) { + if (res = checkSegmentPoints(segments[0], true) + || checkSegmentPoints(segments[segments.length - 1], true)) + return res; + } else if (options.segments || options.handles) { + for (var i = 0, l = segments.length; i < l; i++) { + if (res = checkSegmentPoints(segments[i])) + return res; + } + } + if (radius > 0) { + loc = this.getNearestLocation(point); + if (loc) { + var parameter = loc.getParameter(); + if (parameter === 0 || parameter === 1) { + if (!checkSegmentStroke(loc.getSegment())) + loc = null; + } else if (loc._distance > radius) { + loc = null; + } + } + if (!loc && join === 'miter') { + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + if (point.getDistance(segment._point) <= miterLimit + && checkSegmentStroke(segment)) { + loc = segment.getLocation(); + break; + } + } + } + } + return !loc && options.fill && this.hasFill() && this.contains(point) + ? new HitResult('fill', this) + : loc + ? new HitResult('stroke', this, { location: loc }) + : null; + } + +}, new function() { + + function drawHandles(ctx, segments, matrix, size) { + var half = size / 2; + + function drawHandle(index) { + var hX = coords[index], + hY = coords[index + 1]; + if (pX != hX || pY != hY) { + ctx.beginPath(); + ctx.moveTo(pX, pY); + ctx.lineTo(hX, hY); + ctx.stroke(); + ctx.beginPath(); + ctx.arc(hX, hY, half, 0, Math.PI * 2, true); + ctx.fill(); + } + } + + var coords = new Array(6); + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + segment._transformCoordinates(matrix, coords, false); + var state = segment._selectionState, + selected = state & 4, + pX = coords[0], + pY = coords[1]; + if (selected || (state & 1)) + drawHandle(2); + if (selected || (state & 2)) + drawHandle(4); + ctx.save(); + ctx.beginPath(); + ctx.rect(pX - half, pY - half, size, size); + ctx.fill(); + if (!selected) { + ctx.beginPath(); + ctx.rect(pX - half + 1, pY - half + 1, size - 2, size - 2); + ctx.fillStyle = '#ffffff'; + ctx.fill(); + } + ctx.restore(); + } + } + + function drawSegments(ctx, path, matrix) { + var segments = path._segments, + length = segments.length, + coords = new Array(6), + first = true, + curX, curY, + prevX, prevY, + inX, inY, + outX, outY; + + function drawSegment(i) { + var segment = segments[i]; + if (matrix) { + segment._transformCoordinates(matrix, coords, false); + curX = coords[0]; + curY = coords[1]; + } else { + var point = segment._point; + curX = point._x; + curY = point._y; + } + if (first) { + ctx.moveTo(curX, curY); + first = false; + } else { + if (matrix) { + inX = coords[2]; + inY = coords[3]; + } else { + var handle = segment._handleIn; + inX = curX + handle._x; + inY = curY + handle._y; + } + if (inX == curX && inY == curY && outX == prevX && outY == prevY) { + ctx.lineTo(curX, curY); + } else { + ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY); + } + } + prevX = curX; + prevY = curY; + if (matrix) { + outX = coords[4]; + outY = coords[5]; + } else { + var handle = segment._handleOut; + outX = prevX + handle._x; + outY = prevY + handle._y; + } + } + + for (var i = 0; i < length; i++) + drawSegment(i); + if (path._closed && length > 1) + drawSegment(0); + } + + return { + _draw: function(ctx, param) { + var clip = param.clip, + compound = param.compound; + if (!compound) + ctx.beginPath(); + + var style = this.getStyle(), + fillColor = style.getFillColor(), + strokeColor = style.getStrokeColor(), + dashArray = style.getDashArray(), + drawDash = !paper.support.nativeDash && strokeColor + && dashArray && dashArray.length; + + if (fillColor || strokeColor && !drawDash || compound || clip) + drawSegments(ctx, this); + + if (this._closed) + ctx.closePath(); + + if (!clip && !compound && (fillColor || strokeColor)) { + this._setStyles(ctx); + if (fillColor) + ctx.fill(); + if (strokeColor) { + if (drawDash) { + ctx.beginPath(); + var flattener = new PathFlattener(this), + from = style.getDashOffset(), to, + i = 0; + while (from < flattener.length) { + to = from + dashArray[(i++) % dashArray.length]; + flattener.drawPart(ctx, from, to); + from = to + dashArray[(i++) % dashArray.length]; + } + } + ctx.stroke(); + } + } + }, + + _drawSelected: function(ctx, matrix) { + ctx.beginPath(); + drawSegments(ctx, this, matrix); + ctx.stroke(); + drawHandles(ctx, this._segments, matrix, + this._project.options.handleSize || 4); + } + }; +}, new function() { + + function getFirstControlPoints(rhs) { + var n = rhs.length, + x = [], + tmp = [], + b = 2; + x[0] = rhs[0] / b; + for (var i = 1; i < n; i++) { + tmp[i] = 1 / b; + b = (i < n - 1 ? 4 : 2) - tmp[i]; + x[i] = (rhs[i] - x[i - 1]) / b; + } + for (var i = 1; i < n; i++) { + x[n - i - 1] -= tmp[n - i] * x[n - i]; + } + return x; + } + + return { + smooth: function() { + var segments = this._segments, + size = segments.length, + n = size, + overlap; + + if (size <= 2) + return; + + if (this._closed) { + overlap = Math.min(size, 4); + n += Math.min(size, overlap) * 2; + } else { + overlap = 0; + } + var knots = []; + for (var i = 0; i < size; i++) + knots[i + overlap] = segments[i]._point; + if (this._closed) { + for (var i = 0; i < overlap; i++) { + knots[i] = segments[i + size - overlap]._point; + knots[i + size + overlap] = segments[i]._point; + } + } else { + n--; + } + var rhs = []; + + for (var i = 1; i < n - 1; i++) + rhs[i] = 4 * knots[i]._x + 2 * knots[i + 1]._x; + rhs[0] = knots[0]._x + 2 * knots[1]._x; + rhs[n - 1] = 3 * knots[n - 1]._x; + var x = getFirstControlPoints(rhs); + + for (var i = 1; i < n - 1; i++) + rhs[i] = 4 * knots[i]._y + 2 * knots[i + 1]._y; + rhs[0] = knots[0]._y + 2 * knots[1]._y; + rhs[n - 1] = 3 * knots[n - 1]._y; + var y = getFirstControlPoints(rhs); + + if (this._closed) { + for (var i = 0, j = size; i < overlap; i++, j++) { + var f1 = i / overlap, + f2 = 1 - f1, + ie = i + overlap, + je = j + overlap; + x[j] = x[i] * f1 + x[j] * f2; + y[j] = y[i] * f1 + y[j] * f2; + x[je] = x[ie] * f2 + x[je] * f1; + y[je] = y[ie] * f2 + y[je] * f1; + } + n--; + } + var handleIn = null; + for (var i = overlap; i <= n - overlap; i++) { + var segment = segments[i - overlap]; + if (handleIn) + segment.setHandleIn(handleIn.subtract(segment._point)); + if (i < n) { + segment.setHandleOut( + new Point(x[i], y[i]).subtract(segment._point)); + if (i < n - 1) + handleIn = new Point( + 2 * knots[i + 1]._x - x[i + 1], + 2 * knots[i + 1]._y - y[i + 1]); + else + handleIn = new Point( + (knots[n]._x + x[n - 1]) / 2, + (knots[n]._y + y[n - 1]) / 2); + } + } + if (this._closed && handleIn) { + var segment = this._segments[0]; + segment.setHandleIn(handleIn.subtract(segment._point)); + } + } + }; +}, new function() { + function getCurrentSegment(that) { + var segments = that._segments; + if (segments.length == 0) + throw new Error('Use a moveTo() command first'); + return segments[segments.length - 1]; + } + + return { + moveTo: function() { + if (this._segments.length === 1) + this.removeSegment(0); + if (!this._segments.length) + this._add([ new Segment(Point.read(arguments)) ]); + }, + + moveBy: function() { + throw new Error('moveBy() is unsupported on Path items.'); + }, + + lineTo: function() { + this._add([ new Segment(Point.read(arguments)) ]); + }, + + cubicCurveTo: function() { + var handle1 = Point.read(arguments), + handle2 = Point.read(arguments), + to = Point.read(arguments); + var current = getCurrentSegment(this); + current.setHandleOut(handle1.subtract(current._point)); + this._add([ new Segment(to, handle2.subtract(to)) ]); + }, + + quadraticCurveTo: function() { + var handle = Point.read(arguments), + to = Point.read(arguments); + var current = getCurrentSegment(this)._point; + this.cubicCurveTo( + handle.add(current.subtract(handle).multiply(1 / 3)), + handle.add(to.subtract(handle).multiply(1 / 3)), + to + ); + }, + + curveTo: function() { + var through = Point.read(arguments), + to = Point.read(arguments), + t = Base.pick(Base.read(arguments), 0.5), + t1 = 1 - t, + current = getCurrentSegment(this)._point, + handle = through.subtract(current.multiply(t1 * t1)) + .subtract(to.multiply(t * t)).divide(2 * t * t1); + if (handle.isNaN()) + throw new Error( + 'Cannot put a curve through points with parameter = ' + t); + this.quadraticCurveTo(handle, to); + }, + + arcTo: function(to, clockwise ) { + var current = getCurrentSegment(this), + from = current._point, + through, + point = Point.read(arguments), + next = Base.pick(Base.peek(arguments), true); + if (typeof next === 'boolean') { + to = point; + clockwise = next; + var middle = from.add(to).divide(2), + through = middle.add(middle.subtract(from).rotate( + clockwise ? -90 : 90)); + } else { + through = point; + to = Point.read(arguments); + } + var l1 = new Line(from.add(through).divide(2), + through.subtract(from).rotate(90), true), + l2 = new Line(through.add(to).divide(2), + to.subtract(through).rotate(90), true), + center = l1.intersect(l2, true), + line = new Line(from, to), + throughSide = line.getSide(through); + if (!center) { + if (!throughSide) + return this.lineTo(to); + throw new Error("Cannot put an arc through the given points: " + + [from, through, to]); + } + var vector = from.subtract(center), + extent = vector.getDirectedAngle(to.subtract(center)), + centerSide = line.getSide(center); + if (centerSide == 0) { + extent = throughSide * Math.abs(extent); + } else if (throughSide == centerSide) { + extent -= 360 * (extent < 0 ? -1 : 1); + } + var ext = Math.abs(extent), + count = ext >= 360 ? 4 : Math.ceil(ext / 90), + inc = extent / count, + half = inc * Math.PI / 360, + z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)), + segments = []; + for (var i = 0; i <= count; i++) { + var pt = i < count ? center.add(vector) : to; + var out = i < count ? vector.rotate(90).multiply(z) : null; + if (i == 0) { + current.setHandleOut(out); + } else { + segments.push( + new Segment(pt, vector.rotate(-90).multiply(z), out)); + } + vector = vector.rotate(inc); + } + this._add(segments); + }, + + lineBy: function(vector) { + vector = Point.read(arguments); + var current = getCurrentSegment(this); + this.lineTo(current._point.add(vector)); + }, + + curveBy: function(throughVector, toVector, parameter) { + throughVector = Point.read(throughVector); + toVector = Point.read(toVector); + var current = getCurrentSegment(this)._point; + this.curveTo(current.add(throughVector), current.add(toVector), + parameter); + }, + + arcBy: function(throughVector, toVector) { + throughVector = Point.read(throughVector); + toVector = Point.read(toVector); + var current = getCurrentSegment(this)._point; + this.arcTo(current.add(throughVector), current.add(toVector)); + }, + + closePath: function() { + var first = this.getFirstSegment(), + last = this.getLastSegment(); + if (first._point.equals(last._point)) { + first.setHandleIn(last._handleIn); + last.remove(); + } + this.setClosed(true); + } + }; +}, { + + _getBounds: function(getter, matrix) { + return Path[getter](this._segments, this._closed, this.getStyle(), + matrix); + }, + +statics: { + isClockwise: function(segments) { + var sum = 0, + xPre, yPre, + add = false; + function edge(x, y) { + if (add) + sum += (xPre - x) * (y + yPre); + xPre = x; + yPre = y; + add = true; + } + for (var i = 0, l = segments.length; i < l; i++) { + var seg1 = segments[i], + seg2 = segments[i + 1 < l ? i + 1 : 0], + point1 = seg1._point, + handle1 = seg1._handleOut, + handle2 = seg2._handleIn, + point2 = seg2._point; + edge(point1._x, point1._y); + edge(point1._x + handle1._x, point1._y + handle1._y); + edge(point2._x + handle2._x, point2._y + handle2._y); + edge(point2._x, point2._y); + } + return sum > 0; + }, + + getBounds: function(segments, closed, style, matrix, strokePadding) { + var first = segments[0]; + if (!first) + return new Rectangle(); + var coords = new Array(6), + prevCoords = first._transformCoordinates(matrix, new Array(6), false), + min = prevCoords.slice(0, 2), + max = min.slice(), + roots = new Array(2); + + function processSegment(segment) { + segment._transformCoordinates(matrix, coords, false); + for (var i = 0; i < 2; i++) { + Curve._addBounds( + prevCoords[i], + prevCoords[i + 4], + coords[i + 2], + coords[i], + i, strokePadding ? strokePadding[i] : 0, min, max, roots); + } + var tmp = prevCoords; + prevCoords = coords; + coords = tmp; + } + + for (var i = 1, l = segments.length; i < l; i++) + processSegment(segments[i]); + if (closed) + processSegment(first); + return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]); + }, + + getStrokeBounds: function(segments, closed, style, matrix) { + function getPenPadding(radius, matrix) { + if (!matrix) + return [radius, radius]; + var mx = matrix.shiftless(), + hor = mx.transform(new Point(radius, 0)), + ver = mx.transform(new Point(0, radius)), + phi = hor.getAngleInRadians(), + a = hor.getLength(), + b = ver.getLength(); + var sin = Math.sin(phi), + cos = Math.cos(phi), + tan = Math.tan(phi), + tx = -Math.atan(b * tan / a), + ty = Math.atan(b / (tan * a)); + return [Math.abs(a * Math.cos(tx) * cos - b * Math.sin(tx) * sin), + Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)]; + } + + if (!style.getStrokeColor() || !style.getStrokeWidth()) + return Path.getBounds(segments, closed, style, matrix); + var length = segments.length - (closed ? 0 : 1), + radius = style.getStrokeWidth() / 2, + padding = getPenPadding(radius, matrix), + bounds = Path.getBounds(segments, closed, style, matrix, padding), + join = style.getStrokeJoin(), + cap = style.getStrokeCap(), + miterLimit = radius * style.getMiterLimit(); + var joinBounds = new Rectangle(new Size(padding).multiply(2)); + + function add(point) { + bounds = bounds.include(matrix + ? matrix._transformPoint(point, point) : point); + } + + function addJoin(segment, join) { + if (join === 'round' || !segment._handleIn.isZero() + && !segment._handleOut.isZero()) { + bounds = bounds.unite(joinBounds.setCenter(matrix + ? matrix._transformPoint(segment._point) : segment._point)); + } else { + Path._addSquareJoin(segment, join, radius, miterLimit, add); + } + } + + function addCap(segment, cap) { + switch (cap) { + case 'round': + addJoin(segment, cap); + break; + case 'butt': + case 'square': + Path._addSquareCap(segment, cap, radius, add); + break; + } + } + + for (var i = 1; i < length; i++) + addJoin(segments[i], join); + if (closed) { + addJoin(segments[0], join); + } else { + addCap(segments[0], cap); + addCap(segments[segments.length - 1], cap); + } + return bounds; + }, + + _addSquareJoin: function(segment, join, radius, miterLimit, addPoint, area) { + var curve2 = segment.getCurve(), + curve1 = curve2.getPrevious(), + point = curve2.getPointAt(0, true), + normal1 = curve1.getNormalAt(1, true), + normal2 = curve2.getNormalAt(0, true), + step = normal1.getDirectedAngle(normal2) < 0 ? -radius : radius; + normal1.setLength(step); + normal2.setLength(step); + if (area) { + addPoint(point); + addPoint(point.add(normal1)); + } + if (join === 'miter') { + var corner = new Line( + point.add(normal1), + new Point(-normal1.y, normal1.x), true + ).intersect(new Line( + point.add(normal2), + new Point(-normal2.y, normal2.x), true + ), true); + if (corner && point.getDistance(corner) <= miterLimit) { + addPoint(corner); + if (!area) + return; + } + } + if (!area) + addPoint(point.add(normal1)); + addPoint(point.add(normal2)); + }, + + _addSquareCap: function(segment, cap, radius, addPoint, area) { + var point = segment._point, + loc = segment.getLocation(), + normal = loc.getNormal().normalize(radius); + if (area) { + addPoint(point.subtract(normal)); + addPoint(point.add(normal)); + } + if (cap === 'square') + point = point.add(normal.rotate(loc.getParameter() == 0 ? -90 : 90)); + addPoint(point.add(normal)); + addPoint(point.subtract(normal)); + }, + + getHandleBounds: function(segments, closed, style, matrix, strokePadding, + joinPadding) { + var coords = new Array(6), + x1 = Infinity, + x2 = -x1, + y1 = x1, + y2 = x2; + strokePadding = strokePadding / 2 || 0; + joinPadding = joinPadding / 2 || 0; + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + segment._transformCoordinates(matrix, coords, false); + for (var j = 0; j < 6; j += 2) { + var padding = j == 0 ? joinPadding : strokePadding, + x = coords[j], + y = coords[j + 1], + xn = x - padding, + xx = x + padding, + yn = y - padding, + yx = y + padding; + if (xn < x1) x1 = xn; + if (xx > x2) x2 = xx; + if (yn < y1) y1 = yn; + if (yx > y2) y2 = yx; + } + } + return new Rectangle(x1, y1, x2 - x1, y2 - y1); + }, + + getRoughBounds: function(segments, closed, style, matrix) { + var strokeWidth = style.getStrokeColor() ? style.getStrokeWidth() : 0, + joinWidth = strokeWidth; + if (strokeWidth > 0) { + if (style.getStrokeJoin() === 'miter') + joinWidth = strokeWidth * style.getMiterLimit(); + if (style.getStrokeCap() === 'square') + joinWidth = Math.max(joinWidth, strokeWidth * Math.sqrt(2)); + } + return Path.getHandleBounds(segments, closed, style, matrix, + strokeWidth, joinWidth); + } +}}); + +Path.inject({ statics: new function() { + + function createPath(args) { + var path = new Path(), + named = Base.getNamed(args); + if (named) + path._set(named); + return path; + } + + function createRectangle() { + var rect = Rectangle.readNamed(arguments, 'rectangle'), + radius = Size.readNamed(arguments, 'radius', 0, 0, true), + bl = rect.getBottomLeft(true), + tl = rect.getTopLeft(true), + tr = rect.getTopRight(true), + br = rect.getBottomRight(true), + path = createPath(arguments); + if (!radius || radius.isZero()) { + path._add([ + new Segment(bl), + new Segment(tl), + new Segment(tr), + new Segment(br) + ]); + } else { + radius = Size.min(radius, rect.getSize(true).divide(2)); + var h = radius.multiply(kappa * 2); + path._add([ + new Segment(bl.add(radius.width, 0), null, [-h.width, 0]), + new Segment(bl.subtract(0, radius.height), [0, h.height], null), + + new Segment(tl.add(0, radius.height), null, [0, -h.height]), + new Segment(tl.add(radius.width, 0), [-h.width, 0], null), + + new Segment(tr.subtract(radius.width, 0), null, [h.width, 0]), + new Segment(tr.add(0, radius.height), [0, -h.height], null), + + new Segment(br.subtract(0, radius.height), null, [0, h.height]), + new Segment(br.subtract(radius.width, 0), [h.width, 0], null) + ]); + } + path._closed = true; + return path; + } + + var kappa = Numerical.KAPPA / 2; + + var ellipseSegments = [ + new Segment([0, 0.5], [0, kappa ], [0, -kappa]), + new Segment([0.5, 0], [-kappa, 0], [kappa, 0 ]), + new Segment([1, 0.5], [0, -kappa], [0, kappa ]), + new Segment([0.5, 1], [kappa, 0 ], [-kappa, 0]) + ]; + + function createEllipse() { + var rect = Rectangle.readNamed(arguments, 'rectangle'), + path = createPath(arguments), + point = rect.getPoint(true), + size = rect.getSize(true), + segments = new Array(4); + for (var i = 0; i < 4; i++) { + var segment = ellipseSegments[i]; + segments[i] = new Segment( + segment._point.multiply(size).add(point), + segment._handleIn.multiply(size), + segment._handleOut.multiply(size) + ); + } + path._add(segments); + path._closed = true; + return path; + } + + return { + Line: function() { + return new Path( + Point.readNamed(arguments, 'from'), + Point.readNamed(arguments, 'to') + ).set(Base.getNamed(arguments)); + }, + + Rectangle: createRectangle, + + RoundRectangle: createRectangle, + + Ellipse: createEllipse, + + Oval: createEllipse, + + Circle: function() { + var center = Point.readNamed(arguments, 'center'), + radius = Base.readNamed(arguments, 'radius'); + return createEllipse(new Rectangle(center.subtract(radius), + new Size(radius * 2, radius * 2))) + .set(Base.getNamed(arguments)); + }, + + Arc: function() { + var from = Point.readNamed(arguments, 'from'), + through = Point.readNamed(arguments, 'through'), + to = Point.readNamed(arguments, 'to'), + path = createPath(arguments); + path.moveTo(from); + path.arcTo(through, to); + return path; + }, + + RegularPolygon: function() { + var center = Point.readNamed(arguments, 'center'), + sides = Base.readNamed(arguments, 'sides'), + radius = Base.readNamed(arguments, 'radius'), + path = createPath(arguments), + step = 360 / sides, + three = !(sides % 3), + vector = new Point(0, three ? -radius : radius), + offset = three ? -1 : 0.5, + segments = new Array(sides); + for (var i = 0; i < sides; i++) { + segments[i] = new Segment(center.add( + vector.rotate((i + offset) * step))); + } + path._add(segments); + path._closed = true; + return path; + }, + + Star: function() { + var center = Point.readNamed(arguments, 'center'), + points = Base.readNamed(arguments, 'points') * 2, + radius1 = Base.readNamed(arguments, 'radius1'), + radius2 = Base.readNamed(arguments, 'radius2'), + path = createPath(arguments), + step = 360 / points, + vector = new Point(0, -1), + segments = new Array(points); + for (var i = 0; i < points; i++) { + segments[i] = new Segment(center.add( + vector.rotate(step * i).multiply(i % 2 ? radius2 : radius1))); + } + path._add(segments); + path._closed = true; + return path; + } + }; +}}); + +var CompoundPath = PathItem.extend({ + _class: 'CompoundPath', + _serializeFields: { + children: [] + }, + + initialize: function CompoundPath(arg) { + PathItem.call(this); + this._children = []; + this._namedChildren = {}; + if (arg && !this._set(arg)) + this.addChildren(Array.isArray(arg) ? arg : arguments); + }, + + insertChildren: function insertChildren(index, items, _preserve) { + items = insertChildren.base.call(this, index, items, _preserve, 'path'); + for (var i = 0, l = !_preserve && items && items.length; i < l; i++) { + var item = items[i]; + if (item._clockwise === undefined) + item.setClockwise(item._index === 0); + } + return items; + }, + + reduce: function() { + if (this._children.length == 1) { + var child = this._children[0]; + child.insertAbove(this); + this.remove(); + return child; + } + return this; + }, + + reverse: function() { + var children = this._children; + for (var i = 0, l = children.length; i < l; i++) + children[i].reverse(); + }, + + smooth: function() { + for (var i = 0, l = this._children.length; i < l; i++) + this._children[i].smooth(); + }, + + isClockwise: function() { + var child = this.getFirstChild(); + return child && child.isClockwise(); + }, + + setClockwise: function(clockwise) { + if (this.isClockwise() != !!clockwise) + this.reverse(); + }, + + getFirstSegment: function() { + var first = this.getFirstChild(); + return first && first.getFirstSegment(); + }, + + getLastSegment: function() { + var last = this.getLastChild(); + return last && last.getLastSegment(); + }, + + getCurves: function() { + var children = this._children, + curves = []; + for (var i = 0, l = children.length; i < l; i++) + curves = curves.concat(children[i].getCurves()); + return curves; + }, + + getFirstCurve: function() { + var first = this.getFirstChild(); + return first && first.getFirstCurve(); + }, + + getLastCurve: function() { + var last = this.getLastChild(); + return last && last.getFirstCurve(); + }, + + getArea: function() { + var children = this._children, + area = 0; + for (var i = 0, l = children.length; i < l; i++) + area += children[i].getArea(); + return area; + }, + + getPathData: function() { + var children = this._children, + paths = []; + for (var i = 0, l = children.length; i < l; i++) + paths.push(children[i].getPathData(arguments[0])); + return paths.join(' '); + }, + + _contains: function(point) { + var children = []; + for (var i = 0, l = this._children.length; i < l; i++) { + var child = this._children[i]; + if (child.contains(point)) + children.push(child); + } + return (children.length & 1) == 1 && children; + }, + + _hitTest: function _hitTest(point, options) { + var res = _hitTest.base.call(this, point, + Base.merge(options, { fill: false })); + if (!res && options.fill && this.hasFill()) { + res = this._contains(point); + res = res ? new HitResult('fill', res[0]) : null; + } + return res; + }, + + _draw: function(ctx, param) { + var children = this._children, + style = this._style; + if (children.length === 0) + return; + ctx.beginPath(); + param = param.extend({ compound: true }); + for (var i = 0, l = children.length; i < l; i++) + children[i].draw(ctx, param); + if (!param.clip) { + this._setStyles(ctx); + if (style.getFillColor()) + ctx.fill(); + if (style.getStrokeColor()) + ctx.stroke(); + } + } +}, new function() { + function getCurrentPath(that) { + if (!that._children.length) + throw new Error('Use a moveTo() command first'); + return that._children[that._children.length - 1]; + } + + var fields = { + moveTo: function() { + var path = new Path(); + this.addChild(path); + path.moveTo.apply(path, arguments); + }, + + moveBy: function() { + this.moveTo(getCurrentPath(this).getLastSegment()._point.add( + Point.read(arguments))); + }, + + closePath: function() { + getCurrentPath(this).closePath(); + } + }; + + Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo', + 'arcTo', 'lineBy', 'curveBy', 'arcBy'], function(key) { + fields[key] = function() { + var path = getCurrentPath(this); + path[key].apply(path, arguments); + }; + }); + + return fields; +}); + +var PathFlattener = Base.extend({ + initialize: function(path) { + this.curves = []; + this.parts = []; + this.length = 0; + this.index = 0; + + var segments = path._segments, + segment1 = segments[0], + segment2, + that = this; + + function addCurve(segment1, segment2) { + var curve = Curve.getValues(segment1, segment2); + that.curves.push(curve); + that._computeParts(curve, segment1._index, 0, 1); + } + + for (var i = 1, l = segments.length; i < l; i++) { + segment2 = segments[i]; + addCurve(segment1, segment2); + segment1 = segment2; + } + if (path._closed) + addCurve(segment2, segments[0]); + }, + + _computeParts: function(curve, index, minT, maxT) { + if ((maxT - minT) > 1 / 32 && !Curve.isFlatEnough(curve, 0.25)) { + var curves = Curve.subdivide(curve); + var halfT = (minT + maxT) / 2; + this._computeParts(curves[0], index, minT, halfT); + this._computeParts(curves[1], index, halfT, maxT); + } else { + var x = curve[6] - curve[0], + y = curve[7] - curve[1], + dist = Math.sqrt(x * x + y * y); + if (dist > 0.00001) { + this.length += dist; + this.parts.push({ + offset: this.length, + value: maxT, + index: index + }); + } + } + }, + + getParameterAt: function(offset) { + var i, j = this.index; + for (;;) { + i = j; + if (j == 0 || this.parts[--j].offset < offset) + break; + } + for (var l = this.parts.length; i < l; i++) { + var part = this.parts[i]; + if (part.offset >= offset) { + this.index = i; + var prev = this.parts[i - 1]; + var prevVal = prev && prev.index == part.index ? prev.value : 0, + prevLen = prev ? prev.offset : 0; + return { + value: prevVal + (part.value - prevVal) + * (offset - prevLen) / (part.offset - prevLen), + index: part.index + }; + } + } + var part = this.parts[this.parts.length - 1]; + return { + value: 1, + index: part.index + }; + }, + + evaluate: function(offset, type) { + var param = this.getParameterAt(offset); + return Curve.evaluate(this.curves[param.index], param.value, true, type); + }, + + drawPart: function(ctx, from, to) { + from = this.getParameterAt(from); + to = this.getParameterAt(to); + for (var i = from.index; i <= to.index; i++) { + var curve = Curve.getPart(this.curves[i], + i == from.index ? from.value : 0, + i == to.index ? to.value : 1); + if (i == from.index) + ctx.moveTo(curve[0], curve[1]); + ctx.bezierCurveTo.apply(ctx, curve.slice(2)); + } + } +}); + +var PathFitter = Base.extend({ + initialize: function(path, error) { + this.points = []; + var segments = path._segments, + prev; + for (var i = 0, l = segments.length; i < l; i++) { + var point = segments[i].point.clone(); + if (!prev || !prev.equals(point)) { + this.points.push(point); + prev = point; + } + } + this.error = error; + }, + + fit: function() { + var points = this.points, + length = points.length; + this.segments = length > 0 ? [new Segment(points[0])] : []; + if (length > 1) + this.fitCubic(0, length - 1, + points[1].subtract(points[0]).normalize(), + points[length - 2].subtract(points[length - 1]).normalize()); + return this.segments; + }, + + fitCubic: function(first, last, tan1, tan2) { + if (last - first == 1) { + var pt1 = this.points[first], + pt2 = this.points[last], + dist = pt1.getDistance(pt2) / 3; + this.addCurve([pt1, pt1.add(tan1.normalize(dist)), + pt2.add(tan2.normalize(dist)), pt2]); + return; + } + var uPrime = this.chordLengthParameterize(first, last), + maxError = Math.max(this.error, this.error * this.error), + split; + for (var i = 0; i <= 4; i++) { + var curve = this.generateBezier(first, last, uPrime, tan1, tan2); + var max = this.findMaxError(first, last, curve, uPrime); + if (max.error < this.error) { + this.addCurve(curve); + return; + } + split = max.index; + if (max.error >= maxError) + break; + this.reparameterize(first, last, uPrime, curve); + maxError = max.error; + } + var V1 = this.points[split - 1].subtract(this.points[split]), + V2 = this.points[split].subtract(this.points[split + 1]), + tanCenter = V1.add(V2).divide(2).normalize(); + this.fitCubic(first, split, tan1, tanCenter); + this.fitCubic(split, last, tanCenter.negate(), tan2); + }, + + addCurve: function(curve) { + var prev = this.segments[this.segments.length - 1]; + prev.setHandleOut(curve[1].subtract(curve[0])); + this.segments.push( + new Segment(curve[3], curve[2].subtract(curve[3]))); + }, + + generateBezier: function(first, last, uPrime, tan1, tan2) { + var epsilon = 1e-11, + pt1 = this.points[first], + pt2 = this.points[last], + C = [[0, 0], [0, 0]], + X = [0, 0]; + + for (var i = 0, l = last - first + 1; i < l; i++) { + var u = uPrime[i], + t = 1 - u, + b = 3 * u * t, + b0 = t * t * t, + b1 = b * t, + b2 = b * u, + b3 = u * u * u, + a1 = tan1.normalize(b1), + a2 = tan2.normalize(b2), + tmp = this.points[first + i] + .subtract(pt1.multiply(b0 + b1)) + .subtract(pt2.multiply(b2 + b3)); + C[0][0] += a1.dot(a1); + C[0][1] += a1.dot(a2); + C[1][0] = C[0][1]; + C[1][1] += a2.dot(a2); + X[0] += a1.dot(tmp); + X[1] += a2.dot(tmp); + } + + var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1], + alpha1, alpha2; + if (Math.abs(detC0C1) > epsilon) { + var detC0X = C[0][0] * X[1] - C[1][0] * X[0], + detXC1 = X[0] * C[1][1] - X[1] * C[0][1]; + alpha1 = detXC1 / detC0C1; + alpha2 = detC0X / detC0C1; + } else { + var c0 = C[0][0] + C[0][1], + c1 = C[1][0] + C[1][1]; + if (Math.abs(c0) > epsilon) { + alpha1 = alpha2 = X[0] / c0; + } else if (Math.abs(c1) > epsilon) { + alpha1 = alpha2 = X[1] / c1; + } else { + alpha1 = alpha2 = 0; + } + } + + var segLength = pt2.getDistance(pt1); + epsilon *= segLength; + if (alpha1 < epsilon || alpha2 < epsilon) { + alpha1 = alpha2 = segLength / 3; + } + + return [pt1, pt1.add(tan1.normalize(alpha1)), + pt2.add(tan2.normalize(alpha2)), pt2]; + }, + + reparameterize: function(first, last, u, curve) { + for (var i = first; i <= last; i++) { + u[i - first] = this.findRoot(curve, this.points[i], u[i - first]); + } + }, + + findRoot: function(curve, point, u) { + var curve1 = [], + curve2 = []; + for (var i = 0; i <= 2; i++) { + curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3); + } + for (var i = 0; i <= 1; i++) { + curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2); + } + var pt = this.evaluate(3, curve, u), + pt1 = this.evaluate(2, curve1, u), + pt2 = this.evaluate(1, curve2, u), + diff = pt.subtract(point), + df = pt1.dot(pt1) + diff.dot(pt2); + if (Math.abs(df) < 0.00001) + return u; + return u - diff.dot(pt1) / df; + }, + + evaluate: function(degree, curve, t) { + var tmp = curve.slice(); + for (var i = 1; i <= degree; i++) { + for (var j = 0; j <= degree - i; j++) { + tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t)); + } + } + return tmp[0]; + }, + + chordLengthParameterize: function(first, last) { + var u = [0]; + for (var i = first + 1; i <= last; i++) { + u[i - first] = u[i - first - 1] + + this.points[i].getDistance(this.points[i - 1]); + } + for (var i = 1, m = last - first; i <= m; i++) { + u[i] /= u[m]; + } + return u; + }, + + findMaxError: function(first, last, curve, u) { + var index = Math.floor((last - first + 1) / 2), + maxDist = 0; + for (var i = first + 1; i < last; i++) { + var P = this.evaluate(3, curve, u[i - first]); + var v = P.subtract(this.points[i]); + var dist = v.x * v.x + v.y * v.y; + if (dist >= maxDist) { + maxDist = dist; + index = i; + } + } + return { + error: maxDist, + index: index + }; + } +}); + +PathItem.inject(new function() { + + function splitPath(intersections, collectOthers) { + intersections.sort(function(loc1, loc2) { + var path1 = loc1.getPath(), + path2 = loc2.getPath(); + return path1 === path2 + ? (loc1.getIndex() + loc1.getParameter()) + - (loc2.getIndex() + loc2.getParameter()) + : path1._id - path2._id; + }); + var others = collectOthers && []; + for (var i = intersections.length - 1; i >= 0; i--) { + var loc = intersections[i], + other = loc.getIntersection(), + curve = loc.divide(), + segment = curve && curve.getSegment1() || loc.getSegment(); + if (others) + others.push(other); + segment._intersection = other; + } + return others; + } + + function reorientPath(path) { + if (path instanceof CompoundPath) { + var children = path._children, + length = children.length, + bounds = new Array(length), + counters = new Array(length), + clockwise = children[0].isClockwise(); + for (var i = 0; i < length; i++) { + bounds[i] = children[i].getBounds(); + counters[i] = 0; + } + for (var i = 0; i < length; i++) { + for (var j = 1; j < length; j++) { + if (i !== j && bounds[i].contains(bounds[j])) + counters[j]++; + } + if (i > 0 && counters[i] % 2 === 0) + children[i].setClockwise(clockwise); + } + } + return path; + } + + function computeBoolean(path1, path2, operator, subtract) { + path1 = reorientPath(path1.clone()); + path2 = reorientPath(path2.clone()); + var path1Clockwise = path1.isClockwise(), + path2Clockwise = path2.isClockwise(), + intersections = path1.getIntersections(path2); + splitPath(splitPath(intersections, true)); + if (subtract) { + path2.reverse(); + path2Clockwise = !path2Clockwise; + } + var paths = [] + .concat(path1._children || [path1]) + .concat(path2._children || [path2]), + segments = [], + result = new CompoundPath(); + for (var i = 0, l = paths.length; i < l; i++) { + var path = paths[i], + parent = path._parent, + clockwise = path.isClockwise(), + segs = path._segments; + path = parent instanceof CompoundPath ? parent : path; + for (var j = segs.length - 1; j >= 0; j--) { + var segment = segs[j], + midPoint = segment.getCurve().getPoint(0.5), + insidePath1 = path !== path1 && path1.contains(midPoint) + && (clockwise === path1Clockwise || subtract + || !testOnCurve(path1, midPoint)), + insidePath2 = path !== path2 && path2.contains(midPoint) + && (clockwise === path2Clockwise + || !testOnCurve(path2, midPoint)); + if (operator(path === path1, insidePath1, insidePath2)) { + segment._invalid = true; + } else { + segments.push(segment); + } + } + } + for (var i = 0, l = segments.length; i < l; i++) { + var segment = segments[i]; + if (segment._visited) + continue; + var path = new Path(), + loc = segment._intersection, + intersection = loc && loc.getSegment(true); + if (segment.getPrevious()._invalid) + segment.setHandleIn(intersection + ? intersection._handleIn + : new Point(0, 0)); + do { + segment._visited = true; + if (segment._invalid && segment._intersection) { + var inter = segment._intersection.getSegment(true); + path.add(new Segment(segment._point, segment._handleIn, + inter._handleOut)); + inter._visited = true; + segment = inter; + } else { + path.add(segment.clone()); + } + segment = segment.getNext(); + } while (segment && !segment._visited && segment !== intersection); + var amount = path._segments.length; + if (amount > 1 && (amount > 2 || !path.isPolygon())) { + path.setClosed(true); + result.addChild(path, true); + } else { + path.remove(); + } + } + path1.remove(); + path2.remove(); + return result.reduce(); + } + + function testOnCurve(path, point) { + var curves = path.getCurves(), + bounds = path.getBounds(); + if (bounds.contains(point)) { + for (var i = 0, l = curves.length; i < l; i++) { + var curve = curves[i]; + if (curve.getBounds().contains(point) + && curve.getParameterOf(point)) + return true; + } + } + return false; + } + + return { + unite: function(path) { + return computeBoolean(this, path, + function(isPath1, isInPath1, isInPath2) { + return isInPath1 || isInPath2; + }); + }, + + intersect: function(path) { + return computeBoolean(this, path, + function(isPath1, isInPath1, isInPath2) { + return !(isInPath1 || isInPath2); + }); + }, + + subtract: function(path) { + return computeBoolean(this, path, + function(isPath1, isInPath1, isInPath2) { + return isPath1 && isInPath2 || !isPath1 && !isInPath1; + }, true); + }, + + exclude: function(path) { + return new Group([this.subtract(path), path.subtract(this)]); + }, + + divide: function(path) { + return new Group([this.subtract(path), this.intersect(path)]); + } + }; +}); + +var TextItem = Item.extend({ + _class: 'TextItem', + _boundsSelected: true, + _serializeFields: { + content: null + }, + _boundsGetter: 'getBounds', + + initialize: function TextItem(arg) { + var hasProperties = arg && Base.isPlainObject(arg) + && arg.x === undefined && arg.y === undefined; + Item.call(this, hasProperties ? null : Point.read(arguments)); + this._content = ''; + this._lines = []; + if (hasProperties) + this._set(arg); + }, + + _clone: function _clone(copy) { + copy.setContent(this._content); + return _clone.base.call(this, copy); + }, + + getContent: function() { + return this._content; + }, + + setContent: function(content) { + this._content = '' + content; + this._lines = this._content.split(/\r\n|\n|\r/mg); + this._changed(69); + }, + + isEmpty: function() { + return !this._content; + }, + + getCharacterStyle: '#getStyle', + setCharacterStyle: '#setStyle', + + getParagraphStyle: '#getStyle', + setParagraphStyle: '#setStyle' +}); + +var PointText = TextItem.extend({ + _class: 'PointText', + + initialize: function PointText() { + TextItem.apply(this, arguments); + }, + + clone: function() { + return this._clone(new PointText()); + }, + + getPoint: function() { + var point = this._matrix.getTranslation(); + return new LinkedPoint(point.x, point.y, this, 'setPoint'); + }, + + setPoint: function(point) { + point = Point.read(arguments); + this.translate(point.subtract(this._matrix.getTranslation())); + }, + + _draw: function(ctx) { + if (!this._content) + return; + this._setStyles(ctx); + var style = this._style, + lines = this._lines, + leading = style.getLeading(); + ctx.font = style.getFontStyle(); + ctx.textAlign = style.getJustification(); + for (var i = 0, l = lines.length; i < l; i++) { + var line = lines[i]; + if (style.getFillColor()) + ctx.fillText(line, 0, 0); + if (style.getStrokeColor()) + ctx.strokeText(line, 0, 0); + ctx.translate(0, leading); + } + } +}, new function() { + var measureCtx = null; + + return { + _getBounds: function(getter, matrix) { + if (!measureCtx) + measureCtx = CanvasProvider.getContext(1, 1); + var style = this._style, + lines = this._lines, + count = lines.length, + justification = style.getJustification(), + leading = style.getLeading(), + x = 0; + measureCtx.font = style.getFontStyle(); + var width = 0; + for (var i = 0; i < count; i++) + width = Math.max(width, measureCtx.measureText(lines[i]).width); + if (justification !== 'left') + x -= width / (justification === 'center' ? 2: 1); + var bounds = new Rectangle(x, + count ? - 0.75 * leading : 0, + width, count * leading); + return matrix ? matrix._transformBounds(bounds, bounds) : bounds; + } + }; +}); + +var Color = Base.extend(new function() { + + var types = { + gray: ['gray'], + rgb: ['red', 'green', 'blue'], + hsb: ['hue', 'saturation', 'brightness'], + hsl: ['hue', 'saturation', 'lightness'], + gradient: ['gradient', 'origin', 'destination', 'highlight'] + }; + + var parsers = {}, + colorCache = {}, + colorCtx; + + function nameToRGB(name) { + var cached = colorCache[name]; + if (!cached) { + if (!colorCtx) { + colorCtx = CanvasProvider.getContext(1, 1); + colorCtx.globalCompositeOperation = 'copy'; + } + colorCtx.fillStyle = 'rgba(0,0,0,0)'; + colorCtx.fillStyle = name; + colorCtx.fillRect(0, 0, 1, 1); + var data = colorCtx.getImageData(0, 0, 1, 1).data; + cached = colorCache[name] = [ + data[0] / 255, + data[1] / 255, + data[2] / 255 + ]; + } + return cached.slice(); + } + + function hexToRGB(string) { + var hex = string.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/); + if (hex.length >= 4) { + var components = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + var value = hex[i + 1]; + components[i] = parseInt(value.length == 1 + ? value + value : value, 16) / 255; + } + return components; + } + } + + var hsbIndices = [ + [0, 3, 1], + [2, 0, 1], + [1, 0, 3], + [1, 2, 0], + [3, 1, 0], + [0, 1, 2] + ]; + + var converters = { + 'rgb-hsb': function(r, g, b) { + var max = Math.max(r, g, b), + min = Math.min(r, g, b), + delta = max - min, + h = delta === 0 ? 0 + : ( max == r ? (g - b) / delta + (g < b ? 6 : 0) + : max == g ? (b - r) / delta + 2 + : (r - g) / delta + 4) * 60; + return [h, max === 0 ? 0 : delta / max, max]; + }, + + 'hsb-rgb': function(h, s, b) { + var h = (h / 60) % 6, + i = Math.floor(h), + f = h - i, + i = hsbIndices[i], + v = [ + b, + b * (1 - s), + b * (1 - s * f), + b * (1 - s * (1 - f)) + ]; + return [v[i[0]], v[i[1]], v[i[2]]]; + }, + + 'rgb-hsl': function(r, g, b) { + var max = Math.max(r, g, b), + min = Math.min(r, g, b), + delta = max - min, + achromatic = delta === 0, + h = achromatic ? 0 + : ( max == r ? (g - b) / delta + (g < b ? 6 : 0) + : max == g ? (b - r) / delta + 2 + : (r - g) / delta + 4) * 60, + l = (max + min) / 2, + s = achromatic ? 0 : l < 0.5 + ? delta / (max + min) + : delta / (2 - max - min); + return [h, s, l]; + }, + + 'hsl-rgb': function(h, s, l) { + h /= 360; + if (s === 0) + return [l, l, l]; + var t3s = [ h + 1 / 3, h, h - 1 / 3 ], + t2 = l < 0.5 ? l * (1 + s) : l + s - l * s, + t1 = 2 * l - t2, + c = []; + for (var i = 0; i < 3; i++) { + var t3 = t3s[i]; + if (t3 < 0) t3 += 1; + if (t3 > 1) t3 -= 1; + c[i] = 6 * t3 < 1 + ? t1 + (t2 - t1) * 6 * t3 + : 2 * t3 < 1 + ? t2 + : 3 * t3 < 2 + ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6 + : t1; + } + return c; + }, + + 'rgb-gray': function(r, g, b) { + return [r * 0.2989 + g * 0.587 + b * 0.114]; + }, + + 'gray-rgb': function(g) { + return [g, g, g]; + }, + + 'gray-hsb': function(g) { + return [0, 0, g]; + }, + + 'gray-hsl': function(g) { + return [0, 0, g]; + }, + + 'gradient-rgb': function() { + return []; + }, + + 'rgb-gradient': function() { + return []; + } + + }; + + return Base.each(types, function(properties, type) { + parsers[type] = []; + Base.each(properties, function(name, index) { + var part = Base.capitalize(name), + hasOverlap = /^(hue|saturation)$/.test(name), + parser = parsers[type][index] = name === 'gradient' + ? function(value) { + var current = this._components[0]; + value = Gradient.read( + Array.isArray(value) ? value : arguments, + 0, 0, true); + if (current !== value) { + if (current) + current._removeOwner(this); + if (value) + value._addOwner(this); + } + return value; + } + : name === 'hue' + ? function(value) { + return isNaN(value) ? 0 + : ((value % 360) + 360) % 360; + } + : type === 'gradient' + ? function() { + return Point.read(arguments, 0, 0, + name === 'highlight', true); + } + : function(value) { + return isNaN(value) ? 0 + : Math.min(Math.max(value, 0), 1); + }; + + this['get' + part] = function() { + return this._type === type + || hasOverlap && /^hs[bl]$/.test(this._type) + ? this._components[index] + : this._convert(type)[index]; + }; + + this['set' + part] = function(value) { + if (this._type !== type + && !(hasOverlap && /^hs[bl]$/.test(this._type))) { + this._components = this._convert(type); + this._type = type; + } + value = parser.call(this, value); + if (value != null) { + this._components[index] = value; + this._changed(); + } + }; + }, this); + }, { + _class: 'Color', + _readIndex: true, + + initialize: function Color(arg) { + var slice = Array.prototype.slice, + args = arguments, + read = 0, + type, + components, + alpha, + values; + if (Array.isArray(arg)) { + args = arg; + arg = args[0]; + } + var argType = arg != null && typeof arg; + if (argType === 'string' && arg in types) { + type = arg; + arg = args[1]; + if (Array.isArray(arg)) { + components = arg; + alpha = args[2]; + } else { + if (this._read) + read = 1; + args = slice.call(args, 1); + argType = typeof arg; + } + } + if (!components) { + values = argType === 'number' + ? args + : argType === 'object' && arg.length != null + ? arg + : null; + if (values) { + if (!type) + type = values.length >= 3 + ? 'rgb' + : 'gray'; + var length = types[type].length; + alpha = values[length]; + if (this._read) + read += values === arguments + ? length + (alpha != null ? 1 : 0) + : 1; + if (values.length > length) + values = slice.call(values, 0, length); + } else if (argType === 'string') { + components = arg.match(/^#[0-9a-f]{3,6}$/i) + ? hexToRGB(arg) + : nameToRGB(arg); + type = 'rgb'; + } else if (argType === 'object') { + if (arg.constructor === Color) { + type = arg._type; + components = arg._components.slice(); + alpha = arg._alpha; + if (type === 'gradient') { + for (var i = 1, l = components.length; i < l; i++) { + var point = components[i]; + if (point) + components[i] = point.clone(); + } + } + } else if (arg.constructor === Gradient) { + type = 'gradient'; + values = args; + } else { + type = 'hue' in arg + ? 'lightness' in arg + ? 'hsl' + : 'hsb' + : 'gradient' in arg || 'stops' in arg + || 'radial' in arg + ? 'gradient' + : 'gray' in arg + ? 'gray' + : 'rgb'; + var properties = types[type]; + parse = parsers[type]; + this._components = components = []; + for (var i = 0, l = properties.length; i < l; i++) { + var value = arg[properties[i]]; + if (value == null && i === 0 && type === 'gradient' + && 'stops' in arg) { + value = { + stops: arg.stops, + radial: arg.radial + }; + } + value = parse[i].call(this, value); + if (value != null) + components[i] = value; + } + alpha = arg.alpha; + } + } + if (this._read && type) + read = 1; + } + this._type = type || 'rgb'; + if (type === 'gradient') + this._id = Color._id = (Color._id || 0) + 1; + if (!components) { + this._components = components = []; + var parse = parsers[this._type]; + for (var i = 0, l = parse.length; i < l; i++) { + var value = parse[i].call(this, values && values[i]); + if (value != null) + components[i] = value; + } + } + this._components = components; + this._alpha = alpha; + if (this._read) + this._read = read; + }, + + _serialize: function(options, dictionary) { + var components = this.getComponents(); + return Base.serialize( + /^(gray|rgb)$/.test(this._type) + ? components + : [this._type].concat(components), + options, true, dictionary); + }, + + _changed: function() { + this._canvasStyle = null; + if (this._owner) + this._owner._changed(17); + }, + + clone: function() { + return new Color(this._type, this._components.slice(), this._alpha); + }, + + _convert: function(type) { + var converter; + return this._type === type + ? this._components.slice() + : (converter = converters[this._type + '-' + type]) + ? converter.apply(this, this._components) + : converters['rgb-' + type].apply(this, + converters[this._type + '-rgb'].apply(this, + this._components)); + }, + + convert: function(type) { + return new Color(type, this._convert(type), this._alpha); + }, + + getType: function() { + return this._type; + }, + + setType: function(type) { + this._components = this._convert(type); + this._type = type; + }, + + getComponents: function() { + var components = this._components.slice(); + if (this._alpha != null) + components.push(this._alpha); + return components; + }, + + getAlpha: function() { + return this._alpha != null ? this._alpha : 1; + }, + + setAlpha: function(alpha) { + this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1); + this._changed(); + }, + + hasAlpha: function() { + return this._alpha != null; + }, + + equals: function(color) { + if (Base.isPlainValue(color)) + color = Color.read(arguments); + return color === this || color && this._type === color._type + && this._alpha === color._alpha + && Base.equals(this._components, color._components) + || false; + }, + + toString: function() { + var properties = types[this._type], + parts = [], + isGradient = this._type === 'gradient', + f = Formatter.instance; + for (var i = 0, l = properties.length; i < l; i++) { + var value = this._components[i]; + if (value != null) + parts.push(properties[i] + ': ' + + (isGradient ? value : f.number(value))); + } + if (this._alpha != null) + parts.push('alpha: ' + f.number(this._alpha)); + return '{ ' + parts.join(', ') + ' }'; + }, + + toCSS: function(noAlpha) { + var components = this._convert('rgb'), + alpha = noAlpha || this._alpha == null ? 1 : this._alpha; + components = [ + Math.round(components[0] * 255), + Math.round(components[1] * 255), + Math.round(components[2] * 255) + ]; + if (alpha < 1) + components.push(alpha); + return (components.length == 4 ? 'rgba(' : 'rgb(') + + components.join(',') + ')'; + }, + + toCanvasStyle: function(ctx) { + if (this._canvasStyle) + return this._canvasStyle; + if (this._type !== 'gradient') + return this._canvasStyle = this.toCSS(); + var components = this._components, + gradient = components[0], + stops = gradient._stops, + origin = components[1], + destination = components[2], + canvasGradient; + if (gradient._radial) { + var radius = destination.getDistance(origin), + highlight = components[3]; + if (highlight) { + var vector = highlight.subtract(origin); + if (vector.getLength() > radius) + highlight = origin.add(vector.normalize(radius - 0.1)); + } + var start = highlight || origin; + canvasGradient = ctx.createRadialGradient(start.x, start.y, + 0, origin.x, origin.y, radius); + } else { + canvasGradient = ctx.createLinearGradient(origin.x, origin.y, + destination.x, destination.y); + } + for (var i = 0, l = stops.length; i < l; i++) { + var stop = stops[i]; + canvasGradient.addColorStop(stop._rampPoint, + stop._color.toCanvasStyle()); + } + return this._canvasStyle = canvasGradient; + }, + + transform: function(matrix) { + if (this._type === 'gradient') { + var components = this._components; + for (var i = 1, l = components.length; i < l; i++) { + var point = components[i]; + matrix._transformPoint(point, point, true); + } + this._changed(); + } + }, + + statics: { + _types: types, + + random: function() { + var random = Math.random; + return new Color(random(), random(), random()); + } + } + }); +}); + +Base.each(Color._types, function(properties, type) { + var ctor = this[Base.capitalize(type) + 'Color'] = function(arg) { + var argType = arg != null && typeof arg, + components = argType === 'object' && arg.length != null + ? arg + : argType === 'string' + ? null + : arguments; + return components + ? new Color(type, components) + : new Color(arg); + }; + if (type.length == 3) { + var acronym = type.toUpperCase(); + Color[acronym] = this[acronym + 'Color'] = ctor; + } +}, this); + +var Gradient = Base.extend({ + _class: 'Gradient', + + initialize: function Gradient(stops, radial) { + this._id = Gradient._id = (Gradient._id || 0) + 1; + if (stops && this._set(stops)) + stops = radial = null; + if (!this._stops) + this.setStops(stops || ['white', 'black']); + if (this._radial == null) + this.setRadial(typeof radial === 'string' && radial === 'radial' + || radial || false); + }, + + _serialize: function(options, dictionary) { + return dictionary.add(this, function() { + return Base.serialize([this._stops, this._radial], + options, true, dictionary); + }); + }, + + _changed: function() { + for (var i = 0, l = this._owners && this._owners.length; i < l; i++) + this._owners[i]._changed(); + }, + + _addOwner: function(color) { + if (!this._owners) + this._owners = []; + this._owners.push(color); + }, + + _removeOwner: function(color) { + var index = this._owners ? this._owners.indexOf(color) : -1; + if (index != -1) { + this._owners.splice(index, 1); + if (this._owners.length === 0) + delete this._owners; + } + }, + + clone: function() { + var stops = []; + for (var i = 0, l = this._stops.length; i < l; i++) + stops[i] = this._stops[i].clone(); + return new this.constructor(stops); + }, + + getStops: function() { + return this._stops; + }, + + setStops: function(stops) { + if (this.stops) { + for (var i = 0, l = this._stops.length; i < l; i++) + delete this._stops[i]._owner; + } + if (stops.length < 2) + throw new Error( + 'Gradient stop list needs to contain at least two stops.'); + this._stops = GradientStop.readAll(stops, 0, false, true); + for (var i = 0, l = this._stops.length; i < l; i++) { + var stop = this._stops[i]; + stop._owner = this; + if (stop._defaultRamp) + stop.setRampPoint(i / (l - 1)); + } + this._changed(); + }, + + getRadial: function() { + return this._radial; + }, + + setRadial: function(radial) { + this._radial = radial; + this._changed(); + }, + + equals: function(gradient) { + if (gradient && gradient.constructor == this.constructor + && this._stops.length == gradient._stops.length) { + for (var i = 0, l = this._stops.length; i < l; i++) { + if (!this._stops[i].equals(gradient._stops[i])) + return false; + } + return true; + } + return false; + } +}); + +var GradientStop = Base.extend({ + _class: 'GradientStop', + + initialize: function GradientStop(arg0, arg1) { + if (arg0) { + var color, rampPoint; + if (arg1 === undefined && Array.isArray(arg0)) { + color = arg0[0]; + rampPoint = arg0[1]; + } else if (arg0.color) { + color = arg0.color; + rampPoint = arg0.rampPoint; + } else { + color = arg0; + rampPoint = arg1; + } + this.setColor(color); + this.setRampPoint(rampPoint); + } + }, + + clone: function() { + return new GradientStop(this._color.clone(), this._rampPoint); + }, + + _serialize: function(options, dictionary) { + return Base.serialize([this._color, this._rampPoint], options, true, + dictionary); + }, + + _changed: function() { + if (this._owner) + this._owner._changed(17); + }, + + getRampPoint: function() { + return this._rampPoint; + }, + + setRampPoint: function(rampPoint) { + this._defaultRamp = rampPoint == null; + this._rampPoint = rampPoint || 0; + this._changed(); + }, + + getColor: function() { + return this._color; + }, + + setColor: function(color) { + this._color = Color.read(arguments); + if (this._color === color) + this._color = color.clone(); + this._color._owner = this; + this._changed(); + }, + + equals: function(stop) { + return stop === this || stop instanceof GradientStop + && this._color.equals(stop._color) + && this._rampPoint == stop._rampPoint + || false; + } +}); + +var Style = Base.extend(new function() { + var defaults = { + fillColor: undefined, + strokeColor: undefined, + selectedColor: undefined, + strokeWidth: 1, + strokeCap: 'butt', + strokeJoin: 'miter', + miterLimit: 10, + dashOffset: 0, + dashArray: [], + font: 'sans-serif', + fontSize: 12, + leading: null, + justification: 'left' + }; + + var flags = { + strokeWidth: 25, + strokeCap: 25, + strokeJoin: 25, + miterLimit: 25, + font: 5, + fontSize: 5, + leading: 5, + justification: 5 + }; + + var item = {}, + fields = { + _defaults: defaults, + _textDefaults: Base.merge(defaults, { + fillColor: new Color() + }) + }; + + Base.each(defaults, function(value, key) { + var isColor = /Color$/.test(key), + part = Base.capitalize(key), + flag = flags[key], + set = 'set' + part, + get = 'get' + part; + + fields[set] = function(value) { + var children = this._item && this._item._children; + if (children && children.length > 0 + && this._item._type !== 'compound-path') { + for (var i = 0, l = children.length; i < l; i++) + children[i]._style[set](value); + } else { + var old = this._values[key]; + if (old != value) { + if (isColor) { + if (old) + delete old._owner; + if (value && value.constructor === Color) + value._owner = this._item; + } + this._values[key] = value; + if (this._item) + this._item._changed(flag || 17); + } + } + }; + + fields[get] = function() { + var value, + children = this._item && this._item._children; + if (!children || children.length === 0 || arguments[0] + || this._item._type === 'compound-path') { + var value = this._values[key]; + if (value === undefined) { + value = this._defaults[key]; + if (value && value.clone) + value = value.clone(); + this._values[key] = value; + } else if (isColor && !(value && value.constructor === Color)) { + this._values[key] = value = Color.read( + [value], 0, 0, true, true); + if (value) + value._owner = this._item; + } + return value; + } + for (var i = 0, l = children.length; i < l; i++) { + var childValue = children[i]._style[get](); + if (i === 0) { + value = childValue; + } else if (!Base.equals(value, childValue)) { + return undefined; + } + } + return value; + }; + + item[get] = function() { + return this._style[get](); + }; + + item[set] = function(value) { + this._style[set](value); + }; + }); + + Item.inject(item); + return fields; +}, { + _class: 'Style', + + initialize: function Style(style, _item) { + this._values = {}; + this._item = _item; + if (_item instanceof TextItem) + this._defaults = this._textDefaults; + if (style) + this.set(style); + }, + + set: function(style) { + var isStyle = style instanceof Style, + values = isStyle ? style._values : style; + if (values) { + for (var key in values) { + if (key in this._defaults) { + var value = values[key]; + this[key] = value && isStyle && value.clone + ? value.clone() : value; + } + } + } + }, + + getLeading: function getLeading() { + var leading = getLeading.base.call(this); + return leading != null ? leading : this.getFontSize() * 1.2; + }, + + getFontStyle: function() { + var size = this.getFontSize(); + return (/[a-z]/i.test(size) ? size + ' ' : size + 'px ') + + this.getFont(); + } + +}); + +var DomElement = new function() { + + var special = /^(checked|value|selected|disabled)$/i, + translated = { text: 'textContent', html: 'innerHTML' }, + unitless = { lineHeight: 1, zoom: 1, zIndex: 1, opacity: 1 }; + + function create(nodes, parent) { + var res = []; + for (var i = 0, l = nodes && nodes.length; i < l;) { + var el = nodes[i++]; + if (typeof el === 'string') { + el = document.createElement(el); + } else if (!el || !el.nodeType) { + continue; + } + if (Base.isPlainObject(nodes[i])) + DomElement.set(el, nodes[i++]); + if (Array.isArray(nodes[i])) + create(nodes[i++], el); + if (parent) + parent.appendChild(el); + res.push(el); + } + return res; + } + + return { + create: function(nodes, parent) { + var isArray = Array.isArray(nodes), + res = create(isArray ? nodes : arguments, isArray ? parent : null); + return res.length == 1 ? res[0] : res; + }, + + find: function(selector, root) { + return (root || document).querySelector(selector); + }, + + findAll: function(selector, root) { + return (root || document).querySelectorAll(selector); + }, + + get: function(el, key) { + return el + ? special.test(key) + ? key === 'value' || typeof el[key] !== 'string' + ? el[key] + : true + : key in translated + ? el[translated[key]] + : el.getAttribute(key) + : null; + }, + + set: function(el, key, value) { + if (typeof key !== 'string') { + for (var name in key) + if (key.hasOwnProperty(name)) + this.set(el, name, key[name]); + } else if (!el || value === undefined) { + return el; + } else if (special.test(key)) { + el[key] = value; + } else if (key in translated) { + el[translated[key]] = value; + } else if (key === 'style') { + this.setStyle(el, value); + } else if (key === 'events') { + DomEvent.add(el, value); + } else { + el.setAttribute(key, value); + } + return el; + }, + + getStyles: function(el) { + var view = el && el.ownerDocument.defaultView; + return view && view.getComputedStyle(el, ''); + }, + + getStyle: function(el, key) { + return el && el.style[key] || this.getStyles(el)[key] || null; + }, + + setStyle: function(el, key, value) { + if (typeof key !== 'string') { + for (var name in key) + if (key.hasOwnProperty(name)) + this.setStyle(el, name, key[name]); + } else { + if (/^-?[\d\.]+$/.test(value) && !(key in unitless)) + value += 'px'; + el.style[key] = value; + } + return el; + }, + + hasClass: function(el, cls) { + return new RegExp('\\s*' + cls + '\\s*').test(el.className); + }, + + addClass: function(el, cls) { + el.className = (el.className + ' ' + cls).trim(); + }, + + removeClass: function(el, cls) { + el.className = el.className.replace( + new RegExp('\\s*' + cls + '\\s*'), ' ').trim(); + }, + + remove: function(el) { + if (el.parentNode) + el.parentNode.removeChild(el); + }, + + removeChildren: function(el) { + while (el.firstChild) + el.removeChild(el.firstChild); + }, + + getBounds: function(el, viewport) { + var doc = el.ownerDocument, + body = doc.body, + html = doc.documentElement, + rect; + try { + rect = el.getBoundingClientRect(); + } catch (e) { + rect = { left: 0, top: 0, width: 0, height: 0 }; + } + var x = rect.left - (html.clientLeft || body.clientLeft || 0), + y = rect.top - (html.clientTop || body.clientTop || 0); + if (!viewport) { + var view = doc.defaultView; + x += view.pageXOffset || html.scrollLeft || body.scrollLeft; + y += view.pageYOffset || html.scrollTop || body.scrollTop; + } + return new Rectangle(x, y, rect.width, rect.height); + }, + + getViewportBounds: function(el) { + var doc = el.ownerDocument, + view = doc.defaultView, + html = doc.documentElement; + return new Rectangle(0, 0, + view.innerWidth || html.clientWidth, + view.innerHeight || html.clientHeight + ); + }, + + getOffset: function(el, viewport) { + return this.getBounds(el, viewport).getPoint(); + }, + + getSize: function(el) { + return this.getBounds(el, true).getSize(); + }, + + isInvisible: function(el) { + return this.getSize(el).equals(new Size(0, 0)); + }, + + isInView: function(el) { + return !this.isInvisible(el) && this.getViewportBounds(el).intersects( + this.getBounds(el, true)); + } + }; +}; + +var DomEvent = { + add: function(el, events) { + for (var type in events) { + var func = events[type]; + if (el.addEventListener) { + el.addEventListener(type, func, false); + } else if (el.attachEvent) { + el.attachEvent('on' + type, func.bound = function() { + func.call(el, window.event); + }); + } + } + }, + + remove: function(el, events) { + for (var type in events) { + var func = events[type]; + if (el.removeEventListener) { + el.removeEventListener(type, func, false); + } else if (el.detachEvent) { + el.detachEvent('on' + type, func.bound); + } + } + }, + + getPoint: function(event) { + var pos = event.targetTouches + ? event.targetTouches.length + ? event.targetTouches[0] + : event.changedTouches[0] + : event; + return new Point( + pos.pageX || pos.clientX + document.documentElement.scrollLeft, + pos.pageY || pos.clientY + document.documentElement.scrollTop + ); + }, + + getTarget: function(event) { + return event.target || event.srcElement; + }, + + getOffset: function(event, target) { + return DomEvent.getPoint(event).subtract(DomElement.getOffset( + target || DomEvent.getTarget(event))); + }, + + preventDefault: function(event) { + if (event.preventDefault) { + event.preventDefault(); + } else { + event.returnValue = false; + } + }, + + stopPropagation: function(event) { + if (event.stopPropagation) { + event.stopPropagation(); + } else { + event.cancelBubble = true; + } + }, + + stop: function(event) { + DomEvent.stopPropagation(event); + DomEvent.preventDefault(event); + } +}; + +DomEvent.requestAnimationFrame = new function() { + var part = 'equestAnimationFrame', + request = window['r' + part] || window['webkitR' + part] + || window['mozR' + part] || window['oR' + part] + || window['msR' + part]; + if (request) { + request(function(time) { + if (time == null) + request = null; + }); + } + + var callbacks = [], + focused = true, + timer; + + DomEvent.add(window, { + focus: function() { + focused = true; + }, + blur: function() { + focused = false; + } + }); + + return function(callback, element) { + if (request) + return request(callback, element); + callbacks.push([callback, element]); + if (timer) + return; + timer = setInterval(function() { + for (var i = callbacks.length - 1; i >= 0; i--) { + var entry = callbacks[i], + func = entry[0], + el = entry[1]; + if (!el || (PaperScope.getAttribute(el, 'keepalive') == 'true' + || focused) && DomElement.isInView(el)) { + callbacks.splice(i, 1); + func(Date.now()); + } + } + }, 1000 / 60); + }; +}; + +var View = Base.extend(Callback, { + _class: 'View', + + initialize: function View(element) { + this._scope = paper; + this._project = paper.project; + this._element = element; + var size; + this._id = element.getAttribute('id'); + if (this._id == null) + element.setAttribute('id', this._id = 'view-' + View._id++); + DomEvent.add(element, this._viewHandlers); + if (PaperScope.hasAttribute(element, 'resize')) { + var offset = DomElement.getOffset(element, true), + that = this; + size = DomElement.getViewportBounds(element) + .getSize().subtract(offset); + this._windowHandlers = { + resize: function() { + if (!DomElement.isInvisible(element)) + offset = DomElement.getOffset(element, true); + that.setViewSize(DomElement.getViewportBounds(element) + .getSize().subtract(offset)); + } + }; + DomEvent.add(window, this._windowHandlers); + } else { + size = new Size(parseInt(element.getAttribute('width'), 10), + parseInt(element.getAttribute('height'), 10)); + if (size.isNaN()) + size = DomElement.getSize(element); + } + element.width = size.width; + element.height = size.height; + if (PaperScope.hasAttribute(element, 'stats')) { + this._stats = new Stats(); + var stats = this._stats.domElement, + style = stats.style, + offset = DomElement.getOffset(element); + style.position = 'absolute'; + style.left = offset.x + 'px'; + style.top = offset.y + 'px'; + document.body.appendChild(stats); + } + View._views.push(this); + View._viewsById[this._id] = this; + this._viewSize = new LinkedSize(size.width, size.height, + this, 'setViewSize'); + this._matrix = new Matrix(); + this._zoom = 1; + if (!View._focused) + View._focused = this; + this._frameItems = {}; + this._frameItemCount = 0; + }, + + remove: function() { + if (!this._project) + return false; + if (View._focused == this) + View._focused = null; + View._views.splice(View._views.indexOf(this), 1); + delete View._viewsById[this._id]; + if (this._project.view == this) + this._project.view = null; + DomEvent.remove(this._element, this._viewHandlers); + DomEvent.remove(window, this._windowHandlers); + this._element = this._project = null; + this.detach('frame'); + this._frameItems = {}; + return true; + }, + + _events: { + onFrame: { + install: function() { + if (!this._requested) { + this._animate = true; + this._handleFrame(true); + } + }, + + uninstall: function() { + this._animate = false; + } + }, + + onResize: {} + }, + + _animate: false, + _time: 0, + _count: 0, + + _handleFrame: function(request) { + this._requested = false; + if (!this._animate) + return; + paper = this._scope; + if (request) { + this._requested = true; + var that = this; + DomEvent.requestAnimationFrame(function() { + that._handleFrame(true); + }, this._element); + } + var now = Date.now() / 1000, + delta = this._before ? now - this._before : 0; + this._before = now; + this._handlingFrame = true; + this.fire('frame', Base.merge({ + delta: delta, + time: this._time += delta, + count: this._count++ + })); + if (this._stats) + this._stats.update(); + this._handlingFrame = false; + this.draw(true); + }, + + _animateItem: function(item, animate) { + var items = this._frameItems; + if (animate) { + items[item._id] = { + item: item, + time: 0, + count: 0 + }; + if (++this._frameItemCount == 1) + this.attach('frame', this._handleFrameItems); + } else { + delete items[item._id]; + if (--this._frameItemCount == 0) { + this.detach('frame', this._handleFrameItems); + } + } + }, + + _handleFrameItems: function(event) { + for (var i in this._frameItems) { + var entry = this._frameItems[i]; + entry.item.fire('frame', Base.merge(event, { + time: entry.time += event.delta, + count: entry.count++ + })); + } + }, + + _redraw: function() { + this._project._needsRedraw = true; + if (this._handlingFrame) + return; + if (this._animate) { + this._handleFrame(); + } else { + this.draw(); + } + }, + + _transform: function(matrix) { + this._matrix.concatenate(matrix); + this._bounds = null; + this._inverse = null; + this._redraw(); + }, + + getElement: function() { + return this._element; + }, + + getViewSize: function() { + return this._viewSize; + }, + + setViewSize: function(size) { + size = Size.read(arguments); + var delta = size.subtract(this._viewSize); + if (delta.isZero()) + return; + this._element.width = size.width; + this._element.height = size.height; + this._viewSize.set(size.width, size.height, true); + this._bounds = null; + this.fire('resize', { + size: size, + delta: delta + }); + this._redraw(); + }, + + getBounds: function() { + if (!this._bounds) + this._bounds = this._getInverse()._transformBounds( + new Rectangle(new Point(), this._viewSize)); + return this._bounds; + }, + + getSize: function() { + return this.getBounds().getSize(arguments[0]); + }, + + getCenter: function() { + return this.getBounds().getCenter(arguments[0]); + }, + + setCenter: function(center) { + center = Point.read(arguments); + this.scrollBy(center.subtract(this.getCenter())); + }, + + getZoom: function() { + return this._zoom; + }, + + setZoom: function(zoom) { + this._transform(new Matrix().scale(zoom / this._zoom, + this.getCenter())); + this._zoom = zoom; + }, + + isVisible: function() { + return DomElement.isInView(this._element); + }, + + scrollBy: function() { + this._transform(new Matrix().translate(Point.read(arguments).negate())); + }, + + projectToView: function() { + return this._matrix._transformPoint(Point.read(arguments)); + }, + + viewToProject: function() { + return this._getInverse()._transformPoint(Point.read(arguments)); + }, + + _getInverse: function() { + if (!this._inverse) + this._inverse = this._matrix.inverted(); + return this._inverse; + } + +}, { + statics: { + _views: [], + _viewsById: {}, + _id: 0, + + create: function(element) { + if (typeof element === 'string') + element = document.getElementById(element); + return new CanvasView(element); + } + } +}, new function() { + var tool, + prevFocus, + tempFocus, + dragging = false; + + function getView(event) { + var target = DomEvent.getTarget(event); + return target.getAttribute && View._viewsById[target.getAttribute('id')]; + } + + function viewToProject(view, event) { + return view.viewToProject(DomEvent.getOffset(event, view._element)); + } + + function updateFocus() { + if (!View._focused || !View._focused.isVisible()) { + for (var i = 0, l = View._views.length; i < l; i++) { + var view = View._views[i]; + if (view && view.isVisible()) { + View._focused = tempFocus = view; + break; + } + } + } + } + + function mousedown(event) { + var view = View._focused = getView(event), + point = viewToProject(view, event); + dragging = true; + if (view._onMouseDown) + view._onMouseDown(event, point); + if (tool = view._scope._tool) + tool._onHandleEvent('mousedown', point, event); + view.draw(true); + } + + function mousemove(event) { + var view; + if (!dragging) { + view = getView(event); + if (view) { + prevFocus = View._focused; + View._focused = tempFocus = view; + } else if (tempFocus && tempFocus == View._focused) { + View._focused = prevFocus; + updateFocus(); + } + } + if (!(view = view || View._focused)) + return; + var point = event && viewToProject(view, event); + if (view._onMouseMove) + view._onMouseMove(event, point); + if (tool = view._scope._tool) { + if (tool._onHandleEvent(dragging && tool.responds('mousedrag') + ? 'mousedrag' : 'mousemove', point, event)) + DomEvent.stop(event); + } + view.draw(true); + } + + function mouseup(event) { + var view = View._focused; + if (!view || !dragging) + return; + var point = viewToProject(view, event); + curPoint = null; + dragging = false; + if (view._onMouseUp) + view._onMouseUp(event, point); + if (tool && tool._onHandleEvent('mouseup', point, event)) + DomEvent.stop(event); + view.draw(true); + } + + function selectstart(event) { + if (dragging) + DomEvent.stop(event); + } + + DomEvent.add(document, { + mousemove: mousemove, + mouseup: mouseup, + touchmove: mousemove, + touchend: mouseup, + selectstart: selectstart, + scroll: updateFocus + }); + + DomEvent.add(window, { + load: updateFocus + }); + + return { + _viewHandlers: { + mousedown: mousedown, + touchstart: mousedown, + selectstart: selectstart + }, + + statics: { + updateFocus: updateFocus + } + }; +}); + +var CanvasView = View.extend({ + _class: 'CanvasView', + + initialize: function CanvasView(canvas) { + if (!(canvas instanceof HTMLCanvasElement)) { + var size = Size.read(arguments, 1); + if (size.isZero()) + size = new Size(1024, 768); + canvas = CanvasProvider.getCanvas(size); + } + this._context = canvas.getContext('2d'); + this._eventCounters = {}; + View.call(this, canvas); + }, + + draw: function(checkRedraw) { + if (checkRedraw && !this._project._needsRedraw) + return false; + var ctx = this._context, + size = this._viewSize; + ctx.clearRect(0, 0, size._width + 1, size._height + 1); + this._project.draw(ctx, this._matrix); + this._project._needsRedraw = false; + return true; + } +}, new function() { + + var downPoint, + lastPoint, + overPoint, + downItem, + lastItem, + overItem, + hasDrag, + doubleClick, + clickTime; + + function callEvent(type, event, point, target, lastPoint, bubble) { + var item = target, + mouseEvent; + while (item) { + if (item.responds(type)) { + if (!mouseEvent) + mouseEvent = new MouseEvent(type, event, point, target, + lastPoint ? point.subtract(lastPoint) : null); + if (item.fire(type, mouseEvent) + && (!bubble || mouseEvent._stopped)) + return false; + } + item = item.getParent(); + } + return true; + } + + function handleEvent(view, type, event, point, lastPoint) { + if (view._eventCounters[type]) { + var project = view._project, + hit = project.hitTest(point, { + tolerance: project.options.hitTolerance || 0, + fill: true, + stroke: true + }), + item = hit && hit.item; + if (item) { + if (type === 'mousemove' && item != overItem) + lastPoint = point; + if (type !== 'mousemove' || !hasDrag) + callEvent(type, event, point, item, lastPoint); + return item; + } + } + } + + return { + _onMouseDown: function(event, point) { + var item = handleEvent(this, 'mousedown', event, point); + doubleClick = lastItem == item && (Date.now() - clickTime < 300); + downItem = lastItem = item; + downPoint = lastPoint = overPoint = point; + hasDrag = downItem && downItem.responds('mousedrag'); + }, + + _onMouseUp: function(event, point) { + var item = handleEvent(this, 'mouseup', event, point); + if (hasDrag) { + if (lastPoint && !lastPoint.equals(point)) + callEvent('mousedrag', event, point, downItem, lastPoint); + if (item != downItem) { + overPoint = point; + callEvent('mousemove', event, point, item, overPoint); + } + } + if (item === downItem) { + clickTime = Date.now(); + if (!doubleClick + || callEvent('doubleclick', event, downPoint, item)) + callEvent('click', event, downPoint, item); + doubleClick = false; + } + downItem = null; + hasDrag = false; + }, + + _onMouseMove: function(event, point) { + if (downItem) + callEvent('mousedrag', event, point, downItem, lastPoint); + var item = handleEvent(this, 'mousemove', event, point, overPoint); + lastPoint = overPoint = point; + if (item !== overItem) { + callEvent('mouseleave', event, point, overItem); + overItem = item; + callEvent('mouseenter', event, point, item); + } + } + }; +}); + +var Event = Base.extend({ + _class: 'Event', + + initialize: function Event(event) { + this.event = event; + }, + + preventDefault: function() { + this._prevented = true; + DomEvent.preventDefault(this.event); + }, + + stopPropagation: function() { + this._stopped = true; + DomEvent.stopPropagation(this.event); + }, + + stop: function() { + this.stopPropagation(); + this.preventDefault(); + }, + + getModifiers: function() { + return Key.modifiers; + } +}); + +var KeyEvent = Event.extend({ + _class: 'KeyEvent', + + initialize: function KeyEvent(down, key, character, event) { + Event.call(this, event); + this.type = down ? 'keydown' : 'keyup'; + this.key = key; + this.character = character; + }, + + toString: function() { + return "{ type: '" + this.type + + "', key: '" + this.key + + "', character: '" + this.character + + "', modifiers: " + this.getModifiers() + + " }"; + } +}); + +var Key = new function() { + + var keys = { + 8: 'backspace', + 9: 'tab', + 13: 'enter', + 16: 'shift', + 17: 'control', + 18: 'option', + 19: 'pause', + 20: 'caps-lock', + 27: 'escape', + 32: 'space', + 35: 'end', + 36: 'home', + 37: 'left', + 38: 'up', + 39: 'right', + 40: 'down', + 46: 'delete', + 91: 'command', + 93: 'command', + 224: 'command' + }, + + modifiers = Base.merge({ + shift: false, + control: false, + option: false, + command: false, + capsLock: false, + space: false + }), + + charCodeMap = {}, + keyMap = {}, + downCode; + + function handleKey(down, keyCode, charCode, event) { + var character = String.fromCharCode(charCode), + key = keys[keyCode] || character.toLowerCase(), + type = down ? 'keydown' : 'keyup', + view = View._focused, + scope = view && view.isVisible() && view._scope, + tool = scope && scope._tool; + keyMap[key] = down; + if (tool && tool.responds(type)) { + tool.fire(type, new KeyEvent(down, key, character, event)); + if (view) + view.draw(true); + } + } + + DomEvent.add(document, { + keydown: function(event) { + var code = event.which || event.keyCode; + var key = keys[code], name; + if (key) { + if ((name = Base.camelize(key)) in modifiers) + modifiers[name] = true; + charCodeMap[code] = 0; + handleKey(true, code, null, event); + } else { + downCode = code; + } + }, + + keypress: function(event) { + if (downCode != null) { + var code = event.which || event.keyCode; + charCodeMap[downCode] = code; + handleKey(true, downCode, code, event); + downCode = null; + } + }, + + keyup: function(event) { + var code = event.which || event.keyCode, + key = keys[code], name; + if (key && (name = Base.camelize(key)) in modifiers) + modifiers[name] = false; + if (charCodeMap[code] != null) { + handleKey(false, code, charCodeMap[code], event); + delete charCodeMap[code]; + } + } + }); + + return { + modifiers: modifiers, + + isDown: function(key) { + return !!keyMap[key]; + } + }; +}; + +var MouseEvent = Event.extend({ + _class: 'MouseEvent', + + initialize: function MouseEvent(type, event, point, target, delta) { + Event.call(this, event); + this.type = type; + this.point = point; + this.target = target; + this.delta = delta; + }, + + toString: function() { + return "{ type: '" + this.type + + "', point: " + this.point + + ', target: ' + this.target + + (this.delta ? ', delta: ' + this.delta : '') + + ', modifiers: ' + this.getModifiers() + + ' }'; + } +}); + + Base.extend(Callback, { + _class: 'Palette', + _events: [ 'onChange' ], + + initialize: function Palette(title, components, values) { + var parent = DomElement.find('.palettejs-panel') + || DomElement.find('body').appendChild( + DomElement.create('div', { 'class': 'palettejs-panel' })); + this._element = parent.appendChild( + DomElement.create('table', { 'class': 'palettejs-pane' })), + this._title = title; + if (!values) + values = {}; + for (var name in (this._components = components)) { + var component = components[name]; + if (!(component instanceof Component)) { + if (component.value == null) + component.value = values[name]; + component.name = name; + component = components[name] = new Component(component); + } + this._element.appendChild(component._element); + component._palette = this; + if (values[name] === undefined) + values[name] = component.value; + } + this._values = Base.each(values, function(value, name) { + var component = components[name]; + if (component) { + Base.define(values, name, { + enumerable: true, + configurable: true, + get: function() { + return component._value; + }, + set: function(val) { + component.setValue(val); + } + }); + } + }); + if (window.paper) + paper.palettes.push(this); + }, + + reset: function() { + for (var i in this._components) + this._components[i].reset(); + }, + + remove: function() { + DomElement.remove(this._element); + } +}); + +var Component = Base.extend(Callback, { + _class: 'Component', + _events: [ 'onChange', 'onClick' ], + + _types: { + 'boolean': { + type: 'checkbox', + value: 'checked' + }, + + string: { + type: 'text' + }, + + number: { + type: 'number', + number: true + }, + + button: { + type: 'button' + }, + + text: { + tag: 'div', + value: 'text' + }, + + slider: { + type: 'range', + number: true + }, + + list: { + tag: 'select', + + options: function() { + DomElement.removeChildren(this._inputItem); + DomElement.create(Base.each(this._options, function(option) { + this.push('option', { value: option, text: option }); + }, []), this._inputItem); + } + } + }, + + initialize: function Component(obj) { + this._type = obj.type in this._types + ? obj.type + : 'options' in obj + ? 'list' + : 'onClick' in obj + ? 'button' + : typeof obj.value; + this._info = this._types[this._type] || { type: this._type }; + var that = this, + fireChange = false; + this._inputItem = DomElement.create(this._info.tag || 'input', { + type: this._info.type, + events: { + change: function() { + that.setValue( + DomElement.get(this, that._info.value || 'value')); + if (fireChange) { + that._palette.fire('change', that, that.name, that._value); + that.fire('change', that._value); + } + }, + click: function() { + that.fire('click'); + } + } + }); + this._element = DomElement.create('tr', [ + this._labelItem = DomElement.create('td'), + 'td', [this._inputItem] + ]); + Base.each(obj, function(value, key) { + this[key] = value; + }, this); + this._defaultValue = this._value; + fireChange = true; + }, + + getType: function() { + return this._type; + }, + + getLabel: function() { + return this._label; + }, + + setLabel: function(label) { + this._label = label; + DomElement.set(this._labelItem, 'text', label + ':'); + }, + + getOptions: function() { + return this._options; + }, + + setOptions: function(options) { + this._options = options; + if (this._info.options) + this._info.options.call(this); + }, + + getValue: function() { + return this._value; + }, + + setValue: function(value) { + var key = this._info.value || 'value'; + DomElement.set(this._inputItem, key, value); + value = DomElement.get(this._inputItem, key); + this._value = this._info.number ? parseFloat(value, 10) : value; + }, + + getRange: function() { + return [parseFloat(DomElement.get(this._inputItem, 'min')), + parseFloat(DomElement.get(this._inputItem, 'max'))]; + }, + + setRange: function(min, max) { + var range = Array.isArray(min) ? min : [min, max]; + DomElement.set(this._inputItem, { min: range[0], max: range[1] }); + }, + + getMin: function() { + return this.getRange()[0]; + }, + + setMin: function(min) { + this.setRange(min, this.getMax()); + }, + + getMax: function() { + return this.getRange()[1]; + }, + + setMax: function(max) { + this.setRange(this.getMin(), max); + }, + + getStep: function() { + return parseFloat(DomElement.get(this._inputItem, 'step')); + }, + + setStep: function(step) { + DomElement.set(this._inputItem, 'step', step); + }, + + reset: function() { + this.setValue(this._defaultValue); + } +}); + +var ToolEvent = Event.extend({ + _class: 'ToolEvent', + _item: null, + + initialize: function ToolEvent(tool, type, event) { + this.tool = tool; + this.type = type; + this.event = event; + }, + + _choosePoint: function(point, toolPoint) { + return point ? point : toolPoint ? toolPoint.clone() : null; + }, + + getPoint: function() { + return this._choosePoint(this._point, this.tool._point); + }, + + setPoint: function(point) { + this._point = point; + }, + + getLastPoint: function() { + return this._choosePoint(this._lastPoint, this.tool._lastPoint); + }, + + setLastPoint: function(lastPoint) { + this._lastPoint = lastPoint; + }, + + getDownPoint: function() { + return this._choosePoint(this._downPoint, this.tool._downPoint); + }, + + setDownPoint: function(downPoint) { + this._downPoint = downPoint; + }, + + getMiddlePoint: function() { + if (!this._middlePoint && this.tool._lastPoint) { + return this.tool._point.add(this.tool._lastPoint).divide(2); + } + return this.middlePoint; + }, + + setMiddlePoint: function(middlePoint) { + this._middlePoint = middlePoint; + }, + + getDelta: function() { + return !this._delta && this.tool._lastPoint + ? this.tool._point.subtract(this.tool._lastPoint) + : this._delta; + }, + + setDelta: function(delta) { + this._delta = delta; + }, + + getCount: function() { + return /^mouse(down|up)$/.test(this.type) + ? this.tool._downCount + : this.tool._count; + }, + + setCount: function(count) { + this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count'] + = count; + }, + + getItem: function() { + if (!this._item) { + var result = this.tool._scope.project.hitTest(this.getPoint()); + if (result) { + var item = result.item, + parent = item._parent; + while (/^(group|compound-path)$/.test(parent._type)) { + item = parent; + parent = parent._parent; + } + this._item = item; + } + } + return this._item; + }, + setItem: function(item) { + this._item = item; + }, + + toString: function() { + return '{ type: ' + this.type + + ', point: ' + this.getPoint() + + ', count: ' + this.getCount() + + ', modifiers: ' + this.getModifiers() + + ' }'; + } +}); + +var Tool = PaperScopeItem.extend({ + _class: 'Tool', + _list: 'tools', + _reference: '_tool', + _events: [ 'onActivate', 'onDeactivate', 'onEditOptions', + 'onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove', + 'onKeyDown', 'onKeyUp' ], + + initialize: function Tool(props) { + PaperScopeItem.call(this); + this._firstMove = true; + this._count = 0; + this._downCount = 0; + this._set(props); + }, + + getMinDistance: function() { + return this._minDistance; + }, + + setMinDistance: function(minDistance) { + this._minDistance = minDistance; + if (this._minDistance != null && this._maxDistance != null + && this._minDistance > this._maxDistance) { + this._maxDistance = this._minDistance; + } + }, + + getMaxDistance: function() { + return this._maxDistance; + }, + + setMaxDistance: function(maxDistance) { + this._maxDistance = maxDistance; + if (this._minDistance != null && this._maxDistance != null + && this._maxDistance < this._minDistance) { + this._minDistance = maxDistance; + } + }, + + getFixedDistance: function() { + return this._minDistance == this._maxDistance + ? this._minDistance : null; + }, + + setFixedDistance: function(distance) { + this._minDistance = distance; + this._maxDistance = distance; + }, + + _updateEvent: function(type, point, minDistance, maxDistance, start, + needsChange, matchMaxDistance) { + if (!start) { + if (minDistance != null || maxDistance != null) { + var minDist = minDistance != null ? minDistance : 0, + vector = point.subtract(this._point), + distance = vector.getLength(); + if (distance < minDist) + return false; + var maxDist = maxDistance != null ? maxDistance : 0; + if (maxDist != 0) { + if (distance > maxDist) { + point = this._point.add(vector.normalize(maxDist)); + } else if (matchMaxDistance) { + return false; + } + } + } + if (needsChange && point.equals(this._point)) + return false; + } + this._lastPoint = start && type == 'mousemove' ? point : this._point; + this._point = point; + switch (type) { + case 'mousedown': + this._lastPoint = this._downPoint; + this._downPoint = this._point; + this._downCount++; + break; + case 'mouseup': + this._lastPoint = this._downPoint; + break; + } + this._count = start ? 0 : this._count + 1; + return true; + }, + + _fireEvent: function(type, event) { + var sets = paper.project._removeSets; + if (sets) { + if (type === 'mouseup') + sets.mousedrag = null; + var set = sets[type]; + if (set) { + for (var id in set) { + var item = set[id]; + for (var key in sets) { + var other = sets[key]; + if (other && other != set) + delete other[item._id]; + } + item.remove(); + } + sets[type] = null; + } + } + return this.responds(type) + && this.fire(type, new ToolEvent(this, type, event)); + }, + + _onHandleEvent: function(type, point, event) { + paper = this._scope; + var called = false; + switch (type) { + case 'mousedown': + this._updateEvent(type, point, null, null, true, false, false); + called = this._fireEvent(type, event); + break; + case 'mousedrag': + var needsChange = false, + matchMaxDistance = false; + while (this._updateEvent(type, point, this.minDistance, + this.maxDistance, false, needsChange, matchMaxDistance)) { + called = this._fireEvent(type, event) || called; + needsChange = true; + matchMaxDistance = true; + } + break; + case 'mouseup': + if (!point.equals(this._point) + && this._updateEvent('mousedrag', point, this.minDistance, + this.maxDistance, false, false, false)) { + called = this._fireEvent('mousedrag', event); + } + this._updateEvent(type, point, null, this.maxDistance, false, + false, false); + called = this._fireEvent(type, event) || called; + this._updateEvent(type, point, null, null, true, false, false); + this._firstMove = true; + break; + case 'mousemove': + while (this._updateEvent(type, point, this.minDistance, + this.maxDistance, this._firstMove, true, false)) { + called = this._fireEvent(type, event) || called; + this._firstMove = false; + } + break; + } + return called; + } + +}); + +var CanvasProvider = { + canvases: [], + + getCanvas: function(width, height) { + var size = height === undefined ? width : new Size(width, height), + canvas, + init = true; + if (this.canvases.length) { + canvas = this.canvases.pop(); + } else { + canvas = document.createElement('canvas'); + + } + var ctx = canvas.getContext('2d'); + ctx.save(); + if (canvas.width === size.width && canvas.height === size.height) { + if (init) + ctx.clearRect(0, 0, size.width + 1, size.height + 1); + } else { + canvas.width = size.width; + canvas.height = size.height; + } + return canvas; + }, + + getContext: function(width, height) { + return this.getCanvas(width, height).getContext('2d'); + }, + + release: function(obj) { + var canvas = obj.canvas ? obj.canvas : obj; + canvas.getContext('2d').restore(); + this.canvases.push(canvas); + } +}; + +var BlendMode = new function() { + var min = Math.min, + max = Math.max, + abs = Math.abs, + sr, sg, sb, sa, + br, bg, bb, ba, + dr, dg, db; + + function getLum(r, g, b) { + return 0.2989 * r + 0.587 * g + 0.114 * b; + } + + function setLum(r, g, b, l) { + var d = l - getLum(r, g, b); + dr = r + d; + dg = g + d; + db = b + d; + var l = getLum(dr, dg, db), + mn = min(dr, dg, db), + mx = max(dr, dg, db); + if (mn < 0) { + var lmn = l - mn; + dr = l + (dr - l) * l / lmn; + dg = l + (dg - l) * l / lmn; + db = l + (db - l) * l / lmn; + } + if (mx > 255) { + var ln = 255 - l, + mxl = mx - l; + dr = l + (dr - l) * ln / mxl; + dg = l + (dg - l) * ln / mxl; + db = l + (db - l) * ln / mxl; + } + } + + function getSat(r, g, b) { + return max(r, g, b) - min(r, g, b); + } + + function setSat(r, g, b, s) { + var col = [r, g, b], + mx = max(r, g, b), + mn = min(r, g, b), + md; + mn = mn === r ? 0 : mn === g ? 1 : 2; + mx = mx === r ? 0 : mx === g ? 1 : 2; + md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0; + if (col[mx] > col[mn]) { + col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]); + col[mx] = s; + } else { + col[md] = col[mx] = 0; + } + col[mn] = 0; + dr = col[0]; + dg = col[1]; + db = col[2]; + } + + var modes = { + multiply: function() { + dr = br * sr / 255; + dg = bg * sg / 255; + db = bb * sb / 255; + }, + + screen: function() { + dr = br + sr - (br * sr / 255); + dg = bg + sg - (bg * sg / 255); + db = bb + sb - (bb * sb / 255); + }, + + overlay: function() { + dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255; + dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255; + db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255; + }, + + 'soft-light': function() { + var t = sr * br / 255; + dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255; + t = sg * bg / 255; + dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255; + t = sb * bb / 255; + db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255; + }, + + 'hard-light': function() { + dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255; + dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255; + db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255; + }, + + 'color-dodge': function() { + dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr)); + dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg)); + db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb)); + }, + + 'color-burn': function() { + dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr); + dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg); + db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb); + }, + + darken: function() { + dr = br < sr ? br : sr; + dg = bg < sg ? bg : sg; + db = bb < sb ? bb : sb; + }, + + lighten: function() { + dr = br > sr ? br : sr; + dg = bg > sg ? bg : sg; + db = bb > sb ? bb : sb; + }, + + difference: function() { + dr = br - sr; + if (dr < 0) + dr = -dr; + dg = bg - sg; + if (dg < 0) + dg = -dg; + db = bb - sb; + if (db < 0) + db = -db; + }, + + exclusion: function() { + dr = br + sr * (255 - br - br) / 255; + dg = bg + sg * (255 - bg - bg) / 255; + db = bb + sb * (255 - bb - bb) / 255; + }, + + hue: function() { + setSat(sr, sg, sb, getSat(br, bg, bb)); + setLum(dr, dg, db, getLum(br, bg, bb)); + }, + + saturation: function() { + setSat(br, bg, bb, getSat(sr, sg, sb)); + setLum(dr, dg, db, getLum(br, bg, bb)); + }, + + luminosity: function() { + setLum(br, bg, bb, getLum(sr, sg, sb)); + }, + + color: function() { + setLum(sr, sg, sb, getLum(br, bg, bb)); + }, + + add: function() { + dr = min(br + sr, 255); + dg = min(bg + sg, 255); + db = min(bb + sb, 255); + }, + + subtract: function() { + dr = max(br - sr, 0); + dg = max(bg - sg, 0); + db = max(bb - sb, 0); + }, + + average: function() { + dr = (br + sr) / 2; + dg = (bg + sg) / 2; + db = (bb + sb) / 2; + }, + + negation: function() { + dr = 255 - abs(255 - sr - br); + dg = 255 - abs(255 - sg - bg); + db = 255 - abs(255 - sb - bb); + } + }; + + var ctx = CanvasProvider.getContext(1, 1); + function testMode(mode) { + ctx.save(); + var darken = mode === 'darken', + ok = false; + ctx.fillStyle = darken ? '#300' : '#a00'; + ctx.fillRect(0, 0, 1, 1); + ctx.globalCompositeOperation = mode; + if (ctx.globalCompositeOperation === mode) { + ctx.fillStyle = darken ? '#a00' : '#300'; + ctx.fillRect(0, 0, 1, 1); + ok = ctx.getImageData(0, 0, 1, 1).data[0] !== (darken ? 170 : 51); + } + ctx.restore(); + return ok; + } + this.nativeModes = testMode('multiply') && Base.each(modes, + function(func, mode) { + this[mode] = testMode(mode); + }, {}); + CanvasProvider.release(ctx); + + this.process = function(mode, srcContext, dstContext, alpha, offset) { + var srcCanvas = srcContext.canvas, + normal = mode === 'normal'; + if (normal || this.nativeModes[mode]) { + dstContext.save(); + dstContext.setTransform(1, 0, 0, 1, 0, 0); + dstContext.globalAlpha = alpha; + if (!normal) + dstContext.globalCompositeOperation = mode; + dstContext.drawImage(srcCanvas, offset.x, offset.y); + dstContext.restore(); + } else { + var process = modes[mode]; + if (!process) + return; + var dstData = dstContext.getImageData(offset.x, offset.y, + srcCanvas.width, srcCanvas.height), + dst = dstData.data, + src = srcContext.getImageData(0, 0, + srcCanvas.width, srcCanvas.height).data; + for (var i = 0, l = dst.length; i < l; i += 4) { + sr = src[i]; + br = dst[i]; + sg = src[i + 1]; + bg = dst[i + 1]; + sb = src[i + 2]; + bb = dst[i + 2]; + sa = src[i + 3]; + ba = dst[i + 3]; + process(); + var a1 = sa * alpha / 255, + a2 = 1 - a1; + dst[i] = a1 * dr + a2 * br; + dst[i + 1] = a1 * dg + a2 * bg; + dst[i + 2] = a1 * db + a2 * bb; + dst[i + 3] = sa * alpha + a2 * ba; + } + dstContext.putImageData(dstData, offset.x, offset.y); + } + }; +}; + +var SVGStyles = Base.each({ + fillColor: ['fill', 'color'], + strokeColor: ['stroke', 'color'], + strokeWidth: ['stroke-width', 'number'], + strokeCap: ['stroke-linecap', 'string'], + strokeJoin: ['stroke-linejoin', 'string'], + miterLimit: ['stroke-miterlimit', 'number'], + dashArray: ['stroke-dasharray', 'array'], + dashOffset: ['stroke-dashoffset', 'number'], + font: ['font-family', 'string'], + fontSize: ['font-size', 'number'], + justification: ['text-anchor', 'lookup', { + left: 'start', + center: 'middle', + right: 'end' + }], + opacity: ['opacity', 'number'], + blendMode: ['mix-blend-mode', 'string'] +}, function(entry, key) { + var part = Base.capitalize(key), + lookup = entry[2]; + this[key] = { + type: entry[1], + property: key, + attribute: entry[0], + toSVG: lookup, + fromSVG: lookup && Base.each(lookup, function(value, name) { + this[value] = name; + }, {}), + get: 'get' + part, + set: 'set' + part + }; +}, {}); + +var SVGNamespaces = { + href: 'http://www.w3.org/1999/xlink', + xlink: 'http://www.w3.org/2000/xmlns' +}; + +new function() { + var formatter = Formatter.instance; + + function setAttributes(node, attrs) { + for (var key in attrs) { + var val = attrs[key], + namespace = SVGNamespaces[key]; + if (typeof val === 'number') + val = formatter.number(val); + if (namespace) { + node.setAttributeNS(namespace, key, val); + } else { + node.setAttribute(key, val); + } + } + return node; + } + + function createElement(tag, attrs) { + return setAttributes( + document.createElementNS('http://www.w3.org/2000/svg', tag), attrs); + } + + function getDistance(segments, index1, index2) { + return segments[index1]._point.getDistance(segments[index2]._point); + } + + function getTransform(item, coordinates) { + var matrix = item._matrix, + trans = matrix.getTranslation(), + attrs = {}; + if (coordinates) { + matrix = matrix.shiftless(); + var point = matrix._inverseTransform(trans); + attrs.x = point.x; + attrs.y = point.y; + trans = null; + } + if (matrix.isIdentity()) + return attrs; + var decomposed = matrix.decompose(); + if (decomposed && !decomposed.shearing) { + var parts = [], + angle = decomposed.rotation, + scale = decomposed.scaling; + if (trans && !trans.isZero()) + parts.push('translate(' + formatter.point(trans) + ')'); + if (!Numerical.isZero(scale.x - 1) || !Numerical.isZero(scale.y - 1)) + parts.push('scale(' + formatter.point(scale) +')'); + if (angle) + parts.push('rotate(' + formatter.number(angle) + ')'); + attrs.transform = parts.join(' '); + } else { + attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')'; + } + return attrs; + } + + function determineAngle(path, segments, type, center) { + var topCenter = type === 'rect' + ? segments[1]._point.add(segments[2]._point).divide(2) + : type === 'roundrect' + ? segments[3]._point.add(segments[4]._point).divide(2) + : type === 'circle' || type === 'ellipse' + ? segments[1]._point + : null; + var angle = topCenter && topCenter.subtract(center).getAngle() + 90; + return Numerical.isZero(angle || 0) ? 0 : angle; + } + + function determineType(path, segments) { + function isColinear(i, j) { + var seg1 = segments[i], + seg2 = seg1.getNext(), + seg3 = segments[j], + seg4 = seg3.getNext(); + return seg1._handleOut.isZero() && seg2._handleIn.isZero() + && seg3._handleOut.isZero() && seg4._handleIn.isZero() + && seg2._point.subtract(seg1._point).isColinear( + seg4._point.subtract(seg3._point)); + } + + function isArc(i) { + var segment = segments[i], + next = segment.getNext(), + handle1 = segment._handleOut, + handle2 = next._handleIn, + kappa = Numerical.KAPPA; + if (handle1.isOrthogonal(handle2)) { + var from = segment._point, + to = next._point, + corner = new Line(from, handle1, true).intersect( + new Line(to, handle2, true), true); + return corner && Numerical.isZero(handle1.getLength() / + corner.subtract(from).getLength() - kappa) + && Numerical.isZero(handle2.getLength() / + corner.subtract(to).getLength() - kappa); + } + } + + if (path.isPolygon()) { + return segments.length === 4 && path._closed + && isColinear(0, 2) && isColinear(1, 3) + ? 'rect' + : segments.length === 0 + ? 'empty' + : segments.length >= 3 + ? path._closed ? 'polygon' : 'polyline' + : 'line'; + } else if (path._closed) { + if (segments.length === 8 + && isArc(0) && isArc(2) && isArc(4) && isArc(6) + && isColinear(1, 5) && isColinear(3, 7)) { + return 'roundrect'; + } else if (segments.length === 4 + && isArc(0) && isArc(1) && isArc(2) && isArc(3)) { + return Numerical.isZero(getDistance(segments, 0, 2) + - getDistance(segments, 1, 3)) + ? 'circle' + : 'ellipse'; + } + } + return 'path'; + } + + function exportGroup(item) { + var attrs = getTransform(item), + children = item._children; + var node = createElement('g', attrs); + for (var i = 0, l = children.length; i < l; i++) { + var child = children[i]; + var childNode = exportSVG(child); + if (childNode) { + if (child.isClipMask()) { + var clip = createElement('clipPath'); + clip.appendChild(childNode); + setDefinition(child, clip, 'clip'); + setAttributes(node, { + 'clip-path': 'url(#' + clip.id + ')' + }); + } else { + node.appendChild(childNode); + } + } + } + return node; + } + + function exportRaster(item) { + var attrs = getTransform(item, true), + size = item.getSize(); + attrs.x -= size.width / 2; + attrs.y -= size.height / 2; + attrs.width = size.width; + attrs.height = size.height; + attrs.href = item.toDataURL(); + return createElement('image', attrs); + } + + function exportPath(item) { + var segments = item._segments, + center = item.getPosition(true), + type = determineType(item, segments), + angle = determineAngle(item, segments, type, center), + attrs; + switch (type) { + case 'empty': + return null; + case 'path': + var data = item.getPathData(); + attrs = data && { d: data }; + break; + case 'polyline': + case 'polygon': + var parts = []; + for(i = 0, l = segments.length; i < l; i++) + parts.push(formatter.point(segments[i]._point)); + attrs = { + points: parts.join(' ') + }; + break; + case 'rect': + var width = getDistance(segments, 0, 3), + height = getDistance(segments, 0, 1), + point = segments[1]._point.rotate(-angle, center); + attrs = { + x: point.x, + y: point.y, + width: width, + height: height + }; + break; + case 'roundrect': + type = 'rect'; + var width = getDistance(segments, 1, 6), + height = getDistance(segments, 0, 3), + rx = (width - getDistance(segments, 0, 7)) / 2, + ry = (height - getDistance(segments, 1, 2)) / 2, + left = segments[3]._point, + right = segments[4]._point, + point = left.subtract(right.subtract(left).normalize(rx)) + .rotate(-angle, center); + attrs = { + x: point.x, + y: point.y, + width: width, + height: height, + rx: rx, + ry: ry + }; + break; + case'line': + var first = segments[0]._point, + last = segments[segments.length - 1]._point; + attrs = { + x1: first.x, + y1: first.y, + x2: last.x, + y2: last.y + }; + break; + case 'circle': + var radius = getDistance(segments, 0, 2) / 2; + attrs = { + cx: center.x, + cy: center.y, + r: radius + }; + break; + case 'ellipse': + var rx = getDistance(segments, 2, 0) / 2, + ry = getDistance(segments, 3, 1) / 2; + attrs = { + cx: center.x, + cy: center.y, + rx: rx, + ry: ry + }; + break; + } + if (angle) { + attrs.transform = 'rotate(' + formatter.number(angle) + ',' + + formatter.point(center) + ')'; + item._gradientMatrix = new Matrix().rotate(-angle, center); + } + return createElement(type, attrs); + } + + function exportCompoundPath(item) { + var attrs = getTransform(item, true); + var data = item.getPathData(); + if (data) + attrs.d = data; + return createElement('path', attrs); + } + + function exportPlacedSymbol(item) { + var attrs = getTransform(item, true), + symbol = item.getSymbol(), + symbolNode = getDefinition(symbol, 'symbol'); + definition = symbol.getDefinition(), + bounds = definition.getBounds(); + if (!symbolNode) { + symbolNode = createElement('symbol', { + viewBox: formatter.rectangle(bounds) + }); + symbolNode.appendChild(exportSVG(definition)); + setDefinition(symbol, symbolNode, 'symbol'); + } + attrs.href = '#' + symbolNode.id; + attrs.x += bounds.x; + attrs.y += bounds.y; + attrs.width = formatter.number(bounds.width); + attrs.height = formatter.number(bounds.height); + return createElement('use', attrs); + } + + function exportGradient(color, item) { + var gradientNode = getDefinition(color, 'color'); + if (!gradientNode) { + var gradient = color.getGradient(), + radial = gradient._radial, + matrix = item._gradientMatrix, + origin = color.getOrigin().transform(matrix), + destination = color.getDestination().transform(matrix), + attrs; + if (radial) { + attrs = { + cx: origin.x, + cy: origin.y, + r: origin.getDistance(destination) + }; + var highlight = color.getHighlight(); + if (highlight) { + highlight = highlight.transform(matrix); + attrs.fx = highlight.x; + attrs.fy = highlight.y; + } + } else { + attrs = { + x1: origin.x, + y1: origin.y, + x2: destination.x, + y2: destination.y + }; + } + attrs.gradientUnits = 'userSpaceOnUse'; + gradientNode = createElement( + (radial ? 'radial' : 'linear') + 'Gradient', attrs); + var stops = gradient._stops; + for (var i = 0, l = stops.length; i < l; i++) { + var stop = stops[i], + stopColor = stop._color, + alpha = stopColor.getAlpha(); + attrs = { + offset: stop._rampPoint, + 'stop-color': stopColor.toCSS(true) + }; + if (alpha < 1) + attrs['stop-opacity'] = alpha; + gradientNode.appendChild(createElement('stop', attrs)); + } + setDefinition(color, gradientNode, 'color'); + } + return 'url(#' + gradientNode.id + ')'; + } + + function exportText(item) { + var node = createElement('text', getTransform(item, true)); + node.textContent = item._content; + return node; + } + + var exporters = { + group: exportGroup, + layer: exportGroup, + raster: exportRaster, + path: exportPath, + 'compound-path': exportCompoundPath, + 'placed-symbol': exportPlacedSymbol, + 'point-text': exportText + }; + + function applyStyle(item, node) { + var attrs = {}, + parent = item.getParent(); + + if (item._name != null) + attrs.id = item._name; + + Base.each(SVGStyles, function(entry) { + var get = entry.get, + type = entry.type, + value = item[get](); + if (!parent || !Base.equals(parent[get](), value)) { + if (type === 'color' && value != null) { + var alpha = value.getAlpha(); + if (alpha < 1) + attrs[entry.attribute + '-opacity'] = alpha; + } + attrs[entry.attribute] = value == null + ? 'none' + : type === 'number' + ? formatter.number(value) + : type === 'color' + ? value.gradient + ? exportGradient(value, item) + : value.toCSS(true) + : type === 'array' + ? value.join(',') + : type === 'lookup' + ? entry.toSVG[value] + : value; + } + }); + + if (attrs.opacity === 1) + delete attrs.opacity; + + if (item._visibility != null && !item._visibility) + attrs.visibility = 'hidden'; + + delete item._gradientMatrix; + return setAttributes(node, attrs); + } + + var definitions; + function getDefinition(item, type) { + if (!definitions) + definitions = { ids: {}, svgs: {} }; + return item && definitions.svgs[type + '-' + item._id]; + } + + function setDefinition(item, node, type) { + if (!definitions) + getDefinition(); + var id = definitions.ids[type] = (definitions.ids[type] || 0) + 1; + node.id = type + '-' + id; + definitions.svgs[type + '-' + item._id] = node; + } + + function exportDefinitions(node) { + if (!definitions) + return node; + var svg = node.nodeName.toLowerCase() === 'svg' && node, + defs = null; + for (var i in definitions.svgs) { + if (!defs) { + if (!svg) { + svg = createElement('svg'); + svg.appendChild(node); + } + defs = svg.insertBefore(createElement('defs'), svg.firstChild); + } + defs.appendChild(definitions.svgs[i]); + } + definitions = null; + return svg; + } + + function exportSVG(item) { + var exporter = exporters[item._type], + node = exporter && exporter(item, item._type); + if (node && item._data) + node.setAttribute('data-paper-data', JSON.stringify(item._data)); + return node && applyStyle(item, node); + } + + Item.inject({ + exportSVG: function() { + return exportDefinitions(exportSVG(this)); + } + }); + + Project.inject({ + exportSVG: function() { + var layers = this.layers, + size = this.view.getSize(), + node = createElement('svg', { + x: 0, + y: 0, + width: size.width, + height: size.height, + version: '1.1', + xmlns: 'http://www.w3.org/2000/svg', + 'xmlns:xlink': 'http://www.w3.org/1999/xlink' + }); + for (var i = 0, l = layers.length; i < l; i++) + node.appendChild(exportSVG(layers[i])); + return exportDefinitions(node); + } + }); +}; + +new function() { + + function getValue(node, name, isString, allowNull) { + var namespace = SVGNamespaces[name], + value = namespace + ? node.getAttributeNS(namespace, name) + : node.getAttribute(name); + if (value === 'null') + value = null; + return value == null + ? allowNull + ? null + : isString + ? '' + : 0 + : isString + ? value + : parseFloat(value); + } + + function getPoint(node, x, y, allowNull) { + x = getValue(node, x, false, allowNull); + y = getValue(node, y, false, allowNull); + return allowNull && x == null && y == null ? null + : new Point(x || 0, y || 0); + } + + function getSize(node, w, h, allowNull) { + w = getValue(node, w, false, allowNull); + h = getValue(node, h, false, allowNull); + return allowNull && w == null && h == null ? null + : new Size(w || 0, h || 0); + } + + function convertValue(value, type, lookup) { + return value === 'none' + ? null + : type === 'number' + ? parseFloat(value) + : type === 'array' + ? value ? value.split(/[\s,]+/g).map(parseFloat) : [] + : type === 'color' + ? getDefinition(value) || value + : type === 'lookup' + ? lookup[value] + : value; + } + + function importGroup(node, type) { + var nodes = node.childNodes, + clip = type === 'clippath', + item = clip ? new CompoundPath() : new Group(), + project = item._project, + currentStyle = project._currentStyle, + children = []; + if (!clip) { + item._transformContent = false; + item = applyAttributes(item, node); + project._currentStyle = item._style.clone(); + } + for (var i = 0, l = nodes.length; i < l; i++) { + var childNode = nodes[i], + child; + if (childNode.nodeType == 1 && (child = importSVG(childNode))) { + if (clip && child instanceof CompoundPath) { + children.push.apply(children, child.removeChildren()); + child.remove(); + } else if (!(child instanceof Symbol)) { + children.push(child); + } + } + } + item.addChildren(children); + if (clip) + item = applyAttributes(item.reduce(), node); + project._currentStyle = currentStyle; + if (clip || type === 'defs') { + item.remove(); + item = null; + } + return item; + } + + function importPoly(node, type) { + var path = new Path(), + points = node.points; + path.moveTo(points.getItem(0)); + for (var i = 1, l = points.numberOfItems; i < l; i++) + path.lineTo(points.getItem(i)); + if (type === 'polygon') + path.closePath(); + return path; + } + + function importPath(node) { + var data = node.getAttribute('d'), + path = data.match(/m/gi).length > 1 + ? new CompoundPath() + : new Path(); + path.setPathData(data); + return path; + } + + function importGradient(node, type) { + var nodes = node.childNodes, + stops = []; + for (var i = 0, l = nodes.length; i < l; i++) { + var child = nodes[i]; + if (child.nodeType == 1) + stops.push(applyAttributes(new GradientStop(), child)); + } + var isRadial = type === 'radialgradient', + gradient = new Gradient(stops, isRadial), + origin, destination, highlight; + if (isRadial) { + origin = getPoint(node, 'cx', 'cy'); + destination = origin.add(getValue(node, 'r'), 0); + highlight = getPoint(node, 'fx', 'fy', true); + } else { + origin = getPoint(node, 'x1', 'y1'); + destination = getPoint(node, 'x2', 'y2'); + } + applyAttributes( + new Color(gradient, origin, destination, highlight), node); + return null; + } + + var importers = { + g: importGroup, + svg: importGroup, + clippath: importGroup, + polygon: importPoly, + polyline: importPoly, + path: importPath, + lineargradient: importGradient, + radialgradient: importGradient, + + image: function (node) { + var raster = new Raster(getValue(node, 'href', true)); + raster.attach('load', function() { + var size = getSize(node, 'width', 'height'); + this.setSize(size); + this.translate(getPoint(node, 'x', 'y').add(size.divide(2))); + }); + return raster; + }, + + symbol: function(node, type) { + return new Symbol(importGroup(node, type), true); + }, + + defs: importGroup, + + use: function(node) { + var id = (getValue(node, 'href', true) || '').substring(1), + definition = definitions[id], + point = getPoint(node, 'x', 'y'); + return definition + ? definition instanceof Symbol + ? definition.place(point) + : definition.clone().translate(point) + : null; + }, + + circle: function(node) { + return new Path.Circle(getPoint(node, 'cx', 'cy'), + getValue(node, 'r')); + }, + + ellipse: function(node) { + var center = getPoint(node, 'cx', 'cy'), + radius = getSize(node, 'rx', 'ry'); + return new Path.Ellipse(new Rectangle(center.subtract(radius), + center.add(radius))); + }, + + rect: function(node) { + var point = getPoint(node, 'x', 'y'), + size = getSize(node, 'width', 'height'), + radius = getSize(node, 'rx', 'ry'); + return new Path.Rectangle(new Rectangle(point, size), radius); + }, + + line: function(node) { + return new Path.Line(getPoint(node, 'x1', 'y1'), + getPoint(node, 'x2', 'y2')); + }, + + text: function(node) { + var text = new PointText(getPoint(node, 'x', 'y', false) + .add(getPoint(node, 'dx', 'dy', false))); + text.setContent(node.textContent.trim() || ''); + return text; + } + }; + + function applyTransform(item, value, name, node) { + var transforms = (node.getAttribute(name) || '').split(/\)\s*/g), + matrix = new Matrix(); + for (var i = 0, l = transforms.length; i < l; i++) { + var transform = transforms[i]; + if (!transform) + break; + var parts = transform.split('('), + command = parts[0], + v = parts[1].split(/[\s,]+/g); + for (var j = 0, m = v.length; j < m; j++) + v[j] = parseFloat(v[j]); + switch (command) { + case 'matrix': + matrix.concatenate( + new Matrix(v[0], v[2], v[1], v[3], v[4], v[5])); + break; + case 'rotate': + matrix.rotate(v[0], v[1], v[2]); + break; + case 'translate': + matrix.translate(v[0], v[1]); + break; + case 'scale': + matrix.scale(v); + break; + case 'skewX': + case 'skewY': + var value = Math.tan(v[0] * Math.PI / 180), + isX = command == 'skewX'; + matrix.shear(isX ? value : 0, isX ? 0 : value); + break; + } + } + item.transform(matrix); + } + + function applyOpacity(item, value, name) { + var color = item[name === 'fill-opacity' ? 'getFillColor' + : 'getStrokeColor'](); + if (color) + color.setAlpha(parseFloat(value)); + } + + var attributes = Base.merge(Base.each(SVGStyles, function(entry) { + this[entry.attribute] = function(item, value) { + item[entry.set]( + convertValue(value, entry.type, entry.fromSVG)); + }; + }, {}), { + id: function(item, value) { + definitions[value] = item; + if (item.setName) + item.setName(value); + }, + + 'clip-path': function(item, value) { + var clip = getDefinition(value); + if (clip) { + clip = clip.clone(); + clip.setClipMask(true); + if (item instanceof Group) { + item.insertChild(0, clip); + } else { + return new Group(clip, item); + } + } + }, + + gradientTransform: applyTransform, + transform: applyTransform, + + 'fill-opacity': applyOpacity, + 'stroke-opacity': applyOpacity, + + visibility: function(item, value) { + item.setVisible(value === 'visible'); + }, + + 'stop-color': function(item, value) { + if (item.setColor) + item.setColor(value); + }, + + 'stop-opacity': function(item, value) { + if (item._color) + item._color.setAlpha(parseFloat(value)); + }, + + offset: function(item, value) { + var percentage = value.match(/(.*)%$/); + item.setRampPoint(percentage + ? percentage[1] / 100 + : parseFloat(value)); + }, + + viewBox: function(item, value, name, node, styles) { + var rect = new Rectangle(convertValue(value, 'array')), + size = getSize(node, 'width', 'height', true); + if (item instanceof Group) { + var scale = size ? rect.getSize().divide(size) : 1, + matrix = new Matrix().translate(rect.getPoint()).scale(scale); + item.transform(matrix.inverted()); + } else if (item instanceof Symbol) { + if (size) + rect.setSize(size); + var clip = getAttribute(node, 'overflow', styles) != 'visible', + group = item._definition; + if (clip && !rect.contains(group.getBounds())) { + clip = new Path.Rectangle(rect).transform(group._matrix); + clip.setClipMask(true); + group.addChild(clip); + } + } + } + }); + + function getAttribute(node, name, styles) { + var attr = node.attributes[name], + value = attr && attr.value; + if (!value) { + var style = Base.camelize(name); + value = node.style[style]; + if (!value && styles.node[style] !== styles.parent[style]) + value = styles.node[style]; + } + return !value + ? undefined + : value === 'none' + ? null + : value; + } + + function applyAttributes(item, node) { + var styles = { + node: DomElement.getStyles(node) || {}, + parent: DomElement.getStyles(node.parentNode) || {} + }; + Base.each(attributes, function(apply, name) { + var value = getAttribute(node, name, styles); + if (value !== undefined) + item = Base.pick(apply(item, value, name, node, styles), item); + }); + return item; + } + + var definitions = {}; + function getDefinition(value) { + var match = value && value.match(/\((?:#|)([^)']+)/); + return match && definitions[match[1]]; + } + + function importSVG(node, clearDefs) { + if (typeof node === 'string') + node = new DOMParser().parseFromString(node, 'image/svg+xml'); + var type = node.nodeName.toLowerCase(), + importer = importers[type], + item = importer && importer(node, type), + data = node.getAttribute('data-paper-data'); + if (item && !(item instanceof Group)) + item = applyAttributes(item, node); + if (item && data) + item._data = JSON.parse(data); + if (clearDefs) + definitions = {}; + return item; + } + + Item.inject({ + importSVG: function(node) { + return this.addChild(importSVG(node, true)); + } + }); + + Project.inject({ + importSVG: function(node) { + this.activate(); + return importSVG(node, true); + } + }); +}; + +paper = new (PaperScope.inject(Base.merge(Base.exports, { + enumerable: true, + Base: Base, + Numerical: Numerical, + DomElement: DomElement, + DomEvent: DomEvent +})))(); + +if (typeof define === 'function' && define.amd) + define(paper); + +return paper; +}; + +paper.PaperScope.prototype.PaperScript = new function() { +(function(e){return"object"==typeof exports&&"object"==typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):(e(this.acorn||(this.acorn={})),void 0)})(function(e){"use strict";function r(e){fr=e||{};for(var r in hr)fr.hasOwnProperty(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;e.length>r;++r)t+="case "+JSON.stringify(e[r])+":";t+="return true}return false;"}e=e.split(" ");var t="",n=[];e:for(var a=0;e.length>a;++a){for(var o=0;n.length>o;++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;n.length>a;++a){var i=n[a];t+="case "+i[0].length+":",r(i)}t+="}"}else r(e);return 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))&&br>o.index;)++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(14>e&&e>8||32===e||160===e)++br;else{if(!(e>=5760&&Wt.test(String.fromCharCode(e))))break;++br}}}function l(){var e=pr.charCodeAt(br+1);return e>=48&&57>=e?E(!0):(++br,i(gt))}function f(){var e=pr.charCodeAt(br+1);return Er?(++br,k()):61===e?x(Ct,2):x(kt,1)}function p(){var e=pr.charCodeAt(br+1);return 61===e?x(Ct,2):x(Ot,1)}function d(e){var r=pr.charCodeAt(br+1);return r===e?x(124===e?It:Lt,2):61===r?x(Ct,2):x(124===e?Ut:Tt,1)}function m(){var e=pr.charCodeAt(br+1);return 61===e?x(Ct,2):x(Rt,1)}function h(e){var r=pr.charCodeAt(br+1);return r===e?x(At,2):61===r?x(Ct,2):x(Et,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(Ct,t+1):x(Ft,t)):(61===r&&(t=61===pr.charCodeAt(br+2)?3:2),x(qt,t))}function b(e){var r=pr.charCodeAt(br+1);return 61===r?x(Vt,61===pr.charCodeAt(br+2)?3:2):x(61===e?wt:St,1)}function y(e){switch(e){case 46:return l();case 40:return++br,i(mt);case 41:return++br,i(ht);case 59:return++br,i(bt);case 44:return++br,i(vt);case 91:return++br,i(lt);case 93:return++br,i(ft);case 123:return++br,i(pt);case 125:return++br,i(dt);case 58:return++br,i(yt);case 63:return++br,i(xt);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(St,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(Dr);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(Ht.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(Fr,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(qr,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(qr,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(Or,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(){Dt=!1;for(var e,r=!0,n=br;;){var a=pr.charCodeAt(br);if(Yt(a))Dt&&(e+=pr.charAt(br)),++br;else{if(92!==a)break;Dt||(e=pr.slice(n,br)),Dt=!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 Dt?e:pr.slice(n,br)}function L(){var e=I(),r=jr;return Dt||(Nt(e)?r=ut[e]:(fr.forbidReserved&&(3===fr.ecmaVersion?Bt:Mt)(e)||Vr&&zt(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 F(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 O(e,r){return e.type=r,e.end=Lr,fr.locations&&(e.loc.end=Ur),fr.ranges&&(e.range[1]=Lr),e}function j(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===Dr||wr===dt||Ht.test(pr.slice(Lr,yr)))}function M(){D(bt)||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&&Xt(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!==Dr;){var n=J();r.body.push(n),t&&j(n)&&R(!0),t=!1}return O(r,"Program")}function J(){wr===kt&&g(!0);var e=wr,r=q();switch(e){case Br:case Xr:U();var n=e===Br;D(bt)||B()?r.label=null:wr!==jr?X():(r.label=lr(),M());for(var a=0;Tr.length>a;++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),O(r,n?"BreakStatement":"ContinueStatement");case Nr:return U(),M(),O(r,"DebuggerStatement");case Jr:return U(),Tr.push(Zt),r.body=J(),Tr.pop(),z(rt),r.test=P(),M(),O(r,"DoWhileStatement");case Gr:if(U(),Tr.push(Zt),z(mt),wr===bt)return G(r,null);if(wr===et){var i=q();return U(),K(i,!0),1===i.declarations.length&&D(ct)?H(r,i):G(r,i)}var i=Q(!1,!0);return D(ct)?(N(i),H(r,i)):G(r,i);case Hr:return U(),cr(r,!0);case Kr:return U(),r.test=P(),r.consequent=J(),r.alternate=D(Pr)?J():null,O(r,"IfStatement");case Qr:return Rr||t(yr,"'return' outside of function"),U(),D(bt)||B()?r.argument=null:(r.argument=Q(),M()),O(r,"ReturnStatement");case Yr:U(),r.discriminant=P(),r.cases=[],z(pt),Tr.push(_t);for(var s,c;wr!=dt;)if(wr===Mr||wr===Wr){var u=wr===Mr;s&&O(s,"SwitchCase"),r.cases.push(s=q()),s.consequent=[],U(),u?s.test=Q():(c&&t(Ir,"Multiple default clauses"),c=!0,s.test=null),z(yt)}else s||X(),s.consequent.push(J());return s&&O(s,"SwitchCase"),U(),Tr.pop(),O(r,"SwitchStatement");case Zr:return U(),Ht.test(pr.slice(Lr,yr))&&t(Lr,"Illegal newline after throw"),r.argument=Q(),M(),O(r,"ThrowStatement");case _r:if(U(),r.block=$(),r.handler=null,wr===zr){var l=q();U(),z(mt),l.param=lr(),Vr&&Xt(l.param.name)&&t(l.param.start,"Binding "+l.param.name+" in strict mode"),z(ht),l.guard=null,l.body=$(),r.handler=O(l,"CatchClause")}return r.finalizer=D($r)?$():null,r.handler||r.finalizer||t(r.start,"Missing catch or finally clause"),O(r,"TryStatement");case et:return U(),r=K(r),M(),r;case rt:return U(),r.test=P(),Tr.push(Zt),r.body=J(),Tr.pop(),O(r,"WhileStatement");case tt:return Vr&&t(yr,"'with' in strict mode"),U(),r.object=P(),r.body=J(),O(r,"WithStatement");case pt:return $();case bt:return U(),O(r,"EmptyStatement");default:var f=Cr,p=Q();if(e===jr&&"Identifier"===p.type&&D(yt)){for(var a=0;Tr.length>a;++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,O(r,"LabeledStatement")}return r.expression=p,M(),O(r,"ExpressionStatement")}}function P(){z(mt);var e=Q();return z(ht),e}function $(){var e,r=q(),t=!0,n=!1;for(r.body=[],z(pt);!D(dt);){var a=J();r.body.push(a),t&&j(a)&&(e=n,R(n=!0)),t=!1}return n&&!e&&R(!1),O(r,"BlockStatement")}function G(e,r){return e.init=r,z(bt),e.test=wr===bt?null:Q(),z(bt),e.update=wr===ht?null:Q(),z(ht),e.body=J(),Tr.pop(),O(e,"ForStatement")}function H(e,r){return e.left=r,e.right=Q(),z(ht),e.body=J(),Tr.pop(),O(e,"ForInStatement")}function K(e,r){for(e.declarations=[],e.kind="var";;){var n=q();if(n.id=lr(),Vr&&Xt(n.id.name)&&t(n.id.start,"Binding "+n.id.name+" in strict mode"),n.init=D(wt)?Q(!0,r):null,e.declarations.push(O(n,"VariableDeclarator")),!D(vt))break}return O(e,"VariableDeclaration")}function Q(e,r){var t=Y(r);if(!e&&wr===vt){var n=F(t);for(n.expressions=[t];D(vt);)n.expressions.push(Y(r));return O(n,"SequenceExpression")}return t}function Y(e){var r=Z(e);if(wr.isAssign){var t=F(r);return t.operator=Cr,t.left=r,U(),t.right=Y(e),N(r),O(t,"AssignmentExpression")}return r}function Z(e){var r=_(e);if(D(xt)){var t=F(r);return t.test=r,t.consequent=Q(!0),z(yt),t.alternate=Q(!0,e),O(t,"ConditionalExpression")}return r}function _(e){return er(rr(e),-1,e)}function er(e,r,t){var n=wr.binop;if(null!=n&&(!t||wr!==ct)&&n>r){var a=F(e);a.left=e,a.operator=Cr,U(),a.right=er(rr(t),n,t);var a=O(a,/&&|\|\|/.test(a.operator)?"LogicalExpression":"BinaryExpression");return er(a,r,t)}return e}function rr(e){if(wr.prefix){var r=q(),n=wr.isUpdate;return r.operator=Cr,r.prefix=!0,U(),r.argument=rr(e),n?N(r.argument):Vr&&"delete"===r.operator&&"Identifier"===r.argument.type&&t(r.start,"Deleting local variable in strict mode"),O(r,n?"UpdateExpression":"UnaryExpression")}for(var a=tr();wr.postfix&&!B();){var r=F(a);r.operator=Cr,r.prefix=!1,r.argument=a,N(a),U(),a=O(r,"UpdateExpression")}return a}function tr(){return nr(ar())}function nr(e,r){if(D(gt)){var t=F(e);return t.object=e,t.property=lr(!0),t.computed=!1,nr(O(t,"MemberExpression"),r)}if(D(lt)){var t=F(e);return t.object=e,t.property=Q(),t.computed=!0,z(ft),nr(O(t,"MemberExpression"),r)}if(!r&&D(mt)){var t=F(e);return t.callee=e,t.arguments=ur(ht,!1),nr(O(t,"CallExpression"),r)}return e}function ar(){switch(wr){case at:var e=q();return U(),O(e,"ThisExpression");case jr:return lr();case qr:case Or:case Fr:var e=q();return e.value=Cr,e.raw=pr.slice(yr,gr),U(),O(e,"Literal");case ot:case it:case st:var e=q();return e.value=wr.atomValue,e.raw=wr.keyword,U(),O(e,"Literal");case mt:var r=xr,t=yr;U();var n=Q();return n.start=t,n.end=gr,fr.locations&&(n.loc.start=r,n.loc.end=kr),fr.ranges&&(n.range=[t,gr]),z(ht),n;case lt:var e=q();return U(),e.elements=ur(ft,!0,!0),O(e,"ArrayExpression");case pt:return ir();case Hr:var e=q();return U(),cr(e,!1);case nt:return or();default:X()}}function or(){var e=q();return U(),e.callee=nr(ar(),!0),e.arguments=D(mt)?ur(ht,!1):[],O(e,"NewExpression")}function ir(){var e=q(),r=!0,n=!1;for(e.properties=[],U();!D(dt);){if(r)r=!1;else if(z(vt),fr.allowTrailingCommas&&D(dt))break;var a,o={key:sr()},i=!1;if(D(yt)?(o.value=Q(!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!==mt&&X(),o.value=cr(q(),!1)):X(),"Identifier"===o.key.type&&(Vr||n))for(var s=0;e.properties.length>s;++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 O(e,"ObjectExpression")}function sr(){return wr===qr||wr===Or?ar():lr(!0)}function cr(e,r){wr===jr?e.id=lr():r?X():e.id=null,e.params=[];var n=!0;for(z(mt);!D(ht);)n?n=!1:z(vt),e.params.push(lr());var a=Rr,o=Tr;if(Rr=!0,Tr=[],e.body=$(!0),Rr=a,Tr=o,Vr||e.body.body.length&&j(e.body.body[0]))for(var i=e.id?-1:0;e.params.length>i;++i){var s=0>i?e.id:e.params[i];if((zt(s.name)||Xt(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 O(e,r?"FunctionDeclaration":"FunctionExpression")}function ur(e,r,t){for(var n=[],a=!0;!D(e);){if(a)a=!1;else if(z(vt),r&&fr.allowTrailingCommas&&D(e))break;t&&wr===vt?n.push(null):n.push(Q(!0))}return n}function lr(e){var r=q();return r.name=wr===jr?Cr:e&&!fr.forbidReserved&&wr.keyword||X(),U(),O(r,"Identifier")}e.version="0.2.01";var fr,pr,dr,mr;e.parse=function(e,t){return pr=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&&r>a.index))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=e+"",dr=pr.length,r(t),o();var a={};return n.jumpTo=function(e,r){if(br=e,fr.locations){Ar=Sr=Kt.lastIndex=0;for(var t;(t=Kt.exec(pr))&&e>t.index;)++Ar,Sr=t.index+t[0].length}pr.charAt(e-1),Er=r,u()},n};var br,yr,gr,xr,kr,wr,Cr,Er,Ar,Sr,Ir,Lr,Ur,Rr,Tr,Vr,qr={type:"num"},Fr={type:"regexp"},Or={type:"string"},jr={type:"name"},Dr={type:"eof"},Br={keyword:"break"},Mr={keyword:"case",beforeExpr:!0},zr={keyword:"catch"},Xr={keyword:"continue"},Nr={keyword:"debugger"},Wr={keyword:"default"},Jr={keyword:"do",isLoop:!0},Pr={keyword:"else",beforeExpr:!0},$r={keyword:"finally"},Gr={keyword:"for",isLoop:!0},Hr={keyword:"function"},Kr={keyword:"if"},Qr={keyword:"return",beforeExpr:!0},Yr={keyword:"switch"},Zr={keyword:"throw",beforeExpr:!0},_r={keyword:"try"},et={keyword:"var"},rt={keyword:"while",isLoop:!0},tt={keyword:"with"},nt={keyword:"new",beforeExpr:!0},at={keyword:"this"},ot={keyword:"null",atomValue:null},it={keyword:"true",atomValue:!0},st={keyword:"false",atomValue:!1},ct={keyword:"in",binop:7,beforeExpr:!0},ut={"break":Br,"case":Mr,"catch":zr,"continue":Xr,"debugger":Nr,"default":Wr,"do":Jr,"else":Pr,"finally":$r,"for":Gr,"function":Hr,"if":Kr,"return":Qr,"switch":Yr,"throw":Zr,"try":_r,"var":et,"while":rt,"with":tt,"null":ot,"true":it,"false":st,"new":nt,"in":ct,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:!0},"this":at,"typeof":{keyword:"typeof",prefix:!0,beforeExpr:!0},"void":{keyword:"void",prefix:!0,beforeExpr:!0},"delete":{keyword:"delete",prefix:!0,beforeExpr:!0}},lt={type:"[",beforeExpr:!0},ft={type:"]"},pt={type:"{",beforeExpr:!0},dt={type:"}"},mt={type:"(",beforeExpr:!0},ht={type:")"},vt={type:",",beforeExpr:!0},bt={type:";",beforeExpr:!0},yt={type:":",beforeExpr:!0},gt={type:"."},xt={type:"?",beforeExpr:!0},kt={binop:10,beforeExpr:!0},wt={isAssign:!0,beforeExpr:!0},Ct={isAssign:!0,beforeExpr:!0},Et={binop:9,prefix:!0,beforeExpr:!0},At={postfix:!0,prefix:!0,isUpdate:!0},St={prefix:!0,beforeExpr:!0},It={binop:1,beforeExpr:!0},Lt={binop:2,beforeExpr:!0},Ut={binop:3,beforeExpr:!0},Rt={binop:4,beforeExpr:!0},Tt={binop:5,beforeExpr:!0},Vt={binop:6,beforeExpr:!0},qt={binop:7,beforeExpr:!0},Ft={binop:8,beforeExpr:!0},Ot={binop:10,beforeExpr:!0};e.tokTypes={bracketL:lt,bracketR:ft,braceL:pt,braceR:dt,parenL:mt,parenR:ht,comma:vt,semi:bt,colon:yt,dot:gt,question:xt,slash:kt,eq:wt,name:jr,eof:Dr,num:qr,regexp:Fr,string:Or};for(var jt in ut)e.tokTypes[jt]=ut[jt];var Dt,Bt=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"),Mt=n("class enum extends super const export import"),zt=n("implements interface let package private protected public static yield"),Xt=n("eval arguments"),Nt=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"),Wt=/[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/,Jt="\u00aa\u00b5\u00ba\u00c0-\u00d6\u00d8-\u00f6\u00f8-\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",Pt="\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=RegExp("["+Jt+"]"),Gt=RegExp("["+Jt+Pt+"]"),Ht=/[\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&&Gt.test(String.fromCharCode(e))},Zt={kind:"loop"},_t={kind:"switch"}}); + + var binaryOperators = { + '+': 'add', + '-': 'subtract', + '*': 'multiply', + '/': 'divide', + '%': 'modulo', + '==': 'equals', + '!=': 'equals' + }; + + var unaryOperators = { + '-': 'negate', + '+': null + }; + + function _$_(left, operator, right) { + var handler = binaryOperators[operator]; + if (left && left[handler]) { + var res = left[handler](right); + return operator === '!=' ? !res : res; + } + switch (operator) { + case '+': return left + right; + case '-': return left - right; + case '*': return left * right; + case '/': return left / right; + case '%': return left % right; + case '==': return left == right; + case '!=': return left != right; + } + } + + function $_(operator, value) { + var handler = unaryOperators[operator]; + if (handler && value && value[handler]) + return value[handler](); + switch (operator) { + case '+': return +value; + case '-': return -value; + } + } + + function compile(code) { + + var insertions = []; + + function getOffset(offset) { + for (var i = 0, l = insertions.length; i < l; i++) { + var insertion = insertions[i]; + if (insertion[0] >= offset) + break; + offset += insertion[1]; + } + return offset; + } + + function getCode(node) { + return code.substring(getOffset(node.range[0]), + getOffset(node.range[1])); + } + + function replaceCode(node, str) { + var start = getOffset(node.range[0]), + end = getOffset(node.range[1]); + var insert = 0; + for (var i = insertions.length - 1; i >= 0; i--) { + if (start > insertions[i][0]) { + insert = i + 1; + break; + } + } + insertions.splice(insert, 0, [start, str.length - end + start]); + code = code.substring(0, start) + str + code.substring(end); + } + + function walkAst(node) { + if (!node || node.type === 'MemberExpression' && node.computed) + return; + for (var key in node) { + if (key === 'range') + continue; + var value = node[key]; + if (Array.isArray(value)) { + for (var i = 0, l = value.length; i < l; i++) + walkAst(value[i]); + } else if (value && typeof value === 'object') { + walkAst(value); + } + } + switch (node && node.type) { + case 'BinaryExpression': + if (node.operator in binaryOperators + && node.left.type !== 'Literal') { + var left = getCode(node.left), + right = getCode(node.right); + replaceCode(node, '_$_(' + left + ', "' + node.operator + + '", ' + right + ')'); + } + break; + case 'AssignmentExpression': + if (/^.=$/.test(node.operator) + && node.left.type !== 'Literal') { + var left = getCode(node.left), + right = getCode(node.right); + replaceCode(node, left + ' = _$_(' + left + ', "' + + node.operator[0] + '", ' + right + ')'); + } + break; + case 'UpdateExpression': + if (!node.prefix) { + var arg = getCode(node.argument); + replaceCode(node, arg + ' = _$_(' + arg + ', "' + + node.operator[0] + '", 1)'); + } + break; + case 'UnaryExpression': + if (node.operator in unaryOperators + && node.argument.type !== 'Literal') { + var arg = getCode(node.argument); + replaceCode(node, '$_("' + node.operator + '", ' + + arg + ')'); + } + break; + } + } + walkAst(acorn.parse(code, { ranges: true })); + return code; + } + + function evaluate(code, scope) { + paper = scope; + var view = scope.project && scope.project.view, + res; + with (scope) { + (function() { + var onActivate, onDeactivate, onEditOptions, + onMouseDown, onMouseUp, onMouseDrag, onMouseMove, + onKeyDown, onKeyUp, onFrame, onResize; + res = eval(compile(code)); + if (/on(?:Key|Mouse)(?:Up|Down|Move|Drag)/.test(code)) { + Base.each(paper.Tool.prototype._events, function(key) { + var value = eval(key); + if (value) { + scope.getTool()[key] = value; + } + }); + } + if (view) { + view.setOnResize(onResize); + view.fire('resize', { + size: view.size, + delta: new Point() + }); + view.setOnFrame(onFrame); + view.draw(); + } + }).call(scope); + } + return res; + } + + function request(url, scope) { + var xhr = new (window.ActiveXObject || XMLHttpRequest)( + 'Microsoft.XMLHTTP'); + xhr.open('GET', url, true); + if (xhr.overrideMimeType) + xhr.overrideMimeType('text/plain'); + xhr.onreadystatechange = function() { + if (xhr.readyState === 4) { + return evaluate(xhr.responseText, scope); + } + }; + return xhr.send(null); + } + + function load() { + var scripts = document.getElementsByTagName('script'), + PaperScope = paper.PaperScope; + for (var i = 0, l = scripts.length; i < l; i++) { + var script = scripts[i]; + if (/^text\/(?:x-|)paperscript$/.test(script.type) + && !script.getAttribute('data-paper-ignore')) { + var canvas = PaperScope.getAttribute(script, 'canvas'), + scope = PaperScope.get(canvas) + || new PaperScope(script).setup(canvas); + if (script.src) { + request(script.src, scope); + } else { + evaluate(script.innerHTML, scope); + } + script.setAttribute('data-paper-ignore', true); + } + } + } + + if (document.readyState === 'complete') { + setTimeout(load); + } else { + paper.DomEvent.add(window, { load: load }); + } + + return { + compile: compile, + evaluate: evaluate, + load: load + }; + +}; + diff --git a/dist/paper-full.min.js b/dist/paper-full.min.js new file mode 100644 index 00000000..da5b00df --- /dev/null +++ b/dist/paper-full.min.js @@ -0,0 +1,37 @@ +/*! + * Paper.js v0.9.5 - The Swiss Army Knife of Vector Graphics Scripting. + * http://paperjs.org/ + * + * Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey + * http://lehni.org/ & http://jonathanpuckey.com/ + * + * Distributed under the MIT license. See LICENSE file for details. + * + * All rights reserved. + * + * Date: Wed Jun 26 19:42:04 2013 -0700 + * + *** + * + * straps.js - Class inheritance library with support for bean-style accessors + * + * Copyright (c) 2006 - 2013 Juerg Lehni + * http://lehni.org/ + * + * Distributed under the MIT license. + * + *** + * + * acorn.js + * http://marijnhaverbeke.nl/acorn/ + * + * Acorn is a tiny, fast JavaScript parser written in JavaScript, + * created by Marijn Haverbeke and released under an MIT license. + * + */ +var paper=new function(){var t=new function(){function e(t,e,n,i,s,a){function h(i,r,a,h){var r=r||(r=d(e,i))&&(r.get?r:r.value);"string"==typeof r&&"#"===r[0]&&(r=e[r.substring(1)]||r);var c,l="function"==typeof r,f=r,g=s||l?r&&r.get?i in t:t[i]:null;!(a||void 0!==r&&e.hasOwnProperty(i))||s&&g||(l&&g&&(r.base=g),l&&u&&0===r.length&&(c=i.match(/^(get|is)(([A-Z])(.*))$/))&&u.push([c[3].toLowerCase()+c[4],c[2]]),f&&!l&&f.get||(f={value:f,writable:!0}),(d(t,i)||{configurable:!0}).configurable&&(f.configurable=!0,f.enumerable=n),_(t,i,f)),!h||!l||s&&h[i]||(h[i]=function(e){return e&&t[i].apply(e,o.call(arguments,1))})}var u;if(e){u=[];for(var c in e)e.hasOwnProperty(c)&&!r.test(c)&&h(c,null,!0,a);h("toString"),h("valueOf");for(var l=0,f=u&&u.length;f>l;l++)try{var g=u[l],p=g[1];h(g[0],{get:t["get"+p]||t["is"+p],set:t["set"+p]},!0)}catch(v){}}return t}function n(e,n,i,r){try{e&&(r||void 0===r&&c(e)?h:u).call(e,n,i=i||e)}catch(s){if(s!==t.stop)throw s}return i}function i(t){return n(t,function(t,e){this[e]=t},new t.constructor)}var r=/^(statics|generics|preserve|enumerable|prototype|toString|valueOf)$/,s=Object.prototype.toString,a=Array.prototype,o=a.slice,h=a.forEach||function(t,e){for(var n=0,i=this.length;i>n;n++)t.call(e,this[n],n,this)},u=function(t,e){for(var n in this)this.hasOwnProperty(n)&&t.call(e,this[n],n,this)},c=Array.isArray=Array.isArray||function(t){return"[object Array]"===s.call(t)},l=Object.create||function(t){return{__proto__:t}},d=Object.getOwnPropertyDescriptor||function(t,e){var n=t.__lookupGetter__&&t.__lookupGetter__(e);return n?{get:n,set:t.__lookupSetter__(e),enumerable:!0,configurable:!0}:t.hasOwnProperty(e)?{value:t[e],enumerable:!0,configurable:!0,writable:!0}:null},f=Object.defineProperty||function(t,e,n){return(n.get||n.set)&&t.__defineGetter__?(n.get&&t.__defineGetter__(e,n.get),n.set&&t.__defineSetter__(e,n.set)):t[e]=n.value,t},_=function(t,e,n){return delete t[e],f(t,e,n)};return e(function(){},{inject:function(t){if(t){var n=this.prototype,i=Object.getPrototypeOf(n).constructor,r=t.statics===!0?t:t.statics;r!=t&&e(n,t,t.enumerable,i&&i.prototype,t.preserve,t.generics&&this),e(this,r,!0,i,t.preserve)}for(var s=1,a=arguments.length;a>s;s++)this.inject(arguments[s]);return this},extend:function(){for(var t,n=this,i=0,r=arguments.length;r>i&&!(t=arguments[i].initialize);i++);return t=t||function(){n.apply(this,arguments)},t.prototype=l(this.prototype),_(t.prototype,"constructor",{value:t,writable:!0,configurable:!0}),e(t,this,!0),arguments.length?this.inject.apply(t,arguments):t}},!0).inject({inject:function(){for(var t=0,n=arguments.length;n>t;t++)e(this,arguments[t],arguments[t].enumerable);return this},extend:function(){var t=l(this);return t.inject.apply(t,arguments)},each:function(t,e){return n(this,t,e)},clone:function(){return i(this)},statics:{each:n,clone:i,define:_,describe:d,create:function(t){return l(t.prototype)},isPlainObject:function(e){var n=null!=e&&e.constructor;return n&&(n===Object||n===t||"Object"===n.name)},check:function(t){return!(!t&&0!==t)},pick:function(){for(var t=0,e=arguments.length;e>t;t++)if(void 0!==arguments[t])return arguments[t];return null},stop:{}}})};t.inject({generics:!0,clone:function(){return new this.constructor(this)},toString:function(){return null!=this._id?(this._class||"Object")+(this._name?" '"+this._name+"'":" @"+this._id):"{ "+t.each(this,function(t,e){if(!/^_/.test(e)){var n=typeof t;this.push(e+": "+("number"===n?s.instance.number(t):"string"===n?"'"+t+"'":t))}},[]).join(", ")+" }"},exportJSON:function(e){return t.exportJSON(this,e)},toJSON:function(){return t.serialize(this)},_set:function(e){if(e&&t.isPlainObject(e)){for(var n in e)e.hasOwnProperty(n)&&n in this&&(this[n]=e[n]);return!0}},statics:{exports:{},extend:function ee(){var e=ee.base.apply(this,arguments),n=e.prototype._class;return n&&!t.exports[n]&&(t.exports[n]=e),e},equals:function(e,n){function i(t,e){for(var n in t)if(t.hasOwnProperty(n)&&void 0===e[n])return!1;return!0}if(e===n)return!0;if(e&&e.equals)return e.equals(n);if(n&&n.equals)return n.equals(e);if(Array.isArray(e)&&Array.isArray(n)){if(e.length!==n.length)return!1;for(var r=0,s=e.length;s>r;r++)if(!t.equals(e[r],n[r]))return!1;return!0}if(e&&"object"==typeof e&&n&&"object"==typeof n){if(!i(e,n)||!i(n,e))return!1;for(var r in e)if(e.hasOwnProperty(r)&&!t.equals(e[r],n[r]))return!1;return!0}return!1},read:function(e,n,i,r,s){if(this===t){var a=this.peek(e,n);return e._index++,e._read=1,a}var o=this.prototype,h=o._readIndex,u=n||h&&e._index||0;i||(i=e.length-u);var c=e[u];return c instanceof this||r&&null==c&&1>=i?(h&&(e._index=u+1),c&&s?c.clone():c):(c=t.create(this),h&&(c._read=!0),c=c.initialize.apply(c,u>0||ia;a++)s.push(Array.isArray(r=t[a])?this.read(r,0,0,n,i):this.read(t,a,1,n,i));return s},readNamed:function(t,e,n,i,r,s){var a=this.getNamed(t,e);return this.read(null!=a?[a]:t,n,i,r,s)},getNamed:function(e,n){var i=e[0];return void 0===e._hasObject&&(e._hasObject=1===e.length&&t.isPlainObject(i)),e._hasObject?n?i[n]:i:void 0},hasNamed:function(t,e){return!!this.getNamed(t,e)},isPlainValue:function(t){return this.isPlainObject(t)||Array.isArray(t)},serialize:function(e,n,i,r){n=n||{};var a,o=!r;if(o&&(n.formatter=new s(n.precision),r={length:0,definitions:{},references:{},add:function(t,e){var n="#"+t._id,i=this.references[n];if(!i){this.length++;var r=e.call(t),s=t._class;s&&r[0]!==s&&r.unshift(s),this.definitions[n]=r,i=this.references[n]=[n]}return i}}),e&&e._serialize){a=e._serialize(n,r);var h=e._class;!h||i||a._compact||a[0]===h||a.unshift(h)}else if(Array.isArray(e)){a=[];for(var u=0,c=e.length;c>u;u++)a[u]=t.serialize(e[u],n,i,r);i&&(a._compact=!0)}else if(t.isPlainObject(e)){a={};for(var u in e)e.hasOwnProperty(u)&&(a[u]=t.serialize(e[u],n,i,r))}else a="number"==typeof e?n.formatter.number(e,n.precision):e;return o&&r.length>0?[["dictionary",r.definitions],a]:a},deserialize:function(e,n){var i=e;if(n=n||{},Array.isArray(e)){var r=e[0],s="dictionary"===r;if(!s){if(n.dictionary&&1==e.length&&/^#/.test(r))return n.dictionary[r];r=t.exports[r]}i=[];for(var a=r?1:0,o=e.length;o>a;a++)i.push(t.deserialize(e[a],n));if(s)n.dictionary=i[0];else if(r){var h=i;i=t.create(r),r.apply(i,h)}}else if(t.isPlainObject(e)){i={};for(var u in e)i[u]=t.deserialize(e[u],n)}return i},exportJSON:function(e,n){return JSON.stringify(t.serialize(e,n))},importJSON:function(e){return t.deserialize("string"==typeof e?JSON.parse(e):e)},splice:function(t,e,n,i){var r=e&&e.length,s=void 0===n;n=s?t.length:n,n>t.length&&(n=t.length);for(var a=0;r>a;a++)e[a]._index=n+a;if(s)return t.push.apply(t,e),[];var o=[n,i];e&&o.push.apply(o,e);for(var h=t.splice.apply(t,o),a=0,u=h.length;u>a;a++)delete h[a]._index;for(var a=n+r,u=t.length;u>a;a++)t[a]._index=a;return h},merge:function(){return t.each(arguments,function(e){t.each(e,function(t,e){this[e]=t},this)},new t,!0)},capitalize:function(t){return t.replace(/\b[a-z]/g,function(t){return t.toUpperCase()})},camelize:function(t){return t.replace(/-(.)/g,function(t,e){return e.toUpperCase()})},hyphenate:function(t){return t.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()}}});var e={attach:function(e,n){if("string"!=typeof e)return t.each(e,function(t,e){this.attach(e,t)},this),void 0;var i=this._eventTypes[e];if(i){var r=this._handlers=this._handlers||{};r=r[e]=r[e]||[],-1==r.indexOf(n)&&(r.push(n),i.install&&1==r.length&&i.install.call(this,e))}},detach:function(e,n){if("string"!=typeof e)return t.each(e,function(t,e){this.detach(e,t)},this),void 0;var i,r=this._eventTypes[e],s=this._handlers&&this._handlers[e];r&&s&&(!n||-1!=(i=s.indexOf(n))&&1==s.length?(r.uninstall&&r.uninstall.call(this,e),delete this._handlers[e]):-1!=i&&s.splice(i,1))},once:function(t,e){this.attach(t,function(){e.apply(this,arguments),this.detach(t,e)})},fire:function(e,n){var i=this._handlers&&this._handlers[e];if(!i)return!1;var r=[].slice.call(arguments,1);return t.each(i,function(t){t.apply(this,r)===!1&&n&&n.stop&&n.stop()},this),!0},responds:function(t){return!(!this._handlers||!this._handlers[t])},on:"#attach",off:"#detach",trigger:"#fire",statics:{inject:function ne(){for(var e=0,n=arguments.length;n>e;e++){var i=arguments[e],r=i._events;if(r){var s={};t.each(r,function(e,n){var r="string"==typeof e,a=r?e:n,o=t.capitalize(a),h=a.substring(2).toLowerCase();s[h]=r?{}:e,a="_"+a,i["get"+o]=function(){return this[a]},i["set"+o]=function(t){t?this.attach(h,t):this[a]&&this.detach(h,this[a]),this[a]=t}}),i._eventTypes=s}ne.base.call(this,i)}return this}}},n=t.extend({_class:"PaperScope",initialize:function ie(t){if(paper=this,this.project=null,this.projects=[],this.tools=[],this.palettes=[],this._id=t&&(t.getAttribute("id")||t.src)||"paperscope-"+ie._id++,t&&t.setAttribute("id",this._id),ie._scopes[this._id]=this,!this.support){var e=Y.getContext(1,1);ie.prototype.support={nativeDash:"setLineDash"in e||"mozDash"in e,nativeBlendModes:K.nativeModes},Y.release(e)}},version:"0.9.5",getView:function(){return this.project&&this.project.view},getTool:function(){return this._tool||(this._tool=new $),this._tool},evaluate:function(t){var e=paper.PaperScript.evaluate(t,this);return V.updateFocus(),e},install:function(e){var n=this;t.each(["project","view","tool"],function(i){t.define(e,i,{configurable:!0,get:function(){return n[i]}})});for(var i in this)/^(version|_id)/.test(i)||i in e||(e[i]=this[i])},setup:function(t){return paper=this,this.project=new p(t),this},clear:function(){for(var t=this.projects.length-1;t>=0;t--)this.projects[t].remove();for(var t=this.tools.length-1;t>=0;t--)this.tools[t].remove();for(var t=this.palettes.length-1;t>=0;t--)this.palettes[t].remove()},remove:function(){this.clear(),delete n._scopes[this._id]},statics:new function(){function t(t){return t+="Attribute",function(e,n){return e[t](n)||e[t]("data-paper-"+n)}}return{_scopes:{},_id:0,get:function(t){return"object"==typeof t&&(t=t.getAttribute("id")),this._scopes[t]||null},getAttribute:t("get"),hasAttribute:t("has")}}}),r=t.extend(e,{initialize:function(t){this._scope=paper,this._index=this._scope[this._list].push(this)-1,(t||!this._scope[this._reference])&&this.activate()},activate:function(){if(!this._scope)return!1;var t=this._scope[this._reference];return t&&t!=this&&t.fire("deactivate"),this._scope[this._reference]=this,this.fire("activate",t),!0},isActive:function(){return this._scope[this._reference]===this},remove:function(){return null==this._index?!1:(t.splice(this._scope[this._list],null,this._index,1),this._scope[this._reference]==this&&(this._scope[this._reference]=null),this._scope=null,!0)}}),s=t.extend({initialize:function(t){this.precision=t||5,this.multiplier=Math.pow(10,this.precision)},number:function(t){return Math.round(t*this.multiplier)/this.multiplier},point:function(t,e){return this.number(t.x)+(e||",")+this.number(t.y)},size:function(t,e){return this.number(t.width)+(e||",")+this.number(t.height)},rectangle:function(t,e){return this.point(t,e)+(e||",")+this.size(t,e)}});s.instance=new s(5);var a=new function(){var t=[[.5773502691896257],[0,.7745966692414834],[.33998104358485626,.8611363115940526],[0,.5384693101056831,.906179845938664],[.2386191860831969,.6612093864662645,.932469514203152],[0,.4058451513773972,.7415311855993945,.9491079123427585],[.1834346424956498,.525532409916329,.7966664774136267,.9602898564975363],[0,.3242534234038089,.6133714327005904,.8360311073266358,.9681602395076261],[.14887433898163122,.4333953941292472,.6794095682990244,.8650633666889845,.9739065285171717],[0,.26954315595234496,.5190961292068118,.7301520055740494,.8870625997680953,.978228658146057],[.1252334085114689,.3678314989981802,.5873179542866175,.7699026741943047,.9041172563704749,.9815606342467192],[0,.2304583159551348,.44849275103644687,.6423493394403402,.8015780907333099,.9175983992229779,.9841830547185881],[.10805494870734367,.31911236892788974,.5152486363581541,.6872929048116855,.827201315069765,.9284348836635735,.9862838086968123],[0,.20119409399743451,.3941513470775634,.5709721726085388,.7244177313601701,.8482065834104272,.937273392400706,.9879925180204854],[.09501250983763744,.2816035507792589,.45801677765722737,.6178762444026438,.755404408355003,.8656312023878318,.9445750230732326,.9894009349916499]],e=[[1],[.8888888888888888,.5555555555555556],[.6521451548625461,.34785484513745385],[.5688888888888889,.47862867049936647,.23692688505618908],[.46791393457269104,.3607615730481386,.17132449237917036],[.4179591836734694,.3818300505051189,.27970539148927664,.1294849661688697],[.362683783378362,.31370664587788727,.22238103445337448,.10122853629037626],[.3302393550012598,.31234707704000286,.26061069640293544,.1806481606948574,.08127438836157441],[.29552422471475287,.26926671930999635,.21908636251598204,.1494513491505806,.06667134430868814],[.2729250867779006,.26280454451024665,.23319376459199048,.18629021092773426,.1255803694649046,.05566856711617366],[.24914704581340277,.2334925365383548,.20316742672306592,.16007832854334622,.10693932599531843,.04717533638651183],[.2325515532308739,.22628318026289723,.2078160475368885,.17814598076194574,.13887351021978725,.09212149983772845,.04048400476531588],[.2152638534631578,.2051984637212956,.18553839747793782,.15720316715819355,.12151857068790319,.08015808715976021,.03511946033175186],[.2025782419255613,.19843148532711158,.1861610000155622,.16626920581699392,.13957067792615432,.10715922046717194,.07036604748810812,.03075324199611727],[.1894506104550685,.18260341504492358,.16915651939500254,.14959598881657674,.12462897125553388,.09515851168249279,.062253523938647894,.027152459411754096]],n=Math.abs,i=Math.sqrt,r=Math.pow,s=Math.cos,o=Math.PI;return{TOLERANCE:1e-5,EPSILON:1e-11,KAPPA:4*(i(2)-1)/3,isZero:function(t){return n(t)<=this.EPSILON},integrate:function(n,i,r,s){for(var a=t[s-2],o=e[s-2],h=.5*(r-i),u=h+i,c=0,l=s+1>>1,d=1&s?o[c++]*n(u):0;l>c;){var f=h*a[c];d+=o[c++]*(n(u+f)+n(u-f))}return h*d},findRoot:function(t,e,i,r,s,a,o){for(var h=0;a>h;h++){var u=t(i),c=u/e(i);if(n(c)0?(s=i,i=r>=l?.5*(r+s):l):(r=i,i=l>=s?.5*(r+s):l)}},solveQuadratic:function(t,e,r,s){var a=this.EPSILON;if(n(t)=a?(s[0]=-r/e,1):n(r)o)return 0;o=i(o),t*=2;var h=0;return s[h++]=(-e-o)/t,o>0&&(s[h++]=(-e+o)/t),h},solveCubic:function(t,e,h,u,c){var l=this.EPSILON;if(n(t)0?1:-1;return c[0]=2*-m*v-e,c[1]=m*v-e,2}if(0>p){var v=i(f),y=Math.acos(_/(v*v*v))/3,w=-2*v,x=2*o/3;return c[0]=w*s(y)-e,c[1]=w*s(y+x)-e,c[2]=w*s(y-x)-e,3}var b=(_>0?-1:1)*r(n(_)+i(p),1/3);return c[0]=b+f/b-e,1}}},o=t.extend({_class:"Point",_readIndex:!0,initialize:function(t,e){var n=typeof t;if("number"===n){var i="number"==typeof e;this.x=t,this.y=i?e:t,this._read&&(this._read=i?2:1)}else"undefined"===n||null===t?(this.x=this.y=0,this._read&&(this._read=null===t?1:0)):(Array.isArray(t)?(this.x=t[0],this.y=t.length>1?t[1]:t[0]):null!=t.x?(this.x=t.x,this.y=t.y):null!=t.width?(this.x=t.width,this.y=t.height):null!=t.angle?(this.x=t.length,this.y=0,this.setAngle(t.angle)):(this.x=this.y=0,this._read&&(this._read=0)),this._read&&(this._read=1))},set:function(t,e){return this.x=t,this.y=e,this},equals:function(t){return t===this||t&&(this.x===t.x&&this.y===t.y||Array.isArray(t)&&this.x===t[0]&&this.y===t[1])||!1},clone:function(){return new o(this.x,this.y)},toString:function(){var t=s.instance;return"{ x: "+t.number(this.x)+", y: "+t.number(this.y)+" }"},_serialize:function(t){var e=t.formatter;return[e.number(this.x),e.number(this.y)]},add:function(t){return t=o.read(arguments),new o(this.x+t.x,this.y+t.y)},subtract:function(t){return t=o.read(arguments),new o(this.x-t.x,this.y-t.y)},multiply:function(t){return t=o.read(arguments),new o(this.x*t.x,this.y*t.y)},divide:function(t){return t=o.read(arguments),new o(this.x/t.x,this.y/t.y)},modulo:function(t){return t=o.read(arguments),new o(this.x%t.x,this.y%t.y)},negate:function(){return new o(-this.x,-this.y)},transform:function(t){return t?t._transformPoint(this):this},getDistance:function(t,e){t=o.read(arguments);var n=t.x-this.x,i=t.y-this.y,r=n*n+i*i;return e?r:Math.sqrt(r)},getLength:function(){var t=this.x*this.x+this.y*this.y;return arguments.length&&arguments[0]?t:Math.sqrt(t)},setLength:function(t){if(this.isZero()){var e=this._angle||0;this.set(Math.cos(e)*t,Math.sin(e)*t)}else{var n=t/this.getLength();a.isZero(n)&&this.getAngle(),this.set(this.x*n,this.y*n)}return this},normalize:function(t){void 0===t&&(t=1);var e=this.getLength(),n=0!==e?t/e:0,i=new o(this.x*n,this.y*n);return i._angle=this._angle,i},getAngle:function(){return 180*this.getAngleInRadians(arguments[0])/Math.PI},setAngle:function(t){if(t=this._angle=t*Math.PI/180,!this.isZero()){var e=this.getLength();this.set(Math.cos(t)*e,Math.sin(t)*e)}return this},getAngleInRadians:function(){if(void 0===arguments[0])return null==this._angle&&(this._angle=Math.atan2(this.y,this.x)),this._angle;var t=o.read(arguments),e=this.getLength()*t.getLength();return a.isZero(e)?0/0:Math.acos(this.dot(t)/e)},getAngleInDegrees:function(){return this.getAngle(arguments[0])},getQuadrant:function(){return this.x>=0?this.y>=0?1:4:this.y>=0?2:3},getDirectedAngle:function(t){return t=o.read(arguments),180*Math.atan2(this.cross(t),this.dot(t))/Math.PI},rotate:function(t,e){if(0===t)return this.clone();t=t*Math.PI/180;var n=e?this.subtract(e):this,i=Math.sin(t),r=Math.cos(t);return n=new o(n.x*r-n.y*i,n.y*r+n.x*i),e?n.add(e):n},isInside:function(t){return t.contains(this)},isClose:function(t,e){return this.getDistance(t)1?t[1]:t[0]):null!=t.width?(this.width=t.width,this.height=t.height):null!=t.x?(this.width=t.x,this.height=t.y):(this.width=this.height=0,this._read&&(this._read=0)),this._read&&(this._read=1))},set:function(t,e){return this.width=t,this.height=e,this},equals:function(t){return t===this||t&&(this.width===t.width&&this.height===t.height||Array.isArray(t)&&this.width===t[0]&&this.height===t[1])||!1},clone:function(){return new u(this.width,this.height)},toString:function(){var t=s.instance;return"{ width: "+t.number(this.width)+", height: "+t.number(this.height)+" }"},_serialize:function(t){var e=t.formatter;return[e.number(this.width),e.number(this.height)]},add:function(t){return t=u.read(arguments),new u(this.width+t.width,this.height+t.height)},subtract:function(t){return t=u.read(arguments),new u(this.width-t.width,this.height-t.height)},multiply:function(t){return t=u.read(arguments),new u(this.width*t.width,this.height*t.height)},divide:function(t){return t=u.read(arguments),new u(this.width/t.width,this.height/t.height)},modulo:function(t){return t=u.read(arguments),new u(this.width%t.width,this.height%t.height)},negate:function(){return new u(-this.width,-this.height)},isZero:function(){return a.isZero(this.width)&&a.isZero(this.height)},isNaN:function(){return isNaN(this.width)||isNaN(this.height)},statics:{min:function(t,e){return new u(Math.min(t.width,e.width),Math.min(t.height,e.height))},max:function(t,e){return new u(Math.max(t.width,e.width),Math.max(t.height,e.height))},random:function(){return new u(Math.random(),Math.random())}}},new function(){return t.each(["round","ceil","floor","abs"],function(t){var e=Math[t];this[t]=function(){return new u(e(this.width),e(this.height))}},{})}),c=u.extend({initialize:function(t,e,n,i){this._width=t,this._height=e,this._owner=n,this._setter=i},set:function(t,e,n){return this._width=t,this._height=e,n||this._owner[this._setter](this),this},getWidth:function(){return this._width},setWidth:function(t){this._width=t,this._owner[this._setter](this)},getHeight:function(){return this._height},setHeight:function(t){this._height=t,this._owner[this._setter](this)}}),d=t.extend({_class:"Rectangle",_readIndex:!0,initialize:function(e,n,i,r){var s=typeof e,a=0;if("number"===s?(this.x=e,this.y=n,this.width=i,this.height=r,a=4):"undefined"===s||null===e?(this.x=this.y=this.width=this.height=0,a=null===e?1:0):1===arguments.length&&(Array.isArray(e)?(this.x=e[0],this.y=e[1],this.width=e[2],this.height=e[3],a=1):void 0!==e.x||void 0!==e.width?(this.x=e.x||0,this.y=e.y||0,this.width=e.width||0,this.height=e.height||0,a=1):void 0===e.from&&void 0===e.to&&(this.x=this.y=this.width=this.height=0,this._set(e),a=1)),!a){var h=o.readNamed(arguments,"from"),c=t.peek(arguments);if(this.x=h.x,this.y=h.y,c&&void 0!==c.x||t.hasNamed(arguments,"to")){var l=o.readNamed(arguments,"to");this.width=l.x-h.x,this.height=l.y-h.y,this.width<0&&(this.x=l.x,this.width=-this.width),this.height<0&&(this.y=l.y,this.height=-this.height)}else{var d=u.read(arguments);this.width=d.width,this.height=d.height}a=arguments._index}this._read&&(this._read=a)},set:function(t,e,n,i){return this.x=t,this.y=e,this.width=n,this.height=i,this},clone:function(){return new d(this.x,this.y,this.width,this.height)},equals:function(e){return t.isPlainValue(e)&&(e=d.read(arguments)),e===this||e&&this.x===e.x&&this.y===e.y&&this.width===e.width&&this.height===e.height||!1},toString:function(){var t=s.instance;return"{ x: "+t.number(this.x)+", y: "+t.number(this.y)+", width: "+t.number(this.width)+", height: "+t.number(this.height)+" }"},_serialize:function(t){var e=t.formatter;return[e.number(this.x),e.number(this.y),e.number(this.width),e.number(this.height)]},getPoint:function(){return new(arguments[0]?o:h)(this.x,this.y,this,"setPoint")},setPoint:function(t){t=o.read(arguments),this.x=t.x,this.y=t.y},getSize:function(){return new(arguments[0]?u:c)(this.width,this.height,this,"setSize")},setSize:function(t){t=u.read(arguments),this._fixX&&(this.x+=(this.width-t.width)*this._fixX),this._fixY&&(this.y+=(this.height-t.height)*this._fixY),this.width=t.width,this.height=t.height,this._fixW=1,this._fixH=1},getLeft:function(){return this.x},setLeft:function(t){this._fixW||(this.width-=t-this.x),this.x=t,this._fixX=0},getTop:function(){return this.y},setTop:function(t){this._fixH||(this.height-=t-this.y),this.y=t,this._fixY=0},getRight:function(){return this.x+this.width},setRight:function(t){void 0!==this._fixX&&1!==this._fixX&&(this._fixW=0),this._fixW?this.x=t-this.width:this.width=t-this.x,this._fixX=1},getBottom:function(){return this.y+this.height},setBottom:function(t){void 0!==this._fixY&&1!==this._fixY&&(this._fixH=0),this._fixH?this.y=t-this.height:this.height=t-this.y,this._fixY=1},getCenterX:function(){return this.x+.5*this.width},setCenterX:function(t){this.x=t-.5*this.width,this._fixX=.5},getCenterY:function(){return this.y+.5*this.height},setCenterY:function(t){this.y=t-.5*this.height,this._fixY=.5},getCenter:function(){return new(arguments[0]?o:h)(this.getCenterX(),this.getCenterY(),this,"setCenter")},setCenter:function(t){return t=o.read(arguments),this.setCenterX(t.x),this.setCenterY(t.y),this},isEmpty:function(){return 0==this.width||0==this.height},contains:function(t){return t&&void 0!==t.width||4==(Array.isArray(t)?t:arguments).length?this._containsRectangle(d.read(arguments)):this._containsPoint(o.read(arguments))},_containsPoint:function(t){var e=t.x,n=t.y;return e>=this.x&&n>=this.y&&e<=this.x+this.width&&n<=this.y+this.height},_containsRectangle:function(t){var e=t.x,n=t.y;return e>=this.x&&n>=this.y&&e+t.width<=this.x+this.width&&n+t.height<=this.y+this.height},intersects:function(t){return t=d.read(arguments),t.x+t.width>this.x&&t.y+t.height>this.y&&t.x=this.x&&t.y+t.height>=this.y&&t.x<=this.x+this.width&&t.y<=this.y+this.height},intersect:function(t){t=d.read(arguments);var e=Math.max(this.x,t.x),n=Math.max(this.y,t.y),i=Math.min(this.x+this.width,t.x+t.width),r=Math.min(this.y+this.height,t.y+t.height);return new d(e,n,i-e,r-n)},unite:function(t){t=d.read(arguments);var e=Math.min(this.x,t.x),n=Math.min(this.y,t.y),i=Math.max(this.x+this.width,t.x+t.width),r=Math.max(this.y+this.height,t.y+t.height);return new d(e,n,i-e,r-n)},include:function(t){t=o.read(arguments);var e=Math.min(this.x,t.x),n=Math.min(this.y,t.y),i=Math.max(this.x+this.width,t.x),r=Math.max(this.y+this.height,t.y);return new d(e,n,i-e,r-n)},expand:function(t,e){return void 0===e&&(e=t),new d(this.x-t/2,this.y-e/2,this.width+t,this.height+e)},scale:function(t,e){return this.expand(this.width*t-this.width,this.height*(void 0===e?t:e)-this.height)}},new function(){return t.each([["Top","Left"],["Top","Right"],["Bottom","Left"],["Bottom","Right"],["Left","Center"],["Top","Center"],["Right","Center"],["Bottom","Center"]],function(t,e){var n=t.join(""),i=/^[RL]/.test(n);e>=4&&(t[1]+=i?"Y":"X");var r=t[i?0:1],s=t[i?1:0],a="get"+r,u="get"+s,c="set"+r,l="set"+s,d="get"+n,f="set"+n;this[d]=function(){return new(arguments[0]?o:h)(this[a](),this[u](),this,f)},this[f]=function(t){t=o.read(arguments),this[c](t.x),this[l](t.y)}},{})}),f=d.extend({initialize:function(t,e,n,i,r,s){this.set(t,e,n,i,!0),this._owner=r,this._setter=s},set:function(t,e,n,i,r){return this._x=t,this._y=e,this._width=n,this._height=i,r||this._owner[this._setter](this),this}},new function(){var e=d.prototype;return t.each(["x","y","width","height"],function(e){var n=t.capitalize(e),i="_"+e;this["get"+n]=function(){return this[i]},this["set"+n]=function(t){this[i]=t,this._dontNotify||this._owner[this._setter](this)}},t.each(["Point","Size","Center","Left","Top","Right","Bottom","CenterX","CenterY","TopLeft","TopRight","BottomLeft","BottomRight","LeftCenter","TopCenter","RightCenter","BottomCenter"],function(t){var n="set"+t;this[n]=function(){this._dontNotify=!0,e[n].apply(this,arguments),delete this._dontNotify,this._owner[this._setter](this)}},{isSelected:function(){return this._owner._boundsSelected},setSelected:function(t){var e=this._owner;e.setSelected&&(e._boundsSelected=t,e.setSelected(t||e._selectedSegmentState>0))}}))}),_=t.extend({_class:"Matrix",initialize:function re(t){var e=arguments.length,n=!0;if(6==e?this.set.apply(this,arguments):1==e?t instanceof re?this.set(t._a,t._c,t._b,t._d,t._tx,t._ty):Array.isArray(t)?this.set.apply(this,t):n=!1:0==e?this.reset():n=!1,!n)throw Error("Unsupported matrix parameters")},set:function(t,e,n,i,r,s){return this._a=t,this._c=e,this._b=n,this._d=i,this._tx=r,this._ty=s,this},_serialize:function(e){return t.serialize(this.getValues(),e)},clone:function(){return new _(this._a,this._c,this._b,this._d,this._tx,this._ty)},equals:function(t){return t===this||t&&this._a==t._a&&this._b==t._b&&this._c==t._c&&this._d==t._d&&this._tx==t._tx&&this._ty==t._ty||!1},toString:function(){var t=s.instance;return"[["+[t.number(this._a),t.number(this._b),t.number(this._tx)].join(", ")+"], ["+[t.number(this._c),t.number(this._d),t.number(this._ty)].join(", ")+"]]"},reset:function(){return this._a=this._d=1,this._c=this._b=this._tx=this._ty=0,this},scale:function(){var t=o.read(arguments),e=o.read(arguments,0,0,!0);return e&&this.translate(e),this._a*=t.x,this._c*=t.x,this._b*=t.y,this._d*=t.y,e&&this.translate(e.negate()),this},translate:function(t){t=o.read(arguments);var e=t.x,n=t.y;return this._tx+=e*this._a+n*this._b,this._ty+=e*this._c+n*this._d,this},rotate:function(t,e){e=o.read(arguments,1),t=t*Math.PI/180;var n=e.x,i=e.y,r=Math.cos(t),s=Math.sin(t),a=n-n*r+i*s,h=i-n*s-i*r,u=this._a,c=this._b,l=this._c,d=this._d;return this._a=r*u+s*c,this._b=-s*u+r*c,this._c=r*l+s*d,this._d=-s*l+r*d,this._tx+=a*u+h*c,this._ty+=a*l+h*d,this},shear:function(){var t=o.read(arguments),e=o.read(arguments,0,0,!0);e&&this.translate(e);var n=this._a,i=this._c;return this._a+=t.y*this._b,this._c+=t.y*this._d,this._b+=t.x*n,this._d+=t.x*i,e&&this.translate(e.negate()),this},isIdentity:function(){return 1==this._a&&0==this._c&&0==this._b&&1==this._d&&0==this._tx&&0==this._ty},isInvertible:function(){return!!this._getDeterminant()},isSingular:function(){return!this._getDeterminant()},concatenate:function(t){var e=this._a,n=this._b,i=this._c,r=this._d;return this._a=t._a*e+t._c*n,this._b=t._b*e+t._d*n,this._c=t._a*i+t._c*r,this._d=t._b*i+t._d*r,this._tx+=t._tx*e+t._ty*n,this._ty+=t._tx*i+t._ty*r,this},preConcatenate:function(t){var e=this._a,n=this._b,i=this._c,r=this._d,s=this._tx,a=this._ty;return this._a=t._a*e+t._b*i,this._b=t._a*n+t._b*r,this._c=t._c*e+t._d*i,this._d=t._c*n+t._d*r,this._tx=t._a*s+t._b*a+t._tx,this._ty=t._c*s+t._d*a+t._ty,this},transform:function(t,e,n,i,r){return arguments.length<5?this._transformPoint(o.read(arguments)):this._transformCoordinates(t,e,n,i,r)},_transformPoint:function(t,e,n){var i=t.x,r=t.y;return e||(e=new o),e.set(i*this._a+r*this._b+this._tx,i*this._c+r*this._d+this._ty,n)},_transformCoordinates:function(t,e,n,i,r){for(var s=e,a=i,o=e+2*r;o>s;){var h=t[s++],u=t[s++];n[a++]=h*this._a+u*this._b+this._tx,n[a++]=h*this._c+u*this._d+this._ty}return n},_transformCorners:function(t){var e=t.x,n=t.y,i=e+t.width,r=n+t.height,s=[e,n,i,n,i,r,e,r];return this._transformCoordinates(s,0,s,0,4)},_transformBounds:function(t,e,n){for(var i=this._transformCorners(t),r=i.slice(0,2),s=i.slice(),a=2;8>a;a++){var o=i[a],h=1&a;os[h]&&(s[h]=o)}return e||(e=new d),e.set(r[0],r[1],s[0]-r[0],s[1]-r[1],n)},inverseTransform:function(){return this._inverseTransform(o.read(arguments))},_getDeterminant:function(){var t=this._a*this._d-this._b*this._c;return isFinite(t)&&!a.isZero(t)&&isFinite(this._tx)&&isFinite(this._ty)?t:null},_inverseTransform:function(t,e,n){var i=this._getDeterminant();if(!i)return null;var r=t.x-this._tx,s=t.y-this._ty;return e||(e=new o),e.set((r*this._d-s*this._b)/i,(s*this._a-r*this._c)/i,n)},decompose:function(){var t=this._a,e=this._b,n=this._c,i=this._d;if(a.isZero(t*i-e*n))return null;var r=Math.sqrt(t*t+e*e);t/=r,e/=r;var s=t*n+e*i;n-=t*s,i-=e*s;var h=Math.sqrt(n*n+i*i);return n/=h,i/=h,s/=h,e*n>t*i&&(t=-t,e=-e,s=-s,r=-r),{translation:this.getTranslation(),scaling:new o(r,h),rotation:180*-Math.atan2(e,t)/Math.PI,shearing:s}},getValues:function(){return[this._a,this._c,this._b,this._d,this._tx,this._ty]},getTranslation:function(){return new o(this._tx,this._ty)},getScaling:function(){return(this.decompose()||{}).scaling},getRotation:function(){return(this.decompose()||{}).rotation +},inverted:function(){var t=this._getDeterminant();return t&&new _(this._d/t,-this._c/t,-this._b/t,this._a/t,(this._b*this._ty-this._d*this._tx)/t,(this._c*this._tx-this._a*this._ty)/t)},shiftless:function(){return new _(this._a,this._c,this._b,this._d,0,0)},applyToContext:function(t){t.transform(this._a,this._c,this._b,this._d,this._tx,this._ty)}},new function(){return t.each({scaleX:"_a",scaleY:"_d",translateX:"_tx",translateY:"_ty",shearX:"_b",shearY:"_c"},function(e,n){n=t.capitalize(n),this["get"+n]=function(){return this[e]},this["set"+n]=function(t){this[e]=t}},{})}),g=t.extend({_class:"Line",initialize:function(t,e,n,i,r){var s=!1;arguments.length>=4?(this._px=t,this._py=e,this._vx=n,this._vy=i,s=r):(this._px=t.x,this._py=t.y,this._vx=e.x,this._vy=e.y,s=n),s||(this._vx-=this._px,this._vy-=this._py)},getPoint:function(){return new o(this._px,this._py)},getVector:function(){return new o(this._vx,this._vy)},getLength:function(){return this.getVector().getLength()},intersect:function(t,e){return g.intersect(this._px,this._py,this._vx,this._vy,t._px,t._py,t._vx,t._vy,!0,e)},getSide:function(t){return g.getSide(this._px,this._py,this._vx,this._vy,t.x,t.y,!0)},getDistance:function(t){return Math.abs(g.getSignedDistance(this._px,this._py,this._vx,this._vy,t.x,t.y,!0))},statics:{intersect:function(t,e,n,i,r,s,h,u,c,l){c||(n-=t,i-=e,h-=r,u-=s);var d=u*n-h*i;if(!a.isZero(d)){var f=t-r,_=e-s,g=(h*_-u*f)/d,p=(n*_-i*f)/d;if((l||g>=0&&1>=g)&&(l||p>=0&&1>=p))return new o(t+g*n,e+g*i)}},getSide:function(t,e,n,i,r,s,a){a||(n-=t,i-=e);var o=r-t,h=s-e,u=o*i-h*n;return 0===u&&(u=o*n+h*i,u>0&&(o-=n,h-=i,u=o*n+h*i,0>u&&(u=0))),0>u?-1:u>0?1:0},getSignedDistance:function(t,e,n,i,r,s,a){a||(n-=t,i-=e);var o=i/n,h=e-o*t;return(s-o*r-h)/Math.sqrt(o*o+1)}}}),p=r.extend({_class:"Project",_list:"projects",_reference:"project",initialize:function(t){r.call(this,!0),this.layers=[],this.symbols=[],this._currentStyle=new F,this.activeLayer=new w,t&&(this.view=t instanceof V?t:V.create(t)),this._selectedItems={},this._selectedItemCount=0,this._drawCount=0,this.options={}},_serialize:function(e,n){return t.serialize(this.layers,e,!0,n)},clear:function(){for(var t=this.layers.length-1;t>=0;t--)this.layers[t].remove();this.symbols=[]},remove:function se(){return se.base.call(this)?(this.view&&this.view.remove(),!0):!1},getCurrentStyle:function(){return this._currentStyle},setCurrentStyle:function(t){this._currentStyle.initialize(t)},getIndex:function(){return this._index},getSelectedItems:function(){var t=[];for(var e in this._selectedItems){var n=this._selectedItems[e];n._drawCount===this._drawCount&&t.push(n)}return t},_updateSelection:function(t){t._selected?(this._selectedItemCount++,this._selectedItems[t._id]=t,t.isInserted()&&(t._drawCount=this._drawCount)):(this._selectedItemCount--,delete this._selectedItems[t._id])},selectAll:function(){for(var t=0,e=this.layers.length;e>t;t++)this.layers[t].setSelected(!0)},deselectAll:function(){for(var t in this._selectedItems)this._selectedItems[t].setSelected(!1)},hitTest:function(e,n){e=o.read(arguments),n=S.getOptions(t.read(arguments));for(var i=this.layers.length-1;i>=0;i--){var r=this.layers[i].hitTest(e,n);if(r)return r}return null},importJSON:function(e){return this.activate(),t.importJSON(e)},draw:function(e,n){this._drawCount++,e.save(),n.applyToContext(e);for(var i=t.merge({offset:new o(0,0),transforms:[n]}),r=0,s=this.layers.length;s>r;r++)this.layers[r].draw(e,i);if(e.restore(),this._selectedItemCount>0){e.save(),e.strokeWidth=1;for(var a in this._selectedItems){var h=this._selectedItems[a];if(h._drawCount===this._drawCount&&(h._drawSelected||h._boundsSelected)){var u=h.getSelectedColor()||h.getLayer().getSelectedColor();e.strokeStyle=e.fillStyle=u?u.toCanvasStyle(e):"#009dec";var c=h._globalMatrix;if(h._drawSelected&&h._drawSelected(e,c),h._boundsSelected){var l=c._transformCorners(h._getBounds("getBounds"));e.beginPath();for(var r=0;8>r;r++)e[0===r?"moveTo":"lineTo"](l[r],l[++r]);e.closePath(),e.stroke();for(var r=0;8>r;r++)e.beginPath(),e.rect(l[r]-2,l[++r]-2,4,4),e.fill()}}}e.restore()}}}),v=t.extend({_class:"Symbol",initialize:function ae(t,e){this._id=ae._id=(ae._id||0)+1,this.project=paper.project,this.project.symbols.push(this),t&&this.setDefinition(t,e),this._instances={}},_serialize:function(e,n){return n.add(this,function(){return t.serialize([this._class,this._definition],e,!1,n)})},_changed:function(e){t.each(this._instances,function(t){t._changed(e)})},getDefinition:function(){return this._definition},setDefinition:function(t){t._parentSymbol&&(t=t.clone()),this._definition&&delete this._definition._parentSymbol,this._definition=t,t.remove(),t.setSelected(!1),arguments[1]||t.setPosition(new o),t._parentSymbol=this,this._changed(5)},place:function(t){return new C(this,t)},clone:function(){return new v(this._definition.clone())}}),m=t.extend(e,{statics:{extend:function oe(e){e._serializeFields&&(e._serializeFields=t.merge(this.prototype._serializeFields,e._serializeFields));var n=oe.base.apply(this,arguments),i=n.prototype,r=i._class;return r&&(i._type=t.hyphenate(r)),n}},_class:"Item",_transformContent:!0,_boundsSelected:!1,_serializeFields:{name:null,matrix:new _,locked:!1,visible:!0,blendMode:"normal",opacity:1,guide:!1,clipMask:!1,data:{}},initialize:function he(t){if(this._id=he._id=(he._id||0)+1,!this._project){var e=paper.project,n=e.activeLayer;n?n.addChild(this):this._setProject(e)}this._style=new F(this._project._currentStyle,this),this._matrix=new _,t&&this._matrix.translate(t)},_events:new function(){var e={mousedown:{mousedown:1,mousedrag:1,click:1,doubleclick:1},mouseup:{mouseup:1,mousedrag:1,click:1,doubleclick:1},mousemove:{mousedrag:1,mousemove:1,mouseenter:1,mouseleave:1}},n={install:function(t){var n=this._project.view._eventCounters;if(n)for(var i in e)n[i]=(n[i]||0)+(e[i][t]||0)},uninstall:function(t){var n=this._project.view._eventCounters;if(n)for(var i in e)n[i]-=e[i][t]||0}};return t.each(["onMouseDown","onMouseUp","onMouseDrag","onClick","onDoubleClick","onMouseMove","onMouseEnter","onMouseLeave"],function(t){this[t]=n},{onFrame:{install:function(){this._project.view._animateItem(this,!0)},uninstall:function(){this._project.view._animateItem(this,!1)}},onLoad:{}})},_serialize:function(e,n){function i(i){for(var a in i){var o=s[a];t.equals(o,i[a])||(r[a]=t.serialize(o,e,"data"!==a,n))}}var r={},s=this;return i(this._serializeFields),this instanceof y||i(this._style._defaults),[this._class,r]},_changed:function(t){if(4&t&&(delete this._bounds,delete this._position),this._parent&&12&t&&this._parent._clearBoundsCache(),2&t&&this._clearBoundsCache(),1&t&&(this._project._needsRedraw=!0),this._parentSymbol&&this._parentSymbol._changed(t),this._project._changes){var e=this._project._changesById[this._id];e?e.flags|=t:(e={item:this,flags:t},this._project._changesById[this._id]=e,this._project._changes.push(e))}},set:function(t){return t&&this._set(t),this},getId:function(){return this._id},getType:function(){return this._type},getName:function(){return this._name},setName:function(t,e){if(this._name&&this._removeFromNamed(),t&&this._parent){for(var n=this._parent._children,i=this._parent._namedChildren,r=t,s=1;e&&n[t];)t=r+" "+s++;(i[t]=i[t]||[]).push(this),n[t]=this}this._name=t||void 0,this._changed(32)},getStyle:function(){return this._style},setStyle:function(t){this.getStyle().set(t)},hasFill:function(){return!!this.getStyle().getFillColor()},hasStroke:function(){var t=this.getStyle();return!!t.getStrokeColor()&&t.getStrokeWidth()>0}},t.each(["locked","visible","blendMode","opacity","guide"],function(e){var n=t.capitalize(e),e="_"+e;this["get"+n]=function(){return this[e]},this["set"+n]=function(t){t!=this[e]&&(this[e]=t,this._changed("_locked"===e?32:33))}},{}),{_locked:!1,_visible:!0,_blendMode:"normal",_opacity:1,_guide:!1,isSelected:function(){if(this._children)for(var t=0,e=this._children.length;e>t;t++)if(this._children[t].isSelected())return!0;return this._selected},setSelected:function(t){if(this._children&&!arguments[1])for(var e=0,n=this._children.length;n>e;e++)this._children[e].setSelected(t);(t=!!t)!=this._selected&&(this._selected=t,this._project._updateSelection(this),this._changed(33))},_selected:!1,isFullySelected:function(){if(this._children&&this._selected){for(var t=0,e=this._children.length;e>t;t++)if(!this._children[t].isFullySelected())return!1;return!0}return this._selected},setFullySelected:function(t){if(this._children)for(var e=0,n=this._children.length;n>e;e++)this._children[e].setFullySelected(t);this.setSelected(t,!0)},isClipMask:function(){return this._clipMask},setClipMask:function(t){this._clipMask!=(t=!!t)&&(this._clipMask=t,t&&(this.setFillColor(null),this.setStrokeColor(null)),this._changed(33),this._parent&&this._parent._changed(256))},_clipMask:!1,getData:function(){return this._data||(this._data={}),this._data},setData:function(t){this._data=t},getPosition:function(){var t=this._position||(this._position=this.getBounds().getCenter(!0));return new(arguments[0]?o:h)(t.x,t.y,this,"setPosition")},setPosition:function(){this.translate(o.read(arguments).subtract(this.getPosition(!0)))},getMatrix:function(){return this._matrix},setMatrix:function(t){this._matrix.initialize(t),this._changed(5)},isEmpty:function(){return 0==this._children.length}},t.each(["getBounds","getStrokeBounds","getHandleBounds","getRoughBounds"],function(t){this[t]=function(){var e=this._boundsGetter,n=this._getCachedBounds("string"==typeof e?e:e&&e[t]||t,arguments[0]);return"getBounds"===t?new f(n.x,n.y,n.width,n.height,this,"setBounds"):n}},{_getCachedBounds:function(t,e,n){var i=(!e||e.equals(this._matrix))&&t;if(n&&this._parent){var r=n._id,s=this._parent._boundsCache=this._parent._boundsCache||{ids:{},list:[]};s.ids[r]||(s.list.push(n),s.ids[r]=n)}if(i&&this._bounds&&this._bounds[i])return this._bounds[i].clone();var a=this._matrix.isIdentity();e=!e||e.isIdentity()?a?null:this._matrix:a?e:e.clone().concatenate(this._matrix);var o=this._getBounds(t,e,i?this:n);return i&&(this._bounds||(this._bounds={}),this._bounds[i]=o.clone()),o},_clearBoundsCache:function(){if(this._boundsCache){for(var t=0,e=this._boundsCache.list,n=e.length;n>t;t++){var i=e[t];delete i._bounds,i!=this&&i._boundsCache&&i._clearBoundsCache()}delete this._boundsCache}},_getBounds:function(t,e,n){var i=this._children;if(!i||0==i.length)return new d;for(var r=1/0,s=-r,a=r,o=s,h=0,u=i.length;u>h;h++){var c=i[h];if(c._visible&&!c.isEmpty()){var l=c._getCachedBounds(t,e,n);r=Math.min(l.x,r),a=Math.min(l.y,a),s=Math.max(l.x+l.width,s),o=Math.max(l.y+l.height,o)}}return isFinite(r)?new d(r,a,s-r,o-a):new d},setBounds:function(t){t=d.read(arguments);var e=this.getBounds(),n=new _,i=t.getCenter();n.translate(i),(t.width!=e.width||t.height!=e.height)&&n.scale(0!=e.width?t.width/e.width:1,0!=e.height?t.height/e.height:1),i=e.getCenter(),n.translate(-i.x,-i.y),this.transform(n)}}),{getProject:function(){return this._project},_setProject:function(t){if(this._project!=t&&(this._project=t,this._children))for(var e=0,n=this._children.length;n>e;e++)this._children[e]._setProject(t)},getLayer:function(){for(var t=this;t=t._parent;)if(t instanceof w)return t;return null},getParent:function(){return this._parent},setParent:function(t){return t.addChild(this)},getChildren:function(){return this._children},setChildren:function(t){this.removeChildren(),this.addChildren(t)},getFirstChild:function(){return this._children&&this._children[0]||null},getLastChild:function(){return this._children&&this._children[this._children.length-1]||null},getNextSibling:function(){return this._parent&&this._parent._children[this._index+1]||null},getPreviousSibling:function(){return this._parent&&this._parent._children[this._index-1]||null},getIndex:function(){return this._index},isInserted:function(){return this._parent?this._parent.isInserted():!1},clone:function(){return this._clone(new this.constructor)},_clone:function(t){if(t.setStyle(this._style),this._children)for(var e=0,n=this._children.length;n>e;e++)t.addChild(this._children[e].clone(),!0);for(var i=["_locked","_visible","_blendMode","_opacity","_clipMask","_guide"],e=0,n=i.length;n>e;e++){var r=i[e];this.hasOwnProperty(r)&&(t[r]=this[r])}return t._matrix.initialize(this._matrix),t.setSelected(this._selected),this._name&&t.setName(this._name,!0),t},copyTo:function(t){var e=this.clone();return t.layers?t.activeLayer.addChild(e):t.addChild(e),e},rasterize:function(e){var n=this.getStrokeBounds(),i=(e||72)/72,r=Y.getCanvas(n.getSize().multiply(i)),s=r.getContext("2d"),a=(new _).scale(i).translate(-n.x,-n.y);s.save(),a.applyToContext(s),this.draw(s,t.merge({transforms:[a]}));var o=new b(r);return o.setBounds(n),s.restore(),o},contains:function(){return!!this._contains(this._matrix._inverseTransform(o.read(arguments)))},_contains:function(t){if(this._children){for(var e=this._children.length-1;e>=0;e--)if(this._children[e].contains(t))return!0;return!1}return t.isInside(this._getBounds("getBounds"))},hitTest:function(e,n){function i(i,r){var o=a["get"+r]();return e.getDistance(o)u&&!r;u++)r=i("bounds",h[u])}return(r||(r=this._children||!(n.guides&&!this._guide||n.selected&&!this._selected)?this._hitTest(e,n):null))&&r.point&&(r.point=s._matrix.transform(r.point)),r},_hitTest:function(t,e){if(this._children){for(var n,i=this._children.length-1;i>=0;i--)if(n=this._children[i].hitTest(t,e))return n}else if(this.hasFill()&&this._contains(t))return new S("fill",this)},addChild:function(t,e){return this.insertChild(void 0,t,e)},insertChild:function(t,e,n){var i=this.insertChildren(t,[e],n);return i&&i[0]},addChildren:function(t,e){return this.insertChildren(this._children.length,t,e)},insertChildren:function(e,n,i,r){var s=this._children;if(s&&n&&n.length>0){n=Array.prototype.slice.apply(n);for(var a=n.length-1;a>=0;a--){var o=n[a];r&&o._type!==r?n.splice(a,1):o._remove(!0)}t.splice(s,n,e,0);for(var a=0,h=n.length;h>a;a++){var o=n[a];o._parent=this,o._setProject(this._project),o._name&&o.setName(o._name)}this._changed(7)}else n=null;return n},insertAbove:function(t,e){var n=t._index;return t._parent==this._parent&&nthis._index&&n--,t._parent.insertChild(n,this,e)},sendToBack:function(){return this._parent.insertChild(0,this)},bringToFront:function(){return this._parent.addChild(this)},appendTop:"#addChild",appendBottom:function(t){return this.insertChild(0,t)},moveAbove:"#insertAbove",moveBelow:"#insertBelow",_removeFromNamed:function(){var t=this._parent._children,e=this._parent._namedChildren,n=this._name,i=e[n],r=i?i.indexOf(this):-1;-1!=r&&(t[n]==this&&delete t[n],i.splice(r,1),i.length?t[n]=i[i.length-1]:delete e[n])},_remove:function(e){return this._parent?(this._name&&this._removeFromNamed(),null!=this._index&&t.splice(this._parent._children,null,this._index,1),e&&this._parent._changed(7),this._parent=null,!0):!1},remove:function(){return this._remove(!0)},removeChildren:function(e,n){if(!this._children)return null;e=e||0,n=t.pick(n,this._children.length);for(var i=t.splice(this._children,null,e,n-e),r=i.length-1;r>=0;r--)i[r]._remove(!1);return i.length>0&&this._changed(7),i},reverseChildren:function(){if(this._children){this._children.reverse();for(var t=0,e=this._children.length;e>t;t++)this._children[t]._index=t;this._changed(7)}},isEditable:function(){for(var t=this;t;){if(!t._visible||t._locked)return!1;t=t._parent}return!0},_getOrder:function(t){function e(t){var e=[];do e.unshift(t);while(t=t._parent);return e}for(var n=e(this),i=e(t),r=0,s=Math.min(n.length,i.length);s>r;r++)if(n[r]!=i[r])return n[r]._index0},isAbove:function(t){return-1==this._getOrder(t)},isBelow:function(t){return 1==this._getOrder(t)},isParent:function(t){return this._parent==t},isChild:function(t){return t&&t._parent==this},isDescendant:function(t){for(var e=this;e=e._parent;)if(e==t)return!0;return!1},isAncestor:function(t){return t?t.isDescendant(this):!1},isGroupedWith:function(t){for(var e=this._parent;e;){if(e._parent&&/^(group|layer|compound-path)$/.test(e._type)&&t.isDescendant(e))return!0;e=e._parent}return!1},scale:function(t,e,n){return(arguments.length<2||"object"==typeof e)&&(n=e,e=t),this.transform((new _).scale(t,e,n||this.getPosition(!0)))},translate:function(){var t=new _;return this.transform(t.translate.apply(t,arguments))},rotate:function(t,e){return this.transform((new _).rotate(t,e||this.getPosition(!0)))},shear:function(t,e,n){return(arguments.length<2||"object"==typeof e)&&(n=e,e=t),this.transform((new _).shear(t,e,n||this.getPosition(!0)))},transform:function(t){var e=this._bounds,n=this._position;if(this._matrix.preConcatenate(t),(this._transformContent||arguments[1])&&this.applyMatrix(!0),this._changed(5),e&&0===t.getRotation()%90){for(var i in e){var r=e[i];t._transformBounds(r,r)}var s=this._boundsGetter,r=e[s&&s.getBounds||s||"getBounds"];r&&(this._position=r.getCenter(!0)),this._bounds=e}else n&&(this._position=t._transformPoint(n,n));return this},_applyMatrix:function(t,e){var n=this._children;if(n&&n.length>0){for(var i=0,r=n.length;r>i;i++)n[i].transform(t,e);return!0}},applyMatrix:function(t){var e=this._matrix;if(this._applyMatrix(e,!0)){var n=this._style,i=n.getFillColor(!0),r=n.getStrokeColor(!0);i&&i.transform(e),r&&r.transform(e),e.reset()}t||this._changed(5)},fitBounds:function(t,e){t=d.read(arguments);var n=this.getBounds(),i=n.height/n.width,r=t.height/t.width,s=(e?i>r:r>i)?t.width/n.width:t.height/n.height,a=new d(new o,new u(n.width*s,n.height*s));a.setCenter(t.getCenter()),this.setBounds(a)},importJSON:function(e){return this.addChild(t.importJSON(e))},_setStyles:function(t){var e=this._style,n=e.getStrokeWidth(),i=e.getStrokeJoin(),r=e.getStrokeCap(),s=e.getMiterLimit(),a=e.getFillColor(),o=e.getStrokeColor(),h=e.getDashArray(),u=e.getDashOffset();null!=n&&(t.lineWidth=n),i&&(t.lineJoin=i),r&&(t.lineCap=r),s&&(t.miterLimit=s),a&&(t.fillStyle=a.toCanvasStyle(t)),o&&(t.strokeStyle=o.toCanvasStyle(t),paper.support.nativeDash&&h&&h.length&&("setLineDash"in t?(t.setLineDash(h),t.lineDashOffset=u):(t.mozDash=h,t.mozDashOffset=u)))},draw:function(t,e){if(this._visible&&0!=this._opacity){this._drawCount=this._project._drawCount;var n=e.transforms,i=n[n.length-1],r=i.clone().concatenate(this._matrix);n.push(this._globalMatrix=r);var s,a,o,h=this._blendMode,c=this._opacity,l=K.nativeModes[h],d="normal"===h&&1===c||(l||1>c)&&this._canComposite();if(!d){var f=this.getStrokeBounds(i);if(!f.width||!f.height)return;o=e.offset,a=e.offset=f.getTopLeft().floor(),s=t,t=Y.getContext(f.getSize().ceil().add(new u(1,1)))}t.save(),d?(t.globalAlpha=c,l&&(t.globalCompositeOperation=h)):t.translate(-a.x,-a.y),(d?this._matrix:r).applyToContext(t),!d&&e.clipItem&&e.clipItem.draw(t,e.extend({clip:!0})),this._draw(t,e),t.restore(),n.pop(),e.clip&&t.clip(),d||(K.process(h,t,s,c,a.subtract(o)),Y.release(t),e.offset=o)}},_canComposite:function(){return!1}},t.each(["down","drag","up","move"],function(e){this["removeOn"+t.capitalize(e)]=function(){var t={};return t[e]=!0,this.removeOn(t)}},{removeOn:function(t){for(var e in t)if(t[e]){var n="mouse"+e,i=this._project,r=i._removeSets=i._removeSets||{};r[n]=r[n]||{},r[n][this._id]=this}return this}})),y=m.extend({_class:"Group",_serializeFields:{children:[]},initialize:function(t){m.call(this),this._children=[],this._namedChildren={},t&&!this._set(t)&&this.addChildren(Array.isArray(t)?t:arguments)},_changed:function ue(t){ue.base.call(this,t),2&t&&this._transformContent&&!this._matrix.isIdentity()&&this.applyMatrix(),258&t&&delete this._clipItem},_getClipItem:function(){if(void 0!==this._clipItem)return this._clipItem;for(var t=0,e=this._children.length;e>t;t++){var n=this._children[t];if(n._clipMask)return this._clipItem=n}return this._clipItem=null},getTransformContent:function(){return this._transformContent},setTransformContent:function(t){this._transformContent=t,t&&this.applyMatrix()},isClipped:function(){return!!this._getClipItem()},setClipped:function(t){var e=this.getFirstChild();e&&e.setClipMask(t)},_draw:function(t,e){var n=e.clipItem=this._getClipItem();n&&n.draw(t,e.extend({clip:!0}));for(var i=0,r=this._children.length;r>i;i++){var s=this._children[i];s!==n&&s.draw(t,e)}e.clipItem=null}}),w=y.extend({_class:"Layer",initialize:function(){this._project=paper.project,this._index=this._project.layers.push(this)-1,y.apply(this,arguments),this.activate()},_remove:function ce(e){return this._parent?ce.base.call(this,e):null!=this._index?(this._project.activeLayer===this&&(this._project.activeLayer=this.getNextSibling()||this.getPreviousSibling()),t.splice(this._project.layers,null,this._index,1),this._project._needsRedraw=!0,!0):!1},getNextSibling:function le(){return this._parent?le.base.call(this):this._project.layers[this._index+1]||null},getPreviousSibling:function de(){return this._parent?de.base.call(this):this._project.layers[this._index-1]||null},isInserted:function fe(){return this._parent?fe.base.call(this):null!=this._index},activate:function(){this._project.activeLayer=this}},new function(){function e(e){return function n(i){return i instanceof w&&!i._parent&&this._remove(!0)?(t.splice(i._project.layers,[this],i._index+(e?1:0),0),this._setProject(i._project),!0):n.base.call(this,i)}}return{insertAbove:e(!0),insertBelow:e(!1)}}),x=m.extend({_class:"Shape",_transformContent:!1,initialize:function(t,e,n){m.call(this,e),this._type=t,this._size=n},_draw:function(t,e){var n=this._style,i=this._size,r=i.width,s=i.height,o=n.getFillColor(),h=n.getStrokeColor();if(o||h||e.clip)switch(t.beginPath(),this._type){case"rect":t.rect(-r/2,-s/2,r,s);break;case"circle":t.arc(0,0,(r+s)/4,0,2*Math.PI,!0);break;case"ellipse":var u=r/2,c=s/2,l=a.KAPPA,d=u*l,f=c*l;t.moveTo(-u,0),t.bezierCurveTo(-u,-f,-d,-c,0,-c),t.bezierCurveTo(d,-c,u,-f,u,0),t.bezierCurveTo(u,f,d,c,0,c),t.bezierCurveTo(-d,c,-u,f,-u,0)}e.clip||!o&&!h||(this._setStyles(t),o&&t.fill(),h&&t.stroke())},_canComposite:function(){return!(this.hasFill()&&this.hasStroke())},_getBounds:function(t,e){var n=new d(this._size).setCenter(0,0);return"getBounds"!==t&&this.hasStroke()&&(n=n.expand(this.getStrokeWidth())),e?e._transformBounds(n):n},_contains:function _e(t){switch(this._type){case"rect":return _e.base.call(this,t);case"circle":case"ellipse":return t.divide(this._size).getLength()<=.5}},_hitTest:function ge(t){if(this.hasStroke()){var e=this._type,n=this.getStrokeWidth();switch(e){case"rect":var i=new d(this._size).setCenter(0,0),r=i.expand(n),s=i.expand(-n);if(r._containsPoint(t)&&!s._containsPoint(t))return new S("stroke",this);break;case"circle":case"ellipse":var a,o=this._size,h=o.width,u=o.height;if("ellipse"===e){var c=t.getAngleInRadians(),l=h*Math.sin(c),f=u*Math.cos(c);a=h*u/(2*Math.sqrt(l*l+f*f))}else a=(h+u)/4;if(2*Math.abs(t.getLength()-a)<=n)return new S("stroke",this)}}return ge.base.apply(this,arguments)},statics:new function(){function e(e,n,i,r){var s=new x(e,n,i),a=t.getNamed(r);return a&&s._set(a),s}return{Circle:function(){var n=o.readNamed(arguments,"center"),i=t.readNamed(arguments,"radius");return e("circle",n,new u(2*i),arguments)},Rectangle:function(){var t=d.readNamed(arguments,"rectangle");return e("rect",t.getCenter(!0),t.getSize(!0),arguments)},Ellipse:function(){var t=d.readNamed(arguments,"rectangle");return e("ellipse",t.getCenter(!0),t.getSize(!0),arguments)}}}}),b=m.extend({_class:"Raster",_transformContent:!1,_boundsGetter:"getBounds",_boundsSelected:!0,_serializeFields:{source:null},initialize:function(t,e){m.call(this,void 0!==e&&o.read(arguments,1)),t&&!this._set(t)&&(t.getContext?this.setCanvas(t):"string"==typeof t?this.setSource(t):this.setImage(t)),this._size||(this._size=new u)},clone:function(){var t=this._image;t||(t=Y.getCanvas(this._size),t.getContext("2d").drawImage(this._canvas,0,0));var e=new b(t);return this._clone(e)},getSize:function(){return this._size},setSize:function(){var t=u.read(arguments);if(!this._size.equals(t)){var e=this.getElement();this.setCanvas(Y.getCanvas(t)),e&&this.getContext(!0).drawImage(e,0,0,t.width,t.height)}},getWidth:function(){return this._size.width},getHeight:function(){return this._size.height},isEmpty:function(){return 0==this._size.width&&0==this._size.height},getPpi:function(){var t=this._matrix,e=new o(0,0).transform(t),n=new o(1,0).transform(t).subtract(e),i=new o(0,1).transform(t).subtract(e);return new u(72/n.getLength(),72/i.getLength())},getContext:function(){return this._context||(this._context=this.getCanvas().getContext("2d")),arguments[0]&&(this._image=null,this._changed(129)),this._context},setContext:function(t){this._context=t},getCanvas:function(){if(!this._canvas){var t=Y.getContext(this._size);try{this._image&&t.drawImage(this._image,0,0),this._canvas=t.canvas}catch(e){Y.release(t)}}return this._canvas},setCanvas:function(t){this._canvas&&Y.release(this._canvas),this._canvas=t,this._size=new u(t.width,t.height),this._image=null,this._context=null,this._changed(133)},getImage:function(){return this._image},setImage:function(t){this._canvas&&Y.release(this._canvas),this._image=t,this._size=new u(t.naturalWidth,t.naturalHeight),this._canvas=null,this._context=null,this._changed(5)},getSource:function(){return this._image&&this._image.src||this.toDataURL()},setSource:function(t){function e(){n.fire("load"),n._project.view&&n._project.view.draw(!0)}var n=this,i=document.getElementById(t)||new Image;q.add(i,{load:function(){n.setImage(i),e()}}),i.width&&i.height?setTimeout(e,0):i.src||(i.src=t),this.setImage(i)},getElement:function(){return this._canvas||this._image},getSubImage:function(t){t=d.read(arguments);var e=Y.getContext(t.getSize());return e.drawImage(this.getCanvas(),t.x,t.y,t.width,t.height,0,0,t.width,t.height),e.canvas},toDataURL:function(){var t=this._image&&this._image.src;if(/^data:/.test(t))return t;var e=this.getCanvas();return e?e.toDataURL():null},drawImage:function(t,e){e=o.read(arguments,1),this.getContext(!0).drawImage(t,e.x,e.y)},getAverageColor:function(e){var n,i;e?e instanceof A?(i=e,n=e.getBounds()):e.width?n=new d(e):e.x&&(n=new d(e.x-.5,e.y-.5,1,1)):n=this.getBounds();var r=32,s=Math.min(n.width,r),a=Math.min(n.height,r),o=b._sampleContext;o?o.clearRect(0,0,r+1,r+1):o=b._sampleContext=Y.getContext(new u(r)),o.save();var h=(new _).scale(s/n.width,a/n.height).translate(-n.x,-n.y);h.applyToContext(o),i&&i.draw(o,t.merge({clip:!0,transforms:[h]})),this._matrix.applyToContext(o),o.drawImage(this.getElement(),-this._size.width/2,-this._size.height/2),o.restore();for(var c=o.getImageData(.5,.5,Math.ceil(s),Math.ceil(a)).data,l=[0,0,0],f=0,g=0,p=c.length;p>g;g+=4){var v=c[g+3];f+=v,v/=255,l[0]+=c[g]*v,l[1]+=c[g+1]*v,l[2]+=c[g+2]*v}for(var g=0;3>g;g++)l[g]/=f;return f?E.read(l):null},getPixel:function(t){t=o.read(arguments);var e=this.getContext().getImageData(t.x,t.y,1,1).data;return new E("rgb",[e[0]/255,e[1]/255,e[2]/255],e[3]/255)},setPixel:function(){var t=o.read(arguments),e=E.read(arguments),n=e._convert("rgb"),i=e._alpha,r=this.getContext(!0),s=r.createImageData(1,1),a=s.data;a[0]=255*n[0],a[1]=255*n[1],a[2]=255*n[2],a[3]=null!=i?255*i:255,r.putImageData(s,t.x,t.y)},createImageData:function(t){return t=u.read(arguments),this.getContext().createImageData(t.width,t.height)},getImageData:function(t){return t=d.read(arguments),t.isEmpty()&&(t=new d(this.getSize())),this.getContext().getImageData(t.x,t.y,t.width,t.height)},setImageData:function(t,e){e=o.read(arguments,1),this.getContext(!0).putImageData(t,e.x,e.y)},_getBounds:function(t,e){var n=new d(this._size).setCenter(0,0);return e?e._transformBounds(n):n},_hitTest:function(t){if(this._contains(t)){var e=this;return new S("pixel",e,{offset:t.add(e._size.divide(2)).round(),color:{get:function(){return e.getPixel(this.offset)}}})}},_draw:function(t){var e=this.getElement();e&&(t.globalAlpha=this._opacity,t.drawImage(e,-this._size.width/2,-this._size.height/2))},_canComposite:function(){return!0}}),C=m.extend({_class:"PlacedSymbol",_transformContent:!1,_boundsGetter:{getBounds:"getStrokeBounds"},_boundsSelected:!0,_serializeFields:{symbol:null},initialize:function(t,e){m.call(this,void 0!==e&&o.read(arguments,1)),t&&!this._set(t)&&this.setSymbol(t instanceof v?t:new v(t))},getSymbol:function(){return this._symbol},setSymbol:function(t){this._symbol&&delete this._symbol._instances[this._id],this._symbol=t,t._instances[this._id]=this},clone:function(){return this._clone(new C(this.symbol))},isEmpty:function(){return this._symbol._definition.isEmpty()},_getBounds:function(t,e){return this.symbol._definition._getCachedBounds(t,e)},_hitTest:function(t,e,n){var i=this._symbol._definition._hitTest(t,e,n);return i&&(i.item=this),i},_draw:function(t,e){this.symbol._definition.draw(t,e)}}),S=t.extend({_class:"HitResult",initialize:function(t,e,n){this.type=t,this.item=e,n&&(n.enumerable=!0,this.inject(n))},statics:{getOptions:function(e){return e&&e._merged?e:t.merge({type:null,tolerance:paper.project.options.hitTolerance||2,fill:!e,stroke:!e,segments:!e,handles:!1,ends:!1,center:!1,bounds:!1,guides:!1,selected:!1,_merged:!0},e)}}}),k=t.extend({_class:"Segment",initialize:function(t,e,n,i,r,s){var a,o,h,u=arguments.length;0===u||(1===u?t.point?(a=t.point,o=t.handleIn,h=t.handleOut):a=t:6>u?2==u&&void 0===e.x?a=[t,e]:(a=t,o=e,h=n):6===u&&(a=[t,e],o=[n,i],h=[r,s])),this._point=new P(a,this),this._handleIn=new P(o,this),this._handleOut=new P(h,this)},_serialize:function(e){return t.serialize(this.isLinear()?this._point:[this._point,this._handleIn,this._handleOut],e,!0)},_changed:function(t){if(this._path){var e,n=this._path._curves&&this.getCurve();n&&(n._changed(),(e=n[t==this._point||t==this._handleIn&&n._segment1==this?"getPrevious":"getNext"]())&&e._changed()),this._path._changed(5)}},getPoint:function(){return this._point},setPoint:function(t){t=o.read(arguments),this._point.set(t.x,t.y)},getHandleIn:function(){return this._handleIn},setHandleIn:function(t){t=o.read(arguments),this._handleIn.set(t.x,t.y)},getHandleOut:function(){return this._handleOut},setHandleOut:function(t){t=o.read(arguments),this._handleOut.set(t.x,t.y)},isLinear:function(){return this._handleIn.isZero()&&this._handleOut.isZero()},setLinear:function(){this._handleIn.set(0,0),this._handleOut.set(0,0)},_isSelected:function(t){var e=this._selectionState;return t==this._point?!!(4&e):t==this._handleIn?!!(1&e):t==this._handleOut?!!(2&e):!1},_setSelected:function(t,e){var n=this._path,e=!!e,i=this._selectionState||0,r=[!!(4&i),!!(1&i),!!(2&i)];if(t==this._point){if(e)r[1]=r[2]=!1;else{var s=this.getPrevious(),a=this.getNext();r[1]=s&&(s._point.isSelected()||s._handleOut.isSelected()),r[2]=a&&(a._point.isSelected()||a._handleIn.isSelected())}r[0]=e}else{var o=t==this._handleIn?1:2;r[o]!=e&&(e&&(r[0]=!1),r[o]=e)}this._selectionState=(r[0]?4:0)|(r[1]?1:0)|(r[2]?2:0),n&&i!=this._selectionState&&(n._updateSelection(this,i,this._selectionState),n._changed(33))},isSelected:function(){return this._isSelected(this._point)},setSelected:function(t){this._setSelected(this._point,t)},getIndex:function(){return void 0!==this._index?this._index:null},getPath:function(){return this._path||null},getCurve:function(){var t=this._path,e=this._index;return t?(t._closed||e!=t._segments.length-1||e--,t.getCurves()[e]||null):null +},getLocation:function(){var t=this.getCurve();return t?new I(t,t.getNext()?0:1):null},getNext:function(){var t=this._path&&this._path._segments;return t&&(t[this._index+1]||this._path._closed&&t[0])||null},getPrevious:function(){var t=this._path&&this._path._segments;return t&&(t[this._index-1]||this._path._closed&&t[t.length-1])||null},reverse:function(){return new k(this._point,this._handleOut,this._handleIn)},remove:function(){return this._path?!!this._path.removeSegment(this._index):!1},clone:function(){return new k(this._point,this._handleIn,this._handleOut)},equals:function(t){return t===this||t&&this._point.equals(t._point)&&this._handleIn.equals(t._handleIn)&&this._handleOut.equals(t._handleOut)||!1},toString:function(){var t=["point: "+this._point];return this._handleIn.isZero()||t.push("handleIn: "+this._handleIn),this._handleOut.isZero()||t.push("handleOut: "+this._handleOut),"{ "+t.join(", ")+" }"},_transformCoordinates:function(t,e,n){var i=this._point,r=n&&this._handleIn.isZero()?null:this._handleIn,s=n&&this._handleOut.isZero()?null:this._handleOut,a=i._x,o=i._y,h=2;return e[0]=a,e[1]=o,r&&(e[h++]=r._x+a,e[h++]=r._y+o),s&&(e[h++]=s._x+a,e[h++]=s._y+o),t&&(t._transformCoordinates(e,0,e,0,h/2),a=e[0],o=e[1],n?(i._x=a,i._y=o,h=2,r&&(r._x=e[h++]-a,r._y=e[h++]-o),s&&(s._x=e[h++]-a,s._y=e[h++]-o)):(r||(e[h++]=a,e[h++]=o),s||(e[h++]=a,e[h++]=o))),e}}),P=o.extend({initialize:function(t,e){var n,i,r;t?void 0!==(n=t[0])?i=t[1]:(void 0===(n=t.x)&&(t=o.read(arguments),n=t.x),i=t.y,r=t.selected):n=i=0,this._x=n,this._y=i,this._owner=e,r&&this.setSelected(!0)},set:function(t,e){return this._x=t,this._y=e,this._owner._changed(this),this},getX:function(){return this._x},setX:function(t){this._x=t,this._owner._changed(this)},getY:function(){return this._y},setY:function(t){this._y=t,this._owner._changed(this)},isZero:function(){return a.isZero(this._x)&&a.isZero(this._y)},setSelected:function(t){this._owner._setSelected(this,t)},isSelected:function(){return this._owner._isSelected(this)}}),M=t.extend({_class:"Curve",initialize:function(t,e,n,i,r,s,a,o){var h=arguments.length;if(3===h)this._path=t,this._segment1=e,this._segment2=n;else if(0===h)this._segment1=new k,this._segment2=new k;else if(1===h)this._segment1=new k(t.segment1),this._segment2=new k(t.segment2);else if(2===h)this._segment1=new k(t),this._segment2=new k(e);else{var u,c,l,d;4===h?(u=t,c=e,l=n,d=i):8===h&&(u=[t,e],d=[a,o],c=[n-t,i-e],l=[r-a,s-o]),this._segment1=new k(u,null,c),this._segment2=new k(d,l,null)}},_changed:function(){delete this._length,delete this._bounds},getPoint1:function(){return this._segment1._point},setPoint1:function(t){t=o.read(arguments),this._segment1._point.set(t.x,t.y)},getPoint2:function(){return this._segment2._point},setPoint2:function(t){t=o.read(arguments),this._segment2._point.set(t.x,t.y)},getHandle1:function(){return this._segment1._handleOut},setHandle1:function(t){t=o.read(arguments),this._segment1._handleOut.set(t.x,t.y)},getHandle2:function(){return this._segment2._handleIn},setHandle2:function(t){t=o.read(arguments),this._segment2._handleIn.set(t.x,t.y)},getSegment1:function(){return this._segment1},getSegment2:function(){return this._segment2},getPath:function(){return this._path},getIndex:function(){return this._segment1._index},getNext:function(){var t=this._path&&this._path._curves;return t&&(t[this._segment1._index+1]||this._path._closed&&t[0])||null},getPrevious:function(){var t=this._path&&this._path._curves;return t&&(t[this._segment1._index-1]||this._path._closed&&t[t.length-1])||null},isSelected:function(){return this.getHandle1().isSelected()&&this.getHandle2().isSelected()},setSelected:function(t){this.getHandle1().setSelected(t),this.getHandle2().setSelected(t)},getValues:function(){return M.getValues(this._segment1,this._segment2)},getPoints:function(){for(var t=this.getValues(),e=[],n=0;8>n;n+=2)e.push(new o(t[n],t[n+1]));return e},getLength:function(){var t=arguments[0],e=arguments[1],n=0===arguments.length||0===t&&1===e;if(n&&null!=this._length)return this._length;var i=M.getLength(this.getValues(),t,e);return n&&(this._length=i),i},getArea:function(){return M.getArea(this.getValues())},getPart:function(t,e){return new M(M.getPart(this.getValues(),t,e))},isLinear:function(){return this._segment1._handleOut.isZero()&&this._segment2._handleIn.isZero()},getIntersections:function(t){return M.getIntersections(this.getValues(),t.getValues(),this,t,[])},reverse:function(){return new M(this._segment2.reverse(),this._segment1.reverse())},divide:function(t){var e=null;if(t&&t.curve===this&&(t=t.parameter),t>0&&1>t){var n=M.subdivide(this.getValues(),t),i=this.isLinear(),r=n[0],s=n[1];i||(this._segment1._handleOut.set(r[2]-r[0],r[3]-r[1]),this._segment2._handleIn.set(s[4]-s[6],s[5]-s[7]));var a=r[6],h=r[7],u=new k(new o(a,h),!i&&new o(r[4]-a,r[5]-h),!i&&new o(s[2]-a,s[3]-h));if(this._path)this._segment1._index>0&&0===this._segment2._index?this._path.add(u):this._path.insert(this._segment2._index,u),e=this;else{var c=this._segment2;this._segment2=u,e=new M(u,c)}}return e},split:function(t){return this._path?this._path.split(this._segment1._index,t):null},clone:function(){return new M(this._segment1,this._segment2)},toString:function(){var t=["point1: "+this._segment1._point];return this._segment1._handleOut.isZero()||t.push("handle1: "+this._segment1._handleOut),this._segment2._handleIn.isZero()||t.push("handle2: "+this._segment2._handleIn),t.push("point2: "+this._segment2._point),"{ "+t.join(", ")+" }"},statics:{getValues:function(t,e){var n=t._point,i=t._handleOut,r=e._handleIn,s=e._point;return[n._x,n._y,n._x+i._x,n._y+i._y,s._x+r._x,s._y+r._y,s._x,s._y]},evaluate:function(t,e,n,i){var r,s,a=n?e:M.getParameterAt(t,e,0),h=t[0],u=t[1],c=t[2],l=t[3],d=t[4],f=t[5],_=t[6],g=t[7];if(0!==i||0!==a&&1!==a){var p=3*(c-h),v=3*(d-c)-p,m=_-h-p-v,y=3*(l-u),w=3*(f-l)-y,x=g-u-y-w;if(0===i)r=((m*a+v)*a+p)*a+h,s=((x*a+w)*a+y)*a+u;else{var b=1e-5;if(b>a&&c==h&&l==u||a>1-b&&d==_&&f==g?(r=d-c,s=f-l):(r=(3*m*a+2*v)*a+p,s=(3*x*a+2*w)*a+y),3===i){var C=6*m*a+2*v,S=6*x*a+2*w;return(r*S-s*C)/Math.pow(r*r+s*s,1.5)}}}else r=0===a?h:_,s=0===a?u:g;return 2==i?new o(s,-r):new o(r,s)},subdivide:function(t,e){var n=t[0],i=t[1],r=t[2],s=t[3],a=t[4],o=t[5],h=t[6],u=t[7];void 0===e&&(e=.5);var c=1-e,l=c*n+e*r,d=c*i+e*s,f=c*r+e*a,_=c*s+e*o,g=c*a+e*h,p=c*o+e*u,v=c*l+e*f,m=c*d+e*_,y=c*f+e*g,w=c*_+e*p,x=c*v+e*y,b=c*m+e*w;return[[n,i,l,d,v,m,x,b],[x,b,y,w,g,p,h,u]]},solveCubic:function(t,e,n,i){var r=t[e],s=t[e+2],o=t[e+4],h=t[e+6],u=3*(s-r),c=3*(o-s)-u,l=h-r-u-c;return a.solveCubic(l,c,u,r-n,i)},getParameterOf:function(t,e,n){if(Math.abs(t[0]-e)<1e-5&&Math.abs(t[1]-n)<1e-5)return 0;if(Math.abs(t[6]-e)<1e-5&&Math.abs(t[7]-n)<1e-5)return 1;for(var i,r,s=[],a=[],o=M.solveCubic(t,0,e,s),h=M.solveCubic(t,1,n,a),u=0;-1==o||o>u;)if(-1==o||(i=s[u++])>=0&&1>=i){for(var c=0;-1==h||h>c;)if((-1==h||(r=a[c++])>=0&&1>=r)&&(-1==o?i=r:-1==h&&(r=i),Math.abs(i-r)<1e-5))return.5*(i+r);if(-1==o)break}return null},getPart:function(t,e,n){return e>0&&(t=M.subdivide(t,e)[1]),1>n&&(t=M.subdivide(t,(n-e)/(1-e))[0]),t},isLinear:function(t){return t[0]===t[2]&&t[1]===t[3]&&t[4]===t[6]&&t[5]===t[7]},isFlatEnough:function(t,e){var n=t[0],i=t[1],r=t[2],s=t[3],a=t[4],o=t[5],h=t[6],u=t[7],c=3*r-2*n-h,l=3*s-2*i-u,d=3*a-2*h-n,f=3*o-2*u-i;return Math.max(c*c,d*d)+Math.max(l*l,f*f)<10*e*e},getArea:function(t){var e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],h=t[7];return(3*r*e-1.5*r*s-1.5*r*o-3*n*i-1.5*n*s-.5*n*o+1.5*a*e+1.5*a*i-3*a*o+.5*h*e+1.5*h*i+3*h*s)/10},getBounds:function(t){for(var e=t.slice(0,2),n=e.slice(),i=[0,0],r=0;2>r;r++)M._addBounds(t[r],t[r+2],t[r+4],t[r+6],r,0,e,n,i);return new d(e[0],e[1],n[0]-e[0],n[1]-e[1])},_getCrossings:function(t,e,n,i,r){function s(t){return M.evaluate(e,1,!0,1).y*t.y>0}var a=M.solveCubic(t,1,i,r),o=0,h=1e-5,u=Math.abs;-1===a&&(r[0]=M.getParameterOf(t,n,i),a=null!==r[0]?1:0);for(var c=0;a>c;c++){var l=r[c];if(l>-h&&1-h>l){var d=M.evaluate(t,l,!0,0);if(n-180&&0>_&&(l>h||s(f)))continue}else if(u(f.y)l&&!s(f))continue;o++}}}return o},_addBounds:function(t,e,n,i,r,s,o,h,u){function c(t,e){var n=t-e,i=t+e;nh[r]&&(h[r]=i)}var l=3*(e-n)-t+i,d=2*(t+n)-4*e,f=e-t,_=a.solveQuadratic(l,d,f,u),g=1e-5,p=1-g;c(i,0);for(var v=0;_>v;v++){var m=u[v],y=1-m;m>g&&p>m&&c(y*y*y*t+3*y*y*m*e+3*y*m*m*n+m*m*m*i,s)}}}},t.each(["getBounds","getStrokeBounds","getHandleBounds","getRoughBounds"],function(t){this[t]=function(){this._bounds||(this._bounds={});var e=this._bounds[t];return e||(e=this._bounds[t]=z[t]([this._segment1,this._segment2],!1,this._path.getStyle())),e.clone()}},{}),t.each(["getPoint","getTangent","getNormal","getCurvatureAt"],function(t,e){this[t+"At"]=function(t,n){return M.evaluate(this.getValues(),t,n,e)},this[t]=function(t){return M.evaluate(this.getValues(),t,!0,e)}},{getParameterAt:function(t,e){return M.getParameterAt(this.getValues(),t,void 0!==e?e:0>t?1:0)},getParameterOf:function(t){return t=o.read(arguments),M.getParameterOf(this.getValues(),t.x,t.y)},getLocationAt:function(t,e){return e||(t=this.getParameterAt(t)),new I(this,t)},getLocationOf:function(t){t=o.read(arguments);var e=this.getParameterOf(t);return null!=e?new I(this,e):null},getNearestLocation:function(t){function e(e){if(e>=0&&1>=e){var i=t.getDistance(M.evaluate(n,e,!0,0),!0);if(s>i)return s=i,h=e,!0}}t=o.read(arguments);for(var n=this.getValues(),i=100,r=a.TOLERANCE,s=1/0,h=0,u=0;i>=u;u++)e(u/i);for(var c=1/(2*i);c>r;)e(h-c)||e(h+c)||(c/=2);var l=M.evaluate(n,h,!0,0);return new I(this,h,l,null,null,null,t.getDistance(l))},getNearestPoint:function(t){return t=o.read(arguments),this.getNearestLocation(t).getPoint()}}),new function(){function t(t){var e=t[0],n=t[1],i=t[2],r=t[3],s=t[4],a=t[5],o=t[6],h=t[7],u=9*(i-s)+3*(o-e),c=6*(e+s)-12*i,l=3*(i-e),d=9*(r-a)+3*(h-n),f=6*(n+a)-12*r,_=3*(r-n);return function(t){var e=(u*t+c)*t+l,n=(d*t+f)*t+_;return Math.sqrt(e*e+n*n)}}function e(t,e){return Math.max(2,Math.min(16,Math.ceil(32*Math.abs(e-t))))}return{statics:!0,getLength:function(n,i,r){if(void 0===i&&(i=0),void 0===r&&(r=1),n[0]==n[2]&&n[1]==n[3]&&n[6]==n[4]&&n[7]==n[5]){var s=n[6]-n[0],o=n[7]-n[1];return(r-i)*Math.sqrt(s*s+o*o)}var h=t(n);return a.integrate(h,i,r,e(i,r))},getParameterAt:function(n,i,r){function s(t){var n=e(r,t);return f+=t>r?a.integrate(c,r,t,n):-a.integrate(c,t,r,n),r=t,f-i}if(0===i)return r;var o=i>0,h=o?r:0,u=o?1:r,i=Math.abs(i),c=t(n),l=a.integrate(c,h,u,e(h,u));if(i>=l)return o?u:h;var d=i/l,f=0;return a.findRoot(s,c,o?h+d:u-d,h,u,16,1e-5)}}},new function(){function t(t,e,n,i,r,s,a){var o=t[0],h=t[t.length-1];o&&i.equals(o._point)||h&&i.equals(h._point)||t.push(new I(e,n,i,r,s,a))}function e(i,r,s,a,o,h,u,c){if(c=(c||0)+1,!(c>20)){h=h||[0,1],u=u||[0,1];for(var l=M.getPart(i,h[0],h[1]),d=M.getPart(r,u[0],u[1]),f=0;f++<20;){var _,g=n(l,d,_=u.slice()),p=0;if(0===g)break;if(g>0){if(u=_,d=M.getPart(r,u[0],u[1]),p=n(d,l,_=h.slice()),0===p)break;g>0&&(h=_,l=M.getPart(i,h[0],h[1]))}if(0>g||0>p){if(h[1]-h[0]>u[1]-u[0]){var v=(h[0]+h[1])/2;e(i,r,s,a,o,[h[0],v],u,c),e(i,r,s,a,o,[v,h[1]],u,c);break}var v=(u[0]+u[1])/2;e(i,r,s,a,o,h,[u[0],v],c),e(i,r,s,a,o,h,[v,u[1]],c);break}if(Math.abs(h[1]-h[0])<=1e-5&&Math.abs(u[1]-u[0])<=1e-5){var m=(h[0]+h[1])/2,y=(u[0]+u[1])/2;t(o,s,m,M.evaluate(i,m,!0,0),a,y,M.evaluate(r,y,!0,0));break}}}}function n(t,e,n){var r=t[0],s=t[1],a=t[2],o=t[3],h=t[4],u=t[5],c=t[6],l=t[7],d=e[0],f=e[1],_=e[2],p=e[3],v=e[4],m=e[5],y=e[6],w=e[7],x=g.getSignedDistance,b=x(r,s,c,l,a,o)||0,C=x(r,s,c,l,h,u)||0,S=b*C>0?.75:4/9,k=S*Math.min(0,b,C),P=S*Math.max(0,b,C),I=x(r,s,c,l,d,f),A=x(r,s,c,l,_,p),z=x(r,s,c,l,v,m),L=x(r,s,c,l,y,w);if(k>Math.max(I,A,z,L)||PL&&(O=k,k=P,P=O);for(var D=-1/0,j=1/0,E=-1/0,B=0,N=T.length;N>B;B++){var F=T[B],R=T[(B+1)%N];R[1]=V&&Z>=k){var X=q+(k-V)/U;j>X&&(j=X),X>D&&(D=X)}if(P>=V&&Z>=P){var X=q+(P-V)/U;X>E&&(E=X),j>X&&(j=0)}}if(1/0!==j&&E!==-1/0){var J=Math.min(k,P),G=Math.max(k,P);L>J&&G>L&&(E=1),I>J&&G>I&&(j=0),D>E&&(E=1);var W=n[0],$=n[1]-W;if(n[0]=W+j*$,n[1]=W+E*$,($-(n[1]-n[0]))/$>=.2)return 1}return M.getBounds(t).touches(M.getBounds(e))?-1:0}function i(t,e,n,i){var r=[0,t],s=[1/3,e],a=[2/3,n],o=[1,i],h=g.getSignedDistance,u=h(0,t,1,i,1/3,e),c=h(0,t,1,i,2/3,n);if(0>u*c)return[r,s,o,a];var l,d;return Math.abs(u)>Math.abs(c)?(l=s,d=(i-n-(i-t)/3)*(2*(i-n)-i+e)/3):(l=a,d=(e-t+(t-i)/3)*(-2*(t-e)+t-n)/3),0>d?[r,l,o]:[r,s,a,o]}function r(e,n,i,r,s){for(var a=M.isLinear(e),o=a?n:e,h=a?e:n,u=h[0],c=h[1],l=h[6],d=h[7],f=l-u,_=d-c,g=Math.atan2(-_,f),p=Math.sin(g),v=Math.cos(g),m=f*v-_*p,y=[],w=0;8>w;w+=2){var x=o[w]-u,b=o[w+1]-c;y.push(x*v-b*p,b*v+x*p)}for(var C=[],S=M.solveCubic(y,1,0,C),w=0;S>w;w++){var k=C[w];if(k>=0&&1>=k){var P=M.evaluate(y,k,!0,0);P.x>=0&&P.x<=m&&t(s,a?r:i,k,M.evaluate(o,k,!0,0),a?i:r)}}}function s(e,n,i,r,s){var a=g.intersect(e[0],e[1],e[6],e[7],n[0],n[1],n[6],n[7]);a&&t(s,i,null,a,r)}return{statics:{getIntersections:function(t,n,i,a,o){var h=M.isLinear(t),u=M.isLinear(n);return(h&&u?s:h||u?r:e)(t,n,i,a,o),o}}}}),I=t.extend({_class:"CurveLocation",initialize:function pe(t,e,n,i,r,s,a){this._id=pe._id=(pe._id||0)+1,this._curve=t,this._segment1=t._segment1,this._segment2=t._segment2,this._parameter=e,this._point=n,this._curve2=i,this._parameter2=r,this._point2=s,this._distance=a},getSegment:function(){if(!this._segment){var t=this.getCurve(),e=this.getParameter();if(1===e)this._segment=t._segment2;else if(0===e||arguments[0])this._segment=t._segment1;else{if(null==e)return null;this._segment=t.getLength(0,e)a;a++)s[a]=i[a].getValues();for(var a=0,o=n.length;o>a;a++)for(var h=n[a],u=h.getValues(),c=0;r>c;c++)M.getIntersections(u,s[c],h,i[c],e);return e},setPathData:function(t){function e(t,e,n){var r=parseFloat(i[t]);return a&&(r+=h[e]),n&&(h[e]=r),r}function n(t,n){return new o(e(t,"x",n),e(t+1,"y",n))}var i,r,s=t.match(/[a-z][^a-z]*/gi),a=!1,h=new o;"path"===this._type?this.removeSegments():this.removeChildren();for(var u=0,c=s.length;c>u;u++){var l=s[u],d=l[0],f=d.toLowerCase();i=l.slice(1).trim().split(/[\s,]+|(?=[+-])/),a=d===f;var _=i.length;switch(f){case"m":case"l":for(var g=0;_>g;g+=2)this[0===g&&"m"===f?"moveTo":"lineTo"](n(g,!0));break;case"h":case"v":for(var p="h"==f?"x":"y",g=0;_>g;g++)e(g,p,!0),this.lineTo(h);break;case"c":for(var g=0;_>g;g+=6)this.cubicCurveTo(n(g),r=n(g+2),n(g+4,!0));break;case"s":for(var g=0;_>g;g+=4)this.cubicCurveTo(h.multiply(2).subtract(r),r=n(g),n(g+2,!0));break;case"q":for(var g=0;_>g;g+=4)this.quadraticCurveTo(r=n(g),n(g+2,!0));break;case"t":for(var g=0;_>g;g+=2)this.quadraticCurveTo(r=h.multiply(2).subtract(r),n(g,!0));break;case"a":break;case"z":this.closePath()}}},_canComposite:function(){return!(this.hasFill()&&this.hasStroke())}}),z=A.extend({_class:"Path",_serializeFields:{segments:[],closed:!1},initialize:function(t){this._closed=!1,this._segments=[],m.call(this);var e=Array.isArray(t)?"object"==typeof t[0]?t:arguments:!t||void 0===t.point&&void 0===t.x?null:arguments;this.setSegments(e||[]),t&&!e&&this._set(t)},clone:function(){var t=this._clone(new z(this._segments));return t._closed=this._closed,void 0!==this._clockwise&&(t._clockwise=this._clockwise),t},_changed:function(t){if(m.prototype._changed.call(this,t),4&t){if(delete this._length,delete this._clockwise,this._curves)for(var e=0,n=this._curves.length;n>e;e++)this._curves[e]._changed(5)}else 8&t&&delete this._bounds},getSegments:function(){return this._segments},setSegments:function(t){this._selectedSegmentState=0,this._segments.length=0,delete this._curves,this._add(k.readAll(t))},getFirstSegment:function(){return this._segments[0]},getLastSegment:function(){return this._segments[this._segments.length-1]},getCurves:function(){var t=this._curves,e=this._segments;if(!t){var n=this._countCurves();t=this._curves=Array(n);for(var i=0;n>i;i++)t[i]=new M(this,e[i],e[i+1]||e[0])}return t},getFirstCurve:function(){return this.getCurves()[0]},getLastCurve:function(){var t=this.getCurves();return t[t.length-1]},getPathData:function(){function t(t,e,s){var a=t._point,o=e._point,h=t._handleOut,u=e._handleIn;if(h.isZero()&&u.isZero())s||r.push("L"+i.point(o,n));else{var c=o.subtract(a);r.push("c"+i.point(h,n)+" "+i.point(c.add(u),n)+" "+i.point(c,n))}}var e=this._segments,n=arguments[0],i=s.instance,r=[];if(0===e.length)return"";r.push("M"+i.point(e[0]._point));for(var a=0,o=e.length-1;o>a;a++)t(e[a],e[a+1],!1);return this._closed&&(t(e[e.length-1],e[0],!0),r.push("z")),r.join("")},isClosed:function(){return this._closed},setClosed:function(t){if(this._closed!=(t=!!t)){if(this._closed=t,this._curves){var e=this._curves.length=this._countCurves();t&&(this._curves[e-1]=new M(this,this._segments[e-1],this._segments[0]))}this._changed(5)}},isEmpty:function(){return 0===this._segments.length},isPolygon:function(){for(var t=0,e=this._segments.length;e>t;t++)if(!this._segments[t].isLinear())return!1;return!0},_applyMatrix:function(t){for(var e=Array(6),n=0,i=this._segments.length;i>n;n++)this._segments[n]._transformCoordinates(t,e,!0);return!0},_add:function(t,e){for(var n=this._segments,i=this._curves,r=t.length,s=null==e,e=s?n.length:e,a=this.isFullySelected(),o=0;r>o;o++){var h=t[o];h._path&&(h=t[o]=h.clone()),h._path=this,h._index=e+o,a&&(h._selectionState=4),h._selectionState&&this._updateSelection(h,0,h._selectionState)}if(s)n.push.apply(n,t);else{n.splice.apply(n,[e,0].concat(t));for(var o=e+r,u=n.length;u>o;o++)n[o]._index=o}if(i||t._curves){i||(i=this._curves=[]);var c=e>0?e-1:e,l=c,d=Math.min(c+r,this._countCurves());t._curves&&(i.splice.apply(i,[c,0].concat(t._curves)),l+=t._curves.length);for(var o=l;d>o;o++)i.splice(o,0,new M(this,null,null));this._adjustCurves(c,d)}return this._changed(5),t},_adjustCurves:function(t,e){for(var n,i=this._segments,r=this._curves,s=t;e>s;s++)n=r[s],n._path=this,n._segment1=i[s],n._segment2=i[s+1]||i[0];(n=r[this._closed&&0===t?i.length-1:t-1])&&(n._segment2=i[t]||i[0]),(n=r[e])&&(n._segment1=i[e])},_countCurves:function(){var t=this._segments.length;return!this._closed&&t>0?t-1:t},add:function(t){return arguments.length>1&&"number"!=typeof t?this._add(k.readAll(arguments)):this._add([k.read(arguments)])[0]},insert:function(t,e){return arguments.length>2&&"number"!=typeof e?this._add(k.readAll(arguments,1),t):this._add([k.read(arguments,1)],t)[0]},addSegment:function(){return this._add([k.read(arguments)])[0]},insertSegment:function(t){return this._add([k.read(arguments,1)],t)[0]},addSegments:function(t){return this._add(k.readAll(t))},insertSegments:function(t,e){return this._add(k.readAll(e),t)},removeSegment:function(t){return this.removeSegments(t,t+1)[0]||null},removeSegments:function(e,n){e=e||0,n=t.pick(n,this._segments.length);var i=this._segments,r=this._curves,s=i.length,a=i.splice(e,n-e),o=a.length;if(!o)return a;for(var h=0;o>h;h++){var u=a[h];u._selectionState&&this._updateSelection(u,u._selectionState,0),delete u._index,delete u._path}for(var h=e,c=i.length;c>h;h++)i[h]._index=h;if(r){var l=e>0&&n===s+(this._closed?1:0)?e-1:e,r=r.splice(l,o);arguments[2]&&(a._curves=r.slice(1)),this._adjustCurves(l,l)}return this._changed(5),a},isFullySelected:function(){return this._selected&&this._selectedSegmentState==4*this._segments.length},setFullySelected:function(t){t&&this._selectSegments(!0),this.setSelected(t)},setSelected:function ve(t){t||this._selectSegments(!1),ve.base.call(this,t)},_selectSegments:function(t){var e=this._segments.length;this._selectedSegmentState=t?4*e:0;for(var n=0;e>n;n++)this._segments[n]._selectionState=t?4:0},_updateSelection:function(t,e,n){t._selectionState=n;var i=this._selectedSegmentState+=n-e;i>0&&this.setSelected(!0)},flatten:function(t){for(var e=new O(this),n=0,i=e.length/Math.ceil(e.length/t),r=e.length+(this._closed?-i:i)/2,s=[];r>=n;)s.push(new k(e.evaluate(n,0))),n+=i;this.setSegments(s)},simplify:function(t){if(this._segments.length>2){var e=new T(this,t||2.5);this.setSegments(e.fit())}},split:function(t,e){if(null!==e){if(1==arguments.length){var n=t;"number"==typeof n&&(n=this.getLocationAt(n)),t=n.index,e=n.parameter}e>=1&&(t++,e--);var i=this.getCurves();if(t>=0&&t0&&i[t++].divide(e);var r,s=this.removeSegments(t,this._segments.length,!0);return this._closed?(this.setClosed(!1),r=this):t>0&&(r=this._clone((new z).insertAbove(this,!0))),r._add(s,0),this.addSegment(s[0]),r}return null}},isClockwise:function(){return void 0!==this._clockwise?this._clockwise:z.isClockwise(this._segments)},setClockwise:function(t){this.isClockwise()!=(t=!!t)&&this.reverse(),this._clockwise=t},reverse:function(){this._segments.reverse();for(var t=0,e=this._segments.length;e>t;t++){var n=this._segments[t],i=n._handleIn;n._handleIn=n._handleOut,n._handleOut=i,n._index=t}delete this._curves,void 0!==this._clockwise&&(this._clockwise=!this._clockwise)},join:function(t){if(t){var e=t._segments,n=this.getLastSegment(),i=t.getLastSegment();n._point.equals(i._point)&&t.reverse();var r=t.getFirstSegment();if(n._point.equals(r._point))n.setHandleOut(r._handleOut),this._add(e.slice(1));else{var s=this.getFirstSegment();s._point.equals(r._point)&&t.reverse(),i=t.getLastSegment(),s._point.equals(i._point)?(s.setHandleIn(i._handleIn),this._add(e.slice(0,e.length-1),0)):this._add(e.slice())}t.remove();var s=this.getFirstSegment();return n=this.getLastSegment(),n._point.equals(s._point)&&(s.setHandleIn(n._handleIn),n.remove(),this.setClosed(!0)),this._changed(5),!0}return!1},reduce:function(){return this},getLength:function(){if(null==this._length){var t=this.getCurves();this._length=0;for(var e=0,n=t.length;n>e;e++)this._length+=t[e].getLength()}return this._length},getArea:function(){for(var t=this.getCurves(),e=0,n=0,i=t.length;i>n;n++)e+=t[n].getArea();return e},_getOffset:function(t){var e=t&&t.getIndex();if(null!=e){for(var n=this.getCurves(),i=0,r=0;e>r;r++)i+=n[r].getLength();var s=n[e];return i+s.getLength(0,t.getParameter())}return null},getLocationOf:function(t){t=o.read(arguments);for(var e=this.getCurves(),n=0,i=e.length;i>n;n++){var r=e[n].getLocationOf(t);if(r)return r}return null},getLocationAt:function(t,e){var n=this.getCurves(),i=0;if(e){var r=~~t;return n[r].getLocationAt(t-r,!0)}for(var s=0,a=n.length;a>s;s++){var o=i,h=n[s];if(i+=h.getLength(),i>=t)return h.getLocationAt(t-o)}return t<=this.getLength()?new I(n[n.length-1],1):null},getPointAt:function(t,e){var n=this.getLocationAt(t,e);return n&&n.getPoint()},getTangentAt:function(t,e){var n=this.getLocationAt(t,e);return n&&n.getTangent()},getNormalAt:function(t,e){var n=this.getLocationAt(t,e);return n&&n.getNormal()},getNearestLocation:function(t){t=o.read(arguments);for(var e=this.getCurves(),n=1/0,i=null,r=0,s=e.length;s>r;r++){var a=e[r].getNearestLocation(t);a._distanceh;h++){var c=n[h].getValues(),l=c[0],d=c[1];(l!==c[2]||d!==c[3]||l!==c[4]||d!==c[5]||l!==c[6]||d!==c[7])&&(r+=M._getCrossings(c,o,t.x,t.y,s),o=c)}return e||(r+=M._getCrossings(a,o,t.x,t.y,s)),1===(1&r)},_hitTest:function(t,e){function n(e,n,i){return t.getDistance(n)a;a++){var o=s(a);r+=M._getCrossings(o,n,t.x,t.y,i),n=o}return 1===(1&r)}function o(e){return("round"!==h||"round"!==u)&&(l=[],p||e._index>0&&e._index0)?a(t):t.getDistance(e._point)<=m}var h,u,c,l,d,f,_=this.getStyle(),g=this._segments,p=this._closed,v=e.tolerance||0,m=0,y=this;if(e.stroke&&_.getStrokeColor()&&(h=_.getStrokeJoin(),u=_.getStrokeCap(),m=_.getStrokeWidth()/2+v,c=m*_.getMiterLimit()),!e.ends||e.segments||p){if(e.segments||e.handles)for(var w=0,x=g.length;x>w;w++)if(f=i(g[w]))return f}else if(f=i(g[0],!0)||i(g[g.length-1],!0))return f;if(m>0){if(d=this.getNearestLocation(t)){var b=d.getParameter();0===b||1===b?o(d.getSegment())||(d=null):d._distance>m&&(d=null)}if(!d&&"miter"===h)for(var w=0,x=g.length;x>w;w++){var C=g[w];if(t.getDistance(C._point)<=c&&o(C)){d=C.getLocation();break}}}return!d&&e.fill&&this.hasFill()&&this.contains(t)?new S("fill",this):d?new S("stroke",this,{location:d}):null}},new function(){function t(t,e,n,i){function r(e){var n=a[e],i=a[e+1];(d!=n||f!=i)&&(t.beginPath(),t.moveTo(d,f),t.lineTo(n,i),t.stroke(),t.beginPath(),t.arc(n,i,s,0,2*Math.PI,!0),t.fill())}for(var s=i/2,a=Array(6),o=0,h=e.length;h>o;o++){var u=e[o];u._transformCoordinates(n,a,!1);var c=u._selectionState,l=4&c,d=a[0],f=a[1];(l||1&c)&&r(2),(l||2&c)&&r(4),t.save(),t.beginPath(),t.rect(d-s,f-s,i,i),t.fill(),l||(t.beginPath(),t.rect(d-s+1,f-s+1,i-2,i-2),t.fillStyle="#ffffff",t.fill()),t.restore()}}function e(t,e,n){function i(e){var i=d[e];if(n)i._transformCoordinates(n,_,!1),r=_[0],s=_[1];else{var f=i._point;r=f._x,s=f._y}if(g)t.moveTo(r,s),g=!1;else{if(n)h=_[2],u=_[3];else{var p=i._handleIn;h=r+p._x,u=s+p._y}h==r&&u==s&&c==a&&l==o?t.lineTo(r,s):t.bezierCurveTo(c,l,h,u,r,s)}if(a=r,o=s,n)c=_[4],l=_[5];else{var p=i._handleOut;c=a+p._x,l=o+p._y}}for(var r,s,a,o,h,u,c,l,d=e._segments,f=d.length,_=Array(6),g=!0,p=0;f>p;p++)i(p);e._closed&&f>1&&i(0)}return{_draw:function(t,n){var i=n.clip,r=n.compound;r||t.beginPath();var s=this.getStyle(),a=s.getFillColor(),o=s.getStrokeColor(),h=s.getDashArray(),u=!paper.support.nativeDash&&o&&h&&h.length;if((a||o&&!u||r||i)&&e(t,this),this._closed&&t.closePath(),!i&&!r&&(a||o)&&(this._setStyles(t),a&&t.fill(),o)){if(u){t.beginPath();for(var c,l=new O(this),d=s.getDashOffset(),f=0;ds;s++)i[s]=1/r,r=(e-1>s?4:2)-i[s],n[s]=(t[s]-n[s-1])/r;for(var s=1;e>s;s++)n[e-s-1]-=i[e-s]*n[e-s];return n}return{smooth:function(){var e,n=this._segments,i=n.length,r=i;if(!(2>=i)){this._closed?(e=Math.min(i,4),r+=2*Math.min(i,e)):e=0;for(var s=[],a=0;i>a;a++)s[a+e]=n[a]._point;if(this._closed)for(var a=0;e>a;a++)s[a]=n[a+i-e]._point,s[a+i+e]=n[a]._point;else r--;for(var h=[],a=1;r-1>a;a++)h[a]=4*s[a]._x+2*s[a+1]._x;h[0]=s[0]._x+2*s[1]._x,h[r-1]=3*s[r-1]._x;for(var u=t(h),a=1;r-1>a;a++)h[a]=4*s[a]._y+2*s[a+1]._y;h[0]=s[0]._y+2*s[1]._y,h[r-1]=3*s[r-1]._y;var c=t(h);if(this._closed){for(var a=0,l=i;e>a;a++,l++){var d=a/e,f=1-d,_=a+e,g=l+e;u[l]=u[a]*d+u[l]*f,c[l]=c[a]*d+c[l]*f,u[g]=u[_]*f+u[g]*d,c[g]=c[_]*f+c[g]*d}r--}for(var p=null,a=e;r-e>=a;a++){var v=n[a-e];p&&v.setHandleIn(p.subtract(v._point)),r>a&&(v.setHandleOut(new o(u[a],c[a]).subtract(v._point)),p=r-1>a?new o(2*s[a+1]._x-u[a+1],2*s[a+1]._y-c[a+1]):new o((s[r]._x+u[r-1])/2,(s[r]._y+c[r-1])/2))}if(this._closed&&p){var v=this._segments[0];v.setHandleIn(p.subtract(v._point))}}}}},new function(){function e(t){var e=t._segments;if(0==e.length)throw Error("Use a moveTo() command first");return e[e.length-1]}return{moveTo:function(){1===this._segments.length&&this.removeSegment(0),this._segments.length||this._add([new k(o.read(arguments))])},moveBy:function(){throw Error("moveBy() is unsupported on Path items.")},lineTo:function(){this._add([new k(o.read(arguments))])},cubicCurveTo:function(){var t=o.read(arguments),n=o.read(arguments),i=o.read(arguments),r=e(this);r.setHandleOut(t.subtract(r._point)),this._add([new k(i,n.subtract(i))])},quadraticCurveTo:function(){var t=o.read(arguments),n=o.read(arguments),i=e(this)._point;this.cubicCurveTo(t.add(i.subtract(t).multiply(1/3)),t.add(n.subtract(t).multiply(1/3)),n)},curveTo:function(){var n=o.read(arguments),i=o.read(arguments),r=t.pick(t.read(arguments),.5),s=1-r,a=e(this)._point,h=n.subtract(a.multiply(s*s)).subtract(i.multiply(r*r)).divide(2*r*s);if(h.isNaN())throw Error("Cannot put a curve through points with parameter = "+r);this.quadraticCurveTo(h,i)},arcTo:function(n,i){var r,s=e(this),a=s._point,h=o.read(arguments),u=t.pick(t.peek(arguments),!0);if("boolean"==typeof u){n=h,i=u;var c=a.add(n).divide(2),r=c.add(c.subtract(a).rotate(i?-90:90))}else r=h,n=o.read(arguments);var l=new g(a.add(r).divide(2),r.subtract(a).rotate(90),!0),d=new g(r.add(n).divide(2),n.subtract(r).rotate(90),!0),f=l.intersect(d,!0),_=new g(a,n),p=_.getSide(r);if(!f){if(!p)return this.lineTo(n);throw Error("Cannot put an arc through the given points: "+[a,r,n])}var v=a.subtract(f),m=v.getDirectedAngle(n.subtract(f)),y=_.getSide(f);0==y?m=p*Math.abs(m):p==y&&(m-=360*(0>m?-1:1));for(var w=Math.abs(m),x=w>=360?4:Math.ceil(w/90),b=m/x,C=b*Math.PI/360,S=4/3*Math.sin(C)/(1+Math.cos(C)),P=[],M=0;x>=M;M++){var I=x>M?f.add(v):n,A=x>M?v.rotate(90).multiply(S):null;0==M?s.setHandleOut(A):P.push(new k(I,v.rotate(-90).multiply(S),A)),v=v.rotate(b)}this._add(P)},lineBy:function(t){t=o.read(arguments);var n=e(this);this.lineTo(n._point.add(t))},curveBy:function(t,n,i){t=o.read(t),n=o.read(n);var r=e(this)._point;this.curveTo(r.add(t),r.add(n),i)},arcBy:function(t,n){t=o.read(t),n=o.read(n); +var i=e(this)._point;this.arcTo(i.add(t),i.add(n))},closePath:function(){var t=this.getFirstSegment(),e=this.getLastSegment();t._point.equals(e._point)&&(t.setHandleIn(e._handleIn),e.remove()),this.setClosed(!0)}}},{_getBounds:function(t,e){return z[t](this._segments,this._closed,this.getStyle(),e)},statics:{isClockwise:function(t){function e(t,e){s&&(r+=(n-t)*(e+i)),n=t,i=e,s=!0}for(var n,i,r=0,s=!1,a=0,o=t.length;o>a;a++){var h=t[a],u=t[o>a+1?a+1:0],c=h._point,l=h._handleOut,d=u._handleIn,f=u._point;e(c._x,c._y),e(c._x+l._x,c._y+l._y),e(f._x+d._x,f._y+d._y),e(f._x,f._y)}return r>0},getBounds:function(t,e,n,i,r){function s(t){t._transformCoordinates(i,o,!1);for(var e=0;2>e;e++)M._addBounds(h[e],h[e+4],o[e+2],o[e],e,r?r[e]:0,u,c,l);var n=h;h=o,o=n}var a=t[0];if(!a)return new d;for(var o=Array(6),h=a._transformCoordinates(i,Array(6),!1),u=h.slice(0,2),c=u.slice(),l=Array(2),f=1,_=t.length;_>f;f++)s(t[f]);return e&&s(a),new d(u[0],u[1],c[0]-u[0],c[1]-u[1])},getStrokeBounds:function(t,e,n,i){function r(t,e){if(!e)return[t,t];var n=e.shiftless(),i=n.transform(new o(t,0)),r=n.transform(new o(0,t)),s=i.getAngleInRadians(),a=i.getLength(),h=r.getLength(),u=Math.sin(s),c=Math.cos(s),l=Math.tan(s),d=-Math.atan(h*l/a),f=Math.atan(h/(l*a));return[Math.abs(a*Math.cos(d)*c-h*Math.sin(d)*u),Math.abs(h*Math.sin(f)*c+a*Math.cos(f)*u)]}function s(t){_=_.include(i?i._transformPoint(t,t):t)}function a(t,e){"round"===e||!t._handleIn.isZero()&&!t._handleOut.isZero()?_=_.unite(m.setCenter(i?i._transformPoint(t._point):t._point)):z._addSquareJoin(t,e,l,v,s)}function h(t,e){switch(e){case"round":a(t,e);break;case"butt":case"square":z._addSquareCap(t,e,l,s)}}if(!n.getStrokeColor()||!n.getStrokeWidth())return z.getBounds(t,e,n,i);for(var c=t.length-(e?0:1),l=n.getStrokeWidth()/2,f=r(l,i),_=z.getBounds(t,e,n,i,f),g=n.getStrokeJoin(),p=n.getStrokeCap(),v=l*n.getMiterLimit(),m=new d(new u(f).multiply(2)),y=1;c>y;y++)a(t[y],g);return e?a(t[0],g):(h(t[0],p),h(t[t.length-1],p)),_},_addSquareJoin:function(t,e,n,i,r,s){var a=t.getCurve(),h=a.getPrevious(),u=a.getPointAt(0,!0),c=h.getNormalAt(1,!0),l=a.getNormalAt(0,!0),d=c.getDirectedAngle(l)<0?-n:n;if(c.setLength(d),l.setLength(d),s&&(r(u),r(u.add(c))),"miter"===e){var f=new g(u.add(c),new o(-c.y,c.x),!0).intersect(new g(u.add(l),new o(-l.y,l.x),!0),!0);if(f&&u.getDistance(f)<=i&&(r(f),!s))return}s||r(u.add(c)),r(u.add(l))},_addSquareCap:function(t,e,n,i,r){var s=t._point,a=t.getLocation(),o=a.getNormal().normalize(n);r&&(i(s.subtract(o)),i(s.add(o))),"square"===e&&(s=s.add(o.rotate(0==a.getParameter()?-90:90))),i(s.add(o)),i(s.subtract(o))},getHandleBounds:function(t,e,n,i,r,s){var a=Array(6),o=1/0,h=-o,u=o,c=h;r=r/2||0,s=s/2||0;for(var l=0,f=t.length;f>l;l++){var _=t[l];_._transformCoordinates(i,a,!1);for(var g=0;6>g;g+=2){var p=0==g?s:r,v=a[g],m=a[g+1],y=v-p,w=v+p,x=m-p,b=m+p;o>y&&(o=y),w>h&&(h=w),u>x&&(u=x),b>c&&(c=b)}}return new d(o,u,h-o,c-u)},getRoughBounds:function(t,e,n,i){var r=n.getStrokeColor()?n.getStrokeWidth():0,s=r;return r>0&&("miter"===n.getStrokeJoin()&&(s=r*n.getMiterLimit()),"square"===n.getStrokeCap()&&(s=Math.max(s,r*Math.sqrt(2)))),z.getHandleBounds(t,e,n,i,r,s)}}});z.inject({statics:new function(){function e(e){var n=new z,i=t.getNamed(e);return i&&n._set(i),n}function n(){var t=d.readNamed(arguments,"rectangle"),n=u.readNamed(arguments,"radius",0,0,!0),i=t.getBottomLeft(!0),s=t.getTopLeft(!0),a=t.getTopRight(!0),o=t.getBottomRight(!0),h=e(arguments);if(!n||n.isZero())h._add([new k(i),new k(s),new k(a),new k(o)]);else{n=u.min(n,t.getSize(!0).divide(2));var c=n.multiply(2*r);h._add([new k(i.add(n.width,0),null,[-c.width,0]),new k(i.subtract(0,n.height),[0,c.height],null),new k(s.add(0,n.height),null,[0,-c.height]),new k(s.add(n.width,0),[-c.width,0],null),new k(a.subtract(n.width,0),null,[c.width,0]),new k(a.add(0,n.height),[0,-c.height],null),new k(o.subtract(0,n.height),null,[0,c.height]),new k(o.subtract(n.width,0),[c.width,0],null)])}return h._closed=!0,h}function i(){for(var t=d.readNamed(arguments,"rectangle"),n=e(arguments),i=t.getPoint(!0),r=t.getSize(!0),a=Array(4),o=0;4>o;o++){var h=s[o];a[o]=new k(h._point.multiply(r).add(i),h._handleIn.multiply(r),h._handleOut.multiply(r))}return n._add(a),n._closed=!0,n}var r=a.KAPPA/2,s=[new k([0,.5],[0,r],[0,-r]),new k([.5,0],[-r,0],[r,0]),new k([1,.5],[0,-r],[0,r]),new k([.5,1],[r,0],[-r,0])];return{Line:function(){return new z(o.readNamed(arguments,"from"),o.readNamed(arguments,"to")).set(t.getNamed(arguments))},Rectangle:n,RoundRectangle:n,Ellipse:i,Oval:i,Circle:function(){var e=o.readNamed(arguments,"center"),n=t.readNamed(arguments,"radius");return i(new d(e.subtract(n),new u(2*n,2*n))).set(t.getNamed(arguments))},Arc:function(){var t=o.readNamed(arguments,"from"),n=o.readNamed(arguments,"through"),i=o.readNamed(arguments,"to"),r=e(arguments);return r.moveTo(t),r.arcTo(n,i),r},RegularPolygon:function(){for(var n=o.readNamed(arguments,"center"),i=t.readNamed(arguments,"sides"),r=t.readNamed(arguments,"radius"),s=e(arguments),a=360/i,h=!(i%3),u=new o(0,h?-r:r),c=h?-1:.5,l=Array(i),d=0;i>d;d++)l[d]=new k(n.add(u.rotate((d+c)*a)));return s._add(l),s._closed=!0,s},Star:function(){for(var n=o.readNamed(arguments,"center"),i=2*t.readNamed(arguments,"points"),r=t.readNamed(arguments,"radius1"),s=t.readNamed(arguments,"radius2"),a=e(arguments),h=360/i,u=new o(0,-1),c=Array(i),l=0;i>l;l++)c[l]=new k(n.add(u.rotate(h*l).multiply(l%2?s:r)));return a._add(c),a._closed=!0,a}}}});var L=A.extend({_class:"CompoundPath",_serializeFields:{children:[]},initialize:function(t){A.call(this),this._children=[],this._namedChildren={},t&&!this._set(t)&&this.addChildren(Array.isArray(t)?t:arguments)},insertChildren:function me(t,e,n){e=me.base.call(this,t,e,n,"path");for(var i=0,r=!n&&e&&e.length;r>i;i++){var s=e[i];void 0===s._clockwise&&s.setClockwise(0===s._index)}return e},reduce:function(){if(1==this._children.length){var t=this._children[0];return t.insertAbove(this),this.remove(),t}return this},reverse:function(){for(var t=this._children,e=0,n=t.length;n>e;e++)t[e].reverse()},smooth:function(){for(var t=0,e=this._children.length;e>t;t++)this._children[t].smooth()},isClockwise:function(){var t=this.getFirstChild();return t&&t.isClockwise()},setClockwise:function(t){this.isClockwise()!=!!t&&this.reverse()},getFirstSegment:function(){var t=this.getFirstChild();return t&&t.getFirstSegment()},getLastSegment:function(){var t=this.getLastChild();return t&&t.getLastSegment()},getCurves:function(){for(var t=this._children,e=[],n=0,i=t.length;i>n;n++)e=e.concat(t[n].getCurves());return e},getFirstCurve:function(){var t=this.getFirstChild();return t&&t.getFirstCurve()},getLastCurve:function(){var t=this.getLastChild();return t&&t.getFirstCurve()},getArea:function(){for(var t=this._children,e=0,n=0,i=t.length;i>n;n++)e+=t[n].getArea();return e},getPathData:function(){for(var t=this._children,e=[],n=0,i=t.length;i>n;n++)e.push(t[n].getPathData(arguments[0]));return e.join(" ")},_contains:function(t){for(var e=[],n=0,i=this._children.length;i>n;n++){var r=this._children[n];r.contains(t)&&e.push(r)}return 1==(1&e.length)&&e},_hitTest:function ye(e,n){var i=ye.base.call(this,e,t.merge(n,{fill:!1}));return!i&&n.fill&&this.hasFill()&&(i=this._contains(e),i=i?new S("fill",i[0]):null),i},_draw:function(t,e){var n=this._children,i=this._style;if(0!==n.length){t.beginPath(),e=e.extend({compound:!0});for(var r=0,s=n.length;s>r;r++)n[r].draw(t,e);e.clip||(this._setStyles(t),i.getFillColor()&&t.fill(),i.getStrokeColor()&&t.stroke())}}},new function(){function e(t){if(!t._children.length)throw Error("Use a moveTo() command first");return t._children[t._children.length-1]}var n={moveTo:function(){var t=new z;this.addChild(t),t.moveTo.apply(t,arguments)},moveBy:function(){this.moveTo(e(this).getLastSegment()._point.add(o.read(arguments)))},closePath:function(){e(this).closePath()}};return t.each(["lineTo","cubicCurveTo","quadraticCurveTo","curveTo","arcTo","lineBy","curveBy","arcBy"],function(t){n[t]=function(){var n=e(this);n[t].apply(n,arguments)}}),n}),O=t.extend({initialize:function(t){function e(t,e){var n=M.getValues(t,e);s.curves.push(n),s._computeParts(n,t._index,0,1)}this.curves=[],this.parts=[],this.length=0,this.index=0;for(var n,i=t._segments,r=i[0],s=this,a=1,o=i.length;o>a;a++)n=i[a],e(r,n),r=n;t._closed&&e(n,i[0])},_computeParts:function(t,e,n,i){if(i-n>1/32&&!M.isFlatEnough(t,.25)){var r=M.subdivide(t),s=(n+i)/2;this._computeParts(r[0],e,n,s),this._computeParts(r[1],e,s,i)}else{var a=t[6]-t[0],o=t[7]-t[1],h=Math.sqrt(a*a+o*o);h>1e-5&&(this.length+=h,this.parts.push({offset:this.length,value:i,index:e}))}},getParameterAt:function(t){for(var e,n=this.index;e=n,!(0==n||this.parts[--n].offsete;e++){var r=this.parts[e];if(r.offset>=t){this.index=e;var s=this.parts[e-1],a=s&&s.index==r.index?s.value:0,o=s?s.offset:0;return{value:a+(r.value-a)*(t-o)/(r.offset-o),index:r.index}}}var r=this.parts[this.parts.length-1];return{value:1,index:r.index}},evaluate:function(t,e){var n=this.getParameterAt(t);return M.evaluate(this.curves[n.index],n.value,!0,e)},drawPart:function(t,e,n){e=this.getParameterAt(e),n=this.getParameterAt(n);for(var i=e.index;i<=n.index;i++){var r=M.getPart(this.curves[i],i==e.index?e.value:0,i==n.index?n.value:1);i==e.index&&t.moveTo(r[0],r[1]),t.bezierCurveTo.apply(t,r.slice(2))}}}),T=t.extend({initialize:function(t,e){this.points=[];for(var n,i=t._segments,r=0,s=i.length;s>r;r++){var a=i[r].point.clone();n&&n.equals(a)||(this.points.push(a),n=a)}this.error=e},fit:function(){var t=this.points,e=t.length;return this.segments=e>0?[new k(t[0])]:[],e>1&&this.fitCubic(0,e-1,t[1].subtract(t[0]).normalize(),t[e-2].subtract(t[e-1]).normalize()),this.segments},fitCubic:function(t,e,n,i){if(1==e-t){var r=this.points[t],s=this.points[e],a=r.getDistance(s)/3;return this.addCurve([r,r.add(n.normalize(a)),s.add(i.normalize(a)),s]),void 0}for(var o,h=this.chordLengthParameterize(t,e),u=Math.max(this.error,this.error*this.error),c=0;4>=c;c++){var l=this.generateBezier(t,e,h,n,i),d=this.findMaxError(t,e,l,h);if(d.error=u)break;this.reparameterize(t,e,h,l),u=d.error}var f=this.points[o-1].subtract(this.points[o]),_=this.points[o].subtract(this.points[o+1]),g=f.add(_).divide(2).normalize();this.fitCubic(t,o,n,g),this.fitCubic(o,e,g.negate(),i)},addCurve:function(t){var e=this.segments[this.segments.length-1];e.setHandleOut(t[1].subtract(t[0])),this.segments.push(new k(t[3],t[2].subtract(t[3])))},generateBezier:function(t,e,n,i,r){for(var s=1e-11,a=this.points[t],o=this.points[e],h=[[0,0],[0,0]],u=[0,0],c=0,l=e-t+1;l>c;c++){var d=n[c],f=1-d,_=3*d*f,g=f*f*f,p=_*f,v=_*d,m=d*d*d,y=i.normalize(p),w=r.normalize(v),x=this.points[t+c].subtract(a.multiply(g+p)).subtract(o.multiply(v+m));h[0][0]+=y.dot(y),h[0][1]+=y.dot(w),h[1][0]=h[0][1],h[1][1]+=w.dot(w),u[0]+=y.dot(x),u[1]+=w.dot(x)}var b,C,S=h[0][0]*h[1][1]-h[1][0]*h[0][1];if(Math.abs(S)>s){var k=h[0][0]*u[1]-h[1][0]*u[0],P=u[0]*h[1][1]-u[1]*h[0][1];b=P/S,C=k/S}else{var M=h[0][0]+h[0][1],I=h[1][0]+h[1][1];b=C=Math.abs(M)>s?u[0]/M:Math.abs(I)>s?u[1]/I:0}var A=o.getDistance(a);return s*=A,(s>b||s>C)&&(b=C=A/3),[a,a.add(i.normalize(b)),o.add(r.normalize(C)),o]},reparameterize:function(t,e,n,i){for(var r=t;e>=r;r++)n[r-t]=this.findRoot(i,this.points[r],n[r-t])},findRoot:function(t,e,n){for(var i=[],r=[],s=0;2>=s;s++)i[s]=t[s+1].subtract(t[s]).multiply(3);for(var s=0;1>=s;s++)r[s]=i[s+1].subtract(i[s]).multiply(2);var a=this.evaluate(3,t,n),o=this.evaluate(2,i,n),h=this.evaluate(1,r,n),u=a.subtract(e),c=o.dot(o)+u.dot(h);return Math.abs(c)<1e-5?n:n-u.dot(o)/c},evaluate:function(t,e,n){for(var i=e.slice(),r=1;t>=r;r++)for(var s=0;t-r>=s;s++)i[s]=i[s].multiply(1-n).add(i[s+1].multiply(n));return i[0]},chordLengthParameterize:function(t,e){for(var n=[0],i=t+1;e>=i;i++)n[i-t]=n[i-t-1]+this.points[i].getDistance(this.points[i-1]);for(var i=1,r=e-t;r>=i;i++)n[i]/=n[r];return n},findMaxError:function(t,e,n,i){for(var r=Math.floor((e-t+1)/2),s=0,a=t+1;e>a;a++){var o=this.evaluate(3,n,i[a-t]),h=o.subtract(this.points[a]),u=h.x*h.x+h.y*h.y;u>=s&&(s=u,r=a)}return{error:s,index:r}}});A.inject(new function(){function t(t,e){t.sort(function(t,e){var n=t.getPath(),i=e.getPath();return n===i?t.getIndex()+t.getParameter()-(e.getIndex()+e.getParameter()):n._id-i._id});for(var n=e&&[],i=t.length-1;i>=0;i--){var r=t[i],s=r.getIntersection(),a=r.divide(),o=a&&a.getSegment1()||r.getSegment();n&&n.push(s),o._intersection=s}return n}function e(t){if(t instanceof L){for(var e=t._children,n=e.length,i=Array(n),r=Array(n),s=e[0].isClockwise(),a=0;n>a;a++)i[a]=e[a].getBounds(),r[a]=0;for(var a=0;n>a;a++){for(var o=1;n>o;o++)a!==o&&i[a].contains(i[o])&&r[o]++;a>0&&0===r[a]%2&&e[a].setClockwise(s)}}return t}function n(n,r,s,a){n=e(n.clone()),r=e(r.clone());var h=n.isClockwise(),u=r.isClockwise(),c=n.getIntersections(r);t(t(c,!0)),a&&(r.reverse(),u=!u);for(var l=[].concat(n._children||[n]).concat(r._children||[r]),d=[],f=new L,_=0,g=l.length;g>_;_++){var p=l[_],v=p._parent,m=p.isClockwise(),y=p._segments;p=v instanceof L?v:p;for(var w=y.length-1;w>=0;w--){var x=y[w],b=x.getCurve().getPoint(.5),C=p!==n&&n.contains(b)&&(m===h||a||!i(n,b)),S=p!==r&&r.contains(b)&&(m===u||!i(r,b));s(p===n,C,S)?x._invalid=!0:d.push(x)}}for(var _=0,g=d.length;g>_;_++){var x=d[_];if(!x._visited){var p=new z,P=x._intersection,M=P&&P.getSegment(!0);x.getPrevious()._invalid&&x.setHandleIn(M?M._handleIn:new o(0,0));do{if(x._visited=!0,x._invalid&&x._intersection){var I=x._intersection.getSegment(!0);p.add(new k(x._point,x._handleIn,I._handleOut)),I._visited=!0,x=I}else p.add(x.clone());x=x.getNext()}while(x&&!x._visited&&x!==M);var A=p._segments.length;A>1&&(A>2||!p.isPolygon())?(p.setClosed(!0),f.addChild(p,!0)):p.remove()}}return n.remove(),r.remove(),f.reduce()}function i(t,e){var n=t.getCurves(),i=t.getBounds();if(i.contains(e))for(var r=0,s=n.length;s>r;r++){var a=n[r];if(a.getBounds().contains(e)&&a.getParameterOf(e))return!0}return!1}return{unite:function(t){return n(this,t,function(t,e,n){return e||n})},intersect:function(t){return n(this,t,function(t,e,n){return!(e||n)})},subtract:function(t){return n(this,t,function(t,e,n){return t&&n||!t&&!e},!0)},exclude:function(t){return new y([this.subtract(t),t.subtract(this)])},divide:function(t){return new y([this.subtract(t),this.intersect(t)])}}});var D=m.extend({_class:"TextItem",_boundsSelected:!0,_serializeFields:{content:null},_boundsGetter:"getBounds",initialize:function(e){var n=e&&t.isPlainObject(e)&&void 0===e.x&&void 0===e.y;m.call(this,n?null:o.read(arguments)),this._content="",this._lines=[],n&&this._set(e)},_clone:function we(t){return t.setContent(this._content),we.base.call(this,t)},getContent:function(){return this._content},setContent:function(t){this._content=""+t,this._lines=this._content.split(/\r\n|\n|\r/gm),this._changed(69)},isEmpty:function(){return!this._content},getCharacterStyle:"#getStyle",setCharacterStyle:"#setStyle",getParagraphStyle:"#getStyle",setParagraphStyle:"#setStyle"}),j=D.extend({_class:"PointText",initialize:function(){D.apply(this,arguments)},clone:function(){return this._clone(new j)},getPoint:function(){var t=this._matrix.getTranslation();return new h(t.x,t.y,this,"setPoint")},setPoint:function(t){t=o.read(arguments),this.translate(t.subtract(this._matrix.getTranslation()))},_draw:function(t){if(this._content){this._setStyles(t);var e=this._style,n=this._lines,i=e.getLeading();t.font=e.getFontStyle(),t.textAlign=e.getJustification();for(var r=0,s=n.length;s>r;r++){var a=n[r];e.getFillColor()&&t.fillText(a,0,0),e.getStrokeColor()&&t.strokeText(a,0,0),t.translate(0,i)}}}},new function(){var t=null;return{_getBounds:function(e,n){t||(t=Y.getContext(1,1));var i=this._style,r=this._lines,s=r.length,a=i.getJustification(),o=i.getLeading(),h=0;t.font=i.getFontStyle();for(var u=0,c=0;s>c;c++)u=Math.max(u,t.measureText(r[c]).width);"left"!==a&&(h-=u/("center"===a?2:1));var l=new d(h,s?-.75*o:0,u,s*o);return n?n._transformBounds(l,l):l}}}),E=t.extend(new function(){function e(t){var e=h[t];if(!e){i||(i=Y.getContext(1,1),i.globalCompositeOperation="copy"),i.fillStyle="rgba(0,0,0,0)",i.fillStyle=t,i.fillRect(0,0,1,1);var n=i.getImageData(0,0,1,1).data;e=h[t]=[n[0]/255,n[1]/255,n[2]/255]}return e.slice()}function n(t){var e=t.match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);if(e.length>=4){for(var n=[0,0,0],i=0;3>i;i++){var r=e[i+1];n[i]=parseInt(1==r.length?r+r:r,16)/255}return n}}var i,r={gray:["gray"],rgb:["red","green","blue"],hsb:["hue","saturation","brightness"],hsl:["hue","saturation","lightness"],gradient:["gradient","origin","destination","highlight"]},a={},h={},u=[[0,3,1],[2,0,1],[1,0,3],[1,2,0],[3,1,0],[0,1,2]],c={"rgb-hsb":function(t,e,n){var i=Math.max(t,e,n),r=Math.min(t,e,n),s=i-r,a=0===s?0:60*(i==t?(e-n)/s+(n>e?6:0):i==e?(n-t)/s+2:(t-e)/s+4);return[a,0===i?0:s/i,i]},"hsb-rgb":function(t,e,n){var t=t/60%6,i=Math.floor(t),r=t-i,i=u[i],s=[n,n*(1-e),n*(1-e*r),n*(1-e*(1-r))];return[s[i[0]],s[i[1]],s[i[2]]]},"rgb-hsl":function(t,e,n){var i=Math.max(t,e,n),r=Math.min(t,e,n),s=i-r,a=0===s,o=a?0:60*(i==t?(e-n)/s+(n>e?6:0):i==e?(n-t)/s+2:(t-e)/s+4),h=(i+r)/2,u=a?0:.5>h?s/(i+r):s/(2-i-r);return[o,u,h]},"hsl-rgb":function(t,e,n){if(t/=360,0===e)return[n,n,n];for(var i=[t+1/3,t,t-1/3],r=.5>n?n*(1+e):n+e-n*e,s=2*n-r,a=[],o=0;3>o;o++){var h=i[o];0>h&&(h+=1),h>1&&(h-=1),a[o]=1>6*h?s+6*(r-s)*h:1>2*h?r:2>3*h?s+6*(r-s)*(2/3-h):s}return a},"rgb-gray":function(t,e,n){return[.2989*t+.587*e+.114*n]},"gray-rgb":function(t){return[t,t,t]},"gray-hsb":function(t){return[0,0,t]},"gray-hsl":function(t){return[0,0,t]},"gradient-rgb":function(){return[]},"rgb-gradient":function(){return[]}};return t.each(r,function(e,n){a[n]=[],t.each(e,function(e,i){var r=t.capitalize(e),s=/^(hue|saturation)$/.test(e),h=a[n][i]="gradient"===e?function(t){var e=this._components[0];return t=B.read(Array.isArray(t)?t:arguments,0,0,!0),e!==t&&(e&&e._removeOwner(this),t&&t._addOwner(this)),t}:"hue"===e?function(t){return isNaN(t)?0:(t%360+360)%360}:"gradient"===n?function(){return o.read(arguments,0,0,"highlight"===e,!0)}:function(t){return isNaN(t)?0:Math.min(Math.max(t,0),1)};this["get"+r]=function(){return this._type===n||s&&/^hs[bl]$/.test(this._type)?this._components[i]:this._convert(n)[i]},this["set"+r]=function(t){this._type===n||s&&/^hs[bl]$/.test(this._type)||(this._components=this._convert(n),this._type=n),t=h.call(this,t),null!=t&&(this._components[i]=t,this._changed())}},this)},{_class:"Color",_readIndex:!0,initialize:function l(t){var i,s,o,h,u=Array.prototype.slice,c=arguments,d=0;Array.isArray(t)&&(c=t,t=c[0]);var f=null!=t&&typeof t;if("string"===f&&t in r&&(i=t,t=c[1],Array.isArray(t)?(s=t,o=c[2]):(this._read&&(d=1),c=u.call(c,1),f=typeof t)),!s){if(h="number"===f?c:"object"===f&&null!=t.length?t:null){i||(i=h.length>=3?"rgb":"gray");var _=r[i].length;o=h[_],this._read&&(d+=h===arguments?_+(null!=o?1:0):1),h.length>_&&(h=u.call(h,0,_))}else if("string"===f)s=t.match(/^#[0-9a-f]{3,6}$/i)?n(t):e(t),i="rgb";else if("object"===f)if(t.constructor===l){if(i=t._type,s=t._components.slice(),o=t._alpha,"gradient"===i)for(var g=1,p=s.length;p>g;g++){var v=s[g];v&&(s[g]=v.clone())}}else if(t.constructor===B)i="gradient",h=c;else{i="hue"in t?"lightness"in t?"hsl":"hsb":"gradient"in t||"stops"in t||"radial"in t?"gradient":"gray"in t?"gray":"rgb";var m=r[i];w=a[i],this._components=s=[];for(var g=0,p=m.length;p>g;g++){var y=t[m[g]];null==y&&0===g&&"gradient"===i&&"stops"in t&&(y={stops:t.stops,radial:t.radial}),y=w[g].call(this,y),null!=y&&(s[g]=y)}o=t.alpha}this._read&&i&&(d=1)}if(this._type=i||"rgb","gradient"===i&&(this._id=l._id=(l._id||0)+1),!s){this._components=s=[];for(var w=a[this._type],g=0,p=w.length;p>g;g++){var y=w[g].call(this,h&&h[g]);null!=y&&(s[g]=y)}}this._components=s,this._alpha=o,this._read&&(this._read=d)},_serialize:function(e,n){var i=this.getComponents();return t.serialize(/^(gray|rgb)$/.test(this._type)?i:[this._type].concat(i),e,!0,n)},_changed:function(){this._canvasStyle=null,this._owner&&this._owner._changed(17)},clone:function(){return new E(this._type,this._components.slice(),this._alpha)},_convert:function(t){var e;return this._type===t?this._components.slice():(e=c[this._type+"-"+t])?e.apply(this,this._components):c["rgb-"+t].apply(this,c[this._type+"-rgb"].apply(this,this._components))},convert:function(t){return new E(t,this._convert(t),this._alpha)},getType:function(){return this._type},setType:function(t){this._components=this._convert(t),this._type=t},getComponents:function(){var t=this._components.slice();return null!=this._alpha&&t.push(this._alpha),t},getAlpha:function(){return null!=this._alpha?this._alpha:1},setAlpha:function(t){this._alpha=null==t?null:Math.min(Math.max(t,0),1),this._changed()},hasAlpha:function(){return null!=this._alpha},equals:function(e){return t.isPlainValue(e)&&(e=E.read(arguments)),e===this||e&&this._type===e._type&&this._alpha===e._alpha&&t.equals(this._components,e._components)||!1},toString:function(){for(var t=r[this._type],e=[],n="gradient"===this._type,i=s.instance,a=0,o=t.length;o>a;a++){var h=this._components[a];null!=h&&e.push(t[a]+": "+(n?h:i.number(h)))}return null!=this._alpha&&e.push("alpha: "+i.number(this._alpha)),"{ "+e.join(", ")+" }"},toCSS:function(t){var e=this._convert("rgb"),n=t||null==this._alpha?1:this._alpha;return e=[Math.round(255*e[0]),Math.round(255*e[1]),Math.round(255*e[2])],1>n&&e.push(n),(4==e.length?"rgba(":"rgb(")+e.join(",")+")"},toCanvasStyle:function(t){if(this._canvasStyle)return this._canvasStyle;if("gradient"!==this._type)return this._canvasStyle=this.toCSS();var e,n=this._components,i=n[0],r=i._stops,s=n[1],a=n[2];if(i._radial){var o=a.getDistance(s),h=n[3];if(h){var u=h.subtract(s);u.getLength()>o&&(h=s.add(u.normalize(o-.1)))}var c=h||s;e=t.createRadialGradient(c.x,c.y,0,s.x,s.y,o)}else e=t.createLinearGradient(s.x,s.y,a.x,a.y);for(var l=0,d=r.length;d>l;l++){var f=r[l];e.addColorStop(f._rampPoint,f._color.toCanvasStyle())}return this._canvasStyle=e},transform:function(t){if("gradient"===this._type){for(var e=this._components,n=1,i=e.length;i>n;n++){var r=e[n];t._transformPoint(r,r,!0)}this._changed()}},statics:{_types:r,random:function(){var t=Math.random;return new E(t(),t(),t())}}})});t.each(E._types,function(e,n){var i=this[t.capitalize(n)+"Color"]=function(t){var e=null!=t&&typeof t,i="object"===e&&null!=t.length?t:"string"===e?null:arguments;return i?new E(n,i):new E(t)};if(3==n.length){var r=n.toUpperCase();E[r]=this[r+"Color"]=i}},this);var B=t.extend({_class:"Gradient",initialize:function xe(t,e){this._id=xe._id=(xe._id||0)+1,t&&this._set(t)&&(t=e=null),this._stops||this.setStops(t||["white","black"]),null==this._radial&&this.setRadial("string"==typeof e&&"radial"===e||e||!1)},_serialize:function(e,n){return n.add(this,function(){return t.serialize([this._stops,this._radial],e,!0,n)})},_changed:function(){for(var t=0,e=this._owners&&this._owners.length;e>t;t++)this._owners[t]._changed()},_addOwner:function(t){this._owners||(this._owners=[]),this._owners.push(t)},_removeOwner:function(t){var e=this._owners?this._owners.indexOf(t):-1;-1!=e&&(this._owners.splice(e,1),0===this._owners.length&&delete this._owners)},clone:function(){for(var t=[],e=0,n=this._stops.length;n>e;e++)t[e]=this._stops[e].clone();return new this.constructor(t)},getStops:function(){return this._stops},setStops:function(t){if(this.stops)for(var e=0,n=this._stops.length;n>e;e++)delete this._stops[e]._owner;if(t.length<2)throw Error("Gradient stop list needs to contain at least two stops.");this._stops=N.readAll(t,0,!1,!0);for(var e=0,n=this._stops.length;n>e;e++){var i=this._stops[e];i._owner=this,i._defaultRamp&&i.setRampPoint(e/(n-1))}this._changed()},getRadial:function(){return this._radial},setRadial:function(t){this._radial=t,this._changed()},equals:function(t){if(t&&t.constructor==this.constructor&&this._stops.length==t._stops.length){for(var e=0,n=this._stops.length;n>e;e++)if(!this._stops[e].equals(t._stops[e]))return!1;return!0}return!1}}),N=t.extend({_class:"GradientStop",initialize:function(t,e){if(t){var n,i;void 0===e&&Array.isArray(t)?(n=t[0],i=t[1]):t.color?(n=t.color,i=t.rampPoint):(n=t,i=e),this.setColor(n),this.setRampPoint(i)}},clone:function(){return new N(this._color.clone(),this._rampPoint)},_serialize:function(e,n){return t.serialize([this._color,this._rampPoint],e,!0,n)},_changed:function(){this._owner&&this._owner._changed(17)},getRampPoint:function(){return this._rampPoint},setRampPoint:function(t){this._defaultRamp=null==t,this._rampPoint=t||0,this._changed()},getColor:function(){return this._color},setColor:function(t){this._color=E.read(arguments),this._color===t&&(this._color=t.clone()),this._color._owner=this,this._changed()},equals:function(t){return t===this||t instanceof N&&this._color.equals(t._color)&&this._rampPoint==t._rampPoint||!1}}),F=t.extend(new function(){var e={fillColor:void 0,strokeColor:void 0,selectedColor:void 0,strokeWidth:1,strokeCap:"butt",strokeJoin:"miter",miterLimit:10,dashOffset:0,dashArray:[],font:"sans-serif",fontSize:12,leading:null,justification:"left"},n={strokeWidth:25,strokeCap:25,strokeJoin:25,miterLimit:25,font:5,fontSize:5,leading:5,justification:5},i={},r={_defaults:e,_textDefaults:t.merge(e,{fillColor:new E})};return t.each(e,function(e,s){var a=/Color$/.test(s),o=t.capitalize(s),h=n[s],u="set"+o,c="get"+o;r[u]=function(t){var e=this._item&&this._item._children;if(e&&e.length>0&&"compound-path"!==this._item._type)for(var n=0,i=e.length;i>n;n++)e[n]._style[u](t);else{var r=this._values[s];r!=t&&(a&&(r&&delete r._owner,t&&t.constructor===E&&(t._owner=this._item)),this._values[s]=t,this._item&&this._item._changed(h||17))}},r[c]=function(){var e,n=this._item&&this._item._children;if(!n||0===n.length||arguments[0]||"compound-path"===this._item._type){var e=this._values[s];return void 0===e?(e=this._defaults[s],e&&e.clone&&(e=e.clone()),this._values[s]=e):!a||e&&e.constructor===E||(this._values[s]=e=E.read([e],0,0,!0,!0),e&&(e._owner=this._item)),e}for(var i=0,r=n.length;r>i;i++){var o=n[i]._style[c]();if(0===i)e=o;else if(!t.equals(e,o))return void 0}return e},i[c]=function(){return this._style[c]()},i[u]=function(t){this._style[u](t)}}),m.inject(i),r},{_class:"Style",initialize:function(t,e){this._values={},this._item=e,e instanceof D&&(this._defaults=this._textDefaults),t&&this.set(t)},set:function(t){var e=t instanceof F,n=e?t._values:t;if(n)for(var i in n)if(i in this._defaults){var r=n[i];this[i]=r&&e&&r.clone?r.clone():r}},getLeading:function be(){var t=be.base.call(this);return null!=t?t:1.2*this.getFontSize()},getFontStyle:function(){var t=this.getFontSize();return(/[a-z]/i.test(t)?t+" ":t+"px ")+this.getFont()}}),R=new function(){function e(n,i){for(var r=[],s=0,a=n&&n.length;a>s;){var o=n[s++];if("string"==typeof o)o=document.createElement(o);else if(!o||!o.nodeType)continue;t.isPlainObject(n[s])&&R.set(o,n[s++]),Array.isArray(n[s])&&e(n[s++],o),i&&i.appendChild(o),r.push(o)}return r}var n=/^(checked|value|selected|disabled)$/i,i={text:"textContent",html:"innerHTML"},r={lineHeight:1,zoom:1,zIndex:1,opacity:1};return{create:function(t,n){var i=Array.isArray(t),r=e(i?t:arguments,i?n:null);return 1==r.length?r[0]:r},find:function(t,e){return(e||document).querySelector(t)},findAll:function(t,e){return(e||document).querySelectorAll(t)},get:function(t,e){return t?n.test(e)?"value"===e||"string"!=typeof t[e]?t[e]:!0:e in i?t[i[e]]:t.getAttribute(e):null},set:function(t,e,r){if("string"!=typeof e)for(var s in e)e.hasOwnProperty(s)&&this.set(t,s,e[s]);else{if(!t||void 0===r)return t;n.test(e)?t[e]=r:e in i?t[i[e]]=r:"style"===e?this.setStyle(t,r):"events"===e?q.add(t,r):t.setAttribute(e,r)}return t},getStyles:function(t){var e=t&&t.ownerDocument.defaultView;return e&&e.getComputedStyle(t,"")},getStyle:function(t,e){return t&&t.style[e]||this.getStyles(t)[e]||null},setStyle:function(t,e,n){if("string"!=typeof e)for(var i in e)e.hasOwnProperty(i)&&this.setStyle(t,i,e[i]);else!/^-?[\d\.]+$/.test(n)||e in r||(n+="px"),t.style[e]=n;return t},hasClass:function(t,e){return RegExp("\\s*"+e+"\\s*").test(t.className)},addClass:function(t,e){t.className=(t.className+" "+e).trim()},removeClass:function(t,e){t.className=t.className.replace(RegExp("\\s*"+e+"\\s*")," ").trim()},remove:function(t){t.parentNode&&t.parentNode.removeChild(t)},removeChildren:function(t){for(;t.firstChild;)t.removeChild(t.firstChild)},getBounds:function(t,e){var n,i=t.ownerDocument,r=i.body,s=i.documentElement;try{n=t.getBoundingClientRect()}catch(a){n={left:0,top:0,width:0,height:0}}var o=n.left-(s.clientLeft||r.clientLeft||0),h=n.top-(s.clientTop||r.clientTop||0);if(!e){var u=i.defaultView;o+=u.pageXOffset||s.scrollLeft||r.scrollLeft,h+=u.pageYOffset||s.scrollTop||r.scrollTop}return new d(o,h,n.width,n.height)},getViewportBounds:function(t){var e=t.ownerDocument,n=e.defaultView,i=e.documentElement;return new d(0,0,n.innerWidth||i.clientWidth,n.innerHeight||i.clientHeight)},getOffset:function(t,e){return this.getBounds(t,e).getPoint()},getSize:function(t){return this.getBounds(t,!0).getSize()},isInvisible:function(t){return this.getSize(t).equals(new u(0,0))},isInView:function(t){return!this.isInvisible(t)&&this.getViewportBounds(t).intersects(this.getBounds(t,!0))}}},q={add:function(t,e){for(var n in e){var i=e[n];t.addEventListener?t.addEventListener(n,i,!1):t.attachEvent&&t.attachEvent("on"+n,i.bound=function(){i.call(t,window.event)})}},remove:function(t,e){for(var n in e){var i=e[n];t.removeEventListener?t.removeEventListener(n,i,!1):t.detachEvent&&t.detachEvent("on"+n,i.bound)}},getPoint:function(t){var e=t.targetTouches?t.targetTouches.length?t.targetTouches[0]:t.changedTouches[0]:t;return new o(e.pageX||e.clientX+document.documentElement.scrollLeft,e.pageY||e.clientY+document.documentElement.scrollTop)},getTarget:function(t){return t.target||t.srcElement},getOffset:function(t,e){return q.getPoint(t).subtract(R.getOffset(e||q.getTarget(t)))},preventDefault:function(t){t.preventDefault?t.preventDefault():t.returnValue=!1},stopPropagation:function(t){t.stopPropagation?t.stopPropagation():t.cancelBubble=!0},stop:function(t){q.stopPropagation(t),q.preventDefault(t)}};q.requestAnimationFrame=new function(){var t="equestAnimationFrame",e=window["r"+t]||window["webkitR"+t]||window["mozR"+t]||window["oR"+t]||window["msR"+t];e&&e(function(t){null==t&&(e=null)});var i,r=[],s=!0;return q.add(window,{focus:function(){s=!0},blur:function(){s=!1}}),function(t,a){return e?e(t,a):(r.push([t,a]),i||(i=setInterval(function(){for(var t=r.length-1;t>=0;t--){var e=r[t],i=e[0],a=e[1];(!a||("true"==n.getAttribute(a,"keepalive")||s)&&R.isInView(a))&&(r.splice(t,1),i(Date.now()))}},1e3/60)),void 0)}};var V=t.extend(e,{_class:"View",initialize:function Ce(t){this._scope=paper,this._project=paper.project,this._element=t;var e;if(this._id=t.getAttribute("id"),null==this._id&&t.setAttribute("id",this._id="view-"+Ce._id++),q.add(t,this._viewHandlers),n.hasAttribute(t,"resize")){var i=R.getOffset(t,!0),r=this;e=R.getViewportBounds(t).getSize().subtract(i),this._windowHandlers={resize:function(){R.isInvisible(t)||(i=R.getOffset(t,!0)),r.setViewSize(R.getViewportBounds(t).getSize().subtract(i))}},q.add(window,this._windowHandlers)}else e=new u(parseInt(t.getAttribute("width"),10),parseInt(t.getAttribute("height"),10)),e.isNaN()&&(e=R.getSize(t));if(t.width=e.width,t.height=e.height,n.hasAttribute(t,"stats")){this._stats=new Stats;var s=this._stats.domElement,a=s.style,i=R.getOffset(t);a.position="absolute",a.left=i.x+"px",a.top=i.y+"px",document.body.appendChild(s)}Ce._views.push(this),Ce._viewsById[this._id]=this,this._viewSize=new c(e.width,e.height,this,"setViewSize"),this._matrix=new _,this._zoom=1,Ce._focused||(Ce._focused=this),this._frameItems={},this._frameItemCount=0},remove:function(){return this._project?(V._focused==this&&(V._focused=null),V._views.splice(V._views.indexOf(this),1),delete V._viewsById[this._id],this._project.view==this&&(this._project.view=null),q.remove(this._element,this._viewHandlers),q.remove(window,this._windowHandlers),this._element=this._project=null,this.detach("frame"),this._frameItems={},!0):!1 +},_events:{onFrame:{install:function(){this._requested||(this._animate=!0,this._handleFrame(!0))},uninstall:function(){this._animate=!1}},onResize:{}},_animate:!1,_time:0,_count:0,_handleFrame:function(e){if(this._requested=!1,this._animate){if(paper=this._scope,e){this._requested=!0;var n=this;q.requestAnimationFrame(function(){n._handleFrame(!0)},this._element)}var i=Date.now()/1e3,r=this._before?i-this._before:0;this._before=i,this._handlingFrame=!0,this.fire("frame",t.merge({delta:r,time:this._time+=r,count:this._count++})),this._stats&&this._stats.update(),this._handlingFrame=!1,this.draw(!0)}},_animateItem:function(t,e){var n=this._frameItems;e?(n[t._id]={item:t,time:0,count:0},1==++this._frameItemCount&&this.attach("frame",this._handleFrameItems)):(delete n[t._id],0==--this._frameItemCount&&this.detach("frame",this._handleFrameItems))},_handleFrameItems:function(e){for(var n in this._frameItems){var i=this._frameItems[n];i.item.fire("frame",t.merge(e,{time:i.time+=e.delta,count:i.count++}))}},_redraw:function(){this._project._needsRedraw=!0,this._handlingFrame||(this._animate?this._handleFrame():this.draw())},_transform:function(t){this._matrix.concatenate(t),this._bounds=null,this._inverse=null,this._redraw()},getElement:function(){return this._element},getViewSize:function(){return this._viewSize},setViewSize:function(t){t=u.read(arguments);var e=t.subtract(this._viewSize);e.isZero()||(this._element.width=t.width,this._element.height=t.height,this._viewSize.set(t.width,t.height,!0),this._bounds=null,this.fire("resize",{size:t,delta:e}),this._redraw())},getBounds:function(){return this._bounds||(this._bounds=this._getInverse()._transformBounds(new d(new o,this._viewSize))),this._bounds},getSize:function(){return this.getBounds().getSize(arguments[0])},getCenter:function(){return this.getBounds().getCenter(arguments[0])},setCenter:function(t){t=o.read(arguments),this.scrollBy(t.subtract(this.getCenter()))},getZoom:function(){return this._zoom},setZoom:function(t){this._transform((new _).scale(t/this._zoom,this.getCenter())),this._zoom=t},isVisible:function(){return R.isInView(this._element)},scrollBy:function(){this._transform((new _).translate(o.read(arguments).negate()))},projectToView:function(){return this._matrix._transformPoint(o.read(arguments))},viewToProject:function(){return this._getInverse()._transformPoint(o.read(arguments))},_getInverse:function(){return this._inverse||(this._inverse=this._matrix.inverted()),this._inverse}},{statics:{_views:[],_viewsById:{},_id:0,create:function(t){return"string"==typeof t&&(t=document.getElementById(t)),new H(t)}}},new function(){function t(t){var e=q.getTarget(t);return e.getAttribute&&V._viewsById[e.getAttribute("id")]}function e(t,e){return t.viewToProject(q.getOffset(e,t._element))}function n(){if(!V._focused||!V._focused.isVisible())for(var t=0,e=V._views.length;e>t;t++){var n=V._views[t];if(n&&n.isVisible()){V._focused=u=n;break}}}function i(n){var i=V._focused=t(n),r=e(i,n);c=!0,i._onMouseDown&&i._onMouseDown(n,r),(o=i._scope._tool)&&o._onHandleEvent("mousedown",r,n),i.draw(!0)}function r(i){var r;if(c||(r=t(i),r?(h=V._focused,V._focused=u=r):u&&u==V._focused&&(V._focused=h,n())),r=r||V._focused){var s=i&&e(r,i);r._onMouseMove&&r._onMouseMove(i,s),(o=r._scope._tool)&&o._onHandleEvent(c&&o.responds("mousedrag")?"mousedrag":"mousemove",s,i)&&q.stop(i),r.draw(!0)}}function s(t){var n=V._focused;if(n&&c){var i=e(n,t);curPoint=null,c=!1,n._onMouseUp&&n._onMouseUp(t,i),o&&o._onHandleEvent("mouseup",i,t)&&q.stop(t),n.draw(!0)}}function a(t){c&&q.stop(t)}var o,h,u,c=!1;return q.add(document,{mousemove:r,mouseup:s,touchmove:r,touchend:s,selectstart:a,scroll:n}),q.add(window,{load:n}),{_viewHandlers:{mousedown:i,touchstart:i,selectstart:a},statics:{updateFocus:n}}}),H=V.extend({_class:"CanvasView",initialize:function(t){if(!(t instanceof HTMLCanvasElement)){var e=u.read(arguments,1);e.isZero()&&(e=new u(1024,768)),t=Y.getCanvas(e)}this._context=t.getContext("2d"),this._eventCounters={},V.call(this,t)},draw:function(t){if(t&&!this._project._needsRedraw)return!1;var e=this._context,n=this._viewSize;return e.clearRect(0,0,n._width+1,n._height+1),this._project.draw(e,this._matrix),this._project._needsRedraw=!1,!0}},new function(){function t(t,e,n,i,r,s){for(var a,o=i;o;){if(o.responds(t)&&(a||(a=new J(t,e,n,i,r?n.subtract(r):null)),o.fire(t,a)&&(!s||a._stopped)))return!1;o=o.getParent()}return!0}function e(e,n,i,r,s){if(e._eventCounters[n]){var a=e._project,u=a.hitTest(r,{tolerance:a.options.hitTolerance||0,fill:!0,stroke:!0}),c=u&&u.item;if(c)return"mousemove"===n&&c!=o&&(s=r),"mousemove"===n&&h||t(n,i,r,c,s),c}}var n,i,r,s,a,o,h,u,c;return{_onMouseDown:function(t,o){var l=e(this,"mousedown",t,o);u=a==l&&Date.now()-c<300,s=a=l,n=i=r=o,h=s&&s.responds("mousedrag")},_onMouseUp:function(a,o){var l=e(this,"mouseup",a,o);h&&(i&&!i.equals(o)&&t("mousedrag",a,o,s,i),l!=s&&(r=o,t("mousemove",a,o,l,r))),l===s&&(c=Date.now(),(!u||t("doubleclick",a,n,l))&&t("click",a,n,l),u=!1),s=null,h=!1},_onMouseMove:function(n,a){s&&t("mousedrag",n,a,s,i);var h=e(this,"mousemove",n,a,r);i=r=a,h!==o&&(t("mouseleave",n,a,o),o=h,t("mouseenter",n,a,h))}}}),Z=t.extend({_class:"Event",initialize:function(t){this.event=t},preventDefault:function(){this._prevented=!0,q.preventDefault(this.event)},stopPropagation:function(){this._stopped=!0,q.stopPropagation(this.event)},stop:function(){this.stopPropagation(),this.preventDefault()},getModifiers:function(){return X.modifiers}}),U=Z.extend({_class:"KeyEvent",initialize:function(t,e,n,i){Z.call(this,i),this.type=t?"keydown":"keyup",this.key=e,this.character=n},toString:function(){return"{ type: '"+this.type+"', key: '"+this.key+"', character: '"+this.character+"', modifiers: "+this.getModifiers()+" }"}}),X=new function(){function e(t,e,n,r){var s=String.fromCharCode(n),o=i[e]||s.toLowerCase(),h=t?"keydown":"keyup",u=V._focused,c=u&&u.isVisible()&&u._scope,l=c&&c._tool;a[o]=t,l&&l.responds(h)&&(l.fire(h,new U(t,o,s,r)),u&&u.draw(!0))}var n,i={8:"backspace",9:"tab",13:"enter",16:"shift",17:"control",18:"option",19:"pause",20:"caps-lock",27:"escape",32:"space",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",46:"delete",91:"command",93:"command",224:"command"},r=t.merge({shift:!1,control:!1,option:!1,command:!1,capsLock:!1,space:!1}),s={},a={};return q.add(document,{keydown:function(a){var o,h=a.which||a.keyCode,u=i[h];u?((o=t.camelize(u))in r&&(r[o]=!0),s[h]=0,e(!0,h,null,a)):n=h},keypress:function(t){if(null!=n){var i=t.which||t.keyCode;s[n]=i,e(!0,n,i,t),n=null}},keyup:function(n){var a,o=n.which||n.keyCode,h=i[o];h&&(a=t.camelize(h))in r&&(r[a]=!1),null!=s[o]&&(e(!1,o,s[o],n),delete s[o])}}),{modifiers:r,isDown:function(t){return!!a[t]}}},J=Z.extend({_class:"MouseEvent",initialize:function(t,e,n,i,r){Z.call(this,e),this.type=t,this.point=n,this.target=i,this.delta=r},toString:function(){return"{ type: '"+this.type+"', point: "+this.point+", target: "+this.target+(this.delta?", delta: "+this.delta:"")+", modifiers: "+this.getModifiers()+" }"}});t.extend(e,{_class:"Palette",_events:["onChange"],initialize:function(e,n,i){var r=R.find(".palettejs-panel")||R.find("body").appendChild(R.create("div",{"class":"palettejs-panel"}));this._element=r.appendChild(R.create("table",{"class":"palettejs-pane"})),this._title=e,i||(i={});for(var s in this._components=n){var a=n[s];a instanceof G||(null==a.value&&(a.value=i[s]),a.name=s,a=n[s]=new G(a)),this._element.appendChild(a._element),a._palette=this,void 0===i[s]&&(i[s]=a.value)}this._values=t.each(i,function(e,r){var s=n[r];s&&t.define(i,r,{enumerable:!0,configurable:!0,get:function(){return s._value},set:function(t){s.setValue(t)}})}),window.paper&&paper.palettes.push(this)},reset:function(){for(var t in this._components)this._components[t].reset()},remove:function(){R.remove(this._element)}});var G=t.extend(e,{_class:"Component",_events:["onChange","onClick"],_types:{"boolean":{type:"checkbox",value:"checked"},string:{type:"text"},number:{type:"number",number:!0},button:{type:"button"},text:{tag:"div",value:"text"},slider:{type:"range",number:!0},list:{tag:"select",options:function(){R.removeChildren(this._inputItem),R.create(t.each(this._options,function(t){this.push("option",{value:t,text:t})},[]),this._inputItem)}}},initialize:function(e){this._type=e.type in this._types?e.type:"options"in e?"list":"onClick"in e?"button":typeof e.value,this._info=this._types[this._type]||{type:this._type};var n=this,i=!1;this._inputItem=R.create(this._info.tag||"input",{type:this._info.type,events:{change:function(){n.setValue(R.get(this,n._info.value||"value")),i&&(n._palette.fire("change",n,n.name,n._value),n.fire("change",n._value))},click:function(){n.fire("click")}}}),this._element=R.create("tr",[this._labelItem=R.create("td"),"td",[this._inputItem]]),t.each(e,function(t,e){this[e]=t},this),this._defaultValue=this._value,i=!0},getType:function(){return this._type},getLabel:function(){return this._label},setLabel:function(t){this._label=t,R.set(this._labelItem,"text",t+":")},getOptions:function(){return this._options},setOptions:function(t){this._options=t,this._info.options&&this._info.options.call(this)},getValue:function(){return this._value},setValue:function(t){var e=this._info.value||"value";R.set(this._inputItem,e,t),t=R.get(this._inputItem,e),this._value=this._info.number?parseFloat(t,10):t},getRange:function(){return[parseFloat(R.get(this._inputItem,"min")),parseFloat(R.get(this._inputItem,"max"))]},setRange:function(t,e){var n=Array.isArray(t)?t:[t,e];R.set(this._inputItem,{min:n[0],max:n[1]})},getMin:function(){return this.getRange()[0]},setMin:function(t){this.setRange(t,this.getMax())},getMax:function(){return this.getRange()[1]},setMax:function(t){this.setRange(this.getMin(),t)},getStep:function(){return parseFloat(R.get(this._inputItem,"step"))},setStep:function(t){R.set(this._inputItem,"step",t)},reset:function(){this.setValue(this._defaultValue)}}),W=Z.extend({_class:"ToolEvent",_item:null,initialize:function(t,e,n){this.tool=t,this.type=e,this.event=n},_choosePoint:function(t,e){return t?t:e?e.clone():null},getPoint:function(){return this._choosePoint(this._point,this.tool._point)},setPoint:function(t){this._point=t},getLastPoint:function(){return this._choosePoint(this._lastPoint,this.tool._lastPoint)},setLastPoint:function(t){this._lastPoint=t},getDownPoint:function(){return this._choosePoint(this._downPoint,this.tool._downPoint)},setDownPoint:function(t){this._downPoint=t},getMiddlePoint:function(){return!this._middlePoint&&this.tool._lastPoint?this.tool._point.add(this.tool._lastPoint).divide(2):this.middlePoint},setMiddlePoint:function(t){this._middlePoint=t},getDelta:function(){return!this._delta&&this.tool._lastPoint?this.tool._point.subtract(this.tool._lastPoint):this._delta},setDelta:function(t){this._delta=t},getCount:function(){return/^mouse(down|up)$/.test(this.type)?this.tool._downCount:this.tool._count},setCount:function(t){this.tool[/^mouse(down|up)$/.test(this.type)?"downCount":"count"]=t},getItem:function(){if(!this._item){var t=this.tool._scope.project.hitTest(this.getPoint());if(t){for(var e=t.item,n=e._parent;/^(group|compound-path)$/.test(n._type);)e=n,n=n._parent;this._item=e}}return this._item},setItem:function(t){this._item=t},toString:function(){return"{ type: "+this.type+", point: "+this.getPoint()+", count: "+this.getCount()+", modifiers: "+this.getModifiers()+" }"}}),$=r.extend({_class:"Tool",_list:"tools",_reference:"_tool",_events:["onActivate","onDeactivate","onEditOptions","onMouseDown","onMouseUp","onMouseDrag","onMouseMove","onKeyDown","onKeyUp"],initialize:function(t){r.call(this),this._firstMove=!0,this._count=0,this._downCount=0,this._set(t)},getMinDistance:function(){return this._minDistance},setMinDistance:function(t){this._minDistance=t,null!=this._minDistance&&null!=this._maxDistance&&this._minDistance>this._maxDistance&&(this._maxDistance=this._minDistance)},getMaxDistance:function(){return this._maxDistance},setMaxDistance:function(t){this._maxDistance=t,null!=this._minDistance&&null!=this._maxDistance&&this._maxDistanceu)return!1;var c=null!=i?i:0;if(0!=c)if(u>c)e=this._point.add(h.normalize(c));else if(a)return!1}if(s&&e.equals(this._point))return!1}switch(this._lastPoint=r&&"mousemove"==t?e:this._point,this._point=e,t){case"mousedown":this._lastPoint=this._downPoint,this._downPoint=this._point,this._downCount++;break;case"mouseup":this._lastPoint=this._downPoint}return this._count=r?0:this._count+1,!0},_fireEvent:function(t,e){var n=paper.project._removeSets;if(n){"mouseup"===t&&(n.mousedrag=null);var i=n[t];if(i){for(var r in i){var s=i[r];for(var a in n){var o=n[a];o&&o!=i&&delete o[s._id]}s.remove()}n[t]=null}}return this.responds(t)&&this.fire(t,new W(this,t,e))},_onHandleEvent:function(t,e,n){paper=this._scope;var i=!1;switch(t){case"mousedown":this._updateEvent(t,e,null,null,!0,!1,!1),i=this._fireEvent(t,n);break;case"mousedrag":for(var r=!1,s=!1;this._updateEvent(t,e,this.minDistance,this.maxDistance,!1,r,s);)i=this._fireEvent(t,n)||i,r=!0,s=!0;break;case"mouseup":!e.equals(this._point)&&this._updateEvent("mousedrag",e,this.minDistance,this.maxDistance,!1,!1,!1)&&(i=this._fireEvent("mousedrag",n)),this._updateEvent(t,e,null,this.maxDistance,!1,!1,!1),i=this._fireEvent(t,n)||i,this._updateEvent(t,e,null,null,!0,!1,!1),this._firstMove=!0;break;case"mousemove":for(;this._updateEvent(t,e,this.minDistance,this.maxDistance,this._firstMove,!0,!1);)i=this._fireEvent(t,n)||i,this._firstMove=!1}return i}}),Y={canvases:[],getCanvas:function(t,e){var n,i=void 0===e?t:new u(t,e),r=!0;n=this.canvases.length?this.canvases.pop():document.createElement("canvas");var s=n.getContext("2d");return s.save(),n.width===i.width&&n.height===i.height?r&&s.clearRect(0,0,i.width+1,i.height+1):(n.width=i.width,n.height=i.height),n},getContext:function(t,e){return this.getCanvas(t,e).getContext("2d")},release:function(t){var e=t.canvas?t.canvas:t;e.getContext("2d").restore(),this.canvases.push(e)}},K=new function(){function e(t,e,n){return.2989*t+.587*e+.114*n}function n(t,n,i,r){var s=r-e(t,n,i);_=t+s,g=n+s,p=i+s;var r=e(_,g,p),a=v(_,g,p),o=m(_,g,p);if(0>a){var h=r-a;_=r+(_-r)*r/h,g=r+(g-r)*r/h,p=r+(p-r)*r/h}if(o>255){var u=255-r,c=o-r;_=r+(_-r)*u/c,g=r+(g-r)*u/c,p=r+(p-r)*u/c}}function i(t,e,n){return m(t,e,n)-v(t,e,n)}function r(t,e,n,i){var r,s=[t,e,n],a=m(t,e,n),o=v(t,e,n);o=o===t?0:o===e?1:2,a=a===t?0:a===e?1:2,r=0===v(o,a)?1===m(o,a)?2:1:0,s[a]>s[o]?(s[r]=(s[r]-s[o])*i/(s[a]-s[o]),s[a]=i):s[r]=s[a]=0,s[o]=0,_=s[0],g=s[1],p=s[2]}function s(t){x.save();var e="darken"===t,n=!1;return x.fillStyle=e?"#300":"#a00",x.fillRect(0,0,1,1),x.globalCompositeOperation=t,x.globalCompositeOperation===t&&(x.fillStyle=e?"#a00":"#300",x.fillRect(0,0,1,1),n=x.getImageData(0,0,1,1).data[0]!==(e?170:51)),x.restore(),n}var a,o,h,u,c,l,d,f,_,g,p,v=Math.min,m=Math.max,y=Math.abs,w={multiply:function(){_=c*a/255,g=l*o/255,p=d*h/255},screen:function(){_=c+a-c*a/255,g=l+o-l*o/255,p=d+h-d*h/255},overlay:function(){_=128>c?2*c*a/255:255-2*(255-c)*(255-a)/255,g=128>l?2*l*o/255:255-2*(255-l)*(255-o)/255,p=128>d?2*d*h/255:255-2*(255-d)*(255-h)/255},"soft-light":function(){var t=a*c/255;_=t+c*(255-(255-c)*(255-a)/255-t)/255,t=o*l/255,g=t+l*(255-(255-l)*(255-o)/255-t)/255,t=h*d/255,p=t+d*(255-(255-d)*(255-h)/255-t)/255},"hard-light":function(){_=128>a?2*a*c/255:255-2*(255-a)*(255-c)/255,g=128>o?2*o*l/255:255-2*(255-o)*(255-l)/255,p=128>h?2*h*d/255:255-2*(255-h)*(255-d)/255},"color-dodge":function(){_=0===c?0:255===a?255:v(255,255*c/(255-a)),g=0===l?0:255===o?255:v(255,255*l/(255-o)),p=0===d?0:255===h?255:v(255,255*d/(255-h))},"color-burn":function(){_=255===c?255:0===a?0:m(0,255-255*(255-c)/a),g=255===l?255:0===o?0:m(0,255-255*(255-l)/o),p=255===d?255:0===h?0:m(0,255-255*(255-d)/h)},darken:function(){_=a>c?c:a,g=o>l?l:o,p=h>d?d:h},lighten:function(){_=c>a?c:a,g=l>o?l:o,p=d>h?d:h},difference:function(){_=c-a,0>_&&(_=-_),g=l-o,0>g&&(g=-g),p=d-h,0>p&&(p=-p)},exclusion:function(){_=c+a*(255-c-c)/255,g=l+o*(255-l-l)/255,p=d+h*(255-d-d)/255},hue:function(){r(a,o,h,i(c,l,d)),n(_,g,p,e(c,l,d))},saturation:function(){r(c,l,d,i(a,o,h)),n(_,g,p,e(c,l,d))},luminosity:function(){n(c,l,d,e(a,o,h))},color:function(){n(a,o,h,e(c,l,d))},add:function(){_=v(c+a,255),g=v(l+o,255),p=v(d+h,255)},subtract:function(){_=m(c-a,0),g=m(l-o,0),p=m(d-h,0)},average:function(){_=(c+a)/2,g=(l+o)/2,p=(d+h)/2},negation:function(){_=255-y(255-a-c),g=255-y(255-o-l),p=255-y(255-h-d)}},x=Y.getContext(1,1);this.nativeModes=s("multiply")&&t.each(w,function(t,e){this[e]=s(e)},{}),Y.release(x),this.process=function(t,e,n,i,r){var s=e.canvas,v="normal"===t;if(v||this.nativeModes[t])n.save(),n.setTransform(1,0,0,1,0,0),n.globalAlpha=i,v||(n.globalCompositeOperation=t),n.drawImage(s,r.x,r.y),n.restore();else{var m=w[t];if(!m)return;for(var y=n.getImageData(r.x,r.y,s.width,s.height),x=y.data,b=e.getImageData(0,0,s.width,s.height).data,C=0,S=x.length;S>C;C+=4){a=b[C],c=x[C],o=b[C+1],l=x[C+1],h=b[C+2],d=x[C+2],u=b[C+3],f=x[C+3],m();var k=u*i/255,P=1-k;x[C]=k*_+P*c,x[C+1]=k*g+P*l,x[C+2]=k*p+P*d,x[C+3]=u*i+P*f}n.putImageData(y,r.x,r.y)}}},Q=t.each({fillColor:["fill","color"],strokeColor:["stroke","color"],strokeWidth:["stroke-width","number"],strokeCap:["stroke-linecap","string"],strokeJoin:["stroke-linejoin","string"],miterLimit:["stroke-miterlimit","number"],dashArray:["stroke-dasharray","array"],dashOffset:["stroke-dashoffset","number"],font:["font-family","string"],fontSize:["font-size","number"],justification:["text-anchor","lookup",{left:"start",center:"middle",right:"end"}],opacity:["opacity","number"],blendMode:["mix-blend-mode","string"]},function(e,n){var i=t.capitalize(n),r=e[2];this[n]={type:e[1],property:n,attribute:e[0],toSVG:r,fromSVG:r&&t.each(r,function(t,e){this[t]=e},{}),get:"get"+i,set:"set"+i}},{}),te={href:"http://www.w3.org/1999/xlink",xlink:"http://www.w3.org/2000/xmlns"};return new function(){function e(t,e){for(var n in e){var i=e[n],r=te[n];"number"==typeof i&&(i=I.number(i)),r?t.setAttributeNS(r,n,i):t.setAttribute(n,i)}return t}function n(t,n){return e(document.createElementNS("http://www.w3.org/2000/svg",t),n)}function r(t,e,n){return t[e]._point.getDistance(t[n]._point)}function o(t,e){var n=t._matrix,i=n.getTranslation(),r={};if(e){n=n.shiftless();var s=n._inverseTransform(i);r.x=s.x,r.y=s.y,i=null}if(n.isIdentity())return r;var o=n.decompose();if(o&&!o.shearing){var h=[],u=o.rotation,c=o.scaling;i&&!i.isZero()&&h.push("translate("+I.point(i)+")"),a.isZero(c.x-1)&&a.isZero(c.y-1)||h.push("scale("+I.point(c)+")"),u&&h.push("rotate("+I.number(u)+")"),r.transform=h.join(" ")}else r.transform="matrix("+n.getValues().join(",")+")";return r}function h(t,e,n,i){var r="rect"===n?e[1]._point.add(e[2]._point).divide(2):"roundrect"===n?e[3]._point.add(e[4]._point).divide(2):"circle"===n||"ellipse"===n?e[1]._point:null,s=r&&r.subtract(i).getAngle()+90;return a.isZero(s||0)?0:s}function u(t,e){function n(t,n){var i=e[t],r=i.getNext(),s=e[n],a=s.getNext();return i._handleOut.isZero()&&r._handleIn.isZero()&&s._handleOut.isZero()&&a._handleIn.isZero()&&r._point.subtract(i._point).isColinear(a._point.subtract(s._point))}function i(t){var n=e[t],i=n.getNext(),r=n._handleOut,s=i._handleIn,o=a.KAPPA;if(r.isOrthogonal(s)){var h=n._point,u=i._point,c=new g(h,r,!0).intersect(new g(u,s,!0),!0);return c&&a.isZero(r.getLength()/c.subtract(h).getLength()-o)&&a.isZero(s.getLength()/c.subtract(u).getLength()-o)}}if(t.isPolygon())return 4===e.length&&t._closed&&n(0,2)&&n(1,3)?"rect":0===e.length?"empty":e.length>=3?t._closed?"polygon":"polyline":"line";if(t._closed){if(8===e.length&&i(0)&&i(2)&&i(4)&&i(6)&&n(1,5)&&n(3,7))return"roundrect";if(4===e.length&&i(0)&&i(1)&&i(2)&&i(3))return a.isZero(r(e,0,2)-r(e,1,3))?"circle":"ellipse"}return"path"}function c(t){for(var i=o(t),r=t._children,s=n("g",i),a=0,h=r.length;h>a;a++){var u=r[a],c=P(u);if(c)if(u.isClipMask()){var l=n("clipPath");l.appendChild(c),S(u,l,"clip"),e(s,{"clip-path":"url(#"+l.id+")"})}else s.appendChild(c)}return s}function d(t){var e=o(t,!0),i=t.getSize();return e.x-=i.width/2,e.y-=i.height/2,e.width=i.width,e.height=i.height,e.href=t.toDataURL(),n("image",e)}function f(t){var e,s=t._segments,a=t.getPosition(!0),o=u(t,s),c=h(t,s,o,a);switch(o){case"empty":return null;case"path":var d=t.getPathData();e=d&&{d:d};break;case"polyline":case"polygon":var f=[];for(i=0,l=s.length;l>i;i++)f.push(I.point(s[i]._point));e={points:f.join(" ")};break;case"rect":var g=r(s,0,3),p=r(s,0,1),v=s[1]._point.rotate(-c,a);e={x:v.x,y:v.y,width:g,height:p};break;case"roundrect":o="rect";var g=r(s,1,6),p=r(s,0,3),m=(g-r(s,0,7))/2,y=(p-r(s,1,2))/2,w=s[3]._point,x=s[4]._point,v=w.subtract(x.subtract(w).normalize(m)).rotate(-c,a);e={x:v.x,y:v.y,width:g,height:p,rx:m,ry:y};break;case"line":var b=s[0]._point,C=s[s.length-1]._point;e={x1:b.x,y1:b.y,x2:C.x,y2:C.y};break;case"circle":var S=r(s,0,2)/2;e={cx:a.x,cy:a.y,r:S};break;case"ellipse":var m=r(s,2,0)/2,y=r(s,3,1)/2;e={cx:a.x,cy:a.y,rx:m,ry:y}}return c&&(e.transform="rotate("+I.number(c)+","+I.point(a)+")",t._gradientMatrix=(new _).rotate(-c,a)),n(o,e)}function v(t){var e=o(t,!0),i=t.getPathData();return i&&(e.d=i),n("path",e)}function y(t){var e=o(t,!0),i=t.getSymbol(),r=C(i,"symbol");return definition=i.getDefinition(),bounds=definition.getBounds(),r||(r=n("symbol",{viewBox:I.rectangle(bounds)}),r.appendChild(P(definition)),S(i,r,"symbol")),e.href="#"+r.id,e.x+=bounds.x,e.y+=bounds.y,e.width=I.number(bounds.width),e.height=I.number(bounds.height),n("use",e)}function w(t,e){var i=C(t,"color");if(!i){var r,s=t.getGradient(),a=s._radial,o=e._gradientMatrix,h=t.getOrigin().transform(o),u=t.getDestination().transform(o);if(a){r={cx:h.x,cy:h.y,r:h.getDistance(u)};var c=t.getHighlight();c&&(c=c.transform(o),r.fx=c.x,r.fy=c.y)}else r={x1:h.x,y1:h.y,x2:u.x,y2:u.y};r.gradientUnits="userSpaceOnUse",i=n((a?"radial":"linear")+"Gradient",r);for(var l=s._stops,d=0,f=l.length;f>d;d++){var _=l[d],g=_._color,p=g.getAlpha();r={offset:_._rampPoint,"stop-color":g.toCSS(!0)},1>p&&(r["stop-opacity"]=p),i.appendChild(n("stop",r))}S(t,i,"color")}return"url(#"+i.id+")"}function x(t){var e=n("text",o(t,!0));return e.textContent=t._content,e}function b(n,i){var r={},s=n.getParent();return null!=n._name&&(r.id=n._name),t.each(Q,function(e){var i=e.get,a=e.type,o=n[i]();if(!s||!t.equals(s[i](),o)){if("color"===a&&null!=o){var h=o.getAlpha();1>h&&(r[e.attribute+"-opacity"]=h)}r[e.attribute]=null==o?"none":"number"===a?I.number(o):"color"===a?o.gradient?w(o,n):o.toCSS(!0):"array"===a?o.join(","):"lookup"===a?e.toSVG[o]:o}}),1===r.opacity&&delete r.opacity,null==n._visibility||n._visibility||(r.visibility="hidden"),delete n._gradientMatrix,e(i,r)}function C(t,e){return M||(M={ids:{},svgs:{}}),t&&M.svgs[e+"-"+t._id]}function S(t,e,n){M||C();var i=M.ids[n]=(M.ids[n]||0)+1;e.id=n+"-"+i,M.svgs[n+"-"+t._id]=e}function k(t){if(!M)return t;var e="svg"===t.nodeName.toLowerCase()&&t,i=null;for(var r in M.svgs)i||(e||(e=n("svg"),e.appendChild(t)),i=e.insertBefore(n("defs"),e.firstChild)),i.appendChild(M.svgs[r]);return M=null,e}function P(t){var e=A[t._type],n=e&&e(t,t._type);return n&&t._data&&n.setAttribute("data-paper-data",JSON.stringify(t._data)),n&&b(t,n)}var M,I=s.instance,A={group:c,layer:c,raster:d,path:f,"compound-path":v,"placed-symbol":y,"point-text":x};m.inject({exportSVG:function(){return k(P(this))}}),p.inject({exportSVG:function(){for(var t=this.layers,e=this.view.getSize(),i=n("svg",{x:0,y:0,width:e.width,height:e.height,version:"1.1",xmlns:"http://www.w3.org/2000/svg","xmlns:xlink":"http://www.w3.org/1999/xlink"}),r=0,s=t.length;s>r;r++)i.appendChild(P(t[r]));return k(i)}})},new function(){function e(t,e,n,i){var r=te[e],s=r?t.getAttributeNS(r,e):t.getAttribute(e);return"null"===s&&(s=null),null==s?i?null:n?"":0:n?s:parseFloat(s)}function n(t,n,i,r){return n=e(t,n,!1,r),i=e(t,i,!1,r),r&&null==n&&null==i?null:new o(n||0,i||0)}function i(t,n,i,r){return n=e(t,n,!1,r),i=e(t,i,!1,r),r&&null==n&&null==i?null:new u(n||0,i||0)}function r(t,e,n){return"none"===t?null:"number"===e?parseFloat(t):"array"===e?t?t.split(/[\s,]+/g).map(parseFloat):[]:"color"===e?x(t)||t:"lookup"===e?n[t]:t}function s(t,e){var n=t.childNodes,i="clippath"===e,r=i?new L:new y,s=r._project,a=s._currentStyle,o=[];i||(r._transformContent=!1,r=w(r,t),s._currentStyle=r._style.clone());for(var h=0,u=n.length;u>h;h++){var c,l=n[h];1==l.nodeType&&(c=C(l))&&(i&&c instanceof L?(o.push.apply(o,c.removeChildren()),c.remove()):c instanceof v||o.push(c))}return r.addChildren(o),i&&(r=w(r.reduce(),t)),s._currentStyle=a,(i||"defs"===e)&&(r.remove(),r=null),r}function a(t,e){var n=new z,i=t.points;n.moveTo(i.getItem(0));for(var r=1,s=i.numberOfItems;s>r;r++)n.lineTo(i.getItem(r));return"polygon"===e&&n.closePath(),n}function h(t){var e=t.getAttribute("d"),n=e.match(/m/gi).length>1?new L:new z;return n.setPathData(e),n}function c(t,i){for(var r=t.childNodes,s=[],a=0,o=r.length;o>a;a++){var h=r[a];1==h.nodeType&&s.push(w(new N,h))}var u,c,l,d="radialgradient"===i,f=new B(s,d);return d?(u=n(t,"cx","cy"),c=u.add(e(t,"r"),0),l=n(t,"fx","fy",!0)):(u=n(t,"x1","y1"),c=n(t,"x2","y2")),w(new E(f,u,c,l),t),null}function l(t,e,n,i){for(var r=(i.getAttribute(n)||"").split(/\)\s*/g),s=new _,a=0,o=r.length;o>a;a++){var h=r[a];if(!h)break;for(var u=h.split("("),c=u[0],l=u[1].split(/[\s,]+/g),d=0,f=l.length;f>d;d++)l[d]=parseFloat(l[d]);switch(c){case"matrix":s.concatenate(new _(l[0],l[2],l[1],l[3],l[4],l[5]));break;case"rotate":s.rotate(l[0],l[1],l[2]);break;case"translate":s.translate(l[0],l[1]);break;case"scale":s.scale(l);break;case"skewX":case"skewY":var e=Math.tan(l[0]*Math.PI/180),g="skewX"==c;s.shear(g?e:0,g?0:e)}}t.transform(s)}function f(t,e,n){var i=t["fill-opacity"===n?"getFillColor":"getStrokeColor"]();i&&i.setAlpha(parseFloat(e))}function g(e,n,i){var r=e.attributes[n],s=r&&r.value;if(!s){var a=t.camelize(n);s=e.style[a],s||i.node[a]===i.parent[a]||(s=i.node[a])}return s?"none"===s?null:s:void 0}function w(e,n){var i={node:R.getStyles(n)||{},parent:R.getStyles(n.parentNode)||{}};return t.each(k,function(r,s){var a=g(n,s,i);void 0!==a&&(e=t.pick(r(e,a,s,n,i),e))}),e}function x(t){var e=t&&t.match(/\((?:#|)([^)']+)/);return e&&P[e[1]]}function C(t,e){"string"==typeof t&&(t=(new DOMParser).parseFromString(t,"image/svg+xml"));var n=t.nodeName.toLowerCase(),i=S[n],r=i&&i(t,n),s=t.getAttribute("data-paper-data");return!r||r instanceof y||(r=w(r,t)),r&&s&&(r._data=JSON.parse(s)),e&&(P={}),r}var S={g:s,svg:s,clippath:s,polygon:a,polyline:a,path:h,lineargradient:c,radialgradient:c,image:function(t){var r=new b(e(t,"href",!0));return r.attach("load",function(){var e=i(t,"width","height");this.setSize(e),this.translate(n(t,"x","y").add(e.divide(2)))}),r},symbol:function(t,e){return new v(s(t,e),!0)},defs:s,use:function(t){var i=(e(t,"href",!0)||"").substring(1),r=P[i],s=n(t,"x","y");return r?r instanceof v?r.place(s):r.clone().translate(s):null},circle:function(t){return new z.Circle(n(t,"cx","cy"),e(t,"r"))},ellipse:function(t){var e=n(t,"cx","cy"),r=i(t,"rx","ry");return new z.Ellipse(new d(e.subtract(r),e.add(r)))},rect:function(t){var e=n(t,"x","y"),r=i(t,"width","height"),s=i(t,"rx","ry");return new z.Rectangle(new d(e,r),s)},line:function(t){return new z.Line(n(t,"x1","y1"),n(t,"x2","y2"))},text:function(t){var e=new j(n(t,"x","y",!1).add(n(t,"dx","dy",!1)));return e.setContent(t.textContent.trim()||""),e}},k=t.merge(t.each(Q,function(t){this[t.attribute]=function(e,n){e[t.set](r(n,t.type,t.fromSVG))}},{}),{id:function(t,e){P[e]=t,t.setName&&t.setName(e)},"clip-path":function(t,e){var n=x(e);if(n){if(n=n.clone(),n.setClipMask(!0),!(t instanceof y))return new y(n,t);t.insertChild(0,n)}},gradientTransform:l,transform:l,"fill-opacity":f,"stroke-opacity":f,visibility:function(t,e){t.setVisible("visible"===e)},"stop-color":function(t,e){t.setColor&&t.setColor(e)},"stop-opacity":function(t,e){t._color&&t._color.setAlpha(parseFloat(e))},offset:function(t,e){var n=e.match(/(.*)%$/);t.setRampPoint(n?n[1]/100:parseFloat(e))},viewBox:function(t,e,n,s,a){var o=new d(r(e,"array")),h=i(s,"width","height",!0);if(t instanceof y){var u=h?o.getSize().divide(h):1,c=(new _).translate(o.getPoint()).scale(u);t.transform(c.inverted())}else if(t instanceof v){h&&o.setSize(h);var l="visible"!=g(s,"overflow",a),f=t._definition;l&&!o.contains(f.getBounds())&&(l=new z.Rectangle(o).transform(f._matrix),l.setClipMask(!0),f.addChild(l))}}}),P={};m.inject({importSVG:function(t){return this.addChild(C(t,!0))}}),p.inject({importSVG:function(t){return this.activate(),C(t,!0)}})},paper=new(n.inject(t.merge(t.exports,{enumerable:!0,Base:t,Numerical:a,DomElement:R,DomEvent:q}))),"function"==typeof define&&define.amd&&define(paper),paper};paper.PaperScope.prototype.PaperScript=new function(){function _$_(t,e,n){var i=binaryOperators[e];if(t&&t[i]){var r=t[i](n);return"!="===e?!r:r}switch(e){case"+":return t+n;case"-":return t-n;case"*":return t*n;case"/":return t/n;case"%":return t%n;case"==":return t==n;case"!=":return t!=n}}function $_(t,e){var n=unaryOperators[t];if(n&&e&&e[n])return e[n]();switch(t){case"+":return+e;case"-":return-e}}function compile(t){function e(t){for(var e=0,n=s.length;n>e;e++){var i=s[e];if(i[0]>=t)break;t+=i[1]}return t}function n(n){return t.substring(e(n.range[0]),e(n.range[1]))}function i(n,i){for(var r=e(n.range[0]),a=e(n.range[1]),o=0,h=s.length-1;h>=0;h--)if(r>s[h][0]){o=h+1;break}s.splice(o,0,[r,i.length-a+r]),t=t.substring(0,r)+i+t.substring(a)}function r(t){if(t&&("MemberExpression"!==t.type||!t.computed)){for(var e in t)if("range"!==e){var s=t[e];if(Array.isArray(s))for(var a=0,o=s.length;o>a;a++)r(s[a]);else s&&"object"==typeof s&&r(s)}switch(t&&t.type){case"BinaryExpression":if(t.operator in binaryOperators&&"Literal"!==t.left.type){var h=n(t.left),u=n(t.right);i(t,"_$_("+h+', "'+t.operator+'", '+u+")")}break;case"AssignmentExpression":if(/^.=$/.test(t.operator)&&"Literal"!==t.left.type){var h=n(t.left),u=n(t.right);i(t,h+" = _$_("+h+', "'+t.operator[0]+'", '+u+")")}break;case"UpdateExpression":if(!t.prefix){var c=n(t.argument);i(t,c+" = _$_("+c+', "'+t.operator[0]+'", 1)')}break;case"UnaryExpression":if(t.operator in unaryOperators&&"Literal"!==t.argument.type){var c=n(t.argument);i(t,'$_("'+t.operator+'", '+c+")")}}}}var s=[];return r(acorn.parse(t,{ranges:!0})),t}function evaluate(code,scope){paper=scope;var view=scope.project&&scope.project.view,res;with(scope)!function(){var onActivate,onDeactivate,onEditOptions,onMouseDown,onMouseUp,onMouseDrag,onMouseMove,onKeyDown,onKeyUp,onFrame,onResize;res=eval(compile(code)),/on(?:Key|Mouse)(?:Up|Down|Move|Drag)/.test(code)&&Base.each(paper.Tool.prototype._events,function(key){var value=eval(key);value&&(scope.getTool()[key]=value)}),view&&(view.setOnResize(onResize),view.fire("resize",{size:view.size,delta:new Point}),view.setOnFrame(onFrame),view.draw())}.call(scope);return res}function request(t,e){var n=new(window.ActiveXObject||XMLHttpRequest)("Microsoft.XMLHTTP");return n.open("GET",t,!0),n.overrideMimeType&&n.overrideMimeType("text/plain"),n.onreadystatechange=function(){return 4===n.readyState?evaluate(n.responseText,e):void 0},n.send(null)}function load(){for(var t=document.getElementsByTagName("script"),e=paper.PaperScope,n=0,i=t.length;i>n;n++){var r=t[n];if(/^text\/(?:x-|)paperscript$/.test(r.type)&&!r.getAttribute("data-paper-ignore")){var s=e.getAttribute(r,"canvas"),a=e.get(s)||new e(r).setup(s);r.src?request(r.src,a):evaluate(r.innerHTML,a),r.setAttribute("data-paper-ignore",!0)}}}!function(t){return"object"==typeof exports&&"object"==typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):(t(this.acorn||(this.acorn={})),void 0) +}(function(t){"use strict";function e(t){le=t||{};for(var e in ge)le.hasOwnProperty(e)||(le[e]=ge[e]);_e=le.sourceFile||null}function n(t,e){var n=pe(de,t);e+=" ("+n.line+":"+n.column+")";var i=new SyntaxError(e);throw i.pos=t,i.loc=n,i.raisedAt=ve,i}function i(t){function e(t){if(1==t.length)return n+="return str === "+JSON.stringify(t[0])+";";n+="switch(str){";for(var e=0;t.length>e;++e)n+="case "+JSON.stringify(t[e])+":";n+="return true}return false;"}t=t.split(" ");var n="",i=[];t:for(var r=0;t.length>r;++r){for(var s=0;i.length>s;++s)if(i[s][0].length==t[r].length){i[s].push(t[r]);continue t}i.push([t[r]])}if(i.length>3){i.sort(function(t,e){return e.length-t.length}),n+="switch(str.length){";for(var r=0;i.length>r;++r){var a=i[r];n+="case "+a[0].length+":",e(a)}n+="}"}else e(t);return Function("str",n)}function r(){this.line=ke,this.column=ve-Pe}function s(){ke=1,ve=Pe=0,Se=!0,u()}function a(t,e){ye=ve,le.locations&&(xe=new r),be=t,u(),Ce=e,Se=t.beforeExpr}function o(){var t=le.onComment&&le.locations&&new r,e=ve,i=de.indexOf("*/",ve+=2);if(-1===i&&n(ve-2,"Unterminated comment"),ve=i+2,le.locations){$n.lastIndex=e;for(var s;(s=$n.exec(de))&&ve>s.index;)++ke,Pe=s.index+s[0].length}le.onComment&&le.onComment(!0,de.slice(e+2,i),e,ve,t,le.locations&&new r)}function h(){for(var t=ve,e=le.onComment&&le.locations&&new r,n=de.charCodeAt(ve+=2);fe>ve&&10!==n&&13!==n&&8232!==n&&8329!==n;)++ve,n=de.charCodeAt(ve);le.onComment&&le.onComment(!1,de.slice(t+2,ve),t,ve,e,le.locations&&new r)}function u(){for(;fe>ve;){var t=de.charCodeAt(ve);if(32===t)++ve;else if(13===t){++ve;var e=de.charCodeAt(ve);10===e&&++ve,le.locations&&(++ke,Pe=ve)}else if(10===t)++ve,++ke,Pe=ve;else if(14>t&&t>8)++ve;else if(47===t){var e=de.charCodeAt(ve+1);if(42===e)o();else{if(47!==e)break;h()}}else if(14>t&&t>8||32===t||160===t)++ve;else{if(!(t>=5760&&Zn.test(String.fromCharCode(t))))break;++ve}}}function c(){var t=de.charCodeAt(ve+1);return t>=48&&57>=t?S(!0):(++ve,a(wn))}function l(){var t=de.charCodeAt(ve+1);return Se?(++ve,x()):61===t?w(Sn,2):w(bn,1)}function d(){var t=de.charCodeAt(ve+1);return 61===t?w(Sn,2):w(En,1)}function f(t){var e=de.charCodeAt(ve+1);return e===t?w(124===t?In:An,2):61===e?w(Sn,2):w(124===t?zn:On,1)}function _(){var t=de.charCodeAt(ve+1);return 61===t?w(Sn,2):w(Ln,1)}function g(t){var e=de.charCodeAt(ve+1);return e===t?w(Pn,2):61===e?w(Sn,2):w(kn,1)}function p(t){var e=de.charCodeAt(ve+1),n=1;return e===t?(n=62===t&&62===de.charCodeAt(ve+2)?3:2,61===de.charCodeAt(ve+n)?w(Sn,n+1):w(jn,n)):(61===e&&(n=61===de.charCodeAt(ve+2)?3:2),w(Dn,n))}function v(t){var e=de.charCodeAt(ve+1);return 61===e?w(Tn,61===de.charCodeAt(ve+2)?3:2):w(61===t?Cn:Mn,1)}function m(t){switch(t){case 46:return c();case 40:return++ve,a(gn);case 41:return++ve,a(pn);case 59:return++ve,a(mn);case 44:return++ve,a(vn);case 91:return++ve,a(ln);case 93:return++ve,a(dn);case 123:return++ve,a(fn);case 125:return++ve,a(_n);case 58:return++ve,a(yn);case 63:return++ve,a(xn);case 48:var e=de.charCodeAt(ve+1);if(120===e||88===e)return C();case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return S(!1);case 34:case 39:return k(t);case 47:return l(t);case 37:case 42:return d();case 124:case 38:return f(t);case 94:return _();case 43:case 45:return g(t);case 60:case 62:return p(t);case 61:case 33:return v(t);case 126:return w(Mn,1)}return!1}function y(t){if(t?ve=me+1:me=ve,le.locations&&(we=new r),t)return x();if(ve>=fe)return a(Be);var e=de.charCodeAt(ve);if(Yn(e)||92===e)return I();var i=m(e);if(i===!1){var s=String.fromCharCode(e);if("\\"===s||Jn.test(s))return I();n(ve,"Unexpected character '"+s+"'")}return i}function w(t,e){var n=de.slice(ve,ve+e);ve+=e,a(t,n)}function x(){for(var t,e,i="",r=ve;;){ve>=fe&&n(r,"Unterminated regular expression");var s=de.charAt(ve);if(Wn.test(s)&&n(r,"Unterminated regular expression"),t)t=!1;else{if("["===s)e=!0;else if("]"===s&&e)e=!1;else if("/"===s&&!e)break;t="\\"===s}++ve}var i=de.slice(r,ve);++ve;var o=M();return o&&!/^[gmsiy]*$/.test(o)&&n(r,"Invalid regexp flag"),a(De,RegExp(i,o))}function b(t,e){for(var n=ve,i=0,r=0,s=null==e?1/0:e;s>r;++r){var a,o=de.charCodeAt(ve);if(a=o>=97?o-97+10:o>=65?o-65+10:o>=48&&57>=o?o-48:1/0,a>=t)break;++ve,i=i*t+a}return ve===n||null!=e&&ve-n!==e?null:i}function C(){ve+=2;var t=b(16);return null==t&&n(me+2,"Expected hexadecimal number"),Yn(de.charCodeAt(ve))&&n(ve,"Identifier directly after number"),a(Te,t)}function S(t){var e=ve,i=!1,r=48===de.charCodeAt(ve);t||null!==b(10)||n(e,"Invalid number"),46===de.charCodeAt(ve)&&(++ve,b(10),i=!0);var s=de.charCodeAt(ve);(69===s||101===s)&&(s=de.charCodeAt(++ve),(43===s||45===s)&&++ve,null===b(10)&&n(e,"Invalid number"),i=!0),Yn(de.charCodeAt(ve))&&n(ve,"Identifier directly after number");var o,h=de.slice(e,ve);return i?o=parseFloat(h):r&&1!==h.length?/[89]/.test(h)||Oe?n(e,"Invalid number"):o=parseInt(h,8):o=parseInt(h,10),a(Te,o)}function k(t){ve++;for(var e="";;){ve>=fe&&n(me,"Unterminated string constant");var i=de.charCodeAt(ve);if(i===t)return++ve,a(je,e);if(92===i){i=de.charCodeAt(++ve);var r=/^[0-7]+/.exec(de.slice(ve,ve+3));for(r&&(r=r[0]);r&&parseInt(r,8)>255;)r=r.slice(0,r.length-1);if("0"===r&&(r=null),++ve,r)Oe&&n(ve-2,"Octal literal in strict mode"),e+=String.fromCharCode(parseInt(r,8)),ve+=r.length-1;else switch(i){case 110:e+="\n";break;case 114:e+="\r";break;case 120:e+=String.fromCharCode(P(2));break;case 117:e+=String.fromCharCode(P(4));break;case 85:e+=String.fromCharCode(P(8));break;case 116:e+=" ";break;case 98:e+="\b";break;case 118:e+=" ";break;case 102:e+="\f";break;case 48:e+="\0";break;case 13:10===de.charCodeAt(ve)&&++ve;case 10:le.locations&&(Pe=ve,++ke);break;default:e+=String.fromCharCode(i)}}else(13===i||10===i||8232===i||8329===i)&&n(me,"Unterminated string constant"),e+=String.fromCharCode(i),++ve}}function P(t){var e=b(16,t);return null===e&&n(me,"Bad character escape sequence"),e}function M(){Nn=!1;for(var t,e=!0,i=ve;;){var r=de.charCodeAt(ve);if(Kn(r))Nn&&(t+=de.charAt(ve)),++ve;else{if(92!==r)break;Nn||(t=de.slice(i,ve)),Nn=!0,117!=de.charCodeAt(++ve)&&n(ve,"Expecting Unicode escape sequence \\uXXXX"),++ve;var s=P(4),a=String.fromCharCode(s);a||n(ve-1,"Invalid Unicode escape"),(e?Yn(s):Kn(s))||n(ve-4,"Invalid Unicode escape"),t+=a}e=!1}return Nn?t:de.slice(i,ve)}function I(){var t=M(),e=Ee;return Nn||(Hn(t)?e=cn[t]:(le.forbidReserved&&(3===le.ecmaVersion?Fn:Rn)(t)||Oe&&qn(t))&&n(me,"The keyword '"+t+"' is reserved")),a(e,t)}function A(){Me=me,Ie=ye,Ae=xe,y()}function z(t){for(Oe=t,ve=Ie;Pe>ve;)Pe=de.lastIndexOf("\n",Pe-2)+1,--ke;u(),y()}function L(){this.type=null,this.start=me,this.end=null}function O(){this.start=we,this.end=null,null!==_e&&(this.source=_e)}function T(){var t=new L;return le.locations&&(t.loc=new O),le.ranges&&(t.range=[me,0]),t}function D(t){var e=new L;return e.start=t.start,le.locations&&(e.loc=new O,e.loc.start=t.loc.start),le.ranges&&(e.range=[t.range[0],0]),e}function j(t,e){return t.type=e,t.end=Ie,le.locations&&(t.loc.end=Ae),le.ranges&&(t.range[1]=Ie),t}function E(t){return le.ecmaVersion>=5&&"ExpressionStatement"===t.type&&"Literal"===t.expression.type&&"use strict"===t.expression.value}function B(t){return be===t?(A(),!0):void 0}function N(){return!le.strictSemicolons&&(be===Be||be===_n||Wn.test(de.slice(Ie,me)))}function F(){B(mn)||N()||q()}function R(t){be===t?A():q()}function q(){n(me,"Unexpected token")}function V(t){"Identifier"!==t.type&&"MemberExpression"!==t.type&&n(t.start,"Assigning to rvalue"),Oe&&"Identifier"===t.type&&Vn(t.name)&&n(t.start,"Assigning to "+t.name+" in strict mode")}function H(t){Me=Ie=ve,le.locations&&(Ae=new r),ze=Oe=null,Le=[],y();var e=t||T(),n=!0;for(t||(e.body=[]);be!==Be;){var i=Z();e.body.push(i),n&&E(i)&&z(!0),n=!1}return j(e,"Program")}function Z(){be===bn&&y(!0);var t=be,e=T();switch(t){case Ne:case qe:A();var i=t===Ne;B(mn)||N()?e.label=null:be!==Ee?q():(e.label=ce(),F());for(var r=0;Le.length>r;++r){var s=Le[r];if(null==e.label||s.name===e.label.name){if(null!=s.kind&&(i||"loop"===s.kind))break;if(e.label&&i)break}}return r===Le.length&&n(e.start,"Unsyntactic "+t.keyword),j(e,i?"BreakStatement":"ContinueStatement");case Ve:return A(),F(),j(e,"DebuggerStatement");case Ze:return A(),Le.push(Qn),e.body=Z(),Le.pop(),R(en),e.test=U(),F(),j(e,"DoWhileStatement");case Je:if(A(),Le.push(Qn),R(gn),be===mn)return J(e,null);if(be===tn){var a=T();return A(),W(a,!0),1===a.declarations.length&&B(un)?G(e,a):J(e,a)}var a=$(!1,!0);return B(un)?(V(a),G(e,a)):J(e,a);case Ge:return A(),he(e,!0);case We:return A(),e.test=U(),e.consequent=Z(),e.alternate=B(Ue)?Z():null,j(e,"IfStatement");case $e:return ze||n(me,"'return' outside of function"),A(),B(mn)||N()?e.argument=null:(e.argument=$(),F()),j(e,"ReturnStatement");case Ye:A(),e.discriminant=U(),e.cases=[],R(fn),Le.push(ti);for(var o,h;be!=_n;)if(be===Fe||be===He){var u=be===Fe;o&&j(o,"SwitchCase"),e.cases.push(o=T()),o.consequent=[],A(),u?o.test=$():(h&&n(Me,"Multiple default clauses"),h=!0,o.test=null),R(yn)}else o||q(),o.consequent.push(Z());return o&&j(o,"SwitchCase"),A(),Le.pop(),j(e,"SwitchStatement");case Ke:return A(),Wn.test(de.slice(Ie,me))&&n(Ie,"Illegal newline after throw"),e.argument=$(),F(),j(e,"ThrowStatement");case Qe:if(A(),e.block=X(),e.handler=null,be===Re){var c=T();A(),R(gn),c.param=ce(),Oe&&Vn(c.param.name)&&n(c.param.start,"Binding "+c.param.name+" in strict mode"),R(pn),c.guard=null,c.body=X(),e.handler=j(c,"CatchClause")}return e.finalizer=B(Xe)?X():null,e.handler||e.finalizer||n(e.start,"Missing catch or finally clause"),j(e,"TryStatement");case tn:return A(),e=W(e),F(),e;case en:return A(),e.test=U(),Le.push(Qn),e.body=Z(),Le.pop(),j(e,"WhileStatement");case nn:return Oe&&n(me,"'with' in strict mode"),A(),e.object=U(),e.body=Z(),j(e,"WithStatement");case fn:return X();case mn:return A(),j(e,"EmptyStatement");default:var l=Ce,d=$();if(t===Ee&&"Identifier"===d.type&&B(yn)){for(var r=0;Le.length>r;++r)Le[r].name===l&&n(d.start,"Label '"+l+"' is already declared");var f=be.isLoop?"loop":be===Ye?"switch":null;return Le.push({name:l,kind:f}),e.body=Z(),Le.pop(),e.label=d,j(e,"LabeledStatement")}return e.expression=d,F(),j(e,"ExpressionStatement")}}function U(){R(gn);var t=$();return R(pn),t}function X(){var t,e=T(),n=!0,i=!1;for(e.body=[],R(fn);!B(_n);){var r=Z();e.body.push(r),n&&E(r)&&(t=i,z(i=!0)),n=!1}return i&&!t&&z(!1),j(e,"BlockStatement")}function J(t,e){return t.init=e,R(mn),t.test=be===mn?null:$(),R(mn),t.update=be===pn?null:$(),R(pn),t.body=Z(),Le.pop(),j(t,"ForStatement")}function G(t,e){return t.left=e,t.right=$(),R(pn),t.body=Z(),Le.pop(),j(t,"ForInStatement")}function W(t,e){for(t.declarations=[],t.kind="var";;){var i=T();if(i.id=ce(),Oe&&Vn(i.id.name)&&n(i.id.start,"Binding "+i.id.name+" in strict mode"),i.init=B(Cn)?$(!0,e):null,t.declarations.push(j(i,"VariableDeclarator")),!B(vn))break}return j(t,"VariableDeclaration")}function $(t,e){var n=Y(e);if(!t&&be===vn){var i=D(n);for(i.expressions=[n];B(vn);)i.expressions.push(Y(e));return j(i,"SequenceExpression")}return n}function Y(t){var e=K(t);if(be.isAssign){var n=D(e);return n.operator=Ce,n.left=e,A(),n.right=Y(t),V(e),j(n,"AssignmentExpression")}return e}function K(t){var e=Q(t);if(B(xn)){var n=D(e);return n.test=e,n.consequent=$(!0),R(yn),n.alternate=$(!0,t),j(n,"ConditionalExpression")}return e}function Q(t){return te(ee(t),-1,t)}function te(t,e,n){var i=be.binop;if(null!=i&&(!n||be!==un)&&i>e){var r=D(t);r.left=t,r.operator=Ce,A(),r.right=te(ee(n),i,n);var r=j(r,/&&|\|\|/.test(r.operator)?"LogicalExpression":"BinaryExpression");return te(r,e,n)}return t}function ee(t){if(be.prefix){var e=T(),i=be.isUpdate;return e.operator=Ce,e.prefix=!0,A(),e.argument=ee(t),i?V(e.argument):Oe&&"delete"===e.operator&&"Identifier"===e.argument.type&&n(e.start,"Deleting local variable in strict mode"),j(e,i?"UpdateExpression":"UnaryExpression")}for(var r=ne();be.postfix&&!N();){var e=D(r);e.operator=Ce,e.prefix=!1,e.argument=r,V(r),A(),r=j(e,"UpdateExpression")}return r}function ne(){return ie(re())}function ie(t,e){if(B(wn)){var n=D(t);return n.object=t,n.property=ce(!0),n.computed=!1,ie(j(n,"MemberExpression"),e)}if(B(ln)){var n=D(t);return n.object=t,n.property=$(),n.computed=!0,R(dn),ie(j(n,"MemberExpression"),e)}if(!e&&B(gn)){var n=D(t);return n.callee=t,n.arguments=ue(pn,!1),ie(j(n,"CallExpression"),e)}return t}function re(){switch(be){case sn:var t=T();return A(),j(t,"ThisExpression");case Ee:return ce();case Te:case je:case De:var t=T();return t.value=Ce,t.raw=de.slice(me,ye),A(),j(t,"Literal");case an:case on:case hn:var t=T();return t.value=be.atomValue,t.raw=be.keyword,A(),j(t,"Literal");case gn:var e=we,n=me;A();var i=$();return i.start=n,i.end=ye,le.locations&&(i.loc.start=e,i.loc.end=xe),le.ranges&&(i.range=[n,ye]),R(pn),i;case ln:var t=T();return A(),t.elements=ue(dn,!0,!0),j(t,"ArrayExpression");case fn:return ae();case Ge:var t=T();return A(),he(t,!1);case rn:return se();default:q()}}function se(){var t=T();return A(),t.callee=ie(re(),!0),t.arguments=B(gn)?ue(pn,!1):[],j(t,"NewExpression")}function ae(){var t=T(),e=!0,i=!1;for(t.properties=[],A();!B(_n);){if(e)e=!1;else if(R(vn),le.allowTrailingCommas&&B(_n))break;var r,s={key:oe()},a=!1;if(B(yn)?(s.value=$(!0),r=s.kind="init"):le.ecmaVersion>=5&&"Identifier"===s.key.type&&("get"===s.key.name||"set"===s.key.name)?(a=i=!0,r=s.kind=s.key.name,s.key=oe(),be!==gn&&q(),s.value=he(T(),!1)):q(),"Identifier"===s.key.type&&(Oe||i))for(var o=0;t.properties.length>o;++o){var h=t.properties[o];if(h.key.name===s.key.name){var u=r==h.kind||a&&"init"===h.kind||"init"===r&&("get"===h.kind||"set"===h.kind);u&&!Oe&&"init"===r&&"init"===h.kind&&(u=!1),u&&n(s.key.start,"Redefinition of property")}}t.properties.push(s)}return j(t,"ObjectExpression")}function oe(){return be===Te||be===je?re():ce(!0)}function he(t,e){be===Ee?t.id=ce():e?q():t.id=null,t.params=[];var i=!0;for(R(gn);!B(pn);)i?i=!1:R(vn),t.params.push(ce());var r=ze,s=Le;if(ze=!0,Le=[],t.body=X(!0),ze=r,Le=s,Oe||t.body.body.length&&E(t.body.body[0]))for(var a=t.id?-1:0;t.params.length>a;++a){var o=0>a?t.id:t.params[a];if((qn(o.name)||Vn(o.name))&&n(o.start,"Defining '"+o.name+"' in strict mode"),a>=0)for(var h=0;a>h;++h)o.name===t.params[h].name&&n(o.start,"Argument name clash in strict mode")}return j(t,e?"FunctionDeclaration":"FunctionExpression")}function ue(t,e,n){for(var i=[],r=!0;!B(t);){if(r)r=!1;else if(R(vn),e&&le.allowTrailingCommas&&B(t))break;n&&be===vn?i.push(null):i.push($(!0))}return i}function ce(t){var e=T();return e.name=be===Ee?Ce:t&&!le.forbidReserved&&be.keyword||q(),A(),j(e,"Identifier")}t.version="0.2.01";var le,de,fe,_e;t.parse=function(t,n){return de=t+"",fe=de.length,e(n),s(),H(le.program)};var ge=t.defaultOptions={ecmaVersion:5,strictSemicolons:!1,allowTrailingCommas:!0,forbidReserved:!1,locations:!1,onComment:null,ranges:!1,program:null,sourceFile:null},pe=t.getLineInfo=function(t,e){for(var n=1,i=0;;){$n.lastIndex=i;var r=$n.exec(t);if(!(r&&e>r.index))break;++n,i=r.index+r[0].length}return{line:n,column:e-i}};t.tokenize=function(t,n){function i(t){return y(t),r.start=me,r.end=ye,r.startLoc=we,r.endLoc=xe,r.type=be,r.value=Ce,r}de=t+"",fe=de.length,e(n),s();var r={};return i.jumpTo=function(t,e){if(ve=t,le.locations){ke=Pe=$n.lastIndex=0;for(var n;(n=$n.exec(de))&&t>n.index;)++ke,Pe=n.index+n[0].length}de.charAt(t-1),Se=e,u()},i};var ve,me,ye,we,xe,be,Ce,Se,ke,Pe,Me,Ie,Ae,ze,Le,Oe,Te={type:"num"},De={type:"regexp"},je={type:"string"},Ee={type:"name"},Be={type:"eof"},Ne={keyword:"break"},Fe={keyword:"case",beforeExpr:!0},Re={keyword:"catch"},qe={keyword:"continue"},Ve={keyword:"debugger"},He={keyword:"default"},Ze={keyword:"do",isLoop:!0},Ue={keyword:"else",beforeExpr:!0},Xe={keyword:"finally"},Je={keyword:"for",isLoop:!0},Ge={keyword:"function"},We={keyword:"if"},$e={keyword:"return",beforeExpr:!0},Ye={keyword:"switch"},Ke={keyword:"throw",beforeExpr:!0},Qe={keyword:"try"},tn={keyword:"var"},en={keyword:"while",isLoop:!0},nn={keyword:"with"},rn={keyword:"new",beforeExpr:!0},sn={keyword:"this"},an={keyword:"null",atomValue:null},on={keyword:"true",atomValue:!0},hn={keyword:"false",atomValue:!1},un={keyword:"in",binop:7,beforeExpr:!0},cn={"break":Ne,"case":Fe,"catch":Re,"continue":qe,"debugger":Ve,"default":He,"do":Ze,"else":Ue,"finally":Xe,"for":Je,"function":Ge,"if":We,"return":$e,"switch":Ye,"throw":Ke,"try":Qe,"var":tn,"while":en,"with":nn,"null":an,"true":on,"false":hn,"new":rn,"in":un,"instanceof":{keyword:"instanceof",binop:7,beforeExpr:!0},"this":sn,"typeof":{keyword:"typeof",prefix:!0,beforeExpr:!0},"void":{keyword:"void",prefix:!0,beforeExpr:!0},"delete":{keyword:"delete",prefix:!0,beforeExpr:!0}},ln={type:"[",beforeExpr:!0},dn={type:"]"},fn={type:"{",beforeExpr:!0},_n={type:"}"},gn={type:"(",beforeExpr:!0},pn={type:")"},vn={type:",",beforeExpr:!0},mn={type:";",beforeExpr:!0},yn={type:":",beforeExpr:!0},wn={type:"."},xn={type:"?",beforeExpr:!0},bn={binop:10,beforeExpr:!0},Cn={isAssign:!0,beforeExpr:!0},Sn={isAssign:!0,beforeExpr:!0},kn={binop:9,prefix:!0,beforeExpr:!0},Pn={postfix:!0,prefix:!0,isUpdate:!0},Mn={prefix:!0,beforeExpr:!0},In={binop:1,beforeExpr:!0},An={binop:2,beforeExpr:!0},zn={binop:3,beforeExpr:!0},Ln={binop:4,beforeExpr:!0},On={binop:5,beforeExpr:!0},Tn={binop:6,beforeExpr:!0},Dn={binop:7,beforeExpr:!0},jn={binop:8,beforeExpr:!0},En={binop:10,beforeExpr:!0};t.tokTypes={bracketL:ln,bracketR:dn,braceL:fn,braceR:_n,parenL:gn,parenR:pn,comma:vn,semi:mn,colon:yn,dot:wn,question:xn,slash:bn,eq:Cn,name:Ee,eof:Be,num:Te,regexp:De,string:je};for(var Bn in cn)t.tokTypes[Bn]=cn[Bn];var Nn,Fn=i("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"),Rn=i("class enum extends super const export import"),qn=i("implements interface let package private protected public static yield"),Vn=i("eval arguments"),Hn=i("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"),Zn=/[\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]/,Un="\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",Xn="\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",Jn=RegExp("["+Un+"]"),Gn=RegExp("["+Un+Xn+"]"),Wn=/[\n\r\u2028\u2029]/,$n=/\r\n|[\n\r\u2028\u2029]/g,Yn=t.isIdentifierStart=function(t){return 65>t?36===t:91>t?!0:97>t?95===t:123>t?!0:t>=170&&Jn.test(String.fromCharCode(t))},Kn=t.isIdentifierChar=function(t){return 48>t?36===t:58>t?!0:65>t?!1:91>t?!0:97>t?95===t:123>t?!0:t>=170&&Gn.test(String.fromCharCode(t))},Qn={kind:"loop"},ti={kind:"switch"}});var binaryOperators={"+":"add","-":"subtract","*":"multiply","/":"divide","%":"modulo","==":"equals","!=":"equals"},unaryOperators={"-":"negate","+":null};return"complete"===document.readyState?setTimeout(load):paper.DomEvent.add(window,{load:load}),{compile:compile,evaluate:evaluate,load:load}}; \ No newline at end of file diff --git a/dist/paper.js b/dist/paper.js index 37e257c7..22b425de 120000 --- a/dist/paper.js +++ b/dist/paper.js @@ -1 +1 @@ -../src/load.js \ No newline at end of file +paper-full.js \ No newline at end of file diff --git a/package.json b/package.json index 65dd2c94..ae1b5a77 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "paper", - "version": "0.9.4", + "version": "0.9.5", "main": "./src/node/index.js", "engines": { "node": ">= 0.4.0"