forked from paperjs/paper.js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathItem.js
More file actions
3395 lines (3238 loc) · 97.2 KB
/
Copy pathItem.js
File metadata and controls
3395 lines (3238 loc) · 97.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Paper.js - The Swiss Army Knife of Vector Graphics Scripting.
* http://paperjs.org/
*
* Copyright (c) 2011 - 2013, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
* Distributed under the MIT license. See LICENSE file for details.
*
* All rights reserved.
*/
/**
* @name Item
*
* @class The Item type allows you to access and modify the items in
* Paper.js projects. Its functionality is inherited by different project
* item types such as {@link Path}, {@link CompoundPath}, {@link Group},
* {@link Layer} and {@link Raster}. They each add a layer of functionality that
* is unique to their type, but share the underlying properties and functions
* that they inherit from Item.
*/
var Item = Base.extend(Callback, /** @lends Item# */{
statics: {
/**
* Override Item.extend() to merge the subclass' _serializeFields with
* the parent class' _serializeFields.
*
* @private
*/
extend: function extend(src) {
if (src._serializeFields)
src._serializeFields = Base.merge(
this.prototype._serializeFields, src._serializeFields);
var res = extend.base.apply(this, arguments),
proto = res.prototype,
name = proto._class;
// Derive the _type string from class name
if (name)
proto._type = Base.hyphenate(name);
return res;
}
},
_class: 'Item',
// All items apply their matrix by default.
// Exceptions are Raster, PlacedSymbol, Clip and Shape.
_transformContent: true,
_boundsSelected: false,
// Provide information about fields to be serialized, with their defaults
// that can be ommited.
_serializeFields: {
name: null,
matrix: new Matrix(),
locked: false,
visible: true,
blendMode: 'normal',
opacity: 1,
guide: false,
selected: false,
clipMask: false,
data: {}
},
initialize: function Item() {
// Do nothing.
},
_initialize: function(props, point) {
// Define this Item's unique id.
this._id = Item._id = (Item._id || 0) + 1;
// If _project is already set, the item was already moved into the DOM
// hierarchy. Used by Layer, where it's added to project.layers instead
if (!this._project) {
var project = paper.project,
layer = project.activeLayer;
// Do not insert into DOM if props.insert is false.
if (layer && !(props && props.insert === false)) {
layer.addChild(this);
} else {
this._setProject(project);
}
}
this._style = new Style(this._project._currentStyle, this);
this._matrix = new Matrix();
if (point)
this._matrix.translate(point);
return props ? this._set(props, { insert: true }) : true;
},
_events: new function() {
// Flags defining which native events are required by which Paper events
// as required for counting amount of necessary natives events.
// The mapping is native -> virtual
var mouseFlags = {
mousedown: {
mousedown: 1,
mousedrag: 1,
click: 1,
doubleclick: 1
},
mouseup: {
mouseup: 1,
mousedrag: 1,
click: 1,
doubleclick: 1
},
mousemove: {
mousedrag: 1,
mousemove: 1,
mouseenter: 1,
mouseleave: 1
}
};
// Entry for all mouse events in the _events list
var mouseEvent = {
install: function(type) {
// If the view requires counting of installed mouse events,
// increase the counters now according to mouseFlags
var counters = this._project.view._eventCounters;
if (counters) {
for (var key in mouseFlags) {
counters[key] = (counters[key] || 0)
+ (mouseFlags[key][type] || 0);
}
}
},
uninstall: function(type) {
// If the view requires counting of installed mouse events,
// decrease the counters now according to mouseFlags
var counters = this._project.view._eventCounters;
if (counters) {
for (var key in mouseFlags)
counters[key] -= mouseFlags[key][type] || 0;
}
}
};
return Base.each(['onMouseDown', 'onMouseUp', 'onMouseDrag', 'onClick',
'onDoubleClick', 'onMouseMove', 'onMouseEnter', 'onMouseLeave'],
function(name) {
this[name] = mouseEvent;
}, {
onFrame: {
install: function() {
this._project.view._animateItem(this, true);
},
uninstall: function() {
this._project.view._animateItem(this, false);
}
},
// Only for external sources, e.g. Raster
onLoad: {}
}
);
},
_serialize: function(options, dictionary) {
var props = {},
that = this;
function serialize(fields) {
for (var key in fields) {
var value = that[key];
// Style#leading is a special case, as its default value is
// dependent on the fontSize. Handle this here separately.
if (!Base.equals(value, key === 'leading'
? fields.fontSize * 1.2 : fields[key])) {
props[key] = Base.serialize(value, options,
// Do not use compact mode for data
key !== 'data', dictionary);
}
}
}
// Serialize fields that this Item subclass defines first
serialize(this._serializeFields);
// Serialize style fields, but only if they differ from defaults.
// Do not serialize styles on Groups and Layers, since they just unify
// their children's own styles.
if (!(this instanceof Group))
serialize(this._style._defaults);
// There is no compact form for Item serialization, we always keep the
// class.
return [ this._class, props ];
},
/**
* Private notifier that is called whenever a change occurs in this item or
* its sub-elements, such as Segments, Curves, Styles, etc.
*
* @param {ChangeFlag} flags describes what exactly has changed.
*/
_changed: function(flags) {
var parent = this._parent,
project = this._project,
symbol = this._parentSymbol;
// Reset _drawCount on each change.
this._drawCount = null;
if (flags & /*#=*/ ChangeFlag.GEOMETRY) {
// Clear cached bounds and position whenever geometry changes
delete this._bounds;
delete this._position;
}
if (parent && (flags
& (/*#=*/ ChangeFlag.GEOMETRY | /*#=*/ ChangeFlag.STROKE))) {
// Clear cached bounds of all items that this item contributes to.
// We call this on the parent, since the information is cached on
// the parent, see getBounds().
parent._clearBoundsCache();
}
if (flags & /*#=*/ ChangeFlag.HIERARCHY) {
// Clear cached bounds of all items that this item contributes to.
// We don't call this on the parent, since we're already the parent
// of the child that modified the hierarchy (that's where these
// HIERARCHY notifications go)
this._clearBoundsCache();
}
if (project) {
if (flags & /*#=*/ ChangeFlag.APPEARANCE) {
project._needsRedraw = true;
}
// Have project keep track of changed items so they can be iterated.
// This can be used for example to update the SVG tree. Needs to be
// activated in Project
if (project._changes) {
var entry = project._changesById[this._id];
if (entry) {
entry.flags |= flags;
} else {
entry = { item: this, flags: flags };
project._changesById[this._id] = entry;
project._changes.push(entry);
}
}
}
// If this item is a symbol's definition, notify it of the change too
if (symbol)
symbol._changed(flags);
},
/**
* Sets those properties of the passed object literal on this item to
* the values defined in the object literal, if the item has property of the
* given name (or a setter defined for it).
* @param {Object} props
* @return {Item} the item itself.
*
* @example {@paperscript}
* // Setting properties through an object literal
* var circle = new Path.Circle({
* center: [80, 50],
* radius: 35
* });
*
* circle.set({
* strokeColor: 'red',
* strokeWidth: 10,
* fillColor: 'black',
* selected: true
* });
*/
set: function(props) {
if (props)
this._set(props);
return this;
},
/**
* The unique id of the item.
*
* @type Number
* @bean
*/
getId: function() {
return this._id;
},
/**
* The type of the item as a string.
*
* @type String('group', 'layer', 'path', 'compound-path', 'raster',
* 'placed-symbol', 'point-text')
* @bean
*/
getType: function() {
return this._type;
},
/**
* The name of the item. If the item has a name, it can be accessed by name
* through its parent's children list.
*
* @type String
* @bean
*
* @example {@paperscript}
* var path = new Path.Circle({
* center: [80, 50],
* radius: 35
* });
* // Set the name of the path:
* path.name = 'example';
*
* // Create a group and add path to it as a child:
* var group = new Group();
* group.addChild(path);
*
* // The path can be accessed by name:
* group.children['example'].fillColor = 'red';
*/
getName: function() {
return this._name;
},
setName: function(name, unique) {
// Note: Don't check if the name has changed and bail out if it has not,
// because setName is used internally also to update internal structures
// when an item is moved from one parent to another.
// If the item already had a name, remove the reference to it from the
// parent's children object:
if (this._name)
this._removeNamed();
// See if the name is a simple number, which we cannot support due to
// the named lookup on the children array.
if (name === (+name) + '')
throw new Error(
'Names consisting only of numbers are not supported.');
if (name && this._parent) {
var children = this._parent._children,
namedChildren = this._parent._namedChildren,
orig = name,
i = 1;
// If unique is true, make sure we're not overriding other names
while (unique && children[name])
name = orig + ' ' + (i++);
(namedChildren[name] = namedChildren[name] || []).push(this);
children[name] = this;
}
this._name = name || undefined;
this._changed(/*#=*/ ChangeFlag.ATTRIBUTE);
},
/**
* The path style of the item.
*
* @name Item#getStyle
* @type Style
* @bean
*
* @example {@paperscript}
* // Applying several styles to an item in one go, by passing an object
* // to its style property:
* var circle = new Path.Circle({
* center: [80, 50],
* radius: 30
* });
* circle.style = {
* fillColor: 'blue',
* strokeColor: 'red',
* strokeWidth: 5
* };
*
* @example {@paperscript split=true height=100}
* // Copying the style of another item:
* var path = new Path.Circle({
* center: [50, 50],
* radius: 30,
* fillColor: 'red'
* });
*
* var path2 = new Path.Circle({
* center: new Point(180, 50),
* radius: 20
* });
*
* // Copy the path style of path:
* path2.style = path.style;
*
* @example {@paperscript}
* // Applying the same style object to multiple items:
* var myStyle = {
* fillColor: 'red',
* strokeColor: 'blue',
* strokeWidth: 4
* };
*
* var path = new Path.Circle({
* center: [50, 50],
* radius: 30
* });
* path.style = myStyle;
*
* var path2 = new Path.Circle({
* center: new Point(150, 50),
* radius: 20
* });
* path2.style = myStyle;
*/
getStyle: function() {
return this._style;
},
setStyle: function(style) {
// Don't access _style directly so Path#getStyle() can be overriden for
// CompoundPaths.
this.getStyle().set(style);
},
// DOCS: Item#hasFill()
hasFill: function() {
return this.getStyle().hasFill();
},
// DOCS: Item#hasStroke()
hasStroke: function() {
return this.getStyle().hasStroke();
}
}, Base.each(['locked', 'visible', 'blendMode', 'opacity', 'guide'],
// Produce getter/setters for properties. We need setters because we want to
// call _changed() if a property was modified.
function(name) {
var part = Base.capitalize(name),
name = '_' + name;
this['get' + part] = function() {
return this[name];
};
this['set' + part] = function(value) {
if (value != this[name]) {
this[name] = value;
// #locked does not change appearance, all others do:
this._changed(name === '_locked'
? /*#=*/ ChangeFlag.ATTRIBUTE : /*#=*/ Change.ATTRIBUTE);
}
};
}, {}), /** @lends Item# */{
// Note: These properties have their getter / setters produced in the
// injection scope above.
/**
* Specifies whether the item is locked.
*
* @name Item#locked
* @type Boolean
* @default false
* @ignore
*/
_locked: false,
/**
* Specifies whether the item is visible. When set to {@code false}, the
* item won't be drawn.
*
* @name Item#visible
* @type Boolean
* @default true
*
* @example {@paperscript}
* // Hiding an item:
* var path = new Path.Circle({
* center: [50, 50],
* radius: 20,
* fillColor: 'red'
* });
*
* // Hide the path:
* path.visible = false;
*/
_visible: true,
/**
* The blend mode with which the item is composited onto the canvas. Both
* the standard canvas compositing modes, as well as the new CSS blend modes
* are supported. If blend-modes cannot be rendered natively, they are
* emulated. Be aware that emulation can have an impact on performance.
*
* @name Item#blendMode
* @type String('normal', 'multiply', 'screen', 'overlay', 'soft-light',
* 'hard-light', 'color-dodge', 'color-burn', 'darken', 'lighten',
* 'difference', 'exclusion', 'hue', 'saturation', 'luminosity', 'color',
* 'add', 'subtract', 'average', 'pin-light', 'negation', 'source-over',
* 'source-in', 'source-out', 'source-atop', 'destination-over',
* 'destination-in', 'destination-out', 'destination-atop', 'lighter',
* 'darker', 'copy', 'xor')
* @default 'normal'
*
* @example {@paperscript}
* // Setting an item's blend mode:
*
* // Create a white rectangle in the background
* // with the same dimensions as the view:
* var background = new Path.Rectangle(view.bounds);
* background.fillColor = 'white';
*
* var circle = new Path.Circle({
* center: [80, 50],
* radius: 35,
* fillColor: 'red'
* });
*
* var circle2 = new Path.Circle({
* center: new Point(120, 50),
* radius: 35,
* fillColor: 'blue'
* });
*
* // Set the blend mode of circle2:
* circle2.blendMode = 'multiply';
*/
_blendMode: 'normal',
/**
* The opacity of the item as a value between {@code 0} and {@code 1}.
*
* @name Item#opacity
* @type Number
* @default 1
*
* @example {@paperscript}
* // Making an item 50% transparent:
* var circle = new Path.Circle({
* center: [80, 50],
* radius: 35,
* fillColor: 'red'
* });
*
* var circle2 = new Path.Circle({
* center: new Point(120, 50),
* radius: 35,
* fillColor: 'blue',
* strokeColor: 'green',
* strokeWidth: 10
* });
*
* // Make circle2 50% transparent:
* circle2.opacity = 0.5;
*/
_opacity: 1,
// TODO: Implement guides
/**
* Specifies whether the item functions as a guide. When set to
* {@code true}, the item will be drawn at the end as a guide.
*
* @name Item#guide
* @type Boolean
* @default true
* @ignore
*/
_guide: false,
/**
* Specifies whether an item is selected and will also return {@code true}
* if the item is partially selected (groups with some selected or partially
* selected paths).
*
* Paper.js draws the visual outlines of selected items on top of your
* project. This can be useful for debugging, as it allows you to see the
* construction of paths, position of path curves, individual segment points
* and bounding boxes of symbol and raster items.
*
* @type Boolean
* @default false
* @bean
* @see Project#selectedItems
* @see Segment#selected
* @see Point#selected
*
* @example {@paperscript}
* // Selecting an item:
* var path = new Path.Circle({
* center: [80, 50],
* radius: 35
* });
* path.selected = true; // Select the path
*/
isSelected: function() {
if (this._children) {
for (var i = 0, l = this._children.length; i < l; i++)
if (this._children[i].isSelected())
return true;
}
return this._selected;
},
setSelected: function(selected /*, noChildren */) {
// Don't recursively call #setSelected() if it was called with
// noChildren set to true, see #setFullySelected().
if (this._children && !arguments[1]) {
for (var i = 0, l = this._children.length; i < l; i++)
this._children[i].setSelected(selected);
}
if ((selected = !!selected) != this._selected) {
this._selected = selected;
this._project._updateSelection(this);
this._changed(/*#=*/ Change.ATTRIBUTE);
}
},
_selected: false,
isFullySelected: function() {
if (this._children && this._selected) {
for (var i = 0, l = this._children.length; i < l; i++)
if (!this._children[i].isFullySelected())
return false;
return true;
}
// If there are no children, this is the same as #selected
return this._selected;
},
setFullySelected: function(selected) {
if (this._children) {
for (var i = 0, l = this._children.length; i < l; i++)
this._children[i].setFullySelected(selected);
}
// Pass true for hidden noChildren argument
this.setSelected(selected, true);
},
/**
* Specifies whether the item defines a clip mask. This can only be set on
* paths, compound paths, and text frame objects, and only if the item is
* already contained within a clipping group.
*
* @type Boolean
* @default false
* @bean
*/
isClipMask: function() {
return this._clipMask;
},
setClipMask: function(clipMask) {
// On-the-fly conversion to boolean:
if (this._clipMask != (clipMask = !!clipMask)) {
this._clipMask = clipMask;
if (clipMask) {
this.setFillColor(null);
this.setStrokeColor(null);
}
this._changed(/*#=*/ Change.ATTRIBUTE);
// Tell the parent the clipping mask has changed
if (this._parent)
this._parent._changed(/*#=*/ ChangeFlag.CLIPPING);
}
},
_clipMask: false,
// TODO: get/setIsolated (print specific feature)
// TODO: get/setKnockout (print specific feature)
// TODO: get/setAlphaIsShape
/**
* A plain javascript object which can be used to store
* arbitrary data on the item.
*
* @type Object
* @bean
*
* @example
* var path = new Path();
* path.data.remember = 'milk';
*
* @example
* var path = new Path();
* path.data.malcolm = new Point(20, 30);
* console.log(path.data.malcolm.x); // 20
*
* @example
* var path = new Path();
* path.data = {
* home: 'Omicron Theta',
* found: 2338,
* pets: ['Spot']
* };
* console.log(path.data.pets.length); // 1
*
* @example
* var path = new Path({
* data: {
* home: 'Omicron Theta',
* found: 2338,
* pets: ['Spot']
* }
* });
* console.log(path.data.pets.length); // 1
*/
getData: function() {
if (!this._data)
this._data = {};
return this._data;
},
setData: function(data) {
this._data = data;
},
/**
* {@grouptitle Position and Bounding Boxes}
*
* The item's position within the project. This is the
* {@link Rectangle#center} of the item's {@link #bounds} rectangle.
*
* @type Point
* @bean
*
* @example {@paperscript}
* // Changing the position of a path:
*
* // Create a circle at position { x: 10, y: 10 }
* var circle = new Path.Circle({
* center: new Point(10, 10),
* radius: 10,
* fillColor: 'red'
* });
*
* // Move the circle to { x: 20, y: 20 }
* circle.position = new Point(20, 20);
*
* // Move the circle 100 points to the right and 50 points down
* circle.position += new Point(100, 50);
*
* @example {@paperscript split=true height=100}
* // Changing the x coordinate of an item's position:
*
* // Create a circle at position { x: 20, y: 20 }
* var circle = new Path.Circle({
* center: new Point(20, 20),
* radius: 10,
* fillColor: 'red'
* });
*
* // Move the circle 100 points to the right
* circle.position.x += 100;
*/
getPosition: function(/* dontLink */) {
// Cache position value.
// Pass true for dontLink in getCenter(), so receive back a normal point
var pos = this._position
|| (this._position = this.getBounds().getCenter(true));
// Do not cache LinkedPoints directly, since we would not be able to
// use them to calculate the difference in #setPosition, as when it is
// modified, it would hold new values already and only then cause the
// calling of #setPosition.
return new (arguments[0] ? Point : LinkedPoint)
(pos.x, pos.y, this, 'setPosition');
},
setPosition: function(/* point */) {
// Calculate the distance to the current position, by which to
// translate the item. Pass true for dontLink, as we do not need a
// LinkedPoint to simply calculate this distance.
this.translate(Point.read(arguments).subtract(this.getPosition(true)));
},
/**
* The item's transformation matrix, defining position and dimensions in
* relation to its parent item in which it is contained.
*
* @type Matrix
* @bean
*/
getMatrix: function() {
return this._matrix;
},
setMatrix: function(matrix) {
// Use Matrix#initialize to easily copy over values.
this._matrix.initialize(matrix);
this._changed(/*#=*/ Change.GEOMETRY);
},
/**
* The item's global transformation matrix in relation to the global project
* coordinate space.
*
* @type Matrix
* @bean
*/
getGlobalMatrix: function() {
// TODO: if drawCount is out of sync, we still need to walk up the chain
// and concatenate the matrices.
return this._drawCount === this._project._drawCount
&& this._globalMatrix || null;
},
/**
* Converts the specified point from global project coordinates to local
* coordinates in relation to the the item's own coordinate space.
*
* @param {Point} point the point to be transformed
* @return {Point} the transformed point as a new instance
*/
globalToLocal: function(/* point */) {
var matrix = this.getGlobalMatrix();
return matrix && matrix._transformPoint(Point.read(arguments));
},
/**
* Converts the specified point from local coordinates to global coordinates
* in relation to the the project coordinate space.
*
* @param {Point} point the point to be transformed
* @return {Point} the transformed point as a new instance
*/
localToGlobal: function(/* point */) {
var matrix = this.getGlobalMatrix();
return matrix && matrix._inverseTransform(Point.read(arguments));
},
/**
* Specifies whether the item has any content or not. The meaning of what
* content is differs from type to type. For example, a {@link Group} with
* no children, a {@link TextItem} with no text content and a {@link Path}
* with no segments all are considered empty.
*
* @type Boolean
*/
isEmpty: function() {
return !this._children || this._children.length == 0;
}
}, Base.each(['getBounds', 'getStrokeBounds', 'getHandleBounds', 'getRoughBounds'],
function(name) {
// Produce getters for bounds properties. These handle caching, matrices
// and redirect the call to the private _getBounds, which can be
// overridden by subclasses, see below.
this[name] = function(/* matrix */) {
var getter = this._boundsGetter,
// Allow subclasses to override _boundsGetter if they use
// the same calculations for multiple type of bounds.
// The default is name:
bounds = this._getCachedBounds(typeof getter == 'string'
? getter : getter && getter[name] || name, arguments[0]);
// If we're returning 'bounds', create a LinkedRectangle that uses
// the setBounds() setter to update the Item whenever the bounds are
// changed:
return name === 'getBounds'
? new LinkedRectangle(bounds.x, bounds.y, bounds.width,
bounds.height, this, 'setBounds')
: bounds;
};
},
/** @lends Item# */{
/**
* Private method that deals with the calling of _getBounds, recursive
* matrix concatenation and handles all the complicated caching mechanisms.
*/
_getCachedBounds: function(getter, matrix, cacheItem) {
// See if we can cache these bounds. We only cache the bounds
// transformed with the internally stored _matrix, (the default if no
// matrix is passed).
var cache = (!matrix || matrix.equals(this._matrix)) && getter;
// Set up a boundsCache structure that keeps track of items that keep
// cached bounds that depend on this item. We store this in our parent,
// for multiple reasons:
// The parent receives HIERARCHY change notifications for when its
// children are added or removed and can thus clear the cache, and we
// save a lot of memory, e.g. when grouping 100 items and asking the
// group for its bounds. If stored on the children, we would have 100
// times the same structure.
// Note: This needs to happen before returning cached values, since even
// then, _boundsCache needs to be kept up-to-date.
if (cacheItem && this._parent) {
// Set-up the parent's boundsCache structure if it does not
// exist yet and add the cacheItem to it.
var id = cacheItem._id,
ref = this._parent._boundsCache
= this._parent._boundsCache || {
// Use both a hashtable for ids and an array for the list,
// so we can keep track of items that were added already
ids: {},
list: []
};
if (!ref.ids[id]) {
ref.list.push(cacheItem);
ref.ids[id] = cacheItem;
}
}
if (cache && this._bounds && this._bounds[cache])
return this._bounds[cache].clone();
// If the result of concatinating the passed matrix with our internal
// one is an identity transformation, set it to null for faster
// processing
var identity = this._matrix.isIdentity();
matrix = !matrix || matrix.isIdentity()
? identity ? null : this._matrix
: identity ? matrix : matrix.clone().concatenate(this._matrix);
// If we're caching bounds on this item, pass it on as cacheItem, so the
// children can setup the _boundsCache structures for it.
var bounds = this._getBounds(getter, matrix, cache ? this : cacheItem);
// If we can cache the result, update the _bounds cache structure
// before returning
if (cache) {
if (!this._bounds)
this._bounds = {};
this._bounds[cache] = bounds.clone();
}
return bounds;
},
/**
* Clears cached bounds of all items that the children of this item are
* contributing to. See #_getCachedBounds() for an explanation why this
* information is stored on parents, not the children themselves.
*/
_clearBoundsCache: function() {
if (this._boundsCache) {
for (var i = 0, list = this._boundsCache.list, l = list.length;
i < l; i++) {
var item = list[i];
delete item._bounds;
// We need to recursively call _clearBoundsCache, because if the
// cache for this item's children is not valid anymore, that
// propagates up the DOM tree.
if (item != this && item._boundsCache)
item._clearBoundsCache();
}
delete this._boundsCache;
}
},
/**
* Protected method used in all the bounds getters. It loops through all the
* children, gets their bounds and finds the bounds around all of them.
* Subclasses override it to define calculations for the various required
* bounding types.
*/
_getBounds: function(getter, matrix, cacheItem) {
// Note: We cannot cache these results here, since we do not get
// _changed() notifications here for changing geometry in children.
// But cacheName is used in sub-classes such as PlacedSymbol and Raster.
var children = this._children;
// TODO: What to return if nothing is defined, e.g. empty Groups?
// Scriptographer behaves weirdly then too.
if (!children || children.length == 0)
return new Rectangle();
var x1 = Infinity,
x2 = -x1,
y1 = x1,
y2 = x2;
for (var i = 0, l = children.length; i < l; i++) {
var child = children[i];
if (child._visible && !child.isEmpty()) {
var rect = child._getCachedBounds(getter, matrix, cacheItem);
x1 = Math.min(rect.x, x1);
y1 = Math.min(rect.y, y1);
x2 = Math.max(rect.x + rect.width, x2);
y2 = Math.max(rect.y + rect.height, y2);
}
}
return isFinite(x1)
? new Rectangle(x1, y1, x2 - x1, y2 - y1)
: new Rectangle();
},
setBounds: function(rect) {
rect = Rectangle.read(arguments);
var bounds = this.getBounds(),
matrix = new Matrix(),
center = rect.getCenter();
// Read this from bottom to top:
// Translate to new center:
matrix.translate(center);
// Scale to new Size, if size changes and avoid divisions by 0:
if (rect.width != bounds.width || rect.height != bounds.height) {
matrix.scale(
bounds.width != 0 ? rect.width / bounds.width : 1,
bounds.height != 0 ? rect.height / bounds.height : 1);
}
// Translate to bounds center:
center = bounds.getCenter();
matrix.translate(-center.x, -center.y);
// Now execute the transformation
this.transform(matrix);
}
/**
* The bounding rectangle of the item excluding stroke width.
*
* @name Item#getBounds
* @type Rectangle
* @bean
*/
/**
* The bounding rectangle of the item including stroke width.
*
* @name Item#getStrokeBounds
* @type Rectangle
* @bean
*/