diff options
| author | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
|---|---|---|
| committer | mirror <mirror@localhost> | 2026-11-22 08:41:00 +0900 |
| commit | 449d8b74bd6d9dae98a07254cdfad677b920e7b0 (patch) | |
| tree | c131c3528c4d517f56e19b854a7453fedb097d40 /lib/model/source/location | |
| download | aves-src-master.tar.gz aves-src-master.zip | |
Diffstat (limited to 'lib/model/source/location')
| -rw-r--r-- | lib/model/source/location/country.dart | 64 | ||||
| -rw-r--r-- | lib/model/source/location/location.dart | 208 | ||||
| -rw-r--r-- | lib/model/source/location/place.dart | 58 | ||||
| -rw-r--r-- | lib/model/source/location/state.dart | 64 |
4 files changed, 394 insertions, 0 deletions
diff --git a/lib/model/source/location/country.dart b/lib/model/source/location/country.dart new file mode 100644 index 0000000..f799407 --- /dev/null +++ b/lib/model/source/location/country.dart @@ -0,0 +1,64 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:collection/collection.dart'; + +mixin CountryMixin on SourceBase { + // by country code + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidateCountryFilterSummary({ + Set<AvesEntry>? entries, + Set<String>? countryCodes, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && countryCodes == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + countryCodes ??= {}; + if (entries != null) { + countryCodes.addAll(entries.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.countryCode).nonNulls); + } + countryCodes.forEach((countryCode) { + _filterEntryCountMap.remove(countryCode); + _filterSizeMap.remove(countryCode); + _filterRecentEntryMap.remove(countryCode); + }); + } + if (notify) { + eventBus.fire(CountrySummaryInvalidatedEvent(countryCodes)); + } + } + + int countryEntryCount(LocationFilter filter) { + final countryCode = filter.code; + if (countryCode == null) return 0; + return _filterEntryCountMap.putIfAbsent(countryCode, () => visibleEntries.where(filter.test).length); + } + + int countrySize(LocationFilter filter) { + final countryCode = filter.code; + if (countryCode == null) return 0; + return _filterSizeMap.putIfAbsent(countryCode, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? countryRecentEntry(LocationFilter filter) { + final countryCode = filter.code; + if (countryCode == null) return null; + return _filterRecentEntryMap.putIfAbsent(countryCode, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } +} + +class CountriesChangedEvent {} + +class CountrySummaryInvalidatedEvent { + final Set<String>? countryCodes; + + const CountrySummaryInvalidatedEvent(this.countryCodes); +} diff --git a/lib/model/source/location/location.dart b/lib/model/source/location/location.dart new file mode 100644 index 0000000..30ca150 --- /dev/null +++ b/lib/model/source/location/location.dart @@ -0,0 +1,208 @@ +import 'dart:math'; + +import 'package:aves/geo/countries.dart'; +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/entry/extensions/location.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/metadata/address.dart'; +import 'package:aves/model/settings/settings.dart'; +import 'package:aves/model/source/analysis_controller.dart'; +import 'package:aves/model/source/location/country.dart'; +import 'package:aves/model/source/location/place.dart'; +import 'package:aves/model/source/location/state.dart'; +import 'package:aves/services/common/services.dart'; +import 'package:aves_model/aves_model.dart'; +import 'package:collection/collection.dart'; +import 'package:flutter/foundation.dart'; + +mixin LocationMixin on CountryMixin, StateMixin { + static const commitCountThreshold = 200; + static const _stopCheckCountThreshold = 50; + + List<String> sortedCountries = List.unmodifiable([]); + List<String> sortedStates = List.unmodifiable([]); + List<String> sortedPlaces = List.unmodifiable([]); + + Future<void> loadAddresses({Set<int>? ids}) async { + final saved = await (ids != null ? localMediaDb.loadAddressesById(ids) : localMediaDb.loadAddresses()); + final idMap = entryById; + saved.forEach((metadata) => idMap[metadata.id]?.addressDetails = metadata); + invalidateEntries(); + onAddressMetadataChanged(); + } + + Future<void> locateEntries(AnalysisController controller, Set<AvesEntry> candidateEntries) async { + await _locateCountries(controller, candidateEntries); + await _locatePlaces(controller, candidateEntries); + + final unlocatedIds = candidateEntries.where((entry) => !entry.hasGps).map((entry) => entry.id).toSet(); + if (unlocatedIds.isNotEmpty) { + await localMediaDb.removeIds(unlocatedIds, dataTypes: {EntryDataType.address}); + onAddressMetadataChanged(); + } + } + + static bool locateCountriesTest(AvesEntry entry) => entry.hasGps && !entry.hasAddress; + + static bool locatePlacesTest(AvesEntry entry) => entry.hasGps && !entry.hasFineAddress; + + // quick reverse geocoding to find the countries, using an offline asset + Future<void> _locateCountries(AnalysisController controller, Set<AvesEntry> candidateEntries) async { + if (controller.isStopping) return; + + final force = controller.force; + final todo = (force ? candidateEntries.where((entry) => entry.hasGps) : candidateEntries.where(locateCountriesTest)).toSet(); + if (todo.isEmpty) return; + + state = SourceState.locatingCountries; + var progressDone = 0; + final progressTotal = todo.length; + setProgress(done: progressDone, total: progressTotal); + + final countryCodeMap = await countryTopology.countryCodeMap(todo.map((entry) => entry.latLng!).toSet()); + final newAddresses = <AddressDetails>{}; + todo.forEach((entry) { + final position = entry.latLng; + final countryCode = countryCodeMap.entries.firstWhereOrNull((kv) => kv.value.contains(position))?.key; + entry.setCountry(countryCode); + if (entry.hasAddress) { + newAddresses.add(entry.addressDetails!); + } + setProgress(done: ++progressDone, total: progressTotal); + }); + if (newAddresses.isNotEmpty) { + await localMediaDb.saveAddresses(Set.unmodifiable(newAddresses)); + onAddressMetadataChanged(); + } + } + + // full reverse geocoding, requiring geocoder and some connectivity + Future<void> _locatePlaces(AnalysisController controller, Set<AvesEntry> candidateEntries) async { + if (controller.isStopping) return; + if (!await availability.canLocatePlaces) return; + + final force = controller.force; + final todo = (force ? candidateEntries.where((entry) => entry.hasGps) : candidateEntries.where(locatePlacesTest)).toSet(); + if (todo.isEmpty) return; + + // geocoder calls take between 150ms and 250ms + // approximation and caching can reduce geocoder usage + // for example, for a set of 2932 entries: + // - 2476 calls (84%) when approximating to 6 decimal places (~10cm - individual humans) + // - 2433 calls (83%) when approximating to 5 decimal places (~1m - individual trees, houses) + // - 2277 calls (78%) when approximating to 4 decimal places (~10m - individual street, large buildings) + // - 1521 calls (52%) when approximating to 3 decimal places (~100m - neighborhood, street) + // - 652 calls (22%) when approximating to 2 decimal places (~1km - town or village) + // cf https://en.wikipedia.org/wiki/Decimal_degrees#Precision + final latLngFactor = pow(10, 2); + (int latitude, int longitude) approximateLatLng(AvesEntry entry) { + // entry has coordinates + final catalogMetadata = entry.catalogMetadata!; + final lat = catalogMetadata.latitude!; + final lng = catalogMetadata.longitude!; + return ((lat * latLngFactor).round(), (lng * latLngFactor).round()); + } + + final located = visibleEntries.where((entry) => entry.hasGps).toSet().difference(todo); + final knownLocations = <(int, int), AddressDetails?>{}; + located.forEach((entry) { + knownLocations.putIfAbsent(approximateLatLng(entry), () => entry.addressDetails); + }); + + state = SourceState.locatingPlaces; + var progressDone = 0; + final progressTotal = todo.length; + setProgress(done: progressDone, total: progressTotal); + + var stopCheckCount = 0; + final newAddresses = <AddressDetails>{}; + for (final entry in todo) { + final latLng = approximateLatLng(entry); + if (knownLocations.containsKey(latLng)) { + entry.addressDetails = knownLocations[latLng]?.copyWith(id: entry.id); + } else { + await entry.locatePlace(background: true, force: force, geocoderLocale: settings.appliedLocale); + // it is intended to insert `null` if the geocoder failed, + // so that we skip geocoding of following entries with the same coordinates + knownLocations[latLng] = entry.addressDetails; + } + if (entry.hasFineAddress) { + newAddresses.add(entry.addressDetails!); + if (newAddresses.length >= commitCountThreshold) { + await localMediaDb.saveAddresses(Set.unmodifiable(newAddresses)); + onAddressMetadataChanged(); + newAddresses.clear(); + } + if (++stopCheckCount >= _stopCheckCountThreshold) { + stopCheckCount = 0; + if (controller.isStopping) return; + } + } + setProgress(done: ++progressDone, total: progressTotal); + } + if (newAddresses.isNotEmpty) { + await localMediaDb.saveAddresses(Set.unmodifiable(newAddresses)); + onAddressMetadataChanged(); + } + } + + void onAddressMetadataChanged() { + updateLocations(); + eventBus.fire(AddressMetadataChangedEvent()); + } + + void updateLocations() { + final locations = visibleEntries.map((entry) => entry.addressDetails).nonNulls.toList(); + + final updatedPlaces = locations.map((address) => address.place).nonNulls.where((v) => v.isNotEmpty).toSet().toList()..sort(compareAsciiUpperCase); + if (!listEquals(updatedPlaces, sortedPlaces)) { + sortedPlaces = List.unmodifiable(updatedPlaces); + eventBus.fire(PlacesChangedEvent()); + } + + final updatedStates = _getAreaByCode( + locations: locations, + getCode: (v) => v.stateCode, + getName: (v) => v.stateName, + ); + if (!listEquals(updatedStates, sortedStates)) { + sortedStates = List.unmodifiable(updatedStates); + invalidateStateFilterSummary(); + eventBus.fire(StatesChangedEvent()); + } + + final updatedCountries = _getAreaByCode( + locations: locations, + getCode: (v) => v.countryCode, + getName: (v) => v.countryName, + ); + if (!listEquals(updatedCountries, sortedCountries)) { + sortedCountries = List.unmodifiable(updatedCountries); + invalidateCountryFilterSummary(); + eventBus.fire(CountriesChangedEvent()); + } + } + + // the same country/state code could be found with different country/state names + // e.g. if the locale changed between geocoding calls + // so we merge countries/states by code, keeping only one name for each code + List<String> _getAreaByCode({ + required List<AddressDetails> locations, + required String? Function(AddressDetails address) getCode, + required String? Function(AddressDetails address) getName, + }) { + final namesByCode = Map.fromEntries(locations.map((address) { + final code = getCode(address); + if (code == null || code.isEmpty) return null; + return MapEntry(code, getName(address)); + }).nonNulls); + return namesByCode.entries.map((kv) { + final code = kv.key; + final name = kv.value; + return '${name != null && name.isNotEmpty ? name : code}${LocationFilter.locationSeparator}$code'; + }).toList() + ..sort(compareAsciiUpperCase); + } +} + +class AddressMetadataChangedEvent {} diff --git a/lib/model/source/location/place.dart b/lib/model/source/location/place.dart new file mode 100644 index 0000000..42d7cd3 --- /dev/null +++ b/lib/model/source/location/place.dart @@ -0,0 +1,58 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:collection/collection.dart'; + +mixin PlaceMixin on SourceBase { + // by place + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidatePlaceFilterSummary({ + Set<AvesEntry>? entries, + Set<String>? places, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && places == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + places ??= {}; + if (entries != null) { + places.addAll(entries.map((entry) => entry.addressDetails?.place).nonNulls); + } + places.forEach((place) { + _filterEntryCountMap.remove(place); + _filterSizeMap.remove(place); + _filterRecentEntryMap.remove(place); + }); + } + if (notify) { + eventBus.fire(PlaceSummaryInvalidatedEvent(places)); + } + } + + int placeEntryCount(LocationFilter filter) { + return _filterEntryCountMap.putIfAbsent(filter.place, () => visibleEntries.where(filter.test).length); + } + + int placeSize(LocationFilter filter) { + return _filterSizeMap.putIfAbsent(filter.place, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? placeRecentEntry(LocationFilter filter) { + return _filterRecentEntryMap.putIfAbsent(filter.place, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } +} + +class PlacesChangedEvent {} + +class PlaceSummaryInvalidatedEvent { + final Set<String>? places; + + const PlaceSummaryInvalidatedEvent(this.places); +} diff --git a/lib/model/source/location/state.dart b/lib/model/source/location/state.dart new file mode 100644 index 0000000..8eb4abd --- /dev/null +++ b/lib/model/source/location/state.dart @@ -0,0 +1,64 @@ +import 'package:aves/model/entry/entry.dart'; +import 'package:aves/model/filters/covered/location.dart'; +import 'package:aves/model/source/collection_source.dart'; +import 'package:aves/utils/collection_utils.dart'; +import 'package:collection/collection.dart'; + +mixin StateMixin on SourceBase { + // by state code + final Map<String, int> _filterEntryCountMap = {}, _filterSizeMap = {}; + final Map<String, AvesEntry?> _filterRecentEntryMap = {}; + + void invalidateStateFilterSummary({ + Set<AvesEntry>? entries, + Set<String>? stateCodes, + bool notify = true, + }) { + if (_filterEntryCountMap.isEmpty && _filterSizeMap.isEmpty && _filterRecentEntryMap.isEmpty) return; + + if (entries == null && stateCodes == null) { + _filterEntryCountMap.clear(); + _filterSizeMap.clear(); + _filterRecentEntryMap.clear(); + } else { + stateCodes ??= {}; + if (entries != null) { + stateCodes.addAll(entries.where((entry) => entry.hasAddress).map((entry) => entry.addressDetails?.stateCode).nonNulls); + } + stateCodes.forEach((stateCode) { + _filterEntryCountMap.remove(stateCode); + _filterSizeMap.remove(stateCode); + _filterRecentEntryMap.remove(stateCode); + }); + } + if (notify) { + eventBus.fire(StateSummaryInvalidatedEvent(stateCodes)); + } + } + + int stateEntryCount(LocationFilter filter) { + final stateCode = filter.code; + if (stateCode == null) return 0; + return _filterEntryCountMap.putIfAbsent(stateCode, () => visibleEntries.where(filter.test).length); + } + + int stateSize(LocationFilter filter) { + final stateCode = filter.code; + if (stateCode == null) return 0; + return _filterSizeMap.putIfAbsent(stateCode, () => visibleEntries.where(filter.test).map((v) => v.sizeBytes).sum); + } + + AvesEntry? stateRecentEntry(LocationFilter filter) { + final stateCode = filter.code; + if (stateCode == null) return null; + return _filterRecentEntryMap.putIfAbsent(stateCode, () => sortedEntriesByDate.firstWhereOrNull(filter.test)); + } +} + +class StatesChangedEvent {} + +class StateSummaryInvalidatedEvent { + final Set<String>? stateCodes; + + const StateSummaryInvalidatedEvent(this.stateCodes); +} |
