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