paper-full.js 429 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994
  1. /*!
  2. * Paper.js v0.12.0 - The Swiss Army Knife of Vector Graphics Scripting.
  3. * http://paperjs.org/
  4. *
  5. * Copyright (c) 2011 - 2016, Juerg Lehni & Jonathan Puckey
  6. * http://scratchdisk.com/ & https://puckey.studio/
  7. *
  8. * Distributed under the MIT license. See LICENSE file for details.
  9. *
  10. * All rights reserved.
  11. *
  12. * Date: Mon Dec 3 14:19:11 2018 +0100
  13. *
  14. ***
  15. *
  16. * Straps.js - Class inheritance library with support for bean-style accessors
  17. *
  18. * Copyright (c) 2006 - 2016 Juerg Lehni
  19. * http://scratchdisk.com/
  20. *
  21. * Distributed under the MIT license.
  22. *
  23. ***
  24. *
  25. * Acorn.js
  26. * https://marijnhaverbeke.nl/acorn/
  27. *
  28. * Acorn is a tiny, fast JavaScript parser written in JavaScript,
  29. * created by Marijn Haverbeke and released under an MIT license.
  30. *
  31. */
  32. var paper = function(self, undefined) {
  33. self = self || require('./node/self.js');
  34. var window = self.window,
  35. document = self.document;
  36. var Base = new function() {
  37. var hidden = /^(statics|enumerable|beans|preserve)$/,
  38. array = [],
  39. slice = array.slice,
  40. create = Object.create,
  41. describe = Object.getOwnPropertyDescriptor,
  42. define = Object.defineProperty,
  43. forEach = array.forEach || function(iter, bind) {
  44. for (var i = 0, l = this.length; i < l; i++) {
  45. iter.call(bind, this[i], i, this);
  46. }
  47. },
  48. forIn = function(iter, bind) {
  49. for (var i in this) {
  50. if (this.hasOwnProperty(i))
  51. iter.call(bind, this[i], i, this);
  52. }
  53. },
  54. set = Object.assign || function(dst) {
  55. for (var i = 1, l = arguments.length; i < l; i++) {
  56. var src = arguments[i];
  57. for (var key in src) {
  58. if (src.hasOwnProperty(key))
  59. dst[key] = src[key];
  60. }
  61. }
  62. return dst;
  63. },
  64. each = function(obj, iter, bind) {
  65. if (obj) {
  66. var desc = describe(obj, 'length');
  67. (desc && typeof desc.value === 'number' ? forEach : forIn)
  68. .call(obj, iter, bind = bind || obj);
  69. }
  70. return bind;
  71. };
  72. function inject(dest, src, enumerable, beans, preserve) {
  73. var beansNames = {};
  74. function field(name, val) {
  75. val = val || (val = describe(src, name))
  76. && (val.get ? val : val.value);
  77. if (typeof val === 'string' && val[0] === '#')
  78. val = dest[val.substring(1)] || val;
  79. var isFunc = typeof val === 'function',
  80. res = val,
  81. prev = preserve || isFunc && !val.base
  82. ? (val && val.get ? name in dest : dest[name])
  83. : null,
  84. bean;
  85. if (!preserve || !prev) {
  86. if (isFunc && prev)
  87. val.base = prev;
  88. if (isFunc && beans !== false
  89. && (bean = name.match(/^([gs]et|is)(([A-Z])(.*))$/)))
  90. beansNames[bean[3].toLowerCase() + bean[4]] = bean[2];
  91. if (!res || isFunc || !res.get || typeof res.get !== 'function'
  92. || !Base.isPlainObject(res)) {
  93. res = { value: res, writable: true };
  94. }
  95. if ((describe(dest, name)
  96. || { configurable: true }).configurable) {
  97. res.configurable = true;
  98. res.enumerable = enumerable != null ? enumerable : !bean;
  99. }
  100. define(dest, name, res);
  101. }
  102. }
  103. if (src) {
  104. for (var name in src) {
  105. if (src.hasOwnProperty(name) && !hidden.test(name))
  106. field(name);
  107. }
  108. for (var name in beansNames) {
  109. var part = beansNames[name],
  110. set = dest['set' + part],
  111. get = dest['get' + part] || set && dest['is' + part];
  112. if (get && (beans === true || get.length === 0))
  113. field(name, { get: get, set: set });
  114. }
  115. }
  116. return dest;
  117. }
  118. function Base() {
  119. for (var i = 0, l = arguments.length; i < l; i++) {
  120. var src = arguments[i];
  121. if (src)
  122. set(this, src);
  123. }
  124. return this;
  125. }
  126. return inject(Base, {
  127. inject: function(src) {
  128. if (src) {
  129. var statics = src.statics === true ? src : src.statics,
  130. beans = src.beans,
  131. preserve = src.preserve;
  132. if (statics !== src)
  133. inject(this.prototype, src, src.enumerable, beans, preserve);
  134. inject(this, statics, null, beans, preserve);
  135. }
  136. for (var i = 1, l = arguments.length; i < l; i++)
  137. this.inject(arguments[i]);
  138. return this;
  139. },
  140. extend: function() {
  141. var base = this,
  142. ctor,
  143. proto;
  144. for (var i = 0, obj, l = arguments.length;
  145. i < l && !(ctor && proto); i++) {
  146. obj = arguments[i];
  147. ctor = ctor || obj.initialize;
  148. proto = proto || obj.prototype;
  149. }
  150. ctor = ctor || function() {
  151. base.apply(this, arguments);
  152. };
  153. proto = ctor.prototype = proto || create(this.prototype);
  154. define(proto, 'constructor',
  155. { value: ctor, writable: true, configurable: true });
  156. inject(ctor, this);
  157. if (arguments.length)
  158. this.inject.apply(ctor, arguments);
  159. ctor.base = base;
  160. return ctor;
  161. }
  162. }).inject({
  163. enumerable: false,
  164. initialize: Base,
  165. set: Base,
  166. inject: function() {
  167. for (var i = 0, l = arguments.length; i < l; i++) {
  168. var src = arguments[i];
  169. if (src) {
  170. inject(this, src, src.enumerable, src.beans, src.preserve);
  171. }
  172. }
  173. return this;
  174. },
  175. extend: function() {
  176. var res = create(this);
  177. return res.inject.apply(res, arguments);
  178. },
  179. each: function(iter, bind) {
  180. return each(this, iter, bind);
  181. },
  182. clone: function() {
  183. return new this.constructor(this);
  184. },
  185. statics: {
  186. set: set,
  187. each: each,
  188. create: create,
  189. define: define,
  190. describe: describe,
  191. clone: function(obj) {
  192. return set(new obj.constructor(), obj);
  193. },
  194. isPlainObject: function(obj) {
  195. var ctor = obj != null && obj.constructor;
  196. return ctor && (ctor === Object || ctor === Base
  197. || ctor.name === 'Object');
  198. },
  199. pick: function(a, b) {
  200. return a !== undefined ? a : b;
  201. },
  202. slice: function(list, begin, end) {
  203. return slice.call(list, begin, end);
  204. }
  205. }
  206. });
  207. };
  208. if (typeof module !== 'undefined')
  209. module.exports = Base;
  210. Base.inject({
  211. enumerable: false,
  212. toString: function() {
  213. return this._id != null
  214. ? (this._class || 'Object') + (this._name
  215. ? " '" + this._name + "'"
  216. : ' @' + this._id)
  217. : '{ ' + Base.each(this, function(value, key) {
  218. if (!/^_/.test(key)) {
  219. var type = typeof value;
  220. this.push(key + ': ' + (type === 'number'
  221. ? Formatter.instance.number(value)
  222. : type === 'string' ? "'" + value + "'" : value));
  223. }
  224. }, []).join(', ') + ' }';
  225. },
  226. getClassName: function() {
  227. return this._class || '';
  228. },
  229. importJSON: function(json) {
  230. return Base.importJSON(json, this);
  231. },
  232. exportJSON: function(options) {
  233. return Base.exportJSON(this, options);
  234. },
  235. toJSON: function() {
  236. return Base.serialize(this);
  237. },
  238. set: function(props, exclude) {
  239. if (props)
  240. Base.filter(this, props, exclude, this._prioritize);
  241. return this;
  242. }
  243. }, {
  244. beans: false,
  245. statics: {
  246. exports: {},
  247. extend: function extend() {
  248. var res = extend.base.apply(this, arguments),
  249. name = res.prototype._class;
  250. if (name && !Base.exports[name])
  251. Base.exports[name] = res;
  252. return res;
  253. },
  254. equals: function(obj1, obj2) {
  255. if (obj1 === obj2)
  256. return true;
  257. if (obj1 && obj1.equals)
  258. return obj1.equals(obj2);
  259. if (obj2 && obj2.equals)
  260. return obj2.equals(obj1);
  261. if (obj1 && obj2
  262. && typeof obj1 === 'object' && typeof obj2 === 'object') {
  263. if (Array.isArray(obj1) && Array.isArray(obj2)) {
  264. var length = obj1.length;
  265. if (length !== obj2.length)
  266. return false;
  267. while (length--) {
  268. if (!Base.equals(obj1[length], obj2[length]))
  269. return false;
  270. }
  271. } else {
  272. var keys = Object.keys(obj1),
  273. length = keys.length;
  274. if (length !== Object.keys(obj2).length)
  275. return false;
  276. while (length--) {
  277. var key = keys[length];
  278. if (!(obj2.hasOwnProperty(key)
  279. && Base.equals(obj1[key], obj2[key])))
  280. return false;
  281. }
  282. }
  283. return true;
  284. }
  285. return false;
  286. },
  287. read: function(list, start, options, amount) {
  288. if (this === Base) {
  289. var value = this.peek(list, start);
  290. list.__index++;
  291. return value;
  292. }
  293. var proto = this.prototype,
  294. readIndex = proto._readIndex,
  295. begin = start || readIndex && list.__index || 0,
  296. length = list.length,
  297. obj = list[begin];
  298. amount = amount || length - begin;
  299. if (obj instanceof this
  300. || options && options.readNull && obj == null && amount <= 1) {
  301. if (readIndex)
  302. list.__index = begin + 1;
  303. return obj && options && options.clone ? obj.clone() : obj;
  304. }
  305. obj = Base.create(proto);
  306. if (readIndex)
  307. obj.__read = true;
  308. obj = obj.initialize.apply(obj, begin > 0 || begin + amount < length
  309. ? Base.slice(list, begin, begin + amount)
  310. : list) || obj;
  311. if (readIndex) {
  312. list.__index = begin + obj.__read;
  313. var filtered = obj.__filtered;
  314. if (filtered) {
  315. list.__filtered = filtered;
  316. obj.__filtered = undefined;
  317. }
  318. obj.__read = undefined;
  319. }
  320. return obj;
  321. },
  322. peek: function(list, start) {
  323. return list[list.__index = start || list.__index || 0];
  324. },
  325. remain: function(list) {
  326. return list.length - (list.__index || 0);
  327. },
  328. readList: function(list, start, options, amount) {
  329. var res = [],
  330. entry,
  331. begin = start || 0,
  332. end = amount ? begin + amount : list.length;
  333. for (var i = begin; i < end; i++) {
  334. res.push(Array.isArray(entry = list[i])
  335. ? this.read(entry, 0, options)
  336. : this.read(list, i, options, 1));
  337. }
  338. return res;
  339. },
  340. readNamed: function(list, name, start, options, amount) {
  341. var value = this.getNamed(list, name),
  342. hasObject = value !== undefined;
  343. if (hasObject) {
  344. var filtered = list.__filtered;
  345. if (!filtered) {
  346. filtered = list.__filtered = Base.create(list[0]);
  347. filtered.__unfiltered = list[0];
  348. }
  349. filtered[name] = undefined;
  350. }
  351. var l = hasObject ? [value] : list,
  352. res = this.read(l, start, options, amount);
  353. return res;
  354. },
  355. getNamed: function(list, name) {
  356. var arg = list[0];
  357. if (list._hasObject === undefined)
  358. list._hasObject = list.length === 1 && Base.isPlainObject(arg);
  359. if (list._hasObject)
  360. return name ? arg[name] : list.__filtered || arg;
  361. },
  362. hasNamed: function(list, name) {
  363. return !!this.getNamed(list, name);
  364. },
  365. filter: function(dest, source, exclude, prioritize) {
  366. var processed;
  367. function handleKey(key) {
  368. if (!(exclude && key in exclude) &&
  369. !(processed && key in processed)) {
  370. var value = source[key];
  371. if (value !== undefined)
  372. dest[key] = value;
  373. }
  374. }
  375. if (prioritize) {
  376. var keys = {};
  377. for (var i = 0, key, l = prioritize.length; i < l; i++) {
  378. if ((key = prioritize[i]) in source) {
  379. handleKey(key);
  380. keys[key] = true;
  381. }
  382. }
  383. processed = keys;
  384. }
  385. Object.keys(source.__unfiltered || source).forEach(handleKey);
  386. return dest;
  387. },
  388. isPlainValue: function(obj, asString) {
  389. return Base.isPlainObject(obj) || Array.isArray(obj)
  390. || asString && typeof obj === 'string';
  391. },
  392. serialize: function(obj, options, compact, dictionary) {
  393. options = options || {};
  394. var isRoot = !dictionary,
  395. res;
  396. if (isRoot) {
  397. options.formatter = new Formatter(options.precision);
  398. dictionary = {
  399. length: 0,
  400. definitions: {},
  401. references: {},
  402. add: function(item, create) {
  403. var id = '#' + item._id,
  404. ref = this.references[id];
  405. if (!ref) {
  406. this.length++;
  407. var res = create.call(item),
  408. name = item._class;
  409. if (name && res[0] !== name)
  410. res.unshift(name);
  411. this.definitions[id] = res;
  412. ref = this.references[id] = [id];
  413. }
  414. return ref;
  415. }
  416. };
  417. }
  418. if (obj && obj._serialize) {
  419. res = obj._serialize(options, dictionary);
  420. var name = obj._class;
  421. if (name && !obj._compactSerialize && (isRoot || !compact)
  422. && res[0] !== name) {
  423. res.unshift(name);
  424. }
  425. } else if (Array.isArray(obj)) {
  426. res = [];
  427. for (var i = 0, l = obj.length; i < l; i++)
  428. res[i] = Base.serialize(obj[i], options, compact, dictionary);
  429. } else if (Base.isPlainObject(obj)) {
  430. res = {};
  431. var keys = Object.keys(obj);
  432. for (var i = 0, l = keys.length; i < l; i++) {
  433. var key = keys[i];
  434. res[key] = Base.serialize(obj[key], options, compact,
  435. dictionary);
  436. }
  437. } else if (typeof obj === 'number') {
  438. res = options.formatter.number(obj, options.precision);
  439. } else {
  440. res = obj;
  441. }
  442. return isRoot && dictionary.length > 0
  443. ? [['dictionary', dictionary.definitions], res]
  444. : res;
  445. },
  446. deserialize: function(json, create, _data, _setDictionary, _isRoot) {
  447. var res = json,
  448. isFirst = !_data,
  449. hasDictionary = isFirst && json && json.length
  450. && json[0][0] === 'dictionary';
  451. _data = _data || {};
  452. if (Array.isArray(json)) {
  453. var type = json[0],
  454. isDictionary = type === 'dictionary';
  455. if (json.length == 1 && /^#/.test(type)) {
  456. return _data.dictionary[type];
  457. }
  458. type = Base.exports[type];
  459. res = [];
  460. for (var i = type ? 1 : 0, l = json.length; i < l; i++) {
  461. res.push(Base.deserialize(json[i], create, _data,
  462. isDictionary, hasDictionary));
  463. }
  464. if (type) {
  465. var args = res;
  466. if (create) {
  467. res = create(type, args, isFirst || _isRoot);
  468. } else {
  469. res = new type(args);
  470. }
  471. }
  472. } else if (Base.isPlainObject(json)) {
  473. res = {};
  474. if (_setDictionary)
  475. _data.dictionary = res;
  476. for (var key in json)
  477. res[key] = Base.deserialize(json[key], create, _data);
  478. }
  479. return hasDictionary ? res[1] : res;
  480. },
  481. exportJSON: function(obj, options) {
  482. var json = Base.serialize(obj, options);
  483. return options && options.asString == false
  484. ? json
  485. : JSON.stringify(json);
  486. },
  487. importJSON: function(json, target) {
  488. return Base.deserialize(
  489. typeof json === 'string' ? JSON.parse(json) : json,
  490. function(ctor, args, isRoot) {
  491. var useTarget = isRoot && target
  492. && target.constructor === ctor,
  493. obj = useTarget ? target
  494. : Base.create(ctor.prototype);
  495. if (args.length === 1 && obj instanceof Item
  496. && (useTarget || !(obj instanceof Layer))) {
  497. var arg = args[0];
  498. if (Base.isPlainObject(arg))
  499. arg.insert = false;
  500. }
  501. (useTarget ? obj.set : ctor).apply(obj, args);
  502. if (useTarget)
  503. target = null;
  504. return obj;
  505. });
  506. },
  507. push: function(list, items) {
  508. var itemsLength = items.length;
  509. if (itemsLength < 4096) {
  510. list.push.apply(list, items);
  511. } else {
  512. var startLength = list.length;
  513. list.length += itemsLength;
  514. for (var i = 0; i < itemsLength; i++) {
  515. list[startLength + i] = items[i];
  516. }
  517. }
  518. return list;
  519. },
  520. splice: function(list, items, index, remove) {
  521. var amount = items && items.length,
  522. append = index === undefined;
  523. index = append ? list.length : index;
  524. if (index > list.length)
  525. index = list.length;
  526. for (var i = 0; i < amount; i++)
  527. items[i]._index = index + i;
  528. if (append) {
  529. Base.push(list, items);
  530. return [];
  531. } else {
  532. var args = [index, remove];
  533. if (items)
  534. Base.push(args, items);
  535. var removed = list.splice.apply(list, args);
  536. for (var i = 0, l = removed.length; i < l; i++)
  537. removed[i]._index = undefined;
  538. for (var i = index + amount, l = list.length; i < l; i++)
  539. list[i]._index = i;
  540. return removed;
  541. }
  542. },
  543. capitalize: function(str) {
  544. return str.replace(/\b[a-z]/g, function(match) {
  545. return match.toUpperCase();
  546. });
  547. },
  548. camelize: function(str) {
  549. return str.replace(/-(.)/g, function(match, chr) {
  550. return chr.toUpperCase();
  551. });
  552. },
  553. hyphenate: function(str) {
  554. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  555. }
  556. }});
  557. var Emitter = {
  558. on: function(type, func) {
  559. if (typeof type !== 'string') {
  560. Base.each(type, function(value, key) {
  561. this.on(key, value);
  562. }, this);
  563. } else {
  564. var types = this._eventTypes,
  565. entry = types && types[type],
  566. handlers = this._callbacks = this._callbacks || {};
  567. handlers = handlers[type] = handlers[type] || [];
  568. if (handlers.indexOf(func) === -1) {
  569. handlers.push(func);
  570. if (entry && entry.install && handlers.length === 1)
  571. entry.install.call(this, type);
  572. }
  573. }
  574. return this;
  575. },
  576. off: function(type, func) {
  577. if (typeof type !== 'string') {
  578. Base.each(type, function(value, key) {
  579. this.off(key, value);
  580. }, this);
  581. return;
  582. }
  583. var types = this._eventTypes,
  584. entry = types && types[type],
  585. handlers = this._callbacks && this._callbacks[type],
  586. index;
  587. if (handlers) {
  588. if (!func || (index = handlers.indexOf(func)) !== -1
  589. && handlers.length === 1) {
  590. if (entry && entry.uninstall)
  591. entry.uninstall.call(this, type);
  592. delete this._callbacks[type];
  593. } else if (index !== -1) {
  594. handlers.splice(index, 1);
  595. }
  596. }
  597. return this;
  598. },
  599. once: function(type, func) {
  600. return this.on(type, function handler() {
  601. func.apply(this, arguments);
  602. this.off(type, handler);
  603. });
  604. },
  605. emit: function(type, event) {
  606. var handlers = this._callbacks && this._callbacks[type];
  607. if (!handlers)
  608. return false;
  609. var args = Base.slice(arguments, 1),
  610. setTarget = event && event.target && !event.currentTarget;
  611. handlers = handlers.slice();
  612. if (setTarget)
  613. event.currentTarget = this;
  614. for (var i = 0, l = handlers.length; i < l; i++) {
  615. if (handlers[i].apply(this, args) == false) {
  616. if (event && event.stop)
  617. event.stop();
  618. break;
  619. }
  620. }
  621. if (setTarget)
  622. delete event.currentTarget;
  623. return true;
  624. },
  625. responds: function(type) {
  626. return !!(this._callbacks && this._callbacks[type]);
  627. },
  628. attach: '#on',
  629. detach: '#off',
  630. fire: '#emit',
  631. _installEvents: function(install) {
  632. var types = this._eventTypes,
  633. handlers = this._callbacks,
  634. key = install ? 'install' : 'uninstall';
  635. if (types) {
  636. for (var type in handlers) {
  637. if (handlers[type].length > 0) {
  638. var entry = types[type],
  639. func = entry && entry[key];
  640. if (func)
  641. func.call(this, type);
  642. }
  643. }
  644. }
  645. },
  646. statics: {
  647. inject: function inject(src) {
  648. var events = src._events;
  649. if (events) {
  650. var types = {};
  651. Base.each(events, function(entry, key) {
  652. var isString = typeof entry === 'string',
  653. name = isString ? entry : key,
  654. part = Base.capitalize(name),
  655. type = name.substring(2).toLowerCase();
  656. types[type] = isString ? {} : entry;
  657. name = '_' + name;
  658. src['get' + part] = function() {
  659. return this[name];
  660. };
  661. src['set' + part] = function(func) {
  662. var prev = this[name];
  663. if (prev)
  664. this.off(type, prev);
  665. if (func)
  666. this.on(type, func);
  667. this[name] = func;
  668. };
  669. });
  670. src._eventTypes = types;
  671. }
  672. return inject.base.apply(this, arguments);
  673. }
  674. }
  675. };
  676. var PaperScope = Base.extend({
  677. _class: 'PaperScope',
  678. initialize: function PaperScope() {
  679. paper = this;
  680. this.settings = new Base({
  681. applyMatrix: true,
  682. insertItems: true,
  683. handleSize: 4,
  684. hitTolerance: 0
  685. });
  686. this.project = null;
  687. this.projects = [];
  688. this.tools = [];
  689. this._id = PaperScope._id++;
  690. PaperScope._scopes[this._id] = this;
  691. var proto = PaperScope.prototype;
  692. if (!this.support) {
  693. var ctx = CanvasProvider.getContext(1, 1) || {};
  694. proto.support = {
  695. nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx,
  696. nativeBlendModes: BlendMode.nativeModes
  697. };
  698. CanvasProvider.release(ctx);
  699. }
  700. if (!this.agent) {
  701. var user = self.navigator.userAgent.toLowerCase(),
  702. os = (/(darwin|win|mac|linux|freebsd|sunos)/.exec(user)||[])[0],
  703. platform = os === 'darwin' ? 'mac' : os,
  704. agent = proto.agent = proto.browser = { platform: platform };
  705. if (platform)
  706. agent[platform] = true;
  707. user.replace(
  708. /(opera|chrome|safari|webkit|firefox|msie|trident|atom|node)\/?\s*([.\d]+)(?:.*version\/([.\d]+))?(?:.*rv\:v?([.\d]+))?/g,
  709. function(match, n, v1, v2, rv) {
  710. if (!agent.chrome) {
  711. var v = n === 'opera' ? v2 :
  712. /^(node|trident)$/.test(n) ? rv : v1;
  713. agent.version = v;
  714. agent.versionNumber = parseFloat(v);
  715. n = n === 'trident' ? 'msie' : n;
  716. agent.name = n;
  717. agent[n] = true;
  718. }
  719. }
  720. );
  721. if (agent.chrome)
  722. delete agent.webkit;
  723. if (agent.atom)
  724. delete agent.chrome;
  725. }
  726. },
  727. version: "0.12.0",
  728. getView: function() {
  729. var project = this.project;
  730. return project && project._view;
  731. },
  732. getPaper: function() {
  733. return this;
  734. },
  735. execute: function(code, options) {
  736. var exports = paper.PaperScript.execute(code, this, options);
  737. View.updateFocus();
  738. return exports;
  739. },
  740. install: function(scope) {
  741. var that = this;
  742. Base.each(['project', 'view', 'tool'], function(key) {
  743. Base.define(scope, key, {
  744. configurable: true,
  745. get: function() {
  746. return that[key];
  747. }
  748. });
  749. });
  750. for (var key in this)
  751. if (!/^_/.test(key) && this[key])
  752. scope[key] = this[key];
  753. },
  754. setup: function(element) {
  755. paper = this;
  756. this.project = new Project(element);
  757. return this;
  758. },
  759. createCanvas: function(width, height) {
  760. return CanvasProvider.getCanvas(width, height);
  761. },
  762. activate: function() {
  763. paper = this;
  764. },
  765. clear: function() {
  766. var projects = this.projects,
  767. tools = this.tools;
  768. for (var i = projects.length - 1; i >= 0; i--)
  769. projects[i].remove();
  770. for (var i = tools.length - 1; i >= 0; i--)
  771. tools[i].remove();
  772. },
  773. remove: function() {
  774. this.clear();
  775. delete PaperScope._scopes[this._id];
  776. },
  777. statics: new function() {
  778. function handleAttribute(name) {
  779. name += 'Attribute';
  780. return function(el, attr) {
  781. return el[name](attr) || el[name]('data-paper-' + attr);
  782. };
  783. }
  784. return {
  785. _scopes: {},
  786. _id: 0,
  787. get: function(id) {
  788. return this._scopes[id] || null;
  789. },
  790. getAttribute: handleAttribute('get'),
  791. hasAttribute: handleAttribute('has')
  792. };
  793. }
  794. });
  795. var PaperScopeItem = Base.extend(Emitter, {
  796. initialize: function(activate) {
  797. this._scope = paper;
  798. this._index = this._scope[this._list].push(this) - 1;
  799. if (activate || !this._scope[this._reference])
  800. this.activate();
  801. },
  802. activate: function() {
  803. if (!this._scope)
  804. return false;
  805. var prev = this._scope[this._reference];
  806. if (prev && prev !== this)
  807. prev.emit('deactivate');
  808. this._scope[this._reference] = this;
  809. this.emit('activate', prev);
  810. return true;
  811. },
  812. isActive: function() {
  813. return this._scope[this._reference] === this;
  814. },
  815. remove: function() {
  816. if (this._index == null)
  817. return false;
  818. Base.splice(this._scope[this._list], null, this._index, 1);
  819. if (this._scope[this._reference] == this)
  820. this._scope[this._reference] = null;
  821. this._scope = null;
  822. return true;
  823. },
  824. getView: function() {
  825. return this._scope.getView();
  826. }
  827. });
  828. var Formatter = Base.extend({
  829. initialize: function(precision) {
  830. this.precision = Base.pick(precision, 5);
  831. this.multiplier = Math.pow(10, this.precision);
  832. },
  833. number: function(val) {
  834. return this.precision < 16
  835. ? Math.round(val * this.multiplier) / this.multiplier : val;
  836. },
  837. pair: function(val1, val2, separator) {
  838. return this.number(val1) + (separator || ',') + this.number(val2);
  839. },
  840. point: function(val, separator) {
  841. return this.number(val.x) + (separator || ',') + this.number(val.y);
  842. },
  843. size: function(val, separator) {
  844. return this.number(val.width) + (separator || ',')
  845. + this.number(val.height);
  846. },
  847. rectangle: function(val, separator) {
  848. return this.point(val, separator) + (separator || ',')
  849. + this.size(val, separator);
  850. }
  851. });
  852. Formatter.instance = new Formatter();
  853. var Numerical = new function() {
  854. var abscissas = [
  855. [ 0.5773502691896257645091488],
  856. [0,0.7745966692414833770358531],
  857. [ 0.3399810435848562648026658,0.8611363115940525752239465],
  858. [0,0.5384693101056830910363144,0.9061798459386639927976269],
  859. [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
  860. [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
  861. [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
  862. [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
  863. [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
  864. [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
  865. [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
  866. [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
  867. [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
  868. [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
  869. [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
  870. ];
  871. var weights = [
  872. [1],
  873. [0.8888888888888888888888889,0.5555555555555555555555556],
  874. [0.6521451548625461426269361,0.3478548451374538573730639],
  875. [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
  876. [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
  877. [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
  878. [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
  879. [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
  880. [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
  881. [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
  882. [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
  883. [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
  884. [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
  885. [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
  886. [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
  887. ];
  888. var abs = Math.abs,
  889. sqrt = Math.sqrt,
  890. pow = Math.pow,
  891. log2 = Math.log2 || function(x) {
  892. return Math.log(x) * Math.LOG2E;
  893. },
  894. EPSILON = 1e-12,
  895. MACHINE_EPSILON = 1.12e-16;
  896. function clamp(value, min, max) {
  897. return value < min ? min : value > max ? max : value;
  898. }
  899. function getDiscriminant(a, b, c) {
  900. function split(v) {
  901. var x = v * 134217729,
  902. y = v - x,
  903. hi = y + x,
  904. lo = v - hi;
  905. return [hi, lo];
  906. }
  907. var D = b * b - a * c,
  908. E = b * b + a * c;
  909. if (abs(D) * 3 < E) {
  910. var ad = split(a),
  911. bd = split(b),
  912. cd = split(c),
  913. p = b * b,
  914. dp = (bd[0] * bd[0] - p + 2 * bd[0] * bd[1]) + bd[1] * bd[1],
  915. q = a * c,
  916. dq = (ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0])
  917. + ad[1] * cd[1];
  918. D = (p - q) + (dp - dq);
  919. }
  920. return D;
  921. }
  922. function getNormalizationFactor() {
  923. var norm = Math.max.apply(Math, arguments);
  924. return norm && (norm < 1e-8 || norm > 1e8)
  925. ? pow(2, -Math.round(log2(norm)))
  926. : 0;
  927. }
  928. return {
  929. EPSILON: EPSILON,
  930. MACHINE_EPSILON: MACHINE_EPSILON,
  931. CURVETIME_EPSILON: 1e-8,
  932. GEOMETRIC_EPSILON: 1e-7,
  933. TRIGONOMETRIC_EPSILON: 1e-8,
  934. KAPPA: 4 * (sqrt(2) - 1) / 3,
  935. isZero: function(val) {
  936. return val >= -EPSILON && val <= EPSILON;
  937. },
  938. clamp: clamp,
  939. integrate: function(f, a, b, n) {
  940. var x = abscissas[n - 2],
  941. w = weights[n - 2],
  942. A = (b - a) * 0.5,
  943. B = A + a,
  944. i = 0,
  945. m = (n + 1) >> 1,
  946. sum = n & 1 ? w[i++] * f(B) : 0;
  947. while (i < m) {
  948. var Ax = A * x[i];
  949. sum += w[i++] * (f(B + Ax) + f(B - Ax));
  950. }
  951. return A * sum;
  952. },
  953. findRoot: function(f, df, x, a, b, n, tolerance) {
  954. for (var i = 0; i < n; i++) {
  955. var fx = f(x),
  956. dx = fx / df(x),
  957. nx = x - dx;
  958. if (abs(dx) < tolerance) {
  959. x = nx;
  960. break;
  961. }
  962. if (fx > 0) {
  963. b = x;
  964. x = nx <= a ? (a + b) * 0.5 : nx;
  965. } else {
  966. a = x;
  967. x = nx >= b ? (a + b) * 0.5 : nx;
  968. }
  969. }
  970. return clamp(x, a, b);
  971. },
  972. solveQuadratic: function(a, b, c, roots, min, max) {
  973. var x1, x2 = Infinity;
  974. if (abs(a) < EPSILON) {
  975. if (abs(b) < EPSILON)
  976. return abs(c) < EPSILON ? -1 : 0;
  977. x1 = -c / b;
  978. } else {
  979. b *= -0.5;
  980. var D = getDiscriminant(a, b, c);
  981. if (D && abs(D) < MACHINE_EPSILON) {
  982. var f = getNormalizationFactor(abs(a), abs(b), abs(c));
  983. if (f) {
  984. a *= f;
  985. b *= f;
  986. c *= f;
  987. D = getDiscriminant(a, b, c);
  988. }
  989. }
  990. if (D >= -MACHINE_EPSILON) {
  991. var Q = D < 0 ? 0 : sqrt(D),
  992. R = b + (b < 0 ? -Q : Q);
  993. if (R === 0) {
  994. x1 = c / a;
  995. x2 = -x1;
  996. } else {
  997. x1 = R / a;
  998. x2 = c / R;
  999. }
  1000. }
  1001. }
  1002. var count = 0,
  1003. boundless = min == null,
  1004. minB = min - EPSILON,
  1005. maxB = max + EPSILON;
  1006. if (isFinite(x1) && (boundless || x1 > minB && x1 < maxB))
  1007. roots[count++] = boundless ? x1 : clamp(x1, min, max);
  1008. if (x2 !== x1
  1009. && isFinite(x2) && (boundless || x2 > minB && x2 < maxB))
  1010. roots[count++] = boundless ? x2 : clamp(x2, min, max);
  1011. return count;
  1012. },
  1013. solveCubic: function(a, b, c, d, roots, min, max) {
  1014. var f = getNormalizationFactor(abs(a), abs(b), abs(c), abs(d)),
  1015. x, b1, c2, qd, q;
  1016. if (f) {
  1017. a *= f;
  1018. b *= f;
  1019. c *= f;
  1020. d *= f;
  1021. }
  1022. function evaluate(x0) {
  1023. x = x0;
  1024. var tmp = a * x;
  1025. b1 = tmp + b;
  1026. c2 = b1 * x + c;
  1027. qd = (tmp + b1) * x + c2;
  1028. q = c2 * x + d;
  1029. }
  1030. if (abs(a) < EPSILON) {
  1031. a = b;
  1032. b1 = c;
  1033. c2 = d;
  1034. x = Infinity;
  1035. } else if (abs(d) < EPSILON) {
  1036. b1 = b;
  1037. c2 = c;
  1038. x = 0;
  1039. } else {
  1040. evaluate(-(b / a) / 3);
  1041. var t = q / a,
  1042. r = pow(abs(t), 1/3),
  1043. s = t < 0 ? -1 : 1,
  1044. td = -qd / a,
  1045. rd = td > 0 ? 1.324717957244746 * Math.max(r, sqrt(td)) : r,
  1046. x0 = x - s * rd;
  1047. if (x0 !== x) {
  1048. do {
  1049. evaluate(x0);
  1050. x0 = qd === 0 ? x : x - q / qd / (1 + MACHINE_EPSILON);
  1051. } while (s * x0 > s * x);
  1052. if (abs(a) * x * x > abs(d / x)) {
  1053. c2 = -d / x;
  1054. b1 = (c2 - c) / x;
  1055. }
  1056. }
  1057. }
  1058. var count = Numerical.solveQuadratic(a, b1, c2, roots, min, max),
  1059. boundless = min == null;
  1060. if (isFinite(x) && (count === 0
  1061. || count > 0 && x !== roots[0] && x !== roots[1])
  1062. && (boundless || x > min - EPSILON && x < max + EPSILON))
  1063. roots[count++] = boundless ? x : clamp(x, min, max);
  1064. return count;
  1065. }
  1066. };
  1067. };
  1068. var UID = {
  1069. _id: 1,
  1070. _pools: {},
  1071. get: function(name) {
  1072. if (name) {
  1073. var pool = this._pools[name];
  1074. if (!pool)
  1075. pool = this._pools[name] = { _id: 1 };
  1076. return pool._id++;
  1077. } else {
  1078. return this._id++;
  1079. }
  1080. }
  1081. };
  1082. var Point = Base.extend({
  1083. _class: 'Point',
  1084. _readIndex: true,
  1085. initialize: function Point(arg0, arg1) {
  1086. var type = typeof arg0,
  1087. reading = this.__read,
  1088. read = 0;
  1089. if (type === 'number') {
  1090. var hasY = typeof arg1 === 'number';
  1091. this._set(arg0, hasY ? arg1 : arg0);
  1092. if (reading)
  1093. read = hasY ? 2 : 1;
  1094. } else if (type === 'undefined' || arg0 === null) {
  1095. this._set(0, 0);
  1096. if (reading)
  1097. read = arg0 === null ? 1 : 0;
  1098. } else {
  1099. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1100. read = 1;
  1101. if (Array.isArray(obj)) {
  1102. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1103. } else if ('x' in obj) {
  1104. this._set(obj.x || 0, obj.y || 0);
  1105. } else if ('width' in obj) {
  1106. this._set(obj.width || 0, obj.height || 0);
  1107. } else if ('angle' in obj) {
  1108. this._set(obj.length || 0, 0);
  1109. this.setAngle(obj.angle || 0);
  1110. } else {
  1111. this._set(0, 0);
  1112. read = 0;
  1113. }
  1114. }
  1115. if (reading)
  1116. this.__read = read;
  1117. return this;
  1118. },
  1119. set: '#initialize',
  1120. _set: function(x, y) {
  1121. this.x = x;
  1122. this.y = y;
  1123. return this;
  1124. },
  1125. equals: function(point) {
  1126. return this === point || point
  1127. && (this.x === point.x && this.y === point.y
  1128. || Array.isArray(point)
  1129. && this.x === point[0] && this.y === point[1])
  1130. || false;
  1131. },
  1132. clone: function() {
  1133. return new Point(this.x, this.y);
  1134. },
  1135. toString: function() {
  1136. var f = Formatter.instance;
  1137. return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
  1138. },
  1139. _serialize: function(options) {
  1140. var f = options.formatter;
  1141. return [f.number(this.x), f.number(this.y)];
  1142. },
  1143. getLength: function() {
  1144. return Math.sqrt(this.x * this.x + this.y * this.y);
  1145. },
  1146. setLength: function(length) {
  1147. if (this.isZero()) {
  1148. var angle = this._angle || 0;
  1149. this._set(
  1150. Math.cos(angle) * length,
  1151. Math.sin(angle) * length
  1152. );
  1153. } else {
  1154. var scale = length / this.getLength();
  1155. if (Numerical.isZero(scale))
  1156. this.getAngle();
  1157. this._set(
  1158. this.x * scale,
  1159. this.y * scale
  1160. );
  1161. }
  1162. },
  1163. getAngle: function() {
  1164. return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI;
  1165. },
  1166. setAngle: function(angle) {
  1167. this.setAngleInRadians.call(this, angle * Math.PI / 180);
  1168. },
  1169. getAngleInDegrees: '#getAngle',
  1170. setAngleInDegrees: '#setAngle',
  1171. getAngleInRadians: function() {
  1172. if (!arguments.length) {
  1173. return this.isZero()
  1174. ? this._angle || 0
  1175. : this._angle = Math.atan2(this.y, this.x);
  1176. } else {
  1177. var point = Point.read(arguments),
  1178. div = this.getLength() * point.getLength();
  1179. if (Numerical.isZero(div)) {
  1180. return NaN;
  1181. } else {
  1182. var a = this.dot(point) / div;
  1183. return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a);
  1184. }
  1185. }
  1186. },
  1187. setAngleInRadians: function(angle) {
  1188. this._angle = angle;
  1189. if (!this.isZero()) {
  1190. var length = this.getLength();
  1191. this._set(
  1192. Math.cos(angle) * length,
  1193. Math.sin(angle) * length
  1194. );
  1195. }
  1196. },
  1197. getQuadrant: function() {
  1198. return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
  1199. }
  1200. }, {
  1201. beans: false,
  1202. getDirectedAngle: function() {
  1203. var point = Point.read(arguments);
  1204. return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
  1205. },
  1206. getDistance: function() {
  1207. var point = Point.read(arguments),
  1208. x = point.x - this.x,
  1209. y = point.y - this.y,
  1210. d = x * x + y * y,
  1211. squared = Base.read(arguments);
  1212. return squared ? d : Math.sqrt(d);
  1213. },
  1214. normalize: function(length) {
  1215. if (length === undefined)
  1216. length = 1;
  1217. var current = this.getLength(),
  1218. scale = current !== 0 ? length / current : 0,
  1219. point = new Point(this.x * scale, this.y * scale);
  1220. if (scale >= 0)
  1221. point._angle = this._angle;
  1222. return point;
  1223. },
  1224. rotate: function(angle, center) {
  1225. if (angle === 0)
  1226. return this.clone();
  1227. angle = angle * Math.PI / 180;
  1228. var point = center ? this.subtract(center) : this,
  1229. sin = Math.sin(angle),
  1230. cos = Math.cos(angle);
  1231. point = new Point(
  1232. point.x * cos - point.y * sin,
  1233. point.x * sin + point.y * cos
  1234. );
  1235. return center ? point.add(center) : point;
  1236. },
  1237. transform: function(matrix) {
  1238. return matrix ? matrix._transformPoint(this) : this;
  1239. },
  1240. add: function() {
  1241. var point = Point.read(arguments);
  1242. return new Point(this.x + point.x, this.y + point.y);
  1243. },
  1244. subtract: function() {
  1245. var point = Point.read(arguments);
  1246. return new Point(this.x - point.x, this.y - point.y);
  1247. },
  1248. multiply: function() {
  1249. var point = Point.read(arguments);
  1250. return new Point(this.x * point.x, this.y * point.y);
  1251. },
  1252. divide: function() {
  1253. var point = Point.read(arguments);
  1254. return new Point(this.x / point.x, this.y / point.y);
  1255. },
  1256. modulo: function() {
  1257. var point = Point.read(arguments);
  1258. return new Point(this.x % point.x, this.y % point.y);
  1259. },
  1260. negate: function() {
  1261. return new Point(-this.x, -this.y);
  1262. },
  1263. isInside: function() {
  1264. return Rectangle.read(arguments).contains(this);
  1265. },
  1266. isClose: function() {
  1267. var point = Point.read(arguments),
  1268. tolerance = Base.read(arguments);
  1269. return this.getDistance(point) <= tolerance;
  1270. },
  1271. isCollinear: function() {
  1272. var point = Point.read(arguments);
  1273. return Point.isCollinear(this.x, this.y, point.x, point.y);
  1274. },
  1275. isColinear: '#isCollinear',
  1276. isOrthogonal: function() {
  1277. var point = Point.read(arguments);
  1278. return Point.isOrthogonal(this.x, this.y, point.x, point.y);
  1279. },
  1280. isZero: function() {
  1281. var isZero = Numerical.isZero;
  1282. return isZero(this.x) && isZero(this.y);
  1283. },
  1284. isNaN: function() {
  1285. return isNaN(this.x) || isNaN(this.y);
  1286. },
  1287. isInQuadrant: function(q) {
  1288. return this.x * (q > 1 && q < 4 ? -1 : 1) >= 0
  1289. && this.y * (q > 2 ? -1 : 1) >= 0;
  1290. },
  1291. dot: function() {
  1292. var point = Point.read(arguments);
  1293. return this.x * point.x + this.y * point.y;
  1294. },
  1295. cross: function() {
  1296. var point = Point.read(arguments);
  1297. return this.x * point.y - this.y * point.x;
  1298. },
  1299. project: function() {
  1300. var point = Point.read(arguments),
  1301. scale = point.isZero() ? 0 : this.dot(point) / point.dot(point);
  1302. return new Point(
  1303. point.x * scale,
  1304. point.y * scale
  1305. );
  1306. },
  1307. statics: {
  1308. min: function() {
  1309. var point1 = Point.read(arguments),
  1310. point2 = Point.read(arguments);
  1311. return new Point(
  1312. Math.min(point1.x, point2.x),
  1313. Math.min(point1.y, point2.y)
  1314. );
  1315. },
  1316. max: function() {
  1317. var point1 = Point.read(arguments),
  1318. point2 = Point.read(arguments);
  1319. return new Point(
  1320. Math.max(point1.x, point2.x),
  1321. Math.max(point1.y, point2.y)
  1322. );
  1323. },
  1324. random: function() {
  1325. return new Point(Math.random(), Math.random());
  1326. },
  1327. isCollinear: function(x1, y1, x2, y2) {
  1328. return Math.abs(x1 * y2 - y1 * x2)
  1329. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1330. * 1e-8;
  1331. },
  1332. isOrthogonal: function(x1, y1, x2, y2) {
  1333. return Math.abs(x1 * x2 + y1 * y2)
  1334. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1335. * 1e-8;
  1336. }
  1337. }
  1338. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1339. var op = Math[key];
  1340. this[key] = function() {
  1341. return new Point(op(this.x), op(this.y));
  1342. };
  1343. }, {}));
  1344. var LinkedPoint = Point.extend({
  1345. initialize: function Point(x, y, owner, setter) {
  1346. this._x = x;
  1347. this._y = y;
  1348. this._owner = owner;
  1349. this._setter = setter;
  1350. },
  1351. _set: function(x, y, _dontNotify) {
  1352. this._x = x;
  1353. this._y = y;
  1354. if (!_dontNotify)
  1355. this._owner[this._setter](this);
  1356. return this;
  1357. },
  1358. getX: function() {
  1359. return this._x;
  1360. },
  1361. setX: function(x) {
  1362. this._x = x;
  1363. this._owner[this._setter](this);
  1364. },
  1365. getY: function() {
  1366. return this._y;
  1367. },
  1368. setY: function(y) {
  1369. this._y = y;
  1370. this._owner[this._setter](this);
  1371. },
  1372. isSelected: function() {
  1373. return !!(this._owner._selection & this._getSelection());
  1374. },
  1375. setSelected: function(selected) {
  1376. this._owner._changeSelection(this._getSelection(), selected);
  1377. },
  1378. _getSelection: function() {
  1379. return this._setter === 'setPosition' ? 4 : 0;
  1380. }
  1381. });
  1382. var Size = Base.extend({
  1383. _class: 'Size',
  1384. _readIndex: true,
  1385. initialize: function Size(arg0, arg1) {
  1386. var type = typeof arg0,
  1387. reading = this.__read,
  1388. read = 0;
  1389. if (type === 'number') {
  1390. var hasHeight = typeof arg1 === 'number';
  1391. this._set(arg0, hasHeight ? arg1 : arg0);
  1392. if (reading)
  1393. read = hasHeight ? 2 : 1;
  1394. } else if (type === 'undefined' || arg0 === null) {
  1395. this._set(0, 0);
  1396. if (reading)
  1397. read = arg0 === null ? 1 : 0;
  1398. } else {
  1399. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1400. read = 1;
  1401. if (Array.isArray(obj)) {
  1402. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1403. } else if ('width' in obj) {
  1404. this._set(obj.width || 0, obj.height || 0);
  1405. } else if ('x' in obj) {
  1406. this._set(obj.x || 0, obj.y || 0);
  1407. } else {
  1408. this._set(0, 0);
  1409. read = 0;
  1410. }
  1411. }
  1412. if (reading)
  1413. this.__read = read;
  1414. return this;
  1415. },
  1416. set: '#initialize',
  1417. _set: function(width, height) {
  1418. this.width = width;
  1419. this.height = height;
  1420. return this;
  1421. },
  1422. equals: function(size) {
  1423. return size === this || size && (this.width === size.width
  1424. && this.height === size.height
  1425. || Array.isArray(size) && this.width === size[0]
  1426. && this.height === size[1]) || false;
  1427. },
  1428. clone: function() {
  1429. return new Size(this.width, this.height);
  1430. },
  1431. toString: function() {
  1432. var f = Formatter.instance;
  1433. return '{ width: ' + f.number(this.width)
  1434. + ', height: ' + f.number(this.height) + ' }';
  1435. },
  1436. _serialize: function(options) {
  1437. var f = options.formatter;
  1438. return [f.number(this.width),
  1439. f.number(this.height)];
  1440. },
  1441. add: function() {
  1442. var size = Size.read(arguments);
  1443. return new Size(this.width + size.width, this.height + size.height);
  1444. },
  1445. subtract: function() {
  1446. var size = Size.read(arguments);
  1447. return new Size(this.width - size.width, this.height - size.height);
  1448. },
  1449. multiply: function() {
  1450. var size = Size.read(arguments);
  1451. return new Size(this.width * size.width, this.height * size.height);
  1452. },
  1453. divide: function() {
  1454. var size = Size.read(arguments);
  1455. return new Size(this.width / size.width, this.height / size.height);
  1456. },
  1457. modulo: function() {
  1458. var size = Size.read(arguments);
  1459. return new Size(this.width % size.width, this.height % size.height);
  1460. },
  1461. negate: function() {
  1462. return new Size(-this.width, -this.height);
  1463. },
  1464. isZero: function() {
  1465. var isZero = Numerical.isZero;
  1466. return isZero(this.width) && isZero(this.height);
  1467. },
  1468. isNaN: function() {
  1469. return isNaN(this.width) || isNaN(this.height);
  1470. },
  1471. statics: {
  1472. min: function(size1, size2) {
  1473. return new Size(
  1474. Math.min(size1.width, size2.width),
  1475. Math.min(size1.height, size2.height));
  1476. },
  1477. max: function(size1, size2) {
  1478. return new Size(
  1479. Math.max(size1.width, size2.width),
  1480. Math.max(size1.height, size2.height));
  1481. },
  1482. random: function() {
  1483. return new Size(Math.random(), Math.random());
  1484. }
  1485. }
  1486. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1487. var op = Math[key];
  1488. this[key] = function() {
  1489. return new Size(op(this.width), op(this.height));
  1490. };
  1491. }, {}));
  1492. var LinkedSize = Size.extend({
  1493. initialize: function Size(width, height, owner, setter) {
  1494. this._width = width;
  1495. this._height = height;
  1496. this._owner = owner;
  1497. this._setter = setter;
  1498. },
  1499. _set: function(width, height, _dontNotify) {
  1500. this._width = width;
  1501. this._height = height;
  1502. if (!_dontNotify)
  1503. this._owner[this._setter](this);
  1504. return this;
  1505. },
  1506. getWidth: function() {
  1507. return this._width;
  1508. },
  1509. setWidth: function(width) {
  1510. this._width = width;
  1511. this._owner[this._setter](this);
  1512. },
  1513. getHeight: function() {
  1514. return this._height;
  1515. },
  1516. setHeight: function(height) {
  1517. this._height = height;
  1518. this._owner[this._setter](this);
  1519. }
  1520. });
  1521. var Rectangle = Base.extend({
  1522. _class: 'Rectangle',
  1523. _readIndex: true,
  1524. beans: true,
  1525. initialize: function Rectangle(arg0, arg1, arg2, arg3) {
  1526. var type = typeof arg0,
  1527. read;
  1528. if (type === 'number') {
  1529. this._set(arg0, arg1, arg2, arg3);
  1530. read = 4;
  1531. } else if (type === 'undefined' || arg0 === null) {
  1532. this._set(0, 0, 0, 0);
  1533. read = arg0 === null ? 1 : 0;
  1534. } else if (arguments.length === 1) {
  1535. if (Array.isArray(arg0)) {
  1536. this._set.apply(this, arg0);
  1537. read = 1;
  1538. } else if (arg0.x !== undefined || arg0.width !== undefined) {
  1539. this._set(arg0.x || 0, arg0.y || 0,
  1540. arg0.width || 0, arg0.height || 0);
  1541. read = 1;
  1542. } else if (arg0.from === undefined && arg0.to === undefined) {
  1543. this._set(0, 0, 0, 0);
  1544. Base.filter(this, arg0);
  1545. read = 1;
  1546. }
  1547. }
  1548. if (read === undefined) {
  1549. var frm = Point.readNamed(arguments, 'from'),
  1550. next = Base.peek(arguments),
  1551. x = frm.x,
  1552. y = frm.y,
  1553. width,
  1554. height;
  1555. if (next && next.x !== undefined
  1556. || Base.hasNamed(arguments, 'to')) {
  1557. var to = Point.readNamed(arguments, 'to');
  1558. width = to.x - x;
  1559. height = to.y - y;
  1560. if (width < 0) {
  1561. x = to.x;
  1562. width = -width;
  1563. }
  1564. if (height < 0) {
  1565. y = to.y;
  1566. height = -height;
  1567. }
  1568. } else {
  1569. var size = Size.read(arguments);
  1570. width = size.width;
  1571. height = size.height;
  1572. }
  1573. this._set(x, y, width, height);
  1574. read = arguments.__index;
  1575. var filtered = arguments.__filtered;
  1576. if (filtered)
  1577. this.__filtered = filtered;
  1578. }
  1579. if (this.__read)
  1580. this.__read = read;
  1581. return this;
  1582. },
  1583. set: '#initialize',
  1584. _set: function(x, y, width, height) {
  1585. this.x = x;
  1586. this.y = y;
  1587. this.width = width;
  1588. this.height = height;
  1589. return this;
  1590. },
  1591. clone: function() {
  1592. return new Rectangle(this.x, this.y, this.width, this.height);
  1593. },
  1594. equals: function(rect) {
  1595. var rt = Base.isPlainValue(rect)
  1596. ? Rectangle.read(arguments)
  1597. : rect;
  1598. return rt === this
  1599. || rt && this.x === rt.x && this.y === rt.y
  1600. && this.width === rt.width && this.height === rt.height
  1601. || false;
  1602. },
  1603. toString: function() {
  1604. var f = Formatter.instance;
  1605. return '{ x: ' + f.number(this.x)
  1606. + ', y: ' + f.number(this.y)
  1607. + ', width: ' + f.number(this.width)
  1608. + ', height: ' + f.number(this.height)
  1609. + ' }';
  1610. },
  1611. _serialize: function(options) {
  1612. var f = options.formatter;
  1613. return [f.number(this.x),
  1614. f.number(this.y),
  1615. f.number(this.width),
  1616. f.number(this.height)];
  1617. },
  1618. getPoint: function(_dontLink) {
  1619. var ctor = _dontLink ? Point : LinkedPoint;
  1620. return new ctor(this.x, this.y, this, 'setPoint');
  1621. },
  1622. setPoint: function() {
  1623. var point = Point.read(arguments);
  1624. this.x = point.x;
  1625. this.y = point.y;
  1626. },
  1627. getSize: function(_dontLink) {
  1628. var ctor = _dontLink ? Size : LinkedSize;
  1629. return new ctor(this.width, this.height, this, 'setSize');
  1630. },
  1631. _fw: 1,
  1632. _fh: 1,
  1633. setSize: function() {
  1634. var size = Size.read(arguments),
  1635. sx = this._sx,
  1636. sy = this._sy,
  1637. w = size.width,
  1638. h = size.height;
  1639. if (sx) {
  1640. this.x += (this.width - w) * sx;
  1641. }
  1642. if (sy) {
  1643. this.y += (this.height - h) * sy;
  1644. }
  1645. this.width = w;
  1646. this.height = h;
  1647. this._fw = this._fh = 1;
  1648. },
  1649. getLeft: function() {
  1650. return this.x;
  1651. },
  1652. setLeft: function(left) {
  1653. if (!this._fw) {
  1654. var amount = left - this.x;
  1655. this.width -= this._sx === 0.5 ? amount * 2 : amount;
  1656. }
  1657. this.x = left;
  1658. this._sx = this._fw = 0;
  1659. },
  1660. getTop: function() {
  1661. return this.y;
  1662. },
  1663. setTop: function(top) {
  1664. if (!this._fh) {
  1665. var amount = top - this.y;
  1666. this.height -= this._sy === 0.5 ? amount * 2 : amount;
  1667. }
  1668. this.y = top;
  1669. this._sy = this._fh = 0;
  1670. },
  1671. getRight: function() {
  1672. return this.x + this.width;
  1673. },
  1674. setRight: function(right) {
  1675. if (!this._fw) {
  1676. var amount = right - this.x;
  1677. this.width = this._sx === 0.5 ? amount * 2 : amount;
  1678. }
  1679. this.x = right - this.width;
  1680. this._sx = 1;
  1681. this._fw = 0;
  1682. },
  1683. getBottom: function() {
  1684. return this.y + this.height;
  1685. },
  1686. setBottom: function(bottom) {
  1687. if (!this._fh) {
  1688. var amount = bottom - this.y;
  1689. this.height = this._sy === 0.5 ? amount * 2 : amount;
  1690. }
  1691. this.y = bottom - this.height;
  1692. this._sy = 1;
  1693. this._fh = 0;
  1694. },
  1695. getCenterX: function() {
  1696. return this.x + this.width / 2;
  1697. },
  1698. setCenterX: function(x) {
  1699. if (this._fw || this._sx === 0.5) {
  1700. this.x = x - this.width / 2;
  1701. } else {
  1702. if (this._sx) {
  1703. this.x += (x - this.x) * 2 * this._sx;
  1704. }
  1705. this.width = (x - this.x) * 2;
  1706. }
  1707. this._sx = 0.5;
  1708. this._fw = 0;
  1709. },
  1710. getCenterY: function() {
  1711. return this.y + this.height / 2;
  1712. },
  1713. setCenterY: function(y) {
  1714. if (this._fh || this._sy === 0.5) {
  1715. this.y = y - this.height / 2;
  1716. } else {
  1717. if (this._sy) {
  1718. this.y += (y - this.y) * 2 * this._sy;
  1719. }
  1720. this.height = (y - this.y) * 2;
  1721. }
  1722. this._sy = 0.5;
  1723. this._fh = 0;
  1724. },
  1725. getCenter: function(_dontLink) {
  1726. var ctor = _dontLink ? Point : LinkedPoint;
  1727. return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter');
  1728. },
  1729. setCenter: function() {
  1730. var point = Point.read(arguments);
  1731. this.setCenterX(point.x);
  1732. this.setCenterY(point.y);
  1733. return this;
  1734. },
  1735. getArea: function() {
  1736. return this.width * this.height;
  1737. },
  1738. isEmpty: function() {
  1739. return this.width === 0 || this.height === 0;
  1740. },
  1741. contains: function(arg) {
  1742. return arg && arg.width !== undefined
  1743. || (Array.isArray(arg) ? arg : arguments).length === 4
  1744. ? this._containsRectangle(Rectangle.read(arguments))
  1745. : this._containsPoint(Point.read(arguments));
  1746. },
  1747. _containsPoint: function(point) {
  1748. var x = point.x,
  1749. y = point.y;
  1750. return x >= this.x && y >= this.y
  1751. && x <= this.x + this.width
  1752. && y <= this.y + this.height;
  1753. },
  1754. _containsRectangle: function(rect) {
  1755. var x = rect.x,
  1756. y = rect.y;
  1757. return x >= this.x && y >= this.y
  1758. && x + rect.width <= this.x + this.width
  1759. && y + rect.height <= this.y + this.height;
  1760. },
  1761. intersects: function() {
  1762. var rect = Rectangle.read(arguments),
  1763. epsilon = Base.read(arguments) || 0;
  1764. return rect.x + rect.width > this.x - epsilon
  1765. && rect.y + rect.height > this.y - epsilon
  1766. && rect.x < this.x + this.width + epsilon
  1767. && rect.y < this.y + this.height + epsilon;
  1768. },
  1769. intersect: function() {
  1770. var rect = Rectangle.read(arguments),
  1771. x1 = Math.max(this.x, rect.x),
  1772. y1 = Math.max(this.y, rect.y),
  1773. x2 = Math.min(this.x + this.width, rect.x + rect.width),
  1774. y2 = Math.min(this.y + this.height, rect.y + rect.height);
  1775. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1776. },
  1777. unite: function() {
  1778. var rect = Rectangle.read(arguments),
  1779. x1 = Math.min(this.x, rect.x),
  1780. y1 = Math.min(this.y, rect.y),
  1781. x2 = Math.max(this.x + this.width, rect.x + rect.width),
  1782. y2 = Math.max(this.y + this.height, rect.y + rect.height);
  1783. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1784. },
  1785. include: function() {
  1786. var point = Point.read(arguments);
  1787. var x1 = Math.min(this.x, point.x),
  1788. y1 = Math.min(this.y, point.y),
  1789. x2 = Math.max(this.x + this.width, point.x),
  1790. y2 = Math.max(this.y + this.height, point.y);
  1791. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1792. },
  1793. expand: function() {
  1794. var amount = Size.read(arguments),
  1795. hor = amount.width,
  1796. ver = amount.height;
  1797. return new Rectangle(this.x - hor / 2, this.y - ver / 2,
  1798. this.width + hor, this.height + ver);
  1799. },
  1800. scale: function(hor, ver) {
  1801. return this.expand(this.width * hor - this.width,
  1802. this.height * (ver === undefined ? hor : ver) - this.height);
  1803. }
  1804. }, Base.each([
  1805. ['Top', 'Left'], ['Top', 'Right'],
  1806. ['Bottom', 'Left'], ['Bottom', 'Right'],
  1807. ['Left', 'Center'], ['Top', 'Center'],
  1808. ['Right', 'Center'], ['Bottom', 'Center']
  1809. ],
  1810. function(parts, index) {
  1811. var part = parts.join(''),
  1812. xFirst = /^[RL]/.test(part);
  1813. if (index >= 4)
  1814. parts[1] += xFirst ? 'Y' : 'X';
  1815. var x = parts[xFirst ? 0 : 1],
  1816. y = parts[xFirst ? 1 : 0],
  1817. getX = 'get' + x,
  1818. getY = 'get' + y,
  1819. setX = 'set' + x,
  1820. setY = 'set' + y,
  1821. get = 'get' + part,
  1822. set = 'set' + part;
  1823. this[get] = function(_dontLink) {
  1824. var ctor = _dontLink ? Point : LinkedPoint;
  1825. return new ctor(this[getX](), this[getY](), this, set);
  1826. };
  1827. this[set] = function() {
  1828. var point = Point.read(arguments);
  1829. this[setX](point.x);
  1830. this[setY](point.y);
  1831. };
  1832. }, {
  1833. beans: true
  1834. }
  1835. ));
  1836. var LinkedRectangle = Rectangle.extend({
  1837. initialize: function Rectangle(x, y, width, height, owner, setter) {
  1838. this._set(x, y, width, height, true);
  1839. this._owner = owner;
  1840. this._setter = setter;
  1841. },
  1842. _set: function(x, y, width, height, _dontNotify) {
  1843. this._x = x;
  1844. this._y = y;
  1845. this._width = width;
  1846. this._height = height;
  1847. if (!_dontNotify)
  1848. this._owner[this._setter](this);
  1849. return this;
  1850. }
  1851. },
  1852. new function() {
  1853. var proto = Rectangle.prototype;
  1854. return Base.each(['x', 'y', 'width', 'height'], function(key) {
  1855. var part = Base.capitalize(key),
  1856. internal = '_' + key;
  1857. this['get' + part] = function() {
  1858. return this[internal];
  1859. };
  1860. this['set' + part] = function(value) {
  1861. this[internal] = value;
  1862. if (!this._dontNotify)
  1863. this._owner[this._setter](this);
  1864. };
  1865. }, Base.each(['Point', 'Size', 'Center',
  1866. 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
  1867. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  1868. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
  1869. function(key) {
  1870. var name = 'set' + key;
  1871. this[name] = function() {
  1872. this._dontNotify = true;
  1873. proto[name].apply(this, arguments);
  1874. this._dontNotify = false;
  1875. this._owner[this._setter](this);
  1876. };
  1877. }, {
  1878. isSelected: function() {
  1879. return !!(this._owner._selection & 2);
  1880. },
  1881. setSelected: function(selected) {
  1882. var owner = this._owner;
  1883. if (owner._changeSelection) {
  1884. owner._changeSelection(2, selected);
  1885. }
  1886. }
  1887. })
  1888. );
  1889. });
  1890. var Matrix = Base.extend({
  1891. _class: 'Matrix',
  1892. initialize: function Matrix(arg, _dontNotify) {
  1893. var count = arguments.length,
  1894. ok = true;
  1895. if (count >= 6) {
  1896. this._set.apply(this, arguments);
  1897. } else if (count === 1 || count === 2) {
  1898. if (arg instanceof Matrix) {
  1899. this._set(arg._a, arg._b, arg._c, arg._d, arg._tx, arg._ty,
  1900. _dontNotify);
  1901. } else if (Array.isArray(arg)) {
  1902. this._set.apply(this,
  1903. _dontNotify ? arg.concat([_dontNotify]) : arg);
  1904. } else {
  1905. ok = false;
  1906. }
  1907. } else if (!count) {
  1908. this.reset();
  1909. } else {
  1910. ok = false;
  1911. }
  1912. if (!ok) {
  1913. throw new Error('Unsupported matrix parameters');
  1914. }
  1915. return this;
  1916. },
  1917. set: '#initialize',
  1918. _set: function(a, b, c, d, tx, ty, _dontNotify) {
  1919. this._a = a;
  1920. this._b = b;
  1921. this._c = c;
  1922. this._d = d;
  1923. this._tx = tx;
  1924. this._ty = ty;
  1925. if (!_dontNotify)
  1926. this._changed();
  1927. return this;
  1928. },
  1929. _serialize: function(options, dictionary) {
  1930. return Base.serialize(this.getValues(), options, true, dictionary);
  1931. },
  1932. _changed: function() {
  1933. var owner = this._owner;
  1934. if (owner) {
  1935. if (owner._applyMatrix) {
  1936. owner.transform(null, true);
  1937. } else {
  1938. owner._changed(25);
  1939. }
  1940. }
  1941. },
  1942. clone: function() {
  1943. return new Matrix(this._a, this._b, this._c, this._d,
  1944. this._tx, this._ty);
  1945. },
  1946. equals: function(mx) {
  1947. return mx === this || mx && this._a === mx._a && this._b === mx._b
  1948. && this._c === mx._c && this._d === mx._d
  1949. && this._tx === mx._tx && this._ty === mx._ty;
  1950. },
  1951. toString: function() {
  1952. var f = Formatter.instance;
  1953. return '[[' + [f.number(this._a), f.number(this._c),
  1954. f.number(this._tx)].join(', ') + '], ['
  1955. + [f.number(this._b), f.number(this._d),
  1956. f.number(this._ty)].join(', ') + ']]';
  1957. },
  1958. reset: function(_dontNotify) {
  1959. this._a = this._d = 1;
  1960. this._b = this._c = this._tx = this._ty = 0;
  1961. if (!_dontNotify)
  1962. this._changed();
  1963. return this;
  1964. },
  1965. apply: function(recursively, _setApplyMatrix) {
  1966. var owner = this._owner;
  1967. if (owner) {
  1968. owner.transform(null, true, Base.pick(recursively, true),
  1969. _setApplyMatrix);
  1970. return this.isIdentity();
  1971. }
  1972. return false;
  1973. },
  1974. translate: function() {
  1975. var point = Point.read(arguments),
  1976. x = point.x,
  1977. y = point.y;
  1978. this._tx += x * this._a + y * this._c;
  1979. this._ty += x * this._b + y * this._d;
  1980. this._changed();
  1981. return this;
  1982. },
  1983. scale: function() {
  1984. var scale = Point.read(arguments),
  1985. center = Point.read(arguments, 0, { readNull: true });
  1986. if (center)
  1987. this.translate(center);
  1988. this._a *= scale.x;
  1989. this._b *= scale.x;
  1990. this._c *= scale.y;
  1991. this._d *= scale.y;
  1992. if (center)
  1993. this.translate(center.negate());
  1994. this._changed();
  1995. return this;
  1996. },
  1997. rotate: function(angle ) {
  1998. angle *= Math.PI / 180;
  1999. var center = Point.read(arguments, 1),
  2000. x = center.x,
  2001. y = center.y,
  2002. cos = Math.cos(angle),
  2003. sin = Math.sin(angle),
  2004. tx = x - x * cos + y * sin,
  2005. ty = y - x * sin - y * cos,
  2006. a = this._a,
  2007. b = this._b,
  2008. c = this._c,
  2009. d = this._d;
  2010. this._a = cos * a + sin * c;
  2011. this._b = cos * b + sin * d;
  2012. this._c = -sin * a + cos * c;
  2013. this._d = -sin * b + cos * d;
  2014. this._tx += tx * a + ty * c;
  2015. this._ty += tx * b + ty * d;
  2016. this._changed();
  2017. return this;
  2018. },
  2019. shear: function() {
  2020. var shear = Point.read(arguments),
  2021. center = Point.read(arguments, 0, { readNull: true });
  2022. if (center)
  2023. this.translate(center);
  2024. var a = this._a,
  2025. b = this._b;
  2026. this._a += shear.y * this._c;
  2027. this._b += shear.y * this._d;
  2028. this._c += shear.x * a;
  2029. this._d += shear.x * b;
  2030. if (center)
  2031. this.translate(center.negate());
  2032. this._changed();
  2033. return this;
  2034. },
  2035. skew: function() {
  2036. var skew = Point.read(arguments),
  2037. center = Point.read(arguments, 0, { readNull: true }),
  2038. toRadians = Math.PI / 180,
  2039. shear = new Point(Math.tan(skew.x * toRadians),
  2040. Math.tan(skew.y * toRadians));
  2041. return this.shear(shear, center);
  2042. },
  2043. append: function(mx, _dontNotify) {
  2044. if (mx) {
  2045. var a1 = this._a,
  2046. b1 = this._b,
  2047. c1 = this._c,
  2048. d1 = this._d,
  2049. a2 = mx._a,
  2050. b2 = mx._c,
  2051. c2 = mx._b,
  2052. d2 = mx._d,
  2053. tx2 = mx._tx,
  2054. ty2 = mx._ty;
  2055. this._a = a2 * a1 + c2 * c1;
  2056. this._c = b2 * a1 + d2 * c1;
  2057. this._b = a2 * b1 + c2 * d1;
  2058. this._d = b2 * b1 + d2 * d1;
  2059. this._tx += tx2 * a1 + ty2 * c1;
  2060. this._ty += tx2 * b1 + ty2 * d1;
  2061. if (!_dontNotify)
  2062. this._changed();
  2063. }
  2064. return this;
  2065. },
  2066. prepend: function(mx, _dontNotify) {
  2067. if (mx) {
  2068. var a1 = this._a,
  2069. b1 = this._b,
  2070. c1 = this._c,
  2071. d1 = this._d,
  2072. tx1 = this._tx,
  2073. ty1 = this._ty,
  2074. a2 = mx._a,
  2075. b2 = mx._c,
  2076. c2 = mx._b,
  2077. d2 = mx._d,
  2078. tx2 = mx._tx,
  2079. ty2 = mx._ty;
  2080. this._a = a2 * a1 + b2 * b1;
  2081. this._c = a2 * c1 + b2 * d1;
  2082. this._b = c2 * a1 + d2 * b1;
  2083. this._d = c2 * c1 + d2 * d1;
  2084. this._tx = a2 * tx1 + b2 * ty1 + tx2;
  2085. this._ty = c2 * tx1 + d2 * ty1 + ty2;
  2086. if (!_dontNotify)
  2087. this._changed();
  2088. }
  2089. return this;
  2090. },
  2091. appended: function(mx) {
  2092. return this.clone().append(mx);
  2093. },
  2094. prepended: function(mx) {
  2095. return this.clone().prepend(mx);
  2096. },
  2097. invert: function() {
  2098. var a = this._a,
  2099. b = this._b,
  2100. c = this._c,
  2101. d = this._d,
  2102. tx = this._tx,
  2103. ty = this._ty,
  2104. det = a * d - b * c,
  2105. res = null;
  2106. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2107. this._a = d / det;
  2108. this._b = -b / det;
  2109. this._c = -c / det;
  2110. this._d = a / det;
  2111. this._tx = (c * ty - d * tx) / det;
  2112. this._ty = (b * tx - a * ty) / det;
  2113. res = this;
  2114. }
  2115. return res;
  2116. },
  2117. inverted: function() {
  2118. return this.clone().invert();
  2119. },
  2120. concatenate: '#append',
  2121. preConcatenate: '#prepend',
  2122. chain: '#appended',
  2123. _shiftless: function() {
  2124. return new Matrix(this._a, this._b, this._c, this._d, 0, 0);
  2125. },
  2126. _orNullIfIdentity: function() {
  2127. return this.isIdentity() ? null : this;
  2128. },
  2129. isIdentity: function() {
  2130. return this._a === 1 && this._b === 0 && this._c === 0 && this._d === 1
  2131. && this._tx === 0 && this._ty === 0;
  2132. },
  2133. isInvertible: function() {
  2134. var det = this._a * this._d - this._c * this._b;
  2135. return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty);
  2136. },
  2137. isSingular: function() {
  2138. return !this.isInvertible();
  2139. },
  2140. transform: function( src, dst, count) {
  2141. return arguments.length < 3
  2142. ? this._transformPoint(Point.read(arguments))
  2143. : this._transformCoordinates(src, dst, count);
  2144. },
  2145. _transformPoint: function(point, dest, _dontNotify) {
  2146. var x = point.x,
  2147. y = point.y;
  2148. if (!dest)
  2149. dest = new Point();
  2150. return dest._set(
  2151. x * this._a + y * this._c + this._tx,
  2152. x * this._b + y * this._d + this._ty,
  2153. _dontNotify);
  2154. },
  2155. _transformCoordinates: function(src, dst, count) {
  2156. for (var i = 0, max = 2 * count; i < max; i += 2) {
  2157. var x = src[i],
  2158. y = src[i + 1];
  2159. dst[i] = x * this._a + y * this._c + this._tx;
  2160. dst[i + 1] = x * this._b + y * this._d + this._ty;
  2161. }
  2162. return dst;
  2163. },
  2164. _transformCorners: function(rect) {
  2165. var x1 = rect.x,
  2166. y1 = rect.y,
  2167. x2 = x1 + rect.width,
  2168. y2 = y1 + rect.height,
  2169. coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
  2170. return this._transformCoordinates(coords, coords, 4);
  2171. },
  2172. _transformBounds: function(bounds, dest, _dontNotify) {
  2173. var coords = this._transformCorners(bounds),
  2174. min = coords.slice(0, 2),
  2175. max = min.slice();
  2176. for (var i = 2; i < 8; i++) {
  2177. var val = coords[i],
  2178. j = i & 1;
  2179. if (val < min[j]) {
  2180. min[j] = val;
  2181. } else if (val > max[j]) {
  2182. max[j] = val;
  2183. }
  2184. }
  2185. if (!dest)
  2186. dest = new Rectangle();
  2187. return dest._set(min[0], min[1], max[0] - min[0], max[1] - min[1],
  2188. _dontNotify);
  2189. },
  2190. inverseTransform: function() {
  2191. return this._inverseTransform(Point.read(arguments));
  2192. },
  2193. _inverseTransform: function(point, dest, _dontNotify) {
  2194. var a = this._a,
  2195. b = this._b,
  2196. c = this._c,
  2197. d = this._d,
  2198. tx = this._tx,
  2199. ty = this._ty,
  2200. det = a * d - b * c,
  2201. res = null;
  2202. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2203. var x = point.x - this._tx,
  2204. y = point.y - this._ty;
  2205. if (!dest)
  2206. dest = new Point();
  2207. res = dest._set(
  2208. (x * d - y * c) / det,
  2209. (y * a - x * b) / det,
  2210. _dontNotify);
  2211. }
  2212. return res;
  2213. },
  2214. decompose: function() {
  2215. var a = this._a,
  2216. b = this._b,
  2217. c = this._c,
  2218. d = this._d,
  2219. det = a * d - b * c,
  2220. sqrt = Math.sqrt,
  2221. atan2 = Math.atan2,
  2222. degrees = 180 / Math.PI,
  2223. rotate,
  2224. scale,
  2225. skew;
  2226. if (a !== 0 || b !== 0) {
  2227. var r = sqrt(a * a + b * b);
  2228. rotate = Math.acos(a / r) * (b > 0 ? 1 : -1);
  2229. scale = [r, det / r];
  2230. skew = [atan2(a * c + b * d, r * r), 0];
  2231. } else if (c !== 0 || d !== 0) {
  2232. var s = sqrt(c * c + d * d);
  2233. rotate = Math.asin(c / s) * (d > 0 ? 1 : -1);
  2234. scale = [det / s, s];
  2235. skew = [0, atan2(a * c + b * d, s * s)];
  2236. } else {
  2237. rotate = 0;
  2238. skew = scale = [0, 0];
  2239. }
  2240. return {
  2241. translation: this.getTranslation(),
  2242. rotation: rotate * degrees,
  2243. scaling: new Point(scale),
  2244. skewing: new Point(skew[0] * degrees, skew[1] * degrees)
  2245. };
  2246. },
  2247. getValues: function() {
  2248. return [ this._a, this._b, this._c, this._d, this._tx, this._ty ];
  2249. },
  2250. getTranslation: function() {
  2251. return new Point(this._tx, this._ty);
  2252. },
  2253. getScaling: function() {
  2254. return this.decompose().scaling;
  2255. },
  2256. getRotation: function() {
  2257. return this.decompose().rotation;
  2258. },
  2259. applyToContext: function(ctx) {
  2260. if (!this.isIdentity()) {
  2261. ctx.transform(this._a, this._b, this._c, this._d,
  2262. this._tx, this._ty);
  2263. }
  2264. }
  2265. }, Base.each(['a', 'b', 'c', 'd', 'tx', 'ty'], function(key) {
  2266. var part = Base.capitalize(key),
  2267. prop = '_' + key;
  2268. this['get' + part] = function() {
  2269. return this[prop];
  2270. };
  2271. this['set' + part] = function(value) {
  2272. this[prop] = value;
  2273. this._changed();
  2274. };
  2275. }, {}));
  2276. var Line = Base.extend({
  2277. _class: 'Line',
  2278. initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
  2279. var asVector = false;
  2280. if (arguments.length >= 4) {
  2281. this._px = arg0;
  2282. this._py = arg1;
  2283. this._vx = arg2;
  2284. this._vy = arg3;
  2285. asVector = arg4;
  2286. } else {
  2287. this._px = arg0.x;
  2288. this._py = arg0.y;
  2289. this._vx = arg1.x;
  2290. this._vy = arg1.y;
  2291. asVector = arg2;
  2292. }
  2293. if (!asVector) {
  2294. this._vx -= this._px;
  2295. this._vy -= this._py;
  2296. }
  2297. },
  2298. getPoint: function() {
  2299. return new Point(this._px, this._py);
  2300. },
  2301. getVector: function() {
  2302. return new Point(this._vx, this._vy);
  2303. },
  2304. getLength: function() {
  2305. return this.getVector().getLength();
  2306. },
  2307. intersect: function(line, isInfinite) {
  2308. return Line.intersect(
  2309. this._px, this._py, this._vx, this._vy,
  2310. line._px, line._py, line._vx, line._vy,
  2311. true, isInfinite);
  2312. },
  2313. getSide: function(point, isInfinite) {
  2314. return Line.getSide(
  2315. this._px, this._py, this._vx, this._vy,
  2316. point.x, point.y, true, isInfinite);
  2317. },
  2318. getDistance: function(point) {
  2319. return Math.abs(this.getSignedDistance(point));
  2320. },
  2321. getSignedDistance: function(point) {
  2322. return Line.getSignedDistance(this._px, this._py, this._vx, this._vy,
  2323. point.x, point.y, true);
  2324. },
  2325. isCollinear: function(line) {
  2326. return Point.isCollinear(this._vx, this._vy, line._vx, line._vy);
  2327. },
  2328. isOrthogonal: function(line) {
  2329. return Point.isOrthogonal(this._vx, this._vy, line._vx, line._vy);
  2330. },
  2331. statics: {
  2332. intersect: function(p1x, p1y, v1x, v1y, p2x, p2y, v2x, v2y, asVector,
  2333. isInfinite) {
  2334. if (!asVector) {
  2335. v1x -= p1x;
  2336. v1y -= p1y;
  2337. v2x -= p2x;
  2338. v2y -= p2y;
  2339. }
  2340. var cross = v1x * v2y - v1y * v2x;
  2341. if (!Numerical.isZero(cross)) {
  2342. var dx = p1x - p2x,
  2343. dy = p1y - p2y,
  2344. u1 = (v2x * dy - v2y * dx) / cross,
  2345. u2 = (v1x * dy - v1y * dx) / cross,
  2346. epsilon = 1e-12,
  2347. uMin = -epsilon,
  2348. uMax = 1 + epsilon;
  2349. if (isInfinite
  2350. || uMin < u1 && u1 < uMax && uMin < u2 && u2 < uMax) {
  2351. if (!isInfinite) {
  2352. u1 = u1 <= 0 ? 0 : u1 >= 1 ? 1 : u1;
  2353. }
  2354. return new Point(
  2355. p1x + u1 * v1x,
  2356. p1y + u1 * v1y);
  2357. }
  2358. }
  2359. },
  2360. getSide: function(px, py, vx, vy, x, y, asVector, isInfinite) {
  2361. if (!asVector) {
  2362. vx -= px;
  2363. vy -= py;
  2364. }
  2365. var v2x = x - px,
  2366. v2y = y - py,
  2367. ccw = v2x * vy - v2y * vx;
  2368. if (!isInfinite && Numerical.isZero(ccw)) {
  2369. ccw = (v2x * vx + v2x * vx) / (vx * vx + vy * vy);
  2370. if (ccw >= 0 && ccw <= 1)
  2371. ccw = 0;
  2372. }
  2373. return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
  2374. },
  2375. getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
  2376. if (!asVector) {
  2377. vx -= px;
  2378. vy -= py;
  2379. }
  2380. return vx === 0 ? vy > 0 ? x - px : px - x
  2381. : vy === 0 ? vx < 0 ? y - py : py - y
  2382. : ((x-px) * vy - (y-py) * vx) / Math.sqrt(vx * vx + vy * vy);
  2383. },
  2384. getDistance: function(px, py, vx, vy, x, y, asVector) {
  2385. return Math.abs(
  2386. Line.getSignedDistance(px, py, vx, vy, x, y, asVector));
  2387. }
  2388. }
  2389. });
  2390. var Project = PaperScopeItem.extend({
  2391. _class: 'Project',
  2392. _list: 'projects',
  2393. _reference: 'project',
  2394. _compactSerialize: true,
  2395. initialize: function Project(element) {
  2396. PaperScopeItem.call(this, true);
  2397. this._children = [];
  2398. this._namedChildren = {};
  2399. this._activeLayer = null;
  2400. this._currentStyle = new Style(null, null, this);
  2401. this._view = View.create(this,
  2402. element || CanvasProvider.getCanvas(1, 1));
  2403. this._selectionItems = {};
  2404. this._selectionCount = 0;
  2405. this._updateVersion = 0;
  2406. },
  2407. _serialize: function(options, dictionary) {
  2408. return Base.serialize(this._children, options, true, dictionary);
  2409. },
  2410. _changed: function(flags, item) {
  2411. if (flags & 1) {
  2412. var view = this._view;
  2413. if (view) {
  2414. view._needsUpdate = true;
  2415. if (!view._requested && view._autoUpdate)
  2416. view.requestUpdate();
  2417. }
  2418. }
  2419. var changes = this._changes;
  2420. if (changes && item) {
  2421. var changesById = this._changesById,
  2422. id = item._id,
  2423. entry = changesById[id];
  2424. if (entry) {
  2425. entry.flags |= flags;
  2426. } else {
  2427. changes.push(changesById[id] = { item: item, flags: flags });
  2428. }
  2429. }
  2430. },
  2431. clear: function() {
  2432. var children = this._children;
  2433. for (var i = children.length - 1; i >= 0; i--)
  2434. children[i].remove();
  2435. },
  2436. isEmpty: function() {
  2437. return !this._children.length;
  2438. },
  2439. remove: function remove() {
  2440. if (!remove.base.call(this))
  2441. return false;
  2442. if (this._view)
  2443. this._view.remove();
  2444. return true;
  2445. },
  2446. getView: function() {
  2447. return this._view;
  2448. },
  2449. getCurrentStyle: function() {
  2450. return this._currentStyle;
  2451. },
  2452. setCurrentStyle: function(style) {
  2453. this._currentStyle.set(style);
  2454. },
  2455. getIndex: function() {
  2456. return this._index;
  2457. },
  2458. getOptions: function() {
  2459. return this._scope.settings;
  2460. },
  2461. getLayers: function() {
  2462. return this._children;
  2463. },
  2464. getActiveLayer: function() {
  2465. return this._activeLayer || new Layer({ project: this, insert: true });
  2466. },
  2467. getSymbolDefinitions: function() {
  2468. var definitions = [],
  2469. ids = {};
  2470. this.getItems({
  2471. class: SymbolItem,
  2472. match: function(item) {
  2473. var definition = item._definition,
  2474. id = definition._id;
  2475. if (!ids[id]) {
  2476. ids[id] = true;
  2477. definitions.push(definition);
  2478. }
  2479. return false;
  2480. }
  2481. });
  2482. return definitions;
  2483. },
  2484. getSymbols: 'getSymbolDefinitions',
  2485. getSelectedItems: function() {
  2486. var selectionItems = this._selectionItems,
  2487. items = [];
  2488. for (var id in selectionItems) {
  2489. var item = selectionItems[id],
  2490. selection = item._selection;
  2491. if ((selection & 1) && item.isInserted()) {
  2492. items.push(item);
  2493. } else if (!selection) {
  2494. this._updateSelection(item);
  2495. }
  2496. }
  2497. return items;
  2498. },
  2499. _updateSelection: function(item) {
  2500. var id = item._id,
  2501. selectionItems = this._selectionItems;
  2502. if (item._selection) {
  2503. if (selectionItems[id] !== item) {
  2504. this._selectionCount++;
  2505. selectionItems[id] = item;
  2506. }
  2507. } else if (selectionItems[id] === item) {
  2508. this._selectionCount--;
  2509. delete selectionItems[id];
  2510. }
  2511. },
  2512. selectAll: function() {
  2513. var children = this._children;
  2514. for (var i = 0, l = children.length; i < l; i++)
  2515. children[i].setFullySelected(true);
  2516. },
  2517. deselectAll: function() {
  2518. var selectionItems = this._selectionItems;
  2519. for (var i in selectionItems)
  2520. selectionItems[i].setFullySelected(false);
  2521. },
  2522. addLayer: function(layer) {
  2523. return this.insertLayer(undefined, layer);
  2524. },
  2525. insertLayer: function(index, layer) {
  2526. if (layer instanceof Layer) {
  2527. layer._remove(false, true);
  2528. Base.splice(this._children, [layer], index, 0);
  2529. layer._setProject(this, true);
  2530. var name = layer._name;
  2531. if (name)
  2532. layer.setName(name);
  2533. if (this._changes)
  2534. layer._changed(5);
  2535. if (!this._activeLayer)
  2536. this._activeLayer = layer;
  2537. } else {
  2538. layer = null;
  2539. }
  2540. return layer;
  2541. },
  2542. _insertItem: function(index, item, _created) {
  2543. item = this.insertLayer(index, item)
  2544. || (this._activeLayer || this._insertItem(undefined,
  2545. new Layer(Item.NO_INSERT), true))
  2546. .insertChild(index, item);
  2547. if (_created && item.activate)
  2548. item.activate();
  2549. return item;
  2550. },
  2551. getItems: function(options) {
  2552. return Item._getItems(this, options);
  2553. },
  2554. getItem: function(options) {
  2555. return Item._getItems(this, options, null, null, true)[0] || null;
  2556. },
  2557. importJSON: function(json) {
  2558. this.activate();
  2559. var layer = this._activeLayer;
  2560. return Base.importJSON(json, layer && layer.isEmpty() && layer);
  2561. },
  2562. removeOn: function(type) {
  2563. var sets = this._removeSets;
  2564. if (sets) {
  2565. if (type === 'mouseup')
  2566. sets.mousedrag = null;
  2567. var set = sets[type];
  2568. if (set) {
  2569. for (var id in set) {
  2570. var item = set[id];
  2571. for (var key in sets) {
  2572. var other = sets[key];
  2573. if (other && other != set)
  2574. delete other[item._id];
  2575. }
  2576. item.remove();
  2577. }
  2578. sets[type] = null;
  2579. }
  2580. }
  2581. },
  2582. draw: function(ctx, matrix, pixelRatio) {
  2583. this._updateVersion++;
  2584. ctx.save();
  2585. matrix.applyToContext(ctx);
  2586. var children = this._children,
  2587. param = new Base({
  2588. offset: new Point(0, 0),
  2589. pixelRatio: pixelRatio,
  2590. viewMatrix: matrix.isIdentity() ? null : matrix,
  2591. matrices: [new Matrix()],
  2592. updateMatrix: true
  2593. });
  2594. for (var i = 0, l = children.length; i < l; i++) {
  2595. children[i].draw(ctx, param);
  2596. }
  2597. ctx.restore();
  2598. if (this._selectionCount > 0) {
  2599. ctx.save();
  2600. ctx.strokeWidth = 1;
  2601. var items = this._selectionItems,
  2602. size = this._scope.settings.handleSize,
  2603. version = this._updateVersion;
  2604. for (var id in items) {
  2605. items[id]._drawSelection(ctx, matrix, size, items, version);
  2606. }
  2607. ctx.restore();
  2608. }
  2609. }
  2610. });
  2611. var Item = Base.extend(Emitter, {
  2612. statics: {
  2613. extend: function extend(src) {
  2614. if (src._serializeFields)
  2615. src._serializeFields = Base.set({},
  2616. this.prototype._serializeFields, src._serializeFields);
  2617. return extend.base.apply(this, arguments);
  2618. },
  2619. NO_INSERT: { insert: false }
  2620. },
  2621. _class: 'Item',
  2622. _name: null,
  2623. _applyMatrix: true,
  2624. _canApplyMatrix: true,
  2625. _canScaleStroke: false,
  2626. _pivot: null,
  2627. _visible: true,
  2628. _blendMode: 'normal',
  2629. _opacity: 1,
  2630. _locked: false,
  2631. _guide: false,
  2632. _clipMask: false,
  2633. _selection: 0,
  2634. _selectBounds: true,
  2635. _selectChildren: false,
  2636. _serializeFields: {
  2637. name: null,
  2638. applyMatrix: null,
  2639. matrix: new Matrix(),
  2640. pivot: null,
  2641. visible: true,
  2642. blendMode: 'normal',
  2643. opacity: 1,
  2644. locked: false,
  2645. guide: false,
  2646. clipMask: false,
  2647. selected: false,
  2648. data: {}
  2649. },
  2650. _prioritize: ['applyMatrix']
  2651. },
  2652. new function() {
  2653. var handlers = ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
  2654. 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'];
  2655. return Base.each(handlers,
  2656. function(name) {
  2657. this._events[name] = {
  2658. install: function(type) {
  2659. this.getView()._countItemEvent(type, 1);
  2660. },
  2661. uninstall: function(type) {
  2662. this.getView()._countItemEvent(type, -1);
  2663. }
  2664. };
  2665. }, {
  2666. _events: {
  2667. onFrame: {
  2668. install: function() {
  2669. this.getView()._animateItem(this, true);
  2670. },
  2671. uninstall: function() {
  2672. this.getView()._animateItem(this, false);
  2673. }
  2674. },
  2675. onLoad: {},
  2676. onError: {}
  2677. },
  2678. statics: {
  2679. _itemHandlers: handlers
  2680. }
  2681. }
  2682. );
  2683. }, {
  2684. initialize: function Item() {
  2685. },
  2686. _initialize: function(props, point) {
  2687. var hasProps = props && Base.isPlainObject(props),
  2688. internal = hasProps && props.internal === true,
  2689. matrix = this._matrix = new Matrix(),
  2690. project = hasProps && props.project || paper.project,
  2691. settings = paper.settings;
  2692. this._id = internal ? null : UID.get();
  2693. this._parent = this._index = null;
  2694. this._applyMatrix = this._canApplyMatrix && settings.applyMatrix;
  2695. if (point)
  2696. matrix.translate(point);
  2697. matrix._owner = this;
  2698. this._style = new Style(project._currentStyle, this, project);
  2699. if (internal || hasProps && props.insert == false
  2700. || !settings.insertItems && !(hasProps && props.insert === true)) {
  2701. this._setProject(project);
  2702. } else {
  2703. (hasProps && props.parent || project)
  2704. ._insertItem(undefined, this, true);
  2705. }
  2706. if (hasProps && props !== Item.NO_INSERT) {
  2707. this.set(props, {
  2708. internal: true, insert: true, project: true, parent: true
  2709. });
  2710. }
  2711. return hasProps;
  2712. },
  2713. _serialize: function(options, dictionary) {
  2714. var props = {},
  2715. that = this;
  2716. function serialize(fields) {
  2717. for (var key in fields) {
  2718. var value = that[key];
  2719. if (!Base.equals(value, key === 'leading'
  2720. ? fields.fontSize * 1.2 : fields[key])) {
  2721. props[key] = Base.serialize(value, options,
  2722. key !== 'data', dictionary);
  2723. }
  2724. }
  2725. }
  2726. serialize(this._serializeFields);
  2727. if (!(this instanceof Group))
  2728. serialize(this._style._defaults);
  2729. return [ this._class, props ];
  2730. },
  2731. _changed: function(flags) {
  2732. var symbol = this._symbol,
  2733. cacheParent = this._parent || symbol,
  2734. project = this._project;
  2735. if (flags & 8) {
  2736. this._bounds = this._position = this._decomposed = undefined;
  2737. }
  2738. if (flags & 16) {
  2739. this._globalMatrix = undefined;
  2740. }
  2741. if (cacheParent
  2742. && (flags & 72)) {
  2743. Item._clearBoundsCache(cacheParent);
  2744. }
  2745. if (flags & 2) {
  2746. Item._clearBoundsCache(this);
  2747. }
  2748. if (project)
  2749. project._changed(flags, this);
  2750. if (symbol)
  2751. symbol._changed(flags);
  2752. },
  2753. getId: function() {
  2754. return this._id;
  2755. },
  2756. getName: function() {
  2757. return this._name;
  2758. },
  2759. setName: function(name) {
  2760. if (this._name)
  2761. this._removeNamed();
  2762. if (name === (+name) + '')
  2763. throw new Error(
  2764. 'Names consisting only of numbers are not supported.');
  2765. var owner = this._getOwner();
  2766. if (name && owner) {
  2767. var children = owner._children,
  2768. namedChildren = owner._namedChildren;
  2769. (namedChildren[name] = namedChildren[name] || []).push(this);
  2770. if (!(name in children))
  2771. children[name] = this;
  2772. }
  2773. this._name = name || undefined;
  2774. this._changed(256);
  2775. },
  2776. getStyle: function() {
  2777. return this._style;
  2778. },
  2779. setStyle: function(style) {
  2780. this.getStyle().set(style);
  2781. }
  2782. }, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
  2783. function(name) {
  2784. var part = Base.capitalize(name),
  2785. key = '_' + name,
  2786. flags = {
  2787. locked: 256,
  2788. visible: 265
  2789. };
  2790. this['get' + part] = function() {
  2791. return this[key];
  2792. };
  2793. this['set' + part] = function(value) {
  2794. if (value != this[key]) {
  2795. this[key] = value;
  2796. this._changed(flags[name] || 257);
  2797. }
  2798. };
  2799. },
  2800. {}), {
  2801. beans: true,
  2802. getSelection: function() {
  2803. return this._selection;
  2804. },
  2805. setSelection: function(selection) {
  2806. if (selection !== this._selection) {
  2807. this._selection = selection;
  2808. var project = this._project;
  2809. if (project) {
  2810. project._updateSelection(this);
  2811. this._changed(257);
  2812. }
  2813. }
  2814. },
  2815. _changeSelection: function(flag, selected) {
  2816. var selection = this._selection;
  2817. this.setSelection(selected ? selection | flag : selection & ~flag);
  2818. },
  2819. isSelected: function() {
  2820. if (this._selectChildren) {
  2821. var children = this._children;
  2822. for (var i = 0, l = children.length; i < l; i++)
  2823. if (children[i].isSelected())
  2824. return true;
  2825. }
  2826. return !!(this._selection & 1);
  2827. },
  2828. setSelected: function(selected) {
  2829. if (this._selectChildren) {
  2830. var children = this._children;
  2831. for (var i = 0, l = children.length; i < l; i++)
  2832. children[i].setSelected(selected);
  2833. }
  2834. this._changeSelection(1, selected);
  2835. },
  2836. isFullySelected: function() {
  2837. var children = this._children,
  2838. selected = !!(this._selection & 1);
  2839. if (children && selected) {
  2840. for (var i = 0, l = children.length; i < l; i++)
  2841. if (!children[i].isFullySelected())
  2842. return false;
  2843. return true;
  2844. }
  2845. return selected;
  2846. },
  2847. setFullySelected: function(selected) {
  2848. var children = this._children;
  2849. if (children) {
  2850. for (var i = 0, l = children.length; i < l; i++)
  2851. children[i].setFullySelected(selected);
  2852. }
  2853. this._changeSelection(1, selected);
  2854. },
  2855. isClipMask: function() {
  2856. return this._clipMask;
  2857. },
  2858. setClipMask: function(clipMask) {
  2859. if (this._clipMask != (clipMask = !!clipMask)) {
  2860. this._clipMask = clipMask;
  2861. if (clipMask) {
  2862. this.setFillColor(null);
  2863. this.setStrokeColor(null);
  2864. }
  2865. this._changed(257);
  2866. if (this._parent)
  2867. this._parent._changed(2048);
  2868. }
  2869. },
  2870. getData: function() {
  2871. if (!this._data)
  2872. this._data = {};
  2873. return this._data;
  2874. },
  2875. setData: function(data) {
  2876. this._data = data;
  2877. },
  2878. getPosition: function(_dontLink) {
  2879. var ctor = _dontLink ? Point : LinkedPoint;
  2880. var position = this._position ||
  2881. (this._position = this._getPositionFromBounds());
  2882. return new ctor(position.x, position.y, this, 'setPosition');
  2883. },
  2884. setPosition: function() {
  2885. this.translate(Point.read(arguments).subtract(this.getPosition(true)));
  2886. },
  2887. _getPositionFromBounds: function(bounds) {
  2888. return this._pivot
  2889. ? this._matrix._transformPoint(this._pivot)
  2890. : (bounds || this.getBounds()).getCenter(true);
  2891. },
  2892. getPivot: function() {
  2893. var pivot = this._pivot;
  2894. return pivot
  2895. ? new LinkedPoint(pivot.x, pivot.y, this, 'setPivot')
  2896. : null;
  2897. },
  2898. setPivot: function() {
  2899. this._pivot = Point.read(arguments, 0, { clone: true, readNull: true });
  2900. this._position = undefined;
  2901. }
  2902. }, Base.each({
  2903. getStrokeBounds: { stroke: true },
  2904. getHandleBounds: { handle: true },
  2905. getInternalBounds: { internal: true }
  2906. },
  2907. function(options, key) {
  2908. this[key] = function(matrix) {
  2909. return this.getBounds(matrix, options);
  2910. };
  2911. },
  2912. {
  2913. beans: true,
  2914. getBounds: function(matrix, options) {
  2915. var hasMatrix = options || matrix instanceof Matrix,
  2916. opts = Base.set({}, hasMatrix ? options : matrix,
  2917. this._boundsOptions);
  2918. if (!opts.stroke || this.getStrokeScaling())
  2919. opts.cacheItem = this;
  2920. var rect = this._getCachedBounds(hasMatrix && matrix, opts).rect;
  2921. return !arguments.length
  2922. ? new LinkedRectangle(rect.x, rect.y, rect.width, rect.height,
  2923. this, 'setBounds')
  2924. : rect;
  2925. },
  2926. setBounds: function() {
  2927. var rect = Rectangle.read(arguments),
  2928. bounds = this.getBounds(),
  2929. _matrix = this._matrix,
  2930. matrix = new Matrix(),
  2931. center = rect.getCenter();
  2932. matrix.translate(center);
  2933. if (rect.width != bounds.width || rect.height != bounds.height) {
  2934. if (!_matrix.isInvertible()) {
  2935. _matrix.set(_matrix._backup
  2936. || new Matrix().translate(_matrix.getTranslation()));
  2937. bounds = this.getBounds();
  2938. }
  2939. matrix.scale(
  2940. bounds.width !== 0 ? rect.width / bounds.width : 0,
  2941. bounds.height !== 0 ? rect.height / bounds.height : 0);
  2942. }
  2943. center = bounds.getCenter();
  2944. matrix.translate(-center.x, -center.y);
  2945. this.transform(matrix);
  2946. },
  2947. _getBounds: function(matrix, options) {
  2948. var children = this._children;
  2949. if (!children || !children.length)
  2950. return new Rectangle();
  2951. Item._updateBoundsCache(this, options.cacheItem);
  2952. return Item._getBounds(children, matrix, options);
  2953. },
  2954. _getBoundsCacheKey: function(options, internal) {
  2955. return [
  2956. options.stroke ? 1 : 0,
  2957. options.handle ? 1 : 0,
  2958. internal ? 1 : 0
  2959. ].join('');
  2960. },
  2961. _getCachedBounds: function(matrix, options, noInternal) {
  2962. matrix = matrix && matrix._orNullIfIdentity();
  2963. var internal = options.internal && !noInternal,
  2964. cacheItem = options.cacheItem,
  2965. _matrix = internal ? null : this._matrix._orNullIfIdentity(),
  2966. cacheKey = cacheItem && (!matrix || matrix.equals(_matrix))
  2967. && this._getBoundsCacheKey(options, internal),
  2968. bounds = this._bounds;
  2969. Item._updateBoundsCache(this._parent || this._symbol, cacheItem);
  2970. if (cacheKey && bounds && cacheKey in bounds) {
  2971. var cached = bounds[cacheKey];
  2972. return {
  2973. rect: cached.rect.clone(),
  2974. nonscaling: cached.nonscaling
  2975. };
  2976. }
  2977. var res = this._getBounds(matrix || _matrix, options),
  2978. rect = res.rect || res,
  2979. style = this._style,
  2980. nonscaling = res.nonscaling || style.hasStroke()
  2981. && !style.getStrokeScaling();
  2982. if (cacheKey) {
  2983. if (!bounds) {
  2984. this._bounds = bounds = {};
  2985. }
  2986. var cached = bounds[cacheKey] = {
  2987. rect: rect.clone(),
  2988. nonscaling: nonscaling,
  2989. internal: internal
  2990. };
  2991. }
  2992. return {
  2993. rect: rect,
  2994. nonscaling: nonscaling
  2995. };
  2996. },
  2997. _getStrokeMatrix: function(matrix, options) {
  2998. var parent = this.getStrokeScaling() ? null
  2999. : options && options.internal ? this
  3000. : this._parent || this._symbol && this._symbol._item,
  3001. mx = parent ? parent.getViewMatrix().invert() : matrix;
  3002. return mx && mx._shiftless();
  3003. },
  3004. statics: {
  3005. _updateBoundsCache: function(parent, item) {
  3006. if (parent && item) {
  3007. var id = item._id,
  3008. ref = parent._boundsCache = parent._boundsCache || {
  3009. ids: {},
  3010. list: []
  3011. };
  3012. if (!ref.ids[id]) {
  3013. ref.list.push(item);
  3014. ref.ids[id] = item;
  3015. }
  3016. }
  3017. },
  3018. _clearBoundsCache: function(item) {
  3019. var cache = item._boundsCache;
  3020. if (cache) {
  3021. item._bounds = item._position = item._boundsCache = undefined;
  3022. for (var i = 0, list = cache.list, l = list.length; i < l; i++){
  3023. var other = list[i];
  3024. if (other !== item) {
  3025. other._bounds = other._position = undefined;
  3026. if (other._boundsCache)
  3027. Item._clearBoundsCache(other);
  3028. }
  3029. }
  3030. }
  3031. },
  3032. _getBounds: function(items, matrix, options) {
  3033. var x1 = Infinity,
  3034. x2 = -x1,
  3035. y1 = x1,
  3036. y2 = x2,
  3037. nonscaling = false;
  3038. options = options || {};
  3039. for (var i = 0, l = items.length; i < l; i++) {
  3040. var item = items[i];
  3041. if (item._visible && !item.isEmpty()) {
  3042. var bounds = item._getCachedBounds(
  3043. matrix && matrix.appended(item._matrix), options, true),
  3044. rect = bounds.rect;
  3045. x1 = Math.min(rect.x, x1);
  3046. y1 = Math.min(rect.y, y1);
  3047. x2 = Math.max(rect.x + rect.width, x2);
  3048. y2 = Math.max(rect.y + rect.height, y2);
  3049. if (bounds.nonscaling)
  3050. nonscaling = true;
  3051. }
  3052. }
  3053. return {
  3054. rect: isFinite(x1)
  3055. ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
  3056. : new Rectangle(),
  3057. nonscaling: nonscaling
  3058. };
  3059. }
  3060. }
  3061. }), {
  3062. beans: true,
  3063. _decompose: function() {
  3064. return this._applyMatrix
  3065. ? null
  3066. : this._decomposed || (this._decomposed = this._matrix.decompose());
  3067. },
  3068. getRotation: function() {
  3069. var decomposed = this._decompose();
  3070. return decomposed ? decomposed.rotation : 0;
  3071. },
  3072. setRotation: function(rotation) {
  3073. var current = this.getRotation();
  3074. if (current != null && rotation != null) {
  3075. var decomposed = this._decomposed;
  3076. this.rotate(rotation - current);
  3077. if (decomposed) {
  3078. decomposed.rotation = rotation;
  3079. this._decomposed = decomposed;
  3080. }
  3081. }
  3082. },
  3083. getScaling: function() {
  3084. var decomposed = this._decompose(),
  3085. s = decomposed && decomposed.scaling;
  3086. return new LinkedPoint(s ? s.x : 1, s ? s.y : 1, this, 'setScaling');
  3087. },
  3088. setScaling: function() {
  3089. var current = this.getScaling(),
  3090. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  3091. if (current && scaling && !current.equals(scaling)) {
  3092. var rotation = this.getRotation(),
  3093. decomposed = this._decomposed,
  3094. matrix = new Matrix(),
  3095. center = this.getPosition(true);
  3096. matrix.translate(center);
  3097. if (rotation)
  3098. matrix.rotate(rotation);
  3099. matrix.scale(scaling.x / current.x, scaling.y / current.y);
  3100. if (rotation)
  3101. matrix.rotate(-rotation);
  3102. matrix.translate(center.negate());
  3103. this.transform(matrix);
  3104. if (decomposed) {
  3105. decomposed.scaling = scaling;
  3106. this._decomposed = decomposed;
  3107. }
  3108. }
  3109. },
  3110. getMatrix: function() {
  3111. return this._matrix;
  3112. },
  3113. setMatrix: function() {
  3114. var matrix = this._matrix;
  3115. matrix.initialize.apply(matrix, arguments);
  3116. },
  3117. getGlobalMatrix: function(_dontClone) {
  3118. var matrix = this._globalMatrix;
  3119. if (matrix) {
  3120. var parent = this._parent;
  3121. var parents = [];
  3122. while (parent) {
  3123. if (!parent._globalMatrix) {
  3124. matrix = null;
  3125. for (var i = 0, l = parents.length; i < l; i++) {
  3126. parents[i]._globalMatrix = null;
  3127. }
  3128. break;
  3129. }
  3130. parents.push(parent);
  3131. parent = parent._parent;
  3132. }
  3133. }
  3134. if (!matrix) {
  3135. matrix = this._globalMatrix = this._matrix.clone();
  3136. var parent = this._parent;
  3137. if (parent)
  3138. matrix.prepend(parent.getGlobalMatrix(true));
  3139. }
  3140. return _dontClone ? matrix : matrix.clone();
  3141. },
  3142. getViewMatrix: function() {
  3143. return this.getGlobalMatrix().prepend(this.getView()._matrix);
  3144. },
  3145. getApplyMatrix: function() {
  3146. return this._applyMatrix;
  3147. },
  3148. setApplyMatrix: function(apply) {
  3149. if (this._applyMatrix = this._canApplyMatrix && !!apply)
  3150. this.transform(null, true);
  3151. },
  3152. getTransformContent: '#getApplyMatrix',
  3153. setTransformContent: '#setApplyMatrix',
  3154. }, {
  3155. getProject: function() {
  3156. return this._project;
  3157. },
  3158. _setProject: function(project, installEvents) {
  3159. if (this._project !== project) {
  3160. if (this._project)
  3161. this._installEvents(false);
  3162. this._project = project;
  3163. var children = this._children;
  3164. for (var i = 0, l = children && children.length; i < l; i++)
  3165. children[i]._setProject(project);
  3166. installEvents = true;
  3167. }
  3168. if (installEvents)
  3169. this._installEvents(true);
  3170. },
  3171. getView: function() {
  3172. return this._project._view;
  3173. },
  3174. _installEvents: function _installEvents(install) {
  3175. _installEvents.base.call(this, install);
  3176. var children = this._children;
  3177. for (var i = 0, l = children && children.length; i < l; i++)
  3178. children[i]._installEvents(install);
  3179. },
  3180. getLayer: function() {
  3181. var parent = this;
  3182. while (parent = parent._parent) {
  3183. if (parent instanceof Layer)
  3184. return parent;
  3185. }
  3186. return null;
  3187. },
  3188. getParent: function() {
  3189. return this._parent;
  3190. },
  3191. setParent: function(item) {
  3192. return item.addChild(this);
  3193. },
  3194. _getOwner: '#getParent',
  3195. getChildren: function() {
  3196. return this._children;
  3197. },
  3198. setChildren: function(items) {
  3199. this.removeChildren();
  3200. this.addChildren(items);
  3201. },
  3202. getFirstChild: function() {
  3203. return this._children && this._children[0] || null;
  3204. },
  3205. getLastChild: function() {
  3206. return this._children && this._children[this._children.length - 1]
  3207. || null;
  3208. },
  3209. getNextSibling: function() {
  3210. var owner = this._getOwner();
  3211. return owner && owner._children[this._index + 1] || null;
  3212. },
  3213. getPreviousSibling: function() {
  3214. var owner = this._getOwner();
  3215. return owner && owner._children[this._index - 1] || null;
  3216. },
  3217. getIndex: function() {
  3218. return this._index;
  3219. },
  3220. equals: function(item) {
  3221. return item === this || item && this._class === item._class
  3222. && this._style.equals(item._style)
  3223. && this._matrix.equals(item._matrix)
  3224. && this._locked === item._locked
  3225. && this._visible === item._visible
  3226. && this._blendMode === item._blendMode
  3227. && this._opacity === item._opacity
  3228. && this._clipMask === item._clipMask
  3229. && this._guide === item._guide
  3230. && this._equals(item)
  3231. || false;
  3232. },
  3233. _equals: function(item) {
  3234. return Base.equals(this._children, item._children);
  3235. },
  3236. clone: function(options) {
  3237. var copy = new this.constructor(Item.NO_INSERT),
  3238. children = this._children,
  3239. insert = Base.pick(options ? options.insert : undefined,
  3240. options === undefined || options === true),
  3241. deep = Base.pick(options ? options.deep : undefined, true);
  3242. if (children)
  3243. copy.copyAttributes(this);
  3244. if (!children || deep)
  3245. copy.copyContent(this);
  3246. if (!children)
  3247. copy.copyAttributes(this);
  3248. if (insert)
  3249. copy.insertAbove(this);
  3250. var name = this._name,
  3251. parent = this._parent;
  3252. if (name && parent) {
  3253. var children = parent._children,
  3254. orig = name,
  3255. i = 1;
  3256. while (children[name])
  3257. name = orig + ' ' + (i++);
  3258. if (name !== orig)
  3259. copy.setName(name);
  3260. }
  3261. return copy;
  3262. },
  3263. copyContent: function(source) {
  3264. var children = source._children;
  3265. for (var i = 0, l = children && children.length; i < l; i++) {
  3266. this.addChild(children[i].clone(false), true);
  3267. }
  3268. },
  3269. copyAttributes: function(source, excludeMatrix) {
  3270. this.setStyle(source._style);
  3271. var keys = ['_locked', '_visible', '_blendMode', '_opacity',
  3272. '_clipMask', '_guide'];
  3273. for (var i = 0, l = keys.length; i < l; i++) {
  3274. var key = keys[i];
  3275. if (source.hasOwnProperty(key))
  3276. this[key] = source[key];
  3277. }
  3278. if (!excludeMatrix)
  3279. this._matrix.set(source._matrix, true);
  3280. this.setApplyMatrix(source._applyMatrix);
  3281. this.setPivot(source._pivot);
  3282. this.setSelection(source._selection);
  3283. var data = source._data,
  3284. name = source._name;
  3285. this._data = data ? Base.clone(data) : null;
  3286. if (name)
  3287. this.setName(name);
  3288. },
  3289. rasterize: function(resolution, insert) {
  3290. var bounds = this.getStrokeBounds(),
  3291. scale = (resolution || this.getView().getResolution()) / 72,
  3292. topLeft = bounds.getTopLeft().floor(),
  3293. bottomRight = bounds.getBottomRight().ceil(),
  3294. size = new Size(bottomRight.subtract(topLeft)),
  3295. raster = new Raster(Item.NO_INSERT);
  3296. if (!size.isZero()) {
  3297. var canvas = CanvasProvider.getCanvas(size.multiply(scale)),
  3298. ctx = canvas.getContext('2d'),
  3299. matrix = new Matrix().scale(scale).translate(topLeft.negate());
  3300. ctx.save();
  3301. matrix.applyToContext(ctx);
  3302. this.draw(ctx, new Base({ matrices: [matrix] }));
  3303. ctx.restore();
  3304. raster.setCanvas(canvas);
  3305. }
  3306. raster.transform(new Matrix().translate(topLeft.add(size.divide(2)))
  3307. .scale(1 / scale));
  3308. if (insert === undefined || insert)
  3309. raster.insertAbove(this);
  3310. return raster;
  3311. },
  3312. contains: function() {
  3313. return !!this._contains(
  3314. this._matrix._inverseTransform(Point.read(arguments)));
  3315. },
  3316. _contains: function(point) {
  3317. var children = this._children;
  3318. if (children) {
  3319. for (var i = children.length - 1; i >= 0; i--) {
  3320. if (children[i].contains(point))
  3321. return true;
  3322. }
  3323. return false;
  3324. }
  3325. return point.isInside(this.getInternalBounds());
  3326. },
  3327. isInside: function() {
  3328. return Rectangle.read(arguments).contains(this.getBounds());
  3329. },
  3330. _asPathItem: function() {
  3331. return new Path.Rectangle({
  3332. rectangle: this.getInternalBounds(),
  3333. matrix: this._matrix,
  3334. insert: false,
  3335. });
  3336. },
  3337. intersects: function(item, _matrix) {
  3338. if (!(item instanceof Item))
  3339. return false;
  3340. return this._asPathItem().getIntersections(item._asPathItem(), null,
  3341. _matrix, true).length > 0;
  3342. }
  3343. },
  3344. new function() {
  3345. function hitTest() {
  3346. return this._hitTest(
  3347. Point.read(arguments),
  3348. HitResult.getOptions(arguments));
  3349. }
  3350. function hitTestAll() {
  3351. var point = Point.read(arguments),
  3352. options = HitResult.getOptions(arguments),
  3353. all = [];
  3354. this._hitTest(point, Base.set({ all: all }, options));
  3355. return all;
  3356. }
  3357. function hitTestChildren(point, options, viewMatrix, _exclude) {
  3358. var children = this._children;
  3359. if (children) {
  3360. for (var i = children.length - 1; i >= 0; i--) {
  3361. var child = children[i];
  3362. var res = child !== _exclude && child._hitTest(point, options,
  3363. viewMatrix);
  3364. if (res && !options.all)
  3365. return res;
  3366. }
  3367. }
  3368. return null;
  3369. }
  3370. Project.inject({
  3371. hitTest: hitTest,
  3372. hitTestAll: hitTestAll,
  3373. _hitTest: hitTestChildren
  3374. });
  3375. return {
  3376. hitTest: hitTest,
  3377. hitTestAll: hitTestAll,
  3378. _hitTestChildren: hitTestChildren,
  3379. };
  3380. }, {
  3381. _hitTest: function(point, options, parentViewMatrix) {
  3382. if (this._locked || !this._visible || this._guide && !options.guides
  3383. || this.isEmpty()) {
  3384. return null;
  3385. }
  3386. var matrix = this._matrix,
  3387. viewMatrix = parentViewMatrix
  3388. ? parentViewMatrix.appended(matrix)
  3389. : this.getGlobalMatrix().prepend(this.getView()._matrix),
  3390. tolerance = Math.max(options.tolerance, 1e-12),
  3391. tolerancePadding = options._tolerancePadding = new Size(
  3392. Path._getStrokePadding(tolerance,
  3393. matrix._shiftless().invert()));
  3394. point = matrix._inverseTransform(point);
  3395. if (!point || !this._children &&
  3396. !this.getBounds({ internal: true, stroke: true, handle: true })
  3397. .expand(tolerancePadding.multiply(2))._containsPoint(point)) {
  3398. return null;
  3399. }
  3400. var checkSelf = !(options.guides && !this._guide
  3401. || options.selected && !this.isSelected()
  3402. || options.type && options.type !== Base.hyphenate(this._class)
  3403. || options.class && !(this instanceof options.class)),
  3404. match = options.match,
  3405. that = this,
  3406. bounds,
  3407. res;
  3408. function filter(hit) {
  3409. if (hit && match && !match(hit))
  3410. hit = null;
  3411. if (hit && options.all)
  3412. options.all.push(hit);
  3413. return hit;
  3414. }
  3415. function checkPoint(type, part) {
  3416. var pt = part ? bounds['get' + part]() : that.getPosition();
  3417. if (point.subtract(pt).divide(tolerancePadding).length <= 1) {
  3418. return new HitResult(type, that, {
  3419. name: part ? Base.hyphenate(part) : type,
  3420. point: pt
  3421. });
  3422. }
  3423. }
  3424. var checkPosition = options.position,
  3425. checkCenter = options.center,
  3426. checkBounds = options.bounds;
  3427. if (checkSelf && this._parent
  3428. && (checkPosition || checkCenter || checkBounds)) {
  3429. if (checkCenter || checkBounds) {
  3430. bounds = this.getInternalBounds();
  3431. }
  3432. res = checkPosition && checkPoint('position') ||
  3433. checkCenter && checkPoint('center', 'Center');
  3434. if (!res && checkBounds) {
  3435. var points = [
  3436. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  3437. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
  3438. ];
  3439. for (var i = 0; i < 8 && !res; i++) {
  3440. res = checkPoint('bounds', points[i]);
  3441. }
  3442. }
  3443. res = filter(res);
  3444. }
  3445. if (!res) {
  3446. res = this._hitTestChildren(point, options, viewMatrix)
  3447. || checkSelf
  3448. && filter(this._hitTestSelf(point, options, viewMatrix,
  3449. this.getStrokeScaling() ? null
  3450. : viewMatrix._shiftless().invert()))
  3451. || null;
  3452. }
  3453. if (res && res.point) {
  3454. res.point = matrix.transform(res.point);
  3455. }
  3456. return res;
  3457. },
  3458. _hitTestSelf: function(point, options) {
  3459. if (options.fill && this.hasFill() && this._contains(point))
  3460. return new HitResult('fill', this);
  3461. },
  3462. matches: function(name, compare) {
  3463. function matchObject(obj1, obj2) {
  3464. for (var i in obj1) {
  3465. if (obj1.hasOwnProperty(i)) {
  3466. var val1 = obj1[i],
  3467. val2 = obj2[i];
  3468. if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
  3469. if (!matchObject(val1, val2))
  3470. return false;
  3471. } else if (!Base.equals(val1, val2)) {
  3472. return false;
  3473. }
  3474. }
  3475. }
  3476. return true;
  3477. }
  3478. var type = typeof name;
  3479. if (type === 'object') {
  3480. for (var key in name) {
  3481. if (name.hasOwnProperty(key) && !this.matches(key, name[key]))
  3482. return false;
  3483. }
  3484. return true;
  3485. } else if (type === 'function') {
  3486. return name(this);
  3487. } else if (name === 'match') {
  3488. return compare(this);
  3489. } else {
  3490. var value = /^(empty|editable)$/.test(name)
  3491. ? this['is' + Base.capitalize(name)]()
  3492. : name === 'type'
  3493. ? Base.hyphenate(this._class)
  3494. : this[name];
  3495. if (name === 'class') {
  3496. if (typeof compare === 'function')
  3497. return this instanceof compare;
  3498. value = this._class;
  3499. }
  3500. if (typeof compare === 'function') {
  3501. return !!compare(value);
  3502. } else if (compare) {
  3503. if (compare.test) {
  3504. return compare.test(value);
  3505. } else if (Base.isPlainObject(compare)) {
  3506. return matchObject(compare, value);
  3507. }
  3508. }
  3509. return Base.equals(value, compare);
  3510. }
  3511. },
  3512. getItems: function(options) {
  3513. return Item._getItems(this, options, this._matrix);
  3514. },
  3515. getItem: function(options) {
  3516. return Item._getItems(this, options, this._matrix, null, true)[0]
  3517. || null;
  3518. },
  3519. statics: {
  3520. _getItems: function _getItems(item, options, matrix, param, firstOnly) {
  3521. if (!param) {
  3522. var obj = typeof options === 'object' && options,
  3523. overlapping = obj && obj.overlapping,
  3524. inside = obj && obj.inside,
  3525. bounds = overlapping || inside,
  3526. rect = bounds && Rectangle.read([bounds]);
  3527. param = {
  3528. items: [],
  3529. recursive: obj && obj.recursive !== false,
  3530. inside: !!inside,
  3531. overlapping: !!overlapping,
  3532. rect: rect,
  3533. path: overlapping && new Path.Rectangle({
  3534. rectangle: rect,
  3535. insert: false
  3536. })
  3537. };
  3538. if (obj) {
  3539. options = Base.filter({}, options, {
  3540. recursive: true, inside: true, overlapping: true
  3541. });
  3542. }
  3543. }
  3544. var children = item._children,
  3545. items = param.items,
  3546. rect = param.rect;
  3547. matrix = rect && (matrix || new Matrix());
  3548. for (var i = 0, l = children && children.length; i < l; i++) {
  3549. var child = children[i],
  3550. childMatrix = matrix && matrix.appended(child._matrix),
  3551. add = true;
  3552. if (rect) {
  3553. var bounds = child.getBounds(childMatrix);
  3554. if (!rect.intersects(bounds))
  3555. continue;
  3556. if (!(rect.contains(bounds)
  3557. || param.overlapping && (bounds.contains(rect)
  3558. || param.path.intersects(child, childMatrix))))
  3559. add = false;
  3560. }
  3561. if (add && child.matches(options)) {
  3562. items.push(child);
  3563. if (firstOnly)
  3564. break;
  3565. }
  3566. if (param.recursive !== false) {
  3567. _getItems(child, options, childMatrix, param, firstOnly);
  3568. }
  3569. if (firstOnly && items.length > 0)
  3570. break;
  3571. }
  3572. return items;
  3573. }
  3574. }
  3575. }, {
  3576. importJSON: function(json) {
  3577. var res = Base.importJSON(json, this);
  3578. return res !== this ? this.addChild(res) : res;
  3579. },
  3580. addChild: function(item) {
  3581. return this.insertChild(undefined, item);
  3582. },
  3583. insertChild: function(index, item) {
  3584. var res = item ? this.insertChildren(index, [item]) : null;
  3585. return res && res[0];
  3586. },
  3587. addChildren: function(items) {
  3588. return this.insertChildren(this._children.length, items);
  3589. },
  3590. insertChildren: function(index, items) {
  3591. var children = this._children;
  3592. if (children && items && items.length > 0) {
  3593. items = Base.slice(items);
  3594. var inserted = {};
  3595. for (var i = items.length - 1; i >= 0; i--) {
  3596. var item = items[i],
  3597. id = item && item._id;
  3598. if (!item || inserted[id]) {
  3599. items.splice(i, 1);
  3600. } else {
  3601. item._remove(false, true);
  3602. inserted[id] = true;
  3603. }
  3604. }
  3605. Base.splice(children, items, index, 0);
  3606. var project = this._project,
  3607. notifySelf = project._changes;
  3608. for (var i = 0, l = items.length; i < l; i++) {
  3609. var item = items[i],
  3610. name = item._name;
  3611. item._parent = this;
  3612. item._setProject(project, true);
  3613. if (name)
  3614. item.setName(name);
  3615. if (notifySelf)
  3616. item._changed(5);
  3617. }
  3618. this._changed(11);
  3619. } else {
  3620. items = null;
  3621. }
  3622. return items;
  3623. },
  3624. _insertItem: '#insertChild',
  3625. _insertAt: function(item, offset) {
  3626. var owner = item && item._getOwner(),
  3627. res = item !== this && owner ? this : null;
  3628. if (res) {
  3629. res._remove(false, true);
  3630. owner._insertItem(item._index + offset, res);
  3631. }
  3632. return res;
  3633. },
  3634. insertAbove: function(item) {
  3635. return this._insertAt(item, 1);
  3636. },
  3637. insertBelow: function(item) {
  3638. return this._insertAt(item, 0);
  3639. },
  3640. sendToBack: function() {
  3641. var owner = this._getOwner();
  3642. return owner ? owner._insertItem(0, this) : null;
  3643. },
  3644. bringToFront: function() {
  3645. var owner = this._getOwner();
  3646. return owner ? owner._insertItem(undefined, this) : null;
  3647. },
  3648. appendTop: '#addChild',
  3649. appendBottom: function(item) {
  3650. return this.insertChild(0, item);
  3651. },
  3652. moveAbove: '#insertAbove',
  3653. moveBelow: '#insertBelow',
  3654. addTo: function(owner) {
  3655. return owner._insertItem(undefined, this);
  3656. },
  3657. copyTo: function(owner) {
  3658. return this.clone(false).addTo(owner);
  3659. },
  3660. reduce: function(options) {
  3661. var children = this._children;
  3662. if (children && children.length === 1) {
  3663. var child = children[0].reduce(options);
  3664. if (this._parent) {
  3665. child.insertAbove(this);
  3666. this.remove();
  3667. } else {
  3668. child.remove();
  3669. }
  3670. return child;
  3671. }
  3672. return this;
  3673. },
  3674. _removeNamed: function() {
  3675. var owner = this._getOwner();
  3676. if (owner) {
  3677. var children = owner._children,
  3678. namedChildren = owner._namedChildren,
  3679. name = this._name,
  3680. namedArray = namedChildren[name],
  3681. index = namedArray ? namedArray.indexOf(this) : -1;
  3682. if (index !== -1) {
  3683. if (children[name] == this)
  3684. delete children[name];
  3685. namedArray.splice(index, 1);
  3686. if (namedArray.length) {
  3687. children[name] = namedArray[0];
  3688. } else {
  3689. delete namedChildren[name];
  3690. }
  3691. }
  3692. }
  3693. },
  3694. _remove: function(notifySelf, notifyParent) {
  3695. var owner = this._getOwner(),
  3696. project = this._project,
  3697. index = this._index;
  3698. if (this._style)
  3699. this._style._dispose();
  3700. if (owner) {
  3701. if (this._name)
  3702. this._removeNamed();
  3703. if (index != null) {
  3704. if (project._activeLayer === this)
  3705. project._activeLayer = this.getNextSibling()
  3706. || this.getPreviousSibling();
  3707. Base.splice(owner._children, null, index, 1);
  3708. }
  3709. this._installEvents(false);
  3710. if (notifySelf && project._changes)
  3711. this._changed(5);
  3712. if (notifyParent)
  3713. owner._changed(11, this);
  3714. this._parent = null;
  3715. return true;
  3716. }
  3717. return false;
  3718. },
  3719. remove: function() {
  3720. return this._remove(true, true);
  3721. },
  3722. replaceWith: function(item) {
  3723. var ok = item && item.insertBelow(this);
  3724. if (ok)
  3725. this.remove();
  3726. return ok;
  3727. },
  3728. removeChildren: function(start, end) {
  3729. if (!this._children)
  3730. return null;
  3731. start = start || 0;
  3732. end = Base.pick(end, this._children.length);
  3733. var removed = Base.splice(this._children, null, start, end - start);
  3734. for (var i = removed.length - 1; i >= 0; i--) {
  3735. removed[i]._remove(true, false);
  3736. }
  3737. if (removed.length > 0)
  3738. this._changed(11);
  3739. return removed;
  3740. },
  3741. clear: '#removeChildren',
  3742. reverseChildren: function() {
  3743. if (this._children) {
  3744. this._children.reverse();
  3745. for (var i = 0, l = this._children.length; i < l; i++)
  3746. this._children[i]._index = i;
  3747. this._changed(11);
  3748. }
  3749. },
  3750. isEmpty: function() {
  3751. var children = this._children;
  3752. return !children || !children.length;
  3753. },
  3754. isEditable: function() {
  3755. var item = this;
  3756. while (item) {
  3757. if (!item._visible || item._locked)
  3758. return false;
  3759. item = item._parent;
  3760. }
  3761. return true;
  3762. },
  3763. hasFill: function() {
  3764. return this.getStyle().hasFill();
  3765. },
  3766. hasStroke: function() {
  3767. return this.getStyle().hasStroke();
  3768. },
  3769. hasShadow: function() {
  3770. return this.getStyle().hasShadow();
  3771. },
  3772. _getOrder: function(item) {
  3773. function getList(item) {
  3774. var list = [];
  3775. do {
  3776. list.unshift(item);
  3777. } while (item = item._parent);
  3778. return list;
  3779. }
  3780. var list1 = getList(this),
  3781. list2 = getList(item);
  3782. for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
  3783. if (list1[i] != list2[i]) {
  3784. return list1[i]._index < list2[i]._index ? 1 : -1;
  3785. }
  3786. }
  3787. return 0;
  3788. },
  3789. hasChildren: function() {
  3790. return this._children && this._children.length > 0;
  3791. },
  3792. isInserted: function() {
  3793. return this._parent ? this._parent.isInserted() : false;
  3794. },
  3795. isAbove: function(item) {
  3796. return this._getOrder(item) === -1;
  3797. },
  3798. isBelow: function(item) {
  3799. return this._getOrder(item) === 1;
  3800. },
  3801. isParent: function(item) {
  3802. return this._parent === item;
  3803. },
  3804. isChild: function(item) {
  3805. return item && item._parent === this;
  3806. },
  3807. isDescendant: function(item) {
  3808. var parent = this;
  3809. while (parent = parent._parent) {
  3810. if (parent === item)
  3811. return true;
  3812. }
  3813. return false;
  3814. },
  3815. isAncestor: function(item) {
  3816. return item ? item.isDescendant(this) : false;
  3817. },
  3818. isSibling: function(item) {
  3819. return this._parent === item._parent;
  3820. },
  3821. isGroupedWith: function(item) {
  3822. var parent = this._parent;
  3823. while (parent) {
  3824. if (parent._parent
  3825. && /^(Group|Layer|CompoundPath)$/.test(parent._class)
  3826. && item.isDescendant(parent))
  3827. return true;
  3828. parent = parent._parent;
  3829. }
  3830. return false;
  3831. },
  3832. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  3833. var rotate = key === 'rotate';
  3834. this[key] = function() {
  3835. var value = (rotate ? Base : Point).read(arguments),
  3836. center = Point.read(arguments, 0, { readNull: true });
  3837. return this.transform(new Matrix()[key](value,
  3838. center || this.getPosition(true)));
  3839. };
  3840. }, {
  3841. translate: function() {
  3842. var mx = new Matrix();
  3843. return this.transform(mx.translate.apply(mx, arguments));
  3844. },
  3845. transform: function(matrix, _applyMatrix, _applyRecursively,
  3846. _setApplyMatrix) {
  3847. var _matrix = this._matrix,
  3848. transformMatrix = matrix && !matrix.isIdentity(),
  3849. applyMatrix = (_applyMatrix || this._applyMatrix)
  3850. && ((!_matrix.isIdentity() || transformMatrix)
  3851. || _applyMatrix && _applyRecursively && this._children);
  3852. if (!transformMatrix && !applyMatrix)
  3853. return this;
  3854. if (transformMatrix) {
  3855. if (!matrix.isInvertible() && _matrix.isInvertible())
  3856. _matrix._backup = _matrix.getValues();
  3857. _matrix.prepend(matrix, true);
  3858. var style = this._style,
  3859. fillColor = style.getFillColor(true),
  3860. strokeColor = style.getStrokeColor(true);
  3861. if (fillColor)
  3862. fillColor.transform(matrix);
  3863. if (strokeColor)
  3864. strokeColor.transform(matrix);
  3865. }
  3866. if (applyMatrix && (applyMatrix = this._transformContent(_matrix,
  3867. _applyRecursively, _setApplyMatrix))) {
  3868. var pivot = this._pivot;
  3869. if (pivot)
  3870. _matrix._transformPoint(pivot, pivot, true);
  3871. _matrix.reset(true);
  3872. if (_setApplyMatrix && this._canApplyMatrix)
  3873. this._applyMatrix = true;
  3874. }
  3875. var bounds = this._bounds,
  3876. position = this._position;
  3877. if (transformMatrix || applyMatrix) {
  3878. this._changed(25);
  3879. }
  3880. var decomp = transformMatrix && bounds && matrix.decompose();
  3881. if (decomp && decomp.skewing.isZero() && decomp.rotation % 90 === 0) {
  3882. for (var key in bounds) {
  3883. var cache = bounds[key];
  3884. if (cache.nonscaling) {
  3885. delete bounds[key];
  3886. } else if (applyMatrix || !cache.internal) {
  3887. var rect = cache.rect;
  3888. matrix._transformBounds(rect, rect);
  3889. }
  3890. }
  3891. this._bounds = bounds;
  3892. var cached = bounds[this._getBoundsCacheKey(
  3893. this._boundsOptions || {})];
  3894. if (cached) {
  3895. this._position = this._getPositionFromBounds(cached.rect);
  3896. }
  3897. } else if (transformMatrix && position && this._pivot) {
  3898. this._position = matrix._transformPoint(position, position);
  3899. }
  3900. return this;
  3901. },
  3902. _transformContent: function(matrix, applyRecursively, setApplyMatrix) {
  3903. var children = this._children;
  3904. if (children) {
  3905. for (var i = 0, l = children.length; i < l; i++)
  3906. children[i].transform(matrix, true, applyRecursively,
  3907. setApplyMatrix);
  3908. return true;
  3909. }
  3910. },
  3911. globalToLocal: function() {
  3912. return this.getGlobalMatrix(true)._inverseTransform(
  3913. Point.read(arguments));
  3914. },
  3915. localToGlobal: function() {
  3916. return this.getGlobalMatrix(true)._transformPoint(
  3917. Point.read(arguments));
  3918. },
  3919. parentToLocal: function() {
  3920. return this._matrix._inverseTransform(Point.read(arguments));
  3921. },
  3922. localToParent: function() {
  3923. return this._matrix._transformPoint(Point.read(arguments));
  3924. },
  3925. fitBounds: function(rectangle, fill) {
  3926. rectangle = Rectangle.read(arguments);
  3927. var bounds = this.getBounds(),
  3928. itemRatio = bounds.height / bounds.width,
  3929. rectRatio = rectangle.height / rectangle.width,
  3930. scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
  3931. ? rectangle.width / bounds.width
  3932. : rectangle.height / bounds.height,
  3933. newBounds = new Rectangle(new Point(),
  3934. new Size(bounds.width * scale, bounds.height * scale));
  3935. newBounds.setCenter(rectangle.getCenter());
  3936. this.setBounds(newBounds);
  3937. }
  3938. }), {
  3939. _setStyles: function(ctx, param, viewMatrix) {
  3940. var style = this._style,
  3941. matrix = this._matrix;
  3942. if (style.hasFill()) {
  3943. ctx.fillStyle = style.getFillColor().toCanvasStyle(ctx, matrix);
  3944. }
  3945. if (style.hasStroke()) {
  3946. ctx.strokeStyle = style.getStrokeColor().toCanvasStyle(ctx, matrix);
  3947. ctx.lineWidth = style.getStrokeWidth();
  3948. var strokeJoin = style.getStrokeJoin(),
  3949. strokeCap = style.getStrokeCap(),
  3950. miterLimit = style.getMiterLimit();
  3951. if (strokeJoin)
  3952. ctx.lineJoin = strokeJoin;
  3953. if (strokeCap)
  3954. ctx.lineCap = strokeCap;
  3955. if (miterLimit)
  3956. ctx.miterLimit = miterLimit;
  3957. if (paper.support.nativeDash) {
  3958. var dashArray = style.getDashArray(),
  3959. dashOffset = style.getDashOffset();
  3960. if (dashArray && dashArray.length) {
  3961. if ('setLineDash' in ctx) {
  3962. ctx.setLineDash(dashArray);
  3963. ctx.lineDashOffset = dashOffset;
  3964. } else {
  3965. ctx.mozDash = dashArray;
  3966. ctx.mozDashOffset = dashOffset;
  3967. }
  3968. }
  3969. }
  3970. }
  3971. if (style.hasShadow()) {
  3972. var pixelRatio = param.pixelRatio || 1,
  3973. mx = viewMatrix._shiftless().prepend(
  3974. new Matrix().scale(pixelRatio, pixelRatio)),
  3975. blur = mx.transform(new Point(style.getShadowBlur(), 0)),
  3976. offset = mx.transform(this.getShadowOffset());
  3977. ctx.shadowColor = style.getShadowColor().toCanvasStyle(ctx);
  3978. ctx.shadowBlur = blur.getLength();
  3979. ctx.shadowOffsetX = offset.x;
  3980. ctx.shadowOffsetY = offset.y;
  3981. }
  3982. },
  3983. draw: function(ctx, param, parentStrokeMatrix) {
  3984. var updateVersion = this._updateVersion = this._project._updateVersion;
  3985. if (!this._visible || this._opacity === 0)
  3986. return;
  3987. var matrices = param.matrices,
  3988. viewMatrix = param.viewMatrix,
  3989. matrix = this._matrix,
  3990. globalMatrix = matrices[matrices.length - 1].appended(matrix);
  3991. if (!globalMatrix.isInvertible())
  3992. return;
  3993. viewMatrix = viewMatrix ? viewMatrix.appended(globalMatrix)
  3994. : globalMatrix;
  3995. matrices.push(globalMatrix);
  3996. if (param.updateMatrix) {
  3997. this._globalMatrix = globalMatrix;
  3998. }
  3999. var blendMode = this._blendMode,
  4000. opacity = this._opacity,
  4001. normalBlend = blendMode === 'normal',
  4002. nativeBlend = BlendMode.nativeModes[blendMode],
  4003. direct = normalBlend && opacity === 1
  4004. || param.dontStart
  4005. || param.clip
  4006. || (nativeBlend || normalBlend && opacity < 1)
  4007. && this._canComposite(),
  4008. pixelRatio = param.pixelRatio || 1,
  4009. mainCtx, itemOffset, prevOffset;
  4010. if (!direct) {
  4011. var bounds = this.getStrokeBounds(viewMatrix);
  4012. if (!bounds.width || !bounds.height) {
  4013. matrices.pop();
  4014. return;
  4015. }
  4016. prevOffset = param.offset;
  4017. itemOffset = param.offset = bounds.getTopLeft().floor();
  4018. mainCtx = ctx;
  4019. ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1)
  4020. .multiply(pixelRatio));
  4021. if (pixelRatio !== 1)
  4022. ctx.scale(pixelRatio, pixelRatio);
  4023. }
  4024. ctx.save();
  4025. var strokeMatrix = parentStrokeMatrix
  4026. ? parentStrokeMatrix.appended(matrix)
  4027. : this._canScaleStroke && !this.getStrokeScaling(true)
  4028. && viewMatrix,
  4029. clip = !direct && param.clipItem,
  4030. transform = !strokeMatrix || clip;
  4031. if (direct) {
  4032. ctx.globalAlpha = opacity;
  4033. if (nativeBlend)
  4034. ctx.globalCompositeOperation = blendMode;
  4035. } else if (transform) {
  4036. ctx.translate(-itemOffset.x, -itemOffset.y);
  4037. }
  4038. if (transform) {
  4039. (direct ? matrix : viewMatrix).applyToContext(ctx);
  4040. }
  4041. if (clip) {
  4042. param.clipItem.draw(ctx, param.extend({ clip: true }));
  4043. }
  4044. if (strokeMatrix) {
  4045. ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  4046. var offset = param.offset;
  4047. if (offset)
  4048. ctx.translate(-offset.x, -offset.y);
  4049. }
  4050. this._draw(ctx, param, viewMatrix, strokeMatrix);
  4051. ctx.restore();
  4052. matrices.pop();
  4053. if (param.clip && !param.dontFinish)
  4054. ctx.clip();
  4055. if (!direct) {
  4056. BlendMode.process(blendMode, ctx, mainCtx, opacity,
  4057. itemOffset.subtract(prevOffset).multiply(pixelRatio));
  4058. CanvasProvider.release(ctx);
  4059. param.offset = prevOffset;
  4060. }
  4061. },
  4062. _isUpdated: function(updateVersion) {
  4063. var parent = this._parent;
  4064. if (parent instanceof CompoundPath)
  4065. return parent._isUpdated(updateVersion);
  4066. var updated = this._updateVersion === updateVersion;
  4067. if (!updated && parent && parent._visible
  4068. && parent._isUpdated(updateVersion)) {
  4069. this._updateVersion = updateVersion;
  4070. updated = true;
  4071. }
  4072. return updated;
  4073. },
  4074. _drawSelection: function(ctx, matrix, size, selectionItems, updateVersion) {
  4075. var selection = this._selection,
  4076. itemSelected = selection & 1,
  4077. boundsSelected = selection & 2
  4078. || itemSelected && this._selectBounds,
  4079. positionSelected = selection & 4;
  4080. if (!this._drawSelected)
  4081. itemSelected = false;
  4082. if ((itemSelected || boundsSelected || positionSelected)
  4083. && this._isUpdated(updateVersion)) {
  4084. var layer,
  4085. color = this.getSelectedColor(true) || (layer = this.getLayer())
  4086. && layer.getSelectedColor(true),
  4087. mx = matrix.appended(this.getGlobalMatrix(true)),
  4088. half = size / 2;
  4089. ctx.strokeStyle = ctx.fillStyle = color
  4090. ? color.toCanvasStyle(ctx) : '#009dec';
  4091. if (itemSelected)
  4092. this._drawSelected(ctx, mx, selectionItems);
  4093. if (positionSelected) {
  4094. var pos = this.getPosition(true),
  4095. parent = this._parent,
  4096. point = parent ? parent.localToGlobal(pos) : pos,
  4097. x = point.x,
  4098. y = point.y;
  4099. ctx.beginPath();
  4100. ctx.arc(x, y, half, 0, Math.PI * 2, true);
  4101. ctx.stroke();
  4102. var deltas = [[0, -1], [1, 0], [0, 1], [-1, 0]],
  4103. start = half,
  4104. end = size + 1;
  4105. for (var i = 0; i < 4; i++) {
  4106. var delta = deltas[i],
  4107. dx = delta[0],
  4108. dy = delta[1];
  4109. ctx.moveTo(x + dx * start, y + dy * start);
  4110. ctx.lineTo(x + dx * end, y + dy * end);
  4111. ctx.stroke();
  4112. }
  4113. }
  4114. if (boundsSelected) {
  4115. var coords = mx._transformCorners(this.getInternalBounds());
  4116. ctx.beginPath();
  4117. for (var i = 0; i < 8; i++) {
  4118. ctx[!i ? 'moveTo' : 'lineTo'](coords[i], coords[++i]);
  4119. }
  4120. ctx.closePath();
  4121. ctx.stroke();
  4122. for (var i = 0; i < 8; i++) {
  4123. ctx.fillRect(coords[i] - half, coords[++i] - half,
  4124. size, size);
  4125. }
  4126. }
  4127. }
  4128. },
  4129. _canComposite: function() {
  4130. return false;
  4131. }
  4132. }, Base.each(['down', 'drag', 'up', 'move'], function(key) {
  4133. this['removeOn' + Base.capitalize(key)] = function() {
  4134. var hash = {};
  4135. hash[key] = true;
  4136. return this.removeOn(hash);
  4137. };
  4138. }, {
  4139. removeOn: function(obj) {
  4140. for (var name in obj) {
  4141. if (obj[name]) {
  4142. var key = 'mouse' + name,
  4143. project = this._project,
  4144. sets = project._removeSets = project._removeSets || {};
  4145. sets[key] = sets[key] || {};
  4146. sets[key][this._id] = this;
  4147. }
  4148. }
  4149. return this;
  4150. }
  4151. }), {
  4152. tween: function(from, to, options) {
  4153. if (!options) {
  4154. options = to;
  4155. to = from;
  4156. from = null;
  4157. if (!options) {
  4158. options = to;
  4159. to = null;
  4160. }
  4161. }
  4162. var easing = options && options.easing,
  4163. start = options && options.start,
  4164. duration = options != null && (
  4165. typeof options === 'number' ? options : options.duration
  4166. ),
  4167. tween = new Tween(this, from, to, duration, easing, start);
  4168. function onFrame(event) {
  4169. tween._handleFrame(event.time * 1000);
  4170. if (!tween.running) {
  4171. this.off('frame', onFrame);
  4172. }
  4173. }
  4174. if (duration) {
  4175. this.on('frame', onFrame);
  4176. }
  4177. return tween;
  4178. },
  4179. tweenTo: function(to, options) {
  4180. return this.tween(null, to, options);
  4181. },
  4182. tweenFrom: function(from, options) {
  4183. return this.tween(from, null, options);
  4184. }
  4185. });
  4186. var Group = Item.extend({
  4187. _class: 'Group',
  4188. _selectBounds: false,
  4189. _selectChildren: true,
  4190. _serializeFields: {
  4191. children: []
  4192. },
  4193. initialize: function Group(arg) {
  4194. this._children = [];
  4195. this._namedChildren = {};
  4196. if (!this._initialize(arg))
  4197. this.addChildren(Array.isArray(arg) ? arg : arguments);
  4198. },
  4199. _changed: function _changed(flags) {
  4200. _changed.base.call(this, flags);
  4201. if (flags & 2050) {
  4202. this._clipItem = undefined;
  4203. }
  4204. },
  4205. _getClipItem: function() {
  4206. var clipItem = this._clipItem;
  4207. if (clipItem === undefined) {
  4208. clipItem = null;
  4209. var children = this._children;
  4210. for (var i = 0, l = children.length; i < l; i++) {
  4211. if (children[i]._clipMask) {
  4212. clipItem = children[i];
  4213. break;
  4214. }
  4215. }
  4216. this._clipItem = clipItem;
  4217. }
  4218. return clipItem;
  4219. },
  4220. isClipped: function() {
  4221. return !!this._getClipItem();
  4222. },
  4223. setClipped: function(clipped) {
  4224. var child = this.getFirstChild();
  4225. if (child)
  4226. child.setClipMask(clipped);
  4227. },
  4228. _getBounds: function _getBounds(matrix, options) {
  4229. var clipItem = this._getClipItem();
  4230. return clipItem
  4231. ? clipItem._getCachedBounds(
  4232. matrix && matrix.appended(clipItem._matrix),
  4233. Base.set({}, options, { stroke: false }))
  4234. : _getBounds.base.call(this, matrix, options);
  4235. },
  4236. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  4237. var clipItem = this._getClipItem();
  4238. return (!clipItem || clipItem.contains(point))
  4239. && _hitTestChildren.base.call(this, point, options, viewMatrix,
  4240. clipItem);
  4241. },
  4242. _draw: function(ctx, param) {
  4243. var clip = param.clip,
  4244. clipItem = !clip && this._getClipItem();
  4245. param = param.extend({ clipItem: clipItem, clip: false });
  4246. if (clip) {
  4247. ctx.beginPath();
  4248. param.dontStart = param.dontFinish = true;
  4249. } else if (clipItem) {
  4250. clipItem.draw(ctx, param.extend({ clip: true }));
  4251. }
  4252. var children = this._children;
  4253. for (var i = 0, l = children.length; i < l; i++) {
  4254. var item = children[i];
  4255. if (item !== clipItem)
  4256. item.draw(ctx, param);
  4257. }
  4258. }
  4259. });
  4260. var Layer = Group.extend({
  4261. _class: 'Layer',
  4262. initialize: function Layer() {
  4263. Group.apply(this, arguments);
  4264. },
  4265. _getOwner: function() {
  4266. return this._parent || this._index != null && this._project;
  4267. },
  4268. isInserted: function isInserted() {
  4269. return this._parent ? isInserted.base.call(this) : this._index != null;
  4270. },
  4271. activate: function() {
  4272. this._project._activeLayer = this;
  4273. },
  4274. _hitTestSelf: function() {
  4275. }
  4276. });
  4277. var Shape = Item.extend({
  4278. _class: 'Shape',
  4279. _applyMatrix: false,
  4280. _canApplyMatrix: false,
  4281. _canScaleStroke: true,
  4282. _serializeFields: {
  4283. type: null,
  4284. size: null,
  4285. radius: null
  4286. },
  4287. initialize: function Shape(props, point) {
  4288. this._initialize(props, point);
  4289. },
  4290. _equals: function(item) {
  4291. return this._type === item._type
  4292. && this._size.equals(item._size)
  4293. && Base.equals(this._radius, item._radius);
  4294. },
  4295. copyContent: function(source) {
  4296. this.setType(source._type);
  4297. this.setSize(source._size);
  4298. this.setRadius(source._radius);
  4299. },
  4300. getType: function() {
  4301. return this._type;
  4302. },
  4303. setType: function(type) {
  4304. this._type = type;
  4305. },
  4306. getShape: '#getType',
  4307. setShape: '#setType',
  4308. getSize: function() {
  4309. var size = this._size;
  4310. return new LinkedSize(size.width, size.height, this, 'setSize');
  4311. },
  4312. setSize: function() {
  4313. var size = Size.read(arguments);
  4314. if (!this._size) {
  4315. this._size = size.clone();
  4316. } else if (!this._size.equals(size)) {
  4317. var type = this._type,
  4318. width = size.width,
  4319. height = size.height;
  4320. if (type === 'rectangle') {
  4321. this._radius.set(Size.min(this._radius, size.divide(2)));
  4322. } else if (type === 'circle') {
  4323. width = height = (width + height) / 2;
  4324. this._radius = width / 2;
  4325. } else if (type === 'ellipse') {
  4326. this._radius._set(width / 2, height / 2);
  4327. }
  4328. this._size._set(width, height);
  4329. this._changed(9);
  4330. }
  4331. },
  4332. getRadius: function() {
  4333. var rad = this._radius;
  4334. return this._type === 'circle'
  4335. ? rad
  4336. : new LinkedSize(rad.width, rad.height, this, 'setRadius');
  4337. },
  4338. setRadius: function(radius) {
  4339. var type = this._type;
  4340. if (type === 'circle') {
  4341. if (radius === this._radius)
  4342. return;
  4343. var size = radius * 2;
  4344. this._radius = radius;
  4345. this._size._set(size, size);
  4346. } else {
  4347. radius = Size.read(arguments);
  4348. if (!this._radius) {
  4349. this._radius = radius.clone();
  4350. } else {
  4351. if (this._radius.equals(radius))
  4352. return;
  4353. this._radius.set(radius);
  4354. if (type === 'rectangle') {
  4355. var size = Size.max(this._size, radius.multiply(2));
  4356. this._size.set(size);
  4357. } else if (type === 'ellipse') {
  4358. this._size._set(radius.width * 2, radius.height * 2);
  4359. }
  4360. }
  4361. }
  4362. this._changed(9);
  4363. },
  4364. isEmpty: function() {
  4365. return false;
  4366. },
  4367. toPath: function(insert) {
  4368. var path = new Path[Base.capitalize(this._type)]({
  4369. center: new Point(),
  4370. size: this._size,
  4371. radius: this._radius,
  4372. insert: false
  4373. });
  4374. path.copyAttributes(this);
  4375. if (paper.settings.applyMatrix)
  4376. path.setApplyMatrix(true);
  4377. if (insert === undefined || insert)
  4378. path.insertAbove(this);
  4379. return path;
  4380. },
  4381. toShape: '#clone',
  4382. _asPathItem: function() {
  4383. return this.toPath(false);
  4384. },
  4385. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  4386. var style = this._style,
  4387. hasFill = style.hasFill(),
  4388. hasStroke = style.hasStroke(),
  4389. dontPaint = param.dontFinish || param.clip,
  4390. untransformed = !strokeMatrix;
  4391. if (hasFill || hasStroke || dontPaint) {
  4392. var type = this._type,
  4393. radius = this._radius,
  4394. isCircle = type === 'circle';
  4395. if (!param.dontStart)
  4396. ctx.beginPath();
  4397. if (untransformed && isCircle) {
  4398. ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
  4399. } else {
  4400. var rx = isCircle ? radius : radius.width,
  4401. ry = isCircle ? radius : radius.height,
  4402. size = this._size,
  4403. width = size.width,
  4404. height = size.height;
  4405. if (untransformed && type === 'rectangle' && rx === 0 && ry === 0) {
  4406. ctx.rect(-width / 2, -height / 2, width, height);
  4407. } else {
  4408. var x = width / 2,
  4409. y = height / 2,
  4410. kappa = 1 - 0.5522847498307936,
  4411. cx = rx * kappa,
  4412. cy = ry * kappa,
  4413. c = [
  4414. -x, -y + ry,
  4415. -x, -y + cy,
  4416. -x + cx, -y,
  4417. -x + rx, -y,
  4418. x - rx, -y,
  4419. x - cx, -y,
  4420. x, -y + cy,
  4421. x, -y + ry,
  4422. x, y - ry,
  4423. x, y - cy,
  4424. x - cx, y,
  4425. x - rx, y,
  4426. -x + rx, y,
  4427. -x + cx, y,
  4428. -x, y - cy,
  4429. -x, y - ry
  4430. ];
  4431. if (strokeMatrix)
  4432. strokeMatrix.transform(c, c, 32);
  4433. ctx.moveTo(c[0], c[1]);
  4434. ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]);
  4435. if (x !== rx)
  4436. ctx.lineTo(c[8], c[9]);
  4437. ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]);
  4438. if (y !== ry)
  4439. ctx.lineTo(c[16], c[17]);
  4440. ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]);
  4441. if (x !== rx)
  4442. ctx.lineTo(c[24], c[25]);
  4443. ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]);
  4444. }
  4445. }
  4446. ctx.closePath();
  4447. }
  4448. if (!dontPaint && (hasFill || hasStroke)) {
  4449. this._setStyles(ctx, param, viewMatrix);
  4450. if (hasFill) {
  4451. ctx.fill(style.getFillRule());
  4452. ctx.shadowColor = 'rgba(0,0,0,0)';
  4453. }
  4454. if (hasStroke)
  4455. ctx.stroke();
  4456. }
  4457. },
  4458. _canComposite: function() {
  4459. return !(this.hasFill() && this.hasStroke());
  4460. },
  4461. _getBounds: function(matrix, options) {
  4462. var rect = new Rectangle(this._size).setCenter(0, 0),
  4463. style = this._style,
  4464. strokeWidth = options.stroke && style.hasStroke()
  4465. && style.getStrokeWidth();
  4466. if (matrix)
  4467. rect = matrix._transformBounds(rect);
  4468. return strokeWidth
  4469. ? rect.expand(Path._getStrokePadding(strokeWidth,
  4470. this._getStrokeMatrix(matrix, options)))
  4471. : rect;
  4472. }
  4473. },
  4474. new function() {
  4475. function getCornerCenter(that, point, expand) {
  4476. var radius = that._radius;
  4477. if (!radius.isZero()) {
  4478. var halfSize = that._size.divide(2);
  4479. for (var q = 1; q <= 4; q++) {
  4480. var dir = new Point(q > 1 && q < 4 ? -1 : 1, q > 2 ? -1 : 1),
  4481. corner = dir.multiply(halfSize),
  4482. center = corner.subtract(dir.multiply(radius)),
  4483. rect = new Rectangle(
  4484. expand ? corner.add(dir.multiply(expand)) : corner,
  4485. center);
  4486. if (rect.contains(point))
  4487. return { point: center, quadrant: q };
  4488. }
  4489. }
  4490. }
  4491. function isOnEllipseStroke(point, radius, padding, quadrant) {
  4492. var vector = point.divide(radius);
  4493. return (!quadrant || vector.isInQuadrant(quadrant)) &&
  4494. vector.subtract(vector.normalize()).multiply(radius)
  4495. .divide(padding).length <= 1;
  4496. }
  4497. return {
  4498. _contains: function _contains(point) {
  4499. if (this._type === 'rectangle') {
  4500. var center = getCornerCenter(this, point);
  4501. return center
  4502. ? point.subtract(center.point).divide(this._radius)
  4503. .getLength() <= 1
  4504. : _contains.base.call(this, point);
  4505. } else {
  4506. return point.divide(this.size).getLength() <= 0.5;
  4507. }
  4508. },
  4509. _hitTestSelf: function _hitTestSelf(point, options, viewMatrix,
  4510. strokeMatrix) {
  4511. var hit = false,
  4512. style = this._style,
  4513. hitStroke = options.stroke && style.hasStroke(),
  4514. hitFill = options.fill && style.hasFill();
  4515. if (hitStroke || hitFill) {
  4516. var type = this._type,
  4517. radius = this._radius,
  4518. strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : 0,
  4519. strokePadding = options._tolerancePadding.add(
  4520. Path._getStrokePadding(strokeRadius,
  4521. !style.getStrokeScaling() && strokeMatrix));
  4522. if (type === 'rectangle') {
  4523. var padding = strokePadding.multiply(2),
  4524. center = getCornerCenter(this, point, padding);
  4525. if (center) {
  4526. hit = isOnEllipseStroke(point.subtract(center.point),
  4527. radius, strokePadding, center.quadrant);
  4528. } else {
  4529. var rect = new Rectangle(this._size).setCenter(0, 0),
  4530. outer = rect.expand(padding),
  4531. inner = rect.expand(padding.negate());
  4532. hit = outer._containsPoint(point)
  4533. && !inner._containsPoint(point);
  4534. }
  4535. } else {
  4536. hit = isOnEllipseStroke(point, radius, strokePadding);
  4537. }
  4538. }
  4539. return hit ? new HitResult(hitStroke ? 'stroke' : 'fill', this)
  4540. : _hitTestSelf.base.apply(this, arguments);
  4541. }
  4542. };
  4543. }, {
  4544. statics: new function() {
  4545. function createShape(type, point, size, radius, args) {
  4546. var item = new Shape(Base.getNamed(args), point);
  4547. item._type = type;
  4548. item._size = size;
  4549. item._radius = radius;
  4550. return item;
  4551. }
  4552. return {
  4553. Circle: function() {
  4554. var center = Point.readNamed(arguments, 'center'),
  4555. radius = Base.readNamed(arguments, 'radius');
  4556. return createShape('circle', center, new Size(radius * 2), radius,
  4557. arguments);
  4558. },
  4559. Rectangle: function() {
  4560. var rect = Rectangle.readNamed(arguments, 'rectangle'),
  4561. radius = Size.min(Size.readNamed(arguments, 'radius'),
  4562. rect.getSize(true).divide(2));
  4563. return createShape('rectangle', rect.getCenter(true),
  4564. rect.getSize(true), radius, arguments);
  4565. },
  4566. Ellipse: function() {
  4567. var ellipse = Shape._readEllipse(arguments),
  4568. radius = ellipse.radius;
  4569. return createShape('ellipse', ellipse.center, radius.multiply(2),
  4570. radius, arguments);
  4571. },
  4572. _readEllipse: function(args) {
  4573. var center,
  4574. radius;
  4575. if (Base.hasNamed(args, 'radius')) {
  4576. center = Point.readNamed(args, 'center');
  4577. radius = Size.readNamed(args, 'radius');
  4578. } else {
  4579. var rect = Rectangle.readNamed(args, 'rectangle');
  4580. center = rect.getCenter(true);
  4581. radius = rect.getSize(true).divide(2);
  4582. }
  4583. return { center: center, radius: radius };
  4584. }
  4585. };
  4586. }});
  4587. var Raster = Item.extend({
  4588. _class: 'Raster',
  4589. _applyMatrix: false,
  4590. _canApplyMatrix: false,
  4591. _boundsOptions: { stroke: false, handle: false },
  4592. _serializeFields: {
  4593. crossOrigin: null,
  4594. source: null
  4595. },
  4596. _prioritize: ['crossOrigin'],
  4597. _smoothing: true,
  4598. initialize: function Raster(object, position) {
  4599. if (!this._initialize(object,
  4600. position !== undefined && Point.read(arguments, 1))) {
  4601. var image = typeof object === 'string'
  4602. ? document.getElementById(object) : object;
  4603. if (image) {
  4604. this.setImage(image);
  4605. } else {
  4606. this.setSource(object);
  4607. }
  4608. }
  4609. if (!this._size) {
  4610. this._size = new Size();
  4611. this._loaded = false;
  4612. }
  4613. },
  4614. _equals: function(item) {
  4615. return this.getSource() === item.getSource();
  4616. },
  4617. copyContent: function(source) {
  4618. var image = source._image,
  4619. canvas = source._canvas;
  4620. if (image) {
  4621. this._setImage(image);
  4622. } else if (canvas) {
  4623. var copyCanvas = CanvasProvider.getCanvas(source._size);
  4624. copyCanvas.getContext('2d').drawImage(canvas, 0, 0);
  4625. this._setImage(copyCanvas);
  4626. }
  4627. this._crossOrigin = source._crossOrigin;
  4628. },
  4629. getSize: function() {
  4630. var size = this._size;
  4631. return new LinkedSize(size ? size.width : 0, size ? size.height : 0,
  4632. this, 'setSize');
  4633. },
  4634. setSize: function() {
  4635. var size = Size.read(arguments);
  4636. if (!size.equals(this._size)) {
  4637. if (size.width > 0 && size.height > 0) {
  4638. var element = this.getElement();
  4639. this._setImage(CanvasProvider.getCanvas(size));
  4640. if (element)
  4641. this.getContext(true).drawImage(element, 0, 0,
  4642. size.width, size.height);
  4643. } else {
  4644. if (this._canvas)
  4645. CanvasProvider.release(this._canvas);
  4646. this._size = size.clone();
  4647. }
  4648. }
  4649. },
  4650. getWidth: function() {
  4651. return this._size ? this._size.width : 0;
  4652. },
  4653. setWidth: function(width) {
  4654. this.setSize(width, this.getHeight());
  4655. },
  4656. getHeight: function() {
  4657. return this._size ? this._size.height : 0;
  4658. },
  4659. setHeight: function(height) {
  4660. this.setSize(this.getWidth(), height);
  4661. },
  4662. getLoaded: function() {
  4663. return this._loaded;
  4664. },
  4665. isEmpty: function() {
  4666. var size = this._size;
  4667. return !size || size.width === 0 && size.height === 0;
  4668. },
  4669. getResolution: function() {
  4670. var matrix = this._matrix,
  4671. orig = new Point(0, 0).transform(matrix),
  4672. u = new Point(1, 0).transform(matrix).subtract(orig),
  4673. v = new Point(0, 1).transform(matrix).subtract(orig);
  4674. return new Size(
  4675. 72 / u.getLength(),
  4676. 72 / v.getLength()
  4677. );
  4678. },
  4679. getPpi: '#getResolution',
  4680. getImage: function() {
  4681. return this._image;
  4682. },
  4683. setImage: function(image) {
  4684. var that = this;
  4685. function emit(event) {
  4686. var view = that.getView(),
  4687. type = event && event.type || 'load';
  4688. if (view && that.responds(type)) {
  4689. paper = view._scope;
  4690. that.emit(type, new Event(event));
  4691. }
  4692. }
  4693. this._setImage(image);
  4694. if (this._loaded) {
  4695. setTimeout(emit, 0);
  4696. } else if (image) {
  4697. DomEvent.add(image, {
  4698. load: function(event) {
  4699. that._setImage(image);
  4700. emit(event);
  4701. },
  4702. error: emit
  4703. });
  4704. }
  4705. },
  4706. _setImage: function(image) {
  4707. if (this._canvas)
  4708. CanvasProvider.release(this._canvas);
  4709. if (image && image.getContext) {
  4710. this._image = null;
  4711. this._canvas = image;
  4712. this._loaded = true;
  4713. } else {
  4714. this._image = image;
  4715. this._canvas = null;
  4716. this._loaded = !!(image && image.src && image.complete);
  4717. }
  4718. this._size = new Size(
  4719. image ? image.naturalWidth || image.width : 0,
  4720. image ? image.naturalHeight || image.height : 0);
  4721. this._context = null;
  4722. this._changed(1033);
  4723. },
  4724. getCanvas: function() {
  4725. if (!this._canvas) {
  4726. var ctx = CanvasProvider.getContext(this._size);
  4727. try {
  4728. if (this._image)
  4729. ctx.drawImage(this._image, 0, 0);
  4730. this._canvas = ctx.canvas;
  4731. } catch (e) {
  4732. CanvasProvider.release(ctx);
  4733. }
  4734. }
  4735. return this._canvas;
  4736. },
  4737. setCanvas: '#setImage',
  4738. getContext: function(modify) {
  4739. if (!this._context)
  4740. this._context = this.getCanvas().getContext('2d');
  4741. if (modify) {
  4742. this._image = null;
  4743. this._changed(1025);
  4744. }
  4745. return this._context;
  4746. },
  4747. setContext: function(context) {
  4748. this._context = context;
  4749. },
  4750. getSource: function() {
  4751. var image = this._image;
  4752. return image && image.src || this.toDataURL();
  4753. },
  4754. setSource: function(src) {
  4755. var image = new self.Image(),
  4756. crossOrigin = this._crossOrigin;
  4757. if (crossOrigin)
  4758. image.crossOrigin = crossOrigin;
  4759. image.src = src;
  4760. this.setImage(image);
  4761. },
  4762. getCrossOrigin: function() {
  4763. var image = this._image;
  4764. return image && image.crossOrigin || this._crossOrigin || '';
  4765. },
  4766. setCrossOrigin: function(crossOrigin) {
  4767. this._crossOrigin = crossOrigin;
  4768. var image = this._image;
  4769. if (image)
  4770. image.crossOrigin = crossOrigin;
  4771. },
  4772. getSmoothing: function() {
  4773. return this._smoothing;
  4774. },
  4775. setSmoothing: function(smoothing) {
  4776. this._smoothing = smoothing;
  4777. this._changed(257);
  4778. },
  4779. getElement: function() {
  4780. return this._canvas || this._loaded && this._image;
  4781. }
  4782. }, {
  4783. beans: false,
  4784. getSubCanvas: function() {
  4785. var rect = Rectangle.read(arguments),
  4786. ctx = CanvasProvider.getContext(rect.getSize());
  4787. ctx.drawImage(this.getCanvas(), rect.x, rect.y,
  4788. rect.width, rect.height, 0, 0, rect.width, rect.height);
  4789. return ctx.canvas;
  4790. },
  4791. getSubRaster: function() {
  4792. var rect = Rectangle.read(arguments),
  4793. raster = new Raster(Item.NO_INSERT);
  4794. raster._setImage(this.getSubCanvas(rect));
  4795. raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
  4796. raster._matrix.prepend(this._matrix);
  4797. raster.insertAbove(this);
  4798. return raster;
  4799. },
  4800. toDataURL: function() {
  4801. var image = this._image,
  4802. src = image && image.src;
  4803. if (/^data:/.test(src))
  4804. return src;
  4805. var canvas = this.getCanvas();
  4806. return canvas ? canvas.toDataURL.apply(canvas, arguments) : null;
  4807. },
  4808. drawImage: function(image ) {
  4809. var point = Point.read(arguments, 1);
  4810. this.getContext(true).drawImage(image, point.x, point.y);
  4811. },
  4812. getAverageColor: function(object) {
  4813. var bounds, path;
  4814. if (!object) {
  4815. bounds = this.getBounds();
  4816. } else if (object instanceof PathItem) {
  4817. path = object;
  4818. bounds = object.getBounds();
  4819. } else if (typeof object === 'object') {
  4820. if ('width' in object) {
  4821. bounds = new Rectangle(object);
  4822. } else if ('x' in object) {
  4823. bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
  4824. }
  4825. }
  4826. if (!bounds)
  4827. return null;
  4828. var sampleSize = 32,
  4829. width = Math.min(bounds.width, sampleSize),
  4830. height = Math.min(bounds.height, sampleSize);
  4831. var ctx = Raster._sampleContext;
  4832. if (!ctx) {
  4833. ctx = Raster._sampleContext = CanvasProvider.getContext(
  4834. new Size(sampleSize));
  4835. } else {
  4836. ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
  4837. }
  4838. ctx.save();
  4839. var matrix = new Matrix()
  4840. .scale(width / bounds.width, height / bounds.height)
  4841. .translate(-bounds.x, -bounds.y);
  4842. matrix.applyToContext(ctx);
  4843. if (path)
  4844. path.draw(ctx, new Base({ clip: true, matrices: [matrix] }));
  4845. this._matrix.applyToContext(ctx);
  4846. var element = this.getElement(),
  4847. size = this._size;
  4848. if (element)
  4849. ctx.drawImage(element, -size.width / 2, -size.height / 2);
  4850. ctx.restore();
  4851. var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
  4852. Math.ceil(height)).data,
  4853. channels = [0, 0, 0],
  4854. total = 0;
  4855. for (var i = 0, l = pixels.length; i < l; i += 4) {
  4856. var alpha = pixels[i + 3];
  4857. total += alpha;
  4858. alpha /= 255;
  4859. channels[0] += pixels[i] * alpha;
  4860. channels[1] += pixels[i + 1] * alpha;
  4861. channels[2] += pixels[i + 2] * alpha;
  4862. }
  4863. for (var i = 0; i < 3; i++)
  4864. channels[i] /= total;
  4865. return total ? Color.read(channels) : null;
  4866. },
  4867. getPixel: function() {
  4868. var point = Point.read(arguments);
  4869. var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
  4870. return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
  4871. data[3] / 255);
  4872. },
  4873. setPixel: function() {
  4874. var point = Point.read(arguments),
  4875. color = Color.read(arguments),
  4876. components = color._convert('rgb'),
  4877. alpha = color._alpha,
  4878. ctx = this.getContext(true),
  4879. imageData = ctx.createImageData(1, 1),
  4880. data = imageData.data;
  4881. data[0] = components[0] * 255;
  4882. data[1] = components[1] * 255;
  4883. data[2] = components[2] * 255;
  4884. data[3] = alpha != null ? alpha * 255 : 255;
  4885. ctx.putImageData(imageData, point.x, point.y);
  4886. },
  4887. createImageData: function() {
  4888. var size = Size.read(arguments);
  4889. return this.getContext().createImageData(size.width, size.height);
  4890. },
  4891. getImageData: function() {
  4892. var rect = Rectangle.read(arguments);
  4893. if (rect.isEmpty())
  4894. rect = new Rectangle(this._size);
  4895. return this.getContext().getImageData(rect.x, rect.y,
  4896. rect.width, rect.height);
  4897. },
  4898. setImageData: function(data ) {
  4899. var point = Point.read(arguments, 1);
  4900. this.getContext(true).putImageData(data, point.x, point.y);
  4901. },
  4902. _getBounds: function(matrix, options) {
  4903. var rect = new Rectangle(this._size).setCenter(0, 0);
  4904. return matrix ? matrix._transformBounds(rect) : rect;
  4905. },
  4906. _hitTestSelf: function(point) {
  4907. if (this._contains(point)) {
  4908. var that = this;
  4909. return new HitResult('pixel', that, {
  4910. offset: point.add(that._size.divide(2)).round(),
  4911. color: {
  4912. get: function() {
  4913. return that.getPixel(this.offset);
  4914. }
  4915. }
  4916. });
  4917. }
  4918. },
  4919. _draw: function(ctx, param, viewMatrix) {
  4920. var element = this.getElement();
  4921. if (element && element.width > 0 && element.height > 0) {
  4922. ctx.globalAlpha = this._opacity;
  4923. this._setStyles(ctx, param, viewMatrix);
  4924. DomElement.setPrefixed(
  4925. ctx, 'imageSmoothingEnabled', this._smoothing
  4926. );
  4927. ctx.drawImage(element,
  4928. -this._size.width / 2, -this._size.height / 2);
  4929. }
  4930. },
  4931. _canComposite: function() {
  4932. return true;
  4933. }
  4934. });
  4935. var SymbolItem = Item.extend({
  4936. _class: 'SymbolItem',
  4937. _applyMatrix: false,
  4938. _canApplyMatrix: false,
  4939. _boundsOptions: { stroke: true },
  4940. _serializeFields: {
  4941. symbol: null
  4942. },
  4943. initialize: function SymbolItem(arg0, arg1) {
  4944. if (!this._initialize(arg0,
  4945. arg1 !== undefined && Point.read(arguments, 1)))
  4946. this.setDefinition(arg0 instanceof SymbolDefinition ?
  4947. arg0 : new SymbolDefinition(arg0));
  4948. },
  4949. _equals: function(item) {
  4950. return this._definition === item._definition;
  4951. },
  4952. copyContent: function(source) {
  4953. this.setDefinition(source._definition);
  4954. },
  4955. getDefinition: function() {
  4956. return this._definition;
  4957. },
  4958. setDefinition: function(definition) {
  4959. this._definition = definition;
  4960. this._changed(9);
  4961. },
  4962. getSymbol: '#getDefinition',
  4963. setSymbol: '#setDefinition',
  4964. isEmpty: function() {
  4965. return this._definition._item.isEmpty();
  4966. },
  4967. _getBounds: function(matrix, options) {
  4968. var item = this._definition._item;
  4969. return item._getCachedBounds(item._matrix.prepended(matrix), options);
  4970. },
  4971. _hitTestSelf: function(point, options, viewMatrix) {
  4972. var res = this._definition._item._hitTest(point, options, viewMatrix);
  4973. if (res)
  4974. res.item = this;
  4975. return res;
  4976. },
  4977. _draw: function(ctx, param) {
  4978. this._definition._item.draw(ctx, param);
  4979. }
  4980. });
  4981. var SymbolDefinition = Base.extend({
  4982. _class: 'SymbolDefinition',
  4983. initialize: function SymbolDefinition(item, dontCenter) {
  4984. this._id = UID.get();
  4985. this.project = paper.project;
  4986. if (item)
  4987. this.setItem(item, dontCenter);
  4988. },
  4989. _serialize: function(options, dictionary) {
  4990. return dictionary.add(this, function() {
  4991. return Base.serialize([this._class, this._item],
  4992. options, false, dictionary);
  4993. });
  4994. },
  4995. _changed: function(flags) {
  4996. if (flags & 8)
  4997. Item._clearBoundsCache(this);
  4998. if (flags & 1)
  4999. this.project._changed(flags);
  5000. },
  5001. getItem: function() {
  5002. return this._item;
  5003. },
  5004. setItem: function(item, _dontCenter) {
  5005. if (item._symbol)
  5006. item = item.clone();
  5007. if (this._item)
  5008. this._item._symbol = null;
  5009. this._item = item;
  5010. item.remove();
  5011. item.setSelected(false);
  5012. if (!_dontCenter)
  5013. item.setPosition(new Point());
  5014. item._symbol = this;
  5015. this._changed(9);
  5016. },
  5017. getDefinition: '#getItem',
  5018. setDefinition: '#setItem',
  5019. place: function(position) {
  5020. return new SymbolItem(this, position);
  5021. },
  5022. clone: function() {
  5023. return new SymbolDefinition(this._item.clone(false));
  5024. },
  5025. equals: function(symbol) {
  5026. return symbol === this
  5027. || symbol && this._item.equals(symbol._item)
  5028. || false;
  5029. }
  5030. });
  5031. var HitResult = Base.extend({
  5032. _class: 'HitResult',
  5033. initialize: function HitResult(type, item, values) {
  5034. this.type = type;
  5035. this.item = item;
  5036. if (values)
  5037. this.inject(values);
  5038. },
  5039. statics: {
  5040. getOptions: function(args) {
  5041. var options = args && Base.read(args);
  5042. return Base.set({
  5043. type: null,
  5044. tolerance: paper.settings.hitTolerance,
  5045. fill: !options,
  5046. stroke: !options,
  5047. segments: !options,
  5048. handles: false,
  5049. ends: false,
  5050. position: false,
  5051. center: false,
  5052. bounds: false,
  5053. guides: false,
  5054. selected: false
  5055. }, options);
  5056. }
  5057. }
  5058. });
  5059. var Segment = Base.extend({
  5060. _class: 'Segment',
  5061. beans: true,
  5062. _selection: 0,
  5063. initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
  5064. var count = arguments.length,
  5065. point, handleIn, handleOut, selection;
  5066. if (count > 0) {
  5067. if (arg0 == null || typeof arg0 === 'object') {
  5068. if (count === 1 && arg0 && 'point' in arg0) {
  5069. point = arg0.point;
  5070. handleIn = arg0.handleIn;
  5071. handleOut = arg0.handleOut;
  5072. selection = arg0.selection;
  5073. } else {
  5074. point = arg0;
  5075. handleIn = arg1;
  5076. handleOut = arg2;
  5077. selection = arg3;
  5078. }
  5079. } else {
  5080. point = [ arg0, arg1 ];
  5081. handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
  5082. handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
  5083. }
  5084. }
  5085. new SegmentPoint(point, this, '_point');
  5086. new SegmentPoint(handleIn, this, '_handleIn');
  5087. new SegmentPoint(handleOut, this, '_handleOut');
  5088. if (selection)
  5089. this.setSelection(selection);
  5090. },
  5091. _serialize: function(options, dictionary) {
  5092. var point = this._point,
  5093. selection = this._selection,
  5094. obj = selection || this.hasHandles()
  5095. ? [point, this._handleIn, this._handleOut]
  5096. : point;
  5097. if (selection)
  5098. obj.push(selection);
  5099. return Base.serialize(obj, options, true, dictionary);
  5100. },
  5101. _changed: function(point) {
  5102. var path = this._path;
  5103. if (!path)
  5104. return;
  5105. var curves = path._curves,
  5106. index = this._index,
  5107. curve;
  5108. if (curves) {
  5109. if ((!point || point === this._point || point === this._handleIn)
  5110. && (curve = index > 0 ? curves[index - 1] : path._closed
  5111. ? curves[curves.length - 1] : null))
  5112. curve._changed();
  5113. if ((!point || point === this._point || point === this._handleOut)
  5114. && (curve = curves[index]))
  5115. curve._changed();
  5116. }
  5117. path._changed(41);
  5118. },
  5119. getPoint: function() {
  5120. return this._point;
  5121. },
  5122. setPoint: function() {
  5123. this._point.set(Point.read(arguments));
  5124. },
  5125. getHandleIn: function() {
  5126. return this._handleIn;
  5127. },
  5128. setHandleIn: function() {
  5129. this._handleIn.set(Point.read(arguments));
  5130. },
  5131. getHandleOut: function() {
  5132. return this._handleOut;
  5133. },
  5134. setHandleOut: function() {
  5135. this._handleOut.set(Point.read(arguments));
  5136. },
  5137. hasHandles: function() {
  5138. return !this._handleIn.isZero() || !this._handleOut.isZero();
  5139. },
  5140. isSmooth: function() {
  5141. var handleIn = this._handleIn,
  5142. handleOut = this._handleOut;
  5143. return !handleIn.isZero() && !handleOut.isZero()
  5144. && handleIn.isCollinear(handleOut);
  5145. },
  5146. clearHandles: function() {
  5147. this._handleIn._set(0, 0);
  5148. this._handleOut._set(0, 0);
  5149. },
  5150. getSelection: function() {
  5151. return this._selection;
  5152. },
  5153. setSelection: function(selection) {
  5154. var oldSelection = this._selection,
  5155. path = this._path;
  5156. this._selection = selection = selection || 0;
  5157. if (path && selection !== oldSelection) {
  5158. path._updateSelection(this, oldSelection, selection);
  5159. path._changed(257);
  5160. }
  5161. },
  5162. _changeSelection: function(flag, selected) {
  5163. var selection = this._selection;
  5164. this.setSelection(selected ? selection | flag : selection & ~flag);
  5165. },
  5166. isSelected: function() {
  5167. return !!(this._selection & 7);
  5168. },
  5169. setSelected: function(selected) {
  5170. this._changeSelection(7, selected);
  5171. },
  5172. getIndex: function() {
  5173. return this._index !== undefined ? this._index : null;
  5174. },
  5175. getPath: function() {
  5176. return this._path || null;
  5177. },
  5178. getCurve: function() {
  5179. var path = this._path,
  5180. index = this._index;
  5181. if (path) {
  5182. if (index > 0 && !path._closed
  5183. && index === path._segments.length - 1)
  5184. index--;
  5185. return path.getCurves()[index] || null;
  5186. }
  5187. return null;
  5188. },
  5189. getLocation: function() {
  5190. var curve = this.getCurve();
  5191. return curve
  5192. ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1)
  5193. : null;
  5194. },
  5195. getNext: function() {
  5196. var segments = this._path && this._path._segments;
  5197. return segments && (segments[this._index + 1]
  5198. || this._path._closed && segments[0]) || null;
  5199. },
  5200. smooth: function(options, _first, _last) {
  5201. var opts = options || {},
  5202. type = opts.type,
  5203. factor = opts.factor,
  5204. prev = this.getPrevious(),
  5205. next = this.getNext(),
  5206. p0 = (prev || this)._point,
  5207. p1 = this._point,
  5208. p2 = (next || this)._point,
  5209. d1 = p0.getDistance(p1),
  5210. d2 = p1.getDistance(p2);
  5211. if (!type || type === 'catmull-rom') {
  5212. var a = factor === undefined ? 0.5 : factor,
  5213. d1_a = Math.pow(d1, a),
  5214. d1_2a = d1_a * d1_a,
  5215. d2_a = Math.pow(d2, a),
  5216. d2_2a = d2_a * d2_a;
  5217. if (!_first && prev) {
  5218. var A = 2 * d2_2a + 3 * d2_a * d1_a + d1_2a,
  5219. N = 3 * d2_a * (d2_a + d1_a);
  5220. this.setHandleIn(N !== 0
  5221. ? new Point(
  5222. (d2_2a * p0._x + A * p1._x - d1_2a * p2._x) / N - p1._x,
  5223. (d2_2a * p0._y + A * p1._y - d1_2a * p2._y) / N - p1._y)
  5224. : new Point());
  5225. }
  5226. if (!_last && next) {
  5227. var A = 2 * d1_2a + 3 * d1_a * d2_a + d2_2a,
  5228. N = 3 * d1_a * (d1_a + d2_a);
  5229. this.setHandleOut(N !== 0
  5230. ? new Point(
  5231. (d1_2a * p2._x + A * p1._x - d2_2a * p0._x) / N - p1._x,
  5232. (d1_2a * p2._y + A * p1._y - d2_2a * p0._y) / N - p1._y)
  5233. : new Point());
  5234. }
  5235. } else if (type === 'geometric') {
  5236. if (prev && next) {
  5237. var vector = p0.subtract(p2),
  5238. t = factor === undefined ? 0.4 : factor,
  5239. k = t * d1 / (d1 + d2);
  5240. if (!_first)
  5241. this.setHandleIn(vector.multiply(k));
  5242. if (!_last)
  5243. this.setHandleOut(vector.multiply(k - t));
  5244. }
  5245. } else {
  5246. throw new Error('Smoothing method \'' + type + '\' not supported.');
  5247. }
  5248. },
  5249. getPrevious: function() {
  5250. var segments = this._path && this._path._segments;
  5251. return segments && (segments[this._index - 1]
  5252. || this._path._closed && segments[segments.length - 1]) || null;
  5253. },
  5254. isFirst: function() {
  5255. return !this._index;
  5256. },
  5257. isLast: function() {
  5258. var path = this._path;
  5259. return path && this._index === path._segments.length - 1 || false;
  5260. },
  5261. reverse: function() {
  5262. var handleIn = this._handleIn,
  5263. handleOut = this._handleOut,
  5264. tmp = handleIn.clone();
  5265. handleIn.set(handleOut);
  5266. handleOut.set(tmp);
  5267. },
  5268. reversed: function() {
  5269. return new Segment(this._point, this._handleOut, this._handleIn);
  5270. },
  5271. remove: function() {
  5272. return this._path ? !!this._path.removeSegment(this._index) : false;
  5273. },
  5274. clone: function() {
  5275. return new Segment(this._point, this._handleIn, this._handleOut);
  5276. },
  5277. equals: function(segment) {
  5278. return segment === this || segment && this._class === segment._class
  5279. && this._point.equals(segment._point)
  5280. && this._handleIn.equals(segment._handleIn)
  5281. && this._handleOut.equals(segment._handleOut)
  5282. || false;
  5283. },
  5284. toString: function() {
  5285. var parts = [ 'point: ' + this._point ];
  5286. if (!this._handleIn.isZero())
  5287. parts.push('handleIn: ' + this._handleIn);
  5288. if (!this._handleOut.isZero())
  5289. parts.push('handleOut: ' + this._handleOut);
  5290. return '{ ' + parts.join(', ') + ' }';
  5291. },
  5292. transform: function(matrix) {
  5293. this._transformCoordinates(matrix, new Array(6), true);
  5294. this._changed();
  5295. },
  5296. interpolate: function(from, to, factor) {
  5297. var u = 1 - factor,
  5298. v = factor,
  5299. point1 = from._point,
  5300. point2 = to._point,
  5301. handleIn1 = from._handleIn,
  5302. handleIn2 = to._handleIn,
  5303. handleOut2 = to._handleOut,
  5304. handleOut1 = from._handleOut;
  5305. this._point._set(
  5306. u * point1._x + v * point2._x,
  5307. u * point1._y + v * point2._y, true);
  5308. this._handleIn._set(
  5309. u * handleIn1._x + v * handleIn2._x,
  5310. u * handleIn1._y + v * handleIn2._y, true);
  5311. this._handleOut._set(
  5312. u * handleOut1._x + v * handleOut2._x,
  5313. u * handleOut1._y + v * handleOut2._y, true);
  5314. this._changed();
  5315. },
  5316. _transformCoordinates: function(matrix, coords, change) {
  5317. var point = this._point,
  5318. handleIn = !change || !this._handleIn.isZero()
  5319. ? this._handleIn : null,
  5320. handleOut = !change || !this._handleOut.isZero()
  5321. ? this._handleOut : null,
  5322. x = point._x,
  5323. y = point._y,
  5324. i = 2;
  5325. coords[0] = x;
  5326. coords[1] = y;
  5327. if (handleIn) {
  5328. coords[i++] = handleIn._x + x;
  5329. coords[i++] = handleIn._y + y;
  5330. }
  5331. if (handleOut) {
  5332. coords[i++] = handleOut._x + x;
  5333. coords[i++] = handleOut._y + y;
  5334. }
  5335. if (matrix) {
  5336. matrix._transformCoordinates(coords, coords, i / 2);
  5337. x = coords[0];
  5338. y = coords[1];
  5339. if (change) {
  5340. point._x = x;
  5341. point._y = y;
  5342. i = 2;
  5343. if (handleIn) {
  5344. handleIn._x = coords[i++] - x;
  5345. handleIn._y = coords[i++] - y;
  5346. }
  5347. if (handleOut) {
  5348. handleOut._x = coords[i++] - x;
  5349. handleOut._y = coords[i++] - y;
  5350. }
  5351. } else {
  5352. if (!handleIn) {
  5353. coords[i++] = x;
  5354. coords[i++] = y;
  5355. }
  5356. if (!handleOut) {
  5357. coords[i++] = x;
  5358. coords[i++] = y;
  5359. }
  5360. }
  5361. }
  5362. return coords;
  5363. }
  5364. });
  5365. var SegmentPoint = Point.extend({
  5366. initialize: function SegmentPoint(point, owner, key) {
  5367. var x, y,
  5368. selected;
  5369. if (!point) {
  5370. x = y = 0;
  5371. } else if ((x = point[0]) !== undefined) {
  5372. y = point[1];
  5373. } else {
  5374. var pt = point;
  5375. if ((x = pt.x) === undefined) {
  5376. pt = Point.read(arguments);
  5377. x = pt.x;
  5378. }
  5379. y = pt.y;
  5380. selected = pt.selected;
  5381. }
  5382. this._x = x;
  5383. this._y = y;
  5384. this._owner = owner;
  5385. owner[key] = this;
  5386. if (selected)
  5387. this.setSelected(true);
  5388. },
  5389. _set: function(x, y) {
  5390. this._x = x;
  5391. this._y = y;
  5392. this._owner._changed(this);
  5393. return this;
  5394. },
  5395. getX: function() {
  5396. return this._x;
  5397. },
  5398. setX: function(x) {
  5399. this._x = x;
  5400. this._owner._changed(this);
  5401. },
  5402. getY: function() {
  5403. return this._y;
  5404. },
  5405. setY: function(y) {
  5406. this._y = y;
  5407. this._owner._changed(this);
  5408. },
  5409. isZero: function() {
  5410. var isZero = Numerical.isZero;
  5411. return isZero(this._x) && isZero(this._y);
  5412. },
  5413. isSelected: function() {
  5414. return !!(this._owner._selection & this._getSelection());
  5415. },
  5416. setSelected: function(selected) {
  5417. this._owner._changeSelection(this._getSelection(), selected);
  5418. },
  5419. _getSelection: function() {
  5420. var owner = this._owner;
  5421. return this === owner._point ? 1
  5422. : this === owner._handleIn ? 2
  5423. : this === owner._handleOut ? 4
  5424. : 0;
  5425. }
  5426. });
  5427. var Curve = Base.extend({
  5428. _class: 'Curve',
  5429. beans: true,
  5430. initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
  5431. var count = arguments.length,
  5432. seg1, seg2,
  5433. point1, point2,
  5434. handle1, handle2;
  5435. if (count === 3) {
  5436. this._path = arg0;
  5437. seg1 = arg1;
  5438. seg2 = arg2;
  5439. } else if (!count) {
  5440. seg1 = new Segment();
  5441. seg2 = new Segment();
  5442. } else if (count === 1) {
  5443. if ('segment1' in arg0) {
  5444. seg1 = new Segment(arg0.segment1);
  5445. seg2 = new Segment(arg0.segment2);
  5446. } else if ('point1' in arg0) {
  5447. point1 = arg0.point1;
  5448. handle1 = arg0.handle1;
  5449. handle2 = arg0.handle2;
  5450. point2 = arg0.point2;
  5451. } else if (Array.isArray(arg0)) {
  5452. point1 = [arg0[0], arg0[1]];
  5453. point2 = [arg0[6], arg0[7]];
  5454. handle1 = [arg0[2] - arg0[0], arg0[3] - arg0[1]];
  5455. handle2 = [arg0[4] - arg0[6], arg0[5] - arg0[7]];
  5456. }
  5457. } else if (count === 2) {
  5458. seg1 = new Segment(arg0);
  5459. seg2 = new Segment(arg1);
  5460. } else if (count === 4) {
  5461. point1 = arg0;
  5462. handle1 = arg1;
  5463. handle2 = arg2;
  5464. point2 = arg3;
  5465. } else if (count === 8) {
  5466. point1 = [arg0, arg1];
  5467. point2 = [arg6, arg7];
  5468. handle1 = [arg2 - arg0, arg3 - arg1];
  5469. handle2 = [arg4 - arg6, arg5 - arg7];
  5470. }
  5471. this._segment1 = seg1 || new Segment(point1, null, handle1);
  5472. this._segment2 = seg2 || new Segment(point2, handle2, null);
  5473. },
  5474. _serialize: function(options, dictionary) {
  5475. return Base.serialize(this.hasHandles()
  5476. ? [this.getPoint1(), this.getHandle1(), this.getHandle2(),
  5477. this.getPoint2()]
  5478. : [this.getPoint1(), this.getPoint2()],
  5479. options, true, dictionary);
  5480. },
  5481. _changed: function() {
  5482. this._length = this._bounds = undefined;
  5483. },
  5484. clone: function() {
  5485. return new Curve(this._segment1, this._segment2);
  5486. },
  5487. toString: function() {
  5488. var parts = [ 'point1: ' + this._segment1._point ];
  5489. if (!this._segment1._handleOut.isZero())
  5490. parts.push('handle1: ' + this._segment1._handleOut);
  5491. if (!this._segment2._handleIn.isZero())
  5492. parts.push('handle2: ' + this._segment2._handleIn);
  5493. parts.push('point2: ' + this._segment2._point);
  5494. return '{ ' + parts.join(', ') + ' }';
  5495. },
  5496. classify: function() {
  5497. return Curve.classify(this.getValues());
  5498. },
  5499. remove: function() {
  5500. var removed = false;
  5501. if (this._path) {
  5502. var segment2 = this._segment2,
  5503. handleOut = segment2._handleOut;
  5504. removed = segment2.remove();
  5505. if (removed)
  5506. this._segment1._handleOut.set(handleOut);
  5507. }
  5508. return removed;
  5509. },
  5510. getPoint1: function() {
  5511. return this._segment1._point;
  5512. },
  5513. setPoint1: function() {
  5514. this._segment1._point.set(Point.read(arguments));
  5515. },
  5516. getPoint2: function() {
  5517. return this._segment2._point;
  5518. },
  5519. setPoint2: function() {
  5520. this._segment2._point.set(Point.read(arguments));
  5521. },
  5522. getHandle1: function() {
  5523. return this._segment1._handleOut;
  5524. },
  5525. setHandle1: function() {
  5526. this._segment1._handleOut.set(Point.read(arguments));
  5527. },
  5528. getHandle2: function() {
  5529. return this._segment2._handleIn;
  5530. },
  5531. setHandle2: function() {
  5532. this._segment2._handleIn.set(Point.read(arguments));
  5533. },
  5534. getSegment1: function() {
  5535. return this._segment1;
  5536. },
  5537. getSegment2: function() {
  5538. return this._segment2;
  5539. },
  5540. getPath: function() {
  5541. return this._path;
  5542. },
  5543. getIndex: function() {
  5544. return this._segment1._index;
  5545. },
  5546. getNext: function() {
  5547. var curves = this._path && this._path._curves;
  5548. return curves && (curves[this._segment1._index + 1]
  5549. || this._path._closed && curves[0]) || null;
  5550. },
  5551. getPrevious: function() {
  5552. var curves = this._path && this._path._curves;
  5553. return curves && (curves[this._segment1._index - 1]
  5554. || this._path._closed && curves[curves.length - 1]) || null;
  5555. },
  5556. isFirst: function() {
  5557. return !this._segment1._index;
  5558. },
  5559. isLast: function() {
  5560. var path = this._path;
  5561. return path && this._segment1._index === path._curves.length - 1
  5562. || false;
  5563. },
  5564. isSelected: function() {
  5565. return this.getPoint1().isSelected()
  5566. && this.getHandle1().isSelected()
  5567. && this.getHandle2().isSelected()
  5568. && this.getPoint2().isSelected();
  5569. },
  5570. setSelected: function(selected) {
  5571. this.getPoint1().setSelected(selected);
  5572. this.getHandle1().setSelected(selected);
  5573. this.getHandle2().setSelected(selected);
  5574. this.getPoint2().setSelected(selected);
  5575. },
  5576. getValues: function(matrix) {
  5577. return Curve.getValues(this._segment1, this._segment2, matrix);
  5578. },
  5579. getPoints: function() {
  5580. var coords = this.getValues(),
  5581. points = [];
  5582. for (var i = 0; i < 8; i += 2)
  5583. points.push(new Point(coords[i], coords[i + 1]));
  5584. return points;
  5585. }
  5586. }, {
  5587. getLength: function() {
  5588. if (this._length == null)
  5589. this._length = Curve.getLength(this.getValues(), 0, 1);
  5590. return this._length;
  5591. },
  5592. getArea: function() {
  5593. return Curve.getArea(this.getValues());
  5594. },
  5595. getLine: function() {
  5596. return new Line(this._segment1._point, this._segment2._point);
  5597. },
  5598. getPart: function(from, to) {
  5599. return new Curve(Curve.getPart(this.getValues(), from, to));
  5600. },
  5601. getPartLength: function(from, to) {
  5602. return Curve.getLength(this.getValues(), from, to);
  5603. },
  5604. divideAt: function(location) {
  5605. return this.divideAtTime(location && location.curve === this
  5606. ? location.time : this.getTimeAt(location));
  5607. },
  5608. divideAtTime: function(time, _setHandles) {
  5609. var tMin = 1e-8,
  5610. tMax = 1 - tMin,
  5611. res = null;
  5612. if (time >= tMin && time <= tMax) {
  5613. var parts = Curve.subdivide(this.getValues(), time),
  5614. left = parts[0],
  5615. right = parts[1],
  5616. setHandles = _setHandles || this.hasHandles(),
  5617. seg1 = this._segment1,
  5618. seg2 = this._segment2,
  5619. path = this._path;
  5620. if (setHandles) {
  5621. seg1._handleOut._set(left[2] - left[0], left[3] - left[1]);
  5622. seg2._handleIn._set(right[4] - right[6],right[5] - right[7]);
  5623. }
  5624. var x = left[6], y = left[7],
  5625. segment = new Segment(new Point(x, y),
  5626. setHandles && new Point(left[4] - x, left[5] - y),
  5627. setHandles && new Point(right[2] - x, right[3] - y));
  5628. if (path) {
  5629. path.insert(seg1._index + 1, segment);
  5630. res = this.getNext();
  5631. } else {
  5632. this._segment2 = segment;
  5633. this._changed();
  5634. res = new Curve(segment, seg2);
  5635. }
  5636. }
  5637. return res;
  5638. },
  5639. splitAt: function(location) {
  5640. var path = this._path;
  5641. return path ? path.splitAt(location) : null;
  5642. },
  5643. splitAtTime: function(time) {
  5644. return this.splitAt(this.getLocationAtTime(time));
  5645. },
  5646. divide: function(offset, isTime) {
  5647. return this.divideAtTime(offset === undefined ? 0.5 : isTime ? offset
  5648. : this.getTimeAt(offset));
  5649. },
  5650. split: function(offset, isTime) {
  5651. return this.splitAtTime(offset === undefined ? 0.5 : isTime ? offset
  5652. : this.getTimeAt(offset));
  5653. },
  5654. reversed: function() {
  5655. return new Curve(this._segment2.reversed(), this._segment1.reversed());
  5656. },
  5657. clearHandles: function() {
  5658. this._segment1._handleOut._set(0, 0);
  5659. this._segment2._handleIn._set(0, 0);
  5660. },
  5661. statics: {
  5662. getValues: function(segment1, segment2, matrix, straight) {
  5663. var p1 = segment1._point,
  5664. h1 = segment1._handleOut,
  5665. h2 = segment2._handleIn,
  5666. p2 = segment2._point,
  5667. x1 = p1.x, y1 = p1.y,
  5668. x2 = p2.x, y2 = p2.y,
  5669. values = straight
  5670. ? [ x1, y1, x1, y1, x2, y2, x2, y2 ]
  5671. : [
  5672. x1, y1,
  5673. x1 + h1._x, y1 + h1._y,
  5674. x2 + h2._x, y2 + h2._y,
  5675. x2, y2
  5676. ];
  5677. if (matrix)
  5678. matrix._transformCoordinates(values, values, 4);
  5679. return values;
  5680. },
  5681. subdivide: function(v, t) {
  5682. var x0 = v[0], y0 = v[1],
  5683. x1 = v[2], y1 = v[3],
  5684. x2 = v[4], y2 = v[5],
  5685. x3 = v[6], y3 = v[7];
  5686. if (t === undefined)
  5687. t = 0.5;
  5688. var u = 1 - t,
  5689. x4 = u * x0 + t * x1, y4 = u * y0 + t * y1,
  5690. x5 = u * x1 + t * x2, y5 = u * y1 + t * y2,
  5691. x6 = u * x2 + t * x3, y6 = u * y2 + t * y3,
  5692. x7 = u * x4 + t * x5, y7 = u * y4 + t * y5,
  5693. x8 = u * x5 + t * x6, y8 = u * y5 + t * y6,
  5694. x9 = u * x7 + t * x8, y9 = u * y7 + t * y8;
  5695. return [
  5696. [x0, y0, x4, y4, x7, y7, x9, y9],
  5697. [x9, y9, x8, y8, x6, y6, x3, y3]
  5698. ];
  5699. },
  5700. getMonoCurves: function(v, dir) {
  5701. var curves = [],
  5702. io = dir ? 0 : 1,
  5703. o0 = v[io + 0],
  5704. o1 = v[io + 2],
  5705. o2 = v[io + 4],
  5706. o3 = v[io + 6];
  5707. if ((o0 >= o1) === (o1 >= o2) && (o1 >= o2) === (o2 >= o3)
  5708. || Curve.isStraight(v)) {
  5709. curves.push(v);
  5710. } else {
  5711. var a = 3 * (o1 - o2) - o0 + o3,
  5712. b = 2 * (o0 + o2) - 4 * o1,
  5713. c = o1 - o0,
  5714. tMin = 1e-8,
  5715. tMax = 1 - tMin,
  5716. roots = [],
  5717. n = Numerical.solveQuadratic(a, b, c, roots, tMin, tMax);
  5718. if (!n) {
  5719. curves.push(v);
  5720. } else {
  5721. roots.sort();
  5722. var t = roots[0],
  5723. parts = Curve.subdivide(v, t);
  5724. curves.push(parts[0]);
  5725. if (n > 1) {
  5726. t = (roots[1] - t) / (1 - t);
  5727. parts = Curve.subdivide(parts[1], t);
  5728. curves.push(parts[0]);
  5729. }
  5730. curves.push(parts[1]);
  5731. }
  5732. }
  5733. return curves;
  5734. },
  5735. solveCubic: function (v, coord, val, roots, min, max) {
  5736. var v0 = v[coord],
  5737. v1 = v[coord + 2],
  5738. v2 = v[coord + 4],
  5739. v3 = v[coord + 6],
  5740. res = 0;
  5741. if ( !(v0 < val && v3 < val && v1 < val && v2 < val ||
  5742. v0 > val && v3 > val && v1 > val && v2 > val)) {
  5743. var c = 3 * (v1 - v0),
  5744. b = 3 * (v2 - v1) - c,
  5745. a = v3 - v0 - c - b;
  5746. res = Numerical.solveCubic(a, b, c, v0 - val, roots, min, max);
  5747. }
  5748. return res;
  5749. },
  5750. getTimeOf: function(v, point) {
  5751. var p0 = new Point(v[0], v[1]),
  5752. p3 = new Point(v[6], v[7]),
  5753. epsilon = 1e-12,
  5754. geomEpsilon = 1e-7,
  5755. t = point.isClose(p0, epsilon) ? 0
  5756. : point.isClose(p3, epsilon) ? 1
  5757. : null;
  5758. if (t === null) {
  5759. var coords = [point.x, point.y],
  5760. roots = [];
  5761. for (var c = 0; c < 2; c++) {
  5762. var count = Curve.solveCubic(v, c, coords[c], roots, 0, 1);
  5763. for (var i = 0; i < count; i++) {
  5764. var u = roots[i];
  5765. if (point.isClose(Curve.getPoint(v, u), geomEpsilon))
  5766. return u;
  5767. }
  5768. }
  5769. }
  5770. return point.isClose(p0, geomEpsilon) ? 0
  5771. : point.isClose(p3, geomEpsilon) ? 1
  5772. : null;
  5773. },
  5774. getNearestTime: function(v, point) {
  5775. if (Curve.isStraight(v)) {
  5776. var x0 = v[0], y0 = v[1],
  5777. x3 = v[6], y3 = v[7],
  5778. vx = x3 - x0, vy = y3 - y0,
  5779. det = vx * vx + vy * vy;
  5780. if (det === 0)
  5781. return 0;
  5782. var u = ((point.x - x0) * vx + (point.y - y0) * vy) / det;
  5783. return u < 1e-12 ? 0
  5784. : u > 0.999999999999 ? 1
  5785. : Curve.getTimeOf(v,
  5786. new Point(x0 + u * vx, y0 + u * vy));
  5787. }
  5788. var count = 100,
  5789. minDist = Infinity,
  5790. minT = 0;
  5791. function refine(t) {
  5792. if (t >= 0 && t <= 1) {
  5793. var dist = point.getDistance(Curve.getPoint(v, t), true);
  5794. if (dist < minDist) {
  5795. minDist = dist;
  5796. minT = t;
  5797. return true;
  5798. }
  5799. }
  5800. }
  5801. for (var i = 0; i <= count; i++)
  5802. refine(i / count);
  5803. var step = 1 / (count * 2);
  5804. while (step > 1e-8) {
  5805. if (!refine(minT - step) && !refine(minT + step))
  5806. step /= 2;
  5807. }
  5808. return minT;
  5809. },
  5810. getPart: function(v, from, to) {
  5811. var flip = from > to;
  5812. if (flip) {
  5813. var tmp = from;
  5814. from = to;
  5815. to = tmp;
  5816. }
  5817. if (from > 0)
  5818. v = Curve.subdivide(v, from)[1];
  5819. if (to < 1)
  5820. v = Curve.subdivide(v, (to - from) / (1 - from))[0];
  5821. return flip
  5822. ? [v[6], v[7], v[4], v[5], v[2], v[3], v[0], v[1]]
  5823. : v;
  5824. },
  5825. isFlatEnough: function(v, flatness) {
  5826. var x0 = v[0], y0 = v[1],
  5827. x1 = v[2], y1 = v[3],
  5828. x2 = v[4], y2 = v[5],
  5829. x3 = v[6], y3 = v[7],
  5830. ux = 3 * x1 - 2 * x0 - x3,
  5831. uy = 3 * y1 - 2 * y0 - y3,
  5832. vx = 3 * x2 - 2 * x3 - x0,
  5833. vy = 3 * y2 - 2 * y3 - y0;
  5834. return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
  5835. <= 16 * flatness * flatness;
  5836. },
  5837. getArea: function(v) {
  5838. var x0 = v[0], y0 = v[1],
  5839. x1 = v[2], y1 = v[3],
  5840. x2 = v[4], y2 = v[5],
  5841. x3 = v[6], y3 = v[7];
  5842. return 3 * ((y3 - y0) * (x1 + x2) - (x3 - x0) * (y1 + y2)
  5843. + y1 * (x0 - x2) - x1 * (y0 - y2)
  5844. + y3 * (x2 + x0 / 3) - x3 * (y2 + y0 / 3)) / 20;
  5845. },
  5846. getBounds: function(v) {
  5847. var min = v.slice(0, 2),
  5848. max = min.slice(),
  5849. roots = [0, 0];
  5850. for (var i = 0; i < 2; i++)
  5851. Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
  5852. i, 0, min, max, roots);
  5853. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  5854. },
  5855. _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
  5856. function add(value, padding) {
  5857. var left = value - padding,
  5858. right = value + padding;
  5859. if (left < min[coord])
  5860. min[coord] = left;
  5861. if (right > max[coord])
  5862. max[coord] = right;
  5863. }
  5864. padding /= 2;
  5865. var minPad = min[coord] - padding,
  5866. maxPad = max[coord] + padding;
  5867. if ( v0 < minPad || v1 < minPad || v2 < minPad || v3 < minPad ||
  5868. v0 > maxPad || v1 > maxPad || v2 > maxPad || v3 > maxPad) {
  5869. if (v1 < v0 != v1 < v3 && v2 < v0 != v2 < v3) {
  5870. add(v0, padding);
  5871. add(v3, padding);
  5872. } else {
  5873. var a = 3 * (v1 - v2) - v0 + v3,
  5874. b = 2 * (v0 + v2) - 4 * v1,
  5875. c = v1 - v0,
  5876. count = Numerical.solveQuadratic(a, b, c, roots),
  5877. tMin = 1e-8,
  5878. tMax = 1 - tMin;
  5879. add(v3, 0);
  5880. for (var i = 0; i < count; i++) {
  5881. var t = roots[i],
  5882. u = 1 - t;
  5883. if (tMin <= t && t <= tMax)
  5884. add(u * u * u * v0
  5885. + 3 * u * u * t * v1
  5886. + 3 * u * t * t * v2
  5887. + t * t * t * v3,
  5888. padding);
  5889. }
  5890. }
  5891. }
  5892. }
  5893. }}, Base.each(
  5894. ['getBounds', 'getStrokeBounds', 'getHandleBounds'],
  5895. function(name) {
  5896. this[name] = function() {
  5897. if (!this._bounds)
  5898. this._bounds = {};
  5899. var bounds = this._bounds[name];
  5900. if (!bounds) {
  5901. bounds = this._bounds[name] = Path[name](
  5902. [this._segment1, this._segment2], false, this._path);
  5903. }
  5904. return bounds.clone();
  5905. };
  5906. },
  5907. {
  5908. }), Base.each({
  5909. isStraight: function(p1, h1, h2, p2) {
  5910. if (h1.isZero() && h2.isZero()) {
  5911. return true;
  5912. } else {
  5913. var v = p2.subtract(p1);
  5914. if (v.isZero()) {
  5915. return false;
  5916. } else if (v.isCollinear(h1) && v.isCollinear(h2)) {
  5917. var l = new Line(p1, p2),
  5918. epsilon = 1e-7;
  5919. if (l.getDistance(p1.add(h1)) < epsilon &&
  5920. l.getDistance(p2.add(h2)) < epsilon) {
  5921. var div = v.dot(v),
  5922. s1 = v.dot(h1) / div,
  5923. s2 = v.dot(h2) / div;
  5924. return s1 >= 0 && s1 <= 1 && s2 <= 0 && s2 >= -1;
  5925. }
  5926. }
  5927. }
  5928. return false;
  5929. },
  5930. isLinear: function(p1, h1, h2, p2) {
  5931. var third = p2.subtract(p1).divide(3);
  5932. return h1.equals(third) && h2.negate().equals(third);
  5933. }
  5934. }, function(test, name) {
  5935. this[name] = function(epsilon) {
  5936. var seg1 = this._segment1,
  5937. seg2 = this._segment2;
  5938. return test(seg1._point, seg1._handleOut, seg2._handleIn, seg2._point,
  5939. epsilon);
  5940. };
  5941. this.statics[name] = function(v, epsilon) {
  5942. var x0 = v[0], y0 = v[1],
  5943. x3 = v[6], y3 = v[7];
  5944. return test(
  5945. new Point(x0, y0),
  5946. new Point(v[2] - x0, v[3] - y0),
  5947. new Point(v[4] - x3, v[5] - y3),
  5948. new Point(x3, y3), epsilon);
  5949. };
  5950. }, {
  5951. statics: {},
  5952. hasHandles: function() {
  5953. return !this._segment1._handleOut.isZero()
  5954. || !this._segment2._handleIn.isZero();
  5955. },
  5956. hasLength: function(epsilon) {
  5957. return (!this.getPoint1().equals(this.getPoint2()) || this.hasHandles())
  5958. && this.getLength() > (epsilon || 0);
  5959. },
  5960. isCollinear: function(curve) {
  5961. return curve && this.isStraight() && curve.isStraight()
  5962. && this.getLine().isCollinear(curve.getLine());
  5963. },
  5964. isHorizontal: function() {
  5965. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).y)
  5966. < 1e-8;
  5967. },
  5968. isVertical: function() {
  5969. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).x)
  5970. < 1e-8;
  5971. }
  5972. }), {
  5973. beans: false,
  5974. getLocationAt: function(offset, _isTime) {
  5975. return this.getLocationAtTime(
  5976. _isTime ? offset : this.getTimeAt(offset));
  5977. },
  5978. getLocationAtTime: function(t) {
  5979. return t != null && t >= 0 && t <= 1
  5980. ? new CurveLocation(this, t)
  5981. : null;
  5982. },
  5983. getTimeAt: function(offset, start) {
  5984. return Curve.getTimeAt(this.getValues(), offset, start);
  5985. },
  5986. getParameterAt: '#getTimeAt',
  5987. getTimesWithTangent: function () {
  5988. var tangent = Point.read(arguments);
  5989. return tangent.isZero()
  5990. ? []
  5991. : Curve.getTimesWithTangent(this.getValues(), tangent);
  5992. },
  5993. getOffsetAtTime: function(t) {
  5994. return this.getPartLength(0, t);
  5995. },
  5996. getLocationOf: function() {
  5997. return this.getLocationAtTime(this.getTimeOf(Point.read(arguments)));
  5998. },
  5999. getOffsetOf: function() {
  6000. var loc = this.getLocationOf.apply(this, arguments);
  6001. return loc ? loc.getOffset() : null;
  6002. },
  6003. getTimeOf: function() {
  6004. return Curve.getTimeOf(this.getValues(), Point.read(arguments));
  6005. },
  6006. getParameterOf: '#getTimeOf',
  6007. getNearestLocation: function() {
  6008. var point = Point.read(arguments),
  6009. values = this.getValues(),
  6010. t = Curve.getNearestTime(values, point),
  6011. pt = Curve.getPoint(values, t);
  6012. return new CurveLocation(this, t, pt, null, point.getDistance(pt));
  6013. },
  6014. getNearestPoint: function() {
  6015. var loc = this.getNearestLocation.apply(this, arguments);
  6016. return loc ? loc.getPoint() : loc;
  6017. }
  6018. },
  6019. new function() {
  6020. var methods = ['getPoint', 'getTangent', 'getNormal', 'getWeightedTangent',
  6021. 'getWeightedNormal', 'getCurvature'];
  6022. return Base.each(methods,
  6023. function(name) {
  6024. this[name + 'At'] = function(location, _isTime) {
  6025. var values = this.getValues();
  6026. return Curve[name](values, _isTime ? location
  6027. : Curve.getTimeAt(values, location));
  6028. };
  6029. this[name + 'AtTime'] = function(time) {
  6030. return Curve[name](this.getValues(), time);
  6031. };
  6032. }, {
  6033. statics: {
  6034. _evaluateMethods: methods
  6035. }
  6036. }
  6037. );
  6038. },
  6039. new function() {
  6040. function getLengthIntegrand(v) {
  6041. var x0 = v[0], y0 = v[1],
  6042. x1 = v[2], y1 = v[3],
  6043. x2 = v[4], y2 = v[5],
  6044. x3 = v[6], y3 = v[7],
  6045. ax = 9 * (x1 - x2) + 3 * (x3 - x0),
  6046. bx = 6 * (x0 + x2) - 12 * x1,
  6047. cx = 3 * (x1 - x0),
  6048. ay = 9 * (y1 - y2) + 3 * (y3 - y0),
  6049. by = 6 * (y0 + y2) - 12 * y1,
  6050. cy = 3 * (y1 - y0);
  6051. return function(t) {
  6052. var dx = (ax * t + bx) * t + cx,
  6053. dy = (ay * t + by) * t + cy;
  6054. return Math.sqrt(dx * dx + dy * dy);
  6055. };
  6056. }
  6057. function getIterations(a, b) {
  6058. return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
  6059. }
  6060. function evaluate(v, t, type, normalized) {
  6061. if (t == null || t < 0 || t > 1)
  6062. return null;
  6063. var x0 = v[0], y0 = v[1],
  6064. x1 = v[2], y1 = v[3],
  6065. x2 = v[4], y2 = v[5],
  6066. x3 = v[6], y3 = v[7],
  6067. isZero = Numerical.isZero;
  6068. if (isZero(x1 - x0) && isZero(y1 - y0)) {
  6069. x1 = x0;
  6070. y1 = y0;
  6071. }
  6072. if (isZero(x2 - x3) && isZero(y2 - y3)) {
  6073. x2 = x3;
  6074. y2 = y3;
  6075. }
  6076. var cx = 3 * (x1 - x0),
  6077. bx = 3 * (x2 - x1) - cx,
  6078. ax = x3 - x0 - cx - bx,
  6079. cy = 3 * (y1 - y0),
  6080. by = 3 * (y2 - y1) - cy,
  6081. ay = y3 - y0 - cy - by,
  6082. x, y;
  6083. if (type === 0) {
  6084. x = t === 0 ? x0 : t === 1 ? x3
  6085. : ((ax * t + bx) * t + cx) * t + x0;
  6086. y = t === 0 ? y0 : t === 1 ? y3
  6087. : ((ay * t + by) * t + cy) * t + y0;
  6088. } else {
  6089. var tMin = 1e-8,
  6090. tMax = 1 - tMin;
  6091. if (t < tMin) {
  6092. x = cx;
  6093. y = cy;
  6094. } else if (t > tMax) {
  6095. x = 3 * (x3 - x2);
  6096. y = 3 * (y3 - y2);
  6097. } else {
  6098. x = (3 * ax * t + 2 * bx) * t + cx;
  6099. y = (3 * ay * t + 2 * by) * t + cy;
  6100. }
  6101. if (normalized) {
  6102. if (x === 0 && y === 0 && (t < tMin || t > tMax)) {
  6103. x = x2 - x1;
  6104. y = y2 - y1;
  6105. }
  6106. var len = Math.sqrt(x * x + y * y);
  6107. if (len) {
  6108. x /= len;
  6109. y /= len;
  6110. }
  6111. }
  6112. if (type === 3) {
  6113. var x2 = 6 * ax * t + 2 * bx,
  6114. y2 = 6 * ay * t + 2 * by,
  6115. d = Math.pow(x * x + y * y, 3 / 2);
  6116. x = d !== 0 ? (x * y2 - y * x2) / d : 0;
  6117. y = 0;
  6118. }
  6119. }
  6120. return type === 2 ? new Point(y, -x) : new Point(x, y);
  6121. }
  6122. return { statics: {
  6123. classify: function(v) {
  6124. var x0 = v[0], y0 = v[1],
  6125. x1 = v[2], y1 = v[3],
  6126. x2 = v[4], y2 = v[5],
  6127. x3 = v[6], y3 = v[7],
  6128. a1 = x0 * (y3 - y2) + y0 * (x2 - x3) + x3 * y2 - y3 * x2,
  6129. a2 = x1 * (y0 - y3) + y1 * (x3 - x0) + x0 * y3 - y0 * x3,
  6130. a3 = x2 * (y1 - y0) + y2 * (x0 - x1) + x1 * y0 - y1 * x0,
  6131. d3 = 3 * a3,
  6132. d2 = d3 - a2,
  6133. d1 = d2 - a2 + a1,
  6134. l = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3),
  6135. s = l !== 0 ? 1 / l : 0,
  6136. isZero = Numerical.isZero,
  6137. serpentine = 'serpentine';
  6138. d1 *= s;
  6139. d2 *= s;
  6140. d3 *= s;
  6141. function type(type, t1, t2) {
  6142. var hasRoots = t1 !== undefined,
  6143. t1Ok = hasRoots && t1 > 0 && t1 < 1,
  6144. t2Ok = hasRoots && t2 > 0 && t2 < 1;
  6145. if (hasRoots && (!(t1Ok || t2Ok)
  6146. || type === 'loop' && !(t1Ok && t2Ok))) {
  6147. type = 'arch';
  6148. t1Ok = t2Ok = false;
  6149. }
  6150. return {
  6151. type: type,
  6152. roots: t1Ok || t2Ok
  6153. ? t1Ok && t2Ok
  6154. ? t1 < t2 ? [t1, t2] : [t2, t1]
  6155. : [t1Ok ? t1 : t2]
  6156. : null
  6157. };
  6158. }
  6159. if (isZero(d1)) {
  6160. return isZero(d2)
  6161. ? type(isZero(d3) ? 'line' : 'quadratic')
  6162. : type(serpentine, d3 / (3 * d2));
  6163. }
  6164. var d = 3 * d2 * d2 - 4 * d1 * d3;
  6165. if (isZero(d)) {
  6166. return type('cusp', d2 / (2 * d1));
  6167. }
  6168. var f1 = d > 0 ? Math.sqrt(d / 3) : Math.sqrt(-d),
  6169. f2 = 2 * d1;
  6170. return type(d > 0 ? serpentine : 'loop',
  6171. (d2 + f1) / f2,
  6172. (d2 - f1) / f2);
  6173. },
  6174. getLength: function(v, a, b, ds) {
  6175. if (a === undefined)
  6176. a = 0;
  6177. if (b === undefined)
  6178. b = 1;
  6179. if (Curve.isStraight(v)) {
  6180. var c = v;
  6181. if (b < 1) {
  6182. c = Curve.subdivide(c, b)[0];
  6183. a /= b;
  6184. }
  6185. if (a > 0) {
  6186. c = Curve.subdivide(c, a)[1];
  6187. }
  6188. var dx = c[6] - c[0],
  6189. dy = c[7] - c[1];
  6190. return Math.sqrt(dx * dx + dy * dy);
  6191. }
  6192. return Numerical.integrate(ds || getLengthIntegrand(v), a, b,
  6193. getIterations(a, b));
  6194. },
  6195. getTimeAt: function(v, offset, start) {
  6196. if (start === undefined)
  6197. start = offset < 0 ? 1 : 0;
  6198. if (offset === 0)
  6199. return start;
  6200. var abs = Math.abs,
  6201. epsilon = 1e-12,
  6202. forward = offset > 0,
  6203. a = forward ? start : 0,
  6204. b = forward ? 1 : start,
  6205. ds = getLengthIntegrand(v),
  6206. rangeLength = Curve.getLength(v, a, b, ds),
  6207. diff = abs(offset) - rangeLength;
  6208. if (abs(diff) < epsilon) {
  6209. return forward ? b : a;
  6210. } else if (diff > epsilon) {
  6211. return null;
  6212. }
  6213. var guess = offset / rangeLength,
  6214. length = 0;
  6215. function f(t) {
  6216. length += Numerical.integrate(ds, start, t,
  6217. getIterations(start, t));
  6218. start = t;
  6219. return length - offset;
  6220. }
  6221. return Numerical.findRoot(f, ds, start + guess, a, b, 32,
  6222. 1e-12);
  6223. },
  6224. getPoint: function(v, t) {
  6225. return evaluate(v, t, 0, false);
  6226. },
  6227. getTangent: function(v, t) {
  6228. return evaluate(v, t, 1, true);
  6229. },
  6230. getWeightedTangent: function(v, t) {
  6231. return evaluate(v, t, 1, false);
  6232. },
  6233. getNormal: function(v, t) {
  6234. return evaluate(v, t, 2, true);
  6235. },
  6236. getWeightedNormal: function(v, t) {
  6237. return evaluate(v, t, 2, false);
  6238. },
  6239. getCurvature: function(v, t) {
  6240. return evaluate(v, t, 3, false).x;
  6241. },
  6242. getPeaks: function(v) {
  6243. var x0 = v[0], y0 = v[1],
  6244. x1 = v[2], y1 = v[3],
  6245. x2 = v[4], y2 = v[5],
  6246. x3 = v[6], y3 = v[7],
  6247. ax = -x0 + 3 * x1 - 3 * x2 + x3,
  6248. bx = 3 * x0 - 6 * x1 + 3 * x2,
  6249. cx = -3 * x0 + 3 * x1,
  6250. ay = -y0 + 3 * y1 - 3 * y2 + y3,
  6251. by = 3 * y0 - 6 * y1 + 3 * y2,
  6252. cy = -3 * y0 + 3 * y1,
  6253. tMin = 1e-8,
  6254. tMax = 1 - tMin,
  6255. roots = [];
  6256. Numerical.solveCubic(
  6257. 9 * (ax * ax + ay * ay),
  6258. 9 * (ax * bx + by * ay),
  6259. 2 * (bx * bx + by * by) + 3 * (cx * ax + cy * ay),
  6260. (cx * bx + by * cy),
  6261. roots, tMin, tMax);
  6262. return roots.sort();
  6263. }
  6264. }};
  6265. },
  6266. new function() {
  6267. function addLocation(locations, include, c1, t1, c2, t2, overlap) {
  6268. var excludeStart = !overlap && c1.getPrevious() === c2,
  6269. excludeEnd = !overlap && c1 !== c2 && c1.getNext() === c2,
  6270. tMin = 1e-8,
  6271. tMax = 1 - tMin;
  6272. if (t1 !== null && t1 >= (excludeStart ? tMin : 0) &&
  6273. t1 <= (excludeEnd ? tMax : 1)) {
  6274. if (t2 !== null && t2 >= (excludeEnd ? tMin : 0) &&
  6275. t2 <= (excludeStart ? tMax : 1)) {
  6276. var loc1 = new CurveLocation(c1, t1, null, overlap),
  6277. loc2 = new CurveLocation(c2, t2, null, overlap);
  6278. loc1._intersection = loc2;
  6279. loc2._intersection = loc1;
  6280. if (!include || include(loc1)) {
  6281. CurveLocation.insert(locations, loc1, true);
  6282. }
  6283. }
  6284. }
  6285. }
  6286. function addCurveIntersections(v1, v2, c1, c2, locations, include, flip,
  6287. recursion, calls, tMin, tMax, uMin, uMax) {
  6288. if (++calls >= 4096 || ++recursion >= 40)
  6289. return calls;
  6290. var fatLineEpsilon = 1e-9,
  6291. q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7],
  6292. getSignedDistance = Line.getSignedDistance,
  6293. d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]),
  6294. d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]),
  6295. factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
  6296. dMin = factor * Math.min(0, d1, d2),
  6297. dMax = factor * Math.max(0, d1, d2),
  6298. dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]),
  6299. dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]),
  6300. dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]),
  6301. dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]),
  6302. hull = getConvexHull(dp0, dp1, dp2, dp3),
  6303. top = hull[0],
  6304. bottom = hull[1],
  6305. tMinClip,
  6306. tMaxClip;
  6307. if (d1 === 0 && d2 === 0
  6308. && dp0 === 0 && dp1 === 0 && dp2 === 0 && dp3 === 0
  6309. || (tMinClip = clipConvexHull(top, bottom, dMin, dMax)) == null
  6310. || (tMaxClip = clipConvexHull(top.reverse(), bottom.reverse(),
  6311. dMin, dMax)) == null)
  6312. return calls;
  6313. var tMinNew = tMin + (tMax - tMin) * tMinClip,
  6314. tMaxNew = tMin + (tMax - tMin) * tMaxClip;
  6315. if (Math.max(uMax - uMin, tMaxNew - tMinNew) < fatLineEpsilon) {
  6316. var t = (tMinNew + tMaxNew) / 2,
  6317. u = (uMin + uMax) / 2;
  6318. addLocation(locations, include,
  6319. flip ? c2 : c1, flip ? u : t,
  6320. flip ? c1 : c2, flip ? t : u);
  6321. } else {
  6322. v1 = Curve.getPart(v1, tMinClip, tMaxClip);
  6323. if (tMaxClip - tMinClip > 0.8) {
  6324. if (tMaxNew - tMinNew > uMax - uMin) {
  6325. var parts = Curve.subdivide(v1, 0.5),
  6326. t = (tMinNew + tMaxNew) / 2;
  6327. calls = addCurveIntersections(
  6328. v2, parts[0], c2, c1, locations, include, !flip,
  6329. recursion, calls, uMin, uMax, tMinNew, t);
  6330. calls = addCurveIntersections(
  6331. v2, parts[1], c2, c1, locations, include, !flip,
  6332. recursion, calls, uMin, uMax, t, tMaxNew);
  6333. } else {
  6334. var parts = Curve.subdivide(v2, 0.5),
  6335. u = (uMin + uMax) / 2;
  6336. calls = addCurveIntersections(
  6337. parts[0], v1, c2, c1, locations, include, !flip,
  6338. recursion, calls, uMin, u, tMinNew, tMaxNew);
  6339. calls = addCurveIntersections(
  6340. parts[1], v1, c2, c1, locations, include, !flip,
  6341. recursion, calls, u, uMax, tMinNew, tMaxNew);
  6342. }
  6343. } else {
  6344. if (uMax - uMin >= fatLineEpsilon) {
  6345. calls = addCurveIntersections(
  6346. v2, v1, c2, c1, locations, include, !flip,
  6347. recursion, calls, uMin, uMax, tMinNew, tMaxNew);
  6348. } else {
  6349. calls = addCurveIntersections(
  6350. v1, v2, c1, c2, locations, include, flip,
  6351. recursion, calls, tMinNew, tMaxNew, uMin, uMax);
  6352. }
  6353. }
  6354. }
  6355. return calls;
  6356. }
  6357. function getConvexHull(dq0, dq1, dq2, dq3) {
  6358. var p0 = [ 0, dq0 ],
  6359. p1 = [ 1 / 3, dq1 ],
  6360. p2 = [ 2 / 3, dq2 ],
  6361. p3 = [ 1, dq3 ],
  6362. dist1 = dq1 - (2 * dq0 + dq3) / 3,
  6363. dist2 = dq2 - (dq0 + 2 * dq3) / 3,
  6364. hull;
  6365. if (dist1 * dist2 < 0) {
  6366. hull = [[p0, p1, p3], [p0, p2, p3]];
  6367. } else {
  6368. var distRatio = dist1 / dist2;
  6369. hull = [
  6370. distRatio >= 2 ? [p0, p1, p3]
  6371. : distRatio <= 0.5 ? [p0, p2, p3]
  6372. : [p0, p1, p2, p3],
  6373. [p0, p3]
  6374. ];
  6375. }
  6376. return (dist1 || dist2) < 0 ? hull.reverse() : hull;
  6377. }
  6378. function clipConvexHull(hullTop, hullBottom, dMin, dMax) {
  6379. if (hullTop[0][1] < dMin) {
  6380. return clipConvexHullPart(hullTop, true, dMin);
  6381. } else if (hullBottom[0][1] > dMax) {
  6382. return clipConvexHullPart(hullBottom, false, dMax);
  6383. } else {
  6384. return hullTop[0][0];
  6385. }
  6386. }
  6387. function clipConvexHullPart(part, top, threshold) {
  6388. var px = part[0][0],
  6389. py = part[0][1];
  6390. for (var i = 1, l = part.length; i < l; i++) {
  6391. var qx = part[i][0],
  6392. qy = part[i][1];
  6393. if (top ? qy >= threshold : qy <= threshold) {
  6394. return qy === threshold ? qx
  6395. : px + (threshold - py) * (qx - px) / (qy - py);
  6396. }
  6397. px = qx;
  6398. py = qy;
  6399. }
  6400. return null;
  6401. }
  6402. function getCurveLineIntersections(v, px, py, vx, vy) {
  6403. var isZero = Numerical.isZero;
  6404. if (isZero(vx) && isZero(vy)) {
  6405. var t = Curve.getTimeOf(v, new Point(px, py));
  6406. return t === null ? [] : [t];
  6407. }
  6408. var angle = Math.atan2(-vy, vx),
  6409. sin = Math.sin(angle),
  6410. cos = Math.cos(angle),
  6411. rv = [],
  6412. roots = [];
  6413. for (var i = 0; i < 8; i += 2) {
  6414. var x = v[i] - px,
  6415. y = v[i + 1] - py;
  6416. rv.push(
  6417. x * cos - y * sin,
  6418. x * sin + y * cos);
  6419. }
  6420. Curve.solveCubic(rv, 1, 0, roots, 0, 1);
  6421. return roots;
  6422. }
  6423. function addCurveLineIntersections(v1, v2, c1, c2, locations, include,
  6424. flip) {
  6425. var x1 = v2[0], y1 = v2[1],
  6426. x2 = v2[6], y2 = v2[7],
  6427. roots = getCurveLineIntersections(v1, x1, y1, x2 - x1, y2 - y1);
  6428. for (var i = 0, l = roots.length; i < l; i++) {
  6429. var t1 = roots[i],
  6430. p1 = Curve.getPoint(v1, t1),
  6431. t2 = Curve.getTimeOf(v2, p1);
  6432. if (t2 !== null) {
  6433. addLocation(locations, include,
  6434. flip ? c2 : c1, flip ? t2 : t1,
  6435. flip ? c1 : c2, flip ? t1 : t2);
  6436. }
  6437. }
  6438. }
  6439. function addLineIntersection(v1, v2, c1, c2, locations, include) {
  6440. var pt = Line.intersect(
  6441. v1[0], v1[1], v1[6], v1[7],
  6442. v2[0], v2[1], v2[6], v2[7]);
  6443. if (pt) {
  6444. addLocation(locations, include,
  6445. c1, Curve.getTimeOf(v1, pt),
  6446. c2, Curve.getTimeOf(v2, pt));
  6447. }
  6448. }
  6449. function getCurveIntersections(v1, v2, c1, c2, locations, include) {
  6450. var epsilon = 1e-12,
  6451. min = Math.min,
  6452. max = Math.max;
  6453. if (max(v1[0], v1[2], v1[4], v1[6]) + epsilon >
  6454. min(v2[0], v2[2], v2[4], v2[6]) &&
  6455. min(v1[0], v1[2], v1[4], v1[6]) - epsilon <
  6456. max(v2[0], v2[2], v2[4], v2[6]) &&
  6457. max(v1[1], v1[3], v1[5], v1[7]) + epsilon >
  6458. min(v2[1], v2[3], v2[5], v2[7]) &&
  6459. min(v1[1], v1[3], v1[5], v1[7]) - epsilon <
  6460. max(v2[1], v2[3], v2[5], v2[7])) {
  6461. var overlaps = getOverlaps(v1, v2);
  6462. if (overlaps) {
  6463. for (var i = 0; i < 2; i++) {
  6464. var overlap = overlaps[i];
  6465. addLocation(locations, include,
  6466. c1, overlap[0],
  6467. c2, overlap[1], true);
  6468. }
  6469. } else {
  6470. var straight1 = Curve.isStraight(v1),
  6471. straight2 = Curve.isStraight(v2),
  6472. straight = straight1 && straight2,
  6473. flip = straight1 && !straight2,
  6474. before = locations.length;
  6475. (straight
  6476. ? addLineIntersection
  6477. : straight1 || straight2
  6478. ? addCurveLineIntersections
  6479. : addCurveIntersections)(
  6480. flip ? v2 : v1, flip ? v1 : v2,
  6481. flip ? c2 : c1, flip ? c1 : c2,
  6482. locations, include, flip,
  6483. 0, 0, 0, 1, 0, 1);
  6484. if (!straight || locations.length === before) {
  6485. for (var i = 0; i < 4; i++) {
  6486. var t1 = i >> 1,
  6487. t2 = i & 1,
  6488. i1 = t1 * 6,
  6489. i2 = t2 * 6,
  6490. p1 = new Point(v1[i1], v1[i1 + 1]),
  6491. p2 = new Point(v2[i2], v2[i2 + 1]);
  6492. if (p1.isClose(p2, epsilon)) {
  6493. addLocation(locations, include,
  6494. c1, t1,
  6495. c2, t2);
  6496. }
  6497. }
  6498. }
  6499. }
  6500. }
  6501. return locations;
  6502. }
  6503. function getLoopIntersection(v1, c1, locations, include) {
  6504. var info = Curve.classify(v1);
  6505. if (info.type === 'loop') {
  6506. var roots = info.roots;
  6507. addLocation(locations, include,
  6508. c1, roots[0],
  6509. c1, roots[1]);
  6510. }
  6511. return locations;
  6512. }
  6513. function getIntersections(curves1, curves2, include, matrix1, matrix2,
  6514. _returnFirst) {
  6515. var self = !curves2;
  6516. if (self)
  6517. curves2 = curves1;
  6518. var length1 = curves1.length,
  6519. length2 = curves2.length,
  6520. values2 = [],
  6521. arrays = [],
  6522. locations,
  6523. current;
  6524. for (var i = 0; i < length2; i++)
  6525. values2[i] = curves2[i].getValues(matrix2);
  6526. for (var i = 0; i < length1; i++) {
  6527. var curve1 = curves1[i],
  6528. values1 = self ? values2[i] : curve1.getValues(matrix1),
  6529. path1 = curve1.getPath();
  6530. if (path1 !== current) {
  6531. current = path1;
  6532. locations = [];
  6533. arrays.push(locations);
  6534. }
  6535. if (self) {
  6536. getLoopIntersection(values1, curve1, locations, include);
  6537. }
  6538. for (var j = self ? i + 1 : 0; j < length2; j++) {
  6539. if (_returnFirst && locations.length)
  6540. return locations;
  6541. getCurveIntersections(values1, values2[j], curve1, curves2[j],
  6542. locations, include);
  6543. }
  6544. }
  6545. locations = [];
  6546. for (var i = 0, l = arrays.length; i < l; i++) {
  6547. Base.push(locations, arrays[i]);
  6548. }
  6549. return locations;
  6550. }
  6551. function getOverlaps(v1, v2) {
  6552. function getSquaredLineLength(v) {
  6553. var x = v[6] - v[0],
  6554. y = v[7] - v[1];
  6555. return x * x + y * y;
  6556. }
  6557. var abs = Math.abs,
  6558. getDistance = Line.getDistance,
  6559. timeEpsilon = 1e-8,
  6560. geomEpsilon = 1e-7,
  6561. straight1 = Curve.isStraight(v1),
  6562. straight2 = Curve.isStraight(v2),
  6563. straightBoth = straight1 && straight2,
  6564. flip = getSquaredLineLength(v1) < getSquaredLineLength(v2),
  6565. l1 = flip ? v2 : v1,
  6566. l2 = flip ? v1 : v2,
  6567. px = l1[0], py = l1[1],
  6568. vx = l1[6] - px, vy = l1[7] - py;
  6569. if (getDistance(px, py, vx, vy, l2[0], l2[1], true) < geomEpsilon &&
  6570. getDistance(px, py, vx, vy, l2[6], l2[7], true) < geomEpsilon) {
  6571. if (!straightBoth &&
  6572. getDistance(px, py, vx, vy, l1[2], l1[3], true) < geomEpsilon &&
  6573. getDistance(px, py, vx, vy, l1[4], l1[5], true) < geomEpsilon &&
  6574. getDistance(px, py, vx, vy, l2[2], l2[3], true) < geomEpsilon &&
  6575. getDistance(px, py, vx, vy, l2[4], l2[5], true) < geomEpsilon) {
  6576. straight1 = straight2 = straightBoth = true;
  6577. }
  6578. } else if (straightBoth) {
  6579. return null;
  6580. }
  6581. if (straight1 ^ straight2) {
  6582. return null;
  6583. }
  6584. var v = [v1, v2],
  6585. pairs = [];
  6586. for (var i = 0; i < 4 && pairs.length < 2; i++) {
  6587. var i1 = i & 1,
  6588. i2 = i1 ^ 1,
  6589. t1 = i >> 1,
  6590. t2 = Curve.getTimeOf(v[i1], new Point(
  6591. v[i2][t1 ? 6 : 0],
  6592. v[i2][t1 ? 7 : 1]));
  6593. if (t2 != null) {
  6594. var pair = i1 ? [t1, t2] : [t2, t1];
  6595. if (!pairs.length ||
  6596. abs(pair[0] - pairs[0][0]) > timeEpsilon &&
  6597. abs(pair[1] - pairs[0][1]) > timeEpsilon) {
  6598. pairs.push(pair);
  6599. }
  6600. }
  6601. if (i > 2 && !pairs.length)
  6602. break;
  6603. }
  6604. if (pairs.length !== 2) {
  6605. pairs = null;
  6606. } else if (!straightBoth) {
  6607. var o1 = Curve.getPart(v1, pairs[0][0], pairs[1][0]),
  6608. o2 = Curve.getPart(v2, pairs[0][1], pairs[1][1]);
  6609. if (abs(o2[2] - o1[2]) > geomEpsilon ||
  6610. abs(o2[3] - o1[3]) > geomEpsilon ||
  6611. abs(o2[4] - o1[4]) > geomEpsilon ||
  6612. abs(o2[5] - o1[5]) > geomEpsilon)
  6613. pairs = null;
  6614. }
  6615. return pairs;
  6616. }
  6617. function getTimesWithTangent(v, tangent) {
  6618. var x0 = v[0], y0 = v[1],
  6619. x1 = v[2], y1 = v[3],
  6620. x2 = v[4], y2 = v[5],
  6621. x3 = v[6], y3 = v[7],
  6622. normalized = tangent.normalize(),
  6623. tx = normalized.x,
  6624. ty = normalized.y,
  6625. ax = 3 * x3 - 9 * x2 + 9 * x1 - 3 * x0,
  6626. ay = 3 * y3 - 9 * y2 + 9 * y1 - 3 * y0,
  6627. bx = 6 * x2 - 12 * x1 + 6 * x0,
  6628. by = 6 * y2 - 12 * y1 + 6 * y0,
  6629. cx = 3 * x1 - 3 * x0,
  6630. cy = 3 * y1 - 3 * y0,
  6631. den = 2 * ax * ty - 2 * ay * tx,
  6632. times = [];
  6633. if (Math.abs(den) < Numerical.CURVETIME_EPSILON) {
  6634. var num = ax * cy - ay * cx,
  6635. den = ax * by - ay * bx;
  6636. if (den != 0) {
  6637. var t = -num / den;
  6638. if (t >= 0 && t <= 1) times.push(t);
  6639. }
  6640. } else {
  6641. var delta = (bx * bx - 4 * ax * cx) * ty * ty +
  6642. (-2 * bx * by + 4 * ay * cx + 4 * ax * cy) * tx * ty +
  6643. (by * by - 4 * ay * cy) * tx * tx,
  6644. k = bx * ty - by * tx;
  6645. if (delta >= 0 && den != 0) {
  6646. var d = Math.sqrt(delta),
  6647. t0 = -(k + d) / den,
  6648. t1 = (-k + d) / den;
  6649. if (t0 >= 0 && t0 <= 1) times.push(t0);
  6650. if (t1 >= 0 && t1 <= 1) times.push(t1);
  6651. }
  6652. }
  6653. return times;
  6654. }
  6655. return {
  6656. getIntersections: function(curve) {
  6657. var v1 = this.getValues(),
  6658. v2 = curve && curve !== this && curve.getValues();
  6659. return v2 ? getCurveIntersections(v1, v2, this, curve, [])
  6660. : getLoopIntersection(v1, this, []);
  6661. },
  6662. statics: {
  6663. getOverlaps: getOverlaps,
  6664. getIntersections: getIntersections,
  6665. getCurveLineIntersections: getCurveLineIntersections,
  6666. getTimesWithTangent: getTimesWithTangent
  6667. }
  6668. };
  6669. });
  6670. var CurveLocation = Base.extend({
  6671. _class: 'CurveLocation',
  6672. initialize: function CurveLocation(curve, time, point, _overlap, _distance) {
  6673. if (time >= 0.99999999) {
  6674. var next = curve.getNext();
  6675. if (next) {
  6676. time = 0;
  6677. curve = next;
  6678. }
  6679. }
  6680. this._setCurve(curve);
  6681. this._time = time;
  6682. this._point = point || curve.getPointAtTime(time);
  6683. this._overlap = _overlap;
  6684. this._distance = _distance;
  6685. this._intersection = this._next = this._previous = null;
  6686. },
  6687. _setCurve: function(curve) {
  6688. var path = curve._path;
  6689. this._path = path;
  6690. this._version = path ? path._version : 0;
  6691. this._curve = curve;
  6692. this._segment = null;
  6693. this._segment1 = curve._segment1;
  6694. this._segment2 = curve._segment2;
  6695. },
  6696. _setSegment: function(segment) {
  6697. this._setCurve(segment.getCurve());
  6698. this._segment = segment;
  6699. this._time = segment === this._segment1 ? 0 : 1;
  6700. this._point = segment._point.clone();
  6701. },
  6702. getSegment: function() {
  6703. var segment = this._segment;
  6704. if (!segment) {
  6705. var curve = this.getCurve(),
  6706. time = this.getTime();
  6707. if (time === 0) {
  6708. segment = curve._segment1;
  6709. } else if (time === 1) {
  6710. segment = curve._segment2;
  6711. } else if (time != null) {
  6712. segment = curve.getPartLength(0, time)
  6713. < curve.getPartLength(time, 1)
  6714. ? curve._segment1
  6715. : curve._segment2;
  6716. }
  6717. this._segment = segment;
  6718. }
  6719. return segment;
  6720. },
  6721. getCurve: function() {
  6722. var path = this._path,
  6723. that = this;
  6724. if (path && path._version !== this._version) {
  6725. this._time = this._offset = this._curveOffset = this._curve = null;
  6726. }
  6727. function trySegment(segment) {
  6728. var curve = segment && segment.getCurve();
  6729. if (curve && (that._time = curve.getTimeOf(that._point)) != null) {
  6730. that._setCurve(curve);
  6731. return curve;
  6732. }
  6733. }
  6734. return this._curve
  6735. || trySegment(this._segment)
  6736. || trySegment(this._segment1)
  6737. || trySegment(this._segment2.getPrevious());
  6738. },
  6739. getPath: function() {
  6740. var curve = this.getCurve();
  6741. return curve && curve._path;
  6742. },
  6743. getIndex: function() {
  6744. var curve = this.getCurve();
  6745. return curve && curve.getIndex();
  6746. },
  6747. getTime: function() {
  6748. var curve = this.getCurve(),
  6749. time = this._time;
  6750. return curve && time == null
  6751. ? this._time = curve.getTimeOf(this._point)
  6752. : time;
  6753. },
  6754. getParameter: '#getTime',
  6755. getPoint: function() {
  6756. return this._point;
  6757. },
  6758. getOffset: function() {
  6759. var offset = this._offset;
  6760. if (offset == null) {
  6761. offset = 0;
  6762. var path = this.getPath(),
  6763. index = this.getIndex();
  6764. if (path && index != null) {
  6765. var curves = path.getCurves();
  6766. for (var i = 0; i < index; i++)
  6767. offset += curves[i].getLength();
  6768. }
  6769. this._offset = offset += this.getCurveOffset();
  6770. }
  6771. return offset;
  6772. },
  6773. getCurveOffset: function() {
  6774. var offset = this._curveOffset;
  6775. if (offset == null) {
  6776. var curve = this.getCurve(),
  6777. time = this.getTime();
  6778. this._curveOffset = offset = time != null && curve
  6779. && curve.getPartLength(0, time);
  6780. }
  6781. return offset;
  6782. },
  6783. getIntersection: function() {
  6784. return this._intersection;
  6785. },
  6786. getDistance: function() {
  6787. return this._distance;
  6788. },
  6789. divide: function() {
  6790. var curve = this.getCurve(),
  6791. res = curve && curve.divideAtTime(this.getTime());
  6792. if (res) {
  6793. this._setSegment(res._segment1);
  6794. }
  6795. return res;
  6796. },
  6797. split: function() {
  6798. var curve = this.getCurve(),
  6799. path = curve._path,
  6800. res = curve && curve.splitAtTime(this.getTime());
  6801. if (res) {
  6802. this._setSegment(path.getLastSegment());
  6803. }
  6804. return res;
  6805. },
  6806. equals: function(loc, _ignoreOther) {
  6807. var res = this === loc;
  6808. if (!res && loc instanceof CurveLocation) {
  6809. var c1 = this.getCurve(),
  6810. c2 = loc.getCurve(),
  6811. p1 = c1._path,
  6812. p2 = c2._path;
  6813. if (p1 === p2) {
  6814. var abs = Math.abs,
  6815. epsilon = 1e-7,
  6816. diff = abs(this.getOffset() - loc.getOffset()),
  6817. i1 = !_ignoreOther && this._intersection,
  6818. i2 = !_ignoreOther && loc._intersection;
  6819. res = (diff < epsilon
  6820. || p1 && abs(p1.getLength() - diff) < epsilon)
  6821. && (!i1 && !i2 || i1 && i2 && i1.equals(i2, true));
  6822. }
  6823. }
  6824. return res;
  6825. },
  6826. toString: function() {
  6827. var parts = [],
  6828. point = this.getPoint(),
  6829. f = Formatter.instance;
  6830. if (point)
  6831. parts.push('point: ' + point);
  6832. var index = this.getIndex();
  6833. if (index != null)
  6834. parts.push('index: ' + index);
  6835. var time = this.getTime();
  6836. if (time != null)
  6837. parts.push('time: ' + f.number(time));
  6838. if (this._distance != null)
  6839. parts.push('distance: ' + f.number(this._distance));
  6840. return '{ ' + parts.join(', ') + ' }';
  6841. },
  6842. isTouching: function() {
  6843. var inter = this._intersection;
  6844. if (inter && this.getTangent().isCollinear(inter.getTangent())) {
  6845. var curve1 = this.getCurve(),
  6846. curve2 = inter.getCurve();
  6847. return !(curve1.isStraight() && curve2.isStraight()
  6848. && curve1.getLine().intersect(curve2.getLine()));
  6849. }
  6850. return false;
  6851. },
  6852. isCrossing: function() {
  6853. var inter = this._intersection;
  6854. if (!inter)
  6855. return false;
  6856. var t1 = this.getTime(),
  6857. t2 = inter.getTime(),
  6858. tMin = 1e-8,
  6859. tMax = 1 - tMin,
  6860. t1Inside = t1 >= tMin && t1 <= tMax,
  6861. t2Inside = t2 >= tMin && t2 <= tMax;
  6862. if (t1Inside && t2Inside)
  6863. return !this.isTouching();
  6864. var c2 = this.getCurve(),
  6865. c1 = t1 < tMin ? c2.getPrevious() : c2,
  6866. c4 = inter.getCurve(),
  6867. c3 = t2 < tMin ? c4.getPrevious() : c4;
  6868. if (t1 > tMax)
  6869. c2 = c2.getNext();
  6870. if (t2 > tMax)
  6871. c4 = c4.getNext();
  6872. if (!c1 || !c2 || !c3 || !c4)
  6873. return false;
  6874. var offsets = [];
  6875. function addOffsets(curve, end) {
  6876. var v = curve.getValues(),
  6877. roots = Curve.classify(v).roots || Curve.getPeaks(v),
  6878. count = roots.length,
  6879. t = end && count > 1 ? roots[count - 1]
  6880. : count > 0 ? roots[0]
  6881. : 0.5;
  6882. offsets.push(Curve.getLength(v, end ? t : 0, end ? 1 : t) / 2);
  6883. }
  6884. function isInRange(angle, min, max) {
  6885. return min < max
  6886. ? angle > min && angle < max
  6887. : angle > min || angle < max;
  6888. }
  6889. if (!t1Inside) {
  6890. addOffsets(c1, true);
  6891. addOffsets(c2, false);
  6892. }
  6893. if (!t2Inside) {
  6894. addOffsets(c3, true);
  6895. addOffsets(c4, false);
  6896. }
  6897. var pt = this.getPoint(),
  6898. offset = Math.min.apply(Math, offsets),
  6899. v2 = t1Inside ? c2.getTangentAtTime(t1)
  6900. : c2.getPointAt(offset).subtract(pt),
  6901. v1 = t1Inside ? v2.negate()
  6902. : c1.getPointAt(-offset).subtract(pt),
  6903. v4 = t2Inside ? c4.getTangentAtTime(t2)
  6904. : c4.getPointAt(offset).subtract(pt),
  6905. v3 = t2Inside ? v4.negate()
  6906. : c3.getPointAt(-offset).subtract(pt),
  6907. a1 = v1.getAngle(),
  6908. a2 = v2.getAngle(),
  6909. a3 = v3.getAngle(),
  6910. a4 = v4.getAngle();
  6911. return !!(t1Inside
  6912. ? (isInRange(a1, a3, a4) ^ isInRange(a2, a3, a4)) &&
  6913. (isInRange(a1, a4, a3) ^ isInRange(a2, a4, a3))
  6914. : (isInRange(a3, a1, a2) ^ isInRange(a4, a1, a2)) &&
  6915. (isInRange(a3, a2, a1) ^ isInRange(a4, a2, a1)));
  6916. },
  6917. hasOverlap: function() {
  6918. return !!this._overlap;
  6919. }
  6920. }, Base.each(Curve._evaluateMethods, function(name) {
  6921. var get = name + 'At';
  6922. this[name] = function() {
  6923. var curve = this.getCurve(),
  6924. time = this.getTime();
  6925. return time != null && curve && curve[get](time, true);
  6926. };
  6927. }, {
  6928. preserve: true
  6929. }),
  6930. new function() {
  6931. function insert(locations, loc, merge) {
  6932. var length = locations.length,
  6933. l = 0,
  6934. r = length - 1;
  6935. function search(index, dir) {
  6936. for (var i = index + dir; i >= -1 && i <= length; i += dir) {
  6937. var loc2 = locations[((i % length) + length) % length];
  6938. if (!loc.getPoint().isClose(loc2.getPoint(),
  6939. 1e-7))
  6940. break;
  6941. if (loc.equals(loc2))
  6942. return loc2;
  6943. }
  6944. return null;
  6945. }
  6946. while (l <= r) {
  6947. var m = (l + r) >>> 1,
  6948. loc2 = locations[m],
  6949. found;
  6950. if (merge && (found = loc.equals(loc2) ? loc2
  6951. : (search(m, -1) || search(m, 1)))) {
  6952. if (loc._overlap) {
  6953. found._overlap = found._intersection._overlap = true;
  6954. }
  6955. return found;
  6956. }
  6957. var path1 = loc.getPath(),
  6958. path2 = loc2.getPath(),
  6959. diff = path1 !== path2
  6960. ? path1._id - path2._id
  6961. : (loc.getIndex() + loc.getTime())
  6962. - (loc2.getIndex() + loc2.getTime());
  6963. if (diff < 0) {
  6964. r = m - 1;
  6965. } else {
  6966. l = m + 1;
  6967. }
  6968. }
  6969. locations.splice(l, 0, loc);
  6970. return loc;
  6971. }
  6972. return { statics: {
  6973. insert: insert,
  6974. expand: function(locations) {
  6975. var expanded = locations.slice();
  6976. for (var i = locations.length - 1; i >= 0; i--) {
  6977. insert(expanded, locations[i]._intersection, false);
  6978. }
  6979. return expanded;
  6980. }
  6981. }};
  6982. });
  6983. var PathItem = Item.extend({
  6984. _class: 'PathItem',
  6985. _selectBounds: false,
  6986. _canScaleStroke: true,
  6987. beans: true,
  6988. initialize: function PathItem() {
  6989. },
  6990. statics: {
  6991. create: function(arg) {
  6992. var data,
  6993. segments,
  6994. compound;
  6995. if (Base.isPlainObject(arg)) {
  6996. segments = arg.segments;
  6997. data = arg.pathData;
  6998. } else if (Array.isArray(arg)) {
  6999. segments = arg;
  7000. } else if (typeof arg === 'string') {
  7001. data = arg;
  7002. }
  7003. if (segments) {
  7004. var first = segments[0];
  7005. compound = first && Array.isArray(first[0]);
  7006. } else if (data) {
  7007. compound = (data.match(/m/gi) || []).length > 1
  7008. || /z\s*\S+/i.test(data);
  7009. }
  7010. var ctor = compound ? CompoundPath : Path;
  7011. return new ctor(arg);
  7012. }
  7013. },
  7014. _asPathItem: function() {
  7015. return this;
  7016. },
  7017. isClockwise: function() {
  7018. return this.getArea() >= 0;
  7019. },
  7020. setClockwise: function(clockwise) {
  7021. if (this.isClockwise() != (clockwise = !!clockwise))
  7022. this.reverse();
  7023. },
  7024. setPathData: function(data) {
  7025. var parts = data && data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
  7026. coords,
  7027. relative = false,
  7028. previous,
  7029. control,
  7030. current = new Point(),
  7031. start = new Point();
  7032. function getCoord(index, coord) {
  7033. var val = +coords[index];
  7034. if (relative)
  7035. val += current[coord];
  7036. return val;
  7037. }
  7038. function getPoint(index) {
  7039. return new Point(
  7040. getCoord(index, 'x'),
  7041. getCoord(index + 1, 'y')
  7042. );
  7043. }
  7044. this.clear();
  7045. for (var i = 0, l = parts && parts.length; i < l; i++) {
  7046. var part = parts[i],
  7047. command = part[0],
  7048. lower = command.toLowerCase();
  7049. coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
  7050. var length = coords && coords.length;
  7051. relative = command === lower;
  7052. if (previous === 'z' && !/[mz]/.test(lower))
  7053. this.moveTo(current);
  7054. switch (lower) {
  7055. case 'm':
  7056. case 'l':
  7057. var move = lower === 'm';
  7058. for (var j = 0; j < length; j += 2) {
  7059. this[move ? 'moveTo' : 'lineTo'](current = getPoint(j));
  7060. if (move) {
  7061. start = current;
  7062. move = false;
  7063. }
  7064. }
  7065. control = current;
  7066. break;
  7067. case 'h':
  7068. case 'v':
  7069. var coord = lower === 'h' ? 'x' : 'y';
  7070. current = current.clone();
  7071. for (var j = 0; j < length; j++) {
  7072. current[coord] = getCoord(j, coord);
  7073. this.lineTo(current);
  7074. }
  7075. control = current;
  7076. break;
  7077. case 'c':
  7078. for (var j = 0; j < length; j += 6) {
  7079. this.cubicCurveTo(
  7080. getPoint(j),
  7081. control = getPoint(j + 2),
  7082. current = getPoint(j + 4));
  7083. }
  7084. break;
  7085. case 's':
  7086. for (var j = 0; j < length; j += 4) {
  7087. this.cubicCurveTo(
  7088. /[cs]/.test(previous)
  7089. ? current.multiply(2).subtract(control)
  7090. : current,
  7091. control = getPoint(j),
  7092. current = getPoint(j + 2));
  7093. previous = lower;
  7094. }
  7095. break;
  7096. case 'q':
  7097. for (var j = 0; j < length; j += 4) {
  7098. this.quadraticCurveTo(
  7099. control = getPoint(j),
  7100. current = getPoint(j + 2));
  7101. }
  7102. break;
  7103. case 't':
  7104. for (var j = 0; j < length; j += 2) {
  7105. this.quadraticCurveTo(
  7106. control = (/[qt]/.test(previous)
  7107. ? current.multiply(2).subtract(control)
  7108. : current),
  7109. current = getPoint(j));
  7110. previous = lower;
  7111. }
  7112. break;
  7113. case 'a':
  7114. for (var j = 0; j < length; j += 7) {
  7115. this.arcTo(current = getPoint(j + 5),
  7116. new Size(+coords[j], +coords[j + 1]),
  7117. +coords[j + 2], +coords[j + 4], +coords[j + 3]);
  7118. }
  7119. break;
  7120. case 'z':
  7121. this.closePath(1e-12);
  7122. current = start;
  7123. break;
  7124. }
  7125. previous = lower;
  7126. }
  7127. },
  7128. _canComposite: function() {
  7129. return !(this.hasFill() && this.hasStroke());
  7130. },
  7131. _contains: function(point) {
  7132. var winding = point.isInside(
  7133. this.getBounds({ internal: true, handle: true }))
  7134. ? this._getWinding(point)
  7135. : {};
  7136. return winding.onPath || !!(this.getFillRule() === 'evenodd'
  7137. ? winding.windingL & 1 || winding.windingR & 1
  7138. : winding.winding);
  7139. },
  7140. getIntersections: function(path, include, _matrix, _returnFirst) {
  7141. var self = this === path || !path,
  7142. matrix1 = this._matrix._orNullIfIdentity(),
  7143. matrix2 = self ? matrix1
  7144. : (_matrix || path._matrix)._orNullIfIdentity();
  7145. return self || this.getBounds(matrix1).intersects(
  7146. path.getBounds(matrix2), 1e-12)
  7147. ? Curve.getIntersections(
  7148. this.getCurves(), !self && path.getCurves(), include,
  7149. matrix1, matrix2, _returnFirst)
  7150. : [];
  7151. },
  7152. getCrossings: function(path) {
  7153. return this.getIntersections(path, function(inter) {
  7154. return inter.hasOverlap() || inter.isCrossing();
  7155. });
  7156. },
  7157. getNearestLocation: function() {
  7158. var point = Point.read(arguments),
  7159. curves = this.getCurves(),
  7160. minDist = Infinity,
  7161. minLoc = null;
  7162. for (var i = 0, l = curves.length; i < l; i++) {
  7163. var loc = curves[i].getNearestLocation(point);
  7164. if (loc._distance < minDist) {
  7165. minDist = loc._distance;
  7166. minLoc = loc;
  7167. }
  7168. }
  7169. return minLoc;
  7170. },
  7171. getNearestPoint: function() {
  7172. var loc = this.getNearestLocation.apply(this, arguments);
  7173. return loc ? loc.getPoint() : loc;
  7174. },
  7175. interpolate: function(from, to, factor) {
  7176. var isPath = !this._children,
  7177. name = isPath ? '_segments' : '_children',
  7178. itemsFrom = from[name],
  7179. itemsTo = to[name],
  7180. items = this[name];
  7181. if (!itemsFrom || !itemsTo || itemsFrom.length !== itemsTo.length) {
  7182. throw new Error('Invalid operands in interpolate() call: ' +
  7183. from + ', ' + to);
  7184. }
  7185. var current = items.length,
  7186. length = itemsTo.length;
  7187. if (current < length) {
  7188. var ctor = isPath ? Segment : Path;
  7189. for (var i = current; i < length; i++) {
  7190. this.add(new ctor());
  7191. }
  7192. } else if (current > length) {
  7193. this[isPath ? 'removeSegments' : 'removeChildren'](length, current);
  7194. }
  7195. for (var i = 0; i < length; i++) {
  7196. items[i].interpolate(itemsFrom[i], itemsTo[i], factor);
  7197. }
  7198. if (isPath) {
  7199. this.setClosed(from._closed);
  7200. this._changed(9);
  7201. }
  7202. },
  7203. compare: function(path) {
  7204. var ok = false;
  7205. if (path) {
  7206. var paths1 = this._children || [this],
  7207. paths2 = path._children ? path._children.slice() : [path],
  7208. length1 = paths1.length,
  7209. length2 = paths2.length,
  7210. matched = [],
  7211. count = 0;
  7212. ok = true;
  7213. for (var i1 = length1 - 1; i1 >= 0 && ok; i1--) {
  7214. var path1 = paths1[i1];
  7215. ok = false;
  7216. for (var i2 = length2 - 1; i2 >= 0 && !ok; i2--) {
  7217. if (path1.compare(paths2[i2])) {
  7218. if (!matched[i2]) {
  7219. matched[i2] = true;
  7220. count++;
  7221. }
  7222. ok = true;
  7223. }
  7224. }
  7225. }
  7226. ok = ok && count === length2;
  7227. }
  7228. return ok;
  7229. },
  7230. });
  7231. var Path = PathItem.extend({
  7232. _class: 'Path',
  7233. _serializeFields: {
  7234. segments: [],
  7235. closed: false
  7236. },
  7237. initialize: function Path(arg) {
  7238. this._closed = false;
  7239. this._segments = [];
  7240. this._version = 0;
  7241. var segments = Array.isArray(arg)
  7242. ? typeof arg[0] === 'object'
  7243. ? arg
  7244. : arguments
  7245. : arg && (arg.size === undefined && (arg.x !== undefined
  7246. || arg.point !== undefined))
  7247. ? arguments
  7248. : null;
  7249. if (segments && segments.length > 0) {
  7250. this.setSegments(segments);
  7251. } else {
  7252. this._curves = undefined;
  7253. this._segmentSelection = 0;
  7254. if (!segments && typeof arg === 'string') {
  7255. this.setPathData(arg);
  7256. arg = null;
  7257. }
  7258. }
  7259. this._initialize(!segments && arg);
  7260. },
  7261. _equals: function(item) {
  7262. return this._closed === item._closed
  7263. && Base.equals(this._segments, item._segments);
  7264. },
  7265. copyContent: function(source) {
  7266. this.setSegments(source._segments);
  7267. this._closed = source._closed;
  7268. },
  7269. _changed: function _changed(flags) {
  7270. _changed.base.call(this, flags);
  7271. if (flags & 8) {
  7272. this._length = this._area = undefined;
  7273. if (flags & 32) {
  7274. this._version++;
  7275. } else if (this._curves) {
  7276. for (var i = 0, l = this._curves.length; i < l; i++)
  7277. this._curves[i]._changed();
  7278. }
  7279. } else if (flags & 64) {
  7280. this._bounds = undefined;
  7281. }
  7282. },
  7283. getStyle: function() {
  7284. var parent = this._parent;
  7285. return (parent instanceof CompoundPath ? parent : this)._style;
  7286. },
  7287. getSegments: function() {
  7288. return this._segments;
  7289. },
  7290. setSegments: function(segments) {
  7291. var fullySelected = this.isFullySelected(),
  7292. length = segments && segments.length;
  7293. this._segments.length = 0;
  7294. this._segmentSelection = 0;
  7295. this._curves = undefined;
  7296. if (length) {
  7297. var last = segments[length - 1];
  7298. if (typeof last === 'boolean') {
  7299. this.setClosed(last);
  7300. length--;
  7301. }
  7302. this._add(Segment.readList(segments, 0, {}, length));
  7303. }
  7304. if (fullySelected)
  7305. this.setFullySelected(true);
  7306. },
  7307. getFirstSegment: function() {
  7308. return this._segments[0];
  7309. },
  7310. getLastSegment: function() {
  7311. return this._segments[this._segments.length - 1];
  7312. },
  7313. getCurves: function() {
  7314. var curves = this._curves,
  7315. segments = this._segments;
  7316. if (!curves) {
  7317. var length = this._countCurves();
  7318. curves = this._curves = new Array(length);
  7319. for (var i = 0; i < length; i++)
  7320. curves[i] = new Curve(this, segments[i],
  7321. segments[i + 1] || segments[0]);
  7322. }
  7323. return curves;
  7324. },
  7325. getFirstCurve: function() {
  7326. return this.getCurves()[0];
  7327. },
  7328. getLastCurve: function() {
  7329. var curves = this.getCurves();
  7330. return curves[curves.length - 1];
  7331. },
  7332. isClosed: function() {
  7333. return this._closed;
  7334. },
  7335. setClosed: function(closed) {
  7336. if (this._closed != (closed = !!closed)) {
  7337. this._closed = closed;
  7338. if (this._curves) {
  7339. var length = this._curves.length = this._countCurves();
  7340. if (closed)
  7341. this._curves[length - 1] = new Curve(this,
  7342. this._segments[length - 1], this._segments[0]);
  7343. }
  7344. this._changed(41);
  7345. }
  7346. }
  7347. }, {
  7348. beans: true,
  7349. getPathData: function(_matrix, _precision) {
  7350. var segments = this._segments,
  7351. length = segments.length,
  7352. f = new Formatter(_precision),
  7353. coords = new Array(6),
  7354. first = true,
  7355. curX, curY,
  7356. prevX, prevY,
  7357. inX, inY,
  7358. outX, outY,
  7359. parts = [];
  7360. function addSegment(segment, skipLine) {
  7361. segment._transformCoordinates(_matrix, coords);
  7362. curX = coords[0];
  7363. curY = coords[1];
  7364. if (first) {
  7365. parts.push('M' + f.pair(curX, curY));
  7366. first = false;
  7367. } else {
  7368. inX = coords[2];
  7369. inY = coords[3];
  7370. if (inX === curX && inY === curY
  7371. && outX === prevX && outY === prevY) {
  7372. if (!skipLine) {
  7373. var dx = curX - prevX,
  7374. dy = curY - prevY;
  7375. parts.push(
  7376. dx === 0 ? 'v' + f.number(dy)
  7377. : dy === 0 ? 'h' + f.number(dx)
  7378. : 'l' + f.pair(dx, dy));
  7379. }
  7380. } else {
  7381. parts.push('c' + f.pair(outX - prevX, outY - prevY)
  7382. + ' ' + f.pair( inX - prevX, inY - prevY)
  7383. + ' ' + f.pair(curX - prevX, curY - prevY));
  7384. }
  7385. }
  7386. prevX = curX;
  7387. prevY = curY;
  7388. outX = coords[4];
  7389. outY = coords[5];
  7390. }
  7391. if (!length)
  7392. return '';
  7393. for (var i = 0; i < length; i++)
  7394. addSegment(segments[i]);
  7395. if (this._closed && length > 0) {
  7396. addSegment(segments[0], true);
  7397. parts.push('z');
  7398. }
  7399. return parts.join('');
  7400. },
  7401. isEmpty: function() {
  7402. return !this._segments.length;
  7403. },
  7404. _transformContent: function(matrix) {
  7405. var segments = this._segments,
  7406. coords = new Array(6);
  7407. for (var i = 0, l = segments.length; i < l; i++)
  7408. segments[i]._transformCoordinates(matrix, coords, true);
  7409. return true;
  7410. },
  7411. _add: function(segs, index) {
  7412. var segments = this._segments,
  7413. curves = this._curves,
  7414. amount = segs.length,
  7415. append = index == null,
  7416. index = append ? segments.length : index;
  7417. for (var i = 0; i < amount; i++) {
  7418. var segment = segs[i];
  7419. if (segment._path)
  7420. segment = segs[i] = segment.clone();
  7421. segment._path = this;
  7422. segment._index = index + i;
  7423. if (segment._selection)
  7424. this._updateSelection(segment, 0, segment._selection);
  7425. }
  7426. if (append) {
  7427. Base.push(segments, segs);
  7428. } else {
  7429. segments.splice.apply(segments, [index, 0].concat(segs));
  7430. for (var i = index + amount, l = segments.length; i < l; i++)
  7431. segments[i]._index = i;
  7432. }
  7433. if (curves) {
  7434. var total = this._countCurves(),
  7435. start = index > 0 && index + amount - 1 === total ? index - 1
  7436. : index,
  7437. insert = start,
  7438. end = Math.min(start + amount, total);
  7439. if (segs._curves) {
  7440. curves.splice.apply(curves, [start, 0].concat(segs._curves));
  7441. insert += segs._curves.length;
  7442. }
  7443. for (var i = insert; i < end; i++)
  7444. curves.splice(i, 0, new Curve(this, null, null));
  7445. this._adjustCurves(start, end);
  7446. }
  7447. this._changed(41);
  7448. return segs;
  7449. },
  7450. _adjustCurves: function(start, end) {
  7451. var segments = this._segments,
  7452. curves = this._curves,
  7453. curve;
  7454. for (var i = start; i < end; i++) {
  7455. curve = curves[i];
  7456. curve._path = this;
  7457. curve._segment1 = segments[i];
  7458. curve._segment2 = segments[i + 1] || segments[0];
  7459. curve._changed();
  7460. }
  7461. if (curve = curves[this._closed && !start ? segments.length - 1
  7462. : start - 1]) {
  7463. curve._segment2 = segments[start] || segments[0];
  7464. curve._changed();
  7465. }
  7466. if (curve = curves[end]) {
  7467. curve._segment1 = segments[end];
  7468. curve._changed();
  7469. }
  7470. },
  7471. _countCurves: function() {
  7472. var length = this._segments.length;
  7473. return !this._closed && length > 0 ? length - 1 : length;
  7474. },
  7475. add: function(segment1 ) {
  7476. return arguments.length > 1 && typeof segment1 !== 'number'
  7477. ? this._add(Segment.readList(arguments))
  7478. : this._add([ Segment.read(arguments) ])[0];
  7479. },
  7480. insert: function(index, segment1 ) {
  7481. return arguments.length > 2 && typeof segment1 !== 'number'
  7482. ? this._add(Segment.readList(arguments, 1), index)
  7483. : this._add([ Segment.read(arguments, 1) ], index)[0];
  7484. },
  7485. addSegment: function() {
  7486. return this._add([ Segment.read(arguments) ])[0];
  7487. },
  7488. insertSegment: function(index ) {
  7489. return this._add([ Segment.read(arguments, 1) ], index)[0];
  7490. },
  7491. addSegments: function(segments) {
  7492. return this._add(Segment.readList(segments));
  7493. },
  7494. insertSegments: function(index, segments) {
  7495. return this._add(Segment.readList(segments), index);
  7496. },
  7497. removeSegment: function(index) {
  7498. return this.removeSegments(index, index + 1)[0] || null;
  7499. },
  7500. removeSegments: function(start, end, _includeCurves) {
  7501. start = start || 0;
  7502. end = Base.pick(end, this._segments.length);
  7503. var segments = this._segments,
  7504. curves = this._curves,
  7505. count = segments.length,
  7506. removed = segments.splice(start, end - start),
  7507. amount = removed.length;
  7508. if (!amount)
  7509. return removed;
  7510. for (var i = 0; i < amount; i++) {
  7511. var segment = removed[i];
  7512. if (segment._selection)
  7513. this._updateSelection(segment, segment._selection, 0);
  7514. segment._index = segment._path = null;
  7515. }
  7516. for (var i = start, l = segments.length; i < l; i++)
  7517. segments[i]._index = i;
  7518. if (curves) {
  7519. var index = start > 0 && end === count + (this._closed ? 1 : 0)
  7520. ? start - 1
  7521. : start,
  7522. curves = curves.splice(index, amount);
  7523. for (var i = curves.length - 1; i >= 0; i--)
  7524. curves[i]._path = null;
  7525. if (_includeCurves)
  7526. removed._curves = curves.slice(1);
  7527. this._adjustCurves(index, index);
  7528. }
  7529. this._changed(41);
  7530. return removed;
  7531. },
  7532. clear: '#removeSegments',
  7533. hasHandles: function() {
  7534. var segments = this._segments;
  7535. for (var i = 0, l = segments.length; i < l; i++) {
  7536. if (segments[i].hasHandles())
  7537. return true;
  7538. }
  7539. return false;
  7540. },
  7541. clearHandles: function() {
  7542. var segments = this._segments;
  7543. for (var i = 0, l = segments.length; i < l; i++)
  7544. segments[i].clearHandles();
  7545. },
  7546. getLength: function() {
  7547. if (this._length == null) {
  7548. var curves = this.getCurves(),
  7549. length = 0;
  7550. for (var i = 0, l = curves.length; i < l; i++)
  7551. length += curves[i].getLength();
  7552. this._length = length;
  7553. }
  7554. return this._length;
  7555. },
  7556. getArea: function() {
  7557. var area = this._area;
  7558. if (area == null) {
  7559. var segments = this._segments,
  7560. closed = this._closed;
  7561. area = 0;
  7562. for (var i = 0, l = segments.length; i < l; i++) {
  7563. var last = i + 1 === l;
  7564. area += Curve.getArea(Curve.getValues(
  7565. segments[i], segments[last ? 0 : i + 1],
  7566. null, last && !closed));
  7567. }
  7568. this._area = area;
  7569. }
  7570. return area;
  7571. },
  7572. isFullySelected: function() {
  7573. var length = this._segments.length;
  7574. return this.isSelected() && length > 0 && this._segmentSelection
  7575. === length * 7;
  7576. },
  7577. setFullySelected: function(selected) {
  7578. if (selected)
  7579. this._selectSegments(true);
  7580. this.setSelected(selected);
  7581. },
  7582. setSelection: function setSelection(selection) {
  7583. if (!(selection & 1))
  7584. this._selectSegments(false);
  7585. setSelection.base.call(this, selection);
  7586. },
  7587. _selectSegments: function(selected) {
  7588. var segments = this._segments,
  7589. length = segments.length,
  7590. selection = selected ? 7 : 0;
  7591. this._segmentSelection = selection * length;
  7592. for (var i = 0; i < length; i++)
  7593. segments[i]._selection = selection;
  7594. },
  7595. _updateSelection: function(segment, oldSelection, newSelection) {
  7596. segment._selection = newSelection;
  7597. var selection = this._segmentSelection += newSelection - oldSelection;
  7598. if (selection > 0)
  7599. this.setSelected(true);
  7600. },
  7601. divideAt: function(location) {
  7602. var loc = this.getLocationAt(location),
  7603. curve;
  7604. return loc && (curve = loc.getCurve().divideAt(loc.getCurveOffset()))
  7605. ? curve._segment1
  7606. : null;
  7607. },
  7608. splitAt: function(location) {
  7609. var loc = this.getLocationAt(location),
  7610. index = loc && loc.index,
  7611. time = loc && loc.time,
  7612. tMin = 1e-8,
  7613. tMax = 1 - tMin;
  7614. if (time > tMax) {
  7615. index++;
  7616. time = 0;
  7617. }
  7618. var curves = this.getCurves();
  7619. if (index >= 0 && index < curves.length) {
  7620. if (time >= tMin) {
  7621. curves[index++].divideAtTime(time);
  7622. }
  7623. var segs = this.removeSegments(index, this._segments.length, true),
  7624. path;
  7625. if (this._closed) {
  7626. this.setClosed(false);
  7627. path = this;
  7628. } else {
  7629. path = new Path(Item.NO_INSERT);
  7630. path.insertAbove(this);
  7631. path.copyAttributes(this);
  7632. }
  7633. path._add(segs, 0);
  7634. this.addSegment(segs[0]);
  7635. return path;
  7636. }
  7637. return null;
  7638. },
  7639. split: function(index, time) {
  7640. var curve,
  7641. location = time === undefined ? index
  7642. : (curve = this.getCurves()[index])
  7643. && curve.getLocationAtTime(time);
  7644. return location != null ? this.splitAt(location) : null;
  7645. },
  7646. join: function(path, tolerance) {
  7647. var epsilon = tolerance || 0;
  7648. if (path && path !== this) {
  7649. var segments = path._segments,
  7650. last1 = this.getLastSegment(),
  7651. last2 = path.getLastSegment();
  7652. if (!last2)
  7653. return this;
  7654. if (last1 && last1._point.isClose(last2._point, epsilon))
  7655. path.reverse();
  7656. var first2 = path.getFirstSegment();
  7657. if (last1 && last1._point.isClose(first2._point, epsilon)) {
  7658. last1.setHandleOut(first2._handleOut);
  7659. this._add(segments.slice(1));
  7660. } else {
  7661. var first1 = this.getFirstSegment();
  7662. if (first1 && first1._point.isClose(first2._point, epsilon))
  7663. path.reverse();
  7664. last2 = path.getLastSegment();
  7665. if (first1 && first1._point.isClose(last2._point, epsilon)) {
  7666. first1.setHandleIn(last2._handleIn);
  7667. this._add(segments.slice(0, segments.length - 1), 0);
  7668. } else {
  7669. this._add(segments.slice());
  7670. }
  7671. }
  7672. if (path._closed)
  7673. this._add([segments[0]]);
  7674. path.remove();
  7675. }
  7676. var first = this.getFirstSegment(),
  7677. last = this.getLastSegment();
  7678. if (first !== last && first._point.isClose(last._point, epsilon)) {
  7679. first.setHandleIn(last._handleIn);
  7680. last.remove();
  7681. this.setClosed(true);
  7682. }
  7683. return this;
  7684. },
  7685. reduce: function(options) {
  7686. var curves = this.getCurves(),
  7687. simplify = options && options.simplify,
  7688. tolerance = simplify ? 1e-7 : 0;
  7689. for (var i = curves.length - 1; i >= 0; i--) {
  7690. var curve = curves[i];
  7691. if (!curve.hasHandles() && (!curve.hasLength(tolerance)
  7692. || simplify && curve.isCollinear(curve.getNext())))
  7693. curve.remove();
  7694. }
  7695. return this;
  7696. },
  7697. reverse: function() {
  7698. this._segments.reverse();
  7699. for (var i = 0, l = this._segments.length; i < l; i++) {
  7700. var segment = this._segments[i];
  7701. var handleIn = segment._handleIn;
  7702. segment._handleIn = segment._handleOut;
  7703. segment._handleOut = handleIn;
  7704. segment._index = i;
  7705. }
  7706. this._curves = null;
  7707. this._changed(9);
  7708. },
  7709. flatten: function(flatness) {
  7710. var flattener = new PathFlattener(this, flatness || 0.25, 256, true),
  7711. parts = flattener.parts,
  7712. length = parts.length,
  7713. segments = [];
  7714. for (var i = 0; i < length; i++) {
  7715. segments.push(new Segment(parts[i].curve.slice(0, 2)));
  7716. }
  7717. if (!this._closed && length > 0) {
  7718. segments.push(new Segment(parts[length - 1].curve.slice(6)));
  7719. }
  7720. this.setSegments(segments);
  7721. },
  7722. simplify: function(tolerance) {
  7723. var segments = new PathFitter(this).fit(tolerance || 2.5);
  7724. if (segments)
  7725. this.setSegments(segments);
  7726. return !!segments;
  7727. },
  7728. smooth: function(options) {
  7729. var that = this,
  7730. opts = options || {},
  7731. type = opts.type || 'asymmetric',
  7732. segments = this._segments,
  7733. length = segments.length,
  7734. closed = this._closed;
  7735. function getIndex(value, _default) {
  7736. var index = value && value.index;
  7737. if (index != null) {
  7738. var path = value.path;
  7739. if (path && path !== that)
  7740. throw new Error(value._class + ' ' + index + ' of ' + path
  7741. + ' is not part of ' + that);
  7742. if (_default && value instanceof Curve)
  7743. index++;
  7744. } else {
  7745. index = typeof value === 'number' ? value : _default;
  7746. }
  7747. return Math.min(index < 0 && closed
  7748. ? index % length
  7749. : index < 0 ? index + length : index, length - 1);
  7750. }
  7751. var loop = closed && opts.from === undefined && opts.to === undefined,
  7752. from = getIndex(opts.from, 0),
  7753. to = getIndex(opts.to, length - 1);
  7754. if (from > to) {
  7755. if (closed) {
  7756. from -= length;
  7757. } else {
  7758. var tmp = from;
  7759. from = to;
  7760. to = tmp;
  7761. }
  7762. }
  7763. if (/^(?:asymmetric|continuous)$/.test(type)) {
  7764. var asymmetric = type === 'asymmetric',
  7765. min = Math.min,
  7766. amount = to - from + 1,
  7767. n = amount - 1,
  7768. padding = loop ? min(amount, 4) : 1,
  7769. paddingLeft = padding,
  7770. paddingRight = padding,
  7771. knots = [];
  7772. if (!closed) {
  7773. paddingLeft = min(1, from);
  7774. paddingRight = min(1, length - to - 1);
  7775. }
  7776. n += paddingLeft + paddingRight;
  7777. if (n <= 1)
  7778. return;
  7779. for (var i = 0, j = from - paddingLeft; i <= n; i++, j++) {
  7780. knots[i] = segments[(j < 0 ? j + length : j) % length]._point;
  7781. }
  7782. var x = knots[0]._x + 2 * knots[1]._x,
  7783. y = knots[0]._y + 2 * knots[1]._y,
  7784. f = 2,
  7785. n_1 = n - 1,
  7786. rx = [x],
  7787. ry = [y],
  7788. rf = [f],
  7789. px = [],
  7790. py = [];
  7791. for (var i = 1; i < n; i++) {
  7792. var internal = i < n_1,
  7793. a = internal ? 1 : asymmetric ? 1 : 2,
  7794. b = internal ? 4 : asymmetric ? 2 : 7,
  7795. u = internal ? 4 : asymmetric ? 3 : 8,
  7796. v = internal ? 2 : asymmetric ? 0 : 1,
  7797. m = a / f;
  7798. f = rf[i] = b - m;
  7799. x = rx[i] = u * knots[i]._x + v * knots[i + 1]._x - m * x;
  7800. y = ry[i] = u * knots[i]._y + v * knots[i + 1]._y - m * y;
  7801. }
  7802. px[n_1] = rx[n_1] / rf[n_1];
  7803. py[n_1] = ry[n_1] / rf[n_1];
  7804. for (var i = n - 2; i >= 0; i--) {
  7805. px[i] = (rx[i] - px[i + 1]) / rf[i];
  7806. py[i] = (ry[i] - py[i + 1]) / rf[i];
  7807. }
  7808. px[n] = (3 * knots[n]._x - px[n_1]) / 2;
  7809. py[n] = (3 * knots[n]._y - py[n_1]) / 2;
  7810. for (var i = paddingLeft, max = n - paddingRight, j = from;
  7811. i <= max; i++, j++) {
  7812. var segment = segments[j < 0 ? j + length : j],
  7813. pt = segment._point,
  7814. hx = px[i] - pt._x,
  7815. hy = py[i] - pt._y;
  7816. if (loop || i < max)
  7817. segment.setHandleOut(hx, hy);
  7818. if (loop || i > paddingLeft)
  7819. segment.setHandleIn(-hx, -hy);
  7820. }
  7821. } else {
  7822. for (var i = from; i <= to; i++) {
  7823. segments[i < 0 ? i + length : i].smooth(opts,
  7824. !loop && i === from, !loop && i === to);
  7825. }
  7826. }
  7827. },
  7828. toShape: function(insert) {
  7829. if (!this._closed)
  7830. return null;
  7831. var segments = this._segments,
  7832. type,
  7833. size,
  7834. radius,
  7835. topCenter;
  7836. function isCollinear(i, j) {
  7837. var seg1 = segments[i],
  7838. seg2 = seg1.getNext(),
  7839. seg3 = segments[j],
  7840. seg4 = seg3.getNext();
  7841. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  7842. && seg3._handleOut.isZero() && seg4._handleIn.isZero()
  7843. && seg2._point.subtract(seg1._point).isCollinear(
  7844. seg4._point.subtract(seg3._point));
  7845. }
  7846. function isOrthogonal(i) {
  7847. var seg2 = segments[i],
  7848. seg1 = seg2.getPrevious(),
  7849. seg3 = seg2.getNext();
  7850. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  7851. && seg2._handleOut.isZero() && seg3._handleIn.isZero()
  7852. && seg2._point.subtract(seg1._point).isOrthogonal(
  7853. seg3._point.subtract(seg2._point));
  7854. }
  7855. function isArc(i) {
  7856. var seg1 = segments[i],
  7857. seg2 = seg1.getNext(),
  7858. handle1 = seg1._handleOut,
  7859. handle2 = seg2._handleIn,
  7860. kappa = 0.5522847498307936;
  7861. if (handle1.isOrthogonal(handle2)) {
  7862. var pt1 = seg1._point,
  7863. pt2 = seg2._point,
  7864. corner = new Line(pt1, handle1, true).intersect(
  7865. new Line(pt2, handle2, true), true);
  7866. return corner && Numerical.isZero(handle1.getLength() /
  7867. corner.subtract(pt1).getLength() - kappa)
  7868. && Numerical.isZero(handle2.getLength() /
  7869. corner.subtract(pt2).getLength() - kappa);
  7870. }
  7871. return false;
  7872. }
  7873. function getDistance(i, j) {
  7874. return segments[i]._point.getDistance(segments[j]._point);
  7875. }
  7876. if (!this.hasHandles() && segments.length === 4
  7877. && isCollinear(0, 2) && isCollinear(1, 3) && isOrthogonal(1)) {
  7878. type = Shape.Rectangle;
  7879. size = new Size(getDistance(0, 3), getDistance(0, 1));
  7880. topCenter = segments[1]._point.add(segments[2]._point).divide(2);
  7881. } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
  7882. && isArc(6) && isCollinear(1, 5) && isCollinear(3, 7)) {
  7883. type = Shape.Rectangle;
  7884. size = new Size(getDistance(1, 6), getDistance(0, 3));
  7885. radius = size.subtract(new Size(getDistance(0, 7),
  7886. getDistance(1, 2))).divide(2);
  7887. topCenter = segments[3]._point.add(segments[4]._point).divide(2);
  7888. } else if (segments.length === 4
  7889. && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
  7890. if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
  7891. type = Shape.Circle;
  7892. radius = getDistance(0, 2) / 2;
  7893. } else {
  7894. type = Shape.Ellipse;
  7895. radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
  7896. }
  7897. topCenter = segments[1]._point;
  7898. }
  7899. if (type) {
  7900. var center = this.getPosition(true),
  7901. shape = new type({
  7902. center: center,
  7903. size: size,
  7904. radius: radius,
  7905. insert: false
  7906. });
  7907. shape.copyAttributes(this, true);
  7908. shape._matrix.prepend(this._matrix);
  7909. shape.rotate(topCenter.subtract(center).getAngle() + 90);
  7910. if (insert === undefined || insert)
  7911. shape.insertAbove(this);
  7912. return shape;
  7913. }
  7914. return null;
  7915. },
  7916. toPath: '#clone',
  7917. compare: function compare(path) {
  7918. if (!path || path instanceof CompoundPath)
  7919. return compare.base.call(this, path);
  7920. var curves1 = this.getCurves(),
  7921. curves2 = path.getCurves(),
  7922. length1 = curves1.length,
  7923. length2 = curves2.length;
  7924. if (!length1 || !length2) {
  7925. return length1 == length2;
  7926. }
  7927. var v1 = curves1[0].getValues(),
  7928. values2 = [],
  7929. pos1 = 0, pos2,
  7930. end1 = 0, end2;
  7931. for (var i = 0; i < length2; i++) {
  7932. var v2 = curves2[i].getValues();
  7933. values2.push(v2);
  7934. var overlaps = Curve.getOverlaps(v1, v2);
  7935. if (overlaps) {
  7936. pos2 = !i && overlaps[0][0] > 0 ? length2 - 1 : i;
  7937. end2 = overlaps[0][1];
  7938. break;
  7939. }
  7940. }
  7941. var abs = Math.abs,
  7942. epsilon = 1e-8,
  7943. v2 = values2[pos2],
  7944. start2;
  7945. while (v1 && v2) {
  7946. var overlaps = Curve.getOverlaps(v1, v2);
  7947. if (overlaps) {
  7948. var t1 = overlaps[0][0];
  7949. if (abs(t1 - end1) < epsilon) {
  7950. end1 = overlaps[1][0];
  7951. if (end1 === 1) {
  7952. v1 = ++pos1 < length1 ? curves1[pos1].getValues() : null;
  7953. end1 = 0;
  7954. }
  7955. var t2 = overlaps[0][1];
  7956. if (abs(t2 - end2) < epsilon) {
  7957. if (!start2)
  7958. start2 = [pos2, t2];
  7959. end2 = overlaps[1][1];
  7960. if (end2 === 1) {
  7961. if (++pos2 >= length2)
  7962. pos2 = 0;
  7963. v2 = values2[pos2] || curves2[pos2].getValues();
  7964. end2 = 0;
  7965. }
  7966. if (!v1) {
  7967. return start2[0] === pos2 && start2[1] === end2;
  7968. }
  7969. continue;
  7970. }
  7971. }
  7972. }
  7973. break;
  7974. }
  7975. return false;
  7976. },
  7977. _hitTestSelf: function(point, options, viewMatrix, strokeMatrix) {
  7978. var that = this,
  7979. style = this.getStyle(),
  7980. segments = this._segments,
  7981. numSegments = segments.length,
  7982. closed = this._closed,
  7983. tolerancePadding = options._tolerancePadding,
  7984. strokePadding = tolerancePadding,
  7985. join, cap, miterLimit,
  7986. area, loc, res,
  7987. hitStroke = options.stroke && style.hasStroke(),
  7988. hitFill = options.fill && style.hasFill(),
  7989. hitCurves = options.curves,
  7990. strokeRadius = hitStroke
  7991. ? style.getStrokeWidth() / 2
  7992. : hitFill && options.tolerance > 0 || hitCurves
  7993. ? 0 : null;
  7994. if (strokeRadius !== null) {
  7995. if (strokeRadius > 0) {
  7996. join = style.getStrokeJoin();
  7997. cap = style.getStrokeCap();
  7998. miterLimit = style.getMiterLimit();
  7999. strokePadding = strokePadding.add(
  8000. Path._getStrokePadding(strokeRadius, strokeMatrix));
  8001. } else {
  8002. join = cap = 'round';
  8003. }
  8004. }
  8005. function isCloseEnough(pt, padding) {
  8006. return point.subtract(pt).divide(padding).length <= 1;
  8007. }
  8008. function checkSegmentPoint(seg, pt, name) {
  8009. if (!options.selected || pt.isSelected()) {
  8010. var anchor = seg._point;
  8011. if (pt !== anchor)
  8012. pt = pt.add(anchor);
  8013. if (isCloseEnough(pt, strokePadding)) {
  8014. return new HitResult(name, that, {
  8015. segment: seg,
  8016. point: pt
  8017. });
  8018. }
  8019. }
  8020. }
  8021. function checkSegmentPoints(seg, ends) {
  8022. return (ends || options.segments)
  8023. && checkSegmentPoint(seg, seg._point, 'segment')
  8024. || (!ends && options.handles) && (
  8025. checkSegmentPoint(seg, seg._handleIn, 'handle-in') ||
  8026. checkSegmentPoint(seg, seg._handleOut, 'handle-out'));
  8027. }
  8028. function addToArea(point) {
  8029. area.add(point);
  8030. }
  8031. function checkSegmentStroke(segment) {
  8032. var isJoin = closed || segment._index > 0
  8033. && segment._index < numSegments - 1;
  8034. if ((isJoin ? join : cap) === 'round') {
  8035. return isCloseEnough(segment._point, strokePadding);
  8036. } else {
  8037. area = new Path({ internal: true, closed: true });
  8038. if (isJoin) {
  8039. if (!segment.isSmooth()) {
  8040. Path._addBevelJoin(segment, join, strokeRadius,
  8041. miterLimit, null, strokeMatrix, addToArea, true);
  8042. }
  8043. } else if (cap === 'square') {
  8044. Path._addSquareCap(segment, cap, strokeRadius, null,
  8045. strokeMatrix, addToArea, true);
  8046. }
  8047. if (!area.isEmpty()) {
  8048. var loc;
  8049. return area.contains(point)
  8050. || (loc = area.getNearestLocation(point))
  8051. && isCloseEnough(loc.getPoint(), tolerancePadding);
  8052. }
  8053. }
  8054. }
  8055. if (options.ends && !options.segments && !closed) {
  8056. if (res = checkSegmentPoints(segments[0], true)
  8057. || checkSegmentPoints(segments[numSegments - 1], true))
  8058. return res;
  8059. } else if (options.segments || options.handles) {
  8060. for (var i = 0; i < numSegments; i++)
  8061. if (res = checkSegmentPoints(segments[i]))
  8062. return res;
  8063. }
  8064. if (strokeRadius !== null) {
  8065. loc = this.getNearestLocation(point);
  8066. if (loc) {
  8067. var time = loc.getTime();
  8068. if (time === 0 || time === 1 && numSegments > 1) {
  8069. if (!checkSegmentStroke(loc.getSegment()))
  8070. loc = null;
  8071. } else if (!isCloseEnough(loc.getPoint(), strokePadding)) {
  8072. loc = null;
  8073. }
  8074. }
  8075. if (!loc && join === 'miter' && numSegments > 1) {
  8076. for (var i = 0; i < numSegments; i++) {
  8077. var segment = segments[i];
  8078. if (point.getDistance(segment._point)
  8079. <= miterLimit * strokeRadius
  8080. && checkSegmentStroke(segment)) {
  8081. loc = segment.getLocation();
  8082. break;
  8083. }
  8084. }
  8085. }
  8086. }
  8087. return !loc && hitFill && this._contains(point)
  8088. || loc && !hitStroke && !hitCurves
  8089. ? new HitResult('fill', this)
  8090. : loc
  8091. ? new HitResult(hitStroke ? 'stroke' : 'curve', this, {
  8092. location: loc,
  8093. point: loc.getPoint()
  8094. })
  8095. : null;
  8096. }
  8097. }, Base.each(Curve._evaluateMethods,
  8098. function(name) {
  8099. this[name + 'At'] = function(offset) {
  8100. var loc = this.getLocationAt(offset);
  8101. return loc && loc[name]();
  8102. };
  8103. },
  8104. {
  8105. beans: false,
  8106. getLocationOf: function() {
  8107. var point = Point.read(arguments),
  8108. curves = this.getCurves();
  8109. for (var i = 0, l = curves.length; i < l; i++) {
  8110. var loc = curves[i].getLocationOf(point);
  8111. if (loc)
  8112. return loc;
  8113. }
  8114. return null;
  8115. },
  8116. getOffsetOf: function() {
  8117. var loc = this.getLocationOf.apply(this, arguments);
  8118. return loc ? loc.getOffset() : null;
  8119. },
  8120. getLocationAt: function(offset) {
  8121. if (typeof offset === 'number') {
  8122. var curves = this.getCurves(),
  8123. length = 0;
  8124. for (var i = 0, l = curves.length; i < l; i++) {
  8125. var start = length,
  8126. curve = curves[i];
  8127. length += curve.getLength();
  8128. if (length > offset) {
  8129. return curve.getLocationAt(offset - start);
  8130. }
  8131. }
  8132. if (curves.length > 0 && offset <= this.getLength()) {
  8133. return new CurveLocation(curves[curves.length - 1], 1);
  8134. }
  8135. } else if (offset && offset.getPath && offset.getPath() === this) {
  8136. return offset;
  8137. }
  8138. return null;
  8139. },
  8140. getOffsetsWithTangent: function() {
  8141. var tangent = Point.read(arguments);
  8142. if (tangent.isZero()) {
  8143. return [];
  8144. }
  8145. var offsets = [];
  8146. var curveStart = 0;
  8147. var curves = this.getCurves();
  8148. for (var i = 0, l = curves.length; i < l; i++) {
  8149. var curve = curves[i];
  8150. var curveTimes = curve.getTimesWithTangent(tangent);
  8151. for (var j = 0, m = curveTimes.length; j < m; j++) {
  8152. var offset = curveStart + curve.getOffsetAtTime(curveTimes[j]);
  8153. if (offsets.indexOf(offset) < 0) {
  8154. offsets.push(offset);
  8155. }
  8156. }
  8157. curveStart += curve.length;
  8158. }
  8159. return offsets;
  8160. }
  8161. }),
  8162. new function() {
  8163. function drawHandles(ctx, segments, matrix, size) {
  8164. var half = size / 2,
  8165. coords = new Array(6),
  8166. pX, pY;
  8167. function drawHandle(index) {
  8168. var hX = coords[index],
  8169. hY = coords[index + 1];
  8170. if (pX != hX || pY != hY) {
  8171. ctx.beginPath();
  8172. ctx.moveTo(pX, pY);
  8173. ctx.lineTo(hX, hY);
  8174. ctx.stroke();
  8175. ctx.beginPath();
  8176. ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
  8177. ctx.fill();
  8178. }
  8179. }
  8180. for (var i = 0, l = segments.length; i < l; i++) {
  8181. var segment = segments[i],
  8182. selection = segment._selection;
  8183. segment._transformCoordinates(matrix, coords);
  8184. pX = coords[0];
  8185. pY = coords[1];
  8186. if (selection & 2)
  8187. drawHandle(2);
  8188. if (selection & 4)
  8189. drawHandle(4);
  8190. ctx.fillRect(pX - half, pY - half, size, size);
  8191. if (!(selection & 1)) {
  8192. var fillStyle = ctx.fillStyle;
  8193. ctx.fillStyle = '#ffffff';
  8194. ctx.fillRect(pX - half + 1, pY - half + 1, size - 2, size - 2);
  8195. ctx.fillStyle = fillStyle;
  8196. }
  8197. }
  8198. }
  8199. function drawSegments(ctx, path, matrix) {
  8200. var segments = path._segments,
  8201. length = segments.length,
  8202. coords = new Array(6),
  8203. first = true,
  8204. curX, curY,
  8205. prevX, prevY,
  8206. inX, inY,
  8207. outX, outY;
  8208. function drawSegment(segment) {
  8209. if (matrix) {
  8210. segment._transformCoordinates(matrix, coords);
  8211. curX = coords[0];
  8212. curY = coords[1];
  8213. } else {
  8214. var point = segment._point;
  8215. curX = point._x;
  8216. curY = point._y;
  8217. }
  8218. if (first) {
  8219. ctx.moveTo(curX, curY);
  8220. first = false;
  8221. } else {
  8222. if (matrix) {
  8223. inX = coords[2];
  8224. inY = coords[3];
  8225. } else {
  8226. var handle = segment._handleIn;
  8227. inX = curX + handle._x;
  8228. inY = curY + handle._y;
  8229. }
  8230. if (inX === curX && inY === curY
  8231. && outX === prevX && outY === prevY) {
  8232. ctx.lineTo(curX, curY);
  8233. } else {
  8234. ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
  8235. }
  8236. }
  8237. prevX = curX;
  8238. prevY = curY;
  8239. if (matrix) {
  8240. outX = coords[4];
  8241. outY = coords[5];
  8242. } else {
  8243. var handle = segment._handleOut;
  8244. outX = prevX + handle._x;
  8245. outY = prevY + handle._y;
  8246. }
  8247. }
  8248. for (var i = 0; i < length; i++)
  8249. drawSegment(segments[i]);
  8250. if (path._closed && length > 0)
  8251. drawSegment(segments[0]);
  8252. }
  8253. return {
  8254. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8255. var dontStart = param.dontStart,
  8256. dontPaint = param.dontFinish || param.clip,
  8257. style = this.getStyle(),
  8258. hasFill = style.hasFill(),
  8259. hasStroke = style.hasStroke(),
  8260. dashArray = style.getDashArray(),
  8261. dashLength = !paper.support.nativeDash && hasStroke
  8262. && dashArray && dashArray.length;
  8263. if (!dontStart)
  8264. ctx.beginPath();
  8265. if (hasFill || hasStroke && !dashLength || dontPaint) {
  8266. drawSegments(ctx, this, strokeMatrix);
  8267. if (this._closed)
  8268. ctx.closePath();
  8269. }
  8270. function getOffset(i) {
  8271. return dashArray[((i % dashLength) + dashLength) % dashLength];
  8272. }
  8273. if (!dontPaint && (hasFill || hasStroke)) {
  8274. this._setStyles(ctx, param, viewMatrix);
  8275. if (hasFill) {
  8276. ctx.fill(style.getFillRule());
  8277. ctx.shadowColor = 'rgba(0,0,0,0)';
  8278. }
  8279. if (hasStroke) {
  8280. if (dashLength) {
  8281. if (!dontStart)
  8282. ctx.beginPath();
  8283. var flattener = new PathFlattener(this, 0.25, 32, false,
  8284. strokeMatrix),
  8285. length = flattener.length,
  8286. from = -style.getDashOffset(), to,
  8287. i = 0;
  8288. from = from % length;
  8289. while (from > 0) {
  8290. from -= getOffset(i--) + getOffset(i--);
  8291. }
  8292. while (from < length) {
  8293. to = from + getOffset(i++);
  8294. if (from > 0 || to > 0)
  8295. flattener.drawPart(ctx,
  8296. Math.max(from, 0), Math.max(to, 0));
  8297. from = to + getOffset(i++);
  8298. }
  8299. }
  8300. ctx.stroke();
  8301. }
  8302. }
  8303. },
  8304. _drawSelected: function(ctx, matrix) {
  8305. ctx.beginPath();
  8306. drawSegments(ctx, this, matrix);
  8307. ctx.stroke();
  8308. drawHandles(ctx, this._segments, matrix, paper.settings.handleSize);
  8309. }
  8310. };
  8311. },
  8312. new function() {
  8313. function getCurrentSegment(that) {
  8314. var segments = that._segments;
  8315. if (!segments.length)
  8316. throw new Error('Use a moveTo() command first');
  8317. return segments[segments.length - 1];
  8318. }
  8319. return {
  8320. moveTo: function() {
  8321. var segments = this._segments;
  8322. if (segments.length === 1)
  8323. this.removeSegment(0);
  8324. if (!segments.length)
  8325. this._add([ new Segment(Point.read(arguments)) ]);
  8326. },
  8327. moveBy: function() {
  8328. throw new Error('moveBy() is unsupported on Path items.');
  8329. },
  8330. lineTo: function() {
  8331. this._add([ new Segment(Point.read(arguments)) ]);
  8332. },
  8333. cubicCurveTo: function() {
  8334. var handle1 = Point.read(arguments),
  8335. handle2 = Point.read(arguments),
  8336. to = Point.read(arguments),
  8337. current = getCurrentSegment(this);
  8338. current.setHandleOut(handle1.subtract(current._point));
  8339. this._add([ new Segment(to, handle2.subtract(to)) ]);
  8340. },
  8341. quadraticCurveTo: function() {
  8342. var handle = Point.read(arguments),
  8343. to = Point.read(arguments),
  8344. current = getCurrentSegment(this)._point;
  8345. this.cubicCurveTo(
  8346. handle.add(current.subtract(handle).multiply(1 / 3)),
  8347. handle.add(to.subtract(handle).multiply(1 / 3)),
  8348. to
  8349. );
  8350. },
  8351. curveTo: function() {
  8352. var through = Point.read(arguments),
  8353. to = Point.read(arguments),
  8354. t = Base.pick(Base.read(arguments), 0.5),
  8355. t1 = 1 - t,
  8356. current = getCurrentSegment(this)._point,
  8357. handle = through.subtract(current.multiply(t1 * t1))
  8358. .subtract(to.multiply(t * t)).divide(2 * t * t1);
  8359. if (handle.isNaN())
  8360. throw new Error(
  8361. 'Cannot put a curve through points with parameter = ' + t);
  8362. this.quadraticCurveTo(handle, to);
  8363. },
  8364. arcTo: function() {
  8365. var abs = Math.abs,
  8366. sqrt = Math.sqrt,
  8367. current = getCurrentSegment(this),
  8368. from = current._point,
  8369. to = Point.read(arguments),
  8370. through,
  8371. peek = Base.peek(arguments),
  8372. clockwise = Base.pick(peek, true),
  8373. center, extent, vector, matrix;
  8374. if (typeof clockwise === 'boolean') {
  8375. var middle = from.add(to).divide(2),
  8376. through = middle.add(middle.subtract(from).rotate(
  8377. clockwise ? -90 : 90));
  8378. } else if (Base.remain(arguments) <= 2) {
  8379. through = to;
  8380. to = Point.read(arguments);
  8381. } else {
  8382. var radius = Size.read(arguments),
  8383. isZero = Numerical.isZero;
  8384. if (isZero(radius.width) || isZero(radius.height))
  8385. return this.lineTo(to);
  8386. var rotation = Base.read(arguments),
  8387. clockwise = !!Base.read(arguments),
  8388. large = !!Base.read(arguments),
  8389. middle = from.add(to).divide(2),
  8390. pt = from.subtract(middle).rotate(-rotation),
  8391. x = pt.x,
  8392. y = pt.y,
  8393. rx = abs(radius.width),
  8394. ry = abs(radius.height),
  8395. rxSq = rx * rx,
  8396. rySq = ry * ry,
  8397. xSq = x * x,
  8398. ySq = y * y;
  8399. var factor = sqrt(xSq / rxSq + ySq / rySq);
  8400. if (factor > 1) {
  8401. rx *= factor;
  8402. ry *= factor;
  8403. rxSq = rx * rx;
  8404. rySq = ry * ry;
  8405. }
  8406. factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) /
  8407. (rxSq * ySq + rySq * xSq);
  8408. if (abs(factor) < 1e-12)
  8409. factor = 0;
  8410. if (factor < 0)
  8411. throw new Error(
  8412. 'Cannot create an arc with the given arguments');
  8413. center = new Point(rx * y / ry, -ry * x / rx)
  8414. .multiply((large === clockwise ? -1 : 1) * sqrt(factor))
  8415. .rotate(rotation).add(middle);
  8416. matrix = new Matrix().translate(center).rotate(rotation)
  8417. .scale(rx, ry);
  8418. vector = matrix._inverseTransform(from);
  8419. extent = vector.getDirectedAngle(matrix._inverseTransform(to));
  8420. if (!clockwise && extent > 0)
  8421. extent -= 360;
  8422. else if (clockwise && extent < 0)
  8423. extent += 360;
  8424. }
  8425. if (through) {
  8426. var l1 = new Line(from.add(through).divide(2),
  8427. through.subtract(from).rotate(90), true),
  8428. l2 = new Line(through.add(to).divide(2),
  8429. to.subtract(through).rotate(90), true),
  8430. line = new Line(from, to),
  8431. throughSide = line.getSide(through);
  8432. center = l1.intersect(l2, true);
  8433. if (!center) {
  8434. if (!throughSide)
  8435. return this.lineTo(to);
  8436. throw new Error(
  8437. 'Cannot create an arc with the given arguments');
  8438. }
  8439. vector = from.subtract(center);
  8440. extent = vector.getDirectedAngle(to.subtract(center));
  8441. var centerSide = line.getSide(center, true);
  8442. if (centerSide === 0) {
  8443. extent = throughSide * abs(extent);
  8444. } else if (throughSide === centerSide) {
  8445. extent += extent < 0 ? 360 : -360;
  8446. }
  8447. }
  8448. var epsilon = 1e-7,
  8449. ext = abs(extent),
  8450. count = ext >= 360 ? 4 : Math.ceil((ext - epsilon) / 90),
  8451. inc = extent / count,
  8452. half = inc * Math.PI / 360,
  8453. z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
  8454. segments = [];
  8455. for (var i = 0; i <= count; i++) {
  8456. var pt = to,
  8457. out = null;
  8458. if (i < count) {
  8459. out = vector.rotate(90).multiply(z);
  8460. if (matrix) {
  8461. pt = matrix._transformPoint(vector);
  8462. out = matrix._transformPoint(vector.add(out))
  8463. .subtract(pt);
  8464. } else {
  8465. pt = center.add(vector);
  8466. }
  8467. }
  8468. if (!i) {
  8469. current.setHandleOut(out);
  8470. } else {
  8471. var _in = vector.rotate(-90).multiply(z);
  8472. if (matrix) {
  8473. _in = matrix._transformPoint(vector.add(_in))
  8474. .subtract(pt);
  8475. }
  8476. segments.push(new Segment(pt, _in, out));
  8477. }
  8478. vector = vector.rotate(inc);
  8479. }
  8480. this._add(segments);
  8481. },
  8482. lineBy: function() {
  8483. var to = Point.read(arguments),
  8484. current = getCurrentSegment(this)._point;
  8485. this.lineTo(current.add(to));
  8486. },
  8487. curveBy: function() {
  8488. var through = Point.read(arguments),
  8489. to = Point.read(arguments),
  8490. parameter = Base.read(arguments),
  8491. current = getCurrentSegment(this)._point;
  8492. this.curveTo(current.add(through), current.add(to), parameter);
  8493. },
  8494. cubicCurveBy: function() {
  8495. var handle1 = Point.read(arguments),
  8496. handle2 = Point.read(arguments),
  8497. to = Point.read(arguments),
  8498. current = getCurrentSegment(this)._point;
  8499. this.cubicCurveTo(current.add(handle1), current.add(handle2),
  8500. current.add(to));
  8501. },
  8502. quadraticCurveBy: function() {
  8503. var handle = Point.read(arguments),
  8504. to = Point.read(arguments),
  8505. current = getCurrentSegment(this)._point;
  8506. this.quadraticCurveTo(current.add(handle), current.add(to));
  8507. },
  8508. arcBy: function() {
  8509. var current = getCurrentSegment(this)._point,
  8510. point = current.add(Point.read(arguments)),
  8511. clockwise = Base.pick(Base.peek(arguments), true);
  8512. if (typeof clockwise === 'boolean') {
  8513. this.arcTo(point, clockwise);
  8514. } else {
  8515. this.arcTo(point, current.add(Point.read(arguments)));
  8516. }
  8517. },
  8518. closePath: function(tolerance) {
  8519. this.setClosed(true);
  8520. this.join(this, tolerance);
  8521. }
  8522. };
  8523. }, {
  8524. _getBounds: function(matrix, options) {
  8525. var method = options.handle
  8526. ? 'getHandleBounds'
  8527. : options.stroke
  8528. ? 'getStrokeBounds'
  8529. : 'getBounds';
  8530. return Path[method](this._segments, this._closed, this, matrix, options);
  8531. },
  8532. statics: {
  8533. getBounds: function(segments, closed, path, matrix, options, strokePadding) {
  8534. var first = segments[0];
  8535. if (!first)
  8536. return new Rectangle();
  8537. var coords = new Array(6),
  8538. prevCoords = first._transformCoordinates(matrix, new Array(6)),
  8539. min = prevCoords.slice(0, 2),
  8540. max = min.slice(),
  8541. roots = new Array(2);
  8542. function processSegment(segment) {
  8543. segment._transformCoordinates(matrix, coords);
  8544. for (var i = 0; i < 2; i++) {
  8545. Curve._addBounds(
  8546. prevCoords[i],
  8547. prevCoords[i + 4],
  8548. coords[i + 2],
  8549. coords[i],
  8550. i, strokePadding ? strokePadding[i] : 0, min, max, roots);
  8551. }
  8552. var tmp = prevCoords;
  8553. prevCoords = coords;
  8554. coords = tmp;
  8555. }
  8556. for (var i = 1, l = segments.length; i < l; i++)
  8557. processSegment(segments[i]);
  8558. if (closed)
  8559. processSegment(first);
  8560. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  8561. },
  8562. getStrokeBounds: function(segments, closed, path, matrix, options) {
  8563. var style = path.getStyle(),
  8564. stroke = style.hasStroke(),
  8565. strokeWidth = style.getStrokeWidth(),
  8566. strokeMatrix = stroke && path._getStrokeMatrix(matrix, options),
  8567. strokePadding = stroke && Path._getStrokePadding(strokeWidth,
  8568. strokeMatrix),
  8569. bounds = Path.getBounds(segments, closed, path, matrix, options,
  8570. strokePadding);
  8571. if (!stroke)
  8572. return bounds;
  8573. var strokeRadius = strokeWidth / 2,
  8574. join = style.getStrokeJoin(),
  8575. cap = style.getStrokeCap(),
  8576. miterLimit = style.getMiterLimit(),
  8577. joinBounds = new Rectangle(new Size(strokePadding));
  8578. function addPoint(point) {
  8579. bounds = bounds.include(point);
  8580. }
  8581. function addRound(segment) {
  8582. bounds = bounds.unite(
  8583. joinBounds.setCenter(segment._point.transform(matrix)));
  8584. }
  8585. function addJoin(segment, join) {
  8586. if (join === 'round' || segment.isSmooth()) {
  8587. addRound(segment);
  8588. } else {
  8589. Path._addBevelJoin(segment, join, strokeRadius, miterLimit,
  8590. matrix, strokeMatrix, addPoint);
  8591. }
  8592. }
  8593. function addCap(segment, cap) {
  8594. if (cap === 'round') {
  8595. addRound(segment);
  8596. } else {
  8597. Path._addSquareCap(segment, cap, strokeRadius, matrix,
  8598. strokeMatrix, addPoint);
  8599. }
  8600. }
  8601. var length = segments.length - (closed ? 0 : 1);
  8602. for (var i = 1; i < length; i++)
  8603. addJoin(segments[i], join);
  8604. if (closed) {
  8605. addJoin(segments[0], join);
  8606. } else if (length > 0) {
  8607. addCap(segments[0], cap);
  8608. addCap(segments[segments.length - 1], cap);
  8609. }
  8610. return bounds;
  8611. },
  8612. _getStrokePadding: function(radius, matrix) {
  8613. if (!matrix)
  8614. return [radius, radius];
  8615. var hor = new Point(radius, 0).transform(matrix),
  8616. ver = new Point(0, radius).transform(matrix),
  8617. phi = hor.getAngleInRadians(),
  8618. a = hor.getLength(),
  8619. b = ver.getLength();
  8620. var sin = Math.sin(phi),
  8621. cos = Math.cos(phi),
  8622. tan = Math.tan(phi),
  8623. tx = Math.atan2(b * tan, a),
  8624. ty = Math.atan2(b, tan * a);
  8625. return [Math.abs(a * Math.cos(tx) * cos + b * Math.sin(tx) * sin),
  8626. Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
  8627. },
  8628. _addBevelJoin: function(segment, join, radius, miterLimit, matrix,
  8629. strokeMatrix, addPoint, isArea) {
  8630. var curve2 = segment.getCurve(),
  8631. curve1 = curve2.getPrevious(),
  8632. point = curve2.getPoint1().transform(matrix),
  8633. normal1 = curve1.getNormalAtTime(1).multiply(radius)
  8634. .transform(strokeMatrix),
  8635. normal2 = curve2.getNormalAtTime(0).multiply(radius)
  8636. .transform(strokeMatrix);
  8637. if (normal1.getDirectedAngle(normal2) < 0) {
  8638. normal1 = normal1.negate();
  8639. normal2 = normal2.negate();
  8640. }
  8641. if (isArea)
  8642. addPoint(point);
  8643. addPoint(point.add(normal1));
  8644. if (join === 'miter') {
  8645. var corner = new Line(point.add(normal1),
  8646. new Point(-normal1.y, normal1.x), true
  8647. ).intersect(new Line(point.add(normal2),
  8648. new Point(-normal2.y, normal2.x), true
  8649. ), true);
  8650. if (corner && point.getDistance(corner) <= miterLimit * radius) {
  8651. addPoint(corner);
  8652. }
  8653. }
  8654. addPoint(point.add(normal2));
  8655. },
  8656. _addSquareCap: function(segment, cap, radius, matrix, strokeMatrix,
  8657. addPoint, isArea) {
  8658. var point = segment._point.transform(matrix),
  8659. loc = segment.getLocation(),
  8660. normal = loc.getNormal()
  8661. .multiply(loc.getTime() === 0 ? radius : -radius)
  8662. .transform(strokeMatrix);
  8663. if (cap === 'square') {
  8664. if (isArea) {
  8665. addPoint(point.subtract(normal));
  8666. addPoint(point.add(normal));
  8667. }
  8668. point = point.add(normal.rotate(-90));
  8669. }
  8670. addPoint(point.add(normal));
  8671. addPoint(point.subtract(normal));
  8672. },
  8673. getHandleBounds: function(segments, closed, path, matrix, options) {
  8674. var style = path.getStyle(),
  8675. stroke = options.stroke && style.hasStroke(),
  8676. strokePadding,
  8677. joinPadding;
  8678. if (stroke) {
  8679. var strokeMatrix = path._getStrokeMatrix(matrix, options),
  8680. strokeRadius = style.getStrokeWidth() / 2,
  8681. joinRadius = strokeRadius;
  8682. if (style.getStrokeJoin() === 'miter')
  8683. joinRadius = strokeRadius * style.getMiterLimit();
  8684. if (style.getStrokeCap() === 'square')
  8685. joinRadius = Math.max(joinRadius, strokeRadius * Math.SQRT2);
  8686. strokePadding = Path._getStrokePadding(strokeRadius, strokeMatrix);
  8687. joinPadding = Path._getStrokePadding(joinRadius, strokeMatrix);
  8688. }
  8689. var coords = new Array(6),
  8690. x1 = Infinity,
  8691. x2 = -x1,
  8692. y1 = x1,
  8693. y2 = x2;
  8694. for (var i = 0, l = segments.length; i < l; i++) {
  8695. var segment = segments[i];
  8696. segment._transformCoordinates(matrix, coords);
  8697. for (var j = 0; j < 6; j += 2) {
  8698. var padding = !j ? joinPadding : strokePadding,
  8699. paddingX = padding ? padding[0] : 0,
  8700. paddingY = padding ? padding[1] : 0,
  8701. x = coords[j],
  8702. y = coords[j + 1],
  8703. xn = x - paddingX,
  8704. xx = x + paddingX,
  8705. yn = y - paddingY,
  8706. yx = y + paddingY;
  8707. if (xn < x1) x1 = xn;
  8708. if (xx > x2) x2 = xx;
  8709. if (yn < y1) y1 = yn;
  8710. if (yx > y2) y2 = yx;
  8711. }
  8712. }
  8713. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  8714. }
  8715. }});
  8716. Path.inject({ statics: new function() {
  8717. var kappa = 0.5522847498307936,
  8718. ellipseSegments = [
  8719. new Segment([-1, 0], [0, kappa ], [0, -kappa]),
  8720. new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
  8721. new Segment([1, 0], [0, -kappa], [0, kappa ]),
  8722. new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
  8723. ];
  8724. function createPath(segments, closed, args) {
  8725. var props = Base.getNamed(args),
  8726. path = new Path(props && props.insert == false && Item.NO_INSERT);
  8727. path._add(segments);
  8728. path._closed = closed;
  8729. return path.set(props, { insert: true });
  8730. }
  8731. function createEllipse(center, radius, args) {
  8732. var segments = new Array(4);
  8733. for (var i = 0; i < 4; i++) {
  8734. var segment = ellipseSegments[i];
  8735. segments[i] = new Segment(
  8736. segment._point.multiply(radius).add(center),
  8737. segment._handleIn.multiply(radius),
  8738. segment._handleOut.multiply(radius)
  8739. );
  8740. }
  8741. return createPath(segments, true, args);
  8742. }
  8743. return {
  8744. Line: function() {
  8745. return createPath([
  8746. new Segment(Point.readNamed(arguments, 'from')),
  8747. new Segment(Point.readNamed(arguments, 'to'))
  8748. ], false, arguments);
  8749. },
  8750. Circle: function() {
  8751. var center = Point.readNamed(arguments, 'center'),
  8752. radius = Base.readNamed(arguments, 'radius');
  8753. return createEllipse(center, new Size(radius), arguments);
  8754. },
  8755. Rectangle: function() {
  8756. var rect = Rectangle.readNamed(arguments, 'rectangle'),
  8757. radius = Size.readNamed(arguments, 'radius', 0,
  8758. { readNull: true }),
  8759. bl = rect.getBottomLeft(true),
  8760. tl = rect.getTopLeft(true),
  8761. tr = rect.getTopRight(true),
  8762. br = rect.getBottomRight(true),
  8763. segments;
  8764. if (!radius || radius.isZero()) {
  8765. segments = [
  8766. new Segment(bl),
  8767. new Segment(tl),
  8768. new Segment(tr),
  8769. new Segment(br)
  8770. ];
  8771. } else {
  8772. radius = Size.min(radius, rect.getSize(true).divide(2));
  8773. var rx = radius.width,
  8774. ry = radius.height,
  8775. hx = rx * kappa,
  8776. hy = ry * kappa;
  8777. segments = [
  8778. new Segment(bl.add(rx, 0), null, [-hx, 0]),
  8779. new Segment(bl.subtract(0, ry), [0, hy]),
  8780. new Segment(tl.add(0, ry), null, [0, -hy]),
  8781. new Segment(tl.add(rx, 0), [-hx, 0], null),
  8782. new Segment(tr.subtract(rx, 0), null, [hx, 0]),
  8783. new Segment(tr.add(0, ry), [0, -hy], null),
  8784. new Segment(br.subtract(0, ry), null, [0, hy]),
  8785. new Segment(br.subtract(rx, 0), [hx, 0])
  8786. ];
  8787. }
  8788. return createPath(segments, true, arguments);
  8789. },
  8790. RoundRectangle: '#Rectangle',
  8791. Ellipse: function() {
  8792. var ellipse = Shape._readEllipse(arguments);
  8793. return createEllipse(ellipse.center, ellipse.radius, arguments);
  8794. },
  8795. Oval: '#Ellipse',
  8796. Arc: function() {
  8797. var from = Point.readNamed(arguments, 'from'),
  8798. through = Point.readNamed(arguments, 'through'),
  8799. to = Point.readNamed(arguments, 'to'),
  8800. props = Base.getNamed(arguments),
  8801. path = new Path(props && props.insert == false
  8802. && Item.NO_INSERT);
  8803. path.moveTo(from);
  8804. path.arcTo(through, to);
  8805. return path.set(props);
  8806. },
  8807. RegularPolygon: function() {
  8808. var center = Point.readNamed(arguments, 'center'),
  8809. sides = Base.readNamed(arguments, 'sides'),
  8810. radius = Base.readNamed(arguments, 'radius'),
  8811. step = 360 / sides,
  8812. three = sides % 3 === 0,
  8813. vector = new Point(0, three ? -radius : radius),
  8814. offset = three ? -1 : 0.5,
  8815. segments = new Array(sides);
  8816. for (var i = 0; i < sides; i++)
  8817. segments[i] = new Segment(center.add(
  8818. vector.rotate((i + offset) * step)));
  8819. return createPath(segments, true, arguments);
  8820. },
  8821. Star: function() {
  8822. var center = Point.readNamed(arguments, 'center'),
  8823. points = Base.readNamed(arguments, 'points') * 2,
  8824. radius1 = Base.readNamed(arguments, 'radius1'),
  8825. radius2 = Base.readNamed(arguments, 'radius2'),
  8826. step = 360 / points,
  8827. vector = new Point(0, -1),
  8828. segments = new Array(points);
  8829. for (var i = 0; i < points; i++)
  8830. segments[i] = new Segment(center.add(vector.rotate(step * i)
  8831. .multiply(i % 2 ? radius2 : radius1)));
  8832. return createPath(segments, true, arguments);
  8833. }
  8834. };
  8835. }});
  8836. var CompoundPath = PathItem.extend({
  8837. _class: 'CompoundPath',
  8838. _serializeFields: {
  8839. children: []
  8840. },
  8841. beans: true,
  8842. initialize: function CompoundPath(arg) {
  8843. this._children = [];
  8844. this._namedChildren = {};
  8845. if (!this._initialize(arg)) {
  8846. if (typeof arg === 'string') {
  8847. this.setPathData(arg);
  8848. } else {
  8849. this.addChildren(Array.isArray(arg) ? arg : arguments);
  8850. }
  8851. }
  8852. },
  8853. insertChildren: function insertChildren(index, items) {
  8854. var list = items,
  8855. first = list[0];
  8856. if (first && typeof first[0] === 'number')
  8857. list = [list];
  8858. for (var i = items.length - 1; i >= 0; i--) {
  8859. var item = list[i];
  8860. if (list === items && !(item instanceof Path))
  8861. list = Base.slice(list);
  8862. if (Array.isArray(item)) {
  8863. list[i] = new Path({ segments: item, insert: false });
  8864. } else if (item instanceof CompoundPath) {
  8865. list.splice.apply(list, [i, 1].concat(item.removeChildren()));
  8866. item.remove();
  8867. }
  8868. }
  8869. return insertChildren.base.call(this, index, list);
  8870. },
  8871. reduce: function reduce(options) {
  8872. var children = this._children;
  8873. for (var i = children.length - 1; i >= 0; i--) {
  8874. var path = children[i].reduce(options);
  8875. if (path.isEmpty())
  8876. path.remove();
  8877. }
  8878. if (!children.length) {
  8879. var path = new Path(Item.NO_INSERT);
  8880. path.copyAttributes(this);
  8881. path.insertAbove(this);
  8882. this.remove();
  8883. return path;
  8884. }
  8885. return reduce.base.call(this);
  8886. },
  8887. isClosed: function() {
  8888. var children = this._children;
  8889. for (var i = 0, l = children.length; i < l; i++) {
  8890. if (!children[i]._closed)
  8891. return false;
  8892. }
  8893. return true;
  8894. },
  8895. setClosed: function(closed) {
  8896. var children = this._children;
  8897. for (var i = 0, l = children.length; i < l; i++) {
  8898. children[i].setClosed(closed);
  8899. }
  8900. },
  8901. getFirstSegment: function() {
  8902. var first = this.getFirstChild();
  8903. return first && first.getFirstSegment();
  8904. },
  8905. getLastSegment: function() {
  8906. var last = this.getLastChild();
  8907. return last && last.getLastSegment();
  8908. },
  8909. getCurves: function() {
  8910. var children = this._children,
  8911. curves = [];
  8912. for (var i = 0, l = children.length; i < l; i++) {
  8913. Base.push(curves, children[i].getCurves());
  8914. }
  8915. return curves;
  8916. },
  8917. getFirstCurve: function() {
  8918. var first = this.getFirstChild();
  8919. return first && first.getFirstCurve();
  8920. },
  8921. getLastCurve: function() {
  8922. var last = this.getLastChild();
  8923. return last && last.getLastCurve();
  8924. },
  8925. getArea: function() {
  8926. var children = this._children,
  8927. area = 0;
  8928. for (var i = 0, l = children.length; i < l; i++)
  8929. area += children[i].getArea();
  8930. return area;
  8931. },
  8932. getLength: function() {
  8933. var children = this._children,
  8934. length = 0;
  8935. for (var i = 0, l = children.length; i < l; i++)
  8936. length += children[i].getLength();
  8937. return length;
  8938. },
  8939. getPathData: function(_matrix, _precision) {
  8940. var children = this._children,
  8941. paths = [];
  8942. for (var i = 0, l = children.length; i < l; i++) {
  8943. var child = children[i],
  8944. mx = child._matrix;
  8945. paths.push(child.getPathData(_matrix && !mx.isIdentity()
  8946. ? _matrix.appended(mx) : _matrix, _precision));
  8947. }
  8948. return paths.join('');
  8949. },
  8950. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  8951. return _hitTestChildren.base.call(this, point,
  8952. options.class === Path || options.type === 'path' ? options
  8953. : Base.set({}, options, { fill: false }),
  8954. viewMatrix);
  8955. },
  8956. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8957. var children = this._children;
  8958. if (!children.length)
  8959. return;
  8960. param = param.extend({ dontStart: true, dontFinish: true });
  8961. ctx.beginPath();
  8962. for (var i = 0, l = children.length; i < l; i++)
  8963. children[i].draw(ctx, param, strokeMatrix);
  8964. if (!param.clip) {
  8965. this._setStyles(ctx, param, viewMatrix);
  8966. var style = this._style;
  8967. if (style.hasFill()) {
  8968. ctx.fill(style.getFillRule());
  8969. ctx.shadowColor = 'rgba(0,0,0,0)';
  8970. }
  8971. if (style.hasStroke())
  8972. ctx.stroke();
  8973. }
  8974. },
  8975. _drawSelected: function(ctx, matrix, selectionItems) {
  8976. var children = this._children;
  8977. for (var i = 0, l = children.length; i < l; i++) {
  8978. var child = children[i],
  8979. mx = child._matrix;
  8980. if (!selectionItems[child._id]) {
  8981. child._drawSelected(ctx, mx.isIdentity() ? matrix
  8982. : matrix.appended(mx));
  8983. }
  8984. }
  8985. }
  8986. },
  8987. new function() {
  8988. function getCurrentPath(that, check) {
  8989. var children = that._children;
  8990. if (check && !children.length)
  8991. throw new Error('Use a moveTo() command first');
  8992. return children[children.length - 1];
  8993. }
  8994. return Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
  8995. 'arcTo', 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy',
  8996. 'arcBy'],
  8997. function(key) {
  8998. this[key] = function() {
  8999. var path = getCurrentPath(this, true);
  9000. path[key].apply(path, arguments);
  9001. };
  9002. }, {
  9003. moveTo: function() {
  9004. var current = getCurrentPath(this),
  9005. path = current && current.isEmpty() ? current
  9006. : new Path(Item.NO_INSERT);
  9007. if (path !== current)
  9008. this.addChild(path);
  9009. path.moveTo.apply(path, arguments);
  9010. },
  9011. moveBy: function() {
  9012. var current = getCurrentPath(this, true),
  9013. last = current && current.getLastSegment(),
  9014. point = Point.read(arguments);
  9015. this.moveTo(last ? point.add(last._point) : point);
  9016. },
  9017. closePath: function(tolerance) {
  9018. getCurrentPath(this, true).closePath(tolerance);
  9019. }
  9020. }
  9021. );
  9022. }, Base.each(['reverse', 'flatten', 'simplify', 'smooth'], function(key) {
  9023. this[key] = function(param) {
  9024. var children = this._children,
  9025. res;
  9026. for (var i = 0, l = children.length; i < l; i++) {
  9027. res = children[i][key](param) || res;
  9028. }
  9029. return res;
  9030. };
  9031. }, {}));
  9032. PathItem.inject(new function() {
  9033. var min = Math.min,
  9034. max = Math.max,
  9035. abs = Math.abs,
  9036. operators = {
  9037. unite: { '1': true, '2': true },
  9038. intersect: { '2': true },
  9039. subtract: { '1': true },
  9040. exclude: { '1': true, '-1': true }
  9041. };
  9042. function preparePath(path, resolve) {
  9043. var res = path.clone(false).reduce({ simplify: true })
  9044. .transform(null, true, true);
  9045. return resolve
  9046. ? res.resolveCrossings().reorient(
  9047. res.getFillRule() === 'nonzero', true)
  9048. : res;
  9049. }
  9050. function createResult(paths, simplify, path1, path2, options) {
  9051. var result = new CompoundPath(Item.NO_INSERT);
  9052. result.addChildren(paths, true);
  9053. result = result.reduce({ simplify: simplify });
  9054. if (!(options && options.insert == false)) {
  9055. result.insertAbove(path2 && path1.isSibling(path2)
  9056. && path1.getIndex() < path2.getIndex() ? path2 : path1);
  9057. }
  9058. result.copyAttributes(path1, true);
  9059. return result;
  9060. }
  9061. function traceBoolean(path1, path2, operation, options) {
  9062. if (options && (options.trace == false || options.stroke) &&
  9063. /^(subtract|intersect)$/.test(operation))
  9064. return splitBoolean(path1, path2, operation);
  9065. var _path1 = preparePath(path1, true),
  9066. _path2 = path2 && path1 !== path2 && preparePath(path2, true),
  9067. operator = operators[operation];
  9068. operator[operation] = true;
  9069. if (_path2 && (operator.subtract || operator.exclude)
  9070. ^ (_path2.isClockwise() ^ _path1.isClockwise()))
  9071. _path2.reverse();
  9072. var crossings = divideLocations(
  9073. CurveLocation.expand(_path1.getCrossings(_path2))),
  9074. paths1 = _path1._children || [_path1],
  9075. paths2 = _path2 && (_path2._children || [_path2]),
  9076. segments = [],
  9077. curves = [],
  9078. paths;
  9079. function collect(paths) {
  9080. for (var i = 0, l = paths.length; i < l; i++) {
  9081. var path = paths[i];
  9082. Base.push(segments, path._segments);
  9083. Base.push(curves, path.getCurves());
  9084. path._overlapsOnly = true;
  9085. }
  9086. }
  9087. if (crossings.length) {
  9088. collect(paths1);
  9089. if (paths2)
  9090. collect(paths2);
  9091. for (var i = 0, l = crossings.length; i < l; i++) {
  9092. propagateWinding(crossings[i]._segment, _path1, _path2, curves,
  9093. operator);
  9094. }
  9095. for (var i = 0, l = segments.length; i < l; i++) {
  9096. var segment = segments[i],
  9097. inter = segment._intersection;
  9098. if (!segment._winding) {
  9099. propagateWinding(segment, _path1, _path2, curves, operator);
  9100. }
  9101. if (!(inter && inter._overlap))
  9102. segment._path._overlapsOnly = false;
  9103. }
  9104. paths = tracePaths(segments, operator);
  9105. } else {
  9106. paths = reorientPaths(
  9107. paths2 ? paths1.concat(paths2) : paths1.slice(),
  9108. function(w) {
  9109. return !!operator[w];
  9110. });
  9111. }
  9112. return createResult(paths, true, path1, path2, options);
  9113. }
  9114. function splitBoolean(path1, path2, operation) {
  9115. var _path1 = preparePath(path1),
  9116. _path2 = preparePath(path2),
  9117. crossings = _path1.getCrossings(_path2),
  9118. subtract = operation === 'subtract',
  9119. divide = operation === 'divide',
  9120. added = {},
  9121. paths = [];
  9122. function addPath(path) {
  9123. if (!added[path._id] && (divide ||
  9124. _path2.contains(path.getPointAt(path.getLength() / 2))
  9125. ^ subtract)) {
  9126. paths.unshift(path);
  9127. return added[path._id] = true;
  9128. }
  9129. }
  9130. for (var i = crossings.length - 1; i >= 0; i--) {
  9131. var path = crossings[i].split();
  9132. if (path) {
  9133. if (addPath(path))
  9134. path.getFirstSegment().setHandleIn(0, 0);
  9135. _path1.getLastSegment().setHandleOut(0, 0);
  9136. }
  9137. }
  9138. addPath(_path1);
  9139. return createResult(paths, false, path1, path2);
  9140. }
  9141. function linkIntersections(from, to) {
  9142. var prev = from;
  9143. while (prev) {
  9144. if (prev === to)
  9145. return;
  9146. prev = prev._previous;
  9147. }
  9148. while (from._next && from._next !== to)
  9149. from = from._next;
  9150. if (!from._next) {
  9151. while (to._previous)
  9152. to = to._previous;
  9153. from._next = to;
  9154. to._previous = from;
  9155. }
  9156. }
  9157. function clearCurveHandles(curves) {
  9158. for (var i = curves.length - 1; i >= 0; i--)
  9159. curves[i].clearHandles();
  9160. }
  9161. function reorientPaths(paths, isInside, clockwise) {
  9162. var length = paths && paths.length;
  9163. if (length) {
  9164. var lookup = Base.each(paths, function (path, i) {
  9165. this[path._id] = {
  9166. container: null,
  9167. winding: path.isClockwise() ? 1 : -1,
  9168. index: i
  9169. };
  9170. }, {}),
  9171. sorted = paths.slice().sort(function (a, b) {
  9172. return abs(b.getArea()) - abs(a.getArea());
  9173. }),
  9174. first = sorted[0];
  9175. if (clockwise == null)
  9176. clockwise = first.isClockwise();
  9177. for (var i = 0; i < length; i++) {
  9178. var path1 = sorted[i],
  9179. entry1 = lookup[path1._id],
  9180. point = path1.getInteriorPoint(),
  9181. containerWinding = 0;
  9182. for (var j = i - 1; j >= 0; j--) {
  9183. var path2 = sorted[j];
  9184. if (path2.contains(point)) {
  9185. var entry2 = lookup[path2._id];
  9186. containerWinding = entry2.winding;
  9187. entry1.winding += containerWinding;
  9188. entry1.container = entry2.exclude ? entry2.container
  9189. : path2;
  9190. break;
  9191. }
  9192. }
  9193. if (isInside(entry1.winding) === isInside(containerWinding)) {
  9194. entry1.exclude = true;
  9195. paths[entry1.index] = null;
  9196. } else {
  9197. var container = entry1.container;
  9198. path1.setClockwise(container ? !container.isClockwise()
  9199. : clockwise);
  9200. }
  9201. }
  9202. }
  9203. return paths;
  9204. }
  9205. function divideLocations(locations, include, clearLater) {
  9206. var results = include && [],
  9207. tMin = 1e-8,
  9208. tMax = 1 - tMin,
  9209. clearHandles = false,
  9210. clearCurves = clearLater || [],
  9211. clearLookup = clearLater && {},
  9212. renormalizeLocs,
  9213. prevCurve,
  9214. prevTime;
  9215. function getId(curve) {
  9216. return curve._path._id + '.' + curve._segment1._index;
  9217. }
  9218. for (var i = (clearLater && clearLater.length) - 1; i >= 0; i--) {
  9219. var curve = clearLater[i];
  9220. if (curve._path)
  9221. clearLookup[getId(curve)] = true;
  9222. }
  9223. for (var i = locations.length - 1; i >= 0; i--) {
  9224. var loc = locations[i],
  9225. time = loc._time,
  9226. origTime = time,
  9227. exclude = include && !include(loc),
  9228. curve = loc._curve,
  9229. segment;
  9230. if (curve) {
  9231. if (curve !== prevCurve) {
  9232. clearHandles = !curve.hasHandles()
  9233. || clearLookup && clearLookup[getId(curve)];
  9234. renormalizeLocs = [];
  9235. prevTime = null;
  9236. prevCurve = curve;
  9237. } else if (prevTime >= tMin) {
  9238. time /= prevTime;
  9239. }
  9240. }
  9241. if (exclude) {
  9242. if (renormalizeLocs)
  9243. renormalizeLocs.push(loc);
  9244. continue;
  9245. } else if (include) {
  9246. results.unshift(loc);
  9247. }
  9248. prevTime = origTime;
  9249. if (time < tMin) {
  9250. segment = curve._segment1;
  9251. } else if (time > tMax) {
  9252. segment = curve._segment2;
  9253. } else {
  9254. var newCurve = curve.divideAtTime(time, true);
  9255. if (clearHandles)
  9256. clearCurves.push(curve, newCurve);
  9257. segment = newCurve._segment1;
  9258. for (var j = renormalizeLocs.length - 1; j >= 0; j--) {
  9259. var l = renormalizeLocs[j];
  9260. l._time = (l._time - time) / (1 - time);
  9261. }
  9262. }
  9263. loc._setSegment(segment);
  9264. var inter = segment._intersection,
  9265. dest = loc._intersection;
  9266. if (inter) {
  9267. linkIntersections(inter, dest);
  9268. var other = inter;
  9269. while (other) {
  9270. linkIntersections(other._intersection, inter);
  9271. other = other._next;
  9272. }
  9273. } else {
  9274. segment._intersection = dest;
  9275. }
  9276. }
  9277. if (!clearLater)
  9278. clearCurveHandles(clearCurves);
  9279. return results || locations;
  9280. }
  9281. function getWinding(point, curves, dir, closed, dontFlip) {
  9282. var ia = dir ? 1 : 0,
  9283. io = ia ^ 1,
  9284. pv = [point.x, point.y],
  9285. pa = pv[ia],
  9286. po = pv[io],
  9287. windingEpsilon = 1e-9,
  9288. qualityEpsilon = 1e-6,
  9289. paL = pa - windingEpsilon,
  9290. paR = pa + windingEpsilon,
  9291. windingL = 0,
  9292. windingR = 0,
  9293. pathWindingL = 0,
  9294. pathWindingR = 0,
  9295. onPath = false,
  9296. onAnyPath = false,
  9297. quality = 1,
  9298. roots = [],
  9299. vPrev,
  9300. vClose;
  9301. function addWinding(v) {
  9302. var o0 = v[io + 0],
  9303. o3 = v[io + 6];
  9304. if (po < min(o0, o3) || po > max(o0, o3)) {
  9305. return;
  9306. }
  9307. var a0 = v[ia + 0],
  9308. a1 = v[ia + 2],
  9309. a2 = v[ia + 4],
  9310. a3 = v[ia + 6];
  9311. if (o0 === o3) {
  9312. if (a0 < paR && a3 > paL || a3 < paR && a0 > paL) {
  9313. onPath = true;
  9314. }
  9315. return;
  9316. }
  9317. var t = po === o0 ? 0
  9318. : po === o3 ? 1
  9319. : paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3)
  9320. ? 1
  9321. : Curve.solveCubic(v, io, po, roots, 0, 1) > 0
  9322. ? roots[0]
  9323. : 1,
  9324. a = t === 0 ? a0
  9325. : t === 1 ? a3
  9326. : Curve.getPoint(v, t)[dir ? 'y' : 'x'],
  9327. winding = o0 > o3 ? 1 : -1,
  9328. windingPrev = vPrev[io] > vPrev[io + 6] ? 1 : -1,
  9329. a3Prev = vPrev[ia + 6];
  9330. if (po !== o0) {
  9331. if (a < paL) {
  9332. pathWindingL += winding;
  9333. } else if (a > paR) {
  9334. pathWindingR += winding;
  9335. } else {
  9336. onPath = true;
  9337. }
  9338. if (a > pa - qualityEpsilon && a < pa + qualityEpsilon)
  9339. quality /= 2;
  9340. } else {
  9341. if (winding !== windingPrev) {
  9342. if (a0 < paL) {
  9343. pathWindingL += winding;
  9344. } else if (a0 > paR) {
  9345. pathWindingR += winding;
  9346. }
  9347. } else if (a0 != a3Prev) {
  9348. if (a3Prev < paR && a > paR) {
  9349. pathWindingR += winding;
  9350. onPath = true;
  9351. } else if (a3Prev > paL && a < paL) {
  9352. pathWindingL += winding;
  9353. onPath = true;
  9354. }
  9355. }
  9356. quality = 0;
  9357. }
  9358. vPrev = v;
  9359. return !dontFlip && a > paL && a < paR
  9360. && Curve.getTangent(v, t)[dir ? 'x' : 'y'] === 0
  9361. && getWinding(point, curves, !dir, closed, true);
  9362. }
  9363. function handleCurve(v) {
  9364. var o0 = v[io + 0],
  9365. o1 = v[io + 2],
  9366. o2 = v[io + 4],
  9367. o3 = v[io + 6];
  9368. if (po <= max(o0, o1, o2, o3) && po >= min(o0, o1, o2, o3)) {
  9369. var a0 = v[ia + 0],
  9370. a1 = v[ia + 2],
  9371. a2 = v[ia + 4],
  9372. a3 = v[ia + 6],
  9373. monoCurves = paL > max(a0, a1, a2, a3) ||
  9374. paR < min(a0, a1, a2, a3)
  9375. ? [v] : Curve.getMonoCurves(v, dir),
  9376. res;
  9377. for (var i = 0, l = monoCurves.length; i < l; i++) {
  9378. if (res = addWinding(monoCurves[i]))
  9379. return res;
  9380. }
  9381. }
  9382. }
  9383. for (var i = 0, l = curves.length; i < l; i++) {
  9384. var curve = curves[i],
  9385. path = curve._path,
  9386. v = curve.getValues(),
  9387. res;
  9388. if (!i || curves[i - 1]._path !== path) {
  9389. vPrev = null;
  9390. if (!path._closed) {
  9391. vClose = Curve.getValues(
  9392. path.getLastCurve().getSegment2(),
  9393. curve.getSegment1(),
  9394. null, !closed);
  9395. if (vClose[io] !== vClose[io + 6]) {
  9396. vPrev = vClose;
  9397. }
  9398. }
  9399. if (!vPrev) {
  9400. vPrev = v;
  9401. var prev = path.getLastCurve();
  9402. while (prev && prev !== curve) {
  9403. var v2 = prev.getValues();
  9404. if (v2[io] !== v2[io + 6]) {
  9405. vPrev = v2;
  9406. break;
  9407. }
  9408. prev = prev.getPrevious();
  9409. }
  9410. }
  9411. }
  9412. if (res = handleCurve(v))
  9413. return res;
  9414. if (i + 1 === l || curves[i + 1]._path !== path) {
  9415. if (vClose && (res = handleCurve(vClose)))
  9416. return res;
  9417. if (onPath && !pathWindingL && !pathWindingR) {
  9418. pathWindingL = pathWindingR = path.isClockwise(closed) ^ dir
  9419. ? 1 : -1;
  9420. }
  9421. windingL += pathWindingL;
  9422. windingR += pathWindingR;
  9423. pathWindingL = pathWindingR = 0;
  9424. if (onPath) {
  9425. onAnyPath = true;
  9426. onPath = false;
  9427. }
  9428. vClose = null;
  9429. }
  9430. }
  9431. windingL = abs(windingL);
  9432. windingR = abs(windingR);
  9433. return {
  9434. winding: max(windingL, windingR),
  9435. windingL: windingL,
  9436. windingR: windingR,
  9437. quality: quality,
  9438. onPath: onAnyPath
  9439. };
  9440. }
  9441. function propagateWinding(segment, path1, path2, curves, operator) {
  9442. var chain = [],
  9443. start = segment,
  9444. totalLength = 0,
  9445. winding;
  9446. do {
  9447. var curve = segment.getCurve(),
  9448. length = curve.getLength();
  9449. chain.push({ segment: segment, curve: curve, length: length });
  9450. totalLength += length;
  9451. segment = segment.getNext();
  9452. } while (segment && !segment._intersection && segment !== start);
  9453. var offsets = [0.5, 0.25, 0.75],
  9454. winding = { winding: 0, quality: -1 },
  9455. tMin = 1e-8,
  9456. tMax = 1 - tMin;
  9457. for (var i = 0; i < offsets.length && winding.quality < 0.5; i++) {
  9458. var length = totalLength * offsets[i];
  9459. for (var j = 0, l = chain.length; j < l; j++) {
  9460. var entry = chain[j],
  9461. curveLength = entry.length;
  9462. if (length <= curveLength) {
  9463. var curve = entry.curve,
  9464. path = curve._path,
  9465. parent = path._parent,
  9466. operand = parent instanceof CompoundPath ? parent : path,
  9467. t = Numerical.clamp(curve.getTimeAt(length), tMin, tMax),
  9468. pt = curve.getPointAtTime(t),
  9469. dir = abs(curve.getTangentAtTime(t).y) < Math.SQRT1_2;
  9470. var wind = null;
  9471. if (operator.subtract && path2) {
  9472. var pathWinding = operand === path1
  9473. ? path2._getWinding(pt, dir, true)
  9474. : path1._getWinding(pt, dir, true);
  9475. if (operand === path1 && pathWinding.winding ||
  9476. operand === path2 && !pathWinding.winding) {
  9477. if (pathWinding.quality < 1) {
  9478. continue;
  9479. } else {
  9480. wind = { winding: 0, quality: 1 };
  9481. }
  9482. }
  9483. }
  9484. wind = wind || getWinding(pt, curves, dir, true);
  9485. if (wind.quality > winding.quality)
  9486. winding = wind;
  9487. break;
  9488. }
  9489. length -= curveLength;
  9490. }
  9491. }
  9492. for (var j = chain.length - 1; j >= 0; j--) {
  9493. chain[j].segment._winding = winding;
  9494. }
  9495. }
  9496. function tracePaths(segments, operator) {
  9497. var paths = [],
  9498. starts;
  9499. function isValid(seg) {
  9500. var winding;
  9501. return !!(seg && !seg._visited && (!operator
  9502. || operator[(winding = seg._winding || {}).winding]
  9503. && !(operator.unite && winding.winding === 2
  9504. && winding.windingL && winding.windingR)));
  9505. }
  9506. function isStart(seg) {
  9507. if (seg) {
  9508. for (var i = 0, l = starts.length; i < l; i++) {
  9509. if (seg === starts[i])
  9510. return true;
  9511. }
  9512. }
  9513. return false;
  9514. }
  9515. function visitPath(path) {
  9516. var segments = path._segments;
  9517. for (var i = 0, l = segments.length; i < l; i++) {
  9518. segments[i]._visited = true;
  9519. }
  9520. }
  9521. function getCrossingSegments(segment, collectStarts) {
  9522. var inter = segment._intersection,
  9523. start = inter,
  9524. crossings = [];
  9525. if (collectStarts)
  9526. starts = [segment];
  9527. function collect(inter, end) {
  9528. while (inter && inter !== end) {
  9529. var other = inter._segment,
  9530. path = other && other._path;
  9531. if (path) {
  9532. var next = other.getNext() || path.getFirstSegment(),
  9533. nextInter = next._intersection;
  9534. if (other !== segment && (isStart(other)
  9535. || isStart(next)
  9536. || next && (isValid(other) && (isValid(next)
  9537. || nextInter && isValid(nextInter._segment))))
  9538. ) {
  9539. crossings.push(other);
  9540. }
  9541. if (collectStarts)
  9542. starts.push(other);
  9543. }
  9544. inter = inter._next;
  9545. }
  9546. }
  9547. if (inter) {
  9548. collect(inter);
  9549. while (inter && inter._prev)
  9550. inter = inter._prev;
  9551. collect(inter, start);
  9552. }
  9553. return crossings;
  9554. }
  9555. segments.sort(function(seg1, seg2) {
  9556. var inter1 = seg1._intersection,
  9557. inter2 = seg2._intersection,
  9558. over1 = !!(inter1 && inter1._overlap),
  9559. over2 = !!(inter2 && inter2._overlap),
  9560. path1 = seg1._path,
  9561. path2 = seg2._path;
  9562. return over1 ^ over2
  9563. ? over1 ? 1 : -1
  9564. : !inter1 ^ !inter2
  9565. ? inter1 ? 1 : -1
  9566. : path1 !== path2
  9567. ? path1._id - path2._id
  9568. : seg1._index - seg2._index;
  9569. });
  9570. for (var i = 0, l = segments.length; i < l; i++) {
  9571. var seg = segments[i],
  9572. valid = isValid(seg),
  9573. path = null,
  9574. finished = false,
  9575. closed = true,
  9576. branches = [],
  9577. branch,
  9578. visited,
  9579. handleIn;
  9580. if (valid && seg._path._overlapsOnly) {
  9581. var path1 = seg._path,
  9582. path2 = seg._intersection._segment._path;
  9583. if (path1.compare(path2)) {
  9584. if (path1.getArea())
  9585. paths.push(path1.clone(false));
  9586. visitPath(path1);
  9587. visitPath(path2);
  9588. valid = false;
  9589. }
  9590. }
  9591. while (valid) {
  9592. var first = !path,
  9593. crossings = getCrossingSegments(seg, first),
  9594. other = crossings.shift(),
  9595. finished = !first && (isStart(seg) || isStart(other)),
  9596. cross = !finished && other;
  9597. if (first) {
  9598. path = new Path(Item.NO_INSERT);
  9599. branch = null;
  9600. }
  9601. if (finished) {
  9602. if (seg.isFirst() || seg.isLast())
  9603. closed = seg._path._closed;
  9604. seg._visited = true;
  9605. break;
  9606. }
  9607. if (cross && branch) {
  9608. branches.push(branch);
  9609. branch = null;
  9610. }
  9611. if (!branch) {
  9612. if (cross)
  9613. crossings.push(seg);
  9614. branch = {
  9615. start: path._segments.length,
  9616. crossings: crossings,
  9617. visited: visited = [],
  9618. handleIn: handleIn
  9619. };
  9620. }
  9621. if (cross)
  9622. seg = other;
  9623. if (!isValid(seg)) {
  9624. path.removeSegments(branch.start);
  9625. for (var j = 0, k = visited.length; j < k; j++) {
  9626. visited[j]._visited = false;
  9627. }
  9628. visited.length = 0;
  9629. do {
  9630. seg = branch && branch.crossings.shift();
  9631. if (!seg || !seg._path) {
  9632. seg = null;
  9633. branch = branches.pop();
  9634. if (branch) {
  9635. visited = branch.visited;
  9636. handleIn = branch.handleIn;
  9637. }
  9638. }
  9639. } while (branch && !isValid(seg));
  9640. if (!seg)
  9641. break;
  9642. }
  9643. var next = seg.getNext();
  9644. path.add(new Segment(seg._point, handleIn,
  9645. next && seg._handleOut));
  9646. seg._visited = true;
  9647. visited.push(seg);
  9648. seg = next || seg._path.getFirstSegment();
  9649. handleIn = next && next._handleIn;
  9650. }
  9651. if (finished) {
  9652. if (closed) {
  9653. path.getFirstSegment().setHandleIn(handleIn);
  9654. path.setClosed(closed);
  9655. }
  9656. if (path.getArea() !== 0) {
  9657. paths.push(path);
  9658. }
  9659. }
  9660. }
  9661. return paths;
  9662. }
  9663. return {
  9664. _getWinding: function(point, dir, closed) {
  9665. return getWinding(point, this.getCurves(), dir, closed);
  9666. },
  9667. unite: function(path, options) {
  9668. return traceBoolean(this, path, 'unite', options);
  9669. },
  9670. intersect: function(path, options) {
  9671. return traceBoolean(this, path, 'intersect', options);
  9672. },
  9673. subtract: function(path, options) {
  9674. return traceBoolean(this, path, 'subtract', options);
  9675. },
  9676. exclude: function(path, options) {
  9677. return traceBoolean(this, path, 'exclude', options);
  9678. },
  9679. divide: function(path, options) {
  9680. return options && (options.trace == false || options.stroke)
  9681. ? splitBoolean(this, path, 'divide')
  9682. : createResult([
  9683. this.subtract(path, options),
  9684. this.intersect(path, options)
  9685. ], true, this, path, options);
  9686. },
  9687. resolveCrossings: function() {
  9688. var children = this._children,
  9689. paths = children || [this];
  9690. function hasOverlap(seg, path) {
  9691. var inter = seg && seg._intersection;
  9692. return inter && inter._overlap && inter._path === path;
  9693. }
  9694. var hasOverlaps = false,
  9695. hasCrossings = false,
  9696. intersections = this.getIntersections(null, function(inter) {
  9697. return inter.hasOverlap() && (hasOverlaps = true) ||
  9698. inter.isCrossing() && (hasCrossings = true);
  9699. }),
  9700. clearCurves = hasOverlaps && hasCrossings && [];
  9701. intersections = CurveLocation.expand(intersections);
  9702. if (hasOverlaps) {
  9703. var overlaps = divideLocations(intersections, function(inter) {
  9704. return inter.hasOverlap();
  9705. }, clearCurves);
  9706. for (var i = overlaps.length - 1; i >= 0; i--) {
  9707. var overlap = overlaps[i],
  9708. path = overlap._path,
  9709. seg = overlap._segment,
  9710. prev = seg.getPrevious(),
  9711. next = seg.getNext();
  9712. if (hasOverlap(prev, path) && hasOverlap(next, path)) {
  9713. seg.remove();
  9714. prev._handleOut._set(0, 0);
  9715. next._handleIn._set(0, 0);
  9716. if (prev !== seg && !prev.getCurve().hasLength()) {
  9717. next._handleIn.set(prev._handleIn);
  9718. prev.remove();
  9719. }
  9720. }
  9721. }
  9722. }
  9723. if (hasCrossings) {
  9724. divideLocations(intersections, hasOverlaps && function(inter) {
  9725. var curve1 = inter.getCurve(),
  9726. seg1 = inter.getSegment(),
  9727. other = inter._intersection,
  9728. curve2 = other._curve,
  9729. seg2 = other._segment;
  9730. if (curve1 && curve2 && curve1._path && curve2._path)
  9731. return true;
  9732. if (seg1)
  9733. seg1._intersection = null;
  9734. if (seg2)
  9735. seg2._intersection = null;
  9736. }, clearCurves);
  9737. if (clearCurves)
  9738. clearCurveHandles(clearCurves);
  9739. paths = tracePaths(Base.each(paths, function(path) {
  9740. Base.push(this, path._segments);
  9741. }, []));
  9742. }
  9743. var length = paths.length,
  9744. item;
  9745. if (length > 1 && children) {
  9746. if (paths !== children)
  9747. this.setChildren(paths);
  9748. item = this;
  9749. } else if (length === 1 && !children) {
  9750. if (paths[0] !== this)
  9751. this.setSegments(paths[0].removeSegments());
  9752. item = this;
  9753. }
  9754. if (!item) {
  9755. item = new CompoundPath(Item.NO_INSERT);
  9756. item.addChildren(paths);
  9757. item = item.reduce();
  9758. item.copyAttributes(this);
  9759. this.replaceWith(item);
  9760. }
  9761. return item;
  9762. },
  9763. reorient: function(nonZero, clockwise) {
  9764. var children = this._children;
  9765. if (children && children.length) {
  9766. this.setChildren(reorientPaths(this.removeChildren(),
  9767. function(w) {
  9768. return !!(nonZero ? w : w & 1);
  9769. },
  9770. clockwise));
  9771. } else if (clockwise !== undefined) {
  9772. this.setClockwise(clockwise);
  9773. }
  9774. return this;
  9775. },
  9776. getInteriorPoint: function() {
  9777. var bounds = this.getBounds(),
  9778. point = bounds.getCenter(true);
  9779. if (!this.contains(point)) {
  9780. var curves = this.getCurves(),
  9781. y = point.y,
  9782. intercepts = [],
  9783. roots = [];
  9784. for (var i = 0, l = curves.length; i < l; i++) {
  9785. var v = curves[i].getValues(),
  9786. o0 = v[1],
  9787. o1 = v[3],
  9788. o2 = v[5],
  9789. o3 = v[7];
  9790. if (y >= min(o0, o1, o2, o3) && y <= max(o0, o1, o2, o3)) {
  9791. var monoCurves = Curve.getMonoCurves(v);
  9792. for (var j = 0, m = monoCurves.length; j < m; j++) {
  9793. var mv = monoCurves[j],
  9794. mo0 = mv[1],
  9795. mo3 = mv[7];
  9796. if ((mo0 !== mo3) &&
  9797. (y >= mo0 && y <= mo3 || y >= mo3 && y <= mo0)){
  9798. var x = y === mo0 ? mv[0]
  9799. : y === mo3 ? mv[6]
  9800. : Curve.solveCubic(mv, 1, y, roots, 0, 1)
  9801. === 1
  9802. ? Curve.getPoint(mv, roots[0]).x
  9803. : (mv[0] + mv[6]) / 2;
  9804. intercepts.push(x);
  9805. }
  9806. }
  9807. }
  9808. }
  9809. if (intercepts.length > 1) {
  9810. intercepts.sort(function(a, b) { return a - b; });
  9811. point.x = (intercepts[0] + intercepts[1]) / 2;
  9812. }
  9813. }
  9814. return point;
  9815. }
  9816. };
  9817. });
  9818. var PathFlattener = Base.extend({
  9819. _class: 'PathFlattener',
  9820. initialize: function(path, flatness, maxRecursion, ignoreStraight, matrix) {
  9821. var curves = [],
  9822. parts = [],
  9823. length = 0,
  9824. minSpan = 1 / (maxRecursion || 32),
  9825. segments = path._segments,
  9826. segment1 = segments[0],
  9827. segment2;
  9828. function addCurve(segment1, segment2) {
  9829. var curve = Curve.getValues(segment1, segment2, matrix);
  9830. curves.push(curve);
  9831. computeParts(curve, segment1._index, 0, 1);
  9832. }
  9833. function computeParts(curve, index, t1, t2) {
  9834. if ((t2 - t1) > minSpan
  9835. && !(ignoreStraight && Curve.isStraight(curve))
  9836. && !Curve.isFlatEnough(curve, flatness || 0.25)) {
  9837. var halves = Curve.subdivide(curve, 0.5),
  9838. tMid = (t1 + t2) / 2;
  9839. computeParts(halves[0], index, t1, tMid);
  9840. computeParts(halves[1], index, tMid, t2);
  9841. } else {
  9842. var dx = curve[6] - curve[0],
  9843. dy = curve[7] - curve[1],
  9844. dist = Math.sqrt(dx * dx + dy * dy);
  9845. if (dist > 0) {
  9846. length += dist;
  9847. parts.push({
  9848. offset: length,
  9849. curve: curve,
  9850. index: index,
  9851. time: t2,
  9852. });
  9853. }
  9854. }
  9855. }
  9856. for (var i = 1, l = segments.length; i < l; i++) {
  9857. segment2 = segments[i];
  9858. addCurve(segment1, segment2);
  9859. segment1 = segment2;
  9860. }
  9861. if (path._closed)
  9862. addCurve(segment2 || segment1, segments[0]);
  9863. this.curves = curves;
  9864. this.parts = parts;
  9865. this.length = length;
  9866. this.index = 0;
  9867. },
  9868. _get: function(offset) {
  9869. var parts = this.parts,
  9870. length = parts.length,
  9871. start,
  9872. i, j = this.index;
  9873. for (;;) {
  9874. i = j;
  9875. if (!j || parts[--j].offset < offset)
  9876. break;
  9877. }
  9878. for (; i < length; i++) {
  9879. var part = parts[i];
  9880. if (part.offset >= offset) {
  9881. this.index = i;
  9882. var prev = parts[i - 1],
  9883. prevTime = prev && prev.index === part.index ? prev.time : 0,
  9884. prevOffset = prev ? prev.offset : 0;
  9885. return {
  9886. index: part.index,
  9887. time: prevTime + (part.time - prevTime)
  9888. * (offset - prevOffset) / (part.offset - prevOffset)
  9889. };
  9890. }
  9891. }
  9892. return {
  9893. index: parts[length - 1].index,
  9894. time: 1
  9895. };
  9896. },
  9897. drawPart: function(ctx, from, to) {
  9898. var start = this._get(from),
  9899. end = this._get(to);
  9900. for (var i = start.index, l = end.index; i <= l; i++) {
  9901. var curve = Curve.getPart(this.curves[i],
  9902. i === start.index ? start.time : 0,
  9903. i === end.index ? end.time : 1);
  9904. if (i === start.index)
  9905. ctx.moveTo(curve[0], curve[1]);
  9906. ctx.bezierCurveTo.apply(ctx, curve.slice(2));
  9907. }
  9908. }
  9909. }, Base.each(Curve._evaluateMethods,
  9910. function(name) {
  9911. this[name + 'At'] = function(offset) {
  9912. var param = this._get(offset);
  9913. return Curve[name](this.curves[param.index], param.time);
  9914. };
  9915. }, {})
  9916. );
  9917. var PathFitter = Base.extend({
  9918. initialize: function(path) {
  9919. var points = this.points = [],
  9920. segments = path._segments,
  9921. closed = path._closed;
  9922. for (var i = 0, prev, l = segments.length; i < l; i++) {
  9923. var point = segments[i].point;
  9924. if (!prev || !prev.equals(point)) {
  9925. points.push(prev = point.clone());
  9926. }
  9927. }
  9928. if (closed) {
  9929. points.unshift(points[points.length - 1]);
  9930. points.push(points[1]);
  9931. }
  9932. this.closed = closed;
  9933. },
  9934. fit: function(error) {
  9935. var points = this.points,
  9936. length = points.length,
  9937. segments = null;
  9938. if (length > 0) {
  9939. segments = [new Segment(points[0])];
  9940. if (length > 1) {
  9941. this.fitCubic(segments, error, 0, length - 1,
  9942. points[1].subtract(points[0]),
  9943. points[length - 2].subtract(points[length - 1]));
  9944. if (this.closed) {
  9945. segments.shift();
  9946. segments.pop();
  9947. }
  9948. }
  9949. }
  9950. return segments;
  9951. },
  9952. fitCubic: function(segments, error, first, last, tan1, tan2) {
  9953. var points = this.points;
  9954. if (last - first === 1) {
  9955. var pt1 = points[first],
  9956. pt2 = points[last],
  9957. dist = pt1.getDistance(pt2) / 3;
  9958. this.addCurve(segments, [pt1, pt1.add(tan1.normalize(dist)),
  9959. pt2.add(tan2.normalize(dist)), pt2]);
  9960. return;
  9961. }
  9962. var uPrime = this.chordLengthParameterize(first, last),
  9963. maxError = Math.max(error, error * error),
  9964. split,
  9965. parametersInOrder = true;
  9966. for (var i = 0; i <= 4; i++) {
  9967. var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
  9968. var max = this.findMaxError(first, last, curve, uPrime);
  9969. if (max.error < error && parametersInOrder) {
  9970. this.addCurve(segments, curve);
  9971. return;
  9972. }
  9973. split = max.index;
  9974. if (max.error >= maxError)
  9975. break;
  9976. parametersInOrder = this.reparameterize(first, last, uPrime, curve);
  9977. maxError = max.error;
  9978. }
  9979. var tanCenter = points[split - 1].subtract(points[split + 1]);
  9980. this.fitCubic(segments, error, first, split, tan1, tanCenter);
  9981. this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2);
  9982. },
  9983. addCurve: function(segments, curve) {
  9984. var prev = segments[segments.length - 1];
  9985. prev.setHandleOut(curve[1].subtract(curve[0]));
  9986. segments.push(new Segment(curve[3], curve[2].subtract(curve[3])));
  9987. },
  9988. generateBezier: function(first, last, uPrime, tan1, tan2) {
  9989. var epsilon = 1e-12,
  9990. abs = Math.abs,
  9991. points = this.points,
  9992. pt1 = points[first],
  9993. pt2 = points[last],
  9994. C = [[0, 0], [0, 0]],
  9995. X = [0, 0];
  9996. for (var i = 0, l = last - first + 1; i < l; i++) {
  9997. var u = uPrime[i],
  9998. t = 1 - u,
  9999. b = 3 * u * t,
  10000. b0 = t * t * t,
  10001. b1 = b * t,
  10002. b2 = b * u,
  10003. b3 = u * u * u,
  10004. a1 = tan1.normalize(b1),
  10005. a2 = tan2.normalize(b2),
  10006. tmp = points[first + i]
  10007. .subtract(pt1.multiply(b0 + b1))
  10008. .subtract(pt2.multiply(b2 + b3));
  10009. C[0][0] += a1.dot(a1);
  10010. C[0][1] += a1.dot(a2);
  10011. C[1][0] = C[0][1];
  10012. C[1][1] += a2.dot(a2);
  10013. X[0] += a1.dot(tmp);
  10014. X[1] += a2.dot(tmp);
  10015. }
  10016. var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
  10017. alpha1,
  10018. alpha2;
  10019. if (abs(detC0C1) > epsilon) {
  10020. var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
  10021. detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
  10022. alpha1 = detXC1 / detC0C1;
  10023. alpha2 = detC0X / detC0C1;
  10024. } else {
  10025. var c0 = C[0][0] + C[0][1],
  10026. c1 = C[1][0] + C[1][1];
  10027. alpha1 = alpha2 = abs(c0) > epsilon ? X[0] / c0
  10028. : abs(c1) > epsilon ? X[1] / c1
  10029. : 0;
  10030. }
  10031. var segLength = pt2.getDistance(pt1),
  10032. eps = epsilon * segLength,
  10033. handle1,
  10034. handle2;
  10035. if (alpha1 < eps || alpha2 < eps) {
  10036. alpha1 = alpha2 = segLength / 3;
  10037. } else {
  10038. var line = pt2.subtract(pt1);
  10039. handle1 = tan1.normalize(alpha1);
  10040. handle2 = tan2.normalize(alpha2);
  10041. if (handle1.dot(line) - handle2.dot(line) > segLength * segLength) {
  10042. alpha1 = alpha2 = segLength / 3;
  10043. handle1 = handle2 = null;
  10044. }
  10045. }
  10046. return [pt1,
  10047. pt1.add(handle1 || tan1.normalize(alpha1)),
  10048. pt2.add(handle2 || tan2.normalize(alpha2)),
  10049. pt2];
  10050. },
  10051. reparameterize: function(first, last, u, curve) {
  10052. for (var i = first; i <= last; i++) {
  10053. u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
  10054. }
  10055. for (var i = 1, l = u.length; i < l; i++) {
  10056. if (u[i] <= u[i - 1])
  10057. return false;
  10058. }
  10059. return true;
  10060. },
  10061. findRoot: function(curve, point, u) {
  10062. var curve1 = [],
  10063. curve2 = [];
  10064. for (var i = 0; i <= 2; i++) {
  10065. curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
  10066. }
  10067. for (var i = 0; i <= 1; i++) {
  10068. curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
  10069. }
  10070. var pt = this.evaluate(3, curve, u),
  10071. pt1 = this.evaluate(2, curve1, u),
  10072. pt2 = this.evaluate(1, curve2, u),
  10073. diff = pt.subtract(point),
  10074. df = pt1.dot(pt1) + diff.dot(pt2);
  10075. return Numerical.isZero(df) ? u : u - diff.dot(pt1) / df;
  10076. },
  10077. evaluate: function(degree, curve, t) {
  10078. var tmp = curve.slice();
  10079. for (var i = 1; i <= degree; i++) {
  10080. for (var j = 0; j <= degree - i; j++) {
  10081. tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
  10082. }
  10083. }
  10084. return tmp[0];
  10085. },
  10086. chordLengthParameterize: function(first, last) {
  10087. var u = [0];
  10088. for (var i = first + 1; i <= last; i++) {
  10089. u[i - first] = u[i - first - 1]
  10090. + this.points[i].getDistance(this.points[i - 1]);
  10091. }
  10092. for (var i = 1, m = last - first; i <= m; i++) {
  10093. u[i] /= u[m];
  10094. }
  10095. return u;
  10096. },
  10097. findMaxError: function(first, last, curve, u) {
  10098. var index = Math.floor((last - first + 1) / 2),
  10099. maxDist = 0;
  10100. for (var i = first + 1; i < last; i++) {
  10101. var P = this.evaluate(3, curve, u[i - first]);
  10102. var v = P.subtract(this.points[i]);
  10103. var dist = v.x * v.x + v.y * v.y;
  10104. if (dist >= maxDist) {
  10105. maxDist = dist;
  10106. index = i;
  10107. }
  10108. }
  10109. return {
  10110. error: maxDist,
  10111. index: index
  10112. };
  10113. }
  10114. });
  10115. var TextItem = Item.extend({
  10116. _class: 'TextItem',
  10117. _applyMatrix: false,
  10118. _canApplyMatrix: false,
  10119. _serializeFields: {
  10120. content: null
  10121. },
  10122. _boundsOptions: { stroke: false, handle: false },
  10123. initialize: function TextItem(arg) {
  10124. this._content = '';
  10125. this._lines = [];
  10126. var hasProps = arg && Base.isPlainObject(arg)
  10127. && arg.x === undefined && arg.y === undefined;
  10128. this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
  10129. },
  10130. _equals: function(item) {
  10131. return this._content === item._content;
  10132. },
  10133. copyContent: function(source) {
  10134. this.setContent(source._content);
  10135. },
  10136. getContent: function() {
  10137. return this._content;
  10138. },
  10139. setContent: function(content) {
  10140. this._content = '' + content;
  10141. this._lines = this._content.split(/\r\n|\n|\r/mg);
  10142. this._changed(521);
  10143. },
  10144. isEmpty: function() {
  10145. return !this._content;
  10146. },
  10147. getCharacterStyle: '#getStyle',
  10148. setCharacterStyle: '#setStyle',
  10149. getParagraphStyle: '#getStyle',
  10150. setParagraphStyle: '#setStyle'
  10151. });
  10152. var PointText = TextItem.extend({
  10153. _class: 'PointText',
  10154. initialize: function PointText() {
  10155. TextItem.apply(this, arguments);
  10156. },
  10157. getPoint: function() {
  10158. var point = this._matrix.getTranslation();
  10159. return new LinkedPoint(point.x, point.y, this, 'setPoint');
  10160. },
  10161. setPoint: function() {
  10162. var point = Point.read(arguments);
  10163. this.translate(point.subtract(this._matrix.getTranslation()));
  10164. },
  10165. _draw: function(ctx, param, viewMatrix) {
  10166. if (!this._content)
  10167. return;
  10168. this._setStyles(ctx, param, viewMatrix);
  10169. var lines = this._lines,
  10170. style = this._style,
  10171. hasFill = style.hasFill(),
  10172. hasStroke = style.hasStroke(),
  10173. leading = style.getLeading(),
  10174. shadowColor = ctx.shadowColor;
  10175. ctx.font = style.getFontStyle();
  10176. ctx.textAlign = style.getJustification();
  10177. for (var i = 0, l = lines.length; i < l; i++) {
  10178. ctx.shadowColor = shadowColor;
  10179. var line = lines[i];
  10180. if (hasFill) {
  10181. ctx.fillText(line, 0, 0);
  10182. ctx.shadowColor = 'rgba(0,0,0,0)';
  10183. }
  10184. if (hasStroke)
  10185. ctx.strokeText(line, 0, 0);
  10186. ctx.translate(0, leading);
  10187. }
  10188. },
  10189. _getBounds: function(matrix, options) {
  10190. var style = this._style,
  10191. lines = this._lines,
  10192. numLines = lines.length,
  10193. justification = style.getJustification(),
  10194. leading = style.getLeading(),
  10195. width = this.getView().getTextWidth(style.getFontStyle(), lines),
  10196. x = 0;
  10197. if (justification !== 'left')
  10198. x -= width / (justification === 'center' ? 2: 1);
  10199. var rect = new Rectangle(x,
  10200. numLines ? - 0.75 * leading : 0,
  10201. width, numLines * leading);
  10202. return matrix ? matrix._transformBounds(rect, rect) : rect;
  10203. }
  10204. });
  10205. var Color = Base.extend(new function() {
  10206. var types = {
  10207. gray: ['gray'],
  10208. rgb: ['red', 'green', 'blue'],
  10209. hsb: ['hue', 'saturation', 'brightness'],
  10210. hsl: ['hue', 'saturation', 'lightness'],
  10211. gradient: ['gradient', 'origin', 'destination', 'highlight']
  10212. };
  10213. var componentParsers = {},
  10214. namedColors = {
  10215. transparent: [0, 0, 0, 0]
  10216. },
  10217. colorCtx;
  10218. function fromCSS(string) {
  10219. var match = string.match(
  10220. /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i
  10221. ) || string.match(
  10222. /^#([\da-f])([\da-f])([\da-f])([\da-f])?$/i
  10223. ),
  10224. type = 'rgb',
  10225. components;
  10226. if (match) {
  10227. var amount = match[4] ? 4 : 3;
  10228. components = new Array(amount);
  10229. for (var i = 0; i < amount; i++) {
  10230. var value = match[i + 1];
  10231. components[i] = parseInt(value.length == 1
  10232. ? value + value : value, 16) / 255;
  10233. }
  10234. } else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) {
  10235. type = match[1];
  10236. components = match[2].split(/[,\s]+/g);
  10237. var isHSL = type === 'hsl';
  10238. for (var i = 0, l = Math.min(components.length, 4); i < l; i++) {
  10239. var component = components[i];
  10240. var value = parseFloat(component);
  10241. if (isHSL) {
  10242. if (i === 0) {
  10243. var unit = component.match(/([a-z]*)$/)[1];
  10244. value *= ({
  10245. turn: 360,
  10246. rad: 180 / Math.PI,
  10247. grad: 0.9
  10248. }[unit] || 1);
  10249. } else if (i < 3) {
  10250. value /= 100;
  10251. }
  10252. } else if (i < 3) {
  10253. value /= 255;
  10254. }
  10255. components[i] = value;
  10256. }
  10257. } else {
  10258. var color = namedColors[string];
  10259. if (!color) {
  10260. if (window) {
  10261. if (!colorCtx) {
  10262. colorCtx = CanvasProvider.getContext(1, 1);
  10263. colorCtx.globalCompositeOperation = 'copy';
  10264. }
  10265. colorCtx.fillStyle = 'rgba(0,0,0,0)';
  10266. colorCtx.fillStyle = string;
  10267. colorCtx.fillRect(0, 0, 1, 1);
  10268. var data = colorCtx.getImageData(0, 0, 1, 1).data;
  10269. color = namedColors[string] = [
  10270. data[0] / 255,
  10271. data[1] / 255,
  10272. data[2] / 255
  10273. ];
  10274. } else {
  10275. color = [0, 0, 0];
  10276. }
  10277. }
  10278. components = color.slice();
  10279. }
  10280. return [type, components];
  10281. }
  10282. var hsbIndices = [
  10283. [0, 3, 1],
  10284. [2, 0, 1],
  10285. [1, 0, 3],
  10286. [1, 2, 0],
  10287. [3, 1, 0],
  10288. [0, 1, 2]
  10289. ];
  10290. var converters = {
  10291. 'rgb-hsb': function(r, g, b) {
  10292. var max = Math.max(r, g, b),
  10293. min = Math.min(r, g, b),
  10294. delta = max - min,
  10295. h = delta === 0 ? 0
  10296. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10297. : max == g ? (b - r) / delta + 2
  10298. : (r - g) / delta + 4) * 60;
  10299. return [h, max === 0 ? 0 : delta / max, max];
  10300. },
  10301. 'hsb-rgb': function(h, s, b) {
  10302. h = (((h / 60) % 6) + 6) % 6;
  10303. var i = Math.floor(h),
  10304. f = h - i,
  10305. i = hsbIndices[i],
  10306. v = [
  10307. b,
  10308. b * (1 - s),
  10309. b * (1 - s * f),
  10310. b * (1 - s * (1 - f))
  10311. ];
  10312. return [v[i[0]], v[i[1]], v[i[2]]];
  10313. },
  10314. 'rgb-hsl': function(r, g, b) {
  10315. var max = Math.max(r, g, b),
  10316. min = Math.min(r, g, b),
  10317. delta = max - min,
  10318. achromatic = delta === 0,
  10319. h = achromatic ? 0
  10320. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10321. : max == g ? (b - r) / delta + 2
  10322. : (r - g) / delta + 4) * 60,
  10323. l = (max + min) / 2,
  10324. s = achromatic ? 0 : l < 0.5
  10325. ? delta / (max + min)
  10326. : delta / (2 - max - min);
  10327. return [h, s, l];
  10328. },
  10329. 'hsl-rgb': function(h, s, l) {
  10330. h = (((h / 360) % 1) + 1) % 1;
  10331. if (s === 0)
  10332. return [l, l, l];
  10333. var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
  10334. t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
  10335. t1 = 2 * l - t2,
  10336. c = [];
  10337. for (var i = 0; i < 3; i++) {
  10338. var t3 = t3s[i];
  10339. if (t3 < 0) t3 += 1;
  10340. if (t3 > 1) t3 -= 1;
  10341. c[i] = 6 * t3 < 1
  10342. ? t1 + (t2 - t1) * 6 * t3
  10343. : 2 * t3 < 1
  10344. ? t2
  10345. : 3 * t3 < 2
  10346. ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
  10347. : t1;
  10348. }
  10349. return c;
  10350. },
  10351. 'rgb-gray': function(r, g, b) {
  10352. return [r * 0.2989 + g * 0.587 + b * 0.114];
  10353. },
  10354. 'gray-rgb': function(g) {
  10355. return [g, g, g];
  10356. },
  10357. 'gray-hsb': function(g) {
  10358. return [0, 0, g];
  10359. },
  10360. 'gray-hsl': function(g) {
  10361. return [0, 0, g];
  10362. },
  10363. 'gradient-rgb': function() {
  10364. return [];
  10365. },
  10366. 'rgb-gradient': function() {
  10367. return [];
  10368. }
  10369. };
  10370. return Base.each(types, function(properties, type) {
  10371. componentParsers[type] = [];
  10372. Base.each(properties, function(name, index) {
  10373. var part = Base.capitalize(name),
  10374. hasOverlap = /^(hue|saturation)$/.test(name),
  10375. parser = componentParsers[type][index] = type === 'gradient'
  10376. ? name === 'gradient'
  10377. ? function(value) {
  10378. var current = this._components[0];
  10379. value = Gradient.read(
  10380. Array.isArray(value)
  10381. ? value
  10382. : arguments, 0, { readNull: true }
  10383. );
  10384. if (current !== value) {
  10385. if (current)
  10386. current._removeOwner(this);
  10387. if (value)
  10388. value._addOwner(this);
  10389. }
  10390. return value;
  10391. }
  10392. : function() {
  10393. return Point.read(arguments, 0, {
  10394. readNull: name === 'highlight',
  10395. clone: true
  10396. });
  10397. }
  10398. : function(value) {
  10399. return value == null || isNaN(value) ? 0 : +value;
  10400. };
  10401. this['get' + part] = function() {
  10402. return this._type === type
  10403. || hasOverlap && /^hs[bl]$/.test(this._type)
  10404. ? this._components[index]
  10405. : this._convert(type)[index];
  10406. };
  10407. this['set' + part] = function(value) {
  10408. if (this._type !== type
  10409. && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
  10410. this._components = this._convert(type);
  10411. this._properties = types[type];
  10412. this._type = type;
  10413. }
  10414. this._components[index] = parser.call(this, value);
  10415. this._changed();
  10416. };
  10417. }, this);
  10418. }, {
  10419. _class: 'Color',
  10420. _readIndex: true,
  10421. initialize: function Color(arg) {
  10422. var args = arguments,
  10423. reading = this.__read,
  10424. read = 0,
  10425. type,
  10426. components,
  10427. alpha,
  10428. values;
  10429. if (Array.isArray(arg)) {
  10430. args = arg;
  10431. arg = args[0];
  10432. }
  10433. var argType = arg != null && typeof arg;
  10434. if (argType === 'string' && arg in types) {
  10435. type = arg;
  10436. arg = args[1];
  10437. if (Array.isArray(arg)) {
  10438. components = arg;
  10439. alpha = args[2];
  10440. } else {
  10441. if (reading)
  10442. read = 1;
  10443. args = Base.slice(args, 1);
  10444. argType = typeof arg;
  10445. }
  10446. }
  10447. if (!components) {
  10448. values = argType === 'number'
  10449. ? args
  10450. : argType === 'object' && arg.length != null
  10451. ? arg
  10452. : null;
  10453. if (values) {
  10454. if (!type)
  10455. type = values.length >= 3
  10456. ? 'rgb'
  10457. : 'gray';
  10458. var length = types[type].length;
  10459. alpha = values[length];
  10460. if (reading) {
  10461. read += values === arguments
  10462. ? length + (alpha != null ? 1 : 0)
  10463. : 1;
  10464. }
  10465. if (values.length > length)
  10466. values = Base.slice(values, 0, length);
  10467. } else if (argType === 'string') {
  10468. var converted = fromCSS(arg);
  10469. type = converted[0];
  10470. components = converted[1];
  10471. if (components.length === 4) {
  10472. alpha = components[3];
  10473. components.length--;
  10474. }
  10475. } else if (argType === 'object') {
  10476. if (arg.constructor === Color) {
  10477. type = arg._type;
  10478. components = arg._components.slice();
  10479. alpha = arg._alpha;
  10480. if (type === 'gradient') {
  10481. for (var i = 1, l = components.length; i < l; i++) {
  10482. var point = components[i];
  10483. if (point)
  10484. components[i] = point.clone();
  10485. }
  10486. }
  10487. } else if (arg.constructor === Gradient) {
  10488. type = 'gradient';
  10489. values = args;
  10490. } else {
  10491. type = 'hue' in arg
  10492. ? 'lightness' in arg
  10493. ? 'hsl'
  10494. : 'hsb'
  10495. : 'gradient' in arg || 'stops' in arg
  10496. || 'radial' in arg
  10497. ? 'gradient'
  10498. : 'gray' in arg
  10499. ? 'gray'
  10500. : 'rgb';
  10501. var properties = types[type],
  10502. parsers = componentParsers[type];
  10503. this._components = components = [];
  10504. for (var i = 0, l = properties.length; i < l; i++) {
  10505. var value = arg[properties[i]];
  10506. if (value == null && !i && type === 'gradient'
  10507. && 'stops' in arg) {
  10508. value = {
  10509. stops: arg.stops,
  10510. radial: arg.radial
  10511. };
  10512. }
  10513. value = parsers[i].call(this, value);
  10514. if (value != null)
  10515. components[i] = value;
  10516. }
  10517. alpha = arg.alpha;
  10518. }
  10519. }
  10520. if (reading && type)
  10521. read = 1;
  10522. }
  10523. this._type = type || 'rgb';
  10524. if (!components) {
  10525. this._components = components = [];
  10526. var parsers = componentParsers[this._type];
  10527. for (var i = 0, l = parsers.length; i < l; i++) {
  10528. var value = parsers[i].call(this, values && values[i]);
  10529. if (value != null)
  10530. components[i] = value;
  10531. }
  10532. }
  10533. this._components = components;
  10534. this._properties = types[this._type];
  10535. this._alpha = alpha;
  10536. if (reading)
  10537. this.__read = read;
  10538. return this;
  10539. },
  10540. set: '#initialize',
  10541. _serialize: function(options, dictionary) {
  10542. var components = this.getComponents();
  10543. return Base.serialize(
  10544. /^(gray|rgb)$/.test(this._type)
  10545. ? components
  10546. : [this._type].concat(components),
  10547. options, true, dictionary);
  10548. },
  10549. _changed: function() {
  10550. this._canvasStyle = null;
  10551. if (this._owner)
  10552. this._owner._changed(129);
  10553. },
  10554. _convert: function(type) {
  10555. var converter;
  10556. return this._type === type
  10557. ? this._components.slice()
  10558. : (converter = converters[this._type + '-' + type])
  10559. ? converter.apply(this, this._components)
  10560. : converters['rgb-' + type].apply(this,
  10561. converters[this._type + '-rgb'].apply(this,
  10562. this._components));
  10563. },
  10564. convert: function(type) {
  10565. return new Color(type, this._convert(type), this._alpha);
  10566. },
  10567. getType: function() {
  10568. return this._type;
  10569. },
  10570. setType: function(type) {
  10571. this._components = this._convert(type);
  10572. this._properties = types[type];
  10573. this._type = type;
  10574. },
  10575. getComponents: function() {
  10576. var components = this._components.slice();
  10577. if (this._alpha != null)
  10578. components.push(this._alpha);
  10579. return components;
  10580. },
  10581. getAlpha: function() {
  10582. return this._alpha != null ? this._alpha : 1;
  10583. },
  10584. setAlpha: function(alpha) {
  10585. this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
  10586. this._changed();
  10587. },
  10588. hasAlpha: function() {
  10589. return this._alpha != null;
  10590. },
  10591. equals: function(color) {
  10592. var col = Base.isPlainValue(color, true)
  10593. ? Color.read(arguments)
  10594. : color;
  10595. return col === this || col && this._class === col._class
  10596. && this._type === col._type
  10597. && this.getAlpha() === col.getAlpha()
  10598. && Base.equals(this._components, col._components)
  10599. || false;
  10600. },
  10601. toString: function() {
  10602. var properties = this._properties,
  10603. parts = [],
  10604. isGradient = this._type === 'gradient',
  10605. f = Formatter.instance;
  10606. for (var i = 0, l = properties.length; i < l; i++) {
  10607. var value = this._components[i];
  10608. if (value != null)
  10609. parts.push(properties[i] + ': '
  10610. + (isGradient ? value : f.number(value)));
  10611. }
  10612. if (this._alpha != null)
  10613. parts.push('alpha: ' + f.number(this._alpha));
  10614. return '{ ' + parts.join(', ') + ' }';
  10615. },
  10616. toCSS: function(hex) {
  10617. var components = this._convert('rgb'),
  10618. alpha = hex || this._alpha == null ? 1 : this._alpha;
  10619. function convert(val) {
  10620. return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255);
  10621. }
  10622. components = [
  10623. convert(components[0]),
  10624. convert(components[1]),
  10625. convert(components[2])
  10626. ];
  10627. if (alpha < 1)
  10628. components.push(alpha < 0 ? 0 : alpha);
  10629. return hex
  10630. ? '#' + ((1 << 24) + (components[0] << 16)
  10631. + (components[1] << 8)
  10632. + components[2]).toString(16).slice(1)
  10633. : (components.length == 4 ? 'rgba(' : 'rgb(')
  10634. + components.join(',') + ')';
  10635. },
  10636. toCanvasStyle: function(ctx, matrix) {
  10637. if (this._canvasStyle)
  10638. return this._canvasStyle;
  10639. if (this._type !== 'gradient')
  10640. return this._canvasStyle = this.toCSS();
  10641. var components = this._components,
  10642. gradient = components[0],
  10643. stops = gradient._stops,
  10644. origin = components[1],
  10645. destination = components[2],
  10646. highlight = components[3],
  10647. inverse = matrix && matrix.inverted(),
  10648. canvasGradient;
  10649. if (inverse) {
  10650. origin = inverse._transformPoint(origin);
  10651. destination = inverse._transformPoint(destination);
  10652. if (highlight)
  10653. highlight = inverse._transformPoint(highlight);
  10654. }
  10655. if (gradient._radial) {
  10656. var radius = destination.getDistance(origin);
  10657. if (highlight) {
  10658. var vector = highlight.subtract(origin);
  10659. if (vector.getLength() > radius)
  10660. highlight = origin.add(vector.normalize(radius - 0.1));
  10661. }
  10662. var start = highlight || origin;
  10663. canvasGradient = ctx.createRadialGradient(start.x, start.y,
  10664. 0, origin.x, origin.y, radius);
  10665. } else {
  10666. canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
  10667. destination.x, destination.y);
  10668. }
  10669. for (var i = 0, l = stops.length; i < l; i++) {
  10670. var stop = stops[i],
  10671. offset = stop._offset;
  10672. canvasGradient.addColorStop(
  10673. offset == null ? i / (l - 1) : offset,
  10674. stop._color.toCanvasStyle());
  10675. }
  10676. return this._canvasStyle = canvasGradient;
  10677. },
  10678. transform: function(matrix) {
  10679. if (this._type === 'gradient') {
  10680. var components = this._components;
  10681. for (var i = 1, l = components.length; i < l; i++) {
  10682. var point = components[i];
  10683. matrix._transformPoint(point, point, true);
  10684. }
  10685. this._changed();
  10686. }
  10687. },
  10688. statics: {
  10689. _types: types,
  10690. random: function() {
  10691. var random = Math.random;
  10692. return new Color(random(), random(), random());
  10693. }
  10694. }
  10695. });
  10696. },
  10697. new function() {
  10698. var operators = {
  10699. add: function(a, b) {
  10700. return a + b;
  10701. },
  10702. subtract: function(a, b) {
  10703. return a - b;
  10704. },
  10705. multiply: function(a, b) {
  10706. return a * b;
  10707. },
  10708. divide: function(a, b) {
  10709. return a / b;
  10710. }
  10711. };
  10712. return Base.each(operators, function(operator, name) {
  10713. this[name] = function(color) {
  10714. color = Color.read(arguments);
  10715. var type = this._type,
  10716. components1 = this._components,
  10717. components2 = color._convert(type);
  10718. for (var i = 0, l = components1.length; i < l; i++)
  10719. components2[i] = operator(components1[i], components2[i]);
  10720. return new Color(type, components2,
  10721. this._alpha != null
  10722. ? operator(this._alpha, color.getAlpha())
  10723. : null);
  10724. };
  10725. }, {
  10726. });
  10727. });
  10728. var Gradient = Base.extend({
  10729. _class: 'Gradient',
  10730. initialize: function Gradient(stops, radial) {
  10731. this._id = UID.get();
  10732. if (stops && Base.isPlainObject(stops)) {
  10733. this.set(stops);
  10734. stops = radial = null;
  10735. }
  10736. if (this._stops == null) {
  10737. this.setStops(stops || ['white', 'black']);
  10738. }
  10739. if (this._radial == null) {
  10740. this.setRadial(typeof radial === 'string' && radial === 'radial'
  10741. || radial || false);
  10742. }
  10743. },
  10744. _serialize: function(options, dictionary) {
  10745. return dictionary.add(this, function() {
  10746. return Base.serialize([this._stops, this._radial],
  10747. options, true, dictionary);
  10748. });
  10749. },
  10750. _changed: function() {
  10751. for (var i = 0, l = this._owners && this._owners.length; i < l; i++) {
  10752. this._owners[i]._changed();
  10753. }
  10754. },
  10755. _addOwner: function(color) {
  10756. if (!this._owners)
  10757. this._owners = [];
  10758. this._owners.push(color);
  10759. },
  10760. _removeOwner: function(color) {
  10761. var index = this._owners ? this._owners.indexOf(color) : -1;
  10762. if (index != -1) {
  10763. this._owners.splice(index, 1);
  10764. if (!this._owners.length)
  10765. this._owners = undefined;
  10766. }
  10767. },
  10768. clone: function() {
  10769. var stops = [];
  10770. for (var i = 0, l = this._stops.length; i < l; i++) {
  10771. stops[i] = this._stops[i].clone();
  10772. }
  10773. return new Gradient(stops, this._radial);
  10774. },
  10775. getStops: function() {
  10776. return this._stops;
  10777. },
  10778. setStops: function(stops) {
  10779. if (stops.length < 2) {
  10780. throw new Error(
  10781. 'Gradient stop list needs to contain at least two stops.');
  10782. }
  10783. var _stops = this._stops;
  10784. if (_stops) {
  10785. for (var i = 0, l = _stops.length; i < l; i++)
  10786. _stops[i]._owner = undefined;
  10787. }
  10788. _stops = this._stops = GradientStop.readList(stops, 0, { clone: true });
  10789. for (var i = 0, l = _stops.length; i < l; i++)
  10790. _stops[i]._owner = this;
  10791. this._changed();
  10792. },
  10793. getRadial: function() {
  10794. return this._radial;
  10795. },
  10796. setRadial: function(radial) {
  10797. this._radial = radial;
  10798. this._changed();
  10799. },
  10800. equals: function(gradient) {
  10801. if (gradient === this)
  10802. return true;
  10803. if (gradient && this._class === gradient._class) {
  10804. var stops1 = this._stops,
  10805. stops2 = gradient._stops,
  10806. length = stops1.length;
  10807. if (length === stops2.length) {
  10808. for (var i = 0; i < length; i++) {
  10809. if (!stops1[i].equals(stops2[i]))
  10810. return false;
  10811. }
  10812. return true;
  10813. }
  10814. }
  10815. return false;
  10816. }
  10817. });
  10818. var GradientStop = Base.extend({
  10819. _class: 'GradientStop',
  10820. initialize: function GradientStop(arg0, arg1) {
  10821. var color = arg0,
  10822. offset = arg1;
  10823. if (typeof arg0 === 'object' && arg1 === undefined) {
  10824. if (Array.isArray(arg0) && typeof arg0[0] !== 'number') {
  10825. color = arg0[0];
  10826. offset = arg0[1];
  10827. } else if ('color' in arg0 || 'offset' in arg0
  10828. || 'rampPoint' in arg0) {
  10829. color = arg0.color;
  10830. offset = arg0.offset || arg0.rampPoint || 0;
  10831. }
  10832. }
  10833. this.setColor(color);
  10834. this.setOffset(offset);
  10835. },
  10836. clone: function() {
  10837. return new GradientStop(this._color.clone(), this._offset);
  10838. },
  10839. _serialize: function(options, dictionary) {
  10840. var color = this._color,
  10841. offset = this._offset;
  10842. return Base.serialize(offset == null ? [color] : [color, offset],
  10843. options, true, dictionary);
  10844. },
  10845. _changed: function() {
  10846. if (this._owner)
  10847. this._owner._changed(129);
  10848. },
  10849. getOffset: function() {
  10850. return this._offset;
  10851. },
  10852. setOffset: function(offset) {
  10853. this._offset = offset;
  10854. this._changed();
  10855. },
  10856. getRampPoint: '#getOffset',
  10857. setRampPoint: '#setOffset',
  10858. getColor: function() {
  10859. return this._color;
  10860. },
  10861. setColor: function() {
  10862. var color = Color.read(arguments, 0, { clone: true });
  10863. if (color)
  10864. color._owner = this;
  10865. this._color = color;
  10866. this._changed();
  10867. },
  10868. equals: function(stop) {
  10869. return stop === this || stop && this._class === stop._class
  10870. && this._color.equals(stop._color)
  10871. && this._offset == stop._offset
  10872. || false;
  10873. }
  10874. });
  10875. var Style = Base.extend(new function() {
  10876. var itemDefaults = {
  10877. fillColor: null,
  10878. fillRule: 'nonzero',
  10879. strokeColor: null,
  10880. strokeWidth: 1,
  10881. strokeCap: 'butt',
  10882. strokeJoin: 'miter',
  10883. strokeScaling: true,
  10884. miterLimit: 10,
  10885. dashOffset: 0,
  10886. dashArray: [],
  10887. shadowColor: null,
  10888. shadowBlur: 0,
  10889. shadowOffset: new Point(),
  10890. selectedColor: null
  10891. },
  10892. groupDefaults = Base.set({}, itemDefaults, {
  10893. fontFamily: 'sans-serif',
  10894. fontWeight: 'normal',
  10895. fontSize: 12,
  10896. leading: null,
  10897. justification: 'left'
  10898. }),
  10899. textDefaults = Base.set({}, groupDefaults, {
  10900. fillColor: new Color()
  10901. }),
  10902. flags = {
  10903. strokeWidth: 193,
  10904. strokeCap: 193,
  10905. strokeJoin: 193,
  10906. strokeScaling: 201,
  10907. miterLimit: 193,
  10908. fontFamily: 9,
  10909. fontWeight: 9,
  10910. fontSize: 9,
  10911. font: 9,
  10912. leading: 9,
  10913. justification: 9
  10914. },
  10915. item = {
  10916. beans: true
  10917. },
  10918. fields = {
  10919. _class: 'Style',
  10920. beans: true,
  10921. initialize: function Style(style, _owner, _project) {
  10922. this._values = {};
  10923. this._owner = _owner;
  10924. this._project = _owner && _owner._project || _project
  10925. || paper.project;
  10926. this._defaults = !_owner || _owner instanceof Group ? groupDefaults
  10927. : _owner instanceof TextItem ? textDefaults
  10928. : itemDefaults;
  10929. if (style)
  10930. this.set(style);
  10931. }
  10932. };
  10933. Base.each(groupDefaults, function(value, key) {
  10934. var isColor = /Color$/.test(key),
  10935. isPoint = key === 'shadowOffset',
  10936. part = Base.capitalize(key),
  10937. flag = flags[key],
  10938. set = 'set' + part,
  10939. get = 'get' + part;
  10940. fields[set] = function(value) {
  10941. var owner = this._owner,
  10942. children = owner && owner._children,
  10943. applyToChildren = children && children.length > 0
  10944. && !(owner instanceof CompoundPath);
  10945. if (applyToChildren) {
  10946. for (var i = 0, l = children.length; i < l; i++)
  10947. children[i]._style[set](value);
  10948. }
  10949. if ((key === 'selectedColor' || !applyToChildren)
  10950. && key in this._defaults) {
  10951. var old = this._values[key];
  10952. if (old !== value) {
  10953. if (isColor) {
  10954. if (old && old._owner !== undefined) {
  10955. old._owner = undefined;
  10956. old._canvasStyle = null;
  10957. }
  10958. if (value && value.constructor === Color) {
  10959. if (value._owner)
  10960. value = value.clone();
  10961. value._owner = owner;
  10962. }
  10963. }
  10964. this._values[key] = value;
  10965. if (owner)
  10966. owner._changed(flag || 129);
  10967. }
  10968. }
  10969. };
  10970. fields[get] = function(_dontMerge) {
  10971. var owner = this._owner,
  10972. children = owner && owner._children,
  10973. value;
  10974. if (key in this._defaults && (!children || !children.length
  10975. || _dontMerge || owner instanceof CompoundPath)) {
  10976. var value = this._values[key];
  10977. if (value === undefined) {
  10978. value = this._defaults[key];
  10979. if (value && value.clone)
  10980. value = value.clone();
  10981. } else {
  10982. var ctor = isColor ? Color : isPoint ? Point : null;
  10983. if (ctor && !(value && value.constructor === ctor)) {
  10984. this._values[key] = value = ctor.read([value], 0,
  10985. { readNull: true, clone: true });
  10986. if (value && isColor)
  10987. value._owner = owner;
  10988. }
  10989. }
  10990. } else if (children) {
  10991. for (var i = 0, l = children.length; i < l; i++) {
  10992. var childValue = children[i]._style[get]();
  10993. if (!i) {
  10994. value = childValue;
  10995. } else if (!Base.equals(value, childValue)) {
  10996. return undefined;
  10997. }
  10998. }
  10999. }
  11000. return value;
  11001. };
  11002. item[get] = function(_dontMerge) {
  11003. return this._style[get](_dontMerge);
  11004. };
  11005. item[set] = function(value) {
  11006. this._style[set](value);
  11007. };
  11008. });
  11009. Base.each({
  11010. Font: 'FontFamily',
  11011. WindingRule: 'FillRule'
  11012. }, function(value, key) {
  11013. var get = 'get' + key,
  11014. set = 'set' + key;
  11015. fields[get] = item[get] = '#get' + value;
  11016. fields[set] = item[set] = '#set' + value;
  11017. });
  11018. Item.inject(item);
  11019. return fields;
  11020. }, {
  11021. set: function(style) {
  11022. var isStyle = style instanceof Style,
  11023. values = isStyle ? style._values : style;
  11024. if (values) {
  11025. for (var key in values) {
  11026. if (key in this._defaults) {
  11027. var value = values[key];
  11028. this[key] = value && isStyle && value.clone
  11029. ? value.clone() : value;
  11030. }
  11031. }
  11032. }
  11033. },
  11034. equals: function(style) {
  11035. function compare(style1, style2, secondary) {
  11036. var values1 = style1._values,
  11037. values2 = style2._values,
  11038. defaults2 = style2._defaults;
  11039. for (var key in values1) {
  11040. var value1 = values1[key],
  11041. value2 = values2[key];
  11042. if (!(secondary && key in values2) && !Base.equals(value1,
  11043. value2 === undefined ? defaults2[key] : value2))
  11044. return false;
  11045. }
  11046. return true;
  11047. }
  11048. return style === this || style && this._class === style._class
  11049. && compare(this, style)
  11050. && compare(style, this, true)
  11051. || false;
  11052. },
  11053. _dispose: function() {
  11054. var color;
  11055. color = this.getFillColor();
  11056. if (color) color._canvasStyle = null;
  11057. color = this.getStrokeColor();
  11058. if (color) color._canvasStyle = null;
  11059. color = this.getShadowColor();
  11060. if (color) color._canvasStyle = null;
  11061. },
  11062. hasFill: function() {
  11063. var color = this.getFillColor();
  11064. return !!color && color.alpha > 0;
  11065. },
  11066. hasStroke: function() {
  11067. var color = this.getStrokeColor();
  11068. return !!color && color.alpha > 0 && this.getStrokeWidth() > 0;
  11069. },
  11070. hasShadow: function() {
  11071. var color = this.getShadowColor();
  11072. return !!color && color.alpha > 0 && (this.getShadowBlur() > 0
  11073. || !this.getShadowOffset().isZero());
  11074. },
  11075. getView: function() {
  11076. return this._project._view;
  11077. },
  11078. getFontStyle: function() {
  11079. var fontSize = this.getFontSize();
  11080. return this.getFontWeight()
  11081. + ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ')
  11082. + this.getFontFamily();
  11083. },
  11084. getFont: '#getFontFamily',
  11085. setFont: '#setFontFamily',
  11086. getLeading: function getLeading() {
  11087. var leading = getLeading.base.call(this),
  11088. fontSize = this.getFontSize();
  11089. if (/pt|em|%|px/.test(fontSize))
  11090. fontSize = this.getView().getPixelSize(fontSize);
  11091. return leading != null ? leading : fontSize * 1.2;
  11092. }
  11093. });
  11094. var DomElement = new function() {
  11095. function handlePrefix(el, name, set, value) {
  11096. var prefixes = ['', 'webkit', 'moz', 'Moz', 'ms', 'o'],
  11097. suffix = name[0].toUpperCase() + name.substring(1);
  11098. for (var i = 0; i < 6; i++) {
  11099. var prefix = prefixes[i],
  11100. key = prefix ? prefix + suffix : name;
  11101. if (key in el) {
  11102. if (set) {
  11103. el[key] = value;
  11104. } else {
  11105. return el[key];
  11106. }
  11107. break;
  11108. }
  11109. }
  11110. }
  11111. return {
  11112. getStyles: function(el) {
  11113. var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
  11114. view = doc && doc.defaultView;
  11115. return view && view.getComputedStyle(el, '');
  11116. },
  11117. getBounds: function(el, viewport) {
  11118. var doc = el.ownerDocument,
  11119. body = doc.body,
  11120. html = doc.documentElement,
  11121. rect;
  11122. try {
  11123. rect = el.getBoundingClientRect();
  11124. } catch (e) {
  11125. rect = { left: 0, top: 0, width: 0, height: 0 };
  11126. }
  11127. var x = rect.left - (html.clientLeft || body.clientLeft || 0),
  11128. y = rect.top - (html.clientTop || body.clientTop || 0);
  11129. if (!viewport) {
  11130. var view = doc.defaultView;
  11131. x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
  11132. y += view.pageYOffset || html.scrollTop || body.scrollTop;
  11133. }
  11134. return new Rectangle(x, y, rect.width, rect.height);
  11135. },
  11136. getViewportBounds: function(el) {
  11137. var doc = el.ownerDocument,
  11138. view = doc.defaultView,
  11139. html = doc.documentElement;
  11140. return new Rectangle(0, 0,
  11141. view.innerWidth || html.clientWidth,
  11142. view.innerHeight || html.clientHeight
  11143. );
  11144. },
  11145. getOffset: function(el, viewport) {
  11146. return DomElement.getBounds(el, viewport).getPoint();
  11147. },
  11148. getSize: function(el) {
  11149. return DomElement.getBounds(el, true).getSize();
  11150. },
  11151. isInvisible: function(el) {
  11152. return DomElement.getSize(el).equals(new Size(0, 0));
  11153. },
  11154. isInView: function(el) {
  11155. return !DomElement.isInvisible(el)
  11156. && DomElement.getViewportBounds(el).intersects(
  11157. DomElement.getBounds(el, true));
  11158. },
  11159. isInserted: function(el) {
  11160. return document.body.contains(el);
  11161. },
  11162. getPrefixed: function(el, name) {
  11163. return el && handlePrefix(el, name);
  11164. },
  11165. setPrefixed: function(el, name, value) {
  11166. if (typeof name === 'object') {
  11167. for (var key in name)
  11168. handlePrefix(el, key, true, name[key]);
  11169. } else {
  11170. handlePrefix(el, name, true, value);
  11171. }
  11172. }
  11173. };
  11174. };
  11175. var DomEvent = {
  11176. add: function(el, events) {
  11177. if (el) {
  11178. for (var type in events) {
  11179. var func = events[type],
  11180. parts = type.split(/[\s,]+/g);
  11181. for (var i = 0, l = parts.length; i < l; i++) {
  11182. var name = parts[i];
  11183. var options = (
  11184. el === document
  11185. && (name === 'touchstart' || name === 'touchmove')
  11186. ) ? { passive: false } : false;
  11187. el.addEventListener(name, func, options);
  11188. }
  11189. }
  11190. }
  11191. },
  11192. remove: function(el, events) {
  11193. if (el) {
  11194. for (var type in events) {
  11195. var func = events[type],
  11196. parts = type.split(/[\s,]+/g);
  11197. for (var i = 0, l = parts.length; i < l; i++)
  11198. el.removeEventListener(parts[i], func, false);
  11199. }
  11200. }
  11201. },
  11202. getPoint: function(event) {
  11203. var pos = event.targetTouches
  11204. ? event.targetTouches.length
  11205. ? event.targetTouches[0]
  11206. : event.changedTouches[0]
  11207. : event;
  11208. return new Point(
  11209. pos.pageX || pos.clientX + document.documentElement.scrollLeft,
  11210. pos.pageY || pos.clientY + document.documentElement.scrollTop
  11211. );
  11212. },
  11213. getTarget: function(event) {
  11214. return event.target || event.srcElement;
  11215. },
  11216. getRelatedTarget: function(event) {
  11217. return event.relatedTarget || event.toElement;
  11218. },
  11219. getOffset: function(event, target) {
  11220. return DomEvent.getPoint(event).subtract(DomElement.getOffset(
  11221. target || DomEvent.getTarget(event)));
  11222. }
  11223. };
  11224. DomEvent.requestAnimationFrame = new function() {
  11225. var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'),
  11226. requested = false,
  11227. callbacks = [],
  11228. timer;
  11229. function handleCallbacks() {
  11230. var functions = callbacks;
  11231. callbacks = [];
  11232. for (var i = 0, l = functions.length; i < l; i++)
  11233. functions[i]();
  11234. requested = nativeRequest && callbacks.length;
  11235. if (requested)
  11236. nativeRequest(handleCallbacks);
  11237. }
  11238. return function(callback) {
  11239. callbacks.push(callback);
  11240. if (nativeRequest) {
  11241. if (!requested) {
  11242. nativeRequest(handleCallbacks);
  11243. requested = true;
  11244. }
  11245. } else if (!timer) {
  11246. timer = setInterval(handleCallbacks, 1000 / 60);
  11247. }
  11248. };
  11249. };
  11250. var View = Base.extend(Emitter, {
  11251. _class: 'View',
  11252. initialize: function View(project, element) {
  11253. function getSize(name) {
  11254. return element[name] || parseInt(element.getAttribute(name), 10);
  11255. }
  11256. function getCanvasSize() {
  11257. var size = DomElement.getSize(element);
  11258. return size.isNaN() || size.isZero()
  11259. ? new Size(getSize('width'), getSize('height'))
  11260. : size;
  11261. }
  11262. var size;
  11263. if (window && element) {
  11264. this._id = element.getAttribute('id');
  11265. if (this._id == null)
  11266. element.setAttribute('id', this._id = 'view-' + View._id++);
  11267. DomEvent.add(element, this._viewEvents);
  11268. var none = 'none';
  11269. DomElement.setPrefixed(element.style, {
  11270. userDrag: none,
  11271. userSelect: none,
  11272. touchCallout: none,
  11273. contentZooming: none,
  11274. tapHighlightColor: 'rgba(0,0,0,0)'
  11275. });
  11276. if (PaperScope.hasAttribute(element, 'resize')) {
  11277. var that = this;
  11278. DomEvent.add(window, this._windowEvents = {
  11279. resize: function() {
  11280. that.setViewSize(getCanvasSize());
  11281. }
  11282. });
  11283. }
  11284. size = getCanvasSize();
  11285. if (PaperScope.hasAttribute(element, 'stats')
  11286. && typeof Stats !== 'undefined') {
  11287. this._stats = new Stats();
  11288. var stats = this._stats.domElement,
  11289. style = stats.style,
  11290. offset = DomElement.getOffset(element);
  11291. style.position = 'absolute';
  11292. style.left = offset.x + 'px';
  11293. style.top = offset.y + 'px';
  11294. document.body.appendChild(stats);
  11295. }
  11296. } else {
  11297. size = new Size(element);
  11298. element = null;
  11299. }
  11300. this._project = project;
  11301. this._scope = project._scope;
  11302. this._element = element;
  11303. if (!this._pixelRatio)
  11304. this._pixelRatio = window && window.devicePixelRatio || 1;
  11305. this._setElementSize(size.width, size.height);
  11306. this._viewSize = size;
  11307. View._views.push(this);
  11308. View._viewsById[this._id] = this;
  11309. (this._matrix = new Matrix())._owner = this;
  11310. if (!View._focused)
  11311. View._focused = this;
  11312. this._frameItems = {};
  11313. this._frameItemCount = 0;
  11314. this._itemEvents = { native: {}, virtual: {} };
  11315. this._autoUpdate = !paper.agent.node;
  11316. this._needsUpdate = false;
  11317. },
  11318. remove: function() {
  11319. if (!this._project)
  11320. return false;
  11321. if (View._focused === this)
  11322. View._focused = null;
  11323. View._views.splice(View._views.indexOf(this), 1);
  11324. delete View._viewsById[this._id];
  11325. var project = this._project;
  11326. if (project._view === this)
  11327. project._view = null;
  11328. DomEvent.remove(this._element, this._viewEvents);
  11329. DomEvent.remove(window, this._windowEvents);
  11330. this._element = this._project = null;
  11331. this.off('frame');
  11332. this._animate = false;
  11333. this._frameItems = {};
  11334. return true;
  11335. },
  11336. _events: Base.each(
  11337. Item._itemHandlers.concat(['onResize', 'onKeyDown', 'onKeyUp']),
  11338. function(name) {
  11339. this[name] = {};
  11340. }, {
  11341. onFrame: {
  11342. install: function() {
  11343. this.play();
  11344. },
  11345. uninstall: function() {
  11346. this.pause();
  11347. }
  11348. }
  11349. }
  11350. ),
  11351. _animate: false,
  11352. _time: 0,
  11353. _count: 0,
  11354. getAutoUpdate: function() {
  11355. return this._autoUpdate;
  11356. },
  11357. setAutoUpdate: function(autoUpdate) {
  11358. this._autoUpdate = autoUpdate;
  11359. if (autoUpdate)
  11360. this.requestUpdate();
  11361. },
  11362. update: function() {
  11363. },
  11364. draw: function() {
  11365. this.update();
  11366. },
  11367. requestUpdate: function() {
  11368. if (!this._requested) {
  11369. var that = this;
  11370. DomEvent.requestAnimationFrame(function() {
  11371. that._requested = false;
  11372. if (that._animate) {
  11373. that.requestUpdate();
  11374. var element = that._element;
  11375. if ((!DomElement.getPrefixed(document, 'hidden')
  11376. || PaperScope.getAttribute(element, 'keepalive')
  11377. === 'true') && DomElement.isInView(element)) {
  11378. that._handleFrame();
  11379. }
  11380. }
  11381. if (that._autoUpdate)
  11382. that.update();
  11383. });
  11384. this._requested = true;
  11385. }
  11386. },
  11387. play: function() {
  11388. this._animate = true;
  11389. this.requestUpdate();
  11390. },
  11391. pause: function() {
  11392. this._animate = false;
  11393. },
  11394. _handleFrame: function() {
  11395. paper = this._scope;
  11396. var now = Date.now() / 1000,
  11397. delta = this._last ? now - this._last : 0;
  11398. this._last = now;
  11399. this.emit('frame', new Base({
  11400. delta: delta,
  11401. time: this._time += delta,
  11402. count: this._count++
  11403. }));
  11404. if (this._stats)
  11405. this._stats.update();
  11406. },
  11407. _animateItem: function(item, animate) {
  11408. var items = this._frameItems;
  11409. if (animate) {
  11410. items[item._id] = {
  11411. item: item,
  11412. time: 0,
  11413. count: 0
  11414. };
  11415. if (++this._frameItemCount === 1)
  11416. this.on('frame', this._handleFrameItems);
  11417. } else {
  11418. delete items[item._id];
  11419. if (--this._frameItemCount === 0) {
  11420. this.off('frame', this._handleFrameItems);
  11421. }
  11422. }
  11423. },
  11424. _handleFrameItems: function(event) {
  11425. for (var i in this._frameItems) {
  11426. var entry = this._frameItems[i];
  11427. entry.item.emit('frame', new Base(event, {
  11428. time: entry.time += event.delta,
  11429. count: entry.count++
  11430. }));
  11431. }
  11432. },
  11433. _changed: function() {
  11434. this._project._changed(4097);
  11435. this._bounds = this._decomposed = undefined;
  11436. },
  11437. getElement: function() {
  11438. return this._element;
  11439. },
  11440. getPixelRatio: function() {
  11441. return this._pixelRatio;
  11442. },
  11443. getResolution: function() {
  11444. return this._pixelRatio * 72;
  11445. },
  11446. getViewSize: function() {
  11447. var size = this._viewSize;
  11448. return new LinkedSize(size.width, size.height, this, 'setViewSize');
  11449. },
  11450. setViewSize: function() {
  11451. var size = Size.read(arguments),
  11452. delta = size.subtract(this._viewSize);
  11453. if (delta.isZero())
  11454. return;
  11455. this._setElementSize(size.width, size.height);
  11456. this._viewSize.set(size);
  11457. this._changed();
  11458. this.emit('resize', { size: size, delta: delta });
  11459. if (this._autoUpdate) {
  11460. this.update();
  11461. }
  11462. },
  11463. _setElementSize: function(width, height) {
  11464. var element = this._element;
  11465. if (element) {
  11466. if (element.width !== width)
  11467. element.width = width;
  11468. if (element.height !== height)
  11469. element.height = height;
  11470. }
  11471. },
  11472. getBounds: function() {
  11473. if (!this._bounds)
  11474. this._bounds = this._matrix.inverted()._transformBounds(
  11475. new Rectangle(new Point(), this._viewSize));
  11476. return this._bounds;
  11477. },
  11478. getSize: function() {
  11479. return this.getBounds().getSize();
  11480. },
  11481. isVisible: function() {
  11482. return DomElement.isInView(this._element);
  11483. },
  11484. isInserted: function() {
  11485. return DomElement.isInserted(this._element);
  11486. },
  11487. getPixelSize: function(size) {
  11488. var element = this._element,
  11489. pixels;
  11490. if (element) {
  11491. var parent = element.parentNode,
  11492. temp = document.createElement('div');
  11493. temp.style.fontSize = size;
  11494. parent.appendChild(temp);
  11495. pixels = parseFloat(DomElement.getStyles(temp).fontSize);
  11496. parent.removeChild(temp);
  11497. } else {
  11498. pixels = parseFloat(pixels);
  11499. }
  11500. return pixels;
  11501. },
  11502. getTextWidth: function(font, lines) {
  11503. return 0;
  11504. }
  11505. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  11506. var rotate = key === 'rotate';
  11507. this[key] = function() {
  11508. var value = (rotate ? Base : Point).read(arguments),
  11509. center = Point.read(arguments, 0, { readNull: true });
  11510. return this.transform(new Matrix()[key](value,
  11511. center || this.getCenter(true)));
  11512. };
  11513. }, {
  11514. _decompose: function() {
  11515. return this._decomposed || (this._decomposed = this._matrix.decompose());
  11516. },
  11517. translate: function() {
  11518. var mx = new Matrix();
  11519. return this.transform(mx.translate.apply(mx, arguments));
  11520. },
  11521. getCenter: function() {
  11522. return this.getBounds().getCenter();
  11523. },
  11524. setCenter: function() {
  11525. var center = Point.read(arguments);
  11526. this.translate(this.getCenter().subtract(center));
  11527. },
  11528. getZoom: function() {
  11529. var scaling = this._decompose().scaling;
  11530. return (scaling.x + scaling.y) / 2;
  11531. },
  11532. setZoom: function(zoom) {
  11533. this.transform(new Matrix().scale(zoom / this.getZoom(),
  11534. this.getCenter()));
  11535. },
  11536. getRotation: function() {
  11537. return this._decompose().rotation;
  11538. },
  11539. setRotation: function(rotation) {
  11540. var current = this.getRotation();
  11541. if (current != null && rotation != null) {
  11542. this.rotate(rotation - current);
  11543. }
  11544. },
  11545. getScaling: function() {
  11546. var scaling = this._decompose().scaling;
  11547. return new LinkedPoint(scaling.x, scaling.y, this, 'setScaling');
  11548. },
  11549. setScaling: function() {
  11550. var current = this.getScaling(),
  11551. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  11552. if (current && scaling) {
  11553. this.scale(scaling.x / current.x, scaling.y / current.y);
  11554. }
  11555. },
  11556. getMatrix: function() {
  11557. return this._matrix;
  11558. },
  11559. setMatrix: function() {
  11560. var matrix = this._matrix;
  11561. matrix.initialize.apply(matrix, arguments);
  11562. },
  11563. transform: function(matrix) {
  11564. this._matrix.append(matrix);
  11565. },
  11566. scrollBy: function() {
  11567. this.translate(Point.read(arguments).negate());
  11568. }
  11569. }), {
  11570. projectToView: function() {
  11571. return this._matrix._transformPoint(Point.read(arguments));
  11572. },
  11573. viewToProject: function() {
  11574. return this._matrix._inverseTransform(Point.read(arguments));
  11575. },
  11576. getEventPoint: function(event) {
  11577. return this.viewToProject(DomEvent.getOffset(event, this._element));
  11578. },
  11579. }, {
  11580. statics: {
  11581. _views: [],
  11582. _viewsById: {},
  11583. _id: 0,
  11584. create: function(project, element) {
  11585. if (document && typeof element === 'string')
  11586. element = document.getElementById(element);
  11587. var ctor = window ? CanvasView : View;
  11588. return new ctor(project, element);
  11589. }
  11590. }
  11591. },
  11592. new function() {
  11593. if (!window)
  11594. return;
  11595. var prevFocus,
  11596. tempFocus,
  11597. dragging = false,
  11598. mouseDown = false;
  11599. function getView(event) {
  11600. var target = DomEvent.getTarget(event);
  11601. return target.getAttribute && View._viewsById[
  11602. target.getAttribute('id')];
  11603. }
  11604. function updateFocus() {
  11605. var view = View._focused;
  11606. if (!view || !view.isVisible()) {
  11607. for (var i = 0, l = View._views.length; i < l; i++) {
  11608. if ((view = View._views[i]).isVisible()) {
  11609. View._focused = tempFocus = view;
  11610. break;
  11611. }
  11612. }
  11613. }
  11614. }
  11615. function handleMouseMove(view, event, point) {
  11616. view._handleMouseEvent('mousemove', event, point);
  11617. }
  11618. var navigator = window.navigator,
  11619. mousedown, mousemove, mouseup;
  11620. if (navigator.pointerEnabled || navigator.msPointerEnabled) {
  11621. mousedown = 'pointerdown MSPointerDown';
  11622. mousemove = 'pointermove MSPointerMove';
  11623. mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel';
  11624. } else {
  11625. mousedown = 'touchstart';
  11626. mousemove = 'touchmove';
  11627. mouseup = 'touchend touchcancel';
  11628. if (!('ontouchstart' in window && navigator.userAgent.match(
  11629. /mobile|tablet|ip(ad|hone|od)|android|silk/i))) {
  11630. mousedown += ' mousedown';
  11631. mousemove += ' mousemove';
  11632. mouseup += ' mouseup';
  11633. }
  11634. }
  11635. var viewEvents = {},
  11636. docEvents = {
  11637. mouseout: function(event) {
  11638. var view = View._focused,
  11639. target = DomEvent.getRelatedTarget(event);
  11640. if (view && (!target || target.nodeName === 'HTML')) {
  11641. var offset = DomEvent.getOffset(event, view._element),
  11642. x = offset.x,
  11643. abs = Math.abs,
  11644. ax = abs(x),
  11645. max = 1 << 25,
  11646. diff = ax - max;
  11647. offset.x = abs(diff) < ax ? diff * (x < 0 ? -1 : 1) : x;
  11648. handleMouseMove(view, event, view.viewToProject(offset));
  11649. }
  11650. },
  11651. scroll: updateFocus
  11652. };
  11653. viewEvents[mousedown] = function(event) {
  11654. var view = View._focused = getView(event);
  11655. if (!dragging) {
  11656. dragging = true;
  11657. view._handleMouseEvent('mousedown', event);
  11658. }
  11659. };
  11660. docEvents[mousemove] = function(event) {
  11661. var view = View._focused;
  11662. if (!mouseDown) {
  11663. var target = getView(event);
  11664. if (target) {
  11665. if (view !== target) {
  11666. if (view)
  11667. handleMouseMove(view, event);
  11668. if (!prevFocus)
  11669. prevFocus = view;
  11670. view = View._focused = tempFocus = target;
  11671. }
  11672. } else if (tempFocus && tempFocus === view) {
  11673. if (prevFocus && !prevFocus.isInserted())
  11674. prevFocus = null;
  11675. view = View._focused = prevFocus;
  11676. prevFocus = null;
  11677. updateFocus();
  11678. }
  11679. }
  11680. if (view)
  11681. handleMouseMove(view, event);
  11682. };
  11683. docEvents[mousedown] = function() {
  11684. mouseDown = true;
  11685. };
  11686. docEvents[mouseup] = function(event) {
  11687. var view = View._focused;
  11688. if (view && dragging)
  11689. view._handleMouseEvent('mouseup', event);
  11690. mouseDown = dragging = false;
  11691. };
  11692. DomEvent.add(document, docEvents);
  11693. DomEvent.add(window, {
  11694. load: updateFocus
  11695. });
  11696. var called = false,
  11697. prevented = false,
  11698. fallbacks = {
  11699. doubleclick: 'click',
  11700. mousedrag: 'mousemove'
  11701. },
  11702. wasInView = false,
  11703. overView,
  11704. downPoint,
  11705. lastPoint,
  11706. downItem,
  11707. overItem,
  11708. dragItem,
  11709. clickItem,
  11710. clickTime,
  11711. dblClick;
  11712. function emitMouseEvent(obj, target, type, event, point, prevPoint,
  11713. stopItem) {
  11714. var stopped = false,
  11715. mouseEvent;
  11716. function emit(obj, type) {
  11717. if (obj.responds(type)) {
  11718. if (!mouseEvent) {
  11719. mouseEvent = new MouseEvent(type, event, point,
  11720. target || obj,
  11721. prevPoint ? point.subtract(prevPoint) : null);
  11722. }
  11723. if (obj.emit(type, mouseEvent)) {
  11724. called = true;
  11725. if (mouseEvent.prevented)
  11726. prevented = true;
  11727. if (mouseEvent.stopped)
  11728. return stopped = true;
  11729. }
  11730. } else {
  11731. var fallback = fallbacks[type];
  11732. if (fallback)
  11733. return emit(obj, fallback);
  11734. }
  11735. }
  11736. while (obj && obj !== stopItem) {
  11737. if (emit(obj, type))
  11738. break;
  11739. obj = obj._parent;
  11740. }
  11741. return stopped;
  11742. }
  11743. function emitMouseEvents(view, hitItem, type, event, point, prevPoint) {
  11744. view._project.removeOn(type);
  11745. prevented = called = false;
  11746. return (dragItem && emitMouseEvent(dragItem, null, type, event,
  11747. point, prevPoint)
  11748. || hitItem && hitItem !== dragItem
  11749. && !hitItem.isDescendant(dragItem)
  11750. && emitMouseEvent(hitItem, null, type === 'mousedrag' ?
  11751. 'mousemove' : type, event, point, prevPoint, dragItem)
  11752. || emitMouseEvent(view, dragItem || hitItem || view, type, event,
  11753. point, prevPoint));
  11754. }
  11755. var itemEventsMap = {
  11756. mousedown: {
  11757. mousedown: 1,
  11758. mousedrag: 1,
  11759. click: 1,
  11760. doubleclick: 1
  11761. },
  11762. mouseup: {
  11763. mouseup: 1,
  11764. mousedrag: 1,
  11765. click: 1,
  11766. doubleclick: 1
  11767. },
  11768. mousemove: {
  11769. mousedrag: 1,
  11770. mousemove: 1,
  11771. mouseenter: 1,
  11772. mouseleave: 1
  11773. }
  11774. };
  11775. return {
  11776. _viewEvents: viewEvents,
  11777. _handleMouseEvent: function(type, event, point) {
  11778. var itemEvents = this._itemEvents,
  11779. hitItems = itemEvents.native[type],
  11780. nativeMove = type === 'mousemove',
  11781. tool = this._scope.tool,
  11782. view = this;
  11783. function responds(type) {
  11784. return itemEvents.virtual[type] || view.responds(type)
  11785. || tool && tool.responds(type);
  11786. }
  11787. if (nativeMove && dragging && responds('mousedrag'))
  11788. type = 'mousedrag';
  11789. if (!point)
  11790. point = this.getEventPoint(event);
  11791. var inView = this.getBounds().contains(point),
  11792. hit = hitItems && inView && view._project.hitTest(point, {
  11793. tolerance: 0,
  11794. fill: true,
  11795. stroke: true
  11796. }),
  11797. hitItem = hit && hit.item || null,
  11798. handle = false,
  11799. mouse = {};
  11800. mouse[type.substr(5)] = true;
  11801. if (hitItems && hitItem !== overItem) {
  11802. if (overItem) {
  11803. emitMouseEvent(overItem, null, 'mouseleave', event, point);
  11804. }
  11805. if (hitItem) {
  11806. emitMouseEvent(hitItem, null, 'mouseenter', event, point);
  11807. }
  11808. overItem = hitItem;
  11809. }
  11810. if (wasInView ^ inView) {
  11811. emitMouseEvent(this, null, inView ? 'mouseenter' : 'mouseleave',
  11812. event, point);
  11813. overView = inView ? this : null;
  11814. handle = true;
  11815. }
  11816. if ((inView || mouse.drag) && !point.equals(lastPoint)) {
  11817. emitMouseEvents(this, hitItem, nativeMove ? type : 'mousemove',
  11818. event, point, lastPoint);
  11819. handle = true;
  11820. }
  11821. wasInView = inView;
  11822. if (mouse.down && inView || mouse.up && downPoint) {
  11823. emitMouseEvents(this, hitItem, type, event, point, downPoint);
  11824. if (mouse.down) {
  11825. dblClick = hitItem === clickItem
  11826. && (Date.now() - clickTime < 300);
  11827. downItem = clickItem = hitItem;
  11828. if (!prevented && hitItem) {
  11829. var item = hitItem;
  11830. while (item && !item.responds('mousedrag'))
  11831. item = item._parent;
  11832. if (item)
  11833. dragItem = hitItem;
  11834. }
  11835. downPoint = point;
  11836. } else if (mouse.up) {
  11837. if (!prevented && hitItem === downItem) {
  11838. clickTime = Date.now();
  11839. emitMouseEvents(this, hitItem, dblClick ? 'doubleclick'
  11840. : 'click', event, point, downPoint);
  11841. dblClick = false;
  11842. }
  11843. downItem = dragItem = null;
  11844. }
  11845. wasInView = false;
  11846. handle = true;
  11847. }
  11848. lastPoint = point;
  11849. if (handle && tool) {
  11850. called = tool._handleMouseEvent(type, event, point, mouse)
  11851. || called;
  11852. }
  11853. if (
  11854. event.cancelable !== false
  11855. && (called && !mouse.move || mouse.down && responds('mouseup'))
  11856. ) {
  11857. event.preventDefault();
  11858. }
  11859. },
  11860. _handleKeyEvent: function(type, event, key, character) {
  11861. var scope = this._scope,
  11862. tool = scope.tool,
  11863. keyEvent;
  11864. function emit(obj) {
  11865. if (obj.responds(type)) {
  11866. paper = scope;
  11867. obj.emit(type, keyEvent = keyEvent
  11868. || new KeyEvent(type, event, key, character));
  11869. }
  11870. }
  11871. if (this.isVisible()) {
  11872. emit(this);
  11873. if (tool && tool.responds(type))
  11874. emit(tool);
  11875. }
  11876. },
  11877. _countItemEvent: function(type, sign) {
  11878. var itemEvents = this._itemEvents,
  11879. native = itemEvents.native,
  11880. virtual = itemEvents.virtual;
  11881. for (var key in itemEventsMap) {
  11882. native[key] = (native[key] || 0)
  11883. + (itemEventsMap[key][type] || 0) * sign;
  11884. }
  11885. virtual[type] = (virtual[type] || 0) + sign;
  11886. },
  11887. statics: {
  11888. updateFocus: updateFocus,
  11889. _resetState: function() {
  11890. dragging = mouseDown = called = wasInView = false;
  11891. prevFocus = tempFocus = overView = downPoint = lastPoint =
  11892. downItem = overItem = dragItem = clickItem = clickTime =
  11893. dblClick = null;
  11894. }
  11895. }
  11896. };
  11897. });
  11898. var CanvasView = View.extend({
  11899. _class: 'CanvasView',
  11900. initialize: function CanvasView(project, canvas) {
  11901. if (!(canvas instanceof window.HTMLCanvasElement)) {
  11902. var size = Size.read(arguments, 1);
  11903. if (size.isZero())
  11904. throw new Error(
  11905. 'Cannot create CanvasView with the provided argument: '
  11906. + Base.slice(arguments, 1));
  11907. canvas = CanvasProvider.getCanvas(size);
  11908. }
  11909. var ctx = this._context = canvas.getContext('2d');
  11910. ctx.save();
  11911. this._pixelRatio = 1;
  11912. if (!/^off|false$/.test(PaperScope.getAttribute(canvas, 'hidpi'))) {
  11913. var deviceRatio = window.devicePixelRatio || 1,
  11914. backingStoreRatio = DomElement.getPrefixed(ctx,
  11915. 'backingStorePixelRatio') || 1;
  11916. this._pixelRatio = deviceRatio / backingStoreRatio;
  11917. }
  11918. View.call(this, project, canvas);
  11919. this._needsUpdate = true;
  11920. },
  11921. remove: function remove() {
  11922. this._context.restore();
  11923. return remove.base.call(this);
  11924. },
  11925. _setElementSize: function _setElementSize(width, height) {
  11926. var pixelRatio = this._pixelRatio;
  11927. _setElementSize.base.call(this, width * pixelRatio, height * pixelRatio);
  11928. if (pixelRatio !== 1) {
  11929. var element = this._element,
  11930. ctx = this._context;
  11931. if (!PaperScope.hasAttribute(element, 'resize')) {
  11932. var style = element.style;
  11933. style.width = width + 'px';
  11934. style.height = height + 'px';
  11935. }
  11936. ctx.restore();
  11937. ctx.save();
  11938. ctx.scale(pixelRatio, pixelRatio);
  11939. }
  11940. },
  11941. getPixelSize: function getPixelSize(size) {
  11942. var agent = paper.agent,
  11943. pixels;
  11944. if (agent && agent.firefox) {
  11945. pixels = getPixelSize.base.call(this, size);
  11946. } else {
  11947. var ctx = this._context,
  11948. prevFont = ctx.font;
  11949. ctx.font = size + ' serif';
  11950. pixels = parseFloat(ctx.font);
  11951. ctx.font = prevFont;
  11952. }
  11953. return pixels;
  11954. },
  11955. getTextWidth: function(font, lines) {
  11956. var ctx = this._context,
  11957. prevFont = ctx.font,
  11958. width = 0;
  11959. ctx.font = font;
  11960. for (var i = 0, l = lines.length; i < l; i++)
  11961. width = Math.max(width, ctx.measureText(lines[i]).width);
  11962. ctx.font = prevFont;
  11963. return width;
  11964. },
  11965. update: function() {
  11966. if (!this._needsUpdate)
  11967. return false;
  11968. var project = this._project,
  11969. ctx = this._context,
  11970. size = this._viewSize;
  11971. ctx.clearRect(0, 0, size.width + 1, size.height + 1);
  11972. if (project)
  11973. project.draw(ctx, this._matrix, this._pixelRatio);
  11974. this._needsUpdate = false;
  11975. return true;
  11976. }
  11977. });
  11978. var Event = Base.extend({
  11979. _class: 'Event',
  11980. initialize: function Event(event) {
  11981. this.event = event;
  11982. this.type = event && event.type;
  11983. },
  11984. prevented: false,
  11985. stopped: false,
  11986. preventDefault: function() {
  11987. this.prevented = true;
  11988. this.event.preventDefault();
  11989. },
  11990. stopPropagation: function() {
  11991. this.stopped = true;
  11992. this.event.stopPropagation();
  11993. },
  11994. stop: function() {
  11995. this.stopPropagation();
  11996. this.preventDefault();
  11997. },
  11998. getTimeStamp: function() {
  11999. return this.event.timeStamp;
  12000. },
  12001. getModifiers: function() {
  12002. return Key.modifiers;
  12003. }
  12004. });
  12005. var KeyEvent = Event.extend({
  12006. _class: 'KeyEvent',
  12007. initialize: function KeyEvent(type, event, key, character) {
  12008. this.type = type;
  12009. this.event = event;
  12010. this.key = key;
  12011. this.character = character;
  12012. },
  12013. toString: function() {
  12014. return "{ type: '" + this.type
  12015. + "', key: '" + this.key
  12016. + "', character: '" + this.character
  12017. + "', modifiers: " + this.getModifiers()
  12018. + " }";
  12019. }
  12020. });
  12021. var Key = new function() {
  12022. var keyLookup = {
  12023. '\t': 'tab',
  12024. ' ': 'space',
  12025. '\b': 'backspace',
  12026. '\x7f': 'delete',
  12027. 'Spacebar': 'space',
  12028. 'Del': 'delete',
  12029. 'Win': 'meta',
  12030. 'Esc': 'escape'
  12031. },
  12032. charLookup = {
  12033. 'tab': '\t',
  12034. 'space': ' ',
  12035. 'enter': '\r'
  12036. },
  12037. keyMap = {},
  12038. charMap = {},
  12039. metaFixMap,
  12040. downKey,
  12041. modifiers = new Base({
  12042. shift: false,
  12043. control: false,
  12044. alt: false,
  12045. meta: false,
  12046. capsLock: false,
  12047. space: false
  12048. }).inject({
  12049. option: {
  12050. get: function() {
  12051. return this.alt;
  12052. }
  12053. },
  12054. command: {
  12055. get: function() {
  12056. var agent = paper && paper.agent;
  12057. return agent && agent.mac ? this.meta : this.control;
  12058. }
  12059. }
  12060. });
  12061. function getKey(event) {
  12062. var key = event.key || event.keyIdentifier;
  12063. key = /^U\+/.test(key)
  12064. ? String.fromCharCode(parseInt(key.substr(2), 16))
  12065. : /^Arrow[A-Z]/.test(key) ? key.substr(5)
  12066. : key === 'Unidentified' || key === undefined
  12067. ? String.fromCharCode(event.keyCode)
  12068. : key;
  12069. return keyLookup[key] ||
  12070. (key.length > 1 ? Base.hyphenate(key) : key.toLowerCase());
  12071. }
  12072. function handleKey(down, key, character, event) {
  12073. var type = down ? 'keydown' : 'keyup',
  12074. view = View._focused,
  12075. name;
  12076. keyMap[key] = down;
  12077. if (down) {
  12078. charMap[key] = character;
  12079. } else {
  12080. delete charMap[key];
  12081. }
  12082. if (key.length > 1 && (name = Base.camelize(key)) in modifiers) {
  12083. modifiers[name] = down;
  12084. var agent = paper && paper.agent;
  12085. if (name === 'meta' && agent && agent.mac) {
  12086. if (down) {
  12087. metaFixMap = {};
  12088. } else {
  12089. for (var k in metaFixMap) {
  12090. if (k in charMap)
  12091. handleKey(false, k, metaFixMap[k], event);
  12092. }
  12093. metaFixMap = null;
  12094. }
  12095. }
  12096. } else if (down && metaFixMap) {
  12097. metaFixMap[key] = character;
  12098. }
  12099. if (view) {
  12100. view._handleKeyEvent(down ? 'keydown' : 'keyup', event, key,
  12101. character);
  12102. }
  12103. }
  12104. DomEvent.add(document, {
  12105. keydown: function(event) {
  12106. var key = getKey(event),
  12107. agent = paper && paper.agent;
  12108. if (key.length > 1 || agent && (agent.chrome && (event.altKey
  12109. || agent.mac && event.metaKey
  12110. || !agent.mac && event.ctrlKey))) {
  12111. handleKey(true, key,
  12112. charLookup[key] || (key.length > 1 ? '' : key), event);
  12113. } else {
  12114. downKey = key;
  12115. }
  12116. },
  12117. keypress: function(event) {
  12118. if (downKey) {
  12119. var key = getKey(event),
  12120. code = event.charCode,
  12121. character = code >= 32 ? String.fromCharCode(code)
  12122. : key.length > 1 ? '' : key;
  12123. if (key !== downKey) {
  12124. key = character.toLowerCase();
  12125. }
  12126. handleKey(true, key, character, event);
  12127. downKey = null;
  12128. }
  12129. },
  12130. keyup: function(event) {
  12131. var key = getKey(event);
  12132. if (key in charMap)
  12133. handleKey(false, key, charMap[key], event);
  12134. }
  12135. });
  12136. DomEvent.add(window, {
  12137. blur: function(event) {
  12138. for (var key in charMap)
  12139. handleKey(false, key, charMap[key], event);
  12140. }
  12141. });
  12142. return {
  12143. modifiers: modifiers,
  12144. isDown: function(key) {
  12145. return !!keyMap[key];
  12146. }
  12147. };
  12148. };
  12149. var MouseEvent = Event.extend({
  12150. _class: 'MouseEvent',
  12151. initialize: function MouseEvent(type, event, point, target, delta) {
  12152. this.type = type;
  12153. this.event = event;
  12154. this.point = point;
  12155. this.target = target;
  12156. this.delta = delta;
  12157. },
  12158. toString: function() {
  12159. return "{ type: '" + this.type
  12160. + "', point: " + this.point
  12161. + ', target: ' + this.target
  12162. + (this.delta ? ', delta: ' + this.delta : '')
  12163. + ', modifiers: ' + this.getModifiers()
  12164. + ' }';
  12165. }
  12166. });
  12167. var ToolEvent = Event.extend({
  12168. _class: 'ToolEvent',
  12169. _item: null,
  12170. initialize: function ToolEvent(tool, type, event) {
  12171. this.tool = tool;
  12172. this.type = type;
  12173. this.event = event;
  12174. },
  12175. _choosePoint: function(point, toolPoint) {
  12176. return point ? point : toolPoint ? toolPoint.clone() : null;
  12177. },
  12178. getPoint: function() {
  12179. return this._choosePoint(this._point, this.tool._point);
  12180. },
  12181. setPoint: function(point) {
  12182. this._point = point;
  12183. },
  12184. getLastPoint: function() {
  12185. return this._choosePoint(this._lastPoint, this.tool._lastPoint);
  12186. },
  12187. setLastPoint: function(lastPoint) {
  12188. this._lastPoint = lastPoint;
  12189. },
  12190. getDownPoint: function() {
  12191. return this._choosePoint(this._downPoint, this.tool._downPoint);
  12192. },
  12193. setDownPoint: function(downPoint) {
  12194. this._downPoint = downPoint;
  12195. },
  12196. getMiddlePoint: function() {
  12197. if (!this._middlePoint && this.tool._lastPoint) {
  12198. return this.tool._point.add(this.tool._lastPoint).divide(2);
  12199. }
  12200. return this._middlePoint;
  12201. },
  12202. setMiddlePoint: function(middlePoint) {
  12203. this._middlePoint = middlePoint;
  12204. },
  12205. getDelta: function() {
  12206. return !this._delta && this.tool._lastPoint
  12207. ? this.tool._point.subtract(this.tool._lastPoint)
  12208. : this._delta;
  12209. },
  12210. setDelta: function(delta) {
  12211. this._delta = delta;
  12212. },
  12213. getCount: function() {
  12214. return this.tool[/^mouse(down|up)$/.test(this.type)
  12215. ? '_downCount' : '_moveCount'];
  12216. },
  12217. setCount: function(count) {
  12218. this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
  12219. = count;
  12220. },
  12221. getItem: function() {
  12222. if (!this._item) {
  12223. var result = this.tool._scope.project.hitTest(this.getPoint());
  12224. if (result) {
  12225. var item = result.item,
  12226. parent = item._parent;
  12227. while (/^(Group|CompoundPath)$/.test(parent._class)) {
  12228. item = parent;
  12229. parent = parent._parent;
  12230. }
  12231. this._item = item;
  12232. }
  12233. }
  12234. return this._item;
  12235. },
  12236. setItem: function(item) {
  12237. this._item = item;
  12238. },
  12239. toString: function() {
  12240. return '{ type: ' + this.type
  12241. + ', point: ' + this.getPoint()
  12242. + ', count: ' + this.getCount()
  12243. + ', modifiers: ' + this.getModifiers()
  12244. + ' }';
  12245. }
  12246. });
  12247. var Tool = PaperScopeItem.extend({
  12248. _class: 'Tool',
  12249. _list: 'tools',
  12250. _reference: 'tool',
  12251. _events: ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
  12252. 'onActivate', 'onDeactivate', 'onEditOptions', 'onKeyDown',
  12253. 'onKeyUp'],
  12254. initialize: function Tool(props) {
  12255. PaperScopeItem.call(this);
  12256. this._moveCount = -1;
  12257. this._downCount = -1;
  12258. this.set(props);
  12259. },
  12260. getMinDistance: function() {
  12261. return this._minDistance;
  12262. },
  12263. setMinDistance: function(minDistance) {
  12264. this._minDistance = minDistance;
  12265. if (minDistance != null && this._maxDistance != null
  12266. && minDistance > this._maxDistance) {
  12267. this._maxDistance = minDistance;
  12268. }
  12269. },
  12270. getMaxDistance: function() {
  12271. return this._maxDistance;
  12272. },
  12273. setMaxDistance: function(maxDistance) {
  12274. this._maxDistance = maxDistance;
  12275. if (this._minDistance != null && maxDistance != null
  12276. && maxDistance < this._minDistance) {
  12277. this._minDistance = maxDistance;
  12278. }
  12279. },
  12280. getFixedDistance: function() {
  12281. return this._minDistance == this._maxDistance
  12282. ? this._minDistance : null;
  12283. },
  12284. setFixedDistance: function(distance) {
  12285. this._minDistance = this._maxDistance = distance;
  12286. },
  12287. _handleMouseEvent: function(type, event, point, mouse) {
  12288. paper = this._scope;
  12289. if (mouse.drag && !this.responds(type))
  12290. type = 'mousemove';
  12291. var move = mouse.move || mouse.drag,
  12292. responds = this.responds(type),
  12293. minDistance = this.minDistance,
  12294. maxDistance = this.maxDistance,
  12295. called = false,
  12296. tool = this;
  12297. function update(minDistance, maxDistance) {
  12298. var pt = point,
  12299. toolPoint = move ? tool._point : (tool._downPoint || pt);
  12300. if (move) {
  12301. if (tool._moveCount >= 0 && pt.equals(toolPoint)) {
  12302. return false;
  12303. }
  12304. if (toolPoint && (minDistance != null || maxDistance != null)) {
  12305. var vector = pt.subtract(toolPoint),
  12306. distance = vector.getLength();
  12307. if (distance < (minDistance || 0))
  12308. return false;
  12309. if (maxDistance) {
  12310. pt = toolPoint.add(vector.normalize(
  12311. Math.min(distance, maxDistance)));
  12312. }
  12313. }
  12314. tool._moveCount++;
  12315. }
  12316. tool._point = pt;
  12317. tool._lastPoint = toolPoint || pt;
  12318. if (mouse.down) {
  12319. tool._moveCount = -1;
  12320. tool._downPoint = pt;
  12321. tool._downCount++;
  12322. }
  12323. return true;
  12324. }
  12325. function emit() {
  12326. if (responds) {
  12327. called = tool.emit(type, new ToolEvent(tool, type, event))
  12328. || called;
  12329. }
  12330. }
  12331. if (mouse.down) {
  12332. update();
  12333. emit();
  12334. } else if (mouse.up) {
  12335. update(null, maxDistance);
  12336. emit();
  12337. } else if (responds) {
  12338. while (update(minDistance, maxDistance))
  12339. emit();
  12340. }
  12341. return called;
  12342. }
  12343. });
  12344. var Tween = Base.extend(Emitter, {
  12345. _class: 'Tween',
  12346. statics: {
  12347. easings: {
  12348. linear: function(t) {
  12349. return t;
  12350. },
  12351. easeInQuad: function(t) {
  12352. return t * t;
  12353. },
  12354. easeOutQuad: function(t) {
  12355. return t * (2 - t);
  12356. },
  12357. easeInOutQuad: function(t) {
  12358. return t < 0.5
  12359. ? 2 * t * t
  12360. : -1 + 2 * (2 - t) * t;
  12361. },
  12362. easeInCubic: function(t) {
  12363. return t * t * t;
  12364. },
  12365. easeOutCubic: function(t) {
  12366. return --t * t * t + 1;
  12367. },
  12368. easeInOutCubic: function(t) {
  12369. return t < 0.5
  12370. ? 4 * t * t * t
  12371. : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  12372. },
  12373. easeInQuart: function(t) {
  12374. return t * t * t * t;
  12375. },
  12376. easeOutQuart: function(t) {
  12377. return 1 - (--t) * t * t * t;
  12378. },
  12379. easeInOutQuart: function(t) {
  12380. return t < 0.5
  12381. ? 8 * t * t * t * t
  12382. : 1 - 8 * (--t) * t * t * t;
  12383. },
  12384. easeInQuint: function(t) {
  12385. return t * t * t * t * t;
  12386. },
  12387. easeOutQuint: function(t) {
  12388. return 1 + --t * t * t * t * t;
  12389. },
  12390. easeInOutQuint: function(t) {
  12391. return t < 0.5
  12392. ? 16 * t * t * t * t * t
  12393. : 1 + 16 * (--t) * t * t * t * t;
  12394. }
  12395. }
  12396. },
  12397. initialize: function Tween(object, from, to, duration, easing, start) {
  12398. this.object = object;
  12399. var type = typeof easing;
  12400. var isFunction = type === 'function';
  12401. this.type = isFunction
  12402. ? type
  12403. : type === 'string'
  12404. ? easing
  12405. : 'linear';
  12406. this.easing = isFunction ? easing : Tween.easings[this.type];
  12407. this.duration = duration;
  12408. this.running = false;
  12409. this._then = null;
  12410. this._startTime = null;
  12411. var state = from || to;
  12412. this._keys = state ? Object.keys(state) : [];
  12413. this._parsedKeys = this._parseKeys(this._keys);
  12414. this._from = state && this._getState(from);
  12415. this._to = state && this._getState(to);
  12416. if (start !== false) {
  12417. this.start();
  12418. }
  12419. },
  12420. then: function(then) {
  12421. this._then = then;
  12422. return this;
  12423. },
  12424. start: function() {
  12425. this._startTime = null;
  12426. this.running = true;
  12427. return this;
  12428. },
  12429. stop: function() {
  12430. this.running = false;
  12431. return this;
  12432. },
  12433. update: function(progress) {
  12434. if (this.running) {
  12435. if (progress > 1) {
  12436. progress = 1;
  12437. this.running = false;
  12438. }
  12439. var factor = this.easing(progress),
  12440. keys = this._keys,
  12441. getValue = function(value) {
  12442. return typeof value === 'function'
  12443. ? value(factor, progress)
  12444. : value;
  12445. };
  12446. for (var i = 0, l = keys && keys.length; i < l; i++) {
  12447. var key = keys[i],
  12448. from = getValue(this._from[key]),
  12449. to = getValue(this._to[key]),
  12450. value = (from && to && from.__add && to.__add)
  12451. ? to.__subtract(from).__multiply(factor).__add(from)
  12452. : ((to - from) * factor) + from;
  12453. this._setProperty(this._parsedKeys[key], value);
  12454. }
  12455. if (!this.running && this._then) {
  12456. this._then(this.object);
  12457. }
  12458. if (this.responds('update')) {
  12459. this.emit('update', new Base({
  12460. progress: progress,
  12461. factor: factor
  12462. }));
  12463. }
  12464. }
  12465. return this;
  12466. },
  12467. _events: {
  12468. onUpdate: {}
  12469. },
  12470. _handleFrame: function(time) {
  12471. var startTime = this._startTime,
  12472. progress = startTime
  12473. ? (time - startTime) / this.duration
  12474. : 0;
  12475. if (!startTime) {
  12476. this._startTime = time;
  12477. }
  12478. this.update(progress);
  12479. },
  12480. _getState: function(state) {
  12481. var keys = this._keys,
  12482. result = {};
  12483. for (var i = 0, l = keys.length; i < l; i++) {
  12484. var key = keys[i],
  12485. path = this._parsedKeys[key],
  12486. current = this._getProperty(path),
  12487. value;
  12488. if (state) {
  12489. var resolved = this._resolveValue(current, state[key]);
  12490. this._setProperty(path, resolved);
  12491. value = this._getProperty(path);
  12492. value = value && value.clone ? value.clone() : value;
  12493. this._setProperty(path, current);
  12494. } else {
  12495. value = current && current.clone ? current.clone() : current;
  12496. }
  12497. result[key] = value;
  12498. }
  12499. return result;
  12500. },
  12501. _resolveValue: function(current, value) {
  12502. if (value) {
  12503. if (Array.isArray(value) && value.length === 2) {
  12504. var operator = value[0];
  12505. return (
  12506. operator &&
  12507. operator.match &&
  12508. operator.match(/^[+\-*/]=/)
  12509. )
  12510. ? this._calculate(current, operator[0], value[1])
  12511. : value;
  12512. } else if (typeof value === 'string') {
  12513. var match = value.match(/^[+\-*/]=(.*)/);
  12514. if (match) {
  12515. var parsed = JSON.parse(match[1].replace(
  12516. /(['"])?([a-zA-Z0-9_]+)(['"])?:/g,
  12517. '"$2": '
  12518. ));
  12519. return this._calculate(current, value[0], parsed);
  12520. }
  12521. }
  12522. }
  12523. return value;
  12524. },
  12525. _calculate: function(left, operator, right) {
  12526. return paper.PaperScript.calculateBinary(left, operator, right);
  12527. },
  12528. _parseKeys: function(keys) {
  12529. var parsed = {};
  12530. for (var i = 0, l = keys.length; i < l; i++) {
  12531. var key = keys[i],
  12532. path = key
  12533. .replace(/\.([^.]*)/g, '/$1')
  12534. .replace(/\[['"]?([^'"\]]*)['"]?\]/g, '/$1');
  12535. parsed[key] = path.split('/');
  12536. }
  12537. return parsed;
  12538. },
  12539. _getProperty: function(path, offset) {
  12540. var obj = this.object;
  12541. for (var i = 0, l = path.length - (offset || 0); i < l && obj; i++) {
  12542. obj = obj[path[i]];
  12543. }
  12544. return obj;
  12545. },
  12546. _setProperty: function(path, value) {
  12547. var dest = this._getProperty(path, 1);
  12548. if (dest) {
  12549. dest[path[path.length - 1]] = value;
  12550. }
  12551. }
  12552. });
  12553. var Http = {
  12554. request: function(options) {
  12555. var xhr = new self.XMLHttpRequest();
  12556. xhr.open((options.method || 'get').toUpperCase(), options.url,
  12557. Base.pick(options.async, true));
  12558. if (options.mimeType)
  12559. xhr.overrideMimeType(options.mimeType);
  12560. xhr.onload = function() {
  12561. var status = xhr.status;
  12562. if (status === 0 || status === 200) {
  12563. if (options.onLoad) {
  12564. options.onLoad.call(xhr, xhr.responseText);
  12565. }
  12566. } else {
  12567. xhr.onerror();
  12568. }
  12569. };
  12570. xhr.onerror = function() {
  12571. var status = xhr.status,
  12572. message = 'Could not load "' + options.url + '" (Status: '
  12573. + status + ')';
  12574. if (options.onError) {
  12575. options.onError(message, status);
  12576. } else {
  12577. throw new Error(message);
  12578. }
  12579. };
  12580. return xhr.send(null);
  12581. }
  12582. };
  12583. var CanvasProvider = {
  12584. canvases: [],
  12585. getCanvas: function(width, height) {
  12586. if (!window)
  12587. return null;
  12588. var canvas,
  12589. clear = true;
  12590. if (typeof width === 'object') {
  12591. height = width.height;
  12592. width = width.width;
  12593. }
  12594. if (this.canvases.length) {
  12595. canvas = this.canvases.pop();
  12596. } else {
  12597. canvas = document.createElement('canvas');
  12598. clear = false;
  12599. }
  12600. var ctx = canvas.getContext('2d');
  12601. if (!ctx) {
  12602. throw new Error('Canvas ' + canvas +
  12603. ' is unable to provide a 2D context.');
  12604. }
  12605. if (canvas.width === width && canvas.height === height) {
  12606. if (clear)
  12607. ctx.clearRect(0, 0, width + 1, height + 1);
  12608. } else {
  12609. canvas.width = width;
  12610. canvas.height = height;
  12611. }
  12612. ctx.save();
  12613. return canvas;
  12614. },
  12615. getContext: function(width, height) {
  12616. var canvas = this.getCanvas(width, height);
  12617. return canvas ? canvas.getContext('2d') : null;
  12618. },
  12619. release: function(obj) {
  12620. var canvas = obj && obj.canvas ? obj.canvas : obj;
  12621. if (canvas && canvas.getContext) {
  12622. canvas.getContext('2d').restore();
  12623. this.canvases.push(canvas);
  12624. }
  12625. }
  12626. };
  12627. var BlendMode = new function() {
  12628. var min = Math.min,
  12629. max = Math.max,
  12630. abs = Math.abs,
  12631. sr, sg, sb, sa,
  12632. br, bg, bb, ba,
  12633. dr, dg, db;
  12634. function getLum(r, g, b) {
  12635. return 0.2989 * r + 0.587 * g + 0.114 * b;
  12636. }
  12637. function setLum(r, g, b, l) {
  12638. var d = l - getLum(r, g, b);
  12639. dr = r + d;
  12640. dg = g + d;
  12641. db = b + d;
  12642. var l = getLum(dr, dg, db),
  12643. mn = min(dr, dg, db),
  12644. mx = max(dr, dg, db);
  12645. if (mn < 0) {
  12646. var lmn = l - mn;
  12647. dr = l + (dr - l) * l / lmn;
  12648. dg = l + (dg - l) * l / lmn;
  12649. db = l + (db - l) * l / lmn;
  12650. }
  12651. if (mx > 255) {
  12652. var ln = 255 - l,
  12653. mxl = mx - l;
  12654. dr = l + (dr - l) * ln / mxl;
  12655. dg = l + (dg - l) * ln / mxl;
  12656. db = l + (db - l) * ln / mxl;
  12657. }
  12658. }
  12659. function getSat(r, g, b) {
  12660. return max(r, g, b) - min(r, g, b);
  12661. }
  12662. function setSat(r, g, b, s) {
  12663. var col = [r, g, b],
  12664. mx = max(r, g, b),
  12665. mn = min(r, g, b),
  12666. md;
  12667. mn = mn === r ? 0 : mn === g ? 1 : 2;
  12668. mx = mx === r ? 0 : mx === g ? 1 : 2;
  12669. md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
  12670. if (col[mx] > col[mn]) {
  12671. col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
  12672. col[mx] = s;
  12673. } else {
  12674. col[md] = col[mx] = 0;
  12675. }
  12676. col[mn] = 0;
  12677. dr = col[0];
  12678. dg = col[1];
  12679. db = col[2];
  12680. }
  12681. var modes = {
  12682. multiply: function() {
  12683. dr = br * sr / 255;
  12684. dg = bg * sg / 255;
  12685. db = bb * sb / 255;
  12686. },
  12687. screen: function() {
  12688. dr = br + sr - (br * sr / 255);
  12689. dg = bg + sg - (bg * sg / 255);
  12690. db = bb + sb - (bb * sb / 255);
  12691. },
  12692. overlay: function() {
  12693. dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
  12694. dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
  12695. db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
  12696. },
  12697. 'soft-light': function() {
  12698. var t = sr * br / 255;
  12699. dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
  12700. t = sg * bg / 255;
  12701. dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
  12702. t = sb * bb / 255;
  12703. db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
  12704. },
  12705. 'hard-light': function() {
  12706. dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
  12707. dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
  12708. db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
  12709. },
  12710. 'color-dodge': function() {
  12711. dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
  12712. dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
  12713. db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
  12714. },
  12715. 'color-burn': function() {
  12716. dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
  12717. dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
  12718. db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
  12719. },
  12720. darken: function() {
  12721. dr = br < sr ? br : sr;
  12722. dg = bg < sg ? bg : sg;
  12723. db = bb < sb ? bb : sb;
  12724. },
  12725. lighten: function() {
  12726. dr = br > sr ? br : sr;
  12727. dg = bg > sg ? bg : sg;
  12728. db = bb > sb ? bb : sb;
  12729. },
  12730. difference: function() {
  12731. dr = br - sr;
  12732. if (dr < 0)
  12733. dr = -dr;
  12734. dg = bg - sg;
  12735. if (dg < 0)
  12736. dg = -dg;
  12737. db = bb - sb;
  12738. if (db < 0)
  12739. db = -db;
  12740. },
  12741. exclusion: function() {
  12742. dr = br + sr * (255 - br - br) / 255;
  12743. dg = bg + sg * (255 - bg - bg) / 255;
  12744. db = bb + sb * (255 - bb - bb) / 255;
  12745. },
  12746. hue: function() {
  12747. setSat(sr, sg, sb, getSat(br, bg, bb));
  12748. setLum(dr, dg, db, getLum(br, bg, bb));
  12749. },
  12750. saturation: function() {
  12751. setSat(br, bg, bb, getSat(sr, sg, sb));
  12752. setLum(dr, dg, db, getLum(br, bg, bb));
  12753. },
  12754. luminosity: function() {
  12755. setLum(br, bg, bb, getLum(sr, sg, sb));
  12756. },
  12757. color: function() {
  12758. setLum(sr, sg, sb, getLum(br, bg, bb));
  12759. },
  12760. add: function() {
  12761. dr = min(br + sr, 255);
  12762. dg = min(bg + sg, 255);
  12763. db = min(bb + sb, 255);
  12764. },
  12765. subtract: function() {
  12766. dr = max(br - sr, 0);
  12767. dg = max(bg - sg, 0);
  12768. db = max(bb - sb, 0);
  12769. },
  12770. average: function() {
  12771. dr = (br + sr) / 2;
  12772. dg = (bg + sg) / 2;
  12773. db = (bb + sb) / 2;
  12774. },
  12775. negation: function() {
  12776. dr = 255 - abs(255 - sr - br);
  12777. dg = 255 - abs(255 - sg - bg);
  12778. db = 255 - abs(255 - sb - bb);
  12779. }
  12780. };
  12781. var nativeModes = this.nativeModes = Base.each([
  12782. 'source-over', 'source-in', 'source-out', 'source-atop',
  12783. 'destination-over', 'destination-in', 'destination-out',
  12784. 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
  12785. ], function(mode) {
  12786. this[mode] = true;
  12787. }, {});
  12788. var ctx = CanvasProvider.getContext(1, 1);
  12789. if (ctx) {
  12790. Base.each(modes, function(func, mode) {
  12791. var darken = mode === 'darken',
  12792. ok = false;
  12793. ctx.save();
  12794. try {
  12795. ctx.fillStyle = darken ? '#300' : '#a00';
  12796. ctx.fillRect(0, 0, 1, 1);
  12797. ctx.globalCompositeOperation = mode;
  12798. if (ctx.globalCompositeOperation === mode) {
  12799. ctx.fillStyle = darken ? '#a00' : '#300';
  12800. ctx.fillRect(0, 0, 1, 1);
  12801. ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken
  12802. ? 170 : 51;
  12803. }
  12804. } catch (e) {}
  12805. ctx.restore();
  12806. nativeModes[mode] = ok;
  12807. });
  12808. CanvasProvider.release(ctx);
  12809. }
  12810. this.process = function(mode, srcContext, dstContext, alpha, offset) {
  12811. var srcCanvas = srcContext.canvas,
  12812. normal = mode === 'normal';
  12813. if (normal || nativeModes[mode]) {
  12814. dstContext.save();
  12815. dstContext.setTransform(1, 0, 0, 1, 0, 0);
  12816. dstContext.globalAlpha = alpha;
  12817. if (!normal)
  12818. dstContext.globalCompositeOperation = mode;
  12819. dstContext.drawImage(srcCanvas, offset.x, offset.y);
  12820. dstContext.restore();
  12821. } else {
  12822. var process = modes[mode];
  12823. if (!process)
  12824. return;
  12825. var dstData = dstContext.getImageData(offset.x, offset.y,
  12826. srcCanvas.width, srcCanvas.height),
  12827. dst = dstData.data,
  12828. src = srcContext.getImageData(0, 0,
  12829. srcCanvas.width, srcCanvas.height).data;
  12830. for (var i = 0, l = dst.length; i < l; i += 4) {
  12831. sr = src[i];
  12832. br = dst[i];
  12833. sg = src[i + 1];
  12834. bg = dst[i + 1];
  12835. sb = src[i + 2];
  12836. bb = dst[i + 2];
  12837. sa = src[i + 3];
  12838. ba = dst[i + 3];
  12839. process();
  12840. var a1 = sa * alpha / 255,
  12841. a2 = 1 - a1;
  12842. dst[i] = a1 * dr + a2 * br;
  12843. dst[i + 1] = a1 * dg + a2 * bg;
  12844. dst[i + 2] = a1 * db + a2 * bb;
  12845. dst[i + 3] = sa * alpha + a2 * ba;
  12846. }
  12847. dstContext.putImageData(dstData, offset.x, offset.y);
  12848. }
  12849. };
  12850. };
  12851. var SvgElement = new function() {
  12852. var svg = 'http://www.w3.org/2000/svg',
  12853. xmlns = 'http://www.w3.org/2000/xmlns',
  12854. xlink = 'http://www.w3.org/1999/xlink',
  12855. attributeNamespace = {
  12856. href: xlink,
  12857. xlink: xmlns,
  12858. xmlns: xmlns + '/',
  12859. 'xmlns:xlink': xmlns + '/'
  12860. };
  12861. function create(tag, attributes, formatter) {
  12862. return set(document.createElementNS(svg, tag), attributes, formatter);
  12863. }
  12864. function get(node, name) {
  12865. var namespace = attributeNamespace[name],
  12866. value = namespace
  12867. ? node.getAttributeNS(namespace, name)
  12868. : node.getAttribute(name);
  12869. return value === 'null' ? null : value;
  12870. }
  12871. function set(node, attributes, formatter) {
  12872. for (var name in attributes) {
  12873. var value = attributes[name],
  12874. namespace = attributeNamespace[name];
  12875. if (typeof value === 'number' && formatter)
  12876. value = formatter.number(value);
  12877. if (namespace) {
  12878. node.setAttributeNS(namespace, name, value);
  12879. } else {
  12880. node.setAttribute(name, value);
  12881. }
  12882. }
  12883. return node;
  12884. }
  12885. return {
  12886. svg: svg,
  12887. xmlns: xmlns,
  12888. xlink: xlink,
  12889. create: create,
  12890. get: get,
  12891. set: set
  12892. };
  12893. };
  12894. var SvgStyles = Base.each({
  12895. fillColor: ['fill', 'color'],
  12896. fillRule: ['fill-rule', 'string'],
  12897. strokeColor: ['stroke', 'color'],
  12898. strokeWidth: ['stroke-width', 'number'],
  12899. strokeCap: ['stroke-linecap', 'string'],
  12900. strokeJoin: ['stroke-linejoin', 'string'],
  12901. strokeScaling: ['vector-effect', 'lookup', {
  12902. true: 'none',
  12903. false: 'non-scaling-stroke'
  12904. }, function(item, value) {
  12905. return !value
  12906. && (item instanceof PathItem
  12907. || item instanceof Shape
  12908. || item instanceof TextItem);
  12909. }],
  12910. miterLimit: ['stroke-miterlimit', 'number'],
  12911. dashArray: ['stroke-dasharray', 'array'],
  12912. dashOffset: ['stroke-dashoffset', 'number'],
  12913. fontFamily: ['font-family', 'string'],
  12914. fontWeight: ['font-weight', 'string'],
  12915. fontSize: ['font-size', 'number'],
  12916. justification: ['text-anchor', 'lookup', {
  12917. left: 'start',
  12918. center: 'middle',
  12919. right: 'end'
  12920. }],
  12921. opacity: ['opacity', 'number'],
  12922. blendMode: ['mix-blend-mode', 'style']
  12923. }, function(entry, key) {
  12924. var part = Base.capitalize(key),
  12925. lookup = entry[2];
  12926. this[key] = {
  12927. type: entry[1],
  12928. property: key,
  12929. attribute: entry[0],
  12930. toSVG: lookup,
  12931. fromSVG: lookup && Base.each(lookup, function(value, name) {
  12932. this[value] = name;
  12933. }, {}),
  12934. exportFilter: entry[3],
  12935. get: 'get' + part,
  12936. set: 'set' + part
  12937. };
  12938. }, {});
  12939. new function() {
  12940. var formatter;
  12941. function getTransform(matrix, coordinates, center) {
  12942. var attrs = new Base(),
  12943. trans = matrix.getTranslation();
  12944. if (coordinates) {
  12945. matrix = matrix._shiftless();
  12946. var point = matrix._inverseTransform(trans);
  12947. attrs[center ? 'cx' : 'x'] = point.x;
  12948. attrs[center ? 'cy' : 'y'] = point.y;
  12949. trans = null;
  12950. }
  12951. if (!matrix.isIdentity()) {
  12952. var decomposed = matrix.decompose();
  12953. if (decomposed) {
  12954. var parts = [],
  12955. angle = decomposed.rotation,
  12956. scale = decomposed.scaling,
  12957. skew = decomposed.skewing;
  12958. if (trans && !trans.isZero())
  12959. parts.push('translate(' + formatter.point(trans) + ')');
  12960. if (angle)
  12961. parts.push('rotate(' + formatter.number(angle) + ')');
  12962. if (!Numerical.isZero(scale.x - 1)
  12963. || !Numerical.isZero(scale.y - 1))
  12964. parts.push('scale(' + formatter.point(scale) +')');
  12965. if (skew.x)
  12966. parts.push('skewX(' + formatter.number(skew.x) + ')');
  12967. if (skew.y)
  12968. parts.push('skewY(' + formatter.number(skew.y) + ')');
  12969. attrs.transform = parts.join(' ');
  12970. } else {
  12971. attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
  12972. }
  12973. }
  12974. return attrs;
  12975. }
  12976. function exportGroup(item, options) {
  12977. var attrs = getTransform(item._matrix),
  12978. children = item._children;
  12979. var node = SvgElement.create('g', attrs, formatter);
  12980. for (var i = 0, l = children.length; i < l; i++) {
  12981. var child = children[i];
  12982. var childNode = exportSVG(child, options);
  12983. if (childNode) {
  12984. if (child.isClipMask()) {
  12985. var clip = SvgElement.create('clipPath');
  12986. clip.appendChild(childNode);
  12987. setDefinition(child, clip, 'clip');
  12988. SvgElement.set(node, {
  12989. 'clip-path': 'url(#' + clip.id + ')'
  12990. });
  12991. } else {
  12992. node.appendChild(childNode);
  12993. }
  12994. }
  12995. }
  12996. return node;
  12997. }
  12998. function exportRaster(item, options) {
  12999. var attrs = getTransform(item._matrix, true),
  13000. size = item.getSize(),
  13001. image = item.getImage();
  13002. attrs.x -= size.width / 2;
  13003. attrs.y -= size.height / 2;
  13004. attrs.width = size.width;
  13005. attrs.height = size.height;
  13006. attrs.href = options.embedImages == false && image && image.src
  13007. || item.toDataURL();
  13008. return SvgElement.create('image', attrs, formatter);
  13009. }
  13010. function exportPath(item, options) {
  13011. var matchShapes = options.matchShapes;
  13012. if (matchShapes) {
  13013. var shape = item.toShape(false);
  13014. if (shape)
  13015. return exportShape(shape, options);
  13016. }
  13017. var segments = item._segments,
  13018. length = segments.length,
  13019. type,
  13020. attrs = getTransform(item._matrix);
  13021. if (matchShapes && length >= 2 && !item.hasHandles()) {
  13022. if (length > 2) {
  13023. type = item._closed ? 'polygon' : 'polyline';
  13024. var parts = [];
  13025. for (var i = 0; i < length; i++) {
  13026. parts.push(formatter.point(segments[i]._point));
  13027. }
  13028. attrs.points = parts.join(' ');
  13029. } else {
  13030. type = 'line';
  13031. var start = segments[0]._point,
  13032. end = segments[1]._point;
  13033. attrs.set({
  13034. x1: start.x,
  13035. y1: start.y,
  13036. x2: end.x,
  13037. y2: end.y
  13038. });
  13039. }
  13040. } else {
  13041. type = 'path';
  13042. attrs.d = item.getPathData(null, options.precision);
  13043. }
  13044. return SvgElement.create(type, attrs, formatter);
  13045. }
  13046. function exportShape(item) {
  13047. var type = item._type,
  13048. radius = item._radius,
  13049. attrs = getTransform(item._matrix, true, type !== 'rectangle');
  13050. if (type === 'rectangle') {
  13051. type = 'rect';
  13052. var size = item._size,
  13053. width = size.width,
  13054. height = size.height;
  13055. attrs.x -= width / 2;
  13056. attrs.y -= height / 2;
  13057. attrs.width = width;
  13058. attrs.height = height;
  13059. if (radius.isZero())
  13060. radius = null;
  13061. }
  13062. if (radius) {
  13063. if (type === 'circle') {
  13064. attrs.r = radius;
  13065. } else {
  13066. attrs.rx = radius.width;
  13067. attrs.ry = radius.height;
  13068. }
  13069. }
  13070. return SvgElement.create(type, attrs, formatter);
  13071. }
  13072. function exportCompoundPath(item, options) {
  13073. var attrs = getTransform(item._matrix);
  13074. var data = item.getPathData(null, options.precision);
  13075. if (data)
  13076. attrs.d = data;
  13077. return SvgElement.create('path', attrs, formatter);
  13078. }
  13079. function exportSymbolItem(item, options) {
  13080. var attrs = getTransform(item._matrix, true),
  13081. definition = item._definition,
  13082. node = getDefinition(definition, 'symbol'),
  13083. definitionItem = definition._item,
  13084. bounds = definitionItem.getBounds();
  13085. if (!node) {
  13086. node = SvgElement.create('symbol', {
  13087. viewBox: formatter.rectangle(bounds)
  13088. });
  13089. node.appendChild(exportSVG(definitionItem, options));
  13090. setDefinition(definition, node, 'symbol');
  13091. }
  13092. attrs.href = '#' + node.id;
  13093. attrs.x += bounds.x;
  13094. attrs.y += bounds.y;
  13095. attrs.width = bounds.width;
  13096. attrs.height = bounds.height;
  13097. attrs.overflow = 'visible';
  13098. return SvgElement.create('use', attrs, formatter);
  13099. }
  13100. function exportGradient(color) {
  13101. var gradientNode = getDefinition(color, 'color');
  13102. if (!gradientNode) {
  13103. var gradient = color.getGradient(),
  13104. radial = gradient._radial,
  13105. origin = color.getOrigin(),
  13106. destination = color.getDestination(),
  13107. attrs;
  13108. if (radial) {
  13109. attrs = {
  13110. cx: origin.x,
  13111. cy: origin.y,
  13112. r: origin.getDistance(destination)
  13113. };
  13114. var highlight = color.getHighlight();
  13115. if (highlight) {
  13116. attrs.fx = highlight.x;
  13117. attrs.fy = highlight.y;
  13118. }
  13119. } else {
  13120. attrs = {
  13121. x1: origin.x,
  13122. y1: origin.y,
  13123. x2: destination.x,
  13124. y2: destination.y
  13125. };
  13126. }
  13127. attrs.gradientUnits = 'userSpaceOnUse';
  13128. gradientNode = SvgElement.create((radial ? 'radial' : 'linear')
  13129. + 'Gradient', attrs, formatter);
  13130. var stops = gradient._stops;
  13131. for (var i = 0, l = stops.length; i < l; i++) {
  13132. var stop = stops[i],
  13133. stopColor = stop._color,
  13134. alpha = stopColor.getAlpha(),
  13135. offset = stop._offset;
  13136. attrs = {
  13137. offset: offset == null ? i / (l - 1) : offset
  13138. };
  13139. if (stopColor)
  13140. attrs['stop-color'] = stopColor.toCSS(true);
  13141. if (alpha < 1)
  13142. attrs['stop-opacity'] = alpha;
  13143. gradientNode.appendChild(
  13144. SvgElement.create('stop', attrs, formatter));
  13145. }
  13146. setDefinition(color, gradientNode, 'color');
  13147. }
  13148. return 'url(#' + gradientNode.id + ')';
  13149. }
  13150. function exportText(item) {
  13151. var node = SvgElement.create('text', getTransform(item._matrix, true),
  13152. formatter);
  13153. node.textContent = item._content;
  13154. return node;
  13155. }
  13156. var exporters = {
  13157. Group: exportGroup,
  13158. Layer: exportGroup,
  13159. Raster: exportRaster,
  13160. Path: exportPath,
  13161. Shape: exportShape,
  13162. CompoundPath: exportCompoundPath,
  13163. SymbolItem: exportSymbolItem,
  13164. PointText: exportText
  13165. };
  13166. function applyStyle(item, node, isRoot) {
  13167. var attrs = {},
  13168. parent = !isRoot && item.getParent(),
  13169. style = [];
  13170. if (item._name != null)
  13171. attrs.id = item._name;
  13172. Base.each(SvgStyles, function(entry) {
  13173. var get = entry.get,
  13174. type = entry.type,
  13175. value = item[get]();
  13176. if (entry.exportFilter
  13177. ? entry.exportFilter(item, value)
  13178. : !parent || !Base.equals(parent[get](), value)) {
  13179. if (type === 'color' && value != null) {
  13180. var alpha = value.getAlpha();
  13181. if (alpha < 1)
  13182. attrs[entry.attribute + '-opacity'] = alpha;
  13183. }
  13184. if (type === 'style') {
  13185. style.push(entry.attribute + ': ' + value);
  13186. } else {
  13187. attrs[entry.attribute] = value == null ? 'none'
  13188. : type === 'color' ? value.gradient
  13189. ? exportGradient(value, item)
  13190. : value.toCSS(true)
  13191. : type === 'array' ? value.join(',')
  13192. : type === 'lookup' ? entry.toSVG[value]
  13193. : value;
  13194. }
  13195. }
  13196. });
  13197. if (style.length)
  13198. attrs.style = style.join(';');
  13199. if (attrs.opacity === 1)
  13200. delete attrs.opacity;
  13201. if (!item._visible)
  13202. attrs.visibility = 'hidden';
  13203. return SvgElement.set(node, attrs, formatter);
  13204. }
  13205. var definitions;
  13206. function getDefinition(item, type) {
  13207. if (!definitions)
  13208. definitions = { ids: {}, svgs: {} };
  13209. return item && definitions.svgs[type + '-'
  13210. + (item._id || item.__id || (item.__id = UID.get('svg')))];
  13211. }
  13212. function setDefinition(item, node, type) {
  13213. if (!definitions)
  13214. getDefinition();
  13215. var typeId = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
  13216. node.id = type + '-' + typeId;
  13217. definitions.svgs[type + '-' + (item._id || item.__id)] = node;
  13218. }
  13219. function exportDefinitions(node, options) {
  13220. var svg = node,
  13221. defs = null;
  13222. if (definitions) {
  13223. svg = node.nodeName.toLowerCase() === 'svg' && node;
  13224. for (var i in definitions.svgs) {
  13225. if (!defs) {
  13226. if (!svg) {
  13227. svg = SvgElement.create('svg');
  13228. svg.appendChild(node);
  13229. }
  13230. defs = svg.insertBefore(SvgElement.create('defs'),
  13231. svg.firstChild);
  13232. }
  13233. defs.appendChild(definitions.svgs[i]);
  13234. }
  13235. definitions = null;
  13236. }
  13237. return options.asString
  13238. ? new self.XMLSerializer().serializeToString(svg)
  13239. : svg;
  13240. }
  13241. function exportSVG(item, options, isRoot) {
  13242. var exporter = exporters[item._class],
  13243. node = exporter && exporter(item, options);
  13244. if (node) {
  13245. var onExport = options.onExport;
  13246. if (onExport)
  13247. node = onExport(item, node, options) || node;
  13248. var data = JSON.stringify(item._data);
  13249. if (data && data !== '{}' && data !== 'null')
  13250. node.setAttribute('data-paper-data', data);
  13251. }
  13252. return node && applyStyle(item, node, isRoot);
  13253. }
  13254. function setOptions(options) {
  13255. if (!options)
  13256. options = {};
  13257. formatter = new Formatter(options.precision);
  13258. return options;
  13259. }
  13260. Item.inject({
  13261. exportSVG: function(options) {
  13262. options = setOptions(options);
  13263. return exportDefinitions(exportSVG(this, options, true), options);
  13264. }
  13265. });
  13266. Project.inject({
  13267. exportSVG: function(options) {
  13268. options = setOptions(options);
  13269. var children = this._children,
  13270. view = this.getView(),
  13271. bounds = Base.pick(options.bounds, 'view'),
  13272. mx = options.matrix || bounds === 'view' && view._matrix,
  13273. matrix = mx && Matrix.read([mx]),
  13274. rect = bounds === 'view'
  13275. ? new Rectangle([0, 0], view.getViewSize())
  13276. : bounds === 'content'
  13277. ? Item._getBounds(children, matrix, { stroke: true })
  13278. .rect
  13279. : Rectangle.read([bounds], 0, { readNull: true }),
  13280. attrs = {
  13281. version: '1.1',
  13282. xmlns: SvgElement.svg,
  13283. 'xmlns:xlink': SvgElement.xlink,
  13284. };
  13285. if (rect) {
  13286. attrs.width = rect.width;
  13287. attrs.height = rect.height;
  13288. if (rect.x || rect.y)
  13289. attrs.viewBox = formatter.rectangle(rect);
  13290. }
  13291. var node = SvgElement.create('svg', attrs, formatter),
  13292. parent = node;
  13293. if (matrix && !matrix.isIdentity()) {
  13294. parent = node.appendChild(SvgElement.create('g',
  13295. getTransform(matrix), formatter));
  13296. }
  13297. for (var i = 0, l = children.length; i < l; i++) {
  13298. parent.appendChild(exportSVG(children[i], options, true));
  13299. }
  13300. return exportDefinitions(node, options);
  13301. }
  13302. });
  13303. };
  13304. new function() {
  13305. var definitions = {},
  13306. rootSize;
  13307. function getValue(node, name, isString, allowNull, allowPercent) {
  13308. var value = SvgElement.get(node, name),
  13309. res = value == null
  13310. ? allowNull
  13311. ? null
  13312. : isString ? '' : 0
  13313. : isString
  13314. ? value
  13315. : parseFloat(value);
  13316. return /%\s*$/.test(value)
  13317. ? (res / 100) * (allowPercent ? 1
  13318. : rootSize[/x|^width/.test(name) ? 'width' : 'height'])
  13319. : res;
  13320. }
  13321. function getPoint(node, x, y, allowNull, allowPercent) {
  13322. x = getValue(node, x || 'x', false, allowNull, allowPercent);
  13323. y = getValue(node, y || 'y', false, allowNull, allowPercent);
  13324. return allowNull && (x == null || y == null) ? null
  13325. : new Point(x, y);
  13326. }
  13327. function getSize(node, w, h, allowNull, allowPercent) {
  13328. w = getValue(node, w || 'width', false, allowNull, allowPercent);
  13329. h = getValue(node, h || 'height', false, allowNull, allowPercent);
  13330. return allowNull && (w == null || h == null) ? null
  13331. : new Size(w, h);
  13332. }
  13333. function convertValue(value, type, lookup) {
  13334. return value === 'none' ? null
  13335. : type === 'number' ? parseFloat(value)
  13336. : type === 'array' ?
  13337. value ? value.split(/[\s,]+/g).map(parseFloat) : []
  13338. : type === 'color' ? getDefinition(value) || value
  13339. : type === 'lookup' ? lookup[value]
  13340. : value;
  13341. }
  13342. function importGroup(node, type, options, isRoot) {
  13343. var nodes = node.childNodes,
  13344. isClip = type === 'clippath',
  13345. isDefs = type === 'defs',
  13346. item = new Group(),
  13347. project = item._project,
  13348. currentStyle = project._currentStyle,
  13349. children = [];
  13350. if (!isClip && !isDefs) {
  13351. item = applyAttributes(item, node, isRoot);
  13352. project._currentStyle = item._style.clone();
  13353. }
  13354. if (isRoot) {
  13355. var defs = node.querySelectorAll('defs');
  13356. for (var i = 0, l = defs.length; i < l; i++) {
  13357. importNode(defs[i], options, false);
  13358. }
  13359. }
  13360. for (var i = 0, l = nodes.length; i < l; i++) {
  13361. var childNode = nodes[i],
  13362. child;
  13363. if (childNode.nodeType === 1
  13364. && !/^defs$/i.test(childNode.nodeName)
  13365. && (child = importNode(childNode, options, false))
  13366. && !(child instanceof SymbolDefinition))
  13367. children.push(child);
  13368. }
  13369. item.addChildren(children);
  13370. if (isClip)
  13371. item = applyAttributes(item.reduce(), node, isRoot);
  13372. project._currentStyle = currentStyle;
  13373. if (isClip || isDefs) {
  13374. item.remove();
  13375. item = null;
  13376. }
  13377. return item;
  13378. }
  13379. function importPoly(node, type) {
  13380. var coords = node.getAttribute('points').match(
  13381. /[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g),
  13382. points = [];
  13383. for (var i = 0, l = coords.length; i < l; i += 2)
  13384. points.push(new Point(
  13385. parseFloat(coords[i]),
  13386. parseFloat(coords[i + 1])));
  13387. var path = new Path(points);
  13388. if (type === 'polygon')
  13389. path.closePath();
  13390. return path;
  13391. }
  13392. function importPath(node) {
  13393. return PathItem.create(node.getAttribute('d'));
  13394. }
  13395. function importGradient(node, type) {
  13396. var id = (getValue(node, 'href', true) || '').substring(1),
  13397. radial = type === 'radialgradient',
  13398. gradient;
  13399. if (id) {
  13400. gradient = definitions[id].getGradient();
  13401. if (gradient._radial ^ radial) {
  13402. gradient = gradient.clone();
  13403. gradient._radial = radial;
  13404. }
  13405. } else {
  13406. var nodes = node.childNodes,
  13407. stops = [];
  13408. for (var i = 0, l = nodes.length; i < l; i++) {
  13409. var child = nodes[i];
  13410. if (child.nodeType === 1)
  13411. stops.push(applyAttributes(new GradientStop(), child));
  13412. }
  13413. gradient = new Gradient(stops, radial);
  13414. }
  13415. var origin, destination, highlight,
  13416. scaleToBounds = getValue(node, 'gradientUnits', true) !==
  13417. 'userSpaceOnUse';
  13418. if (radial) {
  13419. origin = getPoint(node, 'cx', 'cy', false, scaleToBounds);
  13420. destination = origin.add(
  13421. getValue(node, 'r', false, false, scaleToBounds), 0);
  13422. highlight = getPoint(node, 'fx', 'fy', true, scaleToBounds);
  13423. } else {
  13424. origin = getPoint(node, 'x1', 'y1', false, scaleToBounds);
  13425. destination = getPoint(node, 'x2', 'y2', false, scaleToBounds);
  13426. }
  13427. var color = applyAttributes(
  13428. new Color(gradient, origin, destination, highlight), node);
  13429. color._scaleToBounds = scaleToBounds;
  13430. return null;
  13431. }
  13432. var importers = {
  13433. '#document': function (node, type, options, isRoot) {
  13434. var nodes = node.childNodes;
  13435. for (var i = 0, l = nodes.length; i < l; i++) {
  13436. var child = nodes[i];
  13437. if (child.nodeType === 1)
  13438. return importNode(child, options, isRoot);
  13439. }
  13440. },
  13441. g: importGroup,
  13442. svg: importGroup,
  13443. clippath: importGroup,
  13444. polygon: importPoly,
  13445. polyline: importPoly,
  13446. path: importPath,
  13447. lineargradient: importGradient,
  13448. radialgradient: importGradient,
  13449. image: function (node) {
  13450. var raster = new Raster(getValue(node, 'href', true));
  13451. raster.on('load', function() {
  13452. var size = getSize(node);
  13453. this.setSize(size);
  13454. var center = getPoint(node).add(size.divide(2));
  13455. this._matrix.append(new Matrix().translate(center));
  13456. });
  13457. return raster;
  13458. },
  13459. symbol: function(node, type, options, isRoot) {
  13460. return new SymbolDefinition(
  13461. importGroup(node, type, options, isRoot), true);
  13462. },
  13463. defs: importGroup,
  13464. use: function(node) {
  13465. var id = (getValue(node, 'href', true) || '').substring(1),
  13466. definition = definitions[id],
  13467. point = getPoint(node);
  13468. return definition
  13469. ? definition instanceof SymbolDefinition
  13470. ? definition.place(point)
  13471. : definition.clone().translate(point)
  13472. : null;
  13473. },
  13474. circle: function(node) {
  13475. return new Shape.Circle(
  13476. getPoint(node, 'cx', 'cy'),
  13477. getValue(node, 'r'));
  13478. },
  13479. ellipse: function(node) {
  13480. return new Shape.Ellipse({
  13481. center: getPoint(node, 'cx', 'cy'),
  13482. radius: getSize(node, 'rx', 'ry')
  13483. });
  13484. },
  13485. rect: function(node) {
  13486. return new Shape.Rectangle(new Rectangle(
  13487. getPoint(node),
  13488. getSize(node)
  13489. ), getSize(node, 'rx', 'ry'));
  13490. },
  13491. line: function(node) {
  13492. return new Path.Line(
  13493. getPoint(node, 'x1', 'y1'),
  13494. getPoint(node, 'x2', 'y2'));
  13495. },
  13496. text: function(node) {
  13497. var text = new PointText(getPoint(node).add(
  13498. getPoint(node, 'dx', 'dy')));
  13499. text.setContent(node.textContent.trim() || '');
  13500. return text;
  13501. }
  13502. };
  13503. function applyTransform(item, value, name, node) {
  13504. if (item.transform) {
  13505. var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
  13506. matrix = new Matrix();
  13507. for (var i = 0, l = transforms.length; i < l; i++) {
  13508. var transform = transforms[i];
  13509. if (!transform)
  13510. break;
  13511. var parts = transform.split(/\(\s*/),
  13512. command = parts[0],
  13513. v = parts[1].split(/[\s,]+/g);
  13514. for (var j = 0, m = v.length; j < m; j++)
  13515. v[j] = parseFloat(v[j]);
  13516. switch (command) {
  13517. case 'matrix':
  13518. matrix.append(
  13519. new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
  13520. break;
  13521. case 'rotate':
  13522. matrix.rotate(v[0], v[1] || 0, v[2] || 0);
  13523. break;
  13524. case 'translate':
  13525. matrix.translate(v[0], v[1] || 0);
  13526. break;
  13527. case 'scale':
  13528. matrix.scale(v);
  13529. break;
  13530. case 'skewX':
  13531. matrix.skew(v[0], 0);
  13532. break;
  13533. case 'skewY':
  13534. matrix.skew(0, v[0]);
  13535. break;
  13536. }
  13537. }
  13538. item.transform(matrix);
  13539. }
  13540. }
  13541. function applyOpacity(item, value, name) {
  13542. var key = name === 'fill-opacity' ? 'getFillColor' : 'getStrokeColor',
  13543. color = item[key] && item[key]();
  13544. if (color)
  13545. color.setAlpha(parseFloat(value));
  13546. }
  13547. var attributes = Base.set(Base.each(SvgStyles, function(entry) {
  13548. this[entry.attribute] = function(item, value) {
  13549. if (item[entry.set]) {
  13550. item[entry.set](convertValue(value, entry.type, entry.fromSVG));
  13551. if (entry.type === 'color') {
  13552. var color = item[entry.get]();
  13553. if (color) {
  13554. if (color._scaleToBounds) {
  13555. var bounds = item.getBounds();
  13556. color.transform(new Matrix()
  13557. .translate(bounds.getPoint())
  13558. .scale(bounds.getSize()));
  13559. }
  13560. }
  13561. }
  13562. }
  13563. };
  13564. }, {}), {
  13565. id: function(item, value) {
  13566. definitions[value] = item;
  13567. if (item.setName)
  13568. item.setName(value);
  13569. },
  13570. 'clip-path': function(item, value) {
  13571. var clip = getDefinition(value);
  13572. if (clip) {
  13573. clip = clip.clone();
  13574. clip.setClipMask(true);
  13575. if (item instanceof Group) {
  13576. item.insertChild(0, clip);
  13577. } else {
  13578. return new Group(clip, item);
  13579. }
  13580. }
  13581. },
  13582. gradientTransform: applyTransform,
  13583. transform: applyTransform,
  13584. 'fill-opacity': applyOpacity,
  13585. 'stroke-opacity': applyOpacity,
  13586. visibility: function(item, value) {
  13587. if (item.setVisible)
  13588. item.setVisible(value === 'visible');
  13589. },
  13590. display: function(item, value) {
  13591. if (item.setVisible)
  13592. item.setVisible(value !== null);
  13593. },
  13594. 'stop-color': function(item, value) {
  13595. if (item.setColor)
  13596. item.setColor(value);
  13597. },
  13598. 'stop-opacity': function(item, value) {
  13599. if (item._color)
  13600. item._color.setAlpha(parseFloat(value));
  13601. },
  13602. offset: function(item, value) {
  13603. if (item.setOffset) {
  13604. var percent = value.match(/(.*)%$/);
  13605. item.setOffset(percent ? percent[1] / 100 : parseFloat(value));
  13606. }
  13607. },
  13608. viewBox: function(item, value, name, node, styles) {
  13609. var rect = new Rectangle(convertValue(value, 'array')),
  13610. size = getSize(node, null, null, true),
  13611. group,
  13612. matrix;
  13613. if (item instanceof Group) {
  13614. var scale = size ? size.divide(rect.getSize()) : 1,
  13615. matrix = new Matrix().scale(scale)
  13616. .translate(rect.getPoint().negate());
  13617. group = item;
  13618. } else if (item instanceof SymbolDefinition) {
  13619. if (size)
  13620. rect.setSize(size);
  13621. group = item._item;
  13622. }
  13623. if (group) {
  13624. if (getAttribute(node, 'overflow', styles) !== 'visible') {
  13625. var clip = new Shape.Rectangle(rect);
  13626. clip.setClipMask(true);
  13627. group.addChild(clip);
  13628. }
  13629. if (matrix)
  13630. group.transform(matrix);
  13631. }
  13632. }
  13633. });
  13634. function getAttribute(node, name, styles) {
  13635. var attr = node.attributes[name],
  13636. value = attr && attr.value;
  13637. if (!value && node.style) {
  13638. var style = Base.camelize(name);
  13639. value = node.style[style];
  13640. if (!value && styles.node[style] !== styles.parent[style])
  13641. value = styles.node[style];
  13642. }
  13643. return !value ? undefined
  13644. : value === 'none' ? null
  13645. : value;
  13646. }
  13647. function applyAttributes(item, node, isRoot) {
  13648. var parent = node.parentNode,
  13649. styles = {
  13650. node: DomElement.getStyles(node) || {},
  13651. parent: !isRoot && !/^defs$/i.test(parent.tagName)
  13652. && DomElement.getStyles(parent) || {}
  13653. };
  13654. Base.each(attributes, function(apply, name) {
  13655. var value = getAttribute(node, name, styles);
  13656. item = value !== undefined
  13657. && apply(item, value, name, node, styles) || item;
  13658. });
  13659. return item;
  13660. }
  13661. function getDefinition(value) {
  13662. var match = value && value.match(/\((?:["'#]*)([^"')]+)/),
  13663. name = match && match[1],
  13664. res = name && definitions[window
  13665. ? name.replace(window.location.href.split('#')[0] + '#', '')
  13666. : name];
  13667. if (res && res._scaleToBounds) {
  13668. res = res.clone();
  13669. res._scaleToBounds = true;
  13670. }
  13671. return res;
  13672. }
  13673. function importNode(node, options, isRoot) {
  13674. var type = node.nodeName.toLowerCase(),
  13675. isElement = type !== '#document',
  13676. body = document.body,
  13677. container,
  13678. parent,
  13679. next;
  13680. if (isRoot && isElement) {
  13681. rootSize = paper.getView().getSize();
  13682. rootSize = getSize(node, null, null, true) || rootSize;
  13683. container = SvgElement.create('svg', {
  13684. style: 'stroke-width: 1px; stroke-miterlimit: 10'
  13685. });
  13686. parent = node.parentNode;
  13687. next = node.nextSibling;
  13688. container.appendChild(node);
  13689. body.appendChild(container);
  13690. }
  13691. var settings = paper.settings,
  13692. applyMatrix = settings.applyMatrix,
  13693. insertItems = settings.insertItems;
  13694. settings.applyMatrix = false;
  13695. settings.insertItems = false;
  13696. var importer = importers[type],
  13697. item = importer && importer(node, type, options, isRoot) || null;
  13698. settings.insertItems = insertItems;
  13699. settings.applyMatrix = applyMatrix;
  13700. if (item) {
  13701. if (isElement && !(item instanceof Group))
  13702. item = applyAttributes(item, node, isRoot);
  13703. var onImport = options.onImport,
  13704. data = isElement && node.getAttribute('data-paper-data');
  13705. if (onImport)
  13706. item = onImport(node, item, options) || item;
  13707. if (options.expandShapes && item instanceof Shape) {
  13708. item.remove();
  13709. item = item.toPath();
  13710. }
  13711. if (data)
  13712. item._data = JSON.parse(data);
  13713. }
  13714. if (container) {
  13715. body.removeChild(container);
  13716. if (parent) {
  13717. if (next) {
  13718. parent.insertBefore(node, next);
  13719. } else {
  13720. parent.appendChild(node);
  13721. }
  13722. }
  13723. }
  13724. if (isRoot) {
  13725. definitions = {};
  13726. if (item && Base.pick(options.applyMatrix, applyMatrix))
  13727. item.matrix.apply(true, true);
  13728. }
  13729. return item;
  13730. }
  13731. function importSVG(source, options, owner) {
  13732. if (!source)
  13733. return null;
  13734. options = typeof options === 'function' ? { onLoad: options }
  13735. : options || {};
  13736. var scope = paper,
  13737. item = null;
  13738. function onLoad(svg) {
  13739. try {
  13740. var node = typeof svg === 'object' ? svg : new self.DOMParser()
  13741. .parseFromString(svg, 'image/svg+xml');
  13742. if (!node.nodeName) {
  13743. node = null;
  13744. throw new Error('Unsupported SVG source: ' + source);
  13745. }
  13746. paper = scope;
  13747. item = importNode(node, options, true);
  13748. if (!options || options.insert !== false) {
  13749. owner._insertItem(undefined, item);
  13750. }
  13751. var onLoad = options.onLoad;
  13752. if (onLoad)
  13753. onLoad(item, svg);
  13754. } catch (e) {
  13755. onError(e);
  13756. }
  13757. }
  13758. function onError(message, status) {
  13759. var onError = options.onError;
  13760. if (onError) {
  13761. onError(message, status);
  13762. } else {
  13763. throw new Error(message);
  13764. }
  13765. }
  13766. if (typeof source === 'string' && !/^.*</.test(source)) {
  13767. var node = document.getElementById(source);
  13768. if (node) {
  13769. onLoad(node);
  13770. } else {
  13771. Http.request({
  13772. url: source,
  13773. async: true,
  13774. onLoad: onLoad,
  13775. onError: onError
  13776. });
  13777. }
  13778. } else if (typeof File !== 'undefined' && source instanceof File) {
  13779. var reader = new FileReader();
  13780. reader.onload = function() {
  13781. onLoad(reader.result);
  13782. };
  13783. reader.onerror = function() {
  13784. onError(reader.error);
  13785. };
  13786. return reader.readAsText(source);
  13787. } else {
  13788. onLoad(source);
  13789. }
  13790. return item;
  13791. }
  13792. Item.inject({
  13793. importSVG: function(node, options) {
  13794. return importSVG(node, options, this);
  13795. }
  13796. });
  13797. Project.inject({
  13798. importSVG: function(node, options) {
  13799. this.activate();
  13800. return importSVG(node, options, this);
  13801. }
  13802. });
  13803. };
  13804. Base.exports.PaperScript = function() {
  13805. var global = this,
  13806. acorn = global.acorn;
  13807. if (!acorn && typeof require !== 'undefined') {
  13808. try { acorn = require('acorn'); } catch(e) {}
  13809. }
  13810. if (!acorn) {
  13811. var exports, module;
  13812. acorn = exports = module = {};
  13813. (function(root, mod) {
  13814. if (typeof exports == "object" && typeof module == "object") return mod(exports);
  13815. if (typeof define == "function" && define.amd) return define(["exports"], mod);
  13816. mod(root.acorn || (root.acorn = {}));
  13817. })(this, function(exports) {
  13818. "use strict";
  13819. exports.version = "0.5.0";
  13820. var options, input, inputLen, sourceFile;
  13821. exports.parse = function(inpt, opts) {
  13822. input = String(inpt); inputLen = input.length;
  13823. setOptions(opts);
  13824. initTokenState();
  13825. return parseTopLevel(options.program);
  13826. };
  13827. var defaultOptions = exports.defaultOptions = {
  13828. ecmaVersion: 5,
  13829. strictSemicolons: false,
  13830. allowTrailingCommas: true,
  13831. forbidReserved: false,
  13832. allowReturnOutsideFunction: false,
  13833. locations: false,
  13834. onComment: null,
  13835. ranges: false,
  13836. program: null,
  13837. sourceFile: null,
  13838. directSourceFile: null
  13839. };
  13840. function setOptions(opts) {
  13841. options = opts || {};
  13842. for (var opt in defaultOptions) if (!Object.prototype.hasOwnProperty.call(options, opt))
  13843. options[opt] = defaultOptions[opt];
  13844. sourceFile = options.sourceFile || null;
  13845. }
  13846. var getLineInfo = exports.getLineInfo = function(input, offset) {
  13847. for (var line = 1, cur = 0;;) {
  13848. lineBreak.lastIndex = cur;
  13849. var match = lineBreak.exec(input);
  13850. if (match && match.index < offset) {
  13851. ++line;
  13852. cur = match.index + match[0].length;
  13853. } else break;
  13854. }
  13855. return {line: line, column: offset - cur};
  13856. };
  13857. exports.tokenize = function(inpt, opts) {
  13858. input = String(inpt); inputLen = input.length;
  13859. setOptions(opts);
  13860. initTokenState();
  13861. var t = {};
  13862. function getToken(forceRegexp) {
  13863. lastEnd = tokEnd;
  13864. readToken(forceRegexp);
  13865. t.start = tokStart; t.end = tokEnd;
  13866. t.startLoc = tokStartLoc; t.endLoc = tokEndLoc;
  13867. t.type = tokType; t.value = tokVal;
  13868. return t;
  13869. }
  13870. getToken.jumpTo = function(pos, reAllowed) {
  13871. tokPos = pos;
  13872. if (options.locations) {
  13873. tokCurLine = 1;
  13874. tokLineStart = lineBreak.lastIndex = 0;
  13875. var match;
  13876. while ((match = lineBreak.exec(input)) && match.index < pos) {
  13877. ++tokCurLine;
  13878. tokLineStart = match.index + match[0].length;
  13879. }
  13880. }
  13881. tokRegexpAllowed = reAllowed;
  13882. skipSpace();
  13883. };
  13884. return getToken;
  13885. };
  13886. var tokPos;
  13887. var tokStart, tokEnd;
  13888. var tokStartLoc, tokEndLoc;
  13889. var tokType, tokVal;
  13890. var tokRegexpAllowed;
  13891. var tokCurLine, tokLineStart;
  13892. var lastStart, lastEnd, lastEndLoc;
  13893. var inFunction, labels, strict;
  13894. function raise(pos, message) {
  13895. var loc = getLineInfo(input, pos);
  13896. message += " (" + loc.line + ":" + loc.column + ")";
  13897. var err = new SyntaxError(message);
  13898. err.pos = pos; err.loc = loc; err.raisedAt = tokPos;
  13899. throw err;
  13900. }
  13901. var empty = [];
  13902. var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"};
  13903. var _name = {type: "name"}, _eof = {type: "eof"};
  13904. var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"};
  13905. var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"};
  13906. var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true};
  13907. var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"};
  13908. var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"};
  13909. var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"};
  13910. var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true};
  13911. var _this = {keyword: "this"};
  13912. var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true};
  13913. var _false = {keyword: "false", atomValue: false};
  13914. var _in = {keyword: "in", binop: 7, beforeExpr: true};
  13915. var keywordTypes = {"break": _break, "case": _case, "catch": _catch,
  13916. "continue": _continue, "debugger": _debugger, "default": _default,
  13917. "do": _do, "else": _else, "finally": _finally, "for": _for,
  13918. "function": _function, "if": _if, "return": _return, "switch": _switch,
  13919. "throw": _throw, "try": _try, "var": _var, "while": _while, "with": _with,
  13920. "null": _null, "true": _true, "false": _false, "new": _new, "in": _in,
  13921. "instanceof": {keyword: "instanceof", binop: 7, beforeExpr: true}, "this": _this,
  13922. "typeof": {keyword: "typeof", prefix: true, beforeExpr: true},
  13923. "void": {keyword: "void", prefix: true, beforeExpr: true},
  13924. "delete": {keyword: "delete", prefix: true, beforeExpr: true}};
  13925. var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true};
  13926. var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"};
  13927. var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true};
  13928. var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true};
  13929. var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true};
  13930. var _assign = {isAssign: true, beforeExpr: true};
  13931. var _incDec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true};
  13932. var _logicalOR = {binop: 1, beforeExpr: true};
  13933. var _logicalAND = {binop: 2, beforeExpr: true};
  13934. var _bitwiseOR = {binop: 3, beforeExpr: true};
  13935. var _bitwiseXOR = {binop: 4, beforeExpr: true};
  13936. var _bitwiseAND = {binop: 5, beforeExpr: true};
  13937. var _equality = {binop: 6, beforeExpr: true};
  13938. var _relational = {binop: 7, beforeExpr: true};
  13939. var _bitShift = {binop: 8, beforeExpr: true};
  13940. var _plusMin = {binop: 9, prefix: true, beforeExpr: true};
  13941. var _multiplyModulo = {binop: 10, beforeExpr: true};
  13942. exports.tokTypes = {bracketL: _bracketL, bracketR: _bracketR, braceL: _braceL, braceR: _braceR,
  13943. parenL: _parenL, parenR: _parenR, comma: _comma, semi: _semi, colon: _colon,
  13944. dot: _dot, question: _question, slash: _slash, eq: _eq, name: _name, eof: _eof,
  13945. num: _num, regexp: _regexp, string: _string};
  13946. for (var kw in keywordTypes) exports.tokTypes["_" + kw] = keywordTypes[kw];
  13947. function makePredicate(words) {
  13948. words = words.split(" ");
  13949. var f = "", cats = [];
  13950. out: for (var i = 0; i < words.length; ++i) {
  13951. for (var j = 0; j < cats.length; ++j)
  13952. if (cats[j][0].length == words[i].length) {
  13953. cats[j].push(words[i]);
  13954. continue out;
  13955. }
  13956. cats.push([words[i]]);
  13957. }
  13958. function compareTo(arr) {
  13959. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  13960. f += "switch(str){";
  13961. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  13962. f += "return true}return false;";
  13963. }
  13964. if (cats.length > 3) {
  13965. cats.sort(function(a, b) {return b.length - a.length;});
  13966. f += "switch(str.length){";
  13967. for (var i = 0; i < cats.length; ++i) {
  13968. var cat = cats[i];
  13969. f += "case " + cat[0].length + ":";
  13970. compareTo(cat);
  13971. }
  13972. f += "}";
  13973. } else {
  13974. compareTo(words);
  13975. }
  13976. return new Function("str", f);
  13977. }
  13978. var isReservedWord3 = makePredicate("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");
  13979. var isReservedWord5 = makePredicate("class enum extends super const export import");
  13980. var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield");
  13981. var isStrictBadIdWord = makePredicate("eval arguments");
  13982. var isKeyword = makePredicate("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");
  13983. var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  13984. var nonASCIIidentifierStartChars = "\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";
  13985. var nonASCIIidentifierChars = "\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";
  13986. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  13987. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  13988. var newline = /[\n\r\u2028\u2029]/;
  13989. var lineBreak = /\r\n|[\n\r\u2028\u2029]/g;
  13990. var isIdentifierStart = exports.isIdentifierStart = function(code) {
  13991. if (code < 65) return code === 36;
  13992. if (code < 91) return true;
  13993. if (code < 97) return code === 95;
  13994. if (code < 123)return true;
  13995. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  13996. };
  13997. var isIdentifierChar = exports.isIdentifierChar = function(code) {
  13998. if (code < 48) return code === 36;
  13999. if (code < 58) return true;
  14000. if (code < 65) return false;
  14001. if (code < 91) return true;
  14002. if (code < 97) return code === 95;
  14003. if (code < 123)return true;
  14004. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  14005. };
  14006. function line_loc_t() {
  14007. this.line = tokCurLine;
  14008. this.column = tokPos - tokLineStart;
  14009. }
  14010. function initTokenState() {
  14011. tokCurLine = 1;
  14012. tokPos = tokLineStart = 0;
  14013. tokRegexpAllowed = true;
  14014. skipSpace();
  14015. }
  14016. function finishToken(type, val) {
  14017. tokEnd = tokPos;
  14018. if (options.locations) tokEndLoc = new line_loc_t;
  14019. tokType = type;
  14020. skipSpace();
  14021. tokVal = val;
  14022. tokRegexpAllowed = type.beforeExpr;
  14023. }
  14024. function skipBlockComment() {
  14025. var startLoc = options.onComment && options.locations && new line_loc_t;
  14026. var start = tokPos, end = input.indexOf("*/", tokPos += 2);
  14027. if (end === -1) raise(tokPos - 2, "Unterminated comment");
  14028. tokPos = end + 2;
  14029. if (options.locations) {
  14030. lineBreak.lastIndex = start;
  14031. var match;
  14032. while ((match = lineBreak.exec(input)) && match.index < tokPos) {
  14033. ++tokCurLine;
  14034. tokLineStart = match.index + match[0].length;
  14035. }
  14036. }
  14037. if (options.onComment)
  14038. options.onComment(true, input.slice(start + 2, end), start, tokPos,
  14039. startLoc, options.locations && new line_loc_t);
  14040. }
  14041. function skipLineComment() {
  14042. var start = tokPos;
  14043. var startLoc = options.onComment && options.locations && new line_loc_t;
  14044. var ch = input.charCodeAt(tokPos+=2);
  14045. while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
  14046. ++tokPos;
  14047. ch = input.charCodeAt(tokPos);
  14048. }
  14049. if (options.onComment)
  14050. options.onComment(false, input.slice(start + 2, tokPos), start, tokPos,
  14051. startLoc, options.locations && new line_loc_t);
  14052. }
  14053. function skipSpace() {
  14054. while (tokPos < inputLen) {
  14055. var ch = input.charCodeAt(tokPos);
  14056. if (ch === 32) {
  14057. ++tokPos;
  14058. } else if (ch === 13) {
  14059. ++tokPos;
  14060. var next = input.charCodeAt(tokPos);
  14061. if (next === 10) {
  14062. ++tokPos;
  14063. }
  14064. if (options.locations) {
  14065. ++tokCurLine;
  14066. tokLineStart = tokPos;
  14067. }
  14068. } else if (ch === 10 || ch === 8232 || ch === 8233) {
  14069. ++tokPos;
  14070. if (options.locations) {
  14071. ++tokCurLine;
  14072. tokLineStart = tokPos;
  14073. }
  14074. } else if (ch > 8 && ch < 14) {
  14075. ++tokPos;
  14076. } else if (ch === 47) {
  14077. var next = input.charCodeAt(tokPos + 1);
  14078. if (next === 42) {
  14079. skipBlockComment();
  14080. } else if (next === 47) {
  14081. skipLineComment();
  14082. } else break;
  14083. } else if (ch === 160) {
  14084. ++tokPos;
  14085. } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  14086. ++tokPos;
  14087. } else {
  14088. break;
  14089. }
  14090. }
  14091. }
  14092. function readToken_dot() {
  14093. var next = input.charCodeAt(tokPos + 1);
  14094. if (next >= 48 && next <= 57) return readNumber(true);
  14095. ++tokPos;
  14096. return finishToken(_dot);
  14097. }
  14098. function readToken_slash() {
  14099. var next = input.charCodeAt(tokPos + 1);
  14100. if (tokRegexpAllowed) {++tokPos; return readRegexp();}
  14101. if (next === 61) return finishOp(_assign, 2);
  14102. return finishOp(_slash, 1);
  14103. }
  14104. function readToken_mult_modulo() {
  14105. var next = input.charCodeAt(tokPos + 1);
  14106. if (next === 61) return finishOp(_assign, 2);
  14107. return finishOp(_multiplyModulo, 1);
  14108. }
  14109. function readToken_pipe_amp(code) {
  14110. var next = input.charCodeAt(tokPos + 1);
  14111. if (next === code) return finishOp(code === 124 ? _logicalOR : _logicalAND, 2);
  14112. if (next === 61) return finishOp(_assign, 2);
  14113. return finishOp(code === 124 ? _bitwiseOR : _bitwiseAND, 1);
  14114. }
  14115. function readToken_caret() {
  14116. var next = input.charCodeAt(tokPos + 1);
  14117. if (next === 61) return finishOp(_assign, 2);
  14118. return finishOp(_bitwiseXOR, 1);
  14119. }
  14120. function readToken_plus_min(code) {
  14121. var next = input.charCodeAt(tokPos + 1);
  14122. if (next === code) {
  14123. if (next == 45 && input.charCodeAt(tokPos + 2) == 62 &&
  14124. newline.test(input.slice(lastEnd, tokPos))) {
  14125. tokPos += 3;
  14126. skipLineComment();
  14127. skipSpace();
  14128. return readToken();
  14129. }
  14130. return finishOp(_incDec, 2);
  14131. }
  14132. if (next === 61) return finishOp(_assign, 2);
  14133. return finishOp(_plusMin, 1);
  14134. }
  14135. function readToken_lt_gt(code) {
  14136. var next = input.charCodeAt(tokPos + 1);
  14137. var size = 1;
  14138. if (next === code) {
  14139. size = code === 62 && input.charCodeAt(tokPos + 2) === 62 ? 3 : 2;
  14140. if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1);
  14141. return finishOp(_bitShift, size);
  14142. }
  14143. if (next == 33 && code == 60 && input.charCodeAt(tokPos + 2) == 45 &&
  14144. input.charCodeAt(tokPos + 3) == 45) {
  14145. tokPos += 4;
  14146. skipLineComment();
  14147. skipSpace();
  14148. return readToken();
  14149. }
  14150. if (next === 61)
  14151. size = input.charCodeAt(tokPos + 2) === 61 ? 3 : 2;
  14152. return finishOp(_relational, size);
  14153. }
  14154. function readToken_eq_excl(code) {
  14155. var next = input.charCodeAt(tokPos + 1);
  14156. if (next === 61) return finishOp(_equality, input.charCodeAt(tokPos + 2) === 61 ? 3 : 2);
  14157. return finishOp(code === 61 ? _eq : _prefix, 1);
  14158. }
  14159. function getTokenFromCode(code) {
  14160. switch(code) {
  14161. case 46:
  14162. return readToken_dot();
  14163. case 40: ++tokPos; return finishToken(_parenL);
  14164. case 41: ++tokPos; return finishToken(_parenR);
  14165. case 59: ++tokPos; return finishToken(_semi);
  14166. case 44: ++tokPos; return finishToken(_comma);
  14167. case 91: ++tokPos; return finishToken(_bracketL);
  14168. case 93: ++tokPos; return finishToken(_bracketR);
  14169. case 123: ++tokPos; return finishToken(_braceL);
  14170. case 125: ++tokPos; return finishToken(_braceR);
  14171. case 58: ++tokPos; return finishToken(_colon);
  14172. case 63: ++tokPos; return finishToken(_question);
  14173. case 48:
  14174. var next = input.charCodeAt(tokPos + 1);
  14175. if (next === 120 || next === 88) return readHexNumber();
  14176. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57:
  14177. return readNumber(false);
  14178. case 34: case 39:
  14179. return readString(code);
  14180. case 47:
  14181. return readToken_slash(code);
  14182. case 37: case 42:
  14183. return readToken_mult_modulo();
  14184. case 124: case 38:
  14185. return readToken_pipe_amp(code);
  14186. case 94:
  14187. return readToken_caret();
  14188. case 43: case 45:
  14189. return readToken_plus_min(code);
  14190. case 60: case 62:
  14191. return readToken_lt_gt(code);
  14192. case 61: case 33:
  14193. return readToken_eq_excl(code);
  14194. case 126:
  14195. return finishOp(_prefix, 1);
  14196. }
  14197. return false;
  14198. }
  14199. function readToken(forceRegexp) {
  14200. if (!forceRegexp) tokStart = tokPos;
  14201. else tokPos = tokStart + 1;
  14202. if (options.locations) tokStartLoc = new line_loc_t;
  14203. if (forceRegexp) return readRegexp();
  14204. if (tokPos >= inputLen) return finishToken(_eof);
  14205. var code = input.charCodeAt(tokPos);
  14206. if (isIdentifierStart(code) || code === 92 ) return readWord();
  14207. var tok = getTokenFromCode(code);
  14208. if (tok === false) {
  14209. var ch = String.fromCharCode(code);
  14210. if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord();
  14211. raise(tokPos, "Unexpected character '" + ch + "'");
  14212. }
  14213. return tok;
  14214. }
  14215. function finishOp(type, size) {
  14216. var str = input.slice(tokPos, tokPos + size);
  14217. tokPos += size;
  14218. finishToken(type, str);
  14219. }
  14220. function readRegexp() {
  14221. var content = "", escaped, inClass, start = tokPos;
  14222. for (;;) {
  14223. if (tokPos >= inputLen) raise(start, "Unterminated regular expression");
  14224. var ch = input.charAt(tokPos);
  14225. if (newline.test(ch)) raise(start, "Unterminated regular expression");
  14226. if (!escaped) {
  14227. if (ch === "[") inClass = true;
  14228. else if (ch === "]" && inClass) inClass = false;
  14229. else if (ch === "/" && !inClass) break;
  14230. escaped = ch === "\\";
  14231. } else escaped = false;
  14232. ++tokPos;
  14233. }
  14234. var content = input.slice(start, tokPos);
  14235. ++tokPos;
  14236. var mods = readWord1();
  14237. if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regexp flag");
  14238. try {
  14239. var value = new RegExp(content, mods);
  14240. } catch (e) {
  14241. if (e instanceof SyntaxError) raise(start, e.message);
  14242. raise(e);
  14243. }
  14244. return finishToken(_regexp, value);
  14245. }
  14246. function readInt(radix, len) {
  14247. var start = tokPos, total = 0;
  14248. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  14249. var code = input.charCodeAt(tokPos), val;
  14250. if (code >= 97) val = code - 97 + 10;
  14251. else if (code >= 65) val = code - 65 + 10;
  14252. else if (code >= 48 && code <= 57) val = code - 48;
  14253. else val = Infinity;
  14254. if (val >= radix) break;
  14255. ++tokPos;
  14256. total = total * radix + val;
  14257. }
  14258. if (tokPos === start || len != null && tokPos - start !== len) return null;
  14259. return total;
  14260. }
  14261. function readHexNumber() {
  14262. tokPos += 2;
  14263. var val = readInt(16);
  14264. if (val == null) raise(tokStart + 2, "Expected hexadecimal number");
  14265. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  14266. return finishToken(_num, val);
  14267. }
  14268. function readNumber(startsWithDot) {
  14269. var start = tokPos, isFloat = false, octal = input.charCodeAt(tokPos) === 48;
  14270. if (!startsWithDot && readInt(10) === null) raise(start, "Invalid number");
  14271. if (input.charCodeAt(tokPos) === 46) {
  14272. ++tokPos;
  14273. readInt(10);
  14274. isFloat = true;
  14275. }
  14276. var next = input.charCodeAt(tokPos);
  14277. if (next === 69 || next === 101) {
  14278. next = input.charCodeAt(++tokPos);
  14279. if (next === 43 || next === 45) ++tokPos;
  14280. if (readInt(10) === null) raise(start, "Invalid number");
  14281. isFloat = true;
  14282. }
  14283. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  14284. var str = input.slice(start, tokPos), val;
  14285. if (isFloat) val = parseFloat(str);
  14286. else if (!octal || str.length === 1) val = parseInt(str, 10);
  14287. else if (/[89]/.test(str) || strict) raise(start, "Invalid number");
  14288. else val = parseInt(str, 8);
  14289. return finishToken(_num, val);
  14290. }
  14291. function readString(quote) {
  14292. tokPos++;
  14293. var out = "";
  14294. for (;;) {
  14295. if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant");
  14296. var ch = input.charCodeAt(tokPos);
  14297. if (ch === quote) {
  14298. ++tokPos;
  14299. return finishToken(_string, out);
  14300. }
  14301. if (ch === 92) {
  14302. ch = input.charCodeAt(++tokPos);
  14303. var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));
  14304. if (octal) octal = octal[0];
  14305. while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1);
  14306. if (octal === "0") octal = null;
  14307. ++tokPos;
  14308. if (octal) {
  14309. if (strict) raise(tokPos - 2, "Octal literal in strict mode");
  14310. out += String.fromCharCode(parseInt(octal, 8));
  14311. tokPos += octal.length - 1;
  14312. } else {
  14313. switch (ch) {
  14314. case 110: out += "\n"; break;
  14315. case 114: out += "\r"; break;
  14316. case 120: out += String.fromCharCode(readHexChar(2)); break;
  14317. case 117: out += String.fromCharCode(readHexChar(4)); break;
  14318. case 85: out += String.fromCharCode(readHexChar(8)); break;
  14319. case 116: out += "\t"; break;
  14320. case 98: out += "\b"; break;
  14321. case 118: out += "\u000b"; break;
  14322. case 102: out += "\f"; break;
  14323. case 48: out += "\0"; break;
  14324. case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos;
  14325. case 10:
  14326. if (options.locations) { tokLineStart = tokPos; ++tokCurLine; }
  14327. break;
  14328. default: out += String.fromCharCode(ch); break;
  14329. }
  14330. }
  14331. } else {
  14332. if (ch === 13 || ch === 10 || ch === 8232 || ch === 8233) raise(tokStart, "Unterminated string constant");
  14333. out += String.fromCharCode(ch);
  14334. ++tokPos;
  14335. }
  14336. }
  14337. }
  14338. function readHexChar(len) {
  14339. var n = readInt(16, len);
  14340. if (n === null) raise(tokStart, "Bad character escape sequence");
  14341. return n;
  14342. }
  14343. var containsEsc;
  14344. function readWord1() {
  14345. containsEsc = false;
  14346. var word, first = true, start = tokPos;
  14347. for (;;) {
  14348. var ch = input.charCodeAt(tokPos);
  14349. if (isIdentifierChar(ch)) {
  14350. if (containsEsc) word += input.charAt(tokPos);
  14351. ++tokPos;
  14352. } else if (ch === 92) {
  14353. if (!containsEsc) word = input.slice(start, tokPos);
  14354. containsEsc = true;
  14355. if (input.charCodeAt(++tokPos) != 117)
  14356. raise(tokPos, "Expecting Unicode escape sequence \\uXXXX");
  14357. ++tokPos;
  14358. var esc = readHexChar(4);
  14359. var escStr = String.fromCharCode(esc);
  14360. if (!escStr) raise(tokPos - 1, "Invalid Unicode escape");
  14361. if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc)))
  14362. raise(tokPos - 4, "Invalid Unicode escape");
  14363. word += escStr;
  14364. } else {
  14365. break;
  14366. }
  14367. first = false;
  14368. }
  14369. return containsEsc ? word : input.slice(start, tokPos);
  14370. }
  14371. function readWord() {
  14372. var word = readWord1();
  14373. var type = _name;
  14374. if (!containsEsc && isKeyword(word))
  14375. type = keywordTypes[word];
  14376. return finishToken(type, word);
  14377. }
  14378. function next() {
  14379. lastStart = tokStart;
  14380. lastEnd = tokEnd;
  14381. lastEndLoc = tokEndLoc;
  14382. readToken();
  14383. }
  14384. function setStrict(strct) {
  14385. strict = strct;
  14386. tokPos = tokStart;
  14387. if (options.locations) {
  14388. while (tokPos < tokLineStart) {
  14389. tokLineStart = input.lastIndexOf("\n", tokLineStart - 2) + 1;
  14390. --tokCurLine;
  14391. }
  14392. }
  14393. skipSpace();
  14394. readToken();
  14395. }
  14396. function node_t() {
  14397. this.type = null;
  14398. this.start = tokStart;
  14399. this.end = null;
  14400. }
  14401. function node_loc_t() {
  14402. this.start = tokStartLoc;
  14403. this.end = null;
  14404. if (sourceFile !== null) this.source = sourceFile;
  14405. }
  14406. function startNode() {
  14407. var node = new node_t();
  14408. if (options.locations)
  14409. node.loc = new node_loc_t();
  14410. if (options.directSourceFile)
  14411. node.sourceFile = options.directSourceFile;
  14412. if (options.ranges)
  14413. node.range = [tokStart, 0];
  14414. return node;
  14415. }
  14416. function startNodeFrom(other) {
  14417. var node = new node_t();
  14418. node.start = other.start;
  14419. if (options.locations) {
  14420. node.loc = new node_loc_t();
  14421. node.loc.start = other.loc.start;
  14422. }
  14423. if (options.ranges)
  14424. node.range = [other.range[0], 0];
  14425. return node;
  14426. }
  14427. function finishNode(node, type) {
  14428. node.type = type;
  14429. node.end = lastEnd;
  14430. if (options.locations)
  14431. node.loc.end = lastEndLoc;
  14432. if (options.ranges)
  14433. node.range[1] = lastEnd;
  14434. return node;
  14435. }
  14436. function isUseStrict(stmt) {
  14437. return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
  14438. stmt.expression.type === "Literal" && stmt.expression.value === "use strict";
  14439. }
  14440. function eat(type) {
  14441. if (tokType === type) {
  14442. next();
  14443. return true;
  14444. }
  14445. }
  14446. function canInsertSemicolon() {
  14447. return !options.strictSemicolons &&
  14448. (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart)));
  14449. }
  14450. function semicolon() {
  14451. if (!eat(_semi) && !canInsertSemicolon()) unexpected();
  14452. }
  14453. function expect(type) {
  14454. if (tokType === type) next();
  14455. else unexpected();
  14456. }
  14457. function unexpected() {
  14458. raise(tokStart, "Unexpected token");
  14459. }
  14460. function checkLVal(expr) {
  14461. if (expr.type !== "Identifier" && expr.type !== "MemberExpression")
  14462. raise(expr.start, "Assigning to rvalue");
  14463. if (strict && expr.type === "Identifier" && isStrictBadIdWord(expr.name))
  14464. raise(expr.start, "Assigning to " + expr.name + " in strict mode");
  14465. }
  14466. function parseTopLevel(program) {
  14467. lastStart = lastEnd = tokPos;
  14468. if (options.locations) lastEndLoc = new line_loc_t;
  14469. inFunction = strict = null;
  14470. labels = [];
  14471. readToken();
  14472. var node = program || startNode(), first = true;
  14473. if (!program) node.body = [];
  14474. while (tokType !== _eof) {
  14475. var stmt = parseStatement();
  14476. node.body.push(stmt);
  14477. if (first && isUseStrict(stmt)) setStrict(true);
  14478. first = false;
  14479. }
  14480. return finishNode(node, "Program");
  14481. }
  14482. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  14483. function parseStatement() {
  14484. if (tokType === _slash || tokType === _assign && tokVal == "/=")
  14485. readToken(true);
  14486. var starttype = tokType, node = startNode();
  14487. switch (starttype) {
  14488. case _break: case _continue:
  14489. next();
  14490. var isBreak = starttype === _break;
  14491. if (eat(_semi) || canInsertSemicolon()) node.label = null;
  14492. else if (tokType !== _name) unexpected();
  14493. else {
  14494. node.label = parseIdent();
  14495. semicolon();
  14496. }
  14497. for (var i = 0; i < labels.length; ++i) {
  14498. var lab = labels[i];
  14499. if (node.label == null || lab.name === node.label.name) {
  14500. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  14501. if (node.label && isBreak) break;
  14502. }
  14503. }
  14504. if (i === labels.length) raise(node.start, "Unsyntactic " + starttype.keyword);
  14505. return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  14506. case _debugger:
  14507. next();
  14508. semicolon();
  14509. return finishNode(node, "DebuggerStatement");
  14510. case _do:
  14511. next();
  14512. labels.push(loopLabel);
  14513. node.body = parseStatement();
  14514. labels.pop();
  14515. expect(_while);
  14516. node.test = parseParenExpression();
  14517. semicolon();
  14518. return finishNode(node, "DoWhileStatement");
  14519. case _for:
  14520. next();
  14521. labels.push(loopLabel);
  14522. expect(_parenL);
  14523. if (tokType === _semi) return parseFor(node, null);
  14524. if (tokType === _var) {
  14525. var init = startNode();
  14526. next();
  14527. parseVar(init, true);
  14528. finishNode(init, "VariableDeclaration");
  14529. if (init.declarations.length === 1 && eat(_in))
  14530. return parseForIn(node, init);
  14531. return parseFor(node, init);
  14532. }
  14533. var init = parseExpression(false, true);
  14534. if (eat(_in)) {checkLVal(init); return parseForIn(node, init);}
  14535. return parseFor(node, init);
  14536. case _function:
  14537. next();
  14538. return parseFunction(node, true);
  14539. case _if:
  14540. next();
  14541. node.test = parseParenExpression();
  14542. node.consequent = parseStatement();
  14543. node.alternate = eat(_else) ? parseStatement() : null;
  14544. return finishNode(node, "IfStatement");
  14545. case _return:
  14546. if (!inFunction && !options.allowReturnOutsideFunction)
  14547. raise(tokStart, "'return' outside of function");
  14548. next();
  14549. if (eat(_semi) || canInsertSemicolon()) node.argument = null;
  14550. else { node.argument = parseExpression(); semicolon(); }
  14551. return finishNode(node, "ReturnStatement");
  14552. case _switch:
  14553. next();
  14554. node.discriminant = parseParenExpression();
  14555. node.cases = [];
  14556. expect(_braceL);
  14557. labels.push(switchLabel);
  14558. for (var cur, sawDefault; tokType != _braceR;) {
  14559. if (tokType === _case || tokType === _default) {
  14560. var isCase = tokType === _case;
  14561. if (cur) finishNode(cur, "SwitchCase");
  14562. node.cases.push(cur = startNode());
  14563. cur.consequent = [];
  14564. next();
  14565. if (isCase) cur.test = parseExpression();
  14566. else {
  14567. if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true;
  14568. cur.test = null;
  14569. }
  14570. expect(_colon);
  14571. } else {
  14572. if (!cur) unexpected();
  14573. cur.consequent.push(parseStatement());
  14574. }
  14575. }
  14576. if (cur) finishNode(cur, "SwitchCase");
  14577. next();
  14578. labels.pop();
  14579. return finishNode(node, "SwitchStatement");
  14580. case _throw:
  14581. next();
  14582. if (newline.test(input.slice(lastEnd, tokStart)))
  14583. raise(lastEnd, "Illegal newline after throw");
  14584. node.argument = parseExpression();
  14585. semicolon();
  14586. return finishNode(node, "ThrowStatement");
  14587. case _try:
  14588. next();
  14589. node.block = parseBlock();
  14590. node.handler = null;
  14591. if (tokType === _catch) {
  14592. var clause = startNode();
  14593. next();
  14594. expect(_parenL);
  14595. clause.param = parseIdent();
  14596. if (strict && isStrictBadIdWord(clause.param.name))
  14597. raise(clause.param.start, "Binding " + clause.param.name + " in strict mode");
  14598. expect(_parenR);
  14599. clause.guard = null;
  14600. clause.body = parseBlock();
  14601. node.handler = finishNode(clause, "CatchClause");
  14602. }
  14603. node.guardedHandlers = empty;
  14604. node.finalizer = eat(_finally) ? parseBlock() : null;
  14605. if (!node.handler && !node.finalizer)
  14606. raise(node.start, "Missing catch or finally clause");
  14607. return finishNode(node, "TryStatement");
  14608. case _var:
  14609. next();
  14610. parseVar(node);
  14611. semicolon();
  14612. return finishNode(node, "VariableDeclaration");
  14613. case _while:
  14614. next();
  14615. node.test = parseParenExpression();
  14616. labels.push(loopLabel);
  14617. node.body = parseStatement();
  14618. labels.pop();
  14619. return finishNode(node, "WhileStatement");
  14620. case _with:
  14621. if (strict) raise(tokStart, "'with' in strict mode");
  14622. next();
  14623. node.object = parseParenExpression();
  14624. node.body = parseStatement();
  14625. return finishNode(node, "WithStatement");
  14626. case _braceL:
  14627. return parseBlock();
  14628. case _semi:
  14629. next();
  14630. return finishNode(node, "EmptyStatement");
  14631. default:
  14632. var maybeName = tokVal, expr = parseExpression();
  14633. if (starttype === _name && expr.type === "Identifier" && eat(_colon)) {
  14634. for (var i = 0; i < labels.length; ++i)
  14635. if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared");
  14636. var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null;
  14637. labels.push({name: maybeName, kind: kind});
  14638. node.body = parseStatement();
  14639. labels.pop();
  14640. node.label = expr;
  14641. return finishNode(node, "LabeledStatement");
  14642. } else {
  14643. node.expression = expr;
  14644. semicolon();
  14645. return finishNode(node, "ExpressionStatement");
  14646. }
  14647. }
  14648. }
  14649. function parseParenExpression() {
  14650. expect(_parenL);
  14651. var val = parseExpression();
  14652. expect(_parenR);
  14653. return val;
  14654. }
  14655. function parseBlock(allowStrict) {
  14656. var node = startNode(), first = true, strict = false, oldStrict;
  14657. node.body = [];
  14658. expect(_braceL);
  14659. while (!eat(_braceR)) {
  14660. var stmt = parseStatement();
  14661. node.body.push(stmt);
  14662. if (first && allowStrict && isUseStrict(stmt)) {
  14663. oldStrict = strict;
  14664. setStrict(strict = true);
  14665. }
  14666. first = false;
  14667. }
  14668. if (strict && !oldStrict) setStrict(false);
  14669. return finishNode(node, "BlockStatement");
  14670. }
  14671. function parseFor(node, init) {
  14672. node.init = init;
  14673. expect(_semi);
  14674. node.test = tokType === _semi ? null : parseExpression();
  14675. expect(_semi);
  14676. node.update = tokType === _parenR ? null : parseExpression();
  14677. expect(_parenR);
  14678. node.body = parseStatement();
  14679. labels.pop();
  14680. return finishNode(node, "ForStatement");
  14681. }
  14682. function parseForIn(node, init) {
  14683. node.left = init;
  14684. node.right = parseExpression();
  14685. expect(_parenR);
  14686. node.body = parseStatement();
  14687. labels.pop();
  14688. return finishNode(node, "ForInStatement");
  14689. }
  14690. function parseVar(node, noIn) {
  14691. node.declarations = [];
  14692. node.kind = "var";
  14693. for (;;) {
  14694. var decl = startNode();
  14695. decl.id = parseIdent();
  14696. if (strict && isStrictBadIdWord(decl.id.name))
  14697. raise(decl.id.start, "Binding " + decl.id.name + " in strict mode");
  14698. decl.init = eat(_eq) ? parseExpression(true, noIn) : null;
  14699. node.declarations.push(finishNode(decl, "VariableDeclarator"));
  14700. if (!eat(_comma)) break;
  14701. }
  14702. return node;
  14703. }
  14704. function parseExpression(noComma, noIn) {
  14705. var expr = parseMaybeAssign(noIn);
  14706. if (!noComma && tokType === _comma) {
  14707. var node = startNodeFrom(expr);
  14708. node.expressions = [expr];
  14709. while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn));
  14710. return finishNode(node, "SequenceExpression");
  14711. }
  14712. return expr;
  14713. }
  14714. function parseMaybeAssign(noIn) {
  14715. var left = parseMaybeConditional(noIn);
  14716. if (tokType.isAssign) {
  14717. var node = startNodeFrom(left);
  14718. node.operator = tokVal;
  14719. node.left = left;
  14720. next();
  14721. node.right = parseMaybeAssign(noIn);
  14722. checkLVal(left);
  14723. return finishNode(node, "AssignmentExpression");
  14724. }
  14725. return left;
  14726. }
  14727. function parseMaybeConditional(noIn) {
  14728. var expr = parseExprOps(noIn);
  14729. if (eat(_question)) {
  14730. var node = startNodeFrom(expr);
  14731. node.test = expr;
  14732. node.consequent = parseExpression(true);
  14733. expect(_colon);
  14734. node.alternate = parseExpression(true, noIn);
  14735. return finishNode(node, "ConditionalExpression");
  14736. }
  14737. return expr;
  14738. }
  14739. function parseExprOps(noIn) {
  14740. return parseExprOp(parseMaybeUnary(), -1, noIn);
  14741. }
  14742. function parseExprOp(left, minPrec, noIn) {
  14743. var prec = tokType.binop;
  14744. if (prec != null && (!noIn || tokType !== _in)) {
  14745. if (prec > minPrec) {
  14746. var node = startNodeFrom(left);
  14747. node.left = left;
  14748. node.operator = tokVal;
  14749. var op = tokType;
  14750. next();
  14751. node.right = parseExprOp(parseMaybeUnary(), prec, noIn);
  14752. var exprNode = finishNode(node, (op === _logicalOR || op === _logicalAND) ? "LogicalExpression" : "BinaryExpression");
  14753. return parseExprOp(exprNode, minPrec, noIn);
  14754. }
  14755. }
  14756. return left;
  14757. }
  14758. function parseMaybeUnary() {
  14759. if (tokType.prefix) {
  14760. var node = startNode(), update = tokType.isUpdate;
  14761. node.operator = tokVal;
  14762. node.prefix = true;
  14763. tokRegexpAllowed = true;
  14764. next();
  14765. node.argument = parseMaybeUnary();
  14766. if (update) checkLVal(node.argument);
  14767. else if (strict && node.operator === "delete" &&
  14768. node.argument.type === "Identifier")
  14769. raise(node.start, "Deleting local variable in strict mode");
  14770. return finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  14771. }
  14772. var expr = parseExprSubscripts();
  14773. while (tokType.postfix && !canInsertSemicolon()) {
  14774. var node = startNodeFrom(expr);
  14775. node.operator = tokVal;
  14776. node.prefix = false;
  14777. node.argument = expr;
  14778. checkLVal(expr);
  14779. next();
  14780. expr = finishNode(node, "UpdateExpression");
  14781. }
  14782. return expr;
  14783. }
  14784. function parseExprSubscripts() {
  14785. return parseSubscripts(parseExprAtom());
  14786. }
  14787. function parseSubscripts(base, noCalls) {
  14788. if (eat(_dot)) {
  14789. var node = startNodeFrom(base);
  14790. node.object = base;
  14791. node.property = parseIdent(true);
  14792. node.computed = false;
  14793. return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
  14794. } else if (eat(_bracketL)) {
  14795. var node = startNodeFrom(base);
  14796. node.object = base;
  14797. node.property = parseExpression();
  14798. node.computed = true;
  14799. expect(_bracketR);
  14800. return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
  14801. } else if (!noCalls && eat(_parenL)) {
  14802. var node = startNodeFrom(base);
  14803. node.callee = base;
  14804. node.arguments = parseExprList(_parenR, false);
  14805. return parseSubscripts(finishNode(node, "CallExpression"), noCalls);
  14806. } else return base;
  14807. }
  14808. function parseExprAtom() {
  14809. switch (tokType) {
  14810. case _this:
  14811. var node = startNode();
  14812. next();
  14813. return finishNode(node, "ThisExpression");
  14814. case _name:
  14815. return parseIdent();
  14816. case _num: case _string: case _regexp:
  14817. var node = startNode();
  14818. node.value = tokVal;
  14819. node.raw = input.slice(tokStart, tokEnd);
  14820. next();
  14821. return finishNode(node, "Literal");
  14822. case _null: case _true: case _false:
  14823. var node = startNode();
  14824. node.value = tokType.atomValue;
  14825. node.raw = tokType.keyword;
  14826. next();
  14827. return finishNode(node, "Literal");
  14828. case _parenL:
  14829. var tokStartLoc1 = tokStartLoc, tokStart1 = tokStart;
  14830. next();
  14831. var val = parseExpression();
  14832. val.start = tokStart1;
  14833. val.end = tokEnd;
  14834. if (options.locations) {
  14835. val.loc.start = tokStartLoc1;
  14836. val.loc.end = tokEndLoc;
  14837. }
  14838. if (options.ranges)
  14839. val.range = [tokStart1, tokEnd];
  14840. expect(_parenR);
  14841. return val;
  14842. case _bracketL:
  14843. var node = startNode();
  14844. next();
  14845. node.elements = parseExprList(_bracketR, true, true);
  14846. return finishNode(node, "ArrayExpression");
  14847. case _braceL:
  14848. return parseObj();
  14849. case _function:
  14850. var node = startNode();
  14851. next();
  14852. return parseFunction(node, false);
  14853. case _new:
  14854. return parseNew();
  14855. default:
  14856. unexpected();
  14857. }
  14858. }
  14859. function parseNew() {
  14860. var node = startNode();
  14861. next();
  14862. node.callee = parseSubscripts(parseExprAtom(), true);
  14863. if (eat(_parenL)) node.arguments = parseExprList(_parenR, false);
  14864. else node.arguments = empty;
  14865. return finishNode(node, "NewExpression");
  14866. }
  14867. function parseObj() {
  14868. var node = startNode(), first = true, sawGetSet = false;
  14869. node.properties = [];
  14870. next();
  14871. while (!eat(_braceR)) {
  14872. if (!first) {
  14873. expect(_comma);
  14874. if (options.allowTrailingCommas && eat(_braceR)) break;
  14875. } else first = false;
  14876. var prop = {key: parsePropertyName()}, isGetSet = false, kind;
  14877. if (eat(_colon)) {
  14878. prop.value = parseExpression(true);
  14879. kind = prop.kind = "init";
  14880. } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
  14881. (prop.key.name === "get" || prop.key.name === "set")) {
  14882. isGetSet = sawGetSet = true;
  14883. kind = prop.kind = prop.key.name;
  14884. prop.key = parsePropertyName();
  14885. if (tokType !== _parenL) unexpected();
  14886. prop.value = parseFunction(startNode(), false);
  14887. } else unexpected();
  14888. if (prop.key.type === "Identifier" && (strict || sawGetSet)) {
  14889. for (var i = 0; i < node.properties.length; ++i) {
  14890. var other = node.properties[i];
  14891. if (other.key.name === prop.key.name) {
  14892. var conflict = kind == other.kind || isGetSet && other.kind === "init" ||
  14893. kind === "init" && (other.kind === "get" || other.kind === "set");
  14894. if (conflict && !strict && kind === "init" && other.kind === "init") conflict = false;
  14895. if (conflict) raise(prop.key.start, "Redefinition of property");
  14896. }
  14897. }
  14898. }
  14899. node.properties.push(prop);
  14900. }
  14901. return finishNode(node, "ObjectExpression");
  14902. }
  14903. function parsePropertyName() {
  14904. if (tokType === _num || tokType === _string) return parseExprAtom();
  14905. return parseIdent(true);
  14906. }
  14907. function parseFunction(node, isStatement) {
  14908. if (tokType === _name) node.id = parseIdent();
  14909. else if (isStatement) unexpected();
  14910. else node.id = null;
  14911. node.params = [];
  14912. var first = true;
  14913. expect(_parenL);
  14914. while (!eat(_parenR)) {
  14915. if (!first) expect(_comma); else first = false;
  14916. node.params.push(parseIdent());
  14917. }
  14918. var oldInFunc = inFunction, oldLabels = labels;
  14919. inFunction = true; labels = [];
  14920. node.body = parseBlock(true);
  14921. inFunction = oldInFunc; labels = oldLabels;
  14922. if (strict || node.body.body.length && isUseStrict(node.body.body[0])) {
  14923. for (var i = node.id ? -1 : 0; i < node.params.length; ++i) {
  14924. var id = i < 0 ? node.id : node.params[i];
  14925. if (isStrictReservedWord(id.name) || isStrictBadIdWord(id.name))
  14926. raise(id.start, "Defining '" + id.name + "' in strict mode");
  14927. if (i >= 0) for (var j = 0; j < i; ++j) if (id.name === node.params[j].name)
  14928. raise(id.start, "Argument name clash in strict mode");
  14929. }
  14930. }
  14931. return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  14932. }
  14933. function parseExprList(close, allowTrailingComma, allowEmpty) {
  14934. var elts = [], first = true;
  14935. while (!eat(close)) {
  14936. if (!first) {
  14937. expect(_comma);
  14938. if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break;
  14939. } else first = false;
  14940. if (allowEmpty && tokType === _comma) elts.push(null);
  14941. else elts.push(parseExpression(true));
  14942. }
  14943. return elts;
  14944. }
  14945. function parseIdent(liberal) {
  14946. var node = startNode();
  14947. if (liberal && options.forbidReserved == "everywhere") liberal = false;
  14948. if (tokType === _name) {
  14949. if (!liberal &&
  14950. (options.forbidReserved &&
  14951. (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(tokVal) ||
  14952. strict && isStrictReservedWord(tokVal)) &&
  14953. input.slice(tokStart, tokEnd).indexOf("\\") == -1)
  14954. raise(tokStart, "The keyword '" + tokVal + "' is reserved");
  14955. node.name = tokVal;
  14956. } else if (liberal && tokType.keyword) {
  14957. node.name = tokType.keyword;
  14958. } else {
  14959. unexpected();
  14960. }
  14961. tokRegexpAllowed = false;
  14962. next();
  14963. return finishNode(node, "Identifier");
  14964. }
  14965. });
  14966. if (!acorn.version)
  14967. acorn = null;
  14968. }
  14969. function parse(code, options) {
  14970. return (global.acorn || acorn).parse(code, options);
  14971. }
  14972. var binaryOperators = {
  14973. '+': '__add',
  14974. '-': '__subtract',
  14975. '*': '__multiply',
  14976. '/': '__divide',
  14977. '%': '__modulo',
  14978. '==': '__equals',
  14979. '!=': '__equals'
  14980. };
  14981. var unaryOperators = {
  14982. '-': '__negate',
  14983. '+': '__self'
  14984. };
  14985. var fields = Base.each(
  14986. ['add', 'subtract', 'multiply', 'divide', 'modulo', 'equals', 'negate'],
  14987. function(name) {
  14988. this['__' + name] = '#' + name;
  14989. },
  14990. {
  14991. __self: function() {
  14992. return this;
  14993. }
  14994. }
  14995. );
  14996. Point.inject(fields);
  14997. Size.inject(fields);
  14998. Color.inject(fields);
  14999. function __$__(left, operator, right) {
  15000. var handler = binaryOperators[operator];
  15001. if (left && left[handler]) {
  15002. var res = left[handler](right);
  15003. return operator === '!=' ? !res : res;
  15004. }
  15005. switch (operator) {
  15006. case '+': return left + right;
  15007. case '-': return left - right;
  15008. case '*': return left * right;
  15009. case '/': return left / right;
  15010. case '%': return left % right;
  15011. case '==': return left == right;
  15012. case '!=': return left != right;
  15013. }
  15014. }
  15015. function $__(operator, value) {
  15016. var handler = unaryOperators[operator];
  15017. if (value && value[handler])
  15018. return value[handler]();
  15019. switch (operator) {
  15020. case '+': return +value;
  15021. case '-': return -value;
  15022. }
  15023. }
  15024. function compile(code, options) {
  15025. if (!code)
  15026. return '';
  15027. options = options || {};
  15028. var insertions = [];
  15029. function getOffset(offset) {
  15030. for (var i = 0, l = insertions.length; i < l; i++) {
  15031. var insertion = insertions[i];
  15032. if (insertion[0] >= offset)
  15033. break;
  15034. offset += insertion[1];
  15035. }
  15036. return offset;
  15037. }
  15038. function getCode(node) {
  15039. return code.substring(getOffset(node.range[0]),
  15040. getOffset(node.range[1]));
  15041. }
  15042. function getBetween(left, right) {
  15043. return code.substring(getOffset(left.range[1]),
  15044. getOffset(right.range[0]));
  15045. }
  15046. function replaceCode(node, str) {
  15047. var start = getOffset(node.range[0]),
  15048. end = getOffset(node.range[1]),
  15049. insert = 0;
  15050. for (var i = insertions.length - 1; i >= 0; i--) {
  15051. if (start > insertions[i][0]) {
  15052. insert = i + 1;
  15053. break;
  15054. }
  15055. }
  15056. insertions.splice(insert, 0, [start, str.length - end + start]);
  15057. code = code.substring(0, start) + str + code.substring(end);
  15058. }
  15059. function walkAST(node, parent) {
  15060. if (!node)
  15061. return;
  15062. for (var key in node) {
  15063. if (key === 'range' || key === 'loc')
  15064. continue;
  15065. var value = node[key];
  15066. if (Array.isArray(value)) {
  15067. for (var i = 0, l = value.length; i < l; i++)
  15068. walkAST(value[i], node);
  15069. } else if (value && typeof value === 'object') {
  15070. walkAST(value, node);
  15071. }
  15072. }
  15073. switch (node.type) {
  15074. case 'UnaryExpression':
  15075. if (node.operator in unaryOperators
  15076. && node.argument.type !== 'Literal') {
  15077. var arg = getCode(node.argument);
  15078. replaceCode(node, '$__("' + node.operator + '", '
  15079. + arg + ')');
  15080. }
  15081. break;
  15082. case 'BinaryExpression':
  15083. if (node.operator in binaryOperators
  15084. && node.left.type !== 'Literal') {
  15085. var left = getCode(node.left),
  15086. right = getCode(node.right),
  15087. between = getBetween(node.left, node.right),
  15088. operator = node.operator;
  15089. replaceCode(node, '__$__(' + left + ','
  15090. + between.replace(new RegExp('\\' + operator),
  15091. '"' + operator + '"')
  15092. + ', ' + right + ')');
  15093. }
  15094. break;
  15095. case 'UpdateExpression':
  15096. case 'AssignmentExpression':
  15097. var parentType = parent && parent.type;
  15098. if (!(
  15099. parentType === 'ForStatement'
  15100. || parentType === 'BinaryExpression'
  15101. && /^[=!<>]/.test(parent.operator)
  15102. || parentType === 'MemberExpression' && parent.computed
  15103. )) {
  15104. if (node.type === 'UpdateExpression') {
  15105. var arg = getCode(node.argument),
  15106. exp = '__$__(' + arg + ', "' + node.operator[0]
  15107. + '", 1)',
  15108. str = arg + ' = ' + exp;
  15109. if (!node.prefix
  15110. && (parentType === 'AssignmentExpression'
  15111. || parentType === 'VariableDeclarator')) {
  15112. if (getCode(parent.left || parent.id) === arg)
  15113. str = exp;
  15114. str = arg + '; ' + str;
  15115. }
  15116. replaceCode(node, str);
  15117. } else {
  15118. if (/^.=$/.test(node.operator)
  15119. && node.left.type !== 'Literal') {
  15120. var left = getCode(node.left),
  15121. right = getCode(node.right),
  15122. exp = left + ' = __$__(' + left + ', "'
  15123. + node.operator[0] + '", ' + right + ')';
  15124. replaceCode(node, /^\(.*\)$/.test(getCode(node))
  15125. ? '(' + exp + ')' : exp);
  15126. }
  15127. }
  15128. }
  15129. break;
  15130. case 'ExportDefaultDeclaration':
  15131. replaceCode({
  15132. range: [node.start, node.declaration.start]
  15133. }, 'module.exports = ');
  15134. break;
  15135. case 'ExportNamedDeclaration':
  15136. var declaration = node.declaration;
  15137. var specifiers = node.specifiers;
  15138. if (declaration) {
  15139. var declarations = declaration.declarations;
  15140. if (declarations) {
  15141. declarations.forEach(function(dec) {
  15142. replaceCode(dec, 'module.exports.' + getCode(dec));
  15143. });
  15144. replaceCode({
  15145. range: [
  15146. node.start,
  15147. declaration.start + declaration.kind.length
  15148. ]
  15149. }, '');
  15150. }
  15151. } else if (specifiers) {
  15152. var exports = specifiers.map(function(specifier) {
  15153. var name = getCode(specifier);
  15154. return 'module.exports.' + name + ' = ' + name + '; ';
  15155. }).join('');
  15156. if (exports) {
  15157. replaceCode(node, exports);
  15158. }
  15159. }
  15160. break;
  15161. }
  15162. }
  15163. function encodeVLQ(value) {
  15164. var res = '',
  15165. base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  15166. value = (Math.abs(value) << 1) + (value < 0 ? 1 : 0);
  15167. while (value || !res) {
  15168. var next = value & (32 - 1);
  15169. value >>= 5;
  15170. if (value)
  15171. next |= 32;
  15172. res += base64[next];
  15173. }
  15174. return res;
  15175. }
  15176. var url = options.url || '',
  15177. agent = paper.agent,
  15178. version = agent.versionNumber,
  15179. offsetCode = false,
  15180. sourceMaps = options.sourceMaps,
  15181. source = options.source || code,
  15182. lineBreaks = /\r\n|\n|\r/mg,
  15183. offset = options.offset || 0,
  15184. map;
  15185. if (sourceMaps && (agent.chrome && version >= 30
  15186. || agent.webkit && version >= 537.76
  15187. || agent.firefox && version >= 23
  15188. || agent.node)) {
  15189. if (agent.node) {
  15190. offset -= 2;
  15191. } else if (window && url && !window.location.href.indexOf(url)) {
  15192. var html = document.getElementsByTagName('html')[0].innerHTML;
  15193. offset = html.substr(0, html.indexOf(code) + 1).match(
  15194. lineBreaks).length + 1;
  15195. }
  15196. offsetCode = offset > 0 && !(
  15197. agent.chrome && version >= 36 ||
  15198. agent.safari && version >= 600 ||
  15199. agent.firefox && version >= 40 ||
  15200. agent.node);
  15201. var mappings = ['AA' + encodeVLQ(offsetCode ? 0 : offset) + 'A'];
  15202. mappings.length = (code.match(lineBreaks) || []).length + 1
  15203. + (offsetCode ? offset : 0);
  15204. map = {
  15205. version: 3,
  15206. file: url,
  15207. names:[],
  15208. mappings: mappings.join(';AACA'),
  15209. sourceRoot: '',
  15210. sources: [url],
  15211. sourcesContent: [source]
  15212. };
  15213. }
  15214. walkAST(parse(code, {
  15215. ranges: true,
  15216. preserveParens: true,
  15217. sourceType: 'module'
  15218. }));
  15219. if (map) {
  15220. if (offsetCode) {
  15221. code = new Array(offset + 1).join('\n') + code;
  15222. }
  15223. if (/^(inline|both)$/.test(sourceMaps)) {
  15224. code += "\n//# sourceMappingURL=data:application/json;base64,"
  15225. + self.btoa(unescape(encodeURIComponent(
  15226. JSON.stringify(map))));
  15227. }
  15228. code += "\n//# sourceURL=" + (url || 'paperscript');
  15229. }
  15230. return {
  15231. url: url,
  15232. source: source,
  15233. code: code,
  15234. map: map
  15235. };
  15236. }
  15237. function execute(code, scope, options) {
  15238. paper = scope;
  15239. var view = scope.getView(),
  15240. tool = /\btool\.\w+|\s+on(?:Key|Mouse)(?:Up|Down|Move|Drag)\b/
  15241. .test(code) && !/\bnew\s+Tool\b/.test(code)
  15242. ? new Tool() : null,
  15243. toolHandlers = tool ? tool._events : [],
  15244. handlers = ['onFrame', 'onResize'].concat(toolHandlers),
  15245. params = [],
  15246. args = [],
  15247. func,
  15248. compiled = typeof code === 'object' ? code : compile(code, options);
  15249. code = compiled.code;
  15250. function expose(scope, hidden) {
  15251. for (var key in scope) {
  15252. if ((hidden || !/^_/.test(key)) && new RegExp('([\\b\\s\\W]|^)'
  15253. + key.replace(/\$/g, '\\$') + '\\b').test(code)) {
  15254. params.push(key);
  15255. args.push(scope[key]);
  15256. }
  15257. }
  15258. }
  15259. expose({ __$__: __$__, $__: $__, paper: scope, view: view, tool: tool },
  15260. true);
  15261. expose(scope);
  15262. code = 'var module = { exports: {} }; ' + code;
  15263. var exports = Base.each(handlers, function(key) {
  15264. if (new RegExp('\\s+' + key + '\\b').test(code)) {
  15265. params.push(key);
  15266. this.push('module.exports.' + key + ' = ' + key + ';');
  15267. }
  15268. }, []).join('\n');
  15269. if (exports) {
  15270. code += '\n' + exports;
  15271. }
  15272. code += '\nreturn module.exports;';
  15273. var agent = paper.agent;
  15274. if (document && (agent.chrome
  15275. || agent.firefox && agent.versionNumber < 40)) {
  15276. var script = document.createElement('script'),
  15277. head = document.head || document.getElementsByTagName('head')[0];
  15278. if (agent.firefox)
  15279. code = '\n' + code;
  15280. script.appendChild(document.createTextNode(
  15281. 'document.__paperscript__ = function(' + params + ') {' +
  15282. code +
  15283. '\n}'
  15284. ));
  15285. head.appendChild(script);
  15286. func = document.__paperscript__;
  15287. delete document.__paperscript__;
  15288. head.removeChild(script);
  15289. } else {
  15290. func = Function(params, code);
  15291. }
  15292. var exports = func && func.apply(scope, args);
  15293. var obj = exports || {};
  15294. Base.each(toolHandlers, function(key) {
  15295. var value = obj[key];
  15296. if (value)
  15297. tool[key] = value;
  15298. });
  15299. if (view) {
  15300. if (obj.onResize)
  15301. view.setOnResize(obj.onResize);
  15302. view.emit('resize', {
  15303. size: view.size,
  15304. delta: new Point()
  15305. });
  15306. if (obj.onFrame)
  15307. view.setOnFrame(obj.onFrame);
  15308. view.requestUpdate();
  15309. }
  15310. return exports;
  15311. }
  15312. function loadScript(script) {
  15313. if (/^text\/(?:x-|)paperscript$/.test(script.type)
  15314. && PaperScope.getAttribute(script, 'ignore') !== 'true') {
  15315. var canvasId = PaperScope.getAttribute(script, 'canvas'),
  15316. canvas = document.getElementById(canvasId),
  15317. src = script.src || script.getAttribute('data-src'),
  15318. async = PaperScope.hasAttribute(script, 'async'),
  15319. scopeAttribute = 'data-paper-scope';
  15320. if (!canvas)
  15321. throw new Error('Unable to find canvas with id "'
  15322. + canvasId + '"');
  15323. var scope = PaperScope.get(canvas.getAttribute(scopeAttribute))
  15324. || new PaperScope().setup(canvas);
  15325. canvas.setAttribute(scopeAttribute, scope._id);
  15326. if (src) {
  15327. Http.request({
  15328. url: src,
  15329. async: async,
  15330. mimeType: 'text/plain',
  15331. onLoad: function(code) {
  15332. execute(code, scope, src);
  15333. }
  15334. });
  15335. } else {
  15336. execute(script.innerHTML, scope, script.baseURI);
  15337. }
  15338. script.setAttribute('data-paper-ignore', 'true');
  15339. return scope;
  15340. }
  15341. }
  15342. function loadAll() {
  15343. Base.each(document && document.getElementsByTagName('script'),
  15344. loadScript);
  15345. }
  15346. function load(script) {
  15347. return script ? loadScript(script) : loadAll();
  15348. }
  15349. if (window) {
  15350. if (document.readyState === 'complete') {
  15351. setTimeout(loadAll);
  15352. } else {
  15353. DomEvent.add(window, { load: loadAll });
  15354. }
  15355. }
  15356. return {
  15357. compile: compile,
  15358. execute: execute,
  15359. load: load,
  15360. parse: parse,
  15361. calculateBinary: __$__,
  15362. calculateUnary: $__
  15363. };
  15364. }.call(this);
  15365. var paper = new (PaperScope.inject(Base.exports, {
  15366. Base: Base,
  15367. Numerical: Numerical,
  15368. Key: Key,
  15369. DomEvent: DomEvent,
  15370. DomElement: DomElement,
  15371. document: document,
  15372. window: window,
  15373. Symbol: SymbolDefinition,
  15374. PlacedSymbol: SymbolItem
  15375. }))();
  15376. if (paper.agent.node) {
  15377. require('./node/extend.js')(paper);
  15378. }
  15379. if (typeof define === 'function' && define.amd) {
  15380. define('paper', paper);
  15381. } else if (typeof module === 'object' && module) {
  15382. module.exports = paper;
  15383. }
  15384. return paper;
  15385. }.call(this, typeof self === 'object' ? self : null);