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