/*
* 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
* Copyright(c) 2012 Mark MacKay
*
*/
// Dependencies:
// 1) units.js
// 2) browser.js
// 3) svgcanvas.js
(function() {
document.addEventListener("touchstart", touchHandler, true);
document.addEventListener("touchmove", touchHandler, true);
document.addEventListener("touchend", touchHandler, true);
document.addEventListener("touchcancel", touchHandler, true);
if(!window.svgEditor) window.svgEditor = function($) {
var svgCanvas;
var Editor = {};
var is_ready = false;
curConfig = {
canvas_expansion: 1,
dimensions: [580,400],
initFill: {color: 'fff', opacity: 1},
initStroke: {width: 1.5, color: '000', opacity: 1},
initOpacity: 1,
imgPath: 'images/',
extPath: 'extensions/',
jGraduatePath: 'jgraduate/images/',
extensions: [],
initTool: 'select',
wireframe: false,
colorPickerCSS: false,
gridSnapping: false,
gridColor: "#000",
baseUnit: 'px',
snappingStep: 10,
showRulers: (svgedit.browser.isTouch()) ? false : true,
show_outside_canvas: false,
no_save_warning: true,
initFont: 'Helvetica, Arial, sans-serif'
},
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;
Editor.setConfig = function(opts) {
$.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() {
$("#canvas_width").val(curConfig.dimensions[0]);
$("#canvas_height").val(curConfig.dimensions[1]);
$("body").toggleClass("touch", svgedit.browser.isTouch());
// 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);
}
} 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);
}
});
});
}
// 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:27, h:27,
id_match: false,
no_img: !svgedit.browser.isWebkit(), // Opera & Firefox 4 gives odd behavior w/images
fallback_path: curConfig.imgPath,
fallback:{
'logo':'logo.png',
'select':'select.png',
'select_node':'select_node.png',
'pencil':'pencil.png',
'pen':'line.png',
'rect':'square.png',
'ellipse':'ellipse.png',
'path':'path.png',
'text':'text.png',
'image':'image.png',
'zoom':'zoom.png',
'delete':'delete.png',
'spapelib':'shapelib.png',
'node_delete':'node_delete.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',
'arrow_right':'flyouth.png',
'arrow_down':'dropdown.gif'
},
placement: {
'#logo':'logo',
'#tool_select':'select',
'#tool_fhpath':'pencil',
'#tool_line':'pen',
'#tool_rect,#tools_rect_show':'rect',
'#tool_ellipse,#tools_ellipse_show':'ellipse',
'#tool_path':'path',
'#tool_text,#layer_rename':'text',
'#tool_image':'image',
'#tool_zoom':'zoom',
'#tool_node_clone':'node_clone',
'#tool_node_delete':'node_delete',
'#tool_add_subpath':'add_subpath',
'#tool_openclose_path':'open_path',
'#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',
'#zoomLabel':'zoom',
'#palette .palette_item:first, #fill_bg, #stroke_bg':'no_color'
},
resize: {
'#logo .svg_icon': 15,
'.flyout_arrow_horiz .svg_icon': 5,
'#fill_bg .svg_icon, #stroke_bg .svg_icon': svgedit.browser.isTouch() ? 24 : 24,
'.palette_item:first .svg_icon': svgedit.browser.isTouch() ? 30 : 16,
'#zoomLabel .svg_icon': 16,
'#zoom_dropdown .svg_icon': 7
},
callback: function(icons) {
$('.toolbar_button button > svg, .toolbar_button button > img').each(function() {
$(this).parent().prepend(this);
});
$('.tool_button, .tool_button_current').addClass("loaded")
var tleft = $('#tools_left');
if (tleft.length != 0) {
var min_height = tleft.offset().top + tleft.outerHeight();
}
// 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);
}
});
$('#rulers').on("dblclick", function(e){
$("#base_unit_container").css({
top: e.pageY-10,
left: e.pageX-50,
display: 'block'
})
})
$("#base_unit_container")
.on("mouseleave mouseenter", function(e){
t = setTimeout(function(){$("#base_unit_container").fadeOut(500)}, 200)
if(event.type == "mouseover") clearTimeout(t)
})
$("#base_unit")
.on("change", function(e) {
savePreferences();
});
Editor.canvas = svgCanvas = new $.SvgCanvas(document.getElementById("svgcanvas"), curConfig);
Editor.show_save_warning = false;
Editor.paintBox = {fill: null, stroke:null, canvas:null};
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"
],
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 + "placeholder.svg",
workarea = $("#workarea"),
canv_menu = $("#cmenu_canvas"),
exportWindow = null,
tool_scale = 1,
ui_context = 'toolbars',
orig_source = '';
// This puts the correct shortcuts in the menus
if (!isMac) {
$('.shortcut').each(function(){
var text = $(this).text();
$(this).text(text.split("⌘").join("Ctrl+"))
});
}
// 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('
'+msg.replace(/\n/g,'
')+'
')
.toggleClass('prompt',(type=='prompt'));
btn_holder.empty();
var ok = $('').appendTo(btn_holder);
if(type != 'alert') {
$('')
.appendTo(btn_holder)
.on("click, touchstart", function() { box.hide();callback(false)});
}
if(type == 'prompt') {
var input = $('').prependTo(btn_holder);
input.val(defText || '');
input.bind('keydown', 'return', function() {ok.trigger("click touchstart");});
}
if(type == 'process') {
ok.hide();
}
box.show();
ok.on("click touchstart", 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');
}
svgCanvas.setMode('select');
};
var setEyedropperMode = function() {
var curr = $('.tool_button_current');
if(curr.length && curr[0].id !== 'tool_eyedropper') {
curr.removeClass('tool_button_current').addClass('tool_button');
$('#tool_eyedropper').addClass('tool_button_current').removeClass('tool_button');
}
svgCanvas.setMode('eyedropper');
}
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_canvas').hide();
$('#tool_select').addClass('tool_button_current').removeClass('tool_button');
setIcon('#tool_select', 'select_node');
multiselected = false;
if(elems.length) {
selectedElement = elems[0];
}
} else {
if (elems[0]) {
var selector = svgCanvas.selectorManager.requestSelector(elems[0])
selector.reset(elems[0]);
selector.selectorRect.setAttribute('display', 'inline');
}
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 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 = '\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
if(ua.indexOf('Gecko/') !== -1) {
if(svg.indexOf('', {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);
elems = elems.filter(Boolean)
multiselected = (elems.length >= 2) ? elems : false;
if (svgCanvas.elementsAreSame(multiselected)) selectedElement = multiselected[0]
if (selectedElement != null) {
if (!is_node) {
$('#multiselected_panel').hide()
updateToolbar();
}
if (multiselected.length) {//multiselected elements are the same
$('#tools_top').addClass('multiselected')
}
}
else if (multiselected.length) {
$('.context_panel').hide()
$('#tools_top').removeClass('multiselected')
$('#multiselected_panel').show()
}
else {
$('.context_panel').hide()
$('#canvas_panel').show()
$('#tools_top').removeClass('multiselected')
}
togglePathEditMode(is_node, elems);
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) ? elems : null;
// Only updating fields for single elements for now
if(!multiselected) {
switch ( mode ) {
case "rotate":
var ang = svgCanvas.getRotationAngle(elem);
$('#angle').val(Math.round(ang));
rotateCursor(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") {
Editor.paintBox.fill.update();
Editor.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;
}
//animate
var start = Date.now();
var duration = 500;
var diff = (zoomlevel) - (res.zoom)
var zoom = $('#zoom')[0]
var current_zoom = res.zoom
var animateZoom = function(timestamp) {
var progress = timestamp - start
var tick = progress / duration
tick = (Math.pow((tick-1), 3) +1);
svgCanvas.setZoom(current_zoom + (diff*tick));
updateCanvas();
if (tick < 1) {
requestAnimationFrame(animateZoom)
}
else {
$("#zoom").val(zoomlevel*100)
$("option", "#zoom_select").removeAttr("selected")
$("option[value="+ zoomlevel*100 +"]", "#zoom_select").attr("selected", "selected")
}
}
animateZoom(Date.now())
//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) {
var link_str = '';
if(context) {
var str = '';
link_str = '' + svgCanvas.getCurrentDrawing().getCurrentLayerName() + '';
$(context).parentsUntil('#svgcontent > g').andSelf().each(function() {
if(this.id) {
str += ' > ' + this.id;
if(this !== context) {
link_str += ' > ' + this.id + '';
} else {
link_str += ' > ' + this.id;
}
}
});
cur_context = str;
} else {
cur_context = null;
}
$('#cur_context_panel').toggle(!!context).html(link_str);
}
// Makes sure the current selected paint is available to work with
var prepPaints = function() {
Editor.paintBox.fill.prep();
Editor.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 ($('#tools_shapelib').is(":visible")) toolButtonClick(show_sel, false);
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
},50);
} 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 = $('
',{
'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;
var tooltips = [];
$(this).children().each(function() {
tooltips.push(this.title);
});
shower[0].title = tooltips.join(' / ');
});
}
var resize_timer;
var extAdded = function(window, ext) {
var cb_called = false;
var resize_done = false;
var cb_ready = true; // Set to false to delay callback (e.g. wait for $.svgIcons)
function prepResize() {
if(resize_timer) {
clearTimeout(resize_timer);
resize_timer = null;
}
if(!resize_done) {
resize_timer = setTimeout(function() {
resize_done = true;
setIconSize(curPrefs.iconsize);
}, 50);
}
}
var runCallback = function() {
if(ext.callback && !cb_called && cb_ready) {
cb_called = true;
ext.callback();
}
}
var btn_selects = [];
if(ext.context_tools) {
$.each(ext.context_tools, function(i, tool) {
// Add select tool
var cont_id = tool.container_id?(' id="' + tool.container_id + '"'):"";
var panel = $('#' + tool.panel);
// create the panel if it doesn't exist
if(!panel.length)
panel = $('
', {id: tool.panel}).appendTo("#tools_top").hide();
// TODO: Allow support for other types, or adding to existing tool
switch (tool.type) {
case 'tool_button':
var html = '
' + tool.id + '
';
var div = $(html).appendTo(panel);
if (tool.events) {
$.each(tool.events, function(evt, func) {
$(div).bind(evt, func);
});
}
break;
case 'select':
var html = '";
// Creates the tool, hides & adds it, returns the select element
var sel = $(html).appendTo(panel).find('select');
$.each(tool.events, function(evt, func) {
$(sel).bind(evt, func);
});
break;
case 'button-select':
var html = '
'
+ '
';
var list = $('
').appendTo('#option_lists');
if(tool.colnum) {
list.addClass('optcols' + tool.colnum);
}
// Creates the tool, hides & adds it, returns the select element
var dropdown = $(html).appendTo(panel).children();
btn_selects.push({
elem: ('#' + tool.id),
list: ('#' + tool.id + '_opts'),
title: tool.title,
callback: tool.events.change,
cur: ('#cur_' + tool.id)
});
break;
case 'input':
var html = ''
// Creates the tool, hides & adds it, returns the select element
// Add to given tool.panel
var inp = $(html).appendTo(panel).find('input');
if(tool.spindata) {
inp.SpinButton(tool.spindata);
}
if(tool.events) {
$.each(tool.events, function(evt, func) {
inp.bind(evt, func);
});
}
break;
default:
break;
}
});
}
if(ext.buttons) {
var fallback_obj = {},
placement_obj = {},
svgicons = ext.svgicons;
var holders = {};
// Add buttons given by extension
$.each(ext.buttons, function(i, btn) {
var icon;
var id = btn.id;
var num = i;
// Give button a unique ID
while($('#'+id).length) {
id = btn.id + '_' + (++num);
}
if(!svgicons) {
icon = (btn.type == "menu") ? "" : $('');
} else {
fallback_obj[id] = btn.icon;
var svgicon = btn.svgicon ? btn.svgicon : btn.id;
if(btn.type == 'app_menu') {
placement_obj['#' + id + ' > div'] = svgicon;
} else {
placement_obj['#' + id] = svgicon;
}
}
var cls, parent;
// Set button up according to its type
switch ( btn.type ) {
case 'mode_flyout':
case 'mode':
cls = 'tool_button';
if(btn.cls) {
cls += " " + btn.cls;
}
parent = "#tools_left";
break;
case 'context':
cls = 'tool_button';
parent = "#" + btn.panel;
// create the panel if it doesn't exist
if(!$(parent).length)
$('
', {id: btn.panel}).appendTo("#tools_top");
break;
case 'menu':
cls = 'menu_item tool_button';
parent = "#" + (btn.after || btn.panel);
break;
case 'app_menu':
cls = '';
parent = btn.parent || '#main_menu ul';
// create the panel if it doesn't exist
if(!$(parent).length)
$('
', {id: btn.panel}).appendTo("#tools_top");
break;
}
var button = $((btn.list || btn.type == 'app_menu')?'':'')
.attr("id", id)
.attr("title", btn.title)
.addClass(cls);
if(!btn.includeWith && !btn.list) {
if("position" in btn) {
$(parent).children().eq(btn.position).before(button);
} else {
if (btn.type != "menu" || !btn.after) button.appendTo(parent);
else $(parent).after(button);
}
if(btn.type =='mode_flyout') {
// Add to flyout menu / make flyout menu
// var opts = btn.includeWith;
// // opts.button, default, position
var ref_btn = $(button);
var flyout_holder = ref_btn.parent();
// Create a flyout menu if there isn't one already
if(!ref_btn.parent().hasClass('tools_flyout')) {
// Create flyout placeholder
var tls_id = ref_btn[0].id.replace('tool_','tools_')
var show_btn = ref_btn.clone()
.attr('id',tls_id + '_show')
.append($('
',{'class':'flyout_arrow_horiz'}));
ref_btn.before(show_btn);
// Create a flyout div
flyout_holder = makeFlyoutHolder(tls_id, ref_btn);
flyout_holder.data('isLibrary', true);
show_btn.data('isLibrary', true);
}
// var ref_data = Actions.getButtonData(opts.button);
placement_obj['#' + tls_id + '_show'] = btn.id;
// TODO: Find way to set the current icon using the iconloader if this is not default
// Include data for extension button as well as ref button
var cur_h = holders['#'+flyout_holder[0].id] = [{
sel: '#'+id,
fn: btn.events.click,
icon: btn.id,
//key: btn.key,
isDefault: true
}, ref_data];
} else if(btn.type == 'app_menu' || btn.type == 'menu') {
button.append(btn.title);
}
} else if(btn.list) {
// Add button to list
button.addClass('push_button');
$('#' + btn.list + '_opts').append(button);
if(btn.isDefault) {
$('#cur_' + btn.list).append(button.children().clone());
var svgicon = btn.svgicon?btn.svgicon:btn.id;
placement_obj['#cur_' + btn.list] = svgicon;
}
} else if(btn.includeWith) {
// Add to flyout menu / make flyout menu
var opts = btn.includeWith;
// opts.button, default, position
var ref_btn = $(opts.button);
var flyout_holder = ref_btn.parent();
// Create a flyout menu if there isn't one already
if(!ref_btn.parent().hasClass('tools_flyout')) {
// Create flyout placeholder
var tls_id = ref_btn[0].id.replace('tool_','tools_')
var show_btn = ref_btn.clone()
.attr('id',tls_id + '_show')
.append($('
',{'class':'flyout_arrow_horiz'}));
ref_btn.before(show_btn);
// Create a flyout div
flyout_holder = makeFlyoutHolder(tls_id, ref_btn);
}
var ref_data = Actions.getButtonData(opts.button);
if(opts.isDefault) {
placement_obj['#' + tls_id + '_show'] = btn.id;
}
// TODO: Find way to set the current icon using the iconloader if this is not default
// Include data for extension button as well as ref button
var cur_h = holders['#'+flyout_holder[0].id] = [{
sel: '#'+id,
fn: btn.events.click,
icon: btn.id,
key: btn.key,
isDefault: btn.includeWith?btn.includeWith.isDefault:0
}, ref_data];
// {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'}
var pos = ("position" in opts)?opts.position:'last';
var len = flyout_holder.children().length;
// Add at given position or end
if(!isNaN(pos) && pos >= 0 && pos < len) {
flyout_holder.children().eq(pos).before(button);
} else {
flyout_holder.append(button);
cur_h.reverse();
}
}
if(!svgicons) {
button.append(icon);
}
if(!btn.list) {
// Add given events to button
$.each(btn.events, function(name, func) {
if(name == "click") {
if(btn.type == 'mode') {
if(btn.includeWith) {
button.bind(name, func);
} else {
button.bind(name, function() {
if(toolButtonClick(button)) {
func();
}
});
}
if(btn.key) {
$(document).bind('keydown', btn.key, func);
if(btn.title) button.attr("title", btn.title + ' ['+btn.key+']');
}
} else {
button.bind(name, func);
}
} else {
button.bind(name, func);
}
});
}
setupFlyouts(holders);
});
$.each(btn_selects, function() {
addAltDropDown(this.elem, this.list, this.callback, {seticon: true});
});
if (svgicons)
cb_ready = false; // Delay callback
$.svgIcons(svgicons, {
w:27, h:27,
id_match: false,
no_img: (!isWebkit),
fallback: fallback_obj,
placement: placement_obj,
callback: function(icons) {
// Non-ideal hack to make the icon match the current size
if(curPrefs.iconsize && curPrefs.iconsize != 'm') {
prepResize();
}
cb_ready = true; // Ready for callback
runCallback();
}
});
}
runCallback();
};
var getPaint = function(color, opac, type) {
// update the editor's fill paint
var opts = null;
if (color.indexOf("url(#") === 0) {
var refElem = svgCanvas.getRefElem(color);
if(refElem) {
refElem = refElem.cloneNode(true);
} else {
refElem = $("#" + type + "_color defs *")[0];
}
opts = { alpha: opac };
opts[refElem.tagName] = refElem;
}
else if (color.indexOf("#") === 0) {
opts = {
alpha: opac,
solidColor: color.substr(1)
};
}
else {
opts = {
alpha: opac,
solidColor: 'none'
};
}
return new $.jGraduate.Paint(opts);
};
// set the canvas properties at init
var res = svgCanvas.getResolution();
if(curConfig.baseUnit !== "px") {
res.w = svgedit.units.convertUnit(res.w) + curConfig.baseUnit;
res.h = svgedit.units.convertUnit(res.h) + curConfig.baseUnit;
}
var createBackground = function(fill) {
svgCanvas.createLayer("background")
cur_shape = svgCanvas.addSvgElementFromJson({
"element": "rect",
"attr": {
"x": -1,
"y": -1,
"width": res.w+2,
"height": res.h+2,
"stroke": "none",
"id": "canvas_background",
"opacity": 1,
"fill": fill || "#fff",
"style": "pointer-events:none"
}
});
svgCanvas.setCurrentLayer("Layer 1")
svgCanvas.setCurrentLayerPosition("1")
}
// create a new layer background if it doesn't exist
if (!document.getElementById('canvas_background')) createBackground();
var fill = document.getElementById('canvas_background').getAttribute("fill");
// updates the toolbar (colors, opacity, etc) based on the selected element
// This function also updates the opacity and id elements that are in the context panel
var updateToolbar = function() {
if (selectedElement != null) {
switch ( selectedElement.tagName ) {
case 'use':
case 'image':
case 'foreignObject':
break;
case 'g':
case 'a':
// Look for common styles
var gWidth = null;
var childs = selectedElement.getElementsByTagName('*');
for(var i = 0, len = childs.length; i < len; i++) {
var swidth = childs[i].getAttribute("stroke-width");
if(i === 0) {
gWidth = swidth;
} else if(gWidth !== swidth) {
gWidth = null;
}
}
$('#stroke_width').val(gWidth === null ? "" : gWidth);
Editor.paintBox.fill.update(true);
Editor.paintBox.stroke.update(true);
break;
default:
Editor.paintBox.fill.update(true);
Editor.paintBox.stroke.update(true);
$('#stroke_width').val(selectedElement.getAttribute("stroke-width") || 1);
var dash = selectedElement.getAttribute("stroke-dasharray") || "none"
$('option', '#stroke_style').removeAttr('selected');
$('#stroke_style option[value="'+ dash +'"]').attr("selected", "selected");
$('#stroke_style').trigger('change');
$.fn.dragInput.updateCursor($('#stroke_width')[0])
var attr = selectedElement.getAttribute("stroke-linejoin") || 'miter';
if ($('#linejoin_' + attr).length != 0)
setStrokeOpt($('#linejoin_' + attr)[0]);
attr = selectedElement.getAttribute("stroke-linecap") || 'butt';
if ($('#linecap_' + attr).length != 0)
setStrokeOpt($('#linecap_' + attr)[0]);
}
}
// All elements including image and group have opacity
if(selectedElement != null) {
var opac_perc = ((selectedElement.getAttribute("opacity")||1.0)*100);
$('#group_opacity').val(opac_perc);
$.fn.dragInput.updateCursor($('#group_opacity')[0])
}
updateToolButtonState();
};
var setImageURL = Editor.setImageURL = function(url) {
if(!url) url = default_img_url;
svgCanvas.setImageURL(url);
$('#image_url').val(url);
}
var setInputWidth = function(elem) {
var w = Math.min(Math.max(12 + elem.value.length * 6, 50), 300);
$(elem).width(w);
}
// updates the context panel tools based on the selected element
var updateContextPanel = function(e) {
var elem = selectedElement;
// If element has just been deleted, consider it null
if(elem != null && !elem.parentNode) elem = null;
if (multiselected && multiselected[0] != null && !multiselected[0].parentNode) multiselected = false;
var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName();
var currentMode = svgCanvas.getMode();
var unit = curConfig.baseUnit !== 'px' ? curConfig.baseUnit : null;
var is_node = currentMode == 'pathedit'; //elem ? (elem.id && elem.id.indexOf('pathpointgrip') == 0) : false;
var menu_items = $('#cmenu_canvas li');
$('.context_panel').hide();
$('.menu_item', '#edit_menu').addClass('disabled');
$('.menu_item', '#object_menu').addClass('disabled');
//hack to show the proper multialign box
if (multiselected) {
multiselected = multiselected.filter(Boolean);
elem = (svgCanvas.elementsAreSame(multiselected)) ? multiselected[0] : null
if (elem) $("#tools_top").addClass("multiselected")
}
if (!elem && !multiselected) {
$("#tools_top").removeClass("multiselected")
$("#stroke_panel").hide();
$("#canvas_panel").show();
}
if (elem != null) {
$("#stroke_panel").show();
var elname = elem.nodeName;
var angle = svgCanvas.getRotationAngle(elem);
$('#angle').val(Math.round(angle));
var blurval = svgCanvas.getBlur(elem);
$('#blur').val(blurval);
if(!is_node && currentMode != 'pathedit') {
$('#selected_panel').show();
$('.action_selected').removeClass('disabled');
// Elements in this array already have coord fields
var x, y
if(['g', 'polyline', 'path'].indexOf(elname) >= 0) {
var bb = svgCanvas.getStrokedBBox([elem]);
if(bb) {
x = bb.x;
y = bb.y;
}
}
if(unit) {
x = svgedit.units.convertUnit(x);
y = svgedit.units.convertUnit(y);
}
$("#" + elname +"_x").val(Math.round(x))
$("#" + elname +"_y").val(Math.round(y))
if (elname === "polyline") {
//we're acting as if polylines were paths
$("#path_x").val(Math.round(x))
$("#path_y").val(Math.round(y))
}
// Elements in this array cannot be converted to a path
var no_path = ['image', 'text', 'path', 'g', 'use'].indexOf(elname) == -1;
if (no_path) $('.action_path_convert_selected').removeClass('disabled');
if (elname === "path") $('.action_path_selected').removeClass('disabled');
} else {
$('#path_node_panel').show();
$('#stroke_panel').hide();
var point = path.getNodePoint();
$('#tool_add_subpath').removeClass('push_button_pressed').addClass('tool_button');
$('#tool_node_delete').toggleClass('disabled', !path.canDeleteNodes);
// Show open/close button based on selected point
setIcon('#tool_openclose_path', path.closed_subpath ? 'open_path' : 'close_path');
if(point) {
var seg_type = $('#seg_type');
if(unit) {
point.x = svgedit.units.convertUnit(point.x);
point.y = svgedit.units.convertUnit(point.y);
}
$('#path_node_x').val(Math.round(point.x));
$('#path_node_y').val(Math.round(point.y));
if(point.type) {
seg_type.val(point.type).removeAttr('disabled');
} else {
seg_type.val(4).attr('disabled','disabled');
}
}
return;
}
var link_href = null;
if (el_name === 'a') {
link_href = svgCanvas.getHref(elem);
$('#g_panel').show();
}
if(elem.parentNode.tagName === 'a') {
if(!$(elem).siblings().length) {
$('#a_panel').show();
link_href = svgCanvas.getHref(elem.parentNode);
}
}
// Hide/show the make_link buttons
$('#tool_make_link, #tool_make_link').toggle(!link_href);
if(link_href) {
$('#link_url').val(link_href);
}
// update contextual tools here
var panels = {
g: [],
a: [],
rect: ['rx','width','height', 'x', 'y'],
image: ['width','height', 'x', 'y'],
circle: ['cx','cy','r'],
ellipse: ['cx','cy','rx','ry'],
line: ['x1','y1','x2','y2'],
text: ['x', 'y'],
'use': [],
path : []
};
var el_name = elem.tagName;
if($(elem).data('gsvg')) {
$('#g_panel').show();
}
if (el_name == "path" || el_name == "polyline") {
$('#path_panel').show();
}
if(panels[el_name]) {
var cur_panel = panels[el_name];
$('#' + el_name + '_panel').show();
// corner radius has to live in a different panel
// because otherwise it changes the position of the
// of the elements
if(el_name == "rect") $("#cornerRadiusLabel").show()
else $("#cornerRadiusLabel").hide()
$.each(cur_panel, function(i, item) {
var attrVal = elem.getAttribute(item);
if(curConfig.baseUnit !== 'px' && elem[item]) {
var bv = elem[item].baseVal.value;
attrVal = svgedit.units.convertUnit(bv);
}
//update the draginput cursors
var name_item = document.getElementById(el_name + '_' + item);
name_item.value = Math.round(attrVal) || 0;
if (name_item.getAttribute("data-cursor") === "true") {
$.fn.dragInput.updateCursor(name_item );
}
});
if(el_name == 'text') {
var font_family = elem.getAttribute("font-family");
var select = document.getElementById("font_family_dropdown");
select.selectedIndex = 3
$('#text_panel').css("display", "inline");
$('#tool_italic').toggleClass('active', svgCanvas.getItalic())
$('#tool_bold').toggleClass('active', svgCanvas.getBold())
$('#font_family').val(font_family);
$('#font_size').val(elem.getAttribute("font-size"));
$('#text').val(elem.textContent);
$('#preview_font').text(font_family.split(",")[0].replace(/'/g, "")).css('font-family', font_family);
if (svgCanvas.addedNew) {
// Timeout needed for IE9
setTimeout(function() {
$('#text').focus().select();
},100);
}
} // text
else if(el_name == 'image') {
setImageURL(svgCanvas.getHref(elem));
} // image
else if(el_name === 'g' || el_name === 'use') {
$('#container_panel').show();
$('.action_group_selected').removeClass('disabled');
var title = svgCanvas.getTitle();
}
}
menu_items[(el_name === 'g' ? 'en':'dis') + 'ableContextMenuItems']('#ungroup');
menu_items[((el_name === 'g' || !multiselected) ? 'dis':'en') + 'ableContextMenuItems']('#group');
}
if (multiselected) {
$('#multiselected_panel').show();
$('.action_multi_selected').removeClass('disabled');
menu_items
.enableContextMenuItems('#group')
.disableContextMenuItems('#ungroup');
}
if (!elem) {
menu_items.disableContextMenuItems('#delete,#cut,#copy,#group,#ungroup,#move_front,#move_up,#move_down,#move_back');
}
// update history buttons
if (undoMgr.getUndoStackSize() > 0) {
$('#tool_undo').removeClass( 'disabled');
}
else {
$('#tool_undo').addClass( 'disabled');
}
if (undoMgr.getRedoStackSize() > 0) {
$('#tool_redo').removeClass( 'disabled');
}
else {
$('#tool_redo').addClass( 'disabled');
}
svgCanvas.addedNew = false;
if ( (elem && !is_node) || multiselected) {
// update the selected elements' layer
$('#selLayerNames').removeAttr('disabled').val(currentLayerName);
// Enable regular menu options
canv_menu.enableContextMenuItems('#delete,#cut,#copy,#move_front,#move_up,#move_down,#move_back');
}
};
$('#text').on("focus", function(e){ textBeingEntered = true; } );
$('#text').on("blur", function(){ textBeingEntered = false; } );
// bind the selected event to our function that handles updates to the UI
svgCanvas.bind("selected", selectedChanged);
svgCanvas.bind("transition", elementTransition);
svgCanvas.bind("changed", elementChanged);
svgCanvas.bind("saved", saveHandler);
svgCanvas.bind("exported", exportHandler);
svgCanvas.bind("zoomed", zoomChanged);
svgCanvas.bind("contextset", contextChanged);
svgCanvas.bind("extension_added", extAdded);
svgCanvas.textActions.setInputElem($("#text")[0]);
var str = ''
$.each(palette, function(i,item){
str += '';
});
$('#palette').append(str);
var changeFontSize = function(ctl) {
svgCanvas.setFontSize(ctl.value);
}
var changeStrokeWidth = function(ctl) {
var val = ctl.value;
if(val == 0 && selectedElement && ['line', 'polyline'].indexOf(selectedElement.nodeName) >= 0) {
val = ctl.value = 1;
}
svgCanvas.setStrokeWidth(val);
}
//cache
var $indicator = $('#tool_angle_indicator')
var $reorient = $('#tool_reorient')
rotateCursor = function(angle){
var rotate_string = 'rotate('+ angle + 'deg)'
$indicator.css({
'-webkit-transform': rotate_string,
'-moz-transform': rotate_string,
'-o-transform': rotate_string,
'-ms-transform': rotate_string,
'transform': rotate_string
});
}
var changeRotationAngle = function(ctl) {
svgCanvas.setRotationAngle(ctl.value);
rotateCursor(ctl.value)
$('#tool_reorient').toggleClass('disabled', ctl.value == 0);
}
var changeZoom = function(ctl) {
var zoomlevel = ctl.value / 100;
if(zoomlevel < .001) {
ctl.value = .1;
return;
}
var zoom = svgCanvas.getZoom();
var w_area = workarea;
zoomChanged(window, {
width: 0,
height: 0,
// center pt of scroll position
x: (w_area[0].scrollLeft + w_area.width()/2)/zoom,
y: (w_area[0].scrollTop + w_area.height()/2)/zoom,
zoom: zoomlevel
}, true);
}
var changeBlur = function(ctl, completed) {
val = ctl.value;
$('#blur').val(val);
svgCanvas.setBlur(val, true);
}
var operaRepaint = function() {
// Repaints canvas in Opera. Needed for stroke-dasharray change as well as fill change
if(!window.opera) return;
$('').hide().appendTo('body').remove();
}
$('#stroke_style').change(function(){
svgCanvas.setStrokeAttr('stroke-dasharray', $(this).val());
$("#stroke_style_label").html(this.options[this.selectedIndex].text)
operaRepaint();
});
$('#seg_type').change(function() {
svgCanvas.setSegType($(this).val());
$("#seg_type_label").html(this.options[this.selectedIndex].text)
});
// Lose focus for select elements when changed (Allows keyboard shortcuts to work better)
$('select').change(function(){$(this).blur();});
$('#font_family').change(function() {
svgCanvas.setFontFamily(this.value);
});
$('#text').keyup(function(){
svgCanvas.setTextContent(this.value);
});
changeAttribute = function(el, completed) {
var attr = el.getAttribute("data-attr");
var multiplier = el.getAttribute("data-multiplier") || 1;
multiplier = parseFloat(multiplier);
var val = el.value * multiplier;
var valid = svgedit.units.isValidUnit(attr, val, selectedElement);
if(!valid) {
$.alert(uiStrings.notification.invalidAttrValGiven);
el.value = selectedElement.getAttribute(attr);
return false;
}
//if (!noUndo) svgCanvas.changeSelectedAttribute(attr, val);
svgCanvas.changeSelectedAttributeNoUndo(attr, val);
};
// Prevent selection of elements when shift-clicking
$('#palette').mouseover(function() {
var inp = $('');
$(this).append(inp);
inp.focus().remove();
});
$('.palette_item').on("mousedown touchstart touchmove", function(evt){
var isStroke = $('#tool_stroke').hasClass('active');
var picker = isStroke ? "stroke" : "fill";
var color = $(this).attr('data-rgb');
var paint = null;
// Webkit-based browsers returned 'initial' here for no stroke
if (color === 'transparent' || color === 'initial' || color === '#none') {
color = 'none';
paint = new $.jGraduate.Paint();
}
else {
paint = new $.jGraduate.Paint({alpha: 100, solidColor: color.substr(1)});
}
Editor.paintBox[picker].setPaint(paint);
if (isStroke) {
svgCanvas.setColor('stroke', color);
if (color != 'none' && svgCanvas.getStrokeOpacity() != 1) {
svgCanvas.setPaintOpacity('stroke', 1.0);
}
} else {
svgCanvas.setColor('fill', color);
if (color != 'none' && svgCanvas.getFillOpacity() != 1) {
svgCanvas.setPaintOpacity('fill', 1.0);
}
}
updateToolButtonState();
}).bind('contextmenu', function(e) {e.preventDefault()});
$("#toggle_stroke_tools").toggle(function() {
$(".stroke_tool").css('display','table-cell');
$(this).addClass('expanded');
resetScrollPos();
}, function() {
$(".stroke_tool").css('display','none');
$(this).removeClass('expanded');
resetScrollPos();
});
// 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 = function(button, noHiding) {
if ($(button).hasClass('disabled')) return false;
if($(button).parent().hasClass('tools_flyout')) return true;
var fadeFlyouts = fadeFlyouts || 'normal';
if(!noHiding) {
$('.tools_flyout').fadeOut(fadeFlyouts);
}
$('#styleoverrides').text('');
$('.tool_button_current').removeClass('tool_button_current').addClass('tool_button');
$(button).addClass('tool_button_current').removeClass('tool_button');
return true;
};
(function() {
var last_x = null, last_y = null, w_area = workarea[0],
panning = false, keypan = false;
$('#svgcanvas').bind('mousemove mouseup touchend', function(evt) {
if(panning === false) return;
w_area.scrollLeft -= (evt.clientX - last_x);
w_area.scrollTop -= (evt.clientY - last_y);
last_x = evt.clientX;
last_y = evt.clientY;
if(evt.type === 'mouseup' || evt.type === 'touchend') panning = false;
return false;
})
.on("mousedown touchmove", function(evt) {
if(evt.button === 1 || keypan === true || (evt.originalEvent.touches && evt.originalEvent.touches.length >= 2)) {
panning = true;
last_x = evt.clientX;
last_y = evt.clientY;
return false;
}
});
$(window).mouseup(function() {
panning = false;
$('body').removeClass('dragging')
});
$(document).bind('keydown', 'space', function(evt) {
evt.preventDefault();
svgCanvas.spaceKey = keypan = true;
}).bind('keyup', 'space', function(evt) {
evt.preventDefault();
svgCanvas.spaceKey = keypan = false;
}).bind('keydown', 'alt', function(evt) {
if(svgCanvas.getMode() === 'zoom') {
workarea.addClass('out');
}
}).bind('keyup', 'alt', function(evt) {
if(svgCanvas.getMode() === 'zoom') {
workarea.removeClass('out');
}
})
}());
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');
}
//menu handling
var menus = $('.menu');
var blinker = function(e) {
e.target.style.background = "#fff";
setTimeout(function(){e.target.style.background = "#ddd";}, 50);
setTimeout(function(){e.target.style.background = "#fff";}, 150);
setTimeout(function(){e.target.style.background = "#ddd";}, 200);
setTimeout(function(){e.target.style.background = "";}, 200);
setTimeout(function(){$('#menu_bar').removeClass('active')}, 220);
return false;
}
var closer = function(e){
if (e.target.nodeName.toLowerCase() === "input") return false;
if (!$(e.target).hasClass("menu_title") && !$(e.target).parent().hasClass("menu_title")) {
if(!$(e.target).hasClass("disabled") && $(e.target).hasClass("menu_item")) blinker(e)
else $('#menu_bar').removeClass('active')
}
}
$('.menu_item').on('mousedown touchstart', function(e){blinker(e)});
$("svg, body").on('mousedown touchstart', function(e){closer(e)});
var accumulatedDelta = 0
var zoomSteps = [6, 12, 16, 33, 50, 66, 100, 150, 200, 300, 400, 600, 800, 1200]
$('#workarea').on('mousewheel', function(e, delta, deltaX, deltaY){
if (e.altKey) {
e.preventDefault();
var currentZoom = svgCanvas.getZoom()*100;
var arr_length = zoomSteps.length;
for (i=0; i 0) zoom = (zoomSteps[i] <= currentZoom) ? zoomSteps[max] : zoom;
if (deltaY < 0) zoom = (zoomSteps[i] < currentZoom) ? zoomSteps[i] : zoom;
}
if (zoom) changeZoom({value: zoom});
}
})
$('.menu_title')
.on('mousedown', function() {
$("#tools_shapelib").hide()
$("#menu_bar").toggleClass('active');
menus.removeClass('open');
$(this).parent().addClass('open');
})
.on('mouseover', function() {
menus.removeClass('open');
$(this).parent().addClass('open');
});
// Made public for UI customization.
// TODO: Group UI functions into a public svgEditor.ui interface.
Editor.addDropDown = function(elem, callback, dropUp) {
if ($(elem).length == 0) return; // Quit if called on non-existant element
var button = $(elem).find('button');
var list = $(elem).find('ul').attr('id', $(elem)[0].id + '-list');
if(!dropUp) {
// Move list to place where it can overflow container
$('#option_lists').append(list);
}
var on_button = false;
if(dropUp) {
$(elem).addClass('dropup');
}
list.find('li').bind('mouseup', callback);
$(window).mouseup(function(evt) {
if(!on_button) {
button.removeClass('down');
list.hide();
}
on_button = false;
});
button.bind('mousedown',function() {
if (!button.hasClass('down')) {
button.addClass('down');
if(!dropUp) {
var pos = $(elem).offset();
// position slider
list.css({
top: pos.top,
left: pos.left - 110
});
}
list.show();
on_button = true;
} else {
button.removeClass('down');
list.hide();
}
}).hover(function() {
on_button = true;
}).mouseout(function() {
on_button = false;
});
}
// TODO: Combine this with addDropDown or find other way to optimize
var addAltDropDown = function(elem, list, callback, opts) {
var button = $(elem);
var list = $(list);
var on_button = false;
var dropUp = opts.dropUp;
if(dropUp) {
$(elem).addClass('dropup');
}
list.find('li').bind('mouseup', function() {
if(opts.seticon) {
setIcon('#cur_' + button[0].id , $(this).children());
$(this).addClass('current').siblings().removeClass('current');
}
callback.apply(this, arguments);
});
$(window).mouseup(function(evt) {
if(!on_button) {
button.removeClass('down');
list.hide();
list.css({top:0, left:0});
}
on_button = false;
});
var height = list.height();
$(elem).bind('mousedown',function() {
var off = $(elem).offset();
if(dropUp) {
off.top -= list.height();
off.left += 8;
} else {
off.top += $(elem).height();
}
$(list).offset(off);
if (!button.hasClass('down')) {
button.addClass('down');
list.show();
on_button = true;
return false;
} else {
button.removeClass('down');
// CSS position must be reset for Webkit
list.hide();
list.css({top:0, left:0});
}
}).hover(function() {
on_button = true;
}).mouseout(function() {
on_button = false;
});
if(opts.multiclick) {
list.mousedown(function() {
on_button = true;
});
}
}
$('#font_family_dropdown').change(function() {
var fam = this.options[this.selectedIndex].value
var fam_display = this.options[this.selectedIndex].text
$('#preview_font').html(fam_display).css("font-family", fam);
$('#font_family').val(fam).change();
});
$('div', '#position_opts').each(function(){
this.addEventListener("mouseup", function(){
var letter = this.id.replace('tool_pos','').charAt(0);
svgCanvas.alignSelectedElements(letter, 'page');
})
});
/*
When a flyout icon is selected
(if flyout) {
- Change the icon
- Make pressing the button run its stuff
}
- Run its stuff
When its shortcut key is pressed
- If not current in list, do as above
, else:
- Just run its stuff
*/
// Unfocus text input when workarea is mousedowned.
(function() {
var inp;
var unfocus = function() {
$(inp).blur();
}
$('#svg_editor').find('button, select, input:not(#text)').focus(function() {
inp = this;
ui_context = 'toolbars';
workarea.mousedown(unfocus);
}).blur(function() {
ui_context = 'canvas';
workarea.unbind('mousedown', unfocus);
// Go back to selecting text if in textedit mode
if(svgCanvas.getMode() == 'textedit') {
$('#text').focus();
}
});
}());
var clickSelect = function() {
if (toolButtonClick('#tool_select')) {
svgCanvas.setMode('select');
}
};
var clickFHPath = function() {
if (toolButtonClick('#tool_fhpath')) {
svgCanvas.setMode('fhpath');
}
};
var clickLine = function() {
if (toolButtonClick('#tool_line')) {
svgCanvas.setMode('line');
}
};
var clickSquare = function(){
if (toolButtonClick('#tool_square')) {
svgCanvas.setMode('square');
}
};
var clickRect = function(){
if (toolButtonClick('#tool_rect')) {
svgCanvas.setMode('rect');
}
};
var clickFHRect = function(){
if (toolButtonClick('#tool_fhrect')) {
svgCanvas.setMode('fhrect');
}
};
var clickCircle = function(){
if (toolButtonClick('#tool_circle')) {
svgCanvas.setMode('circle');
}
};
var clickEllipse = function(){
if (toolButtonClick('#tool_ellipse')) {
svgCanvas.setMode('ellipse');
}
};
var clickFHEllipse = function(){
if (toolButtonClick('#tool_fhellipse')) {
svgCanvas.setMode('fhellipse');
}
};
var clickImage = function(){
if (toolButtonClick('#tool_image')) {
svgCanvas.setMode('image');
}
};
var clickZoom = function(){
if (toolButtonClick('#tool_zoom')) {
svgCanvas.setMode('zoom');
}
};
var dblclickZoom = function(){
if (toolButtonClick('#tool_zoom')) {
zoomImage();
setSelectMode();
}
};
var clickText = function(){
if (toolButtonClick('#tool_text')) {
svgCanvas.setMode('text');
}
};
var clickPath = function(){
if (toolButtonClick('#tool_path')) {
svgCanvas.setMode('path');
}
};
// Delete is a contextual tool that only appears in the ribbon if
// an element has been selected
var deleteSelected = function() {
if (selectedElement != null || multiselected) {
svgCanvas.deleteSelectedElements();
}
};
var cutSelected = function() {
if (selectedElement != null || multiselected) {
if (window.event.type === "keydown") flash($('#edit_menu'));
svgCanvas.cutSelectedElements();
}
};
var copySelected = function() {
if (selectedElement != null || multiselected) {
if (window.event.type === "keydown") flash($('#edit_menu'));
svgCanvas.copySelectedElements();
}
};
var pasteSelected = function() {
if (window.event.type === "keydown") flash($('#edit_menu'));
var zoom = svgCanvas.getZoom();
var x = (workarea[0].scrollLeft + workarea.width()/2)/zoom - svgCanvas.contentW;
var y = (workarea[0].scrollTop + workarea.height()/2)/zoom - svgCanvas.contentH;
svgCanvas.pasteElements('point', x, y);
}
var moveToTopSelected = function() {
if (selectedElement != null) {
if (window.event.type === "keydown") flash($('#object_menu'));
svgCanvas.moveToTopSelectedElement();
}
};
var moveToBottomSelected = function() {
if (selectedElement != null) {
if (window.event.type === "keydown") flash($('#object_menu'));
svgCanvas.moveToBottomSelectedElement();
}
};
var moveUpSelected = function() {
if (selectedElement != null) {
if (window.event.type === "keydown") flash($('#object_menu'));
svgCanvas.moveUpDownSelected("Up");
}
};
var moveDownSelected = function() {
if (selectedElement != null) {
if (window.event.type === "keydown") flash($('#object_menu'));
svgCanvas.moveUpDownSelected("Down");
}
};
var moveUpDownSelected = function(dir) {
if (selectedElement != null) {
if (window.event.type === "keydown") flash($('#object_menu'));
svgCanvas.moveUpDownSelected(dir);
}
};
var convertToPath = function() {
if (selectedElement != null) {
svgCanvas.convertToPath();
elems = svgCanvas.getSelectedElems()
//svgCanvas.selectorManager.requestSelector(elems[0]).reset(elems[0])
svgCanvas.selectorManager.requestSelector(elems[0]).selectorRect.setAttribute("display", "none");
svgCanvas.setMode("pathedit")
path.toEditMode(elems[0]);
svgCanvas.clearSelection();
}
}
var reorientPath = function() {
if (selectedElement != null) {
path.reorient();
}
}
var makeHyperlink = function() {
if (selectedElement != null || multiselected) {
$.prompt(uiStrings.notification.enterNewLinkURL, "http://", function(url) {
if(url) svgCanvas.makeHyperlink(url);
});
}
}
var moveSelected = function(dx,dy) {
if (selectedElement != null || multiselected) {
if(curConfig.gridSnapping) {
// Use grid snap value regardless of zoom level
var multi = svgCanvas.getZoom() * curConfig.snappingStep;
dx *= multi;
dy *= multi;
}
$('input').blur()
svgCanvas.moveSelectedElements(dx,dy);
}
};
var linkControlPoints = function() {
var linked = !$('#tool_node_link').hasClass('checked');
if (linked)
$('#tool_node_link').addClass('checked').find("input").attr("checked", true);
else
$('#tool_node_link').removeClass('checked').find("input").attr("checked", false);
path.linkControlPoints(linked);
}
var clonePathNode = function() {
if (path.getNodePoint()) {
path.clonePathNode();
}
};
var deletePathNode = function() {
if (path.getNodePoint()) {
path.deletePathNode();
}
};
var addSubPath = function() {
var button = $('#tool_add_subpath');
var sp = !button.hasClass('push_button_pressed');
if (sp) {
button.addClass('push_button_pressed').removeClass('tool_button');
} else {
button.removeClass('push_button_pressed').addClass('tool_button');
}
path.addSubPath(sp);
};
var opencloseSubPath = function() {
path.opencloseSubPath();
}
var selectNext = function() {
svgCanvas.cycleElement(1);
};
var selectPrev = function() {
svgCanvas.cycleElement(0);
};
var rotateSelected = function(cw,step) {
if (selectedElement == null || multiselected) return;
if(!cw) step *= -1;
var new_angle = $('#angle').val()*1 + step;
svgCanvas.setRotationAngle(new_angle);
updateContextPanel();
};
var clickClear = function(){
var dims = curConfig.dimensions;
$.confirm(uiStrings.notification.QwantToClear, function(ok) {
if(!ok) return;
setSelectMode();
svgCanvas.clear();
svgCanvas.setResolution(dims[0], dims[1]);
updateCanvas(true);
zoomImage();
updateContextPanel();
prepPaints();
svgCanvas.runExtensions('onNewDocument');
});
};
var clickBold = function(){
svgCanvas.setBold( !svgCanvas.getBold() );
updateContextPanel();
return false;
};
var clickItalic = function(){
svgCanvas.setItalic( !svgCanvas.getItalic() );
updateContextPanel();
return false;
};
var clickExport = function() {
// Open placeholder window (prevents popup)
if(!customHandlers.pngsave) {
var str = uiStrings.notification.loadingImage;
exportWindow = window.open("data:text/html;charset=utf-8," + str + "<\/title>
" + str + "<\/h1>");
}
if(window.canvg) {
svgCanvas.rasterExport();
} else {
$.getScript('canvg/rgbcolor.js', function() {
$.getScript('canvg/canvg.js', function() {
svgCanvas.rasterExport();
});
});
}
}
// by default, svgCanvas.open() is a no-op.
// it is up to an extension mechanism (opera widget, etc)
// to call setCustomHandlers() which will make it do something
var clickOpen = function(){
svgCanvas.open();
};
var clickImport = function(){
};
var flash = function($menu){
var menu_title = $menu.prev();
menu_title.css("background", "#09f");
setTimeout(function(){menu_title.css("background", "")}, 200);
}
var clickUndo = function(){
if (undoMgr.getUndoStackSize() > 0) {
if (window.event.type === "keydown") flash($('#edit_menu'));
undoMgr.undo();
}
};
var clickRedo = function(){
if (undoMgr.getRedoStackSize() > 0) {
if (window.event.type === "keydown") flash($('#edit_menu'));
undoMgr.redo();
}
};
var clickGroup = function(){
// group
if (multiselected) {
svgCanvas.groupSelectedElements();
}
// ungroup
else if(selectedElement){
svgCanvas.ungroupSelectedElement();
}
};
var clickClone = function(){
if (window.event.type === "keydown") flash($('#edit_menu'));
svgCanvas.cloneSelectedElements(20,20);
};
var clickAlign = function() {
var letter = this.id.replace('tool_align','').charAt(0);
svgCanvas.alignSelectedElements(letter, $('#align_relative_to').val());
};
var clickSwitch = function() {
var stroke_rect = document.querySelector('#tool_stroke rect');
var fill_rect = document.querySelector('#tool_fill rect');
var fill_color = fill_rect.getAttribute("fill");
var stroke_color = stroke_rect.getAttribute("fill");
var stroke_opacity = parseFloat(stroke_rect.getAttribute("stroke-opacity"));
if (isNaN(stroke_opacity)) {stroke_opacity = 100;}
var fill_opacity = parseFloat(fill_rect.getAttribute("fill-opacity"));
if (isNaN(fill_opacity)) {fill_opacity = 100;}
var stroke = getPaint(stroke_color, stroke_opacity, "stroke");
var fill = getPaint(fill_color, fill_opacity, "fill");
Editor.paintBox.fill.setPaint(stroke, true);
Editor.paintBox.stroke.setPaint(fill, true);
};
var zoomImage = function(multiplier) {
var res = svgCanvas.getResolution();
multiplier = multiplier?res.zoom * multiplier:1;
// setResolution(res.w * multiplier, res.h * multiplier, true);
$('#zoom').val(multiplier * 100);
svgCanvas.setZoom(multiplier);
zoomDone();
updateCanvas(true);
};
var zoomDone = function() {
// updateBgImage();
updateWireFrame();
//updateCanvas(); // necessary?
}
var clickWireframe = function() {
var wf = !$('#tool_wireframe').hasClass('push_button_pressed');
if (wf)
$('#tool_wireframe').addClass('push_button_pressed');
else
$('#tool_wireframe').removeClass('push_button_pressed');
workarea.toggleClass('wireframe');
if(supportsNonSS) return;
var wf_rules = $('#wireframe_rules');
if(!wf_rules.length) {
wf_rules = $('