helper-cairo.cc revision 998e8dda938cfef0146f1bfc4e8973a0e12d7d35
1/*
2 * Copyright © 2011  Google, Inc.
3 *
4 *  This is part of HarfBuzz, a text shaping library.
5 *
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.
11 *
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
16 * DAMAGE.
17 *
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.
23 *
24 * Google Author(s): Behdad Esfahbod
25 */
26
27#include "helper-cairo.hh"
28
29#include <cairo-ft.h>
30#include <hb-ft.h>
31
32#include "helper-cairo-ansi.hh"
33#ifdef CAIRO_HAS_SVG_SURFACE
34#  include <cairo-svg.h>
35#endif
36#ifdef CAIRO_HAS_PDF_SURFACE
37#  include <cairo-pdf.h>
38#endif
39#ifdef CAIRO_HAS_PS_SURFACE
40#  include <cairo-ps.h>
41#  if CAIRO_VERSION >= CAIRO_VERSION_ENCODE(1,6,0)
42#    define HAS_EPS 1
43
44static cairo_surface_t *
45_cairo_eps_surface_create_for_stream (cairo_write_func_t  write_func,
46				      void               *closure,
47				      double              width,
48				      double              height)
49{
50  cairo_surface_t *surface;
51
52  surface = cairo_ps_surface_create_for_stream (write_func, closure, width, height);
53  cairo_ps_surface_set_eps (surface, true);
54
55  return surface;
56}
57
58#  else
59#    undef HAS_EPS
60#  endif
61#endif
62
63
64static FT_Library ft_library;
65
66static inline
67void free_ft_library (void)
68{
69  FT_Done_FreeType (ft_library);
70}
71
72cairo_scaled_font_t *
73helper_cairo_create_scaled_font (const font_options_t *font_opts)
74{
75  hb_font_t *font = hb_font_reference (font_opts->get_font ());
76
77  cairo_font_face_t *cairo_face;
78  FT_Face ft_face = hb_ft_font_get_face (font);
79  if (!ft_face)
80  {
81    if (!ft_library)
82    {
83      FT_Init_FreeType (&ft_library);
84#ifdef HAVE_ATEXIT
85      atexit (free_ft_library);
86#endif
87    }
88    FT_New_Face (ft_library,
89		 font_opts->font_file,
90		 font_opts->face_index,
91		 &ft_face);
92  }
93  if (!ft_face)
94  {
95    /* This allows us to get some boxes at least... */
96    cairo_face = cairo_toy_font_face_create ("@cairo:sans",
97					     CAIRO_FONT_SLANT_NORMAL,
98					     CAIRO_FONT_WEIGHT_NORMAL);
99  }
100  else
101    cairo_face = cairo_ft_font_face_create_for_ft_face (ft_face, 0);
102  cairo_matrix_t ctm, font_matrix;
103  cairo_font_options_t *font_options;
104
105  cairo_matrix_init_identity (&ctm);
106  cairo_matrix_init_scale (&font_matrix,
107			   font_opts->font_size_x,
108			   font_opts->font_size_y);
109  font_options = cairo_font_options_create ();
110  cairo_font_options_set_hint_style (font_options, CAIRO_HINT_STYLE_NONE);
111  cairo_font_options_set_hint_metrics (font_options, CAIRO_HINT_METRICS_OFF);
112
113  cairo_scaled_font_t *scaled_font = cairo_scaled_font_create (cairo_face,
114							       &font_matrix,
115							       &ctm,
116							       font_options);
117
118  cairo_font_options_destroy (font_options);
119  cairo_font_face_destroy (cairo_face);
120
121  static cairo_user_data_key_t key;
122  if (cairo_scaled_font_set_user_data (scaled_font,
123				       &key,
124				       (void *) font,
125				       (cairo_destroy_func_t) hb_font_destroy))
126    hb_font_destroy (font);
127
128  return scaled_font;
129}
130
131bool
132helper_cairo_scaled_font_has_color (cairo_scaled_font_t *scaled_font)
133{
134  bool ret = false;
135#ifdef FT_HAS_COLOR
136  FT_Face ft_face = cairo_ft_scaled_font_lock_face (scaled_font);
137  if (ft_face)
138  {
139    if (FT_HAS_COLOR (ft_face))
140      ret = true;
141    cairo_ft_scaled_font_unlock_face (scaled_font);
142  }
143#endif
144  return ret;
145}
146
147
148struct finalize_closure_t {
149  void (*callback)(finalize_closure_t *);
150  cairo_surface_t *surface;
151  cairo_write_func_t write_func;
152  void *closure;
153};
154static cairo_user_data_key_t finalize_closure_key;
155
156
157static void
158finalize_ansi (finalize_closure_t *closure)
159{
160  cairo_status_t status;
161  status = helper_cairo_surface_write_to_ansi_stream (closure->surface,
162						      closure->write_func,
163						      closure->closure);
164  if (status != CAIRO_STATUS_SUCCESS)
165    fail (false, "Failed to write output: %s",
166	  cairo_status_to_string (status));
167}
168
169static cairo_surface_t *
170_cairo_ansi_surface_create_for_stream (cairo_write_func_t write_func,
171				       void *closure,
172				       double width,
173				       double height,
174				       cairo_content_t content)
175{
176  cairo_surface_t *surface;
177  int w = ceil (width);
178  int h = ceil (height);
179
180  switch (content) {
181    case CAIRO_CONTENT_ALPHA:
182      surface = cairo_image_surface_create (CAIRO_FORMAT_A8, w, h);
183      break;
184    default:
185    case CAIRO_CONTENT_COLOR:
186      surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, w, h);
187      break;
188    case CAIRO_CONTENT_COLOR_ALPHA:
189      surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
190      break;
191  }
192  cairo_status_t status = cairo_surface_status (surface);
193  if (status != CAIRO_STATUS_SUCCESS)
194    fail (false, "Failed to create cairo surface: %s",
195	  cairo_status_to_string (status));
196
197  finalize_closure_t *ansi_closure = g_new0 (finalize_closure_t, 1);
198  ansi_closure->callback = finalize_ansi;
199  ansi_closure->surface = surface;
200  ansi_closure->write_func = write_func;
201  ansi_closure->closure = closure;
202
203  if (cairo_surface_set_user_data (surface,
204				   &finalize_closure_key,
205				   (void *) ansi_closure,
206				   (cairo_destroy_func_t) g_free))
207    g_free ((void *) closure);
208
209  return surface;
210}
211
212
213#ifdef CAIRO_HAS_PNG_FUNCTIONS
214
215static void
216finalize_png (finalize_closure_t *closure)
217{
218  cairo_status_t status;
219  status = cairo_surface_write_to_png_stream (closure->surface,
220					      closure->write_func,
221					      closure->closure);
222  if (status != CAIRO_STATUS_SUCCESS)
223    fail (false, "Failed to write output: %s",
224	  cairo_status_to_string (status));
225}
226
227static cairo_surface_t *
228_cairo_png_surface_create_for_stream (cairo_write_func_t write_func,
229				      void *closure,
230				      double width,
231				      double height,
232				      cairo_content_t content)
233{
234  cairo_surface_t *surface;
235  int w = ceil (width);
236  int h = ceil (height);
237
238  switch (content) {
239    case CAIRO_CONTENT_ALPHA:
240      surface = cairo_image_surface_create (CAIRO_FORMAT_A8, w, h);
241      break;
242    default:
243    case CAIRO_CONTENT_COLOR:
244      surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, w, h);
245      break;
246    case CAIRO_CONTENT_COLOR_ALPHA:
247      surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
248      break;
249  }
250  cairo_status_t status = cairo_surface_status (surface);
251  if (status != CAIRO_STATUS_SUCCESS)
252    fail (false, "Failed to create cairo surface: %s",
253	  cairo_status_to_string (status));
254
255  finalize_closure_t *png_closure = g_new0 (finalize_closure_t, 1);
256  png_closure->callback = finalize_png;
257  png_closure->surface = surface;
258  png_closure->write_func = write_func;
259  png_closure->closure = closure;
260
261  if (cairo_surface_set_user_data (surface,
262				   &finalize_closure_key,
263				   (void *) png_closure,
264				   (cairo_destroy_func_t) g_free))
265    g_free ((void *) closure);
266
267  return surface;
268}
269
270#endif
271
272static cairo_status_t
273stdio_write_func (void                *closure,
274		  const unsigned char *data,
275		  unsigned int         size)
276{
277  FILE *fp = (FILE *) closure;
278
279  while (size) {
280    size_t ret = fwrite (data, 1, size, fp);
281    size -= ret;
282    data += ret;
283    if (size && ferror (fp))
284      fail (false, "Failed to write output: %s", strerror (errno));
285  }
286
287  return CAIRO_STATUS_SUCCESS;
288}
289
290const char *helper_cairo_supported_formats[] =
291{
292  "ansi",
293  #ifdef CAIRO_HAS_PNG_FUNCTIONS
294  "png",
295  #endif
296  #ifdef CAIRO_HAS_SVG_SURFACE
297  "svg",
298  #endif
299  #ifdef CAIRO_HAS_PDF_SURFACE
300  "pdf",
301  #endif
302  #ifdef CAIRO_HAS_PS_SURFACE
303  "ps",
304   #ifdef HAS_EPS
305    "eps",
306   #endif
307  #endif
308  NULL
309};
310
311cairo_t *
312helper_cairo_create_context (double w, double h,
313			     view_options_t *view_opts,
314			     output_options_t *out_opts,
315			     cairo_content_t content)
316{
317  cairo_surface_t *(*constructor) (cairo_write_func_t write_func,
318				   void *closure,
319				   double width,
320				   double height) = NULL;
321  cairo_surface_t *(*constructor2) (cairo_write_func_t write_func,
322				    void *closure,
323				    double width,
324				    double height,
325				    cairo_content_t content) = NULL;
326
327  const char *extension = out_opts->output_format;
328  if (!extension) {
329#if HAVE_ISATTY
330    if (isatty (fileno (out_opts->get_file_handle ())))
331      extension = "ansi";
332    else
333#endif
334    {
335#ifdef CAIRO_HAS_PNG_FUNCTIONS
336      extension = "png";
337#else
338      extension = "ansi";
339#endif
340    }
341  }
342  if (0)
343    ;
344    else if (0 == g_ascii_strcasecmp (extension, "ansi"))
345      constructor2 = _cairo_ansi_surface_create_for_stream;
346  #ifdef CAIRO_HAS_PNG_FUNCTIONS
347    else if (0 == g_ascii_strcasecmp (extension, "png"))
348      constructor2 = _cairo_png_surface_create_for_stream;
349  #endif
350  #ifdef CAIRO_HAS_SVG_SURFACE
351    else if (0 == g_ascii_strcasecmp (extension, "svg"))
352      constructor = cairo_svg_surface_create_for_stream;
353  #endif
354  #ifdef CAIRO_HAS_PDF_SURFACE
355    else if (0 == g_ascii_strcasecmp (extension, "pdf"))
356      constructor = cairo_pdf_surface_create_for_stream;
357  #endif
358  #ifdef CAIRO_HAS_PS_SURFACE
359    else if (0 == g_ascii_strcasecmp (extension, "ps"))
360      constructor = cairo_ps_surface_create_for_stream;
361   #ifdef HAS_EPS
362    else if (0 == g_ascii_strcasecmp (extension, "eps"))
363      constructor = _cairo_eps_surface_create_for_stream;
364   #endif
365  #endif
366
367
368  unsigned int fr, fg, fb, fa, br, bg, bb, ba;
369  const char *color;
370  br = bg = bb = 0; ba = 255;
371  color = view_opts->back ? view_opts->back : DEFAULT_BACK;
372  sscanf (color + (*color=='#'), "%2x%2x%2x%2x", &br, &bg, &bb, &ba);
373  fr = fg = fb = 0; fa = 255;
374  color = view_opts->fore ? view_opts->fore : DEFAULT_FORE;
375  sscanf (color + (*color=='#'), "%2x%2x%2x%2x", &fr, &fg, &fb, &fa);
376
377  if (content == CAIRO_CONTENT_ALPHA)
378  {
379    if (view_opts->annotate ||
380	br != bg || bg != bb ||
381	fr != fg || fg != fb)
382      content = CAIRO_CONTENT_COLOR;
383  }
384  if (ba != 255)
385    content = CAIRO_CONTENT_COLOR_ALPHA;
386
387  cairo_surface_t *surface;
388  FILE *f = out_opts->get_file_handle ();
389  if (constructor)
390    surface = constructor (stdio_write_func, f, w, h);
391  else if (constructor2)
392    surface = constructor2 (stdio_write_func, f, w, h, content);
393  else
394    fail (false, "Unknown output format `%s'; supported formats are: %s%s",
395	  extension,
396	  g_strjoinv ("/", const_cast<char**> (helper_cairo_supported_formats)),
397	  out_opts->explicit_output_format ? "" :
398	  "\nTry setting format using --output-format");
399
400  cairo_t *cr = cairo_create (surface);
401  content = cairo_surface_get_content (surface);
402
403  switch (content) {
404    case CAIRO_CONTENT_ALPHA:
405      cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
406      cairo_set_source_rgba (cr, 1., 1., 1., br / 255.);
407      cairo_paint (cr);
408      cairo_set_source_rgba (cr, 1., 1., 1.,
409			     (fr / 255.) * (fa / 255.) + (br / 255) * (1 - (fa / 255.)));
410      break;
411    default:
412    case CAIRO_CONTENT_COLOR:
413    case CAIRO_CONTENT_COLOR_ALPHA:
414      cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
415      cairo_set_source_rgba (cr, br / 255., bg / 255., bb / 255., ba / 255.);
416      cairo_paint (cr);
417      cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
418      cairo_set_source_rgba (cr, fr / 255., fg / 255., fb / 255., fa / 255.);
419      break;
420  }
421
422  cairo_surface_destroy (surface);
423  return cr;
424}
425
426void
427helper_cairo_destroy_context (cairo_t *cr)
428{
429  finalize_closure_t *closure = (finalize_closure_t *)
430				cairo_surface_get_user_data (cairo_get_target (cr),
431							     &finalize_closure_key);
432  if (closure)
433    closure->callback (closure);
434
435  cairo_status_t status = cairo_status (cr);
436  if (status != CAIRO_STATUS_SUCCESS)
437    fail (false, "Failed: %s",
438	  cairo_status_to_string (status));
439  cairo_destroy (cr);
440}
441
442
443void
444helper_cairo_line_from_buffer (helper_cairo_line_t *l,
445			       hb_buffer_t         *buffer,
446			       const char          *text,
447			       unsigned int         text_len,
448			       int                  scale_bits,
449			       hb_bool_t            utf8_clusters)
450{
451  memset (l, 0, sizeof (*l));
452
453  l->num_glyphs = hb_buffer_get_length (buffer);
454  hb_glyph_info_t *hb_glyph = hb_buffer_get_glyph_infos (buffer, NULL);
455  hb_glyph_position_t *hb_position = hb_buffer_get_glyph_positions (buffer, NULL);
456  l->glyphs = cairo_glyph_allocate (l->num_glyphs + 1);
457
458  if (text) {
459    l->utf8 = g_strndup (text, text_len);
460    l->utf8_len = text_len;
461    l->num_clusters = l->num_glyphs ? 1 : 0;
462    for (unsigned int i = 1; i < l->num_glyphs; i++)
463      if (hb_glyph[i].cluster != hb_glyph[i-1].cluster)
464	l->num_clusters++;
465    l->clusters = cairo_text_cluster_allocate (l->num_clusters);
466  }
467
468  if ((l->num_glyphs && !l->glyphs) ||
469      (l->utf8_len && !l->utf8) ||
470      (l->num_clusters && !l->clusters))
471  {
472    l->finish ();
473    return;
474  }
475
476  hb_position_t x = 0, y = 0;
477  int i;
478  for (i = 0; i < (int) l->num_glyphs; i++)
479  {
480    l->glyphs[i].index = hb_glyph[i].codepoint;
481    l->glyphs[i].x = scalbn ((double)  hb_position->x_offset + x, scale_bits);
482    l->glyphs[i].y = scalbn ((double) -hb_position->y_offset + y, scale_bits);
483    x +=  hb_position->x_advance;
484    y += -hb_position->y_advance;
485
486    hb_position++;
487  }
488  l->glyphs[i].index = -1;
489  l->glyphs[i].x = scalbn ((double) x, scale_bits);
490  l->glyphs[i].y = scalbn ((double) y, scale_bits);
491
492  if (l->num_clusters) {
493    memset ((void *) l->clusters, 0, l->num_clusters * sizeof (l->clusters[0]));
494    hb_bool_t backward = HB_DIRECTION_IS_BACKWARD (hb_buffer_get_direction (buffer));
495    l->cluster_flags = backward ? CAIRO_TEXT_CLUSTER_FLAG_BACKWARD : (cairo_text_cluster_flags_t) 0;
496    unsigned int cluster = 0;
497    const char *start = l->utf8, *end;
498    l->clusters[cluster].num_glyphs++;
499    if (backward) {
500      for (i = l->num_glyphs - 2; i >= 0; i--) {
501	if (hb_glyph[i].cluster != hb_glyph[i+1].cluster) {
502	  g_assert (hb_glyph[i].cluster > hb_glyph[i+1].cluster);
503	  if (utf8_clusters)
504	    end = start + hb_glyph[i].cluster - hb_glyph[i+1].cluster;
505	  else
506	    end = g_utf8_offset_to_pointer (start, hb_glyph[i].cluster - hb_glyph[i+1].cluster);
507	  l->clusters[cluster].num_bytes = end - start;
508	  start = end;
509	  cluster++;
510	}
511	l->clusters[cluster].num_glyphs++;
512      }
513      l->clusters[cluster].num_bytes = l->utf8 + text_len - start;
514    } else {
515      for (i = 1; i < (int) l->num_glyphs; i++) {
516	if (hb_glyph[i].cluster != hb_glyph[i-1].cluster) {
517	  g_assert (hb_glyph[i].cluster > hb_glyph[i-1].cluster);
518	  if (utf8_clusters)
519	    end = start + hb_glyph[i].cluster - hb_glyph[i-1].cluster;
520	  else
521	    end = g_utf8_offset_to_pointer (start, hb_glyph[i].cluster - hb_glyph[i-1].cluster);
522	  l->clusters[cluster].num_bytes = end - start;
523	  start = end;
524	  cluster++;
525	}
526	l->clusters[cluster].num_glyphs++;
527      }
528      l->clusters[cluster].num_bytes = l->utf8 + text_len - start;
529    }
530  }
531}
532