svg-editor.js 158 KB

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