Debian Codegraph @

src/igraph/drawing/cairo/text.py

raw
1 """
2 Drawers for labels on plots.
3 """
4
5 import re
6 from warnings import warn
7
8 from igraph.drawing.cairo.base import AbstractCairoDrawer
9
10 __all__ = ("CairoTextDrawer",)
11
12
13 class CairoTextDrawer(AbstractCairoDrawer):
14 """Class that draws text on a Cairo context.
15
16 This class supports multi-line text unlike the original Cairo text
17 drawing methods."""
18
19 LEFT, CENTER, RIGHT = "left", "center", "right"
20 TOP, BOTTOM = "top", "bottom"
21
22 def __init__(self, context, text="", halign="center", valign="center"):
23 """Constructs a new instance that will draw the given C{text} on
24 the given Cairo C{context}.
25 """
26 super().__init__(context, (0, 0))
27 self.text = text
28 self.halign = halign
29 self.valign = valign
30
31 def draw(self, wrap=False):
32 """Draws the text in the current bounding box of the drawer.
33
34 Since the class itself is an instance of L{AbstractCairoDrawer}, it
35 has an attribute named C{bbox} which will be used as a bounding box.
36
37 @param wrap: whether to allow re-wrapping of the text if it does not
38 fit within the bounding box horizontally.
39 """
40 ctx = self.context
41 bbox = self.bbox
42
43 text_layout = self.get_text_layout(bbox.left, bbox.top, bbox.width, wrap)
44 if not text_layout:
45 return
46
47 _, font_descent, line_height = ctx.font_extents()[:3]
48 yb = ctx.text_extents(text_layout[0][2])[1]
49 total_height = len(text_layout) * line_height
50
51 if self.valign == self.BOTTOM:
52 # Bottom vertical alignment
53 dy = bbox.height - total_height - yb + font_descent
54 elif self.valign == self.CENTER:
55 # Centered vertical alignment
56 dy = (bbox.height - total_height - yb + font_descent + line_height) / 2.0
57 else:
58 # Top vertical alignment
59 dy = line_height
60
61 for ref_x, ref_y, line in text_layout:
62 ctx.move_to(ref_x, ref_y + dy)
63 ctx.show_text(line)
64 ctx.new_path()
65
66 def get_text_layout(self, x=None, y=None, width=None, wrap=False):
67 """Calculates the layout of the current text. C{x} and C{y} denote the
68 coordinates where the drawing should start. If they are both C{None},
69 the current position of the context will be used.
70
71 Vertical alignment settings are not taken into account in this method
72 as the text is not drawn within a box.
73
74 @param x: The X coordinate of the reference point where the layout should
75 start.
76 @param y: The Y coordinate of the reference point where the layout should
77 start.
78 @param width: The width of the box in which the text will be fitted. It
79 matters only when the text is right-aligned or centered. The text
80 will overflow the box if any of the lines is longer than the box
81 width and C{wrap} is C{False}.
82 @param wrap: whether to allow re-wrapping of the text if it does not
83 fit within the given width.
84
85 @return: a list consisting of C{(x, y, line)} tuples where C{x} and
86 C{y} refer to reference points on the Cairo canvas and C{line}
87 refers to the corresponding text that should be plotted there.
88 """
89 ctx = self.context
90
91 if x is None or y is None:
92 x, y = ctx.get_current_point()
93
94 line_height = ctx.font_extents()[2]
95
96 if wrap and width and width > 0:
97 iterlines = self._iterlines_wrapped(width)
98 elif wrap:
99 warn("ignoring wrap=True as no width was specified", stacklevel=1)
100 iterlines = self._iterlines()
101 else:
102 iterlines = self._iterlines()
103
104 result = []
105
106 if self.halign == self.CENTER:
107 # Centered alignment
108 if width is None:
109 width = self.text_extents()[2]
110 for line, line_width, x_bearing in iterlines:
111 result.append((x + (width - line_width) / 2.0 - x_bearing, y, line))
112 y += line_height
113
114 elif self.halign == self.RIGHT:
115 # Right alignment
116 if width is None:
117 width = self.text_extents()[2]
118 x += width
119 for line, line_width, x_bearing in iterlines:
120 result.append((x - line_width - x_bearing, y, line))
121 y += line_height
122
123 else:
124 # Left alignment
125 for line, _, x_bearing in iterlines:
126 result.append((x - x_bearing, y, line))
127 y += line_height
128
129 return result
130
131 def draw_at(self, x=None, y=None, width=None, wrap=False):
132 """Draws the text by setting up an appropriate path on the Cairo
133 context and filling it. C{x} and C{y} denote the coordinates where the
134 drawing should start. If they are both C{None}, the current position
135 of the context will be used.
136
137 Vertical alignment settings are not taken into account in this method
138 as the text is not drawn within a box.
139
140 @param x: The X coordinate of the reference point where the layout should
141 start.
142 @param y: The Y coordinate of the reference point where the layout should
143 start.
144 @param width: The width of the box in which the text will be fitted. It
145 matters only when the text is right-aligned or centered. The text
146 will overflow the box if any of the lines is longer than the box
147 width and C{wrap} is C{False}.
148 @param wrap: whether to allow re-wrapping of the text if it does not
149 fit within the given width.
150 """
151 ctx = self.context
152 for ref_x, ref_y, line in self.get_text_layout(x, y, width, wrap):
153 ctx.move_to(ref_x, ref_y)
154 ctx.show_text(line)
155 ctx.new_path()
156
157 def _iterlines(self):
158 """Iterates over the label line by line and returns a tuple containing
159 the folloing for each line: the line itself, the width of the line and
160 the X-bearing of the line."""
161 ctx = self.context
162 for line in self._text.split("\n"):
163 xb, _, line_width, _, _, _ = ctx.text_extents(line)
164 yield (line, line_width, xb)
165
166 def _iterlines_wrapped(self, width):
167 """Iterates over the label line by line and returns a tuple containing
168 the folloing for each line: the line itself, the width of the line and
169 the X-bearing of the line.
170
171 The difference between this method and L{_iterlines()} is that this
172 method is allowed to re-wrap the line if necessary.
173
174 @param width: The width of the box in which the text will be fitted.
175 Lines will be wrapped if they are wider than this width.
176 """
177 ctx = self.context
178 for line in self._text.split("\n"):
179 xb, _, line_width, _, _, _ = ctx.text_extents(line)
180 if line_width <= width:
181 yield (line, line_width, xb)
182 continue
183
184 # We have to wrap the line
185 current_line, current_width, last_sep_width = [], 0, 0
186 for match in re.finditer(r"(\S+)(\s+)?", line):
187 word, sep = match.groups()
188 word_width = ctx.text_extents(word)[4]
189 if sep:
190 sep_width = ctx.text_extents(sep)[4]
191 else:
192 sep_width = 0
193 current_width += word_width
194 if current_width >= width and current_line:
195 yield ("".join(current_line), current_width - word_width, 0)
196 # Starting a new line
197 current_line, current_width = [word], word_width
198 if sep is not None:
199 current_line.append(sep)
200 else:
201 current_width += last_sep_width
202 current_line.append(word)
203 if sep is not None:
204 current_line.append(sep)
205 last_sep_width = sep_width
206 if current_line:
207 yield ("".join(current_line), current_width, 0)
208
209 @property
210 def text(self):
211 """Returns the text to be drawn."""
212 return self._text
213
214 @text.setter
215 def text(self, text):
216 """Sets the text that will be drawn.
217
218 If C{text} is C{None}, it will be mapped to an empty string; otherwise,
219 it will be converted to a string."""
220 if text is None:
221 self._text = ""
222 else:
223 self._text = str(text)
224
225 def text_extents(self):
226 """Returns the X-bearing, Y-bearing, width, height, X-advance and
227 Y-advance of the text.
228
229 For multi-line text, the X-bearing and Y-bearing correspond to the
230 first line, while the X-advance is extracted from the last line.
231 and the Y-advance is the sum of all the Y-advances. The width and
232 height correspond to the entire bounding box of the text."""
233 lines = self.text.split("\n")
234 if len(lines) <= 1:
235 return self.context.text_extents(self.text)
236
237 (
238 x_bearing,
239 y_bearing,
240 width,
241 height,
242 x_advance,
243 y_advance,
244 ) = self.context.text_extents(lines[0])
245
246 line_height = self.context.font_extents()[2]
247 for line in lines[1:]:
248 _, _, w, _, x_advance, ya = self.context.text_extents(line)
249 width = max(width, w)
250 height += line_height
251 y_advance += ya
252
253 return x_bearing, y_bearing, width, height, x_advance, y_advance
254
255
256 def test():
257 """Testing routine for L{CairoTextDrawer}"""
258 import math
259 from igraph.drawing.cairo.utils import find_cairo
260 from igraph.drawing.text import TextAlignment
261
262 cairo = find_cairo()
263
264 text = "The quick brown fox\njumps over a\nlazy dog"
265 width, height = (600, 1000)
266
267 surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
268 context = cairo.Context(surface)
269 drawer = CairoTextDrawer(context, text)
270
271 context.set_source_rgb(1, 1, 1)
272 context.set_font_size(16.0)
273 context.rectangle(0, 0, width, height)
274 context.fill()
275
276 context.set_source_rgb(0.5, 0.5, 0.5)
277 for i in range(200, width, 200):
278 context.move_to(i, 0)
279 context.line_to(i, height)
280 context.stroke()
281 for i in range(200, height, 200):
282 context.move_to(0, i)
283 context.line_to(width, i)
284 context.stroke()
285 context.set_source_rgb(0.75, 0.75, 0.75)
286 context.set_line_width(0.5)
287 for i in range(100, width, 200):
288 context.move_to(i, 0)
289 context.line_to(i, height)
290 context.stroke()
291 for i in range(100, height, 200):
292 context.move_to(0, i)
293 context.line_to(width, i)
294 context.stroke()
295
296 def mark_point(red, green, blue):
297 """Marks the current point on the canvas by the given color"""
298 x, y = context.get_current_point()
299 context.set_source_rgba(red, green, blue, 0.5)
300 context.arc(x, y, 4, 0, 2 * math.pi)
301 context.fill()
302
303 # Testing drawer.draw_at()
304 alignments = TextAlignment.LEFT, TextAlignment.CENTER, TextAlignment.RIGHT
305 for i, halign in enumerate(alignments):
306 # Mark the reference points
307 context.move_to(i * 200, 40)
308 mark_point(0, 0, 1)
309 context.move_to(i * 200, 140)
310 mark_point(0, 0, 1)
311
312 # Draw the text
313 context.set_source_rgb(0, 0, 0)
314 drawer.halign = halign
315 drawer.draw_at(i * 200, 40)
316 drawer.draw_at(i * 200, 140, width=200)
317
318 # Mark the new reference point
319 mark_point(1, 0, 0)
320
321 # Testing TextDrawer.draw()
322 for i, halign in enumerate(("left", "center", "right")):
323 for j, valign in enumerate(("top", "center", "bottom")):
324 # Draw the text
325 context.set_source_rgb(0, 0, 0)
326 drawer.halign = halign
327 drawer.valign = valign
328 drawer.bbox = (i * 200, j * 200 + 200, i * 200 + 200, j * 200 + 400)
329 drawer.draw()
330 # Mark the new reference point
331 mark_point(1, 0, 0)
332
333 # Testing TextDrawer.wrap()
334 drawer.text = (
335 "Jackdaws love my big sphinx of quartz. Yay, wrapping! "
336 + "Jackdaws love my big sphinx of quartz.\n\n"
337 + "Jackdaws love my big sphinx of quartz."
338 )
339 drawer.valign = TextAlignment.TOP
340 for i, halign in enumerate(("left", "center", "right")):
341 context.move_to(i * 200, 840)
342
343 # Mark the reference point
344 mark_point(0, 0, 1)
345
346 # Draw the text
347 context.set_source_rgb(0, 0, 0)
348 drawer.halign = halign
349 drawer.draw_at(i * 200, 840, width=199, wrap=True)
350
351 # Mark the new reference point
352 mark_point(1, 0, 0)
353
354 surface.write_to_png("test.png")
355
356
357 if __name__ == "__main__":
358 test()