Imported Upstream version 2.6.7
[platform/upstream/harfbuzz.git] / util / options.cc
1 /*
2  * Copyright © 2011,2012  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 "options.hh"
28
29 #ifdef HAVE_FREETYPE
30 #include <hb-ft.h>
31 #endif
32 #include <hb-ot.h>
33
34 #define DELIMITERS "<+>{},;&#\\xXuUnNiI\n\t\v\f\r "
35
36 static struct supported_font_funcs_t {
37         char name[4];
38         void (*func) (hb_font_t *);
39 } supported_font_funcs[] =
40 {
41 #ifdef HAVE_FREETYPE
42   {"ft",        hb_ft_font_set_funcs},
43 #endif
44   {"ot",        hb_ot_font_set_funcs},
45 };
46
47
48 void
49 fail (hb_bool_t suggest_help, const char *format, ...)
50 {
51   const char *msg;
52
53   va_list vap;
54   va_start (vap, format);
55   msg = g_strdup_vprintf (format, vap);
56   va_end (vap);
57   const char *prgname = g_get_prgname ();
58   g_printerr ("%s: %s\n", prgname, msg);
59   if (suggest_help)
60     g_printerr ("Try `%s --help' for more information.\n", prgname);
61
62   exit (1);
63 }
64
65
66 static gchar *
67 shapers_to_string ()
68 {
69   GString *shapers = g_string_new (nullptr);
70   const char **shaper_list = hb_shape_list_shapers ();
71
72   for (; *shaper_list; shaper_list++) {
73     g_string_append (shapers, *shaper_list);
74     g_string_append_c (shapers, ',');
75   }
76   g_string_truncate (shapers, MAX (0, (gint)shapers->len - 1));
77
78   return g_string_free (shapers, false);
79 }
80
81 static G_GNUC_NORETURN gboolean
82 show_version (const char *name G_GNUC_UNUSED,
83               const char *arg G_GNUC_UNUSED,
84               gpointer    data G_GNUC_UNUSED,
85               GError    **error G_GNUC_UNUSED)
86 {
87   g_printf ("%s (%s) %s\n", g_get_prgname (), PACKAGE_NAME, PACKAGE_VERSION);
88
89   char *shapers = shapers_to_string ();
90   g_printf ("Available shapers: %s\n", shapers);
91   g_free (shapers);
92   if (strcmp (HB_VERSION_STRING, hb_version_string ()))
93     g_printf ("Linked HarfBuzz library has a different version: %s\n", hb_version_string ());
94
95   exit(0);
96 }
97
98
99 void
100 option_parser_t::add_main_options ()
101 {
102   GOptionEntry entries[] =
103   {
104     {"version",         0, G_OPTION_FLAG_NO_ARG,
105                               G_OPTION_ARG_CALLBACK,    (gpointer) &show_version,       "Show version numbers",                 nullptr},
106     {nullptr}
107   };
108   g_option_context_add_main_entries (context, entries, nullptr);
109 }
110
111 static gboolean
112 pre_parse (GOptionContext *context G_GNUC_UNUSED,
113            GOptionGroup *group G_GNUC_UNUSED,
114            gpointer data,
115            GError **error)
116 {
117   option_group_t *option_group = (option_group_t *) data;
118   option_group->pre_parse (error);
119   return !*error;
120 }
121
122 static gboolean
123 post_parse (GOptionContext *context G_GNUC_UNUSED,
124             GOptionGroup *group G_GNUC_UNUSED,
125             gpointer data,
126             GError **error)
127 {
128   option_group_t *option_group = static_cast<option_group_t *>(data);
129   option_group->post_parse (error);
130   return !*error;
131 }
132
133 void
134 option_parser_t::add_group (GOptionEntry   *entries,
135                             const gchar    *name,
136                             const gchar    *description,
137                             const gchar    *help_description,
138                             option_group_t *option_group)
139 {
140   GOptionGroup *group = g_option_group_new (name, description, help_description,
141                                             static_cast<gpointer>(option_group), nullptr);
142   g_option_group_add_entries (group, entries);
143   g_option_group_set_parse_hooks (group, pre_parse, post_parse);
144   g_option_context_add_group (context, group);
145 }
146
147 void
148 option_parser_t::parse (int *argc, char ***argv)
149 {
150   setlocale (LC_ALL, "");
151
152   GError *parse_error = nullptr;
153   if (!g_option_context_parse (context, argc, argv, &parse_error))
154   {
155     if (parse_error)
156     {
157       fail (true, "%s", parse_error->message);
158       //g_error_free (parse_error);
159     }
160     else
161       fail (true, "Option parse error");
162   }
163 }
164
165
166 static gboolean
167 parse_font_extents (const char *name G_GNUC_UNUSED,
168                     const char *arg,
169                     gpointer    data,
170                     GError    **error G_GNUC_UNUSED)
171 {
172   view_options_t *view_opts = (view_options_t *) data;
173   view_options_t::font_extents_t &e = view_opts->font_extents;
174   switch (sscanf (arg, "%lf%*[ ,]%lf%*[ ,]%lf", &e.ascent, &e.descent, &e.line_gap)) {
175     case 1: HB_FALLTHROUGH;
176     case 2: HB_FALLTHROUGH;
177     case 3:
178       view_opts->have_font_extents = true;
179       return true;
180     default:
181       g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
182                    "%s argument should be one to three space-separated numbers",
183                    name);
184       return false;
185   }
186 }
187
188 static gboolean
189 parse_margin (const char *name G_GNUC_UNUSED,
190               const char *arg,
191               gpointer    data,
192               GError    **error G_GNUC_UNUSED)
193 {
194   view_options_t *view_opts = (view_options_t *) data;
195   view_options_t::margin_t &m = view_opts->margin;
196   switch (sscanf (arg, "%lf%*[ ,]%lf%*[ ,]%lf%*[ ,]%lf", &m.t, &m.r, &m.b, &m.l)) {
197     case 1: m.r = m.t; HB_FALLTHROUGH;
198     case 2: m.b = m.t; HB_FALLTHROUGH;
199     case 3: m.l = m.r; HB_FALLTHROUGH;
200     case 4: return true;
201     default:
202       g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
203                    "%s argument should be one to four space-separated numbers",
204                    name);
205       return false;
206   }
207 }
208
209
210 static gboolean
211 parse_shapers (const char *name G_GNUC_UNUSED,
212                const char *arg,
213                gpointer    data,
214                GError    **error)
215 {
216   shape_options_t *shape_opts = (shape_options_t *) data;
217   char **shapers = g_strsplit (arg, ",", 0);
218
219   for (char **shaper = shapers; *shaper; shaper++) {
220     bool found = false;
221     for (const char **hb_shaper = hb_shape_list_shapers (); *hb_shaper; hb_shaper++) {
222       if (strcmp (*shaper, *hb_shaper) == 0) {
223         found = true;
224         break;
225       }
226     }
227     if (!found) {
228       g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
229                    "Unknown or unsupported shaper: %s", *shaper);
230       g_strfreev (shapers);
231       return false;
232     }
233   }
234
235   g_strfreev (shape_opts->shapers);
236   shape_opts->shapers = shapers;
237   return true;
238 }
239
240 static G_GNUC_NORETURN gboolean
241 list_shapers (const char *name G_GNUC_UNUSED,
242               const char *arg G_GNUC_UNUSED,
243               gpointer    data G_GNUC_UNUSED,
244               GError    **error G_GNUC_UNUSED)
245 {
246   for (const char **shaper = hb_shape_list_shapers (); *shaper; shaper++)
247     g_printf ("%s\n", *shaper);
248
249   exit(0);
250 }
251
252
253 static gboolean
254 parse_features (const char *name G_GNUC_UNUSED,
255                 const char *arg,
256                 gpointer    data,
257                 GError    **error G_GNUC_UNUSED)
258 {
259   shape_options_t *shape_opts = (shape_options_t *) data;
260   char *s = (char *) arg;
261   char *p;
262
263   shape_opts->num_features = 0;
264   g_free (shape_opts->features);
265   shape_opts->features = nullptr;
266
267   if (!*s)
268     return true;
269
270   /* count the features first, so we can allocate memory */
271   p = s;
272   do {
273     shape_opts->num_features++;
274     p = strchr (p, ',');
275     if (p)
276       p++;
277   } while (p);
278
279   shape_opts->features = (hb_feature_t *) calloc (shape_opts->num_features, sizeof (*shape_opts->features));
280   if (!shape_opts->features)
281     return false;
282
283   /* now do the actual parsing */
284   p = s;
285   shape_opts->num_features = 0;
286   while (p && *p) {
287     char *end = strchr (p, ',');
288     if (hb_feature_from_string (p, end ? end - p : -1, &shape_opts->features[shape_opts->num_features]))
289       shape_opts->num_features++;
290     p = end ? end + 1 : nullptr;
291   }
292
293   return true;
294 }
295
296 static gboolean
297 parse_variations (const char *name G_GNUC_UNUSED,
298                   const char *arg,
299                   gpointer    data,
300                   GError    **error G_GNUC_UNUSED)
301 {
302   font_options_t *font_opts = (font_options_t *) data;
303   char *s = (char *) arg;
304   char *p;
305
306   font_opts->num_variations = 0;
307   g_free (font_opts->variations);
308   font_opts->variations = nullptr;
309
310   if (!*s)
311     return true;
312
313   /* count the variations first, so we can allocate memory */
314   p = s;
315   do {
316     font_opts->num_variations++;
317     p = strchr (p, ',');
318     if (p)
319       p++;
320   } while (p);
321
322   font_opts->variations = (hb_variation_t *) calloc (font_opts->num_variations, sizeof (*font_opts->variations));
323   if (!font_opts->variations)
324     return false;
325
326   /* now do the actual parsing */
327   p = s;
328   font_opts->num_variations = 0;
329   while (p && *p) {
330     char *end = strchr (p, ',');
331     if (hb_variation_from_string (p, end ? end - p : -1, &font_opts->variations[font_opts->num_variations]))
332       font_opts->num_variations++;
333     p = end ? end + 1 : nullptr;
334   }
335
336   return true;
337 }
338
339 static gboolean
340 parse_text (const char *name G_GNUC_UNUSED,
341             const char *arg,
342             gpointer    data,
343             GError    **error G_GNUC_UNUSED)
344 {
345   text_options_t *text_opts = (text_options_t *) data;
346
347   if (text_opts->text)
348   {
349     g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
350                  "Either --text or --unicodes can be provided but not both");
351     return false;
352   }
353
354   text_opts->text_len = -1;
355   text_opts->text = g_strdup (arg);
356   return true;
357 }
358
359
360 static gboolean
361 parse_unicodes (const char *name G_GNUC_UNUSED,
362                 const char *arg,
363                 gpointer    data,
364                 GError    **error G_GNUC_UNUSED)
365 {
366   text_options_t *text_opts = (text_options_t *) data;
367
368   if (text_opts->text)
369   {
370     g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
371                  "Either --text or --unicodes can be provided but not both");
372     return false;
373   }
374
375   GString *gs = g_string_new (nullptr);
376   if (0 == strcmp (arg, "*"))
377   {
378     g_string_append_c (gs, '*');
379   }
380   else
381   {
382
383     char *s = (char *) arg;
384     char *p;
385
386     while (s && *s)
387     {
388       while (*s && strchr (DELIMITERS, *s))
389         s++;
390       if (!*s)
391         break;
392
393       errno = 0;
394       hb_codepoint_t u = strtoul (s, &p, 16);
395       if (errno || s == p)
396       {
397         g_string_free (gs, TRUE);
398         g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
399                      "Failed parsing Unicode values at: '%s'", s);
400         return false;
401       }
402
403       g_string_append_unichar (gs, u);
404
405       s = p;
406     }
407   }
408
409   text_opts->text_len = gs->len;
410   text_opts->text = g_string_free (gs, FALSE);
411   return true;
412 }
413
414
415 void
416 view_options_t::add_options (option_parser_t *parser)
417 {
418   GOptionEntry entries[] =
419   {
420     {"annotate",        0, 0, G_OPTION_ARG_NONE,        &this->annotate,                "Annotate output rendering",                            nullptr},
421     {"background",      0, 0, G_OPTION_ARG_STRING,      &this->back,                    "Set background color (default: " DEFAULT_BACK ")",     "rrggbb/rrggbbaa"},
422     {"foreground",      0, 0, G_OPTION_ARG_STRING,      &this->fore,                    "Set foreground color (default: " DEFAULT_FORE ")",     "rrggbb/rrggbbaa"},
423     {"line-space",      0, 0, G_OPTION_ARG_DOUBLE,      &this->line_space,              "Set space between lines (default: 0)",                 "units"},
424     {"font-extents",    0, 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_font_extents, "Set font ascent/descent/line-gap (default: auto)","one to three numbers"},
425     {"margin",          0, 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_margin,       "Margin around output (default: " G_STRINGIFY(DEFAULT_MARGIN) ")","one to four numbers"},
426     {nullptr}
427   };
428   parser->add_group (entries,
429                      "view",
430                      "View options:",
431                      "Options for output rendering",
432                      this);
433 }
434
435 void
436 shape_options_t::add_options (option_parser_t *parser)
437 {
438   GOptionEntry entries[] =
439   {
440     {"list-shapers",    0, G_OPTION_FLAG_NO_ARG,
441                               G_OPTION_ARG_CALLBACK,    (gpointer) &list_shapers,       "List available shapers and quit",      nullptr},
442     {"shaper",          0, G_OPTION_FLAG_HIDDEN,
443                               G_OPTION_ARG_CALLBACK,    (gpointer) &parse_shapers,      "Hidden duplicate of --shapers",        nullptr},
444     {"shapers",         0, 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_shapers,      "Set comma-separated list of shapers to try","list"},
445     {"direction",       0, 0, G_OPTION_ARG_STRING,      &this->direction,               "Set text direction (default: auto)",   "ltr/rtl/ttb/btt"},
446     {"language",        0, 0, G_OPTION_ARG_STRING,      &this->language,                "Set text language (default: $LANG)",   "langstr"},
447     {"script",          0, 0, G_OPTION_ARG_STRING,      &this->script,                  "Set text script (default: auto)",      "ISO-15924 tag"},
448     {"bot",             0, 0, G_OPTION_ARG_NONE,        &this->bot,                     "Treat text as beginning-of-paragraph", nullptr},
449     {"eot",             0, 0, G_OPTION_ARG_NONE,        &this->eot,                     "Treat text as end-of-paragraph",       nullptr},
450     {"preserve-default-ignorables",0, 0, G_OPTION_ARG_NONE,     &this->preserve_default_ignorables,     "Preserve Default-Ignorable characters",        nullptr},
451     {"remove-default-ignorables",0, 0, G_OPTION_ARG_NONE,       &this->remove_default_ignorables,       "Remove Default-Ignorable characters",  nullptr},
452     {"invisible-glyph", 0, 0, G_OPTION_ARG_INT,         &this->invisible_glyph,         "Glyph value to replace Default-Ignorables with",       nullptr},
453     {"utf8-clusters",   0, 0, G_OPTION_ARG_NONE,        &this->utf8_clusters,           "Use UTF8 byte indices, not char indices",      nullptr},
454     {"cluster-level",   0, 0, G_OPTION_ARG_INT,         &this->cluster_level,           "Cluster merging level (default: 0)",   "0/1/2"},
455     {"normalize-glyphs",0, 0, G_OPTION_ARG_NONE,        &this->normalize_glyphs,        "Rearrange glyph clusters in nominal order",    nullptr},
456     {"verify",          0, 0, G_OPTION_ARG_NONE,        &this->verify,                  "Perform sanity checks on shaping results",     nullptr},
457     {"num-iterations", 'n', 0, G_OPTION_ARG_INT,                &this->num_iterations,          "Run shaper N times (default: 1)",      "N"},
458     {nullptr}
459   };
460   parser->add_group (entries,
461                      "shape",
462                      "Shape options:",
463                      "Options for the shaping process",
464                      this);
465
466   const gchar *features_help = "Comma-separated list of font features\n"
467     "\n"
468     "    Features can be enabled or disabled, either globally or limited to\n"
469     "    specific character ranges.  The format for specifying feature settings\n"
470     "    follows.  All valid CSS font-feature-settings values other than 'normal'\n"
471     "    and the global values are also accepted, though not documented below.\n"
472     "    CSS string escapes are not supported."
473     "\n"
474     "    The range indices refer to the positions between Unicode characters,\n"
475     "    unless the --utf8-clusters is provided, in which case range indices\n"
476     "    refer to UTF-8 byte indices. The position before the first character\n"
477     "    is always 0.\n"
478     "\n"
479     "    The format is Python-esque.  Here is how it all works:\n"
480     "\n"
481     "      Syntax:       Value:    Start:    End:\n"
482     "\n"
483     "    Setting value:\n"
484     "      \"kern\"        1         0         ∞         # Turn feature on\n"
485     "      \"+kern\"       1         0         ∞         # Turn feature on\n"
486     "      \"-kern\"       0         0         ∞         # Turn feature off\n"
487     "      \"kern=0\"      0         0         ∞         # Turn feature off\n"
488     "      \"kern=1\"      1         0         ∞         # Turn feature on\n"
489     "      \"aalt=2\"      2         0         ∞         # Choose 2nd alternate\n"
490     "\n"
491     "    Setting index:\n"
492     "      \"kern[]\"      1         0         ∞         # Turn feature on\n"
493     "      \"kern[:]\"     1         0         ∞         # Turn feature on\n"
494     "      \"kern[5:]\"    1         5         ∞         # Turn feature on, partial\n"
495     "      \"kern[:5]\"    1         0         5         # Turn feature on, partial\n"
496     "      \"kern[3:5]\"   1         3         5         # Turn feature on, range\n"
497     "      \"kern[3]\"     1         3         3+1       # Turn feature on, single char\n"
498     "\n"
499     "    Mixing it all:\n"
500     "\n"
501     "      \"aalt[3:5]=2\" 2         3         5         # Turn 2nd alternate on for range";
502
503   GOptionEntry entries2[] =
504   {
505     {"features",        0, 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_features,     features_help,  "list"},
506     {nullptr}
507   };
508   parser->add_group (entries2,
509                      "features",
510                      "Features options:",
511                      "Options for font features used",
512                      this);
513 }
514
515 static gboolean
516 parse_font_size (const char *name G_GNUC_UNUSED,
517                  const char *arg,
518                  gpointer    data,
519                  GError    **error G_GNUC_UNUSED)
520 {
521   font_options_t *font_opts = (font_options_t *) data;
522   if (0 == strcmp (arg, "upem"))
523   {
524     font_opts->font_size_y = font_opts->font_size_x = FONT_SIZE_UPEM;
525     return true;
526   }
527   switch (sscanf (arg, "%lf%*[ ,]%lf", &font_opts->font_size_x, &font_opts->font_size_y)) {
528     case 1: font_opts->font_size_y = font_opts->font_size_x; HB_FALLTHROUGH;
529     case 2: return true;
530     default:
531       g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
532                    "%s argument should be one or two space-separated numbers",
533                    name);
534       return false;
535   }
536 }
537
538 static gboolean
539 parse_font_ppem (const char *name G_GNUC_UNUSED,
540                  const char *arg,
541                  gpointer    data,
542                  GError    **error G_GNUC_UNUSED)
543 {
544   font_options_t *font_opts = (font_options_t *) data;
545   switch (sscanf (arg, "%d%*[ ,]%d", &font_opts->x_ppem, &font_opts->y_ppem)) {
546     case 1: font_opts->y_ppem = font_opts->x_ppem; HB_FALLTHROUGH;
547     case 2: return true;
548     default:
549       g_set_error (error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
550                    "%s argument should be one or two space-separated numbers",
551                    name);
552       return false;
553   }
554 }
555
556 void
557 font_options_t::add_options (option_parser_t *parser)
558 {
559   char *text = nullptr;
560
561   {
562     static_assert ((ARRAY_LENGTH_CONST (supported_font_funcs) > 0),
563                    "No supported font-funcs found.");
564     GString *s = g_string_new (nullptr);
565     g_string_printf (s, "Set font functions implementation to use (default: %s)\n\n    Supported font function implementations are: %s",
566                      supported_font_funcs[0].name,
567                      supported_font_funcs[0].name);
568     for (unsigned int i = 1; i < ARRAY_LENGTH (supported_font_funcs); i++)
569     {
570       g_string_append_c (s, '/');
571       g_string_append (s, supported_font_funcs[i].name);
572     }
573     text = g_string_free (s, FALSE);
574     parser->free_later (text);
575   }
576
577   char *font_size_text;
578   if (default_font_size == FONT_SIZE_UPEM)
579     font_size_text = (char *) "Font size (default: upem)";
580   else
581   {
582     font_size_text = g_strdup_printf ("Font size (default: %d)", default_font_size);
583     parser->free_later (font_size_text);
584   }
585
586   GOptionEntry entries[] =
587   {
588     {"font-file",       0, 0, G_OPTION_ARG_STRING,      &this->font_file,               "Set font file-name",                           "filename"},
589     {"face-index",      0, 0, G_OPTION_ARG_INT,         &this->face_index,              "Set face index (default: 0)",                  "index"},
590     {"font-size",       0, default_font_size ? 0 : G_OPTION_FLAG_HIDDEN,
591                               G_OPTION_ARG_CALLBACK,    (gpointer) &parse_font_size,    font_size_text,                                 "1/2 integers or 'upem'"},
592     {"font-ppem",       0, 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_font_ppem,    "Set x,y pixels per EM (default: 0; disabled)", "1/2 integers"},
593     {"font-ptem",       0, 0, G_OPTION_ARG_DOUBLE,      &this->ptem,                    "Set font point-size (default: 0; disabled)",   "point-size"},
594     {"font-funcs",      0, 0, G_OPTION_ARG_STRING,      &this->font_funcs,              text,                                           "impl"},
595     {"ft-load-flags",   0, 0, G_OPTION_ARG_INT,         &this->ft_load_flags,           "Set FreeType load-flags (default: 2)",         "integer"},
596     {nullptr}
597   };
598   parser->add_group (entries,
599                      "font",
600                      "Font options:",
601                      "Options for the font",
602                      this);
603
604   const gchar *variations_help = "Comma-separated list of font variations\n"
605     "\n"
606     "    Variations are set globally. The format for specifying variation settings\n"
607     "    follows.  All valid CSS font-variation-settings values other than 'normal'\n"
608     "    and 'inherited' are also accepted, though, not documented below.\n"
609     "\n"
610     "    The format is a tag, optionally followed by an equals sign, followed by a\n"
611     "    number. For example:\n"
612     "\n"
613     "      \"wght=500\"\n"
614     "      \"slnt=-7.5\"\n";
615
616   GOptionEntry entries2[] =
617   {
618     {"variations",      0, 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_variations,   variations_help,        "list"},
619     {nullptr}
620   };
621   parser->add_group (entries2,
622                      "variations",
623                      "Variations options:",
624                      "Options for font variations used",
625                      this);
626 }
627
628 void
629 text_options_t::add_options (option_parser_t *parser)
630 {
631   GOptionEntry entries[] =
632   {
633     {"text",            0, 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_text,         "Set input text",                       "string"},
634     {"text-file",       0, 0, G_OPTION_ARG_STRING,      &this->text_file,               "Set input text file-name\n\n    If no text is provided, standard input is used for input.\n",          "filename"},
635     {"unicodes",      'u', 0, G_OPTION_ARG_CALLBACK,    (gpointer) &parse_unicodes,             "Set input Unicode codepoints",         "list of hex numbers"},
636     {"text-before",     0, 0, G_OPTION_ARG_STRING,      &this->text_before,             "Set text context before each line",    "string"},
637     {"text-after",      0, 0, G_OPTION_ARG_STRING,      &this->text_after,              "Set text context after each line",     "string"},
638     {nullptr}
639   };
640   parser->add_group (entries,
641                      "text",
642                      "Text options:",
643                      "Options for the input text",
644                      this);
645 }
646
647 void
648 output_options_t::add_options (option_parser_t *parser)
649 {
650   const char *text;
651
652   if (!supported_formats)
653     text = "Set output serialization format";
654   else
655   {
656     char *items = g_strjoinv ("/", const_cast<char **> (supported_formats));
657     text = g_strdup_printf ("Set output format\n\n    Supported output formats are: %s", items);
658     g_free (items);
659     parser->free_later ((char *) text);
660   }
661
662   GOptionEntry entries[] =
663   {
664     {"output-file",   'o', 0, G_OPTION_ARG_STRING,      &this->output_file,             "Set output file-name (default: stdout)","filename"},
665     {"output-format", 'O', 0, G_OPTION_ARG_STRING,      &this->output_format,           text,                                   "format"},
666     {nullptr}
667   };
668   parser->add_group (entries,
669                      "output",
670                      "Output destination & format options:",
671                      "Options for the destination & form of the output",
672                      this);
673 }
674
675
676
677 hb_font_t *
678 font_options_t::get_font () const
679 {
680   if (font)
681     return font;
682
683   /* Create the blob */
684   if (!font_file)
685     fail (true, "No font file set");
686
687   const char *font_path = font_file;
688
689   if (0 == strcmp (font_path, "-"))
690   {
691 #if defined(_WIN32) || defined(__CYGWIN__)
692     setmode (fileno (stdin), O_BINARY);
693     font_path = "STDIN";
694 #else
695     font_path = "/dev/stdin";
696 #endif
697   }
698
699   blob = hb_blob_create_from_file (font_path);
700
701   if (blob == hb_blob_get_empty ())
702     fail (false, "Couldn't read or find %s, or it was empty.", font_path);
703
704   /* Create the face */
705   hb_face_t *face = hb_face_create (blob, face_index);
706   hb_blob_destroy (blob);
707
708
709   font = hb_font_create (face);
710
711   if (font_size_x == FONT_SIZE_UPEM)
712     font_size_x = hb_face_get_upem (face);
713   if (font_size_y == FONT_SIZE_UPEM)
714     font_size_y = hb_face_get_upem (face);
715
716   hb_font_set_ppem (font, x_ppem, y_ppem);
717   hb_font_set_ptem (font, ptem);
718
719   int scale_x = (int) scalbnf (font_size_x, subpixel_bits);
720   int scale_y = (int) scalbnf (font_size_y, subpixel_bits);
721   hb_font_set_scale (font, scale_x, scale_y);
722   hb_face_destroy (face);
723
724   hb_font_set_variations (font, variations, num_variations);
725
726   void (*set_font_funcs) (hb_font_t *) = nullptr;
727   if (!font_funcs)
728   {
729     set_font_funcs = supported_font_funcs[0].func;
730   }
731   else
732   {
733     for (unsigned int i = 0; i < ARRAY_LENGTH (supported_font_funcs); i++)
734       if (0 == g_ascii_strcasecmp (font_funcs, supported_font_funcs[i].name))
735       {
736         set_font_funcs = supported_font_funcs[i].func;
737         break;
738       }
739     if (!set_font_funcs)
740     {
741       GString *s = g_string_new (nullptr);
742       for (unsigned int i = 0; i < ARRAY_LENGTH (supported_font_funcs); i++)
743       {
744         if (i)
745           g_string_append_c (s, '/');
746         g_string_append (s, supported_font_funcs[i].name);
747       }
748       char *p = g_string_free (s, FALSE);
749       fail (false, "Unknown font function implementation `%s'; supported values are: %s; default is %s",
750             font_funcs,
751             p,
752             supported_font_funcs[0].name);
753       //free (p);
754     }
755   }
756   set_font_funcs (font);
757 #ifdef HAVE_FREETYPE
758   hb_ft_font_set_load_flags (font, ft_load_flags);
759 #endif
760
761   return font;
762 }
763
764
765 const char *
766 text_options_t::get_line (unsigned int *len)
767 {
768   if (text) {
769     if (!line)
770     {
771       line = text;
772       line_len = text_len;
773     }
774     if (line_len == UINT_MAX)
775       line_len = strlen (line);
776
777     if (!line_len) {
778       *len = 0;
779       return nullptr;
780     }
781
782     const char *ret = line;
783     const char *p = (const char *) memchr (line, '\n', line_len);
784     unsigned int ret_len;
785     if (!p) {
786       ret_len = line_len;
787       line += ret_len;
788       line_len = 0;
789     } else {
790       ret_len = p - ret;
791       line += ret_len + 1;
792       line_len -= ret_len + 1;
793     }
794
795     *len = ret_len;
796     return ret;
797   }
798
799   if (!fp) {
800     if (!text_file)
801       fail (true, "At least one of text or text-file must be set");
802
803     if (0 != strcmp (text_file, "-"))
804       fp = fopen (text_file, "r");
805     else
806       fp = stdin;
807
808     if (!fp)
809       fail (false, "Failed opening text file `%s': %s",
810             text_file, strerror (errno));
811
812     gs = g_string_new (nullptr);
813   }
814
815   g_string_set_size (gs, 0);
816   char buf[BUFSIZ];
817   while (fgets (buf, sizeof (buf), fp)) {
818     unsigned int bytes = strlen (buf);
819     if (bytes && buf[bytes - 1] == '\n') {
820       bytes--;
821       g_string_append_len (gs, buf, bytes);
822       break;
823     }
824       g_string_append_len (gs, buf, bytes);
825   }
826   if (ferror (fp))
827     fail (false, "Failed reading text: %s",
828           strerror (errno));
829   *len = gs->len;
830   return !*len && feof (fp) ? nullptr : gs->str;
831 }
832
833
834 FILE *
835 output_options_t::get_file_handle ()
836 {
837   if (fp)
838     return fp;
839
840   if (output_file)
841     fp = fopen (output_file, "wb");
842   else {
843 #if defined(_WIN32) || defined(__CYGWIN__)
844     setmode (fileno (stdout), O_BINARY);
845 #endif
846     fp = stdout;
847   }
848   if (!fp)
849     fail (false, "Cannot open output file `%s': %s",
850           g_filename_display_name (output_file), strerror (errno));
851
852   return fp;
853 }
854
855 static gboolean
856 parse_verbose (const char *name G_GNUC_UNUSED,
857                const char *arg G_GNUC_UNUSED,
858                gpointer    data G_GNUC_UNUSED,
859                GError    **error G_GNUC_UNUSED)
860 {
861   format_options_t *format_opts = (format_options_t *) data;
862   format_opts->show_text = format_opts->show_unicode = format_opts->show_line_num = true;
863   return true;
864 }
865
866 static gboolean
867 parse_ned (const char *name G_GNUC_UNUSED,
868            const char *arg G_GNUC_UNUSED,
869            gpointer    data G_GNUC_UNUSED,
870            GError    **error G_GNUC_UNUSED)
871 {
872   format_options_t *format_opts = (format_options_t *) data;
873   format_opts->show_clusters = format_opts->show_advances = false;
874   return true;
875 }
876
877 void
878 format_options_t::add_options (option_parser_t *parser)
879 {
880   GOptionEntry entries[] =
881   {
882     {"show-text",       0, 0, G_OPTION_ARG_NONE,        &this->show_text,               "Prefix each line of output with its corresponding input text",         nullptr},
883     {"show-unicode",    0, 0, G_OPTION_ARG_NONE,        &this->show_unicode,            "Prefix each line of output with its corresponding input codepoint(s)", nullptr},
884     {"show-line-num",   0, 0, G_OPTION_ARG_NONE,        &this->show_line_num,           "Prefix each line of output with its corresponding input line number",  nullptr},
885     {"verbose",       'v', G_OPTION_FLAG_NO_ARG,
886                               G_OPTION_ARG_CALLBACK,    (gpointer) &parse_verbose,      "Prefix each line of output with all of the above",                     nullptr},
887     {"no-glyph-names",  0, G_OPTION_FLAG_REVERSE,
888                               G_OPTION_ARG_NONE,        &this->show_glyph_names,        "Output glyph indices instead of names",                                nullptr},
889     {"no-positions",    0, G_OPTION_FLAG_REVERSE,
890                               G_OPTION_ARG_NONE,        &this->show_positions,          "Do not output glyph positions",                                        nullptr},
891     {"no-advances",     0, G_OPTION_FLAG_REVERSE,
892                               G_OPTION_ARG_NONE,        &this->show_advances,           "Do not output glyph advances",                                         nullptr},
893     {"no-clusters",     0, G_OPTION_FLAG_REVERSE,
894                               G_OPTION_ARG_NONE,        &this->show_clusters,           "Do not output cluster indices",                                        nullptr},
895     {"show-extents",    0, 0, G_OPTION_ARG_NONE,        &this->show_extents,            "Output glyph extents",                                                 nullptr},
896     {"show-flags",      0, 0, G_OPTION_ARG_NONE,        &this->show_flags,              "Output glyph flags",                                                   nullptr},
897     {"ned",           'v', G_OPTION_FLAG_NO_ARG,
898                               G_OPTION_ARG_CALLBACK,    (gpointer) &parse_ned,          "No Extra Data; Do not output clusters or advances",                    nullptr},
899     {"trace",         'V', 0, G_OPTION_ARG_NONE,        &this->trace,                   "Output interim shaping results",                                       nullptr},
900     {nullptr}
901   };
902   parser->add_group (entries,
903                      "output-syntax",
904                      "Output syntax:\n"
905          "    text: [<glyph name or index>=<glyph cluster index within input>@<horizontal displacement>,<vertical displacement>+<horizontal advance>,<vertical advance>|...]\n"
906          "    json: [{\"g\": <glyph name or index>, \"ax\": <horizontal advance>, \"ay\": <vertical advance>, \"dx\": <horizontal displacement>, \"dy\": <vertical displacement>, \"cl\": <glyph cluster index within input>}, ...]\n"
907          "\nOutput syntax options:",
908                      "Options for the syntax of the output",
909                      this);
910 }
911
912 void
913 format_options_t::serialize_unicode (hb_buffer_t *buffer,
914                                      GString     *gs)
915 {
916   unsigned int num_glyphs = hb_buffer_get_length (buffer);
917   hb_glyph_info_t *info = hb_buffer_get_glyph_infos (buffer, nullptr);
918
919   g_string_append_c (gs, '<');
920   for (unsigned int i = 0; i < num_glyphs; i++)
921   {
922     if (i)
923       g_string_append_c (gs, ',');
924     g_string_append_printf (gs, "U+%04X", info->codepoint);
925     info++;
926   }
927   g_string_append_c (gs, '>');
928 }
929
930 void
931 format_options_t::serialize_glyphs (hb_buffer_t *buffer,
932                                     hb_font_t   *font,
933                                     hb_buffer_serialize_format_t output_format,
934                                     hb_buffer_serialize_flags_t flags,
935                                     GString     *gs)
936 {
937   g_string_append_c (gs, '[');
938   unsigned int num_glyphs = hb_buffer_get_length (buffer);
939   unsigned int start = 0;
940
941   while (start < num_glyphs)
942   {
943     char buf[32768];
944     unsigned int consumed;
945     start += hb_buffer_serialize_glyphs (buffer, start, num_glyphs,
946                                          buf, sizeof (buf), &consumed,
947                                          font, output_format, flags);
948     if (!consumed)
949       break;
950     g_string_append (gs, buf);
951   }
952   g_string_append_c (gs, ']');
953 }
954 void
955 format_options_t::serialize_line_no (unsigned int  line_no,
956                                      GString      *gs)
957 {
958   if (show_line_num)
959     g_string_append_printf (gs, "%d: ", line_no);
960 }
961 void
962 format_options_t::serialize_buffer_of_text (hb_buffer_t  *buffer,
963                                             unsigned int  line_no,
964                                             const char   *text,
965                                             unsigned int  text_len,
966                                             hb_font_t    *font,
967                                             GString      *gs)
968 {
969   if (show_text)
970   {
971     serialize_line_no (line_no, gs);
972     g_string_append_c (gs, '(');
973     g_string_append_len (gs, text, text_len);
974     g_string_append_c (gs, ')');
975     g_string_append_c (gs, '\n');
976   }
977
978   if (show_unicode)
979   {
980     serialize_line_no (line_no, gs);
981     serialize_unicode (buffer, gs);
982     g_string_append_c (gs, '\n');
983   }
984 }
985 void
986 format_options_t::serialize_message (unsigned int  line_no,
987                                      const char   *type,
988                                      const char   *msg,
989                                      GString      *gs)
990 {
991   serialize_line_no (line_no, gs);
992   g_string_append_printf (gs, "%s: %s", type, msg);
993   g_string_append_c (gs, '\n');
994 }
995 void
996 format_options_t::serialize_buffer_of_glyphs (hb_buffer_t  *buffer,
997                                               unsigned int  line_no,
998                                               const char   *text,
999                                               unsigned int  text_len,
1000                                               hb_font_t    *font,
1001                                               hb_buffer_serialize_format_t output_format,
1002                                               hb_buffer_serialize_flags_t format_flags,
1003                                               GString      *gs)
1004 {
1005   serialize_line_no (line_no, gs);
1006   serialize_glyphs (buffer, font, output_format, format_flags, gs);
1007   g_string_append_c (gs, '\n');
1008 }