aboutsummaryrefslogtreecommitdiff
path: root/lib/model/source/collection_source.dart
blob: e591691068c8f137c9a264a1b3e0ebed57a3bc8e (plain) (blame)
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
import 'dart:async';
import 'dart:ui';

import 'package:aves/model/covers.dart';
import 'package:aves/model/entry/entry.dart';
import 'package:aves/model/entry/extensions/catalog.dart';
import 'package:aves/model/entry/extensions/keys.dart';
import 'package:aves/model/entry/extensions/location.dart';
import 'package:aves/model/entry/sort.dart';
import 'package:aves/model/favourites.dart';
import 'package:aves/model/filters/container/album_group.dart';
import 'package:aves/model/filters/container/tag_group.dart';
import 'package:aves/model/filters/covered/location.dart';
import 'package:aves/model/filters/covered/stored_album.dart';
import 'package:aves/model/filters/filters.dart';
import 'package:aves/model/filters/trash.dart';
import 'package:aves/model/grouping/common.dart';
import 'package:aves/model/grouping/convert.dart';
import 'package:aves/model/metadata/trash.dart';
import 'package:aves/model/settings/settings.dart';
import 'package:aves/model/source/album.dart';
import 'package:aves/model/source/analysis_controller.dart';
import 'package:aves/model/source/events.dart';
import 'package:aves/model/source/location/country.dart';
import 'package:aves/model/source/location/location.dart';
import 'package:aves/model/source/location/place.dart';
import 'package:aves/model/source/location/state.dart';
import 'package:aves/model/source/tag.dart';
import 'package:aves/model/source/trash.dart';
import 'package:aves/model/vaults/vaults.dart';
import 'package:aves/services/analysis_service.dart';
import 'package:aves/services/common/image_op_events.dart';
import 'package:aves/services/common/services.dart';
import 'package:aves/widgets/aves_app.dart';
import 'package:aves_model/aves_model.dart';
import 'package:collection/collection.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/foundation.dart';
import 'package:leak_tracker/leak_tracker.dart';

typedef SourceScope = Set<CollectionFilter>?;

mixin SourceBase {
  EventBus get eventBus;

  Map<int, AvesEntry> get entryById;

  Set<AvesEntry> get allEntries;

  Set<AvesEntry> get visibleEntries;

  Set<AvesEntry> get trashedEntries;

  List<AvesEntry> get sortedEntriesByDate;

  ValueNotifier<SourceState> stateNotifier = ValueNotifier(SourceState.ready);

  set state(SourceState value) => stateNotifier.value = value;

  SourceState get state => stateNotifier.value;

  bool get isReady => state == SourceState.ready;

  ValueNotifier<ProgressEvent> progressNotifier = ValueNotifier(const ProgressEvent(done: 0, total: 0));

  void setProgress({required int done, required int total}) => progressNotifier.value = ProgressEvent(done: done, total: total);

  void invalidateEntries();
}

abstract class CollectionSource with SourceBase, AlbumMixin, CountryMixin, PlaceMixin, StateMixin, LocationMixin, TagMixin, TrashMixin {
  static const fullScope = <CollectionFilter>{};

  CollectionSource() {
    if (kFlutterMemoryAllocationsEnabled) {
      LeakTracking.dispatchObjectCreated(
        library: 'aves',
        className: '$CollectionSource',
        object: this,
      );
    }
    settings.updateStream.where((event) => event.key == SettingKeys.localeKey).listen((_) => invalidateStoredAlbumDisplayNames());
    settings.updateStream.where((event) => event.key == SettingKeys.hiddenFiltersKey).listen((event) {
      final oldValue = event.oldValue;
      if (oldValue is List<String>?) {
        final oldHiddenFilters = (oldValue ?? []).map(CollectionFilter.fromJson).nonNulls.toSet();
        final newlyVisibleFilters = oldHiddenFilters.whereNot(settings.hiddenFilters.contains).toSet();
        _onFilterVisibilityChanged(newlyVisibleFilters);
      }
    });
    vaults.addListener(_onVaultsChanged);
  }

  @mustCallSuper
  void dispose() {
    if (kFlutterMemoryAllocationsEnabled) {
      LeakTracking.dispatchObjectDisposed(object: this);
    }
    vaults.removeListener(_onVaultsChanged);
    _rawEntries.forEach((v) => v.dispose());
  }

  set canAnalyze(bool enabled);

  final EventBus _eventBus = EventBus();

  @override
  EventBus get eventBus => _eventBus;

  final Map<int, AvesEntry> _entryById = {};

  @override
  Map<int, AvesEntry> get entryById => Map.unmodifiable(_entryById);

  final Set<AvesEntry> _rawEntries = {};

  @override
  Set<AvesEntry> get allEntries => Set.unmodifiable(_rawEntries);

  Set<AvesEntry>? _visibleEntries, _trashedEntries;

  @override
  Set<AvesEntry> get visibleEntries {
    _visibleEntries ??= Set.unmodifiable(_applyHiddenFilters(_rawEntries));
    return _visibleEntries!;
  }

  @override
  Set<AvesEntry> get trashedEntries {
    _trashedEntries ??= Set.unmodifiable(_applyTrashFilter(_rawEntries));
    return _trashedEntries!;
  }

  List<AvesEntry>? _sortedEntriesByDate;

  @override
  List<AvesEntry> get sortedEntriesByDate {
    _sortedEntriesByDate ??= List.unmodifiable(visibleEntries.toList()..sort(AvesEntrySort.compareByDate));
    return _sortedEntriesByDate!;
  }

  // known date by entry ID
  late Map<int?, int?> _savedDates;

  Future<void> loadDates() async {
    _savedDates = Map.unmodifiable(await localMediaDb.loadDates());
  }

  Set<CollectionFilter> _getAppHiddenFilters() => {
        ...settings.hiddenFilters,
        ...vaults.vaultDirectories.where(vaults.isLocked).map((v) => StoredAlbumFilter(v, null)),
      };

  Iterable<AvesEntry> _applyHiddenFilters(Iterable<AvesEntry> entries) {
    final hiddenFilters = {
      TrashFilter.instance,
      ..._getAppHiddenFilters(),
    };
    return entries.where((entry) => !hiddenFilters.any((filter) => filter.test(entry)));
  }

  Iterable<AvesEntry> _applyTrashFilter(Iterable<AvesEntry> entries) {
    final hiddenFilters = _getAppHiddenFilters();
    return entries.where(TrashFilter.instance.test).where((entry) => !hiddenFilters.any((filter) => filter.test(entry)));
  }

  void _invalidate({Set<AvesEntry>? entries, bool notify = true}) {
    invalidateEntries();
    invalidateAlbumFilterSummary(entries: entries, notify: notify);
    invalidateCountryFilterSummary(entries: entries, notify: notify);
    invalidatePlaceFilterSummary(entries: entries, notify: notify);
    invalidateStateFilterSummary(entries: entries, notify: notify);
    invalidateTagFilterSummary(entries: entries, notify: notify);
  }

  @override
  void invalidateEntries() {
    _visibleEntries = null;
    _trashedEntries = null;
    _sortedEntriesByDate = null;
  }

  void updateDerivedFilters([Set<AvesEntry>? entries]) {
    _invalidate(entries: entries);
    // it is possible for entries hidden by a filter type, to have an impact on other types
    // e.g. given a sole entry for country C and tag T, hiding T should make C disappear too
    updateDirectories();
    updateLocations();
    updateTags();
  }

  void addEntries(Set<AvesEntry> entries, {bool notify = true}) {
    if (entries.isEmpty) return;

    final newIdMapEntries = Map.fromEntries(entries.map((entry) => MapEntry(entry.id, entry)));
    if (_rawEntries.isNotEmpty) {
      final newIds = newIdMapEntries.keys.toSet();
      _rawEntries.removeWhere((entry) => newIds.contains(entry.id));
    }

    entries.where((entry) => entry.catalogDateMillis == null).forEach((entry) {
      entry.catalogDateMillis = _savedDates[entry.id];
    });

    _entryById.addAll(newIdMapEntries);
    _rawEntries.addAll(entries);
    _invalidate(entries: entries, notify: notify);

    addDirectories(albums: _applyHiddenFilters(entries).map((entry) => entry.directory).toSet(), notify: notify);
    if (notify) {
      eventBus.fire(EntryAddedEvent(entries));
    }
  }

  Future<void> removeEntries(Set<String> uris, {required bool includeTrash}) async {
    if (uris.isEmpty) return;

    final entries = _rawEntries.where((entry) => uris.contains(entry.uri)).toSet();
    if (!includeTrash) {
      entries.removeWhere(TrashFilter.instance.test);
    }
    if (entries.isEmpty) return;

    final ids = entries.map((entry) => entry.id).toSet();
    await favourites.removeIds(ids);
    await covers.removeIds(ids);
    await localMediaDb.removeIds(ids);

    ids.forEach((id) => _entryById.remove);
    _rawEntries.removeAll(entries);
    updateDerivedFilters(entries);
    eventBus.fire(EntryRemovedEvent(entries));
  }

  void clearEntries() {
    _entryById.clear();
    _rawEntries.clear();
    _invalidate();

    // do not update directories/locations/tags here
    // as it could reset filter dependent settings (pins, bookmarks, etc.)
    // caller should take care of updating these at the right time
  }

  Future<void> _moveEntry(AvesEntry entry, Map newFields, {required bool persist}) async {
    newFields.keys.forEach((key) {
      final newValue = newFields[key];
      switch (key) {
        case EntryFields.contentId:
          entry.contentId = newValue as int?;
        case EntryFields.dateModifiedMillis:
          // `dateModifiedMillis` changes when moving entries to another directory,
          // but it does not change when renaming the containing directory
          entry.dateModifiedMillis = newValue as int?;
        case EntryFields.path:
          entry.path = newValue as String?;
        case EntryFields.title:
          entry.sourceTitle = newValue as String?;
        case EntryFields.trashed:
          final trashed = newValue as bool;
          entry.trashed = trashed;
          entry.trashDetails = trashed
              ? TrashDetails(
                  id: entry.id,
                  path: newFields[EntryFields.trashPath] as String,
                  dateMillis: DateTime.now().millisecondsSinceEpoch,
                )
              : null;
        case EntryFields.uri:
          entry.uri = newValue as String;
        case EntryFields.origin:
          entry.origin = newValue as int;
      }
    });
    if (entry.trashed) {
      final trashPath = entry.trashDetails?.path;
      if (trashPath != null) {
        entry.contentId = null;
        entry.uri = Uri.file(trashPath).toString();
      } else {
        debugPrint('failed to update uri from unknown trash path for uri=${entry.uri}');
      }
    }

    if (persist) {
      await covers.moveEntry(entry);
      final id = entry.id;
      await localMediaDb.updateEntry(id, entry);
      await localMediaDb.updateCatalogMetadata(id, entry.catalogMetadata);
      await localMediaDb.updateAddress(id, entry.addressDetails);
      await localMediaDb.updateTrash(id, entry.trashDetails);
    }
  }

  Future<void> renameStoredAlbum(String sourceAlbum, String destinationAlbum, Set<AvesEntry> entries, Set<MoveOpEvent> movedOps) async {
    final oldFilter = StoredAlbumFilter(sourceAlbum, null);
    final newFilter = StoredAlbumFilter(destinationAlbum, null);

    final group = albumGrouping.getFilterParent(oldFilter);
    final pinned = settings.pinnedFilters.contains(oldFilter);

    if (vaults.isVault(sourceAlbum)) {
      await vaults.rename(sourceAlbum, destinationAlbum);
    }

    final existingCover = covers.of(oldFilter);
    await covers.set(
      filter: newFilter,
      entryId: existingCover?.$1,
      packageName: existingCover?.$2,
      color: existingCover?.$3,
    );

    renameNewAlbum(sourceAlbum, destinationAlbum);
    await updateAfterMove(
      todoEntries: entries,
      moveType: MoveType.move,
      destinationAlbums: {destinationAlbum},
      movedOps: movedOps,
    );

    // update bookmark
    final albumBookmarks = settings.drawerAlbumBookmarks;
    if (albumBookmarks != null) {
      final index = albumBookmarks.indexWhere((v) => v is StoredAlbumFilter && v.album == sourceAlbum);
      if (index >= 0) {
        albumBookmarks.removeAt(index);
        albumBookmarks.insert(index, newFilter);
        settings.drawerAlbumBookmarks = albumBookmarks;
      }
    }
    // update group
    if (group != null) {
      final newFilterUri = GroupingConversion.filterToUri(newFilter);
      if (newFilterUri != null) {
        albumGrouping.addToGroup({newFilterUri}, group);
      }
      final oldFilterUri = GroupingConversion.filterToUri(oldFilter);
      if (oldFilterUri != null) {
        albumGrouping.addToGroup({oldFilterUri}, null);
      }
    }
    // restore pin, as the obsolete album got removed and its associated state cleaned
    if (pinned) {
      settings.pinnedFilters = settings.pinnedFilters
        ..remove(oldFilter)
        ..add(newFilter);
    }
  }

  Future<void> updateAfterMove({
    required Set<AvesEntry> todoEntries,
    required MoveType moveType,
    required Set<String> destinationAlbums,
    required Set<MoveOpEvent> movedOps,
  }) async {
    if (movedOps.isEmpty) return;

    final replacedUris = movedOps
        .map((movedOp) => movedOp.newFields[EntryFields.path] as String?)
        .map((targetPath) {
          final existingEntry = _rawEntries.firstWhereOrNull((entry) => entry.path == targetPath && !entry.trashed);
          return existingEntry?.uri;
        })
        .nonNulls
        .toSet();
    await removeEntries(replacedUris, includeTrash: false);

    final fromAlbums = <String?>{};
    final movedEntries = <AvesEntry>{};
    final copy = moveType == MoveType.copy;
    if (copy) {
      movedOps.forEach((movedOp) {
        final sourceUri = movedOp.uri;
        final newFields = movedOp.newFields;
        final sourceEntry = todoEntries.firstWhereOrNull((entry) => entry.uri == sourceUri);
        if (sourceEntry != null) {
          fromAlbums.add(sourceEntry.directory);
          movedEntries.add(sourceEntry.copyWith(
            id: localMediaDb.nextId,
            uri: newFields[EntryFields.uri] as String?,
            path: newFields[EntryFields.path] as String?,
            contentId: newFields[EntryFields.contentId] as int?,
            // title can change when moved files are automatically renamed to avoid conflict
            title: newFields[EntryFields.title] as String?,
            dateAddedSecs: newFields[EntryFields.dateAddedSecs] as int?,
            dateModifiedMillis: newFields[EntryFields.dateModifiedMillis] as int?,
            origin: newFields[EntryFields.origin] as int?,
          ));
        } else {
          debugPrint('failed to find source entry with uri=$sourceUri');
        }
      });
      await localMediaDb.insertEntries(movedEntries);
      await localMediaDb.saveCatalogMetadata(movedEntries.map((entry) => entry.catalogMetadata).nonNulls.toSet());
      await localMediaDb.saveAddresses(movedEntries.map((entry) => entry.addressDetails).nonNulls.toSet());
    } else {
      await Future.forEach<MoveOpEvent>(movedOps, (movedOp) async {
        final newFields = movedOp.newFields;
        if (newFields.isNotEmpty) {
          final sourceUri = movedOp.uri;
          final entry = todoEntries.firstWhereOrNull((entry) => entry.uri == sourceUri);
          if (entry != null) {
            if (moveType == MoveType.fromBin) {
              newFields[EntryFields.trashed] = false;
            } else {
              fromAlbums.add(entry.directory);
            }
            movedEntries.add(entry);
            await _moveEntry(entry, newFields, persist: true);
          }
        }
      });
    }

    switch (moveType) {
      case MoveType.copy:
        addEntries(movedEntries);
      case MoveType.move:
      case MoveType.export:
        cleanEmptyAlbums(fromAlbums.nonNulls.toSet());
        addDirectories(albums: destinationAlbums);
      case MoveType.toBin:
      case MoveType.fromBin:
        updateDerivedFilters(movedEntries);
    }
    invalidateAlbumFilterSummary(directories: fromAlbums);
    _invalidate(entries: movedEntries);
    eventBus.fire(EntryMovedEvent(moveType, movedEntries));
  }

  Future<void> updateAfterRename({
    required Set<AvesEntry> todoEntries,
    required Set<MoveOpEvent> movedOps,
    required bool persist,
  }) async {
    if (movedOps.isEmpty) return;

    final movedEntries = <AvesEntry>{};
    await Future.forEach<MoveOpEvent>(movedOps, (movedOp) async {
      final newFields = movedOp.newFields;
      if (newFields.isNotEmpty) {
        final sourceUri = movedOp.uri;
        final entry = todoEntries.firstWhereOrNull((entry) => entry.uri == sourceUri);
        if (entry != null) {
          movedEntries.add(entry);
          await _moveEntry(entry, newFields, persist: persist);
        }
      }
    });

    eventBus.fire(EntryMovedEvent(MoveType.move, movedEntries));
  }

  SourceScope get loadedScope;

  SourceScope get targetScope;

  Future<void> init({
    required SourceScope scope,
    AnalysisController? analysisController,
    bool loadTopEntriesFirst = false,
  });

  Future<Set<String>> refreshUris(Set<String> changedUris, {AnalysisController? analysisController});

  Future<void> refreshEntries(Set<AvesEntry> entries, Set<EntryDataType> dataTypes) async {
    const background = false;
    const persist = true;

    await Future.forEach(entries, (entry) async {
      await entry.refresh(background: background, persist: persist, dataTypes: dataTypes);
    });

    if (dataTypes.contains(EntryDataType.aspectRatio)) {
      onAspectRatioChanged();
    }

    if (dataTypes.contains(EntryDataType.catalog)) {
      // explicit GC before cataloguing multiple items
      await deviceService.requestGarbageCollection();
      await Future.forEach(entries, (entry) async {
        await entry.catalog(background: background, force: dataTypes.contains(EntryDataType.catalog), persist: persist);
        await localMediaDb.updateCatalogMetadata(entry.id, entry.catalogMetadata);
      });
      onCatalogMetadataChanged();
    }

    if (dataTypes.contains(EntryDataType.address)) {
      await Future.forEach(entries, (entry) async {
        await entry.locate(background: background, force: dataTypes.contains(EntryDataType.address), geocoderLocale: settings.appliedLocale);
        await localMediaDb.updateAddress(entry.id, entry.addressDetails);
      });
      onAddressMetadataChanged();
    }

    updateDerivedFilters(entries);
    eventBus.fire(EntryRefreshedEvent(entries));
  }

  Future<void> analyze(AnalysisController? analysisController, {Set<AvesEntry>? entries}) async {
    // not only visible entries, as hidden and vault items may be analyzed
    final todoEntries = entries ?? allEntries;
    final defaultAnalysisController = AnalysisController();
    final _analysisController = analysisController ?? defaultAnalysisController;
    final force = _analysisController.force;
    if (!_analysisController.isStopping) {
      var startAnalysisService = false;
      if (_analysisController.canStartService && settings.canUseAnalysisService) {
        // cataloguing
        if (!startAnalysisService) {
          final opCount = (force ? todoEntries : todoEntries.where(TagMixin.catalogEntriesTest)).length;
          startAnalysisService = opCount > TagMixin.commitCountThreshold;
        }
        // ignore locating countries
        // locating places
        if (!startAnalysisService && await availability.canLocatePlaces) {
          final opCount = (force ? todoEntries.where((entry) => entry.hasGps) : todoEntries.where(LocationMixin.locatePlacesTest)).length;
          startAnalysisService = opCount > LocationMixin.commitCountThreshold;
        }
      }

      debugPrint('analyze ${todoEntries.length} entries, force=$force, starting service=$startAnalysisService');
      if (startAnalysisService) {
        final lifecycleState = AvesApp.lifecycleStateNotifier.value;
        switch (lifecycleState) {
          case AppLifecycleState.resumed:
          case AppLifecycleState.inactive:
            await AnalysisService.startService(
              force: force,
              entryIds: entries?.map((entry) => entry.id).toList(),
            );
          default:
            unawaited(reportService.log('analysis service not started because app is in state=$lifecycleState'));
        }
      } else {
        // explicit GC before cataloguing multiple items
        await deviceService.requestGarbageCollection();
        await catalogEntries(_analysisController, todoEntries);
        updateDerivedFilters(todoEntries);
        await locateEntries(_analysisController, todoEntries);
        updateDerivedFilters(todoEntries);
      }
    }
    defaultAnalysisController.dispose();
    state = SourceState.ready;
  }

  void onAspectRatioChanged() => eventBus.fire(AspectRatioChangedEvent());

  // monitoring

  bool _canRefresh = true;

  void pauseMonitoring() => _canRefresh = false;

  void resumeMonitoring() => _canRefresh = true;

  bool get canRefresh => _canRefresh;

  // filter summary

  int count(CollectionFilter filter) {
    switch (filter) {
      case AlbumBaseFilter _:
        return albumEntryCount(filter);
      case LocationFilter(level: LocationLevel.country):
        return countryEntryCount(filter);
      case LocationFilter(level: LocationLevel.state):
        return stateEntryCount(filter);
      case LocationFilter(level: LocationLevel.place):
        return placeEntryCount(filter);
      case TagBaseFilter _:
        return tagEntryCount(filter);
    }
    return 0;
  }

  int size(CollectionFilter filter) {
    switch (filter) {
      case AlbumBaseFilter _:
        return albumSize(filter);
      case LocationFilter(level: LocationLevel.country):
        return countrySize(filter);
      case LocationFilter(level: LocationLevel.state):
        return stateSize(filter);
      case LocationFilter(level: LocationLevel.place):
        return placeSize(filter);
      case TagBaseFilter _:
        return tagSize(filter);
    }
    return 0;
  }

  AvesEntry? recentEntry(CollectionFilter filter) {
    switch (filter) {
      case AlbumBaseFilter _:
        return albumRecentEntry(filter);
      case LocationFilter(level: LocationLevel.country):
        return countryRecentEntry(filter);
      case LocationFilter(level: LocationLevel.state):
        return stateRecentEntry(filter);
      case LocationFilter(level: LocationLevel.place):
        return placeRecentEntry(filter);
      case TagBaseFilter _:
        return tagRecentEntry(filter);
    }
    return null;
  }

  AvesEntry? coverEntry(CollectionFilter filter) {
    final id = covers.of(filter)?.$1;
    if (id != null) {
      final entry = visibleEntries.firstWhereOrNull((entry) => entry.id == id);
      if (entry != null) return entry;
    }
    return recentEntry(filter);
  }

  void _onFilterVisibilityChanged(Set<CollectionFilter> newlyVisibleFilters) {
    updateDerivedFilters();
    eventBus.fire(const FilterVisibilityChangedEvent());

    if (newlyVisibleFilters.isNotEmpty) {
      final candidateEntries = visibleEntries.where((entry) => newlyVisibleFilters.any((f) => f.test(entry))).toSet();
      analyze(null, entries: candidateEntries);
    }
  }

  void _onVaultsChanged() {
    final newlyVisibleFilters = vaults.vaultDirectories.whereNot(vaults.isLocked).map((v) => StoredAlbumFilter(v, null)).toSet();
    _onFilterVisibilityChanged(newlyVisibleFilters);
  }
}

class AspectRatioChangedEvent {}