Debian Codegraph @

dojox/gfx/svg.js

raw symbols SCIP
1 define(["dojo/_base/lang", "dojo/_base/sniff", "dojo/_base/window", "dojo/dom", "dojo/_base/declare", "dojo/_base/array",
2 "dojo/dom-geometry", "dojo/dom-attr", "dojo/_base/Color", "./_base", "./shape", "./path"],
3 function(lang, has, win, dom, declare, arr, domGeom, domAttr, Color, g, gs, pathLib){
4
5 var svg = g.svg = {
6 // summary:
7 // This the graphics rendering bridge for browsers compliant with W3C SVG1.0.
8 // This is the preferred renderer to use for interactive and accessible graphics.
9 };
10 svg.useSvgWeb = (typeof window.svgweb != "undefined");
11
12 // Need to detect iOS in order to workaround bug when
13 // touching nodes with text
14 var uagent = navigator.userAgent,
15 safMobile = has("ios"),
16 android = has("android"),
17 textRenderingFix = has("chrome") || (android && android>=4) ? "auto" : "optimizeLegibility";// #16099, #16461
18
19 function _createElementNS(ns, nodeType){
20 // summary:
21 // Internal helper to deal with creating elements that
22 // are namespaced. Mainly to get SVG markup output
23 // working on IE.
24 if(win.doc.createElementNS){
25 return win.doc.createElementNS(ns,nodeType);
26 }else{
27 return win.doc.createElement(nodeType);
28 }
29 }
30
31 function _setAttributeNS(node, ns, attr, value){
32 if(node.setAttributeNS){
33 return node.setAttributeNS(ns, attr, value);
34 }else{
35 return node.setAttribute(attr, value);
36 }
37 }
38
39 function _createTextNode(text){
40 if(svg.useSvgWeb){
41 return win.doc.createTextNode(text, true);
42 }else{
43 return win.doc.createTextNode(text);
44 }
45 }
46
47 function _createFragment(){
48 if(svg.useSvgWeb){
49 return win.doc.createDocumentFragment(true);
50 }else{
51 return win.doc.createDocumentFragment();
52 }
53 }
54
55 svg.xmlns = {
56 xlink: "http://www.w3.org/1999/xlink",
57 svg: "http://www.w3.org/2000/svg"
58 };
59
60 svg.getRef = function(name){
61 // summary:
62 // looks up a node by its external name
63 // name: String
64 // an SVG external reference
65 // returns:
66 // returns a DOM Node specified by the name argument or null
67 if(!name || name == "none") return null;
68 if(name.match(/^url\(#.+\)$/)){
69 return dom.byId(name.slice(5, -1)); // Node
70 }
71 // alternative representation of a reference
72 if(name.match(/^#dojoUnique\d+$/)){
73 // we assume here that a reference was generated by dojox/gfx
74 return dom.byId(name.slice(1)); // Node
75 }
76 return null; // Node
77 };
78
79 svg.dasharray = {
80 solid: "none",
81 shortdash: [4, 1],
82 shortdot: [1, 1],
83 shortdashdot: [4, 1, 1, 1],
84 shortdashdotdot: [4, 1, 1, 1, 1, 1],
85 dot: [1, 3],
86 dash: [4, 3],
87 longdash: [8, 3],
88 dashdot: [4, 3, 1, 3],
89 longdashdot: [8, 3, 1, 3],
90 longdashdotdot: [8, 3, 1, 3, 1, 3]
91 };
92
93 var clipCount = 0;
94
95 svg.Shape = declare("dojox.gfx.svg.Shape", gs.Shape, {
96 // summary:
97 // SVG-specific implementation of dojox/gfx/shape.Shape methods
98
99 destroy: function(){
100 if(this.fillStyle && "type" in this.fillStyle){
101 var fill = this.rawNode.getAttribute("fill"),
102 ref = svg.getRef(fill);
103 if(ref){
104 ref.parentNode.removeChild(ref);
105 }
106 }
107 if(this.clip){
108 var clipPathProp = this.rawNode.getAttribute("clip-path");
109 if(clipPathProp){
110 var clipNode = dom.byId(clipPathProp.match(/gfx_clip[\d]+/)[0]);
111 if(clipNode){ clipNode.parentNode.removeChild(clipNode); }
112 }
113 }
114 gs.Shape.prototype.destroy.apply(this, arguments);
115 },
116
117 setFill: function(fill){
118 // summary:
119 // sets a fill object (SVG)
120 // fill: Object
121 // a fill object
122 // (see dojox/gfx.defaultLinearGradient,
123 // dojox/gfx.defaultRadialGradient,
124 // dojox/gfx.defaultPattern,
125 // or dojo/_base/Color)
126
127 if(!fill){
128 // don't fill
129 this.fillStyle = null;
130 this.rawNode.setAttribute("fill", "none");
131 this.rawNode.setAttribute("fill-opacity", 0);
132 return this;
133 }
134 var f;
135 // FIXME: slightly magical. We're using the outer scope's "f", but setting it later
136 var setter = function(x){
137 // we assume that we're executing in the scope of the node to mutate
138 this.setAttribute(x, f[x].toFixed(8));
139 };
140 if(typeof(fill) == "object" && "type" in fill){
141 // gradient
142 switch(fill.type){
143 case "linear":
144 f = g.makeParameters(g.defaultLinearGradient, fill);
145 var gradient = this._setFillObject(f, "linearGradient");
146 arr.forEach(["x1", "y1", "x2", "y2"], setter, gradient);
147 break;
148 case "radial":
149 f = g.makeParameters(g.defaultRadialGradient, fill);
150 var grad = this._setFillObject(f, "radialGradient");
151 arr.forEach(["cx", "cy", "r"], setter, grad);
152 break;
153 case "pattern":
154 f = g.makeParameters(g.defaultPattern, fill);
155 var pattern = this._setFillObject(f, "pattern");
156 arr.forEach(["x", "y", "width", "height"], setter, pattern);
157 break;
158 }
159 this.fillStyle = f;
160 return this;
161 }
162 // color object
163 f = g.normalizeColor(fill);
164 this.fillStyle = f;
165 this.rawNode.setAttribute("fill", f.toCss());
166 this.rawNode.setAttribute("fill-opacity", f.a);
167 this.rawNode.setAttribute("fill-rule", "evenodd");
168 return this; // self
169 },
170
171 setStroke: function(stroke){
172 // summary:
173 // sets a stroke object (SVG)
174 // stroke: Object
175 // a stroke object (see dojox/gfx.defaultStroke)
176
177 var rn = this.rawNode;
178 if(!stroke){
179 // don't stroke
180 this.strokeStyle = null;
181 rn.setAttribute("stroke", "none");
182 rn.setAttribute("stroke-opacity", 0);
183 return this;
184 }
185 // normalize the stroke
186 if(typeof stroke == "string" || lang.isArray(stroke) || stroke instanceof Color){
187 stroke = { color: stroke };
188 }
189 var s = this.strokeStyle = g.makeParameters(g.defaultStroke, stroke);
190 s.color = g.normalizeColor(s.color);
191 // generate attributes
192 if(s){
193 var w = s.width < 0 ? 0 : s.width;
194 rn.setAttribute("stroke", s.color.toCss());
195 rn.setAttribute("stroke-opacity", s.color.a);
196 rn.setAttribute("stroke-width", w);
197 rn.setAttribute("stroke-linecap", s.cap);
198 if(typeof s.join == "number"){
199 rn.setAttribute("stroke-linejoin", "miter");
200 rn.setAttribute("stroke-miterlimit", s.join);
201 }else{
202 rn.setAttribute("stroke-linejoin", s.join);
203 }
204 var da = s.style.toLowerCase();
205 if(da in svg.dasharray){
206 da = svg.dasharray[da];
207 }
208 if(da instanceof Array){
209 da = lang._toArray(da);
210 var i;
211 for(i = 0; i < da.length; ++i){
212 da[i] *= w;
213 }
214 if(s.cap != "butt"){
215 for(i = 0; i < da.length; i += 2){
216 da[i] -= w;
217 if(da[i] < 1){ da[i] = 1; }
218 }
219 for(i = 1; i < da.length; i += 2){
220 da[i] += w;
221 }
222 }
223 da = da.join(",");
224 }
225 rn.setAttribute("stroke-dasharray", da);
226 rn.setAttribute("dojoGfxStrokeStyle", s.style);
227 }
228 return this; // self
229 },
230
231 _getParentSurface: function(){
232 var surface = this.parent;
233 for(; surface && !(surface instanceof g.Surface); surface = surface.parent);
234 return surface;
235 },
236
237 _setFillObject: function(f, nodeType){
238 var svgns = svg.xmlns.svg;
239 this.fillStyle = f;
240 var surface = this._getParentSurface(),
241 defs = surface.defNode,
242 fill = this.rawNode.getAttribute("fill"),
243 ref = svg.getRef(fill);
244 if(ref){
245 fill = ref;
246 if(fill.tagName.toLowerCase() != nodeType.toLowerCase()){
247 var id = fill.id;
248 fill.parentNode.removeChild(fill);
249 fill = _createElementNS(svgns, nodeType);
250 fill.setAttribute("id", id);
251 defs.appendChild(fill);
252 }else{
253 while(fill.childNodes.length){
254 fill.removeChild(fill.lastChild);
255 }
256 }
257 }else{
258 fill = _createElementNS(svgns, nodeType);
259 fill.setAttribute("id", g._base._getUniqueId());
260 defs.appendChild(fill);
261 }
262 if(nodeType == "pattern"){
263 fill.setAttribute("patternUnits", "userSpaceOnUse");
264 var img = _createElementNS(svgns, "image");
265 img.setAttribute("x", 0);
266 img.setAttribute("y", 0);
267 img.setAttribute("width", (f.width < 0 ? 0 : f.width).toFixed(8));
268 img.setAttribute("height", (f.height < 0 ? 0 : f.height).toFixed(8));
269 _setAttributeNS(img, svg.xmlns.xlink, "xlink:href", f.src);
270 fill.appendChild(img);
271 }else{
272 fill.setAttribute("gradientUnits", "userSpaceOnUse");
273 for(var i = 0; i < f.colors.length; ++i){
274 var c = f.colors[i], t = _createElementNS(svgns, "stop"),
275 cc = c.color = g.normalizeColor(c.color);
276 t.setAttribute("offset", c.offset.toFixed(8));
277 t.setAttribute("stop-color", cc.toCss());
278 t.setAttribute("stop-opacity", cc.a);
279 fill.appendChild(t);
280 }
281 }
282 this.rawNode.setAttribute("fill", "url(#" + fill.getAttribute("id") +")");
283 this.rawNode.removeAttribute("fill-opacity");
284 this.rawNode.setAttribute("fill-rule", "evenodd");
285 return fill;
286 },
287
288 _applyTransform: function() {
289 var matrix = this.matrix;
290 if(matrix){
291 var tm = this.matrix;
292 this.rawNode.setAttribute("transform", "matrix(" +
293 tm.xx.toFixed(8) + "," + tm.yx.toFixed(8) + "," +
294 tm.xy.toFixed(8) + "," + tm.yy.toFixed(8) + "," +
295 tm.dx.toFixed(8) + "," + tm.dy.toFixed(8) + ")");
296 }else{
297 this.rawNode.removeAttribute("transform");
298 }
299 return this;
300 },
301
302 setRawNode: function(rawNode){
303 // summary:
304 // assigns and clears the underlying node that will represent this
305 // shape. Once set, transforms, gradients, etc, can be applied.
306 // (no fill & stroke by default)
307 var r = this.rawNode = rawNode;
308 if(this.shape.type!="image"){
309 r.setAttribute("fill", "none");
310 }
311 r.setAttribute("fill-opacity", 0);
312 r.setAttribute("stroke", "none");
313 r.setAttribute("stroke-opacity", 0);
314 r.setAttribute("stroke-width", 1);
315 r.setAttribute("stroke-linecap", "butt");
316 r.setAttribute("stroke-linejoin", "miter");
317 r.setAttribute("stroke-miterlimit", 4);
318 // Bind GFX object with SVG node for ease of retrieval - that is to
319 // save code/performance to keep this association elsewhere
320 r.__gfxObject__ = this;
321 },
322
323 setShape: function(newShape){
324 // summary:
325 // sets a shape object (SVG)
326 // newShape: Object
327 // a shape object
328 // (see dojox/gfx.defaultPath,
329 // dojox/gfx.defaultPolyline,
330 // dojox/gfx.defaultRect,
331 // dojox/gfx.defaultEllipse,
332 // dojox/gfx.defaultCircle,
333 // dojox/gfx.defaultLine,
334 // or dojox/gfx.defaultImage)
335 this.shape = g.makeParameters(this.shape, newShape);
336 for(var i in this.shape){
337 if(i != "type"){
338 var v = this.shape[i];
339 if(i === "width" || i === "height"){
340 v = v < 0 ? 0 : v;
341 }
342 this.rawNode.setAttribute(i, v);
343 }
344 }
345 this.bbox = null;
346 return this; // self
347 },
348
349 // move family
350
351 _moveToFront: function(){
352 // summary:
353 // moves a shape to front of its parent's list of shapes (SVG)
354 this.rawNode.parentNode.appendChild(this.rawNode);
355 return this; // self
356 },
357 _moveToBack: function(){
358 // summary:
359 // moves a shape to back of its parent's list of shapes (SVG)
360 this.rawNode.parentNode.insertBefore(this.rawNode, this.rawNode.parentNode.firstChild);
361 return this; // self
362 },
363 setClip: function(clip){
364 // summary:
365 // sets the clipping area of this shape.
366 // description:
367 // This method overrides the dojox/gfx/shape.Shape.setClip() method.
368 // clip: Object
369 // an object that defines the clipping geometry, or null to remove clip.
370 this.inherited(arguments);
371 var clipType = clip ? "width" in clip ? "rect" :
372 "cx" in clip ? "ellipse" :
373 "points" in clip ? "polyline" : "d" in clip ? "path" : null : null;
374 if(clip && !clipType){
375 return this;
376 }
377 if(clipType === "polyline"){
378 clip = lang.clone(clip);
379 clip.points = clip.points.join(",");
380 }
381 var clipNode, clipShape,
382 clipPathProp = domAttr.get(this.rawNode, "clip-path");
383 if(clipPathProp){
384 clipNode = dom.byId(clipPathProp.match(/gfx_clip[\d]+/)[0]);
385 if(clipNode){ // may be null if not in the DOM anymore
386 clipNode.removeChild(clipNode.childNodes[0]);
387 }
388 }
389 if(clip){
390 if(clipNode){
391 clipShape = _createElementNS(svg.xmlns.svg, clipType);
392 clipNode.appendChild(clipShape);
393 }else{
394 var idIndex = ++clipCount;
395 var clipId = "gfx_clip" + idIndex;
396 var clipUrl = "url(#" + clipId + ")";
397 this.rawNode.setAttribute("clip-path", clipUrl);
398 clipNode = _createElementNS(svg.xmlns.svg, "clipPath");
399 clipShape = _createElementNS(svg.xmlns.svg, clipType);
400 clipNode.appendChild(clipShape);
401 this.rawNode.parentNode.insertBefore(clipNode, this.rawNode);
402 domAttr.set(clipNode, "id", clipId);
403 }
404 domAttr.set(clipShape, clip);
405 }else{
406 //remove clip-path
407 this.rawNode.removeAttribute("clip-path");
408 if(clipNode){
409 clipNode.parentNode.removeChild(clipNode);
410 }
411 }
412 return this;
413 },
414 _removeClipNode: function(){
415 var clipNode, clipPathProp = domAttr.get(this.rawNode, "clip-path");
416 if(clipPathProp){
417 clipNode = dom.byId(clipPathProp.match(/gfx_clip[\d]+/)[0]);
418 if(clipNode){
419 clipNode.parentNode.removeChild(clipNode);
420 }
421 }
422 return clipNode;
423 }
424 });
425
426
427 svg.Group = declare("dojox.gfx.svg.Group", svg.Shape, {
428 // summary:
429 // a group shape (SVG), which can be used
430 // to logically group shapes (e.g, to propagate matricies)
431 constructor: function(){
432 gs.Container._init.call(this);
433 },
434 setRawNode: function(rawNode){
435 // summary:
436 // sets a raw SVG node to be used by this shape
437 // rawNode: Node
438 // an SVG node
439 this.rawNode = rawNode;
440 // Bind GFX object with SVG node for ease of retrieval - that is to
441 // save code/performance to keep this association elsewhere
442 this.rawNode.__gfxObject__ = this;
443 },
444 destroy: function(){
445 // summary:
446 // Releases all internal resources owned by this shape. Once this method has been called,
447 // the instance is considered disposed and should not be used anymore.
448 this.clear(true);
449 // avoid this.inherited
450 svg.Shape.prototype.destroy.apply(this, arguments);
451 }
452 });
453 svg.Group.nodeType = "g";
454
455 svg.Rect = declare("dojox.gfx.svg.Rect", [svg.Shape, gs.Rect], {
456 // summary:
457 // a rectangle shape (SVG)
458 setShape: function(newShape){
459 // summary:
460 // sets a rectangle shape object (SVG)
461 // newShape: Object
462 // a rectangle shape object
463 this.shape = g.makeParameters(this.shape, newShape);
464 this.bbox = null;
465 for(var i in this.shape){
466 if(i != "type" && i != "r"){
467 var v = this.shape[i];
468 if(i === "width" || i === "height"){
469 v = v < 0 ? 0 : v;
470 }
471 this.rawNode.setAttribute(i, v);
472 }
473 }
474 if(this.shape.r != null){
475 this.rawNode.setAttribute("ry", this.shape.r);
476 this.rawNode.setAttribute("rx", this.shape.r);
477 }
478 return this; // self
479 }
480 });
481 svg.Rect.nodeType = "rect";
482
483 svg.Ellipse = declare("dojox.gfx.svg.Ellipse", [svg.Shape, gs.Ellipse], {});
484 svg.Ellipse.nodeType = "ellipse";
485
486 svg.Circle = declare("dojox.gfx.svg.Circle", [svg.Shape, gs.Circle], {});
487 svg.Circle.nodeType = "circle";
488
489 svg.Line = declare("dojox.gfx.svg.Line", [svg.Shape, gs.Line], {});
490 svg.Line.nodeType = "line";
491
492 svg.Polyline = declare("dojox.gfx.svg.Polyline", [svg.Shape, gs.Polyline], {
493 // summary:
494 // a polyline/polygon shape (SVG)
495 setShape: function(points, closed){
496 // summary:
497 // sets a polyline/polygon shape object (SVG)
498 // points: Object|Array
499 // a polyline/polygon shape object, or an array of points
500 if(points && points instanceof Array){
501 this.shape = g.makeParameters(this.shape, { points: points });
502 if(closed && this.shape.points.length){
503 this.shape.points.push(this.shape.points[0]);
504 }
505 }else{
506 this.shape = g.makeParameters(this.shape, points);
507 }
508 this.bbox = null;
509 this._normalizePoints();
510 var attr = [], p = this.shape.points;
511 for(var i = 0; i < p.length; ++i){
512 attr.push(p[i].x.toFixed(8), p[i].y.toFixed(8));
513 }
514 this.rawNode.setAttribute("points", attr.join(" "));
515 return this; // self
516 }
517 });
518 svg.Polyline.nodeType = "polyline";
519
520 svg.Image = declare("dojox.gfx.svg.Image", [svg.Shape, gs.Image], {
521 // summary:
522 // an image (SVG)
523 setShape: function(newShape){
524 // summary:
525 // sets an image shape object (SVG)
526 // newShape: Object
527 // an image shape object
528 this.shape = g.makeParameters(this.shape, newShape);
529 this.bbox = null;
530 var rawNode = this.rawNode;
531 for(var i in this.shape){
532 if(i != "type" && i != "src"){
533 var v = this.shape[i];
534 if(i === "width" || i === "height"){
535 v = v < 0 ? 0 : v;
536 }
537 rawNode.setAttribute(i, v);
538 }
539 }
540 rawNode.setAttribute("preserveAspectRatio", "none");
541 _setAttributeNS(rawNode, svg.xmlns.xlink, "xlink:href", this.shape.src);
542 // Bind GFX object with SVG node for ease of retrieval - that is to
543 // save code/performance to keep this association elsewhere
544 rawNode.__gfxObject__ = this;
545 return this; // self
546 }
547 });
548 svg.Image.nodeType = "image";
549
550 svg.Text = declare("dojox.gfx.svg.Text", [svg.Shape, gs.Text], {
551 // summary:
552 // an anchored text (SVG)
553 setShape: function(newShape){
554 // summary:
555 // sets a text shape object (SVG)
556 // newShape: Object
557 // a text shape object
558 this.shape = g.makeParameters(this.shape, newShape);
559 this.bbox = null;
560 var r = this.rawNode, s = this.shape;
561 r.setAttribute("x", s.x);
562 r.setAttribute("y", s.y);
563 r.setAttribute("text-anchor", s.align);
564 r.setAttribute("text-decoration", s.decoration);
565 r.setAttribute("rotate", s.rotated ? 90 : 0);
566 r.setAttribute("kerning", s.kerning ? "auto" : 0);
567 r.setAttribute("text-rendering", textRenderingFix);
568
569 // update the text content
570 if(r.firstChild){
571 r.firstChild.nodeValue = s.text;
572 }else{
573 r.appendChild(_createTextNode(s.text));
574 }
575 return this; // self
576 },
577 getTextWidth: function(){
578 // summary:
579 // get the text width in pixels
580 var rawNode = this.rawNode,
581 oldParent = rawNode.parentNode,
582 _measurementNode = rawNode.cloneNode(true);
583 _measurementNode.style.visibility = "hidden";
584
585 // solution to the "orphan issue" in FF
586 var _width = 0, _text = _measurementNode.firstChild.nodeValue;
587 oldParent.appendChild(_measurementNode);
588
589 // solution to the "orphan issue" in Opera
590 // (nodeValue == "" hangs firefox)
591 if(_text!=""){
592 while(!_width){
593 //Yang: work around svgweb bug 417 -- http://code.google.com/p/svgweb/issues/detail?id=417
594 if (_measurementNode.getBBox)
595 _width = parseInt(_measurementNode.getBBox().width);
596 else
597 _width = 68;
598 }
599 }
600 oldParent.removeChild(_measurementNode);
601 return _width;
602 },
603 getBoundingBox: function(){
604 var s = this.getShape(), bbox = null;
605 if(s.text){
606 // try/catch the FF native getBBox error.
607 try {
608 bbox = this.rawNode.getBBox();
609 } catch (e) {
610 // under FF when the node is orphan (all other browsers return a 0ed bbox.
611 bbox = {x:0, y:0, width:0, height:0};
612 }
613 }
614 return bbox;
615 }
616 });
617 svg.Text.nodeType = "text";
618
619 svg.Path = declare("dojox.gfx.svg.Path", [svg.Shape, pathLib.Path], {
620 // summary:
621 // a path shape (SVG)
622 _updateWithSegment: function(segment){
623 // summary:
624 // updates the bounding box of path with new segment
625 // segment: Object
626 // a segment
627 this.inherited(arguments);
628 if(typeof(this.shape.path) == "string"){
629 this.rawNode.setAttribute("d", this.shape.path);
630 }
631 },
632 setShape: function(newShape){
633 // summary:
634 // forms a path using a shape (SVG)
635 // newShape: Object
636 // an SVG path string or a path object (see dojox/gfx.defaultPath)
637 this.inherited(arguments);
638 if(this.shape.path){
639 this.rawNode.setAttribute("d", this.shape.path);
640 }else{
641 this.rawNode.removeAttribute("d");
642 }
643 return this; // self
644 }
645 });
646 svg.Path.nodeType = "path";
647
648 svg.TextPath = declare("dojox.gfx.svg.TextPath", [svg.Shape, pathLib.TextPath], {
649 // summary:
650 // a textpath shape (SVG)
651 _updateWithSegment: function(segment){
652 // summary:
653 // updates the bounding box of path with new segment
654 // segment: Object
655 // a segment
656 this.inherited(arguments);
657 this._setTextPath();
658 },
659 setShape: function(newShape){
660 // summary:
661 // forms a path using a shape (SVG)
662 // newShape: Object
663 // an SVG path string or a path object (see dojox/gfx.defaultPath)
664 this.inherited(arguments);
665 this._setTextPath();
666 return this; // self
667 },
668 _setTextPath: function(){
669 if(typeof this.shape.path != "string"){ return; }
670 var r = this.rawNode;
671 if(!r.firstChild){
672 var tp = _createElementNS(svg.xmlns.svg, "textPath"),
673 tx = _createTextNode("");
674 tp.appendChild(tx);
675 r.appendChild(tp);
676 }
677 var ref = r.firstChild.getAttributeNS(svg.xmlns.xlink, "href"),
678 path = ref && svg.getRef(ref);
679 if(!path){
680 var surface = this._getParentSurface();
681 if(surface){
682 var defs = surface.defNode;
683 path = _createElementNS(svg.xmlns.svg, "path");
684 var id = g._base._getUniqueId();
685 path.setAttribute("id", id);
686 defs.appendChild(path);
687 _setAttributeNS(r.firstChild, svg.xmlns.xlink, "xlink:href", "#" + id);
688 }
689 }
690 if(path){
691 path.setAttribute("d", this.shape.path);
692 }
693 },
694 _setText: function(){
695 var r = this.rawNode;
696 if(!r.firstChild){
697 var tp = _createElementNS(svg.xmlns.svg, "textPath"),
698 tx = _createTextNode("");
699 tp.appendChild(tx);
700 r.appendChild(tp);
701 }
702 r = r.firstChild;
703 var t = this.text;
704 r.setAttribute("alignment-baseline", "middle");
705 switch(t.align){
706 case "middle":
707 r.setAttribute("text-anchor", "middle");
708 r.setAttribute("startOffset", "50%");
709 break;
710 case "end":
711 r.setAttribute("text-anchor", "end");
712 r.setAttribute("startOffset", "100%");
713 break;
714 default:
715 r.setAttribute("text-anchor", "start");
716 r.setAttribute("startOffset", "0%");
717 break;
718 }
719 //r.parentNode.setAttribute("alignment-baseline", "central");
720 //r.setAttribute("dominant-baseline", "central");
721 r.setAttribute("baseline-shift", "0.5ex");
722 r.setAttribute("text-decoration", t.decoration);
723 r.setAttribute("rotate", t.rotated ? 90 : 0);
724 r.setAttribute("kerning", t.kerning ? "auto" : 0);
725 r.firstChild.data = t.text;
726 }
727 });
728 svg.TextPath.nodeType = "text";
729
730 // Fix for setDimension bug:
731 // http://bugs.dojotoolkit.org/ticket/16100
732 // (https://code.google.com/p/chromium/issues/detail?id=162628)
733 var hasSvgSetAttributeBug = (function(){ var matches = /WebKit\/(\d*)/.exec(uagent); return matches ? matches[1] : 0})() > 534;
734
735 svg.Surface = declare("dojox.gfx.svg.Surface", gs.Surface, {
736 // summary:
737 // a surface object to be used for drawings (SVG)
738 constructor: function(){
739 gs.Container._init.call(this);
740 },
741 destroy: function(){
742 // no need to call svg.Container.clear to remove the children raw
743 // nodes since the surface raw node will be removed. So, only dispose at gfx level
744 gs.Container.clear.call(this, true);
745 this.defNode = null; // release the external reference
746 this.inherited(arguments);
747 },
748 setDimensions: function(width, height){
749 // summary:
750 // sets the width and height of the rawNode
751 // width: String
752 // width of surface, e.g., "100px"
753 // height: String
754 // height of surface, e.g., "100px"
755 if(!this.rawNode){ return this; }
756 var w = width < 0 ? 0 : width,
757 h = height < 0 ? 0 : height;
758 this.rawNode.setAttribute("width", w);
759 this.rawNode.setAttribute("height", h);
760 if(hasSvgSetAttributeBug){
761 this.rawNode.style.width = w;
762 this.rawNode.style.height = h;
763 }
764 return this; // self
765 },
766 getDimensions: function(){
767 // summary:
768 // returns an object with properties "width" and "height"
769 var t = this.rawNode ? {
770 width: g.normalizedLength(this.rawNode.getAttribute("width")),
771 height: g.normalizedLength(this.rawNode.getAttribute("height"))} : null;
772 return t; // Object
773 }
774 });
775
776 svg.createSurface = function(parentNode, width, height){
777 // summary:
778 // creates a surface (SVG)
779 // parentNode: Node
780 // a parent node
781 // width: String|Number
782 // width of surface, e.g., "100px" or 100
783 // height: String|Number
784 // height of surface, e.g., "100px" or 100
785 // returns: dojox/gfx/shape.Surface
786 // newly created surface
787
788 var s = new svg.Surface();
789 s.rawNode = _createElementNS(svg.xmlns.svg, "svg");
790 s.rawNode.setAttribute("overflow", "hidden");
791 if(width){
792 s.rawNode.setAttribute("width", width < 0 ? 0 : width);
793 }
794 if(height){
795 s.rawNode.setAttribute("height", height < 0 ? 0 : height);
796 }
797
798 var defNode = _createElementNS(svg.xmlns.svg, "defs");
799 s.rawNode.appendChild(defNode);
800 s.defNode = defNode;
801
802 s._parent = dom.byId(parentNode);
803 s._parent.appendChild(s.rawNode);
804
805 g._base._fixMsTouchAction(s);
806
807 return s; // dojox/gfx.Surface
808 };
809
810 // Extenders
811
812 var Font = {
813 _setFont: function(){
814 // summary:
815 // sets a font object (SVG)
816 var f = this.fontStyle;
817 // next line doesn't work in Firefox 2 or Opera 9
818 //this.rawNode.setAttribute("font", dojox.gfx.makeFontString(this.fontStyle));
819 this.rawNode.setAttribute("font-style", f.style);
820 this.rawNode.setAttribute("font-variant", f.variant);
821 this.rawNode.setAttribute("font-weight", f.weight);
822 this.rawNode.setAttribute("font-size", f.size);
823 this.rawNode.setAttribute("font-family", f.family);
824 }
825 };
826
827 var C = gs.Container;
828 var Container = svg.Container = {
829 openBatch: function() {
830 // summary:
831 // starts a new batch, subsequent new child shapes will be held in
832 // the batch instead of appending to the container directly
833 if(!this._batch){
834 this.fragment = _createFragment();
835 }
836 ++this._batch;
837 return this;
838 },
839 closeBatch: function() {
840 // summary:
841 // submits the current batch, append all pending child shapes to DOM
842 this._batch = this._batch > 0 ? --this._batch : 0;
843 if (this.fragment && !this._batch) {
844 this.rawNode.appendChild(this.fragment);
845 delete this.fragment;
846 }
847 return this;
848 },
849 add: function(shape){
850 // summary:
851 // adds a shape to a group/surface
852 // shape: dojox/gfx/shape.Shape
853 // an VML shape object
854 if(this != shape.getParent()){
855 if (this.fragment) {
856 this.fragment.appendChild(shape.rawNode);
857 } else {
858 this.rawNode.appendChild(shape.rawNode);
859 }
860 C.add.apply(this, arguments);
861 // update clipnode with new parent
862 shape.setClip(shape.clip);
863 }
864 return this; // self
865 },
866 remove: function(shape, silently){
867 // summary:
868 // remove a shape from a group/surface
869 // shape: dojox/gfx/shape.Shape
870 // an VML shape object
871 // silently: Boolean?
872 // if true, regenerate a picture
873 if(this == shape.getParent()){
874 if(this.rawNode == shape.rawNode.parentNode){
875 this.rawNode.removeChild(shape.rawNode);
876 }
877 if(this.fragment && this.fragment == shape.rawNode.parentNode){
878 this.fragment.removeChild(shape.rawNode);
879 }
880 // remove clip node from parent
881 shape._removeClipNode();
882 C.remove.apply(this, arguments);
883 }
884 return this; // self
885 },
886 clear: function(){
887 // summary:
888 // removes all shapes from a group/surface
889 var r = this.rawNode;
890 while(r.lastChild){
891 r.removeChild(r.lastChild);
892 }
893 var defNode = this.defNode;
894 if(defNode){
895 while(defNode.lastChild){
896 defNode.removeChild(defNode.lastChild);
897 }
898 r.appendChild(defNode);
899 }
900 return C.clear.apply(this, arguments);
901 },
902 getBoundingBox: C.getBoundingBox,
903 _moveChildToFront: C._moveChildToFront,
904 _moveChildToBack: C._moveChildToBack
905 };
906
907 var Creator = svg.Creator = {
908 // summary:
909 // SVG shape creators
910 createObject: function(shapeType, rawShape){
911 // summary:
912 // creates an instance of the passed shapeType class
913 // shapeType: Function
914 // a class constructor to create an instance of
915 // rawShape: Object
916 // properties to be passed in to the classes "setShape" method
917 if(!this.rawNode){ return null; }
918 var shape = new shapeType(),
919 node = _createElementNS(svg.xmlns.svg, shapeType.nodeType);
920
921 shape.setRawNode(node);
922 shape.setShape(rawShape);
923 // rawNode.appendChild() will be done inside this.add(shape) below
924 this.add(shape);
925 return shape; // dojox/gfx/shape.Shape
926 }
927 };
928
929 lang.extend(svg.Text, Font);
930 lang.extend(svg.TextPath, Font);
931
932 lang.extend(svg.Group, Container);
933 lang.extend(svg.Group, gs.Creator);
934 lang.extend(svg.Group, Creator);
935
936 lang.extend(svg.Surface, Container);
937 lang.extend(svg.Surface, gs.Creator);
938 lang.extend(svg.Surface, Creator);
939
940 // Mouse/Touch event
941 svg.fixTarget = function(event, gfxElement) {
942 // summary:
943 // Adds the gfxElement to event.gfxTarget if none exists. This new
944 // property will carry the GFX element associated with this event.
945 // event: Object
946 // The current input event (MouseEvent or TouchEvent)
947 // gfxElement: Object
948 // The GFX target element
949 if (!event.gfxTarget) {
950 if (safMobile && event.target.wholeText) {
951 // Workaround iOS bug when touching text nodes
952 event.gfxTarget = event.target.parentElement.__gfxObject__;
953 } else {
954 event.gfxTarget = event.target.__gfxObject__;
955 }
956 }
957 return true;
958 };
959
960 // some specific override for svgweb + flash
961 if(svg.useSvgWeb){
962 // override createSurface()
963 svg.createSurface = function(parentNode, width, height){
964 var s = new svg.Surface();
965
966 width = width < 0 ? 0 : width;
967 height = height < 0 ? 0 : height;
968
969 // ensure width / height
970 if(!width || !height){
971 var pos = domGeom.position(parentNode);
972 width = width || pos.w;
973 height = height || pos.h;
974 }
975
976 // ensure id
977 parentNode = dom.byId(parentNode);
978 var id = parentNode.id ? parentNode.id+'_svgweb' : g._base._getUniqueId();
979
980 // create dynamic svg root
981 var mockSvg = _createElementNS(svg.xmlns.svg, 'svg');
982 mockSvg.id = id;
983 mockSvg.setAttribute('width', width);
984 mockSvg.setAttribute('height', height);
985 svgweb.appendChild(mockSvg, parentNode);
986
987 // notice: any call to the raw node before flash init will fail.
988 mockSvg.addEventListener('SVGLoad', function(){
989 // become loaded
990 s.rawNode = this;
991 s.isLoaded = true;
992
993 // init defs
994 var defNode = _createElementNS(svg.xmlns.svg, "defs");
995 s.rawNode.appendChild(defNode);
996 s.defNode = defNode;
997
998 // notify application
999 if (s.onLoad)
1000 s.onLoad(s);
1001 }, false);
1002
1003 // flash not loaded yet
1004 s.isLoaded = false;
1005 return s;
1006 };
1007
1008 // override Surface.destroy()
1009 svg.Surface.extend({
1010 destroy: function(){
1011 var mockSvg = this.rawNode;
1012 svgweb.removeChild(mockSvg, mockSvg.parentNode);
1013 }
1014 });
1015
1016 // override connect() & disconnect() for Shape & Surface event processing
1017 var _eventsProcessing = {
1018 connect: function(name, object, method){
1019 // connect events using the mock addEventListener() provided by svgweb
1020 if (name.substring(0, 2)==='on') { name = name.substring(2); }
1021 if (arguments.length == 2) {
1022 method = object;
1023 } else {
1024 method = lang.hitch(object, method);
1025 }
1026 this.getEventSource().addEventListener(name, method, false);
1027 return [this, name, method];
1028 },
1029 disconnect: function(token){
1030 // disconnect events using the mock removeEventListener() provided by svgweb
1031 this.getEventSource().removeEventListener(token[1], token[2], false);
1032 delete token[0];
1033 }
1034 };
1035
1036 lang.extend(svg.Shape, _eventsProcessing);
1037 lang.extend(svg.Surface, _eventsProcessing);
1038 }
1039
1040 return svg;
1041 });