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