π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Remember Auth window placement on Windows
Neeraj Gupta94e362470637
diff --git a/mobile/apps/auth/changes/windows-window-placement.md b/mobile/apps/auth/changes/windows-window-placement.mdnew file mode 100644index 0000000000..8c74bca6ba--- /dev/null+++ b/mobile/apps/auth/changes/windows-window-placement.md@@ -0,0 +1 @@+- Remember the window position and normal size on Windows, including when reopening maximized.diff --git a/mobile/apps/auth/lib/main.dart b/mobile/apps/auth/lib/main.dartindex 17d823df91..825df03b28 100644--- a/mobile/apps/auth/lib/main.dart+++ b/mobile/apps/auth/lib/main.dart@@ -115,11 +115,14 @@ void main() async {bool isMaximized = WindowListenerService.instance.getIsMaximized();await windowManager.waitUntilReadyToShow(windowOptions, () async {await auth_dir_utils.DirectoryUtils.migrateNamingChanges();+ isMaximized = await WindowListenerService.instance+ .restoreWindowPlacement(isMaximized);await windowManager.show();if (isMaximized) {await windowManager.maximize();}await windowManager.focus();+ await WindowListenerService.instance.finishWindowRestore();initSystemTray().ignore();});}diff --git a/mobile/apps/auth/lib/services/window_listener_service.dart b/mobile/apps/auth/lib/services/window_listener_service.dartindex 8ca0fad368..7ccd6aeb04 100644--- a/mobile/apps/auth/lib/services/window_listener_service.dart+++ b/mobile/apps/auth/lib/services/window_listener_service.dart@@ -2,6 +2,7 @@ import 'dart:async';import 'dart:io';import 'package:ente_auth/services/preference_service.dart';+import 'package:ente_auth/services/windows_window_placement.dart';import 'package:flutter/widgets.dart';import 'package:screen_retriever/screen_retriever.dart';import 'package:shared_preferences/shared_preferences.dart';@@ -18,6 +19,7 @@ class WindowListenerService with WindowListener, TrayListener {static const double maxWindowHeight = 8192.0;static const double maxWindowWidth = 8192.0;late SharedPreferences _preferences;+ WindowsWindowPlacement? _windowsPlacement;bool _isListening = false;bool _isQuitting = false;bool _isOneOffWindowed = false;@@ -32,6 +34,9 @@ class WindowListenerService with WindowListener, TrayListener {Future<void> init() async {_preferences = await SharedPreferences.getInstance();+ if (Platform.isWindows) {+ _windowsPlacement ??= WindowsWindowPlacement(_preferences);+ }// Snapshot at launch: toggling the setting mid-session persists the pref// but must not reroute window behavior until restart, since the// startup-only window setup (title bar, size, activation policy) only@@ -71,12 +76,34 @@ class WindowListenerService with WindowListener, TrayListener {return _preferences.getBool('is_maximized') ?? initialIsMaximized;}+ Future<bool> restoreWindowPlacement(bool wasMaximized) async {+ return await _windowsPlacement?.restore(_savedWindowSize(), wasMaximized) ??+ wasMaximized;+ }++ Future<void> finishWindowRestore() async {+ await _windowsPlacement?.startSaving();+ }+@overridevoid onWindowResize() {+ if (_windowsPlacement != null) return;if (isMenubarMode() && !_isOneOffWindowed) return;unawaited(_saveWindowSize());}+ @override+ void onWindowMoved() => unawaited(_windowsPlacement?.save());++ @override+ void onWindowResized() => unawaited(_windowsPlacement?.save());++ @override+ void onWindowMinimize() => unawaited(_windowsPlacement?.save());++ @override+ void onWindowRestore() => unawaited(_windowsPlacement?.save());+Future<void> _saveWindowSize() async {final width = (await windowManager.getSize()).width;final height = (await windowManager.getSize()).height;@@ -86,11 +113,19 @@ class WindowListenerService with WindowListener, TrayListener {@overridevoid onWindowMaximize() {+ if (_windowsPlacement != null) {+ unawaited(_windowsPlacement!.save(maximized: true));+ return;+ }unawaited(_preferences.setBool('is_maximized', true));}@overridevoid onWindowUnmaximize() {+ if (_windowsPlacement != null) {+ unawaited(_windowsPlacement!.save(maximized: false));+ return;+ }unawaited(_preferences.setBool('is_maximized', false));}@@ -259,6 +294,7 @@ class WindowListenerService with WindowListener, TrayListener {}Future<void> _hideWindow() async {+ await _windowsPlacement?.save();await windowManager.hide();if (isMenubarMode()) {if (_isOneOffWindowed) {@@ -322,6 +358,7 @@ class WindowListenerService with WindowListener, TrayListener {_isQuitting = true;if (Platform.isWindows) {+ await _windowsPlacement?.save();final int hProcess = GetCurrentProcess();try {await trayManager.destroy();diff --git a/mobile/apps/auth/lib/services/window_placement.dart b/mobile/apps/auth/lib/services/window_placement.dartnew file mode 100644index 0000000000..1c6e028a5d--- /dev/null+++ b/mobile/apps/auth/lib/services/window_placement.dart@@ -0,0 +1,100 @@+import 'dart:ui';++Rect readRect(Map<dynamic, dynamic> json) {+ final values = [+ 'x',+ 'y',+ 'width',+ 'height',+ ].map((key) => (json[key] as num).toDouble()).toList();+ if (values.any((v) => !v.isFinite) || values[2] <= 0 || values[3] <= 0) {+ throw const FormatException('Invalid window rectangle');+ }+ return Rect.fromLTWH(values[0], values[1], values[2], values[3]);+}++Map<String, double> rectJson(Rect rect) => {+ 'x': rect.left,+ 'y': rect.top,+ 'width': rect.width,+ 'height': rect.height,+};++class Monitor {+ const Monitor(this.id, this.workArea, this.scale, {this.primary = false});+ final String id;+ final Rect workArea;+ final double scale;+ final bool primary;+ factory Monitor.fromJson(Map<dynamic, dynamic> json) => Monitor(+ json['id'] as String,+ readRect(json['workArea'] as Map),+ (json['dpi'] as num) / 96,+ primary: json['primary'] as bool,+ );+}++class Placement {+ const Placement(this.monitorId, this.logicalBounds, this.maximized);+ final String monitorId;+ final Rect logicalBounds;+ final bool maximized;+ factory Placement.fromJson(Map<String, dynamic> json) => Placement(+ json['monitorId'] as String,+ readRect(json['logicalBounds'] as Map),+ json['maximized'] as bool,+ );+ Map<String, dynamic> toJson() => {+ 'monitorId': monitorId,+ 'logicalBounds': rectJson(logicalBounds),+ 'maximized': maximized,+ };+}++Rect fitToWorkArea(Rect bounds, Rect workArea) {+ final width = bounds.width.clamp(1.0, workArea.width);+ final height = bounds.height.clamp(1.0, workArea.height);+ return Rect.fromLTWH(+ bounds.left.clamp(workArea.left, workArea.right - width),+ bounds.top.clamp(workArea.top, workArea.bottom - height),+ width,+ height,+ );+}++Rect restoreBounds(+ Placement? placement,+ List<Monitor> monitors,+ Size fallbackSize,+) {+ if (monitors.isEmpty) throw StateError('No monitors reported');+ final monitor = monitors.firstWhere(+ (m) => m.id == placement?.monitorId,+ orElse: () =>+ monitors.firstWhere((m) => m.primary, orElse: () => monitors.first),+ );+ final logical =+ placement?.logicalBounds ??+ Rect.fromLTWH(70, 70, fallbackSize.width, fallbackSize.height);+ return fitToWorkArea(+ Rect.fromLTWH(+ monitor.workArea.left + logical.left * monitor.scale,+ monitor.workArea.top + logical.top * monitor.scale,+ logical.width * monitor.scale,+ logical.height * monitor.scale,+ ),+ monitor.workArea,+ );+}++Placement captureBounds(Rect bounds, Monitor monitor, bool maximized) =>+ Placement(+ monitor.id,+ Rect.fromLTWH(+ (bounds.left - monitor.workArea.left) / monitor.scale,+ (bounds.top - monitor.workArea.top) / monitor.scale,+ bounds.width / monitor.scale,+ bounds.height / monitor.scale,+ ),+ maximized,+ );diff --git a/mobile/apps/auth/lib/services/windows_window_placement.dart b/mobile/apps/auth/lib/services/windows_window_placement.dartnew file mode 100644index 0000000000..1ec66164df--- /dev/null+++ b/mobile/apps/auth/lib/services/windows_window_placement.dart@@ -0,0 +1,83 @@+import 'dart:convert';++import 'package:ente_auth/services/window_placement.dart';+import 'package:ente_logging/logging.dart';+import 'package:flutter/services.dart';+import 'package:shared_preferences/shared_preferences.dart';++class WindowsWindowPlacement {+ WindowsWindowPlacement(this._preferences);++ static const _channel = MethodChannel('io.ente.auth/window_geometry');+ static const _key = 'windowsWindowPlacement';+ final SharedPreferences _preferences;+ final _logger = Logger('WindowsWindowPlacement');+ Future<void> _pending = Future.value();+ bool _ready = false;+ bool _maximized = false;++ Future<bool> restore(Size fallbackSize, bool fallbackMaximized) async {+ Placement? saved;+ try {+ final json = _preferences.getString(_key);+ if (json != null) {+ saved = Placement.fromJson(jsonDecode(json) as Map<String, dynamic>);+ }+ } catch (error, stack) {+ _logger.warning('Ignoring invalid window placement', error, stack);+ }+ _maximized = saved?.maximized ?? fallbackMaximized;+ try {+ final snapshot = (await _channel.invokeMapMethod<String, dynamic>(+ 'snapshot',+ ))!;+ final monitors = (snapshot['monitors'] as List)+ .map((m) => Monitor.fromJson(m as Map))+ .toList();+ await _channel.invokeMethod<void>(+ 'setBounds',+ rectJson(restoreBounds(saved, monitors, fallbackSize)),+ );+ } catch (error, stack) {+ _logger.warning('Could not restore window placement', error, stack);+ }+ return _maximized;+ }++ Future<void> startSaving() {+ _ready = true;+ return save();+ }++ Future<void> save({bool? maximized}) {+ if (!_ready) return Future.value();+ _pending = _pending+ .then((_) async {+ _maximized = maximized ?? _maximized;+ final snapshot = (await _channel.invokeMapMethod<String, dynamic>(+ 'snapshot',+ ))!;+ if (!(snapshot['minimized'] as bool)) {+ _maximized = snapshot['maximized'] as bool;+ }+ final monitor = (snapshot['monitors'] as List)+ .map((m) => Monitor.fromJson(m as Map))+ .firstWhere((m) => m.id == snapshot['normalMonitorId']);+ final placement = captureBounds(+ readRect(snapshot['normalBounds'] as Map),+ monitor,+ _maximized,+ );+ if (!await _preferences.setString(+ _key,+ jsonEncode(placement.toJson()),+ )) {+ throw StateError('Could not persist window placement');+ }+ })+ .catchError((Object error, StackTrace stack) {+ _logger.warning('Could not save window placement', error, stack);+ });+ return _pending;+ }+}diff --git a/mobile/apps/auth/test/services/window_placement_test.dart b/mobile/apps/auth/test/services/window_placement_test.dartnew file mode 100644index 0000000000..5b3822bee4--- /dev/null+++ b/mobile/apps/auth/test/services/window_placement_test.dart@@ -0,0 +1,85 @@+import 'dart:convert';+import 'dart:ui';++import 'package:ente_auth/services/window_placement.dart';+import 'package:flutter_test/flutter_test.dart';++void main() {+ const primary = Monitor(+ 'primary',+ Rect.fromLTWH(0, 0, 1920, 1040),+ 1,+ primary: true,+ );+ const normal = Placement('primary', Rect.fromLTWH(180, 150, 500, 420), false);+ test('normal bounds survive serialization and restart', () {+ final decoded = Placement.fromJson(jsonDecode(jsonEncode(normal.toJson())));+ expect(+ restoreBounds(decoded, [primary], const Size(800, 1200)),+ normal.logicalBounds,+ );+ });+ for (final area in const [+ Rect.fromLTWH(0, 48, 1920, 1032),+ Rect.fromLTWH(0, 0, 1920, 1032),+ Rect.fromLTWH(48, 0, 1872, 1080),+ Rect.fromLTWH(0, 0, 1872, 1080),+ ]) {+ test('oversized defaults fit taskbar work area $area', () {+ final restored = restoreBounds(null, [+ Monitor('primary', area, 1, primary: true),+ ], const Size(800, 1200));+ expect(restored.top, greaterThanOrEqualTo(area.top));+ expect(restored.bottom, lessThanOrEqualTo(area.bottom));+ expect(restored.left, greaterThanOrEqualTo(area.left));+ expect(restored.right, lessThanOrEqualTo(area.right));+ });+ }+ test('secondary monitor with negative origin restores in its own scale', () {+ const secondary = Monitor(+ 'second',+ Rect.fromLTWH(-2560, 60, 2560, 1380),+ 1.5,+ );+ const bounds = Rect.fromLTWH(-2260, 210, 750, 630);+ final saved = captureBounds(bounds, secondary, false);+ expect(+ restoreBounds(saved, [primary, secondary], const Size(800, 1200)),+ bounds,+ );+ });+ test(+ 'DPI and monitor-layout changes retain logical size and local offset',+ () {+ const moved = Monitor(+ 'primary',+ Rect.fromLTWH(1920, 80, 2560, 1360),+ 2,+ primary: true,+ );+ expect(+ restoreBounds(normal, [moved], const Size(800, 1200)),+ const Rect.fromLTWH(2280, 380, 1000, 840),+ );+ },+ );+ test('removed monitor falls back to primary and fits its work area', () {+ const lost = Placement(+ 'removed',+ Rect.fromLTWH(2000, 2000, 3000, 2000),+ false,+ );+ expect(+ restoreBounds(lost, [primary], const Size(800, 1200)),+ primary.workArea,+ );+ });+ test('invalid persisted geometry is rejected', () {+ for (final invalid in [double.nan, double.infinity, -1.0, 0.0]) {+ expect(+ () => readRect({'x': 0, 'y': 0, 'width': invalid, 'height': 400}),+ throwsFormatException,+ );+ }+ });+}diff --git a/mobile/apps/auth/test/services/windows_window_placement_test.dart b/mobile/apps/auth/test/services/windows_window_placement_test.dartnew file mode 100644index 0000000000..83c99d0a4e--- /dev/null+++ b/mobile/apps/auth/test/services/windows_window_placement_test.dart@@ -0,0 +1,163 @@+import 'dart:async';+import 'dart:convert';++import 'package:ente_auth/services/window_placement.dart';+import 'package:ente_auth/services/windows_window_placement.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:shared_preferences/shared_preferences.dart';++void main() {+ TestWidgetsFlutterBinding.ensureInitialized();+ const channel = MethodChannel('io.ente.auth/window_geometry');+ const key = 'windowsWindowPlacement';+ const size = Size(500, 420);+ const normal = Rect.fromLTWH(180, 150, 500, 420);+ final messenger =+ TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;+ late SharedPreferences preferences;+ late WindowsWindowPlacement placement;+ late Map<String, dynamic> snapshot;+ Rect? restored;+ var captures = 0;+ var fail = false;+ Completer<void>? blocked;++ setUp(() async {+ SharedPreferences.setMockInitialValues({});+ preferences = await SharedPreferences.getInstance();+ placement = WindowsWindowPlacement(preferences);+ restored = null;+ captures = 0;+ fail = false;+ blocked = null;+ snapshot = {+ 'normalBounds': rectJson(normal),+ 'normalMonitorId': 'primary',+ 'maximized': false,+ 'minimized': false,+ 'monitors': [+ {+ 'id': 'primary',+ 'workArea': rectJson(const Rect.fromLTWH(0, 0, 1920, 1040)),+ 'dpi': 96,+ 'primary': true,+ },+ ],+ };+ messenger.setMockMethodCallHandler(channel, (call) async {+ if (call.method == 'snapshot') {+ captures++;+ if (fail) throw PlatformException(code: 'test-failure');+ await blocked?.future;+ return snapshot;+ }+ if (call.method == 'setBounds') {+ restored = readRect(call.arguments as Map);+ }+ return null;+ });+ });++ tearDown(() {+ messenger.setMockMethodCallHandler(channel, null);+ });++ Placement saved() => Placement.fromJson(+ jsonDecode(preferences.getString(key)!) as Map<String, dynamic>,+ );++ test('restores the saved normal bounds and maximized state', () async {+ await preferences.setString(+ key,+ jsonEncode(const Placement('primary', normal, true).toJson()),+ );+ expect(await placement.restore(size, false), isTrue);+ expect(restored, normal);+ });++ test(+ 'first launch retains the legacy size and maximized preference',+ () async {+ expect(await placement.restore(size, true), isTrue);+ expect(restored, const Rect.fromLTWH(70, 70, 500, 420));+ },+ );++ test('invalid stored data uses the legacy defaults', () async {+ await preferences.setString(key, '{broken');+ expect(await placement.restore(size, false), isFalse);+ expect(restored?.size, size);+ });++ test('startup events cannot overwrite saved placement', () async {+ await placement.save(maximized: true);+ await placement.restore(size, false);+ await placement.save();+ expect(captures, 1);+ expect(preferences.getString(key), isNull);+ await placement.startSaving();+ expect(saved().logicalBounds, normal);+ });++ test('maximized capture reads the current native normal rectangle', () async {+ await placement.startSaving();+ const moved = Rect.fromLTWH(300, 180, 460, 380);+ snapshot['normalBounds'] = rectJson(moved);+ snapshot['maximized'] = true;+ await placement.save(maximized: true);+ expect(saved().logicalBounds, moved);+ expect(saved().maximized, isTrue);+ });++ test(+ 'rapid maximize then minimize keeps the latest normal bounds and state',+ () async {+ await placement.startSaving();+ const moved = Rect.fromLTWH(300, 180, 460, 380);+ snapshot['normalBounds'] = rectJson(moved);+ snapshot['minimized'] = true;+ final maximize = placement.save(maximized: true);+ final minimize = placement.save();+ await Future.wait([maximize, minimize]);+ expect(saved().logicalBounds, moved);+ expect(saved().maximized, isTrue);+ snapshot['minimized'] = false;+ await placement.save(maximized: false);+ expect(saved().maximized, isFalse);+ },+ );++ test('a failed capture does not block a later save', () async {+ fail = true;+ await placement.startSaving();+ expect(preferences.getString(key), isNull);+ fail = false;+ await placement.save();+ expect(saved().logicalBounds, normal);+ });++ test('a failed capture retains state events before minimizing', () async {+ await placement.startSaving();+ fail = true;+ await placement.save(maximized: true);+ fail = false;+ snapshot['minimized'] = true;+ await placement.save();+ expect(saved().maximized, isTrue);+ });++ test('the final save waits for earlier captures and persistence', () async {+ await placement.startSaving();+ final initialCaptures = captures;+ blocked = Completer<void>();+ final first = placement.save();+ final flush = placement.save();+ await Future<void>.delayed(Duration.zero);+ expect(captures, initialCaptures + 1);+ blocked!.complete();+ await Future.wait([first, flush]);+ expect(captures, initialCaptures + 2);+ expect(saved().logicalBounds, normal);+ });+}diff --git a/mobile/apps/auth/windows/runner/CMakeLists.txt b/mobile/apps/auth/windows/runner/CMakeLists.txtindex 779b9bde5e..b52934439d 100644--- a/mobile/apps/auth/windows/runner/CMakeLists.txt+++ b/mobile/apps/auth/windows/runner/CMakeLists.txt@@ -6,6 +6,8 @@ add_executable(${BINARY_NAME} WIN32"main.cpp""utils.cpp""win32_window.cpp"+ "window_geometry.cpp"+ "window_geometry_channel.cpp""${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc""Runner.rc""runner.exe.manifest"@@ -23,7 +25,7 @@ target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTtarget_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)-target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")+target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib" "shcore.lib")target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")add_dependencies(${BINARY_NAME} flutter_assemble)diff --git a/mobile/apps/auth/windows/runner/flutter_window.cpp b/mobile/apps/auth/windows/runner/flutter_window.cppindex 385644274c..6eeae7a888 100644--- a/mobile/apps/auth/windows/runner/flutter_window.cpp+++ b/mobile/apps/auth/windows/runner/flutter_window.cpp@@ -24,6 +24,8 @@ bool FlutterWindow::OnCreate() {return false;}RegisterPlugins(flutter_controller_->engine());+ geometry_channel_ = CreateWindowGeometryChannel(+ flutter_controller_->engine()->messenger(), GetHandle());SetChildContent(flutter_controller_->view()->GetNativeWindow());flutter_controller_->engine()->SetNextFrameCallback([&]() {@@ -40,6 +42,7 @@ bool FlutterWindow::OnCreate() {}void FlutterWindow::OnDestroy() {+ geometry_channel_.reset();if (flutter_controller_) {flutter_controller_ = nullptr;}diff --git a/mobile/apps/auth/windows/runner/flutter_window.h b/mobile/apps/auth/windows/runner/flutter_window.hindex d204fc4b5f..d44fc6426d 100644--- a/mobile/apps/auth/windows/runner/flutter_window.h+++ b/mobile/apps/auth/windows/runner/flutter_window.h@@ -7,6 +7,7 @@#include <memory>#include "win32_window.h"+#include "window_geometry_channel.h"class FlutterWindow : public Win32Window {public:@@ -23,6 +24,8 @@ class FlutterWindow : public Win32Window {flutter::DartProject project_;std::unique_ptr<flutter::FlutterViewController> flutter_controller_;+ std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>>+ geometry_channel_;};#endif // RUNNER_FLUTTER_WINDOW_H_diff --git a/mobile/apps/auth/windows/runner/window_geometry.cpp b/mobile/apps/auth/windows/runner/window_geometry.cppnew file mode 100644index 0000000000..2c6ee6c031--- /dev/null+++ b/mobile/apps/auth/windows/runner/window_geometry.cpp@@ -0,0 +1,103 @@+#include "window_geometry.h"++#include <shellscalingapi.h>++#include <algorithm>+#include <utility>++namespace window_geometry {+namespace {++std::optional<Monitor> ReadMonitor(HMONITOR handle) {+ MONITORINFOEXW info{};+ info.cbSize = sizeof(info);+ UINT dpi_x = 0;+ UINT dpi_y = 0;+ if (!GetMonitorInfoW(handle, &info) ||+ FAILED(GetDpiForMonitor(handle, MDT_EFFECTIVE_DPI, &dpi_x, &dpi_y)) ||+ dpi_x == 0) {+ return std::nullopt;+ }+ const int length = WideCharToMultiByte(CP_UTF8, 0, info.szDevice, -1, nullptr,+ 0, nullptr, nullptr);+ if (length == 0) return std::nullopt;+ std::string id(static_cast<size_t>(length), '\0');+ if (!WideCharToMultiByte(CP_UTF8, 0, info.szDevice, -1, id.data(), length,+ nullptr, nullptr)) {+ return std::nullopt;+ }+ id.pop_back();+ return Monitor{handle, std::move(id), info.rcWork, info.rcMonitor, dpi_x,+ (info.dwFlags & MONITORINFOF_PRIMARY) != 0};+}++BOOL CALLBACK AddMonitor(HMONITOR handle, HDC, LPRECT, LPARAM data) {+ auto monitor = ReadMonitor(handle);+ if (!monitor) return FALSE;+ auto* monitors = reinterpret_cast<std::vector<Monitor>*>(data);+ monitors->push_back(std::move(*monitor));+ return TRUE;+}++}++std::optional<Snapshot> Capture(HWND window) {+ Snapshot snapshot{};+ WINDOWPLACEMENT placement{};+ placement.length = sizeof(placement);+ if (!GetWindowRect(window, &snapshot.normal_bounds) ||+ !GetWindowPlacement(window, &placement)) {+ return std::nullopt;+ }+ if (!EnumDisplayMonitors(nullptr, nullptr, AddMonitor,+ reinterpret_cast<LPARAM>(&snapshot.monitors))) {+ return std::nullopt;+ }+ const auto current_handle =+ MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST);+ const auto current = std::find_if(+ snapshot.monitors.begin(), snapshot.monitors.end(),+ [current_handle](const Monitor& monitor) {+ return monitor.handle == current_handle;+ });+ if (current == snapshot.monitors.end()) return std::nullopt;+ snapshot.maximized = placement.showCmd == SW_SHOWMAXIMIZED;+ snapshot.minimized = placement.showCmd == SW_SHOWMINIMIZED;+ if (snapshot.maximized || snapshot.minimized) {+ snapshot.normal_bounds = placement.rcNormalPosition;+ SetLastError(ERROR_SUCCESS);+ const auto style = GetWindowLongPtrW(window, GWL_EXSTYLE);+ if (style == 0 && GetLastError() != ERROR_SUCCESS) return std::nullopt;+ if ((style & WS_EX_TOOLWINDOW) == 0) {+ OffsetRect(&snapshot.normal_bounds,+ current->work_area.left - current->screen.left,+ current->work_area.top - current->screen.top);+ }+ }+ const auto normal_handle =+ MonitorFromRect(&snapshot.normal_bounds, MONITOR_DEFAULTTONEAREST);+ const auto normal = std::find_if(+ snapshot.monitors.begin(), snapshot.monitors.end(),+ [normal_handle](const Monitor& monitor) {+ return monitor.handle == normal_handle;+ });+ if (normal == snapshot.monitors.end()) return std::nullopt;+ snapshot.normal_monitor_id = normal->id;+ return snapshot;+}++bool SetBounds(HWND window, const RECT& bounds) {+ for (int attempt = 0; attempt < 2; ++attempt) {+ if (!SetWindowPos(window, nullptr, bounds.left, bounds.top,+ bounds.right - bounds.left, bounds.bottom - bounds.top,+ SWP_NOZORDER | SWP_NOACTIVATE)) {+ return false;+ }+ RECT actual{};+ if (!GetWindowRect(window, &actual)) return false;+ if (EqualRect(&actual, &bounds)) return true;+ }+ return false;+}++}diff --git a/mobile/apps/auth/windows/runner/window_geometry.h b/mobile/apps/auth/windows/runner/window_geometry.hnew file mode 100644index 0000000000..18bba31783--- /dev/null+++ b/mobile/apps/auth/windows/runner/window_geometry.h@@ -0,0 +1,34 @@+#ifndef RUNNER_WINDOW_GEOMETRY_H_+#define RUNNER_WINDOW_GEOMETRY_H_++#include <windows.h>++#include <optional>+#include <string>+#include <vector>++namespace window_geometry {++struct Monitor {+ HMONITOR handle;+ std::string id;+ RECT work_area;+ RECT screen;+ UINT dpi;+ bool primary;+};++struct Snapshot {+ RECT normal_bounds;+ std::string normal_monitor_id;+ bool maximized;+ bool minimized;+ std::vector<Monitor> monitors;+};++std::optional<Snapshot> Capture(HWND window);+bool SetBounds(HWND window, const RECT& bounds);++}++#endifdiff --git a/mobile/apps/auth/windows/runner/window_geometry_channel.cpp b/mobile/apps/auth/windows/runner/window_geometry_channel.cppnew file mode 100644index 0000000000..a64efc4e9c--- /dev/null+++ b/mobile/apps/auth/windows/runner/window_geometry_channel.cpp@@ -0,0 +1,65 @@+#include "window_geometry_channel.h"++#include <flutter/standard_method_codec.h>++#include <cmath>++#include "window_geometry.h"++namespace {+using Value = flutter::EncodableValue;+using Map = flutter::EncodableMap;++Map Rectangle(const RECT& rect) {+ return {{Value("x"), Value(static_cast<double>(rect.left))},+ {Value("y"), Value(static_cast<double>(rect.top))},+ {Value("width"), Value(static_cast<double>(rect.right - rect.left))},+ {Value("height"), Value(static_cast<double>(rect.bottom - rect.top))}};+}+}++std::unique_ptr<flutter::MethodChannel<Value>> CreateWindowGeometryChannel(+ flutter::BinaryMessenger* messenger, HWND window) {+ auto channel = std::make_unique<flutter::MethodChannel<Value>>(+ messenger, "io.ente.auth/window_geometry",+ &flutter::StandardMethodCodec::GetInstance());+ channel->SetMethodCallHandler([window](const auto& call, auto result) {+ if (call.method_name() == "snapshot") {+ const auto snapshot = window_geometry::Capture(window);+ if (!snapshot) {+ result->Error("win32", "Cannot query window placement");+ return;+ }+ flutter::EncodableList monitors;+ for (const auto& monitor : snapshot->monitors) {+ monitors.emplace_back(Map{+ {Value("id"), Value(monitor.id)},+ {Value("workArea"), Value(Rectangle(monitor.work_area))},+ {Value("dpi"), Value(static_cast<int>(monitor.dpi))},+ {Value("primary"), Value(monitor.primary)}});+ }+ result->Success(Value(Map{+ {Value("normalBounds"), Value(Rectangle(snapshot->normal_bounds))},+ {Value("normalMonitorId"), Value(snapshot->normal_monitor_id)},+ {Value("maximized"), Value(snapshot->maximized)},+ {Value("minimized"), Value(snapshot->minimized)},+ {Value("monitors"), Value(monitors)}}));+ } else if (call.method_name() == "setBounds") {+ const auto& args = std::get<Map>(*call.arguments());+ const auto number = [&args](const char* key) {+ return std::lround(std::get<double>(args.at(Value(key))));+ };+ const LONG x = number("x");+ const LONG y = number("y");+ if (!window_geometry::SetBounds(+ window, RECT{x, y, x + number("width"), y + number("height")})) {+ result->Error("win32", "Cannot restore window placement");+ return;+ }+ result->Success();+ } else {+ result->NotImplemented();+ }+ });+ return channel;+}diff --git a/mobile/apps/auth/windows/runner/window_geometry_channel.h b/mobile/apps/auth/windows/runner/window_geometry_channel.hnew file mode 100644index 0000000000..61b806e0ae--- /dev/null+++ b/mobile/apps/auth/windows/runner/window_geometry_channel.h@@ -0,0 +1,12 @@+#ifndef RUNNER_WINDOW_GEOMETRY_CHANNEL_H_+#define RUNNER_WINDOW_GEOMETRY_CHANNEL_H_++#include <flutter/method_channel.h>+#include <windows.h>++#include <memory>++std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>>+CreateWindowGeometryChannel(flutter::BinaryMessenger* messenger, HWND window);++#endif