helper-cairo.cc revision 0594a2448440208efa0acac9a5d8d52d43108289
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
63cairo_scaled_font_t *
64helper_cairo_create_scaled_font (const font_options_t *font_opts,
65				 double font_size)
66{
67  hb_font_t *font = hb_font_reference (font_opts->get_font ());
68
69  cairo_font_face_t *cairo_face;
70  FT_Face ft_face = hb_ft_font_get_face (font);
71  if (!ft_face)
72    /* This allows us to get some boxes at least... */
73    cairo_face = cairo_toy_font_face_create ("@cairo:sans",
74					     CAIRO_FONT_SLANT_NORMAL,
75					     CAIRO_FONT_WEIGHT_NORMAL);
76  else
77    cairo_face = cairo_ft_font_face_create_for_ft_face (ft_face, 0);
78  cairo_matrix_t ctm, font_matrix;
79  cairo_font_options_t *font_options;
80
81  cairo_matrix_init_identity (&ctm);
82  cairo_matrix_init_scale (&font_matrix,
83			   font_size, font_size);
84  font_options = cairo_font_options_create ();
85  cairo_font_options_set_hint_style (font_options, CAIRO_HINT_STYLE_NONE);
86  cairo_font_options_set_hint_metrics (font_options, CAIRO_HINT_METRICS_OFF);
87
88  cairo_scaled_font_t *scaled_font = cairo_scaled_font_create (cairo_face,
89							       &font_matrix,
90							       &ctm,
91							       font_options);
92
93  cairo_font_options_destroy (font_options);
94  cairo_font_face_destroy (cairo_face);
95
96  static cairo_user_data_key_t key;
97  if (cairo_scaled_font_set_user_data (scaled_font,
98				       &key,
99				       (void *) font,
100				       (cairo_destroy_func_t) hb_font_destroy))
101    hb_font_destroy (font);
102
103  return scaled_font;
104}
105
106
107struct finalize_closure_t {
108  void (*callback)(finalize_closure_t *);
109  cairo_surface_t *surface;
110  cairo_write_func_t write_func;
111  void *closure;
112};
113static cairo_user_data_key_t finalize_closure_key;
114
115
116static void
117finalize_ansi (finalize_closure_t *closure)
118{
119  cairo_status_t status;
120  status = helper_cairo_surface_write_to_ansi_stream (closure->surface,
121						      closure->write_func,
122						      closure->closure);
123  if (status != CAIRO_STATUS_SUCCESS)
124    fail (false, "Failed to write output: %s",
125	  cairo_status_to_string (status));
126}
127
128static cairo_surface_t *
129_cairo_ansi_surface_create_for_stream (cairo_write_func_t write_func,
130				       void *closure,
131				       double width,
132				       double height,
133				       cairo_content_t content)
134{
135  cairo_surface_t *surface;
136  int w = ceil (width);
137  int h = ceil (height);
138
139  switch (content) {
140    case CAIRO_CONTENT_ALPHA:
141      surface = cairo_image_surface_create (CAIRO_FORMAT_A8, w, h);
142      break;
143    default:
144    case CAIRO_CONTENT_COLOR:
145      surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, w, h);
146      break;
147    case CAIRO_CONTENT_COLOR_ALPHA:
148      surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
149      break;
150  }
151  cairo_status_t status = cairo_surface_status (surface);
152  if (status != CAIRO_STATUS_SUCCESS)
153    fail (false, "Failed to create cairo surface: %s",
154	  cairo_status_to_string (status));
155
156  finalize_closure_t *ansi_closure = g_new0 (finalize_closure_t, 1);
157  ansi_closure->callback = finalize_ansi;
158  ansi_closure->surface = surface;
159  ansi_closure->write_func = write_func;
160  ansi_closure->closure = closure;
161
162  if (cairo_surface_set_user_data (surface,
163				   &finalize_closure_key,
164				   (void *) ansi_closure,
165				   (cairo_destroy_func_t) g_free))
166    g_free ((void *) closure);
167
168  return surface;
169}
170
171
172#ifdef CAIRO_HAS_PNG_FUNCTIONS
173
174static void
175finalize_png (finalize_closure_t *closure)
176{
177  cairo_status_t status;
178  status = cairo_surface_write_to_png_stream (closure->surface,
179					      closure->write_func,
180					      closure->closure);
181  if (status != CAIRO_STATUS_SUCCESS)
182    fail (false, "Failed to write output: %s",
183	  cairo_status_to_string (status));
184}
185
186static cairo_surface_t *
187_cairo_png_surface_create_for_stream (cairo_write_func_t write_func,
188				      void *closure,
189				      double width,
190				      double height,
191				      cairo_content_t content)
192{
193  cairo_surface_t *surface;
194  int w = ceil (width);
195  int h = ceil (height);
196
197  switch (content) {
198    case CAIRO_CONTENT_ALPHA:
199      surface = cairo_image_surface_create (CAIRO_FORMAT_A8, w, h);
200      break;
201    default:
202    case CAIRO_CONTENT_COLOR:
203      surface = cairo_image_surface_create (CAIRO_FORMAT_RGB24, w, h);
204      break;
205    case CAIRO_CONTENT_COLOR_ALPHA:
206      surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, w, h);
207      break;
208  }
209  cairo_status_t status = cairo_surface_status (surface);
210  if (status != CAIRO_STATUS_SUCCESS)
211    fail (false, "Failed to create cairo surface: %s",
212	  cairo_status_to_string (status));
213
214  finalize_closure_t *png_closure = g_new0 (finalize_closure_t, 1);
215  png_closure->callback = finalize_png;
216  png_closure->surface = surface;
217  png_closure->write_func = write_func;
218  png_closure->closure = closure;
219
220  if (cairo_surface_set_user_data (surface,
221				   &finalize_closure_key,
222				   (void *) png_closure,
223				   (cairo_destroy_func_t) g_free))
224    g_free ((void *) closure);
225
226  return surface;
227}
228
229#endif
230
231static cairo_status_t
232stdio_write_func (void                *closure,
233		  const unsigned char *data,
234		  unsigned int         size)
235{
236  FILE *fp = (FILE *) closure;
237
238  while (size) {
239    size_t ret = fwrite (data, 1, size, fp);
240    size -= ret;
241    data += ret;
242    if (size && ferror (fp))
243      fail (false, "Failed to write output: %s", strerror (errno));
244  }
245
246  return CAIRO_STATUS_SUCCESS;
247}
248
249cairo_t *
250helper_cairo_create_context (double w, double h,
251			     view_options_t *view_opts,
252			     output_options_t *out_opts)
253{
254  cairo_surface_t *(*constructor) (cairo_write_func_t write_func,
255				   void *closure,
256				   double width,
257				   double height) = NULL;
258  cairo_surface_t *(*constructor2) (cairo_write_func_t write_func,
259				    void *closure,
260				    double width,
261				    double height,
262				    cairo_content_t content) = NULL;
263
264  const char *extension = out_opts->output_format;
265  if (!extension) {
266#if HAVE_ISATTY
267    if (isatty (fileno (out_opts->get_file_handle ())))
268      extension = "ansi";
269    else
270#endif
271      extension = "png";
272  }
273  if (0)
274    ;
275    else if (0 == strcasecmp (extension, "ansi"))
276      constructor2 = _cairo_ansi_surface_create_for_stream;
277  #ifdef CAIRO_HAS_PNG_FUNCTIONS
278    else if (0 == strcasecmp (extension, "png"))
279      constructor2 = _cairo_png_surface_create_for_stream;
280  #endif
281  #ifdef CAIRO_HAS_SVG_SURFACE
282    else if (0 == strcasecmp (extension, "svg"))
283      constructor = cairo_svg_surface_create_for_stream;
284  #endif
285  #ifdef CAIRO_HAS_PDF_SURFACE
286    else if (0 == strcasecmp (extension, "pdf"))
287      constructor = cairo_pdf_surface_create_for_stream;
288  #endif
289  #ifdef CAIRO_HAS_PS_SURFACE
290    else if (0 == strcasecmp (extension, "ps"))
291      constructor = cairo_ps_surface_create_for_stream;
292   #ifdef HAS_EPS
293    else if (0 == strcasecmp (extension, "eps"))
294      constructor = _cairo_eps_surface_create_for_stream;
295   #endif
296  #endif
297
298
299  unsigned int fr, fg, fb, fa, br, bg, bb, ba;
300  br = bg = bb = 0; ba = 255;
301  sscanf (view_opts->back + (*view_opts->back=='#'), "%2x%2x%2x%2x", &br, &bg, &bb, &ba);
302  fr = fg = fb = 0; fa = 255;
303  sscanf (view_opts->fore + (*view_opts->fore=='#'), "%2x%2x%2x%2x", &fr, &fg, &fb, &fa);
304
305  cairo_content_t content;
306  if (!view_opts->annotate && ba == 255 && br == bg && bg == bb && fr == fg && fg == fb)
307    content = CAIRO_CONTENT_ALPHA;
308  else if (ba == 255)
309    content = CAIRO_CONTENT_COLOR;
310  else
311    content = CAIRO_CONTENT_COLOR_ALPHA;
312
313  cairo_surface_t *surface;
314  FILE *f = out_opts->get_file_handle ();
315  if (constructor)
316    surface = constructor (stdio_write_func, f, w, h);
317  else if (constructor2)
318    surface = constructor2 (stdio_write_func, f, w, h, content);
319  else
320    fail (false, "Unknown output format `%s'", extension);
321
322  cairo_t *cr = cairo_create (surface);
323  content = cairo_surface_get_content (surface);
324
325  switch (content) {
326    case CAIRO_CONTENT_ALPHA:
327      cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
328      cairo_set_source_rgba (cr, 1., 1., 1., br / 255.);
329      cairo_paint (cr);
330      cairo_set_source_rgba (cr, 1., 1., 1.,
331			     (fr / 255.) * (fa / 255.) + (br / 255) * (1 - (fa / 255.)));
332      break;
333    default:
334    case CAIRO_CONTENT_COLOR:
335    case CAIRO_CONTENT_COLOR_ALPHA:
336      cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
337      cairo_set_source_rgba (cr, br / 255., bg / 255., bb / 255., ba / 255.);
338      cairo_paint (cr);
339      cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
340      cairo_set_source_rgba (cr, fr / 255., fg / 255., fb / 255., fa / 255.);
341      break;
342  }
343
344  cairo_surface_destroy (surface);
345  return cr;
346}
347
348void
349helper_cairo_destroy_context (cairo_t *cr)
350{
351  finalize_closure_t *closure = (finalize_closure_t *)
352				cairo_surface_get_user_data (cairo_get_target (cr),
353							     &finalize_closure_key);
354  if (closure)
355    closure->callback (closure);
356
357  cairo_status_t status = cairo_status (cr);
358  if (status != CAIRO_STATUS_SUCCESS)
359    fail (false, "Failed: %s",
360	  cairo_status_to_string (status));
361  cairo_destroy (cr);
362}
363
364
365void
366helper_cairo_line_from_buffer (helper_cairo_line_t *l,
367			       hb_buffer_t         *buffer,
368			       const char          *text,
369			       unsigned int         text_len,
370			       double               scale,
371			       hb_bool_t            utf8_clusters)
372{
373  memset (l, 0, sizeof (*l));
374
375  l->num_glyphs = hb_buffer_get_length (buffer);
376  hb_glyph_info_t *hb_glyph = hb_buffer_get_glyph_infos (buffer, NULL);
377  hb_glyph_position_t *hb_position = hb_buffer_get_glyph_positions (buffer, NULL);
378  l->glyphs = cairo_glyph_allocate (l->num_glyphs + 1);
379
380  if (text) {
381    l->utf8 = g_strndup (text, text_len);
382    l->utf8_len = text_len;
383    l->num_clusters = l->num_glyphs ? 1 : 0;
384    for (unsigned int i = 1; i < l->num_glyphs; i++)
385      if (hb_glyph[i].cluster != hb_glyph[i-1].cluster)
386	l->num_clusters++;
387    l->clusters = cairo_text_cluster_allocate (l->num_clusters);
388  }
389
390  if ((l->num_glyphs && !l->glyphs) ||
391      (l->utf8_len && !l->utf8) ||
392      (l->num_clusters && !l->clusters))
393  {
394    l->finish ();
395    return;
396  }
397
398  hb_position_t x = 0, y = 0;
399  int i;
400  for (i = 0; i < (int) l->num_glyphs; i++)
401  {
402    l->glyphs[i].index = hb_glyph[i].codepoint;
403    l->glyphs[i].x = ( hb_position->x_offset + x) * scale;
404    l->glyphs[i].y = (-hb_position->y_offset + y) * scale;
405    x +=  hb_position->x_advance;
406    y += -hb_position->y_advance;
407
408    hb_position++;
409  }
410  l->glyphs[i].index = -1;
411  l->glyphs[i].x = x * scale;
412  l->glyphs[i].y = y * scale;
413
414  if (l->num_clusters) {
415    memset ((void *) l->clusters, 0, l->num_clusters * sizeof (l->clusters[0]));
416    hb_bool_t backward = HB_DIRECTION_IS_BACKWARD (hb_buffer_get_direction (buffer));
417    l->cluster_flags = backward ? CAIRO_TEXT_CLUSTER_FLAG_BACKWARD : (cairo_text_cluster_flags_t) 0;
418    unsigned int cluster = 0;
419    const char *start = l->utf8, *end = start;
420    l->clusters[cluster].num_glyphs++;
421    if (backward) {
422      for (i = l->num_glyphs - 2; i >= 0; i--) {
423	if (hb_glyph[i].cluster != hb_glyph[i+1].cluster) {
424	  g_assert (hb_glyph[i].cluster > hb_glyph[i+1].cluster);
425	  if (utf8_clusters)
426	    end = start + hb_glyph[i].cluster - hb_glyph[i+1].cluster;
427	  else
428	    end = g_utf8_offset_to_pointer (start, hb_glyph[i].cluster - hb_glyph[i+1].cluster);
429	  l->clusters[cluster].num_bytes = end - start;
430	  start = end;
431	  cluster++;
432	}
433	l->clusters[cluster].num_glyphs++;
434      }
435      l->clusters[cluster].num_bytes = l->utf8 + text_len - start;
436    } else {
437      for (i = 1; i < (int) l->num_glyphs; i++) {
438	if (hb_glyph[i].cluster != hb_glyph[i-1].cluster) {
439	  g_assert (hb_glyph[i].cluster > hb_glyph[i-1].cluster);
440	  if (utf8_clusters)
441	    end = start + hb_glyph[i].cluster - hb_glyph[i-1].cluster;
442	  else
443	    end = g_utf8_offset_to_pointer (start, hb_glyph[i].cluster - hb_glyph[i-1].cluster);
444	  l->clusters[cluster].num_bytes = end - start;
445	  start = end;
446	  cluster++;
447	}
448	l->clusters[cluster].num_glyphs++;
449      }
450      l->clusters[cluster].num_bytes = l->utf8 + text_len - start;
451    }
452  }
453}
454