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