Update the year in the *.rc.in files
[platform/upstream/glib.git] / gio / gdbus-tool.c
1 /* GDBus - GLib D-Bus Library
2  *
3  * Copyright (C) 2008-2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General
16  * Public License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place, Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: David Zeuthen <davidz@redhat.com>
21  */
22
23 #include "config.h"
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdio.h>
28 #include <locale.h>
29
30 #include <gio/gio.h>
31
32 #include <gi18n.h>
33
34 /* ---------------------------------------------------------------------------------------------------- */
35
36 G_GNUC_UNUSED static void completion_debug (const gchar *format, ...);
37
38 /* Uncomment to get debug traces in /tmp/gdbus-completion-debug.txt (nice
39  * to not have it interfere with stdout/stderr)
40  */
41 #if 0
42 G_GNUC_UNUSED static void
43 completion_debug (const gchar *format, ...)
44 {
45   va_list var_args;
46   gchar *s;
47   static FILE *f = NULL;
48
49   va_start (var_args, format);
50   s = g_strdup_vprintf (format, var_args);
51   if (f == NULL)
52     {
53       f = fopen ("/tmp/gdbus-completion-debug.txt", "a+");
54     }
55   fprintf (f, "%s\n", s);
56   g_free (s);
57 }
58 #else
59 static void
60 completion_debug (const gchar *format, ...)
61 {
62 }
63 #endif
64
65 /* ---------------------------------------------------------------------------------------------------- */
66
67
68 static void
69 remove_arg (gint num, gint *argc, gchar **argv[])
70 {
71   gint n;
72
73   g_assert (num <= (*argc));
74
75   for (n = num; (*argv)[n] != NULL; n++)
76     (*argv)[n] = (*argv)[n+1];
77   (*argv)[n] = NULL;
78   (*argc) = (*argc) - 1;
79 }
80
81 static void
82 usage (gint *argc, gchar **argv[], gboolean use_stdout)
83 {
84   GOptionContext *o;
85   gchar *s;
86   gchar *program_name;
87
88   o = g_option_context_new (_("COMMAND"));
89   g_option_context_set_help_enabled (o, FALSE);
90   /* Ignore parsing result */
91   g_option_context_parse (o, argc, argv, NULL);
92   program_name = g_path_get_basename ((*argv)[0]);
93   s = g_strdup_printf (_("Commands:\n"
94                          "  help         Shows this information\n"
95                          "  introspect   Introspect a remote object\n"
96                          "  monitor      Monitor a remote object\n"
97                          "  call         Invoke a method on a remote object\n"
98                          "  emit         Emit a signal\n"
99                          "\n"
100                          "Use \"%s COMMAND --help\" to get help on each command.\n"),
101                        program_name);
102   g_free (program_name);
103   g_option_context_set_description (o, s);
104   g_free (s);
105   s = g_option_context_get_help (o, FALSE, NULL);
106   if (use_stdout)
107     g_print ("%s", s);
108   else
109     g_printerr ("%s", s);
110   g_free (s);
111   g_option_context_free (o);
112 }
113
114 static void
115 modify_argv0_for_command (gint *argc, gchar **argv[], const gchar *command)
116 {
117   gchar *s;
118   gchar *program_name;
119
120   /* TODO:
121    *  1. get a g_set_prgname() ?; or
122    *  2. save old argv[0] and restore later
123    */
124
125   g_assert (g_strcmp0 ((*argv)[1], command) == 0);
126   remove_arg (1, argc, argv);
127
128   program_name = g_path_get_basename ((*argv)[0]);
129   s = g_strdup_printf ("%s %s", (*argv)[0], command);
130   (*argv)[0] = s;
131   g_free (program_name);
132 }
133
134 /* ---------------------------------------------------------------------------------------------------- */
135
136 static void
137 print_methods (GDBusConnection *c,
138                const gchar *name,
139                const gchar *path)
140 {
141   GVariant *result;
142   GError *error;
143   const gchar *xml_data;
144   GDBusNodeInfo *node;
145   guint n;
146   guint m;
147
148   error = NULL;
149   result = g_dbus_connection_call_sync (c,
150                                         name,
151                                         path,
152                                         "org.freedesktop.DBus.Introspectable",
153                                         "Introspect",
154                                         NULL,
155                                         G_VARIANT_TYPE ("(s)"),
156                                         G_DBUS_CALL_FLAGS_NONE,
157                                         3000, /* 3 secs */
158                                         NULL,
159                                         &error);
160   if (result == NULL)
161     {
162       g_printerr (_("Error: %s\n"), error->message);
163       g_error_free (error);
164       goto out;
165     }
166   g_variant_get (result, "(&s)", &xml_data);
167
168   error = NULL;
169   node = g_dbus_node_info_new_for_xml (xml_data, &error);
170   g_variant_unref (result);
171   if (node == NULL)
172     {
173       g_printerr (_("Error parsing introspection XML: %s\n"), error->message);
174       g_error_free (error);
175       goto out;
176     }
177
178   for (n = 0; node->interfaces != NULL && node->interfaces[n] != NULL; n++)
179     {
180       const GDBusInterfaceInfo *iface = node->interfaces[n];
181       for (m = 0; iface->methods != NULL && iface->methods[m] != NULL; m++)
182         {
183           const GDBusMethodInfo *method = iface->methods[m];
184           g_print ("%s.%s \n", iface->name, method->name);
185         }
186     }
187   g_dbus_node_info_unref (node);
188
189  out:
190   ;
191 }
192
193 static void
194 print_paths (GDBusConnection *c,
195              const gchar *name,
196              const gchar *path)
197 {
198   GVariant *result;
199   GError *error;
200   const gchar *xml_data;
201   GDBusNodeInfo *node;
202   guint n;
203
204   error = NULL;
205   result = g_dbus_connection_call_sync (c,
206                                         name,
207                                         path,
208                                         "org.freedesktop.DBus.Introspectable",
209                                         "Introspect",
210                                         NULL,
211                                         G_VARIANT_TYPE ("(s)"),
212                                         G_DBUS_CALL_FLAGS_NONE,
213                                         3000, /* 3 secs */
214                                         NULL,
215                                         &error);
216   if (result == NULL)
217     {
218       g_printerr (_("Error: %s\n"), error->message);
219       g_error_free (error);
220       goto out;
221     }
222   g_variant_get (result, "(&s)", &xml_data);
223
224   //g_printerr ("xml=`%s'", xml_data);
225
226   error = NULL;
227   node = g_dbus_node_info_new_for_xml (xml_data, &error);
228   g_variant_unref (result);
229   if (node == NULL)
230     {
231       g_printerr (_("Error parsing introspection XML: %s\n"), error->message);
232       g_error_free (error);
233       goto out;
234     }
235
236   //g_printerr ("bar `%s'\n", path);
237
238   if (node->interfaces != NULL)
239     g_print ("%s \n", path);
240
241   for (n = 0; node->nodes != NULL && node->nodes[n] != NULL; n++)
242     {
243       gchar *s;
244
245       //g_printerr ("foo `%s'\n", node->nodes[n].path);
246
247       if (g_strcmp0 (path, "/") == 0)
248         s = g_strdup_printf ("/%s", node->nodes[n]->path);
249       else
250         s = g_strdup_printf ("%s/%s", path, node->nodes[n]->path);
251
252       print_paths (c, name, s);
253
254       g_free (s);
255     }
256   g_dbus_node_info_unref (node);
257
258  out:
259   ;
260 }
261
262 static void
263 print_names (GDBusConnection *c,
264              gboolean         include_unique_names)
265 {
266   GVariant *result;
267   GError *error;
268   GVariantIter *iter;
269   gchar *str;
270   GHashTable *name_set;
271   GList *keys;
272   GList *l;
273
274   name_set = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
275
276   error = NULL;
277   result = g_dbus_connection_call_sync (c,
278                                         "org.freedesktop.DBus",
279                                         "/org/freedesktop/DBus",
280                                         "org.freedesktop.DBus",
281                                         "ListNames",
282                                         NULL,
283                                         G_VARIANT_TYPE ("(as)"),
284                                         G_DBUS_CALL_FLAGS_NONE,
285                                         3000, /* 3 secs */
286                                         NULL,
287                                         &error);
288   if (result == NULL)
289     {
290       g_printerr (_("Error: %s\n"), error->message);
291       g_error_free (error);
292       goto out;
293     }
294   g_variant_get (result, "(as)", &iter);
295   while (g_variant_iter_loop (iter, "s", &str))
296     g_hash_table_insert (name_set, g_strdup (str), NULL);
297   g_variant_iter_free (iter);
298   g_variant_unref (result);
299
300   error = NULL;
301   result = g_dbus_connection_call_sync (c,
302                                         "org.freedesktop.DBus",
303                                         "/org/freedesktop/DBus",
304                                         "org.freedesktop.DBus",
305                                         "ListActivatableNames",
306                                         NULL,
307                                         G_VARIANT_TYPE ("(as)"),
308                                         G_DBUS_CALL_FLAGS_NONE,
309                                         3000, /* 3 secs */
310                                         NULL,
311                                         &error);
312   if (result == NULL)
313     {
314       g_printerr (_("Error: %s\n"), error->message);
315       g_error_free (error);
316       goto out;
317     }
318   g_variant_get (result, "(as)", &iter);
319   while (g_variant_iter_loop (iter, "s", &str))
320     g_hash_table_insert (name_set, g_strdup (str), NULL);
321   g_variant_iter_free (iter);
322   g_variant_unref (result);
323
324   keys = g_hash_table_get_keys (name_set);
325   keys = g_list_sort (keys, (GCompareFunc) g_strcmp0);
326   for (l = keys; l != NULL; l = l->next)
327     {
328       const gchar *name = l->data;
329       if (!include_unique_names && g_str_has_prefix (name, ":"))
330         continue;
331
332       g_print ("%s \n", name);
333     }
334   g_list_free (keys);
335
336  out:
337   g_hash_table_unref (name_set);
338 }
339
340 /* ---------------------------------------------------------------------------------------------------- */
341
342 static gboolean  opt_connection_system  = FALSE;
343 static gboolean  opt_connection_session = FALSE;
344 static gchar    *opt_connection_address = NULL;
345
346 static const GOptionEntry connection_entries[] =
347 {
348   { "system", 'y', 0, G_OPTION_ARG_NONE, &opt_connection_system, N_("Connect to the system bus"), NULL},
349   { "session", 'e', 0, G_OPTION_ARG_NONE, &opt_connection_session, N_("Connect to the session bus"), NULL},
350   { "address", 'a', 0, G_OPTION_ARG_STRING, &opt_connection_address, N_("Connect to given D-Bus address"), NULL},
351   { NULL }
352 };
353
354 static GOptionGroup *
355 connection_get_group (void)
356 {
357   static GOptionGroup *g;
358
359   g = g_option_group_new ("connection",
360                           N_("Connection Endpoint Options:"),
361                           N_("Options specifying the connection endpoint"),
362                           NULL,
363                           NULL);
364   g_option_group_set_translation_domain (g, GETTEXT_PACKAGE);
365   g_option_group_add_entries (g, connection_entries);
366
367   return g;
368 }
369
370 static GDBusConnection *
371 connection_get_dbus_connection (GError **error)
372 {
373   GDBusConnection *c;
374
375   c = NULL;
376
377   /* First, ensure we have exactly one connect */
378   if (!opt_connection_system && !opt_connection_session && opt_connection_address == NULL)
379     {
380       g_set_error (error,
381                    G_IO_ERROR,
382                    G_IO_ERROR_FAILED,
383                    _("No connection endpoint specified"));
384       goto out;
385     }
386   else if ((opt_connection_system && (opt_connection_session || opt_connection_address != NULL)) ||
387            (opt_connection_session && (opt_connection_system || opt_connection_address != NULL)) ||
388            (opt_connection_address != NULL && (opt_connection_system || opt_connection_session)))
389     {
390       g_set_error (error,
391                    G_IO_ERROR,
392                    G_IO_ERROR_FAILED,
393                    _("Multiple connection endpoints specified"));
394       goto out;
395     }
396
397   if (opt_connection_system)
398     {
399       c = g_bus_get_sync (G_BUS_TYPE_SYSTEM, NULL, error);
400     }
401   else if (opt_connection_session)
402     {
403       c = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, error);
404     }
405   else if (opt_connection_address != NULL)
406     {
407       c = g_dbus_connection_new_for_address_sync (opt_connection_address,
408                                                   G_DBUS_CONNECTION_FLAGS_AUTHENTICATION_CLIENT,
409                                                   NULL, /* GDBusAuthObserver */
410                                                   NULL, /* GCancellable */
411                                                   error);
412     }
413
414  out:
415   return c;
416 }
417
418 /* ---------------------------------------------------------------------------------------------------- */
419
420 static GPtrArray *
421 call_helper_get_method_in_signature (GDBusConnection  *c,
422                                      const gchar      *dest,
423                                      const gchar      *path,
424                                      const gchar      *interface_name,
425                                      const gchar      *method_name,
426                                      GError          **error)
427 {
428   GPtrArray *ret;
429   GVariant *result;
430   GDBusNodeInfo *node_info;
431   const gchar *xml_data;
432   GDBusInterfaceInfo *interface_info;
433   GDBusMethodInfo *method_info;
434   guint n;
435
436   ret = NULL;
437   result = NULL;
438   node_info = NULL;
439
440   result = g_dbus_connection_call_sync (c,
441                                         dest,
442                                         path,
443                                         "org.freedesktop.DBus.Introspectable",
444                                         "Introspect",
445                                         NULL,
446                                         G_VARIANT_TYPE ("(s)"),
447                                         G_DBUS_CALL_FLAGS_NONE,
448                                         3000, /* 3 secs */
449                                         NULL,
450                                         error);
451   if (result == NULL)
452     goto out;
453
454   g_variant_get (result, "(&s)", &xml_data);
455   node_info = g_dbus_node_info_new_for_xml (xml_data, error);
456   if (node_info == NULL)
457       goto out;
458
459   interface_info = g_dbus_node_info_lookup_interface (node_info, interface_name);
460   if (interface_info == NULL)
461     {
462       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
463                    _("Warning: According to introspection data, interface `%s' does not exist\n"),
464                    interface_name);
465       goto out;
466     }
467
468   method_info = g_dbus_interface_info_lookup_method (interface_info, method_name);
469   if (method_info == NULL)
470     {
471       g_set_error (error, G_IO_ERROR, G_IO_ERROR_FAILED,
472                    _("Warning: According to introspection data, method `%s' does not exist on interface `%s'\n"),
473                    method_name,
474                    interface_name);
475       goto out;
476     }
477
478   ret = g_ptr_array_new_with_free_func ((GDestroyNotify) g_variant_type_free);
479   for (n = 0; method_info->in_args != NULL && method_info->in_args[n] != NULL; n++)
480     {
481       g_ptr_array_add (ret, g_variant_type_new (method_info->in_args[n]->signature));
482     }
483
484  out:
485   if (node_info != NULL)
486     g_dbus_node_info_unref (node_info);
487   if (result != NULL)
488     g_variant_unref (result);
489
490   return ret;
491 }
492
493 /* ---------------------------------------------------------------------------------------------------- */
494
495 static GVariant *
496 _g_variant_parse_me_harder (GVariantType   *type,
497                             const gchar    *given_str,
498                             GError        **error)
499 {
500   GVariant *value;
501   gchar *s;
502   guint n;
503   GString *str;
504
505   str = g_string_new ("\"");
506   for (n = 0; given_str[n] != '\0'; n++)
507     {
508       if (G_UNLIKELY (given_str[n] == '\"'))
509         g_string_append (str, "\\\"");
510       else
511         g_string_append_c (str, given_str[n]);
512     }
513   g_string_append_c (str, '"');
514   s = g_string_free (str, FALSE);
515
516   value = g_variant_parse (type,
517                            s,
518                            NULL,
519                            NULL,
520                            error);
521   g_free (s);
522
523   return value;
524 }
525
526 /* ---------------------------------------------------------------------------------------------------- */
527
528 static gchar *opt_emit_dest = NULL;
529 static gchar *opt_emit_object_path = NULL;
530 static gchar *opt_emit_signal = NULL;
531
532 static const GOptionEntry emit_entries[] =
533 {
534   { "dest", 'd', 0, G_OPTION_ARG_STRING, &opt_emit_dest, N_("Optional destination for signal (unique name)"), NULL},
535   { "object-path", 'o', 0, G_OPTION_ARG_STRING, &opt_emit_object_path, N_("Object path to emit signal on"), NULL},
536   { "signal", 's', 0, G_OPTION_ARG_STRING, &opt_emit_signal, N_("Signal and interface name"), NULL},
537   { NULL }
538 };
539
540 static gboolean
541 handle_emit (gint        *argc,
542              gchar      **argv[],
543              gboolean     request_completion,
544              const gchar *completion_cur,
545              const gchar *completion_prev)
546 {
547   gint ret;
548   GOptionContext *o;
549   gchar *s;
550   GError *error;
551   GDBusConnection *c;
552   GVariant *parameters;
553   gchar *interface_name;
554   gchar *signal_name;
555   GVariantBuilder builder;
556   guint n;
557
558   ret = FALSE;
559   c = NULL;
560   parameters = NULL;
561   interface_name = NULL;
562   signal_name = NULL;
563
564   modify_argv0_for_command (argc, argv, "emit");
565
566   o = g_option_context_new (NULL);
567   g_option_context_set_help_enabled (o, FALSE);
568   g_option_context_set_summary (o, _("Emit a signal."));
569   g_option_context_add_main_entries (o, emit_entries, GETTEXT_PACKAGE);
570   g_option_context_add_group (o, connection_get_group ());
571
572   if (!g_option_context_parse (o, argc, argv, NULL))
573     {
574       if (!request_completion)
575         {
576           s = g_option_context_get_help (o, FALSE, NULL);
577           g_printerr ("%s", s);
578           g_free (s);
579           goto out;
580         }
581     }
582
583   error = NULL;
584   c = connection_get_dbus_connection (&error);
585   if (c == NULL)
586     {
587       if (request_completion)
588         {
589           if (g_strcmp0 (completion_prev, "--address") == 0)
590             {
591               g_print ("unix:\n"
592                        "tcp:\n"
593                        "nonce-tcp:\n");
594             }
595           else
596             {
597               g_print ("--system \n--session \n--address \n");
598             }
599         }
600       else
601         {
602           g_printerr (_("Error connecting: %s\n"), error->message);
603           g_error_free (error);
604         }
605       goto out;
606     }
607
608   /* All done with completion now */
609   if (request_completion)
610     goto out;
611
612   if (opt_emit_object_path == NULL)
613     {
614       g_printerr (_("Error: object path not specified.\n"));
615       goto out;
616     }
617   if (!g_variant_is_object_path (opt_emit_object_path))
618     {
619       g_printerr (_("Error: %s is not a valid object path\n"), opt_emit_object_path);
620       goto out;
621     }
622
623   if (opt_emit_signal == NULL)
624     {
625       g_printerr (_("Error: signal not specified.\n"));
626       goto out;
627     }
628   s = strrchr (opt_emit_signal, '.');
629   signal_name = g_strdup (s + 1);
630   interface_name = g_strndup (opt_emit_signal, s - opt_emit_signal);
631
632   if (!g_dbus_is_interface_name (interface_name))
633     {
634       g_printerr (_("Error: %s is not a valid interface name\n"), interface_name);
635       goto out;
636     }
637
638   if (!g_dbus_is_member_name (signal_name))
639     {
640       g_printerr (_("Error: %s is not a valid member name\n"), signal_name);
641       goto out;
642     }
643
644   if (opt_emit_dest != NULL && !g_dbus_is_unique_name (opt_emit_dest))
645     {
646       g_printerr (_("Error: %s is not a valid unique bus name.\n"), opt_emit_dest);
647       goto out;
648     }
649
650   /* Read parameters */
651   g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
652   for (n = 1; n < (guint) *argc; n++)
653     {
654       GVariant *value;
655
656       error = NULL;
657       value = g_variant_parse (NULL,
658                                (*argv)[n],
659                                NULL,
660                                NULL,
661                                &error);
662       if (value == NULL)
663         {
664           g_error_free (error);
665           error = NULL;
666           value = _g_variant_parse_me_harder (NULL, (*argv)[n], &error);
667           if (value == NULL)
668             {
669               g_printerr (_("Error parsing parameter %d: %s\n"),
670                           n,
671                           error->message);
672               g_error_free (error);
673               g_variant_builder_clear (&builder);
674               goto out;
675             }
676         }
677       g_variant_builder_add_value (&builder, value);
678     }
679   parameters = g_variant_builder_end (&builder);
680
681   if (parameters != NULL)
682     parameters = g_variant_ref_sink (parameters);
683   if (!g_dbus_connection_emit_signal (c,
684                                       opt_emit_dest,
685                                       opt_emit_object_path,
686                                       interface_name,
687                                       signal_name,
688                                       parameters,
689                                       &error))
690     {
691       g_printerr (_("Error: %s\n"), error->message);
692       g_error_free (error);
693       goto out;
694     }
695
696   if (!g_dbus_connection_flush_sync (c, NULL, &error))
697     {
698       g_printerr (_("Error flushing connection: %s\n"), error->message);
699       g_error_free (error);
700       goto out;
701     }
702
703   ret = TRUE;
704
705  out:
706   if (c != NULL)
707     g_object_unref (c);
708   if (parameters != NULL)
709     g_variant_unref (parameters);
710   g_free (interface_name);
711   g_free (signal_name);
712   g_option_context_free (o);
713   return ret;
714 }
715
716 /* ---------------------------------------------------------------------------------------------------- */
717
718 static gchar *opt_call_dest = NULL;
719 static gchar *opt_call_object_path = NULL;
720 static gchar *opt_call_method = NULL;
721 static gint opt_call_timeout = -1;
722
723 static const GOptionEntry call_entries[] =
724 {
725   { "dest", 'd', 0, G_OPTION_ARG_STRING, &opt_call_dest, N_("Destination name to invoke method on"), NULL},
726   { "object-path", 'o', 0, G_OPTION_ARG_STRING, &opt_call_object_path, N_("Object path to invoke method on"), NULL},
727   { "method", 'm', 0, G_OPTION_ARG_STRING, &opt_call_method, N_("Method and interface name"), NULL},
728   { "timeout", 't', 0, G_OPTION_ARG_INT, &opt_call_timeout, N_("Timeout in seconds"), NULL},
729   { NULL }
730 };
731
732 static gboolean
733 handle_call (gint        *argc,
734              gchar      **argv[],
735              gboolean     request_completion,
736              const gchar *completion_cur,
737              const gchar *completion_prev)
738 {
739   gint ret;
740   GOptionContext *o;
741   gchar *s;
742   GError *error;
743   GDBusConnection *c;
744   GVariant *parameters;
745   gchar *interface_name;
746   gchar *method_name;
747   GVariant *result;
748   GPtrArray *in_signature_types;
749   gboolean complete_names;
750   gboolean complete_paths;
751   gboolean complete_methods;
752   GVariantBuilder builder;
753   guint n;
754
755   ret = FALSE;
756   c = NULL;
757   parameters = NULL;
758   interface_name = NULL;
759   method_name = NULL;
760   result = NULL;
761   in_signature_types = NULL;
762
763   modify_argv0_for_command (argc, argv, "call");
764
765   o = g_option_context_new (NULL);
766   g_option_context_set_help_enabled (o, FALSE);
767   g_option_context_set_summary (o, _("Invoke a method on a remote object."));
768   g_option_context_add_main_entries (o, call_entries, GETTEXT_PACKAGE);
769   g_option_context_add_group (o, connection_get_group ());
770
771   complete_names = FALSE;
772   if (request_completion && *argc > 1 && g_strcmp0 ((*argv)[(*argc)-1], "--dest") == 0)
773     {
774       complete_names = TRUE;
775       remove_arg ((*argc) - 1, argc, argv);
776     }
777
778   complete_paths = FALSE;
779   if (request_completion && *argc > 1 && g_strcmp0 ((*argv)[(*argc)-1], "--object-path") == 0)
780     {
781       complete_paths = TRUE;
782       remove_arg ((*argc) - 1, argc, argv);
783     }
784
785   complete_methods = FALSE;
786   if (request_completion && *argc > 1 && g_strcmp0 ((*argv)[(*argc)-1], "--method") == 0)
787     {
788       complete_methods = TRUE;
789       remove_arg ((*argc) - 1, argc, argv);
790     }
791
792   if (!g_option_context_parse (o, argc, argv, NULL))
793     {
794       if (!request_completion)
795         {
796           s = g_option_context_get_help (o, FALSE, NULL);
797           g_printerr ("%s", s);
798           g_free (s);
799           goto out;
800         }
801     }
802
803   error = NULL;
804   c = connection_get_dbus_connection (&error);
805   if (c == NULL)
806     {
807       if (request_completion)
808         {
809           if (g_strcmp0 (completion_prev, "--address") == 0)
810             {
811               g_print ("unix:\n"
812                        "tcp:\n"
813                        "nonce-tcp:\n");
814             }
815           else
816             {
817               g_print ("--system \n--session \n--address \n");
818             }
819         }
820       else
821         {
822           g_printerr (_("Error connecting: %s\n"), error->message);
823           g_error_free (error);
824         }
825       goto out;
826     }
827
828   /* validate and complete destination (bus name) */
829   if (g_dbus_connection_get_unique_name (c) != NULL)
830     {
831       /* this only makes sense on message bus connections */
832       if (complete_names)
833         {
834           print_names (c, FALSE);
835           goto out;
836         }
837       if (opt_call_dest == NULL)
838         {
839           if (request_completion)
840             g_print ("--dest \n");
841           else
842             g_printerr (_("Error: Destination is not specified\n"));
843           goto out;
844         }
845       if (request_completion && g_strcmp0 ("--dest", completion_prev) == 0)
846         {
847           print_names (c, g_str_has_prefix (opt_call_dest, ":"));
848           goto out;
849         }
850     }
851
852   /* validate and complete object path */
853   if (complete_paths)
854     {
855       print_paths (c, opt_call_dest, "/");
856       goto out;
857     }
858   if (opt_call_object_path == NULL)
859     {
860       if (request_completion)
861         g_print ("--object-path \n");
862       else
863         g_printerr (_("Error: Object path is not specified\n"));
864       goto out;
865     }
866   if (request_completion && g_strcmp0 ("--object-path", completion_prev) == 0)
867     {
868       gchar *p;
869       s = g_strdup (opt_call_object_path);
870       p = strrchr (s, '/');
871       if (p != NULL)
872         {
873           if (p == s)
874             p++;
875           *p = '\0';
876         }
877       print_paths (c, opt_call_dest, s);
878       g_free (s);
879       goto out;
880     }
881   if (!request_completion && !g_variant_is_object_path (opt_call_object_path))
882     {
883       g_printerr (_("Error: %s is not a valid object path\n"), opt_call_object_path);
884       goto out;
885     }
886
887   /* validate and complete method (interface + method name) */
888   if (complete_methods)
889     {
890       print_methods (c, opt_call_dest, opt_call_object_path);
891       goto out;
892     }
893   if (opt_call_method == NULL)
894     {
895       if (request_completion)
896         g_print ("--method \n");
897       else
898         g_printerr (_("Error: Method name is not specified\n"));
899       goto out;
900     }
901   if (request_completion && g_strcmp0 ("--method", completion_prev) == 0)
902     {
903       print_methods (c, opt_call_dest, opt_call_object_path);
904       goto out;
905     }
906   s = strrchr (opt_call_method, '.');
907   if (!request_completion && s == NULL)
908     {
909       g_printerr (_("Error: Method name `%s' is invalid\n"), opt_call_method);
910       goto out;
911     }
912   method_name = g_strdup (s + 1);
913   interface_name = g_strndup (opt_call_method, s - opt_call_method);
914
915   /* All done with completion now */
916   if (request_completion)
917     goto out;
918
919   /* Introspect, for easy conversion - it's not fatal if we can't do this */
920   in_signature_types = call_helper_get_method_in_signature (c,
921                                                             opt_call_dest,
922                                                             opt_call_object_path,
923                                                             interface_name,
924                                                             method_name,
925                                                             &error);
926   if (in_signature_types == NULL)
927     {
928       //g_printerr ("Error getting introspection data: %s\n", error->message);
929       g_error_free (error);
930       error = NULL;
931     }
932
933   /* Read parameters */
934   g_variant_builder_init (&builder, G_VARIANT_TYPE_TUPLE);
935   for (n = 1; n < (guint) *argc; n++)
936     {
937       GVariant *value;
938       GVariantType *type;
939
940       type = NULL;
941       if (in_signature_types != NULL)
942         {
943           if (n - 1 >= in_signature_types->len)
944             {
945               /* Only warn for the first param */
946               if (n - 1 == in_signature_types->len)
947                 {
948                   g_printerr ("Warning: Introspection data indicates %d parameters but more was passed\n",
949                               in_signature_types->len);
950                 }
951             }
952           else
953             {
954               type = in_signature_types->pdata[n - 1];
955             }
956         }
957
958       error = NULL;
959       value = g_variant_parse (type,
960                                (*argv)[n],
961                                NULL,
962                                NULL,
963                                &error);
964       if (value == NULL)
965         {
966           g_error_free (error);
967           error = NULL;
968           value = _g_variant_parse_me_harder (type, (*argv)[n], &error);
969           if (value == NULL)
970             {
971               if (type != NULL)
972                 {
973                   s = g_variant_type_dup_string (type);
974                   g_printerr (_("Error parsing parameter %d of type `%s': %s\n"),
975                               n,
976                               s,
977                               error->message);
978                   g_free (s);
979                 }
980               else
981                 {
982                   g_printerr (_("Error parsing parameter %d: %s\n"),
983                               n,
984                               error->message);
985                 }
986               g_error_free (error);
987               g_variant_builder_clear (&builder);
988               goto out;
989             }
990         }
991       g_variant_builder_add_value (&builder, value);
992     }
993   parameters = g_variant_builder_end (&builder);
994
995   if (parameters != NULL)
996     parameters = g_variant_ref_sink (parameters);
997   result = g_dbus_connection_call_sync (c,
998                                         opt_call_dest,
999                                         opt_call_object_path,
1000                                         interface_name,
1001                                         method_name,
1002                                         parameters,
1003                                         NULL,
1004                                         G_DBUS_CALL_FLAGS_NONE,
1005                                         opt_call_timeout > 0 ? opt_call_timeout * 1000 : opt_call_timeout,
1006                                         NULL,
1007                                         &error);
1008   if (result == NULL)
1009     {
1010       g_printerr (_("Error: %s\n"), error->message);
1011       g_error_free (error);
1012       if (in_signature_types != NULL)
1013         {
1014           GString *s;
1015           s = g_string_new (NULL);
1016           for (n = 0; n < in_signature_types->len; n++)
1017             {
1018               GVariantType *type = in_signature_types->pdata[n];
1019               g_string_append_len (s,
1020                                    g_variant_type_peek_string (type),
1021                                    g_variant_type_get_string_length (type));
1022             }
1023           g_printerr ("(According to introspection data, you need to pass `%s')\n", s->str);
1024           g_string_free (s, TRUE);
1025         }
1026       goto out;
1027     }
1028
1029   s = g_variant_print (result, TRUE);
1030   g_print ("%s\n", s);
1031   g_free (s);
1032
1033   ret = TRUE;
1034
1035  out:
1036   if (in_signature_types != NULL)
1037     g_ptr_array_unref (in_signature_types);
1038   if (result != NULL)
1039     g_variant_unref (result);
1040   if (c != NULL)
1041     g_object_unref (c);
1042   if (parameters != NULL)
1043     g_variant_unref (parameters);
1044   g_free (interface_name);
1045   g_free (method_name);
1046   g_option_context_free (o);
1047   return ret;
1048 }
1049
1050 /* ---------------------------------------------------------------------------------------------------- */
1051
1052 /* TODO: dump annotations */
1053
1054 static void
1055 dump_annotation (const GDBusAnnotationInfo *o,
1056                  guint indent,
1057                  gboolean ignore_indent)
1058 {
1059   guint n;
1060   g_print ("%*s@%s(\"%s\")\n",
1061            ignore_indent ? 0 : indent, "",
1062            o->key,
1063            o->value);
1064   for (n = 0; o->annotations != NULL && o->annotations[n] != NULL; n++)
1065     dump_annotation (o->annotations[n], indent + 2, FALSE);
1066 }
1067
1068 static void
1069 dump_arg (const GDBusArgInfo *o,
1070           guint indent,
1071           const gchar *direction,
1072           gboolean ignore_indent,
1073           gboolean include_newline)
1074 {
1075   guint n;
1076
1077   for (n = 0; o->annotations != NULL && o->annotations[n] != NULL; n++)
1078     {
1079       dump_annotation (o->annotations[n], indent, ignore_indent);
1080       ignore_indent = FALSE;
1081     }
1082
1083   g_print ("%*s%s%s %s%s",
1084            ignore_indent ? 0 : indent, "",
1085            direction,
1086            o->signature,
1087            o->name,
1088            include_newline ? ",\n" : "");
1089 }
1090
1091 static guint
1092 count_args (GDBusArgInfo **args)
1093 {
1094   guint n;
1095   n = 0;
1096   if (args == NULL)
1097     goto out;
1098   while (args[n] != NULL)
1099     n++;
1100  out:
1101   return n;
1102 }
1103
1104 static void
1105 dump_method (const GDBusMethodInfo *o,
1106              guint                  indent)
1107 {
1108   guint n;
1109   guint m;
1110   guint name_len;
1111   guint total_num_args;
1112
1113   for (n = 0; o->annotations != NULL && o->annotations[n] != NULL; n++)
1114     dump_annotation (o->annotations[n], indent, FALSE);
1115
1116   g_print ("%*s%s(", indent, "", o->name);
1117   name_len = strlen (o->name);
1118   total_num_args = count_args (o->in_args) + count_args (o->out_args);
1119   for (n = 0, m = 0; o->in_args != NULL && o->in_args[n] != NULL; n++, m++)
1120     {
1121       gboolean ignore_indent = (m == 0);
1122       gboolean include_newline = (m != total_num_args - 1);
1123
1124       dump_arg (o->in_args[n],
1125                 indent + name_len + 1,
1126                 "in  ",
1127                 ignore_indent,
1128                 include_newline);
1129     }
1130   for (n = 0; o->out_args != NULL && o->out_args[n] != NULL; n++, m++)
1131     {
1132       gboolean ignore_indent = (m == 0);
1133       gboolean include_newline = (m != total_num_args - 1);
1134       dump_arg (o->out_args[n],
1135                 indent + name_len + 1,
1136                 "out ",
1137                 ignore_indent,
1138                 include_newline);
1139     }
1140   g_print (");\n");
1141 }
1142
1143 static void
1144 dump_signal (const GDBusSignalInfo *o,
1145              guint                  indent)
1146 {
1147   guint n;
1148   guint name_len;
1149   guint total_num_args;
1150
1151   for (n = 0; o->annotations != NULL && o->annotations[n] != NULL; n++)
1152     dump_annotation (o->annotations[n], indent, FALSE);
1153
1154   g_print ("%*s%s(", indent, "", o->name);
1155   name_len = strlen (o->name);
1156   total_num_args = count_args (o->args);
1157   for (n = 0; o->args != NULL && o->args[n] != NULL; n++)
1158     {
1159       gboolean ignore_indent = (n == 0);
1160       gboolean include_newline = (n != total_num_args - 1);
1161       dump_arg (o->args[n],
1162                 indent + name_len + 1,
1163                 "",
1164                 ignore_indent,
1165                 include_newline);
1166     }
1167   g_print (");\n");
1168 }
1169
1170 static void
1171 dump_property (const GDBusPropertyInfo *o,
1172                guint                    indent,
1173                GVariant                *value)
1174 {
1175   const gchar *access;
1176   guint n;
1177
1178   if (o->flags == G_DBUS_PROPERTY_INFO_FLAGS_READABLE)
1179     access = "readonly";
1180   else if (o->flags == G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE)
1181     access = "writeonly";
1182   else if (o->flags == (G_DBUS_PROPERTY_INFO_FLAGS_READABLE | G_DBUS_PROPERTY_INFO_FLAGS_WRITABLE))
1183     access = "readwrite";
1184   else
1185     g_assert_not_reached ();
1186
1187   for (n = 0; o->annotations != NULL && o->annotations[n] != NULL; n++)
1188     dump_annotation (o->annotations[n], indent, FALSE);
1189
1190   if (value != NULL)
1191     {
1192       gchar *s = g_variant_print (value, FALSE);
1193       g_print ("%*s%s %s %s = %s;\n", indent, "", access, o->signature, o->name, s);
1194       g_free (s);
1195     }
1196   else
1197     {
1198       g_print ("%*s%s %s %s;\n", indent, "", access, o->signature, o->name);
1199     }
1200 }
1201
1202 static void
1203 dump_interface (GDBusConnection          *c,
1204                 const gchar              *name,
1205                 const GDBusInterfaceInfo *o,
1206                 guint                     indent,
1207                 const gchar              *object_path)
1208 {
1209   guint n;
1210   GHashTable *properties;
1211
1212   properties = g_hash_table_new_full (g_str_hash,
1213                                       g_str_equal,
1214                                       g_free,
1215                                       (GDestroyNotify) g_variant_unref);
1216
1217   /* Try to get properties */
1218   if (c != NULL && name != NULL && object_path != NULL && o->properties != NULL)
1219     {
1220       GVariant *result;
1221       result = g_dbus_connection_call_sync (c,
1222                                             name,
1223                                             object_path,
1224                                             "org.freedesktop.DBus.Properties",
1225                                             "GetAll",
1226                                             g_variant_new ("(s)", o->name),
1227                                             NULL,
1228                                             G_DBUS_CALL_FLAGS_NONE,
1229                                             3000,
1230                                             NULL,
1231                                             NULL);
1232       if (result != NULL)
1233         {
1234           if (g_variant_is_of_type (result, G_VARIANT_TYPE ("(a{sv})")))
1235             {
1236               GVariantIter *iter;
1237               GVariant *item;
1238               g_variant_get (result,
1239                              "(a{sv})",
1240                              &iter);
1241               while ((item = g_variant_iter_next_value (iter)))
1242                 {
1243                   gchar *key;
1244                   GVariant *value;
1245                   g_variant_get (item,
1246                                  "{sv}",
1247                                  &key,
1248                                  &value);
1249
1250                   g_hash_table_insert (properties, key, g_variant_ref (value));
1251                 }
1252             }
1253           g_variant_unref (result);
1254         }
1255       else
1256         {
1257           guint n;
1258           for (n = 0; o->properties != NULL && o->properties[n] != NULL; n++)
1259             {
1260               result = g_dbus_connection_call_sync (c,
1261                                                     name,
1262                                                     object_path,
1263                                                     "org.freedesktop.DBus.Properties",
1264                                                     "Get",
1265                                                     g_variant_new ("(ss)", o->name, o->properties[n]->name),
1266                                                     G_VARIANT_TYPE ("(v)"),
1267                                                     G_DBUS_CALL_FLAGS_NONE,
1268                                                     3000,
1269                                                     NULL,
1270                                                     NULL);
1271               if (result != NULL)
1272                 {
1273                   GVariant *property_value;
1274                   g_variant_get (result,
1275                                  "(v)",
1276                                  &property_value);
1277                   g_hash_table_insert (properties,
1278                                        g_strdup (o->properties[n]->name),
1279                                        g_variant_ref (property_value));
1280                   g_variant_unref (result);
1281                 }
1282             }
1283         }
1284     }
1285
1286   for (n = 0; o->annotations != NULL && o->annotations[n] != NULL; n++)
1287     dump_annotation (o->annotations[n], indent, FALSE);
1288
1289   g_print ("%*sinterface %s {\n", indent, "", o->name);
1290   if (o->methods != NULL)
1291     {
1292       g_print ("%*s  methods:\n", indent, "");
1293       for (n = 0; o->methods[n] != NULL; n++)
1294         dump_method (o->methods[n], indent + 4);
1295     }
1296   if (o->signals != NULL)
1297     {
1298       g_print ("%*s  signals:\n", indent, "");
1299       for (n = 0; o->signals[n] != NULL; n++)
1300         dump_signal (o->signals[n], indent + 4);
1301     }
1302   if (o->properties != NULL)
1303     {
1304       g_print ("%*s  properties:\n", indent, "");
1305       for (n = 0; o->properties[n] != NULL; n++)
1306         {
1307           dump_property (o->properties[n],
1308                          indent + 4,
1309                          g_hash_table_lookup (properties, (o->properties[n])->name));
1310         }
1311     }
1312   g_print ("%*s};\n",
1313            indent, "");
1314
1315   g_hash_table_unref (properties);
1316 }
1317
1318 static void
1319 dump_node (GDBusConnection      *c,
1320            const gchar          *name,
1321            const GDBusNodeInfo  *o,
1322            guint                 indent,
1323            const gchar          *object_path)
1324 {
1325   guint n;
1326   const gchar *object_path_to_print;
1327
1328   object_path_to_print = object_path;
1329   if (o->path != NULL)
1330     object_path_to_print = o->path;
1331
1332   for (n = 0; o->annotations != NULL && o->annotations[n] != NULL; n++)
1333     dump_annotation (o->annotations[n], indent, FALSE);
1334
1335   g_print ("%*snode %s", indent, "", object_path_to_print != NULL ? object_path_to_print : "(not set)");
1336   if (o->interfaces != NULL || o->nodes != NULL)
1337     {
1338       g_print (" {\n");
1339       for (n = 0; o->interfaces != NULL && o->interfaces[n] != NULL; n++)
1340         dump_interface (c, name, o->interfaces[n], indent + 2, object_path);
1341       for (n = 0; o->nodes != NULL && o->nodes[n] != NULL; n++)
1342         dump_node (NULL, NULL, o->nodes[n], indent + 2, NULL);
1343       g_print ("%*s};\n",
1344                indent, "");
1345     }
1346   else
1347     {
1348       g_print ("\n");
1349     }
1350 }
1351
1352 static gchar *opt_introspect_dest = NULL;
1353 static gchar *opt_introspect_object_path = NULL;
1354 static gboolean opt_introspect_xml = FALSE;
1355
1356 static const GOptionEntry introspect_entries[] =
1357 {
1358   { "dest", 'd', 0, G_OPTION_ARG_STRING, &opt_introspect_dest, N_("Destination name to introspect"), NULL},
1359   { "object-path", 'o', 0, G_OPTION_ARG_STRING, &opt_introspect_object_path, N_("Object path to introspect"), NULL},
1360   { "xml", 'x', 0, G_OPTION_ARG_NONE, &opt_introspect_xml, N_("Print XML"), NULL},
1361   { NULL }
1362 };
1363
1364 static gboolean
1365 handle_introspect (gint        *argc,
1366                    gchar      **argv[],
1367                    gboolean     request_completion,
1368                    const gchar *completion_cur,
1369                    const gchar *completion_prev)
1370 {
1371   gint ret;
1372   GOptionContext *o;
1373   gchar *s;
1374   GError *error;
1375   GDBusConnection *c;
1376   GVariant *result;
1377   const gchar *xml_data;
1378   GDBusNodeInfo *node;
1379   gboolean complete_names;
1380   gboolean complete_paths;
1381
1382   ret = FALSE;
1383   c = NULL;
1384   node = NULL;
1385   result = NULL;
1386
1387   modify_argv0_for_command (argc, argv, "introspect");
1388
1389   o = g_option_context_new (NULL);
1390   if (request_completion)
1391     g_option_context_set_ignore_unknown_options (o, TRUE);
1392   g_option_context_set_help_enabled (o, FALSE);
1393   g_option_context_set_summary (o, _("Introspect a remote object."));
1394   g_option_context_add_main_entries (o, introspect_entries, GETTEXT_PACKAGE);
1395   g_option_context_add_group (o, connection_get_group ());
1396
1397   complete_names = FALSE;
1398   if (request_completion && *argc > 1 && g_strcmp0 ((*argv)[(*argc)-1], "--dest") == 0)
1399     {
1400       complete_names = TRUE;
1401       remove_arg ((*argc) - 1, argc, argv);
1402     }
1403
1404   complete_paths = FALSE;
1405   if (request_completion && *argc > 1 && g_strcmp0 ((*argv)[(*argc)-1], "--object-path") == 0)
1406     {
1407       complete_paths = TRUE;
1408       remove_arg ((*argc) - 1, argc, argv);
1409     }
1410
1411   if (!g_option_context_parse (o, argc, argv, NULL))
1412     {
1413       if (!request_completion)
1414         {
1415           s = g_option_context_get_help (o, FALSE, NULL);
1416           g_printerr ("%s", s);
1417           g_free (s);
1418           goto out;
1419         }
1420     }
1421
1422   error = NULL;
1423   c = connection_get_dbus_connection (&error);
1424   if (c == NULL)
1425     {
1426       if (request_completion)
1427         {
1428           if (g_strcmp0 (completion_prev, "--address") == 0)
1429             {
1430               g_print ("unix:\n"
1431                        "tcp:\n"
1432                        "nonce-tcp:\n");
1433             }
1434           else
1435             {
1436               g_print ("--system \n--session \n--address \n");
1437             }
1438         }
1439       else
1440         {
1441           g_printerr (_("Error connecting: %s\n"), error->message);
1442           g_error_free (error);
1443         }
1444       goto out;
1445     }
1446
1447   if (g_dbus_connection_get_unique_name (c) != NULL)
1448     {
1449       if (complete_names)
1450         {
1451           print_names (c, FALSE);
1452           goto out;
1453         }
1454       /* this only makes sense on message bus connections */
1455       if (opt_introspect_dest == NULL)
1456         {
1457           if (request_completion)
1458             g_print ("--dest \n");
1459           else
1460             g_printerr (_("Error: Destination is not specified\n"));
1461           goto out;
1462         }
1463       if (request_completion && g_strcmp0 ("--dest", completion_prev) == 0)
1464         {
1465           print_names (c, g_str_has_prefix (opt_introspect_dest, ":"));
1466           goto out;
1467         }
1468     }
1469   if (complete_paths)
1470     {
1471       print_paths (c, opt_introspect_dest, "/");
1472       goto out;
1473     }
1474   if (opt_introspect_object_path == NULL)
1475     {
1476       if (request_completion)
1477         g_print ("--object-path \n");
1478       else
1479         g_printerr (_("Error: Object path is not specified\n"));
1480       goto out;
1481     }
1482   if (request_completion && g_strcmp0 ("--object-path", completion_prev) == 0)
1483     {
1484       gchar *p;
1485       s = g_strdup (opt_introspect_object_path);
1486       p = strrchr (s, '/');
1487       if (p != NULL)
1488         {
1489           if (p == s)
1490             p++;
1491           *p = '\0';
1492         }
1493       print_paths (c, opt_introspect_dest, s);
1494       g_free (s);
1495       goto out;
1496     }
1497   if (!request_completion && !g_variant_is_object_path (opt_introspect_object_path))
1498     {
1499       g_printerr (_("Error: %s is not a valid object path\n"), opt_introspect_object_path);
1500       goto out;
1501     }
1502
1503   /* All done with completion now */
1504   if (request_completion)
1505     goto out;
1506
1507   result = g_dbus_connection_call_sync (c,
1508                                         opt_introspect_dest,
1509                                         opt_introspect_object_path,
1510                                         "org.freedesktop.DBus.Introspectable",
1511                                         "Introspect",
1512                                         NULL,
1513                                         G_VARIANT_TYPE ("(s)"),
1514                                         G_DBUS_CALL_FLAGS_NONE,
1515                                         3000, /* 3 sec */
1516                                         NULL,
1517                                         &error);
1518   if (result == NULL)
1519     {
1520       g_printerr (_("Error: %s\n"), error->message);
1521       g_error_free (error);
1522       goto out;
1523     }
1524   g_variant_get (result, "(&s)", &xml_data);
1525
1526   if (opt_introspect_xml)
1527     {
1528       g_print ("%s", xml_data);
1529     }
1530   else
1531     {
1532       error = NULL;
1533       node = g_dbus_node_info_new_for_xml (xml_data, &error);
1534       if (node == NULL)
1535         {
1536           g_printerr (_("Error parsing introspection XML: %s\n"), error->message);
1537           g_error_free (error);
1538           goto out;
1539         }
1540
1541       dump_node (c, opt_introspect_dest, node, 0, opt_introspect_object_path);
1542     }
1543
1544   ret = TRUE;
1545
1546  out:
1547   if (node != NULL)
1548     g_dbus_node_info_unref (node);
1549   if (result != NULL)
1550     g_variant_unref (result);
1551   if (c != NULL)
1552     g_object_unref (c);
1553   g_option_context_free (o);
1554   return ret;
1555 }
1556
1557 /* ---------------------------------------------------------------------------------------------------- */
1558
1559 static gchar *opt_monitor_dest = NULL;
1560 static gchar *opt_monitor_object_path = NULL;
1561
1562 static guint monitor_filter_id = 0;
1563
1564 static void
1565 monitor_signal_cb (GDBusConnection *connection,
1566                    const gchar     *sender_name,
1567                    const gchar     *object_path,
1568                    const gchar     *interface_name,
1569                    const gchar     *signal_name,
1570                    GVariant        *parameters,
1571                    gpointer         user_data)
1572 {
1573   gchar *s;
1574   s = g_variant_print (parameters, TRUE);
1575   g_print ("%s: %s.%s %s\n",
1576            object_path,
1577            interface_name,
1578            signal_name,
1579            s);
1580   g_free (s);
1581 }
1582
1583 static void
1584 monitor_on_name_appeared (GDBusConnection *connection,
1585                           const gchar *name,
1586                           const gchar *name_owner,
1587                           gpointer user_data)
1588 {
1589   g_print ("The name %s is owned by %s\n", name, name_owner);
1590   g_assert (monitor_filter_id == 0);
1591   monitor_filter_id = g_dbus_connection_signal_subscribe (connection,
1592                                                           name_owner,
1593                                                           NULL,  /* any interface */
1594                                                           NULL,  /* any member */
1595                                                           opt_monitor_object_path,
1596                                                           NULL,  /* arg0 */
1597                                                           G_DBUS_SIGNAL_FLAGS_NONE,
1598                                                           monitor_signal_cb,
1599                                                           NULL,  /* user_data */
1600                                                           NULL); /* user_data destroy notify */
1601 }
1602
1603 static void
1604 monitor_on_name_vanished (GDBusConnection *connection,
1605                           const gchar *name,
1606                           gpointer user_data)
1607 {
1608   g_print ("The name %s does not have an owner\n", name);
1609
1610   if (monitor_filter_id != 0)
1611     {
1612       g_dbus_connection_signal_unsubscribe (connection, monitor_filter_id);
1613       monitor_filter_id = 0;
1614     }
1615 }
1616
1617 static const GOptionEntry monitor_entries[] =
1618 {
1619   { "dest", 'd', 0, G_OPTION_ARG_STRING, &opt_monitor_dest, N_("Destination name to monitor"), NULL},
1620   { "object-path", 'o', 0, G_OPTION_ARG_STRING, &opt_monitor_object_path, N_("Object path to monitor"), NULL},
1621   { NULL }
1622 };
1623
1624 static gboolean
1625 handle_monitor (gint        *argc,
1626                 gchar      **argv[],
1627                 gboolean     request_completion,
1628                 const gchar *completion_cur,
1629                 const gchar *completion_prev)
1630 {
1631   gint ret;
1632   GOptionContext *o;
1633   gchar *s;
1634   GError *error;
1635   GDBusConnection *c;
1636   GVariant *result;
1637   GDBusNodeInfo *node;
1638   gboolean complete_names;
1639   gboolean complete_paths;
1640   GMainLoop *loop;
1641
1642   ret = FALSE;
1643   c = NULL;
1644   node = NULL;
1645   result = NULL;
1646
1647   modify_argv0_for_command (argc, argv, "monitor");
1648
1649   o = g_option_context_new (NULL);
1650   if (request_completion)
1651     g_option_context_set_ignore_unknown_options (o, TRUE);
1652   g_option_context_set_help_enabled (o, FALSE);
1653   g_option_context_set_summary (o, _("Monitor a remote object."));
1654   g_option_context_add_main_entries (o, monitor_entries, GETTEXT_PACKAGE);
1655   g_option_context_add_group (o, connection_get_group ());
1656
1657   complete_names = FALSE;
1658   if (request_completion && *argc > 1 && g_strcmp0 ((*argv)[(*argc)-1], "--dest") == 0)
1659     {
1660       complete_names = TRUE;
1661       remove_arg ((*argc) - 1, argc, argv);
1662     }
1663
1664   complete_paths = FALSE;
1665   if (request_completion && *argc > 1 && g_strcmp0 ((*argv)[(*argc)-1], "--object-path") == 0)
1666     {
1667       complete_paths = TRUE;
1668       remove_arg ((*argc) - 1, argc, argv);
1669     }
1670
1671   if (!g_option_context_parse (o, argc, argv, NULL))
1672     {
1673       if (!request_completion)
1674         {
1675           s = g_option_context_get_help (o, FALSE, NULL);
1676           g_printerr ("%s", s);
1677           g_free (s);
1678           goto out;
1679         }
1680     }
1681
1682   error = NULL;
1683   c = connection_get_dbus_connection (&error);
1684   if (c == NULL)
1685     {
1686       if (request_completion)
1687         {
1688           if (g_strcmp0 (completion_prev, "--address") == 0)
1689             {
1690               g_print ("unix:\n"
1691                        "tcp:\n"
1692                        "nonce-tcp:\n");
1693             }
1694           else
1695             {
1696               g_print ("--system \n--session \n--address \n");
1697             }
1698         }
1699       else
1700         {
1701           g_printerr (_("Error connecting: %s\n"), error->message);
1702           g_error_free (error);
1703         }
1704       goto out;
1705     }
1706
1707   if (g_dbus_connection_get_unique_name (c) != NULL)
1708     {
1709       if (complete_names)
1710         {
1711           print_names (c, FALSE);
1712           goto out;
1713         }
1714       /* this only makes sense on message bus connections */
1715       if (opt_monitor_dest == NULL)
1716         {
1717           if (request_completion)
1718             g_print ("--dest \n");
1719           else
1720             g_printerr (_("Error: Destination is not specified\n"));
1721           goto out;
1722         }
1723       if (request_completion && g_strcmp0 ("--dest", completion_prev) == 0)
1724         {
1725           print_names (c, g_str_has_prefix (opt_monitor_dest, ":"));
1726           goto out;
1727         }
1728     }
1729   if (complete_paths)
1730     {
1731       print_paths (c, opt_monitor_dest, "/");
1732       goto out;
1733     }
1734   if (opt_monitor_object_path == NULL)
1735     {
1736       if (request_completion)
1737         {
1738           g_print ("--object-path \n");
1739           goto out;
1740         }
1741       /* it's fine to not have an object path */
1742     }
1743   if (request_completion && g_strcmp0 ("--object-path", completion_prev) == 0)
1744     {
1745       gchar *p;
1746       s = g_strdup (opt_monitor_object_path);
1747       p = strrchr (s, '/');
1748       if (p != NULL)
1749         {
1750           if (p == s)
1751             p++;
1752           *p = '\0';
1753         }
1754       print_paths (c, opt_monitor_dest, s);
1755       g_free (s);
1756       goto out;
1757     }
1758   if (!request_completion && (opt_monitor_object_path != NULL && !g_variant_is_object_path (opt_monitor_object_path)))
1759     {
1760       g_printerr (_("Error: %s is not a valid object path\n"), opt_monitor_object_path);
1761       goto out;
1762     }
1763
1764   /* All done with completion now */
1765   if (request_completion)
1766     goto out;
1767
1768   if (opt_monitor_object_path != NULL)
1769     g_print ("Monitoring signals on object %s owned by %s\n", opt_monitor_object_path, opt_monitor_dest);
1770   else
1771     g_print ("Monitoring signals from all objects owned by %s\n", opt_monitor_dest);
1772
1773   loop = g_main_loop_new (NULL, FALSE);
1774   g_bus_watch_name_on_connection (c,
1775                                   opt_monitor_dest,
1776                                   G_BUS_NAME_WATCHER_FLAGS_AUTO_START,
1777                                   monitor_on_name_appeared,
1778                                   monitor_on_name_vanished,
1779                                   NULL,
1780                                   NULL);
1781
1782   g_main_loop_run (loop);
1783   g_main_loop_unref (loop);
1784
1785   ret = TRUE;
1786
1787  out:
1788   if (node != NULL)
1789     g_dbus_node_info_unref (node);
1790   if (result != NULL)
1791     g_variant_unref (result);
1792   if (c != NULL)
1793     g_object_unref (c);
1794   g_option_context_free (o);
1795   return ret;
1796 }
1797
1798 /* ---------------------------------------------------------------------------------------------------- */
1799
1800 static gchar *
1801 pick_word_at (const gchar  *s,
1802               gint          cursor,
1803               gint         *out_word_begins_at)
1804 {
1805   gint begin;
1806   gint end;
1807
1808   if (s[0] == '\0')
1809     {
1810       if (out_word_begins_at != NULL)
1811         *out_word_begins_at = -1;
1812       return NULL;
1813     }
1814
1815   if (g_ascii_isspace (s[cursor]) && ((cursor > 0 && g_ascii_isspace(s[cursor-1])) || cursor == 0))
1816     {
1817       if (out_word_begins_at != NULL)
1818         *out_word_begins_at = cursor;
1819       return g_strdup ("");
1820     }
1821
1822   while (!g_ascii_isspace (s[cursor - 1]) && cursor > 0)
1823     cursor--;
1824   begin = cursor;
1825
1826   end = begin;
1827   while (!g_ascii_isspace (s[end]) && s[end] != '\0')
1828     end++;
1829
1830   if (out_word_begins_at != NULL)
1831     *out_word_begins_at = begin;
1832
1833   return g_strndup (s + begin, end - begin);
1834 }
1835
1836 gint
1837 main (gint argc, gchar *argv[])
1838 {
1839   gint ret;
1840   const gchar *command;
1841   gboolean request_completion;
1842   gchar *completion_cur;
1843   gchar *completion_prev;
1844
1845   setlocale (LC_ALL, "");
1846   textdomain (GETTEXT_PACKAGE);
1847
1848 #ifdef G_OS_WIN32
1849   extern gchar *_glib_get_locale_dir (void);
1850   gchar *tmp = _glib_get_locale_dir ();
1851   bindtextdomain (GETTEXT_PACKAGE, tmp);
1852   g_free (tmp);
1853 #else
1854   bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
1855 #endif
1856
1857 #ifdef HAVE_BIND_TEXTDOMAIN_CODESET
1858   bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
1859 #endif
1860
1861   ret = 1;
1862   completion_cur = NULL;
1863   completion_prev = NULL;
1864
1865   g_type_init ();
1866
1867   if (argc < 2)
1868     {
1869       usage (&argc, &argv, FALSE);
1870       goto out;
1871     }
1872
1873   request_completion = FALSE;
1874
1875   //completion_debug ("---- argc=%d --------------------------------------------------------", argc);
1876
1877  again:
1878   command = argv[1];
1879   if (g_strcmp0 (command, "help") == 0)
1880     {
1881       if (request_completion)
1882         {
1883           /* do nothing */
1884         }
1885       else
1886         {
1887           usage (&argc, &argv, TRUE);
1888           ret = 0;
1889         }
1890       goto out;
1891     }
1892   else if (g_strcmp0 (command, "emit") == 0)
1893     {
1894       if (handle_emit (&argc,
1895                        &argv,
1896                        request_completion,
1897                        completion_cur,
1898                        completion_prev))
1899         ret = 0;
1900       goto out;
1901     }
1902   else if (g_strcmp0 (command, "call") == 0)
1903     {
1904       if (handle_call (&argc,
1905                        &argv,
1906                        request_completion,
1907                        completion_cur,
1908                        completion_prev))
1909         ret = 0;
1910       goto out;
1911     }
1912   else if (g_strcmp0 (command, "introspect") == 0)
1913     {
1914       if (handle_introspect (&argc,
1915                              &argv,
1916                              request_completion,
1917                              completion_cur,
1918                              completion_prev))
1919         ret = 0;
1920       goto out;
1921     }
1922   else if (g_strcmp0 (command, "monitor") == 0)
1923     {
1924       if (handle_monitor (&argc,
1925                           &argv,
1926                           request_completion,
1927                           completion_cur,
1928                           completion_prev))
1929         ret = 0;
1930       goto out;
1931     }
1932   else if (g_strcmp0 (command, "complete") == 0 && argc == 4 && !request_completion)
1933     {
1934       const gchar *completion_line;
1935       gchar **completion_argv;
1936       gint completion_argc;
1937       gint completion_point;
1938       gchar *endp;
1939       gint cur_begin;
1940
1941       request_completion = TRUE;
1942
1943       completion_line = argv[2];
1944       completion_point = strtol (argv[3], &endp, 10);
1945       if (endp == argv[3] || *endp != '\0')
1946         goto out;
1947
1948 #if 0
1949       completion_debug ("completion_point=%d", completion_point);
1950       completion_debug ("----");
1951       completion_debug (" 0123456789012345678901234567890123456789012345678901234567890123456789");
1952       completion_debug ("`%s'", completion_line);
1953       completion_debug (" %*s^",
1954                          completion_point, "");
1955       completion_debug ("----");
1956 #endif
1957
1958       if (!g_shell_parse_argv (completion_line,
1959                                &completion_argc,
1960                                &completion_argv,
1961                                NULL))
1962         {
1963           /* it's very possible the command line can't be parsed (for
1964            * example, missing quotes etc) - in that case, we just
1965            * don't autocomplete at all
1966            */
1967           goto out;
1968         }
1969
1970       /* compute cur and prev */
1971       completion_prev = NULL;
1972       completion_cur = pick_word_at (completion_line, completion_point, &cur_begin);
1973       if (cur_begin > 0)
1974         {
1975           gint prev_end;
1976           for (prev_end = cur_begin - 1; prev_end >= 0; prev_end--)
1977             {
1978               if (!g_ascii_isspace (completion_line[prev_end]))
1979                 {
1980                   completion_prev = pick_word_at (completion_line, prev_end, NULL);
1981                   break;
1982                 }
1983             }
1984         }
1985 #if 0
1986       completion_debug (" cur=`%s'", completion_cur);
1987       completion_debug ("prev=`%s'", completion_prev);
1988 #endif
1989
1990       argc = completion_argc;
1991       argv = completion_argv;
1992
1993       ret = 0;
1994
1995       goto again;
1996     }
1997   else
1998     {
1999       if (request_completion)
2000         {
2001           g_print ("help \nemit \ncall \nintrospect \nmonitor \n");
2002           ret = 0;
2003           goto out;
2004         }
2005       else
2006         {
2007           g_printerr ("Unknown command `%s'\n", command);
2008           usage (&argc, &argv, FALSE);
2009           goto out;
2010         }
2011     }
2012
2013  out:
2014   g_free (completion_cur);
2015   g_free (completion_prev);
2016   return ret;
2017 }