Debian Codegraph @

src/tools/abstract_tool.py

raw symbols SCIP
1 # abstract_tool.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, Gdk
20
21 class WrongToolIdException(Exception):
22 def __init__(self, expected, actual):
23 # Context: an error message
24 msg = _("Can't start operation: wrong tool id (expected {0}, got {1})")
25 super().__init__(msg.format(expected, actual))
26
27 ################################################################################
28
29 class AbstractAbstractTool():
30 """Super-class implemented and extended by all tools."""
31
32 __gtype_name__ = 'AbstractAbstractTool'
33 UI_PATH = '/com/github/maoschanz/drawing/tools/ui/'
34
35 def __init__(self, tool_id, label, icon_name, window, **kwargs):
36 self.window = window
37 # The tool's identity
38 self.id = tool_id
39 self.menu_id = 0
40 self.label = self._mnemo_label = label
41 self._mnemo_char = ""
42 self._icon_name = icon_name
43 # The options it supports
44 self.accept_selection = False
45 self.use_color = False
46 self.use_operator = False
47 # The tool's state
48 self.cursor_name = 'cell'
49 self._ongoing_operation = False
50 self._modifier_keys = []
51 # Once everything is set, build the UI
52 self.try_build_pane()
53
54 ############################################################################
55 # Utilities managing actions for tool's options ############################
56
57 def add_tool_action_simple(self, action_name, callback):
58 """Convenient wrapper method adding a stateless action to the window. It
59 will be named 'action_name' (string) and activating the action will
60 trigger the method 'callback'."""
61 # XXX allow to set shortcuts here?
62 self.window.add_action_simple(action_name, callback)
63
64 def add_tool_action_boolean(self, action_name, default):
65 self.window.options_manager.add_option_boolean(action_name, default)
66
67 def add_tool_action_enum(self, action_name, default):
68 self.window.options_manager.add_option_enum(action_name, default)
69
70 def load_tool_action_boolean(self, action_name, key_name):
71 om = self.window.options_manager
72 return om.add_option_from_bool_key(action_name, key_name)
73
74 def load_tool_action_enum(self, action_name, key_name):
75 om = self.window.options_manager
76 return om.add_option_from_enum_key(action_name, key_name)
77
78 def get_option_value(self, action_name):
79 return self.window.options_manager.get_value(action_name)
80
81 def set_action_sensitivity(self, action_name, state):
82 self.window.lookup_action(action_name).set_enabled(state)
83
84 def update_actions_state(self):
85 self.set_action_sensitivity('main_color', self.use_color)
86 self.set_action_sensitivity('secondary_color', self.use_color)
87 self.set_action_sensitivity('exchange_color', self.use_color)
88 self.set_action_sensitivity('cairo_operator', self.use_operator)
89
90 self.set_action_sensitivity('cancel_transform', False)
91 self.set_action_sensitivity('apply_transform', False)
92
93 def get_settings(self):
94 return self.window.options_manager._tools_gsettings
95
96 def update_modifier_state(self, event_state):
97 modifier_keys = []
98 # CONTROL_MASK can't be used, because it already has an effect app-wide.
99 if (event_state & Gdk.ModifierType.SHIFT_MASK) == Gdk.ModifierType.SHIFT_MASK:
100 modifier_keys.append('SHIFT')
101 if (event_state & Gdk.ModifierType.MOD1_MASK) == Gdk.ModifierType.MOD1_MASK:
102 modifier_keys.append('ALT')
103 self._modifier_keys = modifier_keys
104
105 ############################################################################
106 # Various utilities ########################################################
107
108 def show_error(self, error_text):
109 self.window.reveal_message(error_text)
110
111 def get_tooltip(self, event_x, event_y, motion_behavior):
112 return None
113
114 ############################################################################
115 # Bottom pane and menubar integration ######################################
116
117 def try_build_pane(self):
118 pass
119
120 def build_bottom_pane(self):
121 return None
122
123 def on_apply_transform_tool_operation(self, *args):
124 pass # implemented only by transform tools
125
126 def on_cancel_transform_tool_operation(self, *args):
127 pass # implemented only by transform tools
128
129 def get_options_label(self):
130 return _("No options")
131
132 def adapt_to_window_size(self, available_width):
133 pass
134
135 def add_item_to_menu(self, tools_menu):
136 tools_menu.append(self._mnemo_label, 'win.active_tool::' + self.id)
137
138 def get_options_model(self):
139 """Returns a Gio.MenuModel corresponding to the tool's options. It'll be
140 shown in the menubar (if any) and in the bottom pane (if the tool's
141 bottom pane supports such a feature)."""
142 fpath = self.UI_PATH + 'tool-' + self.id + '.ui'
143 builder = Gtk.Builder.new_from_resource(fpath)
144 return builder.get_object('options-menu')
145
146 def get_options_widget(self):
147 """Returns a Gtk.Widget (normally a box) corresponding to the tool's
148 options. It'll be in the bottom pane (if the tool's bottom pane supports
149 such a feature) in replacement of the Gio.MenuModel if such a simple
150 menu can't provide all the features."""
151 return None
152
153 def get_editing_tips(self):
154 return [self.label]
155
156 ############################################################################
157 # Side pane ################################################################
158
159 def set_mnemonics(self, character):
160 self._mnemo_label = self.label.replace(character, "_" + character, 1)
161 self._mnemo_char = character.upper()
162
163 def build_flowbox_child(self, flowbox):
164 """Build the icon and its label for the sidebar."""
165 # The icon
166 if self.window.gsettings.get_boolean('big-icons'):
167 size = Gtk.IconSize.LARGE_TOOLBAR
168 else:
169 size = Gtk.IconSize.SMALL_TOOLBAR
170 image = Gtk.Image().new_from_icon_name(self._icon_name, size)
171 self._label_box = Gtk.Box( \
172 orientation=Gtk.Orientation.HORIZONTAL, \
173 spacing=8, \
174 margin=8 \
175 )
176 self._label_box.add(image)
177
178 # The readable label
179 label_widget = Gtk.Label(use_underline=True, label=self._mnemo_label)
180 self._label_box.add(label_widget)
181 self._label_box.show_all()
182
183 # The "mini-label" is shown only when pressing <Alt>
184 mini_label = Gtk.Label(use_underline=True, label="_" + self._mnemo_char)
185 self._label_box.add(mini_label)
186
187 flowbox.add(self._label_box)
188 self._fb_child = self._label_box.get_parent()
189
190 # The item's tooltip
191 if self._mnemo_char == "":
192 self._fb_child.set_tooltip_text(self.label)
193 else:
194 tooltip = self.label + " (Alt+" + self._mnemo_char + ")"
195 self._fb_child.set_tooltip_text(tooltip)
196
197 def select_flowbox_child(self, *args):
198 self.window.tools_flowbox.select_child(self._fb_child)
199
200 def is_flowbox_child_selected(self):
201 return self._fb_child.is_selected()
202
203 def set_show_label(self, label_visible):
204 label_widget = self._label_box.get_children()[1]
205 label_widget.set_visible(label_visible)
206 icon = self._label_box.get_children()[0]
207 if label_visible:
208 icon.set_halign(Gtk.Align.START)
209 else:
210 icon.set_halign(Gtk.Align.CENTER)
211
212 def update_icon_size(self):
213 image = self._label_box.get_children()[0]
214 if self.window.gsettings.get_boolean('big-icons'):
215 size = Gtk.IconSize.LARGE_TOOLBAR
216 else:
217 size = Gtk.IconSize.SMALL_TOOLBAR
218 image.set_from_icon_name(self._icon_name, size)
219
220 def show_only_mnemonics(self, should_show):
221 if self._mnemo_char == "":
222 return
223 label_widget = self._label_box.get_children()[1]
224 if label_widget.get_visible():
225 return
226 image = self._label_box.get_children()[0]
227 mini_label = self._label_box.get_children()[2]
228
229 image.set_visible(not should_show)
230 mini_label.set_visible(should_show)
231
232 ############################################################################
233 # Activation or not ########################################################
234
235 def on_tool_selected(self):
236 pass
237
238 def on_tool_unselected(self):
239 pass
240
241 def cancel_ongoing_operation(self):
242 """Reset the current tool when 'undo' is pressed while an operation has
243 been started but not applied."""
244 self.on_tool_unselected()
245 self.give_back_control(self.accept_selection) # XXX pas sûr
246 self.on_tool_selected()
247 self.restore_pixbuf()
248 self.non_destructive_show_modif()
249 self._ongoing_operation = False
250
251 def give_back_control(self, preserve_selection):
252 """Reset the tool's state well enough to allow for a new tool to start.
253 It should include unselecting/applying the selection if the next tool
254 doesn't support it."""
255 self.restore_pixbuf()
256 self.non_destructive_show_modif()
257
258 ############################################################################
259 # History ##################################################################
260
261 def has_ongoing_operation(self):
262 return self._ongoing_operation
263
264 def do_tool_operation(self, operation):
265 pass
266
267 def start_tool_operation(self, operation):
268 if operation['tool_id'] != self.id:
269 raise WrongToolIdException(operation['tool_id'], self.id)
270 self.restore_pixbuf()
271 self._ongoing_operation = True
272
273 def apply_operation(self, operation):
274 """Complete method to apply an operation: the operation is applied and
275 the image is updated as well as the state of actions."""
276 self.simple_apply_operation(operation)
277 self.get_image().update_actions_state()
278 self.get_image().update_history_sensitivity()
279
280 def simple_apply_operation(self, operation):
281 """Simpler apply_operation, for the 'rebuild from history' method."""
282 try:
283 self.do_tool_operation(operation)
284 self.get_image().add_to_history(operation)
285 except Exception as e:
286 self.show_error(str(e))
287 self._ongoing_operation = False
288 self.non_destructive_show_modif() # XXX nécessaire ?
289
290 ############################################################################
291 # Selection ################################################################
292
293 def get_selection(self):
294 return self.get_image().selection
295
296 def selection_is_active(self):
297 return self.get_selection().is_active
298
299 def get_selection_pixbuf(self):
300 return self.get_selection().get_pixbuf()
301
302 def get_overlay_thickness(self):
303 return (1 / self.get_image().zoom_level)
304
305 ############################################################################
306 # Image management #########################################################
307
308 def get_image(self):
309 return self.window.get_active_image()
310
311 def get_surface(self):
312 return self.get_image().get_surface()
313
314 def scale_factor(self):
315 return self.get_image().SCALE_FACTOR
316
317 def get_context(self):
318 return cairo.Context(self.get_surface())
319
320 def get_main_pixbuf(self):
321 return self.get_image().main_pixbuf
322
323 def non_destructive_show_modif(self):
324 self.get_image().update()
325
326 def restore_pixbuf(self):
327 self.get_image().use_stable_pixbuf()
328
329 ############################################################################
330 # Signals handling #########################################################
331
332 def on_press_on_area(self, event, surface, event_x, event_y):
333 pass
334
335 def on_motion_on_area(self, event, surface, event_x, event_y, render=True):
336 pass
337
338 def on_unclicked_motion_on_area(self, event, surface):
339 pass
340
341 def on_release_on_area(self, event, surface, event_x, event_y):
342 pass
343
344 def on_draw_above(self, area, cairo_context):
345 pass
346
347 ############################################################################
348 ################################################################################
349