svg-editor.js 145 KB

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