svgcanvas.js 326 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412
  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 userAgent = navigator.userAgent,
  81. // Note: Browser sniffing should only be used if no other detection method is possible
  82. isOpera = !!window.opera,
  83. isWebkit = userAgent.indexOf("AppleWebKit") >= 0,
  84. isGecko = userAgent.indexOf('Gecko/') >= 0,
  85. // Object populated later with booleans indicating support for features
  86. support = {},
  87. // this defines which elements and attributes that we support
  88. svgWhiteList = {
  89. // SVG Elements
  90. "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"],
  91. "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"],
  92. "clipPath": ["class", "clipPathUnits", "id"],
  93. "defs": [],
  94. "desc": [],
  95. "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"],
  96. "feGaussianBlur": ["class", "color-interpolation-filters", "id", "requiredFeatures", "stdDeviation"],
  97. "filter": ["class", "color-interpolation-filters", "filterRes", "filterUnits", "height", "id", "primitiveUnits", "requiredFeatures", "width", "x", "xlink:href", "y"],
  98. "foreignObject": ["class", "font-size", "height", "id", "opacity", "requiredFeatures", "style", "transform", "width", "x", "y"],
  99. "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"],
  100. "image": ["class", "clip-path", "clip-rule", "filter", "height", "id", "mask", "opacity", "requiredFeatures", "style", "systemLanguage", "transform", "width", "x", "xlink:href", "xlink:title", "y"],
  101. "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"],
  102. "linearGradient": ["class", "id", "gradientTransform", "gradientUnits", "requiredFeatures", "spreadMethod", "systemLanguage", "x1", "x2", "xlink:href", "y1", "y2"],
  103. "marker": ["id", "class", "markerHeight", "markerUnits", "markerWidth", "orient", "preserveAspectRatio", "refX", "refY", "systemLanguage", "viewBox"],
  104. "mask": ["class", "height", "id", "maskContentUnits", "maskUnits", "width", "x", "y"],
  105. "metadata": ["class", "id"],
  106. "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"],
  107. "pattern": ["class", "height", "id", "patternContentUnits", "patternTransform", "patternUnits", "requiredFeatures", "style", "systemLanguage", "width", "x", "xlink:href", "y"],
  108. "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"],
  109. "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"],
  110. "radialGradient": ["class", "cx", "cy", "fx", "fy", "gradientTransform", "gradientUnits", "id", "r", "requiredFeatures", "spreadMethod", "systemLanguage", "xlink:href"],
  111. "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"],
  112. "stop": ["class", "id", "offset", "requiredFeatures", "stop-color", "stop-opacity", "style", "systemLanguage"],
  113. "svg": ["class", "clip-path", "clip-rule", "filter", "id", "height", "mask", "preserveAspectRatio", "requiredFeatures", "style", "systemLanguage", "viewBox", "width", "x", "xmlns", "xmlns:se", "xmlns:xlink", "y"],
  114. "switch": ["class", "id", "requiredFeatures", "systemLanguage"],
  115. "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"],
  116. "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"],
  117. "textPath": ["class", "id", "method", "requiredFeatures", "spacing", "startOffset", "style", "systemLanguage", "transform", "xlink:href"],
  118. "title": [],
  119. "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"],
  120. "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"],
  121. // MathML Elements
  122. "annotation": ["encoding"],
  123. "annotation-xml": ["encoding"],
  124. "maction": ["actiontype", "other", "selection"],
  125. "math": ["class", "id", "display", "xmlns"],
  126. "menclose": ["notation"],
  127. "merror": [],
  128. "mfrac": ["linethickness"],
  129. "mi": ["mathvariant"],
  130. "mmultiscripts": [],
  131. "mn": [],
  132. "mo": ["fence", "lspace", "maxsize", "minsize", "rspace", "stretchy"],
  133. "mover": [],
  134. "mpadded": ["lspace", "width"],
  135. "mphantom": [],
  136. "mprescripts": [],
  137. "mroot": [],
  138. "mrow": ["xlink:href", "xlink:type", "xmlns:xlink"],
  139. "mspace": ["depth", "height", "width"],
  140. "msqrt": [],
  141. "mstyle": ["displaystyle", "mathbackground", "mathcolor", "mathvariant", "scriptlevel"],
  142. "msub": [],
  143. "msubsup": [],
  144. "msup": [],
  145. "mtable": ["align", "columnalign", "columnlines", "columnspacing", "displaystyle", "equalcolumns", "equalrows", "frame", "rowalign", "rowlines", "rowspacing", "width"],
  146. "mtd": ["columnalign", "columnspan", "rowalign", "rowspan"],
  147. "mtext": [],
  148. "mtr": ["columnalign", "rowalign"],
  149. "munder": [],
  150. "munderover": [],
  151. "none": [],
  152. "semantics": []
  153. },
  154. // Interface strings, usually for title elements
  155. uiStrings = {
  156. "pathNodeTooltip": "Drag node to move it. Double-click node to change segment type",
  157. "pathCtrlPtTooltip": "Drag control point to adjust curve properties",
  158. "exportNoBlur": "Blurred elements will appear as un-blurred",
  159. "exportNoImage": "Image elements will not appear",
  160. "exportNoforeignObject": "foreignObject elements will not appear",
  161. "exportNoDashArray": "Strokes will appear filled",
  162. "exportNoText": "Text may not appear as expected"
  163. },
  164. // Default configuration options
  165. curConfig = {
  166. show_outside_canvas: true,
  167. dimensions: [640, 480]
  168. };
  169. // Much faster than running getBBox() every time
  170. var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use';
  171. var visElems_arr = visElems.split(',');
  172. // var hidElems = 'clipPath,defs,desc,feGaussianBlur,filter,linearGradient,marker,mask,metadata,pattern,radialGradient,stop,switch,symbol,title,textPath';
  173. // Update config with new one if given
  174. if(config) {
  175. $.extend(curConfig, config);
  176. }
  177. // Static class for various utility functions
  178. var Utils = this.Utils = function() {
  179. var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  180. return {
  181. // Function: Utils.toXml
  182. // Converts characters in a string to XML-friendly entities.
  183. //
  184. // Example: "&" becomes "&amp;"
  185. //
  186. // Parameters:
  187. // str - The string to be converted
  188. //
  189. // Returns:
  190. // The converted string
  191. "toXml": function(str) {
  192. return $('<p/>').text(str).html();
  193. },
  194. // Function: Utils.fromXml
  195. // Converts XML entities in a string to single characters.
  196. // Example: "&amp;" becomes "&"
  197. //
  198. // Parameters:
  199. // str - The string to be converted
  200. //
  201. // Returns:
  202. // The converted string
  203. "fromXml": function(str) {
  204. return $('<p/>').html(str).text();
  205. },
  206. // This code was written by Tyler Akins and has been placed in the
  207. // public domain. It would be nice if you left this header intact.
  208. // Base64 code from Tyler Akins -- http://rumkin.com
  209. // schiller: Removed string concatenation in favour of Array.join() optimization,
  210. // also precalculate the size of the array needed.
  211. // Function: Utils.encode64
  212. // Converts a string to base64
  213. "encode64" : function(input) {
  214. // base64 strings are 4/3 larger than the original string
  215. // input = Utils.encodeUTF8(input); // convert non-ASCII characters
  216. input = Utils.convertToXMLReferences(input);
  217. if(window.btoa) return window.btoa(input); // Use native if available
  218. var output = new Array( Math.floor( (input.length + 2) / 3 ) * 4 );
  219. var chr1, chr2, chr3;
  220. var enc1, enc2, enc3, enc4;
  221. var i = 0, p = 0;
  222. do {
  223. chr1 = input.charCodeAt(i++);
  224. chr2 = input.charCodeAt(i++);
  225. chr3 = input.charCodeAt(i++);
  226. enc1 = chr1 >> 2;
  227. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  228. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  229. enc4 = chr3 & 63;
  230. if (isNaN(chr2)) {
  231. enc3 = enc4 = 64;
  232. } else if (isNaN(chr3)) {
  233. enc4 = 64;
  234. }
  235. output[p++] = _keyStr.charAt(enc1);
  236. output[p++] = _keyStr.charAt(enc2);
  237. output[p++] = _keyStr.charAt(enc3);
  238. output[p++] = _keyStr.charAt(enc4);
  239. } while (i < input.length);
  240. return output.join('');
  241. },
  242. // Function: Utils.decode64
  243. // Converts a string from base64
  244. "decode64" : function(input) {
  245. if(window.atob) return window.atob(input);
  246. var output = "";
  247. var chr1, chr2, chr3 = "";
  248. var enc1, enc2, enc3, enc4 = "";
  249. var i = 0;
  250. // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  251. input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  252. do {
  253. enc1 = _keyStr.indexOf(input.charAt(i++));
  254. enc2 = _keyStr.indexOf(input.charAt(i++));
  255. enc3 = _keyStr.indexOf(input.charAt(i++));
  256. enc4 = _keyStr.indexOf(input.charAt(i++));
  257. chr1 = (enc1 << 2) | (enc2 >> 4);
  258. chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
  259. chr3 = ((enc3 & 3) << 6) | enc4;
  260. output = output + String.fromCharCode(chr1);
  261. if (enc3 != 64) {
  262. output = output + String.fromCharCode(chr2);
  263. }
  264. if (enc4 != 64) {
  265. output = output + String.fromCharCode(chr3);
  266. }
  267. chr1 = chr2 = chr3 = "";
  268. enc1 = enc2 = enc3 = enc4 = "";
  269. } while (i < input.length);
  270. return unescape(output);
  271. },
  272. // Currently not being used, so commented out for now
  273. // based on http://phpjs.org/functions/utf8_encode:577
  274. // codedread:does not seem to work with webkit-based browsers on OSX
  275. // "encodeUTF8": function(input) {
  276. // //return unescape(encodeURIComponent(input)); //may or may not work
  277. // var output = '';
  278. // for (var n = 0; n < input.length; n++){
  279. // var c = input.charCodeAt(n);
  280. // if (c < 128) {
  281. // output += input[n];
  282. // }
  283. // else if (c > 127) {
  284. // if (c < 2048){
  285. // output += String.fromCharCode((c >> 6) | 192);
  286. // }
  287. // else {
  288. // output += String.fromCharCode((c >> 12) | 224) + String.fromCharCode((c >> 6) & 63 | 128);
  289. // }
  290. // output += String.fromCharCode((c & 63) | 128);
  291. // }
  292. // }
  293. // return output;
  294. // },
  295. // Function: Utils.convertToXMLReferences
  296. // Converts a string to use XML references
  297. "convertToXMLReferences": function(input) {
  298. var output = '';
  299. for (var n = 0; n < input.length; n++){
  300. var c = input.charCodeAt(n);
  301. if (c < 128) {
  302. output += input[n];
  303. }
  304. else if(c > 127) {
  305. output += ("&#" + c + ";");
  306. }
  307. }
  308. return output;
  309. },
  310. // Function: rectsIntersect
  311. // Check if two rectangles (BBoxes objects) intersect each other
  312. //
  313. // Paramaters:
  314. // r1 - The first BBox-like object
  315. // r2 - The second BBox-like object
  316. //
  317. // Returns:
  318. // Boolean that's true if rectangles intersect
  319. "rectsIntersect": function(r1, r2) {
  320. return r2.x < (r1.x+r1.width) &&
  321. (r2.x+r2.width) > r1.x &&
  322. r2.y < (r1.y+r1.height) &&
  323. (r2.y+r2.height) > r1.y;
  324. },
  325. // Function: snapToAngle
  326. // Returns a 45 degree angle coordinate associated with the two given
  327. // coordinates
  328. //
  329. // Parameters:
  330. // x1 - First coordinate's x value
  331. // x2 - Second coordinate's x value
  332. // y1 - First coordinate's y value
  333. // y2 - Second coordinate's y value
  334. //
  335. // Returns:
  336. // Object with the following values:
  337. // x - The angle-snapped x value
  338. // y - The angle-snapped y value
  339. // snapangle - The angle at which to snap
  340. "snapToAngle": function(x1,y1,x2,y2) {
  341. var snap = Math.PI/4; // 45 degrees
  342. var dx = x2 - x1;
  343. var dy = y2 - y1;
  344. var angle = Math.atan2(dy,dx);
  345. var dist = Math.sqrt(dx * dx + dy * dy);
  346. var snapangle= Math.round(angle/snap)*snap;
  347. var x = x1 + dist*Math.cos(snapangle);
  348. var y = y1 + dist*Math.sin(snapangle);
  349. //console.log(x1,y1,x2,y2,x,y,angle)
  350. return {x:x, y:y, a:snapangle};
  351. },
  352. // Function: snapToGrid
  353. // round value to for snapping
  354. "snapToGrid" : function(value){
  355. var stepSize = curConfig.snappingStep;
  356. value = Math.round(value/stepSize)*stepSize;
  357. return value;
  358. },
  359. // Function: text2xml
  360. // Cross-browser compatible method of converting a string to an XML tree
  361. // found this function here: http://groups.google.com/group/jquery-dev/browse_thread/thread/c6d11387c580a77f
  362. "text2xml": function(sXML) {
  363. if(sXML.indexOf('<svg:svg') >= 0) {
  364. sXML = sXML.replace(/<(\/?)svg:/g, '<$1').replace('xmlns:svg', 'xmlns');
  365. }
  366. var out;
  367. try{
  368. var dXML = (window.DOMParser)?new DOMParser():new ActiveXObject("Microsoft.XMLDOM");
  369. dXML.async = false;
  370. } catch(e){
  371. throw new Error("XML Parser could not be instantiated");
  372. };
  373. try{
  374. if(dXML.loadXML) out = (dXML.loadXML(sXML))?dXML:false;
  375. else out = dXML.parseFromString(sXML, "text/xml");
  376. }
  377. catch(e){ throw new Error("Error parsing XML string"); };
  378. return out;
  379. }
  380. }
  381. }();
  382. var snapToGrid = Utils.snapToGrid;
  383. var elData = $.data;
  384. // TODO: declare the variables and set them as null, then move this setup stuff to
  385. // an initialization function - probably just use clear()
  386. var canvas = this,
  387. // Namespace constants
  388. svgns = "http://www.w3.org/2000/svg",
  389. xlinkns = "http://www.w3.org/1999/xlink",
  390. xmlns = "http://www.w3.org/XML/1998/namespace",
  391. xmlnsns = "http://www.w3.org/2000/xmlns/", // see http://www.w3.org/TR/REC-xml-names/#xmlReserved
  392. se_ns = "http://svg-edit.googlecode.com",
  393. htmlns = "http://www.w3.org/1999/xhtml",
  394. mathns = "http://www.w3.org/1998/Math/MathML",
  395. // Map of units, updated later based on px conversion.
  396. unit_types = {px: 1},
  397. //nonce to uniquify id's
  398. nonce = Math.floor(Math.random()*100001),
  399. // Boolean to indicate whether or not IDs given to elements should be random
  400. randomize_ids = false,
  401. // "document" element associated with the container (same as window.document using default svg-editor.js)
  402. svgdoc = container.ownerDocument,
  403. // Array with width/height of canvas
  404. dimensions = curConfig.dimensions;
  405. // Create Root SVG element. This is a container for the document being edited, not the document itself.
  406. var svgroot = svgdoc.importNode(Utils.text2xml('<svg id="svgroot" xmlns="' + svgns + '" xlinkns="' + xlinkns + '" ' +
  407. 'width="' + dimensions[0] + '" height="' + dimensions[1] + '" x="' + dimensions[0] + '" y="' + dimensions[1] + '" overflow="visible">' +
  408. '<defs>' +
  409. '<filter id="canvashadow" filterUnits="objectBoundingBox">' +
  410. '<feGaussianBlur in="SourceAlpha" stdDeviation="4" result="blur"/>'+
  411. '<feOffset in="blur" dx="5" dy="5" result="offsetBlur"/>'+
  412. '<feMerge>'+
  413. '<feMergeNode in="offsetBlur"/>'+
  414. '<feMergeNode in="SourceGraphic"/>'+
  415. '</feMerge>'+
  416. '</filter>'+
  417. '</defs>'+
  418. '</svg>').documentElement, true);
  419. container.appendChild(svgroot);
  420. // The actual element that represents the final output SVG element
  421. var svgcontent = svgdoc.createElementNS(svgns, "svg");
  422. $(svgcontent).attr({
  423. id: 'svgcontent',
  424. width: dimensions[0],
  425. height: dimensions[1],
  426. x: dimensions[0],
  427. y: dimensions[1],
  428. overflow: curConfig.show_outside_canvas?'visible':'hidden',
  429. xmlns: svgns,
  430. "xmlns:se": se_ns,
  431. "xmlns:xlink": xlinkns
  432. }).appendTo(svgroot);
  433. // Set nonce if randomize_ids = true
  434. if (randomize_ids) svgcontent.setAttributeNS(se_ns, 'se:nonce', nonce);
  435. // map namespace URIs to prefixes
  436. var nsMap = {};
  437. nsMap[xlinkns] = 'xlink';
  438. nsMap[xmlns] = 'xml';
  439. nsMap[xmlnsns] = 'xmlns';
  440. nsMap[se_ns] = 'se';
  441. nsMap[htmlns] = 'xhtml';
  442. nsMap[mathns] = 'mathml';
  443. // map prefixes to namespace URIs
  444. var nsRevMap = {};
  445. $.each(nsMap, function(key,value){
  446. nsRevMap[value] = key;
  447. });
  448. // Produce a Namespace-aware version of svgWhitelist
  449. var svgWhiteListNS = {};
  450. $.each(svgWhiteList, function(elt,atts){
  451. var attNS = {};
  452. $.each(atts, function(i, att){
  453. if (att.indexOf(':') >= 0) {
  454. var v = att.split(':');
  455. attNS[v[1]] = nsRevMap[v[0]];
  456. } else {
  457. attNS[att] = att == 'xmlns' ? xmlnsns : null;
  458. }
  459. });
  460. svgWhiteListNS[elt] = attNS;
  461. });
  462. // Animation element to change the opacity of any newly created element
  463. var opac_ani = document.createElementNS(svgns, 'animate');
  464. $(opac_ani).attr({
  465. attributeName: 'opacity',
  466. begin: 'indefinite',
  467. dur: 1,
  468. fill: 'freeze'
  469. }).appendTo(svgroot);
  470. // Group: Unit conversion functions
  471. // Set the scope for these functions
  472. var convertToNum, convertToUnit, setUnitAttr, unitConvertAttrs;
  473. (function() {
  474. var w_attrs = ['x', 'x1', 'cx', 'rx', 'width'];
  475. var h_attrs = ['y', 'y1', 'cy', 'ry', 'height'];
  476. var unit_attrs = $.merge(['r','radius'], w_attrs);
  477. $.merge(unit_attrs, h_attrs);
  478. // Function: convertToNum
  479. // Converts given values to numbers. Attributes must be supplied in
  480. // case a percentage is given
  481. //
  482. // Parameters:
  483. // attr - String with the name of the attribute associated with the value
  484. // val - String with the attribute value to convert
  485. convertToNum = function(attr, val) {
  486. // Return a number if that's what it already is
  487. if(!isNaN(val)) return val-0;
  488. if(val.substr(-1) === '%') {
  489. // Deal with percentage, depends on attribute
  490. var num = val.substr(0, val.length-1)/100;
  491. var res = getResolution();
  492. if(w_attrs.indexOf(attr) >= 0) {
  493. return num * res.w;
  494. } else if(h_attrs.indexOf(attr) >= 0) {
  495. return num * res.h;
  496. } else {
  497. return num * Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);
  498. }
  499. } else {
  500. var unit = val.substr(-2);
  501. var num = val.substr(0, val.length-2);
  502. // Note that this multiplication turns the string into a number
  503. return num * unit_types[unit];
  504. }
  505. };
  506. // Function: setUnitAttr
  507. // Sets an element's attribute based on the unit in its current value.
  508. //
  509. // Parameters:
  510. // elem - DOM element to be changed
  511. // attr - String with the name of the attribute associated with the value
  512. // val - String with the attribute value to convert
  513. setUnitAttr = function(elem, attr, val) {
  514. if(!isNaN(val)) {
  515. // New value is a number, so check currently used unit
  516. var old_val = elem.getAttribute(attr);
  517. if(old_val !== null && (isNaN(old_val) || curConfig.baseUnit !== 'px')) {
  518. // Old value was a number, so get unit, then convert
  519. var unit;
  520. if(old_val.substr(-1) === '%') {
  521. var res = getResolution();
  522. unit = '%';
  523. val *= 100;
  524. if(w_attrs.indexOf(attr) >= 0) {
  525. val = val / res.w;
  526. } else if(h_attrs.indexOf(attr) >= 0) {
  527. val = val / res.h;
  528. } else {
  529. return val / Math.sqrt((res.w*res.w) + (res.h*res.h))/Math.sqrt(2);
  530. }
  531. } else {
  532. if(curConfig.baseUnit !== 'px') {
  533. unit = curConfig.baseUnit;
  534. } else {
  535. unit = old_val.substr(-2);
  536. }
  537. val = val / unit_types[unit];
  538. }
  539. val += unit;
  540. }
  541. }
  542. elem.setAttribute(attr, val);
  543. }
  544. // Function: isValidUnit
  545. // Check if an attribute's value is in a valid format
  546. //
  547. // Parameters:
  548. // attr - String with the name of the attribute associated with the value
  549. // val - String with the attribute value to check
  550. canvas.isValidUnit = function(attr, val) {
  551. var valid = false;
  552. if(unit_attrs.indexOf(attr) >= 0) {
  553. // True if it's just a number
  554. if(!isNaN(val)) {
  555. valid = true;
  556. } else {
  557. // Not a number, check if it has a valid unit
  558. val = val.toLowerCase();
  559. $.each(unit_types, function(unit) {
  560. if(valid) return;
  561. var re = new RegExp('^-?[\\d\\.]+' + unit + '$');
  562. if(re.test(val)) valid = true;
  563. });
  564. }
  565. } else if (attr == "id") {
  566. // if we're trying to change the id, make sure it's not already present in the doc
  567. // and the id value is valid.
  568. var result = false;
  569. // because getElem() can throw an exception in the case of an invalid id
  570. // (according to http://www.w3.org/TR/xml-id/ IDs must be a NCName)
  571. // we wrap it in an exception and only return true if the ID was valid and
  572. // not already present
  573. try {
  574. var elem = getElem(val);
  575. result = (elem == null);
  576. } catch(e) {}
  577. return result;
  578. } else valid = true;
  579. return valid;
  580. }
  581. // Function: getUnits
  582. // Returns the unit object with values for each unit
  583. canvas.getUnits = function() {
  584. return unit_types;
  585. }
  586. // Function: unitConvertAttrs
  587. // Converts all applicable attributes to the given baseUnit
  588. unitConvertAttrs = canvas.unitConvertAttrs = function(element) {
  589. var elName = element.tagName;
  590. var unit = curConfig.baseUnit;
  591. var attrs;
  592. switch (elName)
  593. {
  594. case "line":
  595. attrs = ['x1', 'x2', 'y1', 'y2'];
  596. break;
  597. case "circle":
  598. attrs = ['cx', 'cy', 'r'];
  599. break;
  600. case "ellipse":
  601. attrs = ['cx', 'cy', 'rx', 'ry'];
  602. break;
  603. case "foreignObject":
  604. case "rect":
  605. case "image":
  606. case "use":
  607. attrs = ['x', 'y', 'width', 'height'];
  608. break;
  609. case "text":
  610. attrs = ['x', 'y'];
  611. break;
  612. }
  613. if(!attrs) return;
  614. var len = attrs.length
  615. for(var i = 0; i < len; i++) {
  616. var attr = attrs[i];
  617. var cur = element.getAttribute(attr);
  618. if(cur) {
  619. if(!isNaN(cur)) {
  620. element.setAttribute(attr, (cur / unit_types[unit]) + unit);
  621. } else {
  622. // Convert existing?
  623. }
  624. }
  625. }
  626. }
  627. })();
  628. // Group: Undo/Redo history management
  629. this.undoCmd = {};
  630. // Function: ChangeElementCommand
  631. // History command to make a change to an element.
  632. // Usually an attribute change, but can also be textcontent.
  633. //
  634. // Parameters:
  635. // elem - The DOM element that was changed
  636. // attrs - An object with the attributes to be changed and the values they had *before* the change
  637. // text - An optional string visible to user related to this change
  638. var ChangeElementCommand = this.undoCmd.changeElement = function(elem, attrs, text) {
  639. this.elem = elem;
  640. this.text = text ? ("Change " + elem.tagName + " " + text) : ("Change " + elem.tagName);
  641. this.newValues = {};
  642. this.oldValues = attrs;
  643. for (var attr in attrs) {
  644. if (attr == "#text") this.newValues[attr] = elem.textContent;
  645. else if (attr == "#href") this.newValues[attr] = getHref(elem);
  646. else this.newValues[attr] = elem.getAttribute(attr);
  647. }
  648. // Function: ChangeElementCommand.apply
  649. // Performs the stored change action
  650. this.apply = function() {
  651. var bChangedTransform = false;
  652. for(var attr in this.newValues ) {
  653. if (this.newValues[attr]) {
  654. if (attr == "#text") this.elem.textContent = this.newValues[attr];
  655. else if (attr == "#href") setHref(this.elem, this.newValues[attr])
  656. else this.elem.setAttribute(attr, this.newValues[attr]);
  657. }
  658. else {
  659. if (attr == "#text") this.elem.textContent = "";
  660. else {
  661. this.elem.setAttribute(attr, "");
  662. this.elem.removeAttribute(attr);
  663. }
  664. }
  665. if (attr == "transform") { bChangedTransform = true; }
  666. else if (attr == "stdDeviation") { canvas.setBlurOffsets(this.elem.parentNode, this.newValues[attr]); }
  667. }
  668. // relocate rotational transform, if necessary
  669. if(!bChangedTransform) {
  670. var angle = getRotationAngle(elem);
  671. if (angle) {
  672. var bbox = elem.getBBox();
  673. var cx = bbox.x + bbox.width/2,
  674. cy = bbox.y + bbox.height/2;
  675. var rotate = ["rotate(", angle, " ", cx, ",", cy, ")"].join('');
  676. if (rotate != elem.getAttribute("transform")) {
  677. elem.setAttribute("transform", rotate);
  678. }
  679. }
  680. }
  681. // if we are changing layer names, re-identify all layers
  682. if (this.elem.tagName == "title" && this.elem.parentNode.parentNode == svgcontent) {
  683. identifyLayers();
  684. }
  685. return true;
  686. };
  687. // Function: ChangeElementCommand.unapply
  688. // Reverses the stored change action
  689. this.unapply = function() {
  690. var bChangedTransform = false;
  691. for(var attr in this.oldValues ) {
  692. if (this.oldValues[attr]) {
  693. if (attr == "#text") this.elem.textContent = this.oldValues[attr];
  694. else if (attr == "#href") setHref(this.elem, this.oldValues[attr]);
  695. else this.elem.setAttribute(attr, this.oldValues[attr]);
  696. if (attr == "stdDeviation") canvas.setBlurOffsets(this.elem.parentNode, this.oldValues[attr]);
  697. }
  698. else {
  699. if (attr == "#text") this.elem.textContent = "";
  700. else this.elem.removeAttribute(attr);
  701. }
  702. if (attr == "transform") { bChangedTransform = true; }
  703. }
  704. // relocate rotational transform, if necessary
  705. if(!bChangedTransform) {
  706. var angle = getRotationAngle(elem);
  707. if (angle) {
  708. var bbox = elem.getBBox();
  709. var cx = bbox.x + bbox.width/2,
  710. cy = bbox.y + bbox.height/2;
  711. var rotate = ["rotate(", angle, " ", cx, ",", cy, ")"].join('');
  712. if (rotate != elem.getAttribute("transform")) {
  713. elem.setAttribute("transform", rotate);
  714. }
  715. }
  716. }
  717. // if we are changing layer names, re-identify all layers
  718. if (this.elem.tagName == "title" && this.elem.parentNode.parentNode == svgcontent) {
  719. identifyLayers();
  720. }
  721. // Remove transformlist to prevent confusion that causes bugs like 575.
  722. if (svgTransformLists[this.elem.id]) {
  723. delete svgTransformLists[this.elem.id];
  724. }
  725. return true;
  726. };
  727. // Function: ChangeElementCommand.elements
  728. // Returns array with element associated with this command
  729. this.elements = function() { return [this.elem]; }
  730. }
  731. // Function: InsertElementCommand
  732. // History command for an element that was added to the DOM
  733. //
  734. // Parameters:
  735. // elem - The newly added DOM element
  736. // text - An optional string visible to user related to this change
  737. var InsertElementCommand = this.undoCmd.insertElement = function(elem, text) {
  738. this.elem = elem;
  739. this.text = text || ("Create " + elem.tagName);
  740. this.parent = elem.parentNode;
  741. // Function: InsertElementCommand.apply
  742. // Re-Inserts the new element
  743. this.apply = function() {
  744. this.elem = this.parent.insertBefore(this.elem, this.elem.nextSibling);
  745. if (this.parent == svgcontent) {
  746. identifyLayers();
  747. }
  748. };
  749. // Function: InsertElementCommand.unapply
  750. // Removes the element
  751. this.unapply = function() {
  752. this.parent = this.elem.parentNode;
  753. this.elem = this.elem.parentNode.removeChild(this.elem);
  754. if (this.parent == svgcontent) {
  755. identifyLayers();
  756. }
  757. };
  758. // Function: InsertElementCommand.elements
  759. // Returns array with element associated with this command
  760. this.elements = function() { return [this.elem]; };
  761. }
  762. // Function: RemoveElementCommand
  763. // History command for an element removed from the DOM
  764. //
  765. // Parameters:
  766. // elem - The removed DOM element
  767. // parent - The DOM element's parent
  768. // text - An optional string visible to user related to this change
  769. var RemoveElementCommand = this.undoCmd.removeElement = function(elem, parent, text) {
  770. this.elem = elem;
  771. this.text = text || ("Delete " + elem.tagName);
  772. this.parent = parent;
  773. // Function: RemoveElementCommand.apply
  774. // Re-removes the new element
  775. this.apply = function() {
  776. if (svgTransformLists[this.elem.id]) {
  777. delete svgTransformLists[this.elem.id];
  778. }
  779. this.parent = this.elem.parentNode;
  780. this.elem = this.parent.removeChild(this.elem);
  781. if (this.parent == svgcontent) {
  782. identifyLayers();
  783. }
  784. };
  785. // Function: RemoveElementCommand.unapply
  786. // Re-adds the new element
  787. this.unapply = function() {
  788. if (svgTransformLists[this.elem.id]) {
  789. delete svgTransformLists[this.elem.id];
  790. }
  791. this.elem = this.parent.insertBefore(this.elem, this.elem.nextSibling);
  792. if (this.parent == svgcontent) {
  793. identifyLayers();
  794. }
  795. };
  796. // Function: RemoveElementCommand.elements
  797. // Returns array with element associated with this command
  798. this.elements = function() { return [this.elem]; };
  799. // special hack for webkit: remove this element's entry in the svgTransformLists map
  800. if (svgTransformLists[elem.id]) {
  801. delete svgTransformLists[elem.id];
  802. }
  803. }
  804. // Function: MoveElementCommand
  805. // History command for an element that had its DOM position changed
  806. //
  807. // Parameters:
  808. // elem - The DOM element that was moved
  809. // oldNextSibling - The element's next sibling before it was moved
  810. // oldParent - The element's parent before it was moved
  811. // text - An optional string visible to user related to this change
  812. var MoveElementCommand = this.undoCmd.moveElement = function(elem, oldNextSibling, oldParent, text) {
  813. this.elem = elem;
  814. this.text = text ? ("Move " + elem.tagName + " to " + text) : ("Move " + elem.tagName);
  815. this.oldNextSibling = oldNextSibling;
  816. this.oldParent = oldParent;
  817. this.newNextSibling = elem.nextSibling;
  818. this.newParent = elem.parentNode;
  819. // Function: MoveElementCommand.unapply
  820. // Re-positions the element
  821. this.apply = function() {
  822. this.elem = this.newParent.insertBefore(this.elem, this.newNextSibling);
  823. if (this.newParent == svgcontent) {
  824. identifyLayers();
  825. }
  826. };
  827. // Function: MoveElementCommand.unapply
  828. // Positions the element back to its original location
  829. this.unapply = function() {
  830. this.elem = this.oldParent.insertBefore(this.elem, this.oldNextSibling);
  831. if (this.oldParent == svgcontent) {
  832. identifyLayers();
  833. }
  834. };
  835. // Function: MoveElementCommand.elements
  836. // Returns array with element associated with this command
  837. this.elements = function() { return [this.elem]; };
  838. }
  839. // TODO: create a 'typing' command object that tracks changes in text
  840. // if a new Typing command is created and the top command on the stack is also a Typing
  841. // and they both affect the same element, then collapse the two commands into one
  842. // Function: BatchCommand
  843. // History command that can contain/execute multiple other commands
  844. //
  845. // Parameters:
  846. // text - An optional string visible to user related to this change
  847. var BatchCommand = this.undoCmd.batch = function(text) {
  848. this.text = text || "Batch Command";
  849. this.stack = [];
  850. // Function: BatchCommand.apply
  851. // Runs "apply" on all subcommands
  852. this.apply = function() {
  853. var len = this.stack.length;
  854. for (var i = 0; i < len; ++i) {
  855. this.stack[i].apply();
  856. }
  857. };
  858. // Function: BatchCommand.unapply
  859. // Runs "unapply" on all subcommands
  860. this.unapply = function() {
  861. for (var i = this.stack.length-1; i >= 0; i--) {
  862. this.stack[i].unapply();
  863. }
  864. };
  865. // Function: BatchCommand.elements
  866. // Iterate through all our subcommands and returns all the elements we are changing
  867. this.elements = function() {
  868. var elems = [];
  869. var cmd = this.stack.length;
  870. while (cmd--) {
  871. var thisElems = this.stack[cmd].elements();
  872. var elem = thisElems.length;
  873. while (elem--) {
  874. if (elems.indexOf(thisElems[elem]) == -1) elems.push(thisElems[elem]);
  875. }
  876. }
  877. return elems;
  878. };
  879. // Function: BatchCommand.addSubCommand
  880. // Adds a given command to the history stack
  881. //
  882. // Parameters:
  883. // cmd - The undo command object to add
  884. this.addSubCommand = function(cmd) { this.stack.push(cmd); };
  885. // Function: BatchCommand.isEmpty
  886. // Returns a boolean indicating whether or not the batch command is empty
  887. this.isEmpty = function() { return this.stack.length == 0; };
  888. }
  889. // Set scope for addCommandToHistory
  890. var addCommandToHistory;
  891. // Undo/redo stack related functions
  892. (function(c) {
  893. var undoStackPointer = 0,
  894. undoStack = [];
  895. c.undoMgr = {
  896. // Function: undoMgr.resetUndoStack
  897. // Resets the undo stack, effectively clearing the undo/redo history
  898. resetUndoStack: function() {
  899. undoStack = [];
  900. undoStackPointer = 0;
  901. },
  902. // Function: undoMgr.getUndoStackSize
  903. // Returns:
  904. // Integer with the current size of the undo history stack
  905. getUndoStackSize: function() { return undoStackPointer; },
  906. // Function: undoMgr.getRedoStackSize
  907. // Returns:
  908. // Integer with the current size of the redo history stack
  909. getRedoStackSize: function() { return undoStack.length - undoStackPointer; },
  910. // Function: undoMgr.getNextUndoCommandText
  911. // Returns:
  912. // String associated with the next undo command
  913. getNextUndoCommandText: function() {
  914. if (undoStackPointer > 0)
  915. return undoStack[undoStackPointer-1].text;
  916. return "";
  917. },
  918. // Function: undoMgr.getNextRedoCommandText
  919. // Returns:
  920. // String associated with the next redo command
  921. getNextRedoCommandText: function() {
  922. if (undoStackPointer < undoStack.length)
  923. return undoStack[undoStackPointer].text;
  924. return "";
  925. },
  926. // Function: undoMgr.undo
  927. // Performs an undo step
  928. undo: function() {
  929. if (undoStackPointer > 0) {
  930. c.clearSelection();
  931. var cmd = undoStack[--undoStackPointer];
  932. cmd.unapply();
  933. pathActions.clear();
  934. call("changed", cmd.elements());
  935. }
  936. },
  937. // Function: undoMgr.redo
  938. // Performs a redo step
  939. redo: function() {
  940. if (undoStackPointer < undoStack.length && undoStack.length > 0) {
  941. c.clearSelection();
  942. var cmd = undoStack[undoStackPointer++];
  943. cmd.apply();
  944. pathActions.clear();
  945. call("changed", cmd.elements());
  946. }
  947. }
  948. };
  949. // Function: addCommandToHistory
  950. // Adds a command object to the undo history stack
  951. //
  952. // Parameters:
  953. // cmd - The command object to add
  954. addCommandToHistory = c.undoCmd.add = function(cmd) {
  955. // FIXME: we MUST compress consecutive text changes to the same element
  956. // (right now each keystroke is saved as a separate command that includes the
  957. // entire text contents of the text element)
  958. // TODO: consider limiting the history that we store here (need to do some slicing)
  959. // if our stack pointer is not at the end, then we have to remove
  960. // all commands after the pointer and insert the new command
  961. if (undoStackPointer < undoStack.length && undoStack.length > 0) {
  962. undoStack = undoStack.splice(0, undoStackPointer);
  963. }
  964. undoStack.push(cmd);
  965. undoStackPointer = undoStack.length;
  966. };
  967. }(canvas));
  968. (function(c) {
  969. // New functions for refactoring of Undo/Redo
  970. // this is the stack that stores the original values, the elements and
  971. // the attribute name for begin/finish
  972. var undoChangeStackPointer = -1;
  973. var undoableChangeStack = [];
  974. // Function: beginUndoableChange
  975. // This function tells the canvas to remember the old values of the
  976. // attrName attribute for each element sent in. The elements and values
  977. // are stored on a stack, so the next call to finishUndoableChange() will
  978. // pop the elements and old values off the stack, gets the current values
  979. // from the DOM and uses all of these to construct the undo-able command.
  980. //
  981. // Parameters:
  982. // attrName - The name of the attribute being changed
  983. // elems - Array of DOM elements being changed
  984. c.beginUndoableChange = function(attrName, elems) {
  985. var p = ++undoChangeStackPointer;
  986. var i = elems.length;
  987. var oldValues = new Array(i), elements = new Array(i);
  988. while (i--) {
  989. var elem = elems[i];
  990. if (elem == null) continue;
  991. elements[i] = elem;
  992. oldValues[i] = elem.getAttribute(attrName);
  993. }
  994. undoableChangeStack[p] = {'attrName': attrName,
  995. 'oldValues': oldValues,
  996. 'elements': elements};
  997. };
  998. // Function: finishUndoableChange
  999. // This function returns a BatchCommand object which summarizes the
  1000. // change since beginUndoableChange was called. The command can then
  1001. // be added to the command history
  1002. //
  1003. // Returns:
  1004. // Batch command object with resulting changes
  1005. c.finishUndoableChange = function() {
  1006. var p = undoChangeStackPointer--;
  1007. var changeset = undoableChangeStack[p];
  1008. var i = changeset['elements'].length;
  1009. var attrName = changeset['attrName'];
  1010. var batchCmd = new BatchCommand("Change " + attrName);
  1011. while (i--) {
  1012. var elem = changeset['elements'][i];
  1013. if (elem == null) continue;
  1014. var changes = {};
  1015. changes[attrName] = changeset['oldValues'][i];
  1016. if (changes[attrName] != elem.getAttribute(attrName)) {
  1017. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes, attrName));
  1018. }
  1019. }
  1020. undoableChangeStack[p] = null;
  1021. return batchCmd;
  1022. };
  1023. }(canvas));
  1024. // Put SelectorManager in this scope
  1025. var SelectorManager;
  1026. (function() {
  1027. // Interface: Selector
  1028. // Private class for DOM element selection boxes
  1029. //
  1030. // Parameters:
  1031. // id - integer to internally indentify the selector
  1032. // elem - DOM element associated with this selector
  1033. function Selector(id, elem) {
  1034. // this is the selector's unique number
  1035. this.id = id;
  1036. // this holds a reference to the element for which this selector is being used
  1037. this.selectedElement = elem;
  1038. // this is a flag used internally to track whether the selector is being used or not
  1039. this.locked = true;
  1040. // Function: Selector.reset
  1041. // Used to reset the id and element that the selector is attached to
  1042. //
  1043. // Parameters:
  1044. // e - DOM element associated with this selector
  1045. this.reset = function(e) {
  1046. this.locked = true;
  1047. this.selectedElement = e;
  1048. this.resize();
  1049. this.selectorGroup.setAttribute("display", "inline");
  1050. };
  1051. // this holds a reference to the <g> element that holds all visual elements of the selector
  1052. this.selectorGroup = addSvgElementFromJson({ "element": "g",
  1053. "attr": {"id": ("selectorGroup"+this.id)}
  1054. });
  1055. // this holds a reference to the path rect
  1056. this.selectorRect = this.selectorGroup.appendChild( addSvgElementFromJson({
  1057. "element": "path",
  1058. "attr": {
  1059. "id": ("selectedBox"+this.id),
  1060. "fill": "none",
  1061. "stroke": "#22C",
  1062. "stroke-width": "1",
  1063. "stroke-dasharray": "5,5",
  1064. // need to specify this so that the rect is not selectable
  1065. "style": "pointer-events:none"
  1066. }
  1067. }) );
  1068. // this holds a reference to the grip coordinates for this selector
  1069. this.gripCoords = { "nw":null,
  1070. "n":null,
  1071. "ne":null,
  1072. "e":null,
  1073. "se":null,
  1074. "s":null,
  1075. "sw":null,
  1076. "w":null
  1077. };
  1078. // Function: Selector.showGrips
  1079. // Show the resize grips of this selector
  1080. //
  1081. // Parameters:
  1082. // show - boolean indicating whether grips should be shown or not
  1083. this.showGrips = function(show) {
  1084. // TODO: use suspendRedraw() here
  1085. var bShow = show ? "inline" : "none";
  1086. selectorManager.selectorGripsGroup.setAttribute("display", bShow);
  1087. var elem = this.selectedElement;
  1088. if(elem && show) {
  1089. this.selectorGroup.appendChild(selectorManager.selectorGripsGroup);
  1090. this.updateGripCursors(getRotationAngle(elem));
  1091. }
  1092. };
  1093. // Function: Selector.updateGripCursors
  1094. // Updates cursors for corner grips on rotation so arrows point the right way
  1095. //
  1096. // Parameters:
  1097. // angle - Float indicating current rotation angle in degrees
  1098. this.updateGripCursors = function(angle) {
  1099. var dir_arr = [];
  1100. var steps = Math.round(angle / 45);
  1101. if(steps < 0) steps += 8;
  1102. for (var dir in selectorManager.selectorGrips) {
  1103. dir_arr.push(dir);
  1104. }
  1105. while(steps > 0) {
  1106. dir_arr.push(dir_arr.shift());
  1107. steps--;
  1108. }
  1109. var i = 0;
  1110. for (var dir in selectorManager.selectorGrips) {
  1111. selectorManager.selectorGrips[dir].setAttribute('style', ("cursor:" + dir_arr[i] + "-resize"));
  1112. i++;
  1113. };
  1114. };
  1115. // Function: Selector.resize
  1116. // Updates the selector to match the element's size
  1117. this.resize = function() {
  1118. var selectedBox = this.selectorRect,
  1119. mgr = selectorManager,
  1120. selectedGrips = mgr.selectorGrips,
  1121. selected = this.selectedElement,
  1122. sw = selected.getAttribute("stroke-width");
  1123. var offset = 1/current_zoom;
  1124. if (selected.getAttribute("stroke") != "none" && !isNaN(sw)) {
  1125. offset += (sw/2);
  1126. }
  1127. if (selected.tagName == "text") {
  1128. offset += 2/current_zoom;
  1129. }
  1130. var bbox = getBBox(selected);
  1131. if(selected.tagName == 'g' && !$(selected).data('gsvg')) {
  1132. // The bbox for a group does not include stroke vals, so we
  1133. // get the bbox based on its children.
  1134. var stroked_bbox = getStrokedBBox(selected.childNodes);
  1135. if(stroked_bbox) {
  1136. var bb = {};
  1137. $.each(bbox, function(key, val) {
  1138. bb[key] = stroked_bbox[key];
  1139. });
  1140. bbox = bb;
  1141. }
  1142. }
  1143. // loop and transform our bounding box until we reach our first rotation
  1144. var m = getMatrix(selected);
  1145. // This should probably be handled somewhere else, but for now
  1146. // it keeps the selection box correctly positioned when zoomed
  1147. m.e *= current_zoom;
  1148. m.f *= current_zoom;
  1149. // apply the transforms
  1150. var l=bbox.x-offset, t=bbox.y-offset, w=bbox.width+(offset*2), h=bbox.height+(offset*2),
  1151. bbox = {x:l, y:t, width:w, height:h};
  1152. // we need to handle temporary transforms too
  1153. // if skewed, get its transformed box, then find its axis-aligned bbox
  1154. //*
  1155. var nbox = transformBox(l*current_zoom, t*current_zoom, w*current_zoom, h*current_zoom, m),
  1156. nbax = nbox.aabox.x,
  1157. nbay = nbox.aabox.y,
  1158. nbaw = nbox.aabox.width,
  1159. nbah = nbox.aabox.height;
  1160. // now if the shape is rotated, un-rotate it
  1161. var cx = nbax + nbaw/2,
  1162. cy = nbay + nbah/2;
  1163. var angle = getRotationAngle(selected);
  1164. if (angle) {
  1165. var rot = svgroot.createSVGTransform();
  1166. rot.setRotate(-angle,cx,cy);
  1167. var rotm = rot.matrix;
  1168. nbox.tl = transformPoint(nbox.tl.x,nbox.tl.y,rotm);
  1169. nbox.tr = transformPoint(nbox.tr.x,nbox.tr.y,rotm);
  1170. nbox.bl = transformPoint(nbox.bl.x,nbox.bl.y,rotm);
  1171. nbox.br = transformPoint(nbox.br.x,nbox.br.y,rotm);
  1172. // calculate the axis-aligned bbox
  1173. var minx = nbox.tl.x,
  1174. miny = nbox.tl.y,
  1175. maxx = nbox.tl.x,
  1176. maxy = nbox.tl.y;
  1177. minx = Math.min(minx, Math.min(nbox.tr.x, Math.min(nbox.bl.x, nbox.br.x) ) );
  1178. miny = Math.min(miny, Math.min(nbox.tr.y, Math.min(nbox.bl.y, nbox.br.y) ) );
  1179. maxx = Math.max(maxx, Math.max(nbox.tr.x, Math.max(nbox.bl.x, nbox.br.x) ) );
  1180. maxy = Math.max(maxy, Math.max(nbox.tr.y, Math.max(nbox.bl.y, nbox.br.y) ) );
  1181. nbax = minx;
  1182. nbay = miny;
  1183. nbaw = (maxx-minx);
  1184. nbah = (maxy-miny);
  1185. }
  1186. var sr_handle = svgroot.suspendRedraw(100);
  1187. var dstr = "M" + nbax + "," + nbay
  1188. + " L" + (nbax+nbaw) + "," + nbay
  1189. + " " + (nbax+nbaw) + "," + (nbay+nbah)
  1190. + " " + nbax + "," + (nbay+nbah) + "z";
  1191. assignAttributes(selectedBox, {'d': dstr});
  1192. this.gripCoords = {
  1193. nw: [nbax, nbay],
  1194. ne: [nbax+nbaw, nbay],
  1195. sw: [nbax, nbay+nbah],
  1196. se: [nbax+nbaw, nbay+nbah],
  1197. n: [nbax + (nbaw)/2, nbay],
  1198. w: [nbax, nbay + (nbah)/2],
  1199. e: [nbax + nbaw, nbay + (nbah)/2],
  1200. s: [nbax + (nbaw)/2, nbay + nbah]
  1201. };
  1202. if(selected == selectedElements[0]) {
  1203. for(var dir in this.gripCoords) {
  1204. var coords = this.gripCoords[dir];
  1205. assignAttributes(selectedGrips[dir], {
  1206. cx: coords[0], cy: coords[1]
  1207. });
  1208. };
  1209. }
  1210. if (angle) {
  1211. this.selectorGroup.setAttribute("transform", "rotate(" + [angle,cx,cy].join(",") + ")");
  1212. }
  1213. else {
  1214. this.selectorGroup.setAttribute("transform", "");
  1215. }
  1216. // we want to go 20 pixels in the negative transformed y direction, ignoring scale
  1217. assignAttributes(mgr.rotateGripConnector, { x1: nbax + (nbaw)/2,
  1218. y1: nbay,
  1219. x2: nbax + (nbaw)/2,
  1220. y2: nbay- 20});
  1221. assignAttributes(mgr.rotateGrip, { cx: nbax + (nbaw)/2,
  1222. cy: nbay - 20 });
  1223. svgroot.unsuspendRedraw(sr_handle);
  1224. };
  1225. // now initialize the selector
  1226. this.reset(elem);
  1227. };
  1228. // Interface: SelectorManager
  1229. // Public class to manage all selector objects (selection boxes)
  1230. SelectorManager = function() {
  1231. // this will hold the <g> element that contains all selector rects/grips
  1232. this.selectorParentGroup = null;
  1233. // this is a special rect that is used for multi-select
  1234. this.rubberBandBox = null;
  1235. // this will hold objects of type Selector (see above)
  1236. this.selectors = [];
  1237. // this holds a map of SVG elements to their Selector object
  1238. this.selectorMap = {};
  1239. // local reference to this object
  1240. var mgr = this;
  1241. // Function: SelectorManager.initGroup
  1242. // Resets the parent selector group element
  1243. this.initGroup = function() {
  1244. // remove old selector parent group if it existed
  1245. if (mgr.selectorParentGroup && mgr.selectorParentGroup.parentNode) {
  1246. mgr.selectorParentGroup.parentNode.removeChild(mgr.selectorParentGroup);
  1247. }
  1248. // create parent selector group and add it to svgroot
  1249. mgr.selectorParentGroup = svgdoc.createElementNS(svgns, "g");
  1250. mgr.selectorParentGroup.setAttribute("id", "selectorParentGroup");
  1251. mgr.selectorGripsGroup = svgdoc.createElementNS(svgns, "g");
  1252. mgr.selectorGripsGroup.setAttribute('display','none');
  1253. svgroot.appendChild(mgr.selectorParentGroup);
  1254. mgr.selectorParentGroup.appendChild(mgr.selectorGripsGroup);
  1255. mgr.selectorMap = {};
  1256. mgr.selectors = [];
  1257. mgr.rubberBandBox = null;
  1258. // this holds a reference to the grip elements
  1259. mgr.selectorGrips = { "nw":null,
  1260. "n":null,
  1261. "ne":null,
  1262. "e":null,
  1263. "se":null,
  1264. "s":null,
  1265. "sw":null,
  1266. "w":null
  1267. };
  1268. // add the corner grips
  1269. for (var dir in mgr.selectorGrips) {
  1270. var grip = addSvgElementFromJson({
  1271. "element": "circle",
  1272. "attr": {
  1273. "id": ("selectorGrip_resize_" + dir),
  1274. "fill": "#22C",
  1275. "r": 4,
  1276. "style": ("cursor:" + dir + "-resize"),
  1277. // This expands the mouse-able area of the grips making them
  1278. // easier to grab with the mouse.
  1279. // This works in Opera and WebKit, but does not work in Firefox
  1280. // see https://bugzilla.mozilla.org/show_bug.cgi?id=500174
  1281. "stroke-width": 2,
  1282. "pointer-events":"all"
  1283. }
  1284. });
  1285. elData(grip, "dir", dir);
  1286. elData(grip, "type", "resize");
  1287. this.selectorGrips[dir] = mgr.selectorGripsGroup.appendChild(grip);
  1288. }
  1289. // add rotator elems
  1290. this.rotateGripConnector = this.selectorGripsGroup.appendChild( addSvgElementFromJson({
  1291. "element": "line",
  1292. "attr": {
  1293. "id": ("selectorGrip_rotateconnector"),
  1294. "stroke": "#22C",
  1295. "stroke-width": "1"
  1296. }
  1297. }) );
  1298. this.rotateGrip = this.selectorGripsGroup.appendChild( addSvgElementFromJson({
  1299. "element": "circle",
  1300. "attr": {
  1301. "id": "selectorGrip_rotate",
  1302. "fill": "lime",
  1303. "r": 4,
  1304. "stroke": "#22C",
  1305. "stroke-width": 2,
  1306. "style": "cursor:url(" + curConfig.imgPath + "rotate.png) 12 12, auto;"
  1307. }
  1308. }) );
  1309. elData(this.rotateGrip, "type", "rotate");
  1310. if($("#canvasBackground").length) return;
  1311. var canvasbg = svgdoc.createElementNS(svgns, "svg");
  1312. var dims = curConfig.dimensions;
  1313. assignAttributes(canvasbg, {
  1314. 'id':'canvasBackground',
  1315. 'width': dims[0],
  1316. 'height': dims[1],
  1317. 'x': 0,
  1318. 'y': 0,
  1319. 'overflow': 'visible',
  1320. 'style': 'pointer-events:none'
  1321. });
  1322. var rect = svgdoc.createElementNS(svgns, "rect");
  1323. assignAttributes(rect, {
  1324. 'width': '100%',
  1325. 'height': '100%',
  1326. 'x': 0,
  1327. 'y': 0,
  1328. 'stroke-width': 1,
  1329. 'stroke': '#000',
  1330. 'fill': '#FFF',
  1331. 'style': 'pointer-events:none'
  1332. });
  1333. // Both Firefox and WebKit are too slow with this filter region (especially at higher
  1334. // zoom levels) and Opera has at least one bug
  1335. // if (!window.opera) rect.setAttribute('filter', 'url(#canvashadow)');
  1336. canvasbg.appendChild(rect);
  1337. svgroot.insertBefore(canvasbg, svgcontent);
  1338. };
  1339. // Function: SelectorManager.requestSelector
  1340. // Returns the selector based on the given element
  1341. //
  1342. // Parameters:
  1343. // elem - DOM element to get the selector for
  1344. this.requestSelector = function(elem) {
  1345. if (elem == null) return null;
  1346. var N = this.selectors.length;
  1347. // if we've already acquired one for this element, return it
  1348. if (typeof(this.selectorMap[elem.id]) == "object") {
  1349. this.selectorMap[elem.id].locked = true;
  1350. return this.selectorMap[elem.id];
  1351. }
  1352. for (var i = 0; i < N; ++i) {
  1353. if (this.selectors[i] && !this.selectors[i].locked) {
  1354. this.selectors[i].locked = true;
  1355. this.selectors[i].reset(elem);
  1356. this.selectorMap[elem.id] = this.selectors[i];
  1357. return this.selectors[i];
  1358. }
  1359. }
  1360. // if we reached here, no available selectors were found, we create one
  1361. this.selectors[N] = new Selector(N, elem);
  1362. this.selectorParentGroup.appendChild(this.selectors[N].selectorGroup);
  1363. this.selectorMap[elem.id] = this.selectors[N];
  1364. return this.selectors[N];
  1365. };
  1366. // Function: SelectorManager.releaseSelector
  1367. // Removes the selector of the given element (hides selection box)
  1368. //
  1369. // Parameters:
  1370. // elem - DOM element to remove the selector for
  1371. this.releaseSelector = function(elem) {
  1372. if (elem == null) return;
  1373. var N = this.selectors.length,
  1374. sel = this.selectorMap[elem.id];
  1375. for (var i = 0; i < N; ++i) {
  1376. if (this.selectors[i] && this.selectors[i] == sel) {
  1377. if (sel.locked == false) {
  1378. console.log("WARNING! selector was released but was already unlocked");
  1379. }
  1380. delete this.selectorMap[elem.id];
  1381. sel.locked = false;
  1382. sel.selectedElement = null;
  1383. sel.showGrips(false);
  1384. // remove from DOM and store reference in JS but only if it exists in the DOM
  1385. try {
  1386. sel.selectorGroup.setAttribute("display", "none");
  1387. } catch(e) { }
  1388. break;
  1389. }
  1390. }
  1391. };
  1392. // Function: SelectorManager.getRubberBandBox
  1393. // Returns the rubberBandBox DOM element. This is the rectangle drawn by the user for selecting/zooming
  1394. this.getRubberBandBox = function() {
  1395. if (this.rubberBandBox == null) {
  1396. this.rubberBandBox = this.selectorParentGroup.appendChild(
  1397. addSvgElementFromJson({ "element": "rect",
  1398. "attr": {
  1399. "id": "selectorRubberBand",
  1400. "fill": "#22C",
  1401. "fill-opacity": 0.15,
  1402. "stroke": "#22C",
  1403. "stroke-width": 0.5,
  1404. "display": "none",
  1405. "style": "pointer-events:none"
  1406. }
  1407. }));
  1408. }
  1409. return this.rubberBandBox;
  1410. };
  1411. this.initGroup();
  1412. };
  1413. }());
  1414. // **************************************************************************************
  1415. // SVGTransformList implementation for Webkit
  1416. // These methods do not currently raise any exceptions.
  1417. // These methods also do not check that transforms are being inserted or handle if
  1418. // a transform is already in the list, etc. This is basically implementing as much
  1419. // of SVGTransformList that we need to get the job done.
  1420. //
  1421. // interface SVGEditTransformList {
  1422. // attribute unsigned long numberOfItems;
  1423. // void clear ( )
  1424. // SVGTransform initialize ( in SVGTransform newItem )
  1425. // SVGTransform getItem ( in unsigned long index )
  1426. // SVGTransform insertItemBefore ( in SVGTransform newItem, in unsigned long index )
  1427. // SVGTransform replaceItem ( in SVGTransform newItem, in unsigned long index )
  1428. // SVGTransform removeItem ( in unsigned long index )
  1429. // SVGTransform appendItem ( in SVGTransform newItem )
  1430. // NOT IMPLEMENTED: SVGTransform createSVGTransformFromMatrix ( in SVGMatrix matrix );
  1431. // NOT IMPLEMENTED: SVGTransform consolidate ( );
  1432. // }
  1433. // **************************************************************************************
  1434. var svgTransformLists = {};
  1435. var SVGEditTransformList = function(elem) {
  1436. function transformToString(xform) {
  1437. var m = xform.matrix,
  1438. text = "";
  1439. switch(xform.type) {
  1440. case 1: // MATRIX
  1441. text = "matrix(" + [m.a,m.b,m.c,m.d,m.e,m.f].join(",") + ")";
  1442. break;
  1443. case 2: // TRANSLATE
  1444. text = "translate(" + m.e + "," + m.f + ")";
  1445. break;
  1446. case 3: // SCALE
  1447. if (m.a == m.d) text = "scale(" + m.a + ")";
  1448. else text = "scale(" + m.a + "," + m.d + ")";
  1449. break;
  1450. case 4: // ROTATE
  1451. var cx = 0, cy = 0;
  1452. // this prevents divide by zero
  1453. if (xform.angle != 0) {
  1454. var K = 1 - m.a;
  1455. cy = ( K * m.f + m.b*m.e ) / ( K*K + m.b*m.b );
  1456. cx = ( m.e - m.b * cy ) / K;
  1457. }
  1458. text = "rotate(" + xform.angle + " " + cx + "," + cy + ")";
  1459. break;
  1460. }
  1461. return text;
  1462. };
  1463. this._elem = elem || null;
  1464. this._xforms = [];
  1465. // TODO: how do we capture the undo-ability in the changed transform list?
  1466. this._update = function() {
  1467. var tstr = "";
  1468. var concatMatrix = svgroot.createSVGMatrix();
  1469. for (var i = 0; i < this.numberOfItems; ++i) {
  1470. var xform = this._list.getItem(i);
  1471. tstr += transformToString(xform) + " ";
  1472. }
  1473. this._elem.setAttribute("transform", tstr);
  1474. };
  1475. this._list = this;
  1476. this._init = function() {
  1477. // Transform attribute parser
  1478. var str = this._elem.getAttribute("transform");
  1479. if(!str) return;
  1480. // TODO: Add skew support in future
  1481. var re = /\s*((scale|matrix|rotate|translate)\s*\(.*?\))\s*,?\s*/;
  1482. var arr = [];
  1483. var m = true;
  1484. while(m) {
  1485. m = str.match(re);
  1486. str = str.replace(re,'');
  1487. if(m && m[1]) {
  1488. var x = m[1];
  1489. var bits = x.split(/\s*\(/);
  1490. var name = bits[0];
  1491. var val_bits = bits[1].match(/\s*(.*?)\s*\)/);
  1492. var val_arr = val_bits[1].split(/[, ]+/);
  1493. var letters = 'abcdef'.split('');
  1494. var mtx = svgroot.createSVGMatrix();
  1495. $.each(val_arr, function(i, item) {
  1496. val_arr[i] = parseFloat(item);
  1497. if(name == 'matrix') {
  1498. mtx[letters[i]] = val_arr[i];
  1499. }
  1500. });
  1501. var xform = svgroot.createSVGTransform();
  1502. var fname = 'set' + name.charAt(0).toUpperCase() + name.slice(1);
  1503. var values = name=='matrix'?[mtx]:val_arr;
  1504. if(name == 'scale' && values.length == 1) {
  1505. values.push(values[0]);
  1506. } else if(name == 'translate' && values.length == 1) {
  1507. values.push(0);
  1508. }
  1509. xform[fname].apply(xform, values);
  1510. this._list.appendItem(xform);
  1511. }
  1512. }
  1513. }
  1514. this.numberOfItems = 0;
  1515. this.clear = function() {
  1516. this.numberOfItems = 0;
  1517. this._xforms = [];
  1518. };
  1519. this.initialize = function(newItem) {
  1520. this.numberOfItems = 1;
  1521. this._xforms = [newItem];
  1522. };
  1523. this.getItem = function(index) {
  1524. if (index < this.numberOfItems && index >= 0) {
  1525. return this._xforms[index];
  1526. }
  1527. return null;
  1528. };
  1529. this.insertItemBefore = function(newItem, index) {
  1530. var retValue = null;
  1531. if (index >= 0) {
  1532. if (index < this.numberOfItems) {
  1533. var newxforms = new Array(this.numberOfItems + 1);
  1534. // TODO: use array copying and slicing
  1535. for ( var i = 0; i < index; ++i) {
  1536. newxforms[i] = this._xforms[i];
  1537. }
  1538. newxforms[i] = newItem;
  1539. for ( var j = i+1; i < this.numberOfItems; ++j, ++i) {
  1540. newxforms[j] = this._xforms[i];
  1541. }
  1542. this.numberOfItems++;
  1543. this._xforms = newxforms;
  1544. retValue = newItem;
  1545. this._list._update();
  1546. }
  1547. else {
  1548. retValue = this._list.appendItem(newItem);
  1549. }
  1550. }
  1551. return retValue;
  1552. };
  1553. this.replaceItem = function(newItem, index) {
  1554. var retValue = null;
  1555. if (index < this.numberOfItems && index >= 0) {
  1556. this._xforms[index] = newItem;
  1557. retValue = newItem;
  1558. this._list._update();
  1559. }
  1560. return retValue;
  1561. };
  1562. this.removeItem = function(index) {
  1563. var retValue = null;
  1564. if (index < this.numberOfItems && index >= 0) {
  1565. var retValue = this._xforms[index];
  1566. var newxforms = new Array(this.numberOfItems - 1);
  1567. for (var i = 0; i < index; ++i) {
  1568. newxforms[i] = this._xforms[i];
  1569. }
  1570. for (var j = i; j < this.numberOfItems-1; ++j, ++i) {
  1571. newxforms[j] = this._xforms[i+1];
  1572. }
  1573. this.numberOfItems--;
  1574. this._xforms = newxforms;
  1575. this._list._update();
  1576. }
  1577. return retValue;
  1578. };
  1579. this.appendItem = function(newItem) {
  1580. this._xforms.push(newItem);
  1581. this.numberOfItems++;
  1582. this._list._update();
  1583. return newItem;
  1584. };
  1585. };
  1586. // **************************************************************************************
  1587. // Group: Helper functions
  1588. // Function: walkTree
  1589. // Walks the tree and executes the callback on each element in a top-down fashion
  1590. //
  1591. // Parameters:
  1592. // elem - DOM element to traverse
  1593. // cbFn - Callback function to run on each element
  1594. function walkTree(elem, cbFn){
  1595. if (elem && elem.nodeType == 1) {
  1596. cbFn(elem);
  1597. var i = elem.childNodes.length;
  1598. while (i--) {
  1599. walkTree(elem.childNodes.item(i), cbFn);
  1600. }
  1601. }
  1602. };
  1603. // Function: walkTreePost
  1604. // Walks the tree and executes the callback on each element in a depth-first fashion
  1605. //
  1606. // Parameters:
  1607. // elem - DOM element to traverse
  1608. // cbFn - Callback function to run on each element
  1609. function walkTreePost(elem, cbFn) {
  1610. if (elem && elem.nodeType == 1) {
  1611. var i = elem.childNodes.length;
  1612. while (i--) {
  1613. walkTree(elem.childNodes.item(i), cbFn);
  1614. }
  1615. cbFn(elem);
  1616. }
  1617. };
  1618. // Function: assignAttributes
  1619. // Assigns multiple attributes to an element.
  1620. //
  1621. // Parameters:
  1622. // node - DOM element to apply new attribute values to
  1623. // attrs - Object with attribute keys/values
  1624. // suspendLength - Optional integer of milliseconds to suspend redraw
  1625. // unitCheck - Boolean to indicate the need to use setUnitAttr
  1626. var assignAttributes = this.assignAttributes = function(node, attrs, suspendLength, unitCheck) {
  1627. if(!suspendLength) suspendLength = 0;
  1628. // Opera has a problem with suspendRedraw() apparently
  1629. var handle = null;
  1630. if (!window.opera) svgroot.suspendRedraw(suspendLength);
  1631. for (var i in attrs) {
  1632. var ns = (i.substr(0,4) == "xml:" ? xmlns :
  1633. i.substr(0,6) == "xlink:" ? xlinkns : null);
  1634. if(ns || !unitCheck) {
  1635. node.setAttributeNS(ns, i, attrs[i]);
  1636. } else {
  1637. setUnitAttr(node, i, attrs[i]);
  1638. }
  1639. }
  1640. if (!window.opera) svgroot.unsuspendRedraw(handle);
  1641. };
  1642. // Function: cleanupElement
  1643. // Remove unneeded (default) attributes, makes resulting SVG smaller
  1644. //
  1645. // Parameters:
  1646. // element - DOM element to clean up
  1647. var cleanupElement = this.cleanupElement = function(element) {
  1648. var handle = svgroot.suspendRedraw(60);
  1649. var defaults = {
  1650. 'fill-opacity':1,
  1651. 'stop-opacity':1,
  1652. 'opacity':1,
  1653. 'stroke':'none',
  1654. 'stroke-dasharray':'none',
  1655. 'stroke-linejoin':'miter',
  1656. 'stroke-linecap':'butt',
  1657. 'stroke-opacity':1,
  1658. 'stroke-width':1,
  1659. 'rx':0,
  1660. 'ry':0
  1661. }
  1662. for(var attr in defaults) {
  1663. var val = defaults[attr];
  1664. if(element.getAttribute(attr) == val) {
  1665. element.removeAttribute(attr);
  1666. }
  1667. }
  1668. svgroot.unsuspendRedraw(handle);
  1669. };
  1670. // Function: addSvgElementFromJson
  1671. // Create a new SVG element based on the given object keys/values and add it to the current layer
  1672. // The element will be ran through cleanupElement before being returned
  1673. //
  1674. // Parameters:
  1675. // data - Object with the following keys/values:
  1676. // * element - DOM element to create
  1677. // * attr - Object with attributes/values to assign to the new element
  1678. // * curStyles - Boolean indicating that current style attributes should be applied first
  1679. //
  1680. // Returns: The new element
  1681. var addSvgElementFromJson = this.addSvgElementFromJson = function(data) {
  1682. var shape = getElem(data.attr.id);
  1683. // if shape is a path but we need to create a rect/ellipse, then remove the path
  1684. if (shape && data.element != shape.tagName) {
  1685. current_layer.removeChild(shape);
  1686. shape = null;
  1687. }
  1688. if (!shape) {
  1689. shape = svgdoc.createElementNS(svgns, data.element);
  1690. if (current_layer) {
  1691. (current_group || current_layer).appendChild(shape);
  1692. }
  1693. }
  1694. if(data.curStyles) {
  1695. assignAttributes(shape, {
  1696. "fill": cur_shape.fill,
  1697. "stroke": cur_shape.stroke,
  1698. "stroke-width": cur_shape.stroke_width,
  1699. "stroke-dasharray": cur_shape.stroke_dasharray,
  1700. "stroke-linejoin": cur_shape.stroke_linejoin,
  1701. "stroke-linecap": cur_shape.stroke_linecap,
  1702. "stroke-opacity": cur_shape.stroke_opacity,
  1703. "fill-opacity": cur_shape.fill_opacity,
  1704. "opacity": cur_shape.opacity / 2,
  1705. "style": "pointer-events:inherit"
  1706. }, 100);
  1707. }
  1708. assignAttributes(shape, data.attr, 100);
  1709. cleanupElement(shape);
  1710. return shape;
  1711. };
  1712. (function() {
  1713. // TODO: make this string optional and set by the client
  1714. var comment = svgdoc.createComment(" Created with SVG-edit - http://svg-edit.googlecode.com/ ");
  1715. svgcontent.appendChild(comment);
  1716. // TODO For Issue 208: this is a start on a thumbnail
  1717. // var svgthumb = svgdoc.createElementNS(svgns, "use");
  1718. // svgthumb.setAttribute('width', '100');
  1719. // svgthumb.setAttribute('height', '100');
  1720. // setHref(svgthumb, '#svgcontent');
  1721. // svgroot.appendChild(svgthumb);
  1722. })();
  1723. // z-ordered array of tuples containing layer names and <g> elements
  1724. // the first layer is the one at the bottom of the rendering
  1725. var all_layers = [],
  1726. // Object to contain image data for raster images that were found encodable
  1727. encodableImages = {},
  1728. // String with image URL of last loadable image
  1729. last_good_img_url = curConfig.imgPath + 'logo.png',
  1730. // pointer to the current layer <g>
  1731. current_layer = null,
  1732. // pointer to current group (for in-group editing)
  1733. current_group = null,
  1734. // Array with current disabled elements (for in-group editing)
  1735. disabled_elems = [],
  1736. // Object with save options
  1737. save_options = {round_digits: 5},
  1738. // Boolean indicating whether or not a draw action has been started
  1739. started = false,
  1740. // Integer with internal ID number for the latest element
  1741. obj_num = 1,
  1742. // String with an element's initial transform attribute value
  1743. start_transform = null,
  1744. // String indicating the current editor mode
  1745. current_mode = "select",
  1746. // String with the current direction in which an element is being resized
  1747. current_resize_mode = "none",
  1748. // Object containing data for the currently selected styles
  1749. all_properties = {
  1750. shape: {
  1751. fill: "#" + curConfig.initFill.color,
  1752. fill_paint: null,
  1753. fill_opacity: curConfig.initFill.opacity,
  1754. stroke: "#" + curConfig.initStroke.color,
  1755. stroke_paint: null,
  1756. stroke_opacity: curConfig.initStroke.opacity,
  1757. stroke_width: curConfig.initStroke.width,
  1758. stroke_dasharray: 'none',
  1759. stroke_linejoin: 'miter',
  1760. stroke_linecap: 'butt',
  1761. opacity: curConfig.initOpacity
  1762. }
  1763. };
  1764. all_properties.text = $.extend(true, {}, all_properties.shape);
  1765. $.extend(all_properties.text, {
  1766. fill: "#000000",
  1767. stroke_width: 0,
  1768. font_size: 24,
  1769. font_family: 'serif'
  1770. });
  1771. // Current shape style properties
  1772. var cur_shape = all_properties.shape,
  1773. // Current text style properties
  1774. cur_text = all_properties.text,
  1775. // Current general properties
  1776. cur_properties = cur_shape,
  1777. // Float displaying the current zoom level (1 = 100%, .5 = 50%, etc)
  1778. current_zoom = 1,
  1779. // Array with all the currently selected elements
  1780. // default size of 1 until it needs to grow bigger
  1781. selectedElements = new Array(1),
  1782. // Array with selected elements' Bounding box object
  1783. selectedBBoxes = new Array(1),
  1784. // The DOM element that was just selected
  1785. justSelected = null,
  1786. // this object manages selectors for us
  1787. selectorManager = this.selectorManager = new SelectorManager(),
  1788. // DOM element for selection rectangle drawn by the user
  1789. rubberBox = null,
  1790. // Array of current BBoxes (still needed?)
  1791. curBBoxes = [],
  1792. // Object to contain all included extensions
  1793. extensions = {},
  1794. // Canvas point for the most recent right click
  1795. lastClickPoint = null;
  1796. // Clipboard for cut, copy&pasted elements
  1797. canvas.clipBoard = [];
  1798. // Should this return an array by default, so extension results aren't overwritten?
  1799. var runExtensions = this.runExtensions = function(action, vars, returnArray) {
  1800. var result = false;
  1801. if(returnArray) result = [];
  1802. $.each(extensions, function(name, opts) {
  1803. if(action in opts) {
  1804. if(returnArray) {
  1805. result.push(opts[action](vars))
  1806. } else {
  1807. result = opts[action](vars);
  1808. }
  1809. }
  1810. });
  1811. return result;
  1812. }
  1813. // Function: addExtension
  1814. // Add an extension to the editor
  1815. //
  1816. // Parameters:
  1817. // name - String with the ID of the extension
  1818. // ext_func - Function supplied by the extension with its data
  1819. this.addExtension = function(name, ext_func) {
  1820. if(!(name in extensions)) {
  1821. // Provide private vars/funcs here. Is there a better way to do this?
  1822. if($.isFunction(ext_func)) {
  1823. var ext = ext_func($.extend(canvas.getPrivateMethods(), {
  1824. svgroot: svgroot,
  1825. svgcontent: svgcontent,
  1826. nonce: nonce,
  1827. selectorManager: selectorManager
  1828. }));
  1829. } else {
  1830. var ext = ext_func;
  1831. }
  1832. extensions[name] = ext;
  1833. call("extension_added", ext);
  1834. } else {
  1835. console.log('Cannot add extension "' + name + '", an extension by that name already exists"');
  1836. }
  1837. };
  1838. // Function: shortFloat
  1839. // Rounds a given value to a float with number of digits defined in save_options
  1840. //
  1841. // Parameters:
  1842. // val - The value as a String, Number or Array of two numbers to be rounded
  1843. //
  1844. // Returns:
  1845. // If a string/number was given, returns a Float. If an array, return a string
  1846. // with comma-seperated floats
  1847. var shortFloat = function(val) {
  1848. var digits = save_options.round_digits;
  1849. if(!isNaN(val)) {
  1850. return Number(Number(val).toFixed(digits));
  1851. } else if($.isArray(val)) {
  1852. return shortFloat(val[0]) + ',' + shortFloat(val[1]);
  1853. } else {
  1854. return parseFloat(val).toFixed(digits) - 0;
  1855. }
  1856. }
  1857. // This method rounds the incoming value to the nearest value based on the current_zoom
  1858. var round = this.round = function(val) {
  1859. return parseInt(val*current_zoom)/current_zoom;
  1860. };
  1861. // This method sends back an array or a NodeList full of elements that
  1862. // intersect the multi-select rubber-band-box on the current_layer only.
  1863. //
  1864. // Since the only browser that supports the SVG DOM getIntersectionList is Opera,
  1865. // we need to provide an implementation here. We brute-force it for now.
  1866. //
  1867. // Reference:
  1868. // Firefox does not implement getIntersectionList(), see https://bugzilla.mozilla.org/show_bug.cgi?id=501421
  1869. // Webkit does not implement getIntersectionList(), see https://bugs.webkit.org/show_bug.cgi?id=11274
  1870. var getIntersectionList = this.getIntersectionList = function(rect) {
  1871. if (rubberBox == null) { return null; }
  1872. var parent = current_group || current_layer;
  1873. if(!curBBoxes.length) {
  1874. // Cache all bboxes
  1875. curBBoxes = getVisibleElements(parent, true);
  1876. }
  1877. var resultList = null;
  1878. try {
  1879. resultList = parent.getIntersectionList(rect, null);
  1880. } catch(e) { }
  1881. if (resultList == null || typeof(resultList.item) != "function") {
  1882. resultList = [];
  1883. if(!rect) {
  1884. var rubberBBox = rubberBox.getBBox();
  1885. var bb = {};
  1886. for(var o in rubberBBox) {
  1887. bb[o] = rubberBBox[o] / current_zoom;
  1888. }
  1889. rubberBBox = bb;
  1890. } else {
  1891. var rubberBBox = rect;
  1892. }
  1893. var i = curBBoxes.length;
  1894. while (i--) {
  1895. if(!rubberBBox.width || !rubberBBox.width) continue;
  1896. if (Utils.rectsIntersect(rubberBBox, curBBoxes[i].bbox)) {
  1897. resultList.push(curBBoxes[i].elem);
  1898. }
  1899. }
  1900. }
  1901. // addToSelection expects an array, but it's ok to pass a NodeList
  1902. // because using square-bracket notation is allowed:
  1903. // http://www.w3.org/TR/DOM-Level-2-Core/ecma-script-binding.html
  1904. return resultList;
  1905. };
  1906. // Function: getStrokedBBox
  1907. // Get the bounding box for one or more stroked and/or transformed elements
  1908. //
  1909. // Parameters:
  1910. // elems - Array with DOM elements to check
  1911. //
  1912. // Returns:
  1913. // A single bounding box object
  1914. var getStrokedBBox = this.getStrokedBBox = function(elems) {
  1915. if(!elems) elems = getVisibleElements();
  1916. if(!elems.length) return false;
  1917. // Make sure the expected BBox is returned if the element is a group
  1918. var getCheckedBBox = function(elem) {
  1919. try {
  1920. // TODO: Fix issue with rotated groups. Currently they work
  1921. // fine in FF, but not in other browsers (same problem mentioned
  1922. // in Issue 339 comment #2).
  1923. var bb = getBBox(elem);
  1924. var angle = getRotationAngle(elem);
  1925. if ((angle && angle % 90) || hasMatrixTransform(getTransformList(elem))) {
  1926. // Accurate way to get BBox of rotated element in Firefox:
  1927. // Put element in group and get its BBox
  1928. var good_bb = false;
  1929. // Get the BBox from the raw path for these elements
  1930. var elemNames = ['ellipse','path','line','polyline','polygon'];
  1931. if(elemNames.indexOf(elem.tagName) >= 0) {
  1932. bb = good_bb = canvas.convertToPath(elem, true);
  1933. } else if(elem.tagName == 'rect') {
  1934. // Look for radius
  1935. var rx = elem.getAttribute('rx');
  1936. var ry = elem.getAttribute('ry');
  1937. if(rx || ry) {
  1938. bb = good_bb = canvas.convertToPath(elem, true);
  1939. }
  1940. }
  1941. if(!good_bb) {
  1942. var g = document.createElementNS(svgns, "g");
  1943. var parent = elem.parentNode;
  1944. parent.replaceChild(g, elem);
  1945. g.appendChild(elem);
  1946. bb = g.getBBox();
  1947. parent.insertBefore(elem,g);
  1948. parent.removeChild(g);
  1949. }
  1950. // Old method: Works by giving the rotated BBox,
  1951. // this is (unfortunately) what Opera and Safari do
  1952. // natively when getting the BBox of the parent group
  1953. // var angle = angle * Math.PI / 180.0;
  1954. // var rminx = Number.MAX_VALUE, rminy = Number.MAX_VALUE,
  1955. // rmaxx = Number.MIN_VALUE, rmaxy = Number.MIN_VALUE;
  1956. // var cx = round(bb.x + bb.width/2),
  1957. // cy = round(bb.y + bb.height/2);
  1958. // var pts = [ [bb.x - cx, bb.y - cy],
  1959. // [bb.x + bb.width - cx, bb.y - cy],
  1960. // [bb.x + bb.width - cx, bb.y + bb.height - cy],
  1961. // [bb.x - cx, bb.y + bb.height - cy] ];
  1962. // var j = 4;
  1963. // while (j--) {
  1964. // var x = pts[j][0],
  1965. // y = pts[j][1],
  1966. // r = Math.sqrt( x*x + y*y );
  1967. // var theta = Math.atan2(y,x) + angle;
  1968. // x = round(r * Math.cos(theta) + cx);
  1969. // y = round(r * Math.sin(theta) + cy);
  1970. //
  1971. // // now set the bbox for the shape after it's been rotated
  1972. // if (x < rminx) rminx = x;
  1973. // if (y < rminy) rminy = y;
  1974. // if (x > rmaxx) rmaxx = x;
  1975. // if (y > rmaxy) rmaxy = y;
  1976. // }
  1977. //
  1978. // bb.x = rminx;
  1979. // bb.y = rminy;
  1980. // bb.width = rmaxx - rminx;
  1981. // bb.height = rmaxy - rminy;
  1982. }
  1983. return bb;
  1984. } catch(e) {
  1985. console.log(elem, e);
  1986. return null;
  1987. }
  1988. }
  1989. var full_bb;
  1990. $.each(elems, function() {
  1991. if(full_bb) return;
  1992. if(!this.parentNode) return;
  1993. full_bb = getCheckedBBox(this);
  1994. if(full_bb) {
  1995. var b = {};
  1996. for(var i in full_bb) b[i] = full_bb[i];
  1997. full_bb = b;
  1998. }
  1999. });
  2000. // This shouldn't ever happen...
  2001. if(full_bb == null) return null;
  2002. // full_bb doesn't include the stoke, so this does no good!
  2003. // if(elems.length == 1) return full_bb;
  2004. var max_x = full_bb.x + full_bb.width;
  2005. var max_y = full_bb.y + full_bb.height;
  2006. var min_x = full_bb.x;
  2007. var min_y = full_bb.y;
  2008. // FIXME: same re-creation problem with this function as getCheckedBBox() above
  2009. var getOffset = function(elem) {
  2010. var sw = elem.getAttribute("stroke-width");
  2011. var offset = 0;
  2012. if (elem.getAttribute("stroke") != "none" && !isNaN(sw)) {
  2013. offset += sw/2;
  2014. }
  2015. return offset;
  2016. }
  2017. var bboxes = [];
  2018. $.each(elems, function(i, elem) {
  2019. var cur_bb = getCheckedBBox(elem);
  2020. if(cur_bb) {
  2021. var offset = getOffset(elem);
  2022. min_x = Math.min(min_x, cur_bb.x - offset);
  2023. min_y = Math.min(min_y, cur_bb.y - offset);
  2024. bboxes.push(cur_bb);
  2025. }
  2026. });
  2027. full_bb.x = min_x;
  2028. full_bb.y = min_y;
  2029. $.each(elems, function(i, elem) {
  2030. var cur_bb = bboxes[i];
  2031. // ensure that elem is really an element node
  2032. if (cur_bb && elem.nodeType == 1) {
  2033. var offset = getOffset(elem);
  2034. max_x = Math.max(max_x, cur_bb.x + cur_bb.width + offset);
  2035. max_y = Math.max(max_y, cur_bb.y + cur_bb.height + offset);
  2036. }
  2037. });
  2038. full_bb.width = max_x - min_x;
  2039. full_bb.height = max_y - min_y;
  2040. return full_bb;
  2041. }
  2042. // Function: getVisibleElements
  2043. // Get all elements that have a BBox (excludes <defs>, <title>, etc).
  2044. // Note that 0-opacity, off-screen etc elements are still considered "visible"
  2045. // for this function
  2046. //
  2047. // Parameters:
  2048. // parent - The parent DOM element to search within
  2049. // includeBBox - Boolean to indicate that an object should return with the element and its bbox
  2050. //
  2051. // Returns:
  2052. // An array with all "visible" elements, or if includeBBox is true, an array with
  2053. // objects that include:
  2054. // * elem - The element
  2055. // * bbox - The element's BBox as retrieved from getStrokedBBox
  2056. var getVisibleElements = this.getVisibleElements = function(parent, includeBBox) {
  2057. if(!parent) parent = $(svgcontent).children(); // Prevent layers from being included
  2058. var contentElems = [];
  2059. $(parent).children().each(function(i, elem) {
  2060. try {
  2061. var box = elem.getBBox();
  2062. if (box) {
  2063. var item = includeBBox?{'elem':elem, 'bbox':getStrokedBBox([elem])}:elem;
  2064. contentElems.push(item);
  2065. }
  2066. } catch(e) {}
  2067. });
  2068. return contentElems.reverse();
  2069. }
  2070. // Function: groupSvgElem
  2071. // Wrap an SVG element into a group element, mark the group as 'gsvg'
  2072. //
  2073. // Parameters:
  2074. // elem - SVG element to wrap
  2075. var groupSvgElem = this.groupSvgElem = function(elem) {
  2076. var g = document.createElementNS(svgns, "g");
  2077. elem.parentNode.replaceChild(g, elem);
  2078. $(g).append(elem).data('gsvg', elem)[0].id = getNextId();
  2079. }
  2080. // Function: copyElem
  2081. // Create a clone of an element, updating its ID and its children's IDs when needed
  2082. //
  2083. // Parameters:
  2084. // el - DOM element to clone
  2085. //
  2086. // Returns: The cloned element
  2087. var copyElem = function(el) {
  2088. // manually create a copy of the element
  2089. var new_el = document.createElementNS(el.namespaceURI, el.nodeName);
  2090. $.each(el.attributes, function(i, attr) {
  2091. if (attr.localName != '-moz-math-font-style') {
  2092. new_el.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.nodeValue);
  2093. }
  2094. });
  2095. // set the copied element's new id
  2096. new_el.removeAttribute("id");
  2097. new_el.id = getNextId();
  2098. // manually increment obj_num because our cloned elements are not in the DOM yet
  2099. obj_num++;
  2100. // Opera's "d" value needs to be reset for Opera/Win/non-EN
  2101. // Also needed for webkit (else does not keep curved segments on clone)
  2102. if((isWebkit) && el.nodeName == 'path') {
  2103. var fixed_d = pathActions.convertPath(el);
  2104. new_el.setAttribute('d', fixed_d);
  2105. }
  2106. // now create copies of all children
  2107. $.each(el.childNodes, function(i, child) {
  2108. switch(child.nodeType) {
  2109. case 1: // element node
  2110. new_el.appendChild(copyElem(child));
  2111. break;
  2112. case 3: // text node
  2113. new_el.textContent = child.nodeValue;
  2114. break;
  2115. default:
  2116. break;
  2117. }
  2118. });
  2119. if($(el).data('gsvg')) {
  2120. $(new_el).data('gsvg', new_el.firstChild);
  2121. } else if($(el).data('symbol')) {
  2122. var ref = $(el).data('symbol');
  2123. $(new_el).data('ref', ref).data('symbol', ref);
  2124. }
  2125. else if(new_el.tagName == 'image') {
  2126. preventClickDefault(new_el);
  2127. }
  2128. return new_el;
  2129. };
  2130. // Function: getElem
  2131. // Get a DOM element by ID within the SVG root element.
  2132. //
  2133. // Parameters:
  2134. // id - String with the element's new ID
  2135. function getElem(id) {
  2136. // if(svgroot.getElementById) {
  2137. // // getElementById lookup
  2138. // return svgroot.getElementById(id);
  2139. // } else
  2140. if(svgroot.querySelector) {
  2141. // querySelector lookup
  2142. return svgroot.querySelector('#'+id);
  2143. } else if(svgdoc.evaluate) {
  2144. // xpath lookup
  2145. return svgdoc.evaluate('svg:svg[@id="svgroot"]//svg:*[@id="'+id+'"]', container, function() { return "http://www.w3.org/2000/svg"; }, 9, null).singleNodeValue;
  2146. } else {
  2147. // jQuery lookup: twice as slow as xpath in FF
  2148. return $(svgroot).find('[id=' + id + ']')[0];
  2149. }
  2150. // getElementById lookup: includes icons, not good
  2151. // return svgdoc.getElementById(id);
  2152. }
  2153. // Set scope for these functions
  2154. var getId, getNextId;
  2155. (function(c) {
  2156. // Object to contain editor event names and callback functions
  2157. var events = {};
  2158. // Prefix string for element IDs
  2159. var idprefix = "svg_";
  2160. // Function: getId
  2161. // Returns the last created DOM element ID string
  2162. getId = c.getId = function() {
  2163. if (events["getid"]) return call("getid", obj_num);
  2164. if (randomize_ids) {
  2165. return idprefix + nonce +'_' + obj_num;
  2166. } else {
  2167. return idprefix + obj_num;
  2168. }
  2169. };
  2170. // Function: getNextId
  2171. // Creates and returns a unique ID string for a DOM element
  2172. getNextId = c.getNextId = function() {
  2173. // ensure the ID does not exist
  2174. var id = getId();
  2175. while (getElem(id)) {
  2176. obj_num++;
  2177. id = getId();
  2178. }
  2179. return id;
  2180. };
  2181. // Function: call
  2182. // Run the callback function associated with the given event
  2183. //
  2184. // Parameters:
  2185. // event - String with the event name
  2186. // arg - Argument to pass through to the callback function
  2187. call = c.call = function(event, arg) {
  2188. if (events[event]) {
  2189. return events[event](this,arg);
  2190. }
  2191. };
  2192. // Function: bind
  2193. // Attaches a callback function to an event
  2194. //
  2195. // Parameters:
  2196. // event - String indicating the name of the event
  2197. // f - The callback function to bind to the event
  2198. //
  2199. // Return:
  2200. // The previous event
  2201. c.bind = function(event, f) {
  2202. var old = events[event];
  2203. events[event] = f;
  2204. return old;
  2205. };
  2206. // Function: setIdPrefix
  2207. // Changes the ID prefix to the given value
  2208. //
  2209. // Parameters:
  2210. // p - String with the new prefix
  2211. c.setIdPrefix = function(p) {
  2212. idprefix = p;
  2213. };
  2214. }(canvas));
  2215. // Function: sanitizeSvg
  2216. // Sanitizes the input node and its children
  2217. // It only keeps what is allowed from our whitelist defined above
  2218. //
  2219. // Parameters:
  2220. // node - The DOM element to be checked, will also check its children
  2221. var sanitizeSvg = this.sanitizeSvg = function(node) {
  2222. // we only care about element nodes
  2223. // automatically return for all comment, etc nodes
  2224. // for text, we do a whitespace trim
  2225. if (node.nodeType == 3) {
  2226. node.nodeValue = node.nodeValue.replace(/^\s+|\s+$/g, "");
  2227. // Remove empty text nodes
  2228. if(!node.nodeValue.length) node.parentNode.removeChild(node);
  2229. }
  2230. if (node.nodeType != 1) return;
  2231. var doc = node.ownerDocument;
  2232. var parent = node.parentNode;
  2233. // can parent ever be null here? I think the root node's parent is the document...
  2234. if (!doc || !parent) return;
  2235. var allowedAttrs = svgWhiteList[node.nodeName];
  2236. var allowedAttrsNS = svgWhiteListNS[node.nodeName];
  2237. // if this element is allowed
  2238. if (allowedAttrs != undefined) {
  2239. var se_attrs = [];
  2240. var i = node.attributes.length;
  2241. while (i--) {
  2242. // if the attribute is not in our whitelist, then remove it
  2243. // could use jQuery's inArray(), but I don't know if that's any better
  2244. var attr = node.attributes.item(i);
  2245. var attrName = attr.nodeName;
  2246. var attrLocalName = attr.localName;
  2247. var attrNsURI = attr.namespaceURI;
  2248. // Check that an attribute with the correct localName in the correct namespace is on
  2249. // our whitelist or is a namespace declaration for one of our allowed namespaces
  2250. if (!(allowedAttrsNS.hasOwnProperty(attrLocalName) && attrNsURI == allowedAttrsNS[attrLocalName] && attrNsURI != xmlnsns) &&
  2251. !(attrNsURI == xmlnsns && nsMap[attr.nodeValue]) )
  2252. {
  2253. // Bypassing the whitelist to allow se: prefixes. Is there
  2254. // a more appropriate way to do this?
  2255. if(attrName.indexOf('se:') == 0) {
  2256. se_attrs.push([attrName, attr.nodeValue]);
  2257. }
  2258. node.removeAttributeNS(attrNsURI, attrLocalName);
  2259. }
  2260. // special handling for path d attribute
  2261. if (node.nodeName == 'path' && attrName == 'd') {
  2262. // Convert to absolute
  2263. node.setAttribute('d',pathActions.convertPath(node));
  2264. pathActions.fixEnd(node);
  2265. }
  2266. // for the style attribute, rewrite it in terms of XML presentational attributes
  2267. if (attrName == "style") {
  2268. var props = attr.nodeValue.split(";"),
  2269. p = props.length;
  2270. while(p--) {
  2271. var nv = props[p].split(":");
  2272. // now check that this attribute is supported
  2273. if (allowedAttrs.indexOf(nv[0]) >= 0) {
  2274. node.setAttribute(nv[0],nv[1]);
  2275. }
  2276. }
  2277. node.removeAttribute('style');
  2278. }
  2279. }
  2280. $.each(se_attrs, function(i, attr) {
  2281. node.setAttributeNS(se_ns, attr[0], attr[1]);
  2282. });
  2283. // for some elements that have a xlink:href, ensure the URI refers to a local element
  2284. // (but not for links)
  2285. var href = getHref(node);
  2286. if(href &&
  2287. ["filter", "linearGradient", "pattern",
  2288. "radialGradient", "textPath", "use"].indexOf(node.nodeName) >= 0)
  2289. {
  2290. // TODO: we simply check if the first character is a #, is this bullet-proof?
  2291. if (href[0] != "#") {
  2292. // remove the attribute (but keep the element)
  2293. setHref(node, "");
  2294. node.removeAttributeNS(xlinkns, "href");
  2295. }
  2296. }
  2297. // Safari crashes on a <use> without a xlink:href, so we just remove the node here
  2298. if (node.nodeName == "use" && !getHref(node)) {
  2299. parent.removeChild(node);
  2300. return;
  2301. }
  2302. // if the element has attributes pointing to a non-local reference,
  2303. // need to remove the attribute
  2304. $.each(["clip-path", "fill", "filter", "marker-end", "marker-mid", "marker-start", "mask", "stroke"],function(i,attr) {
  2305. var val = node.getAttribute(attr);
  2306. if (val) {
  2307. val = getUrlFromAttr(val);
  2308. // simply check for first character being a '#'
  2309. if (val && val[0] != "#") {
  2310. node.setAttribute(attr, "");
  2311. node.removeAttribute(attr);
  2312. }
  2313. }
  2314. });
  2315. // recurse to children
  2316. i = node.childNodes.length;
  2317. while (i--) { sanitizeSvg(node.childNodes.item(i)); }
  2318. }
  2319. // else, remove this element
  2320. else {
  2321. // remove all children from this node and insert them before this node
  2322. // FIXME: in the case of animation elements this will hardly ever be correct
  2323. var children = [];
  2324. while (node.hasChildNodes()) {
  2325. children.push(parent.insertBefore(node.firstChild, node));
  2326. }
  2327. // remove this node from the document altogether
  2328. parent.removeChild(node);
  2329. // call sanitizeSvg on each of those children
  2330. var i = children.length;
  2331. while (i--) { sanitizeSvg(children[i]); }
  2332. }
  2333. };
  2334. // Function: getUrlFromAttr
  2335. // Extracts the URL from the url(...) syntax of some attributes.
  2336. // Three variants:
  2337. // * <circle fill="url(someFile.svg#foo)" />
  2338. // * <circle fill="url('someFile.svg#foo')" />
  2339. // * <circle fill='url("someFile.svg#foo")' />
  2340. //
  2341. // Parameters:
  2342. // attrVal - The attribute value as a string
  2343. //
  2344. // Returns:
  2345. // String with just the URL, like someFile.svg#foo
  2346. var getUrlFromAttr = this.getUrlFromAttr = function(attrVal) {
  2347. if (attrVal) {
  2348. // url("#somegrad")
  2349. if (attrVal.indexOf('url("') == 0) {
  2350. return attrVal.substring(5,attrVal.indexOf('"',6));
  2351. }
  2352. // url('#somegrad')
  2353. else if (attrVal.indexOf("url('") == 0) {
  2354. return attrVal.substring(5,attrVal.indexOf("'",6));
  2355. }
  2356. else if (attrVal.indexOf("url(") == 0) {
  2357. return attrVal.substring(4,attrVal.indexOf(')'));
  2358. }
  2359. }
  2360. return null;
  2361. };
  2362. // Function: getBBox
  2363. // Get the given/selected element's bounding box object, convert it to be more
  2364. // usable when necessary
  2365. //
  2366. // Parameters:
  2367. // elem - Optional DOM element to get the BBox for
  2368. var getBBox = this.getBBox = function(elem) {
  2369. var selected = elem || selectedElements[0];
  2370. if (elem.nodeType != 1) return null;
  2371. var ret = null;
  2372. var elname = selected.nodeName;
  2373. if(elname === 'text' && selected.textContent === '') {
  2374. selected.textContent = 'a'; // Some character needed for the selector to use.
  2375. ret = selected.getBBox();
  2376. selected.textContent = '';
  2377. } else if(elname === 'path' && isWebkit) {
  2378. ret = getPathBBox(selected);
  2379. } else if(elname === 'use' && !isWebkit || elname === 'foreignObject') {
  2380. ret = selected.getBBox();
  2381. var bb = {};
  2382. bb.width = ret.width;
  2383. bb.height = ret.height;
  2384. bb.x = ret.x + parseFloat(selected.getAttribute('x')||0);
  2385. bb.y = ret.y + parseFloat(selected.getAttribute('y')||0);
  2386. ret = bb;
  2387. } else if(~visElems_arr.indexOf(elname)) {
  2388. try { ret = selected.getBBox();}
  2389. catch(e) {
  2390. // Check if element is child of a foreignObject
  2391. var fo = $(selected).closest("foreignObject");
  2392. if(fo.length) {
  2393. try {
  2394. ret = fo[0].getBBox();
  2395. } catch(e) {
  2396. ret = null;
  2397. }
  2398. } else {
  2399. ret = null;
  2400. }
  2401. }
  2402. }
  2403. // get the bounding box from the DOM (which is in that element's coordinate system)
  2404. return ret;
  2405. };
  2406. // Function: ffClone
  2407. // Hack for Firefox bugs where text element features aren't updated.
  2408. // This function clones the element and re-selects it
  2409. // TODO: Test for this bug on load and add it to "support" object instead of
  2410. // browser sniffing
  2411. //
  2412. // Parameters:
  2413. // elem - The (text) DOM element to clone
  2414. var ffClone = function(elem) {
  2415. if(isGecko) return elem;
  2416. var clone = elem.cloneNode(true)
  2417. elem.parentNode.insertBefore(clone, elem);
  2418. elem.parentNode.removeChild(elem);
  2419. selectorManager.releaseSelector(elem);
  2420. selectedElements[0] = clone;
  2421. selectorManager.requestSelector(clone).showGrips(true);
  2422. return clone;
  2423. }
  2424. // Function: getPathBBox
  2425. // Get correct BBox for a path in Webkit
  2426. // Converted from code found here:
  2427. // http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
  2428. //
  2429. // Parameters:
  2430. // path - The path DOM element to get the BBox for
  2431. //
  2432. // Returns:
  2433. // A BBox-like object
  2434. var getPathBBox = function(path) {
  2435. var seglist = path.pathSegList;
  2436. var tot = seglist.numberOfItems;
  2437. var bounds = [[], []];
  2438. var start = seglist.getItem(0);
  2439. var P0 = [start.x, start.y];
  2440. for(var i=0; i < tot; i++) {
  2441. var seg = seglist.getItem(i);
  2442. if(!seg.x) continue;
  2443. // Add actual points to limits
  2444. bounds[0].push(P0[0]);
  2445. bounds[1].push(P0[1]);
  2446. if(seg.x1) {
  2447. var P1 = [seg.x1, seg.y1],
  2448. P2 = [seg.x2, seg.y2],
  2449. P3 = [seg.x, seg.y];
  2450. for(var j=0; j < 2; j++) {
  2451. var calc = function(t) {
  2452. return Math.pow(1-t,3) * P0[j]
  2453. + 3 * Math.pow(1-t,2) * t * P1[j]
  2454. + 3 * (1-t) * Math.pow(t,2) * P2[j]
  2455. + Math.pow(t,3) * P3[j];
  2456. };
  2457. var b = 6 * P0[j] - 12 * P1[j] + 6 * P2[j];
  2458. var a = -3 * P0[j] + 9 * P1[j] - 9 * P2[j] + 3 * P3[j];
  2459. var c = 3 * P1[j] - 3 * P0[j];
  2460. if(a == 0) {
  2461. if(b == 0) {
  2462. continue;
  2463. }
  2464. var t = -c / b;
  2465. if(0 < t && t < 1) {
  2466. bounds[j].push(calc(t));
  2467. }
  2468. continue;
  2469. }
  2470. var b2ac = Math.pow(b,2) - 4 * c * a;
  2471. if(b2ac < 0) continue;
  2472. var t1 = (-b + Math.sqrt(b2ac))/(2 * a);
  2473. if(0 < t1 && t1 < 1) bounds[j].push(calc(t1));
  2474. var t2 = (-b - Math.sqrt(b2ac))/(2 * a);
  2475. if(0 < t2 && t2 < 1) bounds[j].push(calc(t2));
  2476. }
  2477. P0 = P3;
  2478. } else {
  2479. bounds[0].push(seg.x);
  2480. bounds[1].push(seg.y);
  2481. }
  2482. }
  2483. var x = Math.min.apply(null, bounds[0]);
  2484. var w = Math.max.apply(null, bounds[0]) - x;
  2485. var y = Math.min.apply(null, bounds[1]);
  2486. var h = Math.max.apply(null, bounds[1]) - y;
  2487. return {
  2488. 'x': x,
  2489. 'y': y,
  2490. 'width': w,
  2491. 'height': h
  2492. };
  2493. }
  2494. // this.each is deprecated, if any extension used this it can be recreated by doing this:
  2495. // $(canvas.getRootElem()).children().each(...)
  2496. // this.each = function(cb) {
  2497. // $(svgroot).children().each(cb);
  2498. // };
  2499. // Group: Element Transforms
  2500. // Function: getRotationAngle
  2501. // Get the rotation angle of the given/selected DOM element
  2502. //
  2503. // Parameters:
  2504. // elem - Optional DOM element to get the angle for
  2505. // to_rad - Boolean that when true returns the value in radians rather than degrees
  2506. //
  2507. // Returns:
  2508. // Float with the angle in degrees or radians
  2509. var getRotationAngle = this.getRotationAngle = function(elem, to_rad) {
  2510. var selected = elem || selectedElements[0];
  2511. // find the rotation transform (if any) and set it
  2512. var tlist = getTransformList(selected);
  2513. if(!tlist) return 0; // <svg> elements have no tlist
  2514. var N = tlist.numberOfItems;
  2515. for (var i = 0; i < N; ++i) {
  2516. var xform = tlist.getItem(i);
  2517. if (xform.type == 4) {
  2518. return to_rad ? xform.angle * Math.PI / 180.0 : xform.angle;
  2519. }
  2520. }
  2521. return 0.0;
  2522. };
  2523. // Function: setRotationAngle
  2524. // Removes any old rotations if present, prepends a new rotation at the
  2525. // transformed center
  2526. //
  2527. // Parameters:
  2528. // val - The new rotation angle in degrees
  2529. // preventUndo - Boolean indicating whether the action should be undoable or not
  2530. this.setRotationAngle = function(val, preventUndo) {
  2531. // ensure val is the proper type
  2532. val = parseFloat(val);
  2533. var elem = selectedElements[0];
  2534. var oldTransform = elem.getAttribute("transform");
  2535. var bbox = getBBox(elem);
  2536. var cx = bbox.x+bbox.width/2, cy = bbox.y+bbox.height/2;
  2537. var tlist = getTransformList(elem);
  2538. // only remove the real rotational transform if present (i.e. at index=0)
  2539. if (tlist.numberOfItems > 0) {
  2540. var xform = tlist.getItem(0);
  2541. if (xform.type == 4) {
  2542. tlist.removeItem(0);
  2543. }
  2544. }
  2545. // find R_nc and insert it
  2546. if (val != 0) {
  2547. var center = transformPoint(cx,cy,transformListToTransform(tlist).matrix);
  2548. var R_nc = svgroot.createSVGTransform();
  2549. R_nc.setRotate(val, center.x, center.y);
  2550. if(tlist.numberOfItems) {
  2551. tlist.insertItemBefore(R_nc, 0);
  2552. } else {
  2553. tlist.appendItem(R_nc);
  2554. }
  2555. }
  2556. else if (tlist.numberOfItems == 0) {
  2557. elem.removeAttribute("transform");
  2558. }
  2559. if (!preventUndo) {
  2560. // we need to undo it, then redo it so it can be undo-able! :)
  2561. // TODO: figure out how to make changes to transform list undo-able cross-browser?
  2562. var newTransform = elem.getAttribute("transform");
  2563. elem.setAttribute("transform", oldTransform);
  2564. changeSelectedAttribute("transform",newTransform,selectedElements);
  2565. }
  2566. var pointGripContainer = getElem("pathpointgrip_container");
  2567. // if(elem.nodeName == "path" && pointGripContainer) {
  2568. // pathActions.setPointContainerTransform(elem.getAttribute("transform"));
  2569. // }
  2570. var selector = selectorManager.requestSelector(selectedElements[0]);
  2571. selector.resize();
  2572. selector.updateGripCursors(val);
  2573. };
  2574. // Function: getTransformList
  2575. // Returns an object that behaves like a SVGTransformList for the given DOM element
  2576. //
  2577. // Parameters:
  2578. // elem - DOM element to get a transformlist from
  2579. var getTransformList = this.getTransformList = function(elem) {
  2580. if (isWebkit) {
  2581. var id = elem.id;
  2582. if(!id) {
  2583. // Get unique ID for temporary element
  2584. id = 'temp';
  2585. }
  2586. var t = svgTransformLists[id];
  2587. if (!t || id == 'temp') {
  2588. svgTransformLists[id] = new SVGEditTransformList(elem);
  2589. svgTransformLists[id]._init();
  2590. t = svgTransformLists[id];
  2591. }
  2592. return t;
  2593. }
  2594. else if (elem.transform) {
  2595. return elem.transform.baseVal;
  2596. }
  2597. else if (elem.gradientTransform) {
  2598. return elem.gradientTransform.baseVal;
  2599. }
  2600. return null;
  2601. };
  2602. // Function: recalculateAllSelectedDimensions
  2603. // Runs recalculateDimensions on the selected elements,
  2604. // adding the changes to a single batch command
  2605. var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function() {
  2606. var text = (current_resize_mode == "none" ? "position" : "size");
  2607. var batchCmd = new BatchCommand(text);
  2608. var i = selectedElements.length;
  2609. while(i--) {
  2610. var elem = selectedElements[i];
  2611. // if(getRotationAngle(elem) && !hasMatrixTransform(getTransformList(elem))) continue;
  2612. var cmd = recalculateDimensions(elem);
  2613. if (cmd) {
  2614. batchCmd.addSubCommand(cmd);
  2615. }
  2616. }
  2617. if (!batchCmd.isEmpty()) {
  2618. addCommandToHistory(batchCmd);
  2619. call("changed", selectedElements);
  2620. }
  2621. };
  2622. // this is how we map paths to our preferred relative segment types
  2623. var pathMap = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a',
  2624. 'H', 'h', 'V', 'v', 'S', 's', 'T', 't'];
  2625. // Debug tool to easily see the current matrix in the browser's console
  2626. var logMatrix = function(m) {
  2627. console.log([m.a,m.b,m.c,m.d,m.e,m.f]);
  2628. };
  2629. // Function: remapElement
  2630. // Applies coordinate changes to an element based on the given matrix
  2631. //
  2632. // Parameters:
  2633. // selected - DOM element to be changed
  2634. // changes - Object with changes to be remapped
  2635. // m - Matrix object to use for remapping coordinates
  2636. var remapElement = this.remapElement = function(selected,changes,m) {
  2637. var remap = function(x,y) { return transformPoint(x,y,m); },
  2638. scalew = function(w) { return m.a*w; },
  2639. scaleh = function(h) { return m.d*h; },
  2640. box = getBBox(selected);
  2641. switch (selected.tagName)
  2642. {
  2643. case "line":
  2644. var pt1 = remap(changes["x1"],changes["y1"]),
  2645. pt2 = remap(changes["x2"],changes["y2"]);
  2646. changes["x1"] = pt1.x;
  2647. changes["y1"] = pt1.y;
  2648. changes["x2"] = pt2.x;
  2649. changes["y2"] = pt2.y;
  2650. break;
  2651. case "circle":
  2652. var c = remap(changes["cx"],changes["cy"]);
  2653. changes["cx"] = c.x;
  2654. changes["cy"] = c.y;
  2655. // take the minimum of the new selected box's dimensions for the new circle radius
  2656. var tbox = transformBox(box.x, box.y, box.width, box.height, m);
  2657. var w = tbox.tr.x - tbox.tl.x, h = tbox.bl.y - tbox.tl.y;
  2658. changes["r"] = Math.min(w/2, h/2);
  2659. break;
  2660. case "ellipse":
  2661. var c = remap(changes["cx"],changes["cy"]);
  2662. changes["cx"] = c.x;
  2663. changes["cy"] = c.y;
  2664. changes["rx"] = scalew(changes["rx"]);
  2665. changes["ry"] = scaleh(changes["ry"]);
  2666. break;
  2667. case "foreignObject":
  2668. case "rect":
  2669. case "image":
  2670. var pt1 = remap(changes["x"],changes["y"]);
  2671. changes["x"] = pt1.x;
  2672. changes["y"] = pt1.y;
  2673. changes["width"] = scalew(changes["width"]);
  2674. changes["height"] = scaleh(changes["height"]);
  2675. break;
  2676. case "use":
  2677. // var pt1 = remap(changes["x"],changes["y"]);
  2678. // changes["x"] = pt1.x;
  2679. // changes["y"] = pt1.y;
  2680. // break;
  2681. case "g":
  2682. case "text":
  2683. // if it was a translate, then just update x,y
  2684. if (m.a == 1 && m.b == 0 && m.c == 0 && m.d == 1 &&
  2685. (m.e != 0 || m.f != 0) )
  2686. {
  2687. // [T][M] = [M][T']
  2688. // therefore [T'] = [M_inv][T][M]
  2689. var existing = transformListToTransform(selected).matrix,
  2690. t_new = matrixMultiply(existing.inverse(), m, existing);
  2691. changes["x"] = parseFloat(changes["x"]) + t_new.e;
  2692. changes["y"] = parseFloat(changes["y"]) + t_new.f;
  2693. }
  2694. else {
  2695. // we just absorb all matrices into the element and don't do any remapping
  2696. var chlist = getTransformList(selected);
  2697. var mt = svgroot.createSVGTransform();
  2698. mt.setMatrix(matrixMultiply(transformListToTransform(chlist).matrix,m));
  2699. chlist.clear();
  2700. chlist.appendItem(mt);
  2701. }
  2702. break;
  2703. case "polygon":
  2704. case "polyline":
  2705. var len = changes["points"].length;
  2706. for (var i = 0; i < len; ++i) {
  2707. var pt = changes["points"][i];
  2708. pt = remap(pt.x,pt.y);
  2709. changes["points"][i].x = pt.x;
  2710. changes["points"][i].y = pt.y;
  2711. }
  2712. break;
  2713. case "path":
  2714. var segList = selected.pathSegList;
  2715. var len = segList.numberOfItems;
  2716. changes.d = new Array(len);
  2717. for (var i = 0; i < len; ++i) {
  2718. var seg = segList.getItem(i);
  2719. changes.d[i] = {
  2720. type: seg.pathSegType,
  2721. x: seg.x,
  2722. y: seg.y,
  2723. x1: seg.x1,
  2724. y1: seg.y1,
  2725. x2: seg.x2,
  2726. y2: seg.y2,
  2727. r1: seg.r1,
  2728. r2: seg.r2,
  2729. angle: seg.angle,
  2730. largeArcFlag: seg.largeArcFlag,
  2731. sweepFlag: seg.sweepFlag
  2732. };
  2733. }
  2734. var len = changes["d"].length,
  2735. firstseg = changes["d"][0],
  2736. currentpt = remap(firstseg.x,firstseg.y);
  2737. changes["d"][0].x = currentpt.x;
  2738. changes["d"][0].y = currentpt.y;
  2739. for (var i = 1; i < len; ++i) {
  2740. var seg = changes["d"][i];
  2741. var type = seg.type;
  2742. // if absolute or first segment, we want to remap x, y, x1, y1, x2, y2
  2743. // if relative, we want to scalew, scaleh
  2744. if (type % 2 == 0) { // absolute
  2745. var thisx = (seg.x != undefined) ? seg.x : currentpt.x, // for V commands
  2746. thisy = (seg.y != undefined) ? seg.y : currentpt.y, // for H commands
  2747. pt = remap(thisx,thisy),
  2748. pt1 = remap(seg.x1,seg.y1),
  2749. pt2 = remap(seg.x2,seg.y2);
  2750. seg.x = pt.x;
  2751. seg.y = pt.y;
  2752. seg.x1 = pt1.x;
  2753. seg.y1 = pt1.y;
  2754. seg.x2 = pt2.x;
  2755. seg.y2 = pt2.y;
  2756. seg.r1 = scalew(seg.r1),
  2757. seg.r2 = scaleh(seg.r2);
  2758. }
  2759. else { // relative
  2760. seg.x = scalew(seg.x);
  2761. seg.y = scaleh(seg.y);
  2762. seg.x1 = scalew(seg.x1);
  2763. seg.y1 = scaleh(seg.y1);
  2764. seg.x2 = scalew(seg.x2);
  2765. seg.y2 = scaleh(seg.y2);
  2766. seg.r1 = scalew(seg.r1),
  2767. seg.r2 = scaleh(seg.r2);
  2768. }
  2769. // tracks the current position (for H,V commands)
  2770. if (seg.x) currentpt.x = seg.x;
  2771. if (seg.y) currentpt.y = seg.y;
  2772. } // for each segment
  2773. break;
  2774. } // switch on element type to get initial values
  2775. // now we have a set of changes and an applied reduced transform list
  2776. // we apply the changes directly to the DOM
  2777. // TODO: merge this switch with the above one and optimize
  2778. switch (selected.tagName)
  2779. {
  2780. case "foreignObject":
  2781. case "rect":
  2782. case "image":
  2783. changes.x = changes.x-0 + Math.min(0,changes.width);
  2784. changes.y = changes.y-0 + Math.min(0,changes.height);
  2785. changes.width = Math.abs(changes.width);
  2786. changes.height = Math.abs(changes.height);
  2787. if(curConfig.gridSnapping && selected.parentNode.parentNode.localName == "svg"){
  2788. changes.x = snapToGrid(changes.x);
  2789. changes.y = snapToGrid(changes.y);
  2790. changes.width = snapToGrid(changes.width);
  2791. changes.height = snapToGrid(changes.height);
  2792. }
  2793. assignAttributes(selected, changes, 1000, true);
  2794. break;
  2795. case "ellipse":
  2796. changes.rx = Math.abs(changes.rx);
  2797. changes.ry = Math.abs(changes.ry);
  2798. if(curConfig.gridSnapping && selected.parentNode.parentNode.localName == "svg"){
  2799. changes.cx = snapToGrid(changes.cx);
  2800. changes.cy = snapToGrid(changes.cy);
  2801. changes.rx = snapToGrid(changes.rx);
  2802. changes.ry = snapToGrid(changes.ry);
  2803. }
  2804. case "circle":
  2805. if(changes.r) changes.r = Math.abs(changes.r);
  2806. if(curConfig.gridSnapping && selected.parentNode.parentNode.localName == "svg"){
  2807. changes.cx = snapToGrid(changes.cx);
  2808. changes.cy = snapToGrid(changes.cy);
  2809. changes.r = snapToGrid(changes.r);
  2810. }
  2811. case "line":
  2812. if(curConfig.gridSnapping && selected.parentNode.parentNode.localName == "svg"){
  2813. changes.x1 = snapToGrid(changes.x1);
  2814. changes.y1 = snapToGrid(changes.y1);
  2815. changes.x2 = snapToGrid(changes.x2);
  2816. changes.y2 = snapToGrid(changes.y2);
  2817. }
  2818. case "text":
  2819. if(curConfig.gridSnapping && selected.parentNode.parentNode.localName == "svg"){
  2820. changes.x = snapToGrid(changes.x);
  2821. changes.y = snapToGrid(changes.y);
  2822. }
  2823. case "use":
  2824. assignAttributes(selected, changes, 1000, true);
  2825. break;
  2826. case "g":
  2827. var gsvg = $(selected).data('gsvg');
  2828. if(gsvg) {
  2829. assignAttributes(gsvg, changes, 1000, true);
  2830. }
  2831. break;
  2832. case "polyline":
  2833. case "polygon":
  2834. var len = changes["points"].length;
  2835. var pstr = "";
  2836. for (var i = 0; i < len; ++i) {
  2837. var pt = changes["points"][i];
  2838. pstr += pt.x + "," + pt.y + " ";
  2839. }
  2840. selected.setAttribute("points", pstr);
  2841. break;
  2842. case "path":
  2843. var dstr = "";
  2844. var len = changes["d"].length;
  2845. for (var i = 0; i < len; ++i) {
  2846. var seg = changes["d"][i];
  2847. var type = seg.type;
  2848. dstr += pathMap[type];
  2849. switch(type) {
  2850. case 13: // relative horizontal line (h)
  2851. case 12: // absolute horizontal line (H)
  2852. dstr += seg.x + " ";
  2853. break;
  2854. case 15: // relative vertical line (v)
  2855. case 14: // absolute vertical line (V)
  2856. dstr += seg.y + " ";
  2857. break;
  2858. case 3: // relative move (m)
  2859. case 5: // relative line (l)
  2860. case 19: // relative smooth quad (t)
  2861. case 2: // absolute move (M)
  2862. case 4: // absolute line (L)
  2863. case 18: // absolute smooth quad (T)
  2864. dstr += seg.x + "," + seg.y + " ";
  2865. break;
  2866. case 7: // relative cubic (c)
  2867. case 6: // absolute cubic (C)
  2868. dstr += seg.x1 + "," + seg.y1 + " " + seg.x2 + "," + seg.y2 + " " +
  2869. seg.x + "," + seg.y + " ";
  2870. break;
  2871. case 9: // relative quad (q)
  2872. case 8: // absolute quad (Q)
  2873. dstr += seg.x1 + "," + seg.y1 + " " + seg.x + "," + seg.y + " ";
  2874. break;
  2875. case 11: // relative elliptical arc (a)
  2876. case 10: // absolute elliptical arc (A)
  2877. dstr += seg.r1 + "," + seg.r2 + " " + seg.angle + " " + Number(seg.largeArcFlag) +
  2878. " " + Number(seg.sweepFlag) + " " + seg.x + "," + seg.y + " ";
  2879. break;
  2880. case 17: // relative smooth cubic (s)
  2881. case 16: // absolute smooth cubic (S)
  2882. dstr += seg.x2 + "," + seg.y2 + " " + seg.x + "," + seg.y + " ";
  2883. break;
  2884. }
  2885. }
  2886. selected.setAttribute("d", dstr);
  2887. break;
  2888. }
  2889. };
  2890. // Function: updateClipPath
  2891. // Updates a <clipPath>s values based on the given translation of an element
  2892. //
  2893. // Parameters:
  2894. // attr - The clip-path attribute value with the clipPath's ID
  2895. // tx - The translation's x value
  2896. // ty - The translation's y value
  2897. var updateClipPath = function(attr, tx, ty) {
  2898. var id = getUrlFromAttr(attr).substr(1);
  2899. var path = getElem(id).firstChild;
  2900. var cp_xform = getTransformList(path);
  2901. var newxlate = svgroot.createSVGTransform();
  2902. newxlate.setTranslate(tx, ty);
  2903. cp_xform.appendItem(newxlate);
  2904. // Update clipPath's dimensions
  2905. recalculateDimensions(path);
  2906. }
  2907. // Function: recalculateDimensions
  2908. // Decides the course of action based on the element's transform list
  2909. //
  2910. // Parameters:
  2911. // selected - The DOM element to recalculate
  2912. //
  2913. // Returns:
  2914. // Undo command object with the resulting change
  2915. var recalculateDimensions = this.recalculateDimensions = function(selected) {
  2916. if (selected == null) return null;
  2917. var tlist = getTransformList(selected);
  2918. // remove any unnecessary transforms
  2919. if (tlist && tlist.numberOfItems > 0) {
  2920. var k = tlist.numberOfItems;
  2921. while (k--) {
  2922. var xform = tlist.getItem(k);
  2923. if (xform.type === 0) {
  2924. tlist.removeItem(k);
  2925. }
  2926. // remove identity matrices
  2927. else if (xform.type === 1) {
  2928. if (isIdentity(xform.matrix)) {
  2929. tlist.removeItem(k);
  2930. }
  2931. }
  2932. // remove zero-degree rotations
  2933. else if (xform.type === 4) {
  2934. if (xform.angle === 0) {
  2935. tlist.removeItem(k);
  2936. }
  2937. }
  2938. }
  2939. // End here if all it has is a rotation
  2940. if(tlist.numberOfItems === 1 && getRotationAngle(selected)) return null;
  2941. }
  2942. // if this element had no transforms, we are done
  2943. if (!tlist || tlist.numberOfItems == 0) {
  2944. selected.removeAttribute("transform");
  2945. return null;
  2946. }
  2947. // TODO: Make this work for more than 2
  2948. if (tlist) {
  2949. var k = tlist.numberOfItems;
  2950. var mxs = [];
  2951. while (k--) {
  2952. var xform = tlist.getItem(k);
  2953. if (xform.type === 1) {
  2954. mxs.push([xform.matrix, k]);
  2955. } else if(mxs.length) {
  2956. mxs = [];
  2957. }
  2958. }
  2959. if(mxs.length === 2) {
  2960. var m_new = svgroot.createSVGTransformFromMatrix(matrixMultiply(mxs[1][0], mxs[0][0]));
  2961. tlist.removeItem(mxs[0][1]);
  2962. tlist.removeItem(mxs[1][1]);
  2963. tlist.insertItemBefore(m_new, mxs[1][1]);
  2964. }
  2965. // combine matrix + translate
  2966. k = tlist.numberOfItems;
  2967. if(k === 2 && tlist.getItem(0).type === 1 && tlist.getItem(1).type === 2) {
  2968. var mt = svgroot.createSVGTransform();
  2969. logMatrix(tlist.getItem(0).matrix);
  2970. logMatrix(transformListToTransform(tlist).matrix);
  2971. mt.setMatrix(transformListToTransform(tlist).matrix);
  2972. tlist.clear();
  2973. tlist.appendItem(mt);
  2974. }
  2975. }
  2976. // Grouped SVG element
  2977. var gsvg = $(selected).data('gsvg');
  2978. // we know we have some transforms, so set up return variable
  2979. var batchCmd = new BatchCommand("Transform");
  2980. // store initial values that will be affected by reducing the transform list
  2981. var changes = {}, initial = null, attrs = [];
  2982. switch (selected.tagName)
  2983. {
  2984. case "line":
  2985. attrs = ["x1", "y1", "x2", "y2"];
  2986. break;
  2987. case "circle":
  2988. attrs = ["cx", "cy", "r"];
  2989. break;
  2990. case "ellipse":
  2991. attrs = ["cx", "cy", "rx", "ry"];
  2992. break;
  2993. case "foreignObject":
  2994. case "rect":
  2995. case "image":
  2996. attrs = ["width", "height", "x", "y"];
  2997. break;
  2998. case "use":
  2999. case "text":
  3000. attrs = ["x", "y"];
  3001. break;
  3002. case "polygon":
  3003. case "polyline":
  3004. initial = {};
  3005. initial["points"] = selected.getAttribute("points");
  3006. var list = selected.points;
  3007. var len = list.numberOfItems;
  3008. changes["points"] = new Array(len);
  3009. for (var i = 0; i < len; ++i) {
  3010. var pt = list.getItem(i);
  3011. changes["points"][i] = {x:pt.x,y:pt.y};
  3012. }
  3013. break;
  3014. case "path":
  3015. initial = {};
  3016. initial["d"] = selected.getAttribute("d");
  3017. changes["d"] = selected.getAttribute("d");
  3018. break;
  3019. } // switch on element type to get initial values
  3020. if(attrs.length) {
  3021. changes = $(selected).attr(attrs);
  3022. $.each(changes, function(attr, val) {
  3023. changes[attr] = convertToNum(attr, val);
  3024. });
  3025. } else if(gsvg) {
  3026. // GSVG exception
  3027. changes = {
  3028. x: $(gsvg).attr('x') || 0,
  3029. y: $(gsvg).attr('y') || 0
  3030. };
  3031. }
  3032. // if we haven't created an initial array in polygon/polyline/path, then
  3033. // make a copy of initial values and include the transform
  3034. if (initial == null) {
  3035. initial = $.extend(true, {}, changes);
  3036. $.each(initial, function(attr, val) {
  3037. initial[attr] = convertToNum(attr, val);
  3038. });
  3039. }
  3040. // save the start transform value too
  3041. initial["transform"] = start_transform ? start_transform : "";
  3042. // if it's a regular group, we have special processing to flatten transforms
  3043. if ((selected.tagName == "g" && !gsvg) || selected.tagName == "a") {
  3044. var box = getBBox(selected),
  3045. oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
  3046. newcenter = transformPoint(box.x+box.width/2, box.y+box.height/2,
  3047. transformListToTransform(tlist).matrix),
  3048. m = svgroot.createSVGMatrix();
  3049. // temporarily strip off the rotate and save the old center
  3050. var gangle = getRotationAngle(selected);
  3051. if (gangle) {
  3052. var a = gangle * Math.PI / 180;
  3053. if ( Math.abs(a) > (1.0e-10) ) {
  3054. var s = Math.sin(a)/(1 - Math.cos(a));
  3055. } else {
  3056. // FIXME: This blows up if the angle is exactly 0!
  3057. var s = 2/a;
  3058. }
  3059. for (var i = 0; i < tlist.numberOfItems; ++i) {
  3060. var xform = tlist.getItem(i);
  3061. if (xform.type == 4) {
  3062. // extract old center through mystical arts
  3063. var rm = xform.matrix;
  3064. oldcenter.y = (s*rm.e + rm.f)/2;
  3065. oldcenter.x = (rm.e - s*rm.f)/2;
  3066. tlist.removeItem(i);
  3067. break;
  3068. }
  3069. }
  3070. }
  3071. var tx = 0, ty = 0,
  3072. operation = 0,
  3073. N = tlist.numberOfItems;
  3074. if(N) {
  3075. var first_m = tlist.getItem(0).matrix;
  3076. }
  3077. // first, if it was a scale then the second-last transform will be it
  3078. if (N >= 3 && tlist.getItem(N-2).type == 3 &&
  3079. tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2)
  3080. {
  3081. operation = 3; // scale
  3082. // if the children are unrotated, pass the scale down directly
  3083. // otherwise pass the equivalent matrix() down directly
  3084. var tm = tlist.getItem(N-3).matrix,
  3085. sm = tlist.getItem(N-2).matrix,
  3086. tmn = tlist.getItem(N-1).matrix;
  3087. var children = selected.childNodes;
  3088. var c = children.length;
  3089. while (c--) {
  3090. var child = children.item(c);
  3091. tx = 0;
  3092. ty = 0;
  3093. if (child.nodeType == 1) {
  3094. var childTlist = getTransformList(child);
  3095. // some children might not have a transform (<metadata>, <defs>, etc)
  3096. if (!childTlist) continue;
  3097. var m = transformListToTransform(childTlist).matrix;
  3098. // Convert a matrix to a scale if applicable
  3099. // if(hasMatrixTransform(childTlist) && childTlist.numberOfItems == 1) {
  3100. // if(m.b==0 && m.c==0 && m.e==0 && m.f==0) {
  3101. // childTlist.removeItem(0);
  3102. // var translateOrigin = svgroot.createSVGTransform(),
  3103. // scale = svgroot.createSVGTransform(),
  3104. // translateBack = svgroot.createSVGTransform();
  3105. // translateOrigin.setTranslate(0, 0);
  3106. // scale.setScale(m.a, m.d);
  3107. // translateBack.setTranslate(0, 0);
  3108. // childTlist.appendItem(translateBack);
  3109. // childTlist.appendItem(scale);
  3110. // childTlist.appendItem(translateOrigin);
  3111. // }
  3112. // }
  3113. var angle = getRotationAngle(child);
  3114. var old_start_transform = start_transform;
  3115. var childxforms = [];
  3116. start_transform = child.getAttribute("transform");
  3117. if(angle || hasMatrixTransform(childTlist)) {
  3118. var e2t = svgroot.createSVGTransform();
  3119. e2t.setMatrix(matrixMultiply(tm, sm, tmn, m));
  3120. childTlist.clear();
  3121. childTlist.appendItem(e2t);
  3122. childxforms.push(e2t);
  3123. }
  3124. // if not rotated or skewed, push the [T][S][-T] down to the child
  3125. else {
  3126. // update the transform list with translate,scale,translate
  3127. // slide the [T][S][-T] from the front to the back
  3128. // [T][S][-T][M] = [M][T2][S2][-T2]
  3129. // (only bringing [-T] to the right of [M])
  3130. // [T][S][-T][M] = [T][S][M][-T2]
  3131. // [-T2] = [M_inv][-T][M]
  3132. var t2n = matrixMultiply(m.inverse(), tmn, m);
  3133. // [T2] is always negative translation of [-T2]
  3134. var t2 = svgroot.createSVGMatrix();
  3135. t2.e = -t2n.e;
  3136. t2.f = -t2n.f;
  3137. // [T][S][-T][M] = [M][T2][S2][-T2]
  3138. // [S2] = [T2_inv][M_inv][T][S][-T][M][-T2_inv]
  3139. var s2 = matrixMultiply(t2.inverse(), m.inverse(), tm, sm, tmn, m, t2n.inverse());
  3140. var translateOrigin = svgroot.createSVGTransform(),
  3141. scale = svgroot.createSVGTransform(),
  3142. translateBack = svgroot.createSVGTransform();
  3143. translateOrigin.setTranslate(t2n.e, t2n.f);
  3144. scale.setScale(s2.a, s2.d);
  3145. translateBack.setTranslate(t2.e, t2.f);
  3146. childTlist.appendItem(translateBack);
  3147. childTlist.appendItem(scale);
  3148. childTlist.appendItem(translateOrigin);
  3149. childxforms.push(translateBack);
  3150. childxforms.push(scale);
  3151. childxforms.push(translateOrigin);
  3152. logMatrix(translateBack.matrix);
  3153. logMatrix(scale.matrix);
  3154. } // not rotated
  3155. batchCmd.addSubCommand( recalculateDimensions(child) );
  3156. // TODO: If any <use> have this group as a parent and are
  3157. // referencing this child, then we need to impose a reverse
  3158. // scale on it so that when it won't get double-translated
  3159. // var uses = selected.getElementsByTagNameNS(svgns, "use");
  3160. // var href = "#"+child.id;
  3161. // var u = uses.length;
  3162. // while (u--) {
  3163. // var useElem = uses.item(u);
  3164. // if(href == getHref(useElem)) {
  3165. // var usexlate = svgroot.createSVGTransform();
  3166. // usexlate.setTranslate(-tx,-ty);
  3167. // getTransformList(useElem).insertItemBefore(usexlate,0);
  3168. // batchCmd.addSubCommand( recalculateDimensions(useElem) );
  3169. // }
  3170. // }
  3171. start_transform = old_start_transform;
  3172. } // element
  3173. } // for each child
  3174. // Remove these transforms from group
  3175. tlist.removeItem(N-1);
  3176. tlist.removeItem(N-2);
  3177. tlist.removeItem(N-3);
  3178. }
  3179. else if (N >= 3 && tlist.getItem(N-1).type == 1)
  3180. {
  3181. operation = 3; // scale
  3182. m = transformListToTransform(tlist).matrix;
  3183. var e2t = svgroot.createSVGTransform();
  3184. e2t.setMatrix(m);
  3185. tlist.clear();
  3186. tlist.appendItem(e2t);
  3187. }
  3188. // next, check if the first transform was a translate
  3189. // if we had [ T1 ] [ M ] we want to transform this into [ M ] [ T2 ]
  3190. // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ]
  3191. else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
  3192. tlist.getItem(0).type == 2)
  3193. {
  3194. operation = 2; // translate
  3195. var T_M = transformListToTransform(tlist).matrix;
  3196. tlist.removeItem(0);
  3197. var M_inv = transformListToTransform(tlist).matrix.inverse();
  3198. var M2 = matrixMultiply( M_inv, T_M );
  3199. tx = M2.e;
  3200. ty = M2.f;
  3201. if (tx != 0 || ty != 0) {
  3202. // we pass the translates down to the individual children
  3203. var children = selected.childNodes;
  3204. var c = children.length;
  3205. var clipPaths_done = [];
  3206. while (c--) {
  3207. var child = children.item(c);
  3208. if (child.nodeType == 1) {
  3209. // Check if child has clip-path
  3210. if(child.getAttribute('clip-path')) {
  3211. // tx, ty
  3212. var attr = child.getAttribute('clip-path');
  3213. if(clipPaths_done.indexOf(attr) === -1) {
  3214. updateClipPath(attr, tx, ty);
  3215. clipPaths_done.push(attr);
  3216. }
  3217. }
  3218. var old_start_transform = start_transform;
  3219. start_transform = child.getAttribute("transform");
  3220. var childTlist = getTransformList(child);
  3221. // some children might not have a transform (<metadata>, <defs>, etc)
  3222. if (childTlist) {
  3223. var newxlate = svgroot.createSVGTransform();
  3224. newxlate.setTranslate(tx,ty);
  3225. if(childTlist.numberOfItems) {
  3226. childTlist.insertItemBefore(newxlate, 0);
  3227. } else {
  3228. childTlist.appendItem(newxlate);
  3229. }
  3230. batchCmd.addSubCommand( recalculateDimensions(child) );
  3231. // If any <use> have this group as a parent and are
  3232. // referencing this child, then impose a reverse translate on it
  3233. // so that when it won't get double-translated
  3234. var uses = selected.getElementsByTagNameNS(svgns, "use");
  3235. var href = "#"+child.id;
  3236. var u = uses.length;
  3237. while (u--) {
  3238. var useElem = uses.item(u);
  3239. if(href == getHref(useElem)) {
  3240. var usexlate = svgroot.createSVGTransform();
  3241. usexlate.setTranslate(-tx,-ty);
  3242. getTransformList(useElem).insertItemBefore(usexlate,0);
  3243. batchCmd.addSubCommand( recalculateDimensions(useElem) );
  3244. }
  3245. }
  3246. start_transform = old_start_transform;
  3247. }
  3248. }
  3249. }
  3250. clipPaths_done = [];
  3251. start_transform = old_start_transform;
  3252. }
  3253. }
  3254. // else, a matrix imposition from a parent group
  3255. // keep pushing it down to the children
  3256. else if (N == 1 && tlist.getItem(0).type == 1 && !gangle) {
  3257. operation = 1;
  3258. var m = tlist.getItem(0).matrix,
  3259. children = selected.childNodes,
  3260. c = children.length;
  3261. while (c--) {
  3262. var child = children.item(c);
  3263. if (child.nodeType == 1) {
  3264. var old_start_transform = start_transform;
  3265. start_transform = child.getAttribute("transform");
  3266. var childTlist = getTransformList(child);
  3267. if (!childTlist) continue;
  3268. var em = matrixMultiply(m, transformListToTransform(childTlist).matrix);
  3269. var e2m = svgroot.createSVGTransform();
  3270. e2m.setMatrix(em);
  3271. childTlist.clear();
  3272. childTlist.appendItem(e2m,0);
  3273. batchCmd.addSubCommand( recalculateDimensions(child) );
  3274. start_transform = old_start_transform;
  3275. }
  3276. }
  3277. tlist.clear();
  3278. }
  3279. // else it was just a rotate
  3280. else {
  3281. if (gangle) {
  3282. var newRot = svgroot.createSVGTransform();
  3283. newRot.setRotate(gangle,newcenter.x,newcenter.y);
  3284. if(tlist.numberOfItems) {
  3285. tlist.insertItemBefore(newRot, 0);
  3286. } else {
  3287. tlist.appendItem(newRot);
  3288. }
  3289. }
  3290. if (tlist.numberOfItems == 0) {
  3291. selected.removeAttribute("transform");
  3292. }
  3293. return null;
  3294. }
  3295. // if it was a translate, put back the rotate at the new center
  3296. if (operation == 2) {
  3297. if (gangle) {
  3298. newcenter = {
  3299. x: oldcenter.x + first_m.e,
  3300. y: oldcenter.y + first_m.f
  3301. };
  3302. var newRot = svgroot.createSVGTransform();
  3303. newRot.setRotate(gangle,newcenter.x,newcenter.y);
  3304. if(tlist.numberOfItems) {
  3305. tlist.insertItemBefore(newRot, 0);
  3306. } else {
  3307. tlist.appendItem(newRot);
  3308. }
  3309. }
  3310. }
  3311. // if it was a resize
  3312. else if (operation == 3) {
  3313. var m = transformListToTransform(tlist).matrix;
  3314. var roldt = svgroot.createSVGTransform();
  3315. roldt.setRotate(gangle, oldcenter.x, oldcenter.y);
  3316. var rold = roldt.matrix;
  3317. var rnew = svgroot.createSVGTransform();
  3318. rnew.setRotate(gangle, newcenter.x, newcenter.y);
  3319. var rnew_inv = rnew.matrix.inverse(),
  3320. m_inv = m.inverse(),
  3321. extrat = matrixMultiply(m_inv, rnew_inv, rold, m);
  3322. tx = extrat.e;
  3323. ty = extrat.f;
  3324. if (tx != 0 || ty != 0) {
  3325. // now push this transform down to the children
  3326. // we pass the translates down to the individual children
  3327. var children = selected.childNodes;
  3328. var c = children.length;
  3329. while (c--) {
  3330. var child = children.item(c);
  3331. if (child.nodeType == 1) {
  3332. var old_start_transform = start_transform;
  3333. start_transform = child.getAttribute("transform");
  3334. var childTlist = getTransformList(child);
  3335. var newxlate = svgroot.createSVGTransform();
  3336. newxlate.setTranslate(tx,ty);
  3337. if(childTlist.numberOfItems) {
  3338. childTlist.insertItemBefore(newxlate, 0);
  3339. } else {
  3340. childTlist.appendItem(newxlate);
  3341. }
  3342. batchCmd.addSubCommand( recalculateDimensions(child) );
  3343. start_transform = old_start_transform;
  3344. }
  3345. }
  3346. }
  3347. if (gangle) {
  3348. if(tlist.numberOfItems) {
  3349. tlist.insertItemBefore(rnew, 0);
  3350. } else {
  3351. tlist.appendItem(rnew);
  3352. }
  3353. }
  3354. }
  3355. }
  3356. // else, it's a non-group
  3357. else {
  3358. // FIXME: box might be null for some elements (<metadata> etc), need to handle this
  3359. var box = getBBox(selected);
  3360. // Paths (and possbly other shapes) will have no BBox while still in <defs>,
  3361. // but we still may need to recalculate them (see issue 595).
  3362. // TODO: Figure out how to get BBox from these elements in case they
  3363. // have a rotation transform
  3364. if(!box && selected.tagName != 'path') return null;
  3365. var m = svgroot.createSVGMatrix(),
  3366. // temporarily strip off the rotate and save the old center
  3367. angle = getRotationAngle(selected);
  3368. if (angle) {
  3369. var oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
  3370. newcenter = transformPoint(box.x+box.width/2, box.y+box.height/2,
  3371. transformListToTransform(tlist).matrix);
  3372. var a = angle * Math.PI / 180;
  3373. if ( Math.abs(a) > (1.0e-10) ) {
  3374. var s = Math.sin(a)/(1 - Math.cos(a));
  3375. } else {
  3376. // FIXME: This blows up if the angle is exactly 0!
  3377. var s = 2/a;
  3378. }
  3379. for (var i = 0; i < tlist.numberOfItems; ++i) {
  3380. var xform = tlist.getItem(i);
  3381. if (xform.type == 4) {
  3382. // extract old center through mystical arts
  3383. var rm = xform.matrix;
  3384. oldcenter.y = (s*rm.e + rm.f)/2;
  3385. oldcenter.x = (rm.e - s*rm.f)/2;
  3386. tlist.removeItem(i);
  3387. break;
  3388. }
  3389. }
  3390. }
  3391. // 2 = translate, 3 = scale, 4 = rotate, 1 = matrix imposition
  3392. var operation = 0;
  3393. var N = tlist.numberOfItems;
  3394. // Check if it has a gradient with userSpaceOnUse, in which case
  3395. // adjust it by recalculating the matrix transform.
  3396. // TODO: Make this work in Webkit using SVGEditTransformList
  3397. if(!isWebkit) {
  3398. var fill = selected.getAttribute('fill');
  3399. if(fill && fill.indexOf('url(') === 0) {
  3400. var grad = getElem(getUrlFromAttr(fill).substr(1));
  3401. if(grad.getAttribute('gradientUnits') === 'userSpaceOnUse') {
  3402. //Update the userSpaceOnUse element
  3403. var grad = $(grad);
  3404. m = transformListToTransform(tlist).matrix;
  3405. var gtlist = getTransformList(grad[0]);
  3406. var gmatrix = transformListToTransform(gtlist).matrix;
  3407. m = matrixMultiply(m, gmatrix);
  3408. var m_str = "matrix(" + [m.a,m.b,m.c,m.d,m.e,m.f].join(",") + ")";
  3409. grad.attr('gradientTransform', m_str);
  3410. }
  3411. }
  3412. }
  3413. // first, if it was a scale of a non-skewed element, then the second-last
  3414. // transform will be the [S]
  3415. // if we had [M][T][S][T] we want to extract the matrix equivalent of
  3416. // [T][S][T] and push it down to the element
  3417. if (N >= 3 && tlist.getItem(N-2).type == 3 &&
  3418. tlist.getItem(N-3).type == 2 && tlist.getItem(N-1).type == 2)
  3419. // Removed this so a <use> with a given [T][S][T] would convert to a matrix.
  3420. // Is that bad?
  3421. // && selected.nodeName != "use"
  3422. {
  3423. operation = 3; // scale
  3424. m = transformListToTransform(tlist,N-3,N-1).matrix;
  3425. tlist.removeItem(N-1);
  3426. tlist.removeItem(N-2);
  3427. tlist.removeItem(N-3);
  3428. } // if we had [T][S][-T][M], then this was a skewed element being resized
  3429. // Thus, we simply combine it all into one matrix
  3430. else if(N == 4 && tlist.getItem(N-1).type == 1) {
  3431. operation = 3; // scale
  3432. m = transformListToTransform(tlist).matrix;
  3433. var e2t = svgroot.createSVGTransform();
  3434. e2t.setMatrix(m);
  3435. tlist.clear();
  3436. tlist.appendItem(e2t);
  3437. // reset the matrix so that the element is not re-mapped
  3438. m = svgroot.createSVGMatrix();
  3439. } // if we had [R][T][S][-T][M], then this was a rotated matrix-element
  3440. // if we had [T1][M] we want to transform this into [M][T2]
  3441. // therefore [ T2 ] = [ M_inv ] [ T1 ] [ M ] and we can push [T2]
  3442. // down to the element
  3443. else if ( (N == 1 || (N > 1 && tlist.getItem(1).type != 3)) &&
  3444. tlist.getItem(0).type == 2)
  3445. {
  3446. operation = 2; // translate
  3447. var oldxlate = tlist.getItem(0).matrix,
  3448. meq = transformListToTransform(tlist,1).matrix,
  3449. meq_inv = meq.inverse();
  3450. m = matrixMultiply( meq_inv, oldxlate, meq );
  3451. tlist.removeItem(0);
  3452. }
  3453. // else if this child now has a matrix imposition (from a parent group)
  3454. // we might be able to simplify
  3455. else if (N == 1 && tlist.getItem(0).type == 1 && !angle) {
  3456. // Remap all point-based elements
  3457. m = transformListToTransform(tlist).matrix;
  3458. switch (selected.tagName) {
  3459. case 'line':
  3460. changes = $(selected).attr(["x1","y1","x2","y2"]);
  3461. case 'polyline':
  3462. case 'polygon':
  3463. changes.points = selected.getAttribute("points");
  3464. if(changes.points) {
  3465. var list = selected.points;
  3466. var len = list.numberOfItems;
  3467. changes.points = new Array(len);
  3468. for (var i = 0; i < len; ++i) {
  3469. var pt = list.getItem(i);
  3470. changes.points[i] = {x:pt.x,y:pt.y};
  3471. }
  3472. }
  3473. case 'path':
  3474. changes.d = selected.getAttribute("d");
  3475. operation = 1;
  3476. tlist.clear();
  3477. break;
  3478. default:
  3479. break;
  3480. }
  3481. }
  3482. // if it was a rotation, put the rotate back and return without a command
  3483. // (this function has zero work to do for a rotate())
  3484. else {
  3485. operation = 4; // rotation
  3486. if (angle) {
  3487. var newRot = svgroot.createSVGTransform();
  3488. newRot.setRotate(angle,newcenter.x,newcenter.y);
  3489. if(tlist.numberOfItems) {
  3490. tlist.insertItemBefore(newRot, 0);
  3491. } else {
  3492. tlist.appendItem(newRot);
  3493. }
  3494. }
  3495. if (tlist.numberOfItems == 0) {
  3496. selected.removeAttribute("transform");
  3497. }
  3498. return null;
  3499. }
  3500. // if it was a translate or resize, we need to remap the element and absorb the xform
  3501. if (operation == 1 || operation == 2 || operation == 3) {
  3502. remapElement(selected,changes,m);
  3503. } // if we are remapping
  3504. // if it was a translate, put back the rotate at the new center
  3505. if (operation == 2) {
  3506. if (angle) {
  3507. if(!hasMatrixTransform(tlist)) {
  3508. newcenter = {
  3509. x: oldcenter.x + m.e,
  3510. y: oldcenter.y + m.f
  3511. };
  3512. }
  3513. var newRot = svgroot.createSVGTransform();
  3514. newRot.setRotate(angle, newcenter.x, newcenter.y);
  3515. if(tlist.numberOfItems) {
  3516. tlist.insertItemBefore(newRot, 0);
  3517. } else {
  3518. tlist.appendItem(newRot);
  3519. }
  3520. }
  3521. }
  3522. // [Rold][M][T][S][-T] became [Rold][M]
  3523. // we want it to be [Rnew][M][Tr] where Tr is the
  3524. // translation required to re-center it
  3525. // Therefore, [Tr] = [M_inv][Rnew_inv][Rold][M]
  3526. else if (operation == 3 && angle) {
  3527. var m = transformListToTransform(tlist).matrix;
  3528. var roldt = svgroot.createSVGTransform();
  3529. roldt.setRotate(angle, oldcenter.x, oldcenter.y);
  3530. var rold = roldt.matrix;
  3531. var rnew = svgroot.createSVGTransform();
  3532. rnew.setRotate(angle, newcenter.x, newcenter.y);
  3533. var rnew_inv = rnew.matrix.inverse();
  3534. var m_inv = m.inverse();
  3535. var extrat = matrixMultiply(m_inv, rnew_inv, rold, m);
  3536. remapElement(selected,changes,extrat);
  3537. if (angle) {
  3538. if(tlist.numberOfItems) {
  3539. tlist.insertItemBefore(rnew, 0);
  3540. } else {
  3541. tlist.appendItem(rnew);
  3542. }
  3543. }
  3544. }
  3545. } // a non-group
  3546. // if the transform list has been emptied, remove it
  3547. if (tlist.numberOfItems == 0) {
  3548. selected.removeAttribute("transform");
  3549. }
  3550. batchCmd.addSubCommand(new ChangeElementCommand(selected, initial));
  3551. return batchCmd;
  3552. };
  3553. // Root Current Transformation Matrix in user units
  3554. var root_sctm = null;
  3555. // Function: transformPoint
  3556. // A (hopefully) quicker function to transform a point by a matrix
  3557. // (this function avoids any DOM calls and just does the math)
  3558. //
  3559. // Parameters:
  3560. // x - Float representing the x coordinate
  3561. // y - Float representing the y coordinate
  3562. // m - Matrix object to transform the point with
  3563. // Returns a x,y object representing the transformed point
  3564. var transformPoint = function(x, y, m) {
  3565. return { x: m.a * x + m.c * y + m.e, y: m.b * x + m.d * y + m.f};
  3566. };
  3567. // Function: isIdentity
  3568. // Helper function to check if the matrix performs no actual transform
  3569. // (i.e. exists for identity purposes)
  3570. //
  3571. // Parameters:
  3572. // m - The matrix object to check
  3573. //
  3574. // Returns:
  3575. // Boolean indicating whether or not the matrix is 1,0,0,1,0,0
  3576. var isIdentity = function(m) {
  3577. return (m.a == 1 && m.b == 0 && m.c == 0 && m.d == 1 && m.e == 0 && m.f == 0);
  3578. }
  3579. // Function: matrixMultiply
  3580. // This function tries to return a SVGMatrix that is the multiplication m1*m2.
  3581. // We also round to zero when it's near zero
  3582. //
  3583. // Parameters:
  3584. // >= 2 Matrix objects to multiply
  3585. //
  3586. // Returns:
  3587. // The matrix object resulting from the calculation
  3588. var matrixMultiply = this.matrixMultiply = function() {
  3589. var NEAR_ZERO = 1e-14,
  3590. args = arguments, i = args.length, m = args[i-1];
  3591. while(i-- > 1) {
  3592. var m1 = args[i-1];
  3593. m = m1.multiply(m);
  3594. }
  3595. if (Math.abs(m.a) < NEAR_ZERO) m.a = 0;
  3596. if (Math.abs(m.b) < NEAR_ZERO) m.b = 0;
  3597. if (Math.abs(m.c) < NEAR_ZERO) m.c = 0;
  3598. if (Math.abs(m.d) < NEAR_ZERO) m.d = 0;
  3599. if (Math.abs(m.e) < NEAR_ZERO) m.e = 0;
  3600. if (Math.abs(m.f) < NEAR_ZERO) m.f = 0;
  3601. return m;
  3602. }
  3603. // Function: transformListToTransform
  3604. // This returns a single matrix Transform for a given Transform List
  3605. // (this is the equivalent of SVGTransformList.consolidate() but unlike
  3606. // that method, this one does not modify the actual SVGTransformList)
  3607. // This function is very liberal with its min,max arguments
  3608. //
  3609. // Parameters:
  3610. // tlist - The transformlist object
  3611. // min - Optional integer indicating start transform position
  3612. // max - Optional integer indicating end transform position
  3613. //
  3614. // Returns:
  3615. // A single matrix transform object
  3616. var transformListToTransform = this.transformListToTransform = function(tlist, min, max) {
  3617. if(tlist == null) {
  3618. // Or should tlist = null have been prevented before this?
  3619. return svgroot.createSVGTransformFromMatrix(svgroot.createSVGMatrix());
  3620. }
  3621. var min = min == undefined ? 0 : min;
  3622. var max = max == undefined ? (tlist.numberOfItems-1) : max;
  3623. min = parseInt(min);
  3624. max = parseInt(max);
  3625. if (min > max) { var temp = max; max = min; min = temp; }
  3626. var m = svgroot.createSVGMatrix();
  3627. for (var i = min; i <= max; ++i) {
  3628. // if our indices are out of range, just use a harmless identity matrix
  3629. var mtom = (i >= 0 && i < tlist.numberOfItems ?
  3630. tlist.getItem(i).matrix :
  3631. svgroot.createSVGMatrix());
  3632. m = matrixMultiply(m, mtom);
  3633. }
  3634. return svgroot.createSVGTransformFromMatrix(m);
  3635. };
  3636. // Function: hasMatrixTransform
  3637. // See if the given transformlist includes a non-indentity matrix transform
  3638. //
  3639. // Parameters:
  3640. // tlist - The transformlist to check
  3641. //
  3642. // Returns:
  3643. // Boolean on whether or not a matrix transform was found
  3644. var hasMatrixTransform = this.hasMatrixTransform = function(tlist) {
  3645. if(!tlist) return false;
  3646. var num = tlist.numberOfItems;
  3647. while (num--) {
  3648. var xform = tlist.getItem(num);
  3649. if (xform.type == 1 && !isIdentity(xform.matrix)) return true;
  3650. }
  3651. return false;
  3652. }
  3653. // Function: getMatrix
  3654. // Get the matrix object for a given element
  3655. //
  3656. // Parameters:
  3657. // elem - The DOM element to check
  3658. //
  3659. // Returns:
  3660. // The matrix object associated with the element's transformlist
  3661. var getMatrix = function(elem) {
  3662. var tlist = getTransformList(elem);
  3663. return transformListToTransform(tlist).matrix;
  3664. }
  3665. // Function: transformBox
  3666. // Transforms a rectangle based on the given matrix
  3667. //
  3668. // Parameters:
  3669. // l - Float with the box's left coordinate
  3670. // t - Float with the box's top coordinate
  3671. // w - Float with the box width
  3672. // h - Float with the box height
  3673. // m - Matrix object to transform the box by
  3674. //
  3675. // Returns:
  3676. // An object with the following values:
  3677. // * tl - The top left coordinate (x,y object)
  3678. // * tr - The top right coordinate (x,y object)
  3679. // * bl - The bottom left coordinate (x,y object)
  3680. // * br - The bottom right coordinate (x,y object)
  3681. // * aabox - Object with the following values:
  3682. // * Float with the axis-aligned x coordinate
  3683. // * Float with the axis-aligned y coordinate
  3684. // * Float with the axis-aligned width coordinate
  3685. // * Float with the axis-aligned height coordinate
  3686. var transformBox = this.transformBox = function(l, t, w, h, m) {
  3687. var topleft = {x:l,y:t},
  3688. topright = {x:(l+w),y:t},
  3689. botright = {x:(l+w),y:(t+h)},
  3690. botleft = {x:l,y:(t+h)};
  3691. topleft = transformPoint( topleft.x, topleft.y, m );
  3692. var minx = topleft.x,
  3693. maxx = topleft.x,
  3694. miny = topleft.y,
  3695. maxy = topleft.y;
  3696. topright = transformPoint( topright.x, topright.y, m );
  3697. minx = Math.min(minx, topright.x);
  3698. maxx = Math.max(maxx, topright.x);
  3699. miny = Math.min(miny, topright.y);
  3700. maxy = Math.max(maxy, topright.y);
  3701. botleft = transformPoint( botleft.x, botleft.y, m);
  3702. minx = Math.min(minx, botleft.x);
  3703. maxx = Math.max(maxx, botleft.x);
  3704. miny = Math.min(miny, botleft.y);
  3705. maxy = Math.max(maxy, botleft.y);
  3706. botright = transformPoint( botright.x, botright.y, m );
  3707. minx = Math.min(minx, botright.x);
  3708. maxx = Math.max(maxx, botright.x);
  3709. miny = Math.min(miny, botright.y);
  3710. maxy = Math.max(maxy, botright.y);
  3711. return {tl:topleft, tr:topright, bl:botleft, br:botright,
  3712. aabox: {x:minx, y:miny, width:(maxx-minx), height:(maxy-miny)} };
  3713. };
  3714. // Group: Selection
  3715. // Function: clearSelection
  3716. // Clears the selection. The 'selected' handler is then called.
  3717. // Parameters:
  3718. // noCall - Optional boolean that when true does not call the "selected" handler
  3719. var clearSelection = this.clearSelection = function(noCall) {
  3720. if (selectedElements[0] != null) {
  3721. var len = selectedElements.length;
  3722. for (var i = 0; i < len; ++i) {
  3723. var elem = selectedElements[i];
  3724. if (elem == null) break;
  3725. selectorManager.releaseSelector(elem);
  3726. selectedElements[i] = null;
  3727. }
  3728. selectedBBoxes[0] = null;
  3729. }
  3730. if(!noCall) call("selected", selectedElements);
  3731. };
  3732. // TODO: do we need to worry about selectedBBoxes here?
  3733. // Function: addToSelection
  3734. // Adds a list of elements to the selection. The 'selected' handler is then called.
  3735. //
  3736. // Parameters:
  3737. // elemsToAdd - an array of DOM elements to add to the selection
  3738. // showGrips - a boolean flag indicating whether the resize grips should be shown
  3739. var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) {
  3740. if (elemsToAdd.length == 0) { return; }
  3741. // find the first null in our selectedElements array
  3742. var j = 0;
  3743. while (j < selectedElements.length) {
  3744. if (selectedElements[j] == null) {
  3745. break;
  3746. }
  3747. ++j;
  3748. }
  3749. // now add each element consecutively
  3750. var i = elemsToAdd.length;
  3751. while (i--) {
  3752. var elem = elemsToAdd[i];
  3753. if (!elem || !getBBox(elem)) continue;
  3754. // if it's not already there, add it
  3755. if (selectedElements.indexOf(elem) == -1) {
  3756. selectedElements[j] = elem;
  3757. // only the first selectedBBoxes element is ever used in the codebase these days
  3758. if (j == 0) selectedBBoxes[j] = getBBox(elem);
  3759. j++;
  3760. var sel = selectorManager.requestSelector(elem);
  3761. if (selectedElements.length > 1) {
  3762. sel.showGrips(false);
  3763. }
  3764. }
  3765. }
  3766. if(selectedElements[0] && selectedElements.length === 1 && selectedElements[0].tagName == 'a') {
  3767. // Make "a" element's child be the selected element
  3768. selectedElements[0] = selectedElements[0].firstChild;
  3769. }
  3770. call("selected", selectedElements);
  3771. if (showGrips || selectedElements.length == 1) {
  3772. selectorManager.requestSelector(selectedElements[0]).showGrips(true);
  3773. }
  3774. else {
  3775. selectorManager.requestSelector(selectedElements[0]).showGrips(false);
  3776. }
  3777. // make sure the elements are in the correct order
  3778. // See: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition
  3779. selectedElements.sort(function(a,b) {
  3780. if(a && b && a.compareDocumentPosition) {
  3781. return 3 - (b.compareDocumentPosition(a) & 6);
  3782. } else if(a == null) {
  3783. return 1;
  3784. }
  3785. });
  3786. // Make sure first elements are not null
  3787. while(selectedElements[0] == null) selectedElements.shift(0);
  3788. };
  3789. // Function: selectOnly()
  3790. // Selects only the given elements, shortcut for clearSelection(); addToSelection()
  3791. //
  3792. // Parameters:
  3793. // elems - an array of DOM elements to be selected
  3794. var selectOnly = this.selectOnly = function(elems, showGrips) {
  3795. clearSelection(true);
  3796. addToSelection(elems, showGrips);
  3797. }
  3798. // TODO: could use slice here to make this faster?
  3799. // TODO: should the 'selected' handler
  3800. // Function: removeFromSelection
  3801. // Removes elements from the selection.
  3802. //
  3803. // Parameters:
  3804. // elemsToRemove - an array of elements to remove from selection
  3805. var removeFromSelection = this.removeFromSelection = function(elemsToRemove) {
  3806. if (selectedElements[0] == null) { return; }
  3807. if (elemsToRemove.length == 0) { return; }
  3808. // find every element and remove it from our array copy
  3809. var newSelectedItems = new Array(selectedElements.length);
  3810. j = 0,
  3811. len = selectedElements.length;
  3812. for (var i = 0; i < len; ++i) {
  3813. var elem = selectedElements[i];
  3814. if (elem) {
  3815. // keep the item
  3816. if (elemsToRemove.indexOf(elem) == -1) {
  3817. newSelectedItems[j] = elem;
  3818. j++;
  3819. }
  3820. else { // remove the item and its selector
  3821. selectorManager.releaseSelector(elem);
  3822. }
  3823. }
  3824. }
  3825. // the copy becomes the master now
  3826. selectedElements = newSelectedItems;
  3827. };
  3828. // Function: selectAllInCurrentLayer
  3829. // Clears the selection, then adds all elements in the current layer to the selection.
  3830. this.selectAllInCurrentLayer = function() {
  3831. if (current_layer) {
  3832. current_mode = "select";
  3833. selectOnly($(current_group || current_layer).children());
  3834. }
  3835. };
  3836. // Function: smoothControlPoints
  3837. // Takes three points and creates a smoother line based on them
  3838. //
  3839. // Parameters:
  3840. // ct1 - Object with x and y values (first control point)
  3841. // ct2 - Object with x and y values (second control point)
  3842. // pt - Object with x and y values (third point)
  3843. //
  3844. // Returns:
  3845. // Array of two "smoothed" point objects
  3846. var smoothControlPoints = this.smoothControlPoints = function(ct1, ct2, pt) {
  3847. // each point must not be the origin
  3848. var x1 = ct1.x - pt.x,
  3849. y1 = ct1.y - pt.y,
  3850. x2 = ct2.x - pt.x,
  3851. y2 = ct2.y - pt.y;
  3852. if ( (x1 != 0 || y1 != 0) && (x2 != 0 || y2 != 0) ) {
  3853. var anglea = Math.atan2(y1,x1),
  3854. angleb = Math.atan2(y2,x2),
  3855. r1 = Math.sqrt(x1*x1+y1*y1),
  3856. r2 = Math.sqrt(x2*x2+y2*y2),
  3857. nct1 = svgroot.createSVGPoint(),
  3858. nct2 = svgroot.createSVGPoint();
  3859. if (anglea < 0) { anglea += 2*Math.PI; }
  3860. if (angleb < 0) { angleb += 2*Math.PI; }
  3861. var angleBetween = Math.abs(anglea - angleb),
  3862. angleDiff = Math.abs(Math.PI - angleBetween)/2;
  3863. var new_anglea, new_angleb;
  3864. if (anglea - angleb > 0) {
  3865. new_anglea = angleBetween < Math.PI ? (anglea + angleDiff) : (anglea - angleDiff);
  3866. new_angleb = angleBetween < Math.PI ? (angleb - angleDiff) : (angleb + angleDiff);
  3867. }
  3868. else {
  3869. new_anglea = angleBetween < Math.PI ? (anglea - angleDiff) : (anglea + angleDiff);
  3870. new_angleb = angleBetween < Math.PI ? (angleb + angleDiff) : (angleb - angleDiff);
  3871. }
  3872. // rotate the points
  3873. nct1.x = r1 * Math.cos(new_anglea) + pt.x;
  3874. nct1.y = r1 * Math.sin(new_anglea) + pt.y;
  3875. nct2.x = r2 * Math.cos(new_angleb) + pt.x;
  3876. nct2.y = r2 * Math.sin(new_angleb) + pt.y;
  3877. return [nct1, nct2];
  3878. }
  3879. return undefined;
  3880. };
  3881. // Function: getMouseTarget
  3882. // Gets the desired element from a mouse event
  3883. //
  3884. // Parameters:
  3885. // evt - Event object from the mouse event
  3886. //
  3887. // Returns:
  3888. // DOM element we want
  3889. var getMouseTarget = this.getMouseTarget = function(evt) {
  3890. if (evt == null) {
  3891. return null;
  3892. }
  3893. var mouse_target = evt.target;
  3894. // if it was a <use>, Opera and WebKit return the SVGElementInstance
  3895. if (mouse_target.correspondingUseElement) mouse_target = mouse_target.correspondingUseElement;
  3896. // for foreign content, go up until we find the foreignObject
  3897. // WebKit browsers set the mouse target to the svgcanvas div
  3898. if ([mathns, htmlns].indexOf(mouse_target.namespaceURI) >= 0 &&
  3899. mouse_target.id != "svgcanvas")
  3900. {
  3901. while (mouse_target.nodeName != "foreignObject") {
  3902. mouse_target = mouse_target.parentNode;
  3903. if(!mouse_target) return svgroot;
  3904. }
  3905. }
  3906. // Get the desired mouse_target with jQuery selector-fu
  3907. // If it's root-like, select the root
  3908. if([svgroot, container, svgcontent, current_layer].indexOf(mouse_target) >= 0) {
  3909. return svgroot;
  3910. }
  3911. var $target = $(mouse_target);
  3912. // If it's a selection grip, return the grip parent
  3913. if($target.closest('#selectorParentGroup').length) {
  3914. // While we could instead have just returned mouse_target,
  3915. // this makes it easier to indentify as being a selector grip
  3916. return selectorManager.selectorParentGroup;
  3917. }
  3918. while (mouse_target.parentNode !== (current_group || current_layer)) {
  3919. mouse_target = mouse_target.parentNode;
  3920. }
  3921. return mouse_target;
  3922. //
  3923. // // go up until we hit a child of a layer
  3924. // while (mouse_target.parentNode.parentNode.tagName == 'g') {
  3925. // mouse_target = mouse_target.parentNode;
  3926. // }
  3927. // Webkit bubbles the mouse event all the way up to the div, so we
  3928. // set the mouse_target to the svgroot like the other browsers
  3929. // if (mouse_target.nodeName.toLowerCase() == "div") {
  3930. // mouse_target = svgroot;
  3931. // }
  3932. return mouse_target;
  3933. };
  3934. // Mouse events
  3935. (function() {
  3936. var off_x, off_y;
  3937. var d_attr = null,
  3938. start_x = null,
  3939. start_y = null,
  3940. r_start_x = null,
  3941. r_start_y = null,
  3942. init_bbox = {},
  3943. freehand = {
  3944. minx: null,
  3945. miny: null,
  3946. maxx: null,
  3947. maxy: null
  3948. };
  3949. // - when we are in a create mode, the element is added to the canvas
  3950. // but the action is not recorded until mousing up
  3951. // - when we are in select mode, select the element, remember the position
  3952. // and do nothing else
  3953. var mouseDown = function(evt)
  3954. {
  3955. if(canvas.spaceKey) return;
  3956. var right_click = evt.button === 2;
  3957. root_sctm = svgcontent.getScreenCTM().inverse();
  3958. var pt = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  3959. mouse_x = pt.x * current_zoom,
  3960. mouse_y = pt.y * current_zoom;
  3961. if($.browser.msie) {
  3962. var off = $(container.parentNode).offset();
  3963. off_x = svgcontent.getAttribute('x')-0 + off.left - container.parentNode.scrollLeft;
  3964. off_y = svgcontent.getAttribute('y')-0 + off.top - container.parentNode.scrollTop;
  3965. mouse_x = -(off_x - evt.pageX);
  3966. mouse_y = -(off_y - evt.pageY);
  3967. }
  3968. evt.preventDefault();
  3969. if(right_click) {
  3970. current_mode = "select";
  3971. lastClickPoint = pt;
  3972. }
  3973. // This would seem to be unnecessary...
  3974. // if(['select', 'resize'].indexOf(current_mode) == -1) {
  3975. // setGradient();
  3976. // }
  3977. var x = mouse_x / current_zoom,
  3978. y = mouse_y / current_zoom,
  3979. mouse_target = getMouseTarget(evt);
  3980. // real_x/y ignores grid-snap value
  3981. var real_x = r_start_x = start_x = x;
  3982. var real_y = r_start_y = start_y = y;
  3983. if(curConfig.gridSnapping){
  3984. x = snapToGrid(x);
  3985. y = snapToGrid(y);
  3986. start_x = snapToGrid(start_x);
  3987. start_y = snapToGrid(start_y);
  3988. }
  3989. // if it is a selector grip, then it must be a single element selected,
  3990. // set the mouse_target to that and update the mode to rotate/resize
  3991. if (mouse_target == selectorManager.selectorParentGroup && selectedElements[0] != null) {
  3992. var grip = evt.target;
  3993. var griptype = elData(grip, "type");
  3994. // rotating
  3995. if (griptype == "rotate") {
  3996. current_mode = "rotate";
  3997. }
  3998. // resizing
  3999. else if(griptype == "resize") {
  4000. current_mode = "resize";
  4001. current_resize_mode = elData(grip, "dir");
  4002. }
  4003. mouse_target = selectedElements[0];
  4004. }
  4005. start_transform = mouse_target.getAttribute("transform");
  4006. var tlist = getTransformList(mouse_target);
  4007. switch (current_mode) {
  4008. case "select":
  4009. started = true;
  4010. current_resize_mode = "none";
  4011. if(right_click) started = false;
  4012. if (mouse_target != svgroot) {
  4013. // if this element is not yet selected, clear selection and select it
  4014. if (selectedElements.indexOf(mouse_target) == -1) {
  4015. // only clear selection if shift is not pressed (otherwise, add
  4016. // element to selection)
  4017. if (!evt.shiftKey) {
  4018. // No need to do the call here as it will be done on addToSelection
  4019. clearSelection(true);
  4020. }
  4021. addToSelection([mouse_target]);
  4022. justSelected = mouse_target;
  4023. pathActions.clear();
  4024. }
  4025. // else if it's a path, go into pathedit mode in mouseup
  4026. if(!right_click) {
  4027. // insert a dummy transform so if the element(s) are moved it will have
  4028. // a transform to use for its translate
  4029. for (var i = 0; i < selectedElements.length; ++i) {
  4030. if(selectedElements[i] == null) continue;
  4031. var slist = getTransformList(selectedElements[i]);
  4032. if(slist.numberOfItems) {
  4033. slist.insertItemBefore(svgroot.createSVGTransform(), 0);
  4034. } else {
  4035. slist.appendItem(svgroot.createSVGTransform());
  4036. }
  4037. }
  4038. }
  4039. }
  4040. else if(!right_click){
  4041. clearSelection();
  4042. current_mode = "multiselect";
  4043. if (rubberBox == null) {
  4044. rubberBox = selectorManager.getRubberBandBox();
  4045. }
  4046. r_start_x *= current_zoom;
  4047. r_start_y *= current_zoom;
  4048. // console.log('p',[evt.pageX, evt.pageY]);
  4049. // console.log('c',[evt.clientX, evt.clientY]);
  4050. // console.log('o',[evt.offsetX, evt.offsetY]);
  4051. // console.log('s',[start_x, start_y]);
  4052. assignAttributes(rubberBox, {
  4053. 'x': r_start_x,
  4054. 'y': r_start_y,
  4055. 'width': 0,
  4056. 'height': 0,
  4057. 'display': 'inline'
  4058. }, 100);
  4059. }
  4060. break;
  4061. case "zoom":
  4062. started = true;
  4063. if (rubberBox == null) {
  4064. rubberBox = selectorManager.getRubberBandBox();
  4065. }
  4066. assignAttributes(rubberBox, {
  4067. 'x': real_x * current_zoom,
  4068. 'y': real_x * current_zoom,
  4069. 'width': 0,
  4070. 'height': 0,
  4071. 'display': 'inline'
  4072. }, 100);
  4073. break;
  4074. case "resize":
  4075. started = true;
  4076. start_x = x;
  4077. start_y = y;
  4078. // Getting the BBox from the selection box, since we know we
  4079. // want to orient around it
  4080. init_bbox = getBBox($('#selectedBox0')[0]);
  4081. var bb = {};
  4082. $.each(init_bbox, function(key, val) {
  4083. bb[key] = val/current_zoom;
  4084. });
  4085. init_bbox = bb;
  4086. // append three dummy transforms to the tlist so that
  4087. // we can translate,scale,translate in mousemove
  4088. var pos = getRotationAngle(mouse_target)?1:0;
  4089. if(hasMatrixTransform(tlist)) {
  4090. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  4091. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  4092. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  4093. } else {
  4094. tlist.appendItem(svgroot.createSVGTransform());
  4095. tlist.appendItem(svgroot.createSVGTransform());
  4096. tlist.appendItem(svgroot.createSVGTransform());
  4097. }
  4098. break;
  4099. case "fhellipse":
  4100. case "fhrect":
  4101. case "fhpath":
  4102. started = true;
  4103. d_attr = real_x + "," + real_y + " ";
  4104. var stroke_w = cur_shape.stroke_width == 0?1:cur_shape.stroke_width;
  4105. addSvgElementFromJson({
  4106. "element": "polyline",
  4107. "curStyles": true,
  4108. "attr": {
  4109. "points": d_attr,
  4110. "id": getNextId(),
  4111. "fill": "none",
  4112. "opacity": cur_shape.opacity / 2,
  4113. "stroke-linecap": "round",
  4114. "style": "pointer-events:none"
  4115. }
  4116. });
  4117. freehand.minx = real_x;
  4118. freehand.maxx = real_x;
  4119. freehand.miny = real_y;
  4120. freehand.maxy = real_y;
  4121. break;
  4122. case "image":
  4123. started = true;
  4124. var newImage = addSvgElementFromJson({
  4125. "element": "image",
  4126. "attr": {
  4127. "x": x,
  4128. "y": y,
  4129. "width": 0,
  4130. "height": 0,
  4131. "id": getNextId(),
  4132. "opacity": cur_shape.opacity / 2,
  4133. "style": "pointer-events:inherit"
  4134. }
  4135. });
  4136. setHref(newImage, last_good_img_url);
  4137. preventClickDefault(newImage);
  4138. break;
  4139. case "square":
  4140. // FIXME: once we create the rect, we lose information that this was a square
  4141. // (for resizing purposes this could be important)
  4142. case "rect":
  4143. started = true;
  4144. start_x = x;
  4145. start_y = y;
  4146. addSvgElementFromJson({
  4147. "element": "rect",
  4148. "curStyles": true,
  4149. "attr": {
  4150. "x": x,
  4151. "y": y,
  4152. "width": 0,
  4153. "height": 0,
  4154. "id": getNextId(),
  4155. "opacity": cur_shape.opacity / 2
  4156. }
  4157. });
  4158. break;
  4159. case "line":
  4160. started = true;
  4161. var stroke_w = cur_shape.stroke_width == 0?1:cur_shape.stroke_width;
  4162. addSvgElementFromJson({
  4163. "element": "line",
  4164. "curStyles": true,
  4165. "attr": {
  4166. "x1": x,
  4167. "y1": y,
  4168. "x2": x,
  4169. "y2": y,
  4170. "id": getNextId(),
  4171. "stroke": cur_shape.stroke,
  4172. "stroke-width": stroke_w,
  4173. "stroke-dasharray": cur_shape.stroke_dasharray,
  4174. "stroke-linejoin": cur_shape.stroke_linejoin,
  4175. "stroke-linecap": cur_shape.stroke_linecap,
  4176. "stroke-opacity": cur_shape.stroke_opacity,
  4177. "fill": "none",
  4178. "opacity": cur_shape.opacity / 2,
  4179. "style": "pointer-events:none"
  4180. }
  4181. });
  4182. break;
  4183. case "circle":
  4184. started = true;
  4185. addSvgElementFromJson({
  4186. "element": "circle",
  4187. "curStyles": true,
  4188. "attr": {
  4189. "cx": x,
  4190. "cy": y,
  4191. "r": 0,
  4192. "id": getNextId(),
  4193. "opacity": cur_shape.opacity / 2
  4194. }
  4195. });
  4196. break;
  4197. case "ellipse":
  4198. started = true;
  4199. addSvgElementFromJson({
  4200. "element": "ellipse",
  4201. "curStyles": true,
  4202. "attr": {
  4203. "cx": x,
  4204. "cy": y,
  4205. "rx": 0,
  4206. "ry": 0,
  4207. "id": getNextId(),
  4208. "opacity": cur_shape.opacity / 2
  4209. }
  4210. });
  4211. break;
  4212. case "text":
  4213. started = true;
  4214. var newText = addSvgElementFromJson({
  4215. "element": "text",
  4216. "curStyles": true,
  4217. "attr": {
  4218. "x": x,
  4219. "y": y,
  4220. "id": getNextId(),
  4221. "fill": cur_text.fill,
  4222. "stroke-width": cur_text.stroke_width,
  4223. "font-size": cur_text.font_size,
  4224. "font-family": cur_text.font_family,
  4225. "text-anchor": "middle",
  4226. "xml:space": "preserve"
  4227. }
  4228. });
  4229. // newText.textContent = "text";
  4230. break;
  4231. case "path":
  4232. // Fall through
  4233. case "pathedit":
  4234. start_x *= current_zoom;
  4235. start_y *= current_zoom;
  4236. pathActions.mouseDown(evt, mouse_target, start_x, start_y);
  4237. started = true;
  4238. break;
  4239. case "textedit":
  4240. start_x *= current_zoom;
  4241. start_y *= current_zoom;
  4242. textActions.mouseDown(evt, mouse_target, start_x, start_y);
  4243. started = true;
  4244. break;
  4245. case "rotate":
  4246. started = true;
  4247. // we are starting an undoable change (a drag-rotation)
  4248. canvas.beginUndoableChange("transform", selectedElements);
  4249. break;
  4250. default:
  4251. // This could occur in an extension
  4252. break;
  4253. }
  4254. var ext_result = runExtensions("mouseDown", {
  4255. event: evt,
  4256. start_x: start_x,
  4257. start_y: start_y,
  4258. selectedElements: selectedElements
  4259. }, true);
  4260. $.each(ext_result, function(i, r) {
  4261. if(r && r.started) {
  4262. started = true;
  4263. }
  4264. });
  4265. };
  4266. // in this function we do not record any state changes yet (but we do update
  4267. // any elements that are still being created, moved or resized on the canvas)
  4268. // TODO: svgcanvas should just retain a reference to the image being dragged instead
  4269. // of the getId() and getElementById() funkiness - this will help us customize the ids
  4270. // a little bit for squares and paths
  4271. var mouseMove = function(evt)
  4272. {
  4273. if (!started) return;
  4274. if(evt.button === 1 || canvas.spaceKey) return;
  4275. var selected = selectedElements[0],
  4276. pt = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  4277. mouse_x = pt.x * current_zoom,
  4278. mouse_y = pt.y * current_zoom,
  4279. shape = getElem(getId());
  4280. // IE9 gives the wrong root_sctm
  4281. // TODO: Use non-browser sniffing way to make this work
  4282. if($.browser.msie) {
  4283. mouse_x = -(off_x - evt.pageX);
  4284. mouse_y = -(off_y - evt.pageY);
  4285. }
  4286. var real_x = x = mouse_x / current_zoom;
  4287. var real_y = y = mouse_y / current_zoom;
  4288. if(curConfig.gridSnapping){
  4289. x = snapToGrid(x);
  4290. y = snapToGrid(y);
  4291. }
  4292. evt.preventDefault();
  4293. switch (current_mode)
  4294. {
  4295. case "select":
  4296. // we temporarily use a translate on the element(s) being dragged
  4297. // this transform is removed upon mousing up and the element is
  4298. // relocated to the new location
  4299. if (selectedElements[0] != null) {
  4300. var dx = x - start_x;
  4301. var dy = y - start_y;
  4302. if(curConfig.gridSnapping){
  4303. dx = snapToGrid(dx);
  4304. dy = snapToGrid(dy);
  4305. }
  4306. if(evt.shiftKey) { var xya = Utils.snapToAngle(start_x,start_y,x,y); x=xya.x; y=xya.y; }
  4307. if (dx != 0 || dy != 0) {
  4308. var len = selectedElements.length;
  4309. for (var i = 0; i < len; ++i) {
  4310. var selected = selectedElements[i];
  4311. if (selected == null) break;
  4312. if (i==0) {
  4313. var box = getBBox(selected);
  4314. // selectedBBoxes[i].x = box.x + dx;
  4315. // selectedBBoxes[i].y = box.y + dy;
  4316. }
  4317. // update the dummy transform in our transform list
  4318. // to be a translate
  4319. var xform = svgroot.createSVGTransform();
  4320. var tlist = getTransformList(selected);
  4321. // Note that if Webkit and there's no ID for this
  4322. // element, the dummy transform may have gotten lost.
  4323. // This results in unexpected behaviour
  4324. xform.setTranslate(dx,dy);
  4325. if(tlist.numberOfItems) {
  4326. tlist.replaceItem(xform, 0);
  4327. } else {
  4328. tlist.appendItem(xform);
  4329. }
  4330. // update our internal bbox that we're tracking while dragging
  4331. selectorManager.requestSelector(selected).resize();
  4332. }
  4333. }
  4334. }
  4335. break;
  4336. case "multiselect":
  4337. real_x *= current_zoom;
  4338. real_y *= current_zoom;
  4339. assignAttributes(rubberBox, {
  4340. 'x': Math.min(r_start_x, real_x),
  4341. 'y': Math.min(r_start_y, real_y),
  4342. 'width': Math.abs(real_x - r_start_x),
  4343. 'height': Math.abs(real_y - r_start_y)
  4344. },100);
  4345. // for each selected:
  4346. // - if newList contains selected, do nothing
  4347. // - if newList doesn't contain selected, remove it from selected
  4348. // - for any newList that was not in selectedElements, add it to selected
  4349. var elemsToRemove = [], elemsToAdd = [],
  4350. newList = getIntersectionList(),
  4351. len = selectedElements.length;
  4352. for (var i = 0; i < len; ++i) {
  4353. var ind = newList.indexOf(selectedElements[i]);
  4354. if (ind == -1) {
  4355. elemsToRemove.push(selectedElements[i]);
  4356. }
  4357. else {
  4358. newList[ind] = null;
  4359. }
  4360. }
  4361. len = newList.length;
  4362. for (i = 0; i < len; ++i) { if (newList[i]) elemsToAdd.push(newList[i]); }
  4363. if (elemsToRemove.length > 0)
  4364. canvas.removeFromSelection(elemsToRemove);
  4365. if (elemsToAdd.length > 0)
  4366. addToSelection(elemsToAdd);
  4367. break;
  4368. case "resize":
  4369. // we track the resize bounding box and translate/scale the selected element
  4370. // while the mouse is down, when mouse goes up, we use this to recalculate
  4371. // the shape's coordinates
  4372. var tlist = getTransformList(selected),
  4373. hasMatrix = hasMatrixTransform(tlist),
  4374. box=hasMatrix?init_bbox:getBBox(selected),
  4375. left=box.x, top=box.y, width=box.width,
  4376. height=box.height, dx=(x-start_x), dy=(y-start_y);
  4377. if(curConfig.gridSnapping){
  4378. dx = snapToGrid(dx);
  4379. dy = snapToGrid(dy);
  4380. height = snapToGrid(height);
  4381. width = snapToGrid(width);
  4382. }
  4383. // if rotated, adjust the dx,dy values
  4384. var angle = getRotationAngle(selected);
  4385. if (angle) {
  4386. var r = Math.sqrt( dx*dx + dy*dy ),
  4387. theta = Math.atan2(dy,dx) - angle * Math.PI / 180.0;
  4388. dx = r * Math.cos(theta);
  4389. dy = r * Math.sin(theta);
  4390. }
  4391. // if not stretching in y direction, set dy to 0
  4392. // if not stretching in x direction, set dx to 0
  4393. if(current_resize_mode.indexOf("n")==-1 && current_resize_mode.indexOf("s")==-1) {
  4394. dy = 0;
  4395. }
  4396. if(current_resize_mode.indexOf("e")==-1 && current_resize_mode.indexOf("w")==-1) {
  4397. dx = 0;
  4398. }
  4399. var ts = null,
  4400. tx = 0, ty = 0,
  4401. sy = height ? (height+dy)/height : 1,
  4402. sx = width ? (width+dx)/width : 1;
  4403. // if we are dragging on the north side, then adjust the scale factor and ty
  4404. if(current_resize_mode.indexOf("n") >= 0) {
  4405. sy = height ? (height-dy)/height : 1;
  4406. ty = height;
  4407. }
  4408. // if we dragging on the east side, then adjust the scale factor and tx
  4409. if(current_resize_mode.indexOf("w") >= 0) {
  4410. sx = width ? (width-dx)/width : 1;
  4411. tx = width;
  4412. }
  4413. // update the transform list with translate,scale,translate
  4414. var translateOrigin = svgroot.createSVGTransform(),
  4415. scale = svgroot.createSVGTransform(),
  4416. translateBack = svgroot.createSVGTransform();
  4417. if(curConfig.gridSnapping){
  4418. left = snapToGrid(left);
  4419. tx = snapToGrid(tx);
  4420. top = snapToGrid(top);
  4421. ty = snapToGrid(ty);
  4422. }
  4423. translateOrigin.setTranslate(-(left+tx),-(top+ty));
  4424. if(evt.shiftKey) {
  4425. if(sx == 1) sx = sy
  4426. else sy = sx;
  4427. }
  4428. scale.setScale(sx,sy);
  4429. translateBack.setTranslate(left+tx,top+ty);
  4430. if(hasMatrix) {
  4431. var diff = angle?1:0;
  4432. tlist.replaceItem(translateOrigin, 2+diff);
  4433. tlist.replaceItem(scale, 1+diff);
  4434. tlist.replaceItem(translateBack, 0+diff);
  4435. } else {
  4436. var N = tlist.numberOfItems;
  4437. tlist.replaceItem(translateBack, N-3);
  4438. tlist.replaceItem(scale, N-2);
  4439. tlist.replaceItem(translateOrigin, N-1);
  4440. }
  4441. selectorManager.requestSelector(selected).resize();
  4442. break;
  4443. case "zoom":
  4444. real_x *= current_zoom;
  4445. real_y *= current_zoom;
  4446. assignAttributes(rubberBox, {
  4447. 'x': Math.min(r_start_x*current_zoom, real_x),
  4448. 'y': Math.min(r_start_y*current_zoom, real_y),
  4449. 'width': Math.abs(real_x - r_start_x*current_zoom),
  4450. 'height': Math.abs(real_y - r_start_y*current_zoom)
  4451. },100);
  4452. break;
  4453. case "text":
  4454. assignAttributes(shape,{
  4455. 'x': x,
  4456. 'y': y
  4457. },1000);
  4458. break;
  4459. case "line":
  4460. // Opera has a problem with suspendRedraw() apparently
  4461. var handle = null;
  4462. if (!window.opera) svgroot.suspendRedraw(1000);
  4463. if(curConfig.gridSnapping){
  4464. x = snapToGrid(x);
  4465. y = snapToGrid(y);
  4466. }
  4467. var x2 = x;
  4468. var y2 = y;
  4469. if(evt.shiftKey) { var xya=Utils.snapToAngle(start_x,start_y,x2,y2); x2=xya.x; y2=xya.y; }
  4470. shape.setAttributeNS(null, "x2", x2);
  4471. shape.setAttributeNS(null, "y2", y2);
  4472. if (!window.opera) svgroot.unsuspendRedraw(handle);
  4473. break;
  4474. case "foreignObject":
  4475. // fall through
  4476. case "square":
  4477. // fall through
  4478. case "rect":
  4479. // fall through
  4480. case "image":
  4481. var square = (current_mode == 'square') || evt.shiftKey,
  4482. w = Math.abs(x - start_x),
  4483. h = Math.abs(y - start_y),
  4484. new_x, new_y;
  4485. if(square) {
  4486. w = h = Math.max(w, h);
  4487. new_x = start_x < x ? start_x : start_x - w;
  4488. new_y = start_y < y ? start_y : start_y - h;
  4489. } else {
  4490. new_x = Math.min(start_x,x);
  4491. new_y = Math.min(start_y,y);
  4492. }
  4493. if(curConfig.gridSnapping){
  4494. w = snapToGrid(w);
  4495. h = snapToGrid(h);
  4496. new_x = snapToGrid(new_x);
  4497. new_y = snapToGrid(new_y);
  4498. }
  4499. assignAttributes(shape,{
  4500. 'width': w,
  4501. 'height': h,
  4502. 'x': new_x,
  4503. 'y': new_y
  4504. },1000);
  4505. break;
  4506. case "circle":
  4507. var c = $(shape).attr(["cx", "cy"]);
  4508. var cx = c.cx, cy = c.cy,
  4509. rad = Math.sqrt( (x-cx)*(x-cx) + (y-cy)*(y-cy) );
  4510. if(curConfig.gridSnapping){
  4511. rad = snapToGrid(rad);
  4512. }
  4513. shape.setAttributeNS(null, "r", rad);
  4514. break;
  4515. case "ellipse":
  4516. var c = $(shape).attr(["cx", "cy"]);
  4517. var cx = c.cx, cy = c.cy;
  4518. // Opera has a problem with suspendRedraw() apparently
  4519. handle = null;
  4520. if (!window.opera) svgroot.suspendRedraw(1000);
  4521. if(curConfig.gridSnapping){
  4522. x = snapToGrid(x);
  4523. cx = snapToGrid(cx);
  4524. y = snapToGrid(y);
  4525. cy = snapToGrid(cy);
  4526. }
  4527. shape.setAttributeNS(null, "rx", Math.abs(x - cx) );
  4528. var ry = Math.abs(evt.shiftKey?(x - cx):(y - cy));
  4529. shape.setAttributeNS(null, "ry", ry );
  4530. if (!window.opera) svgroot.unsuspendRedraw(handle);
  4531. break;
  4532. case "fhellipse":
  4533. case "fhrect":
  4534. freehand.minx = Math.min(real_x, freehand.minx);
  4535. freehand.maxx = Math.max(real_x, freehand.maxx);
  4536. freehand.miny = Math.min(real_y, freehand.miny);
  4537. freehand.maxy = Math.max(real_y, freehand.maxy);
  4538. // break; missing on purpose
  4539. case "fhpath":
  4540. d_attr += + real_x + "," + real_y + " ";
  4541. shape.setAttributeNS(null, "points", d_attr);
  4542. break;
  4543. // update path stretch line coordinates
  4544. case "path":
  4545. // fall through
  4546. case "pathedit":
  4547. x *= current_zoom;
  4548. y *= current_zoom;
  4549. if(curConfig.gridSnapping){
  4550. x = snapToGrid(x);
  4551. y = snapToGrid(y);
  4552. start_x = snapToGrid(start_x);
  4553. start_y = snapToGrid(start_y);
  4554. }
  4555. if(evt.shiftKey) {
  4556. var x1 = path.dragging?path.dragging[0]:start_x;
  4557. var y1 = path.dragging?path.dragging[1]:start_y;
  4558. var xya=Utils.snapToAngle(x1,y1,x,y);
  4559. x=xya.x; y=xya.y;
  4560. }
  4561. if(rubberBox && rubberBox.getAttribute('display') != 'none') {
  4562. assignAttributes(rubberBox, {
  4563. 'x': Math.min(r_start_x, real_x),
  4564. 'y': Math.min(r_start_y, real_y),
  4565. 'width': Math.abs(real_x - r_start_x),
  4566. 'height': Math.abs(real_y - r_start_y)
  4567. },100);
  4568. }
  4569. pathActions.mouseMove(x, y);
  4570. break;
  4571. case "textedit":
  4572. x *= current_zoom;
  4573. y *= current_zoom;
  4574. // if(rubberBox && rubberBox.getAttribute('display') != 'none') {
  4575. // assignAttributes(rubberBox, {
  4576. // 'x': Math.min(start_x,x),
  4577. // 'y': Math.min(start_y,y),
  4578. // 'width': Math.abs(x-start_x),
  4579. // 'height': Math.abs(y-start_y)
  4580. // },100);
  4581. // }
  4582. textActions.mouseMove(mouse_x, mouse_y);
  4583. break;
  4584. case "rotate":
  4585. var box = getBBox(selected),
  4586. cx = box.x + box.width/2,
  4587. cy = box.y + box.height/2,
  4588. m = getMatrix(selected),
  4589. center = transformPoint(cx,cy,m);
  4590. cx = center.x;
  4591. cy = center.y;
  4592. var angle = ((Math.atan2(cy-y,cx-x) * (180/Math.PI))-90) % 360;
  4593. if(curConfig.gridSnapping){
  4594. angle = snapToGrid(angle);
  4595. }
  4596. if(evt.shiftKey) { // restrict rotations to nice angles (WRS)
  4597. var snap = 45;
  4598. angle= Math.round(angle/snap)*snap;
  4599. }
  4600. canvas.setRotationAngle(angle<-180?(360+angle):angle, true);
  4601. call("changed", selectedElements);
  4602. break;
  4603. default:
  4604. break;
  4605. }
  4606. runExtensions("mouseMove", {
  4607. event: evt,
  4608. mouse_x: mouse_x,
  4609. mouse_y: mouse_y,
  4610. selected: selected
  4611. });
  4612. }; // mouseMove()
  4613. // - in create mode, the element's opacity is set properly, we create an InsertElementCommand
  4614. // and store it on the Undo stack
  4615. // - in move/resize mode, the element's attributes which were affected by the move/resize are
  4616. // identified, a ChangeElementCommand is created and stored on the stack for those attrs
  4617. // this is done in when we recalculate the selected dimensions()
  4618. var mouseUp = function(evt)
  4619. {
  4620. if(evt.button === 2) return;
  4621. var tempJustSelected = justSelected;
  4622. justSelected = null;
  4623. if (!started) return;
  4624. var pt = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  4625. mouse_x = pt.x * current_zoom,
  4626. mouse_y = pt.y * current_zoom,
  4627. x = mouse_x / current_zoom,
  4628. y = mouse_y / current_zoom,
  4629. element = getElem(getId()),
  4630. keep = false;
  4631. var real_x = x;
  4632. var real_y = y;
  4633. var useUnit = (curConfig.baseUnit !== 'px');
  4634. started = false;
  4635. switch (current_mode)
  4636. {
  4637. // intentionally fall-through to select here
  4638. case "resize":
  4639. case "multiselect":
  4640. if (rubberBox != null) {
  4641. rubberBox.setAttribute("display", "none");
  4642. curBBoxes = [];
  4643. }
  4644. current_mode = "select";
  4645. case "select":
  4646. if (selectedElements[0] != null) {
  4647. // if we only have one selected element
  4648. if (selectedElements[1] == null) {
  4649. // set our current stroke/fill properties to the element's
  4650. var selected = selectedElements[0];
  4651. if (selected.tagName != "g" && selected.tagName != "image" && selected.tagName != "foreignObject") {
  4652. cur_properties.fill = selected.getAttribute("fill");
  4653. cur_properties.fill_opacity = selected.getAttribute("fill-opacity");
  4654. cur_properties.stroke = selected.getAttribute("stroke");
  4655. cur_properties.stroke_opacity = selected.getAttribute("stroke-opacity");
  4656. cur_properties.stroke_width = selected.getAttribute("stroke-width");
  4657. cur_properties.stroke_dasharray = selected.getAttribute("stroke-dasharray");
  4658. cur_properties.stroke_linejoin = selected.getAttribute("stroke-linejoin");
  4659. cur_properties.stroke_linecap = selected.getAttribute("stroke-linecap");
  4660. }
  4661. if (selected.tagName == "text") {
  4662. cur_text.font_size = selected.getAttribute("font-size");
  4663. cur_text.font_family = selected.getAttribute("font-family");
  4664. }
  4665. selectorManager.requestSelector(selected).showGrips(true);
  4666. // This shouldn't be necessary as it was done on mouseDown...
  4667. // call("selected", [selected]);
  4668. }
  4669. // always recalculate dimensions to strip off stray identity transforms
  4670. recalculateAllSelectedDimensions();
  4671. // if it was being dragged/resized
  4672. if (real_x != r_start_x || real_y != r_start_y) {
  4673. var len = selectedElements.length;
  4674. for (var i = 0; i < len; ++i) {
  4675. if (selectedElements[i] == null) break;
  4676. if(selectedElements[i].tagName != 'g') {
  4677. // Not needed for groups (incorrectly resizes elems), possibly not needed at all?
  4678. selectorManager.requestSelector(selectedElements[i]).resize();
  4679. }
  4680. }
  4681. }
  4682. // no change in position/size, so maybe we should move to pathedit
  4683. else {
  4684. var t = evt.target;
  4685. if (selectedElements[0].nodeName == "path" && selectedElements[1] == null) {
  4686. pathActions.select(t);
  4687. } // if it was a path
  4688. // else, if it was selected and this is a shift-click, remove it from selection
  4689. else if (evt.shiftKey) {
  4690. if(tempJustSelected != t) {
  4691. canvas.removeFromSelection([t]);
  4692. }
  4693. }
  4694. } // no change in mouse position
  4695. }
  4696. // we return immediately from select so that the obj_num is not incremented
  4697. return;
  4698. break;
  4699. case "zoom":
  4700. if (rubberBox != null) {
  4701. rubberBox.setAttribute("display", "none");
  4702. }
  4703. var factor = evt.shiftKey?.5:2;
  4704. call("zoomed", {
  4705. 'x': Math.min(r_start_x, real_x),
  4706. 'y': Math.min(r_start_y, real_y),
  4707. 'width': Math.abs(real_x - r_start_x),
  4708. 'height': Math.abs(real_y - r_start_y),
  4709. 'factor': factor
  4710. });
  4711. return;
  4712. case "fhpath":
  4713. // Check that the path contains at least 2 points; a degenerate one-point path
  4714. // causes problems.
  4715. // Webkit ignores how we set the points attribute with commas and uses space
  4716. // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870
  4717. var coords = element.getAttribute('points');
  4718. var commaIndex = coords.indexOf(',');
  4719. if (commaIndex >= 0) {
  4720. keep = coords.indexOf(',', commaIndex+1) >= 0;
  4721. } else {
  4722. keep = coords.indexOf(' ', coords.indexOf(' ')+1) >= 0;
  4723. }
  4724. if (keep) {
  4725. element = pathActions.smoothPolylineIntoPath(element);
  4726. }
  4727. break;
  4728. case "line":
  4729. var attrs = $(element).attr(["x1", "x2", "y1", "y2"]);
  4730. keep = (attrs.x1 != attrs.x2 || attrs.y1 != attrs.y2);
  4731. break;
  4732. case "foreignObject":
  4733. case "square":
  4734. case "rect":
  4735. case "image":
  4736. var attrs = $(element).attr(["width", "height"]);
  4737. // Image should be kept regardless of size (use inherit dimensions later)
  4738. keep = (attrs.width != 0 || attrs.height != 0) || current_mode === "image";
  4739. break;
  4740. case "circle":
  4741. keep = (element.getAttribute('r') != 0);
  4742. break;
  4743. case "ellipse":
  4744. var attrs = $(element).attr(["rx", "ry"]);
  4745. keep = (attrs.rx != null || attrs.ry != null);
  4746. break;
  4747. case "fhellipse":
  4748. if ((freehand.maxx - freehand.minx) > 0 &&
  4749. (freehand.maxy - freehand.miny) > 0) {
  4750. element = addSvgElementFromJson({
  4751. "element": "ellipse",
  4752. "curStyles": true,
  4753. "attr": {
  4754. "cx": (freehand.minx + freehand.maxx) / 2,
  4755. "cy": (freehand.miny + freehand.maxy) / 2,
  4756. "rx": (freehand.maxx - freehand.minx) / 2,
  4757. "ry": (freehand.maxy - freehand.miny) / 2,
  4758. "id": getId()
  4759. }
  4760. });
  4761. call("changed",[element]);
  4762. keep = true;
  4763. }
  4764. break;
  4765. case "fhrect":
  4766. if ((freehand.maxx - freehand.minx) > 0 &&
  4767. (freehand.maxy - freehand.miny) > 0) {
  4768. element = addSvgElementFromJson({
  4769. "element": "rect",
  4770. "curStyles": true,
  4771. "attr": {
  4772. "x": freehand.minx,
  4773. "y": freehand.miny,
  4774. "width": (freehand.maxx - freehand.minx),
  4775. "height": (freehand.maxy - freehand.miny),
  4776. "id": getId()
  4777. }
  4778. });
  4779. call("changed",[element]);
  4780. keep = true;
  4781. }
  4782. break;
  4783. case "text":
  4784. keep = true;
  4785. selectOnly([element]);
  4786. textActions.start(element);
  4787. break;
  4788. case "path":
  4789. // set element to null here so that it is not removed nor finalized
  4790. element = null;
  4791. // continue to be set to true so that mouseMove happens
  4792. started = true;
  4793. var res = pathActions.mouseUp(evt, element, mouse_x, mouse_y);
  4794. element = res.element
  4795. keep = res.keep;
  4796. break;
  4797. case "pathedit":
  4798. keep = true;
  4799. element = null;
  4800. pathActions.mouseUp(evt);
  4801. break;
  4802. case "textedit":
  4803. keep = false;
  4804. element = null;
  4805. textActions.mouseUp(evt, mouse_x, mouse_y);
  4806. break;
  4807. case "rotate":
  4808. keep = true;
  4809. element = null;
  4810. current_mode = "select";
  4811. var batchCmd = canvas.finishUndoableChange();
  4812. if (!batchCmd.isEmpty()) {
  4813. addCommandToHistory(batchCmd);
  4814. }
  4815. // perform recalculation to weed out any stray identity transforms that might get stuck
  4816. recalculateAllSelectedDimensions();
  4817. call("changed", selectedElements);
  4818. break;
  4819. default:
  4820. // This could occur in an extension
  4821. break;
  4822. }
  4823. var ext_result = runExtensions("mouseUp", {
  4824. event: evt,
  4825. mouse_x: mouse_x,
  4826. mouse_y: mouse_y
  4827. }, true);
  4828. $.each(ext_result, function(i, r) {
  4829. if(r) {
  4830. keep = r.keep || keep;
  4831. element = r.element;
  4832. started = r.started || started;
  4833. }
  4834. });
  4835. if (!keep && element != null) {
  4836. element.parentNode.removeChild(element);
  4837. element = null;
  4838. var t = evt.target;
  4839. // if this element is in a group, go up until we reach the top-level group
  4840. // just below the layer groups
  4841. // TODO: once we implement links, we also would have to check for <a> elements
  4842. while (t.parentNode.parentNode.tagName == "g") {
  4843. t = t.parentNode;
  4844. }
  4845. // if we are not in the middle of creating a path, and we've clicked on some shape,
  4846. // then go to Select mode.
  4847. // WebKit returns <div> when the canvas is clicked, Firefox/Opera return <svg>
  4848. if ( (current_mode != "path" || current_path_pts.length == 0) &&
  4849. t.parentNode.id != "selectorParentGroup" &&
  4850. t.id != "svgcanvas" && t.id != "svgroot")
  4851. {
  4852. // switch into "select" mode if we've clicked on an element
  4853. canvas.setMode("select");
  4854. selectOnly([t], true);
  4855. }
  4856. } else if (element != null) {
  4857. canvas.addedNew = true;
  4858. if(useUnit) unitConvertAttrs(element);
  4859. var ani_dur = .2, c_ani;
  4860. if(opac_ani.beginElement && element.getAttribute('opacity') != cur_shape.opacity) {
  4861. c_ani = $(opac_ani).clone().attr({
  4862. to: cur_shape.opacity,
  4863. dur: ani_dur
  4864. }).appendTo(element);
  4865. try {
  4866. // Fails in FF4 on foreignObject
  4867. c_ani[0].beginElement();
  4868. } catch(e){}
  4869. } else {
  4870. ani_dur = 0;
  4871. }
  4872. // Ideally this would be done on the endEvent of the animation,
  4873. // but that doesn't seem to be supported in Webkit
  4874. setTimeout(function() {
  4875. if(c_ani) c_ani.remove();
  4876. element.setAttribute("opacity", cur_shape.opacity);
  4877. element.setAttribute("style", "pointer-events:inherit");
  4878. cleanupElement(element);
  4879. if(current_mode == "path") {
  4880. pathActions.toEditMode(element);
  4881. } else {
  4882. selectOnly([element], true);
  4883. }
  4884. // we create the insert command that is stored on the stack
  4885. // undo means to call cmd.unapply(), redo means to call cmd.apply()
  4886. addCommandToHistory(new InsertElementCommand(element));
  4887. call("changed",[element]);
  4888. }, ani_dur * 1000);
  4889. }
  4890. start_transform = null;
  4891. };
  4892. var dblClick = function(evt) {
  4893. var evt_target = evt.target;
  4894. var parent = evt_target.parentNode;
  4895. // Do nothing if already in current group
  4896. if(parent === current_group) return;
  4897. var mouse_target = getMouseTarget(evt);
  4898. if(mouse_target.tagName === 'text' && current_mode !== 'textedit') {
  4899. var pt = transformPoint( evt.pageX, evt.pageY, root_sctm );
  4900. textActions.select(mouse_target, pt.x, pt.y);
  4901. }
  4902. if(getRotationAngle(mouse_target)) {
  4903. // Don't do for rotated groups for now
  4904. return;
  4905. }
  4906. // Reset context
  4907. if(current_group) {
  4908. leaveContext();
  4909. }
  4910. if(parent.tagName !== 'g' || parent === current_layer || mouse_target === selectorManager.selectorParentGroup) {
  4911. // Escape from in-group edit
  4912. return;
  4913. }
  4914. setContext(mouse_target);
  4915. }
  4916. // prevent links from being followed in the canvas
  4917. var handleLinkInCanvas = function(e) {
  4918. e.preventDefault();
  4919. return false;
  4920. };
  4921. $(container).mousedown(mouseDown).mousemove(mouseMove).click(handleLinkInCanvas).dblclick(dblClick);
  4922. $(window).mouseup(mouseUp);
  4923. $(container).bind("mousewheel DOMMouseScroll", function(e){
  4924. if(!e.shiftKey) return;
  4925. e.preventDefault();
  4926. root_sctm = svgcontent.getScreenCTM().inverse();
  4927. var pt = transformPoint( e.pageX, e.pageY, root_sctm );
  4928. var bbox = {
  4929. 'x': pt.x,
  4930. 'y': pt.y,
  4931. 'width': 0,
  4932. 'height': 0
  4933. };
  4934. // Respond to mouse wheel in IE/Webkit/Opera.
  4935. // (It returns up/dn motion in multiples of 120)
  4936. if(e.wheelDelta) {
  4937. if (e.wheelDelta >= 120) {
  4938. bbox.factor = 2;
  4939. } else if (e.wheelDelta <= -120) {
  4940. bbox.factor = .5;
  4941. }
  4942. } else if(e.detail) {
  4943. if (e.detail > 0) {
  4944. bbox.factor = .5;
  4945. } else if (e.detail < 0) {
  4946. bbox.factor = 2;
  4947. }
  4948. }
  4949. if(!bbox.factor) return;
  4950. call("zoomed", bbox);
  4951. });
  4952. }());
  4953. // Function: preventClickDefault
  4954. // Prevents default browser click behaviour on the given element
  4955. //
  4956. // Parameters:
  4957. // img - The DOM element to prevent the cilck on
  4958. var preventClickDefault = function(img) {
  4959. $(img).click(function(e){e.preventDefault()});
  4960. }
  4961. // Group: Text edit functions
  4962. // Functions relating to editing text elements
  4963. var textActions = canvas.textActions = function() {
  4964. var curtext;
  4965. var textinput;
  4966. var cursor;
  4967. var selblock;
  4968. var blinker;
  4969. var chardata = [];
  4970. var textbb, transbb;
  4971. var matrix;
  4972. var last_x, last_y;
  4973. var allow_dbl;
  4974. function setCursor(index) {
  4975. var empty = (textinput.value === "");
  4976. $(textinput).focus();
  4977. if(!arguments.length) {
  4978. if(empty) {
  4979. index = 0;
  4980. } else {
  4981. if(textinput.selectionEnd !== textinput.selectionStart) return;
  4982. index = textinput.selectionEnd;
  4983. }
  4984. }
  4985. var charbb;
  4986. charbb = chardata[index];
  4987. if(!empty) {
  4988. textinput.setSelectionRange(index, index);
  4989. }
  4990. cursor = getElem("text_cursor");
  4991. if (!cursor) {
  4992. cursor = document.createElementNS(svgns, "line");
  4993. assignAttributes(cursor, {
  4994. 'id': "text_cursor",
  4995. 'stroke': "#333",
  4996. 'stroke-width': 1
  4997. });
  4998. cursor = getElem("selectorParentGroup").appendChild(cursor);
  4999. }
  5000. if(!blinker) {
  5001. blinker = setInterval(function() {
  5002. var show = (cursor.getAttribute('display') === 'none');
  5003. cursor.setAttribute('display', show?'inline':'none');
  5004. }, 600);
  5005. }
  5006. var start_pt = ptToScreen(charbb.x, textbb.y);
  5007. var end_pt = ptToScreen(charbb.x, (textbb.y + textbb.height));
  5008. assignAttributes(cursor, {
  5009. x1: start_pt.x,
  5010. y1: start_pt.y,
  5011. x2: end_pt.x,
  5012. y2: end_pt.y,
  5013. visibility: 'visible',
  5014. display: 'inline'
  5015. });
  5016. if(selblock) selblock.setAttribute('d', '');
  5017. }
  5018. function setSelection(start, end, skipInput) {
  5019. if(start === end) {
  5020. setCursor(end);
  5021. return;
  5022. }
  5023. if(!skipInput) {
  5024. textinput.setSelectionRange(start, end);
  5025. }
  5026. selblock = getElem("text_selectblock");
  5027. if (!selblock) {
  5028. selblock = document.createElementNS(svgns, "path");
  5029. assignAttributes(selblock, {
  5030. 'id': "text_selectblock",
  5031. 'fill': "green",
  5032. 'opacity': .5,
  5033. 'style': "pointer-events:none"
  5034. });
  5035. getElem("selectorParentGroup").appendChild(selblock);
  5036. }
  5037. var startbb = chardata[start];
  5038. var endbb = chardata[end];
  5039. cursor.setAttribute('visibility', 'hidden');
  5040. var tl = ptToScreen(startbb.x, textbb.y),
  5041. tr = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y),
  5042. bl = ptToScreen(startbb.x, textbb.y + textbb.height),
  5043. br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height);
  5044. var dstr = "M" + tl.x + "," + tl.y
  5045. + " L" + tr.x + "," + tr.y
  5046. + " " + br.x + "," + br.y
  5047. + " " + bl.x + "," + bl.y + "z";
  5048. assignAttributes(selblock, {
  5049. d: dstr,
  5050. 'display': 'inline'
  5051. });
  5052. }
  5053. function getIndexFromPoint(mouse_x, mouse_y) {
  5054. // Position cursor here
  5055. var pt = svgroot.createSVGPoint();
  5056. pt.x = mouse_x;
  5057. pt.y = mouse_y;
  5058. // No content, so return 0
  5059. if(chardata.length == 1) return 0;
  5060. // Determine if cursor should be on left or right of character
  5061. var charpos = curtext.getCharNumAtPosition(pt);
  5062. if(charpos < 0) {
  5063. // Out of text range, look at mouse coords
  5064. charpos = chardata.length - 2;
  5065. if(mouse_x <= chardata[0].x) {
  5066. charpos = 0;
  5067. }
  5068. } else if(charpos >= chardata.length - 2) {
  5069. charpos = chardata.length - 2;
  5070. }
  5071. var charbb = chardata[charpos];
  5072. var mid = charbb.x + (charbb.width/2);
  5073. if(mouse_x > mid) {
  5074. charpos++;
  5075. }
  5076. return charpos;
  5077. }
  5078. function setCursorFromPoint(mouse_x, mouse_y) {
  5079. setCursor(getIndexFromPoint(mouse_x, mouse_y));
  5080. }
  5081. function setEndSelectionFromPoint(x, y, apply) {
  5082. var i1 = textinput.selectionStart;
  5083. var i2 = getIndexFromPoint(x, y);
  5084. var start = Math.min(i1, i2);
  5085. var end = Math.max(i1, i2);
  5086. setSelection(start, end, !apply);
  5087. }
  5088. function screenToPt(x_in, y_in) {
  5089. var out = {
  5090. x: x_in,
  5091. y: y_in
  5092. }
  5093. out.x /= current_zoom;
  5094. out.y /= current_zoom;
  5095. if(matrix) {
  5096. var pt = transformPoint(out.x, out.y, matrix.inverse());
  5097. out.x = pt.x;
  5098. out.y = pt.y;
  5099. }
  5100. return out;
  5101. }
  5102. function ptToScreen(x_in, y_in) {
  5103. var out = {
  5104. x: x_in,
  5105. y: y_in
  5106. }
  5107. if(matrix) {
  5108. var pt = transformPoint(out.x, out.y, matrix);
  5109. out.x = pt.x;
  5110. out.y = pt.y;
  5111. }
  5112. out.x *= current_zoom;
  5113. out.y *= current_zoom;
  5114. return out;
  5115. }
  5116. function hideCursor() {
  5117. if(cursor) {
  5118. cursor.setAttribute('visibility', 'hidden');
  5119. }
  5120. }
  5121. function selectAll(evt) {
  5122. setSelection(0, curtext.textContent.length);
  5123. $(this).unbind(evt);
  5124. }
  5125. function selectWord(evt) {
  5126. if(!allow_dbl || !curtext) return;
  5127. var ept = transformPoint( evt.pageX, evt.pageY, root_sctm ),
  5128. mouse_x = ept.x * current_zoom,
  5129. mouse_y = ept.y * current_zoom;
  5130. var pt = screenToPt(mouse_x, mouse_y);
  5131. var index = getIndexFromPoint(pt.x, pt.y);
  5132. var str = curtext.textContent;
  5133. var first = str.substr(0, index).replace(/[a-z0-9]+$/i, '').length;
  5134. var m = str.substr(index).match(/^[a-z0-9]+/i);
  5135. var last = (m?m[0].length:0) + index;
  5136. setSelection(first, last);
  5137. // Set tripleclick
  5138. $(evt.target).click(selectAll);
  5139. setTimeout(function() {
  5140. $(evt.target).unbind('click', selectAll);
  5141. }, 300);
  5142. }
  5143. return {
  5144. select: function(target, x, y) {
  5145. curtext = target;
  5146. textActions.toEditMode(x, y);
  5147. },
  5148. start: function(elem) {
  5149. curtext = elem;
  5150. textActions.toEditMode();
  5151. },
  5152. mouseDown: function(evt, mouse_target, start_x, start_y) {
  5153. var pt = screenToPt(start_x, start_y);
  5154. textinput.focus();
  5155. setCursorFromPoint(pt.x, pt.y);
  5156. last_x = start_x;
  5157. last_y = start_y;
  5158. // TODO: Find way to block native selection
  5159. },
  5160. mouseMove: function(mouse_x, mouse_y) {
  5161. var pt = screenToPt(mouse_x, mouse_y);
  5162. setEndSelectionFromPoint(pt.x, pt.y);
  5163. },
  5164. mouseUp: function(evt, mouse_x, mouse_y) {
  5165. var pt = screenToPt(mouse_x, mouse_y);
  5166. setEndSelectionFromPoint(pt.x, pt.y, true);
  5167. // TODO: Find a way to make this work: Use transformed BBox instead of evt.target
  5168. // if(last_x === mouse_x && last_y === mouse_y
  5169. // && !Utils.rectsIntersect(transbb, {x: pt.x, y: pt.y, width:0, height:0})) {
  5170. // textActions.toSelectMode(true);
  5171. // }
  5172. if(last_x === mouse_x && last_y === mouse_y && evt.target !== curtext) {
  5173. textActions.toSelectMode(true);
  5174. }
  5175. },
  5176. setCursor: setCursor,
  5177. toEditMode: function(x, y) {
  5178. allow_dbl = false;
  5179. current_mode = "textedit";
  5180. selectorManager.requestSelector(curtext).showGrips(false);
  5181. // Make selector group accept clicks
  5182. var sel = selectorManager.requestSelector(curtext).selectorRect;
  5183. textActions.init();
  5184. $(curtext).css('cursor', 'text');
  5185. // if(support.editableText) {
  5186. // curtext.setAttribute('editable', 'simple');
  5187. // return;
  5188. // }
  5189. if(!arguments.length) {
  5190. setCursor();
  5191. } else {
  5192. var pt = screenToPt(x, y);
  5193. setCursorFromPoint(pt.x, pt.y);
  5194. }
  5195. setTimeout(function() {
  5196. allow_dbl = true;
  5197. }, 300);
  5198. },
  5199. toSelectMode: function(selectElem) {
  5200. current_mode = "select";
  5201. clearInterval(blinker);
  5202. blinker = null;
  5203. if(selblock) $(selblock).attr('display','none');
  5204. if(cursor) $(cursor).attr('visibility','hidden');
  5205. $(curtext).css('cursor', 'move');
  5206. if(selectElem) {
  5207. clearSelection();
  5208. $(curtext).css('cursor', 'move');
  5209. call("selected", [curtext]);
  5210. addToSelection([curtext], true);
  5211. }
  5212. if(curtext && !curtext.textContent.length) {
  5213. // No content, so delete
  5214. canvas.deleteSelectedElements();
  5215. }
  5216. $(textinput).blur();
  5217. curtext = false;
  5218. // if(support.editableText) {
  5219. // curtext.removeAttribute('editable');
  5220. // }
  5221. },
  5222. setInputElem: function(elem) {
  5223. textinput = elem;
  5224. // $(textinput).blur(hideCursor);
  5225. },
  5226. clear: function() {
  5227. if(current_mode == "textedit") {
  5228. textActions.toSelectMode();
  5229. }
  5230. },
  5231. init: function(inputElem) {
  5232. if(!curtext) return;
  5233. // if(support.editableText) {
  5234. // curtext.select();
  5235. // return;
  5236. // }
  5237. if(!curtext.parentNode) {
  5238. // Result of the ffClone, need to get correct element
  5239. curtext = selectedElements[0];
  5240. selectorManager.requestSelector(curtext).showGrips(false);
  5241. }
  5242. var str = curtext.textContent;
  5243. var len = str.length;
  5244. var xform = curtext.getAttribute('transform');
  5245. textbb = getBBox(curtext);
  5246. matrix = xform?getMatrix(curtext):null;
  5247. chardata = Array(len);
  5248. textinput.focus();
  5249. $(curtext).unbind('dblclick', selectWord).dblclick(selectWord);
  5250. if(!len) {
  5251. var end = {x: textbb.x + (textbb.width/2), width: 0};
  5252. }
  5253. for(var i=0; i<len; i++) {
  5254. var start = curtext.getStartPositionOfChar(i);
  5255. var end = curtext.getEndPositionOfChar(i);
  5256. // Get a "bbox" equivalent for each character. Uses the
  5257. // bbox data of the actual text for y, height purposes
  5258. // TODO: Decide if y, width and height are actually necessary
  5259. chardata[i] = {
  5260. x: start.x,
  5261. y: textbb.y, // start.y?
  5262. width: end.x - start.x,
  5263. height: textbb.height
  5264. };
  5265. }
  5266. // Add a last bbox for cursor at end of text
  5267. chardata.push({
  5268. x: end.x,
  5269. width: 0
  5270. });
  5271. setSelection(textinput.selectionStart, textinput.selectionEnd, true);
  5272. }
  5273. }
  5274. }();
  5275. // Group: Path edit functions
  5276. // Functions relating to editing path elements
  5277. var pathActions = this.pathActions = function() {
  5278. var subpath = false;
  5279. var pathData = {};
  5280. var current_path;
  5281. var path;
  5282. var segData = {
  5283. 2: ['x','y'],
  5284. 4: ['x','y'],
  5285. 6: ['x','y','x1','y1','x2','y2'],
  5286. 8: ['x','y','x1','y1'],
  5287. 10: ['x','y','r1','r2','angle','largeArcFlag','sweepFlag'],
  5288. 12: ['x'],
  5289. 14: ['y'],
  5290. 16: ['x','y','x2','y2'],
  5291. 18: ['x','y']
  5292. };
  5293. function retPath() {
  5294. return path;
  5295. }
  5296. function resetD(p) {
  5297. p.setAttribute("d", pathActions.convertPath(p));
  5298. }
  5299. function insertItemBefore(elem, newseg, index) {
  5300. // Support insertItemBefore on paths for FF2
  5301. var list = elem.pathSegList;
  5302. if(support.pathInsertItemBefore) {
  5303. list.insertItemBefore(newseg, index);
  5304. return;
  5305. }
  5306. var len = list.numberOfItems;
  5307. var arr = [];
  5308. for(var i=0; i<len; i++) {
  5309. var cur_seg = list.getItem(i);
  5310. arr.push(cur_seg)
  5311. }
  5312. list.clear();
  5313. for(var i=0; i<len; i++) {
  5314. if(i == index) { //index+1
  5315. list.appendItem(newseg);
  5316. }
  5317. list.appendItem(arr[i]);
  5318. }
  5319. }
  5320. // TODO: See if this should just live in replacePathSeg
  5321. function ptObjToArr(type, seg_item) {
  5322. var arr = segData[type], len = arr.length;
  5323. var out = Array(len);
  5324. for(var i=0; i<len; i++) {
  5325. out[i] = seg_item[arr[i]];
  5326. }
  5327. return out;
  5328. }
  5329. function getGripContainer() {
  5330. var c = getElem("pathpointgrip_container");
  5331. if (!c) {
  5332. var parent = getElem("selectorParentGroup");
  5333. c = parent.appendChild(document.createElementNS(svgns, "g"));
  5334. c.id = "pathpointgrip_container";
  5335. }
  5336. return c;
  5337. }
  5338. var addPointGrip = function(index, x, y) {
  5339. // create the container of all the point grips
  5340. var pointGripContainer = getGripContainer();
  5341. var pointGrip = getElem("pathpointgrip_"+index);
  5342. // create it
  5343. if (!pointGrip) {
  5344. pointGrip = document.createElementNS(svgns, "circle");
  5345. assignAttributes(pointGrip, {
  5346. 'id': "pathpointgrip_" + index,
  5347. 'display': "none",
  5348. 'r': 4,
  5349. 'fill': "#0FF",
  5350. 'stroke': "#00F",
  5351. 'stroke-width': 2,
  5352. 'cursor': 'move',
  5353. 'style': 'pointer-events:all',
  5354. 'xlink:title': uiStrings.pathNodeTooltip
  5355. });
  5356. pointGrip = pointGripContainer.appendChild(pointGrip);
  5357. var grip = $('#pathpointgrip_'+index);
  5358. grip.dblclick(function() {
  5359. if(path) path.setSegType();
  5360. });
  5361. }
  5362. if(x && y) {
  5363. // set up the point grip element and display it
  5364. assignAttributes(pointGrip, {
  5365. 'cx': x,
  5366. 'cy': y,
  5367. 'display': "inline"
  5368. });
  5369. }
  5370. return pointGrip;
  5371. };
  5372. var getPointGrip = function(seg, update) {
  5373. var index = seg.index;
  5374. var pointGrip = addPointGrip(index);
  5375. if(update) {
  5376. var pt = getGripPt(seg);
  5377. assignAttributes(pointGrip, {
  5378. 'cx': pt.x,
  5379. 'cy': pt.y,
  5380. 'display': "inline"
  5381. });
  5382. }
  5383. return pointGrip;
  5384. }
  5385. var getSegSelector = function(seg, update) {
  5386. var index = seg.index;
  5387. var segLine = getElem("segline_" + index);
  5388. if(!segLine) {
  5389. var pointGripContainer = getGripContainer();
  5390. // create segline
  5391. segLine = document.createElementNS(svgns, "path");
  5392. assignAttributes(segLine, {
  5393. 'id': "segline_" + index,
  5394. 'display': 'none',
  5395. 'fill': "none",
  5396. 'stroke': "#0FF",
  5397. 'stroke-width': 2,
  5398. 'style':'pointer-events:none',
  5399. 'd': 'M0,0 0,0'
  5400. });
  5401. pointGripContainer.appendChild(segLine);
  5402. }
  5403. if(update) {
  5404. var prev = seg.prev;
  5405. if(!prev) {
  5406. segLine.setAttribute("display", "none");
  5407. return segLine;
  5408. }
  5409. var pt = getGripPt(prev);
  5410. // Set start point
  5411. replacePathSeg(2, 0, [pt.x, pt.y], segLine);
  5412. var pts = ptObjToArr(seg.type, seg.item, true);
  5413. for(var i=0; i < pts.length; i+=2) {
  5414. var pt = getGripPt(seg, {x:pts[i], y:pts[i+1]});
  5415. pts[i] = pt.x;
  5416. pts[i+1] = pt.y;
  5417. }
  5418. replacePathSeg(seg.type, 1, pts, segLine);
  5419. }
  5420. return segLine;
  5421. }
  5422. var getControlPoints = function(seg) {
  5423. var item = seg.item;
  5424. var index = seg.index;
  5425. if(!("x1" in item) || !("x2" in item)) return null;
  5426. var cpt = {};
  5427. var pointGripContainer = getGripContainer();
  5428. // Note that this is intentionally not seg.prev.item
  5429. var prev = path.segs[index-1].item;
  5430. var seg_items = [prev, item];
  5431. for(var i=1; i<3; i++) {
  5432. var id = index + 'c' + i;
  5433. var ctrlLine = cpt['c' + i + '_line'] = getElem("ctrlLine_"+id);
  5434. if(!ctrlLine) {
  5435. ctrlLine = document.createElementNS(svgns, "line");
  5436. assignAttributes(ctrlLine, {
  5437. 'id': "ctrlLine_"+id,
  5438. 'stroke': "#555",
  5439. 'stroke-width': 1,
  5440. "style": "pointer-events:none"
  5441. });
  5442. pointGripContainer.appendChild(ctrlLine);
  5443. }
  5444. var pt = getGripPt(seg, {x:item['x' + i], y:item['y' + i]});
  5445. var gpt = getGripPt(seg, {x:seg_items[i-1].x, y:seg_items[i-1].y});
  5446. assignAttributes(ctrlLine, {
  5447. 'x1': pt.x,
  5448. 'y1': pt.y,
  5449. 'x2': gpt.x,
  5450. 'y2': gpt.y,
  5451. 'display': "inline"
  5452. });
  5453. cpt['c' + i + '_line'] = ctrlLine;
  5454. var pointGrip = cpt['c' + i] = getElem("ctrlpointgrip_"+id);
  5455. // create it
  5456. if (!pointGrip) {
  5457. pointGrip = document.createElementNS(svgns, "circle");
  5458. assignAttributes(pointGrip, {
  5459. 'id': "ctrlpointgrip_" + id,
  5460. 'display': "none",
  5461. 'r': 4,
  5462. 'fill': "#0FF",
  5463. 'stroke': "#55F",
  5464. 'stroke-width': 1,
  5465. 'cursor': 'move',
  5466. 'style': 'pointer-events:all',
  5467. 'xlink:title': uiStrings.pathCtrlPtTooltip
  5468. });
  5469. pointGripContainer.appendChild(pointGrip);
  5470. }
  5471. assignAttributes(pointGrip, {
  5472. 'cx': pt.x,
  5473. 'cy': pt.y,
  5474. 'display': "inline"
  5475. });
  5476. cpt['c' + i] = pointGrip;
  5477. }
  5478. return cpt;
  5479. }
  5480. function getGripPt(seg, alt_pt) {
  5481. var out = {
  5482. x: alt_pt? alt_pt.x : seg.item.x,
  5483. y: alt_pt? alt_pt.y : seg.item.y
  5484. }, path = seg.path;
  5485. if(path.matrix) {
  5486. var pt = transformPoint(out.x, out.y, path.matrix);
  5487. out = pt;
  5488. }
  5489. out.x *= current_zoom;
  5490. out.y *= current_zoom;
  5491. return out;
  5492. }
  5493. function getPointFromGrip(pt, path) {
  5494. var out = {
  5495. x: pt.x,
  5496. y: pt.y
  5497. }
  5498. if(path.matrix) {
  5499. var pt = transformPoint(out.x, out.y, path.imatrix);
  5500. out.x = pt.x;
  5501. out.y = pt.y;
  5502. }
  5503. out.x /= current_zoom;
  5504. out.y /= current_zoom;
  5505. return out;
  5506. }
  5507. function Segment(index, item) {
  5508. var s = this;
  5509. s.index = index;
  5510. s.selected = false;
  5511. s.type = item.pathSegType;
  5512. var grip;
  5513. s.addGrip = function() {
  5514. grip = s.ptgrip = getPointGrip(s, true);
  5515. s.ctrlpts = getControlPoints(s, true);
  5516. s.segsel = getSegSelector(s, true);
  5517. }
  5518. s.item = item;
  5519. s.show = function(y) {
  5520. if(grip) {
  5521. grip.setAttribute("display", y?"inline":"none");
  5522. s.segsel.setAttribute("display", y?"inline":"none");
  5523. // Show/hide all control points if available
  5524. s.showCtrlPts(y);
  5525. }
  5526. }
  5527. s.select = function(y) {
  5528. if(grip) {
  5529. grip.setAttribute("stroke", y?"#0FF":"#00F");
  5530. s.segsel.setAttribute("display", y?"inline":"none");
  5531. if(s.ctrlpts) {
  5532. s.selectCtrls(y);
  5533. }
  5534. s.selected = y;
  5535. }
  5536. }
  5537. s.selectCtrls = function(y) {
  5538. $('#ctrlpointgrip_' + s.index + 'c1, #ctrlpointgrip_' + s.index + 'c2').attr('fill',y?'#0FF':'#EEE');
  5539. }
  5540. s.update = function(full) {
  5541. item = s.item;
  5542. if(grip) {
  5543. var pt = getGripPt(s);
  5544. assignAttributes(grip, {
  5545. 'cx': pt.x,
  5546. 'cy': pt.y
  5547. });
  5548. getSegSelector(s, true);
  5549. if(s.ctrlpts) {
  5550. if(full) {
  5551. s.item = path.elem.pathSegList.getItem(s.index);
  5552. s.type = s.item.pathSegType;
  5553. }
  5554. getControlPoints(s);
  5555. }
  5556. // this.segsel.setAttribute("display", y?"inline":"none");
  5557. }
  5558. }
  5559. s.move = function(dx, dy) {
  5560. var item = s.item;
  5561. var cur = s;
  5562. if(cur.ctrlpts) {
  5563. var cur_pts = [item.x += dx, item.y += dy,
  5564. item.x1, item.y1, item.x2 += dx, item.y2 += dy];
  5565. } else {
  5566. var cur_pts = [item.x += dx, item.y += dy];
  5567. }
  5568. replacePathSeg(cur.type, cur.index, cur_pts);
  5569. if(s.next && s.next.ctrlpts) {
  5570. var next = s.next.item;
  5571. var next_pts = [next.x, next.y,
  5572. next.x1 += dx, next.y1 += dy, next.x2, next.y2];
  5573. replacePathSeg(s.next.type, s.next.index, next_pts);
  5574. }
  5575. if(s.mate) {
  5576. // The last point of a closed subpath has a "mate",
  5577. // which is the "M" segment of the subpath
  5578. var item = s.mate.item;
  5579. var pts = [item.x += dx, item.y += dy];
  5580. replacePathSeg(s.mate.type, s.mate.index, pts);
  5581. // Has no grip, so does not need "updating"?
  5582. }
  5583. s.update(true);
  5584. if(s.next) s.next.update(true);
  5585. }
  5586. s.setLinked = function(num) {
  5587. var seg, anum, pt;
  5588. if(num == 2) {
  5589. anum = 1;
  5590. seg = s.next;
  5591. if(!seg) return;
  5592. pt = s.item;
  5593. } else {
  5594. anum = 2;
  5595. seg = s.prev;
  5596. if(!seg) return;
  5597. pt = seg.item;
  5598. }
  5599. var item = seg.item;
  5600. item['x' + anum] = pt.x + (pt.x - s.item['x' + num]);
  5601. item['y' + anum] = pt.y + (pt.y - s.item['y' + num]);
  5602. var pts = [item.x,item.y,
  5603. item.x1,item.y1, item.x2,item.y2];
  5604. replacePathSeg(seg.type, seg.index, pts);
  5605. seg.update(true);
  5606. }
  5607. s.moveCtrl = function(num, dx, dy) {
  5608. var item = s.item;
  5609. item['x' + num] += dx;
  5610. item['y' + num] += dy;
  5611. var pts = [item.x,item.y,
  5612. item.x1,item.y1, item.x2,item.y2];
  5613. replacePathSeg(s.type, s.index, pts);
  5614. s.update(true);
  5615. }
  5616. s.setType = function(new_type, pts) {
  5617. replacePathSeg(new_type, index, pts);
  5618. s.type = new_type;
  5619. s.item = path.elem.pathSegList.getItem(index);
  5620. s.showCtrlPts(new_type === 6);
  5621. s.ctrlpts = getControlPoints(s);
  5622. s.update(true);
  5623. }
  5624. s.showCtrlPts = function(y) {
  5625. if(s.ctrlpts) {
  5626. for (var o in s.ctrlpts) {
  5627. s.ctrlpts[o].setAttribute("display", y?"inline":"none");
  5628. }
  5629. }
  5630. }
  5631. }
  5632. function Path(elem) {
  5633. if(!elem || elem.tagName !== "path") return false;
  5634. var p = path = this;
  5635. this.elem = elem;
  5636. this.segs = [];
  5637. this.selected_pts = [];
  5638. // Reset path data
  5639. this.init = function() {
  5640. // Hide all grips, etc
  5641. $(getGripContainer()).find("*").attr("display", "none");
  5642. var segList = elem.pathSegList;
  5643. var len = segList.numberOfItems;
  5644. p.segs = [];
  5645. p.selected_pts = [];
  5646. p.first_seg = null;
  5647. // Set up segs array
  5648. for(var i=0; i < len; i++) {
  5649. var item = segList.getItem(i);
  5650. var segment = new Segment(i, item);
  5651. segment.path = p;
  5652. p.segs.push(segment);
  5653. }
  5654. var segs = p.segs;
  5655. var start_i = null;
  5656. for(var i=0; i < len; i++) {
  5657. var seg = segs[i];
  5658. var next_seg = (i+1) >= len ? null : segs[i+1];
  5659. var prev_seg = (i-1) < 0 ? null : segs[i-1];
  5660. if(seg.type === 2) {
  5661. if(prev_seg && prev_seg.type !== 1) {
  5662. // New sub-path, last one is open,
  5663. // so add a grip to last sub-path's first point
  5664. var start_seg = segs[start_i];
  5665. start_seg.next = segs[start_i+1];
  5666. start_seg.next.prev = start_seg;
  5667. start_seg.addGrip();
  5668. }
  5669. // Remember that this is a starter seg
  5670. start_i = i;
  5671. } else if(next_seg && next_seg.type === 1) {
  5672. // This is the last real segment of a closed sub-path
  5673. // Next is first seg after "M"
  5674. seg.next = segs[start_i+1];
  5675. // First seg after "M"'s prev is this
  5676. seg.next.prev = seg;
  5677. seg.mate = segs[start_i];
  5678. seg.addGrip();
  5679. if(p.first_seg == null) {
  5680. p.first_seg = seg;
  5681. }
  5682. } else if(!next_seg) {
  5683. if(seg.type !== 1) {
  5684. // Last seg, doesn't close so add a grip
  5685. // to last sub-path's first point
  5686. var start_seg = segs[start_i];
  5687. start_seg.next = segs[start_i+1];
  5688. start_seg.next.prev = start_seg;
  5689. start_seg.addGrip();
  5690. seg.addGrip();
  5691. if(!p.first_seg) {
  5692. // Open path, so set first as real first and add grip
  5693. p.first_seg = segs[start_i];
  5694. }
  5695. }
  5696. } else if(seg.type !== 1){
  5697. // Regular segment, so add grip and its "next"
  5698. seg.addGrip();
  5699. // Don't set its "next" if it's an "M"
  5700. if(next_seg && next_seg.type !== 2) {
  5701. seg.next = next_seg;
  5702. seg.next.prev = seg;
  5703. }
  5704. }
  5705. }
  5706. return p;
  5707. }
  5708. this.init();
  5709. // Update position of all points
  5710. this.update = function() {
  5711. if(getRotationAngle(p.elem)) {
  5712. p.matrix = getMatrix(path.elem);
  5713. p.imatrix = p.matrix.inverse();
  5714. }
  5715. p.eachSeg(function(i) {
  5716. this.item = elem.pathSegList.getItem(i);
  5717. this.update();
  5718. });
  5719. return p;
  5720. }
  5721. this.eachSeg = function(fn) {
  5722. var len = p.segs.length
  5723. for(var i=0; i < len; i++) {
  5724. var ret = fn.call(p.segs[i], i);
  5725. if(ret === false) break;
  5726. }
  5727. }
  5728. this.addSeg = function(index) {
  5729. // Adds a new segment
  5730. var seg = p.segs[index];
  5731. if(!seg.prev) return;
  5732. var prev = seg.prev;
  5733. var newseg;
  5734. switch(seg.item.pathSegType) {
  5735. case 4:
  5736. var new_x = (seg.item.x + prev.item.x) / 2;
  5737. var new_y = (seg.item.y + prev.item.y) / 2;
  5738. newseg = elem.createSVGPathSegLinetoAbs(new_x, new_y);
  5739. break;
  5740. case 6: //make it a curved segment to preserve the shape (WRS)
  5741. // http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm#Geometric_interpretation
  5742. var p0_x = (prev.item.x + seg.item.x1)/2;
  5743. var p1_x = (seg.item.x1 + seg.item.x2)/2;
  5744. var p2_x = (seg.item.x2 + seg.item.x)/2;
  5745. var p01_x = (p0_x + p1_x)/2;
  5746. var p12_x = (p1_x + p2_x)/2;
  5747. var new_x = (p01_x + p12_x)/2;
  5748. var p0_y = (prev.item.y + seg.item.y1)/2;
  5749. var p1_y = (seg.item.y1 + seg.item.y2)/2;
  5750. var p2_y = (seg.item.y2 + seg.item.y)/2;
  5751. var p01_y = (p0_y + p1_y)/2;
  5752. var p12_y = (p1_y + p2_y)/2;
  5753. var new_y = (p01_y + p12_y)/2;
  5754. newseg = elem.createSVGPathSegCurvetoCubicAbs(new_x,new_y, p0_x,p0_y, p01_x,p01_y);
  5755. var pts = [seg.item.x,seg.item.y,p12_x,p12_y,p2_x,p2_y];
  5756. replacePathSeg(seg.type,index,pts);
  5757. break;
  5758. }
  5759. insertItemBefore(elem, newseg, index);
  5760. }
  5761. this.deleteSeg = function(index) {
  5762. var seg = p.segs[index];
  5763. var list = elem.pathSegList;
  5764. seg.show(false);
  5765. var next = seg.next;
  5766. if(seg.mate) {
  5767. // Make the next point be the "M" point
  5768. var pt = [next.item.x, next.item.y];
  5769. replacePathSeg(2, next.index, pt);
  5770. // Reposition last node
  5771. replacePathSeg(4, seg.index, pt);
  5772. list.removeItem(seg.mate.index);
  5773. } else if(!seg.prev) {
  5774. // First node of open path, make next point the M
  5775. var item = seg.item;
  5776. var pt = [next.item.x, next.item.y];
  5777. replacePathSeg(2, seg.next.index, pt);
  5778. list.removeItem(index);
  5779. } else {
  5780. list.removeItem(index);
  5781. }
  5782. }
  5783. this.endChanges = function(text) {
  5784. if(isWebkit) resetD(p.elem);
  5785. var cmd = new ChangeElementCommand(elem, {d: p.last_d}, text);
  5786. addCommandToHistory(cmd);
  5787. call("changed", [elem]);
  5788. }
  5789. this.subpathIsClosed = function(index) {
  5790. var closed = false;
  5791. // Check if subpath is already open
  5792. path.eachSeg(function(i) {
  5793. if(i <= index) return true;
  5794. if(this.type === 2) {
  5795. // Found M first, so open
  5796. return false;
  5797. } else if(this.type === 1) {
  5798. // Found Z first, so closed
  5799. closed = true;
  5800. return false;
  5801. }
  5802. });
  5803. return closed;
  5804. }
  5805. this.addPtsToSelection = function(indexes) {
  5806. if(!$.isArray(indexes)) indexes = [indexes];
  5807. for(var i=0; i< indexes.length; i++) {
  5808. var index = indexes[i];
  5809. var seg = p.segs[index];
  5810. if(seg.ptgrip) {
  5811. if(p.selected_pts.indexOf(index) == -1 && index >= 0) {
  5812. p.selected_pts.push(index);
  5813. }
  5814. }
  5815. };
  5816. p.selected_pts.sort();
  5817. var i = p.selected_pts.length,
  5818. grips = new Array(i);
  5819. // Loop through points to be selected and highlight each
  5820. while(i--) {
  5821. var pt = p.selected_pts[i];
  5822. var seg = p.segs[pt];
  5823. seg.select(true);
  5824. grips[i] = seg.ptgrip;
  5825. }
  5826. // TODO: Correct this:
  5827. pathActions.canDeleteNodes = true;
  5828. pathActions.closed_subpath = p.subpathIsClosed(p.selected_pts[0]);
  5829. call("selected", grips);
  5830. }
  5831. this.removePtFromSelection = function(index) {
  5832. var pos = p.selected_pts.indexOf(index);
  5833. if(pos == -1) {
  5834. return;
  5835. }
  5836. p.segs[index].select(false);
  5837. p.selected_pts.splice(pos, 1);
  5838. }
  5839. this.clearSelection = function() {
  5840. p.eachSeg(function(i) {
  5841. this.select(false);
  5842. });
  5843. p.selected_pts = [];
  5844. }
  5845. this.selectPt = function(pt, ctrl_num) {
  5846. p.clearSelection();
  5847. if(pt == null) {
  5848. p.eachSeg(function(i) {
  5849. if(this.prev) {
  5850. pt = i;
  5851. }
  5852. });
  5853. }
  5854. p.addPtsToSelection(pt);
  5855. if(ctrl_num) {
  5856. p.dragctrl = ctrl_num;
  5857. if(link_control_pts) {
  5858. p.segs[pt].setLinked(ctrl_num);
  5859. }
  5860. }
  5861. }
  5862. this.storeD = function() {
  5863. this.last_d = elem.getAttribute('d');
  5864. }
  5865. this.show = function(y) {
  5866. // Shows this path's segment grips
  5867. p.eachSeg(function() {
  5868. this.show(y);
  5869. });
  5870. if(y) {
  5871. p.selectPt(p.first_seg.index);
  5872. }
  5873. return p;
  5874. }
  5875. // Move selected points
  5876. this.movePts = function(d_x, d_y) {
  5877. var i = p.selected_pts.length;
  5878. while(i--) {
  5879. var seg = p.segs[p.selected_pts[i]];
  5880. seg.move(d_x, d_y);
  5881. }
  5882. }
  5883. this.moveCtrl = function(d_x, d_y) {
  5884. var seg = p.segs[p.selected_pts[0]];
  5885. seg.moveCtrl(p.dragctrl, d_x, d_y);
  5886. if(link_control_pts) {
  5887. seg.setLinked(p.dragctrl);
  5888. }
  5889. }
  5890. this.setSegType = function(new_type) {
  5891. p.storeD();
  5892. var i = p.selected_pts.length;
  5893. var text;
  5894. while(i--) {
  5895. var sel_pt = p.selected_pts[i];
  5896. // Selected seg
  5897. var cur = p.segs[sel_pt];
  5898. var prev = cur.prev;
  5899. if(!prev) continue;
  5900. if(!new_type) { // double-click, so just toggle
  5901. text = "Toggle Path Segment Type";
  5902. // Toggle segment to curve/straight line
  5903. var old_type = cur.type;
  5904. new_type = (old_type == 6) ? 4 : 6;
  5905. }
  5906. new_type = new_type-0;
  5907. var cur_x = cur.item.x;
  5908. var cur_y = cur.item.y;
  5909. var prev_x = prev.item.x;
  5910. var prev_y = prev.item.y;
  5911. var points;
  5912. switch ( new_type ) {
  5913. case 6:
  5914. if(cur.olditem) {
  5915. var old = cur.olditem;
  5916. points = [cur_x,cur_y, old.x1,old.y1, old.x2,old.y2];
  5917. } else {
  5918. var diff_x = cur_x - prev_x;
  5919. var diff_y = cur_y - prev_y;
  5920. // get control points from straight line segment
  5921. /*
  5922. var ct1_x = (prev_x + (diff_y/2));
  5923. var ct1_y = (prev_y - (diff_x/2));
  5924. var ct2_x = (cur_x + (diff_y/2));
  5925. var ct2_y = (cur_y - (diff_x/2));
  5926. */
  5927. //create control points on the line to preserve the shape (WRS)
  5928. var ct1_x = (prev_x + (diff_x/3));
  5929. var ct1_y = (prev_y + (diff_y/3));
  5930. var ct2_x = (cur_x - (diff_x/3));
  5931. var ct2_y = (cur_y - (diff_y/3));
  5932. points = [cur_x,cur_y, ct1_x,ct1_y, ct2_x,ct2_y];
  5933. }
  5934. break;
  5935. case 4:
  5936. points = [cur_x,cur_y];
  5937. // Store original prevve segment nums
  5938. cur.olditem = cur.item;
  5939. break;
  5940. }
  5941. cur.setType(new_type, points);
  5942. }
  5943. path.endChanges(text);
  5944. return;
  5945. }
  5946. }
  5947. function getPath(elem) {
  5948. var p = pathData[elem.id];
  5949. if(!p) p = pathData[elem.id] = new Path(elem);
  5950. return p;
  5951. }
  5952. var pathFuncs = [],
  5953. current_path = null,
  5954. current_path_pts = [],
  5955. link_control_pts = false,
  5956. hasMoved = false;
  5957. // This function converts a polyline (created by the fh_path tool) into
  5958. // a path element and coverts every three line segments into a single bezier
  5959. // curve in an attempt to smooth out the free-hand
  5960. var smoothPolylineIntoPath = function(element) {
  5961. var points = element.points;
  5962. var N = points.numberOfItems;
  5963. if (N >= 4) {
  5964. // loop through every 3 points and convert to a cubic bezier curve segment
  5965. //
  5966. // NOTE: this is cheating, it means that every 3 points has the potential to
  5967. // be a corner instead of treating each point in an equal manner. In general,
  5968. // this technique does not look that good.
  5969. //
  5970. // I am open to better ideas!
  5971. //
  5972. // Reading:
  5973. // - http://www.efg2.com/Lab/Graphics/Jean-YvesQueinecBezierCurves.htm
  5974. // - http://www.codeproject.com/KB/graphics/BezierSpline.aspx?msg=2956963
  5975. // - http://www.ian-ko.com/ET_GeoWizards/UserGuide/smooth.htm
  5976. // - http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-der.html
  5977. var curpos = points.getItem(0), prevCtlPt = null;
  5978. var d = [];
  5979. d.push(["M",curpos.x,",",curpos.y," C"].join(""));
  5980. for (var i = 1; i <= (N-4); i += 3) {
  5981. var ct1 = points.getItem(i);
  5982. var ct2 = points.getItem(i+1);
  5983. var end = points.getItem(i+2);
  5984. // if the previous segment had a control point, we want to smooth out
  5985. // the control points on both sides
  5986. if (prevCtlPt) {
  5987. var newpts = smoothControlPoints( prevCtlPt, ct1, curpos );
  5988. if (newpts && newpts.length == 2) {
  5989. var prevArr = d[d.length-1].split(',');
  5990. prevArr[2] = newpts[0].x;
  5991. prevArr[3] = newpts[0].y;
  5992. d[d.length-1] = prevArr.join(',');
  5993. ct1 = newpts[1];
  5994. }
  5995. }
  5996. d.push([ct1.x,ct1.y,ct2.x,ct2.y,end.x,end.y].join(','));
  5997. curpos = end;
  5998. prevCtlPt = ct2;
  5999. }
  6000. // handle remaining line segments
  6001. d.push("L");
  6002. for(;i < N;++i) {
  6003. var pt = points.getItem(i);
  6004. d.push([pt.x,pt.y].join(","));
  6005. }
  6006. d = d.join(" ");
  6007. // create new path element
  6008. element = addSvgElementFromJson({
  6009. "element": "path",
  6010. "curStyles": true,
  6011. "attr": {
  6012. "id": getId(),
  6013. "d": d,
  6014. "fill": "none"
  6015. }
  6016. });
  6017. call("changed",[element]);
  6018. }
  6019. return element;
  6020. };
  6021. // This replaces the segment at the given index. Type is given as number.
  6022. var replacePathSeg = function(type, index, pts, elem) {
  6023. var path = elem || retPath().elem;
  6024. var func = 'createSVGPathSeg' + pathFuncs[type];
  6025. var seg = path[func].apply(path, pts);
  6026. if(support.pathReplaceItem) {
  6027. path.pathSegList.replaceItem(seg, index);
  6028. } else {
  6029. var segList = path.pathSegList;
  6030. var len = segList.numberOfItems;
  6031. var arr = [];
  6032. for(var i=0; i<len; i++) {
  6033. var cur_seg = segList.getItem(i);
  6034. arr.push(cur_seg)
  6035. }
  6036. segList.clear();
  6037. for(var i=0; i<len; i++) {
  6038. if(i == index) {
  6039. segList.appendItem(seg);
  6040. } else {
  6041. segList.appendItem(arr[i]);
  6042. }
  6043. }
  6044. }
  6045. }
  6046. // If the path was rotated, we must now pay the piper:
  6047. // Every path point must be rotated into the rotated coordinate system of
  6048. // its old center, then determine the new center, then rotate it back
  6049. // This is because we want the path to remember its rotation
  6050. // TODO: This is still using ye olde transform methods, can probably
  6051. // be optimized or even taken care of by recalculateDimensions
  6052. var recalcRotatedPath = function() {
  6053. var current_path = path.elem;
  6054. var angle = getRotationAngle(current_path, true);
  6055. if(!angle) return;
  6056. selectedBBoxes[0] = path.oldbbox;
  6057. var box = getBBox(current_path),
  6058. oldbox = selectedBBoxes[0],
  6059. oldcx = oldbox.x + oldbox.width/2,
  6060. oldcy = oldbox.y + oldbox.height/2,
  6061. newcx = box.x + box.width/2,
  6062. newcy = box.y + box.height/2,
  6063. // un-rotate the new center to the proper position
  6064. dx = newcx - oldcx,
  6065. dy = newcy - oldcy,
  6066. r = Math.sqrt(dx*dx + dy*dy),
  6067. theta = Math.atan2(dy,dx) + angle;
  6068. newcx = r * Math.cos(theta) + oldcx;
  6069. newcy = r * Math.sin(theta) + oldcy;
  6070. var getRotVals = function(x, y) {
  6071. dx = x - oldcx;
  6072. dy = y - oldcy;
  6073. // rotate the point around the old center
  6074. r = Math.sqrt(dx*dx + dy*dy);
  6075. theta = Math.atan2(dy,dx) + angle;
  6076. dx = r * Math.cos(theta) + oldcx;
  6077. dy = r * Math.sin(theta) + oldcy;
  6078. // dx,dy should now hold the actual coordinates of each
  6079. // point after being rotated
  6080. // now we want to rotate them around the new center in the reverse direction
  6081. dx -= newcx;
  6082. dy -= newcy;
  6083. r = Math.sqrt(dx*dx + dy*dy);
  6084. theta = Math.atan2(dy,dx) - angle;
  6085. return {'x':(r * Math.cos(theta) + newcx)/1,
  6086. 'y':(r * Math.sin(theta) + newcy)/1};
  6087. }
  6088. var list = current_path.pathSegList,
  6089. i = list.numberOfItems;
  6090. while (i) {
  6091. i -= 1;
  6092. var seg = list.getItem(i),
  6093. type = seg.pathSegType;
  6094. if(type == 1) continue;
  6095. var rvals = getRotVals(seg.x,seg.y),
  6096. points = [rvals.x, rvals.y];
  6097. if(seg.x1 != null && seg.x2 != null) {
  6098. c_vals1 = getRotVals(seg.x1, seg.y1);
  6099. c_vals2 = getRotVals(seg.x2, seg.y2);
  6100. points.splice(points.length, 0, c_vals1.x , c_vals1.y, c_vals2.x, c_vals2.y);
  6101. }
  6102. replacePathSeg(type, i, points);
  6103. } // loop for each point
  6104. box = getBBox(current_path);
  6105. selectedBBoxes[0].x = box.x; selectedBBoxes[0].y = box.y;
  6106. selectedBBoxes[0].width = box.width; selectedBBoxes[0].height = box.height;
  6107. // now we must set the new transform to be rotated around the new center
  6108. var R_nc = svgroot.createSVGTransform(),
  6109. tlist = getTransformList(current_path);
  6110. R_nc.setRotate((angle * 180.0 / Math.PI), newcx, newcy);
  6111. tlist.replaceItem(R_nc,0);
  6112. }
  6113. return {
  6114. init: function() {
  6115. pathFuncs = [0,'ClosePath'];
  6116. var pathFuncsStrs = ['Moveto','Lineto','CurvetoCubic','CurvetoQuadratic','Arc','LinetoHorizontal','LinetoVertical','CurvetoCubicSmooth','CurvetoQuadraticSmooth'];
  6117. $.each(pathFuncsStrs,function(i,s){pathFuncs.push(s+'Abs');pathFuncs.push(s+'Rel');});
  6118. },
  6119. getPath: function() {
  6120. return path;
  6121. },
  6122. mouseDown: function(evt, mouse_target, start_x, start_y) {
  6123. if(current_mode == "path") return;
  6124. // TODO: Make sure current_path isn't null at this point
  6125. if(!path) return;
  6126. path.storeD();
  6127. var id = evt.target.id;
  6128. if (id.substr(0,14) == "pathpointgrip_") {
  6129. // Select this point
  6130. var cur_pt = path.cur_pt = parseInt(id.substr(14));
  6131. path.dragging = [start_x, start_y];
  6132. var seg = path.segs[cur_pt];
  6133. // only clear selection if shift is not pressed (otherwise, add
  6134. // node to selection)
  6135. if (!evt.shiftKey) {
  6136. if(path.selected_pts.length <= 1 || !seg.selected) {
  6137. path.clearSelection();
  6138. }
  6139. path.addPtsToSelection(cur_pt);
  6140. } else if(seg.selected) {
  6141. path.removePtFromSelection(cur_pt);
  6142. } else {
  6143. path.addPtsToSelection(cur_pt);
  6144. }
  6145. } else if(id.indexOf("ctrlpointgrip_") == 0) {
  6146. path.dragging = [start_x, start_y];
  6147. var parts = id.split('_')[1].split('c');
  6148. var cur_pt = parts[0]-0;
  6149. var ctrl_num = parts[1]-0;
  6150. path.selectPt(cur_pt, ctrl_num);
  6151. }
  6152. // Start selection box
  6153. if(!path.dragging) {
  6154. if (rubberBox == null) {
  6155. rubberBox = selectorManager.getRubberBandBox();
  6156. }
  6157. assignAttributes(rubberBox, {
  6158. 'x': start_x * current_zoom,
  6159. 'y': start_y * current_zoom,
  6160. 'width': 0,
  6161. 'height': 0,
  6162. 'display': 'inline'
  6163. }, 100);
  6164. }
  6165. },
  6166. mouseMove: function(mouse_x, mouse_y) {
  6167. hasMoved = true;
  6168. if(current_mode == "path") {
  6169. var line = getElem("path_stretch_line");
  6170. if (line) {
  6171. line.setAttribute("x2", mouse_x);
  6172. line.setAttribute("y2", mouse_y);
  6173. }
  6174. return;
  6175. }
  6176. // if we are dragging a point, let's move it
  6177. if (path.dragging) {
  6178. var pt = getPointFromGrip({
  6179. x: path.dragging[0],
  6180. y: path.dragging[1]
  6181. }, path);
  6182. var mpt = getPointFromGrip({
  6183. x: mouse_x,
  6184. y: mouse_y
  6185. }, path);
  6186. var diff_x = mpt.x - pt.x;
  6187. var diff_y = mpt.y - pt.y;
  6188. path.dragging = [mouse_x, mouse_y];
  6189. if(path.dragctrl) {
  6190. path.moveCtrl(diff_x, diff_y);
  6191. } else {
  6192. path.movePts(diff_x, diff_y);
  6193. }
  6194. } else {
  6195. path.selected_pts = [];
  6196. path.eachSeg(function(i) {
  6197. var seg = this;
  6198. if(!seg.next && !seg.prev) return;
  6199. var item = seg.item;
  6200. var rbb = rubberBox.getBBox();
  6201. var pt = getGripPt(seg);
  6202. var pt_bb = {
  6203. x: pt.x,
  6204. y: pt.y,
  6205. width: 0,
  6206. height: 0
  6207. };
  6208. var sel = Utils.rectsIntersect(rbb, pt_bb);
  6209. this.select(sel);
  6210. //Note that addPtsToSelection is not being run
  6211. if(sel) path.selected_pts.push(seg.index);
  6212. });
  6213. }
  6214. },
  6215. mouseUp: function(evt, element, mouse_x, mouse_y) {
  6216. // Create mode
  6217. if(current_mode == "path") {
  6218. var x = mouse_x/current_zoom,
  6219. y = mouse_y/current_zoom,
  6220. stretchy = getElem("path_stretch_line");
  6221. if(curConfig.gridSnapping){
  6222. x = snapToGrid(x);
  6223. y = snapToGrid(y);
  6224. mouse_x = snapToGrid(mouse_x);
  6225. mouse_y = snapToGrid(mouse_y);
  6226. }
  6227. if (!stretchy) {
  6228. stretchy = document.createElementNS(svgns, "line");
  6229. assignAttributes(stretchy, {
  6230. 'id': "path_stretch_line",
  6231. 'stroke': "#22C",
  6232. 'stroke-width': "0.5"
  6233. });
  6234. stretchy = getElem("selectorParentGroup").appendChild(stretchy);
  6235. }
  6236. stretchy.setAttribute("display", "inline");
  6237. var keep = null;
  6238. // if pts array is empty, create path element with M at current point
  6239. if (current_path_pts.length == 0) {
  6240. current_path_pts.push(x);
  6241. current_path_pts.push(y);
  6242. d_attr = "M" + x + "," + y + " ";
  6243. addSvgElementFromJson({
  6244. "element": "path",
  6245. "curStyles": true,
  6246. "attr": {
  6247. "d": d_attr,
  6248. "id": getNextId(),
  6249. "opacity": cur_shape.opacity / 2,
  6250. }
  6251. });
  6252. // set stretchy line to first point
  6253. assignAttributes(stretchy, {
  6254. 'x1': mouse_x,
  6255. 'y1': mouse_y,
  6256. 'x2': mouse_x,
  6257. 'y2': mouse_y
  6258. });
  6259. var index = subpath ? path.segs.length : 0;
  6260. addPointGrip(index, mouse_x, mouse_y);
  6261. }
  6262. else {
  6263. // determine if we clicked on an existing point
  6264. var i = current_path_pts.length;
  6265. var FUZZ = 6/current_zoom;
  6266. var clickOnPoint = false;
  6267. while(i) {
  6268. i -= 2;
  6269. var px = current_path_pts[i], py = current_path_pts[i+1];
  6270. // found a matching point
  6271. if ( x >= (px-FUZZ) && x <= (px+FUZZ) && y >= (py-FUZZ) && y <= (py+FUZZ) ) {
  6272. clickOnPoint = true;
  6273. break;
  6274. }
  6275. }
  6276. // get path element that we are in the process of creating
  6277. var id = getId();
  6278. // Remove previous path object if previously created
  6279. if(id in pathData) delete pathData[id];
  6280. var newpath = getElem(id);
  6281. var len = current_path_pts.length;
  6282. // if we clicked on an existing point, then we are done this path, commit it
  6283. // (i,i+1) are the x,y that were clicked on
  6284. if (clickOnPoint) {
  6285. // if clicked on any other point but the first OR
  6286. // the first point was clicked on and there are less than 3 points
  6287. // then leave the path open
  6288. // otherwise, close the path
  6289. if (i == 0 && len >= 6) {
  6290. // Create end segment
  6291. var abs_x = current_path_pts[0];
  6292. var abs_y = current_path_pts[1];
  6293. d_attr += ['L',abs_x,',',abs_y,'z'].join('');
  6294. newpath.setAttribute("d", d_attr);
  6295. } else if(len < 3) {
  6296. keep = false;
  6297. return keep;
  6298. }
  6299. $(stretchy).remove();
  6300. // this will signal to commit the path
  6301. element = newpath;
  6302. current_path_pts = [];
  6303. started = false;
  6304. if(subpath) {
  6305. if(path.matrix) {
  6306. remapElement(newpath, {}, path.matrix.inverse());
  6307. }
  6308. var new_d = newpath.getAttribute("d");
  6309. var orig_d = $(path.elem).attr("d");
  6310. $(path.elem).attr("d", orig_d + new_d);
  6311. $(newpath).remove();
  6312. if(path.matrix) {
  6313. recalcRotatedPath();
  6314. }
  6315. path.init();
  6316. pathActions.toEditMode(path.elem);
  6317. path.selectPt();
  6318. return false;
  6319. }
  6320. }
  6321. // else, create a new point, append to pts array, update path element
  6322. else {
  6323. // Checks if current target or parents are #svgcontent
  6324. if(!$.contains(container, getMouseTarget(evt))) {
  6325. // Clicked outside canvas, so don't make point
  6326. console.log("Clicked outside canvas");
  6327. return false;
  6328. }
  6329. var lastx = current_path_pts[len-2], lasty = current_path_pts[len-1];
  6330. if(evt.shiftKey) { var xya=Utils.snapToAngle(lastx,lasty,x,y); x=xya.x; y=xya.y; }
  6331. // we store absolute values in our path points array for easy checking above
  6332. current_path_pts.push(x);
  6333. current_path_pts.push(y);
  6334. d_attr += "L" + round(x) + "," + round(y) + " ";
  6335. newpath.setAttribute("d", d_attr);
  6336. x *= current_zoom;
  6337. y *= current_zoom;
  6338. // set stretchy line to latest point
  6339. assignAttributes(stretchy, {
  6340. 'x1': x,
  6341. 'y1': y,
  6342. 'x2': x,
  6343. 'y2': y
  6344. });
  6345. var index = (current_path_pts.length/2 - 1);
  6346. if(subpath) index += path.segs.length;
  6347. addPointGrip(index, x, y);
  6348. }
  6349. keep = true;
  6350. }
  6351. return {
  6352. keep: keep,
  6353. element: element
  6354. }
  6355. }
  6356. // Edit mode
  6357. if (path.dragging) {
  6358. var last_pt = path.cur_pt;
  6359. path.dragging = false;
  6360. path.dragctrl = false;
  6361. path.update();
  6362. if(hasMoved) {
  6363. path.endChanges("Move path point(s)");
  6364. }
  6365. if(!evt.shiftKey && !hasMoved) {
  6366. path.selectPt(last_pt);
  6367. }
  6368. }
  6369. else if(rubberBox && rubberBox.getAttribute('display') != 'none') {
  6370. // Done with multi-node-select
  6371. rubberBox.setAttribute("display", "none");
  6372. if(rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) {
  6373. pathActions.toSelectMode(evt.target);
  6374. }
  6375. // else, move back to select mode
  6376. } else {
  6377. pathActions.toSelectMode(evt.target);
  6378. }
  6379. hasMoved = false;
  6380. },
  6381. clearData: function() {
  6382. pathData = {};
  6383. },
  6384. toEditMode: function(element) {
  6385. path = getPath(element);
  6386. current_mode = "pathedit";
  6387. clearSelection();
  6388. path.show(true).update();
  6389. path.oldbbox = getBBox(path.elem);
  6390. subpath = false;
  6391. },
  6392. toSelectMode: function(elem) {
  6393. var selPath = (elem == path.elem);
  6394. current_mode = "select";
  6395. path.show(false);
  6396. current_path = false;
  6397. clearSelection();
  6398. if(path.matrix) {
  6399. // Rotated, so may need to re-calculate the center
  6400. recalcRotatedPath();
  6401. }
  6402. if(selPath) {
  6403. call("selected", [elem]);
  6404. addToSelection([elem], true);
  6405. }
  6406. },
  6407. addSubPath: function(on) {
  6408. if(on) {
  6409. // Internally we go into "path" mode, but in the UI it will
  6410. // still appear as if in "pathedit" mode.
  6411. current_mode = "path";
  6412. subpath = true;
  6413. } else {
  6414. pathActions.clear(true);
  6415. pathActions.toEditMode(path.elem);
  6416. }
  6417. },
  6418. select: function(target) {
  6419. if (current_path == target) {
  6420. pathActions.toEditMode(target);
  6421. current_mode = "pathedit";
  6422. } // going into pathedit mode
  6423. else {
  6424. current_path = target;
  6425. }
  6426. },
  6427. reorient: function() {
  6428. var elem = selectedElements[0];
  6429. if(!elem) return;
  6430. var angle = getRotationAngle(elem);
  6431. if(angle == 0) return;
  6432. var batchCmd = new BatchCommand("Reorient path");
  6433. var changes = {
  6434. d: elem.getAttribute('d'),
  6435. transform: elem.getAttribute('transform')
  6436. };
  6437. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  6438. clearSelection();
  6439. this.resetOrientation(elem);
  6440. addCommandToHistory(batchCmd);
  6441. // Set matrix to null
  6442. getPath(elem).show(false).matrix = null;
  6443. this.clear();
  6444. addToSelection([elem], true);
  6445. call("changed", selectedElements);
  6446. },
  6447. clear: function(remove) {
  6448. current_path = null;
  6449. if (current_mode == "path" && current_path_pts.length > 0) {
  6450. var elem = getElem(getId());
  6451. $(getElem("path_stretch_line")).remove();
  6452. $(elem).remove();
  6453. $(getElem("pathpointgrip_container")).find('*').attr('display', 'none');
  6454. current_path_pts = [];
  6455. started = false;
  6456. } else if (current_mode == "pathedit") {
  6457. this.toSelectMode();
  6458. }
  6459. if(path) path.init().show(false);
  6460. },
  6461. resetOrientation: function(path) {
  6462. if(path == null || path.nodeName != 'path') return false;
  6463. var tlist = getTransformList(path);
  6464. var m = transformListToTransform(tlist).matrix;
  6465. tlist.clear();
  6466. path.removeAttribute("transform");
  6467. var segList = path.pathSegList;
  6468. // Opera/win/non-EN throws an error here.
  6469. // TODO: Find out why!
  6470. // Presumed fixed in Opera 10.5, so commented out for now
  6471. // try {
  6472. var len = segList.numberOfItems;
  6473. // } catch(err) {
  6474. // var fixed_d = pathActions.convertPath(path);
  6475. // path.setAttribute('d', fixed_d);
  6476. // segList = path.pathSegList;
  6477. // var len = segList.numberOfItems;
  6478. // }
  6479. for (var i = 0; i < len; ++i) {
  6480. var seg = segList.getItem(i);
  6481. var type = seg.pathSegType;
  6482. if(type == 1) continue;
  6483. var pts = [];
  6484. $.each(['',1,2], function(j, n) {
  6485. var x = seg['x'+n], y = seg['y'+n];
  6486. if(x && y) {
  6487. var pt = transformPoint(x, y, m);
  6488. pts.splice(pts.length, 0, pt.x, pt.y);
  6489. }
  6490. });
  6491. replacePathSeg(type, i, pts, path);
  6492. }
  6493. },
  6494. zoomChange: function() {
  6495. if(current_mode == "pathedit") {
  6496. path.update();
  6497. }
  6498. },
  6499. getNodePoint: function() {
  6500. var sel_pt = path.selected_pts.length ? path.selected_pts[0] : 1;
  6501. var seg = path.segs[sel_pt];
  6502. return {
  6503. x: seg.item.x,
  6504. y: seg.item.y,
  6505. type: seg.type
  6506. };
  6507. },
  6508. linkControlPoints: function(linkPoints) {
  6509. link_control_pts = linkPoints;
  6510. },
  6511. clonePathNode: function() {
  6512. path.storeD();
  6513. var sel_pts = path.selected_pts;
  6514. var segs = path.segs;
  6515. var i = sel_pts.length;
  6516. var nums = [];
  6517. while(i--) {
  6518. var pt = sel_pts[i];
  6519. path.addSeg(pt);
  6520. nums.push(pt + i);
  6521. nums.push(pt + i + 1);
  6522. }
  6523. path.init().addPtsToSelection(nums);
  6524. path.endChanges("Clone path node(s)");
  6525. },
  6526. opencloseSubPath: function() {
  6527. var sel_pts = path.selected_pts;
  6528. // Only allow one selected node for now
  6529. if(sel_pts.length !== 1) return;
  6530. var elem = path.elem;
  6531. var list = elem.pathSegList;
  6532. var len = list.numberOfItems;
  6533. var index = sel_pts[0];
  6534. var open_pt = null;
  6535. var start_item = null;
  6536. // Check if subpath is already open
  6537. path.eachSeg(function(i) {
  6538. if(this.type === 2 && i <= index) {
  6539. start_item = this.item;
  6540. }
  6541. if(i <= index) return true;
  6542. if(this.type === 2) {
  6543. // Found M first, so open
  6544. open_pt = i;
  6545. return false;
  6546. } else if(this.type === 1) {
  6547. // Found Z first, so closed
  6548. open_pt = false;
  6549. return false;
  6550. }
  6551. });
  6552. if(open_pt == null) {
  6553. // Single path, so close last seg
  6554. open_pt = path.segs.length - 1;
  6555. }
  6556. if(open_pt !== false) {
  6557. // Close this path
  6558. // Create a line going to the previous "M"
  6559. var newseg = elem.createSVGPathSegLinetoAbs(start_item.x, start_item.y);
  6560. var closer = elem.createSVGPathSegClosePath();
  6561. if(open_pt == path.segs.length - 1) {
  6562. list.appendItem(newseg);
  6563. list.appendItem(closer);
  6564. } else {
  6565. insertItemBefore(elem, closer, open_pt);
  6566. insertItemBefore(elem, newseg, open_pt);
  6567. }
  6568. path.init().selectPt(open_pt+1);
  6569. return;
  6570. }
  6571. // M 1,1 L 2,2 L 3,3 L 1,1 z // open at 2,2
  6572. // M 2,2 L 3,3 L 1,1
  6573. // M 1,1 L 2,2 L 1,1 z M 4,4 L 5,5 L6,6 L 5,5 z
  6574. // M 1,1 L 2,2 L 1,1 z [M 4,4] L 5,5 L(M)6,6 L 5,5 z
  6575. var seg = path.segs[index];
  6576. if(seg.mate) {
  6577. list.removeItem(index); // Removes last "L"
  6578. list.removeItem(index); // Removes the "Z"
  6579. path.init().selectPt(index - 1);
  6580. return;
  6581. }
  6582. var last_m, z_seg;
  6583. // Find this sub-path's closing point and remove
  6584. for(var i=0; i<list.numberOfItems; i++) {
  6585. var item = list.getItem(i);
  6586. if(item.pathSegType === 2) {
  6587. // Find the preceding M
  6588. last_m = i;
  6589. } else if(i === index) {
  6590. // Remove it
  6591. list.removeItem(last_m);
  6592. // index--;
  6593. } else if(item.pathSegType === 1 && index < i) {
  6594. // Remove the closing seg of this subpath
  6595. z_seg = i-1;
  6596. list.removeItem(i);
  6597. break;
  6598. }
  6599. }
  6600. var num = (index - last_m) - 1;
  6601. while(num--) {
  6602. insertItemBefore(elem, list.getItem(last_m), z_seg);
  6603. }
  6604. var pt = list.getItem(last_m);
  6605. // Make this point the new "M"
  6606. replacePathSeg(2, last_m, [pt.x, pt.y]);
  6607. var i = index
  6608. path.init().selectPt(0);
  6609. },
  6610. deletePathNode: function() {
  6611. if(!pathActions.canDeleteNodes) return;
  6612. path.storeD();
  6613. var sel_pts = path.selected_pts;
  6614. var i = sel_pts.length;
  6615. while(i--) {
  6616. var pt = sel_pts[i];
  6617. path.deleteSeg(pt);
  6618. }
  6619. // Cleanup
  6620. var cleanup = function() {
  6621. var segList = path.elem.pathSegList;
  6622. var len = segList.numberOfItems;
  6623. var remItems = function(pos, count) {
  6624. while(count--) {
  6625. segList.removeItem(pos);
  6626. }
  6627. }
  6628. if(len <= 1) return true;
  6629. while(len--) {
  6630. var item = segList.getItem(len);
  6631. if(item.pathSegType === 1) {
  6632. var prev = segList.getItem(len-1);
  6633. var nprev = segList.getItem(len-2);
  6634. if(prev.pathSegType === 2) {
  6635. remItems(len-1, 2);
  6636. cleanup();
  6637. break;
  6638. } else if(nprev.pathSegType === 2) {
  6639. remItems(len-2, 3);
  6640. cleanup();
  6641. break;
  6642. }
  6643. } else if(item.pathSegType === 2) {
  6644. if(len > 0) {
  6645. var prev_type = segList.getItem(len-1).pathSegType;
  6646. // Path has M M
  6647. if(prev_type === 2) {
  6648. remItems(len-1, 1);
  6649. cleanup();
  6650. break;
  6651. // Entire path ends with Z M
  6652. } else if(prev_type === 1 && segList.numberOfItems-1 === len) {
  6653. remItems(len, 1);
  6654. cleanup();
  6655. break;
  6656. }
  6657. }
  6658. }
  6659. }
  6660. return false;
  6661. }
  6662. cleanup();
  6663. // Completely delete a path with 1 or 0 segments
  6664. if(path.elem.pathSegList.numberOfItems <= 1) {
  6665. pathActions.toSelectMode(path.elem);
  6666. canvas.deleteSelectedElements();
  6667. return;
  6668. }
  6669. path.init();
  6670. path.clearSelection();
  6671. // TODO: Find right way to select point now
  6672. // path.selectPt(sel_pt);
  6673. if(window.opera) { // Opera repaints incorrectly
  6674. var cp = $(path.elem); cp.attr('d',cp.attr('d'));
  6675. }
  6676. path.endChanges("Delete path node(s)");
  6677. },
  6678. smoothPolylineIntoPath: smoothPolylineIntoPath,
  6679. setSegType: function(v) {
  6680. path.setSegType(v);
  6681. },
  6682. moveNode: function(attr, newValue) {
  6683. var sel_pts = path.selected_pts;
  6684. if(!sel_pts.length) return;
  6685. path.storeD();
  6686. // Get first selected point
  6687. var seg = path.segs[sel_pts[0]];
  6688. var diff = {x:0, y:0};
  6689. diff[attr] = newValue - seg.item[attr];
  6690. seg.move(diff.x, diff.y);
  6691. path.endChanges("Move path point");
  6692. },
  6693. fixEnd: function(elem) {
  6694. // Adds an extra segment if the last seg before a Z doesn't end
  6695. // at its M point
  6696. // M0,0 L0,100 L100,100 z
  6697. var segList = elem.pathSegList;
  6698. var len = segList.numberOfItems;
  6699. var last_m;
  6700. for (var i = 0; i < len; ++i) {
  6701. var item = segList.getItem(i);
  6702. if(item.pathSegType === 2) {
  6703. last_m = item;
  6704. }
  6705. if(item.pathSegType === 1) {
  6706. var prev = segList.getItem(i-1);
  6707. if(prev.x != last_m.x || prev.y != last_m.y) {
  6708. // Add an L segment here
  6709. var newseg = elem.createSVGPathSegLinetoAbs(last_m.x, last_m.y);
  6710. insertItemBefore(elem, newseg, i);
  6711. // Can this be done better?
  6712. pathActions.fixEnd(elem);
  6713. break;
  6714. }
  6715. }
  6716. }
  6717. if(isWebkit) resetD(elem);
  6718. },
  6719. // Convert a path to one with only absolute or relative values
  6720. convertPath: function(path, toRel) {
  6721. var segList = path.pathSegList;
  6722. var len = segList.numberOfItems;
  6723. var curx = 0, cury = 0;
  6724. var d = "";
  6725. var last_m = null;
  6726. for (var i = 0; i < len; ++i) {
  6727. var seg = segList.getItem(i);
  6728. // if these properties are not in the segment, set them to zero
  6729. var x = seg.x || 0,
  6730. y = seg.y || 0,
  6731. x1 = seg.x1 || 0,
  6732. y1 = seg.y1 || 0,
  6733. x2 = seg.x2 || 0,
  6734. y2 = seg.y2 || 0;
  6735. var type = seg.pathSegType;
  6736. var letter = pathMap[type]['to'+(toRel?'Lower':'Upper')+'Case']();
  6737. var addToD = function(pnts, more, last) {
  6738. var str = '';
  6739. var more = more?' '+more.join(' '):'';
  6740. var last = last?' '+shortFloat(last):'';
  6741. $.each(pnts, function(i, pnt) {
  6742. pnts[i] = shortFloat(pnt);
  6743. });
  6744. d += letter + pnts.join(' ') + more + last;
  6745. }
  6746. switch (type) {
  6747. case 1: // z,Z closepath (Z/z)
  6748. d += "z";
  6749. break;
  6750. case 12: // absolute horizontal line (H)
  6751. x -= curx;
  6752. case 13: // relative horizontal line (h)
  6753. if(toRel) {
  6754. curx += x;
  6755. } else {
  6756. x += curx;
  6757. curx = x;
  6758. }
  6759. addToD([[x]]);
  6760. break;
  6761. case 14: // absolute vertical line (V)
  6762. y -= cury;
  6763. case 15: // relative vertical line (v)
  6764. if(toRel) {
  6765. cury += y;
  6766. } else {
  6767. y += cury;
  6768. cury = y;
  6769. }
  6770. addToD([[y]]);
  6771. break;
  6772. case 2: // absolute move (M)
  6773. case 4: // absolute line (L)
  6774. case 18: // absolute smooth quad (T)
  6775. x -= curx;
  6776. y -= cury;
  6777. case 5: // relative line (l)
  6778. case 3: // relative move (m)
  6779. // If the last segment was a "z", this must be relative to
  6780. if(last_m && segList.getItem(i-1).pathSegType === 1 && !toRel) {
  6781. curx = last_m[0];
  6782. cury = last_m[1];
  6783. }
  6784. case 19: // relative smooth quad (t)
  6785. if(toRel) {
  6786. curx += x;
  6787. cury += y;
  6788. } else {
  6789. x += curx;
  6790. y += cury;
  6791. curx = x;
  6792. cury = y;
  6793. }
  6794. if(type === 3) last_m = [curx, cury];
  6795. addToD([[x,y]]);
  6796. break;
  6797. case 6: // absolute cubic (C)
  6798. x -= curx; x1 -= curx; x2 -= curx;
  6799. y -= cury; y1 -= cury; y2 -= cury;
  6800. case 7: // relative cubic (c)
  6801. if(toRel) {
  6802. curx += x;
  6803. cury += y;
  6804. } else {
  6805. x += curx; x1 += curx; x2 += curx;
  6806. y += cury; y1 += cury; y2 += cury;
  6807. curx = x;
  6808. cury = y;
  6809. }
  6810. addToD([[x1,y1],[x2,y2],[x,y]]);
  6811. break;
  6812. case 8: // absolute quad (Q)
  6813. x -= curx; x1 -= curx;
  6814. y -= cury; y1 -= cury;
  6815. case 9: // relative quad (q)
  6816. if(toRel) {
  6817. curx += x;
  6818. cury += y;
  6819. } else {
  6820. x += curx; x1 += curx;
  6821. y += cury; y1 += cury;
  6822. curx = x;
  6823. cury = y;
  6824. }
  6825. addToD([[x1,y1],[x,y]]);
  6826. break;
  6827. case 10: // absolute elliptical arc (A)
  6828. x -= curx;
  6829. y -= cury;
  6830. case 11: // relative elliptical arc (a)
  6831. if(toRel) {
  6832. curx += x;
  6833. cury += y;
  6834. } else {
  6835. x += curx;
  6836. y += cury;
  6837. curx = x;
  6838. cury = y;
  6839. }
  6840. addToD([[seg.r1,seg.r2]], [
  6841. seg.angle,
  6842. (seg.largeArcFlag ? 1 : 0),
  6843. (seg.sweepFlag ? 1 : 0)
  6844. ],[x,y]
  6845. );
  6846. break;
  6847. case 16: // absolute smooth cubic (S)
  6848. x -= curx; x2 -= curx;
  6849. y -= cury; y2 -= cury;
  6850. case 17: // relative smooth cubic (s)
  6851. if(toRel) {
  6852. curx += x;
  6853. cury += y;
  6854. } else {
  6855. x += curx; x2 += curx;
  6856. y += cury; y2 += cury;
  6857. curx = x;
  6858. cury = y;
  6859. }
  6860. addToD([[x2,y2],[x,y]]);
  6861. break;
  6862. } // switch on path segment type
  6863. } // for each segment
  6864. return d;
  6865. }
  6866. }
  6867. }();
  6868. pathActions.init();
  6869. // Group: Serialization
  6870. // Function: removeUnusedDefElems
  6871. // Looks at DOM elements inside the <defs> to see if they are referred to,
  6872. // removes them from the DOM if they are not.
  6873. //
  6874. // Returns:
  6875. // The amount of elements that were removed
  6876. var removeUnusedDefElems = this.removeUnusedDefElems = function() {
  6877. var defs = svgcontent.getElementsByTagNameNS(svgns, "defs");
  6878. if(!defs || !defs.length) return 0;
  6879. var defelem_uses = [],
  6880. numRemoved = 0;
  6881. var attrs = ['fill', 'stroke', 'filter', 'marker-start', 'marker-mid', 'marker-end'];
  6882. var alen = attrs.length;
  6883. var all_els = svgcontent.getElementsByTagNameNS(svgns, '*');
  6884. var all_len = all_els.length;
  6885. for(var i=0; i<all_len; i++) {
  6886. var el = all_els[i];
  6887. for(var j = 0; j < alen; j++) {
  6888. var ref = getUrlFromAttr(el.getAttribute(attrs[j]));
  6889. if(ref) defelem_uses.push(ref.substr(1));
  6890. }
  6891. // gradients can refer to other gradients
  6892. var href = getHref(el);
  6893. if (href && href.indexOf('#') == 0) {
  6894. defelem_uses.push(href.substr(1));
  6895. }
  6896. };
  6897. var defelems = $(svgcontent).find("linearGradient, radialGradient, filter, marker, svg");
  6898. defelem_ids = [],
  6899. i = defelems.length;
  6900. while (i--) {
  6901. var defelem = defelems[i];
  6902. var id = defelem.id;
  6903. if(defelem_uses.indexOf(id) == -1) {
  6904. // Not found, so remove
  6905. defelem.parentNode.removeChild(defelem);
  6906. numRemoved++;
  6907. }
  6908. }
  6909. // Remove defs if empty
  6910. var i = defs.length;
  6911. while (i--) {
  6912. var def = defs[i];
  6913. if(!def.getElementsByTagNameNS(svgns,'*').length) {
  6914. def.parentNode.removeChild(def);
  6915. }
  6916. }
  6917. return numRemoved;
  6918. }
  6919. // Function: svgCanvasToString
  6920. // Main function to set up the SVG content for output
  6921. //
  6922. // Returns:
  6923. // String containing the SVG image for output
  6924. var svgCanvasToString = this.svgCanvasToString = function() {
  6925. // keep calling it until there are none to remove
  6926. while (removeUnusedDefElems() > 0) {};
  6927. pathActions.clear(true);
  6928. // Keep SVG-Edit comment on top
  6929. $.each(svgcontent.childNodes, function(i, node) {
  6930. if(i && node.nodeType == 8 && node.data.indexOf('Created with') >= 0) {
  6931. svgcontent.insertBefore(node, svgcontent.firstChild);
  6932. }
  6933. });
  6934. // Move out of in-group editing mode
  6935. if(current_group) {
  6936. leaveContext();
  6937. selectOnly([current_group]);
  6938. }
  6939. var naked_svgs = [];
  6940. // Unwrap gsvg if it has no special attributes (only id and style)
  6941. $(svgcontent).find('g:data(gsvg)').each(function() {
  6942. var attrs = this.attributes;
  6943. var len = attrs.length;
  6944. for(var i=0; i<len; i++) {
  6945. if(attrs[i].nodeName == 'id' || attrs[i].nodeName == 'style') {
  6946. len--;
  6947. }
  6948. }
  6949. // No significant attributes, so ungroup
  6950. if(len <= 0) {
  6951. var svg = this.firstChild;
  6952. naked_svgs.push(svg);
  6953. $(this).replaceWith(svg);
  6954. }
  6955. });
  6956. var output = svgToString(svgcontent, 0);
  6957. // Rewrap gsvg
  6958. if(naked_svgs.length) {
  6959. $(naked_svgs).each(function() {
  6960. groupSvgElem(this);
  6961. });
  6962. }
  6963. return output;
  6964. }
  6965. // Function: svgToString
  6966. // Sub function ran on each SVG element to convert it to a string as desired
  6967. //
  6968. // Parameters:
  6969. // elem - The SVG element to convert
  6970. // indent - Integer with the amount of spaces to indent this tag
  6971. //
  6972. // Returns:
  6973. // String with the given element as an SVG tag
  6974. var svgToString = this.svgToString = function(elem, indent) {
  6975. var out = new Array(), toXml = Utils.toXml;
  6976. var unit = curConfig.baseUnit
  6977. var unit_re = new RegExp('^-?[\\d\\.]+' + unit + '$');
  6978. if (elem) {
  6979. cleanupElement(elem);
  6980. var attrs = elem.attributes,
  6981. attr,
  6982. i,
  6983. childs = elem.childNodes;
  6984. for (var i=0; i<indent; i++) out.push(" ");
  6985. out.push("<"); out.push(elem.nodeName);
  6986. if(elem.id == 'svgcontent') {
  6987. // Process root element separately
  6988. var res = getResolution();
  6989. out.push(' width="' + res.w + '" height="' + res.h + '" xmlns="'+svgns+'"');
  6990. var nsuris = {};
  6991. // Check elements for namespaces, add if found
  6992. $(elem).find('*').andSelf().each(function() {
  6993. var el = this;
  6994. $.each(this.attributes, function(i, attr) {
  6995. var uri = attr.namespaceURI;
  6996. if(uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) {
  6997. nsuris[uri] = true;
  6998. out.push(" xmlns:" + nsMap[uri] + '="' + uri +'"');
  6999. }
  7000. });
  7001. });
  7002. var i = attrs.length;
  7003. while (i--) {
  7004. attr = attrs.item(i);
  7005. var attrVal = toXml(attr.nodeValue);
  7006. // Namespaces have already been dealt with, so skip
  7007. if(attr.nodeName.indexOf('xmlns:') === 0) continue;
  7008. // only serialize attributes we don't use internally
  7009. if (attrVal != "" &&
  7010. ['width','height','xmlns','x','y','viewBox','id','overflow'].indexOf(attr.localName) == -1)
  7011. {
  7012. if(!attr.namespaceURI || nsMap[attr.namespaceURI]) {
  7013. out.push(' ');
  7014. out.push(attr.nodeName); out.push("=\"");
  7015. out.push(attrVal); out.push("\"");
  7016. }
  7017. }
  7018. }
  7019. } else {
  7020. for (var i=attrs.length-1; i>=0; i--) {
  7021. attr = attrs.item(i);
  7022. var attrVal = toXml(attr.nodeValue);
  7023. //remove bogus attributes added by Gecko
  7024. if (['-moz-math-font-style', '_moz-math-font-style'].indexOf(attr.localName) >= 0) continue;
  7025. if (attrVal != "") {
  7026. if(attrVal.indexOf('pointer-events') === 0) continue;
  7027. if(attr.localName === "class" && attrVal.indexOf('se_') === 0) continue;
  7028. out.push(" ");
  7029. if(attr.localName === 'd') attrVal = pathActions.convertPath(elem, true);
  7030. if(!isNaN(attrVal)) {
  7031. attrVal = shortFloat(attrVal);
  7032. } else if(unit_re.test(attrVal)) {
  7033. attrVal = shortFloat(attrVal) + unit;
  7034. }
  7035. // Embed images when saving
  7036. if(save_options.apply
  7037. && elem.nodeName === 'image'
  7038. && attr.localName === 'href'
  7039. && save_options.images
  7040. && save_options.images === 'embed')
  7041. {
  7042. var img = encodableImages[attrVal];
  7043. if(img) attrVal = img;
  7044. }
  7045. // map various namespaces to our fixed namespace prefixes
  7046. // (the default xmlns attribute itself does not get a prefix)
  7047. if(!attr.namespaceURI || attr.namespaceURI == svgns || nsMap[attr.namespaceURI]) {
  7048. out.push(attr.nodeName); out.push("=\"");
  7049. out.push(attrVal); out.push("\"");
  7050. }
  7051. }
  7052. }
  7053. }
  7054. if (elem.hasChildNodes()) {
  7055. out.push(">");
  7056. indent++;
  7057. var bOneLine = false;
  7058. for (var i=0; i<childs.length; i++)
  7059. {
  7060. var child = childs.item(i);
  7061. switch(child.nodeType) {
  7062. case 1: // element node
  7063. out.push("\n");
  7064. out.push(svgToString(childs.item(i), indent));
  7065. break;
  7066. case 3: // text node
  7067. var str = child.nodeValue.replace(/^\s+|\s+$/g, "");
  7068. if (str != "") {
  7069. bOneLine = true;
  7070. out.push(toXml(str) + "");
  7071. }
  7072. break;
  7073. case 8: // comment
  7074. out.push("\n");
  7075. out.push(new Array(indent+1).join(" "));
  7076. out.push("<!--");
  7077. out.push(child.data);
  7078. out.push("-->");
  7079. break;
  7080. } // switch on node type
  7081. }
  7082. indent--;
  7083. if (!bOneLine) {
  7084. out.push("\n");
  7085. for (var i=0; i<indent; i++) out.push(" ");
  7086. }
  7087. out.push("</"); out.push(elem.nodeName); out.push(">");
  7088. } else {
  7089. out.push("/>");
  7090. }
  7091. }
  7092. return out.join('');
  7093. }; // end svgToString()
  7094. // Function: embedImage
  7095. // Converts a given image file to a data URL when possible, then runs a given callback
  7096. //
  7097. // Parameters:
  7098. // val - String with the path/URL of the image
  7099. // callback - Optional function to run when image data is found, supplies the
  7100. // result (data URL or false) as first parameter.
  7101. this.embedImage = function(val, callback) {
  7102. // load in the image and once it's loaded, get the dimensions
  7103. $(new Image()).load(function() {
  7104. // create a canvas the same size as the raster image
  7105. var canvas = document.createElement("canvas");
  7106. canvas.width = this.width;
  7107. canvas.height = this.height;
  7108. // load the raster image into the canvas
  7109. canvas.getContext("2d").drawImage(this,0,0);
  7110. // retrieve the data: URL
  7111. try {
  7112. var urldata = ';svgedit_url=' + encodeURIComponent(val);
  7113. urldata = canvas.toDataURL().replace(';base64',urldata+';base64');
  7114. encodableImages[val] = urldata;
  7115. } catch(e) {
  7116. encodableImages[val] = false;
  7117. }
  7118. last_good_img_url = val;
  7119. if(callback) callback(encodableImages[val]);
  7120. }).attr('src',val);
  7121. }
  7122. // Function: setGoodImage
  7123. // Sets a given URL to be a "last good image" URL
  7124. this.setGoodImage = function(val) {
  7125. last_good_img_url = val;
  7126. }
  7127. this.open = function() {
  7128. // Nothing by default, handled by optional widget/extension
  7129. };
  7130. // Function: save
  7131. // Serializes the current drawing into SVG XML text and returns it to the 'saved' handler.
  7132. // This function also includes the XML prolog. Clients of the SvgCanvas bind their save
  7133. // function to the 'saved' event.
  7134. //
  7135. // Returns:
  7136. // Nothing
  7137. this.save = function(opts) {
  7138. // remove the selected outline before serializing
  7139. clearSelection();
  7140. // Update save options if provided
  7141. if(opts) $.extend(save_options, opts);
  7142. save_options.apply = true;
  7143. // no need for doctype, see http://jwatt.org/svg/authoring/#doctype-declaration
  7144. var str = svgCanvasToString();
  7145. call("saved", str);
  7146. };
  7147. // Function: rasterExport
  7148. // Generates a PNG Data URL based on the current image, then calls "exported"
  7149. // with an object including the string and any issues found
  7150. this.rasterExport = function() {
  7151. // remove the selected outline before serializing
  7152. clearSelection();
  7153. // Check for known CanVG issues
  7154. var issues = [];
  7155. // Selector and notice
  7156. var issue_list = {
  7157. 'feGaussianBlur': uiStrings.exportNoBlur,
  7158. 'foreignObject': uiStrings.exportNoforeignObject,
  7159. '[stroke-dasharray]': uiStrings.exportNoDashArray
  7160. };
  7161. var content = $(svgcontent);
  7162. // Add font/text check if Canvas Text API is not implemented
  7163. if(!("font" in $('<canvas>')[0].getContext('2d'))) {
  7164. issue_list['text'] = uiStrings.exportNoText;
  7165. }
  7166. $.each(issue_list, function(sel, descr) {
  7167. if(content.find(sel).length) {
  7168. issues.push(descr);
  7169. }
  7170. });
  7171. var str = svgCanvasToString();
  7172. call("exported", {svg: str, issues: issues});
  7173. };
  7174. // Function: getSvgString
  7175. // Returns the current drawing as raw SVG XML text.
  7176. //
  7177. // Returns:
  7178. // The current drawing as raw SVG XML text.
  7179. this.getSvgString = function() {
  7180. save_options.apply = false;
  7181. return svgCanvasToString();
  7182. };
  7183. //function randomizeIds
  7184. // This function determines whether to add a nonce to the prefix, when
  7185. // generating IDs in SVG-Edit
  7186. //
  7187. // Parameters:
  7188. // an opional boolean, which, if true, adds a nonce to the prefix. Thus
  7189. // svgCanvas.randomizeIds() <==> svgCanvas.randomizeIds(true)
  7190. //
  7191. // if you're controlling SVG-Edit externally, and want randomized IDs, call
  7192. // this BEFORE calling svgCanvas.setSvgString
  7193. //
  7194. this.randomizeIds = function() {
  7195. if (arguments.length > 0 && arguments[0] == false) {
  7196. randomize_ids = false;
  7197. if (extensions["Arrows"]) call("unsetarrownonce") ;
  7198. } else {
  7199. randomize_ids = true;
  7200. if (!svgcontent.getAttributeNS(se_ns, 'nonce')) {
  7201. svgcontent.setAttributeNS(se_ns, 'se:nonce', nonce);
  7202. if (extensions["Arrows"]) call("setarrownonce", nonce) ;
  7203. }
  7204. }
  7205. }
  7206. // Function: uniquifyElems
  7207. // Ensure each element has a unique ID
  7208. //
  7209. // Parameters:
  7210. // g - The parent element of the tree to give unique IDs
  7211. var uniquifyElems = this.uniquifyElems = function(g) {
  7212. var ids = {};
  7213. walkTree(g, function(n) {
  7214. // if it's an element node
  7215. if (n.nodeType == 1) {
  7216. // and the element has an ID
  7217. if (n.id) {
  7218. // and we haven't tracked this ID yet
  7219. if (!(n.id in ids)) {
  7220. // add this id to our map
  7221. ids[n.id] = {elem:null, attrs:[], hrefs:[]};
  7222. }
  7223. ids[n.id]["elem"] = n;
  7224. }
  7225. // now search for all attributes on this element that might refer
  7226. // to other elements
  7227. $.each(["clip-path", "fill", "filter", "marker-end", "marker-mid", "marker-start", "mask", "stroke"],function(i,attr) {
  7228. var attrnode = n.getAttributeNode(attr);
  7229. if (attrnode) {
  7230. // the incoming file has been sanitized, so we should be able to safely just strip off the leading #
  7231. var url = getUrlFromAttr(attrnode.value),
  7232. refid = url ? url.substr(1) : null;
  7233. if (refid) {
  7234. if (!(refid in ids)) {
  7235. // add this id to our map
  7236. ids[refid] = {elem:null, attrs:[], hrefs:[]};
  7237. }
  7238. ids[refid]["attrs"].push(attrnode);
  7239. }
  7240. }
  7241. });
  7242. // check xlink:href now
  7243. var href = getHref(n);
  7244. // TODO: what if an <image> or <a> element refers to an element internally?
  7245. if(href &&
  7246. ["filter", "linearGradient", "pattern",
  7247. "radialGradient", "textPath", "use"].indexOf(n.nodeName) >= 0)
  7248. {
  7249. var refid = href.substr(1);
  7250. if (!(refid in ids)) {
  7251. // add this id to our map
  7252. ids[refid] = {elem:null, attrs:[], hrefs:[]};
  7253. }
  7254. ids[refid]["hrefs"].push(n);
  7255. }
  7256. }
  7257. });
  7258. // in ids, we now have a map of ids, elements and attributes, let's re-identify
  7259. for (var oldid in ids) {
  7260. var elem = ids[oldid]["elem"];
  7261. if (elem) {
  7262. var newid = getNextId();
  7263. // manually increment obj_num because our cloned elements are not in the DOM yet
  7264. obj_num++;
  7265. // assign element its new id
  7266. elem.id = newid;
  7267. // remap all url() attributes
  7268. var attrs = ids[oldid]["attrs"];
  7269. var j = attrs.length;
  7270. while (j--) {
  7271. var attr = attrs[j];
  7272. attr.ownerElement.setAttribute(attr.name, "url(#" + newid + ")");
  7273. }
  7274. // remap all href attributes
  7275. var hreffers = ids[oldid]["hrefs"];
  7276. var k = hreffers.length;
  7277. while (k--) {
  7278. var hreffer = hreffers[k];
  7279. setHref(hreffer, "#"+newid);
  7280. }
  7281. }
  7282. }
  7283. // manually increment obj_num because our cloned elements are not in the DOM yet
  7284. obj_num++;
  7285. }
  7286. // Function convertGradients
  7287. // Converts gradients from userSpaceOnUse to objectBoundingBox
  7288. var convertGradients = this.convertGradients = function(elem) {
  7289. var elems = $(elem).find('linearGradient, radialGradient');
  7290. if(!elems.length && isWebkit) {
  7291. // Bug in webkit prevents regular *Gradient selector search
  7292. elems = $(elem).find('*').filter(function() {
  7293. return (this.tagName.indexOf('Gradient') >= 0);
  7294. });
  7295. }
  7296. elems.each(function() {
  7297. var grad = this;
  7298. if($(grad).attr('gradientUnits') === 'userSpaceOnUse') {
  7299. // TODO: Support more than one element with this ref by duplicating parent grad
  7300. var elems = $(svgcontent).find('[fill=url(#' + grad.id + ')],[stroke=url(#' + grad.id + ')]');
  7301. if(!elems.length) return;
  7302. // get object's bounding box
  7303. var bb = getBBox(elems[0]);
  7304. if(grad.tagName === 'linearGradient') {
  7305. var g_coords = $(grad).attr(['x1', 'y1', 'x2', 'y2']);
  7306. $(grad).attr({
  7307. x1: (g_coords.x1 - bb.x) / bb.width,
  7308. y1: (g_coords.y1 - bb.y) / bb.height,
  7309. x2: (g_coords.x2 - bb.x) / bb.width,
  7310. y2: (g_coords.y2 - bb.y) / bb.height
  7311. });
  7312. grad.removeAttribute('gradientUnits');
  7313. } else {
  7314. // Note: radialGradient elements cannot be easily converted
  7315. // because userSpaceOnUse will keep circular gradients, while
  7316. // objectBoundingBox will x/y scale the gradient according to
  7317. // its bbox.
  7318. // For now we'll do nothing, though we should probably have
  7319. // the gradient be updated as the element is moved, as
  7320. // inkscape/illustrator do.
  7321. // var g_coords = $(grad).attr(['cx', 'cy', 'r']);
  7322. //
  7323. // $(grad).attr({
  7324. // cx: (g_coords.cx - bb.x) / bb.width,
  7325. // cy: (g_coords.cy - bb.y) / bb.height,
  7326. // r: g_coords.r
  7327. // });
  7328. //
  7329. // grad.removeAttribute('gradientUnits');
  7330. }
  7331. }
  7332. });
  7333. }
  7334. // Function: convertToGroup
  7335. // Converts selected/given <use> or child SVG element to a group
  7336. var convertToGroup = this.convertToGroup = function(elem) {
  7337. if(!elem) {
  7338. elem = selectedElements[0];
  7339. }
  7340. var $elem = $(elem);
  7341. var batchCmd = new BatchCommand();
  7342. var ts;
  7343. if($elem.data('gsvg')) {
  7344. // Use the gsvg as the new group
  7345. var svg = elem.firstChild;
  7346. var pt = $(svg).attr(['x', 'y']);
  7347. $(elem.firstChild.firstChild).unwrap();
  7348. $(elem).removeData('gsvg');
  7349. var tlist = getTransformList(elem);
  7350. var xform = svgroot.createSVGTransform();
  7351. xform.setTranslate(pt.x, pt.y);
  7352. tlist.appendItem(xform);
  7353. recalculateDimensions(elem);
  7354. call("selected", [elem]);
  7355. } else if($elem.data('symbol')) {
  7356. elem = $elem.data('symbol');
  7357. ts = $elem.attr('transform');
  7358. var pos = $elem.attr(['x','y']);
  7359. // if(ts.length) {
  7360. //
  7361. // ts += " ";
  7362. // }
  7363. // Not ideal, but works
  7364. ts += "translate(" + (pos.x || 0) + "," + (pos.x || 0) + ")";
  7365. var prev = $elem.prev();
  7366. // Remove <use> element
  7367. batchCmd.addSubCommand(new RemoveElementCommand($elem[0], $elem[0].parentNode));
  7368. $elem.remove();
  7369. // See if other elements reference this symbol
  7370. var has_more = $(svgcontent).find('use:data(symbol)').length;
  7371. var g = svgdoc.createElementNS(svgns, "g");
  7372. var childs = elem.childNodes;
  7373. for(var i = 0; i < childs.length; i++) {
  7374. g.appendChild(childs[i].cloneNode(true));
  7375. }
  7376. // while (elem.hasChildNodes())
  7377. // g.appendChild(elem.firstChild.cloneNode(true));
  7378. if (ts)
  7379. g.setAttribute("transform", ts);
  7380. console.log('t',g.getAttribute('transform'));
  7381. var parent = elem.parentNode;
  7382. uniquifyElems(g);
  7383. // now give the g itself a new id
  7384. g.id = getNextId();
  7385. prev.after(g);
  7386. if(parent) {
  7387. if(!has_more) {
  7388. // remove symbol/svg element
  7389. parent.removeChild(elem);
  7390. batchCmd.addSubCommand(new RemoveElementCommand(elem, parent));
  7391. }
  7392. batchCmd.addSubCommand(new InsertElementCommand(g));
  7393. }
  7394. convertGradients(g);
  7395. // recalculate dimensions on the top-level children so that unnecessary transforms
  7396. // are removed
  7397. walkTreePost(g, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}});
  7398. // Give ID for any visible element missing one
  7399. $(g).find(visElems).each(function() {
  7400. if(!this.id) this.id = getNextId();
  7401. });
  7402. selectOnly([g]);
  7403. // Temporary hack to get rid of matrix
  7404. // TODO: See what ungroupSelectedElement does to absorb matrix
  7405. canvas.ungroupSelectedElement();
  7406. canvas.groupSelectedElements();
  7407. //
  7408. addCommandToHistory(batchCmd);
  7409. } else {
  7410. console.log('Unexpected element to ungroup:', elem);
  7411. }
  7412. }
  7413. //
  7414. // Function: setSvgString
  7415. // This function sets the current drawing as the input SVG XML.
  7416. //
  7417. // Parameters:
  7418. // xmlString - The SVG as XML text.
  7419. //
  7420. // Returns:
  7421. // This function returns false if the set was unsuccessful, true otherwise.
  7422. this.setSvgString = function(xmlString) {
  7423. try {
  7424. // convert string into XML document
  7425. var newDoc = Utils.text2xml(xmlString);
  7426. // run it through our sanitizer to remove anything we do not support
  7427. sanitizeSvg(newDoc.documentElement);
  7428. var batchCmd = new BatchCommand("Change Source");
  7429. // remove old svg document
  7430. var oldzoom = svgroot.removeChild(svgcontent);
  7431. batchCmd.addSubCommand(new RemoveElementCommand(oldzoom, svgroot));
  7432. // set new svg document
  7433. svgcontent = svgroot.appendChild(svgdoc.importNode(newDoc.documentElement, true));
  7434. var content = $(svgcontent);
  7435. // retrieve or set the nonce
  7436. n = svgcontent.getAttributeNS(se_ns, 'nonce');
  7437. if (n) {
  7438. randomize_ids = true;
  7439. nonce = n;
  7440. if (extensions["Arrows"]) call("setarrownonce", n) ;
  7441. } else if (randomize_ids) {
  7442. svgcontent.setAttributeNS(xmlnsns, 'xmlns:se', se_ns);
  7443. svgcontent.setAttributeNS(se_ns, 'se:nonce', nonce);
  7444. if (extensions["Arrows"]) call("setarrownonce", nonce) ;
  7445. }
  7446. // change image href vals if possible
  7447. content.find('image').each(function() {
  7448. var image = this;
  7449. preventClickDefault(image);
  7450. var val = getHref(this);
  7451. if(val.indexOf('data:') === 0) {
  7452. // Check if an SVG-edit data URI
  7453. var m = val.match(/svgedit_url=(.*?);/);
  7454. if(m) {
  7455. var url = decodeURIComponent(m[1]);
  7456. $(new Image()).load(function() {
  7457. image.setAttributeNS(xlinkns,'xlink:href',url);
  7458. }).attr('src',url);
  7459. }
  7460. }
  7461. // Add to encodableImages if it loads
  7462. canvas.embedImage(val);
  7463. });
  7464. // Wrap child SVGs in group elements
  7465. content.find('svg').each(function() {
  7466. // Skip if it's in a <defs>
  7467. if($(this).closest('defs').length) return;
  7468. uniquifyElems(this);
  7469. // Check if it already has a gsvg group
  7470. var pa = this.parentNode;
  7471. if(pa.childNodes.length === 1 && pa.nodeName === 'g') {
  7472. $(pa).data('gsvg', this);
  7473. pa.id = pa.id || getNextId();
  7474. } else {
  7475. groupSvgElem(this);
  7476. }
  7477. });
  7478. // For Firefox: Put all gradients in defs
  7479. if(isGecko) {
  7480. content.find('linearGradient, radialGradient').appendTo(findDefs());
  7481. }
  7482. // Set ref element for <use> elements
  7483. // TODO: This should also be done if the object is re-added through "redo"
  7484. content.find('use').each(function() {
  7485. var id = getHref(this).substr(1);
  7486. var ref_elem = getElem(id);
  7487. $(this).data('ref', ref_elem);
  7488. if(ref_elem.tagName == 'symbol' || ref_elem.tagName == 'svg') {
  7489. $(this).data('symbol', ref_elem);
  7490. }
  7491. });
  7492. convertGradients(content[0]);
  7493. // recalculate dimensions on the top-level children so that unnecessary transforms
  7494. // are removed
  7495. walkTreePost(svgcontent, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}});
  7496. var attrs = {
  7497. id: 'svgcontent',
  7498. overflow: curConfig.show_outside_canvas?'visible':'hidden'
  7499. };
  7500. var percs = false;
  7501. // determine proper size
  7502. if (content.attr("viewBox")) {
  7503. var vb = content.attr("viewBox").split(' ');
  7504. attrs.width = vb[2];
  7505. attrs.height = vb[3];
  7506. }
  7507. // handle content that doesn't have a viewBox
  7508. else {
  7509. $.each(['width', 'height'], function(i, dim) {
  7510. // Set to 100 if not given
  7511. var val = content.attr(dim);
  7512. if(!val) val = '100%';
  7513. if((val+'').substr(-1) === "%") {
  7514. // Use user units if percentage given
  7515. percs = true;
  7516. } else {
  7517. attrs[dim] = convertToNum(dim, val);
  7518. }
  7519. });
  7520. }
  7521. // identify layers
  7522. identifyLayers();
  7523. // Give ID for any visible layer children missing one
  7524. content.children().find(visElems).each(function() {
  7525. if(!this.id) this.id = getNextId();
  7526. });
  7527. // Percentage width/height, so let's base it on visible elements
  7528. if(percs) {
  7529. var bb = getStrokedBBox();
  7530. attrs.width = bb.width + bb.x;
  7531. attrs.height = bb.height + bb.y;
  7532. }
  7533. // Just in case negative numbers are given or
  7534. // result from the percs calculation
  7535. if(attrs.width <= 0) attrs.width = 100;
  7536. if(attrs.height <= 0) attrs.height = 100;
  7537. content.attr(attrs);
  7538. this.contentW = attrs['width'];
  7539. this.contentH = attrs['height'];
  7540. batchCmd.addSubCommand(new InsertElementCommand(svgcontent));
  7541. // update root to the correct size
  7542. var changes = content.attr(["width", "height"]);
  7543. batchCmd.addSubCommand(new ChangeElementCommand(svgroot, changes));
  7544. // reset zoom
  7545. current_zoom = 1;
  7546. // reset transform lists
  7547. svgTransformLists = {};
  7548. clearSelection();
  7549. pathActions.clearData();
  7550. svgroot.appendChild(selectorManager.selectorParentGroup);
  7551. addCommandToHistory(batchCmd);
  7552. call("changed", [svgcontent]);
  7553. } catch(e) {
  7554. console.log(e);
  7555. return false;
  7556. }
  7557. return true;
  7558. };
  7559. // Function: importSvgString
  7560. // This function imports the input SVG XML as a <symbol> in the <defs>, then adds a
  7561. // <use> to the current layer.
  7562. //
  7563. // Parameters:
  7564. // xmlString - The SVG as XML text.
  7565. //
  7566. // Returns:
  7567. // This function returns false if the import was unsuccessful, true otherwise.
  7568. // TODO:
  7569. // * properly handle if namespace is introduced by imported content (must add to svgcontent
  7570. // and update all prefixes in the imported node)
  7571. // * properly handle recalculating dimensions, recalculateDimensions() doesn't handle
  7572. // arbitrary transform lists, but makes some assumptions about how the transform list
  7573. // was obtained
  7574. // * import should happen in top-left of current zoomed viewport
  7575. this.importSvgString = function(xmlString) {
  7576. try {
  7577. // convert string into XML document
  7578. var newDoc = Utils.text2xml(xmlString);
  7579. // run it through our sanitizer to remove anything we do not support
  7580. sanitizeSvg(newDoc.documentElement);
  7581. var batchCmd = new BatchCommand("Change Source");
  7582. // import new svg document into our document
  7583. var svg = svgdoc.importNode(newDoc.documentElement, true);
  7584. var innerw = convertToNum('width', svg.getAttribute("width")),
  7585. innerh = convertToNum('height', svg.getAttribute("height")),
  7586. innervb = svg.getAttribute("viewBox"),
  7587. // if no explicit viewbox, create one out of the width and height
  7588. vb = innervb ? innervb.split(" ") : [0,0,innerw,innerh];
  7589. for (var j = 0; j < 4; ++j)
  7590. vb[j] = Number(vb[j]);
  7591. // TODO: properly handle preserveAspectRatio
  7592. var canvasw = Number(svgcontent.getAttribute("width")),
  7593. canvash = Number(svgcontent.getAttribute("height"));
  7594. // imported content should be 1/3 of the canvas on its largest dimension
  7595. if (innerh > innerw) {
  7596. var ts = "scale(" + (canvash/3)/vb[3] + ")";
  7597. }
  7598. else {
  7599. var ts = "scale(" + (canvash/3)/vb[2] + ")";
  7600. }
  7601. // Hack to make recalculateDimensions understand how to scale
  7602. ts = "translate(0) " + ts + " translate(0)";
  7603. // Uncomment this once Firefox has fixed their symbol bug:
  7604. // https://bugzilla.mozilla.org/show_bug.cgi?id=353575
  7605. var symbol = svgdoc.createElementNS(svgns, "symbol");
  7606. var defs = findDefs();
  7607. while (svg.firstChild) {
  7608. var first = svg.firstChild;
  7609. if(isGecko && first.tagName === 'defs') {
  7610. // Move all gradients into root for Firefox
  7611. $(first).find('linearGradient, radialGradient').appendTo(defs);
  7612. }
  7613. symbol.appendChild(first);
  7614. }
  7615. var attrs = svg.attributes;
  7616. for(var i=0; i < attrs.length; i++) {
  7617. var attr = attrs[i];
  7618. symbol.setAttribute(attr.nodeName, attr.nodeValue);
  7619. }
  7620. // var symbol = svg;
  7621. symbol.id = getNextId();
  7622. var use_el = svgdoc.createElementNS(svgns, "use");
  7623. setHref(use_el, "#" + symbol.id);
  7624. findDefs().appendChild(symbol);
  7625. (current_group || current_layer).appendChild(use_el);
  7626. use_el.id = getNextId();
  7627. clearSelection();
  7628. use_el.setAttribute("transform", ts);
  7629. recalculateDimensions(use_el);
  7630. $(use_el).data('symbol', symbol);
  7631. addToSelection([use_el]);
  7632. return true;
  7633. // TODO: Find way to add this in a recalculateDimensions-parsable way
  7634. // if (vb[0] != 0 || vb[1] != 0)
  7635. // ts = "translate(" + (-vb[0]) + "," + (-vb[1]) + ") " + ts;
  7636. } catch(e) {
  7637. console.log(e);
  7638. return false;
  7639. }
  7640. return true;
  7641. };
  7642. // Layer API Functions
  7643. // Group: Layers
  7644. // Function: identifyLayers
  7645. // Updates layer system
  7646. var identifyLayers = function() {
  7647. all_layers = [];
  7648. leaveContext();
  7649. var numchildren = svgcontent.childNodes.length;
  7650. // loop through all children of svgcontent
  7651. var orphans = [], layernames = [];
  7652. for (var i = 0; i < numchildren; ++i) {
  7653. var child = svgcontent.childNodes.item(i);
  7654. // for each g, find its layer name
  7655. if (child && child.nodeType == 1) {
  7656. if (child.tagName == "g") {
  7657. var name = $("title",child).text();
  7658. // Hack for Opera 10.60
  7659. if(!name && isOpera && child.querySelectorAll) {
  7660. name = $(child.querySelectorAll('title')).text();
  7661. }
  7662. // store layer and name in global variable
  7663. if (name) {
  7664. layernames.push(name);
  7665. all_layers.push( [name,child] );
  7666. current_layer = child;
  7667. walkTree(child, function(e){e.setAttribute("style", "pointer-events:inherit");});
  7668. current_layer.setAttribute("style", "pointer-events:none");
  7669. }
  7670. // if group did not have a name, it is an orphan
  7671. else {
  7672. orphans.push(child);
  7673. }
  7674. }
  7675. // if child has a bbox (i.e. not a <title> or <defs> element), then it is an orphan
  7676. else if(getBBox(child) && child.nodeName != 'defs') { // Opera returns a BBox for defs
  7677. var bb = getBBox(child);
  7678. orphans.push(child);
  7679. }
  7680. }
  7681. }
  7682. // create a new layer and add all the orphans to it
  7683. if (orphans.length > 0) {
  7684. var i = 1;
  7685. while (layernames.indexOf(("Layer " + i)) >= 0) { i++; }
  7686. var newname = "Layer " + i;
  7687. current_layer = svgdoc.createElementNS(svgns, "g");
  7688. var layer_title = svgdoc.createElementNS(svgns, "title");
  7689. layer_title.textContent = newname;
  7690. current_layer.appendChild(layer_title);
  7691. for (var j = 0; j < orphans.length; ++j) {
  7692. current_layer.appendChild(orphans[j]);
  7693. }
  7694. current_layer = svgcontent.appendChild(current_layer);
  7695. all_layers.push( [newname, current_layer] );
  7696. }
  7697. walkTree(current_layer, function(e){e.setAttribute("style","pointer-events:inherit");});
  7698. current_layer.setAttribute("style","pointer-events:all");
  7699. };
  7700. // Function: createLayer
  7701. // Creates a new top-level layer in the drawing with the given name, sets the current layer
  7702. // to it, and then clears the selection This function then calls the 'changed' handler.
  7703. // This is an undoable action.
  7704. //
  7705. // Parameters:
  7706. // name - The given name
  7707. this.createLayer = function(name) {
  7708. var batchCmd = new BatchCommand("Create Layer");
  7709. var new_layer = svgdoc.createElementNS(svgns, "g");
  7710. var layer_title = svgdoc.createElementNS(svgns, "title");
  7711. layer_title.textContent = name;
  7712. new_layer.appendChild(layer_title);
  7713. new_layer = svgcontent.appendChild(new_layer);
  7714. batchCmd.addSubCommand(new InsertElementCommand(new_layer));
  7715. addCommandToHistory(batchCmd);
  7716. clearSelection();
  7717. identifyLayers();
  7718. canvas.setCurrentLayer(name);
  7719. call("changed", [new_layer]);
  7720. };
  7721. // Function: cloneLayer
  7722. // Creates a new top-level layer in the drawing with the given name, copies all the current layer's contents
  7723. // to it, and then clears the selection This function then calls the 'changed' handler.
  7724. // This is an undoable action.
  7725. //
  7726. // Parameters:
  7727. // name - The given name
  7728. this.cloneLayer = function(name) {
  7729. var batchCmd = new BatchCommand("Duplicate Layer");
  7730. var new_layer = svgdoc.createElementNS(svgns, "g");
  7731. var layer_title = svgdoc.createElementNS(svgns, "title");
  7732. layer_title.textContent = name;
  7733. new_layer.appendChild(layer_title);
  7734. $(current_layer).after(new_layer);
  7735. var childs = current_layer.childNodes;
  7736. for(var i = 0; i < childs.length; i++) {
  7737. var ch = childs[i];
  7738. if(ch.localName == 'title') continue;
  7739. new_layer.appendChild(copyElem(ch));
  7740. }
  7741. clearSelection();
  7742. identifyLayers();
  7743. batchCmd.addSubCommand(new InsertElementCommand(new_layer));
  7744. addCommandToHistory(batchCmd);
  7745. canvas.setCurrentLayer(name);
  7746. call("changed", [new_layer]);
  7747. };
  7748. // Function: deleteCurrentLayer
  7749. // Deletes the current layer from the drawing and then clears the selection. This function
  7750. // then calls the 'changed' handler. This is an undoable action.
  7751. this.deleteCurrentLayer = function() {
  7752. if (current_layer && all_layers.length > 1) {
  7753. var batchCmd = new BatchCommand("Delete Layer");
  7754. // actually delete from the DOM and store in our Undo History
  7755. var parent = current_layer.parentNode;
  7756. batchCmd.addSubCommand(new RemoveElementCommand(current_layer, parent));
  7757. parent.removeChild(current_layer);
  7758. addCommandToHistory(batchCmd);
  7759. clearSelection();
  7760. identifyLayers();
  7761. canvas.setCurrentLayer(all_layers[all_layers.length-1][0]);
  7762. call("changed", [svgcontent]);
  7763. return true;
  7764. }
  7765. return false;
  7766. };
  7767. // Function: hasLayer
  7768. // Check if layer with given name already exists
  7769. this.hasLayer = function(name) {
  7770. for(var i = 0; i < all_layers.length; i++) {
  7771. if(all_layers[i][0] == name) return true;
  7772. }
  7773. return false;
  7774. };
  7775. // Function: getNumLayers
  7776. // Returns the number of layers in the current drawing.
  7777. //
  7778. // Returns:
  7779. // The number of layers in the current drawing.
  7780. this.getNumLayers = function() {
  7781. return all_layers.length;
  7782. };
  7783. // Function: getLayer
  7784. // Returns the name of the ith layer. If the index is out of range, an empty string is returned.
  7785. //
  7786. // Parameters:
  7787. // i - the zero-based index of the layer you are querying.
  7788. //
  7789. // Returns:
  7790. // The name of the ith layer
  7791. this.getLayer = function(i) {
  7792. if (i >= 0 && i < canvas.getNumLayers()) {
  7793. return all_layers[i][0];
  7794. }
  7795. return "";
  7796. };
  7797. // Function: getCurrentLayer
  7798. // Returns the name of the currently selected layer. If an error occurs, an empty string
  7799. // is returned.
  7800. //
  7801. // Returns:
  7802. // The name of the currently active layer.
  7803. this.getCurrentLayer = function() {
  7804. for (var i = 0; i < all_layers.length; ++i) {
  7805. if (all_layers[i][1] == current_layer) {
  7806. return all_layers[i][0];
  7807. }
  7808. }
  7809. return "";
  7810. };
  7811. // Function: setCurrentLayer
  7812. // Sets the current layer. If the name is not a valid layer name, then this function returns
  7813. // false. Otherwise it returns true. This is not an undo-able action.
  7814. //
  7815. // Parameters:
  7816. // name - the name of the layer you want to switch to.
  7817. //
  7818. // Returns:
  7819. // true if the current layer was switched, otherwise false
  7820. this.setCurrentLayer = function(name) {
  7821. name = Utils.toXml(name);
  7822. for (var i = 0; i < all_layers.length; ++i) {
  7823. if (name == all_layers[i][0]) {
  7824. if (current_layer != all_layers[i][1]) {
  7825. clearSelection();
  7826. current_layer.setAttribute("style", "pointer-events:none");
  7827. current_layer = all_layers[i][1];
  7828. current_layer.setAttribute("style", "pointer-events:all");
  7829. }
  7830. return true;
  7831. }
  7832. }
  7833. return false;
  7834. };
  7835. // Function: renameCurrentLayer
  7836. // Renames the current layer. If the layer name is not valid (i.e. unique), then this function
  7837. // does nothing and returns false, otherwise it returns true. This is an undo-able action.
  7838. //
  7839. // Parameters:
  7840. // newname - the new name you want to give the current layer. This name must be unique
  7841. // among all layer names.
  7842. //
  7843. // Returns:
  7844. // true if the rename succeeded, false otherwise.
  7845. this.renameCurrentLayer = function(newname) {
  7846. if (current_layer) {
  7847. var oldLayer = current_layer;
  7848. // setCurrentLayer will return false if the name doesn't already exists
  7849. if (!canvas.setCurrentLayer(newname)) {
  7850. var batchCmd = new BatchCommand("Rename Layer");
  7851. // find the index of the layer
  7852. for (var i = 0; i < all_layers.length; ++i) {
  7853. if (all_layers[i][1] == oldLayer) break;
  7854. }
  7855. var oldname = all_layers[i][0];
  7856. all_layers[i][0] = Utils.toXml(newname);
  7857. // now change the underlying title element contents
  7858. var len = oldLayer.childNodes.length;
  7859. for (var i = 0; i < len; ++i) {
  7860. var child = oldLayer.childNodes.item(i);
  7861. // found the <title> element, now append all the
  7862. if (child && child.tagName == "title") {
  7863. // wipe out old name
  7864. while (child.firstChild) { child.removeChild(child.firstChild); }
  7865. child.textContent = newname;
  7866. batchCmd.addSubCommand(new ChangeElementCommand(child, {"#text":oldname}));
  7867. addCommandToHistory(batchCmd);
  7868. call("changed", [oldLayer]);
  7869. return true;
  7870. }
  7871. }
  7872. }
  7873. current_layer = oldLayer;
  7874. }
  7875. return false;
  7876. };
  7877. // Function: setCurrentLayerPosition
  7878. // Changes the position of the current layer to the new value. If the new index is not valid,
  7879. // this function does nothing and returns false, otherwise it returns true. This is an
  7880. // undo-able action.
  7881. //
  7882. // Parameters:
  7883. // newpos - The zero-based index of the new position of the layer. This should be between
  7884. // 0 and (number of layers - 1)
  7885. //
  7886. // Returns:
  7887. // true if the current layer position was changed, false otherwise.
  7888. this.setCurrentLayerPosition = function(newpos) {
  7889. if (current_layer && newpos >= 0 && newpos < all_layers.length) {
  7890. for (var oldpos = 0; oldpos < all_layers.length; ++oldpos) {
  7891. if (all_layers[oldpos][1] == current_layer) break;
  7892. }
  7893. // some unknown error condition (current_layer not in all_layers)
  7894. if (oldpos == all_layers.length) { return false; }
  7895. if (oldpos != newpos) {
  7896. // if our new position is below us, we need to insert before the node after newpos
  7897. var refLayer = null;
  7898. var oldNextSibling = current_layer.nextSibling;
  7899. if (newpos > oldpos ) {
  7900. if (newpos < all_layers.length-1) {
  7901. refLayer = all_layers[newpos+1][1];
  7902. }
  7903. }
  7904. // if our new position is above us, we need to insert before the node at newpos
  7905. else {
  7906. refLayer = all_layers[newpos][1];
  7907. }
  7908. svgcontent.insertBefore(current_layer, refLayer);
  7909. addCommandToHistory(new MoveElementCommand(current_layer, oldNextSibling, svgcontent));
  7910. identifyLayers();
  7911. canvas.setCurrentLayer(all_layers[newpos][0]);
  7912. return true;
  7913. }
  7914. }
  7915. return false;
  7916. };
  7917. // Function: getLayerVisibility
  7918. // Returns whether the layer is visible. If the layer name is not valid, then this function
  7919. // returns false.
  7920. //
  7921. // Parameters:
  7922. // layername - the name of the layer which you want to query.
  7923. //
  7924. // Returns:
  7925. // The visibility state of the layer, or false if the layer name was invalid.
  7926. this.getLayerVisibility = function(layername) {
  7927. // find the layer
  7928. var layer = null;
  7929. for (var i = 0; i < all_layers.length; ++i) {
  7930. if (all_layers[i][0] == layername) {
  7931. layer = all_layers[i][1];
  7932. break;
  7933. }
  7934. }
  7935. if (!layer) return false;
  7936. return (layer.getAttribute("display") != "none");
  7937. };
  7938. // Function: setLayerVisibility
  7939. // Sets the visibility of the layer. If the layer name is not valid, this function return
  7940. // false, otherwise it returns true. This is an undo-able action.
  7941. //
  7942. // Parameters:
  7943. // layername - the name of the layer to change the visibility
  7944. // bVisible - true/false, whether the layer should be visible
  7945. //
  7946. // Returns:
  7947. // true if the layer's visibility was set, false otherwise
  7948. this.setLayerVisibility = function(layername, bVisible) {
  7949. // find the layer
  7950. var layer = null;
  7951. for (var i = 0; i < all_layers.length; ++i) {
  7952. if (all_layers[i][0] == layername) {
  7953. layer = all_layers[i][1];
  7954. break;
  7955. }
  7956. }
  7957. if (!layer) return false;
  7958. var oldDisplay = layer.getAttribute("display");
  7959. if (!oldDisplay) oldDisplay = "inline";
  7960. layer.setAttribute("display", bVisible ? "inline" : "none");
  7961. addCommandToHistory(new ChangeElementCommand(layer, {"display":oldDisplay}, "Layer Visibility"));
  7962. if (layer == current_layer) {
  7963. clearSelection();
  7964. pathActions.clear();
  7965. }
  7966. // call("changed", [selected]);
  7967. return true;
  7968. };
  7969. // Function: moveSelectedToLayer
  7970. // Moves the selected elements to layername. If the name is not a valid layer name, then false
  7971. // is returned. Otherwise it returns true. This is an undo-able action.
  7972. //
  7973. // Parameters:
  7974. // layername - the name of the layer you want to which you want to move the selected elements
  7975. //
  7976. // Returns:
  7977. // true if the selected elements were moved to the layer, false otherwise.
  7978. this.moveSelectedToLayer = function(layername) {
  7979. // find the layer
  7980. var layer = null;
  7981. for (var i = 0; i < all_layers.length; ++i) {
  7982. if (all_layers[i][0] == layername) {
  7983. layer = all_layers[i][1];
  7984. break;
  7985. }
  7986. }
  7987. if (!layer) return false;
  7988. var batchCmd = new BatchCommand("Move Elements to Layer");
  7989. // loop for each selected element and move it
  7990. var selElems = selectedElements;
  7991. var i = selElems.length;
  7992. while (i--) {
  7993. var elem = selElems[i];
  7994. if (!elem) continue;
  7995. var oldNextSibling = elem.nextSibling;
  7996. // TODO: this is pretty brittle!
  7997. var oldLayer = elem.parentNode;
  7998. layer.appendChild(elem);
  7999. batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldLayer));
  8000. }
  8001. addCommandToHistory(batchCmd);
  8002. return true;
  8003. };
  8004. this.mergeLayer = function(skipHistory) {
  8005. var batchCmd = new BatchCommand("Merge Layer");
  8006. var prev = $(current_layer).prev()[0];
  8007. if(!prev) return;
  8008. var childs = current_layer.childNodes;
  8009. var len = childs.length;
  8010. batchCmd.addSubCommand(new RemoveElementCommand(current_layer, svgcontent));
  8011. while(current_layer.firstChild) {
  8012. var ch = current_layer.firstChild;
  8013. if(ch.localName == 'title') {
  8014. batchCmd.addSubCommand(new RemoveElementCommand(ch, current_layer));
  8015. current_layer.removeChild(ch);
  8016. continue;
  8017. }
  8018. var oldNextSibling = ch.nextSibling;
  8019. prev.appendChild(ch);
  8020. batchCmd.addSubCommand(new MoveElementCommand(ch, oldNextSibling, current_layer));
  8021. }
  8022. // Remove current layer
  8023. svgcontent.removeChild(current_layer);
  8024. if(!skipHistory) {
  8025. clearSelection();
  8026. identifyLayers();
  8027. call("changed", [svgcontent]);
  8028. addCommandToHistory(batchCmd);
  8029. }
  8030. current_layer = prev;
  8031. return batchCmd;
  8032. }
  8033. this.mergeAllLayers = function() {
  8034. var batchCmd = new BatchCommand("Merge all Layers");
  8035. current_layer = all_layers[all_layers.length-1][1];
  8036. while($(svgcontent).children('g').length > 1) {
  8037. batchCmd.addSubCommand(canvas.mergeLayer(true));
  8038. }
  8039. clearSelection();
  8040. identifyLayers();
  8041. call("changed", [svgcontent]);
  8042. addCommandToHistory(batchCmd);
  8043. }
  8044. // Function: getLayerOpacity
  8045. // Returns the opacity of the given layer. If the input name is not a layer, null is returned.
  8046. //
  8047. // Parameters:
  8048. // layername - name of the layer on which to get the opacity
  8049. //
  8050. // Returns:
  8051. // The opacity value of the given layer. This will be a value between 0.0 and 1.0, or null
  8052. // if layername is not a valid layer
  8053. this.getLayerOpacity = function(layername) {
  8054. for (var i = 0; i < all_layers.length; ++i) {
  8055. if (all_layers[i][0] == layername) {
  8056. var g = all_layers[i][1];
  8057. var opacity = g.getAttribute("opacity");
  8058. if (!opacity) {
  8059. opacity = "1.0";
  8060. }
  8061. return parseFloat(opacity);
  8062. }
  8063. }
  8064. return null;
  8065. };
  8066. // Function: setLayerOpacity
  8067. // Sets the opacity of the given layer. If the input name is not a layer, nothing happens.
  8068. // This is not an undo-able action. NOTE: this function exists solely to apply
  8069. // a highlighting/de-emphasis effect to a layer, when it is possible for a user to affect
  8070. // the opacity of a layer, we will need to allow this function to produce an undo-able action.
  8071. // If opacity is not a value between 0.0 and 1.0, then nothing happens.
  8072. //
  8073. // Parameters:
  8074. // layername - name of the layer on which to set the opacity
  8075. // opacity - a float value in the range 0.0-1.0
  8076. this.setLayerOpacity = function(layername, opacity) {
  8077. if (opacity < 0.0 || opacity > 1.0) return;
  8078. for (var i = 0; i < all_layers.length; ++i) {
  8079. if (all_layers[i][0] == layername) {
  8080. var g = all_layers[i][1];
  8081. g.setAttribute("opacity", opacity);
  8082. break;
  8083. }
  8084. }
  8085. };
  8086. // Function: leaveContext
  8087. // Return from a group context to the regular kind, make any previously
  8088. // disabled elements enabled again
  8089. var leaveContext = this.leaveContext = function() {
  8090. var len = disabled_elems.length;
  8091. if(len) {
  8092. for(var i = 0; i < len; i++) {
  8093. var elem = disabled_elems[i];
  8094. var orig = elData(elem, 'orig_opac');
  8095. if(orig !== 1) {
  8096. elem.setAttribute('opacity', orig);
  8097. } else {
  8098. elem.removeAttribute('opacity');
  8099. }
  8100. elem.setAttribute('style', 'pointer-events: inherit');
  8101. }
  8102. disabled_elems = [];
  8103. clearSelection(true);
  8104. call("contextset", null);
  8105. }
  8106. current_group = null;
  8107. }
  8108. // Function: setContext
  8109. // Set the current context (for in-group editing)
  8110. var setContext = this.setContext = function(elem) {
  8111. leaveContext();
  8112. if(typeof elem === 'string') {
  8113. elem = getElem(elem);
  8114. }
  8115. // Edit inside this group
  8116. current_group = elem;
  8117. // Disable other elements
  8118. $(elem).parentsUntil('#svgcontent').andSelf().siblings().each(function() {
  8119. var opac = this.getAttribute('opacity') || 1;
  8120. // Store the original's opacity
  8121. elData(this, 'orig_opac', opac);
  8122. this.setAttribute('opacity', opac * .33);
  8123. this.setAttribute('style', 'pointer-events: none');
  8124. disabled_elems.push(this);
  8125. });
  8126. clearSelection();
  8127. call("contextset", current_group);
  8128. }
  8129. // Group: Document functions
  8130. // Function: clear
  8131. // Clears the current document. This is not an undoable action.
  8132. this.clear = function() {
  8133. pathActions.clear();
  8134. // clear the svgcontent node
  8135. var nodes = svgcontent.childNodes;
  8136. var len = svgcontent.childNodes.length;
  8137. var i = 0;
  8138. clearSelection();
  8139. for(var rep = 0; rep < len; rep++){
  8140. if (nodes[i].nodeType == 1) { // element node
  8141. svgcontent.removeChild(nodes[i]);
  8142. } else {
  8143. i++;
  8144. }
  8145. }
  8146. // create empty first layer
  8147. all_layers = [];
  8148. canvas.createLayer("Layer 1");
  8149. // clear the undo stack
  8150. canvas.undoMgr.resetUndoStack();
  8151. // reset the selector manager
  8152. selectorManager.initGroup();
  8153. // reset the rubber band box
  8154. rubberBox = selectorManager.getRubberBandBox();
  8155. call("cleared");
  8156. };
  8157. // Function: linkControlPoints
  8158. // Alias function
  8159. this.linkControlPoints = pathActions.linkControlPoints;
  8160. // Function: getContentElem
  8161. // Returns the content DOM element
  8162. this.getContentElem = function() { return svgcontent; };
  8163. // Function: getRootElem
  8164. // Returns the root DOM element
  8165. this.getRootElem = function() { return svgroot; };
  8166. // Function: getSelectedElems
  8167. // Returns the array with selected DOM elements
  8168. this.getSelectedElems = function() { return selectedElements; };
  8169. // Function: getResolution
  8170. // Returns the current dimensions and zoom level in an object
  8171. var getResolution = this.getResolution = function() {
  8172. // var vb = svgcontent.getAttribute("viewBox").split(' ');
  8173. // return {'w':vb[2], 'h':vb[3], 'zoom': current_zoom};
  8174. return {
  8175. 'w':svgcontent.getAttribute("width")/current_zoom,
  8176. 'h':svgcontent.getAttribute("height")/current_zoom,
  8177. 'zoom': current_zoom
  8178. };
  8179. };
  8180. // Function: getZoom
  8181. // Returns the current zoom level
  8182. this.getZoom = function(){return current_zoom;};
  8183. // Function: getVersion
  8184. // Returns a string which describes the revision number of SvgCanvas.
  8185. this.getVersion = function() {
  8186. return "svgcanvas.js ($Rev: 1776 $)";
  8187. };
  8188. // Function: setUiStrings
  8189. // Update interface strings with given values
  8190. //
  8191. // Parameters:
  8192. // strs - Object with strings (see uiStrings for examples)
  8193. this.setUiStrings = function(strs) {
  8194. $.extend(uiStrings, strs);
  8195. }
  8196. // Function: setConfig
  8197. // Update configuration options with given values
  8198. //
  8199. // Parameters:
  8200. // opts - Object with options (see curConfig for examples)
  8201. this.setConfig = function(opts) {
  8202. $.extend(curConfig, opts);
  8203. }
  8204. // Function: getDocumentTitle
  8205. // Returns the current group/SVG's title contents
  8206. this.getTitle = function(elem) {
  8207. elem = elem || selectedElements[0];
  8208. if(!elem) return;
  8209. elem = $(elem).data('gsvg') || $(elem).data('symbol') || elem;
  8210. var childs = elem.childNodes;
  8211. for (var i=0; i<childs.length; i++) {
  8212. if(childs[i].nodeName == 'title') {
  8213. return childs[i].textContent;
  8214. }
  8215. }
  8216. return '';
  8217. }
  8218. // Function: getHref
  8219. // Returns the given element's xlink:href value
  8220. var getHref = this.getHref = function(elem) {
  8221. return elem.getAttributeNS(xlinkns, "href");
  8222. }
  8223. // Function: setHref
  8224. // Sets the given element's xlink:href value
  8225. var setHref = this.setHref = function(elem, val) {
  8226. elem.setAttributeNS(xlinkns, "xlink:href", val);
  8227. }
  8228. // Function: setGroupTitle
  8229. // Sets the group/SVG's title content
  8230. // TODO: Combine this with setDocumentTitle
  8231. this.setGroupTitle = function(val) {
  8232. var elem = selectedElements[0];
  8233. elem = $(elem).data('gsvg') || elem;
  8234. var ts = $(elem).children('title');
  8235. var batchCmd = new BatchCommand("Set Label");
  8236. if(!val.length) {
  8237. // Remove title element
  8238. batchCmd.addSubCommand(new RemoveElementCommand(ts[0], elem));
  8239. ts.remove();
  8240. } else if(ts.length) {
  8241. // Change title contents
  8242. var title = ts[0];
  8243. batchCmd.addSubCommand(new ChangeElementCommand(title, {'#text': title.textContent}));
  8244. title.textContent = val;
  8245. } else {
  8246. // Add title element
  8247. title = svgdoc.createElementNS(svgns, "title");
  8248. title.textContent = val;
  8249. $(elem).prepend(title);
  8250. batchCmd.addSubCommand(new InsertElementCommand(title));
  8251. }
  8252. addCommandToHistory(batchCmd);
  8253. }
  8254. // Function: getDocumentTitle
  8255. // Returns the current document title or an empty string if not found
  8256. this.getDocumentTitle = function() {
  8257. return canvas.getTitle(svgcontent);
  8258. }
  8259. // Function: setDocumentTitle
  8260. // Adds/updates a title element for the document with the given name.
  8261. // This is an undoable action
  8262. //
  8263. // Parameters:
  8264. // newtitle - String with the new title
  8265. this.setDocumentTitle = function(newtitle) {
  8266. var childs = svgcontent.childNodes, doc_title = false, old_title = '';
  8267. var batchCmd = new BatchCommand("Change Image Title");
  8268. for (var i=0; i<childs.length; i++) {
  8269. if(childs[i].nodeName == 'title') {
  8270. doc_title = childs[i];
  8271. old_title = doc_title.textContent;
  8272. break;
  8273. }
  8274. }
  8275. if(!doc_title) {
  8276. doc_title = svgdoc.createElementNS(svgns, "title");
  8277. svgcontent.insertBefore(doc_title, svgcontent.firstChild);
  8278. }
  8279. if(newtitle.length) {
  8280. doc_title.textContent = newtitle;
  8281. } else {
  8282. // No title given, so element is not necessary
  8283. doc_title.parentNode.removeChild(doc_title);
  8284. }
  8285. batchCmd.addSubCommand(new ChangeElementCommand(doc_title, {'#text': old_title}));
  8286. addCommandToHistory(batchCmd);
  8287. }
  8288. // Function: getEditorNS
  8289. // Returns the editor's namespace URL, optionally adds it to root element
  8290. //
  8291. // Parameters:
  8292. // add - Boolean to indicate whether or not to add the namespace value
  8293. this.getEditorNS = function(add) {
  8294. if(add) {
  8295. svgcontent.setAttribute('xmlns:se', se_ns);
  8296. }
  8297. return se_ns;
  8298. }
  8299. // Function: setResolution
  8300. // Changes the document's dimensions to the given size
  8301. //
  8302. // Parameters:
  8303. // x - Number with the width of the new dimensions in user units.
  8304. // Can also be the string "fit" to indicate "fit to content"
  8305. // y - Number with the height of the new dimensions in user units.
  8306. //
  8307. // Returns:
  8308. // Boolean to indicate if resolution change was succesful.
  8309. // It will fail on "fit to content" option with no content to fit to.
  8310. this.setResolution = function(x, y) {
  8311. var res = getResolution();
  8312. var w = res.w, h = res.h;
  8313. var batchCmd;
  8314. if(x == 'fit') {
  8315. // Get bounding box
  8316. var bbox = getStrokedBBox();
  8317. if(bbox) {
  8318. batchCmd = new BatchCommand("Fit Canvas to Content");
  8319. var visEls = getVisibleElements();
  8320. addToSelection(visEls);
  8321. var dx = [], dy = [];
  8322. $.each(visEls, function(i, item) {
  8323. dx.push(bbox.x*-1);
  8324. dy.push(bbox.y*-1);
  8325. });
  8326. var cmd = canvas.moveSelectedElements(dx, dy, true);
  8327. batchCmd.addSubCommand(cmd);
  8328. clearSelection();
  8329. x = Math.round(bbox.width);
  8330. y = Math.round(bbox.height);
  8331. } else {
  8332. return false;
  8333. }
  8334. }
  8335. if (x != w || y != h) {
  8336. var handle = svgroot.suspendRedraw(1000);
  8337. if(!batchCmd) {
  8338. batchCmd = new BatchCommand("Change Image Dimensions");
  8339. }
  8340. x = convertToNum('width', x);
  8341. y = convertToNum('height', y);
  8342. svgcontent.setAttribute('width', x);
  8343. svgcontent.setAttribute('height', y);
  8344. this.contentW = x;
  8345. this.contentH = y;
  8346. batchCmd.addSubCommand(new ChangeElementCommand(svgcontent, {"width":w, "height":h}));
  8347. svgcontent.setAttribute("viewBox", [0, 0, x/current_zoom, y/current_zoom].join(' '));
  8348. batchCmd.addSubCommand(new ChangeElementCommand(svgcontent, {"viewBox": ["0 0", w, h].join(' ')}));
  8349. addCommandToHistory(batchCmd);
  8350. svgroot.unsuspendRedraw(handle);
  8351. call("changed", [svgcontent]);
  8352. }
  8353. return true;
  8354. };
  8355. // Function: getOffset
  8356. // Returns an object with x, y values indicating the svgcontent element's
  8357. // position in the editor's canvas.
  8358. this.getOffset = function() {
  8359. return $(svgcontent).attr(['x', 'y']);
  8360. }
  8361. // Function: setBBoxZoom
  8362. // Sets the zoom level on the canvas-side based on the given value
  8363. //
  8364. // Parameters:
  8365. // val - Bounding box object to zoom to or string indicating zoom option
  8366. // editor_w - Integer with the editor's workarea box's width
  8367. // editor_h - Integer with the editor's workarea box's height
  8368. this.setBBoxZoom = function(val, editor_w, editor_h) {
  8369. var spacer = .85;
  8370. var bb;
  8371. var calcZoom = function(bb) {
  8372. if(!bb) return false;
  8373. var w_zoom = Math.round((editor_w / bb.width)*100 * spacer)/100;
  8374. var h_zoom = Math.round((editor_h / bb.height)*100 * spacer)/100;
  8375. var zoomlevel = Math.min(w_zoom,h_zoom);
  8376. canvas.setZoom(zoomlevel);
  8377. return {'zoom': zoomlevel, 'bbox': bb};
  8378. }
  8379. if(typeof val == 'object') {
  8380. bb = val;
  8381. if(bb.width == 0 || bb.height == 0) {
  8382. var newzoom = bb.zoom?bb.zoom:current_zoom * bb.factor;
  8383. canvas.setZoom(newzoom);
  8384. return {'zoom': current_zoom, 'bbox': bb};
  8385. }
  8386. return calcZoom(bb);
  8387. }
  8388. switch (val) {
  8389. case 'selection':
  8390. if(!selectedElements[0]) return;
  8391. var sel_elems = $.map(selectedElements, function(n){ if(n) return n; });
  8392. bb = getStrokedBBox(sel_elems);
  8393. break;
  8394. case 'canvas':
  8395. var res = getResolution();
  8396. spacer = .95;
  8397. bb = {width:res.w, height:res.h ,x:0, y:0};
  8398. break;
  8399. case 'content':
  8400. bb = getStrokedBBox();
  8401. break;
  8402. case 'layer':
  8403. bb = getStrokedBBox(getVisibleElements(current_layer));
  8404. break;
  8405. default:
  8406. return;
  8407. }
  8408. return calcZoom(bb);
  8409. }
  8410. // Function: setZoom
  8411. // Sets the zoom to the given level
  8412. //
  8413. // Parameters:
  8414. // zoomlevel - Float indicating the zoom level to change to
  8415. this.setZoom = function(zoomlevel) {
  8416. var res = getResolution();
  8417. svgcontent.setAttribute("viewBox", "0 0 " + res.w/zoomlevel + " " + res.h/zoomlevel);
  8418. current_zoom = zoomlevel;
  8419. $.each(selectedElements, function(i, elem) {
  8420. if(!elem) return;
  8421. selectorManager.requestSelector(elem).resize();
  8422. });
  8423. pathActions.zoomChange();
  8424. runExtensions("zoomChanged", zoomlevel);
  8425. }
  8426. // Function: getMode
  8427. // Returns the current editor mode string
  8428. this.getMode = function() {
  8429. return current_mode;
  8430. };
  8431. // Function: setMode
  8432. // Sets the editor's mode to the given string
  8433. //
  8434. // Parameters:
  8435. // name - String with the new mode to change to
  8436. this.setMode = function(name) {
  8437. pathActions.clear(true);
  8438. textActions.clear();
  8439. cur_properties = (selectedElements[0] && selectedElements[0].nodeName == 'text') ? cur_text : cur_shape;
  8440. current_mode = name;
  8441. };
  8442. // Group: Element Styling
  8443. // Function: getColor
  8444. // Returns the current fill/stroke option
  8445. this.getColor = function(type) {
  8446. return cur_properties[type];
  8447. };
  8448. // Function: setColor
  8449. // Change the current stroke/fill color/gradient value
  8450. //
  8451. // Parameters:
  8452. // type - String indicating fill or stroke
  8453. // val - The value to set the stroke attribute to
  8454. // preventUndo - Boolean indicating whether or not this should be and undoable option
  8455. this.setColor = function(type, val, preventUndo) {
  8456. cur_shape[type] = val;
  8457. cur_properties[type + '_paint'] = {type:"solidColor"};
  8458. var elems = [];
  8459. var i = selectedElements.length;
  8460. while (i--) {
  8461. var elem = selectedElements[i];
  8462. if (elem) {
  8463. if (elem.tagName == "g")
  8464. walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);});
  8465. else {
  8466. if(type == 'fill') {
  8467. if(elem.tagName != "polyline" && elem.tagName != "line") {
  8468. elems.push(elem);
  8469. }
  8470. } else {
  8471. elems.push(elem);
  8472. }
  8473. }
  8474. }
  8475. }
  8476. if (elems.length > 0) {
  8477. if (!preventUndo) {
  8478. changeSelectedAttribute(type, val, elems);
  8479. call("changed", elems);
  8480. } else
  8481. changeSelectedAttributeNoUndo(type, val, elems);
  8482. }
  8483. }
  8484. // Function: findDefs
  8485. // Return the document's <defs> element, create it first if necessary
  8486. var findDefs = function() {
  8487. var defs = svgcontent.getElementsByTagNameNS(svgns, "defs");
  8488. if (defs.length > 0) {
  8489. defs = defs[0];
  8490. }
  8491. else {
  8492. // first child is a comment, so call nextSibling
  8493. defs = svgcontent.insertBefore( svgdoc.createElementNS(svgns, "defs" ), svgcontent.firstChild.nextSibling);
  8494. }
  8495. return defs;
  8496. };
  8497. // Function: setGradient
  8498. // Apply the current gradient to selected element's fill or stroke
  8499. //
  8500. // Parameters
  8501. // type - String indicating "fill" or "stroke" to apply to an element
  8502. var setGradient = this.setGradient = function(type) {
  8503. if(!cur_properties[type + '_paint'] || cur_properties[type + '_paint'].type == "solidColor") return;
  8504. var grad = canvas[type + 'Grad'];
  8505. // find out if there is a duplicate gradient already in the defs
  8506. var duplicate_grad = findDuplicateGradient(grad);
  8507. var defs = findDefs();
  8508. // no duplicate found, so import gradient into defs
  8509. if (!duplicate_grad) {
  8510. var orig_grad = grad;
  8511. grad = defs.appendChild( svgdoc.importNode(grad, true) );
  8512. // get next id and set it on the grad
  8513. grad.id = getNextId();
  8514. }
  8515. else { // use existing gradient
  8516. grad = duplicate_grad;
  8517. }
  8518. canvas.setColor(type, "url(#" + grad.id + ")");
  8519. }
  8520. // Function: findDuplicateGradient
  8521. // Check if exact gradient already exists
  8522. //
  8523. // Parameters:
  8524. // grad - The gradient DOM element to compare to others
  8525. //
  8526. // Returns:
  8527. // The existing gradient if found, null if not
  8528. var findDuplicateGradient = function(grad) {
  8529. var defs = findDefs();
  8530. var existing_grads = $(defs).find("linearGradient, radialGradient");
  8531. var i = existing_grads.length;
  8532. var rad_attrs = ['r','cx','cy','fx','fy'];
  8533. while (i--) {
  8534. var og = existing_grads[i];
  8535. if(grad.tagName == "linearGradient") {
  8536. if (grad.getAttribute('x1') != og.getAttribute('x1') ||
  8537. grad.getAttribute('y1') != og.getAttribute('y1') ||
  8538. grad.getAttribute('x2') != og.getAttribute('x2') ||
  8539. grad.getAttribute('y2') != og.getAttribute('y2'))
  8540. {
  8541. continue;
  8542. }
  8543. } else {
  8544. var grad_attrs = $(grad).attr(rad_attrs);
  8545. var og_attrs = $(og).attr(rad_attrs);
  8546. var diff = false;
  8547. $.each(rad_attrs, function(i, attr) {
  8548. if(grad_attrs[attr] != og_attrs[attr]) diff = true;
  8549. });
  8550. if(diff) continue;
  8551. }
  8552. // else could be a duplicate, iterate through stops
  8553. var stops = grad.getElementsByTagNameNS(svgns, "stop");
  8554. var ostops = og.getElementsByTagNameNS(svgns, "stop");
  8555. if (stops.length != ostops.length) {
  8556. continue;
  8557. }
  8558. var j = stops.length;
  8559. while(j--) {
  8560. var stop = stops[j];
  8561. var ostop = ostops[j];
  8562. if (stop.getAttribute('offset') != ostop.getAttribute('offset') ||
  8563. stop.getAttribute('stop-opacity') != ostop.getAttribute('stop-opacity') ||
  8564. stop.getAttribute('stop-color') != ostop.getAttribute('stop-color'))
  8565. {
  8566. break;
  8567. }
  8568. }
  8569. if (j == -1) {
  8570. return og;
  8571. }
  8572. } // for each gradient in defs
  8573. return null;
  8574. };
  8575. // Function: setPaint
  8576. // Set a color/gradient to a fill/stroke
  8577. //
  8578. // Parameters:
  8579. // type - String with "fill" or "stroke"
  8580. // paint - The jGraduate paint object to apply
  8581. this.setPaint = function(type, paint) {
  8582. // make a copy
  8583. var p = new $.jGraduate.Paint(paint);
  8584. this.setPaintOpacity(type, p.alpha/100, true);
  8585. // now set the current paint object
  8586. cur_properties[type + '_paint'] = p;
  8587. switch ( p.type ) {
  8588. case "solidColor":
  8589. this.setColor(type, p.solidColor != "none" ? "#"+p.solidColor : "none");;
  8590. break;
  8591. case "linearGradient":
  8592. case "radialGradient":
  8593. canvas[type + 'Grad'] = p[p.type];
  8594. setGradient(type);
  8595. break;
  8596. default:
  8597. // console.log("none!");
  8598. }
  8599. };
  8600. // this.setStrokePaint = function(p) {
  8601. // // make a copy
  8602. // var p = new $.jGraduate.Paint(p);
  8603. // this.setStrokeOpacity(p.alpha/100);
  8604. //
  8605. // // now set the current paint object
  8606. // cur_properties.stroke_paint = p;
  8607. // switch ( p.type ) {
  8608. // case "solidColor":
  8609. // this.setColor('stroke', p.solidColor != "none" ? "#"+p.solidColor : "none");;
  8610. // break;
  8611. // case "linearGradient"
  8612. // case "radialGradient"
  8613. // canvas.strokeGrad = p[p.type];
  8614. // setGradient(type);
  8615. // default:
  8616. // // console.log("none!");
  8617. // }
  8618. // };
  8619. //
  8620. // this.setFillPaint = function(p, addGrad) {
  8621. // // make a copy
  8622. // var p = new $.jGraduate.Paint(p);
  8623. // this.setFillOpacity(p.alpha/100, true);
  8624. //
  8625. // // now set the current paint object
  8626. // cur_properties.fill_paint = p;
  8627. // if (p.type == "solidColor") {
  8628. // this.setColor('fill', p.solidColor != "none" ? "#"+p.solidColor : "none");
  8629. // }
  8630. // else if(p.type == "linearGradient") {
  8631. // canvas.fillGrad = p.linearGradient;
  8632. // if(addGrad) setGradient();
  8633. // }
  8634. // else if(p.type == "radialGradient") {
  8635. // canvas.fillGrad = p.radialGradient;
  8636. // if(addGrad) setGradient();
  8637. // }
  8638. // else {
  8639. // // console.log("none!");
  8640. // }
  8641. // };
  8642. // Function: getStrokeWidth
  8643. // Returns the current stroke-width value
  8644. this.getStrokeWidth = function() {
  8645. return cur_properties.stroke_width;
  8646. };
  8647. // Function: setStrokeWidth
  8648. // Sets the stroke width for the current selected elements
  8649. // When attempting to set a line's width to 0, this changes it to 1 instead
  8650. //
  8651. // Parameters:
  8652. // val - A Float indicating the new stroke width value
  8653. this.setStrokeWidth = function(val) {
  8654. if(val == 0 && ['line', 'path'].indexOf(current_mode) >= 0) {
  8655. canvas.setStrokeWidth(1);
  8656. return;
  8657. }
  8658. cur_properties.stroke_width = val;
  8659. var elems = [];
  8660. var i = selectedElements.length;
  8661. while (i--) {
  8662. var elem = selectedElements[i];
  8663. if (elem) {
  8664. if (elem.tagName == "g")
  8665. walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);});
  8666. else
  8667. elems.push(elem);
  8668. }
  8669. }
  8670. if (elems.length > 0) {
  8671. changeSelectedAttribute("stroke-width", val, elems);
  8672. call("changed", selectedElements);
  8673. }
  8674. };
  8675. // Function: setStrokeAttr
  8676. // Set the given stroke-related attribute the given value for selected elements
  8677. //
  8678. // Parameters:
  8679. // attr - String with the attribute name
  8680. // val - String or number with the attribute value
  8681. this.setStrokeAttr = function(attr, val) {
  8682. cur_shape[attr.replace('-','_')] = val;
  8683. var elems = [];
  8684. var i = selectedElements.length;
  8685. while (i--) {
  8686. var elem = selectedElements[i];
  8687. if (elem) {
  8688. if (elem.tagName == "g")
  8689. walkTree(elem, function(e){if(e.nodeName!="g") elems.push(e);});
  8690. else
  8691. elems.push(elem);
  8692. }
  8693. }
  8694. if (elems.length > 0) {
  8695. changeSelectedAttribute(attr, val, elems);
  8696. call("changed", selectedElements);
  8697. }
  8698. };
  8699. // Function: getStyle
  8700. // Returns current style options
  8701. this.getStyle = function() {
  8702. return cur_shape;
  8703. }
  8704. // Function: getOpacity
  8705. // Returns the current opacity
  8706. this.getOpacity = function() {
  8707. return cur_shape.opacity;
  8708. };
  8709. // Function: setOpacity
  8710. // Sets the given opacity to the current selected elements
  8711. this.setOpacity = function(val) {
  8712. cur_shape.opacity = val;
  8713. changeSelectedAttribute("opacity", val);
  8714. };
  8715. // Function: getOpacity
  8716. // Returns the current fill opacity
  8717. this.getFillOpacity = function() {
  8718. return cur_shape.fill_opacity;
  8719. };
  8720. // Function: getStrokeOpacity
  8721. // Returns the current stroke opacity
  8722. this.getStrokeOpacity = function() {
  8723. return cur_shape.stroke_opacity;
  8724. };
  8725. // Function: setPaintOpacity
  8726. // Sets the current fill/stroke opacity
  8727. //
  8728. // Parameters:
  8729. // type - String with "fill" or "stroke"
  8730. // val - Float with the new opacity value
  8731. // preventUndo - Boolean indicating whether or not this should be an undoable action
  8732. this.setPaintOpacity = function(type, val, preventUndo) {
  8733. cur_shape[type + '_opacity'] = val;
  8734. if (!preventUndo)
  8735. changeSelectedAttribute(type + "-opacity", val);
  8736. else
  8737. changeSelectedAttributeNoUndo(type + "-opacity", val);
  8738. };
  8739. // Function: getBlur
  8740. // Gets the stdDeviation blur value of the given element
  8741. //
  8742. // Parameters:
  8743. // elem - The element to check the blur value for
  8744. this.getBlur = function(elem) {
  8745. var val = 0;
  8746. // var elem = selectedElements[0];
  8747. if(elem) {
  8748. var filter_url = elem.getAttribute('filter');
  8749. if(filter_url) {
  8750. var blur = getElem(elem.id + '_blur');
  8751. if(blur) {
  8752. val = blur.firstChild.getAttribute('stdDeviation');
  8753. }
  8754. }
  8755. }
  8756. return val;
  8757. };
  8758. (function() {
  8759. var cur_command = null;
  8760. var filter = null;
  8761. var filterHidden = false;
  8762. // Function: setBlurNoUndo
  8763. // Sets the stdDeviation blur value on the selected element without being undoable
  8764. //
  8765. // Parameters:
  8766. // val - The new stdDeviation value
  8767. canvas.setBlurNoUndo = function(val) {
  8768. if(!filter) {
  8769. canvas.setBlur(val);
  8770. return;
  8771. }
  8772. if(val === 0) {
  8773. // Don't change the StdDev, as that will hide the element.
  8774. // Instead, just remove the value for "filter"
  8775. changeSelectedAttributeNoUndo("filter", "");
  8776. filterHidden = true;
  8777. } else {
  8778. if(filterHidden) {
  8779. changeSelectedAttributeNoUndo("filter", 'url(#' + selectedElements[0].id + '_blur)');
  8780. }
  8781. changeSelectedAttributeNoUndo("stdDeviation", val, [filter.firstChild]);
  8782. canvas.setBlurOffsets(filter, val);
  8783. }
  8784. }
  8785. function finishChange() {
  8786. var bCmd = canvas.finishUndoableChange();
  8787. cur_command.addSubCommand(bCmd);
  8788. addCommandToHistory(cur_command);
  8789. cur_command = null;
  8790. filter = null;
  8791. }
  8792. // Function: setBlurOffsets
  8793. // Sets the x, y, with, height values of the filter element in order to
  8794. // make the blur not be clipped. Removes them if not neeeded
  8795. //
  8796. // Parameters:
  8797. // filter - The filter DOM element to update
  8798. // stdDev - The standard deviation value on which to base the offset size
  8799. canvas.setBlurOffsets = function(filter, stdDev) {
  8800. if(stdDev > 3) {
  8801. // TODO: Create algorithm here where size is based on expected blur
  8802. assignAttributes(filter, {
  8803. x: '-50%',
  8804. y: '-50%',
  8805. width: '200%',
  8806. height: '200%',
  8807. }, 100);
  8808. } else {
  8809. filter.removeAttribute('x');
  8810. filter.removeAttribute('y');
  8811. filter.removeAttribute('width');
  8812. filter.removeAttribute('height');
  8813. }
  8814. }
  8815. // Function: setBlur
  8816. // Adds/updates the blur filter to the selected element
  8817. //
  8818. // Parameters:
  8819. // val - Float with the new stdDeviation blur value
  8820. // complete - Boolean indicating whether or not the action should be completed (to add to the undo manager)
  8821. canvas.setBlur = function(val, complete) {
  8822. if(cur_command) {
  8823. finishChange();
  8824. return;
  8825. }
  8826. // Looks for associated blur, creates one if not found
  8827. var elem = selectedElements[0];
  8828. var elem_id = elem.id;
  8829. filter = getElem(elem_id + '_blur');
  8830. val -= 0;
  8831. var batchCmd = new BatchCommand();
  8832. // Blur found!
  8833. if(filter) {
  8834. if(val === 0) {
  8835. filter = null;
  8836. }
  8837. } else {
  8838. // Not found, so create
  8839. var newblur = addSvgElementFromJson({ "element": "feGaussianBlur",
  8840. "attr": {
  8841. "in": 'SourceGraphic',
  8842. "stdDeviation": val
  8843. }
  8844. });
  8845. filter = addSvgElementFromJson({ "element": "filter",
  8846. "attr": {
  8847. "id": elem_id + '_blur'
  8848. }
  8849. });
  8850. filter.appendChild(newblur);
  8851. findDefs().appendChild(filter);
  8852. batchCmd.addSubCommand(new InsertElementCommand(filter));
  8853. }
  8854. var changes = {filter: elem.getAttribute('filter')};
  8855. if(val === 0) {
  8856. elem.removeAttribute("filter");
  8857. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  8858. return;
  8859. } else {
  8860. changeSelectedAttribute("filter", 'url(#' + elem_id + '_blur)');
  8861. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  8862. canvas.setBlurOffsets(filter, val);
  8863. }
  8864. cur_command = batchCmd;
  8865. canvas.beginUndoableChange("stdDeviation", [filter?filter.firstChild:null]);
  8866. if(complete) {
  8867. canvas.setBlurNoUndo(val);
  8868. finishChange();
  8869. }
  8870. };
  8871. }());
  8872. // Function: getBold
  8873. // Check whether selected element is bold or not
  8874. //
  8875. // Returns:
  8876. // Boolean indicating whether or not element is bold
  8877. this.getBold = function() {
  8878. // should only have one element selected
  8879. var selected = selectedElements[0];
  8880. if (selected != null && selected.tagName == "text" &&
  8881. selectedElements[1] == null)
  8882. {
  8883. return (selected.getAttribute("font-weight") == "bold");
  8884. }
  8885. return false;
  8886. };
  8887. // Function: setBold
  8888. // Make the selected element bold or normal
  8889. //
  8890. // Parameters:
  8891. // b - Boolean indicating bold (true) or normal (false)
  8892. this.setBold = function(b) {
  8893. var selected = selectedElements[0];
  8894. if (selected != null && selected.tagName == "text" &&
  8895. selectedElements[1] == null)
  8896. {
  8897. changeSelectedAttribute("font-weight", b ? "bold" : "normal");
  8898. }
  8899. if(!selectedElements[0].textContent) {
  8900. textActions.setCursor();
  8901. }
  8902. };
  8903. // Function: getItalic
  8904. // Check whether selected element is italic or not
  8905. //
  8906. // Returns:
  8907. // Boolean indicating whether or not element is italic
  8908. this.getItalic = function() {
  8909. var selected = selectedElements[0];
  8910. if (selected != null && selected.tagName == "text" &&
  8911. selectedElements[1] == null)
  8912. {
  8913. return (selected.getAttribute("font-style") == "italic");
  8914. }
  8915. return false;
  8916. };
  8917. // Function: setItalic
  8918. // Make the selected element italic or normal
  8919. //
  8920. // Parameters:
  8921. // b - Boolean indicating italic (true) or normal (false)
  8922. this.setItalic = function(i) {
  8923. var selected = selectedElements[0];
  8924. if (selected != null && selected.tagName == "text" &&
  8925. selectedElements[1] == null)
  8926. {
  8927. changeSelectedAttribute("font-style", i ? "italic" : "normal");
  8928. }
  8929. if(!selectedElements[0].textContent) {
  8930. textActions.setCursor();
  8931. }
  8932. };
  8933. // Function: getFontFamily
  8934. // Returns the current font family
  8935. this.getFontFamily = function() {
  8936. return cur_text.font_family;
  8937. };
  8938. // Function: setFontFamily
  8939. // Set the new font family
  8940. //
  8941. // Parameters:
  8942. // val - String with the new font family
  8943. this.setFontFamily = function(val) {
  8944. cur_text.font_family = val;
  8945. changeSelectedAttribute("font-family", val);
  8946. if(selectedElements[0] && !selectedElements[0].textContent) {
  8947. textActions.setCursor();
  8948. }
  8949. };
  8950. // Function: getFontSize
  8951. // Returns the current font size
  8952. this.getFontSize = function() {
  8953. return cur_text.font_size;
  8954. };
  8955. // Function: setFontSize
  8956. // Applies the given font size to the selected element
  8957. //
  8958. // Parameters:
  8959. // val - Float with the new font size
  8960. this.setFontSize = function(val) {
  8961. cur_text.font_size = val;
  8962. changeSelectedAttribute("font-size", val);
  8963. if(!selectedElements[0].textContent) {
  8964. textActions.setCursor();
  8965. }
  8966. };
  8967. // Function: getText
  8968. // Returns the current text (textContent) of the selected element
  8969. this.getText = function() {
  8970. var selected = selectedElements[0];
  8971. if (selected == null) { return ""; }
  8972. return selected.textContent;
  8973. };
  8974. // Function: setTextContent
  8975. // Updates the text element with the given string
  8976. //
  8977. // Parameters:
  8978. // val - String with the new text
  8979. this.setTextContent = function(val) {
  8980. changeSelectedAttribute("#text", val);
  8981. textActions.init(val);
  8982. textActions.setCursor();
  8983. };
  8984. // Function: setImageURL
  8985. // Sets the new image URL for the selected image element. Updates its size if
  8986. // a new URL is given
  8987. //
  8988. // Parameters:
  8989. // val - String with the image URL/path
  8990. this.setImageURL = function(val) {
  8991. var elem = selectedElements[0];
  8992. if(!elem) return;
  8993. var attrs = $(elem).attr(['width', 'height']);
  8994. var setsize = (!attrs.width || !attrs.height);
  8995. var cur_href = getHref(elem);
  8996. // Do nothing if no URL change or size change
  8997. if(cur_href !== val) {
  8998. setsize = true;
  8999. } else if(!setsize) return;
  9000. var batchCmd = new BatchCommand("Change Image URL");
  9001. setHref(elem, val);
  9002. batchCmd.addSubCommand(new ChangeElementCommand(elem, {
  9003. "#href": cur_href
  9004. }));
  9005. if(setsize) {
  9006. $(new Image()).load(function() {
  9007. var changes = $(elem).attr(['width', 'height']);
  9008. $(elem).attr({
  9009. width: this.width,
  9010. height: this.height
  9011. });
  9012. selectorManager.requestSelector(elem).resize();
  9013. batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
  9014. addCommandToHistory(batchCmd);
  9015. call("changed", [elem]);
  9016. }).attr('src',val);
  9017. } else {
  9018. addCommandToHistory(batchCmd);
  9019. }
  9020. };
  9021. // Function: setRectRadius
  9022. // Sets the rx & ry values to the selected rect element to change its corner radius
  9023. //
  9024. // Parameters:
  9025. // val - The new radius
  9026. this.setRectRadius = function(val) {
  9027. var selected = selectedElements[0];
  9028. if (selected != null && selected.tagName == "rect") {
  9029. var r = selected.getAttribute("rx");
  9030. if (r != val) {
  9031. selected.setAttribute("rx", val);
  9032. selected.setAttribute("ry", val);
  9033. addCommandToHistory(new ChangeElementCommand(selected, {"rx":r, "ry":r}, "Radius"));
  9034. call("changed", [selected]);
  9035. }
  9036. }
  9037. };
  9038. // Group: Element manipulation
  9039. // Function: setSegType
  9040. // Sets the new segment type to the selected segment(s).
  9041. //
  9042. // Parameters:
  9043. // new_type - Integer with the new segment type
  9044. // See http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg for list
  9045. this.setSegType = function(new_type) {
  9046. pathActions.setSegType(new_type);
  9047. }
  9048. // Function: convertToPath
  9049. // Convert selected element to a path, or get the BBox of an element-as-path
  9050. //
  9051. // Parameters:
  9052. // elem - The DOM element to be converted
  9053. // getBBox - Boolean on whether or not to only return the path's BBox
  9054. //
  9055. // Returns:
  9056. // If the getBBox flag is true, the resulting path's bounding box object.
  9057. // Otherwise the resulting path element is returned.
  9058. this.convertToPath = function(elem, getBBox) {
  9059. if(elem == null) {
  9060. var elems = selectedElements;
  9061. $.each(selectedElements, function(i, elem) {
  9062. if(elem) canvas.convertToPath(elem);
  9063. });
  9064. return;
  9065. }
  9066. if(!getBBox) {
  9067. var batchCmd = new BatchCommand("Convert element to Path");
  9068. }
  9069. var attrs = getBBox?{}:{
  9070. "fill": cur_shape.fill,
  9071. "fill-opacity": cur_shape.fill_opacity,
  9072. "stroke": cur_shape.stroke,
  9073. "stroke-width": cur_shape.stroke_width,
  9074. "stroke-dasharray": cur_shape.stroke_dasharray,
  9075. "stroke-linejoin": cur_shape.stroke_linejoin,
  9076. "stroke-linecap": cur_shape.stroke_linecap,
  9077. "stroke-opacity": cur_shape.stroke_opacity,
  9078. "opacity": cur_shape.opacity,
  9079. "visibility":"hidden"
  9080. };
  9081. // any attribute on the element not covered by the above
  9082. // TODO: make this list global so that we can properly maintain it
  9083. // TODO: what about @transform, @clip-rule, @fill-rule, etc?
  9084. $.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function() {
  9085. if (elem.getAttribute(this)) {
  9086. attrs[this] = elem.getAttribute(this);
  9087. }
  9088. });
  9089. var path = addSvgElementFromJson({
  9090. "element": "path",
  9091. "attr": attrs
  9092. });
  9093. var eltrans = elem.getAttribute("transform");
  9094. if(eltrans) {
  9095. path.setAttribute("transform",eltrans);
  9096. }
  9097. var id = elem.id;
  9098. var parent = elem.parentNode;
  9099. if(elem.nextSibling) {
  9100. parent.insertBefore(path, elem);
  9101. } else {
  9102. parent.appendChild(path);
  9103. }
  9104. var d = '';
  9105. var joinSegs = function(segs) {
  9106. $.each(segs, function(j, seg) {
  9107. var l = seg[0], pts = seg[1];
  9108. d += l;
  9109. for(var i=0; i < pts.length; i+=2) {
  9110. d += (pts[i] +','+pts[i+1]) + ' ';
  9111. }
  9112. });
  9113. }
  9114. // Possibly the cubed root of 6, but 1.81 works best
  9115. var num = 1.81;
  9116. switch (elem.tagName) {
  9117. case 'ellipse':
  9118. case 'circle':
  9119. var a = $(elem).attr(['rx', 'ry', 'cx', 'cy']);
  9120. var cx = a.cx, cy = a.cy, rx = a.rx, ry = a.ry;
  9121. if(elem.tagName == 'circle') {
  9122. rx = ry = $(elem).attr('r');
  9123. }
  9124. joinSegs([
  9125. ['M',[(cx-rx),(cy)]],
  9126. ['C',[(cx-rx),(cy-ry/num), (cx-rx/num),(cy-ry), (cx),(cy-ry)]],
  9127. ['C',[(cx+rx/num),(cy-ry), (cx+rx),(cy-ry/num), (cx+rx),(cy)]],
  9128. ['C',[(cx+rx),(cy+ry/num), (cx+rx/num),(cy+ry), (cx),(cy+ry)]],
  9129. ['C',[(cx-rx/num),(cy+ry), (cx-rx),(cy+ry/num), (cx-rx),(cy)]],
  9130. ['Z',[]]
  9131. ]);
  9132. break;
  9133. case 'path':
  9134. d = elem.getAttribute('d');
  9135. break;
  9136. case 'line':
  9137. var a = $(elem).attr(["x1", "y1", "x2", "y2"]);
  9138. d = "M"+a.x1+","+a.y1+"L"+a.x2+","+a.y2;
  9139. break;
  9140. case 'polyline':
  9141. case 'polygon':
  9142. d = "M" + elem.getAttribute('points');
  9143. break;
  9144. case 'rect':
  9145. var r = $(elem).attr(['rx', 'ry']);
  9146. var rx = r.rx, ry = r.ry;
  9147. var b = elem.getBBox();
  9148. var x = b.x, y = b.y, w = b.width, h = b.height;
  9149. var num = 4-num; // Why? Because!
  9150. if(!rx && !ry) {
  9151. // Regular rect
  9152. joinSegs([
  9153. ['M',[x, y]],
  9154. ['L',[x+w, y]],
  9155. ['L',[x+w, y+h]],
  9156. ['L',[x, y+h]],
  9157. ['L',[x, y]],
  9158. ['Z',[]]
  9159. ]);
  9160. } else {
  9161. joinSegs([
  9162. ['M',[x, y+ry]],
  9163. ['C',[x,y+ry/num, x+rx/num,y, x+rx,y]],
  9164. ['L',[x+w-rx, y]],
  9165. ['C',[x+w-rx/num,y, x+w,y+ry/num, x+w,y+ry]],
  9166. ['L',[x+w, y+h-ry]],
  9167. ['C',[x+w, y+h-ry/num, x+w-rx/num,y+h, x+w-rx,y+h]],
  9168. ['L',[x+rx, y+h]],
  9169. ['C',[x+rx/num, y+h, x,y+h-ry/num, x,y+h-ry]],
  9170. ['L',[x, y+ry]],
  9171. ['Z',[]]
  9172. ]);
  9173. }
  9174. break;
  9175. default:
  9176. path.parentNode.removeChild(path);
  9177. break;
  9178. }
  9179. if(d) {
  9180. path.setAttribute('d',d);
  9181. }
  9182. if(!getBBox) {
  9183. // Replace the current element with the converted one
  9184. // Reorient if it has a matrix
  9185. if(eltrans) {
  9186. var tlist = getTransformList(path);
  9187. if(hasMatrixTransform(tlist)) {
  9188. pathActions.resetOrientation(path);
  9189. }
  9190. }
  9191. batchCmd.addSubCommand(new RemoveElementCommand(elem, parent));
  9192. batchCmd.addSubCommand(new InsertElementCommand(path));
  9193. clearSelection();
  9194. elem.parentNode.removeChild(elem)
  9195. path.setAttribute('id', id);
  9196. path.removeAttribute("visibility");
  9197. addToSelection([path], true);
  9198. addCommandToHistory(batchCmd);
  9199. } else {
  9200. // Get the correct BBox of the new path, then discard it
  9201. pathActions.resetOrientation(path);
  9202. var bb = false;
  9203. try {
  9204. bb = path.getBBox();
  9205. } catch(e) {
  9206. // Firefox fails
  9207. }
  9208. path.parentNode.removeChild(path);
  9209. return bb;
  9210. }
  9211. }
  9212. // Function: changeSelectedAttributeNoUndo
  9213. // This function makes the changes to the elements. It does not add the change
  9214. // to the history stack.
  9215. //
  9216. // Parameters:
  9217. // attr - String with the attribute name
  9218. // newValue - String or number with the new attribute value
  9219. // elems - The DOM elements to apply the change to
  9220. var changeSelectedAttributeNoUndo = function(attr, newValue, elems) {
  9221. var handle = svgroot.suspendRedraw(1000);
  9222. if(current_mode == 'pathedit') {
  9223. // Editing node
  9224. pathActions.moveNode(attr, newValue);
  9225. }
  9226. var elems = elems || selectedElements;
  9227. var i = elems.length;
  9228. while (i--) {
  9229. var elem = elems[i];
  9230. if (elem == null) continue;
  9231. // Go into "select" mode for text changes
  9232. if(current_mode === "textedit" && attr !== "#text" && elem.textContent.length) {
  9233. textActions.toSelectMode(elem);
  9234. }
  9235. // Set x,y vals on elements that don't have them
  9236. if((attr == 'x' || attr == 'y') && ['g', 'polyline', 'path'].indexOf(elem.tagName) >= 0) {
  9237. var bbox = getStrokedBBox([elem]);
  9238. var diff_x = attr == 'x' ? newValue - bbox.x : 0;
  9239. var diff_y = attr == 'y' ? newValue - bbox.y : 0;
  9240. canvas.moveSelectedElements(diff_x*current_zoom, diff_y*current_zoom, true);
  9241. continue;
  9242. }
  9243. // only allow the transform/opacity attribute to change on <g> elements, slightly hacky
  9244. if (elem.tagName == "g" && ['transform', 'opacity', 'filter'].indexOf(attr) >= 0);
  9245. var oldval = attr == "#text" ? elem.textContent : elem.getAttribute(attr);
  9246. if (oldval == null) oldval = "";
  9247. if (oldval != String(newValue)) {
  9248. if (attr == "#text") {
  9249. var old_w = getBBox(elem).width;
  9250. elem.textContent = newValue;
  9251. elem = ffClone(elem);
  9252. // Hoped to solve the issue of moving text with text-anchor="start",
  9253. // but this doesn't actually fix it. Hopefully on the right track, though. -Fyrd
  9254. // var box=getBBox(elem), left=box.x, top=box.y, width=box.width,
  9255. // height=box.height, dx = width - old_w, dy=0;
  9256. // var angle = getRotationAngle(elem, true);
  9257. // if (angle) {
  9258. // var r = Math.sqrt( dx*dx + dy*dy );
  9259. // var theta = Math.atan2(dy,dx) - angle;
  9260. // dx = r * Math.cos(theta);
  9261. // dy = r * Math.sin(theta);
  9262. //
  9263. // elem.setAttribute('x', elem.getAttribute('x')-dx);
  9264. // elem.setAttribute('y', elem.getAttribute('y')-dy);
  9265. // }
  9266. } else if (attr == "#href") {
  9267. setHref(elem, newValue);
  9268. }
  9269. else elem.setAttribute(attr, newValue);
  9270. if (i==0)
  9271. selectedBBoxes[i] = getBBox(elem);
  9272. // Use the Firefox ffClone hack for text elements with gradients or
  9273. // where other text attributes are changed.
  9274. if(elem.nodeName == 'text') {
  9275. if((newValue+'').indexOf('url') == 0 || ['font-size','font-family','x','y'].indexOf(attr) >= 0 && elem.textContent) {
  9276. elem = ffClone(elem);
  9277. }
  9278. }
  9279. // Timeout needed for Opera & Firefox
  9280. // codedread: it is now possible for this function to be called with elements
  9281. // that are not in the selectedElements array, we need to only request a
  9282. // selector if the element is in that array
  9283. if (selectedElements.indexOf(elem) >= 0) {
  9284. setTimeout(function() {
  9285. // Due to element replacement, this element may no longer
  9286. // be part of the DOM
  9287. if(!elem.parentNode) return;
  9288. selectorManager.requestSelector(elem).resize();
  9289. },0);
  9290. }
  9291. // if this element was rotated, and we changed the position of this element
  9292. // we need to update the rotational transform attribute
  9293. var angle = getRotationAngle(elem);
  9294. if (angle != 0 && attr != "transform") {
  9295. var tlist = getTransformList(elem);
  9296. var n = tlist.numberOfItems;
  9297. while (n--) {
  9298. var xform = tlist.getItem(n);
  9299. if (xform.type == 4) {
  9300. // remove old rotate
  9301. tlist.removeItem(n);
  9302. var box = getBBox(elem);
  9303. var center = transformPoint(box.x+box.width/2, box.y+box.height/2, transformListToTransform(tlist).matrix);
  9304. var cx = center.x,
  9305. cy = center.y;
  9306. var newrot = svgroot.createSVGTransform();
  9307. newrot.setRotate(angle, cx, cy);
  9308. tlist.insertItemBefore(newrot, n);
  9309. break;
  9310. }
  9311. }
  9312. }
  9313. } // if oldValue != newValue
  9314. } // for each elem
  9315. svgroot.unsuspendRedraw(handle);
  9316. };
  9317. // Function: changeSelectedAttribute
  9318. // Change the given/selected element and add the original value to the history stack
  9319. // If you want to change all selectedElements, ignore the elems argument.
  9320. // If you want to change only a subset of selectedElements, then send the
  9321. // subset to this function in the elems argument.
  9322. //
  9323. // Parameters:
  9324. // attr - String with the attribute name
  9325. // newValue - String or number with the new attribute value
  9326. // elems - The DOM elements to apply the change to
  9327. var changeSelectedAttribute = this.changeSelectedAttribute = function(attr, val, elems) {
  9328. var elems = elems || selectedElements;
  9329. canvas.beginUndoableChange(attr, elems);
  9330. var i = elems.length;
  9331. changeSelectedAttributeNoUndo(attr, val, elems);
  9332. var batchCmd = canvas.finishUndoableChange();
  9333. if (!batchCmd.isEmpty()) {
  9334. addCommandToHistory(batchCmd);
  9335. }
  9336. };
  9337. // Function: deleteSelectedElements
  9338. // Removes all selected elements from the DOM and adds the change to the
  9339. // history stack
  9340. this.deleteSelectedElements = function() {
  9341. var batchCmd = new BatchCommand("Delete Elements");
  9342. var len = selectedElements.length;
  9343. var selectedCopy = []; //selectedElements is being deleted
  9344. for (var i = 0; i < len; ++i) {
  9345. var selected = selectedElements[i];
  9346. if (selected == null) break;
  9347. var parent = selected.parentNode;
  9348. var t = selected;
  9349. // this will unselect the element and remove the selectedOutline
  9350. selectorManager.releaseSelector(t);
  9351. var elem = parent.removeChild(t);
  9352. selectedCopy.push(selected) //for the copy
  9353. selectedElements[i] = null;
  9354. batchCmd.addSubCommand(new RemoveElementCommand(elem, parent));
  9355. }
  9356. if (!batchCmd.isEmpty()) addCommandToHistory(batchCmd);
  9357. call("changed", selectedCopy);
  9358. clearSelection();
  9359. };
  9360. // Function: cutSelectedElements
  9361. // Removes all selected elements from the DOM and adds the change to the
  9362. // history stack. Remembers removed elements on the clipboard
  9363. // TODO: Combine similar code with deleteSelectedElements
  9364. this.cutSelectedElements = function() {
  9365. var batchCmd = new BatchCommand("Cut Elements");
  9366. var len = selectedElements.length;
  9367. var selectedCopy = []; //selectedElements is being deleted
  9368. for (var i = 0; i < len; ++i) {
  9369. var selected = selectedElements[i];
  9370. if (selected == null) break;
  9371. var parent = selected.parentNode;
  9372. var t = selected;
  9373. // this will unselect the element and remove the selectedOutline
  9374. selectorManager.releaseSelector(t);
  9375. var elem = parent.removeChild(t);
  9376. selectedCopy.push(selected) //for the copy
  9377. selectedElements[i] = null;
  9378. batchCmd.addSubCommand(new RemoveElementCommand(elem, parent));
  9379. }
  9380. if (!batchCmd.isEmpty()) addCommandToHistory(batchCmd);
  9381. call("changed", selectedCopy);
  9382. clearSelection();
  9383. canvas.clipBoard = selectedCopy;
  9384. };
  9385. // Function: copySelectedElements
  9386. // Remembers the current selected elements on the clipboard
  9387. this.copySelectedElements = function() {
  9388. canvas.clipBoard = $.merge([], selectedElements);
  9389. };
  9390. this.pasteElements = function(type) {
  9391. var cb = canvas.clipBoard;
  9392. var len = cb.length;
  9393. if(!len) return;
  9394. var pasted = [];
  9395. var batchCmd = new BatchCommand('Paste elements');
  9396. // Move elements to lastClickPoint
  9397. while (len--) {
  9398. var elem = cb[len];
  9399. if(!elem) continue;
  9400. var copy = copyElem(elem);
  9401. // See if elem with elem ID is in the DOM already
  9402. if(!getElem(elem.id)) copy.id = elem.id;
  9403. pasted.push(copy);
  9404. (current_group || current_layer).appendChild(copy);
  9405. batchCmd.addSubCommand(new InsertElementCommand(copy));
  9406. }
  9407. selectOnly(pasted);
  9408. if(type !== 'in_place') {
  9409. var bbox = getStrokedBBox(pasted);
  9410. var cx = lastClickPoint.x - (bbox.x + bbox.width/2),
  9411. cy = lastClickPoint.y - (bbox.y + bbox.height/2),
  9412. dx = [],
  9413. dy = [];
  9414. $.each(pasted, function(i, item) {
  9415. dx.push(cx);
  9416. dy.push(cy);
  9417. });
  9418. var cmd = canvas.moveSelectedElements(dx, dy, false);
  9419. batchCmd.addSubCommand(cmd);
  9420. }
  9421. addCommandToHistory(batchCmd);
  9422. call("changed", pasted);
  9423. }
  9424. // Function: groupSelectedElements
  9425. // Wraps all the selected elements in a group (g) element
  9426. this.groupSelectedElements = function() {
  9427. var batchCmd = new BatchCommand("Group Elements");
  9428. // create and insert the group element
  9429. var g = addSvgElementFromJson({
  9430. "element": "g",
  9431. "attr": {
  9432. "id": getNextId()
  9433. }
  9434. });
  9435. batchCmd.addSubCommand(new InsertElementCommand(g));
  9436. // now move all children into the group
  9437. var i = selectedElements.length;
  9438. while (i--) {
  9439. var elem = selectedElements[i];
  9440. if (elem == null) continue;
  9441. var oldNextSibling = elem.nextSibling;
  9442. var oldParent = elem.parentNode;
  9443. g.appendChild(elem);
  9444. batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldParent));
  9445. }
  9446. if (!batchCmd.isEmpty()) addCommandToHistory(batchCmd);
  9447. // update selection
  9448. selectOnly([g], true);
  9449. };
  9450. // Function: ungroupSelectedElement
  9451. // Unwraps all the elements in a selected group (g) element. This requires
  9452. // significant recalculations to apply group's transforms, etc to its children
  9453. this.ungroupSelectedElement = function() {
  9454. var g = selectedElements[0];
  9455. if($(g).data('gsvg') || $(g).data('symbol')) {
  9456. // Is svg, so actually convert to group
  9457. convertToGroup(g);
  9458. return;
  9459. } else if(g.tagName === 'use') {
  9460. // Somehow doesn't have data set, so retrieve
  9461. var symbol = getElem(getHref(g).substr(1));
  9462. $(g).data('symbol', symbol);
  9463. convertToGroup(g);
  9464. return;
  9465. }
  9466. if (g.tagName == "g") {
  9467. var batchCmd = new BatchCommand("Ungroup Elements");
  9468. var parent = g.parentNode;
  9469. var anchor = g.nextSibling;
  9470. var children = new Array(g.childNodes.length);
  9471. var xform = g.getAttribute("transform");
  9472. // get consolidated matrix
  9473. var glist = getTransformList(g);
  9474. var m = transformListToTransform(glist).matrix;
  9475. // TODO: get all fill/stroke properties from the group that we are about to destroy
  9476. // "fill", "fill-opacity", "fill-rule", "stroke", "stroke-dasharray", "stroke-dashoffset",
  9477. // "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity",
  9478. // "stroke-width"
  9479. // and then for each child, if they do not have the attribute (or the value is 'inherit')
  9480. // then set the child's attribute
  9481. var i = 0;
  9482. var gangle = getRotationAngle(g);
  9483. var gattrs = $(g).attr(['filter', 'opacity']);
  9484. var gfilter, gblur;
  9485. while (g.firstChild) {
  9486. var elem = g.firstChild;
  9487. var oldNextSibling = elem.nextSibling;
  9488. var oldParent = elem.parentNode;
  9489. // Remove child title elements
  9490. if(elem.tagName == 'title') {
  9491. batchCmd.addSubCommand(new RemoveElementCommand(elem, oldParent));
  9492. oldParent.removeChild(elem);
  9493. continue;
  9494. }
  9495. children[i++] = elem = parent.insertBefore(elem, anchor);
  9496. batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldParent));
  9497. if(gattrs.opacity !== null && gattrs.opacity !== 1) {
  9498. var c_opac = elem.getAttribute('opacity') || 1;
  9499. var new_opac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100)/100;
  9500. changeSelectedAttribute('opacity', new_opac, [elem]);
  9501. }
  9502. if(gattrs.filter) {
  9503. var cblur = this.getBlur(elem);
  9504. var orig_cblur = cblur;
  9505. if(!gblur) gblur = this.getBlur(g);
  9506. if(cblur) {
  9507. // Is this formula correct?
  9508. cblur = (gblur-0) + (cblur-0);
  9509. } else if(cblur === 0) {
  9510. cblur = gblur;
  9511. }
  9512. // If child has no current filter, get group's filter or clone it.
  9513. if(!orig_cblur) {
  9514. // Set group's filter to use first child's ID
  9515. if(!gfilter) {
  9516. gfilter = getElem(getUrlFromAttr(gattrs.filter).substr(1));
  9517. } else {
  9518. // Clone the group's filter
  9519. gfilter = copyElem(gfilter);
  9520. findDefs().appendChild(gfilter);
  9521. }
  9522. } else {
  9523. gfilter = getElem(getUrlFromAttr(elem.getAttribute('filter')).substr(1));
  9524. }
  9525. // Change this in future for different filters
  9526. var suffix = (gfilter.firstChild.tagName === 'feGaussianBlur')?'blur':'filter';
  9527. gfilter.id = elem.id + '_' + suffix;
  9528. changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]);
  9529. // Update blur value
  9530. if(cblur) {
  9531. changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]);
  9532. canvas.setBlurOffsets(gfilter, cblur);
  9533. }
  9534. }
  9535. var chtlist = getTransformList(elem);
  9536. // Don't process gradient transforms
  9537. if(~elem.tagName.indexOf('Gradient')) chtlist = null;
  9538. // Hopefully not a problem to add this. Necessary for elements like <desc/>
  9539. if(!chtlist) continue;
  9540. if (glist.numberOfItems) {
  9541. // TODO: if the group's transform is just a rotate, we can always transfer the
  9542. // rotate() down to the children (collapsing consecutive rotates and factoring
  9543. // out any translates)
  9544. if (gangle && glist.numberOfItems == 1) {
  9545. // [Rg] [Rc] [Mc]
  9546. // we want [Tr] [Rc2] [Mc] where:
  9547. // - [Rc2] is at the child's current center but has the
  9548. // sum of the group and child's rotation angles
  9549. // - [Tr] is the equivalent translation that this child
  9550. // undergoes if the group wasn't there
  9551. // [Tr] = [Rg] [Rc] [Rc2_inv]
  9552. // get group's rotation matrix (Rg)
  9553. var rgm = glist.getItem(0).matrix;
  9554. // get child's rotation matrix (Rc)
  9555. var rcm = svgroot.createSVGMatrix();
  9556. var cangle = getRotationAngle(elem);
  9557. if (cangle) {
  9558. rcm = chtlist.getItem(0).matrix;
  9559. }
  9560. // get child's old center of rotation
  9561. var cbox = getBBox(elem);
  9562. var ceqm = transformListToTransform(chtlist).matrix;
  9563. var coldc = transformPoint(cbox.x+cbox.width/2, cbox.y+cbox.height/2,ceqm);
  9564. // sum group and child's angles
  9565. var sangle = gangle + cangle;
  9566. // get child's rotation at the old center (Rc2_inv)
  9567. var r2 = svgroot.createSVGTransform();
  9568. r2.setRotate(sangle, coldc.x, coldc.y);
  9569. // calculate equivalent translate
  9570. var trm = matrixMultiply(rgm, rcm, r2.matrix.inverse());
  9571. // set up tlist
  9572. if (cangle) {
  9573. chtlist.removeItem(0);
  9574. }
  9575. if (sangle) {
  9576. if(chtlist.numberOfItems) {
  9577. chtlist.insertItemBefore(r2, 0);
  9578. } else {
  9579. chtlist.appendItem(r2);
  9580. }
  9581. }
  9582. if (trm.e || trm.f) {
  9583. var tr = svgroot.createSVGTransform();
  9584. tr.setTranslate(trm.e, trm.f);
  9585. if(chtlist.numberOfItems) {
  9586. chtlist.insertItemBefore(tr, 0);
  9587. } else {
  9588. chtlist.appendItem(tr);
  9589. }
  9590. }
  9591. }
  9592. else { // more complicated than just a rotate
  9593. // transfer the group's transform down to each child and then
  9594. // call recalculateDimensions()
  9595. var oldxform = elem.getAttribute("transform");
  9596. var changes = {};
  9597. changes["transform"] = oldxform ? oldxform : "";
  9598. var newxform = svgroot.createSVGTransform();
  9599. // [ gm ] [ chm ] = [ chm ] [ gm' ]
  9600. // [ gm' ] = [ chm_inv ] [ gm ] [ chm ]
  9601. var chm = transformListToTransform(chtlist).matrix,
  9602. chm_inv = chm.inverse();
  9603. var gm = matrixMultiply( chm_inv, m, chm );
  9604. newxform.setMatrix(gm);
  9605. chtlist.appendItem(newxform);
  9606. }
  9607. batchCmd.addSubCommand(recalculateDimensions(elem));
  9608. }
  9609. }
  9610. // remove transform and make it undo-able
  9611. if (xform) {
  9612. var changes = {};
  9613. changes["transform"] = xform;
  9614. g.setAttribute("transform", "");
  9615. g.removeAttribute("transform");
  9616. batchCmd.addSubCommand(new ChangeElementCommand(g, changes));
  9617. }
  9618. // remove the group from the selection
  9619. clearSelection();
  9620. // delete the group element (but make undo-able)
  9621. g = parent.removeChild(g);
  9622. batchCmd.addSubCommand(new RemoveElementCommand(g, parent));
  9623. if (!batchCmd.isEmpty()) addCommandToHistory(batchCmd);
  9624. // update selection
  9625. addToSelection(children);
  9626. }
  9627. };
  9628. // Function: moveToTopSelectedElement
  9629. // Repositions the selected element to the bottom in the DOM to appear on top of
  9630. // other elements
  9631. this.moveToTopSelectedElement = function() {
  9632. var selected = selectedElements[0];
  9633. if (selected != null) {
  9634. var t = selected;
  9635. var oldParent = t.parentNode;
  9636. var oldNextSibling = t.nextSibling;
  9637. t = t.parentNode.appendChild(t);
  9638. addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, "top"));
  9639. }
  9640. };
  9641. // Function: moveToBottomSelectedElement
  9642. // Repositions the selected element to the top in the DOM to appear under
  9643. // other elements
  9644. this.moveToBottomSelectedElement = function() {
  9645. var selected = selectedElements[0];
  9646. if (selected != null) {
  9647. var t = selected;
  9648. var oldParent = t.parentNode;
  9649. var oldNextSibling = t.nextSibling;
  9650. var firstChild = t.parentNode.firstChild;
  9651. if (firstChild.tagName == 'title') {
  9652. firstChild = firstChild.nextSibling;
  9653. }
  9654. // This can probably be removed, as the defs should not ever apppear
  9655. // inside a layer group
  9656. if (firstChild.tagName == 'defs') {
  9657. firstChild = firstChild.nextSibling;
  9658. }
  9659. t = t.parentNode.insertBefore(t, firstChild);
  9660. addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, "bottom"));
  9661. }
  9662. };
  9663. // Function: moveUpDownSelected
  9664. // Moves the select element up or down the stack, based on the visibly
  9665. // intersecting elements
  9666. //
  9667. // Parameters:
  9668. // dir - String that's either 'Up' or 'Down'
  9669. this.moveUpDownSelected = function(dir) {
  9670. var selected = selectedElements[0];
  9671. if (!selected) return;
  9672. curBBoxes = [];
  9673. var closest, found_cur;
  9674. // jQuery sorts this list
  9675. var list = $(getIntersectionList(getStrokedBBox([selected]))).toArray();
  9676. if(dir == 'Down') list.reverse();
  9677. $.each(list, function() {
  9678. if(!found_cur) {
  9679. if(this == selected) {
  9680. found_cur = true;
  9681. }
  9682. return;
  9683. }
  9684. closest = this;
  9685. return false;
  9686. });
  9687. if(!closest) return;
  9688. var t = selected;
  9689. var oldParent = t.parentNode;
  9690. var oldNextSibling = t.nextSibling;
  9691. $(closest)[dir == 'Down'?'before':'after'](t);
  9692. addCommandToHistory(new MoveElementCommand(t, oldNextSibling, oldParent, "Move " + dir));
  9693. }
  9694. // Function: moveSelectedElements
  9695. // Moves selected elements on the X/Y axis
  9696. //
  9697. // Parameters:
  9698. // dx - Float with the distance to move on the x-axis
  9699. // dy - Float with the distance to move on the y-axis
  9700. // undoable - Boolean indicating whether or not the action should be undoable
  9701. //
  9702. // Returns:
  9703. // Batch command for the move
  9704. this.moveSelectedElements = function(dx, dy, undoable) {
  9705. // if undoable is not sent, default to true
  9706. // if single values, scale them to the zoom
  9707. if (dx.constructor != Array) {
  9708. dx /= current_zoom;
  9709. dy /= current_zoom;
  9710. }
  9711. var undoable = undoable || true;
  9712. var batchCmd = new BatchCommand("position");
  9713. var i = selectedElements.length;
  9714. while (i--) {
  9715. var selected = selectedElements[i];
  9716. if (selected != null) {
  9717. if (i==0)
  9718. selectedBBoxes[i] = getBBox(selected);
  9719. var b = {};
  9720. for(var j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j];
  9721. selectedBBoxes[i] = b;
  9722. var xform = svgroot.createSVGTransform();
  9723. var tlist = getTransformList(selected);
  9724. // dx and dy could be arrays
  9725. if (dx.constructor == Array) {
  9726. if (i==0) {
  9727. selectedBBoxes[i].x += dx[i];
  9728. selectedBBoxes[i].y += dy[i];
  9729. }
  9730. xform.setTranslate(dx[i],dy[i]);
  9731. } else {
  9732. if (i==0) {
  9733. selectedBBoxes[i].x += dx;
  9734. selectedBBoxes[i].y += dy;
  9735. }
  9736. xform.setTranslate(dx,dy);
  9737. }
  9738. if(tlist.numberOfItems) {
  9739. tlist.insertItemBefore(xform, 0);
  9740. } else {
  9741. tlist.appendItem(xform);
  9742. }
  9743. var cmd = recalculateDimensions(selected);
  9744. if (cmd) {
  9745. batchCmd.addSubCommand(cmd);
  9746. }
  9747. selectorManager.requestSelector(selected).resize();
  9748. }
  9749. }
  9750. if (!batchCmd.isEmpty()) {
  9751. if (undoable)
  9752. addCommandToHistory(batchCmd);
  9753. call("changed", selectedElements);
  9754. return batchCmd;
  9755. }
  9756. };
  9757. // Function: cloneSelectedElements
  9758. // Create deep DOM copies (clones) of all selected elements and move them slightly
  9759. // from their originals
  9760. this.cloneSelectedElements = function() {
  9761. var batchCmd = new BatchCommand("Clone Elements");
  9762. // find all the elements selected (stop at first null)
  9763. var len = selectedElements.length;
  9764. for (var i = 0; i < len; ++i) {
  9765. var elem = selectedElements[i];
  9766. if (elem == null) break;
  9767. }
  9768. // use slice to quickly get the subset of elements we need
  9769. var copiedElements = selectedElements.slice(0,i);
  9770. this.clearSelection(true);
  9771. // note that we loop in the reverse way because of the way elements are added
  9772. // to the selectedElements array (top-first)
  9773. var i = copiedElements.length;
  9774. while (i--) {
  9775. // clone each element and replace it within copiedElements
  9776. var elem = copiedElements[i] = copyElem(copiedElements[i]);
  9777. (current_group || current_layer).appendChild(elem);
  9778. batchCmd.addSubCommand(new InsertElementCommand(elem));
  9779. }
  9780. if (!batchCmd.isEmpty()) {
  9781. addToSelection(copiedElements.reverse()); // Need to reverse for correct selection-adding
  9782. this.moveSelectedElements(20,20,false);
  9783. addCommandToHistory(batchCmd);
  9784. }
  9785. };
  9786. // Function: alignSelectedElements
  9787. // Aligns selected elements
  9788. //
  9789. // Parameters:
  9790. // type - String with single character indicating the alignment type
  9791. // relative_to - String that must be one of the following:
  9792. // "selected", "largest", "smallest", "page"
  9793. this.alignSelectedElements = function(type, relative_to) {
  9794. var bboxes = [], angles = [];
  9795. var minx = Number.MAX_VALUE, maxx = Number.MIN_VALUE, miny = Number.MAX_VALUE, maxy = Number.MIN_VALUE;
  9796. var curwidth = Number.MIN_VALUE, curheight = Number.MIN_VALUE;
  9797. var len = selectedElements.length;
  9798. if (!len) return;
  9799. for (var i = 0; i < len; ++i) {
  9800. if (selectedElements[i] == null) break;
  9801. var elem = selectedElements[i];
  9802. bboxes[i] = getStrokedBBox([elem]);
  9803. // now bbox is axis-aligned and handles rotation
  9804. switch (relative_to) {
  9805. case 'smallest':
  9806. if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth > bboxes[i].width) ||
  9807. (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight > bboxes[i].height) ) {
  9808. minx = bboxes[i].x;
  9809. miny = bboxes[i].y;
  9810. maxx = bboxes[i].x + bboxes[i].width;
  9811. maxy = bboxes[i].y + bboxes[i].height;
  9812. curwidth = bboxes[i].width;
  9813. curheight = bboxes[i].height;
  9814. }
  9815. break;
  9816. case 'largest':
  9817. if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth < bboxes[i].width) ||
  9818. (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight < bboxes[i].height) ) {
  9819. minx = bboxes[i].x;
  9820. miny = bboxes[i].y;
  9821. maxx = bboxes[i].x + bboxes[i].width;
  9822. maxy = bboxes[i].y + bboxes[i].height;
  9823. curwidth = bboxes[i].width;
  9824. curheight = bboxes[i].height;
  9825. }
  9826. break;
  9827. default: // 'selected'
  9828. if (bboxes[i].x < minx) minx = bboxes[i].x;
  9829. if (bboxes[i].y < miny) miny = bboxes[i].y;
  9830. if (bboxes[i].x + bboxes[i].width > maxx) maxx = bboxes[i].x + bboxes[i].width;
  9831. if (bboxes[i].y + bboxes[i].height > maxy) maxy = bboxes[i].y + bboxes[i].height;
  9832. break;
  9833. }
  9834. } // loop for each element to find the bbox and adjust min/max
  9835. if (relative_to == 'page') {
  9836. minx = 0;
  9837. miny = 0;
  9838. maxx = canvas.contentW;
  9839. maxy = canvas.contentH;
  9840. }
  9841. var dx = new Array(len);
  9842. var dy = new Array(len);
  9843. for (var i = 0; i < len; ++i) {
  9844. if (selectedElements[i] == null) break;
  9845. var elem = selectedElements[i];
  9846. var bbox = bboxes[i];
  9847. dx[i] = 0;
  9848. dy[i] = 0;
  9849. switch (type) {
  9850. case 'l': // left (horizontal)
  9851. dx[i] = minx - bbox.x;
  9852. break;
  9853. case 'c': // center (horizontal)
  9854. dx[i] = (minx+maxx)/2 - (bbox.x + bbox.width/2);
  9855. break;
  9856. case 'r': // right (horizontal)
  9857. dx[i] = maxx - (bbox.x + bbox.width);
  9858. break;
  9859. case 't': // top (vertical)
  9860. dy[i] = miny - bbox.y;
  9861. break;
  9862. case 'm': // middle (vertical)
  9863. dy[i] = (miny+maxy)/2 - (bbox.y + bbox.height/2);
  9864. break;
  9865. case 'b': // bottom (vertical)
  9866. dy[i] = maxy - (bbox.y + bbox.height);
  9867. break;
  9868. }
  9869. }
  9870. this.moveSelectedElements(dx,dy);
  9871. };
  9872. // Group: Additional editor tools
  9873. this.contentW = getResolution().w;
  9874. this.contentH = getResolution().h;
  9875. // Function: updateCanvas
  9876. // Updates the editor canvas width/height/position after a zoom has occurred
  9877. //
  9878. // Parameters:
  9879. // w - Float with the new width
  9880. // h - Float with the new height
  9881. //
  9882. // Returns:
  9883. // Object with the following values:
  9884. // * x - The canvas' new x coordinate
  9885. // * y - The canvas' new y coordinate
  9886. // * old_x - The canvas' old x coordinate
  9887. // * old_y - The canvas' old y coordinate
  9888. // * d_x - The x position difference
  9889. // * d_y - The y position difference
  9890. this.updateCanvas = function(w, h) {
  9891. svgroot.setAttribute("width", w);
  9892. svgroot.setAttribute("height", h);
  9893. var bg = $('#canvasBackground')[0];
  9894. var old_x = svgcontent.getAttribute('x');
  9895. var old_y = svgcontent.getAttribute('y');
  9896. var x = (w/2 - this.contentW*current_zoom/2);
  9897. var y = (h/2 - this.contentH*current_zoom/2);
  9898. assignAttributes(svgcontent, {
  9899. width: this.contentW*current_zoom,
  9900. height: this.contentH*current_zoom,
  9901. 'x': x,
  9902. 'y': y,
  9903. "viewBox" : "0 0 " + this.contentW + " " + this.contentH
  9904. });
  9905. assignAttributes(bg, {
  9906. width: svgcontent.getAttribute('width'),
  9907. height: svgcontent.getAttribute('height'),
  9908. x: x,
  9909. y: y
  9910. });
  9911. selectorManager.selectorParentGroup.setAttribute("transform","translate(" + x + "," + y + ")");
  9912. return {x:x, y:y, old_x:old_x, old_y:old_y, d_x:x - old_x, d_y:y - old_y};
  9913. }
  9914. // Function: setBackground
  9915. // Set the background of the editor (NOT the actual document)
  9916. //
  9917. // Parameters:
  9918. // color - String with fill color to apply
  9919. // url - URL or path to image to use
  9920. this.setBackground = function(color, url) {
  9921. var bg = getElem('canvasBackground');
  9922. var border = $(bg).find('rect')[0];
  9923. var bg_img = getElem('background_image');
  9924. border.setAttribute('fill',color);
  9925. if(url) {
  9926. if(!bg_img) {
  9927. bg_img = svgdoc.createElementNS(svgns, "image");
  9928. assignAttributes(bg_img, {
  9929. 'id': 'background_image',
  9930. 'width': '100%',
  9931. 'height': '100%',
  9932. 'preserveAspectRatio': 'xMinYMin',
  9933. 'style':'pointer-events:none'
  9934. });
  9935. }
  9936. setHref(bg_img, url);
  9937. bg.appendChild(bg_img);
  9938. } else if(bg_img) {
  9939. bg_img.parentNode.removeChild(bg_img);
  9940. }
  9941. }
  9942. // Function: cycleElement
  9943. // Select the next/previous element within the current layer
  9944. //
  9945. // Parameters:
  9946. // next - Boolean where true = next and false = previous element
  9947. this.cycleElement = function(next) {
  9948. var cur_elem = selectedElements[0];
  9949. var elem = false;
  9950. var all_elems = getVisibleElements(current_group || current_layer);
  9951. if(!all_elems.length) return;
  9952. if (cur_elem == null) {
  9953. var num = next?all_elems.length-1:0;
  9954. elem = all_elems[num];
  9955. } else {
  9956. var i = all_elems.length;
  9957. while(i--) {
  9958. if(all_elems[i] == cur_elem) {
  9959. var num = next?i-1:i+1;
  9960. if(num >= all_elems.length) {
  9961. num = 0;
  9962. } else if(num < 0) {
  9963. num = all_elems.length-1;
  9964. }
  9965. elem = all_elems[num];
  9966. break;
  9967. }
  9968. }
  9969. }
  9970. selectOnly([elem], true);
  9971. call("selected", selectedElements);
  9972. }
  9973. this.clear();
  9974. // DEPRECATED: getPrivateMethods
  9975. // Since all methods are/should be public somehow, this function should be removed
  9976. // Being able to access private methods publicly seems wrong somehow,
  9977. // but currently appears to be the best way to allow testing and provide
  9978. // access to them to plugins.
  9979. this.getPrivateMethods = function() {
  9980. var obj = {
  9981. addCommandToHistory: addCommandToHistory,
  9982. setGradient: setGradient,
  9983. addSvgElementFromJson: addSvgElementFromJson,
  9984. assignAttributes: assignAttributes,
  9985. BatchCommand: BatchCommand,
  9986. call: call,
  9987. ChangeElementCommand: ChangeElementCommand,
  9988. cleanupElement: cleanupElement,
  9989. copyElem: copyElem,
  9990. ffClone: ffClone,
  9991. findDefs: findDefs,
  9992. findDuplicateGradient: findDuplicateGradient,
  9993. getElem: getElem,
  9994. getId: getId,
  9995. getIntersectionList: getIntersectionList,
  9996. getMouseTarget: getMouseTarget,
  9997. getNextId: getNextId,
  9998. getPathBBox: getPathBBox,
  9999. getUrlFromAttr: getUrlFromAttr,
  10000. hasMatrixTransform: hasMatrixTransform,
  10001. identifyLayers: identifyLayers,
  10002. InsertElementCommand: InsertElementCommand,
  10003. isIdentity: isIdentity,
  10004. logMatrix: logMatrix,
  10005. matrixMultiply: matrixMultiply,
  10006. MoveElementCommand: MoveElementCommand,
  10007. preventClickDefault: preventClickDefault,
  10008. recalculateAllSelectedDimensions: recalculateAllSelectedDimensions,
  10009. recalculateDimensions: recalculateDimensions,
  10010. remapElement: remapElement,
  10011. RemoveElementCommand: RemoveElementCommand,
  10012. removeUnusedDefElems: removeUnusedDefElems,
  10013. round: round,
  10014. runExtensions: runExtensions,
  10015. sanitizeSvg: sanitizeSvg,
  10016. SelectorManager: SelectorManager,
  10017. shortFloat: shortFloat,
  10018. svgCanvasToString: svgCanvasToString,
  10019. SVGEditTransformList: SVGEditTransformList,
  10020. svgToString: svgToString,
  10021. toString: toString,
  10022. transformBox: transformBox,
  10023. transformListToTransform: transformListToTransform,
  10024. transformPoint: transformPoint,
  10025. walkTree: walkTree
  10026. }
  10027. return obj;
  10028. };
  10029. // Temporary fix until MS fixes:
  10030. // https://connect.microsoft.com/IE/feedback/details/599257/
  10031. function disableAdvancedTextEdit() {
  10032. var curtext;
  10033. var textInput = $('#text').css({
  10034. position: 'static'
  10035. });
  10036. $.each(['mouseDown','mouseUp','mouseMove', 'setCursor', 'init', 'select', 'toEditMode'], function() {
  10037. textActions[this] = $.noop;
  10038. });
  10039. textActions.init = function(elem) {
  10040. curtext = elem;
  10041. $(curtext).unbind('dblclick').bind('dblclick', function() {
  10042. textInput.focus();
  10043. });
  10044. }
  10045. canvas.textActions = textActions;
  10046. }
  10047. // Test support for features/bugs
  10048. (function() {
  10049. // segList functions (for FF1.5 and 2.0)
  10050. var path = document.createElementNS(svgns,'path');
  10051. path.setAttribute('d','M0,0 10,10');
  10052. var seglist = path.pathSegList;
  10053. var seg = path.createSVGPathSegLinetoAbs(5,5);
  10054. try {
  10055. seglist.replaceItem(seg, 0);
  10056. support.pathReplaceItem = true;
  10057. } catch(err) {
  10058. support.pathReplaceItem = false;
  10059. }
  10060. try {
  10061. seglist.insertItemBefore(seg, 0);
  10062. support.pathInsertItemBefore = true;
  10063. } catch(err) {
  10064. support.pathInsertItemBefore = false;
  10065. }
  10066. var text = document.createElementNS(svgns,'text');
  10067. text.textContent = 'a';
  10068. svgcontent.appendChild(text);
  10069. // text character positioning
  10070. try {
  10071. text.getStartPositionOfChar(0);
  10072. support.textCharPos = true;
  10073. } catch(err) {
  10074. support.textCharPos = false;
  10075. disableAdvancedTextEdit();
  10076. }
  10077. svgcontent.removeChild(text);
  10078. // TODO: Find better way to check support for this
  10079. support.editableText = isOpera;
  10080. // Correct decimals on clone attributes (Opera < 10.5/win/non-en)
  10081. var rect = document.createElementNS(svgns,'rect');
  10082. rect.setAttribute('x',.1);
  10083. var crect = rect.cloneNode(false);
  10084. support.goodDecimals = (crect.getAttribute('x').indexOf(',') == -1);
  10085. if(!support.goodDecimals) {
  10086. $.alert("NOTE: This version of Opera is known to contain bugs in SVG-edit.\n\
  10087. Please upgrade to the <a href='http://opera.com'>latest version</a> in which the problems have been fixed.");
  10088. }
  10089. // Get correct em/ex values
  10090. var rect = document.createElementNS(svgns,'rect');
  10091. rect.setAttribute('width',"1em");
  10092. rect.setAttribute('height',"1ex");
  10093. rect.setAttribute('x',"1in");
  10094. svgcontent.appendChild(rect);
  10095. var bb = rect.getBBox();
  10096. unit_types.em = bb.width;
  10097. unit_types.ex = bb.height;
  10098. var inch = bb.x;
  10099. unit_types['in'] = inch;
  10100. unit_types.cm = inch / 2.54;
  10101. unit_types.mm = inch / 25.4;
  10102. unit_types.pt = inch / 72;
  10103. unit_types.pc = inch / 6;
  10104. unit_types['%'] = 0;
  10105. svgcontent.removeChild(rect);
  10106. }());
  10107. }