Repository navigation
Expand file tree
/
Copy pathmodel.h
More file actions
1930 lines (1581 loc) · 71.2 KB
/
Copy pathmodel.h
File metadata and controls
1930 lines (1581 loc) · 71.2 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 Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Purpose: View state coordination and navigation. view_state owns the scope and query, results,
// grouping, filtering, selection and history, and the current display - whose type, with its media
// playback, is in model_display.h - plus the durable states the Movie and Edit views keep. Also the
// strategies view_state reaches the application through, including how long-running work reports
// its progress for the taskbar button.
#pragma once
#include "model_zoom.h"
#include "ui_panorama.h"
#include "model_property.h"
#include "model_items.h"
#include "model_locations.h"
#include "model_movie.h"
#include "model_visits.h"
#include "av_host.h"
constexpr core::color32 color_for_delete = core::bgr(0xaa2211);
constexpr core::color32 color_for_action = core::bgr(0xCC6611);
constexpr core::color32 color_rate_rejected = core::bgr(0xE01C2B);
constexpr core::color32 color_label_approved = core::bgr(0x6FC958);
constexpr core::color32 color_label_to_do = core::bgr(0xD08CE0);
constexpr core::color32 color_label_select = core::bgr(0xFD6460);
constexpr core::color32 color_label_review = core::bgr(0x52B7F2);
constexpr core::color32 color_label_second = core::bgr(0xF2CC51);
// The grading vocabulary. One definition drives the grading control, the thumbnail badge, the
// sidebar filters, and the Rate or Label menu, so a mark is learned once and recognized everywhere.
// Reject is a rating of -1 rather than a colour label, so it leads the row with an empty key.
// Each mark has its own glyph as well as its own colour so the row stays readable without colour.
struct rate_label_def
{
std::string_view key;
core::color32 clr;
icon_index icon;
};
inline constexpr rate_label_def rate_label_defs[] = {
{{}, color_rate_rejected, icon_index::cancel},
{label_select_text, color_label_select, icon_index::flag},
{label_second_text, color_label_second, icon_index::bullet},
{label_approved_text, color_label_approved, icon_index::check},
{label_review_text, color_label_review, icon_index::question},
{label_to_do_text, color_label_to_do, icon_index::time},
};
inline constexpr auto& rate_label_reject = rate_label_defs[0];
inline constexpr auto& rate_label_select = rate_label_defs[1];
inline constexpr auto& rate_label_second = rate_label_defs[2];
inline constexpr auto& rate_label_approved = rate_label_defs[3];
inline constexpr auto& rate_label_review = rate_label_defs[4];
inline constexpr auto& rate_label_to_do = rate_label_defs[5];
inline const rate_label_def* find_rate_label_def(const std::string_view label)
{
for (const auto& d : rate_label_defs)
{
if (!d.key.empty() && core::icmp(d.key, label) == 0) return &d;
}
return nullptr;
}
// One badge definition for every surface: the thumbnail flag, the detail row, and the selection
// panel control all draw the same mark for the same state.
void draw_rate_label_badge(render::draw_context& dc, std::string_view label, int rating, recti logical_bounds,
float alpha);
// The pin mark is the same orange badge wherever it appears, so the held item reads the same in the
// item grid, the selection collage and the panel control.
void draw_pin_badge(render::draw_context& dc, recti logical_bounds, float alpha);
class location_cache;
class database;
class tile_cache_db;
class av_player;
class av_format_decoder;
class files;
class scrubber_element;
class display_state_t;
struct sid_voice_mix;
struct tracker_channel_mix;
struct subtitle_choice;
using display_state_ptr = std::shared_ptr<display_state_t>;
render::texture_sampler calc_sampler(sizei draw_extent, sizei texture_extent, const core::orientation& orientation,
bool interactive = false, bool provisional = false);
// The sampler for a video frame drawn into picture_extent: bilinear when it is minified, otherwise as
// calc_sampler chooses for the picture's own extent.
render::texture_sampler calc_video_sampler(sized picture_extent, sizei texture_extent,
const core::orientation& orientation, bool interactive = false);
void draw_texture_info(render::draw_context& rc, recti media_bounds, const render::texture_ptr& tex,
core::orientation orientation, render::texture_sampler sampler, float alpha);
core::unique_paths make_unique_paths(core::paths selection);
struct media_preview_state
{
std::shared_ptr<av_format_decoder> decoder1;
std::shared_ptr<av_format_decoder> decoder2;
// Held with the decoders because constructing one runs jpeg_create_compress and
// jpeg_create_decompress, which a pointer move should not pay for.
std::unique_ptr<files> encoder;
// Owned by the preview worker: set while a newer hover waits behind the one running.
std::atomic_bool* superseded = nullptr;
media_preview_state();
~media_preview_state();
// A pointer that has already moved on makes the rest of the walk toward an exact frame
// worthless, so the decode stops at the nearest frame it has reached and answers with that.
core::cancel_token abandon_token() const
{
return superseded ? core::cancel_token(*superseded) : core::cancel_token{};
}
void close();
bool open1(file_path file_path);
bool open2(file_path file_path);
};
// async_strategy - Core async execution and thread coordination interface.
//
// Provides thread-safe context switching between different execution contexts in the application.
// All background work is dispatched through specialized queues, each running on dedicated threads.
// Results are marshalled back to the UI thread via queue_ui() for safe UI updates.
//
// Queue methods:
// - queue_ui(f) : Execute f on the UI thread. Use for all UI updates from background threads.
// - queue_async(q, f) : Execute f on a background thread pool based on queue type q.
// - queue_location(f) : Execute f with access to the location_cache (reverse geocoding, city lookups).
// - queue_database(f) : Execute f with access to the SQLite database (thumbnails, metadata cache).
// - queue_tile_db(f) : Execute f with access to the map tile store. Its own connection on its own
// thread, so a tile lookup never queues behind index or thumbnail work.
// - queue_media_preview(f, must_run) : Execute f for video seek preview generation. Preview requests
// coalesce so only the newest survives; must_run marks teardown, which is never superseded.
//
// Typical pattern:
// queue_async(async_queue::work, [this] {
// auto result = expensive_computation();
// queue_ui([result] { update_ui_with(result); });
// });
//
// The async_queue enum defines specialized queues for different workloads:
// - scan_folder, scan_modified_items : File system scanning
// - load, load_raw : Image/media loading
// - crc : File hash computation
// - index, index_predictions : Search index operations
// - web, cloud, map_tile : Network operations
// - query, auto_complete : Search and suggestions
//
// See app.cpp for the implementation using platform::task_queue and worker threads.
class async_strategy : public av_host, public df::async_i
{
public:
~async_strategy() override = default;
void queue_ui(std::function<void()> f) override = 0;
void queue_async(async_queue q, std::function<void()> f) override = 0;
// Runs f no sooner than delay_ms from now, superseding anything already waiting on that queue. The
// wait happens in the worker's event wait, so it costs no thread. Only the coalescing queues
// support it - the deadline belongs to the queue, not to f.
virtual void queue_async_after(async_queue q, uint32_t delay_ms, std::function<void()> f) = 0;
virtual void queue_location(std::function<void(location_cache&)>) = 0;
virtual void queue_database(std::function<void(database&)> f) = 0;
virtual void queue_tile_db(std::function<void(tile_cache_db&)> f) = 0;
virtual void queue_media_preview(std::function<void(media_preview_state&)>, bool must_run = false) = 0;
virtual void web_service_cache(std::string key, std::function<void(const std::string&)> f) = 0;
virtual void web_service_cache(std::string key, std::string value) = 0;
// Long-running work reports how far it has got so it also shows outside its own dialog or view,
// on the application's taskbar button. Each source reports under its own key until it finishes;
// a total of zero means the amount is not known yet. UI thread only.
virtual void work_progress(const void* /*source*/, int64_t /*done*/, int64_t /*total*/) {}
virtual void work_finished(const void* /*source*/) {}
};
// The work the taskbar button shows. A task view and a progress dialog can both be running, so each
// reports under its own key and the button follows whichever reported last. UI thread only.
class work_progress_reports
{
public:
struct report
{
const void* source = nullptr;
int64_t done = 0;
int64_t total = 0;
};
void update(const void* source, const int64_t done, const int64_t total)
{
std::erase_if(_reports, [source](const report& r) { return r.source == source; });
_reports.push_back({source, done, total});
}
// Answers whether the source was running, so a source that reports its end again and again
// changes nothing after the first time.
bool finish(const void* source)
{
return std::erase_if(_reports, [source](const report& r) { return r.source == source; }) > 0;
}
std::optional<report> latest() const
{
if (_reports.empty()) return std::nullopt;
return _reports.back();
}
private:
std::vector<report> _reports;
};
// Carries a UI-owned object across a worker hop. A worker must never run these destructors: they
// release D3D textures and cross-device keyed mutexes, tear down av_session decoder threads, and
// every worker runs in its own single-threaded apartment. Capturing a plain shared_ptr lets that
// happen whenever the worker drops the final reference - an early return, a thrown task, or the
// queue truncation each worker performs as it exits. This guard hands that final reference back to
// queue_ui instead, so teardown always runs on the owning context. app_frame joins every worker
// before draining _ui_queue, which is what makes the shutdown hand-back land on the UI thread.
template <typename T> class ui_owned_ptr
{
public:
ui_owned_ptr(async_strategy& async, std::shared_ptr<T> p) noexcept : _async(&async), _p(std::move(p)) {}
ui_owned_ptr(const ui_owned_ptr&) = default;
ui_owned_ptr& operator=(const ui_owned_ptr&) = default;
ui_owned_ptr(ui_owned_ptr&&) noexcept = default;
ui_owned_ptr& operator=(ui_owned_ptr&&) noexcept = default;
~ui_owned_ptr()
{
// The hop is unconditional off the UI thread. use_count cannot be tested and acted on
// atomically: a count above one can drop to zero between the test and this destructor's own
// release, which is precisely the worker-thread destruction this type exists to prevent. The
// hop costs one queued message that releases a reference and does nothing else.
if (_p && !platform::is_ui_thread())
{
_async->queue_ui([p = std::move(_p)] {});
}
}
T* operator->() const noexcept { return _p.get(); }
T& operator*() const noexcept { return *_p; }
T* get() const noexcept { return _p.get(); }
explicit operator bool() const noexcept { return static_cast<bool>(_p); }
const std::shared_ptr<T>& shared() const noexcept { return _p; }
private:
async_strategy* _async;
std::shared_ptr<T> _p;
};
template <typename T> ui_owned_ptr<T> ui_owned(async_strategy& async, std::shared_ptr<T> p)
{
return ui_owned_ptr<T>(async, std::move(p));
}
// state_strategy - Abstract interface for application-level UI coordination and state management.
//
// This interface decouples the view_state (model/data layer) from the application frame (app_frame).
// By using this abstraction, view_state can notify the UI of state changes without depending on
// concrete UI implementation details. This enables:
//
// 1. **Loose Coupling**: view_state communicates through abstract callbacks rather than direct
// method calls to app_frame, making the codebase more modular and testable.
//
// 2. **Testability**: Unit tests can provide a null implementation (see null_state_strategy in
// tests.cpp) that ignores all callbacks, allowing view_state to be tested in isolation.
//
// 3. **Separation of Concerns**: The model layer (view_state) focuses on data and business logic,
// while the app layer handles UI coordination, window management, and command routing.
//
// Key callback categories:
// - **View Lifecycle**: display_changed(), view_changed(), search_complete()
// - **User Interaction**: invoke(), track_menu(), command_hover(), toggle_full_screen()
// - **Item Management**: item_focus_changed(), make_visible(), delete_items()
// - **Rendering**: invalidate_view(), free_graphics_resources(), element_broadcast()
//
// The app_frame class implements this interface to bridge view_state notifications to the
// actual UI components (toolbars, sidebar, views, etc.).
//
// See also: async_strategy for threading/async decoupling, view_host for per-view interactions.
struct state_strategy
{
virtual ~state_strategy() = default;
// Window management
virtual void toggle_full_screen() = 0;
// Navigation and search
virtual bool can_open_search(const df::search_t& path) = 0;
virtual void search_complete(const df::search_t& path, bool path_changed) = 0;
// Called when a scope could not be opened because one of its locations cannot be read.
virtual void report_scope_unavailable(const df::search_t& path) = 0;
// Selection and focus
virtual void item_focus_changed(const df::item_element_ptr& focus, const df::item_element_ptr& previous) = 0;
virtual void make_visible(const df::item_element_ptr& i) = 0;
// View state changes
virtual void display_changed() = 0;
virtual void view_changed(view_type m) = 0;
// Command handling
virtual void invoke(commands id) = 0;
virtual bool is_command_checked(commands cmd) = 0;
virtual ui::command_ptr find_command(commands id) const = 0;
virtual void command_hover(const ui::command_ptr& c, recti window_bounds) = 0;
// UI interactions
virtual void track_menu(const ui::frame_ptr& parent, recti bounds,
const std::vector<ui::command_ptr>& commands) = 0;
virtual void element_broadcast(const view_element_event& event) = 0;
virtual void focus_view() = 0;
// Resource management
virtual void free_graphics_resources(bool items_only, bool offscreen_only) = 0;
virtual void delete_items(const df::item_set& items) = 0;
// Rendering invalidation
virtual void invalidate_view(view_invalid invalid) = 0;
};
class recent_state final : public core::no_copy
{
public:
static constexpr int max_size = 64;
std::vector<std::string> _items;
recent_state() = default;
const std::vector<std::string>& items() const { return _items; }
void count_strings(core::string_counts& results, const int weight, const std::string_view prefix = {}) const
{
// Keys are views, so the text must be interned: _items is rewritten whenever a search or
// folder is used again, which would otherwise leave earlier counts dangling.
for (const auto& i : _items)
{
if (prefix.empty())
{
results[core::cache(i)] += weight;
}
else
{
results[core::cache(std::format("{}{}", prefix, i))] += weight;
}
}
}
void count(core::folder_counts& results, const int weight) const
{
for (const auto& i : _items)
{
if (core::is_path(i))
{
results[core::folder_path(i)] += weight;
}
}
}
void add(const std::string_view v)
{
for (auto i = _items.cbegin(); i != _items.cend(); ++i)
{
if (compare(*i, v) == 0)
{
_items.erase(i);
break;
}
}
if (_items.size() >= max_size)
{
_items.erase(_items.cbegin());
}
_items.emplace_back(v);
}
static void add_list(std::vector<std::string>& results, const std::vector<std::string_view>& adds)
{
for (const auto& a : adds)
{
results.emplace_back(a);
}
}
static void add_list(std::vector<std::string>& results, const std::vector<std::string>& adds)
{
for (const auto& a : adds)
{
results.emplace_back(a);
}
}
static void add_list(std::vector<core::folder_path>& results, const std::vector<std::string_view>& adds)
{
for (const auto& a : adds)
{
results.emplace_back(a);
}
}
template <class t> void add_items(t&& v) { add_list(_items, v); }
static std::string combine(const std::vector<std::string>& strings) { return core::combine(strings); }
static std::string combine(const std::vector<core::folder_path>& strings) { return combine_paths(strings); }
static int compare(const std::string_view l, const std::string_view r) { return core::icmp(l, r); }
static int compare(const core::folder_path l, const core::folder_path r) { return l.compare(r); }
// Builds before 1.27.3 wrote these lists to the INI unquoted, and the reader strips one quote pair
// from each end of a value, so a list that began and ended with quoted entries came back with the
// two quote characters fused between paths, as "' or '". Search syntax such as loc:"Boulder City"
// legitimately puts a double quote next to text, but never directly beside a single quote.
static bool is_damaged_entry(const std::string_view entry)
{
const auto first_text = entry.find_first_not_of("\"'");
if (first_text == std::string_view::npos || !core::is_path(entry.substr(first_text))) return false;
return entry.find("\"'") != std::string_view::npos || entry.find("'\"") != std::string_view::npos;
}
void read(const std::string_view section, const std::string_view key, const platform::setting_file_ptr& properties)
{
std::string str;
properties->read(section, key, str);
for (const auto& item : core::split(str, true))
{
if (!is_damaged_entry(item)) _items.emplace_back(item);
}
}
void write(const std::string_view section, const std::string_view key,
const platform::setting_file_ptr& properties) const
{
properties->write(section, key, combine(_items));
}
};
class history_state final : public core::no_copy
{
public:
struct history_entry
{
df::search_t search;
core::paths selected;
};
static constexpr int max_history_size = 32;
std::vector<history_entry> _history;
ptrdiff_t _pos = -1;
history_state() = default;
void count_strings(core::string_counts& results, const int weight) const
{
for (const auto& h : _history)
{
for (const auto& s : h.search.selectors())
{
results[core::cache(s.str())] += weight;
results[s.folder().text()] += weight;
}
for (const auto& t : h.search.terms())
{
results[core::cache(format_term(t))] += weight;
}
}
}
void count_folders(core::folder_counts& results, int weight) const
{
if (weight == 0)
{
for (const auto& result : results)
{
weight = std::max(weight, static_cast<int>(result.second));
}
}
for (const auto& h : _history)
{
for (const auto& s : h.search.selectors())
{
if (platform::exists(s.folder()))
{
results[s.folder()] += weight;
}
}
}
}
bool can_browse_forward() const { return _pos + 1 < static_cast<int>(_history.size()); }
bool can_browse_back() const { return _pos > 0; }
const history_entry& back_entry() const { return _history[_pos - 1]; }
const history_entry& forward_entry() const { return _history[_pos + 1]; }
bool move_history_pos(const int n, core::paths selected, history_entry& result)
{
const auto i = _pos + n;
if (i >= static_cast<int>(_history.size()) || i < 0)
{
return false;
}
_history[_pos].selected = std::move(selected);
_pos = i;
result = _history[i];
return true;
}
bool history_entry_at(const int n, history_entry& result) const
{
const auto i = _pos + n;
if (i >= static_cast<int>(_history.size()) || i < 0)
{
return false;
}
result = _history[i];
return true;
}
void commit_history_pos(const int n, core::paths selected)
{
const auto i = _pos + n;
core::assert_true(i >= 0 && i < static_cast<int>(_history.size()));
_history[_pos].selected = std::move(selected);
_pos = i;
}
void replace_current_search(const df::search_t& expected, const df::search_t& replacement)
{
if (_pos >= 0 && _pos < static_cast<int>(_history.size()) && _history[_pos].search == expected)
{
_history[_pos].search = replacement;
}
}
void history_add(const df::search_t& link, core::paths selected)
{
if (_pos != -1)
{
if (_history[_pos].search == link)
{
return;
}
_history[_pos].selected = std::move(selected);
_history.resize(_pos + 1);
}
_history.emplace_back(link, core::paths{});
if (_history.size() > max_history_size)
{
_history.erase(_history.cbegin());
}
_pos = static_cast<int>(_history.size()) - 1;
}
};
// The extent a texture's destination is shaped by. A decoded video frame can carry non-square
// pixels, so the stored frame is not the shape to fill: the container's declared display
// dimensions are. A photo keeps its texture's own shape, because a stand-in staged before the
// decode need not match the item's declared dimensions and stretching it would distort the
// picture until the decode landed (#78).
sizei calc_draw_shape(sizei oriented_texture_extent, sizei display_dimensions, bool is_video);
struct texture_source_version
{
core::date_t file;
core::date_t thumbnail;
friend bool operator==(const texture_source_version&, const texture_source_version&) = default;
friend bool operator!=(const texture_source_version&, const texture_source_version&) = default;
};
struct retained_texture_budget_entry
{
bool displayed = false;
size_t decoded_bytes = 0;
};
inline std::vector<size_t> retained_texture_eviction_indexes(std::span<const retained_texture_budget_entry> entries,
const size_t budget)
{
size_t decoded = 0;
for (const auto& entry : entries)
{
if (!entry.displayed) decoded += entry.decoded_bytes;
}
std::vector<size_t> result;
result.reserve(entries.size());
while (decoded > budget)
{
auto found = false;
for (auto i = entries.size(); i > 0; --i)
{
const auto index = i - 1;
const auto& entry = entries[index];
if (entry.displayed || std::ranges::find(result, index) != result.end()) continue;
decoded = entry.decoded_bytes < decoded ? decoded - entry.decoded_bytes : 0;
result.emplace_back(index);
found = true;
break;
}
if (!found) break;
}
return result;
}
class texture_state final : public std::enable_shared_from_this<texture_state>
{
public:
// Why the media area has nothing to draw, so it can say so instead of showing an empty frame.
enum class display_problem
{
none,
too_large,
failed
};
render::texture_ptr _tex;
render::texture_ptr _vid_tex;
async_strategy& _async;
friend class display_state_t;
private:
core::file_path _path;
file_load_result _loaded;
core::const_surface_ptr _staged_surface;
core::const_surface_ptr _retained_surface;
std::shared_ptr<std::atomic_bool> _decode_cancel;
texture_source_version _photo_version;
sizei _loading_scale_hint;
// Whether the decode in flight was asked for packed pixels, which only a projection needs. Part
// of the request, so a change to it re-decodes even at the same size.
bool _loading_packed = false;
uint64_t _decode_generation = 0;
uint64_t _load_generation = 0;
int _load_retry_count = 0;
render::texture_ptr _last_draw_tex;
recti _last_draw_source_rect;
render::texture_sampler _last_drawn_sampler = render::texture_sampler::point;
render::texture_ptr _fade_out_tex;
recti _fade_out_source_rect;
render::texture_sampler _fade_out_sampler = render::texture_sampler::point;
ui::animate_alpha _display_alpha_animation;
std::atomic_int _preview_rendering = 0;
recti _display_bounds;
render::texture_ptr _zoom_texture;
core::const_surface_ptr _zoom_staged_surface;
texture_source_version _zoom_version;
// The projection this frame is drawing, set by the media control before each draw and read by
// the decode ladder as well as by the presentation: a projected view needs the source at the
// resolution its field of view asks for, not at the resolution the viewport asks for.
panorama_request _panorama;
panorama_renderer _panorama_renderer;
core::const_surface_ptr _panorama_source;
core::surface_ptr _panorama_surface;
render::texture_ptr _panorama_tex;
// The same pixels uploaded with a mip chain, for a backend that projects them itself. Kept apart
// from _panorama_tex, which is where the software rasteriser puts its finished frame.
core::const_surface_ptr _panorama_gpu_source;
render::texture_ptr _panorama_gpu_tex;
panorama_view _panorama_rendered_view;
// The rendered pixels depend on the coverage as strongly as on the camera, and the declaration
// read lands after the first frames are already on screen.
prop::panorama_geometry _panorama_rendered_geometry;
bool _panorama_rendered = false;
void update_decode(render::draw_context& rc);
// Everything only a projection needs: the mipped upload, the reduced copies and the frame the
// software rasteriser draws into. Between them they are the largest thing the item holds.
void release_panorama_resources();
public:
bool _is_video_tex = false;
bool _tex_invalid = true;
bool _is_photo = false;
bool _is_raw = false;
bool _photo_loaded = false;
// True while _loaded still holds the item thumbnail standing in for the full-size image.
bool _is_placeholder = true;
bool _display_geometry_known = false;
bool _load_retry_pending = false;
// Armed before a write that changes the modified time without changing what is drawn; consumed by
// the first refresh that sees that write's stamps.
bool _retain_visuals_on_modify = false;
core::orientation _display_orientation = core::orientation::top_left;
sizei _display_dimensions;
display_problem _display_problem = display_problem::none;
// Where the last draw put a video frame, in the view's pixels, and how opaque it was: what subtitles
// are placed on. Empty until a frame has been drawn. The pixels the frame covered, turned or cut for a
// comparison as it was, are where a new frame of the video is shown again.
recti _last_picture_bounds;
float _last_picture_alpha = 0.0f;
recti _last_picture_drawn;
texture_state(async_strategy& async, const df::item_element_ptr& i);
// Brings the picture up to date, as draw does first, and says whether there is one to draw. A panel that
// would rather show nothing than the box a photo waits behind draws only when this answers true.
bool prepare_picture(render::draw_context& rc);
void load_image(const df::item_element_ptr& i);
void load_raw();
// Puts phase 1 on screen at the next draw, using the surface the browser already staged for the
// item. Does nothing once anything better is drawn or staged.
void seed_placeholder(const df::item_element_ptr& i);
void refresh(const df::item_element_ptr& i);
// Declares what is held to be current across the next write, for a write that changes the file's
// modified time without changing what the file draws.
void mark_visuals_current();
// Adopts the image a write just produced, for the path it was written to. Supersedes any load
// already in flight so a slower by-name read cannot land on top of it. The modified time is the
// file's own, so the stamp stays in the same clock domain as the item's timestamps.
void publish_written_image(core::file_path path, file_load_result loaded, core::date_t modified);
void draw(render::draw_context& rc, pointi offset, int compare_pos, bool first_texture, bool interactive = false);
// zoom.md: the same image drawn as the sphere it declares itself to be. Shares the decode ladder
// with draw; only the presentation differs.
void draw_panorama(render::draw_context& rc, pointi offset, const prop::panorama_geometry& geometry,
const panorama_view& view);
void layout(render::measure_context& mc, recti bounds, const df::item_element_ptr& i);
sizei calc_display_dimensions() const;
void clear();
bool is_empty() const;
void fade_out();
void display_dimensions(sizei dims);
sizei display_dimensions() const { return _display_dimensions; }
core::orientation display_orientation() const { return _display_orientation; }
const file_load_result& loaded() const { return _loaded; }
bool step() { return _display_alpha_animation.step(); }
void free_graphics_resources();
// Drops every representation derived from _loaded, keeping _loaded itself, so the next draw decodes
// at the size it needs instead of returning to the file. A format that decoded straight to a
// surface keeps it: _loaded.s is the compressed form it does not have.
void release_decoded_surfaces();
void update(const core::const_surface_ptr& staged_surface);
void update(file_load_result loaded);
void complete_load(file_load_result loaded, uint64_t generation, bool raw);
void cancel_pending_decode();
sizei calc_scale_hint() const;
bool can_preview() const { return _is_raw; }
render::texture_ptr zoom_texture(render::draw_context& rc, sizei extent);
recti display_bounds() const { return _display_bounds; }
bool is_preview() const { return !_loaded.is_empty() && _loaded.is_preview; }
bool is_preview_rendering() const { return _preview_rendering != 0; }
// Whether the next draw has something to show. False is phase 0 - the shaped grey rectangle - which
// every seeding path exists to keep off the screen.
bool has_visual() const
{
return (_tex && _tex->is_valid()) || (_vid_tex && _vid_tex->is_valid()) || is_valid(_staged_surface);
}
bool is_provisional() const
{
if (_is_placeholder || !_tex || !_tex->is_valid()) return true;
auto texture_dims = _tex->source_extent();
auto loaded_dims = _loaded.dimensions();
if (setting.show_rotated && flips_xy(_tex->_orientation)) std::swap(texture_dims.cx, texture_dims.cy);
if (setting.show_rotated && flips_xy(_loaded.orientation())) std::swap(loaded_dims.cx, loaded_dims.cy);
if (_loaded.is_preview)
return _display_bounds.width() > texture_dims.cx || _display_bounds.height() > texture_dims.cy;
const auto required_width = std::min(_display_bounds.width(), loaded_dims.cx);
const auto required_height = std::min(_display_bounds.height(), loaded_dims.cy);
return required_width > texture_dims.cx || required_height > texture_dims.cy;
}
// Everything decoded from _loaded that survives past a draw, deduplicated by buffer because these
// members routinely alias one surface. _loaded.s counts: a format that decodes straight to a
// surface has no encoded form, so its pixels are the only representation it has. The panorama's
// own surfaces are absent deliberately - release_undisplayed drops them before it measures, and a
// displayed texture is never measured at all.
size_t retained_decoded_bytes() const noexcept
{
std::array<const core::surface*, 4> seen{};
size_t seen_count = 0;
size_t bytes = 0;
const auto add = [&seen, &seen_count, &bytes](const core::const_surface_ptr& s)
{
if (!s) return;
for (size_t i = 0; i < seen_count; ++i)
if (seen[i] == s.get()) return;
seen[seen_count++] = s.get();
bytes += s->size();
};
add(_loaded.s);
add(_staged_surface);
add(_retained_surface);
add(_zoom_staged_surface);
return bytes;
}
};
using texture_state_ptr = std::shared_ptr<texture_state>;
// zoom.md: looking around inside a projected panorama. Held beside the zoom state and for the same
// reason - it is the view rather than the picture - and keyed on the path, so moving to another
// panorama opens at that file's own centre instead of wherever the last one was left. UI-thread
// owned; the geometry read is published back through queue_ui against this path.
struct panorama_session
{
core::file_path path;
sizei source;
core::date_t modified;
prop::panorama_geometry geometry;
panorama_view view;
// The declaration has been looked up for this path, source size and file revision, whether or not
// it produced a crop.
bool resolved = false;
bool reset_view_on_resolve = false;
// The user asked for the flat pixels of this file. Per item, because it is a judgement about
// one picture - reading its stitching seams - not a preference about panoramas.
bool flat = false;
};
struct common_display_state_t
{
// True only while the slideshow mode is running. Media transport state lives on the av_session.
bool _is_slideshow = false;
df::zoom_view_state _zoom;
panorama_session _panorama;
std::vector<std::pair<core::file_path, texture_state_ptr>> _recent_textures;
static constexpr size_t max_recent_textures = 5;
void retain_texture(const core::file_path path, const texture_state_ptr& texture)
{
if (!texture) return;
std::erase_if(_recent_textures, [&path](const auto& entry) { return entry.first == path; });
_recent_textures.emplace(_recent_textures.begin(), path, texture);
while (_recent_textures.size() > max_recent_textures) _recent_textures.pop_back();
}
// Nothing off the display keeps decoded pixels. A JPEG holds its encoded file, and re-decoding that
// at display size costs less than the surface costs to keep, so retaining the surface buys nothing.
// What survives is what has no compressed form at all - HEIF, JXL, PSD and a developed RAW decode
// straight to a surface - and that irreproducible remainder is the only thing worth budgeting.
void release_undisplayed(const texture_state_ptr& displayed1, const texture_state_ptr& displayed2)
{
std::vector<retained_texture_budget_entry> entries;
entries.reserve(_recent_textures.size());
for (const auto& [path, texture] : _recent_textures)
{
const auto displayed = texture == displayed1 || texture == displayed2;
if (!displayed) texture->release_decoded_surfaces();
entries.push_back({displayed, displayed ? size_t{0} : texture->retained_decoded_bytes()});
}
// About what the displayed image itself is allowed, so the cache can carry one expensive decode
// forward rather than several.
const auto budget = static_cast<size_t>(render::max_texture_bytes);
for (const auto index : retained_texture_eviction_indexes(entries, budget))
_recent_textures.erase(_recent_textures.begin() + index);
}
// Nothing here is on screen; the displayed textures are held by the display state itself.
void clear_retained_textures() { _recent_textures.clear(); }
};
struct group_and_item
{
df::item_group_ptr group;
df::item_element_ptr item;
};
class filter_t
{
std::unordered_set<file_group_ref> _groups;
std::string _text;
std::string _input_text;
public:
filter_t() = default;
bool match_group(const file_group_ref group) const { return _groups.empty() || _groups.contains(group); }
bool has_group(const file_group_ref group) const { return _groups.contains(group); }
const std::unordered_set<file_group_ref>& groups() const { return _groups; }
void add_group(const file_group_ref group) { _groups.emplace(group); }
bool match_text(const core::cached text) const
{
if (_text.empty()) return true;
if (_text.length() == 1 && _text[0] != '*' && _text[0] != '?') return starts(text, _text);
return wildcard_icmp(text, _text);
}
bool match(const df::item_element_ptr& i) const
{
return match_text(i->name()) && match_group(i->file_type()->group);
}
void toggle(const file_group_ref g)
{
if (_groups.contains(g))
{
_groups.erase(g);
}
else
{
_groups.emplace(g);
}
}
void clear()
{
_groups.clear();
_text.clear();
_input_text.clear();
}
void wildcard(const std::string_view text)
{
_input_text = text;
if (text.length() > 1)
{
_text = "*";
_text += text;
_text += "*";
}
else
{
_text = text;
}
}
[[nodiscard]] std::string text() const { return _input_text; }
bool is_empty() const { return _text.empty() && _groups.empty(); }
};