Debian Codegraph @

garglk/draw.cpp

raw symbols SCIP
1 // Copyright (C) 2006-2009 by Tor Andersson, Jesse McGrew.
2 // Copyright (C) 2010 by Ben Cressey, Chris Spiegel.
3 //
4 // This file is part of Gargoyle.
5 //
6 // Gargoyle is free software; you can redistribute it and/or modify
7 // it under the terms of the GNU General Public License as published by
8 // the Free Software Foundation; either version 2 of the License, or
9 // (at your option) any later version.
10 //
11 // Gargoyle is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License
17 // along with Gargoyle; if not, write to the Free Software
18 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19
20 #include <algorithm>
21 #include <array>
22 #include <cmath>
23 #include <cstddef>
24 #include <functional>
25 #include <iostream>
26 #include <stdexcept>
27 #include <string>
28 #include <unordered_map>
29 #include <utility>
30 #include <vector>
31
32 #include "format.h"
33 #include "optional.hpp"
34
35 #include "glk.h"
36 #include "garglk.h"
37
38 #include <ft2build.h>
39 #include FT_FREETYPE_H
40 #include FT_OUTLINE_H
41 #include FT_LCD_FILTER_H
42
43 #ifdef _WIN32
44 #include <shlwapi.h>
45 #include <windows.h>
46 #endif
47
48 using namespace std::literals;
49
50 #define UNICODE_QUESTION_MARK 63
51
52 #define GAMMA_BITS 11
53 #define GAMMA_MAX ((1 << GAMMA_BITS) - 1)
54
55 #define mul255(a, b) ((static_cast<short>(a) * (b) + 127) / 255)
56 #define mulhigh(a, b) ((static_cast<int>(a) * (b) + (1 << (GAMMA_BITS - 1)) - 1) / GAMMA_MAX)
57 #define grayscale(r, g, b) ((30 * (r) + 59 * (g) + 11 * (b)) / 100)
58
59 static std::string convert_ft_error(FT_Error err, const std::string &basemsg);
60
61 namespace {
62
63 struct Bitmap {
64 int w, h, lsb, top, pitch;
65 std::vector<unsigned char> data;
66 };
67
68 struct FontEntry {
69 int adv;
70 std::array<Bitmap, GLI_SUBPIX> glyph;
71 };
72
73 struct UniqueFaceDeleter {
74 void operator()(FT_Face face) const {
75 FT_Done_Face(face);
76 }
77 };
78
79 using UniqueFace = std::unique_ptr<std::remove_pointer_t<FT_Face>, UniqueFaceDeleter>;
80
81 class Font {
82 public:
83 class LoadError : public std::exception {
84 public:
85 LoadError(FT_Error err, std::string filename, const std::string &basemsg) :
86 m_filename(std::move(filename)),
87 m_what(convert_ft_error(err, basemsg))
88 {
89 }
90
91 const std::string &filename() const {
92 return m_filename;
93 }
94
95 const char *what() const noexcept override {
96 return m_what.c_str();
97 }
98
99 private:
100 std::string m_filename;
101 std::string m_what;
102 };
103
104 Font(FontFace fontface, UniqueFace face, const std::string &fontpath);
105
106 FontEntry getglyph(glui32 cid);
107 int charkern(glui32 c0, glui32 c1);
108 const UniqueFace &face() {
109 return m_face;
110 }
111
112 private:
113 UniqueFace m_face;
114 bool m_make_bold = false;
115 bool m_make_oblique = false;
116 bool m_kerned = false;
117 std::unordered_map<unsigned long long, int> m_kerncache;
118 };
119
120 }
121
122 //
123 // Globals
124 //
125
126 std::unordered_map<FontFace, std::vector<std::string>> gli_conf_glyph_substitution_files;
127
128 static std::array<std::uint16_t, 256> gammamap;
129 static std::array<unsigned char, 1 << GAMMA_BITS> gammainv;
130
131 static std::unordered_map<FontFace, Font> gfont_table;
132 static std::unordered_map<FontFace, std::vector<Font>> glyph_substitution_fonts;
133
134 int gli_cellw = 8;
135 int gli_cellh = 8;
136
137 Canvas<3> gli_image_rgb;
138
139 static FT_Library ftlib;
140 static FT_Matrix ftmat;
141
142 static bool use_freetype_preset_filter = false;
143 static FT_LcdFilter freetype_preset_filter = FT_LCD_FILTER_DEFAULT;
144
145 bool garglk::set_lcdfilter(const std::string &filter)
146 {
147 use_freetype_preset_filter = true;
148
149 if (filter == "none") {
150 freetype_preset_filter = FT_LCD_FILTER_NONE;
151 } else if (filter == "default") {
152 freetype_preset_filter = FT_LCD_FILTER_DEFAULT;
153 } else if (filter == "light") {
154 freetype_preset_filter = FT_LCD_FILTER_LIGHT;
155 } else if (filter == "legacy") {
156 freetype_preset_filter = FT_LCD_FILTER_LEGACY;
157 } else if (filter == "custom") {
158 use_freetype_preset_filter = false;
159 } else {
160 use_freetype_preset_filter = false;
161 return false;
162 }
163
164 return true;
165 }
166
167 //
168 // Font loading
169 //
170
171 static std::string convert_ft_error(FT_Error err, const std::string &basemsg)
172 {
173 // FT_Error_String() was introduced in FreeType 2.10.0.
174 #if FREETYPE_MAJOR == 2 && FREETYPE_MINOR < 10
175 const char *errstr = nullptr;
176 #else
177 // If FreeType was not built with FT_CONFIG_OPTION_ERROR_STRINGS,
178 // this will always be null.
179 const char *errstr = FT_Error_String(err);
180 #endif
181
182 if (errstr == nullptr) {
183 return Format("{} (error code {})", basemsg, err);
184 } else {
185 return Format("{}: {}", basemsg, errstr);
186 }
187 }
188
189 namespace {
190
191 FontEntry Font::getglyph(glui32 cid)
192 {
193 FT_Vector v;
194 int err;
195 glui32 gid;
196 FontEntry entry;
197 std::size_t datasize;
198
199 gid = FT_Get_Char_Index(m_face.get(), cid);
200 if (gid == 0) {
201 throw std::out_of_range(Format("no glyph for {}", cid));
202 }
203
204 for (int x = 0; x < GLI_SUBPIX; x++) {
205 v.x = (x * 64) / GLI_SUBPIX;
206 v.y = 0;
207
208 FT_Set_Transform(m_face.get(), nullptr, &v);
209
210 err = FT_Load_Glyph(m_face.get(), gid,
211 FT_LOAD_NO_BITMAP | FT_LOAD_NO_HINTING);
212 if (err != 0) {
213 throw std::runtime_error(convert_ft_error(err, "FT_Load_Glyph"));
214 }
215
216 if (m_make_bold) {
217 FT_Outline_Embolden(&m_face->glyph->outline, FT_MulFix(m_face->units_per_EM, m_face->size->metrics.y_scale) / 24);
218 }
219
220 if (m_make_oblique) {
221 FT_Outline_Transform(&m_face->glyph->outline, &ftmat);
222 }
223
224 if (gli_conf_lcd) {
225 if (use_freetype_preset_filter) {
226 FT_Library_SetLcdFilter(ftlib, freetype_preset_filter);
227 } else {
228 FT_Library_SetLcdFilterWeights(ftlib, gli_conf_lcd_weights.data());
229 }
230
231 err = FT_Render_Glyph(m_face->glyph, FT_RENDER_MODE_LCD);
232 } else {
233 err = FT_Render_Glyph(m_face->glyph, FT_RENDER_MODE_LIGHT);
234 }
235
236 if (err != 0) {
237 throw std::runtime_error(convert_ft_error(err, "FT_Render_Glyph"));
238 }
239
240 datasize = m_face->glyph->bitmap.pitch * m_face->glyph->bitmap.rows;
241 entry.adv = (m_face->glyph->advance.x * GLI_SUBPIX + 32) / 64;
242
243 entry.glyph[x].lsb = m_face->glyph->bitmap_left;
244 entry.glyph[x].top = m_face->glyph->bitmap_top;
245 entry.glyph[x].w = m_face->glyph->bitmap.width;
246 entry.glyph[x].h = m_face->glyph->bitmap.rows;
247 entry.glyph[x].pitch = m_face->glyph->bitmap.pitch;
248 entry.glyph[x].data.assign(&m_face->glyph->bitmap.buffer[0], &m_face->glyph->bitmap.buffer[datasize]);
249 }
250
251 return entry;
252 }
253
254 }
255
256 // Look in a system-wide location for the fallback Gargoyle fonts; on
257 // Unix this is generally somewhere like /usr/share/gargoyle (although
258 // this can be changed at build time), and on Windows it's the install
259 // directory (e.g. "C:\Program Files (x86)\Gargoyle").
260 static nonstd::optional<std::string> font_path_fallback_system(const std::string &fallback)
261 {
262 #ifdef _WIN32
263 char directory[256];
264 DWORD dsize = sizeof directory;
265 if (RegGetValueA(HKEY_LOCAL_MACHINE, "Software\\Tor Andersson\\Gargoyle", "Directory", RRF_RT_REG_SZ, nullptr, directory, &dsize) != ERROR_SUCCESS) {
266 return nonstd::nullopt;
267 }
268
269 return Format("{}\\{}", directory, fallback);
270 #else
271 return Format("{}/{}", garglk::windatadir(), fallback);
272 #endif
273 }
274
275 // Look in a platform-specific location for the fonts. This is typically
276 // the same directory that the executable is in, but can be anything the
277 // platform code deems appropriate.
278 static nonstd::optional<std::string> font_path_fallback_platform(const std::string &fallback)
279 {
280 return garglk::winfontpath(fallback);
281 }
282
283 // As a last-ditch effort, look in the current directory for the fonts.
284 static nonstd::optional<std::string> font_path_fallback_local(const std::string &fallback)
285 {
286 return fallback;
287 }
288
289 static std::string fontface_to_name(FontFace fontface)
290 {
291 std::string type = fontface.monospace ? "Mono" : "Proportional";
292 std::string style = (fontface.bold && fontface.italic) ? "Bold Italic" :
293 (fontface.bold ) ? "Bold" :
294 (fontface.italic ) ? "Italic" :
295 "Regular";
296
297 return Format("{} {}", type, style);
298 }
299
300 static Font make_font(FontFace fontface, const std::string &fallback, std::vector<std::string> &problem_fonts)
301 {
302 std::vector<std::function<nonstd::optional<std::string>(const std::string &fallback)>> font_paths = {
303 font_path_fallback_system,
304 font_path_fallback_platform,
305 font_path_fallback_local,
306 };
307
308 const auto &fontfiles =
309 fontface == FontFace::monor() ? gli_conf_mono.r :
310 fontface == FontFace::monob() ? gli_conf_mono.b :
311 fontface == FontFace::monoi() ? gli_conf_mono.i :
312 fontface == FontFace::monoz() ? gli_conf_mono.z :
313 fontface == FontFace::propr() ? gli_conf_prop.r :
314 fontface == FontFace::propb() ? gli_conf_prop.b :
315 fontface == FontFace::propi() ? gli_conf_prop.i :
316 fontface == FontFace::propz() ? gli_conf_prop.z :
317 gli_conf_mono.r;
318
319 const auto &path = fontfiles.fontpath();
320 const auto &override = fontfiles.override;
321
322 // First look for a user-specified font. This will be either based
323 // on a font family (propfont or monofont), or specific font files
324 // (e.g. propr, monor, etc).
325 nonstd::optional<Font::LoadError> error;
326 FT_Face face;
327 if (path.has_value() && FT_New_Face(ftlib, path->c_str(), 0, &face) == 0) {
328 try {
329 return {fontface, UniqueFace(face), *path};
330 } catch (const Font::LoadError &e) {
331 error = e;
332 }
333 }
334
335 // If no user font can be loaded, try to find a fallback.
336 for (const auto &get_font_path : font_paths) {
337 auto fontpath = get_font_path(fallback);
338 if (fontpath.has_value() && FT_New_Face(ftlib, fontpath->c_str(), 0, &face) == 0) {
339 if (error.has_value()) {
340 problem_fonts.push_back(Format("Unable to load font file \"{}\" ({}): using fallback {}.", error->filename(), error->what(), *fontpath));
341 }
342 return {fontface, UniqueFace(face), *fontpath};
343 }
344 }
345
346 garglk::winabort(Format("Unable to find font \"{}\" for {}, and fallback {} not found",
347 override.value_or(fontface.monospace ? gli_conf_monofont : gli_conf_propfont),
348 fontface_to_name(fontface),
349 fallback));
350 }
351
352 static std::vector<Font> make_substitution_fonts(FontFace fontface)
353 {
354 FT_Face face;
355 std::vector<Font> fonts;
356
357 auto files = gli_conf_glyph_substitution_files[fontface];
358
359
360 for (const auto &path : {garglk::windatadir(), "."s}) {
361 files.push_back(Format("{}/unifont.otf", path));
362 files.push_back(Format("{}/unifont_upper.otf", path));
363 }
364
365 for (const auto &file : files) {
366 if (FT_New_Face(ftlib, file.c_str(), 0, &face) == 0) {
367 try {
368 fonts.emplace_back(fontface, UniqueFace(face), file);
369 } catch (const Font::LoadError &) {
370 }
371 }
372 }
373
374 return fonts;
375 }
376
377 Font::Font(FontFace fontface, UniqueFace face, const std::string &fontpath) :
378 m_face(std::move(face))
379 {
380 int err = 0;
381 double aspect, size;
382
383 if (fontface.monospace) {
384 aspect = gli_conf_monoaspect;
385 size = gli_conf_monosize;
386 } else {
387 aspect = gli_conf_propaspect;
388 size = gli_conf_propsize;
389 }
390
391 auto dot = fontpath.rfind('.');
392 if (dot != std::string::npos) {
393 std::string afmbuf = fontpath;
394 auto ext = afmbuf.substr(dot);
395 if (ext == ".pfa" || ext == ".PFA" || ext == ".pfb" || ext == ".PFB") {
396 afmbuf.replace(dot, std::string::npos, ".afm");
397 FT_Attach_File(m_face.get(), afmbuf.c_str());
398 afmbuf.replace(dot, std::string::npos, ".AFM");
399 FT_Attach_File(m_face.get(), afmbuf.c_str());
400 }
401 }
402
403 err = FT_Set_Char_Size(m_face.get(), size * aspect * 64, size * 64, 72, 72);
404 if (err != 0) {
405 throw LoadError(err, fontpath, "FT_Set_Char_Size");
406 }
407
408 err = FT_Select_Charmap(m_face.get(), FT_ENCODING_UNICODE);
409 if (err != 0) {
410 throw LoadError(err, fontpath, "FT_Select_CharMap");
411 }
412
413 m_kerned = FT_HAS_KERNING(m_face);
414
415 m_make_bold = fontface.bold && ((m_face->style_flags & FT_STYLE_FLAG_BOLD) == 0);
416 m_make_oblique = fontface.italic && ((m_face->style_flags & FT_STYLE_FLAG_ITALIC) == 0);
417 }
418
419 void gli_initialize_fonts()
420 {
421 int err;
422
423 for (int i = 0; i < 256; i++) {
424 gammamap[i] = std::round(std::pow(i / 255.0, gli_conf_gamma) * GAMMA_MAX);
425 }
426
427 for (int i = 0; i <= GAMMA_MAX; i++) {
428 gammainv[i] = std::round(std::pow(i / static_cast<double>(GAMMA_MAX), 1.0 / gli_conf_gamma) * 255.0);
429 }
430
431 err = FT_Init_FreeType(&ftlib);
432 if (err != 0) {
433 garglk::winabort(convert_ft_error(err, "Unable to initialize FreeType"));
434 }
435
436 std::vector<std::string> problem_fonts;
437
438 // Gargoyle ships "Gargoyle Mono" and "Gargoyle Serif" fonts, which
439 // can be installed system-wide; it also sets the default mono and
440 // prop fonts to these values. However, it's certainly not required
441 // for these fonts to be installed system-wide, so it has a fallback
442 // mechanism, which, if Gargoyle is installed/configured properly,
443 // will fall back to "known-good" locations of these fonts.
444 //
445 // The problem is that Gargoyle has, in the past, shipped with a
446 // garglk.ini specifying these fonts. That's always been fine,
447 // because Gargoyle falls back silently if they're not installed,
448 // and nobody's the wiser. But Gargoyle always fell back silently if
449 // _any_ user-specified font couldn't be located, which meant that
450 // if a user mistyped a font, the fallback would be substituted
451 // without warning. Gargoyle now warns about missing fonts, but that
452 // leads to the problem of Gargoyle warning about its own specified
453 // fonts not being installed, if indeed they're not. This wouldn't
454 // be a problem if users didn't already have garglk.ini, but they
455 // do, so it is.
456 //
457 // At the moment the solution is to elide the warning when either
458 // of Gargoyle's own fonts is requested, i.e. the fonts listed in
459 // the default garglk.ini. This is a bit ugly since it means
460 // Gargoyle treats two specific font names as special. Ideally the
461 // default fonts would be empty and Gargoyle would use that to mean
462 // "built-in/fallback fonts", but with existing configs out there,
463 // it's not meant to be.
464 fontload();
465 if (!garglk::fontreplace(gli_conf_monofont, FontType::Monospace) && gli_conf_monofont != DEFAULT_MONO_FONT) {
466 problem_fonts.push_back(Format("Unable to find monospace font \"{}\", using fallback.", gli_conf_monofont));
467 }
468 if (!garglk::fontreplace(gli_conf_propfont, FontType::Proportional) && gli_conf_propfont != DEFAULT_PROP_FONT) {
469 problem_fonts.push_back(Format("Unable to find proportional font \"{}\", using fallback.", gli_conf_propfont));
470 }
471 fontunload();
472
473 // Set up the Unicode fallback font.
474 auto faces = {FontFace::propr(), FontFace::propi(), FontFace::propb(), FontFace::propz(),
475 FontFace::monor(), FontFace::monoi(), FontFace::monob(), FontFace::monoz()};
476 for (const auto &fontface : faces) {
477 glyph_substitution_fonts.insert({fontface, make_substitution_fonts(fontface)});
478 }
479
480 // create oblique transform matrix
481 ftmat.xx = 0x10000L;
482 ftmat.yx = 0x00000L;
483 ftmat.xy = 0x03000L;
484 ftmat.yy = 0x10000L;
485
486 auto make_entry = [&problem_fonts](FontFace face, const std::string &fallback) {
487 return std::make_pair(face, make_font(face, fallback, problem_fonts));
488 };
489
490 try {
491 gfont_table.insert(make_entry(FontFace::monor(), "Gargoyle-Mono.ttf"));
492 gfont_table.insert(make_entry(FontFace::monob(), "Gargoyle-Mono-Bold.ttf"));
493 gfont_table.insert(make_entry(FontFace::monoi(), "Gargoyle-Mono-Italic.ttf"));
494 gfont_table.insert(make_entry(FontFace::monoz(), "Gargoyle-Mono-Bold-Italic.ttf"));
495 gfont_table.insert(make_entry(FontFace::propr(), "Gargoyle-Serif.ttf"));
496 gfont_table.insert(make_entry(FontFace::propb(), "Gargoyle-Serif-Bold.ttf"));
497 gfont_table.insert(make_entry(FontFace::propi(), "Gargoyle-Serif-Italic.ttf"));
498 gfont_table.insert(make_entry(FontFace::propz(), "Gargoyle-Serif-Bold-Italic.ttf"));
499
500 const auto &entry = gfont_table.at(FontFace::monor()).getglyph('0');
501
502 gli_cellh = gli_leading;
503 gli_cellw = (entry.adv + GLI_SUBPIX - 1) / GLI_SUBPIX;
504 } catch (const Font::LoadError &e) {
505 garglk::winabort(Format("Unable to load font file \"{}\" ({}).", e.filename(), e.what()));
506 }
507
508 if (!problem_fonts.empty()) {
509 auto msg = garglk::join(problem_fonts, "\n\n");
510 garglk::winwarning("Font error", msg);
511 }
512 }
513
514 //
515 // Drawing
516 //
517
518 void gli_draw_pixel(int x, int y, const Color &rgb)
519 {
520 if (x < 0 || x >= gli_image_rgb.width()) {
521 return;
522 }
523 if (y < 0 || y >= gli_image_rgb.height()) {
524 return;
525 }
526 gli_image_rgb[y][x] = rgb;
527 }
528
529 static void draw_pixel_gamma(int x, int y, unsigned char alpha, const Color &rgb)
530 {
531 if (x < 0 || x >= gli_image_rgb.width()) {
532 return;
533 }
534 if (y < 0 || y >= gli_image_rgb.height()) {
535 return;
536 }
537
538 std::uint16_t invalf = GAMMA_MAX - (alpha * GAMMA_MAX / 255);
539 std::array<std::uint16_t, 3> bg = {
540 gammamap[gli_image_rgb[y][x][0]],
541 gammamap[gli_image_rgb[y][x][1]],
542 gammamap[gli_image_rgb[y][x][2]]
543 };
544 std::array<std::uint16_t, 3> fg = {
545 gammamap[rgb[0]],
546 gammamap[rgb[1]],
547 gammamap[rgb[2]]
548 };
549
550 gli_image_rgb[y][x] = Pixel<3>(gammainv[fg[0] + mulhigh(static_cast<int>(bg[0]) - fg[0], invalf)],
551 gammainv[fg[1] + mulhigh(static_cast<int>(bg[1]) - fg[1], invalf)],
552 gammainv[fg[2] + mulhigh(static_cast<int>(bg[2]) - fg[2], invalf)]);
553 }
554
555 static void draw_pixel_lcd_gamma(int x, int y, const unsigned char *alpha, const Color &rgb)
556 {
557 if (x < 0 || x >= gli_image_rgb.width()) {
558 return;
559 }
560 if (y < 0 || y >= gli_image_rgb.height()) {
561 return;
562 }
563
564 std::array<std::uint16_t, 3> invalf = {
565 static_cast<std::uint16_t>(GAMMA_MAX - (alpha[0] * GAMMA_MAX / 255)),
566 static_cast<std::uint16_t>(GAMMA_MAX - (alpha[1] * GAMMA_MAX / 255)),
567 static_cast<std::uint16_t>(GAMMA_MAX - (alpha[2] * GAMMA_MAX / 255)),
568 };
569 std::array<std::uint16_t, 3> bg = {
570 gammamap[gli_image_rgb[y][x][0]],
571 gammamap[gli_image_rgb[y][x][1]],
572 gammamap[gli_image_rgb[y][x][2]]
573 };
574 std::array<std::uint16_t, 3> fg = {
575 gammamap[rgb[0]],
576 gammamap[rgb[1]],
577 gammamap[rgb[2]]
578 };
579
580 gli_image_rgb[y][x] = Pixel<3>(gammainv[fg[0] + mulhigh(static_cast<int>(bg[0]) - fg[0], invalf[0])],
581 gammainv[fg[1] + mulhigh(static_cast<int>(bg[1]) - fg[1], invalf[1])],
582 gammainv[fg[2] + mulhigh(static_cast<int>(bg[2]) - fg[2], invalf[2])]);
583 }
584
585 static void draw_bitmap_gamma(const Bitmap &b, int x, int y, const Color &rgb)
586 {
587 for (int k = 0; k < b.h; k++) {
588 for (int i = 0; i < b.w; i++) {
589 auto c = b.data[k * b.pitch + i];
590 draw_pixel_gamma(x + b.lsb + i, y - b.top + k, c, rgb);
591 }
592 }
593 }
594
595 static void draw_bitmap_lcd_gamma(const Bitmap &b, int x, int y, const Color &rgb)
596 {
597 for (int k = 0; k < b.h; k++) {
598 for (int i = 0, j = 0; i < b.w; i += 3, j++) {
599 draw_pixel_lcd_gamma(x + b.lsb + j, y - b.top + k, b.data.data() + k * b.pitch + i, rgb);
600 }
601 }
602 }
603
604 void gli_draw_clear(const Color &rgb)
605 {
606 gli_image_rgb.fill(rgb);
607 }
608
609 void gli_draw_rect(int x0, int y0, int w, int h, const Color &rgb)
610 {
611 int x1 = x0 + w;
612 int y1 = y0 + h;
613 int y;
614
615 x0 = garglk::clamp(x0, 0, gli_image_rgb.width());
616 y0 = garglk::clamp(y0, 0, gli_image_rgb.height());
617 x1 = garglk::clamp(x1, 0, gli_image_rgb.width());
618 y1 = garglk::clamp(y1, 0, gli_image_rgb.height());
619
620 for (y = y0; y < y1; y++) {
621 gli_image_rgb[y].fill(rgb, x0, x1);
622 }
623 }
624
625 int Font::charkern(glui32 c0, glui32 c1)
626 {
627 FT_Vector v;
628 int err;
629 int g0, g1;
630
631 if (!m_kerned) {
632 return 0;
633 }
634
635 unsigned long long key = (static_cast<unsigned long long>(c0) << 32) | c1;
636 try {
637 return m_kerncache.at(key);
638 } catch (const std::out_of_range &) {
639 }
640
641 g0 = FT_Get_Char_Index(m_face.get(), c0);
642 g1 = FT_Get_Char_Index(m_face.get(), c1);
643
644 if (g0 == 0 || g1 == 0) {
645 return 0;
646 }
647
648 err = FT_Get_Kerning(m_face.get(), g0, g1, FT_KERNING_UNFITTED, &v);
649 if (err != 0) {
650 throw std::runtime_error(convert_ft_error(err, "FT_Get_Kerning"));
651 }
652
653 int value = (v.x * GLI_SUBPIX) / 64.0;
654 m_kerncache.emplace(key, value);
655
656 return value;
657 }
658
659 static const std::vector<std::pair<std::vector<glui32>, glui32>> ligatures = {
660 {{'f', 'f', 'i'}, UNI_LIG_FFI},
661 {{'f', 'f', 'l'}, UNI_LIG_FFL},
662 {{'f', 'f'}, UNI_LIG_FF},
663 {{'f', 'i'}, UNI_LIG_FI},
664 {{'f', 'l'}, UNI_LIG_FL},
665 };
666
667 static int gli_string_impl(int x, FontFace fontface, const glui32 *s, std::size_t n, int spw, const std::function<void(int, const std::array<Bitmap, GLI_SUBPIX> &)> &callback)
668 {
669 auto &f = gfont_table.at(fontface);
670 bool dolig = !FT_IS_FIXED_WIDTH(f.face());
671 int prev = -1;
672 glui32 c;
673
674 while (n > 0) {
675 auto it = ligatures.end();
676 if (dolig) {
677 it = std::find_if(ligatures.begin(), ligatures.end(), [s, n](const std::pair<std::vector<glui32>, glui32> &ligentry) {
678 const auto &ligature = ligentry.first;
679 if (ligature.size() > n) {
680 return false;
681 }
682
683 for (std::size_t i = 0; i < ligature.size(); i++) {
684 if (s[i] != ligature[i]) {
685 return false;
686 }
687 }
688
689 return true;
690 });
691 }
692
693 if (it != ligatures.end() && FT_Get_Char_Index(f.face().get(), it->second) != 0) {
694 c = it->second;
695 s += it->first.size();
696 n -= it->first.size();
697 } else {
698 c = *s++;
699 n--;
700 }
701
702 // Return a FontEntry corresponding to the specific glyph. If
703 // that glyph is unavailable, log a warning and select a
704 // question mark instead. If a question mark can't be loaded,
705 // abort with an error message. Lookups are cached.
706 auto glyph = [&f, &fontface](glui32 c) -> const FontEntry & {
707 static std::unordered_map<std::pair<FontFace, glui32>, FontEntry> fallback_cache;
708
709 auto key = std::make_pair(fontface, c);
710
711 auto it = fallback_cache.find(key);
712 if (it == fallback_cache.end()) {
713 try {
714 it = fallback_cache.emplace(key, f.getglyph(c)).first;
715 } catch (const std::out_of_range &) {
716 for (auto &font : glyph_substitution_fonts[fontface]) {
717 try {
718 it = fallback_cache.emplace(key, font.getglyph(c)).first;
719 break;
720 } catch (const std::out_of_range &) {
721 }
722 }
723 }
724
725 if (it == fallback_cache.end()) {
726 auto msg = Format("Unable to look up glyph {} for {}", c, fontface_to_name(fontface));
727 std::cerr << msg << std::endl;
728 try {
729 it = fallback_cache.emplace(key, f.getglyph(UNICODE_QUESTION_MARK)).first;
730 } catch (const std::out_of_range &) {
731 garglk::winabort(Format("{}, and substituting '?' failed", msg));
732 }
733 }
734 }
735
736 return it->second;
737 };
738
739 if (prev != -1) {
740 x += f.charkern(prev, c);
741 }
742
743 const auto &entry = glyph(c);
744
745 callback(x, entry.glyph);
746
747 if (spw >= 0 && c == ' ') {
748 x += spw;
749 } else {
750 x += entry.adv;
751 }
752
753 prev = c;
754 }
755
756 return x;
757 }
758
759 int gli_draw_string_uni(int x, int y, FontFace face, const Color &rgb,
760 const glui32 *text, int len, int spacewidth)
761 {
762 return gli_string_impl(x, face, text, len, spacewidth, [&y, &rgb](int x, const std::array<Bitmap, GLI_SUBPIX> &glyphs) {
763 int px = x / GLI_SUBPIX;
764 int sx = x % GLI_SUBPIX;
765
766 if (gli_conf_lcd) {
767 draw_bitmap_lcd_gamma(glyphs[sx], px, y, rgb);
768 } else {
769 draw_bitmap_gamma(glyphs[sx], px, y, rgb);
770 }
771 });
772 }
773
774 int gli_string_width_uni(FontFace face, const glui32 *text, int len, int spacewidth)
775 {
776 return gli_string_impl(0, face, text, len, spacewidth, [](int, const std::array<Bitmap, GLI_SUBPIX> &) {});
777 }
778
779 void gli_draw_caret(int x, int y)
780 {
781 x = x / GLI_SUBPIX;
782 if (gli_caret_shape == 0) {
783 gli_draw_rect(x + 0, y + 1, 1, 1, gli_caret_color);
784 gli_draw_rect(x - 1, y + 2, 3, 1, gli_caret_color);
785 gli_draw_rect(x - 2, y + 3, 5, 1, gli_caret_color);
786 } else if (gli_caret_shape == 1) {
787 gli_draw_rect(x + 0, y + 1, 1, 1, gli_caret_color);
788 gli_draw_rect(x - 1, y + 2, 3, 1, gli_caret_color);
789 gli_draw_rect(x - 2, y + 3, 5, 1, gli_caret_color);
790 gli_draw_rect(x - 3, y + 4, 7, 1, gli_caret_color);
791 } else if (gli_caret_shape == 2) {
792 gli_draw_rect(x + 0, y - gli_baseline + 1, 1, gli_leading - 2, gli_caret_color);
793 } else if (gli_caret_shape == 3) {
794 gli_draw_rect(x + 0, y - gli_baseline + 1, 2, gli_leading - 2, gli_caret_color);
795 } else {
796 gli_draw_rect(x + 0, y - gli_baseline + 1, gli_cellw, gli_leading - 2, gli_caret_color);
797 }
798 }
799
800 void gli_draw_picture(const picture_t *pic, int x0, int y0, int dx0, int dy0, int dx1, int dy1)
801 {
802 int x1, y1, sx0, sy0, sx1, sy1;
803 int w, h;
804
805 sx0 = 0;
806 sy0 = 0;
807 sx1 = pic->w;
808 sy1 = pic->h;
809
810 x1 = x0 + pic->w;
811 y1 = y0 + pic->h;
812
813 if (x1 <= dx0 || x0 >= dx1) {
814 return;
815 }
816 if (y1 <= dy0 || y0 >= dy1) {
817 return;
818 }
819 if (x0 < dx0) {
820 sx0 += dx0 - x0;
821 x0 = dx0;
822 }
823 if (y0 < dy0) {
824 sy0 += dy0 - y0;
825 y0 = dy0;
826 }
827 if (x1 > dx1) {
828 sx1 += dx1 - x1;
829 }
830 if (y1 > dy1) {
831 sy1 += dy1 - y1;
832 }
833
834 w = sx1 - sx0;
835 h = sy1 - sy0;
836
837 for (int y = 0; y < h; y++) {
838 for (int x = 0; x < w; x++) {
839 auto existing = gli_image_rgb[y + y0][x + x0];
840 unsigned char sa = pic->rgba[y + sy0][x + sx0][3];
841 unsigned char na = 255 - sa;
842 unsigned char sr = mul255(pic->rgba[y + sy0][x + sx0][0], sa);
843 unsigned char sg = mul255(pic->rgba[y + sy0][x + sx0][1], sa);
844 unsigned char sb = mul255(pic->rgba[y + sy0][x + sx0][2], sa);
845 gli_image_rgb[y + y0][x + x0] = Pixel<3>(sr + mul255(existing[0], na),
846 sg + mul255(existing[1], na),
847 sb + mul255(existing[2], na));
848 }
849 }
850 }