/
utils.c
2240 lines (1883 loc) · 54.6 KB
/
utils.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* utils.c - this file is part of Geany, a fast and lightweight IDE
*
* Copyright 2005-2012 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
* Copyright 2006-2012 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
/*
* General utility functions, non-GTK related.
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
#include "utils.h"
#include "app.h"
#include "dialogs.h"
#include "document.h"
#include "keyfile.h"
#include "main.h"
#include "prefs.h"
#include "prefix.h"
#include "sciwrappers.h"
#include "spawn.h"
#include "support.h"
#include "templates.h"
#include "ui_utils.h"
#include "win32.h"
#include "osx.h"
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdarg.h>
#ifdef HAVE_SYS_STAT_H
# include <sys/stat.h>
#endif
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#include <glib/gstdio.h>
#include <gio/gio.h>
/**
* Tries to open the given URI in a browser.
* On Windows, the system's default browser is opened.
* On non-Windows systems, the browser command set in the preferences dialog is used. In case
* that fails or it is unset, the user is asked to correct or fill it.
*
* @param uri The URI to open in the web browser.
*
* @since 0.16
**/
GEANY_API_SYMBOL
void utils_open_browser(const gchar *uri)
{
#ifdef G_OS_WIN32
g_return_if_fail(uri != NULL);
win32_open_browser(uri);
#else
gchar *argv[2] = { (gchar *) uri, NULL };
g_return_if_fail(uri != NULL);
while (!spawn_async(NULL, tool_prefs.browser_cmd, argv, NULL, NULL, NULL))
{
gchar *new_cmd = dialogs_show_input(_("Select Browser"), GTK_WINDOW(main_widgets.window),
_("Failed to spawn the configured browser command. "
"Please correct it or enter another one."),
tool_prefs.browser_cmd);
if (new_cmd == NULL) /* user canceled */
break;
SETPTR(tool_prefs.browser_cmd, new_cmd);
}
#endif
}
/* taken from anjuta, to determine the EOL mode of the file */
gint utils_get_line_endings(const gchar* buffer, gsize size)
{
gsize i;
guint cr, lf, crlf, max_mode;
gint mode;
cr = lf = crlf = 0;
for (i = 0; i < size ; i++)
{
if (buffer[i] == 0x0a)
{
/* LF */
lf++;
}
else if (buffer[i] == 0x0d)
{
if (i >= (size - 1))
{
/* Last char, CR */
cr++;
}
else
{
if (buffer[i + 1] != 0x0a)
{
/* CR */
cr++;
}
else
{
/* CRLF */
crlf++;
}
i++;
}
}
}
/* Vote for the maximum */
mode = SC_EOL_LF;
max_mode = lf;
if (crlf > max_mode)
{
mode = SC_EOL_CRLF;
max_mode = crlf;
}
if (cr > max_mode)
{
mode = SC_EOL_CR;
max_mode = cr;
}
return mode;
}
gboolean utils_isbrace(gchar c, gboolean include_angles)
{
switch (c)
{
case '<':
case '>':
return include_angles;
case '(':
case ')':
case '{':
case '}':
case '[':
case ']': return TRUE;
default: return FALSE;
}
}
gboolean utils_is_opening_brace(gchar c, gboolean include_angles)
{
switch (c)
{
case '<':
return include_angles;
case '(':
case '{':
case '[': return TRUE;
default: return FALSE;
}
}
/**
* Writes @a text into a file named @a filename.
* If the file doesn't exist, it will be created.
* If it already exists, it will be overwritten.
*
* @warning You should use @c g_file_set_contents() instead if you don't need
* file permissions and other metadata to be preserved, as that always handles
* disk exhaustion safely.
*
* @param filename The filename of the file to write, in locale encoding.
* @param text The text to write into the file.
*
* @return 0 if the file was successfully written, otherwise the @c errno of the
* failed operation is returned.
**/
GEANY_API_SYMBOL
gint utils_write_file(const gchar *filename, const gchar *text)
{
g_return_val_if_fail(filename != NULL, ENOENT);
g_return_val_if_fail(text != NULL, EINVAL);
if (file_prefs.use_safe_file_saving)
{
GError *error = NULL;
if (! g_file_set_contents(filename, text, -1, &error))
{
geany_debug("%s: could not write to file %s (%s)", G_STRFUNC, filename, error->message);
g_error_free(error);
return EIO;
}
}
else
{
FILE *fp;
gsize bytes_written, len;
gboolean fail = FALSE;
if (filename == NULL)
return ENOENT;
len = strlen(text);
errno = 0;
fp = g_fopen(filename, "w");
if (fp == NULL)
fail = TRUE;
else
{
bytes_written = fwrite(text, sizeof(gchar), len, fp);
if (len != bytes_written)
{
fail = TRUE;
geany_debug(
"utils_write_file(): written only %"G_GSIZE_FORMAT" bytes, had to write %"G_GSIZE_FORMAT" bytes to %s",
bytes_written, len, filename);
}
if (fclose(fp) != 0)
fail = TRUE;
}
if (fail)
{
geany_debug("utils_write_file(): could not write to file %s (%s)",
filename, g_strerror(errno));
return FALLBACK(errno, EIO);
}
}
return 0;
}
/** Searches backward through @a size bytes looking for a '<'.
* @param sel .
* @param size .
* @return The tag name (newly allocated) or @c NULL if no opening tag was found.
*/
GEANY_API_SYMBOL
gchar *utils_find_open_xml_tag(const gchar sel[], gint size)
{
const gchar *cur, *begin;
gsize len;
cur = utils_find_open_xml_tag_pos(sel, size);
if (cur == NULL)
return NULL;
cur++; /* skip the bracket */
begin = cur;
while (strchr(":_-.", *cur) || isalnum(*cur))
cur++;
len = (gsize)(cur - begin);
return len ? g_strndup(begin, len) : NULL;
}
/** Searches backward through @a size bytes looking for a '<'.
* @param sel .
* @param size .
* @return pointer to '<' of the found opening tag within @a sel, or @c NULL if no opening tag was found.
*/
GEANY_API_SYMBOL
const gchar *utils_find_open_xml_tag_pos(const gchar sel[], gint size)
{
/* stolen from anjuta and modified */
const gchar *begin, *cur;
if (G_UNLIKELY(size < 3))
{ /* Smallest tag is "<p>" which is 3 characters */
return NULL;
}
begin = &sel[0];
cur = &sel[size - 1];
/* Skip to the character before the closing brace */
while (cur > begin)
{
if (*cur == '>')
break;
--cur;
}
--cur;
/* skip whitespace */
while (cur > begin && isspace(*cur))
cur--;
if (*cur == '/')
return NULL; /* we found a short tag which doesn't need to be closed */
while (cur > begin)
{
if (*cur == '<')
break;
/* exit immediately if such non-valid XML/HTML is detected, e.g. "<script>if a >" */
else if (*cur == '>')
break;
--cur;
}
/* if the found tag is an opening, not a closing tag or empty <> */
if (*cur == '<' && *(cur + 1) != '/' && *(cur + 1) != '>')
return cur;
return NULL;
}
/* Returns true if tag_name is a self-closing tag */
gboolean utils_is_short_html_tag(const gchar *tag_name)
{
const gchar names[][20] = {
"area",
"base",
"basefont", /* < or not < */
"br",
"col",
"command",
"embed",
"frame",
"hr",
"img",
"input",
"keygen",
"link",
"meta",
"param",
"source",
"track",
"wbr"
};
if (tag_name)
{
if (bsearch(tag_name, names, G_N_ELEMENTS(names), 20,
(GCompareFunc)g_ascii_strcasecmp))
return TRUE;
}
return FALSE;
}
const gchar *utils_get_eol_name(gint eol_mode)
{
switch (eol_mode)
{
case SC_EOL_CRLF: return _("Windows (CRLF)"); break;
case SC_EOL_CR: return _("Classic Mac (CR)"); break;
default: return _("Unix (LF)"); break;
}
}
const gchar *utils_get_eol_short_name(gint eol_mode)
{
switch (eol_mode)
{
case SC_EOL_CRLF: return _("CRLF"); break;
case SC_EOL_CR: return _("CR"); break;
default: return _("LF"); break;
}
}
const gchar *utils_get_eol_char(gint eol_mode)
{
switch (eol_mode)
{
case SC_EOL_CRLF: return "\r\n"; break;
case SC_EOL_CR: return "\r"; break;
default: return "\n"; break;
}
}
/* Converts line endings to @a target_eol_mode. */
void utils_ensure_same_eol_characters(GString *string, gint target_eol_mode)
{
const gchar *eol_str = utils_get_eol_char(target_eol_mode);
/* first convert data to LF only */
utils_string_replace_all(string, "\r\n", "\n");
utils_string_replace_all(string, "\r", "\n");
if (target_eol_mode == SC_EOL_LF)
return;
/* now convert to desired line endings */
utils_string_replace_all(string, "\n", eol_str);
}
gboolean utils_atob(const gchar *str)
{
if (G_UNLIKELY(str == NULL))
return FALSE;
else if (strcmp(str, "TRUE") == 0 || strcmp(str, "true") == 0)
return TRUE;
return FALSE;
}
/* NULL-safe version of g_path_is_absolute(). */
gboolean utils_is_absolute_path(const gchar *path)
{
if (G_UNLIKELY(EMPTY(path)))
return FALSE;
return g_path_is_absolute(path);
}
/* Skips root if path is absolute, do nothing otherwise.
* This is a relative-safe version of g_path_skip_root().
*/
const gchar *utils_path_skip_root(const gchar *path)
{
const gchar *path_relative;
path_relative = g_path_skip_root(path);
return (path_relative != NULL) ? path_relative : path;
}
gdouble utils_scale_round(gdouble val, gdouble factor)
{
/*val = floor(val * factor + 0.5);*/
val = floor(val);
val = MAX(val, 0);
val = MIN(val, factor);
return val;
}
/* like g_utf8_strdown() but if @str is not valid UTF8, convert it from locale first.
* returns NULL on charset conversion failure */
static gchar *utf8_strdown(const gchar *str)
{
gchar *down;
if (g_utf8_validate(str, -1, NULL))
down = g_utf8_strdown(str, -1);
else
{
down = g_locale_to_utf8(str, -1, NULL, NULL, NULL);
if (down)
SETPTR(down, g_utf8_strdown(down, -1));
}
return down;
}
/**
* A replacement function for g_strncasecmp() to compare strings case-insensitive.
* It converts both strings into lowercase using g_utf8_strdown() and then compare
* both strings using strcmp().
* This is not completely accurate regarding locale-specific case sorting rules
* but seems to be a good compromise between correctness and performance.
*
* The input strings should be in UTF-8 or locale encoding.
*
* @param s1 Pointer to first string or @c NULL.
* @param s2 Pointer to second string or @c NULL.
*
* @return an integer less than, equal to, or greater than zero if @a s1 is found, respectively,
* to be less than, to match, or to be greater than @a s2.
*
* @since 0.16
*/
GEANY_API_SYMBOL
gint utils_str_casecmp(const gchar *s1, const gchar *s2)
{
gchar *tmp1, *tmp2;
gint result;
g_return_val_if_fail(s1 != NULL, 1);
g_return_val_if_fail(s2 != NULL, -1);
/* ensure strings are UTF-8 and lowercase */
tmp1 = utf8_strdown(s1);
if (! tmp1)
return 1;
tmp2 = utf8_strdown(s2);
if (! tmp2)
{
g_free(tmp1);
return -1;
}
/* compare */
result = strcmp(tmp1, tmp2);
g_free(tmp1);
g_free(tmp2);
return result;
}
/**
* Truncates the input string to a given length.
* Characters are removed from the middle of the string, so the start and the end of string
* won't change.
*
* @param string Input string.
* @param truncate_length The length in characters of the resulting string.
*
* @return A copy of @a string which is truncated to @a truncate_length characters,
* should be freed when no longer needed.
*
* @since 0.17
*/
/* This following function is taken from Gedit. */
GEANY_API_SYMBOL
gchar *utils_str_middle_truncate(const gchar *string, guint truncate_length)
{
GString *truncated;
guint length;
guint n_chars;
guint num_left_chars;
guint right_offset;
guint delimiter_length;
const gchar *delimiter = "\342\200\246";
g_return_val_if_fail(string != NULL, NULL);
length = strlen(string);
g_return_val_if_fail(g_utf8_validate(string, length, NULL), NULL);
/* It doesn't make sense to truncate strings to less than the size of the delimiter plus 2
* characters (one on each side) */
delimiter_length = g_utf8_strlen(delimiter, -1);
if (truncate_length < (delimiter_length + 2))
return g_strdup(string);
n_chars = g_utf8_strlen(string, length);
/* Make sure the string is not already small enough. */
if (n_chars <= truncate_length)
return g_strdup (string);
/* Find the 'middle' where the truncation will occur. */
num_left_chars = (truncate_length - delimiter_length) / 2;
right_offset = n_chars - truncate_length + num_left_chars + delimiter_length;
truncated = g_string_new_len(string, g_utf8_offset_to_pointer(string, num_left_chars) - string);
g_string_append(truncated, delimiter);
g_string_append(truncated, g_utf8_offset_to_pointer(string, right_offset));
return g_string_free(truncated, FALSE);
}
/**
* @c NULL-safe string comparison. Returns @c TRUE if both @a a and @a b are @c NULL
* or if @a a and @a b refer to valid strings which are equal.
*
* @param a Pointer to first string or @c NULL.
* @param b Pointer to second string or @c NULL.
*
* @return @c TRUE if @a a equals @a b, else @c FALSE.
**/
GEANY_API_SYMBOL
gboolean utils_str_equal(const gchar *a, const gchar *b)
{
/* (taken from libexo from os-cillation) */
if (a == NULL && b == NULL) return TRUE;
else if (a == NULL || b == NULL) return FALSE;
return strcmp(a, b) == 0;
}
/**
* Removes the extension from @a filename and return the result in a newly allocated string.
*
* @param filename The filename to operate on.
*
* @return A newly-allocated string, should be freed when no longer needed.
**/
GEANY_API_SYMBOL
gchar *utils_remove_ext_from_filename(const gchar *filename)
{
gchar *last_dot;
gchar *result;
gsize len;
g_return_val_if_fail(filename != NULL, NULL);
last_dot = strrchr(filename, '.');
if (! last_dot)
return g_strdup(filename);
len = (gsize) (last_dot - filename);
result = g_malloc(len + 1);
memcpy(result, filename, len);
result[len] = 0;
return result;
}
gchar utils_brace_opposite(gchar ch)
{
switch (ch)
{
case '(': return ')';
case ')': return '(';
case '[': return ']';
case ']': return '[';
case '{': return '}';
case '}': return '{';
case '<': return '>';
case '>': return '<';
default: return '\0';
}
}
/* Checks whether the given file can be written. locale_filename is expected in locale encoding.
* Returns 0 if it can be written, otherwise it returns errno */
gint utils_is_file_writable(const gchar *locale_filename)
{
gchar *file;
gint ret;
if (! g_file_test(locale_filename, G_FILE_TEST_EXISTS) &&
! g_file_test(locale_filename, G_FILE_TEST_IS_DIR))
/* get the file's directory to check for write permission if it doesn't yet exist */
file = g_path_get_dirname(locale_filename);
else
file = g_strdup(locale_filename);
#ifdef G_OS_WIN32
/* use _waccess on Windows, access() doesn't accept special characters */
ret = win32_check_write_permission(file);
#else
/* access set also errno to "FILE NOT FOUND" even if locale_filename is writeable, so use
* errno only when access() explicitly returns an error */
if (access(file, R_OK | W_OK) != 0)
ret = errno;
else
ret = 0;
#endif
g_free(file);
return ret;
}
/* Replaces all occurrences of needle in haystack with replacement.
* Warning: *haystack must be a heap address; it may be freed and reassigned.
* Note: utils_string_replace_all() will always be faster when @a replacement is longer
* than @a needle.
* All strings have to be NULL-terminated.
* See utils_string_replace_all() for details. */
void utils_str_replace_all(gchar **haystack, const gchar *needle, const gchar *replacement)
{
GString *str;
g_return_if_fail(*haystack != NULL);
str = g_string_new(*haystack);
g_free(*haystack);
utils_string_replace_all(str, needle, replacement);
*haystack = g_string_free(str, FALSE);
}
gint utils_strpos(const gchar *haystack, const gchar *needle)
{
const gchar *sub;
if (! *needle)
return -1;
sub = strstr(haystack, needle);
if (! sub)
return -1;
return sub - haystack;
}
/**
* Retrieves a formatted date/time string from strftime().
* This function should be preferred to directly calling strftime() since this function
* works on UTF-8 encoded strings.
*
* @param format The format string to pass to strftime(3). See the strftime(3)
* documentation for details, in UTF-8 encoding.
* @param time_to_use The date/time to use, in time_t format or NULL to use the current time.
*
* @return A newly-allocated string, should be freed when no longer needed.
*
* @since 0.16
*/
GEANY_API_SYMBOL
gchar *utils_get_date_time(const gchar *format, time_t *time_to_use)
{
const struct tm *tm;
static gchar date[1024];
gchar *locale_format;
gsize len;
g_return_val_if_fail(format != NULL, NULL);
if (! g_utf8_validate(format, -1, NULL))
{
locale_format = g_locale_from_utf8(format, -1, NULL, NULL, NULL);
if (locale_format == NULL)
return NULL;
}
else
locale_format = g_strdup(format);
if (time_to_use != NULL)
tm = localtime(time_to_use);
else
{
time_t tp = time(NULL);
tm = localtime(&tp);
}
len = strftime(date, 1024, locale_format, tm);
g_free(locale_format);
if (len == 0)
return NULL;
if (! g_utf8_validate(date, len, NULL))
return g_locale_to_utf8(date, len, NULL, NULL, NULL);
else
return g_strdup(date);
}
gchar *utils_get_initials(const gchar *name)
{
gint i = 1, j = 1;
gchar *initials = g_malloc0(5);
initials[0] = name[0];
while (name[i] != '\0' && j < 4)
{
if (name[i] == ' ' && name[i + 1] != ' ')
{
initials[j++] = name[i + 1];
}
i++;
}
return initials;
}
/**
* Wraps g_key_file_get_integer() to add a default value argument.
*
* @param config A GKeyFile object.
* @param section The group name to look in for the key.
* @param key The key to find.
* @param default_value The default value which will be returned when @a section or @a key
* don't exist.
*
* @return The value associated with @a key as an integer, or the given default value if the value
* could not be retrieved.
**/
GEANY_API_SYMBOL
gint utils_get_setting_integer(GKeyFile *config, const gchar *section, const gchar *key,
const gint default_value)
{
gint tmp;
GError *error = NULL;
g_return_val_if_fail(config, default_value);
tmp = g_key_file_get_integer(config, section, key, &error);
if (error)
{
g_error_free(error);
return default_value;
}
return tmp;
}
/**
* Wraps g_key_file_get_boolean() to add a default value argument.
*
* @param config A GKeyFile object.
* @param section The group name to look in for the key.
* @param key The key to find.
* @param default_value The default value which will be returned when @c section or @c key
* don't exist.
*
* @return The value associated with @a key as a boolean, or the given default value if the value
* could not be retrieved.
**/
GEANY_API_SYMBOL
gboolean utils_get_setting_boolean(GKeyFile *config, const gchar *section, const gchar *key,
const gboolean default_value)
{
gboolean tmp;
GError *error = NULL;
g_return_val_if_fail(config, default_value);
tmp = g_key_file_get_boolean(config, section, key, &error);
if (error)
{
g_error_free(error);
return default_value;
}
return tmp;
}
/**
* Wraps g_key_file_get_string() to add a default value argument.
*
* @param config A GKeyFile object.
* @param section The group name to look in for the key.
* @param key The key to find.
* @param default_value The default value which will be returned when @a section or @a key
* don't exist.
*
* @return A newly allocated string, either the value for @a key or a copy of the given
* default value if it could not be retrieved.
**/
GEANY_API_SYMBOL
gchar *utils_get_setting_string(GKeyFile *config, const gchar *section, const gchar *key,
const gchar *default_value)
{
gchar *tmp;
g_return_val_if_fail(config, g_strdup(default_value));
tmp = g_key_file_get_string(config, section, key, NULL);
if (!tmp)
{
return g_strdup(default_value);
}
return tmp;
}
gchar *utils_get_hex_from_color(GdkColor *color)
{
g_return_val_if_fail(color != NULL, NULL);
return g_strdup_printf("#%02X%02X%02X",
(guint) (utils_scale_round(color->red / 256, 255)),
(guint) (utils_scale_round(color->green / 256, 255)),
(guint) (utils_scale_round(color->blue / 256, 255)));
}
/* Get directory from current file in the notebook.
* Returns dir string that should be freed or NULL, depending on whether current file is valid.
* Returned string is in UTF-8 encoding */
gchar *utils_get_current_file_dir_utf8(void)
{
GeanyDocument *doc = document_get_current();
if (doc != NULL)
{
/* get current filename */
const gchar *cur_fname = doc->file_name;
if (cur_fname != NULL)
{
/* get folder part from current filename */
return g_path_get_dirname(cur_fname); /* returns "." if no path */
}
}
return NULL; /* no file open */
}
/* very simple convenience function */
void utils_beep(void)
{
if (prefs.beep_on_errors)
gdk_beep();
}
/* taken from busybox, thanks */
gchar *utils_make_human_readable_str(guint64 size, gulong block_size,
gulong display_unit)
{
/* The code will adjust for additional (appended) units. */
static const gchar zero_and_units[] = { '0', 0, 'K', 'M', 'G', 'T' };
static const gchar fmt[] = "%Lu %c%c";
static const gchar fmt_tenths[] = "%Lu.%d %c%c";
guint64 val;
gint frac;
const gchar *u;
const gchar *f;
u = zero_and_units;
f = fmt;
frac = 0;
val = size * block_size;
if (val == 0)
return g_strdup(u);
if (display_unit)
{
val += display_unit/2; /* Deal with rounding. */
val /= display_unit; /* Don't combine with the line above!!! */
}
else
{
++u;
while ((val >= 1024) && (u < zero_and_units + sizeof(zero_and_units) - 1))
{
f = fmt_tenths;
++u;
frac = ((((gint)(val % 1024)) * 10) + (1024 / 2)) / 1024;
val /= 1024;
}
if (frac >= 10)
{ /* We need to round up here. */
++val;
frac = 0;
}
}
/* If f==fmt then 'frac' and 'u' are ignored. */
return g_strdup_printf(f, val, frac, *u, 'b');
}
/* converts a color representation using gdk_color_parse(), with additional
* support of the "0x" prefix as a synonym for "#" */
gboolean utils_parse_color(const gchar *spec, GdkColor *color)
{
gchar buf[64] = {0};
g_return_val_if_fail(spec != NULL, -1);
if (spec[0] == '0' && (spec[1] == 'x' || spec[1] == 'X'))
{
/* convert to # format for GDK to understand it */
buf[0] = '#';
strncpy(buf + 1, spec + 2, sizeof(buf) - 2);
spec = buf;
}
return gdk_color_parse(spec, color);
}
/* converts a GdkColor to the packed 24 bits BGR format, as understood by Scintilla
* returns a 24 bits BGR color, or -1 on failure */
gint utils_color_to_bgr(const GdkColor *c)
{
g_return_val_if_fail(c != NULL, -1);
return (c->red / 256) | ((c->green / 256) << 8) | ((c->blue / 256) << 16);
}