clang-tidy: readability-inconsistent-declaration-parameter-name
[geeqie.git] / src / misc.cc
1 /*
2  * Copyright (C) 2008 - 2016 The Geeqie Team
3  *
4  * Authors: Vladimir Nadvornik, Laurent Monin
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19  */
20
21 #include <clocale>
22 #include <memory>
23
24 #include "main.h"
25 #include "misc.h"
26
27 #include "filedata.h"
28 #include "ui-fileops.h"
29
30 #include <langinfo.h>
31
32 gdouble get_zoom_increment()
33 {
34         return ((options->image.zoom_increment != 0) ? static_cast<gdouble>(options->image.zoom_increment) / 100.0 : 1.0);
35 }
36
37 gchar *utf8_validate_or_convert(const gchar *text)
38 {
39         gint len;
40
41         if (!text) return nullptr;
42
43         len = strlen(text);
44         if (!g_utf8_validate(text, len, nullptr))
45                 return g_convert(text, len, "UTF-8", "ISO-8859-1", nullptr, nullptr, nullptr);
46
47         return g_strdup(text);
48 }
49
50 gint utf8_compare(const gchar *s1, const gchar *s2, gboolean case_sensitive)
51 {
52         gchar *s1_key, *s2_key;
53         gchar *s1_t, *s2_t;
54         gint ret;
55
56         g_assert(g_utf8_validate(s1, -1, nullptr));
57         g_assert(g_utf8_validate(s2, -1, nullptr));
58
59         if (!case_sensitive)
60                 {
61                 s1_t = g_utf8_casefold(s1, -1);
62                 s2_t = g_utf8_casefold(s2, -1);
63                 }
64         else
65                 {
66                 s1_t = const_cast<gchar *>(s1);
67                 s2_t = const_cast<gchar *>(s2);
68                 }
69
70         s1_key = g_utf8_collate_key(s1_t, -1);
71         s2_key = g_utf8_collate_key(s2_t, -1);
72
73         ret = strcmp(s1_key, s2_key);
74
75         g_free(s1_key);
76         g_free(s2_key);
77
78         if (!case_sensitive)
79                 {
80                 g_free(s1_t);
81                 g_free(s2_t);
82                 }
83
84         return ret;
85 }
86
87 /* Borrowed from gtkfilesystemunix.c */
88 gchar *expand_tilde(const gchar *filename)
89 {
90 #ifndef G_OS_UNIX
91         return g_strdup(filename);
92 #else
93         const gchar *notilde;
94         const gchar *slash;
95         const gchar *home;
96
97         if (filename[0] != '~')
98                 return g_strdup(filename);
99
100         notilde = filename + 1;
101         slash = strchr(notilde, G_DIR_SEPARATOR);
102         if (slash == notilde || !*notilde)
103                 {
104                 home = g_get_home_dir();
105                 if (!home)
106                         return g_strdup(filename);
107                 }
108         else
109                 {
110                 gchar *username;
111                 struct passwd *passwd;
112
113                 if (slash)
114                         username = g_strndup(notilde, slash - notilde);
115                 else
116                         username = g_strdup(notilde);
117
118                 passwd = getpwnam(username);
119                 g_free(username);
120
121                 if (!passwd)
122                         return g_strdup(filename);
123
124                 home = passwd->pw_dir;
125                 }
126
127         if (slash)
128                 return g_build_filename(home, G_DIR_SEPARATOR_S, slash + 1, NULL);
129
130         return g_build_filename(home, G_DIR_SEPARATOR_S, NULL);
131 #endif
132 }
133
134 /* Search for latitude/longitude parameters in a string
135  */
136
137 #define GEOCODE_NAME "geocode-parameters.awk"
138 #define BUFSIZE 128
139
140 gchar *decode_geo_script(const gchar *path_dir, const gchar *input_text)
141 {
142         std::unique_ptr<gchar, decltype(&g_free)> message{nullptr, g_free};
143         gchar *path = g_build_filename(path_dir, GEOCODE_NAME, NULL);
144         gchar *cmd = g_strconcat("echo \'", input_text, "\'  | awk -f ", path, NULL);
145
146         if (g_file_test(path, G_FILE_TEST_EXISTS))
147                 {
148                 gchar buf[BUFSIZE];
149                 FILE *fp;
150
151                 if ((fp = popen(cmd, "r")) == nullptr)
152                         {
153                         message.reset(g_strconcat("Error: opening pipe\n", input_text, NULL));
154                         }
155                 else
156                         {
157                         while (fgets(buf, BUFSIZE, fp))
158                                 {
159                                 DEBUG_1("Output: %s", buf);
160                                 }
161
162                         message.reset(g_strconcat(buf, NULL));
163
164                         if(pclose(fp))
165                                 {
166                                 message.reset(g_strconcat("Error: Command not found or exited with error status\n", input_text, NULL));
167                                 }
168                         }
169                 }
170         else
171                 {
172                 message.reset(g_strconcat(input_text, NULL));
173                 }
174
175         g_free(path);
176         g_free(cmd);
177         return message.release();
178 }
179
180 gchar *decode_geo_parameters(const gchar *input_text)
181 {
182         gchar *message;
183         gchar *dir;
184
185         message = decode_geo_script(gq_bindir, input_text);
186         if (strstr(message, "Error"))
187                 {
188                 g_free(message);
189                 dir = g_build_filename(get_rc_dir(), "applications", NULL);
190                 message = decode_geo_script(dir, input_text);
191                 g_free(dir);
192                 }
193
194         return message;
195 }
196
197 /* Run a command like system() but may output debug messages. */
198 int runcmd(const gchar *cmd)
199 {
200 #if 1
201         return system(cmd);
202         return 0;
203 #else
204         /* For debugging purposes */
205         int retval = -1;
206         FILE *in;
207
208         DEBUG_1("Running command: %s", cmd);
209
210         in = popen(cmd, "r");
211         if (in)
212                 {
213                 int status;
214                 const gchar *msg;
215                 gchar buf[2048];
216
217                 while (fgets(buf, sizeof(buf), in) != NULL )
218                         {
219                         DEBUG_1("Output: %s", buf);
220                         }
221
222                 status = pclose(in);
223
224                 if (WIFEXITED(status))
225                         {
226                         msg = "Command terminated with exit code";
227                         retval = WEXITSTATUS(status);
228                         }
229                 else if (WIFSIGNALED(status))
230                         {
231                         msg = "Command was killed by signal";
232                         retval = WTERMSIG(status);
233                         }
234                 else
235                         {
236                         msg = "pclose() returned";
237                         retval = status;
238                         }
239
240                 DEBUG_1("%s : %d\n", msg, retval);
241         }
242
243         return retval;
244 #endif
245 }
246
247 /**
248  * @brief Returns integer representing first_day_of_week
249  * @returns Integer in range 1 to 7
250  * 
251  * Uses current locale to get first day of week.
252  * If _NL_TIME_FIRST_WEEKDAY is not available, ISO 8601
253  * states first day of week is Monday.
254  * USA, Mexico and Canada (and others) use Sunday as first day of week.
255  * 
256  * Sunday == 1
257  */
258 gint date_get_first_day_of_week()
259 {
260 #ifdef HAVE__NL_TIME_FIRST_WEEKDAY
261         return nl_langinfo(_NL_TIME_FIRST_WEEKDAY)[0];
262 #else
263         gchar *dot;
264         gchar *current_locale;
265
266         current_locale = setlocale(LC_ALL, NULL);
267         dot = strstr(current_locale, ".");
268         if ((strncmp(dot - 2, "US", 2) == 0) || (strncmp(dot - 2, "MX", 2) == 0) || (strncmp(dot - 2, "CA", 2) == 0))
269                 {
270                 return 1;
271                 }
272         else
273                 {
274                 return 2;
275                 }
276 #endif
277 }
278
279 /**
280  * @brief Get an abbreviated day name from locale
281  * @param day Integer in range 1 to 7, representing day of week
282  * @returns String containing abbreviated day name
283  * 
284  *  Uses current locale to get day name
285  * 
286  * Sunday == 1
287  * Result must be freed
288  */
289 gchar *date_get_abbreviated_day_name(gint day)
290 {
291         gchar *abday = nullptr;
292
293         switch (day)
294                 {
295                 case 1:
296                 abday = g_strdup(nl_langinfo(ABDAY_1));
297                 break;
298                 case 2:
299                 abday = g_strdup(nl_langinfo(ABDAY_2));
300                 break;
301                 case 3:
302                 abday = g_strdup(nl_langinfo(ABDAY_3));
303                 break;
304                 case 4:
305                 abday = g_strdup(nl_langinfo(ABDAY_4));
306                 break;
307                 case 5:
308                 abday = g_strdup(nl_langinfo(ABDAY_5));
309                 break;
310                 case 6:
311                 abday = g_strdup(nl_langinfo(ABDAY_6));
312                 break;
313                 case 7:
314                 abday = g_strdup(nl_langinfo(ABDAY_7));
315                 break;
316                 }
317
318         return abday;
319 }
320
321 gchar *convert_rating_to_stars(gint rating)
322 {
323         GString *str = g_string_new(nullptr);
324
325         if (rating == -1)
326                 {
327                 str = g_string_append_unichar(str, options->star_rating.rejected);
328                 return g_string_free(str, FALSE);
329                 }
330
331         if (rating > 0 && rating < 6)
332                 {
333                 for (; rating > 0; --rating)
334                         {
335                         str = g_string_append_unichar(str, options->star_rating.star);
336                         }
337                 return g_string_free(str, FALSE);
338                 }
339
340         return g_strdup("");
341 }
342
343 gchar *get_symbolic_link(const gchar *path_utf8)
344 {
345         gchar *sl;
346         struct stat st;
347         gchar *ret = g_strdup("");
348
349         sl = path_from_utf8(path_utf8);
350
351         if (lstat(sl, &st) == 0 && S_ISLNK(st.st_mode))
352                 {
353                 gchar *buf;
354                 gint l;
355
356                 buf = static_cast<gchar *>(g_malloc(st.st_size + 1));
357                 l = readlink(sl, buf, st.st_size);
358
359                 if (l == st.st_size)
360                         {
361                         buf[l] = '\0';
362
363                         ret = buf;
364                         }
365                 else
366                         {
367                         g_free(buf);
368                         }
369                 }
370
371         g_free(sl);
372
373         return ret;
374 }
375
376 gint get_cpu_cores()
377 {
378     return sysconf(_SC_NPROCESSORS_ONLN);
379 }
380
381 #ifdef HAVE_GTK4
382 void convert_gdkcolor_to_gdkrgba(gpointer data, GdkRGBA *gdk_rgba)
383 {
384 /* @FIXME GTK4 stub */
385 }
386 #else
387 void convert_gdkcolor_to_gdkrgba(gpointer data, GdkRGBA *gdk_rgba)
388 {
389         auto gdk_color = static_cast<GdkColor *>(data);
390
391         gdk_rgba->red = CLAMP((double)gdk_color->red / 65535.0, 0.0, 1.0);
392         gdk_rgba->green = CLAMP((double)gdk_color->green / 65535.0, 0.0, 1.0);
393         gdk_rgba->blue = CLAMP((double)gdk_color->blue / 65535.0, 0.0, 1.0);
394         gdk_rgba->alpha = 1.0;
395 }
396 #endif
397
398 void gq_gtk_entry_set_text(GtkEntry *entry, const gchar *text)
399 {
400         GtkEntryBuffer *buffer;
401
402         buffer = gtk_entry_get_buffer(entry);
403         gtk_entry_buffer_set_text(buffer, text, static_cast<gint>(g_utf8_strlen(text, -1)));
404 }
405
406 const gchar *gq_gtk_entry_get_text(GtkEntry *entry)
407 {
408         GtkEntryBuffer *buffer;
409
410         buffer = gtk_entry_get_buffer(entry);
411         return gtk_entry_buffer_get_text(buffer);
412 }
413
414 void gq_gtk_grid_attach(GtkGrid *grid, GtkWidget *child, guint left_attach, guint right_attach, guint top_attach, guint bottom_attach, GtkAttachOptions, GtkAttachOptions, guint, guint)
415 {
416         gtk_grid_attach(grid, child, left_attach, top_attach, right_attach - left_attach, bottom_attach - top_attach);
417 }
418
419 void gq_gtk_grid_attach_default(GtkGrid *grid, GtkWidget *child, guint left_attach, guint right_attach, guint top_attach, guint bottom_attach )
420 {
421         gtk_grid_attach(grid, child, left_attach, top_attach, right_attach - left_attach, bottom_attach - top_attach);
422 }
423
424 /* Copied from the libarchive .repo. examples */
425
426 #ifndef HAVE_ARCHIVE
427 gchar *open_archive(FileData *)
428 {
429         log_printf("%s", _("Warning: libarchive not installed"));
430         return NULL;
431 }
432
433 #else
434
435 #include <archive.h>
436 #include <archive_entry.h>
437
438 static void errmsg(const char *);
439 static gboolean extract(const char *filename, int do_extract, int flags);
440 static int copy_data(struct archive *, struct archive *);
441 static void msg(const char *);
442 static int verbose = 0;
443
444 gchar *open_archive(FileData *fd)
445 {
446         int flags;
447         gchar *current_dir;
448         gchar *destination_dir;
449         gboolean success;
450         gint error;
451
452         destination_dir = g_build_filename(g_get_tmp_dir(), GQ_ARCHIVE_DIR, instance_identifier, fd->path, NULL);
453
454         if (!recursive_mkdir_if_not_exists(destination_dir, 0755))
455                 {
456                 log_printf("%s%s%s", _("Open Archive - Cannot create directory: "), destination_dir, "\n");
457                 g_free(destination_dir);
458                 return nullptr;
459                 }
460
461         current_dir = g_get_current_dir();
462         error = chdir(destination_dir);
463         if (error)
464                 {
465                 log_printf("%s%s%s%s%s", _("Open Archive - Cannot change directory to: "), destination_dir, _("\n  Error code: "), strerror(errno), "\n");
466                 g_free(destination_dir);
467                 g_free(current_dir);
468                 return nullptr;
469                 }
470
471         flags = ARCHIVE_EXTRACT_TIME;
472         success = extract(fd->path, 1, flags);
473
474         error = chdir(current_dir);
475         if (error)
476                 {
477                 log_printf("%s%s%s%s%s", _("Open Archive - Cannot change directory to: "), current_dir, _("\n  Error code: "), strerror(errno), "\n");
478                 g_free(destination_dir);
479                 g_free(current_dir);
480                 return nullptr;
481                 }
482         g_free(current_dir);
483
484         if (!success)
485                 {
486                 g_free(destination_dir);
487                 destination_dir = nullptr;
488                 }
489
490         return destination_dir;
491 }
492
493 static gboolean extract(const char *filename, int do_extract, int flags)
494 {
495         struct archive *a;
496         struct archive *ext;
497         struct archive_entry *entry;
498         int r;
499
500         a = archive_read_new();
501         ext = archive_write_disk_new();
502         archive_write_disk_set_options(ext, flags);
503         archive_write_disk_set_standard_lookup(ext);
504         archive_read_support_filter_all(a);
505         archive_read_support_format_all(a);
506
507         if (filename != nullptr && strcmp(filename, "-") == 0)
508                 {
509                 filename = nullptr;
510                 }
511         if ((r = archive_read_open_filename(a, filename, 10240)))
512                 {
513                 errmsg(archive_error_string(a));
514                 errmsg("\n");
515                 return(FALSE);
516                 }
517         for (;;)
518                 {
519                 int needcr = 0;
520
521                 r = archive_read_next_header(a, &entry);
522                 if (r == ARCHIVE_EOF)
523                         {
524                         break;
525                         }
526                 if (r != ARCHIVE_OK)
527                         {
528                         errmsg(archive_error_string(a));
529                         errmsg("\n");
530                         return(FALSE);
531                         }
532                 if (verbose && do_extract)
533                         {
534                         msg("x ");
535                         }
536                 if (verbose || !do_extract)
537                         {
538                         msg(archive_entry_pathname(entry));
539                         msg(" ");
540                         needcr = 1;
541                         }
542                 if (do_extract)
543                         {
544                         r = archive_write_header(ext, entry);
545                         if (r != ARCHIVE_OK)
546                                 {
547                                 errmsg(archive_error_string(a));
548                                 needcr = 1;
549                                 }
550                         else
551                                 {
552                                 r = copy_data(a, ext);
553                                 if (r != ARCHIVE_OK)
554                                         {
555                                         needcr = 1;
556                                         }
557                                 }
558                         }
559                 if (needcr)
560                         {
561                         msg("\n");
562                         }
563                 }
564         archive_read_close(a);
565         archive_read_free(a);
566
567         archive_write_close(ext);
568         archive_write_free(ext);
569         return(TRUE);
570 }
571
572 static int copy_data(struct archive *ar, struct archive *aw)
573 {
574         int r;
575         const void *buff;
576         size_t size;
577         int64_t offset;
578
579         for (;;)
580                 {
581                 r = archive_read_data_block(ar, &buff, &size, &offset);
582                 if (r == ARCHIVE_EOF)
583                         return (ARCHIVE_OK);
584                 if (r != ARCHIVE_OK)
585                         {
586                         errmsg(archive_error_string(ar));
587                         return (r);
588                         }
589                 r = archive_write_data_block(aw, buff, size, offset);
590                 if (r != ARCHIVE_OK)
591                         {
592                         errmsg(archive_error_string(ar));
593                         return (r);
594                         }
595                 }
596 }
597
598 static void msg(const char *m)
599 {
600         log_printf("Open Archive - libarchive error: %s \n", m);
601 }
602
603 static void errmsg(const char *m)
604 {
605         if (m == nullptr)
606                 {
607                 m = "Error: No error description provided.\n";
608                 }
609         log_printf("Open Archive - libarchive error: %s \n", m);
610 }
611 #endif
612 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */