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