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