GNU Octave 10.1.0
A high-level interpreted language, primarily intended for numerical computations, mostly compatible with Matlab
 
Loading...
Searching...
No Matches
ft-text-renderer.cc
Go to the documentation of this file.
1////////////////////////////////////////////////////////////////////////
2//
3// Copyright (C) 2009-2025 The Octave Project Developers
4//
5// See the file COPYRIGHT.md in the top-level directory of this
6// distribution or <https://octave.org/copyright/>.
7//
8// This file is part of Octave.
9//
10// Octave is free software: you can redistribute it and/or modify it
11// under the terms of the GNU General Public License as published by
12// the Free Software Foundation, either version 3 of the License, or
13// (at your option) any later version.
14//
15// Octave is distributed in the hope that it will be useful, but
16// WITHOUT ANY WARRANTY; without even the implied warranty of
17// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18// GNU General Public License for more details.
19//
20// You should have received a copy of the GNU General Public License
21// along with Octave; see the file COPYING. If not, see
22// <https://www.gnu.org/licenses/>.
23//
24////////////////////////////////////////////////////////////////////////
25
26#if defined (HAVE_CONFIG_H)
27# include "config.h"
28#endif
29
30#include "base-text-renderer.h"
31#include "ft-text-renderer.h"
32
33#if defined (HAVE_FREETYPE)
34
35#if defined (HAVE_PRAGMA_GCC_DIAGNOSTIC)
36# pragma GCC diagnostic push
37# pragma GCC diagnostic ignored "-Wold-style-cast"
38#endif
39
40#include <ft2build.h>
41#include FT_FREETYPE_H
42#include FT_GLYPH_H
43
44#if defined (HAVE_FONTCONFIG)
45# include <fontconfig/fontconfig.h>
46#endif
47
48#if defined (HAVE_PRAGMA_GCC_DIAGNOSTIC)
49# pragma GCC diagnostic pop
50#endif
51
52#include <clocale>
53#include <cwchar>
54#include <map>
55#include <utility>
56
57#include "singleton-cleanup.h"
58#include "unistr-wrappers.h"
59
60#include "defaults.h"
61#include "error.h"
62#include "file-ops.h"
63#include "oct-env.h"
64#include "pr-output.h"
65#include "sysdep.h"
66#include "text-renderer.h"
67
69
70// FIXME: maybe issue at most one warning per glyph/font/size/weight
71// combination.
72
73static void
74warn_missing_glyph (FT_ULong c)
75{
76 warning_with_id ("Octave:missing-glyph",
77 "text_renderer: skipping missing glyph for character '%lx'", c);
78}
79
80static void
81warn_glyph_render (FT_ULong c)
82{
83 warning_with_id ("Octave:glyph-render",
84 "text_renderer: unable to render glyph for character '%lx'", c);
85}
86
87#if defined (_MSC_VER)
88// FIXME: is this really needed?
89//
90// This is just a trick to avoid multiple symbol definitions.
91// PermMatrix.h contains a dllexport'ed Array<octave_idx_type>
92// that will cause MSVC not to generate a new instantiation and
93// use the imported one instead.
94# include "PermMatrix.h"
95#endif
96
97// Forward declaration
98static void ft_face_destroyed (void *object);
99
100class ft_manager
101{
102private:
103
104 ft_manager ()
105 : m_library (), m_freetype_initialized (false),
106 m_fontconfig_initialized (false)
107 {
108 if (FT_Init_FreeType (&m_library))
109 error ("unable to initialize FreeType library");
110 else
111 m_freetype_initialized = true;
112
113#if defined (HAVE_FONTCONFIG)
114 if (! FcInit ())
115 error ("unable to initialize fontconfig library");
116 else
117 m_fontconfig_initialized = true;
118#endif
119 }
120
121public:
122
123 OCTAVE_DISABLE_COPY_MOVE (ft_manager)
124
125private:
126
127 ~ft_manager ()
128 {
129 if (m_freetype_initialized)
130 FT_Done_FreeType (m_library);
131
132#if defined (HAVE_FONTCONFIG)
133 // FIXME: Skip the call to FcFini because it can trigger the assertion
134 //
135 // octave: fccache.c:507: FcCacheFini: Assertion 'fcCacheChains[i] == ((void *)0)' failed.
136 //
137 // if (m_fontconfig_initialized)
138 // FcFini ();
139#endif
140 }
141
142public:
143
144 static bool instance_ok ()
145 {
146 bool retval = true;
147
148 if (! s_instance)
149 {
150 s_instance = new ft_manager ();
151 singleton_cleanup_list::add (cleanup_instance);
152 }
153
154 return retval;
155 }
156
157 static void cleanup_instance ()
158 { delete s_instance; s_instance = nullptr; }
159
160 static FT_Face get_font (const std::string& name, const std::string& weight,
161 const std::string& angle, double size,
162 FT_ULong c = 0)
163 {
164 return (instance_ok ()
165 ? s_instance->do_get_font (name, weight, angle, size, c)
166 : nullptr);
167 }
168
169 static octave_map get_system_fonts ()
170 {
171 return (instance_ok ()
172 ? s_instance->do_get_system_fonts ()
173 : octave_map ());
174 }
175
176 static void font_destroyed (FT_Face face)
177 {
178 if (instance_ok ())
179 s_instance->do_font_destroyed (face);
180 }
181
182private:
183
184 typedef std::pair<std::string, double> ft_key;
185 typedef std::map<ft_key, FT_Face> ft_cache;
186
187 static octave_map do_get_system_fonts ()
188 {
189 static octave_map font_map;
190
191 if (font_map.isempty ())
192 {
193#if defined (HAVE_FONTCONFIG)
194 FcConfig *config = FcConfigGetCurrent();
195 FcPattern *pat = FcPatternCreate ();
196 FcObjectSet *os = FcObjectSetBuild (FC_FAMILY, FC_SLANT, FC_WEIGHT,
197 FC_CHARSET, nullptr);
198 FcFontSet *fs = FcFontList (config, pat, os);
199
200 if (fs->nfont > 0)
201 {
202 // Mark fonts that have at least all printable ASCII chars
203 FcCharSet *minimal_charset = FcCharSetCreate ();
204 for (int i = 32; i < 127; i++)
205 FcCharSetAddChar (minimal_charset, static_cast<FcChar32> (i));
206
207 string_vector fields (4);
208 fields(0) = "family";
209 fields(1) = "angle";
210 fields(2) = "weight";
211 fields(3) = "suitable";
212
213 dim_vector dv (1, fs->nfont);
214 Cell families (dv);
215 Cell angles (dv);
216 Cell weights (dv);
217 Cell suitable (dv);
218
219 unsigned char *family;
220 int val;
221 for (int i = 0; fs && i < fs->nfont; i++)
222 {
223 FcPattern *font = fs->fonts[i];
224 if (FcPatternGetString (font, FC_FAMILY, 0, &family)
225 == FcResultMatch)
226 families(i) = std::string (reinterpret_cast<char *> (family));
227 else
228 families(i) = "unknown";
229
230 if (FcPatternGetInteger (font, FC_SLANT, 0, &val)
231 == FcResultMatch)
232 angles(i) = (val == FC_SLANT_ITALIC
233 || val == FC_SLANT_OBLIQUE)
234 ? "italic" : "normal";
235 else
236 angles(i) = "unknown";
237
238 if (FcPatternGetInteger (font, FC_WEIGHT, 0, &val)
239 == FcResultMatch)
240 weights(i) = (val == FC_WEIGHT_BOLD
241 || val == FC_WEIGHT_DEMIBOLD)
242 ? "bold" : "normal";
243 else
244 weights(i) = "unknown";
245
246 FcCharSet *cset;
247 if (FcPatternGetCharSet (font, FC_CHARSET, 0, &cset)
248 == FcResultMatch)
249 suitable(i) = (FcCharSetIsSubset (minimal_charset, cset)
250 ? true : false);
251 else
252 suitable(i) = false;
253 }
254
255 font_map = octave_map (dv, fields);
256
257 font_map.assign ("family", families);
258 font_map.assign ("angle", angles);
259 font_map.assign ("weight", weights);
260 font_map.assign ("suitable", suitable);
261
262 // Free up memory within libfontconfig.
263 if (fs)
264 FcFontSetDestroy (fs);
265 if (pat) // Supposed to be freed by FcFontSetDestroy above, but isn't.
266 FcPatternDestroy (pat);
267 if (os)
268 FcObjectSetDestroy (os);
269 if (minimal_charset)
270 FcCharSetDestroy (minimal_charset);
271 }
272#endif
273 }
274
275 return font_map;
276 }
277
278 FT_Face do_get_font (const std::string& name, const std::string& weight,
279 const std::string& angle, double size,
280 FT_ULong search_code_point)
281 {
282 FT_Face retval = nullptr;
283
284#if defined (HAVE_FT_REFERENCE_FACE)
285 // Look first into the font cache, then use fontconfig. If the font
286 // is present in the cache, simply add a reference and return it.
287
288 ft_key key (name + ':' + weight + ':' + angle + ':'
289 + std::to_string (search_code_point), size);
290 ft_cache::const_iterator it = m_cache.find (key);
291
292 if (it != m_cache.end ())
293 {
294 FT_Reference_Face (it->second);
295 return it->second;
296 }
297#endif
298
299 static std::string fonts_dir;
300
301 if (fonts_dir.empty ())
302 {
303 fonts_dir = sys::env::getenv ("OCTAVE_FONTS_DIR");
304
305 if (fonts_dir.empty ())
306#if defined (SYSTEM_FREEFONT_DIR)
307 fonts_dir = SYSTEM_FREEFONT_DIR;
308#else
309 fonts_dir = config::oct_fonts_dir ();
310#endif
311 }
312
313
314 // Default font file
315 std::string file;
316
317 if (! fonts_dir.empty ())
318 {
319 file = fonts_dir + sys::file_ops::dir_sep_str () + "FreeSans";
320
321 if (weight == "bold")
322 file += "Bold";
323
324 if (angle == "italic" || angle == "oblique")
325 file += "Oblique";
326
327 file += ".otf";
328 }
329
330#if defined (HAVE_FONTCONFIG)
331 if ((search_code_point != 0 || name != "*") && m_fontconfig_initialized)
332 {
333 int fc_weight, fc_angle;
334
335 if (weight == "bold")
336 fc_weight = FC_WEIGHT_BOLD;
337 else
338 fc_weight = FC_WEIGHT_NORMAL;
339
340 if (angle == "italic")
341 fc_angle = FC_SLANT_ITALIC;
342 else if (angle == "oblique")
343 fc_angle = FC_SLANT_OBLIQUE;
344 else
345 fc_angle = FC_SLANT_ROMAN;
346
347 FcPattern *pat = FcPatternCreate ();
348
349 FcPatternAddString (pat, FC_FAMILY,
350 (reinterpret_cast<const FcChar8 *>
351 (name.c_str ())));
352
353 FcPatternAddInteger (pat, FC_WEIGHT, fc_weight);
354 FcPatternAddInteger (pat, FC_SLANT, fc_angle);
355 FcPatternAddDouble (pat, FC_PIXEL_SIZE, size);
356
357 if (search_code_point > 0)
358 {
359 FcCharSet *minimal_charset = FcCharSetCreate ();
360 FcCharSetAddChar (minimal_charset,
361 static_cast<FcChar32> (search_code_point));
362 FcPatternAddCharSet (pat, FC_CHARSET, minimal_charset);
363 }
364
365 if (FcConfigSubstitute (nullptr, pat, FcMatchPattern))
366 {
367 FcResult res;
368 FcPattern *match;
369
370 FcDefaultSubstitute (pat);
371
372 match = FcFontMatch (nullptr, pat, &res);
373
374 // FIXME: originally, this test also required that
375 // res != FcResultNoMatch. Is that really needed?
376 if (match)
377 {
378 unsigned char *tmp;
379
380 FcPatternGetString (match, FC_FILE, 0, &tmp);
381 file = reinterpret_cast<char *> (tmp);
382 }
383 else
384 ::warning ("could not match any font: %s-%s-%s-%g, using default font",
385 name.c_str (), weight.c_str (), angle.c_str (),
386 size);
387
388 if (match)
389 FcPatternDestroy (match);
390 }
391
392 FcPatternDestroy (pat);
393 }
394#endif
395
396 if (file.empty ())
397 ::warning ("unable to find default font files");
398 else
399 {
400 std::string ascii_file = sys::get_ASCII_filename (file);
401
402 if (FT_New_Face (m_library, ascii_file.c_str (), 0, &retval))
403 ::warning ("ft_manager: unable to load font: %s", file.c_str ());
404#if defined (HAVE_FT_REFERENCE_FACE)
405 else
406 {
407 // Install a finalizer to notify ft_manager that the font is
408 // being destroyed. The class ft_manager only keeps weak
409 // references to font objects.
410
411 retval->generic.data = new ft_key (key);
412 retval->generic.finalizer = ft_face_destroyed;
413
414 // Insert loaded font into the cache.
415 if (FT_Reference_Face (retval) == 0)
416 m_cache[key] = retval;
417 }
418#endif
419 }
420
421 return retval;
422 }
423
424 void do_font_destroyed (FT_Face face)
425 {
426 if (face->generic.data)
427 {
428 ft_key *pkey = reinterpret_cast<ft_key *> (face->generic.data);
429
430 m_cache.erase (*pkey);
431 delete pkey;
432 face->generic.data = nullptr;
433 FT_Done_Face (face);
434 }
435 }
436
437 //--------
438
439 static ft_manager *s_instance;
440
441 // Cache the fonts loaded by FreeType. This cache only contains
442 // weak references to the fonts, strong references are only present
443 // in class text_renderer.
444 ft_cache m_cache;
445
446 FT_Library m_library;
447 bool m_freetype_initialized;
448 bool m_fontconfig_initialized;
449};
450
451ft_manager *ft_manager::s_instance = nullptr;
452
453static void
454ft_face_destroyed (void *object)
455{
456 ft_manager::font_destroyed (reinterpret_cast<FT_Face> (object));
457}
458
459class OCTINTERP_API ft_text_renderer : public base_text_renderer
460{
461public:
462
463 enum
464 {
465 MODE_BBOX = 0,
466 MODE_RENDER = 1
467 };
468
469public:
470
471 ft_text_renderer ()
472 : base_text_renderer (), m_font (), m_bbox (1, 4, 0.0), m_halign (0),
473 m_xoffset (0), m_line_yoffset (0), m_yoffset (0), m_mode (MODE_BBOX),
474 m_color (dim_vector (1, 3), 0), m_do_strlist (false), m_strlist (),
475 m_line_xoffset (0), m_ymin (0), m_ymax (0), m_deltax (0),
476 m_max_fontsize (0), m_antialias (true)
477 { }
478
479 OCTAVE_DISABLE_COPY_MOVE (ft_text_renderer)
480
481 ~ft_text_renderer () = default;
482
483 void visit (text_element_string& e);
484
485 void visit (text_element_list& e);
486
488
490
491 void visit (text_element_color& e);
492
494
496
498
499 void visit (text_element_symbol& e);
500
502
503 void reset ();
504
505 uint8NDArray get_pixels () const { return m_pixels; }
506
507 Matrix get_boundingbox () const { return m_bbox; }
508
509 uint8NDArray render (text_element *elt, Matrix& box,
510 int rotation = ROTATION_0);
511
512 Matrix get_extent (text_element *elt, double rotation = 0.0);
513 Matrix get_extent (const std::string& txt, double rotation,
515
516 void set_anti_aliasing (bool val) { m_antialias = val; };
517
518 void set_font (const std::string& name, const std::string& weight,
519 const std::string& angle, double size);
520
522
523 void set_color (const Matrix& c);
524
525 void set_mode (int m);
526
527 void text_to_pixels (const std::string& txt,
528 uint8NDArray& pxls, Matrix& bbox,
529 int halign, int valign, double rotation,
531 bool handle_rotation);
532
533private:
534
535 // Class to hold information about fonts and a strong
536 // reference to the font objects loaded by FreeType.
537
538 class ft_font : public text_renderer::font
539 {
540 public:
541
542 ft_font ()
543 : text_renderer::font (), m_face (nullptr) { }
544
545 ft_font (const std::string& nm, const std::string& wt,
546 const std::string& ang, double sz, FT_Face f = nullptr)
547 : text_renderer::font (nm, wt, ang, sz), m_face (f)
548 { }
549
550 ft_font (const ft_font& ft);
551
552 ~ft_font ()
553 {
554 if (m_face)
555 FT_Done_Face (m_face);
556 }
557
558 ft_font& operator = (const ft_font& ft);
559
560 bool is_valid () const { return get_face (); }
561
562 FT_Face get_face () const;
563
564 private:
565
566 mutable FT_Face m_face;
567 };
568
569 void push_new_line ();
570
571 void update_line_bbox ();
572
573 void compute_bbox ();
574
575 int compute_line_xoffset (const Matrix& lb) const;
576
577 FT_UInt process_character (FT_ULong code, FT_UInt previous,
578 std::string& sub_font);
579
580public:
581
582 void text_to_strlist (const std::string& txt,
583 std::list<text_renderer::string>& lst, Matrix& bbox,
584 int halign, int valign, double rotation,
585 const caseless_str& interp);
586
587private:
588
589 // The current font used by the renderer.
590 ft_font m_font;
591
592 // Used to stored the bounding box corresponding to the rendered text.
593 // The bounding box has the form [x, y, w, h] where x and y represent the
594 // coordinates of the bottom left corner relative to the anchor point of
595 // the text (== start of text on the baseline). Due to font descent or
596 // multiple lines, the value y is usually negative.
597 Matrix m_bbox;
598
599 // Used to stored the rendered text. It's a 3D matrix with size MxNx4
600 // where M and N are the width and height of the bounding box.
601 uint8NDArray m_pixels;
602
603 // Used to store the bounding box of each line. This is used to layout
604 // multiline text properly.
605 std::list<Matrix> m_line_bbox;
606
607 // The current horizontal alignment. This is used to align multi-line text.
608 int m_halign;
609
610 // The X offset for the next glyph.
611 int m_xoffset;
612
613 // The Y offset of the baseline for the current line.
614 int m_line_yoffset;
615
616 // The Y offset of the baseline for the next glyph. The offset is relative
617 // to line_yoffset. The total Y offset is computed with:
618 // line_yoffset + yoffset.
619 int m_yoffset;
620
621 // The current mode of the rendering process (box computing or rendering).
622 int m_mode;
623
624 // The base color of the rendered text.
625 uint8NDArray m_color;
626
627 // A list of parsed strings to be used for printing.
628 bool m_do_strlist;
629 std::list<text_renderer::string> m_strlist;
630
631 // The X offset of the baseline for the current line.
632 int m_line_xoffset;
633
634 // Min and max y coordinates of all glyphs in a line.
635 FT_Pos m_ymin;
636 FT_Pos m_ymax;
637
638 // Difference between the advance and the actual extent of the latest glyph
639 FT_Pos m_deltax;
640
641 // Used for computing the distance between lines.
642 double m_max_fontsize;
643
644 // Anti-aliasing.
645 bool m_antialias;
646
647};
648
649void
650ft_text_renderer::set_font (const std::string& name,
651 const std::string& weight,
652 const std::string& angle, double size)
653{
654 // FIXME: take "fontunits" into account
655 m_font = ft_font (name, weight, angle, size, nullptr);
656}
657
659ft_text_renderer::get_system_fonts ()
660{
661 return ft_manager::get_system_fonts ();
662}
663
664void
665ft_text_renderer::push_new_line ()
666{
667 switch (m_mode)
668 {
669 case MODE_BBOX:
670 {
671 // Create a new bbox entry based on the current font.
672
673 FT_Face face = m_font.get_face ();
674
675 if (face)
676 {
677 Matrix bb (1, 5, 0.0);
678
679 m_line_bbox.push_back (bb);
680
681 m_xoffset = m_yoffset = 0;
682 m_ymin = m_ymax = m_deltax = 0;
683 }
684 }
685 break;
686
687 case MODE_RENDER:
688 {
689 // Move to the next line bbox, adjust xoffset based on alignment
690 // and yoffset based on the old and new line bbox.
691
692 Matrix old_bbox = m_line_bbox.front ();
693 m_line_bbox.pop_front ();
694 Matrix new_bbox = m_line_bbox.front ();
695
696 m_xoffset = m_line_xoffset = compute_line_xoffset (new_bbox);
697 m_line_yoffset -= (-old_bbox(1) + math::round (0.4 * m_max_fontsize)
698 + (new_bbox(3) + new_bbox(1)));
699 m_yoffset = 0;
700 m_ymin = m_ymax = m_deltax = 0;
701 }
702 break;
703 }
704}
705
706int
707ft_text_renderer::compute_line_xoffset (const Matrix& lb) const
708{
709 if (! m_bbox.isempty ())
710 {
711 switch (m_halign)
712 {
713 case 0:
714 return 0;
715 case 1:
716 return (m_bbox(2) - lb(2)) / 2;
717 case 2:
718 return (m_bbox(2) - lb(2));
719 }
720 }
721
722 return 0;
723}
724
725void
726ft_text_renderer::compute_bbox ()
727{
728 // Stack the various line bbox together and compute the final
729 // bounding box for the entire text string.
730
731 m_bbox = Matrix ();
732
733 switch (m_line_bbox.size ())
734 {
735 case 0:
736 break;
737
738 case 1:
739 m_bbox = m_line_bbox.front ().extract (0, 0, 0, 3);
740 break;
741
742 default:
743 for (const auto& lbox : m_line_bbox)
744 {
745 if (m_bbox.isempty ())
746 m_bbox = lbox.extract (0, 0, 0, 3);
747 else
748 {
749 double delta = math::round (0.4 * m_max_fontsize) + lbox(3);
750 m_bbox(1) -= delta;
751 m_bbox(3) += delta;
752 m_bbox(2) = math::max (m_bbox(2), lbox(2));
753 }
754 }
755 break;
756 }
757}
758
759void
760ft_text_renderer::update_line_bbox ()
761{
762 // Called after a font change, when in MODE_BBOX mode, to update the
763 // current line bbox with the new font metrics. This also includes the
764 // current yoffset, that is the offset of the current glyph's baseline
765 // the line's baseline.
766
767 if (m_mode == MODE_BBOX)
768 {
769 Matrix& bb = m_line_bbox.back ();
770 bb(1) = m_ymin;
771 // Add one pixel to the bbox height to avoid occasional text clipping.
772 // See bug #55328.
773 bb(3) = (m_ymax + 1) - m_ymin;
774 if (m_deltax > 0)
775 bb(2) += m_deltax;
776 }
777}
778
779void
780ft_text_renderer::set_mode (int m)
781{
782 m_mode = m;
783
784 switch (m_mode)
785 {
786 case MODE_BBOX:
787 m_xoffset = m_line_yoffset = m_yoffset = 0;
788 m_max_fontsize = 0.0;
789 m_bbox = Matrix (1, 4, 0.0);
790 m_line_bbox.clear ();
791 push_new_line ();
792 break;
793
794 case MODE_RENDER:
795 if (m_bbox.numel () != 4)
796 {
797 ::error ("ft_text_renderer: invalid bounding box, cannot render");
798
799 m_xoffset = m_line_yoffset = m_yoffset = 0;
800 m_pixels = uint8NDArray ();
801 }
802 else
803 {
804 dim_vector d (4, octave_idx_type (m_bbox(2)),
805 octave_idx_type (m_bbox(3)));
806 m_pixels = uint8NDArray (d, static_cast<uint8_t> (0));
807 m_xoffset = compute_line_xoffset (m_line_bbox.front ());
808 m_line_yoffset = -m_bbox(1);
809 m_yoffset = 0;
810 }
811 break;
812
813 default:
814 error ("ft_text_renderer: invalid mode '%d'", m_mode);
815 break;
816 }
817}
818
819bool
820is_opaque (const FT_GlyphSlot& glyph, const int x, const int y)
821{
822 // Borrowed from https://stackoverflow.com/questions/14800827/
823 // indexing-pixels-in-a-monochrome-freetype-glyph-buffer
824 int pitch = std::abs (glyph->bitmap.pitch);
825 unsigned char *row = &glyph->bitmap.buffer[pitch * y];
826 char cvalue = row[x >> 3];
827
828 return ((cvalue & (128 >> (x & 7))) != 0);
829}
830
831FT_UInt
832ft_text_renderer::process_character (FT_ULong code, FT_UInt previous,
833 std::string& sub_name)
834{
835 FT_Face face = m_font.get_face ();
836
837 sub_name = face->family_name;
838
839 FT_UInt glyph_index = 0;
840
841 if (face)
842 {
843 glyph_index = FT_Get_Char_Index (face, code);
844
845 if (code != '\n' && code != '\t'
846 && (! glyph_index
847 || FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT)))
848 {
849#if defined (HAVE_FONTCONFIG)
850 // Try to substitue font
851 FT_Face sub_face = ft_manager::get_font (m_font.get_name (),
852 m_font.get_weight (),
853 m_font.get_angle (),
854 m_font.get_size (),
855 code);
856
857 if (sub_face)
858 {
859 FT_Set_Char_Size (sub_face, 0, m_font.get_size ()*64, 0, 0);
860
861 glyph_index = FT_Get_Char_Index (sub_face, code);
862
863 if (glyph_index
864 && (FT_Load_Glyph (sub_face, glyph_index, FT_LOAD_DEFAULT)
865 == 0))
866 {
867 static std::string prev_sub_name;
868
869 if (prev_sub_name.empty ()
870 || prev_sub_name != std::string (sub_face->family_name))
871 {
872 prev_sub_name = sub_face->family_name;
873 warning_with_id ("Octave:substituted-glyph",
874 "text_renderer: substituting font to '%s' for some characters",
875 sub_face->family_name);
876 }
877
878 ft_font saved_font = m_font;
879
880 m_font = ft_font (m_font.get_name (), m_font.get_weight (),
881 m_font.get_angle (), m_font.get_size (),
882 sub_face);
883
884 process_character (code, previous, sub_name);
885
886 m_font = saved_font;
887 }
888 else
889 {
890 glyph_index = 0;
891 warn_missing_glyph (code);
892 }
893 }
894 else
895 {
896 glyph_index = 0;
897 warn_missing_glyph (code);
898 }
899#else
900 glyph_index = 0;
901 warn_missing_glyph (code);
902#endif
903 }
904 else if ((code == '\n') || (code == '\t'))
905 {
906 glyph_index = FT_Get_Char_Index (face, ' ');
907 if (! glyph_index
908 || FT_Load_Glyph (face, glyph_index, FT_LOAD_DEFAULT))
909 {
910 glyph_index = 0;
911 warn_missing_glyph (' ');
912 }
913 else if (code == '\n')
914 push_new_line ();
915 else
916 {
917 // Advance to next multiple of 4 times the width of the "space"
918 // character.
919 int x_tab = 4 * (face->glyph->advance.x >> 6);
920 m_xoffset = (1 + std::floor (1. * m_xoffset / x_tab)) * x_tab;
921 }
922 }
923 else
924 {
925 switch (m_mode)
926 {
927 case MODE_RENDER:
928 if (FT_Render_Glyph (face->glyph, (m_antialias
929 ? FT_RENDER_MODE_NORMAL
930 : FT_RENDER_MODE_MONO)))
931 {
932 glyph_index = 0;
933 warn_glyph_render (code);
934 }
935 else
936 {
937 FT_Bitmap& bitmap = face->glyph->bitmap;
938 int x0, y0;
939
940 if (previous)
941 {
942 FT_Vector delta;
943
944 FT_Get_Kerning (face, previous, glyph_index,
945 FT_KERNING_DEFAULT, &delta);
946
947 m_xoffset += (delta.x >> 6);
948 }
949
950 x0 = m_xoffset + face->glyph->bitmap_left;
951 y0 = m_line_yoffset + m_yoffset
952 + (face->glyph->bitmap_top - 1);
953
954 // 'w' seems to have a negative -1
955 // face->glyph->bitmap_left, this is so we don't index out
956 // of bound, and assumes we've allocated the right amount of
957 // horizontal space in the bbox.
958 if (x0 < 0)
959 x0 = 0;
960
961 for (int r = 0; static_cast<unsigned int> (r) < bitmap.rows; r++)
962 for (int c = 0; static_cast<unsigned int> (c) < bitmap.width; c++)
963 {
964 unsigned char pix
965 = (m_antialias
966 ? bitmap.buffer[r*bitmap.width+c]
967 : (is_opaque (face->glyph, c, r) ? 255 : 0));
968
969 if (x0+c < 0 || x0+c >= m_pixels.dim2 ()
970 || y0-r < 0 || y0-r >= m_pixels.dim3 ())
971 {
972 // ::warning ("ft_text_renderer: x %d, y %d",
973 // x0+c, y0-r);
974 }
975 else if (m_pixels(3, x0+c, y0-r).value () == 0)
976 {
977 m_pixels(0, x0+c, y0-r) = m_color(0);
978 m_pixels(1, x0+c, y0-r) = m_color(1);
979 m_pixels(2, x0+c, y0-r) = m_color(2);
980 m_pixels(3, x0+c, y0-r) = pix;
981 }
982 }
983
984 m_xoffset += (face->glyph->advance.x >> 6);
985 }
986 break;
987
988 case MODE_BBOX:
989 Matrix& bb = m_line_bbox.back ();
990
991 // If we have a previous glyph, use kerning information. This
992 // usually means moving a bit backward before adding the next
993 // glyph. That is, "delta.x" is usually < 0.
994 if (previous)
995 {
996 FT_Vector delta;
997
998 FT_Get_Kerning (face, previous, glyph_index,
999 FT_KERNING_DEFAULT, &delta);
1000
1001 m_xoffset += (delta.x >> 6);
1002 }
1003
1004 // Extend current X offset box by the width of the current
1005 // glyph. Then extend the line bounding box if necessary.
1006
1007 m_xoffset += (face->glyph->advance.x >> 6);
1008 bb(2) = math::max (bb(2), m_xoffset);
1009
1010 // Store the actual bbox vertical coordinates of this character
1011 FT_Glyph glyph;
1012 if (FT_Get_Glyph (face->glyph, &glyph))
1013 warn_glyph_render (code);
1014 else
1015 {
1016 FT_BBox glyph_bbox;
1017 FT_Glyph_Get_CBox (glyph, FT_GLYPH_BBOX_UNSCALED,
1018 &glyph_bbox);
1019 m_deltax = (glyph_bbox.xMax - face->glyph->advance.x) >> 6;
1020 m_ymin = math::min ((glyph_bbox.yMin >> 6) + m_yoffset,
1021 m_ymin);
1022 m_ymax = math::max ((glyph_bbox.yMax >> 6) + m_yoffset,
1023 m_ymax);
1024 FT_Done_Glyph (glyph);
1025 update_line_bbox ();
1026 }
1027 break;
1028 }
1029 }
1030 }
1031
1032 return glyph_index;
1033}
1034
1035void
1036ft_text_renderer::text_to_strlist (const std::string& txt,
1037 std::list<text_renderer::string>& lst,
1038 Matrix& box,
1039 int ha, int va, double rot,
1040 const caseless_str& interp)
1041{
1042 uint8NDArray pxls;
1043
1044 // First run text_to_pixels which will also build the string list
1045
1046 m_strlist = std::list<text_renderer::string> ();
1047
1048 unwind_protect_var<bool> restore_var1 (m_do_strlist);
1050 restore_var2 (m_strlist);
1051
1052 m_do_strlist = true;
1053
1054 text_to_pixels (txt, pxls, box, ha, va, rot, interp, false);
1055
1056 lst = m_strlist;
1057}
1058
1059void
1060ft_text_renderer::visit (text_element_string& e)
1061{
1062 if (m_font.is_valid ())
1063 {
1064 m_max_fontsize = std::max (m_max_fontsize, m_font.get_size ());
1065 FT_UInt glyph_index, previous = 0;
1066
1067 std::string str = e.string_value ();
1068 const uint8_t *c = reinterpret_cast<const uint8_t *> (str.c_str ());
1069 uint32_t u32_c;
1070
1071 std::size_t n = str.size ();
1072 std::size_t icurr = 0;
1073 std::size_t ibegin = 0;
1074
1075 // Initialize a new string
1076 text_renderer::string fs (str, m_font, m_xoffset, m_yoffset);
1077
1078 std::string fname = m_font.get_face ()->family_name;
1079
1080 if (fname.find (" ") != std::string::npos)
1081 fname = "'" + fname + "'";
1082
1083 fs.set_family (fname);
1084
1085 std::vector<double> xdata;
1086 std::string sub_name;
1087
1088 while (n > 0)
1089 {
1090 // Retrieve the length and the u32 representation of the current
1091 // character
1092 int mblen = octave_u8_strmbtouc_wrapper (&u32_c, c + icurr);
1093 if (mblen < 1)
1094 {
1095 // This is not an UTF-8 character, use a replacement character
1096 mblen = 1;
1097 u32_c = 0xFFFD;
1098 }
1099
1100 n -= mblen;
1101
1102 if (m_do_strlist && m_mode == MODE_RENDER)
1103 {
1104 if (u32_c == 10)
1105 {
1106 // Finish previous string in m_strlist before processing
1107 // the newline character
1108 fs.set_y (m_line_yoffset + m_yoffset);
1109 fs.set_color (m_color);
1110
1111 std::string s = str.substr (ibegin, icurr - ibegin);
1112 if (! s.empty ())
1113 {
1114 fs.set_string (s);
1115 fs.set_y (m_line_yoffset + m_yoffset);
1116 fs.set_xdata (xdata);
1117 fs.set_family (fname);
1118 m_strlist.push_back (fs);
1119 }
1120 }
1121 else
1122 xdata.push_back (m_xoffset);
1123 }
1124
1125 glyph_index = process_character (u32_c, previous, sub_name);
1126
1127 if (m_do_strlist && m_mode == MODE_RENDER && ! sub_name.empty ())
1128 {
1129 // Add substitution font to the family name stack
1130 std::string tmp_family = fs.get_family ();
1131
1132 if (tmp_family.find (sub_name) == std::string::npos)
1133 {
1134 if (sub_name.find (" ") != std::string::npos)
1135 sub_name = "'" + sub_name + "'";
1136
1137 fs.set_family (tmp_family + ", " + sub_name);
1138 }
1139 }
1140
1141 if (u32_c == 10)
1142 {
1143 previous = 0;
1144
1145 if (m_do_strlist && m_mode == MODE_RENDER)
1146 {
1147 // Start a new string in m_strlist
1148 ibegin = icurr+1;
1149 xdata.clear ();
1150 fs = text_renderer::string (str.substr (ibegin), m_font,
1151 m_line_xoffset, m_yoffset);
1152 }
1153 }
1154 else
1155 previous = glyph_index;
1156
1157 icurr += mblen;
1158 }
1159
1160 if (m_do_strlist && m_mode == MODE_RENDER
1161 && ! fs.get_string ().empty ())
1162 {
1163 fs.set_y (m_line_yoffset + m_yoffset);
1164 fs.set_color (m_color);
1165 fs.set_xdata (xdata);
1166 m_strlist.push_back (fs);
1167 }
1168 }
1169}
1170
1171void
1172ft_text_renderer::visit (text_element_list& e)
1173{
1174 // Save and restore (after processing the list) the current font and color.
1175
1176 ft_font saved_font (m_font);
1177 uint8NDArray saved_color (m_color);
1178
1180
1181 m_font = saved_font;
1182 m_color = saved_color;
1183}
1184
1185void
1186ft_text_renderer::visit (text_element_subscript& e)
1187{
1188 ft_font saved_font (m_font);
1189 int saved_line_yoffset = m_line_yoffset;
1190 int saved_yoffset = m_yoffset;
1191
1192 double sz = m_font.get_size ();
1193
1194 // Reducing font size by 70% produces decent results.
1195 set_font (m_font.get_name (), m_font.get_weight (), m_font.get_angle (),
1196 std::max (5.0, sz * 0.7));
1197
1198 if (m_font.is_valid ())
1199 {
1200 // Shifting the baseline by 15% of the font size gives decent results.
1201 m_yoffset -= std::ceil (sz * 0.15);
1202
1203 if (m_mode == MODE_BBOX)
1204 update_line_bbox ();
1205 }
1206
1208
1209 m_font = saved_font;
1210 // If line_yoffset changed, this means we moved to a new line; hence yoffset
1211 // cannot be restored, because the saved value is not relevant anymore.
1212 if (m_line_yoffset == saved_line_yoffset)
1213 m_yoffset = saved_yoffset;
1214}
1215
1216void
1217ft_text_renderer::visit (text_element_superscript& e)
1218{
1219 ft_font saved_font (m_font);
1220 int saved_line_yoffset = m_line_yoffset;
1221 int saved_yoffset = m_yoffset;
1222
1223 double sz = m_font.get_size ();
1224
1225 // Reducing font size by 70% produces decent results.
1226 set_font (m_font.get_name (), m_font.get_weight (), m_font.get_angle (),
1227 std::max (5.0, sz * 0.7));
1228
1229 if (saved_font.is_valid ())
1230 {
1231 // Shifting the baseline by 40% of the font size gives decent results.
1232 m_yoffset += std::ceil (sz * 0.4);
1233
1234 if (m_mode == MODE_BBOX)
1235 update_line_bbox ();
1236 }
1237
1239
1240 m_font = saved_font;
1241 // If line_yoffset changed, this means we moved to a new line; hence yoffset
1242 // cannot be restored, because the saved value is not relevant anymore.
1243 if (m_line_yoffset == saved_line_yoffset)
1244 m_yoffset = saved_yoffset;
1245}
1246
1247void
1248ft_text_renderer::visit (text_element_color& e)
1249{
1250 if (m_mode == MODE_RENDER)
1251 set_color (e.get_color ());
1252}
1253
1254void
1255ft_text_renderer::visit (text_element_fontsize& e)
1256{
1257 double sz = e.get_fontsize ();
1258
1259 // FIXME: Matlab documentation says that the font size is expressed
1260 // in the text object FontUnit.
1261
1262 set_font (m_font.get_name (), m_font.get_weight (),
1263 m_font.get_angle (), sz);
1264
1265 if (m_mode == MODE_BBOX)
1266 update_line_bbox ();
1267}
1268
1269void
1270ft_text_renderer::visit (text_element_fontname& e)
1271{
1272 set_font (e.get_fontname (), m_font.get_weight (), m_font.get_angle (),
1273 m_font.get_size ());
1274
1275 if (m_mode == MODE_BBOX)
1276 update_line_bbox ();
1277}
1278
1279void
1280ft_text_renderer::visit (text_element_fontstyle& e)
1281{
1282 switch (e.get_fontstyle ())
1283 {
1285 set_font (m_font.get_name (), "normal", "normal", m_font.get_size ());
1286 break;
1287
1289 set_font (m_font.get_name (), "bold", "normal", m_font.get_size ());
1290 break;
1291
1293 set_font (m_font.get_name (), "normal", "italic", m_font.get_size ());
1294 break;
1295
1297 set_font (m_font.get_name (), "normal", "oblique", m_font.get_size ());
1298 break;
1299 }
1300
1301 if (m_mode == MODE_BBOX)
1302 update_line_bbox ();
1303}
1304
1305void
1306ft_text_renderer::visit (text_element_symbol& e)
1307{
1308 uint32_t code = e.get_symbol_code ();
1309
1310 std::vector<double> xdata (1, m_xoffset);
1311 text_renderer::string fs ("-", m_font, m_xoffset, m_yoffset);
1312
1313 if (code != text_element_symbol::invalid_code && m_font.is_valid ())
1314 {
1315 std::string sub_name;
1316
1317 process_character (code, 0, sub_name);
1318
1319 if (m_do_strlist && m_mode == MODE_RENDER)
1320 {
1321 if (! sub_name.empty ())
1322 {
1323 // Add substitution font to the family name
1324 std::string tmp_family = fs.get_family ();
1325
1326 if (tmp_family.find (sub_name) == std::string::npos)
1327 {
1328 if (sub_name.find (" ") != std::string::npos)
1329 sub_name = "'" + sub_name + "'";
1330
1331 fs.set_family (tmp_family + ", " + sub_name);
1332 }
1333 }
1334
1335 fs.set_code (code);
1336 fs.set_xdata (xdata);
1337 }
1338 }
1339 else if (m_font.is_valid ())
1340 ::warning ("ignoring unknown symbol: %d", e.get_symbol ());
1341
1342 if (m_do_strlist && m_mode == MODE_RENDER && fs.get_code ())
1343 {
1344 fs.set_y (m_line_yoffset + m_yoffset);
1345 fs.set_color (m_color);
1346 fs.set_family (m_font.get_face ()->family_name);
1347 m_strlist.push_back (fs);
1348 }
1349}
1350
1351void
1352ft_text_renderer::visit (text_element_combined& e)
1353{
1354 int saved_xoffset = m_xoffset;
1355 int max_xoffset = m_xoffset;
1356
1357 for (auto *txt_elt : e)
1358 {
1359 m_xoffset = saved_xoffset;
1360 txt_elt->accept (*this);
1361 max_xoffset = math::max (m_xoffset, max_xoffset);
1362 }
1363
1364 m_xoffset = max_xoffset;
1365}
1366
1367void
1368ft_text_renderer::reset ()
1369{
1370 set_mode (MODE_BBOX);
1371 set_color (Matrix (1, 3, 0.0));
1372 m_strlist = std::list<text_renderer::string> ();
1373}
1374
1375void
1376ft_text_renderer::set_color (const Matrix& c)
1377{
1378 if (c.numel () == 3)
1379 {
1380 m_color(0) = static_cast<uint8_t> (c(0)*255);
1381 m_color(1) = static_cast<uint8_t> (c(1)*255);
1382 m_color(2) = static_cast<uint8_t> (c(2)*255);
1383 }
1384 else
1385 ::warning ("ft_text_renderer::set_color: invalid color");
1386}
1387
1389ft_text_renderer::render (text_element *elt, Matrix& box, int rotation)
1390{
1391 set_mode (MODE_BBOX);
1392 elt->accept (*this);
1393 compute_bbox ();
1394 box = m_bbox;
1395
1396 set_mode (MODE_RENDER);
1397
1398 if (m_pixels.numel () > 0)
1399 {
1400 elt->accept (*this);
1401
1402 rotate_pixels (m_pixels, rotation);
1403 }
1404
1405 return m_pixels;
1406}
1407
1408// Note:
1409// x-extent accurately measures width of glyphs.
1410// y-extent is overly large because it is measured from baseline-to-baseline.
1411// Calling routines, such as ylabel, may need to account for this mismatch.
1412
1413Matrix
1414ft_text_renderer::get_extent (text_element *elt, double rotation)
1415{
1416 set_mode (MODE_BBOX);
1417 elt->accept (*this);
1418 compute_bbox ();
1419
1420 Matrix extent (1, 2, 0.0);
1421
1422 switch (rotation_to_mode (rotation))
1423 {
1424 case ROTATION_0:
1425 case ROTATION_180:
1426 extent(0) = m_bbox(2);
1427 extent(1) = m_bbox(3);
1428 break;
1429
1430 case ROTATION_90:
1431 case ROTATION_270:
1432 extent(0) = m_bbox(3);
1433 extent(1) = m_bbox(2);
1434 }
1435
1436 return extent;
1437}
1438
1439Matrix
1440ft_text_renderer::get_extent (const std::string& txt, double rotation,
1442{
1444 Matrix extent = get_extent (elt, rotation);
1445 delete elt;
1446
1447 return extent;
1448}
1449
1450void
1451ft_text_renderer::text_to_pixels (const std::string& txt,
1452 uint8NDArray& pxls, Matrix& box,
1453 int _halign, int valign, double rotation,
1455 bool handle_rotation)
1456{
1457 int rot_mode = rotation_to_mode (rotation);
1458
1459 m_halign = _halign;
1460
1462 pxls = render (elt, box, rot_mode);
1463 delete elt;
1464
1465 if (pxls.isempty ())
1466 return; // nothing to render
1467
1468 // Move X0 and Y0 depending on alignments and eventually swap all values
1469 // for text rotated 90° 180° or 270°
1470 fix_bbox_anchor (box, m_halign, valign, rot_mode, handle_rotation);
1471}
1472
1473ft_text_renderer::ft_font::ft_font (const ft_font& ft)
1474 : text_renderer::font (ft), m_face (nullptr)
1475{
1476#if defined (HAVE_FT_REFERENCE_FACE)
1477 FT_Face ft_face = ft.get_face ();
1478
1479 if (ft_face && FT_Reference_Face (ft_face) == 0)
1480 m_face = ft_face;
1481#endif
1482}
1483
1484ft_text_renderer::ft_font&
1485ft_text_renderer::ft_font::operator = (const ft_font& ft)
1486{
1487 if (&ft != this)
1488 {
1490
1491 if (m_face)
1492 {
1493 FT_Done_Face (m_face);
1494 m_face = nullptr;
1495 }
1496
1497#if defined (HAVE_FT_REFERENCE_FACE)
1498 FT_Face ft_face = ft.get_face ();
1499
1500 if (ft_face && FT_Reference_Face (ft_face) == 0)
1501 m_face = ft_face;
1502#endif
1503 }
1504
1505 return *this;
1506}
1507
1508FT_Face
1509ft_text_renderer::ft_font::get_face () const
1510{
1511 if (! m_face && ! m_name.empty ())
1512 {
1513 m_face = ft_manager::get_font (m_name, m_weight, m_angle, m_size);
1514
1515 if (m_face)
1516 {
1517 if (FT_Set_Char_Size (m_face, 0, m_size*64, 0, 0))
1518 ::warning ("ft_text_renderer: unable to set font size to %g", m_size);
1519 }
1520 else
1521 ::warning ("ft_text_renderer: unable to load appropriate font");
1522 }
1523
1524 return m_face;
1525}
1526
1527OCTAVE_END_NAMESPACE(octave)
1528
1529#endif
1530
1532
1535{
1536#if defined (HAVE_FREETYPE)
1537 return new ft_text_renderer ();
1538#else
1539 return 0;
1540#endif
1541}
1542
1543OCTAVE_END_NAMESPACE(octave)
bool isempty() const
Size of the specified dimension.
Definition Array.h:652
octave_idx_type numel() const
Number of elements in the array.
Definition Array.h:418
Definition Cell.h:41
virtual Matrix get_extent(text_element *elt, double rotation)=0
virtual void text_to_pixels(const std::string &txt, uint8NDArray &pxls, Matrix &bbox, int halign, int valign, double rotation, const caseless_str &interpreter, bool handle_rotation)=0
virtual void text_to_strlist(const std::string &txt, std::list< text_renderer::string > &lst, Matrix &box, int halign, int valign, double rotation, const caseless_str &interpreter="tex")=0
virtual void set_color(const Matrix &c)=0
virtual void set_anti_aliasing(bool val)=0
virtual octave_map get_system_fonts()=0
virtual void set_font(const std::string &name, const std::string &weight, const std::string &angle, double size)=0
Vector representing the dimensions (size) of an Array.
Definition dim-vector.h:90
void assign(const std::string &k, const Cell &val)
Definition oct-map.h:344
bool isempty() const
Definition oct-map.h:370
static void add(fptr f)
const std::string & get_fontname() const
double get_fontsize() const
fontstyle get_fontstyle() const
std::string string_value() const
Definition text-engine.h:74
uint32_t get_symbol_code() const
int get_symbol() const
Definition text-engine.h:96
virtual void accept(text_processor &p)=0
virtual text_element * parse(const std::string &s)=0
virtual void reset()
virtual void visit(text_element_string &)
font & operator=(const font &ft)
OCTAVE_BEGIN_NAMESPACE(octave) static octave_value daspk_fcn
void warning(const char *fmt,...)
Definition error.cc:1078
void warning_with_id(const char *id, const char *fmt,...)
Definition error.cc:1093
void error(const char *fmt,...)
Definition error.cc:1003
base_text_renderer * make_ft_text_renderer()
bool is_opaque(const FT_GlyphSlot &glyph, const int x, const int y)
F77_RET_T const F77_DBLE const F77_DBLE F77_DBLE * d
F77_RET_T const F77_DBLE * x
F77_RET_T const F77_DBLE const F77_DBLE * f
intNDArray< octave_uint8 > uint8NDArray
int octave_u8_strmbtouc_wrapper(uint32_t *puc, const uint8_t *src)