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