-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsvg-editor.js
4889 lines (4206 loc) · 146 KB
/
svg-editor.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* svg-editor.js
*
* Licensed under the Apache License, Version 2
*
* Copyright(c) 2010 Alexis Deveria
* Copyright(c) 2010 Pavol Rusnak
* Copyright(c) 2010 Jeff Schiller
* Copyright(c) 2010 Narendra Sisodiya
*
*/
// Dependencies:
// 1) units.js
// 2) browser.js
// 3) svgcanvas.js
(function() {
if(!window.svgEditor) window.svgEditor = function($) {
var svgCanvas;
var Editor = {};
var is_ready = false;
var defaultPrefs = {
lang:'en',
iconsize:'m',
bkgd_color:'#FFF',
bkgd_url:'',
img_save:'embed'
},
curPrefs = {},
// Note: Difference between Prefs and Config is that Prefs can be
// changed in the UI and are stored in the browser, config can not
curConfig = {
canvas_expansion: 3,
dimensions: [640,480],
initFill: {
color: 'FFFF00', // yellow
opacity: 0.2
},
initStroke: {
width: 1,
color: '000000', // solid black
opacity: 0.5
},
initOpacity: 1,
imgPath: 'images/',
langPath: 'locale/',
extPath: 'extensions/',
jGraduatePath: 'jgraduate/images/',
extensions: ['ext-markers.js','ext-connector.js', 'ext-eyedropper.js', 'ext-shapes.js', 'ext-imagelib.js','ext-grid.js'],
initTool: 'select',
wireframe: false,
colorPickerCSS: null,
gridSnapping: false,
gridColor: "#000",
baseUnit: 'px',
snappingStep: 10,
showRulers: true,
showlayers: true
},
uiStrings = Editor.uiStrings = {
common: {
"ok":"OK",
"cancel":"Cancel",
"key_up":"Up",
"key_down":"Down",
"key_backspace":"Backspace",
"key_del":"Del"
},
// This is needed if the locale is English, since the locale strings are not read in that instance.
layers: {
"layer":"Layer"
},
notification: {
"invalidAttrValGiven":"Invalid value given",
"noContentToFitTo":"No content to fit to",
"dupeLayerName":"There is already a layer named that!",
"enterUniqueLayerName":"Please enter a unique layer name",
"enterNewLayerName":"Please enter the new layer name",
"layerHasThatName":"Layer already has that name",
"QmoveElemsToLayer":"Move selected elements to layer \"%s\"?",
"QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!",
"QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!",
"QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?",
"QignoreSourceChanges":"Ignore changes made to SVG source?",
"featNotSupported":"Feature not supported",
"enterNewImgURL":"Enter the new image URL",
"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.",
"loadingImage":"Loading image, please wait...",
"saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.",
"noteTheseIssues": "Also note the following issues: ",
"unsavedChanges": "There are unsaved changes.",
"enterNewLinkURL": "Enter the new hyperlink URL",
"errorLoadingSVG": "Error: Unable to load SVG data",
"URLloadFail": "Unable to load from URL",
"retrieving": 'Retrieving "%s" ...'
}
};
var curPrefs = {}; //$.extend({}, defaultPrefs);
var customHandlers = {};
Editor.curConfig = curConfig;
Editor.tool_scale = 1;
// Store and retrieve preferences
$.pref = function(key, val) {
if(val) curPrefs[key] = val;
key = 'svg-edit-'+key;
var host = location.hostname,
onweb = host && host.indexOf('.') >= 0,
store = (val != undefined),
storage = false;
// Some FF versions throw security errors here
try {
if(window.localStorage) { // && onweb removed so Webkit works locally
storage = localStorage;
}
} catch(e) {}
try {
if(window.globalStorage && onweb) {
storage = globalStorage[host];
}
} catch(e) {}
if(storage) {
if(store) storage.setItem(key, val);
else if (storage.getItem(key)) return storage.getItem(key) + ''; // Convert to string for FF (.value fails in Webkit)
} else if(window.widget) {
if(store) widget.setPreferenceForKey(val, key);
else return widget.preferenceForKey(key);
} else {
if(store) {
var d = new Date();
d.setTime(d.getTime() + 31536000000);
val = encodeURIComponent(val);
document.cookie = key+'='+val+'; expires='+d.toUTCString();
} else {
var result = document.cookie.match(new RegExp(key + "=([^;]+)"));
return result?decodeURIComponent(result[1]):'';
}
}
}
Editor.setConfig = function(opts) {
$.each(opts, function(key, val) {
// Only allow prefs defined in defaultPrefs
if(key in defaultPrefs) {
$.pref(key, val);
}
});
$.extend(true, curConfig, opts);
if(opts.extensions) {
curConfig.extensions = opts.extensions;
}
}
// Extension mechanisms must call setCustomHandlers with two functions: opts.open and opts.save
// opts.open's responsibilities are:
// - invoke a file chooser dialog in 'open' mode
// - let user pick a SVG file
// - calls setCanvas.setSvgString() with the string contents of that file
// opts.save's responsibilities are:
// - accept the string contents of the current document
// - invoke a file chooser dialog in 'save' mode
// - save the file to location chosen by the user
Editor.setCustomHandlers = function(opts) {
Editor.ready(function() {
if(opts.open) {
$('#tool_open > input[type="file"]').remove();
$('#tool_open').show();
svgCanvas.open = opts.open;
}
if(opts.save) {
Editor.show_save_warning = false;
svgCanvas.bind("saved", opts.save);
}
if(opts.pngsave) {
svgCanvas.bind("exported", opts.pngsave);
}
customHandlers = opts;
});
}
Editor.randomizeIds = function() {
svgCanvas.randomizeIds(arguments)
}
Editor.init = function() {
// For external openers
(function() {
// let the opener know SVG Edit is ready
var w = window.opener;
if (w) {
try {
var svgEditorReadyEvent = w.document.createEvent("Event");
svgEditorReadyEvent.initEvent("svgEditorReady", true, true);
w.document.documentElement.dispatchEvent(svgEditorReadyEvent);
}
catch(e) {}
}
})();
(function() {
// Load config/data from URL if given
var urldata = $.deparam.querystring(true);
if(!$.isEmptyObject(urldata)) {
if(urldata.dimensions) {
urldata.dimensions = urldata.dimensions.split(',');
}
if(urldata.extensions) {
urldata.extensions = urldata.extensions.split(',');
}
if(urldata.bkgd_color) {
urldata.bkgd_color = '#' + urldata.bkgd_color;
}
svgEditor.setConfig(urldata);
var src = urldata.source;
var qstr = $.param.querystring();
if(!src) { // urldata.source may have been null if it ended with '='
if(qstr.indexOf('source=data:') >= 0) {
src = qstr.match(/source=(data:[^&]*)/)[1];
}
}
if(src) {
if(src.indexOf("data:") === 0) {
// plusses get replaced by spaces, so re-insert
src = src.replace(/ /g, "+");
Editor.loadFromDataURI(src);
} else {
Editor.loadFromString(src);
}
}
// Disabled for ext-imageannotation
// else if(qstr.indexOf('paramurl=') !== -1) {
// // Get paramater URL (use full length of remaining location.href)
// svgEditor.loadFromURL(qstr.substr(9));
// } else if(urldata.url) {
// svgEditor.loadFromURL(urldata.url);
// }
}
})();
var extFunc = function() {
$.each(curConfig.extensions, function() {
var extname = this;
$.getScript(curConfig.extPath + extname, function(d) {
// Fails locally in Chrome 5
if(!d) {
var s = document.createElement('script');
s.src = curConfig.extPath + extname;
document.querySelector('head').appendChild(s);
}
});
});
var good_langs = [];
$('#lang_select option').each(function() {
good_langs.push(this.value);
});
// var lang = ('lang' in curPrefs) ? curPrefs.lang : null;
Editor.putLocale(null, good_langs);
}
// Load extensions
// Bit of a hack to run extensions in local Opera/IE9
if(document.location.protocol === 'file:') {
setTimeout(extFunc, 100);
} else {
extFunc();
}
$.svgIcons(curConfig.imgPath + 'svg_edit_icons.svg', {
w:24, h:24,
id_match: false,
no_img: !svgedit.browser.isWebkit(), // Opera & Firefox 4 gives odd behavior w/images
fallback_path: curConfig.imgPath,
fallback:{
'new_image':'clear.png',
'save':'save.png',
'open':'open.png',
'source':'source.png',
'docprops':'document-properties.png',
'wireframe':'wireframe.png',
'undo':'undo.png',
'redo':'redo.png',
'select':'select.png',
'select_node':'select_node.png',
'pencil':'fhpath.png',
'pen':'line.png',
'square':'square.png',
'rect':'rect.png',
'fh_rect':'freehand-square.png',
'circle':'circle.png',
'ellipse':'ellipse.png',
'fh_ellipse':'freehand-circle.png',
'path':'path.png',
'text':'text.png',
'image':'image.png',
'zoom':'zoom.png',
'clone':'clone.png',
'node_clone':'node_clone.png',
'delete':'delete.png',
'node_delete':'node_delete.png',
'group':'shape_group.png',
'ungroup':'shape_ungroup.png',
'move_top':'move_top.png',
'move_bottom':'move_bottom.png',
'to_path':'to_path.png',
'link_controls':'link_controls.png',
'reorient':'reorient.png',
'align_left':'align-left.png',
'align_center':'align-center',
'align_right':'align-right',
'align_top':'align-top',
'align_middle':'align-middle',
'align_bottom':'align-bottom',
'go_up':'go-up.png',
'go_down':'go-down.png',
'ok':'save.png',
'cancel':'cancel.png',
'arrow_right':'flyouth.png',
'arrow_down':'dropdown.gif'
},
placement: {
'#logo':'logo',
'#tool_clear div,#layer_new':'new_image',
'#tool_save div':'save',
'#tool_export div':'export',
'#tool_open div div':'open',
'#tool_import div div':'import',
'#tool_source':'source',
'#tool_docprops > div':'docprops',
'#tool_wireframe':'wireframe',
'#tool_undo':'undo',
'#tool_redo':'redo',
'#tool_select':'select',
'#tool_fhpath':'pencil',
'#tool_line':'pen',
'#tool_rect,#tools_rect_show':'rect',
'#tool_square':'square',
'#tool_fhrect':'fh_rect',
'#tool_ellipse,#tools_ellipse_show':'ellipse',
'#tool_circle':'circle',
'#tool_fhellipse':'fh_ellipse',
'#tool_path':'path',
'#tool_text,#layer_rename':'text',
'#tool_image':'image',
'#tool_zoom':'zoom',
'#tool_clone,#tool_clone_multi':'clone',
'#tool_node_clone':'node_clone',
'#layer_delete,#tool_delete,#tool_delete_multi':'delete',
'#tool_node_delete':'node_delete',
'#tool_add_subpath':'add_subpath',
'#tool_openclose_path':'open_path',
'#tool_move_top':'move_top',
'#tool_move_bottom':'move_bottom',
'#tool_topath':'to_path',
'#tool_node_link':'link_controls',
'#tool_reorient':'reorient',
'#tool_group':'group',
'#tool_ungroup':'ungroup',
'#tool_unlink_use':'unlink_use',
'#tool_alignleft, #tool_posleft':'align_left',
'#tool_aligncenter, #tool_poscenter':'align_center',
'#tool_alignright, #tool_posright':'align_right',
'#tool_aligntop, #tool_postop':'align_top',
'#tool_alignmiddle, #tool_posmiddle':'align_middle',
'#tool_alignbottom, #tool_posbottom':'align_bottom',
'#cur_position':'align',
'#linecap_butt,#cur_linecap':'linecap_butt',
'#linecap_round':'linecap_round',
'#linecap_square':'linecap_square',
'#linejoin_miter,#cur_linejoin':'linejoin_miter',
'#linejoin_round':'linejoin_round',
'#linejoin_bevel':'linejoin_bevel',
'#url_notice':'warning',
'#layer_up':'go_up',
'#layer_down':'go_down',
'#layer_moreopts':'context_menu',
'#layerlist td.layervis':'eye',
'#linelist td.linelink':'eye',
'#tool_source_save,#tool_docprops_save,#tool_prefs_save':'ok',
'#tool_source_cancel,#tool_docprops_cancel,#tool_prefs_cancel':'cancel',
'#rwidthLabel, #iwidthLabel':'width',
'#rheightLabel, #iheightLabel':'height',
'#cornerRadiusLabel span':'c_radius',
'#angleLabel':'angle',
'#linkLabel,#tool_make_link,#tool_make_link_multi':'globe_link',
'#zoomLabel':'zoom',
'#tool_fill label': 'fill',
'#tool_stroke .icon_label': 'stroke',
'#group_opacityLabel': 'opacity',
'#blurLabel': 'blur',
'#font_sizeLabel': 'fontsize',
'.flyout_arrow_horiz':'arrow_right',
'.dropdown button, #main_button .dropdown':'arrow_down',
'#palette .palette_item:first, #fill_bg, #stroke_bg':'no_color'
},
resize: {
'#logo .svg_icon': 32,
'.flyout_arrow_horiz .svg_icon': 5,
'.layer_button .svg_icon, #layerlist td.layervis .svg_icon': 14,
'.dropdown button .svg_icon': 7,
'#main_button .dropdown .svg_icon': 9,
'.palette_item:first .svg_icon, #fill_bg .svg_icon, #stroke_bg .svg_icon': 16,
'.toolbar_button button .svg_icon':16,
'.stroke_tool div div .svg_icon': 20,
'#tools_bottom label .svg_icon': 18
},
callback: function(icons) {
$('.toolbar_button button > svg, .toolbar_button button > img').each(function() {
$(this).parent().prepend(this);
});
var tleft = $('#tools_left');
if (tleft.length != 0) {
var min_height = tleft.offset().top + tleft.outerHeight();
}
// var size = $.pref('iconsize');
// if(size && size != 'm') {
// svgEditor.setIconSize(size);
// } else if($(window).height() < min_height) {
// // Make smaller
// svgEditor.setIconSize('s');
// }
// Look for any missing flyout icons from plugins
$('.tools_flyout').each(function() {
var shower = $('#' + this.id + '_show');
var sel = shower.attr('data-curopt');
// Check if there's an icon here
if(!shower.children('svg, img').length) {
var clone = $(sel).children().clone();
if(clone.length) {
clone[0].removeAttribute('style'); //Needed for Opera
shower.append(clone);
}
}
});
svgEditor.runCallbacks();
setTimeout(function() {
$('.flyout_arrow_horiz:empty').each(function() {
$(this).append($.getSvgIcon('arrow_right').width(5).height(5));
});
}, 1);
}
});
Editor.canvas = svgCanvas = new $.SvgCanvas(document.getElementById("svgcanvas"), curConfig);
Editor.show_save_warning = false;
var palette = ["#000000", "#3f3f3f", "#7f7f7f", "#bfbfbf", "#ffffff",
"#ff0000", "#ff7f00", "#ffff00", "#7fff00",
"#00ff00", "#00ff7f", "#00ffff", "#007fff",
"#0000ff", "#7f00ff", "#ff00ff", "#ff007f",
"#7f0000", "#7f3f00", "#7f7f00", "#3f7f00",
"#007f00", "#007f3f", "#007f7f", "#003f7f",
"#00007f", "#3f007f", "#7f007f", "#7f003f",
"#ffaaaa", "#ffd4aa", "#ffffaa", "#d4ffaa",
"#aaffaa", "#aaffd4", "#aaffff", "#aad4ff",
"#aaaaff", "#d4aaff", "#ffaaff", "#ffaad4"
],
isMac = (navigator.platform.indexOf("Mac") >= 0),
isWebkit = (navigator.userAgent.indexOf("AppleWebKit") >= 0),
modKey = (isMac ? "meta+" : "ctrl+"), // ⌘
path = svgCanvas.pathActions,
undoMgr = svgCanvas.undoMgr,
Utils = svgedit.utilities,
default_img_url = curConfig.imgPath + "logo.png",
workarea = $("#workarea"),
canv_menu = $("#cmenu_canvas"),
layer_menu = $("#cmenu_layers"),
exportWindow = null,
tool_scale = 1,
zoomInIcon = 'crosshair',
zoomOutIcon = 'crosshair',
ui_context = 'toolbars',
orig_source = '',
paintBox = {fill: null, stroke:null};
// This sets up alternative dialog boxes. They mostly work the same way as
// their UI counterparts, expect instead of returning the result, a callback
// needs to be included that returns the result as its first parameter.
// In the future we may want to add additional types of dialog boxes, since
// they should be easy to handle this way.
(function() {
$('#dialog_container').draggable({cancel:'#dialog_content, #dialog_buttons *', containment: 'window'});
var box = $('#dialog_box'), btn_holder = $('#dialog_buttons');
var dbox = function(type, msg, callback, defText) {
$('#dialog_content').html('<p>'+msg.replace(/\n/g,'</p><p>')+'</p>')
.toggleClass('prompt',(type=='prompt'));
btn_holder.empty();
var ok = $('<input type="button" value="' + uiStrings.common.ok + '">').appendTo(btn_holder);
if(type != 'alert') {
$('<input type="button" value="' + uiStrings.common.cancel + '">')
.appendTo(btn_holder)
.click(function() { box.hide();callback(false)});
}
if(type == 'prompt') {
var input = $('<input type="text">').prependTo(btn_holder);
input.val(defText || '');
input.bind('keydown', 'return', function() {ok.click();});
}
if(type == 'process') {
ok.hide();
}
box.show();
ok.click(function() {
box.hide();
var resp = (type == 'prompt')?input.val():true;
if(callback) callback(resp);
}).focus();
if(type == 'prompt') input.focus();
}
$.alert = function(msg, cb) { dbox('alert', msg, cb);};
$.confirm = function(msg, cb) { dbox('confirm', msg, cb);};
$.process_cancel = function(msg, cb) { dbox('process', msg, cb);};
$.prompt = function(msg, txt, cb) { dbox('prompt', msg, cb, txt);};
}());
var setSelectMode = function() {
var curr = $('.tool_button_current');
if(curr.length && curr[0].id !== 'tool_select') {
curr.removeClass('tool_button_current').addClass('tool_button');
$('#tool_select').addClass('tool_button_current').removeClass('tool_button');
$('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all} #svgcanvas svg{cursor:default}');
}
svgCanvas.setMode('select');
workarea.css('cursor','auto');
};
var togglePathEditMode = function(editmode, elems) {
$('#path_node_panel').toggle(editmode);
$('#tools_bottom_2,#tools_bottom_3').toggle(!editmode);
if(editmode) {
// Change select icon
$('.tool_button_current').removeClass('tool_button_current').addClass('tool_button');
$('#tool_select').addClass('tool_button_current').removeClass('tool_button');
setIcon('#tool_select', 'select_node');
multiselected = false;
if(elems.length) {
selectedElement = elems[0];
}
} else {
setIcon('#tool_select', 'select');
}
}
// used to make the flyouts stay on the screen longer the very first time
var flyoutspeed = 1250;
var textBeingEntered = false;
var selectedElement = null;
var multiselected = false;
var editingsource = false;
var docprops = false;
var preferences = false;
var cur_context = '';
var orig_title = $('title:first').text();
var saveHandler = function(window,svg) {
Editor.show_save_warning = false;
// by default, we add the XML prolog back, systems integrating SVG-edit (wikis, CMSs)
// can just provide their own custom save handler and might not want the XML prolog
svg = '<?xml version="1.0"?>\n' + svg;
// Opens the SVG in new window, with warning about Mozilla bug #308590 when applicable
var ua = navigator.userAgent;
// Chrome 5 (and 6?) don't allow saving, show source instead ( http://code.google.com/p/chromium/issues/detail?id=46735 )
// IE9 doesn't allow standalone Data URLs ( https://connect.microsoft.com/IE/feedback/details/542600/data-uri-images-fail-when-loaded-by-themselves )
if((~ua.indexOf('Chrome') && $.browser.version >= 533) || ~ua.indexOf('MSIE')) {
showSourceEditor(0,true);
return;
}
var win = window.open("data:image/svg+xml;base64," + Utils.encode64(svg));
// Alert will only appear the first time saved OR the first time the bug is encountered
var done = $.pref('save_notice_done');
if(done !== "all") {
var note = uiStrings.notification.saveFromBrowser.replace('%s', 'SVG');
// Check if FF and has <defs/>
if(ua.indexOf('Gecko/') !== -1) {
if(svg.indexOf('<defs') !== -1) {
note += "\n\n" + uiStrings.notification.defsFailOnSave;
$.pref('save_notice_done', 'all');
done = "all";
} else {
$.pref('save_notice_done', 'part');
}
} else {
$.pref('save_notice_done', 'all');
}
if(done !== 'part') {
win.alert(note);
}
}
};
var exportHandler = function(window, data) {
var issues = data.issues;
if(!$('#export_canvas').length) {
$('<canvas>', {id: 'export_canvas'}).hide().appendTo('body');
}
var c = $('#export_canvas')[0];
c.width = svgCanvas.contentW;
c.height = svgCanvas.contentH;
canvg(c, data.svg, {renderCallback: function() {
var datauri = c.toDataURL('image/png');
exportWindow.location.href = datauri;
var done = $.pref('export_notice_done');
if(done !== "all") {
var note = uiStrings.notification.saveFromBrowser.replace('%s', 'PNG');
// Check if there's issues
if(issues.length) {
var pre = "\n \u2022 ";
note += ("\n\n" + uiStrings.notification.noteTheseIssues + pre + issues.join(pre));
}
// Note that this will also prevent the notice even though new issues may appear later.
// May want to find a way to deal with that without annoying the user
$.pref('export_notice_done', 'all');
exportWindow.alert(note);
}
}});
};
// called when we've selected a different element
var selectedChanged = function(window,elems) {
var mode = svgCanvas.getMode();
if(mode === "select") setSelectMode();
var is_node = (mode == "pathedit");
// if elems[1] is present, then we have more than one element
selectedElement = (elems.length == 1 || elems[1] == null ? elems[0] : null);
multiselected = (elems.length >= 2 && elems[1] != null);
if (selectedElement != null) {
// unless we're already in always set the mode of the editor to select because
// upon creation of a text element the editor is switched into
// select mode and this event fires - we need our UI to be in sync
if (!is_node) {
updateToolbar();
}
} // if (elem != null)
// Deal with pathedit mode
togglePathEditMode(is_node, elems);
updateContextPanel();
svgCanvas.runExtensions("selectedChanged", {
elems: elems,
selectedElement: selectedElement,
multiselected: multiselected
});
};
// Call when part of element is in process of changing, generally
// on mousemove actions like rotate, move, etc.
var elementTransition = function(window,elems) {
var mode = svgCanvas.getMode();
var elem = elems[0];
if(!elem) return;
multiselected = (elems.length >= 2 && elems[1] != null);
// Only updating fields for single elements for now
if(!multiselected) {
switch ( mode ) {
case "rotate":
var ang = svgCanvas.getRotationAngle(elem);
$('#angle').val(ang);
$('#tool_reorient').toggleClass('disabled', ang == 0);
break;
// TODO: Update values that change on move/resize, etc
// case "select":
// case "resize":
// break;
}
}
svgCanvas.runExtensions("elementTransition", {
elems: elems
});
};
// called when any element has changed
var elementChanged = function(window,elems) {
var mode = svgCanvas.getMode();
if(mode === "select") {
setSelectMode();
}
for (var i = 0; i < elems.length; ++i) {
var elem = elems[i];
// if the element changed was the svg, then it could be a resolution change
if (elem && elem.tagName === "svg") {
populateLayers();
updateCanvas();
}
// Update selectedElement if element is no longer part of the image.
// This occurs for the text elements in Firefox
else if(elem && selectedElement && selectedElement.parentNode == null) {
// || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why
selectedElement = elem;
}
}
Editor.show_save_warning = true;
// we update the contextual panel with potentially new
// positional/sizing information (we DON'T want to update the
// toolbar here as that creates an infinite loop)
// also this updates the history buttons
// we tell it to skip focusing the text control if the
// text element was previously in focus
updateContextPanel();
// In the event a gradient was flipped:
if(selectedElement && mode === "select") {
paintBox.fill.update();
paintBox.stroke.update();
}
svgCanvas.runExtensions("elementChanged", {
elems: elems
});
};
var zoomChanged = function(window, bbox, autoCenter) {
var scrbar = 15,
res = svgCanvas.getResolution(),
w_area = workarea,
canvas_pos = $('#svgcanvas').position();
var z_info = svgCanvas.setBBoxZoom(bbox, w_area.width()-scrbar, w_area.height()-scrbar);
if(!z_info) return;
var zoomlevel = z_info.zoom,
bb = z_info.bbox;
if(zoomlevel < .001) {
changeZoom({value: .1});
return;
}
// $('#zoom').val(Math.round(zoomlevel*100));
$('#zoom').val(zoomlevel*100);
if(autoCenter) {
updateCanvas();
} else {
updateCanvas(false, {x: bb.x * zoomlevel + (bb.width * zoomlevel)/2, y: bb.y * zoomlevel + (bb.height * zoomlevel)/2});
}
if(svgCanvas.getMode() == 'zoom' && bb.width) {
// Go to select if a zoom box was drawn
setSelectMode();
}
zoomDone();
}
$('#cur_context_panel').delegate('a', 'click', function() {
var link = $(this);
if(link.attr('data-root')) {
svgCanvas.leaveContext();
} else {
svgCanvas.setContext(link.text());
}
return false;
});
var contextChanged = function(win, context) {
$('#workarea,#sidepanels').css('top', context?100:75);
$('#rulers').toggleClass('moved', context);
if(cur_context && !context) {
// Back to normal
workarea[0].scrollTop -= 25;
} else if(!cur_context && context) {
workarea[0].scrollTop += 25;
}
var link_str = '';
if(context) {
var str = '';
link_str = '<a href="#" data-root="y">' + svgCanvas.getCurrentDrawing().getCurrentLayerName() + '</a>';
$(context).parentsUntil('#svgcontent > g').andSelf().each(function() {
if(this.id) {
str += ' > ' + this.id;
if(this !== context) {
link_str += ' > <a href="#">' + this.id + '</a>';
} else {
link_str += ' > ' + this.id;
}
}
});
cur_context = str;
} else {
cur_context = null;
}
$('#cur_context_panel').toggle(!!context).html(link_str);
updateTitle();
}
// Makes sure the current selected paint is available to work with
var prepPaints = function() {
paintBox.fill.prep();
paintBox.stroke.prep();
}
var flyout_funcs = {};
var setupFlyouts = function(holders) {
$.each(holders, function(hold_sel, btn_opts) {
var buttons = $(hold_sel).children();
var show_sel = hold_sel + '_show';
var shower = $(show_sel);
var def = false;
buttons.addClass('tool_button')
.unbind('click mousedown mouseup') // may not be necessary
.each(function(i) {
// Get this buttons options
var opts = btn_opts[i];
// Remember the function that goes with this ID
flyout_funcs[opts.sel] = opts.fn;
if(opts.isDefault) def = i;
// Clicking the icon in flyout should set this set's icon
var func = function(event) {
var options = opts;
//find the currently selected tool if comes from keystroke
if (event.type === "keydown") {
var flyoutIsSelected = $(options.parent + "_show").hasClass('tool_button_current');
var currentOperation = $(options.parent + "_show").attr("data-curopt");
$.each(holders[opts.parent], function(i, tool){
if (tool.sel == currentOperation) {
if(!event.shiftKey || !flyoutIsSelected) {
options = tool;
}
else {
options = holders[opts.parent][i+1] || holders[opts.parent][0];
}
}
});
}
if($(this).hasClass('disabled')) return false;
if (toolButtonClick(show_sel)) {
options.fn();
}
if(options.icon) {
var icon = $.getSvgIcon(options.icon, true);
} else {
var icon = $(options.sel).children().eq(0).clone();
}
icon[0].setAttribute('width',shower.width());
icon[0].setAttribute('height',shower.height());
shower.children(':not(.flyout_arrow_horiz)').remove();
shower.append(icon).attr('data-curopt', options.sel); // This sets the current mode
}
$(this).mouseup(func);
if(opts.key) {
$(document).bind('keydown', opts.key[0] + " shift+" + opts.key[0], func);
}
});
if(def) {
shower.attr('data-curopt', btn_opts[def].sel);
} else if(!shower.attr('data-curopt')) {
// Set first as default
shower.attr('data-curopt', btn_opts[0].sel);
}
var timer;
var pos = $(show_sel).position();
$(hold_sel).css({'left': pos.left+34, 'top': pos.top+77});
// Clicking the "show" icon should set the current mode
shower.mousedown(function(evt) {
if(shower.hasClass('disabled')) return false;
var holder = $(hold_sel);
var l = pos.left+34;
var w = holder.width()*-1;
var time = holder.data('shown_popop')?200:0;
timer = setTimeout(function() {
// Show corresponding menu
if(!shower.data('isLibrary')) {
holder.css('left', w).show().animate({
left: l
},150);
} else {
holder.css('left', l).show();
}
holder.data('shown_popop',true);
},time);
evt.preventDefault();
}).mouseup(function(evt) {
clearTimeout(timer);
var opt = $(this).attr('data-curopt');
// Is library and popped up, so do nothing
if(shower.data('isLibrary') && $(show_sel.replace('_show','')).is(':visible')) {
toolButtonClick(show_sel, true);
return;
}
if (toolButtonClick(show_sel) && (opt in flyout_funcs)) {
flyout_funcs[opt]();
}
});
// $('#tools_rect').mouseleave(function(){$('#tools_rect').fadeOut();});
});
setFlyoutTitles();
}
var makeFlyoutHolder = function(id, child) {
var div = $('<div>',{
'class': 'tools_flyout',
id: id
}).appendTo('#svg_editor').append(child);
return div;
}
var setFlyoutPositions = function() {
$('.tools_flyout').each(function() {
var shower = $('#' + this.id + '_show');
var pos = shower.offset();
var w = shower.outerWidth();
$(this).css({left: (pos.left + w)*tool_scale, top: pos.top});
});
}
var setFlyoutTitles = function() {
$('.tools_flyout').each(function() {
var shower = $('#' + this.id + '_show');
if(shower.data('isLibrary')) return;