svgcanvas.js 223 KB

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