Docs: don't use option tags
[platform/upstream/glib.git] / glib / goption.c
1 /* goption.c - Option parser
2  *
3  *  Copyright (C) 1999, 2003 Red Hat Software
4  *  Copyright (C) 2004       Anders Carlsson <andersca@gnome.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Library General Public
8  * License as published by the Free Software Foundation; either
9  * version 2 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Library General Public License for more details.
15  *
16  * You should have received a copy of the GNU Library General Public
17  * License along with this library; if not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * SECTION:option
22  * @Short_description: parses commandline options
23  * @Title: Commandline option parser
24  *
25  * The GOption commandline parser is intended to be a simpler replacement
26  * for the popt library. It supports short and long commandline options,
27  * as shown in the following example:
28  *
29  * <literal>testtreemodel -r 1 --max-size 20 --rand --display=:1.0 -vb -- file1 file2</literal>
30  *
31  * The example demonstrates a number of features of the GOption
32  * commandline parser:
33  *
34  * - Options can be single letters, prefixed by a single dash.
35  *
36  * - Multiple short options can be grouped behind a single dash.
37  *
38  * - Long options are prefixed by two consecutive dashes.
39  *
40  * - Options can have an extra argument, which can be a number, a string or
41  *   a filename. For long options, the extra argument can be appended with
42  *   an equals sign after the option name, which is useful if the extra
43  *   argument starts with a dash, which would otherwise cause it to be
44  *   interpreted as another option.
45  *
46  * - Non-option arguments are returned to the application as rest arguments.
47  *
48  * - An argument consisting solely of two dashes turns off further parsing,
49  *   any remaining arguments (even those starting with a dash) are returned
50  *   to the application as rest arguments.
51  *
52  * Another important feature of GOption is that it can automatically
53  * generate nicely formatted help output. Unless it is explicitly turned
54  * off with g_option_context_set_help_enabled(), GOption will recognize
55  * the `--help`, `-?`, `--help-all` and
56  * `--help-`<replaceable>groupname</replaceable> options
57  * (where <replaceable>groupname</replaceable> is the name of a
58  * #GOptionGroup) and write a text similar to the one shown in the
59  * following example to stdout.
60  *
61  * |[
62  * Usage:
63  *   testtreemodel [OPTION...] - test tree model performance
64  *  
65  * Help Options:
66  *   -h, --help               Show help options
67  *   --help-all               Show all help options
68  *   --help-gtk               Show GTK+ Options
69  *  
70  * Application Options:
71  *   -r, --repeats=N          Average over N repetitions
72  *   -m, --max-size=M         Test up to 2^M items
73  *   --display=DISPLAY        X display to use
74  *   -v, --verbose            Be verbose
75  *   -b, --beep               Beep when done
76  *   --rand                   Randomize the data
77  * ]|
78  *
79  * GOption groups options in #GOptionGroups, which makes it easy to
80  * incorporate options from multiple sources. The intended use for this is
81  * to let applications collect option groups from the libraries it uses,
82  * add them to their #GOptionContext, and parse all options by a single call
83  * to g_option_context_parse(). See gtk_get_option_group() for an example.
84  *
85  * If an option is declared to be of type string or filename, GOption takes
86  * care of converting it to the right encoding; strings are returned in
87  * UTF-8, filenames are returned in the GLib filename encoding. Note that
88  * this only works if setlocale() has been called before
89  * g_option_context_parse().
90  *
91  * Here is a complete example of setting up GOption to parse the example
92  * commandline above and produce the example help output.
93  * |[<!-- language="C" --> 
94  * static gint repeats = 2;
95  * static gint max_size = 8;
96  * static gboolean verbose = FALSE;
97  * static gboolean beep = FALSE;
98  * static gboolean randomize = FALSE;
99  *
100  * static GOptionEntry entries[] =
101  * {
102  *   { "repeats", 'r', 0, G_OPTION_ARG_INT, &repeats, "Average over N repetitions", "N" },
103  *   { "max-size", 'm', 0, G_OPTION_ARG_INT, &max_size, "Test up to 2^M items", "M" },
104  *   { "verbose", 'v', 0, G_OPTION_ARG_NONE, &verbose, "Be verbose", NULL },
105  *   { "beep", 'b', 0, G_OPTION_ARG_NONE, &beep, "Beep when done", NULL },
106  *   { "rand", 0, 0, G_OPTION_ARG_NONE, &randomize, "Randomize the data", NULL },
107  *   { NULL }
108  * };
109  *
110  * int
111  * main (int argc, char *argv[])
112  * {
113  *   GError *error = NULL;
114  *   GOptionContext *context;
115  *
116  *   context = g_option_context_new ("- test tree model performance");
117  *   g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);
118  *   g_option_context_add_group (context, gtk_get_option_group (TRUE));
119  *   if (!g_option_context_parse (context, &argc, &argv, &error))
120  *     {
121  *       g_print ("option parsing failed: %s\n", error->message);
122  *       exit (1);
123  *     }
124  *
125  *   /&ast; ... &ast;/
126  *
127  * }
128  * ]|
129  *
130  * On UNIX systems, the argv that is passed to main() has no particular
131  * encoding, even to the extent that different parts of it may have
132  * different encodings.  In general, normal arguments and flags will be
133  * in the current locale and filenames should be considered to be opaque
134  * byte strings.  Proper use of %G_OPTION_ARG_FILENAME vs
135  * %G_OPTION_ARG_STRING is therefore important.
136  *
137  * Note that on Windows, filenames do have an encoding, but using
138  * #GOptionContext with the argv as passed to main() will result in a
139  * program that can only accept commandline arguments with characters
140  * from the system codepage.  This can cause problems when attempting to
141  * deal with filenames containing Unicode characters that fall outside
142  * of the codepage.
143  *
144  * A solution to this is to use g_win32_get_command_line() and
145  * g_option_context_parse_strv() which will properly handle full Unicode
146  * filenames.  If you are using #GApplication, this is done
147  * automatically for you.
148  *
149  * The following example shows how you can use #GOptionContext directly
150  * in order to correctly deal with Unicode filenames on Windows:
151  *
152  * |[<!-- language="C" --> 
153  * int
154  * main (int argc, char **argv)
155  * {
156  *   GError *error = NULL;
157  *   GOptionContext *context;
158  *   gchar **args;
159  *
160  * #ifdef G_OS_WIN32
161  *   args = g_win32_get_command_line ();
162  * #else
163  *   args = g_strdupv (argv);
164  * #endif
165  *
166  *   /&ast; ... setup context ... &ast;/
167  *
168  *   if (!g_option_context_parse_strv (context, &args, &error))
169  *     {
170  *       /&ast; ... error ... &ast;/
171  *     }
172  *
173  *   /&ast; ... &ast;/
174  *
175  *   g_strfreev (args);
176  *
177  *   /&ast; ... &ast;/
178  * }
179  * ]|
180  */
181
182 #include "config.h"
183
184 #include <string.h>
185 #include <stdlib.h>
186 #include <stdio.h>
187 #include <errno.h>
188
189 #if defined __OpenBSD__
190 #include <sys/types.h>
191 #include <unistd.h>
192 #include <sys/param.h>
193 #include <sys/sysctl.h>
194 #endif
195
196 #include "goption.h"
197
198 #include "gprintf.h"
199 #include "glibintl.h"
200
201 #define TRANSLATE(group, str) (((group)->translate_func ? (* (group)->translate_func) ((str), (group)->translate_data) : (str)))
202
203 #define NO_ARG(entry) ((entry)->arg == G_OPTION_ARG_NONE ||       \
204                        ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
205                         ((entry)->flags & G_OPTION_FLAG_NO_ARG)))
206
207 #define OPTIONAL_ARG(entry) ((entry)->arg == G_OPTION_ARG_CALLBACK &&  \
208                        (entry)->flags & G_OPTION_FLAG_OPTIONAL_ARG)
209
210 typedef struct
211 {
212   GOptionArg arg_type;
213   gpointer arg_data;
214   union
215   {
216     gboolean bool;
217     gint integer;
218     gchar *str;
219     gchar **array;
220     gdouble dbl;
221     gint64 int64;
222   } prev;
223   union
224   {
225     gchar *str;
226     struct
227     {
228       gint len;
229       gchar **data;
230     } array;
231   } allocated;
232 } Change;
233
234 typedef struct
235 {
236   gchar **ptr;
237   gchar *value;
238 } PendingNull;
239
240 struct _GOptionContext
241 {
242   GList           *groups;
243
244   gchar           *parameter_string;
245   gchar           *summary;
246   gchar           *description;
247
248   GTranslateFunc   translate_func;
249   GDestroyNotify   translate_notify;
250   gpointer         translate_data;
251
252   guint            help_enabled   : 1;
253   guint            ignore_unknown : 1;
254   guint            strv_mode      : 1;
255
256   GOptionGroup    *main_group;
257
258   /* We keep a list of change so we can revert them */
259   GList           *changes;
260
261   /* We also keep track of all argv elements
262    * that should be NULLed or modified.
263    */
264   GList           *pending_nulls;
265 };
266
267 struct _GOptionGroup
268 {
269   gchar           *name;
270   gchar           *description;
271   gchar           *help_description;
272
273   GDestroyNotify   destroy_notify;
274   gpointer         user_data;
275
276   GTranslateFunc   translate_func;
277   GDestroyNotify   translate_notify;
278   gpointer         translate_data;
279
280   GOptionEntry    *entries;
281   gint             n_entries;
282
283   GOptionParseFunc pre_parse_func;
284   GOptionParseFunc post_parse_func;
285   GOptionErrorFunc error_func;
286 };
287
288 static void free_changes_list (GOptionContext *context,
289                                gboolean        revert);
290 static void free_pending_nulls (GOptionContext *context,
291                                 gboolean        perform_nulls);
292
293
294 static int
295 _g_unichar_get_width (gunichar c)
296 {
297   if (G_UNLIKELY (g_unichar_iszerowidth (c)))
298     return 0;
299
300   /* we ignore the fact that we should call g_unichar_iswide_cjk() under
301    * some locales (legacy East Asian ones) */
302   if (g_unichar_iswide (c))
303     return 2;
304
305   return 1;
306 }
307
308 static glong
309 _g_utf8_strwidth (const gchar *p)
310 {
311   glong len = 0;
312   g_return_val_if_fail (p != NULL, 0);
313
314   while (*p)
315     {
316       len += _g_unichar_get_width (g_utf8_get_char (p));
317       p = g_utf8_next_char (p);
318     }
319
320   return len;
321 }
322
323 G_DEFINE_QUARK (g-option-context-error-quark, g_option_error)
324
325 /**
326  * g_option_context_new:
327  * @parameter_string: (allow-none): a string which is displayed in
328  *    the first line of `--help` output, after the
329  *    usage summary
330  *    <literal><replaceable>programname</replaceable> [OPTION...]</literal>
331  *
332  * Creates a new option context.
333  *
334  * The @parameter_string can serve multiple purposes. It can be used
335  * to add descriptions for "rest" arguments, which are not parsed by
336  * the #GOptionContext, typically something like "FILES" or
337  * "FILE1 FILE2...". If you are using #G_OPTION_REMAINING for
338  * collecting "rest" arguments, GLib handles this automatically by
339  * using the @arg_description of the corresponding #GOptionEntry in
340  * the usage summary.
341  *
342  * Another usage is to give a short summary of the program
343  * functionality, like " - frob the strings", which will be displayed
344  * in the same line as the usage. For a longer description of the
345  * program functionality that should be displayed as a paragraph
346  * below the usage line, use g_option_context_set_summary().
347  *
348  * Note that the @parameter_string is translated using the
349  * function set with g_option_context_set_translate_func(), so
350  * it should normally be passed untranslated.
351  *
352  * Returns: a newly created #GOptionContext, which must be
353  *    freed with g_option_context_free() after use.
354  *
355  * Since: 2.6
356  */
357 GOptionContext *
358 g_option_context_new (const gchar *parameter_string)
359
360 {
361   GOptionContext *context;
362
363   context = g_new0 (GOptionContext, 1);
364
365   context->parameter_string = g_strdup (parameter_string);
366   context->help_enabled = TRUE;
367   context->ignore_unknown = FALSE;
368
369   return context;
370 }
371
372 /**
373  * g_option_context_free:
374  * @context: a #GOptionContext
375  *
376  * Frees context and all the groups which have been
377  * added to it.
378  *
379  * Please note that parsed arguments need to be freed separately (see
380  * #GOptionEntry).
381  *
382  * Since: 2.6
383  */
384 void g_option_context_free (GOptionContext *context)
385 {
386   g_return_if_fail (context != NULL);
387
388   g_list_free_full (context->groups, (GDestroyNotify) g_option_group_free);
389
390   if (context->main_group)
391     g_option_group_free (context->main_group);
392
393   free_changes_list (context, FALSE);
394   free_pending_nulls (context, FALSE);
395
396   g_free (context->parameter_string);
397   g_free (context->summary);
398   g_free (context->description);
399
400   if (context->translate_notify)
401     (* context->translate_notify) (context->translate_data);
402
403   g_free (context);
404 }
405
406
407 /**
408  * g_option_context_set_help_enabled:
409  * @context: a #GOptionContext
410  * @help_enabled: %TRUE to enable `--help`, %FALSE to disable it
411  *
412  * Enables or disables automatic generation of `--help`
413  * output. By default, g_option_context_parse() recognizes
414  * `--help`, `-h`, `-?`, `--help-all`
415  * and `--help-`<replaceable>groupname</replaceable> and creates
416  * suitable output to stdout.
417  *
418  * Since: 2.6
419  */
420 void g_option_context_set_help_enabled (GOptionContext *context,
421                                         gboolean        help_enabled)
422
423 {
424   g_return_if_fail (context != NULL);
425
426   context->help_enabled = help_enabled;
427 }
428
429 /**
430  * g_option_context_get_help_enabled:
431  * @context: a #GOptionContext
432  *
433  * Returns whether automatic `--help` generation
434  * is turned on for @context. See g_option_context_set_help_enabled().
435  *
436  * Returns: %TRUE if automatic help generation is turned on.
437  *
438  * Since: 2.6
439  */
440 gboolean
441 g_option_context_get_help_enabled (GOptionContext *context)
442 {
443   g_return_val_if_fail (context != NULL, FALSE);
444
445   return context->help_enabled;
446 }
447
448 /**
449  * g_option_context_set_ignore_unknown_options:
450  * @context: a #GOptionContext
451  * @ignore_unknown: %TRUE to ignore unknown options, %FALSE to produce
452  *    an error when unknown options are met
453  *
454  * Sets whether to ignore unknown options or not. If an argument is
455  * ignored, it is left in the @argv array after parsing. By default,
456  * g_option_context_parse() treats unknown options as error.
457  *
458  * This setting does not affect non-option arguments (i.e. arguments
459  * which don't start with a dash). But note that GOption cannot reliably
460  * determine whether a non-option belongs to a preceding unknown option.
461  *
462  * Since: 2.6
463  **/
464 void
465 g_option_context_set_ignore_unknown_options (GOptionContext *context,
466                                              gboolean        ignore_unknown)
467 {
468   g_return_if_fail (context != NULL);
469
470   context->ignore_unknown = ignore_unknown;
471 }
472
473 /**
474  * g_option_context_get_ignore_unknown_options:
475  * @context: a #GOptionContext
476  *
477  * Returns whether unknown options are ignored or not. See
478  * g_option_context_set_ignore_unknown_options().
479  *
480  * Returns: %TRUE if unknown options are ignored.
481  *
482  * Since: 2.6
483  **/
484 gboolean
485 g_option_context_get_ignore_unknown_options (GOptionContext *context)
486 {
487   g_return_val_if_fail (context != NULL, FALSE);
488
489   return context->ignore_unknown;
490 }
491
492 /**
493  * g_option_context_add_group:
494  * @context: a #GOptionContext
495  * @group: the group to add
496  *
497  * Adds a #GOptionGroup to the @context, so that parsing with @context
498  * will recognize the options in the group. Note that the group will
499  * be freed together with the context when g_option_context_free() is
500  * called, so you must not free the group yourself after adding it
501  * to a context.
502  *
503  * Since: 2.6
504  **/
505 void
506 g_option_context_add_group (GOptionContext *context,
507                             GOptionGroup   *group)
508 {
509   GList *list;
510
511   g_return_if_fail (context != NULL);
512   g_return_if_fail (group != NULL);
513   g_return_if_fail (group->name != NULL);
514   g_return_if_fail (group->description != NULL);
515   g_return_if_fail (group->help_description != NULL);
516
517   for (list = context->groups; list; list = list->next)
518     {
519       GOptionGroup *g = (GOptionGroup *)list->data;
520
521       if ((group->name == NULL && g->name == NULL) ||
522           (group->name && g->name && strcmp (group->name, g->name) == 0))
523         g_warning ("A group named \"%s\" is already part of this GOptionContext",
524                    group->name);
525     }
526
527   context->groups = g_list_append (context->groups, group);
528 }
529
530 /**
531  * g_option_context_set_main_group:
532  * @context: a #GOptionContext
533  * @group: the group to set as main group
534  *
535  * Sets a #GOptionGroup as main group of the @context.
536  * This has the same effect as calling g_option_context_add_group(),
537  * the only difference is that the options in the main group are
538  * treated differently when generating `--help` output.
539  *
540  * Since: 2.6
541  **/
542 void
543 g_option_context_set_main_group (GOptionContext *context,
544                                  GOptionGroup   *group)
545 {
546   g_return_if_fail (context != NULL);
547   g_return_if_fail (group != NULL);
548
549   if (context->main_group)
550     {
551       g_warning ("This GOptionContext already has a main group");
552
553       return;
554     }
555
556   context->main_group = group;
557 }
558
559 /**
560  * g_option_context_get_main_group:
561  * @context: a #GOptionContext
562  *
563  * Returns a pointer to the main group of @context.
564  *
565  * Return value: the main group of @context, or %NULL if @context doesn't
566  *  have a main group. Note that group belongs to @context and should
567  *  not be modified or freed.
568  *
569  * Since: 2.6
570  **/
571 GOptionGroup *
572 g_option_context_get_main_group (GOptionContext *context)
573 {
574   g_return_val_if_fail (context != NULL, NULL);
575
576   return context->main_group;
577 }
578
579 /**
580  * g_option_context_add_main_entries:
581  * @context: a #GOptionContext
582  * @entries: a %NULL-terminated array of #GOptionEntrys
583  * @translation_domain: (allow-none): a translation domain to use for translating
584  *    the `--help` output for the options in @entries
585  *    with gettext(), or %NULL
586  *
587  * A convenience function which creates a main group if it doesn't
588  * exist, adds the @entries to it and sets the translation domain.
589  *
590  * Since: 2.6
591  **/
592 void
593 g_option_context_add_main_entries (GOptionContext      *context,
594                                    const GOptionEntry  *entries,
595                                    const gchar         *translation_domain)
596 {
597   g_return_if_fail (entries != NULL);
598
599   if (!context->main_group)
600     context->main_group = g_option_group_new (NULL, NULL, NULL, NULL, NULL);
601
602   g_option_group_add_entries (context->main_group, entries);
603   g_option_group_set_translation_domain (context->main_group, translation_domain);
604 }
605
606 static gint
607 calculate_max_length (GOptionGroup *group,
608                       GHashTable   *aliases)
609 {
610   GOptionEntry *entry;
611   gint i, len, max_length;
612   const gchar *long_name;
613
614   max_length = 0;
615
616   for (i = 0; i < group->n_entries; i++)
617     {
618       entry = &group->entries[i];
619
620       if (entry->flags & G_OPTION_FLAG_HIDDEN)
621         continue;
622
623       long_name = g_hash_table_lookup (aliases, &entry->long_name);
624       if (!long_name)
625         long_name = entry->long_name;
626       len = _g_utf8_strwidth (long_name);
627
628       if (entry->short_name)
629         len += 4;
630
631       if (!NO_ARG (entry) && entry->arg_description)
632         len += 1 + _g_utf8_strwidth (TRANSLATE (group, entry->arg_description));
633
634       max_length = MAX (max_length, len);
635     }
636
637   return max_length;
638 }
639
640 static void
641 print_entry (GOptionGroup       *group,
642              gint                max_length,
643              const GOptionEntry *entry,
644              GString            *string,
645              GHashTable         *aliases)
646 {
647   GString *str;
648   const gchar *long_name;
649
650   if (entry->flags & G_OPTION_FLAG_HIDDEN)
651     return;
652
653   if (entry->long_name[0] == 0)
654     return;
655
656   long_name = g_hash_table_lookup (aliases, &entry->long_name);
657   if (!long_name)
658     long_name = entry->long_name;
659
660   str = g_string_new (NULL);
661
662   if (entry->short_name)
663     g_string_append_printf (str, "  -%c, --%s", entry->short_name, long_name);
664   else
665     g_string_append_printf (str, "  --%s", long_name);
666
667   if (entry->arg_description)
668     g_string_append_printf (str, "=%s", TRANSLATE (group, entry->arg_description));
669
670   g_string_append_printf (string, "%s%*s %s\n", str->str,
671                           (int) (max_length + 4 - _g_utf8_strwidth (str->str)), "",
672                           entry->description ? TRANSLATE (group, entry->description) : "");
673   g_string_free (str, TRUE);
674 }
675
676 static gboolean
677 group_has_visible_entries (GOptionContext *context,
678                            GOptionGroup *group,
679                            gboolean      main_entries)
680 {
681   GOptionFlags reject_filter = G_OPTION_FLAG_HIDDEN;
682   GOptionEntry *entry;
683   gint i, l;
684   gboolean main_group = group == context->main_group;
685
686   if (!main_entries)
687     reject_filter |= G_OPTION_FLAG_IN_MAIN;
688
689   for (i = 0, l = (group ? group->n_entries : 0); i < l; i++)
690     {
691       entry = &group->entries[i];
692
693       if (main_entries && !main_group && !(entry->flags & G_OPTION_FLAG_IN_MAIN))
694         continue;
695       if (entry->long_name[0] == 0) /* ignore rest entry */
696         continue;
697       if (!(entry->flags & reject_filter))
698         return TRUE;
699     }
700
701   return FALSE;
702 }
703
704 static gboolean
705 group_list_has_visible_entries (GOptionContext *context,
706                                 GList          *group_list,
707                                 gboolean       main_entries)
708 {
709   while (group_list)
710     {
711       if (group_has_visible_entries (context, group_list->data, main_entries))
712         return TRUE;
713
714       group_list = group_list->next;
715     }
716
717   return FALSE;
718 }
719
720 static gboolean
721 context_has_h_entry (GOptionContext *context)
722 {
723   gsize i;
724   GList *list;
725
726   if (context->main_group)
727     {
728       for (i = 0; i < context->main_group->n_entries; i++)
729         {
730           if (context->main_group->entries[i].short_name == 'h')
731             return TRUE;
732         }
733     }
734
735   for (list = context->groups; list != NULL; list = g_list_next (list))
736     {
737      GOptionGroup *group;
738
739       group = (GOptionGroup*)list->data;
740       for (i = 0; i < group->n_entries; i++)
741         {
742           if (group->entries[i].short_name == 'h')
743             return TRUE;
744         }
745     }
746   return FALSE;
747 }
748
749 /**
750  * g_option_context_get_help:
751  * @context: a #GOptionContext
752  * @main_help: if %TRUE, only include the main group
753  * @group: (allow-none): the #GOptionGroup to create help for, or %NULL
754  *
755  * Returns a formatted, translated help text for the given context.
756  * To obtain the text produced by `--help`, call
757  * <literal>g_option_context_get_help (context, TRUE, NULL)</literal>.
758  * To obtain the text produced by `--help-all`, call
759  * <literal>g_option_context_get_help (context, FALSE, NULL)</literal>.
760  * To obtain the help text for an option group, call
761  * <literal>g_option_context_get_help (context, FALSE, group)</literal>.
762  *
763  * Returns: A newly allocated string containing the help text
764  *
765  * Since: 2.14
766  */
767 gchar *
768 g_option_context_get_help (GOptionContext *context,
769                            gboolean        main_help,
770                            GOptionGroup   *group)
771 {
772   GList *list;
773   gint max_length = 0, len;
774   gint i;
775   GOptionEntry *entry;
776   GHashTable *shadow_map;
777   GHashTable *aliases;
778   gboolean seen[256];
779   const gchar *rest_description;
780   GString *string;
781   guchar token;
782
783   string = g_string_sized_new (1024);
784
785   rest_description = NULL;
786   if (context->main_group)
787     {
788
789       for (i = 0; i < context->main_group->n_entries; i++)
790         {
791           entry = &context->main_group->entries[i];
792           if (entry->long_name[0] == 0)
793             {
794               rest_description = TRANSLATE (context->main_group, entry->arg_description);
795               break;
796             }
797         }
798     }
799
800   g_string_append_printf (string, "%s\n  %s %s",
801                           _("Usage:"), g_get_prgname(), _("[OPTION...]"));
802
803   if (rest_description)
804     {
805       g_string_append (string, " ");
806       g_string_append (string, rest_description);
807     }
808
809   if (context->parameter_string)
810     {
811       g_string_append (string, " ");
812       g_string_append (string, TRANSLATE (context, context->parameter_string));
813     }
814
815   g_string_append (string, "\n\n");
816
817   if (context->summary)
818     {
819       g_string_append (string, TRANSLATE (context, context->summary));
820       g_string_append (string, "\n\n");
821     }
822
823   memset (seen, 0, sizeof (gboolean) * 256);
824   shadow_map = g_hash_table_new (g_str_hash, g_str_equal);
825   aliases = g_hash_table_new_full (NULL, NULL, NULL, g_free);
826
827   if (context->main_group)
828     {
829       for (i = 0; i < context->main_group->n_entries; i++)
830         {
831           entry = &context->main_group->entries[i];
832           g_hash_table_insert (shadow_map,
833                                (gpointer)entry->long_name,
834                                entry);
835
836           if (seen[(guchar)entry->short_name])
837             entry->short_name = 0;
838           else
839             seen[(guchar)entry->short_name] = TRUE;
840         }
841     }
842
843   list = context->groups;
844   while (list != NULL)
845     {
846       GOptionGroup *g = list->data;
847       for (i = 0; i < g->n_entries; i++)
848         {
849           entry = &g->entries[i];
850           if (g_hash_table_lookup (shadow_map, entry->long_name) &&
851               !(entry->flags & G_OPTION_FLAG_NOALIAS))
852             {
853               g_hash_table_insert (aliases, &entry->long_name,
854                                    g_strdup_printf ("%s-%s", g->name, entry->long_name));
855             }
856           else
857             g_hash_table_insert (shadow_map, (gpointer)entry->long_name, entry);
858
859           if (seen[(guchar)entry->short_name] &&
860               !(entry->flags & G_OPTION_FLAG_NOALIAS))
861             entry->short_name = 0;
862           else
863             seen[(guchar)entry->short_name] = TRUE;
864         }
865       list = list->next;
866     }
867
868   g_hash_table_destroy (shadow_map);
869
870   list = context->groups;
871
872   if (context->help_enabled)
873     {
874       max_length = _g_utf8_strwidth ("-?, --help");
875
876       if (list)
877         {
878           len = _g_utf8_strwidth ("--help-all");
879           max_length = MAX (max_length, len);
880         }
881     }
882
883   if (context->main_group)
884     {
885       len = calculate_max_length (context->main_group, aliases);
886       max_length = MAX (max_length, len);
887     }
888
889   while (list != NULL)
890     {
891       GOptionGroup *g = list->data;
892
893       if (context->help_enabled)
894         {
895           /* First, we check the --help-<groupname> options */
896           len = _g_utf8_strwidth ("--help-") + _g_utf8_strwidth (g->name);
897           max_length = MAX (max_length, len);
898         }
899
900       /* Then we go through the entries */
901       len = calculate_max_length (g, aliases);
902       max_length = MAX (max_length, len);
903
904       list = list->next;
905     }
906
907   /* Add a bit of padding */
908   max_length += 4;
909
910   if (!group && context->help_enabled)
911     {
912       list = context->groups;
913
914       token = context_has_h_entry (context) ? '?' : 'h';
915
916       g_string_append_printf (string, "%s\n  -%c, --%-*s %s\n",
917                               _("Help Options:"), token, max_length - 4, "help",
918                               _("Show help options"));
919
920       /* We only want --help-all when there are groups */
921       if (list)
922         g_string_append_printf (string, "  --%-*s %s\n",
923                                 max_length, "help-all",
924                                 _("Show all help options"));
925
926       while (list)
927         {
928           GOptionGroup *g = list->data;
929
930           if (group_has_visible_entries (context, g, FALSE))
931             g_string_append_printf (string, "  --help-%-*s %s\n",
932                                     max_length - 5, g->name,
933                                     TRANSLATE (g, g->help_description));
934
935           list = list->next;
936         }
937
938       g_string_append (string, "\n");
939     }
940
941   if (group)
942     {
943       /* Print a certain group */
944
945       if (group_has_visible_entries (context, group, FALSE))
946         {
947           g_string_append (string, TRANSLATE (group, group->description));
948           g_string_append (string, "\n");
949           for (i = 0; i < group->n_entries; i++)
950             print_entry (group, max_length, &group->entries[i], string, aliases);
951           g_string_append (string, "\n");
952         }
953     }
954   else if (!main_help)
955     {
956       /* Print all groups */
957
958       list = context->groups;
959
960       while (list)
961         {
962           GOptionGroup *g = list->data;
963
964           if (group_has_visible_entries (context, g, FALSE))
965             {
966               g_string_append (string, g->description);
967               g_string_append (string, "\n");
968               for (i = 0; i < g->n_entries; i++)
969                 if (!(g->entries[i].flags & G_OPTION_FLAG_IN_MAIN))
970                   print_entry (g, max_length, &g->entries[i], string, aliases);
971
972               g_string_append (string, "\n");
973             }
974
975           list = list->next;
976         }
977     }
978
979   /* Print application options if --help or --help-all has been specified */
980   if ((main_help || !group) &&
981       (group_has_visible_entries (context, context->main_group, TRUE) ||
982        group_list_has_visible_entries (context, context->groups, TRUE)))
983     {
984       list = context->groups;
985
986       g_string_append (string,  _("Application Options:"));
987       g_string_append (string, "\n");
988       if (context->main_group)
989         for (i = 0; i < context->main_group->n_entries; i++)
990           print_entry (context->main_group, max_length,
991                        &context->main_group->entries[i], string, aliases);
992
993       while (list != NULL)
994         {
995           GOptionGroup *g = list->data;
996
997           /* Print main entries from other groups */
998           for (i = 0; i < g->n_entries; i++)
999             if (g->entries[i].flags & G_OPTION_FLAG_IN_MAIN)
1000               print_entry (g, max_length, &g->entries[i], string, aliases);
1001
1002           list = list->next;
1003         }
1004
1005       g_string_append (string, "\n");
1006     }
1007
1008   if (context->description)
1009     {
1010       g_string_append (string, TRANSLATE (context, context->description));
1011       g_string_append (string, "\n");
1012     }
1013
1014   g_hash_table_destroy (aliases);
1015
1016   return g_string_free (string, FALSE);
1017 }
1018
1019 G_GNUC_NORETURN
1020 static void
1021 print_help (GOptionContext *context,
1022             gboolean        main_help,
1023             GOptionGroup   *group)
1024 {
1025   gchar *help;
1026
1027   help = g_option_context_get_help (context, main_help, group);
1028   g_print ("%s", help);
1029   g_free (help);
1030
1031   exit (0);
1032 }
1033
1034 static gboolean
1035 parse_int (const gchar *arg_name,
1036            const gchar *arg,
1037            gint        *result,
1038            GError     **error)
1039 {
1040   gchar *end;
1041   glong tmp;
1042
1043   errno = 0;
1044   tmp = strtol (arg, &end, 0);
1045
1046   if (*arg == '\0' || *end != '\0')
1047     {
1048       g_set_error (error,
1049                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1050                    _("Cannot parse integer value '%s' for %s"),
1051                    arg, arg_name);
1052       return FALSE;
1053     }
1054
1055   *result = tmp;
1056   if (*result != tmp || errno == ERANGE)
1057     {
1058       g_set_error (error,
1059                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1060                    _("Integer value '%s' for %s out of range"),
1061                    arg, arg_name);
1062       return FALSE;
1063     }
1064
1065   return TRUE;
1066 }
1067
1068
1069 static gboolean
1070 parse_double (const gchar *arg_name,
1071            const gchar *arg,
1072            gdouble        *result,
1073            GError     **error)
1074 {
1075   gchar *end;
1076   gdouble tmp;
1077
1078   errno = 0;
1079   tmp = g_strtod (arg, &end);
1080
1081   if (*arg == '\0' || *end != '\0')
1082     {
1083       g_set_error (error,
1084                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1085                    _("Cannot parse double value '%s' for %s"),
1086                    arg, arg_name);
1087       return FALSE;
1088     }
1089   if (errno == ERANGE)
1090     {
1091       g_set_error (error,
1092                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1093                    _("Double value '%s' for %s out of range"),
1094                    arg, arg_name);
1095       return FALSE;
1096     }
1097
1098   *result = tmp;
1099
1100   return TRUE;
1101 }
1102
1103
1104 static gboolean
1105 parse_int64 (const gchar *arg_name,
1106              const gchar *arg,
1107              gint64      *result,
1108              GError     **error)
1109 {
1110   gchar *end;
1111   gint64 tmp;
1112
1113   errno = 0;
1114   tmp = g_ascii_strtoll (arg, &end, 0);
1115
1116   if (*arg == '\0' || *end != '\0')
1117     {
1118       g_set_error (error,
1119                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1120                    _("Cannot parse integer value '%s' for %s"),
1121                    arg, arg_name);
1122       return FALSE;
1123     }
1124   if (errno == ERANGE)
1125     {
1126       g_set_error (error,
1127                    G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1128                    _("Integer value '%s' for %s out of range"),
1129                    arg, arg_name);
1130       return FALSE;
1131     }
1132
1133   *result = tmp;
1134
1135   return TRUE;
1136 }
1137
1138
1139 static Change *
1140 get_change (GOptionContext *context,
1141             GOptionArg      arg_type,
1142             gpointer        arg_data)
1143 {
1144   GList *list;
1145   Change *change = NULL;
1146
1147   for (list = context->changes; list != NULL; list = list->next)
1148     {
1149       change = list->data;
1150
1151       if (change->arg_data == arg_data)
1152         goto found;
1153     }
1154
1155   change = g_new0 (Change, 1);
1156   change->arg_type = arg_type;
1157   change->arg_data = arg_data;
1158
1159   context->changes = g_list_prepend (context->changes, change);
1160
1161  found:
1162
1163   return change;
1164 }
1165
1166 static void
1167 add_pending_null (GOptionContext *context,
1168                   gchar         **ptr,
1169                   gchar          *value)
1170 {
1171   PendingNull *n;
1172
1173   n = g_new0 (PendingNull, 1);
1174   n->ptr = ptr;
1175   n->value = value;
1176
1177   context->pending_nulls = g_list_prepend (context->pending_nulls, n);
1178 }
1179
1180 static gboolean
1181 parse_arg (GOptionContext *context,
1182            GOptionGroup   *group,
1183            GOptionEntry   *entry,
1184            const gchar    *value,
1185            const gchar    *option_name,
1186            GError        **error)
1187
1188 {
1189   Change *change;
1190
1191   g_assert (value || OPTIONAL_ARG (entry) || NO_ARG (entry));
1192
1193   switch (entry->arg)
1194     {
1195     case G_OPTION_ARG_NONE:
1196       {
1197         change = get_change (context, G_OPTION_ARG_NONE,
1198                              entry->arg_data);
1199
1200         *(gboolean *)entry->arg_data = !(entry->flags & G_OPTION_FLAG_REVERSE);
1201         break;
1202       }
1203     case G_OPTION_ARG_STRING:
1204       {
1205         gchar *data;
1206
1207 #ifdef G_OS_WIN32
1208         if (!context->strv_mode)
1209           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1210         else
1211           data = g_strdup (value);
1212 #else
1213         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1214 #endif
1215
1216         if (!data)
1217           return FALSE;
1218
1219         change = get_change (context, G_OPTION_ARG_STRING,
1220                              entry->arg_data);
1221         g_free (change->allocated.str);
1222
1223         change->prev.str = *(gchar **)entry->arg_data;
1224         change->allocated.str = data;
1225
1226         *(gchar **)entry->arg_data = data;
1227         break;
1228       }
1229     case G_OPTION_ARG_STRING_ARRAY:
1230       {
1231         gchar *data;
1232
1233 #ifdef G_OS_WIN32
1234         if (!context->strv_mode)
1235           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1236         else
1237           data = g_strdup (value);
1238 #else
1239         data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1240 #endif
1241
1242         if (!data)
1243           return FALSE;
1244
1245         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1246                              entry->arg_data);
1247
1248         if (change->allocated.array.len == 0)
1249           {
1250             change->prev.array = *(gchar ***)entry->arg_data;
1251             change->allocated.array.data = g_new (gchar *, 2);
1252           }
1253         else
1254           change->allocated.array.data =
1255             g_renew (gchar *, change->allocated.array.data,
1256                      change->allocated.array.len + 2);
1257
1258         change->allocated.array.data[change->allocated.array.len] = data;
1259         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1260
1261         change->allocated.array.len ++;
1262
1263         *(gchar ***)entry->arg_data = change->allocated.array.data;
1264
1265         break;
1266       }
1267
1268     case G_OPTION_ARG_FILENAME:
1269       {
1270         gchar *data;
1271
1272 #ifdef G_OS_WIN32
1273         if (!context->strv_mode)
1274           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1275         else
1276           data = g_strdup (value);
1277
1278         if (!data)
1279           return FALSE;
1280 #else
1281         data = g_strdup (value);
1282 #endif
1283         change = get_change (context, G_OPTION_ARG_FILENAME,
1284                              entry->arg_data);
1285         g_free (change->allocated.str);
1286
1287         change->prev.str = *(gchar **)entry->arg_data;
1288         change->allocated.str = data;
1289
1290         *(gchar **)entry->arg_data = data;
1291         break;
1292       }
1293
1294     case G_OPTION_ARG_FILENAME_ARRAY:
1295       {
1296         gchar *data;
1297
1298 #ifdef G_OS_WIN32
1299         if (!context->strv_mode)
1300           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1301         else
1302           data = g_strdup (value);
1303
1304         if (!data)
1305           return FALSE;
1306 #else
1307         data = g_strdup (value);
1308 #endif
1309         change = get_change (context, G_OPTION_ARG_STRING_ARRAY,
1310                              entry->arg_data);
1311
1312         if (change->allocated.array.len == 0)
1313           {
1314             change->prev.array = *(gchar ***)entry->arg_data;
1315             change->allocated.array.data = g_new (gchar *, 2);
1316           }
1317         else
1318           change->allocated.array.data =
1319             g_renew (gchar *, change->allocated.array.data,
1320                      change->allocated.array.len + 2);
1321
1322         change->allocated.array.data[change->allocated.array.len] = data;
1323         change->allocated.array.data[change->allocated.array.len + 1] = NULL;
1324
1325         change->allocated.array.len ++;
1326
1327         *(gchar ***)entry->arg_data = change->allocated.array.data;
1328
1329         break;
1330       }
1331
1332     case G_OPTION_ARG_INT:
1333       {
1334         gint data;
1335
1336         if (!parse_int (option_name, value,
1337                         &data,
1338                         error))
1339           return FALSE;
1340
1341         change = get_change (context, G_OPTION_ARG_INT,
1342                              entry->arg_data);
1343         change->prev.integer = *(gint *)entry->arg_data;
1344         *(gint *)entry->arg_data = data;
1345         break;
1346       }
1347     case G_OPTION_ARG_CALLBACK:
1348       {
1349         gchar *data;
1350         gboolean retval;
1351
1352         if (!value && entry->flags & G_OPTION_FLAG_OPTIONAL_ARG)
1353           data = NULL;
1354         else if (entry->flags & G_OPTION_FLAG_NO_ARG)
1355           data = NULL;
1356         else if (entry->flags & G_OPTION_FLAG_FILENAME)
1357           {
1358 #ifdef G_OS_WIN32
1359             if (!context->strv_mode)
1360               data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1361             else
1362               data = g_strdup (value);
1363 #else
1364             data = g_strdup (value);
1365 #endif
1366           }
1367         else
1368           data = g_locale_to_utf8 (value, -1, NULL, NULL, error);
1369
1370         if (!(entry->flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG)) &&
1371             !data)
1372           return FALSE;
1373
1374         retval = (* (GOptionArgFunc) entry->arg_data) (option_name, data, group->user_data, error);
1375
1376         if (!retval && error != NULL && *error == NULL)
1377           g_set_error (error,
1378                        G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1379                        _("Error parsing option %s"), option_name);
1380
1381         g_free (data);
1382
1383         return retval;
1384
1385         break;
1386       }
1387     case G_OPTION_ARG_DOUBLE:
1388       {
1389         gdouble data;
1390
1391         if (!parse_double (option_name, value,
1392                         &data,
1393                         error))
1394           {
1395             return FALSE;
1396           }
1397
1398         change = get_change (context, G_OPTION_ARG_DOUBLE,
1399                              entry->arg_data);
1400         change->prev.dbl = *(gdouble *)entry->arg_data;
1401         *(gdouble *)entry->arg_data = data;
1402         break;
1403       }
1404     case G_OPTION_ARG_INT64:
1405       {
1406         gint64 data;
1407
1408         if (!parse_int64 (option_name, value,
1409                          &data,
1410                          error))
1411           {
1412             return FALSE;
1413           }
1414
1415         change = get_change (context, G_OPTION_ARG_INT64,
1416                              entry->arg_data);
1417         change->prev.int64 = *(gint64 *)entry->arg_data;
1418         *(gint64 *)entry->arg_data = data;
1419         break;
1420       }
1421     default:
1422       g_assert_not_reached ();
1423     }
1424
1425   return TRUE;
1426 }
1427
1428 static gboolean
1429 parse_short_option (GOptionContext *context,
1430                     GOptionGroup   *group,
1431                     gint            idx,
1432                     gint           *new_idx,
1433                     gchar           arg,
1434                     gint           *argc,
1435                     gchar        ***argv,
1436                     GError        **error,
1437                     gboolean       *parsed)
1438 {
1439   gint j;
1440
1441   for (j = 0; j < group->n_entries; j++)
1442     {
1443       if (arg == group->entries[j].short_name)
1444         {
1445           gchar *option_name;
1446           gchar *value = NULL;
1447
1448           option_name = g_strdup_printf ("-%c", group->entries[j].short_name);
1449
1450           if (NO_ARG (&group->entries[j]))
1451             value = NULL;
1452           else
1453             {
1454               if (*new_idx > idx)
1455                 {
1456                   g_set_error (error,
1457                                G_OPTION_ERROR, G_OPTION_ERROR_FAILED,
1458                                _("Error parsing option %s"), option_name);
1459                   g_free (option_name);
1460                   return FALSE;
1461                 }
1462
1463               if (idx < *argc - 1)
1464                 {
1465                   if (!OPTIONAL_ARG (&group->entries[j]))
1466                     {
1467                       value = (*argv)[idx + 1];
1468                       add_pending_null (context, &((*argv)[idx + 1]), NULL);
1469                       *new_idx = idx + 1;
1470                     }
1471                   else
1472                     {
1473                       if ((*argv)[idx + 1][0] == '-')
1474                         value = NULL;
1475                       else
1476                         {
1477                           value = (*argv)[idx + 1];
1478                           add_pending_null (context, &((*argv)[idx + 1]), NULL);
1479                           *new_idx = idx + 1;
1480                         }
1481                     }
1482                 }
1483               else if (idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1484                 value = NULL;
1485               else
1486                 {
1487                   g_set_error (error,
1488                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1489                                _("Missing argument for %s"), option_name);
1490                   g_free (option_name);
1491                   return FALSE;
1492                 }
1493             }
1494
1495           if (!parse_arg (context, group, &group->entries[j],
1496                           value, option_name, error))
1497             {
1498               g_free (option_name);
1499               return FALSE;
1500             }
1501
1502           g_free (option_name);
1503           *parsed = TRUE;
1504         }
1505     }
1506
1507   return TRUE;
1508 }
1509
1510 static gboolean
1511 parse_long_option (GOptionContext *context,
1512                    GOptionGroup   *group,
1513                    gint           *idx,
1514                    gchar          *arg,
1515                    gboolean        aliased,
1516                    gint           *argc,
1517                    gchar        ***argv,
1518                    GError        **error,
1519                    gboolean       *parsed)
1520 {
1521   gint j;
1522
1523   for (j = 0; j < group->n_entries; j++)
1524     {
1525       if (*idx >= *argc)
1526         return TRUE;
1527
1528       if (aliased && (group->entries[j].flags & G_OPTION_FLAG_NOALIAS))
1529         continue;
1530
1531       if (NO_ARG (&group->entries[j]) &&
1532           strcmp (arg, group->entries[j].long_name) == 0)
1533         {
1534           gchar *option_name;
1535           gboolean retval;
1536
1537           option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1538           retval = parse_arg (context, group, &group->entries[j],
1539                               NULL, option_name, error);
1540           g_free (option_name);
1541
1542           add_pending_null (context, &((*argv)[*idx]), NULL);
1543           *parsed = TRUE;
1544
1545           return retval;
1546         }
1547       else
1548         {
1549           gint len = strlen (group->entries[j].long_name);
1550
1551           if (strncmp (arg, group->entries[j].long_name, len) == 0 &&
1552               (arg[len] == '=' || arg[len] == 0))
1553             {
1554               gchar *value = NULL;
1555               gchar *option_name;
1556
1557               add_pending_null (context, &((*argv)[*idx]), NULL);
1558               option_name = g_strconcat ("--", group->entries[j].long_name, NULL);
1559
1560               if (arg[len] == '=')
1561                 value = arg + len + 1;
1562               else if (*idx < *argc - 1)
1563                 {
1564                   if (!OPTIONAL_ARG (&group->entries[j]))
1565                     {
1566                       value = (*argv)[*idx + 1];
1567                       add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1568                       (*idx)++;
1569                     }
1570                   else
1571                     {
1572                       if ((*argv)[*idx + 1][0] == '-')
1573                         {
1574                           gboolean retval;
1575                           retval = parse_arg (context, group, &group->entries[j],
1576                                               NULL, option_name, error);
1577                           *parsed = TRUE;
1578                           g_free (option_name);
1579                           return retval;
1580                         }
1581                       else
1582                         {
1583                           value = (*argv)[*idx + 1];
1584                           add_pending_null (context, &((*argv)[*idx + 1]), NULL);
1585                           (*idx)++;
1586                         }
1587                     }
1588                 }
1589               else if (*idx >= *argc - 1 && OPTIONAL_ARG (&group->entries[j]))
1590                 {
1591                     gboolean retval;
1592                     retval = parse_arg (context, group, &group->entries[j],
1593                                         NULL, option_name, error);
1594                     *parsed = TRUE;
1595                     g_free (option_name);
1596                     return retval;
1597                 }
1598               else
1599                 {
1600                   g_set_error (error,
1601                                G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE,
1602                                _("Missing argument for %s"), option_name);
1603                   g_free (option_name);
1604                   return FALSE;
1605                 }
1606
1607               if (!parse_arg (context, group, &group->entries[j],
1608                               value, option_name, error))
1609                 {
1610                   g_free (option_name);
1611                   return FALSE;
1612                 }
1613
1614               g_free (option_name);
1615               *parsed = TRUE;
1616             }
1617         }
1618     }
1619
1620   return TRUE;
1621 }
1622
1623 static gboolean
1624 parse_remaining_arg (GOptionContext *context,
1625                      GOptionGroup   *group,
1626                      gint           *idx,
1627                      gint           *argc,
1628                      gchar        ***argv,
1629                      GError        **error,
1630                      gboolean       *parsed)
1631 {
1632   gint j;
1633
1634   for (j = 0; j < group->n_entries; j++)
1635     {
1636       if (*idx >= *argc)
1637         return TRUE;
1638
1639       if (group->entries[j].long_name[0])
1640         continue;
1641
1642       g_return_val_if_fail (group->entries[j].arg == G_OPTION_ARG_CALLBACK ||
1643                             group->entries[j].arg == G_OPTION_ARG_STRING_ARRAY ||
1644                             group->entries[j].arg == G_OPTION_ARG_FILENAME_ARRAY, FALSE);
1645
1646       add_pending_null (context, &((*argv)[*idx]), NULL);
1647
1648       if (!parse_arg (context, group, &group->entries[j], (*argv)[*idx], "", error))
1649         return FALSE;
1650
1651       *parsed = TRUE;
1652       return TRUE;
1653     }
1654
1655   return TRUE;
1656 }
1657
1658 static void
1659 free_changes_list (GOptionContext *context,
1660                    gboolean        revert)
1661 {
1662   GList *list;
1663
1664   for (list = context->changes; list != NULL; list = list->next)
1665     {
1666       Change *change = list->data;
1667
1668       if (revert)
1669         {
1670           switch (change->arg_type)
1671             {
1672             case G_OPTION_ARG_NONE:
1673               *(gboolean *)change->arg_data = change->prev.bool;
1674               break;
1675             case G_OPTION_ARG_INT:
1676               *(gint *)change->arg_data = change->prev.integer;
1677               break;
1678             case G_OPTION_ARG_STRING:
1679             case G_OPTION_ARG_FILENAME:
1680               g_free (change->allocated.str);
1681               *(gchar **)change->arg_data = change->prev.str;
1682               break;
1683             case G_OPTION_ARG_STRING_ARRAY:
1684             case G_OPTION_ARG_FILENAME_ARRAY:
1685               g_strfreev (change->allocated.array.data);
1686               *(gchar ***)change->arg_data = change->prev.array;
1687               break;
1688             case G_OPTION_ARG_DOUBLE:
1689               *(gdouble *)change->arg_data = change->prev.dbl;
1690               break;
1691             case G_OPTION_ARG_INT64:
1692               *(gint64 *)change->arg_data = change->prev.int64;
1693               break;
1694             default:
1695               g_assert_not_reached ();
1696             }
1697         }
1698
1699       g_free (change);
1700     }
1701
1702   g_list_free (context->changes);
1703   context->changes = NULL;
1704 }
1705
1706 static void
1707 free_pending_nulls (GOptionContext *context,
1708                     gboolean        perform_nulls)
1709 {
1710   GList *list;
1711
1712   for (list = context->pending_nulls; list != NULL; list = list->next)
1713     {
1714       PendingNull *n = list->data;
1715
1716       if (perform_nulls)
1717         {
1718           if (n->value)
1719             {
1720               /* Copy back the short options */
1721               *(n->ptr)[0] = '-';
1722               strcpy (*n->ptr + 1, n->value);
1723             }
1724           else
1725             {
1726               if (context->strv_mode)
1727                 g_free (*n->ptr);
1728
1729               *n->ptr = NULL;
1730             }
1731         }
1732
1733       g_free (n->value);
1734       g_free (n);
1735     }
1736
1737   g_list_free (context->pending_nulls);
1738   context->pending_nulls = NULL;
1739 }
1740
1741 /* Use a platform-specific mechanism to look up the first argument to
1742  * the current process. 
1743  * Note if you implement this for other platforms, also add it to
1744  * tests/option-argv0.c
1745  */
1746 static char *
1747 platform_get_argv0 (void)
1748 {
1749 #if defined __linux
1750   char *cmdline;
1751   char *base_arg0;
1752   gsize len;
1753
1754   if (!g_file_get_contents ("/proc/self/cmdline",
1755                             &cmdline,
1756                             &len,
1757                             NULL))
1758     return NULL;
1759   /* Sanity check for a NUL terminator. */
1760   if (!memchr (cmdline, 0, len))
1761     return NULL;
1762   /* We could just return cmdline, but I think it's better
1763    * to hold on to a smaller malloc block; the arguments
1764    * could be large.
1765    */
1766   base_arg0 = g_path_get_basename (cmdline);
1767   g_free (cmdline);
1768   return base_arg0;
1769 #elif defined __OpenBSD__
1770   char **cmdline = NULL;
1771   char *base_arg0;
1772   gsize len = PATH_MAX;
1773
1774   int mib[] = { CTL_KERN, KERN_PROC_ARGS, getpid(), KERN_PROC_ARGV };
1775
1776   cmdline = (char **) realloc (cmdline, len);
1777
1778   if (sysctl (mib, G_N_ELEMENTS (mib), cmdline, &len, NULL, 0) == -1)
1779     {
1780       g_free (cmdline);
1781       return NULL;
1782     }
1783
1784   /* We could just return cmdline, but I think it's better
1785    * to hold on to a smaller malloc block; the arguments
1786    * could be large.
1787    */
1788   base_arg0 = g_path_get_basename (*cmdline);
1789   g_free (cmdline);
1790   return base_arg0;
1791 #endif
1792
1793   return NULL;
1794 }
1795
1796 /**
1797  * g_option_context_parse:
1798  * @context: a #GOptionContext
1799  * @argc: (inout) (allow-none): a pointer to the number of command line arguments
1800  * @argv: (inout) (array length=argc) (allow-none): a pointer to the array of command line arguments
1801  * @error: a return location for errors
1802  *
1803  * Parses the command line arguments, recognizing options
1804  * which have been added to @context. A side-effect of
1805  * calling this function is that g_set_prgname() will be
1806  * called.
1807  *
1808  * If the parsing is successful, any parsed arguments are
1809  * removed from the array and @argc and @argv are updated
1810  * accordingly. A '--' option is stripped from @argv
1811  * unless there are unparsed options before and after it,
1812  * or some of the options after it start with '-'. In case
1813  * of an error, @argc and @argv are left unmodified.
1814  *
1815  * If automatic `--help` support is enabled
1816  * (see g_option_context_set_help_enabled()), and the
1817  * @argv array contains one of the recognized help options,
1818  * this function will produce help output to stdout and
1819  * call <literal>exit (0)</literal>.
1820  *
1821  * Note that function depends on the
1822  * <link linkend="setlocale">current locale</link> for
1823  * automatic character set conversion of string and filename
1824  * arguments.
1825  *
1826  * Return value: %TRUE if the parsing was successful,
1827  *               %FALSE if an error occurred
1828  *
1829  * Since: 2.6
1830  **/
1831 gboolean
1832 g_option_context_parse (GOptionContext   *context,
1833                         gint             *argc,
1834                         gchar          ***argv,
1835                         GError          **error)
1836 {
1837   gint i, j, k;
1838   GList *list;
1839
1840   /* Set program name */
1841   if (!g_get_prgname())
1842     {
1843       gchar *prgname;
1844
1845       if (argc && argv && *argc)
1846         prgname = g_path_get_basename ((*argv)[0]);
1847       else
1848         prgname = platform_get_argv0 ();
1849
1850       if (prgname)
1851         g_set_prgname (prgname);
1852       else
1853         g_set_prgname ("<unknown>");
1854
1855       g_free (prgname);
1856     }
1857
1858   /* Call pre-parse hooks */
1859   list = context->groups;
1860   while (list)
1861     {
1862       GOptionGroup *group = list->data;
1863
1864       if (group->pre_parse_func)
1865         {
1866           if (!(* group->pre_parse_func) (context, group,
1867                                           group->user_data, error))
1868             goto fail;
1869         }
1870
1871       list = list->next;
1872     }
1873
1874   if (context->main_group && context->main_group->pre_parse_func)
1875     {
1876       if (!(* context->main_group->pre_parse_func) (context, context->main_group,
1877                                                     context->main_group->user_data, error))
1878         goto fail;
1879     }
1880
1881   if (argc && argv)
1882     {
1883       gboolean stop_parsing = FALSE;
1884       gboolean has_unknown = FALSE;
1885       gint separator_pos = 0;
1886
1887       for (i = 1; i < *argc; i++)
1888         {
1889           gchar *arg, *dash;
1890           gboolean parsed = FALSE;
1891
1892           if ((*argv)[i][0] == '-' && (*argv)[i][1] != '\0' && !stop_parsing)
1893             {
1894               if ((*argv)[i][1] == '-')
1895                 {
1896                   /* -- option */
1897
1898                   arg = (*argv)[i] + 2;
1899
1900                   /* '--' terminates list of arguments */
1901                   if (*arg == 0)
1902                     {
1903                       separator_pos = i;
1904                       stop_parsing = TRUE;
1905                       continue;
1906                     }
1907
1908                   /* Handle help options */
1909                   if (context->help_enabled)
1910                     {
1911                       if (strcmp (arg, "help") == 0)
1912                         print_help (context, TRUE, NULL);
1913                       else if (strcmp (arg, "help-all") == 0)
1914                         print_help (context, FALSE, NULL);
1915                       else if (strncmp (arg, "help-", 5) == 0)
1916                         {
1917                           list = context->groups;
1918
1919                           while (list)
1920                             {
1921                               GOptionGroup *group = list->data;
1922
1923                               if (strcmp (arg + 5, group->name) == 0)
1924                                 print_help (context, FALSE, group);
1925
1926                               list = list->next;
1927                             }
1928                         }
1929                     }
1930
1931                   if (context->main_group &&
1932                       !parse_long_option (context, context->main_group, &i, arg,
1933                                           FALSE, argc, argv, error, &parsed))
1934                     goto fail;
1935
1936                   if (parsed)
1937                     continue;
1938
1939                   /* Try the groups */
1940                   list = context->groups;
1941                   while (list)
1942                     {
1943                       GOptionGroup *group = list->data;
1944
1945                       if (!parse_long_option (context, group, &i, arg,
1946                                               FALSE, argc, argv, error, &parsed))
1947                         goto fail;
1948
1949                       if (parsed)
1950                         break;
1951
1952                       list = list->next;
1953                     }
1954
1955                   if (parsed)
1956                     continue;
1957
1958                   /* Now look for --<group>-<option> */
1959                   dash = strchr (arg, '-');
1960                   if (dash)
1961                     {
1962                       /* Try the groups */
1963                       list = context->groups;
1964                       while (list)
1965                         {
1966                           GOptionGroup *group = list->data;
1967
1968                           if (strncmp (group->name, arg, dash - arg) == 0)
1969                             {
1970                               if (!parse_long_option (context, group, &i, dash + 1,
1971                                                       TRUE, argc, argv, error, &parsed))
1972                                 goto fail;
1973
1974                               if (parsed)
1975                                 break;
1976                             }
1977
1978                           list = list->next;
1979                         }
1980                     }
1981
1982                   if (context->ignore_unknown)
1983                     continue;
1984                 }
1985               else
1986                 { /* short option */
1987                   gint new_i = i, arg_length;
1988                   gboolean *nulled_out = NULL;
1989                   gboolean has_h_entry = context_has_h_entry (context);
1990                   arg = (*argv)[i] + 1;
1991                   arg_length = strlen (arg);
1992                   nulled_out = g_newa (gboolean, arg_length);
1993                   memset (nulled_out, 0, arg_length * sizeof (gboolean));
1994                   for (j = 0; j < arg_length; j++)
1995                     {
1996                       if (context->help_enabled && (arg[j] == '?' ||
1997                         (arg[j] == 'h' && !has_h_entry)))
1998                         print_help (context, TRUE, NULL);
1999                       parsed = FALSE;
2000                       if (context->main_group &&
2001                           !parse_short_option (context, context->main_group,
2002                                                i, &new_i, arg[j],
2003                                                argc, argv, error, &parsed))
2004                         goto fail;
2005                       if (!parsed)
2006                         {
2007                           /* Try the groups */
2008                           list = context->groups;
2009                           while (list)
2010                             {
2011                               GOptionGroup *group = list->data;
2012                               if (!parse_short_option (context, group, i, &new_i, arg[j],
2013                                                        argc, argv, error, &parsed))
2014                                 goto fail;
2015                               if (parsed)
2016                                 break;
2017                               list = list->next;
2018                             }
2019                         }
2020
2021                       if (context->ignore_unknown && parsed)
2022                         nulled_out[j] = TRUE;
2023                       else if (context->ignore_unknown)
2024                         continue;
2025                       else if (!parsed)
2026                         break;
2027                       /* !context->ignore_unknown && parsed */
2028                     }
2029                   if (context->ignore_unknown)
2030                     {
2031                       gchar *new_arg = NULL;
2032                       gint arg_index = 0;
2033                       for (j = 0; j < arg_length; j++)
2034                         {
2035                           if (!nulled_out[j])
2036                             {
2037                               if (!new_arg)
2038                                 new_arg = g_malloc (arg_length + 1);
2039                               new_arg[arg_index++] = arg[j];
2040                             }
2041                         }
2042                       if (new_arg)
2043                         new_arg[arg_index] = '\0';
2044                       add_pending_null (context, &((*argv)[i]), new_arg);
2045                     }
2046                   else if (parsed)
2047                     {
2048                       add_pending_null (context, &((*argv)[i]), NULL);
2049                       i = new_i;
2050                     }
2051                 }
2052
2053               if (!parsed)
2054                 has_unknown = TRUE;
2055
2056               if (!parsed && !context->ignore_unknown)
2057                 {
2058                   g_set_error (error,
2059                                G_OPTION_ERROR, G_OPTION_ERROR_UNKNOWN_OPTION,
2060                                    _("Unknown option %s"), (*argv)[i]);
2061                   goto fail;
2062                 }
2063             }
2064           else
2065             {
2066               /* Collect remaining args */
2067               if (context->main_group &&
2068                   !parse_remaining_arg (context, context->main_group, &i,
2069                                         argc, argv, error, &parsed))
2070                 goto fail;
2071
2072               if (!parsed && (has_unknown || (*argv)[i][0] == '-'))
2073                 separator_pos = 0;
2074             }
2075         }
2076
2077       if (separator_pos > 0)
2078         add_pending_null (context, &((*argv)[separator_pos]), NULL);
2079
2080     }
2081
2082   /* Call post-parse hooks */
2083   list = context->groups;
2084   while (list)
2085     {
2086       GOptionGroup *group = list->data;
2087
2088       if (group->post_parse_func)
2089         {
2090           if (!(* group->post_parse_func) (context, group,
2091                                            group->user_data, error))
2092             goto fail;
2093         }
2094
2095       list = list->next;
2096     }
2097
2098   if (context->main_group && context->main_group->post_parse_func)
2099     {
2100       if (!(* context->main_group->post_parse_func) (context, context->main_group,
2101                                                      context->main_group->user_data, error))
2102         goto fail;
2103     }
2104
2105   if (argc && argv)
2106     {
2107       free_pending_nulls (context, TRUE);
2108
2109       for (i = 1; i < *argc; i++)
2110         {
2111           for (k = i; k < *argc; k++)
2112             if ((*argv)[k] != NULL)
2113               break;
2114
2115           if (k > i)
2116             {
2117               k -= i;
2118               for (j = i + k; j < *argc; j++)
2119                 {
2120                   (*argv)[j-k] = (*argv)[j];
2121                   (*argv)[j] = NULL;
2122                 }
2123               *argc -= k;
2124             }
2125         }
2126     }
2127
2128   return TRUE;
2129
2130  fail:
2131
2132   /* Call error hooks */
2133   list = context->groups;
2134   while (list)
2135     {
2136       GOptionGroup *group = list->data;
2137
2138       if (group->error_func)
2139         (* group->error_func) (context, group,
2140                                group->user_data, error);
2141
2142       list = list->next;
2143     }
2144
2145   if (context->main_group && context->main_group->error_func)
2146     (* context->main_group->error_func) (context, context->main_group,
2147                                          context->main_group->user_data, error);
2148
2149   free_changes_list (context, TRUE);
2150   free_pending_nulls (context, FALSE);
2151
2152   return FALSE;
2153 }
2154
2155 /**
2156  * g_option_group_new:
2157  * @name: the name for the option group, this is used to provide
2158  *   help for the options in this group with `--help-`@name
2159  * @description: a description for this group to be shown in
2160  *   `--help`. This string is translated using the translation
2161  *   domain or translation function of the group
2162  * @help_description: a description for the `--help-`@name option.
2163  *   This string is translated using the translation domain or translation function
2164  *   of the group
2165  * @user_data: (allow-none): user data that will be passed to the pre- and post-parse hooks,
2166  *   the error hook and to callbacks of %G_OPTION_ARG_CALLBACK options, or %NULL
2167  * @destroy: (allow-none): a function that will be called to free @user_data, or %NULL
2168  *
2169  * Creates a new #GOptionGroup.
2170  *
2171  * Return value: a newly created option group. It should be added
2172  *   to a #GOptionContext or freed with g_option_group_free().
2173  *
2174  * Since: 2.6
2175  **/
2176 GOptionGroup *
2177 g_option_group_new (const gchar    *name,
2178                     const gchar    *description,
2179                     const gchar    *help_description,
2180                     gpointer        user_data,
2181                     GDestroyNotify  destroy)
2182
2183 {
2184   GOptionGroup *group;
2185
2186   group = g_new0 (GOptionGroup, 1);
2187   group->name = g_strdup (name);
2188   group->description = g_strdup (description);
2189   group->help_description = g_strdup (help_description);
2190   group->user_data = user_data;
2191   group->destroy_notify = destroy;
2192
2193   return group;
2194 }
2195
2196
2197 /**
2198  * g_option_group_free:
2199  * @group: a #GOptionGroup
2200  *
2201  * Frees a #GOptionGroup. Note that you must not free groups
2202  * which have been added to a #GOptionContext.
2203  *
2204  * Since: 2.6
2205  */
2206 void
2207 g_option_group_free (GOptionGroup *group)
2208 {
2209   g_return_if_fail (group != NULL);
2210
2211   g_free (group->name);
2212   g_free (group->description);
2213   g_free (group->help_description);
2214
2215   g_free (group->entries);
2216
2217   if (group->destroy_notify)
2218     (* group->destroy_notify) (group->user_data);
2219
2220   if (group->translate_notify)
2221     (* group->translate_notify) (group->translate_data);
2222
2223   g_free (group);
2224 }
2225
2226
2227 /**
2228  * g_option_group_add_entries:
2229  * @group: a #GOptionGroup
2230  * @entries: a %NULL-terminated array of #GOptionEntrys
2231  *
2232  * Adds the options specified in @entries to @group.
2233  *
2234  * Since: 2.6
2235  **/
2236 void
2237 g_option_group_add_entries (GOptionGroup       *group,
2238                             const GOptionEntry *entries)
2239 {
2240   gint i, n_entries;
2241
2242   g_return_if_fail (entries != NULL);
2243
2244   for (n_entries = 0; entries[n_entries].long_name != NULL; n_entries++) ;
2245
2246   group->entries = g_renew (GOptionEntry, group->entries, group->n_entries + n_entries);
2247
2248   memcpy (group->entries + group->n_entries, entries, sizeof (GOptionEntry) * n_entries);
2249
2250   for (i = group->n_entries; i < group->n_entries + n_entries; i++)
2251     {
2252       gchar c = group->entries[i].short_name;
2253
2254       if (c == '-' || (c != 0 && !g_ascii_isprint (c)))
2255         {
2256           g_warning (G_STRLOC ": ignoring invalid short option '%c' (%d) in entry %s:%s",
2257               c, c, group->name, group->entries[i].long_name);
2258           group->entries[i].short_name = '\0';
2259         }
2260
2261       if (group->entries[i].arg != G_OPTION_ARG_NONE &&
2262           (group->entries[i].flags & G_OPTION_FLAG_REVERSE) != 0)
2263         {
2264           g_warning (G_STRLOC ": ignoring reverse flag on option of arg-type %d in entry %s:%s",
2265               group->entries[i].arg, group->name, group->entries[i].long_name);
2266
2267           group->entries[i].flags &= ~G_OPTION_FLAG_REVERSE;
2268         }
2269
2270       if (group->entries[i].arg != G_OPTION_ARG_CALLBACK &&
2271           (group->entries[i].flags & (G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME)) != 0)
2272         {
2273           g_warning (G_STRLOC ": ignoring no-arg, optional-arg or filename flags (%d) on option of arg-type %d in entry %s:%s",
2274               group->entries[i].flags, group->entries[i].arg, group->name, group->entries[i].long_name);
2275
2276           group->entries[i].flags &= ~(G_OPTION_FLAG_NO_ARG|G_OPTION_FLAG_OPTIONAL_ARG|G_OPTION_FLAG_FILENAME);
2277         }
2278     }
2279
2280   group->n_entries += n_entries;
2281 }
2282
2283 /**
2284  * g_option_group_set_parse_hooks:
2285  * @group: a #GOptionGroup
2286  * @pre_parse_func: (allow-none): a function to call before parsing, or %NULL
2287  * @post_parse_func: (allow-none): a function to call after parsing, or %NULL
2288  *
2289  * Associates two functions with @group which will be called
2290  * from g_option_context_parse() before the first option is parsed
2291  * and after the last option has been parsed, respectively.
2292  *
2293  * Note that the user data to be passed to @pre_parse_func and
2294  * @post_parse_func can be specified when constructing the group
2295  * with g_option_group_new().
2296  *
2297  * Since: 2.6
2298  **/
2299 void
2300 g_option_group_set_parse_hooks (GOptionGroup     *group,
2301                                 GOptionParseFunc  pre_parse_func,
2302                                 GOptionParseFunc  post_parse_func)
2303 {
2304   g_return_if_fail (group != NULL);
2305
2306   group->pre_parse_func = pre_parse_func;
2307   group->post_parse_func = post_parse_func;
2308 }
2309
2310 /**
2311  * g_option_group_set_error_hook:
2312  * @group: a #GOptionGroup
2313  * @error_func: a function to call when an error occurs
2314  *
2315  * Associates a function with @group which will be called
2316  * from g_option_context_parse() when an error occurs.
2317  *
2318  * Note that the user data to be passed to @error_func can be
2319  * specified when constructing the group with g_option_group_new().
2320  *
2321  * Since: 2.6
2322  **/
2323 void
2324 g_option_group_set_error_hook (GOptionGroup     *group,
2325                                GOptionErrorFunc  error_func)
2326 {
2327   g_return_if_fail (group != NULL);
2328
2329   group->error_func = error_func;
2330 }
2331
2332
2333 /**
2334  * g_option_group_set_translate_func:
2335  * @group: a #GOptionGroup
2336  * @func: (allow-none): the #GTranslateFunc, or %NULL
2337  * @data: (allow-none): user data to pass to @func, or %NULL
2338  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2339  *
2340  * Sets the function which is used to translate user-visible strings,
2341  * for `--help` output. Different groups can use different
2342  * #GTranslateFuncs. If @func is %NULL, strings are not translated.
2343  *
2344  * If you are using gettext(), you only need to set the translation
2345  * domain, see g_option_group_set_translation_domain().
2346  *
2347  * Since: 2.6
2348  **/
2349 void
2350 g_option_group_set_translate_func (GOptionGroup   *group,
2351                                    GTranslateFunc  func,
2352                                    gpointer        data,
2353                                    GDestroyNotify  destroy_notify)
2354 {
2355   g_return_if_fail (group != NULL);
2356
2357   if (group->translate_notify)
2358     group->translate_notify (group->translate_data);
2359
2360   group->translate_func = func;
2361   group->translate_data = data;
2362   group->translate_notify = destroy_notify;
2363 }
2364
2365 static const gchar *
2366 dgettext_swapped (const gchar *msgid,
2367                   const gchar *domainname)
2368 {
2369   return g_dgettext (domainname, msgid);
2370 }
2371
2372 /**
2373  * g_option_group_set_translation_domain:
2374  * @group: a #GOptionGroup
2375  * @domain: the domain to use
2376  *
2377  * A convenience function to use gettext() for translating
2378  * user-visible strings.
2379  *
2380  * Since: 2.6
2381  **/
2382 void
2383 g_option_group_set_translation_domain (GOptionGroup *group,
2384                                        const gchar  *domain)
2385 {
2386   g_return_if_fail (group != NULL);
2387
2388   g_option_group_set_translate_func (group,
2389                                      (GTranslateFunc)dgettext_swapped,
2390                                      g_strdup (domain),
2391                                      g_free);
2392 }
2393
2394 /**
2395  * g_option_context_set_translate_func:
2396  * @context: a #GOptionContext
2397  * @func: (allow-none): the #GTranslateFunc, or %NULL
2398  * @data: (allow-none): user data to pass to @func, or %NULL
2399  * @destroy_notify: (allow-none): a function which gets called to free @data, or %NULL
2400  *
2401  * Sets the function which is used to translate the contexts
2402  * user-visible strings, for `--help` output. If @func is %NULL,
2403  * strings are not translated.
2404  *
2405  * Note that option groups have their own translation functions,
2406  * this function only affects the @parameter_string (see g_option_context_new()),
2407  * the summary (see g_option_context_set_summary()) and the description
2408  * (see g_option_context_set_description()).
2409  *
2410  * If you are using gettext(), you only need to set the translation
2411  * domain, see g_option_context_set_translation_domain().
2412  *
2413  * Since: 2.12
2414  **/
2415 void
2416 g_option_context_set_translate_func (GOptionContext *context,
2417                                      GTranslateFunc func,
2418                                      gpointer       data,
2419                                      GDestroyNotify destroy_notify)
2420 {
2421   g_return_if_fail (context != NULL);
2422
2423   if (context->translate_notify)
2424     context->translate_notify (context->translate_data);
2425
2426   context->translate_func = func;
2427   context->translate_data = data;
2428   context->translate_notify = destroy_notify;
2429 }
2430
2431 /**
2432  * g_option_context_set_translation_domain:
2433  * @context: a #GOptionContext
2434  * @domain: the domain to use
2435  *
2436  * A convenience function to use gettext() for translating
2437  * user-visible strings.
2438  *
2439  * Since: 2.12
2440  **/
2441 void
2442 g_option_context_set_translation_domain (GOptionContext *context,
2443                                          const gchar     *domain)
2444 {
2445   g_return_if_fail (context != NULL);
2446
2447   g_option_context_set_translate_func (context,
2448                                        (GTranslateFunc)dgettext_swapped,
2449                                        g_strdup (domain),
2450                                        g_free);
2451 }
2452
2453 /**
2454  * g_option_context_set_summary:
2455  * @context: a #GOptionContext
2456  * @summary: (allow-none): a string to be shown in `--help` output
2457  *  before the list of options, or %NULL
2458  *
2459  * Adds a string to be displayed in `--help` output before the list
2460  * of options. This is typically a summary of the program functionality.
2461  *
2462  * Note that the summary is translated (see
2463  * g_option_context_set_translate_func() and
2464  * g_option_context_set_translation_domain()).
2465  *
2466  * Since: 2.12
2467  */
2468 void
2469 g_option_context_set_summary (GOptionContext *context,
2470                               const gchar    *summary)
2471 {
2472   g_return_if_fail (context != NULL);
2473
2474   g_free (context->summary);
2475   context->summary = g_strdup (summary);
2476 }
2477
2478
2479 /**
2480  * g_option_context_get_summary:
2481  * @context: a #GOptionContext
2482  *
2483  * Returns the summary. See g_option_context_set_summary().
2484  *
2485  * Returns: the summary
2486  *
2487  * Since: 2.12
2488  */
2489 const gchar *
2490 g_option_context_get_summary (GOptionContext *context)
2491 {
2492   g_return_val_if_fail (context != NULL, NULL);
2493
2494   return context->summary;
2495 }
2496
2497 /**
2498  * g_option_context_set_description:
2499  * @context: a #GOptionContext
2500  * @description: (allow-none): a string to be shown in `--help` output
2501  *   after the list of options, or %NULL
2502  *
2503  * Adds a string to be displayed in `--help` output after the list
2504  * of options. This text often includes a bug reporting address.
2505  *
2506  * Note that the summary is translated (see
2507  * g_option_context_set_translate_func()).
2508  *
2509  * Since: 2.12
2510  */
2511 void
2512 g_option_context_set_description (GOptionContext *context,
2513                                   const gchar    *description)
2514 {
2515   g_return_if_fail (context != NULL);
2516
2517   g_free (context->description);
2518   context->description = g_strdup (description);
2519 }
2520
2521
2522 /**
2523  * g_option_context_get_description:
2524  * @context: a #GOptionContext
2525  *
2526  * Returns the description. See g_option_context_set_description().
2527  *
2528  * Returns: the description
2529  *
2530  * Since: 2.12
2531  */
2532 const gchar *
2533 g_option_context_get_description (GOptionContext *context)
2534 {
2535   g_return_val_if_fail (context != NULL, NULL);
2536
2537   return context->description;
2538 }
2539
2540 /**
2541  * g_option_context_parse_strv:
2542  * @context: a #GOptionContext
2543  * @arguments: (inout) (array null-terminated=1): a pointer to the
2544  *    command line arguments (which must be in UTF-8 on Windows)
2545  * @error: a return location for errors
2546  *
2547  * Parses the command line arguments.
2548  *
2549  * This function is similar to g_option_context_parse() except that it
2550  * respects the normal memory rules when dealing with a strv instead of
2551  * assuming that the passed-in array is the argv of the main function.
2552  *
2553  * In particular, strings that are removed from the arguments list will
2554  * be freed using g_free().
2555  *
2556  * On Windows, the strings are expected to be in UTF-8.  This is in
2557  * contrast to g_option_context_parse() which expects them to be in the
2558  * system codepage, which is how they are passed as @argv to main().
2559  * See g_win32_get_command_line() for a solution.
2560  *
2561  * This function is useful if you are trying to use #GOptionContext with
2562  * #GApplication.
2563  *
2564  * Returns: %TRUE if the parsing was successful,
2565  *          %FALSE if an error occurred
2566  *
2567  * Since: 2.40
2568  **/
2569 gboolean
2570 g_option_context_parse_strv (GOptionContext   *context,
2571                              gchar          ***arguments,
2572                              GError          **error)
2573 {
2574   gboolean success;
2575   gint argc;
2576
2577   context->strv_mode = TRUE;
2578   argc = g_strv_length (*arguments);
2579   success = g_option_context_parse (context, &argc, arguments, error);
2580   context->strv_mode = FALSE;
2581
2582   return success;
2583 }