svgcanvas.js 299 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320
  1. /*
  2. * svgcanvas.js
  3. *
  4. * Licensed under the Apache License, Version 2
  5. *
  6. * Copyright(c) 2010 Alexis Deveria
  7. * Copyright(c) 2010 Pavol Rusnak
  8. * Copyright(c) 2010 Jeff Schiller
  9. *
  10. */
  11. if(!window.console) {
  12. window.console = {};
  13. window.console.log = function(str) {};
  14. window.console.dir = function(str) {};
  15. }
  16. if(window.opera) {
  17. window.console.log = function(str) {opera.postError(str);};
  18. window.console.dir = function(str) {};
  19. }
  20. (function() {
  21. // This fixes $(...).attr() to work as expected with SVG elements.
  22. // Does not currently use *AttributeNS() since we rarely need that.
  23. // See http://api.jquery.com/attr/ for basic documentation of .attr()
  24. // Additional functionality:
  25. // - When getting attributes, a string that's a number is return as type number.
  26. // - If an array is supplied as first parameter, multiple values are returned
  27. // as an object with values for each given attributes
  28. var proxied = jQuery.fn.attr, svgns = "http://www.w3.org/2000/svg";
  29. jQuery.fn.attr = function(key, value) {
  30. var len = this.length;
  31. if(!len) return this;
  32. for(var i=0; i<len; i++) {
  33. var elem = this[i];
  34. // set/get SVG attribute
  35. if(elem.namespaceURI === svgns) {
  36. // Setting attribute
  37. if(value !== undefined) {
  38. elem.setAttribute(key, value);
  39. } else if($.isArray(key)) {
  40. // Getting attributes from array
  41. var j = key.length, obj = {};
  42. while(j--) {
  43. var aname = key[j];
  44. var attr = elem.getAttribute(aname);
  45. // This returns a number when appropriate
  46. if(attr || attr === "0") {
  47. attr = isNaN(attr)?attr:attr-0;
  48. }
  49. obj[aname] = attr;
  50. }
  51. return obj;
  52. } else if(typeof key === "object") {
  53. // Setting attributes form object
  54. for(var v in key) {
  55. elem.setAttribute(v, key[v]);
  56. }
  57. // Getting attribute
  58. } else {
  59. var attr = elem.getAttribute(key);
  60. if(attr || attr === "0") {
  61. attr = isNaN(attr)?attr:attr-0;
  62. }
  63. return attr;
  64. }
  65. } else {
  66. return proxied.apply(this, arguments);
  67. }
  68. }
  69. return this;
  70. };
  71. }());
  72. // Class: SvgCanvas
  73. // The main SvgCanvas class that manages all SVG-related functions
  74. //
  75. // Parameters:
  76. // container - The container HTML element that should hold the SVG root element
  77. // config - An object that contains configuration data
  78. $.SvgCanvas = function(container, config)
  79. {
  80. var isOpera = !!window.opera,
  81. isWebkit = navigator.userAgent.indexOf("AppleWebKit") != -1,
  82. // Object populated later with booleans indicating support for features
  83. support = {},
  84. // this defines which elements and attributes that we support
  85. svgWhiteList = {
  86. // SVG Elements
  87. "a": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "id", "mask", "opacity", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "xlink:href", "xlink:title"],
  88. "circle": ["class", "clip-path", "clip-rule", "cx", "cy", "fill", "fill-opacity", "fill-rule", "filter", "id", "mask", "opacity", "r", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  89. "clipPath": ["class", "clipPathUnits", "id"],
  90. "defs": [],
  91. "desc": [],
  92. "ellipse": ["class", "clip-path", "clip-rule", "cx", "cy", "fill", "fill-opacity", "fill-rule", "filter", "id", "mask", "opacity", "requiredFeatures", "rx", "ry", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  93. "feGaussianBlur": ["class", "color-interpolation-filters", "id", "requiredFeatures", "stdDeviation"],
  94. "filter": ["class", "color-interpolation-filters", "filterRes", "filterUnits", "height", "id", "primitiveUnits", "requiredFeatures", "width", "x", "xlink:href", "y"],
  95. "foreignObject": ["class", "font-size", "height", "id", "opacity", "requiredFeatures", "style", "transform", "width", "x", "y"],
  96. "g": ["class", "clip-path", "clip-rule", "id", "display", "fill", "fill-opacity", "fill-rule", "filter", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  97. "image": ["class", "clip-path", "clip-rule", "filter", "height", "id", "mask", "opacity", "requiredFeatures", "style", "systemLanguage", "transform", "width", "x", "xlink:href", "xlink:title", "y"],
  98. "line": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "id", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "x1", "x2", "y1", "y2"],
  99. "linearGradient": ["class", "id", "gradientTransform", "gradientUnits", "requiredFeatures", "spreadMethod", "systemLanguage", "x1", "x2", "xlink:href", "y1", "y2"],
  100. "marker": ["id", "class", "markerHeight", "markerUnits", "markerWidth", "orient", "preserveAspectRatio", "refX", "refY", "systemLanguage", "viewBox"],
  101. "mask": ["class", "height", "id", "maskContentUnits", "maskUnits", "width", "x", "y"],
  102. "metadata": ["class", "id"],
  103. "path": ["class", "clip-path", "clip-rule", "d", "fill", "fill-opacity", "fill-rule", "filter", "id", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  104. "pattern": ["class", "height", "id", "patternContentUnits", "patternTransform", "patternUnits", "requiredFeatures", "style", "systemLanguage", "width", "x", "xlink:href", "y"],
  105. "polygon": ["class", "clip-path", "clip-rule", "id", "fill", "fill-opacity", "fill-rule", "filter", "id", "class", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "points", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  106. "polyline": ["class", "clip-path", "clip-rule", "id", "fill", "fill-opacity", "fill-rule", "filter", "marker-end", "marker-mid", "marker-start", "mask", "opacity", "points", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform"],
  107. "radialGradient": ["class", "cx", "cy", "fx", "fy", "gradientTransform", "gradientUnits", "id", "r", "requiredFeatures", "spreadMethod", "systemLanguage", "xlink:href"],
  108. "rect": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "height", "id", "mask", "opacity", "requiredFeatures", "rx", "ry", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "width", "x", "y"],
  109. "stop": ["class", "id", "offset", "requiredFeatures", "stop-color", "stop-opacity", "style", "systemLanguage"],
  110. "svg": ["class", "clip-path", "clip-rule", "filter", "id", "height", "mask", "preserveAspectRatio", "requiredFeatures", "style", "systemLanguage", "viewBox", "width", "x", "xmlns", "xmlns:se", "xmlns:xlink", "y"],
  111. "switch": ["class", "id", "requiredFeatures", "systemLanguage"],
  112. "symbol": ["class", "fill", "fill-opacity", "fill-rule", "filter", "font-family", "font-size", "font-style", "font-weight", "id", "opacity", "preserveAspectRatio", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "transform", "viewBox"],
  113. "text": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "font-family", "font-size", "font-style", "font-weight", "id", "mask", "opacity", "requiredFeatures", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "text-anchor", "transform", "x", "xml:space", "y"],
  114. "textPath": ["class", "id", "method", "requiredFeatures", "spacing", "startOffset", "style", "systemLanguage", "transform", "xlink:href"],
  115. "title": [],
  116. "tspan": ["class", "clip-path", "clip-rule", "dx", "dy", "fill", "fill-opacity", "fill-rule", "filter", "font-family", "font-size", "font-style", "font-weight", "id", "mask", "opacity", "requiredFeatures", "rotate", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "systemLanguage", "text-anchor", "textLength", "transform", "x", "xml:space", "y"],
  117. "use": ["class", "clip-path", "clip-rule", "fill", "fill-opacity", "fill-rule", "filter", "height", "id", "mask", "stroke", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "style", "transform", "width", "x", "xlink:href", "y"],
  118. // MathML Elements
  119. "annotation": ["encoding"],
  120. "annotation-xml": ["encoding"],
  121. "maction": ["actiontype", "other", "selection"],
  122. "math": ["class", "id", "display", "xmlns"],
  123. "menclose": ["notation"],
  124. "merror": [],
  125. "mfrac": ["linethickness"],
  126. "mi": ["mathvariant"],
  127. "mmultiscripts": [],
  128. "mn": [],
  129. "mo": ["fence", "lspace", "maxsize", "minsize", "rspace", "stretchy"],
  130. "mover": [],
  131. "mpadded": ["lspace", "width"],
  132. "mphantom": [],
  133. "mprescripts": [],
  134. "mroot": [],
  135. "mrow": ["xlink:href", "xlink:type", "xmlns:xlink"],
  136. "mspace": ["depth", "height", "width"],
  137. "msqrt": [],
  138. "mstyle": ["displaystyle", "mathbackground", "mathcolor", "mathvariant", "scriptlevel"],
  139. "msub": [],
  140. "msubsup": [],
  141. "msup": [],
  142. "mtable": ["align", "columnalign", "columnlines", "columnspacing", "displaystyle", "equalcolumns", "equalrows", "frame", "rowalign", "rowlines", "rowspacing", "width"],
  143. "mtd": ["columnalign", "columnspan", "rowalign", "rowspan"],
  144. "mtext": [],
  145. "mtr": ["columnalign", "rowalign"],
  146. "munder": [],
  147. "munderover": [],
  148. "none": [],
  149. "semantics": []
  150. },
  151. // Interface strings, usually for title elements
  152. uiStrings = {
  153. "pathNodeTooltip": "Drag node to move it. Double-click node to change segment type",
  154. "pathCtrlPtTooltip": "Drag control point to adjust curve properties",
  155. "exportNoBlur": "Blurred elements will appear as un-blurred",
  156. "exportNoImage": "Image elements will not appear",
  157. "exportNoforeignObject": "foreignObject elements will not appear",
  158. "exportNoDashArray": "Strokes will appear filled",
  159. "exportNoText": "Text may not appear as expected"
  160. },
  161. // Default configuration options
  162. curConfig = {
  163. show_outside_canvas: true,
  164. dimensions: [640, 480]
  165. };
  166. // Update config with new one if given
  167. if(config) {
  168. $.extend(curConfig, config);
  169. }
  170. // Static class for various utility functions
  171. var Utils = this.Utils = function() {
  172. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  173. return {
  174. // Function: Utils.toXml
  175. // Converts characters in a string to XML-friendly entities.
  176. //
  177. // Example: "&" becomes "&amp;"
  178. //
  179. // Parameters:
  180. // str - The string to be converted
  181. //
  182. // Returns:
  183. // The converted string
  184. "toXml": function(str) {
  185. return $('<p/>').text(str).html();
  186. },
  187. // Function: Utils.fromXml
  188. // Converts XML entities in a string to single characters.
  189. // Example: "&amp;" becomes "&"
  190. //
  191. // Parameters:
  192. // str - The string to be converted
  193. //
  194. // Returns:
  195. // The converted string
  196. "fromXml": function(str) {
  197. return $('<p/>').html(str).text();
  198. },
  199. // This code was written by Tyler Akins and has been placed in the
  200. // public domain. It would be nice if you left this header intact.
  201. // Base64 code from Tyler Akins -- http://rumkin.com
  202. // schiller: Removed string concatenation in favour of Array.join() optimization,
  203. // also precalculate the size of the array needed.
  204. // Function: Utils.encode64
  205. // Converts a string to base64
  206. "encode64" : function(input) {
  207. // base64 strings are 4/3 larger than the original string
  208. // input = Utils.encodeUTF8(input); // convert non-ASCII characters
  209. input = Utils.convertToXMLReferences(input);
  210. if(window.btoa) return window.btoa(input); // Use native if available
  211. var output = new Array( Math.floor( (input.length + 2) / 3 ) * 4 );
  212. var chr1, chr2, chr3;
  213. var enc1, enc2, enc3, enc4;
  214. var i = 0, p = 0;
  215. do {
  216. chr1 = input.charCodeAt(i++);
  217. chr2 = input.charCodeAt(i++);
  218. chr3 = input.charCodeAt(i++);
  219. enc1 = chr1 >> 2;
  220. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  221. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  222. enc4 = chr3 & 63;
  223. if (isNaN(chr2)) {
  224. enc3 = enc4 = 64;
  225. } else if (isNaN(chr3)) {
  226. enc4 = 64;
  227. }
  228. output[p++] = _keyStr.charAt(enc1);
  229. output[p++] = _keyStr.charAt(enc2);
  230. output[p++] = _keyStr.charAt(enc3);
  231. output[p++] = _keyStr.charAt(enc4);
  232. } while (i < input.length);
  233. return output.join('');
  234. },
  235. // Function: Utils.decode64
  236. // Converts a string from base64
  237. "decode64" : function(input) {
  238. if(window.atob) return window.atob(input);
  239. var output = "";
  240. var chr1, chr2, chr3 = "";
  241. var enc1, enc2, enc3, enc4 = "";
  242. var i = 0;
  243. // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  244. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  245. do {
  246. enc1 = _keyStr.indexOf(input.charAt(i++));
  247. enc2 = _keyStr.indexOf(input.charAt(i++));
  248. enc3 = _keyStr.indexOf(input.charAt(i++));
  249. enc4 = _keyStr.indexOf(input.charAt(i++));
  250. chr1 = (enc1 << 2) | (enc2 >> 4);
  251. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  252. chr3 = ((enc3 & 3) << 6) | enc4;
  253. output = output + String.fromCharCode(chr1);
  254. if (enc3 != 64) {
  255. output = output + String.fromCharCode(chr2);
  256. }
  257. if (enc4 != 64) {
  258. output = output + String.fromCharCode(chr3);
  259. }
  260. chr1 = chr2 = chr3 = "";
  261. enc1 = enc2 = enc3 = enc4 = "";
  262. } while (i < input.length);
  263. return unescape(output);
  264. },
  265. // Currently not being used, so commented out for now
  266. // based on http://phpjs.org/functions/utf8_encode:577
  267. // codedread:does not seem to work with webkit-based browsers on OSX
  268. // "encodeUTF8": function(input) {
  269. // //return unescape(encodeURIComponent(input)); //may or may not work
  270. // var output = '';
  271. // for (var n = 0; n < input.length; n++){
  272. // var c = input.charCodeAt(n);
  273. // if (c < 128) {
  274. // output += input[n];
  275. // }
  276. // else if (c > 127) {
  277. // if (c < 2048){
  278. // output += String.fromCharCode((c >> 6) | 192);
  279. // }
  280. // else {
  281. // output += String.fromCharCode((c >> 12) | 224) + String.fromCharCode((c >> 6) & 63 | 128);
  282. // }
  283. // output += String.fromCharCode((c & 63) | 128);
  284. // }
  285. // }
  286. // return output;
  287. // },
  288. // Function: Utils.convertToXMLReferences
  289. // Converts a string to use XML references
  290. "convertToXMLReferences": function(input) {
  291. var output = '';
  292. for (var n = 0; n < input.length; n++){
  293. var c = input.charCodeAt(n);
  294. if (c < 128) {
  295. output += input[n];
  296. }
  297. else if(c > 127) {
  298. output += ("&#" + c + ";");
  299. }
  300. }
  301. return output;
  302. },
  303. // Function: rectsIntersect
  304. // Check if two rectangles (BBoxes objects) intersect each other
  305. //
  306. // Paramaters:
  307. // r1 - The first BBox-like object
  308. // r2 - The second BBox-like object
  309. //
  310. // Returns:
  311. // Boolean that's true if rectangles intersect
  312. "rectsIntersect": function(r1, r2) {
  313. return r2.x < (r1.x+r1.width) &&
  314. (r2.x+r2.width) > r1.x &&
  315. r2.y < (r1.y+r1.height) &&
  316. (r2.y+r2.height) > r1.y;
  317. },
  318. // Function: snapToAngle
  319. // Returns a 45 degree angle coordinate associated with the two given
  320. // coordinates
  321. //
  322. // Parameters:
  323. // x1 - First coordinate's x value
  324. // x2 - Second coordinate's x value
  325. // y1 - First coordinate's y value
  326. // y2 - Second coordinate's y value
  327. //
  328. // Returns:
  329. // Object with the following values:
  330. // x - The angle-snapped x value
  331. // y - The angle-snapped y value
  332. // snapangle - The angle at which to snap
  333. "snapToAngle": function(x1,y1,x2,y2) {
  334. var snap = Math.PI/4; // 45 degrees
  335. var dx = x2 - x1;
  336. var dy = y2 - y1;
  337. var angle = Math.atan2(dy,dx);
  338. var dist = Math.sqrt(dx * dx + dy * dy);
  339. var snapangle= Math.round(angle/snap)*snap;
  340. var x = x1 + dist*Math.cos(snapangle);
  341. var y = y1 + dist*Math.sin(snapangle);
  342. //console.log(x1,y1,x2,y2,x,y,angle)
  343. return {x:x, y:y, a:snapangle};
  344. },
  345. // Function: text2xml
  346. // Cross-browser compatible method of converting a string to an XML tree
  347. // found this function here: http://groups.google.com/group/jquery-dev/browse_thread/thread/c6d11387c580a77f
  348. "text2xml": function(sXML) {
  349. var out;
  350. try{
  351. var dXML = ($.browser.msie)?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
  352. dXML.async = false;
  353. } catch(e){
  354. throw new Error("XML Parser could not be instantiated");
  355. };
  356. try{
  357. if($.browser.msie) out = (dXML.loadXML(sXML))?dXML:false;
  358. else out = dXML.parseFromString(sXML, "text/xml");
  359. }
  360. catch(e){ throw new Error("Error parsing XML string"); };
  361. return out;
  362. }
  363. }
  364. }();
  365. // TODO: declare the variables and set them as null, then move this setup stuff to
  366. // an initialization function - probably just use clear()
  367. var canvas = this,
  368. // Namespace constants
  369. svgns = "http://www.w3.org/2000/svg",
  370. xlinkns = "http://www.w3.org/1999/xlink",
  371. xmlns = "http://www.w3.org/XML/1998/namespace",
  372. xmlnsns = "http://www.w3.org/2000/xmlns/", // see http://www.w3.org/TR/REC-xml-names/#xmlReserved
  373. se_ns = "http://svg-edit.googlecode.com",
  374. htmlns = "http://www.w3.org/1999/xhtml",
  375. mathns = "http://www.w3.org/1998/Math/MathML",
  376. // Map of units, those set to 0 are updated later based on calculations
  377. unit_types = {'em':0,'ex':0,'px':1,'cm':35.43307,'mm':3.543307,'in':90,'pt':1.25,'pc':15,'%':0},
  378. //nonce to uniquify id's
  379. nonce = Math.floor(Math.random()*100001),
  380. // Boolean to indicate whether or not IDs given to elements should be random
  381. randomize_ids = false,
  382. // "document" element associated with the container (same as window.document using default svg-editor.js)
  383. svgdoc = container.ownerDocument,
  384. // Array with width/height of canvas
  385. dimensions = curConfig.dimensions,
  386. // Create Root SVG element. This is a container for the document being edited, not the document itself.
  387. svgroot = svgdoc.importNode(Utils.text2xml('<svg id="svgroot" xmlns="' + svgns + '" xlinkns="' + xlinkns + '" ' +
  388. 'width="' + dimensions[0] + '" height="' + dimensions[1] + '" x="' + dimensions[0] + '" y="' + dimensions[1] + '" overflow="visible">' +
  389. '<defs>' +
  390. '<filter id="canvashadow" filterUnits="objectBoundingBox">' +
  391. '<feGaussianBlur in="SourceAlpha" stdDeviation="4" result="blur"/>'+
  392. '<feOffset in="blur" dx="5" dy="5" result="offsetBlur"/>'+
  393. '<feMerge>'+
  394. '<feMergeNode in="offsetBlur"/>'+
  395. '<feMergeNode in="SourceGraphic"/>'+
  396. '</feMerge>'+
  397. '</filter>'+
  398. '</defs>'+
  399. '</svg>').documentElement, true);
  400. container.appendChild(svgroot);
  401. // The actual element that represents the final output SVG element
  402. var svgcontent = svgdoc.createElementNS(svgns, "svg");
  403. $(svgcontent).attr({
  404. id: 'svgcontent',
  405. width: dimensions[0],
  406. height: dimensions[1],
  407. x: dimensions[0],
  408. y: dimensions[1],
  409. overflow: curConfig.show_outside_canvas?'visible':'hidden',
  410. xmlns: svgns,
  411. "xmlns:se": se_ns,
  412. "xmlns:xlink": xlinkns
  413. }).appendTo(svgroot);
  414. // Set nonce if randomize_ids = true
  415. if (randomize_ids) svgcontent.setAttributeNS(se_ns, 'se:nonce', nonce);
  416. // map namespace URIs to prefixes
  417. var nsMap = {};
  418. nsMap[xlinkns] = 'xlink';
  419. nsMap[xmlns] = 'xml';
  420. nsMap[xmlnsns] = 'xmlns';
  421. nsMap[se_ns] = 'se';
  422. nsMap[htmlns] = 'xhtml';
  423. nsMap[mathns] = 'mathml';
  424. // map prefixes to namespace URIs
  425. var nsRevMap = {};
  426. $.each(nsMap, function(key,value){
  427. nsRevMap[value] = key;
  428. });
  429. // Produce a Namespace-aware version of svgWhitelist
  430. var svgWhiteListNS = {};
  431. $.each(svgWhiteList, function(elt,atts){
  432. var attNS = {};
  433. $.each(atts, function(i, att){
  434. if (att.indexOf(':') != -1) {
  435. var v = att.split(':');
  436. attNS[v[1]] = nsRevMap[v[0]];
  437. } else {
  438. attNS[att] = att == 'xmlns' ? xmlnsns : null;
  439. }
  440. });
  441. svgWhiteListNS[elt] = attNS;
  442. });
  443. // Animation element to change the opacity of any newly created element
  444. var opac_ani = document.createElementNS(svgns, 'animate');
  445. $(opac_ani).attr({
  446. attributeName: 'opacity',
  447. begin: 'indefinite',
  448. dur: 1,
  449. fill: 'freeze'
  450. }).appendTo(svgroot);
  451. // Group: Unit conversion functions
  452. // Set the scope for these functions
  453. var convertToNum, convertToUnit, setUnitAttr;
  454. (function() {
  455. var w_attrs = ['x', 'x1', 'cx', 'rx', 'width'];
  456. var h_attrs = ['y', 'y1', 'cy', 'ry', 'height'];
  457. var unit_attrs = $.merge(['r','radius'], w_attrs);
  458. $.merge(unit_attrs, h_attrs);
  459. // Function: convertToNum
  460. // Converts given values to numbers. Attributes must be supplied in
  461. // case a percentage is given
  462. //
  463. // Parameters:
  464. // attr - String with the name of the attribute associated with the value
  465. // val - String with the attribute value to convert
  466. convertToNum = function(attr, val) {
  467. // Return a number if that's what it already is
  468. if(!isNaN(val)) return val-0;
  469. if(val.substr(-1) === '%') {
  470. // Deal with percentage, depends on attribute
  471. var num = val.substr(0, val.length-1)/100;
  472. var res = getResolution();
  473. if($.inArray(attr, w_attrs) !== -1) {
  474. return num * res.w;
  475. } else if($.inArray(attr, h_attrs) !== -1) {
  476. return num * res.h;
  477. } else {
  478. return num * Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);
  479. }
  480. } else {
  481. var unit = val.substr(-2);
  482. var num = val.substr(0, val.length-2);
  483. // Note that this multiplication turns the string into a number
  484. return num * unit_types[unit];
  485. }
  486. };
  487. // Function: setUnitAttr
  488. // Sets an element's attribute based on the unit in its current value.
  489. //
  490. // Parameters:
  491. // elem - DOM element to be changed
  492. // attr - String with the name of the attribute associated with the value
  493. // val - String with the attribute value to convert
  494. setUnitAttr = function(elem, attr, val) {
  495. if(!isNaN(val)) {
  496. // New value is a number, so check currently used unit
  497. var old_val = elem.getAttribute(attr);
  498. if(old_val !== null && isNaN(old_val)) {
  499. // Old value was a number, so get unit, then convert
  500. var unit;
  501. if(old_val.substr(-1) === '%') {
  502. var res = getResolution();
  503. unit = '%';
  504. val *= 100;
  505. if($.inArray(attr, w_attrs) !== -1) {
  506. val = val / res.w;
  507. } else if($.inArray(attr, h_attrs) !== -1) {
  508. val = val / res.h;
  509. } else {
  510. return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);
  511. }
  512. } else {
  513. unit = old_val.substr(-2);
  514. val = val / unit_types[unit];
  515. }
  516. val += unit;
  517. }
  518. }
  519. elem.setAttribute(attr, val);
  520. }
  521. // Function: isValidUnit
  522. // Check if an attribute's value is in a valid format
  523. //
  524. // Parameters:
  525. // attr - String with the name of the attribute associated with the value
  526. // val - String with the attribute value to check
  527. canvas.isValidUnit = function(attr, val) {
  528. var valid = false;
  529. if($.inArray(attr, unit_attrs) != -1) {
  530. // True if it's just a number
  531. if(!isNaN(val)) {
  532. valid = true;
  533. } else {
  534. // Not a number, check if it has a valid unit
  535. val = val.toLowerCase();
  536. $.each(unit_types, function(unit) {
  537. if(valid) return;
  538. var re = new RegExp('^-?[\\d\\.]+' + unit + '$');
  539. if(re.test(val)) valid = true;
  540. });
  541. }
  542. } else if (attr == "id") {
  543. // if we're trying to change the id, make sure it's not already present in the doc
  544. // and the id value is valid.
  545. var result = false;
  546. // because getElem() can throw an exception in the case of an invalid id
  547. // (according to http://www.w3.org/TR/xml-id/ IDs must be a NCName)
  548. // we wrap it in an exception and only return true if the ID was valid and
  549. // not already present
  550. try {
  551. var elem = getElem(val);
  552. result = (elem == null);
  553. } catch(e) {}
  554. return result;
  555. } else valid = true;
  556. return valid;
  557. }
  558. })();
  559. // Group: Undo/Redo history management
  560. this.undoCmd = {};
  561. // Function: ChangeElementCommand
  562. // History command to make a change to an element.
  563. // Usually an attribute change, but can also be textcontent.
  564. //
  565. // Parameters:
  566. // elem - The DOM element that was changed
  567. // attrs - An object with the attributes to be changed and the values they had *before* the change
  568. // text - An optional string visible to user related to this change
  569. var ChangeElementCommand = this.undoCmd.changeElement = function(elem, attrs, text) {
  570. this.elem = elem;
  571. this.text = text ? ("Change " + elem.tagName + " " + text) : ("Change " + elem.tagName);
  572. this.newValues = {};
  573. this.oldValues = attrs;
  574. for (var attr in attrs) {
  575. if (attr == "#text") this.newValues[attr] = elem.textContent;
  576. else if (attr == "#href") this.newValues[attr] = elem.getAttributeNS(xlinkns, "href");
  577. else this.newValues[attr] = elem.getAttribute(attr);
  578. }
  579. // Function: ChangeElementCommand.apply
  580. // Performs the stored change action
  581. this.apply = function() {
  582. var bChangedTransform = false;
  583. for(var attr in this.newValues ) {
  584. if (this.newValues[attr]) {
  585. if (attr == "#text") this.elem.textContent = this.newValues[attr];
  586. else if (attr == "#href") this.elem.setAttributeNS(xlinkns, "xlink:href", this.newValues[attr])
  587. else this.elem.setAttribute(attr, this.newValues[attr]);
  588. }
  589. else {
  590. if (attr == "#text") this.elem.textContent = "";
  591. else {
  592. this.elem.setAttribute(attr, "");
  593. this.elem.removeAttribute(attr);
  594. }
  595. }
  596. if (attr == "transform") { bChangedTransform = true; }
  597. else if (attr == "stdDeviation") { canvas.setBlurOffsets(this.elem.parentNode, this.newValues[attr]); }
  598. }
  599. // relocate rotational transform, if necessary
  600. if(!bChangedTransform) {
  601. var angle = getRotationAngle(elem);
  602. if (angle) {
  603. var bbox = elem.getBBox();
  604. var cx = bbox.x + bbox.width/2,
  605. cy = bbox.y + bbox.height/2;
  606. var rotate = ["rotate(", angle, " ", cx, ",", cy, ")"].join('');
  607. if (rotate != elem.getAttribute("transform")) {
  608. elem.setAttribute("transform", rotate);
  609. }
  610. }
  611. }
  612. // if we are changing layer names, re-identify all layers
  613. if (this.elem.tagName == "title" && this.elem.parentNode.parentNode == svgcontent) {
  614. identifyLayers();
  615. }
  616. return true;
  617. };
  618. // Function: ChangeElementCommand.unapply
  619. // Reverses the stored change action
  620. this.unapply = function() {
  621. var bChangedTransform = false;
  622. for(var attr in this.oldValues ) {
  623. if (this.oldValues[attr]) {
  624. if (attr == "#text") this.elem.textContent = this.oldValues[attr];
  625. else if (attr == "#href") this.elem.setAttributeNS(xlinkns, "xlink:href", this.oldValues[attr]);
  626. else this.elem.setAttribute(attr, this.oldValues[attr]);
  627. if (attr == "stdDeviation") canvas.setBlurOffsets(this.elem.parentNode, this.oldValues[attr]);
  628. }
  629. else {
  630. if (attr == "#text") this.elem.textContent = "";
  631. else this.elem.removeAttribute(attr);
  632. }
  633. if (attr == "transform") { bChangedTransform = true; }
  634. }
  635. // relocate rotational transform, if necessary
  636. if(!bChangedTransform) {
  637. var angle = getRotationAngle(elem);
  638. if (angle) {
  639. var bbox = elem.getBBox();
  640. var cx = bbox.x + bbox.width/2,
  641. cy = bbox.y + bbox.height/2;
  642. var rotate = ["rotate(", angle, " ", cx, ",", cy, ")"].join('');
  643. if (rotate != elem.getAttribute("transform")) {
  644. elem.setAttribute("transform", rotate);
  645. }
  646. }
  647. }
  648. // if we are changing layer names, re-identify all layers
  649. if (this.elem.tagName == "title" && this.elem.parentNode.parentNode == svgcontent) {
  650. identifyLayers();
  651. }
  652. // Remove transformlist to prevent confusion that causes bugs like 575.
  653. if (svgTransformLists[this.elem.id]) {
  654. delete svgTransformLists[this.elem.id];
  655. }
  656. return true;
  657. };
  658. // Function: ChangeElementCommand.elements
  659. // Returns array with element associated with this command
  660. this.elements = function() { return [this.elem]; }
  661. }
  662. // Function: InsertElementCommand
  663. // History command for an element that was added to the DOM
  664. //
  665. // Parameters:
  666. // elem - The newly added DOM element
  667. // text - An optional string visible to user related to this change
  668. var InsertElementCommand = this.undoCmd.insertElement = function(elem, text) {
  669. this.elem = elem;
  670. this.text = text || ("Create " + elem.tagName);
  671. this.parent = elem.parentNode;
  672. // Function: InsertElementCommand.apply
  673. // Re-Inserts the new element
  674. this.apply = function() {
  675. this.elem = this.parent.insertBefore(this.elem, this.elem.nextSibling);
  676. if (this.parent == svgcontent) {
  677. identifyLayers();
  678. }
  679. };
  680. // Function: InsertElementCommand.unapply
  681. // Removes the element
  682. this.unapply = function() {
  683. this.parent = this.elem.parentNode;
  684. this.elem = this.elem.parentNode.removeChild(this.elem);
  685. if (this.parent == svgcontent) {
  686. identifyLayers();
  687. }
  688. };
  689. // Function: InsertElementCommand.elements
  690. // Returns array with element associated with this command
  691. this.elements = function() { return [this.elem]; };
  692. }
  693. // Function: RemoveElementCommand
  694. // History command for an element removed from the DOM
  695. //
  696. // Parameters:
  697. // elem - The removed DOM element
  698. // parent - The DOM element's parent
  699. // text - An optional string visible to user related to this change
  700. var RemoveElementCommand = this.undoCmd.removeElement = function(elem, parent, text) {
  701. this.elem = elem;
  702. this.text = text || ("Delete " + elem.tagName);
  703. this.parent = parent;
  704. // Function: RemoveElementCommand.apply
  705. // Re-removes the new element
  706. this.apply = function() {
  707. if (svgTransformLists[this.elem.id]) {
  708. delete svgTransformLists[this.elem.id];
  709. }
  710. this.parent = this.elem.parentNode;
  711. this.elem = this.parent.removeChild(this.elem);
  712. if (this.parent == svgcontent) {
  713. identifyLayers();
  714. }
  715. };
  716. // Function: RemoveElementCommand.unapply
  717. // Re-adds the new element
  718. this.unapply = function() {
  719. if (svgTransformLists[this.elem.id]) {
  720. delete svgTransformLists[this.elem.id];
  721. }
  722. this.elem = this.parent.insertBefore(this.elem, this.elem.nextSibling);
  723. if (this.parent == svgcontent) {
  724. identifyLayers();
  725. }
  726. };
  727. // Function: RemoveElementCommand.elements
  728. // Returns array with element associated with this command
  729. this.elements = function() { return [this.elem]; };
  730. // special hack for webkit: remove this element's entry in the svgTransformLists map
  731. if (svgTransformLists[elem.id]) {
  732. delete svgTransformLists[elem.id];
  733. }
  734. }
  735. // Function: MoveElementCommand
  736. // History command for an element that had its DOM position changed
  737. //
  738. // Parameters:
  739. // elem - The DOM element that was moved
  740. // oldNextSibling - The element's next sibling before it was moved
  741. // oldParent - The element's parent before it was moved
  742. // text - An optional string visible to user related to this change
  743. var MoveElementCommand = this.undoCmd.moveElement = function(elem, oldNextSibling, oldParent, text) {
  744. this.elem = elem;
  745. this.text = text ? ("Move " + elem.tagName + " to " + text) : ("Move " + elem.tagName);
  746. this.oldNextSibling = oldNextSibling;
  747. this.oldParent = oldParent;
  748. this.newNextSibling = elem.nextSibling;
  749. this.newParent = elem.parentNode;
  750. // Function: MoveElementCommand.unapply
  751. // Re-positions the element
  752. this.apply = function() {
  753. this.elem = this.newParent.insertBefore(this.elem, this.newNextSibling);
  754. if (this.newParent == svgcontent) {
  755. identifyLayers();
  756. }
  757. };
  758. // Function: MoveElementCommand.unapply
  759. // Positions the element back to its original location
  760. this.unapply = function() {
  761. this.elem = this.oldParent.insertBefore(this.elem, this.oldNextSibling);
  762. if (this.oldParent == svgcontent) {
  763. identifyLayers();
  764. }
  765. };
  766. // Function: MoveElementCommand.elements
  767. // Returns array with element associated with this command
  768. this.elements = function() { return [this.elem]; };
  769. }
  770. // TODO: create a 'typing' command object that tracks changes in text
  771. // if a new Typing command is created and the top command on the stack is also a Typing
  772. // and they both affect the same element, then collapse the two commands into one
  773. // Function: BatchCommand
  774. // History command that can contain/execute multiple other commands
  775. //
  776. // Parameters:
  777. // text - An optional string visible to user related to this change
  778. var BatchCommand = this.undoCmd.batch = function(text) {
  779. this.text = text || "Batch Command";
  780. this.stack = [];
  781. // Function: BatchCommand.apply
  782. // Runs "apply" on all subcommands
  783. this.apply = function() {
  784. var len = this.stack.length;
  785. for (var i = 0; i < len; ++i) {
  786. this.stack[i].apply();
  787. }
  788. };
  789. // Function: BatchCommand.unapply
  790. // Runs "unapply" on all subcommands
  791. this.unapply = function() {
  792. for (var i = this.stack.length-1; i >= 0; i--) {
  793. this.stack[i].unapply();
  794. }
  795. };
  796. // Function: BatchCommand.elements
  797. // Iterate through all our subcommands and returns all the elements we are changing
  798. this.elements = function() {
  799. var elems = [];
  800. var cmd = this.stack.length;
  801. while (cmd--) {
  802. var thisElems = this.stack[cmd].elements();
  803. var elem = thisElems.length;
  804. while (elem--) {
  805. if (elems.indexOf(thisElems[elem]) == -1) elems.push(thisElems[elem]);
  806. }
  807. }
  808. return elems;
  809. };
  810. // Function: BatchCommand.addSubCommand
  811. // Adds a given command to the history stack
  812. //
  813. // Parameters:
  814. // cmd - The undo command object to add
  815. this.addSubCommand = function(cmd) { this.stack.push(cmd); };
  816. // Function: BatchCommand.isEmpty
  817. // Returns a boolean indicating whether or not the batch command is empty
  818. this.isEmpty = function() { return this.stack.length == 0; };
  819. }
  820. // Set scope for these undo functions
  821. var resetUndoStack, addCommandToHistory;
  822. // Undo/redo stack related functions
  823. (function(c) {
  824. var undoStackPointer = 0,
  825. undoStack = [];
  826. // Function: resetUndoStack
  827. // Resets the undo stack, effectively clearing the undo/redo history
  828. resetUndoStack = function() {
  829. undoStack = [];
  830. undoStackPointer = 0;
  831. };
  832. c.undoMgr = {
  833. // Function: undoMgr.getUndoStackSize
  834. // Returns:
  835. // Integer with the current size of the undo history stack
  836. getUndoStackSize: function() { return undoStackPointer; },
  837. // Function: undoMgr.getRedoStackSize
  838. // Returns:
  839. // Integer with the current size of the redo history stack
  840. getRedoStackSize: function() { return undoStack.length - undoStackPointer; },
  841. // Function: undoMgr.getNextUndoCommandText
  842. // Returns:
  843. // String associated with the next undo command
  844. getNextUndoCommandText: function() {
  845. if (undoStackPointer > 0)
  846. return undoStack[undoStackPointer-1].text;
  847. return "";
  848. },
  849. // Function: undoMgr.getNextRedoCommandText
  850. // Returns:
  851. // String associated with the next redo command
  852. getNextRedoCommandText: function() {
  853. if (undoStackPointer < undoStack.length)
  854. return undoStack[undoStackPointer].text;
  855. return "";
  856. },
  857. // Function: undoMgr.undo
  858. // Performs an undo step
  859. undo: function() {
  860. if (undoStackPointer > 0) {
  861. c.clearSelection();
  862. var cmd = undoStack[--undoStackPointer];
  863. cmd.unapply();
  864. pathActions.clear();
  865. call("changed", cmd.elements());
  866. }
  867. },
  868. // Function: undoMgr.redo
  869. // Performs a redo step
  870. redo: function() {
  871. if (undoStackPointer < undoStack.length && undoStack.length > 0) {
  872. c.clearSelection();
  873. var cmd = undoStack[undoStackPointer++];
  874. cmd.apply();
  875. pathActions.clear();
  876. call("changed", cmd.elements());
  877. }
  878. }
  879. };
  880. // Function: addCommandToHistory
  881. // Adds a command object to the undo history stack
  882. //
  883. // Parameters:
  884. // cmd - The command object to add
  885. addCommandToHistory = c.undoCmd.add = function(cmd) {
  886. // FIXME: we MUST compress consecutive text changes to the same element
  887. // (right now each keystroke is saved as a separate command that includes the
  888. // entire text contents of the text element)
  889. // TODO: consider limiting the history that we store here (need to do some slicing)
  890. // if our stack pointer is not at the end, then we have to remove
  891. // all commands after the pointer and insert the new command
  892. if (undoStackPointer < undoStack.length && undoStack.length > 0) {
  893. undoStack = undoStack.splice(0, undoStackPointer);
  894. }
  895. undoStack.push(cmd);
  896. undoStackPointer = undoStack.length;
  897. };
  898. }(canvas));
  899. (function(c) {
  900. // New functions for refactoring of Undo/Redo
  901. // this is the stack that stores the original values, the elements and
  902. // the attribute name for begin/finish
  903. var undoChangeStackPointer = -1;
  904. var undoableChangeStack = [];
  905. // Function: beginUndoableChange
  906. // This function tells the canvas to remember the old values of the
  907. // attrName attribute for each element sent in. The elements and values
  908. // are stored on a stack, so the next call to finishUndoableChange() will
  909. // pop the elements and old values off the stack, gets the current values
  910. // from the DOM and uses all of these to construct the undo-able command.
  911. //
  912. // Parameters:
  913. // attrName - The name of the attribute being changed
  914. // elems - Array of DOM elements being changed
  915. c.beginUndoableChange = function(attrName, elems) {
  916. var p = ++undoChangeStackPointer;
  917. var i = elems.length;
  918. var oldValues = new Array(i), elements = new Array(i);
  919. while (i--) {
  920. var elem = elems[i];
  921. if (elem == null) continue;
  922. elements[i] = elem;
  923. oldValues[i] = elem.getAttribute(attrName);
  924. }
  925. undoableChangeStack[p] = {'attrName': attrName,
  926. 'oldValues': oldValues,
  927. 'elements': elements};
  928. };
  929. // Function: finishUndoableChange
  930. // This function returns a BatchCommand object which summarizes the
  931. // change since beginUndoableChange was called. The command can then
  932. // be added to the command history
  933. //
  934. // Returns:
  935. // Batch command object with resulting changes
  936. c.finishUndoableChange = function() {
  937. var p = undoChangeStackPointer--;
  938. var changeset = undoableChangeStack[p];
  939. var i = changeset['elements'].length;
  940. var attrName = changeset['attrName'];
  941. var batchCmd = new BatchCommand("Change " + attrName);
  942. while (i--) {
  943. var elem = changeset['elements'][i];
  944. if (elem == null) continue;
  945. var changes = {};
  946. changes[attrName] = changeset['oldValues'][i];
  947. if (changes[attrName] != elem.getAttribute(attrName)) {
  948. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes, attrName));
  949. }
  950. }
  951. undoableChangeStack[p] = null;
  952. return batchCmd;
  953. };
  954. }(canvas));
  955. // Put SelectorManager in this scope
  956. var SelectorManager;
  957. (function() {
  958. // Interface: Selector
  959. // Private class for DOM element selection boxes
  960. //
  961. // Parameters:
  962. // id - integer to internally indentify the selector
  963. // elem - DOM element associated with this selector
  964. function Selector(id, elem) {
  965. // this is the selector's unique number
  966. this.id = id;
  967. // this holds a reference to the element for which this selector is being used
  968. this.selectedElement = elem;
  969. // this is a flag used internally to track whether the selector is being used or not
  970. this.locked = true;
  971. // Function: Selector.reset
  972. // Used to reset the id and element that the selector is attached to
  973. //
  974. // Parameters:
  975. // e - DOM element associated with this selector
  976. this.reset = function(e) {
  977. this.locked = true;
  978. this.selectedElement = e;
  979. this.resize();
  980. this.selectorGroup.setAttribute("display", "inline");
  981. };
  982. // this holds a reference to the <g> element that holds all visual elements of the selector
  983. this.selectorGroup = addSvgElementFromJson({ "element": "g",
  984. "attr": {"id": ("selectorGroup"+this.id)}
  985. });
  986. // this holds a reference to the path rect
  987. this.selectorRect = this.selectorGroup.appendChild( addSvgElementFromJson({
  988. "element": "path",
  989. "attr": {
  990. "id": ("selectedBox"+this.id),
  991. "fill": "none",
  992. "stroke": "#22C",
  993. "stroke-width": "1",
  994. "stroke-dasharray": "5,5",
  995. // need to specify this so that the rect is not selectable
  996. "style": "pointer-events:none"
  997. }
  998. }) );
  999. // this holds a reference to the grip elements for this selector
  1000. this.selectorGrips = { "nw":null,
  1001. "n":null,
  1002. "ne":null,
  1003. "e":null,
  1004. "se":null,
  1005. "s":null,
  1006. "sw":null,
  1007. "w":null
  1008. };
  1009. this.rotateGripConnector = this.selectorGroup.appendChild( addSvgElementFromJson({
  1010. "element": "line",
  1011. "attr": {
  1012. "id": ("selectorGrip_rotateconnector_" + this.id),
  1013. "stroke": "#22C",
  1014. "stroke-width": "1"
  1015. }
  1016. }) );
  1017. this.rotateGrip = this.selectorGroup.appendChild( addSvgElementFromJson({
  1018. "element": "circle",
  1019. "attr": {
  1020. "id": ("selectorGrip_rotate_" + this.id),
  1021. "fill": "lime",
  1022. "r": 4,
  1023. "stroke": "#22C",
  1024. "stroke-width": 2,
  1025. "style": "cursor:url(" + curConfig.imgPath + "rotate.png) 12 12, auto;"
  1026. }
  1027. }) );
  1028. // add the corner grips
  1029. for (var dir in this.selectorGrips) {
  1030. this.selectorGrips[dir] = this.selectorGroup.appendChild(
  1031. addSvgElementFromJson({
  1032. "element": "circle",
  1033. "attr": {
  1034. "id": ("selectorGrip_resize_" + dir + "_" + this.id),
  1035. "fill": "#22C",
  1036. "r": 4,
  1037. "style": ("cursor:" + dir + "-resize"),
  1038. // This expands the mouse-able area of the grips making them
  1039. // easier to grab with the mouse.
  1040. // This works in Opera and WebKit, but does not work in Firefox
  1041. // see https://bugzilla.mozilla.org/show_bug.cgi?id=500174
  1042. "stroke-width": 2,
  1043. "pointer-events":"all",
  1044. "display":"none"
  1045. }
  1046. }) );
  1047. }
  1048. // Function: Selector.showGrips
  1049. // Show the resize grips of this selector
  1050. //
  1051. // Parameters:
  1052. // show - boolean indicating whether grips should be shown or not
  1053. this.showGrips = function(show) {
  1054. // TODO: use suspendRedraw() here
  1055. var bShow = show ? "inline" : "none";
  1056. this.rotateGrip.setAttribute("display", bShow);
  1057. this.rotateGripConnector.setAttribute("display", bShow);
  1058. var elem = this.selectedElement;
  1059. for (var dir in this.selectorGrips) {
  1060. this.selectorGrips[dir].setAttribute("display", bShow);
  1061. }
  1062. if(elem) this.updateGripCursors(getRotationAngle(elem));
  1063. };
  1064. // Function: Selector.updateGripCursors
  1065. // Updates cursors for corner grips on rotation so arrows point the right way
  1066. //
  1067. // Parameters:
  1068. // angle - Float indicating current rotation angle in degrees
  1069. this.updateGripCursors = function(angle) {
  1070. var dir_arr = [];
  1071. var steps = Math.round(angle / 45);
  1072. if(steps < 0) steps += 8;
  1073. for (var dir in this.selectorGrips) {
  1074. dir_arr.push(dir);
  1075. }
  1076. while(steps > 0) {
  1077. dir_arr.push(dir_arr.shift());
  1078. steps--;
  1079. }
  1080. var i = 0;
  1081. for (var dir in this.selectorGrips) {
  1082. this.selectorGrips[dir].setAttribute('style', ("cursor:" + dir_arr[i] + "-resize"));
  1083. i++;
  1084. };
  1085. };
  1086. // Function: Selector.resize
  1087. // Updates the selector to match the element's size
  1088. this.resize = function() {
  1089. var selectedBox = this.selectorRect,
  1090. selectedGrips = this.selectorGrips,
  1091. selected = this.selectedElement,
  1092. sw = selected.getAttribute("stroke-width");
  1093. var offset = 1/current_zoom;
  1094. if (selected.getAttribute("stroke") != "none" && !isNaN(sw)) {
  1095. offset += (sw/2);
  1096. }
  1097. if (selected.tagName == "text") {
  1098. offset += 2/current_zoom;
  1099. }
  1100. var bbox = getBBox(selected);
  1101. if(selected.tagName == 'g') {
  1102. // The bbox for a group does not include stroke vals, so we
  1103. // get the bbox based on its children.
  1104. var stroked_bbox = getStrokedBBox(selected.childNodes);
  1105. $.each(bbox, function(key, val) {
  1106. bbox[key] = stroked_bbox[key];
  1107. });
  1108. }
  1109. // loop and transform our bounding box until we reach our first rotation
  1110. var m = getMatrix(selected);
  1111. // This should probably be handled somewhere else, but for now
  1112. // it keeps the selection box correctly positioned when zoomed
  1113. m.e *= current_zoom;
  1114. m.f *= current_zoom;
  1115. // apply the transforms
  1116. var l=bbox.x-offset, t=bbox.y-offset, w=bbox.width+(offset*2), h=bbox.height+(offset*2),
  1117. bbox = {x:l, y:t, width:w, height:h};
  1118. // we need to handle temporary transforms too
  1119. // if skewed, get its transformed box, then find its axis-aligned bbox
  1120. //*
  1121. var nbox = transformBox(l*current_zoom, t*current_zoom, w*current_zoom, h*current_zoom, m),
  1122. nbax = nbox.aabox.x,
  1123. nbay = nbox.aabox.y,
  1124. nbaw = nbox.aabox.width,
  1125. nbah = nbox.aabox.height;
  1126. // now if the shape is rotated, un-rotate it
  1127. var cx = nbax + nbaw/2,
  1128. cy = nbay + nbah/2;
  1129. var angle = getRotationAngle(selected);
  1130. if (angle) {
  1131. var rot = svgroot.createSVGTransform();
  1132. rot.setRotate(-angle,cx,cy);
  1133. var rotm = rot.matrix;
  1134. nbox.tl = transformPoint(nbox.tl.x,nbox.tl.y,rotm);
  1135. nbox.tr = transformPoint(nbox.tr.x,nbox.tr.y,rotm);
  1136. nbox.bl = transformPoint(nbox.bl.x,nbox.bl.y,rotm);
  1137. nbox.br = transformPoint(nbox.br.x,nbox.br.y,rotm);
  1138. // calculate the axis-aligned bbox
  1139. var minx = nbox.tl.x,
  1140. miny = nbox.tl.y,
  1141. maxx = nbox.tl.x,
  1142. maxy = nbox.tl.y;
  1143. minx = Math.min(minx, Math.min(nbox.tr.x, Math.min(nbox.bl.x, nbox.br.x) ) );
  1144. miny = Math.min(miny, Math.min(nbox.tr.y, Math.min(nbox.bl.y, nbox.br.y) ) );
  1145. maxx = Math.max(maxx, Math.max(nbox.tr.x, Math.max(nbox.bl.x, nbox.br.x) ) );
  1146. maxy = Math.max(maxy, Math.max(nbox.tr.y, Math.max(nbox.bl.y, nbox.br.y) ) );
  1147. nbax = minx;
  1148. nbay = miny;
  1149. nbaw = (maxx-minx);
  1150. nbah = (maxy-miny);
  1151. }
  1152. var sr_handle = svgroot.suspendRedraw(100);
  1153. var dstr = "M" + nbax + "," + nbay
  1154. + " L" + (nbax+nbaw) + "," + nbay
  1155. + " " + (nbax+nbaw) + "," + (nbay+nbah)
  1156. + " " + nbax + "," + (nbay+nbah) + "z";
  1157. assignAttributes(selectedBox, {'d': dstr});
  1158. var gripCoords = {
  1159. nw: [nbax, nbay],
  1160. ne: [nbax+nbaw, nbay],
  1161. sw: [nbax, nbay+nbah],
  1162. se: [nbax+nbaw, nbay+nbah],
  1163. n: [nbax + (nbaw)/2, nbay],
  1164. w: [nbax, nbay + (nbah)/2],
  1165. e: [nbax + nbaw, nbay + (nbah)/2],
  1166. s: [nbax + (nbaw)/2, nbay + nbah]
  1167. };
  1168. if(selected == selectedElements[0]) {
  1169. for(var dir in gripCoords) {
  1170. var coords = gripCoords[dir];
  1171. assignAttributes(selectedGrips[dir], {
  1172. cx: coords[0], cy: coords[1]
  1173. });
  1174. };
  1175. }
  1176. if (angle) {
  1177. this.selectorGroup.setAttribute("transform", "rotate(" + [angle,cx,cy].join(",") + ")");
  1178. }
  1179. else {
  1180. this.selectorGroup.setAttribute("transform", "");
  1181. }
  1182. // we want to go 20 pixels in the negative transformed y direction, ignoring scale
  1183. assignAttributes(this.rotateGripConnector, { x1: nbax + (nbaw)/2,
  1184. y1: nbay,
  1185. x2: nbax + (nbaw)/2,
  1186. y2: nbay- 20});
  1187. assignAttributes(this.rotateGrip, { cx: nbax + (nbaw)/2,
  1188. cy: nbay - 20 });
  1189. svgroot.unsuspendRedraw(sr_handle);
  1190. };
  1191. // now initialize the selector
  1192. this.reset(elem);
  1193. };
  1194. // Interface: SelectorManager
  1195. // Public class to manage all selector objects (selection boxes)
  1196. SelectorManager = function() {
  1197. // this will hold the <g> element that contains all selector rects/grips
  1198. this.selectorParentGroup = null;
  1199. // this is a special rect that is used for multi-select
  1200. this.rubberBandBox = null;
  1201. // this will hold objects of type Selector (see above)
  1202. this.selectors = [];
  1203. // this holds a map of SVG elements to their Selector object
  1204. this.selectorMap = {};
  1205. // local reference to this object
  1206. var mgr = this;
  1207. // Function: SelectorManager.initGroup
  1208. // Resets the parent selector group element
  1209. this.initGroup = function() {
  1210. // remove old selector parent group if it existed
  1211. if (mgr.selectorParentGroup && mgr.selectorParentGroup.parentNode) {
  1212. mgr.selectorParentGroup.parentNode.removeChild(mgr.selectorParentGroup);
  1213. }
  1214. // create parent selector group and add it to svgroot
  1215. mgr.selectorParentGroup = svgdoc.createElementNS(svgns, "g");
  1216. mgr.selectorParentGroup.setAttribute("id", "selectorParentGroup");
  1217. svgroot.appendChild(mgr.selectorParentGroup);
  1218. mgr.selectorMap = {};
  1219. mgr.selectors = [];
  1220. mgr.rubberBandBox = null;
  1221. if($("#canvasBackground").length) return;
  1222. var canvasbg = svgdoc.createElementNS(svgns, "svg");
  1223. var dims = curConfig.dimensions;
  1224. assignAttributes(canvasbg, {
  1225. 'id':'canvasBackground',
  1226. 'width': dims[0],
  1227. 'height': dims[1],
  1228. 'x': 0,
  1229. 'y': 0,
  1230. 'overflow': 'visible',
  1231. 'style': 'pointer-events:none'
  1232. });
  1233. var rect = svgdoc.createElementNS(svgns, "rect");
  1234. assignAttributes(rect, {
  1235. 'width': '100%',
  1236. 'height': '100%',
  1237. 'x': 0,
  1238. 'y': 0,
  1239. 'stroke-width': 1,
  1240. 'stroke': '#000',
  1241. 'fill': '#FFF',
  1242. 'style': 'pointer-events:none'
  1243. });
  1244. // Both Firefox and WebKit are too slow with this filter region (especially at higher
  1245. // zoom levels) and Opera has at least one bug
  1246. // if (!window.opera) rect.setAttribute('filter', 'url(#canvashadow)');
  1247. canvasbg.appendChild(rect);
  1248. svgroot.insertBefore(canvasbg, svgcontent);
  1249. };
  1250. // Function: SelectorManager.requestSelector
  1251. // Returns the selector based on the given element
  1252. //
  1253. // Parameters:
  1254. // elem - DOM element to get the selector for
  1255. this.requestSelector = function(elem) {
  1256. if (elem == null) return null;
  1257. var N = this.selectors.length;
  1258. // if we've already acquired one for this element, return it
  1259. if (typeof(this.selectorMap[elem.id]) == "object") {
  1260. this.selectorMap[elem.id].locked = true;
  1261. return this.selectorMap[elem.id];
  1262. }
  1263. for (var i = 0; i < N; ++i) {
  1264. if (this.selectors[i] && !this.selectors[i].locked) {
  1265. this.selectors[i].locked = true;
  1266. this.selectors[i].reset(elem);
  1267. this.selectorMap[elem.id] = this.selectors[i];
  1268. return this.selectors[i];
  1269. }
  1270. }
  1271. // if we reached here, no available selectors were found, we create one
  1272. this.selectors[N] = new Selector(N, elem);
  1273. this.selectorParentGroup.appendChild(this.selectors[N].selectorGroup);
  1274. this.selectorMap[elem.id] = this.selectors[N];
  1275. return this.selectors[N];
  1276. };
  1277. // Function: SelectorManager.releaseSelector
  1278. // Removes the selector of the given element (hides selection box)
  1279. //
  1280. // Parameters:
  1281. // elem - DOM element to remove the selector for
  1282. this.releaseSelector = function(elem) {
  1283. if (elem == null) return;
  1284. var N = this.selectors.length,
  1285. sel = this.selectorMap[elem.id];
  1286. for (var i = 0; i < N; ++i) {
  1287. if (this.selectors[i] && this.selectors[i] == sel) {
  1288. if (sel.locked == false) {
  1289. console.log("WARNING! selector was released but was already unlocked");
  1290. }
  1291. delete this.selectorMap[elem.id];
  1292. sel.locked = false;
  1293. sel.selectedElement = null;
  1294. sel.showGrips(false);
  1295. // remove from DOM and store reference in JS but only if it exists in the DOM
  1296. try {
  1297. sel.selectorGroup.setAttribute("display", "none");
  1298. } catch(e) { }
  1299. break;
  1300. }
  1301. }
  1302. };
  1303. // Function: SelectorManager.getRubberBandBox
  1304. // Returns the rubberBandBox DOM element. This is the rectangle drawn by the user for selecting/zooming
  1305. this.getRubberBandBox = function() {
  1306. if (this.rubberBandBox == null) {
  1307. this.rubberBandBox = this.selectorParentGroup.appendChild(
  1308. addSvgElementFromJson({ "element": "rect",
  1309. "attr": {
  1310. "id": "selectorRubberBand",
  1311. "fill": "#22C",
  1312. "fill-opacity": 0.15,
  1313. "stroke": "#22C",
  1314. "stroke-width": 0.5,
  1315. "display": "none",
  1316. "style": "pointer-events:none"
  1317. }
  1318. }));
  1319. }
  1320. return this.rubberBandBox;
  1321. };
  1322. this.initGroup();
  1323. };
  1324. }());
  1325. // **************************************************************************************
  1326. // SVGTransformList implementation for Webkit
  1327. // These methods do not currently raise any exceptions.
  1328. // These methods also do not check that transforms are being inserted or handle if
  1329. // a transform is already in the list, etc. This is basically implementing as much
  1330. // of SVGTransformList that we need to get the job done.
  1331. //
  1332. // interface SVGEditTransformList {
  1333. // attribute unsigned long numberOfItems;
  1334. // void clear ( )
  1335. // SVGTransform initialize ( in SVGTransform newItem )
  1336. // SVGTransform getItem ( in unsigned long index )
  1337. // SVGTransform insertItemBefore ( in SVGTransform newItem, in unsigned long index )
  1338. // SVGTransform replaceItem ( in SVGTransform newItem, in unsigned long index )
  1339. // SVGTransform removeItem ( in unsigned long index )
  1340. // SVGTransform appendItem ( in SVGTransform newItem )
  1341. // NOT IMPLEMENTED: SVGTransform createSVGTransformFromMatrix ( in SVGMatrix matrix );
  1342. // NOT IMPLEMENTED: SVGTransform consolidate ( );
  1343. // }
  1344. // **************************************************************************************
  1345. var svgTransformLists = {};
  1346. var SVGEditTransformList = function(elem) {
  1347. function transformToString(xform) {
  1348. var m = xform.matrix,
  1349. text = "";
  1350. switch(xform.type) {
  1351. case 1: // MATRIX
  1352. text = "matrix(" + [m.a,m.b,m.c,m.d,m.e,m.f].join(",") + ")";
  1353. break;
  1354. case 2: // TRANSLATE
  1355. text = "translate(" + m.e + "," + m.f + ")";
  1356. break;
  1357. case 3: // SCALE
  1358. if (m.a == m.d) text = "scale(" + m.a + ")";
  1359. else text = "scale(" + m.a + "," + m.d + ")";
  1360. break;
  1361. case 4: // ROTATE
  1362. var cx = 0, cy = 0;
  1363. // this prevents divide by zero
  1364. if (xform.angle != 0) {
  1365. var K = 1 - m.a;
  1366. cy = ( K * m.f + m.b*m.e ) / ( K*K + m.b*m.b );
  1367. cx = ( m.e - m.b * cy ) / K;
  1368. }
  1369. text = "rotate(" + xform.angle + " " + cx + "," + cy + ")";
  1370. break;
  1371. }
  1372. return text;
  1373. };
  1374. this._elem = elem || null;
  1375. this._xforms = [];
  1376. // TODO: how do we capture the undo-ability in the changed transform list?
  1377. this._update = function() {
  1378. var tstr = "";
  1379. var concatMatrix = svgroot.createSVGMatrix();
  1380. for (var i = 0; i < this.numberOfItems; ++i) {
  1381. var xform = this._list.getItem(i);
  1382. tstr += transformToString(xform) + " ";
  1383. }
  1384. this._elem.setAttribute("transform", tstr);
  1385. };
  1386. this._list = this;
  1387. this._init = function() {
  1388. // Transform attribute parser
  1389. var str = this._elem.getAttribute("transform");
  1390. if(!str) return;
  1391. // TODO: Add skew support in future
  1392. var re = /\s*((scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/;
  1393. var arr = [];
  1394. var m = true;
  1395. while(m) {
  1396. m = str.match(re);
  1397. str = str.replace(re,'');
  1398. if(m && m[1]) {
  1399. var x = m[1];
  1400. var bits = x.split(/\s*\(/);
  1401. var name = bits[0];
  1402. var val_bits = bits[1].match(/\s*(.*?)\s*\)/);
  1403. var val_arr = val_bits[1].split(/[, ]+/);
  1404. var letters = 'abcdef'.split('');
  1405. var mtx = svgroot.createSVGMatrix();
  1406. $.each(val_arr, function(i, item) {
  1407. val_arr[i] = parseFloat(item);
  1408. if(name == 'matrix') {
  1409. mtx[letters[i]] = val_arr[i];
  1410. }
  1411. });
  1412. var xform = svgroot.createSVGTransform();
  1413. var fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1);
  1414. var values = name=='matrix'?[mtx]:val_arr;
  1415. if(name == 'scale' && values.length == 1) {
  1416. values.push(values[0]);
  1417. } else if(name == 'translate' && values.length == 1) {
  1418. values.push(0);
  1419. }
  1420. xform[fname].apply(xform, values);
  1421. this._list.appendItem(xform);
  1422. }
  1423. }
  1424. }
  1425. this.numberOfItems = 0;
  1426. this.clear = function() {
  1427. this.numberOfItems = 0;
  1428. this._xforms = [];
  1429. };
  1430. this.initialize = function(newItem) {
  1431. this.numberOfItems = 1;
  1432. this._xforms = [newItem];
  1433. };
  1434. this.getItem = function(index) {
  1435. if (index < this.numberOfItems && index >= 0) {
  1436. return this._xforms[index];
  1437. }
  1438. return null;
  1439. };
  1440. this.insertItemBefore = function(newItem, index) {
  1441. var retValue = null;
  1442. if (index >= 0) {
  1443. if (index < this.numberOfItems) {
  1444. var newxforms = new Array(this.numberOfItems + 1);
  1445. // TODO: use array copying and slicing
  1446. for ( var i = 0; i < index; ++i) {
  1447. newxforms[i] = this._xforms[i];
  1448. }
  1449. newxforms[i] = newItem;
  1450. for ( var j = i+1; i < this.numberOfItems; ++j, ++i) {
  1451. newxforms[j] = this._xforms[i];
  1452. }
  1453. this.numberOfItems++;
  1454. this._xforms = newxforms;
  1455. retValue = newItem;
  1456. this._list._update();
  1457. }
  1458. else {
  1459. retValue = this._list.appendItem(newItem);
  1460. }
  1461. }
  1462. return retValue;
  1463. };
  1464. this.replaceItem = function(newItem, index) {
  1465. var retValue = null;
  1466. if (index < this.numberOfItems && index >= 0) {
  1467. this._xforms[index] = newItem;
  1468. retValue = newItem;
  1469. this._list._update();
  1470. }
  1471. return retValue;
  1472. };
  1473. this.removeItem = function(index) {
  1474. var retValue = null;
  1475. if (index < this.numberOfItems && index >= 0) {
  1476. var retValue = this._xforms[index];
  1477. var newxforms = new Array(this.numberOfItems - 1);
  1478. for (var i = 0; i < index; ++i) {
  1479. newxforms[i] = this._xforms[i];
  1480. }
  1481. for (var j = i; j < this.numberOfItems-1; ++j, ++i) {
  1482. newxforms[j] = this._xforms[i+1];
  1483. }
  1484. this.numberOfItems--;
  1485. this._xforms = newxforms;
  1486. this._list._update();
  1487. }
  1488. return retValue;
  1489. };
  1490. this.appendItem = function(newItem) {
  1491. this._xforms.push(newItem);
  1492. this.numberOfItems++;
  1493. this._list._update();
  1494. return newItem;
  1495. };
  1496. };
  1497. // **************************************************************************************
  1498. // Group: Helper functions
  1499. // Function: walkTree
  1500. // Walks the tree and executes the callback on each element in a top-down fashion
  1501. //
  1502. // Parameters:
  1503. // elem - DOM element to traverse
  1504. // cbFn - Callback function to run on each element
  1505. function walkTree(elem, cbFn){
  1506. if (elem && elem.nodeType == 1) {
  1507. cbFn(elem);
  1508. var i = elem.childNodes.length;
  1509. while (i--) {
  1510. walkTree(elem.childNodes.item(i), cbFn);
  1511. }
  1512. }
  1513. };
  1514. // Function: walkTreePost
  1515. // Walks the tree and executes the callback on each element in a depth-first fashion
  1516. //
  1517. // Parameters:
  1518. // elem - DOM element to traverse
  1519. // cbFn - Callback function to run on each element
  1520. function walkTreePost(elem, cbFn) {
  1521. if (elem && elem.nodeType == 1) {
  1522. var i = elem.childNodes.length;
  1523. while (i--) {
  1524. walkTree(elem.childNodes.item(i), cbFn);
  1525. }
  1526. cbFn(elem);
  1527. }
  1528. };
  1529. // Function: assignAttributes
  1530. // Assigns multiple attributes to an element.
  1531. //
  1532. // Parameters:
  1533. // node - DOM element to apply new attribute values to
  1534. // attrs - Object with attribute keys/values
  1535. // suspendLength - Optional integer of milliseconds to suspend redraw
  1536. // unitCheck - Boolean to indicate the need to use setUnitAttr
  1537. var assignAttributes = this.assignAttributes = function(node, attrs, suspendLength, unitCheck) {
  1538. if(!suspendLength) suspendLength = 0;
  1539. // Opera has a problem with suspendRedraw() apparently
  1540. var handle = null;
  1541. if (!window.opera) svgroot.suspendRedraw(suspendLength);
  1542. for (var i in attrs) {
  1543. var ns = (i.substr(0,4) == "xml:" ? xmlns :
  1544. i.substr(0,6) == "xlink:" ? xlinkns : null);
  1545. if(ns || !unitCheck) {
  1546. node.setAttributeNS(ns, i, attrs[i]);
  1547. } else {
  1548. setUnitAttr(node, i, attrs[i]);
  1549. }
  1550. }
  1551. if (!window.opera) svgroot.unsuspendRedraw(handle);
  1552. };
  1553. // Function: cleanupElement
  1554. // Remove unneeded (default) attributes, makes resulting SVG smaller
  1555. //
  1556. // Parameters:
  1557. // element - DOM element to clean up
  1558. var cleanupElement = this.cleanupElement = function(element) {
  1559. var handle = svgroot.suspendRedraw(60);
  1560. var defaults = {
  1561. 'fill-opacity':1,
  1562. 'stop-opacity':1,
  1563. 'opacity':1,
  1564. 'stroke':'none',
  1565. 'stroke-dasharray':'none',
  1566. 'stroke-linejoin':'miter',
  1567. 'stroke-linecap':'butt',
  1568. 'stroke-opacity':1,
  1569. 'stroke-width':1,
  1570. 'rx':0,
  1571. 'ry':0
  1572. }
  1573. for(var attr in defaults) {
  1574. var val = defaults[attr];
  1575. if(element.getAttribute(attr) == val) {
  1576. element.removeAttribute(attr);
  1577. }
  1578. }
  1579. svgroot.unsuspendRedraw(handle);
  1580. };
  1581. // Function: addSvgElementFromJson
  1582. // Create a new SVG element based on the given object keys/values and add it to the current layer
  1583. // The element will be ran through cleanupElement before being returned
  1584. //
  1585. // Parameters:
  1586. // data - Object with the following keys/values:
  1587. // * element - DOM element to create
  1588. // * attr - Object with attributes/values to assign to the new element
  1589. // * curStyles - Boolean indicating that current style attributes should be applied first
  1590. //
  1591. // Returns: The new element
  1592. var addSvgElementFromJson = this.addSvgElementFromJson = function(data) {
  1593. var shape = getElem(data.attr.id);
  1594. // if shape is a path but we need to create a rect/ellipse, then remove the path
  1595. if (shape && data.element != shape.tagName) {
  1596. current_layer.removeChild(shape);
  1597. shape = null;
  1598. }
  1599. if (!shape) {
  1600. shape = svgdoc.createElementNS(svgns, data.element);
  1601. if (current_layer) {
  1602. current_layer.appendChild(shape);
  1603. }
  1604. }
  1605. if(data.curStyles) {
  1606. assignAttributes(shape, {
  1607. "fill": cur_shape.fill,
  1608. "stroke": cur_shape.stroke,
  1609. "stroke-width": cur_shape.stroke_width,
  1610. "stroke-dasharray": cur_shape.stroke_dasharray,
  1611. "stroke-linejoin": cur_shape.stroke_linejoin,
  1612. "stroke-linecap": cur_shape.stroke_linecap,
  1613. "stroke-opacity": cur_shape.stroke_opacity,
  1614. "fill-opacity": cur_shape.fill_opacity,
  1615. "opacity": cur_shape.opacity / 2,
  1616. "style": "pointer-events:inherit"
  1617. }, 100);
  1618. }
  1619. assignAttributes(shape, data.attr, 100);
  1620. cleanupElement(shape);
  1621. return shape;
  1622. };
  1623. (function() {
  1624. // TODO: make this string optional and set by the client
  1625. var comment = svgdoc.createComment(" Created with SVG-edit - http://svg-edit.googlecode.com/ ");
  1626. svgcontent.appendChild(comment);
  1627. // TODO For Issue 208: this is a start on a thumbnail
  1628. // var svgthumb = svgdoc.createElementNS(svgns, "use");
  1629. // svgthumb.setAttribute('width', '100');
  1630. // svgthumb.setAttribute('height', '100');
  1631. // svgthumb.setAttributeNS(xlinkns, 'href', '#svgcontent');
  1632. // svgroot.appendChild(svgthumb);
  1633. })();
  1634. // z-ordered array of tuples containing layer names and <g> elements
  1635. // the first layer is the one at the bottom of the rendering
  1636. var all_layers = [],
  1637. // Object to contain image data for raster images that were found encodable
  1638. encodableImages = {},
  1639. // String with image URL of last loadable image
  1640. last_good_img_url = curConfig.imgPath + 'logo.png',
  1641. // pointer to the current layer <g>
  1642. current_layer = null,
  1643. // Object with save options
  1644. save_options = {round_digits: 5},
  1645. // Boolean indicating whether or not a draw action has been started
  1646. started = false,
  1647. // Integer with internal ID number for the latest element
  1648. obj_num = 1,
  1649. // String with an element's initial transform attribute value
  1650. start_transform = null,
  1651. // String indicating the current editor mode
  1652. current_mode = "select",
  1653. // String with the current direction in which an element is being resized
  1654. current_resize_mode = "none",
  1655. // Object containing data for the currently selected styles
  1656. all_properties = {
  1657. shape: {
  1658. fill: "#" + curConfig.initFill.color,
  1659. fill_paint: null,
  1660. fill_opacity: curConfig.initFill.opacity,
  1661. stroke: "#" + curConfig.initStroke.color,
  1662. stroke_paint: null,
  1663. stroke_opacity: curConfig.initStroke.opacity,
  1664. stroke_width: curConfig.initStroke.width,
  1665. stroke_dasharray: 'none',
  1666. stroke_linejoin: 'miter',
  1667. stroke_linecap: 'butt',
  1668. opacity: curConfig.initOpacity
  1669. }
  1670. };
  1671. all_properties.text = $.extend(true, {}, all_properties.shape);
  1672. $.extend(all_properties.text, {
  1673. fill: "#000000",
  1674. stroke_width: 0,
  1675. font_size: 24,
  1676. font_family: 'serif'
  1677. });
  1678. // Current shape style properties
  1679. var cur_shape = all_properties.shape,
  1680. // Current text style properties
  1681. cur_text = all_properties.text,
  1682. // Current general properties
  1683. cur_properties = cur_shape,
  1684. // Float displaying the current zoom level (1 = 100%, .5 = 50%, etc)
  1685. current_zoom = 1,
  1686. // Array with all the currently selected elements
  1687. // default size of 1 until it needs to grow bigger
  1688. selectedElements = new Array(1),
  1689. // Array with selected elements' Bounding box object
  1690. selectedBBoxes = new Array(1),
  1691. // The DOM element that was just selected
  1692. justSelected = null,
  1693. // this object manages selectors for us
  1694. selectorManager = new SelectorManager(),
  1695. // DOM element for selection rectangle drawn by the user
  1696. rubberBox = null,
  1697. // Array of current BBoxes (still needed?)
  1698. curBBoxes = [],
  1699. // Object to contain all included extensions
  1700. extensions = {};
  1701. // Should this return an array by default, so extension results aren't overwritten?
  1702. var runExtensions = this.runExtensions = function(action, vars, returnArray) {
  1703. var result = false;
  1704. if(returnArray) result = [];
  1705. $.each(extensions, function(name, opts) {
  1706. if(action in opts) {
  1707. if(returnArray) {
  1708. result.push(opts[action](vars))
  1709. } else {
  1710. result = opts[action](vars);
  1711. }
  1712. }
  1713. });
  1714. return result;
  1715. }
  1716. // Function: addExtension
  1717. // Add an extension to the editor
  1718. //
  1719. // Parameters:
  1720. // name - String with the ID of the extension
  1721. // ext_func - Function supplied by the extension with its data
  1722. this.addExtension = function(name, ext_func) {
  1723. if(!(name in extensions)) {
  1724. // Provide private vars/funcs here. Is there a better way to do this?
  1725. if($.isFunction(ext_func)) {
  1726. var ext = ext_func($.extend(canvas.getPrivateMethods(), {
  1727. svgroot: svgroot,
  1728. svgcontent: svgcontent,
  1729. nonce: nonce,
  1730. selectorManager: selectorManager
  1731. }));
  1732. } else {
  1733. var ext = ext_func;
  1734. }
  1735. extensions[name] = ext;
  1736. call("extension_added", ext);
  1737. } else {
  1738. console.log('Cannot add extension "' + name + '", an extension by that name already exists"');
  1739. }
  1740. };
  1741. // Function: shortFloat
  1742. // Rounds a given value to a float with number of digits defined in save_options
  1743. //
  1744. // Parameters:
  1745. // val - The value as a String, Number or Array of two numbers to be rounded
  1746. //
  1747. // Returns:
  1748. // If a string/number was given, returns a Float. If an array, return a string
  1749. // with comma-seperated floats
  1750. var shortFloat = function(val) {
  1751. var digits = save_options.round_digits;
  1752. if(!isNaN(val)) {
  1753. return Number(Number(val).toFixed(digits));
  1754. } else if($.isArray(val)) {
  1755. return shortFloat(val[0]) + ',' + shortFloat(val[1]);
  1756. }
  1757. }
  1758. // This method rounds the incoming value to the nearest value based on the current_zoom
  1759. var round = this.round = function(val) {
  1760. return parseInt(val*current_zoom)/current_zoom;
  1761. };
  1762. // This method sends back an array or a NodeList full of elements that
  1763. // intersect the multi-select rubber-band-box on the current_layer only.
  1764. //
  1765. // Since the only browser that supports the SVG DOM getIntersectionList is Opera,
  1766. // we need to provide an implementation here. We brute-force it for now.
  1767. //
  1768. // Reference:
  1769. // Firefox does not implement getIntersectionList(), see https://bugzilla.mozilla.org/show_bug.cgi?id=501421
  1770. // Webkit does not implement getIntersectionList(), see https://bugs.webkit.org/show_bug.cgi?id=11274
  1771. var getIntersectionList = this.getIntersectionList = function(rect) {
  1772. if (rubberBox == null) { return null; }
  1773. if(!curBBoxes.length) {
  1774. // Cache all bboxes
  1775. curBBoxes = getVisibleElements(current_layer, true);
  1776. }
  1777. var resultList = null;
  1778. try {
  1779. resultList = current_layer.getIntersectionList(rect, null);
  1780. } catch(e) { }
  1781. if (resultList == null || typeof(resultList.item) != "function") {
  1782. resultList = [];
  1783. var rubberBBox = rubberBox.getBBox();
  1784. $.each(rubberBBox, function(key, val) {
  1785. rubberBBox[key] = val / current_zoom;
  1786. });
  1787. var i = curBBoxes.length;
  1788. while (i--) {
  1789. if(!rubberBBox.width || !rubberBBox.width) continue;
  1790. if (Utils.rectsIntersect(rubberBBox, curBBoxes[i].bbox)) {
  1791. resultList.push(curBBoxes[i].elem);
  1792. }
  1793. }
  1794. }
  1795. // addToSelection expects an array, but it's ok to pass a NodeList
  1796. // because using square-bracket notation is allowed:
  1797. // http://www.w3.org/TR/DOM-Level-2-Core/ecma-script-binding.html
  1798. return resultList;
  1799. };
  1800. // Function: getStrokedBBox
  1801. // Get the bounding box for one or more stroked and/or transformed elements
  1802. //
  1803. // Parameters:
  1804. // elems - Array with DOM elements to check
  1805. //
  1806. // Returns:
  1807. // A single bounding box object
  1808. var getStrokedBBox = this.getStrokedBBox = function(elems) {
  1809. if(!elems) elems = getVisibleElements();
  1810. if(!elems.length) return false;
  1811. // Make sure the expected BBox is returned if the element is a group
  1812. var getCheckedBBox = function(elem) {
  1813. try {
  1814. // TODO: Fix issue with rotated groups. Currently they work
  1815. // fine in FF, but not in other browsers (same problem mentioned
  1816. // in Issue 339 comment #2).
  1817. var bb = getBBox(elem);
  1818. var angle = getRotationAngle(elem);
  1819. if ((angle && angle % 90) || hasMatrixTransform(getTransformList(elem))) {
  1820. // Accurate way to get BBox of rotated element in Firefox:
  1821. // Put element in group and get its BBox
  1822. var good_bb = false;
  1823. // Get the BBox from the raw path for these elements
  1824. var elemNames = ['ellipse','path','line','polyline','polygon'];
  1825. if($.inArray(elem.tagName, elemNames) != -1) {
  1826. bb = good_bb = canvas.convertToPath(elem, true);
  1827. } else if(elem.tagName == 'rect') {
  1828. // Look for radius
  1829. var rx = elem.getAttribute('rx');
  1830. var ry = elem.getAttribute('ry');
  1831. if(rx || ry) {
  1832. bb = good_bb = canvas.convertToPath(elem, true);
  1833. }
  1834. }
  1835. if(!good_bb) {
  1836. var g = document.createElementNS(svgns, "g");
  1837. var parent = elem.parentNode;
  1838. parent.replaceChild(g, elem);
  1839. g.appendChild(elem);
  1840. bb = g.getBBox();
  1841. parent.insertBefore(elem,g);
  1842. parent.removeChild(g);
  1843. }
  1844. // Old method: Works by giving the rotated BBox,
  1845. // this is (unfortunately) what Opera and Safari do
  1846. // natively when getting the BBox of the parent group
  1847. // var angle = angle * Math.PI / 180.0;
  1848. // var rminx = Number.MAX_VALUE, rminy = Number.MAX_VALUE,
  1849. // rmaxx = Number.MIN_VALUE, rmaxy = Number.MIN_VALUE;
  1850. // var cx = round(bb.x + bb.width/2),
  1851. // cy = round(bb.y + bb.height/2);
  1852. // var pts = [ [bb.x - cx, bb.y - cy],
  1853. // [bb.x + bb.width - cx, bb.y - cy],
  1854. // [bb.x + bb.width - cx, bb.y + bb.height - cy],
  1855. // [bb.x - cx, bb.y + bb.height - cy] ];
  1856. // var j = 4;
  1857. // while (j--) {
  1858. // var x = pts[j][0],
  1859. // y = pts[j][1],
  1860. // r = Math.sqrt( x*x + y*y );
  1861. // var theta = Math.atan2(y,x) + angle;
  1862. // x = round(r * Math.cos(theta) + cx);
  1863. // y = round(r * Math.sin(theta) + cy);
  1864. //
  1865. // // now set the bbox for the shape after it's been rotated
  1866. // if (x < rminx) rminx = x;
  1867. // if (y < rminy) rminy = y;
  1868. // if (x > rmaxx) rmaxx = x;
  1869. // if (y > rmaxy) rmaxy = y;
  1870. // }
  1871. //
  1872. // bb.x = rminx;
  1873. // bb.y = rminy;
  1874. // bb.width = rmaxx - rminx;
  1875. // bb.height = rmaxy - rminy;
  1876. }
  1877. return bb;
  1878. } catch(e) {
  1879. console.log(elem, e);
  1880. return null;
  1881. }
  1882. }
  1883. var full_bb;
  1884. $.each(elems, function() {
  1885. if(full_bb) return;
  1886. if(!this.parentNode) return;
  1887. full_bb = getCheckedBBox(this);
  1888. });
  1889. // This shouldn't ever happen...
  1890. if(full_bb == null) return null;
  1891. // full_bb doesn't include the stoke, so this does no good!
  1892. // if(elems.length == 1) return full_bb;
  1893. var max_x = full_bb.x + full_bb.width;
  1894. var max_y = full_bb.y + full_bb.height;
  1895. var min_x = full_bb.x;
  1896. var min_y = full_bb.y;
  1897. // FIXME: same re-creation problem with this function as getCheckedBBox() above
  1898. var getOffset = function(elem) {
  1899. var sw = elem.getAttribute("stroke-width");
  1900. var offset = 0;
  1901. if (elem.getAttribute("stroke") != "none" && !isNaN(sw)) {
  1902. offset += sw/2;
  1903. }
  1904. return offset;
  1905. }
  1906. var bboxes = [];
  1907. $.each(elems, function(i, elem) {
  1908. var cur_bb = getCheckedBBox(elem);
  1909. if(cur_bb) {
  1910. var offset = getOffset(elem);
  1911. min_x = Math.min(min_x, cur_bb.x - offset);
  1912. min_y = Math.min(min_y, cur_bb.y - offset);
  1913. bboxes.push(cur_bb);
  1914. }
  1915. });
  1916. full_bb.x = min_x;
  1917. full_bb.y = min_y;
  1918. $.each(elems, function(i, elem) {
  1919. var cur_bb = bboxes[i];
  1920. // ensure that elem is really an element node
  1921. if (cur_bb && elem.nodeType == 1) {
  1922. var offset = getOffset(elem);
  1923. max_x = Math.max(max_x, cur_bb.x + cur_bb.width + offset);
  1924. max_y = Math.max(max_y, cur_bb.y + cur_bb.height + offset);
  1925. }
  1926. });
  1927. full_bb.width = max_x - min_x;
  1928. full_bb.height = max_y - min_y;
  1929. return full_bb;
  1930. }
  1931. // Function: getVisibleElements
  1932. // Get all elements that have a BBox (excludes <defs>, <title>, etc).
  1933. // Note that 0-opacity, off-screen etc elements are still considered "visible"
  1934. // for this function
  1935. //
  1936. // Parameters:
  1937. // parent - The parent DOM element to search within
  1938. // includeBBox - Boolean to indicate that an object should return with the element and its bbox
  1939. //
  1940. // Returns:
  1941. // An array with all "visible" elements, or if includeBBox is true, an array with
  1942. // objects that include:
  1943. // * elem - The element
  1944. // * bbox - The element's BBox as retrieved from getStrokedBBox
  1945. var getVisibleElements = this.getVisibleElements = function(parent, includeBBox) {
  1946. if(!parent) parent = $(svgcontent).children(); // Prevent layers from being included
  1947. var contentElems = [];
  1948. $(parent).children().each(function(i, elem) {
  1949. try {
  1950. var box = elem.getBBox();
  1951. if (box) {
  1952. var item = includeBBox?{'elem':elem, 'bbox':getStrokedBBox([elem])}:elem;
  1953. contentElems.push(item);
  1954. }
  1955. } catch(e) {}
  1956. });
  1957. return contentElems.reverse();
  1958. }
  1959. // Function: copyElem
  1960. // Create a clone of an element, updating its ID and its children's IDs when needed
  1961. //
  1962. // Parameters:
  1963. // el - DOM element to clone
  1964. //
  1965. // Returns: The cloned element
  1966. var copyElem = function(el) {
  1967. // manually create a copy of the element
  1968. var new_el = document.createElementNS(el.namespaceURI, el.nodeName);
  1969. $.each(el.attributes, function(i, attr) {
  1970. if (attr.localName != '-moz-math-font-style') {
  1971. new_el.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.nodeValue);
  1972. }
  1973. });
  1974. // set the copied element's new id
  1975. new_el.removeAttribute("id");
  1976. new_el.id = getNextId();
  1977. // manually increment obj_num because our cloned elements are not in the DOM yet
  1978. obj_num++;
  1979. // Opera's "d" value needs to be reset for Opera/Win/non-EN
  1980. // Also needed for webkit (else does not keep curved segments on clone)
  1981. if((isWebkit) && el.nodeName == 'path') {
  1982. var fixed_d = pathActions.convertPath(el);
  1983. new_el.setAttribute('d', fixed_d);
  1984. }
  1985. // now create copies of all children
  1986. $.each(el.childNodes, function(i, child) {
  1987. switch(child.nodeType) {
  1988. case 1: // element node
  1989. new_el.appendChild(copyElem(child));
  1990. break;
  1991. case 3: // text node
  1992. new_el.textContent = child.nodeValue;
  1993. break;
  1994. default:
  1995. break;
  1996. }
  1997. });
  1998. if(new_el.tagName == 'image') {
  1999. preventClickDefault(new_el);
  2000. }
  2001. return new_el;
  2002. };
  2003. // Function: getElem
  2004. // Get a DOM element by ID within the SVG root element.
  2005. //
  2006. // Parameters:
  2007. // id - String with the element's new ID
  2008. function getElem(id) {
  2009. // if(svgroot.getElementById) {
  2010. // // getElementById lookup
  2011. // return svgroot.getElementById(id);
  2012. // } else
  2013. if(svgroot.querySelector) {
  2014. // querySelector lookup
  2015. return svgroot.querySelector('#'+id);
  2016. } else if(svgdoc.evaluate) {
  2017. // xpath lookup
  2018. return svgdoc.evaluate('svg:svg[@id="svgroot"]//svg:*[@id="'+id+'"]', container, function() { return "http://www.w3.org/2000/svg"; }, 9, null).singleNodeValue;
  2019. } else {
  2020. // jQuery lookup: twice as slow as xpath in FF
  2021. return $(svgroot).find('[id=' + id + ']')[0];
  2022. }
  2023. // getElementById lookup: includes icons, not good
  2024. // return svgdoc.getElementById(id);
  2025. }
  2026. // Set scope for these functions
  2027. var getId, getNextId;
  2028. (function(c) {
  2029. // Object to contain editor event names and callback functions
  2030. var events = {};
  2031. // Prefix string for element IDs
  2032. var idprefix = "svg_";
  2033. // Function: getId
  2034. // Returns the last created DOM element ID string
  2035. getId = c.getId = function() {
  2036. if (events["getid"]) return call("getid", obj_num);
  2037. if (randomize_ids) {
  2038. return idprefix + nonce +'_' + obj_num;
  2039. } else {
  2040. return idprefix + obj_num;
  2041. }
  2042. };
  2043. // Function: getNextId
  2044. // Creates and returns a unique ID string for a DOM element
  2045. getNextId = c.getNextId = function() {
  2046. // ensure the ID does not exist
  2047. var id = getId();
  2048. while (getElem(id)) {
  2049. obj_num++;
  2050. id = getId();
  2051. }
  2052. return id;
  2053. };
  2054. // Run the callback function associated with the given event
  2055. //
  2056. // Parameters:
  2057. // event - String with the event name
  2058. // arg - Argument to pass through to the callback function
  2059. call = c.call = function(event, arg) {
  2060. if (events[event]) {
  2061. return events[event](this,arg);
  2062. }
  2063. };
  2064. // Function: bind
  2065. // Attaches a callback function to an event
  2066. //
  2067. // Parameters:
  2068. // event - String indicating the name of the event
  2069. // f - The callback function to bind to the event
  2070. //
  2071. // Return:
  2072. // The previous event
  2073. c.bind = function(event, f) {
  2074. var old = events[event];
  2075. events[event] = f;
  2076. return old;
  2077. };
  2078. // Function: setIdPrefix
  2079. // Changes the ID prefix to the given value
  2080. //
  2081. // Parameters:
  2082. // p - String with the new prefix
  2083. c.setIdPrefix = function(p) {
  2084. idprefix = p;
  2085. };
  2086. }(canvas));
  2087. // Function: sanitizeSvg
  2088. // Sanitizes the input node and its children
  2089. // It only keeps what is allowed from our whitelist defined above
  2090. //
  2091. // Parameters:
  2092. // node - The DOM element to be checked, will also check its children
  2093. var sanitizeSvg = this.sanitizeSvg = function(node) {
  2094. // we only care about element nodes
  2095. // automatically return for all comment, etc nodes
  2096. // for text, we do a whitespace trim
  2097. if (node.nodeType == 3) {
  2098. node.nodeValue = node.nodeValue.replace(/^\s+|\s+$/g, "");
  2099. // Remove empty text nodes
  2100. if(!node.nodeValue.length) node.parentNode.removeChild(node);
  2101. }
  2102. if (node.nodeType != 1) return;
  2103. var doc = node.ownerDocument;
  2104. var parent = node.parentNode;
  2105. // can parent ever be null here? I think the root node's parent is the document...
  2106. if (!doc || !parent) return;
  2107. var allowedAttrs = svgWhiteList[node.nodeName];
  2108. var allowedAttrsNS = svgWhiteListNS[node.nodeName];
  2109. // if this element is allowed
  2110. if (allowedAttrs != undefined) {
  2111. var se_attrs = [];
  2112. var i = node.attributes.length;
  2113. while (i--) {
  2114. // if the attribute is not in our whitelist, then remove it
  2115. // could use jQuery's inArray(), but I don't know if that's any better
  2116. var attr = node.attributes.item(i);
  2117. var attrName = attr.nodeName;
  2118. var attrLocalName = attr.localName;
  2119. var attrNsURI = attr.namespaceURI;
  2120. // Check that an attribute with the correct localName in the correct namespace is on
  2121. // our whitelist or is a namespace declaration for one of our allowed namespaces
  2122. if (!(allowedAttrsNS.hasOwnProperty(attrLocalName) && attrNsURI == allowedAttrsNS[attrLocalName] && attrNsURI != xmlnsns) &&
  2123. !(attrNsURI == xmlnsns && nsMap[attr.nodeValue]) )
  2124. {
  2125. // Bypassing the whitelist to allow se: prefixes. Is there
  2126. // a more appropriate way to do this?
  2127. if(attrName.indexOf('se:') == 0) {
  2128. se_attrs.push([attrName, attr.nodeValue]);
  2129. }
  2130. node.removeAttributeNS(attrNsURI, attrLocalName);
  2131. }
  2132. // special handling for path d attribute
  2133. if (node.nodeName == 'path' && attrName == 'd') {
  2134. // Convert to absolute
  2135. node.setAttribute('d',pathActions.convertPath(node));
  2136. pathActions.fixEnd(node);
  2137. }
  2138. // for the style attribute, rewrite it in terms of XML presentational attributes
  2139. if (attrName == "style") {
  2140. var props = attr.nodeValue.split(";"),
  2141. p = props.length;
  2142. while(p--) {
  2143. var nv = props[p].split(":");
  2144. // now check that this attribute is supported
  2145. if (allowedAttrs.indexOf(nv[0]) != -1) {
  2146. node.setAttribute(nv[0],nv[1]);
  2147. }
  2148. }
  2149. node.removeAttribute('style');
  2150. }
  2151. }
  2152. $.each(se_attrs, function(i, attr) {
  2153. node.setAttributeNS(se_ns, attr[0], attr[1]);
  2154. });
  2155. // for some elements that have a xlink:href, ensure the URI refers to a local element
  2156. // (but not for links)
  2157. var href = node.getAttributeNS(xlinkns,"href");
  2158. if(href &&
  2159. $.inArray(node.nodeName, ["filter", "linearGradient", "pattern",
  2160. "radialGradient", "textPath", "use"]) != -1)
  2161. {
  2162. // TODO: we simply check if the first character is a #, is this bullet-proof?
  2163. if (href[0] != "#") {
  2164. // remove the attribute (but keep the element)
  2165. node.setAttributeNS(xlinkns, "xlink:href", "");
  2166. node.removeAttributeNS(xlinkns, "href");
  2167. }
  2168. }
  2169. // Safari crashes on a <use> without a xlink:href, so we just remove the node here
  2170. if (node.nodeName == "use" && !node.getAttributeNS(xlinkns,"href")) {
  2171. parent.removeChild(node);
  2172. return;
  2173. }
  2174. // if the element has attributes pointing to a non-local reference,
  2175. // need to remove the attribute
  2176. $.each(["clip-path", "fill", "filter", "marker-end", "marker-mid", "marker-start", "mask", "stroke"],function(i,attr) {
  2177. var val = node.getAttribute(attr);
  2178. if (val) {
  2179. val = getUrlFromAttr(val);
  2180. // simply check for first character being a '#'
  2181. if (val && val[0] != "#") {
  2182. node.setAttribute(attr, "");
  2183. node.removeAttribute(attr);
  2184. }
  2185. }
  2186. });
  2187. // recurse to children
  2188. i = node.childNodes.length;
  2189. while (i--) { sanitizeSvg(node.childNodes.item(i)); }
  2190. }
  2191. // else, remove this element
  2192. else {
  2193. // remove all children from this node and insert them before this node
  2194. // FIXME: in the case of animation elements this will hardly ever be correct
  2195. var children = [];
  2196. while (node.hasChildNodes()) {
  2197. children.push(parent.insertBefore(node.firstChild, node));
  2198. }
  2199. // remove this node from the document altogether
  2200. parent.removeChild(node);
  2201. // call sanitizeSvg on each of those children
  2202. var i = children.length;
  2203. while (i--) { sanitizeSvg(children[i]); }
  2204. }
  2205. };
  2206. // Function: getUrlFromAttr
  2207. // Extracts the URL from the url(...) syntax of some attributes.
  2208. // Three variants:
  2209. // * <circle fill="url(someFile.svg#foo)" />
  2210. // * <circle fill="url('someFile.svg#foo')" />
  2211. // * <circle fill='url("someFile.svg#foo")' />
  2212. //
  2213. // Parameters:
  2214. // attrVal - The attribute value as a string
  2215. //
  2216. // Returns:
  2217. // String with just the URL, like someFile.svg#foo
  2218. var getUrlFromAttr = this.getUrlFromAttr = function(attrVal) {
  2219. if (attrVal) {
  2220. // url("#somegrad")
  2221. if (attrVal.indexOf('url("') == 0) {
  2222. return attrVal.substring(5,attrVal.indexOf('"',6));
  2223. }
  2224. // url('#somegrad')
  2225. else if (attrVal.indexOf("url('") == 0) {
  2226. return attrVal.substring(5,attrVal.indexOf("'",6));
  2227. }
  2228. else if (attrVal.indexOf("url(") == 0) {
  2229. return attrVal.substring(4,attrVal.indexOf(')'));
  2230. }
  2231. }
  2232. return null;
  2233. };
  2234. // Function: getBBox
  2235. // Get the given/selected element's bounding box object, convert it to be more
  2236. // usable when necessary
  2237. //
  2238. // Parameters:
  2239. // elem - Optional DOM element to get the BBox for
  2240. var getBBox = this.getBBox = function(elem) {
  2241. var selected = elem || selectedElements[0];
  2242. if (elem.nodeType != 1) return null;
  2243. var ret = null;
  2244. if(elem.nodeName == 'text' && selected.textContent == '') {
  2245. selected.textContent = 'a'; // Some character needed for the selector to use.
  2246. ret = selected.getBBox();
  2247. selected.textContent = '';
  2248. } else if(elem.nodeName == 'path' && isWebkit) {
  2249. ret = getPathBBox(selected);
  2250. } else if(elem.nodeName == 'use' && !isWebkit) {
  2251. ret = selected.getBBox();
  2252. ret.x += parseFloat(selected.getAttribute('x')||0);
  2253. ret.y += parseFloat(selected.getAttribute('y')||0);
  2254. } else if(elem.nodeName == 'foreignObject') {
  2255. ret = selected.getBBox();
  2256. ret.x += parseFloat(selected.getAttribute('x')||0);
  2257. ret.y += parseFloat(selected.getAttribute('y')||0);
  2258. } else {
  2259. try { ret = selected.getBBox(); }
  2260. catch(e) {
  2261. // Check if element is child of a foreignObject
  2262. var fo = $(selected).closest("foreignObject");
  2263. if(fo.length) {
  2264. try {
  2265. ret = fo[0].getBBox();
  2266. } catch(e) {
  2267. ret = null;
  2268. }
  2269. } else {
  2270. ret = null;
  2271. }
  2272. }
  2273. }
  2274. // get the bounding box from the DOM (which is in that element's coordinate system)
  2275. return ret;
  2276. };
  2277. // Function: ffClone
  2278. // Hack for Firefox bugs where text element features aren't updated.
  2279. // This function clones the element and re-selects it
  2280. // TODO: Test for this bug on load and add it to "support" object instead of
  2281. // browser sniffing
  2282. //
  2283. // Parameters:
  2284. // elem - The (text) DOM element to clone
  2285. var ffClone = function(elem) {
  2286. if(navigator.userAgent.indexOf('Gecko/') == -1) return elem;
  2287. var clone = elem.cloneNode(true)
  2288. elem.parentNode.insertBefore(clone, elem);
  2289. elem.parentNode.removeChild(elem);
  2290. selectorManager.releaseSelector(elem);
  2291. selectedElements[0] = clone;
  2292. selectorManager.requestSelector(clone).showGrips(true);
  2293. return clone;
  2294. }
  2295. // Function: getPathBBox
  2296. // Get correct BBox for a path in Webkit
  2297. // Converted from code found here:
  2298. // http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  2299. //
  2300. // Parameters:
  2301. // path - The path DOM element to get the BBox for
  2302. //
  2303. // Returns:
  2304. // A BBox-like object
  2305. var getPathBBox = function(path) {
  2306. var seglist = path.pathSegList;
  2307. var tot = seglist.numberOfItems;
  2308. var bounds = [[], []];
  2309. var start = seglist.getItem(0);
  2310. var P0 = [start.x, start.y];
  2311. for(var i=0; i < tot; i++) {
  2312. var seg = seglist.getItem(i);
  2313. if(!seg.x) continue;
  2314. // Add actual points to limits
  2315. bounds[0].push(P0[0]);
  2316. bounds[1].push(P0[1]);
  2317. if(seg.x1) {
  2318. var P1 = [seg.x1, seg.y1],
  2319. P2 = [seg.x2, seg.y2],
  2320. P3 = [seg.x, seg.y];
  2321. for(var j=0; j < 2; j++) {
  2322. var calc = function(t) {
  2323. return Math.pow(1-t,3) * P0[j]
  2324. + 3 * Math.pow(1-t,2) * t * P1[j]
  2325. + 3 * (1-t) * Math.pow(t,2) * P2[j]
  2326. + Math.pow(t,3) * P3[j];
  2327. };
  2328. var b = 6 * P0[j] - 12 * P1[j] + 6 * P2[j];
  2329. var a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j];
  2330. var c = 3 * P1[j] - 3 * P0[j];
  2331. if(a == 0) {
  2332. if(b == 0) {
  2333. continue;
  2334. }
  2335. var t = -c / b;
  2336. if(0 < t && t < 1) {
  2337. bounds[j].push(calc(t));
  2338. }
  2339. continue;
  2340. }
  2341. var b2ac = Math.pow(b,2) - 4 * c * a;
  2342. if(b2ac < 0) continue;
  2343. var t1 = (-b + Math.sqrt(b2ac))/(2 * a);
  2344. if(0 < t1 && t1 < 1) bounds[j].push(calc(t1));
  2345. var t2 = (-b - Math.sqrt(b2ac))/(2 * a);
  2346. if(0 < t2 && t2 < 1) bounds[j].push(calc(t2));
  2347. }
  2348. P0 = P3;
  2349. } else {
  2350. bounds[0].push(seg.x);
  2351. bounds[1].push(seg.y);
  2352. }
  2353. }
  2354. var x = Math.min.apply(null, bounds[0]);
  2355. var w = Math.max.apply(null, bounds[0]) - x;
  2356. var y = Math.min.apply(null, bounds[1]);
  2357. var h = Math.max.apply(null, bounds[1]) - y;
  2358. return {
  2359. 'x': x,
  2360. 'y': y,
  2361. 'width': w,
  2362. 'height': h
  2363. };
  2364. }
  2365. // this.each is deprecated, if any extension used this it can be recreated by doing this:
  2366. // $(canvas.getRootElem()).children().each(...)
  2367. // this.each = function(cb) {
  2368. // $(svgroot).children().each(cb);
  2369. // };
  2370. // Group: Element Transforms
  2371. // Function: getRotationAngle
  2372. // Get the rotation angle of the given/selected DOM element
  2373. //
  2374. // Parameters:
  2375. // elem - Optional DOM element to get the angle for
  2376. // to_rad - Boolean that when true returns the value in radians rather than degrees
  2377. //
  2378. // Returns:
  2379. // Float with the angle in degrees or radians
  2380. var getRotationAngle = this.getRotationAngle = function(elem, to_rad) {
  2381. var selected = elem || selectedElements[0];
  2382. // find the rotation transform (if any) and set it
  2383. var tlist = getTransformList(selected);
  2384. if(!tlist) return 0; // <svg> elements have no tlist
  2385. var N = tlist.numberOfItems;
  2386. for (var i = 0; i < N; ++i) {
  2387. var xform = tlist.getItem(i);
  2388. if (xform.type == 4) {
  2389. return to_rad ? xform.angle * Math.PI / 180.0 : xform.angle;
  2390. }
  2391. }
  2392. return 0.0;
  2393. };
  2394. // Function: setRotationAngle
  2395. // Removes any old rotations if present, prepends a new rotation at the
  2396. // transformed center
  2397. //
  2398. // Parameters:
  2399. // val - The new rotation angle in degrees
  2400. // preventUndo - Boolean indicating whether the action should be undoable or not
  2401. this.setRotationAngle = function(val, preventUndo) {
  2402. // ensure val is the proper type
  2403. val = parseFloat(val);
  2404. var elem = selectedElements[0];
  2405. var oldTransform = elem.getAttribute("transform");
  2406. var bbox = getBBox(elem);
  2407. var cx = bbox.x+bbox.width/2, cy = bbox.y+bbox.height/2;
  2408. var tlist = getTransformList(elem);
  2409. // only remove the real rotational transform if present (i.e. at index=0)
  2410. if (tlist.numberOfItems > 0) {
  2411. var xform = tlist.getItem(0);
  2412. if (xform.type == 4) {
  2413. tlist.removeItem(0);
  2414. }
  2415. }
  2416. // find R_nc and insert it
  2417. if (val != 0) {
  2418. var center = transformPoint(cx,cy,transformListToTransform(tlist).matrix);
  2419. var R_nc = svgroot.createSVGTransform();
  2420. R_nc.setRotate(val, center.x, center.y);
  2421. tlist.insertItemBefore(R_nc,0);
  2422. }
  2423. else if (tlist.numberOfItems == 0) {
  2424. elem.removeAttribute("transform");
  2425. }
  2426. if (!preventUndo) {
  2427. // we need to undo it, then redo it so it can be undo-able! :)
  2428. // TODO: figure out how to make changes to transform list undo-able cross-browser?
  2429. var newTransform = elem.getAttribute("transform");
  2430. elem.setAttribute("transform", oldTransform);
  2431. changeSelectedAttribute("transform",newTransform,selectedElements);
  2432. }
  2433. var pointGripContainer = getElem("pathpointgrip_container");
  2434. // if(elem.nodeName == "path" && pointGripContainer) {
  2435. // pathActions.setPointContainerTransform(elem.getAttribute("transform"));
  2436. // }
  2437. var selector = selectorManager.requestSelector(selectedElements[0]);
  2438. selector.resize();
  2439. selector.updateGripCursors(val);
  2440. };
  2441. // Function: getTransformList
  2442. // Returns an object that behaves like a SVGTransformList for the given DOM element
  2443. //
  2444. // Parameters:
  2445. // elem - DOM element to get a transformlist from
  2446. var getTransformList = this.getTransformList = function(elem) {
  2447. if (isWebkit) {
  2448. var id = elem.id;
  2449. if(!id) {
  2450. // Get unique ID for temporary element
  2451. id = 'temp';
  2452. }
  2453. var t = svgTransformLists[id];
  2454. if (!t || id == 'temp') {
  2455. svgTransformLists[id] = new SVGEditTransformList(elem);
  2456. svgTransformLists[id]._init();
  2457. t = svgTransformLists[id];
  2458. }
  2459. return t;
  2460. }
  2461. else if (elem.transform) {
  2462. return elem.transform.baseVal;
  2463. }
  2464. else if (elem.gradientTransform) {
  2465. return elem.gradientTransform.baseVal;
  2466. }
  2467. return null;
  2468. };
  2469. // Function: recalculateAllSelectedDimensions
  2470. // Runs recalculateDimensions on the selected elements,
  2471. // adding the changes to a single batch command
  2472. var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function() {
  2473. var text = (current_resize_mode == "none" ? "position" : "size");
  2474. var batchCmd = new BatchCommand(text);
  2475. var i = selectedElements.length;
  2476. while(i--) {
  2477. var elem = selectedElements[i];
  2478. // if(getRotationAngle(elem) && !hasMatrixTransform(getTransformList(elem))) continue;
  2479. var cmd = recalculateDimensions(elem);
  2480. if (cmd) {
  2481. batchCmd.addSubCommand(cmd);
  2482. }
  2483. }
  2484. if (!batchCmd.isEmpty()) {
  2485. addCommandToHistory(batchCmd);
  2486. call("changed", selectedElements);
  2487. }
  2488. };
  2489. // this is how we map paths to our preferred relative segment types
  2490. var pathMap = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a',
  2491. 'H', 'h', 'V', 'v', 'S', 's', 'T', 't'];
  2492. // Debug tool to easily see the current matrix in the browser's console
  2493. var logMatrix = function(m) {
  2494. console.log([m.a,m.b,m.c,m.d,m.e,m.f]);
  2495. };
  2496. // Function: remapElement
  2497. // Applies coordinate changes to an element based on the given matrix
  2498. //
  2499. // Parameters:
  2500. // selected - DOM element to be changed
  2501. // changes - Object with changes to be remapped
  2502. // m - Matrix object to use for remapping coordinates
  2503. var remapElement = this.remapElement = function(selected,changes,m) {
  2504. var remap = function(x,y) { return transformPoint(x,y,m); },
  2505. scalew = function(w) { return m.a*w; },
  2506. scaleh = function(h) { return m.d*h; },
  2507. box = getBBox(selected);
  2508. switch (selected.tagName)
  2509. {
  2510. case "line":
  2511. var pt1 = remap(changes["x1"],changes["y1"]),
  2512. pt2 = remap(changes["x2"],changes["y2"]);
  2513. changes["x1"] = pt1.x;
  2514. changes["y1"] = pt1.y;
  2515. changes["x2"] = pt2.x;
  2516. changes["y2"] = pt2.y;
  2517. break;
  2518. case "circle":
  2519. var c = remap(changes["cx"],changes["cy"]);
  2520. changes["cx"] = c.x;
  2521. changes["cy"] = c.y;
  2522. // take the minimum of the new selected box's dimensions for the new circle radius
  2523. var tbox = transformBox(box.x, box.y, box.width, box.height, m);
  2524. var w = tbox.tr.x - tbox.tl.x, h = tbox.bl.y - tbox.tl.y;
  2525. changes["r"] = Math.min(w/2, h/2);
  2526. break;
  2527. case "ellipse":
  2528. var c = remap(changes["cx"],changes["cy"]);
  2529. changes["cx"] = c.x;
  2530. changes["cy"] = c.y;
  2531. changes["rx"] = scalew(changes["rx"]);
  2532. changes["ry"] = scaleh(changes["ry"]);
  2533. break;
  2534. case "foreignObject":
  2535. case "rect":
  2536. case "image":
  2537. var pt1 = remap(changes["x"],changes["y"]);
  2538. changes["x"] = pt1.x;
  2539. changes["y"] = pt1.y;
  2540. changes["width"] = scalew(changes["width"]);
  2541. changes["height"] = scaleh(changes["height"]);
  2542. break;
  2543. case "use":
  2544. var pt1 = remap(changes["x"],changes["y"]);
  2545. changes["x"] = pt1.x;
  2546. changes["y"] = pt1.y;
  2547. break;
  2548. case "text":
  2549. // if it was a translate, then just update x,y
  2550. if (m.a == 1 && m.b == 0 && m.c == 0 && m.d == 1 &&
  2551. (m.e != 0 || m.f != 0) )
  2552. {
  2553. // [T][M] = [M][T']
  2554. // therefore [T'] = [M_inv][T][M]
  2555. var existing = transformListToTransform(selected).matrix,
  2556. t_new = matrixMultiply(existing.inverse(), m, existing);
  2557. changes["x"] = parseFloat(changes["x"]) + t_new.e;
  2558. changes["y"] = parseFloat(changes["y"]) + t_new.f;
  2559. }
  2560. else {
  2561. // we just absorb all matrices into the element and don't do any remapping
  2562. var chlist = getTransformList(selected);
  2563. var mt = svgroot.createSVGTransform();
  2564. mt.setMatrix(matrixMultiply(transformListToTransform(chlist).matrix,m));
  2565. chlist.clear();
  2566. chlist.appendItem(mt);
  2567. }
  2568. break;
  2569. case "polygon":
  2570. case "polyline":
  2571. var len = changes["points"].length;
  2572. for (var i = 0; i < len; ++i) {
  2573. var pt = changes["points"][i];
  2574. pt = remap(pt.x,pt.y);
  2575. changes["points"][i].x = pt.x;
  2576. changes["points"][i].y = pt.y;
  2577. }
  2578. break;
  2579. case "path":
  2580. var segList = selected.pathSegList;
  2581. var len = segList.numberOfItems;
  2582. changes.d = new Array(len);
  2583. for (var i = 0; i < len; ++i) {
  2584. var seg = segList.getItem(i);
  2585. changes.d[i] = {
  2586. type: seg.pathSegType,
  2587. x: seg.x,
  2588. y: seg.y,
  2589. x1: seg.x1,
  2590. y1: seg.y1,
  2591. x2: seg.x2,
  2592. y2: seg.y2,
  2593. r1: seg.r1,
  2594. r2: seg.r2,
  2595. angle: seg.angle,
  2596. largeArcFlag: seg.largeArcFlag,
  2597. sweepFlag: seg.sweepFlag
  2598. };
  2599. }
  2600. var len = changes["d"].length,
  2601. firstseg = changes["d"][0],
  2602. currentpt = remap(firstseg.x,firstseg.y);
  2603. changes["d"][0].x = currentpt.x;
  2604. changes["d"][0].y = currentpt.y;
  2605. for (var i = 1; i < len; ++i) {
  2606. var seg = changes["d"][i];
  2607. var type = seg.type;
  2608. // if absolute or first segment, we want to remap x, y, x1, y1, x2, y2
  2609. // if relative, we want to scalew, scaleh
  2610. if (type % 2 == 0) { // absolute
  2611. var thisx = (seg.x != undefined) ? seg.x : currentpt.x, // for V commands
  2612. thisy = (seg.y != undefined) ? seg.y : currentpt.y, // for H commands
  2613. pt = remap(thisx,thisy),
  2614. pt1 = remap(seg.x1,seg.y1),
  2615. pt2 = remap(seg.x2,seg.y2);
  2616. seg.x = pt.x;
  2617. seg.y = pt.y;
  2618. seg.x1 = pt1.x;
  2619. seg.y1 = pt1.y;
  2620. seg.x2 = pt2.x;
  2621. seg.y2 = pt2.y;
  2622. seg.r1 = scalew(seg.r1),
  2623. seg.r2 = scaleh(seg.r2);
  2624. }
  2625. else { // relative
  2626. seg.x = scalew(seg.x);
  2627. seg.y = scaleh(seg.y);
  2628. seg.x1 = scalew(seg.x1);
  2629. seg.y1 = scaleh(seg.y1);
  2630. seg.x2 = scalew(seg.x2);
  2631. seg.y2 = scaleh(seg.y2);
  2632. seg.r1 = scalew(seg.r1),
  2633. seg.r2 = scaleh(seg.r2);
  2634. }
  2635. // tracks the current position (for H,V commands)
  2636. if (seg.x) currentpt.x = seg.x;
  2637. if (seg.y) currentpt.y = seg.y;
  2638. } // for each segment
  2639. break;
  2640. } // switch on element type to get initial values
  2641. // now we have a set of changes and an applied reduced transform list
  2642. // we apply the changes directly to the DOM
  2643. // TODO: merge this switch with the above one and optimize
  2644. switch (selected.tagName)
  2645. {
  2646. case "foreignObject":
  2647. case "rect":
  2648. case "image":
  2649. changes.x = changes.x-0 + Math.min(0,changes.width);
  2650. changes.y = changes.y-0 + Math.min(0,changes.height);
  2651. changes.width = Math.abs(changes.width);
  2652. changes.height = Math.abs(changes.height);
  2653. assignAttributes(selected, changes, 1000, true);
  2654. break;
  2655. case "use":
  2656. assignAttributes(selected, changes, 1000, true);
  2657. break;
  2658. case "ellipse":
  2659. changes.rx = Math.abs(changes.rx);
  2660. changes.ry = Math.abs(changes.ry);
  2661. case "circle":
  2662. if(changes.r) changes.r = Math.abs(changes.r);
  2663. case "line":
  2664. case "text":
  2665. assignAttributes(selected, changes, 1000, true);
  2666. break;
  2667. case "polyline":
  2668. case "polygon":
  2669. var len = changes["points"].length;
  2670. var pstr = "";
  2671. for (var i = 0; i < len; ++i) {
  2672. var pt = changes["points"][i];
  2673. pstr += pt.x + "," + pt.y + " ";
  2674. }
  2675. selected.setAttribute("points", pstr);
  2676. break;
  2677. case "path":
  2678. var dstr = "";
  2679. var len = changes["d"].length;
  2680. for (var i = 0; i < len; ++i) {
  2681. var seg = changes["d"][i];
  2682. var type = seg.type;
  2683. dstr += pathMap[type];
  2684. switch(type) {
  2685. case 13: // relative horizontal line (h)
  2686. case 12: // absolute horizontal line (H)
  2687. dstr += seg.x + " ";
  2688. break;
  2689. case 15: // relative vertical line (v)
  2690. case 14: // absolute vertical line (V)
  2691. dstr += seg.y + " ";
  2692. break;
  2693. case 3: // relative move (m)
  2694. case 5: // relative line (l)
  2695. case 19: // relative smooth quad (t)
  2696. case 2: // absolute move (M)
  2697. case 4: // absolute line (L)
  2698. case 18: // absolute smooth quad (T)
  2699. dstr += seg.x + "," + seg.y + " ";
  2700. break;
  2701. case 7: // relative cubic (c)
  2702. case 6: // absolute cubic (C)
  2703. dstr += seg.x1 + "," + seg.y1 + " " + seg.x2 + "," + seg.y2 + " " +
  2704. seg.x + "," + seg.y + " ";
  2705. break;
  2706. case 9: // relative quad (q)
  2707. case 8: // absolute quad (Q)
  2708. dstr += seg.x1 + "," + seg.y1 + " " + seg.x + "," + seg.y + " ";
  2709. break;
  2710. case 11: // relative elliptical arc (a)
  2711. case 10: // absolute elliptical arc (A)
  2712. dstr += seg.r1 + "," + seg.r2 + " " + seg.angle + " " + Number(seg.largeArcFlag) +
  2713. " " + Number(seg.sweepFlag) + " " + seg.x + "," + seg.y + " ";
  2714. break;
  2715. case 17: // relative smooth cubic (s)
  2716. case 16: // absolute smooth cubic (S)
  2717. dstr += seg.x2 + "," + seg.y2 + " " + seg.x + "," + seg.y + " ";
  2718. break;
  2719. }
  2720. }
  2721. selected.setAttribute("d", dstr);
  2722. break;
  2723. }
  2724. };
  2725. // Function: recalculateDimensions
  2726. // Decides the course of action based on the element's transform list
  2727. //
  2728. // Parameters:
  2729. // selected - The DOM element to recalculate
  2730. //
  2731. // Returns:
  2732. // Undo command object with the resulting change
  2733. var recalculateDimensions = this.recalculateDimensions = function(selected) {
  2734. if (selected == null) return null;
  2735. var tlist = getTransformList(selected);
  2736. // remove any unnecessary transforms
  2737. if (tlist && tlist.numberOfItems > 0) {
  2738. var k = tlist.numberOfItems;
  2739. while (k--) {
  2740. var xform = tlist.getItem(k);
  2741. if (xform.type == 0) {
  2742. tlist.removeItem(k);
  2743. }
  2744. // remove identity matrices
  2745. else if (xform.type == 1) {
  2746. if (isIdentity(xform.matrix)) {
  2747. tlist.removeItem(k);
  2748. }
  2749. }
  2750. // remove zero-degree rotations
  2751. else if (xform.type == 4) {
  2752. if (xform.angle == 0) {
  2753. tlist.removeItem(k);
  2754. }
  2755. }
  2756. }
  2757. // End here if all it has is a rotation
  2758. if(tlist.numberOfItems == 1 && getRotationAngle(selected)) return null;
  2759. }
  2760. // if this element had no transforms, we are done
  2761. if (!tlist || tlist.numberOfItems == 0) {
  2762. selected.removeAttribute("transform");
  2763. return null;
  2764. }
  2765. // we know we have some transforms, so set up return variable
  2766. var batchCmd = new BatchCommand("Transform");
  2767. // store initial values that will be affected by reducing the transform list
  2768. var changes = {}, initial = null, attrs = [];
  2769. switch (selected.tagName)
  2770. {
  2771. case "line":
  2772. attrs = ["x1", "y1", "x2", "y2"];
  2773. break;
  2774. case "circle":
  2775. attrs = ["cx", "cy", "r"];
  2776. break;
  2777. case "ellipse":
  2778. attrs = ["cx", "cy", "rx", "ry"];
  2779. break;
  2780. case "foreignObject":
  2781. case "rect":
  2782. case "image":
  2783. attrs = ["width", "height", "x", "y"];
  2784. break;
  2785. case "use":
  2786. attrs = ["x", "y"];
  2787. break;
  2788. case "text":
  2789. attrs = ["x", "y"];
  2790. break;
  2791. case "polygon":
  2792. case "polyline":
  2793. initial = {};
  2794. initial["points"] = selected.getAttribute("points");
  2795. var list = selected.points;
  2796. var len = list.numberOfItems;
  2797. changes["points"] = new Array(len);
  2798. for (var i = 0; i < len; ++i) {
  2799. var pt = list.getItem(i);
  2800. changes["points"][i] = {x:pt.x,y:pt.y};
  2801. }
  2802. break;
  2803. case "path":
  2804. initial = {};
  2805. initial["d"] = selected.getAttribute("d");
  2806. changes["d"] = selected.getAttribute("d");
  2807. break;
  2808. } // switch on element type to get initial values
  2809. if(attrs.length) {
  2810. changes = $(selected).attr(attrs);
  2811. $.each(changes, function(attr, val) {
  2812. changes[attr] = convertToNum(attr, val);
  2813. });
  2814. }
  2815. // if we haven't created an initial array in polygon/polyline/path, then
  2816. // make a copy of initial values and include the transform
  2817. if (initial == null) {
  2818. initial = $.extend(true, {}, changes);
  2819. $.each(initial, function(attr, val) {
  2820. initial[attr] = convertToNum(attr, val);
  2821. });
  2822. }
  2823. // save the start transform value too
  2824. initial["transform"] = start_transform ? start_transform : "";
  2825. // if it's a group, we have special processing to flatten transforms
  2826. if (selected.tagName == "g" || selected.tagName == "a") {
  2827. var box = getBBox(selected),
  2828. oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
  2829. newcenter = transformPoint(box.x+box.width/2, box.y+box.height/2,
  2830. transformListToTransform(tlist).matrix),
  2831. m = svgroot.createSVGMatrix();
  2832. // temporarily strip off the rotate and save the old center
  2833. var gangle = getRotationAngle(selected);
  2834. if (gangle) {
  2835. var a = gangle * Math.PI / 180;
  2836. if ( Math.abs(a) > (1.0e-10) ) {
  2837. var s = Math.sin(a)/(1 - Math.cos(a));
  2838. } else {
  2839. // FIXME: This blows up if the angle is exactly 0!
  2840. var s = 2/a;
  2841. }
  2842. for (var i = 0; i < tlist.numberOfItems; ++i) {
  2843. var xform = tlist.getItem(i);
  2844. if (xform.type == 4) {
  2845. // extract old center through mystical arts
  2846. var rm = xform.matrix;
  2847. oldcenter.y = (s*rm.e + rm.f)/2;
  2848. oldcenter.x = (rm.e - s*rm.f)/2;
  2849. tlist.removeItem(i);
  2850. break;
  2851. }
  2852. }
  2853. }
  2854. var tx = 0, ty = 0,
  2855. operation = 0,
  2856. N = tlist.numberOfItems;
  2857. if(N) {
  2858. var first_m = tlist.getItem(0).matrix;
  2859. }
  2860. // first, if it was a scale then the second-last transform will be it
  2861. if (N >= 3 && tlist.getItem(N-2).type == 3 &&
  2862. tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2)
  2863. {
  2864. operation = 3; // scale
  2865. // if the children are unrotated, pass the scale down directly
  2866. // otherwise pass the equivalent matrix() down directly
  2867. var tm = tlist.getItem(N-3).matrix,
  2868. sm = tlist.getItem(N-2).matrix,
  2869. tmn = tlist.getItem(N-1).matrix;
  2870. var children = selected.childNodes;
  2871. var c = children.length;
  2872. while (c--) {
  2873. var child = children.item(c);
  2874. tx = 0;
  2875. ty = 0;
  2876. if (child.nodeType == 1) {
  2877. var childTlist = getTransformList(child);
  2878. // some children might not have a transform (<metadata>, <defs>, etc)
  2879. if (!childTlist) continue;
  2880. var m = transformListToTransform(childTlist).matrix;
  2881. var angle = getRotationAngle(child);
  2882. var old_start_transform = start_transform;
  2883. var childxforms = [];
  2884. start_transform = child.getAttribute("transform");
  2885. if(angle || hasMatrixTransform(childTlist)) {
  2886. var e2t = svgroot.createSVGTransform();
  2887. e2t.setMatrix(matrixMultiply(tm, sm, tmn, m));
  2888. childTlist.clear();
  2889. childTlist.appendItem(e2t);
  2890. childxforms.push(e2t);
  2891. }
  2892. // if not rotated or skewed, push the [T][S][-T] down to the child
  2893. else {
  2894. // update the transform list with translate,scale,translate
  2895. // slide the [T][S][-T] from the front to the back
  2896. // [T][S][-T][M] = [M][T2][S2][-T2]
  2897. // (only bringing [-T] to the right of [M])
  2898. // [T][S][-T][M] = [T][S][M][-T2]
  2899. // [-T2] = [M_inv][-T][M]
  2900. var t2n = matrixMultiply(m.inverse(), tmn, m);
  2901. // [T2] is always negative translation of [-T2]
  2902. var t2 = svgroot.createSVGMatrix();
  2903. t2.e = -t2n.e;
  2904. t2.f = -t2n.f;
  2905. // [T][S][-T][M] = [M][T2][S2][-T2]
  2906. // [S2] = [T2_inv][M_inv][T][S][-T][M][-T2_inv]
  2907. var s2 = matrixMultiply(t2.inverse(), m.inverse(), tm, sm, tmn, m, t2n.inverse());
  2908. var translateOrigin = svgroot.createSVGTransform(),
  2909. scale = svgroot.createSVGTransform(),
  2910. translateBack = svgroot.createSVGTransform();
  2911. translateOrigin.setTranslate(t2n.e, t2n.f);
  2912. scale.setScale(s2.a, s2.d);
  2913. translateBack.setTranslate(t2.e, t2.f);
  2914. childTlist.appendItem(translateBack);
  2915. childTlist.appendItem(scale);
  2916. childTlist.appendItem(translateOrigin);
  2917. childxforms.push(translateBack);
  2918. childxforms.push(scale);
  2919. childxforms.push(translateOrigin);
  2920. logMatrix(translateBack.matrix);
  2921. logMatrix(scale.matrix);
  2922. } // not rotated
  2923. batchCmd.addSubCommand( recalculateDimensions(child) );
  2924. // TODO: If any <use> have this group as a parent and are
  2925. // referencing this child, then we need to impose a reverse
  2926. // scale on it so that when it won't get double-translated
  2927. // var uses = selected.getElementsByTagNameNS(svgns, "use");
  2928. // var href = "#"+child.id;
  2929. // var u = uses.length;
  2930. // while (u--) {
  2931. // var useElem = uses.item(u);
  2932. // if(href == useElem.getAttributeNS(xlinkns, "href")) {
  2933. // var usexlate = svgroot.createSVGTransform();
  2934. // usexlate.setTranslate(-tx,-ty);
  2935. // getTransformList(useElem).insertItemBefore(usexlate,0);
  2936. // batchCmd.addSubCommand( recalculateDimensions(useElem) );
  2937. // }
  2938. // }
  2939. start_transform = old_start_transform;
  2940. } // element
  2941. } // for each child
  2942. // Remove these transforms from group
  2943. tlist.removeItem(N-1);
  2944. tlist.removeItem(N-2);
  2945. tlist.removeItem(N-3);
  2946. }
  2947. else if (N >= 3 && tlist.getItem(N-1).type == 1)
  2948. {
  2949. operation = 3; // scale
  2950. m = transformListToTransform(tlist).matrix;
  2951. var e2t = svgroot.createSVGTransform();
  2952. e2t.setMatrix(m);
  2953. tlist.clear();
  2954. tlist.appendItem(e2t);
  2955. }
  2956. // next, check if the first transform was a translate
  2957. // if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ]
  2958. // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ]
  2959. else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
  2960. tlist.getItem(0).type == 2)
  2961. {
  2962. operation = 2; // translate
  2963. var T_M = transformListToTransform(tlist).matrix;
  2964. tlist.removeItem(0);
  2965. var M_inv = transformListToTransform(tlist).matrix.inverse();
  2966. var M2 = matrixMultiply( M_inv, T_M );
  2967. tx = M2.e;
  2968. ty = M2.f;
  2969. if (tx != 0 || ty != 0) {
  2970. // we pass the translates down to the individual children
  2971. var children = selected.childNodes;
  2972. var c = children.length;
  2973. while (c--) {
  2974. var child = children.item(c);
  2975. if (child.nodeType == 1) {
  2976. var old_start_transform = start_transform;
  2977. start_transform = child.getAttribute("transform");
  2978. var childTlist = getTransformList(child);
  2979. // some children might not have a transform (<metadata>, <defs>, etc)
  2980. if (childTlist) {
  2981. var newxlate = svgroot.createSVGTransform();
  2982. newxlate.setTranslate(tx,ty);
  2983. childTlist.insertItemBefore(newxlate, 0);
  2984. batchCmd.addSubCommand( recalculateDimensions(child) );
  2985. // If any <use> have this group as a parent and are
  2986. // referencing this child, then impose a reverse translate on it
  2987. // so that when it won't get double-translated
  2988. var uses = selected.getElementsByTagNameNS(svgns, "use");
  2989. var href = "#"+child.id;
  2990. var u = uses.length;
  2991. while (u--) {
  2992. var useElem = uses.item(u);
  2993. if(href == useElem.getAttributeNS(xlinkns, "href")) {
  2994. var usexlate = svgroot.createSVGTransform();
  2995. usexlate.setTranslate(-tx,-ty);
  2996. getTransformList(useElem).insertItemBefore(usexlate,0);
  2997. batchCmd.addSubCommand( recalculateDimensions(useElem) );
  2998. }
  2999. }
  3000. start_transform = old_start_transform;
  3001. }
  3002. }
  3003. }
  3004. start_transform = old_start_transform;
  3005. }
  3006. }
  3007. // else, a matrix imposition from a parent group
  3008. // keep pushing it down to the children
  3009. else if (N == 1 && tlist.getItem(0).type == 1 && !gangle) {
  3010. operation = 1;
  3011. var m = tlist.getItem(0).matrix,
  3012. children = selected.childNodes,
  3013. c = children.length;
  3014. while (c--) {
  3015. var child = children.item(c);
  3016. if (child.nodeType == 1) {
  3017. var old_start_transform = start_transform;
  3018. start_transform = child.getAttribute("transform");
  3019. var childTlist = getTransformList(child);
  3020. var em = matrixMultiply(m, transformListToTransform(childTlist).matrix);
  3021. var e2m = svgroot.createSVGTransform();
  3022. e2m.setMatrix(em);
  3023. childTlist.clear();
  3024. childTlist.appendItem(e2m,0);
  3025. batchCmd.addSubCommand( recalculateDimensions(child) );
  3026. start_transform = old_start_transform;
  3027. }
  3028. }
  3029. tlist.clear();
  3030. }
  3031. // else it was just a rotate
  3032. else {
  3033. if (gangle) {
  3034. var newRot = svgroot.createSVGTransform();
  3035. newRot.setRotate(gangle,newcenter.x,newcenter.y);
  3036. tlist.insertItemBefore(newRot, 0);
  3037. }
  3038. if (tlist.numberOfItems == 0) {
  3039. selected.removeAttribute("transform");
  3040. }
  3041. return null;
  3042. }
  3043. // if it was a translate, put back the rotate at the new center
  3044. if (operation == 2) {
  3045. if (gangle) {
  3046. newcenter = {
  3047. x: oldcenter.x + first_m.e,
  3048. y: oldcenter.y + first_m.f
  3049. };
  3050. var newRot = svgroot.createSVGTransform();
  3051. newRot.setRotate(gangle,newcenter.x,newcenter.y);
  3052. tlist.insertItemBefore(newRot, 0);
  3053. }
  3054. }
  3055. // if it was a resize
  3056. else if (operation == 3) {
  3057. var m = transformListToTransform(tlist).matrix;
  3058. var roldt = svgroot.createSVGTransform();
  3059. roldt.setRotate(gangle, oldcenter.x, oldcenter.y);
  3060. var rold = roldt.matrix;
  3061. var rnew = svgroot.createSVGTransform();
  3062. rnew.setRotate(gangle, newcenter.x, newcenter.y);
  3063. var rnew_inv = rnew.matrix.inverse(),
  3064. m_inv = m.inverse(),
  3065. extrat = matrixMultiply(m_inv, rnew_inv, rold, m);
  3066. tx = extrat.e;
  3067. ty = extrat.f;
  3068. if (tx != 0 || ty != 0) {
  3069. // now push this transform down to the children
  3070. // we pass the translates down to the individual children
  3071. var children = selected.childNodes;
  3072. var c = children.length;
  3073. while (c--) {
  3074. var child = children.item(c);
  3075. if (child.nodeType == 1) {
  3076. var old_start_transform = start_transform;
  3077. start_transform = child.getAttribute("transform");
  3078. var childTlist = getTransformList(child);
  3079. var newxlate = svgroot.createSVGTransform();
  3080. newxlate.setTranslate(tx,ty);
  3081. childTlist.insertItemBefore(newxlate, 0);
  3082. batchCmd.addSubCommand( recalculateDimensions(child) );
  3083. start_transform = old_start_transform;
  3084. }
  3085. }
  3086. }
  3087. if (gangle) {
  3088. tlist.insertItemBefore(rnew, 0);
  3089. }
  3090. }
  3091. }
  3092. // else, it's a non-group
  3093. else {
  3094. // FIXME: box might be null for some elements (<metadata> etc), need to handle this
  3095. var box = getBBox(selected);
  3096. if(!box) return null;
  3097. var oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
  3098. newcenter = transformPoint(box.x+box.width/2, box.y+box.height/2,
  3099. transformListToTransform(tlist).matrix),
  3100. m = svgroot.createSVGMatrix(),
  3101. // temporarily strip off the rotate and save the old center
  3102. angle = getRotationAngle(selected);
  3103. if (angle) {
  3104. var a = angle * Math.PI / 180;
  3105. if ( Math.abs(a) > (1.0e-10) ) {
  3106. var s = Math.sin(a)/(1 - Math.cos(a));
  3107. } else {
  3108. // FIXME: This blows up if the angle is exactly 0!
  3109. var s = 2/a;
  3110. }
  3111. for (var i = 0; i < tlist.numberOfItems; ++i) {
  3112. var xform = tlist.getItem(i);
  3113. if (xform.type == 4) {
  3114. // extract old center through mystical arts
  3115. var rm = xform.matrix;
  3116. oldcenter.y = (s*rm.e + rm.f)/2;
  3117. oldcenter.x = (rm.e - s*rm.f)/2;
  3118. tlist.removeItem(i);
  3119. break;
  3120. }
  3121. }
  3122. }
  3123. // 2 = translate, 3 = scale, 4 = rotate, 1 = matrix imposition
  3124. var operation = 0;
  3125. var N = tlist.numberOfItems;
  3126. // Check if it has a gradient with userSpaceOnUse, in which case
  3127. // adjust it by recalculating the matrix transform.
  3128. // TODO: Make this work in Webkit using SVGEditTransformList
  3129. if(!isWebkit) {
  3130. var fill = selected.getAttribute('fill');
  3131. if(fill && fill.indexOf('url(') === 0) {
  3132. var grad = getElem(getUrlFromAttr(fill).substr(1));
  3133. if(grad.getAttribute('gradientUnits') === 'userSpaceOnUse') {
  3134. //Update the userSpaceOnUse element
  3135. var grad = $(grad);
  3136. m = transformListToTransform(tlist).matrix;
  3137. var gtlist = getTransformList(grad[0]);
  3138. var gmatrix = transformListToTransform(gtlist).matrix;
  3139. m = matrixMultiply(m, gmatrix);
  3140. var m_str = "matrix(" + [m.a,m.b,m.c,m.d,m.e,m.f].join(",") + ")";
  3141. grad.attr('gradientTransform', m_str);
  3142. }
  3143. }
  3144. }
  3145. // first, if it was a scale of a non-skewed element, then the second-last
  3146. // transform will be the [S]
  3147. // if we had [M][T][S][T] we want to extract the matrix equivalent of
  3148. // [T][S][T] and push it down to the element
  3149. if (N >= 3 && tlist.getItem(N-2).type == 3 &&
  3150. tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2 &&
  3151. selected.nodeName != "use")
  3152. {
  3153. operation = 3; // scale
  3154. m = transformListToTransform(tlist,N-3,N-1).matrix;
  3155. tlist.removeItem(N-1);
  3156. tlist.removeItem(N-2);
  3157. tlist.removeItem(N-3);
  3158. } // if we had [T][S][-T][M], then this was a skewed element being resized
  3159. // Thus, we simply combine it all into one matrix
  3160. else if(N == 4 && tlist.getItem(N-1).type == 1) {
  3161. operation = 3; // scale
  3162. m = transformListToTransform(tlist).matrix;
  3163. var e2t = svgroot.createSVGTransform();
  3164. e2t.setMatrix(m);
  3165. tlist.clear();
  3166. tlist.appendItem(e2t);
  3167. // reset the matrix so that the element is not re-mapped
  3168. m = svgroot.createSVGMatrix();
  3169. } // if we had [R][T][S][-T][M], then this was a rotated matrix-element
  3170. // if we had [T1][M] we want to transform this into [M][T2]
  3171. // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2]
  3172. // down to the element
  3173. else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
  3174. tlist.getItem(0).type == 2)
  3175. {
  3176. operation = 2; // translate
  3177. var oldxlate = tlist.getItem(0).matrix,
  3178. meq = transformListToTransform(tlist,1).matrix,
  3179. meq_inv = meq.inverse();
  3180. m = matrixMultiply( meq_inv, oldxlate, meq );
  3181. tlist.removeItem(0);
  3182. }
  3183. // else if this child now has a matrix imposition (from a parent group)
  3184. // we might be able to simplify
  3185. else if (N == 1 && tlist.getItem(0).type == 1 && !angle) {
  3186. // Remap all point-based elements
  3187. m = transformListToTransform(tlist).matrix;
  3188. switch (selected.tagName) {
  3189. case 'line':
  3190. changes = $(selected).attr(["x1","y1","x2","y2"]);
  3191. case 'polyline':
  3192. case 'polygon':
  3193. changes.points = selected.getAttribute("points");
  3194. if(changes.points) {
  3195. var list = selected.points;
  3196. var len = list.numberOfItems;
  3197. changes.points = new Array(len);
  3198. for (var i = 0; i < len; ++i) {
  3199. var pt = list.getItem(i);
  3200. changes.points[i] = {x:pt.x,y:pt.y};
  3201. }
  3202. }
  3203. case 'path':
  3204. changes.d = selected.getAttribute("d");
  3205. operation = 1;
  3206. tlist.clear();
  3207. break;
  3208. default:
  3209. break;
  3210. }
  3211. }
  3212. // if it was a rotation, put the rotate back and return without a command
  3213. // (this function has zero work to do for a rotate())
  3214. else {
  3215. operation = 4; // rotation
  3216. if (angle) {
  3217. var newRot = svgroot.createSVGTransform();
  3218. newRot.setRotate(angle,newcenter.x,newcenter.y);
  3219. tlist.insertItemBefore(newRot, 0);
  3220. }
  3221. if (tlist.numberOfItems == 0) {
  3222. selected.removeAttribute("transform");
  3223. }
  3224. return null;
  3225. }
  3226. // if it was a translate or resize, we need to remap the element and absorb the xform
  3227. if (operation == 1 || operation == 2 || operation == 3) {
  3228. remapElement(selected,changes,m);
  3229. } // if we are remapping
  3230. // if it was a translate, put back the rotate at the new center
  3231. if (operation == 2) {
  3232. if (angle) {
  3233. newcenter = {
  3234. x: oldcenter.x + m.e,
  3235. y: oldcenter.y + m.f
  3236. };
  3237. var newRot = svgroot.createSVGTransform();
  3238. newRot.setRotate(angle, newcenter.x, newcenter.y);
  3239. tlist.insertItemBefore(newRot, 0);
  3240. }
  3241. }
  3242. // [Rold][M][T][S][-T] became [Rold][M]
  3243. // we want it to be [Rnew][M][Tr] where Tr is the
  3244. // translation required to re-center it
  3245. // Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M]
  3246. else if (operation == 3) {
  3247. var m = transformListToTransform(tlist).matrix;
  3248. var roldt = svgroot.createSVGTransform();
  3249. roldt.setRotate(angle, oldcenter.x, oldcenter.y);
  3250. var rold = roldt.matrix;
  3251. var rnew = svgroot.createSVGTransform();
  3252. rnew.setRotate(angle, newcenter.x, newcenter.y);
  3253. var rnew_inv = rnew.matrix.inverse();
  3254. var m_inv = m.inverse();
  3255. var extrat = matrixMultiply(m_inv, rnew_inv, rold, m);
  3256. remapElement(selected,changes,extrat);
  3257. if (angle) {
  3258. tlist.insertItemBefore(rnew,0);
  3259. }
  3260. }
  3261. } // a non-group
  3262. // if the transform list has been emptied, remove it
  3263. if (tlist.numberOfItems == 0) {
  3264. selected.removeAttribute("transform");
  3265. }
  3266. batchCmd.addSubCommand(new ChangeElementCommand(selected, initial));
  3267. return batchCmd;
  3268. };
  3269. // Root Current Transformation Matrix in user units
  3270. var root_sctm = null;
  3271. // Function: transformPoint
  3272. // A (hopefully) quicker function to transform a point by a matrix
  3273. // (this function avoids any DOM calls and just does the math)
  3274. //
  3275. // Parameters:
  3276. // x - Float representing the x coordinate
  3277. // y - Float representing the y coordinate
  3278. // m - Matrix object to transform the point with
  3279. // Returns a x,y object representing the transformed point
  3280. var transformPoint = function(x, y, m) {
  3281. return { x: m.a * x + m.c * y + m.e, y: m.b * x + m.d * y + m.f};
  3282. };
  3283. // Function: isIdentity
  3284. // Helper function to check if the matrix performs no actual transform
  3285. // (i.e. exists for identity purposes)
  3286. //
  3287. // Parameters:
  3288. // m - The matrix object to check
  3289. //
  3290. // Returns:
  3291. // Boolean indicating whether or not the matrix is 1,0,0,1,0,0
  3292. var isIdentity = function(m) {
  3293. return (m.a == 1 && m.b == 0 && m.c == 0 && m.d == 1 && m.e == 0 && m.f == 0);
  3294. }
  3295. // matrixMultiply() is provided because WebKit didn't implement multiply() correctly
  3296. // on the SVGMatrix interface. See https://bugs.webkit.org/show_bug.cgi?id=16062
  3297. // Function: matrixMultiply
  3298. // This function tries to return a SVGMatrix that is the multiplication m1*m2.
  3299. // We also round to zero when it's near zero
  3300. //
  3301. // Parameters:
  3302. // >= 2 Matrix objects to multiply
  3303. //
  3304. // Returns:
  3305. // The matrix object resulting from the calculation
  3306. var matrixMultiply = this.matrixMultiply = function() {
  3307. var NEAR_ZERO = 1e-14,
  3308. multi2 = function(m1, m2) {
  3309. var m = svgroot.createSVGMatrix();
  3310. m.a = m1.a*m2.a + m1.c*m2.b;
  3311. m.b = m1.b*m2.a + m1.d*m2.b,
  3312. m.c = m1.a*m2.c + m1.c*m2.d,
  3313. m.d = m1.b*m2.c + m1.d*m2.d,
  3314. m.e = m1.a*m2.e + m1.c*m2.f + m1.e,
  3315. m.f = m1.b*m2.e + m1.d*m2.f + m1.f;
  3316. return m;
  3317. },
  3318. args = arguments, i = args.length, m = args[i-1];
  3319. while(i-- > 1) {
  3320. var m1 = args[i-1];
  3321. m = multi2(m1, m);
  3322. }
  3323. if (Math.abs(m.a) < NEAR_ZERO) m.a = 0;
  3324. if (Math.abs(m.b) < NEAR_ZERO) m.b = 0;
  3325. if (Math.abs(m.c) < NEAR_ZERO) m.c = 0;
  3326. if (Math.abs(m.d) < NEAR_ZERO) m.d = 0;
  3327. if (Math.abs(m.e) < NEAR_ZERO) m.e = 0;
  3328. if (Math.abs(m.f) < NEAR_ZERO) m.f = 0;
  3329. return m;
  3330. }
  3331. // Function: transformListToTransform
  3332. // This returns a single matrix Transform for a given Transform List
  3333. // (this is the equivalent of SVGTransformList.consolidate() but unlike
  3334. // that method, this one does not modify the actual SVGTransformList)
  3335. // This function is very liberal with its min,max arguments
  3336. //
  3337. // Parameters:
  3338. // tlist - The transformlist object
  3339. // min - Optional integer indicating start transform position
  3340. // max - Optional integer indicating end transform position
  3341. //
  3342. // Returns:
  3343. // A single matrix transform object
  3344. var transformListToTransform = this.transformListToTransform = function(tlist, min, max) {
  3345. var min = min == undefined ? 0 : min;
  3346. var max = max == undefined ? (tlist.numberOfItems-1) : max;
  3347. min = parseInt(min);
  3348. max = parseInt(max);
  3349. if (min > max) { var temp = max; max = min; min = temp; }
  3350. var m = svgroot.createSVGMatrix();
  3351. for (var i = min; i <= max; ++i) {
  3352. // if our indices are out of range, just use a harmless identity matrix
  3353. var mtom = (i >= 0 && i < tlist.numberOfItems ?
  3354. tlist.getItem(i).matrix :
  3355. svgroot.createSVGMatrix());
  3356. m = matrixMultiply(m, mtom);
  3357. }
  3358. return svgroot.createSVGTransformFromMatrix(m);
  3359. };
  3360. // Function: hasMatrixTransform
  3361. // See if the given transformlist includes a non-indentity matrix transform
  3362. //
  3363. // Parameters:
  3364. // tlist - The transformlist to check
  3365. //
  3366. // Returns:
  3367. // Boolean on whether or not a matrix transform was found
  3368. var hasMatrixTransform = this.hasMatrixTransform = function(tlist) {
  3369. if(!tlist) return false;
  3370. var num = tlist.numberOfItems;
  3371. while (num--) {
  3372. var xform = tlist.getItem(num);
  3373. if (xform.type == 1 && !isIdentity(xform.matrix)) return true;
  3374. }
  3375. return false;
  3376. }
  3377. // Function: getMatrix
  3378. // Get the matrix object for a given element
  3379. //
  3380. // Parameters:
  3381. // elem - The DOM element to check
  3382. //
  3383. // Returns:
  3384. // The matrix object associated with the element's transformlist
  3385. var getMatrix = function(elem) {
  3386. var tlist = getTransformList(elem);
  3387. return transformListToTransform(tlist).matrix;
  3388. }
  3389. // Function: transformBox
  3390. // Transforms a rectangle based on the given matrix
  3391. //
  3392. // Parameters:
  3393. // l - Float with the box's left coordinate
  3394. // t - Float with the box's top coordinate
  3395. // w - Float with the box width
  3396. // h - Float with the box height
  3397. // m - Matrix object to transform the box by
  3398. //
  3399. // Returns:
  3400. // An object with the following values:
  3401. // * tl - The top left coordinate (x,y object)
  3402. // * tr - The top right coordinate (x,y object)
  3403. // * bl - The bottom left coordinate (x,y object)
  3404. // * br - The bottom right coordinate (x,y object)
  3405. // * aabox - Object with the following values:
  3406. // * Float with the axis-aligned x coordinate
  3407. // * Float with the axis-aligned y coordinate
  3408. // * Float with the axis-aligned width coordinate
  3409. // * Float with the axis-aligned height coordinate
  3410. var transformBox = this.transformBox = function(l, t, w, h, m) {
  3411. var topleft = {x:l,y:t},
  3412. topright = {x:(l+w),y:t},
  3413. botright = {x:(l+w),y:(t+h)},
  3414. botleft = {x:l,y:(t+h)};
  3415. topleft = transformPoint( topleft.x, topleft.y, m );
  3416. var minx = topleft.x,
  3417. maxx = topleft.x,
  3418. miny = topleft.y,
  3419. maxy = topleft.y;
  3420. topright = transformPoint( topright.x, topright.y, m );
  3421. minx = Math.min(minx, topright.x);
  3422. maxx = Math.max(maxx, topright.x);
  3423. miny = Math.min(miny, topright.y);
  3424. maxy = Math.max(maxy, topright.y);
  3425. botleft = transformPoint( botleft.x, botleft.y, m);
  3426. minx = Math.min(minx, botleft.x);
  3427. maxx = Math.max(maxx, botleft.x);
  3428. miny = Math.min(miny, botleft.y);
  3429. maxy = Math.max(maxy, botleft.y);
  3430. botright = transformPoint( botright.x, botright.y, m );
  3431. minx = Math.min(minx, botright.x);
  3432. maxx = Math.max(maxx, botright.x);
  3433. miny = Math.min(miny, botright.y);
  3434. maxy = Math.max(maxy, botright.y);
  3435. return {tl:topleft, tr:topright, bl:botleft, br:botright,
  3436. aabox: {x:minx, y:miny, width:(maxx-minx), height:(maxy-miny)} };
  3437. };
  3438. // Group: Selection
  3439. // Function: clearSelection
  3440. // Clears the selection. The 'selected' handler is then called.
  3441. // Parameters:
  3442. // noCall - Optional boolean that when true does not call the "selected" handler
  3443. var clearSelection = this.clearSelection = function(noCall) {
  3444. if (selectedElements[0] != null) {
  3445. var len = selectedElements.length;
  3446. for (var i = 0; i < len; ++i) {
  3447. var elem = selectedElements[i];
  3448. if (elem == null) break;
  3449. selectorManager.releaseSelector(elem);
  3450. selectedElements[i] = null;
  3451. }
  3452. selectedBBoxes[0] = null;
  3453. }
  3454. if(!noCall) call("selected", selectedElements);
  3455. };
  3456. // TODO: do we need to worry about selectedBBoxes here?
  3457. // Function: addToSelection
  3458. // Adds a list of elements to the selection. The 'selected' handler is then called.
  3459. //
  3460. // Parameters:
  3461. // elemsToAdd - an array of DOM elements to add to the selection
  3462. // showGrips - a boolean flag indicating whether the resize grips should be shown
  3463. var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) {
  3464. if (elemsToAdd.length == 0) { return; }
  3465. // find the first null in our selectedElements array
  3466. var j = 0;
  3467. while (j < selectedElements.length) {
  3468. if (selectedElements[j] == null) {
  3469. break;
  3470. }
  3471. ++j;
  3472. }
  3473. // now add each element consecutively
  3474. var i = elemsToAdd.length;
  3475. while (i--) {
  3476. var elem = elemsToAdd[i];
  3477. if (!elem || !getBBox(elem)) continue;
  3478. // if it's not already there, add it
  3479. if (selectedElements.indexOf(elem) == -1) {
  3480. selectedElements[j] = elem;
  3481. // only the first selectedBBoxes element is ever used in the codebase these days
  3482. if (j == 0) selectedBBoxes[j] = getBBox(elem);
  3483. j++;
  3484. var sel = selectorManager.requestSelector(elem);
  3485. if (selectedElements.length > 1) {
  3486. sel.showGrips(false);
  3487. }
  3488. }
  3489. }
  3490. if(selectedElements[0] && selectedElements.length === 1 && selectedElements[0].tagName == 'a') {
  3491. // Make "a" element's child be the selected element
  3492. selectedElements[0] = selectedElements[0].firstChild;
  3493. }
  3494. call("selected", selectedElements);
  3495. if (showGrips || selectedElements.length == 1) {
  3496. selectorManager.requestSelector(selectedElements[0]).showGrips(true);
  3497. }
  3498. else {
  3499. selectorManager.requestSelector(selectedElements[0]).showGrips(false);
  3500. }
  3501. // make sure the elements are in the correct order
  3502. // See: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition
  3503. selectedElements.sort(function(a,b) {
  3504. if(a && b && a.compareDocumentPosition) {
  3505. return 3 - (b.compareDocumentPosition(a) & 6);
  3506. } else if(a == null) {
  3507. return 1;
  3508. }
  3509. });
  3510. // Make sure first elements are not null
  3511. while(selectedElements[0] == null) selectedElements.shift(0);
  3512. };
  3513. // TODO: could use slice here to make this faster?
  3514. // TODO: should the 'selected' handler
  3515. // Function: removeFromSelection
  3516. // Removes elements from the selection.
  3517. //
  3518. // Parameters:
  3519. // elemsToRemove - an array of elements to remove from selection
  3520. var removeFromSelection = this.removeFromSelection = function(elemsToRemove) {
  3521. if (selectedElements[0] == null) { return; }
  3522. if (elemsToRemove.length == 0) { return; }
  3523. // find every element and remove it from our array copy
  3524. var newSelectedItems = new Array(selectedElements.length),
  3525. newSelectedBBoxes = new Array(selectedBBoxes.length),
  3526. j = 0,
  3527. len = selectedElements.length;
  3528. for (var i = 0; i < len; ++i) {
  3529. var elem = selectedElements[i];
  3530. if (elem) {
  3531. // keep the item
  3532. if (elemsToRemove.indexOf(elem) == -1) {
  3533. newSelectedItems[j] = elem;
  3534. if (j==0) newSelectedBBoxes[j] = selectedBBoxes[i];
  3535. j++;
  3536. }
  3537. else { // remove the item and its selector
  3538. selectorManager.releaseSelector(elem);
  3539. }
  3540. }
  3541. }
  3542. // the copy becomes the master now
  3543. selectedElements = newSelectedItems;
  3544. selectedBBoxes = newSelectedBBoxes;
  3545. };
  3546. // Function: selectAllInCurrentLayer
  3547. // Clears the selection, then adds all elements in the current layer to the selection.
  3548. // This function then fires the selected event.
  3549. this.selectAllInCurrentLayer = function() {
  3550. if (current_layer) {
  3551. clearSelection();
  3552. addToSelection($(current_layer).children());
  3553. current_mode = "select";
  3554. call("selected", selectedElements);
  3555. }
  3556. };
  3557. // Function: smoothControlPoints
  3558. // Takes three points and creates a smoother line based on them
  3559. //
  3560. // Parameters:
  3561. // ct1 - Object with x and y values (first control point)
  3562. // ct2 - Object with x and y values (second control point)
  3563. // pt - Object with x and y values (third point)
  3564. //
  3565. // Returns:
  3566. // Array of two "smoothed" point objects
  3567. var smoothControlPoints = this.smoothControlPoints = function(ct1, ct2, pt) {
  3568. // each point must not be the origin
  3569. var x1 = ct1.x - pt.x,
  3570. y1 = ct1.y - pt.y,
  3571. x2 = ct2.x - pt.x,
  3572. y2 = ct2.y - pt.y;
  3573. if ( (x1 != 0 || y1 != 0) && (x2 != 0 || y2 != 0) ) {
  3574. var anglea = Math.atan2(y1,x1),
  3575. angleb = Math.atan2(y2,x2),
  3576. r1 = Math.sqrt(x1*x1+y1*y1),
  3577. r2 = Math.sqrt(x2*x2+y2*y2),
  3578. nct1 = svgroot.createSVGPoint(),
  3579. nct2 = svgroot.createSVGPoint();
  3580. if (anglea < 0) { anglea += 2*Math.PI; }
  3581. if (angleb < 0) { angleb += 2*Math.PI; }
  3582. var angleBetween = Math.abs(anglea - angleb),
  3583. angleDiff = Math.abs(Math.PI - angleBetween)/2;
  3584. var new_anglea, new_angleb;
  3585. if (anglea - angleb > 0) {
  3586. new_anglea = angleBetween < Math.PI ? (anglea + angleDiff) : (anglea - angleDiff);
  3587. new_angleb = angleBetween < Math.PI ? (angleb - angleDiff) : (angleb + angleDiff);
  3588. }
  3589. else {
  3590. new_anglea = angleBetween < Math.PI ? (anglea - angleDiff) : (anglea + angleDiff);
  3591. new_angleb = angleBetween < Math.PI ? (angleb + angleDiff) : (angleb - angleDiff);
  3592. }
  3593. // rotate the points
  3594. nct1.x = r1 * Math.cos(new_anglea) + pt.x;
  3595. nct1.y = r1 * Math.sin(new_anglea) + pt.y;
  3596. nct2.x = r2 * Math.cos(new_angleb) + pt.x;
  3597. nct2.y = r2 * Math.sin(new_angleb) + pt.y;
  3598. return [nct1, nct2];
  3599. }
  3600. return undefined;
  3601. };
  3602. // Function: getMouseTarget
  3603. // Gets the desired element from a mouse event
  3604. //
  3605. // Parameters:
  3606. // evt - Event object from the mouse event
  3607. //
  3608. // Returns:
  3609. // DOM element we want
  3610. var getMouseTarget = this.getMouseTarget = function(evt) {
  3611. if (evt == null) {
  3612. return null;
  3613. }
  3614. var mouse_target = evt.target;
  3615. // if it was a <use>, Opera and WebKit return the SVGElementInstance
  3616. if (mouse_target.correspondingUseElement)
  3617. mouse_target = mouse_target.correspondingUseElement;
  3618. // for foreign content, go up until we find the foreignObject
  3619. // WebKit browsers set the mouse target to the svgcanvas div
  3620. if ($.inArray(mouse_target.namespaceURI, [mathns, htmlns]) != -1 &&
  3621. mouse_target.id != "svgcanvas")
  3622. {
  3623. while (mouse_target.nodeName != "foreignObject") {
  3624. mouse_target = mouse_target.parentNode;
  3625. }
  3626. }
  3627. // go up until we hit a child of a layer
  3628. while (mouse_target.parentNode.parentNode.tagName == "g") {
  3629. mouse_target = mouse_target.parentNode;
  3630. }
  3631. // Webkit bubbles the mouse event all the way up to the div, so we
  3632. // set the mouse_target to the svgroot like the other browsers
  3633. if (mouse_target.nodeName.toLowerCase() == "div") {
  3634. mouse_target = svgroot;
  3635. }
  3636. return mouse_target;
  3637. };
  3638. // Mouse events
  3639. (function() {
  3640. var d_attr = null,
  3641. start_x = null,
  3642. start_y = null,
  3643. init_bbox = {},
  3644. freehand = {
  3645. minx: null,
  3646. miny: null,
  3647. maxx: null,
  3648. maxy: null
  3649. };
  3650. // - when we are in a create mode, the element is added to the canvas
  3651. // but the action is not recorded until mousing up
  3652. // - when we are in select mode, select the element, remember the position
  3653. // and do nothing else
  3654. var mouseDown = function(evt)
  3655. {
  3656. if(evt.button === 1 || canvas.spaceKey) return;
  3657. root_sctm = svgcontent.getScreenCTM().inverse();
  3658. var pt = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  3659. mouse_x = pt.x * current_zoom,
  3660. mouse_y = pt.y * current_zoom;
  3661. evt.preventDefault();
  3662. // This would seem to be unnecessary...
  3663. // if($.inArray(current_mode, ['select', 'resize']) == -1) {
  3664. // setGradient();
  3665. // }
  3666. var x = mouse_x / current_zoom,
  3667. y = mouse_y / current_zoom,
  3668. mouse_target = getMouseTarget(evt);
  3669. start_x = x;
  3670. start_y = y;
  3671. // if it is a selector grip, then it must be a single element selected,
  3672. // set the mouse_target to that and update the mode to rotate/resize
  3673. if (mouse_target.parentNode == selectorManager.selectorParentGroup && selectedElements[0] != null) {
  3674. var gripid = evt.target.id,
  3675. griptype = gripid.substr(0,20);
  3676. // rotating
  3677. if (griptype == "selectorGrip_rotate_") {
  3678. current_mode = "rotate";
  3679. }
  3680. // resizing
  3681. else if(griptype == "selectorGrip_resize_") {
  3682. current_mode = "resize";
  3683. current_resize_mode = gripid.substr(20,gripid.indexOf("_",20)-20);
  3684. }
  3685. mouse_target = selectedElements[0];
  3686. }
  3687. start_transform = mouse_target.getAttribute("transform");
  3688. var tlist = getTransformList(mouse_target);
  3689. switch (current_mode) {
  3690. case "select":
  3691. started = true;
  3692. current_resize_mode = "none";
  3693. if (mouse_target != svgroot) {
  3694. // if this element is not yet selected, clear selection and select it
  3695. if (selectedElements.indexOf(mouse_target) == -1) {
  3696. // only clear selection if shift is not pressed (otherwise, add
  3697. // element to selection)
  3698. if (!evt.shiftKey) {
  3699. // No need to do the call here as it will be done on addToSelection
  3700. clearSelection(true);
  3701. }
  3702. addToSelection([mouse_target]);
  3703. justSelected = mouse_target;
  3704. pathActions.clear();
  3705. }
  3706. // else if it's a path, go into pathedit mode in mouseup
  3707. // insert a dummy transform so if the element(s) are moved it will have
  3708. // a transform to use for its translate
  3709. for (var i = 0; i < selectedElements.length; ++i) {
  3710. if(selectedElements[i] == null) continue;
  3711. var slist = getTransformList(selectedElements[i]);
  3712. slist.insertItemBefore(svgroot.createSVGTransform(), 0);
  3713. }
  3714. }
  3715. else {
  3716. clearSelection();
  3717. current_mode = "multiselect";
  3718. if (rubberBox == null) {
  3719. rubberBox = selectorManager.getRubberBandBox();
  3720. }
  3721. start_x *= current_zoom;
  3722. start_y *= current_zoom;
  3723. assignAttributes(rubberBox, {
  3724. 'x': start_x,
  3725. 'y': start_y,
  3726. 'width': 0,
  3727. 'height': 0,
  3728. 'display': 'inline'
  3729. }, 100);
  3730. }
  3731. break;
  3732. case "zoom":
  3733. started = true;
  3734. start_x = x;
  3735. start_y = y;
  3736. if (rubberBox == null) {
  3737. rubberBox = selectorManager.getRubberBandBox();
  3738. }
  3739. assignAttributes(rubberBox, {
  3740. 'x': start_x * current_zoom,
  3741. 'y': start_y * current_zoom,
  3742. 'width': 0,
  3743. 'height': 0,
  3744. 'display': 'inline'
  3745. }, 100);
  3746. break;
  3747. case "resize":
  3748. started = true;
  3749. start_x = x;
  3750. start_y = y;
  3751. // Getting the BBox from the selection box, since we know we
  3752. // want to orient around it
  3753. init_bbox = getBBox($('#selectedBox0')[0]);
  3754. $.each(init_bbox, function(key, val) {
  3755. init_bbox[key] = val/current_zoom;
  3756. });
  3757. // append three dummy transforms to the tlist so that
  3758. // we can translate,scale,translate in mousemove
  3759. var pos = getRotationAngle(mouse_target)?1:0;
  3760. if(hasMatrixTransform(tlist)) {
  3761. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  3762. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  3763. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  3764. } else {
  3765. tlist.appendItem(svgroot.createSVGTransform());
  3766. tlist.appendItem(svgroot.createSVGTransform());
  3767. tlist.appendItem(svgroot.createSVGTransform());
  3768. }
  3769. break;
  3770. case "fhellipse":
  3771. case "fhrect":
  3772. case "fhpath":
  3773. started = true;
  3774. start_x = x;
  3775. start_y = y;
  3776. d_attr = x + "," + y + " ";
  3777. var stroke_w = cur_shape.stroke_width == 0?1:cur_shape.stroke_width;
  3778. addSvgElementFromJson({
  3779. "element": "polyline",
  3780. "curStyles": true,
  3781. "attr": {
  3782. "points": d_attr,
  3783. "id": getNextId(),
  3784. "fill": "none",
  3785. "opacity": cur_shape.opacity / 2,
  3786. "stroke-linecap": "round",
  3787. "style": "pointer-events:none"
  3788. }
  3789. });
  3790. freehand.minx = x;
  3791. freehand.maxx = x;
  3792. freehand.miny = y;
  3793. freehand.maxy = y;
  3794. break;
  3795. case "image":
  3796. started = true;
  3797. start_x = x;
  3798. start_y = y;
  3799. var newImage = addSvgElementFromJson({
  3800. "element": "image",
  3801. "attr": {
  3802. "x": x,
  3803. "y": y,
  3804. "width": 0,
  3805. "height": 0,
  3806. "id": getNextId(),
  3807. "opacity": cur_shape.opacity / 2,
  3808. "style": "pointer-events:inherit"
  3809. }
  3810. });
  3811. newImage.setAttributeNS(xlinkns, "xlink:href", last_good_img_url);
  3812. preventClickDefault(newImage);
  3813. break;
  3814. case "square":
  3815. // FIXME: once we create the rect, we lose information that this was a square
  3816. // (for resizing purposes this could be important)
  3817. case "rect":
  3818. started = true;
  3819. start_x = x;
  3820. start_y = y;
  3821. addSvgElementFromJson({
  3822. "element": "rect",
  3823. "curStyles": true,
  3824. "attr": {
  3825. "x": x,
  3826. "y": y,
  3827. "width": 0,
  3828. "height": 0,
  3829. "id": getNextId(),
  3830. "opacity": cur_shape.opacity / 2
  3831. }
  3832. });
  3833. break;
  3834. case "line":
  3835. started = true;
  3836. var stroke_w = cur_shape.stroke_width == 0?1:cur_shape.stroke_width;
  3837. addSvgElementFromJson({
  3838. "element": "line",
  3839. "curStyles": true,
  3840. "attr": {
  3841. "x1": x,
  3842. "y1": y,
  3843. "x2": x,
  3844. "y2": y,
  3845. "id": getNextId(),
  3846. "stroke": cur_shape.stroke,
  3847. "stroke-width": stroke_w,
  3848. "stroke-dasharray": cur_shape.stroke_dasharray,
  3849. "stroke-linejoin": cur_shape.stroke_linejoin,
  3850. "stroke-linecap": cur_shape.stroke_linecap,
  3851. "stroke-opacity": cur_shape.stroke_opacity,
  3852. "fill": "none",
  3853. "opacity": cur_shape.opacity / 2,
  3854. "style": "pointer-events:none"
  3855. }
  3856. });
  3857. break;
  3858. case "circle":
  3859. started = true;
  3860. addSvgElementFromJson({
  3861. "element": "circle",
  3862. "curStyles": true,
  3863. "attr": {
  3864. "cx": x,
  3865. "cy": y,
  3866. "r": 0,
  3867. "id": getNextId(),
  3868. "opacity": cur_shape.opacity / 2
  3869. }
  3870. });
  3871. break;
  3872. case "ellipse":
  3873. started = true;
  3874. addSvgElementFromJson({
  3875. "element": "ellipse",
  3876. "curStyles": true,
  3877. "attr": {
  3878. "cx": x,
  3879. "cy": y,
  3880. "rx": 0,
  3881. "ry": 0,
  3882. "id": getNextId(),
  3883. "opacity": cur_shape.opacity / 2
  3884. }
  3885. });
  3886. break;
  3887. case "text":
  3888. started = true;
  3889. var newText = addSvgElementFromJson({
  3890. "element": "text",
  3891. "curStyles": true,
  3892. "attr": {
  3893. "x": x,
  3894. "y": y,
  3895. "id": getNextId(),
  3896. "fill": cur_text.fill,
  3897. "stroke-width": cur_text.stroke_width,
  3898. "font-size": cur_text.font_size,
  3899. "font-family": cur_text.font_family,
  3900. "text-anchor": "middle",
  3901. "xml:space": "preserve"
  3902. }
  3903. });
  3904. // newText.textContent = "text";
  3905. break;
  3906. case "path":
  3907. // Fall through
  3908. case "pathedit":
  3909. start_x *= current_zoom;
  3910. start_y *= current_zoom;
  3911. pathActions.mouseDown(evt, mouse_target, start_x, start_y);
  3912. started = true;
  3913. break;
  3914. case "textedit":
  3915. start_x *= current_zoom;
  3916. start_y *= current_zoom;
  3917. textActions.mouseDown(evt, mouse_target, start_x, start_y);
  3918. started = true;
  3919. break;
  3920. case "rotate":
  3921. started = true;
  3922. // we are starting an undoable change (a drag-rotation)
  3923. canvas.beginUndoableChange("transform", selectedElements);
  3924. break;
  3925. default:
  3926. // This could occur in an extension
  3927. break;
  3928. }
  3929. var ext_result = runExtensions("mouseDown", {
  3930. event: evt,
  3931. start_x: start_x,
  3932. start_y: start_y,
  3933. selectedElements: selectedElements
  3934. }, true);
  3935. $.each(ext_result, function(i, r) {
  3936. if(r && r.started) {
  3937. started = true;
  3938. }
  3939. });
  3940. };
  3941. // in this function we do not record any state changes yet (but we do update
  3942. // any elements that are still being created, moved or resized on the canvas)
  3943. // TODO: svgcanvas should just retain a reference to the image being dragged instead
  3944. // of the getId() and getElementById() funkiness - this will help us customize the ids
  3945. // a little bit for squares and paths
  3946. var mouseMove = function(evt)
  3947. {
  3948. if (!started) return;
  3949. if(evt.button === 1 || canvas.spaceKey) return;
  3950. var selected = selectedElements[0],
  3951. pt = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  3952. mouse_x = pt.x * current_zoom,
  3953. mouse_y = pt.y * current_zoom,
  3954. shape = getElem(getId());
  3955. x = mouse_x / current_zoom;
  3956. y = mouse_y / current_zoom;
  3957. evt.preventDefault();
  3958. switch (current_mode)
  3959. {
  3960. case "select":
  3961. // we temporarily use a translate on the element(s) being dragged
  3962. // this transform is removed upon mousing up and the element is
  3963. // relocated to the new location
  3964. if (selectedElements[0] != null) {
  3965. var dx = x - start_x;
  3966. var dy = y - start_y;
  3967. if(evt.shiftKey) { var xya = Utils.snapToAngle(start_x,start_y,x,y); x=xya.x; y=xya.y; }
  3968. if (dx != 0 || dy != 0) {
  3969. var len = selectedElements.length;
  3970. for (var i = 0; i < len; ++i) {
  3971. var selected = selectedElements[i];
  3972. if (selected == null) break;
  3973. if (i==0) {
  3974. var box = getBBox(selected);
  3975. // selectedBBoxes[i].x = box.x + dx;
  3976. // selectedBBoxes[i].y = box.y + dy;
  3977. }
  3978. // update the dummy transform in our transform list
  3979. // to be a translate
  3980. var xform = svgroot.createSVGTransform();
  3981. var tlist = getTransformList(selected);
  3982. xform.setTranslate(dx,dy);
  3983. if(tlist.numberOfItems) {
  3984. tlist.replaceItem(xform, 0);
  3985. // TODO: Webkit returns null here, find out why
  3986. // console.log(selected.getAttribute("transform"))
  3987. } else {
  3988. tlist.appendItem(xform);
  3989. }
  3990. // update our internal bbox that we're tracking while dragging
  3991. selectorManager.requestSelector(selected).resize();
  3992. }
  3993. }
  3994. }
  3995. break;
  3996. case "multiselect":
  3997. x *= current_zoom;
  3998. y *= current_zoom;
  3999. assignAttributes(rubberBox, {
  4000. 'x': Math.min(start_x,x),
  4001. 'y': Math.min(start_y,y),
  4002. 'width': Math.abs(x-start_x),
  4003. 'height': Math.abs(y-start_y)
  4004. },100);
  4005. // for each selected:
  4006. // - if newList contains selected, do nothing
  4007. // - if newList doesn't contain selected, remove it from selected
  4008. // - for any newList that was not in selectedElements, add it to selected
  4009. var elemsToRemove = [], elemsToAdd = [],
  4010. newList = getIntersectionList(),
  4011. len = selectedElements.length;
  4012. for (var i = 0; i < len; ++i) {
  4013. var ind = newList.indexOf(selectedElements[i]);
  4014. if (ind == -1) {
  4015. elemsToRemove.push(selectedElements[i]);
  4016. }
  4017. else {
  4018. newList[ind] = null;
  4019. }
  4020. }
  4021. len = newList.length;
  4022. for (i = 0; i < len; ++i) { if (newList[i]) elemsToAdd.push(newList[i]); }
  4023. if (elemsToRemove.length > 0)
  4024. canvas.removeFromSelection(elemsToRemove);
  4025. if (elemsToAdd.length > 0)
  4026. addToSelection(elemsToAdd);
  4027. break;
  4028. case "resize":
  4029. // we track the resize bounding box and translate/scale the selected element
  4030. // while the mouse is down, when mouse goes up, we use this to recalculate
  4031. // the shape's coordinates
  4032. var tlist = getTransformList(selected),
  4033. hasMatrix = hasMatrixTransform(tlist),
  4034. box=hasMatrix?init_bbox:getBBox(selected),
  4035. left=box.x, top=box.y, width=box.width,
  4036. height=box.height, dx=(x-start_x), dy=(y-start_y);
  4037. // if rotated, adjust the dx,dy values
  4038. var angle = getRotationAngle(selected);
  4039. if (angle) {
  4040. var r = Math.sqrt( dx*dx + dy*dy ),
  4041. theta = Math.atan2(dy,dx) - angle * Math.PI / 180.0;
  4042. dx = r * Math.cos(theta);
  4043. dy = r * Math.sin(theta);
  4044. }
  4045. // if not stretching in y direction, set dy to 0
  4046. // if not stretching in x direction, set dx to 0
  4047. if(current_resize_mode.indexOf("n")==-1 && current_resize_mode.indexOf("s")==-1) {
  4048. dy = 0;
  4049. }
  4050. if(current_resize_mode.indexOf("e")==-1 && current_resize_mode.indexOf("w")==-1) {
  4051. dx = 0;
  4052. }
  4053. var ts = null,
  4054. tx = 0, ty = 0,
  4055. sy = height ? (height+dy)/height : 1,
  4056. sx = width ? (width+dx)/width : 1;
  4057. // if we are dragging on the north side, then adjust the scale factor and ty
  4058. if(current_resize_mode.indexOf("n") != -1) {
  4059. sy = height ? (height-dy)/height : 1;
  4060. ty = height;
  4061. }
  4062. // if we dragging on the east side, then adjust the scale factor and tx
  4063. if(current_resize_mode.indexOf("w") != -1) {
  4064. sx = width ? (width-dx)/width : 1;
  4065. tx = width;
  4066. }
  4067. // update the transform list with translate,scale,translate
  4068. var translateOrigin = svgroot.createSVGTransform(),
  4069. scale = svgroot.createSVGTransform(),
  4070. translateBack = svgroot.createSVGTransform();
  4071. translateOrigin.setTranslate(-(left+tx),-(top+ty));
  4072. if(evt.shiftKey) {
  4073. if(sx == 1) sx = sy
  4074. else sy = sx;
  4075. }
  4076. scale.setScale(sx,sy);
  4077. translateBack.setTranslate(left+tx,top+ty);
  4078. if(hasMatrix) {
  4079. var diff = angle?1:0;
  4080. tlist.replaceItem(translateOrigin, 2+diff);
  4081. tlist.replaceItem(scale, 1+diff);
  4082. tlist.replaceItem(translateBack, 0+diff);
  4083. } else {
  4084. var N = tlist.numberOfItems;
  4085. tlist.replaceItem(translateBack, N-3);
  4086. tlist.replaceItem(scale, N-2);
  4087. tlist.replaceItem(translateOrigin, N-1);
  4088. }
  4089. var selectedBBox = selectedBBoxes[0];
  4090. // reset selected bbox top-left position
  4091. selectedBBox.x = left;
  4092. selectedBBox.y = top;
  4093. // if this is a translate, adjust the box position
  4094. if (tx) {
  4095. selectedBBox.x += dx;
  4096. }
  4097. if (ty) {
  4098. selectedBBox.y += dy;
  4099. }
  4100. selectorManager.requestSelector(selected).resize();
  4101. break;
  4102. case "zoom":
  4103. x *= current_zoom;
  4104. y *= current_zoom;
  4105. assignAttributes(rubberBox, {
  4106. 'x': Math.min(start_x*current_zoom,x),
  4107. 'y': Math.min(start_y*current_zoom,y),
  4108. 'width': Math.abs(x-start_x*current_zoom),
  4109. 'height': Math.abs(y-start_y*current_zoom)
  4110. },100);
  4111. break;
  4112. case "text":
  4113. assignAttributes(shape,{
  4114. 'x': x,
  4115. 'y': y
  4116. },1000);
  4117. break;
  4118. case "line":
  4119. // Opera has a problem with suspendRedraw() apparently
  4120. var handle = null;
  4121. if (!window.opera) svgroot.suspendRedraw(1000);
  4122. var x2 = x;
  4123. var y2 = y;
  4124. if(evt.shiftKey) { var xya=Utils.snapToAngle(start_x,start_y,x2,y2); x2=xya.x; y2=xya.y; }
  4125. shape.setAttributeNS(null, "x2", x2);
  4126. shape.setAttributeNS(null, "y2", y2);
  4127. if (!window.opera) svgroot.unsuspendRedraw(handle);
  4128. break;
  4129. case "foreignObject":
  4130. // fall through
  4131. case "square":
  4132. // fall through
  4133. case "rect":
  4134. // fall through
  4135. case "image":
  4136. var square = (current_mode == 'square') || evt.shiftKey,
  4137. w = Math.abs(x - start_x),
  4138. h = Math.abs(y - start_y),
  4139. new_x, new_y;
  4140. if(square) {
  4141. w = h = Math.max(w, h);
  4142. new_x = start_x < x ? start_x : start_x - w;
  4143. new_y = start_y < y ? start_y : start_y - h;
  4144. } else {
  4145. new_x = Math.min(start_x,x);
  4146. new_y = Math.min(start_y,y);
  4147. }
  4148. assignAttributes(shape,{
  4149. 'width': w,
  4150. 'height': h,
  4151. 'x': new_x,
  4152. 'y': new_y
  4153. },1000);
  4154. break;
  4155. case "circle":
  4156. var c = $(shape).attr(["cx", "cy"]);
  4157. var cx = c.cx, cy = c.cy,
  4158. rad = Math.sqrt( (x-cx)*(x-cx) + (y-cy)*(y-cy) );
  4159. shape.setAttributeNS(null, "r", rad);
  4160. break;
  4161. case "ellipse":
  4162. var c = $(shape).attr(["cx", "cy"]);
  4163. var cx = c.cx, cy = c.cy;
  4164. // Opera has a problem with suspendRedraw() apparently
  4165. handle = null;
  4166. if (!window.opera) svgroot.suspendRedraw(1000);
  4167. shape.setAttributeNS(null, "rx", Math.abs(x - cx) );
  4168. var ry = Math.abs(evt.shiftKey?(x - cx):(y - cy));
  4169. shape.setAttributeNS(null, "ry", ry );
  4170. if (!window.opera) svgroot.unsuspendRedraw(handle);
  4171. break;
  4172. case "fhellipse":
  4173. case "fhrect":
  4174. freehand.minx = Math.min(x, freehand.minx);
  4175. freehand.maxx = Math.max(x, freehand.maxx);
  4176. freehand.miny = Math.min(y, freehand.miny);
  4177. freehand.maxy = Math.max(y, freehand.maxy);
  4178. // break; missing on purpose
  4179. case "fhpath":
  4180. start_x = x;
  4181. start_y = y;
  4182. d_attr += + x + "," + y + " ";
  4183. shape.setAttributeNS(null, "points", d_attr);
  4184. break;
  4185. // update path stretch line coordinates
  4186. case "path":
  4187. // fall through
  4188. case "pathedit":
  4189. x *= current_zoom;
  4190. y *= current_zoom;
  4191. if(evt.shiftKey) {
  4192. var x1 = path.dragging?path.dragging[0]:start_x;
  4193. var y1 = path.dragging?path.dragging[1]:start_y;
  4194. var xya=Utils.snapToAngle(x1,y1,x,y);
  4195. x=xya.x; y=xya.y;
  4196. }
  4197. if(rubberBox && rubberBox.getAttribute('display') != 'none') {
  4198. assignAttributes(rubberBox, {
  4199. 'x': Math.min(start_x,x),
  4200. 'y': Math.min(start_y,y),
  4201. 'width': Math.abs(x-start_x),
  4202. 'height': Math.abs(y-start_y)
  4203. },100);
  4204. }
  4205. pathActions.mouseMove(x, y);
  4206. break;
  4207. case "textedit":
  4208. x *= current_zoom;
  4209. y *= current_zoom;
  4210. // if(rubberBox && rubberBox.getAttribute('display') != 'none') {
  4211. // assignAttributes(rubberBox, {
  4212. // 'x': Math.min(start_x,x),
  4213. // 'y': Math.min(start_y,y),
  4214. // 'width': Math.abs(x-start_x),
  4215. // 'height': Math.abs(y-start_y)
  4216. // },100);
  4217. // }
  4218. textActions.mouseMove(mouse_x, mouse_y);
  4219. break;
  4220. case "rotate":
  4221. var box = getBBox(selected),
  4222. cx = box.x + box.width/2,
  4223. cy = box.y + box.height/2,
  4224. m = getMatrix(selected),
  4225. center = transformPoint(cx,cy,m);
  4226. cx = center.x;
  4227. cy = center.y;
  4228. var angle = ((Math.atan2(cy-y,cx-x) * (180/Math.PI))-90) % 360;
  4229. if(evt.shiftKey) { // restrict rotations to nice angles (WRS)
  4230. var snap = 45;
  4231. angle= Math.round(angle/snap)*snap;
  4232. }
  4233. canvas.setRotationAngle(angle<-180?(360+angle):angle, true);
  4234. call("changed", selectedElements);
  4235. break;
  4236. default:
  4237. break;
  4238. }
  4239. runExtensions("mouseMove", {
  4240. event: evt,
  4241. mouse_x: mouse_x,
  4242. mouse_y: mouse_y,
  4243. selected: selected
  4244. });
  4245. }; // mouseMove()
  4246. // - in create mode, the element's opacity is set properly, we create an InsertElementCommand
  4247. // and store it on the Undo stack
  4248. // - in move/resize mode, the element's attributes which were affected by the move/resize are
  4249. // identified, a ChangeElementCommand is created and stored on the stack for those attrs
  4250. // this is done in when we recalculate the selected dimensions()
  4251. var mouseUp = function(evt)
  4252. {
  4253. if(evt.button === 1) return;
  4254. var tempJustSelected = justSelected;
  4255. justSelected = null;
  4256. if (!started) return;
  4257. var pt = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  4258. mouse_x = pt.x * current_zoom,
  4259. mouse_y = pt.y * current_zoom,
  4260. x = mouse_x / current_zoom,
  4261. y = mouse_y / current_zoom,
  4262. element = getElem(getId()),
  4263. keep = false;
  4264. started = false;
  4265. switch (current_mode)
  4266. {
  4267. // intentionally fall-through to select here
  4268. case "resize":
  4269. case "multiselect":
  4270. if (rubberBox != null) {
  4271. rubberBox.setAttribute("display", "none");
  4272. curBBoxes = [];
  4273. }
  4274. current_mode = "select";
  4275. case "select":
  4276. if (selectedElements[0] != null) {
  4277. // if we only have one selected element
  4278. if (selectedElements[1] == null) {
  4279. // set our current stroke/fill properties to the element's
  4280. var selected = selectedElements[0];
  4281. if (selected.tagName != "g" && selected.tagName != "image" && selected.tagName != "foreignObject") {
  4282. cur_properties.fill = selected.getAttribute("fill");
  4283. cur_properties.fill_opacity = selected.getAttribute("fill-opacity");
  4284. cur_properties.stroke = selected.getAttribute("stroke");
  4285. cur_properties.stroke_opacity = selected.getAttribute("stroke-opacity");
  4286. cur_properties.stroke_width = selected.getAttribute("stroke-width");
  4287. cur_properties.stroke_dasharray = selected.getAttribute("stroke-dasharray");
  4288. cur_properties.stroke_linejoin = selected.getAttribute("stroke-linejoin");
  4289. cur_properties.stroke_linecap = selected.getAttribute("stroke-linecap");
  4290. }
  4291. if (selected.tagName == "text") {
  4292. cur_text.font_size = selected.getAttribute("font-size");
  4293. cur_text.font_family = selected.getAttribute("font-family");
  4294. }
  4295. selectorManager.requestSelector(selected).showGrips(true);
  4296. // This shouldn't be necessary as it was done on mouseDown...
  4297. // call("selected", [selected]);
  4298. }
  4299. // always recalculate dimensions to strip off stray identity transforms
  4300. recalculateAllSelectedDimensions();
  4301. // if it was being dragged/resized
  4302. if (x != start_x || y != start_y) {
  4303. var len = selectedElements.length;
  4304. for (var i = 0; i < len; ++i) {
  4305. if (selectedElements[i] == null) break;
  4306. if(selectedElements[i].tagName != 'g') {
  4307. // Not needed for groups (incorrectly resizes elems), possibly not needed at all?
  4308. selectorManager.requestSelector(selectedElements[i]).resize();
  4309. }
  4310. }
  4311. }
  4312. // no change in position/size, so maybe we should move to pathedit
  4313. else {
  4314. var t = evt.target;
  4315. if (selectedElements[0].nodeName == "path" && selectedElements[1] == null) {
  4316. pathActions.select(t);
  4317. } // if it was a path
  4318. else if (selectedElements[0].nodeName == "text" && selectedElements[1] == null) {
  4319. textActions.select(t, x, y);
  4320. } // if it was a path
  4321. // else, if it was selected and this is a shift-click, remove it from selection
  4322. else if (evt.shiftKey) {
  4323. if(tempJustSelected != t) {
  4324. canvas.removeFromSelection([t]);
  4325. }
  4326. }
  4327. } // no change in mouse position
  4328. }
  4329. // we return immediately from select so that the obj_num is not incremented
  4330. return;
  4331. break;
  4332. case "zoom":
  4333. if (rubberBox != null) {
  4334. rubberBox.setAttribute("display", "none");
  4335. }
  4336. var factor = evt.shiftKey?.5:2;
  4337. call("zoomed", {
  4338. 'x': Math.min(start_x,x),
  4339. 'y': Math.min(start_y,y),
  4340. 'width': Math.abs(x-start_x),
  4341. 'height': Math.abs(y-start_y),
  4342. 'factor': factor
  4343. });
  4344. return;
  4345. case "fhpath":
  4346. // Check that the path contains at least 2 points; a degenerate one-point path
  4347. // causes problems.
  4348. // Webkit ignores how we set the points attribute with commas and uses space
  4349. // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870
  4350. var coords = element.getAttribute('points');
  4351. var commaIndex = coords.indexOf(',');
  4352. if (commaIndex >= 0) {
  4353. keep = coords.indexOf(',', commaIndex+1) >= 0;
  4354. } else {
  4355. keep = coords.indexOf(' ', coords.indexOf(' ')+1) >= 0;
  4356. }
  4357. if (keep) {
  4358. element = pathActions.smoothPolylineIntoPath(element);
  4359. }
  4360. break;
  4361. case "line":
  4362. var attrs = $(element).attr(["x1", "x2", "y1", "y2"]);
  4363. keep = (attrs.x1 != attrs.x2 || attrs.y1 != attrs.y2);
  4364. break;
  4365. case "foreignObject":
  4366. case "square":
  4367. case "rect":
  4368. case "image":
  4369. var attrs = $(element).attr(["width", "height"]);
  4370. // Image should be kept regardless of size (use inherit dimensions later)
  4371. keep = (attrs.width != 0 || attrs.height != 0) || current_mode === "image";
  4372. break;
  4373. case "circle":
  4374. keep = (element.getAttribute('r') != 0);
  4375. break;
  4376. case "ellipse":
  4377. var attrs = $(element).attr(["rx", "ry"]);
  4378. keep = (attrs.rx != null || attrs.ry != null);
  4379. break;
  4380. case "fhellipse":
  4381. if ((freehand.maxx - freehand.minx) > 0 &&
  4382. (freehand.maxy - freehand.miny) > 0) {
  4383. element = addSvgElementFromJson({
  4384. "element": "ellipse",
  4385. "curStyles": true,
  4386. "attr": {
  4387. "cx": (freehand.minx + freehand.maxx) / 2,
  4388. "cy": (freehand.miny + freehand.maxy) / 2,
  4389. "rx": (freehand.maxx - freehand.minx) / 2,
  4390. "ry": (freehand.maxy - freehand.miny) / 2,
  4391. "id": getId()
  4392. }
  4393. });
  4394. call("changed",[element]);
  4395. keep = true;
  4396. }
  4397. break;
  4398. case "fhrect":
  4399. if ((freehand.maxx - freehand.minx) > 0 &&
  4400. (freehand.maxy - freehand.miny) > 0) {
  4401. element = addSvgElementFromJson({
  4402. "element": "rect",
  4403. "curStyles": true,
  4404. "attr": {
  4405. "x": freehand.minx,
  4406. "y": freehand.miny,
  4407. "width": (freehand.maxx - freehand.minx),
  4408. "height": (freehand.maxy - freehand.miny),
  4409. "id": getId()
  4410. }
  4411. });
  4412. call("changed",[element]);
  4413. keep = true;
  4414. }
  4415. break;
  4416. case "text":
  4417. keep = true;
  4418. addToSelection([element]);
  4419. textActions.start(element);
  4420. break;
  4421. case "path":
  4422. // set element to null here so that it is not removed nor finalized
  4423. element = null;
  4424. // continue to be set to true so that mouseMove happens
  4425. started = true;
  4426. var res = pathActions.mouseUp(evt, element, mouse_x, mouse_y);
  4427. element = res.element
  4428. keep = res.keep;
  4429. break;
  4430. case "pathedit":
  4431. keep = true;
  4432. element = null;
  4433. pathActions.mouseUp(evt);
  4434. break;
  4435. case "textedit":
  4436. keep = false;
  4437. element = null;
  4438. textActions.mouseUp(evt, mouse_x, mouse_y);
  4439. break;
  4440. case "rotate":
  4441. keep = true;
  4442. element = null;
  4443. current_mode = "select";
  4444. var batchCmd = canvas.finishUndoableChange();
  4445. if (!batchCmd.isEmpty()) {
  4446. addCommandToHistory(batchCmd);
  4447. }
  4448. // perform recalculation to weed out any stray identity transforms that might get stuck
  4449. recalculateAllSelectedDimensions();
  4450. break;
  4451. default:
  4452. // This could occur in an extension
  4453. break;
  4454. }
  4455. var ext_result = runExtensions("mouseUp", {
  4456. event: evt,
  4457. mouse_x: mouse_x,
  4458. mouse_y: mouse_y
  4459. }, true);
  4460. $.each(ext_result, function(i, r) {
  4461. if(r) {
  4462. keep = r.keep || keep;
  4463. element = r.element;
  4464. started = r.started || started;
  4465. }
  4466. });
  4467. if (!keep && element != null) {
  4468. element.parentNode.removeChild(element);
  4469. element = null;
  4470. var t = evt.target;
  4471. // if this element is in a group, go up until we reach the top-level group
  4472. // just below the layer groups
  4473. // TODO: once we implement links, we also would have to check for <a> elements
  4474. while (t.parentNode.parentNode.tagName == "g") {
  4475. t = t.parentNode;
  4476. }
  4477. // if we are not in the middle of creating a path, and we've clicked on some shape,
  4478. // then go to Select mode.
  4479. // WebKit returns <div> when the canvas is clicked, Firefox/Opera return <svg>
  4480. if ( (current_mode != "path" || current_path_pts.length == 0) &&
  4481. t.parentNode.id != "selectorParentGroup" &&
  4482. t.id != "svgcanvas" && t.id != "svgroot")
  4483. {
  4484. // switch into "select" mode if we've clicked on an element
  4485. addToSelection([t], true);
  4486. canvas.setMode("select");
  4487. }
  4488. } else if (element != null) {
  4489. canvas.addedNew = true;
  4490. var ani_dur = .2, c_ani;
  4491. if(opac_ani.beginElement && element.getAttribute('opacity') != cur_shape.opacity) {
  4492. c_ani = $(opac_ani).clone().attr({
  4493. to: cur_shape.opacity,
  4494. dur: ani_dur
  4495. }).appendTo(element);
  4496. c_ani[0].beginElement();
  4497. } else {
  4498. ani_dur = 0;
  4499. }
  4500. // Ideally this would be done on the endEvent of the animation,
  4501. // but that doesn't seem to be supported in Webkit
  4502. setTimeout(function() {
  4503. if(c_ani) c_ani.remove();
  4504. element.setAttribute("opacity", cur_shape.opacity);
  4505. element.setAttribute("style", "pointer-events:inherit");
  4506. cleanupElement(element);
  4507. if(current_mode == "path") {
  4508. pathActions.toEditMode(element);
  4509. } else if (current_mode == "text" || current_mode == "image" || current_mode == "foreignObject") {
  4510. // keep us in the tool we were in unless it was a text or image element
  4511. addToSelection([element], true);
  4512. }
  4513. // we create the insert command that is stored on the stack
  4514. // undo means to call cmd.unapply(), redo means to call cmd.apply()
  4515. addCommandToHistory(new InsertElementCommand(element));
  4516. call("changed",[element]);
  4517. }, ani_dur * 1000);
  4518. }
  4519. start_transform = null;
  4520. };
  4521. // prevent links from being followed in the canvas
  4522. var handleLinkInCanvas = function(e) {
  4523. e.preventDefault();
  4524. return false;
  4525. };
  4526. $(container).mousedown(mouseDown).mousemove(mouseMove).click(handleLinkInCanvas);
  4527. $(window).mouseup(mouseUp);
  4528. $(container).bind("mousewheel DOMMouseScroll", function(e){
  4529. if(!e.shiftKey) return;
  4530. e.preventDefault();
  4531. root_sctm = svgcontent.getScreenCTM().inverse();
  4532. var pt = transformPoint( e.pageX, e.pageY, root_sctm );
  4533. var bbox = {
  4534. 'x': pt.x,
  4535. 'y': pt.y,
  4536. 'width': 0,
  4537. 'height': 0
  4538. };
  4539. // Respond to mouse wheel in IE/Webkit/Opera.
  4540. // (It returns up/dn motion in multiples of 120)
  4541. if(e.wheelDelta) {
  4542. if (e.wheelDelta >= 120) {
  4543. bbox.factor = 2;
  4544. } else if (e.wheelDelta <= -120) {
  4545. bbox.factor = .5;
  4546. }
  4547. } else if(e.detail) {
  4548. if (e.detail > 0) {
  4549. bbox.factor = .5;
  4550. } else if (e.detail < 0) {
  4551. bbox.factor = 2;
  4552. }
  4553. }
  4554. if(!bbox.factor) return;
  4555. call("zoomed", bbox);
  4556. });
  4557. }());
  4558. // Function: preventClickDefault
  4559. // Prevents default browser click behaviour on the given element
  4560. //
  4561. // Parameters:
  4562. // img - The DOM element to prevent the cilck on
  4563. var preventClickDefault = function(img) {
  4564. $(img).click(function(e){e.preventDefault()});
  4565. }
  4566. // Group: Text edit functions
  4567. // Functions relating to editing text elements
  4568. var textActions = canvas.textActions = function() {
  4569. var curtext, current_text;
  4570. var textinput;
  4571. var cursor;
  4572. var selblock;
  4573. var blinker;
  4574. var chardata = [];
  4575. var textbb, transbb;
  4576. var matrix;
  4577. var last_x, last_y;
  4578. var allow_dbl;
  4579. function setCursor(index) {
  4580. var empty = (textinput.value === "");
  4581. if(!arguments.length) {
  4582. if(empty) {
  4583. index = 0;
  4584. } else {
  4585. if(textinput.selectionEnd !== textinput.selectionStart) return;
  4586. index = textinput.selectionEnd;
  4587. }
  4588. }
  4589. var charbb;
  4590. charbb = chardata[index];
  4591. if(!empty) {
  4592. textinput.setSelectionRange(index, index);
  4593. }
  4594. cursor = getElem("text_cursor");
  4595. if (!cursor) {
  4596. cursor = document.createElementNS(svgns, "line");
  4597. assignAttributes(cursor, {
  4598. 'id': "text_cursor",
  4599. 'stroke': "#333",
  4600. 'stroke-width': 1
  4601. });
  4602. cursor = getElem("selectorParentGroup").appendChild(cursor);
  4603. }
  4604. if(!blinker) {
  4605. blinker = setInterval(function() {
  4606. var show = (cursor.getAttribute('display') === 'none');
  4607. cursor.setAttribute('display', show?'inline':'none');
  4608. }, 600);
  4609. }
  4610. var start_pt = ptToScreen(charbb.x, textbb.y);
  4611. var end_pt = ptToScreen(charbb.x, (textbb.y + textbb.height));
  4612. assignAttributes(cursor, {
  4613. x1: start_pt.x,
  4614. y1: start_pt.y,
  4615. x2: end_pt.x,
  4616. y2: end_pt.y,
  4617. visibility: 'visible',
  4618. display: 'inline'
  4619. });
  4620. if(selblock) selblock.setAttribute('d', '');
  4621. }
  4622. function setSelection(start, end, skipInput) {
  4623. if(start === end) {
  4624. setCursor(end);
  4625. return;
  4626. }
  4627. if(!skipInput) {
  4628. textinput.setSelectionRange(start, end);
  4629. }
  4630. selblock = getElem("text_selectblock");
  4631. if (!selblock) {
  4632. selblock = document.createElementNS(svgns, "path");
  4633. assignAttributes(selblock, {
  4634. 'id': "text_selectblock",
  4635. 'fill': "green",
  4636. 'opacity': .5,
  4637. 'style': "pointer-events:none"
  4638. });
  4639. getElem("selectorParentGroup").appendChild(selblock);
  4640. }
  4641. var startbb = chardata[start];
  4642. var endbb = chardata[end];
  4643. cursor.setAttribute('visibility', 'hidden');
  4644. var tl = ptToScreen(startbb.x, textbb.y),
  4645. tr = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y),
  4646. bl = ptToScreen(startbb.x, textbb.y + textbb.height),
  4647. br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height);
  4648. var dstr = "M" + tl.x + "," + tl.y
  4649. + " L" + tr.x + "," + tr.y
  4650. + " " + br.x + "," + br.y
  4651. + " " + bl.x + "," + bl.y + "z";
  4652. assignAttributes(selblock, {
  4653. d: dstr,
  4654. 'display': 'inline'
  4655. });
  4656. }
  4657. function getIndexFromPoint(mouse_x, mouse_y) {
  4658. // Position cursor here
  4659. var pt = svgroot.createSVGPoint();
  4660. pt.x = mouse_x;
  4661. pt.y = mouse_y;
  4662. // No content, so return 0
  4663. if(chardata.length == 1) return 0;
  4664. // Determine if cursor should be on left or right of character
  4665. var charpos = curtext.getCharNumAtPosition(pt);
  4666. if(charpos < 0) {
  4667. // Out of text range, look at mouse coords
  4668. charpos = chardata.length - 2;
  4669. if(mouse_x <= chardata[0].x) {
  4670. charpos = 0;
  4671. }
  4672. } else if(charpos >= chardata.length - 2) {
  4673. charpos = chardata.length - 2;
  4674. }
  4675. var charbb = chardata[charpos];
  4676. var mid = charbb.x + (charbb.width/2);
  4677. if(mouse_x > mid) {
  4678. charpos++;
  4679. }
  4680. return charpos;
  4681. }
  4682. function setCursorFromPoint(mouse_x, mouse_y) {
  4683. setCursor(getIndexFromPoint(mouse_x, mouse_y));
  4684. }
  4685. function setEndSelectionFromPoint(x, y, apply) {
  4686. var i1 = textinput.selectionStart;
  4687. var i2 = getIndexFromPoint(x, y);
  4688. var start = Math.min(i1, i2);
  4689. var end = Math.max(i1, i2);
  4690. setSelection(start, end, !apply);
  4691. }
  4692. function screenToPt(x_in, y_in) {
  4693. var out = {
  4694. x: x_in,
  4695. y: y_in
  4696. }
  4697. out.x /= current_zoom;
  4698. out.y /= current_zoom;
  4699. if(matrix) {
  4700. var pt = transformPoint(out.x, out.y, matrix.inverse());
  4701. out.x = pt.x;
  4702. out.y = pt.y;
  4703. }
  4704. return out;
  4705. }
  4706. function ptToScreen(x_in, y_in) {
  4707. var out = {
  4708. x: x_in,
  4709. y: y_in
  4710. }
  4711. if(matrix) {
  4712. var pt = transformPoint(out.x, out.y, matrix);
  4713. out.x = pt.x;
  4714. out.y = pt.y;
  4715. }
  4716. out.x *= current_zoom;
  4717. out.y *= current_zoom;
  4718. return out;
  4719. }
  4720. function hideCursor() {
  4721. if(cursor) {
  4722. cursor.setAttribute('visibility', 'hidden');
  4723. }
  4724. }
  4725. function selectAll(evt) {
  4726. setSelection(0, curtext.textContent.length);
  4727. $(this).unbind(evt);
  4728. }
  4729. function selectWord(evt) {
  4730. if(!allow_dbl) return;
  4731. var ept = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  4732. mouse_x = ept.x * current_zoom,
  4733. mouse_y = ept.y * current_zoom;
  4734. var pt = screenToPt(mouse_x, mouse_y);
  4735. var index = getIndexFromPoint(pt.x, pt.y);
  4736. var str = curtext.textContent;
  4737. var first = str.substr(0, index).replace(/[a-z0-9]+$/i, '').length;
  4738. var m = str.substr(index).match(/^[a-z0-9]+/i);
  4739. var last = (m?m[0].length:0) + index;
  4740. setSelection(first, last);
  4741. // Set tripleclick
  4742. $(evt.target).click(selectAll);
  4743. setTimeout(function() {
  4744. $(evt.target).unbind('click', selectAll);
  4745. }, 300);
  4746. }
  4747. return {
  4748. select: function(target, x, y) {
  4749. if (current_text == target) {
  4750. curtext = target;
  4751. textActions.toEditMode(x, y);
  4752. } // going into pathedit mode
  4753. else {
  4754. current_text = target;
  4755. }
  4756. },
  4757. start: function(elem) {
  4758. curtext = elem;
  4759. textActions.toEditMode();
  4760. },
  4761. mouseDown: function(evt, mouse_target, start_x, start_y) {
  4762. var pt = screenToPt(start_x, start_y);
  4763. textinput.focus();
  4764. setCursorFromPoint(pt.x, pt.y);
  4765. last_x = start_x;
  4766. last_y = start_y;
  4767. // TODO: Find way to block native selection
  4768. },
  4769. mouseMove: function(mouse_x, mouse_y) {
  4770. var pt = screenToPt(mouse_x, mouse_y);
  4771. setEndSelectionFromPoint(pt.x, pt.y);
  4772. },
  4773. mouseUp: function(evt, mouse_x, mouse_y) {
  4774. var pt = screenToPt(mouse_x, mouse_y);
  4775. setEndSelectionFromPoint(pt.x, pt.y, true);
  4776. // TODO: Find a way to make this work: Use transformed BBox instead of evt.target
  4777. // if(last_x === mouse_x && last_y === mouse_y
  4778. // && !Utils.rectsIntersect(transbb, {x: pt.x, y: pt.y, width:0, height:0})) {
  4779. // textActions.toSelectMode(true);
  4780. // }
  4781. if(last_x === mouse_x && last_y === mouse_y && evt.target !== curtext) {
  4782. textActions.toSelectMode(true);
  4783. }
  4784. },
  4785. setCursor: setCursor,
  4786. toEditMode: function(x, y) {
  4787. allow_dbl = false;
  4788. current_mode = "textedit";
  4789. selectorManager.requestSelector(curtext).showGrips(false);
  4790. textActions.init();
  4791. $(curtext).css('cursor', 'text');
  4792. // if(support.editableText) {
  4793. // curtext.setAttribute('editable', 'simple');
  4794. // return;
  4795. // }
  4796. if(!arguments.length) {
  4797. setCursor();
  4798. } else {
  4799. var pt = screenToPt(x, y);
  4800. setCursorFromPoint(pt.x, pt.y);
  4801. }
  4802. setTimeout(function() {
  4803. allow_dbl = true;
  4804. }, 300);
  4805. },
  4806. toSelectMode: function(selectElem) {
  4807. current_mode = "select";
  4808. clearInterval(blinker);
  4809. blinker = null;
  4810. if(selblock) $(selblock).attr('display','none');
  4811. if(cursor) $(cursor).attr('visibility','hidden');
  4812. $(curtext).css('cursor', 'move');
  4813. if(selectElem) {
  4814. clearSelection();
  4815. $(curtext).css('cursor', 'move');
  4816. call("selected", [curtext]);
  4817. addToSelection([curtext], true);
  4818. }
  4819. if(curtext && !curtext.textContent.length) {
  4820. // No content, so delete
  4821. canvas.deleteSelectedElements();
  4822. }
  4823. $(textinput).blur();
  4824. curtext = false;
  4825. // if(support.editableText) {
  4826. // curtext.removeAttribute('editable');
  4827. // }
  4828. },
  4829. setInputElem: function(elem) {
  4830. textinput = elem;
  4831. $(textinput).blur(hideCursor);
  4832. },
  4833. clear: function() {
  4834. current_text = null;
  4835. if(current_mode == "textedit") {
  4836. textActions.toSelectMode();
  4837. }
  4838. },
  4839. init: function(inputElem) {
  4840. if(!curtext) return;
  4841. // if(support.editableText) {
  4842. // curtext.select();
  4843. // return;
  4844. // }
  4845. if(!curtext.parentNode) {
  4846. // Result of the ffClone, need to get correct element
  4847. curtext = selectedElements[0];
  4848. selectorManager.requestSelector(curtext).showGrips(false);
  4849. }
  4850. var str = curtext.textContent;
  4851. var len = str.length;
  4852. var xform = curtext.getAttribute('transform');
  4853. textbb = getBBox(curtext);
  4854. matrix = xform?getMatrix(curtext):null;
  4855. chardata = Array(len);
  4856. textinput.focus();
  4857. $(curtext).unbind('dblclick', selectWord).dblclick(selectWord);
  4858. if(!len) {
  4859. var end = {x: textbb.x + (textbb.width/2), width: 0};
  4860. }
  4861. for(var i=0; i<len; i++) {
  4862. var start = curtext.getStartPositionOfChar(i);
  4863. var end = curtext.getEndPositionOfChar(i);
  4864. // Get a "bbox" equivalent for each character. Uses the
  4865. // bbox data of the actual text for y, height purposes
  4866. // TODO: Decide if y, width and height are actually necessary
  4867. chardata[i] = {
  4868. x: start.x,
  4869. y: textbb.y, // start.y?
  4870. width: end.x - start.x,
  4871. height: textbb.height
  4872. };
  4873. }
  4874. // Add a last bbox for cursor at end of text
  4875. chardata.push({
  4876. x: end.x,
  4877. width: 0
  4878. });
  4879. setSelection(textinput.selectionStart, textinput.selectionEnd, true);
  4880. }
  4881. }
  4882. }();
  4883. // Group: Path edit functions
  4884. // Functions relating to editing path elements
  4885. var pathActions = this.pathActions = function() {
  4886. var subpath = false;
  4887. var pathData = {};
  4888. var current_path;
  4889. var path;
  4890. var segData = {
  4891. 2: ['x','y'],
  4892. 4: ['x','y'],
  4893. 6: ['x','y','x1','y1','x2','y2'],
  4894. 8: ['x','y','x1','y1'],
  4895. 10: ['x','y','r1','r2','angle','largeArcFlag','sweepFlag'],
  4896. 12: ['x'],
  4897. 14: ['y']
  4898. };
  4899. function retPath() {
  4900. return path;
  4901. }
  4902. function resetD(p) {
  4903. p.setAttribute("d", pathActions.convertPath(p));
  4904. }
  4905. function insertItemBefore(elem, newseg, index) {
  4906. // Support insertItemBefore on paths for FF2
  4907. var list = elem.pathSegList;
  4908. if(support.pathInsertItemBefore) {
  4909. list.insertItemBefore(newseg, index);
  4910. return;
  4911. }
  4912. var len = list.numberOfItems;
  4913. var arr = [];
  4914. for(var i=0; i<len; i++) {
  4915. var cur_seg = list.getItem(i);
  4916. arr.push(cur_seg)
  4917. }
  4918. list.clear();
  4919. for(var i=0; i<len; i++) {
  4920. if(i == index) { //index+1
  4921. list.appendItem(newseg);
  4922. }
  4923. list.appendItem(arr[i]);
  4924. }
  4925. }
  4926. // TODO: See if this should just live in replacePathSeg
  4927. function ptObjToArr(type, seg_item) {
  4928. var arr = segData[type], len = arr.length;
  4929. var out = Array(len);
  4930. for(var i=0; i<len; i++) {
  4931. out[i] = seg_item[arr[i]];
  4932. }
  4933. return out;
  4934. }
  4935. function getGripContainer() {
  4936. var c = getElem("pathpointgrip_container");
  4937. if (!c) {
  4938. var parent = getElem("selectorParentGroup");
  4939. c = parent.appendChild(document.createElementNS(svgns, "g"));
  4940. c.id = "pathpointgrip_container";
  4941. }
  4942. return c;
  4943. }
  4944. var addPointGrip = function(index, x, y) {
  4945. // create the container of all the point grips
  4946. var pointGripContainer = getGripContainer();
  4947. var pointGrip = getElem("pathpointgrip_"+index);
  4948. // create it
  4949. if (!pointGrip) {
  4950. pointGrip = document.createElementNS(svgns, "circle");
  4951. assignAttributes(pointGrip, {
  4952. 'id': "pathpointgrip_" + index,
  4953. 'display': "none",
  4954. 'r': 4,
  4955. 'fill': "#0FF",
  4956. 'stroke': "#00F",
  4957. 'stroke-width': 2,
  4958. 'cursor': 'move',
  4959. 'style': 'pointer-events:all',
  4960. 'xlink:title': uiStrings.pathNodeTooltip
  4961. });
  4962. pointGrip = pointGripContainer.appendChild(pointGrip);
  4963. var grip = $('#pathpointgrip_'+index);
  4964. grip.dblclick(function() {
  4965. if(path) path.setSegType();
  4966. });
  4967. }
  4968. if(x && y) {
  4969. // set up the point grip element and display it
  4970. assignAttributes(pointGrip, {
  4971. 'cx': x,
  4972. 'cy': y,
  4973. 'display': "inline"
  4974. });
  4975. }
  4976. return pointGrip;
  4977. };
  4978. var getPointGrip = function(seg, update) {
  4979. var index = seg.index;
  4980. var pointGrip = addPointGrip(index);
  4981. if(update) {
  4982. var pt = getGripPt(seg);
  4983. assignAttributes(pointGrip, {
  4984. 'cx': pt.x,
  4985. 'cy': pt.y,
  4986. 'display': "inline"
  4987. });
  4988. }
  4989. return pointGrip;
  4990. }
  4991. var getSegSelector = function(seg, update) {
  4992. var index = seg.index;
  4993. var segLine = getElem("segline_" + index);
  4994. if(!segLine) {
  4995. var pointGripContainer = getGripContainer();
  4996. // create segline
  4997. segLine = document.createElementNS(svgns, "path");
  4998. assignAttributes(segLine, {
  4999. 'id': "segline_" + index,
  5000. 'display': 'none',
  5001. 'fill': "none",
  5002. 'stroke': "#0FF",
  5003. 'stroke-width': 2,
  5004. 'style':'pointer-events:none',
  5005. 'd': 'M0,0 0,0'
  5006. });
  5007. pointGripContainer.appendChild(segLine);
  5008. }
  5009. if(update) {
  5010. var prev = seg.prev;
  5011. if(!prev) {
  5012. segLine.setAttribute("display", "none");
  5013. return segLine;
  5014. }
  5015. var pt = getGripPt(prev);
  5016. // Set start point
  5017. replacePathSeg(2, 0, [pt.x, pt.y], segLine);
  5018. var pts = ptObjToArr(seg.type, seg.item, true);
  5019. for(var i=0; i < pts.length; i+=2) {
  5020. var pt = getGripPt(seg, {x:pts[i], y:pts[i+1]});
  5021. pts[i] = pt.x;
  5022. pts[i+1] = pt.y;
  5023. }
  5024. replacePathSeg(seg.type, 1, pts, segLine);
  5025. }
  5026. return segLine;
  5027. }
  5028. var getControlPoints = function(seg) {
  5029. var item = seg.item;
  5030. var index = seg.index;
  5031. if(!("x1" in item) || !("x2" in item)) return null;
  5032. var cpt = {};
  5033. var pointGripContainer = getGripContainer();
  5034. // Note that this is intentionally not seg.prev.item
  5035. var prev = path.segs[index-1].item;
  5036. var seg_items = [prev, item];
  5037. for(var i=1; i<3; i++) {
  5038. var id = index + 'c' + i;
  5039. var ctrlLine = cpt['c' + i + '_line'] = getElem("ctrlLine_"+id);
  5040. if(!ctrlLine) {
  5041. ctrlLine = document.createElementNS(svgns, "line");
  5042. assignAttributes(ctrlLine, {
  5043. 'id': "ctrlLine_"+id,
  5044. 'stroke': "#555",
  5045. 'stroke-width': 1,
  5046. "style": "pointer-events:none"
  5047. });
  5048. pointGripContainer.appendChild(ctrlLine);
  5049. }
  5050. var pt = getGripPt(seg, {x:item['x' + i], y:item['y' + i]});
  5051. var gpt = getGripPt(seg, {x:seg_items[i-1].x, y:seg_items[i-1].y});
  5052. assignAttributes(ctrlLine, {
  5053. 'x1': pt.x,
  5054. 'y1': pt.y,
  5055. 'x2': gpt.x,
  5056. 'y2': gpt.y,
  5057. 'display': "inline"
  5058. });
  5059. cpt['c' + i + '_line'] = ctrlLine;
  5060. var pointGrip = cpt['c' + i] = getElem("ctrlpointgrip_"+id);
  5061. // create it
  5062. if (!pointGrip) {
  5063. pointGrip = document.createElementNS(svgns, "circle");
  5064. assignAttributes(pointGrip, {
  5065. 'id': "ctrlpointgrip_" + id,
  5066. 'display': "none",
  5067. 'r': 4,
  5068. 'fill': "#0FF",
  5069. 'stroke': "#55F",
  5070. 'stroke-width': 1,
  5071. 'cursor': 'move',
  5072. 'style': 'pointer-events:all',
  5073. 'xlink:title': uiStrings.pathCtrlPtTooltip
  5074. });
  5075. pointGripContainer.appendChild(pointGrip);
  5076. }
  5077. assignAttributes(pointGrip, {
  5078. 'cx': pt.x,
  5079. 'cy': pt.y,
  5080. 'display': "inline"
  5081. });
  5082. cpt['c' + i] = pointGrip;
  5083. }
  5084. return cpt;
  5085. }
  5086. function getGripPt(seg, alt_pt) {
  5087. var out = {
  5088. x: alt_pt? alt_pt.x : seg.item.x,
  5089. y: alt_pt? alt_pt.y : seg.item.y
  5090. }, path = seg.path;
  5091. if(path.matrix) {
  5092. var pt = transformPoint(out.x, out.y, path.matrix);
  5093. out = pt;
  5094. }
  5095. out.x *= current_zoom;
  5096. out.y *= current_zoom;
  5097. return out;
  5098. }
  5099. function getPointFromGrip(pt, path) {
  5100. var out = {
  5101. x: pt.x,
  5102. y: pt.y
  5103. }
  5104. if(path.matrix) {
  5105. var pt = transformPoint(out.x, out.y, path.imatrix);
  5106. out.x = pt.x;
  5107. out.y = pt.y;
  5108. }
  5109. out.x /= current_zoom;
  5110. out.y /= current_zoom;
  5111. return out;
  5112. }
  5113. function Segment(index, item) {
  5114. var s = this;
  5115. s.index = index;
  5116. s.selected = false;
  5117. s.type = item.pathSegType;
  5118. var grip;
  5119. s.addGrip = function() {
  5120. grip = s.ptgrip = getPointGrip(s, true);
  5121. s.ctrlpts = getControlPoints(s, true);
  5122. s.segsel = getSegSelector(s, true);
  5123. }
  5124. s.item = item;
  5125. s.show = function(y) {
  5126. if(grip) {
  5127. grip.setAttribute("display", y?"inline":"none");
  5128. s.segsel.setAttribute("display", y?"inline":"none");
  5129. // Show/hide all control points if available
  5130. s.showCtrlPts(y);
  5131. }
  5132. }
  5133. s.select = function(y) {
  5134. if(grip) {
  5135. grip.setAttribute("stroke", y?"#0FF":"#00F");
  5136. s.segsel.setAttribute("display", y?"inline":"none");
  5137. if(s.ctrlpts) {
  5138. s.selectCtrls(y);
  5139. }
  5140. s.selected = y;
  5141. }
  5142. }
  5143. s.selectCtrls = function(y) {
  5144. $('#ctrlpointgrip_' + s.index + 'c1, #ctrlpointgrip_' + s.index + 'c2').attr('fill',y?'#0FF':'#EEE');
  5145. }
  5146. s.update = function(full) {
  5147. item = s.item;
  5148. if(grip) {
  5149. var pt = getGripPt(s);
  5150. assignAttributes(grip, {
  5151. 'cx': pt.x,
  5152. 'cy': pt.y
  5153. });
  5154. getSegSelector(s, true);
  5155. if(s.ctrlpts) {
  5156. if(full) {
  5157. s.item = path.elem.pathSegList.getItem(s.index);
  5158. s.type = s.item.pathSegType;
  5159. }
  5160. getControlPoints(s);
  5161. }
  5162. // this.segsel.setAttribute("display", y?"inline":"none");
  5163. }
  5164. }
  5165. s.move = function(dx, dy) {
  5166. var item = s.item;
  5167. var cur = s;
  5168. if(cur.ctrlpts) {
  5169. var cur_pts = [item.x += dx, item.y += dy,
  5170. item.x1, item.y1, item.x2 += dx, item.y2 += dy];
  5171. } else {
  5172. var cur_pts = [item.x += dx, item.y += dy];
  5173. }
  5174. replacePathSeg(cur.type, cur.index, cur_pts);
  5175. if(s.next && s.next.ctrlpts) {
  5176. var next = s.next.item;
  5177. var next_pts = [next.x, next.y,
  5178. next.x1 += dx, next.y1 += dy, next.x2, next.y2];
  5179. replacePathSeg(s.next.type, s.next.index, next_pts);
  5180. }
  5181. if(s.mate) {
  5182. // The last point of a closed subpath has a "mate",
  5183. // which is the "M" segment of the subpath
  5184. var item = s.mate.item;
  5185. var pts = [item.x += dx, item.y += dy];
  5186. replacePathSeg(s.mate.type, s.mate.index, pts);
  5187. // Has no grip, so does not need "updating"?
  5188. }
  5189. s.update(true);
  5190. if(s.next) s.next.update(true);
  5191. }
  5192. s.setLinked = function(num) {
  5193. var seg, anum, pt;
  5194. if(num == 2) {
  5195. anum = 1;
  5196. seg = s.next;
  5197. if(!seg) return;
  5198. pt = s.item;
  5199. } else {
  5200. anum = 2;
  5201. seg = s.prev;
  5202. if(!seg) return;
  5203. pt = seg.item;
  5204. }
  5205. var item = seg.item;
  5206. item['x' + anum] = pt.x + (pt.x - s.item['x' + num]);
  5207. item['y' + anum] = pt.y + (pt.y - s.item['y' + num]);
  5208. var pts = [item.x,item.y,
  5209. item.x1,item.y1, item.x2,item.y2];
  5210. replacePathSeg(seg.type, seg.index, pts);
  5211. seg.update(true);
  5212. }
  5213. s.moveCtrl = function(num, dx, dy) {
  5214. var item = s.item;
  5215. item['x' + num] += dx;
  5216. item['y' + num] += dy;
  5217. var pts = [item.x,item.y,
  5218. item.x1,item.y1, item.x2,item.y2];
  5219. replacePathSeg(s.type, s.index, pts);
  5220. s.update(true);
  5221. }
  5222. s.setType = function(new_type, pts) {
  5223. replacePathSeg(new_type, index, pts);
  5224. s.type = new_type;
  5225. s.item = path.elem.pathSegList.getItem(index);
  5226. s.showCtrlPts(new_type === 6);
  5227. s.ctrlpts = getControlPoints(s);
  5228. s.update(true);
  5229. }
  5230. s.showCtrlPts = function(y) {
  5231. if(s.ctrlpts) {
  5232. for (var o in s.ctrlpts) {
  5233. s.ctrlpts[o].setAttribute("display", y?"inline":"none");
  5234. }
  5235. }
  5236. }
  5237. }
  5238. function Path(elem) {
  5239. if(!elem || elem.tagName !== "path") return false;
  5240. var p = path = this;
  5241. this.elem = elem;
  5242. this.segs = [];
  5243. this.selected_pts = [];
  5244. // Reset path data
  5245. this.init = function() {
  5246. // Hide all grips, etc
  5247. $(getGripContainer()).find("*").attr("display", "none");
  5248. var segList = elem.pathSegList;
  5249. var len = segList.numberOfItems;
  5250. p.segs = [];
  5251. p.selected_pts = [];
  5252. p.first_seg = null;
  5253. // Set up segs array
  5254. for(var i=0; i < len; i++) {
  5255. var item = segList.getItem(i);
  5256. var segment = new Segment(i, item);
  5257. segment.path = p;
  5258. p.segs.push(segment);
  5259. }
  5260. var segs = p.segs;
  5261. var start_i = null;
  5262. for(var i=0; i < len; i++) {
  5263. var seg = segs[i];
  5264. var next_seg = (i+1) >= len ? null : segs[i+1];
  5265. var prev_seg = (i-1) < 0 ? null : segs[i-1];
  5266. if(seg.type === 2) {
  5267. if(prev_seg && prev_seg.type !== 1) {
  5268. // New sub-path, last one is open,
  5269. // so add a grip to last sub-path's first point
  5270. var start_seg = segs[start_i];
  5271. start_seg.next = segs[start_i+1];
  5272. start_seg.next.prev = start_seg;
  5273. start_seg.addGrip();
  5274. }
  5275. // Remember that this is a starter seg
  5276. start_i = i;
  5277. } else if(next_seg && next_seg.type === 1) {
  5278. // This is the last real segment of a closed sub-path
  5279. // Next is first seg after "M"
  5280. seg.next = segs[start_i+1];
  5281. // First seg after "M"'s prev is this
  5282. seg.next.prev = seg;
  5283. seg.mate = segs[start_i];
  5284. seg.addGrip();
  5285. if(p.first_seg == null) {
  5286. p.first_seg = seg;
  5287. }
  5288. } else if(!next_seg) {
  5289. if(seg.type !== 1) {
  5290. // Last seg, doesn't close so add a grip
  5291. // to last sub-path's first point
  5292. var start_seg = segs[start_i];
  5293. start_seg.next = segs[start_i+1];
  5294. start_seg.next.prev = start_seg;
  5295. start_seg.addGrip();
  5296. seg.addGrip();
  5297. if(!p.first_seg) {
  5298. // Open path, so set first as real first and add grip
  5299. p.first_seg = segs[start_i];
  5300. }
  5301. }
  5302. } else if(seg.type !== 1){
  5303. // Regular segment, so add grip and its "next"
  5304. seg.addGrip();
  5305. // Don't set its "next" if it's an "M"
  5306. if(next_seg && next_seg.type !== 2) {
  5307. seg.next = next_seg;
  5308. seg.next.prev = seg;
  5309. }
  5310. }
  5311. }
  5312. return p;
  5313. }
  5314. this.init();
  5315. // Update position of all points
  5316. this.update = function() {
  5317. if(getRotationAngle(p.elem)) {
  5318. p.matrix = getMatrix(path.elem);
  5319. p.imatrix = p.matrix.inverse();
  5320. }
  5321. p.eachSeg(function(i) {
  5322. this.item = elem.pathSegList.getItem(i);
  5323. this.update();
  5324. });
  5325. return p;
  5326. }
  5327. this.eachSeg = function(fn) {
  5328. var len = p.segs.length
  5329. for(var i=0; i < len; i++) {
  5330. var ret = fn.call(p.segs[i], i);
  5331. if(ret === false) break;
  5332. }
  5333. }
  5334. this.addSeg = function(index) {
  5335. // Adds a new segment
  5336. var seg = p.segs[index];
  5337. if(!seg.prev) return;
  5338. var prev = seg.prev;
  5339. var newseg;
  5340. switch(seg.item.pathSegType) {
  5341. case 4:
  5342. var new_x = (seg.item.x + prev.item.x) / 2;
  5343. var new_y = (seg.item.y + prev.item.y) / 2;
  5344. newseg = elem.createSVGPathSegLinetoAbs(new_x, new_y);
  5345. break;
  5346. case 6: //make it a curved segment to preserve the shape (WRS)
  5347. // http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm#Geometric_interpretation
  5348. var p0_x = (prev.item.x + seg.item.x1)/2;
  5349. var p1_x = (seg.item.x1 + seg.item.x2)/2;
  5350. var p2_x = (seg.item.x2 + seg.item.x)/2;
  5351. var p01_x = (p0_x + p1_x)/2;
  5352. var p12_x = (p1_x + p2_x)/2;
  5353. var new_x = (p01_x + p12_x)/2;
  5354. var p0_y = (prev.item.y + seg.item.y1)/2;
  5355. var p1_y = (seg.item.y1 + seg.item.y2)/2;
  5356. var p2_y = (seg.item.y2 + seg.item.y)/2;
  5357. var p01_y = (p0_y + p1_y)/2;
  5358. var p12_y = (p1_y + p2_y)/2;
  5359. var new_y = (p01_y + p12_y)/2;
  5360. newseg = elem.createSVGPathSegCurvetoCubicAbs(new_x,new_y, p0_x,p0_y, p01_x,p01_y);
  5361. var pts = [seg.item.x,seg.item.y,p12_x,p12_y,p2_x,p2_y];
  5362. replacePathSeg(seg.type,index,pts);
  5363. break;
  5364. }
  5365. insertItemBefore(elem, newseg, index);
  5366. }
  5367. this.deleteSeg = function(index) {
  5368. var seg = p.segs[index];
  5369. var list = elem.pathSegList;
  5370. seg.show(false);
  5371. var next = seg.next;
  5372. if(seg.mate) {
  5373. // Make the next point be the "M" point
  5374. var pt = [next.item.x, next.item.y];
  5375. replacePathSeg(2, next.index, pt);
  5376. // Reposition last node
  5377. replacePathSeg(4, seg.index, pt);
  5378. list.removeItem(seg.mate.index);
  5379. } else if(!seg.prev) {
  5380. // First node of open path, make next point the M
  5381. var item = seg.item;
  5382. var pt = [next.item.x, next.item.y];
  5383. replacePathSeg(2, seg.next.index, pt);
  5384. list.removeItem(index);
  5385. } else {
  5386. list.removeItem(index);
  5387. }
  5388. }
  5389. this.endChanges = function(text) {
  5390. if(isWebkit) resetD(p.elem);
  5391. var cmd = new ChangeElementCommand(elem, {d: p.last_d}, text);
  5392. addCommandToHistory(cmd);
  5393. call("changed", [elem]);
  5394. }
  5395. this.subpathIsClosed = function(index) {
  5396. var closed = false;
  5397. // Check if subpath is already open
  5398. path.eachSeg(function(i) {
  5399. if(i <= index) return true;
  5400. if(this.type === 2) {
  5401. // Found M first, so open
  5402. return false;
  5403. } else if(this.type === 1) {
  5404. // Found Z first, so closed
  5405. closed = true;
  5406. return false;
  5407. }
  5408. });
  5409. return closed;
  5410. }
  5411. this.addPtsToSelection = function(indexes) {
  5412. if(!$.isArray(indexes)) indexes = [indexes];
  5413. for(var i=0; i< indexes.length; i++) {
  5414. var index = indexes[i];
  5415. var seg = p.segs[index];
  5416. if(seg.ptgrip) {
  5417. if($.inArray(index, p.selected_pts) == -1 && index >= 0) {
  5418. p.selected_pts.push(index);
  5419. }
  5420. }
  5421. };
  5422. p.selected_pts.sort();
  5423. var i = p.selected_pts.length,
  5424. grips = new Array(i);
  5425. // Loop through points to be selected and highlight each
  5426. while(i--) {
  5427. var pt = p.selected_pts[i];
  5428. var seg = p.segs[pt];
  5429. seg.select(true);
  5430. grips[i] = seg.ptgrip;
  5431. }
  5432. // TODO: Correct this:
  5433. pathActions.canDeleteNodes = true;
  5434. pathActions.closed_subpath = p.subpathIsClosed(p.selected_pts[0]);
  5435. call("selected", grips);
  5436. }
  5437. this.removePtFromSelection = function(index) {
  5438. var pos = $.inArray(index, p.selected_pts);
  5439. if(pos == -1) {
  5440. return;
  5441. }
  5442. p.segs[index].select(false);
  5443. p.selected_pts.splice(pos, 1);
  5444. }
  5445. this.clearSelection = function() {
  5446. p.eachSeg(function(i) {
  5447. this.select(false);
  5448. });
  5449. p.selected_pts = [];
  5450. }
  5451. this.selectPt = function(pt, ctrl_num) {
  5452. p.clearSelection();
  5453. if(pt == null) {
  5454. p.eachSeg(function(i) {
  5455. if(this.prev) {
  5456. pt = i;
  5457. }
  5458. });
  5459. }
  5460. p.addPtsToSelection(pt);
  5461. if(ctrl_num) {
  5462. p.dragctrl = ctrl_num;
  5463. if(link_control_pts) {
  5464. p.segs[pt].setLinked(ctrl_num);
  5465. }
  5466. }
  5467. }
  5468. this.storeD = function() {
  5469. this.last_d = elem.getAttribute('d');
  5470. }
  5471. this.show = function(y) {
  5472. // Shows this path's segment grips
  5473. p.eachSeg(function() {
  5474. this.show(y);
  5475. });
  5476. if(y) {
  5477. p.selectPt(p.first_seg.index);
  5478. }
  5479. return p;
  5480. }
  5481. // Move selected points
  5482. this.movePts = function(d_x, d_y) {
  5483. var i = p.selected_pts.length;
  5484. while(i--) {
  5485. var seg = p.segs[p.selected_pts[i]];
  5486. seg.move(d_x, d_y);
  5487. }
  5488. }
  5489. this.moveCtrl = function(d_x, d_y) {
  5490. var seg = p.segs[p.selected_pts[0]];
  5491. seg.moveCtrl(p.dragctrl, d_x, d_y);
  5492. if(link_control_pts) {
  5493. seg.setLinked(p.dragctrl);
  5494. }
  5495. }
  5496. this.setSegType = function(new_type) {
  5497. p.storeD();
  5498. var i = p.selected_pts.length;
  5499. var text;
  5500. while(i--) {
  5501. var sel_pt = p.selected_pts[i];
  5502. // Selected seg
  5503. var cur = p.segs[sel_pt];
  5504. var prev = cur.prev;
  5505. if(!prev) continue;
  5506. if(!new_type) { // double-click, so just toggle
  5507. text = "Toggle Path Segment Type";
  5508. // Toggle segment to curve/straight line
  5509. var old_type = cur.type;
  5510. new_type = (old_type == 6) ? 4 : 6;
  5511. }
  5512. new_type = new_type-0;
  5513. var cur_x = cur.item.x;
  5514. var cur_y = cur.item.y;
  5515. var prev_x = prev.item.x;
  5516. var prev_y = prev.item.y;
  5517. var points;
  5518. switch ( new_type ) {
  5519. case 6:
  5520. if(cur.olditem) {
  5521. var old = cur.olditem;
  5522. points = [cur_x,cur_y, old.x1,old.y1, old.x2,old.y2];
  5523. } else {
  5524. var diff_x = cur_x - prev_x;
  5525. var diff_y = cur_y - prev_y;
  5526. // get control points from straight line segment
  5527. /*
  5528. var ct1_x = (prev_x + (diff_y/2));
  5529. var ct1_y = (prev_y - (diff_x/2));
  5530. var ct2_x = (cur_x + (diff_y/2));
  5531. var ct2_y = (cur_y - (diff_x/2));
  5532. */
  5533. //create control points on the line to preserve the shape (WRS)
  5534. var ct1_x = (prev_x + (diff_x/3));
  5535. var ct1_y = (prev_y + (diff_y/3));
  5536. var ct2_x = (cur_x - (diff_x/3));
  5537. var ct2_y = (cur_y - (diff_y/3));
  5538. points = [cur_x,cur_y, ct1_x,ct1_y, ct2_x,ct2_y];
  5539. }
  5540. break;
  5541. case 4:
  5542. points = [cur_x,cur_y];
  5543. // Store original prevve segment nums
  5544. cur.olditem = cur.item;
  5545. break;
  5546. }
  5547. cur.setType(new_type, points);
  5548. }
  5549. path.endChanges(text);
  5550. return;
  5551. }
  5552. }
  5553. function getPath(elem) {
  5554. var p = pathData[elem.id];
  5555. if(!p) p = pathData[elem.id] = new Path(elem);
  5556. return p;
  5557. }
  5558. var pathFuncs = [],
  5559. current_path = null,
  5560. current_path_pts = [],
  5561. link_control_pts = false,
  5562. hasMoved = false;
  5563. // This function converts a polyline (created by the fh_path tool) into
  5564. // a path element and coverts every three line segments into a single bezier
  5565. // curve in an attempt to smooth out the free-hand
  5566. var smoothPolylineIntoPath = function(element) {
  5567. var points = element.points;
  5568. var N = points.numberOfItems;
  5569. if (N >= 4) {
  5570. // loop through every 3 points and convert to a cubic bezier curve segment
  5571. //
  5572. // NOTE: this is cheating, it means that every 3 points has the potential to
  5573. // be a corner instead of treating each point in an equal manner. In general,
  5574. // this technique does not look that good.
  5575. //
  5576. // I am open to better ideas!
  5577. //
  5578. // Reading:
  5579. // - http://www.efg2.com/Lab/Graphics/Jean-YvesQueinecBezierCurves.htm
  5580. // - http://www.codeproject.com/KB/graphics/BezierSpline.aspx?msg=2956963
  5581. // - http://www.ian-ko.com/ET_GeoWizards/UserGuide/smooth.htm
  5582. // - http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-der.html
  5583. var curpos = points.getItem(0), prevCtlPt = null;
  5584. var d = [];
  5585. d.push(["M",curpos.x,",",curpos.y," C"].join(""));
  5586. for (var i = 1; i <= (N-4); i += 3) {
  5587. var ct1 = points.getItem(i);
  5588. var ct2 = points.getItem(i+1);
  5589. var end = points.getItem(i+2);
  5590. // if the previous segment had a control point, we want to smooth out
  5591. // the control points on both sides
  5592. if (prevCtlPt) {
  5593. var newpts = smoothControlPoints( prevCtlPt, ct1, curpos );
  5594. if (newpts && newpts.length == 2) {
  5595. var prevArr = d[d.length-1].split(',');
  5596. prevArr[2] = newpts[0].x;
  5597. prevArr[3] = newpts[0].y;
  5598. d[d.length-1] = prevArr.join(',');
  5599. ct1 = newpts[1];
  5600. }
  5601. }
  5602. d.push([ct1.x,ct1.y,ct2.x,ct2.y,end.x,end.y].join(','));
  5603. curpos = end;
  5604. prevCtlPt = ct2;
  5605. }
  5606. // handle remaining line segments
  5607. d.push("L");
  5608. for(;i < N;++i) {
  5609. var pt = points.getItem(i);
  5610. d.push([pt.x,pt.y].join(","));
  5611. }
  5612. d = d.join(" ");
  5613. // create new path element
  5614. element = addSvgElementFromJson({
  5615. "element": "path",
  5616. "curStyles": true,
  5617. "attr": {
  5618. "id": getId(),
  5619. "d": d,
  5620. "fill": "none"
  5621. }
  5622. });
  5623. call("changed",[element]);
  5624. }
  5625. return element;
  5626. };
  5627. // This replaces the segment at the given index. Type is given as number.
  5628. var replacePathSeg = function(type, index, pts, elem) {
  5629. var path = elem || retPath().elem;
  5630. var func = 'createSVGPathSeg' + pathFuncs[type];
  5631. var seg = path[func].apply(path, pts);
  5632. if(support.pathReplaceItem) {
  5633. path.pathSegList.replaceItem(seg, index);
  5634. } else {
  5635. var segList = path.pathSegList;
  5636. var len = segList.numberOfItems;
  5637. var arr = [];
  5638. for(var i=0; i<len; i++) {
  5639. var cur_seg = segList.getItem(i);
  5640. arr.push(cur_seg)
  5641. }
  5642. segList.clear();
  5643. for(var i=0; i<len; i++) {
  5644. if(i == index) {
  5645. segList.appendItem(seg);
  5646. } else {
  5647. segList.appendItem(arr[i]);
  5648. }
  5649. }
  5650. }
  5651. }
  5652. // If the path was rotated, we must now pay the piper:
  5653. // Every path point must be rotated into the rotated coordinate system of
  5654. // its old center, then determine the new center, then rotate it back
  5655. // This is because we want the path to remember its rotation
  5656. // TODO: This is still using ye olde transform methods, can probably
  5657. // be optimized or even taken care of by recalculateDimensions
  5658. var recalcRotatedPath = function() {
  5659. var current_path = path.elem;
  5660. var angle = getRotationAngle(current_path, true);
  5661. if(!angle) return;
  5662. selectedBBoxes[0] = path.oldbbox;
  5663. var box = getBBox(current_path),
  5664. oldbox = selectedBBoxes[0],
  5665. oldcx = oldbox.x + oldbox.width/2,
  5666. oldcy = oldbox.y + oldbox.height/2,
  5667. newcx = box.x + box.width/2,
  5668. newcy = box.y + box.height/2,
  5669. // un-rotate the new center to the proper position
  5670. dx = newcx - oldcx,
  5671. dy = newcy - oldcy,
  5672. r = Math.sqrt(dx*dx + dy*dy),
  5673. theta = Math.atan2(dy,dx) + angle;
  5674. newcx = r * Math.cos(theta) + oldcx;
  5675. newcy = r * Math.sin(theta) + oldcy;
  5676. var getRotVals = function(x, y) {
  5677. dx = x - oldcx;
  5678. dy = y - oldcy;
  5679. // rotate the point around the old center
  5680. r = Math.sqrt(dx*dx + dy*dy);
  5681. theta = Math.atan2(dy,dx) + angle;
  5682. dx = r * Math.cos(theta) + oldcx;
  5683. dy = r * Math.sin(theta) + oldcy;
  5684. // dx,dy should now hold the actual coordinates of each
  5685. // point after being rotated
  5686. // now we want to rotate them around the new center in the reverse direction
  5687. dx -= newcx;
  5688. dy -= newcy;
  5689. r = Math.sqrt(dx*dx + dy*dy);
  5690. theta = Math.atan2(dy,dx) - angle;
  5691. return {'x':(r * Math.cos(theta) + newcx)/1,
  5692. 'y':(r * Math.sin(theta) + newcy)/1};
  5693. }
  5694. var list = current_path.pathSegList,
  5695. i = list.numberOfItems;
  5696. while (i) {
  5697. i -= 1;
  5698. var seg = list.getItem(i),
  5699. type = seg.pathSegType;
  5700. if(type == 1) continue;
  5701. var rvals = getRotVals(seg.x,seg.y),
  5702. points = [rvals.x, rvals.y];
  5703. if(seg.x1 != null && seg.x2 != null) {
  5704. c_vals1 = getRotVals(seg.x1, seg.y1);
  5705. c_vals2 = getRotVals(seg.x2, seg.y2);
  5706. points.splice(points.length, 0, c_vals1.x , c_vals1.y, c_vals2.x, c_vals2.y);
  5707. }
  5708. replacePathSeg(type, i, points);
  5709. } // loop for each point
  5710. box = getBBox(current_path);
  5711. selectedBBoxes[0].x = box.x; selectedBBoxes[0].y = box.y;
  5712. selectedBBoxes[0].width = box.width; selectedBBoxes[0].height = box.height;
  5713. // now we must set the new transform to be rotated around the new center
  5714. var R_nc = svgroot.createSVGTransform(),
  5715. tlist = getTransformList(current_path);
  5716. R_nc.setRotate((angle * 180.0 / Math.PI), newcx, newcy);
  5717. tlist.replaceItem(R_nc,0);
  5718. }
  5719. return {
  5720. init: function() {
  5721. pathFuncs = [0,'ClosePath'];
  5722. var pathFuncsStrs = ['Moveto','Lineto','CurvetoCubic','CurvetoQuadratic','Arc','LinetoHorizontal','LinetoVertical','CurvetoCubicSmooth','CurvetoQuadraticSmooth'];
  5723. $.each(pathFuncsStrs,function(i,s){pathFuncs.push(s+'Abs');pathFuncs.push(s+'Rel');});
  5724. },
  5725. getPath: function() {
  5726. return path;
  5727. },
  5728. mouseDown: function(evt, mouse_target, start_x, start_y) {
  5729. if(current_mode == "path") return;
  5730. // TODO: Make sure current_path isn't null at this point
  5731. if(!path) return;
  5732. path.storeD();
  5733. var id = evt.target.id;
  5734. if (id.substr(0,14) == "pathpointgrip_") {
  5735. // Select this point
  5736. var cur_pt = path.cur_pt = parseInt(id.substr(14));
  5737. path.dragging = [start_x, start_y];
  5738. var seg = path.segs[cur_pt];
  5739. // only clear selection if shift is not pressed (otherwise, add
  5740. // node to selection)
  5741. if (!evt.shiftKey) {
  5742. if(path.selected_pts.length <= 1 || !seg.selected) {
  5743. path.clearSelection();
  5744. }
  5745. path.addPtsToSelection(cur_pt);
  5746. } else if(seg.selected) {
  5747. path.removePtFromSelection(cur_pt);
  5748. } else {
  5749. path.addPtsToSelection(cur_pt);
  5750. }
  5751. } else if(id.indexOf("ctrlpointgrip_") == 0) {
  5752. path.dragging = [start_x, start_y];
  5753. var parts = id.split('_')[1].split('c');
  5754. var cur_pt = parts[0]-0;
  5755. var ctrl_num = parts[1]-0;
  5756. path.selectPt(cur_pt, ctrl_num);
  5757. }
  5758. // Start selection box
  5759. if(!path.dragging) {
  5760. if (rubberBox == null) {
  5761. rubberBox = selectorManager.getRubberBandBox();
  5762. }
  5763. assignAttributes(rubberBox, {
  5764. 'x': start_x * current_zoom,
  5765. 'y': start_y * current_zoom,
  5766. 'width': 0,
  5767. 'height': 0,
  5768. 'display': 'inline'
  5769. }, 100);
  5770. }
  5771. },
  5772. mouseMove: function(mouse_x, mouse_y) {
  5773. hasMoved = true;
  5774. if(current_mode == "path") {
  5775. var line = getElem("path_stretch_line");
  5776. if (line) {
  5777. line.setAttribute("x2", mouse_x);
  5778. line.setAttribute("y2", mouse_y);
  5779. }
  5780. return;
  5781. }
  5782. // if we are dragging a point, let's move it
  5783. if (path.dragging) {
  5784. var pt = getPointFromGrip({
  5785. x: path.dragging[0],
  5786. y: path.dragging[1]
  5787. }, path);
  5788. var mpt = getPointFromGrip({
  5789. x: mouse_x,
  5790. y: mouse_y
  5791. }, path);
  5792. var diff_x = mpt.x - pt.x;
  5793. var diff_y = mpt.y - pt.y;
  5794. path.dragging = [mouse_x, mouse_y];
  5795. if(path.dragctrl) {
  5796. path.moveCtrl(diff_x, diff_y);
  5797. } else {
  5798. path.movePts(diff_x, diff_y);
  5799. }
  5800. } else {
  5801. path.selected_pts = [];
  5802. path.eachSeg(function(i) {
  5803. var seg = this;
  5804. if(!seg.next && !seg.prev) return;
  5805. var item = seg.item;
  5806. var rbb = rubberBox.getBBox();
  5807. var pt = getGripPt(seg);
  5808. var pt_bb = {
  5809. x: pt.x,
  5810. y: pt.y,
  5811. width: 0,
  5812. height: 0
  5813. };
  5814. var sel = Utils.rectsIntersect(rbb, pt_bb);
  5815. this.select(sel);
  5816. //Note that addPtsToSelection is not being run
  5817. if(sel) path.selected_pts.push(seg.index);
  5818. });
  5819. }
  5820. },
  5821. mouseUp: function(evt, element, mouse_x, mouse_y) {
  5822. // Create mode
  5823. if(current_mode == "path") {
  5824. var x = mouse_x/current_zoom,
  5825. y = mouse_y/current_zoom,
  5826. stretchy = getElem("path_stretch_line");
  5827. if (!stretchy) {
  5828. stretchy = document.createElementNS(svgns, "line");
  5829. assignAttributes(stretchy, {
  5830. 'id': "path_stretch_line",
  5831. 'stroke': "#22C",
  5832. 'stroke-width': "0.5"
  5833. });
  5834. stretchy = getElem("selectorParentGroup").appendChild(stretchy);
  5835. }
  5836. stretchy.setAttribute("display", "inline");
  5837. var keep = null;
  5838. // if pts array is empty, create path element with M at current point
  5839. if (current_path_pts.length == 0) {
  5840. current_path_pts.push(x);
  5841. current_path_pts.push(y);
  5842. d_attr = "M" + x + "," + y + " ";
  5843. addSvgElementFromJson({
  5844. "element": "path",
  5845. "curStyles": true,
  5846. "attr": {
  5847. "d": d_attr,
  5848. "id": getNextId(),
  5849. "opacity": cur_shape.opacity / 2,
  5850. }
  5851. });
  5852. // set stretchy line to first point
  5853. assignAttributes(stretchy, {
  5854. 'x1': mouse_x,
  5855. 'y1': mouse_y,
  5856. 'x2': mouse_x,
  5857. 'y2': mouse_y
  5858. });
  5859. var index = subpath ? path.segs.length : 0;
  5860. addPointGrip(index, mouse_x, mouse_y);
  5861. }
  5862. else {
  5863. // determine if we clicked on an existing point
  5864. var i = current_path_pts.length;
  5865. var FUZZ = 6/current_zoom;
  5866. var clickOnPoint = false;
  5867. while(i) {
  5868. i -= 2;
  5869. var px = current_path_pts[i], py = current_path_pts[i+1];
  5870. // found a matching point
  5871. if ( x >= (px-FUZZ) && x <= (px+FUZZ) && y >= (py-FUZZ) && y <= (py+FUZZ) ) {
  5872. clickOnPoint = true;
  5873. break;
  5874. }
  5875. }
  5876. // get path element that we are in the process of creating
  5877. var id = getId();
  5878. // Remove previous path object if previously created
  5879. if(id in pathData) delete pathData[id];
  5880. var newpath = getElem(id);
  5881. var len = current_path_pts.length;
  5882. // if we clicked on an existing point, then we are done this path, commit it
  5883. // (i,i+1) are the x,y that were clicked on
  5884. if (clickOnPoint) {
  5885. // if clicked on any other point but the first OR
  5886. // the first point was clicked on and there are less than 3 points
  5887. // then leave the path open
  5888. // otherwise, close the path
  5889. if (i == 0 && len >= 6) {
  5890. // Create end segment
  5891. var abs_x = current_path_pts[0];
  5892. var abs_y = current_path_pts[1];
  5893. d_attr += ['L',abs_x,',',abs_y,'z'].join('');
  5894. newpath.setAttribute("d", d_attr);
  5895. } else if(len < 3) {
  5896. keep = false;
  5897. return keep;
  5898. }
  5899. $(stretchy).remove();
  5900. // this will signal to commit the path
  5901. element = newpath;
  5902. current_path_pts = [];
  5903. started = false;
  5904. if(subpath) {
  5905. if(path.matrix) {
  5906. remapElement(newpath, {}, path.matrix.inverse());
  5907. }
  5908. var new_d = newpath.getAttribute("d");
  5909. var orig_d = $(path.elem).attr("d");
  5910. $(path.elem).attr("d", orig_d + new_d);
  5911. $(newpath).remove();
  5912. if(path.matrix) {
  5913. recalcRotatedPath();
  5914. }
  5915. path.init();
  5916. pathActions.toEditMode(path.elem);
  5917. path.selectPt();
  5918. return false;
  5919. }
  5920. }
  5921. // else, create a new point, append to pts array, update path element
  5922. else {
  5923. // Checks if current target or parents are #svgcontent
  5924. if(!$.contains(container, getMouseTarget(evt))) {
  5925. // Clicked outside canvas, so don't make point
  5926. console.log("Clicked outside canvas");
  5927. return false;
  5928. }
  5929. var lastx = current_path_pts[len-2], lasty = current_path_pts[len-1];
  5930. if(evt.shiftKey) { var xya=Utils.snapToAngle(lastx,lasty,x,y); x=xya.x; y=xya.y; }
  5931. // we store absolute values in our path points array for easy checking above
  5932. current_path_pts.push(x);
  5933. current_path_pts.push(y);
  5934. d_attr += "L" + round(x) + "," + round(y) + " ";
  5935. newpath.setAttribute("d", d_attr);
  5936. x *= current_zoom;
  5937. y *= current_zoom;
  5938. // set stretchy line to latest point
  5939. assignAttributes(stretchy, {
  5940. 'x1': x,
  5941. 'y1': y,
  5942. 'x2': x,
  5943. 'y2': y
  5944. });
  5945. var index = (current_path_pts.length/2 - 1);
  5946. if(subpath) index += path.segs.length;
  5947. addPointGrip(index, x, y);
  5948. }
  5949. keep = true;
  5950. }
  5951. return {
  5952. keep: keep,
  5953. element: element
  5954. }
  5955. }
  5956. // Edit mode
  5957. if (path.dragging) {
  5958. var last_pt = path.cur_pt;
  5959. path.dragging = false;
  5960. path.dragctrl = false;
  5961. path.update();
  5962. if(hasMoved) {
  5963. path.endChanges("Move path point(s)");
  5964. }
  5965. if(!evt.shiftKey && !hasMoved) {
  5966. path.selectPt(last_pt);
  5967. }
  5968. }
  5969. else if(rubberBox && rubberBox.getAttribute('display') != 'none') {
  5970. // Done with multi-node-select
  5971. rubberBox.setAttribute("display", "none");
  5972. if(rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) {
  5973. pathActions.toSelectMode(evt.target);
  5974. }
  5975. // else, move back to select mode
  5976. } else {
  5977. pathActions.toSelectMode(evt.target);
  5978. }
  5979. hasMoved = false;
  5980. },
  5981. clearData: function() {
  5982. pathData = {};
  5983. },
  5984. toEditMode: function(element) {
  5985. path = getPath(element);
  5986. current_mode = "pathedit";
  5987. clearSelection();
  5988. path.show(true).update();
  5989. path.oldbbox = getBBox(path.elem);
  5990. subpath = false;
  5991. },
  5992. toSelectMode: function(elem) {
  5993. var selPath = (elem == path.elem);
  5994. current_mode = "select";
  5995. path.show(false);
  5996. current_path = false;
  5997. clearSelection();
  5998. if(path.matrix) {
  5999. // Rotated, so may need to re-calculate the center
  6000. recalcRotatedPath();
  6001. }
  6002. if(selPath) {
  6003. call("selected", [elem]);
  6004. addToSelection([elem], true);
  6005. }
  6006. },
  6007. addSubPath: function(on) {
  6008. if(on) {
  6009. // Internally we go into "path" mode, but in the UI it will
  6010. // still appear as if in "pathedit" mode.
  6011. current_mode = "path";
  6012. subpath = true;
  6013. } else {
  6014. pathActions.clear(true);
  6015. pathActions.toEditMode(path.elem);
  6016. }
  6017. },
  6018. select: function(target) {
  6019. if (current_path == target) {
  6020. pathActions.toEditMode(target);
  6021. current_mode = "pathedit";
  6022. } // going into pathedit mode
  6023. else {
  6024. current_path = target;
  6025. }
  6026. },
  6027. reorient: function() {
  6028. var elem = selectedElements[0];
  6029. if(!elem) return;
  6030. var angle = getRotationAngle(elem);
  6031. if(angle == 0) return;
  6032. var batchCmd = new BatchCommand("Reorient path");
  6033. var changes = {
  6034. d: elem.getAttribute('d'),
  6035. transform: elem.getAttribute('transform')
  6036. };
  6037. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  6038. clearSelection();
  6039. this.resetOrientation(elem);
  6040. addCommandToHistory(batchCmd);
  6041. // Set matrix to null
  6042. getPath(elem).show(false).matrix = null;
  6043. this.clear();
  6044. addToSelection([elem], true);
  6045. call("changed", selectedElements);
  6046. },
  6047. clear: function(remove) {
  6048. current_path = null;
  6049. if (current_mode == "path" && current_path_pts.length > 0) {
  6050. var elem = getElem(getId());
  6051. $(getElem("path_stretch_line")).remove();
  6052. $(elem).remove();
  6053. $(getElem("pathpointgrip_container")).find('*').attr('display', 'none');
  6054. current_path_pts = [];
  6055. started = false;
  6056. } else if (current_mode == "pathedit") {
  6057. this.toSelectMode();
  6058. }
  6059. if(path) path.init().show(false);
  6060. },
  6061. resetOrientation: function(path) {
  6062. if(path == null || path.nodeName != 'path') return false;
  6063. var tlist = getTransformList(path);
  6064. var m = transformListToTransform(tlist).matrix;
  6065. tlist.clear();
  6066. path.removeAttribute("transform");
  6067. var segList = path.pathSegList;
  6068. // Opera/win/non-EN throws an error here.
  6069. // TODO: Find out why!
  6070. // Presumed fixed in Opera 10.5, so commented out for now
  6071. // try {
  6072. var len = segList.numberOfItems;
  6073. // } catch(err) {
  6074. // var fixed_d = pathActions.convertPath(path);
  6075. // path.setAttribute('d', fixed_d);
  6076. // segList = path.pathSegList;
  6077. // var len = segList.numberOfItems;
  6078. // }
  6079. for (var i = 0; i < len; ++i) {
  6080. var seg = segList.getItem(i);
  6081. var type = seg.pathSegType;
  6082. if(type == 1) continue;
  6083. var pts = [];
  6084. $.each(['',1,2], function(j, n) {
  6085. var x = seg['x'+n], y = seg['y'+n];
  6086. if(x && y) {
  6087. var pt = transformPoint(x, y, m);
  6088. pts.splice(pts.length, 0, pt.x, pt.y);
  6089. }
  6090. });
  6091. replacePathSeg(type, i, pts, path);
  6092. }
  6093. },
  6094. zoomChange: function() {
  6095. if(current_mode == "pathedit") {
  6096. path.update();
  6097. }
  6098. },
  6099. getNodePoint: function() {
  6100. var sel_pt = path.selected_pts.length ? path.selected_pts[0] : 1;
  6101. var seg = path.segs[sel_pt];
  6102. return {
  6103. x: seg.item.x,
  6104. y: seg.item.y,
  6105. type: seg.type
  6106. };
  6107. },
  6108. linkControlPoints: function(linkPoints) {
  6109. link_control_pts = linkPoints;
  6110. },
  6111. clonePathNode: function() {
  6112. path.storeD();
  6113. var sel_pts = path.selected_pts;
  6114. var segs = path.segs;
  6115. var i = sel_pts.length;
  6116. var nums = [];
  6117. while(i--) {
  6118. var pt = sel_pts[i];
  6119. path.addSeg(pt);
  6120. nums.push(pt + i);
  6121. nums.push(pt + i + 1);
  6122. }
  6123. path.init().addPtsToSelection(nums);
  6124. path.endChanges("Clone path node(s)");
  6125. },
  6126. opencloseSubPath: function() {
  6127. var sel_pts = path.selected_pts;
  6128. // Only allow one selected node for now
  6129. if(sel_pts.length !== 1) return;
  6130. var elem = path.elem;
  6131. var list = elem.pathSegList;
  6132. var len = list.numberOfItems;
  6133. var index = sel_pts[0];
  6134. var open_pt = null;
  6135. var start_item = null;
  6136. // Check if subpath is already open
  6137. path.eachSeg(function(i) {
  6138. if(this.type === 2 && i <= index) {
  6139. start_item = this.item;
  6140. }
  6141. if(i <= index) return true;
  6142. if(this.type === 2) {
  6143. // Found M first, so open
  6144. open_pt = i;
  6145. return false;
  6146. } else if(this.type === 1) {
  6147. // Found Z first, so closed
  6148. open_pt = false;
  6149. return false;
  6150. }
  6151. });
  6152. if(open_pt == null) {
  6153. // Single path, so close last seg
  6154. open_pt = path.segs.length - 1;
  6155. }
  6156. if(open_pt !== false) {
  6157. // Close this path
  6158. // Create a line going to the previous "M"
  6159. var newseg = elem.createSVGPathSegLinetoAbs(start_item.x, start_item.y);
  6160. var closer = elem.createSVGPathSegClosePath();
  6161. if(open_pt == path.segs.length - 1) {
  6162. list.appendItem(newseg);
  6163. list.appendItem(closer);
  6164. } else {
  6165. insertItemBefore(elem, closer, open_pt);
  6166. insertItemBefore(elem, newseg, open_pt);
  6167. }
  6168. path.init().selectPt(open_pt+1);
  6169. return;
  6170. }
  6171. // M 1,1 L 2,2 L 3,3 L 1,1 z // open at 2,2
  6172. // M 2,2 L 3,3 L 1,1
  6173. // M 1,1 L 2,2 L 1,1 z M 4,4 L 5,5 L6,6 L 5,5 z
  6174. // M 1,1 L 2,2 L 1,1 z [M 4,4] L 5,5 L(M)6,6 L 5,5 z
  6175. var seg = path.segs[index];
  6176. if(seg.mate) {
  6177. list.removeItem(index); // Removes last "L"
  6178. list.removeItem(index); // Removes the "Z"
  6179. path.init().selectPt(index - 1);
  6180. return;
  6181. }
  6182. var last_m, z_seg;
  6183. // Find this sub-path's closing point and remove
  6184. for(var i=0; i<list.numberOfItems; i++) {
  6185. var item = list.getItem(i);
  6186. if(item.pathSegType === 2) {
  6187. // Find the preceding M
  6188. last_m = i;
  6189. } else if(i === index) {
  6190. // Remove it
  6191. list.removeItem(last_m);
  6192. // index--;
  6193. } else if(item.pathSegType === 1 && index < i) {
  6194. // Remove the closing seg of this subpath
  6195. z_seg = i-1;
  6196. list.removeItem(i);
  6197. break;
  6198. }
  6199. }
  6200. var num = (index - last_m) - 1;
  6201. while(num--) {
  6202. insertItemBefore(elem, list.getItem(last_m), z_seg);
  6203. }
  6204. var pt = list.getItem(last_m);
  6205. // Make this point the new "M"
  6206. replacePathSeg(2, last_m, [pt.x, pt.y]);
  6207. var i = index
  6208. path.init().selectPt(0);
  6209. },
  6210. deletePathNode: function() {
  6211. if(!pathActions.canDeleteNodes) return;
  6212. path.storeD();
  6213. var sel_pts = path.selected_pts;
  6214. var i = sel_pts.length;
  6215. while(i--) {
  6216. var pt = sel_pts[i];
  6217. path.deleteSeg(pt);
  6218. }
  6219. // Cleanup
  6220. var cleanup = function() {
  6221. var segList = path.elem.pathSegList;
  6222. var len = segList.numberOfItems;
  6223. var remItems = function(pos, count) {
  6224. while(count--) {
  6225. segList.removeItem(pos);
  6226. }
  6227. }
  6228. if(len <= 1) return true;
  6229. while(len--) {
  6230. var item = segList.getItem(len);
  6231. if(item.pathSegType === 1) {
  6232. var prev = segList.getItem(len-1);
  6233. var nprev = segList.getItem(len-2);
  6234. if(prev.pathSegType === 2) {
  6235. remItems(len-1, 2);
  6236. cleanup();
  6237. break;
  6238. } else if(nprev.pathSegType === 2) {
  6239. remItems(len-2, 3);
  6240. cleanup();
  6241. break;
  6242. }
  6243. } else if(item.pathSegType === 2) {
  6244. if(len > 0) {
  6245. var prev_type = segList.getItem(len-1).pathSegType;
  6246. // Path has M M
  6247. if(prev_type === 2) {
  6248. remItems(len-1, 1);
  6249. cleanup();
  6250. break;
  6251. // Entire path ends with Z M
  6252. } else if(prev_type === 1 && segList.numberOfItems-1 === len) {
  6253. remItems(len, 1);
  6254. cleanup();
  6255. break;
  6256. }
  6257. }
  6258. }
  6259. }
  6260. return false;
  6261. }
  6262. cleanup();
  6263. // Completely delete a path with 1 or 0 segments
  6264. if(path.elem.pathSegList.numberOfItems <= 1) {
  6265. pathActions.toSelectMode(path.elem);
  6266. canvas.deleteSelectedElements();
  6267. return;
  6268. }
  6269. path.init();
  6270. path.clearSelection();
  6271. // TODO: Find right way to select point now
  6272. // path.selectPt(sel_pt);
  6273. if(window.opera) { // Opera repaints incorrectly
  6274. var cp = $(path.elem); cp.attr('d',cp.attr('d'));
  6275. }
  6276. path.endChanges("Delete path node(s)");
  6277. },
  6278. smoothPolylineIntoPath: smoothPolylineIntoPath,
  6279. setSegType: function(v) {
  6280. path.setSegType(v);
  6281. },
  6282. moveNode: function(attr, newValue) {
  6283. var sel_pts = path.selected_pts;
  6284. if(!sel_pts.length) return;
  6285. path.storeD();
  6286. // Get first selected point
  6287. var seg = path.segs[sel_pts[0]];
  6288. var diff = {x:0, y:0};
  6289. diff[attr] = newValue - seg.item[attr];
  6290. seg.move(diff.x, diff.y);
  6291. path.endChanges("Move path point");
  6292. },
  6293. fixEnd: function(elem) {
  6294. // Adds an extra segment if the last seg before a Z doesn't end
  6295. // at its M point
  6296. // M0,0 L0,100 L100,100 z
  6297. var segList = elem.pathSegList;
  6298. var len = segList.numberOfItems;
  6299. var last_m;
  6300. for (var i = 0; i < len; ++i) {
  6301. var item = segList.getItem(i);
  6302. if(item.pathSegType === 2) {
  6303. last_m = item;
  6304. }
  6305. if(item.pathSegType === 1) {
  6306. var prev = segList.getItem(i-1);
  6307. if(prev.x != last_m.x || prev.y != last_m.y) {
  6308. // Add an L segment here
  6309. var newseg = elem.createSVGPathSegLinetoAbs(last_m.x, last_m.y);
  6310. insertItemBefore(elem, newseg, i);
  6311. // Can this be done better?
  6312. pathActions.fixEnd(elem);
  6313. break;
  6314. }
  6315. }
  6316. }
  6317. if(isWebkit) resetD(elem);
  6318. },
  6319. // Convert a path to one with only absolute or relative values
  6320. convertPath: function(path, toRel) {
  6321. var segList = path.pathSegList;
  6322. var len = segList.numberOfItems;
  6323. var curx = 0, cury = 0;
  6324. var d = "";
  6325. var last_m = null;
  6326. for (var i = 0; i < len; ++i) {
  6327. var seg = segList.getItem(i);
  6328. // if these properties are not in the segment, set them to zero
  6329. var x = seg.x || 0,
  6330. y = seg.y || 0,
  6331. x1 = seg.x1 || 0,
  6332. y1 = seg.y1 || 0,
  6333. x2 = seg.x2 || 0,
  6334. y2 = seg.y2 || 0;
  6335. var type = seg.pathSegType;
  6336. var letter = pathMap[type]['to'+(toRel?'Lower':'Upper')+'Case']();
  6337. var addToD = function(pnts, more, last) {
  6338. var str = '';
  6339. var more = more?' '+more.join(' '):'';
  6340. var last = last?shortFloat(last):'';
  6341. $.each(pnts, function(i, pnt) {
  6342. pnts[i] = shortFloat(pnt);
  6343. });
  6344. d += letter + pnts.join(' ') + more + last;
  6345. }
  6346. switch (type) {
  6347. case 1: // z,Z closepath (Z/z)
  6348. d += "z";
  6349. break;
  6350. case 12: // absolute horizontal line (H)
  6351. x -= curx;
  6352. case 13: // relative horizontal line (h)
  6353. if(toRel) {
  6354. curx += x;
  6355. } else {
  6356. x += curx;
  6357. curx = x;
  6358. }
  6359. addToD([[x]]);
  6360. break;
  6361. case 14: // absolute vertical line (V)
  6362. y -= cury;
  6363. case 15: // relative vertical line (v)
  6364. if(toRel) {
  6365. cury += y;
  6366. } else {
  6367. y += cury;
  6368. cury = y;
  6369. }
  6370. addToD([[y]]);
  6371. break;
  6372. case 2: // absolute move (M)
  6373. case 4: // absolute line (L)
  6374. case 18: // absolute smooth quad (T)
  6375. x -= curx;
  6376. y -= cury;
  6377. case 5: // relative line (l)
  6378. case 3: // relative move (m)
  6379. // If the last segment was a "z", this must be relative to
  6380. if(last_m && segList.getItem(i-1).pathSegType === 1 && !toRel) {
  6381. curx = last_m[0];
  6382. cury = last_m[1];
  6383. }
  6384. case 19: // relative smooth quad (t)
  6385. if(toRel) {
  6386. curx += x;
  6387. cury += y;
  6388. } else {
  6389. x += curx;
  6390. y += cury;
  6391. curx = x;
  6392. cury = y;
  6393. }
  6394. if(type === 3) last_m = [curx, cury];
  6395. addToD([[x,y]]);
  6396. break;
  6397. case 6: // absolute cubic (C)
  6398. x -= curx; x1 -= curx; x2 -= curx;
  6399. y -= cury; y1 -= cury; y2 -= cury;
  6400. case 7: // relative cubic (c)
  6401. if(toRel) {
  6402. curx += x;
  6403. cury += y;
  6404. } else {
  6405. x += curx; x1 += curx; x2 += curx;
  6406. y += cury; y1 += cury; y2 += cury;
  6407. curx = x;
  6408. cury = y;
  6409. }
  6410. addToD([[x1,y1],[x2,y2],[x,y]]);
  6411. break;
  6412. case 8: // absolute quad (Q)
  6413. x -= curx; x1 -= curx;
  6414. y -= cury; y1 -= cury;
  6415. case 9: // relative quad (q)
  6416. if(toRel) {
  6417. curx += x;
  6418. cury += y;
  6419. } else {
  6420. x += curx; x1 += curx;
  6421. y += cury; y1 += cury;
  6422. curx = x;
  6423. cury = y;
  6424. }
  6425. addToD([[x1,y1],[x,y]]);
  6426. break;
  6427. case 10: // absolute elliptical arc (A)
  6428. x -= curx;
  6429. y -= cury;
  6430. case 11: // relative elliptical arc (a)
  6431. if(toRel) {
  6432. curx += x;
  6433. cury += y;
  6434. } else {
  6435. x += curx;
  6436. y += cury;
  6437. curx = x;
  6438. cury = y;
  6439. }
  6440. addToD([[seg.r1,seg.r2]], [
  6441. seg.angle,
  6442. (seg.largeArcFlag ? 1 : 0),
  6443. (seg.sweepFlag ? 1 : 0)
  6444. ],[x,y]
  6445. );
  6446. break;
  6447. case 16: // absolute smooth cubic (S)
  6448. x -= curx; x2 -= curx;
  6449. y -= cury; y2 -= cury;
  6450. case 17: // relative smooth cubic (s)
  6451. if(toRel) {
  6452. curx += x;
  6453. cury += y;
  6454. } else {
  6455. x += curx; x2 += curx;
  6456. y += cury; y2 += cury;
  6457. curx = x;
  6458. cury = y;
  6459. }
  6460. addToD([[x2,y2],[x,y]]);
  6461. break;
  6462. } // switch on path segment type
  6463. } // for each segment
  6464. return d;
  6465. }
  6466. }
  6467. }();
  6468. pathActions.init();
  6469. // Group: Serialization
  6470. // Function: removeUnusedDefElems
  6471. // Looks at DOM elements inside the <defs> to see if they are referred to,
  6472. // removes them from the DOM if they are not.
  6473. //
  6474. // Returns:
  6475. // The amount of elements that were removed
  6476. var removeUnusedDefElems = this.removeUnusedDefElems = function() {
  6477. var defs = svgcontent.getElementsByTagNameNS(svgns, "defs");
  6478. if(!defs || !defs.length) return 0;
  6479. var defelem_uses = [],
  6480. numRemoved = 0;
  6481. var attrs = ['fill', 'stroke', 'filter', 'marker-start', 'marker-mid', 'marker-end'];
  6482. var alen = attrs.length;
  6483. var all_els = svgcontent.getElementsByTagNameNS(svgns, '*');
  6484. var all_len = all_els.length;
  6485. for(var i=0; i<all_len; i++) {
  6486. var el = all_els[i];
  6487. for(var j = 0; j < alen; j++) {
  6488. var ref = getUrlFromAttr(el.getAttribute(attrs[j]));
  6489. if(ref) defelem_uses.push(ref.substr(1));
  6490. }
  6491. // gradients can refer to other gradients
  6492. var href = el.getAttributeNS(xlinkns, "href");
  6493. if (href && href.indexOf('#') == 0) {
  6494. defelem_uses.push(href.substr(1));
  6495. }
  6496. };
  6497. var defelems = $(svgcontent).find("linearGradient, radialGradient, filter, marker");
  6498. defelem_ids = [],
  6499. i = defelems.length;
  6500. while (i--) {
  6501. var defelem = defelems[i];
  6502. var id = defelem.id;
  6503. if($.inArray(id, defelem_uses) == -1) {
  6504. // Not found, so remove
  6505. defelem.parentNode.removeChild(defelem);
  6506. numRemoved++;
  6507. }
  6508. }
  6509. // Remove defs if empty
  6510. var i = defs.length;
  6511. while (i--) {
  6512. var def = defs[i];
  6513. if(!def.getElementsByTagNameNS(svgns,'*').length) {
  6514. def.parentNode.removeChild(def);
  6515. }
  6516. }
  6517. return numRemoved;
  6518. }
  6519. // Function: svgCanvasToString
  6520. // Main function to set up the SVG content for output
  6521. //
  6522. // Returns:
  6523. // String containing the SVG image for output
  6524. var svgCanvasToString = this.svgCanvasToString = function() {
  6525. // keep calling it until there are none to remove
  6526. while (removeUnusedDefElems() > 0) {};
  6527. pathActions.clear(true);
  6528. // Keep SVG-Edit comment on top
  6529. $.each(svgcontent.childNodes, function(i, node) {
  6530. if(i && node.nodeType == 8 && node.data.indexOf('Created with') != -1) {
  6531. svgcontent.insertBefore(node, svgcontent.firstChild);
  6532. }
  6533. });
  6534. var output = svgToString(svgcontent, 0);
  6535. return output;
  6536. }
  6537. // Function: svgToString
  6538. // Sub function ran on each SVG element to convert it to a string as desired
  6539. //
  6540. // Parameters:
  6541. // elem - The SVG element to convert
  6542. // indent - Integer with the amount of spaces to indent this tag
  6543. //
  6544. // Returns:
  6545. // String with the given element as an SVG tag
  6546. var svgToString = this.svgToString = function(elem, indent) {
  6547. var out = new Array(), toXml = Utils.toXml;
  6548. if (elem) {
  6549. cleanupElement(elem);
  6550. var attrs = elem.attributes,
  6551. attr,
  6552. i,
  6553. childs = elem.childNodes;
  6554. for (var i=0; i<indent; i++) out.push(" ");
  6555. out.push("<"); out.push(elem.nodeName);
  6556. if(elem.id == 'svgcontent') {
  6557. // Process root element separately
  6558. var res = getResolution();
  6559. out.push(' width="' + res.w + '" height="' + res.h + '" xmlns="'+svgns+'"');
  6560. var nsuris = {};
  6561. // Check elements for namespaces, add if found
  6562. $(elem).find('*').andSelf().each(function() {
  6563. var el = this;
  6564. $.each(this.attributes, function(i, attr) {
  6565. var uri = attr.namespaceURI;
  6566. if(uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) {
  6567. nsuris[uri] = true;
  6568. out.push(" xmlns:" + nsMap[uri] + '="' + uri +'"');
  6569. }
  6570. });
  6571. });
  6572. var i = attrs.length;
  6573. while (i--) {
  6574. attr = attrs.item(i);
  6575. var attrVal = toXml(attr.nodeValue);
  6576. // Namespaces have already been dealt with, so skip
  6577. if(attr.nodeName.indexOf('xmlns:') === 0) continue;
  6578. // only serialize attributes we don't use internally
  6579. if (attrVal != "" &&
  6580. $.inArray(attr.localName, ['width','height','xmlns','x','y','viewBox','id','overflow']) == -1)
  6581. {
  6582. if(!attr.namespaceURI || nsMap[attr.namespaceURI]) {
  6583. out.push(' ');
  6584. out.push(attr.nodeName); out.push("=\"");
  6585. out.push(attrVal); out.push("\"");
  6586. }
  6587. }
  6588. }
  6589. } else {
  6590. for (var i=attrs.length-1; i>=0; i--) {
  6591. attr = attrs.item(i);
  6592. var attrVal = toXml(attr.nodeValue);
  6593. //remove bogus attributes added by Gecko
  6594. if ($.inArray(attr.localName, ['-moz-math-font-style', '_moz-math-font-style']) !== -1) continue;
  6595. if (attrVal != "") {
  6596. if(attrVal.indexOf('pointer-events') == 0) continue;
  6597. if(attr.localName == "class" && attrVal.indexOf('se_') == 0) continue;
  6598. out.push(" ");
  6599. if(attr.localName == 'd') attrVal = pathActions.convertPath(elem, true);
  6600. if(!isNaN(attrVal)) {
  6601. attrVal = shortFloat(attrVal);
  6602. }
  6603. // Embed images when saving
  6604. if(save_options.apply
  6605. && elem.nodeName == 'image'
  6606. && attr.localName == 'href'
  6607. && save_options.images
  6608. && save_options.images == 'embed')
  6609. {
  6610. var img = encodableImages[attrVal];
  6611. if(img) attrVal = img;
  6612. }
  6613. // map various namespaces to our fixed namespace prefixes
  6614. // (the default xmlns attribute itself does not get a prefix)
  6615. if(!attr.namespaceURI || attr.namespaceURI == svgns || nsMap[attr.namespaceURI]) {
  6616. out.push(attr.nodeName); out.push("=\"");
  6617. out.push(attrVal); out.push("\"");
  6618. }
  6619. }
  6620. }
  6621. }
  6622. if (elem.hasChildNodes()) {
  6623. out.push(">");
  6624. indent++;
  6625. var bOneLine = false;
  6626. for (var i=0; i<childs.length; i++)
  6627. {
  6628. var child = childs.item(i);
  6629. switch(child.nodeType) {
  6630. case 1: // element node
  6631. out.push("\n");
  6632. out.push(svgToString(childs.item(i), indent));
  6633. break;
  6634. case 3: // text node
  6635. var str = child.nodeValue.replace(/^\s+|\s+$/g, "");
  6636. if (str != "") {
  6637. bOneLine = true;
  6638. out.push(toXml(str) + "");
  6639. }
  6640. break;
  6641. case 8: // comment
  6642. out.push("\n");
  6643. out.push(new Array(indent+1).join(" "));
  6644. out.push("<!--");
  6645. out.push(child.data);
  6646. out.push("-->");
  6647. break;
  6648. } // switch on node type
  6649. }
  6650. indent--;
  6651. if (!bOneLine) {
  6652. out.push("\n");
  6653. for (var i=0; i<indent; i++) out.push(" ");
  6654. }
  6655. out.push("</"); out.push(elem.nodeName); out.push(">");
  6656. } else {
  6657. out.push("/>");
  6658. }
  6659. }
  6660. return out.join('');
  6661. }; // end svgToString()
  6662. // Function: embedImage
  6663. // Converts a given image file to a data URL when possible, then runs a given callback
  6664. //
  6665. // Parameters:
  6666. // val - String with the path/URL of the image
  6667. // callback - Optional function to run when image data is found, supplies the
  6668. // result (data URL or false) as first parameter.
  6669. this.embedImage = function(val, callback) {
  6670. // load in the image and once it's loaded, get the dimensions
  6671. $(new Image()).load(function() {
  6672. // create a canvas the same size as the raster image
  6673. var canvas = document.createElement("canvas");
  6674. canvas.width = this.width;
  6675. canvas.height = this.height;
  6676. // load the raster image into the canvas
  6677. canvas.getContext("2d").drawImage(this,0,0);
  6678. // retrieve the data: URL
  6679. try {
  6680. var urldata = ';svgedit_url=' + encodeURIComponent(val);
  6681. urldata = canvas.toDataURL().replace(';base64',urldata+';base64');
  6682. encodableImages[val] = urldata;
  6683. } catch(e) {
  6684. encodableImages[val] = false;
  6685. }
  6686. last_good_img_url = val;
  6687. if(callback) callback(encodableImages[val]);
  6688. }).attr('src',val);
  6689. }
  6690. // Function: setGoodImage
  6691. // Sets a given URL to be a "last good image" URL
  6692. this.setGoodImage = function(val) {
  6693. last_good_img_url = val;
  6694. }
  6695. this.open = function() {
  6696. // Nothing by default, handled by optional widget/extension
  6697. };
  6698. // Function: save
  6699. // Serializes the current drawing into SVG XML text and returns it to the 'saved' handler.
  6700. // This function also includes the XML prolog. Clients of the SvgCanvas bind their save
  6701. // function to the 'saved' event.
  6702. //
  6703. // Returns:
  6704. // Nothing
  6705. this.save = function(opts) {
  6706. // remove the selected outline before serializing
  6707. clearSelection();
  6708. // Update save options if provided
  6709. if(opts) $.extend(save_options, opts);
  6710. save_options.apply = true;
  6711. // no need for doctype, see http://jwatt.org/svg/authoring/#doctype-declaration
  6712. var str = svgCanvasToString();
  6713. call("saved", str);
  6714. };
  6715. // Function: rasterExport
  6716. // Generates a PNG Data URL based on the current image, then calls "exported"
  6717. // with an object including the string and any issues found
  6718. this.rasterExport = function() {
  6719. // remove the selected outline before serializing
  6720. clearSelection();
  6721. // Check for known CanVG issues
  6722. var issues = [];
  6723. // Selector and notice
  6724. var issue_list = {
  6725. 'feGaussianBlur': uiStrings.exportNoBlur,
  6726. 'image': uiStrings.exportNoImage,
  6727. 'foreignObject': uiStrings.exportNoforeignObject,
  6728. '[stroke-dasharray]': uiStrings.exportNoDashArray
  6729. };
  6730. var content = $(svgcontent);
  6731. // Add font/text check if Canvas Text API is not implemented
  6732. if(!("font" in $('<canvas>')[0].getContext('2d'))) {
  6733. issue_list['text'] = uiStrings.exportNoText;
  6734. }
  6735. $.each(issue_list, function(sel, descr) {
  6736. if(content.find(sel).length) {
  6737. issues.push(descr);
  6738. }
  6739. });
  6740. var str = svgCanvasToString();
  6741. call("exported", {svg: str, issues: issues});
  6742. };
  6743. // Function: getSvgString
  6744. // Returns the current drawing as raw SVG XML text.
  6745. //
  6746. // Returns:
  6747. // The current drawing as raw SVG XML text.
  6748. this.getSvgString = function() {
  6749. save_options.apply = false;
  6750. return svgCanvasToString();
  6751. };
  6752. //function randomizeIds
  6753. // This function determines whether to add a nonce to the prefix, when
  6754. // generating IDs in SVG-Edit
  6755. //
  6756. // Parameters:
  6757. // an opional boolean, which, if true, adds a nonce to the prefix. Thus
  6758. // svgCanvas.randomizeIds() <==> svgCanvas.randomizeIds(true)
  6759. //
  6760. // if you're controlling SVG-Edit externally, and want randomized IDs, call
  6761. // this BEFORE calling svgCanvas.setSvgString
  6762. //
  6763. this.randomizeIds = function() {
  6764. if (arguments.length > 0 && arguments[0] == false) {
  6765. randomize_ids = false;
  6766. if (extensions["Arrows"]) call("unsetarrownonce") ;
  6767. } else {
  6768. randomize_ids = true;
  6769. if (!svgcontent.getAttributeNS(se_ns, 'nonce')) {
  6770. svgcontent.setAttributeNS(se_ns, 'se:nonce', nonce);
  6771. if (extensions["Arrows"]) call("setarrownonce", nonce) ;
  6772. }
  6773. }
  6774. }
  6775. //
  6776. // Function: setSvgString
  6777. // This function sets the current drawing as the input SVG XML.
  6778. //
  6779. // Parameters:
  6780. // xmlString - The SVG as XML text.
  6781. //
  6782. // Returns:
  6783. // This function returns false if the set was unsuccessful, true otherwise.
  6784. this.setSvgString = function(xmlString) {
  6785. try {
  6786. // convert string into XML document
  6787. var newDoc = Utils.text2xml(xmlString);
  6788. // run it through our sanitizer to remove anything we do not support
  6789. sanitizeSvg(newDoc.documentElement);
  6790. var batchCmd = new BatchCommand("Change Source");
  6791. // remove old svg document
  6792. var oldzoom = svgroot.removeChild(svgcontent);
  6793. batchCmd.addSubCommand(new RemoveElementCommand(oldzoom, svgroot));
  6794. // set new svg document
  6795. svgcontent = svgroot.appendChild(svgdoc.importNode(newDoc.documentElement, true));
  6796. // retrieve or set the nonce
  6797. n = svgcontent.getAttributeNS(se_ns, 'nonce');
  6798. if (n) {
  6799. randomize_ids = true;
  6800. nonce = n;
  6801. if (extensions["Arrows"]) call("setarrownonce", n) ;
  6802. } else if (randomize_ids) {
  6803. svgcontent.setAttributeNS(xmlnsns, 'xmlns:se', se_ns);
  6804. svgcontent.setAttributeNS(se_ns, 'se:nonce', nonce);
  6805. if (extensions["Arrows"]) call("setarrownonce", nonce) ;
  6806. }
  6807. // change image href vals if possible
  6808. $(svgcontent).find('image').each(function() {
  6809. var image = this;
  6810. preventClickDefault(image);
  6811. var val = this.getAttributeNS(xlinkns, "href");
  6812. if(val.indexOf('data:') === 0) {
  6813. // Check if an SVG-edit data URI
  6814. var m = val.match(/svgedit_url=(.*?);/);
  6815. if(m) {
  6816. var url = decodeURIComponent(m[1]);
  6817. $(new Image()).load(function() {
  6818. image.setAttributeNS(xlinkns,'xlink:href',url);
  6819. }).attr('src',url);
  6820. }
  6821. }
  6822. // Add to encodableImages if it loads
  6823. canvas.embedImage(val);
  6824. });
  6825. // convert gradients with userSpaceOnUse to objectBoundingBox
  6826. $(svgcontent).find('linearGradient, radialGradient').each(function() {
  6827. var grad = this;
  6828. if($(grad).attr('gradientUnits') === 'userSpaceOnUse') {
  6829. // TODO: Support more than one element with this ref by duplicating parent grad
  6830. var elems = $(svgcontent).find('[fill=url(#' + grad.id + ')],[stroke=url(#' + grad.id + ')]');
  6831. if(!elems.length) return;
  6832. // get object's bounding box
  6833. var bb = elems[0].getBBox();
  6834. if(grad.tagName === 'linearGradient') {
  6835. var g_coords = $(grad).attr(['x1', 'y1', 'x2', 'y2']);
  6836. $(grad).attr({
  6837. x1: (g_coords.x1 - bb.x) / bb.width,
  6838. y1: (g_coords.y1 - bb.y) / bb.height,
  6839. x2: (g_coords.x2 - bb.x) / bb.width,
  6840. y2: (g_coords.y1 - bb.y) / bb.height
  6841. });
  6842. grad.removeAttribute('gradientUnits');
  6843. } else {
  6844. // Note: radialGradient elements cannot be easily converted
  6845. // because userSpaceOnUse will keep circular gradients, while
  6846. // objectBoundingBox will x/y scale the gradient according to
  6847. // its bbox.
  6848. // For now we'll do nothing, though we should probably have
  6849. // the gradient be updated as the element is moved, as
  6850. // inkscape/illustrator do.
  6851. // var g_coords = $(grad).attr(['cx', 'cy', 'r']);
  6852. //
  6853. // $(grad).attr({
  6854. // cx: (g_coords.cx - bb.x) / bb.width,
  6855. // cy: (g_coords.cy - bb.y) / bb.height,
  6856. // r: g_coords.r
  6857. // });
  6858. //
  6859. // grad.removeAttribute('gradientUnits');
  6860. }
  6861. }
  6862. });
  6863. // recalculate dimensions on the top-level children so that unnecessary transforms
  6864. // are removed
  6865. walkTreePost(svgcontent, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}});
  6866. var content = $(svgcontent);
  6867. var attrs = {
  6868. id: 'svgcontent',
  6869. overflow: curConfig.show_outside_canvas?'visible':'hidden'
  6870. };
  6871. // determine proper size
  6872. if (content.attr("viewBox")) {
  6873. var vb = content.attr("viewBox").split(' ');
  6874. attrs.width = vb[2];
  6875. attrs.height = vb[3];
  6876. }
  6877. // handle content that doesn't have a viewBox
  6878. else {
  6879. $.each(['width', 'height'], function(i, dim) {
  6880. // Set to 100 if not given
  6881. var val = content.attr(dim) || 100;
  6882. if((val+'').substr(-1) === "%") {
  6883. // Use user units if percentage given
  6884. attrs[dim] = parseInt(val);
  6885. } else {
  6886. attrs[dim] = convertToNum(dim, val);
  6887. }
  6888. });
  6889. }
  6890. content.attr(attrs);
  6891. this.contentW = attrs['width'];
  6892. this.contentH = attrs['height'];
  6893. batchCmd.addSubCommand(new InsertElementCommand(svgcontent));
  6894. // update root to the correct size
  6895. var changes = content.attr(["width", "height"]);
  6896. batchCmd.addSubCommand(new ChangeElementCommand(svgroot, changes));
  6897. // reset zoom
  6898. current_zoom = 1;
  6899. // identify layers
  6900. identifyLayers();
  6901. // reset transform lists
  6902. svgTransformLists = {};
  6903. clearSelection();
  6904. pathActions.clearData();
  6905. svgroot.appendChild(selectorManager.selectorParentGroup);
  6906. addCommandToHistory(batchCmd);
  6907. call("changed", [svgcontent]);
  6908. } catch(e) {
  6909. console.log(e);
  6910. return false;
  6911. }
  6912. return true;
  6913. };
  6914. // Function: importSvgString
  6915. // This function imports the input SVG XML into the current layer in the drawing
  6916. //
  6917. // Parameters:
  6918. // xmlString - The SVG as XML text.
  6919. //
  6920. // Returns:
  6921. // This function returns false if the import was unsuccessful, true otherwise.
  6922. // TODO:
  6923. // * properly handle if namespace is introduced by imported content (must add to svgcontent
  6924. // and update all prefixes in the imported node)
  6925. // * properly handle recalculating dimensions, recalculateDimensions() doesn't handle
  6926. // arbitrary transform lists, but makes some assumptions about how the transform list
  6927. // was obtained
  6928. // * import should happen in top-left of current zoomed viewport
  6929. // * create a new layer for the imported SVG
  6930. this.importSvgString = function(xmlString) {
  6931. try {
  6932. // convert string into XML document
  6933. var newDoc = Utils.text2xml(xmlString);
  6934. // run it through our sanitizer to remove anything we do not support
  6935. sanitizeSvg(newDoc.documentElement);
  6936. var batchCmd = new BatchCommand("Change Source");
  6937. // import new svg document into our document
  6938. var importedNode = svgdoc.importNode(newDoc.documentElement, true);
  6939. if (current_layer) {
  6940. // TODO: properly handle if width/height are not specified or if in percentages
  6941. // TODO: properly handle if width/height are in units (px, etc)
  6942. var innerw = importedNode.getAttribute("width"),
  6943. innerh = importedNode.getAttribute("height"),
  6944. innervb = importedNode.getAttribute("viewBox"),
  6945. // if no explicit viewbox, create one out of the width and height
  6946. vb = innervb ? innervb.split(" ") : [0,0,innerw,innerh];
  6947. for (var j = 0; j < 4; ++j)
  6948. vb[j] = Number(vb[j]);
  6949. // TODO: properly handle preserveAspectRatio
  6950. var canvasw = Number(svgcontent.getAttribute("width")),
  6951. canvash = Number(svgcontent.getAttribute("height"));
  6952. // imported content should be 1/3 of the canvas on its largest dimension
  6953. if (innerh > innerw) {
  6954. var ts = "scale(" + (canvash/3)/vb[3] + ")";
  6955. }
  6956. else {
  6957. var ts = "scale(" + (canvash/3)/vb[2] + ")";
  6958. }
  6959. // Hack to make recalculateDimensions understand how to scale
  6960. ts = "translate(0) " + ts + " translate(0)";
  6961. // TODO: Find way to add this in a recalculateDimensions-parsable way
  6962. // if (vb[0] != 0 || vb[1] != 0)
  6963. // ts = "translate(" + (-vb[0]) + "," + (-vb[1]) + ") " + ts;
  6964. // add all children of the imported <svg> to the <g> we create
  6965. var g = svgdoc.createElementNS(svgns, "g");
  6966. while (importedNode.hasChildNodes())
  6967. g.appendChild(importedNode.firstChild);
  6968. if (ts)
  6969. g.setAttribute("transform", ts);
  6970. // now ensure each element has a unique ID
  6971. var ids = {};
  6972. walkTree(g, function(n) {
  6973. // if it's an element node
  6974. if (n.nodeType == 1) {
  6975. // and the element has an ID
  6976. if (n.id) {
  6977. // and we haven't tracked this ID yet
  6978. if (!(n.id in ids)) {
  6979. // add this id to our map
  6980. ids[n.id] = {elem:null, attrs:[], hrefs:[]};
  6981. }
  6982. ids[n.id]["elem"] = n;
  6983. }
  6984. // now search for all attributes on this element that might refer
  6985. // to other elements
  6986. $.each(["clip-path", "fill", "filter", "marker-end", "marker-mid", "marker-start", "mask", "stroke"],function(i,attr) {
  6987. var attrnode = n.getAttributeNode(attr);
  6988. if (attrnode) {
  6989. // the incoming file has been sanitized, so we should be able to safely just strip off the leading #
  6990. var url = getUrlFromAttr(attrnode.value),
  6991. refid = url ? url.substr(1) : null;
  6992. if (refid) {
  6993. if (!(refid in ids)) {
  6994. // add this id to our map
  6995. ids[refid] = {elem:null, attrs:[], hrefs:[]};
  6996. }
  6997. ids[refid]["attrs"].push(attrnode);
  6998. }
  6999. }
  7000. });
  7001. // check xlink:href now
  7002. var href = n.getAttributeNS(xlinkns,"href");
  7003. // TODO: what if an <image> or <a> element refers to an element internally?
  7004. if(href &&
  7005. $.inArray(n.nodeName, ["filter", "linearGradient", "pattern",
  7006. "radialGradient", "textPath", "use"]) != -1)
  7007. {
  7008. var refid = href.substr(1);
  7009. if (!(refid in ids)) {
  7010. // add this id to our map
  7011. ids[refid] = {elem:null, attrs:[], hrefs:[]};
  7012. }
  7013. ids[refid]["hrefs"].push(n);
  7014. }
  7015. }
  7016. });
  7017. // in ids, we now have a map of ids, elements and attributes, let's re-identify
  7018. for (var oldid in ids) {
  7019. var elem = ids[oldid]["elem"];
  7020. if (elem) {
  7021. var newid = getNextId();
  7022. // manually increment obj_num because our cloned elements are not in the DOM yet
  7023. obj_num++;
  7024. // assign element its new id
  7025. elem.id = newid;
  7026. // remap all url() attributes
  7027. var attrs = ids[oldid]["attrs"];
  7028. var j = attrs.length;
  7029. while (j--) {
  7030. var attr = attrs[j];
  7031. attr.ownerElement.setAttribute(attr.name, "url(#" + newid + ")");
  7032. }
  7033. // remap all href attributes
  7034. var hreffers = ids[oldid]["hrefs"];
  7035. var k = hreffers.length;
  7036. while (k--) {
  7037. var hreffer = hreffers[k];
  7038. hreffer.setAttributeNS(xlinkns, "xlink:href", "#"+newid);
  7039. }
  7040. }
  7041. }
  7042. // now give the g itself a new id
  7043. g.id = getNextId();
  7044. // manually increment obj_num because our cloned elements are not in the DOM yet
  7045. obj_num++;
  7046. current_layer.appendChild(g);
  7047. }
  7048. // change image href vals if possible
  7049. // $(svgcontent).find('image').each(function() {
  7050. // var image = this;
  7051. // preventClickDefault(image);
  7052. // var val = this.getAttributeNS(xlinkns, "href");
  7053. // if(val.indexOf('data:') === 0) {
  7054. // // Check if an SVG-edit data URI
  7055. // var m = val.match(/svgedit_url=(.*?);/);
  7056. // if(m) {
  7057. // var url = decodeURIComponent(m[1]);
  7058. // $(new Image()).load(function() {
  7059. // image.setAttributeNS(xlinkns,'xlink:href',url);
  7060. // }).attr('src',url);
  7061. // }
  7062. // }
  7063. // // Add to encodableImages if it loads
  7064. // canvas.embedImage(val);
  7065. // });
  7066. // recalculate dimensions on the top-level children so that unnecessary transforms
  7067. // are removed
  7068. walkTreePost(svgcontent, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}});
  7069. batchCmd.addSubCommand(new InsertElementCommand(svgcontent));
  7070. // reset zoom - TODO: why?
  7071. // current_zoom = 1;
  7072. // identify layers
  7073. // identifyLayers();
  7074. // reset transform lists
  7075. svgTransformLists = {};
  7076. clearSelection();
  7077. addCommandToHistory(batchCmd);
  7078. call("changed", [svgcontent]);
  7079. } catch(e) {
  7080. console.log(e);
  7081. return false;
  7082. }
  7083. return true;
  7084. };
  7085. // Layer API Functions
  7086. // Group: Layers
  7087. // Function: identifyLayers
  7088. // Updates layer system
  7089. var identifyLayers = function() {
  7090. all_layers = [];
  7091. var numchildren = svgcontent.childNodes.length;
  7092. // loop through all children of svgcontent
  7093. var orphans = [], layernames = [];
  7094. for (var i = 0; i < numchildren; ++i) {
  7095. var child = svgcontent.childNodes.item(i);
  7096. // for each g, find its layer name
  7097. if (child && child.nodeType == 1) {
  7098. if (child.tagName == "g") {
  7099. var name = $("title",child).text();
  7100. // Hack for Opera 10.60
  7101. if(!name && isOpera && child.querySelectorAll) {
  7102. name = $(child.querySelectorAll('title')).text();
  7103. }
  7104. // store layer and name in global variable
  7105. if (name) {
  7106. layernames.push(name);
  7107. all_layers.push( [name,child] );
  7108. current_layer = child;
  7109. walkTree(child, function(e){e.setAttribute("style", "pointer-events:inherit");});
  7110. current_layer.setAttribute("style", "pointer-events:none");
  7111. }
  7112. // if group did not have a name, it is an orphan
  7113. else {
  7114. orphans.push(child);
  7115. }
  7116. }
  7117. // if child has a bbox (i.e. not a <title> or <defs> element), then it is an orphan
  7118. else if(getBBox(child) && child.nodeName != 'defs') { // Opera returns a BBox for defs
  7119. var bb = getBBox(child);
  7120. orphans.push(child);
  7121. }
  7122. }
  7123. }
  7124. // create a new layer and add all the orphans to it
  7125. if (orphans.length > 0) {
  7126. var i = 1;
  7127. while ($.inArray(("Layer " + i), layernames) != -1) { i++; }
  7128. var newname = "Layer " + i;
  7129. current_layer = svgdoc.createElementNS(svgns, "g");
  7130. var layer_title = svgdoc.createElementNS(svgns, "title");
  7131. layer_title.textContent = newname;
  7132. current_layer.appendChild(layer_title);
  7133. for (var j = 0; j < orphans.length; ++j) {
  7134. current_layer.appendChild(orphans[j]);
  7135. }
  7136. current_layer = svgcontent.appendChild(current_layer);
  7137. all_layers.push( [newname, current_layer] );
  7138. }
  7139. walkTree(current_layer, function(e){e.setAttribute("style","pointer-events:inherit");});
  7140. current_layer.setAttribute("style","pointer-events:all");
  7141. };
  7142. // Function: createLayer
  7143. // Creates a new top-level layer in the drawing with the given name, sets the current layer
  7144. // to it, and then clears the selection This function then calls the 'changed' handler.
  7145. // This is an undoable action.
  7146. //
  7147. // Parameters:
  7148. // name - The given name
  7149. this.createLayer = function(name) {
  7150. var batchCmd = new BatchCommand("Create Layer");
  7151. var new_layer = svgdoc.createElementNS(svgns, "g");
  7152. var layer_title = svgdoc.createElementNS(svgns, "title");
  7153. layer_title.textContent = name;
  7154. new_layer.appendChild(layer_title);
  7155. new_layer = svgcontent.appendChild(new_layer);
  7156. batchCmd.addSubCommand(new InsertElementCommand(new_layer));
  7157. addCommandToHistory(batchCmd);
  7158. clearSelection();
  7159. identifyLayers();
  7160. canvas.setCurrentLayer(name);
  7161. call("changed", [new_layer]);
  7162. };
  7163. // Function: deleteCurrentLayer
  7164. // Deletes the current layer from the drawing and then clears the selection. This function
  7165. // then calls the 'changed' handler. This is an undoable action.
  7166. this.deleteCurrentLayer = function() {
  7167. if (current_layer && all_layers.length > 1) {
  7168. var batchCmd = new BatchCommand("Delete Layer");
  7169. // actually delete from the DOM and store in our Undo History
  7170. var parent = current_layer.parentNode;
  7171. batchCmd.addSubCommand(new RemoveElementCommand(current_layer, parent));
  7172. parent.removeChild(current_layer);
  7173. addCommandToHistory(batchCmd);
  7174. clearSelection();
  7175. identifyLayers();
  7176. canvas.setCurrentLayer(all_layers[all_layers.length-1][0]);
  7177. call("changed", [svgcontent]);
  7178. return true;
  7179. }
  7180. return false;
  7181. };
  7182. // Function: getNumLayers
  7183. // Returns the number of layers in the current drawing.
  7184. //
  7185. // Returns:
  7186. // The number of layers in the current drawing.
  7187. this.getNumLayers = function() {
  7188. return all_layers.length;
  7189. };
  7190. // Function: getLayer
  7191. // Returns the name of the ith layer. If the index is out of range, an empty string is returned.
  7192. //
  7193. // Parameters:
  7194. // i - the zero-based index of the layer you are querying.
  7195. //
  7196. // Returns:
  7197. // The name of the ith layer
  7198. this.getLayer = function(i) {
  7199. if (i >= 0 && i < canvas.getNumLayers()) {
  7200. return all_layers[i][0];
  7201. }
  7202. return "";
  7203. };
  7204. // Function: getCurrentLayer
  7205. // Returns the name of the currently selected layer. If an error occurs, an empty string
  7206. // is returned.
  7207. //
  7208. // Returns:
  7209. // The name of the currently active layer.
  7210. this.getCurrentLayer = function() {
  7211. for (var i = 0; i < all_layers.length; ++i) {
  7212. if (all_layers[i][1] == current_layer) {
  7213. return all_layers[i][0];
  7214. }
  7215. }
  7216. return "";
  7217. };
  7218. // Function: setCurrentLayer
  7219. // Sets the current layer. If the name is not a valid layer name, then this function returns
  7220. // false. Otherwise it returns true. This is not an undo-able action.
  7221. //
  7222. // Parameters:
  7223. // name - the name of the layer you want to switch to.
  7224. //
  7225. // Returns:
  7226. // true if the current layer was switched, otherwise false
  7227. this.setCurrentLayer = function(name) {
  7228. name = Utils.toXml(name);
  7229. for (var i = 0; i < all_layers.length; ++i) {
  7230. if (name == all_layers[i][0]) {
  7231. if (current_layer != all_layers[i][1]) {
  7232. clearSelection();
  7233. current_layer.setAttribute("style", "pointer-events:none");
  7234. current_layer = all_layers[i][1];
  7235. current_layer.setAttribute("style", "pointer-events:all");
  7236. }
  7237. return true;
  7238. }
  7239. }
  7240. return false;
  7241. };
  7242. // Function: renameCurrentLayer
  7243. // Renames the current layer. If the layer name is not valid (i.e. unique), then this function
  7244. // does nothing and returns false, otherwise it returns true. This is an undo-able action.
  7245. //
  7246. // Parameters:
  7247. // newname - the new name you want to give the current layer. This name must be unique
  7248. // among all layer names.
  7249. //
  7250. // Returns:
  7251. // true if the rename succeeded, false otherwise.
  7252. this.renameCurrentLayer = function(newname) {
  7253. if (current_layer) {
  7254. var oldLayer = current_layer;
  7255. // setCurrentLayer will return false if the name doesn't already exists
  7256. if (!canvas.setCurrentLayer(newname)) {
  7257. var batchCmd = new BatchCommand("Rename Layer");
  7258. // find the index of the layer
  7259. for (var i = 0; i < all_layers.length; ++i) {
  7260. if (all_layers[i][1] == oldLayer) break;
  7261. }
  7262. var oldname = all_layers[i][0];
  7263. all_layers[i][0] = Utils.toXml(newname);
  7264. // now change the underlying title element contents
  7265. var len = oldLayer.childNodes.length;
  7266. for (var i = 0; i < len; ++i) {
  7267. var child = oldLayer.childNodes.item(i);
  7268. // found the <title> element, now append all the
  7269. if (child && child.tagName == "title") {
  7270. // wipe out old name
  7271. while (child.firstChild) { child.removeChild(child.firstChild); }
  7272. child.textContent = newname;
  7273. batchCmd.addSubCommand(new ChangeElementCommand(child, {"#text":oldname}));
  7274. addCommandToHistory(batchCmd);
  7275. call("changed", [oldLayer]);
  7276. return true;
  7277. }
  7278. }
  7279. }
  7280. current_layer = oldLayer;
  7281. }
  7282. return false;
  7283. };
  7284. // Function: setCurrentLayerPosition
  7285. // Changes the position of the current layer to the new value. If the new index is not valid,
  7286. // this function does nothing and returns false, otherwise it returns true. This is an
  7287. // undo-able action.
  7288. //
  7289. // Parameters:
  7290. // newpos - The zero-based index of the new position of the layer. This should be between
  7291. // 0 and (number of layers - 1)
  7292. //
  7293. // Returns:
  7294. // true if the current layer position was changed, false otherwise.
  7295. this.setCurrentLayerPosition = function(newpos) {
  7296. if (current_layer && newpos >= 0 && newpos < all_layers.length) {
  7297. for (var oldpos = 0; oldpos < all_layers.length; ++oldpos) {
  7298. if (all_layers[oldpos][1] == current_layer) break;
  7299. }
  7300. // some unknown error condition (current_layer not in all_layers)
  7301. if (oldpos == all_layers.length) { return false; }
  7302. if (oldpos != newpos) {
  7303. // if our new position is below us, we need to insert before the node after newpos
  7304. var refLayer = null;
  7305. var oldNextSibling = current_layer.nextSibling;
  7306. if (newpos > oldpos ) {
  7307. if (newpos < all_layers.length-1) {
  7308. refLayer = all_layers[newpos+1][1];
  7309. }
  7310. }
  7311. // if our new position is above us, we need to insert before the node at newpos
  7312. else {
  7313. refLayer = all_layers[newpos][1];
  7314. }
  7315. svgcontent.insertBefore(current_layer, refLayer);
  7316. addCommandToHistory(new MoveElementCommand(current_layer, oldNextSibling, svgcontent));
  7317. identifyLayers();
  7318. canvas.setCurrentLayer(all_layers[newpos][0]);
  7319. return true;
  7320. }
  7321. }
  7322. return false;
  7323. };
  7324. // Function: getLayerVisibility
  7325. // Returns whether the layer is visible. If the layer name is not valid, then this function
  7326. // returns false.
  7327. //
  7328. // Parameters:
  7329. // layername - the name of the layer which you want to query.
  7330. //
  7331. // Returns:
  7332. // The visibility state of the layer, or false if the layer name was invalid.
  7333. this.getLayerVisibility = function(layername) {
  7334. // find the layer
  7335. var layer = null;
  7336. for (var i = 0; i < all_layers.length; ++i) {
  7337. if (all_layers[i][0] == layername) {
  7338. layer = all_layers[i][1];
  7339. break;
  7340. }
  7341. }
  7342. if (!layer) return false;
  7343. return (layer.getAttribute("display") != "none");
  7344. };
  7345. // Function: setLayerVisibility
  7346. // Sets the visibility of the layer. If the layer name is not valid, this function return
  7347. // false, otherwise it returns true. This is an undo-able action.
  7348. //
  7349. // Parameters:
  7350. // layername - the name of the layer to change the visibility
  7351. // bVisible - true/false, whether the layer should be visible
  7352. //
  7353. // Returns:
  7354. // true if the layer's visibility was set, false otherwise
  7355. this.setLayerVisibility = function(layername, bVisible) {
  7356. // find the layer
  7357. var layer = null;
  7358. for (var i = 0; i < all_layers.length; ++i) {
  7359. if (all_layers[i][0] == layername) {
  7360. layer = all_layers[i][1];
  7361. break;
  7362. }
  7363. }
  7364. if (!layer) return false;
  7365. var oldDisplay = layer.getAttribute("display");
  7366. if (!oldDisplay) oldDisplay = "inline";
  7367. layer.setAttribute("display", bVisible ? "inline" : "none");
  7368. addCommandToHistory(new ChangeElementCommand(layer, {"display":oldDisplay}, "Layer Visibility"));
  7369. if (layer == current_layer) {
  7370. clearSelection();
  7371. pathActions.clear();
  7372. }
  7373. // call("changed", [selected]);
  7374. return true;
  7375. };
  7376. // Function: moveSelectedToLayer
  7377. // Moves the selected elements to layername. If the name is not a valid layer name, then false
  7378. // is returned. Otherwise it returns true. This is an undo-able action.
  7379. //
  7380. // Parameters:
  7381. // layername - the name of the layer you want to which you want to move the selected elements
  7382. //
  7383. // Returns:
  7384. // true if the selected elements were moved to the layer, false otherwise.
  7385. this.moveSelectedToLayer = function(layername) {
  7386. // find the layer
  7387. var layer = null;
  7388. for (var i = 0; i < all_layers.length; ++i) {
  7389. if (all_layers[i][0] == layername) {
  7390. layer = all_layers[i][1];
  7391. break;
  7392. }
  7393. }
  7394. if (!layer) return false;
  7395. var batchCmd = new BatchCommand("Move Elements to Layer");
  7396. // loop for each selected element and move it
  7397. var selElems = selectedElements;
  7398. var i = selElems.length;
  7399. while (i--) {
  7400. var elem = selElems[i];
  7401. if (!elem) continue;
  7402. var oldNextSibling = elem.nextSibling;
  7403. // TODO: this is pretty brittle!
  7404. var oldLayer = elem.parentNode;
  7405. layer.appendChild(elem);
  7406. batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldLayer));
  7407. }
  7408. addCommandToHistory(batchCmd);
  7409. return true;
  7410. };
  7411. // Function: getLayerOpacity
  7412. // Returns the opacity of the given layer. If the input name is not a layer, null is returned.
  7413. //
  7414. // Parameters:
  7415. // layername - name of the layer on which to get the opacity
  7416. //
  7417. // Returns:
  7418. // The opacity value of the given layer. This will be a value between 0.0 and 1.0, or null
  7419. // if layername is not a valid layer
  7420. this.getLayerOpacity = function(layername) {
  7421. for (var i = 0; i < all_layers.length; ++i) {
  7422. if (all_layers[i][0] == layername) {
  7423. var g = all_layers[i][1];
  7424. var opacity = g.getAttribute("opacity");
  7425. if (!opacity) {
  7426. opacity = "1.0";
  7427. }
  7428. return parseFloat(opacity);
  7429. }
  7430. }
  7431. return null;
  7432. };
  7433. // Function: setLayerOpacity
  7434. // Sets the opacity of the given layer. If the input name is not a layer, nothing happens.
  7435. // This is not an undo-able action. NOTE: this function exists solely to apply
  7436. // a highlighting/de-emphasis effect to a layer, when it is possible for a user to affect
  7437. // the opacity of a layer, we will need to allow this function to produce an undo-able action.
  7438. // If opacity is not a value between 0.0 and 1.0, then nothing happens.
  7439. //
  7440. // Parameters:
  7441. // layername - name of the layer on which to set the opacity
  7442. // opacity - a float value in the range 0.0-1.0
  7443. this.setLayerOpacity = function(layername, opacity) {
  7444. if (opacity < 0.0 || opacity > 1.0) return;
  7445. for (var i = 0; i < all_layers.length; ++i) {
  7446. if (all_layers[i][0] == layername) {
  7447. var g = all_layers[i][1];
  7448. g.setAttribute("opacity", opacity);
  7449. break;
  7450. }
  7451. }
  7452. };
  7453. // Group: Document functions
  7454. // Function: clear
  7455. // Clears the current document. This is not an undoable action.
  7456. this.clear = function() {
  7457. pathActions.clear();
  7458. // clear the svgcontent node
  7459. var nodes = svgcontent.childNodes;
  7460. var len = svgcontent.childNodes.length;
  7461. var i = 0;
  7462. clearSelection();
  7463. for(var rep = 0; rep < len; rep++){
  7464. if (nodes[i].nodeType == 1) { // element node
  7465. svgcontent.removeChild(nodes[i]);
  7466. } else {
  7467. i++;
  7468. }
  7469. }
  7470. // create empty first layer
  7471. all_layers = [];
  7472. canvas.createLayer("Layer 1");
  7473. // clear the undo stack
  7474. resetUndoStack();
  7475. // reset the selector manager
  7476. selectorManager.initGroup();
  7477. // reset the rubber band box
  7478. rubberBox = selectorManager.getRubberBandBox();
  7479. call("cleared");
  7480. };
  7481. // Function: linkControlPoints
  7482. // Alias function
  7483. this.linkControlPoints = pathActions.linkControlPoints;
  7484. // Function: getContentElem
  7485. // Returns the content DOM element
  7486. this.getContentElem = function() { return svgcontent; };
  7487. // Function: getRootElem
  7488. // Returns the root DOM element
  7489. this.getRootElem = function() { return svgroot; };
  7490. // Function: getSelectedElems
  7491. // Returns the array with selected DOM elements
  7492. this.getSelectedElems = function() { return selectedElements; };
  7493. // Function: getResolution
  7494. // Returns the current dimensions and zoom level in an object
  7495. var getResolution = this.getResolution = function() {
  7496. // var vb = svgcontent.getAttribute("viewBox").split(' ');
  7497. // return {'w':vb[2], 'h':vb[3], 'zoom': current_zoom};
  7498. return {
  7499. 'w':svgcontent.getAttribute("width")/current_zoom,
  7500. 'h':svgcontent.getAttribute("height")/current_zoom,
  7501. 'zoom': current_zoom
  7502. };
  7503. };
  7504. // Function: getZoom
  7505. // Returns the current zoom level
  7506. this.getZoom = function(){return current_zoom;};
  7507. // Function: getVersion
  7508. // Returns a string which describes the revision number of SvgCanvas.
  7509. this.getVersion = function() {
  7510. return "svgcanvas.js ($Rev: 1738 $)";
  7511. };
  7512. // Function: setUiStrings
  7513. // Update interface strings with given values
  7514. //
  7515. // Parameters:
  7516. // strs - Object with strings (see uiStrings for examples)
  7517. this.setUiStrings = function(strs) {
  7518. $.extend(uiStrings, strs);
  7519. }
  7520. // Function: setConfig
  7521. // Update configuration options with given values
  7522. //
  7523. // Parameters:
  7524. // opts - Object with options (see curConfig for examples)
  7525. this.setConfig = function(opts) {
  7526. $.extend(curConfig, opts);
  7527. }
  7528. // Function: getDocumentTitle
  7529. // Returns the current document title or an empty string if not found
  7530. this.getDocumentTitle = function() {
  7531. var childs = svgcontent.childNodes;
  7532. for (var i=0; i<childs.length; i++) {
  7533. if(childs[i].nodeName == 'title') {
  7534. return childs[i].textContent;
  7535. }
  7536. }
  7537. return '';
  7538. }
  7539. // Function: setDocumentTitle
  7540. // Adds/updates a title element for the document with the given name.
  7541. // This is an undoable action
  7542. //
  7543. // Parameters:
  7544. // newtitle - String with the new title
  7545. this.setDocumentTitle = function(newtitle) {
  7546. var childs = svgcontent.childNodes, doc_title = false, old_title = '';
  7547. var batchCmd = new BatchCommand("Change Image Title");
  7548. for (var i=0; i<childs.length; i++) {
  7549. if(childs[i].nodeName == 'title') {
  7550. doc_title = childs[i];
  7551. old_title = doc_title.textContent;
  7552. break;
  7553. }
  7554. }
  7555. if(!doc_title) {
  7556. doc_title = svgdoc.createElementNS(svgns, "title");
  7557. svgcontent.insertBefore(doc_title, svgcontent.firstChild);
  7558. }
  7559. if(newtitle.length) {
  7560. doc_title.textContent = newtitle;
  7561. } else {
  7562. // No title given, so element is not necessary
  7563. doc_title.parentNode.removeChild(doc_title);
  7564. }
  7565. batchCmd.addSubCommand(new ChangeElementCommand(doc_title, {'#text': old_title}));
  7566. addCommandToHistory(batchCmd);
  7567. }
  7568. // Function: getEditorNS
  7569. // Returns the editor's namespace URL, optionally adds it to root element
  7570. //
  7571. // Parameters:
  7572. // add - Boolean to indicate whether or not to add the namespace value
  7573. this.getEditorNS = function(add) {
  7574. if(add) {
  7575. svgcontent.setAttribute('xmlns:se', se_ns);
  7576. }
  7577. return se_ns;
  7578. }
  7579. // Function: setResolution
  7580. // Changes the document's dimensions to the given size
  7581. //
  7582. // Parameters:
  7583. // x - Number with the width of the new dimensions in user units.
  7584. // Can also be the string "fit" to indicate "fit to content"
  7585. // y - Number with the height of the new dimensions in user units.
  7586. //
  7587. // Returns:
  7588. // Boolean to indicate if resolution change was succesful.
  7589. // It will fail on "fit to content" option with no content to fit to.
  7590. this.setResolution = function(x, y) {
  7591. var res = getResolution();
  7592. var w = res.w, h = res.h;
  7593. var batchCmd;
  7594. if(x == 'fit') {
  7595. // Get bounding box
  7596. var bbox = getStrokedBBox();
  7597. if(bbox) {
  7598. batchCmd = new BatchCommand("Fit Canvas to Content");
  7599. var visEls = getVisibleElements();
  7600. addToSelection(visEls);
  7601. var dx = [], dy = [];
  7602. $.each(visEls, function(i, item) {
  7603. dx.push(bbox.x*-1);
  7604. dy.push(bbox.y*-1);
  7605. });
  7606. var cmd = canvas.moveSelectedElements(dx, dy, true);
  7607. batchCmd.addSubCommand(cmd);
  7608. clearSelection();
  7609. x = Math.round(bbox.width);
  7610. y = Math.round(bbox.height);
  7611. } else {
  7612. return false;
  7613. }
  7614. }
  7615. if (x != w || y != h) {
  7616. var handle = svgroot.suspendRedraw(1000);
  7617. if(!batchCmd) {
  7618. batchCmd = new BatchCommand("Change Image Dimensions");
  7619. }
  7620. x = convertToNum('width', x);
  7621. y = convertToNum('height', y);
  7622. svgcontent.setAttribute('width', x);
  7623. svgcontent.setAttribute('height', y);
  7624. this.contentW = x;
  7625. this.contentH = y;
  7626. batchCmd.addSubCommand(new ChangeElementCommand(svgcontent, {"width":w, "height":h}));
  7627. svgcontent.setAttribute("viewBox", [0, 0, x/current_zoom, y/current_zoom].join(' '));
  7628. batchCmd.addSubCommand(new ChangeElementCommand(svgcontent, {"viewBox": ["0 0", w, h].join(' ')}));
  7629. addCommandToHistory(batchCmd);
  7630. svgroot.unsuspendRedraw(handle);
  7631. call("changed", [svgcontent]);
  7632. }
  7633. return true;
  7634. };
  7635. // Function: getOffset
  7636. // Returns an object with x, y values indicating the svgcontent element's
  7637. // position in the editor's canvas.
  7638. this.getOffset = function() {
  7639. return $(svgcontent).attr(['x', 'y']);
  7640. }
  7641. // Function: setBBoxZoom
  7642. // Sets the zoom level on the canvas-side based on the given value
  7643. //
  7644. // Parameters:
  7645. // val - Bounding box object to zoom to or string indicating zoom option
  7646. // editor_w - Integer with the editor's workarea box's width
  7647. // editor_h - Integer with the editor's workarea box's height
  7648. this.setBBoxZoom = function(val, editor_w, editor_h) {
  7649. var spacer = .85;
  7650. var bb;
  7651. var calcZoom = function(bb) {
  7652. if(!bb) return false;
  7653. var w_zoom = Math.round((editor_w / bb.width)*100 * spacer)/100;
  7654. var h_zoom = Math.round((editor_h / bb.height)*100 * spacer)/100;
  7655. var zoomlevel = Math.min(w_zoom,h_zoom);
  7656. canvas.setZoom(zoomlevel);
  7657. return {'zoom': zoomlevel, 'bbox': bb};
  7658. }
  7659. if(typeof val == 'object') {
  7660. bb = val;
  7661. if(bb.width == 0 || bb.height == 0) {
  7662. var newzoom = bb.zoom?bb.zoom:current_zoom * bb.factor;
  7663. canvas.setZoom(newzoom);
  7664. return {'zoom': current_zoom, 'bbox': bb};
  7665. }
  7666. return calcZoom(bb);
  7667. }
  7668. switch (val) {
  7669. case 'selection':
  7670. if(!selectedElements[0]) return;
  7671. var sel_elems = $.map(selectedElements, function(n){ if(n) return n; });
  7672. bb = getStrokedBBox(sel_elems);
  7673. break;
  7674. case 'canvas':
  7675. var res = getResolution();
  7676. spacer = .95;
  7677. bb = {width:res.w, height:res.h ,x:0, y:0};
  7678. break;
  7679. case 'content':
  7680. bb = getStrokedBBox();
  7681. break;
  7682. case 'layer':
  7683. bb = getStrokedBBox(getVisibleElements(current_layer));
  7684. break;
  7685. default:
  7686. return;
  7687. }
  7688. return calcZoom(bb);
  7689. }
  7690. // Function: setZoom
  7691. // Sets the zoom to the given level
  7692. //
  7693. // Parameters:
  7694. // zoomlevel - Float indicating the zoom level to change to
  7695. this.setZoom = function(zoomlevel) {
  7696. var res = getResolution();
  7697. svgcontent.setAttribute("viewBox", "0 0 " + res.w/zoomlevel + " " + res.h/zoomlevel);
  7698. current_zoom = zoomlevel;
  7699. $.each(selectedElements, function(i, elem) {
  7700. if(!elem) return;
  7701. selectorManager.requestSelector(elem).resize();
  7702. });
  7703. pathActions.zoomChange();
  7704. runExtensions("zoomChanged", zoomlevel);
  7705. }
  7706. // Function: getMode
  7707. // Returns the current editor mode string
  7708. this.getMode = function() {
  7709. return current_mode;
  7710. };
  7711. // Function: setMode
  7712. // Sets the editor's mode to the given string
  7713. //
  7714. // Parameters:
  7715. // name - String with the new mode to change to
  7716. this.setMode = function(name) {
  7717. pathActions.clear(true);
  7718. textActions.clear();
  7719. cur_properties = (selectedElements[0] && selectedElements[0].nodeName == 'text') ? cur_text : cur_shape;
  7720. current_mode = name;
  7721. };
  7722. // Group: Element Styling
  7723. // Function: getColor
  7724. // Returns the current fill/stroke option
  7725. this.getColor = function(type) {
  7726. return cur_properties[type];
  7727. };
  7728. // Function: setColor
  7729. // Change the current stroke/fill color/gradient value
  7730. //
  7731. // Parameters:
  7732. // type - String indicating fill or stroke
  7733. // val - The value to set the stroke attribute to
  7734. // preventUndo - Boolean indicating whether or not this should be and undoable option
  7735. this.setColor = function(type, val, preventUndo) {
  7736. cur_shape[type] = val;
  7737. cur_properties[type + '_paint'] = {type:"solidColor"};
  7738. var elems = [];
  7739. var i = selectedElements.length;
  7740. while (i--) {
  7741. var elem = selectedElements[i];
  7742. if (elem) {
  7743. if (elem.tagName == "g")
  7744. walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);});
  7745. else {
  7746. if(type == 'fill') {
  7747. if(elem.tagName != "polyline" && elem.tagName != "line") {
  7748. elems.push(elem);
  7749. }
  7750. } else {
  7751. elems.push(elem);
  7752. }
  7753. }
  7754. }
  7755. }
  7756. if (elems.length > 0) {
  7757. if (!preventUndo) {
  7758. changeSelectedAttribute(type, val, elems);
  7759. call("changed", elems);
  7760. } else
  7761. changeSelectedAttributeNoUndo(type, val, elems);
  7762. }
  7763. }
  7764. // Function: findDefs
  7765. // Return the document's <defs> element, create it first if necessary
  7766. var findDefs = function() {
  7767. var defs = svgcontent.getElementsByTagNameNS(svgns, "defs");
  7768. if (defs.length > 0) {
  7769. defs = defs[0];
  7770. }
  7771. else {
  7772. // first child is a comment, so call nextSibling
  7773. defs = svgcontent.insertBefore( svgdoc.createElementNS(svgns, "defs" ), svgcontent.firstChild.nextSibling);
  7774. }
  7775. return defs;
  7776. };
  7777. // Function: setGradient
  7778. // Apply the current gradient to selected element's fill or stroke
  7779. //
  7780. // Parameters
  7781. // type - String indicating "fill" or "stroke" to apply to an element
  7782. var setGradient = this.setGradient = function(type) {
  7783. if(!cur_properties[type + '_paint'] || cur_properties[type + '_paint'].type == "solidColor") return;
  7784. var grad = canvas[type + 'Grad'];
  7785. // find out if there is a duplicate gradient already in the defs
  7786. var duplicate_grad = findDuplicateGradient(grad);
  7787. var defs = findDefs();
  7788. // no duplicate found, so import gradient into defs
  7789. if (!duplicate_grad) {
  7790. var orig_grad = grad;
  7791. grad = defs.appendChild( svgdoc.importNode(grad, true) );
  7792. // get next id and set it on the grad
  7793. grad.id = getNextId();
  7794. }
  7795. else { // use existing gradient
  7796. grad = duplicate_grad;
  7797. }
  7798. canvas.setColor(type, "url(#" + grad.id + ")");
  7799. }
  7800. // Function: findDuplicateGradient
  7801. // Check if exact gradient already exists
  7802. //
  7803. // Parameters:
  7804. // grad - The gradient DOM element to compare to others
  7805. //
  7806. // Returns:
  7807. // The existing gradient if found, null if not
  7808. var findDuplicateGradient = function(grad) {
  7809. var defs = findDefs();
  7810. var existing_grads = $(defs).find("linearGradient, radialGradient");
  7811. var i = existing_grads.length;
  7812. var rad_attrs = ['r','cx','cy','fx','fy'];
  7813. while (i--) {
  7814. var og = existing_grads[i];
  7815. if(grad.tagName == "linearGradient") {
  7816. if (grad.getAttribute('x1') != og.getAttribute('x1') ||
  7817. grad.getAttribute('y1') != og.getAttribute('y1') ||
  7818. grad.getAttribute('x2') != og.getAttribute('x2') ||
  7819. grad.getAttribute('y2') != og.getAttribute('y2'))
  7820. {
  7821. continue;
  7822. }
  7823. } else {
  7824. var grad_attrs = $(grad).attr(rad_attrs);
  7825. var og_attrs = $(og).attr(rad_attrs);
  7826. var diff = false;
  7827. $.each(rad_attrs, function(i, attr) {
  7828. if(grad_attrs[attr] != og_attrs[attr]) diff = true;
  7829. });
  7830. if(diff) continue;
  7831. }
  7832. // else could be a duplicate, iterate through stops
  7833. var stops = grad.getElementsByTagNameNS(svgns, "stop");
  7834. var ostops = og.getElementsByTagNameNS(svgns, "stop");
  7835. if (stops.length != ostops.length) {
  7836. continue;
  7837. }
  7838. var j = stops.length;
  7839. while(j--) {
  7840. var stop = stops[j];
  7841. var ostop = ostops[j];
  7842. if (stop.getAttribute('offset') != ostop.getAttribute('offset') ||
  7843. stop.getAttribute('stop-opacity') != ostop.getAttribute('stop-opacity') ||
  7844. stop.getAttribute('stop-color') != ostop.getAttribute('stop-color'))
  7845. {
  7846. break;
  7847. }
  7848. }
  7849. if (j == -1) {
  7850. return og;
  7851. }
  7852. } // for each gradient in defs
  7853. return null;
  7854. };
  7855. // Function: setPaint
  7856. // Set a color/gradient to a fill/stroke
  7857. //
  7858. // Parameters:
  7859. // type - String with "fill" or "stroke"
  7860. // paint - The jGraduate paint object to apply
  7861. this.setPaint = function(type, paint) {
  7862. // make a copy
  7863. var p = new $.jGraduate.Paint(paint);
  7864. this.setPaintOpacity(type, p.alpha/100, true);
  7865. // now set the current paint object
  7866. cur_properties[type + '_paint'] = p;
  7867. switch ( p.type ) {
  7868. case "solidColor":
  7869. this.setColor(type, p.solidColor != "none" ? "#"+p.solidColor : "none");;
  7870. break;
  7871. case "linearGradient":
  7872. case "radialGradient":
  7873. canvas[type + 'Grad'] = p[p.type];
  7874. setGradient(type);
  7875. break;
  7876. default:
  7877. // console.log("none!");
  7878. }
  7879. };
  7880. // this.setStrokePaint = function(p) {
  7881. // // make a copy
  7882. // var p = new $.jGraduate.Paint(p);
  7883. // this.setStrokeOpacity(p.alpha/100);
  7884. //
  7885. // // now set the current paint object
  7886. // cur_properties.stroke_paint = p;
  7887. // switch ( p.type ) {
  7888. // case "solidColor":
  7889. // this.setColor('stroke', p.solidColor != "none" ? "#"+p.solidColor : "none");;
  7890. // break;
  7891. // case "linearGradient"
  7892. // case "radialGradient"
  7893. // canvas.strokeGrad = p[p.type];
  7894. // setGradient(type);
  7895. // default:
  7896. // // console.log("none!");
  7897. // }
  7898. // };
  7899. //
  7900. // this.setFillPaint = function(p, addGrad) {
  7901. // // make a copy
  7902. // var p = new $.jGraduate.Paint(p);
  7903. // this.setFillOpacity(p.alpha/100, true);
  7904. //
  7905. // // now set the current paint object
  7906. // cur_properties.fill_paint = p;
  7907. // if (p.type == "solidColor") {
  7908. // this.setColor('fill', p.solidColor != "none" ? "#"+p.solidColor : "none");
  7909. // }
  7910. // else if(p.type == "linearGradient") {
  7911. // canvas.fillGrad = p.linearGradient;
  7912. // if(addGrad) setGradient();
  7913. // }
  7914. // else if(p.type == "radialGradient") {
  7915. // canvas.fillGrad = p.radialGradient;
  7916. // if(addGrad) setGradient();
  7917. // }
  7918. // else {
  7919. // // console.log("none!");
  7920. // }
  7921. // };
  7922. // Function: getStrokeWidth
  7923. // Returns the current stroke-width value
  7924. this.getStrokeWidth = function() {
  7925. return cur_properties.stroke_width;
  7926. };
  7927. // Function: setStrokeWidth
  7928. // Sets the stroke width for the current selected elements
  7929. // When attempting to set a line's width to 0, this changes it to 1 instead
  7930. //
  7931. // Parameters:
  7932. // val - A Float indicating the new stroke width value
  7933. this.setStrokeWidth = function(val) {
  7934. if(val == 0 && $.inArray(current_mode, ['line', 'path']) != -1) {
  7935. canvas.setStrokeWidth(1);
  7936. return;
  7937. }
  7938. cur_properties.stroke_width = val;
  7939. var elems = [];
  7940. var i = selectedElements.length;
  7941. while (i--) {
  7942. var elem = selectedElements[i];
  7943. if (elem) {
  7944. if (elem.tagName == "g")
  7945. walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);});
  7946. else
  7947. elems.push(elem);
  7948. }
  7949. }
  7950. if (elems.length > 0) {
  7951. changeSelectedAttribute("stroke-width", val, elems);
  7952. call("changed", selectedElements);
  7953. }
  7954. };
  7955. // Function: setStrokeAttr
  7956. // Set the given stroke-related attribute the given value for selected elements
  7957. //
  7958. // Parameters:
  7959. // attr - String with the attribute name
  7960. // val - String or number with the attribute value
  7961. this.setStrokeAttr = function(attr, val) {
  7962. cur_shape[attr.replace('-','_')] = val;
  7963. var elems = [];
  7964. var i = selectedElements.length;
  7965. while (i--) {
  7966. var elem = selectedElements[i];
  7967. if (elem) {
  7968. if (elem.tagName == "g")
  7969. walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);});
  7970. else
  7971. elems.push(elem);
  7972. }
  7973. }
  7974. if (elems.length > 0) {
  7975. changeSelectedAttribute(attr, val, elems);
  7976. call("changed", selectedElements);
  7977. }
  7978. };
  7979. // Function: getOpacity
  7980. // Returns the current opacity
  7981. this.getOpacity = function() {
  7982. return cur_shape.opacity;
  7983. };
  7984. // Function: setOpacity
  7985. // Sets the given opacity to the current selected elements
  7986. this.setOpacity = function(val) {
  7987. cur_shape.opacity = val;
  7988. changeSelectedAttribute("opacity", val);
  7989. };
  7990. // Function: getOpacity
  7991. // Returns the current fill opacity
  7992. this.getFillOpacity = function() {
  7993. return cur_shape.fill_opacity;
  7994. };
  7995. // Function: getStrokeOpacity
  7996. // Returns the current stroke opacity
  7997. this.getStrokeOpacity = function() {
  7998. return cur_shape.stroke_opacity;
  7999. };
  8000. // Function: setPaintOpacity
  8001. // Sets the current fill/stroke opacity
  8002. //
  8003. // Parameters:
  8004. // type - String with "fill" or "stroke"
  8005. // val - Float with the new opacity value
  8006. // preventUndo - Boolean indicating whether or not this should be an undoable action
  8007. this.setPaintOpacity = function(type, val, preventUndo) {
  8008. cur_shape[type + '_opacity'] = val;
  8009. if (!preventUndo)
  8010. changeSelectedAttribute(type + "-opacity", val);
  8011. else
  8012. changeSelectedAttributeNoUndo(type + "-opacity", val);
  8013. };
  8014. // Function: getBlur
  8015. // Gets the stdDeviation blur value of the given element
  8016. //
  8017. // Parameters:
  8018. // elem - The element to check the blur value for
  8019. this.getBlur = function(elem) {
  8020. var val = 0;
  8021. // var elem = selectedElements[0];
  8022. if(elem) {
  8023. var filter_url = elem.getAttribute('filter');
  8024. if(filter_url) {
  8025. var blur = getElem(elem.id + '_blur');
  8026. if(blur) {
  8027. val = blur.firstChild.getAttribute('stdDeviation');
  8028. }
  8029. }
  8030. }
  8031. return val;
  8032. };
  8033. (function() {
  8034. var cur_command = null;
  8035. var filter = null;
  8036. var filterHidden = false;
  8037. // Function: setBlurNoUndo
  8038. // Sets the stdDeviation blur value on the selected element without being undoable
  8039. //
  8040. // Parameters:
  8041. // val - The new stdDeviation value
  8042. canvas.setBlurNoUndo = function(val) {
  8043. if(!filter) {
  8044. canvas.setBlur(val);
  8045. return;
  8046. }
  8047. if(val === 0) {
  8048. // Don't change the StdDev, as that will hide the element.
  8049. // Instead, just remove the value for "filter"
  8050. changeSelectedAttributeNoUndo("filter", "");
  8051. filterHidden = true;
  8052. } else {
  8053. if(filterHidden) {
  8054. changeSelectedAttributeNoUndo("filter", 'url(#' + selectedElements[0].id + '_blur)');
  8055. }
  8056. changeSelectedAttributeNoUndo("stdDeviation", val, [filter.firstChild]);
  8057. canvas.setBlurOffsets(filter, val);
  8058. }
  8059. }
  8060. function finishChange() {
  8061. var bCmd = canvas.finishUndoableChange();
  8062. cur_command.addSubCommand(bCmd);
  8063. addCommandToHistory(cur_command);
  8064. cur_command = null;
  8065. filter = null;
  8066. }
  8067. // Function: setBlurOffsets
  8068. // Sets the x, y, with, height values of the filter element in order to
  8069. // make the blur not be clipped. Removes them if not neeeded
  8070. //
  8071. // Parameters:
  8072. // filter - The filter DOM element to update
  8073. // stdDev - The standard deviation value on which to base the offset size
  8074. canvas.setBlurOffsets = function(filter, stdDev) {
  8075. if(stdDev > 3) {
  8076. // TODO: Create algorithm here where size is based on expected blur
  8077. assignAttributes(filter, {
  8078. x: '-50%',
  8079. y: '-50%',
  8080. width: '200%',
  8081. height: '200%',
  8082. }, 100);
  8083. } else {
  8084. filter.removeAttribute('x');
  8085. filter.removeAttribute('y');
  8086. filter.removeAttribute('width');
  8087. filter.removeAttribute('height');
  8088. }
  8089. }
  8090. // Function: setBlur
  8091. // Adds/updates the blur filter to the selected element
  8092. //
  8093. // Parameters:
  8094. // val - Float with the new stdDeviation blur value
  8095. // complete - Boolean indicating whether or not the action should be completed (to add to the undo manager)
  8096. canvas.setBlur = function(val, complete) {
  8097. if(cur_command) {
  8098. finishChange();
  8099. return;
  8100. }
  8101. // Looks for associated blur, creates one if not found
  8102. var elem = selectedElements[0];
  8103. var elem_id = elem.id;
  8104. filter = getElem(elem_id + '_blur');
  8105. val -= 0;
  8106. var batchCmd = new BatchCommand();
  8107. // Blur found!
  8108. if(filter) {
  8109. if(val === 0) {
  8110. filter = null;
  8111. }
  8112. } else {
  8113. // Not found, so create
  8114. var newblur = addSvgElementFromJson({ "element": "feGaussianBlur",
  8115. "attr": {
  8116. "in": 'SourceGraphic',
  8117. "stdDeviation": val
  8118. }
  8119. });
  8120. filter = addSvgElementFromJson({ "element": "filter",
  8121. "attr": {
  8122. "id": elem_id + '_blur'
  8123. }
  8124. });
  8125. filter.appendChild(newblur);
  8126. findDefs().appendChild(filter);
  8127. batchCmd.addSubCommand(new InsertElementCommand(filter));
  8128. }
  8129. var changes = {filter: elem.getAttribute('filter')};
  8130. if(val === 0) {
  8131. elem.removeAttribute("filter");
  8132. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  8133. return;
  8134. } else {
  8135. changeSelectedAttribute("filter", 'url(#' + elem_id + '_blur)');
  8136. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  8137. canvas.setBlurOffsets(filter, val);
  8138. }
  8139. cur_command = batchCmd;
  8140. canvas.beginUndoableChange("stdDeviation", [filter?filter.firstChild:null]);
  8141. if(complete) {
  8142. canvas.setBlurNoUndo(val);
  8143. finishChange();
  8144. }
  8145. };
  8146. }());
  8147. // Function: getBold
  8148. // Check whether selected element is bold or not
  8149. //
  8150. // Returns:
  8151. // Boolean indicating whether or not element is bold
  8152. this.getBold = function() {
  8153. // should only have one element selected
  8154. var selected = selectedElements[0];
  8155. if (selected != null && selected.tagName == "text" &&
  8156. selectedElements[1] == null)
  8157. {
  8158. return (selected.getAttribute("font-weight") == "bold");
  8159. }
  8160. return false;
  8161. };
  8162. // Function: setBold
  8163. // Make the selected element bold or normal
  8164. //
  8165. // Parameters:
  8166. // b - Boolean indicating bold (true) or normal (false)
  8167. this.setBold = function(b) {
  8168. var selected = selectedElements[0];
  8169. if (selected != null && selected.tagName == "text" &&
  8170. selectedElements[1] == null)
  8171. {
  8172. changeSelectedAttribute("font-weight", b ? "bold" : "normal");
  8173. }
  8174. };
  8175. // Function: getItalic
  8176. // Check whether selected element is italic or not
  8177. //
  8178. // Returns:
  8179. // Boolean indicating whether or not element is italic
  8180. this.getItalic = function() {
  8181. var selected = selectedElements[0];
  8182. if (selected != null && selected.tagName == "text" &&
  8183. selectedElements[1] == null)
  8184. {
  8185. return (selected.getAttribute("font-style") == "italic");
  8186. }
  8187. return false;
  8188. };
  8189. // Function: setItalic
  8190. // Make the selected element italic or normal
  8191. //
  8192. // Parameters:
  8193. // b - Boolean indicating italic (true) or normal (false)
  8194. this.setItalic = function(i) {
  8195. var selected = selectedElements[0];
  8196. if (selected != null && selected.tagName == "text" &&
  8197. selectedElements[1] == null)
  8198. {
  8199. changeSelectedAttribute("font-style", i ? "italic" : "normal");
  8200. }
  8201. };
  8202. // Function: getFontFamily
  8203. // Returns the current font family
  8204. this.getFontFamily = function() {
  8205. return cur_text.font_family;
  8206. };
  8207. // Function: setFontFamily
  8208. // Set the new font family
  8209. //
  8210. // Parameters:
  8211. // val - String with the new font family
  8212. this.setFontFamily = function(val) {
  8213. cur_text.font_family = val;
  8214. changeSelectedAttribute("font-family", val);
  8215. };
  8216. // Function: getFontSize
  8217. // Returns the current font size
  8218. this.getFontSize = function() {
  8219. return cur_text.font_size;
  8220. };
  8221. // Function: setFontSize
  8222. // Applies the given font size to the selected element
  8223. //
  8224. // Parameters:
  8225. // val - Float with the new font size
  8226. this.setFontSize = function(val) {
  8227. cur_text.font_size = val;
  8228. textActions.toSelectMode();
  8229. changeSelectedAttribute("font-size", val);
  8230. };
  8231. // Function: getText
  8232. // Returns the current text (textContent) of the selected element
  8233. this.getText = function() {
  8234. var selected = selectedElements[0];
  8235. if (selected == null) { return ""; }
  8236. return selected.textContent;
  8237. };
  8238. // Function: setTextContent
  8239. // Updates the text element with the given string
  8240. //
  8241. // Parameters:
  8242. // val - String with the new text
  8243. this.setTextContent = function(val) {
  8244. changeSelectedAttribute("#text", val);
  8245. textActions.init(val);
  8246. textActions.setCursor();
  8247. };
  8248. // Function: setImageURL
  8249. // Sets the new image URL for the selected image element. Updates its size if
  8250. // a new URL is given
  8251. //
  8252. // Parameters:
  8253. // val - String with the image URL/path
  8254. this.setImageURL = function(val) {
  8255. var elem = selectedElements[0];
  8256. if(!elem) return;
  8257. var attrs = $(elem).attr(['width', 'height']);
  8258. var setsize = (!attrs.width || !attrs.height);
  8259. var cur_href = elem.getAttributeNS(xlinkns, "href");
  8260. // Do nothing if no URL change or size change
  8261. if(cur_href !== val) {
  8262. setsize = true;
  8263. } else if(!setsize) return;
  8264. var batchCmd = new BatchCommand("Change Image URL");
  8265. elem.setAttributeNS(xlinkns, "xlink:href", val);
  8266. batchCmd.addSubCommand(new ChangeElementCommand(elem, {
  8267. "#href": cur_href
  8268. }));
  8269. if(setsize) {
  8270. $(new Image()).load(function() {
  8271. var changes = $(elem).attr(['width', 'height']);
  8272. $(elem).attr({
  8273. width: this.width,
  8274. height: this.height
  8275. });
  8276. selectorManager.requestSelector(elem).resize();
  8277. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  8278. addCommandToHistory(batchCmd);
  8279. call("changed", elem);
  8280. }).attr('src',val);
  8281. } else {
  8282. addCommandToHistory(batchCmd);
  8283. }
  8284. };
  8285. // Function: setRectRadius
  8286. // Sets the rx & ry values to the selected rect element to change its corner radius
  8287. //
  8288. // Parameters:
  8289. // val - The new radius
  8290. this.setRectRadius = function(val) {
  8291. var selected = selectedElements[0];
  8292. if (selected != null && selected.tagName == "rect") {
  8293. var r = selected.getAttribute("rx");
  8294. if (r != val) {
  8295. selected.setAttribute("rx", val);
  8296. selected.setAttribute("ry", val);
  8297. addCommandToHistory(new ChangeElementCommand(selected, {"rx":r, "ry":r}, "Radius"));
  8298. call("changed", [selected]);
  8299. }
  8300. }
  8301. };
  8302. // Group: Element manipulation
  8303. // Function: setSegType
  8304. // Sets the new segment type to the selected segment(s).
  8305. //
  8306. // Parameters:
  8307. // new_type - Integer with the new segment type
  8308. // See http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg for list
  8309. this.setSegType = function(new_type) {
  8310. pathActions.setSegType(new_type);
  8311. }
  8312. // Function: convertToPath
  8313. // Convert selected element to a path, or get the BBox of an element-as-path
  8314. //
  8315. // Parameters:
  8316. // elem - The DOM element to be converted
  8317. // getBBox - Boolean on whether or not to only return the path's BBox
  8318. //
  8319. // Returns:
  8320. // If the getBBox flag is true, the resulting path's bounding box object.
  8321. // Otherwise the resulting path element is returned.
  8322. this.convertToPath = function(elem, getBBox) {
  8323. if(elem == null) {
  8324. var elems = selectedElements;
  8325. $.each(selectedElements, function(i, elem) {
  8326. if(elem) canvas.convertToPath(elem);
  8327. });
  8328. return;
  8329. }
  8330. if(!getBBox) {
  8331. var batchCmd = new BatchCommand("Convert element to Path");
  8332. }
  8333. var attrs = getBBox?{}:{
  8334. "fill": cur_shape.fill,
  8335. "fill-opacity": cur_shape.fill_opacity,
  8336. "stroke": cur_shape.stroke,
  8337. "stroke-width": cur_shape.stroke_width,
  8338. "stroke-dasharray": cur_shape.stroke_dasharray,
  8339. "stroke-linejoin": cur_shape.stroke_linejoin,
  8340. "stroke-linecap": cur_shape.stroke_linecap,
  8341. "stroke-opacity": cur_shape.stroke_opacity,
  8342. "opacity": cur_shape.opacity,
  8343. "visibility":"hidden"
  8344. };
  8345. // any attribute on the element not covered by the above
  8346. // TODO: make this list global so that we can properly maintain it
  8347. // TODO: what about @transform, @clip-rule, @fill-rule, etc?
  8348. $.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function() {
  8349. if (elem.getAttribute(this)) {
  8350. attrs[this] = elem.getAttribute(this);
  8351. }
  8352. });
  8353. var path = addSvgElementFromJson({
  8354. "element": "path",
  8355. "attr": attrs
  8356. });
  8357. var eltrans = elem.getAttribute("transform");
  8358. if(eltrans) {
  8359. path.setAttribute("transform",eltrans);
  8360. }
  8361. var id = elem.id;
  8362. var parent = elem.parentNode;
  8363. if(elem.nextSibling) {
  8364. parent.insertBefore(path, elem);
  8365. } else {
  8366. parent.appendChild(path);
  8367. }
  8368. var d = '';
  8369. var joinSegs = function(segs) {
  8370. $.each(segs, function(j, seg) {
  8371. var l = seg[0], pts = seg[1];
  8372. d += l;
  8373. for(var i=0; i < pts.length; i+=2) {
  8374. d += (pts[i] +','+pts[i+1]) + ' ';
  8375. }
  8376. });
  8377. }
  8378. // Possibly the cubed root of 6, but 1.81 works best
  8379. var num = 1.81;
  8380. switch (elem.tagName) {
  8381. case 'ellipse':
  8382. case 'circle':
  8383. var a = $(elem).attr(['rx', 'ry', 'cx', 'cy']);
  8384. var cx = a.cx, cy = a.cy, rx = a.rx, ry = a.ry;
  8385. if(elem.tagName == 'circle') {
  8386. rx = ry = $(elem).attr('r');
  8387. }
  8388. joinSegs([
  8389. ['M',[(cx-rx),(cy)]],
  8390. ['C',[(cx-rx),(cy-ry/num), (cx-rx/num),(cy-ry), (cx),(cy-ry)]],
  8391. ['C',[(cx+rx/num),(cy-ry), (cx+rx),(cy-ry/num), (cx+rx),(cy)]],
  8392. ['C',[(cx+rx),(cy+ry/num), (cx+rx/num),(cy+ry), (cx),(cy+ry)]],
  8393. ['C',[(cx-rx/num),(cy+ry), (cx-rx),(cy+ry/num), (cx-rx),(cy)]],
  8394. ['Z',[]]
  8395. ]);
  8396. break;
  8397. case 'path':
  8398. d = elem.getAttribute('d');
  8399. break;
  8400. case 'line':
  8401. var a = $(elem).attr(["x1", "y1", "x2", "y2"]);
  8402. d = "M"+a.x1+","+a.y1+"L"+a.x2+","+a.y2;
  8403. break;
  8404. case 'polyline':
  8405. case 'polygon':
  8406. d = "M" + elem.getAttribute('points');
  8407. break;
  8408. case 'rect':
  8409. var r = $(elem).attr(['rx', 'ry']);
  8410. var rx = r.rx, ry = r.ry;
  8411. var b = elem.getBBox();
  8412. var x = b.x, y = b.y, w = b.width, h = b.height;
  8413. var num = 4-num; // Why? Because!
  8414. if(!rx && !ry) {
  8415. // Regular rect
  8416. joinSegs([
  8417. ['M',[x, y]],
  8418. ['L',[x+w, y]],
  8419. ['L',[x+w, y+h]],
  8420. ['L',[x, y+h]],
  8421. ['L',[x, y]],
  8422. ['Z',[]]
  8423. ]);
  8424. } else {
  8425. joinSegs([
  8426. ['M',[x, y+ry]],
  8427. ['C',[x,y+ry/num, x+rx/num,y, x+rx,y]],
  8428. ['L',[x+w-rx, y]],
  8429. ['C',[x+w-rx/num,y, x+w,y+ry/num, x+w,y+ry]],
  8430. ['L',[x+w, y+h-ry]],
  8431. ['C',[x+w, y+h-ry/num, x+w-rx/num,y+h, x+w-rx,y+h]],
  8432. ['L',[x+rx, y+h]],
  8433. ['C',[x+rx/num, y+h, x,y+h-ry/num, x,y+h-ry]],
  8434. ['L',[x, y+ry]],
  8435. ['Z',[]]
  8436. ]);
  8437. }
  8438. break;
  8439. default:
  8440. path.parentNode.removeChild(path);
  8441. break;
  8442. }
  8443. if(d) {
  8444. path.setAttribute('d',d);
  8445. }
  8446. if(!getBBox) {
  8447. // Replace the current element with the converted one
  8448. // Reorient if it has a matrix
  8449. if(eltrans) {
  8450. var tlist = getTransformList(path);
  8451. if(hasMatrixTransform(tlist)) {
  8452. pathActions.resetOrientation(path);
  8453. }
  8454. }
  8455. batchCmd.addSubCommand(new RemoveElementCommand(elem, parent));
  8456. batchCmd.addSubCommand(new InsertElementCommand(path));
  8457. clearSelection();
  8458. elem.parentNode.removeChild(elem)
  8459. path.setAttribute('id', id);
  8460. path.removeAttribute("visibility");
  8461. addToSelection([path], true);
  8462. addCommandToHistory(batchCmd);
  8463. } else {
  8464. // Get the correct BBox of the new path, then discard it
  8465. pathActions.resetOrientation(path);
  8466. var bb = false;
  8467. try {
  8468. bb = path.getBBox();
  8469. } catch(e) {
  8470. // Firefox fails
  8471. }
  8472. path.parentNode.removeChild(path);
  8473. return bb;
  8474. }
  8475. }
  8476. // Function: changeSelectedAttributeNoUndo
  8477. // This function makes the changes to the elements. It does not add the change
  8478. // to the history stack.
  8479. //
  8480. // Parameters:
  8481. // attr - String with the attribute name
  8482. // newValue - String or number with the new attribute value
  8483. // elems - The DOM elements to apply the change to
  8484. var changeSelectedAttributeNoUndo = function(attr, newValue, elems) {
  8485. var handle = svgroot.suspendRedraw(1000);
  8486. if(current_mode == 'pathedit') {
  8487. // Editing node
  8488. pathActions.moveNode(attr, newValue);
  8489. }
  8490. var elems = elems || selectedElements;
  8491. var i = elems.length;
  8492. while (i--) {
  8493. var elem = elems[i];
  8494. if (elem == null) continue;
  8495. // Go into "select" mode for text changes
  8496. if(current_mode === "textedit" && attr !== "#text") {
  8497. textActions.toSelectMode(elem);
  8498. }
  8499. // Set x,y vals on elements that don't have them
  8500. if((attr == 'x' || attr == 'y') && $.inArray(elem.tagName, ['g', 'polyline', 'path']) != -1) {
  8501. var bbox = getStrokedBBox([elem]);
  8502. var diff_x = attr == 'x' ? newValue - bbox.x : 0;
  8503. var diff_y = attr == 'y' ? newValue - bbox.y : 0;
  8504. canvas.moveSelectedElements(diff_x*current_zoom, diff_y*current_zoom, true);
  8505. continue;
  8506. }
  8507. // only allow the transform/opacity attribute to change on <g> elements, slightly hacky
  8508. if (elem.tagName == "g" && $.inArray(attr, ['transform', 'opacity', 'filter']) !== -1);
  8509. var oldval = attr == "#text" ? elem.textContent : elem.getAttribute(attr);
  8510. if (oldval == null) oldval = "";
  8511. if (oldval != String(newValue)) {
  8512. if (attr == "#text") {
  8513. var old_w = getBBox(elem).width;
  8514. elem.textContent = newValue;
  8515. elem = ffClone(elem);
  8516. // Hoped to solve the issue of moving text with text-anchor="start",
  8517. // but this doesn't actually fix it. Hopefully on the right track, though. -Fyrd
  8518. // var box=getBBox(elem), left=box.x, top=box.y, width=box.width,
  8519. // height=box.height, dx = width - old_w, dy=0;
  8520. // var angle = getRotationAngle(elem, true);
  8521. // if (angle) {
  8522. // var r = Math.sqrt( dx*dx + dy*dy );
  8523. // var theta = Math.atan2(dy,dx) - angle;
  8524. // dx = r * Math.cos(theta);
  8525. // dy = r * Math.sin(theta);
  8526. //
  8527. // elem.setAttribute('x', elem.getAttribute('x')-dx);
  8528. // elem.setAttribute('y', elem.getAttribute('y')-dy);
  8529. // }
  8530. } else if (attr == "#href") {
  8531. elem.setAttributeNS(xlinkns, "xlink:href", newValue);
  8532. }
  8533. else elem.setAttribute(attr, newValue);
  8534. if (i==0)
  8535. selectedBBoxes[i] = getBBox(elem);
  8536. // Use the Firefox ffClone hack for text elements with gradients or
  8537. // where other text attributes are changed.
  8538. if(elem.nodeName == 'text') {
  8539. if((newValue+'').indexOf('url') == 0 || $.inArray(attr, ['font-size','font-family','x','y']) != -1) {
  8540. elem = ffClone(elem);
  8541. }
  8542. }
  8543. // Timeout needed for Opera & Firefox
  8544. // codedread: it is now possible for this function to be called with elements
  8545. // that are not in the selectedElements array, we need to only request a
  8546. // selector if the element is in that array
  8547. if ($.inArray(elem, selectedElements) != -1) {
  8548. setTimeout(function() {
  8549. // Due to element replacement, this element may no longer
  8550. // be part of the DOM
  8551. if(!elem.parentNode) return;
  8552. selectorManager.requestSelector(elem).resize();
  8553. },0);
  8554. }
  8555. // if this element was rotated, and we changed the position of this element
  8556. // we need to update the rotational transform attribute
  8557. var angle = getRotationAngle(elem);
  8558. if (angle != 0 && attr != "transform") {
  8559. var tlist = getTransformList(elem);
  8560. var n = tlist.numberOfItems;
  8561. while (n--) {
  8562. var xform = tlist.getItem(n);
  8563. if (xform.type == 4) {
  8564. // remove old rotate
  8565. tlist.removeItem(n);
  8566. var box = getBBox(elem);
  8567. var center = transformPoint(box.x+box.width/2, box.y+box.height/2, transformListToTransform(tlist).matrix);
  8568. var cx = center.x,
  8569. cy = center.y;
  8570. var newrot = svgroot.createSVGTransform();
  8571. newrot.setRotate(angle, cx, cy);
  8572. tlist.insertItemBefore(newrot, n);
  8573. break;
  8574. }
  8575. }
  8576. }
  8577. } // if oldValue != newValue
  8578. } // for each elem
  8579. svgroot.unsuspendRedraw(handle);
  8580. };
  8581. // Function: changeSelectedAttribute
  8582. // Change the given/selected element and add the original value to the history stack
  8583. // If you want to change all selectedElements, ignore the elems argument.
  8584. // If you want to change only a subset of selectedElements, then send the
  8585. // subset to this function in the elems argument.
  8586. //
  8587. // Parameters:
  8588. // attr - String with the attribute name
  8589. // newValue - String or number with the new attribute value
  8590. // elems - The DOM elements to apply the change to
  8591. var changeSelectedAttribute = this.changeSelectedAttribute = function(attr, val, elems) {
  8592. var elems = elems || selectedElements;
  8593. canvas.beginUndoableChange(attr, elems);
  8594. var i = elems.length;
  8595. changeSelectedAttributeNoUndo(attr, val, elems);
  8596. var batchCmd = canvas.finishUndoableChange();
  8597. if (!batchCmd.isEmpty()) {
  8598. addCommandToHistory(batchCmd);
  8599. }
  8600. };
  8601. // Function: deleteSelectedElements
  8602. // Removes all selected elements from the DOM and adds the change to the
  8603. // history stack
  8604. this.deleteSelectedElements = function() {
  8605. var batchCmd = new BatchCommand("Delete Elements");
  8606. var len = selectedElements.length;
  8607. var selectedCopy = []; //selectedElements is being deleted
  8608. for (var i = 0; i < len; ++i) {
  8609. var selected = selectedElements[i];
  8610. if (selected == null) break;
  8611. var parent = selected.parentNode;
  8612. var t = selected;
  8613. // this will unselect the element and remove the selectedOutline
  8614. selectorManager.releaseSelector(t);
  8615. var elem = parent.removeChild(t);
  8616. selectedCopy.push(selected) //for the copy
  8617. selectedElements[i] = null;
  8618. batchCmd.addSubCommand(new RemoveElementCommand(elem, parent));
  8619. }
  8620. if (!batchCmd.isEmpty()) addCommandToHistory(batchCmd);
  8621. call("changed", selectedCopy);
  8622. clearSelection();
  8623. };
  8624. // Function: groupSelectedElements
  8625. // Wraps all the selected elements in a group (g) element
  8626. this.groupSelectedElements = function() {
  8627. var batchCmd = new BatchCommand("Group Elements");
  8628. // create and insert the group element
  8629. var g = addSvgElementFromJson({
  8630. "element": "g",
  8631. "attr": {
  8632. "id": getNextId()
  8633. }
  8634. });
  8635. batchCmd.addSubCommand(new InsertElementCommand(g));
  8636. // now move all children into the group
  8637. var i = selectedElements.length;
  8638. while (i--) {
  8639. var elem = selectedElements[i];
  8640. if (elem == null) continue;
  8641. var oldNextSibling = elem.nextSibling;
  8642. var oldParent = elem.parentNode;
  8643. g.appendChild(elem);
  8644. batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldParent));
  8645. }
  8646. if (!batchCmd.isEmpty()) addCommandToHistory(batchCmd);
  8647. // update selection
  8648. clearSelection();
  8649. addToSelection([g], true);
  8650. };
  8651. // Function: ungroupSelectedElement
  8652. // Unwraps all the elements in a selected group (g) element. This requires
  8653. // significant recalculations to apply group's transforms, etc to its children
  8654. this.ungroupSelectedElement = function() {
  8655. var g = selectedElements[0];
  8656. if (g.tagName == "g") {
  8657. var batchCmd = new BatchCommand("Ungroup Elements");
  8658. var parent = g.parentNode;
  8659. var anchor = g.previousSibling;
  8660. var children = new Array(g.childNodes.length);
  8661. var xform = g.getAttribute("transform");
  8662. // get consolidated matrix
  8663. var glist = getTransformList(g);
  8664. var m = transformListToTransform(glist).matrix;
  8665. // TODO: get all fill/stroke properties from the group that we are about to destroy
  8666. // "fill", "fill-opacity", "fill-rule", "stroke", "stroke-dasharray", "stroke-dashoffset",
  8667. // "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity",
  8668. // "stroke-width"
  8669. // and then for each child, if they do not have the attribute (or the value is 'inherit')
  8670. // then set the child's attribute
  8671. var i = 0;
  8672. var gangle = getRotationAngle(g);
  8673. var gattrs = $(g).attr(['filter', 'opacity']);
  8674. var gfilter, gblur;
  8675. while (g.firstChild) {
  8676. var elem = g.firstChild;
  8677. var oldNextSibling = elem.nextSibling;
  8678. var oldParent = elem.parentNode;
  8679. children[i++] = elem = parent.insertBefore(elem, anchor);
  8680. batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldParent));
  8681. if(gattrs.opacity !== null && gattrs.opacity !== 1) {
  8682. var c_opac = elem.getAttribute('opacity') || 1;
  8683. var new_opac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100)/100;
  8684. changeSelectedAttribute('opacity', new_opac, [elem]);
  8685. }
  8686. if(gattrs.filter) {
  8687. var cblur = this.getBlur(elem);
  8688. var orig_cblur = cblur;
  8689. if(!gblur) gblur = this.getBlur(g);
  8690. if(cblur) {
  8691. // Is this formula correct?
  8692. cblur = (gblur-0) + (cblur-0);
  8693. } else if(cblur === 0) {
  8694. cblur = gblur;
  8695. }
  8696. // If child has no current filter, get group's filter or clone it.
  8697. if(!orig_cblur) {
  8698. // Set group's filter to use first child's ID
  8699. if(!gfilter) {
  8700. gfilter = getElem(getUrlFromAttr(gattrs.filter).substr(1));
  8701. } else {
  8702. // Clone the group's filter
  8703. gfilter = copyElem(gfilter);
  8704. findDefs().appendChild(gfilter);
  8705. }
  8706. } else {
  8707. gfilter = getElem(getUrlFromAttr(elem.getAttribute('filter')).substr(1));
  8708. }
  8709. // Change this in future for different filters
  8710. var suffix = (gfilter.firstChild.tagName === 'feGaussianBlur')?'blur':'filter';
  8711. gfilter.id = elem.id + '_' + suffix;
  8712. changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]);
  8713. // Update blur value
  8714. if(cblur) {
  8715. changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]);
  8716. canvas.setBlurOffsets(gfilter, cblur);
  8717. }
  8718. }
  8719. var chtlist = getTransformList(elem);
  8720. if (glist.numberOfItems) {
  8721. // TODO: if the group's transform is just a rotate, we can always transfer the
  8722. // rotate() down to the children (collapsing consecutive rotates and factoring
  8723. // out any translates)
  8724. if (gangle && glist.numberOfItems == 1) {
  8725. // [Rg] [Rc] [Mc]
  8726. // we want [Tr] [Rc2] [Mc] where:
  8727. // - [Rc2] is at the child's current center but has the
  8728. // sum of the group and child's rotation angles
  8729. // - [Tr] is the equivalent translation that this child
  8730. // undergoes if the group wasn't there
  8731. // [Tr] = [Rg] [Rc] [Rc2_inv]
  8732. // get group's rotation matrix (Rg)
  8733. var rgm = glist.getItem(0).matrix;
  8734. // get child's rotation matrix (Rc)
  8735. var rcm = svgroot.createSVGMatrix();
  8736. var cangle = getRotationAngle(elem);
  8737. if (cangle) {
  8738. rcm = chtlist.getItem(0).matrix;
  8739. }
  8740. // get child's old center of rotation
  8741. var cbox = getBBox(elem);
  8742. var ceqm = transformListToTransform(chtlist).matrix;
  8743. var coldc = transformPoint(cbox.x+cbox.width/2, cbox.y+cbox.height/2,ceqm);
  8744. // sum group and child's angles
  8745. var sangle = gangle + cangle;
  8746. // get child's rotation at the old center (Rc2_inv)
  8747. var r2 = svgroot.createSVGTransform();
  8748. r2.setRotate(sangle, coldc.x, coldc.y);
  8749. // calculate equivalent translate
  8750. var trm = matrixMultiply(rgm, rcm, r2.matrix.inverse());
  8751. // set up tlist
  8752. if (cangle) {
  8753. chtlist.removeItem(0);
  8754. }
  8755. if (sangle) {
  8756. chtlist.insertItemBefore(r2, 0);
  8757. }
  8758. if (trm.e || trm.f) {
  8759. var tr = svgroot.createSVGTransform();
  8760. tr.setTranslate(trm.e, trm.f);
  8761. chtlist.insertItemBefore(tr, 0);
  8762. }
  8763. }
  8764. else { // more complicated than just a rotate
  8765. // transfer the group's transform down to each child and then
  8766. // call recalculateDimensions()
  8767. var oldxform = elem.getAttribute("transform");
  8768. var changes = {};
  8769. changes["transform"] = oldxform ? oldxform : "";
  8770. var newxform = svgroot.createSVGTransform();
  8771. // [ gm ] [ chm ] = [ chm ] [ gm' ]
  8772. // [ gm' ] = [ chm_inv ] [ gm ] [ chm ]
  8773. var chm = transformListToTransform(chtlist).matrix,
  8774. chm_inv = chm.inverse();
  8775. var gm = matrixMultiply( chm_inv, m, chm );
  8776. newxform.setMatrix(gm);
  8777. chtlist.appendItem(newxform);
  8778. }
  8779. batchCmd.addSubCommand(recalculateDimensions(elem));
  8780. }
  8781. }
  8782. // remove transform and make it undo-able
  8783. if (xform) {
  8784. var changes = {};
  8785. changes["transform"] = xform;
  8786. g.setAttribute("transform", "");
  8787. g.removeAttribute("transform");
  8788. batchCmd.addSubCommand(new ChangeElementCommand(g, changes));
  8789. }
  8790. // remove the group from the selection
  8791. clearSelection();
  8792. // delete the group element (but make undo-able)
  8793. g = parent.removeChild(g);
  8794. batchCmd.addSubCommand(new RemoveElementCommand(g, parent));
  8795. if (!batchCmd.isEmpty()) addCommandToHistory(batchCmd);
  8796. // update selection
  8797. addToSelection(children);
  8798. }
  8799. };
  8800. // Function: moveToTopSelectedElement
  8801. // Repositions the selected element to the bottom in the DOM to appear on top of
  8802. // other elements
  8803. this.moveToTopSelectedElement = function() {
  8804. var selected = selectedElements[0];
  8805. if (selected != null) {
  8806. var t = selected;
  8807. var oldParent = t.parentNode;
  8808. var oldNextSibling = t.nextSibling;
  8809. t = t.parentNode.appendChild(t);
  8810. addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, "top"));
  8811. }
  8812. };
  8813. // Function: moveToBottomSelectedElement
  8814. // Repositions the selected element to the top in the DOM to appear under
  8815. // other elements
  8816. this.moveToBottomSelectedElement = function() {
  8817. var selected = selectedElements[0];
  8818. if (selected != null) {
  8819. var t = selected;
  8820. var oldParent = t.parentNode;
  8821. var oldNextSibling = t.nextSibling;
  8822. var firstChild = t.parentNode.firstChild;
  8823. if (firstChild.tagName == 'title') {
  8824. firstChild = firstChild.nextSibling;
  8825. }
  8826. // This can probably be removed, as the defs should not ever apppear
  8827. // inside a layer group
  8828. if (firstChild.tagName == 'defs') {
  8829. firstChild = firstChild.nextSibling;
  8830. }
  8831. t = t.parentNode.insertBefore(t, firstChild);
  8832. addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, "bottom"));
  8833. }
  8834. };
  8835. // Function: moveSelectedElements
  8836. // Moves selected elements on the X/Y axis
  8837. //
  8838. // Parameters:
  8839. // dx - Float with the distance to move on the x-axis
  8840. // dy - Float with the distance to move on the y-axis
  8841. // undoable - Boolean indicating whether or not the action should be undoable
  8842. //
  8843. // Returns:
  8844. // Batch command for the move
  8845. this.moveSelectedElements = function(dx,dy,undoable) {
  8846. // if undoable is not sent, default to true
  8847. // if single values, scale them to the zoom
  8848. if (dx.constructor != Array) {
  8849. dx /= current_zoom;
  8850. dy /= current_zoom;
  8851. }
  8852. var undoable = undoable || true;
  8853. var batchCmd = new BatchCommand("position");
  8854. var i = selectedElements.length;
  8855. while (i--) {
  8856. var selected = selectedElements[i];
  8857. if (selected != null) {
  8858. if (i==0)
  8859. selectedBBoxes[i] = getBBox(selected);
  8860. var xform = svgroot.createSVGTransform();
  8861. var tlist = getTransformList(selected);
  8862. // dx and dy could be arrays
  8863. if (dx.constructor == Array) {
  8864. if (i==0) {
  8865. selectedBBoxes[i].x += dx[i];
  8866. selectedBBoxes[i].y += dy[i];
  8867. }
  8868. xform.setTranslate(dx[i],dy[i]);
  8869. } else {
  8870. if (i==0) {
  8871. selectedBBoxes[i].x += dx;
  8872. selectedBBoxes[i].y += dy;
  8873. }
  8874. xform.setTranslate(dx,dy);
  8875. }
  8876. tlist.insertItemBefore(xform, 0);
  8877. var cmd = recalculateDimensions(selected);
  8878. if (cmd) {
  8879. batchCmd.addSubCommand(cmd);
  8880. }
  8881. selectorManager.requestSelector(selected).resize();
  8882. }
  8883. }
  8884. if (!batchCmd.isEmpty()) {
  8885. if (undoable)
  8886. addCommandToHistory(batchCmd);
  8887. call("changed", selectedElements);
  8888. return batchCmd;
  8889. }
  8890. };
  8891. // Function: cloneSelectedElements
  8892. // Create deep DOM copies (clones) of all selected elements and move them slightly
  8893. // from their originals
  8894. this.cloneSelectedElements = function() {
  8895. var batchCmd = new BatchCommand("Clone Elements");
  8896. // find all the elements selected (stop at first null)
  8897. var len = selectedElements.length;
  8898. for (var i = 0; i < len; ++i) {
  8899. var elem = selectedElements[i];
  8900. if (elem == null) break;
  8901. }
  8902. // use slice to quickly get the subset of elements we need
  8903. var copiedElements = selectedElements.slice(0,i);
  8904. this.clearSelection();
  8905. // note that we loop in the reverse way because of the way elements are added
  8906. // to the selectedElements array (top-first)
  8907. var i = copiedElements.length;
  8908. while (i--) {
  8909. // clone each element and replace it within copiedElements
  8910. var elem = copiedElements[i] = copyElem(copiedElements[i]);
  8911. current_layer.appendChild(elem);
  8912. batchCmd.addSubCommand(new InsertElementCommand(elem));
  8913. }
  8914. if (!batchCmd.isEmpty()) {
  8915. addToSelection(copiedElements.reverse()); // Need to reverse for correct selection-adding
  8916. this.moveSelectedElements(20,20,false);
  8917. addCommandToHistory(batchCmd);
  8918. call("selected", selectedElements);
  8919. }
  8920. };
  8921. // Function: alignSelectedElements
  8922. // Aligns selected elements
  8923. //
  8924. // Parameters:
  8925. // type - String with single character indicating the alignment type
  8926. // relative_to - String that must be one of the following:
  8927. // "selected", "largest", "smallest", "page"
  8928. this.alignSelectedElements = function(type, relative_to) {
  8929. var bboxes = [], angles = [];
  8930. var minx = Number.MAX_VALUE, maxx = Number.MIN_VALUE, miny = Number.MAX_VALUE, maxy = Number.MIN_VALUE;
  8931. var curwidth = Number.MIN_VALUE, curheight = Number.MIN_VALUE;
  8932. var len = selectedElements.length;
  8933. if (!len) return;
  8934. for (var i = 0; i < len; ++i) {
  8935. if (selectedElements[i] == null) break;
  8936. var elem = selectedElements[i];
  8937. bboxes[i] = getStrokedBBox([elem]);
  8938. // now bbox is axis-aligned and handles rotation
  8939. switch (relative_to) {
  8940. case 'smallest':
  8941. if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth > bboxes[i].width) ||
  8942. (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight > bboxes[i].height) ) {
  8943. minx = bboxes[i].x;
  8944. miny = bboxes[i].y;
  8945. maxx = bboxes[i].x + bboxes[i].width;
  8946. maxy = bboxes[i].y + bboxes[i].height;
  8947. curwidth = bboxes[i].width;
  8948. curheight = bboxes[i].height;
  8949. }
  8950. break;
  8951. case 'largest':
  8952. if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth < bboxes[i].width) ||
  8953. (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight < bboxes[i].height) ) {
  8954. minx = bboxes[i].x;
  8955. miny = bboxes[i].y;
  8956. maxx = bboxes[i].x + bboxes[i].width;
  8957. maxy = bboxes[i].y + bboxes[i].height;
  8958. curwidth = bboxes[i].width;
  8959. curheight = bboxes[i].height;
  8960. }
  8961. break;
  8962. default: // 'selected'
  8963. if (bboxes[i].x < minx) minx = bboxes[i].x;
  8964. if (bboxes[i].y < miny) miny = bboxes[i].y;
  8965. if (bboxes[i].x + bboxes[i].width > maxx) maxx = bboxes[i].x + bboxes[i].width;
  8966. if (bboxes[i].y + bboxes[i].height > maxy) maxy = bboxes[i].y + bboxes[i].height;
  8967. break;
  8968. }
  8969. } // loop for each element to find the bbox and adjust min/max
  8970. if (relative_to == 'page') {
  8971. minx = 0;
  8972. miny = 0;
  8973. maxx = canvas.contentW;
  8974. maxy = canvas.contentH;
  8975. }
  8976. var dx = new Array(len);
  8977. var dy = new Array(len);
  8978. for (var i = 0; i < len; ++i) {
  8979. if (selectedElements[i] == null) break;
  8980. var elem = selectedElements[i];
  8981. var bbox = bboxes[i];
  8982. dx[i] = 0;
  8983. dy[i] = 0;
  8984. switch (type) {
  8985. case 'l': // left (horizontal)
  8986. dx[i] = minx - bbox.x;
  8987. break;
  8988. case 'c': // center (horizontal)
  8989. dx[i] = (minx+maxx)/2 - (bbox.x + bbox.width/2);
  8990. break;
  8991. case 'r': // right (horizontal)
  8992. dx[i] = maxx - (bbox.x + bbox.width);
  8993. break;
  8994. case 't': // top (vertical)
  8995. dy[i] = miny - bbox.y;
  8996. break;
  8997. case 'm': // middle (vertical)
  8998. dy[i] = (miny+maxy)/2 - (bbox.y + bbox.height/2);
  8999. break;
  9000. case 'b': // bottom (vertical)
  9001. dy[i] = maxy - (bbox.y + bbox.height);
  9002. break;
  9003. }
  9004. }
  9005. this.moveSelectedElements(dx,dy);
  9006. };
  9007. // Group: Additional editor tools
  9008. this.contentW = getResolution().w;
  9009. this.contentH = getResolution().h;
  9010. // Function: updateCanvas
  9011. // Updates the editor canvas width/height/position after a zoom has occurred
  9012. //
  9013. // Parameters:
  9014. // w - Float with the new width
  9015. // h - Float with the new height
  9016. //
  9017. // Returns:
  9018. // Object with the following values:
  9019. // * x - The canvas' new x coordinate
  9020. // * y - The canvas' new y coordinate
  9021. // * old_x - The canvas' old x coordinate
  9022. // * old_y - The canvas' old y coordinate
  9023. // * d_x - The x position difference
  9024. // * d_y - The y position difference
  9025. this.updateCanvas = function(w, h) {
  9026. svgroot.setAttribute("width", w);
  9027. svgroot.setAttribute("height", h);
  9028. var bg = $('#canvasBackground')[0];
  9029. var old_x = svgcontent.getAttribute('x');
  9030. var old_y = svgcontent.getAttribute('y');
  9031. var x = (w/2 - this.contentW*current_zoom/2);
  9032. var y = (h/2 - this.contentH*current_zoom/2);
  9033. assignAttributes(svgcontent, {
  9034. width: this.contentW*current_zoom,
  9035. height: this.contentH*current_zoom,
  9036. 'x': x,
  9037. 'y': y,
  9038. "viewBox" : "0 0 " + this.contentW + " " + this.contentH
  9039. });
  9040. assignAttributes(bg, {
  9041. width: svgcontent.getAttribute('width'),
  9042. height: svgcontent.getAttribute('height'),
  9043. x: x,
  9044. y: y
  9045. });
  9046. selectorManager.selectorParentGroup.setAttribute("transform","translate(" + x + "," + y + ")");
  9047. return {x:x, y:y, old_x:old_x, old_y:old_y, d_x:x - old_x, d_y:y - old_y};
  9048. }
  9049. // Function: setBackground
  9050. // Set the background of the editor (NOT the actual document)
  9051. //
  9052. // Parameters:
  9053. // color - String with fill color to apply
  9054. // url - URL or path to image to use
  9055. this.setBackground = function(color, url) {
  9056. var bg = getElem('canvasBackground');
  9057. var border = $(bg).find('rect')[0];
  9058. var bg_img = getElem('background_image');
  9059. border.setAttribute('fill',color);
  9060. if(url) {
  9061. if(!bg_img) {
  9062. bg_img = svgdoc.createElementNS(svgns, "image");
  9063. assignAttributes(bg_img, {
  9064. 'id': 'background_image',
  9065. 'width': '100%',
  9066. 'height': '100%',
  9067. 'preserveAspectRatio': 'xMinYMin',
  9068. 'style':'pointer-events:none'
  9069. });
  9070. }
  9071. bg_img.setAttributeNS(xlinkns, "xlink:href", url);
  9072. bg.appendChild(bg_img);
  9073. } else if(bg_img) {
  9074. bg_img.parentNode.removeChild(bg_img);
  9075. }
  9076. }
  9077. // Function: cycleElement
  9078. // Select the next/previous element within the current layer
  9079. //
  9080. // Parameters:
  9081. // next - Boolean where true = next and false = previous element
  9082. this.cycleElement = function(next) {
  9083. var cur_elem = selectedElements[0];
  9084. var elem = false;
  9085. var all_elems = getVisibleElements(current_layer);
  9086. if (cur_elem == null) {
  9087. var num = next?all_elems.length-1:0;
  9088. elem = all_elems[num];
  9089. } else {
  9090. var i = all_elems.length;
  9091. while(i--) {
  9092. if(all_elems[i] == cur_elem) {
  9093. var num = next?i-1:i+1;
  9094. if(num >= all_elems.length) {
  9095. num = 0;
  9096. } else if(num < 0) {
  9097. num = all_elems.length-1;
  9098. }
  9099. elem = all_elems[num];
  9100. break;
  9101. }
  9102. }
  9103. }
  9104. clearSelection();
  9105. addToSelection([elem], true);
  9106. call("selected", selectedElements);
  9107. }
  9108. this.clear();
  9109. // DEPRECATED: getPrivateMethods
  9110. // Since all methods are/should be public somehow, this function should be removed
  9111. // Being able to access private methods publicly seems wrong somehow,
  9112. // but currently appears to be the best way to allow testing and provide
  9113. // access to them to plugins.
  9114. this.getPrivateMethods = function() {
  9115. var obj = {
  9116. addCommandToHistory: addCommandToHistory,
  9117. setGradient: setGradient,
  9118. addSvgElementFromJson: addSvgElementFromJson,
  9119. assignAttributes: assignAttributes,
  9120. BatchCommand: BatchCommand,
  9121. call: call,
  9122. ChangeElementCommand: ChangeElementCommand,
  9123. cleanupElement: cleanupElement,
  9124. copyElem: copyElem,
  9125. ffClone: ffClone,
  9126. findDefs: findDefs,
  9127. findDuplicateGradient: findDuplicateGradient,
  9128. getElem: getElem,
  9129. getId: getId,
  9130. getIntersectionList: getIntersectionList,
  9131. getMouseTarget: getMouseTarget,
  9132. getNextId: getNextId,
  9133. getPathBBox: getPathBBox,
  9134. getUrlFromAttr: getUrlFromAttr,
  9135. hasMatrixTransform: hasMatrixTransform,
  9136. identifyLayers: identifyLayers,
  9137. InsertElementCommand: InsertElementCommand,
  9138. isIdentity: isIdentity,
  9139. logMatrix: logMatrix,
  9140. matrixMultiply: matrixMultiply,
  9141. MoveElementCommand: MoveElementCommand,
  9142. preventClickDefault: preventClickDefault,
  9143. recalculateAllSelectedDimensions: recalculateAllSelectedDimensions,
  9144. recalculateDimensions: recalculateDimensions,
  9145. remapElement: remapElement,
  9146. RemoveElementCommand: RemoveElementCommand,
  9147. removeUnusedDefElems: removeUnusedDefElems,
  9148. round: round,
  9149. runExtensions: runExtensions,
  9150. sanitizeSvg: sanitizeSvg,
  9151. SelectorManager: SelectorManager,
  9152. shortFloat: shortFloat,
  9153. svgCanvasToString: svgCanvasToString,
  9154. SVGEditTransformList: SVGEditTransformList,
  9155. svgToString: svgToString,
  9156. toString: toString,
  9157. transformBox: transformBox,
  9158. transformListToTransform: transformListToTransform,
  9159. transformPoint: transformPoint,
  9160. walkTree: walkTree
  9161. }
  9162. return obj;
  9163. };
  9164. // console.log('canvas.getPrivateMethods',canvas.getPrivateMethods);
  9165. // Test support for features/bugs
  9166. (function() {
  9167. // segList functions (for FF1.5 and 2.0)
  9168. var path = document.createElementNS(svgns,'path');
  9169. path.setAttribute('d','M0,0 10,10');
  9170. var seglist = path.pathSegList;
  9171. var seg = path.createSVGPathSegLinetoAbs(5,5);
  9172. try {
  9173. seglist.replaceItem(seg, 0);
  9174. support.pathReplaceItem = true;
  9175. } catch(err) {
  9176. support.pathReplaceItem = false;
  9177. }
  9178. try {
  9179. seglist.insertItemBefore(seg, 0);
  9180. support.pathInsertItemBefore = true;
  9181. } catch(err) {
  9182. support.pathInsertItemBefore = false;
  9183. }
  9184. // TODO: Find better way to check support for this
  9185. support.editableText = isOpera;
  9186. // Correct decimals on clone attributes (Opera < 10.5/win/non-en)
  9187. var rect = document.createElementNS(svgns,'rect');
  9188. rect.setAttribute('x',.1);
  9189. var crect = rect.cloneNode(false);
  9190. support.goodDecimals = (crect.getAttribute('x').indexOf(',') == -1);
  9191. if(!support.goodDecimals) {
  9192. $.alert("NOTE: This version of Opera is known to contain bugs in SVG-edit.\n\
  9193. Please upgrade to the <a href='http://opera.com'>latest version</a> in which the problems have been fixed.");
  9194. }
  9195. // Get correct em/ex values
  9196. var rect = document.createElementNS(svgns,'rect');
  9197. rect.setAttribute('width',"1em");
  9198. rect.setAttribute('height',"1ex");
  9199. svgcontent.appendChild(rect);
  9200. var bb = rect.getBBox();
  9201. unit_types.em = bb.width;
  9202. unit_types.ex = bb.height;
  9203. svgcontent.removeChild(rect);
  9204. }());
  9205. }