svg-editor - Copy.js 150 KB

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