clang-tidy: readability-isolate-declaration
[geeqie.git] / src / osd.cc
1 /*
2  * Copyright (C) 2018 The Geeqie Team
3  *
4  * Author: Colin Clark
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 /* Routines for creating the Overlay Screen Display text. Also
22  * used for the same purposes by the Print routines
23  */
24
25 #include "main.h"
26 #include "osd.h"
27
28 #include "dnd.h"
29 #include "exif.h"
30 #include "glua.h"
31 #include "metadata.h"
32 #include "ui-fileops.h"
33 #include "ui-misc.h"
34
35 #include <cmath>
36
37 static const gchar *predefined_tags[][2] = {
38         {"%name%",                                                      N_("Name")},
39         {"%path:60%",                                           N_("Path")},
40         {"%date%",                                                      N_("Date")},
41         {"%size%",                                                      N_("Size")},
42         {"%zoom%",                                                      N_("Zoom")},
43         {"%dimensions%",                                        N_("Dimensions")},
44         {"%collection%",                                        N_("Collection")},
45         {"%number%",                                            N_("Image index")},
46         {"%total%",                                                     N_("Images total")},
47         {"%comment%",                                           N_("Comment")},
48         {"%keywords%",                                          N_("Keywords")},
49         {"%file.ctime%",                                        N_("File ctime")},
50         {"%file.mode%",                                         N_("File mode")},
51         {"%file.owner%",                                        N_("File owner")},
52         {"%file.group%",                                        N_("File group")},
53         {"%file.link%",                                         N_("File link")},
54         {"%file.class%",                                        N_("File class")},
55         {"%file.page_no%",                                      N_("File page no.")},
56         {"%formatted.DateTime%",                        N_("Image date")},
57         {"%formatted.DateTimeDigitized%",       N_("Date digitized")},
58         {"%formatted.ShutterSpeed%",            N_("ShutterSpeed")},
59         {"%formatted.Aperture%",                        N_("Aperture")},
60         {"%formatted.ExposureBias%",            N_("Exposure bias")},
61         {"%formatted.Resolution%",                      N_("Resolution")},
62         {"%formatted.Camera%",                          N_("Camera")},
63         {"%lua.lensID%",                                        N_("Lens")},
64         {"%formatted.ISOSpeedRating%",          N_("ISO")},
65         {"%formatted.FocalLength%",                     N_("Focal length")},
66         {"%formatted.FocalLength35mmFilm%",     N_("Focal len. 35mm")},
67         {"%formatted.SubjectDistance%",         N_("Subject distance")},
68         {"%formatted.Flash%",                           N_("Flash")},
69         {"%formatted.ColorProfile%",            N_("Color profile")},
70         {"%formatted.GPSPosition%",                     N_("Lat, Long")},
71         {"%formatted.GPSAltitude%",                     N_("Altitude")},
72         {"%formatted.localtime%",                       N_("Local time")},
73         {"%formatted.timezone%",                        N_("Timezone")},
74         {"%formatted.countryname%",                     N_("Country name")},
75         {"%formatted.countrycode%",                     N_("Country code")},
76         {"%rating%",                                            N_("Rating")},
77         {"%formatted.star_rating%",                     N_("Star rating")},
78         {"%Xmp.dc.creator%",                            N_("© Creator")},
79         {"%Xmp.dc.contributor%",                        N_("© Contributor")},
80         {"%Xmp.dc.rights%",                                     N_("© Rights")},
81         {nullptr, nullptr}};
82
83 static GtkTargetEntry osd_drag_types[] = {
84         { const_cast<gchar *>("text/plain"), GTK_TARGET_SAME_APP, TARGET_TEXT_PLAIN }
85 };
86
87 struct TagData
88 {
89         gchar *key;
90         gchar *title;
91 };
92
93 static void tag_button_cb(GtkWidget *widget, gpointer data)
94 {
95         auto image_overlay_template_view = static_cast<GtkTextView *>(data);
96         GtkTextBuffer *buffer;
97         TagData *td;
98
99         buffer = gtk_text_view_get_buffer(image_overlay_template_view);
100         td = static_cast<TagData *>(g_object_get_data(G_OBJECT(widget), "tag_data"));
101         gtk_text_buffer_insert_at_cursor(GTK_TEXT_BUFFER(buffer), td->key, -1);
102
103         gtk_widget_grab_focus(GTK_WIDGET(image_overlay_template_view));
104 }
105
106 static void osd_dnd_get_cb(GtkWidget *btn, GdkDragContext *, GtkSelectionData *selection_data, guint, guint, gpointer data)
107 {
108         TagData *td;
109         auto image_overlay_template_view = static_cast<GtkTextView *>(data);
110
111         td = static_cast<TagData *>(g_object_get_data(G_OBJECT(btn), "tag_data"));
112         gtk_selection_data_set_text(selection_data, td->key, -1);
113
114         gtk_widget_grab_focus(GTK_WIDGET(image_overlay_template_view));
115 }
116
117 static void osd_btn_destroy_cb(GtkWidget *btn, GdkDragContext *, GtkSelectionData *, guint, guint, gpointer)
118 {
119         TagData *td;
120
121         td = static_cast<TagData *>(g_object_get_data(G_OBJECT(btn), "tag_data"));
122         g_free(td->key);
123         g_free(td->title);
124 }
125
126 static void set_osd_button(GtkGrid *grid, const gint rows, const gint cols, const gchar *key, const gchar *title, GtkWidget *template_view)
127 {
128         GtkWidget *new_button;
129         TagData *td;
130
131         new_button = gtk_button_new_with_label(title);
132         g_signal_connect(G_OBJECT(new_button), "clicked", G_CALLBACK(tag_button_cb), template_view);
133         gtk_widget_show(new_button);
134
135         td = g_new0(TagData, 1);
136         td->key = g_strdup(key);
137         td->title = g_strdup(title);
138
139         g_object_set_data(G_OBJECT(new_button), "tag_data", td);
140
141         gtk_drag_source_set(new_button, GDK_BUTTON1_MASK, osd_drag_types, 1, GDK_ACTION_COPY);
142         g_signal_connect(G_OBJECT(new_button), "drag_data_get",
143                                                         G_CALLBACK(osd_dnd_get_cb), template_view);
144         g_signal_connect(G_OBJECT(new_button), "destroy",
145                                                         G_CALLBACK(osd_btn_destroy_cb), new_button);
146
147         gtk_grid_attach(grid, new_button, cols, rows, 1, 1);
148
149 }
150
151 GtkWidget *osd_new(gint max_cols, GtkWidget *template_view)
152 {
153         GtkWidget *vbox;
154         GtkWidget *scrolled;
155         gint i = 0;
156         gint rows = 0;
157         gint max_rows = 0;
158         gint cols = 0;
159         gdouble entries;
160         GtkWidget *viewport;
161
162         vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
163
164         pref_label_new(vbox, _("To include predefined tags in the template, click a button or drag-and-drop"));
165
166         scrolled = gq_gtk_scrolled_window_new(nullptr, nullptr);
167         gq_gtk_box_pack_start(GTK_BOX(vbox), scrolled, FALSE, FALSE, 0);
168         gtk_container_set_border_width(GTK_CONTAINER(scrolled), PREF_PAD_BORDER);
169         gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(scrolled),
170                                        GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
171         gtk_widget_show(scrolled);
172         gtk_widget_set_size_request(scrolled, -1, 140);
173
174         viewport = gtk_viewport_new(nullptr, nullptr);
175         gtk_viewport_set_shadow_type(GTK_VIEWPORT(viewport), GTK_SHADOW_NONE);
176         gq_gtk_container_add(GTK_WIDGET(scrolled), viewport);
177         gtk_widget_show(viewport);
178
179         entries = ((gdouble)sizeof(predefined_tags) / sizeof(predefined_tags[0])) - 1;
180         max_rows = ceil(entries / max_cols);
181
182         GtkGrid *grid;
183         grid = GTK_GRID(gtk_grid_new());
184         gq_gtk_container_add(GTK_WIDGET(viewport), GTK_WIDGET(grid));
185         gtk_widget_show(GTK_WIDGET(grid));
186
187         for (rows = 0; rows < max_rows; rows++)
188                 {
189                 cols = 0;
190
191                 while (cols < max_cols && predefined_tags[i][0])
192                         {
193                         set_osd_button(grid, rows, cols, predefined_tags[i][0], predefined_tags[i][1], template_view);
194                         i = i + 1;
195                         cols++;
196                         }
197                 }
198         return vbox;
199 }
200 static gchar *keywords_to_string(FileData *fd)
201 {
202         GList *keywords;
203         GString *kwstr = nullptr;
204
205         g_assert(fd);
206
207         keywords = metadata_read_list(fd, KEYWORD_KEY, METADATA_PLAIN);
208
209         if (keywords)
210                 {
211                 GList *work = keywords;
212
213                 while (work)
214                         {
215                         auto kw = static_cast<gchar *>(work->data);
216                         work = work->next;
217
218                         if (!kw) continue;
219                         if (!kwstr)
220                                 kwstr = g_string_new("");
221                         else
222                                 g_string_append(kwstr, ", ");
223
224                         g_string_append(kwstr, kw);
225                         }
226                 g_list_free_full(keywords, g_free);
227                 }
228
229         if (kwstr)
230                 {
231                 return g_string_free(kwstr, FALSE);
232                 }
233
234         return nullptr;
235 }
236
237 gchar *image_osd_mkinfo(const gchar *str, FileData *fd, GHashTable *vars)
238 {
239         gchar delim = '%';
240         gchar imp = '|';
241         gchar sep[] = " - ";
242         gchar *start;
243         gchar *end;
244         guint pos;
245         guint prev;
246         gboolean want_separator = FALSE;
247         gchar *name;
248         gchar *data;
249         GString *osd_info;
250         gchar *ret;
251
252         if (!str || !*str) return g_strdup("");
253
254         osd_info = g_string_new(str);
255
256         prev = -1;
257
258         while (TRUE)
259                 {
260                 guint limit = 0;
261                 gchar *trunc = nullptr;
262                 gchar *limpos = nullptr;
263                 gchar *extra = nullptr;
264                 gchar *extrapos = nullptr;
265                 gchar *p;
266
267                 start = strchr(osd_info->str + (prev + 1), delim);
268                 if (!start)
269                         break;
270                 end = strchr(start+1, delim);
271                 if (!end)
272                         break;
273
274                 /* Search for optional modifiers
275                  * %name:99:extra% -> name = "name", limit=99, extra = "extra"
276                  */
277                 for (p = start + 1; p < end; p++)
278                         {
279                         if (p[0] == ':')
280                                 {
281                                 if (g_ascii_isdigit(p[1]) && !limpos)
282                                         {
283                                         limpos = p + 1;
284                                         if (!trunc) trunc = p;
285                                         }
286                                 else
287                                         {
288                                         extrapos = p + 1;
289                                         if (!trunc) trunc = p;
290                                         break;
291                                         }
292                                 }
293                         }
294
295                 if (limpos)
296                         limit = static_cast<guint>(atoi(limpos));
297
298                 if (extrapos)
299                         extra = g_strndup(extrapos, end - extrapos);
300
301                 name = g_strndup(start+1, (trunc ? trunc : end)-start-1);
302                 pos = start - osd_info->str;
303                 data = nullptr;
304
305                 if (strcmp(name, "keywords") == 0)
306                         {
307                         data = keywords_to_string(fd);
308                         }
309                 else if (strcmp(name, "comment") == 0)
310                         {
311                         data = metadata_read_string(fd, COMMENT_KEY, METADATA_PLAIN);
312                         }
313                 else if (strcmp(name, "imagecomment") == 0)
314                         {
315                         data = exif_get_image_comment(fd);
316                         }
317                 else if (strcmp(name, "rating") == 0)
318                         {
319                         data = metadata_read_string(fd, RATING_KEY, METADATA_PLAIN);
320                         }
321 #ifdef HAVE_LUA
322                 else if (strncmp(name, "lua/", 4) == 0)
323                         {
324                         gchar *tmp;
325                         tmp = strchr(name+4, '/');
326                         if (!tmp)
327                                 break;
328                         *tmp = '\0';
329                         data = lua_callvalue(fd, name+4, tmp+1);
330                         }
331 #endif
332                 else
333                         {
334                         data = g_strdup(static_cast<const gchar *>(g_hash_table_lookup(vars, static_cast<gconstpointer>(name))));
335                         if (!data)
336                                 data = metadata_read_string(fd, name, METADATA_FORMATTED);
337                         }
338
339                 if (data && *data && limit > 0 && strlen(data) > limit + 3)
340                         {
341                         gchar *new_data = g_strdup_printf("%-*.*s...", limit, limit, data);
342                         g_free(data);
343                         data = new_data;
344                         }
345
346                 if (data)
347                         {
348                         /* Since we use pango markup to display, we need to escape here */
349                         gchar *escaped = g_markup_escape_text(data, -1);
350                         g_free(data);
351                         data = escaped;
352                         }
353
354                 if (extra)
355                         {
356                         if (data && *data)
357                                 {
358                                 /* Display data between left and right parts of extra string
359                                  * the data is expressed by a '*' character. A '*' may be escaped
360                                  * by a \. You should escape all '*' characters, do not rely on the
361                                  * current implementation which only replaces the first unescaped '*'.
362                                  * If no "*" is present, the extra string is just appended to data string.
363                                  * Pango mark up is accepted in left and right parts.
364                                  * Any \n is replaced by a newline
365                                  * Examples:
366                                  * "<i>*</i>\n" -> data is displayed in italics ended with a newline
367                                  * "\n"         -> ended with newline
368                                  * "ISO *"      -> prefix data with "ISO " (ie. "ISO 100")
369                                  * "\**\*"      -> prefix data with a star, and append a star (ie. "*100*")
370                                  * "\\*"        -> prefix data with an anti slash (ie "\100")
371                                  * "Collection <b>*</b>\n" -> display data in bold prefixed by "Collection " and a newline is appended
372                                  */
373                                 /** @FIXME using background / foreground colors lead to weird results.
374                                  */
375                                 gchar *new_data;
376                                 gchar *left = nullptr;
377                                 gchar *right = extra;
378                                 gchar *p;
379                                 guint len = strlen(extra);
380
381                                 /* Search for left and right parts and unescape characters */
382                                 for (p = extra; *p; p++, len--)
383                                         if (p[0] == '\\')
384                                                 {
385                                                 if (p[1] == 'n')
386                                                         {
387                                                         memmove(p+1, p+2, --len);
388                                                         p[0] = '\n';
389                                                         }
390                                                 else if (p[1] != '\0')
391                                                         memmove(p, p+1, len--); // includes \0
392                                                 }
393                                         else if (p[0] == '*' && !left)
394                                                 {
395                                                 right = p + 1;
396                                                 left = extra;
397                                                 }
398
399                                 if (left) right[-1] = '\0';
400
401                                 new_data = g_strdup_printf("%s%s%s", left ? left : "", data, right);
402                                 g_free(data);
403                                 data = new_data;
404                                 }
405                         g_free(extra);
406                         }
407
408                 g_string_erase(osd_info, pos, end-start+1);
409                 if (data && *data)
410                         {
411                         if (want_separator)
412                                 {
413                                 /* insert separator */
414                                 g_string_insert(osd_info, pos, sep);
415                                 pos += strlen(sep);
416                                 want_separator = FALSE;
417                                 }
418
419                         g_string_insert(osd_info, pos, data);
420                         pos += strlen(data);
421                 }
422
423                 if (pos-prev >= 1 && osd_info->str[pos] == imp)
424                         {
425                         /* pipe character is replaced by a separator, delete it
426                          * and raise a flag if needed */
427                         g_string_erase(osd_info, pos--, 1);
428                         want_separator |= (data && *data);
429                         }
430
431                 if (osd_info->str[pos] == '\n') want_separator = FALSE;
432
433                 prev = pos - 1;
434
435                 g_free(name);
436                 g_free(data);
437                 }
438
439         /* search and destroy empty lines */
440         end = osd_info->str;
441         while ((start = strchr(end, '\n')))
442                 {
443                 end = start;
444                 while (*++(end) == '\n')
445                         ;
446                 g_string_erase(osd_info, start-osd_info->str, end-start-1);
447                 }
448
449         ret = g_string_free(osd_info, FALSE);
450
451         return g_strchomp(ret);
452 }
453
454 void osd_template_insert(GHashTable *vars, const gchar *keyword, const gchar *value, OsdTemplateFlags flags)
455 {
456         if (!value)
457                 {
458                 g_hash_table_insert(vars, const_cast<gchar *>(keyword), g_strdup(""));
459                 return;
460                 }
461
462         if (flags & OSDT_NO_DUP)
463                 {
464                 g_hash_table_insert(vars, const_cast<gchar *>(keyword), const_cast<gchar *>(value));
465                 return;
466                 }
467
468         g_hash_table_insert(vars, const_cast<gchar *>(keyword), g_strdup(value));
469
470         if (flags & OSDT_FREE) g_free(const_cast<gchar *>(value));
471 }
472 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */