svg-editor.js 145 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857
  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. // Clicking the "show" icon should set the current mode
  799. shower.mousedown(function(evt) {
  800. if(shower.hasClass('disabled')) return false;
  801. var holder = $(show_sel.replace('_show',''));
  802. var l = holder[0].style.left;
  803. var w = holder.width()*-1;
  804. var time = holder.data('shown_popop')?200:0;
  805. timer = setTimeout(function() {
  806. // Show corresponding menu
  807. if(!shower.data('isLibrary')) {
  808. holder.css('left', w).show().animate({
  809. left: l
  810. },150);
  811. } else {
  812. holder.css('left', l).show();
  813. }
  814. holder.data('shown_popop',true);
  815. },time);
  816. evt.preventDefault();
  817. }).mouseup(function(evt) {
  818. clearTimeout(timer);
  819. var opt = $(this).attr('data-curopt');
  820. // Is library and popped up, so do nothing
  821. if(shower.data('isLibrary') && $(show_sel.replace('_show','')).is(':visible')) {
  822. toolButtonClick(show_sel, true);
  823. return;
  824. }
  825. if (toolButtonClick(show_sel) && (opt in flyout_funcs)) {
  826. flyout_funcs[opt]();
  827. }
  828. });
  829. // $('#tools_rect').mouseleave(function(){$('#tools_rect').fadeOut();});
  830. var pos = $(show_sel).position();
  831. $(hold_sel).css({'left': pos.left+34, 'top': pos.top+77});
  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. var button = $(elem).find('button');
  1846. var list = $(elem).find('ul').attr('id', $(elem)[0].id + '-list');
  1847. if(!dropUp) {
  1848. // Move list to place where it can overflow container
  1849. $('#option_lists').append(list);
  1850. }
  1851. var on_button = false;
  1852. if(dropUp) {
  1853. $(elem).addClass('dropup');
  1854. }
  1855. list.find('li').bind('mouseup', callback);
  1856. $(window).mouseup(function(evt) {
  1857. if(!on_button) {
  1858. button.removeClass('down');
  1859. list.hide();
  1860. }
  1861. on_button = false;
  1862. });
  1863. button.bind('mousedown',function() {
  1864. if (!button.hasClass('down')) {
  1865. button.addClass('down');
  1866. if(!dropUp) {
  1867. var pos = $(elem).position();
  1868. list.css({
  1869. top: pos.top + 24,
  1870. left: pos.left - 10
  1871. });
  1872. }
  1873. list.show();
  1874. on_button = true;
  1875. } else {
  1876. button.removeClass('down');
  1877. list.hide();
  1878. }
  1879. }).hover(function() {
  1880. on_button = true;
  1881. }).mouseout(function() {
  1882. on_button = false;
  1883. });
  1884. }
  1885. // TODO: Combine this with addDropDown or find other way to optimize
  1886. var addAltDropDown = function(elem, list, callback, opts) {
  1887. var button = $(elem);
  1888. var list = $(list);
  1889. var on_button = false;
  1890. var dropUp = opts.dropUp;
  1891. if(dropUp) {
  1892. $(elem).addClass('dropup');
  1893. }
  1894. list.find('li').bind('mouseup', function() {
  1895. if(opts.seticon) {
  1896. setIcon('#cur_' + button[0].id , $(this).children());
  1897. $(this).addClass('current').siblings().removeClass('current');
  1898. }
  1899. callback.apply(this, arguments);
  1900. });
  1901. $(window).mouseup(function(evt) {
  1902. if(!on_button) {
  1903. button.removeClass('down');
  1904. list.hide();
  1905. list.css({top:0, left:0});
  1906. }
  1907. on_button = false;
  1908. });
  1909. var height = list.height();
  1910. $(elem).bind('mousedown',function() {
  1911. var off = $(elem).offset();
  1912. if(dropUp) {
  1913. off.top -= list.height();
  1914. off.left += 8;
  1915. } else {
  1916. off.top += $(elem).height();
  1917. }
  1918. $(list).offset(off);
  1919. if (!button.hasClass('down')) {
  1920. button.addClass('down');
  1921. list.show();
  1922. on_button = true;
  1923. return false;
  1924. } else {
  1925. button.removeClass('down');
  1926. // CSS position must be reset for Webkit
  1927. list.hide();
  1928. list.css({top:0, left:0});
  1929. }
  1930. }).hover(function() {
  1931. on_button = true;
  1932. }).mouseout(function() {
  1933. on_button = false;
  1934. });
  1935. if(opts.multiclick) {
  1936. list.mousedown(function() {
  1937. on_button = true;
  1938. });
  1939. }
  1940. }
  1941. Editor.addDropDown('#font_family_dropdown', function() {
  1942. var fam = $(this).text();
  1943. $('#font_family').val($(this).text()).change();
  1944. });
  1945. Editor.addDropDown('#opacity_dropdown', function() {
  1946. if($(this).find('div').length) return;
  1947. var perc = parseInt($(this).text().split('%')[0]);
  1948. changeOpacity(false, perc);
  1949. }, true);
  1950. // For slider usage, see: http://jqueryui.com/demos/slider/
  1951. $("#opac_slider").slider({
  1952. start: function() {
  1953. $('#opacity_dropdown li:not(.special)').hide();
  1954. },
  1955. stop: function() {
  1956. $('#opacity_dropdown li').show();
  1957. $(window).mouseup();
  1958. },
  1959. slide: function(evt, ui){
  1960. changeOpacity(ui);
  1961. }
  1962. });
  1963. Editor.addDropDown('#blur_dropdown', $.noop);
  1964. var slideStart = false;
  1965. $("#blur_slider").slider({
  1966. max: 10,
  1967. step: .1,
  1968. stop: function(evt, ui) {
  1969. slideStart = false;
  1970. changeBlur(ui);
  1971. $('#blur_dropdown li').show();
  1972. $(window).mouseup();
  1973. },
  1974. start: function() {
  1975. slideStart = true;
  1976. },
  1977. slide: function(evt, ui){
  1978. changeBlur(ui, null, slideStart);
  1979. }
  1980. });
  1981. Editor.addDropDown('#zoom_dropdown', function() {
  1982. var item = $(this);
  1983. var val = item.attr('data-val');
  1984. if(val) {
  1985. zoomChanged(window, val);
  1986. } else {
  1987. changeZoom({value:parseInt(item.text())});
  1988. }
  1989. }, true);
  1990. addAltDropDown('#stroke_linecap', '#linecap_opts', function() {
  1991. setStrokeOpt(this, true);
  1992. }, {dropUp: true});
  1993. addAltDropDown('#stroke_linejoin', '#linejoin_opts', function() {
  1994. setStrokeOpt(this, true);
  1995. }, {dropUp: true});
  1996. addAltDropDown('#tool_position', '#position_opts', function() {
  1997. var letter = this.id.replace('tool_pos','').charAt(0);
  1998. svgCanvas.alignSelectedElements(letter, 'page');
  1999. }, {multiclick: true});
  2000. /*
  2001. When a flyout icon is selected
  2002. (if flyout) {
  2003. - Change the icon
  2004. - Make pressing the button run its stuff
  2005. }
  2006. - Run its stuff
  2007. When its shortcut key is pressed
  2008. - If not current in list, do as above
  2009. , else:
  2010. - Just run its stuff
  2011. */
  2012. // Unfocus text input when workarea is mousedowned.
  2013. (function() {
  2014. var inp;
  2015. var unfocus = function() {
  2016. $(inp).blur();
  2017. }
  2018. $('#svg_editor').find('button, select, input:not(#text)').focus(function() {
  2019. inp = this;
  2020. ui_context = 'toolbars';
  2021. workarea.mousedown(unfocus);
  2022. }).blur(function() {
  2023. ui_context = 'canvas';
  2024. workarea.unbind('mousedown', unfocus);
  2025. // Go back to selecting text if in textedit mode
  2026. if(svgCanvas.getMode() == 'textedit') {
  2027. $('#text').focus();
  2028. }
  2029. });
  2030. }());
  2031. var clickSelect = function() {
  2032. if (toolButtonClick('#tool_select')) {
  2033. svgCanvas.setMode('select');
  2034. $('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all}, #svgcanvas svg{cursor:default}');
  2035. }
  2036. };
  2037. var clickFHPath = function() {
  2038. if (toolButtonClick('#tool_fhpath')) {
  2039. svgCanvas.setMode('fhpath');
  2040. }
  2041. };
  2042. var clickLine = function() {
  2043. if (toolButtonClick('#tool_line')) {
  2044. svgCanvas.setMode('line');
  2045. }
  2046. };
  2047. var clickSquare = function(){
  2048. if (toolButtonClick('#tool_square')) {
  2049. svgCanvas.setMode('square');
  2050. }
  2051. };
  2052. var clickRect = function(){
  2053. if (toolButtonClick('#tool_rect')) {
  2054. svgCanvas.setMode('rect');
  2055. }
  2056. };
  2057. var clickFHRect = function(){
  2058. if (toolButtonClick('#tool_fhrect')) {
  2059. svgCanvas.setMode('fhrect');
  2060. }
  2061. };
  2062. var clickCircle = function(){
  2063. if (toolButtonClick('#tool_circle')) {
  2064. svgCanvas.setMode('circle');
  2065. }
  2066. };
  2067. var clickEllipse = function(){
  2068. if (toolButtonClick('#tool_ellipse')) {
  2069. svgCanvas.setMode('ellipse');
  2070. }
  2071. };
  2072. var clickFHEllipse = function(){
  2073. if (toolButtonClick('#tool_fhellipse')) {
  2074. svgCanvas.setMode('fhellipse');
  2075. }
  2076. };
  2077. var clickImage = function(){
  2078. if (toolButtonClick('#tool_image')) {
  2079. svgCanvas.setMode('image');
  2080. }
  2081. };
  2082. var clickZoom = function(){
  2083. if (toolButtonClick('#tool_zoom')) {
  2084. svgCanvas.setMode('zoom');
  2085. workarea.css('cursor', zoomInIcon);
  2086. }
  2087. };
  2088. var dblclickZoom = function(){
  2089. if (toolButtonClick('#tool_zoom')) {
  2090. zoomImage();
  2091. setSelectMode();
  2092. }
  2093. };
  2094. var clickText = function(){
  2095. if (toolButtonClick('#tool_text')) {
  2096. svgCanvas.setMode('text');
  2097. }
  2098. };
  2099. var clickPath = function(){
  2100. if (toolButtonClick('#tool_path')) {
  2101. svgCanvas.setMode('path');
  2102. }
  2103. };
  2104. // Delete is a contextual tool that only appears in the ribbon if
  2105. // an element has been selected
  2106. var deleteSelected = function() {
  2107. if (selectedElement != null || multiselected) {
  2108. svgCanvas.deleteSelectedElements();
  2109. }
  2110. };
  2111. var cutSelected = function() {
  2112. if (selectedElement != null || multiselected) {
  2113. svgCanvas.cutSelectedElements();
  2114. }
  2115. };
  2116. var copySelected = function() {
  2117. if (selectedElement != null || multiselected) {
  2118. svgCanvas.copySelectedElements();
  2119. }
  2120. };
  2121. var pasteInCenter = function() {
  2122. var zoom = svgCanvas.getZoom();
  2123. var x = (workarea[0].scrollLeft + workarea.width()/2)/zoom - svgCanvas.contentW;
  2124. var y = (workarea[0].scrollTop + workarea.height()/2)/zoom - svgCanvas.contentH;
  2125. svgCanvas.pasteElements('point', x, y);
  2126. }
  2127. var moveToTopSelected = function() {
  2128. if (selectedElement != null) {
  2129. svgCanvas.moveToTopSelectedElement();
  2130. }
  2131. };
  2132. var moveToBottomSelected = function() {
  2133. if (selectedElement != null) {
  2134. svgCanvas.moveToBottomSelectedElement();
  2135. }
  2136. };
  2137. var moveUpDownSelected = function(dir) {
  2138. if (selectedElement != null) {
  2139. svgCanvas.moveUpDownSelected(dir);
  2140. }
  2141. };
  2142. var convertToPath = function() {
  2143. if (selectedElement != null) {
  2144. svgCanvas.convertToPath();
  2145. }
  2146. }
  2147. var reorientPath = function() {
  2148. if (selectedElement != null) {
  2149. path.reorient();
  2150. }
  2151. }
  2152. var makeHyperlink = function() {
  2153. if (selectedElement != null || multiselected) {
  2154. $.prompt(uiStrings.notification.enterNewLinkURL, "http://", function(url) {
  2155. if(url) svgCanvas.makeHyperlink(url);
  2156. });
  2157. }
  2158. }
  2159. var moveSelected = function(dx,dy) {
  2160. if (selectedElement != null || multiselected) {
  2161. if(curConfig.gridSnapping) {
  2162. // Use grid snap value regardless of zoom level
  2163. var multi = svgCanvas.getZoom() * curConfig.snappingStep;
  2164. dx *= multi;
  2165. dy *= multi;
  2166. }
  2167. svgCanvas.moveSelectedElements(dx,dy);
  2168. }
  2169. };
  2170. var linkControlPoints = function() {
  2171. var linked = !$('#tool_node_link').hasClass('push_button_pressed');
  2172. if (linked)
  2173. $('#tool_node_link').addClass('push_button_pressed').removeClass('tool_button');
  2174. else
  2175. $('#tool_node_link').removeClass('push_button_pressed').addClass('tool_button');
  2176. path.linkControlPoints(linked);
  2177. }
  2178. var clonePathNode = function() {
  2179. if (path.getNodePoint()) {
  2180. path.clonePathNode();
  2181. }
  2182. };
  2183. var deletePathNode = function() {
  2184. if (path.getNodePoint()) {
  2185. path.deletePathNode();
  2186. }
  2187. };
  2188. var addSubPath = function() {
  2189. var button = $('#tool_add_subpath');
  2190. var sp = !button.hasClass('push_button_pressed');
  2191. if (sp) {
  2192. button.addClass('push_button_pressed').removeClass('tool_button');
  2193. } else {
  2194. button.removeClass('push_button_pressed').addClass('tool_button');
  2195. }
  2196. path.addSubPath(sp);
  2197. };
  2198. var opencloseSubPath = function() {
  2199. path.opencloseSubPath();
  2200. }
  2201. var selectNext = function() {
  2202. svgCanvas.cycleElement(1);
  2203. };
  2204. var selectPrev = function() {
  2205. svgCanvas.cycleElement(0);
  2206. };
  2207. var rotateSelected = function(cw,step) {
  2208. if (selectedElement == null || multiselected) return;
  2209. if(!cw) step *= -1;
  2210. var new_angle = $('#angle').val()*1 + step;
  2211. svgCanvas.setRotationAngle(new_angle);
  2212. updateContextPanel();
  2213. };
  2214. var clickClear = function(){
  2215. var dims = curConfig.dimensions;
  2216. $.confirm(uiStrings.notification.QwantToClear, function(ok) {
  2217. if(!ok) return;
  2218. setSelectMode();
  2219. svgCanvas.clear();
  2220. svgCanvas.setResolution(dims[0], dims[1]);
  2221. updateCanvas(true);
  2222. zoomImage();
  2223. populateLayers();
  2224. updateContextPanel();
  2225. prepPaints();
  2226. });
  2227. };
  2228. var clickBold = function(){
  2229. svgCanvas.setBold( !svgCanvas.getBold() );
  2230. updateContextPanel();
  2231. return false;
  2232. };
  2233. var clickItalic = function(){
  2234. svgCanvas.setItalic( !svgCanvas.getItalic() );
  2235. updateContextPanel();
  2236. return false;
  2237. };
  2238. var clickSave = function(){
  2239. // In the future, more options can be provided here
  2240. var saveOpts = {
  2241. 'images': curPrefs.img_save,
  2242. 'round_digits': 6
  2243. }
  2244. svgCanvas.save(saveOpts);
  2245. };
  2246. var clickExport = function() {
  2247. // Open placeholder window (prevents popup)
  2248. if(!customHandlers.pngsave) {
  2249. var str = uiStrings.notification.loadingImage;
  2250. exportWindow = window.open("data:text/html;charset=utf-8,<title>" + str + "<\/title><h1>" + str + "<\/h1>");
  2251. }
  2252. if(window.canvg) {
  2253. svgCanvas.rasterExport();
  2254. } else {
  2255. $.getScript('canvg/rgbcolor.js', function() {
  2256. $.getScript('canvg/canvg.js', function() {
  2257. svgCanvas.rasterExport();
  2258. });
  2259. });
  2260. }
  2261. }
  2262. // by default, svgCanvas.open() is a no-op.
  2263. // it is up to an extension mechanism (opera widget, etc)
  2264. // to call setCustomHandlers() which will make it do something
  2265. var clickOpen = function(){
  2266. svgCanvas.open();
  2267. };
  2268. var clickImport = function(){
  2269. };
  2270. var clickUndo = function(){
  2271. if (undoMgr.getUndoStackSize() > 0) {
  2272. undoMgr.undo();
  2273. populateLayers();
  2274. }
  2275. };
  2276. var clickRedo = function(){
  2277. if (undoMgr.getRedoStackSize() > 0) {
  2278. undoMgr.redo();
  2279. populateLayers();
  2280. }
  2281. };
  2282. var clickGroup = function(){
  2283. // group
  2284. if (multiselected) {
  2285. svgCanvas.groupSelectedElements();
  2286. }
  2287. // ungroup
  2288. else if(selectedElement){
  2289. svgCanvas.ungroupSelectedElement();
  2290. }
  2291. };
  2292. var clickClone = function(){
  2293. svgCanvas.cloneSelectedElements(20,20);
  2294. };
  2295. var clickAlign = function() {
  2296. var letter = this.id.replace('tool_align','').charAt(0);
  2297. svgCanvas.alignSelectedElements(letter, $('#align_relative_to').val());
  2298. };
  2299. var zoomImage = function(multiplier) {
  2300. var res = svgCanvas.getResolution();
  2301. multiplier = multiplier?res.zoom * multiplier:1;
  2302. // setResolution(res.w * multiplier, res.h * multiplier, true);
  2303. $('#zoom').val(multiplier * 100);
  2304. svgCanvas.setZoom(multiplier);
  2305. zoomDone();
  2306. updateCanvas(true);
  2307. };
  2308. var zoomDone = function() {
  2309. // updateBgImage();
  2310. updateWireFrame();
  2311. //updateCanvas(); // necessary?
  2312. }
  2313. var clickWireframe = function() {
  2314. var wf = !$('#tool_wireframe').hasClass('push_button_pressed');
  2315. if (wf)
  2316. $('#tool_wireframe').addClass('push_button_pressed').removeClass('tool_button');
  2317. else
  2318. $('#tool_wireframe').removeClass('push_button_pressed').addClass('tool_button');
  2319. workarea.toggleClass('wireframe');
  2320. if(supportsNonSS) return;
  2321. var wf_rules = $('#wireframe_rules');
  2322. if(!wf_rules.length) {
  2323. wf_rules = $('<style id="wireframe_rules"><\/style>').appendTo('head');
  2324. } else {
  2325. wf_rules.empty();
  2326. }
  2327. updateWireFrame();
  2328. }
  2329. var updateWireFrame = function() {
  2330. // Test support
  2331. if(supportsNonSS) return;
  2332. var rule = "#workarea.wireframe #svgcontent * { stroke-width: " + 1/svgCanvas.getZoom() + "px; }";
  2333. $('#wireframe_rules').text(workarea.hasClass('wireframe') ? rule : "");
  2334. }
  2335. var showSourceEditor = function(e, forSaving){
  2336. if (editingsource) return;
  2337. editingsource = true;
  2338. $('#save_output_btns').toggle(!!forSaving);
  2339. $('#tool_source_back').toggle(!forSaving);
  2340. var str = orig_source = svgCanvas.getSvgString();
  2341. $('#svg_source_textarea').val(str);
  2342. $('#svg_source_editor').fadeIn();
  2343. properlySourceSizeTextArea();
  2344. $('#svg_source_textarea').focus();
  2345. };
  2346. $('#svg_docprops_container, #svg_prefs_container').draggable({cancel:'button,fieldset', containment: 'window'});
  2347. var showDocProperties = function(){
  2348. if (docprops) return;
  2349. docprops = true;
  2350. // This selects the correct radio button by using the array notation
  2351. $('#image_save_opts input').val([curPrefs.img_save]);
  2352. // update resolution option with actual resolution
  2353. var res = svgCanvas.getResolution();
  2354. if(curConfig.baseUnit !== "px") {
  2355. res.w = svgedit.units.convertUnit(res.w) + curConfig.baseUnit;
  2356. res.h = svgedit.units.convertUnit(res.h) + curConfig.baseUnit;
  2357. }
  2358. $('#canvas_width').val(res.w);
  2359. $('#canvas_height').val(res.h);
  2360. $('#canvas_title').val(svgCanvas.getDocumentTitle());
  2361. $('#svg_docprops').show();
  2362. };
  2363. var showPreferences = function(){
  2364. if (preferences) return;
  2365. preferences = true;
  2366. $('#main_menu').hide();
  2367. // Update background color with current one
  2368. var blocks = $('#bg_blocks div');
  2369. var cur_bg = 'cur_background';
  2370. var canvas_bg = $.pref('bkgd_color');
  2371. var url = $.pref('bkgd_url');
  2372. // if(url) url = url[1];
  2373. blocks.each(function() {
  2374. var blk = $(this);
  2375. var is_bg = blk.css('background-color') == canvas_bg;
  2376. blk.toggleClass(cur_bg, is_bg);
  2377. if(is_bg) $('#canvas_bg_url').removeClass(cur_bg);
  2378. });
  2379. if(!canvas_bg) blocks.eq(0).addClass(cur_bg);
  2380. if(url) {
  2381. $('#canvas_bg_url').val(url);
  2382. }
  2383. $('grid_snapping_step').attr('value', curConfig.snappingStep);
  2384. if (curConfig.gridSnapping == true) {
  2385. $('#grid_snapping_on').attr('checked', 'checked');
  2386. } else {
  2387. $('#grid_snapping_on').removeAttr('checked');
  2388. }
  2389. $('#svg_prefs').show();
  2390. };
  2391. var properlySourceSizeTextArea = function(){
  2392. // TODO: remove magic numbers here and get values from CSS
  2393. var height = $('#svg_source_container').height() - 80;
  2394. $('#svg_source_textarea').css('height', height);
  2395. };
  2396. var saveSourceEditor = function(){
  2397. if (!editingsource) return;
  2398. var saveChanges = function() {
  2399. svgCanvas.clearSelection();
  2400. hideSourceEditor();
  2401. zoomImage();
  2402. populateLayers();
  2403. updateTitle();
  2404. prepPaints();
  2405. }
  2406. if (!svgCanvas.setSvgString($('#svg_source_textarea').val())) {
  2407. $.confirm(uiStrings.notification.QerrorsRevertToSource, function(ok) {
  2408. if(!ok) return false;
  2409. saveChanges();
  2410. });
  2411. } else {
  2412. saveChanges();
  2413. }
  2414. setSelectMode();
  2415. };
  2416. var updateTitle = function(title) {
  2417. title = title || svgCanvas.getDocumentTitle();
  2418. var new_title = orig_title + (title?': ' + title:'');
  2419. // Remove title update with current context info, isn't really necessary
  2420. // if(cur_context) {
  2421. // new_title = new_title + cur_context;
  2422. // }
  2423. $('title:first').text(new_title);
  2424. }
  2425. var saveDocProperties = function(){
  2426. // set title
  2427. var new_title = $('#canvas_title').val();
  2428. updateTitle(new_title);
  2429. svgCanvas.setDocumentTitle(new_title);
  2430. // update resolution
  2431. var width = $('#canvas_width'), w = width.val();
  2432. var height = $('#canvas_height'), h = height.val();
  2433. if(w != "fit" && !svgedit.units.isValidUnit('width', w)) {
  2434. $.alert(uiStrings.notification.invalidAttrValGiven);
  2435. width.parent().addClass('error');
  2436. return false;
  2437. }
  2438. width.parent().removeClass('error');
  2439. if(h != "fit" && !svgedit.units.isValidUnit('height', h)) {
  2440. $.alert(uiStrings.notification.invalidAttrValGiven);
  2441. height.parent().addClass('error');
  2442. return false;
  2443. }
  2444. height.parent().removeClass('error');
  2445. if(!svgCanvas.setResolution(w, h)) {
  2446. $.alert(uiStrings.notification.noContentToFitTo);
  2447. return false;
  2448. }
  2449. // set image save option
  2450. curPrefs.img_save = $('#image_save_opts :checked').val();
  2451. $.pref('img_save',curPrefs.img_save);
  2452. updateCanvas();
  2453. hideDocProperties();
  2454. };
  2455. var savePreferences = function() {
  2456. // set background
  2457. var color = $('#bg_blocks div.cur_background').css('background-color') || '#FFF';
  2458. setBackground(color, $('#canvas_bg_url').val());
  2459. // set language
  2460. var lang = $('#lang_select').val();
  2461. if(lang != curPrefs.lang) {
  2462. Editor.putLocale(lang);
  2463. }
  2464. // set icon size
  2465. setIconSize($('#iconsize').val());
  2466. // set grid setting
  2467. curConfig.gridSnapping = $('#grid_snapping_on')[0].checked;
  2468. curConfig.snappingStep = $('#grid_snapping_step').val();
  2469. curConfig.showRulers = $('#show_rulers')[0].checked;
  2470. $('#rulers').toggle(curConfig.showRulers);
  2471. if(curConfig.showRulers) updateRulers();
  2472. curConfig.baseUnit = $('#base_unit').val();
  2473. svgCanvas.setConfig(curConfig);
  2474. updateCanvas();
  2475. hidePreferences();
  2476. }
  2477. function setBackground(color, url) {
  2478. // if(color == curPrefs.bkgd_color && url == curPrefs.bkgd_url) return;
  2479. $.pref('bkgd_color', color);
  2480. $.pref('bkgd_url', url);
  2481. // This should be done in svgcanvas.js for the borderRect fill
  2482. svgCanvas.setBackground(color, url);
  2483. }
  2484. var setIcon = Editor.setIcon = function(elem, icon_id, forcedSize) {
  2485. var icon = (typeof icon_id === 'string') ? $.getSvgIcon(icon_id, true) : icon_id.clone();
  2486. if(!icon) {
  2487. console.log('NOTE: Icon image missing: ' + icon_id);
  2488. return;
  2489. }
  2490. $(elem).empty().append(icon);
  2491. }
  2492. var ua_prefix;
  2493. (ua_prefix = function() {
  2494. var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/;
  2495. var someScript = document.getElementsByTagName('script')[0];
  2496. for(var prop in someScript.style) {
  2497. if(regex.test(prop)) {
  2498. // test is faster than match, so it's better to perform
  2499. // that on the lot and match only when necessary
  2500. return prop.match(regex)[0];
  2501. }
  2502. }
  2503. // Nothing found so far?
  2504. if('WebkitOpacity' in someScript.style) return 'Webkit';
  2505. if('KhtmlOpacity' in someScript.style) return 'Khtml';
  2506. return '';
  2507. }());
  2508. var scaleElements = function(elems, scale) {
  2509. var prefix = '-' + ua_prefix.toLowerCase() + '-';
  2510. var sides = ['top', 'left', 'bottom', 'right'];
  2511. elems.each(function() {
  2512. // console.log('go', scale);
  2513. // Handled in CSS
  2514. // this.style[ua_prefix + 'Transform'] = 'scale(' + scale + ')';
  2515. var el = $(this);
  2516. var w = el.outerWidth() * (scale - 1);
  2517. var h = el.outerHeight() * (scale - 1);
  2518. var margins = {};
  2519. for(var i = 0; i < 4; i++) {
  2520. var s = sides[i];
  2521. var cur = el.data('orig_margin-' + s);
  2522. if(cur == null) {
  2523. cur = parseInt(el.css('margin-' + s));
  2524. // Cache the original margin
  2525. el.data('orig_margin-' + s, cur);
  2526. }
  2527. var val = cur * scale;
  2528. if(s === 'right') {
  2529. val += w;
  2530. } else if(s === 'bottom') {
  2531. val += h;
  2532. }
  2533. el.css('margin-' + s, val);
  2534. // el.css('outline', '1px solid red');
  2535. }
  2536. });
  2537. }
  2538. var setIconSize = Editor.setIconSize = function(size, force) {
  2539. if(size == curPrefs.size && !force) return;
  2540. // return;
  2541. // var elems = $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open');
  2542. console.log('size', size);
  2543. var sel_toscale = '#tools_top .toolset, #editor_panel > *, #history_panel > *,\
  2544. #main_button, #tools_left > *, #path_node_panel > *, #multiselected_panel > *,\
  2545. #g_panel > *, #tool_font_size > *, .tools_flyout';
  2546. var elems = $(sel_toscale);
  2547. var scale = 1;
  2548. if(typeof size == 'number') {
  2549. scale = size;
  2550. } else {
  2551. var icon_sizes = { s:.75, m:1, l:1.25, xl:1.5 };
  2552. scale = icon_sizes[size];
  2553. }
  2554. Editor.tool_scale = tool_scale = scale;
  2555. setFlyoutPositions();
  2556. // $('.tools_flyout').each(function() {
  2557. // var pos = $(this).position();
  2558. // console.log($(this), pos.left+(34 * scale));
  2559. // $(this).css({'left': pos.left+(34 * scale), 'top': pos.top+(77 * scale)});
  2560. // console.log('l', $(this).css('left'));
  2561. // });
  2562. // var scale = .75;//0.75;
  2563. var hidden_ps = elems.parents(':hidden');
  2564. hidden_ps.css('visibility', 'hidden').show();
  2565. scaleElements(elems, scale);
  2566. hidden_ps.css('visibility', 'visible').hide();
  2567. // console.timeEnd('elems');
  2568. // return;
  2569. $.pref('iconsize', size);
  2570. $('#iconsize').val(size);
  2571. // Change icon size
  2572. // $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open')
  2573. // .find('> svg, > img').each(function() {
  2574. // this.setAttribute('width',size_num);
  2575. // this.setAttribute('height',size_num);
  2576. // });
  2577. //
  2578. // $.resizeSvgIcons({
  2579. // '.flyout_arrow_horiz > svg, .flyout_arrow_horiz > img': size_num / 5,
  2580. // '#logo > svg, #logo > img': size_num * 1.3,
  2581. // '#tools_bottom .icon_label > *': (size_num === 16 ? 18 : size_num * .75)
  2582. // });
  2583. // if(size != 's') {
  2584. // $.resizeSvgIcons({'#layerbuttons svg, #layerbuttons img': size_num * .6});
  2585. // }
  2586. // Note that all rules will be prefixed with '#svg_editor' when parsed
  2587. var cssResizeRules = {
  2588. // ".tool_button,\
  2589. // .push_button,\
  2590. // .tool_button_current,\
  2591. // .push_button_pressed,\
  2592. // .disabled,\
  2593. // .icon_label,\
  2594. // .tools_flyout .tool_button": {
  2595. // 'width': {s: '16px', l: '32px', xl: '48px'},
  2596. // 'height': {s: '16px', l: '32px', xl: '48px'},
  2597. // 'padding': {s: '1px', l: '2px', xl: '3px'}
  2598. // },
  2599. // ".tool_sep": {
  2600. // 'height': {s: '16px', l: '32px', xl: '48px'},
  2601. // 'margin': {s: '2px 2px', l: '2px 5px', xl: '2px 8px'}
  2602. // },
  2603. // "#main_icon": {
  2604. // 'width': {s: '31px', l: '53px', xl: '75px'},
  2605. // 'height': {s: '22px', l: '42px', xl: '64px'}
  2606. // },
  2607. "#tools_top": {
  2608. 'left': 50,
  2609. 'height': 72
  2610. },
  2611. "#tools_left": {
  2612. 'width': 31,
  2613. 'top': 74
  2614. },
  2615. "div#workarea": {
  2616. 'left': 38,
  2617. 'top': 74
  2618. }
  2619. // "#tools_bottom": {
  2620. // 'left': {s: '27px', l: '46px', xl: '65px'},
  2621. // 'height': {s: '58px', l: '98px', xl: '145px'}
  2622. // },
  2623. // "#color_tools": {
  2624. // 'border-spacing': {s: '0 1px'},
  2625. // 'margin-top': {s: '-1px'}
  2626. // },
  2627. // "#color_tools .icon_label": {
  2628. // 'width': {l:'43px', xl: '60px'}
  2629. // },
  2630. // ".color_tool": {
  2631. // 'height': {s: '20px'}
  2632. // },
  2633. // "#tool_opacity": {
  2634. // 'top': {s: '1px'},
  2635. // 'height': {s: 'auto', l:'auto', xl:'auto'}
  2636. // },
  2637. // "#tools_top input, #tools_bottom input": {
  2638. // 'margin-top': {s: '2px', l: '4px', xl: '5px'},
  2639. // 'height': {s: 'auto', l: 'auto', xl: 'auto'},
  2640. // 'border': {s: '1px solid #555', l: 'auto', xl: 'auto'},
  2641. // 'font-size': {s: '.9em', l: '1.2em', xl: '1.4em'}
  2642. // },
  2643. // "#zoom_panel": {
  2644. // 'margin-top': {s: '3px', l: '4px', xl: '5px'}
  2645. // },
  2646. // "#copyright, #tools_bottom .label": {
  2647. // 'font-size': {l: '1.5em', xl: '2em'},
  2648. // 'line-height': {s: '15px'}
  2649. // },
  2650. // "#tools_bottom_2": {
  2651. // 'width': {l: '295px', xl: '355px'},
  2652. // 'top': {s: '4px'}
  2653. // },
  2654. // "#tools_top > div, #tools_top": {
  2655. // 'line-height': {s: '17px', l: '34px', xl: '50px'}
  2656. // },
  2657. // ".dropdown button": {
  2658. // 'height': {s: '18px', l: '34px', xl: '40px'},
  2659. // 'line-height': {s: '18px', l: '34px', xl: '40px'},
  2660. // 'margin-top': {s: '3px'}
  2661. // },
  2662. // "#tools_top label, #tools_bottom label": {
  2663. // 'font-size': {s: '1em', l: '1.5em', xl: '2em'},
  2664. // 'height': {s: '25px', l: '42px', xl: '64px'}
  2665. // },
  2666. // "div.toolset": {
  2667. // 'height': {s: '25px', l: '42px', xl: '64px'}
  2668. // },
  2669. // "#tool_bold, #tool_italic": {
  2670. // 'font-size': {s: '1.5em', l: '3em', xl: '4.5em'}
  2671. // },
  2672. // "#sidepanels": {
  2673. // 'top': {s: '50px', l: '88px', xl: '125px'},
  2674. // 'bottom': {s: '51px', l: '68px', xl: '65px'}
  2675. // },
  2676. // '#layerbuttons': {
  2677. // 'width': {l: '130px', xl: '175px'},
  2678. // 'height': {l: '24px', xl: '30px'}
  2679. // },
  2680. // '#layerlist': {
  2681. // 'width': {l: '128px', xl: '150px'}
  2682. // },
  2683. // '.layer_button': {
  2684. // 'width': {l: '19px', xl: '28px'},
  2685. // 'height': {l: '19px', xl: '28px'}
  2686. // },
  2687. // "input.spin-button": {
  2688. // 'background-image': {l: "url('images/spinbtn_updn_big.png')", xl: "url('images/spinbtn_updn_big.png')"},
  2689. // 'background-position': {l: '100% -5px', xl: '100% -2px'},
  2690. // 'padding-right': {l: '24px', xl: '24px' }
  2691. // },
  2692. // "input.spin-button.up": {
  2693. // 'background-position': {l: '100% -45px', xl: '100% -42px'}
  2694. // },
  2695. // "input.spin-button.down": {
  2696. // 'background-position': {l: '100% -85px', xl: '100% -82px'}
  2697. // },
  2698. // "#position_opts": {
  2699. // 'width': {all: (size_num*4) +'px'}
  2700. // }
  2701. };
  2702. var rule_elem = $('#tool_size_rules');
  2703. if(!rule_elem.length) {
  2704. rule_elem = $('<style id="tool_size_rules"><\/style>').appendTo('head');
  2705. } else {
  2706. rule_elem.empty();
  2707. }
  2708. if(size != 'm') {
  2709. var style_str = '';
  2710. $.each(cssResizeRules, function(selector, rules) {
  2711. selector = '#svg_editor ' + selector.replace(/,/g,', #svg_editor');
  2712. style_str += selector + '{';
  2713. $.each(rules, function(prop, values) {
  2714. if(typeof values === 'number') {
  2715. var val = (values * scale) + 'px';
  2716. } else if(values[size] || values.all) {
  2717. var val = (values[size] || values.all);
  2718. }
  2719. style_str += (prop + ':' + val + ';');
  2720. });
  2721. style_str += '}';
  2722. });
  2723. //this.style[ua_prefix + 'Transform'] = 'scale(' + scale + ')';
  2724. var prefix = '-' + ua_prefix.toLowerCase() + '-';
  2725. style_str += (sel_toscale + '{' + prefix + 'transform: scale(' + scale + ');}'
  2726. + ' #svg_editor div.toolset .toolset {' + prefix + 'transform: scale(1); margin: 1px !important;}' // Hack for markers
  2727. + ' #svg_editor .ui-slider {' + prefix + 'transform: scale(' + (1/scale) + ');}' // Hack for sliders
  2728. );
  2729. rule_elem.text(style_str);
  2730. }
  2731. setFlyoutPositions();
  2732. }
  2733. var cancelOverlays = function() {
  2734. $('#dialog_box').hide();
  2735. if (!editingsource && !docprops && !preferences) {
  2736. if(cur_context) {
  2737. svgCanvas.leaveContext();
  2738. }
  2739. return;
  2740. };
  2741. if (editingsource) {
  2742. if (orig_source !== $('#svg_source_textarea').val()) {
  2743. $.confirm(uiStrings.notification.QignoreSourceChanges, function(ok) {
  2744. if(ok) hideSourceEditor();
  2745. });
  2746. } else {
  2747. hideSourceEditor();
  2748. }
  2749. }
  2750. else if (docprops) {
  2751. hideDocProperties();
  2752. } else if (preferences) {
  2753. hidePreferences();
  2754. }
  2755. resetScrollPos();
  2756. };
  2757. var hideSourceEditor = function(){
  2758. $('#svg_source_editor').hide();
  2759. editingsource = false;
  2760. $('#svg_source_textarea').blur();
  2761. };
  2762. var hideDocProperties = function(){
  2763. $('#svg_docprops').hide();
  2764. $('#canvas_width,#canvas_height').removeAttr('disabled');
  2765. $('#resolution')[0].selectedIndex = 0;
  2766. $('#image_save_opts input').val([curPrefs.img_save]);
  2767. docprops = false;
  2768. };
  2769. var hidePreferences = function(){
  2770. $('#svg_prefs').hide();
  2771. preferences = false;
  2772. };
  2773. var win_wh = {width:$(window).width(), height:$(window).height()};
  2774. var resetScrollPos = $.noop, curScrollPos;
  2775. // Fix for Issue 781: Drawing area jumps to top-left corner on window resize (IE9)
  2776. if(svgedit.browser.isIE()) {
  2777. (function() {
  2778. resetScrollPos = function() {
  2779. if(workarea[0].scrollLeft === 0
  2780. && workarea[0].scrollTop === 0) {
  2781. workarea[0].scrollLeft = curScrollPos.left;
  2782. workarea[0].scrollTop = curScrollPos.top;
  2783. }
  2784. }
  2785. curScrollPos = {
  2786. left: workarea[0].scrollLeft,
  2787. top: workarea[0].scrollTop
  2788. };
  2789. $(window).resize(resetScrollPos);
  2790. svgEditor.ready(function() {
  2791. // TODO: Find better way to detect when to do this to minimize
  2792. // flickering effect
  2793. setTimeout(function() {
  2794. resetScrollPos();
  2795. }, 500);
  2796. });
  2797. workarea.scroll(function() {
  2798. curScrollPos = {
  2799. left: workarea[0].scrollLeft,
  2800. top: workarea[0].scrollTop
  2801. };
  2802. });
  2803. }());
  2804. }
  2805. $(window).resize(function(evt) {
  2806. if (editingsource) {
  2807. properlySourceSizeTextArea();
  2808. }
  2809. $.each(win_wh, function(type, val) {
  2810. var curval = $(window)[type]();
  2811. workarea[0]['scroll' + (type==='width'?'Left':'Top')] -= (curval - val)/2;
  2812. win_wh[type] = curval;
  2813. });
  2814. });
  2815. (function() {
  2816. workarea.scroll(function() {
  2817. $('#ruler_x')[0].scrollLeft = workarea[0].scrollLeft;
  2818. $('#ruler_y')[0].scrollTop = workarea[0].scrollTop;
  2819. });
  2820. }());
  2821. $('#url_notice').click(function() {
  2822. $.alert(this.title);
  2823. });
  2824. $('#change_image_url').click(promptImgURL);
  2825. function promptImgURL() {
  2826. var curhref = svgCanvas.getHref(selectedElement);
  2827. curhref = curhref.indexOf("data:") === 0?"":curhref;
  2828. $.prompt(uiStrings.notification.enterNewImgURL, curhref, function(url) {
  2829. if(url) setImageURL(url);
  2830. });
  2831. }
  2832. // added these event handlers for all the push buttons so they
  2833. // behave more like buttons being pressed-in and not images
  2834. (function() {
  2835. var toolnames = ['clear','open','save','source','delete','delete_multi','paste','clone','clone_multi','move_top','move_bottom'];
  2836. var all_tools = '';
  2837. var cur_class = 'tool_button_current';
  2838. $.each(toolnames, function(i,item) {
  2839. all_tools += '#tool_' + item + (i==toolnames.length-1?',':'');
  2840. });
  2841. $(all_tools).mousedown(function() {
  2842. $(this).addClass(cur_class);
  2843. }).bind('mousedown mouseout', function() {
  2844. $(this).removeClass(cur_class);
  2845. });
  2846. $('#tool_undo, #tool_redo').mousedown(function(){
  2847. if (!$(this).hasClass('disabled')) $(this).addClass(cur_class);
  2848. }).bind('mousedown mouseout',function(){
  2849. $(this).removeClass(cur_class);}
  2850. );
  2851. }());
  2852. // switch modifier key in tooltips if mac
  2853. // NOTE: This code is not used yet until I can figure out how to successfully bind ctrl/meta
  2854. // in Opera and Chrome
  2855. if (isMac && !window.opera) {
  2856. var shortcutButtons = ["tool_clear", "tool_save", "tool_source", "tool_undo", "tool_redo", "tool_clone"];
  2857. var i = shortcutButtons.length;
  2858. while (i--) {
  2859. var button = document.getElementById(shortcutButtons[i]);
  2860. if (button != null) {
  2861. var title = button.title;
  2862. var index = title.indexOf("Ctrl+");
  2863. button.title = [title.substr(0, index), "Cmd+", title.substr(index + 5)].join('');
  2864. }
  2865. }
  2866. }
  2867. // TODO: go back to the color boxes having white background-color and then setting
  2868. // background-image to none.png (otherwise partially transparent gradients look weird)
  2869. var colorPicker = function(elem) {
  2870. var picker = elem.attr('id') == 'stroke_color' ? 'stroke' : 'fill';
  2871. // var opacity = (picker == 'stroke' ? $('#stroke_opacity') : $('#fill_opacity'));
  2872. var paint = paintBox[picker].paint;
  2873. var title = (picker == 'stroke' ? 'Pick a Stroke Paint and Opacity' : 'Pick a Fill Paint and Opacity');
  2874. var was_none = false;
  2875. var pos = elem.position();
  2876. $("#color_picker")
  2877. .draggable({cancel:'.jGraduate_tabs, .jGraduate_colPick, .jGraduate_gradPick, .jPicker', containment: 'window'})
  2878. .css(curConfig.colorPickerCSS || {'left': pos.left, 'bottom': 50 - pos.top})
  2879. .jGraduate(
  2880. {
  2881. paint: paint,
  2882. window: { pickerTitle: title },
  2883. images: { clientPath: curConfig.jGraduatePath },
  2884. newstop: 'inverse'
  2885. },
  2886. function(p) {
  2887. paint = new $.jGraduate.Paint(p);
  2888. paintBox[picker].setPaint(paint);
  2889. svgCanvas.setPaint(picker, paint);
  2890. $('#color_picker').hide();
  2891. },
  2892. function(p) {
  2893. $('#color_picker').hide();
  2894. });
  2895. };
  2896. var updateToolButtonState = function() {
  2897. var bNoFill = (svgCanvas.getColor('fill') == 'none');
  2898. var bNoStroke = (svgCanvas.getColor('stroke') == 'none');
  2899. var buttonsNeedingStroke = [ '#tool_fhpath', '#tool_line' ];
  2900. var buttonsNeedingFillAndStroke = [ '#tools_rect .tool_button', '#tools_ellipse .tool_button', '#tool_text', '#tool_path'];
  2901. if (bNoStroke) {
  2902. for (var index in buttonsNeedingStroke) {
  2903. var button = buttonsNeedingStroke[index];
  2904. if ($(button).hasClass('tool_button_current')) {
  2905. clickSelect();
  2906. }
  2907. $(button).addClass('disabled');
  2908. }
  2909. }
  2910. else {
  2911. for (var index in buttonsNeedingStroke) {
  2912. var button = buttonsNeedingStroke[index];
  2913. $(button).removeClass('disabled');
  2914. }
  2915. }
  2916. if (bNoStroke && bNoFill) {
  2917. for (var index in buttonsNeedingFillAndStroke) {
  2918. var button = buttonsNeedingFillAndStroke[index];
  2919. if ($(button).hasClass('tool_button_current')) {
  2920. clickSelect();
  2921. }
  2922. $(button).addClass('disabled');
  2923. }
  2924. }
  2925. else {
  2926. for (var index in buttonsNeedingFillAndStroke) {
  2927. var button = buttonsNeedingFillAndStroke[index];
  2928. $(button).removeClass('disabled');
  2929. }
  2930. }
  2931. svgCanvas.runExtensions("toolButtonStateUpdate", {
  2932. nofill: bNoFill,
  2933. nostroke: bNoStroke
  2934. });
  2935. // Disable flyouts if all inside are disabled
  2936. $('.tools_flyout').each(function() {
  2937. var shower = $('#' + this.id + '_show');
  2938. var has_enabled = false;
  2939. $(this).children().each(function() {
  2940. if(!$(this).hasClass('disabled')) {
  2941. has_enabled = true;
  2942. }
  2943. });
  2944. shower.toggleClass('disabled', !has_enabled);
  2945. });
  2946. operaRepaint();
  2947. };
  2948. var PaintBox = function(container, type) {
  2949. var cur = curConfig[type === 'fill' ? 'initFill' : 'initStroke'];
  2950. // set up gradients to be used for the buttons
  2951. var svgdocbox = new DOMParser().parseFromString(
  2952. '<svg xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%"\
  2953. fill="#' + cur.color + '" opacity="' + cur.opacity + '"/>\
  2954. <defs><linearGradient id="gradbox_"/></defs></svg>', 'text/xml');
  2955. var docElem = svgdocbox.documentElement;
  2956. docElem = $(container)[0].appendChild(document.importNode(docElem, true));
  2957. docElem.setAttribute('width',16.5);
  2958. this.rect = docElem.firstChild;
  2959. this.defs = docElem.getElementsByTagName('defs')[0];
  2960. this.grad = this.defs.firstChild;
  2961. this.paint = new $.jGraduate.Paint({solidColor: cur.color});
  2962. this.type = type;
  2963. this.setPaint = function(paint, apply) {
  2964. this.paint = paint;
  2965. var fillAttr = "none";
  2966. var ptype = paint.type;
  2967. var opac = paint.alpha / 100;
  2968. switch ( ptype ) {
  2969. case 'solidColor':
  2970. fillAttr = "#" + paint[ptype];
  2971. break;
  2972. case 'linearGradient':
  2973. case 'radialGradient':
  2974. this.defs.removeChild(this.grad);
  2975. this.grad = this.defs.appendChild(paint[ptype]);
  2976. var id = this.grad.id = 'gradbox_' + this.type;
  2977. fillAttr = "url(#" + id + ')';
  2978. }
  2979. this.rect.setAttribute('fill', fillAttr);
  2980. this.rect.setAttribute('opacity', opac);
  2981. if(apply) {
  2982. svgCanvas.setColor(this.type, paintColor, true);
  2983. svgCanvas.setPaintOpacity(this.type, paintOpacity, true);
  2984. }
  2985. }
  2986. this.update = function(apply) {
  2987. if(!selectedElement) return;
  2988. var type = this.type;
  2989. switch ( selectedElement.tagName ) {
  2990. case 'use':
  2991. case 'image':
  2992. case 'foreignObject':
  2993. // These elements don't have fill or stroke, so don't change
  2994. // the current value
  2995. return;
  2996. case 'g':
  2997. case 'a':
  2998. var gPaint = null;
  2999. var childs = selectedElement.getElementsByTagName('*');
  3000. for(var i = 0, len = childs.length; i < len; i++) {
  3001. var elem = childs[i];
  3002. var p = elem.getAttribute(type);
  3003. if(i === 0) {
  3004. gPaint = p;
  3005. } else if(gPaint !== p) {
  3006. gPaint = null;
  3007. break;
  3008. }
  3009. }
  3010. if(gPaint === null) {
  3011. // No common color, don't update anything
  3012. var paintColor = null;
  3013. return;
  3014. }
  3015. var paintColor = gPaint;
  3016. var paintOpacity = 1;
  3017. break;
  3018. default:
  3019. var paintOpacity = parseFloat(selectedElement.getAttribute(type + "-opacity"));
  3020. if (isNaN(paintOpacity)) {
  3021. paintOpacity = 1.0;
  3022. }
  3023. var defColor = type === "fill" ? "black" : "none";
  3024. var paintColor = selectedElement.getAttribute(type) || defColor;
  3025. }
  3026. if(apply) {
  3027. svgCanvas.setColor(type, paintColor, true);
  3028. svgCanvas.setPaintOpacity(type, paintOpacity, true);
  3029. }
  3030. paintOpacity *= 100;
  3031. var paint = getPaint(paintColor, paintOpacity, type);
  3032. // update the rect inside #fill_color/#stroke_color
  3033. this.setPaint(paint);
  3034. }
  3035. this.prep = function() {
  3036. var ptype = this.paint.type;
  3037. switch ( ptype ) {
  3038. case 'linearGradient':
  3039. case 'radialGradient':
  3040. var paint = new $.jGraduate.Paint({copy: this.paint});
  3041. svgCanvas.setPaint(type, paint);
  3042. }
  3043. }
  3044. };
  3045. paintBox.fill = new PaintBox('#fill_color', 'fill');
  3046. paintBox.stroke = new PaintBox('#stroke_color', 'stroke');
  3047. $('#stroke_width').val(curConfig.initStroke.width);
  3048. $('#group_opacity').val(curConfig.initOpacity * 100);
  3049. // Use this SVG elem to test vectorEffect support
  3050. var test_el = paintBox.fill.rect.cloneNode(false);
  3051. test_el.setAttribute('style','vector-effect:non-scaling-stroke');
  3052. var supportsNonSS = (test_el.style.vectorEffect === 'non-scaling-stroke');
  3053. test_el.removeAttribute('style');
  3054. var svgdocbox = paintBox.fill.rect.ownerDocument;
  3055. // Use this to test support for blur element. Seems to work to test support in Webkit
  3056. var blur_test = svgdocbox.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur');
  3057. if(typeof blur_test.stdDeviationX === "undefined") {
  3058. $('#tool_blur').hide();
  3059. }
  3060. $(blur_test).remove();
  3061. // Test for zoom icon support
  3062. (function() {
  3063. var pre = '-' + ua_prefix.toLowerCase() + '-zoom-';
  3064. var zoom = pre + 'in';
  3065. workarea.css('cursor', zoom);
  3066. if(workarea.css('cursor') === zoom) {
  3067. zoomInIcon = zoom;
  3068. zoomOutIcon = pre + 'out';
  3069. }
  3070. workarea.css('cursor', 'auto');
  3071. }());
  3072. // Test for embedImage support (use timeout to not interfere with page load)
  3073. setTimeout(function() {
  3074. svgCanvas.embedImage('images/logo.png', function(datauri) {
  3075. if(!datauri) {
  3076. // Disable option
  3077. $('#image_save_opts [value=embed]').attr('disabled','disabled');
  3078. $('#image_save_opts input').val(['ref']);
  3079. curPrefs.img_save = 'ref';
  3080. $('#image_opt_embed').css('color','#666').attr('title',uiStrings.notification.featNotSupported);
  3081. }
  3082. });
  3083. },1000);
  3084. $('#fill_color, #tool_fill .icon_label').click(function(){
  3085. colorPicker($('#fill_color'));
  3086. updateToolButtonState();
  3087. });
  3088. $('#stroke_color, #tool_stroke .icon_label').click(function(){
  3089. colorPicker($('#stroke_color'));
  3090. updateToolButtonState();
  3091. });
  3092. $('#group_opacityLabel').click(function() {
  3093. $('#opacity_dropdown button').mousedown();
  3094. $(window).mouseup();
  3095. });
  3096. $('#zoomLabel').click(function() {
  3097. $('#zoom_dropdown button').mousedown();
  3098. $(window).mouseup();
  3099. });
  3100. $('#tool_move_top').mousedown(function(evt){
  3101. $('#tools_stacking').show();
  3102. evt.preventDefault();
  3103. });
  3104. $('.layer_button').mousedown(function() {
  3105. $(this).addClass('layer_buttonpressed');
  3106. }).mouseout(function() {
  3107. $(this).removeClass('layer_buttonpressed');
  3108. }).mouseup(function() {
  3109. $(this).removeClass('layer_buttonpressed');
  3110. });
  3111. $('.push_button').mousedown(function() {
  3112. if (!$(this).hasClass('disabled')) {
  3113. $(this).addClass('push_button_pressed').removeClass('push_button');
  3114. }
  3115. }).mouseout(function() {
  3116. $(this).removeClass('push_button_pressed').addClass('push_button');
  3117. }).mouseup(function() {
  3118. $(this).removeClass('push_button_pressed').addClass('push_button');
  3119. });
  3120. $('#layer_new').click(function() {
  3121. var i = svgCanvas.getCurrentDrawing().getNumLayers();
  3122. do {
  3123. var uniqName = uiStrings.layers.layer + " " + ++i;
  3124. } while(svgCanvas.getCurrentDrawing().hasLayer(uniqName));
  3125. $.prompt(uiStrings.notification.enterUniqueLayerName,uniqName, function(newName) {
  3126. if (!newName) return;
  3127. if (svgCanvas.getCurrentDrawing().hasLayer(newName)) {
  3128. $.alert(uiStrings.notification.dupeLayerName);
  3129. return;
  3130. }
  3131. svgCanvas.createLayer(newName);
  3132. updateContextPanel();
  3133. populateLayers();
  3134. });
  3135. });
  3136. function deleteLayer() {
  3137. if (svgCanvas.deleteCurrentLayer()) {
  3138. updateContextPanel();
  3139. populateLayers();
  3140. // This matches what SvgCanvas does
  3141. // TODO: make this behavior less brittle (svg-editor should get which
  3142. // layer is selected from the canvas and then select that one in the UI)
  3143. $('#layerlist tr.layer').removeClass("layersel");
  3144. $('#layerlist tr.layer:first').addClass("layersel");
  3145. }
  3146. }
  3147. function cloneLayer() {
  3148. var name = svgCanvas.getCurrentDrawing().getCurrentLayerName() + ' copy';
  3149. $.prompt(uiStrings.notification.enterUniqueLayerName, name, function(newName) {
  3150. if (!newName) return;
  3151. if (svgCanvas.getCurrentDrawing().hasLayer(newName)) {
  3152. $.alert(uiStrings.notification.dupeLayerName);
  3153. return;
  3154. }
  3155. svgCanvas.cloneLayer(newName);
  3156. updateContextPanel();
  3157. populateLayers();
  3158. });
  3159. }
  3160. function mergeLayer() {
  3161. if($('#layerlist tr.layersel').index() == svgCanvas.getCurrentDrawing().getNumLayers()-1) return;
  3162. svgCanvas.mergeLayer();
  3163. updateContextPanel();
  3164. populateLayers();
  3165. }
  3166. function moveLayer(pos) {
  3167. var curIndex = $('#layerlist tr.layersel').index();
  3168. var total = svgCanvas.getCurrentDrawing().getNumLayers();
  3169. if(curIndex > 0 || curIndex < total-1) {
  3170. curIndex += pos;
  3171. svgCanvas.setCurrentLayerPosition(total-curIndex-1);
  3172. populateLayers();
  3173. }
  3174. }
  3175. $('#layer_delete').click(deleteLayer);
  3176. $('#layer_up').click(function() {
  3177. moveLayer(-1);
  3178. });
  3179. $('#layer_down').click(function() {
  3180. moveLayer(1);
  3181. });
  3182. $('#layer_rename').click(function() {
  3183. var curIndex = $('#layerlist tr.layersel').prevAll().length;
  3184. var oldName = $('#layerlist tr.layersel td.layername').text();
  3185. $.prompt(uiStrings.notification.enterNewLayerName,"", function(newName) {
  3186. if (!newName) return;
  3187. if (oldName == newName || svgCanvas.getCurrentDrawing().hasLayer(newName)) {
  3188. $.alert(uiStrings.notification.layerHasThatName);
  3189. return;
  3190. }
  3191. svgCanvas.renameCurrentLayer(newName);
  3192. populateLayers();
  3193. });
  3194. });
  3195. var SIDEPANEL_MAXWIDTH = 300;
  3196. var SIDEPANEL_OPENWIDTH = 150;
  3197. var sidedrag = -1, sidedragging = false, allowmove = false;
  3198. var resizePanel = function(evt) {
  3199. if (!allowmove) return;
  3200. if (sidedrag == -1) return;
  3201. sidedragging = true;
  3202. var deltax = sidedrag - evt.pageX;
  3203. var sidepanels = $('#sidepanels');
  3204. var sidewidth = parseInt(sidepanels.css('width'));
  3205. if (sidewidth+deltax > SIDEPANEL_MAXWIDTH) {
  3206. deltax = SIDEPANEL_MAXWIDTH - sidewidth;
  3207. sidewidth = SIDEPANEL_MAXWIDTH;
  3208. }
  3209. else if (sidewidth+deltax < 2) {
  3210. deltax = 2 - sidewidth;
  3211. sidewidth = 2;
  3212. }
  3213. if (deltax == 0) return;
  3214. sidedrag -= deltax;
  3215. var layerpanel = $('#layerpanel');
  3216. workarea.css('right', parseInt(workarea.css('right'))+deltax);
  3217. sidepanels.css('width', parseInt(sidepanels.css('width'))+deltax);
  3218. layerpanel.css('width', parseInt(layerpanel.css('width'))+deltax);
  3219. var ruler_x = $('#ruler_x');
  3220. ruler_x.css('right', parseInt(ruler_x.css('right')) + deltax);
  3221. }
  3222. $('#sidepanel_handle')
  3223. .mousedown(function(evt) {
  3224. sidedrag = evt.pageX;
  3225. $(window).mousemove(resizePanel);
  3226. allowmove = false;
  3227. // Silly hack for Chrome, which always runs mousemove right after mousedown
  3228. setTimeout(function() {
  3229. allowmove = true;
  3230. }, 20);
  3231. })
  3232. .mouseup(function(evt) {
  3233. if (!sidedragging) toggleSidePanel();
  3234. sidedrag = -1;
  3235. sidedragging = false;
  3236. });
  3237. $(window).mouseup(function() {
  3238. sidedrag = -1;
  3239. sidedragging = false;
  3240. $('#svg_editor').unbind('mousemove', resizePanel);
  3241. });
  3242. // if width is non-zero, then fully close it, otherwise fully open it
  3243. // the optional close argument forces the side panel closed
  3244. var toggleSidePanel = function(close){
  3245. var w = parseInt($('#sidepanels').css('width'));
  3246. var deltax = (w > 2 || close ? 2 : SIDEPANEL_OPENWIDTH) - w;
  3247. var sidepanels = $('#sidepanels');
  3248. var layerpanel = $('#layerpanel');
  3249. var ruler_x = $('#ruler_x');
  3250. workarea.css('right', parseInt(workarea.css('right')) + deltax);
  3251. sidepanels.css('width', parseInt(sidepanels.css('width')) + deltax);
  3252. layerpanel.css('width', parseInt(layerpanel.css('width')) + deltax);
  3253. ruler_x.css('right', parseInt(ruler_x.css('right')) + deltax);
  3254. };
  3255. // this function highlights the layer passed in (by fading out the other layers)
  3256. // if no layer is passed in, this function restores the other layers
  3257. var toggleHighlightLayer = function(layerNameToHighlight) {
  3258. var curNames = new Array(svgCanvas.getCurrentDrawing().getNumLayers());
  3259. for (var i = 0; i < curNames.length; ++i) { curNames[i] = svgCanvas.getCurrentDrawing().getLayerName(i); }
  3260. if (layerNameToHighlight) {
  3261. for (var i = 0; i < curNames.length; ++i) {
  3262. if (curNames[i] != layerNameToHighlight) {
  3263. svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 0.5);
  3264. }
  3265. }
  3266. }
  3267. else {
  3268. for (var i = 0; i < curNames.length; ++i) {
  3269. svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 1.0);
  3270. }
  3271. }
  3272. };
  3273. var populateLayers = function(){
  3274. var layerlist = $('#layerlist tbody');
  3275. var selLayerNames = $('#selLayerNames');
  3276. layerlist.empty();
  3277. selLayerNames.empty();
  3278. var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName();
  3279. var layer = svgCanvas.getCurrentDrawing().getNumLayers();
  3280. var icon = $.getSvgIcon('eye');
  3281. // we get the layers in the reverse z-order (the layer rendered on top is listed first)
  3282. while (layer--) {
  3283. var name = svgCanvas.getCurrentDrawing().getLayerName(layer);
  3284. // contenteditable=\"true\"
  3285. var appendstr = "<tr class=\"layer";
  3286. if (name == currentLayerName) {
  3287. appendstr += " layersel"
  3288. }
  3289. appendstr += "\">";
  3290. if (svgCanvas.getCurrentDrawing().getLayerVisibility(name)) {
  3291. appendstr += "<td class=\"layervis\"/><td class=\"layername\" >" + name + "</td></tr>";
  3292. }
  3293. else {
  3294. appendstr += "<td class=\"layervis layerinvis\"/><td class=\"layername\" >" + name + "</td></tr>";
  3295. }
  3296. layerlist.append(appendstr);
  3297. selLayerNames.append("<option value=\"" + name + "\">" + name + "</option>");
  3298. }
  3299. if(icon !== undefined) {
  3300. var copy = icon.clone();
  3301. $('td.layervis',layerlist).append(icon.clone());
  3302. $.resizeSvgIcons({'td.layervis .svg_icon':14});
  3303. }
  3304. // handle selection of layer
  3305. $('#layerlist td.layername')
  3306. .mouseup(function(evt){
  3307. $('#layerlist tr.layer').removeClass("layersel");
  3308. var row = $(this.parentNode);
  3309. row.addClass("layersel");
  3310. svgCanvas.setCurrentLayer(this.textContent);
  3311. evt.preventDefault();
  3312. })
  3313. .mouseover(function(evt){
  3314. $(this).css({"font-style": "italic", "color":"blue"});
  3315. toggleHighlightLayer(this.textContent);
  3316. })
  3317. .mouseout(function(evt){
  3318. $(this).css({"font-style": "normal", "color":"black"});
  3319. toggleHighlightLayer();
  3320. });
  3321. $('#layerlist td.layervis').click(function(evt){
  3322. var row = $(this.parentNode).prevAll().length;
  3323. var name = $('#layerlist tr.layer:eq(' + row + ') td.layername').text();
  3324. var vis = $(this).hasClass('layerinvis');
  3325. svgCanvas.setLayerVisibility(name, vis);
  3326. if (vis) {
  3327. $(this).removeClass('layerinvis');
  3328. }
  3329. else {
  3330. $(this).addClass('layerinvis');
  3331. }
  3332. });
  3333. // if there were too few rows, let's add a few to make it not so lonely
  3334. var num = 5 - $('#layerlist tr.layer').size();
  3335. while (num-- > 0) {
  3336. // FIXME: there must a better way to do this
  3337. layerlist.append("<tr><td style=\"color:white\">_</td><td/></tr>");
  3338. }
  3339. };
  3340. populateLayers();
  3341. // function changeResolution(x,y) {
  3342. // var zoom = svgCanvas.getResolution().zoom;
  3343. // setResolution(x * zoom, y * zoom);
  3344. // }
  3345. var centerCanvas = function() {
  3346. // this centers the canvas vertically in the workarea (horizontal handled in CSS)
  3347. workarea.css('line-height', workarea.height() + 'px');
  3348. };
  3349. $(window).bind('load resize', centerCanvas);
  3350. function stepFontSize(elem, step) {
  3351. var orig_val = elem.value-0;
  3352. var sug_val = orig_val + step;
  3353. var increasing = sug_val >= orig_val;
  3354. if(step === 0) return orig_val;
  3355. if(orig_val >= 24) {
  3356. if(increasing) {
  3357. return Math.round(orig_val * 1.1);
  3358. } else {
  3359. return Math.round(orig_val / 1.1);
  3360. }
  3361. } else if(orig_val <= 1) {
  3362. if(increasing) {
  3363. return orig_val * 2;
  3364. } else {
  3365. return orig_val / 2;
  3366. }
  3367. } else {
  3368. return sug_val;
  3369. }
  3370. }
  3371. function stepZoom(elem, step) {
  3372. var orig_val = elem.value-0;
  3373. if(orig_val === 0) return 100;
  3374. var sug_val = orig_val + step;
  3375. if(step === 0) return orig_val;
  3376. if(orig_val >= 100) {
  3377. return sug_val;
  3378. } else {
  3379. if(sug_val >= orig_val) {
  3380. return orig_val * 2;
  3381. } else {
  3382. return orig_val / 2;
  3383. }
  3384. }
  3385. }
  3386. // function setResolution(w, h, center) {
  3387. // updateCanvas();
  3388. // // w-=0; h-=0;
  3389. // // $('#svgcanvas').css( { 'width': w, 'height': h } );
  3390. // // $('#canvas_width').val(w);
  3391. // // $('#canvas_height').val(h);
  3392. // //
  3393. // // if(center) {
  3394. // // var w_area = workarea;
  3395. // // var scroll_y = h/2 - w_area.height()/2;
  3396. // // var scroll_x = w/2 - w_area.width()/2;
  3397. // // w_area[0].scrollTop = scroll_y;
  3398. // // w_area[0].scrollLeft = scroll_x;
  3399. // // }
  3400. // }
  3401. $('#resolution').change(function(){
  3402. var wh = $('#canvas_width,#canvas_height');
  3403. if(!this.selectedIndex) {
  3404. if($('#canvas_width').val() == 'fit') {
  3405. wh.removeAttr("disabled").val(100);
  3406. }
  3407. } else if(this.value == 'content') {
  3408. wh.val('fit').attr("disabled","disabled");
  3409. } else {
  3410. var dims = this.value.split('x');
  3411. $('#canvas_width').val(dims[0]);
  3412. $('#canvas_height').val(dims[1]);
  3413. wh.removeAttr("disabled");
  3414. }
  3415. });
  3416. //Prevent browser from erroneously repopulating fields
  3417. $('input,select').attr("autocomplete","off");
  3418. // Associate all button actions as well as non-button keyboard shortcuts
  3419. var Actions = function() {
  3420. // sel:'selector', fn:function, evt:'event', key:[key, preventDefault, NoDisableInInput]
  3421. var tool_buttons = [
  3422. {sel:'#tool_select', fn: clickSelect, evt: 'click', key: ['V', true]},
  3423. {sel:'#tool_fhpath', fn: clickFHPath, evt: 'click', key: ['Q', true]},
  3424. {sel:'#tool_line', fn: clickLine, evt: 'click', key: ['L', true]},
  3425. {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: ['R', true], parent: '#tools_rect', icon: 'rect'},
  3426. {sel:'#tool_square', fn: clickSquare, evt: 'mouseup', parent: '#tools_rect', icon: 'square'},
  3427. {sel:'#tool_fhrect', fn: clickFHRect, evt: 'mouseup', parent: '#tools_rect', icon: 'fh_rect'},
  3428. {sel:'#tool_ellipse', fn: clickEllipse, evt: 'mouseup', key: ['E', true], parent: '#tools_ellipse', icon: 'ellipse'},
  3429. {sel:'#tool_circle', fn: clickCircle, evt: 'mouseup', parent: '#tools_ellipse', icon: 'circle'},
  3430. {sel:'#tool_fhellipse', fn: clickFHEllipse, evt: 'mouseup', parent: '#tools_ellipse', icon: 'fh_ellipse'},
  3431. {sel:'#tool_path', fn: clickPath, evt: 'click', key: ['P', true]},
  3432. {sel:'#tool_text', fn: clickText, evt: 'click', key: ['T', true]},
  3433. {sel:'#tool_image', fn: clickImage, evt: 'mouseup'},
  3434. {sel:'#tool_zoom', fn: clickZoom, evt: 'mouseup', key: ['Z', true]},
  3435. {sel:'#tool_clear', fn: clickClear, evt: 'mouseup', key: ['N', true]},
  3436. {sel:'#tool_save', fn: function() { editingsource?saveSourceEditor():clickSave()}, evt: 'mouseup', key: ['S', true]},
  3437. {sel:'#tool_export', fn: clickExport, evt: 'mouseup'},
  3438. {sel:'#tool_open', fn: clickOpen, evt: 'mouseup', key: ['O', true]},
  3439. {sel:'#tool_import', fn: clickImport, evt: 'mouseup'},
  3440. {sel:'#tool_source', fn: showSourceEditor, evt: 'click', key: ['U', true]},
  3441. {sel:'#tool_wireframe', fn: clickWireframe, evt: 'click', key: ['F', true]},
  3442. {sel:'#tool_source_cancel,#svg_source_overlay,#tool_docprops_cancel,#tool_prefs_cancel', fn: cancelOverlays, evt: 'click', key: ['esc', false, false], hidekey: true},
  3443. {sel:'#tool_source_save', fn: saveSourceEditor, evt: 'click'},
  3444. {sel:'#tool_docprops_save', fn: saveDocProperties, evt: 'click'},
  3445. {sel:'#tool_docprops', fn: showDocProperties, evt: 'mouseup', key: ['D', true]},
  3446. {sel:'#tool_prefs_save', fn: savePreferences, evt: 'click'},
  3447. {sel:'#tool_prefs_option', fn: function() {showPreferences();return false}, evt: 'mouseup'},
  3448. {sel:'#tool_delete,#tool_delete_multi', fn: deleteSelected, evt: 'click', key: ['del/backspace', true]},
  3449. {sel:'#tool_reorient', fn: reorientPath, evt: 'click'},
  3450. {sel:'#tool_node_link', fn: linkControlPoints, evt: 'click'},
  3451. {sel:'#tool_node_clone', fn: clonePathNode, evt: 'click'},
  3452. {sel:'#tool_node_delete', fn: deletePathNode, evt: 'click'},
  3453. {sel:'#tool_openclose_path', fn: opencloseSubPath, evt: 'click'},
  3454. {sel:'#tool_add_subpath', fn: addSubPath, evt: 'click'},
  3455. {sel:'#tool_move_top', fn: moveToTopSelected, evt: 'click', key: 'ctrl+shift+]'},
  3456. {sel:'#tool_move_bottom', fn: moveToBottomSelected, evt: 'click', key: 'ctrl+shift+['},
  3457. {sel:'#tool_topath', fn: convertToPath, evt: 'click'},
  3458. {sel:'#tool_make_link,#tool_make_link_multi', fn: makeHyperlink, evt: 'click'},
  3459. {sel:'#tool_undo', fn: clickUndo, evt: 'click', key: ['Z', true]},
  3460. {sel:'#tool_redo', fn: clickRedo, evt: 'click', key: ['Y', true]},
  3461. {sel:'#tool_clone,#tool_clone_multi', fn: clickClone, evt: 'click', key: ['D', true]},
  3462. {sel:'#tool_group', fn: clickGroup, evt: 'click', key: ['G', true]},
  3463. {sel:'#tool_ungroup', fn: clickGroup, evt: 'click'},
  3464. {sel:'#tool_unlink_use', fn: clickGroup, evt: 'click'},
  3465. {sel:'[id^=tool_align]', fn: clickAlign, evt: 'click'},
  3466. // these two lines are required to make Opera work properly with the flyout mechanism
  3467. // {sel:'#tools_rect_show', fn: clickRect, evt: 'click'},
  3468. // {sel:'#tools_ellipse_show', fn: clickEllipse, evt: 'click'},
  3469. {sel:'#tool_bold', fn: clickBold, evt: 'mousedown'},
  3470. {sel:'#tool_italic', fn: clickItalic, evt: 'mousedown'},
  3471. {sel:'#sidepanel_handle', fn: toggleSidePanel, key: ['X']},
  3472. {sel:'#copy_save_done', fn: cancelOverlays, evt: 'click'},
  3473. // Shortcuts not associated with buttons
  3474. {key: 'ctrl+left', fn: function(){rotateSelected(0,1)}},
  3475. {key: 'ctrl+right', fn: function(){rotateSelected(1,1)}},
  3476. {key: 'ctrl+shift+left', fn: function(){rotateSelected(0,5)}},
  3477. {key: 'ctrl+shift+right', fn: function(){rotateSelected(1,5)}},
  3478. {key: 'shift+O', fn: selectPrev},
  3479. {key: 'shift+P', fn: selectNext},
  3480. {key: [modKey+'up', true], fn: function(){zoomImage(2);}},
  3481. {key: [modKey+'down', true], fn: function(){zoomImage(.5);}},
  3482. {key: [modKey+']', true], fn: function(){moveUpDownSelected('Up');}},
  3483. {key: [modKey+'[', true], fn: function(){moveUpDownSelected('Down');}},
  3484. {key: ['up', true], fn: function(){moveSelected(0,-1);}},
  3485. {key: ['down', true], fn: function(){moveSelected(0,1);}},
  3486. {key: ['left', true], fn: function(){moveSelected(-1,0);}},
  3487. {key: ['right', true], fn: function(){moveSelected(1,0);}},
  3488. {key: 'shift+up', fn: function(){moveSelected(0,-10)}},
  3489. {key: 'shift+down', fn: function(){moveSelected(0,10)}},
  3490. {key: 'shift+left', fn: function(){moveSelected(-10,0)}},
  3491. {key: 'shift+right', fn: function(){moveSelected(10,0)}},
  3492. {key: ['alt+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-1)}},
  3493. {key: ['alt+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,1)}},
  3494. {key: ['alt+left', true], fn: function(){svgCanvas.cloneSelectedElements(-1,0)}},
  3495. {key: ['alt+right', true], fn: function(){svgCanvas.cloneSelectedElements(1,0)}},
  3496. {key: ['alt+shift+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-10)}},
  3497. {key: ['alt+shift+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,10)}},
  3498. {key: ['alt+shift+left', true], fn: function(){svgCanvas.cloneSelectedElements(-10,0)}},
  3499. {key: ['alt+shift+right', true], fn: function(){svgCanvas.cloneSelectedElements(10,0)}},
  3500. {key: 'A', fn: function(){svgCanvas.selectAllInCurrentLayer();}},
  3501. // Standard shortcuts
  3502. {key: modKey+'z', fn: clickUndo},
  3503. {key: modKey + 'shift+z', fn: clickRedo},
  3504. {key: modKey + 'y', fn: clickRedo},
  3505. {key: modKey+'x', fn: cutSelected},
  3506. {key: modKey+'c', fn: copySelected},
  3507. {key: modKey+'v', fn: pasteInCenter}
  3508. ];
  3509. // Tooltips not directly associated with a single function
  3510. var key_assocs = {
  3511. '4/Shift+4': '#tools_rect_show',
  3512. '5/Shift+5': '#tools_ellipse_show'
  3513. };
  3514. return {
  3515. setAll: function() {
  3516. var flyouts = {};
  3517. $.each(tool_buttons, function(i, opts) {
  3518. // Bind function to button
  3519. if(opts.sel) {
  3520. var btn = $(opts.sel);
  3521. if (btn.length == 0) return true; // Skip if markup does not exist
  3522. if(opts.evt) {
  3523. btn[opts.evt](opts.fn);
  3524. }
  3525. // Add to parent flyout menu, if able to be displayed
  3526. if(opts.parent && $(opts.parent + '_show').length != 0) {
  3527. var f_h = $(opts.parent);
  3528. if(!f_h.length) {
  3529. f_h = makeFlyoutHolder(opts.parent.substr(1));
  3530. }
  3531. f_h.append(btn);
  3532. if(!$.isArray(flyouts[opts.parent])) {
  3533. flyouts[opts.parent] = [];
  3534. }
  3535. flyouts[opts.parent].push(opts);
  3536. }
  3537. }
  3538. // Bind function to shortcut key
  3539. if(opts.key) {
  3540. // Set shortcut based on options
  3541. var keyval, shortcut = '', disInInp = true, fn = opts.fn, pd = false;
  3542. if($.isArray(opts.key)) {
  3543. keyval = opts.key[0];
  3544. if(opts.key.length > 1) pd = opts.key[1];
  3545. if(opts.key.length > 2) disInInp = opts.key[2];
  3546. } else {
  3547. keyval = opts.key;
  3548. }
  3549. keyval += '';
  3550. $.each(keyval.split('/'), function(i, key) {
  3551. $(document).bind('keydown', key, function(e) {
  3552. fn();
  3553. if(pd) {
  3554. e.preventDefault();
  3555. }
  3556. // Prevent default on ALL keys?
  3557. return false;
  3558. });
  3559. });
  3560. // Put shortcut in title
  3561. if(opts.sel && !opts.hidekey) {
  3562. var new_title = btn.attr('title').split('[')[0] + ' (' + keyval + ')';
  3563. key_assocs[keyval] = opts.sel;
  3564. // Disregard for menu items
  3565. if(!btn.parents('#main_menu').length) {
  3566. btn.attr('title', new_title);
  3567. }
  3568. }
  3569. }
  3570. });
  3571. // Setup flyouts
  3572. setupFlyouts(flyouts);
  3573. // Misc additional actions
  3574. // Make "return" keypress trigger the change event
  3575. $('.attr_changer, #image_url').bind('keydown', 'return',
  3576. function(evt) {$(this).change();evt.preventDefault();}
  3577. );
  3578. $(window).bind('keydown', 'tab', function(e) {
  3579. if(ui_context === 'canvas') {
  3580. e.preventDefault();
  3581. selectNext();
  3582. }
  3583. }).bind('keydown', 'shift+tab', function(e) {
  3584. if(ui_context === 'canvas') {
  3585. e.preventDefault();
  3586. selectPrev();
  3587. }
  3588. });
  3589. $('#tool_zoom').dblclick(dblclickZoom);
  3590. },
  3591. setTitles: function() {
  3592. $.each(key_assocs, function(keyval, sel) {
  3593. var menu = ($(sel).parents('#main_menu').length);
  3594. $(sel).each(function() {
  3595. if(menu) {
  3596. var t = $(this).text().split(' [')[0];
  3597. } else {
  3598. var t = this.title.split(' [')[0];
  3599. }
  3600. var key_str = '';
  3601. // Shift+Up
  3602. $.each(keyval.split('/'), function(i, key) {
  3603. var mod_bits = key.split('+'), mod = '';
  3604. if(mod_bits.length > 1) {
  3605. mod = mod_bits[0] + '+';
  3606. key = mod_bits[1];
  3607. }
  3608. key_str += (i?'/':'') + mod + (uiStrings['key_'+key] || key);
  3609. });
  3610. if(menu) {
  3611. this.lastChild.textContent = t +' ['+key_str+']';
  3612. } else {
  3613. this.title = t +' ['+key_str+']';
  3614. }
  3615. });
  3616. });
  3617. },
  3618. getButtonData: function(sel) {
  3619. var b;
  3620. $.each(tool_buttons, function(i, btn) {
  3621. if(btn.sel === sel) b = btn;
  3622. });
  3623. return b;
  3624. }
  3625. };
  3626. }();
  3627. Actions.setAll();
  3628. // Select given tool
  3629. Editor.ready(function() {
  3630. var tool,
  3631. itool = curConfig.initTool,
  3632. container = $("#tools_left, #svg_editor .tools_flyout"),
  3633. pre_tool = container.find("#tool_" + itool),
  3634. reg_tool = container.find("#" + itool);
  3635. if(pre_tool.length) {
  3636. tool = pre_tool;
  3637. } else if(reg_tool.length){
  3638. tool = reg_tool;
  3639. } else {
  3640. tool = $("#tool_select");
  3641. }
  3642. tool.click().mouseup();
  3643. if(curConfig.wireframe) {
  3644. $('#tool_wireframe').click();
  3645. }
  3646. if(curConfig.showlayers) {
  3647. toggleSidePanel();
  3648. }
  3649. $('#rulers').toggle(!!curConfig.showRulers);
  3650. $('#show_rulers')[0].checked = curConfig.showRulers;
  3651. if(curConfig.gridSnapping) {
  3652. $('#grid_snapping_on')[0].checked = true;
  3653. }
  3654. if(curConfig.baseUnit) {
  3655. $('#base_unit').val(curConfig.baseUnit);
  3656. }
  3657. if(curConfig.snappingStep) {
  3658. $('#grid_snapping_step').val(curConfig.snappingStep);
  3659. }
  3660. });
  3661. $('#rect_rx').SpinButton({ min: 0, max: 1000, step: 1, callback: changeRectRadius });
  3662. $('#stroke_width').SpinButton({ min: 0, max: 99, step: 1, smallStep: 0.1, callback: changeStrokeWidth });
  3663. $('#angle').SpinButton({ min: -180, max: 180, step: 5, callback: changeRotationAngle });
  3664. $('#font_size').SpinButton({ step: 1, min: 0.001, stepfunc: stepFontSize, callback: changeFontSize });
  3665. $('#group_opacity').SpinButton({ step: 5, min: 0, max: 100, callback: changeOpacity });
  3666. $('#blur').SpinButton({ step: .1, min: 0, max: 10, callback: changeBlur });
  3667. $('#zoom').SpinButton({ min: 0.001, max: 10000, step: 50, stepfunc: stepZoom, callback: changeZoom })
  3668. // Set default zoom
  3669. .val(svgCanvas.getZoom() * 100);
  3670. $("#workarea").contextMenu({
  3671. menu: 'cmenu_canvas',
  3672. inSpeed: 0
  3673. },
  3674. function(action, el, pos) {
  3675. switch ( action ) {
  3676. case 'delete':
  3677. deleteSelected();
  3678. break;
  3679. case 'cut':
  3680. cutSelected();
  3681. break;
  3682. case 'copy':
  3683. copySelected();
  3684. break;
  3685. case 'paste':
  3686. svgCanvas.pasteElements();
  3687. break;
  3688. case 'paste_in_place':
  3689. svgCanvas.pasteElements('in_place');
  3690. break;
  3691. case 'group':
  3692. svgCanvas.groupSelectedElements();
  3693. break;
  3694. case 'ungroup':
  3695. svgCanvas.ungroupSelectedElement();
  3696. break;
  3697. case 'move_front':
  3698. moveToTopSelected();
  3699. break;
  3700. case 'move_up':
  3701. moveUpDownSelected('Up');
  3702. break;
  3703. case 'move_down':
  3704. moveUpDownSelected('Down');
  3705. break;
  3706. case 'move_back':
  3707. moveToBottomSelected();
  3708. break;
  3709. }
  3710. if(svgCanvas.clipBoard.length) {
  3711. canv_menu.enableContextMenuItems('#paste,#paste_in_place');
  3712. }
  3713. });
  3714. var lmenu_func = function(action, el, pos) {
  3715. switch ( action ) {
  3716. case 'dupe':
  3717. cloneLayer();
  3718. break;
  3719. case 'delete':
  3720. deleteLayer();
  3721. break;
  3722. case 'merge_down':
  3723. mergeLayer();
  3724. break;
  3725. case 'merge_all':
  3726. svgCanvas.mergeAllLayers();
  3727. updateContextPanel();
  3728. populateLayers();
  3729. break;
  3730. }
  3731. }
  3732. $("#layerlist").contextMenu({
  3733. menu: 'cmenu_layers',
  3734. inSpeed: 0
  3735. },
  3736. lmenu_func
  3737. );
  3738. $("#layer_moreopts").contextMenu({
  3739. menu: 'cmenu_layers',
  3740. inSpeed: 0,
  3741. allowLeft: true
  3742. },
  3743. lmenu_func
  3744. );
  3745. $('.contextMenu li').mousedown(function(ev) {
  3746. ev.preventDefault();
  3747. })
  3748. $('#cmenu_canvas li').disableContextMenu();
  3749. canv_menu.enableContextMenuItems('#delete,#cut,#copy');
  3750. window.onbeforeunload = function() {
  3751. // Suppress warning if page is empty
  3752. if(undoMgr.getUndoStackSize() === 0) {
  3753. show_save_warning = false;
  3754. }
  3755. // show_save_warning is set to "false" when the page is saved.
  3756. if(!curConfig.no_save_warning && show_save_warning) {
  3757. // Browser already asks question about closing the page
  3758. return uiStrings.notification.unsavedChanges;
  3759. }
  3760. };
  3761. Editor.openPrep = function(func) {
  3762. $('#main_menu').hide();
  3763. if(undoMgr.getUndoStackSize() === 0) {
  3764. func(true);
  3765. } else {
  3766. $.confirm(uiStrings.notification.QwantToOpen, func);
  3767. }
  3768. }
  3769. // use HTML5 File API: http://www.w3.org/TR/FileAPI/
  3770. // if browser has HTML5 File API support, then we will show the open menu item
  3771. // and provide a file input to click. When that change event fires, it will
  3772. // get the text contents of the file and send it to the canvas
  3773. if (window.FileReader) {
  3774. var inp = $('<input type="file">').change(function() {
  3775. var f = this;
  3776. Editor.openPrep(function(ok) {
  3777. if(!ok) return;
  3778. svgCanvas.clear();
  3779. if(f.files.length==1) {
  3780. var reader = new FileReader();
  3781. reader.onloadend = function(e) {
  3782. loadSvgString(e.target.result);
  3783. updateCanvas();
  3784. };
  3785. reader.readAsText(f.files[0]);
  3786. }
  3787. });
  3788. });
  3789. $("#tool_open").show().prepend(inp);
  3790. var inp2 = $('<input type="file">').change(function() {
  3791. $('#main_menu').hide();
  3792. if(this.files.length==1) {
  3793. var reader = new FileReader();
  3794. reader.onloadend = function(e) {
  3795. svgCanvas.importSvgString(e.target.result, true);
  3796. updateCanvas();
  3797. };
  3798. reader.readAsText(this.files[0]);
  3799. }
  3800. });
  3801. $("#tool_import").show().prepend(inp2);
  3802. }
  3803. var updateCanvas = Editor.updateCanvas = function(center, new_ctr) {
  3804. var w = workarea.width(), h = workarea.height();
  3805. var w_orig = w, h_orig = h;
  3806. var zoom = svgCanvas.getZoom();
  3807. var w_area = workarea;
  3808. var cnvs = $("#svgcanvas");
  3809. var old_ctr = {
  3810. x: w_area[0].scrollLeft + w_orig/2,
  3811. y: w_area[0].scrollTop + h_orig/2
  3812. };
  3813. var multi = curConfig.canvas_expansion;
  3814. w = Math.max(w_orig, svgCanvas.contentW * zoom * multi);
  3815. h = Math.max(h_orig, svgCanvas.contentH * zoom * multi);
  3816. if(w == w_orig && h == h_orig) {
  3817. workarea.css('overflow','hidden');
  3818. } else {
  3819. workarea.css('overflow','scroll');
  3820. }
  3821. var old_can_y = cnvs.height()/2;
  3822. var old_can_x = cnvs.width()/2;
  3823. cnvs.width(w).height(h);
  3824. var new_can_y = h/2;
  3825. var new_can_x = w/2;
  3826. var offset = svgCanvas.updateCanvas(w, h);
  3827. var ratio = new_can_x / old_can_x;
  3828. var scroll_x = w/2 - w_orig/2;
  3829. var scroll_y = h/2 - h_orig/2;
  3830. if(!new_ctr) {
  3831. var old_dist_x = old_ctr.x - old_can_x;
  3832. var new_x = new_can_x + old_dist_x * ratio;
  3833. var old_dist_y = old_ctr.y - old_can_y;
  3834. var new_y = new_can_y + old_dist_y * ratio;
  3835. new_ctr = {
  3836. x: new_x,
  3837. y: new_y
  3838. };
  3839. } else {
  3840. new_ctr.x += offset.x,
  3841. new_ctr.y += offset.y;
  3842. }
  3843. if(center) {
  3844. // Go to top-left for larger documents
  3845. if(svgCanvas.contentW > w_area.width()) {
  3846. // Top-left
  3847. workarea[0].scrollLeft = offset.x - 10;
  3848. workarea[0].scrollTop = offset.y - 10;
  3849. } else {
  3850. // Center
  3851. w_area[0].scrollLeft = scroll_x;
  3852. w_area[0].scrollTop = scroll_y;
  3853. }
  3854. } else {
  3855. w_area[0].scrollLeft = new_ctr.x - w_orig/2;
  3856. w_area[0].scrollTop = new_ctr.y - h_orig/2;
  3857. }
  3858. if(curConfig.showRulers) {
  3859. updateRulers(cnvs, zoom);
  3860. workarea.scroll();
  3861. }
  3862. }
  3863. // Make [1,2,5] array
  3864. var r_intervals = [];
  3865. for(var i = .1; i < 1E5; i *= 10) {
  3866. r_intervals.push(1 * i);
  3867. r_intervals.push(2 * i);
  3868. r_intervals.push(5 * i);
  3869. }
  3870. function updateRulers(scanvas, zoom) {
  3871. if(!zoom) zoom = svgCanvas.getZoom();
  3872. if(!scanvas) scanvas = $("#svgcanvas");
  3873. var limit = 30000;
  3874. var c_elem = svgCanvas.getContentElem();
  3875. var units = svgedit.units.getTypeMap();
  3876. var unit = units[curConfig.baseUnit]; // 1 = 1px
  3877. for(var d = 0; d < 2; d++) {
  3878. var is_x = (d === 0);
  3879. var dim = is_x ? 'x' : 'y';
  3880. var lentype = is_x?'width':'height';
  3881. var content_d = c_elem.getAttribute(dim)-0;
  3882. var $hcanv_orig = $('#ruler_' + dim + ' canvas:first');
  3883. // Bit of a hack to fully clear the canvas in Safari & IE9
  3884. $hcanv = $hcanv_orig.clone();
  3885. $hcanv_orig.replaceWith($hcanv);
  3886. var hcanv = $hcanv[0];
  3887. // Set the canvas size to the width of the container
  3888. var ruler_len = scanvas[lentype]();
  3889. var total_len = ruler_len;
  3890. hcanv.parentNode.style[lentype] = total_len + 'px';
  3891. var canv_count = 1;
  3892. var ctx_num = 0;
  3893. var ctx_arr;
  3894. var ctx = hcanv.getContext("2d");
  3895. ctx.fillStyle = "rgb(200,0,0)";
  3896. ctx.fillRect(0,0,hcanv.width,hcanv.height);
  3897. // Remove any existing canvasses
  3898. $hcanv.siblings().remove();
  3899. // Create multiple canvases when necessary (due to browser limits)
  3900. if(ruler_len >= limit) {
  3901. var num = parseInt(ruler_len / limit) + 1;
  3902. ctx_arr = Array(num);
  3903. ctx_arr[0] = ctx;
  3904. for(var i = 1; i < num; i++) {
  3905. hcanv[lentype] = limit;
  3906. var copy = hcanv.cloneNode(true);
  3907. hcanv.parentNode.appendChild(copy);
  3908. ctx_arr[i] = copy.getContext('2d');
  3909. }
  3910. copy[lentype] = ruler_len % limit;
  3911. // set copy width to last
  3912. ruler_len = limit;
  3913. }
  3914. hcanv[lentype] = ruler_len;
  3915. var u_multi = unit * zoom;
  3916. // Calculate the main number interval
  3917. var raw_m = 50 / u_multi;
  3918. var multi = 1;
  3919. for(var i = 0; i < r_intervals.length; i++) {
  3920. var num = r_intervals[i];
  3921. multi = num;
  3922. if(raw_m <= num) {
  3923. break;
  3924. }
  3925. }
  3926. var big_int = multi * u_multi;
  3927. ctx.font = "9px sans-serif";
  3928. var ruler_d = ((content_d / u_multi) % multi) * u_multi;
  3929. var label_pos = ruler_d - big_int;
  3930. for (; ruler_d < total_len; ruler_d += big_int) {
  3931. label_pos += big_int;
  3932. var real_d = ruler_d - content_d;
  3933. var cur_d = Math.round(ruler_d) + .5;
  3934. if(is_x) {
  3935. ctx.moveTo(cur_d, 15);
  3936. ctx.lineTo(cur_d, 0);
  3937. } else {
  3938. ctx.moveTo(15, cur_d);
  3939. ctx.lineTo(0, cur_d);
  3940. }
  3941. var num = (label_pos - content_d) / u_multi;
  3942. var label;
  3943. if(multi >= 1) {
  3944. label = Math.round(num);
  3945. } else {
  3946. var decs = (multi+'').split('.')[1].length;
  3947. label = num.toFixed(decs)-0;
  3948. }
  3949. // Do anything special for negative numbers?
  3950. // var is_neg = label < 0;
  3951. // real_d2 = Math.abs(real_d2);
  3952. // Change 1000s to Ks
  3953. if(label !== 0 && label !== 1000 && label % 1000 === 0) {
  3954. label = (label / 1000) + 'K';
  3955. }
  3956. if(is_x) {
  3957. ctx.fillText(label, ruler_d+2, 8);
  3958. } else {
  3959. var str = (label+'').split('');
  3960. for(var i = 0; i < str.length; i++) {
  3961. ctx.fillText(str[i], 1, (ruler_d+9) + i*9);
  3962. }
  3963. }
  3964. var part = big_int / 10;
  3965. for(var i = 1; i < 10; i++) {
  3966. var sub_d = Math.round(ruler_d + part * i) + .5;
  3967. if(ctx_arr && sub_d > ruler_len) {
  3968. ctx_num++;
  3969. ctx.stroke();
  3970. if(ctx_num >= ctx_arr.length) {
  3971. i = 10;
  3972. ruler_d = total_len;
  3973. continue;
  3974. }
  3975. ctx = ctx_arr[ctx_num];
  3976. ruler_d -= limit;
  3977. sub_d = Math.round(ruler_d + part * i) + .5;
  3978. }
  3979. var line_num = (i % 2)?12:10;
  3980. if(is_x) {
  3981. ctx.moveTo(sub_d, 15);
  3982. ctx.lineTo(sub_d, line_num);
  3983. } else {
  3984. ctx.moveTo(15, sub_d);
  3985. ctx.lineTo(line_num ,sub_d);
  3986. }
  3987. }
  3988. }
  3989. // console.log('ctx', ctx);
  3990. ctx.strokeStyle = "#000";
  3991. ctx.stroke();
  3992. }
  3993. }
  3994. // $(function() {
  3995. updateCanvas(true);
  3996. // });
  3997. // var revnums = "svg-editor.js ($Rev: 2028 $) ";
  3998. // revnums += svgCanvas.getVersion();
  3999. // $('#copyright')[0].setAttribute("title", revnums);
  4000. // Callback handler for embedapi.js
  4001. try{
  4002. var json_encode = function(obj){
  4003. //simple partial JSON encoder implementation
  4004. if(window.JSON && JSON.stringify) return JSON.stringify(obj);
  4005. var enc = arguments.callee; //for purposes of recursion
  4006. if(typeof obj == "boolean" || typeof obj == "number"){
  4007. return obj+'' //should work...
  4008. }else if(typeof obj == "string"){
  4009. //a large portion of this is stolen from Douglas Crockford's json2.js
  4010. return '"'+
  4011. obj.replace(
  4012. /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g
  4013. , function (a) {
  4014. return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
  4015. })
  4016. +'"'; //note that this isn't quite as purtyful as the usualness
  4017. }else if(obj.length){ //simple hackish test for arrayish-ness
  4018. for(var i = 0; i < obj.length; i++){
  4019. obj[i] = enc(obj[i]); //encode every sub-thingy on top
  4020. }
  4021. return "["+obj.join(",")+"]";
  4022. }else{
  4023. var pairs = []; //pairs will be stored here
  4024. for(var k in obj){ //loop through thingys
  4025. pairs.push(enc(k)+":"+enc(obj[k])); //key: value
  4026. }
  4027. return "{"+pairs.join(",")+"}" //wrap in the braces
  4028. }
  4029. }
  4030. window.addEventListener("message", function(e){
  4031. var cbid = parseInt(e.data.substr(0, e.data.indexOf(";")));
  4032. try{
  4033. e.source.postMessage("SVGe"+cbid+";"+json_encode(eval(e.data)), "*");
  4034. }catch(err){
  4035. e.source.postMessage("SVGe"+cbid+";error:"+err.message, "*");
  4036. }
  4037. }, false)
  4038. }catch(err){
  4039. window.embed_error = err;
  4040. }
  4041. // For Compatibility with older extensions
  4042. $(function() {
  4043. window.svgCanvas = svgCanvas;
  4044. svgCanvas.ready = svgEditor.ready;
  4045. });
  4046. Editor.setLang = function(lang, allStrings) {
  4047. $.pref('lang', lang);
  4048. $('#lang_select').val(lang);
  4049. if(allStrings) {
  4050. var notif = allStrings.notification;
  4051. // $.extend will only replace the given strings
  4052. var oldLayerName = $('#layerlist tr.layersel td.layername').text();
  4053. var rename_layer = (oldLayerName == uiStrings.common.layer + ' 1');
  4054. $.extend(uiStrings, allStrings);
  4055. svgCanvas.setUiStrings(allStrings);
  4056. Actions.setTitles();
  4057. if(rename_layer) {
  4058. svgCanvas.renameCurrentLayer(uiStrings.common.layer + ' 1');
  4059. populateLayers();
  4060. }
  4061. svgCanvas.runExtensions("langChanged", lang);
  4062. // Update flyout tooltips
  4063. setFlyoutTitles();
  4064. // Copy title for certain tool elements
  4065. var elems = {
  4066. '#stroke_color': '#tool_stroke .icon_label, #tool_stroke .color_block',
  4067. '#fill_color': '#tool_fill label, #tool_fill .color_block',
  4068. '#linejoin_miter': '#cur_linejoin',
  4069. '#linecap_butt': '#cur_linecap'
  4070. }
  4071. $.each(elems, function(source, dest) {
  4072. $(dest).attr('title', $(source)[0].title);
  4073. });
  4074. // Copy alignment titles
  4075. $('#multiselected_panel div[id^=tool_align]').each(function() {
  4076. $('#tool_pos' + this.id.substr(10))[0].title = this.title;
  4077. });
  4078. }
  4079. };
  4080. };
  4081. var callbacks = [];
  4082. function loadSvgString(str, callback) {
  4083. var success = svgCanvas.setSvgString(str) !== false;
  4084. callback = callback || $.noop;
  4085. if(success) {
  4086. callback(true);
  4087. } else {
  4088. $.alert(uiStrings.notification.errorLoadingSVG, function() {
  4089. callback(false);
  4090. });
  4091. }
  4092. }
  4093. Editor.ready = function(cb) {
  4094. if(!is_ready) {
  4095. callbacks.push(cb);
  4096. } else {
  4097. cb();
  4098. }
  4099. };
  4100. Editor.runCallbacks = function() {
  4101. $.each(callbacks, function() {
  4102. this();
  4103. });
  4104. is_ready = true;
  4105. };
  4106. Editor.loadFromString = function(str) {
  4107. Editor.ready(function() {
  4108. loadSvgString(str);
  4109. });
  4110. };
  4111. Editor.disableUI = function(featList) {
  4112. // $(function() {
  4113. // $('#tool_wireframe, #tool_image, #main_button, #tool_source, #sidepanels').remove();
  4114. // $('#tools_top').css('left', 5);
  4115. // });
  4116. };
  4117. Editor.loadFromURL = function(url, opts) {
  4118. if(!opts) opts = {};
  4119. var cache = opts.cache;
  4120. var cb = opts.callback;
  4121. Editor.ready(function() {
  4122. $.ajax({
  4123. 'url': url,
  4124. 'dataType': 'text',
  4125. cache: !!cache,
  4126. success: function(str) {
  4127. loadSvgString(str, cb);
  4128. },
  4129. error: function(xhr, stat, err) {
  4130. if(xhr.status != 404 && xhr.responseText) {
  4131. loadSvgString(xhr.responseText, cb);
  4132. } else {
  4133. $.alert(uiStrings.notification.URLloadFail + ": \n"+err+'', cb);
  4134. }
  4135. }
  4136. });
  4137. });
  4138. };
  4139. Editor.loadFromDataURI = function(str) {
  4140. Editor.ready(function() {
  4141. var pre = 'data:image/svg+xml;base64,';
  4142. var src = str.substring(pre.length);
  4143. loadSvgString(svgedit.utilities.decode64(src));
  4144. });
  4145. };
  4146. Editor.addExtension = function() {
  4147. var args = arguments;
  4148. // Note that we don't want this on Editor.ready since some extensions
  4149. // may want to run before then (like server_opensave).
  4150. $(function() {
  4151. if(svgCanvas) svgCanvas.addExtension.apply(this, args);
  4152. });
  4153. };
  4154. return Editor;
  4155. }(jQuery);
  4156. // Run init once DOM is loaded
  4157. $(svgEditor.init);
  4158. })();
  4159. // ?iconsize=s&bkgd_color=555
  4160. // svgEditor.setConfig({
  4161. // // imgPath: 'foo',
  4162. // dimensions: [800, 600],
  4163. // canvas_expansion: 5,
  4164. // initStroke: {
  4165. // color: '0000FF',
  4166. // width: 3.5,
  4167. // opacity: .5
  4168. // },
  4169. // initFill: {
  4170. // color: '550000',
  4171. // opacity: .75
  4172. // },
  4173. // extensions: ['ext-helloworld.js']
  4174. // })