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