Updated FSF's address
[platform/upstream/glib.git] / gio / gaction.c
1 /*
2  * Copyright © 2010 Codethink Limited
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU Lesser General Public License as published
6  * by the Free Software Foundation; either version 2 of the licence or (at
7  * 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
15  * Public License along with this library; if not, see <http://www.gnu.org/licenses/>.
16  *
17  * Authors: Ryan Lortie <desrt@desrt.ca>
18  */
19
20 #include "config.h"
21 #include "gaction.h"
22 #include "glibintl.h"
23
24 #include <string.h>
25
26 G_DEFINE_INTERFACE (GAction, g_action, G_TYPE_OBJECT)
27
28 /**
29  * SECTION:gaction
30  * @title: GAction
31  * @short_description: An action interface
32  * @include: gio/gio.h
33  *
34  * #GAction represents a single named action.
35  *
36  * The main interface to an action is that it can be activated with
37  * g_action_activate().  This results in the 'activate' signal being
38  * emitted.  An activation has a #GVariant parameter (which may be
39  * %NULL).  The correct type for the parameter is determined by a static
40  * parameter type (which is given at construction time).
41  *
42  * An action may optionally have a state, in which case the state may be
43  * set with g_action_change_state().  This call takes a #GVariant.  The
44  * correct type for the state is determined by a static state type
45  * (which is given at construction time).
46  *
47  * The state may have a hint associated with it, specifying its valid
48  * range.
49  *
50  * #GAction is merely the interface to the concept of an action, as
51  * described above.  Various implementations of actions exist, including
52  * #GSimpleAction.
53  *
54  * In all cases, the implementing class is responsible for storing the
55  * name of the action, the parameter type, the enabled state, the
56  * optional state type and the state and emitting the appropriate
57  * signals when these change.  The implementor responsible for filtering
58  * calls to g_action_activate() and g_action_change_state() for type
59  * safety and for the state being enabled.
60  *
61  * Probably the only useful thing to do with a #GAction is to put it
62  * inside of a #GSimpleActionGroup.
63  **/
64
65 /**
66  * GActionInterface:
67  * @get_name: the virtual function pointer for g_action_get_name()
68  * @get_parameter_type: the virtual function pointer for g_action_get_parameter_type()
69  * @get_state_type: the virtual function pointer for g_action_get_state_type()
70  * @get_state_hint: the virtual function pointer for g_action_get_state_hint()
71  * @get_enabled: the virtual function pointer for g_action_get_enabled()
72  * @get_state: the virtual function pointer for g_action_get_state()
73  * @change_state: the virtual function pointer for g_action_change_state()
74  * @activate: the virtual function pointer for g_action_activate().  Note that #GAction does not have an
75  *            'activate' signal but that implementations of it may have one.
76  *
77  * The virtual function table for #GAction.
78  *
79  * Since: 2.28
80  */
81
82 void
83 g_action_default_init (GActionInterface *iface)
84 {
85   /**
86    * GAction:name:
87    *
88    * The name of the action.  This is mostly meaningful for identifying
89    * the action once it has been added to a #GActionGroup.
90    *
91    * Since: 2.28
92    **/
93   g_object_interface_install_property (iface,
94                                        g_param_spec_string ("name",
95                                                             P_("Action Name"),
96                                                             P_("The name used to invoke the action"),
97                                                             NULL,
98                                                             G_PARAM_READABLE |
99                                                             G_PARAM_STATIC_STRINGS));
100
101   /**
102    * GAction:parameter-type:
103    *
104    * The type of the parameter that must be given when activating the
105    * action.
106    *
107    * Since: 2.28
108    **/
109   g_object_interface_install_property (iface,
110                                        g_param_spec_boxed ("parameter-type",
111                                                            P_("Parameter Type"),
112                                                            P_("The type of GVariant passed to activate()"),
113                                                            G_TYPE_VARIANT_TYPE,
114                                                            G_PARAM_READABLE |
115                                                            G_PARAM_STATIC_STRINGS));
116
117   /**
118    * GAction:enabled:
119    *
120    * If @action is currently enabled.
121    *
122    * If the action is disabled then calls to g_action_activate() and
123    * g_action_change_state() have no effect.
124    *
125    * Since: 2.28
126    **/
127   g_object_interface_install_property (iface,
128                                        g_param_spec_boolean ("enabled",
129                                                              P_("Enabled"),
130                                                              P_("If the action can be activated"),
131                                                              TRUE,
132                                                              G_PARAM_READABLE |
133                                                              G_PARAM_STATIC_STRINGS));
134
135   /**
136    * GAction:state-type:
137    *
138    * The #GVariantType of the state that the action has, or %NULL if the
139    * action is stateless.
140    *
141    * Since: 2.28
142    **/
143   g_object_interface_install_property (iface,
144                                        g_param_spec_boxed ("state-type",
145                                                            P_("State Type"),
146                                                            P_("The type of the state kept by the action"),
147                                                            G_TYPE_VARIANT_TYPE,
148                                                            G_PARAM_READABLE |
149                                                            G_PARAM_STATIC_STRINGS));
150
151   /**
152    * GAction:state:
153    *
154    * The state of the action, or %NULL if the action is stateless.
155    *
156    * Since: 2.28
157    **/
158   g_object_interface_install_property (iface,
159                                        g_param_spec_variant ("state",
160                                                              P_("State"),
161                                                              P_("The state the action is in"),
162                                                              G_VARIANT_TYPE_ANY,
163                                                              NULL,
164                                                              G_PARAM_READABLE |
165                                                              G_PARAM_STATIC_STRINGS));
166 }
167
168 /**
169  * g_action_change_state:
170  * @action: a #GAction
171  * @value: the new state
172  *
173  * Request for the state of @action to be changed to @value.
174  *
175  * The action must be stateful and @value must be of the correct type.
176  * See g_action_get_state_type().
177  *
178  * This call merely requests a change.  The action may refuse to change
179  * its state or may change its state to something other than @value.
180  * See g_action_get_state_hint().
181  *
182  * If the @value GVariant is floating, it is consumed.
183  *
184  * Since: 2.30
185  **/
186 void
187 g_action_change_state (GAction  *action,
188                        GVariant *value)
189 {
190   const GVariantType *state_type;
191
192   g_return_if_fail (G_IS_ACTION (action));
193   g_return_if_fail (value != NULL);
194   state_type = g_action_get_state_type (action);
195   g_return_if_fail (state_type != NULL);
196   g_return_if_fail (g_variant_is_of_type (value, state_type));
197
198   g_variant_ref_sink (value);
199
200   G_ACTION_GET_IFACE (action)
201     ->change_state (action, value);
202
203   g_variant_unref (value);
204 }
205
206 /**
207  * g_action_get_state:
208  * @action: a #GAction
209  *
210  * Queries the current state of @action.
211  *
212  * If the action is not stateful then %NULL will be returned.  If the
213  * action is stateful then the type of the return value is the type
214  * given by g_action_get_state_type().
215  *
216  * The return value (if non-%NULL) should be freed with
217  * g_variant_unref() when it is no longer required.
218  *
219  * Returns: (transfer full): the current state of the action
220  *
221  * Since: 2.28
222  **/
223 GVariant *
224 g_action_get_state (GAction *action)
225 {
226   g_return_val_if_fail (G_IS_ACTION (action), NULL);
227
228   return G_ACTION_GET_IFACE (action)
229     ->get_state (action);
230 }
231
232 /**
233  * g_action_get_name:
234  * @action: a #GAction
235  *
236  * Queries the name of @action.
237  *
238  * Returns: the name of the action
239  *
240  * Since: 2.28
241  **/
242 const gchar *
243 g_action_get_name (GAction *action)
244 {
245   g_return_val_if_fail (G_IS_ACTION (action), NULL);
246
247   return G_ACTION_GET_IFACE (action)
248     ->get_name (action);
249 }
250
251 /**
252  * g_action_get_parameter_type:
253  * @action: a #GAction
254  *
255  * Queries the type of the parameter that must be given when activating
256  * @action.
257  *
258  * When activating the action using g_action_activate(), the #GVariant
259  * given to that function must be of the type returned by this function.
260  *
261  * In the case that this function returns %NULL, you must not give any
262  * #GVariant, but %NULL instead.
263  *
264  * Returns: (allow-none): the parameter type
265  *
266  * Since: 2.28
267  **/
268 const GVariantType *
269 g_action_get_parameter_type (GAction *action)
270 {
271   g_return_val_if_fail (G_IS_ACTION (action), NULL);
272
273   return G_ACTION_GET_IFACE (action)
274     ->get_parameter_type (action);
275 }
276
277 /**
278  * g_action_get_state_type:
279  * @action: a #GAction
280  *
281  * Queries the type of the state of @action.
282  *
283  * If the action is stateful (e.g. created with
284  * g_simple_action_new_stateful()) then this function returns the
285  * #GVariantType of the state.  This is the type of the initial value
286  * given as the state. All calls to g_action_change_state() must give a
287  * #GVariant of this type and g_action_get_state() will return a
288  * #GVariant of the same type.
289  *
290  * If the action is not stateful (e.g. created with g_simple_action_new())
291  * then this function will return %NULL. In that case, g_action_get_state()
292  * will return %NULL and you must not call g_action_change_state().
293  *
294  * Returns: (allow-none): the state type, if the action is stateful
295  *
296  * Since: 2.28
297  **/
298 const GVariantType *
299 g_action_get_state_type (GAction *action)
300 {
301   g_return_val_if_fail (G_IS_ACTION (action), NULL);
302
303   return G_ACTION_GET_IFACE (action)
304     ->get_state_type (action);
305 }
306
307 /**
308  * g_action_get_state_hint:
309  * @action: a #GAction
310  *
311  * Requests a hint about the valid range of values for the state of
312  * @action.
313  *
314  * If %NULL is returned it either means that the action is not stateful
315  * or that there is no hint about the valid range of values for the
316  * state of the action.
317  *
318  * If a #GVariant array is returned then each item in the array is a
319  * possible value for the state.  If a #GVariant pair (ie: two-tuple) is
320  * returned then the tuple specifies the inclusive lower and upper bound
321  * of valid values for the state.
322  *
323  * In any case, the information is merely a hint.  It may be possible to
324  * have a state value outside of the hinted range and setting a value
325  * within the range may fail.
326  *
327  * The return value (if non-%NULL) should be freed with
328  * g_variant_unref() when it is no longer required.
329  *
330  * Returns: (transfer full): the state range hint
331  *
332  * Since: 2.28
333  **/
334 GVariant *
335 g_action_get_state_hint (GAction *action)
336 {
337   g_return_val_if_fail (G_IS_ACTION (action), NULL);
338
339   return G_ACTION_GET_IFACE (action)
340     ->get_state_hint (action);
341 }
342
343 /**
344  * g_action_get_enabled:
345  * @action: a #GAction
346  *
347  * Checks if @action is currently enabled.
348  *
349  * An action must be enabled in order to be activated or in order to
350  * have its state changed from outside callers.
351  *
352  * Returns: whether the action is enabled
353  *
354  * Since: 2.28
355  **/
356 gboolean
357 g_action_get_enabled (GAction *action)
358 {
359   g_return_val_if_fail (G_IS_ACTION (action), FALSE);
360
361   return G_ACTION_GET_IFACE (action)
362     ->get_enabled (action);
363 }
364
365 /**
366  * g_action_activate:
367  * @action: a #GAction
368  * @parameter: (allow-none): the parameter to the activation
369  *
370  * Activates the action.
371  *
372  * @parameter must be the correct type of parameter for the action (ie:
373  * the parameter type given at construction time).  If the parameter
374  * type was %NULL then @parameter must also be %NULL.
375  *
376  * If the @parameter GVariant is floating, it is consumed.
377  *
378  * Since: 2.28
379  **/
380 void
381 g_action_activate (GAction  *action,
382                    GVariant *parameter)
383 {
384   g_return_if_fail (G_IS_ACTION (action));
385
386   if (parameter != NULL)
387     g_variant_ref_sink (parameter);
388
389   G_ACTION_GET_IFACE (action)
390     ->activate (action, parameter);
391
392   if (parameter != NULL)
393     g_variant_unref (parameter);
394 }
395
396 /**
397  * g_action_name_is_valid:
398  * @action_name: an potential action name
399  *
400  * Checks if @action_name is valid.
401  *
402  * @action_name is valid if it consists only of alphanumeric characters,
403  * plus '-' and '.'.  The empty string is not a valid action name.
404  *
405  * It is an error to call this function with a non-utf8 @action_name.
406  * @action_name must not be %NULL.
407  *
408  * Returns: %TRUE if @action_name is valid
409  *
410  * Since: 2.38
411  **/
412 gboolean
413 g_action_name_is_valid (const gchar *action_name)
414 {
415   gchar c;
416   gint i;
417
418   g_return_val_if_fail (action_name != NULL, FALSE);
419
420   for (i = 0; (c = action_name[i]); i++)
421     if (!g_ascii_isalnum (c) && c != '.' && c != '-')
422       return FALSE;
423
424   return i > 0;
425 }
426
427 /**
428  * g_action_parse_detailed_name:
429  * @detailed_name: a detailed action name
430  * @action_name: (out): the action name
431  * @target_value: (out): the target value, or %NULL for no target
432  * @error: a pointer to a %NULL #GError, or %NULL
433  *
434  * Parses a detailed action name into its separate name and target
435  * components.
436  *
437  * Detailed action names can have three formats.
438  *
439  * The first format is used to represent an action name with no target
440  * value and consists of just an action name containing no whitespace
441  * nor the characters ':', '(' or ')'.  For example: "app.action".
442  *
443  * The second format is used to represent an action with a target value
444  * that is a non-empty string consisting only of alphanumerics, plus '-'
445  * and '.'.  In that case, the action name and target value are
446  * separated by a double colon ("::").  For example:
447  * "app.action::target".
448  *
449  * The third format is used to represent an action with any type of
450  * target value, including strings.  The target value follows the action
451  * name, surrounded in parens.  For example: "app.action(42)".  The
452  * target value is parsed using g_variant_parse().  If a tuple-typed
453  * value is desired, it must be specified in the same way, resulting in
454  * two sets of parens, for example: "app.action((1,2,3))".  A string
455  * target can be specified this way as well: "app.action('target')".
456  * For strings, this third format must be used if * target value is
457  * empty or contains characters other than alphanumerics, '-' and '.'.
458  *
459  * Returns: %TRUE if successful, else %FALSE with @error set
460  *
461  * Since: 2.38
462  **/
463 gboolean
464 g_action_parse_detailed_name (const gchar  *detailed_name,
465                               gchar       **action_name,
466                               GVariant    **target_value,
467                               GError      **error)
468 {
469   const gchar *target;
470   gsize target_len;
471   gsize base_len;
472
473   /* For historical (compatibility) reasons, this function accepts some
474    * cases of invalid action names as long as they don't interfere with
475    * the separation of the action from the target value.
476    *
477    * We decide which format we have based on which we see first between
478    * '::' '(' and '\0'.
479    */
480
481   if (*detailed_name == '\0' || *detailed_name == ' ')
482     goto bad_fmt;
483
484   base_len = strcspn (detailed_name, ": ()");
485   target = detailed_name + base_len;
486   target_len = strlen (target);
487
488   switch (target[0])
489     {
490     case ' ':
491     case ')':
492       goto bad_fmt;
493
494     case ':':
495       if (target[1] != ':')
496         goto bad_fmt;
497
498       *target_value = g_variant_ref_sink (g_variant_new_string (target + 2));
499       break;
500
501     case '(':
502       {
503         if (target[target_len - 1] != ')')
504           goto bad_fmt;
505
506         *target_value = g_variant_parse (NULL, target + 1, target + target_len - 1, NULL, error);
507         if (*target_value == NULL)
508           goto bad_fmt;
509       }
510       break;
511
512     case '\0':
513       *target_value = NULL;
514       break;
515     }
516
517   *action_name = g_strndup (detailed_name, base_len);
518
519   return TRUE;
520
521 bad_fmt:
522   if (error)
523     {
524       if (*error == NULL)
525         g_set_error (error, G_VARIANT_PARSE_ERROR, G_VARIANT_PARSE_ERROR_FAILED,
526                      "Detailed action name '%s' has invalid format", detailed_name);
527       else
528         g_prefix_error (error, "Detailed action name '%s' has invalid format: ", detailed_name);
529     }
530
531   return FALSE;
532 }
533
534 /**
535  * g_action_print_detailed_name:
536  * @action_name: a valid action name
537  * @target_value: (allow-none): a #GVariant target value, or %NULL
538  *
539  * Formats a detailed action name from @action_name and @target_value.
540  *
541  * It is an error to call this function with an invalid action name.
542  *
543  * This function is the opposite of
544  * g_action_parse_detailed_action_name().  It will produce a string that
545  * can be parsed back to the @action_name and @target_value by that
546  * function.
547  *
548  * See that function for the types of strings that will be printed by
549  * this function.
550  *
551  * Returns: a detailed format string
552  *
553  * Since: 2.38
554  **/
555 gchar *
556 g_action_print_detailed_name (const gchar *action_name,
557                               GVariant    *target_value)
558 {
559   g_return_val_if_fail (g_action_name_is_valid (action_name), NULL);
560
561   if (target_value == NULL)
562     return g_strdup (action_name);
563
564   if (g_variant_is_of_type (target_value, G_VARIANT_TYPE_STRING))
565     {
566       const gchar *str = g_variant_get_string (target_value, NULL);
567
568       if (g_action_name_is_valid (str))
569         return g_strconcat (action_name, "::", str, NULL);
570     }
571
572   {
573     GString *result = g_string_new (action_name);
574     g_string_append_c (result, '(');
575     g_variant_print_string (target_value, result, TRUE);
576     g_string_append_c (result, ')');
577
578     return g_string_free (result, FALSE);
579   }
580 }