Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add first-party panorama viewer

Neeraj Gupta114e4a2c7865
diff --git a/mobile/apps/photos/changes/fix-blank-cropped-panoramas.md b/mobile/apps/photos/changes/fix-blank-cropped-panoramas.md
new file mode 100644
index 0000000000..32d4d6ad74
--- /dev/null
+++ b/mobile/apps/photos/changes/fix-blank-cropped-panoramas.md
@@ -0,0 +1 @@
+- Fixed cropped panoramas sometimes opening blank. Thanks @agarwalrahul2702!
diff --git a/mobile/apps/photos/changes/improve-panorama-viewer.md b/mobile/apps/photos/changes/improve-panorama-viewer.md
new file mode 100644
index 0000000000..bb92963bb3
--- /dev/null
+++ b/mobile/apps/photos/changes/improve-panorama-viewer.md
@@ -0,0 +1 @@
+- Made panoramic photos open faster and improved panning, zooming, and motion controls.
diff --git a/mobile/apps/photos/ios/Podfile.lock b/mobile/apps/photos/ios/Podfile.lock
index 0f6ed0b1d0..75c2ed49d5 100644
--- a/mobile/apps/photos/ios/Podfile.lock
+++ b/mobile/apps/photos/ios/Podfile.lock
@@ -18,6 +18,8 @@ PODS:
- Flutter
- ente_cast (0.0.1):
- Flutter
+ - ente_panorama_viewer (0.0.1):
+ - Flutter
- ente_photos_rust (0.0.1):
- Flutter
- ente_qr (0.0.1):
@@ -159,8 +161,6 @@ PODS:
- Flutter
- mobile_ocr (0.0.1):
- Flutter
- - motion_sensors (0.0.1):
- - Flutter
- motionphoto (0.0.1):
- Flutter
- move_to_background (0.0.1):
@@ -262,6 +262,7 @@ DEPENDENCIES:
- cupertino_http (from `.symlinks/plugins/cupertino_http/darwin`)
- device_info_plus (from `.symlinks/plugins/device_info_plus/ios`)
- ente_cast (from `.symlinks/plugins/ente_cast/ios`)
+ - ente_panorama_viewer (from `.symlinks/plugins/ente_panorama_viewer/ios`)
- ente_photos_rust (from `.symlinks/plugins/ente_photos_rust/ios`)
- ente_qr (from `.symlinks/plugins/ente_qr/ios`)
- ente_rust (from `.symlinks/plugins/ente_rust/ios`)
@@ -292,7 +293,6 @@ DEPENDENCIES:
- media_kit_libs_ios_video (from `.symlinks/plugins/media_kit_libs_ios_video/ios`)
- media_kit_video (from `.symlinks/plugins/media_kit_video/ios`)
- mobile_ocr (from `.symlinks/plugins/mobile_ocr/ios`)
- - motion_sensors (from `.symlinks/plugins/motion_sensors/ios`)
- motionphoto (from `.symlinks/plugins/motionphoto/ios`)
- move_to_background (from `.symlinks/plugins/move_to_background/ios`)
- native_video_editor (from `.symlinks/plugins/native_video_editor/ios`)
@@ -357,6 +357,8 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/device_info_plus/ios"
ente_cast:
:path: ".symlinks/plugins/ente_cast/ios"
+ ente_panorama_viewer:
+ :path: ".symlinks/plugins/ente_panorama_viewer/ios"
ente_photos_rust:
:path: ".symlinks/plugins/ente_photos_rust/ios"
ente_qr:
@@ -417,8 +419,6 @@ EXTERNAL SOURCES:
:path: ".symlinks/plugins/media_kit_video/ios"
mobile_ocr:
:path: ".symlinks/plugins/mobile_ocr/ios"
- motion_sensors:
- :path: ".symlinks/plugins/motion_sensors/ios"
motionphoto:
:path: ".symlinks/plugins/motionphoto/ios"
move_to_background:
@@ -476,6 +476,7 @@ SPEC CHECKSUMS:
cupertino_http: 94ac07f5ff090b8effa6c5e2c47871d48ab7c86c
device_info_plus: 21fcca2080fbcd348be798aa36c3e5ed849eefbe
ente_cast: a25feb3127397e5fc6aff03a12120916707757d4
+ ente_panorama_viewer: 87bb22e7868c3005314f80c05ee0787aa07edcd8
ente_photos_rust: 2db1f31cbe3f13ef0f52909a52b1f885b880a6ec
ente_qr: 86beaf5d2644705db9b565b32dd8b82c05fb36af
ente_rust: d0197ebd5460e8f67576579452b073d698404abe
@@ -516,7 +517,6 @@ SPEC CHECKSUMS:
media_kit_libs_ios_video: 5a18affdb97d1f5d466dc79988b13eff6c5e2854
media_kit_video: 1746e198cb697d1ffb734b1d05ec429d1fcd1474
mobile_ocr: bb5125a6810b4eead3c69778e6b7f3c61fb3c24d
- motion_sensors: 741e702c17467b9569a92165dda8d4d88c6167f1
motionphoto: 23e2aeb5c6380112f69468d71f970fa7438e5ed1
move_to_background: 7e3467dd2a1d1013e98c9c1cb93fd53cd7ef9d84
nanopb: fad817b59e0457d11a5dfbde799381cd727c1275
diff --git a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
index 2e969ce9a4..9e46943cf0 100644
--- a/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
+++ b/mobile/apps/photos/ios/Runner.xcodeproj/project.pbxproj
@@ -637,6 +637,7 @@
"${BUILT_PRODUCTS_DIR}/cupertino_http/cupertino_http.framework",
"${BUILT_PRODUCTS_DIR}/device_info_plus/device_info_plus.framework",
"${BUILT_PRODUCTS_DIR}/ente_cast/ente_cast.framework",
+ "${BUILT_PRODUCTS_DIR}/ente_panorama_viewer/ente_panorama_viewer.framework",
"${BUILT_PRODUCTS_DIR}/ente_photos_rust/ente_photos_rust.framework",
"${BUILT_PRODUCTS_DIR}/ente_qr/ente_qr.framework",
"${BUILT_PRODUCTS_DIR}/ente_rust/ente_rust.framework",
@@ -663,7 +664,6 @@
"${BUILT_PRODUCTS_DIR}/media_kit_libs_ios_video/media_kit_libs_ios_video.framework",
"${BUILT_PRODUCTS_DIR}/media_kit_video/media_kit_video.framework",
"${BUILT_PRODUCTS_DIR}/mobile_ocr/mobile_ocr.framework",
- "${BUILT_PRODUCTS_DIR}/motion_sensors/motion_sensors.framework",
"${BUILT_PRODUCTS_DIR}/motionphoto/motionphoto.framework",
"${BUILT_PRODUCTS_DIR}/move_to_background/move_to_background.framework",
"${BUILT_PRODUCTS_DIR}/nanopb/nanopb.framework",
@@ -738,6 +738,7 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/cupertino_http.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/device_info_plus.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_cast.framework",
+ "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_panorama_viewer.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_photos_rust.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_qr.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ente_rust.framework",
@@ -764,7 +765,6 @@
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/media_kit_libs_ios_video.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/media_kit_video.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/mobile_ocr.framework",
- "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/motion_sensors.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/motionphoto.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/move_to_background.framework",
"${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/nanopb.framework",
diff --git a/mobile/apps/photos/ios/Runner/Info.plist b/mobile/apps/photos/ios/Runner/Info.plist
index b1c815b3c1..23f72360e2 100644
--- a/mobile/apps/photos/ios/Runner/Info.plist
+++ b/mobile/apps/photos/ios/Runner/Info.plist
@@ -94,6 +94,8 @@
<string>Please allow access to your camera so that you can take photos within ente</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Please allow access to your photos so that ente can encrypt and back them up.</string>
+ <key>NSMotionUsageDescription</key>
+ <string>Ente uses device motion to let you look around panoramic photos.</string>
<key>PHPhotoLibraryPreventAutomaticLimitedAccessAlert</key>
<true/>
<key>UIBackgroundModes</key>
diff --git a/mobile/apps/photos/lib/ui/viewer/file/panorama_view_data.dart b/mobile/apps/photos/lib/ui/viewer/file/panorama_view_data.dart
index 9a6f59007b..3d8d31ed2a 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/panorama_view_data.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/panorama_view_data.dart
@@ -1,5 +1,3 @@
-import "dart:math" as math;
-
import "package:flutter/material.dart";
/// View parameters for rendering a (possibly partial) panorama on a sphere,
@@ -47,33 +45,6 @@ class PanoramaViewData {
return (0.5 - vCenter) * 180;
}
- /// Smallest supported zoom that keeps the initial viewport within the crop.
- double initialZoom(double viewportAspectRatio) {
- const double halfVerticalFieldOfView = 75 * math.pi / 360;
- const double maxZoom = 5;
- final double projectionScale = math.tan(halfVerticalFieldOfView);
-
- final double halfVerticalCrop =
- croppedArea.height / fullHeight * math.pi / 2;
- final double verticalZoom = halfVerticalCrop >= halfVerticalFieldOfView
- ? 1
- : projectionScale / math.tan(halfVerticalCrop);
-
- final double halfHorizontalCrop = croppedArea.width / fullWidth * math.pi;
- final double halfHorizontalFieldOfView = math.atan(
- projectionScale * viewportAspectRatio,
- );
- final double horizontalZoom =
- halfHorizontalCrop >= halfHorizontalFieldOfView
- ? 1
- : projectionScale * viewportAspectRatio / math.tan(halfHorizontalCrop);
-
- return math.min(
- maxZoom,
- math.max(1, math.max(verticalZoom, horizontalZoom)),
- );
- }
-
/// Parses GPano attributes extracted from XMP. Returns null when the
/// metadata is insufficient to place the image on the panorama sphere.
static PanoramaViewData? fromXmp(Map<String, String> data) {
@@ -153,6 +124,19 @@ class PanoramaViewData {
return null;
}
+ final values = [cLeft, cTop, cWidth, cHeight, fWidth, fHeight];
+ if (values.any((value) => !value.isFinite) ||
+ fWidth <= 0 ||
+ fHeight <= 0 ||
+ cLeft < 0 ||
+ cTop < 0 ||
+ cWidth <= 0 ||
+ cHeight <= 0 ||
+ cLeft + cWidth > fWidth ||
+ cTop + cHeight > fHeight) {
+ return null;
+ }
+
return PanoramaViewData(
fullWidth: fWidth,
fullHeight: fHeight,
diff --git a/mobile/apps/photos/lib/ui/viewer/file/panorama_viewer_screen.dart b/mobile/apps/photos/lib/ui/viewer/file/panorama_viewer_screen.dart
index 35eded05b4..bb6deaf528 100644
--- a/mobile/apps/photos/lib/ui/viewer/file/panorama_viewer_screen.dart
+++ b/mobile/apps/photos/lib/ui/viewer/file/panorama_viewer_screen.dart
@@ -1,10 +1,11 @@
import "dart:async";
import "dart:io";
+import "dart:ui" as ui;
+import "package:ente_panorama_viewer/ente_panorama_viewer.dart";
import "package:flutter/material.dart";
import "package:flutter/services.dart";
import "package:logging/logging.dart";
-import "package:panorama/panorama.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/src/rust/api/motion_photo_api.dart";
import "package:photos/ui/viewer/file/panorama_view_data.dart";
@@ -13,6 +14,7 @@ final _logger = Logger("PanoramaViewerScreen");
/// Extracts XMP attributes from the file at [filePath].
typedef XmpExtractor = Future<Map<String, String>> Function(String filePath);
+typedef MotionAvailabilityChecker = Future<bool> Function();
class PanoramaViewerScreen extends StatefulWidget {
const PanoramaViewerScreen({
@@ -20,6 +22,7 @@ class PanoramaViewerScreen extends StatefulWidget {
required this.file,
required this.thumbnail,
this.xmpExtractor,
+ this.motionAvailabilityChecker,
});
final File file;
@@ -27,6 +30,7 @@ class PanoramaViewerScreen extends StatefulWidget {
/// Overridable for tests. Defaults to the Rust XMP extractor.
final XmpExtractor? xmpExtractor;
+ final MotionAvailabilityChecker? motionAvailabilityChecker;
@override
State<PanoramaViewerScreen> createState() => _PanoramaViewerScreenState();
@@ -35,15 +39,17 @@ class PanoramaViewerScreen extends StatefulWidget {
class _PanoramaViewerScreenState extends State<PanoramaViewerScreen> {
PanoramaViewData? viewData;
bool isReady = false;
- SensorControl control = SensorControl.none;
+ bool motionAvailable = false;
+ bool motionEnabled = false;
Timer? timer;
bool isVisible = true;
@override
void initState() {
+ super.initState();
initTimer();
init();
- super.initState();
+ initMotion();
}
@override
@@ -85,14 +91,50 @@ class _PanoramaViewerScreenState extends State<PanoramaViewerScreen> {
static Future<Map<String, String>> _extractXmp(String filePath) =>
extractXmp(filePath: filePath);
+ Future<void> initMotion() async {
+ bool available;
+ try {
+ available =
+ await (widget.motionAvailabilityChecker ??
+ isPanoramaMotionAvailable)();
+ } catch (_) {
+ available = false;
+ }
+ if (!mounted) return;
+ setState(() {
+ motionAvailable = available;
+ });
+ }
+
@override
Widget build(BuildContext context) {
return Scaffold(
- appBar: isVisible ? AppBar() : null,
- // The Panorama widget must only be created once the view parameters are
- // final: changing its croppedArea afterwards makes it regenerate the
- // sphere mesh, which drops an already-loaded texture and leaves the
- // panorama blank (https://github.com/ente-io/ente/issues/11435).
+ backgroundColor: Colors.black,
+ extendBodyBehindAppBar: true,
+ appBar: isVisible
+ ? AppBar(
+ backgroundColor: Colors.transparent,
+ elevation: 0,
+ foregroundColor: Colors.white,
+ systemOverlayStyle: SystemUiOverlayStyle.light,
+ flexibleSpace: DecoratedBox(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [
+ Colors.black.withValues(alpha: 0.72),
+ Colors.black.withValues(alpha: 0.6),
+ Colors.transparent,
+ ],
+ stops: const [0, 0.2, 1],
+ ),
+ ),
+ ),
+ )
+ : null,
+ // Keep the thumbnail visible until the final crop is known so the first
+ // rendered frame does not jump from a full sphere to a partial panorama.
body: isReady ? _buildPanorama() : _buildPlaceholder(),
);
}
@@ -101,85 +143,111 @@ class _PanoramaViewerScreenState extends State<PanoramaViewerScreen> {
if (widget.thumbnail == null) {
return const SizedBox.shrink();
}
- return Center(child: Image.memory(widget.thumbnail!));
+ return _BlurredThumbnail(widget.thumbnail!);
}
Widget _buildPanorama() {
+ final data = viewData;
+ final geometry = data == null
+ ? const PanoramaGeometry.fullSphere()
+ : PanoramaGeometry(
+ fullSize: Size(data.fullWidth, data.fullHeight),
+ croppedArea: data.croppedArea,
+ );
return Stack(
children: [
- LayoutBuilder(
- builder: (context, constraints) {
- final double initialZoom =
- viewData?.initialZoom(
- constraints.maxWidth / constraints.maxHeight,
- ) ??
- 1.0;
- return Panorama(
- onTap: (_, _, _) {
- setState(() {
- if (isVisible) {
- timer?.cancel();
- SystemChrome.setEnabledSystemUIMode(
- SystemUiMode.immersiveSticky,
- );
- } else {
- initTimer();
- }
- isVisible = !isVisible;
- });
- },
- latitude: viewData?.initialLatitude ?? 0.0,
- longitude: viewData?.initialLongitude ?? 0.0,
- zoom: initialZoom,
- minZoom: initialZoom,
- croppedArea:
- viewData?.croppedArea ??
- const Rect.fromLTWH(0.0, 0.0, 1.0, 1.0),
- croppedFullWidth: viewData?.fullWidth ?? 1.0,
- croppedFullHeight: viewData?.fullHeight ?? 1.0,
- sensorControl: control,
- background: widget.thumbnail != null
- ? Image.memory(widget.thumbnail!)
- : null,
- child: Image.file(widget.file),
- );
+ EntePanoramaViewer(
+ image: FileImage(widget.file),
+ geometry: geometry,
+ initialView: PanoramaView(
+ longitude: data?.initialLongitude ?? 0,
+ latitude: data?.initialLatitude ?? 0,
+ ),
+ motionEnabled: motionEnabled,
+ placeholder: widget.thumbnail == null
+ ? null
+ : _BlurredThumbnail(widget.thumbnail!),
+ onError: (error, stackTrace) {
+ _logger.warning("Failed to render panorama", error, stackTrace);
+ },
+ onTap: () {
+ setState(() {
+ if (isVisible) {
+ timer?.cancel();
+ SystemChrome.setEnabledSystemUIMode(
+ SystemUiMode.immersiveSticky,
+ );
+ } else {
+ initTimer();
+ }
+ isVisible = !isVisible;
+ });
},
),
- Visibility(
- visible: isVisible,
- child: Align(
- alignment: Alignment.bottomRight,
- child: Tooltip(
- message: AppLocalizations.of(context).panorama,
- child: Padding(
- padding: const EdgeInsets.only(top: 12, bottom: 32, right: 20),
- child: IconButton(
- style: IconButton.styleFrom(
- backgroundColor: const Color(0xFF252525),
- fixedSize: const Size(44, 44),
+ if (motionAvailable)
+ Visibility(
+ visible: isVisible,
+ child: Align(
+ alignment: Alignment.bottomRight,
+ child: Tooltip(
+ message: AppLocalizations.of(context).panorama,
+ child: Padding(
+ padding: const EdgeInsets.only(
+ top: 12,
+ bottom: 32,
+ right: 20,
),
- icon: Icon(
- control == SensorControl.none
- ? Icons.explore_outlined
- : Icons.explore_off_outlined,
- color: Colors.white,
- size: 26,
+ child: IconButton(
+ style: IconButton.styleFrom(
+ backgroundColor: const Color(0xFF252525),
+ fixedSize: const Size(44, 44),
+ ),
+ icon: Icon(
+ !motionEnabled
+ ? Icons.explore_outlined
+ : Icons.explore_off_outlined,
+ color: Colors.white,
+ size: 26,
+ ),
+ onPressed: () {
+ setState(() {
+ motionEnabled = !motionEnabled;
+ });
+ },
),
- onPressed: () {
- if (control != SensorControl.none) {
- control = SensorControl.none;
- } else {
- control = SensorControl.orientation;
- }
-
- setState(() {});
- },
),
),
),
),
- ),
],
);
}
}
+
+class _BlurredThumbnail extends StatelessWidget {
+ const _BlurredThumbnail(this.bytes);
+
+ final Uint8List bytes;
+
+ @override
+ Widget build(BuildContext context) {
+ return ClipRect(
+ child: ImageFiltered(
+ imageFilter: ui.ImageFilter.blur(
+ sigmaX: 32,
+ sigmaY: 32,
+ tileMode: TileMode.mirror,
+ ),
+ child: Transform.scale(
+ scale: 1.1,
+ child: Image.memory(
+ bytes,
+ width: double.infinity,
+ height: double.infinity,
+ fit: BoxFit.cover,
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/android/build.gradle b/mobile/apps/photos/plugins/ente_panorama_viewer/android/build.gradle
new file mode 100644
index 0000000000..6aed2d97ab
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/android/build.gradle
@@ -0,0 +1,47 @@
+group 'io.ente.panorama_viewer'
+version '1.0'
+
+buildscript {
+ ext.kotlin_version = '2.1.10'
+ repositories {
+ google()
+ mavenCentral()
+ }
+
+ dependencies {
+ classpath 'com.android.tools.build:gradle:8.10.1'
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
+ }
+}
+
+rootProject.allprojects {
+ repositories {
+ google()
+ mavenCentral()
+ }
+}
+
+apply plugin: 'com.android.library'
+apply plugin: 'kotlin-android'
+
+android {
+ namespace 'io.ente.panorama_viewer'
+ compileSdk 36
+
+ compileOptions {
+ sourceCompatibility JavaVersion.VERSION_1_8
+ targetCompatibility JavaVersion.VERSION_1_8
+ }
+
+ kotlinOptions {
+ jvmTarget = '1.8'
+ }
+
+ sourceSets {
+ main.java.srcDirs += 'src/main/kotlin'
+ }
+
+ defaultConfig {
+ minSdkVersion 26
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/android/src/main/AndroidManifest.xml b/mobile/apps/photos/plugins/ente_panorama_viewer/android/src/main/AndroidManifest.xml
new file mode 100644
index 0000000000..94cbbcfc39
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/android/src/main/AndroidManifest.xml
@@ -0,0 +1 @@
+<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/android/src/main/kotlin/io/ente/panorama_viewer/EntePanoramaViewerPlugin.kt b/mobile/apps/photos/plugins/ente_panorama_viewer/android/src/main/kotlin/io/ente/panorama_viewer/EntePanoramaViewerPlugin.kt
new file mode 100644
index 0000000000..a23b2a0c61
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/android/src/main/kotlin/io/ente/panorama_viewer/EntePanoramaViewerPlugin.kt
@@ -0,0 +1,104 @@
+package io.ente.panorama_viewer
+
+import android.content.Context
+import android.hardware.Sensor
+import android.hardware.SensorEvent
+import android.hardware.SensorEventListener
+import android.hardware.SensorManager
+import android.view.WindowManager
+import io.flutter.embedding.engine.plugins.FlutterPlugin
+import io.flutter.plugin.common.EventChannel
+import io.flutter.plugin.common.MethodCall
+import io.flutter.plugin.common.MethodChannel
+
+class EntePanoramaViewerPlugin :
+ FlutterPlugin,
+ MethodChannel.MethodCallHandler,
+ EventChannel.StreamHandler,
+ SensorEventListener {
+ private lateinit var windowManager: WindowManager
+ private lateinit var methodChannel: MethodChannel
+ private lateinit var eventChannel: EventChannel
+ private var sensorManager: SensorManager? = null
+ private var eventSink: EventChannel.EventSink? = null
+
+ override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
+ val context = binding.applicationContext
+ sensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
+ windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+ methodChannel = MethodChannel(binding.binaryMessenger, METHOD_CHANNEL)
+ methodChannel.setMethodCallHandler(this)
+ eventChannel = EventChannel(binding.binaryMessenger, EVENT_CHANNEL)
+ eventChannel.setStreamHandler(this)
+ }
+
+ override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
+ when (call.method) {
+ "isAvailable" -> result.success(resolveSensor() != null)
+ else -> result.notImplemented()
+ }
+ }
+
+ override fun onListen(arguments: Any?, events: EventChannel.EventSink) {
+ stop()
+ val selectedSensor = resolveSensor()
+ if (selectedSensor == null) {
+ events.error("motion_unavailable", "Device orientation is unavailable", null)
+ return
+ }
+ eventSink = events
+ val registered =
+ sensorManager?.registerListener(
+ this,
+ selectedSensor,
+ SensorManager.SENSOR_DELAY_GAME,
+ ) == true
+ if (!registered) {
+ eventSink = null
+ events.error("motion_unavailable", "Failed to start device orientation", null)
+ }
+ }
+
+ override fun onCancel(arguments: Any?) {
+ stop()
+ }
+
+ override fun onSensorChanged(event: SensorEvent) {
+ val quaternion = FloatArray(4)
+ SensorManager.getQuaternionFromVector(quaternion, event.values)
+ val rotation = windowManager.defaultDisplay.rotation
+ eventSink?.success(
+ listOf(
+ quaternion[0].toDouble(),
+ quaternion[1].toDouble(),
+ quaternion[2].toDouble(),
+ quaternion[3].toDouble(),
+ rotation,
+ ),
+ )
+ }
+
+ override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
+
+ override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
+ stop()
+ methodChannel.setMethodCallHandler(null)
+ eventChannel.setStreamHandler(null)
+ sensorManager = null
+ }
+
+ private fun resolveSensor(): Sensor? {
+ return sensorManager?.getDefaultSensor(Sensor.TYPE_GAME_ROTATION_VECTOR)
+ ?: sensorManager?.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR)
+ }
+
+ private fun stop() {
+ sensorManager?.unregisterListener(this)
+ eventSink = null
+ }
+
+ companion object {
+ private const val METHOD_CHANNEL = "io.ente.panorama_viewer/motion"
+ private const val EVENT_CHANNEL = "io.ente.panorama_viewer/motion_events"
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/ios/Classes/EntePanoramaViewerPlugin.swift b/mobile/apps/photos/plugins/ente_panorama_viewer/ios/Classes/EntePanoramaViewerPlugin.swift
new file mode 100644
index 0000000000..783f57dfa3
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/ios/Classes/EntePanoramaViewerPlugin.swift
@@ -0,0 +1,99 @@
+import CoreMotion
+import Flutter
+import UIKit
+
+public final class EntePanoramaViewerPlugin: NSObject, FlutterPlugin, FlutterStreamHandler {
+ private let motionManager = CMMotionManager()
+ private var eventSink: FlutterEventSink?
+
+ public static func register(with registrar: FlutterPluginRegistrar) {
+ let instance = EntePanoramaViewerPlugin()
+ let methodChannel = FlutterMethodChannel(
+ name: "io.ente.panorama_viewer/motion",
+ binaryMessenger: registrar.messenger()
+ )
+ registrar.addMethodCallDelegate(instance, channel: methodChannel)
+ let eventChannel = FlutterEventChannel(
+ name: "io.ente.panorama_viewer/motion_events",
+ binaryMessenger: registrar.messenger()
+ )
+ eventChannel.setStreamHandler(instance)
+ }
+
+ public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
+ switch call.method {
+ case "isAvailable":
+ result(motionManager.isDeviceMotionAvailable)
+ default:
+ result(FlutterMethodNotImplemented)
+ }
+ }
+
+ public func onListen(
+ withArguments arguments: Any?,
+ eventSink events: @escaping FlutterEventSink
+ ) -> FlutterError? {
+ guard motionManager.isDeviceMotionAvailable else {
+ return FlutterError(
+ code: "motion_unavailable",
+ message: "Device orientation is unavailable",
+ details: nil
+ )
+ }
+ motionManager.stopDeviceMotionUpdates()
+ eventSink = events
+ motionManager.deviceMotionUpdateInterval = 1.0 / 60.0
+ motionManager.startDeviceMotionUpdates(
+ using: .xArbitraryZVertical,
+ to: .main
+ ) { [weak self] motion, error in
+ guard let self else { return }
+ if let error {
+ self.motionManager.stopDeviceMotionUpdates()
+ let sink = self.eventSink
+ self.eventSink = nil
+ sink?(
+ FlutterError(
+ code: "motion_error",
+ message: error.localizedDescription,
+ details: nil
+ )
+ )
+ return
+ }
+ guard let motion else { return }
+ let quaternion = motion.attitude.quaternion
+ self.eventSink?([
+ quaternion.w,
+ quaternion.x,
+ quaternion.y,
+ quaternion.z,
+ self.interfaceQuarterTurns(),
+ ])
+ }
+ return nil
+ }
+
+ public func onCancel(withArguments arguments: Any?) -> FlutterError? {
+ motionManager.stopDeviceMotionUpdates()
+ eventSink = nil
+ return nil
+ }
+
+ private func interfaceQuarterTurns() -> Int {
+ let orientation = UIApplication.shared.connectedScenes
+ .compactMap { $0 as? UIWindowScene }
+ .first { $0.activationState == .foregroundActive }?
+ .interfaceOrientation
+ switch orientation {
+ case .landscapeLeft:
+ return 1
+ case .portraitUpsideDown:
+ return 2
+ case .landscapeRight:
+ return 3
+ default:
+ return 0
+ }
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/ios/ente_panorama_viewer.podspec b/mobile/apps/photos/plugins/ente_panorama_viewer/ios/ente_panorama_viewer.podspec
new file mode 100644
index 0000000000..195226a334
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/ios/ente_panorama_viewer.podspec
@@ -0,0 +1,15 @@
+Pod::Spec.new do |s|
+ s.name = 'ente_panorama_viewer'
+ s.version = '0.0.1'
+ s.summary = 'First-party panorama rendering and motion support for Ente Photos.'
+ s.homepage = 'https://ente.com'
+ s.license = { :type => 'AGPL-3.0-only' }
+ s.author = { 'Ente' => '[email protected]' }
+ s.source = { :path => '.' }
+ s.source_files = 'Classes/**/*'
+ s.dependency 'Flutter'
+ s.frameworks = 'CoreMotion'
+ s.platform = :ios, '15.1'
+ s.swift_version = '5.0'
+ s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
+end
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/lib/ente_panorama_viewer.dart b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/ente_panorama_viewer.dart
new file mode 100644
index 0000000000..4aa3e45d60
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/ente_panorama_viewer.dart
@@ -0,0 +1,3 @@
+export "src/models.dart";
+export "src/motion.dart" show isPanoramaMotionAvailable;
+export "src/viewer.dart";
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/camera.dart b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/camera.dart
new file mode 100644
index 0000000000..48374ab848
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/camera.dart
@@ -0,0 +1,333 @@
+import "dart:math" as math;
+import "dart:ui";
+
+import "package:ente_panorama_viewer/src/models.dart";
+import "package:flutter/foundation.dart";
+
+const double _degreesToRadians = math.pi / 180;
+const double _radiansToDegrees = 180 / math.pi;
+const double _baseHalfFieldOfView = 37.5 * _degreesToRadians;
+const double _defaultMaximumZoom = 5;
+
+class PanoramaCamera extends ChangeNotifier {
+ PanoramaCamera({
+ required PanoramaGeometry geometry,
+ PanoramaView? initialView,
+ }) : _geometry = geometry,
+ _view = initialView ?? geometry.centeredView;
+
+ PanoramaGeometry _geometry;
+ PanoramaView _view;
+ Size _viewport = Size.zero;
+ double _minimumZoom = 1;
+ double _cropFitZoom = 1;
+ double _maximumZoom = _defaultMaximumZoom;
+
+ PanoramaView get view => _view;
+ PanoramaGeometry get geometry => _geometry;
+ Size get viewport => _viewport;
+ double get minimumZoom => _minimumZoom;
+ double get cropFitZoom => _cropFitZoom;
+ double get maximumZoom => _maximumZoom;
+
+ double get verticalFieldOfView {
+ return 2 *
+ math.atan(math.tan(_baseHalfFieldOfView) / _view.zoom) *
+ _radiansToDegrees;
+ }
+
+ double get horizontalFieldOfView {
+ if (_viewport.isEmpty) return verticalFieldOfView;
+ final aspect = _viewport.width / _viewport.height;
+ return 2 *
+ math.atan(math.tan(_baseHalfFieldOfView) / _view.zoom * aspect) *
+ _radiansToDegrees;
+ }
+
+ bool updateViewport(Size viewport, {bool notify = true}) {
+ if (viewport.isEmpty || viewport == _viewport) return false;
+ final firstViewport = _viewport.isEmpty;
+ final previousCropFitZoom = _cropFitZoom;
+ _viewport = viewport;
+ _recomputeZoomLimits();
+ final shouldFitCrop =
+ firstViewport ||
+ ((_view.zoom - previousCropFitZoom).abs() < 1e-6 &&
+ _cropFitZoom > _view.zoom);
+ final candidate = shouldFitCrop
+ ? _view.copyWith(zoom: math.max(_view.zoom, _cropFitZoom))
+ : _view;
+ return _setView(candidate, notify: notify);
+ }
+
+ void updateGeometry(PanoramaGeometry geometry, {bool notify = true}) {
+ if (geometry == _geometry) return;
+ _geometry = geometry;
+ _recomputeZoomLimits();
+ _setView(_view, notify: notify);
+ }
+
+ void reset(PanoramaView? initialView, {bool notify = true}) {
+ _recomputeZoomLimits();
+ final candidate = initialView ?? _geometry.centeredView;
+ _setView(
+ candidate.copyWith(zoom: math.max(candidate.zoom, _cropFitZoom)),
+ notify: notify,
+ );
+ }
+
+ bool setView(PanoramaView view) => _setView(view, notify: true);
+
+ bool wouldConstrain(PanoramaView candidate) {
+ if (!candidate.longitude.isFinite ||
+ !candidate.latitude.isFinite ||
+ !candidate.zoom.isFinite) {
+ return true;
+ }
+ final constrained = _clamp(candidate);
+ return shortestLongitudeDelta(
+ candidate.longitude,
+ constrained.longitude,
+ ).abs() >
+ 1e-9 ||
+ (candidate.latitude - constrained.latitude).abs() > 1e-9 ||
+ (candidate.zoom - constrained.zoom).abs() > 1e-9;
+ }
+
+ bool _setView(PanoramaView candidate, {required bool notify}) {
+ final clamped = _clamp(candidate);
+ if (clamped == _view) return false;
+ _view = clamped;
+ if (notify) notifyListeners();
+ return true;
+ }
+
+ PanoramaView _clamp(PanoramaView candidate) {
+ final centered = _geometry.centeredView;
+ final candidateZoom = candidate.zoom.isFinite
+ ? candidate.zoom
+ : (_view.zoom.isFinite ? _view.zoom : centered.zoom);
+ final candidateLatitude = candidate.latitude.isFinite
+ ? candidate.latitude
+ : (_view.latitude.isFinite ? _view.latitude : centered.latitude);
+ final candidateLongitude = candidate.longitude.isFinite
+ ? candidate.longitude
+ : (_view.longitude.isFinite ? _view.longitude : centered.longitude);
+ final zoom = candidateZoom.clamp(_minimumZoom, _maximumZoom).toDouble();
+ final verticalHalf = _verticalHalfFieldOfView(zoom);
+ final crop = _geometry.normalizedCrop;
+ final cropTop = (0.5 - crop.top) * math.pi;
+ final cropBottom = (0.5 - crop.bottom) * math.pi;
+ final poleLimit = math.pi / 2 - verticalHalf;
+ var minimumLatitude = math.max(cropBottom, -poleLimit);
+ var maximumLatitude = math.min(cropTop, poleLimit);
+ if (minimumLatitude > maximumLatitude) {
+ final center = ((cropTop + cropBottom) / 2)
+ .clamp(-poleLimit, poleLimit)
+ .toDouble();
+ minimumLatitude = center;
+ maximumLatitude = center;
+ }
+ final latitude = (candidateLatitude * _degreesToRadians)
+ .clamp(minimumLatitude, maximumLatitude)
+ .toDouble();
+
+ double longitude;
+ if (_geometry.coversFullWidth || _viewport.isEmpty) {
+ longitude = normalizeLongitude(candidateLongitude);
+ } else {
+ final cropLeft = (crop.left - 0.5) * 2 * math.pi;
+ final cropRight = (crop.right - 0.5) * 2 * math.pi;
+ longitude = (candidateLongitude * _degreesToRadians)
+ .clamp(cropLeft, cropRight)
+ .toDouble();
+ longitude *= _radiansToDegrees;
+ }
+
+ return PanoramaView(
+ longitude: longitude,
+ latitude: latitude * _radiansToDegrees,
+ zoom: zoom,
+ );
+ }
+
+ void _recomputeZoomLimits() {
+ if (_viewport.isEmpty) {
+ _minimumZoom = 1;
+ _cropFitZoom = 1;
+ _maximumZoom = _defaultMaximumZoom;
+ return;
+ }
+
+ final crop = _geometry.normalizedCrop;
+ final halfVerticalCrop = crop.height * math.pi / 2;
+ final verticalZoom = halfVerticalCrop >= _baseHalfFieldOfView
+ ? 1.0
+ : math.tan(_baseHalfFieldOfView) / math.tan(halfVerticalCrop);
+
+ var horizontalZoom = 1.0;
+ if (!_geometry.coversFullWidth) {
+ final targetWidth = crop.width * 2 * math.pi;
+ final centerLatitude = (0.5 - crop.center.dy) * math.pi;
+ bool fits(double zoom) {
+ final extent = _relativeLongitudeExtent(
+ latitude: centerLatitude,
+ zoom: zoom,
+ );
+ return extent.maximum - extent.minimum <= targetWidth;
+ }
+
+ var upper = 1.0;
+ while (!fits(upper)) {
+ upper *= 2;
+ }
+ var lower = 1.0;
+ for (var index = 0; index < 40; index++) {
+ final middle = (lower + upper) / 2;
+ if (fits(middle)) {
+ upper = middle;
+ } else {
+ lower = middle;
+ }
+ }
+ horizontalZoom = upper;
+ }
+
+ _minimumZoom = 1;
+ _cropFitZoom = math.max(1, math.max(verticalZoom, horizontalZoom));
+ _maximumZoom = math.max(_defaultMaximumZoom, _cropFitZoom);
+ }
+
+ _AngularExtent _relativeLongitudeExtent({
+ required double latitude,
+ required double zoom,
+ }) {
+ if (_viewport.isEmpty) return const _AngularExtent(0, 0);
+ var minimum = double.infinity;
+ var maximum = double.negativeInfinity;
+ for (final y in const [-1.0, 1.0]) {
+ for (final x in const [-1.0, 1.0]) {
+ final angles = _rayAngles(
+ normalizedX: x,
+ normalizedY: y,
+ longitude: 0,
+ latitude: latitude,
+ zoom: zoom,
+ );
+ minimum = math.min(minimum, angles.longitude);
+ maximum = math.max(maximum, angles.longitude);
+ }
+ }
+ return _AngularExtent(minimum, maximum);
+ }
+
+ Offset sourcePointAt(Offset localPosition) {
+ return _sourcePointAt(_view, localPosition);
+ }
+
+ Offset _sourcePointAt(PanoramaView view, Offset localPosition) {
+ if (_viewport.isEmpty) return Offset.zero;
+ final x = localPosition.dx / _viewport.width * 2 - 1;
+ final y = 1 - localPosition.dy / _viewport.height * 2;
+ final angles = _rayAngles(
+ normalizedX: x,
+ normalizedY: y,
+ longitude: view.longitude * _degreesToRadians,
+ latitude: view.latitude * _degreesToRadians,
+ zoom: view.zoom,
+ );
+ var u = 0.5 + angles.longitude / (2 * math.pi);
+ if (_geometry.coversFullWidth) {
+ u %= 1;
+ if (u < 0) u += 1;
+ } else {
+ final crop = _geometry.normalizedCrop;
+ if (crop.right > 0.99999 && u < crop.left) {
+ u += 1;
+ } else if (crop.left < 0.00001 && u > crop.right) {
+ u -= 1;
+ }
+ }
+ final v = 0.5 - angles.latitude / math.pi;
+ return Offset(u, v);
+ }
+
+ bool anchorSourcePoint(Offset localPosition, Offset sourcePoint) {
+ var candidate = _view;
+ for (var iteration = 0; iteration < 3; iteration++) {
+ final current = _sourcePointAt(candidate, localPosition);
+ final longitudeDelta = shortestLongitudeDelta(
+ current.dx * 360,
+ sourcePoint.dx * 360,
+ );
+ final latitudeDelta = (current.dy - sourcePoint.dy) * 180;
+ candidate = candidate.copyWith(
+ longitude: candidate.longitude + longitudeDelta,
+ latitude: candidate.latitude + latitudeDelta,
+ );
+ candidate = _clamp(candidate);
+ }
+ return _setView(candidate, notify: true);
+ }
+
+ _RayAngles _rayAngles({
+ required double normalizedX,
+ required double normalizedY,
+ required double longitude,
+ required double latitude,
+ required double zoom,
+ }) {
+ final aspect = _viewport.width / _viewport.height;
+ final projection = math.tan(_baseHalfFieldOfView) / zoom;
+ var x = normalizedX * aspect * projection;
+ var y = normalizedY * projection;
+ var z = 1.0;
+ final inverseLength = 1 / math.sqrt(x * x + y * y + z * z);
+ x *= inverseLength;
+ y *= inverseLength;
+ z *= inverseLength;
+
+ final sinLatitude = math.sin(latitude);
+ final cosLatitude = math.cos(latitude);
+ final pitchedY = cosLatitude * y + sinLatitude * z;
+ final pitchedZ = -sinLatitude * y + cosLatitude * z;
+
+ final sinLongitude = math.sin(longitude);
+ final cosLongitude = math.cos(longitude);
+ final rotatedX = cosLongitude * x + sinLongitude * pitchedZ;
+ final rotatedZ = -sinLongitude * x + cosLongitude * pitchedZ;
+
+ return _RayAngles(
+ math.atan2(rotatedX, rotatedZ),
+ math.asin(pitchedY.clamp(-1, 1)),
+ );
+ }
+
+ double _verticalHalfFieldOfView(double zoom) {
+ return math.atan(math.tan(_baseHalfFieldOfView) / zoom);
+ }
+
+ static double normalizeLongitude(double value) {
+ var result = (value + 180) % 360;
+ if (result < 0) result += 360;
+ return result - 180;
+ }
+
+ static double shortestLongitudeDelta(double from, double to) {
+ return normalizeLongitude(to - from);
+ }
+}
+
+class _AngularExtent {
+ const _AngularExtent(this.minimum, this.maximum);
+
+ final double minimum;
+ final double maximum;
+}
+
+class _RayAngles {
+ const _RayAngles(this.longitude, this.latitude);
+
+ final double longitude;
+ final double latitude;
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/models.dart b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/models.dart
new file mode 100644
index 0000000000..e5eb5018cf
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/models.dart
@@ -0,0 +1,109 @@
+import "dart:ui";
+
+/// Position and zoom of the panorama camera.
+class PanoramaView {
+ const PanoramaView({this.longitude = 0, this.latitude = 0, this.zoom = 1});
+
+ /// Horizontal camera angle in degrees.
+ final double longitude;
+
+ /// Vertical camera angle in degrees.
+ final double latitude;
+
+ /// Magnification relative to the viewer's base field of view.
+ final double zoom;
+
+ PanoramaView copyWith({double? longitude, double? latitude, double? zoom}) {
+ return PanoramaView(
+ longitude: longitude ?? this.longitude,
+ latitude: latitude ?? this.latitude,
+ zoom: zoom ?? this.zoom,
+ );
+ }
+
+ @override
+ bool operator ==(Object other) {
+ return other is PanoramaView &&
+ longitude == other.longitude &&
+ latitude == other.latitude &&
+ zoom == other.zoom;
+ }
+
+ @override
+ int get hashCode => Object.hash(longitude, latitude, zoom);
+}
+
+/// Placement of the source image on its full equirectangular canvas.
+class PanoramaGeometry {
+ PanoramaGeometry({required this.fullSize, required this.croppedArea}) {
+ final values = [
+ fullSize.width,
+ fullSize.height,
+ croppedArea.left,
+ croppedArea.top,
+ croppedArea.width,
+ croppedArea.height,
+ ];
+ if (values.any((value) => !value.isFinite) ||
+ fullSize.width <= 0 ||
+ fullSize.height <= 0 ||
+ croppedArea.left < 0 ||
+ croppedArea.top < 0 ||
+ croppedArea.width <= 0 ||
+ croppedArea.height <= 0 ||
+ croppedArea.right > fullSize.width ||
+ croppedArea.bottom > fullSize.height) {
+ throw ArgumentError("Crop must be inside a finite, positive full size");
+ }
+ }
+
+ const PanoramaGeometry.fullSphere()
+ : fullSize = const Size(1, 1),
+ croppedArea = const Rect.fromLTWH(0, 0, 1, 1);
+
+ /// Pixel dimensions of the complete equirectangular canvas.
+ final Size fullSize;
+
+ /// Pixel rectangle occupied by the source image on [fullSize].
+ final Rect croppedArea;
+ Rect get normalizedCrop => Rect.fromLTRB(
+ croppedArea.left / fullSize.width,
+ croppedArea.top / fullSize.height,
+ croppedArea.right / fullSize.width,
+ croppedArea.bottom / fullSize.height,
+ );
+
+ PanoramaView get centeredView {
+ final crop = normalizedCrop;
+ return PanoramaView(
+ longitude: _normalizeLongitude((crop.center.dx - 0.5) * 360),
+ latitude: (0.5 - crop.center.dy) * 180,
+ );
+ }
+
+ bool get coversFullWidth {
+ return croppedArea.left == 0 && croppedArea.right == fullSize.width;
+ }
+
+ bool get coversFullSphere {
+ return coversFullWidth &&
+ croppedArea.top == 0 &&
+ croppedArea.bottom == fullSize.height;
+ }
+
+ @override
+ bool operator ==(Object other) {
+ return other is PanoramaGeometry &&
+ fullSize == other.fullSize &&
+ croppedArea == other.croppedArea;
+ }
+
+ @override
+ int get hashCode => Object.hash(fullSize, croppedArea);
+}
+
+double _normalizeLongitude(double value) {
+ var result = (value + 180) % 360;
+ if (result < 0) result += 360;
+ return result - 180;
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/motion.dart b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/motion.dart
new file mode 100644
index 0000000000..83e3464fc6
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/motion.dart
@@ -0,0 +1,235 @@
+import "dart:async";
+import "dart:math" as math;
+
+import "package:ente_panorama_viewer/src/models.dart";
+import "package:flutter/services.dart";
+import "package:flutter/widgets.dart";
+
+const _methodChannel = MethodChannel("io.ente.panorama_viewer/motion");
+const _eventChannel = EventChannel("io.ente.panorama_viewer/motion_events");
+
+Future<bool> isPanoramaMotionAvailable() async {
+ return await _methodChannel.invokeMethod<bool>("isAvailable") ?? false;
+}
+
+class MotionController {
+ MotionController(
+ this.onViewDelta, {
+ required this.onReferenceChanged,
+ required this.onError,
+ Stream<Object?> Function()? eventStream,
+ }) : _eventStream =
+ eventStream ?? (() => _eventChannel.receiveBroadcastStream());
+
+ final ValueChanged<PanoramaView> onViewDelta;
+ final VoidCallback onReferenceChanged;
+ final void Function(Object error, StackTrace stackTrace) onError;
+ final Stream<Object?> Function() _eventStream;
+
+ // Cancelled by stop(), which is called on disable, pause, and disposal.
+ // ignore: cancel_subscriptions
+ StreamSubscription<Object?>? _subscription;
+ final MotionViewTracker _tracker = MotionViewTracker();
+ Future<void> _transition = Future.value();
+ bool _shouldRun = false;
+ bool _acceptEvents = false;
+ bool _frameScheduled = false;
+ int? _quarterTurns;
+ _Quaternion? _pending;
+
+ void start() {
+ _shouldRun = true;
+ unawaited(_queueTransition());
+ }
+
+ Future<void> stop() {
+ _shouldRun = false;
+ _deactivate();
+ return _queueTransition();
+ }
+
+ Future<void> _queueTransition() {
+ _transition = _transition.then((_) => _applyDesiredState()).catchError((
+ Object error,
+ StackTrace stackTrace,
+ ) {
+ onError(error, stackTrace);
+ });
+ return _transition;
+ }
+
+ Future<void> _applyDesiredState() async {
+ if (_shouldRun) {
+ if (_subscription != null) {
+ _acceptEvents = true;
+ return;
+ }
+ resetReference();
+ _acceptEvents = true;
+ try {
+ _subscription = _eventStream().listen(
+ _onEvent,
+ onError: _onStreamError,
+ );
+ } catch (_) {
+ _deactivate();
+ rethrow;
+ }
+ return;
+ }
+ final subscription = _subscription;
+ _subscription = null;
+ await subscription?.cancel();
+ }
+
+ void _deactivate() {
+ _acceptEvents = false;
+ _pending = null;
+ _frameScheduled = false;
+ resetReference();
+ }
+
+ void _onStreamError(Object error, StackTrace stackTrace) {
+ _shouldRun = false;
+ _deactivate();
+ onError(error, stackTrace);
+ unawaited(_queueTransition());
+ }
+
+ void resetReference() {
+ _tracker.reset();
+ _quarterTurns = null;
+ }
+
+ void _onEvent(Object? event) {
+ if (!_acceptEvents) return;
+ if (event is! List<Object?> || event.length < 5) return;
+ final values = event.take(5).map((value) => (value as num).toDouble());
+ final iterator = values.iterator;
+ iterator.moveNext();
+ final w = iterator.current;
+ iterator.moveNext();
+ final x = iterator.current;
+ iterator.moveNext();
+ final y = iterator.current;
+ iterator.moveNext();
+ final z = iterator.current;
+ iterator.moveNext();
+ final quarterTurns = iterator.current.round();
+ if (_quarterTurns != null && _quarterTurns != quarterTurns) {
+ onReferenceChanged();
+ _tracker.reset();
+ }
+ _quarterTurns = quarterTurns;
+ _pending = _screenAdjustedQuaternion(
+ _Quaternion(w, x, y, z).normalized,
+ quarterTurns,
+ );
+ if (_frameScheduled) return;
+ _frameScheduled = true;
+ WidgetsBinding.instance.scheduleFrameCallback((_) {
+ _frameScheduled = false;
+ final current = _pending;
+ _pending = null;
+ if (current == null || !_acceptEvents || _subscription == null) return;
+ onViewDelta(_tracker._update(current));
+ });
+ }
+}
+
+class MotionViewTracker {
+ _Quaternion? _reference;
+
+ void reset() {
+ _reference = null;
+ }
+
+ PanoramaView _update(_Quaternion current) {
+ final reference = _reference;
+ if (reference == null) {
+ _reference = current;
+ return const PanoramaView();
+ }
+ final relative = (reference.conjugate * current).normalized;
+ final forward = relative.rotate(const _Vector3(0, 0, -1));
+ return PanoramaView(
+ longitude: math.atan2(forward.x, -forward.z) * 180 / math.pi,
+ latitude: math.asin(forward.y.clamp(-1, 1)) * 180 / math.pi,
+ );
+ }
+
+ PanoramaView updateValues({
+ required double w,
+ required double x,
+ required double y,
+ required double z,
+ }) {
+ return _update(_Quaternion(w, x, y, z).normalized);
+ }
+
+ PanoramaView updateScreenAdjustedValues({
+ required double w,
+ required double x,
+ required double y,
+ required double z,
+ required int quarterTurns,
+ }) {
+ return _update(
+ _screenAdjustedQuaternion(
+ _Quaternion(w, x, y, z).normalized,
+ quarterTurns,
+ ),
+ );
+ }
+}
+
+_Quaternion _screenAdjustedQuaternion(_Quaternion attitude, int quarterTurns) {
+ final angle = quarterTurns * math.pi / 2;
+ final screenRotation = _Quaternion(
+ math.cos(angle / 2),
+ 0,
+ 0,
+ math.sin(angle / 2),
+ );
+ return attitude * screenRotation;
+}
+
+class _Quaternion {
+ const _Quaternion(this.w, this.x, this.y, this.z);
+
+ final double w;
+ final double x;
+ final double y;
+ final double z;
+
+ _Quaternion get normalized {
+ final length = math.sqrt(w * w + x * x + y * y + z * z);
+ if (length == 0) return const _Quaternion(1, 0, 0, 0);
+ return _Quaternion(w / length, x / length, y / length, z / length);
+ }
+
+ _Quaternion get conjugate => _Quaternion(w, -x, -y, -z);
+
+ _Quaternion operator *(_Quaternion other) {
+ return _Quaternion(
+ w * other.w - x * other.x - y * other.y - z * other.z,
+ w * other.x + x * other.w + y * other.z - z * other.y,
+ w * other.y - x * other.z + y * other.w + z * other.x,
+ w * other.z + x * other.y - y * other.x + z * other.w,
+ );
+ }
+
+ _Vector3 rotate(_Vector3 vector) {
+ final result =
+ this * _Quaternion(0, vector.x, vector.y, vector.z) * conjugate;
+ return _Vector3(result.x, result.y, result.z);
+ }
+}
+
+class _Vector3 {
+ const _Vector3(this.x, this.y, this.z);
+
+ final double x;
+ final double y;
+ final double z;
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/viewer.dart b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/viewer.dart
new file mode 100644
index 0000000000..d015281e6a
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/lib/src/viewer.dart
@@ -0,0 +1,469 @@
+import "dart:async";
+import "dart:math" as math;
+import "dart:ui" as ui;
+
+import "package:ente_panorama_viewer/src/camera.dart";
+import "package:ente_panorama_viewer/src/models.dart";
+import "package:ente_panorama_viewer/src/motion.dart";
+import "package:flutter/material.dart";
+import "package:flutter/physics.dart";
+import "package:flutter/scheduler.dart";
+
+typedef PanoramaErrorCallback =
+ void Function(Object error, StackTrace stackTrace);
+
+Future<ui.FragmentProgram>? _program;
+
+Future<ui.FragmentProgram> _loadProgram() {
+ return _program ??= ui.FragmentProgram.fromAsset(
+ "packages/ente_panorama_viewer/shaders/equirectangular.frag",
+ );
+}
+
+class EntePanoramaViewer extends StatefulWidget {
+ const EntePanoramaViewer({
+ super.key,
+ required this.image,
+ required this.geometry,
+ this.initialView,
+ this.motionEnabled = false,
+ this.placeholder,
+ this.onTap,
+ this.onViewChanged,
+ this.onError,
+ });
+
+ /// Equirectangular source image, either full or cropped.
+ final ImageProvider image;
+
+ /// Placement of [image] on its complete equirectangular canvas.
+ final PanoramaGeometry geometry;
+
+ /// Camera used only on mount and when [image] changes.
+ final PanoramaView? initialView;
+
+ /// Whether device orientation should adjust the camera.
+ final bool motionEnabled;
+
+ /// Shown until both the image and fragment shader are ready.
+ final Widget? placeholder;
+ final VoidCallback? onTap;
+ final ValueChanged<PanoramaView>? onViewChanged;
+ final PanoramaErrorCallback? onError;
+
+ @override
+ State<EntePanoramaViewer> createState() => _EntePanoramaViewerState();
+}
+
+class _EntePanoramaViewerState extends State<EntePanoramaViewer>
+ with TickerProviderStateMixin, WidgetsBindingObserver {
+ late final PanoramaCamera _camera;
+ late final MotionController _motion;
+ late final Ticker _inertiaTicker;
+
+ ui.FragmentShader? _shader;
+ ImageStream? _imageStream;
+ ImageInfo? _imageInfo;
+ late final ImageStreamListener _imageListener;
+
+ PanoramaView _motionBase = const PanoramaView();
+ Offset _lastFocalPoint = Offset.zero;
+ double _lastGestureScale = 1;
+ int _gesturePointerCount = 0;
+ bool _gesturing = false;
+ bool _gestureWasPinch = false;
+ bool _lifecycleActive = false;
+ bool _tickerModeActive = false;
+ bool _dependenciesReady = false;
+
+ FrictionSimulation? _longitudeInertia;
+ FrictionSimulation? _latitudeInertia;
+
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addObserver(this);
+ _lifecycleActive =
+ WidgetsBinding.instance.lifecycleState == AppLifecycleState.resumed;
+ _camera = PanoramaCamera(
+ geometry: widget.geometry,
+ initialView: widget.initialView,
+ )..addListener(_onCameraChanged);
+ _motion = MotionController(
+ _onMotionDelta,
+ onReferenceChanged: _rebaseMotion,
+ onError: _handleMotionError,
+ );
+ _inertiaTicker = createTicker(_onInertiaTick);
+ _imageListener = ImageStreamListener(
+ _handleImageFrame,
+ onError: _handleImageError,
+ );
+ _loadShader();
+ }
+
+ @override
+ void didChangeDependencies() {
+ super.didChangeDependencies();
+ final tickerModeActive = TickerMode.of(context);
+ final motionStateChanged =
+ !_dependenciesReady || tickerModeActive != _tickerModeActive;
+ _dependenciesReady = true;
+ _tickerModeActive = tickerModeActive;
+ if (motionStateChanged) {
+ _syncMotion();
+ }
+ _resolveImage();
+ }
+
+ @override
+ void didUpdateWidget(EntePanoramaViewer oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (widget.image != oldWidget.image) {
+ _camera.updateGeometry(widget.geometry, notify: false);
+ _camera.reset(widget.initialView);
+ _rebaseMotion();
+ _motion.resetReference();
+ _resolveImage();
+ } else if (widget.geometry != oldWidget.geometry) {
+ _camera.updateGeometry(widget.geometry);
+ _rebaseMotion();
+ }
+ if (widget.motionEnabled != oldWidget.motionEnabled) {
+ _syncMotion();
+ }
+ }
+
+ @override
+ void didChangeAppLifecycleState(AppLifecycleState state) {
+ _lifecycleActive = state == AppLifecycleState.resumed;
+ _syncMotion();
+ }
+
+ Future<void> _loadShader() async {
+ try {
+ final program = await _loadProgram();
+ if (!mounted) return;
+ setState(() {
+ _shader = program.fragmentShader();
+ });
+ } catch (error, stackTrace) {
+ widget.onError?.call(error, stackTrace);
+ }
+ }
+
+ void _resolveImage() {
+ final stream = widget.image.resolve(createLocalImageConfiguration(context));
+ if (_imageStream?.key == stream.key) return;
+ _imageStream?.removeListener(_imageListener);
+ if (_imageInfo != null) {
+ setState(() {
+ _replaceImage(null);
+ });
+ }
+ _imageStream = stream..addListener(_imageListener);
+ }
+
+ void _handleImageFrame(ImageInfo imageInfo, bool _) {
+ if (_imageInfo != null && imageInfo.isCloneOf(_imageInfo!)) {
+ imageInfo.dispose();
+ return;
+ }
+ setState(() {
+ _replaceImage(imageInfo);
+ });
+ }
+
+ void _replaceImage(ImageInfo? imageInfo) {
+ final oldImage = _imageInfo;
+ _imageInfo = imageInfo;
+ if (oldImage != null) {
+ SchedulerBinding.instance.addPostFrameCallback((_) {
+ oldImage.dispose();
+ });
+ }
+ }
+
+ void _handleImageError(Object error, StackTrace? stackTrace) {
+ widget.onError?.call(error, stackTrace ?? StackTrace.current);
+ }
+
+ void _handleMotionError(Object error, StackTrace stackTrace) {
+ if (mounted) widget.onError?.call(error, stackTrace);
+ }
+
+ void _onCameraChanged() {
+ widget.onViewChanged?.call(_camera.view);
+ }
+
+ void _syncMotion() {
+ if (widget.motionEnabled &&
+ _lifecycleActive &&
+ _tickerModeActive &&
+ _dependenciesReady) {
+ _rebaseMotion();
+ _motion.resetReference();
+ _motion.start();
+ } else {
+ unawaited(_motion.stop());
+ }
+ }
+
+ void _rebaseMotion() {
+ _motionBase = _camera.view;
+ }
+
+ void _onMotionDelta(PanoramaView delta) {
+ if (_gesturing ||
+ _inertiaTicker.isActive ||
+ !widget.motionEnabled ||
+ !_lifecycleActive ||
+ !_tickerModeActive) {
+ return;
+ }
+ final requested = PanoramaView(
+ longitude: _motionBase.longitude + delta.longitude,
+ latitude: _motionBase.latitude + delta.latitude,
+ zoom: _camera.view.zoom,
+ );
+ final constrained = _camera.wouldConstrain(requested);
+ _camera.setView(requested);
+ if (constrained) {
+ _rebaseMotion();
+ _motion.resetReference();
+ }
+ }
+
+ void _onScaleStart(ScaleStartDetails details) {
+ _stopInertia();
+ _gesturing = true;
+ _lastFocalPoint = details.localFocalPoint;
+ _lastGestureScale = 1;
+ _gesturePointerCount = details.pointerCount;
+ _gestureWasPinch = details.pointerCount > 1;
+ }
+
+ void _onScaleUpdate(ScaleUpdateDetails details) {
+ _gestureWasPinch |= details.pointerCount > 1;
+ if (details.pointerCount != _gesturePointerCount) {
+ _gesturePointerCount = details.pointerCount;
+ _lastFocalPoint = details.localFocalPoint;
+ _lastGestureScale = details.scale;
+ return;
+ }
+ final anchor = _camera.sourcePointAt(_lastFocalPoint);
+ final scaleDelta = details.scale / _lastGestureScale;
+ _camera.setView(
+ _camera.view.copyWith(zoom: _camera.view.zoom * scaleDelta),
+ );
+ _camera.anchorSourcePoint(details.localFocalPoint, anchor);
+ _lastFocalPoint = details.localFocalPoint;
+ _lastGestureScale = details.scale;
+ }
+
+ void _onScaleEnd(ScaleEndDetails details) {
+ _gesturing = false;
+ _motionBase = _camera.view;
+ _motion.resetReference();
+
+ if (_gestureWasPinch) return;
+ final size = _camera.viewport;
+ if (size.isEmpty) return;
+ final velocity = details.velocity.pixelsPerSecond;
+ final longitudeVelocity =
+ -velocity.dx / size.width * _camera.horizontalFieldOfView;
+ final latitudeVelocity =
+ velocity.dy / size.height * _camera.verticalFieldOfView;
+ const drag = 0.08;
+ _longitudeInertia = FrictionSimulation(
+ drag,
+ _camera.view.longitude,
+ longitudeVelocity,
+ );
+ _latitudeInertia = FrictionSimulation(
+ drag,
+ _camera.view.latitude,
+ latitudeVelocity,
+ );
+ _inertiaTicker.start();
+ }
+
+ void _onInertiaTick(Duration elapsed) {
+ final seconds = elapsed.inMicroseconds / Duration.microsecondsPerSecond;
+ final longitude = _longitudeInertia;
+ final latitude = _latitudeInertia;
+ final requested = PanoramaView(
+ longitude: longitude?.x(seconds) ?? _camera.view.longitude,
+ latitude: latitude?.x(seconds) ?? _camera.view.latitude,
+ zoom: _camera.view.zoom,
+ );
+ _camera.setView(requested);
+ final actual = _camera.view;
+ if (!_camera.geometry.coversFullWidth &&
+ (actual.longitude - requested.longitude).abs() > 1e-9) {
+ _longitudeInertia = null;
+ } else if (longitude?.isDone(seconds) ?? false) {
+ _longitudeInertia = null;
+ }
+ if ((actual.latitude - requested.latitude).abs() > 1e-9 ||
+ (latitude?.isDone(seconds) ?? false)) {
+ _latitudeInertia = null;
+ }
+ if (_longitudeInertia == null && _latitudeInertia == null) {
+ _stopInertia(rebaseMotion: true);
+ }
+ }
+
+ void _stopInertia({bool rebaseMotion = false}) {
+ if (_inertiaTicker.isActive) _inertiaTicker.stop();
+ _longitudeInertia = null;
+ _latitudeInertia = null;
+ if (rebaseMotion && widget.motionEnabled) {
+ _motionBase = _camera.view;
+ _motion.resetReference();
+ }
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final viewport = Size(constraints.maxWidth, constraints.maxHeight);
+ final viewportChanged = viewport != _camera.viewport;
+ final viewChanged = _camera.updateViewport(viewport, notify: false);
+ if (viewChanged && widget.onViewChanged != null) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.onViewChanged?.call(_camera.view);
+ });
+ }
+ if (viewportChanged && widget.motionEnabled) {
+ _rebaseMotion();
+ _motion.resetReference();
+ }
+ final shader = _shader;
+ final image = _imageInfo;
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: widget.onTap,
+ onScaleStart: _onScaleStart,
+ onScaleUpdate: _onScaleUpdate,
+ onScaleEnd: _onScaleEnd,
+ child: Stack(
+ fit: StackFit.expand,
+ children: [
+ if ((shader == null || image == null) &&
+ widget.placeholder != null)
+ widget.placeholder!,
+ if (image != null && !widget.geometry.coversFullSphere)
+ RepaintBoundary(
+ child: CustomPaint(
+ isComplex: true,
+ painter: _BlurredBackgroundPainter(image.image),
+ ),
+ ),
+ if (shader != null && image != null)
+ CustomPaint(
+ isComplex: true,
+ willChange: true,
+ painter: _PanoramaPainter(
+ camera: _camera,
+ shader: shader,
+ image: image.image,
+ ),
+ ),
+ ],
+ ),
+ );
+ },
+ );
+ }
+
+ @override
+ void dispose() {
+ WidgetsBinding.instance.removeObserver(this);
+ unawaited(_motion.stop());
+ _camera
+ ..removeListener(_onCameraChanged)
+ ..dispose();
+ _inertiaTicker.dispose();
+ _imageStream?.removeListener(_imageListener);
+ _imageInfo?.dispose();
+ _shader?.dispose();
+ super.dispose();
+ }
+}
+
+class _BlurredBackgroundPainter extends CustomPainter {
+ const _BlurredBackgroundPainter(this.image);
+
+ final ui.Image image;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final imageSize = Size(image.width.toDouble(), image.height.toDouble());
+ final targetSize = size * 1.1;
+ final fitted = applyBoxFit(BoxFit.cover, imageSize, targetSize);
+ final source = Alignment.center.inscribe(
+ fitted.source,
+ Offset.zero & imageSize,
+ );
+ final destination = Rect.fromCenter(
+ center: size.center(Offset.zero),
+ width: fitted.destination.width,
+ height: fitted.destination.height,
+ );
+ canvas.drawImageRect(
+ image,
+ source,
+ destination,
+ Paint()
+ ..filterQuality = FilterQuality.low
+ ..imageFilter = ui.ImageFilter.blur(
+ sigmaX: 32,
+ sigmaY: 32,
+ tileMode: TileMode.mirror,
+ ),
+ );
+ }
+
+ @override
+ bool shouldRepaint(_BlurredBackgroundPainter oldDelegate) {
+ return oldDelegate.image != image;
+ }
+}
+
+class _PanoramaPainter extends CustomPainter {
+ _PanoramaPainter({
+ required this.camera,
+ required this.shader,
+ required this.image,
+ }) : super(repaint: camera);
+
+ final PanoramaCamera camera;
+ final ui.FragmentShader shader;
+ final ui.Image image;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ final view = camera.view;
+ final crop = camera.geometry.normalizedCrop;
+ shader
+ ..setFloat(0, size.width)
+ ..setFloat(1, size.height)
+ ..setFloat(2, math.tan(37.5 * math.pi / 180) / view.zoom)
+ ..setFloat(3, view.longitude * math.pi / 180)
+ ..setFloat(4, view.latitude * math.pi / 180)
+ ..setFloat(5, crop.left)
+ ..setFloat(6, crop.top)
+ ..setFloat(7, crop.right)
+ ..setFloat(8, crop.bottom)
+ ..setFloat(9, camera.geometry.coversFullWidth ? 1 : 0)
+ ..setImageSampler(0, image);
+ canvas.drawRect(Offset.zero & size, Paint()..shader = shader);
+ }
+
+ @override
+ bool shouldRepaint(_PanoramaPainter oldDelegate) {
+ return oldDelegate.shader != shader || oldDelegate.image != image;
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/pubspec.yaml b/mobile/apps/photos/plugins/ente_panorama_viewer/pubspec.yaml
new file mode 100644
index 0000000000..d1bffbaa97
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/pubspec.yaml
@@ -0,0 +1,27 @@
+name: ente_panorama_viewer
+description: First-party equirectangular panorama viewer for Ente Photos.
+
+resolution: workspace
+environment:
+ sdk: ">=3.10.0 <4.0.0"
+ flutter: ">=3.38.0"
+
+dependencies:
+ flutter:
+ sdk: flutter
+
+dev_dependencies:
+ flutter_lints: 6.0.0
+ flutter_test:
+ sdk: flutter
+
+flutter:
+ plugin:
+ platforms:
+ android:
+ package: io.ente.panorama_viewer
+ pluginClass: EntePanoramaViewerPlugin
+ ios:
+ pluginClass: EntePanoramaViewerPlugin
+ shaders:
+ - shaders/equirectangular.frag
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/shaders/equirectangular.frag b/mobile/apps/photos/plugins/ente_panorama_viewer/shaders/equirectangular.frag
new file mode 100644
index 0000000000..47f95ea584
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/shaders/equirectangular.frag
@@ -0,0 +1,88 @@
+#version 320 es
+
+precision highp float;
+
+#include <flutter/runtime_effect.glsl>
+
+uniform vec2 u_size;
+uniform float u_tan_half_fov;
+uniform float u_longitude;
+uniform float u_latitude;
+uniform vec4 u_crop;
+uniform float u_wrap_longitude;
+uniform sampler2D u_texture;
+
+out vec4 frag_color;
+
+const float PI = 3.14159265358979323846;
+
+void main() {
+ vec2 position = FlutterFragCoord().xy / u_size;
+ vec2 normalized = vec2(
+ position.x * 2.0 - 1.0,
+ 1.0 - position.y * 2.0
+ );
+ float aspect = u_size.x / u_size.y;
+ vec3 ray = normalize(vec3(
+ normalized.x * aspect * u_tan_half_fov,
+ normalized.y * u_tan_half_fov,
+ 1.0
+ ));
+
+ float sin_latitude = sin(u_latitude);
+ float cos_latitude = cos(u_latitude);
+ ray = vec3(
+ ray.x,
+ cos_latitude * ray.y + sin_latitude * ray.z,
+ -sin_latitude * ray.y + cos_latitude * ray.z
+ );
+
+ float sin_longitude = sin(u_longitude);
+ float cos_longitude = cos(u_longitude);
+ ray = vec3(
+ cos_longitude * ray.x + sin_longitude * ray.z,
+ ray.y,
+ -sin_longitude * ray.x + cos_longitude * ray.z
+ );
+
+ float source_u = 0.5 + atan(ray.x, ray.z) / (2.0 * PI);
+ source_u = u_wrap_longitude > 0.5 ? fract(source_u) : source_u;
+ if (u_wrap_longitude < 0.5) {
+ if (u_crop.z > 0.99999 && source_u < u_crop.x) {
+ source_u += 1.0;
+ } else if (u_crop.x < 0.00001 && source_u > u_crop.z) {
+ source_u -= 1.0;
+ }
+ }
+ vec2 sphere_uv = vec2(
+ source_u,
+ 0.5 - asin(clamp(ray.y, -1.0, 1.0)) / PI
+ );
+
+ vec2 texture_uv = (sphere_uv - u_crop.xy) / (u_crop.zw - u_crop.xy);
+ bool inside_crop =
+ texture_uv.x >= 0.0 &&
+ texture_uv.x <= 1.0 &&
+ texture_uv.y >= 0.0 &&
+ texture_uv.y <= 1.0;
+ if (!inside_crop) {
+ frag_color = vec4(0.0);
+ return;
+ }
+
+ vec2 clamped_uv = clamp(texture_uv, vec2(0.00001), vec2(0.99999));
+#ifdef IMPELLER_TARGET_OPENGLES
+ clamped_uv.y = 1.0 - clamped_uv.y;
+#endif
+ vec4 sharp_color = texture(u_texture, clamped_uv);
+ vec2 crop_size = u_crop.zw - u_crop.xy;
+ bool full_sphere = crop_size.x > 0.99999 && crop_size.y > 0.99999;
+ float edge_distance = min(
+ min(texture_uv.x, 1.0 - texture_uv.x),
+ min(texture_uv.y, 1.0 - texture_uv.y)
+ );
+ float edge_alpha = full_sphere
+ ? 1.0
+ : smoothstep(0.0, 0.004, edge_distance);
+ frag_color = sharp_color * edge_alpha;
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/test/camera_test.dart b/mobile/apps/photos/plugins/ente_panorama_viewer/test/camera_test.dart
new file mode 100644
index 0000000000..f74ba00452
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/test/camera_test.dart
@@ -0,0 +1,225 @@
+import "dart:math" as math;
+import "dart:ui";
+
+import "package:ente_panorama_viewer/src/camera.dart";
+import "package:ente_panorama_viewer/src/models.dart";
+import "package:ente_panorama_viewer/src/motion.dart";
+import "package:flutter_test/flutter_test.dart";
+
+final _pixelGeometry = PanoramaGeometry(
+ fullSize: const Size(8762, 4381),
+ croppedArea: const Rect.fromLTWH(6183, 1040, 2520, 1664),
+);
+
+void main() {
+ test("rejects crop geometry outside the full panorama", () {
+ expect(
+ () => PanoramaGeometry(
+ fullSize: const Size(100, 50),
+ croppedArea: const Rect.fromLTWH(90, 0, 20, 20),
+ ),
+ throwsArgumentError,
+ );
+ });
+
+ test("replaces non-finite camera values before rendering", () {
+ final camera = PanoramaCamera(
+ geometry: _pixelGeometry,
+ initialView: const PanoramaView(
+ longitude: double.nan,
+ latitude: double.infinity,
+ zoom: double.nan,
+ ),
+ )..updateViewport(const Size(400, 700), notify: false);
+
+ expect(camera.view.longitude.isFinite, isTrue);
+ expect(camera.view.latitude.isFinite, isTrue);
+ expect(camera.view.zoom.isFinite, isTrue);
+ });
+
+ test(
+ "centers a partial panorama and fits portrait and landscape viewports",
+ () {
+ final camera = PanoramaCamera(geometry: _pixelGeometry);
+
+ camera.updateViewport(const Size(1080, 2115), notify: false);
+ expect(camera.view.longitude, closeTo(125.81, 0.01));
+ expect(camera.view.latitude, closeTo(13.09, 0.01));
+ expect(camera.minimumZoom, 1);
+ expect(camera.cropFitZoom, closeTo(1.13, 0.02));
+ expect(camera.view.zoom, camera.cropFitZoom);
+
+ camera.updateViewport(const Size(2000, 1000), notify: false);
+ expect(camera.cropFitZoom, closeTo(1.42, 0.02));
+ expect(camera.view.zoom, camera.cropFitZoom);
+ },
+ );
+
+ test("opens crop-fit without making it the zoom-out limit", () {
+ final camera = PanoramaCamera(
+ geometry: PanoramaGeometry(
+ fullSize: const Size(4000, 2000),
+ croppedArea: const Rect.fromLTWH(1500, 950, 1000, 100),
+ ),
+ );
+
+ camera.updateViewport(const Size(500, 1000), notify: false);
+
+ expect(camera.minimumZoom, 1);
+ expect(camera.cropFitZoom, greaterThan(5));
+ expect(camera.maximumZoom, camera.cropFitZoom);
+ expect(camera.view.zoom, camera.cropFitZoom);
+ });
+
+ test("maps the viewport center to the center of the source crop", () {
+ final camera = PanoramaCamera(geometry: _pixelGeometry)
+ ..updateViewport(const Size(1080, 2115), notify: false);
+ final point = camera.sourcePointAt(const Offset(540, 1057.5));
+ final crop = _pixelGeometry.normalizedCrop;
+
+ expect(point.dx, closeTo(crop.center.dx, 1e-6));
+ expect(point.dy, closeTo(crop.center.dy, 1e-6));
+ });
+
+ test(
+ "keeps the camera center in the crop while allowing blur-backed edges",
+ () {
+ final camera = PanoramaCamera(geometry: _pixelGeometry)
+ ..updateViewport(const Size(2000, 1000), notify: false);
+ camera.setView(
+ const PanoramaView(longitude: -1000, latitude: 1000, zoom: 1),
+ );
+ final crop = _pixelGeometry.normalizedCrop;
+ final center = camera.sourcePointAt(const Offset(1000, 500));
+
+ expect(center.dx, inInclusiveRange(crop.left - 1e-9, crop.right + 1e-9));
+ expect(center.dy, inInclusiveRange(crop.top - 1e-9, crop.bottom + 1e-9));
+ final edges = [
+ camera.sourcePointAt(const Offset(1000, 0)),
+ camera.sourcePointAt(const Offset(1000, 1000)),
+ camera.sourcePointAt(const Offset(0, 500)),
+ camera.sourcePointAt(const Offset(2000, 500)),
+ ];
+ expect(
+ edges.any(
+ (point) =>
+ point.dx < crop.left ||
+ point.dx > crop.right ||
+ point.dy < crop.top ||
+ point.dy > crop.bottom,
+ ),
+ isTrue,
+ );
+ },
+ );
+
+ test("preserves the panorama point beneath a pinch focal point", () {
+ final camera = PanoramaCamera(geometry: _pixelGeometry)
+ ..updateViewport(const Size(1000, 1500), notify: false);
+ const focalPoint = Offset(700, 800);
+ final sourceBefore = camera.sourcePointAt(focalPoint);
+
+ camera.setView(camera.view.copyWith(zoom: camera.view.zoom * 2));
+ camera.anchorSourcePoint(focalPoint, sourceBefore);
+ final sourceAfter = camera.sourcePointAt(focalPoint);
+
+ expect(sourceAfter.dx, closeTo(sourceBefore.dx, 1e-5));
+ expect(sourceAfter.dy, closeTo(sourceBefore.dy, 1e-5));
+ });
+
+ test("wraps longitude across the full-sphere seam", () {
+ final camera = PanoramaCamera(geometry: const PanoramaGeometry.fullSphere())
+ ..updateViewport(const Size(1000, 1000), notify: false);
+
+ expect(camera.wouldConstrain(const PanoramaView(longitude: 540)), isFalse);
+ camera.setView(const PanoramaView(longitude: 540));
+
+ expect(camera.view.longitude, closeTo(-180, 1e-9));
+ expect(camera.sourcePointAt(const Offset(500, 500)).dx, closeTo(0, 1e-9));
+ });
+
+ test("keeps rays past a partial right seam outside the crop", () {
+ final camera = PanoramaCamera(
+ geometry: PanoramaGeometry(
+ fullSize: const Size(1000, 500),
+ croppedArea: const Rect.fromLTWH(700, 0, 300, 500),
+ ),
+ )..updateViewport(const Size(1000, 1000), notify: false);
+
+ const requested = PanoramaView(longitude: 1000);
+ expect(camera.wouldConstrain(requested), isTrue);
+ camera.setView(requested);
+
+ expect(camera.sourcePointAt(const Offset(500, 500)).dx, closeTo(1, 1e-9));
+ expect(camera.sourcePointAt(const Offset(1000, 500)).dx, greaterThan(1));
+ });
+
+ test(
+ "normalizes quaternion magnitude and reports relative yaw and pitch",
+ () {
+ const angle = 20 * math.pi / 180;
+ final tracker = MotionViewTracker();
+ expect(
+ tracker.updateValues(w: 2, x: 0, y: 0, z: 0),
+ const PanoramaView(),
+ );
+
+ final yaw = tracker.updateValues(
+ w: 2 * math.cos(angle / 2),
+ x: 0,
+ y: -2 * math.sin(angle / 2),
+ z: 0,
+ );
+ expect(yaw.longitude, closeTo(20, 1e-6));
+ expect(yaw.latitude, closeTo(0, 1e-6));
+
+ tracker.reset();
+ tracker.updateValues(w: 1, x: 0, y: 0, z: 0);
+ final pitch = tracker.updateValues(
+ w: math.cos(angle / 2),
+ x: math.sin(angle / 2),
+ y: 0,
+ z: 0,
+ );
+ expect(pitch.longitude, closeTo(0, 1e-6));
+ expect(pitch.latitude, closeTo(20, 1e-6));
+ },
+ );
+
+ test("normalizes motion to the current screen orientation", () {
+ const angle = 20 * math.pi / 180;
+
+ PanoramaView landscapeDelta({
+ required int quarterTurns,
+ required double xAngle,
+ required double yAngle,
+ }) {
+ final tracker = MotionViewTracker();
+ tracker.updateScreenAdjustedValues(
+ w: 1,
+ x: 0,
+ y: 0,
+ z: 0,
+ quarterTurns: quarterTurns,
+ );
+ final halfX = xAngle / 2;
+ final halfY = yAngle / 2;
+ return tracker.updateScreenAdjustedValues(
+ w: math.cos(halfX) * math.cos(halfY),
+ x: math.sin(halfX) * math.cos(halfY),
+ y: math.cos(halfX) * math.sin(halfY),
+ z: -math.sin(halfX) * math.sin(halfY),
+ quarterTurns: quarterTurns,
+ );
+ }
+
+ for (final delta in [
+ landscapeDelta(quarterTurns: 1, xAngle: angle, yAngle: 0),
+ landscapeDelta(quarterTurns: 2, xAngle: 0, yAngle: angle),
+ landscapeDelta(quarterTurns: 3, xAngle: -angle, yAngle: 0),
+ ]) {
+ expect(delta.longitude, closeTo(20, 1e-6));
+ expect(delta.latitude, closeTo(0, 1e-6));
+ }
+ });
+}
diff --git a/mobile/apps/photos/plugins/ente_panorama_viewer/test/viewer_test.dart b/mobile/apps/photos/plugins/ente_panorama_viewer/test/viewer_test.dart
new file mode 100644
index 0000000000..fad2bcad4c
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_panorama_viewer/test/viewer_test.dart
@@ -0,0 +1,342 @@
+import "dart:async";
+import "dart:convert";
+import "dart:typed_data";
+
+import "package:ente_panorama_viewer/ente_panorama_viewer.dart";
+import "package:ente_panorama_viewer/src/camera.dart";
+import "package:ente_panorama_viewer/src/motion.dart";
+import "package:flutter/material.dart";
+import "package:flutter_test/flutter_test.dart";
+
+final _tinyImage = base64Decode(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQI12P4z8DwHwAFAAH/"
+ "iZnRjQAAAABJRU5ErkJggg==",
+);
+
+void main() {
+ Widget wrap(Widget child) {
+ return MaterialApp(
+ home: Scaffold(body: SizedBox.expand(child: child)),
+ );
+ }
+
+ Widget wrapSized(Widget child, Size size) {
+ return MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: SizedBox.fromSize(size: size, child: child),
+ ),
+ ),
+ );
+ }
+
+ testWidgets("retains the placeholder and reports image decode errors", (
+ tester,
+ ) async {
+ Object? reportedError;
+ await tester.pumpWidget(
+ wrap(
+ EntePanoramaViewer(
+ image: MemoryImage(Uint8List.fromList(const [1, 2, 3])),
+ geometry: const PanoramaGeometry.fullSphere(),
+ placeholder: const ColoredBox(
+ key: Key("placeholder"),
+ color: Colors.black,
+ ),
+ onError: (error, _) {
+ reportedError = error;
+ },
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ expect(reportedError, isNotNull);
+ expect(find.byKey(const Key("placeholder")), findsOneWidget);
+ });
+
+ testWidgets("reports taps and view changes from touch gestures", (
+ tester,
+ ) async {
+ var taps = 0;
+ final views = <PanoramaView>[];
+ await tester.pumpWidget(
+ wrap(
+ EntePanoramaViewer(
+ image: MemoryImage(_tinyImage),
+ geometry: const PanoramaGeometry.fullSphere(),
+ onTap: () => taps++,
+ onViewChanged: views.add,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+
+ await tester.tap(find.byType(EntePanoramaViewer));
+ expect(taps, 1);
+
+ await tester.drag(find.byType(EntePanoramaViewer), const Offset(150, 50));
+ await tester.pumpAndSettle();
+ expect(views, isNotEmpty);
+ expect(views.last.longitude, isNot(0));
+ });
+
+ testWidgets("motion stop rejects a sensor frame that is already queued", (
+ tester,
+ ) async {
+ final events = StreamController<Object?>.broadcast(sync: true);
+ final deltas = <PanoramaView>[];
+ final errors = <Object>[];
+ final controller = MotionController(
+ deltas.add,
+ onReferenceChanged: () {},
+ onError: (error, _) => errors.add(error),
+ eventStream: () => events.stream,
+ );
+
+ controller.start();
+ await tester.pump();
+ events.add(const <Object?>[1.0, 0.0, 0.0, 0.0, 0]);
+ unawaited(controller.stop());
+ await tester.pump();
+
+ expect(deltas, isEmpty);
+ expect(errors, isEmpty);
+ unawaited(events.close());
+ });
+
+ testWidgets("motion stream errors are reported and stop sensor delivery", (
+ tester,
+ ) async {
+ final events = StreamController<Object?>.broadcast(sync: true);
+ final deltas = <PanoramaView>[];
+ final errors = <Object>[];
+ final controller = MotionController(
+ deltas.add,
+ onReferenceChanged: () {},
+ onError: (error, _) => errors.add(error),
+ eventStream: () => events.stream,
+ );
+
+ controller.start();
+ await tester.pump();
+ final sensorError = StateError("sensor failed");
+ events.addError(sensorError, StackTrace.current);
+ events.add(const <Object?>[1.0, 0.0, 0.0, 0.0, 0]);
+ await tester.pump();
+
+ expect(errors, [sensorError]);
+ expect(deltas, isEmpty);
+ unawaited(controller.stop());
+ await tester.pump();
+ unawaited(events.close());
+ });
+
+ testWidgets("initial view resets only when the image is replaced", (
+ tester,
+ ) async {
+ var image = MemoryImage(_tinyImage);
+ var initialView = const PanoramaView();
+ final views = <PanoramaView>[];
+ late StateSetter rebuild;
+
+ await tester.pumpWidget(
+ wrap(
+ StatefulBuilder(
+ builder: (context, setState) {
+ rebuild = setState;
+ return EntePanoramaViewer(
+ image: image,
+ geometry: const PanoramaGeometry.fullSphere(),
+ initialView: initialView,
+ onViewChanged: views.add,
+ );
+ },
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.drag(find.byType(EntePanoramaViewer), const Offset(150, 0));
+ await tester.pumpAndSettle();
+ final liveLongitude = views.last.longitude;
+
+ rebuild(() {
+ initialView = const PanoramaView(longitude: 90);
+ });
+ await tester.pump();
+ expect(views.last.longitude, liveLongitude);
+
+ rebuild(() {
+ image = MemoryImage(Uint8List.fromList(_tinyImage));
+ initialView = const PanoramaView(longitude: 45);
+ });
+ await tester.pumpAndSettle();
+ expect(views.last.longitude, closeTo(45, 1e-9));
+ });
+
+ testWidgets("rotation preserves the live camera", (tester) async {
+ var size = const Size(400, 700);
+ final image = MemoryImage(_tinyImage);
+ final views = <PanoramaView>[];
+ late StateSetter rebuild;
+
+ await tester.pumpWidget(
+ StatefulBuilder(
+ builder: (context, setState) {
+ rebuild = setState;
+ return wrapSized(
+ EntePanoramaViewer(
+ image: image,
+ geometry: const PanoramaGeometry.fullSphere(),
+ onViewChanged: views.add,
+ ),
+ size,
+ );
+ },
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.drag(find.byType(EntePanoramaViewer), const Offset(100, 0));
+ await tester.pumpAndSettle();
+ final beforeRotation = views.last.longitude;
+
+ rebuild(() {
+ size = const Size(700, 400);
+ });
+ await tester.pump();
+ await tester.timedDrag(
+ find.byType(EntePanoramaViewer),
+ const Offset(1, 0),
+ const Duration(seconds: 1),
+ );
+ await tester.pumpAndSettle();
+
+ expect((views.last.longitude - beforeRotation).abs(), lessThan(5));
+ });
+
+ testWidgets("crop updates clamp the live camera", (tester) async {
+ final image = MemoryImage(_tinyImage);
+ var geometry = const PanoramaGeometry.fullSphere();
+ final views = <PanoramaView>[];
+ late StateSetter rebuild;
+
+ await tester.pumpWidget(
+ wrapSized(
+ StatefulBuilder(
+ builder: (context, setState) {
+ rebuild = setState;
+ return EntePanoramaViewer(
+ image: image,
+ geometry: geometry,
+ onViewChanged: views.add,
+ );
+ },
+ ),
+ const Size(400, 700),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.drag(find.byType(EntePanoramaViewer), const Offset(150, 0));
+ await tester.pumpAndSettle();
+
+ rebuild(() {
+ geometry = PanoramaGeometry(
+ fullSize: const Size(8762, 4381),
+ croppedArea: const Rect.fromLTWH(6183, 1040, 2520, 1664),
+ );
+ });
+ await tester.pump();
+
+ final validator = PanoramaCamera(geometry: geometry)
+ ..updateViewport(const Size(400, 700), notify: false)
+ ..setView(views.last);
+ expect(validator.view, views.last);
+ });
+
+ testWidgets("pinch zoom preserves its focal panorama point", (tester) async {
+ const size = Size(600, 400);
+ const focal = Offset(370, 180);
+ PanoramaView? lastView;
+ const geometry = PanoramaGeometry.fullSphere();
+ final camera = PanoramaCamera(geometry: geometry)
+ ..updateViewport(size, notify: false);
+
+ await tester.pumpWidget(
+ wrapSized(
+ EntePanoramaViewer(
+ image: MemoryImage(_tinyImage),
+ geometry: geometry,
+ onViewChanged: (view) {
+ lastView = view;
+ },
+ ),
+ size,
+ ),
+ );
+ await tester.pumpAndSettle();
+ final topLeft = tester.getTopLeft(find.byType(EntePanoramaViewer));
+ final first = await tester.startGesture(
+ topLeft + focal - const Offset(50, 0),
+ );
+ final second = await tester.startGesture(
+ topLeft + focal + const Offset(50, 0),
+ );
+ await tester.pump();
+ await first.moveTo(topLeft + focal - const Offset(51, 0));
+ await second.moveTo(topLeft + focal + const Offset(51, 0));
+ await tester.pump();
+ camera.setView(lastView!);
+ final sourceBefore = camera.sourcePointAt(focal);
+
+ await first.moveTo(topLeft + focal - const Offset(100, 0));
+ await second.moveTo(topLeft + focal + const Offset(100, 0));
+ await tester.pump();
+ await first.up();
+ await second.up();
+ await tester.pumpAndSettle();
+
+ camera.setView(lastView!);
+ final sourceAfter = camera.sourcePointAt(focal);
+ expect(sourceAfter.dx, closeTo(sourceBefore.dx, 1e-4));
+ expect(sourceAfter.dy, closeTo(sourceBefore.dy, 1e-4));
+ });
+
+ testWidgets("inertia stops when a partial panorama boundary is reached", (
+ tester,
+ ) async {
+ final geometry = PanoramaGeometry(
+ fullSize: const Size(8762, 4381),
+ croppedArea: const Rect.fromLTWH(6183, 1040, 2520, 1664),
+ );
+ final views = <PanoramaView>[];
+
+ await tester.pumpWidget(
+ wrapSized(
+ EntePanoramaViewer(
+ image: MemoryImage(_tinyImage),
+ geometry: geometry,
+ onViewChanged: views.add,
+ ),
+ const Size(400, 700),
+ ),
+ );
+ await tester.pumpAndSettle();
+ await tester.fling(
+ find.byType(EntePanoramaViewer),
+ const Offset(350, 0),
+ 5000,
+ );
+ await tester.pump(const Duration(milliseconds: 16));
+ await tester.pump(const Duration(milliseconds: 200));
+ final countAtBoundary = views.length;
+ await tester.pump(const Duration(seconds: 1));
+
+ expect(views.length, countAtBoundary);
+ final validator = PanoramaCamera(geometry: geometry)
+ ..updateViewport(const Size(400, 700), notify: false);
+ for (final view in views) {
+ validator.setView(view);
+ expect(validator.view, view);
+ }
+ });
+}
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index 64c6f60a26..6bc2ef3fe5 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -73,6 +73,8 @@ dependencies:
path: ../../packages/install_source
ente_lock_screen:
path: ../../packages/lock_screen
+ ente_panorama_viewer:
+ path: plugins/ente_panorama_viewer
ente_photos_rust:
path: rust_builder
ente_pure_utils:
@@ -193,10 +195,6 @@ dependencies:
url: https://github.com/ente/open-mail-app-flutter.git
ref: 13c0244db82b386ad1a53b2451bdfda8d2687cb6
package_info_plus: 8.3.1
- panorama:
- git:
- url: https://github.com/ente/panorama_blur.git
- ref: d7bf958d045ce5c06080aaa39074546f46f064d1
password_strength: 0.2.0
path: 1.9.1 #dart
path_provider: 2.1.5
diff --git a/mobile/apps/photos/test/ui/viewer/file/panorama_view_data_test.dart b/mobile/apps/photos/test/ui/viewer/file/panorama_view_data_test.dart
index abf3ab9662..664fbee6c2 100644
--- a/mobile/apps/photos/test/ui/viewer/file/panorama_view_data_test.dart
+++ b/mobile/apps/photos/test/ui/viewer/file/panorama_view_data_test.dart
@@ -41,7 +41,7 @@ void main() {
expect(uCenter * 360, closeTo(305.8, 0.1));
});
- test("initial view fits within the cropped area", () {
+ test("initial latitude points at the cropped area center", () {
const data = PanoramaViewData(
fullWidth: 8762,
fullHeight: 4381,
@@ -49,18 +49,6 @@ void main() {
);
expect(data.initialLatitude, closeTo(13.09, 0.01));
- expect(data.initialZoom(1080 / 2115), closeTo(1.13, 0.01));
- expect(data.initialZoom(2), closeTo(1.21, 0.01));
- });
-
- test("caps the initial zoom at the viewer's maximum", () {
- const data = PanoramaViewData(
- fullWidth: 4000,
- fullHeight: 2000,
- croppedArea: Rect.fromLTWH(1500, 950, 1000, 100),
- );
-
- expect(data.initialZoom(0.5), 5);
});
test("initial longitude is normalized to [-180, 180]", () {
@@ -112,5 +100,19 @@ void main() {
);
expect(PanoramaViewData.fromXmp(const {}), isNull);
});
+
+ test("returns null when the crop is outside the full panorama", () {
+ expect(
+ PanoramaViewData.fromXmp(const {
+ "GPano:CroppedAreaLeftPixels": "900",
+ "GPano:CroppedAreaTopPixels": "0",
+ "GPano:CroppedAreaImageWidthPixels": "200",
+ "GPano:CroppedAreaImageHeightPixels": "100",
+ "GPano:FullPanoWidthPixels": "1000",
+ "GPano:FullPanoHeightPixels": "500",
+ }),
+ isNull,
+ );
+ });
});
}
diff --git a/mobile/apps/photos/test/ui/viewer/file/panorama_viewer_screen_test.dart b/mobile/apps/photos/test/ui/viewer/file/panorama_viewer_screen_test.dart
index 69fd92f281..33427da436 100644
--- a/mobile/apps/photos/test/ui/viewer/file/panorama_viewer_screen_test.dart
+++ b/mobile/apps/photos/test/ui/viewer/file/panorama_viewer_screen_test.dart
@@ -2,9 +2,9 @@ import "dart:async";
import "dart:io";
import "dart:typed_data";
+import "package:ente_panorama_viewer/ente_panorama_viewer.dart";
import "package:flutter/material.dart";
import "package:flutter_test/flutter_test.dart";
-import "package:panorama/panorama.dart";
import "package:photos/generated/l10n.dart";
import "package:photos/ui/viewer/file/panorama_viewer_screen.dart";
@@ -127,30 +127,31 @@ void main() {
file: imageFile,
thumbnail: null,
xmpExtractor: (_) => completer.future,
+ motionAvailabilityChecker: () async => false,
),
),
);
- // Regression check for #11435: the Panorama widget must not exist yet.
- // Building it with placeholder crop values and updating them afterwards
- // makes the panorama package regenerate its sphere mesh, dropping the
- // already-loaded texture and rendering a blank (untextured) panorama.
- expect(find.byType(Panorama), findsNothing);
+ expect(find.byType(EntePanoramaViewer), findsNothing);
completer.complete(_pixelXmp);
await tester.pump();
- final pano = tester.widget<Panorama>(find.byType(Panorama));
- expect(pano.croppedArea, const Rect.fromLTWH(6183, 1040, 2520, 1664));
- expect(pano.croppedFullWidth, 8762);
- expect(pano.croppedFullHeight, 4381);
+ final pano = tester.widget<EntePanoramaViewer>(
+ find.byType(EntePanoramaViewer),
+ );
+ expect(
+ pano.geometry,
+ PanoramaGeometry(
+ fullSize: const Size(8762, 4381),
+ croppedArea: const Rect.fromLTWH(6183, 1040, 2520, 1664),
+ ),
+ );
// The initial view must face the cropped area (compass heading 305.8
// degrees maps to longitude 125.81 because the panorama widget's
// longitude 0 faces the horizontal center), not the empty canvas area.
- expect(pano.longitude, closeTo(125.81, 0.01));
- expect(pano.latitude, closeTo(13.09, 0.01));
- expect(pano.zoom, closeTo(1.13, 0.01));
- expect(pano.minZoom, pano.zoom);
+ expect(pano.initialView!.longitude, closeTo(125.81, 0.01));
+ expect(pano.initialView!.latitude, closeTo(13.09, 0.01));
// Let the auto-hide timer fire and dispose the screen.
await tester.pump(const Duration(seconds: 6));
@@ -167,16 +168,17 @@ void main() {
file: imageFile,
thumbnail: null,
xmpExtractor: (_) async => throw StateError("no xmp"),
+ motionAvailabilityChecker: () async => false,
),
),
);
await tester.pump();
- final pano = tester.widget<Panorama>(find.byType(Panorama));
- expect(pano.croppedArea, const Rect.fromLTWH(0, 0, 1, 1));
- expect(pano.croppedFullWidth, 1.0);
- expect(pano.croppedFullHeight, 1.0);
- expect(pano.longitude, 0.0);
+ final pano = tester.widget<EntePanoramaViewer>(
+ find.byType(EntePanoramaViewer),
+ );
+ expect(pano.geometry, const PanoramaGeometry.fullSphere());
+ expect(pano.initialView!.longitude, 0);
await tester.pump(const Duration(seconds: 6));
await tester.pumpWidget(const SizedBox());
@@ -192,16 +194,46 @@ void main() {
file: imageFile,
thumbnail: thumbnail,
xmpExtractor: (_) => completer.future,
+ motionAvailabilityChecker: () async => false,
),
),
);
- expect(find.byType(Panorama), findsNothing);
+ expect(find.byType(EntePanoramaViewer), findsNothing);
expect(find.byType(Image), findsOneWidget);
completer.complete(const {});
await tester.pump();
- expect(find.byType(Panorama), findsOneWidget);
+ expect(find.byType(EntePanoramaViewer), findsOneWidget);
+
+ await tester.pump(const Duration(seconds: 6));
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets("shows and toggles motion only when it is available", (
+ tester,
+ ) async {
+ await tester.pumpWidget(
+ wrap(
+ PanoramaViewerScreen(
+ file: imageFile,
+ thumbnail: null,
+ xmpExtractor: (_) async => _pixelXmp,
+ motionAvailabilityChecker: () async => true,
+ ),
+ ),
+ );
+ await tester.pump();
+
+ expect(find.byIcon(Icons.explore_outlined), findsOneWidget);
+ await tester.tap(find.byIcon(Icons.explore_outlined));
+ await tester.pump();
+
+ final pano = tester.widget<EntePanoramaViewer>(
+ find.byType(EntePanoramaViewer),
+ );
+ expect(pano.motionEnabled, isTrue);
+ expect(find.byIcon(Icons.explore_off_outlined), findsOneWidget);
await tester.pump(const Duration(seconds: 6));
await tester.pumpWidget(const SizedBox());
diff --git a/mobile/pubspec.lock b/mobile/pubspec.lock
index cbca563e15..1fb9a2a7c6 100644
--- a/mobile/pubspec.lock
+++ b/mobile/pubspec.lock
@@ -859,14 +859,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "0.2.4"
- flutter_cube:
- dependency: transitive
- description:
- name: flutter_cube
- sha256: "71cf679a251166eb97f86751c56582b09abdbf859485fbf60524948813914c3b"
- url: "https://pub.dev"
- source: hosted
- version: "0.1.1"
flutter_displaymode:
dependency: transitive
description:
@@ -1844,15 +1836,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.0.0"
- motion_sensors:
- dependency: "direct overridden"
- description:
- path: "."
- ref: "4b11d59f4bda152627f701070272f657f8358e67"
- resolved-ref: "4b11d59f4bda152627f701070272f657f8358e67"
- url: "https://github.com/deckerst/aves_panorama_motion_sensors.git"
- source: git
- version: "0.1.0"
motionphoto:
dependency: transitive
description:
@@ -2056,15 +2039,6 @@ packages:
url: "https://pub.dev"
source: hosted
version: "3.2.1"
- panorama:
- dependency: transitive
- description:
- path: "."
- ref: d7bf958d045ce5c06080aaa39074546f46f064d1
- resolved-ref: d7bf958d045ce5c06080aaa39074546f46f064d1
- url: "https://github.com/ente/panorama_blur.git"
- source: git
- version: "0.4.1"
password_strength:
dependency: transitive
description:
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index 1812623de9..183f4fdc8d 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -11,6 +11,7 @@ workspace:
- apps/photos/plugins/ente_cast
- apps/photos/plugins/ente_crypto
- apps/photos/plugins/ente_feature_flag
+ - apps/photos/plugins/ente_panorama_viewer
- packages/accounts
- packages/account_deletion
- packages/backup_exclusion
@@ -54,10 +55,6 @@ dependency_overrides:
url: https://github.com/Baseflow/flutter_cache_manager.git
ref: 54904e499a06d0364a2b3f4ca9789e5f829f1879
path: flutter_cache_manager
- motion_sensors:
- git:
- url: https://github.com/deckerst/aves_panorama_motion_sensors.git
- ref: 4b11d59f4bda152627f701070272f657f8358e67
# Fixes an iOS AVFoundation crash for videos whose minFrameDuration is zero.
# https://github.com/flutter/flutter/issues/151031
video_player_avfoundation: