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