paper-full.js 417 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494
  1. /*!
  2. * Paper.js v0.11.5 - 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/ & http://jonathanpuckey.com/
  7. *
  8. * Distributed under the MIT license. See LICENSE file for details.
  9. *
  10. * All rights reserved.
  11. *
  12. * Date: Thu Oct 5 16:16:29 2017 +0200
  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. * http://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 = Base.create(type.prototype);
  470. type.apply(res, args);
  471. }
  472. }
  473. } else if (Base.isPlainObject(json)) {
  474. res = {};
  475. if (_setDictionary)
  476. _data.dictionary = res;
  477. for (var key in json)
  478. res[key] = Base.deserialize(json[key], create, _data);
  479. }
  480. return hasDictionary ? res[1] : res;
  481. },
  482. exportJSON: function(obj, options) {
  483. var json = Base.serialize(obj, options);
  484. return options && options.asString == false
  485. ? json
  486. : JSON.stringify(json);
  487. },
  488. importJSON: function(json, target) {
  489. return Base.deserialize(
  490. typeof json === 'string' ? JSON.parse(json) : json,
  491. function(ctor, args, isRoot) {
  492. var useTarget = isRoot && target
  493. && target.constructor === ctor,
  494. obj = useTarget ? target
  495. : Base.create(ctor.prototype);
  496. if (args.length === 1 && obj instanceof Item
  497. && (useTarget || !(obj instanceof Layer))) {
  498. var arg = args[0];
  499. if (Base.isPlainObject(arg))
  500. arg.insert = false;
  501. }
  502. (useTarget ? obj.set : ctor).apply(obj, args);
  503. if (useTarget)
  504. target = null;
  505. return obj;
  506. });
  507. },
  508. splice: function(list, items, index, remove) {
  509. var amount = items && items.length,
  510. append = index === undefined;
  511. index = append ? list.length : index;
  512. if (index > list.length)
  513. index = list.length;
  514. for (var i = 0; i < amount; i++)
  515. items[i]._index = index + i;
  516. if (append) {
  517. list.push.apply(list, items);
  518. return [];
  519. } else {
  520. var args = [index, remove];
  521. if (items)
  522. args.push.apply(args, items);
  523. var removed = list.splice.apply(list, args);
  524. for (var i = 0, l = removed.length; i < l; i++)
  525. removed[i]._index = undefined;
  526. for (var i = index + amount, l = list.length; i < l; i++)
  527. list[i]._index = i;
  528. return removed;
  529. }
  530. },
  531. capitalize: function(str) {
  532. return str.replace(/\b[a-z]/g, function(match) {
  533. return match.toUpperCase();
  534. });
  535. },
  536. camelize: function(str) {
  537. return str.replace(/-(.)/g, function(match, chr) {
  538. return chr.toUpperCase();
  539. });
  540. },
  541. hyphenate: function(str) {
  542. return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
  543. }
  544. }});
  545. var Emitter = {
  546. on: function(type, func) {
  547. if (typeof type !== 'string') {
  548. Base.each(type, function(value, key) {
  549. this.on(key, value);
  550. }, this);
  551. } else {
  552. var types = this._eventTypes,
  553. entry = types && types[type],
  554. handlers = this._callbacks = this._callbacks || {};
  555. handlers = handlers[type] = handlers[type] || [];
  556. if (handlers.indexOf(func) === -1) {
  557. handlers.push(func);
  558. if (entry && entry.install && handlers.length === 1)
  559. entry.install.call(this, type);
  560. }
  561. }
  562. return this;
  563. },
  564. off: function(type, func) {
  565. if (typeof type !== 'string') {
  566. Base.each(type, function(value, key) {
  567. this.off(key, value);
  568. }, this);
  569. return;
  570. }
  571. var types = this._eventTypes,
  572. entry = types && types[type],
  573. handlers = this._callbacks && this._callbacks[type],
  574. index;
  575. if (handlers) {
  576. if (!func || (index = handlers.indexOf(func)) !== -1
  577. && handlers.length === 1) {
  578. if (entry && entry.uninstall)
  579. entry.uninstall.call(this, type);
  580. delete this._callbacks[type];
  581. } else if (index !== -1) {
  582. handlers.splice(index, 1);
  583. }
  584. }
  585. return this;
  586. },
  587. once: function(type, func) {
  588. return this.on(type, function() {
  589. func.apply(this, arguments);
  590. this.off(type, func);
  591. });
  592. },
  593. emit: function(type, event) {
  594. var handlers = this._callbacks && this._callbacks[type];
  595. if (!handlers)
  596. return false;
  597. var args = Base.slice(arguments, 1),
  598. setTarget = event && event.target && !event.currentTarget;
  599. handlers = handlers.slice();
  600. if (setTarget)
  601. event.currentTarget = this;
  602. for (var i = 0, l = handlers.length; i < l; i++) {
  603. if (handlers[i].apply(this, args) == false) {
  604. if (event && event.stop)
  605. event.stop();
  606. break;
  607. }
  608. }
  609. if (setTarget)
  610. delete event.currentTarget;
  611. return true;
  612. },
  613. responds: function(type) {
  614. return !!(this._callbacks && this._callbacks[type]);
  615. },
  616. attach: '#on',
  617. detach: '#off',
  618. fire: '#emit',
  619. _installEvents: function(install) {
  620. var types = this._eventTypes,
  621. handlers = this._callbacks,
  622. key = install ? 'install' : 'uninstall';
  623. if (types) {
  624. for (var type in handlers) {
  625. if (handlers[type].length > 0) {
  626. var entry = types[type],
  627. func = entry && entry[key];
  628. if (func)
  629. func.call(this, type);
  630. }
  631. }
  632. }
  633. },
  634. statics: {
  635. inject: function inject(src) {
  636. var events = src._events;
  637. if (events) {
  638. var types = {};
  639. Base.each(events, function(entry, key) {
  640. var isString = typeof entry === 'string',
  641. name = isString ? entry : key,
  642. part = Base.capitalize(name),
  643. type = name.substring(2).toLowerCase();
  644. types[type] = isString ? {} : entry;
  645. name = '_' + name;
  646. src['get' + part] = function() {
  647. return this[name];
  648. };
  649. src['set' + part] = function(func) {
  650. var prev = this[name];
  651. if (prev)
  652. this.off(type, prev);
  653. if (func)
  654. this.on(type, func);
  655. this[name] = func;
  656. };
  657. });
  658. src._eventTypes = types;
  659. }
  660. return inject.base.apply(this, arguments);
  661. }
  662. }
  663. };
  664. var PaperScope = Base.extend({
  665. _class: 'PaperScope',
  666. initialize: function PaperScope() {
  667. paper = this;
  668. this.settings = new Base({
  669. applyMatrix: true,
  670. insertItems: true,
  671. handleSize: 4,
  672. hitTolerance: 0
  673. });
  674. this.project = null;
  675. this.projects = [];
  676. this.tools = [];
  677. this._id = PaperScope._id++;
  678. PaperScope._scopes[this._id] = this;
  679. var proto = PaperScope.prototype;
  680. if (!this.support) {
  681. var ctx = CanvasProvider.getContext(1, 1) || {};
  682. proto.support = {
  683. nativeDash: 'setLineDash' in ctx || 'mozDash' in ctx,
  684. nativeBlendModes: BlendMode.nativeModes
  685. };
  686. CanvasProvider.release(ctx);
  687. }
  688. if (!this.agent) {
  689. var user = self.navigator.userAgent.toLowerCase(),
  690. os = (/(darwin|win|mac|linux|freebsd|sunos)/.exec(user)||[])[0],
  691. platform = os === 'darwin' ? 'mac' : os,
  692. agent = proto.agent = proto.browser = { platform: platform };
  693. if (platform)
  694. agent[platform] = true;
  695. user.replace(
  696. /(opera|chrome|safari|webkit|firefox|msie|trident|atom|node)\/?\s*([.\d]+)(?:.*version\/([.\d]+))?(?:.*rv\:v?([.\d]+))?/g,
  697. function(match, n, v1, v2, rv) {
  698. if (!agent.chrome) {
  699. var v = n === 'opera' ? v2 :
  700. /^(node|trident)$/.test(n) ? rv : v1;
  701. agent.version = v;
  702. agent.versionNumber = parseFloat(v);
  703. n = n === 'trident' ? 'msie' : n;
  704. agent.name = n;
  705. agent[n] = true;
  706. }
  707. }
  708. );
  709. if (agent.chrome)
  710. delete agent.webkit;
  711. if (agent.atom)
  712. delete agent.chrome;
  713. }
  714. },
  715. version: "0.11.5",
  716. getView: function() {
  717. var project = this.project;
  718. return project && project._view;
  719. },
  720. getPaper: function() {
  721. return this;
  722. },
  723. execute: function(code, options) {
  724. paper.PaperScript.execute(code, this, options);
  725. View.updateFocus();
  726. },
  727. install: function(scope) {
  728. var that = this;
  729. Base.each(['project', 'view', 'tool'], function(key) {
  730. Base.define(scope, key, {
  731. configurable: true,
  732. get: function() {
  733. return that[key];
  734. }
  735. });
  736. });
  737. for (var key in this)
  738. if (!/^_/.test(key) && this[key])
  739. scope[key] = this[key];
  740. },
  741. setup: function(element) {
  742. paper = this;
  743. this.project = new Project(element);
  744. return this;
  745. },
  746. createCanvas: function(width, height) {
  747. return CanvasProvider.getCanvas(width, height);
  748. },
  749. activate: function() {
  750. paper = this;
  751. },
  752. clear: function() {
  753. var projects = this.projects,
  754. tools = this.tools;
  755. for (var i = projects.length - 1; i >= 0; i--)
  756. projects[i].remove();
  757. for (var i = tools.length - 1; i >= 0; i--)
  758. tools[i].remove();
  759. },
  760. remove: function() {
  761. this.clear();
  762. delete PaperScope._scopes[this._id];
  763. },
  764. statics: new function() {
  765. function handleAttribute(name) {
  766. name += 'Attribute';
  767. return function(el, attr) {
  768. return el[name](attr) || el[name]('data-paper-' + attr);
  769. };
  770. }
  771. return {
  772. _scopes: {},
  773. _id: 0,
  774. get: function(id) {
  775. return this._scopes[id] || null;
  776. },
  777. getAttribute: handleAttribute('get'),
  778. hasAttribute: handleAttribute('has')
  779. };
  780. }
  781. });
  782. var PaperScopeItem = Base.extend(Emitter, {
  783. initialize: function(activate) {
  784. this._scope = paper;
  785. this._index = this._scope[this._list].push(this) - 1;
  786. if (activate || !this._scope[this._reference])
  787. this.activate();
  788. },
  789. activate: function() {
  790. if (!this._scope)
  791. return false;
  792. var prev = this._scope[this._reference];
  793. if (prev && prev !== this)
  794. prev.emit('deactivate');
  795. this._scope[this._reference] = this;
  796. this.emit('activate', prev);
  797. return true;
  798. },
  799. isActive: function() {
  800. return this._scope[this._reference] === this;
  801. },
  802. remove: function() {
  803. if (this._index == null)
  804. return false;
  805. Base.splice(this._scope[this._list], null, this._index, 1);
  806. if (this._scope[this._reference] == this)
  807. this._scope[this._reference] = null;
  808. this._scope = null;
  809. return true;
  810. },
  811. getView: function() {
  812. return this._scope.getView();
  813. }
  814. });
  815. var Formatter = Base.extend({
  816. initialize: function(precision) {
  817. this.precision = Base.pick(precision, 5);
  818. this.multiplier = Math.pow(10, this.precision);
  819. },
  820. number: function(val) {
  821. return this.precision < 16
  822. ? Math.round(val * this.multiplier) / this.multiplier : val;
  823. },
  824. pair: function(val1, val2, separator) {
  825. return this.number(val1) + (separator || ',') + this.number(val2);
  826. },
  827. point: function(val, separator) {
  828. return this.number(val.x) + (separator || ',') + this.number(val.y);
  829. },
  830. size: function(val, separator) {
  831. return this.number(val.width) + (separator || ',')
  832. + this.number(val.height);
  833. },
  834. rectangle: function(val, separator) {
  835. return this.point(val, separator) + (separator || ',')
  836. + this.size(val, separator);
  837. }
  838. });
  839. Formatter.instance = new Formatter();
  840. var Numerical = new function() {
  841. var abscissas = [
  842. [ 0.5773502691896257645091488],
  843. [0,0.7745966692414833770358531],
  844. [ 0.3399810435848562648026658,0.8611363115940525752239465],
  845. [0,0.5384693101056830910363144,0.9061798459386639927976269],
  846. [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016],
  847. [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897],
  848. [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609],
  849. [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762],
  850. [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640],
  851. [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380],
  852. [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491],
  853. [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294],
  854. [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973],
  855. [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657],
  856. [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542]
  857. ];
  858. var weights = [
  859. [1],
  860. [0.8888888888888888888888889,0.5555555555555555555555556],
  861. [0.6521451548625461426269361,0.3478548451374538573730639],
  862. [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640],
  863. [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961],
  864. [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114],
  865. [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314],
  866. [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922],
  867. [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688],
  868. [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537],
  869. [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160],
  870. [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216],
  871. [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329],
  872. [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284],
  873. [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806]
  874. ];
  875. var abs = Math.abs,
  876. sqrt = Math.sqrt,
  877. pow = Math.pow,
  878. log2 = Math.log2 || function(x) {
  879. return Math.log(x) * Math.LOG2E;
  880. },
  881. EPSILON = 1e-12,
  882. MACHINE_EPSILON = 1.12e-16;
  883. function clamp(value, min, max) {
  884. return value < min ? min : value > max ? max : value;
  885. }
  886. function getDiscriminant(a, b, c) {
  887. function split(v) {
  888. var x = v * 134217729,
  889. y = v - x,
  890. hi = y + x,
  891. lo = v - hi;
  892. return [hi, lo];
  893. }
  894. var D = b * b - a * c,
  895. E = b * b + a * c;
  896. if (abs(D) * 3 < E) {
  897. var ad = split(a),
  898. bd = split(b),
  899. cd = split(c),
  900. p = b * b,
  901. dp = (bd[0] * bd[0] - p + 2 * bd[0] * bd[1]) + bd[1] * bd[1],
  902. q = a * c,
  903. dq = (ad[0] * cd[0] - q + ad[0] * cd[1] + ad[1] * cd[0])
  904. + ad[1] * cd[1];
  905. D = (p - q) + (dp - dq);
  906. }
  907. return D;
  908. }
  909. function getNormalizationFactor() {
  910. var norm = Math.max.apply(Math, arguments);
  911. return norm && (norm < 1e-8 || norm > 1e8)
  912. ? pow(2, -Math.round(log2(norm)))
  913. : 0;
  914. }
  915. return {
  916. EPSILON: EPSILON,
  917. MACHINE_EPSILON: MACHINE_EPSILON,
  918. CURVETIME_EPSILON: 1e-8,
  919. GEOMETRIC_EPSILON: 1e-7,
  920. TRIGONOMETRIC_EPSILON: 1e-8,
  921. KAPPA: 4 * (sqrt(2) - 1) / 3,
  922. isZero: function(val) {
  923. return val >= -EPSILON && val <= EPSILON;
  924. },
  925. clamp: clamp,
  926. integrate: function(f, a, b, n) {
  927. var x = abscissas[n - 2],
  928. w = weights[n - 2],
  929. A = (b - a) * 0.5,
  930. B = A + a,
  931. i = 0,
  932. m = (n + 1) >> 1,
  933. sum = n & 1 ? w[i++] * f(B) : 0;
  934. while (i < m) {
  935. var Ax = A * x[i];
  936. sum += w[i++] * (f(B + Ax) + f(B - Ax));
  937. }
  938. return A * sum;
  939. },
  940. findRoot: function(f, df, x, a, b, n, tolerance) {
  941. for (var i = 0; i < n; i++) {
  942. var fx = f(x),
  943. dx = fx / df(x),
  944. nx = x - dx;
  945. if (abs(dx) < tolerance) {
  946. x = nx;
  947. break;
  948. }
  949. if (fx > 0) {
  950. b = x;
  951. x = nx <= a ? (a + b) * 0.5 : nx;
  952. } else {
  953. a = x;
  954. x = nx >= b ? (a + b) * 0.5 : nx;
  955. }
  956. }
  957. return clamp(x, a, b);
  958. },
  959. solveQuadratic: function(a, b, c, roots, min, max) {
  960. var x1, x2 = Infinity;
  961. if (abs(a) < EPSILON) {
  962. if (abs(b) < EPSILON)
  963. return abs(c) < EPSILON ? -1 : 0;
  964. x1 = -c / b;
  965. } else {
  966. b *= -0.5;
  967. var D = getDiscriminant(a, b, c);
  968. if (D && abs(D) < MACHINE_EPSILON) {
  969. var f = getNormalizationFactor(abs(a), abs(b), abs(c));
  970. if (f) {
  971. a *= f;
  972. b *= f;
  973. c *= f;
  974. D = getDiscriminant(a, b, c);
  975. }
  976. }
  977. if (D >= -MACHINE_EPSILON) {
  978. var Q = D < 0 ? 0 : sqrt(D),
  979. R = b + (b < 0 ? -Q : Q);
  980. if (R === 0) {
  981. x1 = c / a;
  982. x2 = -x1;
  983. } else {
  984. x1 = R / a;
  985. x2 = c / R;
  986. }
  987. }
  988. }
  989. var count = 0,
  990. boundless = min == null,
  991. minB = min - EPSILON,
  992. maxB = max + EPSILON;
  993. if (isFinite(x1) && (boundless || x1 > minB && x1 < maxB))
  994. roots[count++] = boundless ? x1 : clamp(x1, min, max);
  995. if (x2 !== x1
  996. && isFinite(x2) && (boundless || x2 > minB && x2 < maxB))
  997. roots[count++] = boundless ? x2 : clamp(x2, min, max);
  998. return count;
  999. },
  1000. solveCubic: function(a, b, c, d, roots, min, max) {
  1001. var f = getNormalizationFactor(abs(a), abs(b), abs(c), abs(d)),
  1002. x, b1, c2, qd, q;
  1003. if (f) {
  1004. a *= f;
  1005. b *= f;
  1006. c *= f;
  1007. d *= f;
  1008. }
  1009. function evaluate(x0) {
  1010. x = x0;
  1011. var tmp = a * x;
  1012. b1 = tmp + b;
  1013. c2 = b1 * x + c;
  1014. qd = (tmp + b1) * x + c2;
  1015. q = c2 * x + d;
  1016. }
  1017. if (abs(a) < EPSILON) {
  1018. a = b;
  1019. b1 = c;
  1020. c2 = d;
  1021. x = Infinity;
  1022. } else if (abs(d) < EPSILON) {
  1023. b1 = b;
  1024. c2 = c;
  1025. x = 0;
  1026. } else {
  1027. evaluate(-(b / a) / 3);
  1028. var t = q / a,
  1029. r = pow(abs(t), 1/3),
  1030. s = t < 0 ? -1 : 1,
  1031. td = -qd / a,
  1032. rd = td > 0 ? 1.324717957244746 * Math.max(r, sqrt(td)) : r,
  1033. x0 = x - s * rd;
  1034. if (x0 !== x) {
  1035. do {
  1036. evaluate(x0);
  1037. x0 = qd === 0 ? x : x - q / qd / (1 + MACHINE_EPSILON);
  1038. } while (s * x0 > s * x);
  1039. if (abs(a) * x * x > abs(d / x)) {
  1040. c2 = -d / x;
  1041. b1 = (c2 - c) / x;
  1042. }
  1043. }
  1044. }
  1045. var count = Numerical.solveQuadratic(a, b1, c2, roots, min, max),
  1046. boundless = min == null;
  1047. if (isFinite(x) && (count === 0
  1048. || count > 0 && x !== roots[0] && x !== roots[1])
  1049. && (boundless || x > min - EPSILON && x < max + EPSILON))
  1050. roots[count++] = boundless ? x : clamp(x, min, max);
  1051. return count;
  1052. }
  1053. };
  1054. };
  1055. var UID = {
  1056. _id: 1,
  1057. _pools: {},
  1058. get: function(name) {
  1059. if (name) {
  1060. var pool = this._pools[name];
  1061. if (!pool)
  1062. pool = this._pools[name] = { _id: 1 };
  1063. return pool._id++;
  1064. } else {
  1065. return this._id++;
  1066. }
  1067. }
  1068. };
  1069. var Point = Base.extend({
  1070. _class: 'Point',
  1071. _readIndex: true,
  1072. initialize: function Point(arg0, arg1) {
  1073. var type = typeof arg0,
  1074. reading = this.__read,
  1075. read = 0;
  1076. if (type === 'number') {
  1077. var hasY = typeof arg1 === 'number';
  1078. this._set(arg0, hasY ? arg1 : arg0);
  1079. if (reading)
  1080. read = hasY ? 2 : 1;
  1081. } else if (type === 'undefined' || arg0 === null) {
  1082. this._set(0, 0);
  1083. if (reading)
  1084. read = arg0 === null ? 1 : 0;
  1085. } else {
  1086. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1087. read = 1;
  1088. if (Array.isArray(obj)) {
  1089. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1090. } else if ('x' in obj) {
  1091. this._set(obj.x || 0, obj.y || 0);
  1092. } else if ('width' in obj) {
  1093. this._set(obj.width || 0, obj.height || 0);
  1094. } else if ('angle' in obj) {
  1095. this._set(obj.length || 0, 0);
  1096. this.setAngle(obj.angle || 0);
  1097. } else {
  1098. this._set(0, 0);
  1099. read = 0;
  1100. }
  1101. }
  1102. if (reading)
  1103. this.__read = read;
  1104. return this;
  1105. },
  1106. set: '#initialize',
  1107. _set: function(x, y) {
  1108. this.x = x;
  1109. this.y = y;
  1110. return this;
  1111. },
  1112. equals: function(point) {
  1113. return this === point || point
  1114. && (this.x === point.x && this.y === point.y
  1115. || Array.isArray(point)
  1116. && this.x === point[0] && this.y === point[1])
  1117. || false;
  1118. },
  1119. clone: function() {
  1120. return new Point(this.x, this.y);
  1121. },
  1122. toString: function() {
  1123. var f = Formatter.instance;
  1124. return '{ x: ' + f.number(this.x) + ', y: ' + f.number(this.y) + ' }';
  1125. },
  1126. _serialize: function(options) {
  1127. var f = options.formatter;
  1128. return [f.number(this.x), f.number(this.y)];
  1129. },
  1130. getLength: function() {
  1131. return Math.sqrt(this.x * this.x + this.y * this.y);
  1132. },
  1133. setLength: function(length) {
  1134. if (this.isZero()) {
  1135. var angle = this._angle || 0;
  1136. this._set(
  1137. Math.cos(angle) * length,
  1138. Math.sin(angle) * length
  1139. );
  1140. } else {
  1141. var scale = length / this.getLength();
  1142. if (Numerical.isZero(scale))
  1143. this.getAngle();
  1144. this._set(
  1145. this.x * scale,
  1146. this.y * scale
  1147. );
  1148. }
  1149. },
  1150. getAngle: function() {
  1151. return this.getAngleInRadians.apply(this, arguments) * 180 / Math.PI;
  1152. },
  1153. setAngle: function(angle) {
  1154. this.setAngleInRadians.call(this, angle * Math.PI / 180);
  1155. },
  1156. getAngleInDegrees: '#getAngle',
  1157. setAngleInDegrees: '#setAngle',
  1158. getAngleInRadians: function() {
  1159. if (!arguments.length) {
  1160. return this.isZero()
  1161. ? this._angle || 0
  1162. : this._angle = Math.atan2(this.y, this.x);
  1163. } else {
  1164. var point = Point.read(arguments),
  1165. div = this.getLength() * point.getLength();
  1166. if (Numerical.isZero(div)) {
  1167. return NaN;
  1168. } else {
  1169. var a = this.dot(point) / div;
  1170. return Math.acos(a < -1 ? -1 : a > 1 ? 1 : a);
  1171. }
  1172. }
  1173. },
  1174. setAngleInRadians: function(angle) {
  1175. this._angle = angle;
  1176. if (!this.isZero()) {
  1177. var length = this.getLength();
  1178. this._set(
  1179. Math.cos(angle) * length,
  1180. Math.sin(angle) * length
  1181. );
  1182. }
  1183. },
  1184. getQuadrant: function() {
  1185. return this.x >= 0 ? this.y >= 0 ? 1 : 4 : this.y >= 0 ? 2 : 3;
  1186. }
  1187. }, {
  1188. beans: false,
  1189. getDirectedAngle: function() {
  1190. var point = Point.read(arguments);
  1191. return Math.atan2(this.cross(point), this.dot(point)) * 180 / Math.PI;
  1192. },
  1193. getDistance: function() {
  1194. var point = Point.read(arguments),
  1195. x = point.x - this.x,
  1196. y = point.y - this.y,
  1197. d = x * x + y * y,
  1198. squared = Base.read(arguments);
  1199. return squared ? d : Math.sqrt(d);
  1200. },
  1201. normalize: function(length) {
  1202. if (length === undefined)
  1203. length = 1;
  1204. var current = this.getLength(),
  1205. scale = current !== 0 ? length / current : 0,
  1206. point = new Point(this.x * scale, this.y * scale);
  1207. if (scale >= 0)
  1208. point._angle = this._angle;
  1209. return point;
  1210. },
  1211. rotate: function(angle, center) {
  1212. if (angle === 0)
  1213. return this.clone();
  1214. angle = angle * Math.PI / 180;
  1215. var point = center ? this.subtract(center) : this,
  1216. sin = Math.sin(angle),
  1217. cos = Math.cos(angle);
  1218. point = new Point(
  1219. point.x * cos - point.y * sin,
  1220. point.x * sin + point.y * cos
  1221. );
  1222. return center ? point.add(center) : point;
  1223. },
  1224. transform: function(matrix) {
  1225. return matrix ? matrix._transformPoint(this) : this;
  1226. },
  1227. add: function() {
  1228. var point = Point.read(arguments);
  1229. return new Point(this.x + point.x, this.y + point.y);
  1230. },
  1231. subtract: function() {
  1232. var point = Point.read(arguments);
  1233. return new Point(this.x - point.x, this.y - point.y);
  1234. },
  1235. multiply: function() {
  1236. var point = Point.read(arguments);
  1237. return new Point(this.x * point.x, this.y * point.y);
  1238. },
  1239. divide: function() {
  1240. var point = Point.read(arguments);
  1241. return new Point(this.x / point.x, this.y / point.y);
  1242. },
  1243. modulo: function() {
  1244. var point = Point.read(arguments);
  1245. return new Point(this.x % point.x, this.y % point.y);
  1246. },
  1247. negate: function() {
  1248. return new Point(-this.x, -this.y);
  1249. },
  1250. isInside: function() {
  1251. return Rectangle.read(arguments).contains(this);
  1252. },
  1253. isClose: function() {
  1254. var point = Point.read(arguments),
  1255. tolerance = Base.read(arguments);
  1256. return this.getDistance(point) <= tolerance;
  1257. },
  1258. isCollinear: function() {
  1259. var point = Point.read(arguments);
  1260. return Point.isCollinear(this.x, this.y, point.x, point.y);
  1261. },
  1262. isColinear: '#isCollinear',
  1263. isOrthogonal: function() {
  1264. var point = Point.read(arguments);
  1265. return Point.isOrthogonal(this.x, this.y, point.x, point.y);
  1266. },
  1267. isZero: function() {
  1268. var isZero = Numerical.isZero;
  1269. return isZero(this.x) && isZero(this.y);
  1270. },
  1271. isNaN: function() {
  1272. return isNaN(this.x) || isNaN(this.y);
  1273. },
  1274. isInQuadrant: function(q) {
  1275. return this.x * (q > 1 && q < 4 ? -1 : 1) >= 0
  1276. && this.y * (q > 2 ? -1 : 1) >= 0;
  1277. },
  1278. dot: function() {
  1279. var point = Point.read(arguments);
  1280. return this.x * point.x + this.y * point.y;
  1281. },
  1282. cross: function() {
  1283. var point = Point.read(arguments);
  1284. return this.x * point.y - this.y * point.x;
  1285. },
  1286. project: function() {
  1287. var point = Point.read(arguments),
  1288. scale = point.isZero() ? 0 : this.dot(point) / point.dot(point);
  1289. return new Point(
  1290. point.x * scale,
  1291. point.y * scale
  1292. );
  1293. },
  1294. statics: {
  1295. min: function() {
  1296. var point1 = Point.read(arguments),
  1297. point2 = Point.read(arguments);
  1298. return new Point(
  1299. Math.min(point1.x, point2.x),
  1300. Math.min(point1.y, point2.y)
  1301. );
  1302. },
  1303. max: function() {
  1304. var point1 = Point.read(arguments),
  1305. point2 = Point.read(arguments);
  1306. return new Point(
  1307. Math.max(point1.x, point2.x),
  1308. Math.max(point1.y, point2.y)
  1309. );
  1310. },
  1311. random: function() {
  1312. return new Point(Math.random(), Math.random());
  1313. },
  1314. isCollinear: function(x1, y1, x2, y2) {
  1315. return Math.abs(x1 * y2 - y1 * x2)
  1316. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1317. * 1e-8;
  1318. },
  1319. isOrthogonal: function(x1, y1, x2, y2) {
  1320. return Math.abs(x1 * x2 + y1 * y2)
  1321. <= Math.sqrt((x1 * x1 + y1 * y1) * (x2 * x2 + y2 * y2))
  1322. * 1e-8;
  1323. }
  1324. }
  1325. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1326. var op = Math[key];
  1327. this[key] = function() {
  1328. return new Point(op(this.x), op(this.y));
  1329. };
  1330. }, {}));
  1331. var LinkedPoint = Point.extend({
  1332. initialize: function Point(x, y, owner, setter) {
  1333. this._x = x;
  1334. this._y = y;
  1335. this._owner = owner;
  1336. this._setter = setter;
  1337. },
  1338. _set: function(x, y, _dontNotify) {
  1339. this._x = x;
  1340. this._y = y;
  1341. if (!_dontNotify)
  1342. this._owner[this._setter](this);
  1343. return this;
  1344. },
  1345. getX: function() {
  1346. return this._x;
  1347. },
  1348. setX: function(x) {
  1349. this._x = x;
  1350. this._owner[this._setter](this);
  1351. },
  1352. getY: function() {
  1353. return this._y;
  1354. },
  1355. setY: function(y) {
  1356. this._y = y;
  1357. this._owner[this._setter](this);
  1358. },
  1359. isSelected: function() {
  1360. return !!(this._owner._selection & this._getSelection());
  1361. },
  1362. setSelected: function(selected) {
  1363. this._owner._changeSelection(this._getSelection(), selected);
  1364. },
  1365. _getSelection: function() {
  1366. return this._setter === 'setPosition' ? 4 : 0;
  1367. }
  1368. });
  1369. var Size = Base.extend({
  1370. _class: 'Size',
  1371. _readIndex: true,
  1372. initialize: function Size(arg0, arg1) {
  1373. var type = typeof arg0,
  1374. reading = this.__read,
  1375. read = 0;
  1376. if (type === 'number') {
  1377. var hasHeight = typeof arg1 === 'number';
  1378. this._set(arg0, hasHeight ? arg1 : arg0);
  1379. if (reading)
  1380. read = hasHeight ? 2 : 1;
  1381. } else if (type === 'undefined' || arg0 === null) {
  1382. this._set(0, 0);
  1383. if (reading)
  1384. read = arg0 === null ? 1 : 0;
  1385. } else {
  1386. var obj = type === 'string' ? arg0.split(/[\s,]+/) || [] : arg0;
  1387. read = 1;
  1388. if (Array.isArray(obj)) {
  1389. this._set(+obj[0], +(obj.length > 1 ? obj[1] : obj[0]));
  1390. } else if ('width' in obj) {
  1391. this._set(obj.width || 0, obj.height || 0);
  1392. } else if ('x' in obj) {
  1393. this._set(obj.x || 0, obj.y || 0);
  1394. } else {
  1395. this._set(0, 0);
  1396. read = 0;
  1397. }
  1398. }
  1399. if (reading)
  1400. this.__read = read;
  1401. return this;
  1402. },
  1403. set: '#initialize',
  1404. _set: function(width, height) {
  1405. this.width = width;
  1406. this.height = height;
  1407. return this;
  1408. },
  1409. equals: function(size) {
  1410. return size === this || size && (this.width === size.width
  1411. && this.height === size.height
  1412. || Array.isArray(size) && this.width === size[0]
  1413. && this.height === size[1]) || false;
  1414. },
  1415. clone: function() {
  1416. return new Size(this.width, this.height);
  1417. },
  1418. toString: function() {
  1419. var f = Formatter.instance;
  1420. return '{ width: ' + f.number(this.width)
  1421. + ', height: ' + f.number(this.height) + ' }';
  1422. },
  1423. _serialize: function(options) {
  1424. var f = options.formatter;
  1425. return [f.number(this.width),
  1426. f.number(this.height)];
  1427. },
  1428. add: function() {
  1429. var size = Size.read(arguments);
  1430. return new Size(this.width + size.width, this.height + size.height);
  1431. },
  1432. subtract: function() {
  1433. var size = Size.read(arguments);
  1434. return new Size(this.width - size.width, this.height - size.height);
  1435. },
  1436. multiply: function() {
  1437. var size = Size.read(arguments);
  1438. return new Size(this.width * size.width, this.height * size.height);
  1439. },
  1440. divide: function() {
  1441. var size = Size.read(arguments);
  1442. return new Size(this.width / size.width, this.height / size.height);
  1443. },
  1444. modulo: function() {
  1445. var size = Size.read(arguments);
  1446. return new Size(this.width % size.width, this.height % size.height);
  1447. },
  1448. negate: function() {
  1449. return new Size(-this.width, -this.height);
  1450. },
  1451. isZero: function() {
  1452. var isZero = Numerical.isZero;
  1453. return isZero(this.width) && isZero(this.height);
  1454. },
  1455. isNaN: function() {
  1456. return isNaN(this.width) || isNaN(this.height);
  1457. },
  1458. statics: {
  1459. min: function(size1, size2) {
  1460. return new Size(
  1461. Math.min(size1.width, size2.width),
  1462. Math.min(size1.height, size2.height));
  1463. },
  1464. max: function(size1, size2) {
  1465. return new Size(
  1466. Math.max(size1.width, size2.width),
  1467. Math.max(size1.height, size2.height));
  1468. },
  1469. random: function() {
  1470. return new Size(Math.random(), Math.random());
  1471. }
  1472. }
  1473. }, Base.each(['round', 'ceil', 'floor', 'abs'], function(key) {
  1474. var op = Math[key];
  1475. this[key] = function() {
  1476. return new Size(op(this.width), op(this.height));
  1477. };
  1478. }, {}));
  1479. var LinkedSize = Size.extend({
  1480. initialize: function Size(width, height, owner, setter) {
  1481. this._width = width;
  1482. this._height = height;
  1483. this._owner = owner;
  1484. this._setter = setter;
  1485. },
  1486. _set: function(width, height, _dontNotify) {
  1487. this._width = width;
  1488. this._height = height;
  1489. if (!_dontNotify)
  1490. this._owner[this._setter](this);
  1491. return this;
  1492. },
  1493. getWidth: function() {
  1494. return this._width;
  1495. },
  1496. setWidth: function(width) {
  1497. this._width = width;
  1498. this._owner[this._setter](this);
  1499. },
  1500. getHeight: function() {
  1501. return this._height;
  1502. },
  1503. setHeight: function(height) {
  1504. this._height = height;
  1505. this._owner[this._setter](this);
  1506. }
  1507. });
  1508. var Rectangle = Base.extend({
  1509. _class: 'Rectangle',
  1510. _readIndex: true,
  1511. beans: true,
  1512. initialize: function Rectangle(arg0, arg1, arg2, arg3) {
  1513. var type = typeof arg0,
  1514. read;
  1515. if (type === 'number') {
  1516. this._set(arg0, arg1, arg2, arg3);
  1517. read = 4;
  1518. } else if (type === 'undefined' || arg0 === null) {
  1519. this._set(0, 0, 0, 0);
  1520. read = arg0 === null ? 1 : 0;
  1521. } else if (arguments.length === 1) {
  1522. if (Array.isArray(arg0)) {
  1523. this._set.apply(this, arg0);
  1524. read = 1;
  1525. } else if (arg0.x !== undefined || arg0.width !== undefined) {
  1526. this._set(arg0.x || 0, arg0.y || 0,
  1527. arg0.width || 0, arg0.height || 0);
  1528. read = 1;
  1529. } else if (arg0.from === undefined && arg0.to === undefined) {
  1530. this._set(0, 0, 0, 0);
  1531. Base.filter(this, arg0);
  1532. read = 1;
  1533. }
  1534. }
  1535. if (read === undefined) {
  1536. var frm = Point.readNamed(arguments, 'from'),
  1537. next = Base.peek(arguments),
  1538. x = frm.x,
  1539. y = frm.y,
  1540. width,
  1541. height;
  1542. if (next && next.x !== undefined
  1543. || Base.hasNamed(arguments, 'to')) {
  1544. var to = Point.readNamed(arguments, 'to');
  1545. width = to.x - x;
  1546. height = to.y - y;
  1547. if (width < 0) {
  1548. x = to.x;
  1549. width = -width;
  1550. }
  1551. if (height < 0) {
  1552. y = to.y;
  1553. height = -height;
  1554. }
  1555. } else {
  1556. var size = Size.read(arguments);
  1557. width = size.width;
  1558. height = size.height;
  1559. }
  1560. this._set(x, y, width, height);
  1561. read = arguments.__index;
  1562. var filtered = arguments.__filtered;
  1563. if (filtered)
  1564. this.__filtered = filtered;
  1565. }
  1566. if (this.__read)
  1567. this.__read = read;
  1568. return this;
  1569. },
  1570. set: '#initialize',
  1571. _set: function(x, y, width, height) {
  1572. this.x = x;
  1573. this.y = y;
  1574. this.width = width;
  1575. this.height = height;
  1576. return this;
  1577. },
  1578. clone: function() {
  1579. return new Rectangle(this.x, this.y, this.width, this.height);
  1580. },
  1581. equals: function(rect) {
  1582. var rt = Base.isPlainValue(rect)
  1583. ? Rectangle.read(arguments)
  1584. : rect;
  1585. return rt === this
  1586. || rt && this.x === rt.x && this.y === rt.y
  1587. && this.width === rt.width && this.height === rt.height
  1588. || false;
  1589. },
  1590. toString: function() {
  1591. var f = Formatter.instance;
  1592. return '{ x: ' + f.number(this.x)
  1593. + ', y: ' + f.number(this.y)
  1594. + ', width: ' + f.number(this.width)
  1595. + ', height: ' + f.number(this.height)
  1596. + ' }';
  1597. },
  1598. _serialize: function(options) {
  1599. var f = options.formatter;
  1600. return [f.number(this.x),
  1601. f.number(this.y),
  1602. f.number(this.width),
  1603. f.number(this.height)];
  1604. },
  1605. getPoint: function(_dontLink) {
  1606. var ctor = _dontLink ? Point : LinkedPoint;
  1607. return new ctor(this.x, this.y, this, 'setPoint');
  1608. },
  1609. setPoint: function() {
  1610. var point = Point.read(arguments);
  1611. this.x = point.x;
  1612. this.y = point.y;
  1613. },
  1614. getSize: function(_dontLink) {
  1615. var ctor = _dontLink ? Size : LinkedSize;
  1616. return new ctor(this.width, this.height, this, 'setSize');
  1617. },
  1618. _fw: 1,
  1619. _fh: 1,
  1620. setSize: function() {
  1621. var size = Size.read(arguments),
  1622. sx = this._sx,
  1623. sy = this._sy,
  1624. w = size.width,
  1625. h = size.height;
  1626. if (sx) {
  1627. this.x += (this.width - w) * sx;
  1628. }
  1629. if (sy) {
  1630. this.y += (this.height - h) * sy;
  1631. }
  1632. this.width = w;
  1633. this.height = h;
  1634. this._fw = this._fh = 1;
  1635. },
  1636. getLeft: function() {
  1637. return this.x;
  1638. },
  1639. setLeft: function(left) {
  1640. if (!this._fw) {
  1641. var amount = left - this.x;
  1642. this.width -= this._sx === 0.5 ? amount * 2 : amount;
  1643. }
  1644. this.x = left;
  1645. this._sx = this._fw = 0;
  1646. },
  1647. getTop: function() {
  1648. return this.y;
  1649. },
  1650. setTop: function(top) {
  1651. if (!this._fh) {
  1652. var amount = top - this.y;
  1653. this.height -= this._sy === 0.5 ? amount * 2 : amount;
  1654. }
  1655. this.y = top;
  1656. this._sy = this._fh = 0;
  1657. },
  1658. getRight: function() {
  1659. return this.x + this.width;
  1660. },
  1661. setRight: function(right) {
  1662. if (!this._fw) {
  1663. var amount = right - this.x;
  1664. this.width = this._sx === 0.5 ? amount * 2 : amount;
  1665. }
  1666. this.x = right - this.width;
  1667. this._sx = 1;
  1668. this._fw = 0;
  1669. },
  1670. getBottom: function() {
  1671. return this.y + this.height;
  1672. },
  1673. setBottom: function(bottom) {
  1674. if (!this._fh) {
  1675. var amount = bottom - this.y;
  1676. this.height = this._sy === 0.5 ? amount * 2 : amount;
  1677. }
  1678. this.y = bottom - this.height;
  1679. this._sy = 1;
  1680. this._fh = 0;
  1681. },
  1682. getCenterX: function() {
  1683. return this.x + this.width / 2;
  1684. },
  1685. setCenterX: function(x) {
  1686. if (this._fw || this._sx === 0.5) {
  1687. this.x = x - this.width / 2;
  1688. } else {
  1689. if (this._sx) {
  1690. this.x += (x - this.x) * 2 * this._sx;
  1691. }
  1692. this.width = (x - this.x) * 2;
  1693. }
  1694. this._sx = 0.5;
  1695. this._fw = 0;
  1696. },
  1697. getCenterY: function() {
  1698. return this.y + this.height / 2;
  1699. },
  1700. setCenterY: function(y) {
  1701. if (this._fh || this._sy === 0.5) {
  1702. this.y = y - this.height / 2;
  1703. } else {
  1704. if (this._sy) {
  1705. this.y += (y - this.y) * 2 * this._sy;
  1706. }
  1707. this.height = (y - this.y) * 2;
  1708. }
  1709. this._sy = 0.5;
  1710. this._fh = 0;
  1711. },
  1712. getCenter: function(_dontLink) {
  1713. var ctor = _dontLink ? Point : LinkedPoint;
  1714. return new ctor(this.getCenterX(), this.getCenterY(), this, 'setCenter');
  1715. },
  1716. setCenter: function() {
  1717. var point = Point.read(arguments);
  1718. this.setCenterX(point.x);
  1719. this.setCenterY(point.y);
  1720. return this;
  1721. },
  1722. getArea: function() {
  1723. return this.width * this.height;
  1724. },
  1725. isEmpty: function() {
  1726. return this.width === 0 || this.height === 0;
  1727. },
  1728. contains: function(arg) {
  1729. return arg && arg.width !== undefined
  1730. || (Array.isArray(arg) ? arg : arguments).length === 4
  1731. ? this._containsRectangle(Rectangle.read(arguments))
  1732. : this._containsPoint(Point.read(arguments));
  1733. },
  1734. _containsPoint: function(point) {
  1735. var x = point.x,
  1736. y = point.y;
  1737. return x >= this.x && y >= this.y
  1738. && x <= this.x + this.width
  1739. && y <= this.y + this.height;
  1740. },
  1741. _containsRectangle: function(rect) {
  1742. var x = rect.x,
  1743. y = rect.y;
  1744. return x >= this.x && y >= this.y
  1745. && x + rect.width <= this.x + this.width
  1746. && y + rect.height <= this.y + this.height;
  1747. },
  1748. intersects: function() {
  1749. var rect = Rectangle.read(arguments),
  1750. epsilon = Base.read(arguments) || 0;
  1751. return rect.x + rect.width > this.x - epsilon
  1752. && rect.y + rect.height > this.y - epsilon
  1753. && rect.x < this.x + this.width + epsilon
  1754. && rect.y < this.y + this.height + epsilon;
  1755. },
  1756. intersect: function() {
  1757. var rect = Rectangle.read(arguments),
  1758. x1 = Math.max(this.x, rect.x),
  1759. y1 = Math.max(this.y, rect.y),
  1760. x2 = Math.min(this.x + this.width, rect.x + rect.width),
  1761. y2 = Math.min(this.y + this.height, rect.y + rect.height);
  1762. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1763. },
  1764. unite: function() {
  1765. var rect = Rectangle.read(arguments),
  1766. x1 = Math.min(this.x, rect.x),
  1767. y1 = Math.min(this.y, rect.y),
  1768. x2 = Math.max(this.x + this.width, rect.x + rect.width),
  1769. y2 = Math.max(this.y + this.height, rect.y + rect.height);
  1770. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1771. },
  1772. include: function() {
  1773. var point = Point.read(arguments);
  1774. var x1 = Math.min(this.x, point.x),
  1775. y1 = Math.min(this.y, point.y),
  1776. x2 = Math.max(this.x + this.width, point.x),
  1777. y2 = Math.max(this.y + this.height, point.y);
  1778. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  1779. },
  1780. expand: function() {
  1781. var amount = Size.read(arguments),
  1782. hor = amount.width,
  1783. ver = amount.height;
  1784. return new Rectangle(this.x - hor / 2, this.y - ver / 2,
  1785. this.width + hor, this.height + ver);
  1786. },
  1787. scale: function(hor, ver) {
  1788. return this.expand(this.width * hor - this.width,
  1789. this.height * (ver === undefined ? hor : ver) - this.height);
  1790. }
  1791. }, Base.each([
  1792. ['Top', 'Left'], ['Top', 'Right'],
  1793. ['Bottom', 'Left'], ['Bottom', 'Right'],
  1794. ['Left', 'Center'], ['Top', 'Center'],
  1795. ['Right', 'Center'], ['Bottom', 'Center']
  1796. ],
  1797. function(parts, index) {
  1798. var part = parts.join(''),
  1799. xFirst = /^[RL]/.test(part);
  1800. if (index >= 4)
  1801. parts[1] += xFirst ? 'Y' : 'X';
  1802. var x = parts[xFirst ? 0 : 1],
  1803. y = parts[xFirst ? 1 : 0],
  1804. getX = 'get' + x,
  1805. getY = 'get' + y,
  1806. setX = 'set' + x,
  1807. setY = 'set' + y,
  1808. get = 'get' + part,
  1809. set = 'set' + part;
  1810. this[get] = function(_dontLink) {
  1811. var ctor = _dontLink ? Point : LinkedPoint;
  1812. return new ctor(this[getX](), this[getY](), this, set);
  1813. };
  1814. this[set] = function() {
  1815. var point = Point.read(arguments);
  1816. this[setX](point.x);
  1817. this[setY](point.y);
  1818. };
  1819. }, {
  1820. beans: true
  1821. }
  1822. ));
  1823. var LinkedRectangle = Rectangle.extend({
  1824. initialize: function Rectangle(x, y, width, height, owner, setter) {
  1825. this._set(x, y, width, height, true);
  1826. this._owner = owner;
  1827. this._setter = setter;
  1828. },
  1829. _set: function(x, y, width, height, _dontNotify) {
  1830. this._x = x;
  1831. this._y = y;
  1832. this._width = width;
  1833. this._height = height;
  1834. if (!_dontNotify)
  1835. this._owner[this._setter](this);
  1836. return this;
  1837. }
  1838. },
  1839. new function() {
  1840. var proto = Rectangle.prototype;
  1841. return Base.each(['x', 'y', 'width', 'height'], function(key) {
  1842. var part = Base.capitalize(key),
  1843. internal = '_' + key;
  1844. this['get' + part] = function() {
  1845. return this[internal];
  1846. };
  1847. this['set' + part] = function(value) {
  1848. this[internal] = value;
  1849. if (!this._dontNotify)
  1850. this._owner[this._setter](this);
  1851. };
  1852. }, Base.each(['Point', 'Size', 'Center',
  1853. 'Left', 'Top', 'Right', 'Bottom', 'CenterX', 'CenterY',
  1854. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  1855. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'],
  1856. function(key) {
  1857. var name = 'set' + key;
  1858. this[name] = function() {
  1859. this._dontNotify = true;
  1860. proto[name].apply(this, arguments);
  1861. this._dontNotify = false;
  1862. this._owner[this._setter](this);
  1863. };
  1864. }, {
  1865. isSelected: function() {
  1866. return !!(this._owner._selection & 2);
  1867. },
  1868. setSelected: function(selected) {
  1869. var owner = this._owner;
  1870. if (owner._changeSelection) {
  1871. owner._changeSelection(2, selected);
  1872. }
  1873. }
  1874. })
  1875. );
  1876. });
  1877. var Matrix = Base.extend({
  1878. _class: 'Matrix',
  1879. initialize: function Matrix(arg, _dontNotify) {
  1880. var count = arguments.length,
  1881. ok = true;
  1882. if (count >= 6) {
  1883. this._set.apply(this, arguments);
  1884. } else if (count === 1 || count === 2) {
  1885. if (arg instanceof Matrix) {
  1886. this._set(arg._a, arg._b, arg._c, arg._d, arg._tx, arg._ty,
  1887. _dontNotify);
  1888. } else if (Array.isArray(arg)) {
  1889. this._set.apply(this,
  1890. _dontNotify ? arg.concat([_dontNotify]) : arg);
  1891. } else {
  1892. ok = false;
  1893. }
  1894. } else if (!count) {
  1895. this.reset();
  1896. } else {
  1897. ok = false;
  1898. }
  1899. if (!ok) {
  1900. throw new Error('Unsupported matrix parameters');
  1901. }
  1902. return this;
  1903. },
  1904. set: '#initialize',
  1905. _set: function(a, b, c, d, tx, ty, _dontNotify) {
  1906. this._a = a;
  1907. this._b = b;
  1908. this._c = c;
  1909. this._d = d;
  1910. this._tx = tx;
  1911. this._ty = ty;
  1912. if (!_dontNotify)
  1913. this._changed();
  1914. return this;
  1915. },
  1916. _serialize: function(options, dictionary) {
  1917. return Base.serialize(this.getValues(), options, true, dictionary);
  1918. },
  1919. _changed: function() {
  1920. var owner = this._owner;
  1921. if (owner) {
  1922. if (owner._applyMatrix) {
  1923. owner.transform(null, true);
  1924. } else {
  1925. owner._changed(9);
  1926. }
  1927. }
  1928. },
  1929. clone: function() {
  1930. return new Matrix(this._a, this._b, this._c, this._d,
  1931. this._tx, this._ty);
  1932. },
  1933. equals: function(mx) {
  1934. return mx === this || mx && this._a === mx._a && this._b === mx._b
  1935. && this._c === mx._c && this._d === mx._d
  1936. && this._tx === mx._tx && this._ty === mx._ty;
  1937. },
  1938. toString: function() {
  1939. var f = Formatter.instance;
  1940. return '[[' + [f.number(this._a), f.number(this._c),
  1941. f.number(this._tx)].join(', ') + '], ['
  1942. + [f.number(this._b), f.number(this._d),
  1943. f.number(this._ty)].join(', ') + ']]';
  1944. },
  1945. reset: function(_dontNotify) {
  1946. this._a = this._d = 1;
  1947. this._b = this._c = this._tx = this._ty = 0;
  1948. if (!_dontNotify)
  1949. this._changed();
  1950. return this;
  1951. },
  1952. apply: function(recursively, _setApplyMatrix) {
  1953. var owner = this._owner;
  1954. if (owner) {
  1955. owner.transform(null, true, Base.pick(recursively, true),
  1956. _setApplyMatrix);
  1957. return this.isIdentity();
  1958. }
  1959. return false;
  1960. },
  1961. translate: function() {
  1962. var point = Point.read(arguments),
  1963. x = point.x,
  1964. y = point.y;
  1965. this._tx += x * this._a + y * this._c;
  1966. this._ty += x * this._b + y * this._d;
  1967. this._changed();
  1968. return this;
  1969. },
  1970. scale: function() {
  1971. var scale = Point.read(arguments),
  1972. center = Point.read(arguments, 0, { readNull: true });
  1973. if (center)
  1974. this.translate(center);
  1975. this._a *= scale.x;
  1976. this._b *= scale.x;
  1977. this._c *= scale.y;
  1978. this._d *= scale.y;
  1979. if (center)
  1980. this.translate(center.negate());
  1981. this._changed();
  1982. return this;
  1983. },
  1984. rotate: function(angle ) {
  1985. angle *= Math.PI / 180;
  1986. var center = Point.read(arguments, 1),
  1987. x = center.x,
  1988. y = center.y,
  1989. cos = Math.cos(angle),
  1990. sin = Math.sin(angle),
  1991. tx = x - x * cos + y * sin,
  1992. ty = y - x * sin - y * cos,
  1993. a = this._a,
  1994. b = this._b,
  1995. c = this._c,
  1996. d = this._d;
  1997. this._a = cos * a + sin * c;
  1998. this._b = cos * b + sin * d;
  1999. this._c = -sin * a + cos * c;
  2000. this._d = -sin * b + cos * d;
  2001. this._tx += tx * a + ty * c;
  2002. this._ty += tx * b + ty * d;
  2003. this._changed();
  2004. return this;
  2005. },
  2006. shear: function() {
  2007. var shear = Point.read(arguments),
  2008. center = Point.read(arguments, 0, { readNull: true });
  2009. if (center)
  2010. this.translate(center);
  2011. var a = this._a,
  2012. b = this._b;
  2013. this._a += shear.y * this._c;
  2014. this._b += shear.y * this._d;
  2015. this._c += shear.x * a;
  2016. this._d += shear.x * b;
  2017. if (center)
  2018. this.translate(center.negate());
  2019. this._changed();
  2020. return this;
  2021. },
  2022. skew: function() {
  2023. var skew = Point.read(arguments),
  2024. center = Point.read(arguments, 0, { readNull: true }),
  2025. toRadians = Math.PI / 180,
  2026. shear = new Point(Math.tan(skew.x * toRadians),
  2027. Math.tan(skew.y * toRadians));
  2028. return this.shear(shear, center);
  2029. },
  2030. append: function(mx, _dontNotify) {
  2031. if (mx) {
  2032. var a1 = this._a,
  2033. b1 = this._b,
  2034. c1 = this._c,
  2035. d1 = this._d,
  2036. a2 = mx._a,
  2037. b2 = mx._c,
  2038. c2 = mx._b,
  2039. d2 = mx._d,
  2040. tx2 = mx._tx,
  2041. ty2 = mx._ty;
  2042. this._a = a2 * a1 + c2 * c1;
  2043. this._c = b2 * a1 + d2 * c1;
  2044. this._b = a2 * b1 + c2 * d1;
  2045. this._d = b2 * b1 + d2 * d1;
  2046. this._tx += tx2 * a1 + ty2 * c1;
  2047. this._ty += tx2 * b1 + ty2 * d1;
  2048. if (!_dontNotify)
  2049. this._changed();
  2050. }
  2051. return this;
  2052. },
  2053. prepend: function(mx, _dontNotify) {
  2054. if (mx) {
  2055. var a1 = this._a,
  2056. b1 = this._b,
  2057. c1 = this._c,
  2058. d1 = this._d,
  2059. tx1 = this._tx,
  2060. ty1 = this._ty,
  2061. a2 = mx._a,
  2062. b2 = mx._c,
  2063. c2 = mx._b,
  2064. d2 = mx._d,
  2065. tx2 = mx._tx,
  2066. ty2 = mx._ty;
  2067. this._a = a2 * a1 + b2 * b1;
  2068. this._c = a2 * c1 + b2 * d1;
  2069. this._b = c2 * a1 + d2 * b1;
  2070. this._d = c2 * c1 + d2 * d1;
  2071. this._tx = a2 * tx1 + b2 * ty1 + tx2;
  2072. this._ty = c2 * tx1 + d2 * ty1 + ty2;
  2073. if (!_dontNotify)
  2074. this._changed();
  2075. }
  2076. return this;
  2077. },
  2078. appended: function(mx) {
  2079. return this.clone().append(mx);
  2080. },
  2081. prepended: function(mx) {
  2082. return this.clone().prepend(mx);
  2083. },
  2084. invert: function() {
  2085. var a = this._a,
  2086. b = this._b,
  2087. c = this._c,
  2088. d = this._d,
  2089. tx = this._tx,
  2090. ty = this._ty,
  2091. det = a * d - b * c,
  2092. res = null;
  2093. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2094. this._a = d / det;
  2095. this._b = -b / det;
  2096. this._c = -c / det;
  2097. this._d = a / det;
  2098. this._tx = (c * ty - d * tx) / det;
  2099. this._ty = (b * tx - a * ty) / det;
  2100. res = this;
  2101. }
  2102. return res;
  2103. },
  2104. inverted: function() {
  2105. return this.clone().invert();
  2106. },
  2107. concatenate: '#append',
  2108. preConcatenate: '#prepend',
  2109. chain: '#appended',
  2110. _shiftless: function() {
  2111. return new Matrix(this._a, this._b, this._c, this._d, 0, 0);
  2112. },
  2113. _orNullIfIdentity: function() {
  2114. return this.isIdentity() ? null : this;
  2115. },
  2116. isIdentity: function() {
  2117. return this._a === 1 && this._b === 0 && this._c === 0 && this._d === 1
  2118. && this._tx === 0 && this._ty === 0;
  2119. },
  2120. isInvertible: function() {
  2121. var det = this._a * this._d - this._c * this._b;
  2122. return det && !isNaN(det) && isFinite(this._tx) && isFinite(this._ty);
  2123. },
  2124. isSingular: function() {
  2125. return !this.isInvertible();
  2126. },
  2127. transform: function( src, dst, count) {
  2128. return arguments.length < 3
  2129. ? this._transformPoint(Point.read(arguments))
  2130. : this._transformCoordinates(src, dst, count);
  2131. },
  2132. _transformPoint: function(point, dest, _dontNotify) {
  2133. var x = point.x,
  2134. y = point.y;
  2135. if (!dest)
  2136. dest = new Point();
  2137. return dest._set(
  2138. x * this._a + y * this._c + this._tx,
  2139. x * this._b + y * this._d + this._ty,
  2140. _dontNotify);
  2141. },
  2142. _transformCoordinates: function(src, dst, count) {
  2143. for (var i = 0, max = 2 * count; i < max; i += 2) {
  2144. var x = src[i],
  2145. y = src[i + 1];
  2146. dst[i] = x * this._a + y * this._c + this._tx;
  2147. dst[i + 1] = x * this._b + y * this._d + this._ty;
  2148. }
  2149. return dst;
  2150. },
  2151. _transformCorners: function(rect) {
  2152. var x1 = rect.x,
  2153. y1 = rect.y,
  2154. x2 = x1 + rect.width,
  2155. y2 = y1 + rect.height,
  2156. coords = [ x1, y1, x2, y1, x2, y2, x1, y2 ];
  2157. return this._transformCoordinates(coords, coords, 4);
  2158. },
  2159. _transformBounds: function(bounds, dest, _dontNotify) {
  2160. var coords = this._transformCorners(bounds),
  2161. min = coords.slice(0, 2),
  2162. max = min.slice();
  2163. for (var i = 2; i < 8; i++) {
  2164. var val = coords[i],
  2165. j = i & 1;
  2166. if (val < min[j]) {
  2167. min[j] = val;
  2168. } else if (val > max[j]) {
  2169. max[j] = val;
  2170. }
  2171. }
  2172. if (!dest)
  2173. dest = new Rectangle();
  2174. return dest._set(min[0], min[1], max[0] - min[0], max[1] - min[1],
  2175. _dontNotify);
  2176. },
  2177. inverseTransform: function() {
  2178. return this._inverseTransform(Point.read(arguments));
  2179. },
  2180. _inverseTransform: function(point, dest, _dontNotify) {
  2181. var a = this._a,
  2182. b = this._b,
  2183. c = this._c,
  2184. d = this._d,
  2185. tx = this._tx,
  2186. ty = this._ty,
  2187. det = a * d - b * c,
  2188. res = null;
  2189. if (det && !isNaN(det) && isFinite(tx) && isFinite(ty)) {
  2190. var x = point.x - this._tx,
  2191. y = point.y - this._ty;
  2192. if (!dest)
  2193. dest = new Point();
  2194. res = dest._set(
  2195. (x * d - y * c) / det,
  2196. (y * a - x * b) / det,
  2197. _dontNotify);
  2198. }
  2199. return res;
  2200. },
  2201. decompose: function() {
  2202. var a = this._a,
  2203. b = this._b,
  2204. c = this._c,
  2205. d = this._d,
  2206. det = a * d - b * c,
  2207. sqrt = Math.sqrt,
  2208. atan2 = Math.atan2,
  2209. degrees = 180 / Math.PI,
  2210. rotate,
  2211. scale,
  2212. skew;
  2213. if (a !== 0 || b !== 0) {
  2214. var r = sqrt(a * a + b * b);
  2215. rotate = Math.acos(a / r) * (b > 0 ? 1 : -1);
  2216. scale = [r, det / r];
  2217. skew = [atan2(a * c + b * d, r * r), 0];
  2218. } else if (c !== 0 || d !== 0) {
  2219. var s = sqrt(c * c + d * d);
  2220. rotate = Math.asin(c / s) * (d > 0 ? 1 : -1);
  2221. scale = [det / s, s];
  2222. skew = [0, atan2(a * c + b * d, s * s)];
  2223. } else {
  2224. rotate = 0;
  2225. skew = scale = [0, 0];
  2226. }
  2227. return {
  2228. translation: this.getTranslation(),
  2229. rotation: rotate * degrees,
  2230. scaling: new Point(scale),
  2231. skewing: new Point(skew[0] * degrees, skew[1] * degrees)
  2232. };
  2233. },
  2234. getValues: function() {
  2235. return [ this._a, this._b, this._c, this._d, this._tx, this._ty ];
  2236. },
  2237. getTranslation: function() {
  2238. return new Point(this._tx, this._ty);
  2239. },
  2240. getScaling: function() {
  2241. return (this.decompose() || {}).scaling;
  2242. },
  2243. getRotation: function() {
  2244. return (this.decompose() || {}).rotation;
  2245. },
  2246. applyToContext: function(ctx) {
  2247. if (!this.isIdentity()) {
  2248. ctx.transform(this._a, this._b, this._c, this._d,
  2249. this._tx, this._ty);
  2250. }
  2251. }
  2252. }, Base.each(['a', 'b', 'c', 'd', 'tx', 'ty'], function(key) {
  2253. var part = Base.capitalize(key),
  2254. prop = '_' + key;
  2255. this['get' + part] = function() {
  2256. return this[prop];
  2257. };
  2258. this['set' + part] = function(value) {
  2259. this[prop] = value;
  2260. this._changed();
  2261. };
  2262. }, {}));
  2263. var Line = Base.extend({
  2264. _class: 'Line',
  2265. initialize: function Line(arg0, arg1, arg2, arg3, arg4) {
  2266. var asVector = false;
  2267. if (arguments.length >= 4) {
  2268. this._px = arg0;
  2269. this._py = arg1;
  2270. this._vx = arg2;
  2271. this._vy = arg3;
  2272. asVector = arg4;
  2273. } else {
  2274. this._px = arg0.x;
  2275. this._py = arg0.y;
  2276. this._vx = arg1.x;
  2277. this._vy = arg1.y;
  2278. asVector = arg2;
  2279. }
  2280. if (!asVector) {
  2281. this._vx -= this._px;
  2282. this._vy -= this._py;
  2283. }
  2284. },
  2285. getPoint: function() {
  2286. return new Point(this._px, this._py);
  2287. },
  2288. getVector: function() {
  2289. return new Point(this._vx, this._vy);
  2290. },
  2291. getLength: function() {
  2292. return this.getVector().getLength();
  2293. },
  2294. intersect: function(line, isInfinite) {
  2295. return Line.intersect(
  2296. this._px, this._py, this._vx, this._vy,
  2297. line._px, line._py, line._vx, line._vy,
  2298. true, isInfinite);
  2299. },
  2300. getSide: function(point, isInfinite) {
  2301. return Line.getSide(
  2302. this._px, this._py, this._vx, this._vy,
  2303. point.x, point.y, true, isInfinite);
  2304. },
  2305. getDistance: function(point) {
  2306. return Math.abs(this.getSignedDistance(point));
  2307. },
  2308. getSignedDistance: function(point) {
  2309. return Line.getSignedDistance(this._px, this._py, this._vx, this._vy,
  2310. point.x, point.y, true);
  2311. },
  2312. isCollinear: function(line) {
  2313. return Point.isCollinear(this._vx, this._vy, line._vx, line._vy);
  2314. },
  2315. isOrthogonal: function(line) {
  2316. return Point.isOrthogonal(this._vx, this._vy, line._vx, line._vy);
  2317. },
  2318. statics: {
  2319. intersect: function(p1x, p1y, v1x, v1y, p2x, p2y, v2x, v2y, asVector,
  2320. isInfinite) {
  2321. if (!asVector) {
  2322. v1x -= p1x;
  2323. v1y -= p1y;
  2324. v2x -= p2x;
  2325. v2y -= p2y;
  2326. }
  2327. var cross = v1x * v2y - v1y * v2x;
  2328. if (!Numerical.isZero(cross)) {
  2329. var dx = p1x - p2x,
  2330. dy = p1y - p2y,
  2331. u1 = (v2x * dy - v2y * dx) / cross,
  2332. u2 = (v1x * dy - v1y * dx) / cross,
  2333. epsilon = 1e-12,
  2334. uMin = -epsilon,
  2335. uMax = 1 + epsilon;
  2336. if (isInfinite
  2337. || uMin < u1 && u1 < uMax && uMin < u2 && u2 < uMax) {
  2338. if (!isInfinite) {
  2339. u1 = u1 <= 0 ? 0 : u1 >= 1 ? 1 : u1;
  2340. }
  2341. return new Point(
  2342. p1x + u1 * v1x,
  2343. p1y + u1 * v1y);
  2344. }
  2345. }
  2346. },
  2347. getSide: function(px, py, vx, vy, x, y, asVector, isInfinite) {
  2348. if (!asVector) {
  2349. vx -= px;
  2350. vy -= py;
  2351. }
  2352. var v2x = x - px,
  2353. v2y = y - py,
  2354. ccw = v2x * vy - v2y * vx;
  2355. if (!isInfinite && Numerical.isZero(ccw)) {
  2356. ccw = (v2x * vx + v2x * vx) / (vx * vx + vy * vy);
  2357. if (ccw >= 0 && ccw <= 1)
  2358. ccw = 0;
  2359. }
  2360. return ccw < 0 ? -1 : ccw > 0 ? 1 : 0;
  2361. },
  2362. getSignedDistance: function(px, py, vx, vy, x, y, asVector) {
  2363. if (!asVector) {
  2364. vx -= px;
  2365. vy -= py;
  2366. }
  2367. return vx === 0 ? vy > 0 ? x - px : px - x
  2368. : vy === 0 ? vx < 0 ? y - py : py - y
  2369. : ((x-px) * vy - (y-py) * vx) / Math.sqrt(vx * vx + vy * vy);
  2370. },
  2371. getDistance: function(px, py, vx, vy, x, y, asVector) {
  2372. return Math.abs(
  2373. Line.getSignedDistance(px, py, vx, vy, x, y, asVector));
  2374. }
  2375. }
  2376. });
  2377. var Project = PaperScopeItem.extend({
  2378. _class: 'Project',
  2379. _list: 'projects',
  2380. _reference: 'project',
  2381. _compactSerialize: true,
  2382. initialize: function Project(element) {
  2383. PaperScopeItem.call(this, true);
  2384. this._children = [];
  2385. this._namedChildren = {};
  2386. this._activeLayer = null;
  2387. this._currentStyle = new Style(null, null, this);
  2388. this._view = View.create(this,
  2389. element || CanvasProvider.getCanvas(1, 1));
  2390. this._selectionItems = {};
  2391. this._selectionCount = 0;
  2392. this._updateVersion = 0;
  2393. },
  2394. _serialize: function(options, dictionary) {
  2395. return Base.serialize(this._children, options, true, dictionary);
  2396. },
  2397. _changed: function(flags, item) {
  2398. if (flags & 1) {
  2399. var view = this._view;
  2400. if (view) {
  2401. view._needsUpdate = true;
  2402. if (!view._requested && view._autoUpdate)
  2403. view.requestUpdate();
  2404. }
  2405. }
  2406. var changes = this._changes;
  2407. if (changes && item) {
  2408. var changesById = this._changesById,
  2409. id = item._id,
  2410. entry = changesById[id];
  2411. if (entry) {
  2412. entry.flags |= flags;
  2413. } else {
  2414. changes.push(changesById[id] = { item: item, flags: flags });
  2415. }
  2416. }
  2417. },
  2418. clear: function() {
  2419. var children = this._children;
  2420. for (var i = children.length - 1; i >= 0; i--)
  2421. children[i].remove();
  2422. },
  2423. isEmpty: function() {
  2424. return !this._children.length;
  2425. },
  2426. remove: function remove() {
  2427. if (!remove.base.call(this))
  2428. return false;
  2429. if (this._view)
  2430. this._view.remove();
  2431. return true;
  2432. },
  2433. getView: function() {
  2434. return this._view;
  2435. },
  2436. getCurrentStyle: function() {
  2437. return this._currentStyle;
  2438. },
  2439. setCurrentStyle: function(style) {
  2440. this._currentStyle.set(style);
  2441. },
  2442. getIndex: function() {
  2443. return this._index;
  2444. },
  2445. getOptions: function() {
  2446. return this._scope.settings;
  2447. },
  2448. getLayers: function() {
  2449. return this._children;
  2450. },
  2451. getActiveLayer: function() {
  2452. return this._activeLayer || new Layer({ project: this, insert: true });
  2453. },
  2454. getSymbolDefinitions: function() {
  2455. var definitions = [],
  2456. ids = {};
  2457. this.getItems({
  2458. class: SymbolItem,
  2459. match: function(item) {
  2460. var definition = item._definition,
  2461. id = definition._id;
  2462. if (!ids[id]) {
  2463. ids[id] = true;
  2464. definitions.push(definition);
  2465. }
  2466. return false;
  2467. }
  2468. });
  2469. return definitions;
  2470. },
  2471. getSymbols: 'getSymbolDefinitions',
  2472. getSelectedItems: function() {
  2473. var selectionItems = this._selectionItems,
  2474. items = [];
  2475. for (var id in selectionItems) {
  2476. var item = selectionItems[id],
  2477. selection = item._selection;
  2478. if ((selection & 1) && item.isInserted()) {
  2479. items.push(item);
  2480. } else if (!selection) {
  2481. this._updateSelection(item);
  2482. }
  2483. }
  2484. return items;
  2485. },
  2486. _updateSelection: function(item) {
  2487. var id = item._id,
  2488. selectionItems = this._selectionItems;
  2489. if (item._selection) {
  2490. if (selectionItems[id] !== item) {
  2491. this._selectionCount++;
  2492. selectionItems[id] = item;
  2493. }
  2494. } else if (selectionItems[id] === item) {
  2495. this._selectionCount--;
  2496. delete selectionItems[id];
  2497. }
  2498. },
  2499. selectAll: function() {
  2500. var children = this._children;
  2501. for (var i = 0, l = children.length; i < l; i++)
  2502. children[i].setFullySelected(true);
  2503. },
  2504. deselectAll: function() {
  2505. var selectionItems = this._selectionItems;
  2506. for (var i in selectionItems)
  2507. selectionItems[i].setFullySelected(false);
  2508. },
  2509. addLayer: function(layer) {
  2510. return this.insertLayer(undefined, layer);
  2511. },
  2512. insertLayer: function(index, layer) {
  2513. if (layer instanceof Layer) {
  2514. layer._remove(false, true);
  2515. Base.splice(this._children, [layer], index, 0);
  2516. layer._setProject(this, true);
  2517. var name = layer._name;
  2518. if (name)
  2519. layer.setName(name);
  2520. if (this._changes)
  2521. layer._changed(5);
  2522. if (!this._activeLayer)
  2523. this._activeLayer = layer;
  2524. } else {
  2525. layer = null;
  2526. }
  2527. return layer;
  2528. },
  2529. _insertItem: function(index, item, _created) {
  2530. item = this.insertLayer(index, item)
  2531. || (this._activeLayer || this._insertItem(undefined,
  2532. new Layer(Item.NO_INSERT), true))
  2533. .insertChild(index, item);
  2534. if (_created && item.activate)
  2535. item.activate();
  2536. return item;
  2537. },
  2538. getItems: function(options) {
  2539. return Item._getItems(this, options);
  2540. },
  2541. getItem: function(options) {
  2542. return Item._getItems(this, options, null, null, true)[0] || null;
  2543. },
  2544. importJSON: function(json) {
  2545. this.activate();
  2546. var layer = this._activeLayer;
  2547. return Base.importJSON(json, layer && layer.isEmpty() && layer);
  2548. },
  2549. removeOn: function(type) {
  2550. var sets = this._removeSets;
  2551. if (sets) {
  2552. if (type === 'mouseup')
  2553. sets.mousedrag = null;
  2554. var set = sets[type];
  2555. if (set) {
  2556. for (var id in set) {
  2557. var item = set[id];
  2558. for (var key in sets) {
  2559. var other = sets[key];
  2560. if (other && other != set)
  2561. delete other[item._id];
  2562. }
  2563. item.remove();
  2564. }
  2565. sets[type] = null;
  2566. }
  2567. }
  2568. },
  2569. draw: function(ctx, matrix, pixelRatio) {
  2570. this._updateVersion++;
  2571. ctx.save();
  2572. matrix.applyToContext(ctx);
  2573. var children = this._children,
  2574. param = new Base({
  2575. offset: new Point(0, 0),
  2576. pixelRatio: pixelRatio,
  2577. viewMatrix: matrix.isIdentity() ? null : matrix,
  2578. matrices: [new Matrix()],
  2579. updateMatrix: true
  2580. });
  2581. for (var i = 0, l = children.length; i < l; i++) {
  2582. children[i].draw(ctx, param);
  2583. }
  2584. ctx.restore();
  2585. if (this._selectionCount > 0) {
  2586. ctx.save();
  2587. ctx.strokeWidth = 1;
  2588. var items = this._selectionItems,
  2589. size = this._scope.settings.handleSize,
  2590. version = this._updateVersion;
  2591. for (var id in items) {
  2592. items[id]._drawSelection(ctx, matrix, size, items, version);
  2593. }
  2594. ctx.restore();
  2595. }
  2596. }
  2597. });
  2598. var Item = Base.extend(Emitter, {
  2599. statics: {
  2600. extend: function extend(src) {
  2601. if (src._serializeFields)
  2602. src._serializeFields = Base.set({},
  2603. this.prototype._serializeFields, src._serializeFields);
  2604. return extend.base.apply(this, arguments);
  2605. },
  2606. NO_INSERT: { insert: false }
  2607. },
  2608. _class: 'Item',
  2609. _name: null,
  2610. _applyMatrix: true,
  2611. _canApplyMatrix: true,
  2612. _canScaleStroke: false,
  2613. _pivot: null,
  2614. _visible: true,
  2615. _blendMode: 'normal',
  2616. _opacity: 1,
  2617. _locked: false,
  2618. _guide: false,
  2619. _clipMask: false,
  2620. _selection: 0,
  2621. _selectBounds: true,
  2622. _selectChildren: false,
  2623. _serializeFields: {
  2624. name: null,
  2625. applyMatrix: null,
  2626. matrix: new Matrix(),
  2627. pivot: null,
  2628. visible: true,
  2629. blendMode: 'normal',
  2630. opacity: 1,
  2631. locked: false,
  2632. guide: false,
  2633. clipMask: false,
  2634. selected: false,
  2635. data: {}
  2636. },
  2637. _prioritize: ['applyMatrix']
  2638. },
  2639. new function() {
  2640. var handlers = ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
  2641. 'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'];
  2642. return Base.each(handlers,
  2643. function(name) {
  2644. this._events[name] = {
  2645. install: function(type) {
  2646. this.getView()._countItemEvent(type, 1);
  2647. },
  2648. uninstall: function(type) {
  2649. this.getView()._countItemEvent(type, -1);
  2650. }
  2651. };
  2652. }, {
  2653. _events: {
  2654. onFrame: {
  2655. install: function() {
  2656. this.getView()._animateItem(this, true);
  2657. },
  2658. uninstall: function() {
  2659. this.getView()._animateItem(this, false);
  2660. }
  2661. },
  2662. onLoad: {},
  2663. onError: {}
  2664. },
  2665. statics: {
  2666. _itemHandlers: handlers
  2667. }
  2668. }
  2669. );
  2670. }, {
  2671. initialize: function Item() {
  2672. },
  2673. _initialize: function(props, point) {
  2674. var hasProps = props && Base.isPlainObject(props),
  2675. internal = hasProps && props.internal === true,
  2676. matrix = this._matrix = new Matrix(),
  2677. project = hasProps && props.project || paper.project,
  2678. settings = paper.settings;
  2679. this._id = internal ? null : UID.get();
  2680. this._parent = this._index = null;
  2681. this._applyMatrix = this._canApplyMatrix && settings.applyMatrix;
  2682. if (point)
  2683. matrix.translate(point);
  2684. matrix._owner = this;
  2685. this._style = new Style(project._currentStyle, this, project);
  2686. if (internal || hasProps && props.insert == false
  2687. || !settings.insertItems && !(hasProps && props.insert === true)) {
  2688. this._setProject(project);
  2689. } else {
  2690. (hasProps && props.parent || project)
  2691. ._insertItem(undefined, this, true);
  2692. }
  2693. if (hasProps && props !== Item.NO_INSERT) {
  2694. this.set(props, {
  2695. internal: true, insert: true, project: true, parent: true
  2696. });
  2697. }
  2698. return hasProps;
  2699. },
  2700. _serialize: function(options, dictionary) {
  2701. var props = {},
  2702. that = this;
  2703. function serialize(fields) {
  2704. for (var key in fields) {
  2705. var value = that[key];
  2706. if (!Base.equals(value, key === 'leading'
  2707. ? fields.fontSize * 1.2 : fields[key])) {
  2708. props[key] = Base.serialize(value, options,
  2709. key !== 'data', dictionary);
  2710. }
  2711. }
  2712. }
  2713. serialize(this._serializeFields);
  2714. if (!(this instanceof Group))
  2715. serialize(this._style._defaults);
  2716. return [ this._class, props ];
  2717. },
  2718. _changed: function(flags) {
  2719. var symbol = this._symbol,
  2720. cacheParent = this._parent || symbol,
  2721. project = this._project;
  2722. if (flags & 8) {
  2723. this._bounds = this._position = this._decomposed =
  2724. this._globalMatrix = undefined;
  2725. }
  2726. if (cacheParent
  2727. && (flags & 40)) {
  2728. Item._clearBoundsCache(cacheParent);
  2729. }
  2730. if (flags & 2) {
  2731. Item._clearBoundsCache(this);
  2732. }
  2733. if (project)
  2734. project._changed(flags, this);
  2735. if (symbol)
  2736. symbol._changed(flags);
  2737. },
  2738. getId: function() {
  2739. return this._id;
  2740. },
  2741. getName: function() {
  2742. return this._name;
  2743. },
  2744. setName: function(name) {
  2745. if (this._name)
  2746. this._removeNamed();
  2747. if (name === (+name) + '')
  2748. throw new Error(
  2749. 'Names consisting only of numbers are not supported.');
  2750. var owner = this._getOwner();
  2751. if (name && owner) {
  2752. var children = owner._children,
  2753. namedChildren = owner._namedChildren;
  2754. (namedChildren[name] = namedChildren[name] || []).push(this);
  2755. if (!(name in children))
  2756. children[name] = this;
  2757. }
  2758. this._name = name || undefined;
  2759. this._changed(128);
  2760. },
  2761. getStyle: function() {
  2762. return this._style;
  2763. },
  2764. setStyle: function(style) {
  2765. this.getStyle().set(style);
  2766. }
  2767. }, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
  2768. function(name) {
  2769. var part = Base.capitalize(name),
  2770. key = '_' + name,
  2771. flags = {
  2772. locked: 128,
  2773. visible: 137
  2774. };
  2775. this['get' + part] = function() {
  2776. return this[key];
  2777. };
  2778. this['set' + part] = function(value) {
  2779. if (value != this[key]) {
  2780. this[key] = value;
  2781. this._changed(flags[name] || 129);
  2782. }
  2783. };
  2784. },
  2785. {}), {
  2786. beans: true,
  2787. getSelection: function() {
  2788. return this._selection;
  2789. },
  2790. setSelection: function(selection) {
  2791. if (selection !== this._selection) {
  2792. this._selection = selection;
  2793. var project = this._project;
  2794. if (project) {
  2795. project._updateSelection(this);
  2796. this._changed(129);
  2797. }
  2798. }
  2799. },
  2800. _changeSelection: function(flag, selected) {
  2801. var selection = this._selection;
  2802. this.setSelection(selected ? selection | flag : selection & ~flag);
  2803. },
  2804. isSelected: function() {
  2805. if (this._selectChildren) {
  2806. var children = this._children;
  2807. for (var i = 0, l = children.length; i < l; i++)
  2808. if (children[i].isSelected())
  2809. return true;
  2810. }
  2811. return !!(this._selection & 1);
  2812. },
  2813. setSelected: function(selected) {
  2814. if (this._selectChildren) {
  2815. var children = this._children;
  2816. for (var i = 0, l = children.length; i < l; i++)
  2817. children[i].setSelected(selected);
  2818. }
  2819. this._changeSelection(1, selected);
  2820. },
  2821. isFullySelected: function() {
  2822. var children = this._children,
  2823. selected = !!(this._selection & 1);
  2824. if (children && selected) {
  2825. for (var i = 0, l = children.length; i < l; i++)
  2826. if (!children[i].isFullySelected())
  2827. return false;
  2828. return true;
  2829. }
  2830. return selected;
  2831. },
  2832. setFullySelected: function(selected) {
  2833. var children = this._children;
  2834. if (children) {
  2835. for (var i = 0, l = children.length; i < l; i++)
  2836. children[i].setFullySelected(selected);
  2837. }
  2838. this._changeSelection(1, selected);
  2839. },
  2840. isClipMask: function() {
  2841. return this._clipMask;
  2842. },
  2843. setClipMask: function(clipMask) {
  2844. if (this._clipMask != (clipMask = !!clipMask)) {
  2845. this._clipMask = clipMask;
  2846. if (clipMask) {
  2847. this.setFillColor(null);
  2848. this.setStrokeColor(null);
  2849. }
  2850. this._changed(129);
  2851. if (this._parent)
  2852. this._parent._changed(1024);
  2853. }
  2854. },
  2855. getData: function() {
  2856. if (!this._data)
  2857. this._data = {};
  2858. return this._data;
  2859. },
  2860. setData: function(data) {
  2861. this._data = data;
  2862. },
  2863. getPosition: function(_dontLink) {
  2864. var position = this._position,
  2865. ctor = _dontLink ? Point : LinkedPoint;
  2866. if (!position) {
  2867. var pivot = this._pivot;
  2868. position = this._position = pivot
  2869. ? this._matrix._transformPoint(pivot)
  2870. : this.getBounds().getCenter(true);
  2871. }
  2872. return new ctor(position.x, position.y, this, 'setPosition');
  2873. },
  2874. setPosition: function() {
  2875. this.translate(Point.read(arguments).subtract(this.getPosition(true)));
  2876. },
  2877. getPivot: function() {
  2878. var pivot = this._pivot;
  2879. return pivot
  2880. ? new LinkedPoint(pivot.x, pivot.y, this, 'setPivot')
  2881. : null;
  2882. },
  2883. setPivot: function() {
  2884. this._pivot = Point.read(arguments, 0, { clone: true, readNull: true });
  2885. this._position = undefined;
  2886. }
  2887. }, Base.each({
  2888. getStrokeBounds: { stroke: true },
  2889. getHandleBounds: { handle: true },
  2890. getInternalBounds: { internal: true }
  2891. },
  2892. function(options, key) {
  2893. this[key] = function(matrix) {
  2894. return this.getBounds(matrix, options);
  2895. };
  2896. },
  2897. {
  2898. beans: true,
  2899. getBounds: function(matrix, options) {
  2900. var hasMatrix = options || matrix instanceof Matrix,
  2901. opts = Base.set({}, hasMatrix ? options : matrix,
  2902. this._boundsOptions);
  2903. if (!opts.stroke || this.getStrokeScaling())
  2904. opts.cacheItem = this;
  2905. var rect = this._getCachedBounds(hasMatrix && matrix, opts).rect;
  2906. return !arguments.length
  2907. ? new LinkedRectangle(rect.x, rect.y, rect.width, rect.height,
  2908. this, 'setBounds')
  2909. : rect;
  2910. },
  2911. setBounds: function() {
  2912. var rect = Rectangle.read(arguments),
  2913. bounds = this.getBounds(),
  2914. _matrix = this._matrix,
  2915. matrix = new Matrix(),
  2916. center = rect.getCenter();
  2917. matrix.translate(center);
  2918. if (rect.width != bounds.width || rect.height != bounds.height) {
  2919. if (!_matrix.isInvertible()) {
  2920. _matrix.set(_matrix._backup
  2921. || new Matrix().translate(_matrix.getTranslation()));
  2922. bounds = this.getBounds();
  2923. }
  2924. matrix.scale(
  2925. bounds.width !== 0 ? rect.width / bounds.width : 0,
  2926. bounds.height !== 0 ? rect.height / bounds.height : 0);
  2927. }
  2928. center = bounds.getCenter();
  2929. matrix.translate(-center.x, -center.y);
  2930. this.transform(matrix);
  2931. },
  2932. _getBounds: function(matrix, options) {
  2933. var children = this._children;
  2934. if (!children || !children.length)
  2935. return new Rectangle();
  2936. Item._updateBoundsCache(this, options.cacheItem);
  2937. return Item._getBounds(children, matrix, options);
  2938. },
  2939. _getBoundsCacheKey: function(options, internal) {
  2940. return [
  2941. options.stroke ? 1 : 0,
  2942. options.handle ? 1 : 0,
  2943. internal ? 1 : 0
  2944. ].join('');
  2945. },
  2946. _getCachedBounds: function(matrix, options, noInternal) {
  2947. matrix = matrix && matrix._orNullIfIdentity();
  2948. var internal = options.internal && !noInternal,
  2949. cacheItem = options.cacheItem,
  2950. _matrix = internal ? null : this._matrix._orNullIfIdentity(),
  2951. cacheKey = cacheItem && (!matrix || matrix.equals(_matrix))
  2952. && this._getBoundsCacheKey(options, internal),
  2953. bounds = this._bounds;
  2954. Item._updateBoundsCache(this._parent || this._symbol, cacheItem);
  2955. if (cacheKey && bounds && cacheKey in bounds) {
  2956. var cached = bounds[cacheKey];
  2957. return {
  2958. rect: cached.rect.clone(),
  2959. nonscaling: cached.nonscaling
  2960. };
  2961. }
  2962. var res = this._getBounds(matrix || _matrix, options),
  2963. rect = res.rect || res,
  2964. style = this._style,
  2965. nonscaling = res.nonscaling || style.hasStroke()
  2966. && !style.getStrokeScaling();
  2967. if (cacheKey) {
  2968. if (!bounds) {
  2969. this._bounds = bounds = {};
  2970. }
  2971. var cached = bounds[cacheKey] = {
  2972. rect: rect.clone(),
  2973. nonscaling: nonscaling,
  2974. internal: internal
  2975. };
  2976. }
  2977. return {
  2978. rect: rect,
  2979. nonscaling: nonscaling
  2980. };
  2981. },
  2982. _getStrokeMatrix: function(matrix, options) {
  2983. var parent = this.getStrokeScaling() ? null
  2984. : options && options.internal ? this
  2985. : this._parent || this._symbol && this._symbol._item,
  2986. mx = parent ? parent.getViewMatrix().invert() : matrix;
  2987. return mx && mx._shiftless();
  2988. },
  2989. statics: {
  2990. _updateBoundsCache: function(parent, item) {
  2991. if (parent && item) {
  2992. var id = item._id,
  2993. ref = parent._boundsCache = parent._boundsCache || {
  2994. ids: {},
  2995. list: []
  2996. };
  2997. if (!ref.ids[id]) {
  2998. ref.list.push(item);
  2999. ref.ids[id] = item;
  3000. }
  3001. }
  3002. },
  3003. _clearBoundsCache: function(item) {
  3004. var cache = item._boundsCache;
  3005. if (cache) {
  3006. item._bounds = item._position = item._boundsCache = undefined;
  3007. for (var i = 0, list = cache.list, l = list.length; i < l; i++){
  3008. var other = list[i];
  3009. if (other !== item) {
  3010. other._bounds = other._position = undefined;
  3011. if (other._boundsCache)
  3012. Item._clearBoundsCache(other);
  3013. }
  3014. }
  3015. }
  3016. },
  3017. _getBounds: function(items, matrix, options) {
  3018. var x1 = Infinity,
  3019. x2 = -x1,
  3020. y1 = x1,
  3021. y2 = x2,
  3022. nonscaling = false;
  3023. options = options || {};
  3024. for (var i = 0, l = items.length; i < l; i++) {
  3025. var item = items[i];
  3026. if (item._visible && !item.isEmpty()) {
  3027. var bounds = item._getCachedBounds(
  3028. matrix && matrix.appended(item._matrix), options, true),
  3029. rect = bounds.rect;
  3030. x1 = Math.min(rect.x, x1);
  3031. y1 = Math.min(rect.y, y1);
  3032. x2 = Math.max(rect.x + rect.width, x2);
  3033. y2 = Math.max(rect.y + rect.height, y2);
  3034. if (bounds.nonscaling)
  3035. nonscaling = true;
  3036. }
  3037. }
  3038. return {
  3039. rect: isFinite(x1)
  3040. ? new Rectangle(x1, y1, x2 - x1, y2 - y1)
  3041. : new Rectangle(),
  3042. nonscaling: nonscaling
  3043. };
  3044. }
  3045. }
  3046. }), {
  3047. beans: true,
  3048. _decompose: function() {
  3049. return this._applyMatrix
  3050. ? null
  3051. : this._decomposed || (this._decomposed = this._matrix.decompose());
  3052. },
  3053. getRotation: function() {
  3054. var decomposed = this._decompose();
  3055. return decomposed ? decomposed.rotation : 0;
  3056. },
  3057. setRotation: function(rotation) {
  3058. var current = this.getRotation();
  3059. if (current != null && rotation != null) {
  3060. var decomposed = this._decomposed;
  3061. this.rotate(rotation - current);
  3062. if (decomposed) {
  3063. decomposed.rotation = rotation;
  3064. this._decomposed = decomposed;
  3065. }
  3066. }
  3067. },
  3068. getScaling: function() {
  3069. var decomposed = this._decompose(),
  3070. s = decomposed && decomposed.scaling;
  3071. return new LinkedPoint(s ? s.x : 1, s ? s.y : 1, this, 'setScaling');
  3072. },
  3073. setScaling: function() {
  3074. var current = this.getScaling(),
  3075. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  3076. if (current && scaling && !current.equals(scaling)) {
  3077. var rotation = this.getRotation(),
  3078. decomposed = this._decomposed,
  3079. matrix = new Matrix(),
  3080. center = this.getPosition(true);
  3081. matrix.translate(center);
  3082. if (rotation)
  3083. matrix.rotate(rotation);
  3084. matrix.scale(scaling.x / current.x, scaling.y / current.y);
  3085. if (rotation)
  3086. matrix.rotate(-rotation);
  3087. matrix.translate(center.negate());
  3088. this.transform(matrix);
  3089. if (decomposed) {
  3090. decomposed.scaling = scaling;
  3091. this._decomposed = decomposed;
  3092. }
  3093. }
  3094. },
  3095. getMatrix: function() {
  3096. return this._matrix;
  3097. },
  3098. setMatrix: function() {
  3099. var matrix = this._matrix;
  3100. matrix.initialize.apply(matrix, arguments);
  3101. },
  3102. getGlobalMatrix: function(_dontClone) {
  3103. var matrix = this._globalMatrix,
  3104. updateVersion = this._project._updateVersion;
  3105. if (matrix && matrix._updateVersion !== updateVersion)
  3106. matrix = null;
  3107. if (!matrix) {
  3108. matrix = this._globalMatrix = this._matrix.clone();
  3109. var parent = this._parent;
  3110. if (parent)
  3111. matrix.prepend(parent.getGlobalMatrix(true));
  3112. matrix._updateVersion = updateVersion;
  3113. }
  3114. return _dontClone ? matrix : matrix.clone();
  3115. },
  3116. getViewMatrix: function() {
  3117. return this.getGlobalMatrix().prepend(this.getView()._matrix);
  3118. },
  3119. getApplyMatrix: function() {
  3120. return this._applyMatrix;
  3121. },
  3122. setApplyMatrix: function(apply) {
  3123. if (this._applyMatrix = this._canApplyMatrix && !!apply)
  3124. this.transform(null, true);
  3125. },
  3126. getTransformContent: '#getApplyMatrix',
  3127. setTransformContent: '#setApplyMatrix',
  3128. }, {
  3129. getProject: function() {
  3130. return this._project;
  3131. },
  3132. _setProject: function(project, installEvents) {
  3133. if (this._project !== project) {
  3134. if (this._project)
  3135. this._installEvents(false);
  3136. this._project = project;
  3137. var children = this._children;
  3138. for (var i = 0, l = children && children.length; i < l; i++)
  3139. children[i]._setProject(project);
  3140. installEvents = true;
  3141. }
  3142. if (installEvents)
  3143. this._installEvents(true);
  3144. },
  3145. getView: function() {
  3146. return this._project._view;
  3147. },
  3148. _installEvents: function _installEvents(install) {
  3149. _installEvents.base.call(this, install);
  3150. var children = this._children;
  3151. for (var i = 0, l = children && children.length; i < l; i++)
  3152. children[i]._installEvents(install);
  3153. },
  3154. getLayer: function() {
  3155. var parent = this;
  3156. while (parent = parent._parent) {
  3157. if (parent instanceof Layer)
  3158. return parent;
  3159. }
  3160. return null;
  3161. },
  3162. getParent: function() {
  3163. return this._parent;
  3164. },
  3165. setParent: function(item) {
  3166. return item.addChild(this);
  3167. },
  3168. _getOwner: '#getParent',
  3169. getChildren: function() {
  3170. return this._children;
  3171. },
  3172. setChildren: function(items) {
  3173. this.removeChildren();
  3174. this.addChildren(items);
  3175. },
  3176. getFirstChild: function() {
  3177. return this._children && this._children[0] || null;
  3178. },
  3179. getLastChild: function() {
  3180. return this._children && this._children[this._children.length - 1]
  3181. || null;
  3182. },
  3183. getNextSibling: function() {
  3184. var owner = this._getOwner();
  3185. return owner && owner._children[this._index + 1] || null;
  3186. },
  3187. getPreviousSibling: function() {
  3188. var owner = this._getOwner();
  3189. return owner && owner._children[this._index - 1] || null;
  3190. },
  3191. getIndex: function() {
  3192. return this._index;
  3193. },
  3194. equals: function(item) {
  3195. return item === this || item && this._class === item._class
  3196. && this._style.equals(item._style)
  3197. && this._matrix.equals(item._matrix)
  3198. && this._locked === item._locked
  3199. && this._visible === item._visible
  3200. && this._blendMode === item._blendMode
  3201. && this._opacity === item._opacity
  3202. && this._clipMask === item._clipMask
  3203. && this._guide === item._guide
  3204. && this._equals(item)
  3205. || false;
  3206. },
  3207. _equals: function(item) {
  3208. return Base.equals(this._children, item._children);
  3209. },
  3210. clone: function(options) {
  3211. var copy = new this.constructor(Item.NO_INSERT),
  3212. children = this._children,
  3213. insert = Base.pick(options ? options.insert : undefined,
  3214. options === undefined || options === true),
  3215. deep = Base.pick(options ? options.deep : undefined, true);
  3216. if (children)
  3217. copy.copyAttributes(this);
  3218. if (!children || deep)
  3219. copy.copyContent(this);
  3220. if (!children)
  3221. copy.copyAttributes(this);
  3222. if (insert)
  3223. copy.insertAbove(this);
  3224. var name = this._name,
  3225. parent = this._parent;
  3226. if (name && parent) {
  3227. var children = parent._children,
  3228. orig = name,
  3229. i = 1;
  3230. while (children[name])
  3231. name = orig + ' ' + (i++);
  3232. if (name !== orig)
  3233. copy.setName(name);
  3234. }
  3235. return copy;
  3236. },
  3237. copyContent: function(source) {
  3238. var children = source._children;
  3239. for (var i = 0, l = children && children.length; i < l; i++) {
  3240. this.addChild(children[i].clone(false), true);
  3241. }
  3242. },
  3243. copyAttributes: function(source, excludeMatrix) {
  3244. this.setStyle(source._style);
  3245. var keys = ['_locked', '_visible', '_blendMode', '_opacity',
  3246. '_clipMask', '_guide'];
  3247. for (var i = 0, l = keys.length; i < l; i++) {
  3248. var key = keys[i];
  3249. if (source.hasOwnProperty(key))
  3250. this[key] = source[key];
  3251. }
  3252. if (!excludeMatrix)
  3253. this._matrix.set(source._matrix, true);
  3254. this.setApplyMatrix(source._applyMatrix);
  3255. this.setPivot(source._pivot);
  3256. this.setSelection(source._selection);
  3257. var data = source._data,
  3258. name = source._name;
  3259. this._data = data ? Base.clone(data) : null;
  3260. if (name)
  3261. this.setName(name);
  3262. },
  3263. rasterize: function(resolution, insert) {
  3264. var bounds = this.getStrokeBounds(),
  3265. scale = (resolution || this.getView().getResolution()) / 72,
  3266. topLeft = bounds.getTopLeft().floor(),
  3267. bottomRight = bounds.getBottomRight().ceil(),
  3268. size = new Size(bottomRight.subtract(topLeft)),
  3269. raster = new Raster(Item.NO_INSERT);
  3270. if (!size.isZero()) {
  3271. var canvas = CanvasProvider.getCanvas(size.multiply(scale)),
  3272. ctx = canvas.getContext('2d'),
  3273. matrix = new Matrix().scale(scale).translate(topLeft.negate());
  3274. ctx.save();
  3275. matrix.applyToContext(ctx);
  3276. this.draw(ctx, new Base({ matrices: [matrix] }));
  3277. ctx.restore();
  3278. raster.setCanvas(canvas);
  3279. }
  3280. raster.transform(new Matrix().translate(topLeft.add(size.divide(2)))
  3281. .scale(1 / scale));
  3282. if (insert === undefined || insert)
  3283. raster.insertAbove(this);
  3284. return raster;
  3285. },
  3286. contains: function() {
  3287. return !!this._contains(
  3288. this._matrix._inverseTransform(Point.read(arguments)));
  3289. },
  3290. _contains: function(point) {
  3291. var children = this._children;
  3292. if (children) {
  3293. for (var i = children.length - 1; i >= 0; i--) {
  3294. if (children[i].contains(point))
  3295. return true;
  3296. }
  3297. return false;
  3298. }
  3299. return point.isInside(this.getInternalBounds());
  3300. },
  3301. isInside: function() {
  3302. return Rectangle.read(arguments).contains(this.getBounds());
  3303. },
  3304. _asPathItem: function() {
  3305. return new Path.Rectangle({
  3306. rectangle: this.getInternalBounds(),
  3307. matrix: this._matrix,
  3308. insert: false,
  3309. });
  3310. },
  3311. intersects: function(item, _matrix) {
  3312. if (!(item instanceof Item))
  3313. return false;
  3314. return this._asPathItem().getIntersections(item._asPathItem(), null,
  3315. _matrix, true).length > 0;
  3316. }
  3317. },
  3318. new function() {
  3319. function hitTest() {
  3320. return this._hitTest(
  3321. Point.read(arguments),
  3322. HitResult.getOptions(arguments));
  3323. }
  3324. function hitTestAll() {
  3325. var point = Point.read(arguments),
  3326. options = HitResult.getOptions(arguments),
  3327. all = [];
  3328. this._hitTest(point, Base.set({ all: all }, options));
  3329. return all;
  3330. }
  3331. function hitTestChildren(point, options, viewMatrix, _exclude) {
  3332. var children = this._children;
  3333. if (children) {
  3334. for (var i = children.length - 1; i >= 0; i--) {
  3335. var child = children[i];
  3336. var res = child !== _exclude && child._hitTest(point, options,
  3337. viewMatrix);
  3338. if (res && !options.all)
  3339. return res;
  3340. }
  3341. }
  3342. return null;
  3343. }
  3344. Project.inject({
  3345. hitTest: hitTest,
  3346. hitTestAll: hitTestAll,
  3347. _hitTest: hitTestChildren
  3348. });
  3349. return {
  3350. hitTest: hitTest,
  3351. hitTestAll: hitTestAll,
  3352. _hitTestChildren: hitTestChildren,
  3353. };
  3354. }, {
  3355. _hitTest: function(point, options, parentViewMatrix) {
  3356. if (this._locked || !this._visible || this._guide && !options.guides
  3357. || this.isEmpty()) {
  3358. return null;
  3359. }
  3360. var matrix = this._matrix,
  3361. viewMatrix = parentViewMatrix
  3362. ? parentViewMatrix.appended(matrix)
  3363. : this.getGlobalMatrix().prepend(this.getView()._matrix),
  3364. tolerance = Math.max(options.tolerance, 1e-12),
  3365. tolerancePadding = options._tolerancePadding = new Size(
  3366. Path._getStrokePadding(tolerance,
  3367. matrix._shiftless().invert()));
  3368. point = matrix._inverseTransform(point);
  3369. if (!point || !this._children &&
  3370. !this.getBounds({ internal: true, stroke: true, handle: true })
  3371. .expand(tolerancePadding.multiply(2))._containsPoint(point)) {
  3372. return null;
  3373. }
  3374. var checkSelf = !(options.guides && !this._guide
  3375. || options.selected && !this.isSelected()
  3376. || options.type && options.type !== Base.hyphenate(this._class)
  3377. || options.class && !(this instanceof options.class)),
  3378. match = options.match,
  3379. that = this,
  3380. bounds,
  3381. res;
  3382. function filter(hit) {
  3383. if (hit && match && !match(hit))
  3384. hit = null;
  3385. if (hit && options.all)
  3386. options.all.push(hit);
  3387. return hit;
  3388. }
  3389. function checkPoint(type, part) {
  3390. var pt = part ? bounds['get' + part]() : that.getPosition();
  3391. if (point.subtract(pt).divide(tolerancePadding).length <= 1) {
  3392. return new HitResult(type, that, {
  3393. name: part ? Base.hyphenate(part) : type,
  3394. point: pt
  3395. });
  3396. }
  3397. }
  3398. var checkPosition = options.position,
  3399. checkCenter = options.center,
  3400. checkBounds = options.bounds;
  3401. if (checkSelf && this._parent
  3402. && (checkPosition || checkCenter || checkBounds)) {
  3403. if (checkCenter || checkBounds) {
  3404. bounds = this.getInternalBounds();
  3405. }
  3406. res = checkPosition && checkPoint('position') ||
  3407. checkCenter && checkPoint('center', 'Center');
  3408. if (!res && checkBounds) {
  3409. var points = [
  3410. 'TopLeft', 'TopRight', 'BottomLeft', 'BottomRight',
  3411. 'LeftCenter', 'TopCenter', 'RightCenter', 'BottomCenter'
  3412. ];
  3413. for (var i = 0; i < 8 && !res; i++) {
  3414. res = checkPoint('bounds', points[i]);
  3415. }
  3416. }
  3417. res = filter(res);
  3418. }
  3419. if (!res) {
  3420. res = this._hitTestChildren(point, options, viewMatrix)
  3421. || checkSelf
  3422. && filter(this._hitTestSelf(point, options, viewMatrix,
  3423. this.getStrokeScaling() ? null
  3424. : viewMatrix._shiftless().invert()))
  3425. || null;
  3426. }
  3427. if (res && res.point) {
  3428. res.point = matrix.transform(res.point);
  3429. }
  3430. return res;
  3431. },
  3432. _hitTestSelf: function(point, options) {
  3433. if (options.fill && this.hasFill() && this._contains(point))
  3434. return new HitResult('fill', this);
  3435. },
  3436. matches: function(name, compare) {
  3437. function matchObject(obj1, obj2) {
  3438. for (var i in obj1) {
  3439. if (obj1.hasOwnProperty(i)) {
  3440. var val1 = obj1[i],
  3441. val2 = obj2[i];
  3442. if (Base.isPlainObject(val1) && Base.isPlainObject(val2)) {
  3443. if (!matchObject(val1, val2))
  3444. return false;
  3445. } else if (!Base.equals(val1, val2)) {
  3446. return false;
  3447. }
  3448. }
  3449. }
  3450. return true;
  3451. }
  3452. var type = typeof name;
  3453. if (type === 'object') {
  3454. for (var key in name) {
  3455. if (name.hasOwnProperty(key) && !this.matches(key, name[key]))
  3456. return false;
  3457. }
  3458. return true;
  3459. } else if (type === 'function') {
  3460. return name(this);
  3461. } else if (name === 'match') {
  3462. return compare(this);
  3463. } else {
  3464. var value = /^(empty|editable)$/.test(name)
  3465. ? this['is' + Base.capitalize(name)]()
  3466. : name === 'type'
  3467. ? Base.hyphenate(this._class)
  3468. : this[name];
  3469. if (name === 'class') {
  3470. if (typeof compare === 'function')
  3471. return this instanceof compare;
  3472. value = this._class;
  3473. }
  3474. if (typeof compare === 'function') {
  3475. return !!compare(value);
  3476. } else if (compare) {
  3477. if (compare.test) {
  3478. return compare.test(value);
  3479. } else if (Base.isPlainObject(compare)) {
  3480. return matchObject(compare, value);
  3481. }
  3482. }
  3483. return Base.equals(value, compare);
  3484. }
  3485. },
  3486. getItems: function(options) {
  3487. return Item._getItems(this, options, this._matrix);
  3488. },
  3489. getItem: function(options) {
  3490. return Item._getItems(this, options, this._matrix, null, true)[0]
  3491. || null;
  3492. },
  3493. statics: {
  3494. _getItems: function _getItems(item, options, matrix, param, firstOnly) {
  3495. if (!param) {
  3496. var obj = typeof options === 'object' && options,
  3497. overlapping = obj && obj.overlapping,
  3498. inside = obj && obj.inside,
  3499. bounds = overlapping || inside,
  3500. rect = bounds && Rectangle.read([bounds]);
  3501. param = {
  3502. items: [],
  3503. recursive: obj && obj.recursive !== false,
  3504. inside: !!inside,
  3505. overlapping: !!overlapping,
  3506. rect: rect,
  3507. path: overlapping && new Path.Rectangle({
  3508. rectangle: rect,
  3509. insert: false
  3510. })
  3511. };
  3512. if (obj) {
  3513. options = Base.filter({}, options, {
  3514. recursive: true, inside: true, overlapping: true
  3515. });
  3516. }
  3517. }
  3518. var children = item._children,
  3519. items = param.items,
  3520. rect = param.rect;
  3521. matrix = rect && (matrix || new Matrix());
  3522. for (var i = 0, l = children && children.length; i < l; i++) {
  3523. var child = children[i],
  3524. childMatrix = matrix && matrix.appended(child._matrix),
  3525. add = true;
  3526. if (rect) {
  3527. var bounds = child.getBounds(childMatrix);
  3528. if (!rect.intersects(bounds))
  3529. continue;
  3530. if (!(rect.contains(bounds)
  3531. || param.overlapping && (bounds.contains(rect)
  3532. || param.path.intersects(child, childMatrix))))
  3533. add = false;
  3534. }
  3535. if (add && child.matches(options)) {
  3536. items.push(child);
  3537. if (firstOnly)
  3538. break;
  3539. }
  3540. if (param.recursive !== false) {
  3541. _getItems(child, options, childMatrix, param, firstOnly);
  3542. }
  3543. if (firstOnly && items.length > 0)
  3544. break;
  3545. }
  3546. return items;
  3547. }
  3548. }
  3549. }, {
  3550. importJSON: function(json) {
  3551. var res = Base.importJSON(json, this);
  3552. return res !== this ? this.addChild(res) : res;
  3553. },
  3554. addChild: function(item) {
  3555. return this.insertChild(undefined, item);
  3556. },
  3557. insertChild: function(index, item) {
  3558. var res = item ? this.insertChildren(index, [item]) : null;
  3559. return res && res[0];
  3560. },
  3561. addChildren: function(items) {
  3562. return this.insertChildren(this._children.length, items);
  3563. },
  3564. insertChildren: function(index, items) {
  3565. var children = this._children;
  3566. if (children && items && items.length > 0) {
  3567. items = Base.slice(items);
  3568. var inserted = {};
  3569. for (var i = items.length - 1; i >= 0; i--) {
  3570. var item = items[i],
  3571. id = item && item._id;
  3572. if (!item || inserted[id]) {
  3573. items.splice(i, 1);
  3574. } else {
  3575. item._remove(false, true);
  3576. inserted[id] = true;
  3577. }
  3578. }
  3579. Base.splice(children, items, index, 0);
  3580. var project = this._project,
  3581. notifySelf = project._changes;
  3582. for (var i = 0, l = items.length; i < l; i++) {
  3583. var item = items[i],
  3584. name = item._name;
  3585. item._parent = this;
  3586. item._setProject(project, true);
  3587. if (name)
  3588. item.setName(name);
  3589. if (notifySelf)
  3590. item._changed(5);
  3591. }
  3592. this._changed(11);
  3593. } else {
  3594. items = null;
  3595. }
  3596. return items;
  3597. },
  3598. _insertItem: '#insertChild',
  3599. _insertAt: function(item, offset) {
  3600. var owner = item && item._getOwner(),
  3601. res = item !== this && owner ? this : null;
  3602. if (res) {
  3603. res._remove(false, true);
  3604. owner._insertItem(item._index + offset, res);
  3605. }
  3606. return res;
  3607. },
  3608. insertAbove: function(item) {
  3609. return this._insertAt(item, 1);
  3610. },
  3611. insertBelow: function(item) {
  3612. return this._insertAt(item, 0);
  3613. },
  3614. sendToBack: function() {
  3615. var owner = this._getOwner();
  3616. return owner ? owner._insertItem(0, this) : null;
  3617. },
  3618. bringToFront: function() {
  3619. var owner = this._getOwner();
  3620. return owner ? owner._insertItem(undefined, this) : null;
  3621. },
  3622. appendTop: '#addChild',
  3623. appendBottom: function(item) {
  3624. return this.insertChild(0, item);
  3625. },
  3626. moveAbove: '#insertAbove',
  3627. moveBelow: '#insertBelow',
  3628. addTo: function(owner) {
  3629. return owner._insertItem(undefined, this);
  3630. },
  3631. copyTo: function(owner) {
  3632. return this.clone(false).addTo(owner);
  3633. },
  3634. reduce: function(options) {
  3635. var children = this._children;
  3636. if (children && children.length === 1) {
  3637. var child = children[0].reduce(options);
  3638. if (this._parent) {
  3639. child.insertAbove(this);
  3640. this.remove();
  3641. } else {
  3642. child.remove();
  3643. }
  3644. return child;
  3645. }
  3646. return this;
  3647. },
  3648. _removeNamed: function() {
  3649. var owner = this._getOwner();
  3650. if (owner) {
  3651. var children = owner._children,
  3652. namedChildren = owner._namedChildren,
  3653. name = this._name,
  3654. namedArray = namedChildren[name],
  3655. index = namedArray ? namedArray.indexOf(this) : -1;
  3656. if (index !== -1) {
  3657. if (children[name] == this)
  3658. delete children[name];
  3659. namedArray.splice(index, 1);
  3660. if (namedArray.length) {
  3661. children[name] = namedArray[0];
  3662. } else {
  3663. delete namedChildren[name];
  3664. }
  3665. }
  3666. }
  3667. },
  3668. _remove: function(notifySelf, notifyParent) {
  3669. var owner = this._getOwner(),
  3670. project = this._project,
  3671. index = this._index;
  3672. if (owner) {
  3673. if (this._name)
  3674. this._removeNamed();
  3675. if (index != null) {
  3676. if (project._activeLayer === this)
  3677. project._activeLayer = this.getNextSibling()
  3678. || this.getPreviousSibling();
  3679. Base.splice(owner._children, null, index, 1);
  3680. }
  3681. this._installEvents(false);
  3682. if (notifySelf && project._changes)
  3683. this._changed(5);
  3684. if (notifyParent)
  3685. owner._changed(11, this);
  3686. this._parent = null;
  3687. return true;
  3688. }
  3689. return false;
  3690. },
  3691. remove: function() {
  3692. return this._remove(true, true);
  3693. },
  3694. replaceWith: function(item) {
  3695. var ok = item && item.insertBelow(this);
  3696. if (ok)
  3697. this.remove();
  3698. return ok;
  3699. },
  3700. removeChildren: function(start, end) {
  3701. if (!this._children)
  3702. return null;
  3703. start = start || 0;
  3704. end = Base.pick(end, this._children.length);
  3705. var removed = Base.splice(this._children, null, start, end - start);
  3706. for (var i = removed.length - 1; i >= 0; i--) {
  3707. removed[i]._remove(true, false);
  3708. }
  3709. if (removed.length > 0)
  3710. this._changed(11);
  3711. return removed;
  3712. },
  3713. clear: '#removeChildren',
  3714. reverseChildren: function() {
  3715. if (this._children) {
  3716. this._children.reverse();
  3717. for (var i = 0, l = this._children.length; i < l; i++)
  3718. this._children[i]._index = i;
  3719. this._changed(11);
  3720. }
  3721. },
  3722. isEmpty: function() {
  3723. var children = this._children;
  3724. return !children || !children.length;
  3725. },
  3726. isEditable: function() {
  3727. var item = this;
  3728. while (item) {
  3729. if (!item._visible || item._locked)
  3730. return false;
  3731. item = item._parent;
  3732. }
  3733. return true;
  3734. },
  3735. hasFill: function() {
  3736. return this.getStyle().hasFill();
  3737. },
  3738. hasStroke: function() {
  3739. return this.getStyle().hasStroke();
  3740. },
  3741. hasShadow: function() {
  3742. return this.getStyle().hasShadow();
  3743. },
  3744. _getOrder: function(item) {
  3745. function getList(item) {
  3746. var list = [];
  3747. do {
  3748. list.unshift(item);
  3749. } while (item = item._parent);
  3750. return list;
  3751. }
  3752. var list1 = getList(this),
  3753. list2 = getList(item);
  3754. for (var i = 0, l = Math.min(list1.length, list2.length); i < l; i++) {
  3755. if (list1[i] != list2[i]) {
  3756. return list1[i]._index < list2[i]._index ? 1 : -1;
  3757. }
  3758. }
  3759. return 0;
  3760. },
  3761. hasChildren: function() {
  3762. return this._children && this._children.length > 0;
  3763. },
  3764. isInserted: function() {
  3765. return this._parent ? this._parent.isInserted() : false;
  3766. },
  3767. isAbove: function(item) {
  3768. return this._getOrder(item) === -1;
  3769. },
  3770. isBelow: function(item) {
  3771. return this._getOrder(item) === 1;
  3772. },
  3773. isParent: function(item) {
  3774. return this._parent === item;
  3775. },
  3776. isChild: function(item) {
  3777. return item && item._parent === this;
  3778. },
  3779. isDescendant: function(item) {
  3780. var parent = this;
  3781. while (parent = parent._parent) {
  3782. if (parent === item)
  3783. return true;
  3784. }
  3785. return false;
  3786. },
  3787. isAncestor: function(item) {
  3788. return item ? item.isDescendant(this) : false;
  3789. },
  3790. isSibling: function(item) {
  3791. return this._parent === item._parent;
  3792. },
  3793. isGroupedWith: function(item) {
  3794. var parent = this._parent;
  3795. while (parent) {
  3796. if (parent._parent
  3797. && /^(Group|Layer|CompoundPath)$/.test(parent._class)
  3798. && item.isDescendant(parent))
  3799. return true;
  3800. parent = parent._parent;
  3801. }
  3802. return false;
  3803. },
  3804. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  3805. var rotate = key === 'rotate';
  3806. this[key] = function() {
  3807. var value = (rotate ? Base : Point).read(arguments),
  3808. center = Point.read(arguments, 0, { readNull: true });
  3809. return this.transform(new Matrix()[key](value,
  3810. center || this.getPosition(true)));
  3811. };
  3812. }, {
  3813. translate: function() {
  3814. var mx = new Matrix();
  3815. return this.transform(mx.translate.apply(mx, arguments));
  3816. },
  3817. transform: function(matrix, _applyMatrix, _applyRecursively,
  3818. _setApplyMatrix) {
  3819. var _matrix = this._matrix,
  3820. transform = matrix && !matrix.isIdentity(),
  3821. applyMatrix = (_applyMatrix || this._applyMatrix)
  3822. && ((!_matrix.isIdentity() || transform)
  3823. || _applyMatrix && _applyRecursively && this._children);
  3824. if (!transform && !applyMatrix)
  3825. return this;
  3826. if (transform) {
  3827. if (!matrix.isInvertible() && _matrix.isInvertible())
  3828. _matrix._backup = _matrix.getValues();
  3829. _matrix.prepend(matrix, true);
  3830. var style = this._style,
  3831. fillColor = style.getFillColor(true),
  3832. strokeColor = style.getStrokeColor(true);
  3833. if (fillColor)
  3834. fillColor.transform(matrix);
  3835. if (strokeColor)
  3836. strokeColor.transform(matrix);
  3837. }
  3838. if (applyMatrix && (applyMatrix = this._transformContent(_matrix,
  3839. _applyRecursively, _setApplyMatrix))) {
  3840. var pivot = this._pivot;
  3841. if (pivot)
  3842. _matrix._transformPoint(pivot, pivot, true);
  3843. _matrix.reset(true);
  3844. if (_setApplyMatrix && this._canApplyMatrix)
  3845. this._applyMatrix = true;
  3846. }
  3847. var bounds = this._bounds,
  3848. position = this._position;
  3849. if (transform || applyMatrix) {
  3850. this._changed(9);
  3851. }
  3852. var decomp = transform && bounds && matrix.decompose();
  3853. if (decomp && decomp.skewing.isZero() && decomp.rotation % 90 === 0) {
  3854. for (var key in bounds) {
  3855. var cache = bounds[key];
  3856. if (cache.nonscaling) {
  3857. delete bounds[key];
  3858. } else if (applyMatrix || !cache.internal) {
  3859. var rect = cache.rect;
  3860. matrix._transformBounds(rect, rect);
  3861. }
  3862. }
  3863. this._bounds = bounds;
  3864. var cached = bounds[this._getBoundsCacheKey(
  3865. this._boundsOptions || {})];
  3866. if (cached) {
  3867. this._position = cached.rect.getCenter(true);
  3868. }
  3869. } else if (transform && position && this._pivot) {
  3870. this._position = matrix._transformPoint(position, position);
  3871. }
  3872. return this;
  3873. },
  3874. _transformContent: function(matrix, applyRecursively, setApplyMatrix) {
  3875. var children = this._children;
  3876. if (children) {
  3877. for (var i = 0, l = children.length; i < l; i++)
  3878. children[i].transform(matrix, true, applyRecursively,
  3879. setApplyMatrix);
  3880. return true;
  3881. }
  3882. },
  3883. globalToLocal: function() {
  3884. return this.getGlobalMatrix(true)._inverseTransform(
  3885. Point.read(arguments));
  3886. },
  3887. localToGlobal: function() {
  3888. return this.getGlobalMatrix(true)._transformPoint(
  3889. Point.read(arguments));
  3890. },
  3891. parentToLocal: function() {
  3892. return this._matrix._inverseTransform(Point.read(arguments));
  3893. },
  3894. localToParent: function() {
  3895. return this._matrix._transformPoint(Point.read(arguments));
  3896. },
  3897. fitBounds: function(rectangle, fill) {
  3898. rectangle = Rectangle.read(arguments);
  3899. var bounds = this.getBounds(),
  3900. itemRatio = bounds.height / bounds.width,
  3901. rectRatio = rectangle.height / rectangle.width,
  3902. scale = (fill ? itemRatio > rectRatio : itemRatio < rectRatio)
  3903. ? rectangle.width / bounds.width
  3904. : rectangle.height / bounds.height,
  3905. newBounds = new Rectangle(new Point(),
  3906. new Size(bounds.width * scale, bounds.height * scale));
  3907. newBounds.setCenter(rectangle.getCenter());
  3908. this.setBounds(newBounds);
  3909. }
  3910. }), {
  3911. _setStyles: function(ctx, param, viewMatrix) {
  3912. var style = this._style,
  3913. matrix = this._matrix;
  3914. if (style.hasFill()) {
  3915. ctx.fillStyle = style.getFillColor().toCanvasStyle(ctx, matrix);
  3916. }
  3917. if (style.hasStroke()) {
  3918. ctx.strokeStyle = style.getStrokeColor().toCanvasStyle(ctx, matrix);
  3919. ctx.lineWidth = style.getStrokeWidth();
  3920. var strokeJoin = style.getStrokeJoin(),
  3921. strokeCap = style.getStrokeCap(),
  3922. miterLimit = style.getMiterLimit();
  3923. if (strokeJoin)
  3924. ctx.lineJoin = strokeJoin;
  3925. if (strokeCap)
  3926. ctx.lineCap = strokeCap;
  3927. if (miterLimit)
  3928. ctx.miterLimit = miterLimit;
  3929. if (paper.support.nativeDash) {
  3930. var dashArray = style.getDashArray(),
  3931. dashOffset = style.getDashOffset();
  3932. if (dashArray && dashArray.length) {
  3933. if ('setLineDash' in ctx) {
  3934. ctx.setLineDash(dashArray);
  3935. ctx.lineDashOffset = dashOffset;
  3936. } else {
  3937. ctx.mozDash = dashArray;
  3938. ctx.mozDashOffset = dashOffset;
  3939. }
  3940. }
  3941. }
  3942. }
  3943. if (style.hasShadow()) {
  3944. var pixelRatio = param.pixelRatio || 1,
  3945. mx = viewMatrix._shiftless().prepend(
  3946. new Matrix().scale(pixelRatio, pixelRatio)),
  3947. blur = mx.transform(new Point(style.getShadowBlur(), 0)),
  3948. offset = mx.transform(this.getShadowOffset());
  3949. ctx.shadowColor = style.getShadowColor().toCanvasStyle(ctx);
  3950. ctx.shadowBlur = blur.getLength();
  3951. ctx.shadowOffsetX = offset.x;
  3952. ctx.shadowOffsetY = offset.y;
  3953. }
  3954. },
  3955. draw: function(ctx, param, parentStrokeMatrix) {
  3956. var updateVersion = this._updateVersion = this._project._updateVersion;
  3957. if (!this._visible || this._opacity === 0)
  3958. return;
  3959. var matrices = param.matrices,
  3960. viewMatrix = param.viewMatrix,
  3961. matrix = this._matrix,
  3962. globalMatrix = matrices[matrices.length - 1].appended(matrix);
  3963. if (!globalMatrix.isInvertible())
  3964. return;
  3965. viewMatrix = viewMatrix ? viewMatrix.appended(globalMatrix)
  3966. : globalMatrix;
  3967. matrices.push(globalMatrix);
  3968. if (param.updateMatrix) {
  3969. globalMatrix._updateVersion = updateVersion;
  3970. this._globalMatrix = globalMatrix;
  3971. }
  3972. var blendMode = this._blendMode,
  3973. opacity = this._opacity,
  3974. normalBlend = blendMode === 'normal',
  3975. nativeBlend = BlendMode.nativeModes[blendMode],
  3976. direct = normalBlend && opacity === 1
  3977. || param.dontStart
  3978. || param.clip
  3979. || (nativeBlend || normalBlend && opacity < 1)
  3980. && this._canComposite(),
  3981. pixelRatio = param.pixelRatio || 1,
  3982. mainCtx, itemOffset, prevOffset;
  3983. if (!direct) {
  3984. var bounds = this.getStrokeBounds(viewMatrix);
  3985. if (!bounds.width || !bounds.height)
  3986. return;
  3987. prevOffset = param.offset;
  3988. itemOffset = param.offset = bounds.getTopLeft().floor();
  3989. mainCtx = ctx;
  3990. ctx = CanvasProvider.getContext(bounds.getSize().ceil().add(1)
  3991. .multiply(pixelRatio));
  3992. if (pixelRatio !== 1)
  3993. ctx.scale(pixelRatio, pixelRatio);
  3994. }
  3995. ctx.save();
  3996. var strokeMatrix = parentStrokeMatrix
  3997. ? parentStrokeMatrix.appended(matrix)
  3998. : this._canScaleStroke && !this.getStrokeScaling(true)
  3999. && viewMatrix,
  4000. clip = !direct && param.clipItem,
  4001. transform = !strokeMatrix || clip;
  4002. if (direct) {
  4003. ctx.globalAlpha = opacity;
  4004. if (nativeBlend)
  4005. ctx.globalCompositeOperation = blendMode;
  4006. } else if (transform) {
  4007. ctx.translate(-itemOffset.x, -itemOffset.y);
  4008. }
  4009. if (transform) {
  4010. (direct ? matrix : viewMatrix).applyToContext(ctx);
  4011. }
  4012. if (clip) {
  4013. param.clipItem.draw(ctx, param.extend({ clip: true }));
  4014. }
  4015. if (strokeMatrix) {
  4016. ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0);
  4017. var offset = param.offset;
  4018. if (offset)
  4019. ctx.translate(-offset.x, -offset.y);
  4020. }
  4021. this._draw(ctx, param, viewMatrix, strokeMatrix);
  4022. ctx.restore();
  4023. matrices.pop();
  4024. if (param.clip && !param.dontFinish)
  4025. ctx.clip();
  4026. if (!direct) {
  4027. BlendMode.process(blendMode, ctx, mainCtx, opacity,
  4028. itemOffset.subtract(prevOffset).multiply(pixelRatio));
  4029. CanvasProvider.release(ctx);
  4030. param.offset = prevOffset;
  4031. }
  4032. },
  4033. _isUpdated: function(updateVersion) {
  4034. var parent = this._parent;
  4035. if (parent instanceof CompoundPath)
  4036. return parent._isUpdated(updateVersion);
  4037. var updated = this._updateVersion === updateVersion;
  4038. if (!updated && parent && parent._visible
  4039. && parent._isUpdated(updateVersion)) {
  4040. this._updateVersion = updateVersion;
  4041. updated = true;
  4042. }
  4043. return updated;
  4044. },
  4045. _drawSelection: function(ctx, matrix, size, selectionItems, updateVersion) {
  4046. var selection = this._selection,
  4047. itemSelected = selection & 1,
  4048. boundsSelected = selection & 2
  4049. || itemSelected && this._selectBounds,
  4050. positionSelected = selection & 4;
  4051. if (!this._drawSelected)
  4052. itemSelected = false;
  4053. if ((itemSelected || boundsSelected || positionSelected)
  4054. && this._isUpdated(updateVersion)) {
  4055. var layer,
  4056. color = this.getSelectedColor(true) || (layer = this.getLayer())
  4057. && layer.getSelectedColor(true),
  4058. mx = matrix.appended(this.getGlobalMatrix(true)),
  4059. half = size / 2;
  4060. ctx.strokeStyle = ctx.fillStyle = color
  4061. ? color.toCanvasStyle(ctx) : '#009dec';
  4062. if (itemSelected)
  4063. this._drawSelected(ctx, mx, selectionItems);
  4064. if (positionSelected) {
  4065. var point = this.getPosition(true),
  4066. x = point.x,
  4067. y = point.y;
  4068. ctx.beginPath();
  4069. ctx.arc(x, y, half, 0, Math.PI * 2, true);
  4070. ctx.stroke();
  4071. var deltas = [[0, -1], [1, 0], [0, 1], [-1, 0]],
  4072. start = half,
  4073. end = size + 1;
  4074. for (var i = 0; i < 4; i++) {
  4075. var delta = deltas[i],
  4076. dx = delta[0],
  4077. dy = delta[1];
  4078. ctx.moveTo(x + dx * start, y + dy * start);
  4079. ctx.lineTo(x + dx * end, y + dy * end);
  4080. ctx.stroke();
  4081. }
  4082. }
  4083. if (boundsSelected) {
  4084. var coords = mx._transformCorners(this.getInternalBounds());
  4085. ctx.beginPath();
  4086. for (var i = 0; i < 8; i++) {
  4087. ctx[!i ? 'moveTo' : 'lineTo'](coords[i], coords[++i]);
  4088. }
  4089. ctx.closePath();
  4090. ctx.stroke();
  4091. for (var i = 0; i < 8; i++) {
  4092. ctx.fillRect(coords[i] - half, coords[++i] - half,
  4093. size, size);
  4094. }
  4095. }
  4096. }
  4097. },
  4098. _canComposite: function() {
  4099. return false;
  4100. }
  4101. }, Base.each(['down', 'drag', 'up', 'move'], function(key) {
  4102. this['removeOn' + Base.capitalize(key)] = function() {
  4103. var hash = {};
  4104. hash[key] = true;
  4105. return this.removeOn(hash);
  4106. };
  4107. }, {
  4108. removeOn: function(obj) {
  4109. for (var name in obj) {
  4110. if (obj[name]) {
  4111. var key = 'mouse' + name,
  4112. project = this._project,
  4113. sets = project._removeSets = project._removeSets || {};
  4114. sets[key] = sets[key] || {};
  4115. sets[key][this._id] = this;
  4116. }
  4117. }
  4118. return this;
  4119. }
  4120. }));
  4121. var Group = Item.extend({
  4122. _class: 'Group',
  4123. _selectBounds: false,
  4124. _selectChildren: true,
  4125. _serializeFields: {
  4126. children: []
  4127. },
  4128. initialize: function Group(arg) {
  4129. this._children = [];
  4130. this._namedChildren = {};
  4131. if (!this._initialize(arg))
  4132. this.addChildren(Array.isArray(arg) ? arg : arguments);
  4133. },
  4134. _changed: function _changed(flags) {
  4135. _changed.base.call(this, flags);
  4136. if (flags & 1026) {
  4137. this._clipItem = undefined;
  4138. }
  4139. },
  4140. _getClipItem: function() {
  4141. var clipItem = this._clipItem;
  4142. if (clipItem === undefined) {
  4143. clipItem = null;
  4144. var children = this._children;
  4145. for (var i = 0, l = children.length; i < l; i++) {
  4146. if (children[i]._clipMask) {
  4147. clipItem = children[i];
  4148. break;
  4149. }
  4150. }
  4151. this._clipItem = clipItem;
  4152. }
  4153. return clipItem;
  4154. },
  4155. isClipped: function() {
  4156. return !!this._getClipItem();
  4157. },
  4158. setClipped: function(clipped) {
  4159. var child = this.getFirstChild();
  4160. if (child)
  4161. child.setClipMask(clipped);
  4162. },
  4163. _getBounds: function _getBounds(matrix, options) {
  4164. var clipItem = this._getClipItem();
  4165. return clipItem
  4166. ? clipItem._getCachedBounds(
  4167. matrix && matrix.appended(clipItem._matrix),
  4168. Base.set({}, options, { stroke: false }))
  4169. : _getBounds.base.call(this, matrix, options);
  4170. },
  4171. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  4172. var clipItem = this._getClipItem();
  4173. return (!clipItem || clipItem.contains(point))
  4174. && _hitTestChildren.base.call(this, point, options, viewMatrix,
  4175. clipItem);
  4176. },
  4177. _draw: function(ctx, param) {
  4178. var clip = param.clip,
  4179. clipItem = !clip && this._getClipItem();
  4180. param = param.extend({ clipItem: clipItem, clip: false });
  4181. if (clip) {
  4182. ctx.beginPath();
  4183. param.dontStart = param.dontFinish = true;
  4184. } else if (clipItem) {
  4185. clipItem.draw(ctx, param.extend({ clip: true }));
  4186. }
  4187. var children = this._children;
  4188. for (var i = 0, l = children.length; i < l; i++) {
  4189. var item = children[i];
  4190. if (item !== clipItem)
  4191. item.draw(ctx, param);
  4192. }
  4193. }
  4194. });
  4195. var Layer = Group.extend({
  4196. _class: 'Layer',
  4197. initialize: function Layer() {
  4198. Group.apply(this, arguments);
  4199. },
  4200. _getOwner: function() {
  4201. return this._parent || this._index != null && this._project;
  4202. },
  4203. isInserted: function isInserted() {
  4204. return this._parent ? isInserted.base.call(this) : this._index != null;
  4205. },
  4206. activate: function() {
  4207. this._project._activeLayer = this;
  4208. },
  4209. _hitTestSelf: function() {
  4210. }
  4211. });
  4212. var Shape = Item.extend({
  4213. _class: 'Shape',
  4214. _applyMatrix: false,
  4215. _canApplyMatrix: false,
  4216. _canScaleStroke: true,
  4217. _serializeFields: {
  4218. type: null,
  4219. size: null,
  4220. radius: null
  4221. },
  4222. initialize: function Shape(props, point) {
  4223. this._initialize(props, point);
  4224. },
  4225. _equals: function(item) {
  4226. return this._type === item._type
  4227. && this._size.equals(item._size)
  4228. && Base.equals(this._radius, item._radius);
  4229. },
  4230. copyContent: function(source) {
  4231. this.setType(source._type);
  4232. this.setSize(source._size);
  4233. this.setRadius(source._radius);
  4234. },
  4235. getType: function() {
  4236. return this._type;
  4237. },
  4238. setType: function(type) {
  4239. this._type = type;
  4240. },
  4241. getShape: '#getType',
  4242. setShape: '#setType',
  4243. getSize: function() {
  4244. var size = this._size;
  4245. return new LinkedSize(size.width, size.height, this, 'setSize');
  4246. },
  4247. setSize: function() {
  4248. var size = Size.read(arguments);
  4249. if (!this._size) {
  4250. this._size = size.clone();
  4251. } else if (!this._size.equals(size)) {
  4252. var type = this._type,
  4253. width = size.width,
  4254. height = size.height;
  4255. if (type === 'rectangle') {
  4256. this._radius.set(Size.min(this._radius, size.divide(2)));
  4257. } else if (type === 'circle') {
  4258. width = height = (width + height) / 2;
  4259. this._radius = width / 2;
  4260. } else if (type === 'ellipse') {
  4261. this._radius._set(width / 2, height / 2);
  4262. }
  4263. this._size._set(width, height);
  4264. this._changed(9);
  4265. }
  4266. },
  4267. getRadius: function() {
  4268. var rad = this._radius;
  4269. return this._type === 'circle'
  4270. ? rad
  4271. : new LinkedSize(rad.width, rad.height, this, 'setRadius');
  4272. },
  4273. setRadius: function(radius) {
  4274. var type = this._type;
  4275. if (type === 'circle') {
  4276. if (radius === this._radius)
  4277. return;
  4278. var size = radius * 2;
  4279. this._radius = radius;
  4280. this._size._set(size, size);
  4281. } else {
  4282. radius = Size.read(arguments);
  4283. if (!this._radius) {
  4284. this._radius = radius.clone();
  4285. } else {
  4286. if (this._radius.equals(radius))
  4287. return;
  4288. this._radius.set(radius);
  4289. if (type === 'rectangle') {
  4290. var size = Size.max(this._size, radius.multiply(2));
  4291. this._size.set(size);
  4292. } else if (type === 'ellipse') {
  4293. this._size._set(radius.width * 2, radius.height * 2);
  4294. }
  4295. }
  4296. }
  4297. this._changed(9);
  4298. },
  4299. isEmpty: function() {
  4300. return false;
  4301. },
  4302. toPath: function(insert) {
  4303. var path = new Path[Base.capitalize(this._type)]({
  4304. center: new Point(),
  4305. size: this._size,
  4306. radius: this._radius,
  4307. insert: false
  4308. });
  4309. path.copyAttributes(this);
  4310. if (paper.settings.applyMatrix)
  4311. path.setApplyMatrix(true);
  4312. if (insert === undefined || insert)
  4313. path.insertAbove(this);
  4314. return path;
  4315. },
  4316. toShape: '#clone',
  4317. _asPathItem: function() {
  4318. return this.toPath(false);
  4319. },
  4320. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  4321. var style = this._style,
  4322. hasFill = style.hasFill(),
  4323. hasStroke = style.hasStroke(),
  4324. dontPaint = param.dontFinish || param.clip,
  4325. untransformed = !strokeMatrix;
  4326. if (hasFill || hasStroke || dontPaint) {
  4327. var type = this._type,
  4328. radius = this._radius,
  4329. isCircle = type === 'circle';
  4330. if (!param.dontStart)
  4331. ctx.beginPath();
  4332. if (untransformed && isCircle) {
  4333. ctx.arc(0, 0, radius, 0, Math.PI * 2, true);
  4334. } else {
  4335. var rx = isCircle ? radius : radius.width,
  4336. ry = isCircle ? radius : radius.height,
  4337. size = this._size,
  4338. width = size.width,
  4339. height = size.height;
  4340. if (untransformed && type === 'rectangle' && rx === 0 && ry === 0) {
  4341. ctx.rect(-width / 2, -height / 2, width, height);
  4342. } else {
  4343. var x = width / 2,
  4344. y = height / 2,
  4345. kappa = 1 - 0.5522847498307936,
  4346. cx = rx * kappa,
  4347. cy = ry * kappa,
  4348. c = [
  4349. -x, -y + ry,
  4350. -x, -y + cy,
  4351. -x + cx, -y,
  4352. -x + rx, -y,
  4353. x - rx, -y,
  4354. x - cx, -y,
  4355. x, -y + cy,
  4356. x, -y + ry,
  4357. x, y - ry,
  4358. x, y - cy,
  4359. x - cx, y,
  4360. x - rx, y,
  4361. -x + rx, y,
  4362. -x + cx, y,
  4363. -x, y - cy,
  4364. -x, y - ry
  4365. ];
  4366. if (strokeMatrix)
  4367. strokeMatrix.transform(c, c, 32);
  4368. ctx.moveTo(c[0], c[1]);
  4369. ctx.bezierCurveTo(c[2], c[3], c[4], c[5], c[6], c[7]);
  4370. if (x !== rx)
  4371. ctx.lineTo(c[8], c[9]);
  4372. ctx.bezierCurveTo(c[10], c[11], c[12], c[13], c[14], c[15]);
  4373. if (y !== ry)
  4374. ctx.lineTo(c[16], c[17]);
  4375. ctx.bezierCurveTo(c[18], c[19], c[20], c[21], c[22], c[23]);
  4376. if (x !== rx)
  4377. ctx.lineTo(c[24], c[25]);
  4378. ctx.bezierCurveTo(c[26], c[27], c[28], c[29], c[30], c[31]);
  4379. }
  4380. }
  4381. ctx.closePath();
  4382. }
  4383. if (!dontPaint && (hasFill || hasStroke)) {
  4384. this._setStyles(ctx, param, viewMatrix);
  4385. if (hasFill) {
  4386. ctx.fill(style.getFillRule());
  4387. ctx.shadowColor = 'rgba(0,0,0,0)';
  4388. }
  4389. if (hasStroke)
  4390. ctx.stroke();
  4391. }
  4392. },
  4393. _canComposite: function() {
  4394. return !(this.hasFill() && this.hasStroke());
  4395. },
  4396. _getBounds: function(matrix, options) {
  4397. var rect = new Rectangle(this._size).setCenter(0, 0),
  4398. style = this._style,
  4399. strokeWidth = options.stroke && style.hasStroke()
  4400. && style.getStrokeWidth();
  4401. if (matrix)
  4402. rect = matrix._transformBounds(rect);
  4403. return strokeWidth
  4404. ? rect.expand(Path._getStrokePadding(strokeWidth,
  4405. this._getStrokeMatrix(matrix, options)))
  4406. : rect;
  4407. }
  4408. },
  4409. new function() {
  4410. function getCornerCenter(that, point, expand) {
  4411. var radius = that._radius;
  4412. if (!radius.isZero()) {
  4413. var halfSize = that._size.divide(2);
  4414. for (var q = 1; q <= 4; q++) {
  4415. var dir = new Point(q > 1 && q < 4 ? -1 : 1, q > 2 ? -1 : 1),
  4416. corner = dir.multiply(halfSize),
  4417. center = corner.subtract(dir.multiply(radius)),
  4418. rect = new Rectangle(
  4419. expand ? corner.add(dir.multiply(expand)) : corner,
  4420. center);
  4421. if (rect.contains(point))
  4422. return { point: center, quadrant: q };
  4423. }
  4424. }
  4425. }
  4426. function isOnEllipseStroke(point, radius, padding, quadrant) {
  4427. var vector = point.divide(radius);
  4428. return (!quadrant || vector.isInQuadrant(quadrant)) &&
  4429. vector.subtract(vector.normalize()).multiply(radius)
  4430. .divide(padding).length <= 1;
  4431. }
  4432. return {
  4433. _contains: function _contains(point) {
  4434. if (this._type === 'rectangle') {
  4435. var center = getCornerCenter(this, point);
  4436. return center
  4437. ? point.subtract(center.point).divide(this._radius)
  4438. .getLength() <= 1
  4439. : _contains.base.call(this, point);
  4440. } else {
  4441. return point.divide(this.size).getLength() <= 0.5;
  4442. }
  4443. },
  4444. _hitTestSelf: function _hitTestSelf(point, options, viewMatrix,
  4445. strokeMatrix) {
  4446. var hit = false,
  4447. style = this._style,
  4448. hitStroke = options.stroke && style.hasStroke(),
  4449. hitFill = options.fill && style.hasFill();
  4450. if (hitStroke || hitFill) {
  4451. var type = this._type,
  4452. radius = this._radius,
  4453. strokeRadius = hitStroke ? style.getStrokeWidth() / 2 : 0,
  4454. strokePadding = options._tolerancePadding.add(
  4455. Path._getStrokePadding(strokeRadius,
  4456. !style.getStrokeScaling() && strokeMatrix));
  4457. if (type === 'rectangle') {
  4458. var padding = strokePadding.multiply(2),
  4459. center = getCornerCenter(this, point, padding);
  4460. if (center) {
  4461. hit = isOnEllipseStroke(point.subtract(center.point),
  4462. radius, strokePadding, center.quadrant);
  4463. } else {
  4464. var rect = new Rectangle(this._size).setCenter(0, 0),
  4465. outer = rect.expand(padding),
  4466. inner = rect.expand(padding.negate());
  4467. hit = outer._containsPoint(point)
  4468. && !inner._containsPoint(point);
  4469. }
  4470. } else {
  4471. hit = isOnEllipseStroke(point, radius, strokePadding);
  4472. }
  4473. }
  4474. return hit ? new HitResult(hitStroke ? 'stroke' : 'fill', this)
  4475. : _hitTestSelf.base.apply(this, arguments);
  4476. }
  4477. };
  4478. }, {
  4479. statics: new function() {
  4480. function createShape(type, point, size, radius, args) {
  4481. var item = new Shape(Base.getNamed(args), point);
  4482. item._type = type;
  4483. item._size = size;
  4484. item._radius = radius;
  4485. return item;
  4486. }
  4487. return {
  4488. Circle: function() {
  4489. var center = Point.readNamed(arguments, 'center'),
  4490. radius = Base.readNamed(arguments, 'radius');
  4491. return createShape('circle', center, new Size(radius * 2), radius,
  4492. arguments);
  4493. },
  4494. Rectangle: function() {
  4495. var rect = Rectangle.readNamed(arguments, 'rectangle'),
  4496. radius = Size.min(Size.readNamed(arguments, 'radius'),
  4497. rect.getSize(true).divide(2));
  4498. return createShape('rectangle', rect.getCenter(true),
  4499. rect.getSize(true), radius, arguments);
  4500. },
  4501. Ellipse: function() {
  4502. var ellipse = Shape._readEllipse(arguments),
  4503. radius = ellipse.radius;
  4504. return createShape('ellipse', ellipse.center, radius.multiply(2),
  4505. radius, arguments);
  4506. },
  4507. _readEllipse: function(args) {
  4508. var center,
  4509. radius;
  4510. if (Base.hasNamed(args, 'radius')) {
  4511. center = Point.readNamed(args, 'center');
  4512. radius = Size.readNamed(args, 'radius');
  4513. } else {
  4514. var rect = Rectangle.readNamed(args, 'rectangle');
  4515. center = rect.getCenter(true);
  4516. radius = rect.getSize(true).divide(2);
  4517. }
  4518. return { center: center, radius: radius };
  4519. }
  4520. };
  4521. }});
  4522. var Raster = Item.extend({
  4523. _class: 'Raster',
  4524. _applyMatrix: false,
  4525. _canApplyMatrix: false,
  4526. _boundsOptions: { stroke: false, handle: false },
  4527. _serializeFields: {
  4528. crossOrigin: null,
  4529. source: null
  4530. },
  4531. _prioritize: ['crossOrigin'],
  4532. initialize: function Raster(object, position) {
  4533. if (!this._initialize(object,
  4534. position !== undefined && Point.read(arguments, 1))) {
  4535. var image = typeof object === 'string'
  4536. ? document.getElementById(object) : object;
  4537. if (image) {
  4538. this.setImage(image);
  4539. } else {
  4540. this.setSource(object);
  4541. }
  4542. }
  4543. if (!this._size) {
  4544. this._size = new Size();
  4545. this._loaded = false;
  4546. }
  4547. },
  4548. _equals: function(item) {
  4549. return this.getSource() === item.getSource();
  4550. },
  4551. copyContent: function(source) {
  4552. var image = source._image,
  4553. canvas = source._canvas;
  4554. if (image) {
  4555. this._setImage(image);
  4556. } else if (canvas) {
  4557. var copyCanvas = CanvasProvider.getCanvas(source._size);
  4558. copyCanvas.getContext('2d').drawImage(canvas, 0, 0);
  4559. this._setImage(copyCanvas);
  4560. }
  4561. this._crossOrigin = source._crossOrigin;
  4562. },
  4563. getSize: function() {
  4564. var size = this._size;
  4565. return new LinkedSize(size ? size.width : 0, size ? size.height : 0,
  4566. this, 'setSize');
  4567. },
  4568. setSize: function() {
  4569. var size = Size.read(arguments);
  4570. if (!size.equals(this._size)) {
  4571. if (size.width > 0 && size.height > 0) {
  4572. var element = this.getElement();
  4573. this._setImage(CanvasProvider.getCanvas(size));
  4574. if (element)
  4575. this.getContext(true).drawImage(element, 0, 0,
  4576. size.width, size.height);
  4577. } else {
  4578. if (this._canvas)
  4579. CanvasProvider.release(this._canvas);
  4580. this._size = size.clone();
  4581. }
  4582. }
  4583. },
  4584. getWidth: function() {
  4585. return this._size ? this._size.width : 0;
  4586. },
  4587. setWidth: function(width) {
  4588. this.setSize(width, this.getHeight());
  4589. },
  4590. getHeight: function() {
  4591. return this._size ? this._size.height : 0;
  4592. },
  4593. setHeight: function(height) {
  4594. this.setSize(this.getWidth(), height);
  4595. },
  4596. getLoaded: function() {
  4597. return this._loaded;
  4598. },
  4599. isEmpty: function() {
  4600. var size = this._size;
  4601. return !size || size.width === 0 && size.height === 0;
  4602. },
  4603. getResolution: function() {
  4604. var matrix = this._matrix,
  4605. orig = new Point(0, 0).transform(matrix),
  4606. u = new Point(1, 0).transform(matrix).subtract(orig),
  4607. v = new Point(0, 1).transform(matrix).subtract(orig);
  4608. return new Size(
  4609. 72 / u.getLength(),
  4610. 72 / v.getLength()
  4611. );
  4612. },
  4613. getPpi: '#getResolution',
  4614. getImage: function() {
  4615. return this._image;
  4616. },
  4617. setImage: function(image) {
  4618. var that = this;
  4619. function emit(event) {
  4620. var view = that.getView(),
  4621. type = event && event.type || 'load';
  4622. if (view && that.responds(type)) {
  4623. paper = view._scope;
  4624. that.emit(type, new Event(event));
  4625. }
  4626. }
  4627. this._setImage(image);
  4628. if (this._loaded) {
  4629. setTimeout(emit, 0);
  4630. } else if (image) {
  4631. DomEvent.add(image, {
  4632. load: function(event) {
  4633. that._setImage(image);
  4634. emit(event);
  4635. },
  4636. error: emit
  4637. });
  4638. }
  4639. },
  4640. _setImage: function(image) {
  4641. if (this._canvas)
  4642. CanvasProvider.release(this._canvas);
  4643. if (image && image.getContext) {
  4644. this._image = null;
  4645. this._canvas = image;
  4646. this._loaded = true;
  4647. } else {
  4648. this._image = image;
  4649. this._canvas = null;
  4650. this._loaded = !!(image && image.src && image.complete);
  4651. }
  4652. this._size = new Size(
  4653. image ? image.naturalWidth || image.width : 0,
  4654. image ? image.naturalHeight || image.height : 0);
  4655. this._context = null;
  4656. this._changed(521);
  4657. },
  4658. getCanvas: function() {
  4659. if (!this._canvas) {
  4660. var ctx = CanvasProvider.getContext(this._size);
  4661. try {
  4662. if (this._image)
  4663. ctx.drawImage(this._image, 0, 0);
  4664. this._canvas = ctx.canvas;
  4665. } catch (e) {
  4666. CanvasProvider.release(ctx);
  4667. }
  4668. }
  4669. return this._canvas;
  4670. },
  4671. setCanvas: '#setImage',
  4672. getContext: function(modify) {
  4673. if (!this._context)
  4674. this._context = this.getCanvas().getContext('2d');
  4675. if (modify) {
  4676. this._image = null;
  4677. this._changed(513);
  4678. }
  4679. return this._context;
  4680. },
  4681. setContext: function(context) {
  4682. this._context = context;
  4683. },
  4684. getSource: function() {
  4685. var image = this._image;
  4686. return image && image.src || this.toDataURL();
  4687. },
  4688. setSource: function(src) {
  4689. var image = new self.Image(),
  4690. crossOrigin = this._crossOrigin;
  4691. if (crossOrigin)
  4692. image.crossOrigin = crossOrigin;
  4693. image.src = src;
  4694. this.setImage(image);
  4695. },
  4696. getCrossOrigin: function() {
  4697. var image = this._image;
  4698. return image && image.crossOrigin || this._crossOrigin || '';
  4699. },
  4700. setCrossOrigin: function(crossOrigin) {
  4701. this._crossOrigin = crossOrigin;
  4702. var image = this._image;
  4703. if (image)
  4704. image.crossOrigin = crossOrigin;
  4705. },
  4706. getElement: function() {
  4707. return this._canvas || this._loaded && this._image;
  4708. }
  4709. }, {
  4710. beans: false,
  4711. getSubCanvas: function() {
  4712. var rect = Rectangle.read(arguments),
  4713. ctx = CanvasProvider.getContext(rect.getSize());
  4714. ctx.drawImage(this.getCanvas(), rect.x, rect.y,
  4715. rect.width, rect.height, 0, 0, rect.width, rect.height);
  4716. return ctx.canvas;
  4717. },
  4718. getSubRaster: function() {
  4719. var rect = Rectangle.read(arguments),
  4720. raster = new Raster(Item.NO_INSERT);
  4721. raster._setImage(this.getSubCanvas(rect));
  4722. raster.translate(rect.getCenter().subtract(this.getSize().divide(2)));
  4723. raster._matrix.prepend(this._matrix);
  4724. raster.insertAbove(this);
  4725. return raster;
  4726. },
  4727. toDataURL: function() {
  4728. var image = this._image,
  4729. src = image && image.src;
  4730. if (/^data:/.test(src))
  4731. return src;
  4732. var canvas = this.getCanvas();
  4733. return canvas ? canvas.toDataURL.apply(canvas, arguments) : null;
  4734. },
  4735. drawImage: function(image ) {
  4736. var point = Point.read(arguments, 1);
  4737. this.getContext(true).drawImage(image, point.x, point.y);
  4738. },
  4739. getAverageColor: function(object) {
  4740. var bounds, path;
  4741. if (!object) {
  4742. bounds = this.getBounds();
  4743. } else if (object instanceof PathItem) {
  4744. path = object;
  4745. bounds = object.getBounds();
  4746. } else if (typeof object === 'object') {
  4747. if ('width' in object) {
  4748. bounds = new Rectangle(object);
  4749. } else if ('x' in object) {
  4750. bounds = new Rectangle(object.x - 0.5, object.y - 0.5, 1, 1);
  4751. }
  4752. }
  4753. if (!bounds)
  4754. return null;
  4755. var sampleSize = 32,
  4756. width = Math.min(bounds.width, sampleSize),
  4757. height = Math.min(bounds.height, sampleSize);
  4758. var ctx = Raster._sampleContext;
  4759. if (!ctx) {
  4760. ctx = Raster._sampleContext = CanvasProvider.getContext(
  4761. new Size(sampleSize));
  4762. } else {
  4763. ctx.clearRect(0, 0, sampleSize + 1, sampleSize + 1);
  4764. }
  4765. ctx.save();
  4766. var matrix = new Matrix()
  4767. .scale(width / bounds.width, height / bounds.height)
  4768. .translate(-bounds.x, -bounds.y);
  4769. matrix.applyToContext(ctx);
  4770. if (path)
  4771. path.draw(ctx, new Base({ clip: true, matrices: [matrix] }));
  4772. this._matrix.applyToContext(ctx);
  4773. var element = this.getElement(),
  4774. size = this._size;
  4775. if (element)
  4776. ctx.drawImage(element, -size.width / 2, -size.height / 2);
  4777. ctx.restore();
  4778. var pixels = ctx.getImageData(0.5, 0.5, Math.ceil(width),
  4779. Math.ceil(height)).data,
  4780. channels = [0, 0, 0],
  4781. total = 0;
  4782. for (var i = 0, l = pixels.length; i < l; i += 4) {
  4783. var alpha = pixels[i + 3];
  4784. total += alpha;
  4785. alpha /= 255;
  4786. channels[0] += pixels[i] * alpha;
  4787. channels[1] += pixels[i + 1] * alpha;
  4788. channels[2] += pixels[i + 2] * alpha;
  4789. }
  4790. for (var i = 0; i < 3; i++)
  4791. channels[i] /= total;
  4792. return total ? Color.read(channels) : null;
  4793. },
  4794. getPixel: function() {
  4795. var point = Point.read(arguments);
  4796. var data = this.getContext().getImageData(point.x, point.y, 1, 1).data;
  4797. return new Color('rgb', [data[0] / 255, data[1] / 255, data[2] / 255],
  4798. data[3] / 255);
  4799. },
  4800. setPixel: function() {
  4801. var point = Point.read(arguments),
  4802. color = Color.read(arguments),
  4803. components = color._convert('rgb'),
  4804. alpha = color._alpha,
  4805. ctx = this.getContext(true),
  4806. imageData = ctx.createImageData(1, 1),
  4807. data = imageData.data;
  4808. data[0] = components[0] * 255;
  4809. data[1] = components[1] * 255;
  4810. data[2] = components[2] * 255;
  4811. data[3] = alpha != null ? alpha * 255 : 255;
  4812. ctx.putImageData(imageData, point.x, point.y);
  4813. },
  4814. createImageData: function() {
  4815. var size = Size.read(arguments);
  4816. return this.getContext().createImageData(size.width, size.height);
  4817. },
  4818. getImageData: function() {
  4819. var rect = Rectangle.read(arguments);
  4820. if (rect.isEmpty())
  4821. rect = new Rectangle(this._size);
  4822. return this.getContext().getImageData(rect.x, rect.y,
  4823. rect.width, rect.height);
  4824. },
  4825. setImageData: function(data ) {
  4826. var point = Point.read(arguments, 1);
  4827. this.getContext(true).putImageData(data, point.x, point.y);
  4828. },
  4829. _getBounds: function(matrix, options) {
  4830. var rect = new Rectangle(this._size).setCenter(0, 0);
  4831. return matrix ? matrix._transformBounds(rect) : rect;
  4832. },
  4833. _hitTestSelf: function(point) {
  4834. if (this._contains(point)) {
  4835. var that = this;
  4836. return new HitResult('pixel', that, {
  4837. offset: point.add(that._size.divide(2)).round(),
  4838. color: {
  4839. get: function() {
  4840. return that.getPixel(this.offset);
  4841. }
  4842. }
  4843. });
  4844. }
  4845. },
  4846. _draw: function(ctx) {
  4847. var element = this.getElement();
  4848. if (element) {
  4849. ctx.globalAlpha = this._opacity;
  4850. ctx.drawImage(element,
  4851. -this._size.width / 2, -this._size.height / 2);
  4852. }
  4853. },
  4854. _canComposite: function() {
  4855. return true;
  4856. }
  4857. });
  4858. var SymbolItem = Item.extend({
  4859. _class: 'SymbolItem',
  4860. _applyMatrix: false,
  4861. _canApplyMatrix: false,
  4862. _boundsOptions: { stroke: true },
  4863. _serializeFields: {
  4864. symbol: null
  4865. },
  4866. initialize: function SymbolItem(arg0, arg1) {
  4867. if (!this._initialize(arg0,
  4868. arg1 !== undefined && Point.read(arguments, 1)))
  4869. this.setDefinition(arg0 instanceof SymbolDefinition ?
  4870. arg0 : new SymbolDefinition(arg0));
  4871. },
  4872. _equals: function(item) {
  4873. return this._definition === item._definition;
  4874. },
  4875. copyContent: function(source) {
  4876. this.setDefinition(source._definition);
  4877. },
  4878. getDefinition: function() {
  4879. return this._definition;
  4880. },
  4881. setDefinition: function(definition) {
  4882. this._definition = definition;
  4883. this._changed(9);
  4884. },
  4885. getSymbol: '#getDefinition',
  4886. setSymbol: '#setDefinition',
  4887. isEmpty: function() {
  4888. return this._definition._item.isEmpty();
  4889. },
  4890. _getBounds: function(matrix, options) {
  4891. var item = this._definition._item;
  4892. return item._getCachedBounds(item._matrix.prepended(matrix), options);
  4893. },
  4894. _hitTestSelf: function(point, options, viewMatrix) {
  4895. var res = this._definition._item._hitTest(point, options, viewMatrix);
  4896. if (res)
  4897. res.item = this;
  4898. return res;
  4899. },
  4900. _draw: function(ctx, param) {
  4901. this._definition._item.draw(ctx, param);
  4902. }
  4903. });
  4904. var SymbolDefinition = Base.extend({
  4905. _class: 'SymbolDefinition',
  4906. initialize: function SymbolDefinition(item, dontCenter) {
  4907. this._id = UID.get();
  4908. this.project = paper.project;
  4909. if (item)
  4910. this.setItem(item, dontCenter);
  4911. },
  4912. _serialize: function(options, dictionary) {
  4913. return dictionary.add(this, function() {
  4914. return Base.serialize([this._class, this._item],
  4915. options, false, dictionary);
  4916. });
  4917. },
  4918. _changed: function(flags) {
  4919. if (flags & 8)
  4920. Item._clearBoundsCache(this);
  4921. if (flags & 1)
  4922. this.project._changed(flags);
  4923. },
  4924. getItem: function() {
  4925. return this._item;
  4926. },
  4927. setItem: function(item, _dontCenter) {
  4928. if (item._symbol)
  4929. item = item.clone();
  4930. if (this._item)
  4931. this._item._symbol = null;
  4932. this._item = item;
  4933. item.remove();
  4934. item.setSelected(false);
  4935. if (!_dontCenter)
  4936. item.setPosition(new Point());
  4937. item._symbol = this;
  4938. this._changed(9);
  4939. },
  4940. getDefinition: '#getItem',
  4941. setDefinition: '#setItem',
  4942. place: function(position) {
  4943. return new SymbolItem(this, position);
  4944. },
  4945. clone: function() {
  4946. return new SymbolDefinition(this._item.clone(false));
  4947. },
  4948. equals: function(symbol) {
  4949. return symbol === this
  4950. || symbol && this._item.equals(symbol._item)
  4951. || false;
  4952. }
  4953. });
  4954. var HitResult = Base.extend({
  4955. _class: 'HitResult',
  4956. initialize: function HitResult(type, item, values) {
  4957. this.type = type;
  4958. this.item = item;
  4959. if (values)
  4960. this.inject(values);
  4961. },
  4962. statics: {
  4963. getOptions: function(args) {
  4964. var options = args && Base.read(args);
  4965. return Base.set({
  4966. type: null,
  4967. tolerance: paper.settings.hitTolerance,
  4968. fill: !options,
  4969. stroke: !options,
  4970. segments: !options,
  4971. handles: false,
  4972. ends: false,
  4973. position: false,
  4974. center: false,
  4975. bounds: false,
  4976. guides: false,
  4977. selected: false
  4978. }, options);
  4979. }
  4980. }
  4981. });
  4982. var Segment = Base.extend({
  4983. _class: 'Segment',
  4984. beans: true,
  4985. _selection: 0,
  4986. initialize: function Segment(arg0, arg1, arg2, arg3, arg4, arg5) {
  4987. var count = arguments.length,
  4988. point, handleIn, handleOut, selection;
  4989. if (count > 0) {
  4990. if (arg0 == null || typeof arg0 === 'object') {
  4991. if (count === 1 && arg0 && 'point' in arg0) {
  4992. point = arg0.point;
  4993. handleIn = arg0.handleIn;
  4994. handleOut = arg0.handleOut;
  4995. selection = arg0.selection;
  4996. } else {
  4997. point = arg0;
  4998. handleIn = arg1;
  4999. handleOut = arg2;
  5000. selection = arg3;
  5001. }
  5002. } else {
  5003. point = [ arg0, arg1 ];
  5004. handleIn = arg2 !== undefined ? [ arg2, arg3 ] : null;
  5005. handleOut = arg4 !== undefined ? [ arg4, arg5 ] : null;
  5006. }
  5007. }
  5008. new SegmentPoint(point, this, '_point');
  5009. new SegmentPoint(handleIn, this, '_handleIn');
  5010. new SegmentPoint(handleOut, this, '_handleOut');
  5011. if (selection)
  5012. this.setSelection(selection);
  5013. },
  5014. _serialize: function(options, dictionary) {
  5015. var point = this._point,
  5016. selection = this._selection,
  5017. obj = selection || this.hasHandles()
  5018. ? [point, this._handleIn, this._handleOut]
  5019. : point;
  5020. if (selection)
  5021. obj.push(selection);
  5022. return Base.serialize(obj, options, true, dictionary);
  5023. },
  5024. _changed: function(point) {
  5025. var path = this._path;
  5026. if (!path)
  5027. return;
  5028. var curves = path._curves,
  5029. index = this._index,
  5030. curve;
  5031. if (curves) {
  5032. if ((!point || point === this._point || point === this._handleIn)
  5033. && (curve = index > 0 ? curves[index - 1] : path._closed
  5034. ? curves[curves.length - 1] : null))
  5035. curve._changed();
  5036. if ((!point || point === this._point || point === this._handleOut)
  5037. && (curve = curves[index]))
  5038. curve._changed();
  5039. }
  5040. path._changed(25);
  5041. },
  5042. getPoint: function() {
  5043. return this._point;
  5044. },
  5045. setPoint: function() {
  5046. this._point.set(Point.read(arguments));
  5047. },
  5048. getHandleIn: function() {
  5049. return this._handleIn;
  5050. },
  5051. setHandleIn: function() {
  5052. this._handleIn.set(Point.read(arguments));
  5053. },
  5054. getHandleOut: function() {
  5055. return this._handleOut;
  5056. },
  5057. setHandleOut: function() {
  5058. this._handleOut.set(Point.read(arguments));
  5059. },
  5060. hasHandles: function() {
  5061. return !this._handleIn.isZero() || !this._handleOut.isZero();
  5062. },
  5063. isSmooth: function() {
  5064. var handleIn = this._handleIn,
  5065. handleOut = this._handleOut;
  5066. return !handleIn.isZero() && !handleOut.isZero()
  5067. && handleIn.isCollinear(handleOut);
  5068. },
  5069. clearHandles: function() {
  5070. this._handleIn._set(0, 0);
  5071. this._handleOut._set(0, 0);
  5072. },
  5073. getSelection: function() {
  5074. return this._selection;
  5075. },
  5076. setSelection: function(selection) {
  5077. var oldSelection = this._selection,
  5078. path = this._path;
  5079. this._selection = selection = selection || 0;
  5080. if (path && selection !== oldSelection) {
  5081. path._updateSelection(this, oldSelection, selection);
  5082. path._changed(129);
  5083. }
  5084. },
  5085. _changeSelection: function(flag, selected) {
  5086. var selection = this._selection;
  5087. this.setSelection(selected ? selection | flag : selection & ~flag);
  5088. },
  5089. isSelected: function() {
  5090. return !!(this._selection & 7);
  5091. },
  5092. setSelected: function(selected) {
  5093. this._changeSelection(7, selected);
  5094. },
  5095. getIndex: function() {
  5096. return this._index !== undefined ? this._index : null;
  5097. },
  5098. getPath: function() {
  5099. return this._path || null;
  5100. },
  5101. getCurve: function() {
  5102. var path = this._path,
  5103. index = this._index;
  5104. if (path) {
  5105. if (index > 0 && !path._closed
  5106. && index === path._segments.length - 1)
  5107. index--;
  5108. return path.getCurves()[index] || null;
  5109. }
  5110. return null;
  5111. },
  5112. getLocation: function() {
  5113. var curve = this.getCurve();
  5114. return curve
  5115. ? new CurveLocation(curve, this === curve._segment1 ? 0 : 1)
  5116. : null;
  5117. },
  5118. getNext: function() {
  5119. var segments = this._path && this._path._segments;
  5120. return segments && (segments[this._index + 1]
  5121. || this._path._closed && segments[0]) || null;
  5122. },
  5123. smooth: function(options, _first, _last) {
  5124. var opts = options || {},
  5125. type = opts.type,
  5126. factor = opts.factor,
  5127. prev = this.getPrevious(),
  5128. next = this.getNext(),
  5129. p0 = (prev || this)._point,
  5130. p1 = this._point,
  5131. p2 = (next || this)._point,
  5132. d1 = p0.getDistance(p1),
  5133. d2 = p1.getDistance(p2);
  5134. if (!type || type === 'catmull-rom') {
  5135. var a = factor === undefined ? 0.5 : factor,
  5136. d1_a = Math.pow(d1, a),
  5137. d1_2a = d1_a * d1_a,
  5138. d2_a = Math.pow(d2, a),
  5139. d2_2a = d2_a * d2_a;
  5140. if (!_first && prev) {
  5141. var A = 2 * d2_2a + 3 * d2_a * d1_a + d1_2a,
  5142. N = 3 * d2_a * (d2_a + d1_a);
  5143. this.setHandleIn(N !== 0
  5144. ? new Point(
  5145. (d2_2a * p0._x + A * p1._x - d1_2a * p2._x) / N - p1._x,
  5146. (d2_2a * p0._y + A * p1._y - d1_2a * p2._y) / N - p1._y)
  5147. : new Point());
  5148. }
  5149. if (!_last && next) {
  5150. var A = 2 * d1_2a + 3 * d1_a * d2_a + d2_2a,
  5151. N = 3 * d1_a * (d1_a + d2_a);
  5152. this.setHandleOut(N !== 0
  5153. ? new Point(
  5154. (d1_2a * p2._x + A * p1._x - d2_2a * p0._x) / N - p1._x,
  5155. (d1_2a * p2._y + A * p1._y - d2_2a * p0._y) / N - p1._y)
  5156. : new Point());
  5157. }
  5158. } else if (type === 'geometric') {
  5159. if (prev && next) {
  5160. var vector = p0.subtract(p2),
  5161. t = factor === undefined ? 0.4 : factor,
  5162. k = t * d1 / (d1 + d2);
  5163. if (!_first)
  5164. this.setHandleIn(vector.multiply(k));
  5165. if (!_last)
  5166. this.setHandleOut(vector.multiply(k - t));
  5167. }
  5168. } else {
  5169. throw new Error('Smoothing method \'' + type + '\' not supported.');
  5170. }
  5171. },
  5172. getPrevious: function() {
  5173. var segments = this._path && this._path._segments;
  5174. return segments && (segments[this._index - 1]
  5175. || this._path._closed && segments[segments.length - 1]) || null;
  5176. },
  5177. isFirst: function() {
  5178. return !this._index;
  5179. },
  5180. isLast: function() {
  5181. var path = this._path;
  5182. return path && this._index === path._segments.length - 1 || false;
  5183. },
  5184. reverse: function() {
  5185. var handleIn = this._handleIn,
  5186. handleOut = this._handleOut,
  5187. tmp = handleIn.clone();
  5188. handleIn.set(handleOut);
  5189. handleOut.set(tmp);
  5190. },
  5191. reversed: function() {
  5192. return new Segment(this._point, this._handleOut, this._handleIn);
  5193. },
  5194. remove: function() {
  5195. return this._path ? !!this._path.removeSegment(this._index) : false;
  5196. },
  5197. clone: function() {
  5198. return new Segment(this._point, this._handleIn, this._handleOut);
  5199. },
  5200. equals: function(segment) {
  5201. return segment === this || segment && this._class === segment._class
  5202. && this._point.equals(segment._point)
  5203. && this._handleIn.equals(segment._handleIn)
  5204. && this._handleOut.equals(segment._handleOut)
  5205. || false;
  5206. },
  5207. toString: function() {
  5208. var parts = [ 'point: ' + this._point ];
  5209. if (!this._handleIn.isZero())
  5210. parts.push('handleIn: ' + this._handleIn);
  5211. if (!this._handleOut.isZero())
  5212. parts.push('handleOut: ' + this._handleOut);
  5213. return '{ ' + parts.join(', ') + ' }';
  5214. },
  5215. transform: function(matrix) {
  5216. this._transformCoordinates(matrix, new Array(6), true);
  5217. this._changed();
  5218. },
  5219. interpolate: function(from, to, factor) {
  5220. var u = 1 - factor,
  5221. v = factor,
  5222. point1 = from._point,
  5223. point2 = to._point,
  5224. handleIn1 = from._handleIn,
  5225. handleIn2 = to._handleIn,
  5226. handleOut2 = to._handleOut,
  5227. handleOut1 = from._handleOut;
  5228. this._point._set(
  5229. u * point1._x + v * point2._x,
  5230. u * point1._y + v * point2._y, true);
  5231. this._handleIn._set(
  5232. u * handleIn1._x + v * handleIn2._x,
  5233. u * handleIn1._y + v * handleIn2._y, true);
  5234. this._handleOut._set(
  5235. u * handleOut1._x + v * handleOut2._x,
  5236. u * handleOut1._y + v * handleOut2._y, true);
  5237. this._changed();
  5238. },
  5239. _transformCoordinates: function(matrix, coords, change) {
  5240. var point = this._point,
  5241. handleIn = !change || !this._handleIn.isZero()
  5242. ? this._handleIn : null,
  5243. handleOut = !change || !this._handleOut.isZero()
  5244. ? this._handleOut : null,
  5245. x = point._x,
  5246. y = point._y,
  5247. i = 2;
  5248. coords[0] = x;
  5249. coords[1] = y;
  5250. if (handleIn) {
  5251. coords[i++] = handleIn._x + x;
  5252. coords[i++] = handleIn._y + y;
  5253. }
  5254. if (handleOut) {
  5255. coords[i++] = handleOut._x + x;
  5256. coords[i++] = handleOut._y + y;
  5257. }
  5258. if (matrix) {
  5259. matrix._transformCoordinates(coords, coords, i / 2);
  5260. x = coords[0];
  5261. y = coords[1];
  5262. if (change) {
  5263. point._x = x;
  5264. point._y = y;
  5265. i = 2;
  5266. if (handleIn) {
  5267. handleIn._x = coords[i++] - x;
  5268. handleIn._y = coords[i++] - y;
  5269. }
  5270. if (handleOut) {
  5271. handleOut._x = coords[i++] - x;
  5272. handleOut._y = coords[i++] - y;
  5273. }
  5274. } else {
  5275. if (!handleIn) {
  5276. coords[i++] = x;
  5277. coords[i++] = y;
  5278. }
  5279. if (!handleOut) {
  5280. coords[i++] = x;
  5281. coords[i++] = y;
  5282. }
  5283. }
  5284. }
  5285. return coords;
  5286. }
  5287. });
  5288. var SegmentPoint = Point.extend({
  5289. initialize: function SegmentPoint(point, owner, key) {
  5290. var x, y,
  5291. selected;
  5292. if (!point) {
  5293. x = y = 0;
  5294. } else if ((x = point[0]) !== undefined) {
  5295. y = point[1];
  5296. } else {
  5297. var pt = point;
  5298. if ((x = pt.x) === undefined) {
  5299. pt = Point.read(arguments);
  5300. x = pt.x;
  5301. }
  5302. y = pt.y;
  5303. selected = pt.selected;
  5304. }
  5305. this._x = x;
  5306. this._y = y;
  5307. this._owner = owner;
  5308. owner[key] = this;
  5309. if (selected)
  5310. this.setSelected(true);
  5311. },
  5312. _set: function(x, y) {
  5313. this._x = x;
  5314. this._y = y;
  5315. this._owner._changed(this);
  5316. return this;
  5317. },
  5318. getX: function() {
  5319. return this._x;
  5320. },
  5321. setX: function(x) {
  5322. this._x = x;
  5323. this._owner._changed(this);
  5324. },
  5325. getY: function() {
  5326. return this._y;
  5327. },
  5328. setY: function(y) {
  5329. this._y = y;
  5330. this._owner._changed(this);
  5331. },
  5332. isZero: function() {
  5333. var isZero = Numerical.isZero;
  5334. return isZero(this._x) && isZero(this._y);
  5335. },
  5336. isSelected: function() {
  5337. return !!(this._owner._selection & this._getSelection());
  5338. },
  5339. setSelected: function(selected) {
  5340. this._owner._changeSelection(this._getSelection(), selected);
  5341. },
  5342. _getSelection: function() {
  5343. var owner = this._owner;
  5344. return this === owner._point ? 1
  5345. : this === owner._handleIn ? 2
  5346. : this === owner._handleOut ? 4
  5347. : 0;
  5348. }
  5349. });
  5350. var Curve = Base.extend({
  5351. _class: 'Curve',
  5352. beans: true,
  5353. initialize: function Curve(arg0, arg1, arg2, arg3, arg4, arg5, arg6, arg7) {
  5354. var count = arguments.length,
  5355. seg1, seg2,
  5356. point1, point2,
  5357. handle1, handle2;
  5358. if (count === 3) {
  5359. this._path = arg0;
  5360. seg1 = arg1;
  5361. seg2 = arg2;
  5362. } else if (!count) {
  5363. seg1 = new Segment();
  5364. seg2 = new Segment();
  5365. } else if (count === 1) {
  5366. if ('segment1' in arg0) {
  5367. seg1 = new Segment(arg0.segment1);
  5368. seg2 = new Segment(arg0.segment2);
  5369. } else if ('point1' in arg0) {
  5370. point1 = arg0.point1;
  5371. handle1 = arg0.handle1;
  5372. handle2 = arg0.handle2;
  5373. point2 = arg0.point2;
  5374. } else if (Array.isArray(arg0)) {
  5375. point1 = [arg0[0], arg0[1]];
  5376. point2 = [arg0[6], arg0[7]];
  5377. handle1 = [arg0[2] - arg0[0], arg0[3] - arg0[1]];
  5378. handle2 = [arg0[4] - arg0[6], arg0[5] - arg0[7]];
  5379. }
  5380. } else if (count === 2) {
  5381. seg1 = new Segment(arg0);
  5382. seg2 = new Segment(arg1);
  5383. } else if (count === 4) {
  5384. point1 = arg0;
  5385. handle1 = arg1;
  5386. handle2 = arg2;
  5387. point2 = arg3;
  5388. } else if (count === 8) {
  5389. point1 = [arg0, arg1];
  5390. point2 = [arg6, arg7];
  5391. handle1 = [arg2 - arg0, arg3 - arg1];
  5392. handle2 = [arg4 - arg6, arg5 - arg7];
  5393. }
  5394. this._segment1 = seg1 || new Segment(point1, null, handle1);
  5395. this._segment2 = seg2 || new Segment(point2, handle2, null);
  5396. },
  5397. _serialize: function(options, dictionary) {
  5398. return Base.serialize(this.hasHandles()
  5399. ? [this.getPoint1(), this.getHandle1(), this.getHandle2(),
  5400. this.getPoint2()]
  5401. : [this.getPoint1(), this.getPoint2()],
  5402. options, true, dictionary);
  5403. },
  5404. _changed: function() {
  5405. this._length = this._bounds = undefined;
  5406. },
  5407. clone: function() {
  5408. return new Curve(this._segment1, this._segment2);
  5409. },
  5410. toString: function() {
  5411. var parts = [ 'point1: ' + this._segment1._point ];
  5412. if (!this._segment1._handleOut.isZero())
  5413. parts.push('handle1: ' + this._segment1._handleOut);
  5414. if (!this._segment2._handleIn.isZero())
  5415. parts.push('handle2: ' + this._segment2._handleIn);
  5416. parts.push('point2: ' + this._segment2._point);
  5417. return '{ ' + parts.join(', ') + ' }';
  5418. },
  5419. classify: function() {
  5420. return Curve.classify(this.getValues());
  5421. },
  5422. remove: function() {
  5423. var removed = false;
  5424. if (this._path) {
  5425. var segment2 = this._segment2,
  5426. handleOut = segment2._handleOut;
  5427. removed = segment2.remove();
  5428. if (removed)
  5429. this._segment1._handleOut.set(handleOut);
  5430. }
  5431. return removed;
  5432. },
  5433. getPoint1: function() {
  5434. return this._segment1._point;
  5435. },
  5436. setPoint1: function() {
  5437. this._segment1._point.set(Point.read(arguments));
  5438. },
  5439. getPoint2: function() {
  5440. return this._segment2._point;
  5441. },
  5442. setPoint2: function() {
  5443. this._segment2._point.set(Point.read(arguments));
  5444. },
  5445. getHandle1: function() {
  5446. return this._segment1._handleOut;
  5447. },
  5448. setHandle1: function() {
  5449. this._segment1._handleOut.set(Point.read(arguments));
  5450. },
  5451. getHandle2: function() {
  5452. return this._segment2._handleIn;
  5453. },
  5454. setHandle2: function() {
  5455. this._segment2._handleIn.set(Point.read(arguments));
  5456. },
  5457. getSegment1: function() {
  5458. return this._segment1;
  5459. },
  5460. getSegment2: function() {
  5461. return this._segment2;
  5462. },
  5463. getPath: function() {
  5464. return this._path;
  5465. },
  5466. getIndex: function() {
  5467. return this._segment1._index;
  5468. },
  5469. getNext: function() {
  5470. var curves = this._path && this._path._curves;
  5471. return curves && (curves[this._segment1._index + 1]
  5472. || this._path._closed && curves[0]) || null;
  5473. },
  5474. getPrevious: function() {
  5475. var curves = this._path && this._path._curves;
  5476. return curves && (curves[this._segment1._index - 1]
  5477. || this._path._closed && curves[curves.length - 1]) || null;
  5478. },
  5479. isFirst: function() {
  5480. return !this._segment1._index;
  5481. },
  5482. isLast: function() {
  5483. var path = this._path;
  5484. return path && this._segment1._index === path._curves.length - 1
  5485. || false;
  5486. },
  5487. isSelected: function() {
  5488. return this.getPoint1().isSelected()
  5489. && this.getHandle1().isSelected()
  5490. && this.getHandle2().isSelected()
  5491. && this.getPoint2().isSelected();
  5492. },
  5493. setSelected: function(selected) {
  5494. this.getPoint1().setSelected(selected);
  5495. this.getHandle1().setSelected(selected);
  5496. this.getHandle2().setSelected(selected);
  5497. this.getPoint2().setSelected(selected);
  5498. },
  5499. getValues: function(matrix) {
  5500. return Curve.getValues(this._segment1, this._segment2, matrix);
  5501. },
  5502. getPoints: function() {
  5503. var coords = this.getValues(),
  5504. points = [];
  5505. for (var i = 0; i < 8; i += 2)
  5506. points.push(new Point(coords[i], coords[i + 1]));
  5507. return points;
  5508. }
  5509. }, {
  5510. getLength: function() {
  5511. if (this._length == null)
  5512. this._length = Curve.getLength(this.getValues(), 0, 1);
  5513. return this._length;
  5514. },
  5515. getArea: function() {
  5516. return Curve.getArea(this.getValues());
  5517. },
  5518. getLine: function() {
  5519. return new Line(this._segment1._point, this._segment2._point);
  5520. },
  5521. getPart: function(from, to) {
  5522. return new Curve(Curve.getPart(this.getValues(), from, to));
  5523. },
  5524. getPartLength: function(from, to) {
  5525. return Curve.getLength(this.getValues(), from, to);
  5526. },
  5527. divideAt: function(location) {
  5528. return this.divideAtTime(location && location.curve === this
  5529. ? location.time : this.getTimeAt(location));
  5530. },
  5531. divideAtTime: function(time, _setHandles) {
  5532. var tMin = 1e-8,
  5533. tMax = 1 - tMin,
  5534. res = null;
  5535. if (time >= tMin && time <= tMax) {
  5536. var parts = Curve.subdivide(this.getValues(), time),
  5537. left = parts[0],
  5538. right = parts[1],
  5539. setHandles = _setHandles || this.hasHandles(),
  5540. seg1 = this._segment1,
  5541. seg2 = this._segment2,
  5542. path = this._path;
  5543. if (setHandles) {
  5544. seg1._handleOut._set(left[2] - left[0], left[3] - left[1]);
  5545. seg2._handleIn._set(right[4] - right[6],right[5] - right[7]);
  5546. }
  5547. var x = left[6], y = left[7],
  5548. segment = new Segment(new Point(x, y),
  5549. setHandles && new Point(left[4] - x, left[5] - y),
  5550. setHandles && new Point(right[2] - x, right[3] - y));
  5551. if (path) {
  5552. path.insert(seg1._index + 1, segment);
  5553. res = this.getNext();
  5554. } else {
  5555. this._segment2 = segment;
  5556. this._changed();
  5557. res = new Curve(segment, seg2);
  5558. }
  5559. }
  5560. return res;
  5561. },
  5562. splitAt: function(location) {
  5563. var path = this._path;
  5564. return path ? path.splitAt(location) : null;
  5565. },
  5566. splitAtTime: function(time) {
  5567. return this.splitAt(this.getLocationAtTime(time));
  5568. },
  5569. divide: function(offset, isTime) {
  5570. return this.divideAtTime(offset === undefined ? 0.5 : isTime ? offset
  5571. : this.getTimeAt(offset));
  5572. },
  5573. split: function(offset, isTime) {
  5574. return this.splitAtTime(offset === undefined ? 0.5 : isTime ? offset
  5575. : this.getTimeAt(offset));
  5576. },
  5577. reversed: function() {
  5578. return new Curve(this._segment2.reversed(), this._segment1.reversed());
  5579. },
  5580. clearHandles: function() {
  5581. this._segment1._handleOut._set(0, 0);
  5582. this._segment2._handleIn._set(0, 0);
  5583. },
  5584. statics: {
  5585. getValues: function(segment1, segment2, matrix, straight) {
  5586. var p1 = segment1._point,
  5587. h1 = segment1._handleOut,
  5588. h2 = segment2._handleIn,
  5589. p2 = segment2._point,
  5590. x1 = p1.x, y1 = p1.y,
  5591. x2 = p2.x, y2 = p2.y,
  5592. values = straight
  5593. ? [ x1, y1, x1, y1, x2, y2, x2, y2 ]
  5594. : [
  5595. x1, y1,
  5596. x1 + h1._x, y1 + h1._y,
  5597. x2 + h2._x, y2 + h2._y,
  5598. x2, y2
  5599. ];
  5600. if (matrix)
  5601. matrix._transformCoordinates(values, values, 4);
  5602. return values;
  5603. },
  5604. subdivide: function(v, t) {
  5605. var x0 = v[0], y0 = v[1],
  5606. x1 = v[2], y1 = v[3],
  5607. x2 = v[4], y2 = v[5],
  5608. x3 = v[6], y3 = v[7];
  5609. if (t === undefined)
  5610. t = 0.5;
  5611. var u = 1 - t,
  5612. x4 = u * x0 + t * x1, y4 = u * y0 + t * y1,
  5613. x5 = u * x1 + t * x2, y5 = u * y1 + t * y2,
  5614. x6 = u * x2 + t * x3, y6 = u * y2 + t * y3,
  5615. x7 = u * x4 + t * x5, y7 = u * y4 + t * y5,
  5616. x8 = u * x5 + t * x6, y8 = u * y5 + t * y6,
  5617. x9 = u * x7 + t * x8, y9 = u * y7 + t * y8;
  5618. return [
  5619. [x0, y0, x4, y4, x7, y7, x9, y9],
  5620. [x9, y9, x8, y8, x6, y6, x3, y3]
  5621. ];
  5622. },
  5623. getMonoCurves: function(v, dir) {
  5624. var curves = [],
  5625. io = dir ? 0 : 1,
  5626. o0 = v[io + 0],
  5627. o1 = v[io + 2],
  5628. o2 = v[io + 4],
  5629. o3 = v[io + 6];
  5630. if ((o0 >= o1) === (o1 >= o2) && (o1 >= o2) === (o2 >= o3)
  5631. || Curve.isStraight(v)) {
  5632. curves.push(v);
  5633. } else {
  5634. var a = 3 * (o1 - o2) - o0 + o3,
  5635. b = 2 * (o0 + o2) - 4 * o1,
  5636. c = o1 - o0,
  5637. tMin = 1e-8,
  5638. tMax = 1 - tMin,
  5639. roots = [],
  5640. n = Numerical.solveQuadratic(a, b, c, roots, tMin, tMax);
  5641. if (!n) {
  5642. curves.push(v);
  5643. } else {
  5644. roots.sort();
  5645. var t = roots[0],
  5646. parts = Curve.subdivide(v, t);
  5647. curves.push(parts[0]);
  5648. if (n > 1) {
  5649. t = (roots[1] - t) / (1 - t);
  5650. parts = Curve.subdivide(parts[1], t);
  5651. curves.push(parts[0]);
  5652. }
  5653. curves.push(parts[1]);
  5654. }
  5655. }
  5656. return curves;
  5657. },
  5658. solveCubic: function (v, coord, val, roots, min, max) {
  5659. var v0 = v[coord],
  5660. v1 = v[coord + 2],
  5661. v2 = v[coord + 4],
  5662. v3 = v[coord + 6],
  5663. res = 0;
  5664. if ( !(v0 < val && v3 < val && v1 < val && v2 < val ||
  5665. v0 > val && v3 > val && v1 > val && v2 > val)) {
  5666. var c = 3 * (v1 - v0),
  5667. b = 3 * (v2 - v1) - c,
  5668. a = v3 - v0 - c - b;
  5669. res = Numerical.solveCubic(a, b, c, v0 - val, roots, min, max);
  5670. }
  5671. return res;
  5672. },
  5673. getTimeOf: function(v, point) {
  5674. var p0 = new Point(v[0], v[1]),
  5675. p3 = new Point(v[6], v[7]),
  5676. epsilon = 1e-12,
  5677. geomEpsilon = 1e-7,
  5678. t = point.isClose(p0, epsilon) ? 0
  5679. : point.isClose(p3, epsilon) ? 1
  5680. : null;
  5681. if (t === null) {
  5682. var coords = [point.x, point.y],
  5683. roots = [];
  5684. for (var c = 0; c < 2; c++) {
  5685. var count = Curve.solveCubic(v, c, coords[c], roots, 0, 1);
  5686. for (var i = 0; i < count; i++) {
  5687. var u = roots[i];
  5688. if (point.isClose(Curve.getPoint(v, u), geomEpsilon))
  5689. return u;
  5690. }
  5691. }
  5692. }
  5693. return point.isClose(p0, geomEpsilon) ? 0
  5694. : point.isClose(p3, geomEpsilon) ? 1
  5695. : null;
  5696. },
  5697. getNearestTime: function(v, point) {
  5698. if (Curve.isStraight(v)) {
  5699. var x0 = v[0], y0 = v[1],
  5700. x3 = v[6], y3 = v[7],
  5701. vx = x3 - x0, vy = y3 - y0,
  5702. det = vx * vx + vy * vy;
  5703. if (det === 0)
  5704. return 0;
  5705. var u = ((point.x - x0) * vx + (point.y - y0) * vy) / det;
  5706. return u < 1e-12 ? 0
  5707. : u > 0.999999999999 ? 1
  5708. : Curve.getTimeOf(v,
  5709. new Point(x0 + u * vx, y0 + u * vy));
  5710. }
  5711. var count = 100,
  5712. minDist = Infinity,
  5713. minT = 0;
  5714. function refine(t) {
  5715. if (t >= 0 && t <= 1) {
  5716. var dist = point.getDistance(Curve.getPoint(v, t), true);
  5717. if (dist < minDist) {
  5718. minDist = dist;
  5719. minT = t;
  5720. return true;
  5721. }
  5722. }
  5723. }
  5724. for (var i = 0; i <= count; i++)
  5725. refine(i / count);
  5726. var step = 1 / (count * 2);
  5727. while (step > 1e-8) {
  5728. if (!refine(minT - step) && !refine(minT + step))
  5729. step /= 2;
  5730. }
  5731. return minT;
  5732. },
  5733. getPart: function(v, from, to) {
  5734. var flip = from > to;
  5735. if (flip) {
  5736. var tmp = from;
  5737. from = to;
  5738. to = tmp;
  5739. }
  5740. if (from > 0)
  5741. v = Curve.subdivide(v, from)[1];
  5742. if (to < 1)
  5743. v = Curve.subdivide(v, (to - from) / (1 - from))[0];
  5744. return flip
  5745. ? [v[6], v[7], v[4], v[5], v[2], v[3], v[0], v[1]]
  5746. : v;
  5747. },
  5748. isFlatEnough: function(v, flatness) {
  5749. var x0 = v[0], y0 = v[1],
  5750. x1 = v[2], y1 = v[3],
  5751. x2 = v[4], y2 = v[5],
  5752. x3 = v[6], y3 = v[7],
  5753. ux = 3 * x1 - 2 * x0 - x3,
  5754. uy = 3 * y1 - 2 * y0 - y3,
  5755. vx = 3 * x2 - 2 * x3 - x0,
  5756. vy = 3 * y2 - 2 * y3 - y0;
  5757. return Math.max(ux * ux, vx * vx) + Math.max(uy * uy, vy * vy)
  5758. <= 16 * flatness * flatness;
  5759. },
  5760. getArea: function(v) {
  5761. var x0 = v[0], y0 = v[1],
  5762. x1 = v[2], y1 = v[3],
  5763. x2 = v[4], y2 = v[5],
  5764. x3 = v[6], y3 = v[7];
  5765. return 3 * ((y3 - y0) * (x1 + x2) - (x3 - x0) * (y1 + y2)
  5766. + y1 * (x0 - x2) - x1 * (y0 - y2)
  5767. + y3 * (x2 + x0 / 3) - x3 * (y2 + y0 / 3)) / 20;
  5768. },
  5769. getBounds: function(v) {
  5770. var min = v.slice(0, 2),
  5771. max = min.slice(),
  5772. roots = [0, 0];
  5773. for (var i = 0; i < 2; i++)
  5774. Curve._addBounds(v[i], v[i + 2], v[i + 4], v[i + 6],
  5775. i, 0, min, max, roots);
  5776. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  5777. },
  5778. _addBounds: function(v0, v1, v2, v3, coord, padding, min, max, roots) {
  5779. function add(value, padding) {
  5780. var left = value - padding,
  5781. right = value + padding;
  5782. if (left < min[coord])
  5783. min[coord] = left;
  5784. if (right > max[coord])
  5785. max[coord] = right;
  5786. }
  5787. padding /= 2;
  5788. var minPad = min[coord] - padding,
  5789. maxPad = max[coord] + padding;
  5790. if ( v0 < minPad || v1 < minPad || v2 < minPad || v3 < minPad ||
  5791. v0 > maxPad || v1 > maxPad || v2 > maxPad || v3 > maxPad) {
  5792. if (v1 < v0 != v1 < v3 && v2 < v0 != v2 < v3) {
  5793. add(v0, padding);
  5794. add(v3, padding);
  5795. } else {
  5796. var a = 3 * (v1 - v2) - v0 + v3,
  5797. b = 2 * (v0 + v2) - 4 * v1,
  5798. c = v1 - v0,
  5799. count = Numerical.solveQuadratic(a, b, c, roots),
  5800. tMin = 1e-8,
  5801. tMax = 1 - tMin;
  5802. add(v3, 0);
  5803. for (var i = 0; i < count; i++) {
  5804. var t = roots[i],
  5805. u = 1 - t;
  5806. if (tMin <= t && t <= tMax)
  5807. add(u * u * u * v0
  5808. + 3 * u * u * t * v1
  5809. + 3 * u * t * t * v2
  5810. + t * t * t * v3,
  5811. padding);
  5812. }
  5813. }
  5814. }
  5815. }
  5816. }}, Base.each(
  5817. ['getBounds', 'getStrokeBounds', 'getHandleBounds'],
  5818. function(name) {
  5819. this[name] = function() {
  5820. if (!this._bounds)
  5821. this._bounds = {};
  5822. var bounds = this._bounds[name];
  5823. if (!bounds) {
  5824. bounds = this._bounds[name] = Path[name](
  5825. [this._segment1, this._segment2], false, this._path);
  5826. }
  5827. return bounds.clone();
  5828. };
  5829. },
  5830. {
  5831. }), Base.each({
  5832. isStraight: function(p1, h1, h2, p2) {
  5833. if (h1.isZero() && h2.isZero()) {
  5834. return true;
  5835. } else {
  5836. var v = p2.subtract(p1);
  5837. if (v.isZero()) {
  5838. return false;
  5839. } else if (v.isCollinear(h1) && v.isCollinear(h2)) {
  5840. var l = new Line(p1, p2),
  5841. epsilon = 1e-7;
  5842. if (l.getDistance(p1.add(h1)) < epsilon &&
  5843. l.getDistance(p2.add(h2)) < epsilon) {
  5844. var div = v.dot(v),
  5845. s1 = v.dot(h1) / div,
  5846. s2 = v.dot(h2) / div;
  5847. return s1 >= 0 && s1 <= 1 && s2 <= 0 && s2 >= -1;
  5848. }
  5849. }
  5850. }
  5851. return false;
  5852. },
  5853. isLinear: function(p1, h1, h2, p2) {
  5854. var third = p2.subtract(p1).divide(3);
  5855. return h1.equals(third) && h2.negate().equals(third);
  5856. }
  5857. }, function(test, name) {
  5858. this[name] = function(epsilon) {
  5859. var seg1 = this._segment1,
  5860. seg2 = this._segment2;
  5861. return test(seg1._point, seg1._handleOut, seg2._handleIn, seg2._point,
  5862. epsilon);
  5863. };
  5864. this.statics[name] = function(v, epsilon) {
  5865. var x0 = v[0], y0 = v[1],
  5866. x3 = v[6], y3 = v[7];
  5867. return test(
  5868. new Point(x0, y0),
  5869. new Point(v[2] - x0, v[3] - y0),
  5870. new Point(v[4] - x3, v[5] - y3),
  5871. new Point(x3, y3), epsilon);
  5872. };
  5873. }, {
  5874. statics: {},
  5875. hasHandles: function() {
  5876. return !this._segment1._handleOut.isZero()
  5877. || !this._segment2._handleIn.isZero();
  5878. },
  5879. hasLength: function(epsilon) {
  5880. return (!this.getPoint1().equals(this.getPoint2()) || this.hasHandles())
  5881. && this.getLength() > (epsilon || 0);
  5882. },
  5883. isCollinear: function(curve) {
  5884. return curve && this.isStraight() && curve.isStraight()
  5885. && this.getLine().isCollinear(curve.getLine());
  5886. },
  5887. isHorizontal: function() {
  5888. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).y)
  5889. < 1e-8;
  5890. },
  5891. isVertical: function() {
  5892. return this.isStraight() && Math.abs(this.getTangentAtTime(0.5).x)
  5893. < 1e-8;
  5894. }
  5895. }), {
  5896. beans: false,
  5897. getLocationAt: function(offset, _isTime) {
  5898. return this.getLocationAtTime(
  5899. _isTime ? offset : this.getTimeAt(offset));
  5900. },
  5901. getLocationAtTime: function(t) {
  5902. return t != null && t >= 0 && t <= 1
  5903. ? new CurveLocation(this, t)
  5904. : null;
  5905. },
  5906. getTimeAt: function(offset, start) {
  5907. return Curve.getTimeAt(this.getValues(), offset, start);
  5908. },
  5909. getParameterAt: '#getTimeAt',
  5910. getOffsetAtTime: function(t) {
  5911. return this.getPartLength(0, t);
  5912. },
  5913. getLocationOf: function() {
  5914. return this.getLocationAtTime(this.getTimeOf(Point.read(arguments)));
  5915. },
  5916. getOffsetOf: function() {
  5917. var loc = this.getLocationOf.apply(this, arguments);
  5918. return loc ? loc.getOffset() : null;
  5919. },
  5920. getTimeOf: function() {
  5921. return Curve.getTimeOf(this.getValues(), Point.read(arguments));
  5922. },
  5923. getParameterOf: '#getTimeOf',
  5924. getNearestLocation: function() {
  5925. var point = Point.read(arguments),
  5926. values = this.getValues(),
  5927. t = Curve.getNearestTime(values, point),
  5928. pt = Curve.getPoint(values, t);
  5929. return new CurveLocation(this, t, pt, null, point.getDistance(pt));
  5930. },
  5931. getNearestPoint: function() {
  5932. var loc = this.getNearestLocation.apply(this, arguments);
  5933. return loc ? loc.getPoint() : loc;
  5934. }
  5935. },
  5936. new function() {
  5937. var methods = ['getPoint', 'getTangent', 'getNormal', 'getWeightedTangent',
  5938. 'getWeightedNormal', 'getCurvature'];
  5939. return Base.each(methods,
  5940. function(name) {
  5941. this[name + 'At'] = function(location, _isTime) {
  5942. var values = this.getValues();
  5943. return Curve[name](values, _isTime ? location
  5944. : Curve.getTimeAt(values, location));
  5945. };
  5946. this[name + 'AtTime'] = function(time) {
  5947. return Curve[name](this.getValues(), time);
  5948. };
  5949. }, {
  5950. statics: {
  5951. _evaluateMethods: methods
  5952. }
  5953. }
  5954. );
  5955. },
  5956. new function() {
  5957. function getLengthIntegrand(v) {
  5958. var x0 = v[0], y0 = v[1],
  5959. x1 = v[2], y1 = v[3],
  5960. x2 = v[4], y2 = v[5],
  5961. x3 = v[6], y3 = v[7],
  5962. ax = 9 * (x1 - x2) + 3 * (x3 - x0),
  5963. bx = 6 * (x0 + x2) - 12 * x1,
  5964. cx = 3 * (x1 - x0),
  5965. ay = 9 * (y1 - y2) + 3 * (y3 - y0),
  5966. by = 6 * (y0 + y2) - 12 * y1,
  5967. cy = 3 * (y1 - y0);
  5968. return function(t) {
  5969. var dx = (ax * t + bx) * t + cx,
  5970. dy = (ay * t + by) * t + cy;
  5971. return Math.sqrt(dx * dx + dy * dy);
  5972. };
  5973. }
  5974. function getIterations(a, b) {
  5975. return Math.max(2, Math.min(16, Math.ceil(Math.abs(b - a) * 32)));
  5976. }
  5977. function evaluate(v, t, type, normalized) {
  5978. if (t == null || t < 0 || t > 1)
  5979. return null;
  5980. var x0 = v[0], y0 = v[1],
  5981. x1 = v[2], y1 = v[3],
  5982. x2 = v[4], y2 = v[5],
  5983. x3 = v[6], y3 = v[7],
  5984. isZero = Numerical.isZero;
  5985. if (isZero(x1 - x0) && isZero(y1 - y0)) {
  5986. x1 = x0;
  5987. y1 = y0;
  5988. }
  5989. if (isZero(x2 - x3) && isZero(y2 - y3)) {
  5990. x2 = x3;
  5991. y2 = y3;
  5992. }
  5993. var cx = 3 * (x1 - x0),
  5994. bx = 3 * (x2 - x1) - cx,
  5995. ax = x3 - x0 - cx - bx,
  5996. cy = 3 * (y1 - y0),
  5997. by = 3 * (y2 - y1) - cy,
  5998. ay = y3 - y0 - cy - by,
  5999. x, y;
  6000. if (type === 0) {
  6001. x = t === 0 ? x0 : t === 1 ? x3
  6002. : ((ax * t + bx) * t + cx) * t + x0;
  6003. y = t === 0 ? y0 : t === 1 ? y3
  6004. : ((ay * t + by) * t + cy) * t + y0;
  6005. } else {
  6006. var tMin = 1e-8,
  6007. tMax = 1 - tMin;
  6008. if (t < tMin) {
  6009. x = cx;
  6010. y = cy;
  6011. } else if (t > tMax) {
  6012. x = 3 * (x3 - x2);
  6013. y = 3 * (y3 - y2);
  6014. } else {
  6015. x = (3 * ax * t + 2 * bx) * t + cx;
  6016. y = (3 * ay * t + 2 * by) * t + cy;
  6017. }
  6018. if (normalized) {
  6019. if (x === 0 && y === 0 && (t < tMin || t > tMax)) {
  6020. x = x2 - x1;
  6021. y = y2 - y1;
  6022. }
  6023. var len = Math.sqrt(x * x + y * y);
  6024. if (len) {
  6025. x /= len;
  6026. y /= len;
  6027. }
  6028. }
  6029. if (type === 3) {
  6030. var x2 = 6 * ax * t + 2 * bx,
  6031. y2 = 6 * ay * t + 2 * by,
  6032. d = Math.pow(x * x + y * y, 3 / 2);
  6033. x = d !== 0 ? (x * y2 - y * x2) / d : 0;
  6034. y = 0;
  6035. }
  6036. }
  6037. return type === 2 ? new Point(y, -x) : new Point(x, y);
  6038. }
  6039. return { statics: {
  6040. classify: function(v) {
  6041. var x0 = v[0], y0 = v[1],
  6042. x1 = v[2], y1 = v[3],
  6043. x2 = v[4], y2 = v[5],
  6044. x3 = v[6], y3 = v[7],
  6045. a1 = x0 * (y3 - y2) + y0 * (x2 - x3) + x3 * y2 - y3 * x2,
  6046. a2 = x1 * (y0 - y3) + y1 * (x3 - x0) + x0 * y3 - y0 * x3,
  6047. a3 = x2 * (y1 - y0) + y2 * (x0 - x1) + x1 * y0 - y1 * x0,
  6048. d3 = 3 * a3,
  6049. d2 = d3 - a2,
  6050. d1 = d2 - a2 + a1,
  6051. l = Math.sqrt(d1 * d1 + d2 * d2 + d3 * d3),
  6052. s = l !== 0 ? 1 / l : 0,
  6053. isZero = Numerical.isZero,
  6054. serpentine = 'serpentine';
  6055. d1 *= s;
  6056. d2 *= s;
  6057. d3 *= s;
  6058. function type(type, t1, t2) {
  6059. var hasRoots = t1 !== undefined,
  6060. t1Ok = hasRoots && t1 > 0 && t1 < 1,
  6061. t2Ok = hasRoots && t2 > 0 && t2 < 1;
  6062. if (hasRoots && (!(t1Ok || t2Ok)
  6063. || type === 'loop' && !(t1Ok && t2Ok))) {
  6064. type = 'arch';
  6065. t1Ok = t2Ok = false;
  6066. }
  6067. return {
  6068. type: type,
  6069. roots: t1Ok || t2Ok
  6070. ? t1Ok && t2Ok
  6071. ? t1 < t2 ? [t1, t2] : [t2, t1]
  6072. : [t1Ok ? t1 : t2]
  6073. : null
  6074. };
  6075. }
  6076. if (isZero(d1)) {
  6077. return isZero(d2)
  6078. ? type(isZero(d3) ? 'line' : 'quadratic')
  6079. : type(serpentine, d3 / (3 * d2));
  6080. }
  6081. var d = 3 * d2 * d2 - 4 * d1 * d3;
  6082. if (isZero(d)) {
  6083. return type('cusp', d2 / (2 * d1));
  6084. }
  6085. var f1 = d > 0 ? Math.sqrt(d / 3) : Math.sqrt(-d),
  6086. f2 = 2 * d1;
  6087. return type(d > 0 ? serpentine : 'loop',
  6088. (d2 + f1) / f2,
  6089. (d2 - f1) / f2);
  6090. },
  6091. getLength: function(v, a, b, ds) {
  6092. if (a === undefined)
  6093. a = 0;
  6094. if (b === undefined)
  6095. b = 1;
  6096. if (Curve.isStraight(v)) {
  6097. var c = v;
  6098. if (b < 1) {
  6099. c = Curve.subdivide(c, b)[0];
  6100. a /= b;
  6101. }
  6102. if (a > 0) {
  6103. c = Curve.subdivide(c, a)[1];
  6104. }
  6105. var dx = c[6] - c[0],
  6106. dy = c[7] - c[1];
  6107. return Math.sqrt(dx * dx + dy * dy);
  6108. }
  6109. return Numerical.integrate(ds || getLengthIntegrand(v), a, b,
  6110. getIterations(a, b));
  6111. },
  6112. getTimeAt: function(v, offset, start) {
  6113. if (start === undefined)
  6114. start = offset < 0 ? 1 : 0;
  6115. if (offset === 0)
  6116. return start;
  6117. var abs = Math.abs,
  6118. epsilon = 1e-12,
  6119. forward = offset > 0,
  6120. a = forward ? start : 0,
  6121. b = forward ? 1 : start,
  6122. ds = getLengthIntegrand(v),
  6123. rangeLength = Curve.getLength(v, a, b, ds),
  6124. diff = abs(offset) - rangeLength;
  6125. if (abs(diff) < epsilon) {
  6126. return forward ? b : a;
  6127. } else if (diff > epsilon) {
  6128. return null;
  6129. }
  6130. var guess = offset / rangeLength,
  6131. length = 0;
  6132. function f(t) {
  6133. length += Numerical.integrate(ds, start, t,
  6134. getIterations(start, t));
  6135. start = t;
  6136. return length - offset;
  6137. }
  6138. return Numerical.findRoot(f, ds, start + guess, a, b, 32,
  6139. 1e-12);
  6140. },
  6141. getPoint: function(v, t) {
  6142. return evaluate(v, t, 0, false);
  6143. },
  6144. getTangent: function(v, t) {
  6145. return evaluate(v, t, 1, true);
  6146. },
  6147. getWeightedTangent: function(v, t) {
  6148. return evaluate(v, t, 1, false);
  6149. },
  6150. getNormal: function(v, t) {
  6151. return evaluate(v, t, 2, true);
  6152. },
  6153. getWeightedNormal: function(v, t) {
  6154. return evaluate(v, t, 2, false);
  6155. },
  6156. getCurvature: function(v, t) {
  6157. return evaluate(v, t, 3, false).x;
  6158. },
  6159. getPeaks: function(v) {
  6160. var x0 = v[0], y0 = v[1],
  6161. x1 = v[2], y1 = v[3],
  6162. x2 = v[4], y2 = v[5],
  6163. x3 = v[6], y3 = v[7],
  6164. ax = -x0 + 3 * x1 - 3 * x2 + x3,
  6165. bx = 3 * x0 - 6 * x1 + 3 * x2,
  6166. cx = -3 * x0 + 3 * x1,
  6167. ay = -y0 + 3 * y1 - 3 * y2 + y3,
  6168. by = 3 * y0 - 6 * y1 + 3 * y2,
  6169. cy = -3 * y0 + 3 * y1,
  6170. tMin = 1e-8,
  6171. tMax = 1 - tMin,
  6172. roots = [];
  6173. Numerical.solveCubic(
  6174. 9 * (ax * ax + ay * ay),
  6175. 9 * (ax * bx + by * ay),
  6176. 2 * (bx * bx + by * by) + 3 * (cx * ax + cy * ay),
  6177. (cx * bx + by * cy),
  6178. roots, tMin, tMax);
  6179. return roots.sort();
  6180. }
  6181. }};
  6182. },
  6183. new function() {
  6184. function addLocation(locations, include, c1, t1, c2, t2, overlap) {
  6185. var excludeStart = !overlap && c1.getPrevious() === c2,
  6186. excludeEnd = !overlap && c1 !== c2 && c1.getNext() === c2,
  6187. tMin = 1e-8,
  6188. tMax = 1 - tMin;
  6189. if (t1 !== null && t1 >= (excludeStart ? tMin : 0) &&
  6190. t1 <= (excludeEnd ? tMax : 1)) {
  6191. if (t2 !== null && t2 >= (excludeEnd ? tMin : 0) &&
  6192. t2 <= (excludeStart ? tMax : 1)) {
  6193. var loc1 = new CurveLocation(c1, t1, null, overlap),
  6194. loc2 = new CurveLocation(c2, t2, null, overlap);
  6195. loc1._intersection = loc2;
  6196. loc2._intersection = loc1;
  6197. if (!include || include(loc1)) {
  6198. CurveLocation.insert(locations, loc1, true);
  6199. }
  6200. }
  6201. }
  6202. }
  6203. function addCurveIntersections(v1, v2, c1, c2, locations, include, flip,
  6204. recursion, calls, tMin, tMax, uMin, uMax) {
  6205. if (++calls >= 4096 || ++recursion >= 40)
  6206. return calls;
  6207. var fatLineEpsilon = 1e-9,
  6208. q0x = v2[0], q0y = v2[1], q3x = v2[6], q3y = v2[7],
  6209. getSignedDistance = Line.getSignedDistance,
  6210. d1 = getSignedDistance(q0x, q0y, q3x, q3y, v2[2], v2[3]),
  6211. d2 = getSignedDistance(q0x, q0y, q3x, q3y, v2[4], v2[5]),
  6212. factor = d1 * d2 > 0 ? 3 / 4 : 4 / 9,
  6213. dMin = factor * Math.min(0, d1, d2),
  6214. dMax = factor * Math.max(0, d1, d2),
  6215. dp0 = getSignedDistance(q0x, q0y, q3x, q3y, v1[0], v1[1]),
  6216. dp1 = getSignedDistance(q0x, q0y, q3x, q3y, v1[2], v1[3]),
  6217. dp2 = getSignedDistance(q0x, q0y, q3x, q3y, v1[4], v1[5]),
  6218. dp3 = getSignedDistance(q0x, q0y, q3x, q3y, v1[6], v1[7]),
  6219. hull = getConvexHull(dp0, dp1, dp2, dp3),
  6220. top = hull[0],
  6221. bottom = hull[1],
  6222. tMinClip,
  6223. tMaxClip;
  6224. if (d1 === 0 && d2 === 0
  6225. && dp0 === 0 && dp1 === 0 && dp2 === 0 && dp3 === 0
  6226. || (tMinClip = clipConvexHull(top, bottom, dMin, dMax)) == null
  6227. || (tMaxClip = clipConvexHull(top.reverse(), bottom.reverse(),
  6228. dMin, dMax)) == null)
  6229. return calls;
  6230. var tMinNew = tMin + (tMax - tMin) * tMinClip,
  6231. tMaxNew = tMin + (tMax - tMin) * tMaxClip;
  6232. if (Math.max(uMax - uMin, tMaxNew - tMinNew) < fatLineEpsilon) {
  6233. var t = (tMinNew + tMaxNew) / 2,
  6234. u = (uMin + uMax) / 2;
  6235. addLocation(locations, include,
  6236. flip ? c2 : c1, flip ? u : t,
  6237. flip ? c1 : c2, flip ? t : u);
  6238. } else {
  6239. v1 = Curve.getPart(v1, tMinClip, tMaxClip);
  6240. if (tMaxClip - tMinClip > 0.8) {
  6241. if (tMaxNew - tMinNew > uMax - uMin) {
  6242. var parts = Curve.subdivide(v1, 0.5),
  6243. t = (tMinNew + tMaxNew) / 2;
  6244. calls = addCurveIntersections(
  6245. v2, parts[0], c2, c1, locations, include, !flip,
  6246. recursion, calls, uMin, uMax, tMinNew, t);
  6247. calls = addCurveIntersections(
  6248. v2, parts[1], c2, c1, locations, include, !flip,
  6249. recursion, calls, uMin, uMax, t, tMaxNew);
  6250. } else {
  6251. var parts = Curve.subdivide(v2, 0.5),
  6252. u = (uMin + uMax) / 2;
  6253. calls = addCurveIntersections(
  6254. parts[0], v1, c2, c1, locations, include, !flip,
  6255. recursion, calls, uMin, u, tMinNew, tMaxNew);
  6256. calls = addCurveIntersections(
  6257. parts[1], v1, c2, c1, locations, include, !flip,
  6258. recursion, calls, u, uMax, tMinNew, tMaxNew);
  6259. }
  6260. } else {
  6261. if (uMax - uMin >= fatLineEpsilon) {
  6262. calls = addCurveIntersections(
  6263. v2, v1, c2, c1, locations, include, !flip,
  6264. recursion, calls, uMin, uMax, tMinNew, tMaxNew);
  6265. } else {
  6266. calls = addCurveIntersections(
  6267. v1, v2, c1, c2, locations, include, flip,
  6268. recursion, calls, tMinNew, tMaxNew, uMin, uMax);
  6269. }
  6270. }
  6271. }
  6272. return calls;
  6273. }
  6274. function getConvexHull(dq0, dq1, dq2, dq3) {
  6275. var p0 = [ 0, dq0 ],
  6276. p1 = [ 1 / 3, dq1 ],
  6277. p2 = [ 2 / 3, dq2 ],
  6278. p3 = [ 1, dq3 ],
  6279. dist1 = dq1 - (2 * dq0 + dq3) / 3,
  6280. dist2 = dq2 - (dq0 + 2 * dq3) / 3,
  6281. hull;
  6282. if (dist1 * dist2 < 0) {
  6283. hull = [[p0, p1, p3], [p0, p2, p3]];
  6284. } else {
  6285. var distRatio = dist1 / dist2;
  6286. hull = [
  6287. distRatio >= 2 ? [p0, p1, p3]
  6288. : distRatio <= 0.5 ? [p0, p2, p3]
  6289. : [p0, p1, p2, p3],
  6290. [p0, p3]
  6291. ];
  6292. }
  6293. return (dist1 || dist2) < 0 ? hull.reverse() : hull;
  6294. }
  6295. function clipConvexHull(hullTop, hullBottom, dMin, dMax) {
  6296. if (hullTop[0][1] < dMin) {
  6297. return clipConvexHullPart(hullTop, true, dMin);
  6298. } else if (hullBottom[0][1] > dMax) {
  6299. return clipConvexHullPart(hullBottom, false, dMax);
  6300. } else {
  6301. return hullTop[0][0];
  6302. }
  6303. }
  6304. function clipConvexHullPart(part, top, threshold) {
  6305. var px = part[0][0],
  6306. py = part[0][1];
  6307. for (var i = 1, l = part.length; i < l; i++) {
  6308. var qx = part[i][0],
  6309. qy = part[i][1];
  6310. if (top ? qy >= threshold : qy <= threshold) {
  6311. return qy === threshold ? qx
  6312. : px + (threshold - py) * (qx - px) / (qy - py);
  6313. }
  6314. px = qx;
  6315. py = qy;
  6316. }
  6317. return null;
  6318. }
  6319. function getCurveLineIntersections(v, px, py, vx, vy) {
  6320. var isZero = Numerical.isZero;
  6321. if (isZero(vx) && isZero(vy)) {
  6322. var t = Curve.getTimeOf(v, new Point(px, py));
  6323. return t === null ? [] : [t];
  6324. }
  6325. var angle = Math.atan2(-vy, vx),
  6326. sin = Math.sin(angle),
  6327. cos = Math.cos(angle),
  6328. rv = [],
  6329. roots = [];
  6330. for (var i = 0; i < 8; i += 2) {
  6331. var x = v[i] - px,
  6332. y = v[i + 1] - py;
  6333. rv.push(
  6334. x * cos - y * sin,
  6335. x * sin + y * cos);
  6336. }
  6337. Curve.solveCubic(rv, 1, 0, roots, 0, 1);
  6338. return roots;
  6339. }
  6340. function addCurveLineIntersections(v1, v2, c1, c2, locations, include,
  6341. flip) {
  6342. var x1 = v2[0], y1 = v2[1],
  6343. x2 = v2[6], y2 = v2[7],
  6344. roots = getCurveLineIntersections(v1, x1, y1, x2 - x1, y2 - y1);
  6345. for (var i = 0, l = roots.length; i < l; i++) {
  6346. var t1 = roots[i],
  6347. p1 = Curve.getPoint(v1, t1),
  6348. t2 = Curve.getTimeOf(v2, p1);
  6349. if (t2 !== null) {
  6350. addLocation(locations, include,
  6351. flip ? c2 : c1, flip ? t2 : t1,
  6352. flip ? c1 : c2, flip ? t1 : t2);
  6353. }
  6354. }
  6355. }
  6356. function addLineIntersection(v1, v2, c1, c2, locations, include) {
  6357. var pt = Line.intersect(
  6358. v1[0], v1[1], v1[6], v1[7],
  6359. v2[0], v2[1], v2[6], v2[7]);
  6360. if (pt) {
  6361. addLocation(locations, include,
  6362. c1, Curve.getTimeOf(v1, pt),
  6363. c2, Curve.getTimeOf(v2, pt));
  6364. }
  6365. }
  6366. function getCurveIntersections(v1, v2, c1, c2, locations, include) {
  6367. var epsilon = 1e-12,
  6368. min = Math.min,
  6369. max = Math.max;
  6370. if (max(v1[0], v1[2], v1[4], v1[6]) + epsilon >
  6371. min(v2[0], v2[2], v2[4], v2[6]) &&
  6372. min(v1[0], v1[2], v1[4], v1[6]) - epsilon <
  6373. max(v2[0], v2[2], v2[4], v2[6]) &&
  6374. max(v1[1], v1[3], v1[5], v1[7]) + epsilon >
  6375. min(v2[1], v2[3], v2[5], v2[7]) &&
  6376. min(v1[1], v1[3], v1[5], v1[7]) - epsilon <
  6377. max(v2[1], v2[3], v2[5], v2[7])) {
  6378. var overlaps = getOverlaps(v1, v2);
  6379. if (overlaps) {
  6380. for (var i = 0; i < 2; i++) {
  6381. var overlap = overlaps[i];
  6382. addLocation(locations, include,
  6383. c1, overlap[0],
  6384. c2, overlap[1], true);
  6385. }
  6386. } else {
  6387. var straight1 = Curve.isStraight(v1),
  6388. straight2 = Curve.isStraight(v2),
  6389. straight = straight1 && straight2,
  6390. flip = straight1 && !straight2,
  6391. before = locations.length;
  6392. (straight
  6393. ? addLineIntersection
  6394. : straight1 || straight2
  6395. ? addCurveLineIntersections
  6396. : addCurveIntersections)(
  6397. flip ? v2 : v1, flip ? v1 : v2,
  6398. flip ? c2 : c1, flip ? c1 : c2,
  6399. locations, include, flip,
  6400. 0, 0, 0, 1, 0, 1);
  6401. if (!straight || locations.length === before) {
  6402. for (var i = 0; i < 4; i++) {
  6403. var t1 = i >> 1,
  6404. t2 = i & 1,
  6405. i1 = t1 * 6,
  6406. i2 = t2 * 6,
  6407. p1 = new Point(v1[i1], v1[i1 + 1]),
  6408. p2 = new Point(v2[i2], v2[i2 + 1]);
  6409. if (p1.isClose(p2, epsilon)) {
  6410. addLocation(locations, include,
  6411. c1, t1,
  6412. c2, t2);
  6413. }
  6414. }
  6415. }
  6416. }
  6417. }
  6418. return locations;
  6419. }
  6420. function getLoopIntersection(v1, c1, locations, include) {
  6421. var info = Curve.classify(v1);
  6422. if (info.type === 'loop') {
  6423. var roots = info.roots;
  6424. addLocation(locations, include,
  6425. c1, roots[0],
  6426. c1, roots[1]);
  6427. }
  6428. return locations;
  6429. }
  6430. function getIntersections(curves1, curves2, include, matrix1, matrix2,
  6431. _returnFirst) {
  6432. var self = !curves2;
  6433. if (self)
  6434. curves2 = curves1;
  6435. var length1 = curves1.length,
  6436. length2 = curves2.length,
  6437. values2 = [],
  6438. arrays = [],
  6439. locations,
  6440. current;
  6441. for (var i = 0; i < length2; i++)
  6442. values2[i] = curves2[i].getValues(matrix2);
  6443. for (var i = 0; i < length1; i++) {
  6444. var curve1 = curves1[i],
  6445. values1 = self ? values2[i] : curve1.getValues(matrix1),
  6446. path1 = curve1.getPath();
  6447. if (path1 !== current) {
  6448. current = path1;
  6449. locations = [];
  6450. arrays.push(locations);
  6451. }
  6452. if (self) {
  6453. getLoopIntersection(values1, curve1, locations, include);
  6454. }
  6455. for (var j = self ? i + 1 : 0; j < length2; j++) {
  6456. if (_returnFirst && locations.length)
  6457. return locations;
  6458. getCurveIntersections(values1, values2[j], curve1, curves2[j],
  6459. locations, include);
  6460. }
  6461. }
  6462. locations = [];
  6463. for (var i = 0, l = arrays.length; i < l; i++) {
  6464. locations.push.apply(locations, arrays[i]);
  6465. }
  6466. return locations;
  6467. }
  6468. function getOverlaps(v1, v2) {
  6469. function getSquaredLineLength(v) {
  6470. var x = v[6] - v[0],
  6471. y = v[7] - v[1];
  6472. return x * x + y * y;
  6473. }
  6474. var abs = Math.abs,
  6475. getDistance = Line.getDistance,
  6476. timeEpsilon = 1e-8,
  6477. geomEpsilon = 1e-7,
  6478. straight1 = Curve.isStraight(v1),
  6479. straight2 = Curve.isStraight(v2),
  6480. straightBoth = straight1 && straight2,
  6481. flip = getSquaredLineLength(v1) < getSquaredLineLength(v2),
  6482. l1 = flip ? v2 : v1,
  6483. l2 = flip ? v1 : v2,
  6484. px = l1[0], py = l1[1],
  6485. vx = l1[6] - px, vy = l1[7] - py;
  6486. if (getDistance(px, py, vx, vy, l2[0], l2[1], true) < geomEpsilon &&
  6487. getDistance(px, py, vx, vy, l2[6], l2[7], true) < geomEpsilon) {
  6488. if (!straightBoth &&
  6489. getDistance(px, py, vx, vy, l1[2], l1[3], true) < geomEpsilon &&
  6490. getDistance(px, py, vx, vy, l1[4], l1[5], true) < geomEpsilon &&
  6491. getDistance(px, py, vx, vy, l2[2], l2[3], true) < geomEpsilon &&
  6492. getDistance(px, py, vx, vy, l2[4], l2[5], true) < geomEpsilon) {
  6493. straight1 = straight2 = straightBoth = true;
  6494. }
  6495. } else if (straightBoth) {
  6496. return null;
  6497. }
  6498. if (straight1 ^ straight2) {
  6499. return null;
  6500. }
  6501. var v = [v1, v2],
  6502. pairs = [];
  6503. for (var i = 0; i < 4 && pairs.length < 2; i++) {
  6504. var i1 = i & 1,
  6505. i2 = i1 ^ 1,
  6506. t1 = i >> 1,
  6507. t2 = Curve.getTimeOf(v[i1], new Point(
  6508. v[i2][t1 ? 6 : 0],
  6509. v[i2][t1 ? 7 : 1]));
  6510. if (t2 != null) {
  6511. var pair = i1 ? [t1, t2] : [t2, t1];
  6512. if (!pairs.length ||
  6513. abs(pair[0] - pairs[0][0]) > timeEpsilon &&
  6514. abs(pair[1] - pairs[0][1]) > timeEpsilon) {
  6515. pairs.push(pair);
  6516. }
  6517. }
  6518. if (i > 2 && !pairs.length)
  6519. break;
  6520. }
  6521. if (pairs.length !== 2) {
  6522. pairs = null;
  6523. } else if (!straightBoth) {
  6524. var o1 = Curve.getPart(v1, pairs[0][0], pairs[1][0]),
  6525. o2 = Curve.getPart(v2, pairs[0][1], pairs[1][1]);
  6526. if (abs(o2[2] - o1[2]) > geomEpsilon ||
  6527. abs(o2[3] - o1[3]) > geomEpsilon ||
  6528. abs(o2[4] - o1[4]) > geomEpsilon ||
  6529. abs(o2[5] - o1[5]) > geomEpsilon)
  6530. pairs = null;
  6531. }
  6532. return pairs;
  6533. }
  6534. return {
  6535. getIntersections: function(curve) {
  6536. var v1 = this.getValues(),
  6537. v2 = curve && curve !== this && curve.getValues();
  6538. return v2 ? getCurveIntersections(v1, v2, this, curve, [])
  6539. : getLoopIntersection(v1, this, []);
  6540. },
  6541. statics: {
  6542. getOverlaps: getOverlaps,
  6543. getIntersections: getIntersections,
  6544. getCurveLineIntersections: getCurveLineIntersections
  6545. }
  6546. };
  6547. });
  6548. var CurveLocation = Base.extend({
  6549. _class: 'CurveLocation',
  6550. initialize: function CurveLocation(curve, time, point, _overlap, _distance) {
  6551. if (time >= 0.99999999) {
  6552. var next = curve.getNext();
  6553. if (next) {
  6554. time = 0;
  6555. curve = next;
  6556. }
  6557. }
  6558. this._setCurve(curve);
  6559. this._time = time;
  6560. this._point = point || curve.getPointAtTime(time);
  6561. this._overlap = _overlap;
  6562. this._distance = _distance;
  6563. this._intersection = this._next = this._previous = null;
  6564. },
  6565. _setCurve: function(curve) {
  6566. var path = curve._path;
  6567. this._path = path;
  6568. this._version = path ? path._version : 0;
  6569. this._curve = curve;
  6570. this._segment = null;
  6571. this._segment1 = curve._segment1;
  6572. this._segment2 = curve._segment2;
  6573. },
  6574. _setSegment: function(segment) {
  6575. this._setCurve(segment.getCurve());
  6576. this._segment = segment;
  6577. this._time = segment === this._segment1 ? 0 : 1;
  6578. this._point = segment._point.clone();
  6579. },
  6580. getSegment: function() {
  6581. var segment = this._segment;
  6582. if (!segment) {
  6583. var curve = this.getCurve(),
  6584. time = this.getTime();
  6585. if (time === 0) {
  6586. segment = curve._segment1;
  6587. } else if (time === 1) {
  6588. segment = curve._segment2;
  6589. } else if (time != null) {
  6590. segment = curve.getPartLength(0, time)
  6591. < curve.getPartLength(time, 1)
  6592. ? curve._segment1
  6593. : curve._segment2;
  6594. }
  6595. this._segment = segment;
  6596. }
  6597. return segment;
  6598. },
  6599. getCurve: function() {
  6600. var path = this._path,
  6601. that = this;
  6602. if (path && path._version !== this._version) {
  6603. this._time = this._offset = this._curveOffset = this._curve = null;
  6604. }
  6605. function trySegment(segment) {
  6606. var curve = segment && segment.getCurve();
  6607. if (curve && (that._time = curve.getTimeOf(that._point)) != null) {
  6608. that._setCurve(curve);
  6609. return curve;
  6610. }
  6611. }
  6612. return this._curve
  6613. || trySegment(this._segment)
  6614. || trySegment(this._segment1)
  6615. || trySegment(this._segment2.getPrevious());
  6616. },
  6617. getPath: function() {
  6618. var curve = this.getCurve();
  6619. return curve && curve._path;
  6620. },
  6621. getIndex: function() {
  6622. var curve = this.getCurve();
  6623. return curve && curve.getIndex();
  6624. },
  6625. getTime: function() {
  6626. var curve = this.getCurve(),
  6627. time = this._time;
  6628. return curve && time == null
  6629. ? this._time = curve.getTimeOf(this._point)
  6630. : time;
  6631. },
  6632. getParameter: '#getTime',
  6633. getPoint: function() {
  6634. return this._point;
  6635. },
  6636. getOffset: function() {
  6637. var offset = this._offset;
  6638. if (offset == null) {
  6639. offset = 0;
  6640. var path = this.getPath(),
  6641. index = this.getIndex();
  6642. if (path && index != null) {
  6643. var curves = path.getCurves();
  6644. for (var i = 0; i < index; i++)
  6645. offset += curves[i].getLength();
  6646. }
  6647. this._offset = offset += this.getCurveOffset();
  6648. }
  6649. return offset;
  6650. },
  6651. getCurveOffset: function() {
  6652. var offset = this._curveOffset;
  6653. if (offset == null) {
  6654. var curve = this.getCurve(),
  6655. time = this.getTime();
  6656. this._curveOffset = offset = time != null && curve
  6657. && curve.getPartLength(0, time);
  6658. }
  6659. return offset;
  6660. },
  6661. getIntersection: function() {
  6662. return this._intersection;
  6663. },
  6664. getDistance: function() {
  6665. return this._distance;
  6666. },
  6667. divide: function() {
  6668. var curve = this.getCurve(),
  6669. res = curve && curve.divideAtTime(this.getTime());
  6670. if (res) {
  6671. this._setSegment(res._segment1);
  6672. }
  6673. return res;
  6674. },
  6675. split: function() {
  6676. var curve = this.getCurve(),
  6677. path = curve._path,
  6678. res = curve && curve.splitAtTime(this.getTime());
  6679. if (res) {
  6680. this._setSegment(path.getLastSegment());
  6681. }
  6682. return res;
  6683. },
  6684. equals: function(loc, _ignoreOther) {
  6685. var res = this === loc;
  6686. if (!res && loc instanceof CurveLocation) {
  6687. var c1 = this.getCurve(),
  6688. c2 = loc.getCurve(),
  6689. p1 = c1._path,
  6690. p2 = c2._path;
  6691. if (p1 === p2) {
  6692. var abs = Math.abs,
  6693. epsilon = 1e-7,
  6694. diff = abs(this.getOffset() - loc.getOffset()),
  6695. i1 = !_ignoreOther && this._intersection,
  6696. i2 = !_ignoreOther && loc._intersection;
  6697. res = (diff < epsilon
  6698. || p1 && abs(p1.getLength() - diff) < epsilon)
  6699. && (!i1 && !i2 || i1 && i2 && i1.equals(i2, true));
  6700. }
  6701. }
  6702. return res;
  6703. },
  6704. toString: function() {
  6705. var parts = [],
  6706. point = this.getPoint(),
  6707. f = Formatter.instance;
  6708. if (point)
  6709. parts.push('point: ' + point);
  6710. var index = this.getIndex();
  6711. if (index != null)
  6712. parts.push('index: ' + index);
  6713. var time = this.getTime();
  6714. if (time != null)
  6715. parts.push('time: ' + f.number(time));
  6716. if (this._distance != null)
  6717. parts.push('distance: ' + f.number(this._distance));
  6718. return '{ ' + parts.join(', ') + ' }';
  6719. },
  6720. isTouching: function() {
  6721. var inter = this._intersection;
  6722. if (inter && this.getTangent().isCollinear(inter.getTangent())) {
  6723. var curve1 = this.getCurve(),
  6724. curve2 = inter.getCurve();
  6725. return !(curve1.isStraight() && curve2.isStraight()
  6726. && curve1.getLine().intersect(curve2.getLine()));
  6727. }
  6728. return false;
  6729. },
  6730. isCrossing: function() {
  6731. var inter = this._intersection;
  6732. if (!inter)
  6733. return false;
  6734. var t1 = this.getTime(),
  6735. t2 = inter.getTime(),
  6736. tMin = 1e-8,
  6737. tMax = 1 - tMin,
  6738. t1Inside = t1 >= tMin && t1 <= tMax,
  6739. t2Inside = t2 >= tMin && t2 <= tMax;
  6740. if (t1Inside && t2Inside)
  6741. return !this.isTouching();
  6742. var c2 = this.getCurve(),
  6743. c1 = t1 < tMin ? c2.getPrevious() : c2,
  6744. c4 = inter.getCurve(),
  6745. c3 = t2 < tMin ? c4.getPrevious() : c4;
  6746. if (t1 > tMax)
  6747. c2 = c2.getNext();
  6748. if (t2 > tMax)
  6749. c4 = c4.getNext();
  6750. if (!c1 || !c2 || !c3 || !c4)
  6751. return false;
  6752. var offsets = [];
  6753. function addOffsets(curve, end) {
  6754. var v = curve.getValues(),
  6755. roots = Curve.classify(v).roots || Curve.getPeaks(v),
  6756. count = roots.length,
  6757. t = end && count > 1 ? roots[count - 1]
  6758. : count > 0 ? roots[0]
  6759. : 0.5;
  6760. offsets.push(Curve.getLength(v, end ? t : 0, end ? 1 : t) / 2);
  6761. }
  6762. function isInRange(angle, min, max) {
  6763. return min < max
  6764. ? angle > min && angle < max
  6765. : angle > min || angle < max;
  6766. }
  6767. if (!t1Inside) {
  6768. addOffsets(c1, true);
  6769. addOffsets(c2, false);
  6770. }
  6771. if (!t2Inside) {
  6772. addOffsets(c3, true);
  6773. addOffsets(c4, false);
  6774. }
  6775. var pt = this.getPoint(),
  6776. offset = Math.min.apply(Math, offsets),
  6777. v2 = t1Inside ? c2.getTangentAtTime(t1)
  6778. : c2.getPointAt(offset).subtract(pt),
  6779. v1 = t1Inside ? v2.negate()
  6780. : c1.getPointAt(-offset).subtract(pt),
  6781. v4 = t2Inside ? c4.getTangentAtTime(t2)
  6782. : c4.getPointAt(offset).subtract(pt),
  6783. v3 = t2Inside ? v4.negate()
  6784. : c3.getPointAt(-offset).subtract(pt),
  6785. a1 = v1.getAngle(),
  6786. a2 = v2.getAngle(),
  6787. a3 = v3.getAngle(),
  6788. a4 = v4.getAngle();
  6789. return !!(t1Inside
  6790. ? (isInRange(a1, a3, a4) ^ isInRange(a2, a3, a4)) &&
  6791. (isInRange(a1, a4, a3) ^ isInRange(a2, a4, a3))
  6792. : (isInRange(a3, a1, a2) ^ isInRange(a4, a1, a2)) &&
  6793. (isInRange(a3, a2, a1) ^ isInRange(a4, a2, a1)));
  6794. },
  6795. hasOverlap: function() {
  6796. return !!this._overlap;
  6797. }
  6798. }, Base.each(Curve._evaluateMethods, function(name) {
  6799. var get = name + 'At';
  6800. this[name] = function() {
  6801. var curve = this.getCurve(),
  6802. time = this.getTime();
  6803. return time != null && curve && curve[get](time, true);
  6804. };
  6805. }, {
  6806. preserve: true
  6807. }),
  6808. new function() {
  6809. function insert(locations, loc, merge) {
  6810. var length = locations.length,
  6811. l = 0,
  6812. r = length - 1;
  6813. function search(index, dir) {
  6814. for (var i = index + dir; i >= -1 && i <= length; i += dir) {
  6815. var loc2 = locations[((i % length) + length) % length];
  6816. if (!loc.getPoint().isClose(loc2.getPoint(),
  6817. 1e-7))
  6818. break;
  6819. if (loc.equals(loc2))
  6820. return loc2;
  6821. }
  6822. return null;
  6823. }
  6824. while (l <= r) {
  6825. var m = (l + r) >>> 1,
  6826. loc2 = locations[m],
  6827. found;
  6828. if (merge && (found = loc.equals(loc2) ? loc2
  6829. : (search(m, -1) || search(m, 1)))) {
  6830. if (loc._overlap) {
  6831. found._overlap = found._intersection._overlap = true;
  6832. }
  6833. return found;
  6834. }
  6835. var path1 = loc.getPath(),
  6836. path2 = loc2.getPath(),
  6837. diff = path1 !== path2
  6838. ? path1._id - path2._id
  6839. : (loc.getIndex() + loc.getTime())
  6840. - (loc2.getIndex() + loc2.getTime());
  6841. if (diff < 0) {
  6842. r = m - 1;
  6843. } else {
  6844. l = m + 1;
  6845. }
  6846. }
  6847. locations.splice(l, 0, loc);
  6848. return loc;
  6849. }
  6850. return { statics: {
  6851. insert: insert,
  6852. expand: function(locations) {
  6853. var expanded = locations.slice();
  6854. for (var i = locations.length - 1; i >= 0; i--) {
  6855. insert(expanded, locations[i]._intersection, false);
  6856. }
  6857. return expanded;
  6858. }
  6859. }};
  6860. });
  6861. var PathItem = Item.extend({
  6862. _class: 'PathItem',
  6863. _selectBounds: false,
  6864. _canScaleStroke: true,
  6865. beans: true,
  6866. initialize: function PathItem() {
  6867. },
  6868. statics: {
  6869. create: function(arg) {
  6870. var data,
  6871. segments,
  6872. compound;
  6873. if (Base.isPlainObject(arg)) {
  6874. segments = arg.segments;
  6875. data = arg.pathData;
  6876. } else if (Array.isArray(arg)) {
  6877. segments = arg;
  6878. } else if (typeof arg === 'string') {
  6879. data = arg;
  6880. }
  6881. if (segments) {
  6882. var first = segments[0];
  6883. compound = first && Array.isArray(first[0]);
  6884. } else if (data) {
  6885. compound = (data.match(/m/gi) || []).length > 1
  6886. || /z\s*\S+/i.test(data);
  6887. }
  6888. var ctor = compound ? CompoundPath : Path;
  6889. return new ctor(arg);
  6890. }
  6891. },
  6892. _asPathItem: function() {
  6893. return this;
  6894. },
  6895. isClockwise: function() {
  6896. return this.getArea() >= 0;
  6897. },
  6898. setClockwise: function(clockwise) {
  6899. if (this.isClockwise() != (clockwise = !!clockwise))
  6900. this.reverse();
  6901. },
  6902. setPathData: function(data) {
  6903. var parts = data && data.match(/[mlhvcsqtaz][^mlhvcsqtaz]*/ig),
  6904. coords,
  6905. relative = false,
  6906. previous,
  6907. control,
  6908. current = new Point(),
  6909. start = new Point();
  6910. function getCoord(index, coord) {
  6911. var val = +coords[index];
  6912. if (relative)
  6913. val += current[coord];
  6914. return val;
  6915. }
  6916. function getPoint(index) {
  6917. return new Point(
  6918. getCoord(index, 'x'),
  6919. getCoord(index + 1, 'y')
  6920. );
  6921. }
  6922. this.clear();
  6923. for (var i = 0, l = parts && parts.length; i < l; i++) {
  6924. var part = parts[i],
  6925. command = part[0],
  6926. lower = command.toLowerCase();
  6927. coords = part.match(/[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g);
  6928. var length = coords && coords.length;
  6929. relative = command === lower;
  6930. if (previous === 'z' && !/[mz]/.test(lower))
  6931. this.moveTo(current);
  6932. switch (lower) {
  6933. case 'm':
  6934. case 'l':
  6935. var move = lower === 'm';
  6936. for (var j = 0; j < length; j += 2) {
  6937. this[move ? 'moveTo' : 'lineTo'](current = getPoint(j));
  6938. if (move) {
  6939. start = current;
  6940. move = false;
  6941. }
  6942. }
  6943. control = current;
  6944. break;
  6945. case 'h':
  6946. case 'v':
  6947. var coord = lower === 'h' ? 'x' : 'y';
  6948. current = current.clone();
  6949. for (var j = 0; j < length; j++) {
  6950. current[coord] = getCoord(j, coord);
  6951. this.lineTo(current);
  6952. }
  6953. control = current;
  6954. break;
  6955. case 'c':
  6956. for (var j = 0; j < length; j += 6) {
  6957. this.cubicCurveTo(
  6958. getPoint(j),
  6959. control = getPoint(j + 2),
  6960. current = getPoint(j + 4));
  6961. }
  6962. break;
  6963. case 's':
  6964. for (var j = 0; j < length; j += 4) {
  6965. this.cubicCurveTo(
  6966. /[cs]/.test(previous)
  6967. ? current.multiply(2).subtract(control)
  6968. : current,
  6969. control = getPoint(j),
  6970. current = getPoint(j + 2));
  6971. previous = lower;
  6972. }
  6973. break;
  6974. case 'q':
  6975. for (var j = 0; j < length; j += 4) {
  6976. this.quadraticCurveTo(
  6977. control = getPoint(j),
  6978. current = getPoint(j + 2));
  6979. }
  6980. break;
  6981. case 't':
  6982. for (var j = 0; j < length; j += 2) {
  6983. this.quadraticCurveTo(
  6984. control = (/[qt]/.test(previous)
  6985. ? current.multiply(2).subtract(control)
  6986. : current),
  6987. current = getPoint(j));
  6988. previous = lower;
  6989. }
  6990. break;
  6991. case 'a':
  6992. for (var j = 0; j < length; j += 7) {
  6993. this.arcTo(current = getPoint(j + 5),
  6994. new Size(+coords[j], +coords[j + 1]),
  6995. +coords[j + 2], +coords[j + 4], +coords[j + 3]);
  6996. }
  6997. break;
  6998. case 'z':
  6999. this.closePath(1e-12);
  7000. current = start;
  7001. break;
  7002. }
  7003. previous = lower;
  7004. }
  7005. },
  7006. _canComposite: function() {
  7007. return !(this.hasFill() && this.hasStroke());
  7008. },
  7009. _contains: function(point) {
  7010. var winding = point.isInside(
  7011. this.getBounds({ internal: true, handle: true }))
  7012. ? this._getWinding(point)
  7013. : {};
  7014. return winding.onPath || !!(this.getFillRule() === 'evenodd'
  7015. ? winding.windingL & 1 || winding.windingR & 1
  7016. : winding.winding);
  7017. },
  7018. getIntersections: function(path, include, _matrix, _returnFirst) {
  7019. var self = this === path || !path,
  7020. matrix1 = this._matrix._orNullIfIdentity(),
  7021. matrix2 = self ? matrix1
  7022. : (_matrix || path._matrix)._orNullIfIdentity();
  7023. return self || this.getBounds(matrix1).intersects(
  7024. path.getBounds(matrix2), 1e-12)
  7025. ? Curve.getIntersections(
  7026. this.getCurves(), !self && path.getCurves(), include,
  7027. matrix1, matrix2, _returnFirst)
  7028. : [];
  7029. },
  7030. getCrossings: function(path) {
  7031. return this.getIntersections(path, function(inter) {
  7032. return inter.hasOverlap() || inter.isCrossing();
  7033. });
  7034. },
  7035. getNearestLocation: function() {
  7036. var point = Point.read(arguments),
  7037. curves = this.getCurves(),
  7038. minDist = Infinity,
  7039. minLoc = null;
  7040. for (var i = 0, l = curves.length; i < l; i++) {
  7041. var loc = curves[i].getNearestLocation(point);
  7042. if (loc._distance < minDist) {
  7043. minDist = loc._distance;
  7044. minLoc = loc;
  7045. }
  7046. }
  7047. return minLoc;
  7048. },
  7049. getNearestPoint: function() {
  7050. var loc = this.getNearestLocation.apply(this, arguments);
  7051. return loc ? loc.getPoint() : loc;
  7052. },
  7053. interpolate: function(from, to, factor) {
  7054. var isPath = !this._children,
  7055. name = isPath ? '_segments' : '_children',
  7056. itemsFrom = from[name],
  7057. itemsTo = to[name],
  7058. items = this[name];
  7059. if (!itemsFrom || !itemsTo || itemsFrom.length !== itemsTo.length) {
  7060. throw new Error('Invalid operands in interpolate() call: ' +
  7061. from + ', ' + to);
  7062. }
  7063. var current = items.length,
  7064. length = itemsTo.length;
  7065. if (current < length) {
  7066. var ctor = isPath ? Segment : Path;
  7067. for (var i = current; i < length; i++) {
  7068. this.add(new ctor());
  7069. }
  7070. } else if (current > length) {
  7071. this[isPath ? 'removeSegments' : 'removeChildren'](length, current);
  7072. }
  7073. for (var i = 0; i < length; i++) {
  7074. items[i].interpolate(itemsFrom[i], itemsTo[i], factor);
  7075. }
  7076. if (isPath) {
  7077. this.setClosed(from._closed);
  7078. this._changed(9);
  7079. }
  7080. },
  7081. compare: function(path) {
  7082. var ok = false;
  7083. if (path) {
  7084. var paths1 = this._children || [this],
  7085. paths2 = path._children ? path._children.slice() : [path],
  7086. length1 = paths1.length,
  7087. length2 = paths2.length,
  7088. matched = [],
  7089. count = 0;
  7090. ok = true;
  7091. for (var i1 = length1 - 1; i1 >= 0 && ok; i1--) {
  7092. var path1 = paths1[i1];
  7093. ok = false;
  7094. for (var i2 = length2 - 1; i2 >= 0 && !ok; i2--) {
  7095. if (path1.compare(paths2[i2])) {
  7096. if (!matched[i2]) {
  7097. matched[i2] = true;
  7098. count++;
  7099. }
  7100. ok = true;
  7101. }
  7102. }
  7103. }
  7104. ok = ok && count === length2;
  7105. }
  7106. return ok;
  7107. },
  7108. });
  7109. var Path = PathItem.extend({
  7110. _class: 'Path',
  7111. _serializeFields: {
  7112. segments: [],
  7113. closed: false
  7114. },
  7115. initialize: function Path(arg) {
  7116. this._closed = false;
  7117. this._segments = [];
  7118. this._version = 0;
  7119. var segments = Array.isArray(arg)
  7120. ? typeof arg[0] === 'object'
  7121. ? arg
  7122. : arguments
  7123. : arg && (arg.size === undefined && (arg.x !== undefined
  7124. || arg.point !== undefined))
  7125. ? arguments
  7126. : null;
  7127. if (segments && segments.length > 0) {
  7128. this.setSegments(segments);
  7129. } else {
  7130. this._curves = undefined;
  7131. this._segmentSelection = 0;
  7132. if (!segments && typeof arg === 'string') {
  7133. this.setPathData(arg);
  7134. arg = null;
  7135. }
  7136. }
  7137. this._initialize(!segments && arg);
  7138. },
  7139. _equals: function(item) {
  7140. return this._closed === item._closed
  7141. && Base.equals(this._segments, item._segments);
  7142. },
  7143. copyContent: function(source) {
  7144. this.setSegments(source._segments);
  7145. this._closed = source._closed;
  7146. },
  7147. _changed: function _changed(flags) {
  7148. _changed.base.call(this, flags);
  7149. if (flags & 8) {
  7150. this._length = this._area = undefined;
  7151. if (flags & 16) {
  7152. this._version++;
  7153. } else if (this._curves) {
  7154. for (var i = 0, l = this._curves.length; i < l; i++)
  7155. this._curves[i]._changed();
  7156. }
  7157. } else if (flags & 32) {
  7158. this._bounds = undefined;
  7159. }
  7160. },
  7161. getStyle: function() {
  7162. var parent = this._parent;
  7163. return (parent instanceof CompoundPath ? parent : this)._style;
  7164. },
  7165. getSegments: function() {
  7166. return this._segments;
  7167. },
  7168. setSegments: function(segments) {
  7169. var fullySelected = this.isFullySelected(),
  7170. length = segments && segments.length;
  7171. this._segments.length = 0;
  7172. this._segmentSelection = 0;
  7173. this._curves = undefined;
  7174. if (length) {
  7175. var last = segments[length - 1];
  7176. if (typeof last === 'boolean') {
  7177. this.setClosed(last);
  7178. length--;
  7179. }
  7180. this._add(Segment.readList(segments, 0, {}, length));
  7181. }
  7182. if (fullySelected)
  7183. this.setFullySelected(true);
  7184. },
  7185. getFirstSegment: function() {
  7186. return this._segments[0];
  7187. },
  7188. getLastSegment: function() {
  7189. return this._segments[this._segments.length - 1];
  7190. },
  7191. getCurves: function() {
  7192. var curves = this._curves,
  7193. segments = this._segments;
  7194. if (!curves) {
  7195. var length = this._countCurves();
  7196. curves = this._curves = new Array(length);
  7197. for (var i = 0; i < length; i++)
  7198. curves[i] = new Curve(this, segments[i],
  7199. segments[i + 1] || segments[0]);
  7200. }
  7201. return curves;
  7202. },
  7203. getFirstCurve: function() {
  7204. return this.getCurves()[0];
  7205. },
  7206. getLastCurve: function() {
  7207. var curves = this.getCurves();
  7208. return curves[curves.length - 1];
  7209. },
  7210. isClosed: function() {
  7211. return this._closed;
  7212. },
  7213. setClosed: function(closed) {
  7214. if (this._closed != (closed = !!closed)) {
  7215. this._closed = closed;
  7216. if (this._curves) {
  7217. var length = this._curves.length = this._countCurves();
  7218. if (closed)
  7219. this._curves[length - 1] = new Curve(this,
  7220. this._segments[length - 1], this._segments[0]);
  7221. }
  7222. this._changed(25);
  7223. }
  7224. }
  7225. }, {
  7226. beans: true,
  7227. getPathData: function(_matrix, _precision) {
  7228. var segments = this._segments,
  7229. length = segments.length,
  7230. f = new Formatter(_precision),
  7231. coords = new Array(6),
  7232. first = true,
  7233. curX, curY,
  7234. prevX, prevY,
  7235. inX, inY,
  7236. outX, outY,
  7237. parts = [];
  7238. function addSegment(segment, skipLine) {
  7239. segment._transformCoordinates(_matrix, coords);
  7240. curX = coords[0];
  7241. curY = coords[1];
  7242. if (first) {
  7243. parts.push('M' + f.pair(curX, curY));
  7244. first = false;
  7245. } else {
  7246. inX = coords[2];
  7247. inY = coords[3];
  7248. if (inX === curX && inY === curY
  7249. && outX === prevX && outY === prevY) {
  7250. if (!skipLine) {
  7251. var dx = curX - prevX,
  7252. dy = curY - prevY;
  7253. parts.push(
  7254. dx === 0 ? 'v' + f.number(dy)
  7255. : dy === 0 ? 'h' + f.number(dx)
  7256. : 'l' + f.pair(dx, dy));
  7257. }
  7258. } else {
  7259. parts.push('c' + f.pair(outX - prevX, outY - prevY)
  7260. + ' ' + f.pair( inX - prevX, inY - prevY)
  7261. + ' ' + f.pair(curX - prevX, curY - prevY));
  7262. }
  7263. }
  7264. prevX = curX;
  7265. prevY = curY;
  7266. outX = coords[4];
  7267. outY = coords[5];
  7268. }
  7269. if (!length)
  7270. return '';
  7271. for (var i = 0; i < length; i++)
  7272. addSegment(segments[i]);
  7273. if (this._closed && length > 0) {
  7274. addSegment(segments[0], true);
  7275. parts.push('z');
  7276. }
  7277. return parts.join('');
  7278. },
  7279. isEmpty: function() {
  7280. return !this._segments.length;
  7281. },
  7282. _transformContent: function(matrix) {
  7283. var segments = this._segments,
  7284. coords = new Array(6);
  7285. for (var i = 0, l = segments.length; i < l; i++)
  7286. segments[i]._transformCoordinates(matrix, coords, true);
  7287. return true;
  7288. },
  7289. _add: function(segs, index) {
  7290. var segments = this._segments,
  7291. curves = this._curves,
  7292. amount = segs.length,
  7293. append = index == null,
  7294. index = append ? segments.length : index;
  7295. for (var i = 0; i < amount; i++) {
  7296. var segment = segs[i];
  7297. if (segment._path)
  7298. segment = segs[i] = segment.clone();
  7299. segment._path = this;
  7300. segment._index = index + i;
  7301. if (segment._selection)
  7302. this._updateSelection(segment, 0, segment._selection);
  7303. }
  7304. if (append) {
  7305. segments.push.apply(segments, segs);
  7306. } else {
  7307. segments.splice.apply(segments, [index, 0].concat(segs));
  7308. for (var i = index + amount, l = segments.length; i < l; i++)
  7309. segments[i]._index = i;
  7310. }
  7311. if (curves) {
  7312. var total = this._countCurves(),
  7313. start = index > 0 && index + amount - 1 === total ? index - 1
  7314. : index,
  7315. insert = start,
  7316. end = Math.min(start + amount, total);
  7317. if (segs._curves) {
  7318. curves.splice.apply(curves, [start, 0].concat(segs._curves));
  7319. insert += segs._curves.length;
  7320. }
  7321. for (var i = insert; i < end; i++)
  7322. curves.splice(i, 0, new Curve(this, null, null));
  7323. this._adjustCurves(start, end);
  7324. }
  7325. this._changed(25);
  7326. return segs;
  7327. },
  7328. _adjustCurves: function(start, end) {
  7329. var segments = this._segments,
  7330. curves = this._curves,
  7331. curve;
  7332. for (var i = start; i < end; i++) {
  7333. curve = curves[i];
  7334. curve._path = this;
  7335. curve._segment1 = segments[i];
  7336. curve._segment2 = segments[i + 1] || segments[0];
  7337. curve._changed();
  7338. }
  7339. if (curve = curves[this._closed && !start ? segments.length - 1
  7340. : start - 1]) {
  7341. curve._segment2 = segments[start] || segments[0];
  7342. curve._changed();
  7343. }
  7344. if (curve = curves[end]) {
  7345. curve._segment1 = segments[end];
  7346. curve._changed();
  7347. }
  7348. },
  7349. _countCurves: function() {
  7350. var length = this._segments.length;
  7351. return !this._closed && length > 0 ? length - 1 : length;
  7352. },
  7353. add: function(segment1 ) {
  7354. return arguments.length > 1 && typeof segment1 !== 'number'
  7355. ? this._add(Segment.readList(arguments))
  7356. : this._add([ Segment.read(arguments) ])[0];
  7357. },
  7358. insert: function(index, segment1 ) {
  7359. return arguments.length > 2 && typeof segment1 !== 'number'
  7360. ? this._add(Segment.readList(arguments, 1), index)
  7361. : this._add([ Segment.read(arguments, 1) ], index)[0];
  7362. },
  7363. addSegment: function() {
  7364. return this._add([ Segment.read(arguments) ])[0];
  7365. },
  7366. insertSegment: function(index ) {
  7367. return this._add([ Segment.read(arguments, 1) ], index)[0];
  7368. },
  7369. addSegments: function(segments) {
  7370. return this._add(Segment.readList(segments));
  7371. },
  7372. insertSegments: function(index, segments) {
  7373. return this._add(Segment.readList(segments), index);
  7374. },
  7375. removeSegment: function(index) {
  7376. return this.removeSegments(index, index + 1)[0] || null;
  7377. },
  7378. removeSegments: function(start, end, _includeCurves) {
  7379. start = start || 0;
  7380. end = Base.pick(end, this._segments.length);
  7381. var segments = this._segments,
  7382. curves = this._curves,
  7383. count = segments.length,
  7384. removed = segments.splice(start, end - start),
  7385. amount = removed.length;
  7386. if (!amount)
  7387. return removed;
  7388. for (var i = 0; i < amount; i++) {
  7389. var segment = removed[i];
  7390. if (segment._selection)
  7391. this._updateSelection(segment, segment._selection, 0);
  7392. segment._index = segment._path = null;
  7393. }
  7394. for (var i = start, l = segments.length; i < l; i++)
  7395. segments[i]._index = i;
  7396. if (curves) {
  7397. var index = start > 0 && end === count + (this._closed ? 1 : 0)
  7398. ? start - 1
  7399. : start,
  7400. curves = curves.splice(index, amount);
  7401. for (var i = curves.length - 1; i >= 0; i--)
  7402. curves[i]._path = null;
  7403. if (_includeCurves)
  7404. removed._curves = curves.slice(1);
  7405. this._adjustCurves(index, index);
  7406. }
  7407. this._changed(25);
  7408. return removed;
  7409. },
  7410. clear: '#removeSegments',
  7411. hasHandles: function() {
  7412. var segments = this._segments;
  7413. for (var i = 0, l = segments.length; i < l; i++) {
  7414. if (segments[i].hasHandles())
  7415. return true;
  7416. }
  7417. return false;
  7418. },
  7419. clearHandles: function() {
  7420. var segments = this._segments;
  7421. for (var i = 0, l = segments.length; i < l; i++)
  7422. segments[i].clearHandles();
  7423. },
  7424. getLength: function() {
  7425. if (this._length == null) {
  7426. var curves = this.getCurves(),
  7427. length = 0;
  7428. for (var i = 0, l = curves.length; i < l; i++)
  7429. length += curves[i].getLength();
  7430. this._length = length;
  7431. }
  7432. return this._length;
  7433. },
  7434. getArea: function() {
  7435. var area = this._area;
  7436. if (area == null) {
  7437. var segments = this._segments,
  7438. closed = this._closed;
  7439. area = 0;
  7440. for (var i = 0, l = segments.length; i < l; i++) {
  7441. var last = i + 1 === l;
  7442. area += Curve.getArea(Curve.getValues(
  7443. segments[i], segments[last ? 0 : i + 1],
  7444. null, last && !closed));
  7445. }
  7446. this._area = area;
  7447. }
  7448. return area;
  7449. },
  7450. isFullySelected: function() {
  7451. var length = this._segments.length;
  7452. return this.isSelected() && length > 0 && this._segmentSelection
  7453. === length * 7;
  7454. },
  7455. setFullySelected: function(selected) {
  7456. if (selected)
  7457. this._selectSegments(true);
  7458. this.setSelected(selected);
  7459. },
  7460. setSelection: function setSelection(selection) {
  7461. if (!(selection & 1))
  7462. this._selectSegments(false);
  7463. setSelection.base.call(this, selection);
  7464. },
  7465. _selectSegments: function(selected) {
  7466. var segments = this._segments,
  7467. length = segments.length,
  7468. selection = selected ? 7 : 0;
  7469. this._segmentSelection = selection * length;
  7470. for (var i = 0; i < length; i++)
  7471. segments[i]._selection = selection;
  7472. },
  7473. _updateSelection: function(segment, oldSelection, newSelection) {
  7474. segment._selection = newSelection;
  7475. var selection = this._segmentSelection += newSelection - oldSelection;
  7476. if (selection > 0)
  7477. this.setSelected(true);
  7478. },
  7479. divideAt: function(location) {
  7480. var loc = this.getLocationAt(location),
  7481. curve;
  7482. return loc && (curve = loc.getCurve().divideAt(loc.getCurveOffset()))
  7483. ? curve._segment1
  7484. : null;
  7485. },
  7486. splitAt: function(location) {
  7487. var loc = this.getLocationAt(location),
  7488. index = loc && loc.index,
  7489. time = loc && loc.time,
  7490. tMin = 1e-8,
  7491. tMax = 1 - tMin;
  7492. if (time > tMax) {
  7493. index++;
  7494. time = 0;
  7495. }
  7496. var curves = this.getCurves();
  7497. if (index >= 0 && index < curves.length) {
  7498. if (time >= tMin) {
  7499. curves[index++].divideAtTime(time);
  7500. }
  7501. var segs = this.removeSegments(index, this._segments.length, true),
  7502. path;
  7503. if (this._closed) {
  7504. this.setClosed(false);
  7505. path = this;
  7506. } else {
  7507. path = new Path(Item.NO_INSERT);
  7508. path.insertAbove(this);
  7509. path.copyAttributes(this);
  7510. }
  7511. path._add(segs, 0);
  7512. this.addSegment(segs[0]);
  7513. return path;
  7514. }
  7515. return null;
  7516. },
  7517. split: function(index, time) {
  7518. var curve,
  7519. location = time === undefined ? index
  7520. : (curve = this.getCurves()[index])
  7521. && curve.getLocationAtTime(time);
  7522. return location != null ? this.splitAt(location) : null;
  7523. },
  7524. join: function(path, tolerance) {
  7525. var epsilon = tolerance || 0;
  7526. if (path && path !== this) {
  7527. var segments = path._segments,
  7528. last1 = this.getLastSegment(),
  7529. last2 = path.getLastSegment();
  7530. if (!last2)
  7531. return this;
  7532. if (last1 && last1._point.isClose(last2._point, epsilon))
  7533. path.reverse();
  7534. var first2 = path.getFirstSegment();
  7535. if (last1 && last1._point.isClose(first2._point, epsilon)) {
  7536. last1.setHandleOut(first2._handleOut);
  7537. this._add(segments.slice(1));
  7538. } else {
  7539. var first1 = this.getFirstSegment();
  7540. if (first1 && first1._point.isClose(first2._point, epsilon))
  7541. path.reverse();
  7542. last2 = path.getLastSegment();
  7543. if (first1 && first1._point.isClose(last2._point, epsilon)) {
  7544. first1.setHandleIn(last2._handleIn);
  7545. this._add(segments.slice(0, segments.length - 1), 0);
  7546. } else {
  7547. this._add(segments.slice());
  7548. }
  7549. }
  7550. if (path._closed)
  7551. this._add([segments[0]]);
  7552. path.remove();
  7553. }
  7554. var first = this.getFirstSegment(),
  7555. last = this.getLastSegment();
  7556. if (first !== last && first._point.isClose(last._point, epsilon)) {
  7557. first.setHandleIn(last._handleIn);
  7558. last.remove();
  7559. this.setClosed(true);
  7560. }
  7561. return this;
  7562. },
  7563. reduce: function(options) {
  7564. var curves = this.getCurves(),
  7565. simplify = options && options.simplify,
  7566. tolerance = simplify ? 1e-7 : 0;
  7567. for (var i = curves.length - 1; i >= 0; i--) {
  7568. var curve = curves[i];
  7569. if (!curve.hasHandles() && (!curve.hasLength(tolerance)
  7570. || simplify && curve.isCollinear(curve.getNext())))
  7571. curve.remove();
  7572. }
  7573. return this;
  7574. },
  7575. reverse: function() {
  7576. this._segments.reverse();
  7577. for (var i = 0, l = this._segments.length; i < l; i++) {
  7578. var segment = this._segments[i];
  7579. var handleIn = segment._handleIn;
  7580. segment._handleIn = segment._handleOut;
  7581. segment._handleOut = handleIn;
  7582. segment._index = i;
  7583. }
  7584. this._curves = null;
  7585. this._changed(9);
  7586. },
  7587. flatten: function(flatness) {
  7588. var flattener = new PathFlattener(this, flatness || 0.25, 256, true),
  7589. parts = flattener.parts,
  7590. length = parts.length,
  7591. segments = [];
  7592. for (var i = 0; i < length; i++) {
  7593. segments.push(new Segment(parts[i].curve.slice(0, 2)));
  7594. }
  7595. if (!this._closed && length > 0) {
  7596. segments.push(new Segment(parts[length - 1].curve.slice(6)));
  7597. }
  7598. this.setSegments(segments);
  7599. },
  7600. simplify: function(tolerance) {
  7601. var segments = new PathFitter(this).fit(tolerance || 2.5);
  7602. if (segments)
  7603. this.setSegments(segments);
  7604. return !!segments;
  7605. },
  7606. smooth: function(options) {
  7607. var that = this,
  7608. opts = options || {},
  7609. type = opts.type || 'asymmetric',
  7610. segments = this._segments,
  7611. length = segments.length,
  7612. closed = this._closed;
  7613. function getIndex(value, _default) {
  7614. var index = value && value.index;
  7615. if (index != null) {
  7616. var path = value.path;
  7617. if (path && path !== that)
  7618. throw new Error(value._class + ' ' + index + ' of ' + path
  7619. + ' is not part of ' + that);
  7620. if (_default && value instanceof Curve)
  7621. index++;
  7622. } else {
  7623. index = typeof value === 'number' ? value : _default;
  7624. }
  7625. return Math.min(index < 0 && closed
  7626. ? index % length
  7627. : index < 0 ? index + length : index, length - 1);
  7628. }
  7629. var loop = closed && opts.from === undefined && opts.to === undefined,
  7630. from = getIndex(opts.from, 0),
  7631. to = getIndex(opts.to, length - 1);
  7632. if (from > to) {
  7633. if (closed) {
  7634. from -= length;
  7635. } else {
  7636. var tmp = from;
  7637. from = to;
  7638. to = tmp;
  7639. }
  7640. }
  7641. if (/^(?:asymmetric|continuous)$/.test(type)) {
  7642. var asymmetric = type === 'asymmetric',
  7643. min = Math.min,
  7644. amount = to - from + 1,
  7645. n = amount - 1,
  7646. padding = loop ? min(amount, 4) : 1,
  7647. paddingLeft = padding,
  7648. paddingRight = padding,
  7649. knots = [];
  7650. if (!closed) {
  7651. paddingLeft = min(1, from);
  7652. paddingRight = min(1, length - to - 1);
  7653. }
  7654. n += paddingLeft + paddingRight;
  7655. if (n <= 1)
  7656. return;
  7657. for (var i = 0, j = from - paddingLeft; i <= n; i++, j++) {
  7658. knots[i] = segments[(j < 0 ? j + length : j) % length]._point;
  7659. }
  7660. var x = knots[0]._x + 2 * knots[1]._x,
  7661. y = knots[0]._y + 2 * knots[1]._y,
  7662. f = 2,
  7663. n_1 = n - 1,
  7664. rx = [x],
  7665. ry = [y],
  7666. rf = [f],
  7667. px = [],
  7668. py = [];
  7669. for (var i = 1; i < n; i++) {
  7670. var internal = i < n_1,
  7671. a = internal ? 1 : asymmetric ? 1 : 2,
  7672. b = internal ? 4 : asymmetric ? 2 : 7,
  7673. u = internal ? 4 : asymmetric ? 3 : 8,
  7674. v = internal ? 2 : asymmetric ? 0 : 1,
  7675. m = a / f;
  7676. f = rf[i] = b - m;
  7677. x = rx[i] = u * knots[i]._x + v * knots[i + 1]._x - m * x;
  7678. y = ry[i] = u * knots[i]._y + v * knots[i + 1]._y - m * y;
  7679. }
  7680. px[n_1] = rx[n_1] / rf[n_1];
  7681. py[n_1] = ry[n_1] / rf[n_1];
  7682. for (var i = n - 2; i >= 0; i--) {
  7683. px[i] = (rx[i] - px[i + 1]) / rf[i];
  7684. py[i] = (ry[i] - py[i + 1]) / rf[i];
  7685. }
  7686. px[n] = (3 * knots[n]._x - px[n_1]) / 2;
  7687. py[n] = (3 * knots[n]._y - py[n_1]) / 2;
  7688. for (var i = paddingLeft, max = n - paddingRight, j = from;
  7689. i <= max; i++, j++) {
  7690. var segment = segments[j < 0 ? j + length : j],
  7691. pt = segment._point,
  7692. hx = px[i] - pt._x,
  7693. hy = py[i] - pt._y;
  7694. if (loop || i < max)
  7695. segment.setHandleOut(hx, hy);
  7696. if (loop || i > paddingLeft)
  7697. segment.setHandleIn(-hx, -hy);
  7698. }
  7699. } else {
  7700. for (var i = from; i <= to; i++) {
  7701. segments[i < 0 ? i + length : i].smooth(opts,
  7702. !loop && i === from, !loop && i === to);
  7703. }
  7704. }
  7705. },
  7706. toShape: function(insert) {
  7707. if (!this._closed)
  7708. return null;
  7709. var segments = this._segments,
  7710. type,
  7711. size,
  7712. radius,
  7713. topCenter;
  7714. function isCollinear(i, j) {
  7715. var seg1 = segments[i],
  7716. seg2 = seg1.getNext(),
  7717. seg3 = segments[j],
  7718. seg4 = seg3.getNext();
  7719. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  7720. && seg3._handleOut.isZero() && seg4._handleIn.isZero()
  7721. && seg2._point.subtract(seg1._point).isCollinear(
  7722. seg4._point.subtract(seg3._point));
  7723. }
  7724. function isOrthogonal(i) {
  7725. var seg2 = segments[i],
  7726. seg1 = seg2.getPrevious(),
  7727. seg3 = seg2.getNext();
  7728. return seg1._handleOut.isZero() && seg2._handleIn.isZero()
  7729. && seg2._handleOut.isZero() && seg3._handleIn.isZero()
  7730. && seg2._point.subtract(seg1._point).isOrthogonal(
  7731. seg3._point.subtract(seg2._point));
  7732. }
  7733. function isArc(i) {
  7734. var seg1 = segments[i],
  7735. seg2 = seg1.getNext(),
  7736. handle1 = seg1._handleOut,
  7737. handle2 = seg2._handleIn,
  7738. kappa = 0.5522847498307936;
  7739. if (handle1.isOrthogonal(handle2)) {
  7740. var pt1 = seg1._point,
  7741. pt2 = seg2._point,
  7742. corner = new Line(pt1, handle1, true).intersect(
  7743. new Line(pt2, handle2, true), true);
  7744. return corner && Numerical.isZero(handle1.getLength() /
  7745. corner.subtract(pt1).getLength() - kappa)
  7746. && Numerical.isZero(handle2.getLength() /
  7747. corner.subtract(pt2).getLength() - kappa);
  7748. }
  7749. return false;
  7750. }
  7751. function getDistance(i, j) {
  7752. return segments[i]._point.getDistance(segments[j]._point);
  7753. }
  7754. if (!this.hasHandles() && segments.length === 4
  7755. && isCollinear(0, 2) && isCollinear(1, 3) && isOrthogonal(1)) {
  7756. type = Shape.Rectangle;
  7757. size = new Size(getDistance(0, 3), getDistance(0, 1));
  7758. topCenter = segments[1]._point.add(segments[2]._point).divide(2);
  7759. } else if (segments.length === 8 && isArc(0) && isArc(2) && isArc(4)
  7760. && isArc(6) && isCollinear(1, 5) && isCollinear(3, 7)) {
  7761. type = Shape.Rectangle;
  7762. size = new Size(getDistance(1, 6), getDistance(0, 3));
  7763. radius = size.subtract(new Size(getDistance(0, 7),
  7764. getDistance(1, 2))).divide(2);
  7765. topCenter = segments[3]._point.add(segments[4]._point).divide(2);
  7766. } else if (segments.length === 4
  7767. && isArc(0) && isArc(1) && isArc(2) && isArc(3)) {
  7768. if (Numerical.isZero(getDistance(0, 2) - getDistance(1, 3))) {
  7769. type = Shape.Circle;
  7770. radius = getDistance(0, 2) / 2;
  7771. } else {
  7772. type = Shape.Ellipse;
  7773. radius = new Size(getDistance(2, 0) / 2, getDistance(3, 1) / 2);
  7774. }
  7775. topCenter = segments[1]._point;
  7776. }
  7777. if (type) {
  7778. var center = this.getPosition(true),
  7779. shape = new type({
  7780. center: center,
  7781. size: size,
  7782. radius: radius,
  7783. insert: false
  7784. });
  7785. shape.copyAttributes(this, true);
  7786. shape._matrix.prepend(this._matrix);
  7787. shape.rotate(topCenter.subtract(center).getAngle() + 90);
  7788. if (insert === undefined || insert)
  7789. shape.insertAbove(this);
  7790. return shape;
  7791. }
  7792. return null;
  7793. },
  7794. toPath: '#clone',
  7795. compare: function compare(path) {
  7796. if (!path || path instanceof CompoundPath)
  7797. return compare.base.call(this, path);
  7798. var curves1 = this.getCurves(),
  7799. curves2 = path.getCurves(),
  7800. length1 = curves1.length,
  7801. length2 = curves2.length;
  7802. if (!length1 || !length2) {
  7803. return length1 == length2;
  7804. }
  7805. var v1 = curves1[0].getValues(),
  7806. values2 = [],
  7807. pos1 = 0, pos2,
  7808. end1 = 0, end2;
  7809. for (var i = 0; i < length2; i++) {
  7810. var v2 = curves2[i].getValues();
  7811. values2.push(v2);
  7812. var overlaps = Curve.getOverlaps(v1, v2);
  7813. if (overlaps) {
  7814. pos2 = !i && overlaps[0][0] > 0 ? length2 - 1 : i;
  7815. end2 = overlaps[0][1];
  7816. break;
  7817. }
  7818. }
  7819. var abs = Math.abs,
  7820. epsilon = 1e-8,
  7821. v2 = values2[pos2],
  7822. start2;
  7823. while (v1 && v2) {
  7824. var overlaps = Curve.getOverlaps(v1, v2);
  7825. if (overlaps) {
  7826. var t1 = overlaps[0][0];
  7827. if (abs(t1 - end1) < epsilon) {
  7828. end1 = overlaps[1][0];
  7829. if (end1 === 1) {
  7830. v1 = ++pos1 < length1 ? curves1[pos1].getValues() : null;
  7831. end1 = 0;
  7832. }
  7833. var t2 = overlaps[0][1];
  7834. if (abs(t2 - end2) < epsilon) {
  7835. if (!start2)
  7836. start2 = [pos2, t2];
  7837. end2 = overlaps[1][1];
  7838. if (end2 === 1) {
  7839. if (++pos2 >= length2)
  7840. pos2 = 0;
  7841. v2 = values2[pos2] || curves2[pos2].getValues();
  7842. end2 = 0;
  7843. }
  7844. if (!v1) {
  7845. return start2[0] === pos2 && start2[1] === end2;
  7846. }
  7847. continue;
  7848. }
  7849. }
  7850. }
  7851. break;
  7852. }
  7853. return false;
  7854. },
  7855. _hitTestSelf: function(point, options, viewMatrix, strokeMatrix) {
  7856. var that = this,
  7857. style = this.getStyle(),
  7858. segments = this._segments,
  7859. numSegments = segments.length,
  7860. closed = this._closed,
  7861. tolerancePadding = options._tolerancePadding,
  7862. strokePadding = tolerancePadding,
  7863. join, cap, miterLimit,
  7864. area, loc, res,
  7865. hitStroke = options.stroke && style.hasStroke(),
  7866. hitFill = options.fill && style.hasFill(),
  7867. hitCurves = options.curves,
  7868. strokeRadius = hitStroke
  7869. ? style.getStrokeWidth() / 2
  7870. : hitFill && options.tolerance > 0 || hitCurves
  7871. ? 0 : null;
  7872. if (strokeRadius !== null) {
  7873. if (strokeRadius > 0) {
  7874. join = style.getStrokeJoin();
  7875. cap = style.getStrokeCap();
  7876. miterLimit = style.getMiterLimit();
  7877. strokePadding = strokePadding.add(
  7878. Path._getStrokePadding(strokeRadius, strokeMatrix));
  7879. } else {
  7880. join = cap = 'round';
  7881. }
  7882. }
  7883. function isCloseEnough(pt, padding) {
  7884. return point.subtract(pt).divide(padding).length <= 1;
  7885. }
  7886. function checkSegmentPoint(seg, pt, name) {
  7887. if (!options.selected || pt.isSelected()) {
  7888. var anchor = seg._point;
  7889. if (pt !== anchor)
  7890. pt = pt.add(anchor);
  7891. if (isCloseEnough(pt, strokePadding)) {
  7892. return new HitResult(name, that, {
  7893. segment: seg,
  7894. point: pt
  7895. });
  7896. }
  7897. }
  7898. }
  7899. function checkSegmentPoints(seg, ends) {
  7900. return (ends || options.segments)
  7901. && checkSegmentPoint(seg, seg._point, 'segment')
  7902. || (!ends && options.handles) && (
  7903. checkSegmentPoint(seg, seg._handleIn, 'handle-in') ||
  7904. checkSegmentPoint(seg, seg._handleOut, 'handle-out'));
  7905. }
  7906. function addToArea(point) {
  7907. area.add(point);
  7908. }
  7909. function checkSegmentStroke(segment) {
  7910. var isJoin = closed || segment._index > 0
  7911. && segment._index < numSegments - 1;
  7912. if ((isJoin ? join : cap) === 'round') {
  7913. return isCloseEnough(segment._point, strokePadding);
  7914. } else {
  7915. area = new Path({ internal: true, closed: true });
  7916. if (isJoin) {
  7917. if (!segment.isSmooth()) {
  7918. Path._addBevelJoin(segment, join, strokeRadius,
  7919. miterLimit, null, strokeMatrix, addToArea, true);
  7920. }
  7921. } else if (cap === 'square') {
  7922. Path._addSquareCap(segment, cap, strokeRadius, null,
  7923. strokeMatrix, addToArea, true);
  7924. }
  7925. if (!area.isEmpty()) {
  7926. var loc;
  7927. return area.contains(point)
  7928. || (loc = area.getNearestLocation(point))
  7929. && isCloseEnough(loc.getPoint(), tolerancePadding);
  7930. }
  7931. }
  7932. }
  7933. if (options.ends && !options.segments && !closed) {
  7934. if (res = checkSegmentPoints(segments[0], true)
  7935. || checkSegmentPoints(segments[numSegments - 1], true))
  7936. return res;
  7937. } else if (options.segments || options.handles) {
  7938. for (var i = 0; i < numSegments; i++)
  7939. if (res = checkSegmentPoints(segments[i]))
  7940. return res;
  7941. }
  7942. if (strokeRadius !== null) {
  7943. loc = this.getNearestLocation(point);
  7944. if (loc) {
  7945. var time = loc.getTime();
  7946. if (time === 0 || time === 1 && numSegments > 1) {
  7947. if (!checkSegmentStroke(loc.getSegment()))
  7948. loc = null;
  7949. } else if (!isCloseEnough(loc.getPoint(), strokePadding)) {
  7950. loc = null;
  7951. }
  7952. }
  7953. if (!loc && join === 'miter' && numSegments > 1) {
  7954. for (var i = 0; i < numSegments; i++) {
  7955. var segment = segments[i];
  7956. if (point.getDistance(segment._point)
  7957. <= miterLimit * strokeRadius
  7958. && checkSegmentStroke(segment)) {
  7959. loc = segment.getLocation();
  7960. break;
  7961. }
  7962. }
  7963. }
  7964. }
  7965. return !loc && hitFill && this._contains(point)
  7966. || loc && !hitStroke && !hitCurves
  7967. ? new HitResult('fill', this)
  7968. : loc
  7969. ? new HitResult(hitStroke ? 'stroke' : 'curve', this, {
  7970. location: loc,
  7971. point: loc.getPoint()
  7972. })
  7973. : null;
  7974. }
  7975. }, Base.each(Curve._evaluateMethods,
  7976. function(name) {
  7977. this[name + 'At'] = function(offset) {
  7978. var loc = this.getLocationAt(offset);
  7979. return loc && loc[name]();
  7980. };
  7981. },
  7982. {
  7983. beans: false,
  7984. getLocationOf: function() {
  7985. var point = Point.read(arguments),
  7986. curves = this.getCurves();
  7987. for (var i = 0, l = curves.length; i < l; i++) {
  7988. var loc = curves[i].getLocationOf(point);
  7989. if (loc)
  7990. return loc;
  7991. }
  7992. return null;
  7993. },
  7994. getOffsetOf: function() {
  7995. var loc = this.getLocationOf.apply(this, arguments);
  7996. return loc ? loc.getOffset() : null;
  7997. },
  7998. getLocationAt: function(offset) {
  7999. if (typeof offset === 'number') {
  8000. var curves = this.getCurves(),
  8001. length = 0;
  8002. for (var i = 0, l = curves.length; i < l; i++) {
  8003. var start = length,
  8004. curve = curves[i];
  8005. length += curve.getLength();
  8006. if (length > offset) {
  8007. return curve.getLocationAt(offset - start);
  8008. }
  8009. }
  8010. if (curves.length > 0 && offset <= this.getLength()) {
  8011. return new CurveLocation(curves[curves.length - 1], 1);
  8012. }
  8013. } else if (offset && offset.getPath && offset.getPath() === this) {
  8014. return offset;
  8015. }
  8016. return null;
  8017. }
  8018. }),
  8019. new function() {
  8020. function drawHandles(ctx, segments, matrix, size) {
  8021. var half = size / 2,
  8022. coords = new Array(6),
  8023. pX, pY;
  8024. function drawHandle(index) {
  8025. var hX = coords[index],
  8026. hY = coords[index + 1];
  8027. if (pX != hX || pY != hY) {
  8028. ctx.beginPath();
  8029. ctx.moveTo(pX, pY);
  8030. ctx.lineTo(hX, hY);
  8031. ctx.stroke();
  8032. ctx.beginPath();
  8033. ctx.arc(hX, hY, half, 0, Math.PI * 2, true);
  8034. ctx.fill();
  8035. }
  8036. }
  8037. for (var i = 0, l = segments.length; i < l; i++) {
  8038. var segment = segments[i],
  8039. selection = segment._selection;
  8040. segment._transformCoordinates(matrix, coords);
  8041. pX = coords[0];
  8042. pY = coords[1];
  8043. if (selection & 2)
  8044. drawHandle(2);
  8045. if (selection & 4)
  8046. drawHandle(4);
  8047. ctx.fillRect(pX - half, pY - half, size, size);
  8048. if (!(selection & 1)) {
  8049. var fillStyle = ctx.fillStyle;
  8050. ctx.fillStyle = '#ffffff';
  8051. ctx.fillRect(pX - half + 1, pY - half + 1, size - 2, size - 2);
  8052. ctx.fillStyle = fillStyle;
  8053. }
  8054. }
  8055. }
  8056. function drawSegments(ctx, path, matrix) {
  8057. var segments = path._segments,
  8058. length = segments.length,
  8059. coords = new Array(6),
  8060. first = true,
  8061. curX, curY,
  8062. prevX, prevY,
  8063. inX, inY,
  8064. outX, outY;
  8065. function drawSegment(segment) {
  8066. if (matrix) {
  8067. segment._transformCoordinates(matrix, coords);
  8068. curX = coords[0];
  8069. curY = coords[1];
  8070. } else {
  8071. var point = segment._point;
  8072. curX = point._x;
  8073. curY = point._y;
  8074. }
  8075. if (first) {
  8076. ctx.moveTo(curX, curY);
  8077. first = false;
  8078. } else {
  8079. if (matrix) {
  8080. inX = coords[2];
  8081. inY = coords[3];
  8082. } else {
  8083. var handle = segment._handleIn;
  8084. inX = curX + handle._x;
  8085. inY = curY + handle._y;
  8086. }
  8087. if (inX === curX && inY === curY
  8088. && outX === prevX && outY === prevY) {
  8089. ctx.lineTo(curX, curY);
  8090. } else {
  8091. ctx.bezierCurveTo(outX, outY, inX, inY, curX, curY);
  8092. }
  8093. }
  8094. prevX = curX;
  8095. prevY = curY;
  8096. if (matrix) {
  8097. outX = coords[4];
  8098. outY = coords[5];
  8099. } else {
  8100. var handle = segment._handleOut;
  8101. outX = prevX + handle._x;
  8102. outY = prevY + handle._y;
  8103. }
  8104. }
  8105. for (var i = 0; i < length; i++)
  8106. drawSegment(segments[i]);
  8107. if (path._closed && length > 0)
  8108. drawSegment(segments[0]);
  8109. }
  8110. return {
  8111. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8112. var dontStart = param.dontStart,
  8113. dontPaint = param.dontFinish || param.clip,
  8114. style = this.getStyle(),
  8115. hasFill = style.hasFill(),
  8116. hasStroke = style.hasStroke(),
  8117. dashArray = style.getDashArray(),
  8118. dashLength = !paper.support.nativeDash && hasStroke
  8119. && dashArray && dashArray.length;
  8120. if (!dontStart)
  8121. ctx.beginPath();
  8122. if (hasFill || hasStroke && !dashLength || dontPaint) {
  8123. drawSegments(ctx, this, strokeMatrix);
  8124. if (this._closed)
  8125. ctx.closePath();
  8126. }
  8127. function getOffset(i) {
  8128. return dashArray[((i % dashLength) + dashLength) % dashLength];
  8129. }
  8130. if (!dontPaint && (hasFill || hasStroke)) {
  8131. this._setStyles(ctx, param, viewMatrix);
  8132. if (hasFill) {
  8133. ctx.fill(style.getFillRule());
  8134. ctx.shadowColor = 'rgba(0,0,0,0)';
  8135. }
  8136. if (hasStroke) {
  8137. if (dashLength) {
  8138. if (!dontStart)
  8139. ctx.beginPath();
  8140. var flattener = new PathFlattener(this, 0.25, 32, false,
  8141. strokeMatrix),
  8142. length = flattener.length,
  8143. from = -style.getDashOffset(), to,
  8144. i = 0;
  8145. from = from % length;
  8146. while (from > 0) {
  8147. from -= getOffset(i--) + getOffset(i--);
  8148. }
  8149. while (from < length) {
  8150. to = from + getOffset(i++);
  8151. if (from > 0 || to > 0)
  8152. flattener.drawPart(ctx,
  8153. Math.max(from, 0), Math.max(to, 0));
  8154. from = to + getOffset(i++);
  8155. }
  8156. }
  8157. ctx.stroke();
  8158. }
  8159. }
  8160. },
  8161. _drawSelected: function(ctx, matrix) {
  8162. ctx.beginPath();
  8163. drawSegments(ctx, this, matrix);
  8164. ctx.stroke();
  8165. drawHandles(ctx, this._segments, matrix, paper.settings.handleSize);
  8166. }
  8167. };
  8168. },
  8169. new function() {
  8170. function getCurrentSegment(that) {
  8171. var segments = that._segments;
  8172. if (!segments.length)
  8173. throw new Error('Use a moveTo() command first');
  8174. return segments[segments.length - 1];
  8175. }
  8176. return {
  8177. moveTo: function() {
  8178. var segments = this._segments;
  8179. if (segments.length === 1)
  8180. this.removeSegment(0);
  8181. if (!segments.length)
  8182. this._add([ new Segment(Point.read(arguments)) ]);
  8183. },
  8184. moveBy: function() {
  8185. throw new Error('moveBy() is unsupported on Path items.');
  8186. },
  8187. lineTo: function() {
  8188. this._add([ new Segment(Point.read(arguments)) ]);
  8189. },
  8190. cubicCurveTo: function() {
  8191. var handle1 = Point.read(arguments),
  8192. handle2 = Point.read(arguments),
  8193. to = Point.read(arguments),
  8194. current = getCurrentSegment(this);
  8195. current.setHandleOut(handle1.subtract(current._point));
  8196. this._add([ new Segment(to, handle2.subtract(to)) ]);
  8197. },
  8198. quadraticCurveTo: function() {
  8199. var handle = Point.read(arguments),
  8200. to = Point.read(arguments),
  8201. current = getCurrentSegment(this)._point;
  8202. this.cubicCurveTo(
  8203. handle.add(current.subtract(handle).multiply(1 / 3)),
  8204. handle.add(to.subtract(handle).multiply(1 / 3)),
  8205. to
  8206. );
  8207. },
  8208. curveTo: function() {
  8209. var through = Point.read(arguments),
  8210. to = Point.read(arguments),
  8211. t = Base.pick(Base.read(arguments), 0.5),
  8212. t1 = 1 - t,
  8213. current = getCurrentSegment(this)._point,
  8214. handle = through.subtract(current.multiply(t1 * t1))
  8215. .subtract(to.multiply(t * t)).divide(2 * t * t1);
  8216. if (handle.isNaN())
  8217. throw new Error(
  8218. 'Cannot put a curve through points with parameter = ' + t);
  8219. this.quadraticCurveTo(handle, to);
  8220. },
  8221. arcTo: function() {
  8222. var abs = Math.abs,
  8223. sqrt = Math.sqrt,
  8224. current = getCurrentSegment(this),
  8225. from = current._point,
  8226. to = Point.read(arguments),
  8227. through,
  8228. peek = Base.peek(arguments),
  8229. clockwise = Base.pick(peek, true),
  8230. center, extent, vector, matrix;
  8231. if (typeof clockwise === 'boolean') {
  8232. var middle = from.add(to).divide(2),
  8233. through = middle.add(middle.subtract(from).rotate(
  8234. clockwise ? -90 : 90));
  8235. } else if (Base.remain(arguments) <= 2) {
  8236. through = to;
  8237. to = Point.read(arguments);
  8238. } else {
  8239. var radius = Size.read(arguments),
  8240. isZero = Numerical.isZero;
  8241. if (isZero(radius.width) || isZero(radius.height))
  8242. return this.lineTo(to);
  8243. var rotation = Base.read(arguments),
  8244. clockwise = !!Base.read(arguments),
  8245. large = !!Base.read(arguments),
  8246. middle = from.add(to).divide(2),
  8247. pt = from.subtract(middle).rotate(-rotation),
  8248. x = pt.x,
  8249. y = pt.y,
  8250. rx = abs(radius.width),
  8251. ry = abs(radius.height),
  8252. rxSq = rx * rx,
  8253. rySq = ry * ry,
  8254. xSq = x * x,
  8255. ySq = y * y;
  8256. var factor = sqrt(xSq / rxSq + ySq / rySq);
  8257. if (factor > 1) {
  8258. rx *= factor;
  8259. ry *= factor;
  8260. rxSq = rx * rx;
  8261. rySq = ry * ry;
  8262. }
  8263. factor = (rxSq * rySq - rxSq * ySq - rySq * xSq) /
  8264. (rxSq * ySq + rySq * xSq);
  8265. if (abs(factor) < 1e-12)
  8266. factor = 0;
  8267. if (factor < 0)
  8268. throw new Error(
  8269. 'Cannot create an arc with the given arguments');
  8270. center = new Point(rx * y / ry, -ry * x / rx)
  8271. .multiply((large === clockwise ? -1 : 1) * sqrt(factor))
  8272. .rotate(rotation).add(middle);
  8273. matrix = new Matrix().translate(center).rotate(rotation)
  8274. .scale(rx, ry);
  8275. vector = matrix._inverseTransform(from);
  8276. extent = vector.getDirectedAngle(matrix._inverseTransform(to));
  8277. if (!clockwise && extent > 0)
  8278. extent -= 360;
  8279. else if (clockwise && extent < 0)
  8280. extent += 360;
  8281. }
  8282. if (through) {
  8283. var l1 = new Line(from.add(through).divide(2),
  8284. through.subtract(from).rotate(90), true),
  8285. l2 = new Line(through.add(to).divide(2),
  8286. to.subtract(through).rotate(90), true),
  8287. line = new Line(from, to),
  8288. throughSide = line.getSide(through);
  8289. center = l1.intersect(l2, true);
  8290. if (!center) {
  8291. if (!throughSide)
  8292. return this.lineTo(to);
  8293. throw new Error(
  8294. 'Cannot create an arc with the given arguments');
  8295. }
  8296. vector = from.subtract(center);
  8297. extent = vector.getDirectedAngle(to.subtract(center));
  8298. var centerSide = line.getSide(center);
  8299. if (centerSide === 0) {
  8300. extent = throughSide * abs(extent);
  8301. } else if (throughSide === centerSide) {
  8302. extent += extent < 0 ? 360 : -360;
  8303. }
  8304. }
  8305. var epsilon = 1e-7,
  8306. ext = abs(extent),
  8307. count = ext >= 360 ? 4 : Math.ceil((ext - epsilon) / 90),
  8308. inc = extent / count,
  8309. half = inc * Math.PI / 360,
  8310. z = 4 / 3 * Math.sin(half) / (1 + Math.cos(half)),
  8311. segments = [];
  8312. for (var i = 0; i <= count; i++) {
  8313. var pt = to,
  8314. out = null;
  8315. if (i < count) {
  8316. out = vector.rotate(90).multiply(z);
  8317. if (matrix) {
  8318. pt = matrix._transformPoint(vector);
  8319. out = matrix._transformPoint(vector.add(out))
  8320. .subtract(pt);
  8321. } else {
  8322. pt = center.add(vector);
  8323. }
  8324. }
  8325. if (!i) {
  8326. current.setHandleOut(out);
  8327. } else {
  8328. var _in = vector.rotate(-90).multiply(z);
  8329. if (matrix) {
  8330. _in = matrix._transformPoint(vector.add(_in))
  8331. .subtract(pt);
  8332. }
  8333. segments.push(new Segment(pt, _in, out));
  8334. }
  8335. vector = vector.rotate(inc);
  8336. }
  8337. this._add(segments);
  8338. },
  8339. lineBy: function() {
  8340. var to = Point.read(arguments),
  8341. current = getCurrentSegment(this)._point;
  8342. this.lineTo(current.add(to));
  8343. },
  8344. curveBy: function() {
  8345. var through = Point.read(arguments),
  8346. to = Point.read(arguments),
  8347. parameter = Base.read(arguments),
  8348. current = getCurrentSegment(this)._point;
  8349. this.curveTo(current.add(through), current.add(to), parameter);
  8350. },
  8351. cubicCurveBy: function() {
  8352. var handle1 = Point.read(arguments),
  8353. handle2 = Point.read(arguments),
  8354. to = Point.read(arguments),
  8355. current = getCurrentSegment(this)._point;
  8356. this.cubicCurveTo(current.add(handle1), current.add(handle2),
  8357. current.add(to));
  8358. },
  8359. quadraticCurveBy: function() {
  8360. var handle = Point.read(arguments),
  8361. to = Point.read(arguments),
  8362. current = getCurrentSegment(this)._point;
  8363. this.quadraticCurveTo(current.add(handle), current.add(to));
  8364. },
  8365. arcBy: function() {
  8366. var current = getCurrentSegment(this)._point,
  8367. point = current.add(Point.read(arguments)),
  8368. clockwise = Base.pick(Base.peek(arguments), true);
  8369. if (typeof clockwise === 'boolean') {
  8370. this.arcTo(point, clockwise);
  8371. } else {
  8372. this.arcTo(point, current.add(Point.read(arguments)));
  8373. }
  8374. },
  8375. closePath: function(tolerance) {
  8376. this.setClosed(true);
  8377. this.join(this, tolerance);
  8378. }
  8379. };
  8380. }, {
  8381. _getBounds: function(matrix, options) {
  8382. var method = options.handle
  8383. ? 'getHandleBounds'
  8384. : options.stroke
  8385. ? 'getStrokeBounds'
  8386. : 'getBounds';
  8387. return Path[method](this._segments, this._closed, this, matrix, options);
  8388. },
  8389. statics: {
  8390. getBounds: function(segments, closed, path, matrix, options, strokePadding) {
  8391. var first = segments[0];
  8392. if (!first)
  8393. return new Rectangle();
  8394. var coords = new Array(6),
  8395. prevCoords = first._transformCoordinates(matrix, new Array(6)),
  8396. min = prevCoords.slice(0, 2),
  8397. max = min.slice(),
  8398. roots = new Array(2);
  8399. function processSegment(segment) {
  8400. segment._transformCoordinates(matrix, coords);
  8401. for (var i = 0; i < 2; i++) {
  8402. Curve._addBounds(
  8403. prevCoords[i],
  8404. prevCoords[i + 4],
  8405. coords[i + 2],
  8406. coords[i],
  8407. i, strokePadding ? strokePadding[i] : 0, min, max, roots);
  8408. }
  8409. var tmp = prevCoords;
  8410. prevCoords = coords;
  8411. coords = tmp;
  8412. }
  8413. for (var i = 1, l = segments.length; i < l; i++)
  8414. processSegment(segments[i]);
  8415. if (closed)
  8416. processSegment(first);
  8417. return new Rectangle(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  8418. },
  8419. getStrokeBounds: function(segments, closed, path, matrix, options) {
  8420. var style = path.getStyle(),
  8421. stroke = style.hasStroke(),
  8422. strokeWidth = style.getStrokeWidth(),
  8423. strokeMatrix = stroke && path._getStrokeMatrix(matrix, options),
  8424. strokePadding = stroke && Path._getStrokePadding(strokeWidth,
  8425. strokeMatrix),
  8426. bounds = Path.getBounds(segments, closed, path, matrix, options,
  8427. strokePadding);
  8428. if (!stroke)
  8429. return bounds;
  8430. var strokeRadius = strokeWidth / 2,
  8431. join = style.getStrokeJoin(),
  8432. cap = style.getStrokeCap(),
  8433. miterLimit = style.getMiterLimit(),
  8434. joinBounds = new Rectangle(new Size(strokePadding));
  8435. function addPoint(point) {
  8436. bounds = bounds.include(point);
  8437. }
  8438. function addRound(segment) {
  8439. bounds = bounds.unite(
  8440. joinBounds.setCenter(segment._point.transform(matrix)));
  8441. }
  8442. function addJoin(segment, join) {
  8443. if (join === 'round' || segment.isSmooth()) {
  8444. addRound(segment);
  8445. } else {
  8446. Path._addBevelJoin(segment, join, strokeRadius, miterLimit,
  8447. matrix, strokeMatrix, addPoint);
  8448. }
  8449. }
  8450. function addCap(segment, cap) {
  8451. if (cap === 'round') {
  8452. addRound(segment);
  8453. } else {
  8454. Path._addSquareCap(segment, cap, strokeRadius, matrix,
  8455. strokeMatrix, addPoint);
  8456. }
  8457. }
  8458. var length = segments.length - (closed ? 0 : 1);
  8459. for (var i = 1; i < length; i++)
  8460. addJoin(segments[i], join);
  8461. if (closed) {
  8462. addJoin(segments[0], join);
  8463. } else if (length > 0) {
  8464. addCap(segments[0], cap);
  8465. addCap(segments[segments.length - 1], cap);
  8466. }
  8467. return bounds;
  8468. },
  8469. _getStrokePadding: function(radius, matrix) {
  8470. if (!matrix)
  8471. return [radius, radius];
  8472. var hor = new Point(radius, 0).transform(matrix),
  8473. ver = new Point(0, radius).transform(matrix),
  8474. phi = hor.getAngleInRadians(),
  8475. a = hor.getLength(),
  8476. b = ver.getLength();
  8477. var sin = Math.sin(phi),
  8478. cos = Math.cos(phi),
  8479. tan = Math.tan(phi),
  8480. tx = Math.atan2(b * tan, a),
  8481. ty = Math.atan2(b, tan * a);
  8482. return [Math.abs(a * Math.cos(tx) * cos + b * Math.sin(tx) * sin),
  8483. Math.abs(b * Math.sin(ty) * cos + a * Math.cos(ty) * sin)];
  8484. },
  8485. _addBevelJoin: function(segment, join, radius, miterLimit, matrix,
  8486. strokeMatrix, addPoint, isArea) {
  8487. var curve2 = segment.getCurve(),
  8488. curve1 = curve2.getPrevious(),
  8489. point = curve2.getPoint1().transform(matrix),
  8490. normal1 = curve1.getNormalAtTime(1).multiply(radius)
  8491. .transform(strokeMatrix),
  8492. normal2 = curve2.getNormalAtTime(0).multiply(radius)
  8493. .transform(strokeMatrix);
  8494. if (normal1.getDirectedAngle(normal2) < 0) {
  8495. normal1 = normal1.negate();
  8496. normal2 = normal2.negate();
  8497. }
  8498. if (isArea)
  8499. addPoint(point);
  8500. addPoint(point.add(normal1));
  8501. if (join === 'miter') {
  8502. var corner = new Line(point.add(normal1),
  8503. new Point(-normal1.y, normal1.x), true
  8504. ).intersect(new Line(point.add(normal2),
  8505. new Point(-normal2.y, normal2.x), true
  8506. ), true);
  8507. if (corner && point.getDistance(corner) <= miterLimit * radius) {
  8508. addPoint(corner);
  8509. }
  8510. }
  8511. addPoint(point.add(normal2));
  8512. },
  8513. _addSquareCap: function(segment, cap, radius, matrix, strokeMatrix,
  8514. addPoint, isArea) {
  8515. var point = segment._point.transform(matrix),
  8516. loc = segment.getLocation(),
  8517. normal = loc.getNormal()
  8518. .multiply(loc.getTime() === 0 ? radius : -radius)
  8519. .transform(strokeMatrix);
  8520. if (cap === 'square') {
  8521. if (isArea) {
  8522. addPoint(point.subtract(normal));
  8523. addPoint(point.add(normal));
  8524. }
  8525. point = point.add(normal.rotate(-90));
  8526. }
  8527. addPoint(point.add(normal));
  8528. addPoint(point.subtract(normal));
  8529. },
  8530. getHandleBounds: function(segments, closed, path, matrix, options) {
  8531. var style = path.getStyle(),
  8532. stroke = options.stroke && style.hasStroke(),
  8533. strokePadding,
  8534. joinPadding;
  8535. if (stroke) {
  8536. var strokeMatrix = path._getStrokeMatrix(matrix, options),
  8537. strokeRadius = style.getStrokeWidth() / 2,
  8538. joinRadius = strokeRadius;
  8539. if (style.getStrokeJoin() === 'miter')
  8540. joinRadius = strokeRadius * style.getMiterLimit();
  8541. if (style.getStrokeCap() === 'square')
  8542. joinRadius = Math.max(joinRadius, strokeRadius * Math.SQRT2);
  8543. strokePadding = Path._getStrokePadding(strokeRadius, strokeMatrix);
  8544. joinPadding = Path._getStrokePadding(joinRadius, strokeMatrix);
  8545. }
  8546. var coords = new Array(6),
  8547. x1 = Infinity,
  8548. x2 = -x1,
  8549. y1 = x1,
  8550. y2 = x2;
  8551. for (var i = 0, l = segments.length; i < l; i++) {
  8552. var segment = segments[i];
  8553. segment._transformCoordinates(matrix, coords);
  8554. for (var j = 0; j < 6; j += 2) {
  8555. var padding = !j ? joinPadding : strokePadding,
  8556. paddingX = padding ? padding[0] : 0,
  8557. paddingY = padding ? padding[1] : 0,
  8558. x = coords[j],
  8559. y = coords[j + 1],
  8560. xn = x - paddingX,
  8561. xx = x + paddingX,
  8562. yn = y - paddingY,
  8563. yx = y + paddingY;
  8564. if (xn < x1) x1 = xn;
  8565. if (xx > x2) x2 = xx;
  8566. if (yn < y1) y1 = yn;
  8567. if (yx > y2) y2 = yx;
  8568. }
  8569. }
  8570. return new Rectangle(x1, y1, x2 - x1, y2 - y1);
  8571. }
  8572. }});
  8573. Path.inject({ statics: new function() {
  8574. var kappa = 0.5522847498307936,
  8575. ellipseSegments = [
  8576. new Segment([-1, 0], [0, kappa ], [0, -kappa]),
  8577. new Segment([0, -1], [-kappa, 0], [kappa, 0 ]),
  8578. new Segment([1, 0], [0, -kappa], [0, kappa ]),
  8579. new Segment([0, 1], [kappa, 0 ], [-kappa, 0])
  8580. ];
  8581. function createPath(segments, closed, args) {
  8582. var props = Base.getNamed(args),
  8583. path = new Path(props && props.insert == false && Item.NO_INSERT);
  8584. path._add(segments);
  8585. path._closed = closed;
  8586. return path.set(props, { insert: true });
  8587. }
  8588. function createEllipse(center, radius, args) {
  8589. var segments = new Array(4);
  8590. for (var i = 0; i < 4; i++) {
  8591. var segment = ellipseSegments[i];
  8592. segments[i] = new Segment(
  8593. segment._point.multiply(radius).add(center),
  8594. segment._handleIn.multiply(radius),
  8595. segment._handleOut.multiply(radius)
  8596. );
  8597. }
  8598. return createPath(segments, true, args);
  8599. }
  8600. return {
  8601. Line: function() {
  8602. return createPath([
  8603. new Segment(Point.readNamed(arguments, 'from')),
  8604. new Segment(Point.readNamed(arguments, 'to'))
  8605. ], false, arguments);
  8606. },
  8607. Circle: function() {
  8608. var center = Point.readNamed(arguments, 'center'),
  8609. radius = Base.readNamed(arguments, 'radius');
  8610. return createEllipse(center, new Size(radius), arguments);
  8611. },
  8612. Rectangle: function() {
  8613. var rect = Rectangle.readNamed(arguments, 'rectangle'),
  8614. radius = Size.readNamed(arguments, 'radius', 0,
  8615. { readNull: true }),
  8616. bl = rect.getBottomLeft(true),
  8617. tl = rect.getTopLeft(true),
  8618. tr = rect.getTopRight(true),
  8619. br = rect.getBottomRight(true),
  8620. segments;
  8621. if (!radius || radius.isZero()) {
  8622. segments = [
  8623. new Segment(bl),
  8624. new Segment(tl),
  8625. new Segment(tr),
  8626. new Segment(br)
  8627. ];
  8628. } else {
  8629. radius = Size.min(radius, rect.getSize(true).divide(2));
  8630. var rx = radius.width,
  8631. ry = radius.height,
  8632. hx = rx * kappa,
  8633. hy = ry * kappa;
  8634. segments = [
  8635. new Segment(bl.add(rx, 0), null, [-hx, 0]),
  8636. new Segment(bl.subtract(0, ry), [0, hy]),
  8637. new Segment(tl.add(0, ry), null, [0, -hy]),
  8638. new Segment(tl.add(rx, 0), [-hx, 0], null),
  8639. new Segment(tr.subtract(rx, 0), null, [hx, 0]),
  8640. new Segment(tr.add(0, ry), [0, -hy], null),
  8641. new Segment(br.subtract(0, ry), null, [0, hy]),
  8642. new Segment(br.subtract(rx, 0), [hx, 0])
  8643. ];
  8644. }
  8645. return createPath(segments, true, arguments);
  8646. },
  8647. RoundRectangle: '#Rectangle',
  8648. Ellipse: function() {
  8649. var ellipse = Shape._readEllipse(arguments);
  8650. return createEllipse(ellipse.center, ellipse.radius, arguments);
  8651. },
  8652. Oval: '#Ellipse',
  8653. Arc: function() {
  8654. var from = Point.readNamed(arguments, 'from'),
  8655. through = Point.readNamed(arguments, 'through'),
  8656. to = Point.readNamed(arguments, 'to'),
  8657. props = Base.getNamed(arguments),
  8658. path = new Path(props && props.insert == false
  8659. && Item.NO_INSERT);
  8660. path.moveTo(from);
  8661. path.arcTo(through, to);
  8662. return path.set(props);
  8663. },
  8664. RegularPolygon: function() {
  8665. var center = Point.readNamed(arguments, 'center'),
  8666. sides = Base.readNamed(arguments, 'sides'),
  8667. radius = Base.readNamed(arguments, 'radius'),
  8668. step = 360 / sides,
  8669. three = sides % 3 === 0,
  8670. vector = new Point(0, three ? -radius : radius),
  8671. offset = three ? -1 : 0.5,
  8672. segments = new Array(sides);
  8673. for (var i = 0; i < sides; i++)
  8674. segments[i] = new Segment(center.add(
  8675. vector.rotate((i + offset) * step)));
  8676. return createPath(segments, true, arguments);
  8677. },
  8678. Star: function() {
  8679. var center = Point.readNamed(arguments, 'center'),
  8680. points = Base.readNamed(arguments, 'points') * 2,
  8681. radius1 = Base.readNamed(arguments, 'radius1'),
  8682. radius2 = Base.readNamed(arguments, 'radius2'),
  8683. step = 360 / points,
  8684. vector = new Point(0, -1),
  8685. segments = new Array(points);
  8686. for (var i = 0; i < points; i++)
  8687. segments[i] = new Segment(center.add(vector.rotate(step * i)
  8688. .multiply(i % 2 ? radius2 : radius1)));
  8689. return createPath(segments, true, arguments);
  8690. }
  8691. };
  8692. }});
  8693. var CompoundPath = PathItem.extend({
  8694. _class: 'CompoundPath',
  8695. _serializeFields: {
  8696. children: []
  8697. },
  8698. beans: true,
  8699. initialize: function CompoundPath(arg) {
  8700. this._children = [];
  8701. this._namedChildren = {};
  8702. if (!this._initialize(arg)) {
  8703. if (typeof arg === 'string') {
  8704. this.setPathData(arg);
  8705. } else {
  8706. this.addChildren(Array.isArray(arg) ? arg : arguments);
  8707. }
  8708. }
  8709. },
  8710. insertChildren: function insertChildren(index, items) {
  8711. var list = items,
  8712. first = list[0];
  8713. if (first && typeof first[0] === 'number')
  8714. list = [list];
  8715. for (var i = items.length - 1; i >= 0; i--) {
  8716. var item = list[i];
  8717. if (list === items && !(item instanceof Path))
  8718. list = Base.slice(list);
  8719. if (Array.isArray(item)) {
  8720. list[i] = new Path({ segments: item, insert: false });
  8721. } else if (item instanceof CompoundPath) {
  8722. list.splice.apply(list, [i, 1].concat(item.removeChildren()));
  8723. item.remove();
  8724. }
  8725. }
  8726. return insertChildren.base.call(this, index, list);
  8727. },
  8728. reduce: function reduce(options) {
  8729. var children = this._children;
  8730. for (var i = children.length - 1; i >= 0; i--) {
  8731. var path = children[i].reduce(options);
  8732. if (path.isEmpty())
  8733. path.remove();
  8734. }
  8735. if (!children.length) {
  8736. var path = new Path(Item.NO_INSERT);
  8737. path.copyAttributes(this);
  8738. path.insertAbove(this);
  8739. this.remove();
  8740. return path;
  8741. }
  8742. return reduce.base.call(this);
  8743. },
  8744. isClosed: function() {
  8745. var children = this._children;
  8746. for (var i = 0, l = children.length; i < l; i++) {
  8747. if (!children[i]._closed)
  8748. return false;
  8749. }
  8750. return true;
  8751. },
  8752. setClosed: function(closed) {
  8753. var children = this._children;
  8754. for (var i = 0, l = children.length; i < l; i++) {
  8755. children[i].setClosed(closed);
  8756. }
  8757. },
  8758. getFirstSegment: function() {
  8759. var first = this.getFirstChild();
  8760. return first && first.getFirstSegment();
  8761. },
  8762. getLastSegment: function() {
  8763. var last = this.getLastChild();
  8764. return last && last.getLastSegment();
  8765. },
  8766. getCurves: function() {
  8767. var children = this._children,
  8768. curves = [];
  8769. for (var i = 0, l = children.length; i < l; i++)
  8770. curves.push.apply(curves, children[i].getCurves());
  8771. return curves;
  8772. },
  8773. getFirstCurve: function() {
  8774. var first = this.getFirstChild();
  8775. return first && first.getFirstCurve();
  8776. },
  8777. getLastCurve: function() {
  8778. var last = this.getLastChild();
  8779. return last && last.getLastCurve();
  8780. },
  8781. getArea: function() {
  8782. var children = this._children,
  8783. area = 0;
  8784. for (var i = 0, l = children.length; i < l; i++)
  8785. area += children[i].getArea();
  8786. return area;
  8787. },
  8788. getLength: function() {
  8789. var children = this._children,
  8790. length = 0;
  8791. for (var i = 0, l = children.length; i < l; i++)
  8792. length += children[i].getLength();
  8793. return length;
  8794. },
  8795. getPathData: function(_matrix, _precision) {
  8796. var children = this._children,
  8797. paths = [];
  8798. for (var i = 0, l = children.length; i < l; i++) {
  8799. var child = children[i],
  8800. mx = child._matrix;
  8801. paths.push(child.getPathData(_matrix && !mx.isIdentity()
  8802. ? _matrix.appended(mx) : _matrix, _precision));
  8803. }
  8804. return paths.join('');
  8805. },
  8806. _hitTestChildren: function _hitTestChildren(point, options, viewMatrix) {
  8807. return _hitTestChildren.base.call(this, point,
  8808. options.class === Path || options.type === 'path' ? options
  8809. : Base.set({}, options, { fill: false }),
  8810. viewMatrix);
  8811. },
  8812. _draw: function(ctx, param, viewMatrix, strokeMatrix) {
  8813. var children = this._children;
  8814. if (!children.length)
  8815. return;
  8816. param = param.extend({ dontStart: true, dontFinish: true });
  8817. ctx.beginPath();
  8818. for (var i = 0, l = children.length; i < l; i++)
  8819. children[i].draw(ctx, param, strokeMatrix);
  8820. if (!param.clip) {
  8821. this._setStyles(ctx, param, viewMatrix);
  8822. var style = this._style;
  8823. if (style.hasFill()) {
  8824. ctx.fill(style.getFillRule());
  8825. ctx.shadowColor = 'rgba(0,0,0,0)';
  8826. }
  8827. if (style.hasStroke())
  8828. ctx.stroke();
  8829. }
  8830. },
  8831. _drawSelected: function(ctx, matrix, selectionItems) {
  8832. var children = this._children;
  8833. for (var i = 0, l = children.length; i < l; i++) {
  8834. var child = children[i],
  8835. mx = child._matrix;
  8836. if (!selectionItems[child._id]) {
  8837. child._drawSelected(ctx, mx.isIdentity() ? matrix
  8838. : matrix.appended(mx));
  8839. }
  8840. }
  8841. }
  8842. },
  8843. new function() {
  8844. function getCurrentPath(that, check) {
  8845. var children = that._children;
  8846. if (check && !children.length)
  8847. throw new Error('Use a moveTo() command first');
  8848. return children[children.length - 1];
  8849. }
  8850. return Base.each(['lineTo', 'cubicCurveTo', 'quadraticCurveTo', 'curveTo',
  8851. 'arcTo', 'lineBy', 'cubicCurveBy', 'quadraticCurveBy', 'curveBy',
  8852. 'arcBy'],
  8853. function(key) {
  8854. this[key] = function() {
  8855. var path = getCurrentPath(this, true);
  8856. path[key].apply(path, arguments);
  8857. };
  8858. }, {
  8859. moveTo: function() {
  8860. var current = getCurrentPath(this),
  8861. path = current && current.isEmpty() ? current
  8862. : new Path(Item.NO_INSERT);
  8863. if (path !== current)
  8864. this.addChild(path);
  8865. path.moveTo.apply(path, arguments);
  8866. },
  8867. moveBy: function() {
  8868. var current = getCurrentPath(this, true),
  8869. last = current && current.getLastSegment(),
  8870. point = Point.read(arguments);
  8871. this.moveTo(last ? point.add(last._point) : point);
  8872. },
  8873. closePath: function(tolerance) {
  8874. getCurrentPath(this, true).closePath(tolerance);
  8875. }
  8876. }
  8877. );
  8878. }, Base.each(['reverse', 'flatten', 'simplify', 'smooth'], function(key) {
  8879. this[key] = function(param) {
  8880. var children = this._children,
  8881. res;
  8882. for (var i = 0, l = children.length; i < l; i++) {
  8883. res = children[i][key](param) || res;
  8884. }
  8885. return res;
  8886. };
  8887. }, {}));
  8888. PathItem.inject(new function() {
  8889. var min = Math.min,
  8890. max = Math.max,
  8891. abs = Math.abs,
  8892. operators = {
  8893. unite: { '1': true, '2': true },
  8894. intersect: { '2': true },
  8895. subtract: { '1': true },
  8896. exclude: { '1': true, '-1': true }
  8897. };
  8898. function preparePath(path, resolve) {
  8899. var res = path.clone(false).reduce({ simplify: true })
  8900. .transform(null, true, true);
  8901. return resolve
  8902. ? res.resolveCrossings().reorient(
  8903. res.getFillRule() === 'nonzero', true)
  8904. : res;
  8905. }
  8906. function createResult(paths, simplify, path1, path2, options) {
  8907. var result = new CompoundPath(Item.NO_INSERT);
  8908. result.addChildren(paths, true);
  8909. result = result.reduce({ simplify: simplify });
  8910. if (!(options && options.insert == false)) {
  8911. result.insertAbove(path2 && path1.isSibling(path2)
  8912. && path1.getIndex() < path2.getIndex() ? path2 : path1);
  8913. }
  8914. result.copyAttributes(path1, true);
  8915. return result;
  8916. }
  8917. function traceBoolean(path1, path2, operation, options) {
  8918. if (options && (options.trace == false || options.stroke) &&
  8919. /^(subtract|intersect)$/.test(operation))
  8920. return splitBoolean(path1, path2, operation);
  8921. var _path1 = preparePath(path1, true),
  8922. _path2 = path2 && path1 !== path2 && preparePath(path2, true),
  8923. operator = operators[operation];
  8924. operator[operation] = true;
  8925. if (_path2 && (operator.subtract || operator.exclude)
  8926. ^ (_path2.isClockwise() ^ _path1.isClockwise()))
  8927. _path2.reverse();
  8928. var crossings = divideLocations(
  8929. CurveLocation.expand(_path1.getCrossings(_path2))),
  8930. paths1 = _path1._children || [_path1],
  8931. paths2 = _path2 && (_path2._children || [_path2]),
  8932. segments = [],
  8933. curves = [],
  8934. paths;
  8935. function collect(paths) {
  8936. for (var i = 0, l = paths.length; i < l; i++) {
  8937. var path = paths[i];
  8938. segments.push.apply(segments, path._segments);
  8939. curves.push.apply(curves, path.getCurves());
  8940. path._overlapsOnly = true;
  8941. }
  8942. }
  8943. if (crossings.length) {
  8944. collect(paths1);
  8945. if (paths2)
  8946. collect(paths2);
  8947. for (var i = 0, l = crossings.length; i < l; i++) {
  8948. propagateWinding(crossings[i]._segment, _path1, _path2, curves,
  8949. operator);
  8950. }
  8951. for (var i = 0, l = segments.length; i < l; i++) {
  8952. var segment = segments[i],
  8953. inter = segment._intersection;
  8954. if (!segment._winding) {
  8955. propagateWinding(segment, _path1, _path2, curves, operator);
  8956. }
  8957. if (!(inter && inter._overlap))
  8958. segment._path._overlapsOnly = false;
  8959. }
  8960. paths = tracePaths(segments, operator);
  8961. } else {
  8962. paths = reorientPaths(
  8963. paths2 ? paths1.concat(paths2) : paths1.slice(),
  8964. function(w) {
  8965. return !!operator[w];
  8966. });
  8967. }
  8968. return createResult(paths, true, path1, path2, options);
  8969. }
  8970. function splitBoolean(path1, path2, operation) {
  8971. var _path1 = preparePath(path1),
  8972. _path2 = preparePath(path2),
  8973. crossings = _path1.getCrossings(_path2),
  8974. subtract = operation === 'subtract',
  8975. divide = operation === 'divide',
  8976. added = {},
  8977. paths = [];
  8978. function addPath(path) {
  8979. if (!added[path._id] && (divide ||
  8980. _path2.contains(path.getPointAt(path.getLength() / 2))
  8981. ^ subtract)) {
  8982. paths.unshift(path);
  8983. return added[path._id] = true;
  8984. }
  8985. }
  8986. for (var i = crossings.length - 1; i >= 0; i--) {
  8987. var path = crossings[i].split();
  8988. if (path) {
  8989. if (addPath(path))
  8990. path.getFirstSegment().setHandleIn(0, 0);
  8991. _path1.getLastSegment().setHandleOut(0, 0);
  8992. }
  8993. }
  8994. addPath(_path1);
  8995. return createResult(paths, false, path1, path2);
  8996. }
  8997. function linkIntersections(from, to) {
  8998. var prev = from;
  8999. while (prev) {
  9000. if (prev === to)
  9001. return;
  9002. prev = prev._previous;
  9003. }
  9004. while (from._next && from._next !== to)
  9005. from = from._next;
  9006. if (!from._next) {
  9007. while (to._previous)
  9008. to = to._previous;
  9009. from._next = to;
  9010. to._previous = from;
  9011. }
  9012. }
  9013. function clearCurveHandles(curves) {
  9014. for (var i = curves.length - 1; i >= 0; i--)
  9015. curves[i].clearHandles();
  9016. }
  9017. function reorientPaths(paths, isInside, clockwise) {
  9018. var length = paths && paths.length;
  9019. if (length) {
  9020. var lookup = Base.each(paths, function (path, i) {
  9021. this[path._id] = {
  9022. container: null,
  9023. winding: path.isClockwise() ? 1 : -1,
  9024. index: i
  9025. };
  9026. }, {}),
  9027. sorted = paths.slice().sort(function (a, b) {
  9028. return abs(b.getArea()) - abs(a.getArea());
  9029. }),
  9030. first = sorted[0];
  9031. if (clockwise == null)
  9032. clockwise = first.isClockwise();
  9033. for (var i = 0; i < length; i++) {
  9034. var path1 = sorted[i],
  9035. entry1 = lookup[path1._id],
  9036. point = path1.getInteriorPoint(),
  9037. containerWinding = 0;
  9038. for (var j = i - 1; j >= 0; j--) {
  9039. var path2 = sorted[j];
  9040. if (path2.contains(point)) {
  9041. var entry2 = lookup[path2._id];
  9042. containerWinding = entry2.winding;
  9043. entry1.winding += containerWinding;
  9044. entry1.container = entry2.exclude ? entry2.container
  9045. : path2;
  9046. break;
  9047. }
  9048. }
  9049. if (isInside(entry1.winding) === isInside(containerWinding)) {
  9050. entry1.exclude = true;
  9051. paths[entry1.index] = null;
  9052. } else {
  9053. var container = entry1.container;
  9054. path1.setClockwise(container ? !container.isClockwise()
  9055. : clockwise);
  9056. }
  9057. }
  9058. }
  9059. return paths;
  9060. }
  9061. function divideLocations(locations, include, clearLater) {
  9062. var results = include && [],
  9063. tMin = 1e-8,
  9064. tMax = 1 - tMin,
  9065. clearHandles = false,
  9066. clearCurves = clearLater || [],
  9067. clearLookup = clearLater && {},
  9068. renormalizeLocs,
  9069. prevCurve,
  9070. prevTime;
  9071. function getId(curve) {
  9072. return curve._path._id + '.' + curve._segment1._index;
  9073. }
  9074. for (var i = (clearLater && clearLater.length) - 1; i >= 0; i--) {
  9075. var curve = clearLater[i];
  9076. if (curve._path)
  9077. clearLookup[getId(curve)] = true;
  9078. }
  9079. for (var i = locations.length - 1; i >= 0; i--) {
  9080. var loc = locations[i],
  9081. time = loc._time,
  9082. origTime = time,
  9083. exclude = include && !include(loc),
  9084. curve = loc._curve,
  9085. segment;
  9086. if (curve) {
  9087. if (curve !== prevCurve) {
  9088. clearHandles = !curve.hasHandles()
  9089. || clearLookup && clearLookup[getId(curve)];
  9090. renormalizeLocs = [];
  9091. prevTime = null;
  9092. prevCurve = curve;
  9093. } else if (prevTime >= tMin) {
  9094. time /= prevTime;
  9095. }
  9096. }
  9097. if (exclude) {
  9098. if (renormalizeLocs)
  9099. renormalizeLocs.push(loc);
  9100. continue;
  9101. } else if (include) {
  9102. results.unshift(loc);
  9103. }
  9104. prevTime = origTime;
  9105. if (time < tMin) {
  9106. segment = curve._segment1;
  9107. } else if (time > tMax) {
  9108. segment = curve._segment2;
  9109. } else {
  9110. var newCurve = curve.divideAtTime(time, true);
  9111. if (clearHandles)
  9112. clearCurves.push(curve, newCurve);
  9113. segment = newCurve._segment1;
  9114. for (var j = renormalizeLocs.length - 1; j >= 0; j--) {
  9115. var l = renormalizeLocs[j];
  9116. l._time = (l._time - time) / (1 - time);
  9117. }
  9118. }
  9119. loc._setSegment(segment);
  9120. var inter = segment._intersection,
  9121. dest = loc._intersection;
  9122. if (inter) {
  9123. linkIntersections(inter, dest);
  9124. var other = inter;
  9125. while (other) {
  9126. linkIntersections(other._intersection, inter);
  9127. other = other._next;
  9128. }
  9129. } else {
  9130. segment._intersection = dest;
  9131. }
  9132. }
  9133. if (!clearLater)
  9134. clearCurveHandles(clearCurves);
  9135. return results || locations;
  9136. }
  9137. function getWinding(point, curves, dir, closed, dontFlip) {
  9138. var ia = dir ? 1 : 0,
  9139. io = ia ^ 1,
  9140. pv = [point.x, point.y],
  9141. pa = pv[ia],
  9142. po = pv[io],
  9143. windingEpsilon = 1e-9,
  9144. qualityEpsilon = 1e-6,
  9145. paL = pa - windingEpsilon,
  9146. paR = pa + windingEpsilon,
  9147. windingL = 0,
  9148. windingR = 0,
  9149. pathWindingL = 0,
  9150. pathWindingR = 0,
  9151. onPath = false,
  9152. onAnyPath = false,
  9153. quality = 1,
  9154. roots = [],
  9155. vPrev,
  9156. vClose;
  9157. function addWinding(v) {
  9158. var o0 = v[io + 0],
  9159. o3 = v[io + 6];
  9160. if (po < min(o0, o3) || po > max(o0, o3)) {
  9161. return;
  9162. }
  9163. var a0 = v[ia + 0],
  9164. a1 = v[ia + 2],
  9165. a2 = v[ia + 4],
  9166. a3 = v[ia + 6];
  9167. if (o0 === o3) {
  9168. if (a0 < paR && a3 > paL || a3 < paR && a0 > paL) {
  9169. onPath = true;
  9170. }
  9171. return;
  9172. }
  9173. var t = po === o0 ? 0
  9174. : po === o3 ? 1
  9175. : paL > max(a0, a1, a2, a3) || paR < min(a0, a1, a2, a3)
  9176. ? 1
  9177. : Curve.solveCubic(v, io, po, roots, 0, 1) > 0
  9178. ? roots[0]
  9179. : 1,
  9180. a = t === 0 ? a0
  9181. : t === 1 ? a3
  9182. : Curve.getPoint(v, t)[dir ? 'y' : 'x'],
  9183. winding = o0 > o3 ? 1 : -1,
  9184. windingPrev = vPrev[io] > vPrev[io + 6] ? 1 : -1,
  9185. a3Prev = vPrev[ia + 6];
  9186. if (po !== o0) {
  9187. if (a < paL) {
  9188. pathWindingL += winding;
  9189. } else if (a > paR) {
  9190. pathWindingR += winding;
  9191. } else {
  9192. onPath = true;
  9193. }
  9194. if (a > pa - qualityEpsilon && a < pa + qualityEpsilon)
  9195. quality /= 2;
  9196. } else {
  9197. if (winding !== windingPrev) {
  9198. if (a0 < paL) {
  9199. pathWindingL += winding;
  9200. } else if (a0 > paR) {
  9201. pathWindingR += winding;
  9202. }
  9203. } else if (a0 != a3Prev) {
  9204. if (a3Prev < paR && a > paR) {
  9205. pathWindingR += winding;
  9206. onPath = true;
  9207. } else if (a3Prev > paL && a < paL) {
  9208. pathWindingL += winding;
  9209. onPath = true;
  9210. }
  9211. }
  9212. quality = 0;
  9213. }
  9214. vPrev = v;
  9215. return !dontFlip && a > paL && a < paR
  9216. && Curve.getTangent(v, t)[dir ? 'x' : 'y'] === 0
  9217. && getWinding(point, curves, !dir, closed, true);
  9218. }
  9219. function handleCurve(v) {
  9220. var o0 = v[io + 0],
  9221. o1 = v[io + 2],
  9222. o2 = v[io + 4],
  9223. o3 = v[io + 6];
  9224. if (po <= max(o0, o1, o2, o3) && po >= min(o0, o1, o2, o3)) {
  9225. var a0 = v[ia + 0],
  9226. a1 = v[ia + 2],
  9227. a2 = v[ia + 4],
  9228. a3 = v[ia + 6],
  9229. monoCurves = paL > max(a0, a1, a2, a3) ||
  9230. paR < min(a0, a1, a2, a3)
  9231. ? [v] : Curve.getMonoCurves(v, dir),
  9232. res;
  9233. for (var i = 0, l = monoCurves.length; i < l; i++) {
  9234. if (res = addWinding(monoCurves[i]))
  9235. return res;
  9236. }
  9237. }
  9238. }
  9239. for (var i = 0, l = curves.length; i < l; i++) {
  9240. var curve = curves[i],
  9241. path = curve._path,
  9242. v = curve.getValues(),
  9243. res;
  9244. if (!i || curves[i - 1]._path !== path) {
  9245. vPrev = null;
  9246. if (!path._closed) {
  9247. vClose = Curve.getValues(
  9248. path.getLastCurve().getSegment2(),
  9249. curve.getSegment1(),
  9250. null, !closed);
  9251. if (vClose[io] !== vClose[io + 6]) {
  9252. vPrev = vClose;
  9253. }
  9254. }
  9255. if (!vPrev) {
  9256. vPrev = v;
  9257. var prev = path.getLastCurve();
  9258. while (prev && prev !== curve) {
  9259. var v2 = prev.getValues();
  9260. if (v2[io] !== v2[io + 6]) {
  9261. vPrev = v2;
  9262. break;
  9263. }
  9264. prev = prev.getPrevious();
  9265. }
  9266. }
  9267. }
  9268. if (res = handleCurve(v))
  9269. return res;
  9270. if (i + 1 === l || curves[i + 1]._path !== path) {
  9271. if (vClose && (res = handleCurve(vClose)))
  9272. return res;
  9273. if (onPath && !pathWindingL && !pathWindingR) {
  9274. pathWindingL = pathWindingR = path.isClockwise(closed) ^ dir
  9275. ? 1 : -1;
  9276. }
  9277. windingL += pathWindingL;
  9278. windingR += pathWindingR;
  9279. pathWindingL = pathWindingR = 0;
  9280. if (onPath) {
  9281. onAnyPath = true;
  9282. onPath = false;
  9283. }
  9284. vClose = null;
  9285. }
  9286. }
  9287. windingL = abs(windingL);
  9288. windingR = abs(windingR);
  9289. return {
  9290. winding: max(windingL, windingR),
  9291. windingL: windingL,
  9292. windingR: windingR,
  9293. quality: quality,
  9294. onPath: onAnyPath
  9295. };
  9296. }
  9297. function propagateWinding(segment, path1, path2, curves, operator) {
  9298. var chain = [],
  9299. start = segment,
  9300. totalLength = 0,
  9301. winding;
  9302. do {
  9303. var curve = segment.getCurve(),
  9304. length = curve.getLength();
  9305. chain.push({ segment: segment, curve: curve, length: length });
  9306. totalLength += length;
  9307. segment = segment.getNext();
  9308. } while (segment && !segment._intersection && segment !== start);
  9309. var offsets = [0.5, 0.25, 0.75],
  9310. winding = { winding: 0, quality: -1 },
  9311. tMin = 1e-8,
  9312. tMax = 1 - tMin;
  9313. for (var i = 0; i < offsets.length && winding.quality < 0.5; i++) {
  9314. var length = totalLength * offsets[i];
  9315. for (var j = 0, l = chain.length; j < l; j++) {
  9316. var entry = chain[j],
  9317. curveLength = entry.length;
  9318. if (length <= curveLength) {
  9319. var curve = entry.curve,
  9320. path = curve._path,
  9321. parent = path._parent,
  9322. operand = parent instanceof CompoundPath ? parent : path,
  9323. t = Numerical.clamp(curve.getTimeAt(length), tMin, tMax),
  9324. pt = curve.getPointAtTime(t),
  9325. dir = abs(curve.getTangentAtTime(t).y) < Math.SQRT1_2;
  9326. var wind = !(operator.subtract && path2 && (
  9327. operand === path1 &&
  9328. path2._getWinding(pt, dir, true).winding ||
  9329. operand === path2 &&
  9330. !path1._getWinding(pt, dir, true).winding))
  9331. ? getWinding(pt, curves, dir, true)
  9332. : { winding: 0, quality: 1 };
  9333. if (wind.quality > winding.quality)
  9334. winding = wind;
  9335. break;
  9336. }
  9337. length -= curveLength;
  9338. }
  9339. }
  9340. for (var j = chain.length - 1; j >= 0; j--) {
  9341. chain[j].segment._winding = winding;
  9342. }
  9343. }
  9344. function tracePaths(segments, operator) {
  9345. var paths = [],
  9346. starts;
  9347. function isValid(seg) {
  9348. var winding;
  9349. return !!(seg && !seg._visited && (!operator
  9350. || operator[(winding = seg._winding || {}).winding]
  9351. && !(operator.unite && winding.winding === 2
  9352. && winding.windingL && winding.windingR)));
  9353. }
  9354. function isStart(seg) {
  9355. if (seg) {
  9356. for (var i = 0, l = starts.length; i < l; i++) {
  9357. if (seg === starts[i])
  9358. return true;
  9359. }
  9360. }
  9361. return false;
  9362. }
  9363. function visitPath(path) {
  9364. var segments = path._segments;
  9365. for (var i = 0, l = segments.length; i < l; i++) {
  9366. segments[i]._visited = true;
  9367. }
  9368. }
  9369. function getCrossingSegments(segment, collectStarts) {
  9370. var inter = segment._intersection,
  9371. start = inter,
  9372. crossings = [];
  9373. if (collectStarts)
  9374. starts = [segment];
  9375. function collect(inter, end) {
  9376. while (inter && inter !== end) {
  9377. var other = inter._segment,
  9378. path = other && other._path;
  9379. if (path) {
  9380. var next = other.getNext() || path.getFirstSegment(),
  9381. nextInter = next._intersection;
  9382. if (other !== segment && (isStart(other)
  9383. || isStart(next)
  9384. || next && (isValid(other) && (isValid(next)
  9385. || nextInter && isValid(nextInter._segment))))
  9386. ) {
  9387. crossings.push(other);
  9388. }
  9389. if (collectStarts)
  9390. starts.push(other);
  9391. }
  9392. inter = inter._next;
  9393. }
  9394. }
  9395. if (inter) {
  9396. collect(inter);
  9397. while (inter && inter._prev)
  9398. inter = inter._prev;
  9399. collect(inter, start);
  9400. }
  9401. return crossings;
  9402. }
  9403. segments.sort(function(seg1, seg2) {
  9404. var inter1 = seg1._intersection,
  9405. inter2 = seg2._intersection,
  9406. over1 = !!(inter1 && inter1._overlap),
  9407. over2 = !!(inter2 && inter2._overlap),
  9408. path1 = seg1._path,
  9409. path2 = seg2._path;
  9410. return over1 ^ over2
  9411. ? over1 ? 1 : -1
  9412. : !inter1 ^ !inter2
  9413. ? inter1 ? 1 : -1
  9414. : path1 !== path2
  9415. ? path1._id - path2._id
  9416. : seg1._index - seg2._index;
  9417. });
  9418. for (var i = 0, l = segments.length; i < l; i++) {
  9419. var seg = segments[i],
  9420. valid = isValid(seg),
  9421. path = null,
  9422. finished = false,
  9423. closed = true,
  9424. branches = [],
  9425. branch,
  9426. visited,
  9427. handleIn;
  9428. if (valid && seg._path._overlapsOnly) {
  9429. var path1 = seg._path,
  9430. path2 = seg._intersection._segment._path;
  9431. if (path1.compare(path2)) {
  9432. if (path1.getArea())
  9433. paths.push(path1.clone(false));
  9434. visitPath(path1);
  9435. visitPath(path2);
  9436. valid = false;
  9437. }
  9438. }
  9439. while (valid) {
  9440. var first = !path,
  9441. crossings = getCrossingSegments(seg, first),
  9442. other = crossings.shift(),
  9443. finished = !first && (isStart(seg) || isStart(other)),
  9444. cross = !finished && other;
  9445. if (first) {
  9446. path = new Path(Item.NO_INSERT);
  9447. branch = null;
  9448. }
  9449. if (finished) {
  9450. if (seg.isFirst() || seg.isLast())
  9451. closed = seg._path._closed;
  9452. seg._visited = true;
  9453. break;
  9454. }
  9455. if (cross && branch) {
  9456. branches.push(branch);
  9457. branch = null;
  9458. }
  9459. if (!branch) {
  9460. if (cross)
  9461. crossings.push(seg);
  9462. branch = {
  9463. start: path._segments.length,
  9464. crossings: crossings,
  9465. visited: visited = [],
  9466. handleIn: handleIn
  9467. };
  9468. }
  9469. if (cross)
  9470. seg = other;
  9471. if (!isValid(seg)) {
  9472. path.removeSegments(branch.start);
  9473. for (var j = 0, k = visited.length; j < k; j++) {
  9474. visited[j]._visited = false;
  9475. }
  9476. visited.length = 0;
  9477. do {
  9478. seg = branch && branch.crossings.shift();
  9479. if (!seg || !seg._path) {
  9480. seg = null;
  9481. branch = branches.pop();
  9482. if (branch) {
  9483. visited = branch.visited;
  9484. handleIn = branch.handleIn;
  9485. }
  9486. }
  9487. } while (branch && !isValid(seg));
  9488. if (!seg)
  9489. break;
  9490. }
  9491. var next = seg.getNext();
  9492. path.add(new Segment(seg._point, handleIn,
  9493. next && seg._handleOut));
  9494. seg._visited = true;
  9495. visited.push(seg);
  9496. seg = next || seg._path.getFirstSegment();
  9497. handleIn = next && next._handleIn;
  9498. }
  9499. if (finished) {
  9500. if (closed) {
  9501. path.getFirstSegment().setHandleIn(handleIn);
  9502. path.setClosed(closed);
  9503. }
  9504. if (path.getArea() !== 0) {
  9505. paths.push(path);
  9506. }
  9507. }
  9508. }
  9509. return paths;
  9510. }
  9511. return {
  9512. _getWinding: function(point, dir, closed) {
  9513. return getWinding(point, this.getCurves(), dir, closed);
  9514. },
  9515. unite: function(path, options) {
  9516. return traceBoolean(this, path, 'unite', options);
  9517. },
  9518. intersect: function(path, options) {
  9519. return traceBoolean(this, path, 'intersect', options);
  9520. },
  9521. subtract: function(path, options) {
  9522. return traceBoolean(this, path, 'subtract', options);
  9523. },
  9524. exclude: function(path, options) {
  9525. return traceBoolean(this, path, 'exclude', options);
  9526. },
  9527. divide: function(path, options) {
  9528. return options && (options.trace == false || options.stroke)
  9529. ? splitBoolean(this, path, 'divide')
  9530. : createResult([
  9531. this.subtract(path, options),
  9532. this.intersect(path, options)
  9533. ], true, this, path, options);
  9534. },
  9535. resolveCrossings: function() {
  9536. var children = this._children,
  9537. paths = children || [this];
  9538. function hasOverlap(seg, path) {
  9539. var inter = seg && seg._intersection;
  9540. return inter && inter._overlap && inter._path === path;
  9541. }
  9542. var hasOverlaps = false,
  9543. hasCrossings = false,
  9544. intersections = this.getIntersections(null, function(inter) {
  9545. return inter.hasOverlap() && (hasOverlaps = true) ||
  9546. inter.isCrossing() && (hasCrossings = true);
  9547. }),
  9548. clearCurves = hasOverlaps && hasCrossings && [];
  9549. intersections = CurveLocation.expand(intersections);
  9550. if (hasOverlaps) {
  9551. var overlaps = divideLocations(intersections, function(inter) {
  9552. return inter.hasOverlap();
  9553. }, clearCurves);
  9554. for (var i = overlaps.length - 1; i >= 0; i--) {
  9555. var overlap = overlaps[i],
  9556. path = overlap._path,
  9557. seg = overlap._segment,
  9558. prev = seg.getPrevious(),
  9559. next = seg.getNext();
  9560. if (hasOverlap(prev, path) && hasOverlap(next, path)) {
  9561. seg.remove();
  9562. prev._handleOut._set(0, 0);
  9563. next._handleIn._set(0, 0);
  9564. if (prev !== seg && !prev.getCurve().hasLength()) {
  9565. next._handleIn.set(prev._handleIn);
  9566. prev.remove();
  9567. }
  9568. }
  9569. }
  9570. }
  9571. if (hasCrossings) {
  9572. divideLocations(intersections, hasOverlaps && function(inter) {
  9573. var curve1 = inter.getCurve(),
  9574. seg1 = inter.getSegment(),
  9575. other = inter._intersection,
  9576. curve2 = other._curve,
  9577. seg2 = other._segment;
  9578. if (curve1 && curve2 && curve1._path && curve2._path)
  9579. return true;
  9580. if (seg1)
  9581. seg1._intersection = null;
  9582. if (seg2)
  9583. seg2._intersection = null;
  9584. }, clearCurves);
  9585. if (clearCurves)
  9586. clearCurveHandles(clearCurves);
  9587. paths = tracePaths(Base.each(paths, function(path) {
  9588. this.push.apply(this, path._segments);
  9589. }, []));
  9590. }
  9591. var length = paths.length,
  9592. item;
  9593. if (length > 1 && children) {
  9594. if (paths !== children)
  9595. this.setChildren(paths);
  9596. item = this;
  9597. } else if (length === 1 && !children) {
  9598. if (paths[0] !== this)
  9599. this.setSegments(paths[0].removeSegments());
  9600. item = this;
  9601. }
  9602. if (!item) {
  9603. item = new CompoundPath(Item.NO_INSERT);
  9604. item.addChildren(paths);
  9605. item = item.reduce();
  9606. item.copyAttributes(this);
  9607. this.replaceWith(item);
  9608. }
  9609. return item;
  9610. },
  9611. reorient: function(nonZero, clockwise) {
  9612. var children = this._children;
  9613. if (children && children.length) {
  9614. this.setChildren(reorientPaths(this.removeChildren(),
  9615. function(w) {
  9616. return !!(nonZero ? w : w & 1);
  9617. },
  9618. clockwise));
  9619. } else if (clockwise !== undefined) {
  9620. this.setClockwise(clockwise);
  9621. }
  9622. return this;
  9623. },
  9624. getInteriorPoint: function() {
  9625. var bounds = this.getBounds(),
  9626. point = bounds.getCenter(true);
  9627. if (!this.contains(point)) {
  9628. var curves = this.getCurves(),
  9629. y = point.y,
  9630. intercepts = [],
  9631. roots = [];
  9632. for (var i = 0, l = curves.length; i < l; i++) {
  9633. var v = curves[i].getValues(),
  9634. o0 = v[1],
  9635. o1 = v[3],
  9636. o2 = v[5],
  9637. o3 = v[7];
  9638. if (y >= min(o0, o1, o2, o3) && y <= max(o0, o1, o2, o3)) {
  9639. var monoCurves = Curve.getMonoCurves(v);
  9640. for (var j = 0, m = monoCurves.length; j < m; j++) {
  9641. var mv = monoCurves[j],
  9642. mo0 = mv[1],
  9643. mo3 = mv[7];
  9644. if ((mo0 !== mo3) &&
  9645. (y >= mo0 && y <= mo3 || y >= mo3 && y <= mo0)){
  9646. var x = y === mo0 ? mv[0]
  9647. : y === mo3 ? mv[6]
  9648. : Curve.solveCubic(mv, 1, y, roots, 0, 1)
  9649. === 1
  9650. ? Curve.getPoint(mv, roots[0]).x
  9651. : (mv[0] + mv[6]) / 2;
  9652. intercepts.push(x);
  9653. }
  9654. }
  9655. }
  9656. }
  9657. if (intercepts.length > 1) {
  9658. intercepts.sort(function(a, b) { return a - b; });
  9659. point.x = (intercepts[0] + intercepts[1]) / 2;
  9660. }
  9661. }
  9662. return point;
  9663. }
  9664. };
  9665. });
  9666. var PathFlattener = Base.extend({
  9667. _class: 'PathFlattener',
  9668. initialize: function(path, flatness, maxRecursion, ignoreStraight, matrix) {
  9669. var curves = [],
  9670. parts = [],
  9671. length = 0,
  9672. minSpan = 1 / (maxRecursion || 32),
  9673. segments = path._segments,
  9674. segment1 = segments[0],
  9675. segment2;
  9676. function addCurve(segment1, segment2) {
  9677. var curve = Curve.getValues(segment1, segment2, matrix);
  9678. curves.push(curve);
  9679. computeParts(curve, segment1._index, 0, 1);
  9680. }
  9681. function computeParts(curve, index, t1, t2) {
  9682. if ((t2 - t1) > minSpan
  9683. && !(ignoreStraight && Curve.isStraight(curve))
  9684. && !Curve.isFlatEnough(curve, flatness || 0.25)) {
  9685. var halves = Curve.subdivide(curve, 0.5),
  9686. tMid = (t1 + t2) / 2;
  9687. computeParts(halves[0], index, t1, tMid);
  9688. computeParts(halves[1], index, tMid, t2);
  9689. } else {
  9690. var dx = curve[6] - curve[0],
  9691. dy = curve[7] - curve[1],
  9692. dist = Math.sqrt(dx * dx + dy * dy);
  9693. if (dist > 0) {
  9694. length += dist;
  9695. parts.push({
  9696. offset: length,
  9697. curve: curve,
  9698. index: index,
  9699. time: t2,
  9700. });
  9701. }
  9702. }
  9703. }
  9704. for (var i = 1, l = segments.length; i < l; i++) {
  9705. segment2 = segments[i];
  9706. addCurve(segment1, segment2);
  9707. segment1 = segment2;
  9708. }
  9709. if (path._closed)
  9710. addCurve(segment2, segments[0]);
  9711. this.curves = curves;
  9712. this.parts = parts;
  9713. this.length = length;
  9714. this.index = 0;
  9715. },
  9716. _get: function(offset) {
  9717. var parts = this.parts,
  9718. length = parts.length,
  9719. start,
  9720. i, j = this.index;
  9721. for (;;) {
  9722. i = j;
  9723. if (!j || parts[--j].offset < offset)
  9724. break;
  9725. }
  9726. for (; i < length; i++) {
  9727. var part = parts[i];
  9728. if (part.offset >= offset) {
  9729. this.index = i;
  9730. var prev = parts[i - 1],
  9731. prevTime = prev && prev.index === part.index ? prev.time : 0,
  9732. prevOffset = prev ? prev.offset : 0;
  9733. return {
  9734. index: part.index,
  9735. time: prevTime + (part.time - prevTime)
  9736. * (offset - prevOffset) / (part.offset - prevOffset)
  9737. };
  9738. }
  9739. }
  9740. return {
  9741. index: parts[length - 1].index,
  9742. time: 1
  9743. };
  9744. },
  9745. drawPart: function(ctx, from, to) {
  9746. var start = this._get(from),
  9747. end = this._get(to);
  9748. for (var i = start.index, l = end.index; i <= l; i++) {
  9749. var curve = Curve.getPart(this.curves[i],
  9750. i === start.index ? start.time : 0,
  9751. i === end.index ? end.time : 1);
  9752. if (i === start.index)
  9753. ctx.moveTo(curve[0], curve[1]);
  9754. ctx.bezierCurveTo.apply(ctx, curve.slice(2));
  9755. }
  9756. }
  9757. }, Base.each(Curve._evaluateMethods,
  9758. function(name) {
  9759. this[name + 'At'] = function(offset) {
  9760. var param = this._get(offset);
  9761. return Curve[name](this.curves[param.index], param.time);
  9762. };
  9763. }, {})
  9764. );
  9765. var PathFitter = Base.extend({
  9766. initialize: function(path) {
  9767. var points = this.points = [],
  9768. segments = path._segments,
  9769. closed = path._closed;
  9770. for (var i = 0, prev, l = segments.length; i < l; i++) {
  9771. var point = segments[i].point;
  9772. if (!prev || !prev.equals(point)) {
  9773. points.push(prev = point.clone());
  9774. }
  9775. }
  9776. if (closed) {
  9777. points.unshift(points[points.length - 1]);
  9778. points.push(points[1]);
  9779. }
  9780. this.closed = closed;
  9781. },
  9782. fit: function(error) {
  9783. var points = this.points,
  9784. length = points.length,
  9785. segments = null;
  9786. if (length > 0) {
  9787. segments = [new Segment(points[0])];
  9788. if (length > 1) {
  9789. this.fitCubic(segments, error, 0, length - 1,
  9790. points[1].subtract(points[0]),
  9791. points[length - 2].subtract(points[length - 1]));
  9792. if (this.closed) {
  9793. segments.shift();
  9794. segments.pop();
  9795. }
  9796. }
  9797. }
  9798. return segments;
  9799. },
  9800. fitCubic: function(segments, error, first, last, tan1, tan2) {
  9801. var points = this.points;
  9802. if (last - first === 1) {
  9803. var pt1 = points[first],
  9804. pt2 = points[last],
  9805. dist = pt1.getDistance(pt2) / 3;
  9806. this.addCurve(segments, [pt1, pt1.add(tan1.normalize(dist)),
  9807. pt2.add(tan2.normalize(dist)), pt2]);
  9808. return;
  9809. }
  9810. var uPrime = this.chordLengthParameterize(first, last),
  9811. maxError = Math.max(error, error * error),
  9812. split,
  9813. parametersInOrder = true;
  9814. for (var i = 0; i <= 4; i++) {
  9815. var curve = this.generateBezier(first, last, uPrime, tan1, tan2);
  9816. var max = this.findMaxError(first, last, curve, uPrime);
  9817. if (max.error < error && parametersInOrder) {
  9818. this.addCurve(segments, curve);
  9819. return;
  9820. }
  9821. split = max.index;
  9822. if (max.error >= maxError)
  9823. break;
  9824. parametersInOrder = this.reparameterize(first, last, uPrime, curve);
  9825. maxError = max.error;
  9826. }
  9827. var tanCenter = points[split - 1].subtract(points[split + 1]);
  9828. this.fitCubic(segments, error, first, split, tan1, tanCenter);
  9829. this.fitCubic(segments, error, split, last, tanCenter.negate(), tan2);
  9830. },
  9831. addCurve: function(segments, curve) {
  9832. var prev = segments[segments.length - 1];
  9833. prev.setHandleOut(curve[1].subtract(curve[0]));
  9834. segments.push(new Segment(curve[3], curve[2].subtract(curve[3])));
  9835. },
  9836. generateBezier: function(first, last, uPrime, tan1, tan2) {
  9837. var epsilon = 1e-12,
  9838. abs = Math.abs,
  9839. points = this.points,
  9840. pt1 = points[first],
  9841. pt2 = points[last],
  9842. C = [[0, 0], [0, 0]],
  9843. X = [0, 0];
  9844. for (var i = 0, l = last - first + 1; i < l; i++) {
  9845. var u = uPrime[i],
  9846. t = 1 - u,
  9847. b = 3 * u * t,
  9848. b0 = t * t * t,
  9849. b1 = b * t,
  9850. b2 = b * u,
  9851. b3 = u * u * u,
  9852. a1 = tan1.normalize(b1),
  9853. a2 = tan2.normalize(b2),
  9854. tmp = points[first + i]
  9855. .subtract(pt1.multiply(b0 + b1))
  9856. .subtract(pt2.multiply(b2 + b3));
  9857. C[0][0] += a1.dot(a1);
  9858. C[0][1] += a1.dot(a2);
  9859. C[1][0] = C[0][1];
  9860. C[1][1] += a2.dot(a2);
  9861. X[0] += a1.dot(tmp);
  9862. X[1] += a2.dot(tmp);
  9863. }
  9864. var detC0C1 = C[0][0] * C[1][1] - C[1][0] * C[0][1],
  9865. alpha1,
  9866. alpha2;
  9867. if (abs(detC0C1) > epsilon) {
  9868. var detC0X = C[0][0] * X[1] - C[1][0] * X[0],
  9869. detXC1 = X[0] * C[1][1] - X[1] * C[0][1];
  9870. alpha1 = detXC1 / detC0C1;
  9871. alpha2 = detC0X / detC0C1;
  9872. } else {
  9873. var c0 = C[0][0] + C[0][1],
  9874. c1 = C[1][0] + C[1][1];
  9875. alpha1 = alpha2 = abs(c0) > epsilon ? X[0] / c0
  9876. : abs(c1) > epsilon ? X[1] / c1
  9877. : 0;
  9878. }
  9879. var segLength = pt2.getDistance(pt1),
  9880. eps = epsilon * segLength,
  9881. handle1,
  9882. handle2;
  9883. if (alpha1 < eps || alpha2 < eps) {
  9884. alpha1 = alpha2 = segLength / 3;
  9885. } else {
  9886. var line = pt2.subtract(pt1);
  9887. handle1 = tan1.normalize(alpha1);
  9888. handle2 = tan2.normalize(alpha2);
  9889. if (handle1.dot(line) - handle2.dot(line) > segLength * segLength) {
  9890. alpha1 = alpha2 = segLength / 3;
  9891. handle1 = handle2 = null;
  9892. }
  9893. }
  9894. return [pt1,
  9895. pt1.add(handle1 || tan1.normalize(alpha1)),
  9896. pt2.add(handle2 || tan2.normalize(alpha2)),
  9897. pt2];
  9898. },
  9899. reparameterize: function(first, last, u, curve) {
  9900. for (var i = first; i <= last; i++) {
  9901. u[i - first] = this.findRoot(curve, this.points[i], u[i - first]);
  9902. }
  9903. for (var i = 1, l = u.length; i < l; i++) {
  9904. if (u[i] <= u[i - 1])
  9905. return false;
  9906. }
  9907. return true;
  9908. },
  9909. findRoot: function(curve, point, u) {
  9910. var curve1 = [],
  9911. curve2 = [];
  9912. for (var i = 0; i <= 2; i++) {
  9913. curve1[i] = curve[i + 1].subtract(curve[i]).multiply(3);
  9914. }
  9915. for (var i = 0; i <= 1; i++) {
  9916. curve2[i] = curve1[i + 1].subtract(curve1[i]).multiply(2);
  9917. }
  9918. var pt = this.evaluate(3, curve, u),
  9919. pt1 = this.evaluate(2, curve1, u),
  9920. pt2 = this.evaluate(1, curve2, u),
  9921. diff = pt.subtract(point),
  9922. df = pt1.dot(pt1) + diff.dot(pt2);
  9923. return Numerical.isZero(df) ? u : u - diff.dot(pt1) / df;
  9924. },
  9925. evaluate: function(degree, curve, t) {
  9926. var tmp = curve.slice();
  9927. for (var i = 1; i <= degree; i++) {
  9928. for (var j = 0; j <= degree - i; j++) {
  9929. tmp[j] = tmp[j].multiply(1 - t).add(tmp[j + 1].multiply(t));
  9930. }
  9931. }
  9932. return tmp[0];
  9933. },
  9934. chordLengthParameterize: function(first, last) {
  9935. var u = [0];
  9936. for (var i = first + 1; i <= last; i++) {
  9937. u[i - first] = u[i - first - 1]
  9938. + this.points[i].getDistance(this.points[i - 1]);
  9939. }
  9940. for (var i = 1, m = last - first; i <= m; i++) {
  9941. u[i] /= u[m];
  9942. }
  9943. return u;
  9944. },
  9945. findMaxError: function(first, last, curve, u) {
  9946. var index = Math.floor((last - first + 1) / 2),
  9947. maxDist = 0;
  9948. for (var i = first + 1; i < last; i++) {
  9949. var P = this.evaluate(3, curve, u[i - first]);
  9950. var v = P.subtract(this.points[i]);
  9951. var dist = v.x * v.x + v.y * v.y;
  9952. if (dist >= maxDist) {
  9953. maxDist = dist;
  9954. index = i;
  9955. }
  9956. }
  9957. return {
  9958. error: maxDist,
  9959. index: index
  9960. };
  9961. }
  9962. });
  9963. var TextItem = Item.extend({
  9964. _class: 'TextItem',
  9965. _applyMatrix: false,
  9966. _canApplyMatrix: false,
  9967. _serializeFields: {
  9968. content: null
  9969. },
  9970. _boundsOptions: { stroke: false, handle: false },
  9971. initialize: function TextItem(arg) {
  9972. this._content = '';
  9973. this._lines = [];
  9974. var hasProps = arg && Base.isPlainObject(arg)
  9975. && arg.x === undefined && arg.y === undefined;
  9976. this._initialize(hasProps && arg, !hasProps && Point.read(arguments));
  9977. },
  9978. _equals: function(item) {
  9979. return this._content === item._content;
  9980. },
  9981. copyContent: function(source) {
  9982. this.setContent(source._content);
  9983. },
  9984. getContent: function() {
  9985. return this._content;
  9986. },
  9987. setContent: function(content) {
  9988. this._content = '' + content;
  9989. this._lines = this._content.split(/\r\n|\n|\r/mg);
  9990. this._changed(265);
  9991. },
  9992. isEmpty: function() {
  9993. return !this._content;
  9994. },
  9995. getCharacterStyle: '#getStyle',
  9996. setCharacterStyle: '#setStyle',
  9997. getParagraphStyle: '#getStyle',
  9998. setParagraphStyle: '#setStyle'
  9999. });
  10000. var PointText = TextItem.extend({
  10001. _class: 'PointText',
  10002. initialize: function PointText() {
  10003. TextItem.apply(this, arguments);
  10004. },
  10005. getPoint: function() {
  10006. var point = this._matrix.getTranslation();
  10007. return new LinkedPoint(point.x, point.y, this, 'setPoint');
  10008. },
  10009. setPoint: function() {
  10010. var point = Point.read(arguments);
  10011. this.translate(point.subtract(this._matrix.getTranslation()));
  10012. },
  10013. _draw: function(ctx, param, viewMatrix) {
  10014. if (!this._content)
  10015. return;
  10016. this._setStyles(ctx, param, viewMatrix);
  10017. var lines = this._lines,
  10018. style = this._style,
  10019. hasFill = style.hasFill(),
  10020. hasStroke = style.hasStroke(),
  10021. leading = style.getLeading(),
  10022. shadowColor = ctx.shadowColor;
  10023. ctx.font = style.getFontStyle();
  10024. ctx.textAlign = style.getJustification();
  10025. for (var i = 0, l = lines.length; i < l; i++) {
  10026. ctx.shadowColor = shadowColor;
  10027. var line = lines[i];
  10028. if (hasFill) {
  10029. ctx.fillText(line, 0, 0);
  10030. ctx.shadowColor = 'rgba(0,0,0,0)';
  10031. }
  10032. if (hasStroke)
  10033. ctx.strokeText(line, 0, 0);
  10034. ctx.translate(0, leading);
  10035. }
  10036. },
  10037. _getBounds: function(matrix, options) {
  10038. var style = this._style,
  10039. lines = this._lines,
  10040. numLines = lines.length,
  10041. justification = style.getJustification(),
  10042. leading = style.getLeading(),
  10043. width = this.getView().getTextWidth(style.getFontStyle(), lines),
  10044. x = 0;
  10045. if (justification !== 'left')
  10046. x -= width / (justification === 'center' ? 2: 1);
  10047. var rect = new Rectangle(x,
  10048. numLines ? - 0.75 * leading : 0,
  10049. width, numLines * leading);
  10050. return matrix ? matrix._transformBounds(rect, rect) : rect;
  10051. }
  10052. });
  10053. var Color = Base.extend(new function() {
  10054. var types = {
  10055. gray: ['gray'],
  10056. rgb: ['red', 'green', 'blue'],
  10057. hsb: ['hue', 'saturation', 'brightness'],
  10058. hsl: ['hue', 'saturation', 'lightness'],
  10059. gradient: ['gradient', 'origin', 'destination', 'highlight']
  10060. };
  10061. var componentParsers = {},
  10062. colorCache = {},
  10063. colorCtx;
  10064. function fromCSS(string) {
  10065. var match = string.match(/^#(\w{1,2})(\w{1,2})(\w{1,2})$/),
  10066. components;
  10067. if (match) {
  10068. components = [0, 0, 0];
  10069. for (var i = 0; i < 3; i++) {
  10070. var value = match[i + 1];
  10071. components[i] = parseInt(value.length == 1
  10072. ? value + value : value, 16) / 255;
  10073. }
  10074. } else if (match = string.match(/^rgba?\((.*)\)$/)) {
  10075. components = match[1].split(',');
  10076. for (var i = 0, l = components.length; i < l; i++) {
  10077. var value = +components[i];
  10078. components[i] = i < 3 ? value / 255 : value;
  10079. }
  10080. } else if (window) {
  10081. var cached = colorCache[string];
  10082. if (!cached) {
  10083. if (!colorCtx) {
  10084. colorCtx = CanvasProvider.getContext(1, 1);
  10085. colorCtx.globalCompositeOperation = 'copy';
  10086. }
  10087. colorCtx.fillStyle = 'rgba(0,0,0,0)';
  10088. colorCtx.fillStyle = string;
  10089. colorCtx.fillRect(0, 0, 1, 1);
  10090. var data = colorCtx.getImageData(0, 0, 1, 1).data;
  10091. cached = colorCache[string] = [
  10092. data[0] / 255,
  10093. data[1] / 255,
  10094. data[2] / 255
  10095. ];
  10096. }
  10097. components = cached.slice();
  10098. } else {
  10099. components = [0, 0, 0];
  10100. }
  10101. return components;
  10102. }
  10103. var hsbIndices = [
  10104. [0, 3, 1],
  10105. [2, 0, 1],
  10106. [1, 0, 3],
  10107. [1, 2, 0],
  10108. [3, 1, 0],
  10109. [0, 1, 2]
  10110. ];
  10111. var converters = {
  10112. 'rgb-hsb': function(r, g, b) {
  10113. var max = Math.max(r, g, b),
  10114. min = Math.min(r, g, b),
  10115. delta = max - min,
  10116. h = delta === 0 ? 0
  10117. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10118. : max == g ? (b - r) / delta + 2
  10119. : (r - g) / delta + 4) * 60;
  10120. return [h, max === 0 ? 0 : delta / max, max];
  10121. },
  10122. 'hsb-rgb': function(h, s, b) {
  10123. h = (((h / 60) % 6) + 6) % 6;
  10124. var i = Math.floor(h),
  10125. f = h - i,
  10126. i = hsbIndices[i],
  10127. v = [
  10128. b,
  10129. b * (1 - s),
  10130. b * (1 - s * f),
  10131. b * (1 - s * (1 - f))
  10132. ];
  10133. return [v[i[0]], v[i[1]], v[i[2]]];
  10134. },
  10135. 'rgb-hsl': function(r, g, b) {
  10136. var max = Math.max(r, g, b),
  10137. min = Math.min(r, g, b),
  10138. delta = max - min,
  10139. achromatic = delta === 0,
  10140. h = achromatic ? 0
  10141. : ( max == r ? (g - b) / delta + (g < b ? 6 : 0)
  10142. : max == g ? (b - r) / delta + 2
  10143. : (r - g) / delta + 4) * 60,
  10144. l = (max + min) / 2,
  10145. s = achromatic ? 0 : l < 0.5
  10146. ? delta / (max + min)
  10147. : delta / (2 - max - min);
  10148. return [h, s, l];
  10149. },
  10150. 'hsl-rgb': function(h, s, l) {
  10151. h = (((h / 360) % 1) + 1) % 1;
  10152. if (s === 0)
  10153. return [l, l, l];
  10154. var t3s = [ h + 1 / 3, h, h - 1 / 3 ],
  10155. t2 = l < 0.5 ? l * (1 + s) : l + s - l * s,
  10156. t1 = 2 * l - t2,
  10157. c = [];
  10158. for (var i = 0; i < 3; i++) {
  10159. var t3 = t3s[i];
  10160. if (t3 < 0) t3 += 1;
  10161. if (t3 > 1) t3 -= 1;
  10162. c[i] = 6 * t3 < 1
  10163. ? t1 + (t2 - t1) * 6 * t3
  10164. : 2 * t3 < 1
  10165. ? t2
  10166. : 3 * t3 < 2
  10167. ? t1 + (t2 - t1) * ((2 / 3) - t3) * 6
  10168. : t1;
  10169. }
  10170. return c;
  10171. },
  10172. 'rgb-gray': function(r, g, b) {
  10173. return [r * 0.2989 + g * 0.587 + b * 0.114];
  10174. },
  10175. 'gray-rgb': function(g) {
  10176. return [g, g, g];
  10177. },
  10178. 'gray-hsb': function(g) {
  10179. return [0, 0, g];
  10180. },
  10181. 'gray-hsl': function(g) {
  10182. return [0, 0, g];
  10183. },
  10184. 'gradient-rgb': function() {
  10185. return [];
  10186. },
  10187. 'rgb-gradient': function() {
  10188. return [];
  10189. }
  10190. };
  10191. return Base.each(types, function(properties, type) {
  10192. componentParsers[type] = [];
  10193. Base.each(properties, function(name, index) {
  10194. var part = Base.capitalize(name),
  10195. hasOverlap = /^(hue|saturation)$/.test(name),
  10196. parser = componentParsers[type][index] = name === 'gradient'
  10197. ? function(value) {
  10198. var current = this._components[0];
  10199. value = Gradient.read(Array.isArray(value) ? value
  10200. : arguments, 0, { readNull: true });
  10201. if (current !== value) {
  10202. if (current)
  10203. current._removeOwner(this);
  10204. if (value)
  10205. value._addOwner(this);
  10206. }
  10207. return value;
  10208. }
  10209. : type === 'gradient'
  10210. ? function() {
  10211. return Point.read(arguments, 0, {
  10212. readNull: name === 'highlight',
  10213. clone: true
  10214. });
  10215. }
  10216. : function(value) {
  10217. return value == null || isNaN(value) ? 0 : value;
  10218. };
  10219. this['get' + part] = function() {
  10220. return this._type === type
  10221. || hasOverlap && /^hs[bl]$/.test(this._type)
  10222. ? this._components[index]
  10223. : this._convert(type)[index];
  10224. };
  10225. this['set' + part] = function(value) {
  10226. if (this._type !== type
  10227. && !(hasOverlap && /^hs[bl]$/.test(this._type))) {
  10228. this._components = this._convert(type);
  10229. this._properties = types[type];
  10230. this._type = type;
  10231. }
  10232. this._components[index] = parser.call(this, value);
  10233. this._changed();
  10234. };
  10235. }, this);
  10236. }, {
  10237. _class: 'Color',
  10238. _readIndex: true,
  10239. initialize: function Color(arg) {
  10240. var args = arguments,
  10241. reading = this.__read,
  10242. read = 0,
  10243. type,
  10244. components,
  10245. alpha,
  10246. values;
  10247. if (Array.isArray(arg)) {
  10248. args = arg;
  10249. arg = args[0];
  10250. }
  10251. var argType = arg != null && typeof arg;
  10252. if (argType === 'string' && arg in types) {
  10253. type = arg;
  10254. arg = args[1];
  10255. if (Array.isArray(arg)) {
  10256. components = arg;
  10257. alpha = args[2];
  10258. } else {
  10259. if (reading)
  10260. read = 1;
  10261. args = Base.slice(args, 1);
  10262. argType = typeof arg;
  10263. }
  10264. }
  10265. if (!components) {
  10266. values = argType === 'number'
  10267. ? args
  10268. : argType === 'object' && arg.length != null
  10269. ? arg
  10270. : null;
  10271. if (values) {
  10272. if (!type)
  10273. type = values.length >= 3
  10274. ? 'rgb'
  10275. : 'gray';
  10276. var length = types[type].length;
  10277. alpha = values[length];
  10278. if (reading) {
  10279. read += values === arguments
  10280. ? length + (alpha != null ? 1 : 0)
  10281. : 1;
  10282. }
  10283. if (values.length > length)
  10284. values = Base.slice(values, 0, length);
  10285. } else if (argType === 'string') {
  10286. type = 'rgb';
  10287. components = fromCSS(arg);
  10288. if (components.length === 4) {
  10289. alpha = components[3];
  10290. components.length--;
  10291. }
  10292. } else if (argType === 'object') {
  10293. if (arg.constructor === Color) {
  10294. type = arg._type;
  10295. components = arg._components.slice();
  10296. alpha = arg._alpha;
  10297. if (type === 'gradient') {
  10298. for (var i = 1, l = components.length; i < l; i++) {
  10299. var point = components[i];
  10300. if (point)
  10301. components[i] = point.clone();
  10302. }
  10303. }
  10304. } else if (arg.constructor === Gradient) {
  10305. type = 'gradient';
  10306. values = args;
  10307. } else {
  10308. type = 'hue' in arg
  10309. ? 'lightness' in arg
  10310. ? 'hsl'
  10311. : 'hsb'
  10312. : 'gradient' in arg || 'stops' in arg
  10313. || 'radial' in arg
  10314. ? 'gradient'
  10315. : 'gray' in arg
  10316. ? 'gray'
  10317. : 'rgb';
  10318. var properties = types[type],
  10319. parsers = componentParsers[type];
  10320. this._components = components = [];
  10321. for (var i = 0, l = properties.length; i < l; i++) {
  10322. var value = arg[properties[i]];
  10323. if (value == null && !i && type === 'gradient'
  10324. && 'stops' in arg) {
  10325. value = {
  10326. stops: arg.stops,
  10327. radial: arg.radial
  10328. };
  10329. }
  10330. value = parsers[i].call(this, value);
  10331. if (value != null)
  10332. components[i] = value;
  10333. }
  10334. alpha = arg.alpha;
  10335. }
  10336. }
  10337. if (reading && type)
  10338. read = 1;
  10339. }
  10340. this._type = type || 'rgb';
  10341. if (!components) {
  10342. this._components = components = [];
  10343. var parsers = componentParsers[this._type];
  10344. for (var i = 0, l = parsers.length; i < l; i++) {
  10345. var value = parsers[i].call(this, values && values[i]);
  10346. if (value != null)
  10347. components[i] = value;
  10348. }
  10349. }
  10350. this._components = components;
  10351. this._properties = types[this._type];
  10352. this._alpha = alpha;
  10353. if (reading)
  10354. this.__read = read;
  10355. return this;
  10356. },
  10357. set: '#initialize',
  10358. _serialize: function(options, dictionary) {
  10359. var components = this.getComponents();
  10360. return Base.serialize(
  10361. /^(gray|rgb)$/.test(this._type)
  10362. ? components
  10363. : [this._type].concat(components),
  10364. options, true, dictionary);
  10365. },
  10366. _changed: function() {
  10367. this._canvasStyle = null;
  10368. if (this._owner)
  10369. this._owner._changed(65);
  10370. },
  10371. _convert: function(type) {
  10372. var converter;
  10373. return this._type === type
  10374. ? this._components.slice()
  10375. : (converter = converters[this._type + '-' + type])
  10376. ? converter.apply(this, this._components)
  10377. : converters['rgb-' + type].apply(this,
  10378. converters[this._type + '-rgb'].apply(this,
  10379. this._components));
  10380. },
  10381. convert: function(type) {
  10382. return new Color(type, this._convert(type), this._alpha);
  10383. },
  10384. getType: function() {
  10385. return this._type;
  10386. },
  10387. setType: function(type) {
  10388. this._components = this._convert(type);
  10389. this._properties = types[type];
  10390. this._type = type;
  10391. },
  10392. getComponents: function() {
  10393. var components = this._components.slice();
  10394. if (this._alpha != null)
  10395. components.push(this._alpha);
  10396. return components;
  10397. },
  10398. getAlpha: function() {
  10399. return this._alpha != null ? this._alpha : 1;
  10400. },
  10401. setAlpha: function(alpha) {
  10402. this._alpha = alpha == null ? null : Math.min(Math.max(alpha, 0), 1);
  10403. this._changed();
  10404. },
  10405. hasAlpha: function() {
  10406. return this._alpha != null;
  10407. },
  10408. equals: function(color) {
  10409. var col = Base.isPlainValue(color, true)
  10410. ? Color.read(arguments)
  10411. : color;
  10412. return col === this || col && this._class === col._class
  10413. && this._type === col._type
  10414. && this.getAlpha() === col.getAlpha()
  10415. && Base.equals(this._components, col._components)
  10416. || false;
  10417. },
  10418. toString: function() {
  10419. var properties = this._properties,
  10420. parts = [],
  10421. isGradient = this._type === 'gradient',
  10422. f = Formatter.instance;
  10423. for (var i = 0, l = properties.length; i < l; i++) {
  10424. var value = this._components[i];
  10425. if (value != null)
  10426. parts.push(properties[i] + ': '
  10427. + (isGradient ? value : f.number(value)));
  10428. }
  10429. if (this._alpha != null)
  10430. parts.push('alpha: ' + f.number(this._alpha));
  10431. return '{ ' + parts.join(', ') + ' }';
  10432. },
  10433. toCSS: function(hex) {
  10434. var components = this._convert('rgb'),
  10435. alpha = hex || this._alpha == null ? 1 : this._alpha;
  10436. function convert(val) {
  10437. return Math.round((val < 0 ? 0 : val > 1 ? 1 : val) * 255);
  10438. }
  10439. components = [
  10440. convert(components[0]),
  10441. convert(components[1]),
  10442. convert(components[2])
  10443. ];
  10444. if (alpha < 1)
  10445. components.push(alpha < 0 ? 0 : alpha);
  10446. return hex
  10447. ? '#' + ((1 << 24) + (components[0] << 16)
  10448. + (components[1] << 8)
  10449. + components[2]).toString(16).slice(1)
  10450. : (components.length == 4 ? 'rgba(' : 'rgb(')
  10451. + components.join(',') + ')';
  10452. },
  10453. toCanvasStyle: function(ctx, matrix) {
  10454. if (this._canvasStyle)
  10455. return this._canvasStyle;
  10456. if (this._type !== 'gradient')
  10457. return this._canvasStyle = this.toCSS();
  10458. var components = this._components,
  10459. gradient = components[0],
  10460. stops = gradient._stops,
  10461. origin = components[1],
  10462. destination = components[2],
  10463. highlight = components[3],
  10464. inverse = matrix && matrix.inverted(),
  10465. canvasGradient;
  10466. if (inverse) {
  10467. origin = inverse._transformPoint(origin);
  10468. destination = inverse._transformPoint(destination);
  10469. if (highlight)
  10470. highlight = inverse._transformPoint(highlight);
  10471. }
  10472. if (gradient._radial) {
  10473. var radius = destination.getDistance(origin);
  10474. if (highlight) {
  10475. var vector = highlight.subtract(origin);
  10476. if (vector.getLength() > radius)
  10477. highlight = origin.add(vector.normalize(radius - 0.1));
  10478. }
  10479. var start = highlight || origin;
  10480. canvasGradient = ctx.createRadialGradient(start.x, start.y,
  10481. 0, origin.x, origin.y, radius);
  10482. } else {
  10483. canvasGradient = ctx.createLinearGradient(origin.x, origin.y,
  10484. destination.x, destination.y);
  10485. }
  10486. for (var i = 0, l = stops.length; i < l; i++) {
  10487. var stop = stops[i],
  10488. offset = stop._offset;
  10489. canvasGradient.addColorStop(
  10490. offset == null ? i / (l - 1) : offset,
  10491. stop._color.toCanvasStyle());
  10492. }
  10493. return this._canvasStyle = canvasGradient;
  10494. },
  10495. transform: function(matrix) {
  10496. if (this._type === 'gradient') {
  10497. var components = this._components;
  10498. for (var i = 1, l = components.length; i < l; i++) {
  10499. var point = components[i];
  10500. matrix._transformPoint(point, point, true);
  10501. }
  10502. this._changed();
  10503. }
  10504. },
  10505. statics: {
  10506. _types: types,
  10507. random: function() {
  10508. var random = Math.random;
  10509. return new Color(random(), random(), random());
  10510. }
  10511. }
  10512. });
  10513. },
  10514. new function() {
  10515. var operators = {
  10516. add: function(a, b) {
  10517. return a + b;
  10518. },
  10519. subtract: function(a, b) {
  10520. return a - b;
  10521. },
  10522. multiply: function(a, b) {
  10523. return a * b;
  10524. },
  10525. divide: function(a, b) {
  10526. return a / b;
  10527. }
  10528. };
  10529. return Base.each(operators, function(operator, name) {
  10530. this[name] = function(color) {
  10531. color = Color.read(arguments);
  10532. var type = this._type,
  10533. components1 = this._components,
  10534. components2 = color._convert(type);
  10535. for (var i = 0, l = components1.length; i < l; i++)
  10536. components2[i] = operator(components1[i], components2[i]);
  10537. return new Color(type, components2,
  10538. this._alpha != null
  10539. ? operator(this._alpha, color.getAlpha())
  10540. : null);
  10541. };
  10542. }, {
  10543. });
  10544. });
  10545. var Gradient = Base.extend({
  10546. _class: 'Gradient',
  10547. initialize: function Gradient(stops, radial) {
  10548. this._id = UID.get();
  10549. if (stops && Base.isPlainObject(stops)) {
  10550. this.set(stops);
  10551. stops = radial = null;
  10552. }
  10553. if (this._stops == null) {
  10554. this.setStops(stops || ['white', 'black']);
  10555. }
  10556. if (this._radial == null) {
  10557. this.setRadial(typeof radial === 'string' && radial === 'radial'
  10558. || radial || false);
  10559. }
  10560. },
  10561. _serialize: function(options, dictionary) {
  10562. return dictionary.add(this, function() {
  10563. return Base.serialize([this._stops, this._radial],
  10564. options, true, dictionary);
  10565. });
  10566. },
  10567. _changed: function() {
  10568. for (var i = 0, l = this._owners && this._owners.length; i < l; i++) {
  10569. this._owners[i]._changed();
  10570. }
  10571. },
  10572. _addOwner: function(color) {
  10573. if (!this._owners)
  10574. this._owners = [];
  10575. this._owners.push(color);
  10576. },
  10577. _removeOwner: function(color) {
  10578. var index = this._owners ? this._owners.indexOf(color) : -1;
  10579. if (index != -1) {
  10580. this._owners.splice(index, 1);
  10581. if (!this._owners.length)
  10582. this._owners = undefined;
  10583. }
  10584. },
  10585. clone: function() {
  10586. var stops = [];
  10587. for (var i = 0, l = this._stops.length; i < l; i++) {
  10588. stops[i] = this._stops[i].clone();
  10589. }
  10590. return new Gradient(stops, this._radial);
  10591. },
  10592. getStops: function() {
  10593. return this._stops;
  10594. },
  10595. setStops: function(stops) {
  10596. if (stops.length < 2) {
  10597. throw new Error(
  10598. 'Gradient stop list needs to contain at least two stops.');
  10599. }
  10600. var _stops = this._stops;
  10601. if (_stops) {
  10602. for (var i = 0, l = _stops.length; i < l; i++)
  10603. _stops[i]._owner = undefined;
  10604. }
  10605. _stops = this._stops = GradientStop.readList(stops, 0, { clone: true });
  10606. for (var i = 0, l = _stops.length; i < l; i++)
  10607. _stops[i]._owner = this;
  10608. this._changed();
  10609. },
  10610. getRadial: function() {
  10611. return this._radial;
  10612. },
  10613. setRadial: function(radial) {
  10614. this._radial = radial;
  10615. this._changed();
  10616. },
  10617. equals: function(gradient) {
  10618. if (gradient === this)
  10619. return true;
  10620. if (gradient && this._class === gradient._class) {
  10621. var stops1 = this._stops,
  10622. stops2 = gradient._stops,
  10623. length = stops1.length;
  10624. if (length === stops2.length) {
  10625. for (var i = 0; i < length; i++) {
  10626. if (!stops1[i].equals(stops2[i]))
  10627. return false;
  10628. }
  10629. return true;
  10630. }
  10631. }
  10632. return false;
  10633. }
  10634. });
  10635. var GradientStop = Base.extend({
  10636. _class: 'GradientStop',
  10637. initialize: function GradientStop(arg0, arg1) {
  10638. var color = arg0,
  10639. offset = arg1;
  10640. if (typeof arg0 === 'object' && arg1 === undefined) {
  10641. if (Array.isArray(arg0) && typeof arg0[0] !== 'number') {
  10642. color = arg0[0];
  10643. offset = arg0[1];
  10644. } else if ('color' in arg0 || 'offset' in arg0
  10645. || 'rampPoint' in arg0) {
  10646. color = arg0.color;
  10647. offset = arg0.offset || arg0.rampPoint || 0;
  10648. }
  10649. }
  10650. this.setColor(color);
  10651. this.setOffset(offset);
  10652. },
  10653. clone: function() {
  10654. return new GradientStop(this._color.clone(), this._offset);
  10655. },
  10656. _serialize: function(options, dictionary) {
  10657. var color = this._color,
  10658. offset = this._offset;
  10659. return Base.serialize(offset == null ? [color] : [color, offset],
  10660. options, true, dictionary);
  10661. },
  10662. _changed: function() {
  10663. if (this._owner)
  10664. this._owner._changed(65);
  10665. },
  10666. getOffset: function() {
  10667. return this._offset;
  10668. },
  10669. setOffset: function(offset) {
  10670. this._offset = offset;
  10671. this._changed();
  10672. },
  10673. getRampPoint: '#getOffset',
  10674. setRampPoint: '#setOffset',
  10675. getColor: function() {
  10676. return this._color;
  10677. },
  10678. setColor: function() {
  10679. var color = Color.read(arguments, 0, { clone: true });
  10680. if (color)
  10681. color._owner = this;
  10682. this._color = color;
  10683. this._changed();
  10684. },
  10685. equals: function(stop) {
  10686. return stop === this || stop && this._class === stop._class
  10687. && this._color.equals(stop._color)
  10688. && this._offset == stop._offset
  10689. || false;
  10690. }
  10691. });
  10692. var Style = Base.extend(new function() {
  10693. var itemDefaults = {
  10694. fillColor: null,
  10695. fillRule: 'nonzero',
  10696. strokeColor: null,
  10697. strokeWidth: 1,
  10698. strokeCap: 'butt',
  10699. strokeJoin: 'miter',
  10700. strokeScaling: true,
  10701. miterLimit: 10,
  10702. dashOffset: 0,
  10703. dashArray: [],
  10704. shadowColor: null,
  10705. shadowBlur: 0,
  10706. shadowOffset: new Point(),
  10707. selectedColor: null
  10708. },
  10709. groupDefaults = Base.set({}, itemDefaults, {
  10710. fontFamily: 'sans-serif',
  10711. fontWeight: 'normal',
  10712. fontSize: 12,
  10713. leading: null,
  10714. justification: 'left'
  10715. }),
  10716. textDefaults = Base.set({}, groupDefaults, {
  10717. fillColor: new Color()
  10718. }),
  10719. flags = {
  10720. strokeWidth: 97,
  10721. strokeCap: 97,
  10722. strokeJoin: 97,
  10723. strokeScaling: 105,
  10724. miterLimit: 97,
  10725. fontFamily: 9,
  10726. fontWeight: 9,
  10727. fontSize: 9,
  10728. font: 9,
  10729. leading: 9,
  10730. justification: 9
  10731. },
  10732. item = {
  10733. beans: true
  10734. },
  10735. fields = {
  10736. _class: 'Style',
  10737. beans: true,
  10738. initialize: function Style(style, _owner, _project) {
  10739. this._values = {};
  10740. this._owner = _owner;
  10741. this._project = _owner && _owner._project || _project
  10742. || paper.project;
  10743. this._defaults = !_owner || _owner instanceof Group ? groupDefaults
  10744. : _owner instanceof TextItem ? textDefaults
  10745. : itemDefaults;
  10746. if (style)
  10747. this.set(style);
  10748. }
  10749. };
  10750. Base.each(groupDefaults, function(value, key) {
  10751. var isColor = /Color$/.test(key),
  10752. isPoint = key === 'shadowOffset',
  10753. part = Base.capitalize(key),
  10754. flag = flags[key],
  10755. set = 'set' + part,
  10756. get = 'get' + part;
  10757. fields[set] = function(value) {
  10758. var owner = this._owner,
  10759. children = owner && owner._children;
  10760. if (children && children.length > 0
  10761. && !(owner instanceof CompoundPath)) {
  10762. for (var i = 0, l = children.length; i < l; i++)
  10763. children[i]._style[set](value);
  10764. } else if (key in this._defaults) {
  10765. var old = this._values[key];
  10766. if (old !== value) {
  10767. if (isColor) {
  10768. if (old && old._owner !== undefined)
  10769. old._owner = undefined;
  10770. if (value && value.constructor === Color) {
  10771. if (value._owner)
  10772. value = value.clone();
  10773. value._owner = owner;
  10774. }
  10775. }
  10776. this._values[key] = value;
  10777. if (owner)
  10778. owner._changed(flag || 65);
  10779. }
  10780. }
  10781. };
  10782. fields[get] = function(_dontMerge) {
  10783. var owner = this._owner,
  10784. children = owner && owner._children,
  10785. value;
  10786. if (key in this._defaults && (!children || !children.length
  10787. || _dontMerge || owner instanceof CompoundPath)) {
  10788. var value = this._values[key];
  10789. if (value === undefined) {
  10790. value = this._defaults[key];
  10791. if (value && value.clone)
  10792. value = value.clone();
  10793. } else {
  10794. var ctor = isColor ? Color : isPoint ? Point : null;
  10795. if (ctor && !(value && value.constructor === ctor)) {
  10796. this._values[key] = value = ctor.read([value], 0,
  10797. { readNull: true, clone: true });
  10798. if (value && isColor)
  10799. value._owner = owner;
  10800. }
  10801. }
  10802. } else if (children) {
  10803. for (var i = 0, l = children.length; i < l; i++) {
  10804. var childValue = children[i]._style[get]();
  10805. if (!i) {
  10806. value = childValue;
  10807. } else if (!Base.equals(value, childValue)) {
  10808. return undefined;
  10809. }
  10810. }
  10811. }
  10812. return value;
  10813. };
  10814. item[get] = function(_dontMerge) {
  10815. return this._style[get](_dontMerge);
  10816. };
  10817. item[set] = function(value) {
  10818. this._style[set](value);
  10819. };
  10820. });
  10821. Base.each({
  10822. Font: 'FontFamily',
  10823. WindingRule: 'FillRule'
  10824. }, function(value, key) {
  10825. var get = 'get' + key,
  10826. set = 'set' + key;
  10827. fields[get] = item[get] = '#get' + value;
  10828. fields[set] = item[set] = '#set' + value;
  10829. });
  10830. Item.inject(item);
  10831. return fields;
  10832. }, {
  10833. set: function(style) {
  10834. var isStyle = style instanceof Style,
  10835. values = isStyle ? style._values : style;
  10836. if (values) {
  10837. for (var key in values) {
  10838. if (key in this._defaults) {
  10839. var value = values[key];
  10840. this[key] = value && isStyle && value.clone
  10841. ? value.clone() : value;
  10842. }
  10843. }
  10844. }
  10845. },
  10846. equals: function(style) {
  10847. function compare(style1, style2, secondary) {
  10848. var values1 = style1._values,
  10849. values2 = style2._values,
  10850. defaults2 = style2._defaults;
  10851. for (var key in values1) {
  10852. var value1 = values1[key],
  10853. value2 = values2[key];
  10854. if (!(secondary && key in values2) && !Base.equals(value1,
  10855. value2 === undefined ? defaults2[key] : value2))
  10856. return false;
  10857. }
  10858. return true;
  10859. }
  10860. return style === this || style && this._class === style._class
  10861. && compare(this, style)
  10862. && compare(style, this, true)
  10863. || false;
  10864. },
  10865. hasFill: function() {
  10866. var color = this.getFillColor();
  10867. return !!color && color.alpha > 0;
  10868. },
  10869. hasStroke: function() {
  10870. var color = this.getStrokeColor();
  10871. return !!color && color.alpha > 0 && this.getStrokeWidth() > 0;
  10872. },
  10873. hasShadow: function() {
  10874. var color = this.getShadowColor();
  10875. return !!color && color.alpha > 0 && (this.getShadowBlur() > 0
  10876. || !this.getShadowOffset().isZero());
  10877. },
  10878. getView: function() {
  10879. return this._project._view;
  10880. },
  10881. getFontStyle: function() {
  10882. var fontSize = this.getFontSize();
  10883. return this.getFontWeight()
  10884. + ' ' + fontSize + (/[a-z]/i.test(fontSize + '') ? ' ' : 'px ')
  10885. + this.getFontFamily();
  10886. },
  10887. getFont: '#getFontFamily',
  10888. setFont: '#setFontFamily',
  10889. getLeading: function getLeading() {
  10890. var leading = getLeading.base.call(this),
  10891. fontSize = this.getFontSize();
  10892. if (/pt|em|%|px/.test(fontSize))
  10893. fontSize = this.getView().getPixelSize(fontSize);
  10894. return leading != null ? leading : fontSize * 1.2;
  10895. }
  10896. });
  10897. var DomElement = new function() {
  10898. function handlePrefix(el, name, set, value) {
  10899. var prefixes = ['', 'webkit', 'moz', 'Moz', 'ms', 'o'],
  10900. suffix = name[0].toUpperCase() + name.substring(1);
  10901. for (var i = 0; i < 6; i++) {
  10902. var prefix = prefixes[i],
  10903. key = prefix ? prefix + suffix : name;
  10904. if (key in el) {
  10905. if (set) {
  10906. el[key] = value;
  10907. } else {
  10908. return el[key];
  10909. }
  10910. break;
  10911. }
  10912. }
  10913. }
  10914. return {
  10915. getStyles: function(el) {
  10916. var doc = el && el.nodeType !== 9 ? el.ownerDocument : el,
  10917. view = doc && doc.defaultView;
  10918. return view && view.getComputedStyle(el, '');
  10919. },
  10920. getBounds: function(el, viewport) {
  10921. var doc = el.ownerDocument,
  10922. body = doc.body,
  10923. html = doc.documentElement,
  10924. rect;
  10925. try {
  10926. rect = el.getBoundingClientRect();
  10927. } catch (e) {
  10928. rect = { left: 0, top: 0, width: 0, height: 0 };
  10929. }
  10930. var x = rect.left - (html.clientLeft || body.clientLeft || 0),
  10931. y = rect.top - (html.clientTop || body.clientTop || 0);
  10932. if (!viewport) {
  10933. var view = doc.defaultView;
  10934. x += view.pageXOffset || html.scrollLeft || body.scrollLeft;
  10935. y += view.pageYOffset || html.scrollTop || body.scrollTop;
  10936. }
  10937. return new Rectangle(x, y, rect.width, rect.height);
  10938. },
  10939. getViewportBounds: function(el) {
  10940. var doc = el.ownerDocument,
  10941. view = doc.defaultView,
  10942. html = doc.documentElement;
  10943. return new Rectangle(0, 0,
  10944. view.innerWidth || html.clientWidth,
  10945. view.innerHeight || html.clientHeight
  10946. );
  10947. },
  10948. getOffset: function(el, viewport) {
  10949. return DomElement.getBounds(el, viewport).getPoint();
  10950. },
  10951. getSize: function(el) {
  10952. return DomElement.getBounds(el, true).getSize();
  10953. },
  10954. isInvisible: function(el) {
  10955. return DomElement.getSize(el).equals(new Size(0, 0));
  10956. },
  10957. isInView: function(el) {
  10958. return !DomElement.isInvisible(el)
  10959. && DomElement.getViewportBounds(el).intersects(
  10960. DomElement.getBounds(el, true));
  10961. },
  10962. isInserted: function(el) {
  10963. return document.body.contains(el);
  10964. },
  10965. getPrefixed: function(el, name) {
  10966. return el && handlePrefix(el, name);
  10967. },
  10968. setPrefixed: function(el, name, value) {
  10969. if (typeof name === 'object') {
  10970. for (var key in name)
  10971. handlePrefix(el, key, true, name[key]);
  10972. } else {
  10973. handlePrefix(el, name, true, value);
  10974. }
  10975. }
  10976. };
  10977. };
  10978. var DomEvent = {
  10979. add: function(el, events) {
  10980. if (el) {
  10981. for (var type in events) {
  10982. var func = events[type],
  10983. parts = type.split(/[\s,]+/g);
  10984. for (var i = 0, l = parts.length; i < l; i++)
  10985. el.addEventListener(parts[i], func, false);
  10986. }
  10987. }
  10988. },
  10989. remove: function(el, events) {
  10990. if (el) {
  10991. for (var type in events) {
  10992. var func = events[type],
  10993. parts = type.split(/[\s,]+/g);
  10994. for (var i = 0, l = parts.length; i < l; i++)
  10995. el.removeEventListener(parts[i], func, false);
  10996. }
  10997. }
  10998. },
  10999. getPoint: function(event) {
  11000. var pos = event.targetTouches
  11001. ? event.targetTouches.length
  11002. ? event.targetTouches[0]
  11003. : event.changedTouches[0]
  11004. : event;
  11005. return new Point(
  11006. pos.pageX || pos.clientX + document.documentElement.scrollLeft,
  11007. pos.pageY || pos.clientY + document.documentElement.scrollTop
  11008. );
  11009. },
  11010. getTarget: function(event) {
  11011. return event.target || event.srcElement;
  11012. },
  11013. getRelatedTarget: function(event) {
  11014. return event.relatedTarget || event.toElement;
  11015. },
  11016. getOffset: function(event, target) {
  11017. return DomEvent.getPoint(event).subtract(DomElement.getOffset(
  11018. target || DomEvent.getTarget(event)));
  11019. }
  11020. };
  11021. DomEvent.requestAnimationFrame = new function() {
  11022. var nativeRequest = DomElement.getPrefixed(window, 'requestAnimationFrame'),
  11023. requested = false,
  11024. callbacks = [],
  11025. timer;
  11026. function handleCallbacks() {
  11027. var functions = callbacks;
  11028. callbacks = [];
  11029. for (var i = 0, l = functions.length; i < l; i++)
  11030. functions[i]();
  11031. requested = nativeRequest && callbacks.length;
  11032. if (requested)
  11033. nativeRequest(handleCallbacks);
  11034. }
  11035. return function(callback) {
  11036. callbacks.push(callback);
  11037. if (nativeRequest) {
  11038. if (!requested) {
  11039. nativeRequest(handleCallbacks);
  11040. requested = true;
  11041. }
  11042. } else if (!timer) {
  11043. timer = setInterval(handleCallbacks, 1000 / 60);
  11044. }
  11045. };
  11046. };
  11047. var View = Base.extend(Emitter, {
  11048. _class: 'View',
  11049. initialize: function View(project, element) {
  11050. function getSize(name) {
  11051. return element[name] || parseInt(element.getAttribute(name), 10);
  11052. }
  11053. function getCanvasSize() {
  11054. var size = DomElement.getSize(element);
  11055. return size.isNaN() || size.isZero()
  11056. ? new Size(getSize('width'), getSize('height'))
  11057. : size;
  11058. }
  11059. var size;
  11060. if (window && element) {
  11061. this._id = element.getAttribute('id');
  11062. if (this._id == null)
  11063. element.setAttribute('id', this._id = 'view-' + View._id++);
  11064. DomEvent.add(element, this._viewEvents);
  11065. var none = 'none';
  11066. DomElement.setPrefixed(element.style, {
  11067. userDrag: none,
  11068. userSelect: none,
  11069. touchCallout: none,
  11070. contentZooming: none,
  11071. tapHighlightColor: 'rgba(0,0,0,0)'
  11072. });
  11073. if (PaperScope.hasAttribute(element, 'resize')) {
  11074. var that = this;
  11075. DomEvent.add(window, this._windowEvents = {
  11076. resize: function() {
  11077. that.setViewSize(getCanvasSize());
  11078. }
  11079. });
  11080. }
  11081. size = getCanvasSize();
  11082. if (PaperScope.hasAttribute(element, 'stats')
  11083. && typeof Stats !== 'undefined') {
  11084. this._stats = new Stats();
  11085. var stats = this._stats.domElement,
  11086. style = stats.style,
  11087. offset = DomElement.getOffset(element);
  11088. style.position = 'absolute';
  11089. style.left = offset.x + 'px';
  11090. style.top = offset.y + 'px';
  11091. document.body.appendChild(stats);
  11092. }
  11093. } else {
  11094. size = new Size(element);
  11095. element = null;
  11096. }
  11097. this._project = project;
  11098. this._scope = project._scope;
  11099. this._element = element;
  11100. if (!this._pixelRatio)
  11101. this._pixelRatio = window && window.devicePixelRatio || 1;
  11102. this._setElementSize(size.width, size.height);
  11103. this._viewSize = size;
  11104. View._views.push(this);
  11105. View._viewsById[this._id] = this;
  11106. (this._matrix = new Matrix())._owner = this;
  11107. if (!View._focused)
  11108. View._focused = this;
  11109. this._frameItems = {};
  11110. this._frameItemCount = 0;
  11111. this._itemEvents = { native: {}, virtual: {} };
  11112. this._autoUpdate = !paper.agent.node;
  11113. this._needsUpdate = false;
  11114. },
  11115. remove: function() {
  11116. if (!this._project)
  11117. return false;
  11118. if (View._focused === this)
  11119. View._focused = null;
  11120. View._views.splice(View._views.indexOf(this), 1);
  11121. delete View._viewsById[this._id];
  11122. var project = this._project;
  11123. if (project._view === this)
  11124. project._view = null;
  11125. DomEvent.remove(this._element, this._viewEvents);
  11126. DomEvent.remove(window, this._windowEvents);
  11127. this._element = this._project = null;
  11128. this.off('frame');
  11129. this._animate = false;
  11130. this._frameItems = {};
  11131. return true;
  11132. },
  11133. _events: Base.each(
  11134. Item._itemHandlers.concat(['onResize', 'onKeyDown', 'onKeyUp']),
  11135. function(name) {
  11136. this[name] = {};
  11137. }, {
  11138. onFrame: {
  11139. install: function() {
  11140. this.play();
  11141. },
  11142. uninstall: function() {
  11143. this.pause();
  11144. }
  11145. }
  11146. }
  11147. ),
  11148. _animate: false,
  11149. _time: 0,
  11150. _count: 0,
  11151. getAutoUpdate: function() {
  11152. return this._autoUpdate;
  11153. },
  11154. setAutoUpdate: function(autoUpdate) {
  11155. this._autoUpdate = autoUpdate;
  11156. if (autoUpdate)
  11157. this.requestUpdate();
  11158. },
  11159. update: function() {
  11160. },
  11161. draw: function() {
  11162. this.update();
  11163. },
  11164. requestUpdate: function() {
  11165. if (!this._requested) {
  11166. var that = this;
  11167. DomEvent.requestAnimationFrame(function() {
  11168. that._requested = false;
  11169. if (that._animate) {
  11170. that.requestUpdate();
  11171. var element = that._element;
  11172. if ((!DomElement.getPrefixed(document, 'hidden')
  11173. || PaperScope.getAttribute(element, 'keepalive')
  11174. === 'true') && DomElement.isInView(element)) {
  11175. that._handleFrame();
  11176. }
  11177. }
  11178. if (that._autoUpdate)
  11179. that.update();
  11180. });
  11181. this._requested = true;
  11182. }
  11183. },
  11184. play: function() {
  11185. this._animate = true;
  11186. this.requestUpdate();
  11187. },
  11188. pause: function() {
  11189. this._animate = false;
  11190. },
  11191. _handleFrame: function() {
  11192. paper = this._scope;
  11193. var now = Date.now() / 1000,
  11194. delta = this._last ? now - this._last : 0;
  11195. this._last = now;
  11196. this.emit('frame', new Base({
  11197. delta: delta,
  11198. time: this._time += delta,
  11199. count: this._count++
  11200. }));
  11201. if (this._stats)
  11202. this._stats.update();
  11203. },
  11204. _animateItem: function(item, animate) {
  11205. var items = this._frameItems;
  11206. if (animate) {
  11207. items[item._id] = {
  11208. item: item,
  11209. time: 0,
  11210. count: 0
  11211. };
  11212. if (++this._frameItemCount === 1)
  11213. this.on('frame', this._handleFrameItems);
  11214. } else {
  11215. delete items[item._id];
  11216. if (--this._frameItemCount === 0) {
  11217. this.off('frame', this._handleFrameItems);
  11218. }
  11219. }
  11220. },
  11221. _handleFrameItems: function(event) {
  11222. for (var i in this._frameItems) {
  11223. var entry = this._frameItems[i];
  11224. entry.item.emit('frame', new Base(event, {
  11225. time: entry.time += event.delta,
  11226. count: entry.count++
  11227. }));
  11228. }
  11229. },
  11230. _changed: function() {
  11231. this._project._changed(2049);
  11232. this._bounds = this._decomposed = undefined;
  11233. },
  11234. getElement: function() {
  11235. return this._element;
  11236. },
  11237. getPixelRatio: function() {
  11238. return this._pixelRatio;
  11239. },
  11240. getResolution: function() {
  11241. return this._pixelRatio * 72;
  11242. },
  11243. getViewSize: function() {
  11244. var size = this._viewSize;
  11245. return new LinkedSize(size.width, size.height, this, 'setViewSize');
  11246. },
  11247. setViewSize: function() {
  11248. var size = Size.read(arguments),
  11249. delta = size.subtract(this._viewSize);
  11250. if (delta.isZero())
  11251. return;
  11252. this._setElementSize(size.width, size.height);
  11253. this._viewSize.set(size);
  11254. this._changed();
  11255. this.emit('resize', { size: size, delta: delta });
  11256. if (this._autoUpdate) {
  11257. this.update();
  11258. }
  11259. },
  11260. _setElementSize: function(width, height) {
  11261. var element = this._element;
  11262. if (element) {
  11263. if (element.width !== width)
  11264. element.width = width;
  11265. if (element.height !== height)
  11266. element.height = height;
  11267. }
  11268. },
  11269. getBounds: function() {
  11270. if (!this._bounds)
  11271. this._bounds = this._matrix.inverted()._transformBounds(
  11272. new Rectangle(new Point(), this._viewSize));
  11273. return this._bounds;
  11274. },
  11275. getSize: function() {
  11276. return this.getBounds().getSize();
  11277. },
  11278. isVisible: function() {
  11279. return DomElement.isInView(this._element);
  11280. },
  11281. isInserted: function() {
  11282. return DomElement.isInserted(this._element);
  11283. },
  11284. getPixelSize: function(size) {
  11285. var element = this._element,
  11286. pixels;
  11287. if (element) {
  11288. var parent = element.parentNode,
  11289. temp = document.createElement('div');
  11290. temp.style.fontSize = size;
  11291. parent.appendChild(temp);
  11292. pixels = parseFloat(DomElement.getStyles(temp).fontSize);
  11293. parent.removeChild(temp);
  11294. } else {
  11295. pixels = parseFloat(pixels);
  11296. }
  11297. return pixels;
  11298. },
  11299. getTextWidth: function(font, lines) {
  11300. return 0;
  11301. }
  11302. }, Base.each(['rotate', 'scale', 'shear', 'skew'], function(key) {
  11303. var rotate = key === 'rotate';
  11304. this[key] = function() {
  11305. var value = (rotate ? Base : Point).read(arguments),
  11306. center = Point.read(arguments, 0, { readNull: true });
  11307. return this.transform(new Matrix()[key](value,
  11308. center || this.getCenter(true)));
  11309. };
  11310. }, {
  11311. _decompose: function() {
  11312. return this._decomposed || (this._decomposed = this._matrix.decompose());
  11313. },
  11314. translate: function() {
  11315. var mx = new Matrix();
  11316. return this.transform(mx.translate.apply(mx, arguments));
  11317. },
  11318. getCenter: function() {
  11319. return this.getBounds().getCenter();
  11320. },
  11321. setCenter: function() {
  11322. var center = Point.read(arguments);
  11323. this.translate(this.getCenter().subtract(center));
  11324. },
  11325. getZoom: function() {
  11326. var decomposed = this._decompose(),
  11327. scaling = decomposed && decomposed.scaling;
  11328. return scaling ? (scaling.x + scaling.y) / 2 : 0;
  11329. },
  11330. setZoom: function(zoom) {
  11331. this.transform(new Matrix().scale(zoom / this.getZoom(),
  11332. this.getCenter()));
  11333. },
  11334. getRotation: function() {
  11335. var decomposed = this._decompose();
  11336. return decomposed && decomposed.rotation;
  11337. },
  11338. setRotation: function(rotation) {
  11339. var current = this.getRotation();
  11340. if (current != null && rotation != null) {
  11341. this.rotate(rotation - current);
  11342. }
  11343. },
  11344. getScaling: function() {
  11345. var decomposed = this._decompose(),
  11346. scaling = decomposed && decomposed.scaling;
  11347. return scaling
  11348. ? new LinkedPoint(scaling.x, scaling.y, this, 'setScaling')
  11349. : undefined;
  11350. },
  11351. setScaling: function() {
  11352. var current = this.getScaling(),
  11353. scaling = Point.read(arguments, 0, { clone: true, readNull: true });
  11354. if (current && scaling) {
  11355. this.scale(scaling.x / current.x, scaling.y / current.y);
  11356. }
  11357. },
  11358. getMatrix: function() {
  11359. return this._matrix;
  11360. },
  11361. setMatrix: function() {
  11362. var matrix = this._matrix;
  11363. matrix.initialize.apply(matrix, arguments);
  11364. },
  11365. transform: function(matrix) {
  11366. this._matrix.append(matrix);
  11367. },
  11368. scrollBy: function() {
  11369. this.translate(Point.read(arguments).negate());
  11370. }
  11371. }), {
  11372. projectToView: function() {
  11373. return this._matrix._transformPoint(Point.read(arguments));
  11374. },
  11375. viewToProject: function() {
  11376. return this._matrix._inverseTransform(Point.read(arguments));
  11377. },
  11378. getEventPoint: function(event) {
  11379. return this.viewToProject(DomEvent.getOffset(event, this._element));
  11380. },
  11381. }, {
  11382. statics: {
  11383. _views: [],
  11384. _viewsById: {},
  11385. _id: 0,
  11386. create: function(project, element) {
  11387. if (document && typeof element === 'string')
  11388. element = document.getElementById(element);
  11389. var ctor = window ? CanvasView : View;
  11390. return new ctor(project, element);
  11391. }
  11392. }
  11393. },
  11394. new function() {
  11395. if (!window)
  11396. return;
  11397. var prevFocus,
  11398. tempFocus,
  11399. dragging = false,
  11400. mouseDown = false;
  11401. function getView(event) {
  11402. var target = DomEvent.getTarget(event);
  11403. return target.getAttribute && View._viewsById[
  11404. target.getAttribute('id')];
  11405. }
  11406. function updateFocus() {
  11407. var view = View._focused;
  11408. if (!view || !view.isVisible()) {
  11409. for (var i = 0, l = View._views.length; i < l; i++) {
  11410. if ((view = View._views[i]).isVisible()) {
  11411. View._focused = tempFocus = view;
  11412. break;
  11413. }
  11414. }
  11415. }
  11416. }
  11417. function handleMouseMove(view, event, point) {
  11418. view._handleMouseEvent('mousemove', event, point);
  11419. }
  11420. var navigator = window.navigator,
  11421. mousedown, mousemove, mouseup;
  11422. if (navigator.pointerEnabled || navigator.msPointerEnabled) {
  11423. mousedown = 'pointerdown MSPointerDown';
  11424. mousemove = 'pointermove MSPointerMove';
  11425. mouseup = 'pointerup pointercancel MSPointerUp MSPointerCancel';
  11426. } else {
  11427. mousedown = 'touchstart';
  11428. mousemove = 'touchmove';
  11429. mouseup = 'touchend touchcancel';
  11430. if (!('ontouchstart' in window && navigator.userAgent.match(
  11431. /mobile|tablet|ip(ad|hone|od)|android|silk/i))) {
  11432. mousedown += ' mousedown';
  11433. mousemove += ' mousemove';
  11434. mouseup += ' mouseup';
  11435. }
  11436. }
  11437. var viewEvents = {},
  11438. docEvents = {
  11439. mouseout: function(event) {
  11440. var view = View._focused,
  11441. target = DomEvent.getRelatedTarget(event);
  11442. if (view && (!target || target.nodeName === 'HTML')) {
  11443. var offset = DomEvent.getOffset(event, view._element),
  11444. x = offset.x,
  11445. abs = Math.abs,
  11446. ax = abs(x),
  11447. max = 1 << 25,
  11448. diff = ax - max;
  11449. offset.x = abs(diff) < ax ? diff * (x < 0 ? -1 : 1) : x;
  11450. handleMouseMove(view, event, view.viewToProject(offset));
  11451. }
  11452. },
  11453. scroll: updateFocus
  11454. };
  11455. viewEvents[mousedown] = function(event) {
  11456. var view = View._focused = getView(event);
  11457. if (!dragging) {
  11458. dragging = true;
  11459. view._handleMouseEvent('mousedown', event);
  11460. }
  11461. };
  11462. docEvents[mousemove] = function(event) {
  11463. var view = View._focused;
  11464. if (!mouseDown) {
  11465. var target = getView(event);
  11466. if (target) {
  11467. if (view !== target) {
  11468. if (view)
  11469. handleMouseMove(view, event);
  11470. if (!prevFocus)
  11471. prevFocus = view;
  11472. view = View._focused = tempFocus = target;
  11473. }
  11474. } else if (tempFocus && tempFocus === view) {
  11475. if (prevFocus && !prevFocus.isInserted())
  11476. prevFocus = null;
  11477. view = View._focused = prevFocus;
  11478. prevFocus = null;
  11479. updateFocus();
  11480. }
  11481. }
  11482. if (view)
  11483. handleMouseMove(view, event);
  11484. };
  11485. docEvents[mousedown] = function() {
  11486. mouseDown = true;
  11487. };
  11488. docEvents[mouseup] = function(event) {
  11489. var view = View._focused;
  11490. if (view && dragging)
  11491. view._handleMouseEvent('mouseup', event);
  11492. mouseDown = dragging = false;
  11493. };
  11494. DomEvent.add(document, docEvents);
  11495. DomEvent.add(window, {
  11496. load: updateFocus
  11497. });
  11498. var called = false,
  11499. prevented = false,
  11500. fallbacks = {
  11501. doubleclick: 'click',
  11502. mousedrag: 'mousemove'
  11503. },
  11504. wasInView = false,
  11505. overView,
  11506. downPoint,
  11507. lastPoint,
  11508. downItem,
  11509. overItem,
  11510. dragItem,
  11511. clickItem,
  11512. clickTime,
  11513. dblClick;
  11514. function emitMouseEvent(obj, target, type, event, point, prevPoint,
  11515. stopItem) {
  11516. var stopped = false,
  11517. mouseEvent;
  11518. function emit(obj, type) {
  11519. if (obj.responds(type)) {
  11520. if (!mouseEvent) {
  11521. mouseEvent = new MouseEvent(type, event, point,
  11522. target || obj,
  11523. prevPoint ? point.subtract(prevPoint) : null);
  11524. }
  11525. if (obj.emit(type, mouseEvent)) {
  11526. called = true;
  11527. if (mouseEvent.prevented)
  11528. prevented = true;
  11529. if (mouseEvent.stopped)
  11530. return stopped = true;
  11531. }
  11532. } else {
  11533. var fallback = fallbacks[type];
  11534. if (fallback)
  11535. return emit(obj, fallback);
  11536. }
  11537. }
  11538. while (obj && obj !== stopItem) {
  11539. if (emit(obj, type))
  11540. break;
  11541. obj = obj._parent;
  11542. }
  11543. return stopped;
  11544. }
  11545. function emitMouseEvents(view, hitItem, type, event, point, prevPoint) {
  11546. view._project.removeOn(type);
  11547. prevented = called = false;
  11548. return (dragItem && emitMouseEvent(dragItem, null, type, event,
  11549. point, prevPoint)
  11550. || hitItem && hitItem !== dragItem
  11551. && !hitItem.isDescendant(dragItem)
  11552. && emitMouseEvent(hitItem, null, type, event, point, prevPoint,
  11553. dragItem)
  11554. || emitMouseEvent(view, dragItem || hitItem || view, type, event,
  11555. point, prevPoint));
  11556. }
  11557. var itemEventsMap = {
  11558. mousedown: {
  11559. mousedown: 1,
  11560. mousedrag: 1,
  11561. click: 1,
  11562. doubleclick: 1
  11563. },
  11564. mouseup: {
  11565. mouseup: 1,
  11566. mousedrag: 1,
  11567. click: 1,
  11568. doubleclick: 1
  11569. },
  11570. mousemove: {
  11571. mousedrag: 1,
  11572. mousemove: 1,
  11573. mouseenter: 1,
  11574. mouseleave: 1
  11575. }
  11576. };
  11577. return {
  11578. _viewEvents: viewEvents,
  11579. _handleMouseEvent: function(type, event, point) {
  11580. var itemEvents = this._itemEvents,
  11581. hitItems = itemEvents.native[type],
  11582. nativeMove = type === 'mousemove',
  11583. tool = this._scope.tool,
  11584. view = this;
  11585. function responds(type) {
  11586. return itemEvents.virtual[type] || view.responds(type)
  11587. || tool && tool.responds(type);
  11588. }
  11589. if (nativeMove && dragging && responds('mousedrag'))
  11590. type = 'mousedrag';
  11591. if (!point)
  11592. point = this.getEventPoint(event);
  11593. var inView = this.getBounds().contains(point),
  11594. hit = hitItems && inView && view._project.hitTest(point, {
  11595. tolerance: 0,
  11596. fill: true,
  11597. stroke: true
  11598. }),
  11599. hitItem = hit && hit.item || null,
  11600. handle = false,
  11601. mouse = {};
  11602. mouse[type.substr(5)] = true;
  11603. if (hitItems && hitItem !== overItem) {
  11604. if (overItem) {
  11605. emitMouseEvent(overItem, null, 'mouseleave', event, point);
  11606. }
  11607. if (hitItem) {
  11608. emitMouseEvent(hitItem, null, 'mouseenter', event, point);
  11609. }
  11610. overItem = hitItem;
  11611. }
  11612. if (wasInView ^ inView) {
  11613. emitMouseEvent(this, null, inView ? 'mouseenter' : 'mouseleave',
  11614. event, point);
  11615. overView = inView ? this : null;
  11616. handle = true;
  11617. }
  11618. if ((inView || mouse.drag) && !point.equals(lastPoint)) {
  11619. emitMouseEvents(this, hitItem, nativeMove ? type : 'mousemove',
  11620. event, point, lastPoint);
  11621. handle = true;
  11622. }
  11623. wasInView = inView;
  11624. if (mouse.down && inView || mouse.up && downPoint) {
  11625. emitMouseEvents(this, hitItem, type, event, point, downPoint);
  11626. if (mouse.down) {
  11627. dblClick = hitItem === clickItem
  11628. && (Date.now() - clickTime < 300);
  11629. downItem = clickItem = hitItem;
  11630. if (!prevented && hitItem) {
  11631. var item = hitItem;
  11632. while (item && !item.responds('mousedrag'))
  11633. item = item._parent;
  11634. if (item)
  11635. dragItem = hitItem;
  11636. }
  11637. downPoint = point;
  11638. } else if (mouse.up) {
  11639. if (!prevented && hitItem === downItem) {
  11640. clickTime = Date.now();
  11641. emitMouseEvents(this, hitItem, dblClick ? 'doubleclick'
  11642. : 'click', event, point, downPoint);
  11643. dblClick = false;
  11644. }
  11645. downItem = dragItem = null;
  11646. }
  11647. wasInView = false;
  11648. handle = true;
  11649. }
  11650. lastPoint = point;
  11651. if (handle && tool) {
  11652. called = tool._handleMouseEvent(type, event, point, mouse)
  11653. || called;
  11654. }
  11655. if (called && !mouse.move || mouse.down && responds('mouseup'))
  11656. event.preventDefault();
  11657. },
  11658. _handleKeyEvent: function(type, event, key, character) {
  11659. var scope = this._scope,
  11660. tool = scope.tool,
  11661. keyEvent;
  11662. function emit(obj) {
  11663. if (obj.responds(type)) {
  11664. paper = scope;
  11665. obj.emit(type, keyEvent = keyEvent
  11666. || new KeyEvent(type, event, key, character));
  11667. }
  11668. }
  11669. if (this.isVisible()) {
  11670. emit(this);
  11671. if (tool && tool.responds(type))
  11672. emit(tool);
  11673. }
  11674. },
  11675. _countItemEvent: function(type, sign) {
  11676. var itemEvents = this._itemEvents,
  11677. native = itemEvents.native,
  11678. virtual = itemEvents.virtual;
  11679. for (var key in itemEventsMap) {
  11680. native[key] = (native[key] || 0)
  11681. + (itemEventsMap[key][type] || 0) * sign;
  11682. }
  11683. virtual[type] = (virtual[type] || 0) + sign;
  11684. },
  11685. statics: {
  11686. updateFocus: updateFocus
  11687. }
  11688. };
  11689. });
  11690. var CanvasView = View.extend({
  11691. _class: 'CanvasView',
  11692. initialize: function CanvasView(project, canvas) {
  11693. if (!(canvas instanceof window.HTMLCanvasElement)) {
  11694. var size = Size.read(arguments, 1);
  11695. if (size.isZero())
  11696. throw new Error(
  11697. 'Cannot create CanvasView with the provided argument: '
  11698. + Base.slice(arguments, 1));
  11699. canvas = CanvasProvider.getCanvas(size);
  11700. }
  11701. var ctx = this._context = canvas.getContext('2d');
  11702. ctx.save();
  11703. this._pixelRatio = 1;
  11704. if (!/^off|false$/.test(PaperScope.getAttribute(canvas, 'hidpi'))) {
  11705. var deviceRatio = window.devicePixelRatio || 1,
  11706. backingStoreRatio = DomElement.getPrefixed(ctx,
  11707. 'backingStorePixelRatio') || 1;
  11708. this._pixelRatio = deviceRatio / backingStoreRatio;
  11709. }
  11710. View.call(this, project, canvas);
  11711. this._needsUpdate = true;
  11712. },
  11713. remove: function remove() {
  11714. this._context.restore();
  11715. return remove.base.call(this);
  11716. },
  11717. _setElementSize: function _setElementSize(width, height) {
  11718. var pixelRatio = this._pixelRatio;
  11719. _setElementSize.base.call(this, width * pixelRatio, height * pixelRatio);
  11720. if (pixelRatio !== 1) {
  11721. var element = this._element,
  11722. ctx = this._context;
  11723. if (!PaperScope.hasAttribute(element, 'resize')) {
  11724. var style = element.style;
  11725. style.width = width + 'px';
  11726. style.height = height + 'px';
  11727. }
  11728. ctx.restore();
  11729. ctx.save();
  11730. ctx.scale(pixelRatio, pixelRatio);
  11731. }
  11732. },
  11733. getPixelSize: function getPixelSize(size) {
  11734. var agent = paper.agent,
  11735. pixels;
  11736. if (agent && agent.firefox) {
  11737. pixels = getPixelSize.base.call(this, size);
  11738. } else {
  11739. var ctx = this._context,
  11740. prevFont = ctx.font;
  11741. ctx.font = size + ' serif';
  11742. pixels = parseFloat(ctx.font);
  11743. ctx.font = prevFont;
  11744. }
  11745. return pixels;
  11746. },
  11747. getTextWidth: function(font, lines) {
  11748. var ctx = this._context,
  11749. prevFont = ctx.font,
  11750. width = 0;
  11751. ctx.font = font;
  11752. for (var i = 0, l = lines.length; i < l; i++)
  11753. width = Math.max(width, ctx.measureText(lines[i]).width);
  11754. ctx.font = prevFont;
  11755. return width;
  11756. },
  11757. update: function() {
  11758. if (!this._needsUpdate)
  11759. return false;
  11760. var project = this._project,
  11761. ctx = this._context,
  11762. size = this._viewSize;
  11763. ctx.clearRect(0, 0, size.width + 1, size.height + 1);
  11764. if (project)
  11765. project.draw(ctx, this._matrix, this._pixelRatio);
  11766. this._needsUpdate = false;
  11767. return true;
  11768. }
  11769. });
  11770. var Event = Base.extend({
  11771. _class: 'Event',
  11772. initialize: function Event(event) {
  11773. this.event = event;
  11774. this.type = event && event.type;
  11775. },
  11776. prevented: false,
  11777. stopped: false,
  11778. preventDefault: function() {
  11779. this.prevented = true;
  11780. this.event.preventDefault();
  11781. },
  11782. stopPropagation: function() {
  11783. this.stopped = true;
  11784. this.event.stopPropagation();
  11785. },
  11786. stop: function() {
  11787. this.stopPropagation();
  11788. this.preventDefault();
  11789. },
  11790. getTimeStamp: function() {
  11791. return this.event.timeStamp;
  11792. },
  11793. getModifiers: function() {
  11794. return Key.modifiers;
  11795. }
  11796. });
  11797. var KeyEvent = Event.extend({
  11798. _class: 'KeyEvent',
  11799. initialize: function KeyEvent(type, event, key, character) {
  11800. this.type = type;
  11801. this.event = event;
  11802. this.key = key;
  11803. this.character = character;
  11804. },
  11805. toString: function() {
  11806. return "{ type: '" + this.type
  11807. + "', key: '" + this.key
  11808. + "', character: '" + this.character
  11809. + "', modifiers: " + this.getModifiers()
  11810. + " }";
  11811. }
  11812. });
  11813. var Key = new function() {
  11814. var keyLookup = {
  11815. '\t': 'tab',
  11816. ' ': 'space',
  11817. '\b': 'backspace',
  11818. '\x7f': 'delete',
  11819. 'Spacebar': 'space',
  11820. 'Del': 'delete',
  11821. 'Win': 'meta',
  11822. 'Esc': 'escape'
  11823. },
  11824. charLookup = {
  11825. 'tab': '\t',
  11826. 'space': ' ',
  11827. 'enter': '\r'
  11828. },
  11829. keyMap = {},
  11830. charMap = {},
  11831. metaFixMap,
  11832. downKey,
  11833. modifiers = new Base({
  11834. shift: false,
  11835. control: false,
  11836. alt: false,
  11837. meta: false,
  11838. capsLock: false,
  11839. space: false
  11840. }).inject({
  11841. option: {
  11842. get: function() {
  11843. return this.alt;
  11844. }
  11845. },
  11846. command: {
  11847. get: function() {
  11848. var agent = paper && paper.agent;
  11849. return agent && agent.mac ? this.meta : this.control;
  11850. }
  11851. }
  11852. });
  11853. function getKey(event) {
  11854. var key = event.key || event.keyIdentifier;
  11855. key = /^U\+/.test(key)
  11856. ? String.fromCharCode(parseInt(key.substr(2), 16))
  11857. : /^Arrow[A-Z]/.test(key) ? key.substr(5)
  11858. : key === 'Unidentified' || key === undefined
  11859. ? String.fromCharCode(event.keyCode)
  11860. : key;
  11861. return keyLookup[key] ||
  11862. (key.length > 1 ? Base.hyphenate(key) : key.toLowerCase());
  11863. }
  11864. function handleKey(down, key, character, event) {
  11865. var type = down ? 'keydown' : 'keyup',
  11866. view = View._focused,
  11867. name;
  11868. keyMap[key] = down;
  11869. if (down) {
  11870. charMap[key] = character;
  11871. } else {
  11872. delete charMap[key];
  11873. }
  11874. if (key.length > 1 && (name = Base.camelize(key)) in modifiers) {
  11875. modifiers[name] = down;
  11876. var agent = paper && paper.agent;
  11877. if (name === 'meta' && agent && agent.mac) {
  11878. if (down) {
  11879. metaFixMap = {};
  11880. } else {
  11881. for (var k in metaFixMap) {
  11882. if (k in charMap)
  11883. handleKey(false, k, metaFixMap[k], event);
  11884. }
  11885. metaFixMap = null;
  11886. }
  11887. }
  11888. } else if (down && metaFixMap) {
  11889. metaFixMap[key] = character;
  11890. }
  11891. if (view) {
  11892. view._handleKeyEvent(down ? 'keydown' : 'keyup', event, key,
  11893. character);
  11894. }
  11895. }
  11896. DomEvent.add(document, {
  11897. keydown: function(event) {
  11898. var key = getKey(event),
  11899. agent = paper && paper.agent;
  11900. if (key.length > 1 || agent && (agent.chrome && (event.altKey
  11901. || agent.mac && event.metaKey
  11902. || !agent.mac && event.ctrlKey))) {
  11903. handleKey(true, key,
  11904. charLookup[key] || (key.length > 1 ? '' : key), event);
  11905. } else {
  11906. downKey = key;
  11907. }
  11908. },
  11909. keypress: function(event) {
  11910. if (downKey) {
  11911. var key = getKey(event),
  11912. code = event.charCode,
  11913. character = code >= 32 ? String.fromCharCode(code)
  11914. : key.length > 1 ? '' : key;
  11915. if (key !== downKey) {
  11916. key = character.toLowerCase();
  11917. }
  11918. handleKey(true, key, character, event);
  11919. downKey = null;
  11920. }
  11921. },
  11922. keyup: function(event) {
  11923. var key = getKey(event);
  11924. if (key in charMap)
  11925. handleKey(false, key, charMap[key], event);
  11926. }
  11927. });
  11928. DomEvent.add(window, {
  11929. blur: function(event) {
  11930. for (var key in charMap)
  11931. handleKey(false, key, charMap[key], event);
  11932. }
  11933. });
  11934. return {
  11935. modifiers: modifiers,
  11936. isDown: function(key) {
  11937. return !!keyMap[key];
  11938. }
  11939. };
  11940. };
  11941. var MouseEvent = Event.extend({
  11942. _class: 'MouseEvent',
  11943. initialize: function MouseEvent(type, event, point, target, delta) {
  11944. this.type = type;
  11945. this.event = event;
  11946. this.point = point;
  11947. this.target = target;
  11948. this.delta = delta;
  11949. },
  11950. toString: function() {
  11951. return "{ type: '" + this.type
  11952. + "', point: " + this.point
  11953. + ', target: ' + this.target
  11954. + (this.delta ? ', delta: ' + this.delta : '')
  11955. + ', modifiers: ' + this.getModifiers()
  11956. + ' }';
  11957. }
  11958. });
  11959. var ToolEvent = Event.extend({
  11960. _class: 'ToolEvent',
  11961. _item: null,
  11962. initialize: function ToolEvent(tool, type, event) {
  11963. this.tool = tool;
  11964. this.type = type;
  11965. this.event = event;
  11966. },
  11967. _choosePoint: function(point, toolPoint) {
  11968. return point ? point : toolPoint ? toolPoint.clone() : null;
  11969. },
  11970. getPoint: function() {
  11971. return this._choosePoint(this._point, this.tool._point);
  11972. },
  11973. setPoint: function(point) {
  11974. this._point = point;
  11975. },
  11976. getLastPoint: function() {
  11977. return this._choosePoint(this._lastPoint, this.tool._lastPoint);
  11978. },
  11979. setLastPoint: function(lastPoint) {
  11980. this._lastPoint = lastPoint;
  11981. },
  11982. getDownPoint: function() {
  11983. return this._choosePoint(this._downPoint, this.tool._downPoint);
  11984. },
  11985. setDownPoint: function(downPoint) {
  11986. this._downPoint = downPoint;
  11987. },
  11988. getMiddlePoint: function() {
  11989. if (!this._middlePoint && this.tool._lastPoint) {
  11990. return this.tool._point.add(this.tool._lastPoint).divide(2);
  11991. }
  11992. return this._middlePoint;
  11993. },
  11994. setMiddlePoint: function(middlePoint) {
  11995. this._middlePoint = middlePoint;
  11996. },
  11997. getDelta: function() {
  11998. return !this._delta && this.tool._lastPoint
  11999. ? this.tool._point.subtract(this.tool._lastPoint)
  12000. : this._delta;
  12001. },
  12002. setDelta: function(delta) {
  12003. this._delta = delta;
  12004. },
  12005. getCount: function() {
  12006. return this.tool[/^mouse(down|up)$/.test(this.type)
  12007. ? '_downCount' : '_moveCount'];
  12008. },
  12009. setCount: function(count) {
  12010. this.tool[/^mouse(down|up)$/.test(this.type) ? 'downCount' : 'count']
  12011. = count;
  12012. },
  12013. getItem: function() {
  12014. if (!this._item) {
  12015. var result = this.tool._scope.project.hitTest(this.getPoint());
  12016. if (result) {
  12017. var item = result.item,
  12018. parent = item._parent;
  12019. while (/^(Group|CompoundPath)$/.test(parent._class)) {
  12020. item = parent;
  12021. parent = parent._parent;
  12022. }
  12023. this._item = item;
  12024. }
  12025. }
  12026. return this._item;
  12027. },
  12028. setItem: function(item) {
  12029. this._item = item;
  12030. },
  12031. toString: function() {
  12032. return '{ type: ' + this.type
  12033. + ', point: ' + this.getPoint()
  12034. + ', count: ' + this.getCount()
  12035. + ', modifiers: ' + this.getModifiers()
  12036. + ' }';
  12037. }
  12038. });
  12039. var Tool = PaperScopeItem.extend({
  12040. _class: 'Tool',
  12041. _list: 'tools',
  12042. _reference: 'tool',
  12043. _events: ['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onMouseMove',
  12044. 'onActivate', 'onDeactivate', 'onEditOptions', 'onKeyDown',
  12045. 'onKeyUp'],
  12046. initialize: function Tool(props) {
  12047. PaperScopeItem.call(this);
  12048. this._moveCount = -1;
  12049. this._downCount = -1;
  12050. this.set(props);
  12051. },
  12052. getMinDistance: function() {
  12053. return this._minDistance;
  12054. },
  12055. setMinDistance: function(minDistance) {
  12056. this._minDistance = minDistance;
  12057. if (minDistance != null && this._maxDistance != null
  12058. && minDistance > this._maxDistance) {
  12059. this._maxDistance = minDistance;
  12060. }
  12061. },
  12062. getMaxDistance: function() {
  12063. return this._maxDistance;
  12064. },
  12065. setMaxDistance: function(maxDistance) {
  12066. this._maxDistance = maxDistance;
  12067. if (this._minDistance != null && maxDistance != null
  12068. && maxDistance < this._minDistance) {
  12069. this._minDistance = maxDistance;
  12070. }
  12071. },
  12072. getFixedDistance: function() {
  12073. return this._minDistance == this._maxDistance
  12074. ? this._minDistance : null;
  12075. },
  12076. setFixedDistance: function(distance) {
  12077. this._minDistance = this._maxDistance = distance;
  12078. },
  12079. _handleMouseEvent: function(type, event, point, mouse) {
  12080. paper = this._scope;
  12081. if (mouse.drag && !this.responds(type))
  12082. type = 'mousemove';
  12083. var move = mouse.move || mouse.drag,
  12084. responds = this.responds(type),
  12085. minDistance = this.minDistance,
  12086. maxDistance = this.maxDistance,
  12087. called = false,
  12088. tool = this;
  12089. function update(minDistance, maxDistance) {
  12090. var pt = point,
  12091. toolPoint = move ? tool._point : (tool._downPoint || pt);
  12092. if (move) {
  12093. if (tool._moveCount && pt.equals(toolPoint)) {
  12094. return false;
  12095. }
  12096. if (toolPoint && (minDistance != null || maxDistance != null)) {
  12097. var vector = pt.subtract(toolPoint),
  12098. distance = vector.getLength();
  12099. if (distance < (minDistance || 0))
  12100. return false;
  12101. if (maxDistance) {
  12102. pt = toolPoint.add(vector.normalize(
  12103. Math.min(distance, maxDistance)));
  12104. }
  12105. }
  12106. tool._moveCount++;
  12107. }
  12108. tool._point = pt;
  12109. tool._lastPoint = toolPoint || pt;
  12110. if (mouse.down) {
  12111. tool._moveCount = -1;
  12112. tool._downPoint = pt;
  12113. tool._downCount++;
  12114. }
  12115. return true;
  12116. }
  12117. function emit() {
  12118. if (responds) {
  12119. called = tool.emit(type, new ToolEvent(tool, type, event))
  12120. || called;
  12121. }
  12122. }
  12123. if (mouse.down) {
  12124. update();
  12125. emit();
  12126. } else if (mouse.up) {
  12127. update(null, maxDistance);
  12128. emit();
  12129. } else if (responds) {
  12130. while (update(minDistance, maxDistance))
  12131. emit();
  12132. }
  12133. return called;
  12134. }
  12135. });
  12136. var Http = {
  12137. request: function(options) {
  12138. var xhr = new self.XMLHttpRequest();
  12139. xhr.open((options.method || 'get').toUpperCase(), options.url,
  12140. Base.pick(options.async, true));
  12141. if (options.mimeType)
  12142. xhr.overrideMimeType(options.mimeType);
  12143. xhr.onload = function() {
  12144. var status = xhr.status;
  12145. if (status === 0 || status === 200) {
  12146. if (options.onLoad) {
  12147. options.onLoad.call(xhr, xhr.responseText);
  12148. }
  12149. } else {
  12150. xhr.onerror();
  12151. }
  12152. };
  12153. xhr.onerror = function() {
  12154. var status = xhr.status,
  12155. message = 'Could not load "' + options.url + '" (Status: '
  12156. + status + ')';
  12157. if (options.onError) {
  12158. options.onError(message, status);
  12159. } else {
  12160. throw new Error(message);
  12161. }
  12162. };
  12163. return xhr.send(null);
  12164. }
  12165. };
  12166. var CanvasProvider = {
  12167. canvases: [],
  12168. getCanvas: function(width, height) {
  12169. if (!window)
  12170. return null;
  12171. var canvas,
  12172. clear = true;
  12173. if (typeof width === 'object') {
  12174. height = width.height;
  12175. width = width.width;
  12176. }
  12177. if (this.canvases.length) {
  12178. canvas = this.canvases.pop();
  12179. } else {
  12180. canvas = document.createElement('canvas');
  12181. clear = false;
  12182. }
  12183. var ctx = canvas.getContext('2d');
  12184. if (!ctx) {
  12185. throw new Error('Canvas ' + canvas +
  12186. ' is unable to provide a 2D context.');
  12187. }
  12188. if (canvas.width === width && canvas.height === height) {
  12189. if (clear)
  12190. ctx.clearRect(0, 0, width + 1, height + 1);
  12191. } else {
  12192. canvas.width = width;
  12193. canvas.height = height;
  12194. }
  12195. ctx.save();
  12196. return canvas;
  12197. },
  12198. getContext: function(width, height) {
  12199. var canvas = this.getCanvas(width, height);
  12200. return canvas ? canvas.getContext('2d') : null;
  12201. },
  12202. release: function(obj) {
  12203. var canvas = obj && obj.canvas ? obj.canvas : obj;
  12204. if (canvas && canvas.getContext) {
  12205. canvas.getContext('2d').restore();
  12206. this.canvases.push(canvas);
  12207. }
  12208. }
  12209. };
  12210. var BlendMode = new function() {
  12211. var min = Math.min,
  12212. max = Math.max,
  12213. abs = Math.abs,
  12214. sr, sg, sb, sa,
  12215. br, bg, bb, ba,
  12216. dr, dg, db;
  12217. function getLum(r, g, b) {
  12218. return 0.2989 * r + 0.587 * g + 0.114 * b;
  12219. }
  12220. function setLum(r, g, b, l) {
  12221. var d = l - getLum(r, g, b);
  12222. dr = r + d;
  12223. dg = g + d;
  12224. db = b + d;
  12225. var l = getLum(dr, dg, db),
  12226. mn = min(dr, dg, db),
  12227. mx = max(dr, dg, db);
  12228. if (mn < 0) {
  12229. var lmn = l - mn;
  12230. dr = l + (dr - l) * l / lmn;
  12231. dg = l + (dg - l) * l / lmn;
  12232. db = l + (db - l) * l / lmn;
  12233. }
  12234. if (mx > 255) {
  12235. var ln = 255 - l,
  12236. mxl = mx - l;
  12237. dr = l + (dr - l) * ln / mxl;
  12238. dg = l + (dg - l) * ln / mxl;
  12239. db = l + (db - l) * ln / mxl;
  12240. }
  12241. }
  12242. function getSat(r, g, b) {
  12243. return max(r, g, b) - min(r, g, b);
  12244. }
  12245. function setSat(r, g, b, s) {
  12246. var col = [r, g, b],
  12247. mx = max(r, g, b),
  12248. mn = min(r, g, b),
  12249. md;
  12250. mn = mn === r ? 0 : mn === g ? 1 : 2;
  12251. mx = mx === r ? 0 : mx === g ? 1 : 2;
  12252. md = min(mn, mx) === 0 ? max(mn, mx) === 1 ? 2 : 1 : 0;
  12253. if (col[mx] > col[mn]) {
  12254. col[md] = (col[md] - col[mn]) * s / (col[mx] - col[mn]);
  12255. col[mx] = s;
  12256. } else {
  12257. col[md] = col[mx] = 0;
  12258. }
  12259. col[mn] = 0;
  12260. dr = col[0];
  12261. dg = col[1];
  12262. db = col[2];
  12263. }
  12264. var modes = {
  12265. multiply: function() {
  12266. dr = br * sr / 255;
  12267. dg = bg * sg / 255;
  12268. db = bb * sb / 255;
  12269. },
  12270. screen: function() {
  12271. dr = br + sr - (br * sr / 255);
  12272. dg = bg + sg - (bg * sg / 255);
  12273. db = bb + sb - (bb * sb / 255);
  12274. },
  12275. overlay: function() {
  12276. dr = br < 128 ? 2 * br * sr / 255 : 255 - 2 * (255 - br) * (255 - sr) / 255;
  12277. dg = bg < 128 ? 2 * bg * sg / 255 : 255 - 2 * (255 - bg) * (255 - sg) / 255;
  12278. db = bb < 128 ? 2 * bb * sb / 255 : 255 - 2 * (255 - bb) * (255 - sb) / 255;
  12279. },
  12280. 'soft-light': function() {
  12281. var t = sr * br / 255;
  12282. dr = t + br * (255 - (255 - br) * (255 - sr) / 255 - t) / 255;
  12283. t = sg * bg / 255;
  12284. dg = t + bg * (255 - (255 - bg) * (255 - sg) / 255 - t) / 255;
  12285. t = sb * bb / 255;
  12286. db = t + bb * (255 - (255 - bb) * (255 - sb) / 255 - t) / 255;
  12287. },
  12288. 'hard-light': function() {
  12289. dr = sr < 128 ? 2 * sr * br / 255 : 255 - 2 * (255 - sr) * (255 - br) / 255;
  12290. dg = sg < 128 ? 2 * sg * bg / 255 : 255 - 2 * (255 - sg) * (255 - bg) / 255;
  12291. db = sb < 128 ? 2 * sb * bb / 255 : 255 - 2 * (255 - sb) * (255 - bb) / 255;
  12292. },
  12293. 'color-dodge': function() {
  12294. dr = br === 0 ? 0 : sr === 255 ? 255 : min(255, 255 * br / (255 - sr));
  12295. dg = bg === 0 ? 0 : sg === 255 ? 255 : min(255, 255 * bg / (255 - sg));
  12296. db = bb === 0 ? 0 : sb === 255 ? 255 : min(255, 255 * bb / (255 - sb));
  12297. },
  12298. 'color-burn': function() {
  12299. dr = br === 255 ? 255 : sr === 0 ? 0 : max(0, 255 - (255 - br) * 255 / sr);
  12300. dg = bg === 255 ? 255 : sg === 0 ? 0 : max(0, 255 - (255 - bg) * 255 / sg);
  12301. db = bb === 255 ? 255 : sb === 0 ? 0 : max(0, 255 - (255 - bb) * 255 / sb);
  12302. },
  12303. darken: function() {
  12304. dr = br < sr ? br : sr;
  12305. dg = bg < sg ? bg : sg;
  12306. db = bb < sb ? bb : sb;
  12307. },
  12308. lighten: function() {
  12309. dr = br > sr ? br : sr;
  12310. dg = bg > sg ? bg : sg;
  12311. db = bb > sb ? bb : sb;
  12312. },
  12313. difference: function() {
  12314. dr = br - sr;
  12315. if (dr < 0)
  12316. dr = -dr;
  12317. dg = bg - sg;
  12318. if (dg < 0)
  12319. dg = -dg;
  12320. db = bb - sb;
  12321. if (db < 0)
  12322. db = -db;
  12323. },
  12324. exclusion: function() {
  12325. dr = br + sr * (255 - br - br) / 255;
  12326. dg = bg + sg * (255 - bg - bg) / 255;
  12327. db = bb + sb * (255 - bb - bb) / 255;
  12328. },
  12329. hue: function() {
  12330. setSat(sr, sg, sb, getSat(br, bg, bb));
  12331. setLum(dr, dg, db, getLum(br, bg, bb));
  12332. },
  12333. saturation: function() {
  12334. setSat(br, bg, bb, getSat(sr, sg, sb));
  12335. setLum(dr, dg, db, getLum(br, bg, bb));
  12336. },
  12337. luminosity: function() {
  12338. setLum(br, bg, bb, getLum(sr, sg, sb));
  12339. },
  12340. color: function() {
  12341. setLum(sr, sg, sb, getLum(br, bg, bb));
  12342. },
  12343. add: function() {
  12344. dr = min(br + sr, 255);
  12345. dg = min(bg + sg, 255);
  12346. db = min(bb + sb, 255);
  12347. },
  12348. subtract: function() {
  12349. dr = max(br - sr, 0);
  12350. dg = max(bg - sg, 0);
  12351. db = max(bb - sb, 0);
  12352. },
  12353. average: function() {
  12354. dr = (br + sr) / 2;
  12355. dg = (bg + sg) / 2;
  12356. db = (bb + sb) / 2;
  12357. },
  12358. negation: function() {
  12359. dr = 255 - abs(255 - sr - br);
  12360. dg = 255 - abs(255 - sg - bg);
  12361. db = 255 - abs(255 - sb - bb);
  12362. }
  12363. };
  12364. var nativeModes = this.nativeModes = Base.each([
  12365. 'source-over', 'source-in', 'source-out', 'source-atop',
  12366. 'destination-over', 'destination-in', 'destination-out',
  12367. 'destination-atop', 'lighter', 'darker', 'copy', 'xor'
  12368. ], function(mode) {
  12369. this[mode] = true;
  12370. }, {});
  12371. var ctx = CanvasProvider.getContext(1, 1);
  12372. if (ctx) {
  12373. Base.each(modes, function(func, mode) {
  12374. var darken = mode === 'darken',
  12375. ok = false;
  12376. ctx.save();
  12377. try {
  12378. ctx.fillStyle = darken ? '#300' : '#a00';
  12379. ctx.fillRect(0, 0, 1, 1);
  12380. ctx.globalCompositeOperation = mode;
  12381. if (ctx.globalCompositeOperation === mode) {
  12382. ctx.fillStyle = darken ? '#a00' : '#300';
  12383. ctx.fillRect(0, 0, 1, 1);
  12384. ok = ctx.getImageData(0, 0, 1, 1).data[0] !== darken
  12385. ? 170 : 51;
  12386. }
  12387. } catch (e) {}
  12388. ctx.restore();
  12389. nativeModes[mode] = ok;
  12390. });
  12391. CanvasProvider.release(ctx);
  12392. }
  12393. this.process = function(mode, srcContext, dstContext, alpha, offset) {
  12394. var srcCanvas = srcContext.canvas,
  12395. normal = mode === 'normal';
  12396. if (normal || nativeModes[mode]) {
  12397. dstContext.save();
  12398. dstContext.setTransform(1, 0, 0, 1, 0, 0);
  12399. dstContext.globalAlpha = alpha;
  12400. if (!normal)
  12401. dstContext.globalCompositeOperation = mode;
  12402. dstContext.drawImage(srcCanvas, offset.x, offset.y);
  12403. dstContext.restore();
  12404. } else {
  12405. var process = modes[mode];
  12406. if (!process)
  12407. return;
  12408. var dstData = dstContext.getImageData(offset.x, offset.y,
  12409. srcCanvas.width, srcCanvas.height),
  12410. dst = dstData.data,
  12411. src = srcContext.getImageData(0, 0,
  12412. srcCanvas.width, srcCanvas.height).data;
  12413. for (var i = 0, l = dst.length; i < l; i += 4) {
  12414. sr = src[i];
  12415. br = dst[i];
  12416. sg = src[i + 1];
  12417. bg = dst[i + 1];
  12418. sb = src[i + 2];
  12419. bb = dst[i + 2];
  12420. sa = src[i + 3];
  12421. ba = dst[i + 3];
  12422. process();
  12423. var a1 = sa * alpha / 255,
  12424. a2 = 1 - a1;
  12425. dst[i] = a1 * dr + a2 * br;
  12426. dst[i + 1] = a1 * dg + a2 * bg;
  12427. dst[i + 2] = a1 * db + a2 * bb;
  12428. dst[i + 3] = sa * alpha + a2 * ba;
  12429. }
  12430. dstContext.putImageData(dstData, offset.x, offset.y);
  12431. }
  12432. };
  12433. };
  12434. var SvgElement = new function() {
  12435. var svg = 'http://www.w3.org/2000/svg',
  12436. xmlns = 'http://www.w3.org/2000/xmlns',
  12437. xlink = 'http://www.w3.org/1999/xlink',
  12438. attributeNamespace = {
  12439. href: xlink,
  12440. xlink: xmlns,
  12441. xmlns: xmlns + '/',
  12442. 'xmlns:xlink': xmlns + '/'
  12443. };
  12444. function create(tag, attributes, formatter) {
  12445. return set(document.createElementNS(svg, tag), attributes, formatter);
  12446. }
  12447. function get(node, name) {
  12448. var namespace = attributeNamespace[name],
  12449. value = namespace
  12450. ? node.getAttributeNS(namespace, name)
  12451. : node.getAttribute(name);
  12452. return value === 'null' ? null : value;
  12453. }
  12454. function set(node, attributes, formatter) {
  12455. for (var name in attributes) {
  12456. var value = attributes[name],
  12457. namespace = attributeNamespace[name];
  12458. if (typeof value === 'number' && formatter)
  12459. value = formatter.number(value);
  12460. if (namespace) {
  12461. node.setAttributeNS(namespace, name, value);
  12462. } else {
  12463. node.setAttribute(name, value);
  12464. }
  12465. }
  12466. return node;
  12467. }
  12468. return {
  12469. svg: svg,
  12470. xmlns: xmlns,
  12471. xlink: xlink,
  12472. create: create,
  12473. get: get,
  12474. set: set
  12475. };
  12476. };
  12477. var SvgStyles = Base.each({
  12478. fillColor: ['fill', 'color'],
  12479. fillRule: ['fill-rule', 'string'],
  12480. strokeColor: ['stroke', 'color'],
  12481. strokeWidth: ['stroke-width', 'number'],
  12482. strokeCap: ['stroke-linecap', 'string'],
  12483. strokeJoin: ['stroke-linejoin', 'string'],
  12484. strokeScaling: ['vector-effect', 'lookup', {
  12485. true: 'none',
  12486. false: 'non-scaling-stroke'
  12487. }, function(item, value) {
  12488. return !value
  12489. && (item instanceof PathItem
  12490. || item instanceof Shape
  12491. || item instanceof TextItem);
  12492. }],
  12493. miterLimit: ['stroke-miterlimit', 'number'],
  12494. dashArray: ['stroke-dasharray', 'array'],
  12495. dashOffset: ['stroke-dashoffset', 'number'],
  12496. fontFamily: ['font-family', 'string'],
  12497. fontWeight: ['font-weight', 'string'],
  12498. fontSize: ['font-size', 'number'],
  12499. justification: ['text-anchor', 'lookup', {
  12500. left: 'start',
  12501. center: 'middle',
  12502. right: 'end'
  12503. }],
  12504. opacity: ['opacity', 'number'],
  12505. blendMode: ['mix-blend-mode', 'style']
  12506. }, function(entry, key) {
  12507. var part = Base.capitalize(key),
  12508. lookup = entry[2];
  12509. this[key] = {
  12510. type: entry[1],
  12511. property: key,
  12512. attribute: entry[0],
  12513. toSVG: lookup,
  12514. fromSVG: lookup && Base.each(lookup, function(value, name) {
  12515. this[value] = name;
  12516. }, {}),
  12517. exportFilter: entry[3],
  12518. get: 'get' + part,
  12519. set: 'set' + part
  12520. };
  12521. }, {});
  12522. new function() {
  12523. var formatter;
  12524. function getTransform(matrix, coordinates, center) {
  12525. var attrs = new Base(),
  12526. trans = matrix.getTranslation();
  12527. if (coordinates) {
  12528. matrix = matrix._shiftless();
  12529. var point = matrix._inverseTransform(trans);
  12530. attrs[center ? 'cx' : 'x'] = point.x;
  12531. attrs[center ? 'cy' : 'y'] = point.y;
  12532. trans = null;
  12533. }
  12534. if (!matrix.isIdentity()) {
  12535. var decomposed = matrix.decompose();
  12536. if (decomposed) {
  12537. var parts = [],
  12538. angle = decomposed.rotation,
  12539. scale = decomposed.scaling,
  12540. skew = decomposed.skewing;
  12541. if (trans && !trans.isZero())
  12542. parts.push('translate(' + formatter.point(trans) + ')');
  12543. if (angle)
  12544. parts.push('rotate(' + formatter.number(angle) + ')');
  12545. if (!Numerical.isZero(scale.x - 1)
  12546. || !Numerical.isZero(scale.y - 1))
  12547. parts.push('scale(' + formatter.point(scale) +')');
  12548. if (skew.x)
  12549. parts.push('skewX(' + formatter.number(skew.x) + ')');
  12550. if (skew.y)
  12551. parts.push('skewY(' + formatter.number(skew.y) + ')');
  12552. attrs.transform = parts.join(' ');
  12553. } else {
  12554. attrs.transform = 'matrix(' + matrix.getValues().join(',') + ')';
  12555. }
  12556. }
  12557. return attrs;
  12558. }
  12559. function exportGroup(item, options) {
  12560. var attrs = getTransform(item._matrix),
  12561. children = item._children;
  12562. var node = SvgElement.create('g', attrs, formatter);
  12563. for (var i = 0, l = children.length; i < l; i++) {
  12564. var child = children[i];
  12565. var childNode = exportSVG(child, options);
  12566. if (childNode) {
  12567. if (child.isClipMask()) {
  12568. var clip = SvgElement.create('clipPath');
  12569. clip.appendChild(childNode);
  12570. setDefinition(child, clip, 'clip');
  12571. SvgElement.set(node, {
  12572. 'clip-path': 'url(#' + clip.id + ')'
  12573. });
  12574. } else {
  12575. node.appendChild(childNode);
  12576. }
  12577. }
  12578. }
  12579. return node;
  12580. }
  12581. function exportRaster(item, options) {
  12582. var attrs = getTransform(item._matrix, true),
  12583. size = item.getSize(),
  12584. image = item.getImage();
  12585. attrs.x -= size.width / 2;
  12586. attrs.y -= size.height / 2;
  12587. attrs.width = size.width;
  12588. attrs.height = size.height;
  12589. attrs.href = options.embedImages == false && image && image.src
  12590. || item.toDataURL();
  12591. return SvgElement.create('image', attrs, formatter);
  12592. }
  12593. function exportPath(item, options) {
  12594. var matchShapes = options.matchShapes;
  12595. if (matchShapes) {
  12596. var shape = item.toShape(false);
  12597. if (shape)
  12598. return exportShape(shape, options);
  12599. }
  12600. var segments = item._segments,
  12601. length = segments.length,
  12602. type,
  12603. attrs = getTransform(item._matrix);
  12604. if (matchShapes && length >= 2 && !item.hasHandles()) {
  12605. if (length > 2) {
  12606. type = item._closed ? 'polygon' : 'polyline';
  12607. var parts = [];
  12608. for (var i = 0; i < length; i++) {
  12609. parts.push(formatter.point(segments[i]._point));
  12610. }
  12611. attrs.points = parts.join(' ');
  12612. } else {
  12613. type = 'line';
  12614. var start = segments[0]._point,
  12615. end = segments[1]._point;
  12616. attrs.set({
  12617. x1: start.x,
  12618. y1: start.y,
  12619. x2: end.x,
  12620. y2: end.y
  12621. });
  12622. }
  12623. } else {
  12624. type = 'path';
  12625. attrs.d = item.getPathData(null, options.precision);
  12626. }
  12627. return SvgElement.create(type, attrs, formatter);
  12628. }
  12629. function exportShape(item) {
  12630. var type = item._type,
  12631. radius = item._radius,
  12632. attrs = getTransform(item._matrix, true, type !== 'rectangle');
  12633. if (type === 'rectangle') {
  12634. type = 'rect';
  12635. var size = item._size,
  12636. width = size.width,
  12637. height = size.height;
  12638. attrs.x -= width / 2;
  12639. attrs.y -= height / 2;
  12640. attrs.width = width;
  12641. attrs.height = height;
  12642. if (radius.isZero())
  12643. radius = null;
  12644. }
  12645. if (radius) {
  12646. if (type === 'circle') {
  12647. attrs.r = radius;
  12648. } else {
  12649. attrs.rx = radius.width;
  12650. attrs.ry = radius.height;
  12651. }
  12652. }
  12653. return SvgElement.create(type, attrs, formatter);
  12654. }
  12655. function exportCompoundPath(item, options) {
  12656. var attrs = getTransform(item._matrix);
  12657. var data = item.getPathData(null, options.precision);
  12658. if (data)
  12659. attrs.d = data;
  12660. return SvgElement.create('path', attrs, formatter);
  12661. }
  12662. function exportSymbolItem(item, options) {
  12663. var attrs = getTransform(item._matrix, true),
  12664. definition = item._definition,
  12665. node = getDefinition(definition, 'symbol'),
  12666. definitionItem = definition._item,
  12667. bounds = definitionItem.getBounds();
  12668. if (!node) {
  12669. node = SvgElement.create('symbol', {
  12670. viewBox: formatter.rectangle(bounds)
  12671. });
  12672. node.appendChild(exportSVG(definitionItem, options));
  12673. setDefinition(definition, node, 'symbol');
  12674. }
  12675. attrs.href = '#' + node.id;
  12676. attrs.x += bounds.x;
  12677. attrs.y += bounds.y;
  12678. attrs.width = bounds.width;
  12679. attrs.height = bounds.height;
  12680. attrs.overflow = 'visible';
  12681. return SvgElement.create('use', attrs, formatter);
  12682. }
  12683. function exportGradient(color) {
  12684. var gradientNode = getDefinition(color, 'color');
  12685. if (!gradientNode) {
  12686. var gradient = color.getGradient(),
  12687. radial = gradient._radial,
  12688. origin = color.getOrigin(),
  12689. destination = color.getDestination(),
  12690. attrs;
  12691. if (radial) {
  12692. attrs = {
  12693. cx: origin.x,
  12694. cy: origin.y,
  12695. r: origin.getDistance(destination)
  12696. };
  12697. var highlight = color.getHighlight();
  12698. if (highlight) {
  12699. attrs.fx = highlight.x;
  12700. attrs.fy = highlight.y;
  12701. }
  12702. } else {
  12703. attrs = {
  12704. x1: origin.x,
  12705. y1: origin.y,
  12706. x2: destination.x,
  12707. y2: destination.y
  12708. };
  12709. }
  12710. attrs.gradientUnits = 'userSpaceOnUse';
  12711. gradientNode = SvgElement.create((radial ? 'radial' : 'linear')
  12712. + 'Gradient', attrs, formatter);
  12713. var stops = gradient._stops;
  12714. for (var i = 0, l = stops.length; i < l; i++) {
  12715. var stop = stops[i],
  12716. stopColor = stop._color,
  12717. alpha = stopColor.getAlpha(),
  12718. offset = stop._offset;
  12719. attrs = {
  12720. offset: offset == null ? i / (l - 1) : offset
  12721. };
  12722. if (stopColor)
  12723. attrs['stop-color'] = stopColor.toCSS(true);
  12724. if (alpha < 1)
  12725. attrs['stop-opacity'] = alpha;
  12726. gradientNode.appendChild(
  12727. SvgElement.create('stop', attrs, formatter));
  12728. }
  12729. setDefinition(color, gradientNode, 'color');
  12730. }
  12731. return 'url(#' + gradientNode.id + ')';
  12732. }
  12733. function exportText(item) {
  12734. var node = SvgElement.create('text', getTransform(item._matrix, true),
  12735. formatter);
  12736. node.textContent = item._content;
  12737. return node;
  12738. }
  12739. var exporters = {
  12740. Group: exportGroup,
  12741. Layer: exportGroup,
  12742. Raster: exportRaster,
  12743. Path: exportPath,
  12744. Shape: exportShape,
  12745. CompoundPath: exportCompoundPath,
  12746. SymbolItem: exportSymbolItem,
  12747. PointText: exportText
  12748. };
  12749. function applyStyle(item, node, isRoot) {
  12750. var attrs = {},
  12751. parent = !isRoot && item.getParent(),
  12752. style = [];
  12753. if (item._name != null)
  12754. attrs.id = item._name;
  12755. Base.each(SvgStyles, function(entry) {
  12756. var get = entry.get,
  12757. type = entry.type,
  12758. value = item[get]();
  12759. if (entry.exportFilter
  12760. ? entry.exportFilter(item, value)
  12761. : !parent || !Base.equals(parent[get](), value)) {
  12762. if (type === 'color' && value != null) {
  12763. var alpha = value.getAlpha();
  12764. if (alpha < 1)
  12765. attrs[entry.attribute + '-opacity'] = alpha;
  12766. }
  12767. if (type === 'style') {
  12768. style.push(entry.attribute + ': ' + value);
  12769. } else {
  12770. attrs[entry.attribute] = value == null ? 'none'
  12771. : type === 'color' ? value.gradient
  12772. ? exportGradient(value, item)
  12773. : value.toCSS(true)
  12774. : type === 'array' ? value.join(',')
  12775. : type === 'lookup' ? entry.toSVG[value]
  12776. : value;
  12777. }
  12778. }
  12779. });
  12780. if (style.length)
  12781. attrs.style = style.join(';');
  12782. if (attrs.opacity === 1)
  12783. delete attrs.opacity;
  12784. if (!item._visible)
  12785. attrs.visibility = 'hidden';
  12786. return SvgElement.set(node, attrs, formatter);
  12787. }
  12788. var definitions;
  12789. function getDefinition(item, type) {
  12790. if (!definitions)
  12791. definitions = { ids: {}, svgs: {} };
  12792. return item && definitions.svgs[type + '-'
  12793. + (item._id || item.__id || (item.__id = UID.get('svg')))];
  12794. }
  12795. function setDefinition(item, node, type) {
  12796. if (!definitions)
  12797. getDefinition();
  12798. var typeId = definitions.ids[type] = (definitions.ids[type] || 0) + 1;
  12799. node.id = type + '-' + typeId;
  12800. definitions.svgs[type + '-' + (item._id || item.__id)] = node;
  12801. }
  12802. function exportDefinitions(node, options) {
  12803. var svg = node,
  12804. defs = null;
  12805. if (definitions) {
  12806. svg = node.nodeName.toLowerCase() === 'svg' && node;
  12807. for (var i in definitions.svgs) {
  12808. if (!defs) {
  12809. if (!svg) {
  12810. svg = SvgElement.create('svg');
  12811. svg.appendChild(node);
  12812. }
  12813. defs = svg.insertBefore(SvgElement.create('defs'),
  12814. svg.firstChild);
  12815. }
  12816. defs.appendChild(definitions.svgs[i]);
  12817. }
  12818. definitions = null;
  12819. }
  12820. return options.asString
  12821. ? new self.XMLSerializer().serializeToString(svg)
  12822. : svg;
  12823. }
  12824. function exportSVG(item, options, isRoot) {
  12825. var exporter = exporters[item._class],
  12826. node = exporter && exporter(item, options);
  12827. if (node) {
  12828. var onExport = options.onExport;
  12829. if (onExport)
  12830. node = onExport(item, node, options) || node;
  12831. var data = JSON.stringify(item._data);
  12832. if (data && data !== '{}' && data !== 'null')
  12833. node.setAttribute('data-paper-data', data);
  12834. }
  12835. return node && applyStyle(item, node, isRoot);
  12836. }
  12837. function setOptions(options) {
  12838. if (!options)
  12839. options = {};
  12840. formatter = new Formatter(options.precision);
  12841. return options;
  12842. }
  12843. Item.inject({
  12844. exportSVG: function(options) {
  12845. options = setOptions(options);
  12846. return exportDefinitions(exportSVG(this, options, true), options);
  12847. }
  12848. });
  12849. Project.inject({
  12850. exportSVG: function(options) {
  12851. options = setOptions(options);
  12852. var children = this._children,
  12853. view = this.getView(),
  12854. bounds = Base.pick(options.bounds, 'view'),
  12855. mx = options.matrix || bounds === 'view' && view._matrix,
  12856. matrix = mx && Matrix.read([mx]),
  12857. rect = bounds === 'view'
  12858. ? new Rectangle([0, 0], view.getViewSize())
  12859. : bounds === 'content'
  12860. ? Item._getBounds(children, matrix, { stroke: true })
  12861. .rect
  12862. : Rectangle.read([bounds], 0, { readNull: true }),
  12863. attrs = {
  12864. version: '1.1',
  12865. xmlns: SvgElement.svg,
  12866. 'xmlns:xlink': SvgElement.xlink,
  12867. };
  12868. if (rect) {
  12869. attrs.width = rect.width;
  12870. attrs.height = rect.height;
  12871. if (rect.x || rect.y)
  12872. attrs.viewBox = formatter.rectangle(rect);
  12873. }
  12874. var node = SvgElement.create('svg', attrs, formatter),
  12875. parent = node;
  12876. if (matrix && !matrix.isIdentity()) {
  12877. parent = node.appendChild(SvgElement.create('g',
  12878. getTransform(matrix), formatter));
  12879. }
  12880. for (var i = 0, l = children.length; i < l; i++) {
  12881. parent.appendChild(exportSVG(children[i], options, true));
  12882. }
  12883. return exportDefinitions(node, options);
  12884. }
  12885. });
  12886. };
  12887. new function() {
  12888. var definitions = {},
  12889. rootSize;
  12890. function getValue(node, name, isString, allowNull, allowPercent) {
  12891. var value = SvgElement.get(node, name),
  12892. res = value == null
  12893. ? allowNull
  12894. ? null
  12895. : isString ? '' : 0
  12896. : isString
  12897. ? value
  12898. : parseFloat(value);
  12899. return /%\s*$/.test(value)
  12900. ? (res / 100) * (allowPercent ? 1
  12901. : rootSize[/x|^width/.test(name) ? 'width' : 'height'])
  12902. : res;
  12903. }
  12904. function getPoint(node, x, y, allowNull, allowPercent) {
  12905. x = getValue(node, x || 'x', false, allowNull, allowPercent);
  12906. y = getValue(node, y || 'y', false, allowNull, allowPercent);
  12907. return allowNull && (x == null || y == null) ? null
  12908. : new Point(x, y);
  12909. }
  12910. function getSize(node, w, h, allowNull, allowPercent) {
  12911. w = getValue(node, w || 'width', false, allowNull, allowPercent);
  12912. h = getValue(node, h || 'height', false, allowNull, allowPercent);
  12913. return allowNull && (w == null || h == null) ? null
  12914. : new Size(w, h);
  12915. }
  12916. function convertValue(value, type, lookup) {
  12917. return value === 'none' ? null
  12918. : type === 'number' ? parseFloat(value)
  12919. : type === 'array' ?
  12920. value ? value.split(/[\s,]+/g).map(parseFloat) : []
  12921. : type === 'color' ? getDefinition(value) || value
  12922. : type === 'lookup' ? lookup[value]
  12923. : value;
  12924. }
  12925. function importGroup(node, type, options, isRoot) {
  12926. var nodes = node.childNodes,
  12927. isClip = type === 'clippath',
  12928. isDefs = type === 'defs',
  12929. item = new Group(),
  12930. project = item._project,
  12931. currentStyle = project._currentStyle,
  12932. children = [];
  12933. if (!isClip && !isDefs) {
  12934. item = applyAttributes(item, node, isRoot);
  12935. project._currentStyle = item._style.clone();
  12936. }
  12937. if (isRoot) {
  12938. var defs = node.querySelectorAll('defs');
  12939. for (var i = 0, l = defs.length; i < l; i++) {
  12940. importNode(defs[i], options, false);
  12941. }
  12942. }
  12943. for (var i = 0, l = nodes.length; i < l; i++) {
  12944. var childNode = nodes[i],
  12945. child;
  12946. if (childNode.nodeType === 1
  12947. && !/^defs$/i.test(childNode.nodeName)
  12948. && (child = importNode(childNode, options, false))
  12949. && !(child instanceof SymbolDefinition))
  12950. children.push(child);
  12951. }
  12952. item.addChildren(children);
  12953. if (isClip)
  12954. item = applyAttributes(item.reduce(), node, isRoot);
  12955. project._currentStyle = currentStyle;
  12956. if (isClip || isDefs) {
  12957. item.remove();
  12958. item = null;
  12959. }
  12960. return item;
  12961. }
  12962. function importPoly(node, type) {
  12963. var coords = node.getAttribute('points').match(
  12964. /[+-]?(?:\d*\.\d+|\d+\.?)(?:[eE][+-]?\d+)?/g),
  12965. points = [];
  12966. for (var i = 0, l = coords.length; i < l; i += 2)
  12967. points.push(new Point(
  12968. parseFloat(coords[i]),
  12969. parseFloat(coords[i + 1])));
  12970. var path = new Path(points);
  12971. if (type === 'polygon')
  12972. path.closePath();
  12973. return path;
  12974. }
  12975. function importPath(node) {
  12976. return PathItem.create(node.getAttribute('d'));
  12977. }
  12978. function importGradient(node, type) {
  12979. var id = (getValue(node, 'href', true) || '').substring(1),
  12980. radial = type === 'radialgradient',
  12981. gradient;
  12982. if (id) {
  12983. gradient = definitions[id].getGradient();
  12984. if (gradient._radial ^ radial) {
  12985. gradient = gradient.clone();
  12986. gradient._radial = radial;
  12987. }
  12988. } else {
  12989. var nodes = node.childNodes,
  12990. stops = [];
  12991. for (var i = 0, l = nodes.length; i < l; i++) {
  12992. var child = nodes[i];
  12993. if (child.nodeType === 1)
  12994. stops.push(applyAttributes(new GradientStop(), child));
  12995. }
  12996. gradient = new Gradient(stops, radial);
  12997. }
  12998. var origin, destination, highlight,
  12999. scaleToBounds = getValue(node, 'gradientUnits', true) !==
  13000. 'userSpaceOnUse';
  13001. if (radial) {
  13002. origin = getPoint(node, 'cx', 'cy', false, scaleToBounds);
  13003. destination = origin.add(
  13004. getValue(node, 'r', false, false, scaleToBounds), 0);
  13005. highlight = getPoint(node, 'fx', 'fy', true, scaleToBounds);
  13006. } else {
  13007. origin = getPoint(node, 'x1', 'y1', false, scaleToBounds);
  13008. destination = getPoint(node, 'x2', 'y2', false, scaleToBounds);
  13009. }
  13010. var color = applyAttributes(
  13011. new Color(gradient, origin, destination, highlight), node);
  13012. color._scaleToBounds = scaleToBounds;
  13013. return null;
  13014. }
  13015. var importers = {
  13016. '#document': function (node, type, options, isRoot) {
  13017. var nodes = node.childNodes;
  13018. for (var i = 0, l = nodes.length; i < l; i++) {
  13019. var child = nodes[i];
  13020. if (child.nodeType === 1)
  13021. return importNode(child, options, isRoot);
  13022. }
  13023. },
  13024. g: importGroup,
  13025. svg: importGroup,
  13026. clippath: importGroup,
  13027. polygon: importPoly,
  13028. polyline: importPoly,
  13029. path: importPath,
  13030. lineargradient: importGradient,
  13031. radialgradient: importGradient,
  13032. image: function (node) {
  13033. var raster = new Raster(getValue(node, 'href', true));
  13034. raster.on('load', function() {
  13035. var size = getSize(node);
  13036. this.setSize(size);
  13037. var center = this._matrix._transformPoint(
  13038. getPoint(node).add(size.divide(2)));
  13039. this.translate(center);
  13040. });
  13041. return raster;
  13042. },
  13043. symbol: function(node, type, options, isRoot) {
  13044. return new SymbolDefinition(
  13045. importGroup(node, type, options, isRoot), true);
  13046. },
  13047. defs: importGroup,
  13048. use: function(node) {
  13049. var id = (getValue(node, 'href', true) || '').substring(1),
  13050. definition = definitions[id],
  13051. point = getPoint(node);
  13052. return definition
  13053. ? definition instanceof SymbolDefinition
  13054. ? definition.place(point)
  13055. : definition.clone().translate(point)
  13056. : null;
  13057. },
  13058. circle: function(node) {
  13059. return new Shape.Circle(
  13060. getPoint(node, 'cx', 'cy'),
  13061. getValue(node, 'r'));
  13062. },
  13063. ellipse: function(node) {
  13064. return new Shape.Ellipse({
  13065. center: getPoint(node, 'cx', 'cy'),
  13066. radius: getSize(node, 'rx', 'ry')
  13067. });
  13068. },
  13069. rect: function(node) {
  13070. return new Shape.Rectangle(new Rectangle(
  13071. getPoint(node),
  13072. getSize(node)
  13073. ), getSize(node, 'rx', 'ry'));
  13074. },
  13075. line: function(node) {
  13076. return new Path.Line(
  13077. getPoint(node, 'x1', 'y1'),
  13078. getPoint(node, 'x2', 'y2'));
  13079. },
  13080. text: function(node) {
  13081. var text = new PointText(getPoint(node).add(
  13082. getPoint(node, 'dx', 'dy')));
  13083. text.setContent(node.textContent.trim() || '');
  13084. return text;
  13085. }
  13086. };
  13087. function applyTransform(item, value, name, node) {
  13088. if (item.transform) {
  13089. var transforms = (node.getAttribute(name) || '').split(/\)\s*/g),
  13090. matrix = new Matrix();
  13091. for (var i = 0, l = transforms.length; i < l; i++) {
  13092. var transform = transforms[i];
  13093. if (!transform)
  13094. break;
  13095. var parts = transform.split(/\(\s*/),
  13096. command = parts[0],
  13097. v = parts[1].split(/[\s,]+/g);
  13098. for (var j = 0, m = v.length; j < m; j++)
  13099. v[j] = parseFloat(v[j]);
  13100. switch (command) {
  13101. case 'matrix':
  13102. matrix.append(
  13103. new Matrix(v[0], v[1], v[2], v[3], v[4], v[5]));
  13104. break;
  13105. case 'rotate':
  13106. matrix.rotate(v[0], v[1], v[2]);
  13107. break;
  13108. case 'translate':
  13109. matrix.translate(v[0], v[1]);
  13110. break;
  13111. case 'scale':
  13112. matrix.scale(v);
  13113. break;
  13114. case 'skewX':
  13115. matrix.skew(v[0], 0);
  13116. break;
  13117. case 'skewY':
  13118. matrix.skew(0, v[0]);
  13119. break;
  13120. }
  13121. }
  13122. item.transform(matrix);
  13123. }
  13124. }
  13125. function applyOpacity(item, value, name) {
  13126. var key = name === 'fill-opacity' ? 'getFillColor' : 'getStrokeColor',
  13127. color = item[key] && item[key]();
  13128. if (color)
  13129. color.setAlpha(parseFloat(value));
  13130. }
  13131. var attributes = Base.set(Base.each(SvgStyles, function(entry) {
  13132. this[entry.attribute] = function(item, value) {
  13133. if (item[entry.set]) {
  13134. item[entry.set](convertValue(value, entry.type, entry.fromSVG));
  13135. if (entry.type === 'color') {
  13136. var color = item[entry.get]();
  13137. if (color) {
  13138. if (color._scaleToBounds) {
  13139. var bounds = item.getBounds();
  13140. color.transform(new Matrix()
  13141. .translate(bounds.getPoint())
  13142. .scale(bounds.getSize()));
  13143. }
  13144. }
  13145. }
  13146. }
  13147. };
  13148. }, {}), {
  13149. id: function(item, value) {
  13150. definitions[value] = item;
  13151. if (item.setName)
  13152. item.setName(value);
  13153. },
  13154. 'clip-path': function(item, value) {
  13155. var clip = getDefinition(value);
  13156. if (clip) {
  13157. clip = clip.clone();
  13158. clip.setClipMask(true);
  13159. if (item instanceof Group) {
  13160. item.insertChild(0, clip);
  13161. } else {
  13162. return new Group(clip, item);
  13163. }
  13164. }
  13165. },
  13166. gradientTransform: applyTransform,
  13167. transform: applyTransform,
  13168. 'fill-opacity': applyOpacity,
  13169. 'stroke-opacity': applyOpacity,
  13170. visibility: function(item, value) {
  13171. if (item.setVisible)
  13172. item.setVisible(value === 'visible');
  13173. },
  13174. display: function(item, value) {
  13175. if (item.setVisible)
  13176. item.setVisible(value !== null);
  13177. },
  13178. 'stop-color': function(item, value) {
  13179. if (item.setColor)
  13180. item.setColor(value);
  13181. },
  13182. 'stop-opacity': function(item, value) {
  13183. if (item._color)
  13184. item._color.setAlpha(parseFloat(value));
  13185. },
  13186. offset: function(item, value) {
  13187. if (item.setOffset) {
  13188. var percent = value.match(/(.*)%$/);
  13189. item.setOffset(percent ? percent[1] / 100 : parseFloat(value));
  13190. }
  13191. },
  13192. viewBox: function(item, value, name, node, styles) {
  13193. var rect = new Rectangle(convertValue(value, 'array')),
  13194. size = getSize(node, null, null, true),
  13195. group,
  13196. matrix;
  13197. if (item instanceof Group) {
  13198. var scale = size ? size.divide(rect.getSize()) : 1,
  13199. matrix = new Matrix().scale(scale)
  13200. .translate(rect.getPoint().negate());
  13201. group = item;
  13202. } else if (item instanceof SymbolDefinition) {
  13203. if (size)
  13204. rect.setSize(size);
  13205. group = item._item;
  13206. }
  13207. if (group) {
  13208. if (getAttribute(node, 'overflow', styles) !== 'visible') {
  13209. var clip = new Shape.Rectangle(rect);
  13210. clip.setClipMask(true);
  13211. group.addChild(clip);
  13212. }
  13213. if (matrix)
  13214. group.transform(matrix);
  13215. }
  13216. }
  13217. });
  13218. function getAttribute(node, name, styles) {
  13219. var attr = node.attributes[name],
  13220. value = attr && attr.value;
  13221. if (!value) {
  13222. var style = Base.camelize(name);
  13223. value = node.style[style];
  13224. if (!value && styles.node[style] !== styles.parent[style])
  13225. value = styles.node[style];
  13226. }
  13227. return !value ? undefined
  13228. : value === 'none' ? null
  13229. : value;
  13230. }
  13231. function applyAttributes(item, node, isRoot) {
  13232. if (node.style) {
  13233. var parent = node.parentNode,
  13234. styles = {
  13235. node: DomElement.getStyles(node) || {},
  13236. parent: !isRoot && !/^defs$/i.test(parent.tagName)
  13237. && DomElement.getStyles(parent) || {}
  13238. };
  13239. Base.each(attributes, function(apply, name) {
  13240. var value = getAttribute(node, name, styles);
  13241. item = value !== undefined
  13242. && apply(item, value, name, node, styles) || item;
  13243. });
  13244. }
  13245. return item;
  13246. }
  13247. function getDefinition(value) {
  13248. var match = value && value.match(/\((?:["'#]*)([^"')]+)/),
  13249. name = match && match[1],
  13250. res = name && definitions[window
  13251. ? name.replace(window.location.href.split('#')[0] + '#', '')
  13252. : name];
  13253. if (res && res._scaleToBounds) {
  13254. res = res.clone();
  13255. res._scaleToBounds = true;
  13256. }
  13257. return res;
  13258. }
  13259. function importNode(node, options, isRoot) {
  13260. var type = node.nodeName.toLowerCase(),
  13261. isElement = type !== '#document',
  13262. body = document.body,
  13263. container,
  13264. parent,
  13265. next;
  13266. if (isRoot && isElement) {
  13267. rootSize = paper.getView().getSize();
  13268. rootSize = getSize(node, null, null, true) || rootSize;
  13269. container = SvgElement.create('svg', {
  13270. style: 'stroke-width: 1px; stroke-miterlimit: 10'
  13271. });
  13272. parent = node.parentNode;
  13273. next = node.nextSibling;
  13274. container.appendChild(node);
  13275. body.appendChild(container);
  13276. }
  13277. var settings = paper.settings,
  13278. applyMatrix = settings.applyMatrix,
  13279. insertItems = settings.insertItems;
  13280. settings.applyMatrix = false;
  13281. settings.insertItems = false;
  13282. var importer = importers[type],
  13283. item = importer && importer(node, type, options, isRoot) || null;
  13284. settings.insertItems = insertItems;
  13285. settings.applyMatrix = applyMatrix;
  13286. if (item) {
  13287. if (isElement && !(item instanceof Group))
  13288. item = applyAttributes(item, node, isRoot);
  13289. var onImport = options.onImport,
  13290. data = isElement && node.getAttribute('data-paper-data');
  13291. if (onImport)
  13292. item = onImport(node, item, options) || item;
  13293. if (options.expandShapes && item instanceof Shape) {
  13294. item.remove();
  13295. item = item.toPath();
  13296. }
  13297. if (data)
  13298. item._data = JSON.parse(data);
  13299. }
  13300. if (container) {
  13301. body.removeChild(container);
  13302. if (parent) {
  13303. if (next) {
  13304. parent.insertBefore(node, next);
  13305. } else {
  13306. parent.appendChild(node);
  13307. }
  13308. }
  13309. }
  13310. if (isRoot) {
  13311. definitions = {};
  13312. if (item && Base.pick(options.applyMatrix, applyMatrix))
  13313. item.matrix.apply(true, true);
  13314. }
  13315. return item;
  13316. }
  13317. function importSVG(source, options, owner) {
  13318. if (!source)
  13319. return null;
  13320. options = typeof options === 'function' ? { onLoad: options }
  13321. : options || {};
  13322. var scope = paper,
  13323. item = null;
  13324. function onLoad(svg) {
  13325. try {
  13326. var node = typeof svg === 'object' ? svg : new self.DOMParser()
  13327. .parseFromString(svg, 'image/svg+xml');
  13328. if (!node.nodeName) {
  13329. node = null;
  13330. throw new Error('Unsupported SVG source: ' + source);
  13331. }
  13332. paper = scope;
  13333. item = importNode(node, options, true);
  13334. if (!options || options.insert !== false) {
  13335. owner._insertItem(undefined, item);
  13336. }
  13337. var onLoad = options.onLoad;
  13338. if (onLoad)
  13339. onLoad(item, svg);
  13340. } catch (e) {
  13341. onError(e);
  13342. }
  13343. }
  13344. function onError(message, status) {
  13345. var onError = options.onError;
  13346. if (onError) {
  13347. onError(message, status);
  13348. } else {
  13349. throw new Error(message);
  13350. }
  13351. }
  13352. if (typeof source === 'string' && !/^.*</.test(source)) {
  13353. var node = document.getElementById(source);
  13354. if (node) {
  13355. onLoad(node);
  13356. } else {
  13357. Http.request({
  13358. url: source,
  13359. async: true,
  13360. onLoad: onLoad,
  13361. onError: onError
  13362. });
  13363. }
  13364. } else if (typeof File !== 'undefined' && source instanceof File) {
  13365. var reader = new FileReader();
  13366. reader.onload = function() {
  13367. onLoad(reader.result);
  13368. };
  13369. reader.onerror = function() {
  13370. onError(reader.error);
  13371. };
  13372. return reader.readAsText(source);
  13373. } else {
  13374. onLoad(source);
  13375. }
  13376. return item;
  13377. }
  13378. Item.inject({
  13379. importSVG: function(node, options) {
  13380. return importSVG(node, options, this);
  13381. }
  13382. });
  13383. Project.inject({
  13384. importSVG: function(node, options) {
  13385. this.activate();
  13386. return importSVG(node, options, this);
  13387. }
  13388. });
  13389. };
  13390. Base.exports.PaperScript = function() {
  13391. var global = this,
  13392. acorn = global.acorn;
  13393. if (!acorn && typeof require !== 'undefined') {
  13394. try { acorn = require('acorn'); } catch(e) {}
  13395. }
  13396. if (!acorn) {
  13397. var exports, module;
  13398. acorn = exports = module = {};
  13399. (function(root, mod) {
  13400. if (typeof exports == "object" && typeof module == "object") return mod(exports);
  13401. if (typeof define == "function" && define.amd) return define(["exports"], mod);
  13402. mod(root.acorn || (root.acorn = {}));
  13403. })(this, function(exports) {
  13404. "use strict";
  13405. exports.version = "0.5.0";
  13406. var options, input, inputLen, sourceFile;
  13407. exports.parse = function(inpt, opts) {
  13408. input = String(inpt); inputLen = input.length;
  13409. setOptions(opts);
  13410. initTokenState();
  13411. return parseTopLevel(options.program);
  13412. };
  13413. var defaultOptions = exports.defaultOptions = {
  13414. ecmaVersion: 5,
  13415. strictSemicolons: false,
  13416. allowTrailingCommas: true,
  13417. forbidReserved: false,
  13418. allowReturnOutsideFunction: false,
  13419. locations: false,
  13420. onComment: null,
  13421. ranges: false,
  13422. program: null,
  13423. sourceFile: null,
  13424. directSourceFile: null
  13425. };
  13426. function setOptions(opts) {
  13427. options = opts || {};
  13428. for (var opt in defaultOptions) if (!Object.prototype.hasOwnProperty.call(options, opt))
  13429. options[opt] = defaultOptions[opt];
  13430. sourceFile = options.sourceFile || null;
  13431. }
  13432. var getLineInfo = exports.getLineInfo = function(input, offset) {
  13433. for (var line = 1, cur = 0;;) {
  13434. lineBreak.lastIndex = cur;
  13435. var match = lineBreak.exec(input);
  13436. if (match && match.index < offset) {
  13437. ++line;
  13438. cur = match.index + match[0].length;
  13439. } else break;
  13440. }
  13441. return {line: line, column: offset - cur};
  13442. };
  13443. exports.tokenize = function(inpt, opts) {
  13444. input = String(inpt); inputLen = input.length;
  13445. setOptions(opts);
  13446. initTokenState();
  13447. var t = {};
  13448. function getToken(forceRegexp) {
  13449. lastEnd = tokEnd;
  13450. readToken(forceRegexp);
  13451. t.start = tokStart; t.end = tokEnd;
  13452. t.startLoc = tokStartLoc; t.endLoc = tokEndLoc;
  13453. t.type = tokType; t.value = tokVal;
  13454. return t;
  13455. }
  13456. getToken.jumpTo = function(pos, reAllowed) {
  13457. tokPos = pos;
  13458. if (options.locations) {
  13459. tokCurLine = 1;
  13460. tokLineStart = lineBreak.lastIndex = 0;
  13461. var match;
  13462. while ((match = lineBreak.exec(input)) && match.index < pos) {
  13463. ++tokCurLine;
  13464. tokLineStart = match.index + match[0].length;
  13465. }
  13466. }
  13467. tokRegexpAllowed = reAllowed;
  13468. skipSpace();
  13469. };
  13470. return getToken;
  13471. };
  13472. var tokPos;
  13473. var tokStart, tokEnd;
  13474. var tokStartLoc, tokEndLoc;
  13475. var tokType, tokVal;
  13476. var tokRegexpAllowed;
  13477. var tokCurLine, tokLineStart;
  13478. var lastStart, lastEnd, lastEndLoc;
  13479. var inFunction, labels, strict;
  13480. function raise(pos, message) {
  13481. var loc = getLineInfo(input, pos);
  13482. message += " (" + loc.line + ":" + loc.column + ")";
  13483. var err = new SyntaxError(message);
  13484. err.pos = pos; err.loc = loc; err.raisedAt = tokPos;
  13485. throw err;
  13486. }
  13487. var empty = [];
  13488. var _num = {type: "num"}, _regexp = {type: "regexp"}, _string = {type: "string"};
  13489. var _name = {type: "name"}, _eof = {type: "eof"};
  13490. var _break = {keyword: "break"}, _case = {keyword: "case", beforeExpr: true}, _catch = {keyword: "catch"};
  13491. var _continue = {keyword: "continue"}, _debugger = {keyword: "debugger"}, _default = {keyword: "default"};
  13492. var _do = {keyword: "do", isLoop: true}, _else = {keyword: "else", beforeExpr: true};
  13493. var _finally = {keyword: "finally"}, _for = {keyword: "for", isLoop: true}, _function = {keyword: "function"};
  13494. var _if = {keyword: "if"}, _return = {keyword: "return", beforeExpr: true}, _switch = {keyword: "switch"};
  13495. var _throw = {keyword: "throw", beforeExpr: true}, _try = {keyword: "try"}, _var = {keyword: "var"};
  13496. var _while = {keyword: "while", isLoop: true}, _with = {keyword: "with"}, _new = {keyword: "new", beforeExpr: true};
  13497. var _this = {keyword: "this"};
  13498. var _null = {keyword: "null", atomValue: null}, _true = {keyword: "true", atomValue: true};
  13499. var _false = {keyword: "false", atomValue: false};
  13500. var _in = {keyword: "in", binop: 7, beforeExpr: true};
  13501. var keywordTypes = {"break": _break, "case": _case, "catch": _catch,
  13502. "continue": _continue, "debugger": _debugger, "default": _default,
  13503. "do": _do, "else": _else, "finally": _finally, "for": _for,
  13504. "function": _function, "if": _if, "return": _return, "switch": _switch,
  13505. "throw": _throw, "try": _try, "var": _var, "while": _while, "with": _with,
  13506. "null": _null, "true": _true, "false": _false, "new": _new, "in": _in,
  13507. "instanceof": {keyword: "instanceof", binop: 7, beforeExpr: true}, "this": _this,
  13508. "typeof": {keyword: "typeof", prefix: true, beforeExpr: true},
  13509. "void": {keyword: "void", prefix: true, beforeExpr: true},
  13510. "delete": {keyword: "delete", prefix: true, beforeExpr: true}};
  13511. var _bracketL = {type: "[", beforeExpr: true}, _bracketR = {type: "]"}, _braceL = {type: "{", beforeExpr: true};
  13512. var _braceR = {type: "}"}, _parenL = {type: "(", beforeExpr: true}, _parenR = {type: ")"};
  13513. var _comma = {type: ",", beforeExpr: true}, _semi = {type: ";", beforeExpr: true};
  13514. var _colon = {type: ":", beforeExpr: true}, _dot = {type: "."}, _question = {type: "?", beforeExpr: true};
  13515. var _slash = {binop: 10, beforeExpr: true}, _eq = {isAssign: true, beforeExpr: true};
  13516. var _assign = {isAssign: true, beforeExpr: true};
  13517. var _incDec = {postfix: true, prefix: true, isUpdate: true}, _prefix = {prefix: true, beforeExpr: true};
  13518. var _logicalOR = {binop: 1, beforeExpr: true};
  13519. var _logicalAND = {binop: 2, beforeExpr: true};
  13520. var _bitwiseOR = {binop: 3, beforeExpr: true};
  13521. var _bitwiseXOR = {binop: 4, beforeExpr: true};
  13522. var _bitwiseAND = {binop: 5, beforeExpr: true};
  13523. var _equality = {binop: 6, beforeExpr: true};
  13524. var _relational = {binop: 7, beforeExpr: true};
  13525. var _bitShift = {binop: 8, beforeExpr: true};
  13526. var _plusMin = {binop: 9, prefix: true, beforeExpr: true};
  13527. var _multiplyModulo = {binop: 10, beforeExpr: true};
  13528. exports.tokTypes = {bracketL: _bracketL, bracketR: _bracketR, braceL: _braceL, braceR: _braceR,
  13529. parenL: _parenL, parenR: _parenR, comma: _comma, semi: _semi, colon: _colon,
  13530. dot: _dot, question: _question, slash: _slash, eq: _eq, name: _name, eof: _eof,
  13531. num: _num, regexp: _regexp, string: _string};
  13532. for (var kw in keywordTypes) exports.tokTypes["_" + kw] = keywordTypes[kw];
  13533. function makePredicate(words) {
  13534. words = words.split(" ");
  13535. var f = "", cats = [];
  13536. out: for (var i = 0; i < words.length; ++i) {
  13537. for (var j = 0; j < cats.length; ++j)
  13538. if (cats[j][0].length == words[i].length) {
  13539. cats[j].push(words[i]);
  13540. continue out;
  13541. }
  13542. cats.push([words[i]]);
  13543. }
  13544. function compareTo(arr) {
  13545. if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
  13546. f += "switch(str){";
  13547. for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
  13548. f += "return true}return false;";
  13549. }
  13550. if (cats.length > 3) {
  13551. cats.sort(function(a, b) {return b.length - a.length;});
  13552. f += "switch(str.length){";
  13553. for (var i = 0; i < cats.length; ++i) {
  13554. var cat = cats[i];
  13555. f += "case " + cat[0].length + ":";
  13556. compareTo(cat);
  13557. }
  13558. f += "}";
  13559. } else {
  13560. compareTo(words);
  13561. }
  13562. return new Function("str", f);
  13563. }
  13564. var isReservedWord3 = makePredicate("abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized throws transient volatile");
  13565. var isReservedWord5 = makePredicate("class enum extends super const export import");
  13566. var isStrictReservedWord = makePredicate("implements interface let package private protected public static yield");
  13567. var isStrictBadIdWord = makePredicate("eval arguments");
  13568. var isKeyword = makePredicate("break case catch continue debugger default do else finally for function if return switch throw try var while with null true false instanceof typeof void delete new in this");
  13569. var nonASCIIwhitespace = /[\u1680\u180e\u2000-\u200a\u202f\u205f\u3000\ufeff]/;
  13570. var nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
  13571. var nonASCIIidentifierChars = "\u0300-\u036f\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u0620-\u0649\u0672-\u06d3\u06e7-\u06e8\u06fb-\u06fc\u0730-\u074a\u0800-\u0814\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0840-\u0857\u08e4-\u08fe\u0900-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962-\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09d7\u09df-\u09e0\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5f-\u0b60\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2-\u0ce3\u0ce6-\u0cef\u0d02\u0d03\u0d46-\u0d48\u0d57\u0d62-\u0d63\u0d66-\u0d6f\u0d82\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e34-\u0e3a\u0e40-\u0e45\u0e50-\u0e59\u0eb4-\u0eb9\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f41-\u0f47\u0f71-\u0f84\u0f86-\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1029\u1040-\u1049\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u170e-\u1710\u1720-\u1730\u1740-\u1750\u1772\u1773\u1780-\u17b2\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1920-\u192b\u1930-\u193b\u1951-\u196d\u19b0-\u19c0\u19c8-\u19c9\u19d0-\u19d9\u1a00-\u1a15\u1a20-\u1a53\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1b46-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1bb0-\u1bb9\u1be6-\u1bf3\u1c00-\u1c22\u1c40-\u1c49\u1c5b-\u1c7d\u1cd0-\u1cd2\u1d00-\u1dbe\u1e01-\u1f15\u200c\u200d\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2d81-\u2d96\u2de0-\u2dff\u3021-\u3028\u3099\u309a\ua640-\ua66d\ua674-\ua67d\ua69f\ua6f0-\ua6f1\ua7f8-\ua800\ua806\ua80b\ua823-\ua827\ua880-\ua881\ua8b4-\ua8c4\ua8d0-\ua8d9\ua8f3-\ua8f7\ua900-\ua909\ua926-\ua92d\ua930-\ua945\ua980-\ua983\ua9b3-\ua9c0\uaa00-\uaa27\uaa40-\uaa41\uaa4c-\uaa4d\uaa50-\uaa59\uaa7b\uaae0-\uaae9\uaaf2-\uaaf3\uabc0-\uabe1\uabec\uabed\uabf0-\uabf9\ufb20-\ufb28\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
  13572. var nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
  13573. var nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
  13574. var newline = /[\n\r\u2028\u2029]/;
  13575. var lineBreak = /\r\n|[\n\r\u2028\u2029]/g;
  13576. var isIdentifierStart = exports.isIdentifierStart = function(code) {
  13577. if (code < 65) return code === 36;
  13578. if (code < 91) return true;
  13579. if (code < 97) return code === 95;
  13580. if (code < 123)return true;
  13581. return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
  13582. };
  13583. var isIdentifierChar = exports.isIdentifierChar = function(code) {
  13584. if (code < 48) return code === 36;
  13585. if (code < 58) return true;
  13586. if (code < 65) return false;
  13587. if (code < 91) return true;
  13588. if (code < 97) return code === 95;
  13589. if (code < 123)return true;
  13590. return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
  13591. };
  13592. function line_loc_t() {
  13593. this.line = tokCurLine;
  13594. this.column = tokPos - tokLineStart;
  13595. }
  13596. function initTokenState() {
  13597. tokCurLine = 1;
  13598. tokPos = tokLineStart = 0;
  13599. tokRegexpAllowed = true;
  13600. skipSpace();
  13601. }
  13602. function finishToken(type, val) {
  13603. tokEnd = tokPos;
  13604. if (options.locations) tokEndLoc = new line_loc_t;
  13605. tokType = type;
  13606. skipSpace();
  13607. tokVal = val;
  13608. tokRegexpAllowed = type.beforeExpr;
  13609. }
  13610. function skipBlockComment() {
  13611. var startLoc = options.onComment && options.locations && new line_loc_t;
  13612. var start = tokPos, end = input.indexOf("*/", tokPos += 2);
  13613. if (end === -1) raise(tokPos - 2, "Unterminated comment");
  13614. tokPos = end + 2;
  13615. if (options.locations) {
  13616. lineBreak.lastIndex = start;
  13617. var match;
  13618. while ((match = lineBreak.exec(input)) && match.index < tokPos) {
  13619. ++tokCurLine;
  13620. tokLineStart = match.index + match[0].length;
  13621. }
  13622. }
  13623. if (options.onComment)
  13624. options.onComment(true, input.slice(start + 2, end), start, tokPos,
  13625. startLoc, options.locations && new line_loc_t);
  13626. }
  13627. function skipLineComment() {
  13628. var start = tokPos;
  13629. var startLoc = options.onComment && options.locations && new line_loc_t;
  13630. var ch = input.charCodeAt(tokPos+=2);
  13631. while (tokPos < inputLen && ch !== 10 && ch !== 13 && ch !== 8232 && ch !== 8233) {
  13632. ++tokPos;
  13633. ch = input.charCodeAt(tokPos);
  13634. }
  13635. if (options.onComment)
  13636. options.onComment(false, input.slice(start + 2, tokPos), start, tokPos,
  13637. startLoc, options.locations && new line_loc_t);
  13638. }
  13639. function skipSpace() {
  13640. while (tokPos < inputLen) {
  13641. var ch = input.charCodeAt(tokPos);
  13642. if (ch === 32) {
  13643. ++tokPos;
  13644. } else if (ch === 13) {
  13645. ++tokPos;
  13646. var next = input.charCodeAt(tokPos);
  13647. if (next === 10) {
  13648. ++tokPos;
  13649. }
  13650. if (options.locations) {
  13651. ++tokCurLine;
  13652. tokLineStart = tokPos;
  13653. }
  13654. } else if (ch === 10 || ch === 8232 || ch === 8233) {
  13655. ++tokPos;
  13656. if (options.locations) {
  13657. ++tokCurLine;
  13658. tokLineStart = tokPos;
  13659. }
  13660. } else if (ch > 8 && ch < 14) {
  13661. ++tokPos;
  13662. } else if (ch === 47) {
  13663. var next = input.charCodeAt(tokPos + 1);
  13664. if (next === 42) {
  13665. skipBlockComment();
  13666. } else if (next === 47) {
  13667. skipLineComment();
  13668. } else break;
  13669. } else if (ch === 160) {
  13670. ++tokPos;
  13671. } else if (ch >= 5760 && nonASCIIwhitespace.test(String.fromCharCode(ch))) {
  13672. ++tokPos;
  13673. } else {
  13674. break;
  13675. }
  13676. }
  13677. }
  13678. function readToken_dot() {
  13679. var next = input.charCodeAt(tokPos + 1);
  13680. if (next >= 48 && next <= 57) return readNumber(true);
  13681. ++tokPos;
  13682. return finishToken(_dot);
  13683. }
  13684. function readToken_slash() {
  13685. var next = input.charCodeAt(tokPos + 1);
  13686. if (tokRegexpAllowed) {++tokPos; return readRegexp();}
  13687. if (next === 61) return finishOp(_assign, 2);
  13688. return finishOp(_slash, 1);
  13689. }
  13690. function readToken_mult_modulo() {
  13691. var next = input.charCodeAt(tokPos + 1);
  13692. if (next === 61) return finishOp(_assign, 2);
  13693. return finishOp(_multiplyModulo, 1);
  13694. }
  13695. function readToken_pipe_amp(code) {
  13696. var next = input.charCodeAt(tokPos + 1);
  13697. if (next === code) return finishOp(code === 124 ? _logicalOR : _logicalAND, 2);
  13698. if (next === 61) return finishOp(_assign, 2);
  13699. return finishOp(code === 124 ? _bitwiseOR : _bitwiseAND, 1);
  13700. }
  13701. function readToken_caret() {
  13702. var next = input.charCodeAt(tokPos + 1);
  13703. if (next === 61) return finishOp(_assign, 2);
  13704. return finishOp(_bitwiseXOR, 1);
  13705. }
  13706. function readToken_plus_min(code) {
  13707. var next = input.charCodeAt(tokPos + 1);
  13708. if (next === code) {
  13709. if (next == 45 && input.charCodeAt(tokPos + 2) == 62 &&
  13710. newline.test(input.slice(lastEnd, tokPos))) {
  13711. tokPos += 3;
  13712. skipLineComment();
  13713. skipSpace();
  13714. return readToken();
  13715. }
  13716. return finishOp(_incDec, 2);
  13717. }
  13718. if (next === 61) return finishOp(_assign, 2);
  13719. return finishOp(_plusMin, 1);
  13720. }
  13721. function readToken_lt_gt(code) {
  13722. var next = input.charCodeAt(tokPos + 1);
  13723. var size = 1;
  13724. if (next === code) {
  13725. size = code === 62 && input.charCodeAt(tokPos + 2) === 62 ? 3 : 2;
  13726. if (input.charCodeAt(tokPos + size) === 61) return finishOp(_assign, size + 1);
  13727. return finishOp(_bitShift, size);
  13728. }
  13729. if (next == 33 && code == 60 && input.charCodeAt(tokPos + 2) == 45 &&
  13730. input.charCodeAt(tokPos + 3) == 45) {
  13731. tokPos += 4;
  13732. skipLineComment();
  13733. skipSpace();
  13734. return readToken();
  13735. }
  13736. if (next === 61)
  13737. size = input.charCodeAt(tokPos + 2) === 61 ? 3 : 2;
  13738. return finishOp(_relational, size);
  13739. }
  13740. function readToken_eq_excl(code) {
  13741. var next = input.charCodeAt(tokPos + 1);
  13742. if (next === 61) return finishOp(_equality, input.charCodeAt(tokPos + 2) === 61 ? 3 : 2);
  13743. return finishOp(code === 61 ? _eq : _prefix, 1);
  13744. }
  13745. function getTokenFromCode(code) {
  13746. switch(code) {
  13747. case 46:
  13748. return readToken_dot();
  13749. case 40: ++tokPos; return finishToken(_parenL);
  13750. case 41: ++tokPos; return finishToken(_parenR);
  13751. case 59: ++tokPos; return finishToken(_semi);
  13752. case 44: ++tokPos; return finishToken(_comma);
  13753. case 91: ++tokPos; return finishToken(_bracketL);
  13754. case 93: ++tokPos; return finishToken(_bracketR);
  13755. case 123: ++tokPos; return finishToken(_braceL);
  13756. case 125: ++tokPos; return finishToken(_braceR);
  13757. case 58: ++tokPos; return finishToken(_colon);
  13758. case 63: ++tokPos; return finishToken(_question);
  13759. case 48:
  13760. var next = input.charCodeAt(tokPos + 1);
  13761. if (next === 120 || next === 88) return readHexNumber();
  13762. case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57:
  13763. return readNumber(false);
  13764. case 34: case 39:
  13765. return readString(code);
  13766. case 47:
  13767. return readToken_slash(code);
  13768. case 37: case 42:
  13769. return readToken_mult_modulo();
  13770. case 124: case 38:
  13771. return readToken_pipe_amp(code);
  13772. case 94:
  13773. return readToken_caret();
  13774. case 43: case 45:
  13775. return readToken_plus_min(code);
  13776. case 60: case 62:
  13777. return readToken_lt_gt(code);
  13778. case 61: case 33:
  13779. return readToken_eq_excl(code);
  13780. case 126:
  13781. return finishOp(_prefix, 1);
  13782. }
  13783. return false;
  13784. }
  13785. function readToken(forceRegexp) {
  13786. if (!forceRegexp) tokStart = tokPos;
  13787. else tokPos = tokStart + 1;
  13788. if (options.locations) tokStartLoc = new line_loc_t;
  13789. if (forceRegexp) return readRegexp();
  13790. if (tokPos >= inputLen) return finishToken(_eof);
  13791. var code = input.charCodeAt(tokPos);
  13792. if (isIdentifierStart(code) || code === 92 ) return readWord();
  13793. var tok = getTokenFromCode(code);
  13794. if (tok === false) {
  13795. var ch = String.fromCharCode(code);
  13796. if (ch === "\\" || nonASCIIidentifierStart.test(ch)) return readWord();
  13797. raise(tokPos, "Unexpected character '" + ch + "'");
  13798. }
  13799. return tok;
  13800. }
  13801. function finishOp(type, size) {
  13802. var str = input.slice(tokPos, tokPos + size);
  13803. tokPos += size;
  13804. finishToken(type, str);
  13805. }
  13806. function readRegexp() {
  13807. var content = "", escaped, inClass, start = tokPos;
  13808. for (;;) {
  13809. if (tokPos >= inputLen) raise(start, "Unterminated regular expression");
  13810. var ch = input.charAt(tokPos);
  13811. if (newline.test(ch)) raise(start, "Unterminated regular expression");
  13812. if (!escaped) {
  13813. if (ch === "[") inClass = true;
  13814. else if (ch === "]" && inClass) inClass = false;
  13815. else if (ch === "/" && !inClass) break;
  13816. escaped = ch === "\\";
  13817. } else escaped = false;
  13818. ++tokPos;
  13819. }
  13820. var content = input.slice(start, tokPos);
  13821. ++tokPos;
  13822. var mods = readWord1();
  13823. if (mods && !/^[gmsiy]*$/.test(mods)) raise(start, "Invalid regexp flag");
  13824. try {
  13825. var value = new RegExp(content, mods);
  13826. } catch (e) {
  13827. if (e instanceof SyntaxError) raise(start, e.message);
  13828. raise(e);
  13829. }
  13830. return finishToken(_regexp, value);
  13831. }
  13832. function readInt(radix, len) {
  13833. var start = tokPos, total = 0;
  13834. for (var i = 0, e = len == null ? Infinity : len; i < e; ++i) {
  13835. var code = input.charCodeAt(tokPos), val;
  13836. if (code >= 97) val = code - 97 + 10;
  13837. else if (code >= 65) val = code - 65 + 10;
  13838. else if (code >= 48 && code <= 57) val = code - 48;
  13839. else val = Infinity;
  13840. if (val >= radix) break;
  13841. ++tokPos;
  13842. total = total * radix + val;
  13843. }
  13844. if (tokPos === start || len != null && tokPos - start !== len) return null;
  13845. return total;
  13846. }
  13847. function readHexNumber() {
  13848. tokPos += 2;
  13849. var val = readInt(16);
  13850. if (val == null) raise(tokStart + 2, "Expected hexadecimal number");
  13851. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  13852. return finishToken(_num, val);
  13853. }
  13854. function readNumber(startsWithDot) {
  13855. var start = tokPos, isFloat = false, octal = input.charCodeAt(tokPos) === 48;
  13856. if (!startsWithDot && readInt(10) === null) raise(start, "Invalid number");
  13857. if (input.charCodeAt(tokPos) === 46) {
  13858. ++tokPos;
  13859. readInt(10);
  13860. isFloat = true;
  13861. }
  13862. var next = input.charCodeAt(tokPos);
  13863. if (next === 69 || next === 101) {
  13864. next = input.charCodeAt(++tokPos);
  13865. if (next === 43 || next === 45) ++tokPos;
  13866. if (readInt(10) === null) raise(start, "Invalid number");
  13867. isFloat = true;
  13868. }
  13869. if (isIdentifierStart(input.charCodeAt(tokPos))) raise(tokPos, "Identifier directly after number");
  13870. var str = input.slice(start, tokPos), val;
  13871. if (isFloat) val = parseFloat(str);
  13872. else if (!octal || str.length === 1) val = parseInt(str, 10);
  13873. else if (/[89]/.test(str) || strict) raise(start, "Invalid number");
  13874. else val = parseInt(str, 8);
  13875. return finishToken(_num, val);
  13876. }
  13877. function readString(quote) {
  13878. tokPos++;
  13879. var out = "";
  13880. for (;;) {
  13881. if (tokPos >= inputLen) raise(tokStart, "Unterminated string constant");
  13882. var ch = input.charCodeAt(tokPos);
  13883. if (ch === quote) {
  13884. ++tokPos;
  13885. return finishToken(_string, out);
  13886. }
  13887. if (ch === 92) {
  13888. ch = input.charCodeAt(++tokPos);
  13889. var octal = /^[0-7]+/.exec(input.slice(tokPos, tokPos + 3));
  13890. if (octal) octal = octal[0];
  13891. while (octal && parseInt(octal, 8) > 255) octal = octal.slice(0, -1);
  13892. if (octal === "0") octal = null;
  13893. ++tokPos;
  13894. if (octal) {
  13895. if (strict) raise(tokPos - 2, "Octal literal in strict mode");
  13896. out += String.fromCharCode(parseInt(octal, 8));
  13897. tokPos += octal.length - 1;
  13898. } else {
  13899. switch (ch) {
  13900. case 110: out += "\n"; break;
  13901. case 114: out += "\r"; break;
  13902. case 120: out += String.fromCharCode(readHexChar(2)); break;
  13903. case 117: out += String.fromCharCode(readHexChar(4)); break;
  13904. case 85: out += String.fromCharCode(readHexChar(8)); break;
  13905. case 116: out += "\t"; break;
  13906. case 98: out += "\b"; break;
  13907. case 118: out += "\u000b"; break;
  13908. case 102: out += "\f"; break;
  13909. case 48: out += "\0"; break;
  13910. case 13: if (input.charCodeAt(tokPos) === 10) ++tokPos;
  13911. case 10:
  13912. if (options.locations) { tokLineStart = tokPos; ++tokCurLine; }
  13913. break;
  13914. default: out += String.fromCharCode(ch); break;
  13915. }
  13916. }
  13917. } else {
  13918. if (ch === 13 || ch === 10 || ch === 8232 || ch === 8233) raise(tokStart, "Unterminated string constant");
  13919. out += String.fromCharCode(ch);
  13920. ++tokPos;
  13921. }
  13922. }
  13923. }
  13924. function readHexChar(len) {
  13925. var n = readInt(16, len);
  13926. if (n === null) raise(tokStart, "Bad character escape sequence");
  13927. return n;
  13928. }
  13929. var containsEsc;
  13930. function readWord1() {
  13931. containsEsc = false;
  13932. var word, first = true, start = tokPos;
  13933. for (;;) {
  13934. var ch = input.charCodeAt(tokPos);
  13935. if (isIdentifierChar(ch)) {
  13936. if (containsEsc) word += input.charAt(tokPos);
  13937. ++tokPos;
  13938. } else if (ch === 92) {
  13939. if (!containsEsc) word = input.slice(start, tokPos);
  13940. containsEsc = true;
  13941. if (input.charCodeAt(++tokPos) != 117)
  13942. raise(tokPos, "Expecting Unicode escape sequence \\uXXXX");
  13943. ++tokPos;
  13944. var esc = readHexChar(4);
  13945. var escStr = String.fromCharCode(esc);
  13946. if (!escStr) raise(tokPos - 1, "Invalid Unicode escape");
  13947. if (!(first ? isIdentifierStart(esc) : isIdentifierChar(esc)))
  13948. raise(tokPos - 4, "Invalid Unicode escape");
  13949. word += escStr;
  13950. } else {
  13951. break;
  13952. }
  13953. first = false;
  13954. }
  13955. return containsEsc ? word : input.slice(start, tokPos);
  13956. }
  13957. function readWord() {
  13958. var word = readWord1();
  13959. var type = _name;
  13960. if (!containsEsc && isKeyword(word))
  13961. type = keywordTypes[word];
  13962. return finishToken(type, word);
  13963. }
  13964. function next() {
  13965. lastStart = tokStart;
  13966. lastEnd = tokEnd;
  13967. lastEndLoc = tokEndLoc;
  13968. readToken();
  13969. }
  13970. function setStrict(strct) {
  13971. strict = strct;
  13972. tokPos = tokStart;
  13973. if (options.locations) {
  13974. while (tokPos < tokLineStart) {
  13975. tokLineStart = input.lastIndexOf("\n", tokLineStart - 2) + 1;
  13976. --tokCurLine;
  13977. }
  13978. }
  13979. skipSpace();
  13980. readToken();
  13981. }
  13982. function node_t() {
  13983. this.type = null;
  13984. this.start = tokStart;
  13985. this.end = null;
  13986. }
  13987. function node_loc_t() {
  13988. this.start = tokStartLoc;
  13989. this.end = null;
  13990. if (sourceFile !== null) this.source = sourceFile;
  13991. }
  13992. function startNode() {
  13993. var node = new node_t();
  13994. if (options.locations)
  13995. node.loc = new node_loc_t();
  13996. if (options.directSourceFile)
  13997. node.sourceFile = options.directSourceFile;
  13998. if (options.ranges)
  13999. node.range = [tokStart, 0];
  14000. return node;
  14001. }
  14002. function startNodeFrom(other) {
  14003. var node = new node_t();
  14004. node.start = other.start;
  14005. if (options.locations) {
  14006. node.loc = new node_loc_t();
  14007. node.loc.start = other.loc.start;
  14008. }
  14009. if (options.ranges)
  14010. node.range = [other.range[0], 0];
  14011. return node;
  14012. }
  14013. function finishNode(node, type) {
  14014. node.type = type;
  14015. node.end = lastEnd;
  14016. if (options.locations)
  14017. node.loc.end = lastEndLoc;
  14018. if (options.ranges)
  14019. node.range[1] = lastEnd;
  14020. return node;
  14021. }
  14022. function isUseStrict(stmt) {
  14023. return options.ecmaVersion >= 5 && stmt.type === "ExpressionStatement" &&
  14024. stmt.expression.type === "Literal" && stmt.expression.value === "use strict";
  14025. }
  14026. function eat(type) {
  14027. if (tokType === type) {
  14028. next();
  14029. return true;
  14030. }
  14031. }
  14032. function canInsertSemicolon() {
  14033. return !options.strictSemicolons &&
  14034. (tokType === _eof || tokType === _braceR || newline.test(input.slice(lastEnd, tokStart)));
  14035. }
  14036. function semicolon() {
  14037. if (!eat(_semi) && !canInsertSemicolon()) unexpected();
  14038. }
  14039. function expect(type) {
  14040. if (tokType === type) next();
  14041. else unexpected();
  14042. }
  14043. function unexpected() {
  14044. raise(tokStart, "Unexpected token");
  14045. }
  14046. function checkLVal(expr) {
  14047. if (expr.type !== "Identifier" && expr.type !== "MemberExpression")
  14048. raise(expr.start, "Assigning to rvalue");
  14049. if (strict && expr.type === "Identifier" && isStrictBadIdWord(expr.name))
  14050. raise(expr.start, "Assigning to " + expr.name + " in strict mode");
  14051. }
  14052. function parseTopLevel(program) {
  14053. lastStart = lastEnd = tokPos;
  14054. if (options.locations) lastEndLoc = new line_loc_t;
  14055. inFunction = strict = null;
  14056. labels = [];
  14057. readToken();
  14058. var node = program || startNode(), first = true;
  14059. if (!program) node.body = [];
  14060. while (tokType !== _eof) {
  14061. var stmt = parseStatement();
  14062. node.body.push(stmt);
  14063. if (first && isUseStrict(stmt)) setStrict(true);
  14064. first = false;
  14065. }
  14066. return finishNode(node, "Program");
  14067. }
  14068. var loopLabel = {kind: "loop"}, switchLabel = {kind: "switch"};
  14069. function parseStatement() {
  14070. if (tokType === _slash || tokType === _assign && tokVal == "/=")
  14071. readToken(true);
  14072. var starttype = tokType, node = startNode();
  14073. switch (starttype) {
  14074. case _break: case _continue:
  14075. next();
  14076. var isBreak = starttype === _break;
  14077. if (eat(_semi) || canInsertSemicolon()) node.label = null;
  14078. else if (tokType !== _name) unexpected();
  14079. else {
  14080. node.label = parseIdent();
  14081. semicolon();
  14082. }
  14083. for (var i = 0; i < labels.length; ++i) {
  14084. var lab = labels[i];
  14085. if (node.label == null || lab.name === node.label.name) {
  14086. if (lab.kind != null && (isBreak || lab.kind === "loop")) break;
  14087. if (node.label && isBreak) break;
  14088. }
  14089. }
  14090. if (i === labels.length) raise(node.start, "Unsyntactic " + starttype.keyword);
  14091. return finishNode(node, isBreak ? "BreakStatement" : "ContinueStatement");
  14092. case _debugger:
  14093. next();
  14094. semicolon();
  14095. return finishNode(node, "DebuggerStatement");
  14096. case _do:
  14097. next();
  14098. labels.push(loopLabel);
  14099. node.body = parseStatement();
  14100. labels.pop();
  14101. expect(_while);
  14102. node.test = parseParenExpression();
  14103. semicolon();
  14104. return finishNode(node, "DoWhileStatement");
  14105. case _for:
  14106. next();
  14107. labels.push(loopLabel);
  14108. expect(_parenL);
  14109. if (tokType === _semi) return parseFor(node, null);
  14110. if (tokType === _var) {
  14111. var init = startNode();
  14112. next();
  14113. parseVar(init, true);
  14114. finishNode(init, "VariableDeclaration");
  14115. if (init.declarations.length === 1 && eat(_in))
  14116. return parseForIn(node, init);
  14117. return parseFor(node, init);
  14118. }
  14119. var init = parseExpression(false, true);
  14120. if (eat(_in)) {checkLVal(init); return parseForIn(node, init);}
  14121. return parseFor(node, init);
  14122. case _function:
  14123. next();
  14124. return parseFunction(node, true);
  14125. case _if:
  14126. next();
  14127. node.test = parseParenExpression();
  14128. node.consequent = parseStatement();
  14129. node.alternate = eat(_else) ? parseStatement() : null;
  14130. return finishNode(node, "IfStatement");
  14131. case _return:
  14132. if (!inFunction && !options.allowReturnOutsideFunction)
  14133. raise(tokStart, "'return' outside of function");
  14134. next();
  14135. if (eat(_semi) || canInsertSemicolon()) node.argument = null;
  14136. else { node.argument = parseExpression(); semicolon(); }
  14137. return finishNode(node, "ReturnStatement");
  14138. case _switch:
  14139. next();
  14140. node.discriminant = parseParenExpression();
  14141. node.cases = [];
  14142. expect(_braceL);
  14143. labels.push(switchLabel);
  14144. for (var cur, sawDefault; tokType != _braceR;) {
  14145. if (tokType === _case || tokType === _default) {
  14146. var isCase = tokType === _case;
  14147. if (cur) finishNode(cur, "SwitchCase");
  14148. node.cases.push(cur = startNode());
  14149. cur.consequent = [];
  14150. next();
  14151. if (isCase) cur.test = parseExpression();
  14152. else {
  14153. if (sawDefault) raise(lastStart, "Multiple default clauses"); sawDefault = true;
  14154. cur.test = null;
  14155. }
  14156. expect(_colon);
  14157. } else {
  14158. if (!cur) unexpected();
  14159. cur.consequent.push(parseStatement());
  14160. }
  14161. }
  14162. if (cur) finishNode(cur, "SwitchCase");
  14163. next();
  14164. labels.pop();
  14165. return finishNode(node, "SwitchStatement");
  14166. case _throw:
  14167. next();
  14168. if (newline.test(input.slice(lastEnd, tokStart)))
  14169. raise(lastEnd, "Illegal newline after throw");
  14170. node.argument = parseExpression();
  14171. semicolon();
  14172. return finishNode(node, "ThrowStatement");
  14173. case _try:
  14174. next();
  14175. node.block = parseBlock();
  14176. node.handler = null;
  14177. if (tokType === _catch) {
  14178. var clause = startNode();
  14179. next();
  14180. expect(_parenL);
  14181. clause.param = parseIdent();
  14182. if (strict && isStrictBadIdWord(clause.param.name))
  14183. raise(clause.param.start, "Binding " + clause.param.name + " in strict mode");
  14184. expect(_parenR);
  14185. clause.guard = null;
  14186. clause.body = parseBlock();
  14187. node.handler = finishNode(clause, "CatchClause");
  14188. }
  14189. node.guardedHandlers = empty;
  14190. node.finalizer = eat(_finally) ? parseBlock() : null;
  14191. if (!node.handler && !node.finalizer)
  14192. raise(node.start, "Missing catch or finally clause");
  14193. return finishNode(node, "TryStatement");
  14194. case _var:
  14195. next();
  14196. parseVar(node);
  14197. semicolon();
  14198. return finishNode(node, "VariableDeclaration");
  14199. case _while:
  14200. next();
  14201. node.test = parseParenExpression();
  14202. labels.push(loopLabel);
  14203. node.body = parseStatement();
  14204. labels.pop();
  14205. return finishNode(node, "WhileStatement");
  14206. case _with:
  14207. if (strict) raise(tokStart, "'with' in strict mode");
  14208. next();
  14209. node.object = parseParenExpression();
  14210. node.body = parseStatement();
  14211. return finishNode(node, "WithStatement");
  14212. case _braceL:
  14213. return parseBlock();
  14214. case _semi:
  14215. next();
  14216. return finishNode(node, "EmptyStatement");
  14217. default:
  14218. var maybeName = tokVal, expr = parseExpression();
  14219. if (starttype === _name && expr.type === "Identifier" && eat(_colon)) {
  14220. for (var i = 0; i < labels.length; ++i)
  14221. if (labels[i].name === maybeName) raise(expr.start, "Label '" + maybeName + "' is already declared");
  14222. var kind = tokType.isLoop ? "loop" : tokType === _switch ? "switch" : null;
  14223. labels.push({name: maybeName, kind: kind});
  14224. node.body = parseStatement();
  14225. labels.pop();
  14226. node.label = expr;
  14227. return finishNode(node, "LabeledStatement");
  14228. } else {
  14229. node.expression = expr;
  14230. semicolon();
  14231. return finishNode(node, "ExpressionStatement");
  14232. }
  14233. }
  14234. }
  14235. function parseParenExpression() {
  14236. expect(_parenL);
  14237. var val = parseExpression();
  14238. expect(_parenR);
  14239. return val;
  14240. }
  14241. function parseBlock(allowStrict) {
  14242. var node = startNode(), first = true, strict = false, oldStrict;
  14243. node.body = [];
  14244. expect(_braceL);
  14245. while (!eat(_braceR)) {
  14246. var stmt = parseStatement();
  14247. node.body.push(stmt);
  14248. if (first && allowStrict && isUseStrict(stmt)) {
  14249. oldStrict = strict;
  14250. setStrict(strict = true);
  14251. }
  14252. first = false;
  14253. }
  14254. if (strict && !oldStrict) setStrict(false);
  14255. return finishNode(node, "BlockStatement");
  14256. }
  14257. function parseFor(node, init) {
  14258. node.init = init;
  14259. expect(_semi);
  14260. node.test = tokType === _semi ? null : parseExpression();
  14261. expect(_semi);
  14262. node.update = tokType === _parenR ? null : parseExpression();
  14263. expect(_parenR);
  14264. node.body = parseStatement();
  14265. labels.pop();
  14266. return finishNode(node, "ForStatement");
  14267. }
  14268. function parseForIn(node, init) {
  14269. node.left = init;
  14270. node.right = parseExpression();
  14271. expect(_parenR);
  14272. node.body = parseStatement();
  14273. labels.pop();
  14274. return finishNode(node, "ForInStatement");
  14275. }
  14276. function parseVar(node, noIn) {
  14277. node.declarations = [];
  14278. node.kind = "var";
  14279. for (;;) {
  14280. var decl = startNode();
  14281. decl.id = parseIdent();
  14282. if (strict && isStrictBadIdWord(decl.id.name))
  14283. raise(decl.id.start, "Binding " + decl.id.name + " in strict mode");
  14284. decl.init = eat(_eq) ? parseExpression(true, noIn) : null;
  14285. node.declarations.push(finishNode(decl, "VariableDeclarator"));
  14286. if (!eat(_comma)) break;
  14287. }
  14288. return node;
  14289. }
  14290. function parseExpression(noComma, noIn) {
  14291. var expr = parseMaybeAssign(noIn);
  14292. if (!noComma && tokType === _comma) {
  14293. var node = startNodeFrom(expr);
  14294. node.expressions = [expr];
  14295. while (eat(_comma)) node.expressions.push(parseMaybeAssign(noIn));
  14296. return finishNode(node, "SequenceExpression");
  14297. }
  14298. return expr;
  14299. }
  14300. function parseMaybeAssign(noIn) {
  14301. var left = parseMaybeConditional(noIn);
  14302. if (tokType.isAssign) {
  14303. var node = startNodeFrom(left);
  14304. node.operator = tokVal;
  14305. node.left = left;
  14306. next();
  14307. node.right = parseMaybeAssign(noIn);
  14308. checkLVal(left);
  14309. return finishNode(node, "AssignmentExpression");
  14310. }
  14311. return left;
  14312. }
  14313. function parseMaybeConditional(noIn) {
  14314. var expr = parseExprOps(noIn);
  14315. if (eat(_question)) {
  14316. var node = startNodeFrom(expr);
  14317. node.test = expr;
  14318. node.consequent = parseExpression(true);
  14319. expect(_colon);
  14320. node.alternate = parseExpression(true, noIn);
  14321. return finishNode(node, "ConditionalExpression");
  14322. }
  14323. return expr;
  14324. }
  14325. function parseExprOps(noIn) {
  14326. return parseExprOp(parseMaybeUnary(), -1, noIn);
  14327. }
  14328. function parseExprOp(left, minPrec, noIn) {
  14329. var prec = tokType.binop;
  14330. if (prec != null && (!noIn || tokType !== _in)) {
  14331. if (prec > minPrec) {
  14332. var node = startNodeFrom(left);
  14333. node.left = left;
  14334. node.operator = tokVal;
  14335. var op = tokType;
  14336. next();
  14337. node.right = parseExprOp(parseMaybeUnary(), prec, noIn);
  14338. var exprNode = finishNode(node, (op === _logicalOR || op === _logicalAND) ? "LogicalExpression" : "BinaryExpression");
  14339. return parseExprOp(exprNode, minPrec, noIn);
  14340. }
  14341. }
  14342. return left;
  14343. }
  14344. function parseMaybeUnary() {
  14345. if (tokType.prefix) {
  14346. var node = startNode(), update = tokType.isUpdate;
  14347. node.operator = tokVal;
  14348. node.prefix = true;
  14349. tokRegexpAllowed = true;
  14350. next();
  14351. node.argument = parseMaybeUnary();
  14352. if (update) checkLVal(node.argument);
  14353. else if (strict && node.operator === "delete" &&
  14354. node.argument.type === "Identifier")
  14355. raise(node.start, "Deleting local variable in strict mode");
  14356. return finishNode(node, update ? "UpdateExpression" : "UnaryExpression");
  14357. }
  14358. var expr = parseExprSubscripts();
  14359. while (tokType.postfix && !canInsertSemicolon()) {
  14360. var node = startNodeFrom(expr);
  14361. node.operator = tokVal;
  14362. node.prefix = false;
  14363. node.argument = expr;
  14364. checkLVal(expr);
  14365. next();
  14366. expr = finishNode(node, "UpdateExpression");
  14367. }
  14368. return expr;
  14369. }
  14370. function parseExprSubscripts() {
  14371. return parseSubscripts(parseExprAtom());
  14372. }
  14373. function parseSubscripts(base, noCalls) {
  14374. if (eat(_dot)) {
  14375. var node = startNodeFrom(base);
  14376. node.object = base;
  14377. node.property = parseIdent(true);
  14378. node.computed = false;
  14379. return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
  14380. } else if (eat(_bracketL)) {
  14381. var node = startNodeFrom(base);
  14382. node.object = base;
  14383. node.property = parseExpression();
  14384. node.computed = true;
  14385. expect(_bracketR);
  14386. return parseSubscripts(finishNode(node, "MemberExpression"), noCalls);
  14387. } else if (!noCalls && eat(_parenL)) {
  14388. var node = startNodeFrom(base);
  14389. node.callee = base;
  14390. node.arguments = parseExprList(_parenR, false);
  14391. return parseSubscripts(finishNode(node, "CallExpression"), noCalls);
  14392. } else return base;
  14393. }
  14394. function parseExprAtom() {
  14395. switch (tokType) {
  14396. case _this:
  14397. var node = startNode();
  14398. next();
  14399. return finishNode(node, "ThisExpression");
  14400. case _name:
  14401. return parseIdent();
  14402. case _num: case _string: case _regexp:
  14403. var node = startNode();
  14404. node.value = tokVal;
  14405. node.raw = input.slice(tokStart, tokEnd);
  14406. next();
  14407. return finishNode(node, "Literal");
  14408. case _null: case _true: case _false:
  14409. var node = startNode();
  14410. node.value = tokType.atomValue;
  14411. node.raw = tokType.keyword;
  14412. next();
  14413. return finishNode(node, "Literal");
  14414. case _parenL:
  14415. var tokStartLoc1 = tokStartLoc, tokStart1 = tokStart;
  14416. next();
  14417. var val = parseExpression();
  14418. val.start = tokStart1;
  14419. val.end = tokEnd;
  14420. if (options.locations) {
  14421. val.loc.start = tokStartLoc1;
  14422. val.loc.end = tokEndLoc;
  14423. }
  14424. if (options.ranges)
  14425. val.range = [tokStart1, tokEnd];
  14426. expect(_parenR);
  14427. return val;
  14428. case _bracketL:
  14429. var node = startNode();
  14430. next();
  14431. node.elements = parseExprList(_bracketR, true, true);
  14432. return finishNode(node, "ArrayExpression");
  14433. case _braceL:
  14434. return parseObj();
  14435. case _function:
  14436. var node = startNode();
  14437. next();
  14438. return parseFunction(node, false);
  14439. case _new:
  14440. return parseNew();
  14441. default:
  14442. unexpected();
  14443. }
  14444. }
  14445. function parseNew() {
  14446. var node = startNode();
  14447. next();
  14448. node.callee = parseSubscripts(parseExprAtom(), true);
  14449. if (eat(_parenL)) node.arguments = parseExprList(_parenR, false);
  14450. else node.arguments = empty;
  14451. return finishNode(node, "NewExpression");
  14452. }
  14453. function parseObj() {
  14454. var node = startNode(), first = true, sawGetSet = false;
  14455. node.properties = [];
  14456. next();
  14457. while (!eat(_braceR)) {
  14458. if (!first) {
  14459. expect(_comma);
  14460. if (options.allowTrailingCommas && eat(_braceR)) break;
  14461. } else first = false;
  14462. var prop = {key: parsePropertyName()}, isGetSet = false, kind;
  14463. if (eat(_colon)) {
  14464. prop.value = parseExpression(true);
  14465. kind = prop.kind = "init";
  14466. } else if (options.ecmaVersion >= 5 && prop.key.type === "Identifier" &&
  14467. (prop.key.name === "get" || prop.key.name === "set")) {
  14468. isGetSet = sawGetSet = true;
  14469. kind = prop.kind = prop.key.name;
  14470. prop.key = parsePropertyName();
  14471. if (tokType !== _parenL) unexpected();
  14472. prop.value = parseFunction(startNode(), false);
  14473. } else unexpected();
  14474. if (prop.key.type === "Identifier" && (strict || sawGetSet)) {
  14475. for (var i = 0; i < node.properties.length; ++i) {
  14476. var other = node.properties[i];
  14477. if (other.key.name === prop.key.name) {
  14478. var conflict = kind == other.kind || isGetSet && other.kind === "init" ||
  14479. kind === "init" && (other.kind === "get" || other.kind === "set");
  14480. if (conflict && !strict && kind === "init" && other.kind === "init") conflict = false;
  14481. if (conflict) raise(prop.key.start, "Redefinition of property");
  14482. }
  14483. }
  14484. }
  14485. node.properties.push(prop);
  14486. }
  14487. return finishNode(node, "ObjectExpression");
  14488. }
  14489. function parsePropertyName() {
  14490. if (tokType === _num || tokType === _string) return parseExprAtom();
  14491. return parseIdent(true);
  14492. }
  14493. function parseFunction(node, isStatement) {
  14494. if (tokType === _name) node.id = parseIdent();
  14495. else if (isStatement) unexpected();
  14496. else node.id = null;
  14497. node.params = [];
  14498. var first = true;
  14499. expect(_parenL);
  14500. while (!eat(_parenR)) {
  14501. if (!first) expect(_comma); else first = false;
  14502. node.params.push(parseIdent());
  14503. }
  14504. var oldInFunc = inFunction, oldLabels = labels;
  14505. inFunction = true; labels = [];
  14506. node.body = parseBlock(true);
  14507. inFunction = oldInFunc; labels = oldLabels;
  14508. if (strict || node.body.body.length && isUseStrict(node.body.body[0])) {
  14509. for (var i = node.id ? -1 : 0; i < node.params.length; ++i) {
  14510. var id = i < 0 ? node.id : node.params[i];
  14511. if (isStrictReservedWord(id.name) || isStrictBadIdWord(id.name))
  14512. raise(id.start, "Defining '" + id.name + "' in strict mode");
  14513. if (i >= 0) for (var j = 0; j < i; ++j) if (id.name === node.params[j].name)
  14514. raise(id.start, "Argument name clash in strict mode");
  14515. }
  14516. }
  14517. return finishNode(node, isStatement ? "FunctionDeclaration" : "FunctionExpression");
  14518. }
  14519. function parseExprList(close, allowTrailingComma, allowEmpty) {
  14520. var elts = [], first = true;
  14521. while (!eat(close)) {
  14522. if (!first) {
  14523. expect(_comma);
  14524. if (allowTrailingComma && options.allowTrailingCommas && eat(close)) break;
  14525. } else first = false;
  14526. if (allowEmpty && tokType === _comma) elts.push(null);
  14527. else elts.push(parseExpression(true));
  14528. }
  14529. return elts;
  14530. }
  14531. function parseIdent(liberal) {
  14532. var node = startNode();
  14533. if (liberal && options.forbidReserved == "everywhere") liberal = false;
  14534. if (tokType === _name) {
  14535. if (!liberal &&
  14536. (options.forbidReserved &&
  14537. (options.ecmaVersion === 3 ? isReservedWord3 : isReservedWord5)(tokVal) ||
  14538. strict && isStrictReservedWord(tokVal)) &&
  14539. input.slice(tokStart, tokEnd).indexOf("\\") == -1)
  14540. raise(tokStart, "The keyword '" + tokVal + "' is reserved");
  14541. node.name = tokVal;
  14542. } else if (liberal && tokType.keyword) {
  14543. node.name = tokType.keyword;
  14544. } else {
  14545. unexpected();
  14546. }
  14547. tokRegexpAllowed = false;
  14548. next();
  14549. return finishNode(node, "Identifier");
  14550. }
  14551. });
  14552. if (!acorn.version)
  14553. acorn = null;
  14554. }
  14555. function parse(code, options) {
  14556. return (global.acorn || acorn).parse(code, options);
  14557. }
  14558. var binaryOperators = {
  14559. '+': '__add',
  14560. '-': '__subtract',
  14561. '*': '__multiply',
  14562. '/': '__divide',
  14563. '%': '__modulo',
  14564. '==': '__equals',
  14565. '!=': '__equals'
  14566. };
  14567. var unaryOperators = {
  14568. '-': '__negate',
  14569. '+': '__self'
  14570. };
  14571. var fields = Base.each(
  14572. ['add', 'subtract', 'multiply', 'divide', 'modulo', 'equals', 'negate'],
  14573. function(name) {
  14574. this['__' + name] = '#' + name;
  14575. },
  14576. {
  14577. __self: function() {
  14578. return this;
  14579. }
  14580. }
  14581. );
  14582. Point.inject(fields);
  14583. Size.inject(fields);
  14584. Color.inject(fields);
  14585. function __$__(left, operator, right) {
  14586. var handler = binaryOperators[operator];
  14587. if (left && left[handler]) {
  14588. var res = left[handler](right);
  14589. return operator === '!=' ? !res : res;
  14590. }
  14591. switch (operator) {
  14592. case '+': return left + right;
  14593. case '-': return left - right;
  14594. case '*': return left * right;
  14595. case '/': return left / right;
  14596. case '%': return left % right;
  14597. case '==': return left == right;
  14598. case '!=': return left != right;
  14599. }
  14600. }
  14601. function $__(operator, value) {
  14602. var handler = unaryOperators[operator];
  14603. if (value && value[handler])
  14604. return value[handler]();
  14605. switch (operator) {
  14606. case '+': return +value;
  14607. case '-': return -value;
  14608. }
  14609. }
  14610. function compile(code, options) {
  14611. if (!code)
  14612. return '';
  14613. options = options || {};
  14614. var insertions = [];
  14615. function getOffset(offset) {
  14616. for (var i = 0, l = insertions.length; i < l; i++) {
  14617. var insertion = insertions[i];
  14618. if (insertion[0] >= offset)
  14619. break;
  14620. offset += insertion[1];
  14621. }
  14622. return offset;
  14623. }
  14624. function getCode(node) {
  14625. return code.substring(getOffset(node.range[0]),
  14626. getOffset(node.range[1]));
  14627. }
  14628. function getBetween(left, right) {
  14629. return code.substring(getOffset(left.range[1]),
  14630. getOffset(right.range[0]));
  14631. }
  14632. function replaceCode(node, str) {
  14633. var start = getOffset(node.range[0]),
  14634. end = getOffset(node.range[1]),
  14635. insert = 0;
  14636. for (var i = insertions.length - 1; i >= 0; i--) {
  14637. if (start > insertions[i][0]) {
  14638. insert = i + 1;
  14639. break;
  14640. }
  14641. }
  14642. insertions.splice(insert, 0, [start, str.length - end + start]);
  14643. code = code.substring(0, start) + str + code.substring(end);
  14644. }
  14645. function walkAST(node, parent) {
  14646. if (!node)
  14647. return;
  14648. for (var key in node) {
  14649. if (key === 'range' || key === 'loc')
  14650. continue;
  14651. var value = node[key];
  14652. if (Array.isArray(value)) {
  14653. for (var i = 0, l = value.length; i < l; i++)
  14654. walkAST(value[i], node);
  14655. } else if (value && typeof value === 'object') {
  14656. walkAST(value, node);
  14657. }
  14658. }
  14659. switch (node.type) {
  14660. case 'UnaryExpression':
  14661. if (node.operator in unaryOperators
  14662. && node.argument.type !== 'Literal') {
  14663. var arg = getCode(node.argument);
  14664. replaceCode(node, '$__("' + node.operator + '", '
  14665. + arg + ')');
  14666. }
  14667. break;
  14668. case 'BinaryExpression':
  14669. if (node.operator in binaryOperators
  14670. && node.left.type !== 'Literal') {
  14671. var left = getCode(node.left),
  14672. right = getCode(node.right),
  14673. between = getBetween(node.left, node.right),
  14674. operator = node.operator;
  14675. replaceCode(node, '__$__(' + left + ','
  14676. + between.replace(new RegExp('\\' + operator),
  14677. '"' + operator + '"')
  14678. + ', ' + right + ')');
  14679. }
  14680. break;
  14681. case 'UpdateExpression':
  14682. case 'AssignmentExpression':
  14683. var parentType = parent && parent.type;
  14684. if (!(
  14685. parentType === 'ForStatement'
  14686. || parentType === 'BinaryExpression'
  14687. && /^[=!<>]/.test(parent.operator)
  14688. || parentType === 'MemberExpression' && parent.computed
  14689. )) {
  14690. if (node.type === 'UpdateExpression') {
  14691. var arg = getCode(node.argument),
  14692. exp = '__$__(' + arg + ', "' + node.operator[0]
  14693. + '", 1)',
  14694. str = arg + ' = ' + exp;
  14695. if (!node.prefix
  14696. && (parentType === 'AssignmentExpression'
  14697. || parentType === 'VariableDeclarator')) {
  14698. if (getCode(parent.left || parent.id) === arg)
  14699. str = exp;
  14700. str = arg + '; ' + str;
  14701. }
  14702. replaceCode(node, str);
  14703. } else {
  14704. if (/^.=$/.test(node.operator)
  14705. && node.left.type !== 'Literal') {
  14706. var left = getCode(node.left),
  14707. right = getCode(node.right),
  14708. exp = left + ' = __$__(' + left + ', "'
  14709. + node.operator[0] + '", ' + right + ')';
  14710. replaceCode(node, /^\(.*\)$/.test(getCode(node))
  14711. ? '(' + exp + ')' : exp);
  14712. }
  14713. }
  14714. }
  14715. break;
  14716. }
  14717. }
  14718. function encodeVLQ(value) {
  14719. var res = '',
  14720. base64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  14721. value = (Math.abs(value) << 1) + (value < 0 ? 1 : 0);
  14722. while (value || !res) {
  14723. var next = value & (32 - 1);
  14724. value >>= 5;
  14725. if (value)
  14726. next |= 32;
  14727. res += base64[next];
  14728. }
  14729. return res;
  14730. }
  14731. var url = options.url || '',
  14732. agent = paper.agent,
  14733. version = agent.versionNumber,
  14734. offsetCode = false,
  14735. sourceMaps = options.sourceMaps,
  14736. source = options.source || code,
  14737. lineBreaks = /\r\n|\n|\r/mg,
  14738. offset = options.offset || 0,
  14739. map;
  14740. if (sourceMaps && (agent.chrome && version >= 30
  14741. || agent.webkit && version >= 537.76
  14742. || agent.firefox && version >= 23
  14743. || agent.node)) {
  14744. if (agent.node) {
  14745. offset -= 2;
  14746. } else if (window && url && !window.location.href.indexOf(url)) {
  14747. var html = document.getElementsByTagName('html')[0].innerHTML;
  14748. offset = html.substr(0, html.indexOf(code) + 1).match(
  14749. lineBreaks).length + 1;
  14750. }
  14751. offsetCode = offset > 0 && !(
  14752. agent.chrome && version >= 36 ||
  14753. agent.safari && version >= 600 ||
  14754. agent.firefox && version >= 40 ||
  14755. agent.node);
  14756. var mappings = ['AA' + encodeVLQ(offsetCode ? 0 : offset) + 'A'];
  14757. mappings.length = (code.match(lineBreaks) || []).length + 1
  14758. + (offsetCode ? offset : 0);
  14759. map = {
  14760. version: 3,
  14761. file: url,
  14762. names:[],
  14763. mappings: mappings.join(';AACA'),
  14764. sourceRoot: '',
  14765. sources: [url],
  14766. sourcesContent: [source]
  14767. };
  14768. }
  14769. walkAST(parse(code, { ranges: true, preserveParens: true }));
  14770. if (map) {
  14771. if (offsetCode) {
  14772. code = new Array(offset + 1).join('\n') + code;
  14773. }
  14774. if (/^(inline|both)$/.test(sourceMaps)) {
  14775. code += "\n//# sourceMappingURL=data:application/json;base64,"
  14776. + self.btoa(unescape(encodeURIComponent(
  14777. JSON.stringify(map))));
  14778. }
  14779. code += "\n//# sourceURL=" + (url || 'paperscript');
  14780. }
  14781. return {
  14782. url: url,
  14783. source: source,
  14784. code: code,
  14785. map: map
  14786. };
  14787. }
  14788. function execute(code, scope, options) {
  14789. paper = scope;
  14790. var view = scope.getView(),
  14791. tool = /\btool\.\w+|\s+on(?:Key|Mouse)(?:Up|Down|Move|Drag)\b/
  14792. .test(code) && !/\bnew\s+Tool\b/.test(code)
  14793. ? new Tool() : null,
  14794. toolHandlers = tool ? tool._events : [],
  14795. handlers = ['onFrame', 'onResize'].concat(toolHandlers),
  14796. params = [],
  14797. args = [],
  14798. func,
  14799. compiled = typeof code === 'object' ? code : compile(code, options);
  14800. code = compiled.code;
  14801. function expose(scope, hidden) {
  14802. for (var key in scope) {
  14803. if ((hidden || !/^_/.test(key)) && new RegExp('([\\b\\s\\W]|^)'
  14804. + key.replace(/\$/g, '\\$') + '\\b').test(code)) {
  14805. params.push(key);
  14806. args.push(scope[key]);
  14807. }
  14808. }
  14809. }
  14810. expose({ __$__: __$__, $__: $__, paper: scope, view: view, tool: tool },
  14811. true);
  14812. expose(scope);
  14813. handlers = Base.each(handlers, function(key) {
  14814. if (new RegExp('\\s+' + key + '\\b').test(code)) {
  14815. params.push(key);
  14816. this.push(key + ': ' + key);
  14817. }
  14818. }, []).join(', ');
  14819. if (handlers)
  14820. code += '\nreturn { ' + handlers + ' };';
  14821. var agent = paper.agent;
  14822. if (document && (agent.chrome
  14823. || agent.firefox && agent.versionNumber < 40)) {
  14824. var script = document.createElement('script'),
  14825. head = document.head || document.getElementsByTagName('head')[0];
  14826. if (agent.firefox)
  14827. code = '\n' + code;
  14828. script.appendChild(document.createTextNode(
  14829. 'paper._execute = function(' + params + ') {' + code + '\n}'
  14830. ));
  14831. head.appendChild(script);
  14832. func = paper._execute;
  14833. delete paper._execute;
  14834. head.removeChild(script);
  14835. } else {
  14836. func = Function(params, code);
  14837. }
  14838. var res = func.apply(scope, args) || {};
  14839. Base.each(toolHandlers, function(key) {
  14840. var value = res[key];
  14841. if (value)
  14842. tool[key] = value;
  14843. });
  14844. if (view) {
  14845. if (res.onResize)
  14846. view.setOnResize(res.onResize);
  14847. view.emit('resize', {
  14848. size: view.size,
  14849. delta: new Point()
  14850. });
  14851. if (res.onFrame)
  14852. view.setOnFrame(res.onFrame);
  14853. view.requestUpdate();
  14854. }
  14855. return compiled;
  14856. }
  14857. function loadScript(script) {
  14858. if (/^text\/(?:x-|)paperscript$/.test(script.type)
  14859. && PaperScope.getAttribute(script, 'ignore') !== 'true') {
  14860. var canvasId = PaperScope.getAttribute(script, 'canvas'),
  14861. canvas = document.getElementById(canvasId),
  14862. src = script.src || script.getAttribute('data-src'),
  14863. async = PaperScope.hasAttribute(script, 'async'),
  14864. scopeAttribute = 'data-paper-scope';
  14865. if (!canvas)
  14866. throw new Error('Unable to find canvas with id "'
  14867. + canvasId + '"');
  14868. var scope = PaperScope.get(canvas.getAttribute(scopeAttribute))
  14869. || new PaperScope().setup(canvas);
  14870. canvas.setAttribute(scopeAttribute, scope._id);
  14871. if (src) {
  14872. Http.request({
  14873. url: src,
  14874. async: async,
  14875. mimeType: 'text/plain',
  14876. onLoad: function(code) {
  14877. execute(code, scope, src);
  14878. }
  14879. });
  14880. } else {
  14881. execute(script.innerHTML, scope, script.baseURI);
  14882. }
  14883. script.setAttribute('data-paper-ignore', 'true');
  14884. return scope;
  14885. }
  14886. }
  14887. function loadAll() {
  14888. Base.each(document && document.getElementsByTagName('script'),
  14889. loadScript);
  14890. }
  14891. function load(script) {
  14892. return script ? loadScript(script) : loadAll();
  14893. }
  14894. if (window) {
  14895. if (document.readyState === 'complete') {
  14896. setTimeout(loadAll);
  14897. } else {
  14898. DomEvent.add(window, { load: loadAll });
  14899. }
  14900. }
  14901. return {
  14902. compile: compile,
  14903. execute: execute,
  14904. load: load,
  14905. parse: parse
  14906. };
  14907. }.call(this);
  14908. paper = new (PaperScope.inject(Base.exports, {
  14909. Base: Base,
  14910. Numerical: Numerical,
  14911. Key: Key,
  14912. DomEvent: DomEvent,
  14913. DomElement: DomElement,
  14914. document: document,
  14915. window: window,
  14916. Symbol: SymbolDefinition,
  14917. PlacedSymbol: SymbolItem
  14918. }))();
  14919. if (paper.agent.node) {
  14920. require('./node/extend.js')(paper);
  14921. }
  14922. if (typeof define === 'function' && define.amd) {
  14923. define('paper', paper);
  14924. } else if (typeof module === 'object' && module) {
  14925. module.exports = paper;
  14926. }
  14927. return paper;
  14928. }.call(this, typeof self === 'object' ? self : null);