Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Bound photo map marker clustering

Neeraj Guptaab62a8b9a625
diff --git a/mobile/apps/photos/lib/db/files_db.dart b/mobile/apps/photos/lib/db/files_db.dart
index 3a3a80ab1f..21ee5dc638 100644
--- a/mobile/apps/photos/lib/db/files_db.dart
+++ b/mobile/apps/photos/lib/db/files_db.dart
@@ -2006,7 +2006,10 @@ class FilesDB with SqlDbBase {
}
final results = await db.getAll(query, args);
- final files = convertToFiles(results);
+ final List<EnteFile> files = await Computer.shared().compute(
+ convertToFilesForIsolate,
+ param: {"result": results},
+ );
final List<EnteFile> filteredFiles = await applyDBFilters(
files,
filterOptions,
diff --git a/mobile/apps/photos/lib/services/search_service.dart b/mobile/apps/photos/lib/services/search_service.dart
index 145fd1eb6d..252d904721 100644
--- a/mobile/apps/photos/lib/services/search_service.dart
+++ b/mobile/apps/photos/lib/services/search_service.dart
@@ -295,6 +295,20 @@ class SearchService {
return _cachedFilesForSearch!;
}
+ Future<List<EnteFile>> getAllFilesWithLocationForSearch() async {
+ final result = await FilesDB.instance
+ .fetchAllUploadedAndSharedFilesWithLocation(
+ galleryLoadStartTime,
+ galleryLoadEndTime,
+ asc: false,
+ filterOptions: DBFilterOptions(
+ ignoredCollectionIDs: ignoreCollections(),
+ dedupeUploadID: true,
+ ),
+ );
+ return result.files;
+ }
+
Future<bool> hasAnyFilesForSearch() async {
if (_cachedFilesFuture != null && _cachedFilesForSearch != null) {
return (await _cachedFilesForSearch!).isNotEmpty;
diff --git a/mobile/apps/photos/lib/ui/map/image_marker.dart b/mobile/apps/photos/lib/ui/map/image_marker.dart
index f3a70295be..98105ae414 100644
--- a/mobile/apps/photos/lib/ui/map/image_marker.dart
+++ b/mobile/apps/photos/lib/ui/map/image_marker.dart
@@ -4,10 +4,12 @@ class ImageMarker {
final EnteFile imageFile;
final double latitude;
final double longitude;
+ final int imageCount;
ImageMarker({
required this.imageFile,
required this.latitude,
required this.longitude,
+ this.imageCount = 1,
});
}
diff --git a/mobile/apps/photos/lib/ui/map/map_isolate.dart b/mobile/apps/photos/lib/ui/map/map_isolate.dart
index 0f993799e7..ba6c7edf20 100644
--- a/mobile/apps/photos/lib/ui/map/map_isolate.dart
+++ b/mobile/apps/photos/lib/ui/map/map_isolate.dart
@@ -1,16 +1,127 @@
import "dart:isolate";
+import "dart:math";
import "package:flutter_map/flutter_map.dart";
-import "package:photos/ui/map/image_marker.dart";
+import "package:latlong2/latlong.dart";
-class MapIsolate {
- final LatLngBounds bounds;
- final List<ImageMarker> imageMarkers;
+class MapPoint {
+ final int imageIndex;
+ final double latitude;
+ final double longitude;
+
+ const MapPoint({
+ required this.imageIndex,
+ required this.latitude,
+ required this.longitude,
+ });
+}
+
+class MapMarkerGroup {
+ final int imageIndex;
+ final double latitude;
+ final double longitude;
+ final int imageCount;
+
+ const MapMarkerGroup({
+ required this.imageIndex,
+ required this.latitude,
+ required this.longitude,
+ required this.imageCount,
+ });
+
+ MapMarkerGroup withIncrementedCount() {
+ return MapMarkerGroup(
+ imageIndex: imageIndex,
+ latitude: latitude,
+ longitude: longitude,
+ imageCount: imageCount + 1,
+ );
+ }
+}
+
+class MapWorkerInit {
+ final List<MapPoint> points;
final SendPort sendPort;
- MapIsolate({
+ const MapWorkerInit({required this.points, required this.sendPort});
+}
+
+class MapViewportRequest {
+ final int id;
+ final LatLngBounds bounds;
+ final double zoom;
+
+ const MapViewportRequest({
+ required this.id,
required this.bounds,
- required this.imageMarkers,
- required this.sendPort,
+ required this.zoom,
+ });
+}
+
+class MapViewportResult {
+ final int id;
+ final List<int> visibleImageIndexes;
+ final List<MapMarkerGroup> markerGroups;
+
+ const MapViewportResult({
+ required this.id,
+ required this.visibleImageIndexes,
+ required this.markerGroups,
+ });
+}
+
+const double _markerBucketSizePixels = 64;
+const double _webMercatorTileSize = 256;
+const double _mercatorLatitudeLimit = 85.05112878;
+
+void mapWorker(MapWorkerInit init) {
+ final receivePort = ReceivePort();
+ init.sendPort.send(receivePort.sendPort);
+ receivePort.listen((message) {
+ if (message is! MapViewportRequest) {
+ return;
+ }
+
+ final visibleIndexes = <int>[];
+ final groups = <(int, int), MapMarkerGroup>{};
+ final scale = _webMercatorTileSize * pow(2, message.zoom);
+
+ for (final point in init.points) {
+ final latLng = LatLng(point.latitude, point.longitude);
+ if (!message.bounds.contains(latLng)) {
+ continue;
+ }
+
+ visibleIndexes.add(point.imageIndex);
+ final latitude = point.latitude.clamp(
+ -_mercatorLatitudeLimit,
+ _mercatorLatitudeLimit,
+ );
+ final sinLatitude = sin(latitude * pi / 180);
+ final x = (point.longitude + 180) / 360 * scale;
+ final y =
+ (0.5 - log((1 + sinLatitude) / (1 - sinLatitude)) / (4 * pi)) * scale;
+ final key = (
+ (x / _markerBucketSizePixels).floor(),
+ (y / _markerBucketSizePixels).floor(),
+ );
+ final group = groups[key];
+ groups[key] = group == null
+ ? MapMarkerGroup(
+ imageIndex: point.imageIndex,
+ latitude: point.latitude,
+ longitude: point.longitude,
+ imageCount: 1,
+ )
+ : group.withIncrementedCount();
+ }
+
+ init.sendPort.send(
+ MapViewportResult(
+ id: message.id,
+ visibleImageIndexes: visibleIndexes,
+ markerGroups: groups.values.toList(growable: false),
+ ),
+ );
});
}
diff --git a/mobile/apps/photos/lib/ui/map/map_marker.dart b/mobile/apps/photos/lib/ui/map/map_marker.dart
index 9c9909616f..f30bb2637c 100644
--- a/mobile/apps/photos/lib/ui/map/map_marker.dart
+++ b/mobile/apps/photos/lib/ui/map/map_marker.dart
@@ -2,6 +2,7 @@ import "package:flutter/material.dart";
import "package:flutter_map/flutter_map.dart";
import "package:latlong2/latlong.dart";
import "package:photos/ui/map/image_marker.dart";
+import "package:photos/ui/map/map_gallery_tile_badge.dart";
import "package:photos/ui/map/map_view.dart";
import "package:photos/ui/map/marker_image.dart";
@@ -16,11 +17,17 @@ Marker mapMarker(
width: markerSize.width,
height: markerSize.height,
point: LatLng(imageMarker.latitude, imageMarker.longitude),
- child: MarkerImage(
- file: imageMarker.imageFile,
- seperator:
- (MapView.defaultMarkerSize.height + 10) -
- (MapView.defaultMarkerSize.height - markerSize.height),
+ child: Stack(
+ children: [
+ MarkerImage(
+ file: imageMarker.imageFile,
+ seperator:
+ (MapView.defaultMarkerSize.height + 10) -
+ (MapView.defaultMarkerSize.height - markerSize.height),
+ ),
+ if (imageMarker.imageCount > 1)
+ MapGalleryTileBadge(size: imageMarker.imageCount),
+ ],
),
);
}
diff --git a/mobile/apps/photos/lib/ui/map/map_screen.dart b/mobile/apps/photos/lib/ui/map/map_screen.dart
index 1c7c4d20ab..a12e40c243 100644
--- a/mobile/apps/photos/lib/ui/map/map_screen.dart
+++ b/mobile/apps/photos/lib/ui/map/map_screen.dart
@@ -1,7 +1,6 @@
import "dart:async";
import "dart:isolate";
-import "package:collection/collection.dart";
import "package:computer/computer.dart";
import "package:ente_strings/ente_strings.dart";
import "package:ente_ui/components/loading_widget.dart";
@@ -47,13 +46,15 @@ class _MapScreenState extends State<MapScreen> {
bool hasLocationData = true;
double maxZoom = 18.0;
double minZoom = 2.8;
- int debounceDuration = 500;
late LatLng center;
final Logger _logger = Logger("_MapScreenState");
- StreamSubscription? _mapMoveSubscription;
- Isolate? isolate;
+ ReceivePort? _mapWorkerReceivePort;
+ StreamSubscription? _mapWorkerSubscription;
+ SendPort? _mapWorkerSendPort;
+ Isolate? _mapWorkerIsolate;
static const bottomSheetDraggableAreaHeight = 32.0;
- List<EnteFile>? prevMessage;
+ List<int>? _previousVisibleIndexes;
+ int _viewportRequestID = 0;
@override
void initState() {
@@ -63,16 +64,18 @@ class _MapScreenState extends State<MapScreen> {
@override
void dispose() {
+ unawaited(_mapWorkerSubscription?.cancel());
+ _mapWorkerReceivePort?.close();
+ _mapWorkerIsolate?.kill();
+ unawaited(visibleImages.close());
super.dispose();
- visibleImages.close();
- _mapMoveSubscription?.cancel();
}
Future<void> initialize() async {
try {
center = widget.center ?? const LatLng(46.7286, 4.8614);
allImages = await widget.filesFutureFn();
- unawaited(processFiles(allImages));
+ await processFiles(allImages);
} catch (e, s) {
_logger.severe("Error initializing map screen", e, s);
}
@@ -80,14 +83,14 @@ class _MapScreenState extends State<MapScreen> {
Future<void> processFiles(List<EnteFile> files) async {
final result = await Computer.shared().compute(
- _findRecentFileAndGenerateTempMarkers,
+ _findRecentImageAndMapPoints,
param: {"files": files, "center": widget.center},
);
- final EnteFile? mostRecentFile = result.$1;
- final List<ImageMarker> tempMarkers = result.$2;
+ final int? mostRecentImageIndex = result.$1;
+ final List<MapPoint> mapPoints = result.$2;
- if (tempMarkers.isEmpty) {
+ if (mapPoints.isEmpty) {
if (!mounted) return;
showShortToast(context, context.strings.noImagesWithLocation);
if (!visibleImages.isClosed) {
@@ -98,7 +101,7 @@ class _MapScreenState extends State<MapScreen> {
}
setState(() {
hasLocationData = false;
- imageMarkers = tempMarkers;
+ imageMarkers = [];
isLoading = false;
});
return;
@@ -107,8 +110,8 @@ class _MapScreenState extends State<MapScreen> {
center =
widget.center ??
LatLng(
- mostRecentFile!.location!.latitude!,
- mostRecentFile.location!.longitude!,
+ allImages[mostRecentImageIndex!].location!.latitude!,
+ allImages[mostRecentImageIndex].location!.longitude!,
);
if (kDebugMode) {
@@ -117,62 +120,102 @@ class _MapScreenState extends State<MapScreen> {
);
}
+ await _startMapWorker(mapPoints);
+ if (!mounted) return;
setState(() {
hasLocationData = true;
- imageMarkers = tempMarkers;
});
- mapController.move(center, widget.initialZoom);
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (!mounted) return;
+ mapController.move(center, widget.initialZoom);
+ _requestViewport(
+ mapController.camera.visibleBounds,
+ mapController.camera.zoom,
+ );
+ });
+ }
- Timer(Duration(milliseconds: debounceDuration), () {
- if (!mounted) {
- return;
+ Future<void> _startMapWorker(List<MapPoint> mapPoints) async {
+ _mapWorkerReceivePort = ReceivePort();
+ final sendPortCompleter = Completer<SendPort>();
+ _mapWorkerSubscription = _mapWorkerReceivePort!.listen((message) {
+ if (message is SendPort) {
+ _mapWorkerSendPort = message;
+ if (!sendPortCompleter.isCompleted) {
+ sendPortCompleter.complete(message);
+ }
+ } else if (message is MapViewportResult) {
+ _applyViewportResult(message);
}
- calculateVisibleMarkers(mapController.camera.visibleBounds);
- setState(() {
- isLoading = false;
- });
});
+ _mapWorkerIsolate = await Isolate.spawn(
+ mapWorker,
+ MapWorkerInit(
+ points: mapPoints,
+ sendPort: _mapWorkerReceivePort!.sendPort,
+ ),
+ );
+ await sendPortCompleter.future;
}
- void calculateVisibleMarkers(LatLngBounds bounds) async {
- final ReceivePort receivePort = ReceivePort();
- isolate = await Isolate.spawn<MapIsolate>(
- _calculateMarkersIsolate,
- MapIsolate(
- bounds: bounds,
- imageMarkers: imageMarkers,
- sendPort: receivePort.sendPort,
- ),
+ void _requestViewport(LatLngBounds bounds, double zoom) {
+ final sendPort = _mapWorkerSendPort;
+ if (sendPort == null) return;
+ sendPort.send(
+ MapViewportRequest(id: ++_viewportRequestID, bounds: bounds, zoom: zoom),
);
+ }
- _mapMoveSubscription = receivePort.listen((dynamic message) async {
- if (message is List<EnteFile>) {
- if (!message.equals(prevMessage ?? [])) {
- if (visibleImages.isClosed) {
- return;
- }
- visibleImages.sink.add(message);
- }
+ void _applyViewportResult(MapViewportResult result) {
+ if (!mounted || result.id != _viewportRequestID) return;
- prevMessage = message;
- } else {
- await _mapMoveSubscription?.cancel();
- isolate?.kill();
+ final visibleIndexes = result.visibleImageIndexes;
+ if (!_sameIndexes(visibleIndexes, _previousVisibleIndexes)) {
+ _previousVisibleIndexes = visibleIndexes;
+ if (!visibleImages.isClosed) {
+ visibleImages.add(
+ visibleIndexes
+ .map((index) => allImages[index])
+ .toList(growable: false),
+ );
}
+ }
+
+ setState(() {
+ imageMarkers = result.markerGroups
+ .map(
+ (group) => ImageMarker(
+ imageFile: allImages[group.imageIndex],
+ latitude: group.latitude,
+ longitude: group.longitude,
+ imageCount: group.imageCount,
+ ),
+ )
+ .toList(growable: false);
+ isLoading = false;
});
}
- static (EnteFile?, List<ImageMarker>) _findRecentFileAndGenerateTempMarkers(
+ bool _sameIndexes(List<int> current, List<int>? previous) {
+ if (previous == null || current.length != previous.length) return false;
+ for (var i = 0; i < current.length; i++) {
+ if (current[i] != previous[i]) return false;
+ }
+ return true;
+ }
+
+ static (int?, List<MapPoint>) _findRecentImageAndMapPoints(
Map<String, dynamic> args,
) {
final Logger logger = Logger("_MapScreenState");
final files = args["files"] as List<EnteFile>;
final center = args["center"] as LatLng?;
- final List<ImageMarker> tempMarkers = [];
- EnteFile? mostRecentFile;
+ final List<MapPoint> mapPoints = [];
+ int? mostRecentImageIndex;
- for (var file in files) {
+ for (var index = 0; index < files.length; index++) {
+ final file = files[index];
if (file.hasLocation) {
if (!Location.isValidRange(
latitude: file.location!.latitude!,
@@ -185,45 +228,27 @@ class _MapScreenState extends State<MapScreen> {
}
if (center == null) {
- if (mostRecentFile == null) {
- mostRecentFile = file;
+ if (mostRecentImageIndex == null) {
+ mostRecentImageIndex = index;
} else {
+ final mostRecentFile = files[mostRecentImageIndex];
if ((mostRecentFile.creationTime ?? 0) < (file.creationTime ?? 0)) {
- mostRecentFile = file;
+ mostRecentImageIndex = index;
}
}
}
- tempMarkers.add(
- ImageMarker(
+ mapPoints.add(
+ MapPoint(
+ imageIndex: index,
latitude: file.location!.latitude!,
longitude: file.location!.longitude!,
- imageFile: file,
),
);
}
}
- return (mostRecentFile, tempMarkers);
- }
-
- @pragma('vm:entry-point')
- static void _calculateMarkersIsolate(MapIsolate message) async {
- final bounds = message.bounds;
- final imageMarkers = message.imageMarkers;
- final SendPort sendPort = message.sendPort;
- try {
- final List<EnteFile> visibleFiles = [];
- for (var imageMarker in imageMarkers) {
- final point = LatLng(imageMarker.latitude, imageMarker.longitude);
- if (bounds.contains(point)) {
- visibleFiles.add(imageMarker.imageFile);
- }
- }
- sendPort.send(visibleFiles);
- } catch (e) {
- sendPort.send(e.toString());
- }
+ return (mostRecentImageIndex, mapPoints);
}
@override
@@ -249,12 +274,9 @@ class _MapScreenState extends State<MapScreen> {
bottomSheetDraggableAreaHeight -
bottomUnsafeArea,
child: MapView(
- key: ValueKey(
- 'image-marker-count-${imageMarkers.length}',
- ),
controller: mapController,
imageMarkers: imageMarkers,
- updateVisibleImages: calculateVisibleMarkers,
+ updateVisibleImages: _requestViewport,
center: center,
initialZoom: widget.initialZoom,
minZoom: minZoom,
diff --git a/mobile/apps/photos/lib/ui/map/map_view.dart b/mobile/apps/photos/lib/ui/map/map_view.dart
index eba1db6901..b5dcf8059d 100644
--- a/mobile/apps/photos/lib/ui/map/map_view.dart
+++ b/mobile/apps/photos/lib/ui/map/map_view.dart
@@ -39,7 +39,7 @@ Future<bool> _launchCoordinates(double latitude, double longitude) async {
class MapView extends StatefulWidget {
final List<ImageMarker> imageMarkers;
- final Function updateVisibleImages;
+ final void Function(LatLngBounds bounds, double zoom) updateVisibleImages;
final MapController controller;
final LatLng center;
final double minZoom;
@@ -87,9 +87,17 @@ class _MapViewState extends State<MapView> {
_markers = _buildMakers();
}
- void onChange(LatLngBounds bounds) {
+ @override
+ void didUpdateWidget(MapView oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (!identical(oldWidget.imageMarkers, widget.imageMarkers)) {
+ _markers = _buildMakers();
+ }
+ }
+
+ void onChange(LatLngBounds bounds, double zoom) {
_debouncer.run(() async {
- widget.updateVisibleImages(bounds);
+ widget.updateVisibleImages(bounds, zoom);
});
}
@@ -121,7 +129,7 @@ class _MapViewState extends State<MapView> {
),
),
onPositionChanged: (position, hasGesture) {
- onChange(position.visibleBounds);
+ onChange(position.visibleBounds, position.zoom);
},
),
children: [
@@ -136,13 +144,20 @@ class _MapViewState extends State<MapView> {
padding: const EdgeInsets.all(80),
markers: _markers,
onClusterTap: (_) {
- onChange(widget.controller.camera.visibleBounds);
+ onChange(
+ widget.controller.camera.visibleBounds,
+ widget.controller.camera.zoom,
+ );
},
builder: (context, List<Marker> markers) {
final valueKey = markers.first.key as ValueKey;
final index = valueKey.value as int;
- final clusterKey = 'map-badge-$index-len-${markers.length}';
+ final imageCount = markers.fold<int>(0, (count, marker) {
+ final markerIndex = (marker.key! as ValueKey<int>).value;
+ return count + widget.imageMarkers[markerIndex].imageCount;
+ });
+ final clusterKey = 'map-badge-$index-len-$imageCount';
return Stack(
key: ValueKey(clusterKey),
@@ -151,7 +166,7 @@ class _MapViewState extends State<MapView> {
key: Key(markers.first.key.toString()),
imageMarker: widget.imageMarkers[index],
),
- MapGalleryTileBadge(size: markers.length),
+ MapGalleryTileBadge(size: imageCount),
],
);
},
diff --git a/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart b/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart
index c84d906f84..9db06667c8 100644
--- a/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file_details/location_tags_widget.dart
@@ -208,7 +208,7 @@ class _InfoMapState extends State<InfoMap> {
key: ValueKey(_hasEnabledMap),
children: [
MapView(
- updateVisibleImages: () {},
+ updateVisibleImages: (_, _) {},
imageMarkers: [
ImageMarker(
imageFile: widget.file,
@@ -253,7 +253,7 @@ class _InfoMapState extends State<InfoMap> {
clipBehavior: Clip.none,
children: [
MapView(
- updateVisibleImages: () {},
+ updateVisibleImages: (_, _) {},
imageMarkers: const [],
controller: _mapController,
center: const LatLng(13.041599, 77.594566),
@@ -343,7 +343,8 @@ class _InfoMapState extends State<InfoMap> {
.push(
MaterialPageRoute(
builder: (context) => MapScreen(
- filesFutureFn: SearchService.instance.getAllFilesForSearch,
+ filesFutureFn:
+ SearchService.instance.getAllFilesWithLocationForSearch,
center: LatLng(_fileLat, _fileLng),
initialZoom: 16,
),
diff --git a/mobile/apps/photos/lib/ui/viewer/search/search_map_navigation.dart b/mobile/apps/photos/lib/ui/viewer/search/search_map_navigation.dart
index d12a89aec1..8b9ad2c64f 100644
--- a/mobile/apps/photos/lib/ui/viewer/search/search_map_navigation.dart
+++ b/mobile/apps/photos/lib/ui/viewer/search/search_map_navigation.dart
@@ -27,7 +27,8 @@ Future<void> openSearchMap(BuildContext context) async {
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => MapScreen(
- filesFutureFn: SearchService.instance.getAllFilesForSearch,
+ filesFutureFn:
+ SearchService.instance.getAllFilesWithLocationForSearch,
),
),
),