]> Pileus Git - ~andy/gtk/blob - gtk/gtkapplication.c
application: Add unique IDs for GtkApplicationWindow
[~andy/gtk] / gtk / gtkapplication.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but 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, see <http://www.gnu.org/licenses/>.
16  *
17  * Author: Ryan Lortie <desrt@desrt.ca>
18  */
19
20 #include "config.h"
21
22 #include "gtkapplication.h"
23
24 #include <stdlib.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <string.h>
29
30 #include "gtkapplicationprivate.h"
31 #include "gtkclipboard.h"
32 #include "gtkmarshalers.h"
33 #include "gtkmain.h"
34 #include "gtkrecentmanager.h"
35 #include "gtkaccelmapprivate.h"
36 #include "gactionmuxer.h"
37 #include "gtkintl.h"
38
39 #ifdef GDK_WINDOWING_QUARTZ
40 #include "gtkquartz-menu.h"
41 #import <Cocoa/Cocoa.h>
42 #include <Carbon/Carbon.h>
43 #include "gtkmessagedialog.h"
44 #endif
45
46 #include <gdk/gdk.h>
47 #ifdef GDK_WINDOWING_X11
48 #include <gdk/x11/gdkx.h>
49 #endif
50
51 /**
52  * SECTION:gtkapplication
53  * @title: GtkApplication
54  * @short_description: Application class
55  *
56  * #GtkApplication is a class that handles many important aspects
57  * of a GTK+ application in a convenient fashion, without enforcing
58  * a one-size-fits-all application model.
59  *
60  * Currently, GtkApplication handles GTK+ initialization, application
61  * uniqueness, session management, provides some basic scriptability and
62  * desktop shell integration by exporting actions and menus and manages a
63  * list of toplevel windows whose life-cycle is automatically tied to the
64  * life-cycle of your application.
65  *
66  * While GtkApplication works fine with plain #GtkWindows, it is recommended
67  * to use it together with #GtkApplicationWindow.
68  *
69  * When GDK threads are enabled, GtkApplication will acquire the GDK
70  * lock when invoking actions that arrive from other processes.  The GDK
71  * lock is not touched for local action invocations.  In order to have
72  * actions invoked in a predictable context it is therefore recommended
73  * that the GDK lock be held while invoking actions locally with
74  * g_action_group_activate_action().  The same applies to actions
75  * associated with #GtkApplicationWindow and to the 'activate' and
76  * 'open' #GApplication methods.
77  *
78  * To set an application menu for a GtkApplication, use
79  * gtk_application_set_app_menu(). The #GMenuModel that this function
80  * expects is usually constructed using #GtkBuilder, as seen in the
81  * following example. To specify a menubar that will be shown by
82  * #GApplicationWindows, use gtk_application_set_menubar(). Use the base
83  * #GActionMap interface to add actions, to respond to the user
84  * selecting these menu items.
85  *
86  * GTK+ displays these menus as expected, depending on the platform
87  * the application is running on.
88  *
89  * <figure label="Menu integration in OS X">
90  * <graphic fileref="bloatpad-osx.png" format="PNG"/>
91  * </figure>
92  *
93  * <figure label="Menu integration in GNOME">
94  * <graphic fileref="bloatpad-gnome.png" format="PNG"/>
95  * </figure>
96  *
97  * <figure label="Menu integration in Xfce">
98  * <graphic fileref="bloatpad-xfce.png" format="PNG"/>
99  * </figure>
100  *
101  * <example id="gtkapplication"><title>A simple application</title>
102  * <programlisting>
103  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../examples/bloatpad.c">
104  *  <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
105  * </xi:include>
106  * </programlisting>
107  * </example>
108  *
109  * GtkApplication optionally registers with a session manager
110  * of the users session (if you set the #GtkApplication:register-session
111  * property) and offers various functionality related to the session
112  * life-cycle.
113  *
114  * An application can block various ways to end the session with
115  * the gtk_application_inhibit() function. Typical use cases for
116  * this kind of inhibiting are long-running, uninterruptible operations,
117  * such as burning a CD or performing a disk backup. The session
118  * manager may not honor the inhibitor, but it can be expected to
119  * inform the user about the negative consequences of ending the
120  * session while inhibitors are present.
121  */
122
123 enum {
124   WINDOW_ADDED,
125   WINDOW_REMOVED,
126   LAST_SIGNAL
127 };
128
129 static guint gtk_application_signals[LAST_SIGNAL];
130
131 enum {
132   PROP_ZERO,
133   PROP_REGISTER_SESSION,
134   PROP_APP_MENU,
135   PROP_MENUBAR
136 };
137
138 G_DEFINE_TYPE (GtkApplication, gtk_application, G_TYPE_APPLICATION)
139
140 struct _GtkApplicationPrivate
141 {
142   GList *windows;
143
144   gboolean register_session;
145
146   GMenuModel      *app_menu;
147   GMenuModel      *menubar;
148
149 #ifdef GDK_WINDOWING_X11
150   GDBusConnection *session_bus;
151   const gchar     *application_id;
152   const gchar     *object_path;
153
154   gchar           *app_menu_path;
155   guint            app_menu_id;
156
157   gchar           *menubar_path;
158   guint            menubar_id;
159
160   guint next_id;
161
162   GDBusProxy *sm_proxy;
163   GDBusProxy *client_proxy;
164   gchar *app_id;
165   gchar *client_path;
166 #endif
167
168 #ifdef GDK_WINDOWING_QUARTZ
169   GActionMuxer *muxer;
170   GMenu *combined;
171
172   GSList *inhibitors;
173   gint quit_inhibit;
174   guint next_cookie;
175 #endif
176 };
177
178 #ifdef GDK_WINDOWING_X11
179 static void
180 gtk_application_x11_publish_menu (GtkApplication  *application,
181                                   const gchar     *type,
182                                   GMenuModel      *model,
183                                   guint           *id,
184                                   gchar          **path)
185 {
186   gint i;
187
188   if (application->priv->session_bus == NULL)
189     return;
190
191   /* unexport any existing menu */
192   if (*id)
193     {
194       g_dbus_connection_unexport_menu_model (application->priv->session_bus, *id);
195       g_free (*path);
196       *path = NULL;
197       *id = 0;
198     }
199
200   /* export the new menu, if there is one */
201   if (model != NULL)
202     {
203       /* try getting the preferred name */
204       *path = g_strconcat (application->priv->object_path, "/menus/", type, NULL);
205       *id = g_dbus_connection_export_menu_model (application->priv->session_bus, *path, model, NULL);
206
207       /* keep trying until we get a working name... */
208       for (i = 0; *id == 0; i++)
209         {
210           g_free (*path);
211           *path = g_strdup_printf ("%s/menus/%s%d", application->priv->object_path, type, i);
212           *id = g_dbus_connection_export_menu_model (application->priv->session_bus, *path, model, NULL);
213         }
214     }
215 }
216
217 static void
218 gtk_application_set_app_menu_x11 (GtkApplication *application,
219                                   GMenuModel     *app_menu)
220 {
221   gtk_application_x11_publish_menu (application, "appmenu", app_menu,
222                                     &application->priv->app_menu_id,
223                                     &application->priv->app_menu_path);
224 }
225
226 static void
227 gtk_application_set_menubar_x11 (GtkApplication *application,
228                                  GMenuModel     *menubar)
229 {
230   gtk_application_x11_publish_menu (application, "menubar", menubar,
231                                     &application->priv->menubar_id,
232                                     &application->priv->menubar_path);
233 }
234
235 static void
236 gtk_application_window_added_x11 (GtkApplication *application,
237                                   GtkWindow      *window)
238 {
239   if (application->priv->session_bus == NULL)
240     return;
241
242   if (GTK_IS_APPLICATION_WINDOW (window))
243     {
244       GtkApplicationWindow *app_window = GTK_APPLICATION_WINDOW (window);
245       gboolean success;
246
247       /* GtkApplicationWindow associates with us when it is first created,
248        * so surely it's not realized yet...
249        */
250       g_assert (!gtk_widget_get_realized (GTK_WIDGET (window)));
251
252       do
253         {
254           gchar *window_path;
255           guint window_id;
256
257           window_id = application->priv->next_id++;
258           window_path = g_strdup_printf ("%s/window/%u", application->priv->object_path, window_id);
259           success = gtk_application_window_publish (app_window, application->priv->session_bus, window_path, window_id);
260           g_free (window_path);
261         }
262       while (!success);
263     }
264 }
265
266 static void
267 gtk_application_window_removed_x11 (GtkApplication *application,
268                                     GtkWindow      *window)
269 {
270   if (application->priv->session_bus == NULL)
271     return;
272
273   if (GTK_IS_APPLICATION_WINDOW (window))
274     gtk_application_window_unpublish (GTK_APPLICATION_WINDOW (window));
275 }
276
277 static void gtk_application_startup_session_dbus (GtkApplication *app);
278
279 static void
280 gtk_application_startup_x11 (GtkApplication *application)
281 {
282   application->priv->session_bus = g_application_get_dbus_connection (G_APPLICATION (application));
283   application->priv->object_path = g_application_get_dbus_object_path (G_APPLICATION (application));
284
285   gtk_application_startup_session_dbus (GTK_APPLICATION (application));
286 }
287
288 static void
289 gtk_application_shutdown_x11 (GtkApplication *application)
290 {
291   application->priv->session_bus = NULL;
292   application->priv->object_path = NULL;
293
294   g_clear_object (&application->priv->sm_proxy);
295   g_clear_object (&application->priv->client_proxy);
296   g_free (application->priv->app_id);
297   g_free (application->priv->client_path);
298 }
299
300 const gchar *
301 gtk_application_get_app_menu_object_path (GtkApplication *application)
302 {
303   return application->priv->app_menu_path;
304 }
305
306 const gchar *
307 gtk_application_get_menubar_object_path (GtkApplication *application)
308 {
309   return application->priv->menubar_path;
310 }
311
312 #endif
313
314 #ifdef GDK_WINDOWING_QUARTZ
315
316 typedef struct {
317   guint cookie;
318   GtkApplicationInhibitFlags flags;
319   char *reason;
320   GtkWindow *window;
321 } GtkApplicationQuartzInhibitor;
322
323 static void
324 gtk_application_quartz_inhibitor_free (GtkApplicationQuartzInhibitor *inhibitor)
325 {
326   g_free (inhibitor->reason);
327   g_clear_object (&inhibitor->window);
328   g_slice_free (GtkApplicationQuartzInhibitor, inhibitor);
329 }
330
331 static void
332 gtk_application_menu_changed_quartz (GObject    *object,
333                                      GParamSpec *pspec,
334                                      gpointer    user_data)
335 {
336   GtkApplication *application = GTK_APPLICATION (object);
337   GMenu *combined;
338
339   combined = g_menu_new ();
340   g_menu_append_submenu (combined, "Application", gtk_application_get_app_menu (application));
341   g_menu_append_section (combined, NULL, gtk_application_get_menubar (application));
342
343   gtk_quartz_set_main_menu (G_MENU_MODEL (combined), G_ACTION_OBSERVABLE (application->priv->muxer));
344 }
345
346 static void gtk_application_startup_session_quartz (GtkApplication *app);
347
348 static void
349 gtk_application_startup_quartz (GtkApplication *application)
350 {
351   [NSApp finishLaunching];
352
353   application->priv->muxer = g_action_muxer_new ();
354   g_action_muxer_insert (application->priv->muxer, "app", G_ACTION_GROUP (application));
355
356   g_signal_connect (application, "notify::app-menu", G_CALLBACK (gtk_application_menu_changed_quartz), NULL);
357   g_signal_connect (application, "notify::menubar", G_CALLBACK (gtk_application_menu_changed_quartz), NULL);
358   gtk_application_menu_changed_quartz (G_OBJECT (application), NULL, NULL);
359
360   gtk_application_startup_session_quartz (application);
361 }
362
363 static void
364 gtk_application_shutdown_quartz (GtkApplication *application)
365 {
366   g_signal_handlers_disconnect_by_func (application, gtk_application_menu_changed_quartz, NULL);
367
368   g_object_unref (application->priv->muxer);
369   application->priv->muxer = NULL;
370
371   g_slist_free_full (application->priv->inhibitors,
372                      (GDestroyNotify) gtk_application_quartz_inhibitor_free);
373   application->priv->inhibitors = NULL;
374 }
375
376 static void
377 gtk_application_focus_changed (GtkApplication *application,
378                                GtkWindow      *window)
379 {
380   if (G_IS_ACTION_GROUP (window))
381     g_action_muxer_insert (application->priv->muxer, "win", G_ACTION_GROUP (window));
382   else
383     g_action_muxer_remove (application->priv->muxer, "win");
384 }
385 #endif
386
387 static gboolean
388 gtk_application_focus_in_event_cb (GtkWindow      *window,
389                                    GdkEventFocus  *event,
390                                    GtkApplication *application)
391 {
392   GtkApplicationPrivate *priv = application->priv;
393   GList *link;
394
395   /* Keep the window list sorted by most-recently-focused. */
396   link = g_list_find (priv->windows, window);
397   if (link != NULL && link != priv->windows)
398     {
399       priv->windows = g_list_remove_link (priv->windows, link);
400       priv->windows = g_list_concat (link, priv->windows);
401     }
402
403 #ifdef GDK_WINDOWING_QUARTZ
404   gtk_application_focus_changed (application, window);
405 #endif
406
407   return FALSE;
408 }
409
410 static void
411 gtk_application_startup (GApplication *application)
412 {
413   G_APPLICATION_CLASS (gtk_application_parent_class)
414     ->startup (application);
415
416   gtk_init (0, 0);
417
418 #ifdef GDK_WINDOWING_X11
419   gtk_application_startup_x11 (GTK_APPLICATION (application));
420 #endif
421
422 #ifdef GDK_WINDOWING_QUARTZ
423   gtk_application_startup_quartz (GTK_APPLICATION (application));
424 #endif
425 }
426
427 static void
428 gtk_application_shutdown (GApplication *application)
429 {
430 #ifdef GDK_WINDOWING_X11
431   gtk_application_shutdown_x11 (GTK_APPLICATION (application));
432 #endif
433
434 #ifdef GDK_WINDOWING_QUARTZ
435   gtk_application_shutdown_quartz (GTK_APPLICATION (application));
436 #endif
437
438   /* Try storing all clipboard data we have */
439   _gtk_clipboard_store_all ();
440
441   /* Synchronize the recent manager singleton */
442   _gtk_recent_manager_sync ();
443
444   G_APPLICATION_CLASS (gtk_application_parent_class)
445     ->shutdown (application);
446 }
447
448 static void
449 gtk_application_add_platform_data (GApplication    *application,
450                                    GVariantBuilder *builder)
451 {
452   const gchar *startup_id;
453
454   startup_id = getenv ("DESKTOP_STARTUP_ID");
455   
456   if (startup_id && g_utf8_validate (startup_id, -1, NULL))
457     g_variant_builder_add (builder, "{sv}", "desktop-startup-id",
458                            g_variant_new_string (startup_id));
459 }
460
461 static void
462 gtk_application_before_emit (GApplication *application,
463                              GVariant     *platform_data)
464 {
465   GVariantIter iter;
466   const gchar *key;
467   GVariant *value;
468
469   gdk_threads_enter ();
470
471   g_variant_iter_init (&iter, platform_data);
472   while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
473     {
474 #ifdef GDK_WINDOWING_X11
475       if (strcmp (key, "desktop-startup-id") == 0)
476         {
477           GdkDisplay *display;
478           const gchar *id;
479
480           display = gdk_display_get_default ();
481           id = g_variant_get_string (value, NULL);
482           if (GDK_IS_X11_DISPLAY (display))
483             gdk_x11_display_set_startup_notification_id (display, id);
484        }
485 #endif
486     }
487 }
488
489 static void
490 gtk_application_after_emit (GApplication *application,
491                             GVariant     *platform_data)
492 {
493   gdk_notify_startup_complete ();
494
495   gdk_threads_leave ();
496 }
497
498 static void
499 gtk_application_init (GtkApplication *application)
500 {
501   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application,
502                                                    GTK_TYPE_APPLICATION,
503                                                    GtkApplicationPrivate);
504
505   application->priv->next_id = 1;
506 }
507
508 static void
509 gtk_application_window_added (GtkApplication *application,
510                               GtkWindow      *window)
511 {
512   GtkApplicationPrivate *priv = application->priv;
513
514   priv->windows = g_list_prepend (priv->windows, window);
515   gtk_window_set_application (window, application);
516   g_application_hold (G_APPLICATION (application));
517
518   g_signal_connect (window, "focus-in-event",
519                     G_CALLBACK (gtk_application_focus_in_event_cb),
520                     application);
521
522 #ifdef GDK_WINDOWING_X11
523   gtk_application_window_added_x11 (application, window);
524 #endif
525 }
526
527 static void
528 gtk_application_window_removed (GtkApplication *application,
529                                 GtkWindow      *window)
530 {
531   GtkApplicationPrivate *priv = application->priv;
532
533 #ifdef GDK_WINDOWING_X11
534   gtk_application_window_removed_x11 (application, window);
535 #endif
536
537   g_signal_handlers_disconnect_by_func (window,
538                                         gtk_application_focus_in_event_cb,
539                                         application);
540
541   g_application_release (G_APPLICATION (application));
542   priv->windows = g_list_remove (priv->windows, window);
543   gtk_window_set_application (window, NULL);
544 }
545
546 static void
547 extract_accel_from_menu_item (GMenuModel     *model,
548                               gint            item,
549                               GtkApplication *app)
550 {
551   GMenuAttributeIter *iter;
552   const gchar *key;
553   GVariant *value;
554   const gchar *accel = NULL;
555   const gchar *action = NULL;
556   GVariant *target = NULL;
557
558   iter = g_menu_model_iterate_item_attributes (model, item);
559   while (g_menu_attribute_iter_get_next (iter, &key, &value))
560     {
561       if (g_str_equal (key, "action") && g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
562         action = g_variant_get_string (value, NULL);
563       else if (g_str_equal (key, "accel") && g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
564         accel = g_variant_get_string (value, NULL);
565       else if (g_str_equal (key, "target"))
566         target = g_variant_ref (value);
567       g_variant_unref (value);
568     }
569   g_object_unref (iter);
570
571   if (accel && action)
572     gtk_application_add_accelerator (app, accel, action, target);
573
574   if (target)
575     g_variant_unref (target);
576 }
577
578 static void
579 extract_accels_from_menu (GMenuModel     *model,
580                           GtkApplication *app)
581 {
582   gint i;
583   GMenuLinkIter *iter;
584   const gchar *key;
585   GMenuModel *m;
586
587   for (i = 0; i < g_menu_model_get_n_items (model); i++)
588     {
589       extract_accel_from_menu_item (model, i, app);
590
591       iter = g_menu_model_iterate_item_links (model, i);
592       while (g_menu_link_iter_get_next (iter, &key, &m))
593         {
594           extract_accels_from_menu (m, app);
595           g_object_unref (m);
596         }
597       g_object_unref (iter);
598     }
599 }
600
601 static void
602 gtk_application_get_property (GObject    *object,
603                               guint       prop_id,
604                               GValue     *value,
605                               GParamSpec *pspec)
606 {
607   GtkApplication *application = GTK_APPLICATION (object);
608
609   switch (prop_id)
610     {
611     case PROP_REGISTER_SESSION:
612       g_value_set_boolean (value, application->priv->register_session);
613       break;
614
615     case PROP_APP_MENU:
616       g_value_set_object (value, gtk_application_get_app_menu (application));
617       break;
618
619     case PROP_MENUBAR:
620       g_value_set_object (value, gtk_application_get_menubar (application));
621       break;
622
623     default:
624       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
625       break;
626     }
627 }
628
629 static void
630 gtk_application_set_property (GObject      *object,
631                               guint         prop_id,
632                               const GValue *value,
633                               GParamSpec   *pspec)
634 {
635   GtkApplication *application = GTK_APPLICATION (object);
636
637   switch (prop_id)
638     {
639     case PROP_REGISTER_SESSION:
640       application->priv->register_session = g_value_get_boolean (value);
641       break;
642
643     case PROP_APP_MENU:
644       gtk_application_set_app_menu (application, g_value_get_object (value));
645       break;
646
647     case PROP_MENUBAR:
648       gtk_application_set_menubar (application, g_value_get_object (value));
649       break;
650
651     default:
652       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
653       break;
654     }
655 }
656
657 static void
658 gtk_application_finalize (GObject *object)
659 {
660   GtkApplication *application = GTK_APPLICATION (object);
661
662   g_clear_object (&application->priv->app_menu);
663   g_clear_object (&application->priv->menubar);
664
665   G_OBJECT_CLASS (gtk_application_parent_class)
666     ->finalize (object);
667 }
668
669 static void
670 gtk_application_class_init (GtkApplicationClass *class)
671 {
672   GObjectClass *object_class = G_OBJECT_CLASS (class);
673   GApplicationClass *application_class = G_APPLICATION_CLASS (class);
674
675   object_class->get_property = gtk_application_get_property;
676   object_class->set_property = gtk_application_set_property;
677   object_class->finalize = gtk_application_finalize;
678
679   application_class->add_platform_data = gtk_application_add_platform_data;
680   application_class->before_emit = gtk_application_before_emit;
681   application_class->after_emit = gtk_application_after_emit;
682   application_class->startup = gtk_application_startup;
683   application_class->shutdown = gtk_application_shutdown;
684
685   class->window_added = gtk_application_window_added;
686   class->window_removed = gtk_application_window_removed;
687
688   g_type_class_add_private (class, sizeof (GtkApplicationPrivate));
689
690   /**
691    * GtkApplication::window-added:
692    * @application: the #GtkApplication which emitted the signal
693    * @window: the newly-added #GtkWindow
694    *
695    * Emitted when a #GtkWindow is added to @application through
696    * gtk_application_add_window().
697    *
698    * Since: 3.2
699    */
700   gtk_application_signals[WINDOW_ADDED] =
701     g_signal_new ("window-added", GTK_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
702                   G_STRUCT_OFFSET (GtkApplicationClass, window_added),
703                   NULL, NULL,
704                   g_cclosure_marshal_VOID__OBJECT,
705                   G_TYPE_NONE, 1, GTK_TYPE_WINDOW);
706
707   /**
708    * GtkApplication::window-removed:
709    * @application: the #GtkApplication which emitted the signal
710    * @window: the #GtkWindow that is being removed
711    *
712    * Emitted when a #GtkWindow is removed from @application,
713    * either as a side-effect of being destroyed or explicitly
714    * through gtk_application_remove_window().
715    *
716    * Since: 3.2
717    */
718   gtk_application_signals[WINDOW_REMOVED] =
719     g_signal_new ("window-removed", GTK_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
720                   G_STRUCT_OFFSET (GtkApplicationClass, window_removed),
721                   NULL, NULL,
722                   g_cclosure_marshal_VOID__OBJECT,
723                   G_TYPE_NONE, 1, GTK_TYPE_WINDOW);
724
725   /**
726    * GtkApplication:register-session:
727    *
728    * Set this property to %TRUE to register with the session manager.
729    *
730    * Since: 3.4
731    */
732   g_object_class_install_property (object_class, PROP_REGISTER_SESSION,
733     g_param_spec_boolean ("register-session",
734                           P_("Register session"),
735                           P_("Register with the session manager"),
736                           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
737
738   g_object_class_install_property (object_class, PROP_APP_MENU,
739     g_param_spec_object ("app-menu",
740                          P_("Application menu"),
741                          P_("The GMenuModel for the application menu"),
742                          G_TYPE_MENU_MODEL,
743                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
744
745   g_object_class_install_property (object_class, PROP_MENUBAR,
746     g_param_spec_object ("menubar",
747                          P_("Menubar"),
748                          P_("The GMenuModel for the menubar"),
749                          G_TYPE_MENU_MODEL,
750                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
751 }
752
753 /**
754  * gtk_application_new:
755  * @application_id: the application id
756  * @flags: the application flags
757  *
758  * Creates a new #GtkApplication instance.
759  *
760  * This function calls g_type_init() for you. gtk_init() is called
761  * as soon as the application gets registered as the primary instance.
762  *
763  * Concretely, gtk_init() is called in the default handler for the
764  * #GApplication:startup signal. Therefore, #GtkApplication subclasses should
765  * chain up in their #GApplication:startup handler before using any GTK+ API.
766  *
767  * Note that commandline arguments are not passed to gtk_init().
768  * All GTK+ functionality that is available via commandline arguments
769  * can also be achieved by setting suitable environment variables
770  * such as <envar>G_DEBUG</envar>, so this should not be a big
771  * problem. If you absolutely must support GTK+ commandline arguments,
772  * you can explicitly call gtk_init() before creating the application
773  * instance.
774  *
775  * The application id must be valid. See g_application_id_is_valid().
776  *
777  * Returns: a new #GtkApplication instance
778  *
779  * Since: 3.0
780  */
781 GtkApplication *
782 gtk_application_new (const gchar       *application_id,
783                      GApplicationFlags  flags)
784 {
785   g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);
786
787   g_type_init ();
788
789   return g_object_new (GTK_TYPE_APPLICATION,
790                        "application-id", application_id,
791                        "flags", flags,
792                        NULL);
793 }
794
795 /**
796  * gtk_application_add_window:
797  * @application: a #GtkApplication
798  * @window: a #GtkWindow
799  *
800  * Adds a window to @application.
801  *
802  * This call is equivalent to setting the #GtkWindow:application
803  * property of @window to @application.
804  *
805  * Normally, the connection between the application and the window
806  * will remain until the window is destroyed, but you can explicitly
807  * remove it with gtk_application_remove_window().
808  *
809  * GTK+ will keep the application running as long as it has
810  * any windows.
811  *
812  * Since: 3.0
813  **/
814 void
815 gtk_application_add_window (GtkApplication *application,
816                             GtkWindow      *window)
817 {
818   g_return_if_fail (GTK_IS_APPLICATION (application));
819
820   if (!g_list_find (application->priv->windows, window))
821     g_signal_emit (application,
822                    gtk_application_signals[WINDOW_ADDED], 0, window);
823 }
824
825 /**
826  * gtk_application_remove_window:
827  * @application: a #GtkApplication
828  * @window: a #GtkWindow
829  *
830  * Remove a window from @application.
831  *
832  * If @window belongs to @application then this call is equivalent to
833  * setting the #GtkWindow:application property of @window to
834  * %NULL.
835  *
836  * The application may stop running as a result of a call to this
837  * function.
838  *
839  * Since: 3.0
840  **/
841 void
842 gtk_application_remove_window (GtkApplication *application,
843                                GtkWindow      *window)
844 {
845   g_return_if_fail (GTK_IS_APPLICATION (application));
846
847   if (g_list_find (application->priv->windows, window))
848     g_signal_emit (application,
849                    gtk_application_signals[WINDOW_REMOVED], 0, window);
850 }
851
852 /**
853  * gtk_application_get_windows:
854  * @application: a #GtkApplication
855  *
856  * Gets a list of the #GtkWindows associated with @application.
857  *
858  * The list is sorted by most recently focused window, such that the first
859  * element is the currently focused window. (Useful for choosing a parent
860  * for a transient window.)
861  *
862  * The list that is returned should not be modified in any way. It will
863  * only remain valid until the next focus change or window creation or
864  * deletion.
865  *
866  * Returns: (element-type GtkWindow) (transfer none): a #GList of #GtkWindow
867  *
868  * Since: 3.0
869  **/
870 GList *
871 gtk_application_get_windows (GtkApplication *application)
872 {
873   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
874
875   return application->priv->windows;
876 }
877
878 /**
879  * gtk_application_get_window_by_id:
880  * @application: a #GtkApplication
881  * @id: an identifier number
882  *
883  * Returns: (transfer none): the #GtkApplicationWindow with ID @id, or
884  *   %NULL if there is no window with this ID
885  *
886  * Since: 3.6
887  */
888 GtkWindow *
889 gtk_application_get_window_by_id (GtkApplication *application,
890                                   guint           id)
891 {
892   GList *l;
893
894   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
895
896   for (l = application->priv->windows; l != NULL; l = l->next) 
897     {
898       if (GTK_IS_APPLICATION_WINDOW (l->data) &&
899           gtk_application_window_get_id (GTK_APPLICATION_WINDOW (l->data)) == id)
900         return l->data;
901     }
902
903   return NULL;
904 }
905
906 /**
907  * gtk_application_add_accelerator:
908  * @application: a #GtkApplication
909  * @accelerator: accelerator string
910  * @action_name: the name of the action to activate
911  * @parameter: (allow-none): parameter to pass when activating the action,
912  *   or %NULL if the action does not accept an activation parameter
913  *
914  * Installs an accelerator that will cause the named action
915  * to be activated when the key combination specificed by @accelerator
916  * is pressed.
917  *
918  * @accelerator must be a string that can be parsed by
919  * gtk_accelerator_parse(), e.g. "<Primary>q" or "<Control><Alt>p".
920  *
921  * @action_name must be the name of an action as it would be used
922  * in the app menu, i.e. actions that have been added to the application
923  * are referred to with an "app." prefix, and window-specific actions
924  * with a "win." prefix.
925  *
926  * GtkApplication also extracts accelerators out of 'accel' attributes
927  * in the #GMenuModels passed to gtk_application_set_app_menu() and
928  * gtk_application_set_menubar(), which is usually more convenient
929  * than calling this function for each accelerator.
930  *
931  * Since: 3.4
932  */
933 void
934 gtk_application_add_accelerator (GtkApplication *application,
935                                  const gchar    *accelerator,
936                                  const gchar    *action_name,
937                                  GVariant       *parameter)
938 {
939   gchar *accel_path;
940   guint accel_key;
941   GdkModifierType accel_mods;
942
943   g_return_if_fail (GTK_IS_APPLICATION (application));
944
945   /* Call this here, since gtk_init() is only getting called in startup() */
946   _gtk_accel_map_init ();
947
948   gtk_accelerator_parse (accelerator, &accel_key, &accel_mods);
949
950   if (accel_key == 0)
951     {
952       g_warning ("Failed to parse accelerator: '%s'\n", accelerator);
953       return;
954     }
955
956   accel_path = _gtk_accel_path_for_action (action_name, parameter);
957
958   if (gtk_accel_map_lookup_entry (accel_path, NULL))
959     gtk_accel_map_change_entry (accel_path, accel_key, accel_mods, TRUE);
960   else
961     gtk_accel_map_add_entry (accel_path, accel_key, accel_mods);
962
963   g_free (accel_path);
964 }
965
966 /**
967  * gtk_application_remove_accelerator:
968  * @application: a #GtkApplication
969  * @action_name: the name of the action to activate
970  * @parameter: (allow-none): parameter to pass when activating the action,
971  *   or %NULL if the action does not accept an activation parameter
972  *
973  * Removes an accelerator that has been previously added
974  * with gtk_application_add_accelerator().
975  *
976  * Since: 3.4
977  */
978 void
979 gtk_application_remove_accelerator (GtkApplication *application,
980                                     const gchar    *action_name,
981                                     GVariant       *parameter)
982 {
983   gchar *accel_path;
984
985   g_return_if_fail (GTK_IS_APPLICATION (application));
986
987   accel_path = _gtk_accel_path_for_action (action_name, parameter);
988
989   if (!gtk_accel_map_lookup_entry (accel_path, NULL))
990     {
991       g_warning ("No accelerator found for '%s'\n", accel_path);
992       g_free (accel_path);
993       return;
994     }
995
996   gtk_accel_map_change_entry (accel_path, 0, 0, FALSE);
997   g_free (accel_path);
998 }
999
1000 /**
1001  * gtk_application_set_app_menu:
1002  * @application: a #GtkApplication
1003  * @app_menu: (allow-none): a #GMenuModel, or %NULL
1004  *
1005  * Sets or unsets the application menu for @application.
1006  *
1007  * This can only be done in the primary instance of the application,
1008  * after it has been registered.  #GApplication:startup is a good place
1009  * to call this.
1010  *
1011  * The application menu is a single menu containing items that typically
1012  * impact the application as a whole, rather than acting on a specific
1013  * window or document.  For example, you would expect to see
1014  * "Preferences" or "Quit" in an application menu, but not "Save" or
1015  * "Print".
1016  *
1017  * If supported, the application menu will be rendered by the desktop
1018  * environment.
1019  *
1020  * Use the base #GActionMap interface to add actions, to respond to the user
1021  * selecting these menu items.
1022  *
1023  * Since: 3.4
1024  */
1025 void
1026 gtk_application_set_app_menu (GtkApplication *application,
1027                               GMenuModel     *app_menu)
1028 {
1029   g_return_if_fail (GTK_IS_APPLICATION (application));
1030   g_return_if_fail (g_application_get_is_registered (G_APPLICATION (application)));
1031   g_return_if_fail (!g_application_get_is_remote (G_APPLICATION (application)));
1032
1033   if (app_menu != application->priv->app_menu)
1034     {
1035       if (application->priv->app_menu != NULL)
1036         g_object_unref (application->priv->app_menu);
1037
1038       application->priv->app_menu = app_menu;
1039
1040       if (application->priv->app_menu != NULL)
1041         g_object_ref (application->priv->app_menu);
1042
1043       extract_accels_from_menu (app_menu, application);
1044
1045 #ifdef GDK_WINDOWING_X11
1046       gtk_application_set_app_menu_x11 (application, app_menu);
1047 #endif
1048
1049       g_object_notify (G_OBJECT (application), "app-menu");
1050     }
1051 }
1052
1053 /**
1054  * gtk_application_get_app_menu:
1055  * @application: a #GtkApplication
1056  *
1057  * Returns the menu model that has been set with
1058  * gtk_application_set_app_menu().
1059  *
1060  * Returns: (transfer none): the application menu of @application
1061  *
1062  * Since: 3.4
1063  */
1064 GMenuModel *
1065 gtk_application_get_app_menu (GtkApplication *application)
1066 {
1067   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
1068
1069   return application->priv->app_menu;
1070 }
1071
1072 /**
1073  * gtk_application_set_menubar:
1074  * @application: a #GtkApplication
1075  * @menubar: (allow-none): a #GMenuModel, or %NULL
1076  *
1077  * Sets or unsets the menubar for windows of @application.
1078  *
1079  * This is a menubar in the traditional sense.
1080  *
1081  * This can only be done in the primary instance of the application,
1082  * after it has been registered.  #GApplication:startup is a good place
1083  * to call this.
1084  *
1085  * Depending on the desktop environment, this may appear at the top of
1086  * each window, or at the top of the screen.  In some environments, if
1087  * both the application menu and the menubar are set, the application
1088  * menu will be presented as if it were the first item of the menubar.
1089  * Other environments treat the two as completely separate -- for
1090  * example, the application menu may be rendered by the desktop shell
1091  * while the menubar (if set) remains in each individual window.
1092  *
1093  * Use the base #GActionMap interface to add actions, to respond to the user
1094  * selecting these menu items.
1095  *
1096  * Since: 3.4
1097  */
1098 void
1099 gtk_application_set_menubar (GtkApplication *application,
1100                              GMenuModel     *menubar)
1101 {
1102   g_return_if_fail (GTK_IS_APPLICATION (application));
1103   g_return_if_fail (g_application_get_is_registered (G_APPLICATION (application)));
1104   g_return_if_fail (!g_application_get_is_remote (G_APPLICATION (application)));
1105
1106   if (menubar != application->priv->menubar)
1107     {
1108       if (application->priv->menubar != NULL)
1109         g_object_unref (application->priv->menubar);
1110
1111       application->priv->menubar = menubar;
1112
1113       if (application->priv->menubar != NULL)
1114         g_object_ref (application->priv->menubar);
1115
1116       extract_accels_from_menu (menubar, application);
1117
1118 #ifdef GDK_WINDOWING_X11
1119       gtk_application_set_menubar_x11 (application, menubar);
1120 #endif
1121
1122       g_object_notify (G_OBJECT (application), "menubar");
1123     }
1124 }
1125
1126 /**
1127  * gtk_application_get_menubar:
1128  * @application: a #GtkApplication
1129  *
1130  * Returns the menu model that has been set with
1131  * gtk_application_set_menubar().
1132  *
1133  * Returns: (transfer none): the menubar for windows of @application
1134  *
1135  * Since: 3.4
1136  */
1137 GMenuModel *
1138 gtk_application_get_menubar (GtkApplication *application)
1139 {
1140   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
1141
1142   return application->priv->menubar;
1143 }
1144
1145 #if defined(GDK_WINDOWING_X11)
1146
1147 /* D-Bus Session Management
1148  *
1149  * The protocol and the D-Bus API are described here:
1150  * http://live.gnome.org/SessionManagement/GnomeSession
1151  * http://people.gnome.org/~mccann/gnome-session/docs/gnome-session.html
1152  */
1153
1154 static void
1155 unregister_client (GtkApplication *app)
1156 {
1157   GError *error = NULL;
1158
1159   g_debug ("Unregistering client");
1160
1161   g_dbus_proxy_call_sync (app->priv->sm_proxy,
1162                           "UnregisterClient",
1163                           g_variant_new ("(o)", app->priv->client_path),
1164                           G_DBUS_CALL_FLAGS_NONE,
1165                           G_MAXINT,
1166                           NULL,
1167                           &error);
1168
1169   if (error)
1170     {
1171       g_warning ("Failed to unregister client: %s", error->message);
1172       g_error_free (error);
1173     }
1174
1175   g_clear_object (&app->priv->client_proxy);
1176
1177   g_free (app->priv->client_path);
1178   app->priv->client_path = NULL;
1179 }
1180
1181 static void
1182 gtk_application_quit_response (GtkApplication *application,
1183                                gboolean        will_quit,
1184                                const gchar    *reason)
1185 {
1186   g_debug ("Calling EndSessionResponse %d '%s'", will_quit, reason);
1187
1188   g_dbus_proxy_call (application->priv->client_proxy,
1189                      "EndSessionResponse",
1190                      g_variant_new ("(bs)", will_quit, reason ? reason : ""),
1191                      G_DBUS_CALL_FLAGS_NONE,
1192                      G_MAXINT,
1193                      NULL, NULL, NULL);
1194 }
1195 static void
1196 client_proxy_signal (GDBusProxy     *proxy,
1197                      const gchar    *sender_name,
1198                      const gchar    *signal_name,
1199                      GVariant       *parameters,
1200                      GtkApplication *app)
1201 {
1202   if (strcmp (signal_name, "QueryEndSession") == 0)
1203     {
1204       g_debug ("Received QueryEndSession");
1205       gtk_application_quit_response (app, TRUE, NULL);
1206     }
1207   else if (strcmp (signal_name, "CancelEndSession") == 0)
1208     {
1209       g_debug ("Received CancelEndSession");
1210     }
1211   else if (strcmp (signal_name, "EndSession") == 0)
1212     {
1213       g_debug ("Received EndSession");
1214       gtk_application_quit_response (app, TRUE, NULL);
1215       unregister_client (app);
1216       g_application_quit (G_APPLICATION (app));
1217     }
1218   else if (strcmp (signal_name, "Stop") == 0)
1219     {
1220       g_debug ("Received Stop");
1221       unregister_client (app);
1222       g_application_quit (G_APPLICATION (app));
1223     }
1224 }
1225
1226 static void
1227 gtk_application_startup_session_dbus (GtkApplication *app)
1228 {
1229   static gchar *client_id;
1230   GError *error = NULL;
1231   GVariant *res;
1232
1233   if (app->priv->session_bus == NULL)
1234     return;
1235
1236   if (client_id == NULL)
1237     {
1238       const gchar *desktop_autostart_id;
1239
1240       desktop_autostart_id = g_getenv ("DESKTOP_AUTOSTART_ID");
1241       /* Unset DESKTOP_AUTOSTART_ID in order to avoid child processes to
1242        * use the same client id.
1243        */
1244       g_unsetenv ("DESKTOP_AUTOSTART_ID");
1245       client_id = g_strdup (desktop_autostart_id ? desktop_autostart_id : "");
1246     }
1247
1248   g_debug ("Connecting to session manager");
1249
1250   app->priv->sm_proxy = g_dbus_proxy_new_sync (app->priv->session_bus,
1251                                                G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
1252                                                G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
1253                                                NULL,
1254                                                "org.gnome.SessionManager",
1255                                                "/org/gnome/SessionManager",
1256                                                "org.gnome.SessionManager",
1257                                                NULL,
1258                                                &error);
1259   if (error)
1260     {
1261       g_warning ("Failed to get a session proxy: %s", error->message);
1262       g_error_free (error);
1263       return;
1264     }
1265
1266   /* FIXME: should we reuse the D-Bus application id here ? */
1267   app->priv->app_id = g_strdup (g_get_prgname ());
1268
1269   if (!app->priv->register_session)
1270     return;
1271
1272   g_debug ("Registering client '%s' '%s'", app->priv->app_id, client_id);
1273
1274   res = g_dbus_proxy_call_sync (app->priv->sm_proxy,
1275                                 "RegisterClient",
1276                                 g_variant_new ("(ss)", app->priv->app_id, client_id),
1277                                 G_DBUS_CALL_FLAGS_NONE,
1278                                 G_MAXINT,
1279                                 NULL,
1280                                 &error);
1281
1282   if (error)
1283     {
1284       g_warning ("Failed to register client: %s", error->message);
1285       g_error_free (error);
1286       g_clear_object (&app->priv->sm_proxy);
1287       return;
1288     }
1289
1290   g_variant_get (res, "(o)", &app->priv->client_path);
1291   g_variant_unref (res);
1292
1293   g_debug ("Registered client at '%s'", app->priv->client_path);
1294
1295   app->priv->client_proxy = g_dbus_proxy_new_sync (app->priv->session_bus, 0,
1296                                                    NULL,
1297                                                    "org.gnome.SessionManager",
1298                                                    app->priv->client_path,
1299                                                    "org.gnome.SessionManager.ClientPrivate",
1300                                                    NULL,
1301                                                    &error);
1302   if (error)
1303     {
1304       g_warning ("Failed to get client proxy: %s", error->message);
1305       g_error_free (error);
1306       g_clear_object (&app->priv->sm_proxy);
1307       g_free (app->priv->client_path);
1308       app->priv->client_path = NULL;
1309       return;
1310     }
1311
1312   g_signal_connect (app->priv->client_proxy, "g-signal", G_CALLBACK (client_proxy_signal), app);
1313 }
1314
1315
1316
1317 /**
1318  * GtkApplicationInhibitFlags:
1319  * @GTK_APPLICATION_INHIBIT_LOGOUT: Inhibit ending the user session
1320  *     by logging out or by shutting down the computer
1321  * @GTK_APPLICATION_INHIBIT_SWITCH: Inhibit user switching
1322  * @GTK_APPLICATION_INHIBIT_SUSPEND: Inhibit suspending the
1323  *     session or computer
1324  * @GTK_APPLICATION_INHIBIT_IDLE: Inhibit the session being
1325  *     marked as idle (and possibly locked)
1326  *
1327  * Types of user actions that may be blocked by gtk_application_inhibit().
1328  *
1329  * Since: 3.4
1330  */
1331
1332 /**
1333  * gtk_application_inhibit:
1334  * @application: the #GApplication
1335  * @window: (allow-none): a #GtkWindow, or %NULL
1336  * @flags: what types of actions should be inhibited
1337  * @reason: (allow-none): a short, human-readable string that explains
1338  *     why these operations are inhibited
1339  *
1340  * Inform the session manager that certain types of actions should be
1341  * inhibited. This is not guaranteed to work on all platforms and for
1342  * all types of actions.
1343  *
1344  * Applications should invoke this method when they begin an operation
1345  * that should not be interrupted, such as creating a CD or DVD. The
1346  * types of actions that may be blocked are specified by the @flags
1347  * parameter. When the application completes the operation it should
1348  * call g_application_uninhibit() to remove the inhibitor. Note that
1349  * an application can have multiple inhibitors, and all of the must
1350  * be individually removed. Inhibitors are also cleared when the
1351  * application exits.
1352  *
1353  * Applications should not expect that they will always be able to block
1354  * the action. In most cases, users will be given the option to force
1355  * the action to take place.
1356  *
1357  * Reasons should be short and to the point.
1358  *
1359  * If @window is given, the session manager may point the user to
1360  * this window to find out more about why the action is inhibited.
1361  *
1362  * Returns: A non-zero cookie that is used to uniquely identify this
1363  *     request. It should be used as an argument to g_application_uninhibit()
1364  *     in order to remove the request. If the platform does not support
1365  *     inhibiting or the request failed for some reason, 0 is returned.
1366  *
1367  * Since: 3.4
1368  */
1369 guint
1370 gtk_application_inhibit (GtkApplication             *application,
1371                          GtkWindow                  *window,
1372                          GtkApplicationInhibitFlags  flags,
1373                          const gchar                *reason)
1374 {
1375   GVariant *res;
1376   GError *error = NULL;
1377   guint cookie;
1378   guint xid;
1379
1380   g_return_val_if_fail (GTK_IS_APPLICATION (application), 0);
1381   g_return_val_if_fail (!g_application_get_is_remote (G_APPLICATION (application)), 0);
1382   g_return_val_if_fail (application->priv->sm_proxy != NULL, 0);
1383
1384   if (window != NULL)
1385     xid = GDK_WINDOW_XID (gtk_widget_get_window (GTK_WIDGET (window)));
1386   else
1387     xid = 0;
1388
1389   res = g_dbus_proxy_call_sync (application->priv->sm_proxy,
1390                                 "Inhibit",
1391                                 g_variant_new ("(susu)",
1392                                                application->priv->app_id,
1393                                                xid,
1394                                                reason,
1395                                                flags),
1396                                 G_DBUS_CALL_FLAGS_NONE,
1397                                 G_MAXINT,
1398                                 NULL,
1399                                 &error);
1400  if (error)
1401     {
1402       g_warning ("Calling Inhibit failed: %s", error->message);
1403       g_error_free (error);
1404       return 0;
1405     }
1406
1407   g_variant_get (res, "(u)", &cookie);
1408   g_variant_unref (res);
1409
1410   return cookie;
1411 }
1412
1413 /**
1414  * gtk_application_uninhibit:
1415  * @application: the #GApplication
1416  * @cookie: a cookie that was returned by g_application_inhibit()
1417  *
1418  * Removes an inhibitor that has been established with g_application_inhibit().
1419  * Inhibitors are also cleared when the application exits.
1420  *
1421  * Since: 3.4
1422  */
1423 void
1424 gtk_application_uninhibit (GtkApplication *application,
1425                            guint           cookie)
1426 {
1427   g_return_if_fail (GTK_IS_APPLICATION (application));
1428   g_return_if_fail (!g_application_get_is_remote (G_APPLICATION (application)));
1429   g_return_if_fail (application->priv->sm_proxy != NULL);
1430
1431   g_dbus_proxy_call (application->priv->sm_proxy,
1432                      "Uninhibit",
1433                      g_variant_new ("(u)", cookie),
1434                      G_DBUS_CALL_FLAGS_NONE,
1435                      G_MAXINT,
1436                      NULL, NULL, NULL);
1437 }
1438
1439 /**
1440  * gtk_application_is_inhibited:
1441  * @application: the #GApplication
1442  * @flags: what types of actions should be queried
1443  *
1444  * Determines if any of the actions specified in @flags are
1445  * currently inhibited (possibly by another application).
1446  *
1447  * Returns: %TRUE if any of the actions specified in @flags are inhibited
1448  *
1449  * Since: 3.4
1450  */
1451 gboolean
1452 gtk_application_is_inhibited (GtkApplication             *application,
1453                               GtkApplicationInhibitFlags  flags)
1454 {
1455   GVariant *res;
1456   GError *error = NULL;
1457   gboolean inhibited;
1458
1459   g_return_val_if_fail (GTK_IS_APPLICATION (application), FALSE);
1460   g_return_val_if_fail (!g_application_get_is_remote (G_APPLICATION (application)), FALSE);
1461   g_return_val_if_fail (application->priv->sm_proxy != NULL, FALSE);
1462
1463   res = g_dbus_proxy_call_sync (application->priv->sm_proxy,
1464                                 "IsInhibited",
1465                                 g_variant_new ("(u)", flags),
1466                                 G_DBUS_CALL_FLAGS_NONE,
1467                                 G_MAXINT,
1468                                 NULL,
1469                                 &error);
1470   if (error)
1471     {
1472       g_warning ("Calling IsInhibited failed: %s", error->message);
1473       g_error_free (error);
1474       return FALSE;
1475     }
1476
1477   g_variant_get (res, "(b)", &inhibited);
1478   g_variant_unref (res);
1479
1480   return inhibited;
1481 }
1482
1483 #elif defined(GDK_WINDOWING_QUARTZ)
1484
1485 /* OS X implementation copied from EggSMClient, but simplified since
1486  * it doesn't need to interact with the user.
1487  */
1488
1489 static gboolean
1490 idle_will_quit (gpointer data)
1491 {
1492   GtkApplication *app = data;
1493
1494   if (app->priv->quit_inhibit == 0)
1495     g_application_quit (G_APPLICATION (app));
1496   else
1497     {
1498       GtkApplicationQuartzInhibitor *inhibitor;
1499       GSList *iter;
1500       GtkWidget *dialog;
1501
1502       for (iter = app->priv->inhibitors; iter; iter = iter->next)
1503         {
1504           inhibitor = iter->data;
1505           if (inhibitor->flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1506             break;
1507         }
1508       g_assert (inhibitor != NULL);
1509
1510       dialog = gtk_message_dialog_new (inhibitor->window,
1511                                        GTK_DIALOG_MODAL,
1512                                        GTK_MESSAGE_ERROR,
1513                                        GTK_BUTTONS_OK,
1514                                        _("%s cannot quit at this time:\n\n%s"),
1515                                        g_get_application_name (),
1516                                        inhibitor->reason);
1517       g_signal_connect_swapped (dialog,
1518                                 "response",
1519                                 G_CALLBACK (gtk_widget_destroy),
1520                                 dialog);
1521       gtk_widget_show_all (dialog);
1522     }
1523
1524   return G_SOURCE_REMOVE;
1525 }
1526
1527 static pascal OSErr
1528 quit_requested (const AppleEvent *aevt,
1529                 AppleEvent       *reply,
1530                 long              refcon)
1531 {
1532   GtkApplication *app = GSIZE_TO_POINTER ((gsize)refcon);
1533
1534   /* Don't emit the "quit" signal immediately, since we're
1535    * called from a weird point in the guts of gdkeventloop-quartz.c
1536    */
1537   g_idle_add_full (G_PRIORITY_DEFAULT, idle_will_quit, app, NULL);
1538
1539   return app->priv->quit_inhibit == 0 ? noErr : userCanceledErr;
1540 }
1541
1542 static void
1543 gtk_application_startup_session_quartz (GtkApplication *app)
1544 {
1545   if (app->priv->register_session)
1546     AEInstallEventHandler (kCoreEventClass, kAEQuitApplication,
1547                            NewAEEventHandlerUPP (quit_requested),
1548                            (long)GPOINTER_TO_SIZE (app), false);
1549 }
1550
1551 guint
1552 gtk_application_inhibit (GtkApplication             *application,
1553                          GtkWindow                  *window,
1554                          GtkApplicationInhibitFlags  flags,
1555                          const gchar                *reason)
1556 {
1557   GtkApplicationQuartzInhibitor *inhibitor;
1558
1559   g_return_val_if_fail (GTK_IS_APPLICATION (application), 0);
1560   g_return_val_if_fail (flags != 0, 0);
1561
1562   inhibitor = g_slice_new (GtkApplicationQuartzInhibitor);
1563   inhibitor->cookie = ++application->priv->next_cookie;
1564   inhibitor->flags = flags;
1565   inhibitor->reason = g_strdup (reason);
1566   inhibitor->window = window ? g_object_ref (window) : NULL;
1567
1568   application->priv->inhibitors = g_slist_prepend (application->priv->inhibitors, inhibitor);
1569
1570   if (flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1571     application->priv->quit_inhibit++;
1572
1573   return inhibitor->cookie;
1574 }
1575
1576 void
1577 gtk_application_uninhibit (GtkApplication *application,
1578                            guint           cookie)
1579 {
1580   GSList *iter;
1581
1582   for (iter = application->priv->inhibitors; iter; iter = iter->next)
1583     {
1584       GtkApplicationQuartzInhibitor *inhibitor = iter->data;
1585
1586       if (inhibitor->cookie == cookie)
1587         {
1588           if (inhibitor->flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1589             application->priv->quit_inhibit--;
1590           gtk_application_quartz_inhibitor_free (inhibitor);
1591           application->priv->inhibitors = g_slist_delete_link (application->priv->inhibitors, iter);
1592           return;
1593         }
1594     }
1595
1596   g_warning ("Invalid inhibitor cookie");
1597 }
1598
1599 gboolean
1600 gtk_application_is_inhibited (GtkApplication             *application,
1601                               GtkApplicationInhibitFlags  flags)
1602 {
1603   if (flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1604     return application->priv->quit_inhibit > 0;
1605
1606   return FALSE;
1607 }
1608
1609 #else
1610
1611 /* Trivial implementation.
1612  *
1613  * For the inhibit API on Windows, see
1614  * http://msdn.microsoft.com/en-us/library/ms700677%28VS.85%29.aspx
1615  */
1616
1617 guint
1618 gtk_application_inhibit (GtkApplication             *application,
1619                          GtkWindow                  *window,
1620                          GtkApplicationInhibitFlags  flags,
1621                          const gchar                *reason)
1622 {
1623   return 0;
1624 }
1625
1626 void
1627 gtk_application_uninhibit (GtkApplication *application,
1628                            guint           cookie)
1629 {
1630 }
1631
1632 gboolean
1633 gtk_application_is_inhibited (GtkApplication             *application,
1634                               GtkApplicationInhibitFlags  flags)
1635 {
1636   return FALSE;
1637 }
1638
1639 #endif