svgcanvas.js 224 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799
  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. };