wlt: fix shl_hook API changes
[platform/upstream/kmscon.git] / src / font.c
1 /*
2  * kmscon - Font handling
3  *
4  * Copyright (c) 2012-2013 David Herrmann <dh.herrmann@googlemail.com>
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining
7  * a copy of this software and associated documentation files
8  * (the "Software"), to deal in the Software without restriction, including
9  * without limitation the rights to use, copy, modify, merge, publish,
10  * distribute, sublicense, and/or sell copies of the Software, and to
11  * permit persons to whom the Software is furnished to do so, subject to
12  * the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included
15  * in all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25
26 /**
27  * SECTION:font
28  * @short_description: Font handling
29  * @include: font.h
30  *
31  * The text renderer needs a backend that draws glyphs which then can be shown
32  * on the screen. This font handling subsystem provides a very simple API to
33  * load arbitrary font-renderer backends. That is, you can choose from
34  * in-memory bitmap fonts up to full Unicode compatible font libraries like
35  * pango during runtime.
36  *
37  * This system does not provide any renderer by itself. You need to register one
38  * of the available font-renderers first which then is used as backend for this
39  * system. kmscon_font_register() and kmscon_font_unregister() can be used to
40  * register font-renderers manually.
41  *
42  * @kmscon_font_attr is used to specify font-attributes for the fonts you want.
43  * Please see kmscon_font_find() for more information on font-attributes. This
44  * function returns a matching font which then can be used for drawing.
45  * kmscon_font_ref()/kmscon_font_unref() are used for reference counting.
46  * kmscon_font_render() renders a single unicode glyph and returns the glyph
47  * buffer. kmscon_font_drop() frees this buffer again. A kmscon_glyph object
48  * contains a memory-buffer with the renderered glyph plus some metrics like
49  * height/width but also ascent/descent.
50  *
51  * Font-backends must take into account that this API must be thread-safe as it
52  * is shared between different threads to reduce memory-footprint.
53  */
54
55 #include <errno.h>
56 #include <pthread.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include "font.h"
60 #include "kmscon_module.h"
61 #include "log.h"
62 #include "shl_dlist.h"
63 #include "shl_register.h"
64
65 #define LOG_SUBSYSTEM "font"
66
67 static struct shl_register font_reg = SHL_REGISTER_INIT(font_reg);
68
69 /**
70  * kmscon_font_attr_normalize:
71  * @attr: Attribute to normalize
72  *
73  * This normalizes @attr and fills out missing entries. The following is done:
74  * - If attr->name is empty, then it is set to KMSCON_FONT_DEFAULT_NAME
75  * - If attr->ppi is 0, it is set to KMSCON_FONT_DEFAULT_PPI
76  * - If attr->height is not set but attr->points is given, then attr->heights is
77  *   calculated from attr->points.
78  * - If attr->height is set, then attr->points is recalculated and overwritten
79  *
80  * The other fields are not changed. If attr->points is set but attr->height is
81  * not set, then the height is calculated and after that the points are
82  * recalculated so we will never have division-errors.
83  */
84 void kmscon_font_attr_normalize(struct kmscon_font_attr *attr)
85 {
86         if (!attr)
87                 return;
88
89         if (!*attr->name)
90                 memcpy(attr->name, KMSCON_FONT_DEFAULT_NAME,
91                        sizeof(KMSCON_FONT_DEFAULT_NAME));
92
93         if (!attr->ppi)
94                 attr->ppi = KMSCON_FONT_DEFAULT_PPI;
95
96         if (!attr->height && attr->points)
97                 attr->height = attr->points * attr->ppi / 72;
98         if (attr->height)
99                 attr->points = attr->height * 72 / attr->ppi;
100 }
101
102 /**
103  * kmscon_font_attr_match:
104  * @a1: First attribute to match
105  * @a2: Second attribute to match
106  *
107  * Compares @a1 and @a2 and returns true if they match. Both must be normalized
108  * before comparing them, otherwise the comparison may return inexact results.
109  * If width, height or *name is 0, then the fields are _not_ compared so you can
110  * have wildmask matches.
111  * points and dpi are never compared as the normalization already computes the
112  * height correctly. So there is no need to use these.
113  *
114  * Returns: true if they match, otherwise false
115  */
116 bool kmscon_font_attr_match(const struct kmscon_font_attr *a1,
117                             const struct kmscon_font_attr *a2)
118 {
119         if (!a1 || !a2)
120                 return false;
121
122         if (a1->width && a2->width && a1->width != a2->width)
123                 return false;
124         if (a1->height && a2->height && a1->height != a2->height)
125                 return false;
126         if (a1->bold != a2->bold)
127                 return false;
128         if (a1->italic != a2->italic)
129                 return false;
130         if (*a1->name && *a2->name && strcmp(a1->name, a2->name))
131                 return false;
132
133         return true;
134 }
135
136 static inline void kmscon_font_destroy(void *data)
137 {
138         const struct kmscon_font_ops *ops = data;
139
140         kmscon_module_unref(ops->owner);
141 }
142
143 /**
144  * kmscon_font_register:
145  * @ops: Font operations and name for new font backend
146  *
147  * This register a new font backend with operations set to @ops. The name
148  * @ops->name must be valid.
149  *
150  * The first font that is registered automatically becomes the default font and
151  * the fallback font. So make sure you register a safe fallback as first font.
152  * If this font is unregistered, the next font in the list becomes the default
153  * and fallback font.
154  *
155  * Returns: 0 on success, negative error code on failure
156  */
157 int kmscon_font_register(const struct kmscon_font_ops *ops)
158 {
159         int ret;
160
161         if (!ops)
162                 return -EINVAL;
163
164         log_debug("register font backend %s", ops->name);
165
166         ret = shl_register_add_cb(&font_reg, ops->name, (void*)ops,
167                                   kmscon_font_destroy);
168         if (ret) {
169                 log_error("cannot register font backend %s: %d", ops->name,
170                           ret);
171                 return ret;
172         }
173
174         kmscon_module_ref(ops->owner);
175         return 0;
176 }
177
178 /**
179  * kmscon_font_unregister:
180  * @name: Name of font backend
181  *
182  * This unregisters the font-backend that is registered with name @name. If
183  * @name is not found, a warning is printed but nothing else is done.
184  */
185 void kmscon_font_unregister(const char *name)
186 {
187         log_debug("unregister font backend %s", name);
188         shl_register_remove(&font_reg, name);
189 }
190
191 static int new_font(struct kmscon_font *font,
192                     const struct kmscon_font_attr *attr, const char *backend)
193 {
194         struct shl_register_record *record;
195         const char *name = backend ? backend : "<default>";
196         int ret;
197
198         memset(font, 0, sizeof(*font));
199         font->ref = 1;
200
201         if (backend)
202                 record = shl_register_find(&font_reg, backend);
203         else
204                 record = shl_register_first(&font_reg);
205
206         if (!record) {
207                 log_error("requested backend '%s' not found", name);
208                 return -ENOENT;
209         }
210
211         font->record = record;
212         font->ops = record->data;
213
214         if (font->ops->init)
215                 ret = font->ops->init(font, attr);
216         else
217                 ret = 0;
218
219         if (ret) {
220                 log_warning("backend %s cannot create font", name);
221                 shl_register_record_unref(record);
222                 return ret;
223         }
224
225         return 0;
226 }
227
228 /**
229  * kmscon_font_find:
230  * @out: A pointer to the new font is stored here
231  * @attr: Attribute describing the font
232  * @backend: Backend to use or NULL for default backend
233  *
234  * Lookup a font by the given attributes. It uses the font backend @backend. If
235  * it is NULL, the default backend is used. If the given backend cannot find the
236  * a suitable font, the fallback backend is tried. This backend should always
237  * find a suitable font.
238  *
239  * Stores a pointer to the new font in @out and returns 0. Otherwise, @out is
240  * not touched and an error is returned.
241  *
242  * The attributes in @attr are not always matched. There are even font backends
243  * which have only one fixed font and always return this one so you cannot rely
244  * on this behavior. That is, this function cannot be used to get an exact
245  * match, it rather returns the best matching font.
246  * There is currently no need to get an exact match so no API is available to
247  * get this. Instead, you should always use the best match and the user must be
248  * happy. We do print warnings if no close match can be found, though. The user
249  * should read them if they want more information what font fallback was used.
250  *
251  * If this functions fails, you must not assume that there is another font that
252  * might work. Moreover, you must not implement a fallback font yourself as this
253  * is already implemented inside of this function! This function fails only due
254  * to internal errors like failed memory allocations. If it fails, the chances
255  * that you can allocate your own fallback font are pretty small so don't do it.
256  *
257  * About DPI and Point Sizes:
258  * Many computer graphics systems use "Points" as measurement for font sizes.
259  * However, most of them also use 72 or 96 as fixed DPI size for monitors. This
260  * means, the Point sizes can be directly converted into pixels. But lets
261  * look at the facts:
262  *   1 Point is defined as 1/72 of an inch. That is, a 10 Point font will be
263  *   exactly 10 / 72 inches, which is ~0.13889 inches, which is
264  *   0.13889 * 2.54 cm, which is approximately 0.3528 cm. This applies to
265  *   printed paper. If we want the same on a monitor, we must need more
266  *   information. First, the monitor renders in pixels, that is, we must know
267  *   how many Pixels per Inch (PPI) are displayed. Often the same information is
268  *   given as Dots per Inch (DPI) but these two are identical in this context.
269  *   If the DPI is 96, we know that our 10 Point font is 10 / 72 inches. Which
270  *   then means it is 10 / 72 * 96 pixels, which is ~13.333 pixels. So we
271  *   internally render the font with 13 pixels and display it as 13 pixels. This
272  *   guarantees, that the font will be 10 Point big which means 0.3528 cm on the
273  *   display. This of course requires that we know the exact PPI/DPI of the
274  *   display.
275  * But if we take into account that Windows uses fixed 96 PPI and Mac OS X 72
276  * PPI (independent of the monitor), they drop all this information and instead
277  * render the font in pixel sizes. Because if you use fixed 72 PPI, a 10 Point
278  * font will always be 10 / 72 * 72 = 10 pixels high. This means, it would be
279  * rather convenient to directly specify pixel-sizes on the monitor. If you want
280  * to work with documents that shall be printed, you want to specify Points so
281  * the printed result will look nice. But the disadvantage is, that your monitor
282  * can print this font in the weirdest size if it uses PPI much bigger or lower
283  * than the common 96 or 72. Therefore, if you work with a monitor you probably
284  * want to also specify the pixel-height of the font as you probably don't know
285  * the PPI of your monitor and don't want to do all that math in your head.
286  * Therefore, for applications that will probably never print their output (like
287  * the virtual (!) console this is for), it is often requested that we can
288  * specify the pixel size instead of the Point size of a font so you can
289  * predict the output better.
290  * Hence, we provide both. If pixel information is given, that is, attr->height
291  * is not 0, then we try to return a font with this pixel height.
292  * If it is 0, attr->points is used together with attr->ppi to calculate the
293  * pixel size. If attr->ppi is 0, then 72 is used.
294  * After the font was chosen, all fields "points", "ppi", "height" and "width"
295  * will contain the exact values for this font. If "ppi" was zero and pixel
296  * sizes where specified, then the resulting "points" size is calculated with
297  * "ppi" = 72 again. So if you use the "points" field please always specify
298  * "ppi", either.
299  *
300  * Returns: 0 on success, error code on failure
301  */
302 int kmscon_font_find(struct kmscon_font **out,
303                      const struct kmscon_font_attr *attr,
304                      const char *backend)
305 {
306         struct kmscon_font *font;
307         int ret;
308
309         if (!out || !attr)
310                 return -EINVAL;
311
312         log_debug("searching for: be: %s nm: %s ppi: %u pt: %u b: %d i: %d he: %u wt: %u",
313                   backend, attr->name, attr->ppi, attr->points,
314                   attr->bold, attr->italic, attr->height,
315                   attr->width);
316
317         font = malloc(sizeof(*font));
318         if (!font) {
319                 log_error("cannot allocate memory for new font");
320                 return -ENOMEM;
321         }
322
323         ret = new_font(font, attr, backend);
324         if (ret) {
325                 if (backend)
326                         ret = new_font(font, attr, NULL);
327                 if (ret)
328                         goto err_free;
329         }
330
331         log_debug("using: be: %s nm: %s ppi: %u pt: %u b: %d i: %d he: %u wt: %u",
332                   font->ops->name, font->attr.name, font->attr.ppi,
333                   font->attr.points, font->attr.bold, font->attr.italic,
334                   font->attr.height, font->attr.width);
335         *out = font;
336         return 0;
337
338 err_free:
339         free(font);
340         return ret;
341 }
342
343 /**
344  * kmscon_font_ref:
345  * @font: Valid font object
346  *
347  * This increases the reference count of @font by one.
348  */
349 void kmscon_font_ref(struct kmscon_font *font)
350 {
351         if (!font || !font->ref)
352                 return;
353
354         ++font->ref;
355 }
356
357 /**
358  * kmscon_font_unref:
359  * @font: Valid font object
360  *
361  * This decreases the reference count of @font by one. If it drops to zero, the
362  * object is freed.
363  */
364 void kmscon_font_unref(struct kmscon_font *font)
365 {
366         if (!font || !font->ref || --font->ref)
367                 return;
368
369         log_debug("freeing font");
370         if (font->ops->destroy)
371                 font->ops->destroy(font);
372         shl_register_record_unref(font->record);
373         free(font);
374 }
375
376 /**
377  * kmscon_font_render:
378  * @font: Valid font object
379  * @id: Unique ID that identifies @ch globally
380  * @ch: Symbol to find a glyph for
381  * @len: Length of @ch
382  * @out: Output buffer for glyph
383  *
384  * Renders the glyph for symbol @sym and places a pointer to the glyph in @out.
385  * If the glyph cannot be found or is invalid, an error is returned. The glyph
386  * is cached internally and removed when the last reference to this font is
387  * dropped.
388  * If the glyph is no available in this font-set, then -ERANGE is returned.
389  *
390  * Returns: 0 on success, negative error code on failure
391  */
392 int kmscon_font_render(struct kmscon_font *font,
393                        uint32_t id, const uint32_t *ch, size_t len,
394                        const struct kmscon_glyph **out)
395 {
396         if (!font || !out || !ch || !len)
397                 return -EINVAL;
398
399         return font->ops->render(font, id, ch, len, out);
400 }
401
402 /**
403  * kmscon_font_render_empty:
404  * @font: Valid font object
405  * @out: Output buffer for glyph
406  *
407  * Same as kmscon_font_render() but this renders a glyph that has no content and
408  * can be used to blit solid backgrounds. That is, the resulting buffer will be
409  * all 0 but the dimensions are the same as for all other glyphs.
410  *
411  * Returns: 0 on success, negative error code on failure
412  */
413 int kmscon_font_render_empty(struct kmscon_font *font,
414                              const struct kmscon_glyph **out)
415 {
416         if (!font || !out)
417                 return -EINVAL;
418
419         return font->ops->render_empty(font, out);
420 }
421
422 /**
423  * kmscon_font_render_inval:
424  * @font: Valid font object
425  * @out: Output buffer for glyph
426  *
427  * Same sa kmscon_font_render_empty() but renders a glyph that can be used as
428  * replacement for any other non-drawable glyph. That is, if
429  * kmscon_font_render() returns -ERANGE, then this glyph can be used as
430  * replacement.
431  *
432  * Returns: 0 on success ,engative error code on failure
433  */
434 int kmscon_font_render_inval(struct kmscon_font *font,
435                              const struct kmscon_glyph **out)
436 {
437         if (!font || !out)
438                 return -EINVAL;
439
440         return font->ops->render_inval(font, out);
441 }