2 * Copyright © 2011 Google, Inc.
4 * This is part of HarfBuzz, a text shaping library.
6 * Permission is hereby granted, without written agreement and without
7 * license or royalty fees, to use, copy, modify, and distribute this
8 * software and its documentation for any purpose, provided that the
9 * above copyright notice and the following two paragraphs appear in
10 * all copies of this software.
12 * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13 * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14 * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15 * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
18 * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20 * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
21 * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22 * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
24 * Google Author(s): Behdad Esfahbod
27 #ifndef HELPER_CAIRO_HH
28 #define HELPER_CAIRO_HH
30 #include "view-options.hh"
31 #include "output-options.hh"
35 #include FT_MULTIPLE_MASTERS_H
37 #include "helper-cairo-ansi.hh"
38 #ifdef CAIRO_HAS_SVG_SURFACE
39 # include <cairo-svg.h>
41 #ifdef CAIRO_HAS_PDF_SURFACE
42 # include <cairo-pdf.h>
44 #ifdef CAIRO_HAS_PS_SURFACE
45 # include <cairo-ps.h>
46 # if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1,6,0)
49 static cairo_surface_t *
50 _cairo_eps_surface_create_for_stream (cairo_write_func_t write_func,
55 cairo_surface_t *surface;
57 surface = cairo_ps_surface_create_for_stream (write_func, closure, width, height);
58 cairo_ps_surface_set_eps (surface, true);
69 static FT_Library ft_library;
73 void free_ft_library ()
75 FT_Done_FreeType (ft_library);
79 static inline cairo_scaled_font_t *
80 helper_cairo_create_scaled_font (const font_options_t *font_opts)
82 hb_font_t *font = hb_font_reference (font_opts->font);
84 cairo_font_face_t *cairo_face;
85 /* We cannot use the FT_Face from hb_font_t, as doing so will confuse hb_font_t because
86 * cairo will reset the face size. As such, create new face...
87 * TODO Perhaps add API to hb-ft to encapsulate this code. */
88 FT_Face ft_face = nullptr;//hb_ft_font_get_face (font);
93 FT_Init_FreeType (&ft_library);
95 atexit (free_ft_library);
99 unsigned int blob_length;
100 const char *blob_data = hb_blob_get_data (font_opts->blob, &blob_length);
102 if (FT_New_Memory_Face (ft_library,
103 (const FT_Byte *) blob_data,
105 font_opts->face_index,
107 fail (false, "FT_New_Memory_Face fail");
111 /* This allows us to get some boxes at least... */
112 cairo_face = cairo_toy_font_face_create ("@cairo:sans",
113 CAIRO_FONT_SLANT_NORMAL,
114 CAIRO_FONT_WEIGHT_NORMAL);
118 #ifdef HAVE_FT_SET_VAR_BLEND_COORDINATES
119 unsigned int num_coords;
120 const int *coords = hb_font_get_var_coords_normalized (font, &num_coords);
123 FT_Fixed *ft_coords = (FT_Fixed *) calloc (num_coords, sizeof (FT_Fixed));
126 for (unsigned int i = 0; i < num_coords; i++)
127 ft_coords[i] = coords[i] << 2;
128 FT_Set_Var_Blend_Coordinates (ft_face, num_coords, ft_coords);
134 cairo_face = cairo_ft_font_face_create_for_ft_face (ft_face, font_opts->ft_load_flags);
136 cairo_matrix_t ctm, font_matrix;
137 cairo_font_options_t *font_options;
139 cairo_matrix_init_identity (&ctm);
140 cairo_matrix_init_scale (&font_matrix,
141 font_opts->font_size_x,
142 font_opts->font_size_y);
143 font_options = cairo_font_options_create ();
144 cairo_font_options_set_hint_style (font_options, CAIRO_HINT_STYLE_NONE);
145 cairo_font_options_set_hint_metrics (font_options, CAIRO_HINT_METRICS_OFF);
147 cairo_scaled_font_t *scaled_font = cairo_scaled_font_create (cairo_face,
152 cairo_font_options_destroy (font_options);
153 cairo_font_face_destroy (cairo_face);
155 static cairo_user_data_key_t key;
156 if (cairo_scaled_font_set_user_data (scaled_font,
159 (cairo_destroy_func_t) hb_font_destroy))
160 hb_font_destroy (font);
166 helper_cairo_scaled_font_has_color (cairo_scaled_font_t *scaled_font)
170 FT_Face ft_face = cairo_ft_scaled_font_lock_face (scaled_font);
173 if (FT_HAS_COLOR (ft_face))
175 cairo_ft_scaled_font_unlock_face (scaled_font);
182 enum class image_protocol_t {
188 struct finalize_closure_t {
189 void (*callback)(finalize_closure_t *);
190 cairo_surface_t *surface;
191 cairo_write_func_t write_func;
193 image_protocol_t protocol;
195 static cairo_user_data_key_t finalize_closure_key;
199 finalize_ansi (finalize_closure_t *closure)
201 cairo_status_t status;
202 status = helper_cairo_surface_write_to_ansi_stream (closure->surface,
205 if (status != CAIRO_STATUS_SUCCESS)
206 fail (false, "Failed to write output: %s",
207 cairo_status_to_string (status));
210 static cairo_surface_t *
211 _cairo_ansi_surface_create_for_stream (cairo_write_func_t write_func,
215 cairo_content_t content,
216 image_protocol_t protocol HB_UNUSED)
218 cairo_surface_t *surface;
219 int w = ceil (width);
220 int h = ceil (height);
223 case CAIRO_CONTENT_ALPHA:
224 surface = cairo_image_surface_create (CAIRO_FORMAT_A8, w, h);
227 case CAIRO_CONTENT_COLOR:
228 surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, w, h);
230 case CAIRO_CONTENT_COLOR_ALPHA:
231 surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
234 cairo_status_t status = cairo_surface_status (surface);
235 if (status != CAIRO_STATUS_SUCCESS)
236 fail (false, "Failed to create cairo surface: %s",
237 cairo_status_to_string (status));
239 finalize_closure_t *ansi_closure = g_new0 (finalize_closure_t, 1);
240 ansi_closure->callback = finalize_ansi;
241 ansi_closure->surface = surface;
242 ansi_closure->write_func = write_func;
243 ansi_closure->closure = closure;
245 if (cairo_surface_set_user_data (surface,
246 &finalize_closure_key,
247 (void *) ansi_closure,
248 (cairo_destroy_func_t) g_free))
249 g_free ((void *) closure);
255 #ifdef CAIRO_HAS_PNG_FUNCTIONS
257 static cairo_status_t
258 byte_array_write_func (void *closure,
259 const unsigned char *data,
262 g_byte_array_append ((GByteArray *) closure, data, size);
263 return CAIRO_STATUS_SUCCESS;
267 finalize_png (finalize_closure_t *closure)
269 cairo_status_t status;
270 GByteArray *bytes = nullptr;
275 if (closure->protocol == image_protocol_t::NONE)
277 status = cairo_surface_write_to_png_stream (closure->surface,
283 bytes = g_byte_array_new ();
284 status = cairo_surface_write_to_png_stream (closure->surface,
285 byte_array_write_func,
289 if (status != CAIRO_STATUS_SUCCESS)
290 fail (false, "Failed to write output: %s",
291 cairo_status_to_string (status));
293 if (closure->protocol == image_protocol_t::NONE)
296 base64 = g_base64_encode (bytes->data, bytes->len);
297 base64_len = strlen (base64);
299 string = g_string_new (NULL);
300 if (closure->protocol == image_protocol_t::ITERM2)
302 /* https://iterm2.com/documentation-images.html */
303 g_string_printf (string, "\033]1337;File=inline=1;size=%zu:%s\a\n",
306 else if (closure->protocol == image_protocol_t::KITTY)
308 #define CHUNK_SIZE 4096
309 /* https://sw.kovidgoyal.net/kitty/graphics-protocol.html */
310 for (size_t pos = 0; pos < base64_len; pos += CHUNK_SIZE)
312 size_t len = base64_len - pos;
315 g_string_append (string, "\033_Ga=T,f=100,m=");
317 g_string_append (string, "\033_Gm=");
319 if (len > CHUNK_SIZE)
321 g_string_append (string, "1;");
322 g_string_append_len (string, base64 + pos, CHUNK_SIZE);
326 g_string_append (string, "0;");
327 g_string_append_len (string, base64 + pos, len);
330 g_string_append (string, "\033\\");
332 g_string_append (string, "\n");
336 closure->write_func (closure->closure, (unsigned char *) string->str, string->len);
338 g_byte_array_unref (bytes);
340 g_string_free (string, TRUE);
343 static cairo_surface_t *
344 _cairo_png_surface_create_for_stream (cairo_write_func_t write_func,
348 cairo_content_t content,
349 image_protocol_t protocol)
351 cairo_surface_t *surface;
352 int w = ceil (width);
353 int h = ceil (height);
356 case CAIRO_CONTENT_ALPHA:
357 surface = cairo_image_surface_create (CAIRO_FORMAT_A8, w, h);
360 case CAIRO_CONTENT_COLOR:
361 surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, w, h);
363 case CAIRO_CONTENT_COLOR_ALPHA:
364 surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
367 cairo_status_t status = cairo_surface_status (surface);
368 if (status != CAIRO_STATUS_SUCCESS)
369 fail (false, "Failed to create cairo surface: %s",
370 cairo_status_to_string (status));
372 finalize_closure_t *png_closure = g_new0 (finalize_closure_t, 1);
373 png_closure->callback = finalize_png;
374 png_closure->surface = surface;
375 png_closure->write_func = write_func;
376 png_closure->closure = closure;
377 png_closure->protocol = protocol;
379 if (cairo_surface_set_user_data (surface,
380 &finalize_closure_key,
381 (void *) png_closure,
382 (cairo_destroy_func_t) g_free))
383 g_free ((void *) closure);
390 static cairo_status_t
391 stdio_write_func (void *closure,
392 const unsigned char *data,
395 FILE *fp = (FILE *) closure;
398 size_t ret = fwrite (data, 1, size, fp);
401 if (size && ferror (fp))
402 fail (false, "Failed to write output: %s", strerror (errno));
405 return CAIRO_STATUS_SUCCESS;
408 static const char *helper_cairo_supported_formats[] =
411 #ifdef CAIRO_HAS_PNG_FUNCTIONS
414 #ifdef CAIRO_HAS_SVG_SURFACE
417 #ifdef CAIRO_HAS_PDF_SURFACE
420 #ifdef CAIRO_HAS_PS_SURFACE
429 template <typename view_options_t,
430 typename output_options_t>
431 static inline cairo_t *
432 helper_cairo_create_context (double w, double h,
433 view_options_t *view_opts,
434 output_options_t *out_opts,
435 cairo_content_t content)
437 cairo_surface_t *(*constructor) (cairo_write_func_t write_func,
440 double height) = nullptr;
441 cairo_surface_t *(*constructor2) (cairo_write_func_t write_func,
445 cairo_content_t content,
446 image_protocol_t protocol) = nullptr;
448 image_protocol_t protocol = image_protocol_t::NONE;
449 const char *extension = out_opts->output_format;
452 if (isatty (fileno (out_opts->out_fp)))
454 #ifdef CAIRO_HAS_PNG_FUNCTIONS
456 /* https://gitlab.com/gnachman/iterm2/-/issues/7154 */
457 if ((name = getenv ("LC_TERMINAL")) != nullptr &&
458 0 == g_ascii_strcasecmp (name, "iTerm2"))
461 protocol = image_protocol_t::ITERM2;
463 else if ((name = getenv ("TERM")) != nullptr &&
464 0 == g_ascii_strcasecmp (name, "xterm-kitty"))
467 protocol = image_protocol_t::KITTY;
478 #ifdef CAIRO_HAS_PNG_FUNCTIONS
487 else if (0 == g_ascii_strcasecmp (extension, "ansi"))
488 constructor2 = _cairo_ansi_surface_create_for_stream;
489 #ifdef CAIRO_HAS_PNG_FUNCTIONS
490 else if (0 == g_ascii_strcasecmp (extension, "png"))
491 constructor2 = _cairo_png_surface_create_for_stream;
493 #ifdef CAIRO_HAS_SVG_SURFACE
494 else if (0 == g_ascii_strcasecmp (extension, "svg"))
495 constructor = cairo_svg_surface_create_for_stream;
497 #ifdef CAIRO_HAS_PDF_SURFACE
498 else if (0 == g_ascii_strcasecmp (extension, "pdf"))
499 constructor = cairo_pdf_surface_create_for_stream;
501 #ifdef CAIRO_HAS_PS_SURFACE
502 else if (0 == g_ascii_strcasecmp (extension, "ps"))
503 constructor = cairo_ps_surface_create_for_stream;
505 else if (0 == g_ascii_strcasecmp (extension, "eps"))
506 constructor = _cairo_eps_surface_create_for_stream;
511 unsigned int fr, fg, fb, fa, br, bg, bb, ba;
513 br = bg = bb = 0; ba = 255;
514 color = view_opts->back ? view_opts->back : DEFAULT_BACK;
515 sscanf (color + (*color=='#'), "%2x%2x%2x%2x", &br, &bg, &bb, &ba);
516 fr = fg = fb = 0; fa = 255;
517 color = view_opts->fore ? view_opts->fore : DEFAULT_FORE;
518 sscanf (color + (*color=='#'), "%2x%2x%2x%2x", &fr, &fg, &fb, &fa);
520 if (content == CAIRO_CONTENT_ALPHA)
522 if (view_opts->annotate ||
523 br != bg || bg != bb ||
524 fr != fg || fg != fb)
525 content = CAIRO_CONTENT_COLOR;
528 content = CAIRO_CONTENT_COLOR_ALPHA;
530 cairo_surface_t *surface;
531 FILE *f = out_opts->out_fp;
533 surface = constructor (stdio_write_func, f, w, h);
534 else if (constructor2)
535 surface = constructor2 (stdio_write_func, f, w, h, content, protocol);
537 fail (false, "Unknown output format `%s'; supported formats are: %s%s",
539 g_strjoinv ("/", const_cast<char**> (helper_cairo_supported_formats)),
540 out_opts->explicit_output_format ? "" :
541 "\nTry setting format using --output-format");
543 cairo_t *cr = cairo_create (surface);
544 content = cairo_surface_get_content (surface);
547 case CAIRO_CONTENT_ALPHA:
548 cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
549 cairo_set_source_rgba (cr, 1., 1., 1., br / 255.);
551 cairo_set_source_rgba (cr, 1., 1., 1.,
552 (fr / 255.) * (fa / 255.) + (br / 255) * (1 - (fa / 255.)));
555 case CAIRO_CONTENT_COLOR:
556 case CAIRO_CONTENT_COLOR_ALPHA:
557 cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
558 cairo_set_source_rgba (cr, br / 255., bg / 255., bb / 255., ba / 255.);
560 cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
561 cairo_set_source_rgba (cr, fr / 255., fg / 255., fb / 255., fa / 255.);
565 cairo_surface_destroy (surface);
570 helper_cairo_destroy_context (cairo_t *cr)
572 finalize_closure_t *closure = (finalize_closure_t *)
573 cairo_surface_get_user_data (cairo_get_target (cr),
574 &finalize_closure_key);
576 closure->callback (closure);
578 cairo_status_t status = cairo_status (cr);
579 if (status != CAIRO_STATUS_SUCCESS)
580 fail (false, "Failed: %s",
581 cairo_status_to_string (status));
586 struct helper_cairo_line_t {
587 cairo_glyph_t *glyphs;
588 unsigned int num_glyphs;
590 unsigned int utf8_len;
591 cairo_text_cluster_t *clusters;
592 unsigned int num_clusters;
593 cairo_text_cluster_flags_t cluster_flags;
597 cairo_glyph_free (glyphs);
599 cairo_text_cluster_free (clusters);
604 void get_advance (double *x_advance, double *y_advance) {
605 *x_advance = glyphs[num_glyphs].x;
606 *y_advance = glyphs[num_glyphs].y;
611 helper_cairo_line_from_buffer (helper_cairo_line_t *l,
614 unsigned int text_len,
616 hb_bool_t utf8_clusters)
618 memset (l, 0, sizeof (*l));
620 l->num_glyphs = hb_buffer_get_length (buffer);
621 hb_glyph_info_t *hb_glyph = hb_buffer_get_glyph_infos (buffer, nullptr);
622 hb_glyph_position_t *hb_position = hb_buffer_get_glyph_positions (buffer, nullptr);
623 l->glyphs = cairo_glyph_allocate (l->num_glyphs + 1);
626 l->utf8 = g_strndup (text, text_len);
627 l->utf8_len = text_len;
628 l->num_clusters = l->num_glyphs ? 1 : 0;
629 for (unsigned int i = 1; i < l->num_glyphs; i++)
630 if (hb_glyph[i].cluster != hb_glyph[i-1].cluster)
632 l->clusters = cairo_text_cluster_allocate (l->num_clusters);
635 if ((l->num_glyphs && !l->glyphs) ||
636 (l->utf8_len && !l->utf8) ||
637 (l->num_clusters && !l->clusters))
643 hb_position_t x = 0, y = 0;
645 for (i = 0; i < (int) l->num_glyphs; i++)
647 l->glyphs[i].index = hb_glyph[i].codepoint;
648 l->glyphs[i].x = scalbn ((double) hb_position->x_offset + x, scale_bits);
649 l->glyphs[i].y = scalbn ((double) -hb_position->y_offset + y, scale_bits);
650 x += hb_position->x_advance;
651 y += -hb_position->y_advance;
655 l->glyphs[i].index = -1;
656 l->glyphs[i].x = scalbn ((double) x, scale_bits);
657 l->glyphs[i].y = scalbn ((double) y, scale_bits);
659 if (l->num_clusters) {
660 memset ((void *) l->clusters, 0, l->num_clusters * sizeof (l->clusters[0]));
661 hb_bool_t backward = HB_DIRECTION_IS_BACKWARD (hb_buffer_get_direction (buffer));
662 l->cluster_flags = backward ? CAIRO_TEXT_CLUSTER_FLAG_BACKWARD : (cairo_text_cluster_flags_t) 0;
663 unsigned int cluster = 0;
664 const char *start = l->utf8, *end;
665 l->clusters[cluster].num_glyphs++;
667 for (i = l->num_glyphs - 2; i >= 0; i--) {
668 if (hb_glyph[i].cluster != hb_glyph[i+1].cluster) {
669 g_assert (hb_glyph[i].cluster > hb_glyph[i+1].cluster);
671 end = start + hb_glyph[i].cluster - hb_glyph[i+1].cluster;
673 end = g_utf8_offset_to_pointer (start, hb_glyph[i].cluster - hb_glyph[i+1].cluster);
674 l->clusters[cluster].num_bytes = end - start;
678 l->clusters[cluster].num_glyphs++;
680 l->clusters[cluster].num_bytes = l->utf8 + text_len - start;
682 for (i = 1; i < (int) l->num_glyphs; i++) {
683 if (hb_glyph[i].cluster != hb_glyph[i-1].cluster) {
684 g_assert (hb_glyph[i].cluster > hb_glyph[i-1].cluster);
686 end = start + hb_glyph[i].cluster - hb_glyph[i-1].cluster;
688 end = g_utf8_offset_to_pointer (start, hb_glyph[i].cluster - hb_glyph[i-1].cluster);
689 l->clusters[cluster].num_bytes = end - start;
693 l->clusters[cluster].num_glyphs++;
695 l->clusters[cluster].num_bytes = l->utf8 + text_len - start;