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