svg-editor.js 157 KB

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