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