svg-editor.js 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872
  1. /*
  2. * svg-editor.js
  3. *
  4. * Licensed under the Apache License, Version 2
  5. *
  6. * Copyright(c) 2010 Alexis Deveria
  7. * Copyright(c) 2010 Pavol Rusnak
  8. * Copyright(c) 2010 Jeff Schiller
  9. * Copyright(c) 2010 Narendra Sisodiya
  10. *
  11. * Integrate with Chamilo
  12. * Author Juan Carlos Raña Trabado
  13. * Since 25/september/2010
  14. *
  15. */
  16. // Dependencies:
  17. // 1) units.js
  18. // 2) browser.js
  19. // 3) svgcanvas.js
  20. (function() {
  21. if(!window.svgEditor) window.svgEditor = function($) {
  22. var svgCanvas;
  23. var Editor = {};
  24. var is_ready = false;
  25. var defaultPrefs = {
  26. lang:'en',
  27. iconsize:'m',
  28. bkgd_color:'#FFF',
  29. bkgd_url:'',
  30. img_save:'embed'
  31. },
  32. curPrefs = {},
  33. // Note: Difference between Prefs and Config is that Prefs can be
  34. // changed in the UI and are stored in the browser, config can not
  35. // Chamilo added 'ext-server_opensave.js','ext-arrows.js','ext-foreignobject.js'(MathML) extensions
  36. curConfig = {
  37. canvas_expansion: 3,
  38. dimensions: [640,480],
  39. initFill: {
  40. color: 'FF0000', // solid red
  41. opacity: 1
  42. },
  43. initStroke: {
  44. width: 5,
  45. color: '000000', // solid black
  46. opacity: 1
  47. },
  48. initOpacity: 1,
  49. imgPath: 'images/',
  50. langPath: 'locale/',
  51. extPath: 'extensions/',
  52. jGraduatePath: 'jgraduate/images/',
  53. extensions: ['ext-markers.js','ext-connector.js', 'ext-eyedropper.js', 'ext-shapes.js', 'ext-imagelib.js','ext-grid.js','ext-server_opensave.js','ext-arrows.js','ext-foreignobject.js'],
  54. initTool: 'select',
  55. wireframe: false,
  56. colorPickerCSS: null,
  57. gridSnapping: false,
  58. gridColor: "#000",
  59. baseUnit: 'px',
  60. snappingStep: 10,
  61. showRulers: true
  62. },
  63. uiStrings = Editor.uiStrings = {
  64. common: {
  65. "ok":"OK",
  66. "cancel":"Cancel",
  67. "key_up":"Up",
  68. "key_down":"Down",
  69. "key_backspace":"Backspace",
  70. "key_del":"Del"
  71. },
  72. // This is needed if the locale is English, since the locale strings are not read in that instance.
  73. layers: {
  74. "layer":"Layer"
  75. },
  76. notification: {
  77. "invalidAttrValGiven":"Invalid value given",
  78. "noContentToFitTo":"No content to fit to",
  79. "dupeLayerName":"There is already a layer named that!",
  80. "enterUniqueLayerName":"Please enter a unique layer name",
  81. "enterNewLayerName":"Please enter the new layer name",
  82. "layerHasThatName":"Layer already has that name",
  83. "QmoveElemsToLayer":"Move selected elements to layer \"%s\"?",
  84. "QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!",
  85. "QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!",
  86. "QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?",
  87. "QignoreSourceChanges":"Ignore changes made to SVG source?",
  88. "featNotSupported":"Feature not supported",
  89. "enterNewImgURL":"Enter the new image URL",
  90. "defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
  91. "loadingImage":"Loading image, please wait...",
  92. "saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.",
  93. "noteTheseIssues": "Also note the following issues: ",
  94. "unsavedChanges": "There are unsaved changes.",
  95. "enterNewLinkURL": "Enter the new hyperlink URL",
  96. "errorLoadingSVG": "Error: Unable to load SVG data",
  97. "URLloadFail": "Unable to load from URL",
  98. "retrieving": 'Retrieving "%s" ...'
  99. }
  100. };
  101. var curPrefs = {}; //$.extend({}, defaultPrefs);
  102. var customHandlers = {};
  103. Editor.curConfig = curConfig;
  104. Editor.tool_scale = 1;
  105. // Store and retrieve preferences
  106. $.pref = function(key, val) {
  107. if(val) curPrefs[key] = val;
  108. key = 'svg-edit-'+key;
  109. var host = location.hostname,
  110. onweb = host && host.indexOf('.') >= 0,
  111. store = (val != undefined),
  112. storage = false;
  113. // Some FF versions throw security errors here
  114. try {
  115. if(window.localStorage) { // && onweb removed so Webkit works locally
  116. storage = localStorage;
  117. }
  118. } catch(e) {}
  119. try {
  120. if(window.globalStorage && onweb) {
  121. storage = globalStorage[host];
  122. }
  123. } catch(e) {}
  124. if(storage) {
  125. if(store) storage.setItem(key, val);
  126. else if (storage.getItem(key)) return storage.getItem(key) + ''; // Convert to string for FF (.value fails in Webkit)
  127. } else if(window.widget) {
  128. if(store) widget.setPreferenceForKey(val, key);
  129. else return widget.preferenceForKey(key);
  130. } else {
  131. if(store) {
  132. var d = new Date();
  133. d.setTime(d.getTime() + 31536000000);
  134. val = encodeURIComponent(val);
  135. document.cookie = key+'='+val+'; expires='+d.toUTCString();
  136. } else {
  137. var result = document.cookie.match(new RegExp(key + "=([^;]+)"));
  138. return result?decodeURIComponent(result[1]):'';
  139. }
  140. }
  141. }
  142. Editor.setConfig = function(opts) {
  143. $.each(opts, function(key, val) {
  144. // Only allow prefs defined in defaultPrefs
  145. if(key in defaultPrefs) {
  146. $.pref(key, val);
  147. }
  148. });
  149. $.extend(true, curConfig, opts);
  150. if(opts.extensions) {
  151. curConfig.extensions = opts.extensions;
  152. }
  153. }
  154. // Extension mechanisms must call setCustomHandlers with two functions: opts.open and opts.save
  155. // opts.open's responsibilities are:
  156. // - invoke a file chooser dialog in 'open' mode
  157. // - let user pick a SVG file
  158. // - calls setCanvas.setSvgString() with the string contents of that file
  159. // opts.save's responsibilities are:
  160. // - accept the string contents of the current document
  161. // - invoke a file chooser dialog in 'save' mode
  162. // - save the file to location chosen by the user
  163. Editor.setCustomHandlers = function(opts) {
  164. Editor.ready(function() {
  165. if(opts.open) {
  166. $('#tool_open > input[type="file"]').remove();
  167. $('#tool_open').show();
  168. svgCanvas.open = opts.open;
  169. }
  170. if(opts.save) {
  171. Editor.show_save_warning = false;
  172. svgCanvas.bind("saved", opts.save);
  173. }
  174. if(opts.pngsave) {
  175. svgCanvas.bind("exported", opts.pngsave);
  176. }
  177. customHandlers = opts;
  178. });
  179. }
  180. Editor.randomizeIds = function() {
  181. svgCanvas.randomizeIds(arguments)
  182. }
  183. Editor.init = function() {
  184. // For external openers
  185. (function() {
  186. // let the opener know SVG Edit is ready
  187. var w = window.opener;
  188. if (w) {
  189. try {
  190. var svgEditorReadyEvent = w.document.createEvent("Event");
  191. svgEditorReadyEvent.initEvent("svgEditorReady", true, true);
  192. w.document.documentElement.dispatchEvent(svgEditorReadyEvent);
  193. }
  194. catch(e) {}
  195. }
  196. })();
  197. (function() {
  198. // Load config/data from URL if given
  199. var urldata = $.deparam.querystring(true);
  200. if(!$.isEmptyObject(urldata)) {
  201. if(urldata.dimensions) {
  202. urldata.dimensions = urldata.dimensions.split(',');
  203. }
  204. if(urldata.extensions) {
  205. urldata.extensions = urldata.extensions.split(',');
  206. }
  207. if(urldata.bkgd_color) {
  208. urldata.bkgd_color = '#' + urldata.bkgd_color;
  209. }
  210. svgEditor.setConfig(urldata);
  211. var src = urldata.source;
  212. var qstr = $.param.querystring();
  213. if(!src) { // urldata.source may have been null if it ended with '='
  214. if(qstr.indexOf('source=data:') >= 0) {
  215. src = qstr.match(/source=(data:[^&]*)/)[1];
  216. }
  217. }
  218. if(src) {
  219. if(src.indexOf("data:") === 0) {
  220. // plusses get replaced by spaces, so re-insert
  221. src = src.replace(/ /g, "+");
  222. Editor.loadFromDataURI(src);
  223. } else {
  224. Editor.loadFromString(src);
  225. }
  226. } else if(qstr.indexOf('paramurl=') !== -1) {
  227. // Get paramater URL (use full length of remaining location.href)
  228. svgEditor.loadFromURL(qstr.substr(9));
  229. } else if(urldata.url) {
  230. svgEditor.loadFromURL(urldata.url);
  231. }
  232. }
  233. })();
  234. var extFunc = function() {
  235. $.each(curConfig.extensions, function() {
  236. var extname = this;
  237. $.getScript(curConfig.extPath + extname, function(d) {
  238. // Fails locally in Chrome 5
  239. if(!d) {
  240. var s = document.createElement('script');
  241. s.src = curConfig.extPath + extname;
  242. document.querySelector('head').appendChild(s);
  243. }
  244. });
  245. });
  246. var good_langs = [];
  247. $('#lang_select option').each(function() {
  248. good_langs.push(this.value);
  249. });
  250. // var lang = ('lang' in curPrefs) ? curPrefs.lang : null;
  251. Editor.putLocale(null, good_langs);
  252. }
  253. // Load extensions
  254. // Bit of a hack to run extensions in local Opera/IE9
  255. if(document.location.protocol === 'file:') {
  256. setTimeout(extFunc, 100);
  257. } else {
  258. extFunc();
  259. }
  260. $.svgIcons(curConfig.imgPath + 'svg_edit_icons.svg', {
  261. w:24, h:24,
  262. id_match: false,
  263. no_img: !svgedit.browser.isWebkit(), // Opera & Firefox 4 gives odd behavior w/images
  264. fallback_path: curConfig.imgPath,
  265. fallback:{
  266. 'new_image':'clear.png',
  267. 'save':'save.png',
  268. 'open':'open.png',
  269. 'source':'source.png',
  270. 'docprops':'document-properties.png',
  271. 'wireframe':'wireframe.png',
  272. 'undo':'undo.png',
  273. 'redo':'redo.png',
  274. 'select':'select.png',
  275. 'select_node':'select_node.png',
  276. 'pencil':'fhpath.png',
  277. 'pen':'line.png',
  278. 'square':'square.png',
  279. 'rect':'rect.png',
  280. 'fh_rect':'freehand-square.png',
  281. 'circle':'circle.png',
  282. 'ellipse':'ellipse.png',
  283. 'fh_ellipse':'freehand-circle.png',
  284. 'path':'path.png',
  285. 'text':'text.png',
  286. 'image':'image.png',
  287. 'zoom':'zoom.png',
  288. 'clone':'clone.png',
  289. 'node_clone':'node_clone.png',
  290. 'delete':'delete.png',
  291. 'node_delete':'node_delete.png',
  292. 'group':'shape_group.png',
  293. 'ungroup':'shape_ungroup.png',
  294. 'move_top':'move_top.png',
  295. 'move_bottom':'move_bottom.png',
  296. 'to_path':'to_path.png',
  297. 'link_controls':'link_controls.png',
  298. 'reorient':'reorient.png',
  299. 'align_left':'align-left.png',
  300. 'align_center':'align-center',
  301. 'align_right':'align-right',
  302. 'align_top':'align-top',
  303. 'align_middle':'align-middle',
  304. 'align_bottom':'align-bottom',
  305. 'go_up':'go-up.png',
  306. 'go_down':'go-down.png',
  307. 'ok':'save.png',
  308. 'cancel':'cancel.png',
  309. 'arrow_right':'flyouth.png',
  310. 'arrow_down':'dropdown.gif'
  311. },
  312. placement: {
  313. '#logo':'logo',
  314. '#tool_clear div,#layer_new':'new_image',
  315. '#tool_save div':'save',
  316. '#tool_export div':'export',
  317. '#tool_open div div':'open',
  318. '#tool_import div div':'import',
  319. '#tool_source':'source',
  320. '#tool_docprops > div':'docprops',
  321. '#tool_wireframe':'wireframe',
  322. '#tool_undo':'undo',
  323. '#tool_redo':'redo',
  324. '#tool_select':'select',
  325. '#tool_fhpath':'pencil',
  326. '#tool_line':'pen',
  327. '#tool_rect,#tools_rect_show':'rect',
  328. '#tool_square':'square',
  329. '#tool_fhrect':'fh_rect',
  330. '#tool_ellipse,#tools_ellipse_show':'ellipse',
  331. '#tool_circle':'circle',
  332. '#tool_fhellipse':'fh_ellipse',
  333. '#tool_path':'path',
  334. '#tool_text,#layer_rename':'text',
  335. '#tool_image':'image',
  336. '#tool_zoom':'zoom',
  337. '#tool_clone,#tool_clone_multi':'clone',
  338. '#tool_node_clone':'node_clone',
  339. '#layer_delete,#tool_delete,#tool_delete_multi':'delete',
  340. '#tool_node_delete':'node_delete',
  341. '#tool_add_subpath':'add_subpath',
  342. '#tool_openclose_path':'open_path',
  343. '#tool_move_top':'move_top',
  344. '#tool_move_bottom':'move_bottom',
  345. '#tool_topath':'to_path',
  346. '#tool_node_link':'link_controls',
  347. '#tool_reorient':'reorient',
  348. '#tool_group':'group',
  349. '#tool_ungroup':'ungroup',
  350. '#tool_unlink_use':'unlink_use',
  351. '#tool_alignleft, #tool_posleft':'align_left',
  352. '#tool_aligncenter, #tool_poscenter':'align_center',
  353. '#tool_alignright, #tool_posright':'align_right',
  354. '#tool_aligntop, #tool_postop':'align_top',
  355. '#tool_alignmiddle, #tool_posmiddle':'align_middle',
  356. '#tool_alignbottom, #tool_posbottom':'align_bottom',
  357. '#cur_position':'align',
  358. '#linecap_butt,#cur_linecap':'linecap_butt',
  359. '#linecap_round':'linecap_round',
  360. '#linecap_square':'linecap_square',
  361. '#linejoin_miter,#cur_linejoin':'linejoin_miter',
  362. '#linejoin_round':'linejoin_round',
  363. '#linejoin_bevel':'linejoin_bevel',
  364. '#url_notice':'warning',
  365. '#layer_up':'go_up',
  366. '#layer_down':'go_down',
  367. '#layer_moreopts':'context_menu',
  368. '#layerlist td.layervis':'eye',
  369. '#tool_source_save,#tool_docprops_save,#tool_prefs_save':'ok',
  370. '#tool_source_cancel,#tool_docprops_cancel,#tool_prefs_cancel':'cancel',
  371. '#rwidthLabel, #iwidthLabel':'width',
  372. '#rheightLabel, #iheightLabel':'height',
  373. '#cornerRadiusLabel span':'c_radius',
  374. '#angleLabel':'angle',
  375. '#linkLabel,#tool_make_link,#tool_make_link_multi':'globe_link',
  376. '#zoomLabel':'zoom',
  377. '#tool_fill label': 'fill',
  378. '#tool_stroke .icon_label': 'stroke',
  379. '#group_opacityLabel': 'opacity',
  380. '#blurLabel': 'blur',
  381. '#font_sizeLabel': 'fontsize',
  382. '.flyout_arrow_horiz':'arrow_right',
  383. '.dropdown button, #main_button .dropdown':'arrow_down',
  384. '#palette .palette_item:first, #fill_bg, #stroke_bg':'no_color'
  385. },
  386. resize: {
  387. '#logo .svg_icon': 32,
  388. '.flyout_arrow_horiz .svg_icon': 5,
  389. '.layer_button .svg_icon, #layerlist td.layervis .svg_icon': 14,
  390. '.dropdown button .svg_icon': 7,
  391. '#main_button .dropdown .svg_icon': 9,
  392. '.palette_item:first .svg_icon, #fill_bg .svg_icon, #stroke_bg .svg_icon': 16,
  393. '.toolbar_button button .svg_icon':16,
  394. '.stroke_tool div div .svg_icon': 20,
  395. '#tools_bottom label .svg_icon': 18
  396. },
  397. callback: function(icons) {
  398. $('.toolbar_button button > svg, .toolbar_button button > img').each(function() {
  399. $(this).parent().prepend(this);
  400. });
  401. var tleft = $('#tools_left');
  402. if (tleft.length != 0) {
  403. var min_height = tleft.offset().top + tleft.outerHeight();
  404. }
  405. // var size = $.pref('iconsize');
  406. // if(size && size != 'm') {
  407. // svgEditor.setIconSize(size);
  408. // } else if($(window).height() < min_height) {
  409. // // Make smaller
  410. // svgEditor.setIconSize('s');
  411. // }
  412. // Look for any missing flyout icons from plugins
  413. $('.tools_flyout').each(function() {
  414. var shower = $('#' + this.id + '_show');
  415. var sel = shower.attr('data-curopt');
  416. // Check if there's an icon here
  417. if(!shower.children('svg, img').length) {
  418. var clone = $(sel).children().clone();
  419. if(clone.length) {
  420. clone[0].removeAttribute('style'); //Needed for Opera
  421. shower.append(clone);
  422. }
  423. }
  424. });
  425. svgEditor.runCallbacks();
  426. setTimeout(function() {
  427. $('.flyout_arrow_horiz:empty').each(function() {
  428. $(this).append($.getSvgIcon('arrow_right').width(5).height(5));
  429. });
  430. }, 1);
  431. }
  432. });
  433. Editor.canvas = svgCanvas = new $.SvgCanvas(document.getElementById("svgcanvas"), curConfig);
  434. Editor.show_save_warning = false;
  435. var palette = ["#000000", "#3f3f3f", "#7f7f7f", "#bfbfbf", "#ffffff",
  436. "#ff0000", "#ff7f00", "#ffff00", "#7fff00",
  437. "#00ff00", "#00ff7f", "#00ffff", "#007fff",
  438. "#0000ff", "#7f00ff", "#ff00ff", "#ff007f",
  439. "#7f0000", "#7f3f00", "#7f7f00", "#3f7f00",
  440. "#007f00", "#007f3f", "#007f7f", "#003f7f",
  441. "#00007f", "#3f007f", "#7f007f", "#7f003f",
  442. "#ffaaaa", "#ffd4aa", "#ffffaa", "#d4ffaa",
  443. "#aaffaa", "#aaffd4", "#aaffff", "#aad4ff",
  444. "#aaaaff", "#d4aaff", "#ffaaff", "#ffaad4"
  445. ],
  446. isMac = (navigator.platform.indexOf("Mac") >= 0),
  447. isWebkit = (navigator.userAgent.indexOf("AppleWebKit") >= 0),
  448. modKey = (isMac ? "meta+" : "ctrl+"), // ⌘
  449. path = svgCanvas.pathActions,
  450. undoMgr = svgCanvas.undoMgr,
  451. Utils = svgedit.utilities,
  452. default_img_url = curConfig.imgPath + "logo.png",
  453. workarea = $("#workarea"),
  454. canv_menu = $("#cmenu_canvas"),
  455. layer_menu = $("#cmenu_layers"),
  456. exportWindow = null,
  457. tool_scale = 1,
  458. zoomInIcon = 'crosshair',
  459. zoomOutIcon = 'crosshair',
  460. ui_context = 'toolbars',
  461. orig_source = '',
  462. paintBox = {fill: null, stroke:null};
  463. // This sets up alternative dialog boxes. They mostly work the same way as
  464. // their UI counterparts, expect instead of returning the result, a callback
  465. // needs to be included that returns the result as its first parameter.
  466. // In the future we may want to add additional types of dialog boxes, since
  467. // they should be easy to handle this way.
  468. (function() {
  469. $('#dialog_container').draggable({cancel:'#dialog_content, #dialog_buttons *', containment: 'window'});
  470. var box = $('#dialog_box'), btn_holder = $('#dialog_buttons');
  471. var dbox = function(type, msg, callback, defText) {
  472. $('#dialog_content').html('<p>'+msg.replace(/\n/g,'</p><p>')+'</p>')
  473. .toggleClass('prompt',(type=='prompt'));
  474. btn_holder.empty();
  475. var ok = $('<input type="button" value="' + uiStrings.common.ok + '">').appendTo(btn_holder);
  476. if(type != 'alert') {
  477. $('<input type="button" value="' + uiStrings.common.cancel + '">')
  478. .appendTo(btn_holder)
  479. .click(function() { box.hide();callback(false)});
  480. }
  481. if(type == 'prompt') {
  482. var input = $('<input type="text">').prependTo(btn_holder);
  483. input.val(defText || '');
  484. input.bind('keydown', 'return', function() {ok.click();});
  485. }
  486. if(type == 'process') {
  487. ok.hide();
  488. }
  489. box.show();
  490. ok.click(function() {
  491. box.hide();
  492. var resp = (type == 'prompt')?input.val():true;
  493. if(callback) callback(resp);
  494. }).focus();
  495. if(type == 'prompt') input.focus();
  496. }
  497. $.alert = function(msg, cb) { dbox('alert', msg, cb);};
  498. $.confirm = function(msg, cb) { dbox('confirm', msg, cb);};
  499. $.process_cancel = function(msg, cb) { dbox('process', msg, cb);};
  500. $.prompt = function(msg, txt, cb) { dbox('prompt', msg, cb, txt);};
  501. }());
  502. var setSelectMode = function() {
  503. var curr = $('.tool_button_current');
  504. if(curr.length && curr[0].id !== 'tool_select') {
  505. curr.removeClass('tool_button_current').addClass('tool_button');
  506. $('#tool_select').addClass('tool_button_current').removeClass('tool_button');
  507. $('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all} #svgcanvas svg{cursor:default}');
  508. }
  509. svgCanvas.setMode('select');
  510. workarea.css('cursor','auto');
  511. };
  512. var togglePathEditMode = function(editmode, elems) {
  513. $('#path_node_panel').toggle(editmode);
  514. $('#tools_bottom_2,#tools_bottom_3').toggle(!editmode);
  515. if(editmode) {
  516. // Change select icon
  517. $('.tool_button_current').removeClass('tool_button_current').addClass('tool_button');
  518. $('#tool_select').addClass('tool_button_current').removeClass('tool_button');
  519. setIcon('#tool_select', 'select_node');
  520. multiselected = false;
  521. if(elems.length) {
  522. selectedElement = elems[0];
  523. }
  524. } else {
  525. setIcon('#tool_select', 'select');
  526. }
  527. }
  528. // used to make the flyouts stay on the screen longer the very first time
  529. var flyoutspeed = 1250;
  530. var textBeingEntered = false;
  531. var selectedElement = null;
  532. var multiselected = false;
  533. var editingsource = false;
  534. var docprops = false;
  535. var preferences = false;
  536. var cur_context = '';
  537. var orig_title = $('title:first').text();
  538. var saveHandler = function(window,svg) {
  539. Editor.show_save_warning = false;
  540. // by default, we add the XML prolog back, systems integrating SVG-edit (wikis, CMSs)
  541. // can just provide their own custom save handler and might not want the XML prolog
  542. svg = '<?xml version="1.0"?>\n' + svg;
  543. // Opens the SVG in new window, with warning about Mozilla bug #308590 when applicable
  544. var ua = navigator.userAgent;
  545. // Chrome 5 (and 6?) don't allow saving, show source instead ( http://code.google.com/p/chromium/issues/detail?id=46735 )
  546. // IE9 doesn't allow standalone Data URLs ( https://connect.microsoft.com/IE/feedback/details/542600/data-uri-images-fail-when-loaded-by-themselves )
  547. if((~ua.indexOf('Chrome') && $.browser.version >= 533) || ~ua.indexOf('MSIE')) {
  548. showSourceEditor(0,true);
  549. return;
  550. }
  551. var win = window.open("data:image/svg+xml;base64," + Utils.encode64(svg));
  552. // Alert will only appear the first time saved OR the first time the bug is encountered
  553. var done = $.pref('save_notice_done');
  554. if(done !== "all") {
  555. var note = uiStrings.notification.saveFromBrowser.replace('%s', 'SVG');
  556. // Check if FF and has <defs/>
  557. if(ua.indexOf('Gecko/') !== -1) {
  558. if(svg.indexOf('<defs') !== -1) {
  559. note += "\n\n" + uiStrings.notification.defsFailOnSave;
  560. $.pref('save_notice_done', 'all');
  561. done = "all";
  562. } else {
  563. $.pref('save_notice_done', 'part');
  564. }
  565. } else {
  566. $.pref('save_notice_done', 'all');
  567. }
  568. if(done !== 'part') {
  569. win.alert(note);
  570. }
  571. }
  572. };
  573. var exportHandler = function(window, data) {
  574. var issues = data.issues;
  575. if(!$('#export_canvas').length) {
  576. $('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
  577. }
  578. var c = $('#export_canvas')[0];
  579. c.width = svgCanvas.contentW;
  580. c.height = svgCanvas.contentH;
  581. canvg(c, data.svg, {renderCallback: function() {
  582. var datauri = c.toDataURL('image/png');
  583. exportWindow.location.href = datauri;
  584. var done = $.pref('export_notice_done');
  585. if(done !== "all") {
  586. var note = uiStrings.notification.saveFromBrowser.replace('%s', 'PNG');
  587. // Check if there's issues
  588. if(issues.length) {
  589. var pre = "\n \u2022 ";
  590. note += ("\n\n" + uiStrings.notification.noteTheseIssues + pre + issues.join(pre));
  591. }
  592. // Note that this will also prevent the notice even though new issues may appear later.
  593. // May want to find a way to deal with that without annoying the user
  594. $.pref('export_notice_done', 'all');
  595. exportWindow.alert(note);
  596. }
  597. }});
  598. };
  599. // called when we've selected a different element
  600. var selectedChanged = function(window,elems) {
  601. var mode = svgCanvas.getMode();
  602. if(mode === "select") setSelectMode();
  603. var is_node = (mode == "pathedit");
  604. // if elems[1] is present, then we have more than one element
  605. selectedElement = (elems.length == 1 || elems[1] == null ? elems[0] : null);
  606. multiselected = (elems.length >= 2 && elems[1] != null);
  607. if (selectedElement != null) {
  608. // unless we're already in always set the mode of the editor to select because
  609. // upon creation of a text element the editor is switched into
  610. // select mode and this event fires - we need our UI to be in sync
  611. if (!is_node) {
  612. updateToolbar();
  613. }
  614. } // if (elem != null)
  615. // Deal with pathedit mode
  616. togglePathEditMode(is_node, elems);
  617. updateContextPanel();
  618. svgCanvas.runExtensions("selectedChanged", {
  619. elems: elems,
  620. selectedElement: selectedElement,
  621. multiselected: multiselected
  622. });
  623. };
  624. // Call when part of element is in process of changing, generally
  625. // on mousemove actions like rotate, move, etc.
  626. var elementTransition = function(window,elems) {
  627. var mode = svgCanvas.getMode();
  628. var elem = elems[0];
  629. if(!elem) return;
  630. multiselected = (elems.length >= 2 && elems[1] != null);
  631. // Only updating fields for single elements for now
  632. if(!multiselected) {
  633. switch ( mode ) {
  634. case "rotate":
  635. var ang = svgCanvas.getRotationAngle(elem);
  636. $('#angle').val(ang);
  637. $('#tool_reorient').toggleClass('disabled', ang == 0);
  638. break;
  639. // TODO: Update values that change on move/resize, etc
  640. // case "select":
  641. // case "resize":
  642. // break;
  643. }
  644. }
  645. svgCanvas.runExtensions("elementTransition", {
  646. elems: elems
  647. });
  648. };
  649. // called when any element has changed
  650. var elementChanged = function(window,elems) {
  651. var mode = svgCanvas.getMode();
  652. if(mode === "select") {
  653. setSelectMode();
  654. }
  655. for (var i = 0; i < elems.length; ++i) {
  656. var elem = elems[i];
  657. // if the element changed was the svg, then it could be a resolution change
  658. if (elem && elem.tagName === "svg") {
  659. populateLayers();
  660. updateCanvas();
  661. }
  662. // Update selectedElement if element is no longer part of the image.
  663. // This occurs for the text elements in Firefox
  664. else if(elem && selectedElement && selectedElement.parentNode == null) {
  665. // || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why
  666. selectedElement = elem;
  667. }
  668. }
  669. Editor.show_save_warning = false; //Hack for Chamilo, change true by false
  670. // we update the contextual panel with potentially new
  671. // positional/sizing information (we DON'T want to update the
  672. // toolbar here as that creates an infinite loop)
  673. // also this updates the history buttons
  674. // we tell it to skip focusing the text control if the
  675. // text element was previously in focus
  676. updateContextPanel();
  677. // In the event a gradient was flipped:
  678. if(selectedElement && mode === "select") {
  679. paintBox.fill.update();
  680. paintBox.stroke.update();
  681. }
  682. svgCanvas.runExtensions("elementChanged", {
  683. elems: elems
  684. });
  685. };
  686. var zoomChanged = function(window, bbox, autoCenter) {
  687. var scrbar = 15,
  688. res = svgCanvas.getResolution(),
  689. w_area = workarea,
  690. canvas_pos = $('#svgcanvas').position();
  691. var z_info = svgCanvas.setBBoxZoom(bbox, w_area.width()-scrbar, w_area.height()-scrbar);
  692. if(!z_info) return;
  693. var zoomlevel = z_info.zoom,
  694. bb = z_info.bbox;
  695. if(zoomlevel < .001) {
  696. changeZoom({value: .1});
  697. return;
  698. }
  699. // $('#zoom').val(Math.round(zoomlevel*100));
  700. $('#zoom').val(zoomlevel*100);
  701. if(autoCenter) {
  702. updateCanvas();
  703. } else {
  704. updateCanvas(false, {x: bb.x * zoomlevel + (bb.width * zoomlevel)/2, y: bb.y * zoomlevel + (bb.height * zoomlevel)/2});
  705. }
  706. if(svgCanvas.getMode() == 'zoom' && bb.width) {
  707. // Go to select if a zoom box was drawn
  708. setSelectMode();
  709. }
  710. zoomDone();
  711. }
  712. $('#cur_context_panel').delegate('a', 'click', function() {
  713. var link = $(this);
  714. if(link.attr('data-root')) {
  715. svgCanvas.leaveContext();
  716. } else {
  717. svgCanvas.setContext(link.text());
  718. }
  719. return false;
  720. });
  721. var contextChanged = function(win, context) {
  722. $('#workarea,#sidepanels').css('top', context?100:75);
  723. $('#rulers').toggleClass('moved', context);
  724. if(cur_context && !context) {
  725. // Back to normal
  726. workarea[0].scrollTop -= 25;
  727. } else if(!cur_context && context) {
  728. workarea[0].scrollTop += 25;
  729. }
  730. var link_str = '';
  731. if(context) {
  732. var str = '';
  733. link_str = '<a href="#" data-root="y">' + svgCanvas.getCurrentDrawing().getCurrentLayerName() + '</a>';
  734. $(context).parentsUntil('#svgcontent > g').andSelf().each(function() {
  735. if(this.id) {
  736. str += ' > ' + this.id;
  737. if(this !== context) {
  738. link_str += ' > <a href="#">' + this.id + '</a>';
  739. } else {
  740. link_str += ' > ' + this.id;
  741. }
  742. }
  743. });
  744. cur_context = str;
  745. } else {
  746. cur_context = null;
  747. }
  748. $('#cur_context_panel').toggle(!!context).html(link_str);
  749. updateTitle();
  750. }
  751. // Makes sure the current selected paint is available to work with
  752. var prepPaints = function() {
  753. paintBox.fill.prep();
  754. paintBox.stroke.prep();
  755. }
  756. var flyout_funcs = {};
  757. var setupFlyouts = function(holders) {
  758. $.each(holders, function(hold_sel, btn_opts) {
  759. var buttons = $(hold_sel).children();
  760. var show_sel = hold_sel + '_show';
  761. var shower = $(show_sel);
  762. var def = false;
  763. buttons.addClass('tool_button')
  764. .unbind('click mousedown mouseup') // may not be necessary
  765. .each(function(i) {
  766. // Get this buttons options
  767. var opts = btn_opts[i];
  768. // Remember the function that goes with this ID
  769. flyout_funcs[opts.sel] = opts.fn;
  770. if(opts.isDefault) def = i;
  771. // Clicking the icon in flyout should set this set's icon
  772. var func = function() {
  773. if($(this).hasClass('disabled')) return false;
  774. if (toolButtonClick(show_sel)) {
  775. opts.fn();
  776. }
  777. if(opts.icon) {
  778. var icon = $.getSvgIcon(opts.icon, true);
  779. } else {
  780. //
  781. var icon = $(opts.sel).children().eq(0).clone();
  782. }
  783. icon[0].setAttribute('width',shower.width());
  784. icon[0].setAttribute('height',shower.height());
  785. shower.children(':not(.flyout_arrow_horiz)').remove();
  786. shower.append(icon).attr('data-curopt', opts.sel); // This sets the current mode
  787. }
  788. $(this).mouseup(func);
  789. if(opts.key) {
  790. $(document).bind('keydown', opts.key+'', func);
  791. }
  792. });
  793. if(def) {
  794. shower.attr('data-curopt', btn_opts[def].sel);
  795. } else if(!shower.attr('data-curopt')) {
  796. // Set first as default
  797. shower.attr('data-curopt', btn_opts[0].sel);
  798. }
  799. var timer;
  800. var pos = $(show_sel).position();
  801. $(hold_sel).css({'left': pos.left+34, 'top': pos.top+77});
  802. // Clicking the "show" icon should set the current mode
  803. shower.mousedown(function(evt) {
  804. if(shower.hasClass('disabled')) return false;
  805. var holder = $(hold_sel);
  806. var l = pos.left+34;
  807. var w = holder.width()*-1;
  808. var time = holder.data('shown_popop')?200:0;
  809. timer = setTimeout(function() {
  810. // Show corresponding menu
  811. if(!shower.data('isLibrary')) {
  812. holder.css('left', w).show().animate({
  813. left: l
  814. },150);
  815. } else {
  816. holder.css('left', l).show();
  817. }
  818. holder.data('shown_popop',true);
  819. },time);
  820. evt.preventDefault();
  821. }).mouseup(function(evt) {
  822. clearTimeout(timer);
  823. var opt = $(this).attr('data-curopt');
  824. // Is library and popped up, so do nothing
  825. if(shower.data('isLibrary') && $(show_sel.replace('_show','')).is(':visible')) {
  826. toolButtonClick(show_sel, true);
  827. return;
  828. }
  829. if (toolButtonClick(show_sel) && (opt in flyout_funcs)) {
  830. flyout_funcs[opt]();
  831. }
  832. });
  833. // $('#tools_rect').mouseleave(function(){$('#tools_rect').fadeOut();});
  834. });
  835. setFlyoutTitles();
  836. }
  837. var makeFlyoutHolder = function(id, child) {
  838. var div = $('<div>',{
  839. 'class': 'tools_flyout',
  840. id: id
  841. }).appendTo('#svg_editor').append(child);
  842. return div;
  843. }
  844. var setFlyoutPositions = function() {
  845. $('.tools_flyout').each(function() {
  846. var shower = $('#' + this.id + '_show');
  847. var pos = shower.offset();
  848. var w = shower.outerWidth();
  849. $(this).css({left: (pos.left + w)*tool_scale, top: pos.top});
  850. });
  851. }
  852. var setFlyoutTitles = function() {
  853. $('.tools_flyout').each(function() {
  854. var shower = $('#' + this.id + '_show');
  855. if(shower.data('isLibrary')) return;
  856. var tooltips = [];
  857. $(this).children().each(function() {
  858. tooltips.push(this.title);
  859. });
  860. shower[0].title = tooltips.join(' / ');
  861. });
  862. }
  863. var resize_timer;
  864. var extAdded = function(window, ext) {
  865. var cb_called = false;
  866. var resize_done = false;
  867. var cb_ready = true; // Set to false to delay callback (e.g. wait for $.svgIcons)
  868. function prepResize() {
  869. if(resize_timer) {
  870. clearTimeout(resize_timer);
  871. resize_timer = null;
  872. }
  873. if(!resize_done) {
  874. resize_timer = setTimeout(function() {
  875. resize_done = true;
  876. setIconSize(curPrefs.iconsize);
  877. }, 50);
  878. }
  879. }
  880. var runCallback = function() {
  881. if(ext.callback && !cb_called && cb_ready) {
  882. cb_called = true;
  883. ext.callback();
  884. }
  885. }
  886. var btn_selects = [];
  887. if(ext.context_tools) {
  888. $.each(ext.context_tools, function(i, tool) {
  889. // Add select tool
  890. var cont_id = tool.container_id?(' id="' + tool.container_id + '"'):"";
  891. var panel = $('#' + tool.panel);
  892. // create the panel if it doesn't exist
  893. if(!panel.length)
  894. panel = $('<div>', {id: tool.panel}).appendTo("#tools_top");
  895. // TODO: Allow support for other types, or adding to existing tool
  896. switch (tool.type) {
  897. case 'tool_button':
  898. var html = '<div class="tool_button">' + tool.id + '</div>';
  899. var div = $(html).appendTo(panel);
  900. if (tool.events) {
  901. $.each(tool.events, function(evt, func) {
  902. $(div).bind(evt, func);
  903. });
  904. }
  905. break;
  906. case 'select':
  907. var html = '<label' + cont_id + '>'
  908. + '<select id="' + tool.id + '">';
  909. $.each(tool.options, function(val, text) {
  910. var sel = (val == tool.defval) ? " selected":"";
  911. html += '<option value="'+val+'"' + sel + '>' + text + '</option>';
  912. });
  913. html += "</select></label>";
  914. // Creates the tool, hides & adds it, returns the select element
  915. var sel = $(html).appendTo(panel).find('select');
  916. $.each(tool.events, function(evt, func) {
  917. $(sel).bind(evt, func);
  918. });
  919. break;
  920. case 'button-select':
  921. var html = '<div id="' + tool.id + '" class="dropdown toolset" title="' + tool.title + '">'
  922. + '<div id="cur_' + tool.id + '" class="icon_label"></div><button></button></div>';
  923. var list = $('<ul id="' + tool.id + '_opts"></ul>').appendTo('#option_lists');
  924. if(tool.colnum) {
  925. list.addClass('optcols' + tool.colnum);
  926. }
  927. // Creates the tool, hides & adds it, returns the select element
  928. var dropdown = $(html).appendTo(panel).children();
  929. btn_selects.push({
  930. elem: ('#' + tool.id),
  931. list: ('#' + tool.id + '_opts'),
  932. title: tool.title,
  933. callback: tool.events.change,
  934. cur: ('#cur_' + tool.id)
  935. });
  936. break;
  937. case 'input':
  938. var html = '<label' + cont_id + '>'
  939. + '<span id="' + tool.id + '_label">'
  940. + tool.label + ':</span>'
  941. + '<input id="' + tool.id + '" title="' + tool.title
  942. + '" size="' + (tool.size || "4") + '" value="' + (tool.defval || "") + '" type="text"/></label>'
  943. // Creates the tool, hides & adds it, returns the select element
  944. // Add to given tool.panel
  945. var inp = $(html).appendTo(panel).find('input');
  946. if(tool.spindata) {
  947. inp.SpinButton(tool.spindata);
  948. }
  949. if(tool.events) {
  950. $.each(tool.events, function(evt, func) {
  951. inp.bind(evt, func);
  952. });
  953. }
  954. break;
  955. default:
  956. break;
  957. }
  958. });
  959. }
  960. if(ext.buttons) {
  961. var fallback_obj = {},
  962. placement_obj = {},
  963. svgicons = ext.svgicons;
  964. var holders = {};
  965. // Add buttons given by extension
  966. $.each(ext.buttons, function(i, btn) {
  967. var icon;
  968. var id = btn.id;
  969. var num = i;
  970. // Give button a unique ID
  971. while($('#'+id).length) {
  972. id = btn.id + '_' + (++num);
  973. }
  974. if(!svgicons) {
  975. icon = $('<img src="' + btn.icon + '">');
  976. } else {
  977. fallback_obj[id] = btn.icon;
  978. var svgicon = btn.svgicon?btn.svgicon:btn.id;
  979. if(btn.type == 'app_menu') {
  980. placement_obj['#' + id + ' > div'] = svgicon;
  981. } else {
  982. placement_obj['#' + id] = svgicon;
  983. }
  984. }
  985. var cls, parent;
  986. // Set button up according to its type
  987. switch ( btn.type ) {
  988. case 'mode_flyout':
  989. case 'mode':
  990. cls = 'tool_button';
  991. parent = "#tools_left";
  992. break;
  993. case 'context':
  994. cls = 'tool_button';
  995. parent = "#" + btn.panel;
  996. // create the panel if it doesn't exist
  997. if(!$(parent).length)
  998. $('<div>', {id: btn.panel}).appendTo("#tools_top");
  999. break;
  1000. case 'app_menu':
  1001. cls = '';
  1002. parent = '#main_menu ul';
  1003. break;
  1004. }
  1005. var button = $((btn.list || btn.type == 'app_menu')?'<li/>':'<div/>')
  1006. .attr("id", id)
  1007. .attr("title", btn.title)
  1008. .addClass(cls);
  1009. if(!btn.includeWith && !btn.list) {
  1010. if("position" in btn) {
  1011. $(parent).children().eq(btn.position).before(button);
  1012. } else {
  1013. button.appendTo(parent);
  1014. }
  1015. if(btn.type =='mode_flyout') {
  1016. // Add to flyout menu / make flyout menu
  1017. // var opts = btn.includeWith;
  1018. // // opts.button, default, position
  1019. var ref_btn = $(button);
  1020. var flyout_holder = ref_btn.parent();
  1021. // Create a flyout menu if there isn't one already
  1022. if(!ref_btn.parent().hasClass('tools_flyout')) {
  1023. // Create flyout placeholder
  1024. var tls_id = ref_btn[0].id.replace('tool_','tools_')
  1025. var show_btn = ref_btn.clone()
  1026. .attr('id',tls_id + '_show')
  1027. .append($('<div>',{'class':'flyout_arrow_horiz'}));
  1028. ref_btn.before(show_btn);
  1029. // Create a flyout div
  1030. flyout_holder = makeFlyoutHolder(tls_id, ref_btn);
  1031. flyout_holder.data('isLibrary', true);
  1032. show_btn.data('isLibrary', true);
  1033. }
  1034. // var ref_data = Actions.getButtonData(opts.button);
  1035. placement_obj['#' + tls_id + '_show'] = btn.id;
  1036. // TODO: Find way to set the current icon using the iconloader if this is not default
  1037. // Include data for extension button as well as ref button
  1038. var cur_h = holders['#'+flyout_holder[0].id] = [{
  1039. sel: '#'+id,
  1040. fn: btn.events.click,
  1041. icon: btn.id,
  1042. // key: btn.key,
  1043. isDefault: true
  1044. }, ref_data];
  1045. //
  1046. // // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'}
  1047. //
  1048. // var pos = ("position" in opts)?opts.position:'last';
  1049. // var len = flyout_holder.children().length;
  1050. //
  1051. // // Add at given position or end
  1052. // if(!isNaN(pos) && pos >= 0 && pos < len) {
  1053. // flyout_holder.children().eq(pos).before(button);
  1054. // } else {
  1055. // flyout_holder.append(button);
  1056. // cur_h.reverse();
  1057. // }
  1058. } else if(btn.type == 'app_menu') {
  1059. button.append('<div>').append(btn.title);
  1060. }
  1061. } else if(btn.list) {
  1062. // Add button to list
  1063. button.addClass('push_button');
  1064. $('#' + btn.list + '_opts').append(button);
  1065. if(btn.isDefault) {
  1066. $('#cur_' + btn.list).append(button.children().clone());
  1067. var svgicon = btn.svgicon?btn.svgicon:btn.id;
  1068. placement_obj['#cur_' + btn.list] = svgicon;
  1069. }
  1070. } else if(btn.includeWith) {
  1071. // Add to flyout menu / make flyout menu
  1072. var opts = btn.includeWith;
  1073. // opts.button, default, position
  1074. var ref_btn = $(opts.button);
  1075. var flyout_holder = ref_btn.parent();
  1076. // Create a flyout menu if there isn't one already
  1077. if(!ref_btn.parent().hasClass('tools_flyout')) {
  1078. // Create flyout placeholder
  1079. var tls_id = ref_btn[0].id.replace('tool_','tools_')
  1080. var show_btn = ref_btn.clone()
  1081. .attr('id',tls_id + '_show')
  1082. .append($('<div>',{'class':'flyout_arrow_horiz'}));
  1083. ref_btn.before(show_btn);
  1084. // Create a flyout div
  1085. flyout_holder = makeFlyoutHolder(tls_id, ref_btn);
  1086. }
  1087. var ref_data = Actions.getButtonData(opts.button);
  1088. if(opts.isDefault) {
  1089. placement_obj['#' + tls_id + '_show'] = btn.id;
  1090. }
  1091. // TODO: Find way to set the current icon using the iconloader if this is not default
  1092. // Include data for extension button as well as ref button
  1093. var cur_h = holders['#'+flyout_holder[0].id] = [{
  1094. sel: '#'+id,
  1095. fn: btn.events.click,
  1096. icon: btn.id,
  1097. key: btn.key,
  1098. isDefault: btn.includeWith?btn.includeWith.isDefault:0
  1099. }, ref_data];
  1100. // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'}
  1101. var pos = ("position" in opts)?opts.position:'last';
  1102. var len = flyout_holder.children().length;
  1103. // Add at given position or end
  1104. if(!isNaN(pos) && pos >= 0 && pos < len) {
  1105. flyout_holder.children().eq(pos).before(button);
  1106. } else {
  1107. flyout_holder.append(button);
  1108. cur_h.reverse();
  1109. }
  1110. }
  1111. if(!svgicons) {
  1112. button.append(icon);
  1113. }
  1114. if(!btn.list) {
  1115. // Add given events to button
  1116. $.each(btn.events, function(name, func) {
  1117. if(name == "click") {
  1118. if(btn.type == 'mode') {
  1119. if(btn.includeWith) {
  1120. button.bind(name, func);
  1121. } else {
  1122. button.bind(name, function() {
  1123. if(toolButtonClick(button)) {
  1124. func();
  1125. }
  1126. });
  1127. }
  1128. if(btn.key) {
  1129. $(document).bind('keydown', btn.key, func);
  1130. if(btn.title) button.attr("title", btn.title + ' ['+btn.key+']');
  1131. }
  1132. } else {
  1133. button.bind(name, func);
  1134. }
  1135. } else {
  1136. button.bind(name, func);
  1137. }
  1138. });
  1139. }
  1140. setupFlyouts(holders);
  1141. });
  1142. $.each(btn_selects, function() {
  1143. addAltDropDown(this.elem, this.list, this.callback, {seticon: true});
  1144. });
  1145. if (svgicons)
  1146. cb_ready = false; // Delay callback
  1147. $.svgIcons(svgicons, {
  1148. w:24, h:24,
  1149. id_match: false,
  1150. no_img: (!isWebkit),
  1151. fallback: fallback_obj,
  1152. placement: placement_obj,
  1153. callback: function(icons) {
  1154. // Non-ideal hack to make the icon match the current size
  1155. if(curPrefs.iconsize && curPrefs.iconsize != 'm') {
  1156. prepResize();
  1157. }
  1158. cb_ready = true; // Ready for callback
  1159. runCallback();
  1160. }
  1161. });
  1162. }
  1163. runCallback();
  1164. };
  1165. var getPaint = function(color, opac, type) {
  1166. // update the editor's fill paint
  1167. var opts = null;
  1168. if (color.indexOf("url(#") === 0) {
  1169. var refElem = svgCanvas.getRefElem(color);
  1170. if(refElem) {
  1171. refElem = refElem.cloneNode(true);
  1172. } else {
  1173. refElem = $("#" + type + "_color defs *")[0];
  1174. }
  1175. opts = { alpha: opac };
  1176. opts[refElem.tagName] = refElem;
  1177. }
  1178. else if (color.indexOf("#") === 0) {
  1179. opts = {
  1180. alpha: opac,
  1181. solidColor: color.substr(1)
  1182. };
  1183. }
  1184. else {
  1185. opts = {
  1186. alpha: opac,
  1187. solidColor: 'none'
  1188. };
  1189. }
  1190. return new $.jGraduate.Paint(opts);
  1191. };
  1192. // updates the toolbar (colors, opacity, etc) based on the selected element
  1193. // This function also updates the opacity and id elements that are in the context panel
  1194. var updateToolbar = function() {
  1195. if (selectedElement != null) {
  1196. switch ( selectedElement.tagName ) {
  1197. case 'use':
  1198. case 'image':
  1199. case 'foreignObject':
  1200. break;
  1201. case 'g':
  1202. case 'a':
  1203. // Look for common styles
  1204. var gWidth = null;
  1205. var childs = selectedElement.getElementsByTagName('*');
  1206. for(var i = 0, len = childs.length; i < len; i++) {
  1207. var swidth = childs[i].getAttribute("stroke-width");
  1208. if(i === 0) {
  1209. gWidth = swidth;
  1210. } else if(gWidth !== swidth) {
  1211. gWidth = null;
  1212. }
  1213. }
  1214. $('#stroke_width').val(gWidth === null ? "" : gWidth);
  1215. paintBox.fill.update(true);
  1216. paintBox.stroke.update(true);
  1217. break;
  1218. default:
  1219. paintBox.fill.update(true);
  1220. paintBox.stroke.update(true);
  1221. $('#stroke_width').val(selectedElement.getAttribute("stroke-width") || 1);
  1222. $('#stroke_style').val(selectedElement.getAttribute("stroke-dasharray")||"none");
  1223. var attr = selectedElement.getAttribute("stroke-linejoin") || 'miter';
  1224. if ($('#linejoin_' + attr).length != 0)
  1225. setStrokeOpt($('#linejoin_' + attr)[0]);
  1226. attr = selectedElement.getAttribute("stroke-linecap") || 'butt';
  1227. if ($('#linecap_' + attr).length != 0)
  1228. setStrokeOpt($('#linecap_' + attr)[0]);
  1229. }
  1230. }
  1231. // All elements including image and group have opacity
  1232. if(selectedElement != null) {
  1233. var opac_perc = ((selectedElement.getAttribute("opacity")||1.0)*100);
  1234. $('#group_opacity').val(opac_perc);
  1235. $('#opac_slider').slider('option', 'value', opac_perc);
  1236. $('#elem_id').val(selectedElement.id);
  1237. }
  1238. updateToolButtonState();
  1239. };
  1240. var setImageURL = Editor.setImageURL = function(url) {
  1241. if(!url) url = default_img_url;
  1242. svgCanvas.setImageURL(url);
  1243. $('#image_url').val(url);
  1244. if(url.indexOf('data:') === 0) {
  1245. // data URI found
  1246. $('#image_url').hide();
  1247. $('#change_image_url').show();
  1248. } else {
  1249. // regular URL
  1250. svgCanvas.embedImage(url, function(datauri) {
  1251. if(!datauri) {
  1252. // Couldn't embed, so show warning
  1253. $('#url_notice').show();
  1254. } else {
  1255. $('#url_notice').hide();
  1256. }
  1257. default_img_url = url;
  1258. });
  1259. $('#image_url').show();
  1260. $('#change_image_url').hide();
  1261. }
  1262. }
  1263. var setInputWidth = function(elem) {
  1264. var w = Math.min(Math.max(12 + elem.value.length * 6, 50), 300);
  1265. $(elem).width(w);
  1266. }
  1267. // updates the context panel tools based on the selected element
  1268. var updateContextPanel = function() {
  1269. var elem = selectedElement;
  1270. // If element has just been deleted, consider it null
  1271. if(elem != null && !elem.parentNode) elem = null;
  1272. var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName();
  1273. var currentMode = svgCanvas.getMode();
  1274. var unit = curConfig.baseUnit !== 'px' ? curConfig.baseUnit : null;
  1275. var is_node = currentMode == 'pathedit'; //elem ? (elem.id && elem.id.indexOf('pathpointgrip') == 0) : false;
  1276. var menu_items = $('#cmenu_canvas li');
  1277. $('#selected_panel, #multiselected_panel, #g_panel, #rect_panel, #circle_panel,\
  1278. #ellipse_panel, #line_panel, #text_panel, #image_panel, #container_panel, #use_panel, #a_panel').hide();
  1279. if (elem != null) {
  1280. var elname = elem.nodeName;
  1281. // If this is a link with no transform and one child, pretend
  1282. // its child is selected
  1283. // console.log('go', elem)
  1284. // if(elname === 'a') { // && !$(elem).attr('transform')) {
  1285. // elem = elem.firstChild;
  1286. // }
  1287. var angle = svgCanvas.getRotationAngle(elem);
  1288. $('#angle').val(angle);
  1289. var blurval = svgCanvas.getBlur(elem);
  1290. $('#blur').val(blurval);
  1291. $('#blur_slider').slider('option', 'value', blurval);
  1292. if(svgCanvas.addedNew) {
  1293. if(elname === 'image') {
  1294. // Prompt for URL if not a data URL
  1295. if(svgCanvas.getHref(elem).indexOf('data:') !== 0) {
  1296. promptImgURL();
  1297. }
  1298. } /*else if(elname == 'text') {
  1299. // TODO: Do something here for new text
  1300. }*/
  1301. }
  1302. if(!is_node && currentMode != 'pathedit') {
  1303. $('#selected_panel').show();
  1304. // Elements in this array already have coord fields
  1305. if(['line', 'circle', 'ellipse'].indexOf(elname) >= 0) {
  1306. $('#xy_panel').hide();
  1307. } else {
  1308. var x,y;
  1309. // Get BBox vals for g, polyline and path
  1310. if(['g', 'polyline', 'path'].indexOf(elname) >= 0) {
  1311. var bb = svgCanvas.getStrokedBBox([elem]);
  1312. if(bb) {
  1313. x = bb.x;
  1314. y = bb.y;
  1315. }
  1316. } else {
  1317. x = elem.getAttribute('x');
  1318. y = elem.getAttribute('y');
  1319. }
  1320. if(unit) {
  1321. x = svgedit.units.convertUnit(x);
  1322. y = svgedit.units.convertUnit(y);
  1323. }
  1324. $('#selected_x').val(x || 0);
  1325. $('#selected_y').val(y || 0);
  1326. $('#xy_panel').show();
  1327. }
  1328. // Elements in this array cannot be converted to a path
  1329. var no_path = ['image', 'text', 'path', 'g', 'use'].indexOf(elname) == -1;
  1330. $('#tool_topath').toggle(no_path);
  1331. $('#tool_reorient').toggle(elname == 'path');
  1332. $('#tool_reorient').toggleClass('disabled', angle == 0);
  1333. } else {
  1334. var point = path.getNodePoint();
  1335. $('#tool_add_subpath').removeClass('push_button_pressed').addClass('tool_button');
  1336. $('#tool_node_delete').toggleClass('disabled', !path.canDeleteNodes);
  1337. // Show open/close button based on selected point
  1338. setIcon('#tool_openclose_path', path.closed_subpath ? 'open_path' : 'close_path');
  1339. if(point) {
  1340. var seg_type = $('#seg_type');
  1341. if(unit) {
  1342. point.x = svgedit.units.convertUnit(point.x);
  1343. point.y = svgedit.units.convertUnit(point.y);
  1344. }
  1345. $('#path_node_x').val(point.x);
  1346. $('#path_node_y').val(point.y);
  1347. if(point.type) {
  1348. seg_type.val(point.type).removeAttr('disabled');
  1349. } else {
  1350. seg_type.val(4).attr('disabled','disabled');
  1351. }
  1352. }
  1353. return;
  1354. }
  1355. // update contextual tools here
  1356. var panels = {
  1357. g: [],
  1358. a: [],
  1359. rect: ['rx','width','height'],
  1360. image: ['width','height'],
  1361. circle: ['cx','cy','r'],
  1362. ellipse: ['cx','cy','rx','ry'],
  1363. line: ['x1','y1','x2','y2'],
  1364. text: [],
  1365. 'use': []
  1366. };
  1367. var el_name = elem.tagName;
  1368. // if($(elem).data('gsvg')) {
  1369. // $('#g_panel').show();
  1370. // }
  1371. var link_href = null;
  1372. if (el_name === 'a') {
  1373. link_href = svgCanvas.getHref(elem);
  1374. $('#g_panel').show();
  1375. }
  1376. if(elem.parentNode.tagName === 'a') {
  1377. if(!$(elem).siblings().length) {
  1378. $('#a_panel').show();
  1379. link_href = svgCanvas.getHref(elem.parentNode);
  1380. }
  1381. }
  1382. // Hide/show the make_link buttons
  1383. $('#tool_make_link, #tool_make_link').toggle(!link_href);
  1384. if(link_href) {
  1385. $('#link_url').val(link_href);
  1386. }
  1387. if(panels[el_name]) {
  1388. var cur_panel = panels[el_name];
  1389. $('#' + el_name + '_panel').show();
  1390. $.each(cur_panel, function(i, item) {
  1391. var attrVal = elem.getAttribute(item);
  1392. if(curConfig.baseUnit !== 'px' && elem[item]) {
  1393. var bv = elem[item].baseVal.value;
  1394. attrVal = svgedit.units.convertUnit(bv);
  1395. }
  1396. $('#' + el_name + '_' + item).val(attrVal || 0);
  1397. });
  1398. if(el_name == 'text') {
  1399. $('#text_panel').css("display", "inline");
  1400. if (svgCanvas.getItalic()) {
  1401. $('#tool_italic').addClass('push_button_pressed').removeClass('tool_button');
  1402. }
  1403. else {
  1404. $('#tool_italic').removeClass('push_button_pressed').addClass('tool_button');
  1405. }
  1406. if (svgCanvas.getBold()) {
  1407. $('#tool_bold').addClass('push_button_pressed').removeClass('tool_button');
  1408. }
  1409. else {
  1410. $('#tool_bold').removeClass('push_button_pressed').addClass('tool_button');
  1411. }
  1412. $('#font_family').val(elem.getAttribute("font-family"));
  1413. $('#font_size').val(elem.getAttribute("font-size"));
  1414. $('#text').val(elem.textContent);
  1415. if (svgCanvas.addedNew) {
  1416. // Timeout needed for IE9
  1417. setTimeout(function() {
  1418. $('#text').focus().select();
  1419. },100);
  1420. }
  1421. } // text
  1422. else if(el_name == 'image') {
  1423. setImageURL(svgCanvas.getHref(elem));
  1424. } // image
  1425. else if(el_name === 'g' || el_name === 'use') {
  1426. $('#container_panel').show();
  1427. var title = svgCanvas.getTitle();
  1428. var label = $('#g_title')[0];
  1429. label.value = title;
  1430. setInputWidth(label);
  1431. var d = 'disabled';
  1432. if(el_name == 'use') {
  1433. label.setAttribute(d, d);
  1434. } else {
  1435. label.removeAttribute(d);
  1436. }
  1437. }
  1438. }
  1439. menu_items[(el_name === 'g' ? 'en':'dis') + 'ableContextMenuItems']('#ungroup');
  1440. menu_items[((el_name === 'g' || !multiselected) ? 'dis':'en') + 'ableContextMenuItems']('#group');
  1441. } // if (elem != null)
  1442. else if (multiselected) {
  1443. $('#multiselected_panel').show();
  1444. menu_items
  1445. .enableContextMenuItems('#group')
  1446. .disableContextMenuItems('#ungroup');
  1447. } else {
  1448. menu_items.disableContextMenuItems('#delete,#cut,#copy,#group,#ungroup,#move_front,#move_up,#move_down,#move_back');
  1449. }
  1450. // update history buttons
  1451. if (undoMgr.getUndoStackSize() > 0) {
  1452. $('#tool_undo').removeClass( 'disabled');
  1453. }
  1454. else {
  1455. $('#tool_undo').addClass( 'disabled');
  1456. }
  1457. if (undoMgr.getRedoStackSize() > 0) {
  1458. $('#tool_redo').removeClass( 'disabled');
  1459. }
  1460. else {
  1461. $('#tool_redo').addClass( 'disabled');
  1462. }
  1463. svgCanvas.addedNew = false;
  1464. if ( (elem && !is_node) || multiselected) {
  1465. // update the selected elements' layer
  1466. $('#selLayerNames').removeAttr('disabled').val(currentLayerName);
  1467. // Enable regular menu options
  1468. canv_menu.enableContextMenuItems('#delete,#cut,#copy,#move_front,#move_up,#move_down,#move_back');
  1469. }
  1470. else {
  1471. $('#selLayerNames').attr('disabled', 'disabled');
  1472. }
  1473. };
  1474. $('#text').focus( function(){ textBeingEntered = true; } );
  1475. $('#text').blur( function(){ textBeingEntered = false; } );
  1476. // bind the selected event to our function that handles updates to the UI
  1477. svgCanvas.bind("selected", selectedChanged);
  1478. svgCanvas.bind("transition", elementTransition);
  1479. svgCanvas.bind("changed", elementChanged);
  1480. svgCanvas.bind("saved", saveHandler);
  1481. svgCanvas.bind("exported", exportHandler);
  1482. svgCanvas.bind("zoomed", zoomChanged);
  1483. svgCanvas.bind("contextset", contextChanged);
  1484. svgCanvas.bind("extension_added", extAdded);
  1485. svgCanvas.textActions.setInputElem($("#text")[0]);
  1486. var str = '<div class="palette_item" data-rgb="none"></div>'
  1487. $.each(palette, function(i,item){
  1488. str += '<div class="palette_item" style="background-color: ' + item + ';" data-rgb="' + item + '"></div>';
  1489. });
  1490. $('#palette').append(str);
  1491. // Set up editor background functionality
  1492. // TODO add checkerboard as "pattern"
  1493. var color_blocks = ['#FFF','#888','#000']; // ,'url(data:image/gif;base64,R0lGODlhEAAQAIAAAP%2F%2F%2F9bW1iH5BAAAAAAALAAAAAAQABAAAAIfjG%2Bgq4jM3IFLJgpswNly%2FXkcBpIiVaInlLJr9FZWAQA7)'];
  1494. var str = '';
  1495. $.each(color_blocks, function() {
  1496. str += '<div class="color_block" style="background-color:' + this + ';"></div>';
  1497. });
  1498. $('#bg_blocks').append(str);
  1499. var blocks = $('#bg_blocks div');
  1500. var cur_bg = 'cur_background';
  1501. blocks.each(function() {
  1502. var blk = $(this);
  1503. blk.click(function() {
  1504. blocks.removeClass(cur_bg);
  1505. $(this).addClass(cur_bg);
  1506. });
  1507. });
  1508. if($.pref('bkgd_color')) {
  1509. setBackground($.pref('bkgd_color'), $.pref('bkgd_url'));
  1510. } else if($.pref('bkgd_url')) {
  1511. // No color set, only URL
  1512. setBackground(defaultPrefs.bkgd_color, $.pref('bkgd_url'));
  1513. }
  1514. if($.pref('img_save')) {
  1515. curPrefs.img_save = $.pref('img_save');
  1516. $('#image_save_opts input').val([curPrefs.img_save]);
  1517. }
  1518. var changeRectRadius = function(ctl) {
  1519. svgCanvas.setRectRadius(ctl.value);
  1520. }
  1521. var changeFontSize = function(ctl) {
  1522. svgCanvas.setFontSize(ctl.value);
  1523. }
  1524. var changeStrokeWidth = function(ctl) {
  1525. var val = ctl.value;
  1526. if(val == 0 && selectedElement && ['line', 'polyline'].indexOf(selectedElement.nodeName) >= 0) {
  1527. val = ctl.value = 1;
  1528. }
  1529. svgCanvas.setStrokeWidth(val);
  1530. }
  1531. var changeRotationAngle = function(ctl) {
  1532. svgCanvas.setRotationAngle(ctl.value);
  1533. $('#tool_reorient').toggleClass('disabled', ctl.value == 0);
  1534. }
  1535. var changeZoom = function(ctl) {
  1536. var zoomlevel = ctl.value / 100;
  1537. if(zoomlevel < .001) {
  1538. ctl.value = .1;
  1539. return;
  1540. }
  1541. var zoom = svgCanvas.getZoom();
  1542. var w_area = workarea;
  1543. zoomChanged(window, {
  1544. width: 0,
  1545. height: 0,
  1546. // center pt of scroll position
  1547. x: (w_area[0].scrollLeft + w_area.width()/2)/zoom,
  1548. y: (w_area[0].scrollTop + w_area.height()/2)/zoom,
  1549. zoom: zoomlevel
  1550. }, true);
  1551. }
  1552. var changeOpacity = function(ctl, val) {
  1553. if(val == null) val = ctl.value;
  1554. $('#group_opacity').val(val);
  1555. if(!ctl || !ctl.handle) {
  1556. $('#opac_slider').slider('option', 'value', val);
  1557. }
  1558. svgCanvas.setOpacity(val/100);
  1559. }
  1560. var changeBlur = function(ctl, val, noUndo) {
  1561. if(val == null) val = ctl.value;
  1562. $('#blur').val(val);
  1563. var complete = false;
  1564. if(!ctl || !ctl.handle) {
  1565. $('#blur_slider').slider('option', 'value', val);
  1566. complete = true;
  1567. }
  1568. if(noUndo) {
  1569. svgCanvas.setBlurNoUndo(val);
  1570. } else {
  1571. svgCanvas.setBlur(val, complete);
  1572. }
  1573. }
  1574. var operaRepaint = function() {
  1575. // Repaints canvas in Opera. Needed for stroke-dasharray change as well as fill change
  1576. if(!window.opera) return;
  1577. $('<p/>').hide().appendTo('body').remove();
  1578. }
  1579. $('#stroke_style').change(function(){
  1580. svgCanvas.setStrokeAttr('stroke-dasharray', $(this).val());
  1581. operaRepaint();
  1582. });
  1583. $('#stroke_linejoin').change(function(){
  1584. svgCanvas.setStrokeAttr('stroke-linejoin', $(this).val());
  1585. operaRepaint();
  1586. });
  1587. // Lose focus for select elements when changed (Allows keyboard shortcuts to work better)
  1588. $('select').change(function(){$(this).blur();});
  1589. // fired when user wants to move elements to another layer
  1590. var promptMoveLayerOnce = false;
  1591. $('#selLayerNames').change(function(){
  1592. var destLayer = this.options[this.selectedIndex].value;
  1593. var confirm_str = uiStrings.notification.QmoveElemsToLayer.replace('%s',destLayer);
  1594. var moveToLayer = function(ok) {
  1595. if(!ok) return;
  1596. promptMoveLayerOnce = true;
  1597. svgCanvas.moveSelectedToLayer(destLayer);
  1598. svgCanvas.clearSelection();
  1599. populateLayers();
  1600. }
  1601. if (destLayer) {
  1602. if(promptMoveLayerOnce) {
  1603. moveToLayer(true);
  1604. } else {
  1605. $.confirm(confirm_str, moveToLayer);
  1606. }
  1607. }
  1608. });
  1609. $('#font_family').change(function() {
  1610. svgCanvas.setFontFamily(this.value);
  1611. });
  1612. $('#seg_type').change(function() {
  1613. svgCanvas.setSegType($(this).val());
  1614. });
  1615. $('#text').keyup(function(){
  1616. svgCanvas.setTextContent(this.value);
  1617. });
  1618. $('#image_url').change(function(){
  1619. setImageURL(this.value);
  1620. });
  1621. $('#link_url').change(function() {
  1622. if(this.value.length) {
  1623. svgCanvas.setLinkURL(this.value);
  1624. } else {
  1625. svgCanvas.removeHyperlink();
  1626. }
  1627. });
  1628. $('#g_title').change(function() {
  1629. svgCanvas.setGroupTitle(this.value);
  1630. });
  1631. $('.attr_changer').change(function() {
  1632. var attr = this.getAttribute("data-attr");
  1633. var val = this.value;
  1634. var valid = svgedit.units.isValidUnit(attr, val);
  1635. if(!valid) {
  1636. $.alert(uiStrings.notification.invalidAttrValGiven);
  1637. this.value = selectedElement.getAttribute(attr);
  1638. return false;
  1639. }
  1640. if (attr !== "id") {
  1641. if (isNaN(val)) {
  1642. val = svgCanvas.convertToNum(attr, val);
  1643. } else if(curConfig.baseUnit !== 'px') {
  1644. // Convert unitless value to one with given unit
  1645. var unitData = svgedit.units.getTypeMap();
  1646. if(selectedElement[attr] || svgCanvas.getMode() === "pathedit" || attr === "x" || attr === "y") {
  1647. val *= unitData[curConfig.baseUnit];
  1648. }
  1649. }
  1650. }
  1651. // if the user is changing the id, then de-select the element first
  1652. // change the ID, then re-select it with the new ID
  1653. if (attr === "id") {
  1654. var elem = selectedElement;
  1655. svgCanvas.clearSelection();
  1656. elem.id = val;
  1657. svgCanvas.addToSelection([elem],true);
  1658. }
  1659. else {
  1660. svgCanvas.changeSelectedAttribute(attr, val);
  1661. }
  1662. });
  1663. // Prevent selection of elements when shift-clicking
  1664. $('#palette').mouseover(function() {
  1665. var inp = $('<input type="hidden">');
  1666. $(this).append(inp);
  1667. inp.focus().remove();
  1668. })
  1669. $('.palette_item').mousedown(function(evt){
  1670. var right_click = evt.button === 2;
  1671. var isStroke = evt.shiftKey || right_click;
  1672. var picker = isStroke ? "stroke" : "fill";
  1673. var color = $(this).attr('data-rgb');
  1674. var paint = null;
  1675. // Webkit-based browsers returned 'initial' here for no stroke
  1676. if (color === 'transparent' || color === 'initial') {
  1677. color = 'none';
  1678. paint = new $.jGraduate.Paint();
  1679. }
  1680. else {
  1681. paint = new $.jGraduate.Paint({alpha: 100, solidColor: color.substr(1)});
  1682. }
  1683. paintBox[picker].setPaint(paint);
  1684. if (isStroke) {
  1685. svgCanvas.setColor('stroke', color);
  1686. if (color != 'none' && svgCanvas.getStrokeOpacity() != 1) {
  1687. svgCanvas.setPaintOpacity('stroke', 1.0);
  1688. }
  1689. } else {
  1690. svgCanvas.setColor('fill', color);
  1691. if (color != 'none' && svgCanvas.getFillOpacity() != 1) {
  1692. svgCanvas.setPaintOpacity('fill', 1.0);
  1693. }
  1694. }
  1695. updateToolButtonState();
  1696. }).bind('contextmenu', function(e) {e.preventDefault()});
  1697. $("#toggle_stroke_tools").toggle(function() {
  1698. $(".stroke_tool").css('display','table-cell');
  1699. $(this).text('<<');
  1700. resetScrollPos();
  1701. }, function() {
  1702. $(".stroke_tool").css('display','none');
  1703. $(this).text('>>');
  1704. resetScrollPos();
  1705. });
  1706. // This is a common function used when a tool has been clicked (chosen)
  1707. // It does several common things:
  1708. // - removes the tool_button_current class from whatever tool currently has it
  1709. // - hides any flyouts
  1710. // - adds the tool_button_current class to the button passed in
  1711. var toolButtonClick = function(button, noHiding) {
  1712. if ($(button).hasClass('disabled')) return false;
  1713. if($(button).parent().hasClass('tools_flyout')) return true;
  1714. var fadeFlyouts = fadeFlyouts || 'normal';
  1715. if(!noHiding) {
  1716. $('.tools_flyout').fadeOut(fadeFlyouts);
  1717. }
  1718. $('#styleoverrides').text('');
  1719. workarea.css('cursor','auto');
  1720. $('.tool_button_current').removeClass('tool_button_current').addClass('tool_button');
  1721. $(button).addClass('tool_button_current').removeClass('tool_button');
  1722. return true;
  1723. };
  1724. (function() {
  1725. var last_x = null, last_y = null, w_area = workarea[0],
  1726. panning = false, keypan = false;
  1727. $('#svgcanvas').bind('mousemove mouseup', function(evt) {
  1728. if(panning === false) return;
  1729. w_area.scrollLeft -= (evt.clientX - last_x);
  1730. w_area.scrollTop -= (evt.clientY - last_y);
  1731. last_x = evt.clientX;
  1732. last_y = evt.clientY;
  1733. if(evt.type === 'mouseup') panning = false;
  1734. return false;
  1735. }).mousedown(function(evt) {
  1736. if(evt.button === 1 || keypan === true) {
  1737. panning = true;
  1738. last_x = evt.clientX;
  1739. last_y = evt.clientY;
  1740. return false;
  1741. }
  1742. });
  1743. $(window).mouseup(function() {
  1744. panning = false;
  1745. });
  1746. $(document).bind('keydown', 'space', function(evt) {
  1747. svgCanvas.spaceKey = keypan = true;
  1748. evt.preventDefault();
  1749. }).bind('keyup', 'space', function(evt) {
  1750. evt.preventDefault();
  1751. svgCanvas.spaceKey = keypan = false;
  1752. }).bind('keydown', 'shift', function(evt) {
  1753. if(svgCanvas.getMode() === 'zoom') {
  1754. workarea.css('cursor', zoomOutIcon);
  1755. }
  1756. }).bind('keyup', 'shift', function(evt) {
  1757. if(svgCanvas.getMode() === 'zoom') {
  1758. workarea.css('cursor', zoomInIcon);
  1759. }
  1760. })
  1761. }());
  1762. function setStrokeOpt(opt, changeElem) {
  1763. var id = opt.id;
  1764. var bits = id.split('_');
  1765. var pre = bits[0];
  1766. var val = bits[1];
  1767. if(changeElem) {
  1768. svgCanvas.setStrokeAttr('stroke-' + pre, val);
  1769. }
  1770. operaRepaint();
  1771. setIcon('#cur_' + pre , id, 20);
  1772. $(opt).addClass('current').siblings().removeClass('current');
  1773. }
  1774. (function() {
  1775. var button = $('#main_icon');
  1776. var overlay = $('#main_icon span');
  1777. var list = $('#main_menu');
  1778. var on_button = false;
  1779. var height = 0;
  1780. var js_hover = true;
  1781. var set_click = false;
  1782. var hideMenu = function() {
  1783. list.fadeOut(200);
  1784. };
  1785. $(window).mouseup(function(evt) {
  1786. if(!on_button) {
  1787. button.removeClass('buttondown');
  1788. // do not hide if it was the file input as that input needs to be visible
  1789. // for its change event to fire
  1790. if (evt.target.tagName != "INPUT") {
  1791. list.fadeOut(200);
  1792. } else if(!set_click) {
  1793. set_click = true;
  1794. $(evt.target).click(function() {
  1795. list.css('margin-left','-9999px').show();
  1796. });
  1797. }
  1798. }
  1799. on_button = false;
  1800. }).mousedown(function(evt) {
  1801. // $(".contextMenu").hide();
  1802. // console.log('cm', $(evt.target).closest('.contextMenu'));
  1803. var islib = $(evt.target).closest('div.tools_flyout, .contextMenu').length;
  1804. if(!islib) $('.tools_flyout:visible,.contextMenu').fadeOut(250);
  1805. });
  1806. overlay.bind('mousedown',function() {
  1807. if (!button.hasClass('buttondown')) {
  1808. button.addClass('buttondown').removeClass('buttonup')
  1809. // Margin must be reset in case it was changed before;
  1810. list.css('margin-left',0).show();
  1811. if(!height) {
  1812. height = list.height();
  1813. }
  1814. // Using custom animation as slideDown has annoying "bounce effect"
  1815. list.css('height',0).animate({
  1816. 'height': height
  1817. },200);
  1818. on_button = true;
  1819. return false;
  1820. } else {
  1821. button.removeClass('buttondown').addClass('buttonup');
  1822. list.fadeOut(200);
  1823. }
  1824. }).hover(function() {
  1825. on_button = true;
  1826. }).mouseout(function() {
  1827. on_button = false;
  1828. });
  1829. var list_items = $('#main_menu li');
  1830. // Check if JS method of hovering needs to be used (Webkit bug)
  1831. list_items.mouseover(function() {
  1832. js_hover = ($(this).css('background-color') == 'rgba(0, 0, 0, 0)');
  1833. list_items.unbind('mouseover');
  1834. if(js_hover) {
  1835. list_items.mouseover(function() {
  1836. this.style.backgroundColor = '#FFC';
  1837. }).mouseout(function() {
  1838. this.style.backgroundColor = 'transparent';
  1839. return true;
  1840. });
  1841. }
  1842. });
  1843. }());
  1844. // Made public for UI customization.
  1845. // TODO: Group UI functions into a public svgEditor.ui interface.
  1846. Editor.addDropDown = function(elem, callback, dropUp) {
  1847. if ($(elem).length == 0) return; // Quit if called on non-existant element
  1848. var button = $(elem).find('button');
  1849. var list = $(elem).find('ul').attr('id', $(elem)[0].id + '-list');
  1850. if(!dropUp) {
  1851. // Move list to place where it can overflow container
  1852. $('#option_lists').append(list);
  1853. }
  1854. var on_button = false;
  1855. if(dropUp) {
  1856. $(elem).addClass('dropup');
  1857. }
  1858. list.find('li').bind('mouseup', callback);
  1859. $(window).mouseup(function(evt) {
  1860. if(!on_button) {
  1861. button.removeClass('down');
  1862. list.hide();
  1863. }
  1864. on_button = false;
  1865. });
  1866. button.bind('mousedown',function() {
  1867. if (!button.hasClass('down')) {
  1868. button.addClass('down');
  1869. if(!dropUp) {
  1870. var pos = $(elem).position();
  1871. list.css({
  1872. top: pos.top + 24,
  1873. left: pos.left - 10
  1874. });
  1875. }
  1876. list.show();
  1877. on_button = true;
  1878. } else {
  1879. button.removeClass('down');
  1880. list.hide();
  1881. }
  1882. }).hover(function() {
  1883. on_button = true;
  1884. }).mouseout(function() {
  1885. on_button = false;
  1886. });
  1887. }
  1888. // TODO: Combine this with addDropDown or find other way to optimize
  1889. var addAltDropDown = function(elem, list, callback, opts) {
  1890. var button = $(elem);
  1891. var list = $(list);
  1892. var on_button = false;
  1893. var dropUp = opts.dropUp;
  1894. if(dropUp) {
  1895. $(elem).addClass('dropup');
  1896. }
  1897. list.find('li').bind('mouseup', function() {
  1898. if(opts.seticon) {
  1899. setIcon('#cur_' + button[0].id , $(this).children());
  1900. $(this).addClass('current').siblings().removeClass('current');
  1901. }
  1902. callback.apply(this, arguments);
  1903. });
  1904. $(window).mouseup(function(evt) {
  1905. if(!on_button) {
  1906. button.removeClass('down');
  1907. list.hide();
  1908. list.css({top:0, left:0});
  1909. }
  1910. on_button = false;
  1911. });
  1912. var height = list.height();
  1913. $(elem).bind('mousedown',function() {
  1914. var off = $(elem).offset();
  1915. if(dropUp) {
  1916. off.top -= list.height();
  1917. off.left += 8;
  1918. } else {
  1919. off.top += $(elem).height();
  1920. }
  1921. $(list).offset(off);
  1922. if (!button.hasClass('down')) {
  1923. button.addClass('down');
  1924. list.show();
  1925. on_button = true;
  1926. return false;
  1927. } else {
  1928. button.removeClass('down');
  1929. // CSS position must be reset for Webkit
  1930. list.hide();
  1931. list.css({top:0, left:0});
  1932. }
  1933. }).hover(function() {
  1934. on_button = true;
  1935. }).mouseout(function() {
  1936. on_button = false;
  1937. });
  1938. if(opts.multiclick) {
  1939. list.mousedown(function() {
  1940. on_button = true;
  1941. });
  1942. }
  1943. }
  1944. Editor.addDropDown('#font_family_dropdown', function() {
  1945. var fam = $(this).text();
  1946. $('#font_family').val($(this).text()).change();
  1947. });
  1948. Editor.addDropDown('#opacity_dropdown', function() {
  1949. if($(this).find('div').length) return;
  1950. var perc = parseInt($(this).text().split('%')[0]);
  1951. changeOpacity(false, perc);
  1952. }, true);
  1953. // For slider usage, see: http://jqueryui.com/demos/slider/
  1954. $("#opac_slider").slider({
  1955. start: function() {
  1956. $('#opacity_dropdown li:not(.special)').hide();
  1957. },
  1958. stop: function() {
  1959. $('#opacity_dropdown li').show();
  1960. $(window).mouseup();
  1961. },
  1962. slide: function(evt, ui){
  1963. changeOpacity(ui);
  1964. }
  1965. });
  1966. Editor.addDropDown('#blur_dropdown', $.noop);
  1967. var slideStart = false;
  1968. $("#blur_slider").slider({
  1969. max: 10,
  1970. step: .1,
  1971. stop: function(evt, ui) {
  1972. slideStart = false;
  1973. changeBlur(ui);
  1974. $('#blur_dropdown li').show();
  1975. $(window).mouseup();
  1976. },
  1977. start: function() {
  1978. slideStart = true;
  1979. },
  1980. slide: function(evt, ui){
  1981. changeBlur(ui, null, slideStart);
  1982. }
  1983. });
  1984. Editor.addDropDown('#zoom_dropdown', function() {
  1985. var item = $(this);
  1986. var val = item.attr('data-val');
  1987. if(val) {
  1988. zoomChanged(window, val);
  1989. } else {
  1990. changeZoom({value:parseInt(item.text())});
  1991. }
  1992. }, true);
  1993. addAltDropDown('#stroke_linecap', '#linecap_opts', function() {
  1994. setStrokeOpt(this, true);
  1995. }, {dropUp: true});
  1996. addAltDropDown('#stroke_linejoin', '#linejoin_opts', function() {
  1997. setStrokeOpt(this, true);
  1998. }, {dropUp: true});
  1999. addAltDropDown('#tool_position', '#position_opts', function() {
  2000. var letter = this.id.replace('tool_pos','').charAt(0);
  2001. svgCanvas.alignSelectedElements(letter, 'page');
  2002. }, {multiclick: true});
  2003. /*
  2004. When a flyout icon is selected
  2005. (if flyout) {
  2006. - Change the icon
  2007. - Make pressing the button run its stuff
  2008. }
  2009. - Run its stuff
  2010. When its shortcut key is pressed
  2011. - If not current in list, do as above
  2012. , else:
  2013. - Just run its stuff
  2014. */
  2015. // Unfocus text input when workarea is mousedowned.
  2016. (function() {
  2017. var inp;
  2018. var unfocus = function() {
  2019. $(inp).blur();
  2020. }
  2021. $('#svg_editor').find('button, select, input:not(#text)').focus(function() {
  2022. inp = this;
  2023. ui_context = 'toolbars';
  2024. workarea.mousedown(unfocus);
  2025. }).blur(function() {
  2026. ui_context = 'canvas';
  2027. workarea.unbind('mousedown', unfocus);
  2028. // Go back to selecting text if in textedit mode
  2029. if(svgCanvas.getMode() == 'textedit') {
  2030. $('#text').focus();
  2031. }
  2032. });
  2033. }());
  2034. var clickSelect = function() {
  2035. if (toolButtonClick('#tool_select')) {
  2036. svgCanvas.setMode('select');
  2037. $('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all}, #svgcanvas svg{cursor:default}');
  2038. }
  2039. };
  2040. var clickFHPath = function() {
  2041. if (toolButtonClick('#tool_fhpath')) {
  2042. svgCanvas.setMode('fhpath');
  2043. }
  2044. };
  2045. var clickLine = function() {
  2046. if (toolButtonClick('#tool_line')) {
  2047. svgCanvas.setMode('line');
  2048. }
  2049. };
  2050. var clickSquare = function(){
  2051. if (toolButtonClick('#tool_square')) {
  2052. svgCanvas.setMode('square');
  2053. }
  2054. };
  2055. var clickRect = function(){
  2056. if (toolButtonClick('#tool_rect')) {
  2057. svgCanvas.setMode('rect');
  2058. }
  2059. };
  2060. var clickFHRect = function(){
  2061. if (toolButtonClick('#tool_fhrect')) {
  2062. svgCanvas.setMode('fhrect');
  2063. }
  2064. };
  2065. var clickCircle = function(){
  2066. if (toolButtonClick('#tool_circle')) {
  2067. svgCanvas.setMode('circle');
  2068. }
  2069. };
  2070. var clickEllipse = function(){
  2071. if (toolButtonClick('#tool_ellipse')) {
  2072. svgCanvas.setMode('ellipse');
  2073. }
  2074. };
  2075. var clickFHEllipse = function(){
  2076. if (toolButtonClick('#tool_fhellipse')) {
  2077. svgCanvas.setMode('fhellipse');
  2078. }
  2079. };
  2080. var clickImage = function(){
  2081. if (toolButtonClick('#tool_image')) {
  2082. svgCanvas.setMode('image');
  2083. }
  2084. };
  2085. var clickZoom = function(){
  2086. if (toolButtonClick('#tool_zoom')) {
  2087. svgCanvas.setMode('zoom');
  2088. workarea.css('cursor', zoomInIcon);
  2089. }
  2090. };
  2091. var dblclickZoom = function(){
  2092. if (toolButtonClick('#tool_zoom')) {
  2093. zoomImage();
  2094. setSelectMode();
  2095. }
  2096. };
  2097. var clickText = function(){
  2098. if (toolButtonClick('#tool_text')) {
  2099. svgCanvas.setMode('text');
  2100. }
  2101. };
  2102. var clickPath = function(){
  2103. if (toolButtonClick('#tool_path')) {
  2104. svgCanvas.setMode('path');
  2105. }
  2106. };
  2107. // Delete is a contextual tool that only appears in the ribbon if
  2108. // an element has been selected
  2109. var deleteSelected = function() {
  2110. if (selectedElement != null || multiselected) {
  2111. svgCanvas.deleteSelectedElements();
  2112. }
  2113. };
  2114. var cutSelected = function() {
  2115. if (selectedElement != null || multiselected) {
  2116. svgCanvas.cutSelectedElements();
  2117. }
  2118. };
  2119. var copySelected = function() {
  2120. if (selectedElement != null || multiselected) {
  2121. svgCanvas.copySelectedElements();
  2122. }
  2123. };
  2124. var pasteInCenter = function() {
  2125. var zoom = svgCanvas.getZoom();
  2126. var x = (workarea[0].scrollLeft + workarea.width()/2)/zoom - svgCanvas.contentW;
  2127. var y = (workarea[0].scrollTop + workarea.height()/2)/zoom - svgCanvas.contentH;
  2128. svgCanvas.pasteElements('point', x, y);
  2129. }
  2130. var moveToTopSelected = function() {
  2131. if (selectedElement != null) {
  2132. svgCanvas.moveToTopSelectedElement();
  2133. }
  2134. };
  2135. var moveToBottomSelected = function() {
  2136. if (selectedElement != null) {
  2137. svgCanvas.moveToBottomSelectedElement();
  2138. }
  2139. };
  2140. var moveUpDownSelected = function(dir) {
  2141. if (selectedElement != null) {
  2142. svgCanvas.moveUpDownSelected(dir);
  2143. }
  2144. };
  2145. var convertToPath = function() {
  2146. if (selectedElement != null) {
  2147. svgCanvas.convertToPath();
  2148. }
  2149. }
  2150. var reorientPath = function() {
  2151. if (selectedElement != null) {
  2152. path.reorient();
  2153. }
  2154. }
  2155. var makeHyperlink = function() {
  2156. if (selectedElement != null || multiselected) {
  2157. $.prompt(uiStrings.notification.enterNewLinkURL, "http://", function(url) {
  2158. if(url) svgCanvas.makeHyperlink(url);
  2159. });
  2160. }
  2161. }
  2162. var moveSelected = function(dx,dy) {
  2163. if (selectedElement != null || multiselected) {
  2164. if(curConfig.gridSnapping) {
  2165. // Use grid snap value regardless of zoom level
  2166. var multi = svgCanvas.getZoom() * curConfig.snappingStep;
  2167. dx *= multi;
  2168. dy *= multi;
  2169. }
  2170. svgCanvas.moveSelectedElements(dx,dy);
  2171. }
  2172. };
  2173. var linkControlPoints = function() {
  2174. var linked = !$('#tool_node_link').hasClass('push_button_pressed');
  2175. if (linked)
  2176. $('#tool_node_link').addClass('push_button_pressed').removeClass('tool_button');
  2177. else
  2178. $('#tool_node_link').removeClass('push_button_pressed').addClass('tool_button');
  2179. path.linkControlPoints(linked);
  2180. }
  2181. var clonePathNode = function() {
  2182. if (path.getNodePoint()) {
  2183. path.clonePathNode();
  2184. }
  2185. };
  2186. var deletePathNode = function() {
  2187. if (path.getNodePoint()) {
  2188. path.deletePathNode();
  2189. }
  2190. };
  2191. var addSubPath = function() {
  2192. var button = $('#tool_add_subpath');
  2193. var sp = !button.hasClass('push_button_pressed');
  2194. if (sp) {
  2195. button.addClass('push_button_pressed').removeClass('tool_button');
  2196. } else {
  2197. button.removeClass('push_button_pressed').addClass('tool_button');
  2198. }
  2199. path.addSubPath(sp);
  2200. };
  2201. var opencloseSubPath = function() {
  2202. path.opencloseSubPath();
  2203. }
  2204. var selectNext = function() {
  2205. svgCanvas.cycleElement(1);
  2206. };
  2207. var selectPrev = function() {
  2208. svgCanvas.cycleElement(0);
  2209. };
  2210. var rotateSelected = function(cw,step) {
  2211. if (selectedElement == null || multiselected) return;
  2212. if(!cw) step *= -1;
  2213. var new_angle = $('#angle').val()*1 + step;
  2214. svgCanvas.setRotationAngle(new_angle);
  2215. updateContextPanel();
  2216. };
  2217. var clickClear = function(){
  2218. var dims = curConfig.dimensions;
  2219. $.confirm(uiStrings.notification.QwantToClear, function(ok) {
  2220. if(!ok) return;
  2221. setSelectMode();
  2222. svgCanvas.clear();
  2223. svgCanvas.setResolution(dims[0], dims[1]);
  2224. updateCanvas(true);
  2225. zoomImage();
  2226. populateLayers();
  2227. updateContextPanel();
  2228. prepPaints();
  2229. });
  2230. };
  2231. var clickBold = function(){
  2232. svgCanvas.setBold( !svgCanvas.getBold() );
  2233. updateContextPanel();
  2234. return false;
  2235. };
  2236. var clickItalic = function(){
  2237. svgCanvas.setItalic( !svgCanvas.getItalic() );
  2238. updateContextPanel();
  2239. return false;
  2240. };
  2241. var clickSave = function(){
  2242. // In the future, more options can be provided here
  2243. var saveOpts = {
  2244. 'images': curPrefs.img_save,
  2245. 'round_digits': 6
  2246. }
  2247. svgCanvas.save(saveOpts);
  2248. };
  2249. var clickExport = function() {
  2250. // Open placeholder window (prevents popup)
  2251. if(!customHandlers.pngsave) {
  2252. var str = uiStrings.notification.loadingImage;
  2253. exportWindow = window.open("data:text/html;charset=utf-8,<title>" + str + "<\/title><h1>" + str + "<\/h1>");
  2254. }
  2255. if(window.canvg) {
  2256. svgCanvas.rasterExport();
  2257. } else {
  2258. $.getScript('canvg/rgbcolor.js', function() {
  2259. $.getScript('canvg/canvg.js', function() {
  2260. svgCanvas.rasterExport();
  2261. });
  2262. });
  2263. }
  2264. }
  2265. // by default, svgCanvas.open() is a no-op.
  2266. // it is up to an extension mechanism (opera widget, etc)
  2267. // to call setCustomHandlers() which will make it do something
  2268. var clickOpen = function(){
  2269. svgCanvas.open();
  2270. };
  2271. var clickImport = function(){
  2272. };
  2273. var clickUndo = function(){
  2274. if (undoMgr.getUndoStackSize() > 0) {
  2275. undoMgr.undo();
  2276. populateLayers();
  2277. }
  2278. };
  2279. var clickRedo = function(){
  2280. if (undoMgr.getRedoStackSize() > 0) {
  2281. undoMgr.redo();
  2282. populateLayers();
  2283. }
  2284. };
  2285. var clickGroup = function(){
  2286. // group
  2287. if (multiselected) {
  2288. svgCanvas.groupSelectedElements();
  2289. }
  2290. // ungroup
  2291. else if(selectedElement){
  2292. svgCanvas.ungroupSelectedElement();
  2293. }
  2294. };
  2295. var clickClone = function(){
  2296. svgCanvas.cloneSelectedElements(20,20);
  2297. };
  2298. var clickAlign = function() {
  2299. var letter = this.id.replace('tool_align','').charAt(0);
  2300. svgCanvas.alignSelectedElements(letter, $('#align_relative_to').val());
  2301. };
  2302. var zoomImage = function(multiplier) {
  2303. var res = svgCanvas.getResolution();
  2304. multiplier = multiplier?res.zoom * multiplier:1;
  2305. // setResolution(res.w * multiplier, res.h * multiplier, true);
  2306. $('#zoom').val(multiplier * 100);
  2307. svgCanvas.setZoom(multiplier);
  2308. zoomDone();
  2309. updateCanvas(true);
  2310. };
  2311. var zoomDone = function() {
  2312. // updateBgImage();
  2313. updateWireFrame();
  2314. //updateCanvas(); // necessary?
  2315. }
  2316. var clickWireframe = function() {
  2317. var wf = !$('#tool_wireframe').hasClass('push_button_pressed');
  2318. if (wf)
  2319. $('#tool_wireframe').addClass('push_button_pressed').removeClass('tool_button');
  2320. else
  2321. $('#tool_wireframe').removeClass('push_button_pressed').addClass('tool_button');
  2322. workarea.toggleClass('wireframe');
  2323. if(supportsNonSS) return;
  2324. var wf_rules = $('#wireframe_rules');
  2325. if(!wf_rules.length) {
  2326. wf_rules = $('<style id="wireframe_rules"><\/style>').appendTo('head');
  2327. } else {
  2328. wf_rules.empty();
  2329. }
  2330. updateWireFrame();
  2331. }
  2332. var updateWireFrame = function() {
  2333. // Test support
  2334. if(supportsNonSS) return;
  2335. var rule = "#workarea.wireframe #svgcontent * { stroke-width: " + 1/svgCanvas.getZoom() + "px; }";
  2336. $('#wireframe_rules').text(workarea.hasClass('wireframe') ? rule : "");
  2337. }
  2338. var showSourceEditor = function(e, forSaving){
  2339. if (editingsource) return;
  2340. editingsource = true;
  2341. $('#save_output_btns').toggle(!!forSaving);
  2342. $('#tool_source_back').toggle(!forSaving);
  2343. var str = orig_source = svgCanvas.getSvgString();
  2344. $('#svg_source_textarea').val(str);
  2345. $('#svg_source_editor').fadeIn();
  2346. properlySourceSizeTextArea();
  2347. $('#svg_source_textarea').focus();
  2348. };
  2349. $('#svg_docprops_container, #svg_prefs_container').draggable({cancel:'button,fieldset', containment: 'window'});
  2350. var showDocProperties = function(){
  2351. if (docprops) return;
  2352. docprops = true;
  2353. // This selects the correct radio button by using the array notation
  2354. $('#image_save_opts input').val([curPrefs.img_save]);
  2355. // update resolution option with actual resolution
  2356. var res = svgCanvas.getResolution();
  2357. if(curConfig.baseUnit !== "px") {
  2358. res.w = svgedit.units.convertUnit(res.w) + curConfig.baseUnit;
  2359. res.h = svgedit.units.convertUnit(res.h) + curConfig.baseUnit;
  2360. }
  2361. $('#canvas_width').val(res.w);
  2362. $('#canvas_height').val(res.h);
  2363. $('#canvas_title').val(svgCanvas.getDocumentTitle());
  2364. $('#svg_docprops').show();
  2365. };
  2366. var showPreferences = function(){
  2367. if (preferences) return;
  2368. preferences = true;
  2369. $('#main_menu').hide();
  2370. // Update background color with current one
  2371. var blocks = $('#bg_blocks div');
  2372. var cur_bg = 'cur_background';
  2373. var canvas_bg = $.pref('bkgd_color');
  2374. var url = $.pref('bkgd_url');
  2375. // if(url) url = url[1];
  2376. blocks.each(function() {
  2377. var blk = $(this);
  2378. var is_bg = blk.css('background-color') == canvas_bg;
  2379. blk.toggleClass(cur_bg, is_bg);
  2380. if(is_bg) $('#canvas_bg_url').removeClass(cur_bg);
  2381. });
  2382. if(!canvas_bg) blocks.eq(0).addClass(cur_bg);
  2383. if(url) {
  2384. $('#canvas_bg_url').val(url);
  2385. }
  2386. $('grid_snapping_step').attr('value', curConfig.snappingStep);
  2387. if (curConfig.gridSnapping == true) {
  2388. $('#grid_snapping_on').attr('checked', 'checked');
  2389. } else {
  2390. $('#grid_snapping_on').removeAttr('checked');
  2391. }
  2392. $('#svg_prefs').show();
  2393. };
  2394. var properlySourceSizeTextArea = function(){
  2395. // TODO: remove magic numbers here and get values from CSS
  2396. var height = $('#svg_source_container').height() - 80;
  2397. $('#svg_source_textarea').css('height', height);
  2398. };
  2399. var saveSourceEditor = function(){
  2400. if (!editingsource) return;
  2401. var saveChanges = function() {
  2402. svgCanvas.clearSelection();
  2403. hideSourceEditor();
  2404. zoomImage();
  2405. populateLayers();
  2406. updateTitle();
  2407. prepPaints();
  2408. }
  2409. if (!svgCanvas.setSvgString($('#svg_source_textarea').val())) {
  2410. $.confirm(uiStrings.notification.QerrorsRevertToSource, function(ok) {
  2411. if(!ok) return false;
  2412. saveChanges();
  2413. });
  2414. } else {
  2415. saveChanges();
  2416. }
  2417. setSelectMode();
  2418. };
  2419. var updateTitle = function(title) {
  2420. title = title || svgCanvas.getDocumentTitle();
  2421. var new_title = orig_title + (title?': ' + title:'');
  2422. // Remove title update with current context info, isn't really necessary
  2423. // if(cur_context) {
  2424. // new_title = new_title + cur_context;
  2425. // }
  2426. $('title:first').text(new_title);
  2427. }
  2428. var saveDocProperties = function(){
  2429. // set title
  2430. var new_title = $('#canvas_title').val();
  2431. updateTitle(new_title);
  2432. svgCanvas.setDocumentTitle(new_title);
  2433. // update resolution
  2434. var width = $('#canvas_width'), w = width.val();
  2435. var height = $('#canvas_height'), h = height.val();
  2436. if(w != "fit" && !svgedit.units.isValidUnit('width', w)) {
  2437. $.alert(uiStrings.notification.invalidAttrValGiven);
  2438. width.parent().addClass('error');
  2439. return false;
  2440. }
  2441. width.parent().removeClass('error');
  2442. if(h != "fit" && !svgedit.units.isValidUnit('height', h)) {
  2443. $.alert(uiStrings.notification.invalidAttrValGiven);
  2444. height.parent().addClass('error');
  2445. return false;
  2446. }
  2447. height.parent().removeClass('error');
  2448. if(!svgCanvas.setResolution(w, h)) {
  2449. $.alert(uiStrings.notification.noContentToFitTo);
  2450. return false;
  2451. }
  2452. // set image save option
  2453. curPrefs.img_save = $('#image_save_opts :checked').val();
  2454. $.pref('img_save',curPrefs.img_save);
  2455. updateCanvas();
  2456. hideDocProperties();
  2457. };
  2458. var savePreferences = function() {
  2459. // set background
  2460. var color = $('#bg_blocks div.cur_background').css('background-color') || '#FFF';
  2461. setBackground(color, $('#canvas_bg_url').val());
  2462. // set language
  2463. var lang = $('#lang_select').val();
  2464. if(lang != curPrefs.lang) {
  2465. Editor.putLocale(lang);
  2466. }
  2467. // set icon size
  2468. setIconSize($('#iconsize').val());
  2469. // set grid setting
  2470. curConfig.gridSnapping = $('#grid_snapping_on')[0].checked;
  2471. curConfig.snappingStep = $('#grid_snapping_step').val();
  2472. curConfig.showRulers = $('#show_rulers')[0].checked;
  2473. $('#rulers').toggle(curConfig.showRulers);
  2474. if(curConfig.showRulers) updateRulers();
  2475. curConfig.baseUnit = $('#base_unit').val();
  2476. svgCanvas.setConfig(curConfig);
  2477. updateCanvas();
  2478. hidePreferences();
  2479. }
  2480. function setBackground(color, url) {
  2481. // if(color == curPrefs.bkgd_color && url == curPrefs.bkgd_url) return;
  2482. $.pref('bkgd_color', color);
  2483. $.pref('bkgd_url', url);
  2484. // This should be done in svgcanvas.js for the borderRect fill
  2485. svgCanvas.setBackground(color, url);
  2486. }
  2487. var setIcon = Editor.setIcon = function(elem, icon_id, forcedSize) {
  2488. var icon = (typeof icon_id === 'string') ? $.getSvgIcon(icon_id, true) : icon_id.clone();
  2489. if(!icon) {
  2490. console.log('NOTE: Icon image missing: ' + icon_id);
  2491. return;
  2492. }
  2493. $(elem).empty().append(icon);
  2494. }
  2495. var ua_prefix;
  2496. (ua_prefix = function() {
  2497. var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/;
  2498. var someScript = document.getElementsByTagName('script')[0];
  2499. for(var prop in someScript.style) {
  2500. if(regex.test(prop)) {
  2501. // test is faster than match, so it's better to perform
  2502. // that on the lot and match only when necessary
  2503. return prop.match(regex)[0];
  2504. }
  2505. }
  2506. // Nothing found so far?
  2507. if('WebkitOpacity' in someScript.style) return 'Webkit';
  2508. if('KhtmlOpacity' in someScript.style) return 'Khtml';
  2509. return '';
  2510. }());
  2511. var scaleElements = function(elems, scale) {
  2512. var prefix = '-' + ua_prefix.toLowerCase() + '-';
  2513. var sides = ['top', 'left', 'bottom', 'right'];
  2514. elems.each(function() {
  2515. // console.log('go', scale);
  2516. // Handled in CSS
  2517. // this.style[ua_prefix + 'Transform'] = 'scale(' + scale + ')';
  2518. var el = $(this);
  2519. var w = el.outerWidth() * (scale - 1);
  2520. var h = el.outerHeight() * (scale - 1);
  2521. var margins = {};
  2522. for(var i = 0; i < 4; i++) {
  2523. var s = sides[i];
  2524. var cur = el.data('orig_margin-' + s);
  2525. if(cur == null) {
  2526. cur = parseInt(el.css('margin-' + s));
  2527. // Cache the original margin
  2528. el.data('orig_margin-' + s, cur);
  2529. }
  2530. var val = cur * scale;
  2531. if(s === 'right') {
  2532. val += w;
  2533. } else if(s === 'bottom') {
  2534. val += h;
  2535. }
  2536. el.css('margin-' + s, val);
  2537. // el.css('outline', '1px solid red');
  2538. }
  2539. });
  2540. }
  2541. var setIconSize = Editor.setIconSize = function(size, force) {
  2542. if(size == curPrefs.size && !force) return;
  2543. // return;
  2544. // var elems = $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open');
  2545. console.log('size', size);
  2546. var sel_toscale = '#tools_top .toolset, #editor_panel > *, #history_panel > *,\
  2547. #main_button, #tools_left > *, #path_node_panel > *, #multiselected_panel > *,\
  2548. #g_panel > *, #tool_font_size > *, .tools_flyout';
  2549. var elems = $(sel_toscale);
  2550. var scale = 1;
  2551. if(typeof size == 'number') {
  2552. scale = size;
  2553. } else {
  2554. var icon_sizes = { s:.75, m:1, l:1.25, xl:1.5 };
  2555. scale = icon_sizes[size];
  2556. }
  2557. Editor.tool_scale = tool_scale = scale;
  2558. setFlyoutPositions();
  2559. // $('.tools_flyout').each(function() {
  2560. // var pos = $(this).position();
  2561. // console.log($(this), pos.left+(34 * scale));
  2562. // $(this).css({'left': pos.left+(34 * scale), 'top': pos.top+(77 * scale)});
  2563. // console.log('l', $(this).css('left'));
  2564. // });
  2565. // var scale = .75;//0.75;
  2566. var hidden_ps = elems.parents(':hidden');
  2567. hidden_ps.css('visibility', 'hidden').show();
  2568. scaleElements(elems, scale);
  2569. hidden_ps.css('visibility', 'visible').hide();
  2570. // console.timeEnd('elems');
  2571. // return;
  2572. $.pref('iconsize', size);
  2573. $('#iconsize').val(size);
  2574. // Change icon size
  2575. // $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open')
  2576. // .find('> svg, > img').each(function() {
  2577. // this.setAttribute('width',size_num);
  2578. // this.setAttribute('height',size_num);
  2579. // });
  2580. //
  2581. // $.resizeSvgIcons({
  2582. // '.flyout_arrow_horiz > svg, .flyout_arrow_horiz > img': size_num / 5,
  2583. // '#logo > svg, #logo > img': size_num * 1.3,
  2584. // '#tools_bottom .icon_label > *': (size_num === 16 ? 18 : size_num * .75)
  2585. // });
  2586. // if(size != 's') {
  2587. // $.resizeSvgIcons({'#layerbuttons svg, #layerbuttons img': size_num * .6});
  2588. // }
  2589. // Note that all rules will be prefixed with '#svg_editor' when parsed
  2590. var cssResizeRules = {
  2591. // ".tool_button,\
  2592. // .push_button,\
  2593. // .tool_button_current,\
  2594. // .push_button_pressed,\
  2595. // .disabled,\
  2596. // .icon_label,\
  2597. // .tools_flyout .tool_button": {
  2598. // 'width': {s: '16px', l: '32px', xl: '48px'},
  2599. // 'height': {s: '16px', l: '32px', xl: '48px'},
  2600. // 'padding': {s: '1px', l: '2px', xl: '3px'}
  2601. // },
  2602. // ".tool_sep": {
  2603. // 'height': {s: '16px', l: '32px', xl: '48px'},
  2604. // 'margin': {s: '2px 2px', l: '2px 5px', xl: '2px 8px'}
  2605. // },
  2606. // "#main_icon": {
  2607. // 'width': {s: '31px', l: '53px', xl: '75px'},
  2608. // 'height': {s: '22px', l: '42px', xl: '64px'}
  2609. // },
  2610. "#tools_top": {
  2611. 'left': 50,
  2612. 'height': 72
  2613. },
  2614. "#tools_left": {
  2615. 'width': 31,
  2616. 'top': 74
  2617. },
  2618. "div#workarea": {
  2619. 'left': 38,
  2620. 'top': 74
  2621. }
  2622. // "#tools_bottom": {
  2623. // 'left': {s: '27px', l: '46px', xl: '65px'},
  2624. // 'height': {s: '58px', l: '98px', xl: '145px'}
  2625. // },
  2626. // "#color_tools": {
  2627. // 'border-spacing': {s: '0 1px'},
  2628. // 'margin-top': {s: '-1px'}
  2629. // },
  2630. // "#color_tools .icon_label": {
  2631. // 'width': {l:'43px', xl: '60px'}
  2632. // },
  2633. // ".color_tool": {
  2634. // 'height': {s: '20px'}
  2635. // },
  2636. // "#tool_opacity": {
  2637. // 'top': {s: '1px'},
  2638. // 'height': {s: 'auto', l:'auto', xl:'auto'}
  2639. // },
  2640. // "#tools_top input, #tools_bottom input": {
  2641. // 'margin-top': {s: '2px', l: '4px', xl: '5px'},
  2642. // 'height': {s: 'auto', l: 'auto', xl: 'auto'},
  2643. // 'border': {s: '1px solid #555', l: 'auto', xl: 'auto'},
  2644. // 'font-size': {s: '.9em', l: '1.2em', xl: '1.4em'}
  2645. // },
  2646. // "#zoom_panel": {
  2647. // 'margin-top': {s: '3px', l: '4px', xl: '5px'}
  2648. // },
  2649. // "#copyright, #tools_bottom .label": {
  2650. // 'font-size': {l: '1.5em', xl: '2em'},
  2651. // 'line-height': {s: '15px'}
  2652. // },
  2653. // "#tools_bottom_2": {
  2654. // 'width': {l: '295px', xl: '355px'},
  2655. // 'top': {s: '4px'}
  2656. // },
  2657. // "#tools_top > div, #tools_top": {
  2658. // 'line-height': {s: '17px', l: '34px', xl: '50px'}
  2659. // },
  2660. // ".dropdown button": {
  2661. // 'height': {s: '18px', l: '34px', xl: '40px'},
  2662. // 'line-height': {s: '18px', l: '34px', xl: '40px'},
  2663. // 'margin-top': {s: '3px'}
  2664. // },
  2665. // "#tools_top label, #tools_bottom label": {
  2666. // 'font-size': {s: '1em', l: '1.5em', xl: '2em'},
  2667. // 'height': {s: '25px', l: '42px', xl: '64px'}
  2668. // },
  2669. // "div.toolset": {
  2670. // 'height': {s: '25px', l: '42px', xl: '64px'}
  2671. // },
  2672. // "#tool_bold, #tool_italic": {
  2673. // 'font-size': {s: '1.5em', l: '3em', xl: '4.5em'}
  2674. // },
  2675. // "#sidepanels": {
  2676. // 'top': {s: '50px', l: '88px', xl: '125px'},
  2677. // 'bottom': {s: '51px', l: '68px', xl: '65px'}
  2678. // },
  2679. // '#layerbuttons': {
  2680. // 'width': {l: '130px', xl: '175px'},
  2681. // 'height': {l: '24px', xl: '30px'}
  2682. // },
  2683. // '#layerlist': {
  2684. // 'width': {l: '128px', xl: '150px'}
  2685. // },
  2686. // '.layer_button': {
  2687. // 'width': {l: '19px', xl: '28px'},
  2688. // 'height': {l: '19px', xl: '28px'}
  2689. // },
  2690. // "input.spin-button": {
  2691. // 'background-image': {l: "url('images/spinbtn_updn_big.png')", xl: "url('images/spinbtn_updn_big.png')"},
  2692. // 'background-position': {l: '100% -5px', xl: '100% -2px'},
  2693. // 'padding-right': {l: '24px', xl: '24px' }
  2694. // },
  2695. // "input.spin-button.up": {
  2696. // 'background-position': {l: '100% -45px', xl: '100% -42px'}
  2697. // },
  2698. // "input.spin-button.down": {
  2699. // 'background-position': {l: '100% -85px', xl: '100% -82px'}
  2700. // },
  2701. // "#position_opts": {
  2702. // 'width': {all: (size_num*4) +'px'}
  2703. // }
  2704. };
  2705. var rule_elem = $('#tool_size_rules');
  2706. if(!rule_elem.length) {
  2707. rule_elem = $('<style id="tool_size_rules"><\/style>').appendTo('head');
  2708. } else {
  2709. rule_elem.empty();
  2710. }
  2711. if(size != 'm') {
  2712. var style_str = '';
  2713. $.each(cssResizeRules, function(selector, rules) {
  2714. selector = '#svg_editor ' + selector.replace(/,/g,', #svg_editor');
  2715. style_str += selector + '{';
  2716. $.each(rules, function(prop, values) {
  2717. if(typeof values === 'number') {
  2718. var val = (values * scale) + 'px';
  2719. } else if(values[size] || values.all) {
  2720. var val = (values[size] || values.all);
  2721. }
  2722. style_str += (prop + ':' + val + ';');
  2723. });
  2724. style_str += '}';
  2725. });
  2726. //this.style[ua_prefix + 'Transform'] = 'scale(' + scale + ')';
  2727. var prefix = '-' + ua_prefix.toLowerCase() + '-';
  2728. style_str += (sel_toscale + '{' + prefix + 'transform: scale(' + scale + ');}'
  2729. + ' #svg_editor div.toolset .toolset {' + prefix + 'transform: scale(1); margin: 1px !important;}' // Hack for markers
  2730. + ' #svg_editor .ui-slider {' + prefix + 'transform: scale(' + (1/scale) + ');}' // Hack for sliders
  2731. );
  2732. rule_elem.text(style_str);
  2733. }
  2734. setFlyoutPositions();
  2735. }
  2736. var cancelOverlays = function() {
  2737. $('#dialog_box').hide();
  2738. if (!editingsource && !docprops && !preferences) {
  2739. if(cur_context) {
  2740. svgCanvas.leaveContext();
  2741. }
  2742. return;
  2743. };
  2744. if (editingsource) {
  2745. if (orig_source !== $('#svg_source_textarea').val()) {
  2746. $.confirm(uiStrings.notification.QignoreSourceChanges, function(ok) {
  2747. if(ok) hideSourceEditor();
  2748. });
  2749. } else {
  2750. hideSourceEditor();
  2751. }
  2752. }
  2753. else if (docprops) {
  2754. hideDocProperties();
  2755. } else if (preferences) {
  2756. hidePreferences();
  2757. }
  2758. resetScrollPos();
  2759. };
  2760. var hideSourceEditor = function(){
  2761. $('#svg_source_editor').hide();
  2762. editingsource = false;
  2763. $('#svg_source_textarea').blur();
  2764. };
  2765. var hideDocProperties = function(){
  2766. $('#svg_docprops').hide();
  2767. $('#canvas_width,#canvas_height').removeAttr('disabled');
  2768. $('#resolution')[0].selectedIndex = 0;
  2769. $('#image_save_opts input').val([curPrefs.img_save]);
  2770. docprops = false;
  2771. };
  2772. var hidePreferences = function(){
  2773. $('#svg_prefs').hide();
  2774. preferences = false;
  2775. };
  2776. var win_wh = {width:$(window).width(), height:$(window).height()};
  2777. var resetScrollPos = $.noop, curScrollPos;
  2778. // Fix for Issue 781: Drawing area jumps to top-left corner on window resize (IE9)
  2779. if(svgedit.browser.isIE()) {
  2780. (function() {
  2781. resetScrollPos = function() {
  2782. if(workarea[0].scrollLeft === 0
  2783. && workarea[0].scrollTop === 0) {
  2784. workarea[0].scrollLeft = curScrollPos.left;
  2785. workarea[0].scrollTop = curScrollPos.top;
  2786. }
  2787. }
  2788. curScrollPos = {
  2789. left: workarea[0].scrollLeft,
  2790. top: workarea[0].scrollTop
  2791. };
  2792. $(window).resize(resetScrollPos);
  2793. svgEditor.ready(function() {
  2794. // TODO: Find better way to detect when to do this to minimize
  2795. // flickering effect
  2796. setTimeout(function() {
  2797. resetScrollPos();
  2798. }, 500);
  2799. });
  2800. workarea.scroll(function() {
  2801. curScrollPos = {
  2802. left: workarea[0].scrollLeft,
  2803. top: workarea[0].scrollTop
  2804. };
  2805. });
  2806. }());
  2807. }
  2808. $(window).resize(function(evt) {
  2809. if (editingsource) {
  2810. properlySourceSizeTextArea();
  2811. }
  2812. $.each(win_wh, function(type, val) {
  2813. var curval = $(window)[type]();
  2814. workarea[0]['scroll' + (type==='width'?'Left':'Top')] -= (curval - val)/2;
  2815. win_wh[type] = curval;
  2816. });
  2817. });
  2818. (function() {
  2819. workarea.scroll(function() {
  2820. // TODO: jQuery's scrollLeft/Top() wouldn't require a null check
  2821. if ($('#ruler_x').length != 0) {
  2822. $('#ruler_x')[0].scrollLeft = workarea[0].scrollLeft;
  2823. }
  2824. if ($('#ruler_y').length != 0) {
  2825. $('#ruler_y')[0].scrollTop = workarea[0].scrollTop;
  2826. }
  2827. });
  2828. }());
  2829. $('#url_notice').click(function() {
  2830. $.alert(this.title);
  2831. });
  2832. $('#change_image_url').click(promptImgURL);
  2833. function promptImgURL() {
  2834. var curhref = svgCanvas.getHref(selectedElement);
  2835. curhref = curhref.indexOf("data:") === 0?"":curhref;
  2836. $.prompt(uiStrings.notification.enterNewImgURL, curhref, function(url) {
  2837. if(url) setImageURL(url);
  2838. });
  2839. }
  2840. // added these event handlers for all the push buttons so they
  2841. // behave more like buttons being pressed-in and not images
  2842. (function() {
  2843. var toolnames = ['clear','open','save','source','delete','delete_multi','paste','clone','clone_multi','move_top','move_bottom'];
  2844. var all_tools = '';
  2845. var cur_class = 'tool_button_current';
  2846. $.each(toolnames, function(i,item) {
  2847. all_tools += '#tool_' + item + (i==toolnames.length-1?',':'');
  2848. });
  2849. $(all_tools).mousedown(function() {
  2850. $(this).addClass(cur_class);
  2851. }).bind('mousedown mouseout', function() {
  2852. $(this).removeClass(cur_class);
  2853. });
  2854. $('#tool_undo, #tool_redo').mousedown(function(){
  2855. if (!$(this).hasClass('disabled')) $(this).addClass(cur_class);
  2856. }).bind('mousedown mouseout',function(){
  2857. $(this).removeClass(cur_class);}
  2858. );
  2859. }());
  2860. // switch modifier key in tooltips if mac
  2861. // NOTE: This code is not used yet until I can figure out how to successfully bind ctrl/meta
  2862. // in Opera and Chrome
  2863. if (isMac && !window.opera) {
  2864. var shortcutButtons = ["tool_clear", "tool_save", "tool_source", "tool_undo", "tool_redo", "tool_clone"];
  2865. var i = shortcutButtons.length;
  2866. while (i--) {
  2867. var button = document.getElementById(shortcutButtons[i]);
  2868. if (button != null) {
  2869. var title = button.title;
  2870. var index = title.indexOf("Ctrl+");
  2871. button.title = [title.substr(0, index), "Cmd+", title.substr(index + 5)].join('');
  2872. }
  2873. }
  2874. }
  2875. // TODO: go back to the color boxes having white background-color and then setting
  2876. // background-image to none.png (otherwise partially transparent gradients look weird)
  2877. var colorPicker = function(elem) {
  2878. var picker = elem.attr('id') == 'stroke_color' ? 'stroke' : 'fill';
  2879. // var opacity = (picker == 'stroke' ? $('#stroke_opacity') : $('#fill_opacity'));
  2880. var paint = paintBox[picker].paint;
  2881. var title = (picker == 'stroke' ? 'Pick a Stroke Paint and Opacity' : 'Pick a Fill Paint and Opacity');
  2882. var was_none = false;
  2883. var pos = elem.position();
  2884. $("#color_picker")
  2885. .draggable({cancel:'.jGraduate_tabs, .jGraduate_colPick, .jGraduate_gradPick, .jPicker', containment: 'window'})
  2886. .css(curConfig.colorPickerCSS || {'left': pos.left, 'bottom': 50 - pos.top})
  2887. .jGraduate(
  2888. {
  2889. paint: paint,
  2890. window: { pickerTitle: title },
  2891. images: { clientPath: curConfig.jGraduatePath },
  2892. newstop: 'inverse'
  2893. },
  2894. function(p) {
  2895. paint = new $.jGraduate.Paint(p);
  2896. paintBox[picker].setPaint(paint);
  2897. svgCanvas.setPaint(picker, paint);
  2898. $('#color_picker').hide();
  2899. },
  2900. function(p) {
  2901. $('#color_picker').hide();
  2902. });
  2903. };
  2904. var updateToolButtonState = function() {
  2905. var bNoFill = (svgCanvas.getColor('fill') == 'none');
  2906. var bNoStroke = (svgCanvas.getColor('stroke') == 'none');
  2907. var buttonsNeedingStroke = [ '#tool_fhpath', '#tool_line' ];
  2908. var buttonsNeedingFillAndStroke = [ '#tools_rect .tool_button', '#tools_ellipse .tool_button', '#tool_text', '#tool_path'];
  2909. if (bNoStroke) {
  2910. for (var index in buttonsNeedingStroke) {
  2911. var button = buttonsNeedingStroke[index];
  2912. if ($(button).hasClass('tool_button_current')) {
  2913. clickSelect();
  2914. }
  2915. $(button).addClass('disabled');
  2916. }
  2917. }
  2918. else {
  2919. for (var index in buttonsNeedingStroke) {
  2920. var button = buttonsNeedingStroke[index];
  2921. $(button).removeClass('disabled');
  2922. }
  2923. }
  2924. if (bNoStroke && bNoFill) {
  2925. for (var index in buttonsNeedingFillAndStroke) {
  2926. var button = buttonsNeedingFillAndStroke[index];
  2927. if ($(button).hasClass('tool_button_current')) {
  2928. clickSelect();
  2929. }
  2930. $(button).addClass('disabled');
  2931. }
  2932. }
  2933. else {
  2934. for (var index in buttonsNeedingFillAndStroke) {
  2935. var button = buttonsNeedingFillAndStroke[index];
  2936. $(button).removeClass('disabled');
  2937. }
  2938. }
  2939. svgCanvas.runExtensions("toolButtonStateUpdate", {
  2940. nofill: bNoFill,
  2941. nostroke: bNoStroke
  2942. });
  2943. // Disable flyouts if all inside are disabled
  2944. $('.tools_flyout').each(function() {
  2945. var shower = $('#' + this.id + '_show');
  2946. var has_enabled = false;
  2947. $(this).children().each(function() {
  2948. if(!$(this).hasClass('disabled')) {
  2949. has_enabled = true;
  2950. }
  2951. });
  2952. shower.toggleClass('disabled', !has_enabled);
  2953. });
  2954. operaRepaint();
  2955. };
  2956. var PaintBox = function(container, type) {
  2957. var cur = curConfig[type === 'fill' ? 'initFill' : 'initStroke'];
  2958. // set up gradients to be used for the buttons
  2959. var svgdocbox = new DOMParser().parseFromString(
  2960. '<svg xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%"\
  2961. fill="#' + cur.color + '" opacity="' + cur.opacity + '"/>\
  2962. <defs><linearGradient id="gradbox_"/></defs></svg>', 'text/xml');
  2963. var docElem = svgdocbox.documentElement;
  2964. docElem = $(container)[0].appendChild(document.importNode(docElem, true));
  2965. docElem.setAttribute('width',16.5);
  2966. this.rect = docElem.firstChild;
  2967. this.defs = docElem.getElementsByTagName('defs')[0];
  2968. this.grad = this.defs.firstChild;
  2969. this.paint = new $.jGraduate.Paint({solidColor: cur.color});
  2970. this.type = type;
  2971. this.setPaint = function(paint, apply) {
  2972. this.paint = paint;
  2973. var fillAttr = "none";
  2974. var ptype = paint.type;
  2975. var opac = paint.alpha / 100;
  2976. switch ( ptype ) {
  2977. case 'solidColor':
  2978. fillAttr = "#" + paint[ptype];
  2979. break;
  2980. case 'linearGradient':
  2981. case 'radialGradient':
  2982. this.defs.removeChild(this.grad);
  2983. this.grad = this.defs.appendChild(paint[ptype]);
  2984. var id = this.grad.id = 'gradbox_' + this.type;
  2985. fillAttr = "url(#" + id + ')';
  2986. }
  2987. this.rect.setAttribute('fill', fillAttr);
  2988. this.rect.setAttribute('opacity', opac);
  2989. if(apply) {
  2990. svgCanvas.setColor(this.type, paintColor, true);
  2991. svgCanvas.setPaintOpacity(this.type, paintOpacity, true);
  2992. }
  2993. }
  2994. this.update = function(apply) {
  2995. if(!selectedElement) return;
  2996. var type = this.type;
  2997. switch ( selectedElement.tagName ) {
  2998. case 'use':
  2999. case 'image':
  3000. case 'foreignObject':
  3001. // These elements don't have fill or stroke, so don't change
  3002. // the current value
  3003. return;
  3004. case 'g':
  3005. case 'a':
  3006. var gPaint = null;
  3007. var childs = selectedElement.getElementsByTagName('*');
  3008. for(var i = 0, len = childs.length; i < len; i++) {
  3009. var elem = childs[i];
  3010. var p = elem.getAttribute(type);
  3011. if(i === 0) {
  3012. gPaint = p;
  3013. } else if(gPaint !== p) {
  3014. gPaint = null;
  3015. break;
  3016. }
  3017. }
  3018. if(gPaint === null) {
  3019. // No common color, don't update anything
  3020. var paintColor = null;
  3021. return;
  3022. }
  3023. var paintColor = gPaint;
  3024. var paintOpacity = 1;
  3025. break;
  3026. default:
  3027. var paintOpacity = parseFloat(selectedElement.getAttribute(type + "-opacity"));
  3028. if (isNaN(paintOpacity)) {
  3029. paintOpacity = 1.0;
  3030. }
  3031. var defColor = type === "fill" ? "black" : "none";
  3032. var paintColor = selectedElement.getAttribute(type) || defColor;
  3033. }
  3034. if(apply) {
  3035. svgCanvas.setColor(type, paintColor, true);
  3036. svgCanvas.setPaintOpacity(type, paintOpacity, true);
  3037. }
  3038. paintOpacity *= 100;
  3039. var paint = getPaint(paintColor, paintOpacity, type);
  3040. // update the rect inside #fill_color/#stroke_color
  3041. this.setPaint(paint);
  3042. }
  3043. this.prep = function() {
  3044. var ptype = this.paint.type;
  3045. switch ( ptype ) {
  3046. case 'linearGradient':
  3047. case 'radialGradient':
  3048. var paint = new $.jGraduate.Paint({copy: this.paint});
  3049. svgCanvas.setPaint(type, paint);
  3050. }
  3051. }
  3052. };
  3053. paintBox.fill = new PaintBox('#fill_color', 'fill');
  3054. paintBox.stroke = new PaintBox('#stroke_color', 'stroke');
  3055. $('#stroke_width').val(curConfig.initStroke.width);
  3056. $('#group_opacity').val(curConfig.initOpacity * 100);
  3057. // Use this SVG elem to test vectorEffect support
  3058. var test_el = paintBox.fill.rect.cloneNode(false);
  3059. test_el.setAttribute('style','vector-effect:non-scaling-stroke');
  3060. var supportsNonSS = (test_el.style.vectorEffect === 'non-scaling-stroke');
  3061. test_el.removeAttribute('style');
  3062. var svgdocbox = paintBox.fill.rect.ownerDocument;
  3063. // Use this to test support for blur element. Seems to work to test support in Webkit
  3064. var blur_test = svgdocbox.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur');
  3065. if(typeof blur_test.stdDeviationX === "undefined") {
  3066. $('#tool_blur').hide();
  3067. }
  3068. $(blur_test).remove();
  3069. // Test for zoom icon support
  3070. (function() {
  3071. var pre = '-' + ua_prefix.toLowerCase() + '-zoom-';
  3072. var zoom = pre + 'in';
  3073. workarea.css('cursor', zoom);
  3074. if(workarea.css('cursor') === zoom) {
  3075. zoomInIcon = zoom;
  3076. zoomOutIcon = pre + 'out';
  3077. }
  3078. workarea.css('cursor', 'auto');
  3079. }());
  3080. // Test for embedImage support (use timeout to not interfere with page load)
  3081. setTimeout(function() {
  3082. svgCanvas.embedImage('images/logo.png', function(datauri) {
  3083. if(!datauri) {
  3084. // Disable option
  3085. $('#image_save_opts [value=embed]').attr('disabled','disabled');
  3086. $('#image_save_opts input').val(['ref']);
  3087. curPrefs.img_save = 'ref';
  3088. $('#image_opt_embed').css('color','#666').attr('title',uiStrings.notification.featNotSupported);
  3089. }
  3090. });
  3091. },1000);
  3092. $('#fill_color, #tool_fill .icon_label').click(function(){
  3093. colorPicker($('#fill_color'));
  3094. updateToolButtonState();
  3095. });
  3096. $('#stroke_color, #tool_stroke .icon_label').click(function(){
  3097. colorPicker($('#stroke_color'));
  3098. updateToolButtonState();
  3099. });
  3100. $('#group_opacityLabel').click(function() {
  3101. $('#opacity_dropdown button').mousedown();
  3102. $(window).mouseup();
  3103. });
  3104. $('#zoomLabel').click(function() {
  3105. $('#zoom_dropdown button').mousedown();
  3106. $(window).mouseup();
  3107. });
  3108. $('#tool_move_top').mousedown(function(evt){
  3109. $('#tools_stacking').show();
  3110. evt.preventDefault();
  3111. });
  3112. $('.layer_button').mousedown(function() {
  3113. $(this).addClass('layer_buttonpressed');
  3114. }).mouseout(function() {
  3115. $(this).removeClass('layer_buttonpressed');
  3116. }).mouseup(function() {
  3117. $(this).removeClass('layer_buttonpressed');
  3118. });
  3119. $('.push_button').mousedown(function() {
  3120. if (!$(this).hasClass('disabled')) {
  3121. $(this).addClass('push_button_pressed').removeClass('push_button');
  3122. }
  3123. }).mouseout(function() {
  3124. $(this).removeClass('push_button_pressed').addClass('push_button');
  3125. }).mouseup(function() {
  3126. $(this).removeClass('push_button_pressed').addClass('push_button');
  3127. });
  3128. $('#layer_new').click(function() {
  3129. var i = svgCanvas.getCurrentDrawing().getNumLayers();
  3130. do {
  3131. var uniqName = uiStrings.layers.layer + " " + ++i;
  3132. } while(svgCanvas.getCurrentDrawing().hasLayer(uniqName));
  3133. $.prompt(uiStrings.notification.enterUniqueLayerName,uniqName, function(newName) {
  3134. if (!newName) return;
  3135. if (svgCanvas.getCurrentDrawing().hasLayer(newName)) {
  3136. $.alert(uiStrings.notification.dupeLayerName);
  3137. return;
  3138. }
  3139. svgCanvas.createLayer(newName);
  3140. updateContextPanel();
  3141. populateLayers();
  3142. });
  3143. });
  3144. function deleteLayer() {
  3145. if (svgCanvas.deleteCurrentLayer()) {
  3146. updateContextPanel();
  3147. populateLayers();
  3148. // This matches what SvgCanvas does
  3149. // TODO: make this behavior less brittle (svg-editor should get which
  3150. // layer is selected from the canvas and then select that one in the UI)
  3151. $('#layerlist tr.layer').removeClass("layersel");
  3152. $('#layerlist tr.layer:first').addClass("layersel");
  3153. }
  3154. }
  3155. function cloneLayer() {
  3156. var name = svgCanvas.getCurrentDrawing().getCurrentLayerName() + ' copy';
  3157. $.prompt(uiStrings.notification.enterUniqueLayerName, name, function(newName) {
  3158. if (!newName) return;
  3159. if (svgCanvas.getCurrentDrawing().hasLayer(newName)) {
  3160. $.alert(uiStrings.notification.dupeLayerName);
  3161. return;
  3162. }
  3163. svgCanvas.cloneLayer(newName);
  3164. updateContextPanel();
  3165. populateLayers();
  3166. });
  3167. }
  3168. function mergeLayer() {
  3169. if($('#layerlist tr.layersel').index() == svgCanvas.getCurrentDrawing().getNumLayers()-1) return;
  3170. svgCanvas.mergeLayer();
  3171. updateContextPanel();
  3172. populateLayers();
  3173. }
  3174. function moveLayer(pos) {
  3175. var curIndex = $('#layerlist tr.layersel').index();
  3176. var total = svgCanvas.getCurrentDrawing().getNumLayers();
  3177. if(curIndex > 0 || curIndex < total-1) {
  3178. curIndex += pos;
  3179. svgCanvas.setCurrentLayerPosition(total-curIndex-1);
  3180. populateLayers();
  3181. }
  3182. }
  3183. $('#layer_delete').click(deleteLayer);
  3184. $('#layer_up').click(function() {
  3185. moveLayer(-1);
  3186. });
  3187. $('#layer_down').click(function() {
  3188. moveLayer(1);
  3189. });
  3190. $('#layer_rename').click(function() {
  3191. var curIndex = $('#layerlist tr.layersel').prevAll().length;
  3192. var oldName = $('#layerlist tr.layersel td.layername').text();
  3193. $.prompt(uiStrings.notification.enterNewLayerName,"", function(newName) {
  3194. if (!newName) return;
  3195. if (oldName == newName || svgCanvas.getCurrentDrawing().hasLayer(newName)) {
  3196. $.alert(uiStrings.notification.layerHasThatName);
  3197. return;
  3198. }
  3199. svgCanvas.renameCurrentLayer(newName);
  3200. populateLayers();
  3201. });
  3202. });
  3203. var SIDEPANEL_MAXWIDTH = 300;
  3204. var SIDEPANEL_OPENWIDTH = 150;
  3205. var sidedrag = -1, sidedragging = false, allowmove = false;
  3206. var resizePanel = function(evt) {
  3207. if (!allowmove) return;
  3208. if (sidedrag == -1) return;
  3209. sidedragging = true;
  3210. var deltax = sidedrag - evt.pageX;
  3211. var sidepanels = $('#sidepanels');
  3212. var sidewidth = parseInt(sidepanels.css('width'));
  3213. if (sidewidth+deltax > SIDEPANEL_MAXWIDTH) {
  3214. deltax = SIDEPANEL_MAXWIDTH - sidewidth;
  3215. sidewidth = SIDEPANEL_MAXWIDTH;
  3216. }
  3217. else if (sidewidth+deltax < 2) {
  3218. deltax = 2 - sidewidth;
  3219. sidewidth = 2;
  3220. }
  3221. if (deltax == 0) return;
  3222. sidedrag -= deltax;
  3223. var layerpanel = $('#layerpanel');
  3224. workarea.css('right', parseInt(workarea.css('right'))+deltax);
  3225. sidepanels.css('width', parseInt(sidepanels.css('width'))+deltax);
  3226. layerpanel.css('width', parseInt(layerpanel.css('width'))+deltax);
  3227. var ruler_x = $('#ruler_x');
  3228. ruler_x.css('right', parseInt(ruler_x.css('right')) + deltax);
  3229. }
  3230. $('#sidepanel_handle')
  3231. .mousedown(function(evt) {
  3232. sidedrag = evt.pageX;
  3233. $(window).mousemove(resizePanel);
  3234. allowmove = false;
  3235. // Silly hack for Chrome, which always runs mousemove right after mousedown
  3236. setTimeout(function() {
  3237. allowmove = true;
  3238. }, 20);
  3239. })
  3240. .mouseup(function(evt) {
  3241. if (!sidedragging) toggleSidePanel();
  3242. sidedrag = -1;
  3243. sidedragging = false;
  3244. });
  3245. $(window).mouseup(function() {
  3246. sidedrag = -1;
  3247. sidedragging = false;
  3248. $('#svg_editor').unbind('mousemove', resizePanel);
  3249. });
  3250. // if width is non-zero, then fully close it, otherwise fully open it
  3251. // the optional close argument forces the side panel closed
  3252. var toggleSidePanel = function(close){
  3253. var w = parseInt($('#sidepanels').css('width'));
  3254. var deltax = (w > 2 || close ? 2 : SIDEPANEL_OPENWIDTH) - w;
  3255. var sidepanels = $('#sidepanels');
  3256. var layerpanel = $('#layerpanel');
  3257. var ruler_x = $('#ruler_x');
  3258. workarea.css('right', parseInt(workarea.css('right')) + deltax);
  3259. sidepanels.css('width', parseInt(sidepanels.css('width')) + deltax);
  3260. layerpanel.css('width', parseInt(layerpanel.css('width')) + deltax);
  3261. ruler_x.css('right', parseInt(ruler_x.css('right')) + deltax);
  3262. };
  3263. // this function highlights the layer passed in (by fading out the other layers)
  3264. // if no layer is passed in, this function restores the other layers
  3265. var toggleHighlightLayer = function(layerNameToHighlight) {
  3266. var curNames = new Array(svgCanvas.getCurrentDrawing().getNumLayers());
  3267. for (var i = 0; i < curNames.length; ++i) { curNames[i] = svgCanvas.getCurrentDrawing().getLayerName(i); }
  3268. if (layerNameToHighlight) {
  3269. for (var i = 0; i < curNames.length; ++i) {
  3270. if (curNames[i] != layerNameToHighlight) {
  3271. svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 0.5);
  3272. }
  3273. }
  3274. }
  3275. else {
  3276. for (var i = 0; i < curNames.length; ++i) {
  3277. svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 1.0);
  3278. }
  3279. }
  3280. };
  3281. var populateLayers = function(){
  3282. var layerlist = $('#layerlist tbody');
  3283. var selLayerNames = $('#selLayerNames');
  3284. layerlist.empty();
  3285. selLayerNames.empty();
  3286. var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName();
  3287. var layer = svgCanvas.getCurrentDrawing().getNumLayers();
  3288. var icon = $.getSvgIcon('eye');
  3289. // we get the layers in the reverse z-order (the layer rendered on top is listed first)
  3290. while (layer--) {
  3291. var name = svgCanvas.getCurrentDrawing().getLayerName(layer);
  3292. // contenteditable=\"true\"
  3293. var appendstr = "<tr class=\"layer";
  3294. if (name == currentLayerName) {
  3295. appendstr += " layersel"
  3296. }
  3297. appendstr += "\">";
  3298. if (svgCanvas.getCurrentDrawing().getLayerVisibility(name)) {
  3299. appendstr += "<td class=\"layervis\"/><td class=\"layername\" >" + name + "</td></tr>";
  3300. }
  3301. else {
  3302. appendstr += "<td class=\"layervis layerinvis\"/><td class=\"layername\" >" + name + "</td></tr>";
  3303. }
  3304. layerlist.append(appendstr);
  3305. selLayerNames.append("<option value=\"" + name + "\">" + name + "</option>");
  3306. }
  3307. if(icon !== undefined) {
  3308. var copy = icon.clone();
  3309. $('td.layervis',layerlist).append(icon.clone());
  3310. $.resizeSvgIcons({'td.layervis .svg_icon':14});
  3311. }
  3312. // handle selection of layer
  3313. $('#layerlist td.layername')
  3314. .mouseup(function(evt){
  3315. $('#layerlist tr.layer').removeClass("layersel");
  3316. var row = $(this.parentNode);
  3317. row.addClass("layersel");
  3318. svgCanvas.setCurrentLayer(this.textContent);
  3319. evt.preventDefault();
  3320. })
  3321. .mouseover(function(evt){
  3322. $(this).css({"font-style": "italic", "color":"blue"});
  3323. toggleHighlightLayer(this.textContent);
  3324. })
  3325. .mouseout(function(evt){
  3326. $(this).css({"font-style": "normal", "color":"black"});
  3327. toggleHighlightLayer();
  3328. });
  3329. $('#layerlist td.layervis').click(function(evt){
  3330. var row = $(this.parentNode).prevAll().length;
  3331. var name = $('#layerlist tr.layer:eq(' + row + ') td.layername').text();
  3332. var vis = $(this).hasClass('layerinvis');
  3333. svgCanvas.setLayerVisibility(name, vis);
  3334. if (vis) {
  3335. $(this).removeClass('layerinvis');
  3336. }
  3337. else {
  3338. $(this).addClass('layerinvis');
  3339. }
  3340. });
  3341. // if there were too few rows, let's add a few to make it not so lonely
  3342. var num = 5 - $('#layerlist tr.layer').size();
  3343. while (num-- > 0) {
  3344. // FIXME: there must a better way to do this
  3345. layerlist.append("<tr><td style=\"color:white\">_</td><td/></tr>");
  3346. }
  3347. };
  3348. populateLayers();
  3349. // function changeResolution(x,y) {
  3350. // var zoom = svgCanvas.getResolution().zoom;
  3351. // setResolution(x * zoom, y * zoom);
  3352. // }
  3353. var centerCanvas = function() {
  3354. // this centers the canvas vertically in the workarea (horizontal handled in CSS)
  3355. workarea.css('line-height', workarea.height() + 'px');
  3356. };
  3357. $(window).bind('load resize', centerCanvas);
  3358. function stepFontSize(elem, step) {
  3359. var orig_val = elem.value-0;
  3360. var sug_val = orig_val + step;
  3361. var increasing = sug_val >= orig_val;
  3362. if(step === 0) return orig_val;
  3363. if(orig_val >= 24) {
  3364. if(increasing) {
  3365. return Math.round(orig_val * 1.1);
  3366. } else {
  3367. return Math.round(orig_val / 1.1);
  3368. }
  3369. } else if(orig_val <= 1) {
  3370. if(increasing) {
  3371. return orig_val * 2;
  3372. } else {
  3373. return orig_val / 2;
  3374. }
  3375. } else {
  3376. return sug_val;
  3377. }
  3378. }
  3379. function stepZoom(elem, step) {
  3380. var orig_val = elem.value-0;
  3381. if(orig_val === 0) return 100;
  3382. var sug_val = orig_val + step;
  3383. if(step === 0) return orig_val;
  3384. if(orig_val >= 100) {
  3385. return sug_val;
  3386. } else {
  3387. if(sug_val >= orig_val) {
  3388. return orig_val * 2;
  3389. } else {
  3390. return orig_val / 2;
  3391. }
  3392. }
  3393. }
  3394. // function setResolution(w, h, center) {
  3395. // updateCanvas();
  3396. // // w-=0; h-=0;
  3397. // // $('#svgcanvas').css( { 'width': w, 'height': h } );
  3398. // // $('#canvas_width').val(w);
  3399. // // $('#canvas_height').val(h);
  3400. // //
  3401. // // if(center) {
  3402. // // var w_area = workarea;
  3403. // // var scroll_y = h/2 - w_area.height()/2;
  3404. // // var scroll_x = w/2 - w_area.width()/2;
  3405. // // w_area[0].scrollTop = scroll_y;
  3406. // // w_area[0].scrollLeft = scroll_x;
  3407. // // }
  3408. // }
  3409. $('#resolution').change(function(){
  3410. var wh = $('#canvas_width,#canvas_height');
  3411. if(!this.selectedIndex) {
  3412. if($('#canvas_width').val() == 'fit') {
  3413. wh.removeAttr("disabled").val(100);
  3414. }
  3415. } else if(this.value == 'content') {
  3416. wh.val('fit').attr("disabled","disabled");
  3417. } else {
  3418. var dims = this.value.split('x');
  3419. $('#canvas_width').val(dims[0]);
  3420. $('#canvas_height').val(dims[1]);
  3421. wh.removeAttr("disabled");
  3422. }
  3423. });
  3424. //Prevent browser from erroneously repopulating fields
  3425. $('input,select').attr("autocomplete","off");
  3426. // Associate all button actions as well as non-button keyboard shortcuts
  3427. var Actions = function() {
  3428. // sel:'selector', fn:function, evt:'event', key:[key, preventDefault, NoDisableInInput]
  3429. var tool_buttons = [
  3430. {sel:'#tool_select', fn: clickSelect, evt: 'click', key: ['V', true]},
  3431. {sel:'#tool_fhpath', fn: clickFHPath, evt: 'click', key: ['Q', true]},
  3432. {sel:'#tool_line', fn: clickLine, evt: 'click', key: ['L', true]},
  3433. {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: ['R', true], parent: '#tools_rect', icon: 'rect'},
  3434. {sel:'#tool_square', fn: clickSquare, evt: 'mouseup', parent: '#tools_rect', icon: 'square'},
  3435. {sel:'#tool_fhrect', fn: clickFHRect, evt: 'mouseup', parent: '#tools_rect', icon: 'fh_rect'},
  3436. {sel:'#tool_ellipse', fn: clickEllipse, evt: 'mouseup', key: ['E', true], parent: '#tools_ellipse', icon: 'ellipse'},
  3437. {sel:'#tool_circle', fn: clickCircle, evt: 'mouseup', parent: '#tools_ellipse', icon: 'circle'},
  3438. {sel:'#tool_fhellipse', fn: clickFHEllipse, evt: 'mouseup', parent: '#tools_ellipse', icon: 'fh_ellipse'},
  3439. {sel:'#tool_path', fn: clickPath, evt: 'click', key: ['P', true]},
  3440. {sel:'#tool_text', fn: clickText, evt: 'click', key: ['T', true]},
  3441. {sel:'#tool_image', fn: clickImage, evt: 'mouseup'},
  3442. {sel:'#tool_zoom', fn: clickZoom, evt: 'mouseup', key: ['Z', true]},
  3443. {sel:'#tool_clear', fn: clickClear, evt: 'mouseup', key: ['N', true]},
  3444. {sel:'#tool_save', fn: function() { editingsource?saveSourceEditor():clickSave()}, evt: 'mouseup', key: ['S', true]},
  3445. {sel:'#tool_export', fn: clickExport, evt: 'mouseup'},
  3446. {sel:'#tool_open', fn: clickOpen, evt: 'mouseup', key: ['O', true]},
  3447. {sel:'#tool_import', fn: clickImport, evt: 'mouseup'},
  3448. {sel:'#tool_source', fn: showSourceEditor, evt: 'click', key: ['U', true]},
  3449. {sel:'#tool_wireframe', fn: clickWireframe, evt: 'click', key: ['F', true]},
  3450. {sel:'#tool_source_cancel,#svg_source_overlay,#tool_docprops_cancel,#tool_prefs_cancel', fn: cancelOverlays, evt: 'click', key: ['esc', false, false], hidekey: true},
  3451. {sel:'#tool_source_save', fn: saveSourceEditor, evt: 'click'},
  3452. {sel:'#tool_docprops_save', fn: saveDocProperties, evt: 'click'},
  3453. {sel:'#tool_docprops', fn: showDocProperties, evt: 'mouseup'},
  3454. {sel:'#tool_prefs_save', fn: savePreferences, evt: 'click'},
  3455. {sel:'#tool_prefs_option', fn: function() {showPreferences();return false}, evt: 'mouseup'},
  3456. {sel:'#tool_delete,#tool_delete_multi', fn: deleteSelected, evt: 'click', key: ['del/backspace', true]},
  3457. {sel:'#tool_reorient', fn: reorientPath, evt: 'click'},
  3458. {sel:'#tool_node_link', fn: linkControlPoints, evt: 'click'},
  3459. {sel:'#tool_node_clone', fn: clonePathNode, evt: 'click'},
  3460. {sel:'#tool_node_delete', fn: deletePathNode, evt: 'click'},
  3461. {sel:'#tool_openclose_path', fn: opencloseSubPath, evt: 'click'},
  3462. {sel:'#tool_add_subpath', fn: addSubPath, evt: 'click'},
  3463. {sel:'#tool_move_top', fn: moveToTopSelected, evt: 'click', key: 'ctrl+shift+]'},
  3464. {sel:'#tool_move_bottom', fn: moveToBottomSelected, evt: 'click', key: 'ctrl+shift+['},
  3465. {sel:'#tool_topath', fn: convertToPath, evt: 'click'},
  3466. {sel:'#tool_make_link,#tool_make_link_multi', fn: makeHyperlink, evt: 'click'},
  3467. {sel:'#tool_undo', fn: clickUndo, evt: 'click', key: ['Z', true]},
  3468. {sel:'#tool_redo', fn: clickRedo, evt: 'click', key: ['Y', true]},
  3469. {sel:'#tool_clone,#tool_clone_multi', fn: clickClone, evt: 'click', key: ['D', true]},
  3470. {sel:'#tool_group', fn: clickGroup, evt: 'click', key: ['G', true]},
  3471. {sel:'#tool_ungroup', fn: clickGroup, evt: 'click'},
  3472. {sel:'#tool_unlink_use', fn: clickGroup, evt: 'click'},
  3473. {sel:'[id^=tool_align]', fn: clickAlign, evt: 'click'},
  3474. // these two lines are required to make Opera work properly with the flyout mechanism
  3475. // {sel:'#tools_rect_show', fn: clickRect, evt: 'click'},
  3476. // {sel:'#tools_ellipse_show', fn: clickEllipse, evt: 'click'},
  3477. {sel:'#tool_bold', fn: clickBold, evt: 'mousedown'},
  3478. {sel:'#tool_italic', fn: clickItalic, evt: 'mousedown'},
  3479. {sel:'#sidepanel_handle', fn: toggleSidePanel, key: ['X']},
  3480. {sel:'#copy_save_done', fn: cancelOverlays, evt: 'click'},
  3481. // Shortcuts not associated with buttons
  3482. {key: 'ctrl+left', fn: function(){rotateSelected(0,1)}},
  3483. {key: 'ctrl+right', fn: function(){rotateSelected(1,1)}},
  3484. {key: 'ctrl+shift+left', fn: function(){rotateSelected(0,5)}},
  3485. {key: 'ctrl+shift+right', fn: function(){rotateSelected(1,5)}},
  3486. {key: 'shift+O', fn: selectPrev},
  3487. {key: 'shift+P', fn: selectNext},
  3488. {key: [modKey+'up', true], fn: function(){zoomImage(2);}},
  3489. {key: [modKey+'down', true], fn: function(){zoomImage(.5);}},
  3490. {key: [modKey+']', true], fn: function(){moveUpDownSelected('Up');}},
  3491. {key: [modKey+'[', true], fn: function(){moveUpDownSelected('Down');}},
  3492. {key: ['up', true], fn: function(){moveSelected(0,-1);}},
  3493. {key: ['down', true], fn: function(){moveSelected(0,1);}},
  3494. {key: ['left', true], fn: function(){moveSelected(-1,0);}},
  3495. {key: ['right', true], fn: function(){moveSelected(1,0);}},
  3496. {key: 'shift+up', fn: function(){moveSelected(0,-10)}},
  3497. {key: 'shift+down', fn: function(){moveSelected(0,10)}},
  3498. {key: 'shift+left', fn: function(){moveSelected(-10,0)}},
  3499. {key: 'shift+right', fn: function(){moveSelected(10,0)}},
  3500. {key: ['alt+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-1)}},
  3501. {key: ['alt+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,1)}},
  3502. {key: ['alt+left', true], fn: function(){svgCanvas.cloneSelectedElements(-1,0)}},
  3503. {key: ['alt+right', true], fn: function(){svgCanvas.cloneSelectedElements(1,0)}},
  3504. {key: ['alt+shift+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-10)}},
  3505. {key: ['alt+shift+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,10)}},
  3506. {key: ['alt+shift+left', true], fn: function(){svgCanvas.cloneSelectedElements(-10,0)}},
  3507. {key: ['alt+shift+right', true], fn: function(){svgCanvas.cloneSelectedElements(10,0)}},
  3508. {key: 'A', fn: function(){svgCanvas.selectAllInCurrentLayer();}},
  3509. // Standard shortcuts
  3510. {key: modKey+'z', fn: clickUndo},
  3511. {key: modKey + 'shift+z', fn: clickRedo},
  3512. {key: modKey + 'y', fn: clickRedo},
  3513. {key: modKey+'x', fn: cutSelected},
  3514. {key: modKey+'c', fn: copySelected},
  3515. {key: modKey+'v', fn: pasteInCenter}
  3516. ];
  3517. // Tooltips not directly associated with a single function
  3518. var key_assocs = {
  3519. '4/Shift+4': '#tools_rect_show',
  3520. '5/Shift+5': '#tools_ellipse_show'
  3521. };
  3522. return {
  3523. setAll: function() {
  3524. var flyouts = {};
  3525. $.each(tool_buttons, function(i, opts) {
  3526. // Bind function to button
  3527. if(opts.sel) {
  3528. var btn = $(opts.sel);
  3529. if (btn.length == 0) return true; // Skip if markup does not exist
  3530. if(opts.evt) {
  3531. btn[opts.evt](opts.fn);
  3532. }
  3533. // Add to parent flyout menu, if able to be displayed
  3534. if(opts.parent && $(opts.parent + '_show').length != 0) {
  3535. var f_h = $(opts.parent);
  3536. if(!f_h.length) {
  3537. f_h = makeFlyoutHolder(opts.parent.substr(1));
  3538. }
  3539. f_h.append(btn);
  3540. if(!$.isArray(flyouts[opts.parent])) {
  3541. flyouts[opts.parent] = [];
  3542. }
  3543. flyouts[opts.parent].push(opts);
  3544. }
  3545. }
  3546. // Bind function to shortcut key
  3547. if(opts.key) {
  3548. // Set shortcut based on options
  3549. var keyval, shortcut = '', disInInp = true, fn = opts.fn, pd = false;
  3550. if($.isArray(opts.key)) {
  3551. keyval = opts.key[0];
  3552. if(opts.key.length > 1) pd = opts.key[1];
  3553. if(opts.key.length > 2) disInInp = opts.key[2];
  3554. } else {
  3555. keyval = opts.key;
  3556. }
  3557. keyval += '';
  3558. $.each(keyval.split('/'), function(i, key) {
  3559. $(document).bind('keydown', key, function(e) {
  3560. fn();
  3561. if(pd) {
  3562. e.preventDefault();
  3563. }
  3564. // Prevent default on ALL keys?
  3565. return false;
  3566. });
  3567. });
  3568. // Put shortcut in title
  3569. if(opts.sel && !opts.hidekey && btn.attr('title')) {
  3570. var new_title = btn.attr('title').split('[')[0] + ' (' + keyval + ')';
  3571. key_assocs[keyval] = opts.sel;
  3572. // Disregard for menu items
  3573. if(!btn.parents('#main_menu').length) {
  3574. btn.attr('title', new_title);
  3575. }
  3576. }
  3577. }
  3578. });
  3579. // Setup flyouts
  3580. setupFlyouts(flyouts);
  3581. // Misc additional actions
  3582. // Make "return" keypress trigger the change event
  3583. $('.attr_changer, #image_url').bind('keydown', 'return',
  3584. function(evt) {$(this).change();evt.preventDefault();}
  3585. );
  3586. $(window).bind('keydown', 'tab', function(e) {
  3587. if(ui_context === 'canvas') {
  3588. e.preventDefault();
  3589. selectNext();
  3590. }
  3591. }).bind('keydown', 'shift+tab', function(e) {
  3592. if(ui_context === 'canvas') {
  3593. e.preventDefault();
  3594. selectPrev();
  3595. }
  3596. });
  3597. $('#tool_zoom').dblclick(dblclickZoom);
  3598. },
  3599. setTitles: function() {
  3600. $.each(key_assocs, function(keyval, sel) {
  3601. var menu = ($(sel).parents('#main_menu').length);
  3602. $(sel).each(function() {
  3603. if(menu) {
  3604. var t = $(this).text().split(' [')[0];
  3605. } else {
  3606. var t = this.title.split(' [')[0];
  3607. }
  3608. var key_str = '';
  3609. // Shift+Up
  3610. $.each(keyval.split('/'), function(i, key) {
  3611. var mod_bits = key.split('+'), mod = '';
  3612. if(mod_bits.length > 1) {
  3613. mod = mod_bits[0] + '+';
  3614. key = mod_bits[1];
  3615. }
  3616. key_str += (i?'/':'') + mod + (uiStrings['key_'+key] || key);
  3617. });
  3618. if(menu) {
  3619. this.lastChild.textContent = t +' ['+key_str+']';
  3620. } else {
  3621. this.title = t +' ['+key_str+']';
  3622. }
  3623. });
  3624. });
  3625. },
  3626. getButtonData: function(sel) {
  3627. var b;
  3628. $.each(tool_buttons, function(i, btn) {
  3629. if(btn.sel === sel) b = btn;
  3630. });
  3631. return b;
  3632. }
  3633. };
  3634. }();
  3635. Actions.setAll();
  3636. // Select given tool
  3637. Editor.ready(function() {
  3638. var tool,
  3639. itool = curConfig.initTool,
  3640. container = $("#tools_left, #svg_editor .tools_flyout"),
  3641. pre_tool = container.find("#tool_" + itool),
  3642. reg_tool = container.find("#" + itool);
  3643. if(pre_tool.length) {
  3644. tool = pre_tool;
  3645. } else if(reg_tool.length){
  3646. tool = reg_tool;
  3647. } else {
  3648. tool = $("#tool_select");
  3649. }
  3650. tool.click().mouseup();
  3651. if(curConfig.wireframe) {
  3652. $('#tool_wireframe').click();
  3653. }
  3654. if(curConfig.showlayers) {
  3655. toggleSidePanel();
  3656. }
  3657. $('#rulers').toggle(!!curConfig.showRulers);
  3658. if (curConfig.showRulers) {
  3659. $('#show_rulers')[0].checked = true;
  3660. }
  3661. if(curConfig.gridSnapping) {
  3662. $('#grid_snapping_on')[0].checked = true;
  3663. }
  3664. if(curConfig.baseUnit) {
  3665. $('#base_unit').val(curConfig.baseUnit);
  3666. }
  3667. if(curConfig.snappingStep) {
  3668. $('#grid_snapping_step').val(curConfig.snappingStep);
  3669. }
  3670. });
  3671. $('#rect_rx').SpinButton({ min: 0, max: 1000, step: 1, callback: changeRectRadius });
  3672. $('#stroke_width').SpinButton({ min: 0, max: 99, step: 1, smallStep: 0.1, callback: changeStrokeWidth });
  3673. $('#angle').SpinButton({ min: -180, max: 180, step: 5, callback: changeRotationAngle });
  3674. $('#font_size').SpinButton({ step: 1, min: 0.001, stepfunc: stepFontSize, callback: changeFontSize });
  3675. $('#group_opacity').SpinButton({ step: 5, min: 0, max: 100, callback: changeOpacity });
  3676. $('#blur').SpinButton({ step: .1, min: 0, max: 10, callback: changeBlur });
  3677. $('#zoom').SpinButton({ min: 0.001, max: 10000, step: 50, stepfunc: stepZoom, callback: changeZoom })
  3678. // Set default zoom
  3679. .val(svgCanvas.getZoom() * 100);
  3680. $("#workarea").contextMenu({
  3681. menu: 'cmenu_canvas',
  3682. inSpeed: 0
  3683. },
  3684. function(action, el, pos) {
  3685. switch ( action ) {
  3686. case 'delete':
  3687. deleteSelected();
  3688. break;
  3689. case 'cut':
  3690. cutSelected();
  3691. break;
  3692. case 'copy':
  3693. copySelected();
  3694. break;
  3695. case 'paste':
  3696. svgCanvas.pasteElements();
  3697. break;
  3698. case 'paste_in_place':
  3699. svgCanvas.pasteElements('in_place');
  3700. break;
  3701. case 'group':
  3702. svgCanvas.groupSelectedElements();
  3703. break;
  3704. case 'ungroup':
  3705. svgCanvas.ungroupSelectedElement();
  3706. break;
  3707. case 'move_front':
  3708. moveToTopSelected();
  3709. break;
  3710. case 'move_up':
  3711. moveUpDownSelected('Up');
  3712. break;
  3713. case 'move_down':
  3714. moveUpDownSelected('Down');
  3715. break;
  3716. case 'move_back':
  3717. moveToBottomSelected();
  3718. break;
  3719. default:
  3720. if(svgedit.contextmenu && svgedit.contextmenu.hasCustomHandler(action)){
  3721. svgedit.contextmenu.getCustomHandler(action).call();
  3722. }
  3723. break;
  3724. }
  3725. if(svgCanvas.clipBoard.length) {
  3726. canv_menu.enableContextMenuItems('#paste,#paste_in_place');
  3727. }
  3728. });
  3729. var lmenu_func = function(action, el, pos) {
  3730. switch ( action ) {
  3731. case 'dupe':
  3732. cloneLayer();
  3733. break;
  3734. case 'delete':
  3735. deleteLayer();
  3736. break;
  3737. case 'merge_down':
  3738. mergeLayer();
  3739. break;
  3740. case 'merge_all':
  3741. svgCanvas.mergeAllLayers();
  3742. updateContextPanel();
  3743. populateLayers();
  3744. break;
  3745. }
  3746. }
  3747. $("#layerlist").contextMenu({
  3748. menu: 'cmenu_layers',
  3749. inSpeed: 0
  3750. },
  3751. lmenu_func
  3752. );
  3753. $("#layer_moreopts").contextMenu({
  3754. menu: 'cmenu_layers',
  3755. inSpeed: 0,
  3756. allowLeft: true
  3757. },
  3758. lmenu_func
  3759. );
  3760. $('.contextMenu li').mousedown(function(ev) {
  3761. ev.preventDefault();
  3762. })
  3763. $('#cmenu_canvas li').disableContextMenu();
  3764. canv_menu.enableContextMenuItems('#delete,#cut,#copy');
  3765. window.onbeforeunload = function() {
  3766. // Suppress warning if page is empty
  3767. if(undoMgr.getUndoStackSize() === 0) {
  3768. Editor.show_save_warning = false;
  3769. }
  3770. // show_save_warning is set to "false" when the page is saved.
  3771. if(!curConfig.no_save_warning && Editor.show_save_warning) {
  3772. // Browser already asks question about closing the page
  3773. return uiStrings.notification.unsavedChanges;
  3774. }
  3775. };
  3776. Editor.openPrep = function(func) {
  3777. $('#main_menu').hide();
  3778. if(undoMgr.getUndoStackSize() === 0) {
  3779. func(true);
  3780. } else {
  3781. $.confirm(uiStrings.notification.QwantToOpen, func);
  3782. }
  3783. }
  3784. // use HTML5 File API: http://www.w3.org/TR/FileAPI/
  3785. // if browser has HTML5 File API support, then we will show the open menu item
  3786. // and provide a file input to click. When that change event fires, it will
  3787. // get the text contents of the file and send it to the canvas
  3788. if (window.FileReader) {
  3789. var inp = $('<input type="file">').change(function() {
  3790. var f = this;
  3791. Editor.openPrep(function(ok) {
  3792. if(!ok) return;
  3793. svgCanvas.clear();
  3794. if(f.files.length==1) {
  3795. var reader = new FileReader();
  3796. reader.onloadend = function(e) {
  3797. loadSvgString(e.target.result);
  3798. updateCanvas();
  3799. };
  3800. reader.readAsText(f.files[0]);
  3801. }
  3802. });
  3803. });
  3804. $("#tool_open").show().prepend(inp);
  3805. var inp2 = $('<input type="file">').change(function() {
  3806. $('#main_menu').hide();
  3807. if(this.files.length==1) {
  3808. var reader = new FileReader();
  3809. reader.onloadend = function(e) {
  3810. svgCanvas.importSvgString(e.target.result, true);
  3811. updateCanvas();
  3812. };
  3813. reader.readAsText(this.files[0]);
  3814. }
  3815. });
  3816. $("#tool_import").show().prepend(inp2);
  3817. }
  3818. var updateCanvas = Editor.updateCanvas = function(center, new_ctr) {
  3819. var w = workarea.width(), h = workarea.height();
  3820. var w_orig = w, h_orig = h;
  3821. var zoom = svgCanvas.getZoom();
  3822. var w_area = workarea;
  3823. var cnvs = $("#svgcanvas");
  3824. var old_ctr = {
  3825. x: w_area[0].scrollLeft + w_orig/2,
  3826. y: w_area[0].scrollTop + h_orig/2
  3827. };
  3828. var multi = curConfig.canvas_expansion;
  3829. w = Math.max(w_orig, svgCanvas.contentW * zoom * multi);
  3830. h = Math.max(h_orig, svgCanvas.contentH * zoom * multi);
  3831. if(w == w_orig && h == h_orig) {
  3832. workarea.css('overflow','hidden');
  3833. } else {
  3834. workarea.css('overflow','scroll');
  3835. }
  3836. var old_can_y = cnvs.height()/2;
  3837. var old_can_x = cnvs.width()/2;
  3838. cnvs.width(w).height(h);
  3839. var new_can_y = h/2;
  3840. var new_can_x = w/2;
  3841. var offset = svgCanvas.updateCanvas(w, h);
  3842. var ratio = new_can_x / old_can_x;
  3843. var scroll_x = w/2 - w_orig/2;
  3844. var scroll_y = h/2 - h_orig/2;
  3845. if(!new_ctr) {
  3846. var old_dist_x = old_ctr.x - old_can_x;
  3847. var new_x = new_can_x + old_dist_x * ratio;
  3848. var old_dist_y = old_ctr.y - old_can_y;
  3849. var new_y = new_can_y + old_dist_y * ratio;
  3850. new_ctr = {
  3851. x: new_x,
  3852. y: new_y
  3853. };
  3854. } else {
  3855. new_ctr.x += offset.x,
  3856. new_ctr.y += offset.y;
  3857. }
  3858. if(center) {
  3859. // Go to top-left for larger documents
  3860. if(svgCanvas.contentW > w_area.width()) {
  3861. // Top-left
  3862. workarea[0].scrollLeft = offset.x - 10;
  3863. workarea[0].scrollTop = offset.y - 10;
  3864. } else {
  3865. // Center
  3866. w_area[0].scrollLeft = scroll_x;
  3867. w_area[0].scrollTop = scroll_y;
  3868. }
  3869. } else {
  3870. w_area[0].scrollLeft = new_ctr.x - w_orig/2;
  3871. w_area[0].scrollTop = new_ctr.y - h_orig/2;
  3872. }
  3873. if(curConfig.showRulers) {
  3874. updateRulers(cnvs, zoom);
  3875. workarea.scroll();
  3876. }
  3877. }
  3878. // Make [1,2,5] array
  3879. var r_intervals = [];
  3880. for(var i = .1; i < 1E5; i *= 10) {
  3881. r_intervals.push(1 * i);
  3882. r_intervals.push(2 * i);
  3883. r_intervals.push(5 * i);
  3884. }
  3885. function updateRulers(scanvas, zoom) {
  3886. if(!zoom) zoom = svgCanvas.getZoom();
  3887. if(!scanvas) scanvas = $("#svgcanvas");
  3888. var limit = 30000;
  3889. var c_elem = svgCanvas.getContentElem();
  3890. var units = svgedit.units.getTypeMap();
  3891. var unit = units[curConfig.baseUnit]; // 1 = 1px
  3892. for(var d = 0; d < 2; d++) {
  3893. var is_x = (d === 0);
  3894. var dim = is_x ? 'x' : 'y';
  3895. var lentype = is_x?'width':'height';
  3896. var content_d = c_elem.getAttribute(dim)-0;
  3897. var $hcanv_orig = $('#ruler_' + dim + ' canvas:first');
  3898. // Bit of a hack to fully clear the canvas in Safari & IE9
  3899. $hcanv = $hcanv_orig.clone();
  3900. $hcanv_orig.replaceWith($hcanv);
  3901. var hcanv = $hcanv[0];
  3902. // Set the canvas size to the width of the container
  3903. var ruler_len = scanvas[lentype]();
  3904. var total_len = ruler_len;
  3905. hcanv.parentNode.style[lentype] = total_len + 'px';
  3906. var canv_count = 1;
  3907. var ctx_num = 0;
  3908. var ctx_arr;
  3909. var ctx = hcanv.getContext("2d");
  3910. ctx.fillStyle = "rgb(200,0,0)";
  3911. ctx.fillRect(0,0,hcanv.width,hcanv.height);
  3912. // Remove any existing canvasses
  3913. $hcanv.siblings().remove();
  3914. // Create multiple canvases when necessary (due to browser limits)
  3915. if(ruler_len >= limit) {
  3916. var num = parseInt(ruler_len / limit) + 1;
  3917. ctx_arr = Array(num);
  3918. ctx_arr[0] = ctx;
  3919. for(var i = 1; i < num; i++) {
  3920. hcanv[lentype] = limit;
  3921. var copy = hcanv.cloneNode(true);
  3922. hcanv.parentNode.appendChild(copy);
  3923. ctx_arr[i] = copy.getContext('2d');
  3924. }
  3925. copy[lentype] = ruler_len % limit;
  3926. // set copy width to last
  3927. ruler_len = limit;
  3928. }
  3929. hcanv[lentype] = ruler_len;
  3930. var u_multi = unit * zoom;
  3931. // Calculate the main number interval
  3932. var raw_m = 50 / u_multi;
  3933. var multi = 1;
  3934. for(var i = 0; i < r_intervals.length; i++) {
  3935. var num = r_intervals[i];
  3936. multi = num;
  3937. if(raw_m <= num) {
  3938. break;
  3939. }
  3940. }
  3941. var big_int = multi * u_multi;
  3942. ctx.font = "9px sans-serif";
  3943. var ruler_d = ((content_d / u_multi) % multi) * u_multi;
  3944. var label_pos = ruler_d - big_int;
  3945. for (; ruler_d < total_len; ruler_d += big_int) {
  3946. label_pos += big_int;
  3947. var real_d = ruler_d - content_d;
  3948. var cur_d = Math.round(ruler_d) + .5;
  3949. if(is_x) {
  3950. ctx.moveTo(cur_d, 15);
  3951. ctx.lineTo(cur_d, 0);
  3952. } else {
  3953. ctx.moveTo(15, cur_d);
  3954. ctx.lineTo(0, cur_d);
  3955. }
  3956. var num = (label_pos - content_d) / u_multi;
  3957. var label;
  3958. if(multi >= 1) {
  3959. label = Math.round(num);
  3960. } else {
  3961. var decs = (multi+'').split('.')[1].length;
  3962. label = num.toFixed(decs)-0;
  3963. }
  3964. // Do anything special for negative numbers?
  3965. // var is_neg = label < 0;
  3966. // real_d2 = Math.abs(real_d2);
  3967. // Change 1000s to Ks
  3968. if(label !== 0 && label !== 1000 && label % 1000 === 0) {
  3969. label = (label / 1000) + 'K';
  3970. }
  3971. if(is_x) {
  3972. ctx.fillText(label, ruler_d+2, 8);
  3973. } else {
  3974. var str = (label+'').split('');
  3975. for(var i = 0; i < str.length; i++) {
  3976. ctx.fillText(str[i], 1, (ruler_d+9) + i*9);
  3977. }
  3978. }
  3979. var part = big_int / 10;
  3980. for(var i = 1; i < 10; i++) {
  3981. var sub_d = Math.round(ruler_d + part * i) + .5;
  3982. if(ctx_arr && sub_d > ruler_len) {
  3983. ctx_num++;
  3984. ctx.stroke();
  3985. if(ctx_num >= ctx_arr.length) {
  3986. i = 10;
  3987. ruler_d = total_len;
  3988. continue;
  3989. }
  3990. ctx = ctx_arr[ctx_num];
  3991. ruler_d -= limit;
  3992. sub_d = Math.round(ruler_d + part * i) + .5;
  3993. }
  3994. var line_num = (i % 2)?12:10;
  3995. if(is_x) {
  3996. ctx.moveTo(sub_d, 15);
  3997. ctx.lineTo(sub_d, line_num);
  3998. } else {
  3999. ctx.moveTo(15, sub_d);
  4000. ctx.lineTo(line_num ,sub_d);
  4001. }
  4002. }
  4003. }
  4004. // console.log('ctx', ctx);
  4005. ctx.strokeStyle = "#000";
  4006. ctx.stroke();
  4007. }
  4008. }
  4009. // $(function() {
  4010. updateCanvas(true);
  4011. // });
  4012. // var revnums = "svg-editor.js ($Rev: 2056 $) ";
  4013. // revnums += svgCanvas.getVersion();
  4014. // $('#copyright')[0].setAttribute("title", revnums);
  4015. // Callback handler for embedapi.js
  4016. try{
  4017. var json_encode = function(obj){
  4018. //simple partial JSON encoder implementation
  4019. if(window.JSON && JSON.stringify) return JSON.stringify(obj);
  4020. var enc = arguments.callee; //for purposes of recursion
  4021. if(typeof obj == "boolean" || typeof obj == "number"){
  4022. return obj+'' //should work...
  4023. }else if(typeof obj == "string"){
  4024. //a large portion of this is stolen from Douglas Crockford's json2.js
  4025. return '"'+
  4026. obj.replace(
  4027. /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g
  4028. , function (a) {
  4029. return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  4030. })
  4031. +'"'; //note that this isn't quite as purtyful as the usualness
  4032. }else if(obj.length){ //simple hackish test for arrayish-ness
  4033. for(var i = 0; i < obj.length; i++){
  4034. obj[i] = enc(obj[i]); //encode every sub-thingy on top
  4035. }
  4036. return "["+obj.join(",")+"]";
  4037. }else{
  4038. var pairs = []; //pairs will be stored here
  4039. for(var k in obj){ //loop through thingys
  4040. pairs.push(enc(k)+":"+enc(obj[k])); //key: value
  4041. }
  4042. return "{"+pairs.join(",")+"}" //wrap in the braces
  4043. }
  4044. }
  4045. window.addEventListener("message", function(e){
  4046. var cbid = parseInt(e.data.substr(0, e.data.indexOf(";")));
  4047. try{
  4048. e.source.postMessage("SVGe"+cbid+";"+json_encode(eval(e.data)), "*");
  4049. }catch(err){
  4050. e.source.postMessage("SVGe"+cbid+";error:"+err.message, "*");
  4051. }
  4052. }, false)
  4053. }catch(err){
  4054. window.embed_error = err;
  4055. }
  4056. // For Compatibility with older extensions
  4057. $(function() {
  4058. window.svgCanvas = svgCanvas;
  4059. svgCanvas.ready = svgEditor.ready;
  4060. });
  4061. Editor.setLang = function(lang, allStrings) {
  4062. $.pref('lang', lang);
  4063. $('#lang_select').val(lang);
  4064. if(allStrings) {
  4065. var notif = allStrings.notification;
  4066. // $.extend will only replace the given strings
  4067. var oldLayerName = $('#layerlist tr.layersel td.layername').text();
  4068. var rename_layer = (oldLayerName == uiStrings.common.layer + ' 1');
  4069. $.extend(uiStrings, allStrings);
  4070. svgCanvas.setUiStrings(allStrings);
  4071. Actions.setTitles();
  4072. if(rename_layer) {
  4073. svgCanvas.renameCurrentLayer(uiStrings.common.layer + ' 1');
  4074. populateLayers();
  4075. }
  4076. svgCanvas.runExtensions("langChanged", lang);
  4077. // Update flyout tooltips
  4078. setFlyoutTitles();
  4079. // Copy title for certain tool elements
  4080. var elems = {
  4081. '#stroke_color': '#tool_stroke .icon_label, #tool_stroke .color_block',
  4082. '#fill_color': '#tool_fill label, #tool_fill .color_block',
  4083. '#linejoin_miter': '#cur_linejoin',
  4084. '#linecap_butt': '#cur_linecap'
  4085. }
  4086. $.each(elems, function(source, dest) {
  4087. $(dest).attr('title', $(source)[0].title);
  4088. });
  4089. // Copy alignment titles
  4090. $('#multiselected_panel div[id^=tool_align]').each(function() {
  4091. $('#tool_pos' + this.id.substr(10))[0].title = this.title;
  4092. });
  4093. }
  4094. };
  4095. };
  4096. var callbacks = [];
  4097. function loadSvgString(str, callback) {
  4098. var success = svgCanvas.setSvgString(str) !== false;
  4099. callback = callback || $.noop;
  4100. if(success) {
  4101. callback(true);
  4102. } else {
  4103. $.alert(uiStrings.notification.errorLoadingSVG, function() {
  4104. callback(false);
  4105. });
  4106. }
  4107. }
  4108. Editor.ready = function(cb) {
  4109. if(!is_ready) {
  4110. callbacks.push(cb);
  4111. } else {
  4112. cb();
  4113. }
  4114. };
  4115. Editor.runCallbacks = function() {
  4116. $.each(callbacks, function() {
  4117. this();
  4118. });
  4119. is_ready = true;
  4120. };
  4121. Editor.loadFromString = function(str) {
  4122. Editor.ready(function() {
  4123. loadSvgString(str);
  4124. });
  4125. };
  4126. Editor.disableUI = function(featList) {
  4127. // $(function() {
  4128. // $('#tool_wireframe, #tool_image, #main_button, #tool_source, #sidepanels').remove();
  4129. // $('#tools_top').css('left', 5);
  4130. // });
  4131. };
  4132. Editor.loadFromURL = function(url, opts) {
  4133. if(!opts) opts = {};
  4134. var cache = opts.cache;
  4135. var cb = opts.callback;
  4136. Editor.ready(function() {
  4137. $.ajax({
  4138. 'url': url,
  4139. 'dataType': 'text',
  4140. cache: !!cache,
  4141. success: function(str) {
  4142. loadSvgString(str, cb);
  4143. },
  4144. error: function(xhr, stat, err) {
  4145. if(xhr.status != 404 && xhr.responseText) {
  4146. loadSvgString(xhr.responseText, cb);
  4147. } else {
  4148. $.alert(uiStrings.notification.URLloadFail + ": \n"+err+'', cb);
  4149. }
  4150. }
  4151. });
  4152. });
  4153. };
  4154. Editor.loadFromDataURI = function(str) {
  4155. Editor.ready(function() {
  4156. var pre = 'data:image/svg+xml;base64,';
  4157. var src = str.substring(pre.length);
  4158. loadSvgString(svgedit.utilities.decode64(src));
  4159. });
  4160. };
  4161. Editor.addExtension = function() {
  4162. var args = arguments;
  4163. // Note that we don't want this on Editor.ready since some extensions
  4164. // may want to run before then (like server_opensave).
  4165. $(function() {
  4166. if(svgCanvas) svgCanvas.addExtension.apply(this, args);
  4167. });
  4168. };
  4169. return Editor;
  4170. }(jQuery);
  4171. // Run init once DOM is loaded
  4172. $(svgEditor.init);
  4173. })();
  4174. // ?iconsize=s&bkgd_color=555
  4175. // svgEditor.setConfig({
  4176. // // imgPath: 'foo',
  4177. // dimensions: [800, 600],
  4178. // canvas_expansion: 5,
  4179. // initStroke: {
  4180. // color: '0000FF',
  4181. // width: 3.5,
  4182. // opacity: .5
  4183. // },
  4184. // initFill: {
  4185. // color: '550000',
  4186. // opacity: .75
  4187. // },
  4188. // extensions: ['ext-helloworld.js']
  4189. // })