Add API docs for keybinding enums.
[geany-mirror.git] / src / utils.c
blob203624934dd6300edcfa646378413f22280d06ce
1 /*
2 * utils.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * $Id$
25 * General utility functions, non-GTK related.
28 #include "geany.h"
30 #include <stdlib.h>
31 #include <ctype.h>
32 #include <math.h>
33 #include <unistd.h>
34 #include <string.h>
35 #include <errno.h>
36 #include <stdarg.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_TYPES_H
42 # include <sys/types.h>
43 #endif
45 #include <glib/gstdio.h>
47 #ifdef HAVE_GIO
48 # include <gio/gio.h>
49 #endif
51 #include "prefs.h"
52 #include "support.h"
53 #include "document.h"
54 #include "filetypes.h"
55 #include "dialogs.h"
56 #include "win32.h"
57 #include "project.h"
59 #include "utils.h"
62 /**
63 * Tries to open the given URI in a browser.
64 * On Windows, the system's default browser is opened.
65 * On non-Windows systems, the browser command set in the preferences dialog is used. In case
66 * that fails or it is unset, @c xdg-open is used as fallback as well as some other known
67 * browsers.
69 * @param uri The URI to open in the web browser.
71 * @since 0.16
72 **/
73 void utils_open_browser(const gchar *uri)
75 #ifdef G_OS_WIN32
76 g_return_if_fail(uri != NULL);
77 win32_open_browser(uri);
78 #else
79 gchar *cmdline;
81 g_return_if_fail(uri != NULL);
83 cmdline = g_strconcat(tool_prefs.browser_cmd, " \"", uri, "\"", NULL);
84 if (! g_spawn_command_line_async(cmdline, NULL))
86 const gchar *argv[3];
88 argv[0] = "xdg-open";
89 argv[1] = uri;
90 argv[2] = NULL;
91 if (! g_spawn_async(NULL, (gchar**)argv, NULL, G_SPAWN_SEARCH_PATH,
92 NULL, NULL, NULL, NULL))
94 argv[0] = "firefox";
95 if (! g_spawn_async(NULL, (gchar**)argv, NULL, G_SPAWN_SEARCH_PATH,
96 NULL, NULL, NULL, NULL))
98 argv[0] = "mozilla";
99 if (! g_spawn_async(NULL, (gchar**)argv, NULL, G_SPAWN_SEARCH_PATH, NULL,
100 NULL, NULL, NULL))
102 argv[0] = "opera";
103 if (! g_spawn_async(NULL, (gchar**)argv, NULL, G_SPAWN_SEARCH_PATH,
104 NULL, NULL, NULL, NULL))
106 argv[0] = "konqueror";
107 if (! g_spawn_async(NULL, (gchar**)argv, NULL, G_SPAWN_SEARCH_PATH,
108 NULL, NULL, NULL, NULL))
110 argv[0] = "netscape";
111 g_spawn_async(NULL, (gchar**)argv, NULL, G_SPAWN_SEARCH_PATH,
112 NULL, NULL, NULL, NULL);
119 g_free(cmdline);
120 #endif
124 /* taken from anjuta, to determine the EOL mode of the file */
125 gint utils_get_line_endings(const gchar* buffer, glong size)
127 gint i;
128 guint cr, lf, crlf, max_mode;
129 gint mode;
131 cr = lf = crlf = 0;
133 for (i = 0; i < size ; i++)
135 if (buffer[i] == 0x0a)
137 /* LF */
138 lf++;
140 else if (buffer[i] == 0x0d)
142 if (i >= (size - 1))
144 /* Last char, CR */
145 cr++;
147 else
149 if (buffer[i + 1] != 0x0a)
151 /* CR */
152 cr++;
154 else
156 /* CRLF */
157 crlf++;
159 i++;
164 /* Vote for the maximum */
165 mode = SC_EOL_LF;
166 max_mode = lf;
167 if (crlf > max_mode)
169 mode = SC_EOL_CRLF;
170 max_mode = crlf;
172 if (cr > max_mode)
174 mode = SC_EOL_CR;
175 max_mode = cr;
178 return mode;
182 gboolean utils_isbrace(gchar c, gboolean include_angles)
184 switch (c)
186 case '<':
187 case '>':
188 return include_angles;
190 case '(':
191 case ')':
192 case '{':
193 case '}':
194 case '[':
195 case ']': return TRUE;
196 default: return FALSE;
201 gboolean utils_is_opening_brace(gchar c, gboolean include_angles)
203 switch (c)
205 case '<':
206 return include_angles;
208 case '(':
209 case '{':
210 case '[': return TRUE;
211 default: return FALSE;
217 * Writes the given @a text into a file with @a filename.
218 * If the file doesn't exist, it will be created.
219 * If it already exists, it will be overwritten.
221 * @param filename The filename of the file to write, in locale encoding.
222 * @param text The text to write into the file.
224 * @return 0 if the file was successfully written, otherwise the @c errno of the
225 * failed operation is returned.
227 gint utils_write_file(const gchar *filename, const gchar *text)
229 g_return_val_if_fail(filename != NULL, ENOENT);
230 g_return_val_if_fail(text != NULL, EINVAL);
232 if (file_prefs.use_safe_file_saving)
234 GError *error = NULL;
235 if (! g_file_set_contents(filename, text, -1, &error))
237 geany_debug("%s: could not write to file %s (%s)", G_STRFUNC, filename, error->message);
238 g_error_free(error);
239 return EIO;
242 else
244 FILE *fp;
245 gint bytes_written, len;
247 if (filename == NULL)
248 return ENOENT;
250 len = strlen(text);
251 fp = g_fopen(filename, "w");
252 if (fp != NULL)
254 bytes_written = fwrite(text, sizeof (gchar), len, fp);
255 fclose(fp);
257 if (len != bytes_written)
259 geany_debug(
260 "utils_write_file(): written only %d bytes, had to write %d bytes to %s",
261 bytes_written, len, filename);
262 return EIO;
265 else
267 geany_debug("utils_write_file(): could not write to file %s (%s)",
268 filename, g_strerror(errno));
269 return errno;
272 return 0;
277 * (stolen from anjuta and modified)
278 * Search backward through size bytes looking for a '<', then return the tag, if any.
279 * @return The tag name
281 gchar *utils_find_open_xml_tag(const gchar sel[], gint size, gboolean check_tag)
283 const gchar *begin, *cur;
285 if (G_UNLIKELY(size < 3))
286 { /* Smallest tag is "<p>" which is 3 characters */
287 return NULL;
289 begin = &sel[0];
290 if (check_tag)
291 cur = &sel[size - 3];
292 else
293 cur = &sel[size - 1];
295 cur--; /* Skip past the > */
296 while (cur > begin)
298 if (*cur == '<') break;
299 else if (! check_tag && *cur == '>') break;
300 --cur;
303 if (*cur == '<')
305 GString *result = g_string_sized_new(64);
307 cur++;
308 while (strchr(":_-.", *cur) || isalnum(*cur))
310 g_string_append_c(result, *cur);
311 cur++;
313 return g_string_free(result, FALSE);
316 return NULL;
320 const gchar *utils_get_eol_name(gint eol_mode)
322 switch (eol_mode)
324 case SC_EOL_CRLF: return _("Win (CRLF)"); break;
325 case SC_EOL_CR: return _("Mac (CR)"); break;
326 default: return _("Unix (LF)"); break;
331 gboolean utils_atob(const gchar *str)
333 if (G_UNLIKELY(str == NULL))
334 return FALSE;
335 else if (strcmp(str, "TRUE") == 0 || strcmp(str, "true") == 0)
336 return TRUE;
337 return FALSE;
341 /* NULL-safe version of g_path_is_absolute(). */
342 gboolean utils_is_absolute_path(const gchar *path)
344 if (! NZV(path))
345 return FALSE;
347 return g_path_is_absolute(path);
351 /* Skips root if path is absolute, do nothing otherwise.
352 * This is a relative-safe version of g_path_skip_root().
354 const gchar *utils_path_skip_root(const gchar *path)
356 const gchar *path_relative;
358 path_relative = g_path_skip_root(path);
360 return (path_relative != NULL) ? path_relative : path;
364 gdouble utils_scale_round(gdouble val, gdouble factor)
366 /*val = floor(val * factor + 0.5);*/
367 val = floor(val);
368 val = MAX(val, 0);
369 val = MIN(val, factor);
371 return val;
376 * A replacement function for g_strncasecmp() to compare strings case-insensitive.
377 * It converts both strings into lowercase using g_utf8_strdown() and then compare
378 * both strings using strcmp().
379 * This is not completely accurate regarding locale-specific case sorting rules
380 * but seems to be a good compromise between correctness and performance.
382 * The input strings should be in UTF-8 or locale encoding.
384 * @param s1 Pointer to first string or @c NULL.
385 * @param s2 Pointer to second string or @c NULL.
387 * @return an integer less than, equal to, or greater than zero if @a s1 is found, respectively,
388 * to be less than, to match, or to be greater than @a s2.
390 * @since 0.16
392 gint utils_str_casecmp(const gchar *s1, const gchar *s2)
394 gchar *tmp1, *tmp2;
395 gint result;
397 g_return_val_if_fail(s1 != NULL, 1);
398 g_return_val_if_fail(s2 != NULL, -1);
400 tmp1 = g_strdup(s1);
401 tmp2 = g_strdup(s2);
403 /* first ensure strings are UTF-8 */
404 if (! g_utf8_validate(s1, -1, NULL))
405 setptr(tmp1, g_locale_to_utf8(s1, -1, NULL, NULL, NULL));
406 if (! g_utf8_validate(s2, -1, NULL))
407 setptr(tmp2, g_locale_to_utf8(s2, -1, NULL, NULL, NULL));
409 if (tmp1 == NULL)
411 g_free(tmp2);
412 return 1;
414 if (tmp2 == NULL)
416 g_free(tmp1);
417 return -1;
420 /* then convert the strings into a case-insensitive form */
421 setptr(tmp1, g_utf8_strdown(tmp1, -1));
422 setptr(tmp2, g_utf8_strdown(tmp2, -1));
424 /* compare */
425 result = strcmp(tmp1, tmp2);
427 g_free(tmp1);
428 g_free(tmp2);
429 return result;
434 * Truncates the input string to a given length.
435 * Characters are removed from the middle of the string, so the start and the end of string
436 * won't change.
438 * @param string Input string.
439 * @param truncate_length The length in characters of the resulting string.
441 * @return A copy of @a string which is truncated to @a truncate_length characters,
442 * should be freed when no longer needed.
444 * @since 0.17
446 /* This following function is taken from Gedit. */
447 gchar *utils_str_middle_truncate(const gchar *string, guint truncate_length)
449 GString *truncated;
450 guint length;
451 guint n_chars;
452 guint num_left_chars;
453 guint right_offset;
454 guint delimiter_length;
455 const gchar *delimiter = "\342\200\246";
457 g_return_val_if_fail(string != NULL, NULL);
459 length = strlen(string);
461 g_return_val_if_fail(g_utf8_validate(string, length, NULL), NULL);
463 /* It doesnt make sense to truncate strings to less than the size of the delimiter plus 2
464 * characters (one on each side) */
465 delimiter_length = g_utf8_strlen(delimiter, -1);
466 if (truncate_length < (delimiter_length + 2))
467 return g_strdup(string);
469 n_chars = g_utf8_strlen(string, length);
471 /* Make sure the string is not already small enough. */
472 if (n_chars <= truncate_length)
473 return g_strdup (string);
475 /* Find the 'middle' where the truncation will occur. */
476 num_left_chars = (truncate_length - delimiter_length) / 2;
477 right_offset = n_chars - truncate_length + num_left_chars + delimiter_length;
479 truncated = g_string_new_len(string, g_utf8_offset_to_pointer(string, num_left_chars) - string);
480 g_string_append(truncated, delimiter);
481 g_string_append(truncated, g_utf8_offset_to_pointer(string, right_offset));
483 return g_string_free(truncated, FALSE);
488 * @c NULL-safe string comparison. Returns @c TRUE if both @a a and @a b are @c NULL
489 * or if @a a and @a b refer to valid strings which are equal.
491 * @param a Pointer to first string or @c NULL.
492 * @param b Pointer to second string or @c NULL.
494 * @return @c TRUE if @a a equals @a b, else @c FALSE.
496 gboolean utils_str_equal(const gchar *a, const gchar *b)
498 /* (taken from libexo from os-cillation) */
499 if (a == NULL && b == NULL) return TRUE;
500 else if (a == NULL || b == NULL) return FALSE;
502 while (*a == *b++)
503 if (*a++ == '\0')
504 return TRUE;
506 return FALSE;
511 * Removes the extension from @a filename and return the result in a newly allocated string.
513 * @param filename The filename to operate on.
515 * @return A newly-allocated string, should be freed when no longer needed.
517 gchar *utils_remove_ext_from_filename(const gchar *filename)
519 gchar *last_dot;
520 gchar *result;
521 gint i;
523 g_return_val_if_fail(filename != NULL, NULL);
525 last_dot = strrchr(filename, '.');
526 if (! last_dot)
527 return g_strdup(filename);
529 /* assumes extension is small, so extra bytes don't matter */
530 result = g_malloc(strlen(filename));
531 i = 0;
532 while ((filename + i) != last_dot)
534 result[i] = filename[i];
535 i++;
537 result[i] = 0;
538 return result;
542 gchar utils_brace_opposite(gchar ch)
544 switch (ch)
546 case '(': return ')';
547 case ')': return '(';
548 case '[': return ']';
549 case ']': return '[';
550 case '{': return '}';
551 case '}': return '{';
552 case '<': return '>';
553 case '>': return '<';
554 default: return '\0';
559 gchar *utils_get_hostname(void)
561 #ifdef G_OS_WIN32
562 return win32_get_hostname();
563 #elif defined(HAVE_GETHOSTNAME)
564 gchar hostname[100];
565 if (gethostname(hostname, sizeof(hostname)) == 0)
566 return g_strdup(hostname);
567 #endif
568 return g_strdup("localhost");
572 /* Checks whether the given file can be written. locale_filename is expected in locale encoding.
573 * Returns 0 if it can be written, otherwise it returns errno */
574 gint utils_is_file_writeable(const gchar *locale_filename)
576 gchar *file;
577 gint ret;
579 if (! g_file_test(locale_filename, G_FILE_TEST_EXISTS) &&
580 ! g_file_test(locale_filename, G_FILE_TEST_IS_DIR))
581 /* get the file's directory to check for write permission if it doesn't yet exist */
582 file = g_path_get_dirname(locale_filename);
583 else
584 file = g_strdup(locale_filename);
586 #ifdef G_OS_WIN32
587 /* use _waccess on Windows, access() doesn't accept special characters */
588 ret = win32_check_write_permission(file);
589 #else
591 /* access set also errno to "FILE NOT FOUND" even if locale_filename is writeable, so use
592 * errno only when access() explicitly returns an error */
593 if (access(file, R_OK | W_OK) != 0)
594 ret = errno;
595 else
596 ret = 0;
597 #endif
598 g_free(file);
599 return ret;
603 /* Replaces all occurrences of needle in haystack with replacement.
604 * Warning: *haystack must be a heap address; it may be freed and reassigned.
605 * Note: utils_string_replace_all() will always be faster when @a replacement is longer
606 * than @a needle.
607 * All strings have to be NULL-terminated.
608 * See utils_string_replace_all() for details. */
609 void utils_str_replace_all(gchar **haystack, const gchar *needle, const gchar *replacement)
611 GString *str;
613 g_return_if_fail(*haystack != NULL);
615 str = g_string_new(*haystack);
617 g_free(*haystack);
618 utils_string_replace_all(str, needle, replacement);
620 *haystack = g_string_free(str, FALSE);
624 gint utils_strpos(const gchar *haystack, const gchar *needle)
626 gint haystack_length = strlen(haystack);
627 gint needle_length = strlen(needle);
628 gint i, j, pos = -1;
630 if (needle_length > haystack_length)
632 return -1;
634 else
636 for (i = 0; (i < haystack_length) && pos == -1; i++)
638 if (haystack[i] == needle[0] && needle_length == 1)
639 return i;
640 else if (haystack[i] == needle[0])
642 for (j = 1; (j < needle_length); j++)
644 if (haystack[i + j] == needle[j])
646 if (pos == -1)
647 pos = i;
649 else
651 pos = -1;
652 break;
657 return pos;
663 * Retrieves a formatted date/time string from strftime().
664 * This function should be preferred to directly calling strftime() since this function
665 * works on UTF-8 encoded strings.
667 * @param format The format string to pass to strftime(3). See the strftime(3)
668 * documentation for details, in UTF-8 encoding.
669 * @param time_to_use The date/time to use, in time_t format or NULL to use the current time.
671 * @return A newly-allocated string, should be freed when no longer needed.
673 * @since 0.16
675 gchar *utils_get_date_time(const gchar *format, time_t *time_to_use)
677 const struct tm *tm;
678 static gchar date[1024];
679 gchar *locale_format;
680 gsize len;
682 g_return_val_if_fail(format != NULL, NULL);
684 if (! g_utf8_validate(format, -1, NULL))
686 locale_format = g_locale_from_utf8(format, -1, NULL, NULL, NULL);
687 if (locale_format == NULL)
688 return NULL;
690 else
691 locale_format = g_strdup(format);
693 if (time_to_use != NULL)
694 tm = localtime(time_to_use);
695 else
697 time_t tp = time(NULL);
698 tm = localtime(&tp);
701 len = strftime(date, 1024, locale_format, tm);
702 g_free(locale_format);
703 if (len == 0)
704 return NULL;
706 if (! g_utf8_validate(date, len, NULL))
707 return g_locale_to_utf8(date, len, NULL, NULL, NULL);
708 else
709 return g_strdup(date);
713 gchar *utils_get_initials(const gchar *name)
715 gint i = 1, j = 1;
716 gchar *initials = g_malloc0(5);
718 initials[0] = name[0];
719 while (name[i] != '\0' && j < 4)
721 if (name[i] == ' ' && name[i + 1] != ' ')
723 initials[j++] = name[i + 1];
725 i++;
727 return initials;
732 * Wraps g_key_file_get_integer() to add a default value argument.
734 * @param config A GKeyFile object.
735 * @param section The group name to look in for the key.
736 * @param key The key to find.
737 * @param default_value The default value which will be returned when @a section or @a key
738 * don't exist.
740 * @return The value associated with @a key as an integer, or the given default value if the value
741 * could not be retrieved.
743 gint utils_get_setting_integer(GKeyFile *config, const gchar *section, const gchar *key,
744 const gint default_value)
746 gint tmp;
747 GError *error = NULL;
749 if (G_UNLIKELY(config == NULL))
750 return default_value;
752 tmp = g_key_file_get_integer(config, section, key, &error);
753 if (G_UNLIKELY(error))
755 g_error_free(error);
756 return default_value;
758 return tmp;
763 * Wraps g_key_file_get_boolean() to add a default value argument.
765 * @param config A GKeyFile object.
766 * @param section The group name to look in for the key.
767 * @param key The key to find.
768 * @param default_value The default value which will be returned when @c section or @c key
769 * don't exist.
771 * @return The value associated with @a key as a boolean, or the given default value if the value
772 * could not be retrieved.
774 gboolean utils_get_setting_boolean(GKeyFile *config, const gchar *section, const gchar *key,
775 const gboolean default_value)
777 gboolean tmp;
778 GError *error = NULL;
780 if (G_UNLIKELY(config == NULL))
781 return default_value;
783 tmp = g_key_file_get_boolean(config, section, key, &error);
784 if (G_UNLIKELY(error))
786 g_error_free(error);
787 return default_value;
789 return tmp;
794 * Wraps g_key_file_get_string() to add a default value argument.
796 * @param config A GKeyFile object.
797 * @param section The group name to look in for the key.
798 * @param key The key to find.
799 * @param default_value The default value which will be returned when @a section or @a key
800 * don't exist.
802 * @return A newly allocated string, either the value for @a key or a copy of the given
803 * default value if it could not be retrieved.
805 gchar *utils_get_setting_string(GKeyFile *config, const gchar *section, const gchar *key,
806 const gchar *default_value)
808 gchar *tmp;
810 if (G_UNLIKELY(config == NULL))
811 return g_strdup(default_value);
813 tmp = g_key_file_get_string(config, section, key, NULL);
814 if (G_UNLIKELY(!tmp))
816 return g_strdup(default_value);
818 return tmp;
822 gchar *utils_get_hex_from_color(GdkColor *color)
824 gchar *buffer = g_malloc0(9);
826 g_return_val_if_fail(color != NULL, NULL);
828 g_snprintf(buffer, 8, "#%02X%02X%02X",
829 (guint) (utils_scale_round(color->red / 256, 255)),
830 (guint) (utils_scale_round(color->green / 256, 255)),
831 (guint) (utils_scale_round(color->blue / 256, 255)));
833 return buffer;
837 guint utils_invert_color(guint color)
839 guint r, g, b;
841 r = 0xffffff - color;
842 g = 0xffffff - (color >> 8);
843 b = 0xffffff - (color >> 16);
845 return (r | (g << 8) | (b << 16));
849 /* Get directory from current file in the notebook.
850 * Returns dir string that should be freed or NULL, depending on whether current file is valid.
851 * Returned string is in UTF-8 encoding */
852 gchar *utils_get_current_file_dir_utf8(void)
854 GeanyDocument *doc = document_get_current();
856 if (doc != NULL)
858 /* get current filename */
859 const gchar *cur_fname = doc->file_name;
861 if (cur_fname != NULL)
863 /* get folder part from current filename */
864 return g_path_get_dirname(cur_fname); /* returns "." if no path */
868 return NULL; /* no file open */
872 /* very simple convenience function */
873 void utils_beep(void)
875 if (prefs.beep_on_errors)
876 gdk_beep();
880 /* taken from busybox, thanks */
881 gchar *utils_make_human_readable_str(guint64 size, gulong block_size,
882 gulong display_unit)
884 /* The code will adjust for additional (appended) units. */
885 static const gchar zero_and_units[] = { '0', 0, 'K', 'M', 'G', 'T' };
886 static const gchar fmt[] = "%Lu %c%c";
887 static const gchar fmt_tenths[] = "%Lu.%d %c%c";
889 guint64 val;
890 gint frac;
891 const gchar *u;
892 const gchar *f;
894 u = zero_and_units;
895 f = fmt;
896 frac = 0;
898 val = size * block_size;
899 if (val == 0)
900 return g_strdup(u);
902 if (display_unit)
904 val += display_unit/2; /* Deal with rounding. */
905 val /= display_unit; /* Don't combine with the line above!!! */
907 else
909 ++u;
910 while ((val >= 1024) && (u < zero_and_units + sizeof(zero_and_units) - 1))
912 f = fmt_tenths;
913 ++u;
914 frac = ((((gint)(val % 1024)) * 10) + (1024 / 2)) / 1024;
915 val /= 1024;
917 if (frac >= 10)
918 { /* We need to round up here. */
919 ++val;
920 frac = 0;
924 /* If f==fmt then 'frac' and 'u' are ignored. */
925 return g_strdup_printf(f, val, frac, *u, 'b');
929 static guint utils_get_value_of_hex(const gchar ch)
931 if (ch >= '0' && ch <= '9')
932 return ch - '0';
933 else if (ch >= 'A' && ch <= 'F')
934 return ch - 'A' + 10;
935 else if (ch >= 'a' && ch <= 'f')
936 return ch - 'a' + 10;
937 else
938 return 0;
942 /* utils_strtod() converts a string containing a hex colour ("0x00ff00") into an integer.
943 * Basically, it is the same as strtod() would do, but it does not understand hex colour values,
944 * before ANSI-C99. With with_route set, it takes strings of the format "#00ff00".
945 * Returns -1 on failure. */
946 gint utils_strtod(const gchar *source, gchar **end, gboolean with_route)
948 guint red, green, blue, offset = 0;
950 g_return_val_if_fail(source != NULL, -1);
952 if (with_route && (strlen(source) != 7 || source[0] != '#'))
953 return -1;
954 else if (! with_route && (strlen(source) != 8 || source[0] != '0' ||
955 (source[1] != 'x' && source[1] != 'X')))
957 return -1;
960 /* offset is set to 1 when the string starts with 0x, otherwise it starts with #
961 * and we don't need to increase the index */
962 if (! with_route)
963 offset = 1;
965 red = utils_get_value_of_hex(
966 source[1 + offset]) * 16 + utils_get_value_of_hex(source[2 + offset]);
967 green = utils_get_value_of_hex(
968 source[3 + offset]) * 16 + utils_get_value_of_hex(source[4 + offset]);
969 blue = utils_get_value_of_hex(
970 source[5 + offset]) * 16 + utils_get_value_of_hex(source[6 + offset]);
972 return (red | (green << 8) | (blue << 16));
976 /* Returns: newly allocated string with the current time formatted HH:MM:SS. */
977 gchar *utils_get_current_time_string(void)
979 const time_t tp = time(NULL);
980 const struct tm *tmval = localtime(&tp);
981 gchar *result = g_malloc0(9);
983 strftime(result, 9, "%H:%M:%S", tmval);
984 result[8] = '\0';
985 return result;
989 GIOChannel *utils_set_up_io_channel(
990 gint fd, GIOCondition cond, gboolean nblock, GIOFunc func, gpointer data)
992 GIOChannel *ioc;
993 /*const gchar *encoding;*/
995 #ifdef G_OS_WIN32
996 ioc = g_io_channel_win32_new_fd(fd);
997 #else
998 ioc = g_io_channel_unix_new(fd);
999 #endif
1001 if (nblock)
1002 g_io_channel_set_flags(ioc, G_IO_FLAG_NONBLOCK, NULL);
1004 g_io_channel_set_encoding(ioc, NULL, NULL);
1006 if (! g_get_charset(&encoding))
1007 { // hope this works reliably
1008 GError *error = NULL;
1009 g_io_channel_set_encoding(ioc, encoding, &error);
1010 if (error)
1012 geany_debug("%s: %s", G_STRFUNC, error->message);
1013 g_error_free(error);
1014 return ioc;
1018 /* "auto-close" ;-) */
1019 g_io_channel_set_close_on_unref(ioc, TRUE);
1021 g_io_add_watch(ioc, cond, func, data);
1022 g_io_channel_unref(ioc);
1024 return ioc;
1028 gchar **utils_read_file_in_array(const gchar *filename)
1030 gchar **result = NULL;
1031 gchar *data;
1033 g_return_val_if_fail(filename != NULL, NULL);
1035 g_file_get_contents(filename, &data, NULL, NULL);
1037 if (data != NULL)
1039 result = g_strsplit_set(data, "\r\n", -1);
1040 g_free(data);
1043 return result;
1047 /* Contributed by Stefan Oltmanns, thanks.
1048 * Replaces \\, \r, \n, \t and \uXXX by their real counterparts.
1049 * keep_backslash is used for regex strings to leave '\\' and '\?' in place */
1050 gboolean utils_str_replace_escape(gchar *string, gboolean keep_backslash)
1052 gsize i, j, len;
1053 guint unicodechar;
1055 g_return_val_if_fail(string != NULL, FALSE);
1057 j = 0;
1058 len = strlen(string);
1059 for (i = 0; i < len; i++)
1061 if (string[i]=='\\')
1063 if (i++ >= strlen(string))
1065 return FALSE;
1067 switch (string[i])
1069 case '\\':
1070 if (keep_backslash)
1071 string[j++] = '\\';
1072 string[j] = '\\';
1073 break;
1074 case 'n':
1075 string[j] = '\n';
1076 break;
1077 case 'r':
1078 string[j] = '\r';
1079 break;
1080 case 't':
1081 string[j] = '\t';
1082 break;
1083 #if 0
1084 case 'x': /* Warning: May produce illegal utf-8 string! */
1085 i += 2;
1086 if (i >= strlen(string))
1088 return FALSE;
1090 if (isdigit(string[i - 1])) string[j] = string[i - 1] - 48;
1091 else if (isxdigit(string[i - 1])) string[j] = tolower(string[i - 1])-87;
1092 else return FALSE;
1093 string[j] <<= 4;
1094 if (isdigit(string[i])) string[j] |= string[i] - 48;
1095 else if (isxdigit(string[i])) string[j] |= tolower(string[i])-87;
1096 else return FALSE;
1097 break;
1098 #endif
1099 case 'u':
1101 i += 2;
1102 if (i >= strlen(string))
1104 return FALSE;
1106 if (isdigit(string[i - 1])) unicodechar = string[i - 1] - 48;
1107 else if (isxdigit(string[i - 1])) unicodechar = tolower(string[i - 1])-87;
1108 else return FALSE;
1109 unicodechar <<= 4;
1110 if (isdigit(string[i])) unicodechar |= string[i] - 48;
1111 else if (isxdigit(string[i])) unicodechar |= tolower(string[i])-87;
1112 else return FALSE;
1113 if (((i + 2) < strlen(string)) && (isdigit(string[i + 1]) || isxdigit(string[i + 1]))
1114 && (isdigit(string[i + 2]) || isxdigit(string[i + 2])))
1116 i += 2;
1117 unicodechar <<= 8;
1118 if (isdigit(string[i - 1])) unicodechar |= ((string[i - 1] - 48) << 4);
1119 else unicodechar |= ((tolower(string[i - 1])-87) << 4);
1120 if (isdigit(string[i])) unicodechar |= string[i] - 48;
1121 else unicodechar |= tolower(string[i])-87;
1123 if (((i + 2) < strlen(string)) && (isdigit(string[i + 1]) || isxdigit(string[i + 1]))
1124 && (isdigit(string[i + 2]) || isxdigit(string[i + 2])))
1126 i += 2;
1127 unicodechar <<= 8;
1128 if (isdigit(string[i - 1])) unicodechar |= ((string[i - 1] - 48) << 4);
1129 else unicodechar |= ((tolower(string[i - 1])-87) << 4);
1130 if (isdigit(string[i])) unicodechar |= string[i] - 48;
1131 else unicodechar |= tolower(string[i])-87;
1133 if (unicodechar < 0x80)
1135 string[j] = unicodechar;
1137 else if (unicodechar < 0x800)
1139 string[j] = (unsigned char) ((unicodechar >> 6) | 0xC0);
1140 j++;
1141 string[j] = (unsigned char) ((unicodechar & 0x3F) | 0x80);
1143 else if (unicodechar < 0x10000)
1145 string[j] = (unsigned char) ((unicodechar >> 12) | 0xE0);
1146 j++;
1147 string[j] = (unsigned char) (((unicodechar >> 6) & 0x3F) | 0x80);
1148 j++;
1149 string[j] = (unsigned char) ((unicodechar & 0x3F) | 0x80);
1151 else if (unicodechar < 0x110000) /* more chars are not allowed in unicode */
1153 string[j] = (unsigned char) ((unicodechar >> 18) | 0xF0);
1154 j++;
1155 string[j] = (unsigned char) (((unicodechar >> 12) & 0x3F) | 0x80);
1156 j++;
1157 string[j] = (unsigned char) (((unicodechar >> 6) & 0x3F) | 0x80);
1158 j++;
1159 string[j] = (unsigned char) ((unicodechar & 0x3F) | 0x80);
1161 else
1163 return FALSE;
1165 break;
1167 default:
1168 /* unnecessary escapes are allowed */
1169 if (keep_backslash)
1170 string[j++] = '\\';
1171 string[j] = string[i];
1174 else
1176 string[j] = string[i];
1178 j++;
1180 while (j < i)
1182 string[j] = 0;
1183 j++;
1185 return TRUE;
1189 /* Wraps a string in place, replacing a space with a newline character.
1190 * wrapstart is the minimum position to start wrapping or -1 for default */
1191 gboolean utils_wrap_string(gchar *string, gint wrapstart)
1193 gchar *pos, *linestart;
1194 gboolean ret = FALSE;
1196 if (wrapstart < 0)
1197 wrapstart = 80;
1199 for (pos = linestart = string; *pos != '\0'; pos++)
1201 if (pos - linestart >= wrapstart && *pos == ' ')
1203 *pos = '\n';
1204 linestart = pos;
1205 ret = TRUE;
1208 return ret;
1213 * Converts the given UTF-8 encoded string into locale encoding.
1214 * On Windows platforms, it does nothing and instead it just returns a copy of the input string.
1216 * @param utf8_text UTF-8 encoded text.
1218 * @return The converted string in locale encoding, or a copy of the input string if conversion
1219 * failed. Should be freed with g_free(). If @a utf8_text is @c NULL, @c NULL is returned.
1221 gchar *utils_get_locale_from_utf8(const gchar *utf8_text)
1223 #ifdef G_OS_WIN32
1224 /* just do nothing on Windows platforms, this ifdef is just to prevent unwanted conversions
1225 * which would result in wrongly converted strings */
1226 return g_strdup(utf8_text);
1227 #else
1228 gchar *locale_text;
1230 if (! utf8_text)
1231 return NULL;
1232 locale_text = g_locale_from_utf8(utf8_text, -1, NULL, NULL, NULL);
1233 if (locale_text == NULL)
1234 locale_text = g_strdup(utf8_text);
1235 return locale_text;
1236 #endif
1241 * Converts the given string (in locale encoding) into UTF-8 encoding.
1242 * On Windows platforms, it does nothing and instead it just returns a copy of the input string.
1244 * @param locale_text Text in locale encoding.
1246 * @return The converted string in UTF-8 encoding, or a copy of the input string if conversion
1247 * failed. Should be freed with g_free(). If @a locale_text is @c NULL, @c NULL is returned.
1249 gchar *utils_get_utf8_from_locale(const gchar *locale_text)
1251 #ifdef G_OS_WIN32
1252 /* just do nothing on Windows platforms, this ifdef is just to prevent unwanted conversions
1253 * which would result in wrongly converted strings */
1254 return g_strdup(locale_text);
1255 #else
1256 gchar *utf8_text;
1258 if (! locale_text)
1259 return NULL;
1260 utf8_text = g_locale_to_utf8(locale_text, -1, NULL, NULL, NULL);
1261 if (utf8_text == NULL)
1262 utf8_text = g_strdup(locale_text);
1263 return utf8_text;
1264 #endif
1268 /* Pass pointers to free after arg_count.
1269 * The last argument must be NULL as an extra check that arg_count is correct. */
1270 void utils_free_pointers(gsize arg_count, ...)
1272 va_list a;
1273 gsize i;
1274 gpointer ptr;
1276 va_start(a, arg_count);
1277 for (i = 0; i < arg_count; i++)
1279 ptr = va_arg(a, gpointer);
1280 g_free(ptr);
1282 ptr = va_arg(a, gpointer);
1283 if (ptr)
1284 g_warning("Wrong arg_count!");
1285 va_end(a);
1289 /* Creates a string array deep copy of a series of non-NULL strings.
1290 * The first argument is nothing special.
1291 * The list must be ended with NULL.
1292 * If first is NULL, NULL is returned. */
1293 gchar **utils_strv_new(const gchar *first, ...)
1295 gsize strvlen, i;
1296 va_list args;
1297 gchar *str;
1298 gchar **strv;
1300 g_return_val_if_fail(first != NULL, NULL);
1302 strvlen = 1; /* for first argument */
1304 /* count other arguments */
1305 va_start(args, first);
1306 for (; va_arg(args, gchar*) != NULL; strvlen++);
1307 va_end(args);
1309 strv = g_new(gchar*, strvlen + 1); /* +1 for NULL terminator */
1310 strv[0] = g_strdup(first);
1312 va_start(args, first);
1313 for (i = 1; str = va_arg(args, gchar*), str != NULL; i++)
1315 strv[i] = g_strdup(str);
1317 va_end(args);
1319 strv[i] = NULL;
1320 return strv;
1325 * Creates a directory if it doesn't already exist.
1326 * Creates intermediate parent directories as needed, too.
1327 * The permissions of the created directory are set 0700.
1329 * @param path The path of the directory to create, in locale encoding.
1330 * @param create_parent_dirs Whether to create intermediate parent directories if necessary.
1332 * @return 0 if the directory was successfully created, otherwise the @c errno of the
1333 * failed operation is returned.
1335 gint utils_mkdir(const gchar *path, gboolean create_parent_dirs)
1337 gint mode = 0700;
1338 gint result;
1340 if (path == NULL || strlen(path) == 0)
1341 return EFAULT;
1343 result = (create_parent_dirs) ? g_mkdir_with_parents(path, mode) : g_mkdir(path, mode);
1344 if (result != 0)
1345 return errno;
1346 return 0;
1351 * Gets a list of files from the specified directory.
1352 * Locale encoding is expected for @a path and used for the file list. The list and the data
1353 * in the list should be freed after use, e.g.:
1354 * @code
1355 * g_slist_foreach(list, (GFunc) g_free, NULL);
1356 * g_slist_free(list); @endcode
1358 * @note If you don't need a list you should use the foreach_dir() macro instead -
1359 * it's more efficient.
1361 * @param path The path of the directory to scan, in locale encoding.
1362 * @param full_path Whether to include the full path for each filename in the list. Obviously this
1363 * will use more memory.
1364 * @param sort Whether to sort alphabetically (UTF-8 safe).
1365 * @param error The location for storing a possible error, or @c NULL.
1367 * @return A newly allocated list or @c NULL if no files were found. The list and its data should be
1368 * freed when no longer needed.
1369 * @see utils_get_file_list().
1371 GSList *utils_get_file_list_full(const gchar *path, gboolean full_path, gboolean sort, GError **error)
1373 GSList *list = NULL;
1374 GDir *dir;
1375 const gchar *filename;
1377 if (error)
1378 *error = NULL;
1379 g_return_val_if_fail(path != NULL, NULL);
1381 dir = g_dir_open(path, 0, error);
1382 if (dir == NULL)
1383 return NULL;
1385 foreach_dir(filename, dir)
1387 list = g_slist_append(list, full_path ?
1388 g_build_path(G_DIR_SEPARATOR_S, path, filename, NULL) : g_strdup(filename));
1390 g_dir_close(dir);
1391 /* sorting last is quicker than on insertion */
1392 if (sort)
1393 list = g_slist_sort(list, (GCompareFunc) utils_str_casecmp);
1394 return list;
1399 * Gets a sorted list of files from the specified directory.
1400 * Locale encoding is expected for @a path and used for the file list. The list and the data
1401 * in the list should be freed after use, e.g.:
1402 * @code
1403 * g_slist_foreach(list, (GFunc) g_free, NULL);
1404 * g_slist_free(list); @endcode
1406 * @param path The path of the directory to scan, in locale encoding.
1407 * @param length The location to store the number of non-@c NULL data items in the list,
1408 * unless @c NULL.
1409 * @param error The location for storing a possible error, or @c NULL.
1411 * @return A newly allocated list or @c NULL if no files were found. The list and its data should be
1412 * freed when no longer needed.
1413 * @see utils_get_file_list_full().
1415 GSList *utils_get_file_list(const gchar *path, guint *length, GError **error)
1417 GSList *list = utils_get_file_list_full(path, FALSE, TRUE, error);
1419 if (length)
1420 *length = g_slist_length(list);
1421 return list;
1425 /* returns TRUE if any letter in str is a capital, FALSE otherwise. Should be Unicode safe. */
1426 gboolean utils_str_has_upper(const gchar *str)
1428 gunichar c;
1430 if (! NZV(str) || ! g_utf8_validate(str, -1, NULL))
1431 return FALSE;
1433 while (*str != '\0')
1435 c = g_utf8_get_char(str);
1436 /* check only letters and stop once the first non-capital was found */
1437 if (g_unichar_isalpha(c) && g_unichar_isupper(c))
1438 return TRUE;
1439 /* FIXME don't write a const string */
1440 str = g_utf8_next_char(str);
1442 return FALSE;
1446 static guint utils_string_replace_helper(GString *haystack, const gchar *needle,
1447 const gchar *replace, const guint max_replaces)
1449 const gchar *stack, *match;
1450 guint ret = 0;
1451 gssize pos;
1453 g_return_val_if_fail(haystack != NULL, 0);
1454 if (haystack->len == 0)
1455 return FALSE;
1456 g_return_val_if_fail(NZV(needle), 0);
1458 stack = haystack->str;
1459 if (! (match = strstr(stack, needle)))
1460 return 0;
1463 pos = match - haystack->str;
1464 g_string_erase(haystack, pos, strlen(needle));
1466 /* make next search after removed matching text.
1467 * (we have to be careful to only use haystack->str as its address may change) */
1468 stack = haystack->str + pos;
1470 if (G_LIKELY(replace))
1472 g_string_insert(haystack, pos, replace);
1473 stack = haystack->str + pos + strlen(replace); /* skip past replacement */
1476 while (++ret != max_replaces && (match = strstr(stack, needle)));
1478 return ret;
1483 * Replaces all occurrences of @a needle in @a haystack with @a replace.
1484 * As of Geany 0.16, @a replace can match @a needle, so the following will work:
1485 * @code utils_string_replace_all(text, "\n", "\r\n"); @endcode
1487 * @param haystack The input string to operate on. This string is modified in place.
1488 * @param needle The string which should be replaced.
1489 * @param replace The replacement for @a needle.
1491 * @return Number of replacements made.
1493 guint utils_string_replace_all(GString *haystack, const gchar *needle, const gchar *replace)
1495 return utils_string_replace_helper(haystack, needle, replace, 0);
1500 * Replaces only the first occurrence of @a needle in @a haystack
1501 * with @a replace.
1502 * For details, see utils_string_replace_all().
1504 * @param haystack The input string to operate on. This string is modified in place.
1505 * @param needle The string which should be replaced.
1506 * @param replace The replacement for @a needle.
1508 * @return Number of replacements made.
1510 * @since 0.16
1512 guint utils_string_replace_first(GString *haystack, const gchar *needle, const gchar *replace)
1514 return utils_string_replace_helper(haystack, needle, replace, 1);
1518 /* Get project or default startup directory (if set), or NULL. */
1519 const gchar *utils_get_default_dir_utf8(void)
1521 if (app->project && NZV(app->project->base_path))
1523 return app->project->base_path;
1526 if (NZV(prefs.default_open_path))
1528 return prefs.default_open_path;
1530 return NULL;
1534 static gboolean check_error(GError **error)
1536 if (error != NULL && *error != NULL)
1538 /* imitate the GLib warning */
1539 g_warning(
1540 "GError set over the top of a previous GError or uninitialized memory.\n"
1541 "This indicates a bug in someone's code. You must ensure an error is NULL "
1542 "before it's set.");
1543 /* after returning the code may segfault, but we don't care because we should
1544 * make sure *error is NULL */
1545 return FALSE;
1547 return TRUE;
1552 * Wraps g_spawn_sync() and internally calls this function on Unix-like
1553 * systems. On Win32 platforms, it uses the Windows API.
1555 * @param dir The child's current working directory, or @a NULL to inherit parent's.
1556 * @param argv The child's argument vector.
1557 * @param env The child's environment, or @a NULL to inherit parent's.
1558 * @param flags Flags from GSpawnFlags.
1559 * @param child_setup A function to run in the child just before exec().
1560 * @param user_data The user data for child_setup.
1561 * @param std_out The return location for child output.
1562 * @param std_err The return location for child error messages.
1563 * @param exit_status The child exit status, as returned by waitpid().
1564 * @param error The return location for error or @a NULL.
1566 * @return @c TRUE on success, @c FALSE if an error was set.
1568 gboolean utils_spawn_sync(const gchar *dir, gchar **argv, gchar **env, GSpawnFlags flags,
1569 GSpawnChildSetupFunc child_setup, gpointer user_data, gchar **std_out,
1570 gchar **std_err, gint *exit_status, GError **error)
1572 gboolean result;
1574 if (! check_error(error))
1575 return FALSE;
1577 if (argv == NULL)
1579 *error = g_error_new(G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, "argv must not be NULL");
1580 return FALSE;
1583 if (std_out)
1584 *std_out = NULL;
1586 if (std_err)
1587 *std_err = NULL;
1589 #ifdef G_OS_WIN32
1590 result = win32_spawn(dir, argv, env, flags, std_out, std_err, exit_status, error);
1591 #else
1592 result = g_spawn_sync(dir, argv, env, flags, NULL, NULL, std_out, std_err, exit_status, error);
1593 #endif
1595 return result;
1600 * Wraps g_spawn_async() and internally calls this function on Unix-like
1601 * systems. On Win32 platforms, it uses the Windows API.
1603 * @param dir The child's current working directory, or @a NULL to inherit parent's.
1604 * @param argv The child's argument vector.
1605 * @param env The child's environment, or @a NULL to inherit parent's.
1606 * @param flags Flags from GSpawnFlags.
1607 * @param child_setup A function to run in the child just before exec().
1608 * @param user_data The user data for child_setup.
1609 * @param child_pid The return location for child process ID, or NULL.
1610 * @param error The return location for error or @a NULL.
1612 * @return @c TRUE on success, @c FALSE if an error was set.
1614 gboolean utils_spawn_async(const gchar *dir, gchar **argv, gchar **env, GSpawnFlags flags,
1615 GSpawnChildSetupFunc child_setup, gpointer user_data, GPid *child_pid,
1616 GError **error)
1618 gboolean result;
1620 if (! check_error(error))
1621 return FALSE;
1623 if (argv == NULL)
1625 *error = g_error_new(G_SPAWN_ERROR, G_SPAWN_ERROR_FAILED, "argv must not be NULL");
1626 return FALSE;
1629 #ifdef G_OS_WIN32
1630 result = win32_spawn(dir, argv, env, flags, NULL, NULL, NULL, error);
1631 #else
1632 result = g_spawn_async(dir, argv, env, flags, NULL, NULL, child_pid, error);
1633 #endif
1634 return result;
1638 /* Similar to g_build_path() but (re)using a fixed buffer, so never free it.
1639 * This assumes a small enough resulting string length to be kept without freeing,
1640 * but this should be the case for filenames.
1641 * @warning As the buffer is reused, you can't call this recursively, e.g. for a
1642 * function argument and within the function called. */
1643 const gchar *utils_build_path(const gchar *first, ...)
1645 static GString *buffer = NULL;
1646 const gchar *str;
1647 va_list args;
1649 if (! buffer)
1650 buffer = g_string_new(first);
1651 else
1652 g_string_assign(buffer, first);
1654 va_start(args, first);
1655 while (1)
1657 str = va_arg(args, const gchar *);
1658 if (!str)
1659 break;
1661 g_string_append_c(buffer, G_DIR_SEPARATOR);
1662 g_string_append(buffer, str);
1664 va_end(args);
1666 return buffer->str;
1670 /* Retrieves the path for the given URI.
1671 * It returns:
1672 * - the path which was determined by g_filename_from_uri() or GIO
1673 * - NULL if the URI is non-local and gvfs-fuse is not installed
1674 * - a new copy of 'uri' if it is not an URI. */
1675 gchar *utils_get_path_from_uri(const gchar *uri)
1677 gchar *locale_filename;
1679 g_return_val_if_fail(uri != NULL, NULL);
1681 if (! utils_is_uri(uri))
1682 return g_strdup(uri);
1684 /* this will work only for 'file://' URIs */
1685 locale_filename = g_filename_from_uri(uri, NULL, NULL);
1686 #ifdef HAVE_GIO
1687 /* g_filename_from_uri() failed, so we probably have a non-local URI */
1688 if (locale_filename == NULL)
1690 GFile *file = g_file_new_for_uri(uri);
1691 locale_filename = g_file_get_path(file);
1692 g_object_unref(file);
1693 if (locale_filename == NULL)
1695 geany_debug("The URI '%s' could not be resolved to a local path. This means "
1696 "that the URI is invalid or that you don't have gvfs-fuse installed.", uri);
1697 return NULL;
1700 #endif
1701 if (locale_filename == NULL)
1702 geany_debug("The URI '%s' could not be resolved to a local path. This means that the "
1703 "URI is invalid or that Geany can't use GVFS (maybe it is not installed).", uri);
1705 return locale_filename;
1709 gboolean utils_is_uri(const gchar *uri)
1711 g_return_val_if_fail(uri != NULL, FALSE);
1713 return (strstr(uri, "://") != NULL);
1717 /* path should be in locale encoding */
1718 gboolean utils_is_remote_path(const gchar *path)
1720 g_return_val_if_fail(path != NULL, FALSE);
1722 /* if path is an URI and it doesn't start "file://", we take it as remote */
1723 if (utils_is_uri(path) && strncmp(path, "file:", 5) != 0)
1724 return TRUE;
1726 #ifndef G_OS_WIN32
1727 if (glib_check_version(2, 16, 0) == NULL) /* no need to check for this with GLib < 2.16 */
1729 static gchar *fuse_path = NULL;
1730 static gsize len = 0;
1732 if (G_UNLIKELY(fuse_path == NULL))
1734 fuse_path = g_build_filename(g_get_home_dir(), ".gvfs", NULL);
1735 len = strlen(fuse_path);
1737 /* Comparing the file path against a hardcoded path is not the most elegant solution
1738 * but for now it is better than nothing. Ideally, g_file_new_for_path() should create
1739 * proper GFile objects for Fuse paths, but it only does in future GVFS
1740 * versions (gvfs 1.1.1). */
1741 return (strncmp(path, fuse_path, len) == 0);
1743 #endif
1744 return FALSE;
1748 /* Remove all relative and untidy elements from the path of @a filename.
1749 * @param filename must be a valid absolute path.
1750 * @see tm_get_real_path() - also resolves links. */
1751 void utils_tidy_path(gchar *filename)
1753 GString *str = g_string_new(filename);
1754 const gchar *c, *needle;
1755 gchar *tmp;
1756 gssize pos;
1757 gboolean preserve_double_backslash = FALSE;
1759 g_return_if_fail(g_path_is_absolute(filename));
1761 if (str->len >= 2 && strncmp(str->str, "\\\\", 2) == 0)
1762 preserve_double_backslash = TRUE;
1764 /* replace "/./" and "//" */
1765 utils_string_replace_all(str, G_DIR_SEPARATOR_S "." G_DIR_SEPARATOR_S, G_DIR_SEPARATOR_S);
1766 utils_string_replace_all(str, G_DIR_SEPARATOR_S G_DIR_SEPARATOR_S, G_DIR_SEPARATOR_S);
1768 if (preserve_double_backslash)
1769 g_string_prepend(str, "\\");
1771 /* replace "/../" */
1772 needle = G_DIR_SEPARATOR_S ".." G_DIR_SEPARATOR_S;
1773 while (1)
1775 c = strstr(str->str, needle);
1776 if (c == NULL)
1777 break;
1778 else
1780 pos = c - str->str;
1781 if (pos <= 3)
1782 break; /* bad path */
1784 /* replace "/../" */
1785 g_string_erase(str, pos, strlen(needle));
1786 g_string_insert_c(str, pos, G_DIR_SEPARATOR);
1788 tmp = g_strndup(str->str, pos); /* path up to "/../" */
1789 c = g_strrstr(tmp, G_DIR_SEPARATOR_S);
1790 g_return_if_fail(c);
1792 pos = c - tmp; /* position of previous "/" */
1793 g_string_erase(str, pos, strlen(c));
1794 g_free(tmp);
1797 g_return_if_fail(strlen(str->str) <= strlen(filename));
1798 strcpy(filename, str->str);
1799 g_string_free(str, TRUE);
1804 * Removes characters from a string, in place.
1806 * @param string String to search.
1807 * @param chars Characters to remove.
1809 * @return @a string - return value is only useful when nesting function calls, e.g.:
1810 * @code str = utils_str_remove_chars(g_strdup("f_o_o"), "_"); @endcode
1812 * @see @c g_strdelimit.
1814 gchar *utils_str_remove_chars(gchar *string, const gchar *chars)
1816 const gchar *r;
1817 gchar *w = string;
1819 g_return_val_if_fail(string, NULL);
1820 if (!NZV(chars))
1821 return string;
1823 foreach_str(r, string)
1825 if (!strchr(chars, *r))
1826 *w++ = *r;
1828 *w = 0x0;
1829 return string;
1833 static void utils_slist_remove_next(GSList *node)
1835 GSList *old = node->next;
1837 g_return_if_fail(old);
1839 node->next = old->next;
1840 g_slist_free_1(old);
1844 /* Gets list of sorted filenames with no path and no duplicates from user and system config */
1845 GSList *utils_get_config_files(const gchar *subdir)
1847 gchar *path = g_build_path(G_DIR_SEPARATOR_S, app->configdir, subdir, NULL);
1848 GSList *list = utils_get_file_list_full(path, FALSE, FALSE, NULL);
1849 GSList *syslist, *node;
1851 if (!list)
1853 utils_mkdir(path, FALSE);
1855 setptr(path, g_build_path(G_DIR_SEPARATOR_S, app->datadir, subdir, NULL));
1856 syslist = utils_get_file_list_full(path, FALSE, FALSE, NULL);
1857 /* merge lists */
1858 list = g_slist_concat(list, syslist);
1860 list = g_slist_sort(list, (GCompareFunc) utils_str_casecmp);
1861 /* remove duplicates (next to each other after sorting) */
1862 foreach_slist(node, list)
1864 if (node->next && utils_str_equal(node->next->data, node->data))
1866 g_free(node->next->data);
1867 utils_slist_remove_next(node);
1870 g_free(path);
1871 return list;
1875 /* Suffix can be NULL or a string which should be appended to the Help URL like
1876 * an anchor link, e.g. "#some_anchor". */
1877 gchar *utils_get_help_url(const gchar *suffix)
1879 gint skip;
1880 gchar *uri;
1882 #ifdef G_OS_WIN32
1883 skip = 8;
1884 uri = g_strconcat("file:///", app->docdir, "/Manual.html", NULL);
1885 g_strdelimit(uri, "\\", '/'); /* replace '\\' by '/' */
1886 #else
1887 skip = 7;
1888 uri = g_strconcat("file://", app->docdir, "index.html", NULL);
1889 #endif
1891 if (! g_file_test(uri + skip, G_FILE_TEST_IS_REGULAR))
1892 { /* fall back to online documentation if it is not found on the hard disk */
1893 g_free(uri);
1894 uri = g_strconcat(GEANY_HOMEPAGE, "manual/", VERSION, "/index.html", NULL);
1897 if (suffix != NULL)
1899 setptr(uri, g_strconcat(uri, suffix, NULL));
1902 return uri;
1906 static gboolean str_in_array(const gchar **haystack, const gchar *needle)
1908 const gchar **p;
1910 for (p = haystack; *p != NULL; ++p)
1912 if (utils_str_equal(*p, needle))
1913 return TRUE;
1915 return FALSE;
1920 * Copies the current environment into a new array.
1921 * @a exclude_vars is a @c NULL-terminated array of variable names which should be not copied.
1922 * All further arguments are key, value pairs of variables which should be added to
1923 * the environment.
1925 * The argument list must be @c NULL-terminated.
1927 * @param exclude_vars @c NULL-terminated array of variable names to exclude.
1928 * @param first_varname Name of the first variable to copy into the new array.
1929 * @param ... Key-value pairs of variable names and values, @c NULL-terminated.
1931 * @return The new environment array.
1933 gchar **utils_copy_environment(const gchar **exclude_vars, const gchar *first_varname, ...)
1935 gchar **result;
1936 gchar **p;
1937 gchar **env;
1938 va_list args;
1939 const gchar *key, *value;
1940 guint n, o;
1942 /* get all the environ variables */
1943 env = g_listenv();
1945 /* count the additional variables */
1946 va_start(args, first_varname);
1947 for (o = 1; va_arg(args, gchar*) != NULL; o++);
1948 va_end(args);
1949 /* the passed arguments should be even (key, value pairs) */
1950 g_return_val_if_fail(o % 2 == 0, NULL);
1952 o /= 2;
1954 /* create an array large enough to hold the new environment */
1955 n = g_strv_length(env);
1956 /* 'n + o + 1' could leak a little bit when exclude_vars is set */
1957 result = g_new(gchar *, n + o + 1);
1959 /* copy the environment */
1960 for (n = 0, p = env; *p != NULL; ++p)
1962 /* copy the variable */
1963 value = g_getenv(*p);
1964 if (G_LIKELY(value != NULL))
1966 /* skip excluded variables */
1967 if (exclude_vars != NULL && str_in_array(exclude_vars, *p))
1968 continue;
1970 result[n++] = g_strconcat(*p, "=", value, NULL);
1973 g_strfreev(env);
1975 /* now add additional variables */
1976 va_start(args, first_varname);
1977 key = first_varname;
1978 value = va_arg(args, gchar*);
1979 while (key != NULL)
1981 result[n++] = g_strconcat(key, "=", value, NULL);
1983 key = va_arg(args, gchar*);
1984 if (key == NULL)
1985 break;
1986 value = va_arg(args, gchar*);
1988 va_end(args);
1990 result[n] = NULL;
1992 return result;