]> Pileus Git - ~andy/gtk/blob - gtk/gtkapplication.c
GtkApplication: Initial attempt at section headings
[~andy/gtk] / gtk / gtkapplication.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the licence, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  *
19  * Author: Ryan Lortie <desrt@desrt.ca>
20  */
21
22 #include "config.h"
23
24 #include <stdlib.h>
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 #include <string.h>
29
30 #include "gtkapplication.h"
31 #include "gtkmarshalers.h"
32 #include "gtkmain.h"
33 #include "gtkwindow.h"
34 #include "gtkcheckmenuitem.h"
35 #include "gtkseparatormenuitem.h"
36 #include "gtkmenu.h"
37
38 #include <gdk/gdk.h>
39 #ifdef GDK_WINDOWING_X11
40 #include <gdk/x11/gdkx.h>
41 #endif
42
43 /**
44  * SECTION:gtkapplication
45  * @title: GtkApplication
46  * @short_description: Application class
47  *
48  * #GtkApplication is a class that handles many important aspects
49  * of a GTK+ application in a convenient fashion, without enforcing
50  * a one-size-fits-all application model.
51  *
52  * Currently, GtkApplication handles GTK+ initialization, application
53  * uniqueness, provides some basic scriptability by exporting 'actions',
54  * and manages a list of toplevel windows whose life-cycle is automatically
55  * tied to the life-cycle of your application.
56  *
57  * <example id="gtkapplication"><title>A simple application</title>
58  * <programlisting>
59  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../examples/bloatpad.c">
60  *  <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
61  * </xi:include>
62  * </programlisting>
63  * </example>
64  */
65
66 enum {
67   WINDOW_ADDED,
68   WINDOW_REMOVED,
69   LAST_SIGNAL
70 };
71
72 static guint gtk_application_signals[LAST_SIGNAL];
73
74 G_DEFINE_TYPE (GtkApplication, gtk_application, G_TYPE_APPLICATION)
75
76 struct _GtkApplicationPrivate
77 {
78   GList *windows;
79 };
80
81 static gboolean
82 gtk_application_focus_in_event_cb (GtkWindow      *window,
83                                    GdkEventFocus  *event,
84                                    GtkApplication *application)
85 {
86   GtkApplicationPrivate *priv = application->priv;
87   GList *link;
88
89   /* Keep the window list sorted by most-recently-focused. */
90   link = g_list_find (priv->windows, window);
91   if (link != NULL && link != priv->windows)
92     {
93       priv->windows = g_list_remove_link (priv->windows, link);
94       priv->windows = g_list_concat (link, priv->windows);
95     }
96
97   return FALSE;
98 }
99
100 static void
101 gtk_application_startup (GApplication *application)
102 {
103   G_APPLICATION_CLASS (gtk_application_parent_class)
104     ->startup (application);
105
106   gtk_init (0, 0);
107 }
108
109 static void
110 gtk_application_add_platform_data (GApplication    *application,
111                                    GVariantBuilder *builder)
112 {
113   const gchar *startup_id;
114
115   startup_id = getenv ("DESKTOP_STARTUP_ID");
116   
117   if (startup_id && g_utf8_validate (startup_id, -1, NULL))
118     g_variant_builder_add (builder, "{sv}", "desktop-startup-id",
119                            g_variant_new_string (startup_id));
120 }
121
122 static void
123 gtk_application_before_emit (GApplication *application,
124                              GVariant     *platform_data)
125 {
126   GVariantIter iter;
127   const gchar *key;
128   GVariant *value;
129
130   g_variant_iter_init (&iter, platform_data);
131   while (g_variant_iter_loop (&iter, "{&sv}", &key, &value))
132     {
133 #ifdef GDK_WINDOWING_X11
134       if (strcmp (key, "desktop-startup-id") == 0)
135         {
136           GdkDisplay *display;
137           const gchar *id;
138
139           display = gdk_display_get_default ();
140           id = g_variant_get_string (value, NULL);
141           gdk_x11_display_set_startup_notification_id (display, id);
142        }
143 #endif
144     }
145 }
146
147 static void
148 gtk_application_after_emit (GApplication *application,
149                             GVariant     *platform_data)
150 {
151   gdk_notify_startup_complete ();
152 }
153
154 static void
155 gtk_application_init (GtkApplication *application)
156 {
157   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application,
158                                                    GTK_TYPE_APPLICATION,
159                                                    GtkApplicationPrivate);
160 }
161
162 static void
163 gtk_application_window_added (GtkApplication *application,
164                               GtkWindow      *window)
165 {
166   GtkApplicationPrivate *priv = application->priv;
167
168   priv->windows = g_list_prepend (priv->windows, window);
169   gtk_window_set_application (window, application);
170   g_application_hold (G_APPLICATION (application));
171
172   g_signal_connect (window, "focus-in-event",
173                     G_CALLBACK (gtk_application_focus_in_event_cb),
174                     application);
175 }
176
177 static void
178 gtk_application_window_removed (GtkApplication *application,
179                                 GtkWindow      *window)
180 {
181   GtkApplicationPrivate *priv = application->priv;
182
183   g_signal_handlers_disconnect_by_func (window,
184                                         gtk_application_focus_in_event_cb,
185                                         application);
186
187   g_application_release (G_APPLICATION (application));
188   priv->windows = g_list_remove (priv->windows, window);
189   gtk_window_set_application (window, NULL);
190 }
191
192 static void
193 gtk_application_class_init (GtkApplicationClass *class)
194 {
195   GApplicationClass *application_class = G_APPLICATION_CLASS (class);
196
197   application_class->add_platform_data = gtk_application_add_platform_data;
198   application_class->before_emit = gtk_application_before_emit;
199   application_class->after_emit = gtk_application_after_emit;
200   application_class->startup = gtk_application_startup;
201
202   class->window_added = gtk_application_window_added;
203   class->window_removed = gtk_application_window_removed;
204
205   g_type_class_add_private (class, sizeof (GtkApplicationPrivate));
206
207   /**
208    * GtkApplication::window-added:
209    * @application: the #GtkApplication which emitted the signal
210    * @window: the newly-added #GtkWindow
211    *
212    * Emitted when a #GtkWindow is added to @application through
213    * gtk_application_add_window().
214    *
215    * Since: 3.2
216    */
217   gtk_application_signals[WINDOW_ADDED] =
218     g_signal_new ("window-added", GTK_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
219                   G_STRUCT_OFFSET (GtkApplicationClass, window_added),
220                   NULL, NULL,
221                   g_cclosure_marshal_VOID__OBJECT,
222                   G_TYPE_NONE, 1, GTK_TYPE_WINDOW);
223
224   /**
225    * GtkApplication::window-removed:
226    * @application: the #GtkApplication which emitted the signal
227    * @window: the #GtkWindow that is being removed
228    *
229    * Emitted when a #GtkWindow is removed from @application,
230    * either as a side-effect of being destroyed or explicitly
231    * through gtk_application_remove_window().
232    *
233    * Since: 3.2
234    */
235   gtk_application_signals[WINDOW_REMOVED] =
236     g_signal_new ("window-removed", GTK_TYPE_APPLICATION, G_SIGNAL_RUN_FIRST,
237                   G_STRUCT_OFFSET (GtkApplicationClass, window_removed),
238                   NULL, NULL,
239                   g_cclosure_marshal_VOID__OBJECT,
240                   G_TYPE_NONE, 1, GTK_TYPE_WINDOW);
241 }
242
243 /**
244  * gtk_application_new:
245  * @application_id: the application id
246  * @flags: the application flags
247  *
248  * Creates a new #GtkApplication instance.
249  *
250  * This function calls g_type_init() for you. gtk_init() is called
251  * as soon as the application gets registered as the primary instance.
252  *
253  * The application id must be valid. See g_application_id_is_valid().
254  *
255  * Returns: a new #GtkApplication instance
256  */
257 GtkApplication *
258 gtk_application_new (const gchar       *application_id,
259                      GApplicationFlags  flags)
260 {
261   g_return_val_if_fail (g_application_id_is_valid (application_id), NULL);
262
263   g_type_init ();
264
265   return g_object_new (GTK_TYPE_APPLICATION,
266                        "application-id", application_id,
267                        "flags", flags,
268                        NULL);
269 }
270
271 /**
272  * gtk_application_add_window:
273  * @application: a #GtkApplication
274  * @window: a #GtkWindow
275  *
276  * Adds a window from @application.
277  *
278  * This call is equivalent to setting the #GtkWindow:application
279  * property of @window to @application.
280  *
281  * Normally, the connection between the application and the window
282  * will remain until the window is destroyed, but you can explicitly
283  * remove it with gtk_application_remove_window().
284  *
285  * GTK+ will keep the application running as long as it has
286  * any windows.
287  *
288  * Since: 3.0
289  **/
290 void
291 gtk_application_add_window (GtkApplication *application,
292                             GtkWindow      *window)
293 {
294   g_return_if_fail (GTK_IS_APPLICATION (application));
295
296   if (!g_list_find (application->priv->windows, window))
297     g_signal_emit (application,
298                    gtk_application_signals[WINDOW_ADDED], 0, window);
299 }
300
301 /**
302  * gtk_application_remove_window:
303  * @application: a #GtkApplication
304  * @window: a #GtkWindow
305  *
306  * Remove a window from @application.
307  *
308  * If @window belongs to @application then this call is equivalent to
309  * setting the #GtkWindow:application property of @window to
310  * %NULL.
311  *
312  * The application may stop running as a result of a call to this
313  * function.
314  *
315  * Since: 3.0
316  **/
317 void
318 gtk_application_remove_window (GtkApplication *application,
319                                GtkWindow      *window)
320 {
321   g_return_if_fail (GTK_IS_APPLICATION (application));
322
323   if (g_list_find (application->priv->windows, window))
324     g_signal_emit (application,
325                    gtk_application_signals[WINDOW_REMOVED], 0, window);
326 }
327
328 /**
329  * gtk_application_get_windows:
330  * @application: a #GtkApplication
331  *
332  * Gets a list of the #GtkWindow<!-- -->s associated with @application.
333  *
334  * The list is sorted by most recently focused window, such that the first
335  * element is the currently focused window.  (Useful for choosing a parent
336  * for a transient window.)
337  *
338  * The list that is returned should not be modified in any way. It will
339  * only remain valid until the next focus change or window creation or
340  * deletion.
341  *
342  * Returns: (element-type GtkWindow) (transfer none): a #GList of #GtkWindow
343  *
344  * Since: 3.0
345  **/
346 GList *
347 gtk_application_get_windows (GtkApplication *application)
348 {
349   g_return_val_if_fail (GTK_IS_APPLICATION (application), NULL);
350
351   return application->priv->windows;
352 }
353
354 /* GtkMenu construction {{{1 */
355
356 typedef struct {
357   GActionGroup *group;
358   gchar        *name;
359   gchar        *target;
360   gulong        enabled_changed_id;
361   gulong        state_changed_id;
362   gulong        activate_handler;
363 } ActionData;
364
365 static void
366 action_data_free (gpointer data)
367 {
368   ActionData *a = data;
369
370   if (a->enabled_changed_id)
371     g_signal_handler_disconnect (a->group, a->enabled_changed_id);
372
373   if (a->state_changed_id)
374     g_signal_handler_disconnect (a->group, a->state_changed_id);
375
376   g_object_unref (a->group);
377   g_free (a->name);
378   g_free (a->target);
379
380   g_free (a);
381 }
382
383 static void
384 enabled_changed (GActionGroup *group,
385                  const gchar  *action_name,
386                  gboolean      enabled,
387                  GtkWidget    *widget)
388 {
389   gtk_widget_set_sensitive (widget, enabled);
390 }
391
392 static void
393 item_activated (GtkWidget *w,
394                 gpointer   data)
395 {
396   ActionData *a;
397   GVariant *parameter;
398
399   a = g_object_get_data (G_OBJECT (w), "action");
400   if (a->target)
401     parameter = g_variant_ref_sink (g_variant_new_string (a->target));
402   else
403     parameter = NULL;
404   g_action_group_activate_action (a->group, a->name, parameter);
405   if (parameter)
406     g_variant_unref (parameter);
407 }
408
409 static void
410 toggle_state_changed (GActionGroup     *group,
411                       const gchar      *name,
412                       GVariant         *state,
413                       GtkCheckMenuItem *w)
414 {
415   ActionData *a;
416
417   a = g_object_get_data (G_OBJECT (w), "action");
418   g_signal_handler_block (w, a->activate_handler);
419   gtk_check_menu_item_set_active (w, g_variant_get_boolean (state));
420   g_signal_handler_unblock (w, a->activate_handler);
421 }
422
423 static void
424 radio_state_changed (GActionGroup     *group,
425                      const gchar      *name,
426                      GVariant         *state,
427                      GtkCheckMenuItem *w)
428 {
429   ActionData *a;
430   gboolean b;
431
432   a = g_object_get_data (G_OBJECT (w), "action");
433   g_signal_handler_block (w, a->activate_handler);
434   b = g_strcmp0 (a->target, g_variant_get_string (state, NULL)) == 0;
435   gtk_check_menu_item_set_active (w, b);
436   g_signal_handler_unblock (w, a->activate_handler);
437 }
438
439 static GtkWidget *
440 create_menuitem_from_model (GMenuModel   *model,
441                             gint          item,
442                             GActionGroup *group)
443 {
444   GtkWidget *w;
445   gchar *label;
446   gchar *action;
447   gchar *target;
448   gchar *s;
449   ActionData *a;
450   const GVariantType *type;
451   GVariant *v;
452
453   label = NULL;
454   g_menu_model_get_item_attribute (model, item, G_MENU_ATTRIBUTE_LABEL, "s", &label);
455
456   action = NULL;
457   g_menu_model_get_item_attribute (model, item, G_MENU_ATTRIBUTE_ACTION, "s", &action);
458
459   if (action != NULL)
460     type = g_action_group_get_action_state_type (group, action);
461   else
462     type = NULL;
463
464   if (type == NULL)
465     w = gtk_menu_item_new_with_mnemonic (label);
466   else if (g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
467     w = gtk_check_menu_item_new_with_label (label);
468   else if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
469     {
470       w = gtk_check_menu_item_new_with_label (label);
471       gtk_check_menu_item_set_draw_as_radio (GTK_CHECK_MENU_ITEM (w), TRUE);
472     }
473   else
474     g_assert_not_reached ();
475
476   if (action != NULL)
477     {
478       a = g_new0 (ActionData, 1);
479       a->group = g_object_ref (group);
480       a->name = g_strdup (action);
481       g_object_set_data_full (G_OBJECT (w), "action", a, action_data_free);
482
483       if (!g_action_group_get_action_enabled (group, action))
484         gtk_widget_set_sensitive (w, FALSE);
485
486       s = g_strconcat ("action-enabled-changed::", action, NULL);
487       a->enabled_changed_id = g_signal_connect (group, s,
488                                                 G_CALLBACK (enabled_changed), w);
489       g_free (s);
490       a->activate_handler = g_signal_connect (w, "activate",
491                                               G_CALLBACK (item_activated), NULL);
492
493       if (type == NULL)
494         {
495           /* all set */
496         }
497       else if (g_variant_type_equal (type, G_VARIANT_TYPE_BOOLEAN))
498         {
499           s = g_strconcat ("action-state-changed::", action, NULL);
500           a->state_changed_id = g_signal_connect (group, s,
501                                                   G_CALLBACK (toggle_state_changed), w);
502           g_free (s);
503           v = g_action_group_get_action_state (group, action);
504           gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w),
505                                           g_variant_get_boolean (v));
506           g_variant_unref (v);
507         }
508       else if (g_variant_type_equal (type, G_VARIANT_TYPE_STRING))
509         {
510           s = g_strconcat ("action-state-changed::", action, NULL);
511           a->state_changed_id = g_signal_connect (group, s,
512                                                   G_CALLBACK (radio_state_changed), w);
513           g_free (s);
514           g_menu_model_get_item_attribute (model, item, G_MENU_ATTRIBUTE_TARGET, "s", &target);
515           a->target = g_strdup (target);
516           v = g_action_group_get_action_state (group, action);
517           gtk_check_menu_item_set_active (GTK_CHECK_MENU_ITEM (w),
518                                           g_strcmp0 (g_variant_get_string (v, NULL), target) == 0);
519           g_variant_unref (v);
520           g_free (target);
521         }
522       else
523         g_assert_not_reached ();
524     }
525
526   g_free (label);
527   g_free (action);
528
529   return w;
530 }
531
532 static void populate_menu_from_model (GtkMenuShell *menu,
533                                       GMenuModel   *model,
534                                       GActionGroup *group);
535
536 static void
537 append_items_from_model (GtkMenuShell *menu,
538                          GMenuModel   *model,
539                          GActionGroup *group,
540                          gboolean     *need_separator,
541                          const gchar  *heading)
542 {
543   gint n;
544   gint i;
545   GtkWidget *w;
546   GtkWidget *menuitem;
547   GtkWidget *submenu;
548   GMenuModel *m;
549   gchar *label;
550
551   n = g_menu_model_get_n_items (model);
552
553   if (*need_separator && n > 0)
554     {
555       w = gtk_separator_menu_item_new ();
556       gtk_widget_show (w);
557       gtk_menu_shell_append (menu, w);
558
559       *need_separator = FALSE;
560     }
561
562   if (heading != NULL)
563     {
564       w = gtk_menu_item_new_with_label (heading);
565       gtk_widget_show (w);
566       gtk_widget_set_sensitive (w, FALSE);
567       gtk_menu_shell_append (GTK_MENU_SHELL (menu), w);
568     }
569
570   for (i = 0; i < n; i++)
571     {
572       if ((m = g_menu_model_get_item_link (model, i, G_MENU_LINK_SECTION)))
573         {
574           label = NULL;
575           g_menu_model_get_item_attribute (model, i, G_MENU_ATTRIBUTE_LABEL, "s", &label);
576           append_items_from_model (menu, m, group, need_separator, label);
577           g_object_unref (m);
578           g_free (label);
579           continue;
580         }
581
582       menuitem = create_menuitem_from_model (model, i, group);
583
584       if ((m = g_menu_model_get_item_link (model, i, G_MENU_LINK_SUBMENU)))
585         {
586           submenu = gtk_menu_new ();
587           populate_menu_from_model (GTK_MENU_SHELL (submenu), m, group);
588           gtk_menu_item_set_submenu (GTK_MENU_ITEM (menuitem), submenu);
589           g_object_unref (m);
590         }
591
592       gtk_widget_show (menuitem);
593       gtk_menu_shell_append (menu, menuitem);
594
595       *need_separator = TRUE;
596     }
597 }
598
599 static void
600 populate_menu_from_model (GtkMenuShell *menu,
601                           GMenuModel   *model,
602                           GActionGroup *group)
603 {
604   gboolean need_separator;
605
606   need_separator = FALSE;
607   append_items_from_model (menu, model, group, &need_separator, NULL);
608 }
609
610 typedef struct {
611   GtkApplication *application;
612   GtkMenuShell   *menu;
613   guint           update_idle;
614   GHashTable     *connected;
615 } ItemsChangedData;
616
617 static void
618 free_items_changed_data (gpointer data)
619 {
620   ItemsChangedData *d = data;
621
622   g_object_unref (d->application);
623
624   if (d->update_idle != 0)
625     g_source_remove (d->update_idle);
626
627   g_hash_table_unref (d->connected);
628
629   g_free (d);
630 }
631
632 static gboolean
633 repopulate_menu (gpointer data)
634 {
635   ItemsChangedData *d = data;
636   GList *children, *l;
637   GtkWidget *child;
638   GMenuModel *model;
639
640   /* remove current children */
641   children = gtk_container_get_children (GTK_CONTAINER (d->menu));
642   for (l = children; l; l = l->next)
643     {
644       child = l->data;
645       gtk_container_remove (GTK_CONTAINER (d->menu), child);
646     }
647   g_list_free (children);
648
649   /* repopulate */
650   model = g_application_get_menu (G_APPLICATION (d->application));
651   populate_menu_from_model (d->menu, model, G_ACTION_GROUP (d->application));
652
653   d->update_idle = 0;
654
655   return FALSE;
656 }
657
658 static void
659 connect_to_items_changed (GMenuModel *model,
660                           GCallback   callback,
661                           gpointer    data)
662 {
663   ItemsChangedData *d = data;
664   gint i;
665   GMenuModel *m;
666   GMenuLinkIter *iter;
667
668   if (!g_hash_table_lookup (d->connected, model))
669     {
670       g_signal_connect (model, "items-changed", callback, data);
671       g_hash_table_insert (d->connected, model, model);
672     }
673
674   for (i = 0; i < g_menu_model_get_n_items (model); i++)
675     {
676       iter = g_menu_model_iterate_item_links (model, i);
677       while (g_menu_link_iter_next (iter))
678         {
679           m = g_menu_link_iter_get_value (iter);
680           connect_to_items_changed (m, callback, data);
681           g_object_unref (m);
682         }
683       g_object_unref (iter);
684     }
685 }
686
687 static void
688 items_changed (GMenuModel *model,
689                gint        position,
690                gint        removed,
691                gint        added,
692                gpointer    data)
693 {
694   ItemsChangedData *d = data;
695
696   if (d->update_idle == 0)
697     d->update_idle = gdk_threads_add_idle (repopulate_menu, data);
698   connect_to_items_changed (model, G_CALLBACK (items_changed), data);
699 }
700
701 /**
702  * gtk_application_get_menu:
703  * @application: a #GtkApplication
704  *
705  * Populates a menu widget from a menu model that is
706  * associated with @application. See g_application_set_menu().
707  * The menu items will be connected to action of @application,
708  * as indicated by the menu model. The menus contents will be
709  * updated automatically in response to menu model changes.
710  *
711  * It is the callers responsibility to add the menu at a
712  * suitable place in the widget hierarchy.
713  *
714  * This function returns %NULL if @application has no associated
715  * menu model. It also returns %NULL if the menu model is
716  * represented outside the application, e.g. by an application
717  * menu in the desktop shell.
718  *
719  * @menu may be a #GtkMenu or a #GtkMenuBar.
720  *
721  * Returns: A #GtkMenu that has been populated from the
722  *     #GMenuModel that is associated with @application,
723  *     or %NULL
724  */
725 GtkMenu *
726 gtk_application_get_menu (GtkApplication *application)
727 {
728   GtkWidget *menu;
729   GMenuModel *model;
730   ItemsChangedData *data;
731
732   model = g_application_get_menu (G_APPLICATION (application));
733
734   if (!model)
735     return NULL;
736
737   /* FIXME: find out if external menu is available. If yes, return NULL */
738
739   menu = gtk_menu_new ();
740
741   populate_menu_from_model (GTK_MENU_SHELL (menu), model, G_ACTION_GROUP (application));
742
743   data = g_new (ItemsChangedData, 1);
744   data->application = g_object_ref (application);
745   data->menu = GTK_MENU_SHELL (menu);
746   data->update_idle = 0;
747   data->connected = g_hash_table_new (NULL, NULL);
748
749   g_object_set_data_full (G_OBJECT (menu), "gtk-application-menu-data",
750                           data, free_items_changed_data);
751
752   connect_to_items_changed (model, G_CALLBACK (items_changed), data);
753
754   return GTK_MENU (menu);
755 }