Rename the generated private data getter function
[platform/upstream/glib.git] / gio / gapplicationcommandline.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as
6  * published by the Free Software Foundation; either version 2 of the
7  * licence or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful, but
10  * WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the Free Software
16  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
17  * USA.
18  *
19  * Authors: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include "gapplicationcommandline.h"
25
26 #include "glibintl.h"
27 #include "gfile.h"
28
29 #include <string.h>
30 #include <stdio.h>
31
32 #ifdef G_OS_UNIX
33 #include "gunixinputstream.h"
34 #endif
35
36 #ifdef G_OS_WIN32
37 #include <windows.h>
38 #undef environ
39 #include "gwin32inputstream.h"
40 #endif
41
42 /**
43  * SECTION:gapplicationcommandline
44  * @title: GApplicationCommandLine
45  * @short_description: A command-line invocation of an application
46  * @see_also: #GApplication
47  *
48  * #GApplicationCommandLine represents a command-line invocation of
49  * an application.  It is created by #GApplication and emitted
50  * in the #GApplication::command-line signal and virtual function.
51  *
52  * The class contains the list of arguments that the program was invoked
53  * with.  It is also possible to query if the commandline invocation was
54  * local (ie: the current process is running in direct response to the
55  * invocation) or remote (ie: some other process forwarded the
56  * commandline to this process).
57  *
58  * The GApplicationCommandLine object can provide the @argc and @argv
59  * parameters for use with the #GOptionContext command-line parsing API,
60  * with the g_application_command_line_get_arguments() function. See
61  * <xref linkend="gapplication-example-cmdline3"/> for an example.
62  *
63  * The exit status of the originally-invoked process may be set and
64  * messages can be printed to stdout or stderr of that process.  The
65  * lifecycle of the originally-invoked process is tied to the lifecycle
66  * of this object (ie: the process exits when the last reference is
67  * dropped).
68  *
69  * The main use for #GApplicationCommandLine (and the
70  * #GApplication::command-line signal) is 'Emacs server' like use cases:
71  * You can set the <envar>EDITOR</envar> environment variable to have
72  * e.g. git use your favourite editor to edit commit messages, and if you
73  * already have an instance of the editor running, the editing will happen
74  * in the running instance, instead of opening a new one. An important
75  * aspect of this use case is that the process that gets started by git
76  * does not return until the editing is done.
77  *
78  * <example id="gapplication-example-cmdline"><title>Handling commandline arguments with GApplication</title>
79  * <para>
80  * A simple example where the commandline is completely handled
81  * in the #GApplication::command-line handler. The launching instance exits
82  * once the signal handler in the primary instance has returned, and the
83  * return value of the signal handler becomes the exit status of the launching
84  * instance.
85  * </para>
86  * <programlisting>
87  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline.c">
88  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
89  * </xi:include>
90  * </programlisting>
91  * </example>
92  *
93  * <example id="gapplication-example-cmdline2"><title>Split commandline handling</title>
94  * <para>
95  * An example of split commandline handling. Options that start with
96  * <literal>--local-</literal> are handled locally, all other options are
97  * passed to the #GApplication::command-line handler which runs in the primary
98  * instance.
99  * </para>
100  * <programlisting>
101  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline2.c">
102  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
103  * </xi:include>
104  * </programlisting>
105  * </example>
106  *
107  * <example id="gapplication-example-cmdline3"><title>Deferred commandline handling</title>
108  * <para>
109  * An example of deferred commandline handling. Here, the commandline is
110  * not completely handled before the #GApplication::command-line handler
111  * returns. Instead, we keep a reference to the GApplicationCommandLine
112  * object and handle it later(in this example, in an idle). Note that it
113  * is necessary to hold the application until you are done with the
114  * commandline.
115  * </para>
116  * <para>
117  * This example also shows how to use #GOptionContext for parsing the
118  * commandline arguments. Note that it is necessary to disable the
119  * built-in help-handling of #GOptionContext, since it calls exit()
120  * after printing help, which is not what you want to happen in
121  * the primary instance.
122  * </para>
123  * <programlisting>
124  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gio/tests/gapplication-example-cmdline3.c">
125  *   <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
126  * </xi:include>
127  * </programlisting>
128  * </example>
129  **/
130
131 /**
132  * GApplicationCommandLineClass:
133  *
134  * The <structname>GApplicationCommandLineClass</structname> structure
135  * contains private data only
136  *
137  * Since: 2.28
138  **/
139 enum
140 {
141   PROP_NONE,
142   PROP_ARGUMENTS,
143   PROP_PLATFORM_DATA,
144   PROP_IS_REMOTE
145 };
146
147 struct _GApplicationCommandLinePrivate
148 {
149   GVariant *platform_data;
150   GVariant *arguments;
151   gchar *cwd;
152
153   gchar **environ;
154   gint exit_status;
155 };
156
157 G_DEFINE_TYPE_WITH_PRIVATE (GApplicationCommandLine, g_application_command_line, G_TYPE_OBJECT)
158
159 /* All subclasses represent remote invocations of some kind. */
160 #define IS_REMOTE(cmdline) (G_TYPE_FROM_INSTANCE (cmdline) != \
161                             G_TYPE_APPLICATION_COMMAND_LINE)
162
163 static void
164 grok_platform_data (GApplicationCommandLine *cmdline)
165 {
166   GVariantIter iter;
167   const gchar *key;
168   GVariant *value;
169
170   g_variant_iter_init (&iter, cmdline->priv->platform_data);
171
172   while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
173     if (strcmp (key, "cwd") == 0)
174       {
175         if (!cmdline->priv->cwd)
176           cmdline->priv->cwd = g_variant_dup_bytestring (value, NULL);
177       }
178
179     else if (strcmp (key, "environ") == 0)
180       {
181         if (!cmdline->priv->environ)
182           cmdline->priv->environ =
183             g_variant_dup_bytestring_array (value, NULL);
184       }
185 }
186
187 static void
188 g_application_command_line_real_print_literal (GApplicationCommandLine *cmdline,
189                                                const gchar             *message)
190 {
191   g_print ("%s", message);
192 }
193
194 static void
195 g_application_command_line_real_printerr_literal (GApplicationCommandLine *cmdline,
196                                                   const gchar             *message)
197 {
198   g_printerr ("%s", message);
199 }
200
201 static GInputStream *
202 g_application_command_line_real_get_stdin (GApplicationCommandLine *cmdline)
203 {
204 #ifdef G_OS_UNIX
205   return g_unix_input_stream_new (0, FALSE);
206 #else
207   return g_win32_input_stream_new (GetStdHandle (STD_INPUT_HANDLE), FALSE);
208 #endif
209 }
210
211 static void
212 g_application_command_line_get_property (GObject    *object,
213                                          guint       prop_id,
214                                          GValue     *value,
215                                          GParamSpec *pspec)
216 {
217   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
218
219   switch (prop_id)
220     {
221     case PROP_ARGUMENTS:
222       g_value_set_variant (value, cmdline->priv->arguments);
223       break;
224
225     case PROP_PLATFORM_DATA:
226       g_value_set_variant (value, cmdline->priv->platform_data);
227       break;
228
229     case PROP_IS_REMOTE:
230       g_value_set_boolean (value, IS_REMOTE (cmdline));
231       break;
232
233     default:
234       g_assert_not_reached ();
235     }
236 }
237
238 static void
239 g_application_command_line_set_property (GObject      *object,
240                                          guint         prop_id,
241                                          const GValue *value,
242                                          GParamSpec   *pspec)
243 {
244   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
245
246   switch (prop_id)
247     {
248     case PROP_ARGUMENTS:
249       g_assert (cmdline->priv->arguments == NULL);
250       cmdline->priv->arguments = g_value_dup_variant (value);
251       break;
252
253     case PROP_PLATFORM_DATA:
254       g_assert (cmdline->priv->platform_data == NULL);
255       cmdline->priv->platform_data = g_value_dup_variant (value);
256       if (cmdline->priv->platform_data != NULL)
257         grok_platform_data (cmdline);
258       break;
259
260     default:
261       g_assert_not_reached ();
262     }
263 }
264
265 static void
266 g_application_command_line_finalize (GObject *object)
267 {
268   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
269
270   if (cmdline->priv->platform_data)
271     g_variant_unref (cmdline->priv->platform_data);
272   if (cmdline->priv->arguments)
273     g_variant_unref (cmdline->priv->arguments);
274
275   g_free (cmdline->priv->cwd);
276   g_strfreev (cmdline->priv->environ);
277
278   G_OBJECT_CLASS (g_application_command_line_parent_class)
279     ->finalize (object);
280 }
281
282 static void
283 g_application_command_line_init (GApplicationCommandLine *cmdline)
284 {
285   cmdline->priv = g_application_command_line_get_instance_private (cmdline);
286 }
287
288 static void
289 g_application_command_line_constructed (GObject *object)
290 {
291   GApplicationCommandLine *cmdline = G_APPLICATION_COMMAND_LINE (object);
292
293   if (IS_REMOTE (cmdline))
294     return;
295
296   /* In the local case, set cmd and environ */
297   if (!cmdline->priv->cwd)
298     cmdline->priv->cwd = g_get_current_dir ();
299
300   if (!cmdline->priv->environ)
301     cmdline->priv->environ = g_get_environ ();
302 }
303
304 static void
305 g_application_command_line_class_init (GApplicationCommandLineClass *class)
306 {
307   GObjectClass *object_class = G_OBJECT_CLASS (class);
308
309   object_class->get_property = g_application_command_line_get_property;
310   object_class->set_property = g_application_command_line_set_property;
311   object_class->finalize = g_application_command_line_finalize;
312   object_class->constructed = g_application_command_line_constructed;
313
314   class->printerr_literal = g_application_command_line_real_printerr_literal;
315   class->print_literal = g_application_command_line_real_print_literal;
316   class->get_stdin = g_application_command_line_real_get_stdin;
317
318   g_object_class_install_property (object_class, PROP_ARGUMENTS,
319     g_param_spec_variant ("arguments",
320                           P_("Commandline arguments"),
321                           P_("The commandline that caused this ::command-line signal emission"),
322                           G_VARIANT_TYPE_BYTESTRING_ARRAY, NULL,
323                           G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
324                           G_PARAM_STATIC_STRINGS));
325
326   g_object_class_install_property (object_class, PROP_PLATFORM_DATA,
327     g_param_spec_variant ("platform-data",
328                           P_("Platform data"),
329                           P_("Platform-specific data for the commandline"),
330                           G_VARIANT_TYPE ("a{sv}"), NULL,
331                           G_PARAM_WRITABLE | G_PARAM_CONSTRUCT_ONLY |
332                           G_PARAM_STATIC_STRINGS));
333
334   g_object_class_install_property (object_class, PROP_IS_REMOTE,
335     g_param_spec_boolean ("is-remote",
336                           P_("Is remote"),
337                           P_("TRUE if this is a remote commandline"),
338                           FALSE,
339                           G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
340 }
341
342
343 /**
344  * g_application_command_line_get_arguments:
345  * @cmdline: a #GApplicationCommandLine
346  * @argc: (out) (allow-none): the length of the arguments array, or %NULL
347  *
348  * Gets the list of arguments that was passed on the command line.
349  *
350  * The strings in the array may contain non-utf8 data.
351  *
352  * The return value is %NULL-terminated and should be freed using
353  * g_strfreev().
354  *
355  * Returns: (array length=argc) (transfer full): the string array
356  * containing the arguments (the argv)
357  *
358  * Since: 2.28
359  **/
360 gchar **
361 g_application_command_line_get_arguments (GApplicationCommandLine *cmdline,
362                                           int                     *argc)
363 {
364   gchar **argv;
365   gsize len;
366
367   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
368
369   argv = g_variant_dup_bytestring_array (cmdline->priv->arguments, &len);
370
371   if (argc)
372     *argc = len;
373
374   return argv;
375 }
376
377 /**
378  * g_application_command_line_get_stdin:
379  * @cmdline: a #GApplicationCommandLine
380  *
381  * Gets the stdin of the invoking process.
382  *
383  * The #GInputStream can be used to read data passed to the standard
384  * input of the invoking process.
385  * This doesn't work on all platforms.  Presently, it is only available
386  * on UNIX when using a DBus daemon capable of passing file descriptors.
387  * If stdin is not available then %NULL will be returned.  In the
388  * future, support may be expanded to other platforms.
389  *
390  * You must only call this function once per commandline invocation.
391  *
392  * Returns: (transfer full): a #GInputStream for stdin
393  *
394  * Since: 2.34
395  **/
396 GInputStream *
397 g_application_command_line_get_stdin (GApplicationCommandLine *cmdline)
398 {
399   return G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)->get_stdin (cmdline);
400 }
401
402 /**
403  * g_application_command_line_get_cwd:
404  * @cmdline: a #GApplicationCommandLine
405  *
406  * Gets the working directory of the command line invocation.
407  * The string may contain non-utf8 data.
408  *
409  * It is possible that the remote application did not send a working
410  * directory, so this may be %NULL.
411  *
412  * The return value should not be modified or freed and is valid for as
413  * long as @cmdline exists.
414  *
415  * Returns: the current directory, or %NULL
416  *
417  * Since: 2.28
418  **/
419 const gchar *
420 g_application_command_line_get_cwd (GApplicationCommandLine *cmdline)
421 {
422   return cmdline->priv->cwd;
423 }
424
425 /**
426  * g_application_command_line_get_environ:
427  * @cmdline: a #GApplicationCommandLine
428  *
429  * Gets the contents of the 'environ' variable of the command line
430  * invocation, as would be returned by g_get_environ(), ie as a
431  * %NULL-terminated list of strings in the form 'NAME=VALUE'.
432  * The strings may contain non-utf8 data.
433  *
434  * The remote application usually does not send an environment.  Use
435  * %G_APPLICATION_SEND_ENVIRONMENT to affect that.  Even with this flag
436  * set it is possible that the environment is still not available (due
437  * to invocation messages from other applications).
438  *
439  * The return value should not be modified or freed and is valid for as
440  * long as @cmdline exists.
441  *
442  * See g_application_command_line_getenv() if you are only interested
443  * in the value of a single environment variable.
444  *
445  * Returns: (array zero-terminated=1) (transfer none): the environment
446  * strings, or %NULL if they were not sent
447  *
448  * Since: 2.28
449  **/
450 const gchar * const *
451 g_application_command_line_get_environ (GApplicationCommandLine *cmdline)
452 {
453   return (const gchar **)cmdline->priv->environ;
454 }
455
456 /**
457  * g_application_command_line_getenv:
458  * @cmdline: a #GApplicationCommandLine
459  * @name: the environment variable to get
460  *
461  * Gets the value of a particular environment variable of the command
462  * line invocation, as would be returned by g_getenv().  The strings may
463  * contain non-utf8 data.
464  *
465  * The remote application usually does not send an environment.  Use
466  * %G_APPLICATION_SEND_ENVIRONMENT to affect that.  Even with this flag
467  * set it is possible that the environment is still not available (due
468  * to invocation messages from other applications).
469  *
470  * The return value should not be modified or freed and is valid for as
471  * long as @cmdline exists.
472  *
473  * Returns: the value of the variable, or %NULL if unset or unsent
474  *
475  * Since: 2.28
476  **/
477 const gchar *
478 g_application_command_line_getenv (GApplicationCommandLine *cmdline,
479                                    const gchar             *name)
480 {
481   gint length = strlen (name);
482   gint i;
483
484   /* TODO: expand on windows */
485   if (cmdline->priv->environ)
486     for (i = 0; cmdline->priv->environ[i]; i++)
487       if (strncmp (cmdline->priv->environ[i], name, length) == 0 &&
488           cmdline->priv->environ[i][length] == '=')
489         return cmdline->priv->environ[i] + length + 1;
490
491   return NULL;
492 }
493
494 /**
495  * g_application_command_line_get_is_remote:
496  * @cmdline: a #GApplicationCommandLine
497  *
498  * Determines if @cmdline represents a remote invocation.
499  *
500  * Returns: %TRUE if the invocation was remote
501  *
502  * Since: 2.28
503  **/
504 gboolean
505 g_application_command_line_get_is_remote (GApplicationCommandLine *cmdline)
506 {
507   return IS_REMOTE (cmdline);
508 }
509
510 /**
511  * g_application_command_line_print:
512  * @cmdline: a #GApplicationCommandLine
513  * @format: a printf-style format string
514  * @...: arguments, as per @format
515  *
516  * Formats a message and prints it using the stdout print handler in the
517  * invoking process.
518  *
519  * If @cmdline is a local invocation then this is exactly equivalent to
520  * g_print().  If @cmdline is remote then this is equivalent to calling
521  * g_print() in the invoking process.
522  *
523  * Since: 2.28
524  **/
525 void
526 g_application_command_line_print (GApplicationCommandLine *cmdline,
527                                   const gchar             *format,
528                                   ...)
529 {
530   gchar *message;
531   va_list ap;
532
533   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
534   g_return_if_fail (format != NULL);
535
536   va_start (ap, format);
537   message = g_strdup_vprintf (format, ap);
538   va_end (ap);
539
540   G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
541     ->print_literal (cmdline, message);
542   g_free (message);
543 }
544
545 /**
546  * g_application_command_line_printerr:
547  * @cmdline: a #GApplicationCommandLine
548  * @format: a printf-style format string
549  * @...: arguments, as per @format
550  *
551  * Formats a message and prints it using the stderr print handler in the
552  * invoking process.
553  *
554  * If @cmdline is a local invocation then this is exactly equivalent to
555  * g_printerr().  If @cmdline is remote then this is equivalent to
556  * calling g_printerr() in the invoking process.
557  *
558  * Since: 2.28
559  **/
560 void
561 g_application_command_line_printerr (GApplicationCommandLine *cmdline,
562                                      const gchar             *format,
563                                      ...)
564 {
565   gchar *message;
566   va_list ap;
567
568   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
569   g_return_if_fail (format != NULL);
570
571   va_start (ap, format);
572   message = g_strdup_vprintf (format, ap);
573   va_end (ap);
574
575   G_APPLICATION_COMMAND_LINE_GET_CLASS (cmdline)
576     ->printerr_literal (cmdline, message);
577   g_free (message);
578 }
579
580 /**
581  * g_application_command_line_set_exit_status:
582  * @cmdline: a #GApplicationCommandLine
583  * @exit_status: the exit status
584  *
585  * Sets the exit status that will be used when the invoking process
586  * exits.
587  *
588  * The return value of the #GApplication::command-line signal is
589  * passed to this function when the handler returns.  This is the usual
590  * way of setting the exit status.
591  *
592  * In the event that you want the remote invocation to continue running
593  * and want to decide on the exit status in the future, you can use this
594  * call.  For the case of a remote invocation, the remote process will
595  * typically exit when the last reference is dropped on @cmdline.  The
596  * exit status of the remote process will be equal to the last value
597  * that was set with this function.
598  *
599  * In the case that the commandline invocation is local, the situation
600  * is slightly more complicated.  If the commandline invocation results
601  * in the mainloop running (ie: because the use-count of the application
602  * increased to a non-zero value) then the application is considered to
603  * have been 'successful' in a certain sense, and the exit status is
604  * always zero.  If the application use count is zero, though, the exit
605  * status of the local #GApplicationCommandLine is used.
606  *
607  * Since: 2.28
608  **/
609 void
610 g_application_command_line_set_exit_status (GApplicationCommandLine *cmdline,
611                                             int                      exit_status)
612 {
613   g_return_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline));
614
615   cmdline->priv->exit_status = exit_status;
616 }
617
618 /**
619  * g_application_command_line_get_exit_status:
620  * @cmdline: a #GApplicationCommandLine
621  *
622  * Gets the exit status of @cmdline.  See
623  * g_application_command_line_set_exit_status() for more information.
624  *
625  * Returns: the exit status
626  *
627  * Since: 2.28
628  **/
629 int
630 g_application_command_line_get_exit_status (GApplicationCommandLine *cmdline)
631 {
632   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), -1);
633
634   return cmdline->priv->exit_status;
635 }
636
637 /**
638  * g_application_command_line_get_platform_data:
639  * @cmdline: #GApplicationCommandLine
640  *
641  * Gets the platform data associated with the invocation of @cmdline.
642  *
643  * This is a #GVariant dictionary containing information about the
644  * context in which the invocation occurred.  It typically contains
645  * information like the current working directory and the startup
646  * notification ID.
647  *
648  * For local invocation, it will be %NULL.
649  *
650  * Returns: (allow-none): the platform data, or %NULL
651  *
652  * Since: 2.28
653  **/
654 GVariant *
655 g_application_command_line_get_platform_data (GApplicationCommandLine *cmdline)
656 {
657   g_return_val_if_fail (G_IS_APPLICATION_COMMAND_LINE (cmdline), NULL);
658
659   if (cmdline->priv->platform_data)
660     return g_variant_ref (cmdline->priv->platform_data);
661   else
662       return NULL;
663 }
664
665 /**
666  * g_application_command_line_create_file_for_arg:
667  * @cmdline: a #GApplicationCommandLine
668  * @arg: an argument from @cmdline
669  *
670  * Creates a #GFile corresponding to a filename that was given as part
671  * of the invocation of @cmdline.
672  *
673  * This differs from g_file_new_for_commandline_arg() in that it
674  * resolves relative pathnames using the current working directory of
675  * the invoking process rather than the local process.
676  *
677  * Returns: (transfer full): a new #GFile
678  *
679  * Since: 2.36
680  **/
681 GFile *
682 g_application_command_line_create_file_for_arg (GApplicationCommandLine *cmdline,
683                                                 const gchar             *arg)
684 {
685   g_return_val_if_fail (arg != NULL, NULL);
686
687   if (cmdline->priv->cwd)
688     return g_file_new_for_commandline_arg_and_cwd (arg, cmdline->priv->cwd);
689
690   g_warning ("Requested creation of GFile for commandline invocation that did not send cwd. "
691              "Using cwd of local process to resolve relative path names.");
692
693   return g_file_new_for_commandline_arg (arg);
694 }