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