]> Pileus Git - ~andy/gtk/blob - gtk/gtkapplication.c
Change FSF Address
[~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 "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 block various ways to end the session with
112  * the gtk_application_inhibit() function. Typical use cases for
113  * this kind of inhibiting are long-running, uninterruptible operations,
114  * such as burning a CD or performing a disk backup. The session
115  * manager may not honor the inhibitor, but it can be expected to
116  * inform the user about the negative consequences of ending the
117  * session while inhibitors are present.
118  */
119
120 enum {
121   WINDOW_ADDED,
122   WINDOW_REMOVED,
123   LAST_SIGNAL
124 };
125
126 static guint gtk_application_signals[LAST_SIGNAL];
127
128 enum {
129   PROP_ZERO,
130   PROP_REGISTER_SESSION,
131   PROP_APP_MENU,
132   PROP_MENUBAR
133 };
134
135 G_DEFINE_TYPE (GtkApplication, gtk_application, G_TYPE_APPLICATION)
136
137 struct _GtkApplicationPrivate
138 {
139   GList *windows;
140
141   gboolean register_session;
142
143   GMenuModel      *app_menu;
144   GMenuModel      *menubar;
145
146 #ifdef GDK_WINDOWING_X11
147   GDBusConnection *session_bus;
148   const gchar     *application_id;
149   gchar           *object_path;
150
151   gchar           *app_menu_path;
152   guint            app_menu_id;
153
154   gchar           *menubar_path;
155   guint            menubar_id;
156
157   guint next_id;
158
159   GDBusProxy *sm_proxy;
160   GDBusProxy *client_proxy;
161   gchar *app_id;
162   gchar *client_path;
163 #endif
164
165 #ifdef GDK_WINDOWING_QUARTZ
166   GActionMuxer *muxer;
167   GMenu *combined;
168
169   GSList *inhibitors;
170   gint quit_inhibit;
171   guint next_cookie;
172 #endif
173 };
174
175 #ifdef GDK_WINDOWING_X11
176 static void
177 gtk_application_x11_publish_menu (GtkApplication  *application,
178                                   const gchar     *type,
179                                   GMenuModel      *model,
180                                   guint           *id,
181                                   gchar          **path)
182 {
183   gint i;
184
185   /* unexport any existing menu */
186   if (*id)
187     {
188       g_dbus_connection_unexport_menu_model (application->priv->session_bus, *id);
189       g_free (*path);
190       *path = NULL;
191       *id = 0;
192     }
193
194   /* export the new menu, if there is one */
195   if (model != NULL)
196     {
197       /* try getting the preferred name */
198       *path = g_strconcat (application->priv->object_path, "/menus/", type, NULL);
199       *id = g_dbus_connection_export_menu_model (application->priv->session_bus, *path, model, NULL);
200
201       /* keep trying until we get a working name... */
202       for (i = 0; *id == 0; i++)
203         {
204           g_free (*path);
205           *path = g_strdup_printf ("%s/menus/%s%d", application->priv->object_path, type, i);
206           *id = g_dbus_connection_export_menu_model (application->priv->session_bus, *path, model, NULL);
207         }
208     }
209 }
210
211 static void
212 gtk_application_set_app_menu_x11 (GtkApplication *application,
213                                   GMenuModel     *app_menu)
214 {
215   gtk_application_x11_publish_menu (application, "appmenu", app_menu,
216                                     &application->priv->app_menu_id,
217                                     &application->priv->app_menu_path);
218 }
219
220 static void
221 gtk_application_set_menubar_x11 (GtkApplication *application,
222                                  GMenuModel     *menubar)
223 {
224   gtk_application_x11_publish_menu (application, "menubar", menubar,
225                                     &application->priv->menubar_id,
226                                     &application->priv->menubar_path);
227 }
228
229 static void
230 gtk_application_window_added_x11 (GtkApplication *application,
231                                   GtkWindow      *window)
232 {
233   if (application->priv->session_bus == NULL)
234     return;
235
236   if (GTK_IS_APPLICATION_WINDOW (window))
237     {
238       GtkApplicationWindow *app_window = GTK_APPLICATION_WINDOW (window);
239       gboolean success;
240
241       /* GtkApplicationWindow associates with us when it is first created,
242        * so surely it's not realized yet...
243        */
244       g_assert (!gtk_widget_get_realized (GTK_WIDGET (window)));
245
246       do
247         {
248           gchar *window_path;
249           guint window_id;
250
251           window_id = application->priv->next_id++;
252           window_path = g_strdup_printf ("%s/window/%d", application->priv->object_path, window_id);
253           success = gtk_application_window_publish (app_window, application->priv->session_bus, window_path);
254           g_free (window_path);
255         }
256       while (!success);
257     }
258 }
259
260 static void
261 gtk_application_window_removed_x11 (GtkApplication *application,
262                                     GtkWindow      *window)
263 {
264   if (application->priv->session_bus == NULL)
265     return;
266
267   if (GTK_IS_APPLICATION_WINDOW (window))
268     gtk_application_window_unpublish (GTK_APPLICATION_WINDOW (window));
269 }
270
271 static gchar *
272 object_path_from_appid (const gchar *appid)
273 {
274   gchar *appid_path, *iter;
275
276   appid_path = g_strconcat ("/", appid, NULL);
277   for (iter = appid_path; *iter; iter++)
278     {
279       if (*iter == '.')
280         *iter = '/';
281
282       if (*iter == '-')
283         *iter = '_';
284     }
285
286   return appid_path;
287 }
288
289 static void gtk_application_startup_session_dbus (GtkApplication *app);
290
291 static void
292 gtk_application_startup_x11 (GtkApplication *application)
293 {
294   const gchar *application_id;
295
296   application_id = g_application_get_application_id (G_APPLICATION (application));
297   application->priv->session_bus = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, NULL);
298   application->priv->object_path = object_path_from_appid (application_id);
299
300   gtk_application_startup_session_dbus (GTK_APPLICATION (application));
301 }
302
303 static void
304 gtk_application_shutdown_x11 (GtkApplication *application)
305 {
306   g_free (application->priv->object_path);
307   application->priv->object_path = NULL;
308   g_clear_object (&application->priv->session_bus);
309
310   g_clear_object (&application->priv->sm_proxy);
311   g_clear_object (&application->priv->client_proxy);
312   g_free (application->priv->app_id);
313   g_free (application->priv->client_path);
314 }
315
316 const gchar *
317 gtk_application_get_dbus_object_path (GtkApplication *application)
318 {
319   return application->priv->object_path;
320 }
321
322 const gchar *
323 gtk_application_get_app_menu_object_path (GtkApplication *application)
324 {
325   return application->priv->app_menu_path;
326 }
327
328 const gchar *
329 gtk_application_get_menubar_object_path (GtkApplication *application)
330 {
331   return application->priv->menubar_path;
332 }
333
334 #endif
335
336 #ifdef GDK_WINDOWING_QUARTZ
337
338 typedef struct {
339   guint cookie;
340   GtkApplicationInhibitFlags flags;
341   char *reason;
342   GtkWindow *window;
343 } GtkApplicationQuartzInhibitor;
344
345 static void
346 gtk_application_quartz_inhibitor_free (GtkApplicationQuartzInhibitor *inhibitor)
347 {
348   g_free (inhibitor->reason);
349   g_clear_object (&inhibitor->window);
350   g_slice_free (GtkApplicationQuartzInhibitor, inhibitor);
351 }
352
353 static void
354 gtk_application_menu_changed_quartz (GObject    *object,
355                                      GParamSpec *pspec,
356                                      gpointer    user_data)
357 {
358   GtkApplication *application = GTK_APPLICATION (object);
359   GMenu *combined;
360
361   combined = g_menu_new ();
362   g_menu_append_submenu (combined, "Application", gtk_application_get_app_menu (application));
363   g_menu_append_section (combined, NULL, gtk_application_get_menubar (application));
364
365   gtk_quartz_set_main_menu (G_MENU_MODEL (combined), G_ACTION_OBSERVABLE (application->priv->muxer));
366 }
367
368 static void gtk_application_startup_session_quartz (GtkApplication *app);
369
370 static void
371 gtk_application_startup_quartz (GtkApplication *application)
372 {
373   [NSApp finishLaunching];
374
375   application->priv->muxer = g_action_muxer_new ();
376   g_action_muxer_insert (application->priv->muxer, "app", G_ACTION_GROUP (application));
377
378   g_signal_connect (application, "notify::app-menu", G_CALLBACK (gtk_application_menu_changed_quartz), NULL);
379   g_signal_connect (application, "notify::menubar", G_CALLBACK (gtk_application_menu_changed_quartz), NULL);
380   gtk_application_menu_changed_quartz (G_OBJECT (application), NULL, NULL);
381
382   gtk_application_startup_session_quartz (application);
383 }
384
385 static void
386 gtk_application_shutdown_quartz (GtkApplication *application)
387 {
388   g_signal_handlers_disconnect_by_func (application, gtk_application_menu_changed_quartz, NULL);
389
390   g_object_unref (application->priv->muxer);
391   application->priv->muxer = NULL;
392
393   g_slist_free_full (application->priv->inhibitors,
394                      (GDestroyNotify) gtk_application_quartz_inhibitor_free);
395   application->priv->inhibitors = NULL;
396 }
397
398 static void
399 gtk_application_focus_changed (GtkApplication *application,
400                                GtkWindow      *window)
401 {
402   if (G_IS_ACTION_GROUP (window))
403     g_action_muxer_insert (application->priv->muxer, "win", G_ACTION_GROUP (window));
404   else
405     g_action_muxer_remove (application->priv->muxer, "win");
406 }
407 #endif
408
409 static gboolean
410 gtk_application_focus_in_event_cb (GtkWindow      *window,
411                                    GdkEventFocus  *event,
412                                    GtkApplication *application)
413 {
414   GtkApplicationPrivate *priv = application->priv;
415   GList *link;
416
417   /* Keep the window list sorted by most-recently-focused. */
418   link = g_list_find (priv->windows, window);
419   if (link != NULL && link != priv->windows)
420     {
421       priv->windows = g_list_remove_link (priv->windows, link);
422       priv->windows = g_list_concat (link, priv->windows);
423     }
424
425 #ifdef GDK_WINDOWING_QUARTZ
426   gtk_application_focus_changed (application, window);
427 #endif
428
429   return FALSE;
430 }
431
432 static void
433 gtk_application_startup (GApplication *application)
434 {
435   G_APPLICATION_CLASS (gtk_application_parent_class)
436     ->startup (application);
437
438   gtk_init (0, 0);
439
440 #ifdef GDK_WINDOWING_X11
441   gtk_application_startup_x11 (GTK_APPLICATION (application));
442 #endif
443
444 #ifdef GDK_WINDOWING_QUARTZ
445   gtk_application_startup_quartz (GTK_APPLICATION (application));
446 #endif
447 }
448
449 static void
450 gtk_application_shutdown (GApplication *application)
451 {
452 #ifdef GDK_WINDOWING_X11
453   gtk_application_shutdown_x11 (GTK_APPLICATION (application));
454 #endif
455
456 #ifdef GDK_WINDOWING_QUARTZ
457   gtk_application_shutdown_quartz (GTK_APPLICATION (application));
458 #endif
459
460   /* Try storing all clipboard data we have */
461   _gtk_clipboard_store_all ();
462
463   /* Synchronize the recent manager singleton */
464   _gtk_recent_manager_sync ();
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_finalize (GObject *object)
679 {
680   GtkApplication *application = GTK_APPLICATION (object);
681
682   g_clear_object (&application->priv->app_menu);
683   g_clear_object (&application->priv->menubar);
684
685   G_OBJECT_CLASS (gtk_application_parent_class)
686     ->finalize (object);
687 }
688
689 static void
690 gtk_application_class_init (GtkApplicationClass *class)
691 {
692   GObjectClass *object_class = G_OBJECT_CLASS (class);
693   GApplicationClass *application_class = G_APPLICATION_CLASS (class);
694
695   object_class->get_property = gtk_application_get_property;
696   object_class->set_property = gtk_application_set_property;
697   object_class->finalize = gtk_application_finalize;
698
699   application_class->add_platform_data = gtk_application_add_platform_data;
700   application_class->before_emit = gtk_application_before_emit;
701   application_class->after_emit = gtk_application_after_emit;
702   application_class->startup = gtk_application_startup;
703   application_class->shutdown = gtk_application_shutdown;
704
705   class->window_added = gtk_application_window_added;
706   class->window_removed = gtk_application_window_removed;
707
708   g_type_class_add_private (class, sizeof (GtkApplicationPrivate));
709
710   /**
711    * GtkApplication::window-added:
712    * @application: the #GtkApplication which emitted the signal
713    * @window: the newly-added #GtkWindow
714    *
715    * Emitted when a #GtkWindow is added to @application through
716    * gtk_application_add_window().
717    *
718    * Since: 3.2
719    */
720   gtk_application_signals[WINDOW_ADDED] =
721     g_signal_new ("window-added", GTK_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
722                   G_STRUCT_OFFSET (GtkApplicationClass, window_added),
723                   NULL, NULL,
724                   g_cclosure_marshal_VOID__OBJECT,
725                   G_TYPE_NONE, 1, GTK_TYPE_WINDOW);
726
727   /**
728    * GtkApplication::window-removed:
729    * @application: the #GtkApplication which emitted the signal
730    * @window: the #GtkWindow that is being removed
731    *
732    * Emitted when a #GtkWindow is removed from @application,
733    * either as a side-effect of being destroyed or explicitly
734    * through gtk_application_remove_window().
735    *
736    * Since: 3.2
737    */
738   gtk_application_signals[WINDOW_REMOVED] =
739     g_signal_new ("window-removed", GTK_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
740                   G_STRUCT_OFFSET (GtkApplicationClass, window_removed),
741                   NULL, NULL,
742                   g_cclosure_marshal_VOID__OBJECT,
743                   G_TYPE_NONE, 1, GTK_TYPE_WINDOW);
744
745   /**
746    * GtkApplication:register-session:
747    *
748    * Set this property to %TRUE to register with the session manager.
749    *
750    * Since: 3.4
751    */
752   g_object_class_install_property (object_class, PROP_REGISTER_SESSION,
753     g_param_spec_boolean ("register-session",
754                           P_("Register session"),
755                           P_("Register with the session manager"),
756                           FALSE, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
757
758   g_object_class_install_property (object_class, PROP_APP_MENU,
759     g_param_spec_object ("app-menu",
760                          P_("Application menu"),
761                          P_("The GMenuModel for the application menu"),
762                          G_TYPE_MENU_MODEL,
763                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
764
765   g_object_class_install_property (object_class, PROP_MENUBAR,
766     g_param_spec_object ("menubar",
767                          P_("Menubar"),
768                          P_("The GMenuModel for the menubar"),
769                          G_TYPE_MENU_MODEL,
770                          G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
771 }
772
773 /**
774  * gtk_application_new:
775  * @application_id: the application id
776  * @flags: the application flags
777  *
778  * Creates a new #GtkApplication instance.
779  *
780  * This function calls g_type_init() for you. gtk_init() is called
781  * as soon as the application gets registered as the primary instance.
782  *
783  * Concretely, gtk_init() is called in the default handler for the
784  * startup() signal. Therefore, #GtkApplication subclasses should
785  * chain up in their startup() handler before using any GTK+ API.
786  *
787  * Note that commandline arguments are not passed to gtk_init().
788  * All GTK+ functionality that is available via commandline arguments
789  * can also be achieved by setting suitable environment variables
790  * such as <envar>G_DEBUG</envar>, so this should not be a big
791  * problem. If you absolutely must support GTK+ commandline arguments,
792  * you can explicitly call gtk_init() before creating the application
793  * instance.
794  *
795  * The application id must be valid. See g_application_id_is_valid().
796  *
797  * Returns: a new #GtkApplication instance
798  *
799  * Since: 3.0
800  */
801 GtkApplication *
802 gtk_application_new (const gchar       *application_id,
803                      GApplicationFlags  flags)
804 {
805   g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);
806
807   g_type_init ();
808
809   return g_object_new (GTK_TYPE_APPLICATION,
810                        "application-id", application_id,
811                        "flags", flags,
812                        NULL);
813 }
814
815 /**
816  * gtk_application_add_window:
817  * @application: a #GtkApplication
818  * @window: a #GtkWindow
819  *
820  * Adds a window from @application.
821  *
822  * This call is equivalent to setting the #GtkWindow:application
823  * property of @window to @application.
824  *
825  * Normally, the connection between the application and the window
826  * will remain until the window is destroyed, but you can explicitly
827  * remove it with gtk_application_remove_window().
828  *
829  * GTK+ will keep the application running as long as it has
830  * any windows.
831  *
832  * Since: 3.0
833  **/
834 void
835 gtk_application_add_window (GtkApplication *application,
836                             GtkWindow      *window)
837 {
838   g_return_if_fail (GTK_IS_APPLICATION (application));
839
840   if (!g_list_find (application->priv->windows, window))
841     g_signal_emit (application,
842                    gtk_application_signals[WINDOW_ADDED], 0, window);
843 }
844
845 /**
846  * gtk_application_remove_window:
847  * @application: a #GtkApplication
848  * @window: a #GtkWindow
849  *
850  * Remove a window from @application.
851  *
852  * If @window belongs to @application then this call is equivalent to
853  * setting the #GtkWindow:application property of @window to
854  * %NULL.
855  *
856  * The application may stop running as a result of a call to this
857  * function.
858  *
859  * Since: 3.0
860  **/
861 void
862 gtk_application_remove_window (GtkApplication *application,
863                                GtkWindow      *window)
864 {
865   g_return_if_fail (GTK_IS_APPLICATION (application));
866
867   if (g_list_find (application->priv->windows, window))
868     g_signal_emit (application,
869                    gtk_application_signals[WINDOW_REMOVED], 0, window);
870 }
871
872 /**
873  * gtk_application_get_windows:
874  * @application: a #GtkApplication
875  *
876  * Gets a list of the #GtkWindows associated with @application.
877  *
878  * The list is sorted by most recently focused window, such that the first
879  * element is the currently focused window. (Useful for choosing a parent
880  * for a transient window.)
881  *
882  * The list that is returned should not be modified in any way. It will
883  * only remain valid until the next focus change or window creation or
884  * deletion.
885  *
886  * Returns: (element-type GtkWindow) (transfer none): a #GList of #GtkWindow
887  *
888  * Since: 3.0
889  **/
890 GList *
891 gtk_application_get_windows (GtkApplication *application)
892 {
893   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
894
895   return application->priv->windows;
896 }
897
898 /**
899  * gtk_application_add_accelerator:
900  * @application: a #GtkApplication
901  * @accelerator: accelerator string
902  * @action_name: the name of the action to activate
903  * @parameter: (allow-none): parameter to pass when activating the action,
904  *   or %NULL if the action does not accept an activation parameter
905  *
906  * Installs an accelerator that will cause the named action
907  * to be activated when the key combination specificed by @accelerator
908  * is pressed.
909  *
910  * @accelerator must be a string that can be parsed by
911  * gtk_accelerator_parse(), e.g. "<Primary>q" or "<Control><Alt>p".
912  *
913  * @action_name must be the name of an action as it would be used
914  * in the app menu, i.e. actions that have been added to the application
915  * are referred to with an "app." prefix, and window-specific actions
916  * with a "win." prefix.
917  *
918  * GtkApplication also extracts accelerators out of 'accel' attributes
919  * in the #GMenuModels passed to gtk_application_set_app_menu() and
920  * gtk_application_set_menubar(), which is usually more convenient
921  * than calling this function for each accelerator.
922  *
923  * Since: 3.4
924  */
925 void
926 gtk_application_add_accelerator (GtkApplication *application,
927                                  const gchar    *accelerator,
928                                  const gchar    *action_name,
929                                  GVariant       *parameter)
930 {
931   gchar *accel_path;
932   guint accel_key;
933   GdkModifierType accel_mods;
934
935   g_return_if_fail (GTK_IS_APPLICATION (application));
936
937   /* Call this here, since gtk_init() is only getting called in startup() */
938   _gtk_accel_map_init ();
939
940   gtk_accelerator_parse (accelerator, &accel_key, &accel_mods);
941
942   if (accel_key == 0)
943     {
944       g_warning ("Failed to parse accelerator: '%s'\n", accelerator);
945       return;
946     }
947
948   accel_path = _gtk_accel_path_for_action (action_name, parameter);
949
950   if (gtk_accel_map_lookup_entry (accel_path, NULL))
951     gtk_accel_map_change_entry (accel_path, accel_key, accel_mods, TRUE);
952   else
953     gtk_accel_map_add_entry (accel_path, accel_key, accel_mods);
954
955   g_free (accel_path);
956 }
957
958 /**
959  * gtk_application_remove_accelerator:
960  * @application: a #GtkApplication
961  * @action_name: the name of the action to activate
962  * @parameter: (allow-none): parameter to pass when activating the action,
963  *   or %NULL if the action does not accept an activation parameter
964  *
965  * Removes an accelerator that has been previously added
966  * with gtk_application_add_accelerator().
967  *
968  * Since: 3.4
969  */
970 void
971 gtk_application_remove_accelerator (GtkApplication *application,
972                                     const gchar    *action_name,
973                                     GVariant       *parameter)
974 {
975   gchar *accel_path;
976
977   g_return_if_fail (GTK_IS_APPLICATION (application));
978
979   accel_path = _gtk_accel_path_for_action (action_name, parameter);
980
981   if (!gtk_accel_map_lookup_entry (accel_path, NULL))
982     {
983       g_warning ("No accelerator found for '%s'\n", accel_path);
984       g_free (accel_path);
985       return;
986     }
987
988   gtk_accel_map_change_entry (accel_path, 0, 0, FALSE);
989   g_free (accel_path);
990 }
991
992 /**
993  * gtk_application_set_app_menu:
994  * @application: a #GtkApplication
995  * @app_menu: (allow-none): a #GMenuModel, or %NULL
996  *
997  * Sets or unsets the application menu for @application.
998  *
999  * The application menu is a single menu containing items that typically
1000  * impact the application as a whole, rather than acting on a specific
1001  * window or document.  For example, you would expect to see
1002  * "Preferences" or "Quit" in an application menu, but not "Save" or
1003  * "Print".
1004  *
1005  * If supported, the application menu will be rendered by the desktop
1006  * environment.
1007  *
1008  * Since: 3.4
1009  */
1010 void
1011 gtk_application_set_app_menu (GtkApplication *application,
1012                               GMenuModel     *app_menu)
1013 {
1014   g_return_if_fail (GTK_IS_APPLICATION (application));
1015
1016   if (app_menu != application->priv->app_menu)
1017     {
1018       if (application->priv->app_menu != NULL)
1019         g_object_unref (application->priv->app_menu);
1020
1021       application->priv->app_menu = app_menu;
1022
1023       if (application->priv->app_menu != NULL)
1024         g_object_ref (application->priv->app_menu);
1025
1026       extract_accels_from_menu (app_menu, application);
1027
1028 #ifdef GDK_WINDOWING_X11
1029       gtk_application_set_app_menu_x11 (application, app_menu);
1030 #endif
1031
1032       g_object_notify (G_OBJECT (application), "app-menu");
1033     }
1034 }
1035
1036 /**
1037  * gtk_application_get_app_menu:
1038  * @application: a #GtkApplication
1039  *
1040  * Returns the menu model that has been set with
1041  * gtk_application_set_app_menu().
1042  *
1043  * Returns: (transfer none): the application menu of @application
1044  *
1045  * Since: 3.4
1046  */
1047 GMenuModel *
1048 gtk_application_get_app_menu (GtkApplication *application)
1049 {
1050   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
1051
1052   return application->priv->app_menu;
1053 }
1054
1055 /**
1056  * gtk_application_set_menubar:
1057  * @application: a #GtkApplication
1058  * @menubar: (allow-none): a #GMenuModel, or %NULL
1059  *
1060  * Sets or unsets the menubar for windows of @application.
1061  *
1062  * This is a menubar in the traditional sense.
1063  *
1064  * Depending on the desktop environment, this may appear at the top of
1065  * each window, or at the top of the screen.  In some environments, if
1066  * both the application menu and the menubar are set, the application
1067  * menu will be presented as if it were the first item of the menubar.
1068  * Other environments treat the two as completely separate -- for
1069  * example, the application menu may be rendered by the desktop shell
1070  * while the menubar (if set) remains in each individual window.
1071  *
1072  * Since: 3.4
1073  */
1074 void
1075 gtk_application_set_menubar (GtkApplication *application,
1076                              GMenuModel     *menubar)
1077 {
1078   g_return_if_fail (GTK_IS_APPLICATION (application));
1079
1080   if (menubar != application->priv->menubar)
1081     {
1082       if (application->priv->menubar != NULL)
1083         g_object_unref (application->priv->menubar);
1084
1085       application->priv->menubar = menubar;
1086
1087       if (application->priv->menubar != NULL)
1088         g_object_ref (application->priv->menubar);
1089
1090       extract_accels_from_menu (menubar, application);
1091
1092 #ifdef GDK_WINDOWING_X11
1093       gtk_application_set_menubar_x11 (application, menubar);
1094 #endif
1095
1096       g_object_notify (G_OBJECT (application), "menubar");
1097     }
1098 }
1099
1100 /**
1101  * gtk_application_get_menubar:
1102  * @application: a #GtkApplication
1103  *
1104  * Returns the menu model that has been set with
1105  * gtk_application_set_menubar().
1106  *
1107  * Returns: (transfer none): the menubar for windows of @application
1108  *
1109  * Since: 3.4
1110  */
1111 GMenuModel *
1112 gtk_application_get_menubar (GtkApplication *application)
1113 {
1114   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
1115
1116   return application->priv->menubar;
1117 }
1118
1119 #if defined(GDK_WINDOWING_X11)
1120
1121 /* D-Bus Session Management
1122  *
1123  * The protocol and the D-Bus API are described here:
1124  * http://live.gnome.org/SessionManagement/GnomeSession
1125  * http://people.gnome.org/~mccann/gnome-session/docs/gnome-session.html
1126  */
1127
1128 static void
1129 unregister_client (GtkApplication *app)
1130 {
1131   GError *error = NULL;
1132
1133   g_debug ("Unregistering client");
1134
1135   g_dbus_proxy_call_sync (app->priv->sm_proxy,
1136                           "UnregisterClient",
1137                           g_variant_new ("(o)", app->priv->client_path),
1138                           G_DBUS_CALL_FLAGS_NONE,
1139                           G_MAXINT,
1140                           NULL,
1141                           &error);
1142
1143   if (error)
1144     {
1145       g_warning ("Failed to unregister client: %s", error->message);
1146       g_error_free (error);
1147     }
1148
1149   g_clear_object (&app->priv->client_proxy);
1150
1151   g_free (app->priv->client_path);
1152   app->priv->client_path = NULL;
1153 }
1154
1155 static void
1156 gtk_application_quit_response (GtkApplication *application,
1157                                gboolean        will_quit,
1158                                const gchar    *reason)
1159 {
1160   g_debug ("Calling EndSessionResponse %d '%s'", will_quit, reason);
1161
1162   g_dbus_proxy_call (application->priv->client_proxy,
1163                      "EndSessionResponse",
1164                      g_variant_new ("(bs)", will_quit, reason ? reason : ""),
1165                      G_DBUS_CALL_FLAGS_NONE,
1166                      G_MAXINT,
1167                      NULL, NULL, NULL);
1168 }
1169 static void
1170 client_proxy_signal (GDBusProxy     *proxy,
1171                      const gchar    *sender_name,
1172                      const gchar    *signal_name,
1173                      GVariant       *parameters,
1174                      GtkApplication *app)
1175 {
1176   if (strcmp (signal_name, "QueryEndSession") == 0)
1177     {
1178       g_debug ("Received QueryEndSession");
1179       gtk_application_quit_response (app, TRUE, NULL);
1180     }
1181   else if (strcmp (signal_name, "CancelEndSession") == 0)
1182     {
1183       g_debug ("Received CancelEndSession");
1184     }
1185   else if (strcmp (signal_name, "EndSession") == 0)
1186     {
1187       g_debug ("Received EndSession");
1188       gtk_application_quit_response (app, TRUE, NULL);
1189       unregister_client (app);
1190       g_application_quit (G_APPLICATION (app));
1191     }
1192   else if (strcmp (signal_name, "Stop") == 0)
1193     {
1194       g_debug ("Received Stop");
1195       unregister_client (app);
1196       g_application_quit (G_APPLICATION (app));
1197     }
1198 }
1199
1200 static void
1201 gtk_application_startup_session_dbus (GtkApplication *app)
1202 {
1203   static gchar *client_id;
1204   GError *error = NULL;
1205   GVariant *res;
1206
1207   if (app->priv->session_bus == NULL)
1208     return;
1209
1210   if (client_id == NULL)
1211     {
1212       const gchar *desktop_autostart_id;
1213
1214       desktop_autostart_id = g_getenv ("DESKTOP_AUTOSTART_ID");
1215       /* Unset DESKTOP_AUTOSTART_ID in order to avoid child processes to
1216        * use the same client id.
1217        */
1218       g_unsetenv ("DESKTOP_AUTOSTART_ID");
1219       client_id = g_strdup (desktop_autostart_id ? desktop_autostart_id : "");
1220     }
1221
1222   g_debug ("Connecting to session manager");
1223
1224   app->priv->sm_proxy = g_dbus_proxy_new_sync (app->priv->session_bus,
1225                                                G_DBUS_PROXY_FLAGS_DO_NOT_LOAD_PROPERTIES |
1226                                                G_DBUS_PROXY_FLAGS_DO_NOT_CONNECT_SIGNALS,
1227                                                NULL,
1228                                                "org.gnome.SessionManager",
1229                                                "/org/gnome/SessionManager",
1230                                                "org.gnome.SessionManager",
1231                                                NULL,
1232                                                &error);
1233   if (error)
1234     {
1235       g_warning ("Failed to get a session proxy: %s", error->message);
1236       g_error_free (error);
1237       return;
1238     }
1239
1240   /* FIXME: should we reuse the D-Bus application id here ? */
1241   app->priv->app_id = g_strdup (g_get_prgname ());
1242
1243   if (!app->priv->register_session)
1244     return;
1245
1246   g_debug ("Registering client '%s' '%s'", app->priv->app_id, client_id);
1247
1248   res = g_dbus_proxy_call_sync (app->priv->sm_proxy,
1249                                 "RegisterClient",
1250                                 g_variant_new ("(ss)", app->priv->app_id, client_id),
1251                                 G_DBUS_CALL_FLAGS_NONE,
1252                                 G_MAXINT,
1253                                 NULL,
1254                                 &error);
1255
1256   if (error)
1257     {
1258       g_warning ("Failed to register client: %s", error->message);
1259       g_error_free (error);
1260       g_clear_object (&app->priv->sm_proxy);
1261       return;
1262     }
1263
1264   g_variant_get (res, "(o)", &app->priv->client_path);
1265   g_variant_unref (res);
1266
1267   g_debug ("Registered client at '%s'", app->priv->client_path);
1268
1269   app->priv->client_proxy = g_dbus_proxy_new_sync (app->priv->session_bus, 0,
1270                                                    NULL,
1271                                                    "org.gnome.SessionManager",
1272                                                    app->priv->client_path,
1273                                                    "org.gnome.SessionManager.ClientPrivate",
1274                                                    NULL,
1275                                                    &error);
1276   if (error)
1277     {
1278       g_warning ("Failed to get client proxy: %s", error->message);
1279       g_error_free (error);
1280       g_clear_object (&app->priv->sm_proxy);
1281       g_free (app->priv->client_path);
1282       app->priv->client_path = NULL;
1283       return;
1284     }
1285
1286   g_signal_connect (app->priv->client_proxy, "g-signal", G_CALLBACK (client_proxy_signal), app);
1287 }
1288
1289
1290
1291 /**
1292  * GtkApplicationInhibitFlags:
1293  * @GTK_APPLICATION_INHIBIT_LOGOUT: Inhibit ending the user session
1294  *     by logging out or by shutting down the computer
1295  * @GTK_APPLICATION_INHIBIT_SWITCH: Inhibit user switching
1296  * @GTK_APPLICATION_INHIBIT_SUSPEND: Inhibit suspending the
1297  *     session or computer
1298  * @GTK_APPLICATION_INHIBIT_IDLE: Inhibit the session being
1299  *     marked as idle (and possibly locked)
1300  *
1301  * Types of user actions that may be blocked by gtk_application_inhibit().
1302  *
1303  * Since: 3.4
1304  */
1305
1306 /**
1307  * gtk_application_inhibit:
1308  * @application: the #GApplication
1309  * @window: (allow-none): a #GtkWindow, or %NULL
1310  * @flags: what types of actions should be inhibited
1311  * @reason: (allow-none): a short, human-readable string that explains
1312  *     why these operations are inhibited
1313  *
1314  * Inform the session manager that certain types of actions should be
1315  * inhibited. This is not guaranteed to work on all platforms and for
1316  * all types of actions.
1317  *
1318  * Applications should invoke this method when they begin an operation
1319  * that should not be interrupted, such as creating a CD or DVD. The
1320  * types of actions that may be blocked are specified by the @flags
1321  * parameter. When the application completes the operation it should
1322  * call g_application_uninhibit() to remove the inhibitor. Note that
1323  * an application can have multiple inhibitors, and all of the must
1324  * be individually removed. Inhibitors are also cleared when the
1325  * application exits.
1326  *
1327  * Applications should not expect that they will always be able to block
1328  * the action. In most cases, users will be given the option to force
1329  * the action to take place.
1330  *
1331  * Reasons should be short and to the point.
1332  *
1333  * If @window is given, the session manager may point the user to
1334  * this window to find out more about why the action is inhibited.
1335  *
1336  * Returns: A non-zero cookie that is used to uniquely identify this
1337  *     request. It should be used as an argument to g_application_uninhibit()
1338  *     in order to remove the request. If the platform does not support
1339  *     inhibiting or the request failed for some reason, 0 is returned.
1340  *
1341  * Since: 3.4
1342  */
1343 guint
1344 gtk_application_inhibit (GtkApplication             *application,
1345                          GtkWindow                  *window,
1346                          GtkApplicationInhibitFlags  flags,
1347                          const gchar                *reason)
1348 {
1349   GVariant *res;
1350   GError *error = NULL;
1351   guint cookie;
1352   guint xid;
1353
1354   g_return_val_if_fail (GTK_IS_APPLICATION (application), 0);
1355   g_return_val_if_fail (!g_application_get_is_remote (G_APPLICATION (application)), 0);
1356   g_return_val_if_fail (application->priv->sm_proxy != NULL, 0);
1357
1358   if (window != NULL)
1359     xid = GDK_WINDOW_XID (gtk_widget_get_window (GTK_WIDGET (window)));
1360   else
1361     xid = 0;
1362
1363   res = g_dbus_proxy_call_sync (application->priv->sm_proxy,
1364                                 "Inhibit",
1365                                 g_variant_new ("(susu)",
1366                                                application->priv->app_id,
1367                                                xid,
1368                                                reason,
1369                                                flags),
1370                                 G_DBUS_CALL_FLAGS_NONE,
1371                                 G_MAXINT,
1372                                 NULL,
1373                                 &error);
1374  if (error)
1375     {
1376       g_warning ("Calling Inhibit failed: %s", error->message);
1377       g_error_free (error);
1378       return 0;
1379     }
1380
1381   g_variant_get (res, "(u)", &cookie);
1382   g_variant_unref (res);
1383
1384   return cookie;
1385 }
1386
1387 /**
1388  * gtk_application_uninhibit:
1389  * @application: the #GApplication
1390  * @cookie: a cookie that was returned by g_application_inhibit()
1391  *
1392  * Removes an inhibitor that has been established with g_application_inhibit().
1393  * Inhibitors are also cleared when the application exits.
1394  *
1395  * Since: 3.4
1396  */
1397 void
1398 gtk_application_uninhibit (GtkApplication *application,
1399                            guint           cookie)
1400 {
1401   g_return_if_fail (GTK_IS_APPLICATION (application));
1402   g_return_if_fail (!g_application_get_is_remote (G_APPLICATION (application)));
1403   g_return_if_fail (application->priv->sm_proxy != NULL);
1404
1405   g_dbus_proxy_call (application->priv->sm_proxy,
1406                      "Uninhibit",
1407                      g_variant_new ("(u)", cookie),
1408                      G_DBUS_CALL_FLAGS_NONE,
1409                      G_MAXINT,
1410                      NULL, NULL, NULL);
1411 }
1412
1413 /**
1414  * gtk_application_is_inhibited:
1415  * @application: the #GApplication
1416  * @flags: what types of actions should be queried
1417  *
1418  * Determines if any of the actions specified in @flags are
1419  * currently inhibited (possibly by another application).
1420  *
1421  * Returns: %TRUE if any of the actions specified in @flags are inhibited
1422  *
1423  * Since: 3.4
1424  */
1425 gboolean
1426 gtk_application_is_inhibited (GtkApplication             *application,
1427                               GtkApplicationInhibitFlags  flags)
1428 {
1429   GVariant *res;
1430   GError *error = NULL;
1431   gboolean inhibited;
1432
1433   g_return_val_if_fail (GTK_IS_APPLICATION (application), FALSE);
1434   g_return_val_if_fail (!g_application_get_is_remote (G_APPLICATION (application)), FALSE);
1435   g_return_val_if_fail (application->priv->sm_proxy != NULL, FALSE);
1436
1437   res = g_dbus_proxy_call_sync (application->priv->sm_proxy,
1438                                 "IsInhibited",
1439                                 g_variant_new ("(u)", flags),
1440                                 G_DBUS_CALL_FLAGS_NONE,
1441                                 G_MAXINT,
1442                                 NULL,
1443                                 &error);
1444   if (error)
1445     {
1446       g_warning ("Calling IsInhibited failed: %s", error->message);
1447       g_error_free (error);
1448       return FALSE;
1449     }
1450
1451   g_variant_get (res, "(b)", &inhibited);
1452   g_variant_unref (res);
1453
1454   return inhibited;
1455 }
1456
1457 #elif defined(GDK_WINDOWING_QUARTZ)
1458
1459 /* OS X implementation copied from EggSMClient, but simplified since
1460  * it doesn't need to interact with the user.
1461  */
1462
1463 static gboolean
1464 idle_will_quit (gpointer data)
1465 {
1466   GtkApplication *app = data;
1467
1468   if (app->priv->quit_inhibit == 0)
1469     g_application_quit (G_APPLICATION (app));
1470   else
1471     {
1472       GtkApplicationQuartzInhibitor *inhibitor;
1473       GSList *iter;
1474       GtkWidget *dialog;
1475
1476       for (iter = app->priv->inhibitors; iter; iter = iter->next)
1477         {
1478           inhibitor = iter->data;
1479           if (inhibitor->flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1480             break;
1481         }
1482       g_assert (inhibitor != NULL);
1483
1484       dialog = gtk_message_dialog_new (inhibitor->window,
1485                                        GTK_DIALOG_MODAL,
1486                                        GTK_MESSAGE_ERROR,
1487                                        GTK_BUTTONS_OK,
1488                                        _("%s cannot quit at this time:\n\n%s"),
1489                                        g_get_application_name (),
1490                                        inhibitor->reason);
1491       g_signal_connect_swapped (dialog,
1492                                 "response",
1493                                 G_CALLBACK (gtk_widget_destroy),
1494                                 dialog);
1495       gtk_widget_show_all (dialog);
1496     }
1497
1498   return G_SOURCE_REMOVE;
1499 }
1500
1501 static pascal OSErr
1502 quit_requested (const AppleEvent *aevt,
1503                 AppleEvent       *reply,
1504                 long              refcon)
1505 {
1506   GtkApplication *app = GSIZE_TO_POINTER ((gsize)refcon);
1507
1508   /* Don't emit the "quit" signal immediately, since we're
1509    * called from a weird point in the guts of gdkeventloop-quartz.c
1510    */
1511   g_idle_add_full (G_PRIORITY_DEFAULT, idle_will_quit, app, NULL);
1512
1513   return app->priv->quit_inhibit == 0 ? noErr : userCanceledErr;
1514 }
1515
1516 static void
1517 gtk_application_startup_session_quartz (GtkApplication *app)
1518 {
1519   if (app->priv->register_session)
1520     AEInstallEventHandler (kCoreEventClass, kAEQuitApplication,
1521                            NewAEEventHandlerUPP (quit_requested),
1522                            (long)GPOINTER_TO_SIZE (app), false);
1523 }
1524
1525 guint
1526 gtk_application_inhibit (GtkApplication             *application,
1527                          GtkWindow                  *window,
1528                          GtkApplicationInhibitFlags  flags,
1529                          const gchar                *reason)
1530 {
1531   GtkApplicationQuartzInhibitor *inhibitor;
1532
1533   g_return_val_if_fail (GTK_IS_APPLICATION (application), 0);
1534   g_return_val_if_fail (flags != 0, 0);
1535
1536   inhibitor = g_slice_new (GtkApplicationQuartzInhibitor);
1537   inhibitor->cookie = ++application->priv->next_cookie;
1538   inhibitor->flags = flags;
1539   inhibitor->reason = g_strdup (reason);
1540   inhibitor->window = window ? g_object_ref (window) : NULL;
1541
1542   application->priv->inhibitors = g_slist_prepend (application->priv->inhibitors, inhibitor);
1543
1544   if (flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1545     application->priv->quit_inhibit++;
1546
1547   return inhibitor->cookie;
1548 }
1549
1550 void
1551 gtk_application_uninhibit (GtkApplication *application,
1552                            guint           cookie)
1553 {
1554   GSList *iter;
1555
1556   for (iter = application->priv->inhibitors; iter; iter = iter->next)
1557     {
1558       GtkApplicationQuartzInhibitor *inhibitor = iter->data;
1559
1560       if (inhibitor->cookie == cookie)
1561         {
1562           if (inhibitor->flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1563             application->priv->quit_inhibit--;
1564           gtk_application_quartz_inhibitor_free (inhibitor);
1565           application->priv->inhibitors = g_slist_delete_link (application->priv->inhibitors, iter);
1566           return;
1567         }
1568     }
1569
1570   g_warning ("Invalid inhibitor cookie");
1571 }
1572
1573 gboolean
1574 gtk_application_is_inhibited (GtkApplication             *application,
1575                               GtkApplicationInhibitFlags  flags)
1576 {
1577   if (flags & GTK_APPLICATION_INHIBIT_LOGOUT)
1578     return application->priv->quit_inhibit > 0;
1579
1580   return FALSE;
1581 }
1582
1583 #else
1584
1585 /* Trivial implementation.
1586  *
1587  * For the inhibit API on Windows, see
1588  * http://msdn.microsoft.com/en-us/library/ms700677%28VS.85%29.aspx
1589  */
1590
1591 guint
1592 gtk_application_inhibit (GtkApplication             *application,
1593                          GtkWindow                  *window,
1594                          GtkApplicationInhibitFlags  flags,
1595                          const gchar                *reason)
1596 {
1597   return 0;
1598 }
1599
1600 void
1601 gtk_application_uninhibit (GtkApplication *application,
1602                            guint           cookie)
1603 {
1604 }
1605
1606 gboolean
1607 gtk_application_is_inhibited (GtkApplication             *application,
1608                               GtkApplicationInhibitFlags  flags)
1609 {
1610   return FALSE;
1611 }
1612
1613 #endif