svgcanvas.js 224 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798
  1. /*globals $, svgedit, svgCanvas, jsPDF*/
  2. /*jslint vars: true, eqeq: true, todo: true, bitwise: true, continue: true, forin: true */
  3. /*
  4. * svgcanvas.js
  5. *
  6. * Licensed under the MIT License
  7. *
  8. * Copyright(c) 2010 Alexis Deveria
  9. * Copyright(c) 2010 Pavol Rusnak
  10. * Copyright(c) 2010 Jeff Schiller
  11. *
  12. */
  13. // Dependencies:
  14. // 1) jQuery
  15. // 2) pathseg.js
  16. // 3) browser.js
  17. // 4) svgtransformlist.js
  18. // 5) math.js
  19. // 6) units.js
  20. // 7) svgutils.js
  21. // 8) sanitize.js
  22. // 9) history.js
  23. // 10) select.js
  24. // 11) draw.js
  25. // 12) path.js
  26. // 13) coords.js
  27. // 14) recalculate.js
  28. (function () {
  29. if (!window.console) {
  30. window.console = {};
  31. window.console.log = function(str) {};
  32. window.console.dir = function(str) {};
  33. }
  34. if (window.opera) {
  35. window.console.log = function(str) { opera.postError(str); };
  36. window.console.dir = function(str) {};
  37. }
  38. }());
  39. // Class: SvgCanvas
  40. // The main SvgCanvas class that manages all SVG-related functions
  41. //
  42. // Parameters:
  43. // container - The container HTML element that should hold the SVG root element
  44. // config - An object that contains configuration data
  45. $.SvgCanvas = function(container, config) {
  46. // Alias Namespace constants
  47. var NS = svgedit.NS;
  48. // Default configuration options
  49. var curConfig = {
  50. show_outside_canvas: true,
  51. selectNew: true,
  52. dimensions: [640, 480]
  53. };
  54. // Update config with new one if given
  55. if (config) {
  56. $.extend(curConfig, config);
  57. }
  58. // Array with width/height of canvas
  59. var dimensions = curConfig.dimensions;
  60. var canvas = this;
  61. // "document" element associated with the container (same as window.document using default svg-editor.js)
  62. // NOTE: This is not actually a SVG document, but a HTML document.
  63. var svgdoc = container.ownerDocument;
  64. // This is a container for the document being edited, not the document itself.
  65. var svgroot = svgdoc.importNode(svgedit.utilities.text2xml(
  66. '<svg id="svgroot" xmlns="' + NS.SVG + '" xlinkns="' + NS.XLINK + '" ' +
  67. 'width="' + dimensions[0] + '" height="' + dimensions[1] + '" x="' + dimensions[0] + '" y="' + dimensions[1] + '" overflow="visible">' +
  68. '<defs>' +
  69. '<filter id="canvashadow" filterUnits="objectBoundingBox">' +
  70. '<feGaussianBlur in="SourceAlpha" stdDeviation="4" result="blur"/>'+
  71. '<feOffset in="blur" dx="5" dy="5" result="offsetBlur"/>'+
  72. '<feMerge>'+
  73. '<feMergeNode in="offsetBlur"/>'+
  74. '<feMergeNode in="SourceGraphic"/>'+
  75. '</feMerge>'+
  76. '</filter>'+
  77. '</defs>'+
  78. '</svg>').documentElement, true);
  79. container.appendChild(svgroot);
  80. // The actual element that represents the final output SVG element
  81. var svgcontent = svgdoc.createElementNS(NS.SVG, 'svg');
  82. // This function resets the svgcontent element while keeping it in the DOM.
  83. var clearSvgContentElement = canvas.clearSvgContentElement = function() {
  84. while (svgcontent.firstChild) { svgcontent.removeChild(svgcontent.firstChild); }
  85. // TODO: Clear out all other attributes first?
  86. $(svgcontent).attr({
  87. id: 'svgcontent',
  88. width: dimensions[0],
  89. height: dimensions[1],
  90. x: dimensions[0],
  91. y: dimensions[1],
  92. overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden',
  93. xmlns: NS.SVG,
  94. 'xmlns:se': NS.SE,
  95. 'xmlns:xlink': NS.XLINK
  96. }).appendTo(svgroot);
  97. // TODO: make this string optional and set by the client
  98. var comment = svgdoc.createComment(" Created with SVG-edit - http://svg-edit.googlecode.com/ ");
  99. svgcontent.appendChild(comment);
  100. };
  101. clearSvgContentElement();
  102. // Prefix string for element IDs
  103. var idprefix = 'svg_';
  104. // Function: setIdPrefix
  105. // Changes the ID prefix to the given value
  106. //
  107. // Parameters:
  108. // p - String with the new prefix
  109. canvas.setIdPrefix = function(p) {
  110. idprefix = p;
  111. };
  112. // Current svgedit.draw.Drawing object
  113. // @type {svgedit.draw.Drawing}
  114. canvas.current_drawing_ = new svgedit.draw.Drawing(svgcontent, idprefix);
  115. // Function: getCurrentDrawing
  116. // Returns the current Drawing.
  117. // @return {svgedit.draw.Drawing}
  118. var getCurrentDrawing = canvas.getCurrentDrawing = function() {
  119. return canvas.current_drawing_;
  120. };
  121. // Float displaying the current zoom level (1 = 100%, .5 = 50%, etc)
  122. var current_zoom = 1;
  123. // pointer to current group (for in-group editing)
  124. var current_group = null;
  125. // Object containing data for the currently selected styles
  126. var all_properties = {
  127. shape: {
  128. fill: (curConfig.initFill.color == 'none' ? '' : '#') + curConfig.initFill.color,
  129. fill_paint: null,
  130. fill_opacity: curConfig.initFill.opacity,
  131. stroke: '#' + curConfig.initStroke.color,
  132. stroke_paint: null,
  133. stroke_opacity: curConfig.initStroke.opacity,
  134. stroke_width: curConfig.initStroke.width,
  135. stroke_dasharray: 'none',
  136. stroke_linejoin: 'miter',
  137. stroke_linecap: 'butt',
  138. opacity: curConfig.initOpacity
  139. }
  140. };
  141. all_properties.text = $.extend(true, {}, all_properties.shape);
  142. $.extend(all_properties.text, {
  143. fill: '#000000',
  144. stroke_width: 0,
  145. font_size: 24,
  146. font_family: 'serif'
  147. });
  148. // Current shape style properties
  149. var cur_shape = all_properties.shape;
  150. // Array with all the currently selected elements
  151. // default size of 1 until it needs to grow bigger
  152. var selectedElements = [];
  153. // Function: addSvgElementFromJson
  154. // Create a new SVG element based on the given object keys/values and add it to the current layer
  155. // The element will be ran through cleanupElement before being returned
  156. //
  157. // Parameters:
  158. // data - Object with the following keys/values:
  159. // * element - tag name of the SVG element to create
  160. // * attr - Object with attributes key-values to assign to the new element
  161. // * curStyles - Boolean indicating that current style attributes should be applied first
  162. //
  163. // Returns: The new element
  164. var addSvgElementFromJson = this.addSvgElementFromJson = function(data) {
  165. var shape = svgedit.utilities.getElem(data.attr.id);
  166. // if shape is a path but we need to create a rect/ellipse, then remove the path
  167. var current_layer = getCurrentDrawing().getCurrentLayer();
  168. if (shape && data.element != shape.tagName) {
  169. current_layer.removeChild(shape);
  170. shape = null;
  171. }
  172. if (!shape) {
  173. shape = svgdoc.createElementNS(NS.SVG, data.element);
  174. if (current_layer) {
  175. (current_group || current_layer).appendChild(shape);
  176. }
  177. }
  178. if (data.curStyles) {
  179. svgedit.utilities.assignAttributes(shape, {
  180. 'fill': cur_shape.fill,
  181. 'stroke': cur_shape.stroke,
  182. 'stroke-width': cur_shape.stroke_width,
  183. 'stroke-dasharray': cur_shape.stroke_dasharray,
  184. 'stroke-linejoin': cur_shape.stroke_linejoin,
  185. 'stroke-linecap': cur_shape.stroke_linecap,
  186. 'stroke-opacity': cur_shape.stroke_opacity,
  187. 'fill-opacity': cur_shape.fill_opacity,
  188. 'opacity': cur_shape.opacity / 2,
  189. 'style': 'pointer-events:inherit'
  190. }, 100);
  191. }
  192. svgedit.utilities.assignAttributes(shape, data.attr, 100);
  193. svgedit.utilities.cleanupElement(shape);
  194. return shape;
  195. };
  196. // import svgtransformlist.js
  197. var getTransformList = canvas.getTransformList = svgedit.transformlist.getTransformList;
  198. // import from math.js.
  199. var transformPoint = svgedit.math.transformPoint;
  200. var matrixMultiply = canvas.matrixMultiply = svgedit.math.matrixMultiply;
  201. var hasMatrixTransform = canvas.hasMatrixTransform = svgedit.math.hasMatrixTransform;
  202. var transformListToTransform = canvas.transformListToTransform = svgedit.math.transformListToTransform;
  203. var snapToAngle = svgedit.math.snapToAngle;
  204. var getMatrix = svgedit.math.getMatrix;
  205. // initialize from units.js
  206. // send in an object implementing the ElementContainer interface (see units.js)
  207. svgedit.units.init({
  208. getBaseUnit: function() { return curConfig.baseUnit; },
  209. getElement: svgedit.utilities.getElem,
  210. getHeight: function() { return svgcontent.getAttribute('height')/current_zoom; },
  211. getWidth: function() { return svgcontent.getAttribute('width')/current_zoom; },
  212. getRoundDigits: function() { return save_options.round_digits; }
  213. });
  214. // import from units.js
  215. var convertToNum = canvas.convertToNum = svgedit.units.convertToNum;
  216. // import from svgutils.js
  217. svgedit.utilities.init({
  218. getDOMDocument: function() { return svgdoc; },
  219. getDOMContainer: function() { return container; },
  220. getSVGRoot: function() { return svgroot; },
  221. // TODO: replace this mostly with a way to get the current drawing.
  222. getSelectedElements: function() { return selectedElements; },
  223. getSVGContent: function() { return svgcontent; },
  224. getBaseUnit: function() { return curConfig.baseUnit; },
  225. getSnappingStep: function() { return curConfig.snappingStep; }
  226. });
  227. var findDefs = canvas.findDefs = svgedit.utilities.findDefs;
  228. var getUrlFromAttr = canvas.getUrlFromAttr = svgedit.utilities.getUrlFromAttr;
  229. var getHref = canvas.getHref = svgedit.utilities.getHref;
  230. var setHref = canvas.setHref = svgedit.utilities.setHref;
  231. var getPathBBox = svgedit.utilities.getPathBBox;
  232. var getBBox = canvas.getBBox = svgedit.utilities.getBBox;
  233. var getRotationAngle = canvas.getRotationAngle = svgedit.utilities.getRotationAngle;
  234. var getElem = canvas.getElem = svgedit.utilities.getElem;
  235. var getRefElem = canvas.getRefElem = svgedit.utilities.getRefElem;
  236. var assignAttributes = canvas.assignAttributes = svgedit.utilities.assignAttributes;
  237. var cleanupElement = this.cleanupElement = svgedit.utilities.cleanupElement;
  238. // import from coords.js
  239. svgedit.coords.init({
  240. getDrawing: function() { return getCurrentDrawing(); },
  241. getGridSnapping: function() { return curConfig.gridSnapping; }
  242. });
  243. var remapElement = this.remapElement = svgedit.coords.remapElement;
  244. // import from recalculate.js
  245. svgedit.recalculate.init({
  246. getSVGRoot: function() { return svgroot; },
  247. getStartTransform: function() { return startTransform; },
  248. setStartTransform: function(transform) { startTransform = transform; }
  249. });
  250. var recalculateDimensions = this.recalculateDimensions = svgedit.recalculate.recalculateDimensions;
  251. // import from sanitize.js
  252. var nsMap = svgedit.getReverseNS();
  253. var sanitizeSvg = canvas.sanitizeSvg = svgedit.sanitize.sanitizeSvg;
  254. // import from history.js
  255. var MoveElementCommand = svgedit.history.MoveElementCommand;
  256. var InsertElementCommand = svgedit.history.InsertElementCommand;
  257. var RemoveElementCommand = svgedit.history.RemoveElementCommand;
  258. var ChangeElementCommand = svgedit.history.ChangeElementCommand;
  259. var BatchCommand = svgedit.history.BatchCommand;
  260. var call;
  261. // Implement the svgedit.history.HistoryEventHandler interface.
  262. canvas.undoMgr = new svgedit.history.UndoManager({
  263. handleHistoryEvent: function(eventType, cmd) {
  264. var EventTypes = svgedit.history.HistoryEventTypes;
  265. // TODO: handle setBlurOffsets.
  266. if (eventType == EventTypes.BEFORE_UNAPPLY || eventType == EventTypes.BEFORE_APPLY) {
  267. canvas.clearSelection();
  268. } else if (eventType == EventTypes.AFTER_APPLY || eventType == EventTypes.AFTER_UNAPPLY) {
  269. var elems = cmd.elements();
  270. canvas.pathActions.clear();
  271. call('changed', elems);
  272. var cmdType = cmd.type();
  273. var isApply = (eventType == EventTypes.AFTER_APPLY);
  274. if (cmdType == MoveElementCommand.type()) {
  275. var parent = isApply ? cmd.newParent : cmd.oldParent;
  276. if (parent == svgcontent) {
  277. canvas.identifyLayers();
  278. }
  279. } else if (cmdType == InsertElementCommand.type() ||
  280. cmdType == RemoveElementCommand.type()) {
  281. if (cmd.parent == svgcontent) {
  282. canvas.identifyLayers();
  283. }
  284. if (cmdType == InsertElementCommand.type()) {
  285. if (isApply) {restoreRefElems(cmd.elem);}
  286. } else {
  287. if (!isApply) {restoreRefElems(cmd.elem);}
  288. }
  289. if (cmd.elem.tagName === 'use') {
  290. setUseData(cmd.elem);
  291. }
  292. } else if (cmdType == ChangeElementCommand.type()) {
  293. // if we are changing layer names, re-identify all layers
  294. if (cmd.elem.tagName == 'title' && cmd.elem.parentNode.parentNode == svgcontent) {
  295. canvas.identifyLayers();
  296. }
  297. var values = isApply ? cmd.newValues : cmd.oldValues;
  298. // If stdDeviation was changed, update the blur.
  299. if (values.stdDeviation) {
  300. canvas.setBlurOffsets(cmd.elem.parentNode, values.stdDeviation);
  301. }
  302. // This is resolved in later versions of webkit, perhaps we should
  303. // have a featured detection for correct 'use' behavior?
  304. // ——————————
  305. // Remove & Re-add hack for Webkit (issue 775)
  306. //if (cmd.elem.tagName === 'use' && svgedit.browser.isWebkit()) {
  307. // var elem = cmd.elem;
  308. // if (!elem.getAttribute('x') && !elem.getAttribute('y')) {
  309. // var parent = elem.parentNode;
  310. // var sib = elem.nextSibling;
  311. // parent.removeChild(elem);
  312. // parent.insertBefore(elem, sib);
  313. // }
  314. //}
  315. }
  316. }
  317. }
  318. });
  319. var addCommandToHistory = function(cmd) {
  320. canvas.undoMgr.addCommandToHistory(cmd);
  321. };
  322. // import from select.js
  323. svgedit.select.init(curConfig, {
  324. createSVGElement: function(jsonMap) { return canvas.addSvgElementFromJson(jsonMap); },
  325. svgRoot: function() { return svgroot; },
  326. svgContent: function() { return svgcontent; },
  327. currentZoom: function() { return current_zoom; },
  328. // TODO(codedread): Remove when getStrokedBBox() has been put into svgutils.js.
  329. getStrokedBBox: function(elems) { return canvas.getStrokedBBox([elems]); }
  330. });
  331. // this object manages selectors for us
  332. var selectorManager = this.selectorManager = svgedit.select.getSelectorManager();
  333. // Import from path.js
  334. svgedit.path.init({
  335. getCurrentZoom: function() { return current_zoom; },
  336. getSVGRoot: function() { return svgroot; }
  337. });
  338. // Interface strings, usually for title elements
  339. var uiStrings = {
  340. exportNoBlur: "Blurred elements will appear as un-blurred",
  341. exportNoforeignObject: "foreignObject elements will not appear",
  342. exportNoDashArray: "Strokes will appear filled",
  343. exportNoText: "Text may not appear as expected"
  344. };
  345. var visElems = 'a,circle,ellipse,foreignObject,g,image,line,path,polygon,polyline,rect,svg,text,tspan,use';
  346. var ref_attrs = ['clip-path', 'fill', 'filter', 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke'];
  347. var elData = $.data;
  348. // Animation element to change the opacity of any newly created element
  349. var opac_ani = document.createElementNS(NS.SVG, 'animate');
  350. $(opac_ani).attr({
  351. attributeName: 'opacity',
  352. begin: 'indefinite',
  353. dur: 1,
  354. fill: 'freeze'
  355. }).appendTo(svgroot);
  356. var restoreRefElems = function(elem) {
  357. // Look for missing reference elements, restore any found
  358. var o, i, l,
  359. attrs = $(elem).attr(ref_attrs);
  360. for (o in attrs) {
  361. var val = attrs[o];
  362. if (val && val.indexOf('url(') === 0) {
  363. var id = svgedit.utilities.getUrlFromAttr(val).substr(1);
  364. var ref = getElem(id);
  365. if (!ref) {
  366. svgedit.utilities.findDefs().appendChild(removedElements[id]);
  367. delete removedElements[id];
  368. }
  369. }
  370. }
  371. var childs = elem.getElementsByTagName('*');
  372. if (childs.length) {
  373. for (i = 0, l = childs.length; i < l; i++) {
  374. restoreRefElems(childs[i]);
  375. }
  376. }
  377. };
  378. (function() {
  379. // TODO For Issue 208: this is a start on a thumbnail
  380. // var svgthumb = svgdoc.createElementNS(NS.SVG, 'use');
  381. // svgthumb.setAttribute('width', '100');
  382. // svgthumb.setAttribute('height', '100');
  383. // svgedit.utilities.setHref(svgthumb, '#svgcontent');
  384. // svgroot.appendChild(svgthumb);
  385. }());
  386. // Object to contain image data for raster images that were found encodable
  387. var encodableImages = {},
  388. // String with image URL of last loadable image
  389. last_good_img_url = curConfig.imgPath + 'logo.png',
  390. // Array with current disabled elements (for in-group editing)
  391. disabled_elems = [],
  392. // Object with save options
  393. save_options = {round_digits: 5},
  394. // Boolean indicating whether or not a draw action has been started
  395. started = false,
  396. // String with an element's initial transform attribute value
  397. startTransform = null,
  398. // String indicating the current editor mode
  399. current_mode = 'select',
  400. // String with the current direction in which an element is being resized
  401. current_resize_mode = 'none',
  402. // Object with IDs for imported files, to see if one was already added
  403. import_ids = {},
  404. // Current text style properties
  405. cur_text = all_properties.text,
  406. // Current general properties
  407. cur_properties = cur_shape,
  408. // Array with selected elements' Bounding box object
  409. // selectedBBoxes = new Array(1),
  410. // The DOM element that was just selected
  411. justSelected = null,
  412. // DOM element for selection rectangle drawn by the user
  413. rubberBox = null,
  414. // Array of current BBoxes, used in getIntersectionList().
  415. curBBoxes = [],
  416. // Object to contain all included extensions
  417. extensions = {},
  418. // Canvas point for the most recent right click
  419. lastClickPoint = null,
  420. // Map of deleted reference elements
  421. removedElements = {};
  422. // Clipboard for cut, copy&pasted elements
  423. canvas.clipBoard = [];
  424. // Should this return an array by default, so extension results aren't overwritten?
  425. var runExtensions = this.runExtensions = function(action, vars, returnArray) {
  426. var result = returnArray ? [] : false;
  427. $.each(extensions, function(name, opts) {
  428. if (opts && action in opts) {
  429. if (returnArray) {
  430. result.push(opts[action](vars));
  431. } else {
  432. result = opts[action](vars);
  433. }
  434. }
  435. });
  436. return result;
  437. };
  438. // Function: addExtension
  439. // Add an extension to the editor
  440. //
  441. // Parameters:
  442. // name - String with the ID of the extension
  443. // ext_func - Function supplied by the extension with its data
  444. this.addExtension = function(name, ext_func) {
  445. var ext;
  446. if (!(name in extensions)) {
  447. // Provide private vars/funcs here. Is there a better way to do this?
  448. if ($.isFunction(ext_func)) {
  449. ext = ext_func($.extend(canvas.getPrivateMethods(), {
  450. svgroot: svgroot,
  451. svgcontent: svgcontent,
  452. nonce: getCurrentDrawing().getNonce(),
  453. selectorManager: selectorManager
  454. }));
  455. } else {
  456. ext = ext_func;
  457. }
  458. extensions[name] = ext;
  459. call('extension_added', ext);
  460. } else {
  461. console.log('Cannot add extension "' + name + '", an extension by that name already exists.');
  462. }
  463. };
  464. // This method rounds the incoming value to the nearest value based on the current_zoom
  465. var round = this.round = function(val) {
  466. return parseInt(val*current_zoom, 10)/current_zoom;
  467. };
  468. // This method sends back an array or a NodeList full of elements that
  469. // intersect the multi-select rubber-band-box on the current_layer only.
  470. //
  471. // We brute-force getIntersectionList for browsers that do not support it (Firefox).
  472. //
  473. // Reference:
  474. // Firefox does not implement getIntersectionList(), see https://bugzilla.mozilla.org/show_bug.cgi?id=501421
  475. var getIntersectionList = this.getIntersectionList = function(rect) {
  476. if (rubberBox == null) { return null; }
  477. var parent = current_group || getCurrentDrawing().getCurrentLayer();
  478. var rubberBBox;
  479. if (!rect) {
  480. rubberBBox = rubberBox.getBBox();
  481. } else {
  482. rubberBBox = svgcontent.createSVGRect(rect.x, rect.y, rect.width, rect.height);
  483. }
  484. var resultList = null;
  485. if (typeof(svgroot.getIntersectionList) == 'function') {
  486. // Offset the bbox of the rubber box by the offset of the svgcontent element.
  487. rubberBBox.x += parseInt(svgcontent.getAttribute('x'), 10);
  488. rubberBBox.y += parseInt(svgcontent.getAttribute('y'), 10);
  489. resultList = svgroot.getIntersectionList(rubberBBox, parent);
  490. }
  491. if (resultList == null || typeof(resultList.item) != 'function') {
  492. resultList = [];
  493. if (!curBBoxes.length) {
  494. // Cache all bboxes
  495. curBBoxes = getVisibleElementsAndBBoxes(parent);
  496. }
  497. var i = curBBoxes.length;
  498. while (i--) {
  499. if (!rubberBBox.width) {continue;}
  500. if (svgedit.math.rectsIntersect(rubberBBox, curBBoxes[i].bbox)) {
  501. resultList.push(curBBoxes[i].elem);
  502. }
  503. }
  504. }
  505. // addToSelection expects an array, but it's ok to pass a NodeList
  506. // because using square-bracket notation is allowed:
  507. // http://www.w3.org/TR/DOM-Level-2-Core/ecma-script-binding.html
  508. return resultList;
  509. };
  510. // TODO(codedread): Migrate this into svgutils.js
  511. // Function: getStrokedBBox
  512. // Get the bounding box for one or more stroked and/or transformed elements
  513. //
  514. // Parameters:
  515. // elems - Array with DOM elements to check
  516. //
  517. // Returns:
  518. // A single bounding box object
  519. getStrokedBBox = this.getStrokedBBox = function(elems) {
  520. if (!elems) {elems = getVisibleElements();}
  521. if (!elems.length) {return false;}
  522. // Make sure the expected BBox is returned if the element is a group
  523. var getCheckedBBox = function(elem) {
  524. // TODO: Fix issue with rotated groups. Currently they work
  525. // fine in FF, but not in other browsers (same problem mentioned
  526. // in Issue 339 comment #2).
  527. var bb = svgedit.utilities.getBBox(elem);
  528. if (!bb) {
  529. return null;
  530. }
  531. var angle = svgedit.utilities.getRotationAngle(elem);
  532. if ((angle && angle % 90) ||
  533. svgedit.math.hasMatrixTransform(svgedit.transformlist.getTransformList(elem))) {
  534. // Accurate way to get BBox of rotated element in Firefox:
  535. // Put element in group and get its BBox
  536. var good_bb = false;
  537. // Get the BBox from the raw path for these elements
  538. var elemNames = ['ellipse', 'path', 'line', 'polyline', 'polygon'];
  539. if (elemNames.indexOf(elem.tagName) >= 0) {
  540. bb = good_bb = canvas.convertToPath(elem, true);
  541. } else if (elem.tagName == 'rect') {
  542. // Look for radius
  543. var rx = elem.getAttribute('rx');
  544. var ry = elem.getAttribute('ry');
  545. if (rx || ry) {
  546. bb = good_bb = canvas.convertToPath(elem, true);
  547. }
  548. }
  549. if (!good_bb) {
  550. // Must use clone else FF freaks out
  551. var clone = elem.cloneNode(true);
  552. var g = document.createElementNS(NS.SVG, 'g');
  553. var parent = elem.parentNode;
  554. parent.appendChild(g);
  555. g.appendChild(clone);
  556. bb = svgedit.utilities.bboxToObj(g.getBBox());
  557. parent.removeChild(g);
  558. }
  559. // Old method: Works by giving the rotated BBox,
  560. // this is (unfortunately) what Opera and Safari do
  561. // natively when getting the BBox of the parent group
  562. // var angle = angle * Math.PI / 180.0;
  563. // var rminx = Number.MAX_VALUE, rminy = Number.MAX_VALUE,
  564. // rmaxx = Number.MIN_VALUE, rmaxy = Number.MIN_VALUE;
  565. // var cx = round(bb.x + bb.width/2),
  566. // cy = round(bb.y + bb.height/2);
  567. // var pts = [ [bb.x - cx, bb.y - cy],
  568. // [bb.x + bb.width - cx, bb.y - cy],
  569. // [bb.x + bb.width - cx, bb.y + bb.height - cy],
  570. // [bb.x - cx, bb.y + bb.height - cy] ];
  571. // var j = 4;
  572. // while (j--) {
  573. // var x = pts[j][0],
  574. // y = pts[j][1],
  575. // r = Math.sqrt( x*x + y*y );
  576. // var theta = Math.atan2(y,x) + angle;
  577. // x = round(r * Math.cos(theta) + cx);
  578. // y = round(r * Math.sin(theta) + cy);
  579. //
  580. // // now set the bbox for the shape after it's been rotated
  581. // if (x < rminx) rminx = x;
  582. // if (y < rminy) rminy = y;
  583. // if (x > rmaxx) rmaxx = x;
  584. // if (y > rmaxy) rmaxy = y;
  585. // }
  586. //
  587. // bb.x = rminx;
  588. // bb.y = rminy;
  589. // bb.width = rmaxx - rminx;
  590. // bb.height = rmaxy - rminy;
  591. }
  592. return bb;
  593. };
  594. var full_bb;
  595. $.each(elems, function() {
  596. if (full_bb) {return;}
  597. if (!this.parentNode) {return;}
  598. full_bb = getCheckedBBox(this);
  599. });
  600. // This shouldn't ever happen...
  601. if (full_bb == null) {return null;}
  602. // full_bb doesn't include the stoke, so this does no good!
  603. // if (elems.length == 1) return full_bb;
  604. var max_x = full_bb.x + full_bb.width;
  605. var max_y = full_bb.y + full_bb.height;
  606. var min_x = full_bb.x;
  607. var min_y = full_bb.y;
  608. // FIXME: same re-creation problem with this function as getCheckedBBox() above
  609. var getOffset = function(elem) {
  610. var sw = elem.getAttribute('stroke-width');
  611. var offset = 0;
  612. if (elem.getAttribute('stroke') != 'none' && !isNaN(sw)) {
  613. offset += sw/2;
  614. }
  615. return offset;
  616. };
  617. var bboxes = [];
  618. $.each(elems, function(i, elem) {
  619. var cur_bb = getCheckedBBox(elem);
  620. if (cur_bb) {
  621. var offset = getOffset(elem);
  622. min_x = Math.min(min_x, cur_bb.x - offset);
  623. min_y = Math.min(min_y, cur_bb.y - offset);
  624. bboxes.push(cur_bb);
  625. }
  626. });
  627. full_bb.x = min_x;
  628. full_bb.y = min_y;
  629. $.each(elems, function(i, elem) {
  630. var cur_bb = bboxes[i];
  631. // ensure that elem is really an element node
  632. if (cur_bb && elem.nodeType == 1) {
  633. var offset = getOffset(elem);
  634. max_x = Math.max(max_x, cur_bb.x + cur_bb.width + offset);
  635. max_y = Math.max(max_y, cur_bb.y + cur_bb.height + offset);
  636. }
  637. });
  638. full_bb.width = max_x - min_x;
  639. full_bb.height = max_y - min_y;
  640. return full_bb;
  641. };
  642. // Function: getVisibleElements
  643. // Get all elements that have a BBox (excludes <defs>, <title>, etc).
  644. // Note that 0-opacity, off-screen etc elements are still considered "visible"
  645. // for this function
  646. //
  647. // Parameters:
  648. // parent - The parent DOM element to search within
  649. //
  650. // Returns:
  651. // An array with all "visible" elements.
  652. var getVisibleElements = this.getVisibleElements = function(parent) {
  653. if (!parent) {
  654. parent = $(svgcontent).children(); // Prevent layers from being included
  655. }
  656. var contentElems = [];
  657. $(parent).children().each(function(i, elem) {
  658. if (elem.getBBox) {
  659. contentElems.push(elem);
  660. }
  661. });
  662. return contentElems.reverse();
  663. };
  664. // Function: getVisibleElementsAndBBoxes
  665. // Get all elements that have a BBox (excludes <defs>, <title>, etc).
  666. // Note that 0-opacity, off-screen etc elements are still considered "visible"
  667. // for this function
  668. //
  669. // Parameters:
  670. // parent - The parent DOM element to search within
  671. //
  672. // Returns:
  673. // An array with objects that include:
  674. // * elem - The element
  675. // * bbox - The element's BBox as retrieved from getStrokedBBox
  676. var getVisibleElementsAndBBoxes = this.getVisibleElementsAndBBoxes = function(parent) {
  677. if (!parent) {
  678. parent = $(svgcontent).children(); // Prevent layers from being included
  679. }
  680. var contentElems = [];
  681. $(parent).children().each(function(i, elem) {
  682. if (elem.getBBox) {
  683. contentElems.push({'elem':elem, 'bbox':getStrokedBBox([elem])});
  684. }
  685. });
  686. return contentElems.reverse();
  687. };
  688. // Function: groupSvgElem
  689. // Wrap an SVG element into a group element, mark the group as 'gsvg'
  690. //
  691. // Parameters:
  692. // elem - SVG element to wrap
  693. var groupSvgElem = this.groupSvgElem = function(elem) {
  694. var g = document.createElementNS(NS.SVG, 'g');
  695. elem.parentNode.replaceChild(g, elem);
  696. $(g).append(elem).data('gsvg', elem)[0].id = getNextId();
  697. };
  698. // Function: copyElem
  699. // Create a clone of an element, updating its ID and its children's IDs when needed
  700. //
  701. // Parameters:
  702. // el - DOM element to clone
  703. //
  704. // Returns: The cloned element
  705. var copyElem = function(el) {
  706. // manually create a copy of the element
  707. var new_el = document.createElementNS(el.namespaceURI, el.nodeName);
  708. $.each(el.attributes, function(i, attr) {
  709. if (attr.localName != '-moz-math-font-style') {
  710. new_el.setAttributeNS(attr.namespaceURI, attr.nodeName, attr.value);
  711. }
  712. });
  713. // set the copied element's new id
  714. new_el.removeAttribute('id');
  715. new_el.id = getNextId();
  716. // Opera's "d" value needs to be reset for Opera/Win/non-EN
  717. // Also needed for webkit (else does not keep curved segments on clone)
  718. if (svgedit.browser.isWebkit() && el.nodeName == 'path') {
  719. var fixed_d = pathActions.convertPath(el);
  720. new_el.setAttribute('d', fixed_d);
  721. }
  722. // now create copies of all children
  723. $.each(el.childNodes, function(i, child) {
  724. switch(child.nodeType) {
  725. case 1: // element node
  726. new_el.appendChild(copyElem(child));
  727. break;
  728. case 3: // text node
  729. new_el.textContent = child.nodeValue;
  730. break;
  731. default:
  732. break;
  733. }
  734. });
  735. if ($(el).data('gsvg')) {
  736. $(new_el).data('gsvg', new_el.firstChild);
  737. } else if ($(el).data('symbol')) {
  738. var ref = $(el).data('symbol');
  739. $(new_el).data('ref', ref).data('symbol', ref);
  740. } else if (new_el.tagName == 'image') {
  741. preventClickDefault(new_el);
  742. }
  743. return new_el;
  744. };
  745. // Set scope for these functions
  746. var getId, getNextId;
  747. var textActions, pathActions;
  748. (function(c) {
  749. // Object to contain editor event names and callback functions
  750. var events = {};
  751. getId = c.getId = function() { return getCurrentDrawing().getId(); };
  752. getNextId = c.getNextId = function() { return getCurrentDrawing().getNextId(); };
  753. // Function: call
  754. // Run the callback function associated with the given event
  755. //
  756. // Parameters:
  757. // event - String with the event name
  758. // arg - Argument to pass through to the callback function
  759. call = c.call = function(event, arg) {
  760. if (events[event]) {
  761. return events[event](this, arg);
  762. }
  763. };
  764. // Function: bind
  765. // Attaches a callback function to an event
  766. //
  767. // Parameters:
  768. // event - String indicating the name of the event
  769. // f - The callback function to bind to the event
  770. //
  771. // Return:
  772. // The previous event
  773. c.bind = function(event, f) {
  774. var old = events[event];
  775. events[event] = f;
  776. return old;
  777. };
  778. }(canvas));
  779. // Function: canvas.prepareSvg
  780. // Runs the SVG Document through the sanitizer and then updates its paths.
  781. //
  782. // Parameters:
  783. // newDoc - The SVG DOM document
  784. this.prepareSvg = function(newDoc) {
  785. this.sanitizeSvg(newDoc.documentElement);
  786. // convert paths into absolute commands
  787. var i, path, len,
  788. paths = newDoc.getElementsByTagNameNS(NS.SVG, 'path');
  789. for (i = 0, len = paths.length; i < len; ++i) {
  790. path = paths[i];
  791. path.setAttribute('d', pathActions.convertPath(path));
  792. pathActions.fixEnd(path);
  793. }
  794. };
  795. // Function: ffClone
  796. // Hack for Firefox bugs where text element features aren't updated or get
  797. // messed up. See issue 136 and issue 137.
  798. // This function clones the element and re-selects it
  799. // TODO: Test for this bug on load and add it to "support" object instead of
  800. // browser sniffing
  801. //
  802. // Parameters:
  803. // elem - The (text) DOM element to clone
  804. var ffClone = function(elem) {
  805. if (!svgedit.browser.isGecko()) {return elem;}
  806. var clone = elem.cloneNode(true);
  807. elem.parentNode.insertBefore(clone, elem);
  808. elem.parentNode.removeChild(elem);
  809. selectorManager.releaseSelector(elem);
  810. selectedElements[0] = clone;
  811. selectorManager.requestSelector(clone).showGrips(true);
  812. return clone;
  813. };
  814. // this.each is deprecated, if any extension used this it can be recreated by doing this:
  815. // $(canvas.getRootElem()).children().each(...)
  816. // this.each = function(cb) {
  817. // $(svgroot).children().each(cb);
  818. // };
  819. // Function: setRotationAngle
  820. // Removes any old rotations if present, prepends a new rotation at the
  821. // transformed center
  822. //
  823. // Parameters:
  824. // val - The new rotation angle in degrees
  825. // preventUndo - Boolean indicating whether the action should be undoable or not
  826. this.setRotationAngle = function(val, preventUndo) {
  827. // ensure val is the proper type
  828. val = parseFloat(val);
  829. var elem = selectedElements[0];
  830. var oldTransform = elem.getAttribute('transform');
  831. var bbox = svgedit.utilities.getBBox(elem);
  832. var cx = bbox.x+bbox.width/2, cy = bbox.y+bbox.height/2;
  833. var tlist = svgedit.transformlist.getTransformList(elem);
  834. // only remove the real rotational transform if present (i.e. at index=0)
  835. if (tlist.numberOfItems > 0) {
  836. var xform = tlist.getItem(0);
  837. if (xform.type == 4) {
  838. tlist.removeItem(0);
  839. }
  840. }
  841. // find R_nc and insert it
  842. if (val != 0) {
  843. var center = svgedit.math.transformPoint(cx, cy, svgedit.math.transformListToTransform(tlist).matrix);
  844. var R_nc = svgroot.createSVGTransform();
  845. R_nc.setRotate(val, center.x, center.y);
  846. if (tlist.numberOfItems) {
  847. tlist.insertItemBefore(R_nc, 0);
  848. } else {
  849. tlist.appendItem(R_nc);
  850. }
  851. } else if (tlist.numberOfItems == 0) {
  852. elem.removeAttribute('transform');
  853. }
  854. if (!preventUndo) {
  855. // we need to undo it, then redo it so it can be undo-able! :)
  856. // TODO: figure out how to make changes to transform list undo-able cross-browser?
  857. var newTransform = elem.getAttribute('transform');
  858. elem.setAttribute('transform', oldTransform);
  859. changeSelectedAttribute('transform', newTransform, selectedElements);
  860. call('changed', selectedElements);
  861. }
  862. var pointGripContainer = svgedit.utilities.getElem('pathpointgrip_container');
  863. // if (elem.nodeName == 'path' && pointGripContainer) {
  864. // pathActions.setPointContainerTransform(elem.getAttribute('transform'));
  865. // }
  866. var selector = selectorManager.requestSelector(selectedElements[0]);
  867. selector.resize();
  868. selector.updateGripCursors(val);
  869. };
  870. // Function: recalculateAllSelectedDimensions
  871. // Runs recalculateDimensions on the selected elements,
  872. // adding the changes to a single batch command
  873. var recalculateAllSelectedDimensions = this.recalculateAllSelectedDimensions = function() {
  874. var text = (current_resize_mode == 'none' ? 'position' : 'size');
  875. var batchCmd = new svgedit.history.BatchCommand(text);
  876. var i = selectedElements.length;
  877. while (i--) {
  878. var elem = selectedElements[i];
  879. // if (svgedit.utilities.getRotationAngle(elem) && !svgedit.math.hasMatrixTransform(getTransformList(elem))) {continue;}
  880. var cmd = svgedit.recalculate.recalculateDimensions(elem);
  881. if (cmd) {
  882. batchCmd.addSubCommand(cmd);
  883. }
  884. }
  885. if (!batchCmd.isEmpty()) {
  886. addCommandToHistory(batchCmd);
  887. call('changed', selectedElements);
  888. }
  889. };
  890. // this is how we map paths to our preferred relative segment types
  891. var pathMap = [0, 'z', 'M', 'm', 'L', 'l', 'C', 'c', 'Q', 'q', 'A', 'a',
  892. 'H', 'h', 'V', 'v', 'S', 's', 'T', 't'];
  893. // Debug tool to easily see the current matrix in the browser's console
  894. var logMatrix = function(m) {
  895. console.log([m.a, m.b, m.c, m.d, m.e, m.f]);
  896. };
  897. // Root Current Transformation Matrix in user units
  898. var root_sctm = null;
  899. // Group: Selection
  900. // Function: clearSelection
  901. // Clears the selection. The 'selected' handler is then called.
  902. // Parameters:
  903. // noCall - Optional boolean that when true does not call the "selected" handler
  904. var clearSelection = this.clearSelection = function(noCall) {
  905. if (selectedElements[0] != null) {
  906. var i, elem,
  907. len = selectedElements.length;
  908. for (i = 0; i < len; ++i) {
  909. elem = selectedElements[i];
  910. if (elem == null) {break;}
  911. selectorManager.releaseSelector(elem);
  912. selectedElements[i] = null;
  913. }
  914. // selectedBBoxes[0] = null;
  915. }
  916. if (!noCall) {call('selected', selectedElements);}
  917. };
  918. // TODO: do we need to worry about selectedBBoxes here?
  919. // Function: addToSelection
  920. // Adds a list of elements to the selection. The 'selected' handler is then called.
  921. //
  922. // Parameters:
  923. // elemsToAdd - an array of DOM elements to add to the selection
  924. // showGrips - a boolean flag indicating whether the resize grips should be shown
  925. var addToSelection = this.addToSelection = function(elemsToAdd, showGrips) {
  926. if (elemsToAdd.length == 0) { return; }
  927. // find the first null in our selectedElements array
  928. var j = 0;
  929. while (j < selectedElements.length) {
  930. if (selectedElements[j] == null) {
  931. break;
  932. }
  933. ++j;
  934. }
  935. // now add each element consecutively
  936. var i = elemsToAdd.length;
  937. while (i--) {
  938. var elem = elemsToAdd[i];
  939. if (!elem || !svgedit.utilities.getBBox(elem)) {continue;}
  940. if (elem.tagName === 'a' && elem.childNodes.length === 1) {
  941. // Make "a" element's child be the selected element
  942. elem = elem.firstChild;
  943. }
  944. // if it's not already there, add it
  945. if (selectedElements.indexOf(elem) == -1) {
  946. selectedElements[j] = elem;
  947. // only the first selectedBBoxes element is ever used in the codebase these days
  948. // if (j == 0) selectedBBoxes[0] = svgedit.utilities.getBBox(elem);
  949. j++;
  950. var sel = selectorManager.requestSelector(elem);
  951. if (selectedElements.length > 1) {
  952. sel.showGrips(false);
  953. }
  954. }
  955. }
  956. call('selected', selectedElements);
  957. if (showGrips || selectedElements.length == 1) {
  958. selectorManager.requestSelector(selectedElements[0]).showGrips(true);
  959. }
  960. else {
  961. selectorManager.requestSelector(selectedElements[0]).showGrips(false);
  962. }
  963. // make sure the elements are in the correct order
  964. // See: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition
  965. selectedElements.sort(function(a, b) {
  966. if (a && b && a.compareDocumentPosition) {
  967. return 3 - (b.compareDocumentPosition(a) & 6);
  968. }
  969. if (a == null) {
  970. return 1;
  971. }
  972. });
  973. // Make sure first elements are not null
  974. while (selectedElements[0] == null) {
  975. selectedElements.shift(0);
  976. }
  977. };
  978. // Function: selectOnly()
  979. // Selects only the given elements, shortcut for clearSelection(); addToSelection()
  980. //
  981. // Parameters:
  982. // elems - an array of DOM elements to be selected
  983. var selectOnly = this.selectOnly = function(elems, showGrips) {
  984. clearSelection(true);
  985. addToSelection(elems, showGrips);
  986. };
  987. // TODO: could use slice here to make this faster?
  988. // TODO: should the 'selected' handler
  989. // Function: removeFromSelection
  990. // Removes elements from the selection.
  991. //
  992. // Parameters:
  993. // elemsToRemove - an array of elements to remove from selection
  994. var removeFromSelection = this.removeFromSelection = function(elemsToRemove) {
  995. if (selectedElements[0] == null) { return; }
  996. if (elemsToRemove.length == 0) { return; }
  997. // find every element and remove it from our array copy
  998. var i,
  999. j = 0,
  1000. newSelectedItems = [],
  1001. len = selectedElements.length;
  1002. newSelectedItems.length = len;
  1003. for (i = 0; i < len; ++i) {
  1004. var elem = selectedElements[i];
  1005. if (elem) {
  1006. // keep the item
  1007. if (elemsToRemove.indexOf(elem) == -1) {
  1008. newSelectedItems[j] = elem;
  1009. j++;
  1010. } else { // remove the item and its selector
  1011. selectorManager.releaseSelector(elem);
  1012. }
  1013. }
  1014. }
  1015. // the copy becomes the master now
  1016. selectedElements = newSelectedItems;
  1017. };
  1018. // Function: selectAllInCurrentLayer
  1019. // Clears the selection, then adds all elements in the current layer to the selection.
  1020. this.selectAllInCurrentLayer = function() {
  1021. var current_layer = getCurrentDrawing().getCurrentLayer();
  1022. if (current_layer) {
  1023. current_mode = 'select';
  1024. selectOnly($(current_group || current_layer).children());
  1025. }
  1026. };
  1027. // Function: getMouseTarget
  1028. // Gets the desired element from a mouse event
  1029. //
  1030. // Parameters:
  1031. // evt - Event object from the mouse event
  1032. //
  1033. // Returns:
  1034. // DOM element we want
  1035. var getMouseTarget = this.getMouseTarget = function(evt) {
  1036. if (evt == null) {
  1037. return null;
  1038. }
  1039. var mouse_target = evt.target;
  1040. // if it was a <use>, Opera and WebKit return the SVGElementInstance
  1041. if (mouse_target.correspondingUseElement) {mouse_target = mouse_target.correspondingUseElement;}
  1042. // for foreign content, go up until we find the foreignObject
  1043. // WebKit browsers set the mouse target to the svgcanvas div
  1044. if ([NS.MATH, NS.HTML].indexOf(mouse_target.namespaceURI) >= 0 &&
  1045. mouse_target.id != 'svgcanvas')
  1046. {
  1047. while (mouse_target.nodeName != 'foreignObject') {
  1048. mouse_target = mouse_target.parentNode;
  1049. if (!mouse_target) {return svgroot;}
  1050. }
  1051. }
  1052. // Get the desired mouse_target with jQuery selector-fu
  1053. // If it's root-like, select the root
  1054. var current_layer = getCurrentDrawing().getCurrentLayer();
  1055. if ([svgroot, container, svgcontent, current_layer].indexOf(mouse_target) >= 0) {
  1056. return svgroot;
  1057. }
  1058. var $target = $(mouse_target);
  1059. // If it's a selection grip, return the grip parent
  1060. if ($target.closest('#selectorParentGroup').length) {
  1061. // While we could instead have just returned mouse_target,
  1062. // this makes it easier to indentify as being a selector grip
  1063. return selectorManager.selectorParentGroup;
  1064. }
  1065. while (mouse_target.parentNode !== (current_group || current_layer)) {
  1066. mouse_target = mouse_target.parentNode;
  1067. }
  1068. //
  1069. // // go up until we hit a child of a layer
  1070. // while (mouse_target.parentNode.parentNode.tagName == 'g') {
  1071. // mouse_target = mouse_target.parentNode;
  1072. // }
  1073. // Webkit bubbles the mouse event all the way up to the div, so we
  1074. // set the mouse_target to the svgroot like the other browsers
  1075. // if (mouse_target.nodeName.toLowerCase() == 'div') {
  1076. // mouse_target = svgroot;
  1077. // }
  1078. return mouse_target;
  1079. };
  1080. // Mouse events
  1081. (function() {
  1082. var d_attr = null,
  1083. start_x = null,
  1084. start_y = null,
  1085. r_start_x = null,
  1086. r_start_y = null,
  1087. init_bbox = {},
  1088. freehand = {
  1089. minx: null,
  1090. miny: null,
  1091. maxx: null,
  1092. maxy: null
  1093. },
  1094. sumDistance = 0,
  1095. controllPoint2 = {x:0, y:0},
  1096. controllPoint1 = {x:0, y:0},
  1097. start = {x:0, y:0},
  1098. end = {x:0, y:0},
  1099. parameter,
  1100. nextParameter,
  1101. bSpline = {x:0, y:0},
  1102. nextPos = {x:0, y:0},
  1103. THRESHOLD_DIST = 0.8,
  1104. STEP_COUNT = 10;
  1105. var getBsplinePoint = function(t) {
  1106. var spline = {x:0, y:0},
  1107. p0 = controllPoint2,
  1108. p1 = controllPoint1,
  1109. p2 = start,
  1110. p3 = end,
  1111. S = 1.0 / 6.0,
  1112. t2 = t * t,
  1113. t3 = t2 * t;
  1114. var m = [
  1115. [-1, 3, -3, 1],
  1116. [3, -6, 3, 0],
  1117. [-3, 0, 3, 0],
  1118. [1, 4, 1, 0]
  1119. ];
  1120. spline.x = S * (
  1121. (p0.x * m[0][0] + p1.x * m[0][1] + p2.x * m[0][2] + p3.x * m[0][3] ) * t3 +
  1122. (p0.x * m[1][0] + p1.x * m[1][1] + p2.x * m[1][2] + p3.x * m[1][3] ) * t2 +
  1123. (p0.x * m[2][0] + p1.x * m[2][1] + p2.x * m[2][2] + p3.x * m[2][3] ) * t +
  1124. (p0.x * m[3][0] + p1.x * m[3][1] + p2.x * m[3][2] + p3.x * m[3][3] )
  1125. );
  1126. spline.y = S * (
  1127. (p0.y * m[0][0] + p1.y * m[0][1] + p2.y * m[0][2] + p3.y * m[0][3] ) * t3 +
  1128. (p0.y * m[1][0] + p1.y * m[1][1] + p2.y * m[1][2] + p3.y * m[1][3] ) * t2 +
  1129. (p0.y * m[2][0] + p1.y * m[2][1] + p2.y * m[2][2] + p3.y * m[2][3] ) * t +
  1130. (p0.y * m[3][0] + p1.y * m[3][1] + p2.y * m[3][2] + p3.y * m[3][3] )
  1131. );
  1132. return {
  1133. x:spline.x,
  1134. y:spline.y
  1135. };
  1136. };
  1137. // - when we are in a create mode, the element is added to the canvas
  1138. // but the action is not recorded until mousing up
  1139. // - when we are in select mode, select the element, remember the position
  1140. // and do nothing else
  1141. var mouseDown = function(evt) {
  1142. if (canvas.spaceKey || evt.button === 1) {return;}
  1143. var right_click = evt.button === 2;
  1144. if (evt.altKey) { // duplicate when dragging
  1145. svgCanvas.cloneSelectedElements(0, 0);
  1146. }
  1147. root_sctm = $('#svgcontent g')[0].getScreenCTM().inverse();
  1148. var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ),
  1149. mouse_x = pt.x * current_zoom,
  1150. mouse_y = pt.y * current_zoom;
  1151. evt.preventDefault();
  1152. if (right_click) {
  1153. current_mode = 'select';
  1154. lastClickPoint = pt;
  1155. }
  1156. // This would seem to be unnecessary...
  1157. // if (['select', 'resize'].indexOf(current_mode) == -1) {
  1158. // setGradient();
  1159. // }
  1160. var x = mouse_x / current_zoom,
  1161. y = mouse_y / current_zoom,
  1162. mouse_target = getMouseTarget(evt);
  1163. if (mouse_target.tagName === 'a' && mouse_target.childNodes.length === 1) {
  1164. mouse_target = mouse_target.firstChild;
  1165. }
  1166. // real_x/y ignores grid-snap value
  1167. var real_x = x;
  1168. r_start_x = start_x = x;
  1169. var real_y = y;
  1170. r_start_y = start_y = y;
  1171. if (curConfig.gridSnapping){
  1172. x = svgedit.utilities.snapToGrid(x);
  1173. y = svgedit.utilities.snapToGrid(y);
  1174. start_x = svgedit.utilities.snapToGrid(start_x);
  1175. start_y = svgedit.utilities.snapToGrid(start_y);
  1176. }
  1177. // if it is a selector grip, then it must be a single element selected,
  1178. // set the mouse_target to that and update the mode to rotate/resize
  1179. if (mouse_target == selectorManager.selectorParentGroup && selectedElements[0] != null) {
  1180. var grip = evt.target;
  1181. var griptype = elData(grip, 'type');
  1182. // rotating
  1183. if (griptype == 'rotate') {
  1184. current_mode = 'rotate';
  1185. }
  1186. // resizing
  1187. else if (griptype == 'resize') {
  1188. current_mode = 'resize';
  1189. current_resize_mode = elData(grip, 'dir');
  1190. }
  1191. mouse_target = selectedElements[0];
  1192. }
  1193. startTransform = mouse_target.getAttribute('transform');
  1194. var i, stroke_w,
  1195. tlist = svgedit.transformlist.getTransformList(mouse_target);
  1196. switch (current_mode) {
  1197. case 'select':
  1198. started = true;
  1199. current_resize_mode = 'none';
  1200. if (right_click) {started = false;}
  1201. if (mouse_target != svgroot) {
  1202. // if this element is not yet selected, clear selection and select it
  1203. if (selectedElements.indexOf(mouse_target) == -1) {
  1204. // only clear selection if shift is not pressed (otherwise, add
  1205. // element to selection)
  1206. if (!evt.shiftKey) {
  1207. // No need to do the call here as it will be done on addToSelection
  1208. clearSelection(true);
  1209. }
  1210. addToSelection([mouse_target]);
  1211. justSelected = mouse_target;
  1212. pathActions.clear();
  1213. }
  1214. // else if it's a path, go into pathedit mode in mouseup
  1215. if (!right_click) {
  1216. // insert a dummy transform so if the element(s) are moved it will have
  1217. // a transform to use for its translate
  1218. for (i = 0; i < selectedElements.length; ++i) {
  1219. if (selectedElements[i] == null) {continue;}
  1220. var slist = svgedit.transformlist.getTransformList(selectedElements[i]);
  1221. if (slist.numberOfItems) {
  1222. slist.insertItemBefore(svgroot.createSVGTransform(), 0);
  1223. } else {
  1224. slist.appendItem(svgroot.createSVGTransform());
  1225. }
  1226. }
  1227. }
  1228. } else if (!right_click){
  1229. clearSelection();
  1230. current_mode = 'multiselect';
  1231. if (rubberBox == null) {
  1232. rubberBox = selectorManager.getRubberBandBox();
  1233. }
  1234. r_start_x *= current_zoom;
  1235. r_start_y *= current_zoom;
  1236. // console.log('p',[evt.pageX, evt.pageY]);
  1237. // console.log('c',[evt.clientX, evt.clientY]);
  1238. // console.log('o',[evt.offsetX, evt.offsetY]);
  1239. // console.log('s',[start_x, start_y]);
  1240. svgedit.utilities.assignAttributes(rubberBox, {
  1241. 'x': r_start_x,
  1242. 'y': r_start_y,
  1243. 'width': 0,
  1244. 'height': 0,
  1245. 'display': 'inline'
  1246. }, 100);
  1247. }
  1248. break;
  1249. case 'zoom':
  1250. started = true;
  1251. if (rubberBox == null) {
  1252. rubberBox = selectorManager.getRubberBandBox();
  1253. }
  1254. svgedit.utilities.assignAttributes(rubberBox, {
  1255. 'x': real_x * current_zoom,
  1256. 'y': real_x * current_zoom,
  1257. 'width': 0,
  1258. 'height': 0,
  1259. 'display': 'inline'
  1260. }, 100);
  1261. break;
  1262. case 'resize':
  1263. started = true;
  1264. start_x = x;
  1265. start_y = y;
  1266. // Getting the BBox from the selection box, since we know we
  1267. // want to orient around it
  1268. init_bbox = svgedit.utilities.getBBox($('#selectedBox0')[0]);
  1269. var bb = {};
  1270. $.each(init_bbox, function(key, val) {
  1271. bb[key] = val/current_zoom;
  1272. });
  1273. init_bbox = bb;
  1274. // append three dummy transforms to the tlist so that
  1275. // we can translate,scale,translate in mousemove
  1276. var pos = svgedit.utilities.getRotationAngle(mouse_target) ? 1 : 0;
  1277. if (svgedit.math.hasMatrixTransform(tlist)) {
  1278. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  1279. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  1280. tlist.insertItemBefore(svgroot.createSVGTransform(), pos);
  1281. } else {
  1282. tlist.appendItem(svgroot.createSVGTransform());
  1283. tlist.appendItem(svgroot.createSVGTransform());
  1284. tlist.appendItem(svgroot.createSVGTransform());
  1285. if (svgedit.browser.supportsNonScalingStroke()) {
  1286. // Handle crash for newer Chrome and Safari 6 (Mobile and Desktop):
  1287. // https://code.google.com/p/svg-edit/issues/detail?id=904
  1288. // Chromium issue: https://code.google.com/p/chromium/issues/detail?id=114625
  1289. // TODO: Remove this workaround once vendor fixes the issue
  1290. var isWebkit = svgedit.browser.isWebkit();
  1291. if (isWebkit) {
  1292. var delayedStroke = function(ele) {
  1293. var _stroke = ele.getAttributeNS(null, 'stroke');
  1294. ele.removeAttributeNS(null, 'stroke');
  1295. //Re-apply stroke after delay. Anything higher than 1 seems to cause flicker
  1296. setTimeout(function() { ele.setAttributeNS(null, 'stroke', _stroke); }, 0);
  1297. };
  1298. }
  1299. mouse_target.style.vectorEffect = 'non-scaling-stroke';
  1300. if (isWebkit) {delayedStroke(mouse_target);}
  1301. var all = mouse_target.getElementsByTagName('*'),
  1302. len = all.length;
  1303. for (i = 0; i < len; i++) {
  1304. all[i].style.vectorEffect = 'non-scaling-stroke';
  1305. if (isWebkit) {delayedStroke(all[i]);}
  1306. }
  1307. }
  1308. }
  1309. break;
  1310. case 'fhellipse':
  1311. case 'fhrect':
  1312. case 'fhpath':
  1313. start.x = real_x;
  1314. start.y = real_y;
  1315. started = true;
  1316. d_attr = real_x + ',' + real_y + ' ';
  1317. stroke_w = cur_shape.stroke_width == 0 ? 1 : cur_shape.stroke_width;
  1318. addSvgElementFromJson({
  1319. element: 'polyline',
  1320. curStyles: true,
  1321. attr: {
  1322. points: d_attr,
  1323. id: getNextId(),
  1324. fill: 'none',
  1325. opacity: cur_shape.opacity / 2,
  1326. 'stroke-linecap': 'round',
  1327. style: 'pointer-events:none'
  1328. }
  1329. });
  1330. freehand.minx = real_x;
  1331. freehand.maxx = real_x;
  1332. freehand.miny = real_y;
  1333. freehand.maxy = real_y;
  1334. break;
  1335. case 'image':
  1336. started = true;
  1337. var newImage = addSvgElementFromJson({
  1338. element: 'image',
  1339. attr: {
  1340. x: x,
  1341. y: y,
  1342. width: 0,
  1343. height: 0,
  1344. id: getNextId(),
  1345. opacity: cur_shape.opacity / 2,
  1346. style: 'pointer-events:inherit'
  1347. }
  1348. });
  1349. setHref(newImage, last_good_img_url);
  1350. preventClickDefault(newImage);
  1351. break;
  1352. case 'square':
  1353. // FIXME: once we create the rect, we lose information that this was a square
  1354. // (for resizing purposes this could be important)
  1355. case 'rect':
  1356. started = true;
  1357. start_x = x;
  1358. start_y = y;
  1359. addSvgElementFromJson({
  1360. element: 'rect',
  1361. curStyles: true,
  1362. attr: {
  1363. x: x,
  1364. y: y,
  1365. width: 0,
  1366. height: 0,
  1367. id: getNextId(),
  1368. opacity: cur_shape.opacity / 2
  1369. }
  1370. });
  1371. break;
  1372. case 'line':
  1373. started = true;
  1374. stroke_w = cur_shape.stroke_width == 0 ? 1 : cur_shape.stroke_width;
  1375. addSvgElementFromJson({
  1376. element: 'line',
  1377. curStyles: true,
  1378. attr: {
  1379. x1: x,
  1380. y1: y,
  1381. x2: x,
  1382. y2: y,
  1383. id: getNextId(),
  1384. stroke: cur_shape.stroke,
  1385. 'stroke-width': stroke_w,
  1386. 'stroke-dasharray': cur_shape.stroke_dasharray,
  1387. 'stroke-linejoin': cur_shape.stroke_linejoin,
  1388. 'stroke-linecap': cur_shape.stroke_linecap,
  1389. 'stroke-opacity': cur_shape.stroke_opacity,
  1390. fill: 'none',
  1391. opacity: cur_shape.opacity / 2,
  1392. style: 'pointer-events:none'
  1393. }
  1394. });
  1395. break;
  1396. case 'circle':
  1397. started = true;
  1398. addSvgElementFromJson({
  1399. element: 'circle',
  1400. curStyles: true,
  1401. attr: {
  1402. cx: x,
  1403. cy: y,
  1404. r: 0,
  1405. id: getNextId(),
  1406. opacity: cur_shape.opacity / 2
  1407. }
  1408. });
  1409. break;
  1410. case 'ellipse':
  1411. started = true;
  1412. addSvgElementFromJson({
  1413. element: 'ellipse',
  1414. curStyles: true,
  1415. attr: {
  1416. cx: x,
  1417. cy: y,
  1418. rx: 0,
  1419. ry: 0,
  1420. id: getNextId(),
  1421. opacity: cur_shape.opacity / 2
  1422. }
  1423. });
  1424. break;
  1425. case 'text':
  1426. started = true;
  1427. var newText = addSvgElementFromJson({
  1428. element: 'text',
  1429. curStyles: true,
  1430. attr: {
  1431. x: x,
  1432. y: y,
  1433. id: getNextId(),
  1434. fill: cur_text.fill,
  1435. 'stroke-width': cur_text.stroke_width,
  1436. 'font-size': cur_text.font_size,
  1437. 'font-family': cur_text.font_family,
  1438. 'text-anchor': 'middle',
  1439. 'xml:space': 'preserve',
  1440. opacity: cur_shape.opacity
  1441. }
  1442. });
  1443. // newText.textContent = 'text';
  1444. break;
  1445. case 'path':
  1446. // Fall through
  1447. case 'pathedit':
  1448. start_x *= current_zoom;
  1449. start_y *= current_zoom;
  1450. pathActions.mouseDown(evt, mouse_target, start_x, start_y);
  1451. started = true;
  1452. break;
  1453. case 'textedit':
  1454. start_x *= current_zoom;
  1455. start_y *= current_zoom;
  1456. textActions.mouseDown(evt, mouse_target, start_x, start_y);
  1457. started = true;
  1458. break;
  1459. case 'rotate':
  1460. started = true;
  1461. // we are starting an undoable change (a drag-rotation)
  1462. canvas.undoMgr.beginUndoableChange('transform', selectedElements);
  1463. break;
  1464. default:
  1465. // This could occur in an extension
  1466. break;
  1467. }
  1468. var ext_result = runExtensions('mouseDown', {
  1469. event: evt,
  1470. start_x: start_x,
  1471. start_y: start_y,
  1472. selectedElements: selectedElements
  1473. }, true);
  1474. $.each(ext_result, function(i, r) {
  1475. if (r && r.started) {
  1476. started = true;
  1477. }
  1478. });
  1479. };
  1480. // in this function we do not record any state changes yet (but we do update
  1481. // any elements that are still being created, moved or resized on the canvas)
  1482. var mouseMove = function(evt) {
  1483. if (!started) {return;}
  1484. if (evt.button === 1 || canvas.spaceKey) {return;}
  1485. var i, xya, c, cx, cy, dx, dy, len, angle, box,
  1486. selected = selectedElements[0],
  1487. pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ),
  1488. mouse_x = pt.x * current_zoom,
  1489. mouse_y = pt.y * current_zoom,
  1490. shape = svgedit.utilities.getElem(getId());
  1491. var real_x = mouse_x / current_zoom;
  1492. x = real_x;
  1493. var real_y = mouse_y / current_zoom;
  1494. y = real_y;
  1495. if (curConfig.gridSnapping){
  1496. x = svgedit.utilities.snapToGrid(x);
  1497. y = svgedit.utilities.snapToGrid(y);
  1498. }
  1499. evt.preventDefault();
  1500. var tlist;
  1501. switch (current_mode) {
  1502. case 'select':
  1503. // we temporarily use a translate on the element(s) being dragged
  1504. // this transform is removed upon mousing up and the element is
  1505. // relocated to the new location
  1506. if (selectedElements[0] !== null) {
  1507. dx = x - start_x;
  1508. dy = y - start_y;
  1509. if (curConfig.gridSnapping){
  1510. dx = svgedit.utilities.snapToGrid(dx);
  1511. dy = svgedit.utilities.snapToGrid(dy);
  1512. }
  1513. if (evt.shiftKey) {
  1514. xya = svgedit.math.snapToAngle(start_x, start_y, x, y);
  1515. x = xya.x;
  1516. y = xya.y;
  1517. }
  1518. if (dx != 0 || dy != 0) {
  1519. len = selectedElements.length;
  1520. for (i = 0; i < len; ++i) {
  1521. selected = selectedElements[i];
  1522. if (selected == null) {break;}
  1523. // if (i==0) {
  1524. // var box = svgedit.utilities.getBBox(selected);
  1525. // selectedBBoxes[i].x = box.x + dx;
  1526. // selectedBBoxes[i].y = box.y + dy;
  1527. // }
  1528. // update the dummy transform in our transform list
  1529. // to be a translate
  1530. var xform = svgroot.createSVGTransform();
  1531. tlist = svgedit.transformlist.getTransformList(selected);
  1532. // Note that if Webkit and there's no ID for this
  1533. // element, the dummy transform may have gotten lost.
  1534. // This results in unexpected behaviour
  1535. xform.setTranslate(dx, dy);
  1536. if (tlist.numberOfItems) {
  1537. tlist.replaceItem(xform, 0);
  1538. } else {
  1539. tlist.appendItem(xform);
  1540. }
  1541. // update our internal bbox that we're tracking while dragging
  1542. selectorManager.requestSelector(selected).resize();
  1543. }
  1544. call('transition', selectedElements);
  1545. }
  1546. }
  1547. break;
  1548. case 'multiselect':
  1549. real_x *= current_zoom;
  1550. real_y *= current_zoom;
  1551. svgedit.utilities.assignAttributes(rubberBox, {
  1552. 'x': Math.min(r_start_x, real_x),
  1553. 'y': Math.min(r_start_y, real_y),
  1554. 'width': Math.abs(real_x - r_start_x),
  1555. 'height': Math.abs(real_y - r_start_y)
  1556. }, 100);
  1557. // for each selected:
  1558. // - if newList contains selected, do nothing
  1559. // - if newList doesn't contain selected, remove it from selected
  1560. // - for any newList that was not in selectedElements, add it to selected
  1561. var elemsToRemove = selectedElements.slice(), elemsToAdd = [],
  1562. newList = getIntersectionList();
  1563. // For every element in the intersection, add if not present in selectedElements.
  1564. len = newList.length;
  1565. for (i = 0; i < len; ++i) {
  1566. var intElem = newList[i];
  1567. // Found an element that was not selected before, so we should add it.
  1568. if (selectedElements.indexOf(intElem) == -1) {
  1569. elemsToAdd.push(intElem);
  1570. }
  1571. // Found an element that was already selected, so we shouldn't remove it.
  1572. var foundInd = elemsToRemove.indexOf(intElem);
  1573. if (foundInd != -1) {
  1574. elemsToRemove.splice(foundInd, 1)
  1575. }
  1576. }
  1577. if (elemsToRemove.length > 0) {
  1578. canvas.removeFromSelection(elemsToRemove);
  1579. }
  1580. if (elemsToAdd.length > 0) {
  1581. canvas.addToSelection(elemsToAdd);
  1582. }
  1583. break;
  1584. case 'resize':
  1585. // we track the resize bounding box and translate/scale the selected element
  1586. // while the mouse is down, when mouse goes up, we use this to recalculate
  1587. // the shape's coordinates
  1588. tlist = svgedit.transformlist.getTransformList(selected);
  1589. var hasMatrix = svgedit.math.hasMatrixTransform(tlist);
  1590. box = hasMatrix ? init_bbox : svgedit.utilities.getBBox(selected);
  1591. var left = box.x, top = box.y, width = box.width,
  1592. height = box.height;
  1593. dx = (x-start_x);
  1594. dy = (y-start_y);
  1595. if (curConfig.gridSnapping) {
  1596. dx = svgedit.utilities.snapToGrid(dx);
  1597. dy = svgedit.utilities.snapToGrid(dy);
  1598. height = svgedit.utilities.snapToGrid(height);
  1599. width = svgedit.utilities.snapToGrid(width);
  1600. }
  1601. // if rotated, adjust the dx,dy values
  1602. angle = svgedit.utilities.getRotationAngle(selected);
  1603. if (angle) {
  1604. var r = Math.sqrt( dx*dx + dy*dy ),
  1605. theta = Math.atan2(dy, dx) - angle * Math.PI / 180.0;
  1606. dx = r * Math.cos(theta);
  1607. dy = r * Math.sin(theta);
  1608. }
  1609. // if not stretching in y direction, set dy to 0
  1610. // if not stretching in x direction, set dx to 0
  1611. if (current_resize_mode.indexOf('n')==-1 && current_resize_mode.indexOf('s')==-1) {
  1612. dy = 0;
  1613. }
  1614. if (current_resize_mode.indexOf('e')==-1 && current_resize_mode.indexOf('w')==-1) {
  1615. dx = 0;
  1616. }
  1617. var ts = null,
  1618. tx = 0, ty = 0,
  1619. sy = height ? (height+dy)/height : 1,
  1620. sx = width ? (width+dx)/width : 1;
  1621. // if we are dragging on the north side, then adjust the scale factor and ty
  1622. if (current_resize_mode.indexOf('n') >= 0) {
  1623. sy = height ? (height-dy)/height : 1;
  1624. ty = height;
  1625. }
  1626. // if we dragging on the east side, then adjust the scale factor and tx
  1627. if (current_resize_mode.indexOf('w') >= 0) {
  1628. sx = width ? (width-dx)/width : 1;
  1629. tx = width;
  1630. }
  1631. // update the transform list with translate,scale,translate
  1632. var translateOrigin = svgroot.createSVGTransform(),
  1633. scale = svgroot.createSVGTransform(),
  1634. translateBack = svgroot.createSVGTransform();
  1635. if (curConfig.gridSnapping) {
  1636. left = svgedit.utilities.snapToGrid(left);
  1637. tx = svgedit.utilities.snapToGrid(tx);
  1638. top = svgedit.utilities.snapToGrid(top);
  1639. ty = svgedit.utilities.snapToGrid(ty);
  1640. }
  1641. translateOrigin.setTranslate(-(left+tx), -(top+ty));
  1642. if (evt.shiftKey) {
  1643. if (sx == 1) {sx = sy;}
  1644. else {sy = sx;}
  1645. }
  1646. scale.setScale(sx, sy);
  1647. translateBack.setTranslate(left+tx, top+ty);
  1648. if (hasMatrix) {
  1649. var diff = angle ? 1 : 0;
  1650. tlist.replaceItem(translateOrigin, 2+diff);
  1651. tlist.replaceItem(scale, 1+diff);
  1652. tlist.replaceItem(translateBack, Number(diff));
  1653. } else {
  1654. var N = tlist.numberOfItems;
  1655. tlist.replaceItem(translateBack, N-3);
  1656. tlist.replaceItem(scale, N-2);
  1657. tlist.replaceItem(translateOrigin, N-1);
  1658. }
  1659. selectorManager.requestSelector(selected).resize();
  1660. call('transition', selectedElements);
  1661. break;
  1662. case 'zoom':
  1663. real_x *= current_zoom;
  1664. real_y *= current_zoom;
  1665. svgedit.utilities.assignAttributes(rubberBox, {
  1666. 'x': Math.min(r_start_x*current_zoom, real_x),
  1667. 'y': Math.min(r_start_y*current_zoom, real_y),
  1668. 'width': Math.abs(real_x - r_start_x*current_zoom),
  1669. 'height': Math.abs(real_y - r_start_y*current_zoom)
  1670. }, 100);
  1671. break;
  1672. case 'text':
  1673. svgedit.utilities.assignAttributes(shape,{
  1674. 'x': x,
  1675. 'y': y
  1676. }, 1000);
  1677. break;
  1678. case 'line':
  1679. if (curConfig.gridSnapping) {
  1680. x = svgedit.utilities.snapToGrid(x);
  1681. y = svgedit.utilities.snapToGrid(y);
  1682. }
  1683. var x2 = x;
  1684. var y2 = y;
  1685. if (evt.shiftKey) {
  1686. xya = svgedit.math.snapToAngle(start_x, start_y, x2, y2);
  1687. x2 = xya.x;
  1688. y2 = xya.y;
  1689. }
  1690. shape.setAttributeNS(null, 'x2', x2);
  1691. shape.setAttributeNS(null, 'y2', y2);
  1692. break;
  1693. case 'foreignObject':
  1694. // fall through
  1695. case 'square':
  1696. // fall through
  1697. case 'rect':
  1698. // fall through
  1699. case 'image':
  1700. var square = (current_mode == 'square') || evt.shiftKey,
  1701. w = Math.abs(x - start_x),
  1702. h = Math.abs(y - start_y),
  1703. new_x, new_y;
  1704. if (square) {
  1705. w = h = Math.max(w, h);
  1706. new_x = start_x < x ? start_x : start_x - w;
  1707. new_y = start_y < y ? start_y : start_y - h;
  1708. } else {
  1709. new_x = Math.min(start_x, x);
  1710. new_y = Math.min(start_y, y);
  1711. }
  1712. if (curConfig.gridSnapping) {
  1713. w = svgedit.utilities.snapToGrid(w);
  1714. h = svgedit.utilities.snapToGrid(h);
  1715. new_x = svgedit.utilities.snapToGrid(new_x);
  1716. new_y = svgedit.utilities.snapToGrid(new_y);
  1717. }
  1718. svgedit.utilities.assignAttributes(shape,{
  1719. 'width': w,
  1720. 'height': h,
  1721. 'x': new_x,
  1722. 'y': new_y
  1723. },1000);
  1724. break;
  1725. case 'circle':
  1726. c = $(shape).attr(['cx', 'cy']);
  1727. cx = c.cx;
  1728. cy = c.cy;
  1729. var rad = Math.sqrt( (x-cx)*(x-cx) + (y-cy)*(y-cy) );
  1730. if (curConfig.gridSnapping) {
  1731. rad = svgedit.utilities.snapToGrid(rad);
  1732. }
  1733. shape.setAttributeNS(null, 'r', rad);
  1734. break;
  1735. case 'ellipse':
  1736. c = $(shape).attr(['cx', 'cy']);
  1737. cx = c.cx;
  1738. cy = c.cy;
  1739. if (curConfig.gridSnapping) {
  1740. x = svgedit.utilities.snapToGrid(x);
  1741. cx = svgedit.utilities.snapToGrid(cx);
  1742. y = svgedit.utilities.snapToGrid(y);
  1743. cy = svgedit.utilities.snapToGrid(cy);
  1744. }
  1745. shape.setAttributeNS(null, 'rx', Math.abs(x - cx) );
  1746. var ry = Math.abs(evt.shiftKey?(x - cx):(y - cy));
  1747. shape.setAttributeNS(null, 'ry', ry );
  1748. break;
  1749. case 'fhellipse':
  1750. case 'fhrect':
  1751. freehand.minx = Math.min(real_x, freehand.minx);
  1752. freehand.maxx = Math.max(real_x, freehand.maxx);
  1753. freehand.miny = Math.min(real_y, freehand.miny);
  1754. freehand.maxy = Math.max(real_y, freehand.maxy);
  1755. // break; missing on purpose
  1756. case 'fhpath':
  1757. // d_attr += + real_x + ',' + real_y + ' ';
  1758. // shape.setAttributeNS(null, 'points', d_attr);
  1759. end.x = real_x; end.y = real_y;
  1760. if (controllPoint2.x && controllPoint2.y) {
  1761. for (i = 0; i < STEP_COUNT - 1; i++) {
  1762. parameter = i / STEP_COUNT;
  1763. nextParameter = (i + 1) / STEP_COUNT;
  1764. bSpline = getBsplinePoint(nextParameter);
  1765. nextPos = bSpline;
  1766. bSpline = getBsplinePoint(parameter);
  1767. sumDistance += Math.sqrt((nextPos.x - bSpline.x) * (nextPos.x - bSpline.x) + (nextPos.y - bSpline.y) * (nextPos.y - bSpline.y));
  1768. if (sumDistance > THRESHOLD_DIST) {
  1769. d_attr += + bSpline.x + ',' + bSpline.y + ' ';
  1770. shape.setAttributeNS(null, 'points', d_attr);
  1771. sumDistance -= THRESHOLD_DIST;
  1772. }
  1773. }
  1774. }
  1775. controllPoint2 = {x:controllPoint1.x, y:controllPoint1.y};
  1776. controllPoint1 = {x:start.x, y:start.y};
  1777. start = {x:end.x, y:end.y};
  1778. break;
  1779. // update path stretch line coordinates
  1780. case 'path':
  1781. // fall through
  1782. case 'pathedit':
  1783. x *= current_zoom;
  1784. y *= current_zoom;
  1785. if (curConfig.gridSnapping) {
  1786. x = svgedit.utilities.snapToGrid(x);
  1787. y = svgedit.utilities.snapToGrid(y);
  1788. start_x = svgedit.utilities.snapToGrid(start_x);
  1789. start_y = svgedit.utilities.snapToGrid(start_y);
  1790. }
  1791. if (evt.shiftKey) {
  1792. var path = svgedit.path.path;
  1793. var x1, y1;
  1794. if (path) {
  1795. x1 = path.dragging?path.dragging[0]:start_x;
  1796. y1 = path.dragging?path.dragging[1]:start_y;
  1797. } else {
  1798. x1 = start_x;
  1799. y1 = start_y;
  1800. }
  1801. xya = svgedit.math.snapToAngle(x1, y1, x, y);
  1802. x = xya.x;
  1803. y = xya.y;
  1804. }
  1805. if (rubberBox && rubberBox.getAttribute('display') !== 'none') {
  1806. real_x *= current_zoom;
  1807. real_y *= current_zoom;
  1808. svgedit.utilities.assignAttributes(rubberBox, {
  1809. 'x': Math.min(r_start_x*current_zoom, real_x),
  1810. 'y': Math.min(r_start_y*current_zoom, real_y),
  1811. 'width': Math.abs(real_x - r_start_x*current_zoom),
  1812. 'height': Math.abs(real_y - r_start_y*current_zoom)
  1813. },100);
  1814. }
  1815. pathActions.mouseMove(x, y);
  1816. break;
  1817. case 'textedit':
  1818. x *= current_zoom;
  1819. y *= current_zoom;
  1820. // if (rubberBox && rubberBox.getAttribute('display') != 'none') {
  1821. // svgedit.utilities.assignAttributes(rubberBox, {
  1822. // 'x': Math.min(start_x,x),
  1823. // 'y': Math.min(start_y,y),
  1824. // 'width': Math.abs(x-start_x),
  1825. // 'height': Math.abs(y-start_y)
  1826. // },100);
  1827. // }
  1828. textActions.mouseMove(mouse_x, mouse_y);
  1829. break;
  1830. case 'rotate':
  1831. box = svgedit.utilities.getBBox(selected);
  1832. cx = box.x + box.width/2;
  1833. cy = box.y + box.height/2;
  1834. var m = svgedit.math.getMatrix(selected),
  1835. center = svgedit.math.transformPoint(cx, cy, m);
  1836. cx = center.x;
  1837. cy = center.y;
  1838. angle = ((Math.atan2(cy-y, cx-x) * (180/Math.PI))-90) % 360;
  1839. if (curConfig.gridSnapping) {
  1840. angle = svgedit.utilities.snapToGrid(angle);
  1841. }
  1842. if (evt.shiftKey) { // restrict rotations to nice angles (WRS)
  1843. var snap = 45;
  1844. angle= Math.round(angle/snap)*snap;
  1845. }
  1846. canvas.setRotationAngle(angle<-180?(360+angle):angle, true);
  1847. call('transition', selectedElements);
  1848. break;
  1849. default:
  1850. break;
  1851. }
  1852. runExtensions('mouseMove', {
  1853. event: evt,
  1854. mouse_x: mouse_x,
  1855. mouse_y: mouse_y,
  1856. selected: selected
  1857. });
  1858. }; // mouseMove()
  1859. // - in create mode, the element's opacity is set properly, we create an InsertElementCommand
  1860. // and store it on the Undo stack
  1861. // - in move/resize mode, the element's attributes which were affected by the move/resize are
  1862. // identified, a ChangeElementCommand is created and stored on the stack for those attrs
  1863. // this is done in when we recalculate the selected dimensions()
  1864. var mouseUp = function(evt) {
  1865. if (evt.button === 2) {return;}
  1866. var tempJustSelected = justSelected;
  1867. justSelected = null;
  1868. if (!started) {return;}
  1869. var pt = svgedit.math.transformPoint(evt.pageX, evt.pageY, root_sctm),
  1870. mouse_x = pt.x * current_zoom,
  1871. mouse_y = pt.y * current_zoom,
  1872. x = mouse_x / current_zoom,
  1873. y = mouse_y / current_zoom,
  1874. element = svgedit.utilities.getElem(getId()),
  1875. keep = false;
  1876. var real_x = x;
  1877. var real_y = y;
  1878. // TODO: Make true when in multi-unit mode
  1879. var useUnit = false; // (curConfig.baseUnit !== 'px');
  1880. started = false;
  1881. var attrs, t;
  1882. switch (current_mode) {
  1883. // intentionally fall-through to select here
  1884. case 'resize':
  1885. case 'multiselect':
  1886. if (rubberBox != null) {
  1887. rubberBox.setAttribute('display', 'none');
  1888. curBBoxes = [];
  1889. }
  1890. current_mode = 'select';
  1891. case 'select':
  1892. if (selectedElements[0] != null) {
  1893. // if we only have one selected element
  1894. if (selectedElements[1] == null) {
  1895. // set our current stroke/fill properties to the element's
  1896. var selected = selectedElements[0];
  1897. switch ( selected.tagName ) {
  1898. case 'g':
  1899. case 'use':
  1900. case 'image':
  1901. case 'foreignObject':
  1902. break;
  1903. default:
  1904. cur_properties.fill = selected.getAttribute('fill');
  1905. cur_properties.fill_opacity = selected.getAttribute('fill-opacity');
  1906. cur_properties.stroke = selected.getAttribute('stroke');
  1907. cur_properties.stroke_opacity = selected.getAttribute('stroke-opacity');
  1908. cur_properties.stroke_width = selected.getAttribute('stroke-width');
  1909. cur_properties.stroke_dasharray = selected.getAttribute('stroke-dasharray');
  1910. cur_properties.stroke_linejoin = selected.getAttribute('stroke-linejoin');
  1911. cur_properties.stroke_linecap = selected.getAttribute('stroke-linecap');
  1912. }
  1913. if (selected.tagName == 'text') {
  1914. cur_text.font_size = selected.getAttribute('font-size');
  1915. cur_text.font_family = selected.getAttribute('font-family');
  1916. }
  1917. selectorManager.requestSelector(selected).showGrips(true);
  1918. // This shouldn't be necessary as it was done on mouseDown...
  1919. // call('selected', [selected]);
  1920. }
  1921. // always recalculate dimensions to strip off stray identity transforms
  1922. recalculateAllSelectedDimensions();
  1923. // if it was being dragged/resized
  1924. if (real_x != r_start_x || real_y != r_start_y) {
  1925. var i, len = selectedElements.length;
  1926. for (i = 0; i < len; ++i) {
  1927. if (selectedElements[i] == null) {break;}
  1928. if (!selectedElements[i].firstChild) {
  1929. // Not needed for groups (incorrectly resizes elems), possibly not needed at all?
  1930. selectorManager.requestSelector(selectedElements[i]).resize();
  1931. }
  1932. }
  1933. }
  1934. // no change in position/size, so maybe we should move to pathedit
  1935. else {
  1936. t = evt.target;
  1937. if (selectedElements[0].nodeName === 'path' && selectedElements[1] == null) {
  1938. pathActions.select(selectedElements[0]);
  1939. } // if it was a path
  1940. // else, if it was selected and this is a shift-click, remove it from selection
  1941. else if (evt.shiftKey) {
  1942. if (tempJustSelected != t) {
  1943. canvas.removeFromSelection([t]);
  1944. }
  1945. }
  1946. } // no change in mouse position
  1947. // Remove non-scaling stroke
  1948. if (svgedit.browser.supportsNonScalingStroke()) {
  1949. var elem = selectedElements[0];
  1950. if (elem) {
  1951. elem.removeAttribute('style');
  1952. svgedit.utilities.walkTree(elem, function(elem) {
  1953. elem.removeAttribute('style');
  1954. });
  1955. }
  1956. }
  1957. }
  1958. return;
  1959. case 'zoom':
  1960. if (rubberBox != null) {
  1961. rubberBox.setAttribute('display', 'none');
  1962. }
  1963. var factor = evt.shiftKey ? 0.5 : 2;
  1964. call('zoomed', {
  1965. 'x': Math.min(r_start_x, real_x),
  1966. 'y': Math.min(r_start_y, real_y),
  1967. 'width': Math.abs(real_x - r_start_x),
  1968. 'height': Math.abs(real_y - r_start_y),
  1969. 'factor': factor
  1970. });
  1971. return;
  1972. case 'fhpath':
  1973. // Check that the path contains at least 2 points; a degenerate one-point path
  1974. // causes problems.
  1975. // Webkit ignores how we set the points attribute with commas and uses space
  1976. // to separate all coordinates, see https://bugs.webkit.org/show_bug.cgi?id=29870
  1977. sumDistance = 0;
  1978. controllPoint2 = {x:0, y:0};
  1979. controllPoint1 = {x:0, y:0};
  1980. start = {x:0, y:0};
  1981. end = {x:0, y:0};
  1982. var coords = element.getAttribute('points');
  1983. var commaIndex = coords.indexOf(',');
  1984. if (commaIndex >= 0) {
  1985. keep = coords.indexOf(',', commaIndex+1) >= 0;
  1986. } else {
  1987. keep = coords.indexOf(' ', coords.indexOf(' ')+1) >= 0;
  1988. }
  1989. if (keep) {
  1990. element = pathActions.smoothPolylineIntoPath(element);
  1991. }
  1992. break;
  1993. case 'line':
  1994. attrs = $(element).attr(['x1', 'x2', 'y1', 'y2']);
  1995. keep = (attrs.x1 != attrs.x2 || attrs.y1 != attrs.y2);
  1996. break;
  1997. case 'foreignObject':
  1998. case 'square':
  1999. case 'rect':
  2000. case 'image':
  2001. attrs = $(element).attr(['width', 'height']);
  2002. // Image should be kept regardless of size (use inherit dimensions later)
  2003. keep = (attrs.width != 0 || attrs.height != 0) || current_mode === 'image';
  2004. break;
  2005. case 'circle':
  2006. keep = (element.getAttribute('r') != 0);
  2007. break;
  2008. case 'ellipse':
  2009. attrs = $(element).attr(['rx', 'ry']);
  2010. keep = (attrs.rx != null || attrs.ry != null);
  2011. break;
  2012. case 'fhellipse':
  2013. if ((freehand.maxx - freehand.minx) > 0 &&
  2014. (freehand.maxy - freehand.miny) > 0) {
  2015. element = addSvgElementFromJson({
  2016. element: 'ellipse',
  2017. curStyles: true,
  2018. attr: {
  2019. cx: (freehand.minx + freehand.maxx) / 2,
  2020. cy: (freehand.miny + freehand.maxy) / 2,
  2021. rx: (freehand.maxx - freehand.minx) / 2,
  2022. ry: (freehand.maxy - freehand.miny) / 2,
  2023. id: getId()
  2024. }
  2025. });
  2026. call('changed',[element]);
  2027. keep = true;
  2028. }
  2029. break;
  2030. case 'fhrect':
  2031. if ((freehand.maxx - freehand.minx) > 0 &&
  2032. (freehand.maxy - freehand.miny) > 0) {
  2033. element = addSvgElementFromJson({
  2034. element: 'rect',
  2035. curStyles: true,
  2036. attr: {
  2037. x: freehand.minx,
  2038. y: freehand.miny,
  2039. width: (freehand.maxx - freehand.minx),
  2040. height: (freehand.maxy - freehand.miny),
  2041. id: getId()
  2042. }
  2043. });
  2044. call('changed',[element]);
  2045. keep = true;
  2046. }
  2047. break;
  2048. case 'text':
  2049. keep = true;
  2050. selectOnly([element]);
  2051. textActions.start(element);
  2052. break;
  2053. case 'path':
  2054. // set element to null here so that it is not removed nor finalized
  2055. element = null;
  2056. // continue to be set to true so that mouseMove happens
  2057. started = true;
  2058. var res = pathActions.mouseUp(evt, element, mouse_x, mouse_y);
  2059. element = res.element;
  2060. keep = res.keep;
  2061. break;
  2062. case 'pathedit':
  2063. keep = true;
  2064. element = null;
  2065. pathActions.mouseUp(evt);
  2066. break;
  2067. case 'textedit':
  2068. keep = false;
  2069. element = null;
  2070. textActions.mouseUp(evt, mouse_x, mouse_y);
  2071. break;
  2072. case 'rotate':
  2073. keep = true;
  2074. element = null;
  2075. current_mode = 'select';
  2076. var batchCmd = canvas.undoMgr.finishUndoableChange();
  2077. if (!batchCmd.isEmpty()) {
  2078. addCommandToHistory(batchCmd);
  2079. }
  2080. // perform recalculation to weed out any stray identity transforms that might get stuck
  2081. recalculateAllSelectedDimensions();
  2082. call('changed', selectedElements);
  2083. break;
  2084. default:
  2085. // This could occur in an extension
  2086. break;
  2087. }
  2088. var ext_result = runExtensions('mouseUp', {
  2089. event: evt,
  2090. mouse_x: mouse_x,
  2091. mouse_y: mouse_y
  2092. }, true);
  2093. $.each(ext_result, function(i, r) {
  2094. if (r) {
  2095. keep = r.keep || keep;
  2096. element = r.element;
  2097. started = r.started || started;
  2098. }
  2099. });
  2100. if (!keep && element != null) {
  2101. getCurrentDrawing().releaseId(getId());
  2102. element.parentNode.removeChild(element);
  2103. element = null;
  2104. t = evt.target;
  2105. // if this element is in a group, go up until we reach the top-level group
  2106. // just below the layer groups
  2107. // TODO: once we implement links, we also would have to check for <a> elements
  2108. while (t.parentNode.parentNode.tagName == 'g') {
  2109. t = t.parentNode;
  2110. }
  2111. // if we are not in the middle of creating a path, and we've clicked on some shape,
  2112. // then go to Select mode.
  2113. // WebKit returns <div> when the canvas is clicked, Firefox/Opera return <svg>
  2114. if ( (current_mode != 'path' || !drawn_path) &&
  2115. t.parentNode.id != 'selectorParentGroup' &&
  2116. t.id != 'svgcanvas' && t.id != 'svgroot')
  2117. {
  2118. // switch into "select" mode if we've clicked on an element
  2119. canvas.setMode('select');
  2120. selectOnly([t], true);
  2121. }
  2122. } else if (element != null) {
  2123. canvas.addedNew = true;
  2124. if (useUnit) {svgedit.units.convertAttrs(element);}
  2125. var ani_dur = 0.2, c_ani;
  2126. if (opac_ani.beginElement && element.getAttribute('opacity') != cur_shape.opacity) {
  2127. c_ani = $(opac_ani).clone().attr({
  2128. to: cur_shape.opacity,
  2129. dur: ani_dur
  2130. }).appendTo(element);
  2131. try {
  2132. // Fails in FF4 on foreignObject
  2133. c_ani[0].beginElement();
  2134. } catch(e){}
  2135. } else {
  2136. ani_dur = 0;
  2137. }
  2138. // Ideally this would be done on the endEvent of the animation,
  2139. // but that doesn't seem to be supported in Webkit
  2140. setTimeout(function() {
  2141. if (c_ani) {c_ani.remove();}
  2142. element.setAttribute('opacity', cur_shape.opacity);
  2143. element.setAttribute('style', 'pointer-events:inherit');
  2144. cleanupElement(element);
  2145. if (current_mode === 'path') {
  2146. pathActions.toEditMode(element);
  2147. } else if (curConfig.selectNew) {
  2148. selectOnly([element], true);
  2149. }
  2150. // we create the insert command that is stored on the stack
  2151. // undo means to call cmd.unapply(), redo means to call cmd.apply()
  2152. addCommandToHistory(new svgedit.history.InsertElementCommand(element));
  2153. call('changed',[element]);
  2154. }, ani_dur * 1000);
  2155. }
  2156. startTransform = null;
  2157. };
  2158. var dblClick = function(evt) {
  2159. var evt_target = evt.target;
  2160. var parent = evt_target.parentNode;
  2161. // Do nothing if already in current group
  2162. if (parent === current_group) {return;}
  2163. var mouse_target = getMouseTarget(evt);
  2164. var tagName = mouse_target.tagName;
  2165. if (tagName === 'text' && current_mode !== 'textedit') {
  2166. var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm );
  2167. textActions.select(mouse_target, pt.x, pt.y);
  2168. }
  2169. if ((tagName === 'g' || tagName === 'a') && svgedit.utilities.getRotationAngle(mouse_target)) {
  2170. // TODO: Allow method of in-group editing without having to do
  2171. // this (similar to editing rotated paths)
  2172. // Ungroup and regroup
  2173. pushGroupProperties(mouse_target);
  2174. mouse_target = selectedElements[0];
  2175. clearSelection(true);
  2176. }
  2177. // Reset context
  2178. if (current_group) {
  2179. leaveContext();
  2180. }
  2181. if ((parent.tagName !== 'g' && parent.tagName !== 'a') ||
  2182. parent === getCurrentDrawing().getCurrentLayer() ||
  2183. mouse_target === selectorManager.selectorParentGroup)
  2184. {
  2185. // Escape from in-group edit
  2186. return;
  2187. }
  2188. setContext(mouse_target);
  2189. };
  2190. // prevent links from being followed in the canvas
  2191. var handleLinkInCanvas = function(e) {
  2192. e.preventDefault();
  2193. return false;
  2194. };
  2195. // Added mouseup to the container here.
  2196. // TODO(codedread): Figure out why after the Closure compiler, the window mouseup is ignored.
  2197. $(container).mousedown(mouseDown).mousemove(mouseMove).click(handleLinkInCanvas).dblclick(dblClick).mouseup(mouseUp);
  2198. // $(window).mouseup(mouseUp);
  2199. //TODO(rafaelcastrocouto): User preference for shift key and zoom factor
  2200. $(container).bind('mousewheel DOMMouseScroll', function(e){
  2201. //if (!e.shiftKey) {return;}
  2202. e.preventDefault();
  2203. var evt = e.originalEvent;
  2204. root_sctm = $('#svgcontent g')[0].getScreenCTM().inverse();
  2205. var pt = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm );
  2206. var bbox = {
  2207. 'x': pt.x,
  2208. 'y': pt.y,
  2209. 'width': 0,
  2210. 'height': 0
  2211. };
  2212. var delta = (evt.wheelDelta) ? evt.wheelDelta : (evt.detail) ? -evt.detail : 0;
  2213. if (!delta) {return;}
  2214. bbox.factor = Math.max(3/4, Math.min(4/3, (delta)));
  2215. call('zoomed', bbox);
  2216. });
  2217. }());
  2218. // Function: preventClickDefault
  2219. // Prevents default browser click behaviour on the given element
  2220. //
  2221. // Parameters:
  2222. // img - The DOM element to prevent the cilck on
  2223. var preventClickDefault = function(img) {
  2224. $(img).click(function(e){e.preventDefault();});
  2225. };
  2226. // Group: Text edit functions
  2227. // Functions relating to editing text elements
  2228. textActions = canvas.textActions = (function() {
  2229. var curtext;
  2230. var textinput;
  2231. var cursor;
  2232. var selblock;
  2233. var blinker;
  2234. var chardata = [];
  2235. var textbb, transbb;
  2236. var matrix;
  2237. var last_x, last_y;
  2238. var allow_dbl;
  2239. function setCursor(index) {
  2240. var empty = (textinput.value === '');
  2241. $(textinput).focus();
  2242. if (!arguments.length) {
  2243. if (empty) {
  2244. index = 0;
  2245. } else {
  2246. if (textinput.selectionEnd !== textinput.selectionStart) {return;}
  2247. index = textinput.selectionEnd;
  2248. }
  2249. }
  2250. var charbb;
  2251. charbb = chardata[index];
  2252. if (!empty) {
  2253. textinput.setSelectionRange(index, index);
  2254. }
  2255. cursor = svgedit.utilities.getElem('text_cursor');
  2256. if (!cursor) {
  2257. cursor = document.createElementNS(NS.SVG, 'line');
  2258. svgedit.utilities.assignAttributes(cursor, {
  2259. id: 'text_cursor',
  2260. stroke: '#333',
  2261. 'stroke-width': 1
  2262. });
  2263. cursor = svgedit.utilities.getElem('selectorParentGroup').appendChild(cursor);
  2264. }
  2265. if (!blinker) {
  2266. blinker = setInterval(function() {
  2267. var show = (cursor.getAttribute('display') === 'none');
  2268. cursor.setAttribute('display', show?'inline':'none');
  2269. }, 600);
  2270. }
  2271. var start_pt = ptToScreen(charbb.x, textbb.y);
  2272. var end_pt = ptToScreen(charbb.x, (textbb.y + textbb.height));
  2273. svgedit.utilities.assignAttributes(cursor, {
  2274. x1: start_pt.x,
  2275. y1: start_pt.y,
  2276. x2: end_pt.x,
  2277. y2: end_pt.y,
  2278. visibility: 'visible',
  2279. display: 'inline'
  2280. });
  2281. if (selblock) {selblock.setAttribute('d', '');}
  2282. }
  2283. function setSelection(start, end, skipInput) {
  2284. if (start === end) {
  2285. setCursor(end);
  2286. return;
  2287. }
  2288. if (!skipInput) {
  2289. textinput.setSelectionRange(start, end);
  2290. }
  2291. selblock = svgedit.utilities.getElem('text_selectblock');
  2292. if (!selblock) {
  2293. selblock = document.createElementNS(NS.SVG, 'path');
  2294. svgedit.utilities.assignAttributes(selblock, {
  2295. id: 'text_selectblock',
  2296. fill: 'green',
  2297. opacity: 0.5,
  2298. style: 'pointer-events:none'
  2299. });
  2300. svgedit.utilities.getElem('selectorParentGroup').appendChild(selblock);
  2301. }
  2302. var startbb = chardata[start];
  2303. var endbb = chardata[end];
  2304. cursor.setAttribute('visibility', 'hidden');
  2305. var tl = ptToScreen(startbb.x, textbb.y),
  2306. tr = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y),
  2307. bl = ptToScreen(startbb.x, textbb.y + textbb.height),
  2308. br = ptToScreen(startbb.x + (endbb.x - startbb.x), textbb.y + textbb.height);
  2309. var dstr = 'M' + tl.x + ',' + tl.y
  2310. + ' L' + tr.x + ',' + tr.y
  2311. + ' ' + br.x + ',' + br.y
  2312. + ' ' + bl.x + ',' + bl.y + 'z';
  2313. svgedit.utilities.assignAttributes(selblock, {
  2314. d: dstr,
  2315. 'display': 'inline'
  2316. });
  2317. }
  2318. function getIndexFromPoint(mouse_x, mouse_y) {
  2319. // Position cursor here
  2320. var pt = svgroot.createSVGPoint();
  2321. pt.x = mouse_x;
  2322. pt.y = mouse_y;
  2323. // No content, so return 0
  2324. if (chardata.length == 1) {return 0;}
  2325. // Determine if cursor should be on left or right of character
  2326. var charpos = curtext.getCharNumAtPosition(pt);
  2327. if (charpos < 0) {
  2328. // Out of text range, look at mouse coords
  2329. charpos = chardata.length - 2;
  2330. if (mouse_x <= chardata[0].x) {
  2331. charpos = 0;
  2332. }
  2333. } else if (charpos >= chardata.length - 2) {
  2334. charpos = chardata.length - 2;
  2335. }
  2336. var charbb = chardata[charpos];
  2337. var mid = charbb.x + (charbb.width/2);
  2338. if (mouse_x > mid) {
  2339. charpos++;
  2340. }
  2341. return charpos;
  2342. }
  2343. function setCursorFromPoint(mouse_x, mouse_y) {
  2344. setCursor(getIndexFromPoint(mouse_x, mouse_y));
  2345. }
  2346. function setEndSelectionFromPoint(x, y, apply) {
  2347. var i1 = textinput.selectionStart;
  2348. var i2 = getIndexFromPoint(x, y);
  2349. var start = Math.min(i1, i2);
  2350. var end = Math.max(i1, i2);
  2351. setSelection(start, end, !apply);
  2352. }
  2353. function screenToPt(x_in, y_in) {
  2354. var out = {
  2355. x: x_in,
  2356. y: y_in
  2357. };
  2358. out.x /= current_zoom;
  2359. out.y /= current_zoom;
  2360. if (matrix) {
  2361. var pt = svgedit.math.transformPoint(out.x, out.y, matrix.inverse());
  2362. out.x = pt.x;
  2363. out.y = pt.y;
  2364. }
  2365. return out;
  2366. }
  2367. function ptToScreen(x_in, y_in) {
  2368. var out = {
  2369. x: x_in,
  2370. y: y_in
  2371. };
  2372. if (matrix) {
  2373. var pt = svgedit.math.transformPoint(out.x, out.y, matrix);
  2374. out.x = pt.x;
  2375. out.y = pt.y;
  2376. }
  2377. out.x *= current_zoom;
  2378. out.y *= current_zoom;
  2379. return out;
  2380. }
  2381. function hideCursor() {
  2382. if (cursor) {
  2383. cursor.setAttribute('visibility', 'hidden');
  2384. }
  2385. }
  2386. function selectAll(evt) {
  2387. setSelection(0, curtext.textContent.length);
  2388. $(this).unbind(evt);
  2389. }
  2390. function selectWord(evt) {
  2391. if (!allow_dbl || !curtext) {return;}
  2392. var ept = svgedit.math.transformPoint( evt.pageX, evt.pageY, root_sctm ),
  2393. mouse_x = ept.x * current_zoom,
  2394. mouse_y = ept.y * current_zoom;
  2395. var pt = screenToPt(mouse_x, mouse_y);
  2396. var index = getIndexFromPoint(pt.x, pt.y);
  2397. var str = curtext.textContent;
  2398. var first = str.substr(0, index).replace(/[a-z0-9]+$/i, '').length;
  2399. var m = str.substr(index).match(/^[a-z0-9]+/i);
  2400. var last = (m?m[0].length:0) + index;
  2401. setSelection(first, last);
  2402. // Set tripleclick
  2403. $(evt.target).click(selectAll);
  2404. setTimeout(function() {
  2405. $(evt.target).unbind('click', selectAll);
  2406. }, 300);
  2407. }
  2408. return {
  2409. select: function(target, x, y) {
  2410. curtext = target;
  2411. textActions.toEditMode(x, y);
  2412. },
  2413. start: function(elem) {
  2414. curtext = elem;
  2415. textActions.toEditMode();
  2416. },
  2417. mouseDown: function(evt, mouse_target, start_x, start_y) {
  2418. var pt = screenToPt(start_x, start_y);
  2419. textinput.focus();
  2420. setCursorFromPoint(pt.x, pt.y);
  2421. last_x = start_x;
  2422. last_y = start_y;
  2423. // TODO: Find way to block native selection
  2424. },
  2425. mouseMove: function(mouse_x, mouse_y) {
  2426. var pt = screenToPt(mouse_x, mouse_y);
  2427. setEndSelectionFromPoint(pt.x, pt.y);
  2428. },
  2429. mouseUp: function(evt, mouse_x, mouse_y) {
  2430. var pt = screenToPt(mouse_x, mouse_y);
  2431. setEndSelectionFromPoint(pt.x, pt.y, true);
  2432. // TODO: Find a way to make this work: Use transformed BBox instead of evt.target
  2433. // if (last_x === mouse_x && last_y === mouse_y
  2434. // && !svgedit.math.rectsIntersect(transbb, {x: pt.x, y: pt.y, width:0, height:0})) {
  2435. // textActions.toSelectMode(true);
  2436. // }
  2437. if (
  2438. evt.target !== curtext
  2439. && mouse_x < last_x + 2
  2440. && mouse_x > last_x - 2
  2441. && mouse_y < last_y + 2
  2442. && mouse_y > last_y - 2) {
  2443. textActions.toSelectMode(true);
  2444. }
  2445. },
  2446. setCursor: setCursor,
  2447. toEditMode: function(x, y) {
  2448. allow_dbl = false;
  2449. current_mode = 'textedit';
  2450. selectorManager.requestSelector(curtext).showGrips(false);
  2451. // Make selector group accept clicks
  2452. var sel = selectorManager.requestSelector(curtext).selectorRect;
  2453. textActions.init();
  2454. $(curtext).css('cursor', 'text');
  2455. // if (svgedit.browser.supportsEditableText()) {
  2456. // curtext.setAttribute('editable', 'simple');
  2457. // return;
  2458. // }
  2459. if (!arguments.length) {
  2460. setCursor();
  2461. } else {
  2462. var pt = screenToPt(x, y);
  2463. setCursorFromPoint(pt.x, pt.y);
  2464. }
  2465. setTimeout(function() {
  2466. allow_dbl = true;
  2467. }, 300);
  2468. },
  2469. toSelectMode: function(selectElem) {
  2470. current_mode = 'select';
  2471. clearInterval(blinker);
  2472. blinker = null;
  2473. if (selblock) {$(selblock).attr('display', 'none');}
  2474. if (cursor) {$(cursor).attr('visibility', 'hidden');}
  2475. $(curtext).css('cursor', 'move');
  2476. if (selectElem) {
  2477. clearSelection();
  2478. $(curtext).css('cursor', 'move');
  2479. call('selected', [curtext]);
  2480. addToSelection([curtext], true);
  2481. }
  2482. if (curtext && !curtext.textContent.length) {
  2483. // No content, so delete
  2484. canvas.deleteSelectedElements();
  2485. }
  2486. $(textinput).blur();
  2487. curtext = false;
  2488. // if (svgedit.browser.supportsEditableText()) {
  2489. // curtext.removeAttribute('editable');
  2490. // }
  2491. },
  2492. setInputElem: function(elem) {
  2493. textinput = elem;
  2494. // $(textinput).blur(hideCursor);
  2495. },
  2496. clear: function() {
  2497. if (current_mode == 'textedit') {
  2498. textActions.toSelectMode();
  2499. }
  2500. },
  2501. init: function(inputElem) {
  2502. if (!curtext) {return;}
  2503. var i, end;
  2504. // if (svgedit.browser.supportsEditableText()) {
  2505. // curtext.select();
  2506. // return;
  2507. // }
  2508. if (!curtext.parentNode) {
  2509. // Result of the ffClone, need to get correct element
  2510. curtext = selectedElements[0];
  2511. selectorManager.requestSelector(curtext).showGrips(false);
  2512. }
  2513. var str = curtext.textContent;
  2514. var len = str.length;
  2515. var xform = curtext.getAttribute('transform');
  2516. textbb = svgedit.utilities.getBBox(curtext);
  2517. matrix = xform ? svgedit.math.getMatrix(curtext) : null;
  2518. chardata = [];
  2519. chardata.length = len;
  2520. textinput.focus();
  2521. $(curtext).unbind('dblclick', selectWord).dblclick(selectWord);
  2522. if (!len) {
  2523. end = {x: textbb.x + (textbb.width/2), width: 0};
  2524. }
  2525. for (i=0; i<len; i++) {
  2526. var start = curtext.getStartPositionOfChar(i);
  2527. end = curtext.getEndPositionOfChar(i);
  2528. if (!svgedit.browser.supportsGoodTextCharPos()) {
  2529. var offset = canvas.contentW * current_zoom;
  2530. start.x -= offset;
  2531. end.x -= offset;
  2532. start.x /= current_zoom;
  2533. end.x /= current_zoom;
  2534. }
  2535. // Get a "bbox" equivalent for each character. Uses the
  2536. // bbox data of the actual text for y, height purposes
  2537. // TODO: Decide if y, width and height are actually necessary
  2538. chardata[i] = {
  2539. x: start.x,
  2540. y: textbb.y, // start.y?
  2541. width: end.x - start.x,
  2542. height: textbb.height
  2543. };
  2544. }
  2545. // Add a last bbox for cursor at end of text
  2546. chardata.push({
  2547. x: end.x,
  2548. width: 0
  2549. });
  2550. setSelection(textinput.selectionStart, textinput.selectionEnd, true);
  2551. }
  2552. };
  2553. }());
  2554. // TODO: Migrate all of this code into path.js
  2555. // Group: Path edit functions
  2556. // Functions relating to editing path elements
  2557. pathActions = canvas.pathActions = function() {
  2558. var subpath = false;
  2559. var current_path;
  2560. var newPoint, firstCtrl;
  2561. function resetD(p) {
  2562. p.setAttribute('d', pathActions.convertPath(p));
  2563. }
  2564. // TODO: Move into path.js
  2565. svgedit.path.Path.prototype.endChanges = function(text) {
  2566. if (svgedit.browser.isWebkit()) {resetD(this.elem);}
  2567. var cmd = new svgedit.history.ChangeElementCommand(this.elem, {d: this.last_d}, text);
  2568. addCommandToHistory(cmd);
  2569. call('changed', [this.elem]);
  2570. };
  2571. svgedit.path.Path.prototype.addPtsToSelection = function(indexes) {
  2572. var i, seg;
  2573. if (!$.isArray(indexes)) {indexes = [indexes];}
  2574. for (i = 0; i< indexes.length; i++) {
  2575. var index = indexes[i];
  2576. seg = this.segs[index];
  2577. if (seg.ptgrip) {
  2578. if (this.selected_pts.indexOf(index) == -1 && index >= 0) {
  2579. this.selected_pts.push(index);
  2580. }
  2581. }
  2582. }
  2583. this.selected_pts.sort();
  2584. i = this.selected_pts.length;
  2585. var grips = [];
  2586. grips.length = i;
  2587. // Loop through points to be selected and highlight each
  2588. while (i--) {
  2589. var pt = this.selected_pts[i];
  2590. seg = this.segs[pt];
  2591. seg.select(true);
  2592. grips[i] = seg.ptgrip;
  2593. }
  2594. // TODO: Correct this:
  2595. pathActions.canDeleteNodes = true;
  2596. pathActions.closed_subpath = this.subpathIsClosed(this.selected_pts[0]);
  2597. call('selected', grips);
  2598. };
  2599. current_path = null;
  2600. var drawn_path = null,
  2601. hasMoved = false;
  2602. // This function converts a polyline (created by the fh_path tool) into
  2603. // a path element and coverts every three line segments into a single bezier
  2604. // curve in an attempt to smooth out the free-hand
  2605. var smoothPolylineIntoPath = function(element) {
  2606. var i, points = element.points;
  2607. var N = points.numberOfItems;
  2608. if (N >= 4) {
  2609. // loop through every 3 points and convert to a cubic bezier curve segment
  2610. //
  2611. // NOTE: this is cheating, it means that every 3 points has the potential to
  2612. // be a corner instead of treating each point in an equal manner. In general,
  2613. // this technique does not look that good.
  2614. //
  2615. // I am open to better ideas!
  2616. //
  2617. // Reading:
  2618. // - http://www.efg2.com/Lab/Graphics/Jean-YvesQueinecBezierCurves.htm
  2619. // - http://www.codeproject.com/KB/graphics/BezierSpline.aspx?msg=2956963
  2620. // - http://www.ian-ko.com/ET_GeoWizards/UserGuide/smooth.htm
  2621. // - http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-der.html
  2622. var curpos = points.getItem(0), prevCtlPt = null;
  2623. var d = [];
  2624. d.push(['M', curpos.x, ',', curpos.y, ' C'].join(''));
  2625. for (i = 1; i <= (N-4); i += 3) {
  2626. var ct1 = points.getItem(i);
  2627. var ct2 = points.getItem(i+1);
  2628. var end = points.getItem(i+2);
  2629. // if the previous segment had a control point, we want to smooth out
  2630. // the control points on both sides
  2631. if (prevCtlPt) {
  2632. var newpts = svgedit.path.smoothControlPoints( prevCtlPt, ct1, curpos );
  2633. if (newpts && newpts.length == 2) {
  2634. var prevArr = d[d.length-1].split(',');
  2635. prevArr[2] = newpts[0].x;
  2636. prevArr[3] = newpts[0].y;
  2637. d[d.length-1] = prevArr.join(',');
  2638. ct1 = newpts[1];
  2639. }
  2640. }
  2641. d.push([ct1.x, ct1.y, ct2.x, ct2.y, end.x, end.y].join(','));
  2642. curpos = end;
  2643. prevCtlPt = ct2;
  2644. }
  2645. // handle remaining line segments
  2646. d.push('L');
  2647. while (i < N) {
  2648. var pt = points.getItem(i);
  2649. d.push([pt.x, pt.y].join(','));
  2650. i++;
  2651. }
  2652. d = d.join(' ');
  2653. // create new path element
  2654. element = addSvgElementFromJson({
  2655. element: 'path',
  2656. curStyles: true,
  2657. attr: {
  2658. id: getId(),
  2659. d: d,
  2660. fill: 'none'
  2661. }
  2662. });
  2663. // No need to call "changed", as this is already done under mouseUp
  2664. }
  2665. return element;
  2666. };
  2667. return {
  2668. mouseDown: function(evt, mouse_target, start_x, start_y) {
  2669. var id;
  2670. if (current_mode === 'path') {
  2671. mouse_x = start_x;
  2672. mouse_y = start_y;
  2673. var x = mouse_x/current_zoom,
  2674. y = mouse_y/current_zoom,
  2675. stretchy = svgedit.utilities.getElem('path_stretch_line');
  2676. newPoint = [x, y];
  2677. if (curConfig.gridSnapping){
  2678. x = svgedit.utilities.snapToGrid(x);
  2679. y = svgedit.utilities.snapToGrid(y);
  2680. mouse_x = svgedit.utilities.snapToGrid(mouse_x);
  2681. mouse_y = svgedit.utilities.snapToGrid(mouse_y);
  2682. }
  2683. if (!stretchy) {
  2684. stretchy = document.createElementNS(NS.SVG, 'path');
  2685. svgedit.utilities.assignAttributes(stretchy, {
  2686. id: 'path_stretch_line',
  2687. stroke: '#22C',
  2688. 'stroke-width': '0.5',
  2689. fill: 'none'
  2690. });
  2691. stretchy = svgedit.utilities.getElem('selectorParentGroup').appendChild(stretchy);
  2692. }
  2693. stretchy.setAttribute('display', 'inline');
  2694. var keep = null;
  2695. var index;
  2696. // if pts array is empty, create path element with M at current point
  2697. if (!drawn_path) {
  2698. d_attr = 'M' + x + ',' + y + ' ';
  2699. drawn_path = addSvgElementFromJson({
  2700. element: 'path',
  2701. curStyles: true,
  2702. attr: {
  2703. d: d_attr,
  2704. id: getNextId(),
  2705. opacity: cur_shape.opacity / 2
  2706. }
  2707. });
  2708. // set stretchy line to first point
  2709. stretchy.setAttribute('d', ['M', mouse_x, mouse_y, mouse_x, mouse_y].join(' '));
  2710. index = subpath ? svgedit.path.path.segs.length : 0;
  2711. svgedit.path.addPointGrip(index, mouse_x, mouse_y);
  2712. } else {
  2713. // determine if we clicked on an existing point
  2714. var seglist = drawn_path.pathSegList;
  2715. var i = seglist.numberOfItems;
  2716. var FUZZ = 6/current_zoom;
  2717. var clickOnPoint = false;
  2718. while (i) {
  2719. i --;
  2720. var item = seglist.getItem(i);
  2721. var px = item.x, py = item.y;
  2722. // found a matching point
  2723. if ( x >= (px-FUZZ) && x <= (px+FUZZ) && y >= (py-FUZZ) && y <= (py+FUZZ) ) {
  2724. clickOnPoint = true;
  2725. break;
  2726. }
  2727. }
  2728. // get path element that we are in the process of creating
  2729. id = getId();
  2730. // Remove previous path object if previously created
  2731. svgedit.path.removePath_(id);
  2732. var newpath = svgedit.utilities.getElem(id);
  2733. var newseg;
  2734. var s_seg;
  2735. var len = seglist.numberOfItems;
  2736. // if we clicked on an existing point, then we are done this path, commit it
  2737. // (i, i+1) are the x,y that were clicked on
  2738. if (clickOnPoint) {
  2739. // if clicked on any other point but the first OR
  2740. // the first point was clicked on and there are less than 3 points
  2741. // then leave the path open
  2742. // otherwise, close the path
  2743. if (i <= 1 && len >= 2) {
  2744. // Create end segment
  2745. var abs_x = seglist.getItem(0).x;
  2746. var abs_y = seglist.getItem(0).y;
  2747. s_seg = stretchy.pathSegList.getItem(1);
  2748. if (s_seg.pathSegType === 4) {
  2749. newseg = drawn_path.createSVGPathSegLinetoAbs(abs_x, abs_y);
  2750. } else {
  2751. newseg = drawn_path.createSVGPathSegCurvetoCubicAbs(
  2752. abs_x,
  2753. abs_y,
  2754. s_seg.x1 / current_zoom,
  2755. s_seg.y1 / current_zoom,
  2756. abs_x,
  2757. abs_y
  2758. );
  2759. }
  2760. var endseg = drawn_path.createSVGPathSegClosePath();
  2761. seglist.appendItem(newseg);
  2762. seglist.appendItem(endseg);
  2763. } else if (len < 3) {
  2764. keep = false;
  2765. return keep;
  2766. }
  2767. $(stretchy).remove();
  2768. // This will signal to commit the path
  2769. element = newpath;
  2770. drawn_path = null;
  2771. started = false;
  2772. if (subpath) {
  2773. if (svgedit.path.path.matrix) {
  2774. svgedit.coords.remapElement(newpath, {}, svgedit.path.path.matrix.inverse());
  2775. }
  2776. var new_d = newpath.getAttribute('d');
  2777. var orig_d = $(svgedit.path.path.elem).attr('d');
  2778. $(svgedit.path.path.elem).attr('d', orig_d + new_d);
  2779. $(newpath).remove();
  2780. if (svgedit.path.path.matrix) {
  2781. svgedit.path.recalcRotatedPath();
  2782. }
  2783. svgedit.path.path.init();
  2784. pathActions.toEditMode(svgedit.path.path.elem);
  2785. svgedit.path.path.selectPt();
  2786. return false;
  2787. }
  2788. }
  2789. // else, create a new point, update path element
  2790. else {
  2791. // Checks if current target or parents are #svgcontent
  2792. if (!$.contains(container, getMouseTarget(evt))) {
  2793. // Clicked outside canvas, so don't make point
  2794. console.log('Clicked outside canvas');
  2795. return false;
  2796. }
  2797. var num = drawn_path.pathSegList.numberOfItems;
  2798. var last = drawn_path.pathSegList.getItem(num -1);
  2799. var lastx = last.x, lasty = last.y;
  2800. if (evt.shiftKey) {
  2801. var xya = svgedit.math.snapToAngle(lastx, lasty, x, y);
  2802. x = xya.x;
  2803. y = xya.y;
  2804. }
  2805. // Use the segment defined by stretchy
  2806. s_seg = stretchy.pathSegList.getItem(1);
  2807. if (s_seg.pathSegType === 4) {
  2808. newseg = drawn_path.createSVGPathSegLinetoAbs(round(x), round(y));
  2809. } else {
  2810. newseg = drawn_path.createSVGPathSegCurvetoCubicAbs(
  2811. round(x),
  2812. round(y),
  2813. s_seg.x1 / current_zoom,
  2814. s_seg.y1 / current_zoom,
  2815. s_seg.x2 / current_zoom,
  2816. s_seg.y2 / current_zoom
  2817. );
  2818. }
  2819. drawn_path.pathSegList.appendItem(newseg);
  2820. x *= current_zoom;
  2821. y *= current_zoom;
  2822. // set stretchy line to latest point
  2823. stretchy.setAttribute('d', ['M', x, y, x, y].join(' '));
  2824. index = num;
  2825. if (subpath) {index += svgedit.path.path.segs.length;}
  2826. svgedit.path.addPointGrip(index, x, y);
  2827. }
  2828. // keep = true;
  2829. }
  2830. return;
  2831. }
  2832. // TODO: Make sure current_path isn't null at this point
  2833. if (!svgedit.path.path) {return;}
  2834. svgedit.path.path.storeD();
  2835. id = evt.target.id;
  2836. var cur_pt;
  2837. if (id.substr(0,14) == 'pathpointgrip_') {
  2838. // Select this point
  2839. cur_pt = svgedit.path.path.cur_pt = parseInt(id.substr(14));
  2840. svgedit.path.path.dragging = [start_x, start_y];
  2841. var seg = svgedit.path.path.segs[cur_pt];
  2842. // only clear selection if shift is not pressed (otherwise, add
  2843. // node to selection)
  2844. if (!evt.shiftKey) {
  2845. if (svgedit.path.path.selected_pts.length <= 1 || !seg.selected) {
  2846. svgedit.path.path.clearSelection();
  2847. }
  2848. svgedit.path.path.addPtsToSelection(cur_pt);
  2849. } else if (seg.selected) {
  2850. svgedit.path.path.removePtFromSelection(cur_pt);
  2851. } else {
  2852. svgedit.path.path.addPtsToSelection(cur_pt);
  2853. }
  2854. } else if (id.indexOf('ctrlpointgrip_') == 0) {
  2855. svgedit.path.path.dragging = [start_x, start_y];
  2856. var parts = id.split('_')[1].split('c');
  2857. cur_pt = Number(parts[0]);
  2858. var ctrl_num = Number(parts[1]);
  2859. svgedit.path.path.selectPt(cur_pt, ctrl_num);
  2860. }
  2861. // Start selection box
  2862. if (!svgedit.path.path.dragging) {
  2863. if (rubberBox == null) {
  2864. rubberBox = selectorManager.getRubberBandBox();
  2865. }
  2866. svgedit.utilities.assignAttributes(rubberBox, {
  2867. 'x': start_x * current_zoom,
  2868. 'y': start_y * current_zoom,
  2869. 'width': 0,
  2870. 'height': 0,
  2871. 'display': 'inline'
  2872. }, 100);
  2873. }
  2874. },
  2875. mouseMove: function(mouse_x, mouse_y) {
  2876. hasMoved = true;
  2877. if (current_mode === 'path') {
  2878. if (!drawn_path) {return;}
  2879. var seglist = drawn_path.pathSegList;
  2880. var index = seglist.numberOfItems - 1;
  2881. if (newPoint) {
  2882. // First point
  2883. // if (!index) {return;}
  2884. // Set control points
  2885. var pointGrip1 = svgedit.path.addCtrlGrip('1c1');
  2886. var pointGrip2 = svgedit.path.addCtrlGrip('0c2');
  2887. // dragging pointGrip1
  2888. pointGrip1.setAttribute('cx', mouse_x);
  2889. pointGrip1.setAttribute('cy', mouse_y);
  2890. pointGrip1.setAttribute('display', 'inline');
  2891. var pt_x = newPoint[0];
  2892. var pt_y = newPoint[1];
  2893. // set curve
  2894. var seg = seglist.getItem(index);
  2895. var cur_x = mouse_x / current_zoom;
  2896. var cur_y = mouse_y / current_zoom;
  2897. var alt_x = (pt_x + (pt_x - cur_x));
  2898. var alt_y = (pt_y + (pt_y - cur_y));
  2899. pointGrip2.setAttribute('cx', alt_x * current_zoom);
  2900. pointGrip2.setAttribute('cy', alt_y * current_zoom);
  2901. pointGrip2.setAttribute('display', 'inline');
  2902. var ctrlLine = svgedit.path.getCtrlLine(1);
  2903. svgedit.utilities.assignAttributes(ctrlLine, {
  2904. x1: mouse_x,
  2905. y1: mouse_y,
  2906. x2: alt_x * current_zoom,
  2907. y2: alt_y * current_zoom,
  2908. display: 'inline'
  2909. });
  2910. if (index === 0) {
  2911. firstCtrl = [mouse_x, mouse_y];
  2912. } else {
  2913. var last = seglist.getItem(index - 1);
  2914. var last_x = last.x;
  2915. var last_y = last.y;
  2916. if (last.pathSegType === 6) {
  2917. last_x += (last_x - last.x2);
  2918. last_y += (last_y - last.y2);
  2919. } else if (firstCtrl) {
  2920. last_x = firstCtrl[0]/current_zoom;
  2921. last_y = firstCtrl[1]/current_zoom;
  2922. }
  2923. svgedit.path.replacePathSeg(6, index, [pt_x, pt_y, last_x, last_y, alt_x, alt_y], drawn_path);
  2924. }
  2925. } else {
  2926. var stretchy = svgedit.utilities.getElem('path_stretch_line');
  2927. if (stretchy) {
  2928. var prev = seglist.getItem(index);
  2929. if (prev.pathSegType === 6) {
  2930. var prev_x = prev.x + (prev.x - prev.x2);
  2931. var prev_y = prev.y + (prev.y - prev.y2);
  2932. svgedit.path.replacePathSeg(6, 1, [mouse_x, mouse_y, prev_x * current_zoom, prev_y * current_zoom, mouse_x, mouse_y], stretchy);
  2933. } else if (firstCtrl) {
  2934. svgedit.path.replacePathSeg(6, 1, [mouse_x, mouse_y, firstCtrl[0], firstCtrl[1], mouse_x, mouse_y], stretchy);
  2935. } else {
  2936. svgedit.path.replacePathSeg(4, 1, [mouse_x, mouse_y], stretchy);
  2937. }
  2938. }
  2939. }
  2940. return;
  2941. }
  2942. // if we are dragging a point, let's move it
  2943. if (svgedit.path.path.dragging) {
  2944. var pt = svgedit.path.getPointFromGrip({
  2945. x: svgedit.path.path.dragging[0],
  2946. y: svgedit.path.path.dragging[1]
  2947. }, svgedit.path.path);
  2948. var mpt = svgedit.path.getPointFromGrip({
  2949. x: mouse_x,
  2950. y: mouse_y
  2951. }, svgedit.path.path);
  2952. var diff_x = mpt.x - pt.x;
  2953. var diff_y = mpt.y - pt.y;
  2954. svgedit.path.path.dragging = [mouse_x, mouse_y];
  2955. if (svgedit.path.path.dragctrl) {
  2956. svgedit.path.path.moveCtrl(diff_x, diff_y);
  2957. } else {
  2958. svgedit.path.path.movePts(diff_x, diff_y);
  2959. }
  2960. } else {
  2961. svgedit.path.path.selected_pts = [];
  2962. svgedit.path.path.eachSeg(function(i) {
  2963. var seg = this;
  2964. if (!seg.next && !seg.prev) {return;}
  2965. var item = seg.item;
  2966. var rbb = rubberBox.getBBox();
  2967. var pt = svgedit.path.getGripPt(seg);
  2968. var pt_bb = {
  2969. x: pt.x,
  2970. y: pt.y,
  2971. width: 0,
  2972. height: 0
  2973. };
  2974. var sel = svgedit.math.rectsIntersect(rbb, pt_bb);
  2975. this.select(sel);
  2976. //Note that addPtsToSelection is not being run
  2977. if (sel) {svgedit.path.path.selected_pts.push(seg.index);}
  2978. });
  2979. }
  2980. },
  2981. mouseUp: function(evt, element, mouse_x, mouse_y) {
  2982. // Create mode
  2983. if (current_mode === 'path') {
  2984. newPoint = null;
  2985. if (!drawn_path) {
  2986. element = svgedit.utilities.getElem(getId());
  2987. started = false;
  2988. firstCtrl = null;
  2989. }
  2990. return {
  2991. keep: true,
  2992. element: element
  2993. };
  2994. }
  2995. // Edit mode
  2996. if (svgedit.path.path.dragging) {
  2997. var last_pt = svgedit.path.path.cur_pt;
  2998. svgedit.path.path.dragging = false;
  2999. svgedit.path.path.dragctrl = false;
  3000. svgedit.path.path.update();
  3001. if (hasMoved) {
  3002. svgedit.path.path.endChanges('Move path point(s)');
  3003. }
  3004. if (!evt.shiftKey && !hasMoved) {
  3005. svgedit.path.path.selectPt(last_pt);
  3006. }
  3007. } else if (rubberBox && rubberBox.getAttribute('display') != 'none') {
  3008. // Done with multi-node-select
  3009. rubberBox.setAttribute('display', 'none');
  3010. if (rubberBox.getAttribute('width') <= 2 && rubberBox.getAttribute('height') <= 2) {
  3011. pathActions.toSelectMode(evt.target);
  3012. }
  3013. // else, move back to select mode
  3014. } else {
  3015. pathActions.toSelectMode(evt.target);
  3016. }
  3017. hasMoved = false;
  3018. },
  3019. toEditMode: function(element) {
  3020. svgedit.path.path = svgedit.path.getPath_(element);
  3021. current_mode = 'pathedit';
  3022. clearSelection();
  3023. svgedit.path.path.show(true).update();
  3024. svgedit.path.path.oldbbox = svgedit.utilities.getBBox(svgedit.path.path.elem);
  3025. subpath = false;
  3026. },
  3027. toSelectMode: function(elem) {
  3028. var selPath = (elem == svgedit.path.path.elem);
  3029. current_mode = 'select';
  3030. svgedit.path.path.show(false);
  3031. current_path = false;
  3032. clearSelection();
  3033. if (svgedit.path.path.matrix) {
  3034. // Rotated, so may need to re-calculate the center
  3035. svgedit.path.recalcRotatedPath();
  3036. }
  3037. if (selPath) {
  3038. call('selected', [elem]);
  3039. addToSelection([elem], true);
  3040. }
  3041. },
  3042. addSubPath: function(on) {
  3043. if (on) {
  3044. // Internally we go into "path" mode, but in the UI it will
  3045. // still appear as if in "pathedit" mode.
  3046. current_mode = 'path';
  3047. subpath = true;
  3048. } else {
  3049. pathActions.clear(true);
  3050. pathActions.toEditMode(svgedit.path.path.elem);
  3051. }
  3052. },
  3053. select: function(target) {
  3054. if (current_path === target) {
  3055. pathActions.toEditMode(target);
  3056. current_mode = 'pathedit';
  3057. } // going into pathedit mode
  3058. else {
  3059. current_path = target;
  3060. }
  3061. },
  3062. reorient: function() {
  3063. var elem = selectedElements[0];
  3064. if (!elem) {return;}
  3065. var angle = svgedit.utilities.getRotationAngle(elem);
  3066. if (angle == 0) {return;}
  3067. var batchCmd = new svgedit.history.BatchCommand('Reorient path');
  3068. var changes = {
  3069. d: elem.getAttribute('d'),
  3070. transform: elem.getAttribute('transform')
  3071. };
  3072. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, changes));
  3073. clearSelection();
  3074. this.resetOrientation(elem);
  3075. addCommandToHistory(batchCmd);
  3076. // Set matrix to null
  3077. svgedit.path.getPath_(elem).show(false).matrix = null;
  3078. this.clear();
  3079. addToSelection([elem], true);
  3080. call('changed', selectedElements);
  3081. },
  3082. clear: function(remove) {
  3083. current_path = null;
  3084. if (drawn_path) {
  3085. var elem = svgedit.utilities.getElem(getId());
  3086. $(svgedit.utilities.getElem('path_stretch_line')).remove();
  3087. $(elem).remove();
  3088. $(svgedit.utilities.getElem('pathpointgrip_container')).find('*').attr('display', 'none');
  3089. drawn_path = firstCtrl = null;
  3090. started = false;
  3091. } else if (current_mode == 'pathedit') {
  3092. this.toSelectMode();
  3093. }
  3094. if (svgedit.path.path) {svgedit.path.path.init().show(false);}
  3095. },
  3096. resetOrientation: function(path) {
  3097. if (path == null || path.nodeName != 'path') {return false;}
  3098. var tlist = svgedit.transformlist.getTransformList(path);
  3099. var m = svgedit.math.transformListToTransform(tlist).matrix;
  3100. tlist.clear();
  3101. path.removeAttribute('transform');
  3102. var segList = path.pathSegList;
  3103. // Opera/win/non-EN throws an error here.
  3104. // TODO: Find out why!
  3105. // Presumed fixed in Opera 10.5, so commented out for now
  3106. // try {
  3107. var len = segList.numberOfItems;
  3108. // } catch(err) {
  3109. // var fixed_d = pathActions.convertPath(path);
  3110. // path.setAttribute('d', fixed_d);
  3111. // segList = path.pathSegList;
  3112. // var len = segList.numberOfItems;
  3113. // }
  3114. var i, last_x, last_y;
  3115. for (i = 0; i < len; ++i) {
  3116. var seg = segList.getItem(i);
  3117. var type = seg.pathSegType;
  3118. if (type == 1) {continue;}
  3119. var pts = [];
  3120. $.each(['',1,2], function(j, n) {
  3121. var x = seg['x'+n], y = seg['y'+n];
  3122. if (x !== undefined && y !== undefined) {
  3123. var pt = svgedit.math.transformPoint(x, y, m);
  3124. pts.splice(pts.length, 0, pt.x, pt.y);
  3125. }
  3126. });
  3127. svgedit.path.replacePathSeg(type, i, pts, path);
  3128. }
  3129. reorientGrads(path, m);
  3130. },
  3131. zoomChange: function() {
  3132. if (current_mode == 'pathedit') {
  3133. svgedit.path.path.update();
  3134. }
  3135. },
  3136. getNodePoint: function() {
  3137. var sel_pt = svgedit.path.path.selected_pts.length ? svgedit.path.path.selected_pts[0] : 1;
  3138. var seg = svgedit.path.path.segs[sel_pt];
  3139. return {
  3140. x: seg.item.x,
  3141. y: seg.item.y,
  3142. type: seg.type
  3143. };
  3144. },
  3145. linkControlPoints: function(linkPoints) {
  3146. svgedit.path.setLinkControlPoints(linkPoints);
  3147. },
  3148. clonePathNode: function() {
  3149. svgedit.path.path.storeD();
  3150. var sel_pts = svgedit.path.path.selected_pts;
  3151. var segs = svgedit.path.path.segs;
  3152. var i = sel_pts.length;
  3153. var nums = [];
  3154. while (i--) {
  3155. var pt = sel_pts[i];
  3156. svgedit.path.path.addSeg(pt);
  3157. nums.push(pt + i);
  3158. nums.push(pt + i + 1);
  3159. }
  3160. svgedit.path.path.init().addPtsToSelection(nums);
  3161. svgedit.path.path.endChanges('Clone path node(s)');
  3162. },
  3163. opencloseSubPath: function() {
  3164. var sel_pts = svgedit.path.path.selected_pts;
  3165. // Only allow one selected node for now
  3166. if (sel_pts.length !== 1) {return;}
  3167. var elem = svgedit.path.path.elem;
  3168. var list = elem.pathSegList;
  3169. var len = list.numberOfItems;
  3170. var index = sel_pts[0];
  3171. var open_pt = null;
  3172. var start_item = null;
  3173. // Check if subpath is already open
  3174. svgedit.path.path.eachSeg(function(i) {
  3175. if (this.type === 2 && i <= index) {
  3176. start_item = this.item;
  3177. }
  3178. if (i <= index) {return true;}
  3179. if (this.type === 2) {
  3180. // Found M first, so open
  3181. open_pt = i;
  3182. return false;
  3183. }
  3184. if (this.type === 1) {
  3185. // Found Z first, so closed
  3186. open_pt = false;
  3187. return false;
  3188. }
  3189. });
  3190. if (open_pt == null) {
  3191. // Single path, so close last seg
  3192. open_pt = svgedit.path.path.segs.length - 1;
  3193. }
  3194. if (open_pt !== false) {
  3195. // Close this path
  3196. // Create a line going to the previous "M"
  3197. var newseg = elem.createSVGPathSegLinetoAbs(start_item.x, start_item.y);
  3198. var closer = elem.createSVGPathSegClosePath();
  3199. if (open_pt == svgedit.path.path.segs.length - 1) {
  3200. list.appendItem(newseg);
  3201. list.appendItem(closer);
  3202. } else {
  3203. svgedit.path.insertItemBefore(elem, closer, open_pt);
  3204. svgedit.path.insertItemBefore(elem, newseg, open_pt);
  3205. }
  3206. svgedit.path.path.init().selectPt(open_pt+1);
  3207. return;
  3208. }
  3209. // M 1,1 L 2,2 L 3,3 L 1,1 z // open at 2,2
  3210. // M 2,2 L 3,3 L 1,1
  3211. // M 1,1 L 2,2 L 1,1 z M 4,4 L 5,5 L6,6 L 5,5 z
  3212. // M 1,1 L 2,2 L 1,1 z [M 4,4] L 5,5 L(M)6,6 L 5,5 z
  3213. var seg = svgedit.path.path.segs[index];
  3214. if (seg.mate) {
  3215. list.removeItem(index); // Removes last "L"
  3216. list.removeItem(index); // Removes the "Z"
  3217. svgedit.path.path.init().selectPt(index - 1);
  3218. return;
  3219. }
  3220. var i, last_m, z_seg;
  3221. // Find this sub-path's closing point and remove
  3222. for (i = 0; i<list.numberOfItems; i++) {
  3223. var item = list.getItem(i);
  3224. if (item.pathSegType === 2) {
  3225. // Find the preceding M
  3226. last_m = i;
  3227. } else if (i === index) {
  3228. // Remove it
  3229. list.removeItem(last_m);
  3230. // index--;
  3231. } else if (item.pathSegType === 1 && index < i) {
  3232. // Remove the closing seg of this subpath
  3233. z_seg = i-1;
  3234. list.removeItem(i);
  3235. break;
  3236. }
  3237. }
  3238. var num = (index - last_m) - 1;
  3239. while (num--) {
  3240. svgedit.path.insertItemBefore(elem, list.getItem(last_m), z_seg);
  3241. }
  3242. var pt = list.getItem(last_m);
  3243. // Make this point the new "M"
  3244. svgedit.path.replacePathSeg(2, last_m, [pt.x, pt.y]);
  3245. i = index; // i is local here, so has no effect; what is the reason for this?
  3246. svgedit.path.path.init().selectPt(0);
  3247. },
  3248. deletePathNode: function() {
  3249. if (!pathActions.canDeleteNodes) {return;}
  3250. svgedit.path.path.storeD();
  3251. var sel_pts = svgedit.path.path.selected_pts;
  3252. var i = sel_pts.length;
  3253. while (i--) {
  3254. var pt = sel_pts[i];
  3255. svgedit.path.path.deleteSeg(pt);
  3256. }
  3257. // Cleanup
  3258. var cleanup = function() {
  3259. var segList = svgedit.path.path.elem.pathSegList;
  3260. var len = segList.numberOfItems;
  3261. var remItems = function(pos, count) {
  3262. while (count--) {
  3263. segList.removeItem(pos);
  3264. }
  3265. };
  3266. if (len <= 1) {return true;}
  3267. while (len--) {
  3268. var item = segList.getItem(len);
  3269. if (item.pathSegType === 1) {
  3270. var prev = segList.getItem(len-1);
  3271. var nprev = segList.getItem(len-2);
  3272. if (prev.pathSegType === 2) {
  3273. remItems(len-1, 2);
  3274. cleanup();
  3275. break;
  3276. } else if (nprev.pathSegType === 2) {
  3277. remItems(len-2, 3);
  3278. cleanup();
  3279. break;
  3280. }
  3281. } else if (item.pathSegType === 2) {
  3282. if (len > 0) {
  3283. var prev_type = segList.getItem(len-1).pathSegType;
  3284. // Path has M M
  3285. if (prev_type === 2) {
  3286. remItems(len-1, 1);
  3287. cleanup();
  3288. break;
  3289. // Entire path ends with Z M
  3290. } else if (prev_type === 1 && segList.numberOfItems-1 === len) {
  3291. remItems(len, 1);
  3292. cleanup();
  3293. break;
  3294. }
  3295. }
  3296. }
  3297. }
  3298. return false;
  3299. };
  3300. cleanup();
  3301. // Completely delete a path with 1 or 0 segments
  3302. if (svgedit.path.path.elem.pathSegList.numberOfItems <= 1) {
  3303. pathActions.toSelectMode(svgedit.path.path.elem);
  3304. canvas.deleteSelectedElements();
  3305. return;
  3306. }
  3307. svgedit.path.path.init();
  3308. svgedit.path.path.clearSelection();
  3309. // TODO: Find right way to select point now
  3310. // path.selectPt(sel_pt);
  3311. if (window.opera) { // Opera repaints incorrectly
  3312. var cp = $(svgedit.path.path.elem);
  3313. cp.attr('d', cp.attr('d'));
  3314. }
  3315. svgedit.path.path.endChanges('Delete path node(s)');
  3316. },
  3317. smoothPolylineIntoPath: smoothPolylineIntoPath,
  3318. setSegType: function(v) {
  3319. svgedit.path.path.setSegType(v);
  3320. },
  3321. moveNode: function(attr, newValue) {
  3322. var sel_pts = svgedit.path.path.selected_pts;
  3323. if (!sel_pts.length) {return;}
  3324. svgedit.path.path.storeD();
  3325. // Get first selected point
  3326. var seg = svgedit.path.path.segs[sel_pts[0]];
  3327. var diff = {x:0, y:0};
  3328. diff[attr] = newValue - seg.item[attr];
  3329. seg.move(diff.x, diff.y);
  3330. svgedit.path.path.endChanges('Move path point');
  3331. },
  3332. fixEnd: function(elem) {
  3333. // Adds an extra segment if the last seg before a Z doesn't end
  3334. // at its M point
  3335. // M0,0 L0,100 L100,100 z
  3336. var segList = elem.pathSegList;
  3337. var len = segList.numberOfItems;
  3338. var i, last_m;
  3339. for (i = 0; i < len; ++i) {
  3340. var item = segList.getItem(i);
  3341. if (item.pathSegType === 2) {
  3342. last_m = item;
  3343. }
  3344. if (item.pathSegType === 1) {
  3345. var prev = segList.getItem(i-1);
  3346. if (prev.x != last_m.x || prev.y != last_m.y) {
  3347. // Add an L segment here
  3348. var newseg = elem.createSVGPathSegLinetoAbs(last_m.x, last_m.y);
  3349. svgedit.path.insertItemBefore(elem, newseg, i);
  3350. // Can this be done better?
  3351. pathActions.fixEnd(elem);
  3352. break;
  3353. }
  3354. }
  3355. }
  3356. if (svgedit.browser.isWebkit()) {resetD(elem);}
  3357. },
  3358. // Convert a path to one with only absolute or relative values
  3359. convertPath: function(path, toRel) {
  3360. var i;
  3361. var segList = path.pathSegList;
  3362. var len = segList.numberOfItems;
  3363. var curx = 0, cury = 0;
  3364. var d = '';
  3365. var last_m = null;
  3366. for (i = 0; i < len; ++i) {
  3367. var seg = segList.getItem(i);
  3368. // if these properties are not in the segment, set them to zero
  3369. var x = seg.x || 0,
  3370. y = seg.y || 0,
  3371. x1 = seg.x1 || 0,
  3372. y1 = seg.y1 || 0,
  3373. x2 = seg.x2 || 0,
  3374. y2 = seg.y2 || 0;
  3375. var type = seg.pathSegType;
  3376. var letter = pathMap[type]['to'+(toRel?'Lower':'Upper')+'Case']();
  3377. var addToD = function(pnts, more, last) {
  3378. var str = '';
  3379. more = more ? ' ' + more.join(' ') : '';
  3380. last = last ? ' ' + svgedit.units.shortFloat(last) : '';
  3381. $.each(pnts, function(i, pnt) {
  3382. pnts[i] = svgedit.units.shortFloat(pnt);
  3383. });
  3384. d += letter + pnts.join(' ') + more + last;
  3385. };
  3386. switch (type) {
  3387. case 1: // z,Z closepath (Z/z)
  3388. d += 'z';
  3389. break;
  3390. case 12: // absolute horizontal line (H)
  3391. x -= curx;
  3392. case 13: // relative horizontal line (h)
  3393. if (toRel) {
  3394. curx += x;
  3395. letter = 'l';
  3396. } else {
  3397. x += curx;
  3398. curx = x;
  3399. letter = 'L';
  3400. }
  3401. // Convert to "line" for easier editing
  3402. addToD([[x, cury]]);
  3403. break;
  3404. case 14: // absolute vertical line (V)
  3405. y -= cury;
  3406. case 15: // relative vertical line (v)
  3407. if (toRel) {
  3408. cury += y;
  3409. letter = 'l';
  3410. } else {
  3411. y += cury;
  3412. cury = y;
  3413. letter = 'L';
  3414. }
  3415. // Convert to "line" for easier editing
  3416. addToD([[curx, y]]);
  3417. break;
  3418. case 2: // absolute move (M)
  3419. case 4: // absolute line (L)
  3420. case 18: // absolute smooth quad (T)
  3421. x -= curx;
  3422. y -= cury;
  3423. case 5: // relative line (l)
  3424. case 3: // relative move (m)
  3425. // If the last segment was a "z", this must be relative to
  3426. if (last_m && segList.getItem(i-1).pathSegType === 1 && !toRel) {
  3427. curx = last_m[0];
  3428. cury = last_m[1];
  3429. }
  3430. case 19: // relative smooth quad (t)
  3431. if (toRel) {
  3432. curx += x;
  3433. cury += y;
  3434. } else {
  3435. x += curx;
  3436. y += cury;
  3437. curx = x;
  3438. cury = y;
  3439. }
  3440. if (type === 3) {last_m = [curx, cury];}
  3441. addToD([[x, y]]);
  3442. break;
  3443. case 6: // absolute cubic (C)
  3444. x -= curx; x1 -= curx; x2 -= curx;
  3445. y -= cury; y1 -= cury; y2 -= cury;
  3446. case 7: // relative cubic (c)
  3447. if (toRel) {
  3448. curx += x;
  3449. cury += y;
  3450. } else {
  3451. x += curx; x1 += curx; x2 += curx;
  3452. y += cury; y1 += cury; y2 += cury;
  3453. curx = x;
  3454. cury = y;
  3455. }
  3456. addToD([[x1, y1], [x2, y2], [x, y]]);
  3457. break;
  3458. case 8: // absolute quad (Q)
  3459. x -= curx; x1 -= curx;
  3460. y -= cury; y1 -= cury;
  3461. case 9: // relative quad (q)
  3462. if (toRel) {
  3463. curx += x;
  3464. cury += y;
  3465. } else {
  3466. x += curx; x1 += curx;
  3467. y += cury; y1 += cury;
  3468. curx = x;
  3469. cury = y;
  3470. }
  3471. addToD([[x1, y1],[x, y]]);
  3472. break;
  3473. case 10: // absolute elliptical arc (A)
  3474. x -= curx;
  3475. y -= cury;
  3476. case 11: // relative elliptical arc (a)
  3477. if (toRel) {
  3478. curx += x;
  3479. cury += y;
  3480. } else {
  3481. x += curx;
  3482. y += cury;
  3483. curx = x;
  3484. cury = y;
  3485. }
  3486. addToD([[seg.r1, seg.r2]], [
  3487. seg.angle,
  3488. (seg.largeArcFlag ? 1 : 0),
  3489. (seg.sweepFlag ? 1 : 0)
  3490. ], [x, y]
  3491. );
  3492. break;
  3493. case 16: // absolute smooth cubic (S)
  3494. x -= curx; x2 -= curx;
  3495. y -= cury; y2 -= cury;
  3496. case 17: // relative smooth cubic (s)
  3497. if (toRel) {
  3498. curx += x;
  3499. cury += y;
  3500. } else {
  3501. x += curx; x2 += curx;
  3502. y += cury; y2 += cury;
  3503. curx = x;
  3504. cury = y;
  3505. }
  3506. addToD([[x2, y2],[x, y]]);
  3507. break;
  3508. } // switch on path segment type
  3509. } // for each segment
  3510. return d;
  3511. }
  3512. };
  3513. }();
  3514. // end pathActions
  3515. // Group: Serialization
  3516. // Function: removeUnusedDefElems
  3517. // Looks at DOM elements inside the <defs> to see if they are referred to,
  3518. // removes them from the DOM if they are not.
  3519. //
  3520. // Returns:
  3521. // The amount of elements that were removed
  3522. var removeUnusedDefElems = this.removeUnusedDefElems = function() {
  3523. var defs = svgcontent.getElementsByTagNameNS(NS.SVG, 'defs');
  3524. if (!defs || !defs.length) {return 0;}
  3525. // if (!defs.firstChild) {return;}
  3526. var defelem_uses = [],
  3527. numRemoved = 0;
  3528. var attrs = ['fill', 'stroke', 'filter', 'marker-start', 'marker-mid', 'marker-end'];
  3529. var alen = attrs.length;
  3530. var all_els = svgcontent.getElementsByTagNameNS(NS.SVG, '*');
  3531. var all_len = all_els.length;
  3532. var i, j;
  3533. for (i = 0; i < all_len; i++) {
  3534. var el = all_els[i];
  3535. for (j = 0; j < alen; j++) {
  3536. var ref = svgedit.utilities.getUrlFromAttr(el.getAttribute(attrs[j]));
  3537. if (ref) {
  3538. defelem_uses.push(ref.substr(1));
  3539. }
  3540. }
  3541. // gradients can refer to other gradients
  3542. var href = getHref(el);
  3543. if (href && href.indexOf('#') === 0) {
  3544. defelem_uses.push(href.substr(1));
  3545. }
  3546. }
  3547. var defelems = $(defs).find('linearGradient, radialGradient, filter, marker, svg, symbol');
  3548. i = defelems.length;
  3549. while (i--) {
  3550. var defelem = defelems[i];
  3551. var id = defelem.id;
  3552. if (defelem_uses.indexOf(id) < 0) {
  3553. // Not found, so remove (but remember)
  3554. removedElements[id] = defelem;
  3555. defelem.parentNode.removeChild(defelem);
  3556. numRemoved++;
  3557. }
  3558. }
  3559. return numRemoved;
  3560. };
  3561. // Function: svgCanvasToString
  3562. // Main function to set up the SVG content for output
  3563. //
  3564. // Returns:
  3565. // String containing the SVG image for output
  3566. this.svgCanvasToString = function() {
  3567. // keep calling it until there are none to remove
  3568. while (removeUnusedDefElems() > 0) {}
  3569. pathActions.clear(true);
  3570. // Keep SVG-Edit comment on top
  3571. $.each(svgcontent.childNodes, function(i, node) {
  3572. if (i && node.nodeType === 8 && node.data.indexOf('Created with') >= 0) {
  3573. svgcontent.insertBefore(node, svgcontent.firstChild);
  3574. }
  3575. });
  3576. // Move out of in-group editing mode
  3577. if (current_group) {
  3578. leaveContext();
  3579. selectOnly([current_group]);
  3580. }
  3581. var naked_svgs = [];
  3582. // Unwrap gsvg if it has no special attributes (only id and style)
  3583. $(svgcontent).find('g:data(gsvg)').each(function() {
  3584. var attrs = this.attributes;
  3585. var len = attrs.length;
  3586. var i;
  3587. for (i = 0; i < len; i++) {
  3588. if (attrs[i].nodeName == 'id' || attrs[i].nodeName == 'style') {
  3589. len--;
  3590. }
  3591. }
  3592. // No significant attributes, so ungroup
  3593. if (len <= 0) {
  3594. var svg = this.firstChild;
  3595. naked_svgs.push(svg);
  3596. $(this).replaceWith(svg);
  3597. }
  3598. });
  3599. var output = this.svgToString(svgcontent, 0);
  3600. // Rewrap gsvg
  3601. if (naked_svgs.length) {
  3602. $(naked_svgs).each(function() {
  3603. groupSvgElem(this);
  3604. });
  3605. }
  3606. return output;
  3607. };
  3608. // Function: svgToString
  3609. // Sub function ran on each SVG element to convert it to a string as desired
  3610. //
  3611. // Parameters:
  3612. // elem - The SVG element to convert
  3613. // indent - Integer with the amount of spaces to indent this tag
  3614. //
  3615. // Returns:
  3616. // String with the given element as an SVG tag
  3617. this.svgToString = function(elem, indent) {
  3618. var out = [],
  3619. toXml = svgedit.utilities.toXml;
  3620. var unit = curConfig.baseUnit;
  3621. var unit_re = new RegExp('^-?[\\d\\.]+' + unit + '$');
  3622. if (elem) {
  3623. cleanupElement(elem);
  3624. var attrs = elem.attributes,
  3625. attr,
  3626. i,
  3627. childs = elem.childNodes;
  3628. for (i = 0; i < indent; i++) {out.push(' ');}
  3629. out.push('<'); out.push(elem.nodeName);
  3630. if (elem.id === 'svgcontent') {
  3631. // Process root element separately
  3632. var res = getResolution();
  3633. var vb = '';
  3634. // TODO: Allow this by dividing all values by current baseVal
  3635. // Note that this also means we should properly deal with this on import
  3636. // if (curConfig.baseUnit !== 'px') {
  3637. // var unit = curConfig.baseUnit;
  3638. // var unit_m = svgedit.units.getTypeMap()[unit];
  3639. // res.w = svgedit.units.shortFloat(res.w / unit_m)
  3640. // res.h = svgedit.units.shortFloat(res.h / unit_m)
  3641. // vb = ' viewBox="' + [0, 0, res.w, res.h].join(' ') + '"';
  3642. // res.w += unit;
  3643. // res.h += unit;
  3644. // }
  3645. if (unit !== 'px') {
  3646. res.w = svgedit.units.convertUnit(res.w, unit) + unit;
  3647. res.h = svgedit.units.convertUnit(res.h, unit) + unit;
  3648. }
  3649. out.push(' width="' + res.w + '" height="' + res.h + '"' + vb + ' xmlns="'+NS.SVG+'"');
  3650. var nsuris = {};
  3651. // Check elements for namespaces, add if found
  3652. $(elem).find('*').andSelf().each(function() {
  3653. var el = this;
  3654. // for some elements have no attribute
  3655. var uri = this.namespaceURI;
  3656. if(uri && !nsuris[uri] && nsMap[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) {
  3657. nsuris[uri] = true;
  3658. out.push(' xmlns:' + nsMap[uri] + '="' + uri +'"');
  3659. }
  3660. $.each(this.attributes, function(i, attr) {
  3661. var uri = attr.namespaceURI;
  3662. if (uri && !nsuris[uri] && nsMap[uri] !== 'xmlns' && nsMap[uri] !== 'xml' ) {
  3663. nsuris[uri] = true;
  3664. out.push(' xmlns:' + nsMap[uri] + '="' + uri +'"');
  3665. }
  3666. });
  3667. });
  3668. i = attrs.length;
  3669. var attr_names = ['width', 'height', 'xmlns', 'x', 'y', 'viewBox', 'id', 'overflow'];
  3670. while (i--) {
  3671. attr = attrs.item(i);
  3672. var attrVal = toXml(attr.value);
  3673. // Namespaces have already been dealt with, so skip
  3674. if (attr.nodeName.indexOf('xmlns:') === 0) {continue;}
  3675. // only serialize attributes we don't use internally
  3676. if (attrVal != '' && attr_names.indexOf(attr.localName) == -1) {
  3677. if (!attr.namespaceURI || nsMap[attr.namespaceURI]) {
  3678. out.push(' ');
  3679. out.push(attr.nodeName); out.push('="');
  3680. out.push(attrVal); out.push('"');
  3681. }
  3682. }
  3683. }
  3684. } else {
  3685. // Skip empty defs
  3686. if (elem.nodeName === 'defs' && !elem.firstChild) {return;}
  3687. var moz_attrs = ['-moz-math-font-style', '_moz-math-font-style'];
  3688. for (i = attrs.length - 1; i >= 0; i--) {
  3689. attr = attrs.item(i);
  3690. var attrVal = toXml(attr.value);
  3691. //remove bogus attributes added by Gecko
  3692. if (moz_attrs.indexOf(attr.localName) >= 0) {continue;}
  3693. if (attrVal != '') {
  3694. if (attrVal.indexOf('pointer-events') === 0) {continue;}
  3695. if (attr.localName === 'class' && attrVal.indexOf('se_') === 0) {continue;}
  3696. out.push(' ');
  3697. if (attr.localName === 'd') {attrVal = pathActions.convertPath(elem, true);}
  3698. if (!isNaN(attrVal)) {
  3699. attrVal = svgedit.units.shortFloat(attrVal);
  3700. } else if (unit_re.test(attrVal)) {
  3701. attrVal = svgedit.units.shortFloat(attrVal) + unit;
  3702. }
  3703. // Embed images when saving
  3704. if (save_options.apply
  3705. && elem.nodeName === 'image'
  3706. && attr.localName === 'href'
  3707. && save_options.images
  3708. && save_options.images === 'embed')
  3709. {
  3710. var img = encodableImages[attrVal];
  3711. if (img) {attrVal = img;}
  3712. }
  3713. // map various namespaces to our fixed namespace prefixes
  3714. // (the default xmlns attribute itself does not get a prefix)
  3715. if (!attr.namespaceURI || attr.namespaceURI == NS.SVG || nsMap[attr.namespaceURI]) {
  3716. out.push(attr.nodeName); out.push('="');
  3717. out.push(attrVal); out.push('"');
  3718. }
  3719. }
  3720. }
  3721. }
  3722. if (elem.hasChildNodes()) {
  3723. out.push('>');
  3724. indent++;
  3725. var bOneLine = false;
  3726. for (i = 0; i < childs.length; i++) {
  3727. var child = childs.item(i);
  3728. switch(child.nodeType) {
  3729. case 1: // element node
  3730. out.push('\n');
  3731. out.push(this.svgToString(childs.item(i), indent));
  3732. break;
  3733. case 3: // text node
  3734. var str = child.nodeValue.replace(/^\s+|\s+$/g, '');
  3735. if (str != '') {
  3736. bOneLine = true;
  3737. out.push(String(toXml(str)));
  3738. }
  3739. break;
  3740. case 4: // cdata node
  3741. out.push('\n');
  3742. out.push(new Array(indent+1).join(' '));
  3743. out.push('<![CDATA[');
  3744. out.push(child.nodeValue);
  3745. out.push(']]>');
  3746. break;
  3747. case 8: // comment
  3748. out.push('\n');
  3749. out.push(new Array(indent+1).join(' '));
  3750. out.push('<!--');
  3751. out.push(child.data);
  3752. out.push('-->');
  3753. break;
  3754. } // switch on node type
  3755. }
  3756. indent--;
  3757. if (!bOneLine) {
  3758. out.push('\n');
  3759. for (i = 0; i < indent; i++) {out.push(' ');}
  3760. }
  3761. out.push('</'); out.push(elem.nodeName); out.push('>');
  3762. } else {
  3763. out.push('/>');
  3764. }
  3765. }
  3766. return out.join('');
  3767. }; // end svgToString()
  3768. // Function: embedImage
  3769. // Converts a given image file to a data URL when possible, then runs a given callback
  3770. //
  3771. // Parameters:
  3772. // val - String with the path/URL of the image
  3773. // callback - Optional function to run when image data is found, supplies the
  3774. // result (data URL or false) as first parameter.
  3775. this.embedImage = function(val, callback) {
  3776. // load in the image and once it's loaded, get the dimensions
  3777. $(new Image()).load(function() {
  3778. // create a canvas the same size as the raster image
  3779. var canvas = document.createElement('canvas');
  3780. canvas.width = this.width;
  3781. canvas.height = this.height;
  3782. // load the raster image into the canvas
  3783. canvas.getContext('2d').drawImage(this, 0, 0);
  3784. // retrieve the data: URL
  3785. try {
  3786. var urldata = ';svgedit_url=' + encodeURIComponent(val);
  3787. urldata = canvas.toDataURL().replace(';base64', urldata+';base64');
  3788. encodableImages[val] = urldata;
  3789. } catch(e) {
  3790. encodableImages[val] = false;
  3791. }
  3792. last_good_img_url = val;
  3793. if (callback) {callback(encodableImages[val]);}
  3794. }).attr('src', val);
  3795. };
  3796. // Function: setGoodImage
  3797. // Sets a given URL to be a "last good image" URL
  3798. this.setGoodImage = function(val) {
  3799. last_good_img_url = val;
  3800. };
  3801. this.open = function() {
  3802. // Nothing by default, handled by optional widget/extension
  3803. };
  3804. // Function: save
  3805. // Serializes the current drawing into SVG XML text and returns it to the 'saved' handler.
  3806. // This function also includes the XML prolog. Clients of the SvgCanvas bind their save
  3807. // function to the 'saved' event.
  3808. //
  3809. // Returns:
  3810. // Nothing
  3811. this.save = function(opts) {
  3812. // remove the selected outline before serializing
  3813. clearSelection();
  3814. // Update save options if provided
  3815. if (opts) {$.extend(save_options, opts);}
  3816. save_options.apply = true;
  3817. // no need for doctype, see http://jwatt.org/svg/authoring/#doctype-declaration
  3818. var str = this.svgCanvasToString();
  3819. call('saved', str);
  3820. };
  3821. function getIssues () {
  3822. // remove the selected outline before serializing
  3823. clearSelection();
  3824. // Check for known CanVG issues
  3825. var issues = [];
  3826. // Selector and notice
  3827. var issue_list = {
  3828. 'feGaussianBlur': uiStrings.exportNoBlur,
  3829. 'foreignObject': uiStrings.exportNoforeignObject,
  3830. '[stroke-dasharray]': uiStrings.exportNoDashArray
  3831. };
  3832. var content = $(svgcontent);
  3833. // Add font/text check if Canvas Text API is not implemented
  3834. if (!('font' in $('<canvas>')[0].getContext('2d'))) {
  3835. issue_list.text = uiStrings.exportNoText;
  3836. }
  3837. $.each(issue_list, function(sel, descr) {
  3838. if (content.find(sel).length) {
  3839. issues.push(descr);
  3840. }
  3841. });
  3842. return issues;
  3843. }
  3844. // Function: rasterExport
  3845. // Generates a Data URL based on the current image, then calls "exported"
  3846. // with an object including the string, image information, and any issues found
  3847. this.rasterExport = function(imgType, quality, exportWindowName) {
  3848. var mimeType = 'image/' + imgType.toLowerCase();
  3849. var issues = getIssues();
  3850. var str = this.svgCanvasToString();
  3851. svgedit.utilities.buildCanvgCallback(function () {
  3852. var type = imgType || 'PNG';
  3853. if (!$('#export_canvas').length) {
  3854. $('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
  3855. }
  3856. var c = $('#export_canvas')[0];
  3857. c.width = svgCanvas.contentW;
  3858. c.height = svgCanvas.contentH;
  3859. canvg(c, str, {renderCallback: function() {
  3860. var dataURLType = (type === 'ICO' ? 'BMP' : type).toLowerCase();
  3861. var datauri = quality ? c.toDataURL('image/' + dataURLType, quality) : c.toDataURL('image/' + dataURLType);
  3862. call('exported', {datauri: datauri, svg: str, issues: issues, type: imgType, mimeType: mimeType, quality: quality, exportWindowName: exportWindowName});
  3863. }});
  3864. })();
  3865. };
  3866. this.exportPDF = function (exportWindowName, outputType) {
  3867. var that = this;
  3868. svgedit.utilities.buildJSPDFCallback(function () {
  3869. var res = getResolution();
  3870. var orientation = res.w > res.h ? 'landscape' : 'portrait';
  3871. var units = 'pt'; // curConfig.baseUnit; // We could use baseUnit, but that is presumably not intended for export purposes
  3872. var doc = jsPDF({
  3873. orientation: orientation,
  3874. unit: units,
  3875. format: [res.w, res.h]
  3876. // , compressPdf: true
  3877. }); // Todo: Give options to use predefined jsPDF formats like "a4", etc. from pull-down (with option to keep customizable)
  3878. var docTitle = getDocumentTitle();
  3879. doc.setProperties({
  3880. title: docTitle/*,
  3881. subject: '',
  3882. author: '',
  3883. keywords: '',
  3884. creator: ''*/
  3885. });
  3886. var issues = getIssues();
  3887. var str = that.svgCanvasToString();
  3888. doc.addSVG(str, 0, 0);
  3889. // doc.output('save'); // Works to open in a new
  3890. // window; todo: configure this and other export
  3891. // options to optionally work in this manner as
  3892. // opposed to opening a new tab
  3893. var obj = {svg: str, issues: issues, exportWindowName: exportWindowName};
  3894. var method = outputType || 'dataurlstring';
  3895. obj[method] = doc.output(method);
  3896. call('exportedPDF', obj);
  3897. })();
  3898. };
  3899. // Function: getSvgString
  3900. // Returns the current drawing as raw SVG XML text.
  3901. //
  3902. // Returns:
  3903. // The current drawing as raw SVG XML text.
  3904. this.getSvgString = function() {
  3905. save_options.apply = false;
  3906. return this.svgCanvasToString();
  3907. };
  3908. // Function: randomizeIds
  3909. // This function determines whether to use a nonce in the prefix, when
  3910. // generating IDs for future documents in SVG-Edit.
  3911. //
  3912. // Parameters:
  3913. // an optional boolean, which, if true, adds a nonce to the prefix. Thus
  3914. // svgCanvas.randomizeIds() <==> svgCanvas.randomizeIds(true)
  3915. //
  3916. // if you're controlling SVG-Edit externally, and want randomized IDs, call
  3917. // this BEFORE calling svgCanvas.setSvgString
  3918. //
  3919. this.randomizeIds = function(enableRandomization) {
  3920. if (arguments.length > 0 && enableRandomization == false) {
  3921. svgedit.draw.randomizeIds(false, getCurrentDrawing());
  3922. } else {
  3923. svgedit.draw.randomizeIds(true, getCurrentDrawing());
  3924. }
  3925. };
  3926. // Function: uniquifyElems
  3927. // Ensure each element has a unique ID
  3928. //
  3929. // Parameters:
  3930. // g - The parent element of the tree to give unique IDs
  3931. var uniquifyElems = this.uniquifyElems = function(g) {
  3932. var ids = {};
  3933. // TODO: Handle markers and connectors. These are not yet re-identified properly
  3934. // as their referring elements do not get remapped.
  3935. //
  3936. // <marker id='se_marker_end_svg_7'/>
  3937. // <polyline id='svg_7' se:connector='svg_1 svg_6' marker-end='url(#se_marker_end_svg_7)'/>
  3938. //
  3939. // Problem #1: if svg_1 gets renamed, we do not update the polyline's se:connector attribute
  3940. // Problem #2: if the polyline svg_7 gets renamed, we do not update the marker id nor the polyline's marker-end attribute
  3941. var ref_elems = ['filter', 'linearGradient', 'pattern', 'radialGradient', 'symbol', 'textPath', 'use'];
  3942. svgedit.utilities.walkTree(g, function(n) {
  3943. // if it's an element node
  3944. if (n.nodeType == 1) {
  3945. // and the element has an ID
  3946. if (n.id) {
  3947. // and we haven't tracked this ID yet
  3948. if (!(n.id in ids)) {
  3949. // add this id to our map
  3950. ids[n.id] = {elem:null, attrs:[], hrefs:[]};
  3951. }
  3952. ids[n.id].elem = n;
  3953. }
  3954. // now search for all attributes on this element that might refer
  3955. // to other elements
  3956. $.each(ref_attrs, function(i, attr) {
  3957. var attrnode = n.getAttributeNode(attr);
  3958. if (attrnode) {
  3959. // the incoming file has been sanitized, so we should be able to safely just strip off the leading #
  3960. var url = svgedit.utilities.getUrlFromAttr(attrnode.value),
  3961. refid = url ? url.substr(1) : null;
  3962. if (refid) {
  3963. if (!(refid in ids)) {
  3964. // add this id to our map
  3965. ids[refid] = {elem:null, attrs:[], hrefs:[]};
  3966. }
  3967. ids[refid].attrs.push(attrnode);
  3968. }
  3969. }
  3970. });
  3971. // check xlink:href now
  3972. var href = svgedit.utilities.getHref(n);
  3973. // TODO: what if an <image> or <a> element refers to an element internally?
  3974. if (href && ref_elems.indexOf(n.nodeName) >= 0) {
  3975. var refid = href.substr(1);
  3976. if (refid) {
  3977. if (!(refid in ids)) {
  3978. // add this id to our map
  3979. ids[refid] = {elem:null, attrs:[], hrefs:[]};
  3980. }
  3981. ids[refid].hrefs.push(n);
  3982. }
  3983. }
  3984. }
  3985. });
  3986. // in ids, we now have a map of ids, elements and attributes, let's re-identify
  3987. var oldid;
  3988. for (oldid in ids) {
  3989. if (!oldid) {continue;}
  3990. var elem = ids[oldid].elem;
  3991. if (elem) {
  3992. var newid = getNextId();
  3993. // assign element its new id
  3994. elem.id = newid;
  3995. // remap all url() attributes
  3996. var attrs = ids[oldid].attrs;
  3997. var j = attrs.length;
  3998. while (j--) {
  3999. var attr = attrs[j];
  4000. attr.ownerElement.setAttribute(attr.name, 'url(#' + newid + ')');
  4001. }
  4002. // remap all href attributes
  4003. var hreffers = ids[oldid].hrefs;
  4004. var k = hreffers.length;
  4005. while (k--) {
  4006. var hreffer = hreffers[k];
  4007. svgedit.utilities.setHref(hreffer, '#' + newid);
  4008. }
  4009. }
  4010. }
  4011. };
  4012. // Function setUseData
  4013. // Assigns reference data for each use element
  4014. var setUseData = this.setUseData = function(parent) {
  4015. var elems = $(parent);
  4016. if (parent.tagName !== 'use') {
  4017. elems = elems.find('use');
  4018. }
  4019. elems.each(function() {
  4020. var id = getHref(this).substr(1);
  4021. var ref_elem = svgedit.utilities.getElem(id);
  4022. if (!ref_elem) {return;}
  4023. $(this).data('ref', ref_elem);
  4024. if (ref_elem.tagName == 'symbol' || ref_elem.tagName == 'svg') {
  4025. $(this).data('symbol', ref_elem).data('ref', ref_elem);
  4026. }
  4027. });
  4028. };
  4029. // Function convertGradients
  4030. // Converts gradients from userSpaceOnUse to objectBoundingBox
  4031. var convertGradients = this.convertGradients = function(elem) {
  4032. var elems = $(elem).find('linearGradient, radialGradient');
  4033. if (!elems.length && svgedit.browser.isWebkit()) {
  4034. // Bug in webkit prevents regular *Gradient selector search
  4035. elems = $(elem).find('*').filter(function() {
  4036. return (this.tagName.indexOf('Gradient') >= 0);
  4037. });
  4038. }
  4039. elems.each(function() {
  4040. var grad = this;
  4041. if ($(grad).attr('gradientUnits') === 'userSpaceOnUse') {
  4042. // TODO: Support more than one element with this ref by duplicating parent grad
  4043. var elems = $(svgcontent).find('[fill="url(#' + grad.id + ')"],[stroke="url(#' + grad.id + ')"]');
  4044. if (!elems.length) {return;}
  4045. // get object's bounding box
  4046. var bb = svgedit.utilities.getBBox(elems[0]);
  4047. // This will occur if the element is inside a <defs> or a <symbol>,
  4048. // in which we shouldn't need to convert anyway.
  4049. if (!bb) {return;}
  4050. if (grad.tagName === 'linearGradient') {
  4051. var g_coords = $(grad).attr(['x1', 'y1', 'x2', 'y2']);
  4052. // If has transform, convert
  4053. var tlist = grad.gradientTransform.baseVal;
  4054. if (tlist && tlist.numberOfItems > 0) {
  4055. var m = svgedit.math.transformListToTransform(tlist).matrix;
  4056. var pt1 = svgedit.math.transformPoint(g_coords.x1, g_coords.y1, m);
  4057. var pt2 = svgedit.math.transformPoint(g_coords.x2, g_coords.y2, m);
  4058. g_coords.x1 = pt1.x;
  4059. g_coords.y1 = pt1.y;
  4060. g_coords.x2 = pt2.x;
  4061. g_coords.y2 = pt2.y;
  4062. grad.removeAttribute('gradientTransform');
  4063. }
  4064. $(grad).attr({
  4065. x1: (g_coords.x1 - bb.x) / bb.width,
  4066. y1: (g_coords.y1 - bb.y) / bb.height,
  4067. x2: (g_coords.x2 - bb.x) / bb.width,
  4068. y2: (g_coords.y2 - bb.y) / bb.height
  4069. });
  4070. grad.removeAttribute('gradientUnits');
  4071. }
  4072. // else {
  4073. // Note: radialGradient elements cannot be easily converted
  4074. // because userSpaceOnUse will keep circular gradients, while
  4075. // objectBoundingBox will x/y scale the gradient according to
  4076. // its bbox.
  4077. // For now we'll do nothing, though we should probably have
  4078. // the gradient be updated as the element is moved, as
  4079. // inkscape/illustrator do.
  4080. // var g_coords = $(grad).attr(['cx', 'cy', 'r']);
  4081. //
  4082. // $(grad).attr({
  4083. // cx: (g_coords.cx - bb.x) / bb.width,
  4084. // cy: (g_coords.cy - bb.y) / bb.height,
  4085. // r: g_coords.r
  4086. // });
  4087. //
  4088. // grad.removeAttribute('gradientUnits');
  4089. // }
  4090. }
  4091. });
  4092. };
  4093. // Function: convertToGroup
  4094. // Converts selected/given <use> or child SVG element to a group
  4095. var convertToGroup = this.convertToGroup = function(elem) {
  4096. if (!elem) {
  4097. elem = selectedElements[0];
  4098. }
  4099. var $elem = $(elem);
  4100. var batchCmd = new svgedit.history.BatchCommand();
  4101. var ts;
  4102. if ($elem.data('gsvg')) {
  4103. // Use the gsvg as the new group
  4104. var svg = elem.firstChild;
  4105. var pt = $(svg).attr(['x', 'y']);
  4106. $(elem.firstChild.firstChild).unwrap();
  4107. $(elem).removeData('gsvg');
  4108. var tlist = svgedit.transformlist.getTransformList(elem);
  4109. var xform = svgroot.createSVGTransform();
  4110. xform.setTranslate(pt.x, pt.y);
  4111. tlist.appendItem(xform);
  4112. svgedit.recalculate.recalculateDimensions(elem);
  4113. call('selected', [elem]);
  4114. } else if ($elem.data('symbol')) {
  4115. elem = $elem.data('symbol');
  4116. ts = $elem.attr('transform');
  4117. var pos = $elem.attr(['x', 'y']);
  4118. var vb = elem.getAttribute('viewBox');
  4119. if (vb) {
  4120. var nums = vb.split(' ');
  4121. pos.x -= +nums[0];
  4122. pos.y -= +nums[1];
  4123. }
  4124. // Not ideal, but works
  4125. ts += ' translate(' + (pos.x || 0) + ',' + (pos.y || 0) + ')';
  4126. var prev = $elem.prev();
  4127. // Remove <use> element
  4128. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand($elem[0], $elem[0].nextSibling, $elem[0].parentNode));
  4129. $elem.remove();
  4130. // See if other elements reference this symbol
  4131. var has_more = $(svgcontent).find('use:data(symbol)').length;
  4132. var g = svgdoc.createElementNS(NS.SVG, 'g');
  4133. var childs = elem.childNodes;
  4134. var i;
  4135. for (i = 0; i < childs.length; i++) {
  4136. g.appendChild(childs[i].cloneNode(true));
  4137. }
  4138. // Duplicate the gradients for Gecko, since they weren't included in the <symbol>
  4139. if (svgedit.browser.isGecko()) {
  4140. var dupeGrads = $(svgedit.utilities.findDefs()).children('linearGradient,radialGradient,pattern').clone();
  4141. $(g).append(dupeGrads);
  4142. }
  4143. if (ts) {
  4144. g.setAttribute('transform', ts);
  4145. }
  4146. var parent = elem.parentNode;
  4147. uniquifyElems(g);
  4148. // Put the dupe gradients back into <defs> (after uniquifying them)
  4149. if (svgedit.browser.isGecko()) {
  4150. $(findDefs()).append( $(g).find('linearGradient,radialGradient,pattern') );
  4151. }
  4152. // now give the g itself a new id
  4153. g.id = getNextId();
  4154. prev.after(g);
  4155. if (parent) {
  4156. if (!has_more) {
  4157. // remove symbol/svg element
  4158. var nextSibling = elem.nextSibling;
  4159. parent.removeChild(elem);
  4160. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(elem, nextSibling, parent));
  4161. }
  4162. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(g));
  4163. }
  4164. setUseData(g);
  4165. if (svgedit.browser.isGecko()) {
  4166. convertGradients(svgedit.utilities.findDefs());
  4167. } else {
  4168. convertGradients(g);
  4169. }
  4170. // recalculate dimensions on the top-level children so that unnecessary transforms
  4171. // are removed
  4172. svgedit.utilities.walkTreePost(g, function(n){
  4173. try {
  4174. svgedit.recalculate.recalculateDimensions(n);
  4175. } catch(e) {
  4176. console.log(e);
  4177. }
  4178. });
  4179. // Give ID for any visible element missing one
  4180. $(g).find(visElems).each(function() {
  4181. if (!this.id) {this.id = getNextId();}
  4182. });
  4183. selectOnly([g]);
  4184. var cm = pushGroupProperties(g, true);
  4185. if (cm) {
  4186. batchCmd.addSubCommand(cm);
  4187. }
  4188. addCommandToHistory(batchCmd);
  4189. } else {
  4190. console.log('Unexpected element to ungroup:', elem);
  4191. }
  4192. };
  4193. //
  4194. // Function: setSvgString
  4195. // This function sets the current drawing as the input SVG XML.
  4196. //
  4197. // Parameters:
  4198. // xmlString - The SVG as XML text.
  4199. //
  4200. // Returns:
  4201. // This function returns false if the set was unsuccessful, true otherwise.
  4202. this.setSvgString = function(xmlString) {
  4203. try {
  4204. // convert string into XML document
  4205. var newDoc = svgedit.utilities.text2xml(xmlString);
  4206. this.prepareSvg(newDoc);
  4207. var batchCmd = new svgedit.history.BatchCommand('Change Source');
  4208. // remove old svg document
  4209. var nextSibling = svgcontent.nextSibling;
  4210. var oldzoom = svgroot.removeChild(svgcontent);
  4211. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(oldzoom, nextSibling, svgroot));
  4212. // set new svg document
  4213. // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode()
  4214. if (svgdoc.adoptNode) {
  4215. svgcontent = svgdoc.adoptNode(newDoc.documentElement);
  4216. }
  4217. else {
  4218. svgcontent = svgdoc.importNode(newDoc.documentElement, true);
  4219. }
  4220. svgroot.appendChild(svgcontent);
  4221. var content = $(svgcontent);
  4222. canvas.current_drawing_ = new svgedit.draw.Drawing(svgcontent, idprefix);
  4223. // retrieve or set the nonce
  4224. var nonce = getCurrentDrawing().getNonce();
  4225. if (nonce) {
  4226. call('setnonce', nonce);
  4227. } else {
  4228. call('unsetnonce');
  4229. }
  4230. // change image href vals if possible
  4231. content.find('image').each(function() {
  4232. var image = this;
  4233. preventClickDefault(image);
  4234. var val = getHref(this);
  4235. if (val) {
  4236. if (val.indexOf('data:') === 0) {
  4237. // Check if an SVG-edit data URI
  4238. var m = val.match(/svgedit_url=(.*?);/);
  4239. if (m) {
  4240. var url = decodeURIComponent(m[1]);
  4241. $(new Image()).load(function () {
  4242. image.setAttributeNS(NS.XLINK, 'xlink:href', url);
  4243. }).attr('src', url);
  4244. }
  4245. }
  4246. // Add to encodableImages if it loads
  4247. canvas.embedImage(val);
  4248. }
  4249. });
  4250. // Wrap child SVGs in group elements
  4251. content.find('svg').each(function() {
  4252. // Skip if it's in a <defs>
  4253. if ($(this).closest('defs').length) {return;}
  4254. uniquifyElems(this);
  4255. // Check if it already has a gsvg group
  4256. var pa = this.parentNode;
  4257. if (pa.childNodes.length === 1 && pa.nodeName === 'g') {
  4258. $(pa).data('gsvg', this);
  4259. pa.id = pa.id || getNextId();
  4260. } else {
  4261. groupSvgElem(this);
  4262. }
  4263. });
  4264. // For Firefox: Put all paint elems in defs
  4265. if (svgedit.browser.isGecko()) {
  4266. content.find('linearGradient, radialGradient, pattern').appendTo(svgedit.utilities.findDefs());
  4267. }
  4268. // Set ref element for <use> elements
  4269. // TODO: This should also be done if the object is re-added through "redo"
  4270. setUseData(content);
  4271. convertGradients(content[0]);
  4272. // recalculate dimensions on the top-level children so that unnecessary transforms
  4273. // are removed
  4274. svgedit.utilities.walkTreePost(svgcontent, function(n) {
  4275. try {
  4276. svgedit.recalculate.recalculateDimensions(n);
  4277. } catch(e) {
  4278. console.log(e);
  4279. }
  4280. });
  4281. var attrs = {
  4282. id: 'svgcontent',
  4283. overflow: curConfig.show_outside_canvas ? 'visible' : 'hidden'
  4284. };
  4285. var percs = false;
  4286. // determine proper size
  4287. if (content.attr('viewBox')) {
  4288. var vb = content.attr('viewBox').split(' ');
  4289. attrs.width = vb[2];
  4290. attrs.height = vb[3];
  4291. }
  4292. // handle content that doesn't have a viewBox
  4293. else {
  4294. $.each(['width', 'height'], function(i, dim) {
  4295. // Set to 100 if not given
  4296. var val = content.attr(dim);
  4297. if (!val) {val = '100%';}
  4298. if (String(val).substr(-1) === '%') {
  4299. // Use user units if percentage given
  4300. percs = true;
  4301. } else {
  4302. attrs[dim] = svgedit.units.convertToNum(dim, val);
  4303. }
  4304. });
  4305. }
  4306. // identify layers
  4307. identifyLayers();
  4308. // Give ID for any visible layer children missing one
  4309. content.children().find(visElems).each(function() {
  4310. if (!this.id) {this.id = getNextId();}
  4311. });
  4312. // Percentage width/height, so let's base it on visible elements
  4313. if (percs) {
  4314. var bb = getStrokedBBox();
  4315. attrs.width = bb.width + bb.x;
  4316. attrs.height = bb.height + bb.y;
  4317. }
  4318. // Just in case negative numbers are given or
  4319. // result from the percs calculation
  4320. if (attrs.width <= 0) {attrs.width = 100;}
  4321. if (attrs.height <= 0) {attrs.height = 100;}
  4322. content.attr(attrs);
  4323. this.contentW = attrs.width;
  4324. this.contentH = attrs.height;
  4325. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(svgcontent));
  4326. // update root to the correct size
  4327. var changes = content.attr(['width', 'height']);
  4328. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(svgroot, changes));
  4329. // reset zoom
  4330. current_zoom = 1;
  4331. // reset transform lists
  4332. svgedit.transformlist.resetListMap();
  4333. clearSelection();
  4334. svgedit.path.clearData();
  4335. svgroot.appendChild(selectorManager.selectorParentGroup);
  4336. addCommandToHistory(batchCmd);
  4337. call('changed', [svgcontent]);
  4338. } catch(e) {
  4339. console.log(e);
  4340. return false;
  4341. }
  4342. return true;
  4343. };
  4344. // Function: importSvgString
  4345. // This function imports the input SVG XML as a <symbol> in the <defs>, then adds a
  4346. // <use> to the current layer.
  4347. //
  4348. // Parameters:
  4349. // xmlString - The SVG as XML text.
  4350. //
  4351. // Returns:
  4352. // This function returns false if the import was unsuccessful, true otherwise.
  4353. // TODO:
  4354. // * properly handle if namespace is introduced by imported content (must add to svgcontent
  4355. // and update all prefixes in the imported node)
  4356. // * properly handle recalculating dimensions, recalculateDimensions() doesn't handle
  4357. // arbitrary transform lists, but makes some assumptions about how the transform list
  4358. // was obtained
  4359. // * import should happen in top-left of current zoomed viewport
  4360. this.importSvgString = function(xmlString) {
  4361. var j, ts;
  4362. try {
  4363. // Get unique ID
  4364. var uid = svgedit.utilities.encode64(xmlString.length + xmlString).substr(0,32);
  4365. var useExisting = false;
  4366. // Look for symbol and make sure symbol exists in image
  4367. if (import_ids[uid]) {
  4368. if ( $(import_ids[uid].symbol).parents('#svgroot').length ) {
  4369. useExisting = true;
  4370. }
  4371. }
  4372. var batchCmd = new svgedit.history.BatchCommand('Import Image');
  4373. var symbol;
  4374. if (useExisting) {
  4375. symbol = import_ids[uid].symbol;
  4376. ts = import_ids[uid].xform;
  4377. } else {
  4378. // convert string into XML document
  4379. var newDoc = svgedit.utilities.text2xml(xmlString);
  4380. this.prepareSvg(newDoc);
  4381. // import new svg document into our document
  4382. var svg;
  4383. // If DOM3 adoptNode() available, use it. Otherwise fall back to DOM2 importNode()
  4384. if (svgdoc.adoptNode) {
  4385. svg = svgdoc.adoptNode(newDoc.documentElement);
  4386. } else {
  4387. svg = svgdoc.importNode(newDoc.documentElement, true);
  4388. }
  4389. uniquifyElems(svg);
  4390. var innerw = svgedit.units.convertToNum('width', svg.getAttribute('width')),
  4391. innerh = svgedit.units.convertToNum('height', svg.getAttribute('height')),
  4392. innervb = svg.getAttribute('viewBox'),
  4393. // if no explicit viewbox, create one out of the width and height
  4394. vb = innervb ? innervb.split(' ') : [0, 0, innerw, innerh];
  4395. for (j = 0; j < 4; ++j) {
  4396. vb[j] = +(vb[j]);
  4397. }
  4398. // TODO: properly handle preserveAspectRatio
  4399. var canvasw = +svgcontent.getAttribute('width'),
  4400. canvash = +svgcontent.getAttribute('height');
  4401. // imported content should be 1/3 of the canvas on its largest dimension
  4402. if (innerh > innerw) {
  4403. ts = 'scale(' + (canvash/3)/vb[3] + ')';
  4404. } else {
  4405. ts = 'scale(' + (canvash/3)/vb[2] + ')';
  4406. }
  4407. // Hack to make recalculateDimensions understand how to scale
  4408. ts = 'translate(0) ' + ts + ' translate(0)';
  4409. symbol = svgdoc.createElementNS(NS.SVG, 'symbol');
  4410. var defs = svgedit.utilities.findDefs();
  4411. if (svgedit.browser.isGecko()) {
  4412. // Move all gradients into root for Firefox, workaround for this bug:
  4413. // https://bugzilla.mozilla.org/show_bug.cgi?id=353575
  4414. // TODO: Make this properly undo-able.
  4415. $(svg).find('linearGradient, radialGradient, pattern').appendTo(defs);
  4416. }
  4417. while (svg.firstChild) {
  4418. var first = svg.firstChild;
  4419. symbol.appendChild(first);
  4420. }
  4421. var attrs = svg.attributes;
  4422. var i;
  4423. for (i = 0; i < attrs.length; i++) {
  4424. var attr = attrs[i];
  4425. symbol.setAttribute(attr.nodeName, attr.value);
  4426. }
  4427. symbol.id = getNextId();
  4428. // Store data
  4429. import_ids[uid] = {
  4430. symbol: symbol,
  4431. xform: ts
  4432. };
  4433. svgedit.utilities.findDefs().appendChild(symbol);
  4434. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(symbol));
  4435. }
  4436. var use_el = svgdoc.createElementNS(NS.SVG, 'use');
  4437. use_el.id = getNextId();
  4438. setHref(use_el, '#' + symbol.id);
  4439. (current_group || getCurrentDrawing().getCurrentLayer()).appendChild(use_el);
  4440. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(use_el));
  4441. clearSelection();
  4442. use_el.setAttribute('transform', ts);
  4443. svgedit.recalculate.recalculateDimensions(use_el);
  4444. $(use_el).data('symbol', symbol).data('ref', symbol);
  4445. addToSelection([use_el]);
  4446. // TODO: Find way to add this in a recalculateDimensions-parsable way
  4447. // if (vb[0] != 0 || vb[1] != 0)
  4448. // ts = 'translate(' + (-vb[0]) + ',' + (-vb[1]) + ') ' + ts;
  4449. addCommandToHistory(batchCmd);
  4450. call('changed', [svgcontent]);
  4451. } catch(e) {
  4452. console.log(e);
  4453. return false;
  4454. }
  4455. return true;
  4456. };
  4457. // TODO(codedread): Move all layer/context functions in draw.js
  4458. // Layer API Functions
  4459. // Group: Layers
  4460. // Function: identifyLayers
  4461. // Updates layer system
  4462. var identifyLayers = canvas.identifyLayers = function() {
  4463. leaveContext();
  4464. getCurrentDrawing().identifyLayers();
  4465. };
  4466. // Function: createLayer
  4467. // Creates a new top-level layer in the drawing with the given name, sets the current layer
  4468. // to it, and then clears the selection. This function then calls the 'changed' handler.
  4469. // This is an undoable action.
  4470. //
  4471. // Parameters:
  4472. // name - The given name
  4473. this.createLayer = function(name) {
  4474. var batchCmd = new svgedit.history.BatchCommand('Create Layer');
  4475. var new_layer = getCurrentDrawing().createLayer(name);
  4476. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(new_layer));
  4477. addCommandToHistory(batchCmd);
  4478. clearSelection();
  4479. call('changed', [new_layer]);
  4480. };
  4481. // Function: cloneLayer
  4482. // Creates a new top-level layer in the drawing with the given name, copies all the current layer's contents
  4483. // to it, and then clears the selection. This function then calls the 'changed' handler.
  4484. // This is an undoable action.
  4485. //
  4486. // Parameters:
  4487. // name - The given name
  4488. this.cloneLayer = function(name) {
  4489. var batchCmd = new svgedit.history.BatchCommand('Duplicate Layer');
  4490. var new_layer = svgdoc.createElementNS(NS.SVG, 'g');
  4491. var layer_title = svgdoc.createElementNS(NS.SVG, 'title');
  4492. layer_title.textContent = name;
  4493. new_layer.appendChild(layer_title);
  4494. var current_layer = getCurrentDrawing().getCurrentLayer();
  4495. $(current_layer).after(new_layer);
  4496. var childs = current_layer.childNodes;
  4497. var i;
  4498. for (i = 0; i < childs.length; i++) {
  4499. var ch = childs[i];
  4500. if (ch.localName == 'title') {continue;}
  4501. new_layer.appendChild(copyElem(ch));
  4502. }
  4503. clearSelection();
  4504. identifyLayers();
  4505. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(new_layer));
  4506. addCommandToHistory(batchCmd);
  4507. canvas.setCurrentLayer(name);
  4508. call('changed', [new_layer]);
  4509. };
  4510. // Function: deleteCurrentLayer
  4511. // Deletes the current layer from the drawing and then clears the selection. This function
  4512. // then calls the 'changed' handler. This is an undoable action.
  4513. this.deleteCurrentLayer = function() {
  4514. var current_layer = getCurrentDrawing().getCurrentLayer();
  4515. var nextSibling = current_layer.nextSibling;
  4516. var parent = current_layer.parentNode;
  4517. current_layer = getCurrentDrawing().deleteCurrentLayer();
  4518. if (current_layer) {
  4519. var batchCmd = new svgedit.history.BatchCommand('Delete Layer');
  4520. // store in our Undo History
  4521. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(current_layer, nextSibling, parent));
  4522. addCommandToHistory(batchCmd);
  4523. clearSelection();
  4524. call('changed', [parent]);
  4525. return true;
  4526. }
  4527. return false;
  4528. };
  4529. // Function: setCurrentLayer
  4530. // Sets the current layer. If the name is not a valid layer name, then this function returns
  4531. // false. Otherwise it returns true. This is not an undo-able action.
  4532. //
  4533. // Parameters:
  4534. // name - the name of the layer you want to switch to.
  4535. //
  4536. // Returns:
  4537. // true if the current layer was switched, otherwise false
  4538. this.setCurrentLayer = function(name) {
  4539. var result = getCurrentDrawing().setCurrentLayer(svgedit.utilities.toXml(name));
  4540. if (result) {
  4541. clearSelection();
  4542. }
  4543. return result;
  4544. };
  4545. // Function: renameCurrentLayer
  4546. // Renames the current layer. If the layer name is not valid (i.e. unique), then this function
  4547. // does nothing and returns false, otherwise it returns true. This is an undo-able action.
  4548. //
  4549. // Parameters:
  4550. // newname - the new name you want to give the current layer. This name must be unique
  4551. // among all layer names.
  4552. //
  4553. // Returns:
  4554. // true if the rename succeeded, false otherwise.
  4555. this.renameCurrentLayer = function(newname) {
  4556. var i;
  4557. var drawing = getCurrentDrawing();
  4558. if (drawing.current_layer) {
  4559. var oldLayer = drawing.current_layer;
  4560. // setCurrentLayer will return false if the name doesn't already exist
  4561. // this means we are free to rename our oldLayer
  4562. if (!canvas.setCurrentLayer(newname)) {
  4563. var batchCmd = new svgedit.history.BatchCommand('Rename Layer');
  4564. // find the index of the layer
  4565. for (i = 0; i < drawing.getNumLayers(); ++i) {
  4566. if (drawing.all_layers[i][1] == oldLayer) {break;}
  4567. }
  4568. var oldname = drawing.getLayerName(i);
  4569. drawing.all_layers[i][0] = svgedit.utilities.toXml(newname);
  4570. // now change the underlying title element contents
  4571. var len = oldLayer.childNodes.length;
  4572. for (i = 0; i < len; ++i) {
  4573. var child = oldLayer.childNodes.item(i);
  4574. // found the <title> element, now append all the
  4575. if (child && child.tagName == 'title') {
  4576. // wipe out old name
  4577. while (child.firstChild) { child.removeChild(child.firstChild); }
  4578. child.textContent = newname;
  4579. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(child, {'#text':oldname}));
  4580. addCommandToHistory(batchCmd);
  4581. call('changed', [oldLayer]);
  4582. return true;
  4583. }
  4584. }
  4585. }
  4586. drawing.current_layer = oldLayer;
  4587. }
  4588. return false;
  4589. };
  4590. // Function: setCurrentLayerPosition
  4591. // Changes the position of the current layer to the new value. If the new index is not valid,
  4592. // this function does nothing and returns false, otherwise it returns true. This is an
  4593. // undo-able action.
  4594. //
  4595. // Parameters:
  4596. // newpos - The zero-based index of the new position of the layer. This should be between
  4597. // 0 and (number of layers - 1)
  4598. //
  4599. // Returns:
  4600. // true if the current layer position was changed, false otherwise.
  4601. this.setCurrentLayerPosition = function(newpos) {
  4602. var oldpos, drawing = getCurrentDrawing();
  4603. if (drawing.current_layer && newpos >= 0 && newpos < drawing.getNumLayers()) {
  4604. for (oldpos = 0; oldpos < drawing.getNumLayers(); ++oldpos) {
  4605. if (drawing.all_layers[oldpos][1] == drawing.current_layer) {break;}
  4606. }
  4607. // some unknown error condition (current_layer not in all_layers)
  4608. if (oldpos == drawing.getNumLayers()) { return false; }
  4609. if (oldpos != newpos) {
  4610. // if our new position is below us, we need to insert before the node after newpos
  4611. var refLayer = null;
  4612. var oldNextSibling = drawing.current_layer.nextSibling;
  4613. if (newpos > oldpos ) {
  4614. if (newpos < drawing.getNumLayers()-1) {
  4615. refLayer = drawing.all_layers[newpos+1][1];
  4616. }
  4617. }
  4618. // if our new position is above us, we need to insert before the node at newpos
  4619. else {
  4620. refLayer = drawing.all_layers[newpos][1];
  4621. }
  4622. svgcontent.insertBefore(drawing.current_layer, refLayer);
  4623. addCommandToHistory(new svgedit.history.MoveElementCommand(drawing.current_layer, oldNextSibling, svgcontent));
  4624. identifyLayers();
  4625. canvas.setCurrentLayer(drawing.getLayerName(newpos));
  4626. return true;
  4627. }
  4628. }
  4629. return false;
  4630. };
  4631. // Function: setLayerVisibility
  4632. // Sets the visibility of the layer. If the layer name is not valid, this function return
  4633. // false, otherwise it returns true. This is an undo-able action.
  4634. //
  4635. // Parameters:
  4636. // layername - the name of the layer to change the visibility
  4637. // bVisible - true/false, whether the layer should be visible
  4638. //
  4639. // Returns:
  4640. // true if the layer's visibility was set, false otherwise
  4641. this.setLayerVisibility = function(layername, bVisible) {
  4642. var drawing = getCurrentDrawing();
  4643. var prevVisibility = drawing.getLayerVisibility(layername);
  4644. var layer = drawing.setLayerVisibility(layername, bVisible);
  4645. if (layer) {
  4646. var oldDisplay = prevVisibility ? 'inline' : 'none';
  4647. addCommandToHistory(new svgedit.history.ChangeElementCommand(layer, {'display':oldDisplay}, 'Layer Visibility'));
  4648. } else {
  4649. return false;
  4650. }
  4651. if (layer == drawing.getCurrentLayer()) {
  4652. clearSelection();
  4653. pathActions.clear();
  4654. }
  4655. // call('changed', [selected]);
  4656. return true;
  4657. };
  4658. // Function: moveSelectedToLayer
  4659. // Moves the selected elements to layername. If the name is not a valid layer name, then false
  4660. // is returned. Otherwise it returns true. This is an undo-able action.
  4661. //
  4662. // Parameters:
  4663. // layername - the name of the layer you want to which you want to move the selected elements
  4664. //
  4665. // Returns:
  4666. // true if the selected elements were moved to the layer, false otherwise.
  4667. this.moveSelectedToLayer = function(layername) {
  4668. // find the layer
  4669. var i;
  4670. var layer = null;
  4671. var drawing = getCurrentDrawing();
  4672. for (i = 0; i < drawing.getNumLayers(); ++i) {
  4673. if (drawing.getLayerName(i) == layername) {
  4674. layer = drawing.all_layers[i][1];
  4675. break;
  4676. }
  4677. }
  4678. if (!layer) {return false;}
  4679. var batchCmd = new svgedit.history.BatchCommand('Move Elements to Layer');
  4680. // loop for each selected element and move it
  4681. var selElems = selectedElements;
  4682. i = selElems.length;
  4683. while (i--) {
  4684. var elem = selElems[i];
  4685. if (!elem) {continue;}
  4686. var oldNextSibling = elem.nextSibling;
  4687. // TODO: this is pretty brittle!
  4688. var oldLayer = elem.parentNode;
  4689. layer.appendChild(elem);
  4690. batchCmd.addSubCommand(new svgedit.history.MoveElementCommand(elem, oldNextSibling, oldLayer));
  4691. }
  4692. addCommandToHistory(batchCmd);
  4693. return true;
  4694. };
  4695. this.mergeLayer = function(skipHistory) {
  4696. var batchCmd = new svgedit.history.BatchCommand('Merge Layer');
  4697. var drawing = getCurrentDrawing();
  4698. var prev = $(drawing.current_layer).prev()[0];
  4699. if (!prev) {return;}
  4700. var childs = drawing.current_layer.childNodes;
  4701. var len = childs.length;
  4702. var layerNextSibling = drawing.current_layer.nextSibling;
  4703. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(drawing.current_layer, layerNextSibling, svgcontent));
  4704. while (drawing.current_layer.firstChild) {
  4705. var ch = drawing.current_layer.firstChild;
  4706. if (ch.localName == 'title') {
  4707. var chNextSibling = ch.nextSibling;
  4708. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(ch, chNextSibling, drawing.current_layer));
  4709. drawing.current_layer.removeChild(ch);
  4710. continue;
  4711. }
  4712. var oldNextSibling = ch.nextSibling;
  4713. prev.appendChild(ch);
  4714. batchCmd.addSubCommand(new svgedit.history.MoveElementCommand(ch, oldNextSibling, drawing.current_layer));
  4715. }
  4716. // Remove current layer
  4717. svgcontent.removeChild(drawing.current_layer);
  4718. if (!skipHistory) {
  4719. clearSelection();
  4720. identifyLayers();
  4721. call('changed', [svgcontent]);
  4722. addCommandToHistory(batchCmd);
  4723. }
  4724. drawing.current_layer = prev;
  4725. return batchCmd;
  4726. };
  4727. this.mergeAllLayers = function() {
  4728. var batchCmd = new svgedit.history.BatchCommand('Merge all Layers');
  4729. var drawing = getCurrentDrawing();
  4730. drawing.current_layer = drawing.all_layers[drawing.getNumLayers()-1][1];
  4731. while ($(svgcontent).children('g').length > 1) {
  4732. batchCmd.addSubCommand(canvas.mergeLayer(true));
  4733. }
  4734. clearSelection();
  4735. identifyLayers();
  4736. call('changed', [svgcontent]);
  4737. addCommandToHistory(batchCmd);
  4738. };
  4739. // Function: leaveContext
  4740. // Return from a group context to the regular kind, make any previously
  4741. // disabled elements enabled again
  4742. var leaveContext = this.leaveContext = function() {
  4743. var i, len = disabled_elems.length;
  4744. if (len) {
  4745. for (i = 0; i < len; i++) {
  4746. var elem = disabled_elems[i];
  4747. var orig = elData(elem, 'orig_opac');
  4748. if (orig !== 1) {
  4749. elem.setAttribute('opacity', orig);
  4750. } else {
  4751. elem.removeAttribute('opacity');
  4752. }
  4753. elem.setAttribute('style', 'pointer-events: inherit');
  4754. }
  4755. disabled_elems = [];
  4756. clearSelection(true);
  4757. call('contextset', null);
  4758. }
  4759. current_group = null;
  4760. };
  4761. // Function: setContext
  4762. // Set the current context (for in-group editing)
  4763. var setContext = this.setContext = function(elem) {
  4764. leaveContext();
  4765. if (typeof elem === 'string') {
  4766. elem = svgedit.utilities.getElem(elem);
  4767. }
  4768. // Edit inside this group
  4769. current_group = elem;
  4770. // Disable other elements
  4771. $(elem).parentsUntil('#svgcontent').andSelf().siblings().each(function() {
  4772. var opac = this.getAttribute('opacity') || 1;
  4773. // Store the original's opacity
  4774. elData(this, 'orig_opac', opac);
  4775. this.setAttribute('opacity', opac * 0.33);
  4776. this.setAttribute('style', 'pointer-events: none');
  4777. disabled_elems.push(this);
  4778. });
  4779. clearSelection();
  4780. call('contextset', current_group);
  4781. };
  4782. // Group: Document functions
  4783. // Function: clear
  4784. // Clears the current document. This is not an undoable action.
  4785. this.clear = function() {
  4786. pathActions.clear();
  4787. clearSelection();
  4788. // clear the svgcontent node
  4789. canvas.clearSvgContentElement();
  4790. // create new document
  4791. canvas.current_drawing_ = new svgedit.draw.Drawing(svgcontent);
  4792. // create empty first layer
  4793. canvas.createLayer('Layer 1');
  4794. // clear the undo stack
  4795. canvas.undoMgr.resetUndoStack();
  4796. // reset the selector manager
  4797. selectorManager.initGroup();
  4798. // reset the rubber band box
  4799. rubberBox = selectorManager.getRubberBandBox();
  4800. call('cleared');
  4801. };
  4802. // Function: linkControlPoints
  4803. // Alias function
  4804. this.linkControlPoints = pathActions.linkControlPoints;
  4805. // Function: getContentElem
  4806. // Returns the content DOM element
  4807. this.getContentElem = function() { return svgcontent; };
  4808. // Function: getRootElem
  4809. // Returns the root DOM element
  4810. this.getRootElem = function() { return svgroot; };
  4811. // Function: getSelectedElems
  4812. // Returns the array with selected DOM elements
  4813. this.getSelectedElems = function() { return selectedElements; };
  4814. // Function: getResolution
  4815. // Returns the current dimensions and zoom level in an object
  4816. var getResolution = this.getResolution = function() {
  4817. // var vb = svgcontent.getAttribute('viewBox').split(' ');
  4818. // return {'w':vb[2], 'h':vb[3], 'zoom': current_zoom};
  4819. var width = svgcontent.getAttribute('width')/current_zoom;
  4820. var height = svgcontent.getAttribute('height')/current_zoom;
  4821. return {
  4822. 'w': width,
  4823. 'h': height,
  4824. 'zoom': current_zoom
  4825. };
  4826. };
  4827. // Function: getZoom
  4828. // Returns the current zoom level
  4829. this.getZoom = function(){return current_zoom;};
  4830. // Function: getVersion
  4831. // Returns a string which describes the revision number of SvgCanvas.
  4832. this.getVersion = function() {
  4833. return 'svgcanvas.js ($Rev$)';
  4834. };
  4835. // Function: setUiStrings
  4836. // Update interface strings with given values
  4837. //
  4838. // Parameters:
  4839. // strs - Object with strings (see uiStrings for examples)
  4840. this.setUiStrings = function(strs) {
  4841. $.extend(uiStrings, strs.notification);
  4842. };
  4843. // Function: setConfig
  4844. // Update configuration options with given values
  4845. //
  4846. // Parameters:
  4847. // opts - Object with options (see curConfig for examples)
  4848. this.setConfig = function(opts) {
  4849. $.extend(curConfig, opts);
  4850. };
  4851. // Function: getTitle
  4852. // Returns the current group/SVG's title contents
  4853. this.getTitle = function(elem) {
  4854. var i;
  4855. elem = elem || selectedElements[0];
  4856. if (!elem) {return;}
  4857. elem = $(elem).data('gsvg') || $(elem).data('symbol') || elem;
  4858. var childs = elem.childNodes;
  4859. for (i = 0; i < childs.length; i++) {
  4860. if (childs[i].nodeName == 'title') {
  4861. return childs[i].textContent;
  4862. }
  4863. }
  4864. return '';
  4865. };
  4866. // Function: setGroupTitle
  4867. // Sets the group/SVG's title content
  4868. // TODO: Combine this with setDocumentTitle
  4869. this.setGroupTitle = function(val) {
  4870. var elem = selectedElements[0];
  4871. elem = $(elem).data('gsvg') || elem;
  4872. var ts = $(elem).children('title');
  4873. var batchCmd = new svgedit.history.BatchCommand('Set Label');
  4874. if (!val.length) {
  4875. // Remove title element
  4876. var tsNextSibling = ts.nextSibling;
  4877. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(ts[0], tsNextSibling, elem));
  4878. ts.remove();
  4879. } else if (ts.length) {
  4880. // Change title contents
  4881. var title = ts[0];
  4882. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(title, {'#text': title.textContent}));
  4883. title.textContent = val;
  4884. } else {
  4885. // Add title element
  4886. title = svgdoc.createElementNS(NS.SVG, 'title');
  4887. title.textContent = val;
  4888. $(elem).prepend(title);
  4889. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(title));
  4890. }
  4891. addCommandToHistory(batchCmd);
  4892. };
  4893. // Function: getDocumentTitle
  4894. // Returns the current document title or an empty string if not found
  4895. var getDocumentTitle = this.getDocumentTitle = function() {
  4896. return canvas.getTitle(svgcontent);
  4897. };
  4898. // Function: setDocumentTitle
  4899. // Adds/updates a title element for the document with the given name.
  4900. // This is an undoable action
  4901. //
  4902. // Parameters:
  4903. // newtitle - String with the new title
  4904. this.setDocumentTitle = function(newtitle) {
  4905. var i;
  4906. var childs = svgcontent.childNodes, doc_title = false, old_title = '';
  4907. var batchCmd = new svgedit.history.BatchCommand('Change Image Title');
  4908. for (i = 0; i < childs.length; i++) {
  4909. if (childs[i].nodeName == 'title') {
  4910. doc_title = childs[i];
  4911. old_title = doc_title.textContent;
  4912. break;
  4913. }
  4914. }
  4915. if (!doc_title) {
  4916. doc_title = svgdoc.createElementNS(NS.SVG, 'title');
  4917. svgcontent.insertBefore(doc_title, svgcontent.firstChild);
  4918. }
  4919. if (newtitle.length) {
  4920. doc_title.textContent = newtitle;
  4921. } else {
  4922. // No title given, so element is not necessary
  4923. doc_title.parentNode.removeChild(doc_title);
  4924. }
  4925. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(doc_title, {'#text': old_title}));
  4926. addCommandToHistory(batchCmd);
  4927. };
  4928. // Function: getEditorNS
  4929. // Returns the editor's namespace URL, optionally adds it to root element
  4930. //
  4931. // Parameters:
  4932. // add - Boolean to indicate whether or not to add the namespace value
  4933. this.getEditorNS = function(add) {
  4934. if (add) {
  4935. svgcontent.setAttribute('xmlns:se', NS.SE);
  4936. }
  4937. return NS.SE;
  4938. };
  4939. // Function: setResolution
  4940. // Changes the document's dimensions to the given size
  4941. //
  4942. // Parameters:
  4943. // x - Number with the width of the new dimensions in user units.
  4944. // Can also be the string "fit" to indicate "fit to content"
  4945. // y - Number with the height of the new dimensions in user units.
  4946. //
  4947. // Returns:
  4948. // Boolean to indicate if resolution change was succesful.
  4949. // It will fail on "fit to content" option with no content to fit to.
  4950. this.setResolution = function(x, y) {
  4951. var res = getResolution();
  4952. var w = res.w, h = res.h;
  4953. var batchCmd;
  4954. if (x == 'fit') {
  4955. // Get bounding box
  4956. var bbox = getStrokedBBox();
  4957. if (bbox) {
  4958. batchCmd = new svgedit.history.BatchCommand('Fit Canvas to Content');
  4959. var visEls = getVisibleElements();
  4960. addToSelection(visEls);
  4961. var dx = [], dy = [];
  4962. $.each(visEls, function(i, item) {
  4963. dx.push(bbox.x*-1);
  4964. dy.push(bbox.y*-1);
  4965. });
  4966. var cmd = canvas.moveSelectedElements(dx, dy, true);
  4967. batchCmd.addSubCommand(cmd);
  4968. clearSelection();
  4969. x = Math.round(bbox.width);
  4970. y = Math.round(bbox.height);
  4971. } else {
  4972. return false;
  4973. }
  4974. }
  4975. if (x != w || y != h) {
  4976. if (!batchCmd) {
  4977. batchCmd = new svgedit.history.BatchCommand('Change Image Dimensions');
  4978. }
  4979. x = svgedit.units.convertToNum('width', x);
  4980. y = svgedit.units.convertToNum('height', y);
  4981. svgcontent.setAttribute('width', x);
  4982. svgcontent.setAttribute('height', y);
  4983. this.contentW = x;
  4984. this.contentH = y;
  4985. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(svgcontent, {'width':w, 'height':h}));
  4986. svgcontent.setAttribute('viewBox', [0, 0, x/current_zoom, y/current_zoom].join(' '));
  4987. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(svgcontent, {'viewBox': ['0 0', w, h].join(' ')}));
  4988. addCommandToHistory(batchCmd);
  4989. call('changed', [svgcontent]);
  4990. }
  4991. return true;
  4992. };
  4993. // Function: getOffset
  4994. // Returns an object with x, y values indicating the svgcontent element's
  4995. // position in the editor's canvas.
  4996. this.getOffset = function() {
  4997. return $(svgcontent).attr(['x', 'y']);
  4998. };
  4999. // Function: setBBoxZoom
  5000. // Sets the zoom level on the canvas-side based on the given value
  5001. //
  5002. // Parameters:
  5003. // val - Bounding box object to zoom to or string indicating zoom option
  5004. // editor_w - Integer with the editor's workarea box's width
  5005. // editor_h - Integer with the editor's workarea box's height
  5006. this.setBBoxZoom = function(val, editor_w, editor_h) {
  5007. var spacer = 0.85;
  5008. var bb;
  5009. var calcZoom = function(bb) {
  5010. if (!bb) {return false;}
  5011. var w_zoom = Math.round((editor_w / bb.width)*100 * spacer)/100;
  5012. var h_zoom = Math.round((editor_h / bb.height)*100 * spacer)/100;
  5013. var zoomlevel = Math.min(w_zoom, h_zoom);
  5014. canvas.setZoom(zoomlevel);
  5015. return {'zoom': zoomlevel, 'bbox': bb};
  5016. };
  5017. if (typeof val == 'object') {
  5018. bb = val;
  5019. if (bb.width == 0 || bb.height == 0) {
  5020. var newzoom = bb.zoom ? bb.zoom : current_zoom * bb.factor;
  5021. canvas.setZoom(newzoom);
  5022. return {'zoom': current_zoom, 'bbox': bb};
  5023. }
  5024. return calcZoom(bb);
  5025. }
  5026. switch (val) {
  5027. case 'selection':
  5028. if (!selectedElements[0]) {return;}
  5029. var sel_elems = $.map(selectedElements, function(n){ if (n) {return n;} });
  5030. bb = getStrokedBBox(sel_elems);
  5031. break;
  5032. case 'canvas':
  5033. var res = getResolution();
  5034. spacer = 0.95;
  5035. bb = {width:res.w, height:res.h , x:0, y:0};
  5036. break;
  5037. case 'content':
  5038. bb = getStrokedBBox();
  5039. break;
  5040. case 'layer':
  5041. bb = getStrokedBBox(getVisibleElements(getCurrentDrawing().getCurrentLayer()));
  5042. break;
  5043. default:
  5044. return;
  5045. }
  5046. return calcZoom(bb);
  5047. };
  5048. // Function: setZoom
  5049. // Sets the zoom to the given level
  5050. //
  5051. // Parameters:
  5052. // zoomlevel - Float indicating the zoom level to change to
  5053. this.setZoom = function(zoomlevel) {
  5054. var res = getResolution();
  5055. svgcontent.setAttribute('viewBox', '0 0 ' + res.w/zoomlevel + ' ' + res.h/zoomlevel);
  5056. current_zoom = zoomlevel;
  5057. $.each(selectedElements, function(i, elem) {
  5058. if (!elem) {return;}
  5059. selectorManager.requestSelector(elem).resize();
  5060. });
  5061. pathActions.zoomChange();
  5062. runExtensions('zoomChanged', zoomlevel);
  5063. };
  5064. // Function: getMode
  5065. // Returns the current editor mode string
  5066. this.getMode = function() {
  5067. return current_mode;
  5068. };
  5069. // Function: setMode
  5070. // Sets the editor's mode to the given string
  5071. //
  5072. // Parameters:
  5073. // name - String with the new mode to change to
  5074. this.setMode = function(name) {
  5075. pathActions.clear(true);
  5076. textActions.clear();
  5077. cur_properties = (selectedElements[0] && selectedElements[0].nodeName == 'text') ? cur_text : cur_shape;
  5078. current_mode = name;
  5079. };
  5080. // Group: Element Styling
  5081. // Function: getColor
  5082. // Returns the current fill/stroke option
  5083. this.getColor = function(type) {
  5084. return cur_properties[type];
  5085. };
  5086. // Function: setColor
  5087. // Change the current stroke/fill color/gradient value
  5088. //
  5089. // Parameters:
  5090. // type - String indicating fill or stroke
  5091. // val - The value to set the stroke attribute to
  5092. // preventUndo - Boolean indicating whether or not this should be and undoable option
  5093. this.setColor = function(type, val, preventUndo) {
  5094. cur_shape[type] = val;
  5095. cur_properties[type + '_paint'] = {type:'solidColor'};
  5096. var elems = [];
  5097. function addNonG (e) {
  5098. if (e.nodeName != 'g') {
  5099. elems.push(e);
  5100. }
  5101. }
  5102. var i = selectedElements.length;
  5103. while (i--) {
  5104. var elem = selectedElements[i];
  5105. if (elem) {
  5106. if (elem.tagName == 'g') {
  5107. svgedit.utilities.walkTree(elem, addNonG);
  5108. } else {
  5109. if (type == 'fill') {
  5110. if (elem.tagName != 'polyline' && elem.tagName != 'line') {
  5111. elems.push(elem);
  5112. }
  5113. } else {
  5114. elems.push(elem);
  5115. }
  5116. }
  5117. }
  5118. }
  5119. if (elems.length > 0) {
  5120. if (!preventUndo) {
  5121. changeSelectedAttribute(type, val, elems);
  5122. call('changed', elems);
  5123. } else {
  5124. changeSelectedAttributeNoUndo(type, val, elems);
  5125. }
  5126. }
  5127. };
  5128. // Function: setGradient
  5129. // Apply the current gradient to selected element's fill or stroke
  5130. //
  5131. // Parameters
  5132. // type - String indicating "fill" or "stroke" to apply to an element
  5133. var setGradient = this.setGradient = function(type) {
  5134. if (!cur_properties[type + '_paint'] || cur_properties[type + '_paint'].type == 'solidColor') {return;}
  5135. var grad = canvas[type + 'Grad'];
  5136. // find out if there is a duplicate gradient already in the defs
  5137. var duplicate_grad = findDuplicateGradient(grad);
  5138. var defs = svgedit.utilities.findDefs();
  5139. // no duplicate found, so import gradient into defs
  5140. if (!duplicate_grad) {
  5141. var orig_grad = grad;
  5142. grad = defs.appendChild( svgdoc.importNode(grad, true) );
  5143. // get next id and set it on the grad
  5144. grad.id = getNextId();
  5145. } else { // use existing gradient
  5146. grad = duplicate_grad;
  5147. }
  5148. canvas.setColor(type, 'url(#' + grad.id + ')');
  5149. };
  5150. // Function: findDuplicateGradient
  5151. // Check if exact gradient already exists
  5152. //
  5153. // Parameters:
  5154. // grad - The gradient DOM element to compare to others
  5155. //
  5156. // Returns:
  5157. // The existing gradient if found, null if not
  5158. var findDuplicateGradient = function(grad) {
  5159. var defs = svgedit.utilities.findDefs();
  5160. var existing_grads = $(defs).find('linearGradient, radialGradient');
  5161. var i = existing_grads.length;
  5162. var rad_attrs = ['r', 'cx', 'cy', 'fx', 'fy'];
  5163. while (i--) {
  5164. var og = existing_grads[i];
  5165. if (grad.tagName == 'linearGradient') {
  5166. if (grad.getAttribute('x1') != og.getAttribute('x1') ||
  5167. grad.getAttribute('y1') != og.getAttribute('y1') ||
  5168. grad.getAttribute('x2') != og.getAttribute('x2') ||
  5169. grad.getAttribute('y2') != og.getAttribute('y2'))
  5170. {
  5171. continue;
  5172. }
  5173. } else {
  5174. var grad_attrs = $(grad).attr(rad_attrs);
  5175. var og_attrs = $(og).attr(rad_attrs);
  5176. var diff = false;
  5177. $.each(rad_attrs, function(i, attr) {
  5178. if (grad_attrs[attr] != og_attrs[attr]) {diff = true;}
  5179. });
  5180. if (diff) {continue;}
  5181. }
  5182. // else could be a duplicate, iterate through stops
  5183. var stops = grad.getElementsByTagNameNS(NS.SVG, 'stop');
  5184. var ostops = og.getElementsByTagNameNS(NS.SVG, 'stop');
  5185. if (stops.length != ostops.length) {
  5186. continue;
  5187. }
  5188. var j = stops.length;
  5189. while (j--) {
  5190. var stop = stops[j];
  5191. var ostop = ostops[j];
  5192. if (stop.getAttribute('offset') != ostop.getAttribute('offset') ||
  5193. stop.getAttribute('stop-opacity') != ostop.getAttribute('stop-opacity') ||
  5194. stop.getAttribute('stop-color') != ostop.getAttribute('stop-color'))
  5195. {
  5196. break;
  5197. }
  5198. }
  5199. if (j == -1) {
  5200. return og;
  5201. }
  5202. } // for each gradient in defs
  5203. return null;
  5204. };
  5205. function reorientGrads(elem, m) {
  5206. var i;
  5207. var bb = svgedit.utilities.getBBox(elem);
  5208. for (i = 0; i < 2; i++) {
  5209. var type = i === 0 ? 'fill' : 'stroke';
  5210. var attrVal = elem.getAttribute(type);
  5211. if (attrVal && attrVal.indexOf('url(') === 0) {
  5212. var grad = svgedit.utilities.getRefElem(attrVal);
  5213. if (grad.tagName === 'linearGradient') {
  5214. var x1 = grad.getAttribute('x1') || 0;
  5215. var y1 = grad.getAttribute('y1') || 0;
  5216. var x2 = grad.getAttribute('x2') || 1;
  5217. var y2 = grad.getAttribute('y2') || 0;
  5218. // Convert to USOU points
  5219. x1 = (bb.width * x1) + bb.x;
  5220. y1 = (bb.height * y1) + bb.y;
  5221. x2 = (bb.width * x2) + bb.x;
  5222. y2 = (bb.height * y2) + bb.y;
  5223. // Transform those points
  5224. var pt1 = svgedit.math.transformPoint(x1, y1, m);
  5225. var pt2 = svgedit.math.transformPoint(x2, y2, m);
  5226. // Convert back to BB points
  5227. var g_coords = {};
  5228. g_coords.x1 = (pt1.x - bb.x) / bb.width;
  5229. g_coords.y1 = (pt1.y - bb.y) / bb.height;
  5230. g_coords.x2 = (pt2.x - bb.x) / bb.width;
  5231. g_coords.y2 = (pt2.y - bb.y) / bb.height;
  5232. var newgrad = grad.cloneNode(true);
  5233. $(newgrad).attr(g_coords);
  5234. newgrad.id = getNextId();
  5235. svgedit.utilities.findDefs().appendChild(newgrad);
  5236. elem.setAttribute(type, 'url(#' + newgrad.id + ')');
  5237. }
  5238. }
  5239. }
  5240. }
  5241. // Function: setPaint
  5242. // Set a color/gradient to a fill/stroke
  5243. //
  5244. // Parameters:
  5245. // type - String with "fill" or "stroke"
  5246. // paint - The jGraduate paint object to apply
  5247. this.setPaint = function(type, paint) {
  5248. // make a copy
  5249. var p = new $.jGraduate.Paint(paint);
  5250. this.setPaintOpacity(type, p.alpha / 100, true);
  5251. // now set the current paint object
  5252. cur_properties[type + '_paint'] = p;
  5253. switch (p.type) {
  5254. case 'solidColor':
  5255. this.setColor(type, p.solidColor != 'none' ? '#' + p.solidColor : 'none');
  5256. break;
  5257. case 'linearGradient':
  5258. case 'radialGradient':
  5259. canvas[type + 'Grad'] = p[p.type];
  5260. setGradient(type);
  5261. break;
  5262. }
  5263. };
  5264. // alias
  5265. this.setStrokePaint = function(paint) {
  5266. this.setPaint('stroke', paint);
  5267. };
  5268. this.setFillPaint = function(paint) {
  5269. this.setPaint('fill', paint);
  5270. };
  5271. // Function: getStrokeWidth
  5272. // Returns the current stroke-width value
  5273. this.getStrokeWidth = function() {
  5274. return cur_properties.stroke_width;
  5275. };
  5276. // Function: setStrokeWidth
  5277. // Sets the stroke width for the current selected elements
  5278. // When attempting to set a line's width to 0, this changes it to 1 instead
  5279. //
  5280. // Parameters:
  5281. // val - A Float indicating the new stroke width value
  5282. this.setStrokeWidth = function(val) {
  5283. if (val == 0 && ['line', 'path'].indexOf(current_mode) >= 0) {
  5284. canvas.setStrokeWidth(1);
  5285. return;
  5286. }
  5287. cur_properties.stroke_width = val;
  5288. var elems = [];
  5289. function addNonG (e) {
  5290. if (e.nodeName != 'g') {
  5291. elems.push(e);
  5292. }
  5293. }
  5294. var i = selectedElements.length;
  5295. while (i--) {
  5296. var elem = selectedElements[i];
  5297. if (elem) {
  5298. if (elem.tagName == 'g') {
  5299. svgedit.utilities.walkTree(elem, addNonG);
  5300. }
  5301. else {
  5302. elems.push(elem);
  5303. }
  5304. }
  5305. }
  5306. if (elems.length > 0) {
  5307. changeSelectedAttribute('stroke-width', val, elems);
  5308. call('changed', selectedElements);
  5309. }
  5310. };
  5311. // Function: setStrokeAttr
  5312. // Set the given stroke-related attribute the given value for selected elements
  5313. //
  5314. // Parameters:
  5315. // attr - String with the attribute name
  5316. // val - String or number with the attribute value
  5317. this.setStrokeAttr = function(attr, val) {
  5318. cur_shape[attr.replace('-', '_')] = val;
  5319. var elems = [];
  5320. function addNonG (e) {
  5321. if (e.nodeName != 'g') {
  5322. elems.push(e);
  5323. }
  5324. }
  5325. var i = selectedElements.length;
  5326. while (i--) {
  5327. var elem = selectedElements[i];
  5328. if (elem) {
  5329. if (elem.tagName == 'g') {
  5330. svgedit.utilities.walkTree(elem, function(e){if (e.nodeName!='g') {elems.push(e);}});
  5331. }
  5332. else {
  5333. elems.push(elem);
  5334. }
  5335. }
  5336. }
  5337. if (elems.length > 0) {
  5338. changeSelectedAttribute(attr, val, elems);
  5339. call('changed', selectedElements);
  5340. }
  5341. };
  5342. // Function: getStyle
  5343. // Returns current style options
  5344. this.getStyle = function() {
  5345. return cur_shape;
  5346. };
  5347. // Function: getOpacity
  5348. // Returns the current opacity
  5349. this.getOpacity = function() {
  5350. return cur_shape.opacity;
  5351. };
  5352. // Function: setOpacity
  5353. // Sets the given opacity to the current selected elements
  5354. this.setOpacity = function(val) {
  5355. cur_shape.opacity = val;
  5356. changeSelectedAttribute('opacity', val);
  5357. };
  5358. // Function: getOpacity
  5359. // Returns the current fill opacity
  5360. this.getFillOpacity = function() {
  5361. return cur_shape.fill_opacity;
  5362. };
  5363. // Function: getStrokeOpacity
  5364. // Returns the current stroke opacity
  5365. this.getStrokeOpacity = function() {
  5366. return cur_shape.stroke_opacity;
  5367. };
  5368. // Function: setPaintOpacity
  5369. // Sets the current fill/stroke opacity
  5370. //
  5371. // Parameters:
  5372. // type - String with "fill" or "stroke"
  5373. // val - Float with the new opacity value
  5374. // preventUndo - Boolean indicating whether or not this should be an undoable action
  5375. this.setPaintOpacity = function(type, val, preventUndo) {
  5376. cur_shape[type + '_opacity'] = val;
  5377. if (!preventUndo) {
  5378. changeSelectedAttribute(type + '-opacity', val);
  5379. }
  5380. else {
  5381. changeSelectedAttributeNoUndo(type + '-opacity', val);
  5382. }
  5383. };
  5384. // Function: getPaintOpacity
  5385. // Gets the current fill/stroke opacity
  5386. //
  5387. // Parameters:
  5388. // type - String with "fill" or "stroke"
  5389. this.getPaintOpacity = function(type) {
  5390. return type === 'fill' ? this.getFillOpacity() : this.getStrokeOpacity();
  5391. };
  5392. // Function: getBlur
  5393. // Gets the stdDeviation blur value of the given element
  5394. //
  5395. // Parameters:
  5396. // elem - The element to check the blur value for
  5397. this.getBlur = function(elem) {
  5398. var val = 0;
  5399. // var elem = selectedElements[0];
  5400. if (elem) {
  5401. var filter_url = elem.getAttribute('filter');
  5402. if (filter_url) {
  5403. var blur = svgedit.utilities.getElem(elem.id + '_blur');
  5404. if (blur) {
  5405. val = blur.firstChild.getAttribute('stdDeviation');
  5406. }
  5407. }
  5408. }
  5409. return val;
  5410. };
  5411. (function() {
  5412. var cur_command = null;
  5413. var filter = null;
  5414. var filterHidden = false;
  5415. // Function: setBlurNoUndo
  5416. // Sets the stdDeviation blur value on the selected element without being undoable
  5417. //
  5418. // Parameters:
  5419. // val - The new stdDeviation value
  5420. canvas.setBlurNoUndo = function(val) {
  5421. if (!filter) {
  5422. canvas.setBlur(val);
  5423. return;
  5424. }
  5425. if (val === 0) {
  5426. // Don't change the StdDev, as that will hide the element.
  5427. // Instead, just remove the value for "filter"
  5428. changeSelectedAttributeNoUndo('filter', '');
  5429. filterHidden = true;
  5430. } else {
  5431. var elem = selectedElements[0];
  5432. if (filterHidden) {
  5433. changeSelectedAttributeNoUndo('filter', 'url(#' + elem.id + '_blur)');
  5434. }
  5435. if (svgedit.browser.isWebkit()) {
  5436. console.log('e', elem);
  5437. elem.removeAttribute('filter');
  5438. elem.setAttribute('filter', 'url(#' + elem.id + '_blur)');
  5439. }
  5440. changeSelectedAttributeNoUndo('stdDeviation', val, [filter.firstChild]);
  5441. canvas.setBlurOffsets(filter, val);
  5442. }
  5443. };
  5444. function finishChange() {
  5445. var bCmd = canvas.undoMgr.finishUndoableChange();
  5446. cur_command.addSubCommand(bCmd);
  5447. addCommandToHistory(cur_command);
  5448. cur_command = null;
  5449. filter = null;
  5450. }
  5451. // Function: setBlurOffsets
  5452. // Sets the x, y, with, height values of the filter element in order to
  5453. // make the blur not be clipped. Removes them if not neeeded
  5454. //
  5455. // Parameters:
  5456. // filter - The filter DOM element to update
  5457. // stdDev - The standard deviation value on which to base the offset size
  5458. canvas.setBlurOffsets = function(filter, stdDev) {
  5459. if (stdDev > 3) {
  5460. // TODO: Create algorithm here where size is based on expected blur
  5461. svgedit.utilities.assignAttributes(filter, {
  5462. x: '-50%',
  5463. y: '-50%',
  5464. width: '200%',
  5465. height: '200%'
  5466. }, 100);
  5467. } else {
  5468. // Removing these attributes hides text in Chrome (see Issue 579)
  5469. if (!svgedit.browser.isWebkit()) {
  5470. filter.removeAttribute('x');
  5471. filter.removeAttribute('y');
  5472. filter.removeAttribute('width');
  5473. filter.removeAttribute('height');
  5474. }
  5475. }
  5476. };
  5477. // Function: setBlur
  5478. // Adds/updates the blur filter to the selected element
  5479. //
  5480. // Parameters:
  5481. // val - Float with the new stdDeviation blur value
  5482. // complete - Boolean indicating whether or not the action should be completed (to add to the undo manager)
  5483. canvas.setBlur = function(val, complete) {
  5484. if (cur_command) {
  5485. finishChange();
  5486. return;
  5487. }
  5488. // Looks for associated blur, creates one if not found
  5489. var elem = selectedElements[0];
  5490. var elem_id = elem.id;
  5491. filter = svgedit.utilities.getElem(elem_id + '_blur');
  5492. val -= 0;
  5493. var batchCmd = new svgedit.history.BatchCommand();
  5494. // Blur found!
  5495. if (filter) {
  5496. if (val === 0) {
  5497. filter = null;
  5498. }
  5499. } else {
  5500. // Not found, so create
  5501. var newblur = addSvgElementFromJson({ 'element': 'feGaussianBlur',
  5502. 'attr': {
  5503. 'in': 'SourceGraphic',
  5504. 'stdDeviation': val
  5505. }
  5506. });
  5507. filter = addSvgElementFromJson({ 'element': 'filter',
  5508. 'attr': {
  5509. 'id': elem_id + '_blur'
  5510. }
  5511. });
  5512. filter.appendChild(newblur);
  5513. svgedit.utilities.findDefs().appendChild(filter);
  5514. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(filter));
  5515. }
  5516. var changes = {filter: elem.getAttribute('filter')};
  5517. if (val === 0) {
  5518. elem.removeAttribute('filter');
  5519. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, changes));
  5520. return;
  5521. }
  5522. changeSelectedAttribute('filter', 'url(#' + elem_id + '_blur)');
  5523. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, changes));
  5524. canvas.setBlurOffsets(filter, val);
  5525. cur_command = batchCmd;
  5526. canvas.undoMgr.beginUndoableChange('stdDeviation', [filter?filter.firstChild:null]);
  5527. if (complete) {
  5528. canvas.setBlurNoUndo(val);
  5529. finishChange();
  5530. }
  5531. };
  5532. }());
  5533. // Function: getBold
  5534. // Check whether selected element is bold or not
  5535. //
  5536. // Returns:
  5537. // Boolean indicating whether or not element is bold
  5538. this.getBold = function() {
  5539. // should only have one element selected
  5540. var selected = selectedElements[0];
  5541. if (selected != null && selected.tagName == 'text' &&
  5542. selectedElements[1] == null)
  5543. {
  5544. return (selected.getAttribute('font-weight') == 'bold');
  5545. }
  5546. return false;
  5547. };
  5548. // Function: setBold
  5549. // Make the selected element bold or normal
  5550. //
  5551. // Parameters:
  5552. // b - Boolean indicating bold (true) or normal (false)
  5553. this.setBold = function(b) {
  5554. var selected = selectedElements[0];
  5555. if (selected != null && selected.tagName == 'text' &&
  5556. selectedElements[1] == null)
  5557. {
  5558. changeSelectedAttribute('font-weight', b ? 'bold' : 'normal');
  5559. }
  5560. if (!selectedElements[0].textContent) {
  5561. textActions.setCursor();
  5562. }
  5563. };
  5564. // Function: getItalic
  5565. // Check whether selected element is italic or not
  5566. //
  5567. // Returns:
  5568. // Boolean indicating whether or not element is italic
  5569. this.getItalic = function() {
  5570. var selected = selectedElements[0];
  5571. if (selected != null && selected.tagName == 'text' &&
  5572. selectedElements[1] == null)
  5573. {
  5574. return (selected.getAttribute('font-style') == 'italic');
  5575. }
  5576. return false;
  5577. };
  5578. // Function: setItalic
  5579. // Make the selected element italic or normal
  5580. //
  5581. // Parameters:
  5582. // b - Boolean indicating italic (true) or normal (false)
  5583. this.setItalic = function(i) {
  5584. var selected = selectedElements[0];
  5585. if (selected != null && selected.tagName == 'text' &&
  5586. selectedElements[1] == null)
  5587. {
  5588. changeSelectedAttribute('font-style', i ? 'italic' : 'normal');
  5589. }
  5590. if (!selectedElements[0].textContent) {
  5591. textActions.setCursor();
  5592. }
  5593. };
  5594. // Function: getFontFamily
  5595. // Returns the current font family
  5596. this.getFontFamily = function() {
  5597. return cur_text.font_family;
  5598. };
  5599. // Function: setFontFamily
  5600. // Set the new font family
  5601. //
  5602. // Parameters:
  5603. // val - String with the new font family
  5604. this.setFontFamily = function(val) {
  5605. cur_text.font_family = val;
  5606. changeSelectedAttribute('font-family', val);
  5607. if (selectedElements[0] && !selectedElements[0].textContent) {
  5608. textActions.setCursor();
  5609. }
  5610. };
  5611. // Function: setFontColor
  5612. // Set the new font color
  5613. //
  5614. // Parameters:
  5615. // val - String with the new font color
  5616. this.setFontColor = function(val) {
  5617. cur_text.fill = val;
  5618. changeSelectedAttribute('fill', val);
  5619. };
  5620. // Function: getFontColor
  5621. // Returns the current font color
  5622. this.getFontColor = function() {
  5623. return cur_text.fill;
  5624. };
  5625. // Function: getFontSize
  5626. // Returns the current font size
  5627. this.getFontSize = function() {
  5628. return cur_text.font_size;
  5629. };
  5630. // Function: setFontSize
  5631. // Applies the given font size to the selected element
  5632. //
  5633. // Parameters:
  5634. // val - Float with the new font size
  5635. this.setFontSize = function(val) {
  5636. cur_text.font_size = val;
  5637. changeSelectedAttribute('font-size', val);
  5638. if (!selectedElements[0].textContent) {
  5639. textActions.setCursor();
  5640. }
  5641. };
  5642. // Function: getText
  5643. // Returns the current text (textContent) of the selected element
  5644. this.getText = function() {
  5645. var selected = selectedElements[0];
  5646. if (selected == null) { return ''; }
  5647. return selected.textContent;
  5648. };
  5649. // Function: setTextContent
  5650. // Updates the text element with the given string
  5651. //
  5652. // Parameters:
  5653. // val - String with the new text
  5654. this.setTextContent = function(val) {
  5655. changeSelectedAttribute('#text', val);
  5656. textActions.init(val);
  5657. textActions.setCursor();
  5658. };
  5659. // Function: setImageURL
  5660. // Sets the new image URL for the selected image element. Updates its size if
  5661. // a new URL is given
  5662. //
  5663. // Parameters:
  5664. // val - String with the image URL/path
  5665. this.setImageURL = function(val) {
  5666. var elem = selectedElements[0];
  5667. if (!elem) {return;}
  5668. var attrs = $(elem).attr(['width', 'height']);
  5669. var setsize = (!attrs.width || !attrs.height);
  5670. var cur_href = getHref(elem);
  5671. // Do nothing if no URL change or size change
  5672. if (cur_href !== val) {
  5673. setsize = true;
  5674. } else if (!setsize) {return;}
  5675. var batchCmd = new svgedit.history.BatchCommand('Change Image URL');
  5676. setHref(elem, val);
  5677. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, {
  5678. '#href': cur_href
  5679. }));
  5680. if (setsize) {
  5681. $(new Image()).load(function() {
  5682. var changes = $(elem).attr(['width', 'height']);
  5683. $(elem).attr({
  5684. width: this.width,
  5685. height: this.height
  5686. });
  5687. selectorManager.requestSelector(elem).resize();
  5688. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, changes));
  5689. addCommandToHistory(batchCmd);
  5690. call('changed', [elem]);
  5691. }).attr('src', val);
  5692. } else {
  5693. addCommandToHistory(batchCmd);
  5694. }
  5695. };
  5696. // Function: setLinkURL
  5697. // Sets the new link URL for the selected anchor element.
  5698. //
  5699. // Parameters:
  5700. // val - String with the link URL/path
  5701. this.setLinkURL = function(val) {
  5702. var elem = selectedElements[0];
  5703. if (!elem) {return;}
  5704. if (elem.tagName !== 'a') {
  5705. // See if parent is an anchor
  5706. var parents_a = $(elem).parents('a');
  5707. if (parents_a.length) {
  5708. elem = parents_a[0];
  5709. } else {
  5710. return;
  5711. }
  5712. }
  5713. var cur_href = getHref(elem);
  5714. if (cur_href === val) {return;}
  5715. var batchCmd = new svgedit.history.BatchCommand('Change Link URL');
  5716. setHref(elem, val);
  5717. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(elem, {
  5718. '#href': cur_href
  5719. }));
  5720. addCommandToHistory(batchCmd);
  5721. };
  5722. // Function: setRectRadius
  5723. // Sets the rx & ry values to the selected rect element to change its corner radius
  5724. //
  5725. // Parameters:
  5726. // val - The new radius
  5727. this.setRectRadius = function(val) {
  5728. var selected = selectedElements[0];
  5729. if (selected != null && selected.tagName == 'rect') {
  5730. var r = selected.getAttribute('rx');
  5731. if (r != val) {
  5732. selected.setAttribute('rx', val);
  5733. selected.setAttribute('ry', val);
  5734. addCommandToHistory(new svgedit.history.ChangeElementCommand(selected, {'rx':r, 'ry':r}, 'Radius'));
  5735. call('changed', [selected]);
  5736. }
  5737. }
  5738. };
  5739. // Function: makeHyperlink
  5740. // Wraps the selected element(s) in an anchor element or converts group to one
  5741. this.makeHyperlink = function(url) {
  5742. canvas.groupSelectedElements('a', url);
  5743. // TODO: If element is a single "g", convert to "a"
  5744. // if (selectedElements.length > 1 && selectedElements[1]) {
  5745. };
  5746. // Function: removeHyperlink
  5747. this.removeHyperlink = function() {
  5748. canvas.ungroupSelectedElement();
  5749. };
  5750. // Group: Element manipulation
  5751. // Function: setSegType
  5752. // Sets the new segment type to the selected segment(s).
  5753. //
  5754. // Parameters:
  5755. // new_type - Integer with the new segment type
  5756. // See http://www.w3.org/TR/SVG/paths.html#InterfaceSVGPathSeg for list
  5757. this.setSegType = function(new_type) {
  5758. pathActions.setSegType(new_type);
  5759. };
  5760. // TODO(codedread): Remove the getBBox argument and split this function into two.
  5761. // Function: convertToPath
  5762. // Convert selected element to a path, or get the BBox of an element-as-path
  5763. //
  5764. // Parameters:
  5765. // elem - The DOM element to be converted
  5766. // getBBox - Boolean on whether or not to only return the path's BBox
  5767. //
  5768. // Returns:
  5769. // If the getBBox flag is true, the resulting path's bounding box object.
  5770. // Otherwise the resulting path element is returned.
  5771. this.convertToPath = function(elem, getBBox) {
  5772. if (elem == null) {
  5773. var elems = selectedElements;
  5774. $.each(selectedElements, function(i, elem) {
  5775. if (elem) {canvas.convertToPath(elem);}
  5776. });
  5777. return;
  5778. }
  5779. if (!getBBox) {
  5780. var batchCmd = new svgedit.history.BatchCommand('Convert element to Path');
  5781. }
  5782. var attrs = getBBox?{}:{
  5783. 'fill': cur_shape.fill,
  5784. 'fill-opacity': cur_shape.fill_opacity,
  5785. 'stroke': cur_shape.stroke,
  5786. 'stroke-width': cur_shape.stroke_width,
  5787. 'stroke-dasharray': cur_shape.stroke_dasharray,
  5788. 'stroke-linejoin': cur_shape.stroke_linejoin,
  5789. 'stroke-linecap': cur_shape.stroke_linecap,
  5790. 'stroke-opacity': cur_shape.stroke_opacity,
  5791. 'opacity': cur_shape.opacity,
  5792. 'visibility':'hidden'
  5793. };
  5794. // any attribute on the element not covered by the above
  5795. // TODO: make this list global so that we can properly maintain it
  5796. // TODO: what about @transform, @clip-rule, @fill-rule, etc?
  5797. $.each(['marker-start', 'marker-end', 'marker-mid', 'filter', 'clip-path'], function() {
  5798. if (elem.getAttribute(this)) {
  5799. attrs[this] = elem.getAttribute(this);
  5800. }
  5801. });
  5802. var path = addSvgElementFromJson({
  5803. 'element': 'path',
  5804. 'attr': attrs
  5805. });
  5806. var eltrans = elem.getAttribute('transform');
  5807. if (eltrans) {
  5808. path.setAttribute('transform', eltrans);
  5809. }
  5810. var id = elem.id;
  5811. var parent = elem.parentNode;
  5812. if (elem.nextSibling) {
  5813. parent.insertBefore(path, elem);
  5814. } else {
  5815. parent.appendChild(path);
  5816. }
  5817. var d = '';
  5818. var joinSegs = function(segs) {
  5819. $.each(segs, function(j, seg) {
  5820. var i;
  5821. var l = seg[0], pts = seg[1];
  5822. d += l;
  5823. for (i = 0; i < pts.length; i+=2) {
  5824. d += (pts[i] +','+pts[i+1]) + ' ';
  5825. }
  5826. });
  5827. };
  5828. // Possibly the cubed root of 6, but 1.81 works best
  5829. var num = 1.81;
  5830. var a, rx;
  5831. switch (elem.tagName) {
  5832. case 'ellipse':
  5833. case 'circle':
  5834. a = $(elem).attr(['rx', 'ry', 'cx', 'cy']);
  5835. var cx = a.cx, cy = a.cy;
  5836. rx = a.rx;
  5837. ry = a.ry;
  5838. if (elem.tagName == 'circle') {
  5839. rx = ry = $(elem).attr('r');
  5840. }
  5841. joinSegs([
  5842. ['M',[(cx-rx),(cy)]],
  5843. ['C',[(cx-rx),(cy-ry/num), (cx-rx/num),(cy-ry), (cx),(cy-ry)]],
  5844. ['C',[(cx+rx/num),(cy-ry), (cx+rx),(cy-ry/num), (cx+rx),(cy)]],
  5845. ['C',[(cx+rx),(cy+ry/num), (cx+rx/num),(cy+ry), (cx),(cy+ry)]],
  5846. ['C',[(cx-rx/num),(cy+ry), (cx-rx),(cy+ry/num), (cx-rx),(cy)]],
  5847. ['Z',[]]
  5848. ]);
  5849. break;
  5850. case 'path':
  5851. d = elem.getAttribute('d');
  5852. break;
  5853. case 'line':
  5854. a = $(elem).attr(['x1', 'y1', 'x2', 'y2']);
  5855. d = 'M'+a.x1+','+a.y1+'L'+a.x2+','+a.y2;
  5856. break;
  5857. case 'polyline':
  5858. case 'polygon':
  5859. d = 'M' + elem.getAttribute('points');
  5860. break;
  5861. case 'rect':
  5862. var r = $(elem).attr(['rx', 'ry']);
  5863. rx = r.rx;
  5864. ry = r.ry;
  5865. var b = elem.getBBox();
  5866. var x = b.x, y = b.y, w = b.width, h = b.height;
  5867. num = 4 - num; // Why? Because!
  5868. if (!rx && !ry) {
  5869. // Regular rect
  5870. joinSegs([
  5871. ['M',[x, y]],
  5872. ['L',[x+w, y]],
  5873. ['L',[x+w, y+h]],
  5874. ['L',[x, y+h]],
  5875. ['L',[x, y]],
  5876. ['Z',[]]
  5877. ]);
  5878. } else {
  5879. joinSegs([
  5880. ['M',[x, y+ry]],
  5881. ['C',[x, y+ry/num, x+rx/num, y, x+rx, y]],
  5882. ['L',[x+w-rx, y]],
  5883. ['C',[x+w-rx/num, y, x+w, y+ry/num, x+w, y+ry]],
  5884. ['L',[x+w, y+h-ry]],
  5885. ['C',[x+w, y+h-ry/num, x+w-rx/num, y+h, x+w-rx, y+h]],
  5886. ['L',[x+rx, y+h]],
  5887. ['C',[x+rx/num, y+h, x, y+h-ry/num, x, y+h-ry]],
  5888. ['L',[x, y+ry]],
  5889. ['Z',[]]
  5890. ]);
  5891. }
  5892. break;
  5893. default:
  5894. path.parentNode.removeChild(path);
  5895. break;
  5896. }
  5897. if (d) {
  5898. path.setAttribute('d', d);
  5899. }
  5900. if (!getBBox) {
  5901. // Replace the current element with the converted one
  5902. // Reorient if it has a matrix
  5903. if (eltrans) {
  5904. var tlist = svgedit.transformlist.getTransformList(path);
  5905. if (svgedit.math.hasMatrixTransform(tlist)) {
  5906. pathActions.resetOrientation(path);
  5907. }
  5908. }
  5909. var nextSibling = elem.nextSibling;
  5910. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(elem, nextSibling, parent));
  5911. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(path));
  5912. clearSelection();
  5913. elem.parentNode.removeChild(elem);
  5914. path.setAttribute('id', id);
  5915. path.removeAttribute('visibility');
  5916. addToSelection([path], true);
  5917. addCommandToHistory(batchCmd);
  5918. } else {
  5919. // Get the correct BBox of the new path, then discard it
  5920. pathActions.resetOrientation(path);
  5921. var bb = false;
  5922. try {
  5923. bb = path.getBBox();
  5924. } catch(e) {
  5925. // Firefox fails
  5926. }
  5927. path.parentNode.removeChild(path);
  5928. return bb;
  5929. }
  5930. };
  5931. // Function: changeSelectedAttributeNoUndo
  5932. // This function makes the changes to the elements. It does not add the change
  5933. // to the history stack.
  5934. //
  5935. // Parameters:
  5936. // attr - String with the attribute name
  5937. // newValue - String or number with the new attribute value
  5938. // elems - The DOM elements to apply the change to
  5939. var changeSelectedAttributeNoUndo = function(attr, newValue, elems) {
  5940. if (current_mode == 'pathedit') {
  5941. // Editing node
  5942. pathActions.moveNode(attr, newValue);
  5943. }
  5944. elems = elems || selectedElements;
  5945. var i = elems.length;
  5946. var no_xy_elems = ['g', 'polyline', 'path'];
  5947. var good_g_attrs = ['transform', 'opacity', 'filter'];
  5948. while (i--) {
  5949. var elem = elems[i];
  5950. if (elem == null) {continue;}
  5951. // Set x,y vals on elements that don't have them
  5952. if ((attr === 'x' || attr === 'y') && no_xy_elems.indexOf(elem.tagName) >= 0) {
  5953. var bbox = getStrokedBBox([elem]);
  5954. var diff_x = attr === 'x' ? newValue - bbox.x : 0;
  5955. var diff_y = attr === 'y' ? newValue - bbox.y : 0;
  5956. canvas.moveSelectedElements(diff_x*current_zoom, diff_y*current_zoom, true);
  5957. continue;
  5958. }
  5959. // only allow the transform/opacity/filter attribute to change on <g> elements, slightly hacky
  5960. // TODO: FIXME: This doesn't seem right. Where's the body of this if statement?
  5961. if (elem.tagName === 'g' && good_g_attrs.indexOf(attr) >= 0) {}
  5962. var oldval = attr === '#text' ? elem.textContent : elem.getAttribute(attr);
  5963. if (oldval == null) {oldval = '';}
  5964. if (oldval !== String(newValue)) {
  5965. if (attr == '#text') {
  5966. var old_w = svgedit.utilities.getBBox(elem).width;
  5967. elem.textContent = newValue;
  5968. // FF bug occurs on on rotated elements
  5969. if (/rotate/.test(elem.getAttribute('transform'))) {
  5970. elem = ffClone(elem);
  5971. }
  5972. // Hoped to solve the issue of moving text with text-anchor="start",
  5973. // but this doesn't actually fix it. Hopefully on the right track, though. -Fyrd
  5974. // var box=getBBox(elem), left=box.x, top=box.y, width=box.width,
  5975. // height=box.height, dx = width - old_w, dy=0;
  5976. // var angle = svgedit.utilities.getRotationAngle(elem, true);
  5977. // if (angle) {
  5978. // var r = Math.sqrt( dx*dx + dy*dy );
  5979. // var theta = Math.atan2(dy,dx) - angle;
  5980. // dx = r * Math.cos(theta);
  5981. // dy = r * Math.sin(theta);
  5982. //
  5983. // elem.setAttribute('x', elem.getAttribute('x')-dx);
  5984. // elem.setAttribute('y', elem.getAttribute('y')-dy);
  5985. // }
  5986. } else if (attr == '#href') {
  5987. setHref(elem, newValue);
  5988. }
  5989. else {elem.setAttribute(attr, newValue);}
  5990. // Go into "select" mode for text changes
  5991. // NOTE: Important that this happens AFTER elem.setAttribute() or else attributes like
  5992. // font-size can get reset to their old value, ultimately by svgEditor.updateContextPanel(),
  5993. // after calling textActions.toSelectMode() below
  5994. if (current_mode === 'textedit' && attr !== '#text' && elem.textContent.length) {
  5995. textActions.toSelectMode(elem);
  5996. }
  5997. // if (i==0)
  5998. // selectedBBoxes[0] = svgedit.utilities.getBBox(elem);
  5999. // Use the Firefox ffClone hack for text elements with gradients or
  6000. // where other text attributes are changed.
  6001. if (svgedit.browser.isGecko() && elem.nodeName === 'text' && /rotate/.test(elem.getAttribute('transform'))) {
  6002. if (String(newValue).indexOf('url') === 0 || (['font-size', 'font-family', 'x', 'y'].indexOf(attr) >= 0 && elem.textContent)) {
  6003. elem = ffClone(elem);
  6004. }
  6005. }
  6006. // Timeout needed for Opera & Firefox
  6007. // codedread: it is now possible for this function to be called with elements
  6008. // that are not in the selectedElements array, we need to only request a
  6009. // selector if the element is in that array
  6010. if (selectedElements.indexOf(elem) >= 0) {
  6011. setTimeout(function() {
  6012. // Due to element replacement, this element may no longer
  6013. // be part of the DOM
  6014. if (!elem.parentNode) {return;}
  6015. selectorManager.requestSelector(elem).resize();
  6016. }, 0);
  6017. }
  6018. // if this element was rotated, and we changed the position of this element
  6019. // we need to update the rotational transform attribute
  6020. var angle = svgedit.utilities.getRotationAngle(elem);
  6021. if (angle != 0 && attr != 'transform') {
  6022. var tlist = svgedit.transformlist.getTransformList(elem);
  6023. var n = tlist.numberOfItems;
  6024. while (n--) {
  6025. var xform = tlist.getItem(n);
  6026. if (xform.type == 4) {
  6027. // remove old rotate
  6028. tlist.removeItem(n);
  6029. var box = svgedit.utilities.getBBox(elem);
  6030. var center = svgedit.math.transformPoint(box.x+box.width/2, box.y+box.height/2, svgedit.math.transformListToTransform(tlist).matrix);
  6031. var cx = center.x,
  6032. cy = center.y;
  6033. var newrot = svgroot.createSVGTransform();
  6034. newrot.setRotate(angle, cx, cy);
  6035. tlist.insertItemBefore(newrot, n);
  6036. break;
  6037. }
  6038. }
  6039. }
  6040. } // if oldValue != newValue
  6041. } // for each elem
  6042. };
  6043. // Function: changeSelectedAttribute
  6044. // Change the given/selected element and add the original value to the history stack
  6045. // If you want to change all selectedElements, ignore the elems argument.
  6046. // If you want to change only a subset of selectedElements, then send the
  6047. // subset to this function in the elems argument.
  6048. //
  6049. // Parameters:
  6050. // attr - String with the attribute name
  6051. // newValue - String or number with the new attribute value
  6052. // elems - The DOM elements to apply the change to
  6053. var changeSelectedAttribute = this.changeSelectedAttribute = function(attr, val, elems) {
  6054. elems = elems || selectedElements;
  6055. canvas.undoMgr.beginUndoableChange(attr, elems);
  6056. var i = elems.length;
  6057. changeSelectedAttributeNoUndo(attr, val, elems);
  6058. var batchCmd = canvas.undoMgr.finishUndoableChange();
  6059. if (!batchCmd.isEmpty()) {
  6060. addCommandToHistory(batchCmd);
  6061. }
  6062. };
  6063. // Function: deleteSelectedElements
  6064. // Removes all selected elements from the DOM and adds the change to the
  6065. // history stack
  6066. this.deleteSelectedElements = function() {
  6067. var i;
  6068. var batchCmd = new svgedit.history.BatchCommand('Delete Elements');
  6069. var len = selectedElements.length;
  6070. var selectedCopy = []; //selectedElements is being deleted
  6071. for (i = 0; i < len; ++i) {
  6072. var selected = selectedElements[i];
  6073. if (selected == null) {break;}
  6074. var parent = selected.parentNode;
  6075. var t = selected;
  6076. // this will unselect the element and remove the selectedOutline
  6077. selectorManager.releaseSelector(t);
  6078. // Remove the path if present.
  6079. svgedit.path.removePath_(t.id);
  6080. // Get the parent if it's a single-child anchor
  6081. if (parent.tagName === 'a' && parent.childNodes.length === 1) {
  6082. t = parent;
  6083. parent = parent.parentNode;
  6084. }
  6085. var nextSibling = t.nextSibling;
  6086. var elem = parent.removeChild(t);
  6087. selectedCopy.push(selected); //for the copy
  6088. selectedElements[i] = null;
  6089. batchCmd.addSubCommand(new RemoveElementCommand(elem, nextSibling, parent));
  6090. }
  6091. if (!batchCmd.isEmpty()) {addCommandToHistory(batchCmd);}
  6092. call('changed', selectedCopy);
  6093. clearSelection();
  6094. };
  6095. // Function: cutSelectedElements
  6096. // Removes all selected elements from the DOM and adds the change to the
  6097. // history stack. Remembers removed elements on the clipboard
  6098. // TODO: Combine similar code with deleteSelectedElements
  6099. this.cutSelectedElements = function() {
  6100. var i;
  6101. var batchCmd = new svgedit.history.BatchCommand('Cut Elements');
  6102. var len = selectedElements.length;
  6103. var selectedCopy = []; //selectedElements is being deleted
  6104. for (i = 0; i < len; ++i) {
  6105. var selected = selectedElements[i];
  6106. if (selected == null) {break;}
  6107. var parent = selected.parentNode;
  6108. var t = selected;
  6109. // this will unselect the element and remove the selectedOutline
  6110. selectorManager.releaseSelector(t);
  6111. // Remove the path if present.
  6112. svgedit.path.removePath_(t.id);
  6113. var nextSibling = t.nextSibling;
  6114. var elem = parent.removeChild(t);
  6115. selectedCopy.push(selected); //for the copy
  6116. selectedElements[i] = null;
  6117. batchCmd.addSubCommand(new RemoveElementCommand(elem, nextSibling, parent));
  6118. }
  6119. if (!batchCmd.isEmpty()) {addCommandToHistory(batchCmd);}
  6120. call('changed', selectedCopy);
  6121. clearSelection();
  6122. canvas.clipBoard = selectedCopy;
  6123. };
  6124. // Function: copySelectedElements
  6125. // Remembers the current selected elements on the clipboard
  6126. this.copySelectedElements = function() {
  6127. canvas.clipBoard = $.merge([], selectedElements);
  6128. };
  6129. this.pasteElements = function(type, x, y) {
  6130. var cb = canvas.clipBoard;
  6131. var len = cb.length;
  6132. if (!len) {return;}
  6133. var pasted = [];
  6134. var batchCmd = new svgedit.history.BatchCommand('Paste elements');
  6135. // Move elements to lastClickPoint
  6136. while (len--) {
  6137. var elem = cb[len];
  6138. if (!elem) {continue;}
  6139. var copy = copyElem(elem);
  6140. // See if elem with elem ID is in the DOM already
  6141. if (!svgedit.utilities.getElem(elem.id)) {copy.id = elem.id;}
  6142. pasted.push(copy);
  6143. (current_group || getCurrentDrawing().getCurrentLayer()).appendChild(copy);
  6144. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(copy));
  6145. }
  6146. selectOnly(pasted);
  6147. if (type !== 'in_place') {
  6148. var ctr_x, ctr_y;
  6149. if (!type) {
  6150. ctr_x = lastClickPoint.x;
  6151. ctr_y = lastClickPoint.y;
  6152. } else if (type === 'point') {
  6153. ctr_x = x;
  6154. ctr_y = y;
  6155. }
  6156. var bbox = getStrokedBBox(pasted);
  6157. var cx = ctr_x - (bbox.x + bbox.width/2),
  6158. cy = ctr_y - (bbox.y + bbox.height/2),
  6159. dx = [],
  6160. dy = [];
  6161. $.each(pasted, function(i, item) {
  6162. dx.push(cx);
  6163. dy.push(cy);
  6164. });
  6165. var cmd = canvas.moveSelectedElements(dx, dy, false);
  6166. batchCmd.addSubCommand(cmd);
  6167. }
  6168. addCommandToHistory(batchCmd);
  6169. call('changed', pasted);
  6170. };
  6171. // Function: groupSelectedElements
  6172. // Wraps all the selected elements in a group (g) element
  6173. // Parameters:
  6174. // type - type of element to group into, defaults to <g>
  6175. this.groupSelectedElements = function(type, urlArg) {
  6176. if (!type) {type = 'g';}
  6177. var cmd_str = '';
  6178. switch (type) {
  6179. case 'a':
  6180. cmd_str = 'Make hyperlink';
  6181. var url = '';
  6182. if (arguments.length > 1) {
  6183. url = urlArg;
  6184. }
  6185. break;
  6186. default:
  6187. type = 'g';
  6188. cmd_str = 'Group Elements';
  6189. break;
  6190. }
  6191. var batchCmd = new svgedit.history.BatchCommand(cmd_str);
  6192. // create and insert the group element
  6193. var g = addSvgElementFromJson({
  6194. 'element': type,
  6195. 'attr': {
  6196. 'id': getNextId()
  6197. }
  6198. });
  6199. if (type === 'a') {
  6200. setHref(g, url);
  6201. }
  6202. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(g));
  6203. // now move all children into the group
  6204. var i = selectedElements.length;
  6205. while (i--) {
  6206. var elem = selectedElements[i];
  6207. if (elem == null) {continue;}
  6208. if (elem.parentNode.tagName === 'a' && elem.parentNode.childNodes.length === 1) {
  6209. elem = elem.parentNode;
  6210. }
  6211. var oldNextSibling = elem.nextSibling;
  6212. var oldParent = elem.parentNode;
  6213. g.appendChild(elem);
  6214. batchCmd.addSubCommand(new svgedit.history.MoveElementCommand(elem, oldNextSibling, oldParent));
  6215. }
  6216. if (!batchCmd.isEmpty()) {addCommandToHistory(batchCmd);}
  6217. // update selection
  6218. selectOnly([g], true);
  6219. };
  6220. // Function: pushGroupProperties
  6221. // Pushes all appropriate parent group properties down to its children, then
  6222. // removes them from the group
  6223. var pushGroupProperties = this.pushGroupProperties = function(g, undoable) {
  6224. var children = g.childNodes;
  6225. var len = children.length;
  6226. var xform = g.getAttribute('transform');
  6227. var glist = svgedit.transformlist.getTransformList(g);
  6228. var m = svgedit.math.transformListToTransform(glist).matrix;
  6229. var batchCmd = new svgedit.history.BatchCommand('Push group properties');
  6230. // TODO: get all fill/stroke properties from the group that we are about to destroy
  6231. // "fill", "fill-opacity", "fill-rule", "stroke", "stroke-dasharray", "stroke-dashoffset",
  6232. // "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity",
  6233. // "stroke-width"
  6234. // and then for each child, if they do not have the attribute (or the value is 'inherit')
  6235. // then set the child's attribute
  6236. var i = 0;
  6237. var gangle = svgedit.utilities.getRotationAngle(g);
  6238. var gattrs = $(g).attr(['filter', 'opacity']);
  6239. var gfilter, gblur, changes;
  6240. for (i = 0; i < len; i++) {
  6241. var elem = children[i];
  6242. if (elem.nodeType !== 1) {continue;}
  6243. if (gattrs.opacity !== null && gattrs.opacity !== 1) {
  6244. var c_opac = elem.getAttribute('opacity') || 1;
  6245. var new_opac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100)/100;
  6246. changeSelectedAttribute('opacity', new_opac, [elem]);
  6247. }
  6248. if (gattrs.filter) {
  6249. var cblur = this.getBlur(elem);
  6250. var orig_cblur = cblur;
  6251. if (!gblur) {gblur = this.getBlur(g);}
  6252. if (cblur) {
  6253. // Is this formula correct?
  6254. cblur = Number(gblur) + Number(cblur);
  6255. } else if (cblur === 0) {
  6256. cblur = gblur;
  6257. }
  6258. // If child has no current filter, get group's filter or clone it.
  6259. if (!orig_cblur) {
  6260. // Set group's filter to use first child's ID
  6261. if (!gfilter) {
  6262. gfilter = svgedit.utilities.getRefElem(gattrs.filter);
  6263. } else {
  6264. // Clone the group's filter
  6265. gfilter = copyElem(gfilter);
  6266. svgedit.utilities.findDefs().appendChild(gfilter);
  6267. }
  6268. } else {
  6269. gfilter = svgedit.utilities.getRefElem(elem.getAttribute('filter'));
  6270. }
  6271. // Change this in future for different filters
  6272. var suffix = (gfilter.firstChild.tagName === 'feGaussianBlur')?'blur':'filter';
  6273. gfilter.id = elem.id + '_' + suffix;
  6274. changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]);
  6275. // Update blur value
  6276. if (cblur) {
  6277. changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]);
  6278. canvas.setBlurOffsets(gfilter, cblur);
  6279. }
  6280. }
  6281. var chtlist = svgedit.transformlist.getTransformList(elem);
  6282. // Don't process gradient transforms
  6283. if (~elem.tagName.indexOf('Gradient')) {chtlist = null;}
  6284. // Hopefully not a problem to add this. Necessary for elements like <desc/>
  6285. if (!chtlist) {continue;}
  6286. // Apparently <defs> can get get a transformlist, but we don't want it to have one!
  6287. if (elem.tagName === 'defs') {continue;}
  6288. if (glist.numberOfItems) {
  6289. // TODO: if the group's transform is just a rotate, we can always transfer the
  6290. // rotate() down to the children (collapsing consecutive rotates and factoring
  6291. // out any translates)
  6292. if (gangle && glist.numberOfItems == 1) {
  6293. // [Rg] [Rc] [Mc]
  6294. // we want [Tr] [Rc2] [Mc] where:
  6295. // - [Rc2] is at the child's current center but has the
  6296. // sum of the group and child's rotation angles
  6297. // - [Tr] is the equivalent translation that this child
  6298. // undergoes if the group wasn't there
  6299. // [Tr] = [Rg] [Rc] [Rc2_inv]
  6300. // get group's rotation matrix (Rg)
  6301. var rgm = glist.getItem(0).matrix;
  6302. // get child's rotation matrix (Rc)
  6303. var rcm = svgroot.createSVGMatrix();
  6304. var cangle = svgedit.utilities.getRotationAngle(elem);
  6305. if (cangle) {
  6306. rcm = chtlist.getItem(0).matrix;
  6307. }
  6308. // get child's old center of rotation
  6309. var cbox = svgedit.utilities.getBBox(elem);
  6310. var ceqm = svgedit.math.transformListToTransform(chtlist).matrix;
  6311. var coldc = svgedit.math.transformPoint(cbox.x+cbox.width/2, cbox.y+cbox.height/2, ceqm);
  6312. // sum group and child's angles
  6313. var sangle = gangle + cangle;
  6314. // get child's rotation at the old center (Rc2_inv)
  6315. var r2 = svgroot.createSVGTransform();
  6316. r2.setRotate(sangle, coldc.x, coldc.y);
  6317. // calculate equivalent translate
  6318. var trm = svgedit.math.matrixMultiply(rgm, rcm, r2.matrix.inverse());
  6319. // set up tlist
  6320. if (cangle) {
  6321. chtlist.removeItem(0);
  6322. }
  6323. if (sangle) {
  6324. if (chtlist.numberOfItems) {
  6325. chtlist.insertItemBefore(r2, 0);
  6326. } else {
  6327. chtlist.appendItem(r2);
  6328. }
  6329. }
  6330. if (trm.e || trm.f) {
  6331. var tr = svgroot.createSVGTransform();
  6332. tr.setTranslate(trm.e, trm.f);
  6333. if (chtlist.numberOfItems) {
  6334. chtlist.insertItemBefore(tr, 0);
  6335. } else {
  6336. chtlist.appendItem(tr);
  6337. }
  6338. }
  6339. } else { // more complicated than just a rotate
  6340. // transfer the group's transform down to each child and then
  6341. // call svgedit.recalculate.recalculateDimensions()
  6342. var oldxform = elem.getAttribute('transform');
  6343. changes = {};
  6344. changes.transform = oldxform || '';
  6345. var newxform = svgroot.createSVGTransform();
  6346. // [ gm ] [ chm ] = [ chm ] [ gm' ]
  6347. // [ gm' ] = [ chm_inv ] [ gm ] [ chm ]
  6348. var chm = svgedit.math.transformListToTransform(chtlist).matrix,
  6349. chm_inv = chm.inverse();
  6350. var gm = svgedit.math.matrixMultiply( chm_inv, m, chm );
  6351. newxform.setMatrix(gm);
  6352. chtlist.appendItem(newxform);
  6353. }
  6354. var cmd = svgedit.recalculate.recalculateDimensions(elem);
  6355. if (cmd) {batchCmd.addSubCommand(cmd);}
  6356. }
  6357. }
  6358. // remove transform and make it undo-able
  6359. if (xform) {
  6360. changes = {};
  6361. changes.transform = xform;
  6362. g.setAttribute('transform', '');
  6363. g.removeAttribute('transform');
  6364. batchCmd.addSubCommand(new svgedit.history.ChangeElementCommand(g, changes));
  6365. }
  6366. if (undoable && !batchCmd.isEmpty()) {
  6367. return batchCmd;
  6368. }
  6369. };
  6370. // Function: ungroupSelectedElement
  6371. // Unwraps all the elements in a selected group (g) element. This requires
  6372. // significant recalculations to apply group's transforms, etc to its children
  6373. this.ungroupSelectedElement = function() {
  6374. var g = selectedElements[0];
  6375. if (!g) {
  6376. return;
  6377. }
  6378. if ($(g).data('gsvg') || $(g).data('symbol')) {
  6379. // Is svg, so actually convert to group
  6380. convertToGroup(g);
  6381. return;
  6382. }
  6383. if (g.tagName === 'use') {
  6384. // Somehow doesn't have data set, so retrieve
  6385. var symbol = svgedit.utilities.getElem(getHref(g).substr(1));
  6386. $(g).data('symbol', symbol).data('ref', symbol);
  6387. convertToGroup(g);
  6388. return;
  6389. }
  6390. var parents_a = $(g).parents('a');
  6391. if (parents_a.length) {
  6392. g = parents_a[0];
  6393. }
  6394. // Look for parent "a"
  6395. if (g.tagName === 'g' || g.tagName === 'a') {
  6396. var batchCmd = new svgedit.history.BatchCommand('Ungroup Elements');
  6397. var cmd = pushGroupProperties(g, true);
  6398. if (cmd) {batchCmd.addSubCommand(cmd);}
  6399. var parent = g.parentNode;
  6400. var anchor = g.nextSibling;
  6401. var children = new Array(g.childNodes.length);
  6402. var i = 0;
  6403. while (g.firstChild) {
  6404. var elem = g.firstChild;
  6405. var oldNextSibling = elem.nextSibling;
  6406. var oldParent = elem.parentNode;
  6407. // Remove child title elements
  6408. if (elem.tagName === 'title') {
  6409. var nextSibling = elem.nextSibling;
  6410. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(elem, nextSibling, oldParent));
  6411. oldParent.removeChild(elem);
  6412. continue;
  6413. }
  6414. children[i++] = elem = parent.insertBefore(elem, anchor);
  6415. batchCmd.addSubCommand(new svgedit.history.MoveElementCommand(elem, oldNextSibling, oldParent));
  6416. }
  6417. // remove the group from the selection
  6418. clearSelection();
  6419. // delete the group element (but make undo-able)
  6420. var gNextSibling = g.nextSibling;
  6421. g = parent.removeChild(g);
  6422. batchCmd.addSubCommand(new svgedit.history.RemoveElementCommand(g, gNextSibling, parent));
  6423. if (!batchCmd.isEmpty()) {addCommandToHistory(batchCmd);}
  6424. // update selection
  6425. addToSelection(children);
  6426. }
  6427. };
  6428. // Function: moveToTopSelectedElement
  6429. // Repositions the selected element to the bottom in the DOM to appear on top of
  6430. // other elements
  6431. this.moveToTopSelectedElement = function() {
  6432. var selected = selectedElements[0];
  6433. if (selected != null) {
  6434. var t = selected;
  6435. var oldParent = t.parentNode;
  6436. var oldNextSibling = t.nextSibling;
  6437. t = t.parentNode.appendChild(t);
  6438. // If the element actually moved position, add the command and fire the changed
  6439. // event handler.
  6440. if (oldNextSibling != t.nextSibling) {
  6441. addCommandToHistory(new svgedit.history.MoveElementCommand(t, oldNextSibling, oldParent, 'top'));
  6442. call('changed', [t]);
  6443. }
  6444. }
  6445. };
  6446. // Function: moveToBottomSelectedElement
  6447. // Repositions the selected element to the top in the DOM to appear under
  6448. // other elements
  6449. this.moveToBottomSelectedElement = function() {
  6450. var selected = selectedElements[0];
  6451. if (selected != null) {
  6452. var t = selected;
  6453. var oldParent = t.parentNode;
  6454. var oldNextSibling = t.nextSibling;
  6455. var firstChild = t.parentNode.firstChild;
  6456. if (firstChild.tagName == 'title') {
  6457. firstChild = firstChild.nextSibling;
  6458. }
  6459. // This can probably be removed, as the defs should not ever apppear
  6460. // inside a layer group
  6461. if (firstChild.tagName == 'defs') {
  6462. firstChild = firstChild.nextSibling;
  6463. }
  6464. t = t.parentNode.insertBefore(t, firstChild);
  6465. // If the element actually moved position, add the command and fire the changed
  6466. // event handler.
  6467. if (oldNextSibling != t.nextSibling) {
  6468. addCommandToHistory(new svgedit.history.MoveElementCommand(t, oldNextSibling, oldParent, 'bottom'));
  6469. call('changed', [t]);
  6470. }
  6471. }
  6472. };
  6473. // Function: moveUpDownSelected
  6474. // Moves the select element up or down the stack, based on the visibly
  6475. // intersecting elements
  6476. //
  6477. // Parameters:
  6478. // dir - String that's either 'Up' or 'Down'
  6479. this.moveUpDownSelected = function(dir) {
  6480. var selected = selectedElements[0];
  6481. if (!selected) {return;}
  6482. curBBoxes = [];
  6483. var closest, found_cur;
  6484. // jQuery sorts this list
  6485. var list = $(getIntersectionList(getStrokedBBox([selected]))).toArray();
  6486. if (dir == 'Down') {list.reverse();}
  6487. $.each(list, function() {
  6488. if (!found_cur) {
  6489. if (this == selected) {
  6490. found_cur = true;
  6491. }
  6492. return;
  6493. }
  6494. closest = this;
  6495. return false;
  6496. });
  6497. if (!closest) {return;}
  6498. var t = selected;
  6499. var oldParent = t.parentNode;
  6500. var oldNextSibling = t.nextSibling;
  6501. $(closest)[dir == 'Down'?'before':'after'](t);
  6502. // If the element actually moved position, add the command and fire the changed
  6503. // event handler.
  6504. if (oldNextSibling != t.nextSibling) {
  6505. addCommandToHistory(new svgedit.history.MoveElementCommand(t, oldNextSibling, oldParent, 'Move ' + dir));
  6506. call('changed', [t]);
  6507. }
  6508. };
  6509. // Function: moveSelectedElements
  6510. // Moves selected elements on the X/Y axis
  6511. //
  6512. // Parameters:
  6513. // dx - Float with the distance to move on the x-axis
  6514. // dy - Float with the distance to move on the y-axis
  6515. // undoable - Boolean indicating whether or not the action should be undoable
  6516. //
  6517. // Returns:
  6518. // Batch command for the move
  6519. this.moveSelectedElements = function(dx, dy, undoable) {
  6520. // if undoable is not sent, default to true
  6521. // if single values, scale them to the zoom
  6522. if (dx.constructor != Array) {
  6523. dx /= current_zoom;
  6524. dy /= current_zoom;
  6525. }
  6526. undoable = undoable || true;
  6527. var batchCmd = new svgedit.history.BatchCommand('position');
  6528. var i = selectedElements.length;
  6529. while (i--) {
  6530. var selected = selectedElements[i];
  6531. if (selected != null) {
  6532. // if (i==0)
  6533. // selectedBBoxes[0] = svgedit.utilities.getBBox(selected);
  6534. // var b = {};
  6535. // for (var j in selectedBBoxes[i]) b[j] = selectedBBoxes[i][j];
  6536. // selectedBBoxes[i] = b;
  6537. var xform = svgroot.createSVGTransform();
  6538. var tlist = svgedit.transformlist.getTransformList(selected);
  6539. // dx and dy could be arrays
  6540. if (dx.constructor == Array) {
  6541. // if (i==0) {
  6542. // selectedBBoxes[0].x += dx[0];
  6543. // selectedBBoxes[0].y += dy[0];
  6544. // }
  6545. xform.setTranslate(dx[i], dy[i]);
  6546. } else {
  6547. // if (i==0) {
  6548. // selectedBBoxes[0].x += dx;
  6549. // selectedBBoxes[0].y += dy;
  6550. // }
  6551. xform.setTranslate(dx, dy);
  6552. }
  6553. if (tlist.numberOfItems) {
  6554. tlist.insertItemBefore(xform, 0);
  6555. } else {
  6556. tlist.appendItem(xform);
  6557. }
  6558. var cmd = svgedit.recalculate.recalculateDimensions(selected);
  6559. if (cmd) {
  6560. batchCmd.addSubCommand(cmd);
  6561. }
  6562. selectorManager.requestSelector(selected).resize();
  6563. }
  6564. }
  6565. if (!batchCmd.isEmpty()) {
  6566. if (undoable) {
  6567. addCommandToHistory(batchCmd);
  6568. }
  6569. call('changed', selectedElements);
  6570. return batchCmd;
  6571. }
  6572. };
  6573. // Function: cloneSelectedElements
  6574. // Create deep DOM copies (clones) of all selected elements and move them slightly
  6575. // from their originals
  6576. this.cloneSelectedElements = function(x, y) {
  6577. var i, elem;
  6578. var batchCmd = new svgedit.history.BatchCommand('Clone Elements');
  6579. // find all the elements selected (stop at first null)
  6580. var len = selectedElements.length;
  6581. function sortfunction(a, b){
  6582. return ($(b).index() - $(a).index()); //causes an array to be sorted numerically and ascending
  6583. }
  6584. selectedElements.sort(sortfunction);
  6585. for (i = 0; i < len; ++i) {
  6586. elem = selectedElements[i];
  6587. if (elem == null) {break;}
  6588. }
  6589. // use slice to quickly get the subset of elements we need
  6590. var copiedElements = selectedElements.slice(0, i);
  6591. this.clearSelection(true);
  6592. // note that we loop in the reverse way because of the way elements are added
  6593. // to the selectedElements array (top-first)
  6594. i = copiedElements.length;
  6595. while (i--) {
  6596. // clone each element and replace it within copiedElements
  6597. elem = copiedElements[i] = copyElem(copiedElements[i]);
  6598. (current_group || getCurrentDrawing().getCurrentLayer()).appendChild(elem);
  6599. batchCmd.addSubCommand(new svgedit.history.InsertElementCommand(elem));
  6600. }
  6601. if (!batchCmd.isEmpty()) {
  6602. addToSelection(copiedElements.reverse()); // Need to reverse for correct selection-adding
  6603. this.moveSelectedElements(x, y, false);
  6604. addCommandToHistory(batchCmd);
  6605. }
  6606. };
  6607. // Function: alignSelectedElements
  6608. // Aligns selected elements
  6609. //
  6610. // Parameters:
  6611. // type - String with single character indicating the alignment type
  6612. // relative_to - String that must be one of the following:
  6613. // "selected", "largest", "smallest", "page"
  6614. this.alignSelectedElements = function(type, relative_to) {
  6615. var i, elem;
  6616. var bboxes = [], angles = [];
  6617. var minx = Number.MAX_VALUE, maxx = Number.MIN_VALUE, miny = Number.MAX_VALUE, maxy = Number.MIN_VALUE;
  6618. var curwidth = Number.MIN_VALUE, curheight = Number.MIN_VALUE;
  6619. var len = selectedElements.length;
  6620. if (!len) {return;}
  6621. for (i = 0; i < len; ++i) {
  6622. if (selectedElements[i] == null) {break;}
  6623. elem = selectedElements[i];
  6624. bboxes[i] = getStrokedBBox([elem]);
  6625. // now bbox is axis-aligned and handles rotation
  6626. switch (relative_to) {
  6627. case 'smallest':
  6628. if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth > bboxes[i].width) ||
  6629. (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight > bboxes[i].height) ) {
  6630. minx = bboxes[i].x;
  6631. miny = bboxes[i].y;
  6632. maxx = bboxes[i].x + bboxes[i].width;
  6633. maxy = bboxes[i].y + bboxes[i].height;
  6634. curwidth = bboxes[i].width;
  6635. curheight = bboxes[i].height;
  6636. }
  6637. break;
  6638. case 'largest':
  6639. if ( (type == 'l' || type == 'c' || type == 'r') && (curwidth == Number.MIN_VALUE || curwidth < bboxes[i].width) ||
  6640. (type == 't' || type == 'm' || type == 'b') && (curheight == Number.MIN_VALUE || curheight < bboxes[i].height) ) {
  6641. minx = bboxes[i].x;
  6642. miny = bboxes[i].y;
  6643. maxx = bboxes[i].x + bboxes[i].width;
  6644. maxy = bboxes[i].y + bboxes[i].height;
  6645. curwidth = bboxes[i].width;
  6646. curheight = bboxes[i].height;
  6647. }
  6648. break;
  6649. default: // 'selected'
  6650. if (bboxes[i].x < minx) {minx = bboxes[i].x;}
  6651. if (bboxes[i].y < miny) {miny = bboxes[i].y;}
  6652. if (bboxes[i].x + bboxes[i].width > maxx) {maxx = bboxes[i].x + bboxes[i].width;}
  6653. if (bboxes[i].y + bboxes[i].height > maxy) {maxy = bboxes[i].y + bboxes[i].height;}
  6654. break;
  6655. }
  6656. } // loop for each element to find the bbox and adjust min/max
  6657. if (relative_to == 'page') {
  6658. minx = 0;
  6659. miny = 0;
  6660. maxx = canvas.contentW;
  6661. maxy = canvas.contentH;
  6662. }
  6663. var dx = new Array(len);
  6664. var dy = new Array(len);
  6665. for (i = 0; i < len; ++i) {
  6666. if (selectedElements[i] == null) {break;}
  6667. elem = selectedElements[i];
  6668. var bbox = bboxes[i];
  6669. dx[i] = 0;
  6670. dy[i] = 0;
  6671. switch (type) {
  6672. case 'l': // left (horizontal)
  6673. dx[i] = minx - bbox.x;
  6674. break;
  6675. case 'c': // center (horizontal)
  6676. dx[i] = (minx+maxx)/2 - (bbox.x + bbox.width/2);
  6677. break;
  6678. case 'r': // right (horizontal)
  6679. dx[i] = maxx - (bbox.x + bbox.width);
  6680. break;
  6681. case 't': // top (vertical)
  6682. dy[i] = miny - bbox.y;
  6683. break;
  6684. case 'm': // middle (vertical)
  6685. dy[i] = (miny+maxy)/2 - (bbox.y + bbox.height/2);
  6686. break;
  6687. case 'b': // bottom (vertical)
  6688. dy[i] = maxy - (bbox.y + bbox.height);
  6689. break;
  6690. }
  6691. }
  6692. this.moveSelectedElements(dx, dy);
  6693. };
  6694. // Group: Additional editor tools
  6695. this.contentW = getResolution().w;
  6696. this.contentH = getResolution().h;
  6697. // Function: updateCanvas
  6698. // Updates the editor canvas width/height/position after a zoom has occurred
  6699. //
  6700. // Parameters:
  6701. // w - Float with the new width
  6702. // h - Float with the new height
  6703. //
  6704. // Returns:
  6705. // Object with the following values:
  6706. // * x - The canvas' new x coordinate
  6707. // * y - The canvas' new y coordinate
  6708. // * old_x - The canvas' old x coordinate
  6709. // * old_y - The canvas' old y coordinate
  6710. // * d_x - The x position difference
  6711. // * d_y - The y position difference
  6712. this.updateCanvas = function(w, h) {
  6713. svgroot.setAttribute('width', w);
  6714. svgroot.setAttribute('height', h);
  6715. var bg = $('#canvasBackground')[0];
  6716. var old_x = svgcontent.getAttribute('x');
  6717. var old_y = svgcontent.getAttribute('y');
  6718. var x = (w/2 - this.contentW*current_zoom/2);
  6719. var y = (h/2 - this.contentH*current_zoom/2);
  6720. svgedit.utilities.assignAttributes(svgcontent, {
  6721. width: this.contentW*current_zoom,
  6722. height: this.contentH*current_zoom,
  6723. 'x': x,
  6724. 'y': y,
  6725. 'viewBox' : '0 0 ' + this.contentW + ' ' + this.contentH
  6726. });
  6727. svgedit.utilities.assignAttributes(bg, {
  6728. width: svgcontent.getAttribute('width'),
  6729. height: svgcontent.getAttribute('height'),
  6730. x: x,
  6731. y: y
  6732. });
  6733. var bg_img = svgedit.utilities.getElem('background_image');
  6734. if (bg_img) {
  6735. svgedit.utilities.assignAttributes(bg_img, {
  6736. 'width': '100%',
  6737. 'height': '100%'
  6738. });
  6739. }
  6740. selectorManager.selectorParentGroup.setAttribute('transform', 'translate(' + x + ',' + y + ')');
  6741. runExtensions('canvasUpdated', {new_x:x, new_y:y, old_x:old_x, old_y:old_y, d_x:x - old_x, d_y:y - old_y});
  6742. return {x:x, y:y, old_x:old_x, old_y:old_y, d_x:x - old_x, d_y:y - old_y};
  6743. };
  6744. // Function: setBackground
  6745. // Set the background of the editor (NOT the actual document)
  6746. //
  6747. // Parameters:
  6748. // color - String with fill color to apply
  6749. // url - URL or path to image to use
  6750. this.setBackground = function(color, url) {
  6751. var bg = svgedit.utilities.getElem('canvasBackground');
  6752. var border = $(bg).find('rect')[0];
  6753. var bg_img = svgedit.utilities.getElem('background_image');
  6754. border.setAttribute('fill', color);
  6755. if (url) {
  6756. if (!bg_img) {
  6757. bg_img = svgdoc.createElementNS(NS.SVG, 'image');
  6758. svgedit.utilities.assignAttributes(bg_img, {
  6759. 'id': 'background_image',
  6760. 'width': '100%',
  6761. 'height': '100%',
  6762. 'preserveAspectRatio': 'xMinYMin',
  6763. 'style':'pointer-events:none'
  6764. });
  6765. }
  6766. setHref(bg_img, url);
  6767. bg.appendChild(bg_img);
  6768. } else if (bg_img) {
  6769. bg_img.parentNode.removeChild(bg_img);
  6770. }
  6771. };
  6772. // Function: cycleElement
  6773. // Select the next/previous element within the current layer
  6774. //
  6775. // Parameters:
  6776. // next - Boolean where true = next and false = previous element
  6777. this.cycleElement = function(next) {
  6778. var num;
  6779. var cur_elem = selectedElements[0];
  6780. var elem = false;
  6781. var all_elems = getVisibleElements(current_group || getCurrentDrawing().getCurrentLayer());
  6782. if (!all_elems.length) {return;}
  6783. if (cur_elem == null) {
  6784. num = next?all_elems.length-1:0;
  6785. elem = all_elems[num];
  6786. } else {
  6787. var i = all_elems.length;
  6788. while (i--) {
  6789. if (all_elems[i] == cur_elem) {
  6790. num = next ? i - 1 : i + 1;
  6791. if (num >= all_elems.length) {
  6792. num = 0;
  6793. } else if (num < 0) {
  6794. num = all_elems.length-1;
  6795. }
  6796. elem = all_elems[num];
  6797. break;
  6798. }
  6799. }
  6800. }
  6801. selectOnly([elem], true);
  6802. call('selected', selectedElements);
  6803. };
  6804. this.clear();
  6805. // DEPRECATED: getPrivateMethods
  6806. // Since all methods are/should be public somehow, this function should be removed
  6807. // Being able to access private methods publicly seems wrong somehow,
  6808. // but currently appears to be the best way to allow testing and provide
  6809. // access to them to plugins.
  6810. this.getPrivateMethods = function() {
  6811. var obj = {
  6812. addCommandToHistory: addCommandToHistory,
  6813. setGradient: setGradient,
  6814. addSvgElementFromJson: addSvgElementFromJson,
  6815. assignAttributes: assignAttributes,
  6816. BatchCommand: BatchCommand,
  6817. call: call,
  6818. ChangeElementCommand: ChangeElementCommand,
  6819. copyElem: copyElem,
  6820. ffClone: ffClone,
  6821. findDefs: findDefs,
  6822. findDuplicateGradient: findDuplicateGradient,
  6823. getElem: getElem,
  6824. getId: getId,
  6825. getIntersectionList: getIntersectionList,
  6826. getMouseTarget: getMouseTarget,
  6827. getNextId: getNextId,
  6828. getPathBBox: getPathBBox,
  6829. getUrlFromAttr: getUrlFromAttr,
  6830. hasMatrixTransform: hasMatrixTransform,
  6831. identifyLayers: identifyLayers,
  6832. InsertElementCommand: InsertElementCommand,
  6833. isIdentity: svgedit.math.isIdentity,
  6834. logMatrix: logMatrix,
  6835. matrixMultiply: matrixMultiply,
  6836. MoveElementCommand: MoveElementCommand,
  6837. preventClickDefault: preventClickDefault,
  6838. recalculateAllSelectedDimensions: recalculateAllSelectedDimensions,
  6839. recalculateDimensions: recalculateDimensions,
  6840. remapElement: remapElement,
  6841. RemoveElementCommand: RemoveElementCommand,
  6842. removeUnusedDefElems: removeUnusedDefElems,
  6843. round: round,
  6844. runExtensions: runExtensions,
  6845. sanitizeSvg: sanitizeSvg,
  6846. SVGEditTransformList: svgedit.transformlist.SVGTransformList,
  6847. toString: toString,
  6848. transformBox: svgedit.math.transformBox,
  6849. transformListToTransform: transformListToTransform,
  6850. transformPoint: transformPoint,
  6851. walkTree: svgedit.utilities.walkTree
  6852. };
  6853. return obj;
  6854. };
  6855. };