fb88ebd5634dd5d851165a394a749191ca1061f8
[geeqie.git] / src / collect-io.cc
1 /*
2  * Copyright (C) 2004 John Ellis
3  * Copyright (C) 2008 - 2016 The Geeqie Team
4  *
5  * Author: John Ellis
6  *
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.
11  *
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.
16  *
17  * You should have received a copy of the GNU General Public License along
18  * with this program; if not, write to the Free Software Foundation, Inc.,
19  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  */
21
22 #include "main.h"
23 #include "collect-io.h"
24
25 #include "collect.h"
26 #include "filedata.h"
27 #include "layout-util.h"
28 #include "secure-save.h"
29 #include "thumb.h"
30 #include "ui-fileops.h"
31
32 #define GQ_COLLECTION_MARKER "#" GQ_APPNAME
33
34 #define GQ_COLLECTION_FAIL_MIN     300
35 #define GQ_COLLECTION_FAIL_PERCENT 98
36 #define GQ_COLLECTION_READ_BUFSIZE 4096
37
38 struct CollectManagerEntry;
39
40 static void collection_load_thumb_step(CollectionData *cd);
41 static gboolean collection_save_private(CollectionData *cd, const gchar *path);
42
43 static CollectManagerEntry *collect_manager_get_entry(const gchar *path);
44 static void collect_manager_entry_reset(CollectManagerEntry *entry);
45 static gint collect_manager_process_action(CollectManagerEntry *entry, gchar **path_ptr);
46
47
48 static gboolean scan_geometry(gchar *buffer, gint *x, gint *y, gint *w, gint *h)
49 {
50         gint nx, ny, nw, nh;
51
52         if (sscanf(buffer, "%d %d %d %d", &nx, &ny, &nw, &nh) != 4) return FALSE;
53
54         *x = nx;
55         *y = ny;
56         *w = nw;
57         *h = nh;
58
59         return TRUE;
60 }
61
62 static gboolean collection_load_private(CollectionData *cd, const gchar *path, CollectionLoadFlags flags)
63 {
64         gchar s_buf[GQ_COLLECTION_READ_BUFSIZE];
65         FILE *f;
66         gchar *pathl;
67         gboolean limit_failures = TRUE;
68         gboolean success = TRUE;
69         gboolean has_official_header = FALSE;
70         gboolean has_geometry_header = FALSE;
71         gboolean has_gqview_header   = FALSE;
72         gboolean need_header     = TRUE;
73         guint total = 0;
74         guint fail = 0;
75         gboolean changed = FALSE;
76         CollectManagerEntry *entry = nullptr;
77         guint flush = !!(flags & COLLECTION_LOAD_FLUSH);
78         guint append = !!(flags & COLLECTION_LOAD_APPEND);
79         guint only_geometry = !!(flags & COLLECTION_LOAD_GEOMETRY);
80         gboolean reading_extended_filename = FALSE;
81         gchar *buffer2;
82
83         if (!only_geometry)
84                 {
85                 collection_load_stop(cd);
86
87                 if (flush)
88                         collect_manager_flush();
89                 else
90                         entry = collect_manager_get_entry(path);
91
92                 if (!append)
93                         {
94                         g_list_free_full(cd->list, reinterpret_cast<GDestroyNotify>(collection_info_free));
95                         cd->list = nullptr;
96                         }
97                 }
98
99         if (!path && !cd->path) return FALSE;
100
101         if (!path) path = cd->path;
102
103         pathl = path_from_utf8(path);
104
105         DEBUG_1("collection load: append=%d flush=%d only_geometry=%d path=%s",
106                           append, flush, only_geometry, pathl);
107
108         /* load it */
109         f = fopen(pathl, "r");
110         g_free(pathl);
111         if (!f)
112                 {
113                 log_printf("Failed to open collection file: \"%s\"\n", path);
114                 return FALSE;
115                 }
116
117         GString *extended_filename_buffer = g_string_new(nullptr);
118         while (fgets(s_buf, sizeof(s_buf), f))
119                 {
120                 gchar *buf;
121                 gchar *p = s_buf;
122
123                 if (!reading_extended_filename)
124                         {
125                         /* Skip whitespaces and empty lines */
126                         while (*p && g_ascii_isspace(*p)) p++;
127                         if (*p == '\n' || *p == '\r') continue;
128
129                         /* Parse comments */
130                         if (*p == '#')
131                                 {
132                                 if (!need_header) continue;
133                                 if (g_ascii_strncasecmp(p, GQ_COLLECTION_MARKER, strlen(GQ_COLLECTION_MARKER)) == 0)
134                                         {
135                                         /* Looks like an official collection, allow unchecked input.
136                                          * All this does is allow adding files that may not exist,
137                                          * which is needed for the collection manager to work.
138                                          * Also unofficial files abort after too many invalid entries.
139                                          */
140                                         has_official_header = TRUE;
141                                         limit_failures = FALSE;
142                                         }
143                                 else if (strncmp(p, "#geometry:", 10 ) == 0 &&
144                                          scan_geometry(p + 10, &cd->window_x, &cd->window_y, &cd->window_w, &cd->window_h))
145                                         {
146                                         has_geometry_header = TRUE;
147                                         cd->window_read = TRUE;
148                                         if (only_geometry) break;
149                                         }
150                                 else if (g_ascii_strncasecmp(p, "#GQview collection", strlen("#GQview collection")) == 0)
151                                         {
152                                         /* As 2008/04/15 there is no difference between our collection file format
153                                          * and GQview 2.1.5 collection file format so ignore failures as well. */
154                                         has_gqview_header = TRUE;
155                                         limit_failures = FALSE;
156                                         }
157                                 need_header = (!has_official_header && !has_gqview_header) || !has_geometry_header;
158                                 continue;
159                                 }
160
161                         if (only_geometry) continue;
162                         }
163
164                 /* Read filenames */
165                 /** @todo This is not safe! */
166                 /* Updated: anything within double quotes is considered a filename */
167                 if (!reading_extended_filename)
168                         {
169                         /* not yet reading filename */
170                         while (*p && *p != '"') p++;
171                         if (*p) p++;
172                         /* start of filename read */
173                         buf = p;
174                         while (*p && *p != '"') p++;
175                         if (p[0] != '"')
176                                 {
177                                 /* first part of extended filename */
178                                 g_string_append(extended_filename_buffer, buf);
179                                 reading_extended_filename = TRUE;
180                                 continue;
181                                 }
182                         }
183                 else
184                         {
185                         buf = p;
186                         while (*p && *p != '"') p++;
187                         if (p[0] != '"')
188                                 {
189                                 /* end of extended filename still not found */
190                                 g_string_append(extended_filename_buffer, buf);
191                                 continue;
192                                 }
193                         else
194                                 {
195                                 /* end of extended filename found */
196                                 g_string_append_len(extended_filename_buffer, buf, p - buf);
197                                 reading_extended_filename = FALSE;
198                                 }
199                         }
200
201                 if (strlen(extended_filename_buffer->str) > 0)
202                         {
203                         buffer2 = g_strdup(extended_filename_buffer->str);
204                         g_string_erase(extended_filename_buffer, 0, -1);
205                         }
206                 else
207                         {
208                         *p = 0;
209                         buffer2 = g_strdup(buf);
210                         }
211
212                 if (*buffer2)
213                         {
214                         gboolean valid;
215
216                         if (!flush)
217                                 changed |= collect_manager_process_action(entry, &buffer2);
218
219                         valid = (buffer2[0] == G_DIR_SEPARATOR && collection_add_check(cd, file_data_new_simple(buffer2), FALSE, TRUE));
220                         if (!valid) DEBUG_1("collection invalid file: %s", buffer2);
221
222                         total++;
223                         if (!valid)
224                                 {
225                                 fail++;
226                                 if (limit_failures &&
227                                     fail > GQ_COLLECTION_FAIL_MIN &&
228                                     fail * 100 / total > GQ_COLLECTION_FAIL_PERCENT)
229                                         {
230                                         log_printf("%d invalid filenames in unofficial collection file, closing: %s\n", fail, path);
231                                         success = FALSE;
232                                         break;
233                                         }
234                                 }
235                         }
236                 g_free(buffer2);
237                 }
238
239         g_string_free(extended_filename_buffer, TRUE);
240
241         DEBUG_1("collection files: total = %d fail = %d official=%d gqview=%d geometry=%d",
242                           total, fail, has_official_header, has_gqview_header, has_geometry_header);
243
244         fclose(f);
245         if (only_geometry) return has_geometry_header;
246
247         if (!flush)
248                 {
249                 gchar *buf = nullptr;
250                 while (collect_manager_process_action(entry, &buf))
251                         {
252                         collection_add_check(cd, file_data_new_group(buf), FALSE, TRUE);
253                         changed = TRUE;
254                         g_free(buf);
255                         buf = nullptr;
256                         }
257                 }
258
259         cd->list = collection_list_sort(cd->list, cd->sort_method);
260
261         if (!flush && changed && success)
262                 collection_save_private(cd, path);
263
264         if (!flush)
265                 collect_manager_entry_reset(entry);
266
267         if (!append) cd->changed = FALSE;
268
269         return success;
270 }
271
272 gboolean collection_load(CollectionData *cd, const gchar *path, CollectionLoadFlags flags)
273 {
274         if (collection_load_private(cd, path, static_cast<CollectionLoadFlags>(flags | COLLECTION_LOAD_FLUSH)))
275                 {
276                 layout_recent_add_path(cd->path);
277                 return TRUE;
278                 }
279
280         return FALSE;
281 }
282
283 static void collection_load_thumb_do(CollectionData *cd)
284 {
285         GdkPixbuf *pixbuf;
286
287         if (!cd->thumb_loader || !g_list_find(cd->list, cd->thumb_info)) return;
288
289         pixbuf = thumb_loader_get_pixbuf(cd->thumb_loader);
290         collection_info_set_thumb(cd->thumb_info, pixbuf);
291         g_object_unref(pixbuf);
292
293         if (cd->info_updated_func) cd->info_updated_func(cd, cd->thumb_info, cd->info_updated_data);
294 }
295
296 static void collection_load_thumb_error_cb(ThumbLoader *UNUSED(tl), gpointer data)
297 {
298         auto cd = static_cast<CollectionData *>(data);
299
300         collection_load_thumb_do(cd);
301         collection_load_thumb_step(cd);
302 }
303
304 static void collection_load_thumb_done_cb(ThumbLoader *UNUSED(tl), gpointer data)
305 {
306         auto cd = static_cast<CollectionData *>(data);
307
308         collection_load_thumb_do(cd);
309         collection_load_thumb_step(cd);
310 }
311
312 static void collection_load_thumb_step(CollectionData *cd)
313 {
314         GList *work;
315         CollectInfo *ci;
316
317         if (!cd->list)
318                 {
319                 collection_load_stop(cd);
320                 return;
321                 }
322
323         work = cd->list;
324         ci = static_cast<CollectInfo *>(work->data);
325         work = work->next;
326         /* find first unloaded thumb */
327         while (work && ci->pixbuf)
328                 {
329                 ci = static_cast<CollectInfo *>(work->data);
330                 work = work->next;
331                 }
332
333         if (!ci || ci->pixbuf)
334                 {
335                 /* done */
336                 collection_load_stop(cd);
337
338                 /* send a NULL CollectInfo to notify end */
339                 if (cd->info_updated_func) cd->info_updated_func(cd, nullptr, cd->info_updated_data);
340
341                 return;
342                 }
343
344         /* setup loader and call it */
345         cd->thumb_info = ci;
346         thumb_loader_free(cd->thumb_loader);
347         cd->thumb_loader = thumb_loader_new(options->thumbnails.max_width, options->thumbnails.max_height);
348         thumb_loader_set_callbacks(cd->thumb_loader,
349                                    collection_load_thumb_done_cb,
350                                    collection_load_thumb_error_cb,
351                                    nullptr,
352                                    cd);
353
354         /* start it */
355         if (!thumb_loader_start(cd->thumb_loader, ci->fd))
356                 {
357                 /* error, handle it, do next */
358                 DEBUG_1("error loading thumb for %s", ci->fd->path);
359                 collection_load_thumb_do(cd);
360                 collection_load_thumb_step(cd);
361                 }
362 }
363
364 void collection_load_thumb_idle(CollectionData *cd)
365 {
366         if (!cd->thumb_loader) collection_load_thumb_step(cd);
367 }
368
369 gboolean collection_load_begin(CollectionData *cd, const gchar *path, CollectionLoadFlags flags)
370 {
371         if (!collection_load(cd, path, flags)) return FALSE;
372
373         collection_load_thumb_idle(cd);
374
375         return TRUE;
376 }
377
378 void collection_load_stop(CollectionData *cd)
379 {
380         if (!cd->thumb_loader) return;
381
382         thumb_loader_free(cd->thumb_loader);
383         cd->thumb_loader = nullptr;
384 }
385
386 static gboolean collection_save_private(CollectionData *cd, const gchar *path)
387 {
388         SecureSaveInfo *ssi;
389         GList *work;
390         gchar *pathl;
391
392         if (!path && !cd->path) return FALSE;
393
394         if (!path)
395                 {
396                 path = cd->path;
397                 }
398
399
400         pathl = path_from_utf8(path);
401         ssi = secure_open(pathl);
402         g_free(pathl);
403         if (!ssi)
404                 {
405                 log_printf(_("failed to open collection (write) \"%s\"\n"), path);
406                 return FALSE;
407                 }
408
409         secure_fprintf(ssi, "%s collection\n", GQ_COLLECTION_MARKER);
410         secure_fprintf(ssi, "#created with %s version %s\n", GQ_APPNAME, VERSION);
411
412         collection_update_geometry(cd);
413         if (cd->window_read)
414                 {
415                 secure_fprintf(ssi, "#geometry: %d %d %d %d\n", cd->window_x, cd->window_y, cd->window_w, cd->window_h);
416                 }
417
418         work = cd->list;
419         while (work && secsave_errno == SS_ERR_NONE)
420                 {
421                 auto ci = static_cast<CollectInfo *>(work->data);
422                 secure_fprintf(ssi, "\"%s\"\n", ci->fd->path);
423                 work = work->next;
424                 }
425
426         secure_fprintf(ssi, "#end\n");
427
428         if (secure_close(ssi))
429                 {
430                 log_printf(_("error saving collection file: %s\nerror: %s\n"), path,
431                             secsave_strerror(secsave_errno));
432                 return FALSE;
433                 }
434
435         if (!cd->path || strcmp(path, cd->path) != 0)
436                 {
437                 gchar *buf = cd->path;
438                 cd->path = g_strdup(path);
439                 path = cd->path;
440                 g_free(buf);
441
442                 g_free(cd->name);
443                 cd->name = g_strdup(filename_from_path(cd->path));
444
445                 collection_path_changed(cd);
446                 }
447
448         cd->changed = FALSE;
449
450         return TRUE;
451 }
452
453 gboolean collection_save(CollectionData *cd, const gchar *path)
454 {
455         if (collection_save_private(cd, path))
456                 {
457                 layout_recent_add_path(cd->path);
458                 return TRUE;
459                 }
460
461         return FALSE;
462 }
463
464 gboolean collection_load_only_geometry(CollectionData *cd, const gchar *path)
465 {
466         return collection_load(cd, path, COLLECTION_LOAD_GEOMETRY);
467 }
468
469
470 /*
471  *-------------------------------------------------------------------
472  * collection manager
473  *-------------------------------------------------------------------
474  */
475
476 #define COLLECT_MANAGER_ACTIONS_PER_IDLE 1000
477 #define COLLECT_MANAGER_FLUSH_DELAY      10000
478
479 struct CollectManagerEntry
480 {
481         gchar *path;
482         GList *add_list;
483         GHashTable *oldpath_hash;
484         GHashTable *newpath_hash;
485         gboolean empty;
486 };
487
488 enum CollectManagerType {
489         COLLECTION_MANAGER_UPDATE,
490         COLLECTION_MANAGER_ADD,
491         COLLECTION_MANAGER_REMOVE
492 };
493
494 struct CollectManagerAction
495 {
496         gchar *oldpath;
497         gchar *newpath;
498
499         CollectManagerType type;
500
501         gint ref;
502 };
503
504
505 static GList *collection_manager_entry_list = nullptr;
506 static GList *collection_manager_action_list = nullptr;
507 static GList *collection_manager_action_tail = nullptr;
508 static guint collection_manager_timer_id = 0; /* event source id */
509
510
511 static CollectManagerAction *collect_manager_action_new(const gchar *oldpath, const gchar *newpath,
512                                                         CollectManagerType type)
513 {
514         CollectManagerAction *action;
515
516         action = g_new0(CollectManagerAction, 1);
517         action->ref = 1;
518
519         action->oldpath = g_strdup(oldpath);
520         action->newpath = g_strdup(newpath);
521
522         action->type = type;
523
524         return action;
525 }
526
527 static void collect_manager_action_ref(CollectManagerAction *action)
528 {
529         action->ref++;
530 }
531
532 static void collect_manager_action_unref(CollectManagerAction *action)
533 {
534         action->ref--;
535
536         if (action->ref > 0) return;
537
538         g_free(action->oldpath);
539         g_free(action->newpath);
540         g_free(action);
541 }
542
543 static void collect_manager_entry_free_data(CollectManagerEntry *entry)
544 {
545         g_list_free_full(entry->add_list, reinterpret_cast<GDestroyNotify>(collect_manager_action_unref));
546         if (g_hash_table_size(entry->oldpath_hash) > 0)
547                 g_hash_table_destroy(entry->oldpath_hash);
548         else
549                 g_hash_table_unref(entry->oldpath_hash);
550         if (g_hash_table_size(entry->newpath_hash) > 0)
551                 g_hash_table_destroy(entry->newpath_hash);
552         else
553                 g_hash_table_unref(entry->newpath_hash);
554 }
555
556 static void collect_manager_entry_init_data(CollectManagerEntry *entry)
557 {
558         entry->add_list = nullptr;
559         entry->oldpath_hash = g_hash_table_new_full(g_str_hash, g_str_equal, nullptr, reinterpret_cast<GDestroyNotify>(collect_manager_action_unref));
560         entry->newpath_hash = g_hash_table_new(g_str_hash, g_str_equal);
561         entry->empty = TRUE;
562
563 }
564
565 static CollectManagerEntry *collect_manager_entry_new(const gchar *path)
566 {
567         CollectManagerEntry *entry;
568
569         entry = g_new0(CollectManagerEntry, 1);
570         entry->path = g_strdup(path);
571         collect_manager_entry_init_data(entry);
572
573         collection_manager_entry_list = g_list_append(collection_manager_entry_list, entry);
574
575         return entry;
576 }
577
578
579 static void collect_manager_entry_free(CollectManagerEntry *entry)
580 {
581         collection_manager_entry_list = g_list_remove(collection_manager_entry_list, entry);
582
583         collect_manager_entry_free_data(entry);
584
585         g_free(entry->path);
586         g_free(entry);
587 }
588
589 static void collect_manager_entry_reset(CollectManagerEntry *entry)
590 {
591         collect_manager_entry_free_data(entry);
592         collect_manager_entry_init_data(entry);
593 }
594
595 static CollectManagerEntry *collect_manager_get_entry(const gchar *path)
596 {
597         GList *work;
598
599         work = collection_manager_entry_list;
600         while (work)
601                 {
602                 CollectManagerEntry *entry;
603
604                 entry = static_cast<CollectManagerEntry *>(work->data);
605                 work = work->next;
606                 if (strcmp(entry->path, path) == 0)
607                         {
608                         return entry;
609                         }
610                 }
611         return nullptr;
612
613 }
614
615 static void collect_manager_entry_add_action(CollectManagerEntry *entry, CollectManagerAction *action)
616 {
617
618         CollectManagerAction *orig_action;
619
620         entry->empty = FALSE;
621
622         if (action->oldpath == nullptr)
623                 {
624                 /* add file */
625                 if (action->newpath == nullptr)
626                         {
627                         return;
628                         }
629
630                 orig_action = static_cast<CollectManagerAction *>(g_hash_table_lookup(entry->newpath_hash, action->newpath));
631                 if (orig_action)
632                         {
633                         /* target already exists */
634                         log_printf("collection manager failed to add another action for target %s in collection %s\n",
635                                 action->newpath, entry->path);
636                         return;
637                         }
638                 entry->add_list = g_list_append(entry->add_list, action);
639                 g_hash_table_insert(entry->newpath_hash, action->newpath, action);
640                 collect_manager_action_ref(action);
641                 return;
642                 }
643
644         orig_action = static_cast<CollectManagerAction *>(g_hash_table_lookup(entry->newpath_hash, action->oldpath));
645         if (orig_action)
646                 {
647                 /* new action with the same file */
648                 CollectManagerAction *new_action = collect_manager_action_new(orig_action->oldpath, action->newpath, action->type);
649
650                 if (new_action->oldpath)
651                         {
652                         g_hash_table_steal(entry->oldpath_hash, orig_action->oldpath);
653                         g_hash_table_insert(entry->oldpath_hash, new_action->oldpath, new_action);
654                         }
655                 else
656                         {
657                         GList *work = g_list_find(entry->add_list, orig_action);
658                         work->data = new_action;
659                         }
660
661                 g_hash_table_steal(entry->newpath_hash, orig_action->newpath);
662                 if (new_action->newpath)
663                         {
664                         g_hash_table_insert(entry->newpath_hash, new_action->newpath, new_action);
665                         }
666                 collect_manager_action_unref(orig_action);
667                 return;
668                 }
669
670
671         orig_action = static_cast<CollectManagerAction *>(g_hash_table_lookup(entry->oldpath_hash, action->oldpath));
672         if (orig_action)
673                 {
674                 /* another action for the same source, ignore */
675                 log_printf("collection manager failed to add another action for source %s in collection %s\n",
676                         action->oldpath, entry->path);
677                 return;
678                 }
679
680         g_hash_table_insert(entry->oldpath_hash, action->oldpath, action);
681         if (action->newpath)
682                 {
683                 g_hash_table_insert(entry->newpath_hash, action->newpath, action);
684                 }
685         collect_manager_action_ref(action);
686 }
687
688 static gboolean collect_manager_process_action(CollectManagerEntry *entry, gchar **path_ptr)
689 {
690         gchar *path = *path_ptr;
691         CollectManagerAction *action;
692
693         if (path == nullptr)
694                 {
695                 /* get new files */
696                 if (entry->add_list)
697                         {
698                         action = static_cast<CollectManagerAction *>(entry->add_list->data);
699                         g_assert(action->oldpath == nullptr);
700                         entry->add_list = g_list_remove(entry->add_list, action);
701                         path = g_strdup(action->newpath);
702                         g_hash_table_remove(entry->newpath_hash, path);
703                         collect_manager_action_unref(action);
704                         }
705                 *path_ptr = path;
706                 return (path != nullptr);
707                 }
708
709         action = static_cast<CollectManagerAction *>(g_hash_table_lookup(entry->oldpath_hash, path));
710
711         if (action)
712                 {
713                 strcpy(*path_ptr, action->newpath);
714                 return TRUE;
715                 }
716
717         return FALSE; /* no change */
718 }
719
720 static void collect_manager_refresh()
721 {
722         GList *list;
723         GList *work;
724         FileData *dir_fd;
725
726         dir_fd = file_data_new_dir(get_collections_dir());
727         filelist_read(dir_fd, &list, nullptr);
728         file_data_unref(dir_fd);
729
730         work = collection_manager_entry_list;
731         while (work && list)
732                 {
733                 CollectManagerEntry *entry;
734                 GList *list_step;
735
736                 entry = static_cast<CollectManagerEntry *>(work->data);
737                 work = work->next;
738
739                 list_step = list;
740                 while (list_step && entry)
741                         {
742                         FileData *fd;
743
744                         fd = static_cast<FileData *>(list_step->data);
745                         list_step = list_step->next;
746
747                         if (strcmp(fd->path, entry->path) == 0)
748                                 {
749                                 list = g_list_remove(list, fd);
750                                 file_data_unref(fd);
751
752                                 entry = nullptr;
753                                 }
754                         else
755                                 {
756                                 collect_manager_entry_free(entry);
757
758                                 entry = nullptr;
759                                 }
760                         }
761                 }
762
763         work = list;
764         while (work)
765                 {
766                 FileData *fd;
767
768                 fd = static_cast<FileData *>(work->data);
769                 work = work->next;
770
771                 collect_manager_entry_new(fd->path);
772                 }
773
774         filelist_free(list);
775 }
776
777 static void collect_manager_process_actions(gint max)
778 {
779         if (collection_manager_action_list) DEBUG_1("collection manager processing actions");
780
781         while (collection_manager_action_list != nullptr && max > 0)
782                 {
783                 CollectManagerAction *action;
784                 GList *work;
785
786                 action = static_cast<CollectManagerAction *>(collection_manager_action_list->data);
787                 work = collection_manager_entry_list;
788                 while (work)
789                         {
790                         CollectManagerEntry *entry;
791
792                         entry = static_cast<CollectManagerEntry *>(work->data);
793                         work = work->next;
794
795                         if (action->type == COLLECTION_MANAGER_UPDATE)
796                                 {
797                                 collect_manager_entry_add_action(entry, action);
798                                 }
799                         else if (action->oldpath && action->newpath &&
800                                  strcmp(action->newpath, entry->path) == 0)
801                                 {
802                                 /* convert action to standard add format */
803                                 g_free(action->newpath);
804                                 if (action->type == COLLECTION_MANAGER_ADD)
805                                         {
806                                         action->newpath = action->oldpath;
807                                         action->oldpath = nullptr;
808                                         }
809                                 else if (action->type == COLLECTION_MANAGER_REMOVE)
810                                         {
811                                         action->newpath = nullptr;
812                                         }
813                                 collect_manager_entry_add_action(entry, action);
814                                 }
815
816                         max--;
817                         }
818
819                 if (action->type != COLLECTION_MANAGER_UPDATE &&
820                     action->oldpath && action->newpath)
821                         {
822                         log_printf("collection manager failed to %s %s for collection %s\n",
823                                 (action->type == COLLECTION_MANAGER_ADD) ? "add" : "remove",
824                                 action->oldpath, action->newpath);
825                         }
826
827                 if (collection_manager_action_tail == collection_manager_action_list)
828                         {
829                         collection_manager_action_tail = nullptr;
830                         }
831                 collection_manager_action_list = g_list_remove(collection_manager_action_list, action);
832                 collect_manager_action_unref(action);
833                 }
834 }
835
836 static gboolean collect_manager_process_entry(CollectManagerEntry *entry)
837 {
838         CollectionData *cd;
839
840         if (entry->empty) return FALSE;
841
842         cd = collection_new(entry->path);
843         (void) collection_load_private(cd, entry->path, COLLECTION_LOAD_NONE);
844
845         collection_unref(cd);
846
847         return TRUE;
848 }
849
850 static gboolean collect_manager_process_entry_list()
851 {
852         GList *work;
853
854         work = collection_manager_entry_list;
855         while (work)
856                 {
857                 CollectManagerEntry *entry;
858
859                 entry = static_cast<CollectManagerEntry *>(work->data);
860                 work = work->next;
861                 if (collect_manager_process_entry(entry)) return TRUE;
862                 }
863
864         return FALSE;
865 }
866
867
868
869 static gboolean collect_manager_process_cb(gpointer UNUSED(data))
870 {
871         if (collection_manager_action_list) collect_manager_refresh();
872         collect_manager_process_actions(COLLECT_MANAGER_ACTIONS_PER_IDLE);
873         if (collection_manager_action_list) return G_SOURCE_CONTINUE;
874
875         if (collect_manager_process_entry_list()) return G_SOURCE_CONTINUE;
876
877         DEBUG_1("collection manager is up to date");
878         return G_SOURCE_REMOVE;
879 }
880
881 static gboolean collect_manager_timer_cb(gpointer UNUSED(data))
882 {
883         DEBUG_1("collection manager timer expired");
884
885         g_idle_add_full(G_PRIORITY_LOW, collect_manager_process_cb, nullptr, nullptr);
886
887         collection_manager_timer_id = 0;
888         return FALSE;
889 }
890
891 static void collect_manager_timer_push(gint stop)
892 {
893         if (collection_manager_timer_id)
894                 {
895                 if (!stop) return;
896
897                 g_source_remove(collection_manager_timer_id);
898                 collection_manager_timer_id = 0;
899                 }
900
901         if (!stop)
902                 {
903                 collection_manager_timer_id = g_timeout_add(COLLECT_MANAGER_FLUSH_DELAY,
904                                                             collect_manager_timer_cb, nullptr);
905                 DEBUG_1("collection manager timer started");
906                 }
907 }
908
909 static void collect_manager_add_action(CollectManagerAction *action)
910 {
911         if (!action) return;
912
913         /* we keep track of the list's tail to keep this a n(1) operation */
914
915         if (collection_manager_action_tail)
916                 {
917                 collection_manager_action_tail = g_list_append(collection_manager_action_tail, action);
918                 collection_manager_action_tail = collection_manager_action_tail->next;
919                 }
920         else
921                 {
922                 collection_manager_action_list = g_list_append(collection_manager_action_list, action);
923                 collection_manager_action_tail = collection_manager_action_list;
924                 }
925
926         collect_manager_timer_push(FALSE);
927 }
928
929 void collect_manager_moved(FileData *fd)
930 {
931         CollectManagerAction *action;
932         const gchar *oldpath = fd->change->source;
933         const gchar *newpath = fd->change->dest;
934
935         action = collect_manager_action_new(oldpath, newpath, COLLECTION_MANAGER_UPDATE);
936         collect_manager_add_action(action);
937 }
938
939 void collect_manager_add(FileData *fd, const gchar *collection)
940 {
941         CollectManagerAction *action;
942         CollectWindow *cw;
943
944         if (!fd || !collection) return;
945
946         cw = collection_window_find_by_path(collection);
947         if (cw)
948                 {
949                 if (collection_list_find_fd(cw->cd->list, fd) == nullptr)
950                         {
951                         collection_add(cw->cd, fd, FALSE);
952                         }
953                 return;
954                 }
955
956         action = collect_manager_action_new(fd->path, collection, COLLECTION_MANAGER_ADD);
957         collect_manager_add_action(action);
958 }
959
960 void collect_manager_remove(FileData *fd, const gchar *collection)
961 {
962         CollectManagerAction *action;
963         CollectWindow *cw;
964
965         if (!fd || !collection) return;
966
967         cw = collection_window_find_by_path(collection);
968         if (cw)
969                 {
970                 while (collection_remove(cw->cd, fd));
971                 return;
972                 }
973
974         action = collect_manager_action_new(fd->path, collection, COLLECTION_MANAGER_REMOVE);
975         collect_manager_add_action(action);
976 }
977
978 void collect_manager_flush()
979 {
980         collect_manager_timer_push(TRUE);
981
982         DEBUG_1("collection manager flushing");
983         while (collect_manager_process_cb(nullptr));
984 }
985
986 void collect_manager_notify_cb(FileData *fd, NotifyType type, gpointer UNUSED(data))
987 {
988         if (!(type & NOTIFY_CHANGE) || !fd->change) return;
989
990         DEBUG_1("Notify collect_manager: %s %04x", fd->path, type);
991         switch (fd->change->type)
992                 {
993                 case FILEDATA_CHANGE_MOVE:
994                         collect_manager_moved(fd);
995                         break;
996                 case FILEDATA_CHANGE_COPY:
997                         break;
998                 case FILEDATA_CHANGE_RENAME:
999                         collect_manager_moved(fd);
1000                         break;
1001                 case FILEDATA_CHANGE_DELETE:
1002                 case FILEDATA_CHANGE_UNSPECIFIED:
1003                 case FILEDATA_CHANGE_WRITE_METADATA:
1004                         break;
1005                 }
1006 }
1007
1008 static gint collection_manager_sort_cb(gconstpointer a, gconstpointer b)
1009 {
1010         auto char_a = static_cast<const gchar *>(a);
1011         auto char_b = static_cast<const gchar *>(b);
1012
1013         return g_strcmp0(char_a, char_b);
1014 }
1015
1016 /**
1017  * @brief Creates sorted list of collections
1018  * @param[out] names_exc sorted list of collections names excluding extension
1019  * @param[out] names_inc sorted list of collections names including extension
1020  * @param[out] paths sorted list of collection paths
1021  *
1022  * Lists of type gchar.
1023  * Used lists must be freed with string_list_free()
1024  */
1025 void collect_manager_list(GList **names_exc, GList **names_inc, GList **paths)
1026 {
1027         FileData *dir_fd;
1028         GList *list = nullptr;
1029         gchar *name;
1030         FileData *fd;
1031         gchar *filename;
1032
1033         if (names_exc == nullptr && names_inc == nullptr && paths == nullptr)
1034                 {
1035                 return;
1036                 }
1037
1038         dir_fd = file_data_new_dir((get_collections_dir()));
1039
1040         filelist_read(dir_fd, &list, nullptr);
1041
1042         while (list)
1043                 {
1044                 fd = static_cast<FileData *>(list->data);
1045                 filename = g_strdup(filename_from_path(fd->path));
1046
1047                 if (file_extension_match(filename, GQ_COLLECTION_EXT))
1048                         {
1049                         name = remove_extension_from_path(filename);
1050
1051                         if (names_exc != nullptr)
1052                                 {
1053                                 *names_exc = g_list_insert_sorted(*names_exc, g_strdup(name),
1054                                                                                         collection_manager_sort_cb);
1055                                 *names_exc = g_list_first(*names_exc);
1056                                 }
1057                         if (names_inc != nullptr)
1058                                 {
1059                                 *names_inc = g_list_insert_sorted(*names_inc,filename,
1060                                                                                         collection_manager_sort_cb);
1061                                 *names_inc = g_list_first(*names_inc);
1062                                 }
1063                         if (paths != nullptr)
1064                                 {
1065                                 *paths = g_list_insert_sorted(*paths,fd->path,
1066                                                                                         collection_manager_sort_cb);
1067                                 *paths = g_list_first(*paths);
1068                                 }
1069                         g_free(name);
1070                         }
1071                 list = list->next;
1072                 g_free(filename);
1073                 }
1074
1075         filelist_free(list);
1076 }
1077 /* vim: set shiftwidth=8 softtabstop=0 cindent cinoptions={1s: */