Repository navigation
Expand file tree
/
Copy pathapp_util.cpp
More file actions
2237 lines (1917 loc) · 78 KB
/
Copy pathapp_util.cpp
File metadata and controls
2237 lines (1917 loc) · 78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of the Diffractor photo and video organizer
// Copyright 2026 Zac Walker
//
// This program is free software; you can redistribute it and / or modify it
// under the terms of the LGPL License either version 2.1 or later.
// License details are available at https://www.gnu.org/licenses/lgpl-2.1.html
// This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY
// Purpose: Utility functions for file operations including import, sync, and batch
// processing. Handles file renaming, metadata updates, folder synchronization, and the copies
// prepared for sharing.
#include "pch.h"
#include "libdesktop/core/strings.h"
#include "model_display.h"
#include "model_db.h"
#include "app_command_status.h"
#include "app_command_line.h"
#include "app_util.h"
#include "model_index.h"
#include "util_crash_files_db.h"
#include "util_zip.h"
// Process-level state, declared in app_command_line.h and app.h. It is used across the model and
// file layers, so it does not belong to the application frame that used to define it.
command_line_t command_line;
std::function<void(core::file_path path)> test_before_import_rollback_cleanup;
std::function<std::optional<platform::file_op_result>(core::file_path destination)>
test_import_sidecar_write_override;
crash_files_db& crash_files()
{
static crash_files_db instance(platform::probe_data_file("diffractor-files-that-crash.txt"),
crash_files_db::release_tag(s_app_version));
return instance;
}
void flush_open_files_to_crash_files_list()
{
crash_files().flush_open_files();
}
void log_open_files_to_crash_files_list()
{
crash_files().log_open_files();
}
void view_state::modify_items(const df::results_ptr& results, icon_index icon, const std::string_view title,
const df::item_elements& items_to_modify, const metadata_edits& edits,
const view_host_base_ptr& view)
{
batch_edit_spec spec;
spec.make_edits = [edits](core::file_path) { return item_edits{edits, {}}; };
spec.process_type = df::process_items_type::can_save_metadata;
spec.encode_params.jpeg_save_quality = setting.jpeg_save_quality;
// This overload never applies photo edits, so orientation is the only thing that can change what
// is drawn.
spec.changes_presentation = edits.changes_presentation();
modify_items(results, items_to_modify, spec, view);
}
void view_state::modify_items(const df::results_ptr& results, const df::item_elements& items_to_modify,
const batch_edit_spec& spec, const view_host_base_ptr& view)
{
clear_error_items(view);
const auto can_process = df::item_set(items_to_modify).can_process(spec.process_type, true, view);
if (can_process.success())
{
// Handles must stay detached for the whole write, and the destructor touches UI-owned
// state (display, player, selection), so the last reference is handed to the closing UI
// callback. A stack object would reopen the files while the background write is running
// whenever the caller's status does not block (view_command_status::wait_for_complete).
const auto detach = std::make_shared<detach_file_handles>(*this);
struct modify_request
{
index_state::item_scan_request scan;
core::cached name;
core::file_path path;
core::cached xmp;
};
std::vector<modify_request> requests;
requests.reserve(items_to_modify.size());
std::vector<core::file_path> claimed;
claimed.reserve(items_to_modify.size());
for (const auto& item : items_to_modify)
{
// A write that cannot change what is drawn leaves the existing thumbnail correct, so the
// post-write rescan must not regenerate it. Re-decoding one is slow on large video and
// republishing it makes the tile visibly blank and reappear.
const auto load_thumbnail = spec.changes_presentation || !item->has_thumb();
requests.emplace_back(item_index.make_scan_request(item, load_thumbnail, false), item->name(),
item->path(), item->xmp());
claimed.emplace_back(item->path());
}
// Declared here, on the UI thread and before the write starts, so the modified time it
// produces does not send the thumbnail and the displayed image back through a reload that
// would return the same result.
if (!spec.changes_presentation)
{
for (const auto& item : items_to_modify)
{
item->retain_thumbnail_across_next_write();
}
if (const auto d = display_state())
{
const auto is_modified = [&items_to_modify](const df::item_element_ptr& i)
{
if (!i) return false;
for (const auto& item : items_to_modify) if (item == i) return true;
return false;
};
if (d->_selected_texture1 && is_modified(d->_item1)) d->_selected_texture1->mark_visuals_current();
if (d->_selected_texture2 && is_modified(d->_item2)) d->_selected_texture2->mark_visuals_current();
}
}
// No read of these files may be queued while the write runs; anything asked for meanwhile is
// deferred and re-requested on release.
item_index.claim_for_write(claimed);
queue_async(async_queue::work,
[this, requests = std::move(requests), claimed = std::move(claimed), spec, results, detach,
displayed_paths = spec.changes_presentation
? displayed_photo_paths()
: std::vector<core::file_path>{},
detached_av_path = detached_display_av_path()]() mutable
{
result_scope rr(results);
std::string message;
files ff;
// Only the UI hop at the end releases the claim, and drain_queue swallows an
// exception before it is ever posted - which parks these items with no thumbnail and
// no metadata refresh for the rest of the session. The release is therefore owned by
// a guard rather than by the success path. The guard keeps its own copy of the paths
// because the success path moves the originals into the UI callback.
auto claim_handed_over = false;
core::scope_exit release_claim([this, &claim_handed_over, claimed]
{
if (!claim_handed_over)
{
_async.queue_ui([this, claimed] { item_index.release_write_claim(claimed); });
}
});
// Items the write already re-scanned for us vs. those whose scan failed and still need a
// forced background rescan.
std::vector<index_state::item_scan_request> immediate_done;
std::vector<index_state::item_scan_request> needs_force;
// The written bytes for each item on screen, handed over instead of read back. The modified
// time travels with them so the display stamps in the file clock domain.
struct written_image
{
core::file_path path;
file_load_result loaded;
core::date_t modified;
};
std::vector<written_image> written_images;
// The open handle over the playable item the display is about to reopen.
platform::file_ptr detached_av_handle;
for (const auto& request : requests)
{
// Asked before the write, not after it. A cancel that arrived while the
// previous item was being written - or before this loop started at all -
// must not reach one more file, and the row it stops at is reported as the
// cancellation it was rather than left out of the result list entirely.
if (results->is_canceled())
{
results->end_item(request.name, item_status::cancel);
continue;
}
results->start_item(request.name);
const auto edits = spec.make_edits(request.path);
file_update_result update_result;
const auto is_displayed = std::ranges::find(displayed_paths, request.path) !=
displayed_paths.end();
if (edits)
{
update_result = ff.update(request.path, request.path, edits->metadata, edits->image,
spec.encode_params, false, request.xmp, request.xmp,
index_state::make_rescan_spec(request.scan, request.xmp,
is_displayed,
request.path == detached_av_path));
}
results->end_item(request.name, to_status(update_result.code));
if (!update_result.success())
{
if (failed_write_needs_forced_rescan(update_result))
{
needs_force.emplace_back(request.scan);
}
message = update_result.format_error();
break;
}
if (request.path == detached_av_path) detached_av_handle = std::move(
update_result.display_handle);
if (is_displayed)
{
written_images.emplace_back(request.path, std::move(update_result.loaded),
core::date_t(update_result.modified));
}
if (item_index.apply_write_scan(request.scan, update_result))
{
needs_force.emplace_back(request.scan);
}
else
{
immediate_done.emplace_back(request.scan);
}
}
// Background rescan: force the items whose immediate scan failed (the mtime-tie heuristic
// can miss a rapid successive edit whose sidecar modified time ties with the previous scan
// timestamp); the scanned items are already current, so queue them non-forced as a cheap
// no-op safety net. The detach reference is handed over here so the handles stay
// detached until the writes finish and the destructor runs on the UI thread.
_async.queue_ui(
[this, detach = std::move(detach), claimed = std::move(claimed), immediate_done =
std::move(immediate_done), needs_force = std::move(needs_force), written_images =
std::move(written_images), detached_av_path, detached_av_handle = std::move(
detached_av_handle)]() mutable
{
item_index.release_write_claim(claimed);
for (auto& written : written_images)
{
publish_written_image(written.path, std::move(written.loaded), written.modified);
}
// Before the guard is released below, because releasing it is what reopens the session.
publish_written_handle(detached_av_path, std::move(detached_av_handle));
df::item_set immediate_items;
df::item_set force_items;
for (const auto& request : immediate_done)
{
const auto item = request.lifetime.lock();
if (item && item->path() == request.path) immediate_items.add(item);
}
for (const auto& request : needs_force)
{
const auto item = request.lifetime.lock();
if (item && item->path() == request.path) force_items.add(item);
}
if (!force_items.empty()) item_index.queue_scan_modified_items(
std::move(force_items), true);
if (!immediate_items.empty()) item_index.queue_scan_modified_items(
std::move(immediate_items), false);
});
claim_handed_over = true;
rr.complete(message);
});
results->wait_for_complete();
}
else
{
results->show_message(can_process.to_string());
}
}
static platform::file_op_result move_or_copy(const core::file_path source_path, const core::file_path dest_path,
const bool is_move, const bool fail_if_exists)
{
return is_move
? platform::move_file(source_path, dest_path, fail_if_exists)
: platform::copy_file(source_path, dest_path, fail_if_exists, false);
}
static platform::file_op_result delete_temp_file(const core::file_path path)
{
if (path.is_empty()) return {platform::file_op_result_code::OK};
if (!platform::exists(path)) return {platform::file_op_result_code::OK};
platform::make_file_writable(path);
const auto result = platform::delete_file(path);
if (result.failed())
{
core::log(__FUNCTION__, std::format("could not delete temporary file {}; {}", path.str(), result.format_error()));
}
return result;
}
static core::file_path rename_destination(const rename_source& item, const std::string_view name)
{
const auto source = item.source;
return item.is_folder
? core::file_path(source.folder().parent(), name)
: core::file_path(source.folder(), name, source.extension());
}
bool rename_path_exists(const core::file_path path, const bool is_folder)
{
return is_folder ? platform::exists(path.folder().combine(path.name())) : platform::exists(path);
}
std::string rename_path_key(const core::file_path path, const bool is_folder)
{
return is_folder ? std::string(path.folder().combine(path.name()).text()) : path.pack();
}
std::vector<rename_source> snapshot_rename_sources(const df::item_set& items)
{
std::vector<rename_source> result;
result.reserve(items.size());
for (const auto& item : items.items())
{
rename_source source;
source.source = item->path();
source.original_name = item->base_name();
source.metadata = item->metadata();
source.media_created = item->calc_media_created();
source.is_folder = item->is_folder();
if (!source.is_folder)
for (const auto& sidecar_name : split(item->sidecars(), true))
source.sidecars.emplace_back(source.source.folder().combine_file(sidecar_name));
result.emplace_back(std::move(source));
}
return result;
}
// A RAW and the camera's JPEG beside it share a sidecar by name, and both rows listed it, so a rename
// moved it twice: the second move failed that row or, with the JPEG first, carried the RAW's ratings
// and develop settings off to the JPEG's new name. The sidecar stays with one row - the first whose
// file keeps no packet of its own, which is the file that reads it, or else the first.
static void assign_shared_rename_sidecars(std::vector<rename_source>& sources)
{
core::hash_map<core::file_path, size_t, core::ihash, core::ieq> owner;
const auto reads_sidecar = [&sources](const size_t row)
{
const auto* const ft = files::file_type_from_name(sources[row].source);
return ft && !ft->has_trait(file_traits::embedded_xmp);
};
for (size_t row = 0; row < sources.size(); ++row)
{
for (const auto& sidecar : sources[row].sidecars)
{
const auto [found, added] = owner.try_emplace(sidecar, row);
if (!added && found->second != row && !reads_sidecar(found->second) && reads_sidecar(row))
{
found->second = row;
}
}
}
for (size_t row = 0; row < sources.size(); ++row)
{
std::erase_if(sources[row].sidecars, [&owner, row](const core::file_path& sidecar)
{
return owner.at(sidecar) != row;
});
}
}
std::vector<rename_item> calc_item_renames(const std::vector<rename_source>& sources,
const std::string_view template_name,
const int start, const collision_policy policy)
{
auto items = sources;
assign_shared_rename_sidecars(items);
std::vector<rename_item> results;
results.reserve(items.size());
std::vector<char> name_is_usable;
name_is_usable.reserve(items.size());
// Every path this plan moves away from. A destination held by one of them is free by the time
// the run reaches it, so renaming a set onto the names it is vacating is not a collision.
std::set<std::string, core::path_key_less> vacated;
auto seq = start;
const auto assign_sidecars = [](rename_item& rename, const rename_source& i, const core::file_path primary)
{
rename.sidecars.clear();
rename.sidecar_destinations_exist.clear();
rename.sidecar_source_attributes.clear();
rename.sidecar_destination_attributes.clear();
if (i.is_folder) return;
for (const auto sidecar_source : i.sidecars)
{
const auto sidecar_destination = moved_sidecar_path(i.source, primary, sidecar_source);
const auto destination_attributes = platform::file_attributes(sidecar_destination);
rename.sidecar_destinations_exist.emplace_back(destination_attributes.exists());
rename.sidecar_source_attributes.emplace_back(platform::file_attributes(sidecar_source));
rename.sidecar_destination_attributes.emplace_back(destination_attributes);
rename.sidecars.emplace_back(sidecar_source, sidecar_destination);
}
};
for (const auto& i : items)
{
const auto& md = i.metadata;
const auto& original_name = i.original_name;
auto name = format_sequence(original_name, template_name, seq);
name = prop::replace_tokens(name, md, original_name, i.media_created);
rename_item rename;
rename.source = i.source;
rename.is_folder = i.is_folder;
rename.source_attributes = i.is_folder ? platform::file_attributes_t{} : platform::file_attributes(i.source);
rename.policy = policy;
rename.original_name = original_name;
rename.new_name = name;
rename.destination = rename_destination(i, name);
const auto source_key = rename_path_key(rename.source, rename.is_folder);
const auto destination_key = rename_path_key(rename.destination, rename.is_folder);
rename.noop = source_key == destination_key;
assign_sidecars(rename, i, rename.destination);
// A case-only rename does not free the path it renames within, so it vacates nothing - but only
// where the filesystem agrees the two spellings are one path.
if (core::compare_path_key(source_key, destination_key) != 0)
{
vacated.emplace(source_key);
for (const auto& [sidecar_source, sidecar_destination] : rename.sidecars)
if (core::compare_path_key(sidecar_source.pack(), sidecar_destination.pack()) != 0)
vacated.emplace(sidecar_source.pack());
}
name_is_usable.emplace_back(
platform::is_valid_file_name(name) && rename.destination.is_save_valid() ? 1 : 0);
seq += 1;
results.emplace_back(std::move(rename));
}
// Resolve the collision with the one named policy before validity is decided.
for (auto index = 0_z; index < results.size(); ++index)
{
auto& rename = results[index];
const auto& i = items[index];
const auto source_key = rename_path_key(rename.source, rename.is_folder);
auto group_collides = [&]
{
const auto destination_key = rename_path_key(rename.destination, rename.is_folder);
rename.destination_exists = rename_path_exists(rename.destination, rename.is_folder);
rename.destination_attributes = rename.is_folder
? platform::file_attributes_t{}
: platform::file_attributes(rename.destination);
if (core::compare_path_key(source_key, destination_key) != 0 && rename.destination_exists &&
!vacated.contains(destination_key))
return true;
for (auto sidecar = 0_z; sidecar < rename.sidecars.size(); ++sidecar)
{
const auto& [sidecar_source, sidecar_destination] = rename.sidecars[sidecar];
if (core::compare_path_key(sidecar_source.pack(), sidecar_destination.pack()) != 0 &&
rename.sidecar_destinations_exist[sidecar] &&
!vacated.contains(sidecar_destination.pack()))
return true;
}
return false;
};
rename.collides = group_collides();
if (rename.collides && policy == collision_policy::auto_rename)
{
const auto base_name = rename.new_name;
const auto base_destination = rename.destination;
for (auto suffix = 2; suffix < 10000; ++suffix)
{
const auto candidate = std::format("{} ({})", base_name, suffix);
rename.destination = core::file_path(rename.destination.folder(), candidate,
rename.destination.extension());
assign_sidecars(rename, i, rename.destination);
if (!group_collides())
{
rename.new_name = std::string(rename.destination.file_name_without_extension());
rename.renamed_to_avoid_collision = true;
rename.collides = false;
break;
}
}
// Exhausted: the row stays invalid, but it must not keep pointing at the last candidate.
// destination feeds the duplicate-destination pass, so a name this row will never write
// would invalidate whichever row legitimately asked for it.
if (rename.collides)
{
rename.destination = base_destination;
assign_sidecars(rename, i, rename.destination);
}
}
else if (rename.collides && policy == collision_policy::skip)
{
rename.skipped = true;
rename.noop = true;
// Resolved, so the row must not keep the whole batch invalid. The duplicate-destination
// pass below still re-sets it for collisions no policy can resolve.
rename.collides = false;
}
rename.valid = name_is_usable[index] != 0 && (!rename.collides || policy == collision_policy::replace);
}
if (policy == collision_policy::skip)
{
// Skip resolves a collision by leaving the source where it is, so it no longer frees that
// path for whatever row was cleared to take it, and settling that can cascade.
std::map<std::string, size_t, core::path_key_less> wanted;
for (auto index = 0_z; index < results.size(); ++index)
{
wanted.emplace(rename_path_key(results[index].destination, results[index].is_folder), index);
for (const auto& sidecar : results[index].sidecars) wanted.emplace(sidecar.second.pack(), index);
}
std::vector<size_t> stalled;
for (auto index = 0_z; index < results.size(); ++index)
if (results[index].skipped) stalled.emplace_back(index);
while (!stalled.empty())
{
const auto& stalled_row = results[stalled.back()];
stalled.pop_back();
std::vector<std::string> released{rename_path_key(stalled_row.source, stalled_row.is_folder)};
for (const auto& sidecar : stalled_row.sidecars) released.emplace_back(sidecar.first.pack());
for (const auto& key : released)
{
if (vacated.erase(key) == 0) continue;
const auto found = wanted.find(key);
if (found == wanted.end()) continue;
auto& blocked = results[found->second];
if (blocked.noop) continue;
blocked.skipped = true;
blocked.noop = true;
stalled.emplace_back(found->second);
}
}
}
// Two rows targeting the same new name is a collision the policy cannot resolve
// safely without reordering, so it always blocks.
std::map<std::string, int, core::path_key_less> destination_counts;
for (const auto& rename : results)
{
++destination_counts[rename_path_key(rename.destination, rename.is_folder)];
for (const auto& sidecar : rename.sidecars) ++destination_counts[sidecar.second.pack()];
}
for (auto& rename : results)
{
const auto duplicates = destination_counts[rename_path_key(rename.destination, rename.is_folder)] > 1 ||
std::ranges::any_of(rename.sidecars, [&](const auto& sidecar)
{
return destination_counts[sidecar.second.pack()] > 1;
});
if (duplicates)
{
rename.valid = false;
rename.collides = true;
rename.skipped = false;
rename.renamed_to_avoid_collision = false;
}
}
return results;
}
std::vector<rename_item> calc_item_renames(const df::item_set& items, const std::string_view template_name,
const int start, const collision_policy policy)
{
return calc_item_renames(snapshot_rename_sources(items), template_name, start, policy);
}
bool can_rename_items(const std::vector<rename_item>& renames)
{
return !renames.empty() && std::ranges::all_of(renames, [](const rename_item& item) { return item.valid; }) &&
std::ranges::any_of(renames, [](const rename_item& item) { return !item.noop; });
}
int count_rename_collisions(const std::vector<rename_item>& renames, const collision_policy policy)
{
const auto count = [&renames](auto&& predicate)
{
return static_cast<int>(std::ranges::count_if(renames, predicate));
};
switch (policy)
{
case collision_policy::skip: return count([](const rename_item& item) { return item.skipped; });
case collision_policy::auto_rename: return count([](const rename_item& item)
{
return item.renamed_to_avoid_collision;
});
case collision_policy::replace:
case collision_policy::block_run: break;
}
return count([](const rename_item& item) { return item.collides; });
}
std::string format_sequence(const std::string_view original_name, const std::string_view template_name,
const int seq)
{
static auto numbers = "0123456789";
std::string result;
if (!template_name.empty())
{
const auto reverse_template = std::string(template_name.rbegin(), template_name.rend());
const auto reverse_name = std::string(original_name.rbegin(), original_name.rend());
const auto org_len = reverse_name.size();
// A start typed below zero has no digits to write: each one taken from it was a character from
// before the digit table.
auto i_div = std::max(seq, 0);
auto original_index = 0u;
const auto sequence_digits = static_cast<int>(
std::count(reverse_template.begin(), reverse_template.end(), '#'));
auto sequence_placeholders = sequence_digits;
for (const auto c : reverse_template)
{
switch (c)
{
case L'#':
result.push_back(numbers[i_div % 10]);
i_div /= 10;
--sequence_placeholders;
if (sequence_placeholders == 0)
{
while (i_div > 0)
{
result.push_back(numbers[i_div % 10]);
i_div /= 10;
}
}
break;
case L'?':
result.push_back(org_len > original_index ? reverse_name[original_index] : ' ');
++original_index;
break;
default:
result.push_back(c);
break;
}
}
}
return std::string(result.rbegin(), result.rend());
}
bool unchanged_since_analysis(const core::file_path path, const uint64_t modified, const uint64_t size)
{
const auto current = platform::file_attributes(path);
return current.exists() && current.modified == modified && current.size == size;
}
import_analysis_result import_analysis(const std::vector<folder_scan_item>& src_items,
const import_options& options, const item_import_set& previous_imported,
const core::cancel_token& token)
{
import_analysis_result result;
const auto now = core::utc_now();
// Destinations already claimed by earlier items in this plan. Two sources can resolve to the
// same destination (the same file name in different source folders), which the file system
// cannot report because nothing has been written yet. Without this, Replace would silently
// discard one source and Auto-rename would hand both the same free name.
core::unique_paths planned_destinations;
core::unique_paths attached_sidecars;
for (const auto& item : src_items)
{
if (token.is_cancelled()) return result;
if (const auto md = item.item.metadata.load())
for (const auto& name : split(md->sidecars, true))
{
const auto sidecar = item.folder.combine_file(name);
if (sidecar != item.folder.combine_file(item.item.name)) attached_sidecars.emplace(sidecar);
}
}
core::hash_map<core::file_path, core::file_path, core::ihash, core::ieq> sidecar_owners;
for (const auto& i : src_items)
{
if (token.is_cancelled()) break;
const auto md = i.item.metadata.load();
core::date_t created;
if (md)
{
created = md->created();
}
const auto import_folder_out = replace_tokens(options.dest_structure, md, i.item.name, i.item.created());
const auto path_in = i.folder.combine_file(i.item.name);
if (attached_sidecars.contains(path_in)) continue;
auto path_out = options.dest_folder.combine(import_folder_out).combine_file(path_in.name());
const auto import_rec = item_import{i.item.name, i.item.file_modified, i.item.size, now};
std::vector<core::file_path> sidecar_paths_in;
if (md)
{
for (const auto& file_name : split(md->sidecars, true))
{
const auto sidecar_path_in = i.folder.combine_file(file_name);
if (sidecar_path_in != path_in &&
std::ranges::find(sidecar_paths_in, sidecar_path_in) == sidecar_paths_in.end())
sidecar_paths_in.emplace_back(sidecar_path_in);
}
}
auto sidecar_destination = [&path_in](const core::file_path primary, const core::file_path sidecar)
{
return moved_sidecar_path(path_in, primary, sidecar);
};
auto group_exists = [&](const core::file_path primary)
{
if (platform::exists(primary) || planned_destinations.contains(primary)) return true;
return std::ranges::any_of(sidecar_paths_in,
[&](const auto sidecar)
{
const auto destination = sidecar_destination(primary, sidecar);
const auto owner = sidecar_owners.find(destination);
return platform::exists(destination) ||
(planned_destinations.contains(destination) &&
(owner == sidecar_owners.end() || owner->second != sidecar));
});
};
const bool already_exists = group_exists(path_out);
// One explicit collision policy decides what happens when the destination exists.
// Auto-rename resolves the whole media/sidecar group with one shared suffix.
auto blocked_by_collision = false;
if (already_exists)
{
switch (options.collision)
{
case collision_policy::auto_rename:
for (auto suffix = 2; suffix < 10000; ++suffix)
{
const auto candidate = core::file_path(path_out.folder(),
std::format("{} ({})", path_out.file_name_without_extension(),
suffix), path_out.extension());
if (!group_exists(candidate))
{
path_out = candidate;
break;
}
}
break;
case collision_policy::replace:
break;
case collision_policy::skip:
case collision_policy::block_run:
blocked_by_collision = true;
break;
}
}
const auto action = previous_imported.contains(import_rec) ? import_action::already_imported :
blocked_by_collision ? import_action::already_exists : import_action::import;
const auto importing = action == import_action::import;
std::vector<import_analysis_item::sidecar_move> sidecars;
sidecars.reserve(sidecar_paths_in.size());
for (const auto sidecar_path_in : sidecar_paths_in)
{
const auto sidecar_path_out = sidecar_destination(path_out, sidecar_path_in);
sidecars.emplace_back(sidecar_path_in, sidecar_path_out,
importing ? platform::file_attributes(sidecar_path_in) : platform::file_attributes_t{},
importing && options.collision == collision_policy::replace
? platform::file_attributes(sidecar_path_out)
: platform::file_attributes_t{});
if (importing)
{
planned_destinations.emplace(sidecar_path_out);
sidecar_owners.emplace(sidecar_path_out, sidecar_path_in);
}
}
// Ignored rows retain their dependencies, so Move cannot remove a companion they still need.
const auto destination_fi = importing && options.collision == collision_policy::replace
? platform::file_attributes(path_out)
: platform::file_attributes_t{};
result[path_out.folder()].emplace_back(path_in, path_out, action, created, import_rec,
already_exists, import_folder_out,
importing ? platform::file_attributes(path_in) : platform::file_attributes_t{},
destination_fi, std::move(sidecars));
if (importing) planned_destinations.emplace(path_out);
}
return result;
}
import_result import_copy(index_state& index, df::results_ptr results, const import_analysis_result& src_items,
const import_options& options, core::cancel_token token)
{
import_result result;
result_scope rr(results);
std::vector<folder_scan_item> existing;
std::vector<folder_scan_item> previous;
core::unique_folders write_folders;
struct import_group_state
{
bool attempted = false;
bool success = true;
};
core::hash_map<item_import, import_group_state, item_import_hash, item_import_eq> import_states;
struct published_sidecar
{
core::file_path source;
platform::file_attributes_t attributes;
};
core::hash_map<core::file_path, published_sidecar, core::ihash, core::ieq> published_sidecars;
core::hash_map<core::file_path, size_t, core::ihash, core::ieq> sidecar_consumers;
std::string sidecar_cleanup_error;
// Set when a destination folder cannot be made. The run stops there, but everything already
// written still has to be recorded and rescanned below - returning from the middle of the walk
// lost both, so a later run imported those files again and the index never saw them.
std::string abort_message;
for (const auto& ff_dest : src_items)
{
for (const auto& item : ff_dest.second)
{
if (item.action == import_action::import) import_states.try_emplace(item.import_rec);
if (options.is_move)
for (const auto& sidecar : item.sidecars) ++sidecar_consumers[sidecar.source];
}
}
for (const auto& ff_dest : src_items)
{
const auto folder_out = ff_dest.first;
if (token.is_cancelled())
{
for (const auto& item : ff_dest.second)
{
if (item.action == import_action::import)
{
import_states[item.import_rec].success = false;
results->start_item(item.source.name());
results->end_item(item.source.name(), item_status::cancel);
}
else
{
results->end_item(item.source.name(), item_status::ignore);
}
}
continue;
}
// Nothing is written here when every item was already imported or resolved away by the
// collision policy, so do not create a destination folder that would stay empty.
const auto has_imports = std::ranges::any_of(ff_dest.second,
[](const auto& item)
{
return item.action == import_action::import;
});
if (has_imports)
{
const bool folder_out_exists = platform::exists(folder_out);
const auto create_folder_result = folder_out_exists
? platform::file_op_result{platform::file_op_result_code::OK, {}, {}}
: platform::create_folder(folder_out);
if (create_folder_result.failed())
{
abort_message = create_folder_result.format_error(
str_format(tt.error_create_folder_failed_fmt.sv(), folder_out));
break;
}
write_folders.emplace(folder_out);
}
for (const auto& i : ff_dest.second)
{
// Every reviewed row is accounted for in the results, so a file that was skipped or
// already imported is stated as ignored rather than dropping out of the list.
if (i.action != import_action::import)
{
results->end_item(i.source.name(), item_status::ignore);
continue;
}
if (results->is_canceled())
{
import_states[i.import_rec].success = false;
results->start_item(i.source.name());
results->end_item(i.source.name(), item_status::cancel);
continue;
}
results->start_item(i.source.name());
const auto path_in = i.source;
const auto path_out = i.destination;
// Only the Replace policy is allowed to write over an existing destination.
const auto fail_if_exists = options.collision != collision_policy::replace;
// ...and only over the destination the review actually saw. A Replace row whose destination
// was free at analysis is not a reviewed replacement, so the write itself has to prove the
// path is still free rather than overwriting whatever appeared since.
const auto primary_fail_if_exists = fail_if_exists || !i.destination_fi.exists();
// The reviewed row named specific files. A source that no longer matches would import
// content nobody approved, and under Replace a changed destination would be written over
// without ever having been reviewed. Neither is recoverable once the write starts, and
// the sidecars are held to it too - they travel as part of the group, so a group that is
// no longer what was reviewed cannot be written at either end.
const auto reviewed_source = [](const core::file_path path, const platform::file_attributes_t& reviewed)
{
return unchanged_since_analysis(path, reviewed.modified, reviewed.size);
};
const auto reviewed_destination = [fail_if_exists](const core::file_path path,
const platform::file_attributes_t& reviewed)
{
return fail_if_exists || !reviewed.exists() ||
unchanged_since_analysis(path, reviewed.modified, reviewed.size);
};
const auto source_unchanged = reviewed_source(path_in, i.source_fi) &&
std::ranges::all_of(i.sidecars, [&reviewed_source](const import_analysis_item::sidecar_move& sc)
{
return reviewed_source(sc.source, sc.source_fi);
});
const auto destination_unchanged = reviewed_destination(path_out, i.destination_fi) &&
std::ranges::all_of(i.sidecars, [&](const import_analysis_item::sidecar_move& sc)
{
if (const auto found = published_sidecars.find(sc.destination); found != published_sidecars.end())
return found->second.source == sc.source &&
reviewed_source(sc.destination, found->second.attributes);
return reviewed_destination(sc.destination, sc.destination_fi);
});
if (!source_unchanged || !destination_unchanged)
{
auto& state = import_states[i.import_rec];
state.attempted = true;
state.success = false;
results->end_item(i.source.name(), item_status::fail);
++result.refused;
continue;
}
struct sidecar_undo
{
core::file_path source;
core::file_path destination;
core::file_path rollback;
};
// Copy companions before moving a primary. A shared source stays until every dependent
// primary has moved; a failed row only undoes companion destinations it created itself.
auto undo_sidecar = [&](const sidecar_undo& undo)
{
write_folders.emplace(undo.source.folder());
write_folders.emplace(undo.destination.folder());
platform::file_op_result undo_result{platform::file_op_result_code::OK, {}, {}};
if (!undo.rollback.is_empty())