Skip to content

armgit / ente

Public Imported from GitHub
0

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

Use Flutter for the wallpaper UI

Neeraj Gupta0e335de49d01
diff --git a/.github/workflows/mobile-crowdin-push-sources.yml b/.github/workflows/mobile-crowdin-push-sources.yml
index c066e09b22..c5dbd703f8 100644
--- a/.github/workflows/mobile-crowdin-push-sources.yml
+++ b/.github/workflows/mobile-crowdin-push-sources.yml
@@ -5,7 +5,6 @@ on:
branches: [main]
paths:
- ".github/workflows/mobile-crowdin-push-sources.yml"
- - "mobile/packages/strings/android/values/*.xml"
- "mobile/packages/strings/crowdin.yml"
- "mobile/packages/strings/lib/l10n/arb/strings_en.arb"
diff --git a/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/WallpaperActivity.kt b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/WallpaperActivity.kt
new file mode 100644
index 0000000000..b60bfa7ae9
--- /dev/null
+++ b/mobile/apps/photos/android/app/src/main/kotlin/io/ente/photos/WallpaperActivity.kt
@@ -0,0 +1,11 @@
+package io.ente.photos
+
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin
+
+class WallpaperActivity : io.ente.photos.platform.flutter.WallpaperActivity() {
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ super.configureFlutterEngine(flutterEngine)
+ flutterEngine.plugins.add(SharedPreferencesPlugin())
+ }
+}
diff --git a/mobile/apps/photos/lib/main.dart b/mobile/apps/photos/lib/main.dart
index 09231b8c62..68e9585a0e 100644
--- a/mobile/apps/photos/lib/main.dart
+++ b/mobile/apps/photos/lib/main.dart
@@ -64,6 +64,7 @@ import "package:photos/services/sync/sync_service.dart";
import "package:photos/services/video_preview_service.dart";
import "package:photos/src/rust/api/log.dart" as photos_rust_log;
import "package:photos/src/rust/frb_generated.dart";
+import 'package:photos/ui/wallpaper/wallpaper_page.dart';
import "package:photos/utils/bg_task_utils.dart";
import "package:photos/utils/device_info.dart";
import "package:photos/utils/email_util.dart";
@@ -98,6 +99,9 @@ late final photos_rust_log.LogSinkGuard _photosRustLogSinkGuard;
enum ForegroundStartupMode { normal, picker }
+@pragma('vm:entry-point')
+Future<void> wallpaperMain() => runWallpaperApp();
+
void main() async {
debugRepaintRainbowEnabled = false;
WidgetsFlutterBinding.ensureInitialized();
diff --git a/mobile/apps/photos/lib/ui/wallpaper/wallpaper_crop.dart b/mobile/apps/photos/lib/ui/wallpaper/wallpaper_crop.dart
new file mode 100644
index 0000000000..842caec6c6
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/wallpaper/wallpaper_crop.dart
@@ -0,0 +1,124 @@
+import 'dart:math' as math;
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+
+class WallpaperCrop {
+ Offset _center = const Offset(0.5, 0.5);
+ double _zoom = 1;
+ Rect region = const Rect.fromLTWH(0, 0, 1, 1);
+
+ void layout(Size viewport, ui.Image image) {
+ final scale = _scale(viewport, image);
+ final halfWidth = math.min(0.5, viewport.width / (2 * scale * image.width));
+ final halfHeight = math.min(
+ 0.5,
+ viewport.height / (2 * scale * image.height),
+ );
+ _center = Offset(
+ _center.dx.clamp(halfWidth, 1 - halfWidth),
+ _center.dy.clamp(halfHeight, 1 - halfHeight),
+ );
+ region = Rect.fromCenter(
+ center: _center,
+ width: 2 * halfWidth,
+ height: 2 * halfHeight,
+ );
+ }
+
+ void update(
+ ScaleUpdateDetails details,
+ double zoom,
+ Size viewport,
+ ui.Image image,
+ ) {
+ final before = _scale(viewport, image);
+ _zoom = zoom.clamp(1, 4);
+ final after = _scale(viewport, image);
+ final focus = details.localFocalPoint - viewport.center(Offset.zero);
+ final delta =
+ focus * (1 / before - 1 / after) - details.focalPointDelta / before;
+ _center += Offset(delta.dx / image.width, delta.dy / image.height);
+ layout(viewport, image);
+ }
+
+ double _scale(Size viewport, ui.Image image) =>
+ math.max(viewport.width / image.width, viewport.height / image.height) *
+ _zoom;
+}
+
+class WallpaperCropView extends StatefulWidget {
+ const WallpaperCropView({
+ required this.image,
+ required this.crop,
+ required this.enabled,
+ super.key,
+ });
+
+ final ui.Image image;
+ final WallpaperCrop crop;
+ final bool enabled;
+
+ @override
+ State<WallpaperCropView> createState() => _WallpaperCropViewState();
+}
+
+class _WallpaperCropViewState extends State<WallpaperCropView> {
+ double _startZoom = 1;
+
+ @override
+ Widget build(BuildContext context) {
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final viewport = constraints.biggest;
+ widget.crop.layout(viewport, widget.image);
+ return GestureDetector(
+ onScaleStart: widget.enabled
+ ? (_) => _startZoom = widget.crop._zoom
+ : null,
+ onScaleUpdate: widget.enabled
+ ? (details) => setState(() {
+ widget.crop.update(
+ details,
+ _startZoom * details.scale,
+ viewport,
+ widget.image,
+ );
+ })
+ : null,
+ child: CustomPaint(
+ painter: _CropPainter(widget.image, widget.crop.region),
+ size: viewport,
+ ),
+ );
+ },
+ );
+ }
+}
+
+class _CropPainter extends CustomPainter {
+ const _CropPainter(this.image, this.region);
+
+ final ui.Image image;
+ final Rect region;
+
+ @override
+ void paint(Canvas canvas, Size size) {
+ canvas.drawRect(Offset.zero & size, Paint()..color = Colors.black);
+ canvas.drawImageRect(
+ image,
+ Rect.fromLTRB(
+ region.left * image.width,
+ region.top * image.height,
+ region.right * image.width,
+ region.bottom * image.height,
+ ),
+ Offset.zero & size,
+ Paint()..filterQuality = FilterQuality.medium,
+ );
+ }
+
+ @override
+ bool shouldRepaint(_CropPainter oldDelegate) =>
+ image != oldDelegate.image || region != oldDelegate.region;
+}
diff --git a/mobile/apps/photos/lib/ui/wallpaper/wallpaper_page.dart b/mobile/apps/photos/lib/ui/wallpaper/wallpaper_page.dart
new file mode 100644
index 0000000000..6b38637c4e
--- /dev/null
+++ b/mobile/apps/photos/lib/ui/wallpaper/wallpaper_page.dart
@@ -0,0 +1,195 @@
+import 'dart:ui' as ui;
+
+import 'package:adaptive_theme/adaptive_theme.dart';
+import 'package:ente_components/ente_components.dart';
+import 'package:ente_photos_platform/ente_photos_platform.dart';
+import 'package:ente_strings/ente_strings.dart';
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+import 'package:hugeicons/hugeicons.dart';
+import 'package:logging/logging.dart';
+import 'package:photos/ente_theme_data.dart';
+import 'package:photos/locale.dart';
+import 'package:photos/ui/wallpaper/wallpaper_crop.dart';
+
+Future<void> runWallpaperApp() async {
+ WidgetsFlutterBinding.ensureInitialized();
+ ComponentTheme.configure(app: ComponentApp.photos);
+ final theme = await AdaptiveTheme.getThemeMode();
+ final locale = await getLocale(noFallback: true);
+ runApp(
+ MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: lightThemeData,
+ darkTheme: darkThemeData,
+ themeMode: switch (theme) {
+ AdaptiveThemeMode.light => ThemeMode.light,
+ AdaptiveThemeMode.dark => ThemeMode.dark,
+ _ => ThemeMode.system,
+ },
+ locale: locale,
+ supportedLocales: appSupportedLocales,
+ localizationsDelegates: StringsLocalizations.localizationsDelegates,
+ localeListResolutionCallback: localResolutionCallBack,
+ home: const WallpaperPage(),
+ ),
+ );
+}
+
+class WallpaperPage extends StatefulWidget {
+ const WallpaperPage({super.key});
+
+ @override
+ State<WallpaperPage> createState() => _WallpaperPageState();
+}
+
+class _WallpaperPageState extends State<WallpaperPage> {
+ final _client = WallpaperClient();
+ final _crop = WallpaperCrop();
+ ui.Image? _image;
+ Size? _wallpaperSize;
+ String? _error;
+ bool _applying = false;
+ bool _done = false;
+
+ @override
+ void initState() {
+ super.initState();
+ _load();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ final l10n = context.strings;
+ return PopScope(
+ canPop: !_applying,
+ child: Scaffold(
+ appBar: AppBar(
+ leading: IconButton(
+ tooltip: l10n.close,
+ icon: const HugeIcon(icon: HugeIcons.strokeRoundedCancel01),
+ onPressed: _applying ? null : SystemNavigator.pop,
+ ),
+ title: Text(l10n.wallpaper, style: TextStyles.h2),
+ ),
+ body: SafeArea(
+ child: Column(
+ children: [
+ Expanded(
+ child: _image == null
+ ? Center(
+ child: _error == null
+ ? const CircularProgressIndicator()
+ : Text(
+ _error == 'unavailable'
+ ? l10n.wallpaperUnavailable
+ : l10n.wallpaperFailed,
+ textAlign: TextAlign.center,
+ ),
+ )
+ : Center(
+ child: AspectRatio(
+ aspectRatio: _wallpaperSize!.aspectRatio,
+ child: WallpaperCropView(
+ image: _image!,
+ crop: _crop,
+ enabled: !_applying,
+ ),
+ ),
+ ),
+ ),
+ Padding(
+ padding: const EdgeInsets.all(Spacing.xl),
+ child: ButtonComponent(
+ label: _done ? l10n.wallpaperSet : l10n.setWallpaper,
+ isDisabled: _image == null || _applying,
+ shouldSurfaceExecutionStates: false,
+ leading: _applying
+ ? _done
+ ? const Icon(Icons.check)
+ : const SizedBox.square(
+ dimension: 20,
+ child: CircularProgressIndicator(
+ strokeWidth: 2,
+ ),
+ )
+ : null,
+ onTap: _chooseDestination,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> _load() async {
+ try {
+ final preview = await _client.prepare();
+ final image = await decodeImageFromList(preview.bytes);
+ if (!mounted) {
+ image.dispose();
+ return;
+ }
+ setState(() {
+ _image = image;
+ _wallpaperSize = preview.size;
+ });
+ } catch (error) {
+ Logger('Wallpaper').warning('Could not load wallpaper', error);
+ if (mounted) {
+ setState(() {
+ _error = error is PlatformException ? error.code : 'wallpaper_failed';
+ });
+ }
+ }
+ }
+
+ Future<void> _chooseDestination() async {
+ final l10n = context.strings;
+ final destination = await showBottomSheetComponent<WallpaperDestination>(
+ context: context,
+ builder: (context) => BottomSheetComponent(
+ title: l10n.setWallpaper,
+ closeTooltip: l10n.close,
+ actions: [
+ for (final destination in WallpaperDestination.values)
+ ButtonComponent(
+ label: switch (destination) {
+ WallpaperDestination.home => l10n.wallpaperHome,
+ WallpaperDestination.lock => l10n.wallpaperLock,
+ WallpaperDestination.both => l10n.wallpaperBoth,
+ },
+ variant: ButtonComponentVariant.neutral,
+ shouldSurfaceExecutionStates: false,
+ onTap: () => Navigator.of(context).pop(destination),
+ ),
+ ],
+ ),
+ );
+ if (destination == null || !mounted) return;
+ setState(() => _applying = true);
+ try {
+ await _client.apply(_crop.region, destination);
+ if (!mounted) return;
+ setState(() => _done = true);
+ await Future<void>.delayed(const Duration(seconds: 1));
+ if (mounted) await SystemNavigator.pop();
+ } catch (error) {
+ Logger('Wallpaper').warning('Could not set wallpaper', error);
+ if (mounted) {
+ setState(() => _applying = false);
+ ScaffoldMessenger.of(
+ context,
+ ).showSnackBar(SnackBar(content: Text(l10n.wallpaperFailed)));
+ }
+ }
+ }
+
+ @override
+ void dispose() {
+ _image?.dispose();
+ super.dispose();
+ }
+}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle b/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle
index 3dff0a1317..a759d7bf97 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle
+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/build.gradle
@@ -39,8 +39,6 @@ android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
- main.res.srcDir '../../../../../packages/strings/android'
- main.assets.srcDir layout.buildDirectory.dir('generated/wallpaperAssets')
}
defaultConfig {
@@ -48,13 +46,6 @@ android {
}
}
-def wallpaperFonts = tasks.register('prepareWallpaperFonts', Copy) {
- from '../../../../../packages/ente_components/fonts'
- include 'Inter-Regular.ttf', 'Inter-SemiBold.ttf'
- into layout.buildDirectory.dir('generated/wallpaperAssets')
-}
-tasks.named('preBuild').configure { dependsOn wallpaperFonts }
-
dependencies {
implementation 'androidx.exifinterface:exifinterface:1.3.7'
}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml
index dbed2c7d4a..70cbe0543f 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml
+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/AndroidManifest.xml
@@ -2,9 +2,11 @@
<uses-permission android:name="android.permission.SET_WALLPAPER" />
<application android:supportsRtl="true">
<activity
- android:name="io.ente.photos.platform.flutter.WallpaperActivity"
+ android:name="io.ente.photos.WallpaperActivity"
android:exported="true"
android:enableOnBackInvokedCallback="true"
+ android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
+ android:hardwareAccelerated="true"
android:label="@string/wallpaper"
android:theme="@style/WallpaperTheme">
<intent-filter>
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/flutter/WallpaperActivity.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/flutter/WallpaperActivity.kt
index 0fc5e0009d..5c347a58ca 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/flutter/WallpaperActivity.kt
+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/flutter/WallpaperActivity.kt
@@ -1,19 +1,67 @@
package io.ente.photos.platform.flutter
-import android.content.Context
-import android.content.res.Configuration
-import java.util.Locale
+import android.graphics.Point
+import android.graphics.RectF
+import android.view.Surface
+import io.ente.photos.platform.wallpaper.Destination
+import io.ente.photos.platform.wallpaper.WallpaperSession
+import io.flutter.embedding.android.FlutterActivity
+import io.flutter.embedding.engine.FlutterEngine
+import io.flutter.plugin.common.MethodChannel
+import java.util.concurrent.CompletableFuture
-class WallpaperActivity : io.ente.photos.platform.wallpaper.WallpaperActivity() {
- override fun attachBaseContext(base: Context) {
- val language = base.getSharedPreferences("FlutterSharedPreferences", Context.MODE_PRIVATE)
- .getString("flutter.locale", null)
- val localized = if (language == null) base else {
- val configuration = Configuration(base.resources.configuration).apply {
- setLocale(Locale.forLanguageTag(language.replace('_', '-')))
+open class WallpaperActivity : FlutterActivity() {
+ private lateinit var session: WallpaperSession
+ private lateinit var channel: MethodChannel
+
+ override fun getDartEntrypointFunctionName() = "wallpaperMain"
+
+ override fun getInitialRoute() = "/"
+
+ override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
+ val size = Point()
+ @Suppress("DEPRECATION")
+ val display = windowManager.defaultDisplay
+ @Suppress("DEPRECATION")
+ display.getRealSize(size)
+ if (display.rotation == Surface.ROTATION_90 || display.rotation == Surface.ROTATION_270) {
+ size.set(size.y, size.x)
+ }
+ session = WallpaperSession(this, intent.data, size)
+ channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "io.ente.photos.platform/wallpaper")
+ channel.setMethodCallHandler { call, result ->
+ when (call.method) {
+ "prepare" -> reply(session.preview().thenApply { bytes ->
+ mapOf("bytes" to bytes, "width" to size.x, "height" to size.y)
+ }, result)
+ "apply" -> {
+ val region = call.argument<List<Double>>("region")!!
+ val destination = Destination.valueOf(call.argument<String>("destination")!!.uppercase())
+ val crop = RectF(region[0].toFloat(), region[1].toFloat(), region[2].toFloat(), region[3].toFloat())
+ reply(session.apply(crop, destination).thenRun {
+ runOnUiThread { setResult(RESULT_OK) }
+ }, result)
+ }
+ else -> result.notImplemented()
+ }
+ }
+ }
+
+ private fun reply(task: CompletableFuture<*>, result: MethodChannel.Result) {
+ task.whenComplete { value, error ->
+ runOnUiThread {
+ if (!isDestroyed) {
+ if (error == null) result.success(value)
+ else result.error(if (error.cause is UnsupportedOperationException) "unavailable" else "wallpaper_failed", error.message, null)
+ }
}
- base.createConfigurationContext(configuration)
}
- super.attachBaseContext(localized)
+ }
+
+ override fun cleanUpFlutterEngine(flutterEngine: FlutterEngine) {
+ channel.setMethodCallHandler(null)
+ session.close()
+ super.cleanUpFlutterEngine(flutterEngine)
}
}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/DestinationSheet.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/DestinationSheet.kt
deleted file mode 100644
index 819b30923a..0000000000
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/DestinationSheet.kt
+++ /dev/null
@@ -1,93 +0,0 @@
-package io.ente.photos.platform.wallpaper
-
-import android.app.Dialog
-import android.content.Context
-import android.content.res.ColorStateList
-import android.graphics.Color
-import android.graphics.Typeface
-import android.graphics.drawable.ColorDrawable
-import android.graphics.drawable.GradientDrawable
-import android.graphics.drawable.RippleDrawable
-import android.view.Gravity
-import android.view.Window
-import android.view.ViewGroup.LayoutParams.MATCH_PARENT
-import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
-import android.widget.ImageButton
-import android.widget.Button
-import android.widget.LinearLayout
-import android.widget.TextView
-import io.ente.photos.platform.R
-
-internal class DestinationSheet(context: Context, onSelected: (Destination) -> Unit) : Dialog(context) {
- private val regular = Typeface.createFromAsset(context.assets, "Inter-Regular.ttf")
- private val semibold = Typeface.createFromAsset(context.assets, "Inter-SemiBold.ttf")
-
- init {
- requestWindowFeature(Window.FEATURE_NO_TITLE)
- window!!.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
- val content = LinearLayout(context).apply {
- orientation = LinearLayout.VERTICAL
- setPadding(dp(20), dp(20), dp(20), dp(20))
- background = GradientDrawable().apply {
- setColor(0xFF161616.toInt())
- cornerRadii = floatArrayOf(dp(20).toFloat(), dp(20).toFloat(), dp(20).toFloat(), dp(20).toFloat(), 0f, 0f, 0f, 0f)
- }
- }
- val header = LinearLayout(context).apply { gravity = Gravity.CENTER_VERTICAL }
- header.addView(TextView(context).apply {
- setText(R.string.wallpaper_set)
- textSize = 18f
- typeface = semibold
- setTextColor(Color.WHITE)
- }, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
- header.addView(ImageButton(context).apply {
- setImageResource(R.drawable.wallpaper_close)
- contentDescription = context.getString(android.R.string.cancel)
- background = surface(24)
- setOnClickListener { dismiss() }
- }, LinearLayout.LayoutParams(dp(48), dp(48)))
- content.addView(header, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { bottomMargin = dp(16) })
- for (destination in Destination.entries) {
- content.addView(Button(context).apply {
- setText(destination.label)
- isAllCaps = false
- letterSpacing = 0f
- stateListAnimator = null
- textSize = 16f
- typeface = regular
- setTextColor(Color.WHITE)
- gravity = Gravity.CENTER_VERTICAL
- minHeight = dp(56)
- setPadding(dp(20), dp(16), dp(20), dp(16))
- background = surface(20)
- setOnClickListener {
- dismiss()
- onSelected(destination)
- }
- }, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT).apply { bottomMargin = dp(8) })
- }
- setContentView(content)
- setCanceledOnTouchOutside(true)
- }
-
- override fun onStart() {
- super.onStart()
- window!!.apply {
- setGravity(Gravity.BOTTOM)
- setLayout(MATCH_PARENT, WRAP_CONTENT)
- setDimAmount(0.55f)
- navigationBarColor = 0xFF161616.toInt()
- }
- }
-
- private fun surface(radius: Int) = RippleDrawable(
- ColorStateList.valueOf(0x29FFFFFF),
- GradientDrawable().apply {
- setColor(0xFF212121.toInt())
- cornerRadius = dp(radius).toFloat()
- },
- null,
- )
-
- private fun dp(value: Int) = (value * context.resources.displayMetrics.density).toInt()
-}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperActivity.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperActivity.kt
deleted file mode 100644
index 5105532957..0000000000
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperActivity.kt
+++ /dev/null
@@ -1,238 +0,0 @@
-package io.ente.photos.platform.wallpaper
-
-import android.app.Activity
-import android.content.ContentResolver
-import android.content.res.ColorStateList
-import android.graphics.Color
-import android.graphics.Point
-import android.graphics.Typeface
-import android.graphics.drawable.GradientDrawable
-import android.graphics.drawable.RippleDrawable
-import android.net.Uri
-import android.os.Build
-import android.os.Bundle
-import android.util.Log
-import android.view.Gravity
-import android.view.Surface
-import android.view.View
-import android.window.OnBackInvokedDispatcher
-import android.widget.Button
-import android.widget.FrameLayout
-import android.widget.ImageButton
-import android.widget.LinearLayout
-import android.widget.ProgressBar
-import android.widget.TextView
-import android.widget.Toast
-import io.ente.photos.platform.R
-import java.util.concurrent.CompletableFuture
-import java.util.concurrent.Executors
-
-open class WallpaperActivity : Activity() {
- private val executor = Executors.newSingleThreadExecutor()
- private lateinit var preview: WallpaperCropView
- private lateinit var applyButton: Button
- private lateinit var closeButton: ImageButton
- private lateinit var progress: ProgressBar
- private lateinit var service: WallpaperService
- private lateinit var imageUri: Uri
- private var pendingApply: CompletableFuture<Unit>? = null
- private var destinationSheet: DestinationSheet? = null
- private var loaded = false
-
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- @Suppress("UNCHECKED_CAST", "DEPRECATION")
- val retained = lastNonConfigurationInstance as? CompletableFuture<Unit>
- pendingApply = retained
- service = WallpaperService(this)
- if (!service.isAvailable) {
- Toast.makeText(this, R.string.wallpaper_unavailable, Toast.LENGTH_LONG).show()
- finish()
- return
- }
- val uri = intent.data
- if (uri?.scheme != ContentResolver.SCHEME_CONTENT) {
- showFailure(IllegalArgumentException("Expected an image content URI"))
- finish()
- return
- }
- imageUri = uri
- val displaySize = Point()
- @Suppress("DEPRECATION")
- windowManager.defaultDisplay.getRealSize(displaySize)
- @Suppress("DEPRECATION")
- val rotation = windowManager.defaultDisplay.rotation
- if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
- displaySize.set(displaySize.y, displaySize.x)
- }
- preview = WallpaperCropView(this, displaySize)
- preview.restoreCrop(savedInstanceState?.getFloatArray("crop"))
- val content = LinearLayout(this).apply {
- orientation = LinearLayout.VERTICAL
- setOnApplyWindowInsetsListener { view, insets ->
- @Suppress("DEPRECATION")
- view.setPadding(
- insets.systemWindowInsetLeft,
- insets.systemWindowInsetTop,
- insets.systemWindowInsetRight,
- insets.systemWindowInsetBottom,
- )
- insets
- }
- }
- val semibold = Typeface.createFromAsset(assets, "Inter-SemiBold.ttf")
- val header = LinearLayout(this).apply {
- gravity = Gravity.CENTER_VERTICAL
- setPadding(dp(8), dp(4), dp(20), dp(4))
- }
- closeButton = ImageButton(this).apply {
- setImageResource(R.drawable.wallpaper_close)
- contentDescription = getString(android.R.string.cancel)
- background = RippleDrawable(ColorStateList.valueOf(0x29FFFFFF), null, null)
- setOnClickListener { close() }
- }
- header.addView(closeButton, LinearLayout.LayoutParams(dp(48), dp(48)))
- header.addView(TextView(this).apply {
- setText(R.string.wallpaper)
- typeface = semibold
- textSize = 18f
- setTextColor(Color.WHITE)
- })
- content.addView(header)
- content.addView(preview, LinearLayout.LayoutParams(-1, 0, 1f))
- applyButton = Button(this).apply {
- setText(R.string.wallpaper_set)
- isAllCaps = false
- letterSpacing = 0f
- stateListAnimator = null
- typeface = semibold
- textSize = 16f
- minHeight = dp(56)
- setPadding(dp(20), dp(14), dp(20), dp(14))
- background = RippleDrawable(
- ColorStateList.valueOf(0x29000000),
- GradientDrawable().apply {
- setColor(0xFF08C225.toInt())
- cornerRadius = dp(20).toFloat()
- },
- null,
- )
- setOnClickListener { chooseDestination() }
- }
- progress = ProgressBar(this).apply {
- isIndeterminate = true
- indeterminateTintList = ColorStateList.valueOf(Color.WHITE)
- }
- val action = FrameLayout(this).apply {
- addView(applyButton, FrameLayout.LayoutParams(-1, -2))
- addView(progress, FrameLayout.LayoutParams(dp(24), dp(24), Gravity.CENTER))
- }
- content.addView(action, LinearLayout.LayoutParams(-1, -2).apply {
- setMargins(dp(20), dp(16), dp(20), dp(16))
- })
- setBusy(true)
- setContentView(content)
- if (Build.VERSION.SDK_INT >= 33) {
- onBackInvokedDispatcher.registerOnBackInvokedCallback(OnBackInvokedDispatcher.PRIORITY_DEFAULT) { close() }
- }
- retained?.let(::observeApply)
- executor.execute {
- try {
- val bitmap = service.decode(uri, displaySize)
- runOnUiThread {
- if (isDestroyed) {
- bitmap.recycle()
- } else {
- preview.setImage(bitmap)
- loaded = true
- setBusy(pendingApply != null)
- }
- }
- } catch (error: Exception) {
- runOnUiThread {
- if (!isDestroyed) {
- showFailure(error)
- finish()
- }
- }
- }
- }
- }
-
- private fun chooseDestination() {
- destinationSheet = DestinationSheet(this, ::applyWallpaper).also { it.show() }
- }
-
- private fun applyWallpaper(destination: Destination) {
- if (pendingApply != null) return
- val crop = preview.selection()
- val task = CompletableFuture.supplyAsync({
- val bitmap = service.render(imageUri, crop)
- try {
- service.apply(bitmap, destination)
- } finally {
- bitmap.recycle()
- }
- }, executor)
- pendingApply = task
- setBusy(true)
- observeApply(task)
- }
-
- private fun observeApply(task: CompletableFuture<Unit>) {
- task.whenComplete { _, error ->
- runOnUiThread {
- if (isDestroyed) return@runOnUiThread
- if (error == null) {
- Toast.makeText(this, R.string.wallpaper_done, Toast.LENGTH_SHORT).show()
- setResult(RESULT_OK)
- finish()
- } else {
- showFailure(error)
- pendingApply = null
- setBusy(!loaded)
- }
- }
- }
- }
-
- private fun setBusy(busy: Boolean) {
- closeButton.isEnabled = pendingApply == null
- closeButton.alpha = if (closeButton.isEnabled) 1f else 0.4f
- applyButton.isEnabled = !busy
- applyButton.alpha = if (busy) 0.4f else 1f
- applyButton.setTextColor(if (busy) Color.TRANSPARENT else Color.WHITE)
- preview.isEnabled = !busy
- progress.visibility = if (busy) View.VISIBLE else View.GONE
- }
-
- private fun dp(value: Int) = (value * resources.displayMetrics.density).toInt()
-
- private fun close() {
- if (pendingApply == null) finish()
- }
-
- @Suppress("OVERRIDE_DEPRECATION")
- override fun onBackPressed() = close()
-
- private fun showFailure(error: Throwable) {
- Log.e("Wallpaper", "Wallpaper operation failed", error)
- Toast.makeText(this, R.string.wallpaper_failed, Toast.LENGTH_LONG).show()
- }
-
- override fun onSaveInstanceState(outState: Bundle) {
- if (::preview.isInitialized) outState.putFloatArray("crop", preview.saveCrop())
- super.onSaveInstanceState(outState)
- }
-
- @Suppress("OVERRIDE_DEPRECATION")
- override fun onRetainNonConfigurationInstance(): Any? = pendingApply
-
- override fun onDestroy() {
- destinationSheet?.dismiss()
- executor.shutdown()
- if (::preview.isInitialized) preview.release()
- super.onDestroy()
- }
-}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperCropView.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperCropView.kt
deleted file mode 100644
index ec94db709c..0000000000
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperCropView.kt
+++ /dev/null
@@ -1,132 +0,0 @@
-package io.ente.photos.platform.wallpaper
-
-import android.content.Context
-import android.graphics.Bitmap
-import android.graphics.Canvas
-import android.graphics.Color
-import android.graphics.Paint
-import android.graphics.Point
-import android.graphics.RectF
-import android.view.MotionEvent
-import android.view.ScaleGestureDetector
-import android.view.View
-import kotlin.math.max
-import kotlin.math.min
-
-internal class WallpaperCropView(context: Context, private val displaySize: Point) : View(context) {
- private var bitmap: Bitmap? = null
- private val paint = Paint(Paint.ANTI_ALIAS_FLAG or Paint.FILTER_BITMAP_FLAG)
- private val frame = RectF()
- private var zoom = 1f
- private var centerX = 0.5f
- private var centerY = 0.5f
- private var lastX = 0f
- private var lastY = 0f
- private val gestures = ScaleGestureDetector(context,
- object : ScaleGestureDetector.SimpleOnScaleGestureListener() {
- override fun onScale(detector: ScaleGestureDetector): Boolean {
- val image = bitmap ?: return false
- val before = scale(image)
- zoom = (zoom * detector.scaleFactor).coerceIn(1f, 4f)
- val after = scale(image)
- centerX += (detector.focusX - frame.centerX()) * (1 / before - 1 / after) / image.width
- centerY += (detector.focusY - frame.centerY()) * (1 / before - 1 / after) / image.height
- constrain()
- invalidate()
- return true
- }
- },
- )
-
- fun setImage(image: Bitmap) {
- bitmap = image
- constrain()
- invalidate()
- }
-
- fun saveCrop() = floatArrayOf(zoom, centerX, centerY)
-
- fun restoreCrop(crop: FloatArray?) {
- if (crop == null) return
- zoom = crop[0]
- centerX = crop[1]
- centerY = crop[2]
- }
-
- fun selection(): Crop {
- val image = checkNotNull(bitmap)
- val scale = scale(image)
- val halfWidth = frame.width() / (2 * scale * image.width)
- val halfHeight = frame.height() / (2 * scale * image.height)
- return Crop(RectF(centerX - halfWidth, centerY - halfHeight, centerX + halfWidth, centerY + halfHeight), displaySize)
- }
-
- fun release() {
- bitmap?.recycle()
- bitmap = null
- }
-
- override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
- val fit = min(w.toFloat() / displaySize.x, h.toFloat() / displaySize.y)
- val frameWidth = displaySize.x * fit
- val frameHeight = displaySize.y * fit
- frame.set((w - frameWidth) / 2, (h - frameHeight) / 2, (w + frameWidth) / 2, (h + frameHeight) / 2)
- constrain()
- }
-
- override fun onDraw(canvas: Canvas) {
- canvas.drawColor(Color.BLACK)
- canvas.save()
- canvas.clipRect(frame)
- drawImage(canvas)
- canvas.restore()
- }
-
- private fun drawImage(canvas: Canvas) {
- val image = bitmap ?: return
- canvas.translate(frame.centerX(), frame.centerY())
- val scale = scale(image)
- canvas.scale(scale, scale)
- canvas.drawBitmap(image, -centerX * image.width, -centerY * image.height, paint)
- }
-
- override fun onTouchEvent(event: MotionEvent): Boolean {
- val image = bitmap ?: return false
- if (!isEnabled) return false
- gestures.onTouchEvent(event)
- when (event.actionMasked) {
- MotionEvent.ACTION_MOVE -> {
- if (!gestures.isInProgress && event.pointerCount == 1) {
- val scale = scale(image)
- centerX -= (event.x - lastX) / (scale * image.width)
- centerY -= (event.y - lastY) / (scale * image.height)
- constrain()
- invalidate()
- }
- }
- MotionEvent.ACTION_UP -> performClick()
- }
- val pointer = if (event.actionMasked == MotionEvent.ACTION_POINTER_UP && event.actionIndex == 0) 1 else 0
- lastX = event.getX(pointer)
- lastY = event.getY(pointer)
- return true
- }
-
- override fun performClick(): Boolean {
- super.performClick()
- return true
- }
-
- private fun constrain() {
- val image = bitmap ?: return
- if (frame.isEmpty) return
- val scale = scale(image)
- val halfWidth = min(0.5f, frame.width() / (2 * scale * image.width))
- val halfHeight = min(0.5f, frame.height() / (2 * scale * image.height))
- centerX = centerX.coerceIn(halfWidth, 1 - halfWidth)
- centerY = centerY.coerceIn(halfHeight, 1 - halfHeight)
- }
-
- private fun scale(image: Bitmap) = max(frame.width() / image.width, frame.height() / image.height) * zoom
-
-}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperService.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperService.kt
index 215c6eab0e..8bc3403791 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperService.kt
+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperService.kt
@@ -13,15 +13,14 @@ import android.graphics.RectF
import android.net.Uri
import android.os.Build
import androidx.exifinterface.media.ExifInterface
-import io.ente.photos.platform.R
import java.io.IOException
import kotlin.math.max
import kotlin.math.min
-internal enum class Destination(val label: Int, val flags: Int) {
- HOME(R.string.wallpaper_home, WallpaperManager.FLAG_SYSTEM),
- LOCK(R.string.wallpaper_lock, WallpaperManager.FLAG_LOCK),
- BOTH(R.string.wallpaper_both, WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK),
+internal enum class Destination(val flags: Int) {
+ HOME(WallpaperManager.FLAG_SYSTEM),
+ LOCK(WallpaperManager.FLAG_LOCK),
+ BOTH(WallpaperManager.FLAG_SYSTEM or WallpaperManager.FLAG_LOCK),
}
@android.annotation.TargetApi(24)
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperSession.kt b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperSession.kt
new file mode 100644
index 0000000000..26ce1649fe
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/kotlin/io/ente/photos/platform/wallpaper/WallpaperSession.kt
@@ -0,0 +1,42 @@
+package io.ente.photos.platform.wallpaper
+
+import android.content.ContentResolver
+import android.content.Context
+import android.graphics.Bitmap
+import android.graphics.Point
+import android.graphics.RectF
+import android.net.Uri
+import java.io.ByteArrayOutputStream
+import java.util.concurrent.CompletableFuture
+import java.util.concurrent.Executors
+
+internal class WallpaperSession(context: Context, private val uri: Uri?, private val size: Point) : AutoCloseable {
+ private val service = WallpaperService(context.applicationContext)
+ private val executor = Executors.newSingleThreadExecutor()
+
+ fun preview(): CompletableFuture<ByteArray> = CompletableFuture.supplyAsync({
+ require(uri?.scheme == ContentResolver.SCHEME_CONTENT) { "Expected an image content URI" }
+ if (!service.isAvailable) throw UnsupportedOperationException("Wallpaper changes are not allowed")
+ val bitmap = service.decode(requireNotNull(uri), size)
+ try {
+ ByteArrayOutputStream().use {
+ bitmap.compress(Bitmap.CompressFormat.PNG, 100, it)
+ it.toByteArray()
+ }
+ } finally {
+ bitmap.recycle()
+ }
+ }, executor)
+
+ fun apply(region: RectF, destination: Destination): CompletableFuture<Unit> = CompletableFuture.supplyAsync({
+ val bitmap = service.render(requireNotNull(uri), Crop(region, size))
+ try {
+ service.apply(bitmap, destination)
+ } finally {
+ bitmap.recycle()
+ }
+ }, executor)
+
+ override fun close() { executor.shutdown() }
+}
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/drawable/wallpaper_close.xml b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/drawable/wallpaper_close.xml
deleted file mode 100644
index 4ef9633150..0000000000
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/drawable/wallpaper_close.xml
+++ /dev/null
@@ -1,11 +0,0 @@
-<vector xmlns:android="http://schemas.android.com/apk/res/android"
- android:width="20dp"
- android:height="20dp"
- android:viewportWidth="24"
- android:viewportHeight="24">
- <path
- android:pathData="M6,6 L18,18 M18,6 L6,18"
- android:strokeColor="#FFFFFF"
- android:strokeWidth="1.8"
- android:strokeLineCap="round" />
-</vector>
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/values/wallpaper.xml b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/values/wallpaper.xml
index 3f488fed7a..75562a0e10 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/values/wallpaper.xml
+++ b/mobile/apps/photos/plugins/ente_photos_platform/android/src/main/res/values/wallpaper.xml
@@ -1,4 +1,5 @@
<resources>
+ <string name="wallpaper">Wallpaper</string>
<style name="WallpaperTheme" parent="android:style/Theme.Material.NoActionBar">
<item name="android:colorAccent">#08C225</item>
<item name="android:windowBackground">#000000</item>
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart b/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart
index 1228810475..3399653f2a 100644
--- a/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart
+++ b/mobile/apps/photos/plugins/ente_photos_platform/lib/ente_photos_platform.dart
@@ -2,3 +2,4 @@ export 'src/country_names.dart';
export 'src/device_health.dart';
export 'src/device_trash.dart';
export 'src/process_lock.dart';
+export 'src/wallpaper.dart';
diff --git a/mobile/apps/photos/plugins/ente_photos_platform/lib/src/wallpaper.dart b/mobile/apps/photos/plugins/ente_photos_platform/lib/src/wallpaper.dart
new file mode 100644
index 0000000000..c4370c7511
--- /dev/null
+++ b/mobile/apps/photos/plugins/ente_photos_platform/lib/src/wallpaper.dart
@@ -0,0 +1,34 @@
+import 'package:flutter/services.dart';
+
+enum WallpaperDestination { home, lock, both }
+
+class WallpaperPreview {
+ const WallpaperPreview(this.bytes, this.size);
+
+ final Uint8List bytes;
+ final Size size;
+}
+
+class WallpaperClient {
+ static const _channel = MethodChannel('io.ente.photos.platform/wallpaper');
+
+ Future<WallpaperPreview> prepare() async {
+ final result = (await _channel.invokeMapMethod<String, dynamic>(
+ 'prepare',
+ ))!;
+ return WallpaperPreview(
+ result['bytes'] as Uint8List,
+ Size(
+ (result['width'] as int).toDouble(),
+ (result['height'] as int).toDouble(),
+ ),
+ );
+ }
+
+ Future<void> apply(Rect region, WallpaperDestination destination) {
+ return _channel.invokeMethod('apply', {
+ 'region': [region.left, region.top, region.right, region.bottom],
+ 'destination': destination.name,
+ });
+ }
+}
diff --git a/mobile/packages/strings/README.md b/mobile/packages/strings/README.md
index 0644dc0170..9dabe78402 100644
--- a/mobile/packages/strings/README.md
+++ b/mobile/packages/strings/README.md
@@ -2,8 +2,6 @@
This package contains the user-facing strings and translations shared by the Auth, Locker, and Photos apps. Flutter's localization generator turns the ARB files in `lib/l10n/arb` into the Dart files in `lib/l10n`.
-Native Android strings live in `android/values/`. Crowdin syncs their translations into `android/values-<locale>/`; Android modules include this resource directory directly.
-
## Translate
The strings can be translated in the [Ente Mobile Crowdin project](https://crowdin.com/project/ente-photos-app).
diff --git a/mobile/packages/strings/android/values/wallpaper.xml b/mobile/packages/strings/android/values/wallpaper.xml
deleted file mode 100644
index cec697968c..0000000000
--- a/mobile/packages/strings/android/values/wallpaper.xml
+++ /dev/null
@@ -1,10 +0,0 @@
-<resources>
- <string name="wallpaper">Wallpaper</string>
- <string name="wallpaper_set">Set wallpaper</string>
- <string name="wallpaper_home">Home screen</string>
- <string name="wallpaper_lock">Lock screen</string>
- <string name="wallpaper_both">Home and lock screens</string>
- <string name="wallpaper_done">Wallpaper set</string>
- <string name="wallpaper_failed">Could not set wallpaper</string>
- <string name="wallpaper_unavailable">Wallpaper changes are not allowed on this device</string>
-</resources>
diff --git a/mobile/packages/strings/crowdin.yml b/mobile/packages/strings/crowdin.yml
index 38b81f333f..1c8bf94cc6 100644
--- a/mobile/packages/strings/crowdin.yml
+++ b/mobile/packages/strings/crowdin.yml
@@ -77,6 +77,3 @@ files:
ur-IN: ur
zh-CN: zh_CN
zh-TW: zh_TW
- - source: /android/values/wallpaper.xml
- translation: /android/values-%android_code%/wallpaper.xml
- type: android
diff --git a/mobile/packages/strings/lib/l10n/arb/strings_en.arb b/mobile/packages/strings/lib/l10n/arb/strings_en.arb
index a72d30a396..2947fb101d 100644
--- a/mobile/packages/strings/lib/l10n/arb/strings_en.arb
+++ b/mobile/packages/strings/lib/l10n/arb/strings_en.arb
@@ -1,4 +1,12 @@
{
+ "wallpaper": "Wallpaper",
+ "setWallpaper": "Set wallpaper",
+ "wallpaperHome": "Home screen",
+ "wallpaperLock": "Lock screen",
+ "wallpaperBoth": "Home and lock screens",
+ "wallpaperSet": "Wallpaper set",
+ "wallpaperFailed": "Could not set wallpaper",
+ "wallpaperUnavailable": "Wallpaper changes are not allowed on this device",
"about": "About",
"acceptTrustInvite": "Accept invite",
"account": "Account",