Debian Codegraph @

src/tools/classic_tools/tool_eraser.py

raw symbols SCIP
1 # tool_eraser.py
2 #
3 # Copyright 2018-2023 Romain F. T.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17
18 import cairo, random
19 from gi.repository import Gdk, GdkPixbuf
20 from .tool_pencil import ToolPencil
21 from .abstract_classic_tool import AbstractClassicTool
22 from .utilities_blur import utilities_blur_surface, BlurType, BlurDirection
23
24 class ToolEraser(ToolPencil):
25 __gtype_name__ = 'ToolEraser'
26
27 def __init__(self, window, **kwargs):
28 super().__init__(window)
29 # Context: this is the name of a tool, in the meaning "a rubber eraser"
30 AbstractClassicTool.__init__(self, 'eraser', _("Eraser"), \
31 'tool-eraser-symbolic', window)
32 self.use_operator = False
33 self._fallback_operator = 'clear'
34 self.load_tool_action_enum('selection-color', 'last-delete-replace')
35 self.add_tool_action_enum('eraser-type', 'mosaic')
36 self.add_tool_action_enum('eraser-shape', 'pencil')
37 self._rgba = [0.0, 0.0, 0.0, 0.0]
38
39 def get_editing_tips(self):
40 self._rgba_type = self.get_option_value('selection-color')
41 self._eraser_shape = self.get_option_value('eraser-shape')
42 self._apply_shape_constraints()
43
44 label_options = self.label
45 if self._eraser_shape == 'pencil':
46 label_options += " - " + _("Pencil")
47 else:
48 label_options += " - " + _("Rectangle")
49 if self._eraser_type == 'solid':
50 label_options += " - " + {
51 'alpha': _("Transparency"),
52 'initial': _("Default color"),
53 'secondary': _("Secondary color")
54 }[self._rgba_type]
55 else:
56 label_options += " - " + {
57 'blur': _("Blur"),
58 'shuffle': _("Shuffle pixels"),
59 'mixed': _("Shuffle and blur"),
60 'mosaic': _("Mosaic")
61 }[self._eraser_type]
62
63 if self.get_image().get_mouse_is_pressed():
64 label_modifier_shift = None
65 else:
66 label_modifier_shift = self.label + " - "
67 if self._eraser_shape == 'pencil':
68 label_modifier_shift += _("Press <Shift> to erase a rectangle area instead")
69 else:
70 label_modifier_shift += _("Press <Shift> to erase a path instead")
71
72 full_list = [label_options, label_modifier_shift]
73 return list(filter(None, full_list))
74
75 def get_options_label(self):
76 return _("Eraser options")
77
78 def _apply_shape_constraints(self):
79 self._eraser_type = self.get_option_value('eraser-type')
80
81 can_blur = self._eraser_shape != 'pencil'
82 self.set_action_sensitivity('eraser-type', can_blur)
83 if not can_blur:
84 self._eraser_type = 'solid'
85
86 if 'solid' == self._eraser_type and 'secondary' == self._rgba_type:
87 self._fallback_operator = 'source'
88 else:
89 self._fallback_operator = 'clear'
90 # TODO en pratique non il y a des cas où on est plutôt en train de
91 # flouter, il faudrait un elif, et un autre système pour l'opérateur
92 # en fallback qui afficherait l'icône avec les gouttes.
93 # En fait on devrait yeet le délire du `_fallback_operator` ?
94 self.window.options_manager.update_pane(self)
95
96 ############################################################################
97
98 def on_press_on_area(self, event, surface, event_x, event_y):
99 super().on_press_on_area(event, surface, event_x, event_y)
100 # TODO the eraser grew up to be too different from the pencil, it
101 # shouldn't extend it
102
103 if self._rgba_type == 'alpha':
104 self._rgba = [0.0, 0.0, 0.0, 0.0]
105 elif self._rgba_type == 'initial':
106 clr = self.get_image().get_initial_rgba()
107 self._rgba = [clr.red, clr.green, clr.blue, clr.alpha]
108 elif self._rgba_type == 'secondary':
109 self._rgba = self.secondary_color
110
111 self.update_modifier_state(event.state)
112 if 'SHIFT' in self._modifier_keys:
113 if self._eraser_shape == 'rectangle':
114 self._eraser_shape = 'pencil'
115 else:
116 self._eraser_shape = 'rectangle'
117 self._apply_shape_constraints()
118
119 def on_motion_on_area(self, event, surface, event_x, event_y, render=True):
120 if self._eraser_shape == 'rectangle':
121 self._draw_rectangle(event_x, event_y)
122 else:
123 self._add_point(event_x, event_y)
124
125 if not render:
126 return
127 operation = self.build_operation(True)
128 self.do_tool_operation(operation)
129
130 def on_release_on_area(self, event, surface, event_x, event_y):
131 if self._eraser_shape == 'rectangle':
132 self._draw_rectangle(event_x, event_y)
133 else:
134 self._add_point(event_x, event_y)
135 operation = self.build_operation(False)
136 self.apply_operation(operation)
137 self._reset_temp_points()
138
139 def _draw_rectangle(self, event_x, event_y):
140 cairo_context = self.get_context()
141 cairo_context.move_to(self.x_press, self.y_press)
142 cairo_context.line_to(self.x_press, event_y)
143 cairo_context.line_to(event_x, event_y)
144 cairo_context.line_to(event_x, self.y_press)
145 cairo_context.close_path()
146 self._path = cairo_context.copy_path()
147
148 def _reset_temp_points(self):
149 self._path = None
150 self.x_press = -1.0
151 self.y_press = -1.0
152
153 ############################################################################
154
155 def build_operation(self, is_preview):
156 if is_preview:
157 eraser_type = 'solid'
158 else:
159 eraser_type = self._eraser_type
160 operation = {
161 'tool_id': self.id,
162 'is_preview': is_preview,
163 'line_width': self.tool_width,
164 'line_cap': self._cap_id,
165 'line_join': self._join_id,
166 'replacement': self._rgba,
167 'censor-type': eraser_type,
168 'censor-shape': self._eraser_shape,
169 'antialias': self._use_antialias,
170 'path': self._path
171 }
172 return operation
173
174 def do_tool_operation(self, operation):
175 if operation['path'] is None:
176 return
177 cairo_context = self.start_tool_operation(operation)
178 cairo_context.set_operator(cairo.Operator.SOURCE)
179 censor_type = operation['censor-type']
180
181 if censor_type == 'solid':
182 cairo_context.set_source_rgba(*operation['replacement'])
183 if operation['censor-shape'] == 'rectangle':
184 cairo_context.append_path(operation['path'])
185 cairo_context.fill()
186 else:
187 cairo_context.set_line_cap(cairo.LineCap.ROUND)
188 cairo_context.set_line_join(cairo.LineJoin.ROUND)
189 cairo_context.set_line_width(operation['line_width'])
190 cairo_context.append_path(operation['path'])
191 cairo_context.stroke()
192 return
193 else:
194 cairo_context.append_path(operation['path'])
195
196 [r0, r1, r2, r3] = cairo_context.path_extents()
197 [r0, r1, r2, r3] = [int(r0), int(r1), int(r2), int(r3)]
198 width = r2 - r0
199 height = r3 - r1
200 surface = cairo.ImageSurface(cairo.Format.ARGB32, width, height)
201 ccontext2 = cairo.Context(surface)
202 ccontext2.set_source_surface(self.get_surface(), -1 * r0, -1 * r1)
203 ccontext2.paint()
204 scale = self.scale_factor()
205 surface.set_device_scale(scale, scale)
206
207 b_rad = min(15, int(min(width, height) / 4))
208 b_dir = BlurDirection.BOTH
209 shuffle_intensity = int((width * height) / 2)
210 if censor_type == 'mosaic':
211 bs = utilities_blur_surface(surface, b_rad, BlurType.TILES, b_dir)
212 elif censor_type == 'blur':
213 bs = utilities_blur_surface(surface, b_rad, BlurType.PX_BOX, b_dir)
214 elif censor_type == 'shuffle':
215 bs = self._shuffle_pixels(surface, shuffle_intensity)
216 elif censor_type == 'mixed':
217 bs = self._shuffle_pixels(surface, shuffle_intensity / 2)
218 bs = utilities_blur_surface(bs, b_rad, BlurType.CAIRO_REPAINTS, b_dir)
219
220 cairo_context.clip()
221 # XXX this ^ doesn't work with the 'pencil' shape, which forces me to
222 # disable the 'eraser-type' option in this case
223 cairo_context.set_source_surface(bs, r0, r1)
224 cairo_context.paint()
225
226 ############################################################################
227
228 def _shuffle_pixels(self, surface, iterations):
229 w = surface.get_width()
230 h = surface.get_height()
231 channels = 4 # ARGB
232 if w <= 1 or h <= 1:
233 return surface
234
235 pixels = surface.get_data()
236
237 random.seed(1)
238 while iterations > 0:
239 iterations = iterations - 1
240 self._shuffle_one_iteration(w, h, channels, pixels)
241 return surface
242
243 def _shuffle_one_iteration(self, w, h, channels, pixels):
244 pix1_x = random.randint(0, w - 1)
245 pix1_y = random.randint(0, h - 1)
246
247 # Get data for a first pixel
248 cur_pixel = (pix1_y * w + pix1_x) * channels
249 a1 = pixels[cur_pixel + 0]
250 r1 = pixels[cur_pixel + 1]
251 g1 = pixels[cur_pixel + 2]
252 b1 = pixels[cur_pixel + 3]
253
254 pix2_x = random.randint(0, w - 1)
255 pix2_y = random.randint(0, h - 1)
256
257 # Get data for a second pixel
258 cur_pixel = (pix2_y * w + pix2_x) * channels
259 a2 = pixels[cur_pixel + 0]
260 r2 = pixels[cur_pixel + 1]
261 g2 = pixels[cur_pixel + 2]
262 b2 = pixels[cur_pixel + 3]
263
264 # Data of the 1st pixel is written in the 2nd one
265 pixels[cur_pixel + 0] = a1
266 pixels[cur_pixel + 1] = r1
267 pixels[cur_pixel + 2] = g1
268 pixels[cur_pixel + 3] = b1
269
270 # Data of the 2nd pixel is written in the 1st one
271 cur_pixel = (pix1_y * w + pix1_x) * channels
272 pixels[cur_pixel + 0] = a2
273 pixels[cur_pixel + 1] = r2
274 pixels[cur_pixel + 2] = g2
275 pixels[cur_pixel + 3] = b2
276
277 ############################################################################
278 ################################################################################
279