]> Pileus Git - ~andy/gtk/blob - gtk/gtkapplication.c
application: Allow sub-classes to override the Window creation
[~andy/gtk] / gtk / gtkapplication.c
1 /* GTK - The GIMP Toolkit
2  *
3  * Copyright (C) 2010 Red Hat, Inc.
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  *
20  * Author: Colin Walters <walters@verbum.org>
21  */
22
23 /*
24  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
25  * file for a list of people on the GTK+ Team.  See the ChangeLog
26  * files for a list of changes.  These files are distributed with
27  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
28  */
29
30 #include "config.h"
31
32 #include <stdlib.h>
33 #include <unistd.h>
34
35 #include "gtkapplication.h"
36 #include "gtkmain.h"
37 #include "gtkmarshalers.h"
38 #include "gtkintl.h"
39 #include "gtkprivate.h"
40
41 #include "gtkalias.h"
42
43 #include <gdk/gdk.h>
44 #ifdef GDK_WINDOWING_X11
45 #include <gdk/x11/gdkx.h>
46 #endif
47
48 /**
49  * SECTION:gtkapplication
50  * @title: GtkApplication
51  * @short_description: Application class
52  *
53  * #GtkApplication is a class that handles many important aspects
54  * of a GTK+ application in a convenient fashion, without enforcing
55  * a one-size-fits-all application model.
56  *
57  * Currently, GtkApplication handles application uniqueness, provides
58  * some basic scriptability by exporting 'actions', implements some
59  * standard actions itself (such as 'Quit') and provides a main window
60  * whose life-cycle is automatically tied to the life-cycle of your
61  * application.
62  *
63  * <example id="gtkapplication"><title>A simple application</title>
64  * <programlisting>
65  * <xi:include xmlns:xi="http://www.w3.org/2001/XInclude" parse="text" href="../../../../gtk/tests/gtk-example-application.c">
66  *  <xi:fallback>FIXME: MISSING XINCLUDE CONTENT</xi:fallback>
67  * </xi:include>
68  * </programlisting>
69  * </example>
70  */
71 enum
72 {
73   PROP_0,
74   PROP_WINDOW
75 };
76
77 enum
78 {
79   ACTIVATED,
80   QUIT,
81   ACTION,
82
83   LAST_SIGNAL
84 };
85
86 static guint gtk_application_signals[LAST_SIGNAL] = { 0 };
87
88 struct _GtkApplicationPrivate
89 {
90   GtkActionGroup *main_actions;
91
92   GtkWindow *default_window;
93   GSList *windows;
94 };
95
96 G_DEFINE_TYPE (GtkApplication, gtk_application, G_TYPE_APPLICATION)
97
98 static void
99 process_timestamp_from_platform_data (GVariant *platform_data)
100 {
101   /* TODO - extract timestamp from here, update GDK time */
102 }
103
104 static gboolean
105 gtk_application_default_quit (GtkApplication *application)
106 {
107   gtk_main_quit ();
108   return TRUE;
109 }
110
111 static gboolean
112 gtk_application_default_quit_with_data (GApplication *application,
113                                         GVariant     *platform_data)
114 {
115   gboolean result;
116
117   process_timestamp_from_platform_data (platform_data);
118   
119   g_signal_emit (application, gtk_application_signals[QUIT], 0, &result);
120
121   return result;
122 }
123
124 static void
125 gtk_application_default_run (GApplication *application)
126 {
127   gtk_main ();
128 }
129
130 static void
131 gtk_application_default_prepare_activation (GApplication *application,
132                                             GVariant     *arguments,
133                                             GVariant     *platform_data)
134 {
135   GVariantIter iter;
136   gchar *key;
137   GVariant *value;
138
139   g_variant_iter_init (&iter, platform_data);
140   while (g_variant_iter_next (&iter, "{&sv}", &key, &value))
141     {
142       if (strcmp (key, "startup-notification-id") == 0 &&
143           g_variant_is_of_type (value, G_VARIANT_TYPE_STRING))
144         gdk_notify_startup_complete_with_id (g_variant_get_string (value, NULL));
145       g_variant_unref (value);
146     }
147   
148   g_signal_emit (G_OBJECT (application), gtk_application_signals[ACTIVATED], 0, arguments);
149 }
150
151 static void
152 gtk_application_default_activated (GtkApplication *application,
153                                    GVariant     *arguments)
154 {
155   GtkApplication *app = GTK_APPLICATION (application);
156
157   /* TODO: should we raise the last focused window instead ? */
158   if (app->priv->default_window != NULL)
159     gtk_window_present (app->priv->default_window);
160 }
161
162 static void
163 gtk_application_default_action (GtkApplication *application,
164                                 const gchar    *action_name)
165 {
166   GtkAction *action;
167
168   action = gtk_action_group_get_action (application->priv->main_actions, action_name);
169   if (action)
170     {
171       gtk_action_activate (action);
172     }
173 }
174
175 static GtkWindow *
176 gtk_application_default_create_window (GtkApplication *application)
177 {
178   return GTK_WINDOW (gtk_window_new (GTK_WINDOW_TOPLEVEL));
179 }
180
181 static void
182 gtk_application_default_action_with_data (GApplication *application,
183                                           const gchar  *action_name,
184                                           GVariant     *platform_data)
185 {
186   process_timestamp_from_platform_data (platform_data);
187
188   g_signal_emit (application, gtk_application_signals[ACTION], g_quark_from_string (action_name));
189 }
190
191 static GVariant *
192 gtk_application_format_activation_data (void)
193 {
194   const gchar *startup_id = NULL;
195   GdkDisplay *display = gdk_display_get_default ();
196   GVariantBuilder builder;
197
198   g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
199
200   /* try and get the startup notification id from GDK, the environment
201    * or, if everything else failed, fake one.
202    */
203 #ifdef GDK_WINDOWING_X11
204   startup_id = gdk_x11_display_get_startup_notification_id (display);
205 #endif /* GDK_WINDOWING_X11 */
206
207   if (startup_id)
208     g_variant_builder_add (&builder, "{sv}", "startup-notification-id",
209                            g_variant_new ("s", startup_id));
210   return g_variant_builder_end (&builder);
211 }
212
213 static GVariant *
214 variant_from_argv (int    argc,
215                    char **argv)
216 {
217   GVariantBuilder builder;
218   int i;
219
220   g_variant_builder_init (&builder, G_VARIANT_TYPE ("aay"));
221
222   for (i = 1; i < argc; i++)
223     {
224       guint8 *argv_bytes;
225
226       argv_bytes = (guint8*) argv[i];
227       g_variant_builder_add_value (&builder,
228                                    g_variant_new_byte_array (argv_bytes, -1));
229     }
230   
231   return g_variant_builder_end (&builder);
232 }
233
234 /**
235  * gtk_application_new:
236  * @appid: System-dependent application identifier
237  * @argc: (allow-none) (inout): System argument count
238  * @argv: (allow-none) (inout): System argument vector
239  *
240  * Create a new #GtkApplication, or if one has already been initialized
241  * in this process, return the existing instance. This function will as
242  * a side effect initialize the display system; see gtk_init().
243  *
244  * For the behavior if this application is running in another process,
245  * see g_application_new().
246  *
247  * Returns: (transfer full): A newly-referenced #GtkApplication
248  *
249  * Since: 3.0
250  */
251 GtkApplication*
252 gtk_application_new (const gchar   *appid,
253                      gint          *argc,
254                      gchar       ***argv)
255 {
256   GtkApplication *app;
257   gint argc_for_app;
258   gchar **argv_for_app;
259   GVariant *argv_variant;
260   GError *error = NULL;
261
262   gtk_init (argc, argv);
263
264   if (argc)
265     argc_for_app = *argc;
266   else
267     argc_for_app = 0;
268   if (argv)
269     argv_for_app = *argv;
270   else
271     argv_for_app = NULL;
272
273   argv_variant = variant_from_argv (argc_for_app, argv_for_app);
274
275   app = g_initable_new (GTK_TYPE_APPLICATION, 
276                         NULL,
277                         &error,
278                         "application-id", appid, 
279                         "argv", argv_variant, 
280                         NULL);
281   if (!app)
282     {
283       g_error ("%s", error->message);
284       g_clear_error (&error);
285       return NULL;
286     }
287
288   return app;
289 }
290
291 static void
292 on_action_sensitive (GtkAction      *action,
293                      GParamSpec     *pspec,
294                      GtkApplication *app)
295 {
296   g_application_set_action_enabled (G_APPLICATION (app),
297                                     gtk_action_get_name (action),
298                                     gtk_action_get_sensitive (action));
299 }
300
301 /**
302  * gtk_application_set_action_group:
303  * @app: A #GtkApplication
304  * @group: A #GtkActionGroup
305  *
306  * Set @group as this application's global action group.
307  * This will ensure the operating system interface uses
308  * these actions as follows:
309  *
310  * <itemizedlist>
311  *   <listitem>In GNOME 2 this exposes the actions for scripting.</listitem>
312  *   <listitem>In GNOME 3, this function populates the application menu.</listitem>
313  *   <listitem>In Windows prior to version 7, this function does nothing.</listitem>
314  *   <listitem>In Windows 7, this function adds "Tasks" to the Jump List.</listitem>
315  *   <listitem>In Mac OS X, this function extends the Dock menu.</listitem>
316  * </itemizedlist>
317  *
318  * It is an error to call this function more than once.
319  *
320  * Since: 3.0
321  */
322 void
323 gtk_application_set_action_group (GtkApplication *app,
324                                   GtkActionGroup *group)
325 {
326   GList *actions, *iter;
327
328   g_return_if_fail (GTK_IS_APPLICATION (app));
329   g_return_if_fail (app->priv->main_actions == NULL);
330
331   app->priv->main_actions = g_object_ref (group);
332   actions = gtk_action_group_list_actions (group);
333   for (iter = actions; iter; iter = iter->next)
334     {
335       GtkAction *action = iter->data;
336       g_application_add_action (G_APPLICATION (app),
337                                 gtk_action_get_name (action),
338                                 gtk_action_get_tooltip (action));
339       g_signal_connect (action, "notify::sensitive",
340                         G_CALLBACK (on_action_sensitive), app);
341     }
342   g_list_free (actions);
343 }
344
345 static gboolean
346 gtk_application_on_window_destroy (GtkWidget *window,
347                                    gpointer   user_data)
348 {
349   GtkApplication *app = GTK_APPLICATION (user_data);
350
351   app->priv->windows = g_slist_remove (app->priv->windows, window);
352
353   if (app->priv->windows == NULL)
354     gtk_application_quit (app);
355
356   return FALSE;
357 }
358
359 static gchar *default_title;
360
361 /**
362  * gtk_application_add_window:
363  * @app: a #GtkApplication
364  * @window: a toplevel window to add to @app
365  *
366  * Adds a window to the #GtkApplication.
367  *
368  * If the user closes all of the windows added to @app, the default
369  * behaviour is to call gtk_application_quit().
370  *
371  * If your application uses only a single toplevel window, you can
372  * use gtk_application_get_window(). If you are using a sub-class
373  * of #GtkApplication you should call gtk_application_create_window()
374  * to let the #GtkApplication instance create a #GtkWindow and add
375  * it to the list of toplevels of the application. You should call
376  * this function only to add #GtkWindow<!-- -->s that you created
377  * directly using gtk_window_new().
378  *
379  * Since: 3.0
380  */
381 void
382 gtk_application_add_window (GtkApplication *app,
383                             GtkWindow      *window)
384 {
385   GtkApplicationPrivate *priv;
386
387   g_return_if_fail (GTK_IS_APPLICATION (app));
388   g_return_if_fail (GTK_IS_WINDOW (window));
389
390   priv = app->priv;
391
392   if (g_slist_find (priv->windows, window) != NULL)
393     return;
394
395   priv->windows = g_slist_prepend (priv->windows, window);
396
397   if (priv->default_window == NULL)
398     priv->default_window = window;
399
400   if (gtk_window_get_title (window) == NULL && default_title != NULL)
401     gtk_window_set_title (window, default_title);
402
403   g_signal_connect (window, "destroy",
404                     G_CALLBACK (gtk_application_on_window_destroy),
405                     app);
406 }
407
408 /**
409  * gtk_application_get_window:
410  * @app: a #GtkApplication
411  *
412  * A simple #GtkApplication has a "default window". This window should
413  * act as the primary user interaction point with your application.
414  * The window returned by this function is of type #GTK_WINDOW_TYPE_TOPLEVEL
415  * and its properties such as "title" and "icon-name" will be initialized
416  * as appropriate for the platform.
417  *
418  * If the user closes this window, and your application hasn't created
419  * any other windows, the default action will be to call gtk_application_quit().
420  *
421  * If your application has more than one toplevel window (e.g. an
422  * single-document-interface application with multiple open documents),
423  * or if you are constructing your toplevel windows yourself (e.g. using
424  * #GtkBuilder), use gtk_application_create_window() or
425  * gtk_application_add_window() instead.
426  *
427  * Returns: (transfer none): The default #GtkWindow for this application
428  *
429  * Since: 3.0
430  */
431 GtkWindow *
432 gtk_application_get_window (GtkApplication *app)
433 {
434   GtkApplicationPrivate *priv;
435   GtkWindow *window;
436
437   g_return_val_if_fail (GTK_IS_APPLICATION (app), NULL);
438
439   priv = app->priv;
440
441   if (priv->default_window != NULL)
442     return priv->default_window;
443
444   return gtk_application_create_window (app);
445 }
446
447 /**
448  * gtk_application_create_window:
449  * @app: a #GtkApplication
450  *
451  * Creates a new #GtkWindow for the application.
452  *
453  * This function calls the #GtkApplication::create_window() virtual function,
454  * which can be overridden by sub-classes, for instance to use #GtkBuilder to
455  * create the user interface. After creating a new #GtkWindow instance, it will
456  * be added to the list of toplevels associated to the application.
457  *
458  * Return value: (transfer none): the newly created application #GtkWindow
459  *
460  * Since: 3.0
461  */
462 GtkWindow *
463 gtk_application_create_window (GtkApplication *app)
464 {
465   GtkWindow *window;
466
467   g_return_val_if_fail (GTK_IS_APPLICATION (app), NULL);
468
469   window = GTK_APPLICATION_GET_CLASS (app)->create_window (app);
470   gtk_application_add_window (app, window);
471
472   return window;
473 }
474
475 /**
476  * gtk_application_run:
477  * @app: a #GtkApplication
478  *
479  * Runs the main loop; see g_application_run().
480  * The default implementation for #GtkApplication uses gtk_main().
481  *
482  * Since: 3.0
483  */
484 void
485 gtk_application_run (GtkApplication *app)
486 {
487   g_application_run (G_APPLICATION (app));
488 }
489
490 /**
491  * gtk_application_quit:
492  * @app: a #GtkApplication
493  *
494  * Request the application exit.  This function invokes
495  * g_application_quit_with_data(), which normally will
496  * in turn cause @app to emit #GtkApplication::quit.
497  *
498  * To control an application's quit behavior (for example, to ask for
499  * files to be saved), connect to the #GtkApplication::quit signal
500  * handler.
501  *
502  * Since: 3.0
503  */
504 void
505 gtk_application_quit (GtkApplication *app)
506 {
507   GVariantBuilder builder;
508   GVariant *platform_data;
509
510   g_variant_builder_init (&builder, G_VARIANT_TYPE ("a{sv}"));
511   g_variant_builder_add (&builder, "{sv}",
512                          "timestamp",
513                          g_variant_new ("u",
514                                         gtk_get_current_event_time ()));
515   platform_data = g_variant_builder_end (&builder);
516     
517   g_application_quit_with_data (G_APPLICATION (app), platform_data);
518
519   g_variant_unref (platform_data);
520 }
521
522 static void
523 gtk_application_get_property (GObject    *object,
524                               guint       prop_id,
525                               GValue     *value,
526                               GParamSpec *pspec)
527 {
528   GtkApplication *app = GTK_APPLICATION (object);
529
530   switch (prop_id)
531     {
532       case PROP_WINDOW:
533         g_value_set_object (value, gtk_application_get_window (app));
534         break;
535       default:
536         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
537     }
538 }
539
540 static void
541 gtk_application_set_property (GObject      *object,
542                               guint         prop_id,
543                               const GValue *value,
544                               GParamSpec   *pspec)
545 {
546   GtkApplication *app = GTK_APPLICATION (object);
547
548   g_assert (app != NULL);
549
550   switch (prop_id)
551     {
552       default:
553         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
554     }
555 }
556
557 static void
558 setup_default_window_decorations (void)
559 {
560   const gchar *pid;
561   const gchar *filename;
562   GKeyFile *keyfile;
563   gchar *title;
564   gchar *icon_name;
565
566   pid = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE_PID");
567   filename = g_getenv ("GIO_LAUNCHED_DESKTOP_FILE");
568
569   keyfile = g_key_file_new ();
570
571   if (pid != NULL && filename != NULL && atoi (pid) == getpid () &&
572       g_key_file_load_from_file (keyfile, filename, 0, NULL))
573     {
574       title = g_key_file_get_locale_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_NAME, NULL, NULL);
575       icon_name = g_key_file_get_string (keyfile, G_KEY_FILE_DESKTOP_GROUP, G_KEY_FILE_DESKTOP_KEY_ICON, NULL);
576
577       if (default_title == NULL)
578         default_title = title;
579
580       if (gtk_window_get_default_icon_name () == NULL)
581         gtk_window_set_default_icon_name (icon_name);
582
583       g_free (icon_name);
584     }
585
586   g_key_file_free (keyfile);
587 }
588
589 static void
590 gtk_application_init (GtkApplication *application)
591 {
592   application->priv = G_TYPE_INSTANCE_GET_PRIVATE (application, GTK_TYPE_APPLICATION, GtkApplicationPrivate);
593
594   g_object_set (application, "platform-data", gtk_application_format_activation_data (), NULL);
595
596   setup_default_window_decorations ();
597 }
598
599
600 static GObject*
601 gtk_application_constructor (GType                  type,
602                              guint                  n_construct_properties,
603                              GObjectConstructParam *construct_params)
604 {
605   GObject *object;
606
607   /* Last ditch effort here */
608   gtk_init (0, NULL);
609
610   object = (* G_OBJECT_CLASS (gtk_application_parent_class)->constructor) (type,
611                                                                            n_construct_properties,
612                                                                            construct_params);
613
614   return object;
615 }
616
617 static void
618 gtk_application_class_init (GtkApplicationClass *klass)
619 {
620   GObjectClass *gobject_class;
621   GApplicationClass *application_class;
622
623   gobject_class = G_OBJECT_CLASS (klass);
624   application_class = G_APPLICATION_CLASS (klass);
625
626   gobject_class->constructor = gtk_application_constructor;
627   gobject_class->get_property = gtk_application_get_property;
628   gobject_class->set_property = gtk_application_set_property;
629
630   application_class->run = gtk_application_default_run;
631   application_class->quit_with_data = gtk_application_default_quit_with_data;
632   application_class->action_with_data = gtk_application_default_action_with_data;
633   application_class->prepare_activation = gtk_application_default_prepare_activation;
634
635   klass->quit = gtk_application_default_quit;
636   klass->action = gtk_application_default_action;
637   klass->create_window = gtk_application_default_create_window;
638
639   klass->activated = gtk_application_default_activated;
640
641   /**
642    * GtkApplication::activated:
643    * @arguments: A #GVariant with the signature "aay"
644    *
645    * This signal is emitted when a non-primary process for a given
646    * application is invoked while your application is running; for
647    * example, when a file browser launches your program to open a
648    * file.  The raw operating system arguments are passed in the
649    * variant @arguments.
650    */
651
652   gtk_application_signals[ACTIVATED] =
653     g_signal_new (g_intern_static_string ("activated"),
654                   G_OBJECT_CLASS_TYPE (klass),
655                   G_SIGNAL_RUN_LAST,
656                   G_STRUCT_OFFSET (GtkApplicationClass, activated),
657                   NULL, NULL,
658                   g_cclosure_marshal_VOID__BOXED,
659                   G_TYPE_NONE, 1,
660                   G_TYPE_VARIANT);
661
662   /**
663    * GtkApplication::quit:
664    * @application: the object on which the signal is emitted
665    *
666    * This signal is emitted when a quit is initiated.  See also
667    * the #GApplication::quit-with-data signal which may in
668    * turn trigger this signal.
669    *
670    * The default handler for this signal exits the mainloop of the
671    * application.
672    *
673    * Returns: %TRUE if the signal has been handled, %FALSE to continue
674    *   signal emission
675    */
676   gtk_application_signals[QUIT] =
677     g_signal_new (g_intern_static_string ("quit"),
678                   G_OBJECT_CLASS_TYPE (klass),
679                   G_SIGNAL_RUN_LAST,
680                   G_STRUCT_OFFSET (GtkApplicationClass, quit),
681                   g_signal_accumulator_true_handled, NULL,
682                   _gtk_marshal_BOOLEAN__VOID,
683                   G_TYPE_BOOLEAN, 0);
684
685   /**
686    * GtkApplication::action:
687    * @application: the object on which the signal is emitted
688    * @name: The name of the activated action
689    *
690    * This signal is emitted when an action is activated. The action name
691    * is passed as the first argument, but also as signal detail, so it
692    * is possible to connect to this signal for individual actions.
693    *
694    * See also the #GApplication::action-with-data signal which may in
695    * turn trigger this signal.
696    *
697    * The signal is never emitted for disabled actions.
698    */
699   gtk_application_signals[ACTION] =
700     g_signal_new (g_intern_static_string ("action"),
701                   G_OBJECT_CLASS_TYPE (klass),
702                   G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED,
703                   G_STRUCT_OFFSET (GtkApplicationClass, action),
704                   NULL, NULL,
705                   g_cclosure_marshal_VOID__STRING,
706                   G_TYPE_NONE, 1,
707                   G_TYPE_STRING);
708                  
709   g_type_class_add_private (gobject_class, sizeof (GtkApplicationPrivate));
710 }
711
712 #define __GTK_APPLICATION_C__
713 #include "gtkaliasdef.c"