Repository navigation
Expand file tree
/
Copy pathmodel.cpp
More file actions
5619 lines (4707 loc) · 176 KB
/
Copy pathmodel.cpp
File metadata and controls
5619 lines (4707 loc) · 176 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: Application view state management. Coordinates display state, media playback,
// selection handling, navigation history, and view mode transitions.
#include "pch.h"
#include "model.h"
#include "model_display.h"
#include "model_index.h"
#include "app_command_line.h"
#include "files.h"
#include "model_items.h"
#include "av_visualizer.h"
#include "av_format.h"
#include "metadata_xmp.h"
#include "ui_dialog.h"
#include "ui_controls.h"
#include "app_command_status.h"
static constexpr sizei video_preview_size = {256, 256};
// A hovered thumbnail tells the user what the video contains, not where they are in it, so a frame
// anywhere within this fraction of the duration answers the hover. The scrubber has no such slack:
// it promises the frame playback will jump to.
static constexpr double hover_thumbnail_tolerance = 0.02;
fast_fft av_visualizer::fft;
static bool av_can_use_hw()
{
return setting.use_d3d11va && !command_line.no_gpu && setting.use_gpu &&
!platform::crash_guard_suppressed(platform::crash_guard::gpu_render);
}
df::folder_path view_state::save_path() const
{
if (!_search.has_selector()) return known_path(platform::known_folder::pictures);
return _search.selectors().front().folder();
}
int view_state::displayed_rating() const
{
for (const auto& i : _selected.items())
{
const auto md = i->metadata();
if (md && md->rating)
{
return md->rating;
}
}
return 0;
}
void view_state::toggle_rating(const df::results_ptr& results, const df::item_elements& items, const int r,
const view_host_base_ptr& view)
{
bool add_rating = false;
if (r != 0)
{
for (const auto& i : items)
{
const auto md = i->metadata();
if (md && md->rating != r)
{
add_rating = true;
}
}
}
metadata_edits edits;
if (add_rating)
{
edits.rating = r;
}
else
{
edits.remove_rating = true;
}
modify_items(results, icon_index::star, tt.title_rate, items, edits, view);
}
void view_state::modify_items(const ui::control_frame_ptr& frame, const 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)
{
auto dlg = make_dlg(frame);
const auto results = std::make_shared<command_status>(_async, dlg, icon, title, selected_count());
modify_items(results, icon, title, items_to_modify, edits, view);
}
void display_state_t::load_compare_preview(const int elapsed_numerator, const int elapsed_denominator)
{
if (_is_compare_video && df::file_handles_detached == 0)
{
const auto i1 = _item1;
const auto i2 = _item2;
const auto st1 = _selected_texture1;
const auto st2 = _selected_texture2;
const auto md1 = i1->metadata();
const auto md2 = i2->metadata();
const auto duration1 = md1 ? std::max(1, static_cast<int>(md1->duration)) : 1;
const auto duration2 = md2 ? std::max(1, static_cast<int>(md2->duration)) : 1;
const auto max_duration = std::max(duration1, duration2);
const auto elapsed = std::clamp(df::mul_div(elapsed_numerator, max_duration,
std::max(1, elapsed_denominator)), 0, max_duration);
const auto pos1 = std::min(elapsed, duration1);
const auto pos2 = std::min(elapsed, duration2);
// Detached on the UI thread: item_element is UI-owned, so the worker gets values, not items.
const auto path1 = i1->path();
const auto path2 = i2->path();
// The pane these land in, not the hover popup's 256 square: a compare pane is half the media
// area, so the hover constant would upscale visibly. Decoding at the source's own size is
// the other end of the same mistake - two 4K frames per pointer move, past the texture budget.
const auto pane1 = st1->display_bounds().extent();
const auto pane2 = st2->display_bounds().extent();
const auto max_dim1 = pane1.is_empty() ? video_preview_size : pane1;
const auto max_dim2 = pane2.is_empty() ? video_preview_size : pane2;
_async.queue_media_preview(
[t = ui_owned(_async, shared_from_this()), path1, path2, st1 = ui_owned(_async, st1),
st2 = ui_owned(_async, st2), pos1, pos2, duration1, duration2, max_dim1, max_dim2](
media_preview_state& decoder)
{
if (decoder.open1(path1) &&
decoder.open2(path2))
{
auto surface1 = std::make_shared<ui::surface>();
auto surface2 = std::make_shared<ui::surface>();
if (decoder.decoder1->extract_seek_frame(surface1, max_dim1, pos1, duration1) &&
decoder.decoder2->extract_seek_frame(surface2, max_dim2, pos2, duration2))
{
t->_async.queue_ui([t, st1, st2, surface1, surface2]
{
// The compared pair can be swapped out while the two seeks are in flight.
if (t->_selected_texture1.get() != st1.get() ||
t->_selected_texture2.get() != st2.get())
return;
st1->update(surface1);
st2->update(surface2);
t->_async.invalidate_view(view_invalid::view_redraw);
});
}
}
});
}
}
void display_state_t::load_seek_preview(int pos_numerator, int pos_denominator, std::function<void()> callback)
{
const auto item = _item1;
if (player_has_video() && item && item->online_status() == df::item_online_status::disk && df::file_handles_detached
== 0)
{
// Detached on the UI thread: the worker gets the path, and the item travels only as a
// UI-owned currency token that is compared after the hop back.
const auto path = item->path();
_async.queue_media_preview(
[t = ui_owned(_async, shared_from_this()), item = ui_owned(_async, item), path, pos_numerator,
pos_denominator, callback](
media_preview_state& decoder)
{
if (decoder.open1(path))
{
auto surface = std::make_shared<ui::surface>();
if (decoder.decoder1->extract_seek_frame(surface, video_preview_size, pos_numerator,
pos_denominator, decoder.abandon_token()))
{
t->_async.queue_ui([t, item, surface = std::move(surface), callback]() mutable
{
// The display item can change while the seek decodes; a preview of the
// previous video must not become the current hover surface.
if (t->_item1.get() != item.get()) return;
t->_hover_surface = std::move(surface);
callback();
});
}
}
});
}
}
void display_state_t::update_av_session(const std::shared_ptr<av_session>& ses)
{
if (_session != ses)
{
_session = ses;
// The latch belongs to the clip that ended, not to the display.
_media_end_handled = false;
}
_av_open_failed = !ses;
if (ses)
{
_player_media_info = ses->info();
_full_metadata_loaded = true;
load_xmp_sidecar();
}
else
{
load_selected_item_data();
}
_async.invalidate_view(
view_invalid::view_layout |
view_invalid::screen_saver |
view_invalid::media_elements |
view_invalid::command_state);
}
void display_state_t::load_selected_item_data()
{
df::assert_true(ui::is_ui_thread());
const auto item = _item1;
if (!item) return;
_async.queue_async(async_queue::load,
[self = ui_owned(_async, shared_from_this()), path = item->path()]
{
df::scope_locked_inc l(df::loading_media);
// Shared because the UI task is stored in a std::function, which requires a copyable target.
auto data = std::make_shared<df::blob>(blob_head_from_file(path, df::one_meg));
self->_async.queue_ui([self, data]
{
self->_selected_item_data = std::move(*data);
self->_async.invalidate_view(
view_invalid::media_elements | view_invalid::view_layout);
});
});
}
void display_state_t::load_xmp_sidecar()
{
df::assert_true(ui::is_ui_thread());
const auto item = _item1;
if (!item) return;
const auto xmp_name = item->xmp();
if (xmp_name.is_empty()) return;
for (const auto& b : _player_media_info.metadata)
{
if (b.standard == metadata_standard::xmp) return;
}
const auto sidecar = item->path().folder().combine_file(xmp_name.sv());
const auto generation = _av_generation;
_async.queue_async(async_queue::load, [weak = weak_from_this(), &async = _async, sidecar, generation]
{
const auto packet = df::blob_from_file(sidecar);
if (packet.empty()) return;
bool parsed = false;
auto kv = metadata_xmp::to_info(packet, parsed);
// The packet is the block's real content, so it stays reachable whether or not the toolkit
// could make a tree from it.
constexpr size_t max_raw_bytes = 256 * 1024;
std::string raw;
raw.assign(std::bit_cast<const char*>(packet.data()), std::min(packet.size(), max_raw_bytes));
metadata_block block(metadata_standard::xmp, std::move(kv), packet.size(), parsed, std::move(raw));
async.queue_ui([weak, block = std::move(block), generation]() mutable
{
const auto t = weak.lock();
// A newer open has the display; its own sidecar read will publish.
if (!t || t->_av_generation != generation) return;
for (const auto& b : t->_player_media_info.metadata)
{
if (b.standard == metadata_standard::xmp) return;
}
t->_player_media_info.metadata.emplace_back(std::move(block));
t->_async.invalidate_view(view_invalid::view_layout | view_invalid::media_elements);
});
});
}
void display_state_t::calc_pixel_difference()
{
const auto st1 = _selected_texture1;
const auto st2 = _selected_texture2;
if (st1 && st2)
{
const auto loaded1 = st1->_loaded;
const auto loaded2 = st2->_loaded;
_async.queue_media_preview(
[weak = weak_from_this(), st1 = ui_owned(_async, st1), st2 = ui_owned(_async, st2),
loaded1, loaded2, &async = _async](
media_preview_state& decoder)
{
const auto result = loaded1.calc_pixel_difference(loaded2);
async.queue_ui([weak, st1, st2, result]
{
const auto t = weak.lock();
if (!t || t->_selected_texture1.get() != st1.get() ||
t->_selected_texture2.get() != st2.get())
return;
t->_pixel_difference = result;
t->_async.invalidate_view(view_invalid::view_layout | view_invalid::media_elements);
});
});
}
}
void view_state::load_hover_thumb(const df::item_element_ptr& item, double pos_numerator,
double pos_denominator)
{
df::assert_true(ui::is_ui_thread());
const auto generation = ++_hover_thumbnail_generation;
if (item &&
(item->file_type()->group->traits && file_traits::preview_video) &&
item->online_status() == df::item_online_status::disk &&
df::file_handles_detached == 0)
{
const auto path = item->path();
const auto modified = item->file_modified();
const auto lifetime = item->weak_from_this();
_async.queue_media_preview(
[this, path, modified, lifetime, generation, pos_numerator, pos_denominator](media_preview_state& decoder)
{
if (decoder.open1(path))
{
auto surface = std::make_shared<ui::surface>();
if (decoder.decoder1->
extract_thumbnail(surface, video_preview_size, pos_numerator, pos_denominator, true,
hover_thumbnail_tolerance, decoder.abandon_token()))
{
// The store has one encoder for every producer. Encoding a scrub frame as PNG
// instead ran a zlib deflate per pointer position and put a blob into the
// thumbnail cache several times the size the cache is designed around.
if (!decoder.encoder) decoder.encoder = std::make_unique<files>();
const auto image = decoder.encoder->surface_to_thumbnail(surface);
if (is_valid(image))
{
const auto cover_art = decoder.decoder1->cover_art();
queue_ui([this, lifetime, path, image, cover_art, modified, generation]
{
if (generation == _hover_thumbnail_generation)
{
if (const auto current = lifetime.lock(); current && current->path() == path &&
current->file_modified() == modified)
{
current->thumbnail(image, cover_art, modified);
item_index.queue_stage_thumbnails({current});
item_index.save_thumbnail(path, image, cover_art, modified);
invalidate_view(view_invalid::view_redraw);
}
}
});
}
}
}
});
}
}
void view_state::clear_hover_codec()
{
df::assert_true(ui::is_ui_thread());
++_hover_thumbnail_generation;
_async.queue_media_preview([](media_preview_state& decoder)
{
decoder.close();
}, true);
}
void view_state::rescan_hydrated_display_item()
{
const auto d = _display;
if (!d || !d->_item1 || !d->_selected_texture1)
{
return;
}
const auto& item = d->_item1;
// Re-index a cloud-only placeholder once, after it has been hydrated by viewing it. The trigger
// is the completion of the full-file metadata scan (_full_metadata_loaded): reading the whole
// file is what finishes the OneDrive download and clears the offline attribute -- a partial
// preview read (which is enough to show the image) leaves the file a placeholder, so triggering
// off the loaded texture alone would re-index it while still offline and miss the metadata.
// Once the file is fully hydrated the re-index runs the normal online scan, and that scan's own
// invalidate_view(index_summary | media_elements) rebuilds the summary/tag list from the freshly
// scanned item->metadata() -- no polling or forced refresh needed.
if (item->online_status() != df::item_online_status::offline ||
!d->_full_metadata_loaded ||
d->_selected_texture1->loaded().is_empty() ||
_hydration_rescan_done == item->path())
{
return;
}
_hydration_rescan_done = item->path();
// Build a thumbnail from the image already in memory so the items view updates without waiting
// on an async re-scan, and persist it to the database. Decoding to a surface and re-encoding are
// both expensive, so they run on a worker; the result is published back with a path/modified
// check because the display item can change while the work is in flight.
_async.queue_async(async_queue::load,
[this, loaded = d->_selected_texture1->loaded(), lifetime = std::weak_ptr(item),
path = item->path(), modified = item->file_modified()]() mutable
{
files ff;
const auto thumb_surface = loaded.to_surface(setting.thumbnail_max_dimension, false, {},
decode_intent::thumbnail);
if (!ui::is_valid(thumb_surface)) return;
auto thumb_image = ff.surface_to_thumbnail(thumb_surface);
if (!ui::is_valid(thumb_image) || thumb_image->data().size() >= df::two_fifty_six_k) return;
queue_ui([this, lifetime, path, modified, thumb_image = std::move(thumb_image)]
{
const auto current = lifetime.lock();
if (!current || current->path() != path || current->file_modified() != modified) return;
current->thumbnail(thumb_image, {}, modified);
item_index.save_thumbnail(path, thumb_image, {}, modified);
invalidate_view(view_invalid::view_redraw | view_invalid::view_layout);
});
});
// Queue the rescan so the index catches up: online status clears, the real metadata (tags,
// camera, etc.) is read, and a content hash is computed for duplicate detection.
df::item_set to_rescan;
item->add_to(to_rescan);
item_index.queue_scan_modified_items(to_rescan);
}
// Releases one signal once every handle owner has reported, so a teardown that waits on several
// workers is bounded by a single timeout instead of one timeout per owner.
struct teardown_signal
{
std::atomic_int remaining;
platform::thread_event done{true, false};
explicit teardown_signal(const int owners) : remaining(owners)
{
}
void complete()
{
if (--remaining == 0) done.set();
}
};
// Runs where the first guard waits for the display's media to let go, which pumps messages. Whatever
// the user does in there - closing the view that asked for the guard, say - happens before its caller
// has carried on.
std::function<void()> test_during_detach_file_handles;
detach_file_handles::detach_file_handles(view_state& s) : _state(s)
{
df::gauge_enter(df::file_handles_detached);
if (++s._file_handle_detach_count > 1) return;
s._detached_display_item.reset();
s._detached_display_is_playable = false;
s._detached_display_is_playing = false;
s._detached_display_should_reopen = true;
s._detached_display_video_track = -1;
s._detached_display_audio_track = -1;
// Anything left from an earlier window is stale, and holding it would keep a file open across
// the rename, replace or delete this guard exists for.
s._detached_display_handle.reset();
const auto d = s.display_state();
if (d)
{
// Supersede any open still in flight. It would otherwise publish a live session onto the
// display, reopening the very file the caller is about to rename, replace or delete.
++d->_av_generation;
s._detached_display_item = d->_item1;
s._detached_display_is_playable = d->can_play_media();
s._detached_display_is_playing = d->is_playing_media();
if (d->_session)
{
s._detached_display_video_track = d->_session->video_stream_id();
s._detached_display_audio_track = d->_session->audio_stream_id();
}
if (s._detached_display_is_playable)
{
// Shared, not stack-local: the wait is bounded, and on timeout the workers still own their
// signal long after this frame is gone. One signal for both owners bounds the whole teardown
// by a single timeout rather than one per owner.
const auto teardown = std::make_shared<teardown_signal>(d->_session ? 2 : 1);
d->_hover_surface.reset();
if (d->_session)
{
s._player->close(d->_session, [teardown]
{
teardown->complete();
});
// The close owns its own reference; leaving this one set would let present, transport
// state and the position bar keep using a session that is being torn down.
d->_session.reset();
}
// Must run: a superseded close would leave the file handles open that the caller is about to
// rename, replace or delete over.
s._async.queue_media_preview([teardown](media_preview_state& decoder)
{
decoder.close();
teardown->complete();
}, true);
platform::wait_for({teardown->done, platform::event_exit}, 10000, false);
s._async.invalidate_view(view_invalid::view_layout |
view_invalid::screen_saver |
view_invalid::app_layout |
view_invalid::media_elements |
view_invalid::command_state);
}
d->stop_slideshow();
}
if (test_during_detach_file_handles) test_during_detach_file_handles();
s.clear_hover_codec();
}
detach_file_handles::~detach_file_handles()
{
df::gauge_leave(df::file_handles_detached);
// A worker can own the last reference, because the guard is handed to callers through completion
// callbacks. Everything the release touches is UI-owned, including the non-atomic nesting count.
if (ui::is_ui_thread())
{
_state.release_detached_file_handles(_reopen_display);
}
else
{
auto& s = _state;
s._async.queue_ui([&s, reopen = _reopen_display] { s.release_detached_file_handles(reopen); });
}
}
void view_state::release_detached_file_handles(const bool reopen_display)
{
df::assert_true(ui::is_ui_thread());
if (!reopen_display) _detached_display_should_reopen = false;
if (--_file_handle_detach_count != 0) return;
const auto d = display_state();
if (_detached_display_should_reopen && d && _detached_display_item &&
_detached_display_item == d->_item1)
{
const auto path = _detached_display_item->path();
if (path.exists())
{
if (_detached_display_is_playable)
{
open_av_session(d, _detached_display_item, _detached_display_is_playing,
_detached_display_video_track, _detached_display_audio_track, true,
std::move(_detached_display_handle));
}
}
else
{
select_nothing({});
close();
}
}
// Unconditional: a handle nobody consumed must not outlive the window it was handed over for.
_detached_display_handle.reset();
_detached_display_item.reset();
item_index.queue_scan_modified_items(selected_items());
}
void view_state::publish_written_image(const df::file_path path, file_load_result loaded,
const df::date_t modified) const
{
df::assert_true(ui::is_ui_thread());
const auto d = display_state();
if (!d) return;
if (d->_selected_texture1 && d->_item1 && d->_item1->path() == path)
{
d->_selected_texture1->publish_written_image(path, std::move(loaded), modified);
}
else if (d->_selected_texture2 && d->_item2 && d->_item2->path() == path)
{
d->_selected_texture2->publish_written_image(path, std::move(loaded), modified);
}
}
// Two selected items are both on screen, so both can be handed the bytes a write produced.
std::vector<df::file_path> view_state::displayed_photo_paths() const
{
df::assert_true(ui::is_ui_thread());
const auto d = display_state();
if (!d) return {};
std::vector<df::file_path> result;
if (d->_item1) result.emplace_back(d->_item1->path());
if (d->_item2) result.emplace_back(d->_item2->path());
return result;
}
void view_state::publish_written_handle(const df::file_path path, platform::file_ptr file)
{
df::assert_true(ui::is_ui_thread());
// The reopen only uses the handle for the item it detached, so anything else would just be a
// file held open for nothing.
if (!file || !_detached_display_item || _detached_display_item->path() != path)
{
return;
}
_detached_display_handle = std::move(file);
}
df::file_path view_state::detached_display_av_path() const
{
df::assert_true(ui::is_ui_thread());
return _detached_display_is_playable && _detached_display_should_reopen && _detached_display_item
? _detached_display_item->path()
: df::file_path{};
}
bool media_preview_state::open1(const df::file_path file_path)
{
const auto new_path = !decoder1 || decoder1->path() != file_path;
if (new_path)
{
const auto new_decoder = std::make_shared<av_format_decoder>();
if (new_decoder->open(file_path, media_intent::thumbnail))
{
// Threaded: a hover decodes a whole GOP forward to reach the frame it was asked for.
new_decoder->init_streams(-1, -1, false, true, true);
decoder1 = new_decoder;
}
else
{
decoder1.reset();
}
}
return decoder1 != nullptr;
}
bool media_preview_state::open2(const df::file_path file_path)
{
const auto new_path = !decoder2 || decoder2->path() != file_path;
if (new_path)
{
const auto new_decoder = std::make_shared<av_format_decoder>();
if (new_decoder->open(file_path, media_intent::thumbnail))
{
// Threaded: a hover decodes a whole GOP forward to reach the frame it was asked for.
new_decoder->init_streams(-1, -1, false, true, true);
decoder2 = new_decoder;
}
else
{
decoder2.reset();
}
}
return decoder2 != nullptr;
}
df::unique_paths make_unique_paths(df::paths selection)
{
df::unique_paths result(selection.files.begin(), selection.files.end());
for (const auto& f : selection.folders) result.emplace(f);
return result;
}
void view_state::browse_forward(const view_host_base_ptr& view)
{
history_state::history_entry e;
if (history.history_entry_at(1, e))
{
_pending_history_move = {e.search, 1, _selected.ids()};
if (!open(view, e.search, make_unique_paths(e.selected))) _pending_history_move.reset();
}
}
void view_state::browse_back(const view_host_base_ptr& view)
{
history_state::history_entry e;
if (history.history_entry_at(-1, e))
{
_pending_history_move = {e.search, -1, _selected.ids()};
if (!open(view, e.search, make_unique_paths(e.selected))) _pending_history_move.reset();
}
}
void view_state::capture_display(const std::function<void(file_load_result)>& f) const
{
const auto d = _display;
if (d)
{
// The frame of a playing video arrives later, on this thread, and only the latest request
// may act on it: a Copy overtaken by a newer Copy would otherwise land last and put the older
// frame on a clipboard the user has since filled. Moving on to another item does not
// overtake it - every caller takes what it needs when it asks, so Copy followed at once by
// Next still copies. The display itself is not held: this callback waits on the media read
// thread, which must never be left holding the last reference to UI-owned state.
const auto generation = ++_capture_generation;
const auto deliver = [this, generation, f](file_load_result lr)
{
if (generation != _capture_generation) return;
f(std::move(lr));
};
// player_has_video() reports the media info, which outlives the session across a
// file-handle detach, so the session itself has to be checked too.
if (d->player_has_video() && d->_session)
{
_player->capture(d->_session, deliver);
}
else if (d->_selected_texture1)
{
deliver(d->_selected_texture1->loaded());
}
else
{
deliver({});
}
}
}
void view_state::view_mode(const view_type m)
{
if (_view_mode != m)
{
_view_mode = m;
record_feature_use(features::view_bit(m));
_events.view_changed(_view_mode);
// A task view needs the top bar and its own controls, both of which full screen hides. Full
// screen is also refused from a view, so the two states never coexist in either direction.
if (is_full_screen && m != view_type::media)
{
_events.toggle_full_screen();
}
}
}
void view_state::play(const view_host_base_ptr& view)
{
const auto d = _display;
if (!d)
return;
// Play is media transport only. It never starts a slideshow, but it does stop one so the
// same key that started playing always stops it.
if (d->is_playing())
{
stop();
}
else if (d->can_play_media())
{
_player->play(d->_session);
}
}
void view_state::toggle_slideshow(const view_host_base_ptr& view)
{
const auto d = _display;
if (!d)
return;
if (d->is_slideshow())
{
stop();
return;
}
if (!can_slideshow())
return;
const auto displayed = d->is_one() ? d->_item1 : nullptr;
const auto start = displayed && displayed->is_media() ? displayed : next_media_item(true, true);
if (!start)
return;
record_feature_use(features::slideshow);
// Set before selecting so the display state opened for the first item already knows a
// slideshow is running and starts any video or audio playing.
_common_display_state._is_slideshow = true;
if (start != displayed)
{
select(view, start, false, false, true);
}
else if (d->can_play_media() && !d->is_playing_media())
{
_player->play(d->_session);
}
invalidate_view(view_invalid::command_state | view_invalid::view_redraw | view_invalid::screen_saver);
}
void view_state::stop()
{
const auto d = _display;
_play_next_on_open = false;
if (d)
{
d->stop_slideshow();
if (d->is_playing_media() && d->_session)
{
_player->pause(d->_session);
}
}
_common_display_state._is_slideshow = false;
invalidate_view(view_invalid::command_state | view_invalid::screen_saver);
}
bool display_state_t::publish_av_session(const std::shared_ptr<av_session>& ses, const uint32_t generation)
{
if (generation != _av_generation) return false;
update_av_session(ses);
return true;
}
void view_state::open_av_session(const std::shared_ptr<display_state_t>& d, const df::item_element_ptr& i,
const bool auto_play, const int video_track, const int audio_track,
const bool use_last_played_pos, platform::file_ptr file) const
{
const auto generation = ++d->_av_generation;
_player->open(i, auto_play, video_track, audio_track, av_can_use_hw(), use_last_played_pos,
[d = ui_owned(_async, d), generation, player = _player](const std::shared_ptr<av_session>& ses)
{
// Dropping a superseded session instead of closing it would leave the file open
// across the operation the teardown was for.
if (!d->publish_av_session(ses, generation) && ses)
{
player->close(ses, {});
}
}, std::move(file));
}
void view_state::change_tracks(const int video_track, const int audio_track) const
{
const auto d = _display;
if (d && d->_session)
{
const auto auto_play = d->_session->is_playing();
// The replacement reopens the same file, so the outgoing session must be closed here
// rather than left for whichever thread happens to drop the last reference - that left
// two decoders open on one file and ran the teardown on a decode thread.
_player->close(d->_session, {});
d->_session.reset();
open_av_session(d, d->_item1, auto_play, video_track, audio_track, true);
}
}
void view_state::change_audio_device(const std::string& id) const
{
if (_player)
{
_player->audio_device_id(id);
}
}
void view_state::toggle_group_order()
{
constexpr group_by options[] = {
group_by::file_type,
group_by::size,
group_by::extension,
group_by::location,
group_by::rating_label,
group_by::date_original,
group_by::date_created,
group_by::date_modified,
group_by::camera,
group_by::resolution,
group_by::aspect_ratio,
group_by::album_show,
group_by::folder,
group_by::presence,
};
bool found_order = false;
for (auto i = 0u; i < std::size(options); ++i)
{
if (_group_order == options[i])
{
group_order(options[(i + 1) % std::size(options)], _sort_order);
found_order = true;
break;
}
}
if (!found_order)
{
group_order(group_by::file_type, _sort_order);
}
}
void view_state::group_order(const std::optional<group_by> group, const std::optional<sort_by> order)
{
auto changed = false;
const auto is_currently_shuffle = _group_order == group_by::shuffle;
if (order.has_value() && (_sort_order != order || is_currently_shuffle))
{
_sort_order = order.value();
if (is_currently_shuffle)
{
_group_order = group_by::file_type;
}
changed = true;
}
if (group.has_value() && _group_order != group)
{
_group_order = group.value();
changed = true;
}
if (changed)
{