-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathArea.py
More file actions
1970 lines (1626 loc) · 71.4 KB
/
Area.py
File metadata and controls
1970 lines (1626 loc) · 71.4 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
# -*- coding: utf-8 -*-
"""
@namespace Area
Tools and events manipulation
Copyright 2007, NATE-LSI-EPUSP
Oficina is developed in Brazil at Escola Politécnica of
Universidade de São Paulo. NATE is part of LSI (Integrable
Systems Laboratory) and stands for Learning, Work and Entertainment
Research Group. Visit our web page:
www.lsi.usp.br/nate
Suggestions, bugs and doubts, please email oficina@lsi.usp.br
Oficina 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 version 2 of
the License.
Oficina 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 Oficina; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
Boston, MA 02110-1301 USA.
The copy of the GNU General Public License is found in the
COPYING file included in the source distribution.
Authors:
Joyce Alessandra Saul (joycealess@gmail.com)
Andre Mossinato (andremossinato@gmail.com)
Nathalia Sautchuk Patrício (nathalia.sautchuk@gmail.com)
Pedro Kayatt (pekayatt@gmail.com)
Rafael Barbolo Lopes (barbolo@gmail.com)
Alexandre A. Gonçalves Martinazzo (alexandremartinazzo@gmail.com)
Colaborators:
Bruno Gola (brunogola@gmail.com)
Group Manager:
Irene Karaguilla Ficheman (irene@lsi.usp.br)
Cientific Coordinator:
Roseli de Deus Lopes (roseli@lsi.usp.br)
UI Design (OLPC):
Eben Eliason (eben@laptop.org)
Project Coordinator (OLPC):
Manusheel Gupta (manu@laptop.org)
Project Advisor (OLPC):
Walter Bender (walter@laptop.org)
"""
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import GObject
from gi.repository import Pango
from gi.repository import PangoCairo
from gi.repository import Gst
import logging
import os
import math
import cairo
import io
import array
from Desenho import Desenho
from urllib.parse import urlparse
from sugar3.graphics import style
from sugar3.activity import activity
FALLBACK_FILL = True
try:
from fill import fill
FALLBACK_FILL = False
logging.debug('Found fill binaries.')
except:
logging.error('No valid fill binaries. Using slower python code')
pass
# Tools and events manipulation are handle with this class.
TARGET_URI = 0
MAX_UNDO_STEPS = 12
RESIZE_ARROW_SIZE = style.GRID_CELL_SIZE / 2
SOUNDS = {'arrow': ['oneclick.ogg', False, True, True],
'brush': ['brush.ogg', True, False, False],
'bucket': ['bucket.ogg', False, True, True],
'ellipse': ['oneclick.ogg', False, True, True],
'eraser': ['eraser.ogg', True, False, False],
'freeform': ['oneclick.ogg', False, True, True],
'heart': ['oneclick.ogg', False, True, True],
'kalidoscope': ['brush.ogg', True, False, False],
'line': ['oneclick.ogg', False, True, True],
'marquee-rectangular': ['oneclick.ogg', False, True, True],
'parallelogram': ['oneclick.ogg', False, True, True],
'polygon_regular': ['oneclick.ogg', False, True, True],
'rainbow': ['brush.ogg', True, False, False],
'rectangle': ['oneclick.ogg', False, True, True],
'star': ['oneclick.ogg', False, True, True],
'trapezoid': ['oneclick.ogg', False, True, True],
'triangle': ['oneclick.ogg', False, True, True]}
# this list contain the sounds that should be played manually,
# and no automatically.
IGNORE_AUTO_PLAY = ['bucket']
Gst.init([])
def _get_screen_dpi():
xft_dpi = Gtk.Settings.get_default().get_property('gtk-xft-dpi')
dpi = float(xft_dpi / 1024)
logging.debug('Setting dpi to: %f', dpi)
return dpi
bundle_path = activity.get_bundle_path()
class Area(Gtk.DrawingArea):
__gsignals__ = {
'undo': (GObject.SignalFlags.ACTION, None, ([])),
'redo': (GObject.SignalFlags.ACTION, None, ([])),
'action-saved': (GObject.SignalFlags.ACTION, None, ([])),
'select': (GObject.SignalFlags.ACTION, None, ([])),
}
PENCIL_LIKE_TOOLS = ['pencil', 'eraser', 'brush', 'kalidoscope', 'rainbow',
'stamp', 'load-stamp']
def __init__(self, activity):
""" Initialize the object from class Area which is derived
from Gtk.DrawingArea.
@param self -- the Area object (GtkDrawingArea)
@param activity -- the parent window
"""
Gtk.DrawingArea.__init__(self)
self.set_events(Gdk.EventMask.POINTER_MOTION_MASK |
Gdk.EventMask.POINTER_MOTION_HINT_MASK |
Gdk.EventMask.BUTTON_PRESS_MASK |
Gdk.EventMask.BUTTON_RELEASE_MASK |
Gdk.EventMask.BUTTON_MOTION_MASK |
Gdk.EventMask.EXPOSURE_MASK |
Gdk.EventMask.LEAVE_NOTIFY_MASK |
Gdk.EventMask.ENTER_NOTIFY_MASK |
Gdk.EventMask.KEY_PRESS_MASK |
Gdk.EventMask.TOUCH_MASK)
self.connect('event', self.__event_cb)
self.connect("draw", self.draw)
self.connect("motion_notify_event", self.mousemove)
self.connect("key_press_event", self.key_press)
self.connect("leave_notify_event", self.mouseleave)
self.connect("enter_notify_event", self.mouseenter)
target = [Gtk.TargetEntry.new('text/uri-list', 0, TARGET_URI)]
self.drag_dest_set(Gtk.DestDefaults.ALL, target,
Gdk.DragAction.COPY | Gdk.DragAction.MOVE)
self.connect('drag_data_received', self.drag_data_received)
self.set_can_focus(True)
self.grab_focus()
# TODO gtk3
# self.set_extension_events(Gdk.EXTENSION_EVENTS_CURSOR)
# Define which tool is been used.
# It is now described as a dictionnary,
# with the following keys:
# - 'name' : a string
# - 'line size' : a integer
# - 'stamp size' : a integer
# - 'line shape' : a string - 'circle' or 'square', for now
# - 'fill' : a Boolean value
# - 'vertices' : a integer
# All values migth be None, execept in 'name' key.
self.tool = {
'name': 'brush',
'line size': 4,
'stamp size': self._get_stamp_size(),
'line shape': 'circle',
'fill': True,
'cairo_stroke_color': (0.0, 0.0, 0.0, 1.0),
'cairo_fill_color': (0.0, 0.0, 0.0, 1.0),
'bucket_color': (0, 0, 0),
'alpha': 1.0,
'vertices': 6.0,
'font_description': 'Sans 12'}
self.desenha = False
self._selmove = False
self._selresize = False
self.oldx = 0
self.oldy = 0
self.drawing_canvas = None
# This surface is used when need load data from a file or a process
self.drawing_canvas_data = None
self.textos = []
self.text_in_progress = False
self.activity = activity
self.d = Desenho(self)
self.last = []
self.keep_aspect_ratio = False
self.keep_shape_ratio = False
self._selection_finished = False
self._set_screen_dpi()
self._font_description = None
self.set_font_description(
Pango.FontDescription(self.tool['font_description']))
# selection properties
self.clear_selection()
self.pending_clean_selection_background = False
# List of pixbuf for the Undo function:
self._undo_list = []
self._undo_index = None
self._keep_undo = False
# variables to show the tool shape
self.drawing = False
self.x_cursor = 0
self.y_cursor = 0
# touch cache position
self._last_x_touch = 0
self._last_y_touch = 0
# used to identify emulated mouse
self._on_touch = False
self._update_timer = None
self._resize_hq_timer = None
self._player = None
self._sounds_enabled = False
try:
self._player = Gst.ElementFactory.make('playbin', 'Player')
self._pipeline = Gst.Pipeline()
self._bus = self._pipeline.get_bus()
self._bus.add_signal_watch()
self._bus.connect('message::eos', self.replay_tool_sound)
self._pipeline.add(self._player)
except:
logging.error(
"Sound player is not installed/available in the system.")
def _set_screen_dpi(self):
dpi = _get_screen_dpi()
font_map_default = PangoCairo.font_map_get_default()
font_map_default.set_resolution(dpi)
def set_font_description(self, fd):
self._font_description = fd
self.activity.textview.modify_font(fd)
self.tool['font_description'] = fd.to_string()
if self.text_in_progress:
# set the focus in the textview to enable resize if needed
GLib.idle_add(self.activity.textview.grab_focus)
def get_font_description(self):
return Pango.FontDescription(self.tool['font_description'])
def _get_stamp_size(self):
"""Set the stamp initial size, based on the display DPI."""
return style.zoom(44)
def load_from_file(self, file_path):
# load using a pixbuf to be able to read different formats
loaded_pxb = GdkPixbuf.Pixbuf.new_from_file(file_path)
self.drawing_canvas_data = cairo.ImageSurface(
cairo.FORMAT_ARGB32, loaded_pxb.get_width(),
loaded_pxb.get_height())
ctx = cairo.Context(self.drawing_canvas_data)
Gdk.cairo_set_source_pixbuf(ctx, loaded_pxb, 0, 0)
ctx.paint()
def setup(self, width, height):
"""Configure the Area object."""
logging.debug('Area.setup: w=%s h=%s', width, height)
self.set_size_request(width, height)
self.drawing_canvas = None
self._width = width
self._height = height
self.enable_undo()
# Setting a initial tool
self.set_tool(self.tool)
return True
def get_size(self):
rect = self.get_allocation()
return rect.width, rect.height
def _init_temp_canvas(self, area=None):
# logging.error('init_temp_canvas. area %s', area)
# self.drawing_canvas.flush()
if area is None:
width, height = self.get_size()
self.temp_ctx.rectangle(0, 0, width, height)
else:
self.temp_ctx.rectangle(area.x, area.y, area.width, area.height)
self.temp_ctx.set_source_surface(self.drawing_canvas)
self.temp_ctx.paint()
def display_selection_border(self, ctx):
if not self.is_selected():
return
x, y, width, height = self.get_selection_bounds()
if self._selection_finished:
ctx.save()
selection_surface = self.get_selection()
ctx.translate(x, y)
ctx.set_source_surface(selection_surface)
ctx.rectangle(0, 0, width, height)
ctx.paint()
ctx.restore()
ctx.save()
ctx.set_line_width(1)
ctx.set_source_rgba(1., 1., 1., 1.)
ctx.set_line_cap(cairo.LINE_CAP_ROUND)
ctx.set_line_join(cairo.LINE_JOIN_ROUND)
# draw a dotted rectangle around the selection
ctx.rectangle(x, y, width, height)
ctx.stroke_preserve()
ctx.set_dash([5, 5], 0)
ctx.set_source_rgba(0., 0., 0., 1.)
ctx.stroke()
# draw a triangle to resize the selection
arrow_width = RESIZE_ARROW_SIZE
ctx.new_path()
ctx.move_to(x + width + arrow_width, y + height)
ctx.line_to(x + width + arrow_width, y + height + arrow_width)
ctx.line_to(x + width, y + height + arrow_width)
ctx.close_path()
ctx.set_dash([2, 2], 0)
ctx.set_source_rgba(0., 0., 0., 1.)
ctx.stroke()
ctx.restore()
def configure_line(self, size):
"""Configure the new line's size.
@param self -- the Area object (GtkDrawingArea)
@param size -- the size of the new line
"""
self.drawing_ctx.set_line_width(size)
def draw(self, widget, context):
""" This function define which canvas will be showed to the user.
Show up the Area object (GtkDrawingArea).
@param self -- the Area object (GtkDrawingArea)
@param widget -- the Area object (GtkDrawingArea)
@param event -- GdkEvent
"""
# It is the main canvas, who is display most of the time
# if is not None was read from a file
if self.drawing_canvas is None:
self.drawing_canvas = context.get_target().create_similar(
cairo.CONTENT_COLOR_ALPHA, self._width, self._height)
self.drawing_ctx = cairo.Context(self.drawing_canvas)
# paint background white
self.drawing_ctx.rectangle(0, 0, self._width, self._height)
if self.drawing_canvas_data is None:
self.drawing_ctx.set_source_rgb(1.0, 1.0, 1.0)
self.drawing_ctx.fill()
else:
self.drawing_ctx.set_source_surface(self.drawing_canvas_data)
self.drawing_ctx.paint()
self.drawing_canvas_data = None
# canvas showed when we need display something and not draw it
self.temp_canvas = context.get_target().create_similar(
cairo.CONTENT_COLOR_ALPHA, self._width, self._height)
self.temp_ctx = cairo.Context(self.temp_canvas)
self._init_temp_canvas()
if self.desenha:
# logging.error('Expose use temp canvas area')
# Paint the canvas in the widget:
context.set_source_surface(self.temp_canvas)
context.paint()
else:
# logging.error('Expose use drawing canvas area')
context.set_source_surface(self.drawing_canvas)
context.paint()
self.show_tool_shape(context)
# TODO: gtk3 how get the area to avoid redrawing all ?
self._init_temp_canvas() # area)
self.display_selection_border(context)
if self._keep_undo:
self.keep_undo()
def show_tool_shape(self, context):
"""
Show the shape of the tool selected for pencil, brush,
rainbow and eraser
"""
if self.tool['name'] in self.PENCIL_LIKE_TOOLS:
if not self.drawing:
context.set_source_rgba(*self.tool['cairo_stroke_color'])
context.set_line_width(1)
# draw stamp border in widget.window
if self.tool['name'] in ('stamp', 'load-stamp'):
wr, hr = self.stamp_dimentions
context.rectangle(self.x_cursor - wr / 2,
self.y_cursor - hr / 2, wr, hr)
context.stroke()
# draw shape of the brush, square or circle
elif self.tool['line shape'] == 'circle':
size = self.tool['line size']
context.arc(self.x_cursor,
self.y_cursor, size / 2, 0.,
2 * math.pi)
context.stroke()
else:
size = self.tool['line size']
context.move_to(self.x_cursor - size / 2,
self.y_cursor - size / 2)
context.rectangle(self.x_cursor - size / 2,
self.y_cursor - size / 2, size, size)
context.stroke()
self.last_x_cursor = self.x_cursor
self.last_y_cursor = self.y_cursor
def __event_cb(self, widget, event):
if event.type in (Gdk.EventType.TOUCH_BEGIN,
Gdk.EventType.TOUCH_CANCEL, Gdk.EventType.TOUCH_END,
Gdk.EventType.BUTTON_PRESS,
Gdk.EventType.BUTTON_RELEASE):
x = int(event.get_coords()[1])
y = int(event.get_coords()[2])
# seq = str(event.touch.sequence)
# logging.error('event x %d y %d type %s', x, y, event.type)
if event.type in (Gdk.EventType.TOUCH_BEGIN,
Gdk.EventType.BUTTON_PRESS):
if event.type == Gdk.EventType.BUTTON_PRESS:
# http://developer.gnome.org/gtk3/3.4/
# GtkWidget.html#gtk-widget-get-pointer
_pointer, x, y, state = event.window.get_pointer()
button1_pressed = state & Gdk.ModifierType.BUTTON1_MASK
else:
self._on_touch = True
button1_pressed = True
self.tool_start(x, y, button1_pressed)
elif event.type in (Gdk.EventType.TOUCH_END,
Gdk.EventType.BUTTON_RELEASE):
# set _update_timer = None to avoid executing
# toolmove code after mouse release or touch end
self._update_timer = None
if not self._tool_sound['full_play']:
self.stop_sound()
if event.type == Gdk.EventType.BUTTON_RELEASE:
_pointer, x, y, state = event.window.get_pointer()
shift_pressed = state & Gdk.ModifierType.SHIFT_MASK
else:
self._on_touch = False
shift_pressed = False
GLib.timeout_add(10, self.tool_end, x, y, shift_pressed)
def tool_start(self, coord_x, coord_y, button1_pressed):
width, height = self.get_size()
# text
design_mode = True
if self.tool['name'] == 'text':
self.d.text(self, coord_x, coord_y)
design_mode = False
# This fixes a bug that made the text viewer get stuck in the canvas
elif self.text_in_progress:
design_mode = False
try:
# This works for a Gtk.Entry
text = self.activity.textview.get_text()
except AttributeError:
# This works for a Gtk.TextView
buf = self.activity.textview.get_buffer()
start, end = buf.get_bounds()
text = buf.get_text(start, end, True)
if text is not None:
self.d.text(self, coord_x, coord_y)
self.text_in_progress = False
self.activity.textview.hide()
coords = (coord_x, coord_y)
if not self._selresize:
# if resizing don't update to remember previous resize
self.oldx, self.oldy = coords
if self.tool['name'] == 'picker':
self.pick_color(coord_x, coord_y)
if button1_pressed:
# Handle with the left button click event.
if self._sounds_enabled and not self._tool_sound[
'play_after_release'] and not self.tool[
'name'] in IGNORE_AUTO_PLAY:
self.play_tool_sound()
if self.tool['name'] == 'eraser':
self.last = []
self.d.eraser(self, coords, self.last)
self.last = coords
self.drawing = True
elif self.tool['name'] == 'brush':
self.last = []
self.d.brush(self, coords, self.last)
self.last = coords
self.drawing = True
elif self.tool['name'] == 'kalidoscope':
self.last = []
self.d.kalidoscope(self, coords, self.last)
self.last = coords
self.drawing = True
elif self.tool['name'] in ('stamp', 'load-stamp'):
self.last = []
self.d.stamp(self, coords, self.last)
self.last = coords
self.drawing = True
elif self.tool['name'] == 'rainbow':
self.last = []
self.d.rainbow(self, coords, self.last)
self.last = coords
self.drawing = True
elif self.tool['name'] == 'freeform':
self.configure_line(self.tool['line size'])
self.d.freeform(self, coords, True,
self.tool['fill'], "motion")
if self.tool['name'] == 'marquee-rectangular':
if self.is_selected():
# verify is out of the selected area
sel_x, sel_y, sel_width, sel_height = \
self.get_selection_bounds()
if self.check_point_in_area(coords[0], coords[1],
sel_x, sel_y, sel_width,
sel_height):
# be sure to have the last coords
# because can be older if was resized before
self.oldx, self.oldy = coords
# inside the selected area
self.d.move_selection(self, coords)
self._selmove = True
self._selresize = False
elif self.check_point_in_area(coords[0], coords[1],
sel_x + sel_width,
sel_y + sel_height,
RESIZE_ARROW_SIZE,
RESIZE_ARROW_SIZE):
# in de resize area
self._selmove = False
self._selresize = True
else:
self.end_selection()
design_mode = False
else:
self._selmove = False
if design_mode:
self.desenha = True
def end_selection(self):
if self.is_selected():
self.getout()
self._selmove = False
self._selresize = False
self.queue_draw()
def calculate_damaged_area(self, points):
min_x = points[0][0]
min_y = points[0][1]
max_x = 0
max_y = 0
for point in points:
if point[0] < min_x:
min_x = point[0]
if point[0] > max_x:
max_x = point[0]
if point[1] < min_y:
min_y = point[1]
if point[1] > max_y:
max_y = point[1]
# add the tool size
if self.tool['name'] in ('stamp', 'load-stamp'):
wr, hr = self.stamp_dimentions
elif self.tool['name'] == 'freeform':
wr = hr = 20
else:
wr = hr = self.tool['line size'] * 2
min_x = min_x - wr
min_y = min_y - wr
max_x = max_x + hr
max_y = max_y + hr
return (min_x, min_y, max_x - min_x, max_y - min_y)
def mousemove(self, widget, event):
"""Make the Area object (GtkDrawingArea)
recognize that the mouse is moving.
@param self -- the Area object (GtkDrawingArea)
@param widget -- the Area object (GtkDrawingArea)
@param event -- GdkEvent
"""
if event.get_source_device().get_name().find('touchscreen') >= 0 and \
not self._on_touch:
return
x = event.x
y = event.y
shift_pressed = event.get_state() & Gdk.ModifierType.SHIFT_MASK
button1_pressed = event.get_state() & Gdk.ModifierType.BUTTON1_MASK
if self._update_timer is None:
self._update_timer = GLib.timeout_add(5, self.tool_move, x, y,
button1_pressed,
shift_pressed)
def tool_move(self, x, y, button1_pressed, shift_pressed):
if self._update_timer is None:
return False
self._update_timer = None
self.x_cursor, self.y_cursor = int(x), int(y)
# the touch driver trigger many events sensing movements up and down
# by only a pixel. This code caches the last position and ignores
# the movement if is not bigger than one pixel to avoid redraws
if abs(x - self._last_x_touch) > 1 or \
abs(y > self._last_y_touch) > 1:
self._last_x_touch = x
self._last_y_touch = y
else:
return
coords = int(x), int(y)
if self.tool['name'] in ['rectangle', 'ellipse', 'line']:
if shift_pressed or self.keep_shape_ratio:
if self.tool['name'] in ['rectangle', 'ellipse']:
coords = self._keep_selection_ratio(coords)
elif self.tool['name'] == 'line':
coords = self._keep_line_ratio(coords)
if button1_pressed:
if self.tool['name'] == 'eraser':
self.d.eraser(self, coords, self.last)
self.last = coords
elif self.tool['name'] == 'brush':
self.d.brush(self, coords, self.last)
self.last = coords
elif self.tool['name'] == 'kalidoscope':
self.d.kalidoscope(self, coords, self.last)
self.last = coords
elif self.tool['name'] in ('stamp', 'load-stamp'):
self.d.stamp(self, coords, self.last,
self.tool['stamp size'])
self.last = coords
elif self.tool['name'] == 'rainbow':
self.d.rainbow(self, coords, self.last)
self.last = coords
if self.desenha:
if self.tool['name'] == 'line':
self.d.line(self, coords, True)
elif self.tool['name'] == 'ellipse':
self.d.circle(self, coords, True, self.tool['fill'])
elif self.tool['name'] == 'rectangle':
self.d.square(self, coords, True,
self.tool['fill'])
elif self.tool['name'] == 'marquee-rectangular':
if self._selmove:
# is inside a selected area, move it
self.d.move_selection(self, coords)
elif self._selresize:
self.d.resize_selection(self, coords)
else:
# create a selected area
if shift_pressed or self.keep_aspect_ratio:
coords = self._keep_selection_ratio(coords)
self.d.selection(self, coords)
elif self.tool['name'] == 'freeform':
self.configure_line(self.tool['line size'])
self.d.freeform(self, coords, True,
self.tool['fill'], "motion")
elif self.tool['name'] == 'triangle':
self.d.triangle(self, coords, True, self.tool['fill'])
elif self.tool['name'] == 'trapezoid':
self.d.trapezoid(self, coords, True, self.tool['fill'])
elif self.tool['name'] == 'arrow':
self.d.arrow(self, coords, True, self.tool['fill'])
elif self.tool['name'] == 'parallelogram':
self.d.parallelogram(self, coords, True,
self.tool['fill'])
elif self.tool['name'] == 'star':
self.d.star(self, coords, self.tool['vertices'],
True, self.tool['fill'])
elif self.tool['name'] == 'polygon_regular':
self.d.polygon_regular(self, coords,
self.tool['vertices'], True,
self.tool['fill'])
elif self.tool['name'] == 'heart':
self.d.heart(self, coords, True, self.tool['fill'])
else:
if self.tool['name'] in ['brush', 'eraser', 'rainbow', 'pencil',
'stamp', 'load-stamp']:
# define area to update (only to show the brush shape)
last_coords = (self.last_x_cursor, self.last_y_cursor)
area = self.calculate_damaged_area([last_coords, coords])
self.queue_draw_area(*area)
if self.tool['name'] == 'marquee-rectangular':
sel_x, sel_y, sel_width, sel_height = \
self.get_selection_bounds()
# show appropiate cursor
if self.check_point_in_area(coords[0], coords[1], sel_x, sel_y,
sel_width, sel_height):
# inside the selected area
cursor = Gdk.Cursor.new(Gdk.CursorType.FLEUR)
elif self.check_point_in_area(coords[0], coords[1],
sel_x + sel_width,
sel_y + sel_height,
RESIZE_ARROW_SIZE,
RESIZE_ARROW_SIZE):
# in de resize area
cursor = Gdk.Cursor.new(Gdk.CursorType.BOTTOM_RIGHT_CORNER)
else:
cursor = Gdk.Cursor.new(Gdk.CursorType.CROSS)
self.get_window().set_cursor(cursor)
elif self.tool['name'] == 'freeform':
self.desenha = True
self.configure_line(self.tool['line size'])
self.d.freeform(self, coords, True, self.tool['fill'],
"moving")
window = self.get_window()
if window is not None:
window.process_all_updates()
return False
def check_point_in_area(self, x_point, y_point, x_min, y_min,
width, height):
return not ((x_point < x_min) or (x_point > x_min + width) or
(y_point < y_min) or (y_point > y_min + height))
def tool_end(self, coord_x, coord_y, shift_pressed):
coords = (coord_x, coord_y)
if self.tool['name'] in ['rectangle', 'ellipse', 'line']:
if shift_pressed or self.keep_shape_ratio:
if self.tool['name'] in ['rectangle', 'ellipse']:
coords = self._keep_selection_ratio(coords)
if self.tool['name'] == 'line':
coords = self._keep_line_ratio(coords)
width, height = self.get_size()
private_undo = False
if self.desenha:
if self.tool['name'] == 'line':
self.d.line(self, coords, False)
elif self.tool['name'] == 'ellipse':
self.d.circle(self, coords, False, self.tool['fill'])
elif self.tool['name'] == 'rectangle':
self.d.square(self, coords, False, self.tool['fill'])
elif self.tool['name'] == 'marquee-rectangular':
private_undo = True
if self.is_selected() and not self._selmove and \
not self._selresize:
self.create_selection_surface()
self.emit('select')
else:
self.apply_temp_selection()
elif self.tool['name'] == 'freeform':
self.d.freeform(self, coords, False,
self.tool['fill'], 'release')
private_undo = True
elif self.tool['name'] == 'bucket':
self.get_window().set_cursor(Gdk.Cursor.new(
Gdk.CursorType.WATCH))
GLib.idle_add(self.flood_fill, coords[0], coords[1])
elif self.tool['name'] == 'triangle':
self.d.triangle(self, coords, False, self.tool['fill'])
elif self.tool['name'] == 'trapezoid':
self.d.trapezoid(self, coords, False, self.tool['fill'])
elif self.tool['name'] == 'arrow':
self.d.arrow(self, coords, False, self.tool['fill'])
elif self.tool['name'] == 'parallelogram':
self.d.parallelogram(self, coords, False, self.tool['fill'])
elif self.tool['name'] == 'star':
self.d.star(self, coords, self.tool['vertices'], False,
self.tool['fill'])
elif self.tool['name'] == 'polygon_regular':
self.d.polygon_regular(self, coords, self.tool['vertices'],
False, self.tool['fill'])
elif self.tool['name'] == 'heart':
self.d.heart(self, coords, False, self.tool['fill'])
if self._sounds_enabled and self._tool_sound[
'play_after_release'] and not self.tool[
'name'] in IGNORE_AUTO_PLAY:
self.play_tool_sound()
else:
if self.tool['name'] == 'marquee-rectangular':
if self.is_selected():
self.getout()
if self.tool['name'] in ['brush', 'eraser', 'rainbow', 'pencil',
'stamp', 'load-stamp']:
self.last = []
self.d.finish_trace(self)
self.drawing = False
if not private_undo and \
self.tool['name'] not in ['bucket', 'marquee-rectangular']:
# We have to avoid saving an undo state if the bucket tool
# is selected because this undo state is called before the
# GLib.idle_add (with the fill_flood function) finishes
# and an unconsistent undo state is saved
self.enable_undo()
if self.tool['name'] not in ('marquee-rectangular', 'freeform'):
self.desenha = False
self.queue_draw()
self.d.clear_control_points()
def flood_fill(self, x, y):
bucket_color = self.tool['bucket_color']
r = int((bucket_color[0] / 65536) * 256)
g = int((bucket_color[1] / 65536) * 256)
b = int((bucket_color[2] / 65536) * 256)
a = 255
# pack the color in a int as 0xAARRGGBB
fill_color = (a << 24) + (r << 16) + (g << 8) + (b);
logging.debug('fill_color %d', fill_color)
# load a array with the surface data
for array_type in ['H', 'I', 'L']:
pixels = array.array(array_type)
if pixels.itemsize == 4:
_array_type_used = array_type
break
else:
raise AssertionError()
# need copy self.drawing_canvas in a ImageSurface
# because 'cairo.XlibSurface do not have get_data
image_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self._width,
self._height)
ctx = cairo.Context(image_surface)
ctx.set_source_surface(self.drawing_canvas)
ctx.paint()
pixels.frombytes(image_surface.get_data())
# process the pixels in the array
width = self.drawing_canvas.get_width()
height = self.drawing_canvas.get_height()
old_color = pixels[x + y * width]
if old_color == fill_color:
logging.debug('Already filled')
# reset the cursor
display = Gdk.Display.get_default()
cursor = Gdk.Cursor.new_from_name(display, 'paint-bucket')
self.get_window().set_cursor(cursor)
return
if FALLBACK_FILL:
logging.debug('using python flood_fill')
def within(x, y):
if x < 0 or x >= width:
return False
if y < 0 or y >= height:
return False
return True
if not within(x, y):
return
edge = [(x, y)]
pixels[x + y * width] = fill_color
while len(edge) > 0:
newedge = []
for (x, y) in edge:
for (s, t) in ((x + 1, y), (x - 1, y), (x, y + 1),
(x, y - 1)):
if within(s, t) and \
pixels[s + t * width] == old_color:
pixels[s + t * width] = fill_color
newedge.append((s, t))
edge = newedge
else:
logging.debug('using c flood_fill')
pixels2 = fill(pixels, x, y, width, height, fill_color)
# the c implementation returns a list instead of array.array
pixels = array.array(_array_type_used, pixels2)
del(pixels2)
# create a updated drawing_canvas
self.drawing_canvas_data = cairo.ImageSurface.create_for_data(
pixels, cairo.FORMAT_ARGB32, width, height)
del(pixels)
self.setup(width, height)
self.queue_draw()
self.enable_undo()
display = Gdk.Display.get_default()
cursor = Gdk.Cursor.new_from_name(display, 'paint-bucket')
if self._sounds_enabled:
self.play_tool_sound()
self.get_window().set_cursor(cursor)
def pick_color(self, x, y):
# create a new 1x1 cairo surface
cairo_surface = cairo.ImageSurface(cairo.FORMAT_RGB24, 1, 1)
cairo_context = cairo.Context(cairo_surface)
# translate xlib_surface so that target pixel is at 0, 0
cairo_context.set_source_surface(self.drawing_canvas, -x, -y)
cairo_context.rectangle(0, 0, 1, 1)
cairo_context.set_operator(cairo.OPERATOR_SOURCE)
cairo_context.fill()
cairo_surface.flush()
# Read the pixel
pixels = cairo_surface.get_data()
# the values are between 0 and 255
red = pixels[2] / 256.0 * 65536.0
green = pixels[1] / 256.0 * 65536.0
blue = pixels[0] / 256.0 * 65536.0