Debian Codegraph @

src/tools/classic_tools/tool_text.py

raw symbols SCIP
1 # tool_text.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, GLib, Pango, PangoCairo
20 from .abstract_classic_tool import AbstractClassicTool
21
22 class ToolText(AbstractClassicTool):
23 __gtype_name__ = 'ToolText'
24
25 def __init__(self, window, **kwargs):
26 super().__init__('text', _("Text"), 'tool-text-symbolic', window)
27
28 self._should_cancel = False
29 self._last_click_btn = 1
30
31 self.add_tool_action_simple('text-set-font', self._set_font)
32 self.add_tool_action_boolean('text-bold', False)
33 self.add_tool_action_boolean('text-italic', False)
34
35 self._background_id = self.load_tool_action_enum('text-background', \
36 'last-text-background')
37 self._font_fam_name = self.load_tool_action_enum('text-active-family', \
38 'last-font-name')
39
40 # XXX actions sensitivity?
41 self.add_tool_action_simple('text-cancel', self._on_cancel)
42 self.add_tool_action_simple('text-preview', self._force_refresh)
43 self.add_tool_action_simple('text-insert', self._on_insert_text)
44
45 builder = Gtk.Builder().new_from_resource(self.UI_PATH + 'tool-text.ui')
46 # Widgets for text insertion
47 self._popover = builder.get_object('insertion-popover')
48 self._entry = builder.get_object('entry')
49 self._entry.set_size_request(100, 50)
50 self._entry.get_buffer().connect('changed', self._preview_text)
51 self._hide_entry()
52
53 ############################################################################
54 # Options ##################################################################
55
56 def _set_font(self, *args):
57 dialog = Gtk.FontChooserDialog(show_preview_entry=False)
58 dialog.set_level(Gtk.FontChooserLevel.FAMILY)
59 dialog.set_font(self._font_fam_name)
60
61 # for f in PangoCairo.font_map_get_default().list_families():
62 # print(f.get_name())
63
64 try:
65 status = dialog.run()
66 # ^ FIXME #479
67 except Exception as ex:
68 # probablement qu'on ne catchera rien
69 pass
70 if(status == Gtk.ResponseType.OK):
71 self._font_fam_name = dialog.get_font_family().get_name()
72 # print(dialog.get_font())
73 font_gvar = GLib.Variant.new_string(self._font_fam_name)
74 self.window.lookup_action('text-active-family').set_state(font_gvar)
75 self._preview_text()
76 dialog.destroy()
77 # TODO update le editing tip !!
78
79 def _set_font_options(self, *args):
80 # XXX incomplete? OBLIQUE exists
81 self._is_italic = self.get_option_value('text-italic')
82 self._is_bold = self.get_option_value('text-bold')
83
84 def _set_background_style(self, *args):
85 self._background_id = self.get_option_value('text-background')
86
87 def get_options_label(self):
88 return _("Text options")
89
90 def get_editing_tips(self):
91 self._set_font_options()
92 self._set_background_style()
93
94 # get_editing_tips is likely called because an option changed
95 self._force_refresh()
96
97 label_options = self.label + " - " + self._font_fam_name
98 if self._background_id != 'none':
99 bg_label = {
100 'none': _("No background"),
101 'shadow': _("Shadow"),
102 'thin-outline': _("Thin outline"),
103 'thick-outline': _("Thick outline"),
104 'rectangle': _("Rectangle background"),
105 }[self._background_id]
106 label_options += " - " + bg_label
107
108 return [label_options]
109
110 ############################################################################
111
112 def on_tool_selected(self):
113 super().on_tool_selected()
114 self._last_click_btn = 1
115
116 def on_tool_unselected(self):
117 self.set_action_sensitivity('paste', True)
118 self.set_action_sensitivity('select_all', True)
119 self.set_action_sensitivity('selection_cut', True)
120 self.set_action_sensitivity('selection_copy', True)
121
122 def give_back_control(self, preserve_selection):
123 if self._should_cancel:
124 self._on_cancel()
125
126 def force_text_tool(self, string):
127 self.select_flowbox_child()
128 self.set_common_values(self._last_click_btn, 100, 100)
129 self._open_popover_at(100, 100)
130 self._set_string(string)
131
132 def _set_string(self, string):
133 if string is None:
134 string = ''
135 self._entry.get_buffer().set_text(string, -1)
136
137 ############################################################################
138
139 def on_release_on_area(self, event, surface, event_x, event_y):
140 self._last_click_btn = event.button
141 self._should_cancel = True
142 self.set_common_values(self._last_click_btn, event_x, event_y)
143 self._open_popover_at(event.x, event.y)
144
145 # XXX could there be a better way to move the text ?
146 def _open_popover_at(self, x, y):
147 rectangle = Gdk.Rectangle()
148 rectangle.x = x
149 rectangle.y = y
150 rectangle.height = 1
151 rectangle.width = 1
152 self._popover.set_pointing_to(rectangle)
153 self._popover.set_relative_to(self.get_image())
154 self._popover.popup()
155 self._entry.grab_focus()
156 self._preview_text()
157
158 # Usual text entry shortcuts don't work otherwise
159 self.set_action_sensitivity('paste', False)
160 self.set_action_sensitivity('select_all', False)
161 self.set_action_sensitivity('selection_cut', False)
162 self.set_action_sensitivity('selection_copy', False)
163
164 def _hide_entry(self):
165 self._popover.popdown()
166
167 def _force_refresh(self, *args):
168 self.set_common_values(self._last_click_btn, self.x_press, self.y_press)
169 self._preview_text()
170
171 def _on_insert_text(self, *args):
172 self._hide_entry()
173 if self._has_current_text():
174 operation = self.build_operation()
175 self.apply_operation(operation)
176 self._set_string('')
177 self.set_action_sensitivity('paste', True)
178 self.set_action_sensitivity('select_all', True)
179 self.set_action_sensitivity('selection_cut', True)
180 self.set_action_sensitivity('selection_copy', True)
181
182 def _has_current_text(self):
183 b = self._entry.get_buffer()
184 self.text_string = b.get_text(b.get_start_iter(), b.get_end_iter(), False)
185 if self.text_string == '':
186 self.restore_pixbuf()
187 self.non_destructive_show_modif()
188 return False
189 else:
190 return True
191
192 def _preview_text(self, *args):
193 if self._has_current_text():
194 operation = self.build_operation()
195 self.do_tool_operation(operation)
196
197 def _on_cancel(self, *args):
198 self._hide_entry()
199 self._set_string('')
200 self._should_cancel = False
201
202 ############################################################################
203
204 def build_operation(self):
205 operation = {
206 'tool_id': self.id,
207 'rgba1': self.main_color,
208 'rgba2': self.secondary_color,
209 'font_fam': self._font_fam_name,
210 'is_italic': self._is_italic,
211 'is_bold': self._is_bold,
212 'font_size': self.tool_width,
213 'antialias': self._use_antialias,
214 'x': self.x_press,
215 'y': self.y_press,
216 'background': self._background_id,
217 'text': self.text_string
218 }
219 return operation
220
221 def do_tool_operation(self, operation):
222 cairo_context = self.start_tool_operation(operation)
223
224 font_fam = operation['font_fam']
225 font_size = operation['font_size'] * 2
226 entire_text = operation['text']
227 background_color = operation['rgba2']
228 text_x = operation['x']
229 text_y = operation['y']
230
231 font_description_string = font_fam
232 if operation['is_italic']:
233 font_description_string += " Italic"
234 if operation['is_bold']:
235 font_description_string += " Bold"
236 font_description_string += " " + str(font_size)
237 font = Pango.FontDescription(font_description_string)
238
239 p_context = PangoCairo.create_context(cairo_context)
240 layout = Pango.Layout(p_context)
241 layout.set_font_description(font)
242
243 if not operation['antialias']:
244 font_options = cairo.FontOptions()
245 font_options.set_antialias(cairo.Antialias.NONE)
246 font_options.set_hint_metrics(cairo.HintMetrics.OFF)
247 font_options.set_hint_style(cairo.HintStyle.FULL)
248 PangoCairo.context_set_font_options(p_context, font_options)
249
250 ########################################################################
251 # Draw background ######################################################
252
253 if operation['background'] == 'rectangle':
254 lines = entire_text.split('\n')
255 line_y = text_y
256 for line_text in lines:
257 line_y = self._op_bg_rectangle(cairo_context, layout, \
258 background_color, text_x, line_y, line_text)
259 elif operation['background'] == 'shadow':
260 dist = max(min(int(font_size/16), 4), 1)
261 cairo_context.set_source_rgba(*background_color)
262 self._show_text_at_coords(cairo_context, layout, entire_text, \
263 text_x + dist, text_y + dist)
264 elif operation['background'] == 'thin-outline':
265 cairo_context.set_source_rgba(*background_color)
266 dist = min(int(font_size/16), 10)
267 dist = max(dist, 2)
268 for dx in range(-dist, dist):
269 for dy in range(-dist, dist):
270 if abs(dx) + abs(dy) <= dist * 1.5:
271 self._show_text_at_coords(cairo_context, layout, \
272 entire_text, text_x + dx, text_y + dy)
273 # these `for`s and this `if` should outline with an octogonal shape,
274 # which is close enough to a smooth round outline imho.
275 elif operation['background'] == 'thick-outline':
276 cairo_context.set_source_rgba(*background_color)
277 dist = int(font_size/10)
278 dist = max(dist, 2)
279 for dx in range(-dist, dist):
280 for dy in range(-dist, dist):
281 if abs(dx) + abs(dy) <= dist * 1.5:
282 self._show_text_at_coords(cairo_context, layout, \
283 entire_text, text_x + dx, text_y + dy)
284 # looks better, but so much computation for bullshit...
285
286 ########################################################################
287 # Draw text ############################################################
288
289 cairo_context.set_source_rgba(*operation['rgba1'])
290 self._show_text_at_coords(cairo_context, layout, entire_text, \
291 text_x, text_y)
292
293 self.non_destructive_show_modif()
294
295 def _show_text_at_coords(self, cairo_c, pango_l, text, text_x, text_y):
296 """Use a pango layout (pango_l) to show a line of text (text) on a cairo
297 context (cairo_c) at given coordinates (text_x, text_y)."""
298 cairo_c.move_to(text_x, text_y)
299 pango_l.set_text(text, -1)
300 PangoCairo.update_layout(cairo_c, pango_l)
301 PangoCairo.show_layout(cairo_c, pango_l)
302
303 def _op_bg_rectangle(self, context, layout, c2, text_x, line_y, line_text):
304 # The text is first "displayed" in a transparent color…
305 context.set_source_rgba(0.0, 0.0, 0.0, 0.0)
306 self._show_text_at_coords(context, layout, line_text, text_x, line_y)
307 # …so we can get the size of the displayed line…
308 ink_rect, logical_rect = layout.get_pixel_extents()
309 delta_y = logical_rect.height
310 # …and draw the background rectangle with the correct size.
311 context.rel_line_to(0, delta_y)
312 context.rel_line_to(logical_rect.width, 0)
313 context.rel_line_to(0, -1 * delta_y)
314 context.close_path()
315 context.set_source_rgba(*c2)
316 context.fill()
317 context.stroke()
318 # The returned value will be used as the vertical coord of the next line
319 return line_y + delta_y
320
321 ############################################################################
322 ################################################################################
323