adg: fix typo in adg_round docblock
[adg.git] / src / adg / adg-utils.c
blob6eccab9c6a0c9ddc73f9f920bd1299fb4b158a90
1 /* ADG - Automatic Drawing Generation
2 * Copyright (C) 2007-2017 Nicola Fontana <ntd at entidi.it>
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 License, or (at your option) any later version.
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.
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., 51 Franklin Street, Fifth Floor,
17 * Boston, MA 02110-1301, USA.
21 /**
22 * SECTION:adg-utils
23 * @Section_Id:utilities
24 * @title: Utilities
25 * @short_description: Assorted macros and functions
27 * Collection of macros and functions that do not fit inside any other topic.
29 * Since: 1.0
30 **/
32 /**
33 * ADG_DIR_RIGHT:
35 * Symbolic constant for the right direction (in radians).
37 * Since: 1.0
38 **/
40 /**
41 * ADG_DIR_DOWN:
43 * Symbolic constant for the down direction (in radians).
45 * Since: 1.0
46 **/
48 /**
49 * ADG_DIR_LEFT:
51 * Symbolic constant for the left direction (in radians).
53 * Since: 1.0
54 **/
56 /**
57 * ADG_DIR_UP:
59 * Symbolic constant for the up direction (in radians).
61 * Since: 1.0
62 **/
64 /**
65 * ADG_UTF8_DIAMETER:
67 * String constant that embeds a UTF-8 encoded diameter (U+2300).
68 * It can be used to prefix diameter quotes, such as:
70 * <informalexample><programlisting language="C">
71 * adg_dim_set_value(dim, ADG_UTF8_DIAMETER "<>");
72 * </programlisting></informalexample>
74 * Since: 1.0
75 **/
77 /**
78 * ADG_UTF8_DEGREE:
80 * String constant that embeds a UTF-8 encoded degree symbol (U+00B0).
81 * It is used to suffix by the default implementation of #AdgADim to
82 * suffix the set value, but can be also used manually:
84 * <informalexample><programlisting language="C">
85 * adg_dim_set_value(dim, "<>" ADG_UTF8_DEGREE);
86 * </programlisting></informalexample>
88 * Since: 1.0
89 **/
92 #include "adg-internal.h"
93 #include <string.h>
94 #include <limits.h>
95 #include <math.h>
98 #if GLIB_CHECK_VERSION(2, 16, 0)
99 #else
101 * g_strcmp0:
102 * @s1: a C string or <constant>NULL</constant>
103 * @s2: another C string or <constant>NULL</constant>
105 * Compares @s1 and @s2 like strcmp(). Handles
106 * <constant>NULL</constant> gracefully by sorting it
107 * before non-<constant>NULL</constant> strings.
108 * Comparing two <constant>NULL</constant> pointers
109 * returns 0.
111 * This is a backward compatibility fallback for GLib
112 * prior to 2.16.0.
114 * Returns: an integer less than, equal to, or greater than zero, if @s1 is less than, equal to or greater than @s2.
116 * Since: 1.0
119 g_strcmp0(const char *s1, const char *s2)
121 if (!s1)
122 return -(s1 != s2);
124 if (!s2)
125 return s1 != s2;
127 return strcmp(s1, s2);
129 #endif
132 * adg_is_string_empty:
133 * @str: the subject string
135 * Checks if @str is an empty string, that is if is
136 * <constant>NULL</constant> or if its first character
137 * is <constant>'\0'</constant>.
139 * Returns: <constant>TRUE</constant> if @str is an empty string, <constant>FALSE</constant> otherwise.
141 * Since: 1.0
143 gboolean
144 adg_is_string_empty(const gchar *str)
146 return str == NULL || str[0] == '\0';
150 * adg_is_enum_value:
151 * @value: the enum value to check
152 * @enum_type: a #GEnum based type
154 * Checks if @value is a valid @enum_type value.
156 * Returns: <constant>TRUE</constant> if @value is a valid @enum_type, <constant>FALSE</constant> otherwise.
158 * Since: 1.0
160 gboolean
161 adg_is_enum_value(int value, GType enum_type)
163 GEnumClass *enum_class;
164 gboolean found;
166 enum_class = g_type_class_ref(enum_type);
167 g_return_val_if_fail(enum_class != NULL, FALSE);
169 found = FALSE;
171 if (value >= enum_class->minimum && value <= enum_class->maximum) {
172 GEnumValue *enum_value;
173 guint n;
175 for (n = 0; !found && n < enum_class->n_values; ++n) {
176 enum_value = enum_class->values + n;
177 found = value == enum_value->value;
181 g_type_class_unref(enum_class);
183 return found;
187 * adg_is_boolean_value:
188 * @value: the gboolean value to check
190 * Checks if @value is a valid #gboolean value, that is if it is
191 * <constant>TRUE</constant> or <constant>FALSE</constant>.
192 * No other values are accepted.
194 * Returns: <constant>TRUE</constant> if @value is a valid #gboolean, <constant>FALSE</constant> otherwise.
196 * Since: 1.0
198 gboolean
199 adg_is_boolean_value(gboolean value)
201 return value == TRUE || value == FALSE;
205 * adg_string_replace:
206 * @str: the original string
207 * @from: the substring to replace
208 * @to: the replacement string
210 * Replaces @from with @to inside @str and returns the result as a
211 * newly allocated string.
213 * @str and @from must be non-null valid C strings while @to can be
214 * <constant>NULL</constant>, in which case an empty string
215 * (<constant>""</constant>) will be implied.
217 * Returns: a newly allocated string to be freed with g_free() or <constant>NULL</constant> on errors.
219 * Since: 1.0
221 gchar *
222 adg_string_replace(const gchar *str, const gchar *from, const gchar *to)
224 gchar *result;
225 int from_len;
226 gchar *ptr, *old_result;
228 g_return_val_if_fail(str != NULL, NULL);
229 g_return_val_if_fail(from != NULL, NULL);
231 from_len = strlen(from);
233 g_return_val_if_fail(from_len > 0, NULL);
235 if (to == NULL)
236 to = "";
238 result = g_strdup(str);
240 while ((ptr = strstr(result, from)) != NULL) {
241 *ptr = '\0';
242 old_result = result;
243 result = g_strconcat(old_result, to, ptr + from_len, NULL);
244 g_free(old_result);
247 return result;
251 * _adg_dgettext:
252 * @domain: the translation domain to use, or
253 * <constant>NULL</constant> to use the domain set
254 * with <function>textdomain</function>
255 * @msgid: message to translate
257 * A variant of dgettext() (or of g_dgettext(), if available) that
258 * initialize the ADG localization infrastructure.
260 * Returns: The translated string
262 * Since: 1.0
264 const gchar *
265 _adg_dgettext(const gchar *domain, const gchar *msgid)
267 static gboolean initialized = FALSE;
269 if (G_UNLIKELY(!initialized)) {
270 #ifdef G_OS_UNIX
271 bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR);
272 #else
273 /* On windows, LOCALEDIR is relative to the installation path */
274 gchar *path = g_build_filename(g_win32_get_package_installation_directory_of_module(NULL),
275 LOCALEDIR, NULL);
276 bindtextdomain(GETTEXT_PACKAGE, path);
277 g_free(path);
278 #endif
279 bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8");
280 initialized = TRUE;
283 #if GLIB_CHECK_VERSION(2, 18, 0)
284 return g_dgettext(domain, msgid);
285 #else
286 return dgettext(domain, msgid);
287 #endif
291 * _adg_dpgettext:
292 * @domain: the translation domain to use, or
293 * <constant>NULL</constant> to use the domain set with
294 * <function>textdomain</function>
295 * @msgctxtid: a combined message context and message id, separated
296 * by a \004 character
297 * @msgidoffset: the offset of the message id in @msgctxid
299 * This function is basically a duplicate of g_dpgettext() but using
300 * _adg_dgettext() internally instead of g_dgettext().
302 * Returns: The translated string
304 * Since: 1.0
306 const gchar *
307 _adg_dpgettext(const gchar *domain, const gchar *msgctxtid, gsize msgidoffset)
309 const gchar *translation;
310 gchar *sep;
312 translation = _adg_dgettext(domain, msgctxtid);
314 if (translation == msgctxtid) {
315 if (msgidoffset > 0)
316 return msgctxtid + msgidoffset;
318 sep = strchr(msgctxtid, '|');
320 if (sep) {
321 /* try with '\004' instead of '|', in case
322 * xgettext -kQ_:1g was used
324 gchar *tmp = g_alloca(strlen(msgctxtid) + 1);
325 strcpy(tmp, msgctxtid);
326 tmp[sep - msgctxtid] = '\004';
328 translation = _adg_dgettext(domain, tmp);
330 if (translation == tmp)
331 return sep + 1;
335 return translation;
339 * adg_find_file:
340 * @file: the file to search
341 * @...: a NULL terminated list of paths where to look for
342 * file existence.
344 * Searches @file in the provided paths and returns the full
345 * path to the first existing match. The check is performed
346 * using g_file_test() with the G_FILE_TEST_EXISTS test.
348 * The result should be freed with g_free() when no longer needed.
350 * Returns: a newly allocated string containing the path or <constant>NULL</constant> if not found or on errors.
352 * Since: 1.0
354 gchar *
355 adg_find_file(const gchar *file, ...)
357 va_list var_args;
358 gchar *path;
359 const gchar *base;
361 g_return_val_if_fail(file != NULL, NULL);
363 va_start(var_args, file);
365 while ((base = va_arg(var_args, const gchar *)) != NULL) {
366 path = g_build_filename(base, file, NULL);
367 if (g_file_test(path, G_FILE_TEST_EXISTS))
368 return path;
369 g_free(path);
372 return NULL;
376 * adg_scale_factor:
377 * @scale: a string identifying the scale
379 * Converts a scale in the form x:y (where x and y are respectively
380 * two positive integers representing the numerator and denominator
381 * of a fraction) into its approximate double representation. Any
382 * garbage following x or y will be silently ignored, meaning that
383 * x+garbage:y+garbage is equivalent to x:y. Furthermore, the postfix
384 * :y can be omitted, in which case (double) x will be returned.
386 * x and y are converted by using atof(), so refer to your C library
387 * documentation for details on the algorithm used.
389 * Returns: the (possibly approximated) double conversion of @scale or 0 on errors.
391 * Since: 1.0
393 gdouble
394 adg_scale_factor(const gchar *scale)
396 gdouble numerator, denominator;
397 const gchar *ptr;
398 gchar *orig;
400 g_return_val_if_fail(scale != NULL, 0);
402 orig = setlocale(LC_NUMERIC, NULL);
403 setlocale(LC_NUMERIC, "C");
405 numerator = atof(scale);
407 ptr = strchr(scale, ':');
408 denominator = ptr == NULL ? 1 : atof(ptr + 1);
410 setlocale(LC_NUMERIC, orig);
412 if (denominator == 0)
413 return 0;
415 return numerator / denominator;
419 * adg_type_from_filename:
420 * @file: the full path to the file
422 * Gets the surface type from @file. The algorithm simply looks to the
423 * file name extension and tries to guess the correct surface type. If the
424 * guess fails, e.g. the extension does not exist or it is not usual, the
425 * function returns <constant>CAIRO_SURFACE_TYPE_XLIB</constant>. This is
426 * the value conventionally used to signal unrecognized file names.
428 * Returns: (type gint): the surface type of @file
429 * or <constant>CAIRO_SURFACE_TYPE_XLIB</constant>.
431 * Since: 1.0
433 cairo_surface_type_t
434 adg_type_from_filename(const gchar *file)
436 const gchar *p_suffix;
437 gchar *suffix;
438 cairo_surface_type_t type;
440 g_return_val_if_fail(file != NULL, CAIRO_SURFACE_TYPE_XLIB);
442 p_suffix = strrchr(file, '.');
443 if (p_suffix == NULL)
444 return CAIRO_SURFACE_TYPE_XLIB;
446 /* Put in suffix the lowercase extension without the leading dot */
447 suffix = g_ascii_strdown(p_suffix + 1, -1);
449 if (strcmp(suffix, "png") == 0) {
450 type = CAIRO_SURFACE_TYPE_IMAGE;
451 } else if (strcmp(suffix, "svg") == 0) {
452 type = CAIRO_SURFACE_TYPE_SVG;
453 } else if (strcmp(suffix, "pdf") == 0) {
454 type = CAIRO_SURFACE_TYPE_PDF;
455 } else if (strcmp(suffix, "ps") == 0) {
456 type = CAIRO_SURFACE_TYPE_PS;
457 } else {
458 type = CAIRO_SURFACE_TYPE_XLIB;
461 g_free(suffix);
462 return type;
466 * adg_object_clone:
467 * @src: (transfer none): the source #GObject to clone
469 * A helper method that clones a generic #GObject instance. The implementation
470 * leverages the g_object_get_property() method on @src to get all the
471 * properties and uses g_object_newv() to create the destination clone.
473 * The code is not as sophisticated as one might expect, so apart from what
474 * described there is no other magic involved. It is internally used by ADG to
475 * clone #AdgStyle instances in adg_style_clone().
477 * Returns: (transfer full): the clone of @src.
479 * Since: 1.0
481 GObject *
482 adg_object_clone(GObject *src)
484 GObject *dst;
485 GParameter *params;
486 GParamSpec **specs;
487 guint n, n_specs, n_params;
489 g_return_val_if_fail(G_IS_OBJECT(src), NULL);
490 specs = g_object_class_list_properties(G_OBJECT_GET_CLASS(src), &n_specs);
491 params = g_new0(GParameter, n_specs);
492 n_params = 0;
494 for (n = 0; n < n_specs; ++n) {
495 if ((specs[n]->flags & G_PARAM_READWRITE) == G_PARAM_READWRITE) {
496 params[n_params].name = g_intern_string(specs[n]->name);
497 g_value_init(&params[n_params].value, specs[n]->value_type);
498 g_object_get_property(src, specs[n]->name, &params[n_params].value);
499 ++ n_params;
503 dst = g_object_newv(G_TYPE_FROM_INSTANCE(src), n_params, params);
504 g_free(specs);
505 g_free(params);
507 return dst;
511 * adg_nop:
513 * A function that does nothing. It can be used as
514 * <constant>/dev/null</constant> when callback are required, e.g. with
515 * g_log_set_default_handler().
517 * Since: 1.0
519 void
520 adg_nop(void)
525 * adg_round:
526 * @value: the value to round
527 * @decimals: the number of significant decimals to consider
529 * Rounds the @value floating number to a specific number of digits. Be aware
530 * a binary floating point is unable to represent all decimal numbers, i.e.
531 * (WARNING: pure theoretical example ahead) rounding 3.3333 to the second
532 * decimal can return in 3.32999999.
534 * Returns: (type gdouble): the rounded number.
536 * Since: 1.0
538 gdouble
539 adg_round(gdouble value, gint decimals)
541 return decimals > 0 ? adg_round(value*10, decimals-1) / 10 : round(value);
545 * adg_single_strchr:
546 * @string: a string
547 * @ch: a character to find
549 * Similar to the standard strchr(), this function returns a pointer to the to
550 * the matched character that *is not* preceded by a backslash.
552 * Returns: (transfer none): a pointer to the matched @ch inside @string or
553 * %NULL if not found.
555 * Since: 1.0
557 const gchar *
558 adg_unescaped_strchr(const gchar *string, gint ch)
560 const gchar *ptr;
562 g_return_val_if_fail(string != NULL, NULL);
564 for (ptr = string; (ptr = strchr(ptr, ch)) != NULL; ++ ptr) {
565 if (ptr == string || *(ptr-1) != '\\') {
566 break;
570 return ptr;