',{'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':
$(".context_panel").hide();
$("#use_panel").show();
break;
case 'image':
$(".context_panel").hide();
$("#image_panel").show();
break;
case 'foreignObject':
$(".context_panel").hide();
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 ? "0" : gWidth);
updateContextPanel();
break;
default:
//removed because multiselect shouldnt set color
//Editor.paintBox.fill.update(false);
//Editor.paintBox.stroke.update(false);
$('#stroke_width').val(selectedElement.getAttribute("stroke-width") || 0);
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])
$.fn.dragInput.updateCursor($('#blur')[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])
}
};
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;
if (is_node) {
$('.context_panel').hide();
$('#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');
$("#seg_type_label").html(point.type == 4 ? "Straight" : "Curve")
} else {
seg_type.val(4).attr('disabled','disabled');
}
}
$("#tools_top").removeClass("multiselected")
$("#stroke_panel").hide();
$("#canvas_panel").hide();
return;
}
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');
}
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 = '
\
\
'
palette.forEach(function(item, i){
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) {
var preventUndo = true;
svgCanvas.setRotationAngle(ctl.value, preventUndo);
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);
if (completed) {
svgCanvas.setBlur(val, true);
}
else {
svgCanvas.setBlurNoUndo(val);
}
}
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);
};
picking = false;
$(document).on("mouseup", function(){picking = false;})
$('#palette').on("mousemove mousedown touchstart touchmove", ".palette_item", function(evt){
evt.preventDefault();
if (evt.type == "mousedown") picking = true;
if (picking) {
var isStroke = $('#tool_stroke').hasClass('active');
var picker = isStroke ? "stroke" : "fill";
var color = $(this).attr('data-rgb');
var paint = null;
var noUndo = true;
if (evt.type == "mousedown") noUndo = false
// 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, noUndo);
if (color != 'none' && svgCanvas.getStrokeOpacity() != 1) {
svgCanvas.setPaintOpacity('stroke', 1.0);
}
} else {
svgCanvas.setColor('fill', color, noUndo);
if (color != 'none' && svgCanvas.getFillOpacity() != 1) {
svgCanvas.setPaintOpacity('fill', 1.0);
}
}
}
}).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;
var move_pan = 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;
}
var start_pan = 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;
}
}
$('#svgcanvas')
.on('mousemove mouseup touchend', move_pan)
.on("mousedown touchmove", start_pan)
$(window).mouseup(function() {
panning = false;
});
$(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 && 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
$('#workarea').on('mousewheel', function(e, delta, deltaX, deltaY){
if (e.altKey || e.ctrlKey) {
e.preventDefault();
zoom = parseInt($("#zoom").val())
$("#zoom").val(parseInt(zoom + deltaY*(e.altKey ? 10 : 5))).change()
}
});
$('.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 methodDraw.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();
}
if (path.getNodePoint()) {
path.deletePathNode();
}
};
var cutSelected = function() {
if (selectedElement != null || multiselected) {
flash($('#edit_menu'));
svgCanvas.cutSelectedElements();
}
};
var copySelected = function() {
if (selectedElement != null || multiselected) {
flash($('#edit_menu'));
svgCanvas.copySelectedElements();
}
};
var pasteSelected = function() {
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) {
flash($('#object_menu'));
svgCanvas.moveToTopSelectedElement();
}
};
var moveToBottomSelected = function() {
if (selectedElement != null) {
flash($('#object_menu'));
svgCanvas.moveToBottomSelectedElement();
}
};
var moveUpSelected = function() {
if (selectedElement != null) {
flash($('#object_menu'));
svgCanvas.moveUpDownSelected("Up");
}
};
var moveDownSelected = function() {
if (selectedElement != null) {
flash($('#object_menu'));
svgCanvas.moveUpDownSelected("Down");
}
};
var moveUpDownSelected = function(dir) {
if (selectedElement != null) {
flash($('#object_menu'));
svgCanvas.moveUpDownSelected(dir);
}
};
var convertToPath = function() {
if (selectedElement != null) {
svgCanvas.convertToPath();
var 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();
updateContextPanel();
}
}
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 = document.getElementById('tool_node_link').checked;
// 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.deleteSelectedElements();
svgCanvas.clear();
svgCanvas.setResolution(dims[0], dims[1]);
updateCanvas(true);
createBackground();
zoomImage();
updateContextPanel();
prepPaints();
svgCanvas.runExtensions('onNewDocument');
});
};
var clickBold = function(){
svgCanvas.setBold( !svgCanvas.getBold() );
updateContextPanel();
};
var clickItalic = function(){
svgCanvas.setItalic( !svgCanvas.getItalic() );
updateContextPanel();
};
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": "white",
"color": "black"
});
setTimeout(function(){menu_title.removeAttr("style")}, 200);
}
var clickUndo = function(){
if (undoMgr.getUndoStackSize() > 0) {
flash($('#edit_menu'));
undoMgr.undo();
}
};
var clickRedo = function(){
if (undoMgr.getRedoStackSize() > 0) {
flash($('#edit_menu'));
undoMgr.redo();
}
};
var clickGroup = function(){
// group
if (multiselected) {
flash($('#object_menu'));
svgCanvas.groupSelectedElements();
}
// ungroup
else if(selectedElement){
flash($('#object_menu'));
svgCanvas.ungroupSelectedElement();
}
};
var clickClone = function(){
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');
$("#tool_stroke").toggleClass('active')
$("#tool_fill").toggleClass('active')
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() {
flash($('#view_menu'));
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 = $('