Debian Codegraph @

src/tools/selection_tools/abstract_select.py

raw symbols SCIP
1 # abstract_select.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
19 from gi.repository import Gtk
20 from .abstract_tool import AbstractAbstractTool
21 from .optionsbar_selection import OptionsBarSelection
22 from .utilities_colors import utilities_gdk_rgba_to_normalized_array
23 from .utilities_overlay import utilities_show_overlay_on_context
24 from .selection_manager import NoSelectionPixbufException
25
26 class AbstractSelectionTool(AbstractAbstractTool):
27 __gtype_name__ = 'AbstractSelectionTool'
28
29 def __init__(self, tool_id, label, icon_name, window, **kwargs):
30 super().__init__(tool_id, label, icon_name, window)
31 self.menu_id = 2
32 self.accept_selection = True
33
34 self._future_pixbuf = None
35 self.x_press = 0
36 self.y_press = 0
37 self.local_dx = 0
38 self.local_dy = 0
39 self.operation_type = None # 'op-define'
40
41 self.load_tool_action_enum('selection-color', 'last-delete-replace')
42 self.add_tool_action_boolean('selection-extract', False)
43
44 ############################################################################
45 # UI implementations #######################################################
46
47 def get_options_label(self):
48 return _("Selection")
49
50 def get_editing_tips(self):
51 if self.selection_is_active():
52 label_tip = _("Drag the selection or right-click on the canvas")
53 else:
54 label_tip = _("Select an area or right-click on the canvas")
55 return [label_tip]
56
57 def get_options_model(self):
58 builder = Gtk.Builder.new_from_resource(self.UI_PATH + 'selection.ui')
59 return builder.get_object('options-menu')
60
61 def try_build_pane(self):
62 self.pane_id = 'selection'
63 self.window.options_manager.try_add_bottom_pane(self.pane_id, self)
64
65 def build_bottom_pane(self):
66 return OptionsBarSelection(self.window)
67
68 ############################################################################
69 # Lifecycle implementations ################################################
70
71 def give_back_control(self, preserve_selection):
72 self.get_selection().hide_popovers()
73 # TODO if the selection hasn't been used, nothing should be applied
74 if not preserve_selection:
75 self.unselect_and_apply()
76
77 # def on_tool_selected(self, *args):
78 # pass
79
80 # def on_tool_unselected(self, *args):
81 # pass
82
83 def cancel_ongoing_operation(self):
84 pass # XXX really ?
85
86 def has_ongoing_operation(self):
87 return False
88
89 ############################################################################
90 ############################################################################
91
92 def _get_press_behavior(self, event):
93 if event.button == 3:
94 return 'menu'
95 elif not self.selection_is_active():
96 return 'define'
97 elif self.get_selection().point_is_in_selection(self.x_press, self.y_press):
98 return 'drag'
99 else:
100 return 'cancel'
101
102 def press_define(self, event_x, event_y):
103 pass # implemented by actual tools
104
105 def motion_define(self, event_x, event_y, render):
106 pass # implemented by actual tools
107
108 def release_define(self, surface, event_x, event_y):
109 pass # implemented by actual tools
110
111 ############################################################################
112 # Signal callbacks implementations #########################################
113
114 def on_press_on_area(self, event, surface, event_x, event_y):
115 self.x_press = event_x
116 self.y_press = event_y
117 self.behavior = self._get_press_behavior(event)
118 # print('press', self.behavior)
119 if self.behavior == 'drag':
120 self.cursor_name = 'grabbing'
121 self.window.set_cursor(True)
122 elif self.behavior == 'define':
123 self.press_define(event_x, event_y)
124 elif self.behavior == 'cancel':
125 self.unselect_and_apply()
126 self.restore_pixbuf()
127 self.non_destructive_show_modif()
128
129 def on_motion_on_area(self, event, surface, event_x, event_y, render=True):
130 if self.behavior == 'define':
131 self.motion_define(event_x, event_y, render)
132 elif render and self.behavior == 'drag':
133 self._preview_drag_to(event_x, event_y)
134
135 def _preview_drag_to(self, event_x, event_y):
136 self.local_dx = event_x - self.x_press
137 self.local_dy = event_y - self.y_press
138 self.non_destructive_show_modif()
139
140 def on_unclicked_motion_on_area(self, event, surface):
141 x, y = self.get_image().get_event_coords(event)
142 if not self.selection_is_active():
143 self.cursor_name = 'cross'
144 elif self.get_selection().point_is_in_selection(x, y):
145 self.cursor_name = 'grab'
146 else:
147 self.cursor_name = 'cross'
148 self.window.set_cursor(True)
149
150 def on_release_on_area(self, event, surface, event_x, event_y):
151 if event.button == 3:
152 if not self.get_selection().is_active:
153 self.get_selection().set_coords(True, event_x, event_y)
154 # TODO je ne devrais jamais appeler cette méthode ^ ici
155 self.get_selection().set_popovers_position(event.x, event.y)
156 self.get_selection().show_popover()
157 return
158 self.restore_pixbuf()
159 if self.behavior == 'define':
160 self.release_define(surface, event_x, event_y)
161 elif self.behavior == 'drag':
162 self._apply_drag_to(event_x, event_y)
163
164 def on_draw_above(self, area, ccontext):
165 if not self.selection_is_active():
166 return
167 ldx = self.local_dx
168 ldy = self.local_dy
169 self.get_selection().show_selection_on_surface(ccontext, True, ldx, ldy)
170 dragged_path = self.get_selection().get_path_with_scroll(ldx, ldy)
171 # ^ Method not really use elsewhere, could it be private?
172 thickness = self.get_overlay_thickness()
173 utilities_show_overlay_on_context(ccontext, dragged_path, thickness)
174
175 ############################################################################
176 # Pre-loading the selection manager with non-essential data ################
177
178 # In the first phase of the tool execution (pre-building operations), the
179 # code should never call methods from `self.get_selection().*` aside of:
180 # - the getters (safe by definition)
181 # - the things to show/hide popovers (no actual effect on the image)
182 # - the `set_future_*` methods, which are designed to preload data whose
183 # values don't have any impact on the following operations, but which should
184 # stored image-wide anyway (to avoid inconsistencies when switching to other
185 # tabs and then switching back, for example).
186 #
187 # XXX c'est faux le préchargement des coordonnées ça a un réel impact
188
189 def _pre_load_coords(self, x, y):
190 self.get_selection().set_future_coords(x, y)
191
192 def _pre_load_path(self, path, resync_coords=True):
193 self.get_selection().set_future_path(path, resync_coords)
194
195 def _build_rectangle_path(self, press_x, press_y, release_x, release_y):
196 """Build rectangle path and pre-load it in the selection manager. This
197 is used in `self.select_all` (abstract, here), and in the "rectangle
198 selection" implementation."""
199 # XXX could be in the selection manager?
200 x0 = min(press_x, release_x)
201 y0 = min(press_y, release_y)
202 x1 = max(press_x, release_x)
203 y1 = max(press_y, release_y)
204 w = x1 - x0
205 h = y1 - y0
206 if w <= 0 or h <= 0:
207 return
208 self._pre_load_coords(x0, y0)
209 cairo_context = self.get_context()
210 cairo_context.new_path()
211 cairo_context.move_to(x0, y0)
212 cairo_context.line_to(x1, y0)
213 cairo_context.line_to(x1, y1)
214 cairo_context.line_to(x0, y1)
215 cairo_context.close_path()
216 self._pre_load_path(cairo_context.copy_path(), False)
217
218 ############################################################################
219 # Operations producing methods #############################################
220
221 def _apply_drag_to(self, event_x, event_y):
222 x = self.get_selection().selection_x
223 y = self.get_selection().selection_y
224 fx = x + event_x - self.x_press
225 fy = y + event_y - self.y_press
226 self._pre_load_coords(fx, fy)
227
228 self.operation_type = 'op-drag'
229 operation = self.build_operation()
230 self.do_tool_operation(operation)
231 self.operation_type = 'op-define'
232
233 def select_all(self):
234 total_w = self.get_main_pixbuf().get_width()
235 total_h = self.get_main_pixbuf().get_height()
236 self._build_rectangle_path(0, 0, total_w, total_h)
237 self.operation_type = 'op-define'
238 operation = self.build_operation()
239 self.apply_operation(operation)
240 self.get_selection().show_popover()
241
242 def delete_selection(self):
243 self.operation_type = 'op-delete'
244 operation = self.build_operation()
245 self.apply_operation(operation)
246 self.operation_type = 'op-define'
247
248 def import_selection(self, pixbuf):
249 self.unselect_and_apply()
250 self._future_pixbuf = pixbuf
251 self.operation_type = 'op-import'
252
253 sx = self.get_selection().selection_x
254 sy = self.get_selection().selection_y
255 # when it's 0 and 0, it's pretty hard for the user to understand that
256 # there is an active selection, but changing the coords here sucks, it
257 # would be a pretty bad design, breaking the rules i've decided
258 # concerning interactions with the selection manager.
259 self._pre_load_coords(sx, sy)
260
261 operation = self.build_operation()
262 self.apply_operation(operation)
263 self.operation_type = 'op-define'
264
265 def replace_canvas(self):
266 self.operation_type = 'op-replace-canvas'
267 # XXX it's copied so many times?! ugly but seems necessary
268 self._future_pixbuf = self.get_selection_pixbuf().copy()
269 operation = self.build_operation()
270 self.apply_operation(operation)
271 self.operation_type = 'op-define'
272
273 def invert_selection(self):
274 pass # TODO
275
276 def unselect_and_apply(self):
277 # Pre-loading the coords is NEEDED because we may "unselect_and_apply" a
278 # selection which was defined by a selection manager in very different
279 # state, but was consumed by an "undo".
280 sx = self.get_selection().selection_x
281 sy = self.get_selection().selection_y
282 self._pre_load_coords(sx, sy)
283
284 self.operation_type = 'op-apply'
285 operation = self.build_operation()
286 self.apply_operation(operation)
287 self.operation_type = 'op-define'
288 self.cursor_name = 'cross'
289 self.window.set_cursor(True)
290
291 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
292
293 def build_operation(self):
294 """Operation is built from the operation_type, the current tool's
295 'future_pixbuf' attribute, and '_future_*' attributes from the
296 selection manager that were previously set."""
297 if self._future_pixbuf is None: # Usual case
298 pixbuf = None
299 else: # Case of importation only
300 pixbuf = self._future_pixbuf.copy()
301 self._future_pixbuf = None
302
303 replacement_type = self.get_option_value('selection-color')
304 # FIXME the result is questionable when there was alpha in the area...
305 if replacement_type == 'initial':
306 gdk_rgba = self.get_image().get_initial_rgba()
307 color = utilities_gdk_rgba_to_normalized_array(gdk_rgba)
308 elif replacement_type == 'secondary':
309 gdk_rgba = self.window.options_manager.get_right_color()
310 color = utilities_gdk_rgba_to_normalized_array(gdk_rgba)
311 else: # == 'alpha':
312 color = [1.0, 1.0, 1.0, 0.0]
313 # XXX the replacement is performed when the selection is defined, which
314 # isn't the most intuitive behaviour: if the user sees a wrong
315 # replacement color and changes the value to fix his manipulation, it's
316 # already too late
317
318 operation = {
319 'tool_id': self.id,
320 'operation_type': self.operation_type,
321 'initial_path': self.get_selection().get_future_path(),
322 'replacement': color,
323 'extract': self.get_option_value('selection-extract'),
324 'pixbuf': pixbuf,
325 'pixb_x': self.get_selection().get_future_coords()[0],
326 'pixb_y': self.get_selection().get_future_coords()[1],
327 'local_dx': self.local_dx,
328 'local_dy': self.local_dy,
329 }
330 return operation
331
332 ############################################################################
333 # Operations consuming methods #############################################
334
335 def _op_import(self, op):
336 if op['pixbuf'] is None:
337 raise NoSelectionPixbufException()
338 # XXX does it run cleanly after the "return" to the calling method?
339 # (compared to a more normal return)
340 self._pre_load_coords(op['pixb_x'], op['pixb_y'])
341 self.get_selection().set_coords(False, op['pixb_x'], op['pixb_y'])
342 self.get_selection().set_pixbuf(op['pixbuf'].copy())
343
344 def _op_replace_canvas(self, op):
345 if op['pixbuf'] is None:
346 raise NoSelectionPixbufException()
347 self.get_image().set_main_pixbuf(op['pixbuf'].copy())
348 self.get_image().use_stable_pixbuf()
349 self.get_selection().reset(True)
350 self.get_selection().reset_future_data()
351
352 def _op_clean(self, operation):
353 if operation['initial_path'] is None:
354 return # The user double-clicked: there is no path, and it's normal
355 cairo_context = self.get_context()
356 cairo_context.new_path()
357 cairo_context.append_path(operation['initial_path'])
358 replacement_rgba = operation['replacement']
359 cairo_context.set_operator(cairo.Operator.SOURCE)
360 cairo_context.set_source_rgba(*replacement_rgba)
361 cairo_context.fill()
362 cairo_context.set_operator(cairo.Operator.OVER)
363
364 def _op_drag(self, op):
365 # print("drag to :", op['pixb_x'], op['pixb_y'])
366 self.get_selection().set_coords(False, op['pixb_x'], op['pixb_y'])
367 self.non_destructive_show_modif()
368
369 def _op_define(self, op):
370 if op['initial_path'] is None:
371 return # The user double-clicked: there is no path, and it's normal
372 self.get_selection().set_coords(True, op['pixb_x'], op['pixb_y'])
373 if op['extract']:
374 replacement = op['replacement']
375 else:
376 replacement = None
377 self.get_selection().load_from_path(op['initial_path'], replacement)
378
379 def _op_apply(self, operation):
380 cairo_context = self.get_context()
381 self.get_selection().show_selection_on_surface(cairo_context, False, \
382 operation['local_dx'], operation['local_dy'])
383 self.get_selection().reset(True)
384 self.get_selection().reset_future_data()
385
386 ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ###
387
388 def do_tool_operation(self, operation):
389 self.start_tool_operation(operation)
390 # print('operation_type', operation['operation_type'])
391 if operation['operation_type'] == 'op-delete':
392 # Opération instantanée (sans preview), correspondant à une action
393 # de type "clic-droit > couper" ou "clic-droit > supprimer".
394 # On réinitialise le selection_manager.
395 self.get_selection().reset(True)
396 elif operation['operation_type'] == 'op-import':
397 # Opération instantanée (sans preview), correspondant à une action
398 # de type "clic-droit > importer" ou "clic-droit > coller".
399 # On charge un pixbuf dans le selection_manager.
400 self._op_import(operation)
401 elif operation['operation_type'] == 'op-replace-canvas':
402 # TODO commentaire
403 self._op_replace_canvas(operation)
404 elif operation['operation_type'] == 'op-define':
405 # Opération instantanée (sans preview), correspondant à une
406 # sélection (rectangulaire ou non) par définition d'un path.
407 # On charge un pixbuf dans le selection_manager.
408 self._op_define(operation)
409 self._op_clean(operation)
410 elif operation['operation_type'] == 'op-drag':
411 # Prévisualisation d'opération, correspondant à la définition d'une
412 # sélection (rectangulaire ou non) par construction d'un path.
413 # On modifie les coordonnées connues du selection_manager.
414 self.local_dx = 0
415 self.local_dy = 0
416 self._op_drag(operation)
417 elif operation['operation_type'] == 'op-apply':
418 # Opération instantanée correspondant à l'aperçu de l'op-drag, donc
419 # la définition d'une sélection (rectangulaire ou non) par
420 # construction d'un path qui sera "fusionné" au main_pixbuf.
421 # On modifie les coordonnées connues du selection_manager.
422 if self.get_selection_pixbuf() is None:
423 return
424 self._op_drag(operation)
425 self._op_apply(operation)
426
427 ############################################################################
428 ################################################################################
429