paper-core.js 374 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250
  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. },
  737. install: function(scope) {
  738. var that = this;
  739. Base.each(['project', 'view', 'tool'], function(key) {
  740. Base.define(scope, key, {
  741. configurable: true,
  742. get: function() {
  743. return that[key];
  744. }
  745. });
  746. });
  747. for (var key in this)
  748. if (!/^_/.test(key) && this[key])
  749. scope[key] = this[key];
  750. },
  751. setup: function(element) {
  752. paper = this;
  753. this.project = new Project(element);
  754. return this;
  755. },
  756. createCanvas: function(width, height) {
  757. return CanvasProvider.getCanvas(width, height);
  758. },
  759. activate: function() {
  760. paper = this;
  761. },
  762. clear: function() {
  763. var projects = this.projects,
  764. tools = this.tools;
  765. for (var i = projects.length - 1; i >= 0; i--)
  766. projects[i].remove();
  767. for (var i = tools.length - 1; i >= 0; i--)
  768. tools[i].remove();
  769. },
  770. remove: function() {
  771. this.clear();
  772. delete PaperScope._scopes[this._id];
  773. },
  774. statics: new function() {
  775. function handleAttribute(name) {
  776. name += 'Attribute';
  777. return function(el, attr) {
  778. return el[name](attr) || el[name]('data-paper-' + attr);
  779. };
  780. }
  781. return {
  782. _scopes: {},
  783. _id: 0,
  784. get: function(id) {
  785. return this._scopes[id] || null;
  786. },
  787. getAttribute: handleAttribute('get'),
  788. hasAttribute: handleAttribute('has')
  789. };
  790. }
  791. });
  792. var PaperScopeItem = Base.extend(Emitter, {
  793. initialize: function(activate) {
  794. this._scope = paper;
  795. this._index = this._scope[this._list].push(this) - 1;
  796. if (activate || !this._scope[this._reference])
  797. this.activate();
  798. },
  799. activate: function() {
  800. if (!this._scope)
  801. return false;
  802. var prev = this._scope[this._reference];
  803. if (prev && prev !== this)
  804. prev.emit('deactivate');
  805. this._scope[this._reference] = this;
  806. this.emit('activate', prev);
  807. return true;
  808. },
  809. isActive: function() {
  810. return this._scope[this._reference] === this;
  811. },
  812. remove: function() {
  813. if (this._index == null)
  814. return false;
  815. Base.splice(this._scope[this._list], null, this._index, 1);
  816. if (this._scope[this._reference] == this)
  817. this._scope[this._reference] = null;
  818. this._scope = null;
  819. return true;
  820. },
  821. getView: function() {
  822. return this._scope.getView();
  823. }
  824. });
  825. var Formatter = Base.extend({
  826. initialize: function(precision) {
  827. this.precision = Base.pick(precision, 5);
  828. this.multiplier = Math.pow(10, this.precision);
  829. },
  830. number: function(val) {
  831. return this.precision < 16
  832. ? Math.round(val * this.multiplier) / this.multiplier : val;
  833. },
  834. pair: function(val1, val2, separator) {
  835. return this.number(val1) + (separator || ',') + this.number(val2);
  836. },
  837. point: function(val, separator) {
  838. return this.number(val.x) + (separator || ',') + this.number(val.y);
  839. },
  840. size: function(val, separator) {
  841. return this.number(val.width) + (separator || ',')
  842. + this.number(val.height);
  843. },
  844. rectangle: function(val, separator) {
  845. return this.point(val, separator) + (separator || ',')
  846. + this.size(val, separator);
  847. }
  848. });
  849. Formatter.instance = new Formatter();
  850. var Numerical = new function() {
  851. var abscissas = [
  852. [ 0.5773502691896257645091488],
  853. [0,0.7745966692414833770358531],
  854. [ 0.3399810435848562648026658,0.8611363115940525752239465],
  855. [0,0.5384693101056830910363144,0.9061798459386639927976269],
  856. [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
  857. [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
  858. [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
  859. [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
  860. [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
  861. [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
  862. [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
  863. [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
  864. [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
  865. [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
  866. [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
  867. ];
  868. var weights = [
  869. [1],
  870. [0.8888888888888888888888889,0.5555555555555555555555556],
  871. [0.6521451548625461426269361,0.3478548451374538573730639],
  872. [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
  873. [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
  874. [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
  875. [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
  876. [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
  877. [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
  878. [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
  879. [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
  880. [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
  881. [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
  882. [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
  883. [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
  884. ];
  885. var abs = Math.abs,
  886. sqrt = Math.sqrt,
  887. pow = Math.pow,
  888. log2 = Math.log2 || function(x) {
  889. return Math.log(x) * Math.LOG2E;
  890. },
  891. EPSILON = 1e-12,
  892. MACHINE_EPSILON = 1.12e-16;
  893. function clamp(value, min, max) {
  894. return value < min ? min : value > max ? max : value;
  895. }
  896. function getDiscriminant(a, b, c) {
  897. function split(v) {
  898. var x = v * 134217729,
  899. y = v - x,
  900. hi = y + x,
  901. lo = v - hi;
  902. return [hi, lo];
  903. }
  904. var D = b * b - a * c,
  905. E = b * b + a * c;
  906. if (abs(D) * 3 < E) {
  907. var ad = split(a),
  908. bd = split(b),
  909. cd = split(c),
  910. p = b * b,
  911. dp = (bd[0] * bd[0] - p + 2 * bd[0] * bd[1]) + bd[1] * bd[1],
  912. q = a * c,
  913. dq = (ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0])
  914. + ad[1] * cd[1];
  915. D = (p - q) + (dp - dq);
  916. }
  917. return D;
  918. }
  919. function getNormalizationFactor() {
  920. var norm = Math.max.apply(Math, arguments);
  921. return norm && (norm < 1e-8 || norm > 1e8)
  922. ? pow(2, -Math.round(log2(norm)))
  923. : 0;
  924. }
  925. return {
  926. EPSILON: EPSILON,
  927. MACHINE_EPSILON: MACHINE_EPSILON,
  928. CURVETIME_EPSILON: 1e-8,
  929. GEOMETRIC_EPSILON: 1e-7,
  930. TRIGONOMETRIC_EPSILON: 1e-8,
  931. KAPPA: 4 * (sqrt(2) - 1) / 3,
  932. isZero: function(val) {
  933. return val >= -EPSILON && val <= EPSILON;
  934. },
  935. clamp: clamp,
  936. integrate: function(f, a, b, n) {
  937. var x = abscissas[n - 2],
  938. w = weights[n - 2],
  939. A = (b - a) * 0.5,
  940. B = A + a,
  941. i = 0,
  942. m = (n + 1) >> 1,
  943. sum = n & 1 ? w[i++] * f(B) : 0;
  944. while (i < m) {
  945. var Ax = A * x[i];
  946. sum += w[i++] * (f(B + Ax) + f(B - Ax));
  947. }
  948. return A * sum;
  949. },
  950. findRoot: function(f, df, x, a, b, n, tolerance) {
  951. for (var i = 0; i < n; i++) {
  952. var fx = f(x),
  953. dx = fx / df(x),
  954. nx = x - dx;
  955. if (abs(dx) < tolerance) {
  956. x = nx;
  957. break;
  958. }
  959. if (fx > 0) {
  960. b = x;
  961. x = nx <= a ? (a + b) * 0.5 : nx;
  962. } else {
  963. a = x;
  964. x = nx >= b ? (a + b) * 0.5 : nx;
  965. }
  966. }
  967. return clamp(x, a, b);
  968. },
  969. solveQuadratic: function(a, b, c, roots, min, max) {
  970. var x1, x2 = Infinity;
  971. if (abs(a) < EPSILON) {
  972. if (abs(b) < EPSILON)
  973. return abs(c) < EPSILON ? -1 : 0;
  974. x1 = -c / b;
  975. } else {
  976. b *= -0.5;
  977. var D = getDiscriminant(a, b, c);
  978. if (D && abs(D) < MACHINE_EPSILON) {
  979. var f = getNormalizationFactor(abs(a), abs(b), abs(c));
  980. if (f) {
  981. a *= f;
  982. b *= f;
  983. c *= f;
  984. D = getDiscriminant(a, b, c);
  985. }
  986. }
  987. if (D >= -MACHINE_EPSILON) {
  988. var Q = D < 0 ? 0 : sqrt(D),
  989. R = b + (b < 0 ? -Q : Q);
  990. if (R === 0) {
  991. x1 = c / a;
  992. x2 = -x1;
  993. } else {
  994. x1 = R / a;
  995. x2 = c / R;
  996. }
  997. }
  998. }
  999. var count = 0,
  1000. boundless = min == null,
  1001. minB = min - EPSILON,
  1002. maxB = max + EPSILON;
  1003. if (isFinite(x1) && (boundless || x1 > minB && x1 < maxB))
  1004. roots[count++] = boundless ? x1 : clamp(x1, min, max);
  1005. if (x2 !== x1
  1006. && isFinite(x2) && (boundless || x2 > minB && x2 < maxB))
  1007. roots[count++] = boundless ? x2 : clamp(x2, min, max);
  1008. return count;
  1009. },
  1010. solveCubic: function(a, b, c, d, roots, min, max) {
  1011. var f = getNormalizationFactor(abs(a), abs(b), abs(c), abs(d)),
  1012. x, b1, c2, qd, q;
  1013. if (f) {
  1014. a *= f;
  1015. b *= f;
  1016. c *= f;
  1017. d *= f;
  1018. }
  1019. function evaluate(x0) {
  1020. x = x0;
  1021. var tmp = a * x;
  1022. b1 = tmp + b;
  1023. c2 = b1 * x + c;
  1024. qd = (tmp + b1) * x + c2;
  1025. q = c2 * x + d;
  1026. }
  1027. if (abs(a) < EPSILON) {
  1028. a = b;
  1029. b1 = c;
  1030. c2 = d;
  1031. x = Infinity;
  1032. } else if (abs(d) < EPSILON) {
  1033. b1 = b;
  1034. c2 = c;
  1035. x = 0;
  1036. } else {
  1037. evaluate(-(b / a) / 3);
  1038. var t = q / a,
  1039. r = pow(abs(t), 1/3),
  1040. s = t < 0 ? -1 : 1,
  1041. td = -qd / a,
  1042. rd = td > 0 ? 1.324717957244746 * Math.max(r, sqrt(td)) : r,
  1043. x0 = x - s * rd;
  1044. if (x0 !== x) {
  1045. do {
  1046. evaluate(x0);
  1047. x0 = qd === 0 ? x : x - q / qd / (1 + MACHINE_EPSILON);
  1048. } while (s * x0 > s * x);
  1049. if (abs(a) * x * x > abs(d / x)) {
  1050. c2 = -d / x;
  1051. b1 = (c2 - c) / x;
  1052. }
  1053. }
  1054. }
  1055. var count = Numerical.solveQuadratic(a, b1, c2, roots, min, max),
  1056. boundless = min == null;
  1057. if (isFinite(x) && (count === 0
  1058. || count > 0 && x !== roots[0] && x !== roots[1])
  1059. && (boundless || x > min - EPSILON && x < max + EPSILON))
  1060. roots[count++] = boundless ? x : clamp(x, min, max);
  1061. return count;
  1062. }
  1063. };
  1064. };
  1065. var UID = {
  1066. _id: 1,
  1067. _pools: {},
  1068. get: function(name) {
  1069. if (name) {
  1070. var pool = this._pools[name];
  1071. if (!pool)
  1072. pool = this._pools[name] = { _id: 1 };
  1073. return pool._id++;
  1074. } else {
  1075. return this._id++;
  1076. }
  1077. }
  1078. };
  1079. var Point = Base.extend({
  1080. _class: 'Point',
  1081. _readIndex: true,
  1082. initialize: function Point(arg0, arg1) {
  1083. var type = typeof arg0,
  1084. reading = this.__read,
  1085. read = 0;
  1086. if (type === 'number') {
  1087. var hasY = typeof arg1 === 'number';
  1088. this._set(arg0, hasY ? arg1 : arg0);
  1089. if (reading)
  1090. read = hasY ? 2 : 1;
  1091. } else if (type === 'undefined' || arg0 === null) {
  1092. this._set(0, 0);
  1093. if (reading)
  1094. read = arg0 === null ? 1 : 0;
  1095. } else {
  1096. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1097. read = 1;
  1098. if (Array.isArray(obj)) {
  1099. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1100. } else if ('x' in obj) {
  1101. this._set(obj.x || 0, obj.y || 0);
  1102. } else if ('width' in obj) {
  1103. this._set(obj.width || 0, obj.height || 0);
  1104. } else if ('angle' in obj) {
  1105. this._set(obj.length || 0, 0);
  1106. this.setAngle(obj.angle || 0);
  1107. } else {
  1108. this._set(0, 0);
  1109. read = 0;
  1110. }
  1111. }
  1112. if (reading)
  1113. this.__read = read;
  1114. return this;
  1115. },
  1116. set: '#initialize',
  1117. _set: function(x, y) {
  1118. this.x = x;
  1119. this.y = y;
  1120. return this;
  1121. },
  1122. equals: function(point) {
  1123. return this === point || point
  1124. && (this.x === point.x && this.y === point.y
  1125. || Array.isArray(point)
  1126. && this.x === point[0] && this.y === point[1])
  1127. || false;
  1128. },
  1129. clone: function() {
  1130. return new Point(this.x, this.y);
  1131. },
  1132. toString: function() {
  1133. var f = Formatter.instance;
  1134. return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
  1135. },
  1136. _serialize: function(options) {
  1137. var f = options.formatter;
  1138. return [f.number(this.x), f.number(this.y)];
  1139. },
  1140. getLength: function() {
  1141. return Math.sqrt(this.x * this.x + this.y * this.y);
  1142. },
  1143. setLength: function(length) {
  1144. if (this.isZero()) {
  1145. var angle = this._angle || 0;
  1146. this._set(
  1147. Math.cos(angle) * length,
  1148. Math.sin(angle) * length
  1149. );
  1150. } else {
  1151. var scale = length / this.getLength();
  1152. if (Numerical.isZero(scale))
  1153. this.getAngle();
  1154. this._set(
  1155. this.x * scale,
  1156. this.y * scale
  1157. );
  1158. }
  1159. },
  1160. getAngle: function() {
  1161. return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI;
  1162. },
  1163. setAngle: function(angle) {
  1164. this.setAngleInRadians.call(this, angle * Math.PI / 180);
  1165. },
  1166. getAngleInDegrees: '#getAngle',
  1167. setAngleInDegrees: '#setAngle',
  1168. getAngleInRadians: function() {
  1169. if (!arguments.length) {
  1170. return this.isZero()
  1171. ? this._angle || 0
  1172. : this._angle = Math.atan2(this.y, this.x);
  1173. } else {
  1174. var point = Point.read(arguments),
  1175. div = this.getLength() * point.getLength();
  1176. if (Numerical.isZero(div)) {
  1177. return NaN;
  1178. } else {
  1179. var a = this.dot(point) / div;
  1180. return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a);
  1181. }
  1182. }
  1183. },
  1184. setAngleInRadians: function(angle) {
  1185. this._angle = angle;
  1186. if (!this.isZero()) {
  1187. var length = this.getLength();
  1188. this._set(
  1189. Math.cos(angle) * length,
  1190. Math.sin(angle) * length
  1191. );
  1192. }
  1193. },
  1194. getQuadrant: function() {
  1195. return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
  1196. }
  1197. }, {
  1198. beans: false,
  1199. getDirectedAngle: function() {
  1200. var point = Point.read(arguments);
  1201. return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
  1202. },
  1203. getDistance: function() {
  1204. var point = Point.read(arguments),
  1205. x = point.x - this.x,
  1206. y = point.y - this.y,
  1207. d = x * x + y * y,
  1208. squared = Base.read(arguments);
  1209. return squared ? d : Math.sqrt(d);
  1210. },
  1211. normalize: function(length) {
  1212. if (length === undefined)
  1213. length = 1;
  1214. var current = this.getLength(),
  1215. scale = current !== 0 ? length / current : 0,
  1216. point = new Point(this.x * scale, this.y * scale);
  1217. if (scale >= 0)
  1218. point._angle = this._angle;
  1219. return point;
  1220. },
  1221. rotate: function(angle, center) {
  1222. if (angle === 0)
  1223. return this.clone();
  1224. angle = angle * Math.PI / 180;
  1225. var point = center ? this.subtract(center) : this,
  1226. sin = Math.sin(angle),
  1227. cos = Math.cos(angle);
  1228. point = new Point(
  1229. point.x * cos - point.y * sin,
  1230. point.x * sin + point.y * cos
  1231. );
  1232. return center ? point.add(center) : point;
  1233. },
  1234. transform: function(matrix) {
  1235. return matrix ? matrix._transformPoint(this) : this;
  1236. },
  1237. add: function() {
  1238. var point = Point.read(arguments);
  1239. return new Point(this.x + point.x, this.y + point.y);
  1240. },
  1241. subtract: function() {
  1242. var point = Point.read(arguments);
  1243. return new Point(this.x - point.x, this.y - point.y);
  1244. },
  1245. multiply: function() {
  1246. var point = Point.read(arguments);
  1247. return new Point(this.x * point.x, this.y * point.y);
  1248. },
  1249. divide: function() {
  1250. var point = Point.read(arguments);
  1251. return new Point(this.x / point.x, this.y / point.y);
  1252. },
  1253. modulo: function() {
  1254. var point = Point.read(arguments);
  1255. return new Point(this.x % point.x, this.y % point.y);
  1256. },
  1257. negate: function() {
  1258. return new Point(-this.x, -this.y);
  1259. },
  1260. isInside: function() {
  1261. return Rectangle.read(arguments).contains(this);
  1262. },
  1263. isClose: function() {
  1264. var point = Point.read(arguments),
  1265. tolerance = Base.read(arguments);
  1266. return this.getDistance(point) <= tolerance;
  1267. },
  1268. isCollinear: function() {
  1269. var point = Point.read(arguments);
  1270. return Point.isCollinear(this.x, this.y, point.x, point.y);
  1271. },
  1272. isColinear: '#isCollinear',
  1273. isOrthogonal: function() {
  1274. var point = Point.read(arguments);
  1275. return Point.isOrthogonal(this.x, this.y, point.x, point.y);
  1276. },
  1277. isZero: function() {
  1278. var isZero = Numerical.isZero;
  1279. return isZero(this.x) && isZero(this.y);
  1280. },
  1281. isNaN: function() {
  1282. return isNaN(this.x) || isNaN(this.y);
  1283. },
  1284. isInQuadrant: function(q) {
  1285. return this.x * (q > 1 && q < 4 ? -1 : 1) >= 0
  1286. && this.y * (q > 2 ? -1 : 1) >= 0;
  1287. },
  1288. dot: function() {
  1289. var point = Point.read(arguments);
  1290. return this.x * point.x + this.y * point.y;
  1291. },
  1292. cross: function() {
  1293. var point = Point.read(arguments);
  1294. return this.x * point.y - this.y * point.x;
  1295. },
  1296. project: function() {
  1297. var point = Point.read(arguments),
  1298. scale = point.isZero() ? 0 : this.dot(point) / point.dot(point);
  1299. return new Point(
  1300. point.x * scale,
  1301. point.y * scale
  1302. );
  1303. },
  1304. statics: {
  1305. min: function() {
  1306. var point1 = Point.read(arguments),
  1307. point2 = Point.read(arguments);
  1308. return new Point(
  1309. Math.min(point1.x, point2.x),
  1310. Math.min(point1.y, point2.y)
  1311. );
  1312. },
  1313. max: function() {
  1314. var point1 = Point.read(arguments),
  1315. point2 = Point.read(arguments);
  1316. return new Point(
  1317. Math.max(point1.x, point2.x),
  1318. Math.max(point1.y, point2.y)
  1319. );
  1320. },
  1321. random: function() {
  1322. return new Point(Math.random(), Math.random());
  1323. },
  1324. isCollinear: function(x1, y1, x2, y2) {
  1325. return Math.abs(x1 * y2 - y1 * x2)
  1326. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1327. * 1e-8;
  1328. },
  1329. isOrthogonal: function(x1, y1, x2, y2) {
  1330. return Math.abs(x1 * x2 + y1 * y2)
  1331. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1332. * 1e-8;
  1333. }
  1334. }
  1335. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1336. var op = Math[key];
  1337. this[key] = function() {
  1338. return new Point(op(this.x), op(this.y));
  1339. };
  1340. }, {}));
  1341. var LinkedPoint = Point.extend({
  1342. initialize: function Point(x, y, owner, setter) {
  1343. this._x = x;
  1344. this._y = y;
  1345. this._owner = owner;
  1346. this._setter = setter;
  1347. },
  1348. _set: function(x, y, _dontNotify) {
  1349. this._x = x;
  1350. this._y = y;
  1351. if (!_dontNotify)
  1352. this._owner[this._setter](this);
  1353. return this;
  1354. },
  1355. getX: function() {
  1356. return this._x;
  1357. },
  1358. setX: function(x) {
  1359. this._x = x;
  1360. this._owner[this._setter](this);
  1361. },
  1362. getY: function() {
  1363. return this._y;
  1364. },
  1365. setY: function(y) {
  1366. this._y = y;
  1367. this._owner[this._setter](this);
  1368. },
  1369. isSelected: function() {
  1370. return !!(this._owner._selection & this._getSelection());
  1371. },
  1372. setSelected: function(selected) {
  1373. this._owner._changeSelection(this._getSelection(), selected);
  1374. },
  1375. _getSelection: function() {
  1376. return this._setter === 'setPosition' ? 4 : 0;
  1377. }
  1378. });
  1379. var Size = Base.extend({
  1380. _class: 'Size',
  1381. _readIndex: true,
  1382. initialize: function Size(arg0, arg1) {
  1383. var type = typeof arg0,
  1384. reading = this.__read,
  1385. read = 0;
  1386. if (type === 'number') {
  1387. var hasHeight = typeof arg1 === 'number';
  1388. this._set(arg0, hasHeight ? arg1 : arg0);
  1389. if (reading)
  1390. read = hasHeight ? 2 : 1;
  1391. } else if (type === 'undefined' || arg0 === null) {
  1392. this._set(0, 0);
  1393. if (reading)
  1394. read = arg0 === null ? 1 : 0;
  1395. } else {
  1396. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1397. read = 1;
  1398. if (Array.isArray(obj)) {
  1399. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1400. } else if ('width' in obj) {
  1401. this._set(obj.width || 0, obj.height || 0);
  1402. } else if ('x' in obj) {
  1403. this._set(obj.x || 0, obj.y || 0);
  1404. } else {
  1405. this._set(0, 0);
  1406. read = 0;
  1407. }
  1408. }
  1409. if (reading)
  1410. this.__read = read;
  1411. return this;
  1412. },
  1413. set: '#initialize',
  1414. _set: function(width, height) {
  1415. this.width = width;
  1416. this.height = height;
  1417. return this;
  1418. },
  1419. equals: function(size) {
  1420. return size === this || size && (this.width === size.width
  1421. && this.height === size.height
  1422. || Array.isArray(size) && this.width === size[0]
  1423. && this.height === size[1]) || false;
  1424. },
  1425. clone: function() {
  1426. return new Size(this.width, this.height);
  1427. },
  1428. toString: function() {
  1429. var f = Formatter.instance;
  1430. return '{ width: ' + f.number(this.width)
  1431. + ', height: ' + f.number(this.height) + ' }';
  1432. },
  1433. _serialize: function(options) {
  1434. var f = options.formatter;
  1435. return [f.number(this.width),
  1436. f.number(this.height)];
  1437. },
  1438. add: function() {
  1439. var size = Size.read(arguments);
  1440. return new Size(this.width + size.width, this.height + size.height);
  1441. },
  1442. subtract: function() {
  1443. var size = Size.read(arguments);
  1444. return new Size(this.width - size.width, this.height - size.height);
  1445. },
  1446. multiply: function() {
  1447. var size = Size.read(arguments);
  1448. return new Size(this.width * size.width, this.height * size.height);
  1449. },
  1450. divide: function() {
  1451. var size = Size.read(arguments);
  1452. return new Size(this.width / size.width, this.height / size.height);
  1453. },
  1454. modulo: function() {
  1455. var size = Size.read(arguments);
  1456. return new Size(this.width % size.width, this.height % size.height);
  1457. },
  1458. negate: function() {
  1459. return new Size(-this.width, -this.height);
  1460. },
  1461. isZero: function() {
  1462. var isZero = Numerical.isZero;
  1463. return isZero(this.width) && isZero(this.height);
  1464. },
  1465. isNaN: function() {
  1466. return isNaN(this.width) || isNaN(this.height);
  1467. },
  1468. statics: {
  1469. min: function(size1, size2) {
  1470. return new Size(
  1471. Math.min(size1.width, size2.width),
  1472. Math.min(size1.height, size2.height));
  1473. },
  1474. max: function(size1, size2) {
  1475. return new Size(
  1476. Math.max(size1.width, size2.width),
  1477. Math.max(size1.height, size2.height));
  1478. },
  1479. random: function() {
  1480. return new Size(Math.random(), Math.random());
  1481. }
  1482. }
  1483. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1484. var op = Math[key];
  1485. this[key] = function() {
  1486. return new Size(op(this.width), op(this.height));
  1487. };
  1488. }, {}));
  1489. var LinkedSize = Size.extend({
  1490. initialize: function Size(width, height, owner, setter) {
  1491. this._width = width;
  1492. this._height = height;
  1493. this._owner = owner;
  1494. this._setter = setter;
  1495. },
  1496. _set: function(width, height, _dontNotify) {
  1497. this._width = width;
  1498. this._height = height;
  1499. if (!_dontNotify)
  1500. this._owner[this._setter](this);
  1501. return this;
  1502. },
  1503. getWidth: function() {
  1504. return this._width;
  1505. },
  1506. setWidth: function(width) {
  1507. this._width = width;
  1508. this._owner[this._setter](this);
  1509. },
  1510. getHeight: function() {
  1511. return this._height;
  1512. },
  1513. setHeight: function(height) {
  1514. this._height = height;
  1515. this._owner[this._setter](this);
  1516. }
  1517. });
  1518. var Rectangle = Base.extend({
  1519. _class: 'Rectangle',
  1520. _readIndex: true,
  1521. beans: true,
  1522. initialize: function Rectangle(arg0, arg1, arg2, arg3) {
  1523. var type = typeof arg0,
  1524. read;
  1525. if (type === 'number') {
  1526. this._set(arg0, arg1, arg2, arg3);
  1527. read = 4;
  1528. } else if (type === 'undefined' || arg0 === null) {
  1529. this._set(0, 0, 0, 0);
  1530. read = arg0 === null ? 1 : 0;
  1531. } else if (arguments.length === 1) {
  1532. if (Array.isArray(arg0)) {
  1533. this._set.apply(this, arg0);
  1534. read = 1;
  1535. } else if (arg0.x !== undefined || arg0.width !== undefined) {
  1536. this._set(arg0.x || 0, arg0.y || 0,
  1537. arg0.width || 0, arg0.height || 0);
  1538. read = 1;
  1539. } else if (arg0.from === undefined && arg0.to === undefined) {
  1540. this._set(0, 0, 0, 0);
  1541. Base.filter(this, arg0);
  1542. read = 1;
  1543. }
  1544. }
  1545. if (read === undefined) {
  1546. var frm = Point.readNamed(arguments, 'from'),
  1547. next = Base.peek(arguments),
  1548. x = frm.x,
  1549. y = frm.y,
  1550. width,
  1551. height;
  1552. if (next && next.x !== undefined
  1553. || Base.hasNamed(arguments, 'to')) {
  1554. var to = Point.readNamed(arguments, 'to');
  1555. width = to.x - x;
  1556. height = to.y - y;
  1557. if (width < 0) {
  1558. x = to.x;
  1559. width = -width;
  1560. }
  1561. if (height < 0) {
  1562. y = to.y;
  1563. height = -height;
  1564. }
  1565. } else {
  1566. var size = Size.read(arguments);
  1567. width = size.width;
  1568. height = size.height;
  1569. }
  1570. this._set(x, y, width, height);
  1571. read = arguments.__index;
  1572. var filtered = arguments.__filtered;
  1573. if (filtered)
  1574. this.__filtered = filtered;
  1575. }
  1576. if (this.__read)
  1577. this.__read = read;
  1578. return this;
  1579. },
  1580. set: '#initialize',
  1581. _set: function(x, y, width, height) {
  1582. this.x = x;
  1583. this.y = y;
  1584. this.width = width;
  1585. this.height = height;
  1586. return this;
  1587. },
  1588. clone: function() {
  1589. return new Rectangle(this.x, this.y, this.width, this.height);
  1590. },
  1591. equals: function(rect) {
  1592. var rt = Base.isPlainValue(rect)
  1593. ? Rectangle.read(arguments)
  1594. : rect;
  1595. return rt === this
  1596. || rt && this.x === rt.x && this.y === rt.y
  1597. && this.width === rt.width && this.height === rt.height
  1598. || false;
  1599. },
  1600. toString: function() {
  1601. var f = Formatter.instance;
  1602. return '{ x: ' + f.number(this.x)
  1603. + ', y: ' + f.number(this.y)
  1604. + ', width: ' + f.number(this.width)
  1605. + ', height: ' + f.number(this.height)
  1606. + ' }';
  1607. },
  1608. _serialize: function(options) {
  1609. var f = options.formatter;
  1610. return [f.number(this.x),
  1611. f.number(this.y),
  1612. f.number(this.width),
  1613. f.number(this.height)];
  1614. },
  1615. getPoint: function(_dontLink) {
  1616. var ctor = _dontLink ? Point : LinkedPoint;
  1617. return new ctor(this.x, this.y, this, 'setPoint');
  1618. },
  1619. setPoint: function() {
  1620. var point = Point.read(arguments);
  1621. this.x = point.x;
  1622. this.y = point.y;
  1623. },
  1624. getSize: function(_dontLink) {
  1625. var ctor = _dontLink ? Size : LinkedSize;
  1626. return new ctor(this.width, this.height, this, 'setSize');
  1627. },
  1628. _fw: 1,
  1629. _fh: 1,
  1630. setSize: function() {
  1631. var size = Size.read(arguments),
  1632. sx = this._sx,
  1633. sy = this._sy,
  1634. w = size.width,
  1635. h = size.height;
  1636. if (sx) {
  1637. this.x += (this.width - w) * sx;
  1638. }
  1639. if (sy) {
  1640. this.y += (this.height - h) * sy;
  1641. }
  1642. this.width = w;
  1643. this.height = h;
  1644. this._fw = this._fh = 1;
  1645. },
  1646. getLeft: function() {
  1647. return this.x;
  1648. },
  1649. setLeft: function(left) {
  1650. if (!this._fw) {
  1651. var amount = left - this.x;
  1652. this.width -= this._sx === 0.5 ? amount * 2 : amount;
  1653. }
  1654. this.x = left;
  1655. this._sx = this._fw = 0;
  1656. },
  1657. getTop: function() {
  1658. return this.y;
  1659. },
  1660. setTop: function(top) {
  1661. if (!this._fh) {
  1662. var amount = top - this.y;
  1663. this.height -= this._sy === 0.5 ? amount * 2 : amount;
  1664. }
  1665. this.y = top;
  1666. this._sy = this._fh = 0;
  1667. },
  1668. getRight: function() {
  1669. return this.x + this.width;
  1670. },
  1671. setRight: function(right) {
  1672. if (!this._fw) {
  1673. var amount = right - this.x;
  1674. this.width = this._sx === 0.5 ? amount * 2 : amount;
  1675. }
  1676. this.x = right - this.width;
  1677. this._sx = 1;
  1678. this._fw = 0;
  1679. },
  1680. getBottom: function() {
  1681. return this.y + this.height;
  1682. },
  1683. setBottom: function(bottom) {
  1684. if (!this._fh) {
  1685. var amount = bottom - this.y;
  1686. this.height = this._sy === 0.5 ? amount * 2 : amount;
  1687. }
  1688. this.y = bottom - this.height;
  1689. this._sy = 1;
  1690. this._fh = 0;
  1691. },
  1692. getCenterX: function() {
  1693. return this.x + this.width / 2;
  1694. },
  1695. setCenterX: function(x) {
  1696. if (this._fw || this._sx === 0.5) {
  1697. this.x = x - this.width / 2;
  1698. } else {
  1699. if (this._sx) {
  1700. this.x += (x - this.x) * 2 * this._sx;
  1701. }
  1702. this.width = (x - this.x) * 2;
  1703. }
  1704. this._sx = 0.5;
  1705. this._fw = 0;
  1706. },
  1707. getCenterY: function() {
  1708. return this.y + this.height / 2;
  1709. },
  1710. setCenterY: function(y) {
  1711. if (this._fh || this._sy === 0.5) {
  1712. this.y = y - this.height / 2;
  1713. } else {
  1714. if (this._sy) {
  1715. this.y += (y - this.y) * 2 * this._sy;
  1716. }
  1717. this.height = (y - this.y) * 2;
  1718. }
  1719. this._sy = 0.5;
  1720. this._fh = 0;
  1721. },
  1722. getCenter: function(_dontLink) {
  1723. var ctor = _dontLink ? Point : LinkedPoint;
  1724. return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter');
  1725. },
  1726. setCenter: function() {
  1727. var point = Point.read(arguments);
  1728. this.setCenterX(point.x);
  1729. this.setCenterY(point.y);
  1730. return this;
  1731. },
  1732. getArea: function() {
  1733. return this.width * this.height;
  1734. },
  1735. isEmpty: function() {
  1736. return this.width === 0 || this.height === 0;
  1737. },
  1738. contains: function(arg) {
  1739. return arg && arg.width !== undefined
  1740. || (Array.isArray(arg) ? arg : arguments).length === 4
  1741. ? this._containsRectangle(Rectangle.read(arguments))
  1742. : this._containsPoint(Point.read(arguments));
  1743. },
  1744. _containsPoint: function(point) {
  1745. var x = point.x,
  1746. y = point.y;
  1747. return x >= this.x && y >= this.y
  1748. && x <= this.x + this.width
  1749. && y <= this.y + this.height;
  1750. },
  1751. _containsRectangle: function(rect) {
  1752. var x = rect.x,
  1753. y = rect.y;
  1754. return x >= this.x && y >= this.y
  1755. && x + rect.width <= this.x + this.width
  1756. && y + rect.height <= this.y + this.height;
  1757. },
  1758. intersects: function() {
  1759. var rect = Rectangle.read(arguments),
  1760. epsilon = Base.read(arguments) || 0;
  1761. return rect.x + rect.width > this.x - epsilon
  1762. && rect.y + rect.height > this.y - epsilon
  1763. && rect.x < this.x + this.width + epsilon
  1764. && rect.y < this.y + this.height + epsilon;
  1765. },
  1766. intersect: function() {
  1767. var rect = Rectangle.read(arguments),
  1768. x1 = Math.max(this.x, rect.x),
  1769. y1 = Math.max(this.y, rect.y),
  1770. x2 = Math.min(this.x + this.width, rect.x + rect.width),
  1771. y2 = Math.min(this.y + this.height, rect.y + rect.height);
  1772. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1773. },
  1774. unite: function() {
  1775. var rect = Rectangle.read(arguments),
  1776. x1 = Math.min(this.x, rect.x),
  1777. y1 = Math.min(this.y, rect.y),
  1778. x2 = Math.max(this.x + this.width, rect.x + rect.width),
  1779. y2 = Math.max(this.y + this.height, rect.y + rect.height);
  1780. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1781. },
  1782. include: function() {
  1783. var point = Point.read(arguments);
  1784. var x1 = Math.min(this.x, point.x),
  1785. y1 = Math.min(this.y, point.y),
  1786. x2 = Math.max(this.x + this.width, point.x),
  1787. y2 = Math.max(this.y + this.height, point.y);
  1788. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1789. },
  1790. expand: function() {
  1791. var amount = Size.read(arguments),
  1792. hor = amount.width,
  1793. ver = amount.height;
  1794. return new Rectangle(this.x - hor / 2, this.y - ver / 2,
  1795. this.width + hor, this.height + ver);
  1796. },
  1797. scale: function(hor, ver) {
  1798. return this.expand(this.width * hor - this.width,
  1799. this.height * (ver === undefined ? hor : ver) - this.height);
  1800. }
  1801. }, Base.each([
  1802. ['Top', 'Left'], ['Top', 'Right'],
  1803. ['Bottom', 'Left'], ['Bottom', 'Right'],
  1804. ['Left', 'Center'], ['Top', 'Center'],
  1805. ['Right', 'Center'], ['Bottom', 'Center']
  1806. ],
  1807. function(parts, index) {
  1808. var part = parts.join(''),
  1809. xFirst = /^[RL]/.test(part);
  1810. if (index >= 4)
  1811. parts[1] += xFirst ? 'Y' : 'X';
  1812. var x = parts[xFirst ? 0 : 1],
  1813. y = parts[xFirst ? 1 : 0],
  1814. getX = 'get' + x,
  1815. getY = 'get' + y,
  1816. setX = 'set' + x,
  1817. setY = 'set' + y,
  1818. get = 'get' + part,
  1819. set = 'set' + part;
  1820. this[get] = function(_dontLink) {
  1821. var ctor = _dontLink ? Point : LinkedPoint;
  1822. return new ctor(this[getX](), this[getY](), this, set);
  1823. };
  1824. this[set] = function() {
  1825. var point = Point.read(arguments);
  1826. this[setX](point.x);
  1827. this[setY](point.y);
  1828. };
  1829. }, {
  1830. beans: true
  1831. }
  1832. ));
  1833. var LinkedRectangle = Rectangle.extend({
  1834. initialize: function Rectangle(x, y, width, height, owner, setter) {
  1835. this._set(x, y, width, height, true);
  1836. this._owner = owner;
  1837. this._setter = setter;
  1838. },
  1839. _set: function(x, y, width, height, _dontNotify) {
  1840. this._x = x;
  1841. this._y = y;
  1842. this._width = width;
  1843. this._height = height;
  1844. if (!_dontNotify)
  1845. this._owner[this._setter](this);
  1846. return this;
  1847. }
  1848. },
  1849. new function() {
  1850. var proto = Rectangle.prototype;
  1851. return Base.each(['x', 'y', 'width', 'height'], function(key) {
  1852. var part = Base.capitalize(key),
  1853. internal = '_' + key;
  1854. this['get' + part] = function() {
  1855. return this[internal];
  1856. };
  1857. this['set' + part] = function(value) {
  1858. this[internal] = value;
  1859. if (!this._dontNotify)
  1860. this._owner[this._setter](this);
  1861. };
  1862. }, Base.each(['Point', 'Size', 'Center',
  1863. 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
  1864. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  1865. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
  1866. function(key) {
  1867. var name = 'set' + key;
  1868. this[name] = function() {
  1869. this._dontNotify = true;
  1870. proto[name].apply(this, arguments);
  1871. this._dontNotify = false;
  1872. this._owner[this._setter](this);
  1873. };
  1874. }, {
  1875. isSelected: function() {
  1876. return !!(this._owner._selection & 2);
  1877. },
  1878. setSelected: function(selected) {
  1879. var owner = this._owner;
  1880. if (owner._changeSelection) {
  1881. owner._changeSelection(2, selected);
  1882. }
  1883. }
  1884. })
  1885. );
  1886. });
  1887. var Matrix = Base.extend({
  1888. _class: 'Matrix',
  1889. initialize: function Matrix(arg, _dontNotify) {
  1890. var count = arguments.length,
  1891. ok = true;
  1892. if (count >= 6) {
  1893. this._set.apply(this, arguments);
  1894. } else if (count === 1 || count === 2) {
  1895. if (arg instanceof Matrix) {
  1896. this._set(arg._a, arg._b, arg._c, arg._d, arg._tx, arg._ty,
  1897. _dontNotify);
  1898. } else if (Array.isArray(arg)) {
  1899. this._set.apply(this,
  1900. _dontNotify ? arg.concat([_dontNotify]) : arg);
  1901. } else {
  1902. ok = false;
  1903. }
  1904. } else if (!count) {
  1905. this.reset();
  1906. } else {
  1907. ok = false;
  1908. }
  1909. if (!ok) {
  1910. throw new Error('Unsupported matrix parameters');
  1911. }
  1912. return this;
  1913. },
  1914. set: '#initialize',
  1915. _set: function(a, b, c, d, tx, ty, _dontNotify) {
  1916. this._a = a;
  1917. this._b = b;
  1918. this._c = c;
  1919. this._d = d;
  1920. this._tx = tx;
  1921. this._ty = ty;
  1922. if (!_dontNotify)
  1923. this._changed();
  1924. return this;
  1925. },
  1926. _serialize: function(options, dictionary) {
  1927. return Base.serialize(this.getValues(), options, true, dictionary);
  1928. },
  1929. _changed: function() {
  1930. var owner = this._owner;
  1931. if (owner) {
  1932. if (owner._applyMatrix) {
  1933. owner.transform(null, true);
  1934. } else {
  1935. owner._changed(25);
  1936. }
  1937. }
  1938. },
  1939. clone: function() {
  1940. return new Matrix(this._a, this._b, this._c, this._d,
  1941. this._tx, this._ty);
  1942. },
  1943. equals: function(mx) {
  1944. return mx === this || mx && this._a === mx._a && this._b === mx._b
  1945. && this._c === mx._c && this._d === mx._d
  1946. && this._tx === mx._tx && this._ty === mx._ty;
  1947. },
  1948. toString: function() {
  1949. var f = Formatter.instance;
  1950. return '[[' + [f.number(this._a), f.number(this._c),
  1951. f.number(this._tx)].join(', ') + '], ['
  1952. + [f.number(this._b), f.number(this._d),
  1953. f.number(this._ty)].join(', ') + ']]';
  1954. },
  1955. reset: function(_dontNotify) {
  1956. this._a = this._d = 1;
  1957. this._b = this._c = this._tx = this._ty = 0;
  1958. if (!_dontNotify)
  1959. this._changed();
  1960. return this;
  1961. },
  1962. apply: function(recursively, _setApplyMatrix) {
  1963. var owner = this._owner;
  1964. if (owner) {
  1965. owner.transform(null, true, Base.pick(recursively, true),
  1966. _setApplyMatrix);
  1967. return this.isIdentity();
  1968. }
  1969. return false;
  1970. },
  1971. translate: function() {
  1972. var point = Point.read(arguments),
  1973. x = point.x,
  1974. y = point.y;
  1975. this._tx += x * this._a + y * this._c;
  1976. this._ty += x * this._b + y * this._d;
  1977. this._changed();
  1978. return this;
  1979. },
  1980. scale: function() {
  1981. var scale = Point.read(arguments),
  1982. center = Point.read(arguments, 0, { readNull: true });
  1983. if (center)
  1984. this.translate(center);
  1985. this._a *= scale.x;
  1986. this._b *= scale.x;
  1987. this._c *= scale.y;
  1988. this._d *= scale.y;
  1989. if (center)
  1990. this.translate(center.negate());
  1991. this._changed();
  1992. return this;
  1993. },
  1994. rotate: function(angle ) {
  1995. angle *= Math.PI / 180;
  1996. var center = Point.read(arguments, 1),
  1997. x = center.x,
  1998. y = center.y,
  1999. cos = Math.cos(angle),
  2000. sin = Math.sin(angle),
  2001. tx = x - x * cos + y * sin,
  2002. ty = y - x * sin - y * cos,
  2003. a = this._a,
  2004. b = this._b,
  2005. c = this._c,
  2006. d = this._d;
  2007. this._a = cos * a + sin * c;
  2008. this._b = cos * b + sin * d;
  2009. this._c = -sin * a + cos * c;
  2010. this._d = -sin * b + cos * d;
  2011. this._tx += tx * a + ty * c;
  2012. this._ty += tx * b + ty * d;
  2013. this._changed();
  2014. return this;
  2015. },
  2016. shear: function() {
  2017. var shear = Point.read(arguments),
  2018. center = Point.read(arguments, 0, { readNull: true });
  2019. if (center)
  2020. this.translate(center);
  2021. var a = this._a,
  2022. b = this._b;
  2023. this._a += shear.y * this._c;
  2024. this._b += shear.y * this._d;
  2025. this._c += shear.x * a;
  2026. this._d += shear.x * b;
  2027. if (center)
  2028. this.translate(center.negate());
  2029. this._changed();
  2030. return this;
  2031. },
  2032. skew: function() {
  2033. var skew = Point.read(arguments),
  2034. center = Point.read(arguments, 0, { readNull: true }),
  2035. toRadians = Math.PI / 180,
  2036. shear = new Point(Math.tan(skew.x * toRadians),
  2037. Math.tan(skew.y * toRadians));
  2038. return this.shear(shear, center);
  2039. },
  2040. append: function(mx, _dontNotify) {
  2041. if (mx) {
  2042. var a1 = this._a,
  2043. b1 = this._b,
  2044. c1 = this._c,
  2045. d1 = this._d,
  2046. a2 = mx._a,
  2047. b2 = mx._c,
  2048. c2 = mx._b,
  2049. d2 = mx._d,
  2050. tx2 = mx._tx,
  2051. ty2 = mx._ty;
  2052. this._a = a2 * a1 + c2 * c1;
  2053. this._c = b2 * a1 + d2 * c1;
  2054. this._b = a2 * b1 + c2 * d1;
  2055. this._d = b2 * b1 + d2 * d1;
  2056. this._tx += tx2 * a1 + ty2 * c1;
  2057. this._ty += tx2 * b1 + ty2 * d1;
  2058. if (!_dontNotify)
  2059. this._changed();
  2060. }
  2061. return this;
  2062. },
  2063. prepend: function(mx, _dontNotify) {
  2064. if (mx) {
  2065. var a1 = this._a,
  2066. b1 = this._b,
  2067. c1 = this._c,
  2068. d1 = this._d,
  2069. tx1 = this._tx,
  2070. ty1 = this._ty,
  2071. a2 = mx._a,
  2072. b2 = mx._c,
  2073. c2 = mx._b,
  2074. d2 = mx._d,
  2075. tx2 = mx._tx,
  2076. ty2 = mx._ty;
  2077. this._a = a2 * a1 + b2 * b1;
  2078. this._c = a2 * c1 + b2 * d1;
  2079. this._b = c2 * a1 + d2 * b1;
  2080. this._d = c2 * c1 + d2 * d1;
  2081. this._tx = a2 * tx1 + b2 * ty1 + tx2;
  2082. this._ty = c2 * tx1 + d2 * ty1 + ty2;
  2083. if (!_dontNotify)
  2084. this._changed();
  2085. }
  2086. return this;
  2087. },
  2088. appended: function(mx) {
  2089. return this.clone().append(mx);
  2090. },
  2091. prepended: function(mx) {
  2092. return this.clone().prepend(mx);
  2093. },
  2094. invert: function() {
  2095. var a = this._a,
  2096. b = this._b,
  2097. c = this._c,
  2098. d = this._d,
  2099. tx = this._tx,
  2100. ty = this._ty,
  2101. det = a * d - b * c,
  2102. res = null;
  2103. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2104. this._a = d / det;
  2105. this._b = -b / det;
  2106. this._c = -c / det;
  2107. this._d = a / det;
  2108. this._tx = (c * ty - d * tx) / det;
  2109. this._ty = (b * tx - a * ty) / det;
  2110. res = this;
  2111. }
  2112. return res;
  2113. },
  2114. inverted: function() {
  2115. return this.clone().invert();
  2116. },
  2117. concatenate: '#append',
  2118. preConcatenate: '#prepend',
  2119. chain: '#appended',
  2120. _shiftless: function() {
  2121. return new Matrix(this._a, this._b, this._c, this._d, 0, 0);
  2122. },
  2123. _orNullIfIdentity: function() {
  2124. return this.isIdentity() ? null : this;
  2125. },
  2126. isIdentity: function() {
  2127. return this._a === 1 && this._b === 0 && this._c === 0 && this._d === 1
  2128. && this._tx === 0 && this._ty === 0;
  2129. },
  2130. isInvertible: function() {
  2131. var det = this._a * this._d - this._c * this._b;
  2132. return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty);
  2133. },
  2134. isSingular: function() {
  2135. return !this.isInvertible();
  2136. },
  2137. transform: function( src, dst, count) {
  2138. return arguments.length < 3
  2139. ? this._transformPoint(Point.read(arguments))
  2140. : this._transformCoordinates(src, dst, count);
  2141. },
  2142. _transformPoint: function(point, dest, _dontNotify) {
  2143. var x = point.x,
  2144. y = point.y;
  2145. if (!dest)
  2146. dest = new Point();
  2147. return dest._set(
  2148. x * this._a + y * this._c + this._tx,
  2149. x * this._b + y * this._d + this._ty,
  2150. _dontNotify);
  2151. },
  2152. _transformCoordinates: function(src, dst, count) {
  2153. for (var i = 0, max = 2 * count; i < max; i += 2) {
  2154. var x = src[i],
  2155. y = src[i + 1];
  2156. dst[i] = x * this._a + y * this._c + this._tx;
  2157. dst[i + 1] = x * this._b + y * this._d + this._ty;
  2158. }
  2159. return dst;
  2160. },
  2161. _transformCorners: function(rect) {
  2162. var x1 = rect.x,
  2163. y1 = rect.y,
  2164. x2 = x1 + rect.width,
  2165. y2 = y1 + rect.height,
  2166. coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
  2167. return this._transformCoordinates(coords, coords, 4);
  2168. },
  2169. _transformBounds: function(bounds, dest, _dontNotify) {
  2170. var coords = this._transformCorners(bounds),
  2171. min = coords.slice(0, 2),
  2172. max = min.slice();
  2173. for (var i = 2; i < 8; i++) {
  2174. var val = coords[i],
  2175. j = i & 1;
  2176. if (val < min[j]) {
  2177. min[j] = val;
  2178. } else if (val > max[j]) {
  2179. max[j] = val;
  2180. }
  2181. }
  2182. if (!dest)
  2183. dest = new Rectangle();
  2184. return dest._set(min[0], min[1], max[0] - min[0], max[1] - min[1],
  2185. _dontNotify);
  2186. },
  2187. inverseTransform: function() {
  2188. return this._inverseTransform(Point.read(arguments));
  2189. },
  2190. _inverseTransform: function(point, dest, _dontNotify) {
  2191. var a = this._a,
  2192. b = this._b,
  2193. c = this._c,
  2194. d = this._d,
  2195. tx = this._tx,
  2196. ty = this._ty,
  2197. det = a * d - b * c,
  2198. res = null;
  2199. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2200. var x = point.x - this._tx,
  2201. y = point.y - this._ty;
  2202. if (!dest)
  2203. dest = new Point();
  2204. res = dest._set(
  2205. (x * d - y * c) / det,
  2206. (y * a - x * b) / det,
  2207. _dontNotify);
  2208. }
  2209. return res;
  2210. },
  2211. decompose: function() {
  2212. var a = this._a,
  2213. b = this._b,
  2214. c = this._c,
  2215. d = this._d,
  2216. det = a * d - b * c,
  2217. sqrt = Math.sqrt,
  2218. atan2 = Math.atan2,
  2219. degrees = 180 / Math.PI,
  2220. rotate,
  2221. scale,
  2222. skew;
  2223. if (a !== 0 || b !== 0) {
  2224. var r = sqrt(a * a + b * b);
  2225. rotate = Math.acos(a / r) * (b > 0 ? 1 : -1);
  2226. scale = [r, det / r];
  2227. skew = [atan2(a * c + b * d, r * r), 0];
  2228. } else if (c !== 0 || d !== 0) {
  2229. var s = sqrt(c * c + d * d);
  2230. rotate = Math.asin(c / s) * (d > 0 ? 1 : -1);
  2231. scale = [det / s, s];
  2232. skew = [0, atan2(a * c + b * d, s * s)];
  2233. } else {
  2234. rotate = 0;
  2235. skew = scale = [0, 0];
  2236. }
  2237. return {
  2238. translation: this.getTranslation(),
  2239. rotation: rotate * degrees,
  2240. scaling: new Point(scale),
  2241. skewing: new Point(skew[0] * degrees, skew[1] * degrees)
  2242. };
  2243. },
  2244. getValues: function() {
  2245. return [ this._a, this._b, this._c, this._d, this._tx, this._ty ];
  2246. },
  2247. getTranslation: function() {
  2248. return new Point(this._tx, this._ty);
  2249. },
  2250. getScaling: function() {
  2251. return this.decompose().scaling;
  2252. },
  2253. getRotation: function() {
  2254. return this.decompose().rotation;
  2255. },
  2256. applyToContext: function(ctx) {
  2257. if (!this.isIdentity()) {
  2258. ctx.transform(this._a, this._b, this._c, this._d,
  2259. this._tx, this._ty);
  2260. }
  2261. }
  2262. }, Base.each(['a', 'b', 'c', 'd', 'tx', 'ty'], function(key) {
  2263. var part = Base.capitalize(key),
  2264. prop = '_' + key;
  2265. this['get' + part] = function() {
  2266. return this[prop];
  2267. };
  2268. this['set' + part] = function(value) {
  2269. this[prop] = value;
  2270. this._changed();
  2271. };
  2272. }, {}));
  2273. var Line = Base.extend({
  2274. _class: 'Line',
  2275. initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
  2276. var asVector = false;
  2277. if (arguments.length >= 4) {
  2278. this._px = arg0;
  2279. this._py = arg1;
  2280. this._vx = arg2;
  2281. this._vy = arg3;
  2282. asVector = arg4;
  2283. } else {
  2284. this._px = arg0.x;
  2285. this._py = arg0.y;
  2286. this._vx = arg1.x;
  2287. this._vy = arg1.y;
  2288. asVector = arg2;
  2289. }
  2290. if (!asVector) {
  2291. this._vx -= this._px;
  2292. this._vy -= this._py;
  2293. }
  2294. },
  2295. getPoint: function() {
  2296. return new Point(this._px, this._py);
  2297. },
  2298. getVector: function() {
  2299. return new Point(this._vx, this._vy);
  2300. },
  2301. getLength: function() {
  2302. return this.getVector().getLength();
  2303. },
  2304. intersect: function(line, isInfinite) {
  2305. return Line.intersect(
  2306. this._px, this._py, this._vx, this._vy,
  2307. line._px, line._py, line._vx, line._vy,
  2308. true, isInfinite);
  2309. },
  2310. getSide: function(point, isInfinite) {
  2311. return Line.getSide(
  2312. this._px, this._py, this._vx, this._vy,
  2313. point.x, point.y, true, isInfinite);
  2314. },
  2315. getDistance: function(point) {
  2316. return Math.abs(this.getSignedDistance(point));
  2317. },
  2318. getSignedDistance: function(point) {
  2319. return Line.getSignedDistance(this._px, this._py, this._vx, this._vy,
  2320. point.x, point.y, true);
  2321. },
  2322. isCollinear: function(line) {
  2323. return Point.isCollinear(this._vx, this._vy, line._vx, line._vy);
  2324. },
  2325. isOrthogonal: function(line) {
  2326. return Point.isOrthogonal(this._vx, this._vy, line._vx, line._vy);
  2327. },
  2328. statics: {
  2329. intersect: function(p1x, p1y, v1x, v1y, p2x, p2y, v2x, v2y, asVector,
  2330. isInfinite) {
  2331. if (!asVector) {
  2332. v1x -= p1x;
  2333. v1y -= p1y;
  2334. v2x -= p2x;
  2335. v2y -= p2y;
  2336. }
  2337. var cross = v1x * v2y - v1y * v2x;
  2338. if (!Numerical.isZero(cross)) {
  2339. var dx = p1x - p2x,
  2340. dy = p1y - p2y,
  2341. u1 = (v2x * dy - v2y * dx) / cross,
  2342. u2 = (v1x * dy - v1y * dx) / cross,
  2343. epsilon = 1e-12,
  2344. uMin = -epsilon,
  2345. uMax = 1 + epsilon;
  2346. if (isInfinite
  2347. || uMin < u1 && u1 < uMax && uMin < u2 && u2 < uMax) {
  2348. if (!isInfinite) {
  2349. u1 = u1 <= 0 ? 0 : u1 >= 1 ? 1 : u1;
  2350. }
  2351. return new Point(
  2352. p1x + u1 * v1x,
  2353. p1y + u1 * v1y);
  2354. }
  2355. }
  2356. },
  2357. getSide: function(px, py, vx, vy, x, y, asVector, isInfinite) {
  2358. if (!asVector) {
  2359. vx -= px;
  2360. vy -= py;
  2361. }
  2362. var v2x = x - px,
  2363. v2y = y - py,
  2364. ccw = v2x * vy - v2y * vx;
  2365. if (!isInfinite && Numerical.isZero(ccw)) {
  2366. ccw = (v2x * vx + v2x * vx) / (vx * vx + vy * vy);
  2367. if (ccw >= 0 && ccw <= 1)
  2368. ccw = 0;
  2369. }
  2370. return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
  2371. },
  2372. getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
  2373. if (!asVector) {
  2374. vx -= px;
  2375. vy -= py;
  2376. }
  2377. return vx === 0 ? vy > 0 ? x - px : px - x
  2378. : vy === 0 ? vx < 0 ? y - py : py - y
  2379. : ((x-px) * vy - (y-py) * vx) / Math.sqrt(vx * vx + vy * vy);
  2380. },
  2381. getDistance: function(px, py, vx, vy, x, y, asVector) {
  2382. return Math.abs(
  2383. Line.getSignedDistance(px, py, vx, vy, x, y, asVector));
  2384. }
  2385. }
  2386. });
  2387. var Project = PaperScopeItem.extend({
  2388. _class: 'Project',
  2389. _list: 'projects',
  2390. _reference: 'project',
  2391. _compactSerialize: true,
  2392. initialize: function Project(element) {
  2393. PaperScopeItem.call(this, true);
  2394. this._children = [];
  2395. this._namedChildren = {};
  2396. this._activeLayer = null;
  2397. this._currentStyle = new Style(null, null, this);
  2398. this._view = View.create(this,
  2399. element || CanvasProvider.getCanvas(1, 1));
  2400. this._selectionItems = {};
  2401. this._selectionCount = 0;
  2402. this._updateVersion = 0;
  2403. },
  2404. _serialize: function(options, dictionary) {
  2405. return Base.serialize(this._children, options, true, dictionary);
  2406. },
  2407. _changed: function(flags, item) {
  2408. if (flags & 1) {
  2409. var view = this._view;
  2410. if (view) {
  2411. view._needsUpdate = true;
  2412. if (!view._requested && view._autoUpdate)
  2413. view.requestUpdate();
  2414. }
  2415. }
  2416. var changes = this._changes;
  2417. if (changes && item) {
  2418. var changesById = this._changesById,
  2419. id = item._id,
  2420. entry = changesById[id];
  2421. if (entry) {
  2422. entry.flags |= flags;
  2423. } else {
  2424. changes.push(changesById[id] = { item: item, flags: flags });
  2425. }
  2426. }
  2427. },
  2428. clear: function() {
  2429. var children = this._children;
  2430. for (var i = children.length - 1; i >= 0; i--)
  2431. children[i].remove();
  2432. },
  2433. isEmpty: function() {
  2434. return !this._children.length;
  2435. },
  2436. remove: function remove() {
  2437. if (!remove.base.call(this))
  2438. return false;
  2439. if (this._view)
  2440. this._view.remove();
  2441. return true;
  2442. },
  2443. getView: function() {
  2444. return this._view;
  2445. },
  2446. getCurrentStyle: function() {
  2447. return this._currentStyle;
  2448. },
  2449. setCurrentStyle: function(style) {
  2450. this._currentStyle.set(style);
  2451. },
  2452. getIndex: function() {
  2453. return this._index;
  2454. },
  2455. getOptions: function() {
  2456. return this._scope.settings;
  2457. },
  2458. getLayers: function() {
  2459. return this._children;
  2460. },
  2461. getActiveLayer: function() {
  2462. return this._activeLayer || new Layer({ project: this, insert: true });
  2463. },
  2464. getSymbolDefinitions: function() {
  2465. var definitions = [],
  2466. ids = {};
  2467. this.getItems({
  2468. class: SymbolItem,
  2469. match: function(item) {
  2470. var definition = item._definition,
  2471. id = definition._id;
  2472. if (!ids[id]) {
  2473. ids[id] = true;
  2474. definitions.push(definition);
  2475. }
  2476. return false;
  2477. }
  2478. });
  2479. return definitions;
  2480. },
  2481. getSymbols: 'getSymbolDefinitions',
  2482. getSelectedItems: function() {
  2483. var selectionItems = this._selectionItems,
  2484. items = [];
  2485. for (var id in selectionItems) {
  2486. var item = selectionItems[id],
  2487. selection = item._selection;
  2488. if ((selection & 1) && item.isInserted()) {
  2489. items.push(item);
  2490. } else if (!selection) {
  2491. this._updateSelection(item);
  2492. }
  2493. }
  2494. return items;
  2495. },
  2496. _updateSelection: function(item) {
  2497. var id = item._id,
  2498. selectionItems = this._selectionItems;
  2499. if (item._selection) {
  2500. if (selectionItems[id] !== item) {
  2501. this._selectionCount++;
  2502. selectionItems[id] = item;
  2503. }
  2504. } else if (selectionItems[id] === item) {
  2505. this._selectionCount--;
  2506. delete selectionItems[id];
  2507. }
  2508. },
  2509. selectAll: function() {
  2510. var children = this._children;
  2511. for (var i = 0, l = children.length; i < l; i++)
  2512. children[i].setFullySelected(true);
  2513. },
  2514. deselectAll: function() {
  2515. var selectionItems = this._selectionItems;
  2516. for (var i in selectionItems)
  2517. selectionItems[i].setFullySelected(false);
  2518. },
  2519. addLayer: function(layer) {
  2520. return this.insertLayer(undefined, layer);
  2521. },
  2522. insertLayer: function(index, layer) {
  2523. if (layer instanceof Layer) {
  2524. layer._remove(false, true);
  2525. Base.splice(this._children, [layer], index, 0);
  2526. layer._setProject(this, true);
  2527. var name = layer._name;
  2528. if (name)
  2529. layer.setName(name);
  2530. if (this._changes)
  2531. layer._changed(5);
  2532. if (!this._activeLayer)
  2533. this._activeLayer = layer;
  2534. } else {
  2535. layer = null;
  2536. }
  2537. return layer;
  2538. },
  2539. _insertItem: function(index, item, _created) {
  2540. item = this.insertLayer(index, item)
  2541. || (this._activeLayer || this._insertItem(undefined,
  2542. new Layer(Item.NO_INSERT), true))
  2543. .insertChild(index, item);
  2544. if (_created && item.activate)
  2545. item.activate();
  2546. return item;
  2547. },
  2548. getItems: function(options) {
  2549. return Item._getItems(this, options);
  2550. },
  2551. getItem: function(options) {
  2552. return Item._getItems(this, options, null, null, true)[0] || null;
  2553. },
  2554. importJSON: function(json) {
  2555. this.activate();
  2556. var layer = this._activeLayer;
  2557. return Base.importJSON(json, layer && layer.isEmpty() && layer);
  2558. },
  2559. removeOn: function(type) {
  2560. var sets = this._removeSets;
  2561. if (sets) {
  2562. if (type === 'mouseup')
  2563. sets.mousedrag = null;
  2564. var set = sets[type];
  2565. if (set) {
  2566. for (var id in set) {
  2567. var item = set[id];
  2568. for (var key in sets) {
  2569. var other = sets[key];
  2570. if (other && other != set)
  2571. delete other[item._id];
  2572. }
  2573. item.remove();
  2574. }
  2575. sets[type] = null;
  2576. }
  2577. }
  2578. },
  2579. draw: function(ctx, matrix, pixelRatio) {
  2580. this._updateVersion++;
  2581. ctx.save();
  2582. matrix.applyToContext(ctx);
  2583. var children = this._children,
  2584. param = new Base({
  2585. offset: new Point(0, 0),
  2586. pixelRatio: pixelRatio,
  2587. viewMatrix: matrix.isIdentity() ? null : matrix,
  2588. matrices: [new Matrix()],
  2589. updateMatrix: true
  2590. });
  2591. for (var i = 0, l = children.length; i < l; i++) {
  2592. children[i].draw(ctx, param);
  2593. }
  2594. ctx.restore();
  2595. if (this._selectionCount > 0) {
  2596. ctx.save();
  2597. ctx.strokeWidth = 1;
  2598. var items = this._selectionItems,
  2599. size = this._scope.settings.handleSize,
  2600. version = this._updateVersion;
  2601. for (var id in items) {
  2602. items[id]._drawSelection(ctx, matrix, size, items, version);
  2603. }
  2604. ctx.restore();
  2605. }
  2606. }
  2607. });
  2608. var Item = Base.extend(Emitter, {
  2609. statics: {
  2610. extend: function extend(src) {
  2611. if (src._serializeFields)
  2612. src._serializeFields = Base.set({},
  2613. this.prototype._serializeFields, src._serializeFields);
  2614. return extend.base.apply(this, arguments);
  2615. },
  2616. NO_INSERT: { insert: false }
  2617. },
  2618. _class: 'Item',
  2619. _name: null,
  2620. _applyMatrix: true,
  2621. _canApplyMatrix: true,
  2622. _canScaleStroke: false,
  2623. _pivot: null,
  2624. _visible: true,
  2625. _blendMode: 'normal',
  2626. _opacity: 1,
  2627. _locked: false,
  2628. _guide: false,
  2629. _clipMask: false,
  2630. _selection: 0,
  2631. _selectBounds: true,
  2632. _selectChildren: false,
  2633. _serializeFields: {
  2634. name: null,
  2635. applyMatrix: null,
  2636. matrix: new Matrix(),
  2637. pivot: null,
  2638. visible: true,
  2639. blendMode: 'normal',
  2640. opacity: 1,
  2641. locked: false,
  2642. guide: false,
  2643. clipMask: false,
  2644. selected: false,
  2645. data: {}
  2646. },
  2647. _prioritize: ['applyMatrix']
  2648. },
  2649. new function() {
  2650. var handlers = ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
  2651. 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'];
  2652. return Base.each(handlers,
  2653. function(name) {
  2654. this._events[name] = {
  2655. install: function(type) {
  2656. this.getView()._countItemEvent(type, 1);
  2657. },
  2658. uninstall: function(type) {
  2659. this.getView()._countItemEvent(type, -1);
  2660. }
  2661. };
  2662. }, {
  2663. _events: {
  2664. onFrame: {
  2665. install: function() {
  2666. this.getView()._animateItem(this, true);
  2667. },
  2668. uninstall: function() {
  2669. this.getView()._animateItem(this, false);
  2670. }
  2671. },
  2672. onLoad: {},
  2673. onError: {}
  2674. },
  2675. statics: {
  2676. _itemHandlers: handlers
  2677. }
  2678. }
  2679. );
  2680. }, {
  2681. initialize: function Item() {
  2682. },
  2683. _initialize: function(props, point) {
  2684. var hasProps = props && Base.isPlainObject(props),
  2685. internal = hasProps && props.internal === true,
  2686. matrix = this._matrix = new Matrix(),
  2687. project = hasProps && props.project || paper.project,
  2688. settings = paper.settings;
  2689. this._id = internal ? null : UID.get();
  2690. this._parent = this._index = null;
  2691. this._applyMatrix = this._canApplyMatrix && settings.applyMatrix;
  2692. if (point)
  2693. matrix.translate(point);
  2694. matrix._owner = this;
  2695. this._style = new Style(project._currentStyle, this, project);
  2696. if (internal || hasProps && props.insert == false
  2697. || !settings.insertItems && !(hasProps && props.insert === true)) {
  2698. this._setProject(project);
  2699. } else {
  2700. (hasProps && props.parent || project)
  2701. ._insertItem(undefined, this, true);
  2702. }
  2703. if (hasProps && props !== Item.NO_INSERT) {
  2704. this.set(props, {
  2705. internal: true, insert: true, project: true, parent: true
  2706. });
  2707. }
  2708. return hasProps;
  2709. },
  2710. _serialize: function(options, dictionary) {
  2711. var props = {},
  2712. that = this;
  2713. function serialize(fields) {
  2714. for (var key in fields) {
  2715. var value = that[key];
  2716. if (!Base.equals(value, key === 'leading'
  2717. ? fields.fontSize * 1.2 : fields[key])) {
  2718. props[key] = Base.serialize(value, options,
  2719. key !== 'data', dictionary);
  2720. }
  2721. }
  2722. }
  2723. serialize(this._serializeFields);
  2724. if (!(this instanceof Group))
  2725. serialize(this._style._defaults);
  2726. return [ this._class, props ];
  2727. },
  2728. _changed: function(flags) {
  2729. var symbol = this._symbol,
  2730. cacheParent = this._parent || symbol,
  2731. project = this._project;
  2732. if (flags & 8) {
  2733. this._bounds = this._position = this._decomposed = undefined;
  2734. }
  2735. if (flags & 16) {
  2736. this._globalMatrix = undefined;
  2737. }
  2738. if (cacheParent
  2739. && (flags & 72)) {
  2740. Item._clearBoundsCache(cacheParent);
  2741. }
  2742. if (flags & 2) {
  2743. Item._clearBoundsCache(this);
  2744. }
  2745. if (project)
  2746. project._changed(flags, this);
  2747. if (symbol)
  2748. symbol._changed(flags);
  2749. },
  2750. getId: function() {
  2751. return this._id;
  2752. },
  2753. getName: function() {
  2754. return this._name;
  2755. },
  2756. setName: function(name) {
  2757. if (this._name)
  2758. this._removeNamed();
  2759. if (name === (+name) + '')
  2760. throw new Error(
  2761. 'Names consisting only of numbers are not supported.');
  2762. var owner = this._getOwner();
  2763. if (name && owner) {
  2764. var children = owner._children,
  2765. namedChildren = owner._namedChildren;
  2766. (namedChildren[name] = namedChildren[name] || []).push(this);
  2767. if (!(name in children))
  2768. children[name] = this;
  2769. }
  2770. this._name = name || undefined;
  2771. this._changed(256);
  2772. },
  2773. getStyle: function() {
  2774. return this._style;
  2775. },
  2776. setStyle: function(style) {
  2777. this.getStyle().set(style);
  2778. }
  2779. }, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
  2780. function(name) {
  2781. var part = Base.capitalize(name),
  2782. key = '_' + name,
  2783. flags = {
  2784. locked: 256,
  2785. visible: 265
  2786. };
  2787. this['get' + part] = function() {
  2788. return this[key];
  2789. };
  2790. this['set' + part] = function(value) {
  2791. if (value != this[key]) {
  2792. this[key] = value;
  2793. this._changed(flags[name] || 257);
  2794. }
  2795. };
  2796. },
  2797. {}), {
  2798. beans: true,
  2799. getSelection: function() {
  2800. return this._selection;
  2801. },
  2802. setSelection: function(selection) {
  2803. if (selection !== this._selection) {
  2804. this._selection = selection;
  2805. var project = this._project;
  2806. if (project) {
  2807. project._updateSelection(this);
  2808. this._changed(257);
  2809. }
  2810. }
  2811. },
  2812. _changeSelection: function(flag, selected) {
  2813. var selection = this._selection;
  2814. this.setSelection(selected ? selection | flag : selection & ~flag);
  2815. },
  2816. isSelected: function() {
  2817. if (this._selectChildren) {
  2818. var children = this._children;
  2819. for (var i = 0, l = children.length; i < l; i++)
  2820. if (children[i].isSelected())
  2821. return true;
  2822. }
  2823. return !!(this._selection & 1);
  2824. },
  2825. setSelected: function(selected) {
  2826. if (this._selectChildren) {
  2827. var children = this._children;
  2828. for (var i = 0, l = children.length; i < l; i++)
  2829. children[i].setSelected(selected);
  2830. }
  2831. this._changeSelection(1, selected);
  2832. },
  2833. isFullySelected: function() {
  2834. var children = this._children,
  2835. selected = !!(this._selection & 1);
  2836. if (children && selected) {
  2837. for (var i = 0, l = children.length; i < l; i++)
  2838. if (!children[i].isFullySelected())
  2839. return false;
  2840. return true;
  2841. }
  2842. return selected;
  2843. },
  2844. setFullySelected: function(selected) {
  2845. var children = this._children;
  2846. if (children) {
  2847. for (var i = 0, l = children.length; i < l; i++)
  2848. children[i].setFullySelected(selected);
  2849. }
  2850. this._changeSelection(1, selected);
  2851. },
  2852. isClipMask: function() {
  2853. return this._clipMask;
  2854. },
  2855. setClipMask: function(clipMask) {
  2856. if (this._clipMask != (clipMask = !!clipMask)) {
  2857. this._clipMask = clipMask;
  2858. if (clipMask) {
  2859. this.setFillColor(null);
  2860. this.setStrokeColor(null);
  2861. }
  2862. this._changed(257);
  2863. if (this._parent)
  2864. this._parent._changed(2048);
  2865. }
  2866. },
  2867. getData: function() {
  2868. if (!this._data)
  2869. this._data = {};
  2870. return this._data;
  2871. },
  2872. setData: function(data) {
  2873. this._data = data;
  2874. },
  2875. getPosition: function(_dontLink) {
  2876. var ctor = _dontLink ? Point : LinkedPoint;
  2877. var position = this._position ||
  2878. (this._position = this._getPositionFromBounds());
  2879. return new ctor(position.x, position.y, this, 'setPosition');
  2880. },
  2881. setPosition: function() {
  2882. this.translate(Point.read(arguments).subtract(this.getPosition(true)));
  2883. },
  2884. _getPositionFromBounds: function(bounds) {
  2885. return this._pivot
  2886. ? this._matrix._transformPoint(this._pivot)
  2887. : (bounds || this.getBounds()).getCenter(true);
  2888. },
  2889. getPivot: function() {
  2890. var pivot = this._pivot;
  2891. return pivot
  2892. ? new LinkedPoint(pivot.x, pivot.y, this, 'setPivot')
  2893. : null;
  2894. },
  2895. setPivot: function() {
  2896. this._pivot = Point.read(arguments, 0, { clone: true, readNull: true });
  2897. this._position = undefined;
  2898. }
  2899. }, Base.each({
  2900. getStrokeBounds: { stroke: true },
  2901. getHandleBounds: { handle: true },
  2902. getInternalBounds: { internal: true }
  2903. },
  2904. function(options, key) {
  2905. this[key] = function(matrix) {
  2906. return this.getBounds(matrix, options);
  2907. };
  2908. },
  2909. {
  2910. beans: true,
  2911. getBounds: function(matrix, options) {
  2912. var hasMatrix = options || matrix instanceof Matrix,
  2913. opts = Base.set({}, hasMatrix ? options : matrix,
  2914. this._boundsOptions);
  2915. if (!opts.stroke || this.getStrokeScaling())
  2916. opts.cacheItem = this;
  2917. var rect = this._getCachedBounds(hasMatrix && matrix, opts).rect;
  2918. return !arguments.length
  2919. ? new LinkedRectangle(rect.x, rect.y, rect.width, rect.height,
  2920. this, 'setBounds')
  2921. : rect;
  2922. },
  2923. setBounds: function() {
  2924. var rect = Rectangle.read(arguments),
  2925. bounds = this.getBounds(),
  2926. _matrix = this._matrix,
  2927. matrix = new Matrix(),
  2928. center = rect.getCenter();
  2929. matrix.translate(center);
  2930. if (rect.width != bounds.width || rect.height != bounds.height) {
  2931. if (!_matrix.isInvertible()) {
  2932. _matrix.set(_matrix._backup
  2933. || new Matrix().translate(_matrix.getTranslation()));
  2934. bounds = this.getBounds();
  2935. }
  2936. matrix.scale(
  2937. bounds.width !== 0 ? rect.width / bounds.width : 0,
  2938. bounds.height !== 0 ? rect.height / bounds.height : 0);
  2939. }
  2940. center = bounds.getCenter();
  2941. matrix.translate(-center.x, -center.y);
  2942. this.transform(matrix);
  2943. },
  2944. _getBounds: function(matrix, options) {
  2945. var children = this._children;
  2946. if (!children || !children.length)
  2947. return new Rectangle();
  2948. Item._updateBoundsCache(this, options.cacheItem);
  2949. return Item._getBounds(children, matrix, options);
  2950. },
  2951. _getBoundsCacheKey: function(options, internal) {
  2952. return [
  2953. options.stroke ? 1 : 0,
  2954. options.handle ? 1 : 0,
  2955. internal ? 1 : 0
  2956. ].join('');
  2957. },
  2958. _getCachedBounds: function(matrix, options, noInternal) {
  2959. matrix = matrix && matrix._orNullIfIdentity();
  2960. var internal = options.internal && !noInternal,
  2961. cacheItem = options.cacheItem,
  2962. _matrix = internal ? null : this._matrix._orNullIfIdentity(),
  2963. cacheKey = cacheItem && (!matrix || matrix.equals(_matrix))
  2964. && this._getBoundsCacheKey(options, internal),
  2965. bounds = this._bounds;
  2966. Item._updateBoundsCache(this._parent || this._symbol, cacheItem);
  2967. if (cacheKey && bounds && cacheKey in bounds) {
  2968. var cached = bounds[cacheKey];
  2969. return {
  2970. rect: cached.rect.clone(),
  2971. nonscaling: cached.nonscaling
  2972. };
  2973. }
  2974. var res = this._getBounds(matrix || _matrix, options),
  2975. rect = res.rect || res,
  2976. style = this._style,
  2977. nonscaling = res.nonscaling || style.hasStroke()
  2978. && !style.getStrokeScaling();
  2979. if (cacheKey) {
  2980. if (!bounds) {
  2981. this._bounds = bounds = {};
  2982. }
  2983. var cached = bounds[cacheKey] = {
  2984. rect: rect.clone(),
  2985. nonscaling: nonscaling,
  2986. internal: internal
  2987. };
  2988. }
  2989. return {
  2990. rect: rect,
  2991. nonscaling: nonscaling
  2992. };
  2993. },
  2994. _getStrokeMatrix: function(matrix, options) {
  2995. var parent = this.getStrokeScaling() ? null
  2996. : options && options.internal ? this
  2997. : this._parent || this._symbol && this._symbol._item,
  2998. mx = parent ? parent.getViewMatrix().invert() : matrix;
  2999. return mx && mx._shiftless();
  3000. },
  3001. statics: {
  3002. _updateBoundsCache: function(parent, item) {
  3003. if (parent && item) {
  3004. var id = item._id,
  3005. ref = parent._boundsCache = parent._boundsCache || {
  3006. ids: {},
  3007. list: []
  3008. };
  3009. if (!ref.ids[id]) {
  3010. ref.list.push(item);
  3011. ref.ids[id] = item;
  3012. }
  3013. }
  3014. },
  3015. _clearBoundsCache: function(item) {
  3016. var cache = item._boundsCache;
  3017. if (cache) {
  3018. item._bounds = item._position = item._boundsCache = undefined;
  3019. for (var i = 0, list = cache.list, l = list.length; i < l; i++){
  3020. var other = list[i];
  3021. if (other !== item) {
  3022. other._bounds = other._position = undefined;
  3023. if (other._boundsCache)
  3024. Item._clearBoundsCache(other);
  3025. }
  3026. }
  3027. }
  3028. },
  3029. _getBounds: function(items, matrix, options) {
  3030. var x1 = Infinity,
  3031. x2 = -x1,
  3032. y1 = x1,
  3033. y2 = x2,
  3034. nonscaling = false;
  3035. options = options || {};
  3036. for (var i = 0, l = items.length; i < l; i++) {
  3037. var item = items[i];
  3038. if (item._visible && !item.isEmpty()) {
  3039. var bounds = item._getCachedBounds(
  3040. matrix && matrix.appended(item._matrix), options, true),
  3041. rect = bounds.rect;
  3042. x1 = Math.min(rect.x, x1);
  3043. y1 = Math.min(rect.y, y1);
  3044. x2 = Math.max(rect.x + rect.width, x2);
  3045. y2 = Math.max(rect.y + rect.height, y2);
  3046. if (bounds.nonscaling)
  3047. nonscaling = true;
  3048. }
  3049. }
  3050. return {
  3051. rect: isFinite(x1)
  3052. ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
  3053. : new Rectangle(),
  3054. nonscaling: nonscaling
  3055. };
  3056. }
  3057. }
  3058. }), {
  3059. beans: true,
  3060. _decompose: function() {
  3061. return this._applyMatrix
  3062. ? null
  3063. : this._decomposed || (this._decomposed = this._matrix.decompose());
  3064. },
  3065. getRotation: function() {
  3066. var decomposed = this._decompose();
  3067. return decomposed ? decomposed.rotation : 0;
  3068. },
  3069. setRotation: function(rotation) {
  3070. var current = this.getRotation();
  3071. if (current != null && rotation != null) {
  3072. var decomposed = this._decomposed;
  3073. this.rotate(rotation - current);
  3074. if (decomposed) {
  3075. decomposed.rotation = rotation;
  3076. this._decomposed = decomposed;
  3077. }
  3078. }
  3079. },
  3080. getScaling: function() {
  3081. var decomposed = this._decompose(),
  3082. s = decomposed && decomposed.scaling;
  3083. return new LinkedPoint(s ? s.x : 1, s ? s.y : 1, this, 'setScaling');
  3084. },
  3085. setScaling: function() {
  3086. var current = this.getScaling(),
  3087. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  3088. if (current && scaling && !current.equals(scaling)) {
  3089. var rotation = this.getRotation(),
  3090. decomposed = this._decomposed,
  3091. matrix = new Matrix(),
  3092. center = this.getPosition(true);
  3093. matrix.translate(center);
  3094. if (rotation)
  3095. matrix.rotate(rotation);
  3096. matrix.scale(scaling.x / current.x, scaling.y / current.y);
  3097. if (rotation)
  3098. matrix.rotate(-rotation);
  3099. matrix.translate(center.negate());
  3100. this.transform(matrix);
  3101. if (decomposed) {
  3102. decomposed.scaling = scaling;
  3103. this._decomposed = decomposed;
  3104. }
  3105. }
  3106. },
  3107. getMatrix: function() {
  3108. return this._matrix;
  3109. },
  3110. setMatrix: function() {
  3111. var matrix = this._matrix;
  3112. matrix.initialize.apply(matrix, arguments);
  3113. },
  3114. getGlobalMatrix: function(_dontClone) {
  3115. var matrix = this._globalMatrix;
  3116. if (matrix) {
  3117. var parent = this._parent;
  3118. var parents = [];
  3119. while (parent) {
  3120. if (!parent._globalMatrix) {
  3121. matrix = null;
  3122. for (var i = 0, l = parents.length; i < l; i++) {
  3123. parents[i]._globalMatrix = null;
  3124. }
  3125. break;
  3126. }
  3127. parents.push(parent);
  3128. parent = parent._parent;
  3129. }
  3130. }
  3131. if (!matrix) {
  3132. matrix = this._globalMatrix = this._matrix.clone();
  3133. var parent = this._parent;
  3134. if (parent)
  3135. matrix.prepend(parent.getGlobalMatrix(true));
  3136. }
  3137. return _dontClone ? matrix : matrix.clone();
  3138. },
  3139. getViewMatrix: function() {
  3140. return this.getGlobalMatrix().prepend(this.getView()._matrix);
  3141. },
  3142. getApplyMatrix: function() {
  3143. return this._applyMatrix;
  3144. },
  3145. setApplyMatrix: function(apply) {
  3146. if (this._applyMatrix = this._canApplyMatrix && !!apply)
  3147. this.transform(null, true);
  3148. },
  3149. getTransformContent: '#getApplyMatrix',
  3150. setTransformContent: '#setApplyMatrix',
  3151. }, {
  3152. getProject: function() {
  3153. return this._project;
  3154. },
  3155. _setProject: function(project, installEvents) {
  3156. if (this._project !== project) {
  3157. if (this._project)
  3158. this._installEvents(false);
  3159. this._project = project;
  3160. var children = this._children;
  3161. for (var i = 0, l = children && children.length; i < l; i++)
  3162. children[i]._setProject(project);
  3163. installEvents = true;
  3164. }
  3165. if (installEvents)
  3166. this._installEvents(true);
  3167. },
  3168. getView: function() {
  3169. return this._project._view;
  3170. },
  3171. _installEvents: function _installEvents(install) {
  3172. _installEvents.base.call(this, install);
  3173. var children = this._children;
  3174. for (var i = 0, l = children && children.length; i < l; i++)
  3175. children[i]._installEvents(install);
  3176. },
  3177. getLayer: function() {
  3178. var parent = this;
  3179. while (parent = parent._parent) {
  3180. if (parent instanceof Layer)
  3181. return parent;
  3182. }
  3183. return null;
  3184. },
  3185. getParent: function() {
  3186. return this._parent;
  3187. },
  3188. setParent: function(item) {
  3189. return item.addChild(this);
  3190. },
  3191. _getOwner: '#getParent',
  3192. getChildren: function() {
  3193. return this._children;
  3194. },
  3195. setChildren: function(items) {
  3196. this.removeChildren();
  3197. this.addChildren(items);
  3198. },
  3199. getFirstChild: function() {
  3200. return this._children && this._children[0] || null;
  3201. },
  3202. getLastChild: function() {
  3203. return this._children && this._children[this._children.length - 1]
  3204. || null;
  3205. },
  3206. getNextSibling: function() {
  3207. var owner = this._getOwner();
  3208. return owner && owner._children[this._index + 1] || null;
  3209. },
  3210. getPreviousSibling: function() {
  3211. var owner = this._getOwner();
  3212. return owner && owner._children[this._index - 1] || null;
  3213. },
  3214. getIndex: function() {
  3215. return this._index;
  3216. },
  3217. equals: function(item) {
  3218. return item === this || item && this._class === item._class
  3219. && this._style.equals(item._style)
  3220. && this._matrix.equals(item._matrix)
  3221. && this._locked === item._locked
  3222. && this._visible === item._visible
  3223. && this._blendMode === item._blendMode
  3224. && this._opacity === item._opacity
  3225. && this._clipMask === item._clipMask
  3226. && this._guide === item._guide
  3227. && this._equals(item)
  3228. || false;
  3229. },
  3230. _equals: function(item) {
  3231. return Base.equals(this._children, item._children);
  3232. },
  3233. clone: function(options) {
  3234. var copy = new this.constructor(Item.NO_INSERT),
  3235. children = this._children,
  3236. insert = Base.pick(options ? options.insert : undefined,
  3237. options === undefined || options === true),
  3238. deep = Base.pick(options ? options.deep : undefined, true);
  3239. if (children)
  3240. copy.copyAttributes(this);
  3241. if (!children || deep)
  3242. copy.copyContent(this);
  3243. if (!children)
  3244. copy.copyAttributes(this);
  3245. if (insert)
  3246. copy.insertAbove(this);
  3247. var name = this._name,
  3248. parent = this._parent;
  3249. if (name && parent) {
  3250. var children = parent._children,
  3251. orig = name,
  3252. i = 1;
  3253. while (children[name])
  3254. name = orig + ' ' + (i++);
  3255. if (name !== orig)
  3256. copy.setName(name);
  3257. }
  3258. return copy;
  3259. },
  3260. copyContent: function(source) {
  3261. var children = source._children;
  3262. for (var i = 0, l = children && children.length; i < l; i++) {
  3263. this.addChild(children[i].clone(false), true);
  3264. }
  3265. },
  3266. copyAttributes: function(source, excludeMatrix) {
  3267. this.setStyle(source._style);
  3268. var keys = ['_locked', '_visible', '_blendMode', '_opacity',
  3269. '_clipMask', '_guide'];
  3270. for (var i = 0, l = keys.length; i < l; i++) {
  3271. var key = keys[i];
  3272. if (source.hasOwnProperty(key))
  3273. this[key] = source[key];
  3274. }
  3275. if (!excludeMatrix)
  3276. this._matrix.set(source._matrix, true);
  3277. this.setApplyMatrix(source._applyMatrix);
  3278. this.setPivot(source._pivot);
  3279. this.setSelection(source._selection);
  3280. var data = source._data,
  3281. name = source._name;
  3282. this._data = data ? Base.clone(data) : null;
  3283. if (name)
  3284. this.setName(name);
  3285. },
  3286. rasterize: function(resolution, insert) {
  3287. var bounds = this.getStrokeBounds(),
  3288. scale = (resolution || this.getView().getResolution()) / 72,
  3289. topLeft = bounds.getTopLeft().floor(),
  3290. bottomRight = bounds.getBottomRight().ceil(),
  3291. size = new Size(bottomRight.subtract(topLeft)),
  3292. raster = new Raster(Item.NO_INSERT);
  3293. if (!size.isZero()) {
  3294. var canvas = CanvasProvider.getCanvas(size.multiply(scale)),
  3295. ctx = canvas.getContext('2d'),
  3296. matrix = new Matrix().scale(scale).translate(topLeft.negate());
  3297. ctx.save();
  3298. matrix.applyToContext(ctx);
  3299. this.draw(ctx, new Base({ matrices: [matrix] }));
  3300. ctx.restore();
  3301. raster.setCanvas(canvas);
  3302. }
  3303. raster.transform(new Matrix().translate(topLeft.add(size.divide(2)))
  3304. .scale(1 / scale));
  3305. if (insert === undefined || insert)
  3306. raster.insertAbove(this);
  3307. return raster;
  3308. },
  3309. contains: function() {
  3310. return !!this._contains(
  3311. this._matrix._inverseTransform(Point.read(arguments)));
  3312. },
  3313. _contains: function(point) {
  3314. var children = this._children;
  3315. if (children) {
  3316. for (var i = children.length - 1; i >= 0; i--) {
  3317. if (children[i].contains(point))
  3318. return true;
  3319. }
  3320. return false;
  3321. }
  3322. return point.isInside(this.getInternalBounds());
  3323. },
  3324. isInside: function() {
  3325. return Rectangle.read(arguments).contains(this.getBounds());
  3326. },
  3327. _asPathItem: function() {
  3328. return new Path.Rectangle({
  3329. rectangle: this.getInternalBounds(),
  3330. matrix: this._matrix,
  3331. insert: false,
  3332. });
  3333. },
  3334. intersects: function(item, _matrix) {
  3335. if (!(item instanceof Item))
  3336. return false;
  3337. return this._asPathItem().getIntersections(item._asPathItem(), null,
  3338. _matrix, true).length > 0;
  3339. }
  3340. },
  3341. new function() {
  3342. function hitTest() {
  3343. return this._hitTest(
  3344. Point.read(arguments),
  3345. HitResult.getOptions(arguments));
  3346. }
  3347. function hitTestAll() {
  3348. var point = Point.read(arguments),
  3349. options = HitResult.getOptions(arguments),
  3350. all = [];
  3351. this._hitTest(point, Base.set({ all: all }, options));
  3352. return all;
  3353. }
  3354. function hitTestChildren(point, options, viewMatrix, _exclude) {
  3355. var children = this._children;
  3356. if (children) {
  3357. for (var i = children.length - 1; i >= 0; i--) {
  3358. var child = children[i];
  3359. var res = child !== _exclude && child._hitTest(point, options,
  3360. viewMatrix);
  3361. if (res && !options.all)
  3362. return res;
  3363. }
  3364. }
  3365. return null;
  3366. }
  3367. Project.inject({
  3368. hitTest: hitTest,
  3369. hitTestAll: hitTestAll,
  3370. _hitTest: hitTestChildren
  3371. });
  3372. return {
  3373. hitTest: hitTest,
  3374. hitTestAll: hitTestAll,
  3375. _hitTestChildren: hitTestChildren,
  3376. };
  3377. }, {
  3378. _hitTest: function(point, options, parentViewMatrix) {
  3379. if (this._locked || !this._visible || this._guide && !options.guides
  3380. || this.isEmpty()) {
  3381. return null;
  3382. }
  3383. var matrix = this._matrix,
  3384. viewMatrix = parentViewMatrix
  3385. ? parentViewMatrix.appended(matrix)
  3386. : this.getGlobalMatrix().prepend(this.getView()._matrix),
  3387. tolerance = Math.max(options.tolerance, 1e-12),
  3388. tolerancePadding = options._tolerancePadding = new Size(
  3389. Path._getStrokePadding(tolerance,
  3390. matrix._shiftless().invert()));
  3391. point = matrix._inverseTransform(point);
  3392. if (!point || !this._children &&
  3393. !this.getBounds({ internal: true, stroke: true, handle: true })
  3394. .expand(tolerancePadding.multiply(2))._containsPoint(point)) {
  3395. return null;
  3396. }
  3397. var checkSelf = !(options.guides && !this._guide
  3398. || options.selected && !this.isSelected()
  3399. || options.type && options.type !== Base.hyphenate(this._class)
  3400. || options.class && !(this instanceof options.class)),
  3401. match = options.match,
  3402. that = this,
  3403. bounds,
  3404. res;
  3405. function filter(hit) {
  3406. if (hit && match && !match(hit))
  3407. hit = null;
  3408. if (hit && options.all)
  3409. options.all.push(hit);
  3410. return hit;
  3411. }
  3412. function checkPoint(type, part) {
  3413. var pt = part ? bounds['get' + part]() : that.getPosition();
  3414. if (point.subtract(pt).divide(tolerancePadding).length <= 1) {
  3415. return new HitResult(type, that, {
  3416. name: part ? Base.hyphenate(part) : type,
  3417. point: pt
  3418. });
  3419. }
  3420. }
  3421. var checkPosition = options.position,
  3422. checkCenter = options.center,
  3423. checkBounds = options.bounds;
  3424. if (checkSelf && this._parent
  3425. && (checkPosition || checkCenter || checkBounds)) {
  3426. if (checkCenter || checkBounds) {
  3427. bounds = this.getInternalBounds();
  3428. }
  3429. res = checkPosition && checkPoint('position') ||
  3430. checkCenter && checkPoint('center', 'Center');
  3431. if (!res && checkBounds) {
  3432. var points = [
  3433. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  3434. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
  3435. ];
  3436. for (var i = 0; i < 8 && !res; i++) {
  3437. res = checkPoint('bounds', points[i]);
  3438. }
  3439. }
  3440. res = filter(res);
  3441. }
  3442. if (!res) {
  3443. res = this._hitTestChildren(point, options, viewMatrix)
  3444. || checkSelf
  3445. && filter(this._hitTestSelf(point, options, viewMatrix,
  3446. this.getStrokeScaling() ? null
  3447. : viewMatrix._shiftless().invert()))
  3448. || null;
  3449. }
  3450. if (res && res.point) {
  3451. res.point = matrix.transform(res.point);
  3452. }
  3453. return res;
  3454. },
  3455. _hitTestSelf: function(point, options) {
  3456. if (options.fill && this.hasFill() && this._contains(point))
  3457. return new HitResult('fill', this);
  3458. },
  3459. matches: function(name, compare) {
  3460. function matchObject(obj1, obj2) {
  3461. for (var i in obj1) {
  3462. if (obj1.hasOwnProperty(i)) {
  3463. var val1 = obj1[i],
  3464. val2 = obj2[i];
  3465. if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
  3466. if (!matchObject(val1, val2))
  3467. return false;
  3468. } else if (!Base.equals(val1, val2)) {
  3469. return false;
  3470. }
  3471. }
  3472. }
  3473. return true;
  3474. }
  3475. var type = typeof name;
  3476. if (type === 'object') {
  3477. for (var key in name) {
  3478. if (name.hasOwnProperty(key) && !this.matches(key, name[key]))
  3479. return false;
  3480. }
  3481. return true;
  3482. } else if (type === 'function') {
  3483. return name(this);
  3484. } else if (name === 'match') {
  3485. return compare(this);
  3486. } else {
  3487. var value = /^(empty|editable)$/.test(name)
  3488. ? this['is' + Base.capitalize(name)]()
  3489. : name === 'type'
  3490. ? Base.hyphenate(this._class)
  3491. : this[name];
  3492. if (name === 'class') {
  3493. if (typeof compare === 'function')
  3494. return this instanceof compare;
  3495. value = this._class;
  3496. }
  3497. if (typeof compare === 'function') {
  3498. return !!compare(value);
  3499. } else if (compare) {
  3500. if (compare.test) {
  3501. return compare.test(value);
  3502. } else if (Base.isPlainObject(compare)) {
  3503. return matchObject(compare, value);
  3504. }
  3505. }
  3506. return Base.equals(value, compare);
  3507. }
  3508. },
  3509. getItems: function(options) {
  3510. return Item._getItems(this, options, this._matrix);
  3511. },
  3512. getItem: function(options) {
  3513. return Item._getItems(this, options, this._matrix, null, true)[0]
  3514. || null;
  3515. },
  3516. statics: {
  3517. _getItems: function _getItems(item, options, matrix, param, firstOnly) {
  3518. if (!param) {
  3519. var obj = typeof options === 'object' && options,
  3520. overlapping = obj && obj.overlapping,
  3521. inside = obj && obj.inside,
  3522. bounds = overlapping || inside,
  3523. rect = bounds && Rectangle.read([bounds]);
  3524. param = {
  3525. items: [],
  3526. recursive: obj && obj.recursive !== false,
  3527. inside: !!inside,
  3528. overlapping: !!overlapping,
  3529. rect: rect,
  3530. path: overlapping && new Path.Rectangle({
  3531. rectangle: rect,
  3532. insert: false
  3533. })
  3534. };
  3535. if (obj) {
  3536. options = Base.filter({}, options, {
  3537. recursive: true, inside: true, overlapping: true
  3538. });
  3539. }
  3540. }
  3541. var children = item._children,
  3542. items = param.items,
  3543. rect = param.rect;
  3544. matrix = rect && (matrix || new Matrix());
  3545. for (var i = 0, l = children && children.length; i < l; i++) {
  3546. var child = children[i],
  3547. childMatrix = matrix && matrix.appended(child._matrix),
  3548. add = true;
  3549. if (rect) {
  3550. var bounds = child.getBounds(childMatrix);
  3551. if (!rect.intersects(bounds))
  3552. continue;
  3553. if (!(rect.contains(bounds)
  3554. || param.overlapping && (bounds.contains(rect)
  3555. || param.path.intersects(child, childMatrix))))
  3556. add = false;
  3557. }
  3558. if (add && child.matches(options)) {
  3559. items.push(child);
  3560. if (firstOnly)
  3561. break;
  3562. }
  3563. if (param.recursive !== false) {
  3564. _getItems(child, options, childMatrix, param, firstOnly);
  3565. }
  3566. if (firstOnly && items.length > 0)
  3567. break;
  3568. }
  3569. return items;
  3570. }
  3571. }
  3572. }, {
  3573. importJSON: function(json) {
  3574. var res = Base.importJSON(json, this);
  3575. return res !== this ? this.addChild(res) : res;
  3576. },
  3577. addChild: function(item) {
  3578. return this.insertChild(undefined, item);
  3579. },
  3580. insertChild: function(index, item) {
  3581. var res = item ? this.insertChildren(index, [item]) : null;
  3582. return res && res[0];
  3583. },
  3584. addChildren: function(items) {
  3585. return this.insertChildren(this._children.length, items);
  3586. },
  3587. insertChildren: function(index, items) {
  3588. var children = this._children;
  3589. if (children && items && items.length > 0) {
  3590. items = Base.slice(items);
  3591. var inserted = {};
  3592. for (var i = items.length - 1; i >= 0; i--) {
  3593. var item = items[i],
  3594. id = item && item._id;
  3595. if (!item || inserted[id]) {
  3596. items.splice(i, 1);
  3597. } else {
  3598. item._remove(false, true);
  3599. inserted[id] = true;
  3600. }
  3601. }
  3602. Base.splice(children, items, index, 0);
  3603. var project = this._project,
  3604. notifySelf = project._changes;
  3605. for (var i = 0, l = items.length; i < l; i++) {
  3606. var item = items[i],
  3607. name = item._name;
  3608. item._parent = this;
  3609. item._setProject(project, true);
  3610. if (name)
  3611. item.setName(name);
  3612. if (notifySelf)
  3613. item._changed(5);
  3614. }
  3615. this._changed(11);
  3616. } else {
  3617. items = null;
  3618. }
  3619. return items;
  3620. },
  3621. _insertItem: '#insertChild',
  3622. _insertAt: function(item, offset) {
  3623. var owner = item && item._getOwner(),
  3624. res = item !== this && owner ? this : null;
  3625. if (res) {
  3626. res._remove(false, true);
  3627. owner._insertItem(item._index + offset, res);
  3628. }
  3629. return res;
  3630. },
  3631. insertAbove: function(item) {
  3632. return this._insertAt(item, 1);
  3633. },
  3634. insertBelow: function(item) {
  3635. return this._insertAt(item, 0);
  3636. },
  3637. sendToBack: function() {
  3638. var owner = this._getOwner();
  3639. return owner ? owner._insertItem(0, this) : null;
  3640. },
  3641. bringToFront: function() {
  3642. var owner = this._getOwner();
  3643. return owner ? owner._insertItem(undefined, this) : null;
  3644. },
  3645. appendTop: '#addChild',
  3646. appendBottom: function(item) {
  3647. return this.insertChild(0, item);
  3648. },
  3649. moveAbove: '#insertAbove',
  3650. moveBelow: '#insertBelow',
  3651. addTo: function(owner) {
  3652. return owner._insertItem(undefined, this);
  3653. },
  3654. copyTo: function(owner) {
  3655. return this.clone(false).addTo(owner);
  3656. },
  3657. reduce: function(options) {
  3658. var children = this._children;
  3659. if (children && children.length === 1) {
  3660. var child = children[0].reduce(options);
  3661. if (this._parent) {
  3662. child.insertAbove(this);
  3663. this.remove();
  3664. } else {
  3665. child.remove();
  3666. }
  3667. return child;
  3668. }
  3669. return this;
  3670. },
  3671. _removeNamed: function() {
  3672. var owner = this._getOwner();
  3673. if (owner) {
  3674. var children = owner._children,
  3675. namedChildren = owner._namedChildren,
  3676. name = this._name,
  3677. namedArray = namedChildren[name],
  3678. index = namedArray ? namedArray.indexOf(this) : -1;
  3679. if (index !== -1) {
  3680. if (children[name] == this)
  3681. delete children[name];
  3682. namedArray.splice(index, 1);
  3683. if (namedArray.length) {
  3684. children[name] = namedArray[0];
  3685. } else {
  3686. delete namedChildren[name];
  3687. }
  3688. }
  3689. }
  3690. },
  3691. _remove: function(notifySelf, notifyParent) {
  3692. var owner = this._getOwner(),
  3693. project = this._project,
  3694. index = this._index;
  3695. if (this._style)
  3696. this._style._dispose();
  3697. if (owner) {
  3698. if (this._name)
  3699. this._removeNamed();
  3700. if (index != null) {
  3701. if (project._activeLayer === this)
  3702. project._activeLayer = this.getNextSibling()
  3703. || this.getPreviousSibling();
  3704. Base.splice(owner._children, null, index, 1);
  3705. }
  3706. this._installEvents(false);
  3707. if (notifySelf && project._changes)
  3708. this._changed(5);
  3709. if (notifyParent)
  3710. owner._changed(11, this);
  3711. this._parent = null;
  3712. return true;
  3713. }
  3714. return false;
  3715. },
  3716. remove: function() {
  3717. return this._remove(true, true);
  3718. },
  3719. replaceWith: function(item) {
  3720. var ok = item && item.insertBelow(this);
  3721. if (ok)
  3722. this.remove();
  3723. return ok;
  3724. },
  3725. removeChildren: function(start, end) {
  3726. if (!this._children)
  3727. return null;
  3728. start = start || 0;
  3729. end = Base.pick(end, this._children.length);
  3730. var removed = Base.splice(this._children, null, start, end - start);
  3731. for (var i = removed.length - 1; i >= 0; i--) {
  3732. removed[i]._remove(true, false);
  3733. }
  3734. if (removed.length > 0)
  3735. this._changed(11);
  3736. return removed;
  3737. },
  3738. clear: '#removeChildren',
  3739. reverseChildren: function() {
  3740. if (this._children) {
  3741. this._children.reverse();
  3742. for (var i = 0, l = this._children.length; i < l; i++)
  3743. this._children[i]._index = i;
  3744. this._changed(11);
  3745. }
  3746. },
  3747. isEmpty: function() {
  3748. var children = this._children;
  3749. return !children || !children.length;
  3750. },
  3751. isEditable: function() {
  3752. var item = this;
  3753. while (item) {
  3754. if (!item._visible || item._locked)
  3755. return false;
  3756. item = item._parent;
  3757. }
  3758. return true;
  3759. },
  3760. hasFill: function() {
  3761. return this.getStyle().hasFill();
  3762. },
  3763. hasStroke: function() {
  3764. return this.getStyle().hasStroke();
  3765. },
  3766. hasShadow: function() {
  3767. return this.getStyle().hasShadow();
  3768. },
  3769. _getOrder: function(item) {
  3770. function getList(item) {
  3771. var list = [];
  3772. do {
  3773. list.unshift(item);
  3774. } while (item = item._parent);
  3775. return list;
  3776. }
  3777. var list1 = getList(this),
  3778. list2 = getList(item);
  3779. for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
  3780. if (list1[i] != list2[i]) {
  3781. return list1[i]._index < list2[i]._index ? 1 : -1;
  3782. }
  3783. }
  3784. return 0;
  3785. },
  3786. hasChildren: function() {
  3787. return this._children && this._children.length > 0;
  3788. },
  3789. isInserted: function() {
  3790. return this._parent ? this._parent.isInserted() : false;
  3791. },
  3792. isAbove: function(item) {
  3793. return this._getOrder(item) === -1;
  3794. },
  3795. isBelow: function(item) {
  3796. return this._getOrder(item) === 1;
  3797. },
  3798. isParent: function(item) {
  3799. return this._parent === item;
  3800. },
  3801. isChild: function(item) {
  3802. return item && item._parent === this;
  3803. },
  3804. isDescendant: function(item) {
  3805. var parent = this;
  3806. while (parent = parent._parent) {
  3807. if (parent === item)
  3808. return true;
  3809. }
  3810. return false;
  3811. },
  3812. isAncestor: function(item) {
  3813. return item ? item.isDescendant(this) : false;
  3814. },
  3815. isSibling: function(item) {
  3816. return this._parent === item._parent;
  3817. },
  3818. isGroupedWith: function(item) {
  3819. var parent = this._parent;
  3820. while (parent) {
  3821. if (parent._parent
  3822. && /^(Group|Layer|CompoundPath)$/.test(parent._class)
  3823. && item.isDescendant(parent))
  3824. return true;
  3825. parent = parent._parent;
  3826. }
  3827. return false;
  3828. },
  3829. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  3830. var rotate = key === 'rotate';
  3831. this[key] = function() {
  3832. var value = (rotate ? Base : Point).read(arguments),
  3833. center = Point.read(arguments, 0, { readNull: true });
  3834. return this.transform(new Matrix()[key](value,
  3835. center || this.getPosition(true)));
  3836. };
  3837. }, {
  3838. translate: function() {
  3839. var mx = new Matrix();
  3840. return this.transform(mx.translate.apply(mx, arguments));
  3841. },
  3842. transform: function(matrix, _applyMatrix, _applyRecursively,
  3843. _setApplyMatrix) {
  3844. var _matrix = this._matrix,
  3845. transformMatrix = matrix && !matrix.isIdentity(),
  3846. applyMatrix = (_applyMatrix || this._applyMatrix)
  3847. && ((!_matrix.isIdentity() || transformMatrix)
  3848. || _applyMatrix && _applyRecursively && this._children);
  3849. if (!transformMatrix && !applyMatrix)
  3850. return this;
  3851. if (transformMatrix) {
  3852. if (!matrix.isInvertible() && _matrix.isInvertible())
  3853. _matrix._backup = _matrix.getValues();
  3854. _matrix.prepend(matrix, true);
  3855. var style = this._style,
  3856. fillColor = style.getFillColor(true),
  3857. strokeColor = style.getStrokeColor(true);
  3858. if (fillColor)
  3859. fillColor.transform(matrix);
  3860. if (strokeColor)
  3861. strokeColor.transform(matrix);
  3862. }
  3863. if (applyMatrix && (applyMatrix = this._transformContent(_matrix,
  3864. _applyRecursively, _setApplyMatrix))) {
  3865. var pivot = this._pivot;
  3866. if (pivot)
  3867. _matrix._transformPoint(pivot, pivot, true);
  3868. _matrix.reset(true);
  3869. if (_setApplyMatrix && this._canApplyMatrix)
  3870. this._applyMatrix = true;
  3871. }
  3872. var bounds = this._bounds,
  3873. position = this._position;
  3874. if (transformMatrix || applyMatrix) {
  3875. this._changed(25);
  3876. }
  3877. var decomp = transformMatrix && bounds && matrix.decompose();
  3878. if (decomp && decomp.skewing.isZero() && decomp.rotation % 90 === 0) {
  3879. for (var key in bounds) {
  3880. var cache = bounds[key];
  3881. if (cache.nonscaling) {
  3882. delete bounds[key];
  3883. } else if (applyMatrix || !cache.internal) {
  3884. var rect = cache.rect;
  3885. matrix._transformBounds(rect, rect);
  3886. }
  3887. }
  3888. this._bounds = bounds;
  3889. var cached = bounds[this._getBoundsCacheKey(
  3890. this._boundsOptions || {})];
  3891. if (cached) {
  3892. this._position = this._getPositionFromBounds(cached.rect);
  3893. }
  3894. } else if (transformMatrix && position && this._pivot) {
  3895. this._position = matrix._transformPoint(position, position);
  3896. }
  3897. return this;
  3898. },
  3899. _transformContent: function(matrix, applyRecursively, setApplyMatrix) {
  3900. var children = this._children;
  3901. if (children) {
  3902. for (var i = 0, l = children.length; i < l; i++)
  3903. children[i].transform(matrix, true, applyRecursively,
  3904. setApplyMatrix);
  3905. return true;
  3906. }
  3907. },
  3908. globalToLocal: function() {
  3909. return this.getGlobalMatrix(true)._inverseTransform(
  3910. Point.read(arguments));
  3911. },
  3912. localToGlobal: function() {
  3913. return this.getGlobalMatrix(true)._transformPoint(
  3914. Point.read(arguments));
  3915. },
  3916. parentToLocal: function() {
  3917. return this._matrix._inverseTransform(Point.read(arguments));
  3918. },
  3919. localToParent: function() {
  3920. return this._matrix._transformPoint(Point.read(arguments));
  3921. },
  3922. fitBounds: function(rectangle, fill) {
  3923. rectangle = Rectangle.read(arguments);
  3924. var bounds = this.getBounds(),
  3925. itemRatio = bounds.height / bounds.width,
  3926. rectRatio = rectangle.height / rectangle.width,
  3927. scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
  3928. ? rectangle.width / bounds.width
  3929. : rectangle.height / bounds.height,
  3930. newBounds = new Rectangle(new Point(),
  3931. new Size(bounds.width * scale, bounds.height * scale));
  3932. newBounds.setCenter(rectangle.getCenter());
  3933. this.setBounds(newBounds);
  3934. }
  3935. }), {
  3936. _setStyles: function(ctx, param, viewMatrix) {
  3937. var style = this._style,
  3938. matrix = this._matrix;
  3939. if (style.hasFill()) {
  3940. ctx.fillStyle = style.getFillColor().toCanvasStyle(ctx, matrix);
  3941. }
  3942. if (style.hasStroke()) {
  3943. ctx.strokeStyle = style.getStrokeColor().toCanvasStyle(ctx, matrix);
  3944. ctx.lineWidth = style.getStrokeWidth();
  3945. var strokeJoin = style.getStrokeJoin(),
  3946. strokeCap = style.getStrokeCap(),
  3947. miterLimit = style.getMiterLimit();
  3948. if (strokeJoin)
  3949. ctx.lineJoin = strokeJoin;
  3950. if (strokeCap)
  3951. ctx.lineCap = strokeCap;
  3952. if (miterLimit)
  3953. ctx.miterLimit = miterLimit;
  3954. if (paper.support.nativeDash) {
  3955. var dashArray = style.getDashArray(),
  3956. dashOffset = style.getDashOffset();
  3957. if (dashArray && dashArray.length) {
  3958. if ('setLineDash' in ctx) {
  3959. ctx.setLineDash(dashArray);
  3960. ctx.lineDashOffset = dashOffset;
  3961. } else {
  3962. ctx.mozDash = dashArray;
  3963. ctx.mozDashOffset = dashOffset;
  3964. }
  3965. }
  3966. }
  3967. }
  3968. if (style.hasShadow()) {
  3969. var pixelRatio = param.pixelRatio || 1,
  3970. mx = viewMatrix._shiftless().prepend(
  3971. new Matrix().scale(pixelRatio, pixelRatio)),
  3972. blur = mx.transform(new Point(style.getShadowBlur(), 0)),
  3973. offset = mx.transform(this.getShadowOffset());
  3974. ctx.shadowColor = style.getShadowColor().toCanvasStyle(ctx);
  3975. ctx.shadowBlur = blur.getLength();
  3976. ctx.shadowOffsetX = offset.x;
  3977. ctx.shadowOffsetY = offset.y;
  3978. }
  3979. },
  3980. draw: function(ctx, param, parentStrokeMatrix) {
  3981. var updateVersion = this._updateVersion = this._project._updateVersion;
  3982. if (!this._visible || this._opacity === 0)
  3983. return;
  3984. var matrices = param.matrices,
  3985. viewMatrix = param.viewMatrix,
  3986. matrix = this._matrix,
  3987. globalMatrix = matrices[matrices.length - 1].appended(matrix);
  3988. if (!globalMatrix.isInvertible())
  3989. return;
  3990. viewMatrix = viewMatrix ? viewMatrix.appended(globalMatrix)
  3991. : globalMatrix;
  3992. matrices.push(globalMatrix);
  3993. if (param.updateMatrix) {
  3994. this._globalMatrix = globalMatrix;
  3995. }
  3996. var blendMode = this._blendMode,
  3997. opacity = this._opacity,
  3998. normalBlend = blendMode === 'normal',
  3999. nativeBlend = BlendMode.nativeModes[blendMode],
  4000. direct = normalBlend && opacity === 1
  4001. || param.dontStart
  4002. || param.clip
  4003. || (nativeBlend || normalBlend && opacity < 1)
  4004. && this._canComposite(),
  4005. pixelRatio = param.pixelRatio || 1,
  4006. mainCtx, itemOffset, prevOffset;
  4007. if (!direct) {
  4008. var bounds = this.getStrokeBounds(viewMatrix);
  4009. if (!bounds.width || !bounds.height) {
  4010. matrices.pop();
  4011. return;
  4012. }
  4013. prevOffset = param.offset;
  4014. itemOffset = param.offset = bounds.getTopLeft().floor();
  4015. mainCtx = ctx;
  4016. ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1)
  4017. .multiply(pixelRatio));
  4018. if (pixelRatio !== 1)
  4019. ctx.scale(pixelRatio, pixelRatio);
  4020. }
  4021. ctx.save();
  4022. var strokeMatrix = parentStrokeMatrix
  4023. ? parentStrokeMatrix.appended(matrix)
  4024. : this._canScaleStroke && !this.getStrokeScaling(true)
  4025. && viewMatrix,
  4026. clip = !direct && param.clipItem,
  4027. transform = !strokeMatrix || clip;
  4028. if (direct) {
  4029. ctx.globalAlpha = opacity;
  4030. if (nativeBlend)
  4031. ctx.globalCompositeOperation = blendMode;
  4032. } else if (transform) {
  4033. ctx.translate(-itemOffset.x, -itemOffset.y);
  4034. }
  4035. if (transform) {
  4036. (direct ? matrix : viewMatrix).applyToContext(ctx);
  4037. }
  4038. if (clip) {
  4039. param.clipItem.draw(ctx, param.extend({ clip: true }));
  4040. }
  4041. if (strokeMatrix) {
  4042. ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  4043. var offset = param.offset;
  4044. if (offset)
  4045. ctx.translate(-offset.x, -offset.y);
  4046. }
  4047. this._draw(ctx, param, viewMatrix, strokeMatrix);
  4048. ctx.restore();
  4049. matrices.pop();
  4050. if (param.clip && !param.dontFinish)
  4051. ctx.clip();
  4052. if (!direct) {
  4053. BlendMode.process(blendMode, ctx, mainCtx, opacity,
  4054. itemOffset.subtract(prevOffset).multiply(pixelRatio));
  4055. CanvasProvider.release(ctx);
  4056. param.offset = prevOffset;
  4057. }
  4058. },
  4059. _isUpdated: function(updateVersion) {
  4060. var parent = this._parent;
  4061. if (parent instanceof CompoundPath)
  4062. return parent._isUpdated(updateVersion);
  4063. var updated = this._updateVersion === updateVersion;
  4064. if (!updated && parent && parent._visible
  4065. && parent._isUpdated(updateVersion)) {
  4066. this._updateVersion = updateVersion;
  4067. updated = true;
  4068. }
  4069. return updated;
  4070. },
  4071. _drawSelection: function(ctx, matrix, size, selectionItems, updateVersion) {
  4072. var selection = this._selection,
  4073. itemSelected = selection & 1,
  4074. boundsSelected = selection & 2
  4075. || itemSelected && this._selectBounds,
  4076. positionSelected = selection & 4;
  4077. if (!this._drawSelected)
  4078. itemSelected = false;
  4079. if ((itemSelected || boundsSelected || positionSelected)
  4080. && this._isUpdated(updateVersion)) {
  4081. var layer,
  4082. color = this.getSelectedColor(true) || (layer = this.getLayer())
  4083. && layer.getSelectedColor(true),
  4084. mx = matrix.appended(this.getGlobalMatrix(true)),
  4085. half = size / 2;
  4086. ctx.strokeStyle = ctx.fillStyle = color
  4087. ? color.toCanvasStyle(ctx) : '#009dec';
  4088. if (itemSelected)
  4089. this._drawSelected(ctx, mx, selectionItems);
  4090. if (positionSelected) {
  4091. var pos = this.getPosition(true),
  4092. parent = this._parent,
  4093. point = parent ? parent.localToGlobal(pos) : pos,
  4094. x = point.x,
  4095. y = point.y;
  4096. ctx.beginPath();
  4097. ctx.arc(x, y, half, 0, Math.PI * 2, true);
  4098. ctx.stroke();
  4099. var deltas = [[0, -1], [1, 0], [0, 1], [-1, 0]],
  4100. start = half,
  4101. end = size + 1;
  4102. for (var i = 0; i < 4; i++) {
  4103. var delta = deltas[i],
  4104. dx = delta[0],
  4105. dy = delta[1];
  4106. ctx.moveTo(x + dx * start, y + dy * start);
  4107. ctx.lineTo(x + dx * end, y + dy * end);
  4108. ctx.stroke();
  4109. }
  4110. }
  4111. if (boundsSelected) {
  4112. var coords = mx._transformCorners(this.getInternalBounds());
  4113. ctx.beginPath();
  4114. for (var i = 0; i < 8; i++) {
  4115. ctx[!i ? 'moveTo' : 'lineTo'](coords[i], coords[++i]);
  4116. }
  4117. ctx.closePath();
  4118. ctx.stroke();
  4119. for (var i = 0; i < 8; i++) {
  4120. ctx.fillRect(coords[i] - half, coords[++i] - half,
  4121. size, size);
  4122. }
  4123. }
  4124. }
  4125. },
  4126. _canComposite: function() {
  4127. return false;
  4128. }
  4129. }, Base.each(['down', 'drag', 'up', 'move'], function(key) {
  4130. this['removeOn' + Base.capitalize(key)] = function() {
  4131. var hash = {};
  4132. hash[key] = true;
  4133. return this.removeOn(hash);
  4134. };
  4135. }, {
  4136. removeOn: function(obj) {
  4137. for (var name in obj) {
  4138. if (obj[name]) {
  4139. var key = 'mouse' + name,
  4140. project = this._project,
  4141. sets = project._removeSets = project._removeSets || {};
  4142. sets[key] = sets[key] || {};
  4143. sets[key][this._id] = this;
  4144. }
  4145. }
  4146. return this;
  4147. }
  4148. }), {
  4149. tween: function(from, to, options) {
  4150. if (!options) {
  4151. options = to;
  4152. to = from;
  4153. from = null;
  4154. if (!options) {
  4155. options = to;
  4156. to = null;
  4157. }
  4158. }
  4159. var easing = options && options.easing,
  4160. start = options && options.start,
  4161. duration = options != null && (
  4162. typeof options === 'number' ? options : options.duration
  4163. ),
  4164. tween = new Tween(this, from, to, duration, easing, start);
  4165. function onFrame(event) {
  4166. tween._handleFrame(event.time * 1000);
  4167. if (!tween.running) {
  4168. this.off('frame', onFrame);
  4169. }
  4170. }
  4171. if (duration) {
  4172. this.on('frame', onFrame);
  4173. }
  4174. return tween;
  4175. },
  4176. tweenTo: function(to, options) {
  4177. return this.tween(null, to, options);
  4178. },
  4179. tweenFrom: function(from, options) {
  4180. return this.tween(from, null, options);
  4181. }
  4182. });
  4183. var Group = Item.extend({
  4184. _class: 'Group',
  4185. _selectBounds: false,
  4186. _selectChildren: true,
  4187. _serializeFields: {
  4188. children: []
  4189. },
  4190. initialize: function Group(arg) {
  4191. this._children = [];
  4192. this._namedChildren = {};
  4193. if (!this._initialize(arg))
  4194. this.addChildren(Array.isArray(arg) ? arg : arguments);
  4195. },
  4196. _changed: function _changed(flags) {
  4197. _changed.base.call(this, flags);
  4198. if (flags & 2050) {
  4199. this._clipItem = undefined;
  4200. }
  4201. },
  4202. _getClipItem: function() {
  4203. var clipItem = this._clipItem;
  4204. if (clipItem === undefined) {
  4205. clipItem = null;
  4206. var children = this._children;
  4207. for (var i = 0, l = children.length; i < l; i++) {
  4208. if (children[i]._clipMask) {
  4209. clipItem = children[i];
  4210. break;
  4211. }
  4212. }
  4213. this._clipItem = clipItem;
  4214. }
  4215. return clipItem;
  4216. },
  4217. isClipped: function() {
  4218. return !!this._getClipItem();
  4219. },
  4220. setClipped: function(clipped) {
  4221. var child = this.getFirstChild();
  4222. if (child)
  4223. child.setClipMask(clipped);
  4224. },
  4225. _getBounds: function _getBounds(matrix, options) {
  4226. var clipItem = this._getClipItem();
  4227. return clipItem
  4228. ? clipItem._getCachedBounds(
  4229. matrix && matrix.appended(clipItem._matrix),
  4230. Base.set({}, options, { stroke: false }))
  4231. : _getBounds.base.call(this, matrix, options);
  4232. },
  4233. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  4234. var clipItem = this._getClipItem();
  4235. return (!clipItem || clipItem.contains(point))
  4236. && _hitTestChildren.base.call(this, point, options, viewMatrix,
  4237. clipItem);
  4238. },
  4239. _draw: function(ctx, param) {
  4240. var clip = param.clip,
  4241. clipItem = !clip && this._getClipItem();
  4242. param = param.extend({ clipItem: clipItem, clip: false });
  4243. if (clip) {
  4244. ctx.beginPath();
  4245. param.dontStart = param.dontFinish = true;
  4246. } else if (clipItem) {
  4247. clipItem.draw(ctx, param.extend({ clip: true }));
  4248. }
  4249. var children = this._children;
  4250. for (var i = 0, l = children.length; i < l; i++) {
  4251. var item = children[i];
  4252. if (item !== clipItem)
  4253. item.draw(ctx, param);
  4254. }
  4255. }
  4256. });
  4257. var Layer = Group.extend({
  4258. _class: 'Layer',
  4259. initialize: function Layer() {
  4260. Group.apply(this, arguments);
  4261. },
  4262. _getOwner: function() {
  4263. return this._parent || this._index != null && this._project;
  4264. },
  4265. isInserted: function isInserted() {
  4266. return this._parent ? isInserted.base.call(this) : this._index != null;
  4267. },
  4268. activate: function() {
  4269. this._project._activeLayer = this;
  4270. },
  4271. _hitTestSelf: function() {
  4272. }
  4273. });
  4274. var Shape = Item.extend({
  4275. _class: 'Shape',
  4276. _applyMatrix: false,
  4277. _canApplyMatrix: false,
  4278. _canScaleStroke: true,
  4279. _serializeFields: {
  4280. type: null,
  4281. size: null,
  4282. radius: null
  4283. },
  4284. initialize: function Shape(props, point) {
  4285. this._initialize(props, point);
  4286. },
  4287. _equals: function(item) {
  4288. return this._type === item._type
  4289. && this._size.equals(item._size)
  4290. && Base.equals(this._radius, item._radius);
  4291. },
  4292. copyContent: function(source) {
  4293. this.setType(source._type);
  4294. this.setSize(source._size);
  4295. this.setRadius(source._radius);
  4296. },
  4297. getType: function() {
  4298. return this._type;
  4299. },
  4300. setType: function(type) {
  4301. this._type = type;
  4302. },
  4303. getShape: '#getType',
  4304. setShape: '#setType',
  4305. getSize: function() {
  4306. var size = this._size;
  4307. return new LinkedSize(size.width, size.height, this, 'setSize');
  4308. },
  4309. setSize: function() {
  4310. var size = Size.read(arguments);
  4311. if (!this._size) {
  4312. this._size = size.clone();
  4313. } else if (!this._size.equals(size)) {
  4314. var type = this._type,
  4315. width = size.width,
  4316. height = size.height;
  4317. if (type === 'rectangle') {
  4318. this._radius.set(Size.min(this._radius, size.divide(2)));
  4319. } else if (type === 'circle') {
  4320. width = height = (width + height) / 2;
  4321. this._radius = width / 2;
  4322. } else if (type === 'ellipse') {
  4323. this._radius._set(width / 2, height / 2);
  4324. }
  4325. this._size._set(width, height);
  4326. this._changed(9);
  4327. }
  4328. },
  4329. getRadius: function() {
  4330. var rad = this._radius;
  4331. return this._type === 'circle'
  4332. ? rad
  4333. : new LinkedSize(rad.width, rad.height, this, 'setRadius');
  4334. },
  4335. setRadius: function(radius) {
  4336. var type = this._type;
  4337. if (type === 'circle') {
  4338. if (radius === this._radius)
  4339. return;
  4340. var size = radius * 2;
  4341. this._radius = radius;
  4342. this._size._set(size, size);
  4343. } else {
  4344. radius = Size.read(arguments);
  4345. if (!this._radius) {
  4346. this._radius = radius.clone();
  4347. } else {
  4348. if (this._radius.equals(radius))
  4349. return;
  4350. this._radius.set(radius);
  4351. if (type === 'rectangle') {
  4352. var size = Size.max(this._size, radius.multiply(2));
  4353. this._size.set(size);
  4354. } else if (type === 'ellipse') {
  4355. this._size._set(radius.width * 2, radius.height * 2);
  4356. }
  4357. }
  4358. }
  4359. this._changed(9);
  4360. },
  4361. isEmpty: function() {
  4362. return false;
  4363. },
  4364. toPath: function(insert) {
  4365. var path = new Path[Base.capitalize(this._type)]({
  4366. center: new Point(),
  4367. size: this._size,
  4368. radius: this._radius,
  4369. insert: false
  4370. });
  4371. path.copyAttributes(this);
  4372. if (paper.settings.applyMatrix)
  4373. path.setApplyMatrix(true);
  4374. if (insert === undefined || insert)
  4375. path.insertAbove(this);
  4376. return path;
  4377. },
  4378. toShape: '#clone',
  4379. _asPathItem: function() {
  4380. return this.toPath(false);
  4381. },
  4382. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  4383. var style = this._style,
  4384. hasFill = style.hasFill(),
  4385. hasStroke = style.hasStroke(),
  4386. dontPaint = param.dontFinish || param.clip,
  4387. untransformed = !strokeMatrix;
  4388. if (hasFill || hasStroke || dontPaint) {
  4389. var type = this._type,
  4390. radius = this._radius,
  4391. isCircle = type === 'circle';
  4392. if (!param.dontStart)
  4393. ctx.beginPath();
  4394. if (untransformed && isCircle) {
  4395. ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
  4396. } else {
  4397. var rx = isCircle ? radius : radius.width,
  4398. ry = isCircle ? radius : radius.height,
  4399. size = this._size,
  4400. width = size.width,
  4401. height = size.height;
  4402. if (untransformed && type === 'rectangle' && rx === 0 && ry === 0) {
  4403. ctx.rect(-width / 2, -height / 2, width, height);
  4404. } else {
  4405. var x = width / 2,
  4406. y = height / 2,
  4407. kappa = 1 - 0.5522847498307936,
  4408. cx = rx * kappa,
  4409. cy = ry * kappa,
  4410. c = [
  4411. -x, -y + ry,
  4412. -x, -y + cy,
  4413. -x + cx, -y,
  4414. -x + rx, -y,
  4415. x - rx, -y,
  4416. x - cx, -y,
  4417. x, -y + cy,
  4418. x, -y + ry,
  4419. x, y - ry,
  4420. x, y - cy,
  4421. x - cx, y,
  4422. x - rx, y,
  4423. -x + rx, y,
  4424. -x + cx, y,
  4425. -x, y - cy,
  4426. -x, y - ry
  4427. ];
  4428. if (strokeMatrix)
  4429. strokeMatrix.transform(c, c, 32);
  4430. ctx.moveTo(c[0], c[1]);
  4431. ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]);
  4432. if (x !== rx)
  4433. ctx.lineTo(c[8], c[9]);
  4434. ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]);
  4435. if (y !== ry)
  4436. ctx.lineTo(c[16], c[17]);
  4437. ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]);
  4438. if (x !== rx)
  4439. ctx.lineTo(c[24], c[25]);
  4440. ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]);
  4441. }
  4442. }
  4443. ctx.closePath();
  4444. }
  4445. if (!dontPaint && (hasFill || hasStroke)) {
  4446. this._setStyles(ctx, param, viewMatrix);
  4447. if (hasFill) {
  4448. ctx.fill(style.getFillRule());
  4449. ctx.shadowColor = 'rgba(0,0,0,0)';
  4450. }
  4451. if (hasStroke)
  4452. ctx.stroke();
  4453. }
  4454. },
  4455. _canComposite: function() {
  4456. return !(this.hasFill() && this.hasStroke());
  4457. },
  4458. _getBounds: function(matrix, options) {
  4459. var rect = new Rectangle(this._size).setCenter(0, 0),
  4460. style = this._style,
  4461. strokeWidth = options.stroke && style.hasStroke()
  4462. && style.getStrokeWidth();
  4463. if (matrix)
  4464. rect = matrix._transformBounds(rect);
  4465. return strokeWidth
  4466. ? rect.expand(Path._getStrokePadding(strokeWidth,
  4467. this._getStrokeMatrix(matrix, options)))
  4468. : rect;
  4469. }
  4470. },
  4471. new function() {
  4472. function getCornerCenter(that, point, expand) {
  4473. var radius = that._radius;
  4474. if (!radius.isZero()) {
  4475. var halfSize = that._size.divide(2);
  4476. for (var q = 1; q <= 4; q++) {
  4477. var dir = new Point(q > 1 && q < 4 ? -1 : 1, q > 2 ? -1 : 1),
  4478. corner = dir.multiply(halfSize),
  4479. center = corner.subtract(dir.multiply(radius)),
  4480. rect = new Rectangle(
  4481. expand ? corner.add(dir.multiply(expand)) : corner,
  4482. center);
  4483. if (rect.contains(point))
  4484. return { point: center, quadrant: q };
  4485. }
  4486. }
  4487. }
  4488. function isOnEllipseStroke(point, radius, padding, quadrant) {
  4489. var vector = point.divide(radius);
  4490. return (!quadrant || vector.isInQuadrant(quadrant)) &&
  4491. vector.subtract(vector.normalize()).multiply(radius)
  4492. .divide(padding).length <= 1;
  4493. }
  4494. return {
  4495. _contains: function _contains(point) {
  4496. if (this._type === 'rectangle') {
  4497. var center = getCornerCenter(this, point);
  4498. return center
  4499. ? point.subtract(center.point).divide(this._radius)
  4500. .getLength() <= 1
  4501. : _contains.base.call(this, point);
  4502. } else {
  4503. return point.divide(this.size).getLength() <= 0.5;
  4504. }
  4505. },
  4506. _hitTestSelf: function _hitTestSelf(point, options, viewMatrix,
  4507. strokeMatrix) {
  4508. var hit = false,
  4509. style = this._style,
  4510. hitStroke = options.stroke && style.hasStroke(),
  4511. hitFill = options.fill && style.hasFill();
  4512. if (hitStroke || hitFill) {
  4513. var type = this._type,
  4514. radius = this._radius,
  4515. strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : 0,
  4516. strokePadding = options._tolerancePadding.add(
  4517. Path._getStrokePadding(strokeRadius,
  4518. !style.getStrokeScaling() && strokeMatrix));
  4519. if (type === 'rectangle') {
  4520. var padding = strokePadding.multiply(2),
  4521. center = getCornerCenter(this, point, padding);
  4522. if (center) {
  4523. hit = isOnEllipseStroke(point.subtract(center.point),
  4524. radius, strokePadding, center.quadrant);
  4525. } else {
  4526. var rect = new Rectangle(this._size).setCenter(0, 0),
  4527. outer = rect.expand(padding),
  4528. inner = rect.expand(padding.negate());
  4529. hit = outer._containsPoint(point)
  4530. && !inner._containsPoint(point);
  4531. }
  4532. } else {
  4533. hit = isOnEllipseStroke(point, radius, strokePadding);
  4534. }
  4535. }
  4536. return hit ? new HitResult(hitStroke ? 'stroke' : 'fill', this)
  4537. : _hitTestSelf.base.apply(this, arguments);
  4538. }
  4539. };
  4540. }, {
  4541. statics: new function() {
  4542. function createShape(type, point, size, radius, args) {
  4543. var item = new Shape(Base.getNamed(args), point);
  4544. item._type = type;
  4545. item._size = size;
  4546. item._radius = radius;
  4547. return item;
  4548. }
  4549. return {
  4550. Circle: function() {
  4551. var center = Point.readNamed(arguments, 'center'),
  4552. radius = Base.readNamed(arguments, 'radius');
  4553. return createShape('circle', center, new Size(radius * 2), radius,
  4554. arguments);
  4555. },
  4556. Rectangle: function() {
  4557. var rect = Rectangle.readNamed(arguments, 'rectangle'),
  4558. radius = Size.min(Size.readNamed(arguments, 'radius'),
  4559. rect.getSize(true).divide(2));
  4560. return createShape('rectangle', rect.getCenter(true),
  4561. rect.getSize(true), radius, arguments);
  4562. },
  4563. Ellipse: function() {
  4564. var ellipse = Shape._readEllipse(arguments),
  4565. radius = ellipse.radius;
  4566. return createShape('ellipse', ellipse.center, radius.multiply(2),
  4567. radius, arguments);
  4568. },
  4569. _readEllipse: function(args) {
  4570. var center,
  4571. radius;
  4572. if (Base.hasNamed(args, 'radius')) {
  4573. center = Point.readNamed(args, 'center');
  4574. radius = Size.readNamed(args, 'radius');
  4575. } else {
  4576. var rect = Rectangle.readNamed(args, 'rectangle');
  4577. center = rect.getCenter(true);
  4578. radius = rect.getSize(true).divide(2);
  4579. }
  4580. return { center: center, radius: radius };
  4581. }
  4582. };
  4583. }});
  4584. var Raster = Item.extend({
  4585. _class: 'Raster',
  4586. _applyMatrix: false,
  4587. _canApplyMatrix: false,
  4588. _boundsOptions: { stroke: false, handle: false },
  4589. _serializeFields: {
  4590. crossOrigin: null,
  4591. source: null
  4592. },
  4593. _prioritize: ['crossOrigin'],
  4594. _smoothing: true,
  4595. initialize: function Raster(object, position) {
  4596. if (!this._initialize(object,
  4597. position !== undefined && Point.read(arguments, 1))) {
  4598. var image = typeof object === 'string'
  4599. ? document.getElementById(object) : object;
  4600. if (image) {
  4601. this.setImage(image);
  4602. } else {
  4603. this.setSource(object);
  4604. }
  4605. }
  4606. if (!this._size) {
  4607. this._size = new Size();
  4608. this._loaded = false;
  4609. }
  4610. },
  4611. _equals: function(item) {
  4612. return this.getSource() === item.getSource();
  4613. },
  4614. copyContent: function(source) {
  4615. var image = source._image,
  4616. canvas = source._canvas;
  4617. if (image) {
  4618. this._setImage(image);
  4619. } else if (canvas) {
  4620. var copyCanvas = CanvasProvider.getCanvas(source._size);
  4621. copyCanvas.getContext('2d').drawImage(canvas, 0, 0);
  4622. this._setImage(copyCanvas);
  4623. }
  4624. this._crossOrigin = source._crossOrigin;
  4625. },
  4626. getSize: function() {
  4627. var size = this._size;
  4628. return new LinkedSize(size ? size.width : 0, size ? size.height : 0,
  4629. this, 'setSize');
  4630. },
  4631. setSize: function() {
  4632. var size = Size.read(arguments);
  4633. if (!size.equals(this._size)) {
  4634. if (size.width > 0 && size.height > 0) {
  4635. var element = this.getElement();
  4636. this._setImage(CanvasProvider.getCanvas(size));
  4637. if (element)
  4638. this.getContext(true).drawImage(element, 0, 0,
  4639. size.width, size.height);
  4640. } else {
  4641. if (this._canvas)
  4642. CanvasProvider.release(this._canvas);
  4643. this._size = size.clone();
  4644. }
  4645. }
  4646. },
  4647. getWidth: function() {
  4648. return this._size ? this._size.width : 0;
  4649. },
  4650. setWidth: function(width) {
  4651. this.setSize(width, this.getHeight());
  4652. },
  4653. getHeight: function() {
  4654. return this._size ? this._size.height : 0;
  4655. },
  4656. setHeight: function(height) {
  4657. this.setSize(this.getWidth(), height);
  4658. },
  4659. getLoaded: function() {
  4660. return this._loaded;
  4661. },
  4662. isEmpty: function() {
  4663. var size = this._size;
  4664. return !size || size.width === 0 && size.height === 0;
  4665. },
  4666. getResolution: function() {
  4667. var matrix = this._matrix,
  4668. orig = new Point(0, 0).transform(matrix),
  4669. u = new Point(1, 0).transform(matrix).subtract(orig),
  4670. v = new Point(0, 1).transform(matrix).subtract(orig);
  4671. return new Size(
  4672. 72 / u.getLength(),
  4673. 72 / v.getLength()
  4674. );
  4675. },
  4676. getPpi: '#getResolution',
  4677. getImage: function() {
  4678. return this._image;
  4679. },
  4680. setImage: function(image) {
  4681. var that = this;
  4682. function emit(event) {
  4683. var view = that.getView(),
  4684. type = event && event.type || 'load';
  4685. if (view && that.responds(type)) {
  4686. paper = view._scope;
  4687. that.emit(type, new Event(event));
  4688. }
  4689. }
  4690. this._setImage(image);
  4691. if (this._loaded) {
  4692. setTimeout(emit, 0);
  4693. } else if (image) {
  4694. DomEvent.add(image, {
  4695. load: function(event) {
  4696. that._setImage(image);
  4697. emit(event);
  4698. },
  4699. error: emit
  4700. });
  4701. }
  4702. },
  4703. _setImage: function(image) {
  4704. if (this._canvas)
  4705. CanvasProvider.release(this._canvas);
  4706. if (image && image.getContext) {
  4707. this._image = null;
  4708. this._canvas = image;
  4709. this._loaded = true;
  4710. } else {
  4711. this._image = image;
  4712. this._canvas = null;
  4713. this._loaded = !!(image && image.src && image.complete);
  4714. }
  4715. this._size = new Size(
  4716. image ? image.naturalWidth || image.width : 0,
  4717. image ? image.naturalHeight || image.height : 0);
  4718. this._context = null;
  4719. this._changed(1033);
  4720. },
  4721. getCanvas: function() {
  4722. if (!this._canvas) {
  4723. var ctx = CanvasProvider.getContext(this._size);
  4724. try {
  4725. if (this._image)
  4726. ctx.drawImage(this._image, 0, 0);
  4727. this._canvas = ctx.canvas;
  4728. } catch (e) {
  4729. CanvasProvider.release(ctx);
  4730. }
  4731. }
  4732. return this._canvas;
  4733. },
  4734. setCanvas: '#setImage',
  4735. getContext: function(modify) {
  4736. if (!this._context)
  4737. this._context = this.getCanvas().getContext('2d');
  4738. if (modify) {
  4739. this._image = null;
  4740. this._changed(1025);
  4741. }
  4742. return this._context;
  4743. },
  4744. setContext: function(context) {
  4745. this._context = context;
  4746. },
  4747. getSource: function() {
  4748. var image = this._image;
  4749. return image && image.src || this.toDataURL();
  4750. },
  4751. setSource: function(src) {
  4752. var image = new self.Image(),
  4753. crossOrigin = this._crossOrigin;
  4754. if (crossOrigin)
  4755. image.crossOrigin = crossOrigin;
  4756. image.src = src;
  4757. this.setImage(image);
  4758. },
  4759. getCrossOrigin: function() {
  4760. var image = this._image;
  4761. return image && image.crossOrigin || this._crossOrigin || '';
  4762. },
  4763. setCrossOrigin: function(crossOrigin) {
  4764. this._crossOrigin = crossOrigin;
  4765. var image = this._image;
  4766. if (image)
  4767. image.crossOrigin = crossOrigin;
  4768. },
  4769. getSmoothing: function() {
  4770. return this._smoothing;
  4771. },
  4772. setSmoothing: function(smoothing) {
  4773. this._smoothing = smoothing;
  4774. this._changed(257);
  4775. },
  4776. getElement: function() {
  4777. return this._canvas || this._loaded && this._image;
  4778. }
  4779. }, {
  4780. beans: false,
  4781. getSubCanvas: function() {
  4782. var rect = Rectangle.read(arguments),
  4783. ctx = CanvasProvider.getContext(rect.getSize());
  4784. ctx.drawImage(this.getCanvas(), rect.x, rect.y,
  4785. rect.width, rect.height, 0, 0, rect.width, rect.height);
  4786. return ctx.canvas;
  4787. },
  4788. getSubRaster: function() {
  4789. var rect = Rectangle.read(arguments),
  4790. raster = new Raster(Item.NO_INSERT);
  4791. raster._setImage(this.getSubCanvas(rect));
  4792. raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
  4793. raster._matrix.prepend(this._matrix);
  4794. raster.insertAbove(this);
  4795. return raster;
  4796. },
  4797. toDataURL: function() {
  4798. var image = this._image,
  4799. src = image && image.src;
  4800. if (/^data:/.test(src))
  4801. return src;
  4802. var canvas = this.getCanvas();
  4803. return canvas ? canvas.toDataURL.apply(canvas, arguments) : null;
  4804. },
  4805. drawImage: function(image ) {
  4806. var point = Point.read(arguments, 1);
  4807. this.getContext(true).drawImage(image, point.x, point.y);
  4808. },
  4809. getAverageColor: function(object) {
  4810. var bounds, path;
  4811. if (!object) {
  4812. bounds = this.getBounds();
  4813. } else if (object instanceof PathItem) {
  4814. path = object;
  4815. bounds = object.getBounds();
  4816. } else if (typeof object === 'object') {
  4817. if ('width' in object) {
  4818. bounds = new Rectangle(object);
  4819. } else if ('x' in object) {
  4820. bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
  4821. }
  4822. }
  4823. if (!bounds)
  4824. return null;
  4825. var sampleSize = 32,
  4826. width = Math.min(bounds.width, sampleSize),
  4827. height = Math.min(bounds.height, sampleSize);
  4828. var ctx = Raster._sampleContext;
  4829. if (!ctx) {
  4830. ctx = Raster._sampleContext = CanvasProvider.getContext(
  4831. new Size(sampleSize));
  4832. } else {
  4833. ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
  4834. }
  4835. ctx.save();
  4836. var matrix = new Matrix()
  4837. .scale(width / bounds.width, height / bounds.height)
  4838. .translate(-bounds.x, -bounds.y);
  4839. matrix.applyToContext(ctx);
  4840. if (path)
  4841. path.draw(ctx, new Base({ clip: true, matrices: [matrix] }));
  4842. this._matrix.applyToContext(ctx);
  4843. var element = this.getElement(),
  4844. size = this._size;
  4845. if (element)
  4846. ctx.drawImage(element, -size.width / 2, -size.height / 2);
  4847. ctx.restore();
  4848. var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
  4849. Math.ceil(height)).data,
  4850. channels = [0, 0, 0],
  4851. total = 0;
  4852. for (var i = 0, l = pixels.length; i < l; i += 4) {
  4853. var alpha = pixels[i + 3];
  4854. total += alpha;
  4855. alpha /= 255;
  4856. channels[0] += pixels[i] * alpha;
  4857. channels[1] += pixels[i + 1] * alpha;
  4858. channels[2] += pixels[i + 2] * alpha;
  4859. }
  4860. for (var i = 0; i < 3; i++)
  4861. channels[i] /= total;
  4862. return total ? Color.read(channels) : null;
  4863. },
  4864. getPixel: function() {
  4865. var point = Point.read(arguments);
  4866. var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
  4867. return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
  4868. data[3] / 255);
  4869. },
  4870. setPixel: function() {
  4871. var point = Point.read(arguments),
  4872. color = Color.read(arguments),
  4873. components = color._convert('rgb'),
  4874. alpha = color._alpha,
  4875. ctx = this.getContext(true),
  4876. imageData = ctx.createImageData(1, 1),
  4877. data = imageData.data;
  4878. data[0] = components[0] * 255;
  4879. data[1] = components[1] * 255;
  4880. data[2] = components[2] * 255;
  4881. data[3] = alpha != null ? alpha * 255 : 255;
  4882. ctx.putImageData(imageData, point.x, point.y);
  4883. },
  4884. createImageData: function() {
  4885. var size = Size.read(arguments);
  4886. return this.getContext().createImageData(size.width, size.height);
  4887. },
  4888. getImageData: function() {
  4889. var rect = Rectangle.read(arguments);
  4890. if (rect.isEmpty())
  4891. rect = new Rectangle(this._size);
  4892. return this.getContext().getImageData(rect.x, rect.y,
  4893. rect.width, rect.height);
  4894. },
  4895. setImageData: function(data ) {
  4896. var point = Point.read(arguments, 1);
  4897. this.getContext(true).putImageData(data, point.x, point.y);
  4898. },
  4899. _getBounds: function(matrix, options) {
  4900. var rect = new Rectangle(this._size).setCenter(0, 0);
  4901. return matrix ? matrix._transformBounds(rect) : rect;
  4902. },
  4903. _hitTestSelf: function(point) {
  4904. if (this._contains(point)) {
  4905. var that = this;
  4906. return new HitResult('pixel', that, {
  4907. offset: point.add(that._size.divide(2)).round(),
  4908. color: {
  4909. get: function() {
  4910. return that.getPixel(this.offset);
  4911. }
  4912. }
  4913. });
  4914. }
  4915. },
  4916. _draw: function(ctx, param, viewMatrix) {
  4917. var element = this.getElement();
  4918. if (element && element.width > 0 && element.height > 0) {
  4919. ctx.globalAlpha = this._opacity;
  4920. this._setStyles(ctx, param, viewMatrix);
  4921. DomElement.setPrefixed(
  4922. ctx, 'imageSmoothingEnabled', this._smoothing
  4923. );
  4924. ctx.drawImage(element,
  4925. -this._size.width / 2, -this._size.height / 2);
  4926. }
  4927. },
  4928. _canComposite: function() {
  4929. return true;
  4930. }
  4931. });
  4932. var SymbolItem = Item.extend({
  4933. _class: 'SymbolItem',
  4934. _applyMatrix: false,
  4935. _canApplyMatrix: false,
  4936. _boundsOptions: { stroke: true },
  4937. _serializeFields: {
  4938. symbol: null
  4939. },
  4940. initialize: function SymbolItem(arg0, arg1) {
  4941. if (!this._initialize(arg0,
  4942. arg1 !== undefined && Point.read(arguments, 1)))
  4943. this.setDefinition(arg0 instanceof SymbolDefinition ?
  4944. arg0 : new SymbolDefinition(arg0));
  4945. },
  4946. _equals: function(item) {
  4947. return this._definition === item._definition;
  4948. },
  4949. copyContent: function(source) {
  4950. this.setDefinition(source._definition);
  4951. },
  4952. getDefinition: function() {
  4953. return this._definition;
  4954. },
  4955. setDefinition: function(definition) {
  4956. this._definition = definition;
  4957. this._changed(9);
  4958. },
  4959. getSymbol: '#getDefinition',
  4960. setSymbol: '#setDefinition',
  4961. isEmpty: function() {
  4962. return this._definition._item.isEmpty();
  4963. },
  4964. _getBounds: function(matrix, options) {
  4965. var item = this._definition._item;
  4966. return item._getCachedBounds(item._matrix.prepended(matrix), options);
  4967. },
  4968. _hitTestSelf: function(point, options, viewMatrix) {
  4969. var res = this._definition._item._hitTest(point, options, viewMatrix);
  4970. if (res)
  4971. res.item = this;
  4972. return res;
  4973. },
  4974. _draw: function(ctx, param) {
  4975. this._definition._item.draw(ctx, param);
  4976. }
  4977. });
  4978. var SymbolDefinition = Base.extend({
  4979. _class: 'SymbolDefinition',
  4980. initialize: function SymbolDefinition(item, dontCenter) {
  4981. this._id = UID.get();
  4982. this.project = paper.project;
  4983. if (item)
  4984. this.setItem(item, dontCenter);
  4985. },
  4986. _serialize: function(options, dictionary) {
  4987. return dictionary.add(this, function() {
  4988. return Base.serialize([this._class, this._item],
  4989. options, false, dictionary);
  4990. });
  4991. },
  4992. _changed: function(flags) {
  4993. if (flags & 8)
  4994. Item._clearBoundsCache(this);
  4995. if (flags & 1)
  4996. this.project._changed(flags);
  4997. },
  4998. getItem: function() {
  4999. return this._item;
  5000. },
  5001. setItem: function(item, _dontCenter) {
  5002. if (item._symbol)
  5003. item = item.clone();
  5004. if (this._item)
  5005. this._item._symbol = null;
  5006. this._item = item;
  5007. item.remove();
  5008. item.setSelected(false);
  5009. if (!_dontCenter)
  5010. item.setPosition(new Point());
  5011. item._symbol = this;
  5012. this._changed(9);
  5013. },
  5014. getDefinition: '#getItem',
  5015. setDefinition: '#setItem',
  5016. place: function(position) {
  5017. return new SymbolItem(this, position);
  5018. },
  5019. clone: function() {
  5020. return new SymbolDefinition(this._item.clone(false));
  5021. },
  5022. equals: function(symbol) {
  5023. return symbol === this
  5024. || symbol && this._item.equals(symbol._item)
  5025. || false;
  5026. }
  5027. });
  5028. var HitResult = Base.extend({
  5029. _class: 'HitResult',
  5030. initialize: function HitResult(type, item, values) {
  5031. this.type = type;
  5032. this.item = item;
  5033. if (values)
  5034. this.inject(values);
  5035. },
  5036. statics: {
  5037. getOptions: function(args) {
  5038. var options = args && Base.read(args);
  5039. return Base.set({
  5040. type: null,
  5041. tolerance: paper.settings.hitTolerance,
  5042. fill: !options,
  5043. stroke: !options,
  5044. segments: !options,
  5045. handles: false,
  5046. ends: false,
  5047. position: false,
  5048. center: false,
  5049. bounds: false,
  5050. guides: false,
  5051. selected: false
  5052. }, options);
  5053. }
  5054. }
  5055. });
  5056. var Segment = Base.extend({
  5057. _class: 'Segment',
  5058. beans: true,
  5059. _selection: 0,
  5060. initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
  5061. var count = arguments.length,
  5062. point, handleIn, handleOut, selection;
  5063. if (count > 0) {
  5064. if (arg0 == null || typeof arg0 === 'object') {
  5065. if (count === 1 && arg0 && 'point' in arg0) {
  5066. point = arg0.point;
  5067. handleIn = arg0.handleIn;
  5068. handleOut = arg0.handleOut;
  5069. selection = arg0.selection;
  5070. } else {
  5071. point = arg0;
  5072. handleIn = arg1;
  5073. handleOut = arg2;
  5074. selection = arg3;
  5075. }
  5076. } else {
  5077. point = [ arg0, arg1 ];
  5078. handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
  5079. handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
  5080. }
  5081. }
  5082. new SegmentPoint(point, this, '_point');
  5083. new SegmentPoint(handleIn, this, '_handleIn');
  5084. new SegmentPoint(handleOut, this, '_handleOut');
  5085. if (selection)
  5086. this.setSelection(selection);
  5087. },
  5088. _serialize: function(options, dictionary) {
  5089. var point = this._point,
  5090. selection = this._selection,
  5091. obj = selection || this.hasHandles()
  5092. ? [point, this._handleIn, this._handleOut]
  5093. : point;
  5094. if (selection)
  5095. obj.push(selection);
  5096. return Base.serialize(obj, options, true, dictionary);
  5097. },
  5098. _changed: function(point) {
  5099. var path = this._path;
  5100. if (!path)
  5101. return;
  5102. var curves = path._curves,
  5103. index = this._index,
  5104. curve;
  5105. if (curves) {
  5106. if ((!point || point === this._point || point === this._handleIn)
  5107. && (curve = index > 0 ? curves[index - 1] : path._closed
  5108. ? curves[curves.length - 1] : null))
  5109. curve._changed();
  5110. if ((!point || point === this._point || point === this._handleOut)
  5111. && (curve = curves[index]))
  5112. curve._changed();
  5113. }
  5114. path._changed(41);
  5115. },
  5116. getPoint: function() {
  5117. return this._point;
  5118. },
  5119. setPoint: function() {
  5120. this._point.set(Point.read(arguments));
  5121. },
  5122. getHandleIn: function() {
  5123. return this._handleIn;
  5124. },
  5125. setHandleIn: function() {
  5126. this._handleIn.set(Point.read(arguments));
  5127. },
  5128. getHandleOut: function() {
  5129. return this._handleOut;
  5130. },
  5131. setHandleOut: function() {
  5132. this._handleOut.set(Point.read(arguments));
  5133. },
  5134. hasHandles: function() {
  5135. return !this._handleIn.isZero() || !this._handleOut.isZero();
  5136. },
  5137. isSmooth: function() {
  5138. var handleIn = this._handleIn,
  5139. handleOut = this._handleOut;
  5140. return !handleIn.isZero() && !handleOut.isZero()
  5141. && handleIn.isCollinear(handleOut);
  5142. },
  5143. clearHandles: function() {
  5144. this._handleIn._set(0, 0);
  5145. this._handleOut._set(0, 0);
  5146. },
  5147. getSelection: function() {
  5148. return this._selection;
  5149. },
  5150. setSelection: function(selection) {
  5151. var oldSelection = this._selection,
  5152. path = this._path;
  5153. this._selection = selection = selection || 0;
  5154. if (path && selection !== oldSelection) {
  5155. path._updateSelection(this, oldSelection, selection);
  5156. path._changed(257);
  5157. }
  5158. },
  5159. _changeSelection: function(flag, selected) {
  5160. var selection = this._selection;
  5161. this.setSelection(selected ? selection | flag : selection & ~flag);
  5162. },
  5163. isSelected: function() {
  5164. return !!(this._selection & 7);
  5165. },
  5166. setSelected: function(selected) {
  5167. this._changeSelection(7, selected);
  5168. },
  5169. getIndex: function() {
  5170. return this._index !== undefined ? this._index : null;
  5171. },
  5172. getPath: function() {
  5173. return this._path || null;
  5174. },
  5175. getCurve: function() {
  5176. var path = this._path,
  5177. index = this._index;
  5178. if (path) {
  5179. if (index > 0 && !path._closed
  5180. && index === path._segments.length - 1)
  5181. index--;
  5182. return path.getCurves()[index] || null;
  5183. }
  5184. return null;
  5185. },
  5186. getLocation: function() {
  5187. var curve = this.getCurve();
  5188. return curve
  5189. ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1)
  5190. : null;
  5191. },
  5192. getNext: function() {
  5193. var segments = this._path && this._path._segments;
  5194. return segments && (segments[this._index + 1]
  5195. || this._path._closed && segments[0]) || null;
  5196. },
  5197. smooth: function(options, _first, _last) {
  5198. var opts = options || {},
  5199. type = opts.type,
  5200. factor = opts.factor,
  5201. prev = this.getPrevious(),
  5202. next = this.getNext(),
  5203. p0 = (prev || this)._point,
  5204. p1 = this._point,
  5205. p2 = (next || this)._point,
  5206. d1 = p0.getDistance(p1),
  5207. d2 = p1.getDistance(p2);
  5208. if (!type || type === 'catmull-rom') {
  5209. var a = factor === undefined ? 0.5 : factor,
  5210. d1_a = Math.pow(d1, a),
  5211. d1_2a = d1_a * d1_a,
  5212. d2_a = Math.pow(d2, a),
  5213. d2_2a = d2_a * d2_a;
  5214. if (!_first && prev) {
  5215. var A = 2 * d2_2a + 3 * d2_a * d1_a + d1_2a,
  5216. N = 3 * d2_a * (d2_a + d1_a);
  5217. this.setHandleIn(N !== 0
  5218. ? new Point(
  5219. (d2_2a * p0._x + A * p1._x - d1_2a * p2._x) / N - p1._x,
  5220. (d2_2a * p0._y + A * p1._y - d1_2a * p2._y) / N - p1._y)
  5221. : new Point());
  5222. }
  5223. if (!_last && next) {
  5224. var A = 2 * d1_2a + 3 * d1_a * d2_a + d2_2a,
  5225. N = 3 * d1_a * (d1_a + d2_a);
  5226. this.setHandleOut(N !== 0
  5227. ? new Point(
  5228. (d1_2a * p2._x + A * p1._x - d2_2a * p0._x) / N - p1._x,
  5229. (d1_2a * p2._y + A * p1._y - d2_2a * p0._y) / N - p1._y)
  5230. : new Point());
  5231. }
  5232. } else if (type === 'geometric') {
  5233. if (prev && next) {
  5234. var vector = p0.subtract(p2),
  5235. t = factor === undefined ? 0.4 : factor,
  5236. k = t * d1 / (d1 + d2);
  5237. if (!_first)
  5238. this.setHandleIn(vector.multiply(k));
  5239. if (!_last)
  5240. this.setHandleOut(vector.multiply(k - t));
  5241. }
  5242. } else {
  5243. throw new Error('Smoothing method \'' + type + '\' not supported.');
  5244. }
  5245. },
  5246. getPrevious: function() {
  5247. var segments = this._path && this._path._segments;
  5248. return segments && (segments[this._index - 1]
  5249. || this._path._closed && segments[segments.length - 1]) || null;
  5250. },
  5251. isFirst: function() {
  5252. return !this._index;
  5253. },
  5254. isLast: function() {
  5255. var path = this._path;
  5256. return path && this._index === path._segments.length - 1 || false;
  5257. },
  5258. reverse: function() {
  5259. var handleIn = this._handleIn,
  5260. handleOut = this._handleOut,
  5261. tmp = handleIn.clone();
  5262. handleIn.set(handleOut);
  5263. handleOut.set(tmp);
  5264. },
  5265. reversed: function() {
  5266. return new Segment(this._point, this._handleOut, this._handleIn);
  5267. },
  5268. remove: function() {
  5269. return this._path ? !!this._path.removeSegment(this._index) : false;
  5270. },
  5271. clone: function() {
  5272. return new Segment(this._point, this._handleIn, this._handleOut);
  5273. },
  5274. equals: function(segment) {
  5275. return segment === this || segment && this._class === segment._class
  5276. && this._point.equals(segment._point)
  5277. && this._handleIn.equals(segment._handleIn)
  5278. && this._handleOut.equals(segment._handleOut)
  5279. || false;
  5280. },
  5281. toString: function() {
  5282. var parts = [ 'point: ' + this._point ];
  5283. if (!this._handleIn.isZero())
  5284. parts.push('handleIn: ' + this._handleIn);
  5285. if (!this._handleOut.isZero())
  5286. parts.push('handleOut: ' + this._handleOut);
  5287. return '{ ' + parts.join(', ') + ' }';
  5288. },
  5289. transform: function(matrix) {
  5290. this._transformCoordinates(matrix, new Array(6), true);
  5291. this._changed();
  5292. },
  5293. interpolate: function(from, to, factor) {
  5294. var u = 1 - factor,
  5295. v = factor,
  5296. point1 = from._point,
  5297. point2 = to._point,
  5298. handleIn1 = from._handleIn,
  5299. handleIn2 = to._handleIn,
  5300. handleOut2 = to._handleOut,
  5301. handleOut1 = from._handleOut;
  5302. this._point._set(
  5303. u * point1._x + v * point2._x,
  5304. u * point1._y + v * point2._y, true);
  5305. this._handleIn._set(
  5306. u * handleIn1._x + v * handleIn2._x,
  5307. u * handleIn1._y + v * handleIn2._y, true);
  5308. this._handleOut._set(
  5309. u * handleOut1._x + v * handleOut2._x,
  5310. u * handleOut1._y + v * handleOut2._y, true);
  5311. this._changed();
  5312. },
  5313. _transformCoordinates: function(matrix, coords, change) {
  5314. var point = this._point,
  5315. handleIn = !change || !this._handleIn.isZero()
  5316. ? this._handleIn : null,
  5317. handleOut = !change || !this._handleOut.isZero()
  5318. ? this._handleOut : null,
  5319. x = point._x,
  5320. y = point._y,
  5321. i = 2;
  5322. coords[0] = x;
  5323. coords[1] = y;
  5324. if (handleIn) {
  5325. coords[i++] = handleIn._x + x;
  5326. coords[i++] = handleIn._y + y;
  5327. }
  5328. if (handleOut) {
  5329. coords[i++] = handleOut._x + x;
  5330. coords[i++] = handleOut._y + y;
  5331. }
  5332. if (matrix) {
  5333. matrix._transformCoordinates(coords, coords, i / 2);
  5334. x = coords[0];
  5335. y = coords[1];
  5336. if (change) {
  5337. point._x = x;
  5338. point._y = y;
  5339. i = 2;
  5340. if (handleIn) {
  5341. handleIn._x = coords[i++] - x;
  5342. handleIn._y = coords[i++] - y;
  5343. }
  5344. if (handleOut) {
  5345. handleOut._x = coords[i++] - x;
  5346. handleOut._y = coords[i++] - y;
  5347. }
  5348. } else {
  5349. if (!handleIn) {
  5350. coords[i++] = x;
  5351. coords[i++] = y;
  5352. }
  5353. if (!handleOut) {
  5354. coords[i++] = x;
  5355. coords[i++] = y;
  5356. }
  5357. }
  5358. }
  5359. return coords;
  5360. }
  5361. });
  5362. var SegmentPoint = Point.extend({
  5363. initialize: function SegmentPoint(point, owner, key) {
  5364. var x, y,
  5365. selected;
  5366. if (!point) {
  5367. x = y = 0;
  5368. } else if ((x = point[0]) !== undefined) {
  5369. y = point[1];
  5370. } else {
  5371. var pt = point;
  5372. if ((x = pt.x) === undefined) {
  5373. pt = Point.read(arguments);
  5374. x = pt.x;
  5375. }
  5376. y = pt.y;
  5377. selected = pt.selected;
  5378. }
  5379. this._x = x;
  5380. this._y = y;
  5381. this._owner = owner;
  5382. owner[key] = this;
  5383. if (selected)
  5384. this.setSelected(true);
  5385. },
  5386. _set: function(x, y) {
  5387. this._x = x;
  5388. this._y = y;
  5389. this._owner._changed(this);
  5390. return this;
  5391. },
  5392. getX: function() {
  5393. return this._x;
  5394. },
  5395. setX: function(x) {
  5396. this._x = x;
  5397. this._owner._changed(this);
  5398. },
  5399. getY: function() {
  5400. return this._y;
  5401. },
  5402. setY: function(y) {
  5403. this._y = y;
  5404. this._owner._changed(this);
  5405. },
  5406. isZero: function() {
  5407. var isZero = Numerical.isZero;
  5408. return isZero(this._x) && isZero(this._y);
  5409. },
  5410. isSelected: function() {
  5411. return !!(this._owner._selection & this._getSelection());
  5412. },
  5413. setSelected: function(selected) {
  5414. this._owner._changeSelection(this._getSelection(), selected);
  5415. },
  5416. _getSelection: function() {
  5417. var owner = this._owner;
  5418. return this === owner._point ? 1
  5419. : this === owner._handleIn ? 2
  5420. : this === owner._handleOut ? 4
  5421. : 0;
  5422. }
  5423. });
  5424. var Curve = Base.extend({
  5425. _class: 'Curve',
  5426. beans: true,
  5427. initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
  5428. var count = arguments.length,
  5429. seg1, seg2,
  5430. point1, point2,
  5431. handle1, handle2;
  5432. if (count === 3) {
  5433. this._path = arg0;
  5434. seg1 = arg1;
  5435. seg2 = arg2;
  5436. } else if (!count) {
  5437. seg1 = new Segment();
  5438. seg2 = new Segment();
  5439. } else if (count === 1) {
  5440. if ('segment1' in arg0) {
  5441. seg1 = new Segment(arg0.segment1);
  5442. seg2 = new Segment(arg0.segment2);
  5443. } else if ('point1' in arg0) {
  5444. point1 = arg0.point1;
  5445. handle1 = arg0.handle1;
  5446. handle2 = arg0.handle2;
  5447. point2 = arg0.point2;
  5448. } else if (Array.isArray(arg0)) {
  5449. point1 = [arg0[0], arg0[1]];
  5450. point2 = [arg0[6], arg0[7]];
  5451. handle1 = [arg0[2] - arg0[0], arg0[3] - arg0[1]];
  5452. handle2 = [arg0[4] - arg0[6], arg0[5] - arg0[7]];
  5453. }
  5454. } else if (count === 2) {
  5455. seg1 = new Segment(arg0);
  5456. seg2 = new Segment(arg1);
  5457. } else if (count === 4) {
  5458. point1 = arg0;
  5459. handle1 = arg1;
  5460. handle2 = arg2;
  5461. point2 = arg3;
  5462. } else if (count === 8) {
  5463. point1 = [arg0, arg1];
  5464. point2 = [arg6, arg7];
  5465. handle1 = [arg2 - arg0, arg3 - arg1];
  5466. handle2 = [arg4 - arg6, arg5 - arg7];
  5467. }
  5468. this._segment1 = seg1 || new Segment(point1, null, handle1);
  5469. this._segment2 = seg2 || new Segment(point2, handle2, null);
  5470. },
  5471. _serialize: function(options, dictionary) {
  5472. return Base.serialize(this.hasHandles()
  5473. ? [this.getPoint1(), this.getHandle1(), this.getHandle2(),
  5474. this.getPoint2()]
  5475. : [this.getPoint1(), this.getPoint2()],
  5476. options, true, dictionary);
  5477. },
  5478. _changed: function() {
  5479. this._length = this._bounds = undefined;
  5480. },
  5481. clone: function() {
  5482. return new Curve(this._segment1, this._segment2);
  5483. },
  5484. toString: function() {
  5485. var parts = [ 'point1: ' + this._segment1._point ];
  5486. if (!this._segment1._handleOut.isZero())
  5487. parts.push('handle1: ' + this._segment1._handleOut);
  5488. if (!this._segment2._handleIn.isZero())
  5489. parts.push('handle2: ' + this._segment2._handleIn);
  5490. parts.push('point2: ' + this._segment2._point);
  5491. return '{ ' + parts.join(', ') + ' }';
  5492. },
  5493. classify: function() {
  5494. return Curve.classify(this.getValues());
  5495. },
  5496. remove: function() {
  5497. var removed = false;
  5498. if (this._path) {
  5499. var segment2 = this._segment2,
  5500. handleOut = segment2._handleOut;
  5501. removed = segment2.remove();
  5502. if (removed)
  5503. this._segment1._handleOut.set(handleOut);
  5504. }
  5505. return removed;
  5506. },
  5507. getPoint1: function() {
  5508. return this._segment1._point;
  5509. },
  5510. setPoint1: function() {
  5511. this._segment1._point.set(Point.read(arguments));
  5512. },
  5513. getPoint2: function() {
  5514. return this._segment2._point;
  5515. },
  5516. setPoint2: function() {
  5517. this._segment2._point.set(Point.read(arguments));
  5518. },
  5519. getHandle1: function() {
  5520. return this._segment1._handleOut;
  5521. },
  5522. setHandle1: function() {
  5523. this._segment1._handleOut.set(Point.read(arguments));
  5524. },
  5525. getHandle2: function() {
  5526. return this._segment2._handleIn;
  5527. },
  5528. setHandle2: function() {
  5529. this._segment2._handleIn.set(Point.read(arguments));
  5530. },
  5531. getSegment1: function() {
  5532. return this._segment1;
  5533. },
  5534. getSegment2: function() {
  5535. return this._segment2;
  5536. },
  5537. getPath: function() {
  5538. return this._path;
  5539. },
  5540. getIndex: function() {
  5541. return this._segment1._index;
  5542. },
  5543. getNext: function() {
  5544. var curves = this._path && this._path._curves;
  5545. return curves && (curves[this._segment1._index + 1]
  5546. || this._path._closed && curves[0]) || null;
  5547. },
  5548. getPrevious: function() {
  5549. var curves = this._path && this._path._curves;
  5550. return curves && (curves[this._segment1._index - 1]
  5551. || this._path._closed && curves[curves.length - 1]) || null;
  5552. },
  5553. isFirst: function() {
  5554. return !this._segment1._index;
  5555. },
  5556. isLast: function() {
  5557. var path = this._path;
  5558. return path && this._segment1._index === path._curves.length - 1
  5559. || false;
  5560. },
  5561. isSelected: function() {
  5562. return this.getPoint1().isSelected()
  5563. && this.getHandle1().isSelected()
  5564. && this.getHandle2().isSelected()
  5565. && this.getPoint2().isSelected();
  5566. },
  5567. setSelected: function(selected) {
  5568. this.getPoint1().setSelected(selected);
  5569. this.getHandle1().setSelected(selected);
  5570. this.getHandle2().setSelected(selected);
  5571. this.getPoint2().setSelected(selected);
  5572. },
  5573. getValues: function(matrix) {
  5574. return Curve.getValues(this._segment1, this._segment2, matrix);
  5575. },
  5576. getPoints: function() {
  5577. var coords = this.getValues(),
  5578. points = [];
  5579. for (var i = 0; i < 8; i += 2)
  5580. points.push(new Point(coords[i], coords[i + 1]));
  5581. return points;
  5582. }
  5583. }, {
  5584. getLength: function() {
  5585. if (this._length == null)
  5586. this._length = Curve.getLength(this.getValues(), 0, 1);
  5587. return this._length;
  5588. },
  5589. getArea: function() {
  5590. return Curve.getArea(this.getValues());
  5591. },
  5592. getLine: function() {
  5593. return new Line(this._segment1._point, this._segment2._point);
  5594. },
  5595. getPart: function(from, to) {
  5596. return new Curve(Curve.getPart(this.getValues(), from, to));
  5597. },
  5598. getPartLength: function(from, to) {
  5599. return Curve.getLength(this.getValues(), from, to);
  5600. },
  5601. divideAt: function(location) {
  5602. return this.divideAtTime(location && location.curve === this
  5603. ? location.time : this.getTimeAt(location));
  5604. },
  5605. divideAtTime: function(time, _setHandles) {
  5606. var tMin = 1e-8,
  5607. tMax = 1 - tMin,
  5608. res = null;
  5609. if (time >= tMin && time <= tMax) {
  5610. var parts = Curve.subdivide(this.getValues(), time),
  5611. left = parts[0],
  5612. right = parts[1],
  5613. setHandles = _setHandles || this.hasHandles(),
  5614. seg1 = this._segment1,
  5615. seg2 = this._segment2,
  5616. path = this._path;
  5617. if (setHandles) {
  5618. seg1._handleOut._set(left[2] - left[0], left[3] - left[1]);
  5619. seg2._handleIn._set(right[4] - right[6],right[5] - right[7]);
  5620. }
  5621. var x = left[6], y = left[7],
  5622. segment = new Segment(new Point(x, y),
  5623. setHandles && new Point(left[4] - x, left[5] - y),
  5624. setHandles && new Point(right[2] - x, right[3] - y));
  5625. if (path) {
  5626. path.insert(seg1._index + 1, segment);
  5627. res = this.getNext();
  5628. } else {
  5629. this._segment2 = segment;
  5630. this._changed();
  5631. res = new Curve(segment, seg2);
  5632. }
  5633. }
  5634. return res;
  5635. },
  5636. splitAt: function(location) {
  5637. var path = this._path;
  5638. return path ? path.splitAt(location) : null;
  5639. },
  5640. splitAtTime: function(time) {
  5641. return this.splitAt(this.getLocationAtTime(time));
  5642. },
  5643. divide: function(offset, isTime) {
  5644. return this.divideAtTime(offset === undefined ? 0.5 : isTime ? offset
  5645. : this.getTimeAt(offset));
  5646. },
  5647. split: function(offset, isTime) {
  5648. return this.splitAtTime(offset === undefined ? 0.5 : isTime ? offset
  5649. : this.getTimeAt(offset));
  5650. },
  5651. reversed: function() {
  5652. return new Curve(this._segment2.reversed(), this._segment1.reversed());
  5653. },
  5654. clearHandles: function() {
  5655. this._segment1._handleOut._set(0, 0);
  5656. this._segment2._handleIn._set(0, 0);
  5657. },
  5658. statics: {
  5659. getValues: function(segment1, segment2, matrix, straight) {
  5660. var p1 = segment1._point,
  5661. h1 = segment1._handleOut,
  5662. h2 = segment2._handleIn,
  5663. p2 = segment2._point,
  5664. x1 = p1.x, y1 = p1.y,
  5665. x2 = p2.x, y2 = p2.y,
  5666. values = straight
  5667. ? [ x1, y1, x1, y1, x2, y2, x2, y2 ]
  5668. : [
  5669. x1, y1,
  5670. x1 + h1._x, y1 + h1._y,
  5671. x2 + h2._x, y2 + h2._y,
  5672. x2, y2
  5673. ];
  5674. if (matrix)
  5675. matrix._transformCoordinates(values, values, 4);
  5676. return values;
  5677. },
  5678. subdivide: function(v, t) {
  5679. var x0 = v[0], y0 = v[1],
  5680. x1 = v[2], y1 = v[3],
  5681. x2 = v[4], y2 = v[5],
  5682. x3 = v[6], y3 = v[7];
  5683. if (t === undefined)
  5684. t = 0.5;
  5685. var u = 1 - t,
  5686. x4 = u * x0 + t * x1, y4 = u * y0 + t * y1,
  5687. x5 = u * x1 + t * x2, y5 = u * y1 + t * y2,
  5688. x6 = u * x2 + t * x3, y6 = u * y2 + t * y3,
  5689. x7 = u * x4 + t * x5, y7 = u * y4 + t * y5,
  5690. x8 = u * x5 + t * x6, y8 = u * y5 + t * y6,
  5691. x9 = u * x7 + t * x8, y9 = u * y7 + t * y8;
  5692. return [
  5693. [x0, y0, x4, y4, x7, y7, x9, y9],
  5694. [x9, y9, x8, y8, x6, y6, x3, y3]
  5695. ];
  5696. },
  5697. getMonoCurves: function(v, dir) {
  5698. var curves = [],
  5699. io = dir ? 0 : 1,
  5700. o0 = v[io + 0],
  5701. o1 = v[io + 2],
  5702. o2 = v[io + 4],
  5703. o3 = v[io + 6];
  5704. if ((o0 >= o1) === (o1 >= o2) && (o1 >= o2) === (o2 >= o3)
  5705. || Curve.isStraight(v)) {
  5706. curves.push(v);
  5707. } else {
  5708. var a = 3 * (o1 - o2) - o0 + o3,
  5709. b = 2 * (o0 + o2) - 4 * o1,
  5710. c = o1 - o0,
  5711. tMin = 1e-8,
  5712. tMax = 1 - tMin,
  5713. roots = [],
  5714. n = Numerical.solveQuadratic(a, b, c, roots, tMin, tMax);
  5715. if (!n) {
  5716. curves.push(v);
  5717. } else {
  5718. roots.sort();
  5719. var t = roots[0],
  5720. parts = Curve.subdivide(v, t);
  5721. curves.push(parts[0]);
  5722. if (n > 1) {
  5723. t = (roots[1] - t) / (1 - t);
  5724. parts = Curve.subdivide(parts[1], t);
  5725. curves.push(parts[0]);
  5726. }
  5727. curves.push(parts[1]);
  5728. }
  5729. }
  5730. return curves;
  5731. },
  5732. solveCubic: function (v, coord, val, roots, min, max) {
  5733. var v0 = v[coord],
  5734. v1 = v[coord + 2],
  5735. v2 = v[coord + 4],
  5736. v3 = v[coord + 6],
  5737. res = 0;
  5738. if ( !(v0 < val && v3 < val && v1 < val && v2 < val ||
  5739. v0 > val && v3 > val && v1 > val && v2 > val)) {
  5740. var c = 3 * (v1 - v0),
  5741. b = 3 * (v2 - v1) - c,
  5742. a = v3 - v0 - c - b;
  5743. res = Numerical.solveCubic(a, b, c, v0 - val, roots, min, max);
  5744. }
  5745. return res;
  5746. },
  5747. getTimeOf: function(v, point) {
  5748. var p0 = new Point(v[0], v[1]),
  5749. p3 = new Point(v[6], v[7]),
  5750. epsilon = 1e-12,
  5751. geomEpsilon = 1e-7,
  5752. t = point.isClose(p0, epsilon) ? 0
  5753. : point.isClose(p3, epsilon) ? 1
  5754. : null;
  5755. if (t === null) {
  5756. var coords = [point.x, point.y],
  5757. roots = [];
  5758. for (var c = 0; c < 2; c++) {
  5759. var count = Curve.solveCubic(v, c, coords[c], roots, 0, 1);
  5760. for (var i = 0; i < count; i++) {
  5761. var u = roots[i];
  5762. if (point.isClose(Curve.getPoint(v, u), geomEpsilon))
  5763. return u;
  5764. }
  5765. }
  5766. }
  5767. return point.isClose(p0, geomEpsilon) ? 0
  5768. : point.isClose(p3, geomEpsilon) ? 1
  5769. : null;
  5770. },
  5771. getNearestTime: function(v, point) {
  5772. if (Curve.isStraight(v)) {
  5773. var x0 = v[0], y0 = v[1],
  5774. x3 = v[6], y3 = v[7],
  5775. vx = x3 - x0, vy = y3 - y0,
  5776. det = vx * vx + vy * vy;
  5777. if (det === 0)
  5778. return 0;
  5779. var u = ((point.x - x0) * vx + (point.y - y0) * vy) / det;
  5780. return u < 1e-12 ? 0
  5781. : u > 0.999999999999 ? 1
  5782. : Curve.getTimeOf(v,
  5783. new Point(x0 + u * vx, y0 + u * vy));
  5784. }
  5785. var count = 100,
  5786. minDist = Infinity,
  5787. minT = 0;
  5788. function refine(t) {
  5789. if (t >= 0 && t <= 1) {
  5790. var dist = point.getDistance(Curve.getPoint(v, t), true);
  5791. if (dist < minDist) {
  5792. minDist = dist;
  5793. minT = t;
  5794. return true;
  5795. }
  5796. }
  5797. }
  5798. for (var i = 0; i <= count; i++)
  5799. refine(i / count);
  5800. var step = 1 / (count * 2);
  5801. while (step > 1e-8) {
  5802. if (!refine(minT - step) && !refine(minT + step))
  5803. step /= 2;
  5804. }
  5805. return minT;
  5806. },
  5807. getPart: function(v, from, to) {
  5808. var flip = from > to;
  5809. if (flip) {
  5810. var tmp = from;
  5811. from = to;
  5812. to = tmp;
  5813. }
  5814. if (from > 0)
  5815. v = Curve.subdivide(v, from)[1];
  5816. if (to < 1)
  5817. v = Curve.subdivide(v, (to - from) / (1 - from))[0];
  5818. return flip
  5819. ? [v[6], v[7], v[4], v[5], v[2], v[3], v[0], v[1]]
  5820. : v;
  5821. },
  5822. isFlatEnough: function(v, flatness) {
  5823. var x0 = v[0], y0 = v[1],
  5824. x1 = v[2], y1 = v[3],
  5825. x2 = v[4], y2 = v[5],
  5826. x3 = v[6], y3 = v[7],
  5827. ux = 3 * x1 - 2 * x0 - x3,
  5828. uy = 3 * y1 - 2 * y0 - y3,
  5829. vx = 3 * x2 - 2 * x3 - x0,
  5830. vy = 3 * y2 - 2 * y3 - y0;
  5831. return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
  5832. <= 16 * flatness * flatness;
  5833. },
  5834. getArea: function(v) {
  5835. var x0 = v[0], y0 = v[1],
  5836. x1 = v[2], y1 = v[3],
  5837. x2 = v[4], y2 = v[5],
  5838. x3 = v[6], y3 = v[7];
  5839. return 3 * ((y3 - y0) * (x1 + x2) - (x3 - x0) * (y1 + y2)
  5840. + y1 * (x0 - x2) - x1 * (y0 - y2)
  5841. + y3 * (x2 + x0 / 3) - x3 * (y2 + y0 / 3)) / 20;
  5842. },
  5843. getBounds: function(v) {
  5844. var min = v.slice(0, 2),
  5845. max = min.slice(),
  5846. roots = [0, 0];
  5847. for (var i = 0; i < 2; i++)
  5848. Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
  5849. i, 0, min, max, roots);
  5850. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  5851. },
  5852. _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
  5853. function add(value, padding) {
  5854. var left = value - padding,
  5855. right = value + padding;
  5856. if (left < min[coord])
  5857. min[coord] = left;
  5858. if (right > max[coord])
  5859. max[coord] = right;
  5860. }
  5861. padding /= 2;
  5862. var minPad = min[coord] - padding,
  5863. maxPad = max[coord] + padding;
  5864. if ( v0 < minPad || v1 < minPad || v2 < minPad || v3 < minPad ||
  5865. v0 > maxPad || v1 > maxPad || v2 > maxPad || v3 > maxPad) {
  5866. if (v1 < v0 != v1 < v3 && v2 < v0 != v2 < v3) {
  5867. add(v0, padding);
  5868. add(v3, padding);
  5869. } else {
  5870. var a = 3 * (v1 - v2) - v0 + v3,
  5871. b = 2 * (v0 + v2) - 4 * v1,
  5872. c = v1 - v0,
  5873. count = Numerical.solveQuadratic(a, b, c, roots),
  5874. tMin = 1e-8,
  5875. tMax = 1 - tMin;
  5876. add(v3, 0);
  5877. for (var i = 0; i < count; i++) {
  5878. var t = roots[i],
  5879. u = 1 - t;
  5880. if (tMin <= t && t <= tMax)
  5881. add(u * u * u * v0
  5882. + 3 * u * u * t * v1
  5883. + 3 * u * t * t * v2
  5884. + t * t * t * v3,
  5885. padding);
  5886. }
  5887. }
  5888. }
  5889. }
  5890. }}, Base.each(
  5891. ['getBounds', 'getStrokeBounds', 'getHandleBounds'],
  5892. function(name) {
  5893. this[name] = function() {
  5894. if (!this._bounds)
  5895. this._bounds = {};
  5896. var bounds = this._bounds[name];
  5897. if (!bounds) {
  5898. bounds = this._bounds[name] = Path[name](
  5899. [this._segment1, this._segment2], false, this._path);
  5900. }
  5901. return bounds.clone();
  5902. };
  5903. },
  5904. {
  5905. }), Base.each({
  5906. isStraight: function(p1, h1, h2, p2) {
  5907. if (h1.isZero() && h2.isZero()) {
  5908. return true;
  5909. } else {
  5910. var v = p2.subtract(p1);
  5911. if (v.isZero()) {
  5912. return false;
  5913. } else if (v.isCollinear(h1) && v.isCollinear(h2)) {
  5914. var l = new Line(p1, p2),
  5915. epsilon = 1e-7;
  5916. if (l.getDistance(p1.add(h1)) < epsilon &&
  5917. l.getDistance(p2.add(h2)) < epsilon) {
  5918. var div = v.dot(v),
  5919. s1 = v.dot(h1) / div,
  5920. s2 = v.dot(h2) / div;
  5921. return s1 >= 0 && s1 <= 1 && s2 <= 0 && s2 >= -1;
  5922. }
  5923. }
  5924. }
  5925. return false;
  5926. },
  5927. isLinear: function(p1, h1, h2, p2) {
  5928. var third = p2.subtract(p1).divide(3);
  5929. return h1.equals(third) && h2.negate().equals(third);
  5930. }
  5931. }, function(test, name) {
  5932. this[name] = function(epsilon) {
  5933. var seg1 = this._segment1,
  5934. seg2 = this._segment2;
  5935. return test(seg1._point, seg1._handleOut, seg2._handleIn, seg2._point,
  5936. epsilon);
  5937. };
  5938. this.statics[name] = function(v, epsilon) {
  5939. var x0 = v[0], y0 = v[1],
  5940. x3 = v[6], y3 = v[7];
  5941. return test(
  5942. new Point(x0, y0),
  5943. new Point(v[2] - x0, v[3] - y0),
  5944. new Point(v[4] - x3, v[5] - y3),
  5945. new Point(x3, y3), epsilon);
  5946. };
  5947. }, {
  5948. statics: {},
  5949. hasHandles: function() {
  5950. return !this._segment1._handleOut.isZero()
  5951. || !this._segment2._handleIn.isZero();
  5952. },
  5953. hasLength: function(epsilon) {
  5954. return (!this.getPoint1().equals(this.getPoint2()) || this.hasHandles())
  5955. && this.getLength() > (epsilon || 0);
  5956. },
  5957. isCollinear: function(curve) {
  5958. return curve && this.isStraight() && curve.isStraight()
  5959. && this.getLine().isCollinear(curve.getLine());
  5960. },
  5961. isHorizontal: function() {
  5962. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).y)
  5963. < 1e-8;
  5964. },
  5965. isVertical: function() {
  5966. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).x)
  5967. < 1e-8;
  5968. }
  5969. }), {
  5970. beans: false,
  5971. getLocationAt: function(offset, _isTime) {
  5972. return this.getLocationAtTime(
  5973. _isTime ? offset : this.getTimeAt(offset));
  5974. },
  5975. getLocationAtTime: function(t) {
  5976. return t != null && t >= 0 && t <= 1
  5977. ? new CurveLocation(this, t)
  5978. : null;
  5979. },
  5980. getTimeAt: function(offset, start) {
  5981. return Curve.getTimeAt(this.getValues(), offset, start);
  5982. },
  5983. getParameterAt: '#getTimeAt',
  5984. getTimesWithTangent: function () {
  5985. var tangent = Point.read(arguments);
  5986. return tangent.isZero()
  5987. ? []
  5988. : Curve.getTimesWithTangent(this.getValues(), tangent);
  5989. },
  5990. getOffsetAtTime: function(t) {
  5991. return this.getPartLength(0, t);
  5992. },
  5993. getLocationOf: function() {
  5994. return this.getLocationAtTime(this.getTimeOf(Point.read(arguments)));
  5995. },
  5996. getOffsetOf: function() {
  5997. var loc = this.getLocationOf.apply(this, arguments);
  5998. return loc ? loc.getOffset() : null;
  5999. },
  6000. getTimeOf: function() {
  6001. return Curve.getTimeOf(this.getValues(), Point.read(arguments));
  6002. },
  6003. getParameterOf: '#getTimeOf',
  6004. getNearestLocation: function() {
  6005. var point = Point.read(arguments),
  6006. values = this.getValues(),
  6007. t = Curve.getNearestTime(values, point),
  6008. pt = Curve.getPoint(values, t);
  6009. return new CurveLocation(this, t, pt, null, point.getDistance(pt));
  6010. },
  6011. getNearestPoint: function() {
  6012. var loc = this.getNearestLocation.apply(this, arguments);
  6013. return loc ? loc.getPoint() : loc;
  6014. }
  6015. },
  6016. new function() {
  6017. var methods = ['getPoint', 'getTangent', 'getNormal', 'getWeightedTangent',
  6018. 'getWeightedNormal', 'getCurvature'];
  6019. return Base.each(methods,
  6020. function(name) {
  6021. this[name + 'At'] = function(location, _isTime) {
  6022. var values = this.getValues();
  6023. return Curve[name](values, _isTime ? location
  6024. : Curve.getTimeAt(values, location));
  6025. };
  6026. this[name + 'AtTime'] = function(time) {
  6027. return Curve[name](this.getValues(), time);
  6028. };
  6029. }, {
  6030. statics: {
  6031. _evaluateMethods: methods
  6032. }
  6033. }
  6034. );
  6035. },
  6036. new function() {
  6037. function getLengthIntegrand(v) {
  6038. var x0 = v[0], y0 = v[1],
  6039. x1 = v[2], y1 = v[3],
  6040. x2 = v[4], y2 = v[5],
  6041. x3 = v[6], y3 = v[7],
  6042. ax = 9 * (x1 - x2) + 3 * (x3 - x0),
  6043. bx = 6 * (x0 + x2) - 12 * x1,
  6044. cx = 3 * (x1 - x0),
  6045. ay = 9 * (y1 - y2) + 3 * (y3 - y0),
  6046. by = 6 * (y0 + y2) - 12 * y1,
  6047. cy = 3 * (y1 - y0);
  6048. return function(t) {
  6049. var dx = (ax * t + bx) * t + cx,
  6050. dy = (ay * t + by) * t + cy;
  6051. return Math.sqrt(dx * dx + dy * dy);
  6052. };
  6053. }
  6054. function getIterations(a, b) {
  6055. return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
  6056. }
  6057. function evaluate(v, t, type, normalized) {
  6058. if (t == null || t < 0 || t > 1)
  6059. return null;
  6060. var x0 = v[0], y0 = v[1],
  6061. x1 = v[2], y1 = v[3],
  6062. x2 = v[4], y2 = v[5],
  6063. x3 = v[6], y3 = v[7],
  6064. isZero = Numerical.isZero;
  6065. if (isZero(x1 - x0) && isZero(y1 - y0)) {
  6066. x1 = x0;
  6067. y1 = y0;
  6068. }
  6069. if (isZero(x2 - x3) && isZero(y2 - y3)) {
  6070. x2 = x3;
  6071. y2 = y3;
  6072. }
  6073. var cx = 3 * (x1 - x0),
  6074. bx = 3 * (x2 - x1) - cx,
  6075. ax = x3 - x0 - cx - bx,
  6076. cy = 3 * (y1 - y0),
  6077. by = 3 * (y2 - y1) - cy,
  6078. ay = y3 - y0 - cy - by,
  6079. x, y;
  6080. if (type === 0) {
  6081. x = t === 0 ? x0 : t === 1 ? x3
  6082. : ((ax * t + bx) * t + cx) * t + x0;
  6083. y = t === 0 ? y0 : t === 1 ? y3
  6084. : ((ay * t + by) * t + cy) * t + y0;
  6085. } else {
  6086. var tMin = 1e-8,
  6087. tMax = 1 - tMin;
  6088. if (t < tMin) {
  6089. x = cx;
  6090. y = cy;
  6091. } else if (t > tMax) {
  6092. x = 3 * (x3 - x2);
  6093. y = 3 * (y3 - y2);
  6094. } else {
  6095. x = (3 * ax * t + 2 * bx) * t + cx;
  6096. y = (3 * ay * t + 2 * by) * t + cy;
  6097. }
  6098. if (normalized) {
  6099. if (x === 0 && y === 0 && (t < tMin || t > tMax)) {
  6100. x = x2 - x1;
  6101. y = y2 - y1;
  6102. }
  6103. var len = Math.sqrt(x * x + y * y);
  6104. if (len) {
  6105. x /= len;
  6106. y /= len;
  6107. }
  6108. }
  6109. if (type === 3) {
  6110. var x2 = 6 * ax * t + 2 * bx,
  6111. y2 = 6 * ay * t + 2 * by,
  6112. d = Math.pow(x * x + y * y, 3 / 2);
  6113. x = d !== 0 ? (x * y2 - y * x2) / d : 0;
  6114. y = 0;
  6115. }
  6116. }
  6117. return type === 2 ? new Point(y, -x) : new Point(x, y);
  6118. }
  6119. return { statics: {
  6120. classify: function(v) {
  6121. var x0 = v[0], y0 = v[1],
  6122. x1 = v[2], y1 = v[3],
  6123. x2 = v[4], y2 = v[5],
  6124. x3 = v[6], y3 = v[7],
  6125. a1 = x0 * (y3 - y2) + y0 * (x2 - x3) + x3 * y2 - y3 * x2,
  6126. a2 = x1 * (y0 - y3) + y1 * (x3 - x0) + x0 * y3 - y0 * x3,
  6127. a3 = x2 * (y1 - y0) + y2 * (x0 - x1) + x1 * y0 - y1 * x0,
  6128. d3 = 3 * a3,
  6129. d2 = d3 - a2,
  6130. d1 = d2 - a2 + a1,
  6131. l = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3),
  6132. s = l !== 0 ? 1 / l : 0,
  6133. isZero = Numerical.isZero,
  6134. serpentine = 'serpentine';
  6135. d1 *= s;
  6136. d2 *= s;
  6137. d3 *= s;
  6138. function type(type, t1, t2) {
  6139. var hasRoots = t1 !== undefined,
  6140. t1Ok = hasRoots && t1 > 0 && t1 < 1,
  6141. t2Ok = hasRoots && t2 > 0 && t2 < 1;
  6142. if (hasRoots && (!(t1Ok || t2Ok)
  6143. || type === 'loop' && !(t1Ok && t2Ok))) {
  6144. type = 'arch';
  6145. t1Ok = t2Ok = false;
  6146. }
  6147. return {
  6148. type: type,
  6149. roots: t1Ok || t2Ok
  6150. ? t1Ok && t2Ok
  6151. ? t1 < t2 ? [t1, t2] : [t2, t1]
  6152. : [t1Ok ? t1 : t2]
  6153. : null
  6154. };
  6155. }
  6156. if (isZero(d1)) {
  6157. return isZero(d2)
  6158. ? type(isZero(d3) ? 'line' : 'quadratic')
  6159. : type(serpentine, d3 / (3 * d2));
  6160. }
  6161. var d = 3 * d2 * d2 - 4 * d1 * d3;
  6162. if (isZero(d)) {
  6163. return type('cusp', d2 / (2 * d1));
  6164. }
  6165. var f1 = d > 0 ? Math.sqrt(d / 3) : Math.sqrt(-d),
  6166. f2 = 2 * d1;
  6167. return type(d > 0 ? serpentine : 'loop',
  6168. (d2 + f1) / f2,
  6169. (d2 - f1) / f2);
  6170. },
  6171. getLength: function(v, a, b, ds) {
  6172. if (a === undefined)
  6173. a = 0;
  6174. if (b === undefined)
  6175. b = 1;
  6176. if (Curve.isStraight(v)) {
  6177. var c = v;
  6178. if (b < 1) {
  6179. c = Curve.subdivide(c, b)[0];
  6180. a /= b;
  6181. }
  6182. if (a > 0) {
  6183. c = Curve.subdivide(c, a)[1];
  6184. }
  6185. var dx = c[6] - c[0],
  6186. dy = c[7] - c[1];
  6187. return Math.sqrt(dx * dx + dy * dy);
  6188. }
  6189. return Numerical.integrate(ds || getLengthIntegrand(v), a, b,
  6190. getIterations(a, b));
  6191. },
  6192. getTimeAt: function(v, offset, start) {
  6193. if (start === undefined)
  6194. start = offset < 0 ? 1 : 0;
  6195. if (offset === 0)
  6196. return start;
  6197. var abs = Math.abs,
  6198. epsilon = 1e-12,
  6199. forward = offset > 0,
  6200. a = forward ? start : 0,
  6201. b = forward ? 1 : start,
  6202. ds = getLengthIntegrand(v),
  6203. rangeLength = Curve.getLength(v, a, b, ds),
  6204. diff = abs(offset) - rangeLength;
  6205. if (abs(diff) < epsilon) {
  6206. return forward ? b : a;
  6207. } else if (diff > epsilon) {
  6208. return null;
  6209. }
  6210. var guess = offset / rangeLength,
  6211. length = 0;
  6212. function f(t) {
  6213. length += Numerical.integrate(ds, start, t,
  6214. getIterations(start, t));
  6215. start = t;
  6216. return length - offset;
  6217. }
  6218. return Numerical.findRoot(f, ds, start + guess, a, b, 32,
  6219. 1e-12);
  6220. },
  6221. getPoint: function(v, t) {
  6222. return evaluate(v, t, 0, false);
  6223. },
  6224. getTangent: function(v, t) {
  6225. return evaluate(v, t, 1, true);
  6226. },
  6227. getWeightedTangent: function(v, t) {
  6228. return evaluate(v, t, 1, false);
  6229. },
  6230. getNormal: function(v, t) {
  6231. return evaluate(v, t, 2, true);
  6232. },
  6233. getWeightedNormal: function(v, t) {
  6234. return evaluate(v, t, 2, false);
  6235. },
  6236. getCurvature: function(v, t) {
  6237. return evaluate(v, t, 3, false).x;
  6238. },
  6239. getPeaks: function(v) {
  6240. var x0 = v[0], y0 = v[1],
  6241. x1 = v[2], y1 = v[3],
  6242. x2 = v[4], y2 = v[5],
  6243. x3 = v[6], y3 = v[7],
  6244. ax = -x0 + 3 * x1 - 3 * x2 + x3,
  6245. bx = 3 * x0 - 6 * x1 + 3 * x2,
  6246. cx = -3 * x0 + 3 * x1,
  6247. ay = -y0 + 3 * y1 - 3 * y2 + y3,
  6248. by = 3 * y0 - 6 * y1 + 3 * y2,
  6249. cy = -3 * y0 + 3 * y1,
  6250. tMin = 1e-8,
  6251. tMax = 1 - tMin,
  6252. roots = [];
  6253. Numerical.solveCubic(
  6254. 9 * (ax * ax + ay * ay),
  6255. 9 * (ax * bx + by * ay),
  6256. 2 * (bx * bx + by * by) + 3 * (cx * ax + cy * ay),
  6257. (cx * bx + by * cy),
  6258. roots, tMin, tMax);
  6259. return roots.sort();
  6260. }
  6261. }};
  6262. },
  6263. new function() {
  6264. function addLocation(locations, include, c1, t1, c2, t2, overlap) {
  6265. var excludeStart = !overlap && c1.getPrevious() === c2,
  6266. excludeEnd = !overlap && c1 !== c2 && c1.getNext() === c2,
  6267. tMin = 1e-8,
  6268. tMax = 1 - tMin;
  6269. if (t1 !== null && t1 >= (excludeStart ? tMin : 0) &&
  6270. t1 <= (excludeEnd ? tMax : 1)) {
  6271. if (t2 !== null && t2 >= (excludeEnd ? tMin : 0) &&
  6272. t2 <= (excludeStart ? tMax : 1)) {
  6273. var loc1 = new CurveLocation(c1, t1, null, overlap),
  6274. loc2 = new CurveLocation(c2, t2, null, overlap);
  6275. loc1._intersection = loc2;
  6276. loc2._intersection = loc1;
  6277. if (!include || include(loc1)) {
  6278. CurveLocation.insert(locations, loc1, true);
  6279. }
  6280. }
  6281. }
  6282. }
  6283. function addCurveIntersections(v1, v2, c1, c2, locations, include, flip,
  6284. recursion, calls, tMin, tMax, uMin, uMax) {
  6285. if (++calls >= 4096 || ++recursion >= 40)
  6286. return calls;
  6287. var fatLineEpsilon = 1e-9,
  6288. q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7],
  6289. getSignedDistance = Line.getSignedDistance,
  6290. d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]),
  6291. d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]),
  6292. factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
  6293. dMin = factor * Math.min(0, d1, d2),
  6294. dMax = factor * Math.max(0, d1, d2),
  6295. dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]),
  6296. dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]),
  6297. dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]),
  6298. dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]),
  6299. hull = getConvexHull(dp0, dp1, dp2, dp3),
  6300. top = hull[0],
  6301. bottom = hull[1],
  6302. tMinClip,
  6303. tMaxClip;
  6304. if (d1 === 0 && d2 === 0
  6305. && dp0 === 0 && dp1 === 0 && dp2 === 0 && dp3 === 0
  6306. || (tMinClip = clipConvexHull(top, bottom, dMin, dMax)) == null
  6307. || (tMaxClip = clipConvexHull(top.reverse(), bottom.reverse(),
  6308. dMin, dMax)) == null)
  6309. return calls;
  6310. var tMinNew = tMin + (tMax - tMin) * tMinClip,
  6311. tMaxNew = tMin + (tMax - tMin) * tMaxClip;
  6312. if (Math.max(uMax - uMin, tMaxNew - tMinNew) < fatLineEpsilon) {
  6313. var t = (tMinNew + tMaxNew) / 2,
  6314. u = (uMin + uMax) / 2;
  6315. addLocation(locations, include,
  6316. flip ? c2 : c1, flip ? u : t,
  6317. flip ? c1 : c2, flip ? t : u);
  6318. } else {
  6319. v1 = Curve.getPart(v1, tMinClip, tMaxClip);
  6320. if (tMaxClip - tMinClip > 0.8) {
  6321. if (tMaxNew - tMinNew > uMax - uMin) {
  6322. var parts = Curve.subdivide(v1, 0.5),
  6323. t = (tMinNew + tMaxNew) / 2;
  6324. calls = addCurveIntersections(
  6325. v2, parts[0], c2, c1, locations, include, !flip,
  6326. recursion, calls, uMin, uMax, tMinNew, t);
  6327. calls = addCurveIntersections(
  6328. v2, parts[1], c2, c1, locations, include, !flip,
  6329. recursion, calls, uMin, uMax, t, tMaxNew);
  6330. } else {
  6331. var parts = Curve.subdivide(v2, 0.5),
  6332. u = (uMin + uMax) / 2;
  6333. calls = addCurveIntersections(
  6334. parts[0], v1, c2, c1, locations, include, !flip,
  6335. recursion, calls, uMin, u, tMinNew, tMaxNew);
  6336. calls = addCurveIntersections(
  6337. parts[1], v1, c2, c1, locations, include, !flip,
  6338. recursion, calls, u, uMax, tMinNew, tMaxNew);
  6339. }
  6340. } else {
  6341. if (uMax - uMin >= fatLineEpsilon) {
  6342. calls = addCurveIntersections(
  6343. v2, v1, c2, c1, locations, include, !flip,
  6344. recursion, calls, uMin, uMax, tMinNew, tMaxNew);
  6345. } else {
  6346. calls = addCurveIntersections(
  6347. v1, v2, c1, c2, locations, include, flip,
  6348. recursion, calls, tMinNew, tMaxNew, uMin, uMax);
  6349. }
  6350. }
  6351. }
  6352. return calls;
  6353. }
  6354. function getConvexHull(dq0, dq1, dq2, dq3) {
  6355. var p0 = [ 0, dq0 ],
  6356. p1 = [ 1 / 3, dq1 ],
  6357. p2 = [ 2 / 3, dq2 ],
  6358. p3 = [ 1, dq3 ],
  6359. dist1 = dq1 - (2 * dq0 + dq3) / 3,
  6360. dist2 = dq2 - (dq0 + 2 * dq3) / 3,
  6361. hull;
  6362. if (dist1 * dist2 < 0) {
  6363. hull = [[p0, p1, p3], [p0, p2, p3]];
  6364. } else {
  6365. var distRatio = dist1 / dist2;
  6366. hull = [
  6367. distRatio >= 2 ? [p0, p1, p3]
  6368. : distRatio <= 0.5 ? [p0, p2, p3]
  6369. : [p0, p1, p2, p3],
  6370. [p0, p3]
  6371. ];
  6372. }
  6373. return (dist1 || dist2) < 0 ? hull.reverse() : hull;
  6374. }
  6375. function clipConvexHull(hullTop, hullBottom, dMin, dMax) {
  6376. if (hullTop[0][1] < dMin) {
  6377. return clipConvexHullPart(hullTop, true, dMin);
  6378. } else if (hullBottom[0][1] > dMax) {
  6379. return clipConvexHullPart(hullBottom, false, dMax);
  6380. } else {
  6381. return hullTop[0][0];
  6382. }
  6383. }
  6384. function clipConvexHullPart(part, top, threshold) {
  6385. var px = part[0][0],
  6386. py = part[0][1];
  6387. for (var i = 1, l = part.length; i < l; i++) {
  6388. var qx = part[i][0],
  6389. qy = part[i][1];
  6390. if (top ? qy >= threshold : qy <= threshold) {
  6391. return qy === threshold ? qx
  6392. : px + (threshold - py) * (qx - px) / (qy - py);
  6393. }
  6394. px = qx;
  6395. py = qy;
  6396. }
  6397. return null;
  6398. }
  6399. function getCurveLineIntersections(v, px, py, vx, vy) {
  6400. var isZero = Numerical.isZero;
  6401. if (isZero(vx) && isZero(vy)) {
  6402. var t = Curve.getTimeOf(v, new Point(px, py));
  6403. return t === null ? [] : [t];
  6404. }
  6405. var angle = Math.atan2(-vy, vx),
  6406. sin = Math.sin(angle),
  6407. cos = Math.cos(angle),
  6408. rv = [],
  6409. roots = [];
  6410. for (var i = 0; i < 8; i += 2) {
  6411. var x = v[i] - px,
  6412. y = v[i + 1] - py;
  6413. rv.push(
  6414. x * cos - y * sin,
  6415. x * sin + y * cos);
  6416. }
  6417. Curve.solveCubic(rv, 1, 0, roots, 0, 1);
  6418. return roots;
  6419. }
  6420. function addCurveLineIntersections(v1, v2, c1, c2, locations, include,
  6421. flip) {
  6422. var x1 = v2[0], y1 = v2[1],
  6423. x2 = v2[6], y2 = v2[7],
  6424. roots = getCurveLineIntersections(v1, x1, y1, x2 - x1, y2 - y1);
  6425. for (var i = 0, l = roots.length; i < l; i++) {
  6426. var t1 = roots[i],
  6427. p1 = Curve.getPoint(v1, t1),
  6428. t2 = Curve.getTimeOf(v2, p1);
  6429. if (t2 !== null) {
  6430. addLocation(locations, include,
  6431. flip ? c2 : c1, flip ? t2 : t1,
  6432. flip ? c1 : c2, flip ? t1 : t2);
  6433. }
  6434. }
  6435. }
  6436. function addLineIntersection(v1, v2, c1, c2, locations, include) {
  6437. var pt = Line.intersect(
  6438. v1[0], v1[1], v1[6], v1[7],
  6439. v2[0], v2[1], v2[6], v2[7]);
  6440. if (pt) {
  6441. addLocation(locations, include,
  6442. c1, Curve.getTimeOf(v1, pt),
  6443. c2, Curve.getTimeOf(v2, pt));
  6444. }
  6445. }
  6446. function getCurveIntersections(v1, v2, c1, c2, locations, include) {
  6447. var epsilon = 1e-12,
  6448. min = Math.min,
  6449. max = Math.max;
  6450. if (max(v1[0], v1[2], v1[4], v1[6]) + epsilon >
  6451. min(v2[0], v2[2], v2[4], v2[6]) &&
  6452. min(v1[0], v1[2], v1[4], v1[6]) - epsilon <
  6453. max(v2[0], v2[2], v2[4], v2[6]) &&
  6454. max(v1[1], v1[3], v1[5], v1[7]) + epsilon >
  6455. min(v2[1], v2[3], v2[5], v2[7]) &&
  6456. min(v1[1], v1[3], v1[5], v1[7]) - epsilon <
  6457. max(v2[1], v2[3], v2[5], v2[7])) {
  6458. var overlaps = getOverlaps(v1, v2);
  6459. if (overlaps) {
  6460. for (var i = 0; i < 2; i++) {
  6461. var overlap = overlaps[i];
  6462. addLocation(locations, include,
  6463. c1, overlap[0],
  6464. c2, overlap[1], true);
  6465. }
  6466. } else {
  6467. var straight1 = Curve.isStraight(v1),
  6468. straight2 = Curve.isStraight(v2),
  6469. straight = straight1 && straight2,
  6470. flip = straight1 && !straight2,
  6471. before = locations.length;
  6472. (straight
  6473. ? addLineIntersection
  6474. : straight1 || straight2
  6475. ? addCurveLineIntersections
  6476. : addCurveIntersections)(
  6477. flip ? v2 : v1, flip ? v1 : v2,
  6478. flip ? c2 : c1, flip ? c1 : c2,
  6479. locations, include, flip,
  6480. 0, 0, 0, 1, 0, 1);
  6481. if (!straight || locations.length === before) {
  6482. for (var i = 0; i < 4; i++) {
  6483. var t1 = i >> 1,
  6484. t2 = i & 1,
  6485. i1 = t1 * 6,
  6486. i2 = t2 * 6,
  6487. p1 = new Point(v1[i1], v1[i1 + 1]),
  6488. p2 = new Point(v2[i2], v2[i2 + 1]);
  6489. if (p1.isClose(p2, epsilon)) {
  6490. addLocation(locations, include,
  6491. c1, t1,
  6492. c2, t2);
  6493. }
  6494. }
  6495. }
  6496. }
  6497. }
  6498. return locations;
  6499. }
  6500. function getLoopIntersection(v1, c1, locations, include) {
  6501. var info = Curve.classify(v1);
  6502. if (info.type === 'loop') {
  6503. var roots = info.roots;
  6504. addLocation(locations, include,
  6505. c1, roots[0],
  6506. c1, roots[1]);
  6507. }
  6508. return locations;
  6509. }
  6510. function getIntersections(curves1, curves2, include, matrix1, matrix2,
  6511. _returnFirst) {
  6512. var self = !curves2;
  6513. if (self)
  6514. curves2 = curves1;
  6515. var length1 = curves1.length,
  6516. length2 = curves2.length,
  6517. values2 = [],
  6518. arrays = [],
  6519. locations,
  6520. current;
  6521. for (var i = 0; i < length2; i++)
  6522. values2[i] = curves2[i].getValues(matrix2);
  6523. for (var i = 0; i < length1; i++) {
  6524. var curve1 = curves1[i],
  6525. values1 = self ? values2[i] : curve1.getValues(matrix1),
  6526. path1 = curve1.getPath();
  6527. if (path1 !== current) {
  6528. current = path1;
  6529. locations = [];
  6530. arrays.push(locations);
  6531. }
  6532. if (self) {
  6533. getLoopIntersection(values1, curve1, locations, include);
  6534. }
  6535. for (var j = self ? i + 1 : 0; j < length2; j++) {
  6536. if (_returnFirst && locations.length)
  6537. return locations;
  6538. getCurveIntersections(values1, values2[j], curve1, curves2[j],
  6539. locations, include);
  6540. }
  6541. }
  6542. locations = [];
  6543. for (var i = 0, l = arrays.length; i < l; i++) {
  6544. Base.push(locations, arrays[i]);
  6545. }
  6546. return locations;
  6547. }
  6548. function getOverlaps(v1, v2) {
  6549. function getSquaredLineLength(v) {
  6550. var x = v[6] - v[0],
  6551. y = v[7] - v[1];
  6552. return x * x + y * y;
  6553. }
  6554. var abs = Math.abs,
  6555. getDistance = Line.getDistance,
  6556. timeEpsilon = 1e-8,
  6557. geomEpsilon = 1e-7,
  6558. straight1 = Curve.isStraight(v1),
  6559. straight2 = Curve.isStraight(v2),
  6560. straightBoth = straight1 && straight2,
  6561. flip = getSquaredLineLength(v1) < getSquaredLineLength(v2),
  6562. l1 = flip ? v2 : v1,
  6563. l2 = flip ? v1 : v2,
  6564. px = l1[0], py = l1[1],
  6565. vx = l1[6] - px, vy = l1[7] - py;
  6566. if (getDistance(px, py, vx, vy, l2[0], l2[1], true) < geomEpsilon &&
  6567. getDistance(px, py, vx, vy, l2[6], l2[7], true) < geomEpsilon) {
  6568. if (!straightBoth &&
  6569. getDistance(px, py, vx, vy, l1[2], l1[3], true) < geomEpsilon &&
  6570. getDistance(px, py, vx, vy, l1[4], l1[5], true) < geomEpsilon &&
  6571. getDistance(px, py, vx, vy, l2[2], l2[3], true) < geomEpsilon &&
  6572. getDistance(px, py, vx, vy, l2[4], l2[5], true) < geomEpsilon) {
  6573. straight1 = straight2 = straightBoth = true;
  6574. }
  6575. } else if (straightBoth) {
  6576. return null;
  6577. }
  6578. if (straight1 ^ straight2) {
  6579. return null;
  6580. }
  6581. var v = [v1, v2],
  6582. pairs = [];
  6583. for (var i = 0; i < 4 && pairs.length < 2; i++) {
  6584. var i1 = i & 1,
  6585. i2 = i1 ^ 1,
  6586. t1 = i >> 1,
  6587. t2 = Curve.getTimeOf(v[i1], new Point(
  6588. v[i2][t1 ? 6 : 0],
  6589. v[i2][t1 ? 7 : 1]));
  6590. if (t2 != null) {
  6591. var pair = i1 ? [t1, t2] : [t2, t1];
  6592. if (!pairs.length ||
  6593. abs(pair[0] - pairs[0][0]) > timeEpsilon &&
  6594. abs(pair[1] - pairs[0][1]) > timeEpsilon) {
  6595. pairs.push(pair);
  6596. }
  6597. }
  6598. if (i > 2 && !pairs.length)
  6599. break;
  6600. }
  6601. if (pairs.length !== 2) {
  6602. pairs = null;
  6603. } else if (!straightBoth) {
  6604. var o1 = Curve.getPart(v1, pairs[0][0], pairs[1][0]),
  6605. o2 = Curve.getPart(v2, pairs[0][1], pairs[1][1]);
  6606. if (abs(o2[2] - o1[2]) > geomEpsilon ||
  6607. abs(o2[3] - o1[3]) > geomEpsilon ||
  6608. abs(o2[4] - o1[4]) > geomEpsilon ||
  6609. abs(o2[5] - o1[5]) > geomEpsilon)
  6610. pairs = null;
  6611. }
  6612. return pairs;
  6613. }
  6614. function getTimesWithTangent(v, tangent) {
  6615. var x0 = v[0], y0 = v[1],
  6616. x1 = v[2], y1 = v[3],
  6617. x2 = v[4], y2 = v[5],
  6618. x3 = v[6], y3 = v[7],
  6619. normalized = tangent.normalize(),
  6620. tx = normalized.x,
  6621. ty = normalized.y,
  6622. ax = 3 * x3 - 9 * x2 + 9 * x1 - 3 * x0,
  6623. ay = 3 * y3 - 9 * y2 + 9 * y1 - 3 * y0,
  6624. bx = 6 * x2 - 12 * x1 + 6 * x0,
  6625. by = 6 * y2 - 12 * y1 + 6 * y0,
  6626. cx = 3 * x1 - 3 * x0,
  6627. cy = 3 * y1 - 3 * y0,
  6628. den = 2 * ax * ty - 2 * ay * tx,
  6629. times = [];
  6630. if (Math.abs(den) < Numerical.CURVETIME_EPSILON) {
  6631. var num = ax * cy - ay * cx,
  6632. den = ax * by - ay * bx;
  6633. if (den != 0) {
  6634. var t = -num / den;
  6635. if (t >= 0 && t <= 1) times.push(t);
  6636. }
  6637. } else {
  6638. var delta = (bx * bx - 4 * ax * cx) * ty * ty +
  6639. (-2 * bx * by + 4 * ay * cx + 4 * ax * cy) * tx * ty +
  6640. (by * by - 4 * ay * cy) * tx * tx,
  6641. k = bx * ty - by * tx;
  6642. if (delta >= 0 && den != 0) {
  6643. var d = Math.sqrt(delta),
  6644. t0 = -(k + d) / den,
  6645. t1 = (-k + d) / den;
  6646. if (t0 >= 0 && t0 <= 1) times.push(t0);
  6647. if (t1 >= 0 && t1 <= 1) times.push(t1);
  6648. }
  6649. }
  6650. return times;
  6651. }
  6652. return {
  6653. getIntersections: function(curve) {
  6654. var v1 = this.getValues(),
  6655. v2 = curve && curve !== this && curve.getValues();
  6656. return v2 ? getCurveIntersections(v1, v2, this, curve, [])
  6657. : getLoopIntersection(v1, this, []);
  6658. },
  6659. statics: {
  6660. getOverlaps: getOverlaps,
  6661. getIntersections: getIntersections,
  6662. getCurveLineIntersections: getCurveLineIntersections,
  6663. getTimesWithTangent: getTimesWithTangent
  6664. }
  6665. };
  6666. });
  6667. var CurveLocation = Base.extend({
  6668. _class: 'CurveLocation',
  6669. initialize: function CurveLocation(curve, time, point, _overlap, _distance) {
  6670. if (time >= 0.99999999) {
  6671. var next = curve.getNext();
  6672. if (next) {
  6673. time = 0;
  6674. curve = next;
  6675. }
  6676. }
  6677. this._setCurve(curve);
  6678. this._time = time;
  6679. this._point = point || curve.getPointAtTime(time);
  6680. this._overlap = _overlap;
  6681. this._distance = _distance;
  6682. this._intersection = this._next = this._previous = null;
  6683. },
  6684. _setCurve: function(curve) {
  6685. var path = curve._path;
  6686. this._path = path;
  6687. this._version = path ? path._version : 0;
  6688. this._curve = curve;
  6689. this._segment = null;
  6690. this._segment1 = curve._segment1;
  6691. this._segment2 = curve._segment2;
  6692. },
  6693. _setSegment: function(segment) {
  6694. this._setCurve(segment.getCurve());
  6695. this._segment = segment;
  6696. this._time = segment === this._segment1 ? 0 : 1;
  6697. this._point = segment._point.clone();
  6698. },
  6699. getSegment: function() {
  6700. var segment = this._segment;
  6701. if (!segment) {
  6702. var curve = this.getCurve(),
  6703. time = this.getTime();
  6704. if (time === 0) {
  6705. segment = curve._segment1;
  6706. } else if (time === 1) {
  6707. segment = curve._segment2;
  6708. } else if (time != null) {
  6709. segment = curve.getPartLength(0, time)
  6710. < curve.getPartLength(time, 1)
  6711. ? curve._segment1
  6712. : curve._segment2;
  6713. }
  6714. this._segment = segment;
  6715. }
  6716. return segment;
  6717. },
  6718. getCurve: function() {
  6719. var path = this._path,
  6720. that = this;
  6721. if (path && path._version !== this._version) {
  6722. this._time = this._offset = this._curveOffset = this._curve = null;
  6723. }
  6724. function trySegment(segment) {
  6725. var curve = segment && segment.getCurve();
  6726. if (curve && (that._time = curve.getTimeOf(that._point)) != null) {
  6727. that._setCurve(curve);
  6728. return curve;
  6729. }
  6730. }
  6731. return this._curve
  6732. || trySegment(this._segment)
  6733. || trySegment(this._segment1)
  6734. || trySegment(this._segment2.getPrevious());
  6735. },
  6736. getPath: function() {
  6737. var curve = this.getCurve();
  6738. return curve && curve._path;
  6739. },
  6740. getIndex: function() {
  6741. var curve = this.getCurve();
  6742. return curve && curve.getIndex();
  6743. },
  6744. getTime: function() {
  6745. var curve = this.getCurve(),
  6746. time = this._time;
  6747. return curve && time == null
  6748. ? this._time = curve.getTimeOf(this._point)
  6749. : time;
  6750. },
  6751. getParameter: '#getTime',
  6752. getPoint: function() {
  6753. return this._point;
  6754. },
  6755. getOffset: function() {
  6756. var offset = this._offset;
  6757. if (offset == null) {
  6758. offset = 0;
  6759. var path = this.getPath(),
  6760. index = this.getIndex();
  6761. if (path && index != null) {
  6762. var curves = path.getCurves();
  6763. for (var i = 0; i < index; i++)
  6764. offset += curves[i].getLength();
  6765. }
  6766. this._offset = offset += this.getCurveOffset();
  6767. }
  6768. return offset;
  6769. },
  6770. getCurveOffset: function() {
  6771. var offset = this._curveOffset;
  6772. if (offset == null) {
  6773. var curve = this.getCurve(),
  6774. time = this.getTime();
  6775. this._curveOffset = offset = time != null && curve
  6776. && curve.getPartLength(0, time);
  6777. }
  6778. return offset;
  6779. },
  6780. getIntersection: function() {
  6781. return this._intersection;
  6782. },
  6783. getDistance: function() {
  6784. return this._distance;
  6785. },
  6786. divide: function() {
  6787. var curve = this.getCurve(),
  6788. res = curve && curve.divideAtTime(this.getTime());
  6789. if (res) {
  6790. this._setSegment(res._segment1);
  6791. }
  6792. return res;
  6793. },
  6794. split: function() {
  6795. var curve = this.getCurve(),
  6796. path = curve._path,
  6797. res = curve && curve.splitAtTime(this.getTime());
  6798. if (res) {
  6799. this._setSegment(path.getLastSegment());
  6800. }
  6801. return res;
  6802. },
  6803. equals: function(loc, _ignoreOther) {
  6804. var res = this === loc;
  6805. if (!res && loc instanceof CurveLocation) {
  6806. var c1 = this.getCurve(),
  6807. c2 = loc.getCurve(),
  6808. p1 = c1._path,
  6809. p2 = c2._path;
  6810. if (p1 === p2) {
  6811. var abs = Math.abs,
  6812. epsilon = 1e-7,
  6813. diff = abs(this.getOffset() - loc.getOffset()),
  6814. i1 = !_ignoreOther && this._intersection,
  6815. i2 = !_ignoreOther && loc._intersection;
  6816. res = (diff < epsilon
  6817. || p1 && abs(p1.getLength() - diff) < epsilon)
  6818. && (!i1 && !i2 || i1 && i2 && i1.equals(i2, true));
  6819. }
  6820. }
  6821. return res;
  6822. },
  6823. toString: function() {
  6824. var parts = [],
  6825. point = this.getPoint(),
  6826. f = Formatter.instance;
  6827. if (point)
  6828. parts.push('point: ' + point);
  6829. var index = this.getIndex();
  6830. if (index != null)
  6831. parts.push('index: ' + index);
  6832. var time = this.getTime();
  6833. if (time != null)
  6834. parts.push('time: ' + f.number(time));
  6835. if (this._distance != null)
  6836. parts.push('distance: ' + f.number(this._distance));
  6837. return '{ ' + parts.join(', ') + ' }';
  6838. },
  6839. isTouching: function() {
  6840. var inter = this._intersection;
  6841. if (inter && this.getTangent().isCollinear(inter.getTangent())) {
  6842. var curve1 = this.getCurve(),
  6843. curve2 = inter.getCurve();
  6844. return !(curve1.isStraight() && curve2.isStraight()
  6845. && curve1.getLine().intersect(curve2.getLine()));
  6846. }
  6847. return false;
  6848. },
  6849. isCrossing: function() {
  6850. var inter = this._intersection;
  6851. if (!inter)
  6852. return false;
  6853. var t1 = this.getTime(),
  6854. t2 = inter.getTime(),
  6855. tMin = 1e-8,
  6856. tMax = 1 - tMin,
  6857. t1Inside = t1 >= tMin && t1 <= tMax,
  6858. t2Inside = t2 >= tMin && t2 <= tMax;
  6859. if (t1Inside && t2Inside)
  6860. return !this.isTouching();
  6861. var c2 = this.getCurve(),
  6862. c1 = t1 < tMin ? c2.getPrevious() : c2,
  6863. c4 = inter.getCurve(),
  6864. c3 = t2 < tMin ? c4.getPrevious() : c4;
  6865. if (t1 > tMax)
  6866. c2 = c2.getNext();
  6867. if (t2 > tMax)
  6868. c4 = c4.getNext();
  6869. if (!c1 || !c2 || !c3 || !c4)
  6870. return false;
  6871. var offsets = [];
  6872. function addOffsets(curve, end) {
  6873. var v = curve.getValues(),
  6874. roots = Curve.classify(v).roots || Curve.getPeaks(v),
  6875. count = roots.length,
  6876. t = end && count > 1 ? roots[count - 1]
  6877. : count > 0 ? roots[0]
  6878. : 0.5;
  6879. offsets.push(Curve.getLength(v, end ? t : 0, end ? 1 : t) / 2);
  6880. }
  6881. function isInRange(angle, min, max) {
  6882. return min < max
  6883. ? angle > min && angle < max
  6884. : angle > min || angle < max;
  6885. }
  6886. if (!t1Inside) {
  6887. addOffsets(c1, true);
  6888. addOffsets(c2, false);
  6889. }
  6890. if (!t2Inside) {
  6891. addOffsets(c3, true);
  6892. addOffsets(c4, false);
  6893. }
  6894. var pt = this.getPoint(),
  6895. offset = Math.min.apply(Math, offsets),
  6896. v2 = t1Inside ? c2.getTangentAtTime(t1)
  6897. : c2.getPointAt(offset).subtract(pt),
  6898. v1 = t1Inside ? v2.negate()
  6899. : c1.getPointAt(-offset).subtract(pt),
  6900. v4 = t2Inside ? c4.getTangentAtTime(t2)
  6901. : c4.getPointAt(offset).subtract(pt),
  6902. v3 = t2Inside ? v4.negate()
  6903. : c3.getPointAt(-offset).subtract(pt),
  6904. a1 = v1.getAngle(),
  6905. a2 = v2.getAngle(),
  6906. a3 = v3.getAngle(),
  6907. a4 = v4.getAngle();
  6908. return !!(t1Inside
  6909. ? (isInRange(a1, a3, a4) ^ isInRange(a2, a3, a4)) &&
  6910. (isInRange(a1, a4, a3) ^ isInRange(a2, a4, a3))
  6911. : (isInRange(a3, a1, a2) ^ isInRange(a4, a1, a2)) &&
  6912. (isInRange(a3, a2, a1) ^ isInRange(a4, a2, a1)));
  6913. },
  6914. hasOverlap: function() {
  6915. return !!this._overlap;
  6916. }
  6917. }, Base.each(Curve._evaluateMethods, function(name) {
  6918. var get = name + 'At';
  6919. this[name] = function() {
  6920. var curve = this.getCurve(),
  6921. time = this.getTime();
  6922. return time != null && curve && curve[get](time, true);
  6923. };
  6924. }, {
  6925. preserve: true
  6926. }),
  6927. new function() {
  6928. function insert(locations, loc, merge) {
  6929. var length = locations.length,
  6930. l = 0,
  6931. r = length - 1;
  6932. function search(index, dir) {
  6933. for (var i = index + dir; i >= -1 && i <= length; i += dir) {
  6934. var loc2 = locations[((i % length) + length) % length];
  6935. if (!loc.getPoint().isClose(loc2.getPoint(),
  6936. 1e-7))
  6937. break;
  6938. if (loc.equals(loc2))
  6939. return loc2;
  6940. }
  6941. return null;
  6942. }
  6943. while (l <= r) {
  6944. var m = (l + r) >>> 1,
  6945. loc2 = locations[m],
  6946. found;
  6947. if (merge && (found = loc.equals(loc2) ? loc2
  6948. : (search(m, -1) || search(m, 1)))) {
  6949. if (loc._overlap) {
  6950. found._overlap = found._intersection._overlap = true;
  6951. }
  6952. return found;
  6953. }
  6954. var path1 = loc.getPath(),
  6955. path2 = loc2.getPath(),
  6956. diff = path1 !== path2
  6957. ? path1._id - path2._id
  6958. : (loc.getIndex() + loc.getTime())
  6959. - (loc2.getIndex() + loc2.getTime());
  6960. if (diff < 0) {
  6961. r = m - 1;
  6962. } else {
  6963. l = m + 1;
  6964. }
  6965. }
  6966. locations.splice(l, 0, loc);
  6967. return loc;
  6968. }
  6969. return { statics: {
  6970. insert: insert,
  6971. expand: function(locations) {
  6972. var expanded = locations.slice();
  6973. for (var i = locations.length - 1; i >= 0; i--) {
  6974. insert(expanded, locations[i]._intersection, false);
  6975. }
  6976. return expanded;
  6977. }
  6978. }};
  6979. });
  6980. var PathItem = Item.extend({
  6981. _class: 'PathItem',
  6982. _selectBounds: false,
  6983. _canScaleStroke: true,
  6984. beans: true,
  6985. initialize: function PathItem() {
  6986. },
  6987. statics: {
  6988. create: function(arg) {
  6989. var data,
  6990. segments,
  6991. compound;
  6992. if (Base.isPlainObject(arg)) {
  6993. segments = arg.segments;
  6994. data = arg.pathData;
  6995. } else if (Array.isArray(arg)) {
  6996. segments = arg;
  6997. } else if (typeof arg === 'string') {
  6998. data = arg;
  6999. }
  7000. if (segments) {
  7001. var first = segments[0];
  7002. compound = first && Array.isArray(first[0]);
  7003. } else if (data) {
  7004. compound = (data.match(/m/gi) || []).length > 1
  7005. || /z\s*\S+/i.test(data);
  7006. }
  7007. var ctor = compound ? CompoundPath : Path;
  7008. return new ctor(arg);
  7009. }
  7010. },
  7011. _asPathItem: function() {
  7012. return this;
  7013. },
  7014. isClockwise: function() {
  7015. return this.getArea() >= 0;
  7016. },
  7017. setClockwise: function(clockwise) {
  7018. if (this.isClockwise() != (clockwise = !!clockwise))
  7019. this.reverse();
  7020. },
  7021. setPathData: function(data) {
  7022. var parts = data && data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
  7023. coords,
  7024. relative = false,
  7025. previous,
  7026. control,
  7027. current = new Point(),
  7028. start = new Point();
  7029. function getCoord(index, coord) {
  7030. var val = +coords[index];
  7031. if (relative)
  7032. val += current[coord];
  7033. return val;
  7034. }
  7035. function getPoint(index) {
  7036. return new Point(
  7037. getCoord(index, 'x'),
  7038. getCoord(index + 1, 'y')
  7039. );
  7040. }
  7041. this.clear();
  7042. for (var i = 0, l = parts && parts.length; i < l; i++) {
  7043. var part = parts[i],
  7044. command = part[0],
  7045. lower = command.toLowerCase();
  7046. coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
  7047. var length = coords && coords.length;
  7048. relative = command === lower;
  7049. if (previous === 'z' && !/[mz]/.test(lower))
  7050. this.moveTo(current);
  7051. switch (lower) {
  7052. case 'm':
  7053. case 'l':
  7054. var move = lower === 'm';
  7055. for (var j = 0; j < length; j += 2) {
  7056. this[move ? 'moveTo' : 'lineTo'](current = getPoint(j));
  7057. if (move) {
  7058. start = current;
  7059. move = false;
  7060. }
  7061. }
  7062. control = current;
  7063. break;
  7064. case 'h':
  7065. case 'v':
  7066. var coord = lower === 'h' ? 'x' : 'y';
  7067. current = current.clone();
  7068. for (var j = 0; j < length; j++) {
  7069. current[coord] = getCoord(j, coord);
  7070. this.lineTo(current);
  7071. }
  7072. control = current;
  7073. break;
  7074. case 'c':
  7075. for (var j = 0; j < length; j += 6) {
  7076. this.cubicCurveTo(
  7077. getPoint(j),
  7078. control = getPoint(j + 2),
  7079. current = getPoint(j + 4));
  7080. }
  7081. break;
  7082. case 's':
  7083. for (var j = 0; j < length; j += 4) {
  7084. this.cubicCurveTo(
  7085. /[cs]/.test(previous)
  7086. ? current.multiply(2).subtract(control)
  7087. : current,
  7088. control = getPoint(j),
  7089. current = getPoint(j + 2));
  7090. previous = lower;
  7091. }
  7092. break;
  7093. case 'q':
  7094. for (var j = 0; j < length; j += 4) {
  7095. this.quadraticCurveTo(
  7096. control = getPoint(j),
  7097. current = getPoint(j + 2));
  7098. }
  7099. break;
  7100. case 't':
  7101. for (var j = 0; j < length; j += 2) {
  7102. this.quadraticCurveTo(
  7103. control = (/[qt]/.test(previous)
  7104. ? current.multiply(2).subtract(control)
  7105. : current),
  7106. current = getPoint(j));
  7107. previous = lower;
  7108. }
  7109. break;
  7110. case 'a':
  7111. for (var j = 0; j < length; j += 7) {
  7112. this.arcTo(current = getPoint(j + 5),
  7113. new Size(+coords[j], +coords[j + 1]),
  7114. +coords[j + 2], +coords[j + 4], +coords[j + 3]);
  7115. }
  7116. break;
  7117. case 'z':
  7118. this.closePath(1e-12);
  7119. current = start;
  7120. break;
  7121. }
  7122. previous = lower;
  7123. }
  7124. },
  7125. _canComposite: function() {
  7126. return !(this.hasFill() && this.hasStroke());
  7127. },
  7128. _contains: function(point) {
  7129. var winding = point.isInside(
  7130. this.getBounds({ internal: true, handle: true }))
  7131. ? this._getWinding(point)
  7132. : {};
  7133. return winding.onPath || !!(this.getFillRule() === 'evenodd'
  7134. ? winding.windingL & 1 || winding.windingR & 1
  7135. : winding.winding);
  7136. },
  7137. getIntersections: function(path, include, _matrix, _returnFirst) {
  7138. var self = this === path || !path,
  7139. matrix1 = this._matrix._orNullIfIdentity(),
  7140. matrix2 = self ? matrix1
  7141. : (_matrix || path._matrix)._orNullIfIdentity();
  7142. return self || this.getBounds(matrix1).intersects(
  7143. path.getBounds(matrix2), 1e-12)
  7144. ? Curve.getIntersections(
  7145. this.getCurves(), !self && path.getCurves(), include,
  7146. matrix1, matrix2, _returnFirst)
  7147. : [];
  7148. },
  7149. getCrossings: function(path) {
  7150. return this.getIntersections(path, function(inter) {
  7151. return inter.hasOverlap() || inter.isCrossing();
  7152. });
  7153. },
  7154. getNearestLocation: function() {
  7155. var point = Point.read(arguments),
  7156. curves = this.getCurves(),
  7157. minDist = Infinity,
  7158. minLoc = null;
  7159. for (var i = 0, l = curves.length; i < l; i++) {
  7160. var loc = curves[i].getNearestLocation(point);
  7161. if (loc._distance < minDist) {
  7162. minDist = loc._distance;
  7163. minLoc = loc;
  7164. }
  7165. }
  7166. return minLoc;
  7167. },
  7168. getNearestPoint: function() {
  7169. var loc = this.getNearestLocation.apply(this, arguments);
  7170. return loc ? loc.getPoint() : loc;
  7171. },
  7172. interpolate: function(from, to, factor) {
  7173. var isPath = !this._children,
  7174. name = isPath ? '_segments' : '_children',
  7175. itemsFrom = from[name],
  7176. itemsTo = to[name],
  7177. items = this[name];
  7178. if (!itemsFrom || !itemsTo || itemsFrom.length !== itemsTo.length) {
  7179. throw new Error('Invalid operands in interpolate() call: ' +
  7180. from + ', ' + to);
  7181. }
  7182. var current = items.length,
  7183. length = itemsTo.length;
  7184. if (current < length) {
  7185. var ctor = isPath ? Segment : Path;
  7186. for (var i = current; i < length; i++) {
  7187. this.add(new ctor());
  7188. }
  7189. } else if (current > length) {
  7190. this[isPath ? 'removeSegments' : 'removeChildren'](length, current);
  7191. }
  7192. for (var i = 0; i < length; i++) {
  7193. items[i].interpolate(itemsFrom[i], itemsTo[i], factor);
  7194. }
  7195. if (isPath) {
  7196. this.setClosed(from._closed);
  7197. this._changed(9);
  7198. }
  7199. },
  7200. compare: function(path) {
  7201. var ok = false;
  7202. if (path) {
  7203. var paths1 = this._children || [this],
  7204. paths2 = path._children ? path._children.slice() : [path],
  7205. length1 = paths1.length,
  7206. length2 = paths2.length,
  7207. matched = [],
  7208. count = 0;
  7209. ok = true;
  7210. for (var i1 = length1 - 1; i1 >= 0 && ok; i1--) {
  7211. var path1 = paths1[i1];
  7212. ok = false;
  7213. for (var i2 = length2 - 1; i2 >= 0 && !ok; i2--) {
  7214. if (path1.compare(paths2[i2])) {
  7215. if (!matched[i2]) {
  7216. matched[i2] = true;
  7217. count++;
  7218. }
  7219. ok = true;
  7220. }
  7221. }
  7222. }
  7223. ok = ok && count === length2;
  7224. }
  7225. return ok;
  7226. },
  7227. });
  7228. var Path = PathItem.extend({
  7229. _class: 'Path',
  7230. _serializeFields: {
  7231. segments: [],
  7232. closed: false
  7233. },
  7234. initialize: function Path(arg) {
  7235. this._closed = false;
  7236. this._segments = [];
  7237. this._version = 0;
  7238. var segments = Array.isArray(arg)
  7239. ? typeof arg[0] === 'object'
  7240. ? arg
  7241. : arguments
  7242. : arg && (arg.size === undefined && (arg.x !== undefined
  7243. || arg.point !== undefined))
  7244. ? arguments
  7245. : null;
  7246. if (segments && segments.length > 0) {
  7247. this.setSegments(segments);
  7248. } else {
  7249. this._curves = undefined;
  7250. this._segmentSelection = 0;
  7251. if (!segments && typeof arg === 'string') {
  7252. this.setPathData(arg);
  7253. arg = null;
  7254. }
  7255. }
  7256. this._initialize(!segments && arg);
  7257. },
  7258. _equals: function(item) {
  7259. return this._closed === item._closed
  7260. && Base.equals(this._segments, item._segments);
  7261. },
  7262. copyContent: function(source) {
  7263. this.setSegments(source._segments);
  7264. this._closed = source._closed;
  7265. },
  7266. _changed: function _changed(flags) {
  7267. _changed.base.call(this, flags);
  7268. if (flags & 8) {
  7269. this._length = this._area = undefined;
  7270. if (flags & 32) {
  7271. this._version++;
  7272. } else if (this._curves) {
  7273. for (var i = 0, l = this._curves.length; i < l; i++)
  7274. this._curves[i]._changed();
  7275. }
  7276. } else if (flags & 64) {
  7277. this._bounds = undefined;
  7278. }
  7279. },
  7280. getStyle: function() {
  7281. var parent = this._parent;
  7282. return (parent instanceof CompoundPath ? parent : this)._style;
  7283. },
  7284. getSegments: function() {
  7285. return this._segments;
  7286. },
  7287. setSegments: function(segments) {
  7288. var fullySelected = this.isFullySelected(),
  7289. length = segments && segments.length;
  7290. this._segments.length = 0;
  7291. this._segmentSelection = 0;
  7292. this._curves = undefined;
  7293. if (length) {
  7294. var last = segments[length - 1];
  7295. if (typeof last === 'boolean') {
  7296. this.setClosed(last);
  7297. length--;
  7298. }
  7299. this._add(Segment.readList(segments, 0, {}, length));
  7300. }
  7301. if (fullySelected)
  7302. this.setFullySelected(true);
  7303. },
  7304. getFirstSegment: function() {
  7305. return this._segments[0];
  7306. },
  7307. getLastSegment: function() {
  7308. return this._segments[this._segments.length - 1];
  7309. },
  7310. getCurves: function() {
  7311. var curves = this._curves,
  7312. segments = this._segments;
  7313. if (!curves) {
  7314. var length = this._countCurves();
  7315. curves = this._curves = new Array(length);
  7316. for (var i = 0; i < length; i++)
  7317. curves[i] = new Curve(this, segments[i],
  7318. segments[i + 1] || segments[0]);
  7319. }
  7320. return curves;
  7321. },
  7322. getFirstCurve: function() {
  7323. return this.getCurves()[0];
  7324. },
  7325. getLastCurve: function() {
  7326. var curves = this.getCurves();
  7327. return curves[curves.length - 1];
  7328. },
  7329. isClosed: function() {
  7330. return this._closed;
  7331. },
  7332. setClosed: function(closed) {
  7333. if (this._closed != (closed = !!closed)) {
  7334. this._closed = closed;
  7335. if (this._curves) {
  7336. var length = this._curves.length = this._countCurves();
  7337. if (closed)
  7338. this._curves[length - 1] = new Curve(this,
  7339. this._segments[length - 1], this._segments[0]);
  7340. }
  7341. this._changed(41);
  7342. }
  7343. }
  7344. }, {
  7345. beans: true,
  7346. getPathData: function(_matrix, _precision) {
  7347. var segments = this._segments,
  7348. length = segments.length,
  7349. f = new Formatter(_precision),
  7350. coords = new Array(6),
  7351. first = true,
  7352. curX, curY,
  7353. prevX, prevY,
  7354. inX, inY,
  7355. outX, outY,
  7356. parts = [];
  7357. function addSegment(segment, skipLine) {
  7358. segment._transformCoordinates(_matrix, coords);
  7359. curX = coords[0];
  7360. curY = coords[1];
  7361. if (first) {
  7362. parts.push('M' + f.pair(curX, curY));
  7363. first = false;
  7364. } else {
  7365. inX = coords[2];
  7366. inY = coords[3];
  7367. if (inX === curX && inY === curY
  7368. && outX === prevX && outY === prevY) {
  7369. if (!skipLine) {
  7370. var dx = curX - prevX,
  7371. dy = curY - prevY;
  7372. parts.push(
  7373. dx === 0 ? 'v' + f.number(dy)
  7374. : dy === 0 ? 'h' + f.number(dx)
  7375. : 'l' + f.pair(dx, dy));
  7376. }
  7377. } else {
  7378. parts.push('c' + f.pair(outX - prevX, outY - prevY)
  7379. + ' ' + f.pair( inX - prevX, inY - prevY)
  7380. + ' ' + f.pair(curX - prevX, curY - prevY));
  7381. }
  7382. }
  7383. prevX = curX;
  7384. prevY = curY;
  7385. outX = coords[4];
  7386. outY = coords[5];
  7387. }
  7388. if (!length)
  7389. return '';
  7390. for (var i = 0; i < length; i++)
  7391. addSegment(segments[i]);
  7392. if (this._closed && length > 0) {
  7393. addSegment(segments[0], true);
  7394. parts.push('z');
  7395. }
  7396. return parts.join('');
  7397. },
  7398. isEmpty: function() {
  7399. return !this._segments.length;
  7400. },
  7401. _transformContent: function(matrix) {
  7402. var segments = this._segments,
  7403. coords = new Array(6);
  7404. for (var i = 0, l = segments.length; i < l; i++)
  7405. segments[i]._transformCoordinates(matrix, coords, true);
  7406. return true;
  7407. },
  7408. _add: function(segs, index) {
  7409. var segments = this._segments,
  7410. curves = this._curves,
  7411. amount = segs.length,
  7412. append = index == null,
  7413. index = append ? segments.length : index;
  7414. for (var i = 0; i < amount; i++) {
  7415. var segment = segs[i];
  7416. if (segment._path)
  7417. segment = segs[i] = segment.clone();
  7418. segment._path = this;
  7419. segment._index = index + i;
  7420. if (segment._selection)
  7421. this._updateSelection(segment, 0, segment._selection);
  7422. }
  7423. if (append) {
  7424. Base.push(segments, segs);
  7425. } else {
  7426. segments.splice.apply(segments, [index, 0].concat(segs));
  7427. for (var i = index + amount, l = segments.length; i < l; i++)
  7428. segments[i]._index = i;
  7429. }
  7430. if (curves) {
  7431. var total = this._countCurves(),
  7432. start = index > 0 && index + amount - 1 === total ? index - 1
  7433. : index,
  7434. insert = start,
  7435. end = Math.min(start + amount, total);
  7436. if (segs._curves) {
  7437. curves.splice.apply(curves, [start, 0].concat(segs._curves));
  7438. insert += segs._curves.length;
  7439. }
  7440. for (var i = insert; i < end; i++)
  7441. curves.splice(i, 0, new Curve(this, null, null));
  7442. this._adjustCurves(start, end);
  7443. }
  7444. this._changed(41);
  7445. return segs;
  7446. },
  7447. _adjustCurves: function(start, end) {
  7448. var segments = this._segments,
  7449. curves = this._curves,
  7450. curve;
  7451. for (var i = start; i < end; i++) {
  7452. curve = curves[i];
  7453. curve._path = this;
  7454. curve._segment1 = segments[i];
  7455. curve._segment2 = segments[i + 1] || segments[0];
  7456. curve._changed();
  7457. }
  7458. if (curve = curves[this._closed && !start ? segments.length - 1
  7459. : start - 1]) {
  7460. curve._segment2 = segments[start] || segments[0];
  7461. curve._changed();
  7462. }
  7463. if (curve = curves[end]) {
  7464. curve._segment1 = segments[end];
  7465. curve._changed();
  7466. }
  7467. },
  7468. _countCurves: function() {
  7469. var length = this._segments.length;
  7470. return !this._closed && length > 0 ? length - 1 : length;
  7471. },
  7472. add: function(segment1 ) {
  7473. return arguments.length > 1 && typeof segment1 !== 'number'
  7474. ? this._add(Segment.readList(arguments))
  7475. : this._add([ Segment.read(arguments) ])[0];
  7476. },
  7477. insert: function(index, segment1 ) {
  7478. return arguments.length > 2 && typeof segment1 !== 'number'
  7479. ? this._add(Segment.readList(arguments, 1), index)
  7480. : this._add([ Segment.read(arguments, 1) ], index)[0];
  7481. },
  7482. addSegment: function() {
  7483. return this._add([ Segment.read(arguments) ])[0];
  7484. },
  7485. insertSegment: function(index ) {
  7486. return this._add([ Segment.read(arguments, 1) ], index)[0];
  7487. },
  7488. addSegments: function(segments) {
  7489. return this._add(Segment.readList(segments));
  7490. },
  7491. insertSegments: function(index, segments) {
  7492. return this._add(Segment.readList(segments), index);
  7493. },
  7494. removeSegment: function(index) {
  7495. return this.removeSegments(index, index + 1)[0] || null;
  7496. },
  7497. removeSegments: function(start, end, _includeCurves) {
  7498. start = start || 0;
  7499. end = Base.pick(end, this._segments.length);
  7500. var segments = this._segments,
  7501. curves = this._curves,
  7502. count = segments.length,
  7503. removed = segments.splice(start, end - start),
  7504. amount = removed.length;
  7505. if (!amount)
  7506. return removed;
  7507. for (var i = 0; i < amount; i++) {
  7508. var segment = removed[i];
  7509. if (segment._selection)
  7510. this._updateSelection(segment, segment._selection, 0);
  7511. segment._index = segment._path = null;
  7512. }
  7513. for (var i = start, l = segments.length; i < l; i++)
  7514. segments[i]._index = i;
  7515. if (curves) {
  7516. var index = start > 0 && end === count + (this._closed ? 1 : 0)
  7517. ? start - 1
  7518. : start,
  7519. curves = curves.splice(index, amount);
  7520. for (var i = curves.length - 1; i >= 0; i--)
  7521. curves[i]._path = null;
  7522. if (_includeCurves)
  7523. removed._curves = curves.slice(1);
  7524. this._adjustCurves(index, index);
  7525. }
  7526. this._changed(41);
  7527. return removed;
  7528. },
  7529. clear: '#removeSegments',
  7530. hasHandles: function() {
  7531. var segments = this._segments;
  7532. for (var i = 0, l = segments.length; i < l; i++) {
  7533. if (segments[i].hasHandles())
  7534. return true;
  7535. }
  7536. return false;
  7537. },
  7538. clearHandles: function() {
  7539. var segments = this._segments;
  7540. for (var i = 0, l = segments.length; i < l; i++)
  7541. segments[i].clearHandles();
  7542. },
  7543. getLength: function() {
  7544. if (this._length == null) {
  7545. var curves = this.getCurves(),
  7546. length = 0;
  7547. for (var i = 0, l = curves.length; i < l; i++)
  7548. length += curves[i].getLength();
  7549. this._length = length;
  7550. }
  7551. return this._length;
  7552. },
  7553. getArea: function() {
  7554. var area = this._area;
  7555. if (area == null) {
  7556. var segments = this._segments,
  7557. closed = this._closed;
  7558. area = 0;
  7559. for (var i = 0, l = segments.length; i < l; i++) {
  7560. var last = i + 1 === l;
  7561. area += Curve.getArea(Curve.getValues(
  7562. segments[i], segments[last ? 0 : i + 1],
  7563. null, last && !closed));
  7564. }
  7565. this._area = area;
  7566. }
  7567. return area;
  7568. },
  7569. isFullySelected: function() {
  7570. var length = this._segments.length;
  7571. return this.isSelected() && length > 0 && this._segmentSelection
  7572. === length * 7;
  7573. },
  7574. setFullySelected: function(selected) {
  7575. if (selected)
  7576. this._selectSegments(true);
  7577. this.setSelected(selected);
  7578. },
  7579. setSelection: function setSelection(selection) {
  7580. if (!(selection & 1))
  7581. this._selectSegments(false);
  7582. setSelection.base.call(this, selection);
  7583. },
  7584. _selectSegments: function(selected) {
  7585. var segments = this._segments,
  7586. length = segments.length,
  7587. selection = selected ? 7 : 0;
  7588. this._segmentSelection = selection * length;
  7589. for (var i = 0; i < length; i++)
  7590. segments[i]._selection = selection;
  7591. },
  7592. _updateSelection: function(segment, oldSelection, newSelection) {
  7593. segment._selection = newSelection;
  7594. var selection = this._segmentSelection += newSelection - oldSelection;
  7595. if (selection > 0)
  7596. this.setSelected(true);
  7597. },
  7598. divideAt: function(location) {
  7599. var loc = this.getLocationAt(location),
  7600. curve;
  7601. return loc && (curve = loc.getCurve().divideAt(loc.getCurveOffset()))
  7602. ? curve._segment1
  7603. : null;
  7604. },
  7605. splitAt: function(location) {
  7606. var loc = this.getLocationAt(location),
  7607. index = loc && loc.index,
  7608. time = loc && loc.time,
  7609. tMin = 1e-8,
  7610. tMax = 1 - tMin;
  7611. if (time > tMax) {
  7612. index++;
  7613. time = 0;
  7614. }
  7615. var curves = this.getCurves();
  7616. if (index >= 0 && index < curves.length) {
  7617. if (time >= tMin) {
  7618. curves[index++].divideAtTime(time);
  7619. }
  7620. var segs = this.removeSegments(index, this._segments.length, true),
  7621. path;
  7622. if (this._closed) {
  7623. this.setClosed(false);
  7624. path = this;
  7625. } else {
  7626. path = new Path(Item.NO_INSERT);
  7627. path.insertAbove(this);
  7628. path.copyAttributes(this);
  7629. }
  7630. path._add(segs, 0);
  7631. this.addSegment(segs[0]);
  7632. return path;
  7633. }
  7634. return null;
  7635. },
  7636. split: function(index, time) {
  7637. var curve,
  7638. location = time === undefined ? index
  7639. : (curve = this.getCurves()[index])
  7640. && curve.getLocationAtTime(time);
  7641. return location != null ? this.splitAt(location) : null;
  7642. },
  7643. join: function(path, tolerance) {
  7644. var epsilon = tolerance || 0;
  7645. if (path && path !== this) {
  7646. var segments = path._segments,
  7647. last1 = this.getLastSegment(),
  7648. last2 = path.getLastSegment();
  7649. if (!last2)
  7650. return this;
  7651. if (last1 && last1._point.isClose(last2._point, epsilon))
  7652. path.reverse();
  7653. var first2 = path.getFirstSegment();
  7654. if (last1 && last1._point.isClose(first2._point, epsilon)) {
  7655. last1.setHandleOut(first2._handleOut);
  7656. this._add(segments.slice(1));
  7657. } else {
  7658. var first1 = this.getFirstSegment();
  7659. if (first1 && first1._point.isClose(first2._point, epsilon))
  7660. path.reverse();
  7661. last2 = path.getLastSegment();
  7662. if (first1 && first1._point.isClose(last2._point, epsilon)) {
  7663. first1.setHandleIn(last2._handleIn);
  7664. this._add(segments.slice(0, segments.length - 1), 0);
  7665. } else {
  7666. this._add(segments.slice());
  7667. }
  7668. }
  7669. if (path._closed)
  7670. this._add([segments[0]]);
  7671. path.remove();
  7672. }
  7673. var first = this.getFirstSegment(),
  7674. last = this.getLastSegment();
  7675. if (first !== last && first._point.isClose(last._point, epsilon)) {
  7676. first.setHandleIn(last._handleIn);
  7677. last.remove();
  7678. this.setClosed(true);
  7679. }
  7680. return this;
  7681. },
  7682. reduce: function(options) {
  7683. var curves = this.getCurves(),
  7684. simplify = options && options.simplify,
  7685. tolerance = simplify ? 1e-7 : 0;
  7686. for (var i = curves.length - 1; i >= 0; i--) {
  7687. var curve = curves[i];
  7688. if (!curve.hasHandles() && (!curve.hasLength(tolerance)
  7689. || simplify && curve.isCollinear(curve.getNext())))
  7690. curve.remove();
  7691. }
  7692. return this;
  7693. },
  7694. reverse: function() {
  7695. this._segments.reverse();
  7696. for (var i = 0, l = this._segments.length; i < l; i++) {
  7697. var segment = this._segments[i];
  7698. var handleIn = segment._handleIn;
  7699. segment._handleIn = segment._handleOut;
  7700. segment._handleOut = handleIn;
  7701. segment._index = i;
  7702. }
  7703. this._curves = null;
  7704. this._changed(9);
  7705. },
  7706. flatten: function(flatness) {
  7707. var flattener = new PathFlattener(this, flatness || 0.25, 256, true),
  7708. parts = flattener.parts,
  7709. length = parts.length,
  7710. segments = [];
  7711. for (var i = 0; i < length; i++) {
  7712. segments.push(new Segment(parts[i].curve.slice(0, 2)));
  7713. }
  7714. if (!this._closed && length > 0) {
  7715. segments.push(new Segment(parts[length - 1].curve.slice(6)));
  7716. }
  7717. this.setSegments(segments);
  7718. },
  7719. simplify: function(tolerance) {
  7720. var segments = new PathFitter(this).fit(tolerance || 2.5);
  7721. if (segments)
  7722. this.setSegments(segments);
  7723. return !!segments;
  7724. },
  7725. smooth: function(options) {
  7726. var that = this,
  7727. opts = options || {},
  7728. type = opts.type || 'asymmetric',
  7729. segments = this._segments,
  7730. length = segments.length,
  7731. closed = this._closed;
  7732. function getIndex(value, _default) {
  7733. var index = value && value.index;
  7734. if (index != null) {
  7735. var path = value.path;
  7736. if (path && path !== that)
  7737. throw new Error(value._class + ' ' + index + ' of ' + path
  7738. + ' is not part of ' + that);
  7739. if (_default && value instanceof Curve)
  7740. index++;
  7741. } else {
  7742. index = typeof value === 'number' ? value : _default;
  7743. }
  7744. return Math.min(index < 0 && closed
  7745. ? index % length
  7746. : index < 0 ? index + length : index, length - 1);
  7747. }
  7748. var loop = closed && opts.from === undefined && opts.to === undefined,
  7749. from = getIndex(opts.from, 0),
  7750. to = getIndex(opts.to, length - 1);
  7751. if (from > to) {
  7752. if (closed) {
  7753. from -= length;
  7754. } else {
  7755. var tmp = from;
  7756. from = to;
  7757. to = tmp;
  7758. }
  7759. }
  7760. if (/^(?:asymmetric|continuous)$/.test(type)) {
  7761. var asymmetric = type === 'asymmetric',
  7762. min = Math.min,
  7763. amount = to - from + 1,
  7764. n = amount - 1,
  7765. padding = loop ? min(amount, 4) : 1,
  7766. paddingLeft = padding,
  7767. paddingRight = padding,
  7768. knots = [];
  7769. if (!closed) {
  7770. paddingLeft = min(1, from);
  7771. paddingRight = min(1, length - to - 1);
  7772. }
  7773. n += paddingLeft + paddingRight;
  7774. if (n <= 1)
  7775. return;
  7776. for (var i = 0, j = from - paddingLeft; i <= n; i++, j++) {
  7777. knots[i] = segments[(j < 0 ? j + length : j) % length]._point;
  7778. }
  7779. var x = knots[0]._x + 2 * knots[1]._x,
  7780. y = knots[0]._y + 2 * knots[1]._y,
  7781. f = 2,
  7782. n_1 = n - 1,
  7783. rx = [x],
  7784. ry = [y],
  7785. rf = [f],
  7786. px = [],
  7787. py = [];
  7788. for (var i = 1; i < n; i++) {
  7789. var internal = i < n_1,
  7790. a = internal ? 1 : asymmetric ? 1 : 2,
  7791. b = internal ? 4 : asymmetric ? 2 : 7,
  7792. u = internal ? 4 : asymmetric ? 3 : 8,
  7793. v = internal ? 2 : asymmetric ? 0 : 1,
  7794. m = a / f;
  7795. f = rf[i] = b - m;
  7796. x = rx[i] = u * knots[i]._x + v * knots[i + 1]._x - m * x;
  7797. y = ry[i] = u * knots[i]._y + v * knots[i + 1]._y - m * y;
  7798. }
  7799. px[n_1] = rx[n_1] / rf[n_1];
  7800. py[n_1] = ry[n_1] / rf[n_1];
  7801. for (var i = n - 2; i >= 0; i--) {
  7802. px[i] = (rx[i] - px[i + 1]) / rf[i];
  7803. py[i] = (ry[i] - py[i + 1]) / rf[i];
  7804. }
  7805. px[n] = (3 * knots[n]._x - px[n_1]) / 2;
  7806. py[n] = (3 * knots[n]._y - py[n_1]) / 2;
  7807. for (var i = paddingLeft, max = n - paddingRight, j = from;
  7808. i <= max; i++, j++) {
  7809. var segment = segments[j < 0 ? j + length : j],
  7810. pt = segment._point,
  7811. hx = px[i] - pt._x,
  7812. hy = py[i] - pt._y;
  7813. if (loop || i < max)
  7814. segment.setHandleOut(hx, hy);
  7815. if (loop || i > paddingLeft)
  7816. segment.setHandleIn(-hx, -hy);
  7817. }
  7818. } else {
  7819. for (var i = from; i <= to; i++) {
  7820. segments[i < 0 ? i + length : i].smooth(opts,
  7821. !loop && i === from, !loop && i === to);
  7822. }
  7823. }
  7824. },
  7825. toShape: function(insert) {
  7826. if (!this._closed)
  7827. return null;
  7828. var segments = this._segments,
  7829. type,
  7830. size,
  7831. radius,
  7832. topCenter;
  7833. function isCollinear(i, j) {
  7834. var seg1 = segments[i],
  7835. seg2 = seg1.getNext(),
  7836. seg3 = segments[j],
  7837. seg4 = seg3.getNext();
  7838. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  7839. && seg3._handleOut.isZero() && seg4._handleIn.isZero()
  7840. && seg2._point.subtract(seg1._point).isCollinear(
  7841. seg4._point.subtract(seg3._point));
  7842. }
  7843. function isOrthogonal(i) {
  7844. var seg2 = segments[i],
  7845. seg1 = seg2.getPrevious(),
  7846. seg3 = seg2.getNext();
  7847. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  7848. && seg2._handleOut.isZero() && seg3._handleIn.isZero()
  7849. && seg2._point.subtract(seg1._point).isOrthogonal(
  7850. seg3._point.subtract(seg2._point));
  7851. }
  7852. function isArc(i) {
  7853. var seg1 = segments[i],
  7854. seg2 = seg1.getNext(),
  7855. handle1 = seg1._handleOut,
  7856. handle2 = seg2._handleIn,
  7857. kappa = 0.5522847498307936;
  7858. if (handle1.isOrthogonal(handle2)) {
  7859. var pt1 = seg1._point,
  7860. pt2 = seg2._point,
  7861. corner = new Line(pt1, handle1, true).intersect(
  7862. new Line(pt2, handle2, true), true);
  7863. return corner && Numerical.isZero(handle1.getLength() /
  7864. corner.subtract(pt1).getLength() - kappa)
  7865. && Numerical.isZero(handle2.getLength() /
  7866. corner.subtract(pt2).getLength() - kappa);
  7867. }
  7868. return false;
  7869. }
  7870. function getDistance(i, j) {
  7871. return segments[i]._point.getDistance(segments[j]._point);
  7872. }
  7873. if (!this.hasHandles() && segments.length === 4
  7874. && isCollinear(0, 2) && isCollinear(1, 3) && isOrthogonal(1)) {
  7875. type = Shape.Rectangle;
  7876. size = new Size(getDistance(0, 3), getDistance(0, 1));
  7877. topCenter = segments[1]._point.add(segments[2]._point).divide(2);
  7878. } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
  7879. && isArc(6) && isCollinear(1, 5) && isCollinear(3, 7)) {
  7880. type = Shape.Rectangle;
  7881. size = new Size(getDistance(1, 6), getDistance(0, 3));
  7882. radius = size.subtract(new Size(getDistance(0, 7),
  7883. getDistance(1, 2))).divide(2);
  7884. topCenter = segments[3]._point.add(segments[4]._point).divide(2);
  7885. } else if (segments.length === 4
  7886. && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
  7887. if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
  7888. type = Shape.Circle;
  7889. radius = getDistance(0, 2) / 2;
  7890. } else {
  7891. type = Shape.Ellipse;
  7892. radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
  7893. }
  7894. topCenter = segments[1]._point;
  7895. }
  7896. if (type) {
  7897. var center = this.getPosition(true),
  7898. shape = new type({
  7899. center: center,
  7900. size: size,
  7901. radius: radius,
  7902. insert: false
  7903. });
  7904. shape.copyAttributes(this, true);
  7905. shape._matrix.prepend(this._matrix);
  7906. shape.rotate(topCenter.subtract(center).getAngle() + 90);
  7907. if (insert === undefined || insert)
  7908. shape.insertAbove(this);
  7909. return shape;
  7910. }
  7911. return null;
  7912. },
  7913. toPath: '#clone',
  7914. compare: function compare(path) {
  7915. if (!path || path instanceof CompoundPath)
  7916. return compare.base.call(this, path);
  7917. var curves1 = this.getCurves(),
  7918. curves2 = path.getCurves(),
  7919. length1 = curves1.length,
  7920. length2 = curves2.length;
  7921. if (!length1 || !length2) {
  7922. return length1 == length2;
  7923. }
  7924. var v1 = curves1[0].getValues(),
  7925. values2 = [],
  7926. pos1 = 0, pos2,
  7927. end1 = 0, end2;
  7928. for (var i = 0; i < length2; i++) {
  7929. var v2 = curves2[i].getValues();
  7930. values2.push(v2);
  7931. var overlaps = Curve.getOverlaps(v1, v2);
  7932. if (overlaps) {
  7933. pos2 = !i && overlaps[0][0] > 0 ? length2 - 1 : i;
  7934. end2 = overlaps[0][1];
  7935. break;
  7936. }
  7937. }
  7938. var abs = Math.abs,
  7939. epsilon = 1e-8,
  7940. v2 = values2[pos2],
  7941. start2;
  7942. while (v1 && v2) {
  7943. var overlaps = Curve.getOverlaps(v1, v2);
  7944. if (overlaps) {
  7945. var t1 = overlaps[0][0];
  7946. if (abs(t1 - end1) < epsilon) {
  7947. end1 = overlaps[1][0];
  7948. if (end1 === 1) {
  7949. v1 = ++pos1 < length1 ? curves1[pos1].getValues() : null;
  7950. end1 = 0;
  7951. }
  7952. var t2 = overlaps[0][1];
  7953. if (abs(t2 - end2) < epsilon) {
  7954. if (!start2)
  7955. start2 = [pos2, t2];
  7956. end2 = overlaps[1][1];
  7957. if (end2 === 1) {
  7958. if (++pos2 >= length2)
  7959. pos2 = 0;
  7960. v2 = values2[pos2] || curves2[pos2].getValues();
  7961. end2 = 0;
  7962. }
  7963. if (!v1) {
  7964. return start2[0] === pos2 && start2[1] === end2;
  7965. }
  7966. continue;
  7967. }
  7968. }
  7969. }
  7970. break;
  7971. }
  7972. return false;
  7973. },
  7974. _hitTestSelf: function(point, options, viewMatrix, strokeMatrix) {
  7975. var that = this,
  7976. style = this.getStyle(),
  7977. segments = this._segments,
  7978. numSegments = segments.length,
  7979. closed = this._closed,
  7980. tolerancePadding = options._tolerancePadding,
  7981. strokePadding = tolerancePadding,
  7982. join, cap, miterLimit,
  7983. area, loc, res,
  7984. hitStroke = options.stroke && style.hasStroke(),
  7985. hitFill = options.fill && style.hasFill(),
  7986. hitCurves = options.curves,
  7987. strokeRadius = hitStroke
  7988. ? style.getStrokeWidth() / 2
  7989. : hitFill && options.tolerance > 0 || hitCurves
  7990. ? 0 : null;
  7991. if (strokeRadius !== null) {
  7992. if (strokeRadius > 0) {
  7993. join = style.getStrokeJoin();
  7994. cap = style.getStrokeCap();
  7995. miterLimit = style.getMiterLimit();
  7996. strokePadding = strokePadding.add(
  7997. Path._getStrokePadding(strokeRadius, strokeMatrix));
  7998. } else {
  7999. join = cap = 'round';
  8000. }
  8001. }
  8002. function isCloseEnough(pt, padding) {
  8003. return point.subtract(pt).divide(padding).length <= 1;
  8004. }
  8005. function checkSegmentPoint(seg, pt, name) {
  8006. if (!options.selected || pt.isSelected()) {
  8007. var anchor = seg._point;
  8008. if (pt !== anchor)
  8009. pt = pt.add(anchor);
  8010. if (isCloseEnough(pt, strokePadding)) {
  8011. return new HitResult(name, that, {
  8012. segment: seg,
  8013. point: pt
  8014. });
  8015. }
  8016. }
  8017. }
  8018. function checkSegmentPoints(seg, ends) {
  8019. return (ends || options.segments)
  8020. && checkSegmentPoint(seg, seg._point, 'segment')
  8021. || (!ends && options.handles) && (
  8022. checkSegmentPoint(seg, seg._handleIn, 'handle-in') ||
  8023. checkSegmentPoint(seg, seg._handleOut, 'handle-out'));
  8024. }
  8025. function addToArea(point) {
  8026. area.add(point);
  8027. }
  8028. function checkSegmentStroke(segment) {
  8029. var isJoin = closed || segment._index > 0
  8030. && segment._index < numSegments - 1;
  8031. if ((isJoin ? join : cap) === 'round') {
  8032. return isCloseEnough(segment._point, strokePadding);
  8033. } else {
  8034. area = new Path({ internal: true, closed: true });
  8035. if (isJoin) {
  8036. if (!segment.isSmooth()) {
  8037. Path._addBevelJoin(segment, join, strokeRadius,
  8038. miterLimit, null, strokeMatrix, addToArea, true);
  8039. }
  8040. } else if (cap === 'square') {
  8041. Path._addSquareCap(segment, cap, strokeRadius, null,
  8042. strokeMatrix, addToArea, true);
  8043. }
  8044. if (!area.isEmpty()) {
  8045. var loc;
  8046. return area.contains(point)
  8047. || (loc = area.getNearestLocation(point))
  8048. && isCloseEnough(loc.getPoint(), tolerancePadding);
  8049. }
  8050. }
  8051. }
  8052. if (options.ends && !options.segments && !closed) {
  8053. if (res = checkSegmentPoints(segments[0], true)
  8054. || checkSegmentPoints(segments[numSegments - 1], true))
  8055. return res;
  8056. } else if (options.segments || options.handles) {
  8057. for (var i = 0; i < numSegments; i++)
  8058. if (res = checkSegmentPoints(segments[i]))
  8059. return res;
  8060. }
  8061. if (strokeRadius !== null) {
  8062. loc = this.getNearestLocation(point);
  8063. if (loc) {
  8064. var time = loc.getTime();
  8065. if (time === 0 || time === 1 && numSegments > 1) {
  8066. if (!checkSegmentStroke(loc.getSegment()))
  8067. loc = null;
  8068. } else if (!isCloseEnough(loc.getPoint(), strokePadding)) {
  8069. loc = null;
  8070. }
  8071. }
  8072. if (!loc && join === 'miter' && numSegments > 1) {
  8073. for (var i = 0; i < numSegments; i++) {
  8074. var segment = segments[i];
  8075. if (point.getDistance(segment._point)
  8076. <= miterLimit * strokeRadius
  8077. && checkSegmentStroke(segment)) {
  8078. loc = segment.getLocation();
  8079. break;
  8080. }
  8081. }
  8082. }
  8083. }
  8084. return !loc && hitFill && this._contains(point)
  8085. || loc && !hitStroke && !hitCurves
  8086. ? new HitResult('fill', this)
  8087. : loc
  8088. ? new HitResult(hitStroke ? 'stroke' : 'curve', this, {
  8089. location: loc,
  8090. point: loc.getPoint()
  8091. })
  8092. : null;
  8093. }
  8094. }, Base.each(Curve._evaluateMethods,
  8095. function(name) {
  8096. this[name + 'At'] = function(offset) {
  8097. var loc = this.getLocationAt(offset);
  8098. return loc && loc[name]();
  8099. };
  8100. },
  8101. {
  8102. beans: false,
  8103. getLocationOf: function() {
  8104. var point = Point.read(arguments),
  8105. curves = this.getCurves();
  8106. for (var i = 0, l = curves.length; i < l; i++) {
  8107. var loc = curves[i].getLocationOf(point);
  8108. if (loc)
  8109. return loc;
  8110. }
  8111. return null;
  8112. },
  8113. getOffsetOf: function() {
  8114. var loc = this.getLocationOf.apply(this, arguments);
  8115. return loc ? loc.getOffset() : null;
  8116. },
  8117. getLocationAt: function(offset) {
  8118. if (typeof offset === 'number') {
  8119. var curves = this.getCurves(),
  8120. length = 0;
  8121. for (var i = 0, l = curves.length; i < l; i++) {
  8122. var start = length,
  8123. curve = curves[i];
  8124. length += curve.getLength();
  8125. if (length > offset) {
  8126. return curve.getLocationAt(offset - start);
  8127. }
  8128. }
  8129. if (curves.length > 0 && offset <= this.getLength()) {
  8130. return new CurveLocation(curves[curves.length - 1], 1);
  8131. }
  8132. } else if (offset && offset.getPath && offset.getPath() === this) {
  8133. return offset;
  8134. }
  8135. return null;
  8136. },
  8137. getOffsetsWithTangent: function() {
  8138. var tangent = Point.read(arguments);
  8139. if (tangent.isZero()) {
  8140. return [];
  8141. }
  8142. var offsets = [];
  8143. var curveStart = 0;
  8144. var curves = this.getCurves();
  8145. for (var i = 0, l = curves.length; i < l; i++) {
  8146. var curve = curves[i];
  8147. var curveTimes = curve.getTimesWithTangent(tangent);
  8148. for (var j = 0, m = curveTimes.length; j < m; j++) {
  8149. var offset = curveStart + curve.getOffsetAtTime(curveTimes[j]);
  8150. if (offsets.indexOf(offset) < 0) {
  8151. offsets.push(offset);
  8152. }
  8153. }
  8154. curveStart += curve.length;
  8155. }
  8156. return offsets;
  8157. }
  8158. }),
  8159. new function() {
  8160. function drawHandles(ctx, segments, matrix, size) {
  8161. var half = size / 2,
  8162. coords = new Array(6),
  8163. pX, pY;
  8164. function drawHandle(index) {
  8165. var hX = coords[index],
  8166. hY = coords[index + 1];
  8167. if (pX != hX || pY != hY) {
  8168. ctx.beginPath();
  8169. ctx.moveTo(pX, pY);
  8170. ctx.lineTo(hX, hY);
  8171. ctx.stroke();
  8172. ctx.beginPath();
  8173. ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
  8174. ctx.fill();
  8175. }
  8176. }
  8177. for (var i = 0, l = segments.length; i < l; i++) {
  8178. var segment = segments[i],
  8179. selection = segment._selection;
  8180. segment._transformCoordinates(matrix, coords);
  8181. pX = coords[0];
  8182. pY = coords[1];
  8183. if (selection & 2)
  8184. drawHandle(2);
  8185. if (selection & 4)
  8186. drawHandle(4);
  8187. ctx.fillRect(pX - half, pY - half, size, size);
  8188. if (!(selection & 1)) {
  8189. var fillStyle = ctx.fillStyle;
  8190. ctx.fillStyle = '#ffffff';
  8191. ctx.fillRect(pX - half + 1, pY - half + 1, size - 2, size - 2);
  8192. ctx.fillStyle = fillStyle;
  8193. }
  8194. }
  8195. }
  8196. function drawSegments(ctx, path, matrix) {
  8197. var segments = path._segments,
  8198. length = segments.length,
  8199. coords = new Array(6),
  8200. first = true,
  8201. curX, curY,
  8202. prevX, prevY,
  8203. inX, inY,
  8204. outX, outY;
  8205. function drawSegment(segment) {
  8206. if (matrix) {
  8207. segment._transformCoordinates(matrix, coords);
  8208. curX = coords[0];
  8209. curY = coords[1];
  8210. } else {
  8211. var point = segment._point;
  8212. curX = point._x;
  8213. curY = point._y;
  8214. }
  8215. if (first) {
  8216. ctx.moveTo(curX, curY);
  8217. first = false;
  8218. } else {
  8219. if (matrix) {
  8220. inX = coords[2];
  8221. inY = coords[3];
  8222. } else {
  8223. var handle = segment._handleIn;
  8224. inX = curX + handle._x;
  8225. inY = curY + handle._y;
  8226. }
  8227. if (inX === curX && inY === curY
  8228. && outX === prevX && outY === prevY) {
  8229. ctx.lineTo(curX, curY);
  8230. } else {
  8231. ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
  8232. }
  8233. }
  8234. prevX = curX;
  8235. prevY = curY;
  8236. if (matrix) {
  8237. outX = coords[4];
  8238. outY = coords[5];
  8239. } else {
  8240. var handle = segment._handleOut;
  8241. outX = prevX + handle._x;
  8242. outY = prevY + handle._y;
  8243. }
  8244. }
  8245. for (var i = 0; i < length; i++)
  8246. drawSegment(segments[i]);
  8247. if (path._closed && length > 0)
  8248. drawSegment(segments[0]);
  8249. }
  8250. return {
  8251. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8252. var dontStart = param.dontStart,
  8253. dontPaint = param.dontFinish || param.clip,
  8254. style = this.getStyle(),
  8255. hasFill = style.hasFill(),
  8256. hasStroke = style.hasStroke(),
  8257. dashArray = style.getDashArray(),
  8258. dashLength = !paper.support.nativeDash && hasStroke
  8259. && dashArray && dashArray.length;
  8260. if (!dontStart)
  8261. ctx.beginPath();
  8262. if (hasFill || hasStroke && !dashLength || dontPaint) {
  8263. drawSegments(ctx, this, strokeMatrix);
  8264. if (this._closed)
  8265. ctx.closePath();
  8266. }
  8267. function getOffset(i) {
  8268. return dashArray[((i % dashLength) + dashLength) % dashLength];
  8269. }
  8270. if (!dontPaint && (hasFill || hasStroke)) {
  8271. this._setStyles(ctx, param, viewMatrix);
  8272. if (hasFill) {
  8273. ctx.fill(style.getFillRule());
  8274. ctx.shadowColor = 'rgba(0,0,0,0)';
  8275. }
  8276. if (hasStroke) {
  8277. if (dashLength) {
  8278. if (!dontStart)
  8279. ctx.beginPath();
  8280. var flattener = new PathFlattener(this, 0.25, 32, false,
  8281. strokeMatrix),
  8282. length = flattener.length,
  8283. from = -style.getDashOffset(), to,
  8284. i = 0;
  8285. from = from % length;
  8286. while (from > 0) {
  8287. from -= getOffset(i--) + getOffset(i--);
  8288. }
  8289. while (from < length) {
  8290. to = from + getOffset(i++);
  8291. if (from > 0 || to > 0)
  8292. flattener.drawPart(ctx,
  8293. Math.max(from, 0), Math.max(to, 0));
  8294. from = to + getOffset(i++);
  8295. }
  8296. }
  8297. ctx.stroke();
  8298. }
  8299. }
  8300. },
  8301. _drawSelected: function(ctx, matrix) {
  8302. ctx.beginPath();
  8303. drawSegments(ctx, this, matrix);
  8304. ctx.stroke();
  8305. drawHandles(ctx, this._segments, matrix, paper.settings.handleSize);
  8306. }
  8307. };
  8308. },
  8309. new function() {
  8310. function getCurrentSegment(that) {
  8311. var segments = that._segments;
  8312. if (!segments.length)
  8313. throw new Error('Use a moveTo() command first');
  8314. return segments[segments.length - 1];
  8315. }
  8316. return {
  8317. moveTo: function() {
  8318. var segments = this._segments;
  8319. if (segments.length === 1)
  8320. this.removeSegment(0);
  8321. if (!segments.length)
  8322. this._add([ new Segment(Point.read(arguments)) ]);
  8323. },
  8324. moveBy: function() {
  8325. throw new Error('moveBy() is unsupported on Path items.');
  8326. },
  8327. lineTo: function() {
  8328. this._add([ new Segment(Point.read(arguments)) ]);
  8329. },
  8330. cubicCurveTo: function() {
  8331. var handle1 = Point.read(arguments),
  8332. handle2 = Point.read(arguments),
  8333. to = Point.read(arguments),
  8334. current = getCurrentSegment(this);
  8335. current.setHandleOut(handle1.subtract(current._point));
  8336. this._add([ new Segment(to, handle2.subtract(to)) ]);
  8337. },
  8338. quadraticCurveTo: function() {
  8339. var handle = Point.read(arguments),
  8340. to = Point.read(arguments),
  8341. current = getCurrentSegment(this)._point;
  8342. this.cubicCurveTo(
  8343. handle.add(current.subtract(handle).multiply(1 / 3)),
  8344. handle.add(to.subtract(handle).multiply(1 / 3)),
  8345. to
  8346. );
  8347. },
  8348. curveTo: function() {
  8349. var through = Point.read(arguments),
  8350. to = Point.read(arguments),
  8351. t = Base.pick(Base.read(arguments), 0.5),
  8352. t1 = 1 - t,
  8353. current = getCurrentSegment(this)._point,
  8354. handle = through.subtract(current.multiply(t1 * t1))
  8355. .subtract(to.multiply(t * t)).divide(2 * t * t1);
  8356. if (handle.isNaN())
  8357. throw new Error(
  8358. 'Cannot put a curve through points with parameter = ' + t);
  8359. this.quadraticCurveTo(handle, to);
  8360. },
  8361. arcTo: function() {
  8362. var abs = Math.abs,
  8363. sqrt = Math.sqrt,
  8364. current = getCurrentSegment(this),
  8365. from = current._point,
  8366. to = Point.read(arguments),
  8367. through,
  8368. peek = Base.peek(arguments),
  8369. clockwise = Base.pick(peek, true),
  8370. center, extent, vector, matrix;
  8371. if (typeof clockwise === 'boolean') {
  8372. var middle = from.add(to).divide(2),
  8373. through = middle.add(middle.subtract(from).rotate(
  8374. clockwise ? -90 : 90));
  8375. } else if (Base.remain(arguments) <= 2) {
  8376. through = to;
  8377. to = Point.read(arguments);
  8378. } else {
  8379. var radius = Size.read(arguments),
  8380. isZero = Numerical.isZero;
  8381. if (isZero(radius.width) || isZero(radius.height))
  8382. return this.lineTo(to);
  8383. var rotation = Base.read(arguments),
  8384. clockwise = !!Base.read(arguments),
  8385. large = !!Base.read(arguments),
  8386. middle = from.add(to).divide(2),
  8387. pt = from.subtract(middle).rotate(-rotation),
  8388. x = pt.x,
  8389. y = pt.y,
  8390. rx = abs(radius.width),
  8391. ry = abs(radius.height),
  8392. rxSq = rx * rx,
  8393. rySq = ry * ry,
  8394. xSq = x * x,
  8395. ySq = y * y;
  8396. var factor = sqrt(xSq / rxSq + ySq / rySq);
  8397. if (factor > 1) {
  8398. rx *= factor;
  8399. ry *= factor;
  8400. rxSq = rx * rx;
  8401. rySq = ry * ry;
  8402. }
  8403. factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) /
  8404. (rxSq * ySq + rySq * xSq);
  8405. if (abs(factor) < 1e-12)
  8406. factor = 0;
  8407. if (factor < 0)
  8408. throw new Error(
  8409. 'Cannot create an arc with the given arguments');
  8410. center = new Point(rx * y / ry, -ry * x / rx)
  8411. .multiply((large === clockwise ? -1 : 1) * sqrt(factor))
  8412. .rotate(rotation).add(middle);
  8413. matrix = new Matrix().translate(center).rotate(rotation)
  8414. .scale(rx, ry);
  8415. vector = matrix._inverseTransform(from);
  8416. extent = vector.getDirectedAngle(matrix._inverseTransform(to));
  8417. if (!clockwise && extent > 0)
  8418. extent -= 360;
  8419. else if (clockwise && extent < 0)
  8420. extent += 360;
  8421. }
  8422. if (through) {
  8423. var l1 = new Line(from.add(through).divide(2),
  8424. through.subtract(from).rotate(90), true),
  8425. l2 = new Line(through.add(to).divide(2),
  8426. to.subtract(through).rotate(90), true),
  8427. line = new Line(from, to),
  8428. throughSide = line.getSide(through);
  8429. center = l1.intersect(l2, true);
  8430. if (!center) {
  8431. if (!throughSide)
  8432. return this.lineTo(to);
  8433. throw new Error(
  8434. 'Cannot create an arc with the given arguments');
  8435. }
  8436. vector = from.subtract(center);
  8437. extent = vector.getDirectedAngle(to.subtract(center));
  8438. var centerSide = line.getSide(center, true);
  8439. if (centerSide === 0) {
  8440. extent = throughSide * abs(extent);
  8441. } else if (throughSide === centerSide) {
  8442. extent += extent < 0 ? 360 : -360;
  8443. }
  8444. }
  8445. var epsilon = 1e-7,
  8446. ext = abs(extent),
  8447. count = ext >= 360 ? 4 : Math.ceil((ext - epsilon) / 90),
  8448. inc = extent / count,
  8449. half = inc * Math.PI / 360,
  8450. z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
  8451. segments = [];
  8452. for (var i = 0; i <= count; i++) {
  8453. var pt = to,
  8454. out = null;
  8455. if (i < count) {
  8456. out = vector.rotate(90).multiply(z);
  8457. if (matrix) {
  8458. pt = matrix._transformPoint(vector);
  8459. out = matrix._transformPoint(vector.add(out))
  8460. .subtract(pt);
  8461. } else {
  8462. pt = center.add(vector);
  8463. }
  8464. }
  8465. if (!i) {
  8466. current.setHandleOut(out);
  8467. } else {
  8468. var _in = vector.rotate(-90).multiply(z);
  8469. if (matrix) {
  8470. _in = matrix._transformPoint(vector.add(_in))
  8471. .subtract(pt);
  8472. }
  8473. segments.push(new Segment(pt, _in, out));
  8474. }
  8475. vector = vector.rotate(inc);
  8476. }
  8477. this._add(segments);
  8478. },
  8479. lineBy: function() {
  8480. var to = Point.read(arguments),
  8481. current = getCurrentSegment(this)._point;
  8482. this.lineTo(current.add(to));
  8483. },
  8484. curveBy: function() {
  8485. var through = Point.read(arguments),
  8486. to = Point.read(arguments),
  8487. parameter = Base.read(arguments),
  8488. current = getCurrentSegment(this)._point;
  8489. this.curveTo(current.add(through), current.add(to), parameter);
  8490. },
  8491. cubicCurveBy: function() {
  8492. var handle1 = Point.read(arguments),
  8493. handle2 = Point.read(arguments),
  8494. to = Point.read(arguments),
  8495. current = getCurrentSegment(this)._point;
  8496. this.cubicCurveTo(current.add(handle1), current.add(handle2),
  8497. current.add(to));
  8498. },
  8499. quadraticCurveBy: function() {
  8500. var handle = Point.read(arguments),
  8501. to = Point.read(arguments),
  8502. current = getCurrentSegment(this)._point;
  8503. this.quadraticCurveTo(current.add(handle), current.add(to));
  8504. },
  8505. arcBy: function() {
  8506. var current = getCurrentSegment(this)._point,
  8507. point = current.add(Point.read(arguments)),
  8508. clockwise = Base.pick(Base.peek(arguments), true);
  8509. if (typeof clockwise === 'boolean') {
  8510. this.arcTo(point, clockwise);
  8511. } else {
  8512. this.arcTo(point, current.add(Point.read(arguments)));
  8513. }
  8514. },
  8515. closePath: function(tolerance) {
  8516. this.setClosed(true);
  8517. this.join(this, tolerance);
  8518. }
  8519. };
  8520. }, {
  8521. _getBounds: function(matrix, options) {
  8522. var method = options.handle
  8523. ? 'getHandleBounds'
  8524. : options.stroke
  8525. ? 'getStrokeBounds'
  8526. : 'getBounds';
  8527. return Path[method](this._segments, this._closed, this, matrix, options);
  8528. },
  8529. statics: {
  8530. getBounds: function(segments, closed, path, matrix, options, strokePadding) {
  8531. var first = segments[0];
  8532. if (!first)
  8533. return new Rectangle();
  8534. var coords = new Array(6),
  8535. prevCoords = first._transformCoordinates(matrix, new Array(6)),
  8536. min = prevCoords.slice(0, 2),
  8537. max = min.slice(),
  8538. roots = new Array(2);
  8539. function processSegment(segment) {
  8540. segment._transformCoordinates(matrix, coords);
  8541. for (var i = 0; i < 2; i++) {
  8542. Curve._addBounds(
  8543. prevCoords[i],
  8544. prevCoords[i + 4],
  8545. coords[i + 2],
  8546. coords[i],
  8547. i, strokePadding ? strokePadding[i] : 0, min, max, roots);
  8548. }
  8549. var tmp = prevCoords;
  8550. prevCoords = coords;
  8551. coords = tmp;
  8552. }
  8553. for (var i = 1, l = segments.length; i < l; i++)
  8554. processSegment(segments[i]);
  8555. if (closed)
  8556. processSegment(first);
  8557. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  8558. },
  8559. getStrokeBounds: function(segments, closed, path, matrix, options) {
  8560. var style = path.getStyle(),
  8561. stroke = style.hasStroke(),
  8562. strokeWidth = style.getStrokeWidth(),
  8563. strokeMatrix = stroke && path._getStrokeMatrix(matrix, options),
  8564. strokePadding = stroke && Path._getStrokePadding(strokeWidth,
  8565. strokeMatrix),
  8566. bounds = Path.getBounds(segments, closed, path, matrix, options,
  8567. strokePadding);
  8568. if (!stroke)
  8569. return bounds;
  8570. var strokeRadius = strokeWidth / 2,
  8571. join = style.getStrokeJoin(),
  8572. cap = style.getStrokeCap(),
  8573. miterLimit = style.getMiterLimit(),
  8574. joinBounds = new Rectangle(new Size(strokePadding));
  8575. function addPoint(point) {
  8576. bounds = bounds.include(point);
  8577. }
  8578. function addRound(segment) {
  8579. bounds = bounds.unite(
  8580. joinBounds.setCenter(segment._point.transform(matrix)));
  8581. }
  8582. function addJoin(segment, join) {
  8583. if (join === 'round' || segment.isSmooth()) {
  8584. addRound(segment);
  8585. } else {
  8586. Path._addBevelJoin(segment, join, strokeRadius, miterLimit,
  8587. matrix, strokeMatrix, addPoint);
  8588. }
  8589. }
  8590. function addCap(segment, cap) {
  8591. if (cap === 'round') {
  8592. addRound(segment);
  8593. } else {
  8594. Path._addSquareCap(segment, cap, strokeRadius, matrix,
  8595. strokeMatrix, addPoint);
  8596. }
  8597. }
  8598. var length = segments.length - (closed ? 0 : 1);
  8599. for (var i = 1; i < length; i++)
  8600. addJoin(segments[i], join);
  8601. if (closed) {
  8602. addJoin(segments[0], join);
  8603. } else if (length > 0) {
  8604. addCap(segments[0], cap);
  8605. addCap(segments[segments.length - 1], cap);
  8606. }
  8607. return bounds;
  8608. },
  8609. _getStrokePadding: function(radius, matrix) {
  8610. if (!matrix)
  8611. return [radius, radius];
  8612. var hor = new Point(radius, 0).transform(matrix),
  8613. ver = new Point(0, radius).transform(matrix),
  8614. phi = hor.getAngleInRadians(),
  8615. a = hor.getLength(),
  8616. b = ver.getLength();
  8617. var sin = Math.sin(phi),
  8618. cos = Math.cos(phi),
  8619. tan = Math.tan(phi),
  8620. tx = Math.atan2(b * tan, a),
  8621. ty = Math.atan2(b, tan * a);
  8622. return [Math.abs(a * Math.cos(tx) * cos + b * Math.sin(tx) * sin),
  8623. Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
  8624. },
  8625. _addBevelJoin: function(segment, join, radius, miterLimit, matrix,
  8626. strokeMatrix, addPoint, isArea) {
  8627. var curve2 = segment.getCurve(),
  8628. curve1 = curve2.getPrevious(),
  8629. point = curve2.getPoint1().transform(matrix),
  8630. normal1 = curve1.getNormalAtTime(1).multiply(radius)
  8631. .transform(strokeMatrix),
  8632. normal2 = curve2.getNormalAtTime(0).multiply(radius)
  8633. .transform(strokeMatrix);
  8634. if (normal1.getDirectedAngle(normal2) < 0) {
  8635. normal1 = normal1.negate();
  8636. normal2 = normal2.negate();
  8637. }
  8638. if (isArea)
  8639. addPoint(point);
  8640. addPoint(point.add(normal1));
  8641. if (join === 'miter') {
  8642. var corner = new Line(point.add(normal1),
  8643. new Point(-normal1.y, normal1.x), true
  8644. ).intersect(new Line(point.add(normal2),
  8645. new Point(-normal2.y, normal2.x), true
  8646. ), true);
  8647. if (corner && point.getDistance(corner) <= miterLimit * radius) {
  8648. addPoint(corner);
  8649. }
  8650. }
  8651. addPoint(point.add(normal2));
  8652. },
  8653. _addSquareCap: function(segment, cap, radius, matrix, strokeMatrix,
  8654. addPoint, isArea) {
  8655. var point = segment._point.transform(matrix),
  8656. loc = segment.getLocation(),
  8657. normal = loc.getNormal()
  8658. .multiply(loc.getTime() === 0 ? radius : -radius)
  8659. .transform(strokeMatrix);
  8660. if (cap === 'square') {
  8661. if (isArea) {
  8662. addPoint(point.subtract(normal));
  8663. addPoint(point.add(normal));
  8664. }
  8665. point = point.add(normal.rotate(-90));
  8666. }
  8667. addPoint(point.add(normal));
  8668. addPoint(point.subtract(normal));
  8669. },
  8670. getHandleBounds: function(segments, closed, path, matrix, options) {
  8671. var style = path.getStyle(),
  8672. stroke = options.stroke && style.hasStroke(),
  8673. strokePadding,
  8674. joinPadding;
  8675. if (stroke) {
  8676. var strokeMatrix = path._getStrokeMatrix(matrix, options),
  8677. strokeRadius = style.getStrokeWidth() / 2,
  8678. joinRadius = strokeRadius;
  8679. if (style.getStrokeJoin() === 'miter')
  8680. joinRadius = strokeRadius * style.getMiterLimit();
  8681. if (style.getStrokeCap() === 'square')
  8682. joinRadius = Math.max(joinRadius, strokeRadius * Math.SQRT2);
  8683. strokePadding = Path._getStrokePadding(strokeRadius, strokeMatrix);
  8684. joinPadding = Path._getStrokePadding(joinRadius, strokeMatrix);
  8685. }
  8686. var coords = new Array(6),
  8687. x1 = Infinity,
  8688. x2 = -x1,
  8689. y1 = x1,
  8690. y2 = x2;
  8691. for (var i = 0, l = segments.length; i < l; i++) {
  8692. var segment = segments[i];
  8693. segment._transformCoordinates(matrix, coords);
  8694. for (var j = 0; j < 6; j += 2) {
  8695. var padding = !j ? joinPadding : strokePadding,
  8696. paddingX = padding ? padding[0] : 0,
  8697. paddingY = padding ? padding[1] : 0,
  8698. x = coords[j],
  8699. y = coords[j + 1],
  8700. xn = x - paddingX,
  8701. xx = x + paddingX,
  8702. yn = y - paddingY,
  8703. yx = y + paddingY;
  8704. if (xn < x1) x1 = xn;
  8705. if (xx > x2) x2 = xx;
  8706. if (yn < y1) y1 = yn;
  8707. if (yx > y2) y2 = yx;
  8708. }
  8709. }
  8710. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  8711. }
  8712. }});
  8713. Path.inject({ statics: new function() {
  8714. var kappa = 0.5522847498307936,
  8715. ellipseSegments = [
  8716. new Segment([-1, 0], [0, kappa ], [0, -kappa]),
  8717. new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
  8718. new Segment([1, 0], [0, -kappa], [0, kappa ]),
  8719. new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
  8720. ];
  8721. function createPath(segments, closed, args) {
  8722. var props = Base.getNamed(args),
  8723. path = new Path(props && props.insert == false && Item.NO_INSERT);
  8724. path._add(segments);
  8725. path._closed = closed;
  8726. return path.set(props, { insert: true });
  8727. }
  8728. function createEllipse(center, radius, args) {
  8729. var segments = new Array(4);
  8730. for (var i = 0; i < 4; i++) {
  8731. var segment = ellipseSegments[i];
  8732. segments[i] = new Segment(
  8733. segment._point.multiply(radius).add(center),
  8734. segment._handleIn.multiply(radius),
  8735. segment._handleOut.multiply(radius)
  8736. );
  8737. }
  8738. return createPath(segments, true, args);
  8739. }
  8740. return {
  8741. Line: function() {
  8742. return createPath([
  8743. new Segment(Point.readNamed(arguments, 'from')),
  8744. new Segment(Point.readNamed(arguments, 'to'))
  8745. ], false, arguments);
  8746. },
  8747. Circle: function() {
  8748. var center = Point.readNamed(arguments, 'center'),
  8749. radius = Base.readNamed(arguments, 'radius');
  8750. return createEllipse(center, new Size(radius), arguments);
  8751. },
  8752. Rectangle: function() {
  8753. var rect = Rectangle.readNamed(arguments, 'rectangle'),
  8754. radius = Size.readNamed(arguments, 'radius', 0,
  8755. { readNull: true }),
  8756. bl = rect.getBottomLeft(true),
  8757. tl = rect.getTopLeft(true),
  8758. tr = rect.getTopRight(true),
  8759. br = rect.getBottomRight(true),
  8760. segments;
  8761. if (!radius || radius.isZero()) {
  8762. segments = [
  8763. new Segment(bl),
  8764. new Segment(tl),
  8765. new Segment(tr),
  8766. new Segment(br)
  8767. ];
  8768. } else {
  8769. radius = Size.min(radius, rect.getSize(true).divide(2));
  8770. var rx = radius.width,
  8771. ry = radius.height,
  8772. hx = rx * kappa,
  8773. hy = ry * kappa;
  8774. segments = [
  8775. new Segment(bl.add(rx, 0), null, [-hx, 0]),
  8776. new Segment(bl.subtract(0, ry), [0, hy]),
  8777. new Segment(tl.add(0, ry), null, [0, -hy]),
  8778. new Segment(tl.add(rx, 0), [-hx, 0], null),
  8779. new Segment(tr.subtract(rx, 0), null, [hx, 0]),
  8780. new Segment(tr.add(0, ry), [0, -hy], null),
  8781. new Segment(br.subtract(0, ry), null, [0, hy]),
  8782. new Segment(br.subtract(rx, 0), [hx, 0])
  8783. ];
  8784. }
  8785. return createPath(segments, true, arguments);
  8786. },
  8787. RoundRectangle: '#Rectangle',
  8788. Ellipse: function() {
  8789. var ellipse = Shape._readEllipse(arguments);
  8790. return createEllipse(ellipse.center, ellipse.radius, arguments);
  8791. },
  8792. Oval: '#Ellipse',
  8793. Arc: function() {
  8794. var from = Point.readNamed(arguments, 'from'),
  8795. through = Point.readNamed(arguments, 'through'),
  8796. to = Point.readNamed(arguments, 'to'),
  8797. props = Base.getNamed(arguments),
  8798. path = new Path(props && props.insert == false
  8799. && Item.NO_INSERT);
  8800. path.moveTo(from);
  8801. path.arcTo(through, to);
  8802. return path.set(props);
  8803. },
  8804. RegularPolygon: function() {
  8805. var center = Point.readNamed(arguments, 'center'),
  8806. sides = Base.readNamed(arguments, 'sides'),
  8807. radius = Base.readNamed(arguments, 'radius'),
  8808. step = 360 / sides,
  8809. three = sides % 3 === 0,
  8810. vector = new Point(0, three ? -radius : radius),
  8811. offset = three ? -1 : 0.5,
  8812. segments = new Array(sides);
  8813. for (var i = 0; i < sides; i++)
  8814. segments[i] = new Segment(center.add(
  8815. vector.rotate((i + offset) * step)));
  8816. return createPath(segments, true, arguments);
  8817. },
  8818. Star: function() {
  8819. var center = Point.readNamed(arguments, 'center'),
  8820. points = Base.readNamed(arguments, 'points') * 2,
  8821. radius1 = Base.readNamed(arguments, 'radius1'),
  8822. radius2 = Base.readNamed(arguments, 'radius2'),
  8823. step = 360 / points,
  8824. vector = new Point(0, -1),
  8825. segments = new Array(points);
  8826. for (var i = 0; i < points; i++)
  8827. segments[i] = new Segment(center.add(vector.rotate(step * i)
  8828. .multiply(i % 2 ? radius2 : radius1)));
  8829. return createPath(segments, true, arguments);
  8830. }
  8831. };
  8832. }});
  8833. var CompoundPath = PathItem.extend({
  8834. _class: 'CompoundPath',
  8835. _serializeFields: {
  8836. children: []
  8837. },
  8838. beans: true,
  8839. initialize: function CompoundPath(arg) {
  8840. this._children = [];
  8841. this._namedChildren = {};
  8842. if (!this._initialize(arg)) {
  8843. if (typeof arg === 'string') {
  8844. this.setPathData(arg);
  8845. } else {
  8846. this.addChildren(Array.isArray(arg) ? arg : arguments);
  8847. }
  8848. }
  8849. },
  8850. insertChildren: function insertChildren(index, items) {
  8851. var list = items,
  8852. first = list[0];
  8853. if (first && typeof first[0] === 'number')
  8854. list = [list];
  8855. for (var i = items.length - 1; i >= 0; i--) {
  8856. var item = list[i];
  8857. if (list === items && !(item instanceof Path))
  8858. list = Base.slice(list);
  8859. if (Array.isArray(item)) {
  8860. list[i] = new Path({ segments: item, insert: false });
  8861. } else if (item instanceof CompoundPath) {
  8862. list.splice.apply(list, [i, 1].concat(item.removeChildren()));
  8863. item.remove();
  8864. }
  8865. }
  8866. return insertChildren.base.call(this, index, list);
  8867. },
  8868. reduce: function reduce(options) {
  8869. var children = this._children;
  8870. for (var i = children.length - 1; i >= 0; i--) {
  8871. var path = children[i].reduce(options);
  8872. if (path.isEmpty())
  8873. path.remove();
  8874. }
  8875. if (!children.length) {
  8876. var path = new Path(Item.NO_INSERT);
  8877. path.copyAttributes(this);
  8878. path.insertAbove(this);
  8879. this.remove();
  8880. return path;
  8881. }
  8882. return reduce.base.call(this);
  8883. },
  8884. isClosed: function() {
  8885. var children = this._children;
  8886. for (var i = 0, l = children.length; i < l; i++) {
  8887. if (!children[i]._closed)
  8888. return false;
  8889. }
  8890. return true;
  8891. },
  8892. setClosed: function(closed) {
  8893. var children = this._children;
  8894. for (var i = 0, l = children.length; i < l; i++) {
  8895. children[i].setClosed(closed);
  8896. }
  8897. },
  8898. getFirstSegment: function() {
  8899. var first = this.getFirstChild();
  8900. return first && first.getFirstSegment();
  8901. },
  8902. getLastSegment: function() {
  8903. var last = this.getLastChild();
  8904. return last && last.getLastSegment();
  8905. },
  8906. getCurves: function() {
  8907. var children = this._children,
  8908. curves = [];
  8909. for (var i = 0, l = children.length; i < l; i++) {
  8910. Base.push(curves, children[i].getCurves());
  8911. }
  8912. return curves;
  8913. },
  8914. getFirstCurve: function() {
  8915. var first = this.getFirstChild();
  8916. return first && first.getFirstCurve();
  8917. },
  8918. getLastCurve: function() {
  8919. var last = this.getLastChild();
  8920. return last && last.getLastCurve();
  8921. },
  8922. getArea: function() {
  8923. var children = this._children,
  8924. area = 0;
  8925. for (var i = 0, l = children.length; i < l; i++)
  8926. area += children[i].getArea();
  8927. return area;
  8928. },
  8929. getLength: function() {
  8930. var children = this._children,
  8931. length = 0;
  8932. for (var i = 0, l = children.length; i < l; i++)
  8933. length += children[i].getLength();
  8934. return length;
  8935. },
  8936. getPathData: function(_matrix, _precision) {
  8937. var children = this._children,
  8938. paths = [];
  8939. for (var i = 0, l = children.length; i < l; i++) {
  8940. var child = children[i],
  8941. mx = child._matrix;
  8942. paths.push(child.getPathData(_matrix && !mx.isIdentity()
  8943. ? _matrix.appended(mx) : _matrix, _precision));
  8944. }
  8945. return paths.join('');
  8946. },
  8947. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  8948. return _hitTestChildren.base.call(this, point,
  8949. options.class === Path || options.type === 'path' ? options
  8950. : Base.set({}, options, { fill: false }),
  8951. viewMatrix);
  8952. },
  8953. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8954. var children = this._children;
  8955. if (!children.length)
  8956. return;
  8957. param = param.extend({ dontStart: true, dontFinish: true });
  8958. ctx.beginPath();
  8959. for (var i = 0, l = children.length; i < l; i++)
  8960. children[i].draw(ctx, param, strokeMatrix);
  8961. if (!param.clip) {
  8962. this._setStyles(ctx, param, viewMatrix);
  8963. var style = this._style;
  8964. if (style.hasFill()) {
  8965. ctx.fill(style.getFillRule());
  8966. ctx.shadowColor = 'rgba(0,0,0,0)';
  8967. }
  8968. if (style.hasStroke())
  8969. ctx.stroke();
  8970. }
  8971. },
  8972. _drawSelected: function(ctx, matrix, selectionItems) {
  8973. var children = this._children;
  8974. for (var i = 0, l = children.length; i < l; i++) {
  8975. var child = children[i],
  8976. mx = child._matrix;
  8977. if (!selectionItems[child._id]) {
  8978. child._drawSelected(ctx, mx.isIdentity() ? matrix
  8979. : matrix.appended(mx));
  8980. }
  8981. }
  8982. }
  8983. },
  8984. new function() {
  8985. function getCurrentPath(that, check) {
  8986. var children = that._children;
  8987. if (check && !children.length)
  8988. throw new Error('Use a moveTo() command first');
  8989. return children[children.length - 1];
  8990. }
  8991. return Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
  8992. 'arcTo', 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy',
  8993. 'arcBy'],
  8994. function(key) {
  8995. this[key] = function() {
  8996. var path = getCurrentPath(this, true);
  8997. path[key].apply(path, arguments);
  8998. };
  8999. }, {
  9000. moveTo: function() {
  9001. var current = getCurrentPath(this),
  9002. path = current && current.isEmpty() ? current
  9003. : new Path(Item.NO_INSERT);
  9004. if (path !== current)
  9005. this.addChild(path);
  9006. path.moveTo.apply(path, arguments);
  9007. },
  9008. moveBy: function() {
  9009. var current = getCurrentPath(this, true),
  9010. last = current && current.getLastSegment(),
  9011. point = Point.read(arguments);
  9012. this.moveTo(last ? point.add(last._point) : point);
  9013. },
  9014. closePath: function(tolerance) {
  9015. getCurrentPath(this, true).closePath(tolerance);
  9016. }
  9017. }
  9018. );
  9019. }, Base.each(['reverse', 'flatten', 'simplify', 'smooth'], function(key) {
  9020. this[key] = function(param) {
  9021. var children = this._children,
  9022. res;
  9023. for (var i = 0, l = children.length; i < l; i++) {
  9024. res = children[i][key](param) || res;
  9025. }
  9026. return res;
  9027. };
  9028. }, {}));
  9029. PathItem.inject(new function() {
  9030. var min = Math.min,
  9031. max = Math.max,
  9032. abs = Math.abs,
  9033. operators = {
  9034. unite: { '1': true, '2': true },
  9035. intersect: { '2': true },
  9036. subtract: { '1': true },
  9037. exclude: { '1': true, '-1': true }
  9038. };
  9039. function preparePath(path, resolve) {
  9040. var res = path.clone(false).reduce({ simplify: true })
  9041. .transform(null, true, true);
  9042. return resolve
  9043. ? res.resolveCrossings().reorient(
  9044. res.getFillRule() === 'nonzero', true)
  9045. : res;
  9046. }
  9047. function createResult(paths, simplify, path1, path2, options) {
  9048. var result = new CompoundPath(Item.NO_INSERT);
  9049. result.addChildren(paths, true);
  9050. result = result.reduce({ simplify: simplify });
  9051. if (!(options && options.insert == false)) {
  9052. result.insertAbove(path2 && path1.isSibling(path2)
  9053. && path1.getIndex() < path2.getIndex() ? path2 : path1);
  9054. }
  9055. result.copyAttributes(path1, true);
  9056. return result;
  9057. }
  9058. function traceBoolean(path1, path2, operation, options) {
  9059. if (options && (options.trace == false || options.stroke) &&
  9060. /^(subtract|intersect)$/.test(operation))
  9061. return splitBoolean(path1, path2, operation);
  9062. var _path1 = preparePath(path1, true),
  9063. _path2 = path2 && path1 !== path2 && preparePath(path2, true),
  9064. operator = operators[operation];
  9065. operator[operation] = true;
  9066. if (_path2 && (operator.subtract || operator.exclude)
  9067. ^ (_path2.isClockwise() ^ _path1.isClockwise()))
  9068. _path2.reverse();
  9069. var crossings = divideLocations(
  9070. CurveLocation.expand(_path1.getCrossings(_path2))),
  9071. paths1 = _path1._children || [_path1],
  9072. paths2 = _path2 && (_path2._children || [_path2]),
  9073. segments = [],
  9074. curves = [],
  9075. paths;
  9076. function collect(paths) {
  9077. for (var i = 0, l = paths.length; i < l; i++) {
  9078. var path = paths[i];
  9079. Base.push(segments, path._segments);
  9080. Base.push(curves, path.getCurves());
  9081. path._overlapsOnly = true;
  9082. }
  9083. }
  9084. if (crossings.length) {
  9085. collect(paths1);
  9086. if (paths2)
  9087. collect(paths2);
  9088. for (var i = 0, l = crossings.length; i < l; i++) {
  9089. propagateWinding(crossings[i]._segment, _path1, _path2, curves,
  9090. operator);
  9091. }
  9092. for (var i = 0, l = segments.length; i < l; i++) {
  9093. var segment = segments[i],
  9094. inter = segment._intersection;
  9095. if (!segment._winding) {
  9096. propagateWinding(segment, _path1, _path2, curves, operator);
  9097. }
  9098. if (!(inter && inter._overlap))
  9099. segment._path._overlapsOnly = false;
  9100. }
  9101. paths = tracePaths(segments, operator);
  9102. } else {
  9103. paths = reorientPaths(
  9104. paths2 ? paths1.concat(paths2) : paths1.slice(),
  9105. function(w) {
  9106. return !!operator[w];
  9107. });
  9108. }
  9109. return createResult(paths, true, path1, path2, options);
  9110. }
  9111. function splitBoolean(path1, path2, operation) {
  9112. var _path1 = preparePath(path1),
  9113. _path2 = preparePath(path2),
  9114. crossings = _path1.getCrossings(_path2),
  9115. subtract = operation === 'subtract',
  9116. divide = operation === 'divide',
  9117. added = {},
  9118. paths = [];
  9119. function addPath(path) {
  9120. if (!added[path._id] && (divide ||
  9121. _path2.contains(path.getPointAt(path.getLength() / 2))
  9122. ^ subtract)) {
  9123. paths.unshift(path);
  9124. return added[path._id] = true;
  9125. }
  9126. }
  9127. for (var i = crossings.length - 1; i >= 0; i--) {
  9128. var path = crossings[i].split();
  9129. if (path) {
  9130. if (addPath(path))
  9131. path.getFirstSegment().setHandleIn(0, 0);
  9132. _path1.getLastSegment().setHandleOut(0, 0);
  9133. }
  9134. }
  9135. addPath(_path1);
  9136. return createResult(paths, false, path1, path2);
  9137. }
  9138. function linkIntersections(from, to) {
  9139. var prev = from;
  9140. while (prev) {
  9141. if (prev === to)
  9142. return;
  9143. prev = prev._previous;
  9144. }
  9145. while (from._next && from._next !== to)
  9146. from = from._next;
  9147. if (!from._next) {
  9148. while (to._previous)
  9149. to = to._previous;
  9150. from._next = to;
  9151. to._previous = from;
  9152. }
  9153. }
  9154. function clearCurveHandles(curves) {
  9155. for (var i = curves.length - 1; i >= 0; i--)
  9156. curves[i].clearHandles();
  9157. }
  9158. function reorientPaths(paths, isInside, clockwise) {
  9159. var length = paths && paths.length;
  9160. if (length) {
  9161. var lookup = Base.each(paths, function (path, i) {
  9162. this[path._id] = {
  9163. container: null,
  9164. winding: path.isClockwise() ? 1 : -1,
  9165. index: i
  9166. };
  9167. }, {}),
  9168. sorted = paths.slice().sort(function (a, b) {
  9169. return abs(b.getArea()) - abs(a.getArea());
  9170. }),
  9171. first = sorted[0];
  9172. if (clockwise == null)
  9173. clockwise = first.isClockwise();
  9174. for (var i = 0; i < length; i++) {
  9175. var path1 = sorted[i],
  9176. entry1 = lookup[path1._id],
  9177. point = path1.getInteriorPoint(),
  9178. containerWinding = 0;
  9179. for (var j = i - 1; j >= 0; j--) {
  9180. var path2 = sorted[j];
  9181. if (path2.contains(point)) {
  9182. var entry2 = lookup[path2._id];
  9183. containerWinding = entry2.winding;
  9184. entry1.winding += containerWinding;
  9185. entry1.container = entry2.exclude ? entry2.container
  9186. : path2;
  9187. break;
  9188. }
  9189. }
  9190. if (isInside(entry1.winding) === isInside(containerWinding)) {
  9191. entry1.exclude = true;
  9192. paths[entry1.index] = null;
  9193. } else {
  9194. var container = entry1.container;
  9195. path1.setClockwise(container ? !container.isClockwise()
  9196. : clockwise);
  9197. }
  9198. }
  9199. }
  9200. return paths;
  9201. }
  9202. function divideLocations(locations, include, clearLater) {
  9203. var results = include && [],
  9204. tMin = 1e-8,
  9205. tMax = 1 - tMin,
  9206. clearHandles = false,
  9207. clearCurves = clearLater || [],
  9208. clearLookup = clearLater && {},
  9209. renormalizeLocs,
  9210. prevCurve,
  9211. prevTime;
  9212. function getId(curve) {
  9213. return curve._path._id + '.' + curve._segment1._index;
  9214. }
  9215. for (var i = (clearLater && clearLater.length) - 1; i >= 0; i--) {
  9216. var curve = clearLater[i];
  9217. if (curve._path)
  9218. clearLookup[getId(curve)] = true;
  9219. }
  9220. for (var i = locations.length - 1; i >= 0; i--) {
  9221. var loc = locations[i],
  9222. time = loc._time,
  9223. origTime = time,
  9224. exclude = include && !include(loc),
  9225. curve = loc._curve,
  9226. segment;
  9227. if (curve) {
  9228. if (curve !== prevCurve) {
  9229. clearHandles = !curve.hasHandles()
  9230. || clearLookup && clearLookup[getId(curve)];
  9231. renormalizeLocs = [];
  9232. prevTime = null;
  9233. prevCurve = curve;
  9234. } else if (prevTime >= tMin) {
  9235. time /= prevTime;
  9236. }
  9237. }
  9238. if (exclude) {
  9239. if (renormalizeLocs)
  9240. renormalizeLocs.push(loc);
  9241. continue;
  9242. } else if (include) {
  9243. results.unshift(loc);
  9244. }
  9245. prevTime = origTime;
  9246. if (time < tMin) {
  9247. segment = curve._segment1;
  9248. } else if (time > tMax) {
  9249. segment = curve._segment2;
  9250. } else {
  9251. var newCurve = curve.divideAtTime(time, true);
  9252. if (clearHandles)
  9253. clearCurves.push(curve, newCurve);
  9254. segment = newCurve._segment1;
  9255. for (var j = renormalizeLocs.length - 1; j >= 0; j--) {
  9256. var l = renormalizeLocs[j];
  9257. l._time = (l._time - time) / (1 - time);
  9258. }
  9259. }
  9260. loc._setSegment(segment);
  9261. var inter = segment._intersection,
  9262. dest = loc._intersection;
  9263. if (inter) {
  9264. linkIntersections(inter, dest);
  9265. var other = inter;
  9266. while (other) {
  9267. linkIntersections(other._intersection, inter);
  9268. other = other._next;
  9269. }
  9270. } else {
  9271. segment._intersection = dest;
  9272. }
  9273. }
  9274. if (!clearLater)
  9275. clearCurveHandles(clearCurves);
  9276. return results || locations;
  9277. }
  9278. function getWinding(point, curves, dir, closed, dontFlip) {
  9279. var ia = dir ? 1 : 0,
  9280. io = ia ^ 1,
  9281. pv = [point.x, point.y],
  9282. pa = pv[ia],
  9283. po = pv[io],
  9284. windingEpsilon = 1e-9,
  9285. qualityEpsilon = 1e-6,
  9286. paL = pa - windingEpsilon,
  9287. paR = pa + windingEpsilon,
  9288. windingL = 0,
  9289. windingR = 0,
  9290. pathWindingL = 0,
  9291. pathWindingR = 0,
  9292. onPath = false,
  9293. onAnyPath = false,
  9294. quality = 1,
  9295. roots = [],
  9296. vPrev,
  9297. vClose;
  9298. function addWinding(v) {
  9299. var o0 = v[io + 0],
  9300. o3 = v[io + 6];
  9301. if (po < min(o0, o3) || po > max(o0, o3)) {
  9302. return;
  9303. }
  9304. var a0 = v[ia + 0],
  9305. a1 = v[ia + 2],
  9306. a2 = v[ia + 4],
  9307. a3 = v[ia + 6];
  9308. if (o0 === o3) {
  9309. if (a0 < paR && a3 > paL || a3 < paR && a0 > paL) {
  9310. onPath = true;
  9311. }
  9312. return;
  9313. }
  9314. var t = po === o0 ? 0
  9315. : po === o3 ? 1
  9316. : paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3)
  9317. ? 1
  9318. : Curve.solveCubic(v, io, po, roots, 0, 1) > 0
  9319. ? roots[0]
  9320. : 1,
  9321. a = t === 0 ? a0
  9322. : t === 1 ? a3
  9323. : Curve.getPoint(v, t)[dir ? 'y' : 'x'],
  9324. winding = o0 > o3 ? 1 : -1,
  9325. windingPrev = vPrev[io] > vPrev[io + 6] ? 1 : -1,
  9326. a3Prev = vPrev[ia + 6];
  9327. if (po !== o0) {
  9328. if (a < paL) {
  9329. pathWindingL += winding;
  9330. } else if (a > paR) {
  9331. pathWindingR += winding;
  9332. } else {
  9333. onPath = true;
  9334. }
  9335. if (a > pa - qualityEpsilon && a < pa + qualityEpsilon)
  9336. quality /= 2;
  9337. } else {
  9338. if (winding !== windingPrev) {
  9339. if (a0 < paL) {
  9340. pathWindingL += winding;
  9341. } else if (a0 > paR) {
  9342. pathWindingR += winding;
  9343. }
  9344. } else if (a0 != a3Prev) {
  9345. if (a3Prev < paR && a > paR) {
  9346. pathWindingR += winding;
  9347. onPath = true;
  9348. } else if (a3Prev > paL && a < paL) {
  9349. pathWindingL += winding;
  9350. onPath = true;
  9351. }
  9352. }
  9353. quality = 0;
  9354. }
  9355. vPrev = v;
  9356. return !dontFlip && a > paL && a < paR
  9357. && Curve.getTangent(v, t)[dir ? 'x' : 'y'] === 0
  9358. && getWinding(point, curves, !dir, closed, true);
  9359. }
  9360. function handleCurve(v) {
  9361. var o0 = v[io + 0],
  9362. o1 = v[io + 2],
  9363. o2 = v[io + 4],
  9364. o3 = v[io + 6];
  9365. if (po <= max(o0, o1, o2, o3) && po >= min(o0, o1, o2, o3)) {
  9366. var a0 = v[ia + 0],
  9367. a1 = v[ia + 2],
  9368. a2 = v[ia + 4],
  9369. a3 = v[ia + 6],
  9370. monoCurves = paL > max(a0, a1, a2, a3) ||
  9371. paR < min(a0, a1, a2, a3)
  9372. ? [v] : Curve.getMonoCurves(v, dir),
  9373. res;
  9374. for (var i = 0, l = monoCurves.length; i < l; i++) {
  9375. if (res = addWinding(monoCurves[i]))
  9376. return res;
  9377. }
  9378. }
  9379. }
  9380. for (var i = 0, l = curves.length; i < l; i++) {
  9381. var curve = curves[i],
  9382. path = curve._path,
  9383. v = curve.getValues(),
  9384. res;
  9385. if (!i || curves[i - 1]._path !== path) {
  9386. vPrev = null;
  9387. if (!path._closed) {
  9388. vClose = Curve.getValues(
  9389. path.getLastCurve().getSegment2(),
  9390. curve.getSegment1(),
  9391. null, !closed);
  9392. if (vClose[io] !== vClose[io + 6]) {
  9393. vPrev = vClose;
  9394. }
  9395. }
  9396. if (!vPrev) {
  9397. vPrev = v;
  9398. var prev = path.getLastCurve();
  9399. while (prev && prev !== curve) {
  9400. var v2 = prev.getValues();
  9401. if (v2[io] !== v2[io + 6]) {
  9402. vPrev = v2;
  9403. break;
  9404. }
  9405. prev = prev.getPrevious();
  9406. }
  9407. }
  9408. }
  9409. if (res = handleCurve(v))
  9410. return res;
  9411. if (i + 1 === l || curves[i + 1]._path !== path) {
  9412. if (vClose && (res = handleCurve(vClose)))
  9413. return res;
  9414. if (onPath && !pathWindingL && !pathWindingR) {
  9415. pathWindingL = pathWindingR = path.isClockwise(closed) ^ dir
  9416. ? 1 : -1;
  9417. }
  9418. windingL += pathWindingL;
  9419. windingR += pathWindingR;
  9420. pathWindingL = pathWindingR = 0;
  9421. if (onPath) {
  9422. onAnyPath = true;
  9423. onPath = false;
  9424. }
  9425. vClose = null;
  9426. }
  9427. }
  9428. windingL = abs(windingL);
  9429. windingR = abs(windingR);
  9430. return {
  9431. winding: max(windingL, windingR),
  9432. windingL: windingL,
  9433. windingR: windingR,
  9434. quality: quality,
  9435. onPath: onAnyPath
  9436. };
  9437. }
  9438. function propagateWinding(segment, path1, path2, curves, operator) {
  9439. var chain = [],
  9440. start = segment,
  9441. totalLength = 0,
  9442. winding;
  9443. do {
  9444. var curve = segment.getCurve(),
  9445. length = curve.getLength();
  9446. chain.push({ segment: segment, curve: curve, length: length });
  9447. totalLength += length;
  9448. segment = segment.getNext();
  9449. } while (segment && !segment._intersection && segment !== start);
  9450. var offsets = [0.5, 0.25, 0.75],
  9451. winding = { winding: 0, quality: -1 },
  9452. tMin = 1e-8,
  9453. tMax = 1 - tMin;
  9454. for (var i = 0; i < offsets.length && winding.quality < 0.5; i++) {
  9455. var length = totalLength * offsets[i];
  9456. for (var j = 0, l = chain.length; j < l; j++) {
  9457. var entry = chain[j],
  9458. curveLength = entry.length;
  9459. if (length <= curveLength) {
  9460. var curve = entry.curve,
  9461. path = curve._path,
  9462. parent = path._parent,
  9463. operand = parent instanceof CompoundPath ? parent : path,
  9464. t = Numerical.clamp(curve.getTimeAt(length), tMin, tMax),
  9465. pt = curve.getPointAtTime(t),
  9466. dir = abs(curve.getTangentAtTime(t).y) < Math.SQRT1_2;
  9467. var wind = null;
  9468. if (operator.subtract && path2) {
  9469. var pathWinding = operand === path1
  9470. ? path2._getWinding(pt, dir, true)
  9471. : path1._getWinding(pt, dir, true);
  9472. if (operand === path1 && pathWinding.winding ||
  9473. operand === path2 && !pathWinding.winding) {
  9474. if (pathWinding.quality < 1) {
  9475. continue;
  9476. } else {
  9477. wind = { winding: 0, quality: 1 };
  9478. }
  9479. }
  9480. }
  9481. wind = wind || getWinding(pt, curves, dir, true);
  9482. if (wind.quality > winding.quality)
  9483. winding = wind;
  9484. break;
  9485. }
  9486. length -= curveLength;
  9487. }
  9488. }
  9489. for (var j = chain.length - 1; j >= 0; j--) {
  9490. chain[j].segment._winding = winding;
  9491. }
  9492. }
  9493. function tracePaths(segments, operator) {
  9494. var paths = [],
  9495. starts;
  9496. function isValid(seg) {
  9497. var winding;
  9498. return !!(seg && !seg._visited && (!operator
  9499. || operator[(winding = seg._winding || {}).winding]
  9500. && !(operator.unite && winding.winding === 2
  9501. && winding.windingL && winding.windingR)));
  9502. }
  9503. function isStart(seg) {
  9504. if (seg) {
  9505. for (var i = 0, l = starts.length; i < l; i++) {
  9506. if (seg === starts[i])
  9507. return true;
  9508. }
  9509. }
  9510. return false;
  9511. }
  9512. function visitPath(path) {
  9513. var segments = path._segments;
  9514. for (var i = 0, l = segments.length; i < l; i++) {
  9515. segments[i]._visited = true;
  9516. }
  9517. }
  9518. function getCrossingSegments(segment, collectStarts) {
  9519. var inter = segment._intersection,
  9520. start = inter,
  9521. crossings = [];
  9522. if (collectStarts)
  9523. starts = [segment];
  9524. function collect(inter, end) {
  9525. while (inter && inter !== end) {
  9526. var other = inter._segment,
  9527. path = other && other._path;
  9528. if (path) {
  9529. var next = other.getNext() || path.getFirstSegment(),
  9530. nextInter = next._intersection;
  9531. if (other !== segment && (isStart(other)
  9532. || isStart(next)
  9533. || next && (isValid(other) && (isValid(next)
  9534. || nextInter && isValid(nextInter._segment))))
  9535. ) {
  9536. crossings.push(other);
  9537. }
  9538. if (collectStarts)
  9539. starts.push(other);
  9540. }
  9541. inter = inter._next;
  9542. }
  9543. }
  9544. if (inter) {
  9545. collect(inter);
  9546. while (inter && inter._prev)
  9547. inter = inter._prev;
  9548. collect(inter, start);
  9549. }
  9550. return crossings;
  9551. }
  9552. segments.sort(function(seg1, seg2) {
  9553. var inter1 = seg1._intersection,
  9554. inter2 = seg2._intersection,
  9555. over1 = !!(inter1 && inter1._overlap),
  9556. over2 = !!(inter2 && inter2._overlap),
  9557. path1 = seg1._path,
  9558. path2 = seg2._path;
  9559. return over1 ^ over2
  9560. ? over1 ? 1 : -1
  9561. : !inter1 ^ !inter2
  9562. ? inter1 ? 1 : -1
  9563. : path1 !== path2
  9564. ? path1._id - path2._id
  9565. : seg1._index - seg2._index;
  9566. });
  9567. for (var i = 0, l = segments.length; i < l; i++) {
  9568. var seg = segments[i],
  9569. valid = isValid(seg),
  9570. path = null,
  9571. finished = false,
  9572. closed = true,
  9573. branches = [],
  9574. branch,
  9575. visited,
  9576. handleIn;
  9577. if (valid && seg._path._overlapsOnly) {
  9578. var path1 = seg._path,
  9579. path2 = seg._intersection._segment._path;
  9580. if (path1.compare(path2)) {
  9581. if (path1.getArea())
  9582. paths.push(path1.clone(false));
  9583. visitPath(path1);
  9584. visitPath(path2);
  9585. valid = false;
  9586. }
  9587. }
  9588. while (valid) {
  9589. var first = !path,
  9590. crossings = getCrossingSegments(seg, first),
  9591. other = crossings.shift(),
  9592. finished = !first && (isStart(seg) || isStart(other)),
  9593. cross = !finished && other;
  9594. if (first) {
  9595. path = new Path(Item.NO_INSERT);
  9596. branch = null;
  9597. }
  9598. if (finished) {
  9599. if (seg.isFirst() || seg.isLast())
  9600. closed = seg._path._closed;
  9601. seg._visited = true;
  9602. break;
  9603. }
  9604. if (cross && branch) {
  9605. branches.push(branch);
  9606. branch = null;
  9607. }
  9608. if (!branch) {
  9609. if (cross)
  9610. crossings.push(seg);
  9611. branch = {
  9612. start: path._segments.length,
  9613. crossings: crossings,
  9614. visited: visited = [],
  9615. handleIn: handleIn
  9616. };
  9617. }
  9618. if (cross)
  9619. seg = other;
  9620. if (!isValid(seg)) {
  9621. path.removeSegments(branch.start);
  9622. for (var j = 0, k = visited.length; j < k; j++) {
  9623. visited[j]._visited = false;
  9624. }
  9625. visited.length = 0;
  9626. do {
  9627. seg = branch && branch.crossings.shift();
  9628. if (!seg || !seg._path) {
  9629. seg = null;
  9630. branch = branches.pop();
  9631. if (branch) {
  9632. visited = branch.visited;
  9633. handleIn = branch.handleIn;
  9634. }
  9635. }
  9636. } while (branch && !isValid(seg));
  9637. if (!seg)
  9638. break;
  9639. }
  9640. var next = seg.getNext();
  9641. path.add(new Segment(seg._point, handleIn,
  9642. next && seg._handleOut));
  9643. seg._visited = true;
  9644. visited.push(seg);
  9645. seg = next || seg._path.getFirstSegment();
  9646. handleIn = next && next._handleIn;
  9647. }
  9648. if (finished) {
  9649. if (closed) {
  9650. path.getFirstSegment().setHandleIn(handleIn);
  9651. path.setClosed(closed);
  9652. }
  9653. if (path.getArea() !== 0) {
  9654. paths.push(path);
  9655. }
  9656. }
  9657. }
  9658. return paths;
  9659. }
  9660. return {
  9661. _getWinding: function(point, dir, closed) {
  9662. return getWinding(point, this.getCurves(), dir, closed);
  9663. },
  9664. unite: function(path, options) {
  9665. return traceBoolean(this, path, 'unite', options);
  9666. },
  9667. intersect: function(path, options) {
  9668. return traceBoolean(this, path, 'intersect', options);
  9669. },
  9670. subtract: function(path, options) {
  9671. return traceBoolean(this, path, 'subtract', options);
  9672. },
  9673. exclude: function(path, options) {
  9674. return traceBoolean(this, path, 'exclude', options);
  9675. },
  9676. divide: function(path, options) {
  9677. return options && (options.trace == false || options.stroke)
  9678. ? splitBoolean(this, path, 'divide')
  9679. : createResult([
  9680. this.subtract(path, options),
  9681. this.intersect(path, options)
  9682. ], true, this, path, options);
  9683. },
  9684. resolveCrossings: function() {
  9685. var children = this._children,
  9686. paths = children || [this];
  9687. function hasOverlap(seg, path) {
  9688. var inter = seg && seg._intersection;
  9689. return inter && inter._overlap && inter._path === path;
  9690. }
  9691. var hasOverlaps = false,
  9692. hasCrossings = false,
  9693. intersections = this.getIntersections(null, function(inter) {
  9694. return inter.hasOverlap() && (hasOverlaps = true) ||
  9695. inter.isCrossing() && (hasCrossings = true);
  9696. }),
  9697. clearCurves = hasOverlaps && hasCrossings && [];
  9698. intersections = CurveLocation.expand(intersections);
  9699. if (hasOverlaps) {
  9700. var overlaps = divideLocations(intersections, function(inter) {
  9701. return inter.hasOverlap();
  9702. }, clearCurves);
  9703. for (var i = overlaps.length - 1; i >= 0; i--) {
  9704. var overlap = overlaps[i],
  9705. path = overlap._path,
  9706. seg = overlap._segment,
  9707. prev = seg.getPrevious(),
  9708. next = seg.getNext();
  9709. if (hasOverlap(prev, path) && hasOverlap(next, path)) {
  9710. seg.remove();
  9711. prev._handleOut._set(0, 0);
  9712. next._handleIn._set(0, 0);
  9713. if (prev !== seg && !prev.getCurve().hasLength()) {
  9714. next._handleIn.set(prev._handleIn);
  9715. prev.remove();
  9716. }
  9717. }
  9718. }
  9719. }
  9720. if (hasCrossings) {
  9721. divideLocations(intersections, hasOverlaps && function(inter) {
  9722. var curve1 = inter.getCurve(),
  9723. seg1 = inter.getSegment(),
  9724. other = inter._intersection,
  9725. curve2 = other._curve,
  9726. seg2 = other._segment;
  9727. if (curve1 && curve2 && curve1._path && curve2._path)
  9728. return true;
  9729. if (seg1)
  9730. seg1._intersection = null;
  9731. if (seg2)
  9732. seg2._intersection = null;
  9733. }, clearCurves);
  9734. if (clearCurves)
  9735. clearCurveHandles(clearCurves);
  9736. paths = tracePaths(Base.each(paths, function(path) {
  9737. Base.push(this, path._segments);
  9738. }, []));
  9739. }
  9740. var length = paths.length,
  9741. item;
  9742. if (length > 1 && children) {
  9743. if (paths !== children)
  9744. this.setChildren(paths);
  9745. item = this;
  9746. } else if (length === 1 && !children) {
  9747. if (paths[0] !== this)
  9748. this.setSegments(paths[0].removeSegments());
  9749. item = this;
  9750. }
  9751. if (!item) {
  9752. item = new CompoundPath(Item.NO_INSERT);
  9753. item.addChildren(paths);
  9754. item = item.reduce();
  9755. item.copyAttributes(this);
  9756. this.replaceWith(item);
  9757. }
  9758. return item;
  9759. },
  9760. reorient: function(nonZero, clockwise) {
  9761. var children = this._children;
  9762. if (children && children.length) {
  9763. this.setChildren(reorientPaths(this.removeChildren(),
  9764. function(w) {
  9765. return !!(nonZero ? w : w & 1);
  9766. },
  9767. clockwise));
  9768. } else if (clockwise !== undefined) {
  9769. this.setClockwise(clockwise);
  9770. }
  9771. return this;
  9772. },
  9773. getInteriorPoint: function() {
  9774. var bounds = this.getBounds(),
  9775. point = bounds.getCenter(true);
  9776. if (!this.contains(point)) {
  9777. var curves = this.getCurves(),
  9778. y = point.y,
  9779. intercepts = [],
  9780. roots = [];
  9781. for (var i = 0, l = curves.length; i < l; i++) {
  9782. var v = curves[i].getValues(),
  9783. o0 = v[1],
  9784. o1 = v[3],
  9785. o2 = v[5],
  9786. o3 = v[7];
  9787. if (y >= min(o0, o1, o2, o3) && y <= max(o0, o1, o2, o3)) {
  9788. var monoCurves = Curve.getMonoCurves(v);
  9789. for (var j = 0, m = monoCurves.length; j < m; j++) {
  9790. var mv = monoCurves[j],
  9791. mo0 = mv[1],
  9792. mo3 = mv[7];
  9793. if ((mo0 !== mo3) &&
  9794. (y >= mo0 && y <= mo3 || y >= mo3 && y <= mo0)){
  9795. var x = y === mo0 ? mv[0]
  9796. : y === mo3 ? mv[6]
  9797. : Curve.solveCubic(mv, 1, y, roots, 0, 1)
  9798. === 1
  9799. ? Curve.getPoint(mv, roots[0]).x
  9800. : (mv[0] + mv[6]) / 2;
  9801. intercepts.push(x);
  9802. }
  9803. }
  9804. }
  9805. }
  9806. if (intercepts.length > 1) {
  9807. intercepts.sort(function(a, b) { return a - b; });
  9808. point.x = (intercepts[0] + intercepts[1]) / 2;
  9809. }
  9810. }
  9811. return point;
  9812. }
  9813. };
  9814. });
  9815. var PathFlattener = Base.extend({
  9816. _class: 'PathFlattener',
  9817. initialize: function(path, flatness, maxRecursion, ignoreStraight, matrix) {
  9818. var curves = [],
  9819. parts = [],
  9820. length = 0,
  9821. minSpan = 1 / (maxRecursion || 32),
  9822. segments = path._segments,
  9823. segment1 = segments[0],
  9824. segment2;
  9825. function addCurve(segment1, segment2) {
  9826. var curve = Curve.getValues(segment1, segment2, matrix);
  9827. curves.push(curve);
  9828. computeParts(curve, segment1._index, 0, 1);
  9829. }
  9830. function computeParts(curve, index, t1, t2) {
  9831. if ((t2 - t1) > minSpan
  9832. && !(ignoreStraight && Curve.isStraight(curve))
  9833. && !Curve.isFlatEnough(curve, flatness || 0.25)) {
  9834. var halves = Curve.subdivide(curve, 0.5),
  9835. tMid = (t1 + t2) / 2;
  9836. computeParts(halves[0], index, t1, tMid);
  9837. computeParts(halves[1], index, tMid, t2);
  9838. } else {
  9839. var dx = curve[6] - curve[0],
  9840. dy = curve[7] - curve[1],
  9841. dist = Math.sqrt(dx * dx + dy * dy);
  9842. if (dist > 0) {
  9843. length += dist;
  9844. parts.push({
  9845. offset: length,
  9846. curve: curve,
  9847. index: index,
  9848. time: t2,
  9849. });
  9850. }
  9851. }
  9852. }
  9853. for (var i = 1, l = segments.length; i < l; i++) {
  9854. segment2 = segments[i];
  9855. addCurve(segment1, segment2);
  9856. segment1 = segment2;
  9857. }
  9858. if (path._closed)
  9859. addCurve(segment2 || segment1, segments[0]);
  9860. this.curves = curves;
  9861. this.parts = parts;
  9862. this.length = length;
  9863. this.index = 0;
  9864. },
  9865. _get: function(offset) {
  9866. var parts = this.parts,
  9867. length = parts.length,
  9868. start,
  9869. i, j = this.index;
  9870. for (;;) {
  9871. i = j;
  9872. if (!j || parts[--j].offset < offset)
  9873. break;
  9874. }
  9875. for (; i < length; i++) {
  9876. var part = parts[i];
  9877. if (part.offset >= offset) {
  9878. this.index = i;
  9879. var prev = parts[i - 1],
  9880. prevTime = prev && prev.index === part.index ? prev.time : 0,
  9881. prevOffset = prev ? prev.offset : 0;
  9882. return {
  9883. index: part.index,
  9884. time: prevTime + (part.time - prevTime)
  9885. * (offset - prevOffset) / (part.offset - prevOffset)
  9886. };
  9887. }
  9888. }
  9889. return {
  9890. index: parts[length - 1].index,
  9891. time: 1
  9892. };
  9893. },
  9894. drawPart: function(ctx, from, to) {
  9895. var start = this._get(from),
  9896. end = this._get(to);
  9897. for (var i = start.index, l = end.index; i <= l; i++) {
  9898. var curve = Curve.getPart(this.curves[i],
  9899. i === start.index ? start.time : 0,
  9900. i === end.index ? end.time : 1);
  9901. if (i === start.index)
  9902. ctx.moveTo(curve[0], curve[1]);
  9903. ctx.bezierCurveTo.apply(ctx, curve.slice(2));
  9904. }
  9905. }
  9906. }, Base.each(Curve._evaluateMethods,
  9907. function(name) {
  9908. this[name + 'At'] = function(offset) {
  9909. var param = this._get(offset);
  9910. return Curve[name](this.curves[param.index], param.time);
  9911. };
  9912. }, {})
  9913. );
  9914. var PathFitter = Base.extend({
  9915. initialize: function(path) {
  9916. var points = this.points = [],
  9917. segments = path._segments,
  9918. closed = path._closed;
  9919. for (var i = 0, prev, l = segments.length; i < l; i++) {
  9920. var point = segments[i].point;
  9921. if (!prev || !prev.equals(point)) {
  9922. points.push(prev = point.clone());
  9923. }
  9924. }
  9925. if (closed) {
  9926. points.unshift(points[points.length - 1]);
  9927. points.push(points[1]);
  9928. }
  9929. this.closed = closed;
  9930. },
  9931. fit: function(error) {
  9932. var points = this.points,
  9933. length = points.length,
  9934. segments = null;
  9935. if (length > 0) {
  9936. segments = [new Segment(points[0])];
  9937. if (length > 1) {
  9938. this.fitCubic(segments, error, 0, length - 1,
  9939. points[1].subtract(points[0]),
  9940. points[length - 2].subtract(points[length - 1]));
  9941. if (this.closed) {
  9942. segments.shift();
  9943. segments.pop();
  9944. }
  9945. }
  9946. }
  9947. return segments;
  9948. },
  9949. fitCubic: function(segments, error, first, last, tan1, tan2) {
  9950. var points = this.points;
  9951. if (last - first === 1) {
  9952. var pt1 = points[first],
  9953. pt2 = points[last],
  9954. dist = pt1.getDistance(pt2) / 3;
  9955. this.addCurve(segments, [pt1, pt1.add(tan1.normalize(dist)),
  9956. pt2.add(tan2.normalize(dist)), pt2]);
  9957. return;
  9958. }
  9959. var uPrime = this.chordLengthParameterize(first, last),
  9960. maxError = Math.max(error, error * error),
  9961. split,
  9962. parametersInOrder = true;
  9963. for (var i = 0; i <= 4; i++) {
  9964. var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
  9965. var max = this.findMaxError(first, last, curve, uPrime);
  9966. if (max.error < error && parametersInOrder) {
  9967. this.addCurve(segments, curve);
  9968. return;
  9969. }
  9970. split = max.index;
  9971. if (max.error >= maxError)
  9972. break;
  9973. parametersInOrder = this.reparameterize(first, last, uPrime, curve);
  9974. maxError = max.error;
  9975. }
  9976. var tanCenter = points[split - 1].subtract(points[split + 1]);
  9977. this.fitCubic(segments, error, first, split, tan1, tanCenter);
  9978. this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2);
  9979. },
  9980. addCurve: function(segments, curve) {
  9981. var prev = segments[segments.length - 1];
  9982. prev.setHandleOut(curve[1].subtract(curve[0]));
  9983. segments.push(new Segment(curve[3], curve[2].subtract(curve[3])));
  9984. },
  9985. generateBezier: function(first, last, uPrime, tan1, tan2) {
  9986. var epsilon = 1e-12,
  9987. abs = Math.abs,
  9988. points = this.points,
  9989. pt1 = points[first],
  9990. pt2 = points[last],
  9991. C = [[0, 0], [0, 0]],
  9992. X = [0, 0];
  9993. for (var i = 0, l = last - first + 1; i < l; i++) {
  9994. var u = uPrime[i],
  9995. t = 1 - u,
  9996. b = 3 * u * t,
  9997. b0 = t * t * t,
  9998. b1 = b * t,
  9999. b2 = b * u,
  10000. b3 = u * u * u,
  10001. a1 = tan1.normalize(b1),
  10002. a2 = tan2.normalize(b2),
  10003. tmp = points[first + i]
  10004. .subtract(pt1.multiply(b0 + b1))
  10005. .subtract(pt2.multiply(b2 + b3));
  10006. C[0][0] += a1.dot(a1);
  10007. C[0][1] += a1.dot(a2);
  10008. C[1][0] = C[0][1];
  10009. C[1][1] += a2.dot(a2);
  10010. X[0] += a1.dot(tmp);
  10011. X[1] += a2.dot(tmp);
  10012. }
  10013. var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
  10014. alpha1,
  10015. alpha2;
  10016. if (abs(detC0C1) > epsilon) {
  10017. var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
  10018. detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
  10019. alpha1 = detXC1 / detC0C1;
  10020. alpha2 = detC0X / detC0C1;
  10021. } else {
  10022. var c0 = C[0][0] + C[0][1],
  10023. c1 = C[1][0] + C[1][1];
  10024. alpha1 = alpha2 = abs(c0) > epsilon ? X[0] / c0
  10025. : abs(c1) > epsilon ? X[1] / c1
  10026. : 0;
  10027. }
  10028. var segLength = pt2.getDistance(pt1),
  10029. eps = epsilon * segLength,
  10030. handle1,
  10031. handle2;
  10032. if (alpha1 < eps || alpha2 < eps) {
  10033. alpha1 = alpha2 = segLength / 3;
  10034. } else {
  10035. var line = pt2.subtract(pt1);
  10036. handle1 = tan1.normalize(alpha1);
  10037. handle2 = tan2.normalize(alpha2);
  10038. if (handle1.dot(line) - handle2.dot(line) > segLength * segLength) {
  10039. alpha1 = alpha2 = segLength / 3;
  10040. handle1 = handle2 = null;
  10041. }
  10042. }
  10043. return [pt1,
  10044. pt1.add(handle1 || tan1.normalize(alpha1)),
  10045. pt2.add(handle2 || tan2.normalize(alpha2)),
  10046. pt2];
  10047. },
  10048. reparameterize: function(first, last, u, curve) {
  10049. for (var i = first; i <= last; i++) {
  10050. u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
  10051. }
  10052. for (var i = 1, l = u.length; i < l; i++) {
  10053. if (u[i] <= u[i - 1])
  10054. return false;
  10055. }
  10056. return true;
  10057. },
  10058. findRoot: function(curve, point, u) {
  10059. var curve1 = [],
  10060. curve2 = [];
  10061. for (var i = 0; i <= 2; i++) {
  10062. curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
  10063. }
  10064. for (var i = 0; i <= 1; i++) {
  10065. curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
  10066. }
  10067. var pt = this.evaluate(3, curve, u),
  10068. pt1 = this.evaluate(2, curve1, u),
  10069. pt2 = this.evaluate(1, curve2, u),
  10070. diff = pt.subtract(point),
  10071. df = pt1.dot(pt1) + diff.dot(pt2);
  10072. return Numerical.isZero(df) ? u : u - diff.dot(pt1) / df;
  10073. },
  10074. evaluate: function(degree, curve, t) {
  10075. var tmp = curve.slice();
  10076. for (var i = 1; i <= degree; i++) {
  10077. for (var j = 0; j <= degree - i; j++) {
  10078. tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
  10079. }
  10080. }
  10081. return tmp[0];
  10082. },
  10083. chordLengthParameterize: function(first, last) {
  10084. var u = [0];
  10085. for (var i = first + 1; i <= last; i++) {
  10086. u[i - first] = u[i - first - 1]
  10087. + this.points[i].getDistance(this.points[i - 1]);
  10088. }
  10089. for (var i = 1, m = last - first; i <= m; i++) {
  10090. u[i] /= u[m];
  10091. }
  10092. return u;
  10093. },
  10094. findMaxError: function(first, last, curve, u) {
  10095. var index = Math.floor((last - first + 1) / 2),
  10096. maxDist = 0;
  10097. for (var i = first + 1; i < last; i++) {
  10098. var P = this.evaluate(3, curve, u[i - first]);
  10099. var v = P.subtract(this.points[i]);
  10100. var dist = v.x * v.x + v.y * v.y;
  10101. if (dist >= maxDist) {
  10102. maxDist = dist;
  10103. index = i;
  10104. }
  10105. }
  10106. return {
  10107. error: maxDist,
  10108. index: index
  10109. };
  10110. }
  10111. });
  10112. var TextItem = Item.extend({
  10113. _class: 'TextItem',
  10114. _applyMatrix: false,
  10115. _canApplyMatrix: false,
  10116. _serializeFields: {
  10117. content: null
  10118. },
  10119. _boundsOptions: { stroke: false, handle: false },
  10120. initialize: function TextItem(arg) {
  10121. this._content = '';
  10122. this._lines = [];
  10123. var hasProps = arg && Base.isPlainObject(arg)
  10124. && arg.x === undefined && arg.y === undefined;
  10125. this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
  10126. },
  10127. _equals: function(item) {
  10128. return this._content === item._content;
  10129. },
  10130. copyContent: function(source) {
  10131. this.setContent(source._content);
  10132. },
  10133. getContent: function() {
  10134. return this._content;
  10135. },
  10136. setContent: function(content) {
  10137. this._content = '' + content;
  10138. this._lines = this._content.split(/\r\n|\n|\r/mg);
  10139. this._changed(521);
  10140. },
  10141. isEmpty: function() {
  10142. return !this._content;
  10143. },
  10144. getCharacterStyle: '#getStyle',
  10145. setCharacterStyle: '#setStyle',
  10146. getParagraphStyle: '#getStyle',
  10147. setParagraphStyle: '#setStyle'
  10148. });
  10149. var PointText = TextItem.extend({
  10150. _class: 'PointText',
  10151. initialize: function PointText() {
  10152. TextItem.apply(this, arguments);
  10153. },
  10154. getPoint: function() {
  10155. var point = this._matrix.getTranslation();
  10156. return new LinkedPoint(point.x, point.y, this, 'setPoint');
  10157. },
  10158. setPoint: function() {
  10159. var point = Point.read(arguments);
  10160. this.translate(point.subtract(this._matrix.getTranslation()));
  10161. },
  10162. _draw: function(ctx, param, viewMatrix) {
  10163. if (!this._content)
  10164. return;
  10165. this._setStyles(ctx, param, viewMatrix);
  10166. var lines = this._lines,
  10167. style = this._style,
  10168. hasFill = style.hasFill(),
  10169. hasStroke = style.hasStroke(),
  10170. leading = style.getLeading(),
  10171. shadowColor = ctx.shadowColor;
  10172. ctx.font = style.getFontStyle();
  10173. ctx.textAlign = style.getJustification();
  10174. for (var i = 0, l = lines.length; i < l; i++) {
  10175. ctx.shadowColor = shadowColor;
  10176. var line = lines[i];
  10177. if (hasFill) {
  10178. ctx.fillText(line, 0, 0);
  10179. ctx.shadowColor = 'rgba(0,0,0,0)';
  10180. }
  10181. if (hasStroke)
  10182. ctx.strokeText(line, 0, 0);
  10183. ctx.translate(0, leading);
  10184. }
  10185. },
  10186. _getBounds: function(matrix, options) {
  10187. var style = this._style,
  10188. lines = this._lines,
  10189. numLines = lines.length,
  10190. justification = style.getJustification(),
  10191. leading = style.getLeading(),
  10192. width = this.getView().getTextWidth(style.getFontStyle(), lines),
  10193. x = 0;
  10194. if (justification !== 'left')
  10195. x -= width / (justification === 'center' ? 2: 1);
  10196. var rect = new Rectangle(x,
  10197. numLines ? - 0.75 * leading : 0,
  10198. width, numLines * leading);
  10199. return matrix ? matrix._transformBounds(rect, rect) : rect;
  10200. }
  10201. });
  10202. var Color = Base.extend(new function() {
  10203. var types = {
  10204. gray: ['gray'],
  10205. rgb: ['red', 'green', 'blue'],
  10206. hsb: ['hue', 'saturation', 'brightness'],
  10207. hsl: ['hue', 'saturation', 'lightness'],
  10208. gradient: ['gradient', 'origin', 'destination', 'highlight']
  10209. };
  10210. var componentParsers = {},
  10211. namedColors = {
  10212. transparent: [0, 0, 0, 0]
  10213. },
  10214. colorCtx;
  10215. function fromCSS(string) {
  10216. var match = string.match(
  10217. /^#([\da-f]{2})([\da-f]{2})([\da-f]{2})([\da-f]{2})?$/i
  10218. ) || string.match(
  10219. /^#([\da-f])([\da-f])([\da-f])([\da-f])?$/i
  10220. ),
  10221. type = 'rgb',
  10222. components;
  10223. if (match) {
  10224. var amount = match[4] ? 4 : 3;
  10225. components = new Array(amount);
  10226. for (var i = 0; i < amount; i++) {
  10227. var value = match[i + 1];
  10228. components[i] = parseInt(value.length == 1
  10229. ? value + value : value, 16) / 255;
  10230. }
  10231. } else if (match = string.match(/^(rgb|hsl)a?\((.*)\)$/)) {
  10232. type = match[1];
  10233. components = match[2].split(/[,\s]+/g);
  10234. var isHSL = type === 'hsl';
  10235. for (var i = 0, l = Math.min(components.length, 4); i < l; i++) {
  10236. var component = components[i];
  10237. var value = parseFloat(component);
  10238. if (isHSL) {
  10239. if (i === 0) {
  10240. var unit = component.match(/([a-z]*)$/)[1];
  10241. value *= ({
  10242. turn: 360,
  10243. rad: 180 / Math.PI,
  10244. grad: 0.9
  10245. }[unit] || 1);
  10246. } else if (i < 3) {
  10247. value /= 100;
  10248. }
  10249. } else if (i < 3) {
  10250. value /= 255;
  10251. }
  10252. components[i] = value;
  10253. }
  10254. } else {
  10255. var color = namedColors[string];
  10256. if (!color) {
  10257. if (window) {
  10258. if (!colorCtx) {
  10259. colorCtx = CanvasProvider.getContext(1, 1);
  10260. colorCtx.globalCompositeOperation = 'copy';
  10261. }
  10262. colorCtx.fillStyle = 'rgba(0,0,0,0)';
  10263. colorCtx.fillStyle = string;
  10264. colorCtx.fillRect(0, 0, 1, 1);
  10265. var data = colorCtx.getImageData(0, 0, 1, 1).data;
  10266. color = namedColors[string] = [
  10267. data[0] / 255,
  10268. data[1] / 255,
  10269. data[2] / 255
  10270. ];
  10271. } else {
  10272. color = [0, 0, 0];
  10273. }
  10274. }
  10275. components = color.slice();
  10276. }
  10277. return [type, components];
  10278. }
  10279. var hsbIndices = [
  10280. [0, 3, 1],
  10281. [2, 0, 1],
  10282. [1, 0, 3],
  10283. [1, 2, 0],
  10284. [3, 1, 0],
  10285. [0, 1, 2]
  10286. ];
  10287. var converters = {
  10288. 'rgb-hsb': function(r, g, b) {
  10289. var max = Math.max(r, g, b),
  10290. min = Math.min(r, g, b),
  10291. delta = max - min,
  10292. h = delta === 0 ? 0
  10293. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10294. : max == g ? (b - r) / delta + 2
  10295. : (r - g) / delta + 4) * 60;
  10296. return [h, max === 0 ? 0 : delta / max, max];
  10297. },
  10298. 'hsb-rgb': function(h, s, b) {
  10299. h = (((h / 60) % 6) + 6) % 6;
  10300. var i = Math.floor(h),
  10301. f = h - i,
  10302. i = hsbIndices[i],
  10303. v = [
  10304. b,
  10305. b * (1 - s),
  10306. b * (1 - s * f),
  10307. b * (1 - s * (1 - f))
  10308. ];
  10309. return [v[i[0]], v[i[1]], v[i[2]]];
  10310. },
  10311. 'rgb-hsl': function(r, g, b) {
  10312. var max = Math.max(r, g, b),
  10313. min = Math.min(r, g, b),
  10314. delta = max - min,
  10315. achromatic = delta === 0,
  10316. h = achromatic ? 0
  10317. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10318. : max == g ? (b - r) / delta + 2
  10319. : (r - g) / delta + 4) * 60,
  10320. l = (max + min) / 2,
  10321. s = achromatic ? 0 : l < 0.5
  10322. ? delta / (max + min)
  10323. : delta / (2 - max - min);
  10324. return [h, s, l];
  10325. },
  10326. 'hsl-rgb': function(h, s, l) {
  10327. h = (((h / 360) % 1) + 1) % 1;
  10328. if (s === 0)
  10329. return [l, l, l];
  10330. var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
  10331. t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
  10332. t1 = 2 * l - t2,
  10333. c = [];
  10334. for (var i = 0; i < 3; i++) {
  10335. var t3 = t3s[i];
  10336. if (t3 < 0) t3 += 1;
  10337. if (t3 > 1) t3 -= 1;
  10338. c[i] = 6 * t3 < 1
  10339. ? t1 + (t2 - t1) * 6 * t3
  10340. : 2 * t3 < 1
  10341. ? t2
  10342. : 3 * t3 < 2
  10343. ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
  10344. : t1;
  10345. }
  10346. return c;
  10347. },
  10348. 'rgb-gray': function(r, g, b) {
  10349. return [r * 0.2989 + g * 0.587 + b * 0.114];
  10350. },
  10351. 'gray-rgb': function(g) {
  10352. return [g, g, g];
  10353. },
  10354. 'gray-hsb': function(g) {
  10355. return [0, 0, g];
  10356. },
  10357. 'gray-hsl': function(g) {
  10358. return [0, 0, g];
  10359. },
  10360. 'gradient-rgb': function() {
  10361. return [];
  10362. },
  10363. 'rgb-gradient': function() {
  10364. return [];
  10365. }
  10366. };
  10367. return Base.each(types, function(properties, type) {
  10368. componentParsers[type] = [];
  10369. Base.each(properties, function(name, index) {
  10370. var part = Base.capitalize(name),
  10371. hasOverlap = /^(hue|saturation)$/.test(name),
  10372. parser = componentParsers[type][index] = type === 'gradient'
  10373. ? name === 'gradient'
  10374. ? function(value) {
  10375. var current = this._components[0];
  10376. value = Gradient.read(
  10377. Array.isArray(value)
  10378. ? value
  10379. : arguments, 0, { readNull: true }
  10380. );
  10381. if (current !== value) {
  10382. if (current)
  10383. current._removeOwner(this);
  10384. if (value)
  10385. value._addOwner(this);
  10386. }
  10387. return value;
  10388. }
  10389. : function() {
  10390. return Point.read(arguments, 0, {
  10391. readNull: name === 'highlight',
  10392. clone: true
  10393. });
  10394. }
  10395. : function(value) {
  10396. return value == null || isNaN(value) ? 0 : +value;
  10397. };
  10398. this['get' + part] = function() {
  10399. return this._type === type
  10400. || hasOverlap && /^hs[bl]$/.test(this._type)
  10401. ? this._components[index]
  10402. : this._convert(type)[index];
  10403. };
  10404. this['set' + part] = function(value) {
  10405. if (this._type !== type
  10406. && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
  10407. this._components = this._convert(type);
  10408. this._properties = types[type];
  10409. this._type = type;
  10410. }
  10411. this._components[index] = parser.call(this, value);
  10412. this._changed();
  10413. };
  10414. }, this);
  10415. }, {
  10416. _class: 'Color',
  10417. _readIndex: true,
  10418. initialize: function Color(arg) {
  10419. var args = arguments,
  10420. reading = this.__read,
  10421. read = 0,
  10422. type,
  10423. components,
  10424. alpha,
  10425. values;
  10426. if (Array.isArray(arg)) {
  10427. args = arg;
  10428. arg = args[0];
  10429. }
  10430. var argType = arg != null && typeof arg;
  10431. if (argType === 'string' && arg in types) {
  10432. type = arg;
  10433. arg = args[1];
  10434. if (Array.isArray(arg)) {
  10435. components = arg;
  10436. alpha = args[2];
  10437. } else {
  10438. if (reading)
  10439. read = 1;
  10440. args = Base.slice(args, 1);
  10441. argType = typeof arg;
  10442. }
  10443. }
  10444. if (!components) {
  10445. values = argType === 'number'
  10446. ? args
  10447. : argType === 'object' && arg.length != null
  10448. ? arg
  10449. : null;
  10450. if (values) {
  10451. if (!type)
  10452. type = values.length >= 3
  10453. ? 'rgb'
  10454. : 'gray';
  10455. var length = types[type].length;
  10456. alpha = values[length];
  10457. if (reading) {
  10458. read += values === arguments
  10459. ? length + (alpha != null ? 1 : 0)
  10460. : 1;
  10461. }
  10462. if (values.length > length)
  10463. values = Base.slice(values, 0, length);
  10464. } else if (argType === 'string') {
  10465. var converted = fromCSS(arg);
  10466. type = converted[0];
  10467. components = converted[1];
  10468. if (components.length === 4) {
  10469. alpha = components[3];
  10470. components.length--;
  10471. }
  10472. } else if (argType === 'object') {
  10473. if (arg.constructor === Color) {
  10474. type = arg._type;
  10475. components = arg._components.slice();
  10476. alpha = arg._alpha;
  10477. if (type === 'gradient') {
  10478. for (var i = 1, l = components.length; i < l; i++) {
  10479. var point = components[i];
  10480. if (point)
  10481. components[i] = point.clone();
  10482. }
  10483. }
  10484. } else if (arg.constructor === Gradient) {
  10485. type = 'gradient';
  10486. values = args;
  10487. } else {
  10488. type = 'hue' in arg
  10489. ? 'lightness' in arg
  10490. ? 'hsl'
  10491. : 'hsb'
  10492. : 'gradient' in arg || 'stops' in arg
  10493. || 'radial' in arg
  10494. ? 'gradient'
  10495. : 'gray' in arg
  10496. ? 'gray'
  10497. : 'rgb';
  10498. var properties = types[type],
  10499. parsers = componentParsers[type];
  10500. this._components = components = [];
  10501. for (var i = 0, l = properties.length; i < l; i++) {
  10502. var value = arg[properties[i]];
  10503. if (value == null && !i && type === 'gradient'
  10504. && 'stops' in arg) {
  10505. value = {
  10506. stops: arg.stops,
  10507. radial: arg.radial
  10508. };
  10509. }
  10510. value = parsers[i].call(this, value);
  10511. if (value != null)
  10512. components[i] = value;
  10513. }
  10514. alpha = arg.alpha;
  10515. }
  10516. }
  10517. if (reading && type)
  10518. read = 1;
  10519. }
  10520. this._type = type || 'rgb';
  10521. if (!components) {
  10522. this._components = components = [];
  10523. var parsers = componentParsers[this._type];
  10524. for (var i = 0, l = parsers.length; i < l; i++) {
  10525. var value = parsers[i].call(this, values && values[i]);
  10526. if (value != null)
  10527. components[i] = value;
  10528. }
  10529. }
  10530. this._components = components;
  10531. this._properties = types[this._type];
  10532. this._alpha = alpha;
  10533. if (reading)
  10534. this.__read = read;
  10535. return this;
  10536. },
  10537. set: '#initialize',
  10538. _serialize: function(options, dictionary) {
  10539. var components = this.getComponents();
  10540. return Base.serialize(
  10541. /^(gray|rgb)$/.test(this._type)
  10542. ? components
  10543. : [this._type].concat(components),
  10544. options, true, dictionary);
  10545. },
  10546. _changed: function() {
  10547. this._canvasStyle = null;
  10548. if (this._owner)
  10549. this._owner._changed(129);
  10550. },
  10551. _convert: function(type) {
  10552. var converter;
  10553. return this._type === type
  10554. ? this._components.slice()
  10555. : (converter = converters[this._type + '-' + type])
  10556. ? converter.apply(this, this._components)
  10557. : converters['rgb-' + type].apply(this,
  10558. converters[this._type + '-rgb'].apply(this,
  10559. this._components));
  10560. },
  10561. convert: function(type) {
  10562. return new Color(type, this._convert(type), this._alpha);
  10563. },
  10564. getType: function() {
  10565. return this._type;
  10566. },
  10567. setType: function(type) {
  10568. this._components = this._convert(type);
  10569. this._properties = types[type];
  10570. this._type = type;
  10571. },
  10572. getComponents: function() {
  10573. var components = this._components.slice();
  10574. if (this._alpha != null)
  10575. components.push(this._alpha);
  10576. return components;
  10577. },
  10578. getAlpha: function() {
  10579. return this._alpha != null ? this._alpha : 1;
  10580. },
  10581. setAlpha: function(alpha) {
  10582. this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
  10583. this._changed();
  10584. },
  10585. hasAlpha: function() {
  10586. return this._alpha != null;
  10587. },
  10588. equals: function(color) {
  10589. var col = Base.isPlainValue(color, true)
  10590. ? Color.read(arguments)
  10591. : color;
  10592. return col === this || col && this._class === col._class
  10593. && this._type === col._type
  10594. && this.getAlpha() === col.getAlpha()
  10595. && Base.equals(this._components, col._components)
  10596. || false;
  10597. },
  10598. toString: function() {
  10599. var properties = this._properties,
  10600. parts = [],
  10601. isGradient = this._type === 'gradient',
  10602. f = Formatter.instance;
  10603. for (var i = 0, l = properties.length; i < l; i++) {
  10604. var value = this._components[i];
  10605. if (value != null)
  10606. parts.push(properties[i] + ': '
  10607. + (isGradient ? value : f.number(value)));
  10608. }
  10609. if (this._alpha != null)
  10610. parts.push('alpha: ' + f.number(this._alpha));
  10611. return '{ ' + parts.join(', ') + ' }';
  10612. },
  10613. toCSS: function(hex) {
  10614. var components = this._convert('rgb'),
  10615. alpha = hex || this._alpha == null ? 1 : this._alpha;
  10616. function convert(val) {
  10617. return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255);
  10618. }
  10619. components = [
  10620. convert(components[0]),
  10621. convert(components[1]),
  10622. convert(components[2])
  10623. ];
  10624. if (alpha < 1)
  10625. components.push(alpha < 0 ? 0 : alpha);
  10626. return hex
  10627. ? '#' + ((1 << 24) + (components[0] << 16)
  10628. + (components[1] << 8)
  10629. + components[2]).toString(16).slice(1)
  10630. : (components.length == 4 ? 'rgba(' : 'rgb(')
  10631. + components.join(',') + ')';
  10632. },
  10633. toCanvasStyle: function(ctx, matrix) {
  10634. if (this._canvasStyle)
  10635. return this._canvasStyle;
  10636. if (this._type !== 'gradient')
  10637. return this._canvasStyle = this.toCSS();
  10638. var components = this._components,
  10639. gradient = components[0],
  10640. stops = gradient._stops,
  10641. origin = components[1],
  10642. destination = components[2],
  10643. highlight = components[3],
  10644. inverse = matrix && matrix.inverted(),
  10645. canvasGradient;
  10646. if (inverse) {
  10647. origin = inverse._transformPoint(origin);
  10648. destination = inverse._transformPoint(destination);
  10649. if (highlight)
  10650. highlight = inverse._transformPoint(highlight);
  10651. }
  10652. if (gradient._radial) {
  10653. var radius = destination.getDistance(origin);
  10654. if (highlight) {
  10655. var vector = highlight.subtract(origin);
  10656. if (vector.getLength() > radius)
  10657. highlight = origin.add(vector.normalize(radius - 0.1));
  10658. }
  10659. var start = highlight || origin;
  10660. canvasGradient = ctx.createRadialGradient(start.x, start.y,
  10661. 0, origin.x, origin.y, radius);
  10662. } else {
  10663. canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
  10664. destination.x, destination.y);
  10665. }
  10666. for (var i = 0, l = stops.length; i < l; i++) {
  10667. var stop = stops[i],
  10668. offset = stop._offset;
  10669. canvasGradient.addColorStop(
  10670. offset == null ? i / (l - 1) : offset,
  10671. stop._color.toCanvasStyle());
  10672. }
  10673. return this._canvasStyle = canvasGradient;
  10674. },
  10675. transform: function(matrix) {
  10676. if (this._type === 'gradient') {
  10677. var components = this._components;
  10678. for (var i = 1, l = components.length; i < l; i++) {
  10679. var point = components[i];
  10680. matrix._transformPoint(point, point, true);
  10681. }
  10682. this._changed();
  10683. }
  10684. },
  10685. statics: {
  10686. _types: types,
  10687. random: function() {
  10688. var random = Math.random;
  10689. return new Color(random(), random(), random());
  10690. }
  10691. }
  10692. });
  10693. },
  10694. new function() {
  10695. var operators = {
  10696. add: function(a, b) {
  10697. return a + b;
  10698. },
  10699. subtract: function(a, b) {
  10700. return a - b;
  10701. },
  10702. multiply: function(a, b) {
  10703. return a * b;
  10704. },
  10705. divide: function(a, b) {
  10706. return a / b;
  10707. }
  10708. };
  10709. return Base.each(operators, function(operator, name) {
  10710. this[name] = function(color) {
  10711. color = Color.read(arguments);
  10712. var type = this._type,
  10713. components1 = this._components,
  10714. components2 = color._convert(type);
  10715. for (var i = 0, l = components1.length; i < l; i++)
  10716. components2[i] = operator(components1[i], components2[i]);
  10717. return new Color(type, components2,
  10718. this._alpha != null
  10719. ? operator(this._alpha, color.getAlpha())
  10720. : null);
  10721. };
  10722. }, {
  10723. });
  10724. });
  10725. var Gradient = Base.extend({
  10726. _class: 'Gradient',
  10727. initialize: function Gradient(stops, radial) {
  10728. this._id = UID.get();
  10729. if (stops && Base.isPlainObject(stops)) {
  10730. this.set(stops);
  10731. stops = radial = null;
  10732. }
  10733. if (this._stops == null) {
  10734. this.setStops(stops || ['white', 'black']);
  10735. }
  10736. if (this._radial == null) {
  10737. this.setRadial(typeof radial === 'string' && radial === 'radial'
  10738. || radial || false);
  10739. }
  10740. },
  10741. _serialize: function(options, dictionary) {
  10742. return dictionary.add(this, function() {
  10743. return Base.serialize([this._stops, this._radial],
  10744. options, true, dictionary);
  10745. });
  10746. },
  10747. _changed: function() {
  10748. for (var i = 0, l = this._owners && this._owners.length; i < l; i++) {
  10749. this._owners[i]._changed();
  10750. }
  10751. },
  10752. _addOwner: function(color) {
  10753. if (!this._owners)
  10754. this._owners = [];
  10755. this._owners.push(color);
  10756. },
  10757. _removeOwner: function(color) {
  10758. var index = this._owners ? this._owners.indexOf(color) : -1;
  10759. if (index != -1) {
  10760. this._owners.splice(index, 1);
  10761. if (!this._owners.length)
  10762. this._owners = undefined;
  10763. }
  10764. },
  10765. clone: function() {
  10766. var stops = [];
  10767. for (var i = 0, l = this._stops.length; i < l; i++) {
  10768. stops[i] = this._stops[i].clone();
  10769. }
  10770. return new Gradient(stops, this._radial);
  10771. },
  10772. getStops: function() {
  10773. return this._stops;
  10774. },
  10775. setStops: function(stops) {
  10776. if (stops.length < 2) {
  10777. throw new Error(
  10778. 'Gradient stop list needs to contain at least two stops.');
  10779. }
  10780. var _stops = this._stops;
  10781. if (_stops) {
  10782. for (var i = 0, l = _stops.length; i < l; i++)
  10783. _stops[i]._owner = undefined;
  10784. }
  10785. _stops = this._stops = GradientStop.readList(stops, 0, { clone: true });
  10786. for (var i = 0, l = _stops.length; i < l; i++)
  10787. _stops[i]._owner = this;
  10788. this._changed();
  10789. },
  10790. getRadial: function() {
  10791. return this._radial;
  10792. },
  10793. setRadial: function(radial) {
  10794. this._radial = radial;
  10795. this._changed();
  10796. },
  10797. equals: function(gradient) {
  10798. if (gradient === this)
  10799. return true;
  10800. if (gradient && this._class === gradient._class) {
  10801. var stops1 = this._stops,
  10802. stops2 = gradient._stops,
  10803. length = stops1.length;
  10804. if (length === stops2.length) {
  10805. for (var i = 0; i < length; i++) {
  10806. if (!stops1[i].equals(stops2[i]))
  10807. return false;
  10808. }
  10809. return true;
  10810. }
  10811. }
  10812. return false;
  10813. }
  10814. });
  10815. var GradientStop = Base.extend({
  10816. _class: 'GradientStop',
  10817. initialize: function GradientStop(arg0, arg1) {
  10818. var color = arg0,
  10819. offset = arg1;
  10820. if (typeof arg0 === 'object' && arg1 === undefined) {
  10821. if (Array.isArray(arg0) && typeof arg0[0] !== 'number') {
  10822. color = arg0[0];
  10823. offset = arg0[1];
  10824. } else if ('color' in arg0 || 'offset' in arg0
  10825. || 'rampPoint' in arg0) {
  10826. color = arg0.color;
  10827. offset = arg0.offset || arg0.rampPoint || 0;
  10828. }
  10829. }
  10830. this.setColor(color);
  10831. this.setOffset(offset);
  10832. },
  10833. clone: function() {
  10834. return new GradientStop(this._color.clone(), this._offset);
  10835. },
  10836. _serialize: function(options, dictionary) {
  10837. var color = this._color,
  10838. offset = this._offset;
  10839. return Base.serialize(offset == null ? [color] : [color, offset],
  10840. options, true, dictionary);
  10841. },
  10842. _changed: function() {
  10843. if (this._owner)
  10844. this._owner._changed(129);
  10845. },
  10846. getOffset: function() {
  10847. return this._offset;
  10848. },
  10849. setOffset: function(offset) {
  10850. this._offset = offset;
  10851. this._changed();
  10852. },
  10853. getRampPoint: '#getOffset',
  10854. setRampPoint: '#setOffset',
  10855. getColor: function() {
  10856. return this._color;
  10857. },
  10858. setColor: function() {
  10859. var color = Color.read(arguments, 0, { clone: true });
  10860. if (color)
  10861. color._owner = this;
  10862. this._color = color;
  10863. this._changed();
  10864. },
  10865. equals: function(stop) {
  10866. return stop === this || stop && this._class === stop._class
  10867. && this._color.equals(stop._color)
  10868. && this._offset == stop._offset
  10869. || false;
  10870. }
  10871. });
  10872. var Style = Base.extend(new function() {
  10873. var itemDefaults = {
  10874. fillColor: null,
  10875. fillRule: 'nonzero',
  10876. strokeColor: null,
  10877. strokeWidth: 1,
  10878. strokeCap: 'butt',
  10879. strokeJoin: 'miter',
  10880. strokeScaling: true,
  10881. miterLimit: 10,
  10882. dashOffset: 0,
  10883. dashArray: [],
  10884. shadowColor: null,
  10885. shadowBlur: 0,
  10886. shadowOffset: new Point(),
  10887. selectedColor: null
  10888. },
  10889. groupDefaults = Base.set({}, itemDefaults, {
  10890. fontFamily: 'sans-serif',
  10891. fontWeight: 'normal',
  10892. fontSize: 12,
  10893. leading: null,
  10894. justification: 'left'
  10895. }),
  10896. textDefaults = Base.set({}, groupDefaults, {
  10897. fillColor: new Color()
  10898. }),
  10899. flags = {
  10900. strokeWidth: 193,
  10901. strokeCap: 193,
  10902. strokeJoin: 193,
  10903. strokeScaling: 201,
  10904. miterLimit: 193,
  10905. fontFamily: 9,
  10906. fontWeight: 9,
  10907. fontSize: 9,
  10908. font: 9,
  10909. leading: 9,
  10910. justification: 9
  10911. },
  10912. item = {
  10913. beans: true
  10914. },
  10915. fields = {
  10916. _class: 'Style',
  10917. beans: true,
  10918. initialize: function Style(style, _owner, _project) {
  10919. this._values = {};
  10920. this._owner = _owner;
  10921. this._project = _owner && _owner._project || _project
  10922. || paper.project;
  10923. this._defaults = !_owner || _owner instanceof Group ? groupDefaults
  10924. : _owner instanceof TextItem ? textDefaults
  10925. : itemDefaults;
  10926. if (style)
  10927. this.set(style);
  10928. }
  10929. };
  10930. Base.each(groupDefaults, function(value, key) {
  10931. var isColor = /Color$/.test(key),
  10932. isPoint = key === 'shadowOffset',
  10933. part = Base.capitalize(key),
  10934. flag = flags[key],
  10935. set = 'set' + part,
  10936. get = 'get' + part;
  10937. fields[set] = function(value) {
  10938. var owner = this._owner,
  10939. children = owner && owner._children,
  10940. applyToChildren = children && children.length > 0
  10941. && !(owner instanceof CompoundPath);
  10942. if (applyToChildren) {
  10943. for (var i = 0, l = children.length; i < l; i++)
  10944. children[i]._style[set](value);
  10945. }
  10946. if ((key === 'selectedColor' || !applyToChildren)
  10947. && key in this._defaults) {
  10948. var old = this._values[key];
  10949. if (old !== value) {
  10950. if (isColor) {
  10951. if (old && old._owner !== undefined) {
  10952. old._owner = undefined;
  10953. old._canvasStyle = null;
  10954. }
  10955. if (value && value.constructor === Color) {
  10956. if (value._owner)
  10957. value = value.clone();
  10958. value._owner = owner;
  10959. }
  10960. }
  10961. this._values[key] = value;
  10962. if (owner)
  10963. owner._changed(flag || 129);
  10964. }
  10965. }
  10966. };
  10967. fields[get] = function(_dontMerge) {
  10968. var owner = this._owner,
  10969. children = owner && owner._children,
  10970. value;
  10971. if (key in this._defaults && (!children || !children.length
  10972. || _dontMerge || owner instanceof CompoundPath)) {
  10973. var value = this._values[key];
  10974. if (value === undefined) {
  10975. value = this._defaults[key];
  10976. if (value && value.clone)
  10977. value = value.clone();
  10978. } else {
  10979. var ctor = isColor ? Color : isPoint ? Point : null;
  10980. if (ctor && !(value && value.constructor === ctor)) {
  10981. this._values[key] = value = ctor.read([value], 0,
  10982. { readNull: true, clone: true });
  10983. if (value && isColor)
  10984. value._owner = owner;
  10985. }
  10986. }
  10987. } else if (children) {
  10988. for (var i = 0, l = children.length; i < l; i++) {
  10989. var childValue = children[i]._style[get]();
  10990. if (!i) {
  10991. value = childValue;
  10992. } else if (!Base.equals(value, childValue)) {
  10993. return undefined;
  10994. }
  10995. }
  10996. }
  10997. return value;
  10998. };
  10999. item[get] = function(_dontMerge) {
  11000. return this._style[get](_dontMerge);
  11001. };
  11002. item[set] = function(value) {
  11003. this._style[set](value);
  11004. };
  11005. });
  11006. Base.each({
  11007. Font: 'FontFamily',
  11008. WindingRule: 'FillRule'
  11009. }, function(value, key) {
  11010. var get = 'get' + key,
  11011. set = 'set' + key;
  11012. fields[get] = item[get] = '#get' + value;
  11013. fields[set] = item[set] = '#set' + value;
  11014. });
  11015. Item.inject(item);
  11016. return fields;
  11017. }, {
  11018. set: function(style) {
  11019. var isStyle = style instanceof Style,
  11020. values = isStyle ? style._values : style;
  11021. if (values) {
  11022. for (var key in values) {
  11023. if (key in this._defaults) {
  11024. var value = values[key];
  11025. this[key] = value && isStyle && value.clone
  11026. ? value.clone() : value;
  11027. }
  11028. }
  11029. }
  11030. },
  11031. equals: function(style) {
  11032. function compare(style1, style2, secondary) {
  11033. var values1 = style1._values,
  11034. values2 = style2._values,
  11035. defaults2 = style2._defaults;
  11036. for (var key in values1) {
  11037. var value1 = values1[key],
  11038. value2 = values2[key];
  11039. if (!(secondary && key in values2) && !Base.equals(value1,
  11040. value2 === undefined ? defaults2[key] : value2))
  11041. return false;
  11042. }
  11043. return true;
  11044. }
  11045. return style === this || style && this._class === style._class
  11046. && compare(this, style)
  11047. && compare(style, this, true)
  11048. || false;
  11049. },
  11050. _dispose: function() {
  11051. var color;
  11052. color = this.getFillColor();
  11053. if (color) color._canvasStyle = null;
  11054. color = this.getStrokeColor();
  11055. if (color) color._canvasStyle = null;
  11056. color = this.getShadowColor();
  11057. if (color) color._canvasStyle = null;
  11058. },
  11059. hasFill: function() {
  11060. var color = this.getFillColor();
  11061. return !!color && color.alpha > 0;
  11062. },
  11063. hasStroke: function() {
  11064. var color = this.getStrokeColor();
  11065. return !!color && color.alpha > 0 && this.getStrokeWidth() > 0;
  11066. },
  11067. hasShadow: function() {
  11068. var color = this.getShadowColor();
  11069. return !!color && color.alpha > 0 && (this.getShadowBlur() > 0
  11070. || !this.getShadowOffset().isZero());
  11071. },
  11072. getView: function() {
  11073. return this._project._view;
  11074. },
  11075. getFontStyle: function() {
  11076. var fontSize = this.getFontSize();
  11077. return this.getFontWeight()
  11078. + ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ')
  11079. + this.getFontFamily();
  11080. },
  11081. getFont: '#getFontFamily',
  11082. setFont: '#setFontFamily',
  11083. getLeading: function getLeading() {
  11084. var leading = getLeading.base.call(this),
  11085. fontSize = this.getFontSize();
  11086. if (/pt|em|%|px/.test(fontSize))
  11087. fontSize = this.getView().getPixelSize(fontSize);
  11088. return leading != null ? leading : fontSize * 1.2;
  11089. }
  11090. });
  11091. var DomElement = new function() {
  11092. function handlePrefix(el, name, set, value) {
  11093. var prefixes = ['', 'webkit', 'moz', 'Moz', 'ms', 'o'],
  11094. suffix = name[0].toUpperCase() + name.substring(1);
  11095. for (var i = 0; i < 6; i++) {
  11096. var prefix = prefixes[i],
  11097. key = prefix ? prefix + suffix : name;
  11098. if (key in el) {
  11099. if (set) {
  11100. el[key] = value;
  11101. } else {
  11102. return el[key];
  11103. }
  11104. break;
  11105. }
  11106. }
  11107. }
  11108. return {
  11109. getStyles: function(el) {
  11110. var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
  11111. view = doc && doc.defaultView;
  11112. return view && view.getComputedStyle(el, '');
  11113. },
  11114. getBounds: function(el, viewport) {
  11115. var doc = el.ownerDocument,
  11116. body = doc.body,
  11117. html = doc.documentElement,
  11118. rect;
  11119. try {
  11120. rect = el.getBoundingClientRect();
  11121. } catch (e) {
  11122. rect = { left: 0, top: 0, width: 0, height: 0 };
  11123. }
  11124. var x = rect.left - (html.clientLeft || body.clientLeft || 0),
  11125. y = rect.top - (html.clientTop || body.clientTop || 0);
  11126. if (!viewport) {
  11127. var view = doc.defaultView;
  11128. x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
  11129. y += view.pageYOffset || html.scrollTop || body.scrollTop;
  11130. }
  11131. return new Rectangle(x, y, rect.width, rect.height);
  11132. },
  11133. getViewportBounds: function(el) {
  11134. var doc = el.ownerDocument,
  11135. view = doc.defaultView,
  11136. html = doc.documentElement;
  11137. return new Rectangle(0, 0,
  11138. view.innerWidth || html.clientWidth,
  11139. view.innerHeight || html.clientHeight
  11140. );
  11141. },
  11142. getOffset: function(el, viewport) {
  11143. return DomElement.getBounds(el, viewport).getPoint();
  11144. },
  11145. getSize: function(el) {
  11146. return DomElement.getBounds(el, true).getSize();
  11147. },
  11148. isInvisible: function(el) {
  11149. return DomElement.getSize(el).equals(new Size(0, 0));
  11150. },
  11151. isInView: function(el) {
  11152. return !DomElement.isInvisible(el)
  11153. && DomElement.getViewportBounds(el).intersects(
  11154. DomElement.getBounds(el, true));
  11155. },
  11156. isInserted: function(el) {
  11157. return document.body.contains(el);
  11158. },
  11159. getPrefixed: function(el, name) {
  11160. return el && handlePrefix(el, name);
  11161. },
  11162. setPrefixed: function(el, name, value) {
  11163. if (typeof name === 'object') {
  11164. for (var key in name)
  11165. handlePrefix(el, key, true, name[key]);
  11166. } else {
  11167. handlePrefix(el, name, true, value);
  11168. }
  11169. }
  11170. };
  11171. };
  11172. var DomEvent = {
  11173. add: function(el, events) {
  11174. if (el) {
  11175. for (var type in events) {
  11176. var func = events[type],
  11177. parts = type.split(/[\s,]+/g);
  11178. for (var i = 0, l = parts.length; i < l; i++) {
  11179. var name = parts[i];
  11180. var options = (
  11181. el === document
  11182. && (name === 'touchstart' || name === 'touchmove')
  11183. ) ? { passive: false } : false;
  11184. el.addEventListener(name, func, options);
  11185. }
  11186. }
  11187. }
  11188. },
  11189. remove: function(el, events) {
  11190. if (el) {
  11191. for (var type in events) {
  11192. var func = events[type],
  11193. parts = type.split(/[\s,]+/g);
  11194. for (var i = 0, l = parts.length; i < l; i++)
  11195. el.removeEventListener(parts[i], func, false);
  11196. }
  11197. }
  11198. },
  11199. getPoint: function(event) {
  11200. var pos = event.targetTouches
  11201. ? event.targetTouches.length
  11202. ? event.targetTouches[0]
  11203. : event.changedTouches[0]
  11204. : event;
  11205. return new Point(
  11206. pos.pageX || pos.clientX + document.documentElement.scrollLeft,
  11207. pos.pageY || pos.clientY + document.documentElement.scrollTop
  11208. );
  11209. },
  11210. getTarget: function(event) {
  11211. return event.target || event.srcElement;
  11212. },
  11213. getRelatedTarget: function(event) {
  11214. return event.relatedTarget || event.toElement;
  11215. },
  11216. getOffset: function(event, target) {
  11217. return DomEvent.getPoint(event).subtract(DomElement.getOffset(
  11218. target || DomEvent.getTarget(event)));
  11219. }
  11220. };
  11221. DomEvent.requestAnimationFrame = new function() {
  11222. var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'),
  11223. requested = false,
  11224. callbacks = [],
  11225. timer;
  11226. function handleCallbacks() {
  11227. var functions = callbacks;
  11228. callbacks = [];
  11229. for (var i = 0, l = functions.length; i < l; i++)
  11230. functions[i]();
  11231. requested = nativeRequest && callbacks.length;
  11232. if (requested)
  11233. nativeRequest(handleCallbacks);
  11234. }
  11235. return function(callback) {
  11236. callbacks.push(callback);
  11237. if (nativeRequest) {
  11238. if (!requested) {
  11239. nativeRequest(handleCallbacks);
  11240. requested = true;
  11241. }
  11242. } else if (!timer) {
  11243. timer = setInterval(handleCallbacks, 1000 / 60);
  11244. }
  11245. };
  11246. };
  11247. var View = Base.extend(Emitter, {
  11248. _class: 'View',
  11249. initialize: function View(project, element) {
  11250. function getSize(name) {
  11251. return element[name] || parseInt(element.getAttribute(name), 10);
  11252. }
  11253. function getCanvasSize() {
  11254. var size = DomElement.getSize(element);
  11255. return size.isNaN() || size.isZero()
  11256. ? new Size(getSize('width'), getSize('height'))
  11257. : size;
  11258. }
  11259. var size;
  11260. if (window && element) {
  11261. this._id = element.getAttribute('id');
  11262. if (this._id == null)
  11263. element.setAttribute('id', this._id = 'view-' + View._id++);
  11264. DomEvent.add(element, this._viewEvents);
  11265. var none = 'none';
  11266. DomElement.setPrefixed(element.style, {
  11267. userDrag: none,
  11268. userSelect: none,
  11269. touchCallout: none,
  11270. contentZooming: none,
  11271. tapHighlightColor: 'rgba(0,0,0,0)'
  11272. });
  11273. if (PaperScope.hasAttribute(element, 'resize')) {
  11274. var that = this;
  11275. DomEvent.add(window, this._windowEvents = {
  11276. resize: function() {
  11277. that.setViewSize(getCanvasSize());
  11278. }
  11279. });
  11280. }
  11281. size = getCanvasSize();
  11282. if (PaperScope.hasAttribute(element, 'stats')
  11283. && typeof Stats !== 'undefined') {
  11284. this._stats = new Stats();
  11285. var stats = this._stats.domElement,
  11286. style = stats.style,
  11287. offset = DomElement.getOffset(element);
  11288. style.position = 'absolute';
  11289. style.left = offset.x + 'px';
  11290. style.top = offset.y + 'px';
  11291. document.body.appendChild(stats);
  11292. }
  11293. } else {
  11294. size = new Size(element);
  11295. element = null;
  11296. }
  11297. this._project = project;
  11298. this._scope = project._scope;
  11299. this._element = element;
  11300. if (!this._pixelRatio)
  11301. this._pixelRatio = window && window.devicePixelRatio || 1;
  11302. this._setElementSize(size.width, size.height);
  11303. this._viewSize = size;
  11304. View._views.push(this);
  11305. View._viewsById[this._id] = this;
  11306. (this._matrix = new Matrix())._owner = this;
  11307. if (!View._focused)
  11308. View._focused = this;
  11309. this._frameItems = {};
  11310. this._frameItemCount = 0;
  11311. this._itemEvents = { native: {}, virtual: {} };
  11312. this._autoUpdate = !paper.agent.node;
  11313. this._needsUpdate = false;
  11314. },
  11315. remove: function() {
  11316. if (!this._project)
  11317. return false;
  11318. if (View._focused === this)
  11319. View._focused = null;
  11320. View._views.splice(View._views.indexOf(this), 1);
  11321. delete View._viewsById[this._id];
  11322. var project = this._project;
  11323. if (project._view === this)
  11324. project._view = null;
  11325. DomEvent.remove(this._element, this._viewEvents);
  11326. DomEvent.remove(window, this._windowEvents);
  11327. this._element = this._project = null;
  11328. this.off('frame');
  11329. this._animate = false;
  11330. this._frameItems = {};
  11331. return true;
  11332. },
  11333. _events: Base.each(
  11334. Item._itemHandlers.concat(['onResize', 'onKeyDown', 'onKeyUp']),
  11335. function(name) {
  11336. this[name] = {};
  11337. }, {
  11338. onFrame: {
  11339. install: function() {
  11340. this.play();
  11341. },
  11342. uninstall: function() {
  11343. this.pause();
  11344. }
  11345. }
  11346. }
  11347. ),
  11348. _animate: false,
  11349. _time: 0,
  11350. _count: 0,
  11351. getAutoUpdate: function() {
  11352. return this._autoUpdate;
  11353. },
  11354. setAutoUpdate: function(autoUpdate) {
  11355. this._autoUpdate = autoUpdate;
  11356. if (autoUpdate)
  11357. this.requestUpdate();
  11358. },
  11359. update: function() {
  11360. },
  11361. draw: function() {
  11362. this.update();
  11363. },
  11364. requestUpdate: function() {
  11365. if (!this._requested) {
  11366. var that = this;
  11367. DomEvent.requestAnimationFrame(function() {
  11368. that._requested = false;
  11369. if (that._animate) {
  11370. that.requestUpdate();
  11371. var element = that._element;
  11372. if ((!DomElement.getPrefixed(document, 'hidden')
  11373. || PaperScope.getAttribute(element, 'keepalive')
  11374. === 'true') && DomElement.isInView(element)) {
  11375. that._handleFrame();
  11376. }
  11377. }
  11378. if (that._autoUpdate)
  11379. that.update();
  11380. });
  11381. this._requested = true;
  11382. }
  11383. },
  11384. play: function() {
  11385. this._animate = true;
  11386. this.requestUpdate();
  11387. },
  11388. pause: function() {
  11389. this._animate = false;
  11390. },
  11391. _handleFrame: function() {
  11392. paper = this._scope;
  11393. var now = Date.now() / 1000,
  11394. delta = this._last ? now - this._last : 0;
  11395. this._last = now;
  11396. this.emit('frame', new Base({
  11397. delta: delta,
  11398. time: this._time += delta,
  11399. count: this._count++
  11400. }));
  11401. if (this._stats)
  11402. this._stats.update();
  11403. },
  11404. _animateItem: function(item, animate) {
  11405. var items = this._frameItems;
  11406. if (animate) {
  11407. items[item._id] = {
  11408. item: item,
  11409. time: 0,
  11410. count: 0
  11411. };
  11412. if (++this._frameItemCount === 1)
  11413. this.on('frame', this._handleFrameItems);
  11414. } else {
  11415. delete items[item._id];
  11416. if (--this._frameItemCount === 0) {
  11417. this.off('frame', this._handleFrameItems);
  11418. }
  11419. }
  11420. },
  11421. _handleFrameItems: function(event) {
  11422. for (var i in this._frameItems) {
  11423. var entry = this._frameItems[i];
  11424. entry.item.emit('frame', new Base(event, {
  11425. time: entry.time += event.delta,
  11426. count: entry.count++
  11427. }));
  11428. }
  11429. },
  11430. _changed: function() {
  11431. this._project._changed(4097);
  11432. this._bounds = this._decomposed = undefined;
  11433. },
  11434. getElement: function() {
  11435. return this._element;
  11436. },
  11437. getPixelRatio: function() {
  11438. return this._pixelRatio;
  11439. },
  11440. getResolution: function() {
  11441. return this._pixelRatio * 72;
  11442. },
  11443. getViewSize: function() {
  11444. var size = this._viewSize;
  11445. return new LinkedSize(size.width, size.height, this, 'setViewSize');
  11446. },
  11447. setViewSize: function() {
  11448. var size = Size.read(arguments),
  11449. delta = size.subtract(this._viewSize);
  11450. if (delta.isZero())
  11451. return;
  11452. this._setElementSize(size.width, size.height);
  11453. this._viewSize.set(size);
  11454. this._changed();
  11455. this.emit('resize', { size: size, delta: delta });
  11456. if (this._autoUpdate) {
  11457. this.update();
  11458. }
  11459. },
  11460. _setElementSize: function(width, height) {
  11461. var element = this._element;
  11462. if (element) {
  11463. if (element.width !== width)
  11464. element.width = width;
  11465. if (element.height !== height)
  11466. element.height = height;
  11467. }
  11468. },
  11469. getBounds: function() {
  11470. if (!this._bounds)
  11471. this._bounds = this._matrix.inverted()._transformBounds(
  11472. new Rectangle(new Point(), this._viewSize));
  11473. return this._bounds;
  11474. },
  11475. getSize: function() {
  11476. return this.getBounds().getSize();
  11477. },
  11478. isVisible: function() {
  11479. return DomElement.isInView(this._element);
  11480. },
  11481. isInserted: function() {
  11482. return DomElement.isInserted(this._element);
  11483. },
  11484. getPixelSize: function(size) {
  11485. var element = this._element,
  11486. pixels;
  11487. if (element) {
  11488. var parent = element.parentNode,
  11489. temp = document.createElement('div');
  11490. temp.style.fontSize = size;
  11491. parent.appendChild(temp);
  11492. pixels = parseFloat(DomElement.getStyles(temp).fontSize);
  11493. parent.removeChild(temp);
  11494. } else {
  11495. pixels = parseFloat(pixels);
  11496. }
  11497. return pixels;
  11498. },
  11499. getTextWidth: function(font, lines) {
  11500. return 0;
  11501. }
  11502. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  11503. var rotate = key === 'rotate';
  11504. this[key] = function() {
  11505. var value = (rotate ? Base : Point).read(arguments),
  11506. center = Point.read(arguments, 0, { readNull: true });
  11507. return this.transform(new Matrix()[key](value,
  11508. center || this.getCenter(true)));
  11509. };
  11510. }, {
  11511. _decompose: function() {
  11512. return this._decomposed || (this._decomposed = this._matrix.decompose());
  11513. },
  11514. translate: function() {
  11515. var mx = new Matrix();
  11516. return this.transform(mx.translate.apply(mx, arguments));
  11517. },
  11518. getCenter: function() {
  11519. return this.getBounds().getCenter();
  11520. },
  11521. setCenter: function() {
  11522. var center = Point.read(arguments);
  11523. this.translate(this.getCenter().subtract(center));
  11524. },
  11525. getZoom: function() {
  11526. var scaling = this._decompose().scaling;
  11527. return (scaling.x + scaling.y) / 2;
  11528. },
  11529. setZoom: function(zoom) {
  11530. this.transform(new Matrix().scale(zoom / this.getZoom(),
  11531. this.getCenter()));
  11532. },
  11533. getRotation: function() {
  11534. return this._decompose().rotation;
  11535. },
  11536. setRotation: function(rotation) {
  11537. var current = this.getRotation();
  11538. if (current != null && rotation != null) {
  11539. this.rotate(rotation - current);
  11540. }
  11541. },
  11542. getScaling: function() {
  11543. var scaling = this._decompose().scaling;
  11544. return new LinkedPoint(scaling.x, scaling.y, this, 'setScaling');
  11545. },
  11546. setScaling: function() {
  11547. var current = this.getScaling(),
  11548. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  11549. if (current && scaling) {
  11550. this.scale(scaling.x / current.x, scaling.y / current.y);
  11551. }
  11552. },
  11553. getMatrix: function() {
  11554. return this._matrix;
  11555. },
  11556. setMatrix: function() {
  11557. var matrix = this._matrix;
  11558. matrix.initialize.apply(matrix, arguments);
  11559. },
  11560. transform: function(matrix) {
  11561. this._matrix.append(matrix);
  11562. },
  11563. scrollBy: function() {
  11564. this.translate(Point.read(arguments).negate());
  11565. }
  11566. }), {
  11567. projectToView: function() {
  11568. return this._matrix._transformPoint(Point.read(arguments));
  11569. },
  11570. viewToProject: function() {
  11571. return this._matrix._inverseTransform(Point.read(arguments));
  11572. },
  11573. getEventPoint: function(event) {
  11574. return this.viewToProject(DomEvent.getOffset(event, this._element));
  11575. },
  11576. }, {
  11577. statics: {
  11578. _views: [],
  11579. _viewsById: {},
  11580. _id: 0,
  11581. create: function(project, element) {
  11582. if (document && typeof element === 'string')
  11583. element = document.getElementById(element);
  11584. var ctor = window ? CanvasView : View;
  11585. return new ctor(project, element);
  11586. }
  11587. }
  11588. },
  11589. new function() {
  11590. if (!window)
  11591. return;
  11592. var prevFocus,
  11593. tempFocus,
  11594. dragging = false,
  11595. mouseDown = false;
  11596. function getView(event) {
  11597. var target = DomEvent.getTarget(event);
  11598. return target.getAttribute && View._viewsById[
  11599. target.getAttribute('id')];
  11600. }
  11601. function updateFocus() {
  11602. var view = View._focused;
  11603. if (!view || !view.isVisible()) {
  11604. for (var i = 0, l = View._views.length; i < l; i++) {
  11605. if ((view = View._views[i]).isVisible()) {
  11606. View._focused = tempFocus = view;
  11607. break;
  11608. }
  11609. }
  11610. }
  11611. }
  11612. function handleMouseMove(view, event, point) {
  11613. view._handleMouseEvent('mousemove', event, point);
  11614. }
  11615. var navigator = window.navigator,
  11616. mousedown, mousemove, mouseup;
  11617. if (navigator.pointerEnabled || navigator.msPointerEnabled) {
  11618. mousedown = 'pointerdown MSPointerDown';
  11619. mousemove = 'pointermove MSPointerMove';
  11620. mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel';
  11621. } else {
  11622. mousedown = 'touchstart';
  11623. mousemove = 'touchmove';
  11624. mouseup = 'touchend touchcancel';
  11625. if (!('ontouchstart' in window && navigator.userAgent.match(
  11626. /mobile|tablet|ip(ad|hone|od)|android|silk/i))) {
  11627. mousedown += ' mousedown';
  11628. mousemove += ' mousemove';
  11629. mouseup += ' mouseup';
  11630. }
  11631. }
  11632. var viewEvents = {},
  11633. docEvents = {
  11634. mouseout: function(event) {
  11635. var view = View._focused,
  11636. target = DomEvent.getRelatedTarget(event);
  11637. if (view && (!target || target.nodeName === 'HTML')) {
  11638. var offset = DomEvent.getOffset(event, view._element),
  11639. x = offset.x,
  11640. abs = Math.abs,
  11641. ax = abs(x),
  11642. max = 1 << 25,
  11643. diff = ax - max;
  11644. offset.x = abs(diff) < ax ? diff * (x < 0 ? -1 : 1) : x;
  11645. handleMouseMove(view, event, view.viewToProject(offset));
  11646. }
  11647. },
  11648. scroll: updateFocus
  11649. };
  11650. viewEvents[mousedown] = function(event) {
  11651. var view = View._focused = getView(event);
  11652. if (!dragging) {
  11653. dragging = true;
  11654. view._handleMouseEvent('mousedown', event);
  11655. }
  11656. };
  11657. docEvents[mousemove] = function(event) {
  11658. var view = View._focused;
  11659. if (!mouseDown) {
  11660. var target = getView(event);
  11661. if (target) {
  11662. if (view !== target) {
  11663. if (view)
  11664. handleMouseMove(view, event);
  11665. if (!prevFocus)
  11666. prevFocus = view;
  11667. view = View._focused = tempFocus = target;
  11668. }
  11669. } else if (tempFocus && tempFocus === view) {
  11670. if (prevFocus && !prevFocus.isInserted())
  11671. prevFocus = null;
  11672. view = View._focused = prevFocus;
  11673. prevFocus = null;
  11674. updateFocus();
  11675. }
  11676. }
  11677. if (view)
  11678. handleMouseMove(view, event);
  11679. };
  11680. docEvents[mousedown] = function() {
  11681. mouseDown = true;
  11682. };
  11683. docEvents[mouseup] = function(event) {
  11684. var view = View._focused;
  11685. if (view && dragging)
  11686. view._handleMouseEvent('mouseup', event);
  11687. mouseDown = dragging = false;
  11688. };
  11689. DomEvent.add(document, docEvents);
  11690. DomEvent.add(window, {
  11691. load: updateFocus
  11692. });
  11693. var called = false,
  11694. prevented = false,
  11695. fallbacks = {
  11696. doubleclick: 'click',
  11697. mousedrag: 'mousemove'
  11698. },
  11699. wasInView = false,
  11700. overView,
  11701. downPoint,
  11702. lastPoint,
  11703. downItem,
  11704. overItem,
  11705. dragItem,
  11706. clickItem,
  11707. clickTime,
  11708. dblClick;
  11709. function emitMouseEvent(obj, target, type, event, point, prevPoint,
  11710. stopItem) {
  11711. var stopped = false,
  11712. mouseEvent;
  11713. function emit(obj, type) {
  11714. if (obj.responds(type)) {
  11715. if (!mouseEvent) {
  11716. mouseEvent = new MouseEvent(type, event, point,
  11717. target || obj,
  11718. prevPoint ? point.subtract(prevPoint) : null);
  11719. }
  11720. if (obj.emit(type, mouseEvent)) {
  11721. called = true;
  11722. if (mouseEvent.prevented)
  11723. prevented = true;
  11724. if (mouseEvent.stopped)
  11725. return stopped = true;
  11726. }
  11727. } else {
  11728. var fallback = fallbacks[type];
  11729. if (fallback)
  11730. return emit(obj, fallback);
  11731. }
  11732. }
  11733. while (obj && obj !== stopItem) {
  11734. if (emit(obj, type))
  11735. break;
  11736. obj = obj._parent;
  11737. }
  11738. return stopped;
  11739. }
  11740. function emitMouseEvents(view, hitItem, type, event, point, prevPoint) {
  11741. view._project.removeOn(type);
  11742. prevented = called = false;
  11743. return (dragItem && emitMouseEvent(dragItem, null, type, event,
  11744. point, prevPoint)
  11745. || hitItem && hitItem !== dragItem
  11746. && !hitItem.isDescendant(dragItem)
  11747. && emitMouseEvent(hitItem, null, type === 'mousedrag' ?
  11748. 'mousemove' : type, event, point, prevPoint, dragItem)
  11749. || emitMouseEvent(view, dragItem || hitItem || view, type, event,
  11750. point, prevPoint));
  11751. }
  11752. var itemEventsMap = {
  11753. mousedown: {
  11754. mousedown: 1,
  11755. mousedrag: 1,
  11756. click: 1,
  11757. doubleclick: 1
  11758. },
  11759. mouseup: {
  11760. mouseup: 1,
  11761. mousedrag: 1,
  11762. click: 1,
  11763. doubleclick: 1
  11764. },
  11765. mousemove: {
  11766. mousedrag: 1,
  11767. mousemove: 1,
  11768. mouseenter: 1,
  11769. mouseleave: 1
  11770. }
  11771. };
  11772. return {
  11773. _viewEvents: viewEvents,
  11774. _handleMouseEvent: function(type, event, point) {
  11775. var itemEvents = this._itemEvents,
  11776. hitItems = itemEvents.native[type],
  11777. nativeMove = type === 'mousemove',
  11778. tool = this._scope.tool,
  11779. view = this;
  11780. function responds(type) {
  11781. return itemEvents.virtual[type] || view.responds(type)
  11782. || tool && tool.responds(type);
  11783. }
  11784. if (nativeMove && dragging && responds('mousedrag'))
  11785. type = 'mousedrag';
  11786. if (!point)
  11787. point = this.getEventPoint(event);
  11788. var inView = this.getBounds().contains(point),
  11789. hit = hitItems && inView && view._project.hitTest(point, {
  11790. tolerance: 0,
  11791. fill: true,
  11792. stroke: true
  11793. }),
  11794. hitItem = hit && hit.item || null,
  11795. handle = false,
  11796. mouse = {};
  11797. mouse[type.substr(5)] = true;
  11798. if (hitItems && hitItem !== overItem) {
  11799. if (overItem) {
  11800. emitMouseEvent(overItem, null, 'mouseleave', event, point);
  11801. }
  11802. if (hitItem) {
  11803. emitMouseEvent(hitItem, null, 'mouseenter', event, point);
  11804. }
  11805. overItem = hitItem;
  11806. }
  11807. if (wasInView ^ inView) {
  11808. emitMouseEvent(this, null, inView ? 'mouseenter' : 'mouseleave',
  11809. event, point);
  11810. overView = inView ? this : null;
  11811. handle = true;
  11812. }
  11813. if ((inView || mouse.drag) && !point.equals(lastPoint)) {
  11814. emitMouseEvents(this, hitItem, nativeMove ? type : 'mousemove',
  11815. event, point, lastPoint);
  11816. handle = true;
  11817. }
  11818. wasInView = inView;
  11819. if (mouse.down && inView || mouse.up && downPoint) {
  11820. emitMouseEvents(this, hitItem, type, event, point, downPoint);
  11821. if (mouse.down) {
  11822. dblClick = hitItem === clickItem
  11823. && (Date.now() - clickTime < 300);
  11824. downItem = clickItem = hitItem;
  11825. if (!prevented && hitItem) {
  11826. var item = hitItem;
  11827. while (item && !item.responds('mousedrag'))
  11828. item = item._parent;
  11829. if (item)
  11830. dragItem = hitItem;
  11831. }
  11832. downPoint = point;
  11833. } else if (mouse.up) {
  11834. if (!prevented && hitItem === downItem) {
  11835. clickTime = Date.now();
  11836. emitMouseEvents(this, hitItem, dblClick ? 'doubleclick'
  11837. : 'click', event, point, downPoint);
  11838. dblClick = false;
  11839. }
  11840. downItem = dragItem = null;
  11841. }
  11842. wasInView = false;
  11843. handle = true;
  11844. }
  11845. lastPoint = point;
  11846. if (handle && tool) {
  11847. called = tool._handleMouseEvent(type, event, point, mouse)
  11848. || called;
  11849. }
  11850. if (
  11851. event.cancelable !== false
  11852. && (called && !mouse.move || mouse.down && responds('mouseup'))
  11853. ) {
  11854. event.preventDefault();
  11855. }
  11856. },
  11857. _handleKeyEvent: function(type, event, key, character) {
  11858. var scope = this._scope,
  11859. tool = scope.tool,
  11860. keyEvent;
  11861. function emit(obj) {
  11862. if (obj.responds(type)) {
  11863. paper = scope;
  11864. obj.emit(type, keyEvent = keyEvent
  11865. || new KeyEvent(type, event, key, character));
  11866. }
  11867. }
  11868. if (this.isVisible()) {
  11869. emit(this);
  11870. if (tool && tool.responds(type))
  11871. emit(tool);
  11872. }
  11873. },
  11874. _countItemEvent: function(type, sign) {
  11875. var itemEvents = this._itemEvents,
  11876. native = itemEvents.native,
  11877. virtual = itemEvents.virtual;
  11878. for (var key in itemEventsMap) {
  11879. native[key] = (native[key] || 0)
  11880. + (itemEventsMap[key][type] || 0) * sign;
  11881. }
  11882. virtual[type] = (virtual[type] || 0) + sign;
  11883. },
  11884. statics: {
  11885. updateFocus: updateFocus,
  11886. _resetState: function() {
  11887. dragging = mouseDown = called = wasInView = false;
  11888. prevFocus = tempFocus = overView = downPoint = lastPoint =
  11889. downItem = overItem = dragItem = clickItem = clickTime =
  11890. dblClick = null;
  11891. }
  11892. }
  11893. };
  11894. });
  11895. var CanvasView = View.extend({
  11896. _class: 'CanvasView',
  11897. initialize: function CanvasView(project, canvas) {
  11898. if (!(canvas instanceof window.HTMLCanvasElement)) {
  11899. var size = Size.read(arguments, 1);
  11900. if (size.isZero())
  11901. throw new Error(
  11902. 'Cannot create CanvasView with the provided argument: '
  11903. + Base.slice(arguments, 1));
  11904. canvas = CanvasProvider.getCanvas(size);
  11905. }
  11906. var ctx = this._context = canvas.getContext('2d');
  11907. ctx.save();
  11908. this._pixelRatio = 1;
  11909. if (!/^off|false$/.test(PaperScope.getAttribute(canvas, 'hidpi'))) {
  11910. var deviceRatio = window.devicePixelRatio || 1,
  11911. backingStoreRatio = DomElement.getPrefixed(ctx,
  11912. 'backingStorePixelRatio') || 1;
  11913. this._pixelRatio = deviceRatio / backingStoreRatio;
  11914. }
  11915. View.call(this, project, canvas);
  11916. this._needsUpdate = true;
  11917. },
  11918. remove: function remove() {
  11919. this._context.restore();
  11920. return remove.base.call(this);
  11921. },
  11922. _setElementSize: function _setElementSize(width, height) {
  11923. var pixelRatio = this._pixelRatio;
  11924. _setElementSize.base.call(this, width * pixelRatio, height * pixelRatio);
  11925. if (pixelRatio !== 1) {
  11926. var element = this._element,
  11927. ctx = this._context;
  11928. if (!PaperScope.hasAttribute(element, 'resize')) {
  11929. var style = element.style;
  11930. style.width = width + 'px';
  11931. style.height = height + 'px';
  11932. }
  11933. ctx.restore();
  11934. ctx.save();
  11935. ctx.scale(pixelRatio, pixelRatio);
  11936. }
  11937. },
  11938. getPixelSize: function getPixelSize(size) {
  11939. var agent = paper.agent,
  11940. pixels;
  11941. if (agent && agent.firefox) {
  11942. pixels = getPixelSize.base.call(this, size);
  11943. } else {
  11944. var ctx = this._context,
  11945. prevFont = ctx.font;
  11946. ctx.font = size + ' serif';
  11947. pixels = parseFloat(ctx.font);
  11948. ctx.font = prevFont;
  11949. }
  11950. return pixels;
  11951. },
  11952. getTextWidth: function(font, lines) {
  11953. var ctx = this._context,
  11954. prevFont = ctx.font,
  11955. width = 0;
  11956. ctx.font = font;
  11957. for (var i = 0, l = lines.length; i < l; i++)
  11958. width = Math.max(width, ctx.measureText(lines[i]).width);
  11959. ctx.font = prevFont;
  11960. return width;
  11961. },
  11962. update: function() {
  11963. if (!this._needsUpdate)
  11964. return false;
  11965. var project = this._project,
  11966. ctx = this._context,
  11967. size = this._viewSize;
  11968. ctx.clearRect(0, 0, size.width + 1, size.height + 1);
  11969. if (project)
  11970. project.draw(ctx, this._matrix, this._pixelRatio);
  11971. this._needsUpdate = false;
  11972. return true;
  11973. }
  11974. });
  11975. var Event = Base.extend({
  11976. _class: 'Event',
  11977. initialize: function Event(event) {
  11978. this.event = event;
  11979. this.type = event && event.type;
  11980. },
  11981. prevented: false,
  11982. stopped: false,
  11983. preventDefault: function() {
  11984. this.prevented = true;
  11985. this.event.preventDefault();
  11986. },
  11987. stopPropagation: function() {
  11988. this.stopped = true;
  11989. this.event.stopPropagation();
  11990. },
  11991. stop: function() {
  11992. this.stopPropagation();
  11993. this.preventDefault();
  11994. },
  11995. getTimeStamp: function() {
  11996. return this.event.timeStamp;
  11997. },
  11998. getModifiers: function() {
  11999. return Key.modifiers;
  12000. }
  12001. });
  12002. var KeyEvent = Event.extend({
  12003. _class: 'KeyEvent',
  12004. initialize: function KeyEvent(type, event, key, character) {
  12005. this.type = type;
  12006. this.event = event;
  12007. this.key = key;
  12008. this.character = character;
  12009. },
  12010. toString: function() {
  12011. return "{ type: '" + this.type
  12012. + "', key: '" + this.key
  12013. + "', character: '" + this.character
  12014. + "', modifiers: " + this.getModifiers()
  12015. + " }";
  12016. }
  12017. });
  12018. var Key = new function() {
  12019. var keyLookup = {
  12020. '\t': 'tab',
  12021. ' ': 'space',
  12022. '\b': 'backspace',
  12023. '\x7f': 'delete',
  12024. 'Spacebar': 'space',
  12025. 'Del': 'delete',
  12026. 'Win': 'meta',
  12027. 'Esc': 'escape'
  12028. },
  12029. charLookup = {
  12030. 'tab': '\t',
  12031. 'space': ' ',
  12032. 'enter': '\r'
  12033. },
  12034. keyMap = {},
  12035. charMap = {},
  12036. metaFixMap,
  12037. downKey,
  12038. modifiers = new Base({
  12039. shift: false,
  12040. control: false,
  12041. alt: false,
  12042. meta: false,
  12043. capsLock: false,
  12044. space: false
  12045. }).inject({
  12046. option: {
  12047. get: function() {
  12048. return this.alt;
  12049. }
  12050. },
  12051. command: {
  12052. get: function() {
  12053. var agent = paper && paper.agent;
  12054. return agent && agent.mac ? this.meta : this.control;
  12055. }
  12056. }
  12057. });
  12058. function getKey(event) {
  12059. var key = event.key || event.keyIdentifier;
  12060. key = /^U\+/.test(key)
  12061. ? String.fromCharCode(parseInt(key.substr(2), 16))
  12062. : /^Arrow[A-Z]/.test(key) ? key.substr(5)
  12063. : key === 'Unidentified' || key === undefined
  12064. ? String.fromCharCode(event.keyCode)
  12065. : key;
  12066. return keyLookup[key] ||
  12067. (key.length > 1 ? Base.hyphenate(key) : key.toLowerCase());
  12068. }
  12069. function handleKey(down, key, character, event) {
  12070. var type = down ? 'keydown' : 'keyup',
  12071. view = View._focused,
  12072. name;
  12073. keyMap[key] = down;
  12074. if (down) {
  12075. charMap[key] = character;
  12076. } else {
  12077. delete charMap[key];
  12078. }
  12079. if (key.length > 1 && (name = Base.camelize(key)) in modifiers) {
  12080. modifiers[name] = down;
  12081. var agent = paper && paper.agent;
  12082. if (name === 'meta' && agent && agent.mac) {
  12083. if (down) {
  12084. metaFixMap = {};
  12085. } else {
  12086. for (var k in metaFixMap) {
  12087. if (k in charMap)
  12088. handleKey(false, k, metaFixMap[k], event);
  12089. }
  12090. metaFixMap = null;
  12091. }
  12092. }
  12093. } else if (down && metaFixMap) {
  12094. metaFixMap[key] = character;
  12095. }
  12096. if (view) {
  12097. view._handleKeyEvent(down ? 'keydown' : 'keyup', event, key,
  12098. character);
  12099. }
  12100. }
  12101. DomEvent.add(document, {
  12102. keydown: function(event) {
  12103. var key = getKey(event),
  12104. agent = paper && paper.agent;
  12105. if (key.length > 1 || agent && (agent.chrome && (event.altKey
  12106. || agent.mac && event.metaKey
  12107. || !agent.mac && event.ctrlKey))) {
  12108. handleKey(true, key,
  12109. charLookup[key] || (key.length > 1 ? '' : key), event);
  12110. } else {
  12111. downKey = key;
  12112. }
  12113. },
  12114. keypress: function(event) {
  12115. if (downKey) {
  12116. var key = getKey(event),
  12117. code = event.charCode,
  12118. character = code >= 32 ? String.fromCharCode(code)
  12119. : key.length > 1 ? '' : key;
  12120. if (key !== downKey) {
  12121. key = character.toLowerCase();
  12122. }
  12123. handleKey(true, key, character, event);
  12124. downKey = null;
  12125. }
  12126. },
  12127. keyup: function(event) {
  12128. var key = getKey(event);
  12129. if (key in charMap)
  12130. handleKey(false, key, charMap[key], event);
  12131. }
  12132. });
  12133. DomEvent.add(window, {
  12134. blur: function(event) {
  12135. for (var key in charMap)
  12136. handleKey(false, key, charMap[key], event);
  12137. }
  12138. });
  12139. return {
  12140. modifiers: modifiers,
  12141. isDown: function(key) {
  12142. return !!keyMap[key];
  12143. }
  12144. };
  12145. };
  12146. var MouseEvent = Event.extend({
  12147. _class: 'MouseEvent',
  12148. initialize: function MouseEvent(type, event, point, target, delta) {
  12149. this.type = type;
  12150. this.event = event;
  12151. this.point = point;
  12152. this.target = target;
  12153. this.delta = delta;
  12154. },
  12155. toString: function() {
  12156. return "{ type: '" + this.type
  12157. + "', point: " + this.point
  12158. + ', target: ' + this.target
  12159. + (this.delta ? ', delta: ' + this.delta : '')
  12160. + ', modifiers: ' + this.getModifiers()
  12161. + ' }';
  12162. }
  12163. });
  12164. var ToolEvent = Event.extend({
  12165. _class: 'ToolEvent',
  12166. _item: null,
  12167. initialize: function ToolEvent(tool, type, event) {
  12168. this.tool = tool;
  12169. this.type = type;
  12170. this.event = event;
  12171. },
  12172. _choosePoint: function(point, toolPoint) {
  12173. return point ? point : toolPoint ? toolPoint.clone() : null;
  12174. },
  12175. getPoint: function() {
  12176. return this._choosePoint(this._point, this.tool._point);
  12177. },
  12178. setPoint: function(point) {
  12179. this._point = point;
  12180. },
  12181. getLastPoint: function() {
  12182. return this._choosePoint(this._lastPoint, this.tool._lastPoint);
  12183. },
  12184. setLastPoint: function(lastPoint) {
  12185. this._lastPoint = lastPoint;
  12186. },
  12187. getDownPoint: function() {
  12188. return this._choosePoint(this._downPoint, this.tool._downPoint);
  12189. },
  12190. setDownPoint: function(downPoint) {
  12191. this._downPoint = downPoint;
  12192. },
  12193. getMiddlePoint: function() {
  12194. if (!this._middlePoint && this.tool._lastPoint) {
  12195. return this.tool._point.add(this.tool._lastPoint).divide(2);
  12196. }
  12197. return this._middlePoint;
  12198. },
  12199. setMiddlePoint: function(middlePoint) {
  12200. this._middlePoint = middlePoint;
  12201. },
  12202. getDelta: function() {
  12203. return !this._delta && this.tool._lastPoint
  12204. ? this.tool._point.subtract(this.tool._lastPoint)
  12205. : this._delta;
  12206. },
  12207. setDelta: function(delta) {
  12208. this._delta = delta;
  12209. },
  12210. getCount: function() {
  12211. return this.tool[/^mouse(down|up)$/.test(this.type)
  12212. ? '_downCount' : '_moveCount'];
  12213. },
  12214. setCount: function(count) {
  12215. this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
  12216. = count;
  12217. },
  12218. getItem: function() {
  12219. if (!this._item) {
  12220. var result = this.tool._scope.project.hitTest(this.getPoint());
  12221. if (result) {
  12222. var item = result.item,
  12223. parent = item._parent;
  12224. while (/^(Group|CompoundPath)$/.test(parent._class)) {
  12225. item = parent;
  12226. parent = parent._parent;
  12227. }
  12228. this._item = item;
  12229. }
  12230. }
  12231. return this._item;
  12232. },
  12233. setItem: function(item) {
  12234. this._item = item;
  12235. },
  12236. toString: function() {
  12237. return '{ type: ' + this.type
  12238. + ', point: ' + this.getPoint()
  12239. + ', count: ' + this.getCount()
  12240. + ', modifiers: ' + this.getModifiers()
  12241. + ' }';
  12242. }
  12243. });
  12244. var Tool = PaperScopeItem.extend({
  12245. _class: 'Tool',
  12246. _list: 'tools',
  12247. _reference: 'tool',
  12248. _events: ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
  12249. 'onActivate', 'onDeactivate', 'onEditOptions', 'onKeyDown',
  12250. 'onKeyUp'],
  12251. initialize: function Tool(props) {
  12252. PaperScopeItem.call(this);
  12253. this._moveCount = -1;
  12254. this._downCount = -1;
  12255. this.set(props);
  12256. },
  12257. getMinDistance: function() {
  12258. return this._minDistance;
  12259. },
  12260. setMinDistance: function(minDistance) {
  12261. this._minDistance = minDistance;
  12262. if (minDistance != null && this._maxDistance != null
  12263. && minDistance > this._maxDistance) {
  12264. this._maxDistance = minDistance;
  12265. }
  12266. },
  12267. getMaxDistance: function() {
  12268. return this._maxDistance;
  12269. },
  12270. setMaxDistance: function(maxDistance) {
  12271. this._maxDistance = maxDistance;
  12272. if (this._minDistance != null && maxDistance != null
  12273. && maxDistance < this._minDistance) {
  12274. this._minDistance = maxDistance;
  12275. }
  12276. },
  12277. getFixedDistance: function() {
  12278. return this._minDistance == this._maxDistance
  12279. ? this._minDistance : null;
  12280. },
  12281. setFixedDistance: function(distance) {
  12282. this._minDistance = this._maxDistance = distance;
  12283. },
  12284. _handleMouseEvent: function(type, event, point, mouse) {
  12285. paper = this._scope;
  12286. if (mouse.drag && !this.responds(type))
  12287. type = 'mousemove';
  12288. var move = mouse.move || mouse.drag,
  12289. responds = this.responds(type),
  12290. minDistance = this.minDistance,
  12291. maxDistance = this.maxDistance,
  12292. called = false,
  12293. tool = this;
  12294. function update(minDistance, maxDistance) {
  12295. var pt = point,
  12296. toolPoint = move ? tool._point : (tool._downPoint || pt);
  12297. if (move) {
  12298. if (tool._moveCount >= 0 && pt.equals(toolPoint)) {
  12299. return false;
  12300. }
  12301. if (toolPoint && (minDistance != null || maxDistance != null)) {
  12302. var vector = pt.subtract(toolPoint),
  12303. distance = vector.getLength();
  12304. if (distance < (minDistance || 0))
  12305. return false;
  12306. if (maxDistance) {
  12307. pt = toolPoint.add(vector.normalize(
  12308. Math.min(distance, maxDistance)));
  12309. }
  12310. }
  12311. tool._moveCount++;
  12312. }
  12313. tool._point = pt;
  12314. tool._lastPoint = toolPoint || pt;
  12315. if (mouse.down) {
  12316. tool._moveCount = -1;
  12317. tool._downPoint = pt;
  12318. tool._downCount++;
  12319. }
  12320. return true;
  12321. }
  12322. function emit() {
  12323. if (responds) {
  12324. called = tool.emit(type, new ToolEvent(tool, type, event))
  12325. || called;
  12326. }
  12327. }
  12328. if (mouse.down) {
  12329. update();
  12330. emit();
  12331. } else if (mouse.up) {
  12332. update(null, maxDistance);
  12333. emit();
  12334. } else if (responds) {
  12335. while (update(minDistance, maxDistance))
  12336. emit();
  12337. }
  12338. return called;
  12339. }
  12340. });
  12341. var Tween = Base.extend(Emitter, {
  12342. _class: 'Tween',
  12343. statics: {
  12344. easings: {
  12345. linear: function(t) {
  12346. return t;
  12347. },
  12348. easeInQuad: function(t) {
  12349. return t * t;
  12350. },
  12351. easeOutQuad: function(t) {
  12352. return t * (2 - t);
  12353. },
  12354. easeInOutQuad: function(t) {
  12355. return t < 0.5
  12356. ? 2 * t * t
  12357. : -1 + 2 * (2 - t) * t;
  12358. },
  12359. easeInCubic: function(t) {
  12360. return t * t * t;
  12361. },
  12362. easeOutCubic: function(t) {
  12363. return --t * t * t + 1;
  12364. },
  12365. easeInOutCubic: function(t) {
  12366. return t < 0.5
  12367. ? 4 * t * t * t
  12368. : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
  12369. },
  12370. easeInQuart: function(t) {
  12371. return t * t * t * t;
  12372. },
  12373. easeOutQuart: function(t) {
  12374. return 1 - (--t) * t * t * t;
  12375. },
  12376. easeInOutQuart: function(t) {
  12377. return t < 0.5
  12378. ? 8 * t * t * t * t
  12379. : 1 - 8 * (--t) * t * t * t;
  12380. },
  12381. easeInQuint: function(t) {
  12382. return t * t * t * t * t;
  12383. },
  12384. easeOutQuint: function(t) {
  12385. return 1 + --t * t * t * t * t;
  12386. },
  12387. easeInOutQuint: function(t) {
  12388. return t < 0.5
  12389. ? 16 * t * t * t * t * t
  12390. : 1 + 16 * (--t) * t * t * t * t;
  12391. }
  12392. }
  12393. },
  12394. initialize: function Tween(object, from, to, duration, easing, start) {
  12395. this.object = object;
  12396. var type = typeof easing;
  12397. var isFunction = type === 'function';
  12398. this.type = isFunction
  12399. ? type
  12400. : type === 'string'
  12401. ? easing
  12402. : 'linear';
  12403. this.easing = isFunction ? easing : Tween.easings[this.type];
  12404. this.duration = duration;
  12405. this.running = false;
  12406. this._then = null;
  12407. this._startTime = null;
  12408. var state = from || to;
  12409. this._keys = state ? Object.keys(state) : [];
  12410. this._parsedKeys = this._parseKeys(this._keys);
  12411. this._from = state && this._getState(from);
  12412. this._to = state && this._getState(to);
  12413. if (start !== false) {
  12414. this.start();
  12415. }
  12416. },
  12417. then: function(then) {
  12418. this._then = then;
  12419. return this;
  12420. },
  12421. start: function() {
  12422. this._startTime = null;
  12423. this.running = true;
  12424. return this;
  12425. },
  12426. stop: function() {
  12427. this.running = false;
  12428. return this;
  12429. },
  12430. update: function(progress) {
  12431. if (this.running) {
  12432. if (progress > 1) {
  12433. progress = 1;
  12434. this.running = false;
  12435. }
  12436. var factor = this.easing(progress),
  12437. keys = this._keys,
  12438. getValue = function(value) {
  12439. return typeof value === 'function'
  12440. ? value(factor, progress)
  12441. : value;
  12442. };
  12443. for (var i = 0, l = keys && keys.length; i < l; i++) {
  12444. var key = keys[i],
  12445. from = getValue(this._from[key]),
  12446. to = getValue(this._to[key]),
  12447. value = (from && to && from.__add && to.__add)
  12448. ? to.__subtract(from).__multiply(factor).__add(from)
  12449. : ((to - from) * factor) + from;
  12450. this._setProperty(this._parsedKeys[key], value);
  12451. }
  12452. if (!this.running && this._then) {
  12453. this._then(this.object);
  12454. }
  12455. if (this.responds('update')) {
  12456. this.emit('update', new Base({
  12457. progress: progress,
  12458. factor: factor
  12459. }));
  12460. }
  12461. }
  12462. return this;
  12463. },
  12464. _events: {
  12465. onUpdate: {}
  12466. },
  12467. _handleFrame: function(time) {
  12468. var startTime = this._startTime,
  12469. progress = startTime
  12470. ? (time - startTime) / this.duration
  12471. : 0;
  12472. if (!startTime) {
  12473. this._startTime = time;
  12474. }
  12475. this.update(progress);
  12476. },
  12477. _getState: function(state) {
  12478. var keys = this._keys,
  12479. result = {};
  12480. for (var i = 0, l = keys.length; i < l; i++) {
  12481. var key = keys[i],
  12482. path = this._parsedKeys[key],
  12483. current = this._getProperty(path),
  12484. value;
  12485. if (state) {
  12486. var resolved = this._resolveValue(current, state[key]);
  12487. this._setProperty(path, resolved);
  12488. value = this._getProperty(path);
  12489. value = value && value.clone ? value.clone() : value;
  12490. this._setProperty(path, current);
  12491. } else {
  12492. value = current && current.clone ? current.clone() : current;
  12493. }
  12494. result[key] = value;
  12495. }
  12496. return result;
  12497. },
  12498. _resolveValue: function(current, value) {
  12499. if (value) {
  12500. if (Array.isArray(value) && value.length === 2) {
  12501. var operator = value[0];
  12502. return (
  12503. operator &&
  12504. operator.match &&
  12505. operator.match(/^[+\-*/]=/)
  12506. )
  12507. ? this._calculate(current, operator[0], value[1])
  12508. : value;
  12509. } else if (typeof value === 'string') {
  12510. var match = value.match(/^[+\-*/]=(.*)/);
  12511. if (match) {
  12512. var parsed = JSON.parse(match[1].replace(
  12513. /(['"])?([a-zA-Z0-9_]+)(['"])?:/g,
  12514. '"$2": '
  12515. ));
  12516. return this._calculate(current, value[0], parsed);
  12517. }
  12518. }
  12519. }
  12520. return value;
  12521. },
  12522. _calculate: function(left, operator, right) {
  12523. return paper.PaperScript.calculateBinary(left, operator, right);
  12524. },
  12525. _parseKeys: function(keys) {
  12526. var parsed = {};
  12527. for (var i = 0, l = keys.length; i < l; i++) {
  12528. var key = keys[i],
  12529. path = key
  12530. .replace(/\.([^.]*)/g, '/$1')
  12531. .replace(/\[['"]?([^'"\]]*)['"]?\]/g, '/$1');
  12532. parsed[key] = path.split('/');
  12533. }
  12534. return parsed;
  12535. },
  12536. _getProperty: function(path, offset) {
  12537. var obj = this.object;
  12538. for (var i = 0, l = path.length - (offset || 0); i < l && obj; i++) {
  12539. obj = obj[path[i]];
  12540. }
  12541. return obj;
  12542. },
  12543. _setProperty: function(path, value) {
  12544. var dest = this._getProperty(path, 1);
  12545. if (dest) {
  12546. dest[path[path.length - 1]] = value;
  12547. }
  12548. }
  12549. });
  12550. var Http = {
  12551. request: function(options) {
  12552. var xhr = new self.XMLHttpRequest();
  12553. xhr.open((options.method || 'get').toUpperCase(), options.url,
  12554. Base.pick(options.async, true));
  12555. if (options.mimeType)
  12556. xhr.overrideMimeType(options.mimeType);
  12557. xhr.onload = function() {
  12558. var status = xhr.status;
  12559. if (status === 0 || status === 200) {
  12560. if (options.onLoad) {
  12561. options.onLoad.call(xhr, xhr.responseText);
  12562. }
  12563. } else {
  12564. xhr.onerror();
  12565. }
  12566. };
  12567. xhr.onerror = function() {
  12568. var status = xhr.status,
  12569. message = 'Could not load "' + options.url + '" (Status: '
  12570. + status + ')';
  12571. if (options.onError) {
  12572. options.onError(message, status);
  12573. } else {
  12574. throw new Error(message);
  12575. }
  12576. };
  12577. return xhr.send(null);
  12578. }
  12579. };
  12580. var CanvasProvider = {
  12581. canvases: [],
  12582. getCanvas: function(width, height) {
  12583. if (!window)
  12584. return null;
  12585. var canvas,
  12586. clear = true;
  12587. if (typeof width === 'object') {
  12588. height = width.height;
  12589. width = width.width;
  12590. }
  12591. if (this.canvases.length) {
  12592. canvas = this.canvases.pop();
  12593. } else {
  12594. canvas = document.createElement('canvas');
  12595. clear = false;
  12596. }
  12597. var ctx = canvas.getContext('2d');
  12598. if (!ctx) {
  12599. throw new Error('Canvas ' + canvas +
  12600. ' is unable to provide a 2D context.');
  12601. }
  12602. if (canvas.width === width && canvas.height === height) {
  12603. if (clear)
  12604. ctx.clearRect(0, 0, width + 1, height + 1);
  12605. } else {
  12606. canvas.width = width;
  12607. canvas.height = height;
  12608. }
  12609. ctx.save();
  12610. return canvas;
  12611. },
  12612. getContext: function(width, height) {
  12613. var canvas = this.getCanvas(width, height);
  12614. return canvas ? canvas.getContext('2d') : null;
  12615. },
  12616. release: function(obj) {
  12617. var canvas = obj && obj.canvas ? obj.canvas : obj;
  12618. if (canvas && canvas.getContext) {
  12619. canvas.getContext('2d').restore();
  12620. this.canvases.push(canvas);
  12621. }
  12622. }
  12623. };
  12624. var BlendMode = new function() {
  12625. var min = Math.min,
  12626. max = Math.max,
  12627. abs = Math.abs,
  12628. sr, sg, sb, sa,
  12629. br, bg, bb, ba,
  12630. dr, dg, db;
  12631. function getLum(r, g, b) {
  12632. return 0.2989 * r + 0.587 * g + 0.114 * b;
  12633. }
  12634. function setLum(r, g, b, l) {
  12635. var d = l - getLum(r, g, b);
  12636. dr = r + d;
  12637. dg = g + d;
  12638. db = b + d;
  12639. var l = getLum(dr, dg, db),
  12640. mn = min(dr, dg, db),
  12641. mx = max(dr, dg, db);
  12642. if (mn < 0) {
  12643. var lmn = l - mn;
  12644. dr = l + (dr - l) * l / lmn;
  12645. dg = l + (dg - l) * l / lmn;
  12646. db = l + (db - l) * l / lmn;
  12647. }
  12648. if (mx > 255) {
  12649. var ln = 255 - l,
  12650. mxl = mx - l;
  12651. dr = l + (dr - l) * ln / mxl;
  12652. dg = l + (dg - l) * ln / mxl;
  12653. db = l + (db - l) * ln / mxl;
  12654. }
  12655. }
  12656. function getSat(r, g, b) {
  12657. return max(r, g, b) - min(r, g, b);
  12658. }
  12659. function setSat(r, g, b, s) {
  12660. var col = [r, g, b],
  12661. mx = max(r, g, b),
  12662. mn = min(r, g, b),
  12663. md;
  12664. mn = mn === r ? 0 : mn === g ? 1 : 2;
  12665. mx = mx === r ? 0 : mx === g ? 1 : 2;
  12666. md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
  12667. if (col[mx] > col[mn]) {
  12668. col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
  12669. col[mx] = s;
  12670. } else {
  12671. col[md] = col[mx] = 0;
  12672. }
  12673. col[mn] = 0;
  12674. dr = col[0];
  12675. dg = col[1];
  12676. db = col[2];
  12677. }
  12678. var modes = {
  12679. multiply: function() {
  12680. dr = br * sr / 255;
  12681. dg = bg * sg / 255;
  12682. db = bb * sb / 255;
  12683. },
  12684. screen: function() {
  12685. dr = br + sr - (br * sr / 255);
  12686. dg = bg + sg - (bg * sg / 255);
  12687. db = bb + sb - (bb * sb / 255);
  12688. },
  12689. overlay: function() {
  12690. dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
  12691. dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
  12692. db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
  12693. },
  12694. 'soft-light': function() {
  12695. var t = sr * br / 255;
  12696. dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
  12697. t = sg * bg / 255;
  12698. dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
  12699. t = sb * bb / 255;
  12700. db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
  12701. },
  12702. 'hard-light': function() {
  12703. dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
  12704. dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
  12705. db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
  12706. },
  12707. 'color-dodge': function() {
  12708. dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
  12709. dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
  12710. db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
  12711. },
  12712. 'color-burn': function() {
  12713. dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
  12714. dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
  12715. db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
  12716. },
  12717. darken: function() {
  12718. dr = br < sr ? br : sr;
  12719. dg = bg < sg ? bg : sg;
  12720. db = bb < sb ? bb : sb;
  12721. },
  12722. lighten: function() {
  12723. dr = br > sr ? br : sr;
  12724. dg = bg > sg ? bg : sg;
  12725. db = bb > sb ? bb : sb;
  12726. },
  12727. difference: function() {
  12728. dr = br - sr;
  12729. if (dr < 0)
  12730. dr = -dr;
  12731. dg = bg - sg;
  12732. if (dg < 0)
  12733. dg = -dg;
  12734. db = bb - sb;
  12735. if (db < 0)
  12736. db = -db;
  12737. },
  12738. exclusion: function() {
  12739. dr = br + sr * (255 - br - br) / 255;
  12740. dg = bg + sg * (255 - bg - bg) / 255;
  12741. db = bb + sb * (255 - bb - bb) / 255;
  12742. },
  12743. hue: function() {
  12744. setSat(sr, sg, sb, getSat(br, bg, bb));
  12745. setLum(dr, dg, db, getLum(br, bg, bb));
  12746. },
  12747. saturation: function() {
  12748. setSat(br, bg, bb, getSat(sr, sg, sb));
  12749. setLum(dr, dg, db, getLum(br, bg, bb));
  12750. },
  12751. luminosity: function() {
  12752. setLum(br, bg, bb, getLum(sr, sg, sb));
  12753. },
  12754. color: function() {
  12755. setLum(sr, sg, sb, getLum(br, bg, bb));
  12756. },
  12757. add: function() {
  12758. dr = min(br + sr, 255);
  12759. dg = min(bg + sg, 255);
  12760. db = min(bb + sb, 255);
  12761. },
  12762. subtract: function() {
  12763. dr = max(br - sr, 0);
  12764. dg = max(bg - sg, 0);
  12765. db = max(bb - sb, 0);
  12766. },
  12767. average: function() {
  12768. dr = (br + sr) / 2;
  12769. dg = (bg + sg) / 2;
  12770. db = (bb + sb) / 2;
  12771. },
  12772. negation: function() {
  12773. dr = 255 - abs(255 - sr - br);
  12774. dg = 255 - abs(255 - sg - bg);
  12775. db = 255 - abs(255 - sb - bb);
  12776. }
  12777. };
  12778. var nativeModes = this.nativeModes = Base.each([
  12779. 'source-over', 'source-in', 'source-out', 'source-atop',
  12780. 'destination-over', 'destination-in', 'destination-out',
  12781. 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
  12782. ], function(mode) {
  12783. this[mode] = true;
  12784. }, {});
  12785. var ctx = CanvasProvider.getContext(1, 1);
  12786. if (ctx) {
  12787. Base.each(modes, function(func, mode) {
  12788. var darken = mode === 'darken',
  12789. ok = false;
  12790. ctx.save();
  12791. try {
  12792. ctx.fillStyle = darken ? '#300' : '#a00';
  12793. ctx.fillRect(0, 0, 1, 1);
  12794. ctx.globalCompositeOperation = mode;
  12795. if (ctx.globalCompositeOperation === mode) {
  12796. ctx.fillStyle = darken ? '#a00' : '#300';
  12797. ctx.fillRect(0, 0, 1, 1);
  12798. ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken
  12799. ? 170 : 51;
  12800. }
  12801. } catch (e) {}
  12802. ctx.restore();
  12803. nativeModes[mode] = ok;
  12804. });
  12805. CanvasProvider.release(ctx);
  12806. }
  12807. this.process = function(mode, srcContext, dstContext, alpha, offset) {
  12808. var srcCanvas = srcContext.canvas,
  12809. normal = mode === 'normal';
  12810. if (normal || nativeModes[mode]) {
  12811. dstContext.save();
  12812. dstContext.setTransform(1, 0, 0, 1, 0, 0);
  12813. dstContext.globalAlpha = alpha;
  12814. if (!normal)
  12815. dstContext.globalCompositeOperation = mode;
  12816. dstContext.drawImage(srcCanvas, offset.x, offset.y);
  12817. dstContext.restore();
  12818. } else {
  12819. var process = modes[mode];
  12820. if (!process)
  12821. return;
  12822. var dstData = dstContext.getImageData(offset.x, offset.y,
  12823. srcCanvas.width, srcCanvas.height),
  12824. dst = dstData.data,
  12825. src = srcContext.getImageData(0, 0,
  12826. srcCanvas.width, srcCanvas.height).data;
  12827. for (var i = 0, l = dst.length; i < l; i += 4) {
  12828. sr = src[i];
  12829. br = dst[i];
  12830. sg = src[i + 1];
  12831. bg = dst[i + 1];
  12832. sb = src[i + 2];
  12833. bb = dst[i + 2];
  12834. sa = src[i + 3];
  12835. ba = dst[i + 3];
  12836. process();
  12837. var a1 = sa * alpha / 255,
  12838. a2 = 1 - a1;
  12839. dst[i] = a1 * dr + a2 * br;
  12840. dst[i + 1] = a1 * dg + a2 * bg;
  12841. dst[i + 2] = a1 * db + a2 * bb;
  12842. dst[i + 3] = sa * alpha + a2 * ba;
  12843. }
  12844. dstContext.putImageData(dstData, offset.x, offset.y);
  12845. }
  12846. };
  12847. };
  12848. var SvgElement = new function() {
  12849. var svg = 'http://www.w3.org/2000/svg',
  12850. xmlns = 'http://www.w3.org/2000/xmlns',
  12851. xlink = 'http://www.w3.org/1999/xlink',
  12852. attributeNamespace = {
  12853. href: xlink,
  12854. xlink: xmlns,
  12855. xmlns: xmlns + '/',
  12856. 'xmlns:xlink': xmlns + '/'
  12857. };
  12858. function create(tag, attributes, formatter) {
  12859. return set(document.createElementNS(svg, tag), attributes, formatter);
  12860. }
  12861. function get(node, name) {
  12862. var namespace = attributeNamespace[name],
  12863. value = namespace
  12864. ? node.getAttributeNS(namespace, name)
  12865. : node.getAttribute(name);
  12866. return value === 'null' ? null : value;
  12867. }
  12868. function set(node, attributes, formatter) {
  12869. for (var name in attributes) {
  12870. var value = attributes[name],
  12871. namespace = attributeNamespace[name];
  12872. if (typeof value === 'number' && formatter)
  12873. value = formatter.number(value);
  12874. if (namespace) {
  12875. node.setAttributeNS(namespace, name, value);
  12876. } else {
  12877. node.setAttribute(name, value);
  12878. }
  12879. }
  12880. return node;
  12881. }
  12882. return {
  12883. svg: svg,
  12884. xmlns: xmlns,
  12885. xlink: xlink,
  12886. create: create,
  12887. get: get,
  12888. set: set
  12889. };
  12890. };
  12891. var SvgStyles = Base.each({
  12892. fillColor: ['fill', 'color'],
  12893. fillRule: ['fill-rule', 'string'],
  12894. strokeColor: ['stroke', 'color'],
  12895. strokeWidth: ['stroke-width', 'number'],
  12896. strokeCap: ['stroke-linecap', 'string'],
  12897. strokeJoin: ['stroke-linejoin', 'string'],
  12898. strokeScaling: ['vector-effect', 'lookup', {
  12899. true: 'none',
  12900. false: 'non-scaling-stroke'
  12901. }, function(item, value) {
  12902. return !value
  12903. && (item instanceof PathItem
  12904. || item instanceof Shape
  12905. || item instanceof TextItem);
  12906. }],
  12907. miterLimit: ['stroke-miterlimit', 'number'],
  12908. dashArray: ['stroke-dasharray', 'array'],
  12909. dashOffset: ['stroke-dashoffset', 'number'],
  12910. fontFamily: ['font-family', 'string'],
  12911. fontWeight: ['font-weight', 'string'],
  12912. fontSize: ['font-size', 'number'],
  12913. justification: ['text-anchor', 'lookup', {
  12914. left: 'start',
  12915. center: 'middle',
  12916. right: 'end'
  12917. }],
  12918. opacity: ['opacity', 'number'],
  12919. blendMode: ['mix-blend-mode', 'style']
  12920. }, function(entry, key) {
  12921. var part = Base.capitalize(key),
  12922. lookup = entry[2];
  12923. this[key] = {
  12924. type: entry[1],
  12925. property: key,
  12926. attribute: entry[0],
  12927. toSVG: lookup,
  12928. fromSVG: lookup && Base.each(lookup, function(value, name) {
  12929. this[value] = name;
  12930. }, {}),
  12931. exportFilter: entry[3],
  12932. get: 'get' + part,
  12933. set: 'set' + part
  12934. };
  12935. }, {});
  12936. new function() {
  12937. var formatter;
  12938. function getTransform(matrix, coordinates, center) {
  12939. var attrs = new Base(),
  12940. trans = matrix.getTranslation();
  12941. if (coordinates) {
  12942. matrix = matrix._shiftless();
  12943. var point = matrix._inverseTransform(trans);
  12944. attrs[center ? 'cx' : 'x'] = point.x;
  12945. attrs[center ? 'cy' : 'y'] = point.y;
  12946. trans = null;
  12947. }
  12948. if (!matrix.isIdentity()) {
  12949. var decomposed = matrix.decompose();
  12950. if (decomposed) {
  12951. var parts = [],
  12952. angle = decomposed.rotation,
  12953. scale = decomposed.scaling,
  12954. skew = decomposed.skewing;
  12955. if (trans && !trans.isZero())
  12956. parts.push('translate(' + formatter.point(trans) + ')');
  12957. if (angle)
  12958. parts.push('rotate(' + formatter.number(angle) + ')');
  12959. if (!Numerical.isZero(scale.x - 1)
  12960. || !Numerical.isZero(scale.y - 1))
  12961. parts.push('scale(' + formatter.point(scale) +')');
  12962. if (skew.x)
  12963. parts.push('skewX(' + formatter.number(skew.x) + ')');
  12964. if (skew.y)
  12965. parts.push('skewY(' + formatter.number(skew.y) + ')');
  12966. attrs.transform = parts.join(' ');
  12967. } else {
  12968. attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
  12969. }
  12970. }
  12971. return attrs;
  12972. }
  12973. function exportGroup(item, options) {
  12974. var attrs = getTransform(item._matrix),
  12975. children = item._children;
  12976. var node = SvgElement.create('g', attrs, formatter);
  12977. for (var i = 0, l = children.length; i < l; i++) {
  12978. var child = children[i];
  12979. var childNode = exportSVG(child, options);
  12980. if (childNode) {
  12981. if (child.isClipMask()) {
  12982. var clip = SvgElement.create('clipPath');
  12983. clip.appendChild(childNode);
  12984. setDefinition(child, clip, 'clip');
  12985. SvgElement.set(node, {
  12986. 'clip-path': 'url(#' + clip.id + ')'
  12987. });
  12988. } else {
  12989. node.appendChild(childNode);
  12990. }
  12991. }
  12992. }
  12993. return node;
  12994. }
  12995. function exportRaster(item, options) {
  12996. var attrs = getTransform(item._matrix, true),
  12997. size = item.getSize(),
  12998. image = item.getImage();
  12999. attrs.x -= size.width / 2;
  13000. attrs.y -= size.height / 2;
  13001. attrs.width = size.width;
  13002. attrs.height = size.height;
  13003. attrs.href = options.embedImages == false && image && image.src
  13004. || item.toDataURL();
  13005. return SvgElement.create('image', attrs, formatter);
  13006. }
  13007. function exportPath(item, options) {
  13008. var matchShapes = options.matchShapes;
  13009. if (matchShapes) {
  13010. var shape = item.toShape(false);
  13011. if (shape)
  13012. return exportShape(shape, options);
  13013. }
  13014. var segments = item._segments,
  13015. length = segments.length,
  13016. type,
  13017. attrs = getTransform(item._matrix);
  13018. if (matchShapes && length >= 2 && !item.hasHandles()) {
  13019. if (length > 2) {
  13020. type = item._closed ? 'polygon' : 'polyline';
  13021. var parts = [];
  13022. for (var i = 0; i < length; i++) {
  13023. parts.push(formatter.point(segments[i]._point));
  13024. }
  13025. attrs.points = parts.join(' ');
  13026. } else {
  13027. type = 'line';
  13028. var start = segments[0]._point,
  13029. end = segments[1]._point;
  13030. attrs.set({
  13031. x1: start.x,
  13032. y1: start.y,
  13033. x2: end.x,
  13034. y2: end.y
  13035. });
  13036. }
  13037. } else {
  13038. type = 'path';
  13039. attrs.d = item.getPathData(null, options.precision);
  13040. }
  13041. return SvgElement.create(type, attrs, formatter);
  13042. }
  13043. function exportShape(item) {
  13044. var type = item._type,
  13045. radius = item._radius,
  13046. attrs = getTransform(item._matrix, true, type !== 'rectangle');
  13047. if (type === 'rectangle') {
  13048. type = 'rect';
  13049. var size = item._size,
  13050. width = size.width,
  13051. height = size.height;
  13052. attrs.x -= width / 2;
  13053. attrs.y -= height / 2;
  13054. attrs.width = width;
  13055. attrs.height = height;
  13056. if (radius.isZero())
  13057. radius = null;
  13058. }
  13059. if (radius) {
  13060. if (type === 'circle') {
  13061. attrs.r = radius;
  13062. } else {
  13063. attrs.rx = radius.width;
  13064. attrs.ry = radius.height;
  13065. }
  13066. }
  13067. return SvgElement.create(type, attrs, formatter);
  13068. }
  13069. function exportCompoundPath(item, options) {
  13070. var attrs = getTransform(item._matrix);
  13071. var data = item.getPathData(null, options.precision);
  13072. if (data)
  13073. attrs.d = data;
  13074. return SvgElement.create('path', attrs, formatter);
  13075. }
  13076. function exportSymbolItem(item, options) {
  13077. var attrs = getTransform(item._matrix, true),
  13078. definition = item._definition,
  13079. node = getDefinition(definition, 'symbol'),
  13080. definitionItem = definition._item,
  13081. bounds = definitionItem.getBounds();
  13082. if (!node) {
  13083. node = SvgElement.create('symbol', {
  13084. viewBox: formatter.rectangle(bounds)
  13085. });
  13086. node.appendChild(exportSVG(definitionItem, options));
  13087. setDefinition(definition, node, 'symbol');
  13088. }
  13089. attrs.href = '#' + node.id;
  13090. attrs.x += bounds.x;
  13091. attrs.y += bounds.y;
  13092. attrs.width = bounds.width;
  13093. attrs.height = bounds.height;
  13094. attrs.overflow = 'visible';
  13095. return SvgElement.create('use', attrs, formatter);
  13096. }
  13097. function exportGradient(color) {
  13098. var gradientNode = getDefinition(color, 'color');
  13099. if (!gradientNode) {
  13100. var gradient = color.getGradient(),
  13101. radial = gradient._radial,
  13102. origin = color.getOrigin(),
  13103. destination = color.getDestination(),
  13104. attrs;
  13105. if (radial) {
  13106. attrs = {
  13107. cx: origin.x,
  13108. cy: origin.y,
  13109. r: origin.getDistance(destination)
  13110. };
  13111. var highlight = color.getHighlight();
  13112. if (highlight) {
  13113. attrs.fx = highlight.x;
  13114. attrs.fy = highlight.y;
  13115. }
  13116. } else {
  13117. attrs = {
  13118. x1: origin.x,
  13119. y1: origin.y,
  13120. x2: destination.x,
  13121. y2: destination.y
  13122. };
  13123. }
  13124. attrs.gradientUnits = 'userSpaceOnUse';
  13125. gradientNode = SvgElement.create((radial ? 'radial' : 'linear')
  13126. + 'Gradient', attrs, formatter);
  13127. var stops = gradient._stops;
  13128. for (var i = 0, l = stops.length; i < l; i++) {
  13129. var stop = stops[i],
  13130. stopColor = stop._color,
  13131. alpha = stopColor.getAlpha(),
  13132. offset = stop._offset;
  13133. attrs = {
  13134. offset: offset == null ? i / (l - 1) : offset
  13135. };
  13136. if (stopColor)
  13137. attrs['stop-color'] = stopColor.toCSS(true);
  13138. if (alpha < 1)
  13139. attrs['stop-opacity'] = alpha;
  13140. gradientNode.appendChild(
  13141. SvgElement.create('stop', attrs, formatter));
  13142. }
  13143. setDefinition(color, gradientNode, 'color');
  13144. }
  13145. return 'url(#' + gradientNode.id + ')';
  13146. }
  13147. function exportText(item) {
  13148. var node = SvgElement.create('text', getTransform(item._matrix, true),
  13149. formatter);
  13150. node.textContent = item._content;
  13151. return node;
  13152. }
  13153. var exporters = {
  13154. Group: exportGroup,
  13155. Layer: exportGroup,
  13156. Raster: exportRaster,
  13157. Path: exportPath,
  13158. Shape: exportShape,
  13159. CompoundPath: exportCompoundPath,
  13160. SymbolItem: exportSymbolItem,
  13161. PointText: exportText
  13162. };
  13163. function applyStyle(item, node, isRoot) {
  13164. var attrs = {},
  13165. parent = !isRoot && item.getParent(),
  13166. style = [];
  13167. if (item._name != null)
  13168. attrs.id = item._name;
  13169. Base.each(SvgStyles, function(entry) {
  13170. var get = entry.get,
  13171. type = entry.type,
  13172. value = item[get]();
  13173. if (entry.exportFilter
  13174. ? entry.exportFilter(item, value)
  13175. : !parent || !Base.equals(parent[get](), value)) {
  13176. if (type === 'color' && value != null) {
  13177. var alpha = value.getAlpha();
  13178. if (alpha < 1)
  13179. attrs[entry.attribute + '-opacity'] = alpha;
  13180. }
  13181. if (type === 'style') {
  13182. style.push(entry.attribute + ': ' + value);
  13183. } else {
  13184. attrs[entry.attribute] = value == null ? 'none'
  13185. : type === 'color' ? value.gradient
  13186. ? exportGradient(value, item)
  13187. : value.toCSS(true)
  13188. : type === 'array' ? value.join(',')
  13189. : type === 'lookup' ? entry.toSVG[value]
  13190. : value;
  13191. }
  13192. }
  13193. });
  13194. if (style.length)
  13195. attrs.style = style.join(';');
  13196. if (attrs.opacity === 1)
  13197. delete attrs.opacity;
  13198. if (!item._visible)
  13199. attrs.visibility = 'hidden';
  13200. return SvgElement.set(node, attrs, formatter);
  13201. }
  13202. var definitions;
  13203. function getDefinition(item, type) {
  13204. if (!definitions)
  13205. definitions = { ids: {}, svgs: {} };
  13206. return item && definitions.svgs[type + '-'
  13207. + (item._id || item.__id || (item.__id = UID.get('svg')))];
  13208. }
  13209. function setDefinition(item, node, type) {
  13210. if (!definitions)
  13211. getDefinition();
  13212. var typeId = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
  13213. node.id = type + '-' + typeId;
  13214. definitions.svgs[type + '-' + (item._id || item.__id)] = node;
  13215. }
  13216. function exportDefinitions(node, options) {
  13217. var svg = node,
  13218. defs = null;
  13219. if (definitions) {
  13220. svg = node.nodeName.toLowerCase() === 'svg' && node;
  13221. for (var i in definitions.svgs) {
  13222. if (!defs) {
  13223. if (!svg) {
  13224. svg = SvgElement.create('svg');
  13225. svg.appendChild(node);
  13226. }
  13227. defs = svg.insertBefore(SvgElement.create('defs'),
  13228. svg.firstChild);
  13229. }
  13230. defs.appendChild(definitions.svgs[i]);
  13231. }
  13232. definitions = null;
  13233. }
  13234. return options.asString
  13235. ? new self.XMLSerializer().serializeToString(svg)
  13236. : svg;
  13237. }
  13238. function exportSVG(item, options, isRoot) {
  13239. var exporter = exporters[item._class],
  13240. node = exporter && exporter(item, options);
  13241. if (node) {
  13242. var onExport = options.onExport;
  13243. if (onExport)
  13244. node = onExport(item, node, options) || node;
  13245. var data = JSON.stringify(item._data);
  13246. if (data && data !== '{}' && data !== 'null')
  13247. node.setAttribute('data-paper-data', data);
  13248. }
  13249. return node && applyStyle(item, node, isRoot);
  13250. }
  13251. function setOptions(options) {
  13252. if (!options)
  13253. options = {};
  13254. formatter = new Formatter(options.precision);
  13255. return options;
  13256. }
  13257. Item.inject({
  13258. exportSVG: function(options) {
  13259. options = setOptions(options);
  13260. return exportDefinitions(exportSVG(this, options, true), options);
  13261. }
  13262. });
  13263. Project.inject({
  13264. exportSVG: function(options) {
  13265. options = setOptions(options);
  13266. var children = this._children,
  13267. view = this.getView(),
  13268. bounds = Base.pick(options.bounds, 'view'),
  13269. mx = options.matrix || bounds === 'view' && view._matrix,
  13270. matrix = mx && Matrix.read([mx]),
  13271. rect = bounds === 'view'
  13272. ? new Rectangle([0, 0], view.getViewSize())
  13273. : bounds === 'content'
  13274. ? Item._getBounds(children, matrix, { stroke: true })
  13275. .rect
  13276. : Rectangle.read([bounds], 0, { readNull: true }),
  13277. attrs = {
  13278. version: '1.1',
  13279. xmlns: SvgElement.svg,
  13280. 'xmlns:xlink': SvgElement.xlink,
  13281. };
  13282. if (rect) {
  13283. attrs.width = rect.width;
  13284. attrs.height = rect.height;
  13285. if (rect.x || rect.y)
  13286. attrs.viewBox = formatter.rectangle(rect);
  13287. }
  13288. var node = SvgElement.create('svg', attrs, formatter),
  13289. parent = node;
  13290. if (matrix && !matrix.isIdentity()) {
  13291. parent = node.appendChild(SvgElement.create('g',
  13292. getTransform(matrix), formatter));
  13293. }
  13294. for (var i = 0, l = children.length; i < l; i++) {
  13295. parent.appendChild(exportSVG(children[i], options, true));
  13296. }
  13297. return exportDefinitions(node, options);
  13298. }
  13299. });
  13300. };
  13301. new function() {
  13302. var definitions = {},
  13303. rootSize;
  13304. function getValue(node, name, isString, allowNull, allowPercent) {
  13305. var value = SvgElement.get(node, name),
  13306. res = value == null
  13307. ? allowNull
  13308. ? null
  13309. : isString ? '' : 0
  13310. : isString
  13311. ? value
  13312. : parseFloat(value);
  13313. return /%\s*$/.test(value)
  13314. ? (res / 100) * (allowPercent ? 1
  13315. : rootSize[/x|^width/.test(name) ? 'width' : 'height'])
  13316. : res;
  13317. }
  13318. function getPoint(node, x, y, allowNull, allowPercent) {
  13319. x = getValue(node, x || 'x', false, allowNull, allowPercent);
  13320. y = getValue(node, y || 'y', false, allowNull, allowPercent);
  13321. return allowNull && (x == null || y == null) ? null
  13322. : new Point(x, y);
  13323. }
  13324. function getSize(node, w, h, allowNull, allowPercent) {
  13325. w = getValue(node, w || 'width', false, allowNull, allowPercent);
  13326. h = getValue(node, h || 'height', false, allowNull, allowPercent);
  13327. return allowNull && (w == null || h == null) ? null
  13328. : new Size(w, h);
  13329. }
  13330. function convertValue(value, type, lookup) {
  13331. return value === 'none' ? null
  13332. : type === 'number' ? parseFloat(value)
  13333. : type === 'array' ?
  13334. value ? value.split(/[\s,]+/g).map(parseFloat) : []
  13335. : type === 'color' ? getDefinition(value) || value
  13336. : type === 'lookup' ? lookup[value]
  13337. : value;
  13338. }
  13339. function importGroup(node, type, options, isRoot) {
  13340. var nodes = node.childNodes,
  13341. isClip = type === 'clippath',
  13342. isDefs = type === 'defs',
  13343. item = new Group(),
  13344. project = item._project,
  13345. currentStyle = project._currentStyle,
  13346. children = [];
  13347. if (!isClip && !isDefs) {
  13348. item = applyAttributes(item, node, isRoot);
  13349. project._currentStyle = item._style.clone();
  13350. }
  13351. if (isRoot) {
  13352. var defs = node.querySelectorAll('defs');
  13353. for (var i = 0, l = defs.length; i < l; i++) {
  13354. importNode(defs[i], options, false);
  13355. }
  13356. }
  13357. for (var i = 0, l = nodes.length; i < l; i++) {
  13358. var childNode = nodes[i],
  13359. child;
  13360. if (childNode.nodeType === 1
  13361. && !/^defs$/i.test(childNode.nodeName)
  13362. && (child = importNode(childNode, options, false))
  13363. && !(child instanceof SymbolDefinition))
  13364. children.push(child);
  13365. }
  13366. item.addChildren(children);
  13367. if (isClip)
  13368. item = applyAttributes(item.reduce(), node, isRoot);
  13369. project._currentStyle = currentStyle;
  13370. if (isClip || isDefs) {
  13371. item.remove();
  13372. item = null;
  13373. }
  13374. return item;
  13375. }
  13376. function importPoly(node, type) {
  13377. var coords = node.getAttribute('points').match(
  13378. /[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g),
  13379. points = [];
  13380. for (var i = 0, l = coords.length; i < l; i += 2)
  13381. points.push(new Point(
  13382. parseFloat(coords[i]),
  13383. parseFloat(coords[i + 1])));
  13384. var path = new Path(points);
  13385. if (type === 'polygon')
  13386. path.closePath();
  13387. return path;
  13388. }
  13389. function importPath(node) {
  13390. return PathItem.create(node.getAttribute('d'));
  13391. }
  13392. function importGradient(node, type) {
  13393. var id = (getValue(node, 'href', true) || '').substring(1),
  13394. radial = type === 'radialgradient',
  13395. gradient;
  13396. if (id) {
  13397. gradient = definitions[id].getGradient();
  13398. if (gradient._radial ^ radial) {
  13399. gradient = gradient.clone();
  13400. gradient._radial = radial;
  13401. }
  13402. } else {
  13403. var nodes = node.childNodes,
  13404. stops = [];
  13405. for (var i = 0, l = nodes.length; i < l; i++) {
  13406. var child = nodes[i];
  13407. if (child.nodeType === 1)
  13408. stops.push(applyAttributes(new GradientStop(), child));
  13409. }
  13410. gradient = new Gradient(stops, radial);
  13411. }
  13412. var origin, destination, highlight,
  13413. scaleToBounds = getValue(node, 'gradientUnits', true) !==
  13414. 'userSpaceOnUse';
  13415. if (radial) {
  13416. origin = getPoint(node, 'cx', 'cy', false, scaleToBounds);
  13417. destination = origin.add(
  13418. getValue(node, 'r', false, false, scaleToBounds), 0);
  13419. highlight = getPoint(node, 'fx', 'fy', true, scaleToBounds);
  13420. } else {
  13421. origin = getPoint(node, 'x1', 'y1', false, scaleToBounds);
  13422. destination = getPoint(node, 'x2', 'y2', false, scaleToBounds);
  13423. }
  13424. var color = applyAttributes(
  13425. new Color(gradient, origin, destination, highlight), node);
  13426. color._scaleToBounds = scaleToBounds;
  13427. return null;
  13428. }
  13429. var importers = {
  13430. '#document': function (node, type, options, isRoot) {
  13431. var nodes = node.childNodes;
  13432. for (var i = 0, l = nodes.length; i < l; i++) {
  13433. var child = nodes[i];
  13434. if (child.nodeType === 1)
  13435. return importNode(child, options, isRoot);
  13436. }
  13437. },
  13438. g: importGroup,
  13439. svg: importGroup,
  13440. clippath: importGroup,
  13441. polygon: importPoly,
  13442. polyline: importPoly,
  13443. path: importPath,
  13444. lineargradient: importGradient,
  13445. radialgradient: importGradient,
  13446. image: function (node) {
  13447. var raster = new Raster(getValue(node, 'href', true));
  13448. raster.on('load', function() {
  13449. var size = getSize(node);
  13450. this.setSize(size);
  13451. var center = getPoint(node).add(size.divide(2));
  13452. this._matrix.append(new Matrix().translate(center));
  13453. });
  13454. return raster;
  13455. },
  13456. symbol: function(node, type, options, isRoot) {
  13457. return new SymbolDefinition(
  13458. importGroup(node, type, options, isRoot), true);
  13459. },
  13460. defs: importGroup,
  13461. use: function(node) {
  13462. var id = (getValue(node, 'href', true) || '').substring(1),
  13463. definition = definitions[id],
  13464. point = getPoint(node);
  13465. return definition
  13466. ? definition instanceof SymbolDefinition
  13467. ? definition.place(point)
  13468. : definition.clone().translate(point)
  13469. : null;
  13470. },
  13471. circle: function(node) {
  13472. return new Shape.Circle(
  13473. getPoint(node, 'cx', 'cy'),
  13474. getValue(node, 'r'));
  13475. },
  13476. ellipse: function(node) {
  13477. return new Shape.Ellipse({
  13478. center: getPoint(node, 'cx', 'cy'),
  13479. radius: getSize(node, 'rx', 'ry')
  13480. });
  13481. },
  13482. rect: function(node) {
  13483. return new Shape.Rectangle(new Rectangle(
  13484. getPoint(node),
  13485. getSize(node)
  13486. ), getSize(node, 'rx', 'ry'));
  13487. },
  13488. line: function(node) {
  13489. return new Path.Line(
  13490. getPoint(node, 'x1', 'y1'),
  13491. getPoint(node, 'x2', 'y2'));
  13492. },
  13493. text: function(node) {
  13494. var text = new PointText(getPoint(node).add(
  13495. getPoint(node, 'dx', 'dy')));
  13496. text.setContent(node.textContent.trim() || '');
  13497. return text;
  13498. }
  13499. };
  13500. function applyTransform(item, value, name, node) {
  13501. if (item.transform) {
  13502. var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
  13503. matrix = new Matrix();
  13504. for (var i = 0, l = transforms.length; i < l; i++) {
  13505. var transform = transforms[i];
  13506. if (!transform)
  13507. break;
  13508. var parts = transform.split(/\(\s*/),
  13509. command = parts[0],
  13510. v = parts[1].split(/[\s,]+/g);
  13511. for (var j = 0, m = v.length; j < m; j++)
  13512. v[j] = parseFloat(v[j]);
  13513. switch (command) {
  13514. case 'matrix':
  13515. matrix.append(
  13516. new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
  13517. break;
  13518. case 'rotate':
  13519. matrix.rotate(v[0], v[1] || 0, v[2] || 0);
  13520. break;
  13521. case 'translate':
  13522. matrix.translate(v[0], v[1] || 0);
  13523. break;
  13524. case 'scale':
  13525. matrix.scale(v);
  13526. break;
  13527. case 'skewX':
  13528. matrix.skew(v[0], 0);
  13529. break;
  13530. case 'skewY':
  13531. matrix.skew(0, v[0]);
  13532. break;
  13533. }
  13534. }
  13535. item.transform(matrix);
  13536. }
  13537. }
  13538. function applyOpacity(item, value, name) {
  13539. var key = name === 'fill-opacity' ? 'getFillColor' : 'getStrokeColor',
  13540. color = item[key] && item[key]();
  13541. if (color)
  13542. color.setAlpha(parseFloat(value));
  13543. }
  13544. var attributes = Base.set(Base.each(SvgStyles, function(entry) {
  13545. this[entry.attribute] = function(item, value) {
  13546. if (item[entry.set]) {
  13547. item[entry.set](convertValue(value, entry.type, entry.fromSVG));
  13548. if (entry.type === 'color') {
  13549. var color = item[entry.get]();
  13550. if (color) {
  13551. if (color._scaleToBounds) {
  13552. var bounds = item.getBounds();
  13553. color.transform(new Matrix()
  13554. .translate(bounds.getPoint())
  13555. .scale(bounds.getSize()));
  13556. }
  13557. }
  13558. }
  13559. }
  13560. };
  13561. }, {}), {
  13562. id: function(item, value) {
  13563. definitions[value] = item;
  13564. if (item.setName)
  13565. item.setName(value);
  13566. },
  13567. 'clip-path': function(item, value) {
  13568. var clip = getDefinition(value);
  13569. if (clip) {
  13570. clip = clip.clone();
  13571. clip.setClipMask(true);
  13572. if (item instanceof Group) {
  13573. item.insertChild(0, clip);
  13574. } else {
  13575. return new Group(clip, item);
  13576. }
  13577. }
  13578. },
  13579. gradientTransform: applyTransform,
  13580. transform: applyTransform,
  13581. 'fill-opacity': applyOpacity,
  13582. 'stroke-opacity': applyOpacity,
  13583. visibility: function(item, value) {
  13584. if (item.setVisible)
  13585. item.setVisible(value === 'visible');
  13586. },
  13587. display: function(item, value) {
  13588. if (item.setVisible)
  13589. item.setVisible(value !== null);
  13590. },
  13591. 'stop-color': function(item, value) {
  13592. if (item.setColor)
  13593. item.setColor(value);
  13594. },
  13595. 'stop-opacity': function(item, value) {
  13596. if (item._color)
  13597. item._color.setAlpha(parseFloat(value));
  13598. },
  13599. offset: function(item, value) {
  13600. if (item.setOffset) {
  13601. var percent = value.match(/(.*)%$/);
  13602. item.setOffset(percent ? percent[1] / 100 : parseFloat(value));
  13603. }
  13604. },
  13605. viewBox: function(item, value, name, node, styles) {
  13606. var rect = new Rectangle(convertValue(value, 'array')),
  13607. size = getSize(node, null, null, true),
  13608. group,
  13609. matrix;
  13610. if (item instanceof Group) {
  13611. var scale = size ? size.divide(rect.getSize()) : 1,
  13612. matrix = new Matrix().scale(scale)
  13613. .translate(rect.getPoint().negate());
  13614. group = item;
  13615. } else if (item instanceof SymbolDefinition) {
  13616. if (size)
  13617. rect.setSize(size);
  13618. group = item._item;
  13619. }
  13620. if (group) {
  13621. if (getAttribute(node, 'overflow', styles) !== 'visible') {
  13622. var clip = new Shape.Rectangle(rect);
  13623. clip.setClipMask(true);
  13624. group.addChild(clip);
  13625. }
  13626. if (matrix)
  13627. group.transform(matrix);
  13628. }
  13629. }
  13630. });
  13631. function getAttribute(node, name, styles) {
  13632. var attr = node.attributes[name],
  13633. value = attr && attr.value;
  13634. if (!value && node.style) {
  13635. var style = Base.camelize(name);
  13636. value = node.style[style];
  13637. if (!value && styles.node[style] !== styles.parent[style])
  13638. value = styles.node[style];
  13639. }
  13640. return !value ? undefined
  13641. : value === 'none' ? null
  13642. : value;
  13643. }
  13644. function applyAttributes(item, node, isRoot) {
  13645. var parent = node.parentNode,
  13646. styles = {
  13647. node: DomElement.getStyles(node) || {},
  13648. parent: !isRoot && !/^defs$/i.test(parent.tagName)
  13649. && DomElement.getStyles(parent) || {}
  13650. };
  13651. Base.each(attributes, function(apply, name) {
  13652. var value = getAttribute(node, name, styles);
  13653. item = value !== undefined
  13654. && apply(item, value, name, node, styles) || item;
  13655. });
  13656. return item;
  13657. }
  13658. function getDefinition(value) {
  13659. var match = value && value.match(/\((?:["'#]*)([^"')]+)/),
  13660. name = match && match[1],
  13661. res = name && definitions[window
  13662. ? name.replace(window.location.href.split('#')[0] + '#', '')
  13663. : name];
  13664. if (res && res._scaleToBounds) {
  13665. res = res.clone();
  13666. res._scaleToBounds = true;
  13667. }
  13668. return res;
  13669. }
  13670. function importNode(node, options, isRoot) {
  13671. var type = node.nodeName.toLowerCase(),
  13672. isElement = type !== '#document',
  13673. body = document.body,
  13674. container,
  13675. parent,
  13676. next;
  13677. if (isRoot && isElement) {
  13678. rootSize = paper.getView().getSize();
  13679. rootSize = getSize(node, null, null, true) || rootSize;
  13680. container = SvgElement.create('svg', {
  13681. style: 'stroke-width: 1px; stroke-miterlimit: 10'
  13682. });
  13683. parent = node.parentNode;
  13684. next = node.nextSibling;
  13685. container.appendChild(node);
  13686. body.appendChild(container);
  13687. }
  13688. var settings = paper.settings,
  13689. applyMatrix = settings.applyMatrix,
  13690. insertItems = settings.insertItems;
  13691. settings.applyMatrix = false;
  13692. settings.insertItems = false;
  13693. var importer = importers[type],
  13694. item = importer && importer(node, type, options, isRoot) || null;
  13695. settings.insertItems = insertItems;
  13696. settings.applyMatrix = applyMatrix;
  13697. if (item) {
  13698. if (isElement && !(item instanceof Group))
  13699. item = applyAttributes(item, node, isRoot);
  13700. var onImport = options.onImport,
  13701. data = isElement && node.getAttribute('data-paper-data');
  13702. if (onImport)
  13703. item = onImport(node, item, options) || item;
  13704. if (options.expandShapes && item instanceof Shape) {
  13705. item.remove();
  13706. item = item.toPath();
  13707. }
  13708. if (data)
  13709. item._data = JSON.parse(data);
  13710. }
  13711. if (container) {
  13712. body.removeChild(container);
  13713. if (parent) {
  13714. if (next) {
  13715. parent.insertBefore(node, next);
  13716. } else {
  13717. parent.appendChild(node);
  13718. }
  13719. }
  13720. }
  13721. if (isRoot) {
  13722. definitions = {};
  13723. if (item && Base.pick(options.applyMatrix, applyMatrix))
  13724. item.matrix.apply(true, true);
  13725. }
  13726. return item;
  13727. }
  13728. function importSVG(source, options, owner) {
  13729. if (!source)
  13730. return null;
  13731. options = typeof options === 'function' ? { onLoad: options }
  13732. : options || {};
  13733. var scope = paper,
  13734. item = null;
  13735. function onLoad(svg) {
  13736. try {
  13737. var node = typeof svg === 'object' ? svg : new self.DOMParser()
  13738. .parseFromString(svg, 'image/svg+xml');
  13739. if (!node.nodeName) {
  13740. node = null;
  13741. throw new Error('Unsupported SVG source: ' + source);
  13742. }
  13743. paper = scope;
  13744. item = importNode(node, options, true);
  13745. if (!options || options.insert !== false) {
  13746. owner._insertItem(undefined, item);
  13747. }
  13748. var onLoad = options.onLoad;
  13749. if (onLoad)
  13750. onLoad(item, svg);
  13751. } catch (e) {
  13752. onError(e);
  13753. }
  13754. }
  13755. function onError(message, status) {
  13756. var onError = options.onError;
  13757. if (onError) {
  13758. onError(message, status);
  13759. } else {
  13760. throw new Error(message);
  13761. }
  13762. }
  13763. if (typeof source === 'string' && !/^.*</.test(source)) {
  13764. var node = document.getElementById(source);
  13765. if (node) {
  13766. onLoad(node);
  13767. } else {
  13768. Http.request({
  13769. url: source,
  13770. async: true,
  13771. onLoad: onLoad,
  13772. onError: onError
  13773. });
  13774. }
  13775. } else if (typeof File !== 'undefined' && source instanceof File) {
  13776. var reader = new FileReader();
  13777. reader.onload = function() {
  13778. onLoad(reader.result);
  13779. };
  13780. reader.onerror = function() {
  13781. onError(reader.error);
  13782. };
  13783. return reader.readAsText(source);
  13784. } else {
  13785. onLoad(source);
  13786. }
  13787. return item;
  13788. }
  13789. Item.inject({
  13790. importSVG: function(node, options) {
  13791. return importSVG(node, options, this);
  13792. }
  13793. });
  13794. Project.inject({
  13795. importSVG: function(node, options) {
  13796. this.activate();
  13797. return importSVG(node, options, this);
  13798. }
  13799. });
  13800. };
  13801. var paper = new (PaperScope.inject(Base.exports, {
  13802. Base: Base,
  13803. Numerical: Numerical,
  13804. Key: Key,
  13805. DomEvent: DomEvent,
  13806. DomElement: DomElement,
  13807. document: document,
  13808. window: window,
  13809. Symbol: SymbolDefinition,
  13810. PlacedSymbol: SymbolItem
  13811. }))();
  13812. if (paper.agent.node) {
  13813. require('./node/extend.js')(paper);
  13814. }
  13815. if (typeof define === 'function' && define.amd) {
  13816. define('paper', paper);
  13817. } else if (typeof module === 'object' && module) {
  13818. module.exports = paper;
  13819. }
  13820. return paper;
  13821. }.call(this, typeof self === 'object' ? self : null);