Fix up docs
[platform/upstream/glib.git] / gio / gdbusmenumodel.c
1 /*
2  * Copyright © 2011 Canonical Ltd.
3  *
4  * This library 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  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "gdbusmenumodel.h"
23
24 #include "gmenumodel.h"
25
26 /* Prelude {{{1 */
27
28 /**
29  * SECTION:gdbusmenumodel
30  * @title: GDBusMenuModel
31  * @short_description: A D-Bus GMenuModel implementation
32  * @see_also: <link linkend="gio-GMenuModel-exporter">GMenuModel Exporter</link>
33  *
34  * #GDBusMenuModel is an implementation of #GMenuModel that can be used
35  * as a proxy for a menu model that is exported over D-Bus with
36  * g_dbus_connection_export_menu_model().
37  */
38
39 /*
40  * There are 3 main (quasi-)classes involved here:
41  *
42  *   - GDBusMenuPath
43  *   - GDBusMenuGroup
44  *   - GDBusMenuModel
45  *
46  * Each of these classes exists as a parameterised singleton keyed to a
47  * particular thing:
48  *
49  *   - GDBusMenuPath represents a D-Bus object path on a particular
50  *     unique bus name on a particular GDBusConnection and in a
51  *     particular GMainContext.
52  *
53  *   - GDBusMenuGroup represents a particular group on a particular
54  *     GDBusMenuPath.
55  *
56  *   - GDBusMenuModel represents a particular menu within a particular
57  *     GDBusMenuGroup.
58  *
59  * There are also two (and a half) utility structs:
60  *
61  *  - PathIdentifier and ConstPathIdentifier
62  *  - GDBusMenuModelItem
63  *
64  * PathIdentifier is the 4-tuple of (GMainContext, GDBusConnection,
65  * unique name, object path) that uniquely identifies a particular
66  * GDBusMenuPath.  It holds ownership on each of these things, so we
67  * have a ConstPathIdentifier variant that does not.
68  *
69  * We have a 3-level hierarchy of hashtables:
70  *
71  *   - a global hashtable (g_dbus_menu_paths) maps from PathIdentifier
72  *     to GDBusMenuPath
73  *
74  *   - each GDBusMenuPath has a hashtable mapping from guint (group
75  *     number) to GDBusMenuGroup
76  *
77  *   - each GDBusMenuGroup has a hashtable mapping from guint (menu
78  *     number) to GDBusMenuModel.
79  *
80  * In this way, each quintuplet of (connection, bus name, object path,
81  * group id, menu id) maps to a single GDBusMenuModel instance that can be
82  * located via 3 hashtable lookups.
83  *
84  * All of the 3 classes are refcounted (GDBusMenuPath and
85  * GDBusMenuGroup manually, and GDBusMenuModel by virtue of being a
86  * GObject).  The hashtables do not hold references -- rather, when the
87  * last reference is dropped, the object is removed from the hashtable.
88  *
89  * The hard references go in the other direction: GDBusMenuModel is created
90  * as the user requests it and only exists as long as the user holds a
91  * reference on it.  GDBusMenuModel holds a reference on the GDBusMenuGroup
92  * from which it came. GDBusMenuGroup holds a reference on
93  * GDBusMenuPath.
94  *
95  * In addition to refcounts, each object has an 'active' variable (ints
96  * for GDBusMenuPath and GDBusMenuGroup, boolean for GDBusMenuModel).
97  *
98  *   - GDBusMenuModel is inactive when created and becomes active only when
99  *     first queried for information.  This prevents extra work from
100  *     happening just by someone acquiring a GDBusMenuModel (and not
101  *     actually trying to display it yet).
102  *
103  *   - The active count on GDBusMenuGroup is equal to the number of
104  *     GDBusMenuModel instances in that group that are active.  When the
105  *     active count transitions from 0 to 1, the group calls the 'Start'
106  *     method on the service to begin monitoring that group.  When it
107  *     drops from 1 to 0, the group calls the 'End' method to stop
108  *     monitoring.
109  *
110  *   - The active count on GDBusMenuPath is equal to the number of
111  *     GDBusMenuGroup instances on that path with a non-zero active
112  *     count.  When the active count transitions from 0 to 1, the path
113  *     sets up a signal subscription to monitor any changes.  The signal
114  *     subscription is taken down when the active count transitions from
115  *     1 to 0.
116  *
117  * When active, GDBusMenuPath gets incoming signals when changes occur.
118  * If the change signal mentions a group for which we currently have an
119  * active GDBusMenuGroup, the change signal is passed along to that
120  * group.  If the group is inactive, the change signal is ignored.
121  *
122  * Most of the "work" occurs in GDBusMenuGroup.  In addition to the
123  * hashtable of GDBusMenuModel instances, it keeps a hashtable of the actual
124  * menu contents, each encoded as GSequence of GDBusMenuModelItem.  It
125  * initially populates this table with the results of the "Start" method
126  * call and then updates it according to incoming change signals.  If
127  * the change signal mentions a menu for which we current have an active
128  * GDBusMenuModel, the change signal is passed along to that model.  If the
129  * model is inactive, the change signal is ignored.
130  *
131  * GDBusMenuModelItem is just a pair of hashtables, one for the attributes
132  * and one for the links of the item.  Both map strings to GVariant
133  * instances.  In the case of links, the GVariant has type '(uu)' and is
134  * turned into a GDBusMenuModel at the point that the user pulls it through
135  * the API.
136  *
137  * Following the "empty is the same as non-existent" rule, the hashtable
138  * of GSequence of GDBusMenuModelItem holds NULL for empty menus.
139  *
140  * GDBusMenuModel contains very little functionality of its own.  It holds a
141  * (weak) reference to the GSequence of GDBusMenuModelItem contained in the
142  * GDBusMenuGroup.  It uses this GSequence to implement the GMenuModel
143  * interface.  It also emits the "items-changed" signal if it is active
144  * and it was told that the contents of the GSequence changed.
145  */
146
147 typedef struct _GDBusMenuGroup GDBusMenuGroup;
148 typedef struct _GDBusMenuPath GDBusMenuPath;
149
150 static void                     g_dbus_menu_group_changed               (GDBusMenuGroup  *group,
151                                                                          guint            menu_id,
152                                                                          gint             position,
153                                                                          gint             removed,
154                                                                          GVariant        *added);
155 static void                     g_dbus_menu_model_changed               (GDBusMenuModel  *proxy,
156                                                                          GSequence       *items,
157                                                                          gint             position,
158                                                                          gint             removed,
159                                                                          gint             added);
160 static GDBusMenuGroup *         g_dbus_menu_group_get_from_path         (GDBusMenuPath   *path,
161                                                                          guint            group_id);
162 static GDBusMenuModel *         g_dbus_menu_model_get_from_group        (GDBusMenuGroup  *group,
163                                                                          guint            menu_id);
164
165 /* PathIdentifier {{{1 */
166 typedef struct
167 {
168   GMainContext *context;
169   GDBusConnection *connection;
170   gchar *bus_name;
171   gchar *object_path;
172 } PathIdentifier;
173
174 typedef const struct
175 {
176   GMainContext *context;
177   GDBusConnection *connection;
178   const gchar *bus_name;
179   const gchar *object_path;
180 } ConstPathIdentifier;
181
182 static guint
183 path_identifier_hash (gconstpointer data)
184 {
185   ConstPathIdentifier *id = data;
186
187   return g_str_hash (id->object_path);
188 }
189
190 static gboolean
191 path_identifier_equal (gconstpointer a,
192                        gconstpointer b)
193 {
194   ConstPathIdentifier *id_a = a;
195   ConstPathIdentifier *id_b = b;
196
197   return id_a->connection == id_b->connection &&
198          g_str_equal (id_a->bus_name, id_b->bus_name) &&
199          g_str_equal (id_a->object_path, id_b->object_path);
200 }
201
202 static void
203 path_identifier_free (PathIdentifier *id)
204 {
205   g_main_context_unref (id->context);
206   g_object_unref (id->connection);
207   g_free (id->bus_name);
208   g_free (id->object_path);
209
210   g_slice_free (PathIdentifier, id);
211 }
212
213 static PathIdentifier *
214 path_identifier_new (ConstPathIdentifier *cid)
215 {
216   PathIdentifier *id;
217
218   id = g_slice_new (PathIdentifier);
219   id->context = g_main_context_ref (cid->context);
220   id->connection = g_object_ref (cid->connection);
221   id->bus_name = g_strdup (cid->bus_name);
222   id->object_path = g_strdup (cid->object_path);
223
224   return id;
225 }
226
227 /* GDBusMenuPath {{{1 */
228
229 struct _GDBusMenuPath
230 {
231   PathIdentifier *id;
232   gint ref_count;
233
234   GHashTable *groups;
235   gint active;
236   guint watch_id;
237 };
238
239 static GHashTable *g_dbus_menu_paths;
240
241 static GDBusMenuPath *
242 g_dbus_menu_path_ref (GDBusMenuPath *path)
243 {
244   path->ref_count++;
245
246   return path;
247 }
248
249 static void
250 g_dbus_menu_path_unref (GDBusMenuPath *path)
251 {
252   if (--path->ref_count == 0)
253     {
254       g_hash_table_remove (g_dbus_menu_paths, path->id);
255       g_hash_table_unref (path->groups);
256       path_identifier_free (path->id);
257
258       g_slice_free (GDBusMenuPath, path);
259     }
260 }
261
262 static void
263 g_dbus_menu_path_signal (GDBusConnection *connection,
264                          const gchar     *sender_name,
265                          const gchar     *object_path,
266                          const gchar     *interface_name,
267                          const gchar     *signal_name,
268                          GVariant        *parameters,
269                          gpointer         user_data)
270 {
271   GDBusMenuPath *path = user_data;
272   GVariantIter *iter;
273   guint group_id;
274   guint menu_id;
275   guint position;
276   guint removes;
277   GVariant *adds;
278
279   if (!g_variant_is_of_type (parameters, G_VARIANT_TYPE ("(a(uuuuaa{sv}))")))
280     return;
281
282   g_variant_get (parameters, "(a(uuuuaa{sv}))", &iter);
283   while (g_variant_iter_loop (iter, "(uuuu@aa{sv})", &group_id, &menu_id, &position, &removes, &adds))
284     {
285       GDBusMenuGroup *group;
286
287       group = g_hash_table_lookup (path->groups, GINT_TO_POINTER (group_id));
288
289       if (group != NULL)
290         g_dbus_menu_group_changed (group, menu_id, position, removes, adds);
291     }
292   g_variant_iter_free (iter);
293 }
294
295 static void
296 g_dbus_menu_path_activate (GDBusMenuPath *path)
297 {
298   if (path->active++ == 0)
299     path->watch_id = g_dbus_connection_signal_subscribe (path->id->connection, path->id->bus_name,
300                                                          "org.gtk.Menus", "Changed", path->id->object_path,
301                                                          NULL, G_DBUS_SIGNAL_FLAGS_NONE,
302                                                          g_dbus_menu_path_signal, path, NULL);
303 }
304
305 static void
306 g_dbus_menu_path_deactivate (GDBusMenuPath *path)
307 {
308   if (--path->active == 0)
309     g_dbus_connection_signal_unsubscribe (path->id->connection, path->watch_id);
310 }
311
312 static GDBusMenuPath *
313 g_dbus_menu_path_get (GMainContext    *context,
314                       GDBusConnection *connection,
315                       const gchar     *bus_name,
316                       const gchar     *object_path)
317 {
318   ConstPathIdentifier cid = { context, connection, bus_name, object_path };
319   GDBusMenuPath *path;
320
321   if (g_dbus_menu_paths == NULL)
322     g_dbus_menu_paths = g_hash_table_new (path_identifier_hash, path_identifier_equal);
323
324   path = g_hash_table_lookup (g_dbus_menu_paths, &cid);
325
326   if (path == NULL)
327     {
328       path = g_slice_new (GDBusMenuPath);
329       path->id = path_identifier_new (&cid);
330       path->groups = g_hash_table_new (NULL, NULL);
331       path->ref_count = 0;
332       path->active = 0;
333
334       g_hash_table_insert (g_dbus_menu_paths, path->id, path);
335     }
336
337   return g_dbus_menu_path_ref (path);
338 }
339
340 /* GDBusMenuGroup, GDBusMenuModelItem {{{1 */
341 typedef enum
342 {
343   GROUP_OFFLINE,
344   GROUP_PENDING,
345   GROUP_ONLINE
346 } GroupStatus;
347
348 struct _GDBusMenuGroup
349 {
350   GDBusMenuPath *path;
351   guint id;
352
353   GHashTable *proxies; /* uint -> unowned GDBusMenuModel */
354   GHashTable *menus;   /* uint -> owned GSequence */
355   gint ref_count;
356   GroupStatus state;
357   gint active;
358 };
359
360 typedef struct
361 {
362   GHashTable *attributes;
363   GHashTable *links;
364 } GDBusMenuModelItem;
365
366 static GDBusMenuGroup *
367 g_dbus_menu_group_ref (GDBusMenuGroup *group)
368 {
369   group->ref_count++;
370
371   return group;
372 }
373
374 static void
375 g_dbus_menu_group_unref (GDBusMenuGroup *group)
376 {
377   if (--group->ref_count == 0)
378     {
379       g_assert (group->state == GROUP_OFFLINE);
380       g_assert (group->active == 0);
381
382       g_hash_table_remove (group->path->groups, GINT_TO_POINTER (group->id));
383       g_hash_table_unref (group->proxies);
384
385       g_dbus_menu_path_unref (group->path);
386
387       g_slice_free (GDBusMenuGroup, group);
388     }
389 }
390
391 static void
392 g_dbus_menu_model_item_free (gpointer data)
393 {
394   GDBusMenuModelItem *item = data;
395
396   g_hash_table_unref (item->attributes);
397   g_hash_table_unref (item->links);
398
399   g_slice_free (GDBusMenuModelItem, item);
400 }
401
402 static GDBusMenuModelItem *
403 g_dbus_menu_group_create_item (GVariant *description)
404 {
405   GDBusMenuModelItem *item;
406   GVariantIter iter;
407   const gchar *key;
408   GVariant *value;
409
410   item = g_slice_new (GDBusMenuModelItem);
411   item->attributes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
412   item->links = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify) g_variant_unref);
413
414   g_variant_iter_init (&iter, description);
415   while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
416     if (key[0] == ':')
417       /* key + 1 to skip the ':' */
418       g_hash_table_insert (item->links, g_strdup (key + 1), g_variant_ref (value));
419     else
420       g_hash_table_insert (item->attributes, g_strdup (key), g_variant_ref (value));
421
422   return item;
423 }
424
425 /*
426  * GDBusMenuGroup can be in three states:
427  *
428  * OFFLINE: not subscribed to this group
429  * PENDING: we made the call to subscribe to this group, but the result
430  *          has not come back yet
431  * ONLINE: we are fully subscribed
432  *
433  * We can get into some nasty situations where we make a call due to an
434  * activation request but receive a deactivation request before the call
435  * returns.  If another activation request occurs then we could risk
436  * sending a Start request even though one is already in progress.  For
437  * this reason, we have to carefully consider what to do in each of the
438  * three states for each of the following situations:
439  *
440  *  - activation requested
441  *  - deactivation requested
442  *  - Start call finishes
443  *
444  * To simplify things a bit, we do not have a callback for the Stop
445  * call.  We just send it and assume that it takes effect immediately.
446  *
447  * Activation requested:
448  *   OFFLINE: make the Start call and transition to PENDING
449  *   PENDING: do nothing -- call is already in progress.
450  *   ONLINE: this should not be possible
451  *
452  * Deactivation requested:
453  *   OFFLINE: this should not be possible
454  *   PENDING: do nothing -- handle it when the Start call finishes
455  *   ONLINE: send the Stop call and move to OFFLINE immediately
456  *
457  * Start call finishes:
458  *   OFFLINE: this should not be possible
459  *   PENDING:
460  *     If we should be active (ie: active count > 0): move to ONLINE
461  *     If not: send Stop call and move to OFFLINE immediately
462  *   ONLINE: this should not be possible
463  *
464  * We have to take care with regards to signal subscriptions (ie:
465  * activation of the GDBusMenuPath).  The signal subscription is always
466  * established when transitioning from OFFLINE to PENDING and taken down
467  * when transitioning to OFFLINE (from either PENDING or ONLINE).
468  *
469  * Since there are two places where we transition to OFFLINE, we split
470  * that code out into a separate function.
471  */
472 static void
473 g_dbus_menu_group_go_offline (GDBusMenuGroup *group)
474 {
475   g_dbus_menu_path_deactivate (group->path);
476   g_dbus_connection_call (group->path->id->connection,
477                           group->path->id->bus_name,
478                           group->path->id->object_path,
479                           "org.gtk.Menus", "End",
480                           g_variant_new_parsed ("([ %u ],)", group->id),
481                           NULL, G_DBUS_CALL_FLAGS_NONE, -1,
482                           NULL, NULL, NULL);
483   group->state = GROUP_OFFLINE;
484 }
485
486
487 static void
488 g_dbus_menu_group_start_ready (GObject      *source_object,
489                                GAsyncResult *result,
490                                gpointer      user_data)
491 {
492   GDBusConnection *connection = G_DBUS_CONNECTION (source_object);
493   GDBusMenuGroup *group = user_data;
494   GVariant *reply;
495
496   g_assert (group->state == GROUP_PENDING);
497
498   reply = g_dbus_connection_call_finish (connection, result, NULL);
499
500   if (group->active)
501     {
502       group->state = GROUP_ONLINE;
503
504       /* If we receive no reply, just act like we got an empty reply. */
505       if (reply)
506         {
507           GVariantIter *iter;
508           GVariant *items;
509           guint group_id;
510           guint menu_id;
511
512           g_variant_get (reply, "(a(uuaa{sv}))", &iter);
513           while (g_variant_iter_loop (iter, "(uu@aa{sv})", &group_id, &menu_id, &items))
514             if (group_id == group->id)
515               g_dbus_menu_group_changed (group, menu_id, 0, 0, items);
516           g_variant_iter_free (iter);
517         }
518     }
519   else
520     g_dbus_menu_group_go_offline (group);
521
522   if (reply)
523     g_variant_unref (reply);
524
525   g_dbus_menu_group_unref (group);
526 }
527
528 static void
529 g_dbus_menu_group_activate (GDBusMenuGroup *group)
530 {
531   if (group->active++ == 0)
532     {
533       g_assert (group->state != GROUP_ONLINE);
534
535       if (group->state == GROUP_OFFLINE)
536         {
537           g_dbus_menu_path_activate (group->path);
538
539           g_dbus_connection_call (group->path->id->connection,
540                                   group->path->id->bus_name,
541                                   group->path->id->object_path,
542                                   "org.gtk.Menus", "Start",
543                                   g_variant_new_parsed ("([ %u ],)", group->id),
544                                   G_VARIANT_TYPE ("(a(uuaa{sv}))"),
545                                   G_DBUS_CALL_FLAGS_NONE, -1, NULL,
546                                   g_dbus_menu_group_start_ready,
547                                   g_dbus_menu_group_ref (group));
548           group->state = GROUP_PENDING;
549         }
550     }
551 }
552
553 static void
554 g_dbus_menu_group_deactivate (GDBusMenuGroup *group)
555 {
556   if (--group->active == 0)
557     {
558       g_assert (group->state != GROUP_OFFLINE);
559
560       if (group->state == GROUP_ONLINE)
561         {
562           /* We are here because nobody is watching, so just free
563            * everything and don't bother with the notifications.
564            */
565           g_hash_table_remove_all (group->menus);
566
567           g_dbus_menu_group_go_offline (group);
568         }
569     }
570 }
571
572 static void
573 g_dbus_menu_group_changed (GDBusMenuGroup *group,
574                            guint           menu_id,
575                            gint            position,
576                            gint            removed,
577                            GVariant       *added)
578 {
579   GSequenceIter *point;
580   GVariantIter iter;
581   GDBusMenuModel *proxy;
582   GSequence *items;
583   GVariant *item;
584   gint n_added;
585
586   /* We could have signals coming to us when we're not active (due to
587    * some other process having subscribed to this group) or when we're
588    * pending.  In both of those cases, we want to ignore the signal
589    * since we'll get our own information when we call "Start" for
590    * ourselves.
591    */
592   if (group->state != GROUP_ONLINE)
593     return;
594
595   items = g_hash_table_lookup (group->menus, GINT_TO_POINTER (menu_id));
596
597   if (items == NULL)
598     {
599       items = g_sequence_new (g_dbus_menu_model_item_free);
600       g_hash_table_insert (group->menus, GINT_TO_POINTER (menu_id), items);
601     }
602
603   point = g_sequence_get_iter_at_pos (items, position + removed);
604
605   g_return_if_fail (point != NULL);
606
607   if (removed)
608     {
609       GSequenceIter *start;
610
611       start = g_sequence_get_iter_at_pos (items, position);
612       g_sequence_remove_range (start, point);
613     }
614
615   n_added = g_variant_iter_init (&iter, added);
616   while (g_variant_iter_loop (&iter, "@a{sv}", &item))
617     g_sequence_insert_before (point, g_dbus_menu_group_create_item (item));
618
619   if (g_sequence_get_length (items) == 0)
620     {
621       g_hash_table_remove (group->menus, GINT_TO_POINTER (menu_id));
622       items = NULL;
623     }
624
625   if ((proxy = g_hash_table_lookup (group->proxies, GINT_TO_POINTER (menu_id))))
626     g_dbus_menu_model_changed (proxy, items, position, removed, n_added);
627 }
628
629 static GDBusMenuGroup *
630 g_dbus_menu_group_get_from_path (GDBusMenuPath *path,
631                                  guint          group_id)
632 {
633   GDBusMenuGroup *group;
634
635   group = g_hash_table_lookup (path->groups, GINT_TO_POINTER (group_id));
636
637   if (group == NULL)
638     {
639       group = g_slice_new (GDBusMenuGroup);
640       group->path = g_dbus_menu_path_ref (path);
641       group->id = group_id;
642       group->proxies = g_hash_table_new (NULL, NULL);
643       group->menus = g_hash_table_new_full (NULL, NULL, NULL, (GDestroyNotify) g_sequence_free);
644       group->state = GROUP_OFFLINE;
645       group->active = 0;
646       group->ref_count = 0;
647
648       g_hash_table_insert (path->groups, GINT_TO_POINTER (group->id), group);
649     }
650
651   return g_dbus_menu_group_ref (group);
652 }
653
654 static GDBusMenuGroup *
655 g_dbus_menu_group_get (GMainContext    *context,
656                        GDBusConnection *connection,
657                        const gchar     *bus_name,
658                        const gchar     *object_path,
659                        guint            group_id)
660 {
661   GDBusMenuGroup *group;
662   GDBusMenuPath *path;
663
664   path = g_dbus_menu_path_get (context, connection, bus_name, object_path);
665   group = g_dbus_menu_group_get_from_path (path, group_id);
666   g_dbus_menu_path_unref (path);
667
668   return group;
669 }
670
671 /* GDBusMenuModel {{{1 */
672
673 typedef GMenuModelClass GDBusMenuModelClass;
674 struct _GDBusMenuModel
675 {
676   GMenuModel parent;
677
678   GDBusMenuGroup *group;
679   guint id;
680
681   GSequence *items; /* unowned */
682   gboolean active;
683 };
684
685 G_DEFINE_TYPE (GDBusMenuModel, g_dbus_menu_model, G_TYPE_MENU_MODEL)
686
687 static gboolean
688 g_dbus_menu_model_is_mutable (GMenuModel *model)
689 {
690   return TRUE;
691 }
692
693 static gint
694 g_dbus_menu_model_get_n_items (GMenuModel *model)
695 {
696   GDBusMenuModel *proxy = G_DBUS_MENU_MODEL (model);
697
698   if (!proxy->active)
699     {
700       g_dbus_menu_group_activate (proxy->group);
701       proxy->active = TRUE;
702     }
703
704   return proxy->items ? g_sequence_get_length (proxy->items) : 0;
705 }
706
707 static void
708 g_dbus_menu_model_get_item_attributes (GMenuModel  *model,
709                                        gint         item_index,
710                                        GHashTable **table)
711 {
712   GDBusMenuModel *proxy = G_DBUS_MENU_MODEL (model);
713   GDBusMenuModelItem *item;
714   GSequenceIter *iter;
715
716   g_return_if_fail (proxy->active);
717   g_return_if_fail (proxy->items);
718
719   iter = g_sequence_get_iter_at_pos (proxy->items, item_index);
720   g_return_if_fail (iter);
721
722   item = g_sequence_get (iter);
723   g_return_if_fail (item);
724
725   *table = g_hash_table_ref (item->attributes);
726 }
727
728 static void
729 g_dbus_menu_model_get_item_links (GMenuModel  *model,
730                                   gint         item_index,
731                                   GHashTable **table)
732 {
733   GDBusMenuModel *proxy = G_DBUS_MENU_MODEL (model);
734   GDBusMenuModelItem *item;
735   GSequenceIter *iter;
736
737   g_return_if_fail (proxy->active);
738   g_return_if_fail (proxy->items);
739
740   iter = g_sequence_get_iter_at_pos (proxy->items, item_index);
741   g_return_if_fail (iter);
742
743   item = g_sequence_get (iter);
744   g_return_if_fail (item);
745
746   *table = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref);
747
748   {
749     GHashTableIter tmp;
750     gpointer key;
751     gpointer value;
752
753     g_hash_table_iter_init (&tmp, item->links);
754     while (g_hash_table_iter_next (&tmp, &key, &value))
755       {
756         if (g_variant_is_of_type (value, G_VARIANT_TYPE ("(uu)")))
757           {
758             guint group_id, menu_id;
759             GDBusMenuGroup *group;
760             GDBusMenuModel *link;
761
762             g_variant_get (value, "(uu)", &group_id, &menu_id);
763
764             /* save the hash lookup in a relatively common case */
765             if (proxy->group->id != group_id)
766               group = g_dbus_menu_group_get_from_path (proxy->group->path, group_id);
767             else
768               group = g_dbus_menu_group_ref (proxy->group);
769
770             link = g_dbus_menu_model_get_from_group (group, menu_id);
771
772             g_hash_table_insert (*table, g_strdup (key), link);
773
774             g_dbus_menu_group_unref (group);
775           }
776       }
777   }
778 }
779
780 static void
781 g_dbus_menu_model_finalize (GObject *object)
782 {
783   GDBusMenuModel *proxy = G_DBUS_MENU_MODEL (object);
784
785   if (proxy->active)
786     g_dbus_menu_group_deactivate (proxy->group);
787
788   g_hash_table_remove (proxy->group->proxies, GINT_TO_POINTER (proxy->id));
789   g_dbus_menu_group_unref (proxy->group);
790
791   G_OBJECT_CLASS (g_dbus_menu_model_parent_class)
792     ->finalize (object);
793 }
794
795 static void
796 g_dbus_menu_model_init (GDBusMenuModel *proxy)
797 {
798 }
799
800 static void
801 g_dbus_menu_model_class_init (GDBusMenuModelClass *class)
802 {
803   GObjectClass *object_class = G_OBJECT_CLASS (class);
804
805   class->is_mutable = g_dbus_menu_model_is_mutable;
806   class->get_n_items = g_dbus_menu_model_get_n_items;
807   class->get_item_attributes = g_dbus_menu_model_get_item_attributes;
808   class->get_item_links = g_dbus_menu_model_get_item_links;
809
810   object_class->finalize = g_dbus_menu_model_finalize;
811 }
812
813 static void
814 g_dbus_menu_model_changed (GDBusMenuModel *proxy,
815                            GSequence      *items,
816                            gint            position,
817                            gint            removed,
818                            gint            added)
819 {
820   proxy->items = items;
821
822   if (proxy->active && (removed || added))
823     g_menu_model_items_changed (G_MENU_MODEL (proxy), position, removed, added);
824 }
825
826 static GDBusMenuModel *
827 g_dbus_menu_model_get_from_group (GDBusMenuGroup *group,
828                                   guint           menu_id)
829 {
830   GDBusMenuModel *proxy;
831
832   proxy = g_hash_table_lookup (group->proxies, GINT_TO_POINTER (menu_id));
833   if (proxy)
834     g_object_ref (proxy);
835
836   if (proxy == NULL)
837     {
838       proxy = g_object_new (G_TYPE_DBUS_MENU_MODEL, NULL);
839       proxy->items = g_hash_table_lookup (group->menus, GINT_TO_POINTER (menu_id));
840       g_hash_table_insert (group->proxies, GINT_TO_POINTER (menu_id), proxy);
841       proxy->group = g_dbus_menu_group_ref (group);
842       proxy->id = menu_id;
843     }
844
845   return proxy;
846 }
847
848 /**
849  * g_dbus_menu_model_get:
850  * @connection: a #GDBusConnection
851  * @bus_name: the bus name which exports the menu model
852  * @object_path: the object path at which the menu model is exported
853  *
854  * Obtains a #GDBusMenuModel for the menu model which is exported
855  * at the given @bus_name and @object_path.
856  *
857  * The thread default main context is taken at the time of this call.
858  * All signals on the menu model (and any linked models) are reported
859  * with respect to this context.  All calls on the returned menu model
860  * (and linked models) must also originate from this same context, with
861  * the thread default main context unchanged.
862  *
863  * Returns: (transfer full): a #GDBusMenuModel object. Free with g_object_unref().
864  */
865 GDBusMenuModel *
866 g_dbus_menu_model_get (GDBusConnection *connection,
867                        const gchar     *bus_name,
868                        const gchar     *object_path)
869 {
870   GDBusMenuGroup *group;
871   GDBusMenuModel *proxy;
872   GMainContext *context;
873
874   context = g_main_context_get_thread_default ();
875   if (context == NULL)
876     context = g_main_context_default ();
877
878   group = g_dbus_menu_group_get (context, connection, bus_name, object_path, 0);
879   proxy = g_dbus_menu_model_get_from_group (group, 0);
880   g_dbus_menu_group_unref (group);
881
882   return proxy;
883 }
884
885 #if 0
886 static void
887 dump_proxy (gpointer key, gpointer value, gpointer data)
888 {
889   GDBusMenuModel *proxy = value;
890
891   g_print ("    menu %d refcount %d active %d\n",
892            proxy->id, G_OBJECT (proxy)->ref_count, proxy->active);
893 }
894
895 static void
896 dump_group (gpointer key, gpointer value, gpointer data)
897 {
898   GDBusMenuGroup *group = value;
899
900   g_print ("  group %d refcount %d state %d active %d\n",
901            group->id, group->ref_count, group->state, group->active);
902
903   g_hash_table_foreach (group->proxies, dump_proxy, NULL);
904 }
905
906 static void
907 dump_path (gpointer key, gpointer value, gpointer data)
908 {
909   PathIdentifier *pid = key;
910   GDBusMenuPath *path = value;
911
912   g_print ("%s active %d\n", pid->object_path, path->active);
913   g_hash_table_foreach (path->groups, dump_group, NULL);
914 }
915
916 void
917 g_dbus_menu_model_dump (void)
918 {
919   g_hash_table_foreach (g_dbus_menu_paths, dump_path, NULL);
920 }
921
922 #endif
923
924 /* Epilogue {{{1 */
925 /* vim:set foldmethod=marker: */