Debian Codegraph @

src/tools/classic_tools/tool_paint.py

raw symbols SCIP
1 # tool_paint.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 Gdk
20 from .abstract_classic_tool import AbstractClassicTool
21 from .utilities_paths import utilities_get_magic_path
22 from .utilities_paths import utilities_get_rgba_for_xy
23
24 class ToolPaint(AbstractClassicTool):
25 __gtype_name__ = 'ToolPaint'
26
27 def __init__(self, window, **kwargs):
28 # Context: the name of a tool to fill an area of one color with an other
29 super().__init__('paint', _("Paint"), 'tool-paint-symbolic', window)
30 self._magic_path = None
31 self.use_size = False
32 self.add_tool_action_enum('paint_algo', 'replace')
33
34 def get_options_label(self):
35 return _("Painting options")
36
37 def get_editing_tips(self):
38 paint_algo = self.get_option_value('paint_algo')
39 if paint_algo == 'clipping':
40 return [_("Click on an area to replace its color by transparency")]
41 elif paint_algo == 'whole':
42 return [_("Click on the canvas to entirely paint it")]
43
44 label_warning1 = self.label + " - " + _("May not work for complex shapes")
45 label_warning2 = self.label + " - " + _("It will not work well if " + \
46 "the area's edges are blurry")
47 return [label_warning1, label_warning2]
48
49 ############################################################################
50
51 def on_press_on_area(self, event, surface, event_x, event_y):
52 self.set_common_values(event.button, event_x, event_y)
53
54 def on_release_on_area(self, event, surface, event_x, event_y):
55 # Guard clause: we can't paint outside of the surface
56 if event_x < 0 or event_x > surface.get_width() \
57 or event_y < 0 or event_y > surface.get_height():
58 return
59
60 self.old_color = utilities_get_rgba_for_xy(surface, event_x, event_y)
61
62 if self.get_option_value('paint_algo') == 'fill':
63 self._magic_path = utilities_get_magic_path(surface, event_x, \
64 event_y, self.window, 1)
65 elif self.get_option_value('paint_algo') == 'replace':
66 self._magic_path = utilities_get_magic_path(surface, event_x, \
67 event_y, self.window, 2)
68 else:
69 pass # == 'clipping' or == 'whole'
70
71 operation = self.build_operation(event_x, event_y)
72 self.apply_operation(operation)
73
74 ############################################################################
75
76 def build_operation(self, x, y):
77 operation = {
78 'tool_id': self.id,
79 'algo': self.get_option_value('paint_algo'),
80 # 'x': x,
81 # 'y': y,
82 'new_rgba': self.main_color,
83 'antialias': self._use_antialias,
84 'old_rgba': self.old_color,
85 'path': self._magic_path
86 }
87 return operation
88
89 def do_tool_operation(self, operation):
90 self.start_tool_operation(operation) # XXX expose antialiasing option?
91
92 if operation['algo'] == 'replace':
93 self._op_replace(operation)
94 elif operation['algo'] == 'whole':
95 self._op_whole(operation)
96 elif operation['algo'] == 'fill':
97 self._op_fill(operation)
98 else: # == 'clipping'
99 self._op_clipping(operation)
100
101 ############################################################################
102
103 def _op_whole(self, operation):
104 """Paint the entire image regardless of existing pixels"""
105 cairo_context = self.get_context()
106 cairo_context.set_source_rgba(*operation['new_rgba'])
107 cairo_context.paint()
108
109 def _op_fill(self, operation):
110 """Simple but ugly, and it's relying on the precision of the provided
111 path whose creation is based on shitty heurisctics."""
112 if operation['path'] is None:
113 return
114 cairo_context = self.get_context()
115 cairo_context.set_source_rgba(*operation['new_rgba'])
116 cairo_context.append_path(operation['path'])
117 # can_fill = cairo_context.in_fill(operation['x'], operation['y'])
118 # print(can_fill)
119 # if not can_fill:
120 # cairo_context.set_fill_rule(cairo.FillRule.EVEN_ODD)
121 # XXX doesn't work as i expected
122 cairo_context.fill()
123
124 def _op_replace(self, operation):
125 """Algorithmically less ugly than `_op_fill`, but the replacing strategy
126 itself doesn't handle (semi-) transparent colors correctly. Looks fine
127 when there is no alpha at all and the anti-aliasing is off."""
128 # In this example, the user paints in blue and clicks on X (red):
129 #
130 # rrrrrrrrrrrrrrrrrrrrrrrrr
131 # rrrgggggggggggggggggrrXrr
132 # rrrgaaaaaaaaaaaaaaagrrrrr
133 # rrrgaaaaaaaaaaaaaaagrrrrr
134 # rrrgggggggggggggggggrraaa
135 # rrrrrrrrrrrrrrrrrrrrrraaa
136 #
137 # All red pixels will be painted blue, but FIXME all the green ones too.
138 if operation['path'] is None:
139 return
140
141 # First, everything BUT the targeted area is erased
142 surface = self.get_surface()
143 cairo_context = cairo.Context(surface)
144 old_rgba = operation['old_rgba']
145 cairo_context.set_source_rgba(255, 255, 255, 1.0)
146 cairo_context.append_path(operation['path'])
147 cairo_context.set_operator(cairo.Operator.DEST_IN)
148 cairo_context.set_line_width(4) # ptêt too much mdr
149 cairo_context.set_antialias(cairo.Antialias.NONE)
150 cairo_context.stroke_preserve()
151 # cairo_context.fill_preserve()
152
153 # The result is loaded as the temp pixbuf…
154 self.get_image().set_temp_pixbuf(Gdk.pixbuf_get_from_surface(surface, \
155 0, 0, surface.get_width(), surface.get_height()))
156 # …where the targeted color is replaced by pure alpha
157 TOLERANCE = 10 # XXX uuugly
158 i = -1 * TOLERANCE
159 while i < TOLERANCE:
160 red = max(0, old_rgba[0]+i)
161 green = max(0, old_rgba[1]+i)
162 blue = max(0, old_rgba[2]+i)
163 red = int(min(255, red))
164 green = int(min(255, green))
165 blue = int(min(255, blue))
166 self._replace_temp_with_alpha(red, green, blue)
167 i = i+1
168
169 # The main pixbuf is restored, since its alterations were a side effect
170 # of this highly stupid algorithm
171 self.restore_pixbuf()
172 # We get a context from it again
173 cairo_context2 = self.get_context()
174
175 # The content of the path is cleared
176 cairo_context2.append_path(operation['path'])
177 cairo_context2.set_operator(cairo.Operator.CLEAR)
178 cairo_context2.set_source_rgba(255, 255, 255, 1.0)
179 cairo_context2.set_line_width(3) # ptêt too much mdr
180 cairo_context.set_antialias(cairo.Antialias.NONE)
181 cairo_context2.stroke_preserve()
182 cairo_context2.fill()
183
184 # The temp pixbuf (where "only" the pixels around the outline which are
185 # not in the targeted color still exist) is shown on top of the image
186 cairo_context2.set_operator(cairo.Operator.OVER)
187 Gdk.cairo_set_source_pixbuf(cairo_context2, \
188 self.get_image().temp_pixbuf, 0, 0)
189 cairo_context2.paint()
190 self.non_destructive_show_modif()
191
192 # The transparent pixels within the path are painted with the new color
193 cairo_context2.set_operator(cairo.Operator.DEST_OVER)
194 cairo_context2.set_source_rgba(*operation['new_rgba'])
195 cairo_context2.append_path(operation['path'])
196 # cairo_context2.paint()
197 cairo_context2.set_line_width(3) # ptêt too much mdr
198 cairo_context2.stroke_preserve()
199 cairo_context2.fill()
200
201 def _op_clipping(self, operation):
202 """Replace the color with transparency by adding an alpha channel."""
203 old_rgba = operation['old_rgba']
204 r0 = old_rgba[0]
205 g0 = old_rgba[1]
206 b0 = old_rgba[2]
207 # ^ it's not possible to take into account the alpha channel
208 margin = 0 # XXX as an option ? is not elegant but it's powerful
209 self._clip_red(margin, r0, g0, b0)
210 self.restore_pixbuf()
211 self.non_destructive_show_modif()
212
213 ############################################################################
214
215 def _clip_red(self, margin, r0, g0, b0):
216 for i in range(-1 * margin, margin + 1):
217 r = r0 + i
218 if r <= 255 and r >= 0:
219 self._clip_green(margin, r, g0, b0)
220
221 def _clip_green(self, margin, r, g0, b0):
222 for i in range(-1 * margin, margin + 1):
223 g = g0 + i
224 if g <= 255 and g >= 0:
225 self._clip_blue(margin, r, g, b0)
226
227 def _clip_blue(self, margin, r, g, b0):
228 for i in range(-1 * margin, margin + 1):
229 b = b0 + i
230 if b <= 255 and b >= 0:
231 self._replace_main_with_alpha(r, g, b)
232
233 def _replace_main_with_alpha(self, red, green, blue):
234 new_pixbuf = self.get_main_pixbuf().add_alpha(True, red, green, blue)
235 self.get_image().set_main_pixbuf(new_pixbuf)
236
237 def _replace_temp_with_alpha(self, red, green, blue):
238 new_pixbuf = self.get_image().temp_pixbuf.add_alpha(True, red, green, blue)
239 self.get_image().set_temp_pixbuf(new_pixbuf)
240
241 ############################################################################
242 ################################################################################