/
beetools.py
2489 lines (1916 loc) · 75.9 KB
/
beetools.py
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
# Beedraw/Hive network capable client and server allowing collaboration on a single image
# Copyright (C) 2009 Thomas Becker
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import PyQt4.QtGui as qtgui
import PyQt4.QtCore as qtcore
import math
import sys
import ImageChops
import ImageFilter
import numpy
import qimage2ndarray
from beeutil import *
from beetypes import *
from beeeventstack import *
from ImageQt import ImageQt
from PencilOptionsWidgetUi import *
from BrushOptionsWidgetUi import *
from SmudgeOptionsWidgetUi import *
from BlurOptionsWidgetUi import *
from EraserOptionsWidgetUi import *
from PaintBucketOptionsWidgetUi import *
from FeatherSelectOptionsWidgetUi import *
from SelectionModificationWidgetUi import *
from beeapp import BeeApp
from beelayer import BeeTemporaryLayer, BeeTemporaryLayerPIL
from scipy.ndimage.filters import gaussian_filter1d, gaussian_filter
try:
import NumPy as numpy
except:
try:
import numpy
except:
import Numeric as numpy
# Class to manage tools and make instances as needed
class BeeToolBox:
def __init__(self):
self.toolslist=[]
self.loadDefaultTools()
self.curtoolindex=0
def loadDefaultTools(self):
self.toolslist.append(PencilToolDesc())
self.toolslist.append(SketchToolDesc())
self.toolslist.append(EraserToolDesc())
self.toolslist.append(RectSelectionToolDesc())
self.toolslist.append(EyeDropperToolDesc())
self.toolslist.append(FeatherSelectToolDesc())
self.toolslist.append(PaintBucketToolDesc())
self.toolslist.append(MoveSelectionToolDesc())
self.toolslist.append(SmudgeToolDesc())
self.toolslist.append(BlurToolDesc())
#self.toolslist.append(SmearToolDesc())
def getCurToolDesc(self):
return self.toolslist[self.curtoolindex]
def setCurToolIndex(self,index):
self.curtoolindex=index
def setCurToolByName(self,name):
for i in range(len(self.toolslist)):
if name==self.toolslist[i].name:
self.curtoolindex=i
return True
return False
def getToolDescByName(self,name):
for tool in self.toolslist:
if name==tool.name:
return tool
print_debug("Error, toolbox couldn't find tool with name: %s" % name)
return None
# Widget class to display a monochrome preview of a brush
class BrushPreviewWidget(qtgui.QWidget):
def __init__(self,replacingwidget,brushimage=None,opacity=0):
qtgui.QWidget.__init__(self,replacingwidget.parentWidget())
replaceWidget(replacingwidget,self)
self.updateBrush(brushimage,opacity)
def updateBrush(self,brushimage,opacity):
self.brushimage=brushimage
self.opacity=opacity
self.setFixedSize(brushimage.size())
self.update()
def paintEvent(self,event):
rect = self.contentsRect()
painter = qtgui.QPainter()
painter.begin(self)
painter.fillRect(rect,qtgui.QColor(255,255,255))
painter.setOpacity(self.opacity)
painter.drawImage(qtcore.QPoint(rect.x(),rect.y()),self.brushimage)
# Base class for a class to describe all tools and spawn tool instances
class AbstractToolDesc:
def __init__(self,name):
self.clippath=None
self.options={}
self.name=name
self.displayname=name
self.setDefaultOptions()
self.optionswidget=None
def pressToolButton(self):
pass
def getCursor(self):
return qtcore.Qt.ArrowCursor
def getDownCursor(self):
return qtcore.Qt.ArrowCursor
def setDefaultOptions(self):
pass
def getOptionsWidget(self,parent=None):
return qtgui.QWidget(parent)
def newModKeys(self,modkeys):
pass
# called when a change in the options for the tool cause the look to be different in such a way it needs to update other internal variables
def updateBrush(self):
pass
# setup needed parts of tool using knowledge of current window
# this should be implemented in subclass if needed
def setupTool(self,window,layerkey):
return None
# what to do when this tool is no longer active
def deactivate(self):
pass
# base class for all drawing tools
class AbstractTool:
logtype=ToolLogTypes.unlogable
allowedonfloating=False
def __init__(self,options,window):
self.fgcolor=None
self.bgcolor=None
self.clippath=None
self.options=options
self.window=window
self.layer=None
self.layerkey=None
self.prevpointshistory=[]
self.pointshistory=[]
# these are expected to get set if a tool is set to do raw logging
self.oldstate=None
self.changedarea=None
# some things are better handled in the GUI thread (ability to use pixmaps) so if needed put it in this function
# also anything that doesn't go out to remote sessions can be put here, such as selection controls.
def guiLevelPenDown(self,x,y,pressure,modkeys=qtcore.Qt.NoModifier):
pass
def guiLevelPenMotion(self,x,y,pressure,modkeys=qtcore.Qt.NoModifier):
pass
def guiLevelPenUp(self,x,y,modkeys=qtcore.Qt.NoModifier):
pass
def newModKeys(self,modkeys):
pass
def setOption(self,key,value):
self.options[key]=value
# what to do when pen is down to be implemented in subclasses
def penDown(self,x,y,pressure):
pass
def penMotion(self,x,y,pressure):
pass
def penUp(self,x=None,y=None,source=0):
pass
def penLeave(self):
pass
def penEnter(self):
pass
def cleanUp(self):
pass
class EyeDropperToolDesc(AbstractToolDesc):
def __init__(self):
AbstractToolDesc.__init__(self,"eyedropper")
self.displayname="Eye Dropper"
def setDefaultOptions(self):
# option for if it should get color for a single layer or the whole visible image
# curently this is set to just the whole visible image because otherwise for transparent colors it composes them onto black which doesn't look right at all
self.options["singlelayer"]=0
def pressToolButton(self):
BeeApp().master.toolselectwindow.ui.eye_dropper_button.setChecked(True)
def setupTool(self,window,layerkey):
tool=EyeDropperTool(self.options,window)
tool.name=self.name
return tool
# eye dropper tool (select color from canvas)
class EyeDropperTool(AbstractTool):
def __init__(self,options,window):
AbstractTool.__init__(self,options,window)
self.name="Eye Dropper"
def guiLevelPenDown(self,x,y,pressure,modkeys=qtcore.Qt.NoModifier):
if self.options["singlelayer"]==0:
color=self.window.getImagePixelColor(x,y)
else:
color=self.window.getCurLayerPixelColor(x,y)
self.window.master.setFGColor(qtgui.QColor(color))
# basic tool for everything that draws points on the canvas
class DrawingTool(AbstractTool):
def __init__(self,options,window):
AbstractTool.__init__(self,options,window)
self.name="pencil"
self.lastpressure=-1
self.compmode=qtgui.QPainter.CompositionMode_SourceOver
self.stampmode=qtgui.QPainter.CompositionMode_SourceOver
self.layer=None
self.pendown=False
self.fullsizedbrush=None
self.inside=True
self.returning=False
self.returnpoint=None
self.logtype=ToolLogTypes.regular
self.brushimageformat=BrushImageFormats.qt
def guiLevelPenDown(self,x,y,pressure,modkeys=qtcore.Qt.NoModifier):
""" guiLevelPenDown method of DrawingTool, if control key is pressed then do a color pick operation and flag the tool as not in drawing mode """
if modkeys==qtcore.Qt.ControlModifier:
color=self.window.getImagePixelColor(x,y)
self.window.master.setFGColor(qtgui.QColor(color))
self.logtype=ToolLogTypes.unlogable
else:
# this must be done here because adding items to the graphics scene must be performed in the GUI thread
self.parentlayer=self.window.getLayerForKey(self.layerkey)
if self.parentlayer:
if self.brushimageformat==BrushImageFormats.qt:
self.layer=self.parentlayer.getTmpLayer(self.options["opacity"]/100.,self.compmode)
else:
self.layer=self.parentlayer.getTmpLayerPIL(self.options["opacity"]/100.,self.compmode,self.clippath)
else:
self.logtype=ToolLogTypes.unlogable
def calculateCloseEdgePoint(self,p1,p2):
""" Stub for now, eventually I'd like this algorithm to take over if the other one encounters data that looks bad """
return p2
def curBrushSize(self):
if self.brushimageformat==BrushImageFormats.pil:
return self.brushimage.size
else:
return self.brushimage.width(),self.brushimage.height()
def calculateEdgePoint(self,p1,p2):
""" Calculate where a continuation of two points would have left the canvas, does this by simply creating a line out of the points and looking for where the line crosses the visable area of the canvas"""
# don't worry about this if it isn't a local layer
if not self.window.localLayer(self.layerkey):
return None
rect=self.window.view.getVisibleImageRect()
leftedge=rect.x()
topedge=rect.y()
rightedge=leftedge+rect.width()
bottomedge=topedge+rect.height()
# factor to go past the edge so the line seems to go all the way instead of stopping short
brushsize=self.curBrushSize()
edgefudge=brushsize[0]/2
leftedge-=edgefudge
topedge-=edgefudge
rightedge+=edgefudge
bottomedge+=edgefudge
exitpoint=None
dx=float(p2[0])-float(p1[0])
dy=float(p2[1])-float(p1[1])
# shouldn't ever get this as input, but just in case
if dx==0 and dy==0:
return None
# special case for going parallel to a side
if dx==0 or dy==0:
m=None
if dx==0:
if dy<0:
exitpoint=(p1[0],topedge)
else:
exitpoint=(p1[0],bottomedge)
if dy==0:
if dx<0:
exitpoint=(leftedge,p1[1])
else:
exitpoint=(rightedge,p1[1])
else:
# calculate slope
m=dy/dx
# calculate line offset
b=p1[1]-(m*p1[0])
sides_to_check=[]
if dy<0:
sides_to_check.append("top")
elif dy>0:
sides_to_check.append("bottom")
if dx<0:
sides_to_check.append("left")
elif dx>0:
sides_to_check.append("right")
for side in sides_to_check:
if side=="top":
x,y=findLineIntersection(-m,1,b,0,1,topedge)
if x>leftedge and x<rightedge:
exitpoint=(x,y)
elif side=="bottom":
x,y=findLineIntersection(-m,1,b,0,1,bottomedge)
if x>leftedge and x<rightedge:
exitpoint=(x,y)
elif side=="right":
x,y=findLineIntersection(-m,1,b,1,0,rightedge)
if y>topedge and y<bottomedge:
exitpoint=(x,y)
elif side=="left":
x,y=findLineIntersection(-m,1,b,1,0,leftedge)
if y>topedge and y<bottomedge:
exitpoint=(x,y)
pointdistance=distance2d(p1[0],p1[1],p2[0],p2[1])
edgedistance=distance2d(p2[0],p2[1],exitpoint[0],exitpoint[1])
#print "last two points:", p1, p2
#print "calculating edge point:", exitpoint
#print "point distance, edge distance:", pointdistance, edgedistance
# figure out if the calculated end point looks bad
# right now the only easy to detect case is when the line is parallel to one edge
if not m:
exitpoint=self.calculateCloseEdgePoint(p1,p2)
return exitpoint
def calculateEdgePressure(self,p1,p2,pexit):
""" method of DrawingTool """
last_distance=distance2d(p1[0],p1[1],p2[0],p2[1])
end_distance=distance2d(p2[0],p2[1],pexit[0],pexit[1])
pressure_trend=p2[2]-p1[2]
new_pressure=p2[2]+(pressure_trend*end_distance/last_distance)
if new_pressure>1:
new_pressure=1
elif new_pressure<0:
new_pressure=0
return new_pressure
def penLeave(self):
""" method of DrawingTool """
#print "Got penLeave"
if self.pendown:
# the leave point can only be calculated if there are multiple points in the current history
if self.pointshistory and len(self.pointshistory) > 1:
exitpoint=self.calculateEdgePoint(self.pointshistory[-2],self.pointshistory[-1])
if exitpoint:
exitpressure=self.calculateEdgePressure(self.pointshistory[-2],self.pointshistory[-1],exitpoint)
#print "Exit point:",exitpoint,exitpressure
self.continueLine(exitpoint[0],exitpoint[1],exitpressure)
self.inside=False
self.returning=False
def penEnter(self):
""" method of DrawingTool """
if self.logtype==ToolLogTypes.unlogable:
return
#print "Got penEnter"
if self.pendown:
self.returning=True
self.inside=True
def updateBrushForPressure(self,pressure,pixelx=0,pixely=0):
""" method of DrawingTool """
# see if we need to update at all
if self.lastpressure==pressure:
return
self.lastpressure=pressure
# if we can use the full sized brush do it
if self.options["pressuresize"]==0 or pressure==1:
self.brushimage=self.fullsizedbrush
self.lastpressure=1
return
# scaled size for brush
bdiameter=self.scaleForPressure(pressure)*self.options["maxdiameter"]
self.diameter=int(math.ceil(bdiameter))
# make target size an odd number
if self.diameter%2==0:
self.diameter+=1
# calculate offset into target
targetoffsetx=((self.diameter-bdiameter)/2.)-.5+(pixelx%1)
targetoffsety=((self.diameter-bdiameter)/2.)-.5+(pixely%1)
# bounding radius for pixels to update
side=self.diameter
fullsizedrect=qtcore.QRectF(0,0,self.fullsizedbrush.width(),self.fullsizedbrush.height())
cursizerect=qtcore.QRectF(targetoffsetx,targetoffsety,bdiameter,bdiameter)
self.brushimage=qtgui.QImage(side,side,qtgui.QImage.Format_ARGB32_Premultiplied)
self.brushimage.fill(0)
painter=qtgui.QPainter()
painter.begin(self.brushimage)
painter.drawImage(cursizerect,self.fullsizedbrush,fullsizedrect)
painter.end()
# make sure brush isn't blank by pasting the brush color onto the center pixel
center=int(self.diameter/2)
self.brushimage.setPixel(center,center,self.fgcolor)
def penDown(self,x,y,pressure):
""" penDown method of DrawingTool """
if self.logtype==ToolLogTypes.unlogable:
return
#print "========================================"
#print "penDown:",x,y,pressure
self.returning=False
self.inside=True
self.pendown=True
self.startLine(x,y,pressure)
# determine if it's moved far enough that we care
def movedFarEnough(self,x,y):
""" method of DrawingTool """
if int(x)==int(self.lastpoint[0]) and int(y)==int(self.lastpoint[1]):
return False
return True
# return how much to scale down the brush for the current pressure
def scaleForPressure(self,pressure):
""" method of DrawingTool """
minsize=self.options["mindiameter"]
maxsize=self.options["maxdiameter"]
sizediff=maxsize-minsize
scale=((sizediff*pressure) + minsize)/maxsize
return scale
def getFullSizedBrushWidth(self):
""" method of DrawingTool """
return self.fullsizedbrush.width()
# since windows apparently won't catch return and leave events when the button is pressed down I'm forced to do this
def checkForPenBounds(self,x,y):
""" method of DrawingTool """
if not self.pendown:
return
# only needed if this is a local layer
if not self.window.localLayer(self.layerkey):
return
rect=self.window.view.getVisibleImageRect()
inside=rect.contains(qtcore.QPointF(x,y))
if inside and not self.inside:
self.penEnter()
if not inside and self.inside:
self.penLeave()
def penMotion(self,x,y,pressure):
""" method of DrawingTool """
#print "penMotion:",x,y,pressure
self.checkForPenBounds(x,y)
if not self.pendown or not self.inside:
return
if self.returning:
#print "detected pen return"
if not self.returnpoint:
self.returnpoint=(x,y,pressure)
return
self.returning=False
enterpoint=self.calculateEdgePoint((x,y,pressure),self.returnpoint)
if enterpoint:
enterpressure=self.calculateEdgePressure((x,y,pressure),self.returnpoint,enterpoint)
self.startLine(enterpoint[0],enterpoint[1],enterpressure)
self.penMotion(self.returnpoint[0],self.returnpoint[1],self.returnpoint[2])
else:
self.startLine(self.returnpoint[0],self.returnpoint[1],self.returnpoint[2])
self.penMotion(x,y,pressure)
self.returnpoint=None
return
self.continueLine(x,y,pressure)
def continueLine(self,x,y,pressure):
""" method of DrawingTool """
# if it hasn't moved just do nothing
if not self.movedFarEnough(x,y):
return
#print "starting new line"
self.pointshistory.append((x,y,pressure))
# get size of layer
layerwidth=self.window.docwidth
layerheight=self.window.docheight
# get points inbetween according to step option and layer size
path=getPointsPath(self.lastpoint[0],self.lastpoint[1],x,y,self.options['step'],layerwidth,layerheight,self.lastpressure,pressure)
# if no points are on the layer just return
if len(path)==0:
return
# figure out the maximum radius the brush will have
maxradius=int(math.ceil(self.getFullSizedBrushWidth()/2.0))
#print "maxradius:", maxradius
#print "path:", path
# calculate the bounding rect for this operation
left=int(math.floor(min(path[0][0],path[-1][0])-maxradius)-1)
top=int(math.floor(min(path[0][1],path[-1][1])-maxradius)-1)
right=int(math.ceil(max(path[0][0],path[-1][0])+maxradius)+1)
bottom=int(math.ceil(max(path[0][1],path[-1][1])+maxradius)+1)
left=max(0,left)
top=max(0,top)
right=min(layerwidth,right)
bottom=min(layerheight,bottom)
# calulate area needed to hold everything
width=right-left
height=bottom-top
if self.brushimageformat==BrushImageFormats.qt:
# then make an image for that bounding rect
#lineimage=qtgui.QImage(width,height,qtgui.QImage.Format_ARGB32_Premultiplied)
#lineimage.fill(0)
# put points in that image
#painter=qtgui.QPainter()
#painter.begin(lineimage)
#painter.setRenderHint(qtgui.QPainter.HighQualityAntialiasing)
for point in path:
self.updateBrushForPressure(point[2],point[0],point[1])
xradius=self.brushimage.width()/2
yradius=self.brushimage.height()/2
pointx=point[0]
pointy=point[1]
stampx=pointx-left-xradius
stampy=pointy-top-yradius
stampx=int(stampx)
stampy=int(stampy)
if self.brushimage.width()%2==0:
if pointx%1<.5:
stampx-=1
if pointy%1<.5:
stampy-=1
#print "stamping at point:", stampx, stampy
#printImage(self.brushimage)
#painter.drawImage(stampx,stampy,self.brushimage)
self.addImageToLayer(self.brushimage,pointx-xradius,pointy-yradius,refresh=False)
#painter.end()
#print "stamping line image:"
#printImage(lineimage)
else:
for point in path:
self.updateBrushForPressure(point[2],point[0],point[1])
brushwidth=self.brushimage.size[0]
brushheight=self.brushimage.size[1]
xradius=brushwidth/2
yradius=brushheight/2
pointx=point[0]
pointy=point[1]
self.addImageToLayer(self.brushimage,pointx-xradius,pointy-yradius,refresh=False)
#self.layer.update(refresharea)
refresharea=qtcore.QRectF(left,top,width,height)
self.layer.updateScene(refresharea)
#self.layer.scene().update(refresharea)
#self.layer.compositeFromCenter(lineimage,left,top,self.stampmode,self.clippath)
#self.addImageToLayer(lineimage,left,top)
self.lastpoint=(path[-1][0],path[-1][1])
def addImageToLayer(self,image,left,top,refresh=True,stampmode=None):
if not self.layer:
# this should only happen if we are in a server drawing thread when using a tool that creates a temporary layer. In that case the layer isn't already created, so create something to use as a temporary layer now.
self.parentlayer=self.window.getLayerForKey(self.layerkey)
if self.brushimageformat==BrushImageFormats.qt:
self.layer=self.parentlayer.getTmpLayer(self.options["opacity"]/100.,self.compmode)
else:
self.layer=self.parentlayer.getTmpLayerPIL(self.options["opacity"]/100.,self.compmode,self.clippath)
if not stampmode:
stampmode=self.stampmode
#print "compositing image into layer:"
#printImage(image)
self.layer.compositeFromCorner(image,left,top,stampmode,self.clippath, refreshimage=refresh)
def startLine(self,x,y,pressure):
""" method of DrawingTool """
if self.pointshistory:
self.prevpointshistory.append(self.pointshistory)
self.pointshistory=[(x,y,pressure)]
self.lastpoint=(x,y)
self.updateBrushForPressure(pressure,x,y)
if self.brushimageformat==BrushImageFormats.qt:
brushwidth=self.brushimage.width()
brushheight=self.brushimage.height()
else:
brushwidth=self.brushimage.size[0]
brushheight=self.brushimage.size[1]
targetx=int(x)-int(brushwidth/2)
targety=int(y)-int(brushheight/2)
# if this is an even number then do adjustments for the center if needed
if brushwidth%2==0:
#print "this is an even sized brush:"
if x%1>.5:
targetx+=1
if y%1>.5:
targety+=1
#self.layer.compositeFromCorner(self.brushimage,targetx,targety,self.stampmode,self.clippath)
self.addImageToLayer(self.brushimage,targetx,targety)
def cleanupTmpLayer(self):
self.oldlayerimage=self.parentlayer.getImageCopy()
parentimagelock=qtcore.QWriteLocker(self.parentlayer.imagelock)
if self.brushimageformat==BrushImageFormats.qt:
tmplayerimage=self.layer.getImageCopy()
else:
tmplayerimage=PilToQImage(self.layer.pilimage)
self.layer.removeFromScene()
#self.layer.setParentItem(None)
#self.window.scene.removeItem(self.layer)
self.parentlayer.compositeFromCorner(tmplayerimage,0,0,self.layer.compmode,opacity=self.layer.getOpacity(),lock=parentimagelock,clippath=self.clippath)
parentimagelock.unlock()
#self.window.scene.update()
self.layer.updateScene()
def penUp(self,x=None,y=None):
""" penUp method of DrawingTool class """
#print "Got penUp"
self.pendown=False
if not self.pointshistory:
return
self.cleanupTmpLayer()
radius=int(math.ceil(self.options["maxdiameter"]))
# get maximum bounds of whole brush stroke
left=self.pointshistory[0][0]
right=self.pointshistory[0][0]
top=self.pointshistory[0][1]
bottom=self.pointshistory[0][1]
for line in self.prevpointshistory:
for point in line:
if point[0]<left:
left=point[0]
elif point[0]>right:
right=point[0]
if point[1]<top:
top=point[1]
elif point[1]>bottom:
bottom=point[1]
for point in self.pointshistory:
if point[0]<left:
left=point[0]
elif point[0]>right:
right=point[0]
if point[1]<top:
top=point[1]
elif point[1]>bottom:
bottom=point[1]
# calculate bounding area of whole event
self.changedarea=qtcore.QRect(left-radius,top-radius,right+(radius*2),bottom+(radius*2))
# bound it by the area of the layer
self.changedarea=rectIntersectBoundingRect(self.changedarea,self.layer.getImageRect())
# get image of what area looked like before
oldimage=self.oldlayerimage.copy(self.changedarea)
command=DrawingCommand(self.layerkey,oldimage,self.changedarea)
self.window.addCommandToHistory(command,self.getOwner())
BeeApp().master.refreshLayerThumb(self.window.id,self.layerkey)
def getOwner(self):
return self.parentlayer.owner
# this is the most basic drawing tool
class PencilToolDesc(AbstractToolDesc):
def __init__(self):
AbstractToolDesc.__init__(self,"pencil")
self.displayname="Pencil"
self.updateBrush()
def updateBrush(self):
self.makeFullSizedBrush()
widget = self.getOptionsWidget()
if widget:
widget.ui.brushpreviewwidget.updateBrush(self.fullsizedbrush,self.options["opacity"]/100.)
def getCursor(self):
return qtcore.Qt.CrossCursor
def getDownCursor(self):
return getBlankCursor()
def setDefaultOptions(self):
self.options["maxdiameter"]=21
self.options["mindiameter"]=0
self.options["step"]=1
self.options["pressuresize"]=1
self.options["pressurebalance"]=100
self.options["opacity"]=100
def pressToolButton(self):
BeeApp().master.toolselectwindow.ui.pencil_button.setChecked(True)
def setupTool(self,window,layerkey):
tool=DrawingTool(self.options,window)
tool.name=self.name
# setup fullsized brush
width=self.diameter
height=self.diameter
coloredfullbrush=qtgui.QImage(width,height,qtgui.QImage.Format_ARGB32_Premultiplied)
coloredfullbrush.fill(BeeApp().master.getFGColor().rgba())
painter = qtgui.QPainter()
painter.begin(coloredfullbrush)
painter.setCompositionMode(qtgui.QPainter.CompositionMode_DestinationIn)
painter.drawImage(qtcore.QPoint(0,0),self.fullsizedbrush)
painter.end()
tool.fullsizedbrush=coloredfullbrush
tool.fgcolor=BeeApp().master.getFGColor().rgba()
tool.layerkey=layerkey
# if there is a selection get a copy of it
tool.clippath=window.getClipPathCopy()
return tool
def makeFullSizedBrush(self):
""" method of DrawingToolDesc """
colortuple=(0,0,0,255)
self.diameter=self.options["maxdiameter"]
width=self.diameter
height=self.diameter
radius=width/2.
imgwidth=int(math.ceil(width))
imgheight=int(math.ceil(height))
# use a greyscale image here to reduce number of calculations
fullsizedbrush=Image.new("RGBA",(imgwidth,imgheight),(0,0,0,0))
# create raw access object for faster pixel setting
pix=fullsizedbrush.load()
for i in range(width):
for j in range(height):
distance=math.sqrt(((i+.5-radius)**2)+((j+.5-radius)**2))
if distance <= radius:
pix[i,j]=colortuple
self.fullsizedbrush=PilToQImage(fullsizedbrush)
def getOptionsWidget(self,parent=None):
if parent and not self.optionswidget:
self.optionswidget=DrawingToolOptionsWidget(parent,self)
self.optionswidget.updateDisplayFromOptions()
return self.optionswidget
class DrawingToolOptionsWidget(qtgui.QWidget):
def __init__(self,parent,tooldesc):
qtgui.QWidget.__init__(self,parent)
self.tooldesc=tooldesc
# setup user interface
self.ui=Ui_PencilOptionsWidget()
self.ui.setupUi(self)
self.ui.brushpreviewwidget = BrushPreviewWidget(self.ui.brushpreviewwidget,tooldesc.fullsizedbrush,1)
def updateDisplayFromOptions(self):
self.ui.brushdiameter.setValue(self.tooldesc.options["maxdiameter"])
self.ui.brushmindiameter.setValue(self.tooldesc.options["mindiameter"])
self.ui.stepsize.setValue(self.tooldesc.options["step"])
self.ui.opacity.setValue(self.tooldesc.options["opacity"])
def on_brushdiameter_valueChanged(self,value):
self.tooldesc.options["maxdiameter"]=value
if(self.tooldesc.options["mindiameter"] > self.tooldesc.options["maxdiameter"]):
self.ui.brushmindiameter.setValue(self.tooldesc.options["maxdiameter"])
self.tooldesc.updateBrush()
def on_brushmindiameter_valueChanged(self,value):
self.tooldesc.options["mindiameter"]=value
if(self.tooldesc.options["mindiameter"] > self.tooldesc.options["maxdiameter"]):
self.ui.brushdiameter.setValue(self.tooldesc.options["mindiameter"])
def on_stepsize_valueChanged(self,value):
self.tooldesc.options["step"]=value
def on_opacity_valueChanged(self,value):
self.tooldesc.options["opacity"]=value
self.tooldesc.updateBrush()
class EraserToolDesc(PencilToolDesc):
# describe actual tool
class Tool(DrawingTool):
def __init__(self,options,window):
DrawingTool.__init__(self,options,window)
self.compmode=qtgui.QPainter.CompositionMode_DestinationOut
self.fgcolor=0
# back to description stuff
def __init__(self):
AbstractToolDesc.__init__(self,"eraser")
self.displayname="Eraser"
self.updateBrush()
def pressToolButton(self):
BeeApp().master.toolselectwindow.ui.eraser_button.setChecked(True)
def setDefaultOptions(self):
self.options["maxdiameter"]=21
self.options["mindiameter"]=0
self.options["step"]=1
self.options["pressuresize"]=1
self.options["pressurebalance"]=100
self.options["blur"]=100
self.options["opacity"]=100
def setupTool(self,window,layerkey):
tool=self.Tool(self.options,window)
tool.name=self.name
tool.clippath=window.getClipPathCopy()
tool.layerkey=window.curlayerkey
# setup fullsized brush
width=self.diameter
height=self.diameter
coloredfullbrush=qtgui.QImage(width,height,qtgui.QImage.Format_ARGB32_Premultiplied)
coloredfullbrush.fill(qtgui.QColor(0,0,0).rgba())
painter = qtgui.QPainter()
painter.begin(coloredfullbrush)
painter.setCompositionMode(qtgui.QPainter.CompositionMode_DestinationIn)
painter.drawImage(qtcore.QPoint(0,0),self.fullsizedbrush)
painter.end()
tool.fullsizedbrush=coloredfullbrush
return tool
def getOptionsWidget(self,parent=None):
if not self.optionswidget:
self.optionswidget=EraserOptionsWidget(parent,self)
self.optionswidget.updateDisplayFromOptions()
return self.optionswidget
class EraserOptionsWidget(qtgui.QWidget):
def __init__(self,parent,tooldesc):
qtgui.QWidget.__init__(self,parent)
self.tooldesc=tooldesc
# setup user interface
self.ui=Ui_EraserOptionsWidget()
self.ui.setupUi(self)
self.ui.brushpreviewwidget = BrushPreviewWidget(self.ui.brushpreviewwidget,tooldesc.fullsizedbrush,1)
def updateDisplayFromOptions(self):
self.ui.eraserdiameter.setValue(self.tooldesc.options["maxdiameter"])
self.ui.mindiameter.setValue(self.tooldesc.options["mindiameter"])
self.ui.stepsize.setValue(self.tooldesc.options["step"])
def on_eraserdiameter_valueChanged(self,value):
self.tooldesc.options["maxdiameter"]=value
if(self.tooldesc.options["mindiameter"] > self.tooldesc.options["maxdiameter"]):
self.ui.mindiameter.setValue(self.tooldesc.options["maxdiameter"])
self.tooldesc.updateBrush()
def on_mindiameter_valueChanged(self,value):
self.tooldesc.options["mindiameter"]=value
if(self.tooldesc.options["mindiameter"] > self.tooldesc.options["maxdiameter"]):
self.ui.eraserdiameter.setValue(self.tooldesc.options["mindiameter"])
def on_stepsize_valueChanged(self,value):
self.tooldesc.options["step"]=value