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