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