SVG-Edit Markers Extension

The arrows extension on steroids.
This commit is contained in:
Jacques Distler 2010-06-03 07:13:37 -05:00
parent c25b608f3d
commit 05ffd215f1
4 changed files with 913 additions and 111 deletions

View file

@ -0,0 +1,561 @@
/*
* ext-markers.js
*
* Licensed under the Apache License, Version 2
*
* Copyright(c) 2010 Will Schleter
* based on ext-arrows.js by Copyright(c) 2010 Alexis Deveria
*
* This extension provides for the addition of markers to the either end
* or the middle of a line, polyline, path, polygon.
*
* Markers may be either a graphic or arbitary text
*
* to simplify the coding and make the implementation as robust as possible,
* markers are not shared - every object has its own set of markers.
* this relationship is maintained by a naming convention between the
* ids of the markers and the ids of the object
*
* The following restrictions exist for simplicty of use and programming
* objects and their markers to have the same color
* marker size is fixed
* text marker font, size, and attributes are fixed
* an application specific attribute - se_type - is added to each marker element
* to store the type of marker
*
* TODO:
* remove some of the restrictions above
* add option for keeping text aligned to horizontal
* add support for dimension extension lines
*
*/
svgEditor.addExtension("Markers", function(S) {
var svgcontent = S.svgcontent,
addElem = S.addSvgElementFromJson,
selElems;
var mtypes = ['start','mid','end'];
var marker_prefix = 'se_marker_';
var id_prefix = 'mkr_';
// note - to add additional marker types add them below with a unique id
// and add the associated icon(s) to marker-icons.svg
// the geometry is normallized to a 100x100 box with the origin at lower left
// Safari did not like negative values for low left of viewBox
// remember that the coordinate system has +y downward
var marker_types = {
nomarker: {},
leftarrow:
{element:'path', attr:{d:'M0,50 L100,90 L70,50 L100,10 Z'}},
rightarrow:
{element:'path', attr:{d:'M100,50 L0,90 L30,50 L0,10 Z'}},
textmarker:
{element:'text', attr: {x:0, y:0,'stroke-width':0,'stroke':'none','font-size':75,'font-family':'serif','text-anchor':'left',
'xml:space': 'preserve'}},
forwardslash:
{element:'path', attr:{d:'M30,100 L70,0'}},
reverseslash:
{element:'path', attr:{d:'M30,0 L70,100'}},
verticalslash:
{element:'path', attr:{d:'M50,0 L50,100'}},
box:
{element:'path', attr:{d:'M20,20 L20,80 L80,80 L80,20 Z'}},
star:
{element:'path', attr:{d:'M10,30 L90,30 L20,90 L50,10 L80,90 Z'}},
xmark:
{element:'path', attr:{d:'M20,80 L80,20 M80,80 L20,20'}},
triangle:
{element:'path', attr:{d:'M10,80 L50,20 L80,80 Z'}},
circle:
{element:'circle', attr:{r:30, cx:50, cy:50}},
}
var lang_list = {
"en":[
{id: "start_marker_list", title: "Select start marker type" },
{id: "mid_marker_list", title: "Select mid marker type" },
{id: "end_marker_list", title: "Select end marker type" },
{id: "nomarker", title: "No Marker" },
{id: "leftarrow", title: "Left Arrow" },
{id: "rightarrow", title: "Right Arrow" },
{id: "textmarker", title: "Text Marker" },
{id: "forwardslash", title: "Forward Slash" },
{id: "reverseslash", title: "Reverse Slash" },
{id: "verticalslash", title: "Vertical Slash" },
{id: "box", title: "Box" },
{id: "star", title: "Star" },
{id: "xmark", title: "X" },
{id: "triangle", title: "Triangle" },
{id: "circle", title: "Circle" },
{id: "leftarrow_o", title: "Open Left Arrow" },
{id: "rightarrow_o", title: "Open Right Arrow" },
{id: "box_o", title: "Open Box" },
{id: "star_o", title: "Open Star" },
{id: "triangle_o", title: "Open Triangle" },
{id: "circle_o", title: "Open Circle" },
]
};
// duplicate shapes to support unfilled (open) marker types with an _o suffix
$.each(['leftarrow','rightarrow','box','star','circle','triangle'],function(i,v) {
marker_types[v+'_o'] = marker_types[v];
});
// elem = a graphic element will have an attribute like marker-start
// attr - marker-start, marker-mid, or marker-end
// returns the marker element that is linked to the graphic element
function getLinked(elem, attr) {
var str = elem.getAttribute(attr);
if(!str) return null;
var m = str.match(/\(\#(.*)\)/);
if(!m || m.length !== 2) {
return null;
}
return S.getElem(m[1]);
}
//toggles context tool panel off/on
//sets the controls with the selected element's settings
function showPanel(on) {
$('#marker_panel').toggle(on);
if(on) {
var el = selElems[0];
var val;
var ci;
$.each(mtypes, function(i, pos) {
var m=getLinked(el,"marker-"+pos);
var txtbox = $('#'+pos+'_marker');
if (!m) {
val='\\nomarker';
ci=val;
txtbox.hide() // hide text box
} else {
if (!m.attributes.se_type) return; // not created by this extension
val='\\'+m.attributes.se_type.textContent;
ci=val;
if (val=='\\textmarker') {
val=m.lastChild.textContent;
//txtbox.show(); // show text box
} else {
txtbox.hide() // hide text box
}
}
txtbox.val(val);
setIcon(pos,ci);
})
}
}
function addMarker(id, val) {
var txt_box_bg = '#ffffff';
var txt_box_border = 'none';
var txt_box_stroke_width = 0;
var marker = S.getElem(id);
if (marker) return;
if (val=='' || val=='\\nomarker') return;
var el = selElems[0];
var color = el.getAttribute('stroke');
//NOTE: Safari didn't like a negative value in viewBox
//so we use a standardized 0 0 100 100
//with 50 50 being mapped to the marker position
var refX = 50;
var refY = 50;
var viewBox = "0 0 100 100";
var markerWidth = 5;
var markerHeight = 5;
var strokeWidth = 10;
if (val.substr(0,1)=='\\') se_type=val.substr(1);
else se_type='textmarker';
if (!marker_types[se_type]) return; // an unknown type!
// create a generic marker
marker = addElem({
"element": "marker",
"attr": {
"id": id,
"markerUnits": "strokeWidth",
"orient": "auto",
"style": "pointer-events:none",
"se_type": se_type
}
});
if (se_type!='textmarker') {
var mel = addElem(marker_types[se_type]);
var fillcolor = color;
if (se_type.substr(-2)=='_o') fillcolor='none';
mel.setAttribute('fill',fillcolor);
mel.setAttribute('stroke',color);
mel.setAttribute('stroke-width',strokeWidth);
marker.appendChild(mel);
} else {
var text = addElem(marker_types[se_type]);
// have to add text to get bounding box
text.textContent = val;
var tb=text.getBBox();
//alert( tb.x + " " + tb.y + " " + tb.width + " " + tb.height);
var pad=1;
var bb = tb;
bb.x = 0;
bb.y = 0;
bb.width += pad*2;
bb.height += pad*2;
// shift text according to its size
text.setAttribute('x', pad);
text.setAttribute('y', bb.height - pad - tb.height/4); // kludge?
text.setAttribute('fill',color);
refX = bb.width/2+pad;
refY = bb.height/2+pad;
viewBox = bb.x + " " + bb.y + " " + bb.width + " " + bb.height;
markerWidth =bb.width/10;
markerHeight = bb.height/10;
var box = addElem({
"element": "rect",
"attr": {
"x": bb.x,
"y": bb.y,
"width": bb.width,
"height": bb.height,
"fill": txt_box_bg,
"stroke": txt_box_border,
"stroke-width": txt_box_stroke_width
}
});
marker.setAttribute("orient",0);
marker.appendChild(box);
marker.appendChild(text);
}
marker.setAttribute("viewBox",viewBox);
marker.setAttribute("markerWidth", markerWidth);
marker.setAttribute("markerHeight", markerHeight);
marker.setAttribute("refX", refX);
marker.setAttribute("refY", refY);
S.findDefs().appendChild(marker);
return marker;
}
function setMarker() {
var poslist={'start_marker':'start','mid_marker':'mid','end_marker':'end'};
var pos = poslist[this.id];
var marker_name = 'marker-'+pos;
var val = this.value;
var el = selElems[0];
var marker = getLinked(el, marker_name);
if (marker) $(marker).remove();
el.removeAttribute(marker_name);
if (val=='') val='\\nomarker';
if (val=='\\nomarker') {
setIcon(pos,val);
return;
}
// Set marker on element
var id = marker_prefix + pos + '_' + el.id;
addMarker(id, val);
svgCanvas.changeSelectedAttribute(marker_name, "url(#" + id + ")");
if (el.tagName == "line" && pos=='mid') el=convertline(el);
S.call("changed", selElems);
setIcon(pos,val);
}
function convertline(elem) {
// this routine came from the connectors extension
// it is needed because midpoint markers don't work with line elements
if (!(elem.tagName == "line")) return elem;
// Convert to polyline to accept mid-arrow
var x1 = elem.getAttribute('x1')-0;
var x2 = elem.getAttribute('x2')-0;
var y1 = elem.getAttribute('y1')-0;
var y2 = elem.getAttribute('y2')-0;
var id = elem.id;
var mid_pt = (' '+((x1+x2)/2)+','+((y1+y2)/2) + ' ');
var pline = addElem({
"element": "polyline",
"attr": {
"points": (x1+','+y1+ mid_pt +x2+','+y2),
"stroke": elem.getAttribute('stroke'),
"stroke-width": elem.getAttribute('stroke-width'),
"fill": "none",
"opacity": elem.getAttribute('opacity') || 1
}
});
$.each(mtypes, function(i, pos) { // get any existing marker definitions
var nam = 'marker-'+pos;
var m = elem.getAttribute(nam);
if (m) pline.setAttribute(nam,elem.getAttribute(nam));
});
$(elem).after(pline).remove();
svgCanvas.clearSelection();
pline.id = id;
svgCanvas.addToSelection([pline]);
return pline;
}
// called when the main system modifies an object
// this routine changes the associated markers to be the same color
function colorChanged(elem) {
var color = elem.getAttribute('stroke');
$.each(mtypes, function(i, pos) {
var marker = getLinked(elem, 'marker-'+pos);
if (!marker) return;
if (!marker.attributes.se_type) return; //not created by this extension
var ch = marker.lastElementChild;
if (!ch) return;
var curfill = ch.getAttribute("fill");
var curstroke = ch.getAttribute("stroke")
if (curfill && curfill!='none') ch.setAttribute("fill",color);
if (curstroke && curstroke!='none') ch.setAttribute("stroke",color);
});
}
// called when the main system creates or modifies an object
// primary purpose is create new markers for cloned objects
function updateReferences(el) {
$.each(mtypes, function (i,pos) {
var id = marker_prefix + pos + '_' + el.id;
var marker_name = 'marker-'+pos;
var marker = getLinked(el, marker_name);
if (!marker || !marker.attributes.se_type) return; //not created by this extension
var url = el.getAttribute(marker_name);
if (url) {
var len = el.id.length;
var linkid = url.substr(-len-1,len);
if (el.id != linkid) {
var val = $('#'+pos+'_marker').attr('value');
addMarker(id, val);
svgCanvas.changeSelectedAttribute(marker_name, "url(#" + id + ")");
if (el.tagName == "line" && pos=='mid') el=convertline(el);
S.call("changed", selElems);
}
}
});
}
// simulate a change event a text box that stores the current element's marker type
function triggerTextEntry(pos,val) {
$('#'+pos+'_marker').val(val);
$('#'+pos+'_marker').change();
var txtbox = $('#'+pos+'_marker');
//if (val.substr(0,1)=='\\') txtbox.hide();
//else txtbox.show();
}
function setIcon(pos,id) {
if (id.substr(0,1)!='\\') id='\\textmarker'
var ci = '#'+id_prefix+pos+'_'+id.substr(1);
svgEditor.setIcon('#cur_' + pos +'_marker_list', $(ci).children());
$(ci).addClass('current').siblings().removeClass('current');
}
function setMarkerSet(obj) {
var parts = this.id.split('_');
var set = parts[2];
switch (set) {
case 'off':
triggerTextEntry('start','\\nomarker');
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\nomarker');
break;
case 'dimension':
triggerTextEntry('start','\\leftarrow');
triggerTextEntry('end','\\rightarrow');
showTextPrompt('mid');
break;
case 'label':
triggerTextEntry('mid','\\nomarker');
triggerTextEntry('end','\\rightarrow');
showTextPrompt('start');
break;
}
}
function showTextPrompt(pos) {
var def = $('#'+pos+'_marker').val();
if (def.substr(0,1)=='\\') def='';
$.prompt('Enter text for ' + pos + ' marker', def , function(txt) { if (txt) triggerTextEntry(pos,txt); });
}
// callback function for a toolbar button click
function setArrowFromButton(obj) {
var parts = this.id.split('_');
var pos = parts[1];
var val = parts[2];
if (parts[3]) val+='_'+parts[3];
if (val!='textmarker') {
triggerTextEntry(pos,'\\'+val);
} else {
showTextPrompt(pos);
}
}
function getTitle(lang,id) {
var list = lang_list[lang];
for (var i in list) {
if (list[i].id==id) return list[i].title;
}
return id;
}
// build the toolbar button array from the marker definitions
// TODO: need to incorporate language specific titles
function buildButtonList() {
var buttons=[];
var i=0;
/*
buttons.push({
id:id_prefix + 'markers_off',
title:'Turn off all markers',
type:'context',
events: { 'click': setMarkerSet },
panel: 'marker_panel'
});
buttons.push({
id:id_prefix + 'markers_dimension',
title:'Dimension',
type:'context',
events: { 'click': setMarkerSet },
panel: 'marker_panel'
});
buttons.push({
id:id_prefix + 'markers_label',
title:'Label',
type:'context',
events: { 'click': setMarkerSet },
panel: 'marker_panel'
});
*/
$.each(mtypes,function(k,pos) {
var listname = pos + "_marker_list";
var def = true;
$.each(marker_types,function(id,v) {
var title = getTitle('en',id);
buttons.push({
id:id_prefix + pos + "_" + id,
svgicon:id,
title:title,
type:'context',
events: { 'click': setArrowFromButton },
panel:'marker_panel',
list: listname,
isDefault: def
});
def = false;
});
});
return buttons;
}
return {
name: "Markers",
svgicons: "extensions/markers-icons.xml",
buttons: buildButtonList(),
context_tools: [
{
type: "input",
panel: "marker_panel",
title: "Start marker",
id: "start_marker",
label: "s",
size: 3,
events: { change: setMarker }
},{
type: "button-select",
panel: "marker_panel",
title: getTitle('en','start_marker_list'),
id: "start_marker_list",
events: { change: setArrowFromButton }
},{
type: "input",
panel: "marker_panel",
title: "Middle marker",
id: "mid_marker",
label: "m",
defval: "",
size: 3,
events: { change: setMarker }
},{
type: "button-select",
panel: "marker_panel",
title: getTitle('en','mid_marker_list'),
id: "mid_marker_list",
events: { change: setArrowFromButton }
},{
type: "input",
panel: "marker_panel",
title: "End marker",
id: "end_marker",
label: "e",
size: 3,
events: { change: setMarker }
},{
type: "button-select",
panel: "marker_panel",
title: getTitle('en','end_marker_list'),
id: "end_marker_list",
events: { change: setArrowFromButton }
} ],
callback: function() {
$('#marker_panel').hide();
},
addLangData: function(lang) {
return { data: lang_list[lang] };
},
selectedChanged: function(opts) {
// Use this to update the current selected elements
//console.log('selectChanged',opts);
selElems = opts.elems;
var i = selElems.length;
var marker_elems = ['line','path','polyline','polygon'];
while(i--) {
var elem = selElems[i];
if(elem && $.inArray(elem.tagName, marker_elems) != -1) {
if(opts.selectedElement && !opts.multiselected) {
showPanel(true);
} else {
showPanel(false);
}
} else {
showPanel(false);
}
}
},
elementChanged: function(opts) {
//console.log('elementChanged',opts);
var elem = opts.elems[0];
if(elem && (
elem.getAttribute("marker-start") ||
elem.getAttribute("marker-mid") ||
elem.getAttribute("marker-end")
)) {
colorChanged(elem);
updateReferences(elem);
}
changing_flag = false;
}
};
});

View file

@ -0,0 +1,120 @@
<svg xmlns="http://www.w3.org/2000/svg">
<!-- Created with SVG-edit - http://svg-edit.googlecode.com/ -->
<g id="nomarker">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="#ff7f00" d="m-50,0l100,0"/>
</svg>
</g>
<g id="leftarrow">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="#ff7f00" d="m-50,0l100,40l-30,-40l30,-40z"/>
</svg>
</g>
<g id="rightarrow">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="#ff7f00" d="m50,0l-100,40l30,-40l-30,-40z"/>
</svg>
</g>
<g id="leftarrow_o">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="m-50,0l100,40l-30,-40l30,-40z"/>
</svg>
</g>
<g id="rightarrow_o">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="m50,0l-100,40l30,-40l-30,-40z"/>
</svg>
</g>
<g id="forwardslash">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="m-20,50l40,-100"/>
</svg>
</g>
<g id="reverseslash">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="m-20,-50l40,100"/>
</svg>
</g>
<g id="verticalslash">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="m0,-50l0,100"/>
</svg>
</g>
<g id="circle">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<circle stroke-width="10" stroke="#ff7f00" fill="#ff7f00" cy="0" cx="0" r="30"/>
</svg>
</g>
<g id="circle_o">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<circle stroke-width="10" stroke="#ff7f00" fill="none" cy="0" cx="0" r="30"/>
</svg>
</g>
<g id="xmark">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="#ff7f00" d="m-30,30l60,-60m0,60l-60,-60"/>
</svg>
</g>
<g id="box">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="#ff7f00" d="m-30,-30l0,60l60,0l0,-60z"/>
</svg>
</g>
<g id="star">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="#ff7f00" d="m-40,-20l80,0l-70,60l30,-80l30,80z"/>
</svg>
</g>
<g id="box_o">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="m-30,-30l0,60l60,0l0,-60z"/>
</svg>
</g>
<g id="star_o">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="m-40,-20l80,0l-70,60l30,-80l30,80z"/>
</svg>
</g>
<g id="triangle_o">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="none" d="M-30,30 L0,-30 L30,30 Z"/>
</svg>
</g>
<g id="triangle">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<path stroke-width="10" stroke="#ff7f00" fill="#ff7f00" d="M-30,30 L0,-30 L30,30 Z"/>
</svg>
</g>
<g id="textmarker">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<text xml:space="preserve" text-anchor="middle" font-family="serif" font-size="120" y="40" x="0" stroke-width="0" stroke="#ff7f00" fill="#ff7f00">T</text>
</svg>
</g>
<g id="textmarker">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<text xml:space="preserve" text-anchor="middle" font-family="serif" font-size="120" y="40" x="0" stroke-width="0" stroke="#ff7f00" fill="#ff7f00">T</text>
</svg>
</g>
<g id="mkr_markers_off">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<line y2="0" x2="50" y1="0" x1="-50" stroke-width="5" stroke="#ff7f00" fill="none"/>
</svg>
</g>
<g id="mkr_markers_dimension">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<line y2="0" x2="40" y1="0" x1="20" stroke-width="5" stroke="#ff7f00" fill="none"/>
<line y2="0" x2="-40" y1="0" x1="-20" stroke-width="5" stroke="#ff7f00" fill="none"/>
<text text-anchor="middle" font-family="serif" font-size="80" y="20" x="0" stroke-width="0" stroke="#ff7f00" fill="#ff7f00">T</text>
<path stroke-width="5" stroke="#ff7f00" fill="#ff7f00" d="M-50,0 L-30,-15 L-30,15 Z"/>
<path stroke-width="5" stroke="#ff7f00" fill="#ff7f00" d="M50,0 L30,-15 L30,15 Z"/>
</svg>
</g>
<g id="mkr_markers_label">
<svg viewBox="-60 -60 120 120" xmlns="http://www.w3.org/2000/svg">
<line y2="0" x2="40" y1="0" x1="-20" stroke-width="5" stroke="#ff7f00" fill="none"/>
<text text-anchor="middle" font-family="serif" font-size="80" y="20" x="-40" stroke-width="0" stroke="#ff7f00" fill="#ff7f00">T</text>
<path stroke-width="5" stroke="#ff7f00" fill="#ff7f00" d="M50,0 L30,-15 L30,15 Z"/>
</svg>
</g>
<g id="svg_eof"/>
</svg>

After

Width:  |  Height:  |  Size: 5.6 KiB

View file

@ -45,7 +45,7 @@
imgPath: 'images/',
langPath: 'locale/',
extPath: 'extensions/',
extensions: ['ext-arrows.js', 'ext-connector.js', 'ext-eyedropper.js', 'ext-itex.js'],
extensions: ['ext-markers.js','ext-connector.js', 'ext-eyedropper.js', 'ext-itex.js'],
initTool: 'select',
wireframe: false
},
@ -776,6 +776,8 @@
}
}
var btn_selects = [];
if(ext.context_tools) {
$.each(ext.context_tools, function(i, tool) {
// Add select tool
@ -813,7 +815,24 @@
$(sel).bind(evt, func);
});
break;
case 'button-select':
var html = '<div id="' + tool.id + '" class="dropdown toolset" title="' + tool.title + '">'
+ '<div id="cur_' + tool.id + '" class="icon_label"></div><button></button></div>';
var list = $('<ul id="' + tool.id + '_opts"></ul>').appendTo('#option_lists');
// 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 = '<label' + cont_id + '>'
+ '<span id="' + tool.id + '_label">'
@ -865,7 +884,8 @@
icon = $('<img src="' + btn.icon + '">');
} else {
fallback_obj[id] = btn.icon;
placement_obj['#' + id] = btn.id;
var svgicon = btn.svgicon?btn.svgicon:btn.id;
placement_obj['#' + id] = svgicon;
}
var cls, parent;
@ -885,13 +905,22 @@
break;
}
var button = $('<div/>')
var button = $(btn.list?'<li/>':'<div/>')
.attr("id", id)
.attr("title", btn.title)
.addClass(cls);
if(!btn.includeWith) {
if(!btn.includeWith && !btn.list) {
button.appendTo(parent);
} else {
} 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
@ -947,35 +976,42 @@
if(!svgicons) {
button.append(icon);
}
// 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);
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, function() {
if(toolButtonClick(button)) {
func();
}
});
}
if(btn.key) {
$(document).bind('keydown', btn.key, func);
if(btn.title) button.attr("title", btn.title + ' ['+btn.key+']');
button.bind(name, func);
}
} 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});
});
$.svgIcons(svgicons, {
w:24, h:24,
id_match: false,
@ -1700,7 +1736,14 @@
if(dropUp) {
$(elem).addClass('dropup');
}
list.find('li').bind('mouseup', callback);
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) {
@ -1712,7 +1755,6 @@
});
var height = list.height();
$(elem).bind('mousedown',function() {
var off = $(elem).offset();
if(dropUp) {
@ -2294,8 +2336,8 @@
svgCanvas.setBackground(color, url);
}
var setIcon = function(elem, icon_id, forcedSize) {
var icon = $.getSvgIcon(icon_id).clone();
var setIcon = Editor.setIcon = function(elem, icon_id, forcedSize) {
var icon = (typeof icon_id == 'string') ? $.getSvgIcon(icon_id).clone() : icon_id.clone();
$(elem).empty().append(icon);
if(forcedSize) {
var obj = {};
@ -3471,7 +3513,7 @@
updateCanvas(true);
// });
// var revnums = "svg-editor.js ($Rev: 1577 $) ";
// var revnums = "svg-editor.js ($Rev: 1586 $) ";
// revnums += svgCanvas.getVersion();
// $('#copyright')[0].setAttribute("title", revnums);

View file

@ -221,7 +221,10 @@ function ChangeElementCommand(elem, attrs, text) {
this.elem.removeAttribute(attr);
}
}
if (attr == "transform") { bChangedTransform = true; }
else if (attr == "stdDeviation") { canvas.setBlurOffsets(this.elem.parentNode, this.newValues[attr]); }
}
// relocate rotational transform, if necessary
if(!bChangedTransform) {
@ -250,6 +253,8 @@ function ChangeElementCommand(elem, attrs, text) {
if (attr == "#text") this.elem.textContent = this.oldValues[attr];
else if (attr == "#href") this.elem.setAttributeNS(xlinkns, "xlink:href", this.oldValues[attr]);
else this.elem.setAttribute(attr, this.oldValues[attr]);
if (attr == "stdDeviation") canvas.setBlurOffsets(this.elem.parentNode, this.oldValues[attr]);
}
else {
if (attr == "#text") this.elem.textContent = "";
@ -1439,6 +1444,7 @@ function BatchCommand(text) {
node.setAttribute(nv[0],nv[1]);
}
}
node.removeAttribute('style');
}
}
@ -2421,8 +2427,10 @@ function BatchCommand(text) {
// else, it's a non-group
else {
// FIXME: box might be null for some elements (<metadata> etc), need to handle this
var box = canvas.getBBox(selected),
oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
var box = canvas.getBBox(selected);
if(!box) return null;
var oldcenter = {x: box.x+box.width/2, y: box.y+box.height/2},
newcenter = transformPoint(box.x+box.width/2, box.y+box.height/2,
transformListToTransform(tlist).matrix),
m = svgroot.createSVGMatrix(),
@ -2647,8 +2655,7 @@ function BatchCommand(text) {
var i = elemsToAdd.length;
while (i--) {
var elem = elemsToAdd[i];
// we ignore any selectors
if (!elem || elem.id.substr(0,13) == "selectorGrip_" || !this.getBBox(elem)) continue;
if (!elem || !this.getBBox(elem)) continue;
// if it's not already there, add it
if (selectedElements.indexOf(elem) == -1) {
selectedElements[j] = elem;
@ -2921,6 +2928,39 @@ function BatchCommand(text) {
return {tl:topleft, tr:topright, bl:botleft, br:botright,
aabox: {x:minx, y:miny, width:(maxx-minx), height:(maxy-miny)} };
};
var getMouseTarget = function(evt) {
if (evt == null) {
return null;
}
var mouse_target = evt.target;
// if it was a <use>, Opera and WebKit return the SVGElementInstance
if (mouse_target.correspondingUseElement)
mouse_target = mouse_target.correspondingUseElement;
// for foreign content, go up until we find the foreignObject
// WebKit browsers set the mouse target to the svgcanvas div
if ($.inArray(mouse_target.namespaceURI, [mathns, htmlns]) != -1 &&
mouse_target.id != "svgcanvas")
{
while (mouse_target.nodeName != "foreignObject") {
mouse_target = mouse_target.parentNode;
}
}
// go up until we hit a child of a layer
while (mouse_target.parentNode.parentNode.tagName == "g") {
mouse_target = mouse_target.parentNode;
}
// Webkit bubbles the mouse event all the way up to the div, so we
// set the mouse_target to the svgroot like the other browsers
if (mouse_target.nodeName.toLowerCase() == "div") {
mouse_target = svgroot;
}
return mouse_target;
};
// Mouse events
(function() {
@ -2955,34 +2995,11 @@ function BatchCommand(text) {
var x = mouse_x / current_zoom,
y = mouse_y / current_zoom,
mouse_target = evt.target;
mouse_target = getMouseTarget(evt);
start_x = x;
start_y = y;
// if it was a <use>, Opera and WebKit return the SVGElementInstance
if (mouse_target.correspondingUseElement)
mouse_target = mouse_target.correspondingUseElement;
// for foreign content, go up until we find the foreignObject
// WebKit browsers set the mouse target to the svgcanvas div
if ($.inArray(mouse_target.namespaceURI, [mathns, htmlns]) != -1 &&
mouse_target.id != "svgcanvas")
{
while (mouse_target.nodeName != "foreignObject") {
mouse_target = mouse_target.parentNode;
}
}
// go up until we hit a child of a layer
while (mouse_target.parentNode.parentNode.tagName == "g") {
mouse_target = mouse_target.parentNode;
}
// Webkit bubbles the mouse event all the way up to the div, so we
// set the mouse_target to the svgroot like the other browsers
if (mouse_target.nodeName.toLowerCase() == "div") {
mouse_target = svgroot;
}
// if it is a selector grip, then it must be a single element selected,
// set the mouse_target to that and update the mode to rotate/resize
if (mouse_target.parentNode == selectorManager.selectorParentGroup && selectedElements[0] != null) {
@ -3261,7 +3278,8 @@ function BatchCommand(text) {
}
});
};
// in this function we do not record any state changes yet (but we do update
// any elements that are still being created, moved or resized on the canvas)
// TODO: svgcanvas should just retain a reference to the image being dragged instead
@ -3292,10 +3310,7 @@ function BatchCommand(text) {
var dx = x - start_x;
var dy = y - start_y;
if(evt.shiftKey) { // restrict to movement up/down/left/right (WRS)
if (Math.abs(dx)>Math.abs(dy)) dy=0;
else dx=0;
}
if(evt.shiftKey) { var xya = snapToAngle(start_x,start_y,x,y); x=xya.x; y=xya.y; }
if (dx != 0 || dy != 0) {
var len = selectedElements.length;
@ -3471,16 +3486,7 @@ function BatchCommand(text) {
var x2 = x;
var y2 = y;
if(evt.shiftKey) {
var snap = Math.PI/4; // 45 degrees
var diff_x = x - start_x;
var diff_y = y - start_y;
var angle = Math.atan2(diff_y,diff_x);
var dist = Math.sqrt(diff_x * diff_x + diff_y * diff_y);
var snapangle= Math.round(angle/snap)*snap;
x2 = start_x + dist*Math.cos(snapangle);
y2 = start_y + dist*Math.sin(snapangle);
}
if(evt.shiftKey) { var xya=Utils.snapToAngle(start_x,start_y,x2,y2); x2=xya.x; y2=xya.y; }
shape.setAttributeNS(null, "x2", x2);
shape.setAttributeNS(null, "y2", y2);
@ -3551,9 +3557,11 @@ function BatchCommand(text) {
x *= current_zoom;
y *= current_zoom;
if(evt.shiftKey) { // restrict path segments to horizontal/vertical (WRS)
if (Math.abs(start_x-x)>Math.abs(start_y-y)) {y=start_y; mouse_y=y;}
else {x=start_x; mouse_x=x;}
if(evt.shiftKey) {
var x1 = path.dragging?path.dragging[0]:start_x;
var y1 = path.dragging?path.dragging[1]:start_y;
var xya=Utils.snapToAngle(x1,y1,x,y);
x=xya.x; y=xya.y;
}
if(rubberBox && rubberBox.getAttribute('display') != 'none') {
@ -3565,7 +3573,7 @@ function BatchCommand(text) {
},100);
}
pathActions.mouseMove(mouse_x, mouse_y);
pathActions.mouseMove(x, y);
break;
case "textedit":
@ -3594,9 +3602,9 @@ function BatchCommand(text) {
var angle = ((Math.atan2(cy-y,cx-x) * (180/Math.PI))-90) % 360;
if(evt.shiftKey) { // restrict rotations to nice angles (WRS)
var snap = 45;
angle= Math.round(angle/snap)*snap;
}
var snap = 45;
angle= Math.round(angle/snap)*snap;
}
canvas.setRotationAngle(angle<-180?(360+angle):angle, true);
call("changed", selectedElements);
@ -3941,7 +3949,7 @@ function BatchCommand(text) {
}());
var textActions = canvas.textActions = function() {
var curtext;
var curtext, current_text;
var textinput;
var cursor;
var selblock;
@ -4164,11 +4172,12 @@ function BatchCommand(text) {
return {
select: function(target, x, y) {
if (curtext == target) {
if (current_text == target) {
curtext = target;
textActions.toEditMode(x, y);
} // going into pathedit mode
else {
curtext = target;
current_text = target;
}
},
start: function(elem) {
@ -4262,6 +4271,7 @@ function BatchCommand(text) {
$(textinput).blur(hideCursor);
},
clear: function() {
current_text = null;
if(current_mode == "textedit") {
textActions.toSelectMode();
}
@ -5516,17 +5526,15 @@ function BatchCommand(text) {
// else, create a new point, append to pts array, update path element
else {
// Checks if current target or parents are #svgcontent
if(!$.contains(container, evt.target)) {
if(!$.contains(container, getMouseTarget(evt))) {
// Clicked outside canvas, so don't make point
console.log("Clicked outside canvas");
return false;
}
var lastx = current_path_pts[len-2], lasty = current_path_pts[len-1];
if (evt.shiftKey) { // restrict to horizonontal/vertical (WRS)
if (Math.abs(x-lastx)>Math.abs(y-lasty)) y=lasty;
else x=lastx;
}
if(evt.shiftKey) { var xya=Utils.snapToAngle(lastx,lasty,x,y); x=xya.x; y=xya.y; }
// we store absolute values in our path points array for easy checking above
current_path_pts.push(x);
@ -5660,6 +5668,7 @@ function BatchCommand(text) {
},
clear: function(remove) {
current_path = null;
if (current_mode == "path" && current_path_pts.length > 0) {
var elem = getElem(getId());
$(getElem("path_stretch_line")).remove();
@ -6660,8 +6669,13 @@ function BatchCommand(text) {
else {
var ts = "scale(" + (canvash/3)/vb[2] + ")";
}
if (vb[0] != 0 || vb[1] != 0)
ts = "translate(" + (-vb[0]) + "," + (-vb[1]) + ") " + ts;
// Hack to make recalculateDimensions understand how to scale
ts = "translate(0) " + ts + " translate(0)";
// TODO: Find way to add this in a recalculateDimensions-parsable way
// if (vb[0] != 0 || vb[1] != 0)
// ts = "translate(" + (-vb[0]) + "," + (-vb[1]) + ") " + ts;
// add all children of the imported <svg> to the <g> we create
var g = svgdoc.createElementNS(svgns, "g");
@ -6750,6 +6764,7 @@ function BatchCommand(text) {
}
// now give the g itself a new id
g.id = getNextId();
// manually increment obj_num because our cloned elements are not in the DOM yet
obj_num++;
@ -6783,7 +6798,7 @@ function BatchCommand(text) {
// recalculate dimensions on the top-level children so that unnecessary transforms
// are removed
walkTreePost(importedNode, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}});
walkTreePost(svgcontent, function(n){try{recalculateDimensions(n)}catch(e){console.log(e)}});
batchCmd.addSubCommand(new InsertElementCommand(svgcontent));
@ -7723,6 +7738,7 @@ function BatchCommand(text) {
canvas.changeSelectedAttributeNoUndo("filter", 'url(#' + selectedElements[0].id + '_blur)');
}
canvas.changeSelectedAttributeNoUndo("stdDeviation", val, [filter.firstChild]);
canvas.setBlurOffsets(filter, val);
}
}
@ -7734,6 +7750,23 @@ function BatchCommand(text) {
filter = null;
}
canvas.setBlurOffsets = function(filter, stdDev) {
if(stdDev > 3) {
// TODO: Create algorithm here where size is based on expected blur
assignAttributes(filter, {
x: '-50%',
y: '-50%',
width: '200%',
height: '200%',
}, 100);
} else {
filter.removeAttribute('x');
filter.removeAttribute('y');
filter.removeAttribute('width');
filter.removeAttribute('height');
}
}
canvas.setBlur = function(val, complete) {
if(cur_command) {
finishChange();
@ -7786,20 +7819,7 @@ function BatchCommand(text) {
batchCmd.addSubCommand(new ChangeElementCommand(elem, changes));
if(val > 3) {
// TODO: Create algorithm here where size is based on expected blur
assignAttributes(filter, {
x: '-50%',
y: '-50%',
width: '200%',
height: '200%',
}, 100);
} else {
filter.removeAttribute('x');
filter.removeAttribute('y');
filter.removeAttribute('width');
filter.removeAttribute('height');
}
canvas.setBlurOffsets(filter, val);
}
cur_command = batchCmd;
@ -8188,7 +8208,7 @@ function BatchCommand(text) {
}
// only allow the transform/opacity attribute to change on <g> elements, slightly hacky
if (elem.tagName == "g" && (attr != "transform" && attr != "opacity")) continue;
if (elem.tagName == "g" && $.inArray(attr, ['transform', 'opacity', 'filter']) !== -1);
var oldval = attr == "#text" ? elem.textContent : elem.getAttribute(attr);
if (oldval == null) oldval = "";
if (oldval != String(newValue)) {
@ -8373,19 +8393,63 @@ function BatchCommand(text) {
// "stroke-width"
// and then for each child, if they do not have the attribute (or the value is 'inherit')
// then set the child's attribute
// TODO: get the group's opacity and propagate it down to the children (multiply it
// by the child's opacity (or 1.0)
var i = 0;
var gangle = canvas.getRotationAngle(g);
var gattrs = $(g).attr(['filter', 'opacity']);
var gfilter, gblur;
while (g.firstChild) {
var elem = g.firstChild;
var oldNextSibling = elem.nextSibling;
var oldParent = elem.parentNode;
children[i++] = elem = parent.insertBefore(elem, anchor);
batchCmd.addSubCommand(new MoveElementCommand(elem, oldNextSibling, oldParent));
if(gattrs.opacity !== null && gattrs.opacity !== 1) {
var c_opac = elem.getAttribute('opacity') || 1;
var new_opac = Math.round((elem.getAttribute('opacity') || 1) * gattrs.opacity * 100)/100;
this.changeSelectedAttribute('opacity', new_opac, [elem]);
}
if(gattrs.filter) {
var cblur = this.getBlur(elem);
var orig_cblur = cblur;
if(!gblur) gblur = this.getBlur(g);
if(cblur) {
// Is this formula correct?
cblur = (gblur-0) + (cblur-0);
} else if(cblur === 0) {
cblur = gblur;
}
// If child has no current filter, get group's filter or clone it.
if(!orig_cblur) {
// Set group's filter to use first child's ID
if(!gfilter) {
gfilter = getElem(getUrlFromAttr(gattrs.filter).substr(1));
} else {
// Clone the group's filter
gfilter = copyElem(gfilter);
findDefs().appendChild(gfilter);
}
} else {
gfilter = getElem(getUrlFromAttr(elem.getAttribute('filter')).substr(1));
}
// Change this in future for different filters
var suffix = (gfilter.firstChild.tagName === 'feGaussianBlur')?'blur':'filter';
gfilter.id = elem.id + '_' + suffix;
this.changeSelectedAttribute('filter', 'url(#' + gfilter.id + ')', [elem]);
// Update blur value
if(cblur) {
this.changeSelectedAttribute('stdDeviation', cblur, [gfilter.firstChild]);
canvas.setBlurOffsets(gfilter, cblur);
}
}
var chtlist = canvas.getTransformList(elem);
if (glist.numberOfItems) {
@ -8462,6 +8526,7 @@ function BatchCommand(text) {
batchCmd.addSubCommand(recalculateDimensions(elem));
}
}
// remove transform and make it undo-able
if (xform) {
@ -9089,7 +9154,7 @@ function BatchCommand(text) {
// Function: getVersion
// Returns a string which describes the revision number of SvgCanvas.
this.getVersion = function() {
return "svgcanvas.js ($Rev: 1576 $)";
return "svgcanvas.js ($Rev: 1586 $)";
};
this.setUiStrings = function(strs) {
@ -9139,6 +9204,7 @@ function BatchCommand(text) {
getElem: getElem,
getId: getId,
getIntersectionList: getIntersectionList,
getMouseTarget: getMouseTarget,
getNextId: getNextId,
getPathBBox: getPathBBox,
getUrlFromAttr: getUrlFromAttr,
@ -9360,6 +9426,19 @@ var Utils = {
(r2.y+r2.height) > r1.y;
},
"snapToAngle": function(x1,y1,x2,y2) {
var snap = Math.PI/4; // 45 degrees
var dx = x2 - x1;
var dy = y2 - y1;
var angle = Math.atan2(dy,dx);
var dist = Math.sqrt(dx * dx + dy * dy);
var snapangle= Math.round(angle/snap)*snap;
var x = x1 + dist*Math.cos(snapangle);
var y = y1 + dist*Math.sin(snapangle);
//console.log(x1,y1,x2,y2,x,y,angle)
return {x:x, y:y, a:snapangle};
},
// found this function http://groups.google.com/group/jquery-dev/browse_thread/thread/c6d11387c580a77f
"text2xml": function(sXML) {
// NOTE: I'd like to use jQuery for this, but jQuery makes all tags uppercase