Debian Codegraph @

doc/programming_guide/text.rst

raw
1 Displaying text
2 ===============
3
4 pyglet provides the :py:mod:`~pyglet.font` module for efficiently rendering
5 high-quality antialiased Unicode glyphs. pyglet can use any installed font
6 on the operating system, or you can provide your own font with your
7 application.
8
9 Please note that not all font formats are supported,
10 see :ref:`guide_supported-font-formats`
11
12 Text rendering is performed with the :py:mod:`~pyglet.text` module, which
13 can display word-wrapped formatted text. There is also support for
14 interactive editing of text on-screen with a caret.
15
16 Simple text rendering
17 ---------------------
18
19 The following complete example creates a window that displays
20 "Hello, World" centered vertically and horizontally::
21
22 window = pyglet.window.Window()
23 label = pyglet.text.Label('Hello, world',
24 font_name='Times New Roman',
25 font_size=36,
26 x=window.width//2, y=window.height//2,
27 anchor_x='center', anchor_y='center')
28
29 @window.event
30 def on_draw():
31 window.clear()
32 label.draw()
33
34 pyglet.app.run()
35
36 The example demonstrates the most common uses of text rendering:
37
38 * The font name and size are specified directly in the constructor.
39 Additional parameters exist for setting the bold and italic styles and the
40 color of the text.
41 * The position of the text is given by the ``x`` and ``y`` coordinates. The
42 meaning of these coordinates is given by the ``anchor_x`` and ``anchor_y``
43 parameters.
44 * The actual drawing of the text to the screen is done with the
45 :py:meth:`pyglet.text.Label.draw` method. Labels can also be added to a
46 graphics batch; see :ref:`guide_batched-rendering` for details.
47
48 The :py:func:`~pyglet.text.HTMLLabel` class is used similarly, but accepts
49 an HTML formatted string instead of parameters describing the style.
50 This allows the label to display text with mixed style::
51
52 label = pyglet.text.HTMLLabel(
53 '<font face="Times New Roman" size="4">Hello, <i>world</i></font>',
54 x=window.width//2, y=window.height//2,
55 anchor_x='center', anchor_y='center')
56
57 See :ref:`guide_formatted-text` for details on the subset of HTML that is
58 supported.
59
60 The document/layout model
61 -------------------------
62
63 The :py:func:`~pyglet.text.Label` class demonstrated above presents a
64 simplified interface to pyglet's complete text rendering capabilities.
65 The underlying :py:func:`~pyglet.text.layout.TextLayout` and
66 :py:class:`~pyglet.text.document.AbstractDocument` classes provide a
67 "model/view" interface to all of pyglet's text features.
68
69 .. image:: img/text_classes.png
70
71 Documents
72 ^^^^^^^^^
73
74 A `document` is the "model" part of the architecture, and describes the
75 content and style of the text to be displayed. There are two concrete
76 document classes: :py:class:`~pyglet.text.document.UnformattedDocument`
77 and :py:class:`~pyglet.text.document.FormattedDocument`.
78 :py:class:`~pyglet.text.document.UnformattedDocument` models a document
79 containing text in just one style, whereas
80 :py:class:`~pyglet.text.document.FormattedDocument` allows the style to
81 change within the text.
82
83 An empty, unstyled document can be created by constructing either of the
84 classes directly. Usually you will want to initialise the document with some
85 text, however. The :py:func:`~pyglet.text.decode_text`,
86 :py:func:`~pyglet.text.decode_attributed` and
87 :py:func:`~pyglet.text.decode_html` functions return a document given a
88 source string. For :py:func:`~pyglet.text.decode_text`,
89 this is simply a plain text string, and the return value is an
90 :py:class:`~pyglet.text.document.UnformattedDocument`::
91
92 document = pyglet.text.decode_text('Hello, world.')
93
94 :py:func:`~pyglet.text.decode_attributed` and
95 :py:func:`~pyglet.text.decode_html` are described in detail in the next
96 section.
97
98 The text of a document can be modified directly as a property on the object::
99
100 document.text = 'Goodbye, cruel world.'
101
102 However, if small changes are being made to the document it can be more
103 efficient (when coupled with an appropriate layout; see below) to use the
104 :py:func:`~pyglet.text.document.AbstractDocument.delete_text` and
105 :py:func:`~pyglet.text.document.AbstractDocument.insert_text` methods instead.
106
107 Layouts
108 ^^^^^^^
109
110 The actual layout and rendering of a document is performed by the
111 :py:func:`~pyglet.text.layout.TextLayout` classes.
112 This split exists to reduce the complexity of the code, and to allow
113 a single document to be displayed in multiple layouts simultaneously (in other
114 words, many layouts can display one document).
115
116 Each of the :py:func:`~pyglet.text.layout.TextLayout` classes perform layout
117 in the same way, but represent a trade-off in efficiency of update against
118 efficiency of drawing and memory usage.
119
120 The base :py:func:`~pyglet.text.layout.TextLayout` class uses little memory,
121 and shares its graphics group with other
122 :py:func:`~pyglet.text.layout.TextLayout` instances in the same batch
123 (see :ref:`guide_batched-rendering`). When the text or style of the document
124 is modified, or the layout constraints change (for example, the width of the
125 layout changes), the entire text layout is recalculated.
126 This is a potentially expensive operation, especially for long documents.
127 This makes :py:func:`~pyglet.text.layout.TextLayout` suitable
128 for relatively short or unchanging documents.
129
130 :py:class:`~pyglet.text.layout.ScrollableTextLayout` is a small extension to
131 :py:func:`~pyglet.text.layout.TextLayout` that culls the
132 text outside of a specified view rectangle, and allows text to be scrolled within that
133 rectangle without performing the layout calculation again. Because of this
134 clipping rectangle the graphics group cannot be shared with other text
135 layouts, so for ideal performance
136 :py:class:`~pyglet.text.layout.ScrollableTextLayout` should be used only
137 if scrolling is required.
138
139 :py:class:`~pyglet.text.layout.IncrementalTextLayout` uses a more sophisticated
140 layout algorithm that performs less work for small changes to documents.
141 For example, if a document is being edited by the user, only the immediately
142 affected lines of text are recalculated when a character is typed or deleted.
143 :py:class:`~pyglet.text.layout.IncrementalTextLayout`
144 also performs view rectangle culling, reducing the amount of layout and
145 rendering required when the document is larger than the view.
146 :py:class:`~pyglet.text.layout.IncrementalTextLayout` should be used for
147 large documents or documents that change rapidly.
148
149 All the layout classes can be constructed given a document and display
150 dimensions::
151
152 layout = pyglet.text.layout.TextLayout(document, width, height)
153
154 Additional arguments to the constructor allow the specification of a graphics
155 batch and group (recommended if many layouts are to be rendered), and the
156 optional `multiline` and `wrap_lines` flags.
157
158 `multiline`
159 To honor newlines in the document you will need to set this to ``True``. If
160 you do not then newlines will be rendered as plain spaces.
161
162 `wrap_lines`
163 If you expect that your document lines will be wider than the display width
164 then pyglet can automatically wrap them to fit the width by setting this
165 option to ``True``. Note that wrapping only works if there are spaces in the
166 text, so it may not be suitable for languages without spaces.
167
168 Like labels, layouts are positioned through their `x`, `y`,
169 `anchor_x` and `anchor_y` properties.
170 Note that unlike :py:class:`~pyglet.image.AbstractImage`, the `anchor`
171 properties accept a string such as ``"bottom"`` or ``"center"`` instead of a
172 numeric displacement.
173
174 .. _guide_formatted-text:
175
176 Formatted text
177 --------------
178
179 The :py:class:`~pyglet.text.document.FormattedDocument` class maintains
180 style information for individual characters in the text, rather than a
181 single style for the whole document.
182 Styles can be accessed and modified by name, for example::
183
184 # Get the font name used at character index 0
185 font_name = document.get_style('font_name', 0)
186
187 # Set the font name and size for the first 5 characters
188 document.set_style(0, 5, dict(font_name='Arial', font_size=12))
189
190 Internally, character styles are run-length encoded over the document text; so
191 longer documents with few style changes do not use excessive memory.
192
193 From the document's point of view, there are no predefined style names: it
194 simply maps names and character ranges to arbitrary Python values.
195 It is the :py:class:`~pyglet.text.layout.TextLayout` classes that interpret
196 this style information; for example, by selecting a different font based on the
197 ``font_name`` style. Unrecognised style names are ignored by the layout
198 -- you can use this knowledge to store additional data alongside the
199 document text (for example, a URL behind a hyperlink).
200
201 Character styles
202 ^^^^^^^^^^^^^^^^
203
204 The following character styles are recognised by all
205 :py:func:`~pyglet.text.layout.TextLayout` classes.
206
207 Where an attribute is marked "as a distance" the value is assumed to be
208 in pixels if given as an int or float, otherwise a string of the form
209 ``"0u"`` is required, where ``0`` is the distance and ``u`` is the unit; one
210 of ``"px"`` (pixels), ``"pt"`` (points), ``"pc"`` (picas), ``"cm"``
211 (centimeters), ``"mm"`` (millimeters) or ``"in"`` (inches). For example,
212 ``"14pt"`` is the distance covering 14 points, which at the default DPI of 96
213 is 18 pixels.
214
215 ``font_name``
216 Font family name, as given to :py:func:`pyglet.font.load`.
217 ``font_size``
218 Font size, in points.
219 ``bold``
220 Boolean.
221 ``italic``
222 Boolean.
223 ``underline``
224 4-tuple of ints in range (0, 255) giving RGBA underline color, or None
225 (default) for no underline.
226 ``kerning``
227 Additional space to insert between glyphs, as a distance. Defaults to 0.
228 ``baseline``
229 Offset of glyph baseline from line baseline, as a distance. Positive
230 values give a superscript, negative values give a subscript. Defaults to
231 0.
232 ``color``
233 4-tuple of ints in range (0, 255) giving RGBA text color
234 ``background_color``
235 4-tuple of ints in range (0, 255) giving RGBA text background color; or
236 ``None`` for no background fill.
237
238 Paragraph styles
239 ^^^^^^^^^^^^^^^^
240
241 Although :py:class:`~pyglet.text.document.FormattedDocument` does not
242 distinguish between character- and paragraph-level styles,
243 :py:func:`~pyglet.text.layout.TextLayout` interprets the following styles
244 only at the paragraph level. You should take care to set these styles for
245 complete paragraphs only, for example, by using
246 :py:meth:`~pyglet.text.document.AbstractDocument.set_paragraph_style`.
247
248 These styles are ignored for layouts without the ``multiline`` flag set.
249
250 ``align``
251 ``"left"`` (default), ``"center"`` or ``"right"``.
252 ``indent``
253 Additional horizontal space to insert before the first glyph of the
254 first line of a paragraph, as a distance.
255 ``leading``
256 Additional space to insert between consecutive lines within a paragraph,
257 as a distance. Defaults to 0.
258 ``line_spacing``
259 Distance between consecutive baselines in a paragraph, as a distance.
260 Defaults to ``None``, which automatically calculates the tightest line
261 spacing for each line based on the maximum font ascent and descent.
262 ``margin_left``
263 Left paragraph margin, as a distance.
264 ``margin_right``
265 Right paragraph margin, as a distance.
266 ``margin_top``
267 Margin above paragraph, as a distance.
268 ``margin_bottom``
269 Margin below paragraph, as a distance. Adjacent margins do not collapse.
270 ``tab_stops``
271 List of horizontal tab stops, as distances, measured from the left edge of
272 the text layout. Defaults to the empty list. When the tab stops
273 are exhausted, they implicitly continue at 50 pixel intervals.
274 ``wrap``
275 Boolean. If True (the default), text wraps within the width of the layout.
276
277 For the purposes of these attributes, paragraphs are split by the newline
278 character (U+0010) or the paragraph break character (U+2029). Line breaks
279 within a paragraph can be forced with character U+2028.
280
281 Tabs
282 ....
283
284 A tab character in pyglet text is interpreted as 'move to the next tab stop'.
285 Tab stops are specified in pixels, not in some font unit; by default
286 there is a tab stop every 50 pixels and because of that a tab can look too
287 small for big fonts or too big for small fonts.
288
289 Additionally, when rendering text with tabs using a `monospace` font,
290 character boxes may not align vertically.
291
292 To avoid these visualization issues the simpler solution is to convert
293 the tabs to spaces before sending a string to a pyglet text-related class.
294
295 Attributed text
296 ^^^^^^^^^^^^^^^
297
298 pyglet provides two formats for decoding formatted documents from plain text.
299 These are useful for loading pre-prepared documents such as help screens. At
300 this time there is no facility for saving (encoding) formatted documents.
301
302 The *attributed text* format is an encoding specific to pyglet that can
303 exactly describe any :py:class:`~pyglet.text.document.FormattedDocument`.
304 You must use this encoding to access all of the features of pyglet text layout.
305 For a more accessible, yet less featureful encoding,
306 see the `HTML` encoding, described below.
307
308 The following example shows a simple attributed text encoded document:
309
310 .. rst-class:: plain
311
312 ::
313
314 Chapter 1
315
316 My father's family name being Pirrip, and my Christian name Philip,
317 my infant tongue could make of both names nothing longer or more
318 explicit than Pip. So, I called myself Pip, and came to be called
319 Pip.
320
321 I give Pirrip as my father's family name, on the authority of his
322 tombstone and my sister - Mrs. Joe Gargery, who married the
323 blacksmith. As I never saw my father or my mother, and never saw
324 any likeness of either of them (for their days were long before the
325 days of photographs), my first fancies regarding what they were
326 like, were unreasonably derived from their tombstones.
327
328 Newlines are ignored, unless two are made in succession, indicating a
329 paragraph break. Line breaks can be forced with the ``\\`` sequence:
330
331 .. rst-class:: plain
332
333 ::
334
335 This is the way the world ends \\
336 This is the way the world ends \\
337 This is the way the world ends \\
338 Not with a bang but a whimper.
339
340 Line breaks are also forced when the text is indented with one or more spaces
341 or tabs, which is useful for typesetting code:
342
343 .. rst-class:: plain
344
345 ::
346
347 The following paragraph has hard line breaks for every line of code:
348
349 import pyglet
350
351 window = pyglet.window.Window()
352 pyglet.app.run()
353
354 Text can be styled using a attribute tag:
355
356 .. rst-class:: plain
357
358 ::
359
360 This sentence makes a {bold True}bold{bold False} statement.
361
362 The attribute tag consists of the attribute name (in this example, ``bold``)
363 followed by a Python bool, int, float, string, tuple or list.
364
365 Unlike most structured documents such as HTML, attributed text has no concept
366 of the "end" of a style; styles merely change within the document.
367 This corresponds exactly to the representation used by
368 :py:class:`~pyglet.text.document.FormattedDocument` internally.
369
370 Some more examples follow:
371
372 .. rst-class:: plain
373
374 ::
375
376 {font_name 'Times New Roman'}{font_size 28}Hello{font_size 12},
377 {color (255, 0, 0, 255)}world{color (0, 0, 0, 255)}!
378
379 (This example uses 28pt Times New Roman for the word "Hello", and 12pt
380 red text for the word "world").
381
382 Paragraph styles can be set by prefixing the style name with a period (.).
383 This ensures the style range exactly encompasses the paragraph:
384
385 .. rst-class:: plain
386
387 ::
388
389 {.margin_left "12px"}This is a block quote, as the margin is inset.
390
391 {.margin_left "24px"}This paragraph is inset yet again.
392
393 Attributed text can be loaded as a Unicode string. In addition, any character
394 can be inserted given its Unicode code point in numeric form, either in
395 decimal:
396
397 .. rst-class:: plain
398
399 ::
400
401 This text is Copyright {#169}.
402
403 or hexadecimal:
404
405 .. rst-class:: plain
406
407 ::
408
409 This text is Copyright {#xa9}.
410
411 The characters ``{`` and ``}`` can be escaped by duplicating them:
412
413 .. rst-class:: plain
414
415 ::
416
417 Attributed text uses many "{{" and "}}" characters.
418
419 Use the ``decode_attributed`` function to decode attributed text into a
420 :py:class:`~pyglet.text.document.FormattedDocument`::
421
422 document = pyglet.text.decode_attributed('Hello, {bold True}world')
423
424 HTML
425 ^^^^
426
427 While attributed text gives access to all of the features of
428 :py:class:`~pyglet.text.document.FormattedDocument` and
429 :py:func:`~pyglet.text.layout.TextLayout`, it is quite verbose and difficult
430 produce text in. For convenience, pyglet provides an HTML 4.01 decoder that
431 can translate a small, commonly used subset of HTML into a
432 :py:class:`~pyglet.text.document.FormattedDocument`.
433
434 Note that the decoder does not preserve the structure of the HTML document --
435 all notion of element hierarchy is lost in the translation, and only the
436 visible style changes are preserved.
437
438 The following example uses :py:func:`~pyglet.text.decode_html` to create a
439 :py:class:`~pyglet.text.document.FormattedDocument` from a string of HTML::
440
441 document = pyglet.text.decode_html('Hello, <b>world</b>')
442
443 The following elements are supported:
444
445 .. rst-class:: plain
446
447 ::
448
449 B BLOCKQUOTE BR CENTER CODE DD DIR DL EM FONT H1 H2 H3 H4 H5 H6 I IMG KBD
450 LI MENU OL P PRE Q SAMP STRONG SUB SUP TT U UL VAR
451
452 The ``style`` attribute is not supported, so font sizes must be given as HTML
453 logical sizes in the range 1 to 7, rather than as point sizes. The
454 corresponding font sizes, and some other stylesheet parameters, can be
455 modified by subclassing `HTMLDecoder`.
456
457 Custom elements
458 ---------------
459
460 Graphics and other visual elements can be inserted inline into a document
461 using :py:meth:`~pyglet.text.document.AbstractDocument.insert_element`.
462 For example, inline elements are used to render HTML images included with
463 the ``IMG`` tag. There is currently no support for floating or
464 absolutely-positioned elements.
465
466 Elements must subclass :py:class:`~pyglet.text.document.InlineElement`
467 and override the `place` and `remove` methods. These methods are called by
468 :py:func:`~pyglet.text.layout.TextLayout` when the element becomes
469 or ceases to be visible. For :py:func:`~pyglet.text.layout.TextLayout`
470 and :py:class:`~pyglet.text.layout.ScrollableTextLayout`,
471 this is when the element is added or removed from the document;
472 but for :py:class:`~pyglet.text.layout.IncrementalTextLayout` the methods
473 are also called as the element scrolls in and out of the viewport.
474
475 The constructor of :py:class:`~pyglet.text.document.InlineElement`
476 gives the width and height (separated into the ascent above the baseline,
477 and descent below the baseline) of the element.
478
479 Typically an :py:class:`~pyglet.text.document.InlineElement` subclass will
480 add graphics primitives to the layout's graphics batch; though applications
481 may choose to simply record the position of the element and render it
482 separately.
483
484 The position of the element in the document text is marked with a NUL
485 character (U+0000) placeholder. This has the effect that inserting an element
486 into a document increases the length of the document text by one. Elements
487 can also be styled as if they were ordinary character text, though the layout
488 ignores any such style attributes.
489
490 User-editable text
491 ------------------
492
493 While pyglet does not come with any complete GUI widgets for applications to
494 use, it does implement many of the features required to implement interactive
495 text editing. These can be used as a basis for a more complete GUI system, or
496 to present a simple text entry field, as demonstrated in the
497 ``examples/text_input.py`` example.
498
499 :py:class:`~pyglet.text.layout.IncrementalTextLayout` should always be used for
500 text that can be edited by the user.
501 This class maintains information about the placement of glyphs on screen,
502 and so can map window coordinates to a document position and vice-versa.
503 These methods are
504 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_position_from_point`,
505 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_point_from_position`,
506 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_line_from_point`,
507 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_point_from_line`,
508 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_line_from_position`,
509 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_position_from_line`,
510 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_position_on_line`
511 and
512 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.get_line_count`.
513
514 The viewable rectangle of the document can be adjusted using a document
515 position instead of a scrollbar using the
516 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.ensure_line_visible` and
517 :py:meth:`~pyglet.text.layout.IncrementalTextLayout.ensure_x_visible` methods.
518
519 :py:class:`~pyglet.text.layout.IncrementalTextLayout` can display a current
520 text selection by temporarily overriding the foreground and background colour
521 of the selected text. The
522 :py:attr:`~pyglet.text.layout.IncrementalTextLayout.selection_start` and
523 :py:attr:`~pyglet.text.layout.IncrementalTextLayout.selection_end` properties
524 give the range of the selection, and
525 :py:attr:`~pyglet.text.layout.IncrementalTextLayout.selection_color` and
526 :py:attr:`~pyglet.text.layout.IncrementalTextLayout.selection_background_color`
527 the colors to use (defaulting to white on blue).
528
529 The :py:class:`~pyglet.text.caret.Caret` class implements an insertion caret
530 (cursor) for :py:class:`~pyglet.text.layout.IncrementalTextLayout`.
531 This includes displaying the blinking caret at the correct location,
532 and handling keyboard, text and mouse events.
533 The behaviour in response to the events is very similar to the system GUIs
534 on Windows, Mac OS X and GTK. Using :py:class:`~pyglet.text.caret.Caret`
535 frees you from using the :py:class:`~pyglet.text.layout.IncrementalTextLayout`
536 methods described above directly.
537
538 The following example creates a document, a layout and a caret and attaches
539 the caret to the window to listen for events::
540
541 import pyglet
542
543 window = pyglet.window.Window()
544 document = pyglet.text.document.FormattedDocument()
545 layout = pyglet.text.layout.IncrementalTextLayout(document, width, height)
546 caret = pyglet.text.caret.Caret(layout)
547 window.push_handlers(caret)
548
549 When the layout is drawn, the caret will also be drawn, so this example is
550 nearly complete enough to display the user input. However, it is suitable for
551 use when only one editable text layout is to be in the window. If multiple
552 text widgets are to be shown, some mechanism is needed to dispatch events to
553 the widget that has keyboard focus. An example of how to do this is given in
554 the `examples/text_input.py` example program.
555
556 Loading system fonts
557 --------------------
558
559 The layout classes automatically load fonts as required. You can also
560 explicitly load fonts to implement your own layout algorithms.
561
562 To load a font you must know its family name. This is the name displayed in
563 the font dialog of any application. For example, all operating systems
564 include the *Times New Roman* font. You must also specify the font size to
565 load, in points::
566
567 # Load "Times New Roman" at 16pt
568 times = pyglet.font.load('Times New Roman', 16)
569
570 Bold and italic variants of the font can specified with keyword parameters::
571
572 times_bold = pyglet.font.load('Times New Roman', 16, bold=True)
573 times_italic = pyglet.font.load('Times New Roman', 16, italic=True)
574 times_bold_italic = pyglet.font.load('Times New Roman', 16,
575 bold=True, italic=True)
576
577 For maximum compatibility on all platforms, you can specify a list of font
578 names to load, in order of preference. For example, many users will have
579 installed the Microsoft Web Fonts pack, which includes `Verdana`, but this
580 cannot be guaranteed, so you might specify `Arial` or `Helvetica` as
581 suitable alternatives::
582
583 sans_serif = pyglet.font.load(('Verdana', 'Helvetica', 'Arial'), 16)
584
585 Also you can check for the availability of a font using
586 :py:func:`pyglet.font.have_font`::
587
588 # Will return True
589 pyglet.font.have_font('Times New Roman')
590
591 # Will return False
592 pyglet.font.have_font('missing-font-name')
593
594 If you do not particularly care which font is used, and just need to display
595 some readable text, you can specify `None` as the family name, which will load
596 a default sans-serif font (Helvetica on Mac OS X, Arial on Windows XP)::
597
598 sans_serif = pyglet.font.load(None, 16)
599
600 Font sizes
601 ----------
602
603 When loading a font you must specify the font size it is to be rendered at, in
604 points. Points are a somewhat historical but conventional unit used in both
605 display and print media. There are various conflicting definitions for the
606 actual length of a point, but pyglet uses the PostScript definition: 1 point =
607 1/72 inches.
608
609 Font resolution
610 ^^^^^^^^^^^^^^^
611
612 The actual rendered size of the font on screen depends on the display
613 resolution. pyglet uses a default DPI of 96 on all operating systems. Most
614 Mac OS X applications use a DPI of 72, so the font sizes will not match up on
615 that operating system. However, application developers can be assured that
616 font sizes remain consistent in pyglet across platforms.
617
618 The DPI can be specified directly in the :py:func:`pyglet.font.load`
619 function, and as an argument to the :py:func:`~pyglet.text.layout.TextLayout`
620 constructor.
621
622 Determining font size
623 ^^^^^^^^^^^^^^^^^^^^^
624
625 Once a font is loaded at a particular size, you can query its pixel size with
626 the attributes::
627
628 Font.ascent
629 Font.descent
630
631 These measurements are shown in the diagram below.
632
633 .. figure:: img/font_metrics.png
634
635 Font metrics. Note that the descent is usually negative as it descends
636 below the baseline.
637
638 You can calculate the distance between successive lines of text as::
639
640 ascent - descent + leading
641
642 where `leading` is the number of pixels to insert between each line of text.
643
644 Loading custom fonts
645 --------------------
646
647 You can supply a font with your application if it's not commonly installed on
648 the target platform. You should ensure you have a license to distribute the
649 font -- the terms are often specified within the font file itself, and can be
650 viewed with your operating system's font viewer.
651
652 Loading a custom font must be performed in two steps:
653
654 1. Let pyglet know about the additional font or font files.
655 2. Load the font by its family name.
656
657 For example, let's say you have the *Action Man* font in a file called
658 ``action_man.ttf``. The following code will load an instance of that font::
659
660 pyglet.font.add_file('action_man.ttf')
661 action_man = pyglet.font.load('Action Man')
662
663 Similarly, once the font file has been added, the font name can be specified
664 as a style on a label or layout::
665
666 label = pyglet.text.Label('Hello', font_name='Action Man')
667
668 Fonts are often distributed in separate files for each variant. *Action Man
669 Bold* would probably be distributed as a separate file called
670 ``action_man_bold.ttf``; you need to let pyglet know about this as well::
671
672 font.add_file('action_man_bold.ttf')
673 action_man_bold = font.load('Action Man', bold=True)
674
675 Note that even when you know the filename of the font you want to load, you
676 must specify the font's family name to :py:func:`pyglet.font.load`.
677
678 You need not have the file on disk to add it to pyglet; you can specify any
679 file-like object supporting the `read` method. This can be useful for
680 extracting fonts from a resource archive or over a network.
681
682 If the custom font is distributed with your application, consider using the
683 :ref:`guide_resources`.
684
685 .. _guide_supported-font-formats:
686
687 Supported font formats
688 ^^^^^^^^^^^^^^^^^^^^^^
689
690 pyglet can load any font file that the operating system natively supports,
691 but not all formats all fully supported.
692
693 The list of supported formats is shown in the table below.
694
695 .. list-table::
696 :header-rows: 1
697
698 * - Font Format
699 - Windows
700 - Mac OS X
701 - Linux (FreeType)
702 * - TrueType (.ttf)
703 - X
704 - X
705 - X
706 * - PostScript Type 1 (.pfm, .pfb)
707 - X
708 - X
709 - X
710 * - Windows Bitmap (.fnt)
711 - X
712 -
713 - X
714 * - Mac OS X Data Fork Font (.dfont)
715 -
716 - X
717 -
718 * - OpenType (.otf) [#opentype]_
719 -
720 - X
721 -
722 * - X11 font formats PCF, BDF, SFONT
723 -
724 -
725 - X
726 * - Bitstream PFR (.pfr)
727 -
728 -
729 - X
730
731 .. [#opentype] All OpenType fonts are backward compatible with TrueType, so
732 while the advanced OpenType features can only be rendered with
733 Mac OS X, the files can be used on any platform. pyglet
734 does not currently make use of the additional kerning and
735 ligature information within OpenType fonts.
736 In Windows a few will use the variant DEVICE_FONTTYPE and may
737 render bad, by example inconsolata.otf, from
738 http://levien.com/type/myfonts/inconsolata.html
739
740 Some of the fonts found in internet may miss information for some operating
741 systems, others may have been written with work in progress tools not fully
742 compliant with standards. Using the font with text editors or fonts viewers
743 can help to determine if the font is broken.
744
745 OpenGL font considerations
746 --------------------------
747
748 Text in pyglet is drawn using textured quads. Each font maintains a set of
749 one or more textures, into which glyphs are uploaded as they are needed. For
750 most applications this detail is transparent and unimportant, however some of
751 the details of these glyph textures are described below for advanced users.
752
753 Context affinity
754 ^^^^^^^^^^^^^^^^
755
756 When a font is loaded, it immediately creates a texture in the current
757 context's object space. Subsequent textures may need to be created if there
758 is not enough room on the first texture for all the glyphs. This is done when
759 the glyph is first requested.
760
761 pyglet always assumes that the object space that was active when the font was
762 loaded is the active one when any texture operations are performed. Normally
763 this assumption is valid, as pyglet shares object spaces between all contexts
764 by default. There are a few situations in which this will not be the case,
765 though:
766
767 * When explicitly setting the context share during context creation.
768 * When multiple display devices are being used which cannot support a shared
769 context object space.
770
771 In any of these cases, you will need to reload the font for each object space
772 that it's needed in. pyglet keeps a cache of fonts, but does so
773 per-object-space, so it knows when it can reuse an existing font instance or
774 if it needs to load it and create new textures. You will also need to ensure
775 that an appropriate context is active when any glyphs may need to be added.
776
777 Blend state
778 ^^^^^^^^^^^
779
780 The glyph textures have an internal format of ``GL_ALPHA``, which provides
781 a simple way to recolour and blend antialiased text by changing the
782 vertex colors. pyglet makes very few assumptions about the OpenGL state, and
783 will not alter it besides changing the currently bound texture.
784
785 The following blend state is used for drawing font glyphs::
786
787 from pyglet.gl import *
788 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
789 glEnable(GL_BLEND)
790
791 All glyph textures use the ``GL_TEXTURE_2D`` target, so you should ensure that
792 a higher priority target such as ``GL_TEXTURE_3D`` is not enabled before
793 trying to render text.