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