/
svg-editor - Copy.js
executable file
·4981 lines (4388 loc) · 150 KB
/
svg-editor - Copy.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
/*globals globalStorage, widget, svgEditor, svgedit, canvg, DOMParser, FileReader, jQuery, $, SVGEditConfig */
/*jslint vars: true, eqeq: true, todo: true, forin: true, continue: true, regexp: true */
/*
* svg-editor.js
*
* Licensed under the MIT License
*
* 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) {
return;
}
window.svgEditor = (function($) {
var svgCanvas,
Editor = {},
urldata,
isReady = false,
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 = {
canvasName: 'default',
canvas_expansion: 3,
dimensions: [640,480],
initFill: {
color: 'FF0000', // solid red
opacity: 1
},
initStroke: {
width: 5,
color: '000000', // solid black
opacity: 1
},
initOpacity: 1,
imgPath: 'images/',
langPath: 'locale/',
extPath: 'extensions/',
jGraduatePath: 'jgraduate/images/',
extensions: [
'ext-overview_window.js',
'ext-markers.js',
'ext-connector.js',
'ext-eyedropper.js',
'ext-shapes.js',
'ext-imagelib.js',
'ext-grid.js',
'ext-polygon.js',
'ext-star.js',
'ext-panning.js',
'ext-storage.js'
],
initTool: 'select',
wireframe: false,
colorPickerCSS: null,
gridSnapping: false,
gridColor: '#000',
baseUnit: 'px',
snappingStep: 10,
showRulers: true,
showlayers: false,
no_save_warning: false,
showGrid: false, // Set by ext-grid.js
noStorageOnLoad: false,
emptyStorageOnDecline: false, // Used by ext-storage.js
prefsLoaded: false,
langChanged: false
},
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\' ...'
}
},
customHandlers = {};
function loadSvgString(str, callback) {
var success = svgCanvas.setSvgString(str) !== false;
callback = callback || $.noop;
if (success) {
callback(true);
} else {
$.alert(uiStrings.notification.errorLoadingSVG, function() {
callback(false);
});
}
}
Editor.curPrefs = curPrefs;
Editor.curConfig = curConfig;
Editor.tool_scale = 1;
Editor.loadContentAndPrefs = function () {
if (curConfig.noStorageOnLoad && !document.cookie.match(/store=(?:prefsAndContent|prefsOnly)/)) {
return;
}
// LOAD CONTENT
if (window.localStorage && // Cookies do not have enough available memory to hold large documents
(!curConfig.noStorageOnLoad || document.cookie.match(/store=prefsAndContent/))
) {
var name = 'svgedit-' + curConfig.canvasName;
var cached = window.localStorage && window.localStorage.getItem(name);
if (cached) {
Editor.loadFromString(cached);
}
}
// LOAD PREFS
var key, storage = false;
// var host = location.hostname,
// onWeb = host && host.indexOf('.') >= 0;
// Some FF versions throw security errors here
try {
if (window.localStorage) { // && onWeb removed so Webkit works locally
storage = localStorage;
}
} catch(err) {}
Editor.storage = storage;
for (key in defaultPrefs) {
if (defaultPrefs.hasOwnProperty(key)) { // It's our own config, so we don't need to iterate up the prototype chain
var storeKey = 'svg-edit-' + key;
if (storage) {
var val = storage.getItem(storeKey);
if (val) {
curPrefs[key] = String(val); // Convert to string for FF (.value fails in Webkit)
}
}
else if (window.widget) {
curPrefs[key] = widget.preferenceForKey(storeKey);
}
else {
var result = document.cookie.match(new RegExp(storeKey + '=([^;]+)'));
curPrefs[key] = result ? decodeURIComponent(result[1]) : '';
}
}
}
curConfig.prefsLoaded = true;
};
/**
* Store and retrieve preferences
* @param {string} key The preference name to be retrieved or set
* @param {string} [val] The value. If the value supplied is missing or falsey, no change to the preference will be made.
* @returns {string} If val is missing or falsey, the value of the previously stored preference will be returned.
*/
$.pref = function(key, val) {
if (val) {
curPrefs[key] = val;
return;
}
return curPrefs[key];
};
Editor.setConfig = function(opts, noOverride) {
$.each(opts, function(key, val) {
if (opts.hasOwnProperty(key)) {
// Only allow prefs defined in defaultPrefs
if (defaultPrefs.hasOwnProperty(key)) {
if (!noOverride || ) {
$.pref(key, val);
}
}
else if (curConfig.hasOwnProperty(key)) {
if (!noOverride) {
curConfig[key] = val;
}
}
}
});
var extensions;
if (opts.extensions) {
extensions = opts.extensions;
delete opts.extensions;
}
if (extensions) {
curConfig.extensions = opts.noDefaultExtensions && curConfig. ? extensions : curConfig.extensions.concat(extensions);
// Now remove any dupes
curConfig.extensions = $.grep(curConfig.extensions, function (n, i) {
return i === curConfig.extensions.indexOf(n);
});
}
};
// Extension mechanisms may call setCustomHandlers with three functions: opts.open, opts.save, and opts.exportImage
// 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
// opts.exportImage's responsibilities (with regard to the object it is supplied in its 2nd argument) are:
// - inform user of any issues supplied via the "issues" property
// - convert the "svg" property SVG string into an image for export;
// utilize the properties "type" (currently 'PNG', 'JPEG', 'BMP',
// 'WEBP'), "mimeType", and "quality" (for 'JPEG' and 'WEBP'
// types) to determine the proper output.
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.showSaveWarning = false;
svgCanvas.bind('saved', opts.save);
}
if (opts.exportImage || opts.pngsave) { // Deprecating pngsave
svgCanvas.bind('exported', opts.exportImage || 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 svgEditorReadyEvent,
w = window.opener;
if (w) {
try {
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 src, qstr;
urldata = $.deparam.querystring(true);
if (!$.isEmptyObject(urldata)) {
if (urldata.dimensions) {
urldata.dimensions = urldata.dimensions.split(',');
}
if (urldata.bkgd_color) {
urldata.bkgd_color = '#' + urldata.bkgd_color;
}
if (urldata.extensions) {
// For security reasons, disallow cross-domain or cross-folder extensions via URL
urldata.extensions = urldata.extensions.match(/[:\/\\]/) ? '' : urldata.extensions.split(',');
}
// Disallowing extension paths via URL for
// security reasons, even for same-domain
// ones given potential to interact in undesirable
// ways with other script resources
if (urldata.extPath) {
delete urldata.extPath;
}
if (urldata.jGraduatePath) {
delete urldata.jGraduatePath;
}
if (urldata.imgPath) {
delete urldata.imgPath;
}
if (urldata.langPath) {
delete urldata.langPath;
}
svgEditor.setConfig(urldata, true);
src = urldata.source;
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);
}
} else if (qstr.indexOf('paramurl=') !== -1) {
// Get parameter URL (use full length of remaining location.href)
svgEditor.loadFromURL(qstr.substr(9));
} else if (urldata.url) {
svgEditor.loadFromURL(urldata.url);
} else if (!urldata.noStorageOnLoad) {
svgEditor.loadContentAndPrefs();
}
}
else {
svgEditor.loadContentAndPrefs();
}
}());
var setIcon = Editor.setIcon = function(elem, icon_id, forcedSize) {
var icon = (typeof icon_id === 'string') ? $.getSvgIcon(icon_id, true) : icon_id.clone();
if (!icon) {
console.log('NOTE: Icon image missing: ' + icon_id);
return;
}
$(elem).empty().append(icon);
};
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_elements.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.png',
'align_right': 'align-right.png',
'align_top': 'align-top.png',
'align_middle': 'align-middle.png',
'align_bottom': 'align-bottom.png',
'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_elements': 'group_elements',
'#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',
'#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': 28,
'.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' : 15,
'#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 min_height,
tleft = $('#tools_left');
if (tleft.length !== 0) {
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.showSaveWarning = 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'
],
modKey = (svgedit.browser.isMac() ? 'meta+' : 'ctrl+'), // ⌘
path = svgCanvas.pathActions,
undoMgr = svgCanvas.undoMgr,
Utils = svgedit.utilities,
defaultImageURL = curConfig.imgPath + 'logo.png',
workarea = $('#workarea'),
canv_menu = $('#cmenu_canvas'),
// layer_menu = $('#cmenu_layers'), // Unused
exportWindow = null,
tool_scale = 1,
zoomInIcon = 'crosshair',
zoomOutIcon = 'crosshair',
ui_context = 'toolbars',
origSource = '',
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'),
dialog_content = $('#dialog_content'),
dbox = function(type, msg, callback, defaultVal, opts, changeCb, checkbox) {
var ok, ctrl, chkbx;
dialog_content.html('<p>'+msg.replace(/\n/g, '</p><p>')+'</p>')
.toggleClass('prompt', (type == 'prompt'));
btn_holder.empty();
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') {
ctrl = $('<input type="text">').prependTo(btn_holder);
ctrl.val(defaultVal || '');
ctrl.bind('keydown', 'return', function() {ok.click();});
}
else if (type === 'select') {
var div = $('<div style="text-align:center;">');
ctrl = $('<select>').appendTo(div);
if (checkbox) {
var label = $('<label>').text(checkbox.label);
chkbx = $('<input type="checkbox">').appendTo(label);
chkbx.val(checkbox.value);
if (checkbox.tooltip) {
label.attr('title', checkbox.tooltip);
}
chkbx.prop('checked', !!checkbox.checked);
div.append($('<div>').append(label));
}
$.each(opts || [], function (opt, val) {
if (typeof val === 'object') {
ctrl.append($('<option>').val(val.value).html(val.text));
}
else {
ctrl.append($('<option>').html(val));
}
});
dialog_content.append(div);
if (defaultVal) {
ctrl.val(defaultVal);
}
if (changeCb) {
ctrl.bind('change', 'return', changeCb);
}
ctrl.bind('keydown', 'return', function() {ok.click();});
}
if (type === 'process') {
ok.hide();
}
box.show();
ok.click(function() {
box.hide();
var resp = (type === 'prompt' || type === 'select') ? ctrl.val() : true;
if (callback) {
if (chkbx) {
callback(resp, chkbx.prop('checked'));
}
else {
callback(resp);
}
}
}).focus();
if (type === 'prompt' || type === 'select') {
ctrl.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);};
$.select = function(msg, opts, cb, changeCb, txt, checkbox) { dbox('select', msg, cb, txt, opts, changeCb, checkbox);};
}());
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');
};
// used to make the flyouts stay on the screen longer the very first time
// var flyoutspeed = 1250; // Currently unused
var textBeingEntered = false;
var selectedElement = null;
var multiselected = false;
var editingsource = false;
var docprops = false;
var preferences = false;
var cur_context = '';
var origTitle = $('title:first').text();
// Make [1,2,5] array
var r_intervals = [];
var i;
for (i = 0.1; i < 1E5; i *= 10) {
r_intervals.push(i);
r_intervals.push(2 * i);
r_intervals.push(5 * i);
}
// This function highlights the layer passed in (by fading out the other layers)
// if no layer is passed in, this function restores the other layers
var toggleHighlightLayer = function(layerNameToHighlight) {
var i, curNames = [], numLayers = svgCanvas.getCurrentDrawing().getNumLayers();
for (i = 0; i < numLayers; i++) {
curNames[i] = svgCanvas.getCurrentDrawing().getLayerName(i);
}
if (layerNameToHighlight) {
for (i = 0; i < numLayers; ++i) {
if (curNames[i] != layerNameToHighlight) {
svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 0.5);
}
}
} else {
for (i = 0; i < numLayers; ++i) {
svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 1.0);
}
}
};
var populateLayers = function() {
svgCanvas.clearSelection();
var layerlist = $('#layerlist tbody').empty();
var selLayerNames = $('#selLayerNames').empty();
var drawing = svgCanvas.getCurrentDrawing();
var currentLayerName = drawing.getCurrentLayerName();
var layer = svgCanvas.getCurrentDrawing().getNumLayers();
var icon = $.getSvgIcon('eye');
// we get the layers in the reverse z-order (the layer rendered on top is listed first)
while (layer--) {
var name = drawing.getLayerName(layer);
var layerTr = $('<tr class="layer">').toggleClass('layersel', name === currentLayerName);
var layerVis = $('<td class="layervis">').toggleClass('layerinvis', !drawing.getLayerVisibility(name));
var layerName = $('<td class="layername">' + name + '</td>');
layerlist.append(layerTr.append(layerVis, layerName));
selLayerNames.append('<option value="' + name + '">' + name + '</option>');
}
if (icon !== undefined) {
var copy = icon.clone();
$('td.layervis', layerlist).append(copy);
$.resizeSvgIcons({'td.layervis .svg_icon': 14});
}
// handle selection of layer
$('#layerlist td.layername')
.mouseup(function(evt) {
$('#layerlist tr.layer').removeClass('layersel');
$(this.parentNode).addClass('layersel');
svgCanvas.setCurrentLayer(this.textContent);
evt.preventDefault();
})
.mouseover(function() {
toggleHighlightLayer(this.textContent);
})
.mouseout(function() {
toggleHighlightLayer();
});
$('#layerlist td.layervis').click(function() {
var row = $(this.parentNode).prevAll().length;
var name = $('#layerlist tr.layer:eq(' + row + ') td.layername').text();
var vis = $(this).hasClass('layerinvis');
svgCanvas.setLayerVisibility(name, vis);
$(this).toggleClass('layerinvis');
});
// if there were too few rows, let's add a few to make it not so lonely
var num = 5 - $('#layerlist tr.layer').size();
while (num-- > 0) {
// FIXME: there must a better way to do this
layerlist.append('<tr><td style="color:white">_</td><td/></tr>');
}
};
var showSourceEditor = function(e, forSaving) {
if (editingsource) {return;}
editingsource = true;
origSource = svgCanvas.getSvgString();
$('#save_output_btns').toggle(!!forSaving);
$('#tool_source_back').toggle(!forSaving);
$('#svg_source_textarea').val(origSource);
$('#svg_source_editor').fadeIn();
$('#svg_source_textarea').focus();
};
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 {
setTimeout(function () {
setIcon('#tool_select', 'select');
}, 1000);
}
};
var saveHandler = function(wind, svg) {
Editor.showSaveWarning = 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;
// IE9 doesn't allow standalone Data URLs
// https://connect.microsoft.com/IE/feedback/details/542600/data-uri-images-fail-when-loaded-by-themselves
if (svgedit.browser.isIE()) {
showSourceEditor(0, true);
return;
}
// Opens the SVG in new window
var win = wind.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 (svgedit.browser.isGecko()) {
if (svg.indexOf('<defs') !== -1) {
// warning about Mozilla bug #308590 when applicable (seems to be fixed now in Feb 2013)
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(win, data) {
var issues = data.issues,
type = data.type || 'PNG',
dataURLType = (type === 'ICO' ? 'BMP' : type).toLowerCase();
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 = data.quality ? c.toDataURL('image/' + dataURLType, data.quality) : c.toDataURL('image/' + dataURLType);
exportWindow.location.href = datauri;
var done = $.pref('export_notice_done');
if (done !== 'all') {
var note = uiStrings.notification.saveFromBrowser.replace('%s', type);
// 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);
}
}});
};
var operaRepaint = function() {
// Repaints canvas in Opera. Needed for stroke-dasharray change as well as fill change
if (!window.opera) {
return;
}
$('<p/>').hide().appendTo('body').remove();
};
function setStrokeOpt(opt, changeElem) {
var id = opt.id;
var bits = id.split('_');
var pre = bits[0];
var val = bits[1];
if (changeElem) {
svgCanvas.setStrokeAttr('stroke-' + pre, val);
}
operaRepaint();
setIcon('#cur_' + pre, id, 20);
$(opt).addClass('current').siblings().removeClass('current');
}
// This is a common function used when a tool has been clicked (chosen)
// It does several common things:
// - removes the tool_button_current class from whatever tool currently has it
// - hides any flyouts
// - adds the tool_button_current class to the button passed in
var toolButtonClick = Editor.toolButtonClick = function(button, noHiding) {
if ($(button).hasClass('disabled')) {return false;}
if ($(button).parent().hasClass('tools_flyout')) {return true;}
var fadeFlyouts = 'normal';
if (!noHiding) {
$('.tools_flyout').fadeOut(fadeFlyouts);
}
$('#styleoverrides').text('');
workarea.css('cursor', 'auto');
$('.tool_button_current').removeClass('tool_button_current').addClass('tool_button');
$(button).addClass('tool_button_current').removeClass('tool_button');
return true;
};
var clickSelect = Editor.clickSelect = function() {
if (toolButtonClick('#tool_select')) {
svgCanvas.setMode('select');
$('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all}, #svgcanvas svg{cursor:default}');
}
};
var setImageURL = Editor.setImageURL = function(url) {
if (!url) {
url = defaultImageURL;
}
svgCanvas.setImageURL(url);
$('#image_url').val(url);
if (url.indexOf('data:') === 0) {
// data URI found
$('#image_url').hide();
$('#change_image_url').show();
} else {
// regular URL
svgCanvas.embedImage(url, function(dataURI) {
// Couldn't embed, so show warning
$('#url_notice').toggle(!dataURI);
defaultImageURL = url;
});
$('#image_url').show();
$('#change_image_url').hide();
}
};
function setBackground(color, url) {
// if (color == curPrefs.bkgd_color && url == curPrefs.bkgd_url) return;
$.pref('bkgd_color', color);