-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path__init__.py
More file actions
3242 lines (2841 loc) · 130 KB
/
Copy path__init__.py
File metadata and controls
3242 lines (2841 loc) · 130 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
### CREDITS ##########################################################################################
# Copyright (c) 2007 Tom De Smedt.
# See LICENSE.txt for details.
__author__ = "Tom De Smedt"
__version__ = "1.9.5"
__copyright__ = "Copyright (c) 2007 Tom De Smedt"
__license__ = "GPL"
from plotdevice import Bezier, Color as PDColor, Image as PDImage
from plotdevice.lib import register
_ctx = register(__name__)
### NODEBOX CORE IMAGE ###############################################################################
# The Core Image library for NodeBox adds image manipulation to NodeBox.
# It's like having control over Photoshop through simple Python programming commands.
# Core Image is a Mac OS X specific framework available from Mac OS X 1.4 (Tiger).
# The library depends on the Cocoa ObjC AppKit and Foundation modules (bundled with NodeBox),
# the Python math module, the Python NumPy module (bundled with NodeBox) for pixel operations,
# the Python Core Graphics module (installed on the Mac by default) for CMYK conversion,
# the nodebox.graphics module for drawing operations in NodeBox.
# However, all of the classes are loosely connected so it probably isn't that much work
# to make the library work in a different environment.
# Different renderers can also "easily" be implemented, for example in PIL.
# The library is currently in alpha stage and has some known issues and limitations,
# check the bottom of the documentation webpage (http://nodebox.net/code/index.php/Core_Image).
# The main issue: exporting image files leaks memory, which can result in kernel panic.
# I haven't found a solution yet, there's a problem when calling CIContext().drawImage.
# For now, don't export movies/PDF's/images in batch or use an external screen capture tool.
### CONSTANTS ########################################################################################
# Layer types.
LAYER_FILE = "file"
LAYER_FILL = "fill"
LAYER_RADIAL_GRADIENT = "radial"
LAYER_LINEAR_GRADIENT = "linear"
LAYER_LAYERS = "layers"
LAYER_PATH = "path"
LAYER_PIXELS = "pixels"
LAYER_CIIMAGEOBJECT = "CIImageobject"
LAYER_NSIMAGEDATA = "NSImageData"
# Layer ordering.
ARRANGE_UP = "up"
ARRANGE_DOWN = "down"
ARRANGE_FRONT = "front"
ARRANGE_BACK = "back"
# Layer transformation point.
ORIGIN_LEFT = "left"
ORIGIN_TOP = "top"
ORIGIN_BOTTOM = "bottom"
ORIGIN_RIGHT = "right"
ORIGIN_CENTER = "center"
# Layer flip modes.
FLIP_HORIZONTAL = "horizontal"
FLIP_VERTICAL = "vertical"
# Layer blend modes.
BLEND_NORMAL = "normal"
BLEND_LIGHTEN = "lighten"
BLEND_DARKEN = "darken"
BLEND_MULTIPLY = "multiply"
BLEND_SCREEN = "screen"
BLEND_OVERLAY = "overlay"
BLEND_SOFTLIGHT = "softlight"
BLEND_HARDLIGHT = "hardlight"
BLEND_DIFFERENCE = "difference"
BLEND_HUE = "hue"
BLEND_COLOR = "color"
# Export formats.
FILE_GIF = ".gif"
FILE_PNG = ".png"
FILE_JPEG = ".jpg"
FILE_TIFF = ".tif"
# Rendering order.
RENDER_OPACITY = "opacity"
RENDER_CROP = "crop"
RENDER_FILTERS = "filters"
RENDER_ADJUSTMENTS = "adjustments"
RENDER_TRANSFORMS = "transforms"
RENDER_MASK = "mask"
# Controls how much extra space to leave between
# the actual path and its bounding box.
PATH_PADDING = 0
# Core Image constants.
from Quartz import kCIFormatARGB8, kCIFormatRGBA16, kCIFormatRGBAf
QUALITY_LOW = "low"
QUALITY_HIGH = "high"
INFINITY = 1e20
### EXCEPTIONS #######################################################################################
class CanvasToNodeBoxError: pass
class CanvasInCanvasRecursionError: pass
### GEOMETRY #########################################################################################
from math import sqrt, pow
from math import sin, cos, atan, pi, radians, degrees
def distance(x0, y0, x1, y1):
return sqrt(pow(x1-x0, 2) + pow(y1-y0, 2))
def angle(x0, y0, x1, y1):
a = degrees( atan((y1-y0) / (x1-x0+0.00001)) ) + 360
if x1-x0 < 0: a += 180
return 360 - a
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
### COLOR ############################################################################################
class Color:
def __init__(self, r, g=None, b=None, a=None):
""" Stores channel values for a color.
If one value is given and it is a Color object, copy that.
If one value is given, create a grayscale color.
If two values are given, create a grayscale color with alpha.
If three values are given, create an opaque color.
"""
try:
is_nodebox_color = isinstance(r, PDColor)
except:
is_nodebox_color = False
# One parameter, a Color object.
if isinstance(r, Color) or is_nodebox_color:
r, g, b, a = r.r, r.g, r.b, r.a
if isinstance(r, (list, tuple)):
if len(r) == 2: r, g = r
elif len(r) == 3: r, g, b = r
elif len(r) == 4: r, g, b, a = r
# No alpha means an opaque color.
if a == None:
a = 1.0
# One parameter, a grayscale value.
if g == None and b == None:
g, b = r, r
# Two parameters, gray value and alpha.
if b == None:
a, g, b = g, r, r
if isinstance(r, int): r = float(r) / 255
if isinstance(g, int): g = float(g) / 255
if isinstance(b, int): b = float(b) / 255
if isinstance(a, int): a = float(a) / 255
self.r = max(0.0, min(r, 1.0))
self.g = max(0.0, min(g, 1.0))
self.b = max(0.0, min(b, 1.0))
self.a = max(0.0, min(a, 1.0))
def __repr__(self):
return "%s(%s, %s, %s, %s)" % (self.__class__.__name__,
self.r, self.g, self.b, self.a)
def color(r=None, g=None, b=None, a=None):
return Color(r, g, b, a)
### TRANSPARENT ######################################################################################
class Transparent(Color):
def __init__(self):
Color.__init__(self, 0.0, 0.0, 0.0, 0.0)
def transparent():
return Transparent()
### PATH #############################################################################################
class Path:
def __init__(self, path):
""" A wrapper for acceptable bezier paths.
Transforms a given path to an NSBezierPath.
Acceptable path parameters are currently:
1) a NodeBox BezierPath which is the handiest format
2) a list of points forming a polygon
3) an NSBezierPath.
"""
self.path = None
# Path from BezierPath.
try:
b = isinstance(path, Bezier)
if b: self.path = path._nsBezierPath
except:
pass
# Path from list of points.
if isinstance(path, list):
p = NSBezierPath.bezierPath()
first = True
for i in range(len(path)/2):
x = path[i*2]
y = path[i*2+1]
if first == True:
p.moveToPoint_((x, y))
first = False
else:
p.lineToPoint_((x, y))
self.path = p
# Path from NSBezierPath.
if isinstance(path, NSBezierPath):
self.path = path
def is_path(self):
return (self.path != None)
### CANVAS ###########################################################################################
from os.path import splitext
class Canvas:
def __init__(self, w, h, renderer):
self.renderer = renderer
self.layers = Layers()
self._parent = None
self.w = w
self.h = h
def copy(self):
canvas = Canvas(self.w, self.h, self.renderer)
canvas._parent = self._parent
for layer in self.layers:
canvas.layers.append(layer.copy())
return canvas
def layer(self, *args, **kwargs):
""" Adds a new layer to the canvas.
A new layer can be created from:
1) layer(str)
2) layer(clr1, clr2, type="linear", spread=0.0)
3) layer(clr)
4) layer(layer)
5) layer(canvas)
6) layer(path, background=None, fill=None, stroke=None, strokewidth=None)
7) layer([clr1, clr2, clr3, ...], w, h)
8) layer(layer.render())
9) layer(canvas.render())
10) layer(NSImage)
11) layer(open(img).read())
12) layer(movieframe)
By default, layers are placed at the center of the canvas.
When a width or height is given for an image file,
the layer will store the original image's width and height and adjust its scaling.
Layers have a default width and height equal to the canvas,
except when given or the source image file has other dimensions.
Always use Canvas.layer() to create new layers as this method
initializes all the layer attributes in the correct way.
"""
x = y = w = h = None
if "x" in kwargs: x = kwargs["x"]
if "y" in kwargs: y = kwargs["y"]
if "w" in kwargs: w = kwargs["w"]
if "h" in kwargs: h = kwargs["h"]
name = ""
type = ""
if "name" in kwargs: name = kwargs["name"]
if "type" in kwargs: type = kwargs["type"]
# Creates a new Layer object in the Canvas.
def _add_layer(data, type, x=None, y=None, w=None, h=None, s=Point(1.0,1.0)):
if x == None: x = self.w/2
if y == None: y = self.h/2
if w == None: w = self.w
if h == None: h = self.h
layer = Layer(self, type, data, x, y, w, h, name)
layer._scale = s
self.layers.append(layer)
return layer
# File: layer(str)
# An image file is a pathname for which the renderer can calculate a size.
# ------------------------------------------------------------------------
try:
w0, h0 = self.renderer.imagesize(args[0])
type = LAYER_FILE
s = Point(1.0, 1.0)
if w != None: s.x = float(w) / w0
if h != None: s.y = float(h) / h0
w, h = w0, h0
return _add_layer(args[0], type, x, y, w, h, s)
except:
pass
# Gradient: layer(clr1, clr2, type="linear", spread=0.0)
# A gradient are two color objects and an optional spread parameter.
# ------------------------------------------------------------------------
try:
r, g, b, a = args[0].r, args[0].g, args[0].b, args[0].a
r, g, b, a = args[1].r, args[1].g, args[1].b, args[1].a
if type == "radial":
type = LAYER_RADIAL_GRADIENT
if "spread" not in kwargs \
or kwargs["spread"] == None:
kwargs["spread"] = 0.0
return _add_layer((args[0], args[1], float(kwargs["spread"])), type, x, y, w, h)
else:
type = LAYER_LINEAR_GRADIENT
return _add_layer((args[0], args[1]), type, x, y, w, h)
except:
pass
# Fill color: layer(clr)
# A fill is a single color object with r, g, b and a properties.
# ------------------------------------------------------------------------
try:
r, g, b, a = args[0].r, args[0].g, args[0].b, args[0].a
type = LAYER_FILL
return _add_layer(args[0], type, x, y, w, h)
except:
pass
# Layer: layer(layer)
# A Layer copied from another canvas.
# ------------------------------------------------------------------------
try:
c, b, f = args[0].canvas, args[0].blendmode, args[0].filters
layer = args[0].copy()
layer.canvas = self
self.layers.append(layer)
return layer
except:
pass
# Canvas: layer(canvas)
# A Canvas is identified by w, h and layers properties.
# ------------------------------------------------------------------------
try:
w0, h0, n = args[0].w, args[0].h, len(args[0].layers)
if args[0] == self: raise CanvasInCanvasRecursionError
type = LAYER_LAYERS
if w == None: w = args[0].w
if h == None: h = args[0].h
return _add_layer(args[0], type, x, y, w, h)
except:
pass
# Path:
# layer(path, background=None, fill=None, stroke=None, strokewidth=None)
# path can be: BezierPath, NSBezierPath, [x1, y1, x2, y2, ...]
# A valid path can be used to initialize a coreimage.Path object.
# ------------------------------------------------------------------------
try:
path = Path(args[0]).path
(dx,dy), (w0,h0) = path.bounds()
type = LAYER_PATH
if x == None: x = self.w/2
if y == None: y = self.h/2
#x += dx
#y += dy
default_fill = Color(0.0)
if self._parent != None and self._parent.mask == self:
default_fill = Color(1.0)
colors = [
kwargs.get("background", Transparent()),
kwargs.get("fill", default_fill),
kwargs.get("stroke", Transparent())
]
for i in range(len(colors)):
clr = colors[i]
if isinstance(clr, int): clr = float(clr)
if isinstance(clr, (list, tuple)):
clr = [float(v) for v in clr]
colors[i] = Color(clr)
background, fill, stroke = colors
strokewidth = kwargs.get("strokewidth", 1.0)
if stroke.a == 0:
strokewidth = 0.0
strokewidth = max(0, strokewidth)
if w == None: w = w0 + strokewidth + PATH_PADDING*2
if h == None: h = h0 + strokewidth + PATH_PADDING*2
return _add_layer((path, background, fill, stroke, strokewidth), type, x, y, w, h)
except:
pass
# Pixels:
# layer([clr1, clr2, clr3, ...], w, h)
# Pixels are passed as a list of color objects and w and h parameters.
# ------------------------------------------------------------------------
try:
r, g, b, a = args[0][0].r, args[0][0].g, args[0][0].b, args[0][0].a
if len(args) >= 2: w = args[1]
if len(args) == 3: h = args[2]
w *= 1
h *= 1
type = LAYER_PIXELS
return _add_layer((args[0], w, h), type, x, y, w, h)
except:
pass
# Core Image CIImage object:
# layer(layer.render())
# layer(canvas.render())
# A CIImage object has an extent() method.
# ----------------------------------------------------------------------
try:
(x0, y0), (w0, h0) = args[0].extent()
type = LAYER_CIIMAGEOBJECT
return _add_layer(args[0], type, x, y, w0, h0)
except:
pass
# TIFF data extracted from Cocoa NSImage object, or byte data:
# layer(NSImage)
# layer(open(img).read())
# layer(movieframe)
# An image byte string can be passed to _ctx.Image() to create an NSImage.
# An NSImage or a movieframe has size() and TIFFRepresentation methods.
# ------------------------------------------------------------------------
try:
try:
img = PDImage(None, data=args[0])
img = img._nsImage
except:
img = args[0]
w0, h0 = img.size()
img = img.TIFFRepresentation()
type = LAYER_NSIMAGEDATA
s = Point(1.0,1.0)
if w != None: s.x = float(w) / w0
if h != None: s.y = float(h) / h0
w, h = w0, h0
return _add_layer(img, type, x, y, w, h, s)
except:
pass
append = layer
def layer_fill(self, clr=None, x=None, y=None, w=None, h=None, name=""):
if clr == None:
clr = Color(0.0)
if self._parent != None and self._parent.mask == self:
clr = Color(1.0)
return self.layer(clr, x=x, y=y, w=w, h=h, name=name)
def layer_gradient(self, clr1=None, clr2=None, type="linear", spread=None, x=None, y=None, w=None, h=None, name=""):
if clr1 == None: clr1 = Color(1.0)
if clr2 == None: clr2 = Color(0.0)
return self.layer(clr1, clr2, type=type, spread=spread, x=x, y=y, w=w, h=h, name=name)
def layer_linear_gradient(self, clr1=None, clr2=None, x=None, y=None, w=None, h=None, name=""):
return self.layer_gradient(clr1, clr2, x=x, y=y, w=w, h=h, name=name)
def layer_radial_gradient(self, clr1=None, clr2=None, spread=0.0, x=None, y=None, w=None, h=None, name=""):
return self.layer_gradient(clr1, clr2, type="radial", spread=spread, x=x, y=y, w=w, h=h, name=name)
def layer_group(self, canvas, x=None, y=None, w=None, h=None, name=""):
return self.layer(canvas, x=x, y=y, w=w, h=h)
def layer_path(self, path, fill=None, background=None, stroke=None, strokewidth=None, x=None, y=None, w=None, h=None, name=""):
return self.layer(path, fill=fill, background=background, stroke=stroke, strokewidth=strokewidth, x=x, y=y, w=w, h=h, name=name)
def layer_pixels(self, colors, w, h, x=None, y=None, name=""):
return self.layer(colors, w, h, x=x, y=y, name=name)
def layer_bytes(self, data, x=None, y=None, w=None, h=None, name=""):
return self.layer(data, x=x, y=y, w=w, h=h, name=name)
fill = add_fill = layer_fill
gradient = add_gradient = layer_gradient
linear = add_linear = layer_linear_gradient
radial = add_radial = layer_radial_gradient
group = add_group = layer_group
path = add_path = layer_path
bytes = add_bytes = layer_bytes
pixels = add_pixels = layer_pixels
def find(self, index):
""" Returns the layer with the given name or index.
Browses the canvas recursively:
if the index is a string, searches layer masks
and composite layers from the given name as well.
"""
return self.layers[index]
def __getitem__(self, index): return self.find(index)
def __getslice__(self, i, j): return self.layers.__getslice__(i, j)
def __getattr__(self, index): return self.layers.__getattr__(index, cls="Canvas")
def __iter__(self): return self.layers.__iter__()
def __len__(self): return len(self.layers)
def _render_shadows(self, layers=[]):
""" A software layer dropshadow renderer.
Each layer in the canvas has a Layer.dropshadow() method.
If the canvas' renderer has no (faster) support for a layer's dropshadow,
creates a copy of the layer, and translates/blackens/blurs it using
the standard layer properties and methods, and then places the shadow underneath the layer.
"""
l = Layers()
if len(layers) == 0:
layers = self.layers
for layer in layers:
if layer.has_shadow:
dx, dy, alpha, blur = layer._shadow
shadow = layer.copy()
shadow.adjust(-1, 0, 0)
shadow.x += dx
shadow.y += dy
shadow.opacity *= alpha
shadow.blur += blur
shadow.blendmode = "multiply"
shadow._shadow = None
l.append(shadow)
l.append(layer)
return l
def render(self, layers=[], fast=True):
""" Returned a rendered version of the canvas.
Flattens the canvas, rendering all the transformed layers.
You can feed the returned object back into a Canvas.layer().
"""
if not self.renderer.can_render_shadows:
layers = self._render_shadows(layers)
return self.renderer.merge(self, layers, fast)
flatten = render
def draw(self, x=0, y=0, layers=[], fast=False, helper=False):
""" Draws the flattened canvas to NodeBox.
Draws the canvas at the given coordinates.
Throws a CanvasToNodeBox error when unable to draw in NodeBox.
"""
if not self.renderer.can_render_shadows:
layers = self._render_shadows(layers)
self.renderer.draw(self, x, y, layers, fast, helper)
def export(self, name, type=FILE_PNG, compression=None, cmyk=False, layers=[]):
""" Exports the flattened canvas to .jpg, .gif, .png or .tif.
"""
if name.endswith(".jpg"): name = name[:-4]; type = FILE_JPEG
if name.endswith(".gif"): name = name[:-4]; type = FILE_GIF
if name.endswith(".png"): name = name[:-4]; type = FILE_PNG
if name.endswith(".tif"): name = name[:-4]; type = FILE_TIFF
if not self.renderer.can_render_shadows:
layers = self._render_shadows(self.layers)
self.renderer.export(self, name+type, type, compression, cmyk, layers)
def export_gif(self, name):
self.renderer.export(self, splitext(name)[0]+".gif", FILE_GIF)
def export_png(self, name):
self.renderer.export(self, splitext(name)[0]+".png", FILE_PNG)
def export_jpg(self, name, quality=1.0):
self.renderer.export(self, splitext(name)[0]+".jpg", FILE_JPEG, quality)
def export_tif(self, name, lzw=False, cmyk=False):
self.renderer.export(self, splitext(name)[0]+".tif", FILE_TIFF, lzw, cmyk)
def canvas(w=None, h=None, renderer=None, quality=None):
from plotdevice.gfx.geometry import Dimension
if not w: w = _ctx.WIDTH
if not h: h = _ctx.HEIGHT
if not renderer: renderer = CoreImageRenderer(quality)
if not isinstance(w, (int, float, Dimension)):
try:
w0, h0 = renderer.imagesize(w)
canvas = Canvas(w0, h0, renderer)
layer = canvas.layer(w)
return canvas
except:
pass
else:
return Canvas(w, h, renderer)
### LAYERS ###########################################################################################
class Layers(list):
def __getitem__(self, index):
""" Extends the canvas.layers[] list so it indexes layers names.
When the index is an integer, returns the layer at that index.
When the index is a string, returns the first layer with that name.
When a layer is a canvas, or when a layer's alpha mask is a canvas, searches recursively.
"""
# Layer by name, recursive.
if isinstance(index, str):
for layer in self:
if layer.name == index:
return layer
if isinstance(layer.data, Canvas):
try: return layer.data.layers[index]
except:
pass
if isinstance(layer.mask, Canvas):
try: return layer.data.layers[index]
except:
pass
raise KeyError(index)
# Layer by index number.
if isinstance(index, int):
return list.__getitem__(self, index)
raise IndexError("list index out of range")
def __getattr__(self, name, cls="Layers"):
""" You can also do: canvas.layers.layer_name (without recursion).
"""
for layer in self:
if layer.name == name:
return layer
# This method is also called from the Canvas object,
# In that case, the cls parameter will be "Canvas".
raise AttributeError(cls+" instance has no attribute '"+name+"'")
### LAYER ############################################################################################
class Layer(object):
def __init__(self, canvas, type, data, x, y, w, h, name=""):
self.canvas = canvas
self.type = type
self.data = data
self.name = name
self.hidden = False
# A layer can be a Canvas.
self.layers = None
if self.type == LAYER_LAYERS:
self.layers = self.data.layers
# Transformations.
self.x = x
self.y = y
self._w = w
self._h = h
self._crop = None
self._origin = Point(0.5, 0.5)
self._flip = (False, False)
self._distort = [Point(0.0, 0.0) for i in range(4)]
self._scale = Point(1.0, 1.0)
self.rotation = 0
# Compositing.
self._opacity = 1.0
self.blendmode = BLEND_NORMAL
# A mask is a grayscale canvas of layers owned by this layer,
# and of the same width and height.
# An alpha mask hides parts of the masked layer
# where the mask is darker.
self.mask = Canvas(self._w, self._h, self.canvas.renderer)
self.mask._parent = self
# Adjustments.
self._brightness = 0.0
self._contrast = 1.0
self._saturation = 1.0
self.inverted = False
# Shadow.
self._shadow = None
# Filters.
self.blur = 0.0
self.sharpness = 0.0
self.filters = []
self._filters_first = True
def _is_file(self) : return (self.type == LAYER_FILE)
def _is_fill(self) : return (self.type == LAYER_FILL)
def _is_gradient(self) : return (self.type == LAYER_LINEAR_GRADIENT or
self.type == LAYER_RADIAL_GRADIENT)
def _is_linear_gradient(self) : return (self.type == LAYER_RADIAL_GRADIENT)
def _is_radial_gradient(self) : return (self.type == LAYER_LINEAR_GRADIENT)
def _is_path(self) : return (self.type == LAYER_PATH)
def _is_pixels(self) : return (self.type == LAYER_PIXELS)
def _has_layers(self) : return (self.type == LAYER_LAYERS)
def _has_shadow(self) : return (self._shadow != None)
def _is_mask(self) : return (self.canvas._parent != None and
self.canvas._parent.mask == self.canvas)
is_file = property(_is_file)
is_fill = property(_is_fill)
is_gradient = property(_is_gradient)
is_linear_gradient = property(_is_linear_gradient)
is_radial_gradient = property(_is_radial_gradient)
is_linear = property(_is_linear_gradient)
is_radial = property(_is_radial_gradient)
is_path = property(_is_path)
is_pixels = property(_is_pixels)
is_group = property(_has_layers)
is_canvas = property(_has_layers)
has_layers = property(_has_layers)
has_shadow = property(_has_shadow)
is_mask = property(_is_mask)
def _index(self):
""" Returns this layer's index in the canvas.layers[].
Searches the position of this layer in the canvas' layers, return None when not found.
"""
if self.canvas == None:
return None
return self.canvas.layers.index(self)
index = property(_index)
def arrange(self, where):
""" Moves the layer either forwards or backwards.
"""
i = self._index()
j = None
if where == ARRANGE_UP : j = i+1
if where == ARRANGE_DOWN : j = i-1
if where == ARRANGE_FRONT : j = len(self.canvas.layers)
if where == ARRANGE_BACK : j = 0
if j != None:
del self.canvas.layers[i]
j = max(0, min(j, len(self.canvas.layers)))
self.canvas.layers.insert(j, self)
return j
def arrange_up(self) : return self.arrange(ARRANGE_UP)
def arrange_down(self) : return self.arrange(ARRANGE_DOWN)
def arrange_front(self) : return self.arrange(ARRANGE_FRONT)
def arrange_back(self) : return self.arrange(ARRANGE_BACK)
up, down = arrange_up, arrange_down
to_front, to_back = arrange_front, arrange_back
def hide(self):
""" Hides the layer from the output.
This is different than a completely transparent layer,
which is rendered and might have sublayers that will also be rendered.
A hidden layer is never rendered.
"""
self.hidden = True
def copy(self):
""" Creates a copy of the layer.
Creates and returns deep copy of the layer.
This means for example that the layers in the mask are recursively copied,
that new copies are made of colors in the gradient.
"""
# Determine the type of layer and copy image data.
if self.type == LAYER_FILE:
data = self.data
if self.type == LAYER_FILL:
data = Color(self.data)
if self.type == LAYER_LINEAR_GRADIENT:
data = (Color(self.data[0]), Color(self.data[1]))
if self.type == LAYER_RADIAL_GRADIENT:
data = (Color(self.data[0]), Color(self.data[1]), self.data[2])
if self.type == LAYER_LAYERS:
data = self.data.copy()
if self.type == LAYER_PATH:
data = (self.data[0].copy(), Color(self.data[1]), Color(self.data[2]), Color(self.data[3]), self.data[4])
if self.type == LAYER_PIXELS:
data = self.data
if self.type == LAYER_CIIMAGEOBJECT:
data = self.data
if self.type == LAYER_NSIMAGEDATA:
data = self.data
layer = Layer(self.canvas, self.type, data, self.x, self.y, self._w, self._h)
# Transformations.
layer._origin = Point(self._origin.x, self._origin.y)
layer._flip = self._flip
layer._distort = [Point(self._distort[i].x, self._distort[i].y) for i in range(4)]
layer._scale = Point(self._scale.x, self._scale.y)
layer.rotation = self.rotation
# Compositing.
layer._opacity = self._opacity
layer.blendmode = self.blendmode
# Alpha mask.
layer.mask = self.mask.copy()
layer.mask._parent = layer
# Adjustments.
layer._brightness = self._brightness
layer._contrast = self._contrast
layer._saturation = self._saturation
layer.inverted = self.inverted
# Shadow.
layer._shadow = self._shadow
# Filters.
layer.blur = self.blur
layer.sharpness = self.sharpness
layer.filters = [(filter, params) for filter, params in self.filters]
return layer
def duplicate(self):
""" Adds a copy of the layer on top of this one.
Creates a copy of this layer,
appends it to the canvas right above this layer,
and returns the index of the new layer.
"""
i = self._index()
layer = self.copy()
self.canvas.layers.insert(i+1, layer)
return layer
def origin(self, x=None, y=None):
""" Sets the transformation origin point.
The origin point is the layer's anchor/pivot/orbit:
it is placed at x and y and is the point
around which the layer rotates,
and from which the layer scales and flips.
"""
def f(s):
if s == ORIGIN_LEFT : return 0.0
if s == ORIGIN_TOP : return 0.0
if s == ORIGIN_RIGHT : return 1.0
if s == ORIGIN_BOTTOM : return 1.0
if s == ORIGIN_CENTER : return 0.5
return s
x = f(x)
y = f(y)
if y == None: y = x
if isinstance(x, int): x = float(x) / self._w
if isinstance(y, int): y = float(y) / self._h
if isinstance(x, float): self._origin.x = x
if isinstance(y, float): self._origin.y = y
return (self._origin.x, self._origin.y)
def origin_top_left(self) : return self.origin(ORIGIN_LEFT , ORIGIN_TOP)
def origin_top_right(self) : return self.origin(ORIGIN_RIGHT , ORIGIN_TOP)
def origin_top_center(self) : return self.origin(ORIGIN_CENTER , ORIGIN_TOP)
def origin_bottom_left(self) : return self.origin(ORIGIN_LEFT , ORIGIN_BOTTOM)
def origin_bottom_right(self) : return self.origin(ORIGIN_RIGHT , ORIGIN_BOTTOM)
def origin_bottom_center(self) : return self.origin(ORIGIN_CENTER , ORIGIN_BOTTOM)
def origin_left_center(self) : return self.origin(ORIGIN_LEFT , ORIGIN_CENTER)
def origin_right_center(self) : return self.origin(ORIGIN_RIGHT , ORIGIN_CENTER)
def origin_center(self) : return self.origin(ORIGIN_CENTER , ORIGIN_CENTER)
def bounds(self):
""" Returns the left, top, right, bottom in pixels.
Calculates the layer's bounding box based on its original size and position
modified by its scaling, rotation and origin point.
Gets the coordinates of the corner points to calculate maximum extent.
This method is also handy to check if the renderer
is handling layer transformations correctly.
When the canvas is scaled, we need to multiply left and right
by the canvas horizontal scaling,
and top and bottom by the canvas vertical scaling to have the
correct bounds for display purposes (but not so for editing).
"""
if isinstance(self.canvas._parent, Layer):
return self.canvas._parent.bounds()
x, y, w, h = self.x, self.y, self._w, self._h
# Crop.
if self._crop != None:
w = min(w, self._crop[2])
h = min(h, self._crop[3])
# Scale.
w = w * self._scale.x
h = h * self._scale.y
# Origin.
ox = x + self._origin.x * w
oy = y + self._origin.y * h
# Rotate and distort.
l = t = float( INFINITY)
r = b = float(-INFINITY)
corners = [(x, y), (x+w, y), (x+w, y+h), (x, y+h)]
for i in range(len(corners)):
dx, dy = corners[i]
dx += self._distort[i].x * w
dy += self._distort[i].y * h
a = self.rotation - angle(ox, oy, dx, dy)
d = distance(ox, oy, dx, dy)
dx = x + d * cos(radians(a))
dy = y + d * sin(radians(a))
l = min(l, dx)
r = max(r, dx)
t = min(t, dy)
b = max(b, dy)
return (l, t, r, b)
def size(self):
""" Returns the layer's size.
Returns the width and height of the layer after it has been rotated and scaled
(whereas the base width and height properties contain the size of the layer's data).
"""
l, t, r, b = self.bounds()
return (r-l, b-t)
def _get_w(self): return self.size()[0]
def _get_h(self): return self.size()[1]
w = width = property(_get_w)
h = height = property(_get_h)
def center(self):
""" Puts the origin point of the layer at the center of the canvas.
"""
self.x = self.canvas.w/2
self.y = self.canvas.h/2
def translate(self, x, y):
""" Places the layer at the given position.
The width and height can be supplied as coordinates relative to the canvas size
(between 0.0 and 1.0), or as absolute coordinates in pixels.
"""
if isinstance(x, float): x = x * self.canvas.w
if isinstance(y, float): y = y * self.canvas.h
self.x = x
self.y = y
def scale(self, w=None, h=None):
""" Scales the layer horizontally and vertically.
The width and height can be supplied as relative coordinates (between 0.0 and 1.0),
or as absolute coordinates in pixels.
If only parameter is supplied, scales the layer proportionally.
"""
if w != None and h == None:
if isinstance(w, float): h = w
else: h = int( float(w) / self._w * self._h )
if h != None and w == None:
if isinstance(h, float): w = h
else: w = int( float(h) * self._w / self._h )
if isinstance(w, float):
self._scale.x = w
if isinstance(h, float):
self._scale.y = h
if isinstance(w, int):
self._scale.x = float(w) / self._w
if isinstance(h, int):
self._scale.y = float(h) / self._h
return (self._scale.x, self._scale.y)
def rotate(self, degrees):
""" Sets the layer's angle to the given degrees.
"""
self.rotation = degrees
def flip(self, horizontal=False, vertical=False):
""" Flips the layer horizontally or vertically.
"""
if horizontal == True or horizontal in ("h", "horizontal"):
self.flip_horizontal()
if vertical == True or horizontal in ("v", "vertical"):
self.flip_vertical()
return self._flip
def flip_horizontal(self):
fx, fy = self._flip
self._flip = (not fx, fy)
def flip_vertical(self):
fx, fy = self._flip
self._flip = (fx, not fy)
def distort(self, dx0=0.0, dy0=0.0, dx1=0.0, dy1=0.0, dx2=0.0, dy2=0.0, dx3=0.0, dy3=0.0):
""" Distorts the layer by moving its corner points.
The given coordinates can be either relative to the corner positions
(between 0.0 and 1.0), or absolute in pixels.
"""
self._distort = [
Point(dx0, dy0),
Point(dx1, dy1),
Point(dx2, dy2),
Point(dx3, dy3)
]
for pt in self._distort:
if isinstance(pt.x, int):
pt.x = float(pt.x) / self._w
if isinstance(pt.y, int):