hook gvariant vectors up to kdbus
[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. It is immutable.
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. This is immutable, and may be %NULL if no parameter is needed when
106    * activating the action.
107    *
108    * Since: 2.28
109    **/
110   g_object_interface_install_property (iface,
111                                        g_param_spec_boxed ("parameter-type",
112                                                            P_("Parameter Type"),
113                                                            P_("The type of GVariant passed to activate()"),
114                                                            G_TYPE_VARIANT_TYPE,
115                                                            G_PARAM_READABLE |
116                                                            G_PARAM_STATIC_STRINGS));
117
118   /**
119    * GAction:enabled:
120    *
121    * If @action is currently enabled.
122    *
123    * If the action is disabled then calls to g_action_activate() and
124    * g_action_change_state() have no effect.
125    *
126    * Since: 2.28
127    **/
128   g_object_interface_install_property (iface,
129                                        g_param_spec_boolean ("enabled",
130                                                              P_("Enabled"),
131                                                              P_("If the action can be activated"),
132                                                              TRUE,
133                                                              G_PARAM_READABLE |
134                                                              G_PARAM_STATIC_STRINGS));
135
136   /**
137    * GAction:state-type:
138    *
139    * The #GVariantType of the state that the action has, or %NULL if the
140    * action is stateless. This is immutable.
141    *
142    * Since: 2.28
143    **/
144   g_object_interface_install_property (iface,
145                                        g_param_spec_boxed ("state-type",
146                                                            P_("State Type"),
147                                                            P_("The type of the state kept by the action"),
148                                                            G_TYPE_VARIANT_TYPE,
149                                                            G_PARAM_READABLE |
150                                                            G_PARAM_STATIC_STRINGS));
151
152   /**
153    * GAction:state:
154    *
155    * The state of the action, or %NULL if the action is stateless.
156    *
157    * Since: 2.28
158    **/
159   g_object_interface_install_property (iface,
160                                        g_param_spec_variant ("state",
161                                                              P_("State"),
162                                                              P_("The state the action is in"),
163                                                              G_VARIANT_TYPE_ANY,
164                                                              NULL,
165                                                              G_PARAM_READABLE |
166                                                              G_PARAM_STATIC_STRINGS));
167 }
168
169 /**
170  * g_action_change_state:
171  * @action: a #GAction
172  * @value: the new state
173  *
174  * Request for the state of @action to be changed to @value.
175  *
176  * The action must be stateful and @value must be of the correct type.
177  * See g_action_get_state_type().
178  *
179  * This call merely requests a change.  The action may refuse to change
180  * its state or may change its state to something other than @value.
181  * See g_action_get_state_hint().
182  *
183  * If the @value GVariant is floating, it is consumed.
184  *
185  * Since: 2.30
186  **/
187 void
188 g_action_change_state (GAction  *action,
189                        GVariant *value)
190 {
191   const GVariantType *state_type;
192
193   g_return_if_fail (G_IS_ACTION (action));
194   g_return_if_fail (value != NULL);
195   state_type = g_action_get_state_type (action);
196   g_return_if_fail (state_type != NULL);
197   g_return_if_fail (g_variant_is_of_type (value, state_type));
198
199   g_variant_ref_sink (value);
200
201   G_ACTION_GET_IFACE (action)
202     ->change_state (action, value);
203
204   g_variant_unref (value);
205 }
206
207 /**
208  * g_action_get_state:
209  * @action: a #GAction
210  *
211  * Queries the current state of @action.
212  *
213  * If the action is not stateful then %NULL will be returned.  If the
214  * action is stateful then the type of the return value is the type
215  * given by g_action_get_state_type().
216  *
217  * The return value (if non-%NULL) should be freed with
218  * g_variant_unref() when it is no longer required.
219  *
220  * Returns: (transfer full): the current state of the action
221  *
222  * Since: 2.28
223  **/
224 GVariant *
225 g_action_get_state (GAction *action)
226 {
227   g_return_val_if_fail (G_IS_ACTION (action), NULL);
228
229   return G_ACTION_GET_IFACE (action)
230     ->get_state (action);
231 }
232
233 /**
234  * g_action_get_name:
235  * @action: a #GAction
236  *
237  * Queries the name of @action.
238  *
239  * Returns: the name of the action
240  *
241  * Since: 2.28
242  **/
243 const gchar *
244 g_action_get_name (GAction *action)
245 {
246   g_return_val_if_fail (G_IS_ACTION (action), NULL);
247
248   return G_ACTION_GET_IFACE (action)
249     ->get_name (action);
250 }
251
252 /**
253  * g_action_get_parameter_type:
254  * @action: a #GAction
255  *
256  * Queries the type of the parameter that must be given when activating
257  * @action.
258  *
259  * When activating the action using g_action_activate(), the #GVariant
260  * given to that function must be of the type returned by this function.
261  *
262  * In the case that this function returns %NULL, you must not give any
263  * #GVariant, but %NULL instead.
264  *
265  * Returns: (allow-none): the parameter type
266  *
267  * Since: 2.28
268  **/
269 const GVariantType *
270 g_action_get_parameter_type (GAction *action)
271 {
272   g_return_val_if_fail (G_IS_ACTION (action), NULL);
273
274   return G_ACTION_GET_IFACE (action)
275     ->get_parameter_type (action);
276 }
277
278 /**
279  * g_action_get_state_type:
280  * @action: a #GAction
281  *
282  * Queries the type of the state of @action.
283  *
284  * If the action is stateful (e.g. created with
285  * g_simple_action_new_stateful()) then this function returns the
286  * #GVariantType of the state.  This is the type of the initial value
287  * given as the state. All calls to g_action_change_state() must give a
288  * #GVariant of this type and g_action_get_state() will return a
289  * #GVariant of the same type.
290  *
291  * If the action is not stateful (e.g. created with g_simple_action_new())
292  * then this function will return %NULL. In that case, g_action_get_state()
293  * will return %NULL and you must not call g_action_change_state().
294  *
295  * Returns: (allow-none): the state type, if the action is stateful
296  *
297  * Since: 2.28
298  **/
299 const GVariantType *
300 g_action_get_state_type (GAction *action)
301 {
302   g_return_val_if_fail (G_IS_ACTION (action), NULL);
303
304   return G_ACTION_GET_IFACE (action)
305     ->get_state_type (action);
306 }
307
308 /**
309  * g_action_get_state_hint:
310  * @action: a #GAction
311  *
312  * Requests a hint about the valid range of values for the state of
313  * @action.
314  *
315  * If %NULL is returned it either means that the action is not stateful
316  * or that there is no hint about the valid range of values for the
317  * state of the action.
318  *
319  * If a #GVariant array is returned then each item in the array is a
320  * possible value for the state.  If a #GVariant pair (ie: two-tuple) is
321  * returned then the tuple specifies the inclusive lower and upper bound
322  * of valid values for the state.
323  *
324  * In any case, the information is merely a hint.  It may be possible to
325  * have a state value outside of the hinted range and setting a value
326  * within the range may fail.
327  *
328  * The return value (if non-%NULL) should be freed with
329  * g_variant_unref() when it is no longer required.
330  *
331  * Returns: (nullable) (transfer full): the state range hint
332  *
333  * Since: 2.28
334  **/
335 GVariant *
336 g_action_get_state_hint (GAction *action)
337 {
338   g_return_val_if_fail (G_IS_ACTION (action), NULL);
339
340   return G_ACTION_GET_IFACE (action)
341     ->get_state_hint (action);
342 }
343
344 /**
345  * g_action_get_enabled:
346  * @action: a #GAction
347  *
348  * Checks if @action is currently enabled.
349  *
350  * An action must be enabled in order to be activated or in order to
351  * have its state changed from outside callers.
352  *
353  * Returns: whether the action is enabled
354  *
355  * Since: 2.28
356  **/
357 gboolean
358 g_action_get_enabled (GAction *action)
359 {
360   g_return_val_if_fail (G_IS_ACTION (action), FALSE);
361
362   return G_ACTION_GET_IFACE (action)
363     ->get_enabled (action);
364 }
365
366 /**
367  * g_action_activate:
368  * @action: a #GAction
369  * @parameter: (allow-none): the parameter to the activation
370  *
371  * Activates the action.
372  *
373  * @parameter must be the correct type of parameter for the action (ie:
374  * the parameter type given at construction time).  If the parameter
375  * type was %NULL then @parameter must also be %NULL.
376  *
377  * If the @parameter GVariant is floating, it is consumed.
378  *
379  * Since: 2.28
380  **/
381 void
382 g_action_activate (GAction  *action,
383                    GVariant *parameter)
384 {
385   g_return_if_fail (G_IS_ACTION (action));
386
387   if (parameter != NULL)
388     g_variant_ref_sink (parameter);
389
390   G_ACTION_GET_IFACE (action)
391     ->activate (action, parameter);
392
393   if (parameter != NULL)
394     g_variant_unref (parameter);
395 }
396
397 /**
398  * g_action_name_is_valid:
399  * @action_name: an potential action name
400  *
401  * Checks if @action_name is valid.
402  *
403  * @action_name is valid if it consists only of alphanumeric characters,
404  * plus '-' and '.'.  The empty string is not a valid action name.
405  *
406  * It is an error to call this function with a non-utf8 @action_name.
407  * @action_name must not be %NULL.
408  *
409  * Returns: %TRUE if @action_name is valid
410  *
411  * Since: 2.38
412  **/
413 gboolean
414 g_action_name_is_valid (const gchar *action_name)
415 {
416   gchar c;
417   gint i;
418
419   g_return_val_if_fail (action_name != NULL, FALSE);
420
421   for (i = 0; (c = action_name[i]); i++)
422     if (!g_ascii_isalnum (c) && c != '.' && c != '-')
423       return FALSE;
424
425   return i > 0;
426 }
427
428 /**
429  * g_action_parse_detailed_name:
430  * @detailed_name: a detailed action name
431  * @action_name: (out): the action name
432  * @target_value: (out): the target value, or %NULL for no target
433  * @error: a pointer to a %NULL #GError, or %NULL
434  *
435  * Parses a detailed action name into its separate name and target
436  * components.
437  *
438  * Detailed action names can have three formats.
439  *
440  * The first format is used to represent an action name with no target
441  * value and consists of just an action name containing no whitespace
442  * nor the characters ':', '(' or ')'.  For example: "app.action".
443  *
444  * The second format is used to represent an action with a target value
445  * that is a non-empty string consisting only of alphanumerics, plus '-'
446  * and '.'.  In that case, the action name and target value are
447  * separated by a double colon ("::").  For example:
448  * "app.action::target".
449  *
450  * The third format is used to represent an action with any type of
451  * target value, including strings.  The target value follows the action
452  * name, surrounded in parens.  For example: "app.action(42)".  The
453  * target value is parsed using g_variant_parse().  If a tuple-typed
454  * value is desired, it must be specified in the same way, resulting in
455  * two sets of parens, for example: "app.action((1,2,3))".  A string
456  * target can be specified this way as well: "app.action('target')".
457  * For strings, this third format must be used if * target value is
458  * empty or contains characters other than alphanumerics, '-' and '.'.
459  *
460  * Returns: %TRUE if successful, else %FALSE with @error set
461  *
462  * Since: 2.38
463  **/
464 gboolean
465 g_action_parse_detailed_name (const gchar  *detailed_name,
466                               gchar       **action_name,
467                               GVariant    **target_value,
468                               GError      **error)
469 {
470   const gchar *target;
471   gsize target_len;
472   gsize base_len;
473
474   /* For historical (compatibility) reasons, this function accepts some
475    * cases of invalid action names as long as they don't interfere with
476    * the separation of the action from the target value.
477    *
478    * We decide which format we have based on which we see first between
479    * '::' '(' and '\0'.
480    */
481
482   if (*detailed_name == '\0' || *detailed_name == ' ')
483     goto bad_fmt;
484
485   base_len = strcspn (detailed_name, ": ()");
486   target = detailed_name + base_len;
487   target_len = strlen (target);
488
489   switch (target[0])
490     {
491     case ' ':
492     case ')':
493       goto bad_fmt;
494
495     case ':':
496       if (target[1] != ':')
497         goto bad_fmt;
498
499       *target_value = g_variant_ref_sink (g_variant_new_string (target + 2));
500       break;
501
502     case '(':
503       {
504         if (target[target_len - 1] != ')')
505           goto bad_fmt;
506
507         *target_value = g_variant_parse (NULL, target + 1, target + target_len - 1, NULL, error);
508         if (*target_value == NULL)
509           goto bad_fmt;
510       }
511       break;
512
513     case '\0':
514       *target_value = NULL;
515       break;
516     }
517
518   *action_name = g_strndup (detailed_name, base_len);
519
520   return TRUE;
521
522 bad_fmt:
523   if (error)
524     {
525       if (*error == NULL)
526         g_set_error (error, G_VARIANT_PARSE_ERROR, G_VARIANT_PARSE_ERROR_FAILED,
527                      "Detailed action name '%s' has invalid format", detailed_name);
528       else
529         g_prefix_error (error, "Detailed action name '%s' has invalid format: ", detailed_name);
530     }
531
532   return FALSE;
533 }
534
535 /**
536  * g_action_print_detailed_name:
537  * @action_name: a valid action name
538  * @target_value: (allow-none): a #GVariant target value, or %NULL
539  *
540  * Formats a detailed action name from @action_name and @target_value.
541  *
542  * It is an error to call this function with an invalid action name.
543  *
544  * This function is the opposite of
545  * g_action_parse_detailed_action_name().  It will produce a string that
546  * can be parsed back to the @action_name and @target_value by that
547  * function.
548  *
549  * See that function for the types of strings that will be printed by
550  * this function.
551  *
552  * Returns: a detailed format string
553  *
554  * Since: 2.38
555  **/
556 gchar *
557 g_action_print_detailed_name (const gchar *action_name,
558                               GVariant    *target_value)
559 {
560   g_return_val_if_fail (g_action_name_is_valid (action_name), NULL);
561
562   if (target_value == NULL)
563     return g_strdup (action_name);
564
565   if (g_variant_is_of_type (target_value, G_VARIANT_TYPE_STRING))
566     {
567       const gchar *str = g_variant_get_string (target_value, NULL);
568
569       if (g_action_name_is_valid (str))
570         return g_strconcat (action_name, "::", str, NULL);
571     }
572
573   {
574     GString *result = g_string_new (action_name);
575     g_string_append_c (result, '(');
576     g_variant_print_string (target_value, result, TRUE);
577     g_string_append_c (result, ')');
578
579     return g_string_free (result, FALSE);
580   }
581 }