-
Notifications
You must be signed in to change notification settings - Fork 150
/
canvas.py
656 lines (487 loc) · 19.2 KB
/
canvas.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
import random
from PyQt5.QtWidgets import *
from hparams import *
def build_font(config):
"""
Construct a complete font from the configuration options
:param self:
:param config:
:return: QFont
"""
font = config['font']
font.setPointSize(config['fontsize'])
font.setBold(config['bold'])
font.setItalic(config['italic'])
font.setUnderline(config['underline'])
return font
class Canvas(QLabel):
mode = 'rectangle'
primary_color = QColor(Qt.black)
secondary_color = None
primary_color_updated = pyqtSignal(str)
secondary_color_updated = pyqtSignal(str)
# Store configuration settings, including pen width, fonts etc.
config = {
# Drawing options.
'size': 1,
'fill': True,
# Font options.
'font': QFont('Times'),
'fontsize': 12,
'bold': False,
'italic': False,
'underline': False,
}
active_color = None
preview_pen = None
timer_event = None
current_stamp = None
time_stamp = 0
display_pad = None
mutex = QMutex()
lock = QMutexLocker(mutex)
ready_pixmap = None
def initialize(self):
self.background_color = QColor(self.secondary_color) if self.secondary_color else QColor(Qt.white)
self.eraser_color = QColor(self.secondary_color) if self.secondary_color else QColor(Qt.white)
# self.eraser_color.setAlpha(100)
self.reset()
if self.display_pad:
self.update()
def reset(self):
# Create the pixmap for display.
self.setPixmap(QPixmap(*CANVAS_DIMENSIONS))
# Clear the canvas.
self.pixmap().fill(self.background_color)
def set_primary_color(self, hex):
self.primary_color = QColor(hex)
def set_secondary_color(self, hex):
self.secondary_color = QColor(hex)
def set_config(self, key, value):
self.config[key] = value
def set_mode(self, mode):
print("set_mode", mode)
# Clean up active timer animations.
self.timer_cleanup()
# Reset mode-specific vars (all)
self.active_shape_fn = None
self.active_shape_args = ()
self.origin_pos = None
self.current_pos = None
self.last_pos = None
self.history_pos = None
self.last_history = []
self.current_text = ""
self.last_text = ""
self.last_config = {}
self.dash_offset = 0
self.locked = False
# Apply the mode
self.mode = mode
def reset_mode(self):
self.set_mode(self.mode)
def on_timer(self):
if self.timer_event:
self.timer_event()
def timer_cleanup(self):
if self.timer_event:
# Stop the timer, then trigger cleanup.
timer_event = self.timer_event
self.timer_event = None
timer_event(final=True)
# Mouse events.
def mousePressEvent(self, e):
fn = getattr(self, "%s_mousePressEvent" % self.mode, None)
if fn:
return fn(e)
def mouseMoveEvent(self, e):
fn = getattr(self, "%s_mouseMoveEvent" % self.mode, None)
if fn:
return fn(e)
def mouseReleaseEvent(self, e):
fn = getattr(self, "%s_mouseReleaseEvent" % self.mode, None)
if fn:
return fn(e)
def mouseDoubleClickEvent(self, e):
fn = getattr(self, "%s_mouseDoubleClickEvent" % self.mode, None)
if fn:
return fn(e)
# Generic events (shared by brush-like tools)
def generic_mousePressEvent(self, e):
self.last_pos = e.pos()
if e.button() == Qt.LeftButton:
self.active_color = self.primary_color
else:
self.active_color = self.secondary_color
def generic_mouseReleaseEvent(self, e):
self.last_pos = None
# Mode-specific events.
# Select polygon events
def clear_mouseReleaseEvent(self, e):
self.initialize()
self.reset_mode()
self.update()
def selectpoly_mousePressEvent(self, e):
if not self.locked or e.button == Qt.RightButton:
self.active_shape_fn = 'drawPolygon'
self.preview_pen = SELECTION_PEN
self.generic_poly_mousePressEvent(e)
def selectpoly_timerEvent(self, final=False):
self.generic_poly_timerEvent(final)
def selectpoly_mouseMoveEvent(self, e):
if not self.locked:
self.generic_poly_mouseMoveEvent(e)
def selectpoly_mouseDoubleClickEvent(self, e):
self.current_pos = e.pos()
self.locked = True
def selectpoly_copy(self):
"""
Copy a polygon region from the current image, returning it.
Create a mask for the selected area, and use it to blank
out non-selected regions. Then get the bounding rect of the
selection and crop to produce the smallest possible image.
:return: QPixmap of the copied region.
"""
self.timer_cleanup()
pixmap = self.pixmap().copy()
bitmap = QBitmap(*CANVAS_DIMENSIONS)
bitmap.clear() # Starts with random data visible.
p = QPainter(bitmap)
# Construct a mask where the user selected area will be kept, the rest removed from the image is transparent.
userpoly = QPolygon(self.history_pos + [self.current_pos])
p.setPen(QPen(Qt.color1))
p.setBrush(QBrush(Qt.color1)) # Solid color, Qt.color1 == bit on.
p.drawPolygon(userpoly)
p.end()
# Set our created mask on the image.
pixmap.setMask(bitmap)
# Calculate the bounding rect and return a copy of that region.
return pixmap.copy(userpoly.boundingRect())
# Select rectangle events
def selectrect_mousePressEvent(self, e):
self.active_shape_fn = 'drawRect'
self.preview_pen = SELECTION_PEN
self.generic_shape_mousePressEvent(e)
def selectrect_timerEvent(self, final=False):
self.generic_shape_timerEvent(final)
def selectrect_mouseMoveEvent(self, e):
if not self.locked:
self.current_pos = e.pos()
def selectrect_mouseReleaseEvent(self, e):
self.current_pos = e.pos()
self.locked = True
def selectrect_copy(self):
"""
Copy a rectangle region of the current image, returning it.
:return: QPixmap of the copied region.
"""
self.timer_cleanup()
return self.pixmap().copy(QRect(self.origin_pos, self.current_pos))
# Eraser events
def eraser_mousePressEvent(self, e):
self.generic_mousePressEvent(e)
def eraser_mouseMoveEvent(self, e):
if self.last_pos:
p = QPainter(self.pixmap())
p.setPen(QPen(self.eraser_color, 15, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
p.drawLine(self.last_pos, e.pos())
self.last_pos = e.pos()
self.update()
def eraser_mouseReleaseEvent(self, e):
self.generic_mouseReleaseEvent(e)
# Stamp (pie) events
def stamp_mousePressEvent(self, e):
p = QPainter(self.pixmap())
stamp = self.current_stamp
p.drawPixmap(e.x() - stamp.width() // 2, e.y() - stamp.height() // 2, stamp)
self.update()
# Pen events
def pen_mousePressEvent(self, e):
self.generic_mousePressEvent(e)
def pen_mouseMoveEvent(self, e):
if self.last_pos:
p = QPainter(self.pixmap())
p.setPen(QPen(self.active_color, self.config['size'], Qt.SolidLine, Qt.SquareCap, Qt.RoundJoin))
p.drawLine(self.last_pos, e.pos())
self.last_pos = e.pos()
self.update()
def pen_mouseReleaseEvent(self, e):
self.generic_mouseReleaseEvent(e)
# Brush events
def brush_mousePressEvent(self, e):
self.generic_mousePressEvent(e)
def brush_mouseMoveEvent(self, e):
if self.last_pos:
p = QPainter(self.pixmap())
p.setPen(QPen(self.active_color, self.config['size'] * BRUSH_MULT, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
p.drawLine(self.last_pos, e.pos())
self.last_pos = e.pos()
self.update()
def brush_mouseReleaseEvent(self, e):
self.generic_mouseReleaseEvent(e)
# Spray events
def spray_mousePressEvent(self, e):
self.generic_mousePressEvent(e)
def spray_mouseMoveEvent(self, e):
if self.last_pos:
p = QPainter(self.pixmap())
p.setPen(QPen(self.active_color, 1))
for n in range(self.config['size'] * SPRAY_PAINT_N):
xo = random.gauss(0, self.config['size'] * SPRAY_PAINT_MULT)
yo = random.gauss(0, self.config['size'] * SPRAY_PAINT_MULT)
p.drawPoint(e.x() + xo, e.y() + yo)
self.update()
def spray_mouseReleaseEvent(self, e):
self.generic_mouseReleaseEvent(e)
# Text events
def keyPressEvent(self, e):
if self.mode == 'text':
if e.key() == Qt.Key_Backspace:
self.current_text = self.current_text[:-1]
else:
self.current_text = self.current_text + e.text()
def text_mousePressEvent(self, e):
if e.button() == Qt.LeftButton and self.current_pos is None:
self.current_pos = e.pos()
self.current_text = ""
self.timer_event = self.text_timerEvent
elif e.button() == Qt.LeftButton:
self.timer_cleanup()
# Draw the text to the image
p = QPainter(self.pixmap())
p.setRenderHints(QPainter.Antialiasing)
font = build_font(self.config)
p.setFont(font)
pen = QPen(self.primary_color, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin)
p.setPen(pen)
p.drawText(self.current_pos, self.current_text)
self.update()
self.reset_mode()
elif e.button() == Qt.RightButton and self.current_pos:
self.reset_mode()
def text_timerEvent(self, final=False):
p = QPainter(self.pixmap())
p.setCompositionMode(QPainter.RasterOp_SourceXorDestination)
pen = PREVIEW_PEN
p.setPen(pen)
if self.last_text:
font = build_font(self.last_config)
p.setFont(font)
p.drawText(self.current_pos, self.last_text)
if not final:
font = build_font(self.config)
p.setFont(font)
p.drawText(self.current_pos, self.current_text)
self.last_text = self.current_text
self.last_config = self.config.copy()
self.update()
# Fill events
def fill_mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
self.active_color = self.primary_color
else:
self.active_color = self.secondary_color
image = self.pixmap().toImage()
w, h = image.width(), image.height()
x, y = e.x(), e.y()
# Get our target color from origin.
target_color = image.pixel(x, y)
have_seen = set()
queue = [(x, y)]
def get_cardinal_points(have_seen, center_pos):
points = []
cx, cy = center_pos
for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
xx, yy = cx + x, cy + y
if (xx >= 0 and xx < w and
yy >= 0 and yy < h and
(xx, yy) not in have_seen):
points.append((xx, yy))
have_seen.add((xx, yy))
return points
# Now perform the search and fill.
p = QPainter(self.pixmap())
p.setPen(QPen(self.active_color))
while queue:
x, y = queue.pop()
if image.pixel(x, y) == target_color:
p.drawPoint(QPoint(x, y))
queue.extend(get_cardinal_points(have_seen, (x, y)))
self.update()
# Dropper events
def dropper_mousePressEvent(self, e):
c = self.pixmap().toImage().pixel(e.pos())
hex = QColor(c).name()
if e.button() == Qt.LeftButton:
self.set_primary_color(hex)
self.primary_color_updated.emit(hex) # Update UI.
elif e.button() == Qt.RightButton:
self.set_secondary_color(hex)
self.secondary_color_updated.emit(hex) # Update UI.
# Generic shape events: Rectangle, Ellipse, Rounded-rect
def generic_shape_mousePressEvent(self, e):
self.origin_pos = e.pos()
self.current_pos = e.pos()
self.timer_event = self.generic_shape_timerEvent
def generic_shape_timerEvent(self, final=False):
p = QPainter(self.pixmap())
p.setCompositionMode(QPainter.RasterOp_SourceXorDestination)
pen = self.preview_pen
pen.setDashOffset(self.dash_offset)
p.setPen(pen)
if self.last_pos:
getattr(p, self.active_shape_fn)(QRect(self.origin_pos, self.last_pos), *self.active_shape_args)
if not final:
self.dash_offset -= 1
pen.setDashOffset(self.dash_offset)
p.setPen(pen)
getattr(p, self.active_shape_fn)(QRect(self.origin_pos, self.current_pos), *self.active_shape_args)
self.update()
self.last_pos = self.current_pos
def generic_shape_mouseMoveEvent(self, e):
self.current_pos = e.pos()
def generic_shape_mouseReleaseEvent(self, e):
if self.last_pos:
# Clear up indicator.
self.timer_cleanup()
p = QPainter(self.pixmap())
p.setPen(QPen(self.primary_color, self.config['size'], Qt.SolidLine, Qt.SquareCap, Qt.MiterJoin))
if self.config['fill']:
p.setBrush(QBrush(self.secondary_color))
getattr(p, self.active_shape_fn)(QRect(self.origin_pos, e.pos()), *self.active_shape_args)
self.update()
self.reset_mode()
# Line events
def line_mousePressEvent(self, e):
self.origin_pos = e.pos()
self.current_pos = e.pos()
self.preview_pen = PREVIEW_PEN
self.timer_event = self.line_timerEvent
def line_timerEvent(self, final=False):
p = QPainter(self.pixmap())
p.setCompositionMode(QPainter.RasterOp_SourceXorDestination)
pen = self.preview_pen
p.setPen(pen)
if self.last_pos:
p.drawLine(self.origin_pos, self.last_pos)
if not final:
p.drawLine(self.origin_pos, self.current_pos)
self.update()
self.last_pos = self.current_pos
def line_mouseMoveEvent(self, e):
self.current_pos = e.pos()
def line_mouseReleaseEvent(self, e):
if self.last_pos:
# Clear up indicator.
self.timer_cleanup()
p = QPainter(self.pixmap())
p.setPen(QPen(self.primary_color, self.config['size'], Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
p.drawLine(self.origin_pos, e.pos())
self.update()
self.reset_mode()
# Generic poly events
def generic_poly_mousePressEvent(self, e):
if e.button() == Qt.LeftButton:
if self.history_pos:
self.history_pos.append(e.pos())
else:
self.history_pos = [e.pos()]
self.current_pos = e.pos()
self.timer_event = self.generic_poly_timerEvent
elif e.button() == Qt.RightButton and self.history_pos:
# Clean up, we're not drawing
self.timer_cleanup()
self.reset_mode()
def generic_poly_timerEvent(self, final=False):
p = QPainter(self.pixmap())
p.setCompositionMode(QPainter.RasterOp_SourceXorDestination)
pen = self.preview_pen
pen.setDashOffset(self.dash_offset)
p.setPen(pen)
if self.last_history:
getattr(p, self.active_shape_fn)(*self.last_history)
if not final:
self.dash_offset -= 1
pen.setDashOffset(self.dash_offset)
p.setPen(pen)
getattr(p, self.active_shape_fn)(*self.history_pos + [self.current_pos])
self.update()
self.last_pos = self.current_pos
self.last_history = self.history_pos + [self.current_pos]
def generic_poly_mouseMoveEvent(self, e):
self.current_pos = e.pos()
def generic_poly_mouseDoubleClickEvent(self, e):
self.timer_cleanup()
p = QPainter(self.pixmap())
p.setPen(QPen(self.primary_color, self.config['size'], Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))
# Note the brush is ignored for polylines.
if self.secondary_color:
p.setBrush(QBrush(self.secondary_color))
getattr(p, self.active_shape_fn)(*self.history_pos + [e.pos()])
self.update()
self.reset_mode()
# Polyline events
def polyline_mousePressEvent(self, e):
self.active_shape_fn = 'drawPolyline'
self.preview_pen = PREVIEW_PEN
self.generic_poly_mousePressEvent(e)
def polyline_timerEvent(self, final=False):
self.generic_poly_timerEvent(final)
def polyline_mouseMoveEvent(self, e):
self.generic_poly_mouseMoveEvent(e)
def polyline_mouseDoubleClickEvent(self, e):
self.generic_poly_mouseDoubleClickEvent(e)
# Rectangle events
def rect_mousePressEvent(self, e):
self.active_shape_fn = 'drawRect'
self.active_shape_args = ()
self.preview_pen = PREVIEW_PEN
self.generic_shape_mousePressEvent(e)
def rect_timerEvent(self, final=False):
self.generic_shape_timerEvent(final)
def rect_mouseMoveEvent(self, e):
self.generic_shape_mouseMoveEvent(e)
def rect_mouseReleaseEvent(self, e):
self.generic_shape_mouseReleaseEvent(e)
# Polygon events
def polygon_mousePressEvent(self, e):
self.active_shape_fn = 'drawPolygon'
self.preview_pen = PREVIEW_PEN
self.generic_poly_mousePressEvent(e)
def polygon_timerEvent(self, final=False):
self.generic_poly_timerEvent(final)
def polygon_mouseMoveEvent(self, e):
self.generic_poly_mouseMoveEvent(e)
def polygon_mouseDoubleClickEvent(self, e):
self.generic_poly_mouseDoubleClickEvent(e)
# Ellipse events
def ellipse_mousePressEvent(self, e):
self.active_shape_fn = 'drawEllipse'
self.active_shape_args = ()
self.preview_pen = PREVIEW_PEN
self.generic_shape_mousePressEvent(e)
def ellipse_timerEvent(self, final=False):
self.generic_shape_timerEvent(final)
def ellipse_mouseMoveEvent(self, e):
self.generic_shape_mouseMoveEvent(e)
def ellipse_mouseReleaseEvent(self, e):
self.generic_shape_mouseReleaseEvent(e)
# Roundedrect events
def roundrect_mousePressEvent(self, e):
self.active_shape_fn = 'drawRoundedRect'
self.active_shape_args = (25, 25)
self.preview_pen = PREVIEW_PEN
self.generic_shape_mousePressEvent(e)
def roundrect_timerEvent(self, final=False):
self.generic_shape_timerEvent(final)
def roundrect_mouseMoveEvent(self, e):
self.generic_shape_mouseMoveEvent(e)
def roundrect_mouseReleaseEvent(self, e):
self.generic_shape_mouseReleaseEvent(e)
def set_display_pad(self, display_pad):
self.display_pad = display_pad
def update(self):
self.time_stamp += 1
super(Canvas, self).update()
# self.ready_pixmap = self.pixmap().copy()
self.display_pad.update()