From b78e5f71756417bdcdafe022d6ebbc39e29d62d7 Mon Sep 17 00:00:00 2001 From: 21pages Date: Mon, 19 Jan 2026 21:08:43 +0800 Subject: [PATCH] wakelock Signed-off-by: 21pages --- flutter/lib/common.dart | 44 +++++++++++++------ .../desktop/pages/desktop_setting_page.dart | 17 ++++--- .../lib/mobile/pages/file_manager_page.dart | 6 +-- flutter/lib/mobile/pages/remote_page.dart | 11 ++--- .../lib/mobile/pages/view_camera_page.dart | 11 ++--- flutter/lib/models/server_model.dart | 26 +++++------ src/server/connection.rs | 27 +++++++++--- src/ui/index.tis | 10 +++++ 8 files changed, 93 insertions(+), 59 deletions(-) diff --git a/flutter/lib/common.dart b/flutter/lib/common.dart index 0097c1828..0650b1b5b 100644 --- a/flutter/lib/common.dart +++ b/flutter/lib/common.dart @@ -1578,7 +1578,7 @@ bool option2bool(String option, String value) { option == kOptionForceAlwaysRelay) { res = value == "Y"; } else { - assert(false); + // "" is true res = value != "N"; } return res; @@ -1596,9 +1596,6 @@ String bool2option(String option, bool b) { option == kOptionForceAlwaysRelay) { res = b ? 'Y' : defaultOptionNo; } else { - if (option != kOptionEnableUdpPunch && option != kOptionEnableIpv6Punch) { - assert(false); - } res = b ? 'Y' : 'N'; } return res; @@ -2684,23 +2681,44 @@ class SimpleWrapper { /// This manager handles multiple tabs within the same isolate. class WakelockManager { static final Set _enabledKeys = {}; + // Don't use WakelockPlus.enabled, it causes error on Android: + // Unhandled Exception: FormatException: Message corrupted + // + // On Linux, multiple enable() calls create only one inhibit, but each disable() + // only releases if _cookie != null. So we need our own _enabled state to avoid + // calling disable() when not enabled. + // See: https://github.com/fluttercommunity/wakelock_plus/blob/0c74e5bbc6aefac57b6c96bb7ef987705ed559ec/wakelock_plus/lib/src/wakelock_plus_linux_plugin.dart#L48 + static bool _enabled = false; - static void enable(UniqueKey key) { + static void enable(UniqueKey key, {bool isServer = false}) { // Check if we should keep awake during outgoing sessions - final keepAwake = mainGetLocalBoolOptionSync('keep-awake-during-outgoing-sessions'); - if (!keepAwake) { - return; // Don't enable wakelock if user disabled keep awake + if (!isServer) { + final keepAwake = + mainGetLocalBoolOptionSync(kOptionKeepAwakeDuringOutgoingSessions); + if (!keepAwake) { + return; // Don't enable wakelock if user disabled keep awake + } + } + if (isDesktop) { + _enabledKeys.add(key); + } + if (!_enabled) { + _enabled = true; + WakelockPlus.enable(); } - _enabledKeys.add(key); - WakelockPlus.enable(); } static void disable(UniqueKey key) { - if (_enabledKeys.remove(key)) { - if (_enabledKeys.isEmpty) { - WakelockPlus.disable(); + if (isDesktop) { + _enabledKeys.remove(key); + if (_enabledKeys.isNotEmpty) { + return; } } + if (_enabled) { + WakelockPlus.disable(); + _enabled = false; + } } } diff --git a/flutter/lib/desktop/pages/desktop_setting_page.dart b/flutter/lib/desktop/pages/desktop_setting_page.dart index 11b011f2b..b513bd4d9 100644 --- a/flutter/lib/desktop/pages/desktop_setting_page.dart +++ b/flutter/lib/desktop/pages/desktop_setting_page.dart @@ -559,12 +559,14 @@ class _GeneralState extends State<_General> { ]; // Add client-side wakelock option for desktop platforms - children.add(_OptionCheckBox( - context, - 'keep-awake-during-outgoing-sessions-label', - kOptionKeepAwakeDuringOutgoingSessions, - isServer: false, - )); + if (!bind.isIncomingOnly()) { + children.add(_OptionCheckBox( + context, + 'keep-awake-during-outgoing-sessions-label', + kOptionKeepAwakeDuringOutgoingSessions, + isServer: false, + )); + } if (!isWeb && bind.mainShowOption(key: kOptionAllowLinuxHeadless)) { children.add(_OptionCheckBox( @@ -1228,7 +1230,8 @@ class _SafetyState extends State<_Safety> with AutomaticKeepAliveClientMixin { ...directIp(context), whitelist(), ...autoDisconnect(context), - _OptionCheckBox(context, 'keep-awake-during-incoming-sessions-label', kOptionKeepAwakeDuringIncomingSessions, + _OptionCheckBox(context, 'keep-awake-during-incoming-sessions-label', + kOptionKeepAwakeDuringIncomingSessions, reverse: false, enabled: enabled), if (bind.mainIsInstalled()) _OptionCheckBox(context, 'allow-only-conn-window-open-tip', diff --git a/flutter/lib/mobile/pages/file_manager_page.dart b/flutter/lib/mobile/pages/file_manager_page.dart index 745df67b5..1e793bca7 100644 --- a/flutter/lib/mobile/pages/file_manager_page.dart +++ b/flutter/lib/mobile/pages/file_manager_page.dart @@ -5,7 +5,6 @@ import 'package:flutter_breadcrumb/flutter_breadcrumb.dart'; import 'package:flutter_hbb/models/file_model.dart'; import 'package:get/get.dart'; import 'package:toggle_switch/toggle_switch.dart'; -import 'package:wakelock_plus/wakelock_plus.dart'; import '../../common.dart'; import '../../common/widgets/dialog.dart'; @@ -72,6 +71,7 @@ class _FileManagerPageState extends State { showLocal ? model.localController : model.remoteController; FileDirectory get currentDir => currentFileController.directory.value; DirectoryOptions get currentOptions => currentFileController.options.value; + final _uniqueKey = UniqueKey(); @override void initState() { @@ -86,7 +86,7 @@ class _FileManagerPageState extends State { .showLoading(translate('Connecting...'), onCancel: closeConnection); }); gFFI.ffiModel.updateEventListener(gFFI.sessionId, widget.id); - WakelockPlus.enable(); + WakelockManager.enable(_uniqueKey); } @override @@ -94,7 +94,7 @@ class _FileManagerPageState extends State { model.close().whenComplete(() { gFFI.close(); gFFI.dialogManager.dismissAll(); - WakelockPlus.disable(); + WakelockManager.disable(_uniqueKey); }); model.jobController.clear(); super.dispose(); diff --git a/flutter/lib/mobile/pages/remote_page.dart b/flutter/lib/mobile/pages/remote_page.dart index 22dbebce6..1850f2093 100644 --- a/flutter/lib/mobile/pages/remote_page.dart +++ b/flutter/lib/mobile/pages/remote_page.dart @@ -14,7 +14,6 @@ import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:provider/provider.dart'; -import 'package:wakelock_plus/wakelock_plus.dart'; import '../../common.dart'; import '../../common/widgets/overlay.dart'; @@ -67,7 +66,7 @@ class _RemotePageState extends State with WidgetsBindingObserver { String _value = ''; Orientation? _currentOrientation; double _viewInsetsBottom = 0; - + final _uniqueKey = UniqueKey(); Timer? _timerDidChangeMetrics; final _blockableOverlayState = BlockableOverlayState(); @@ -105,9 +104,7 @@ class _RemotePageState extends State with WidgetsBindingObserver { gFFI.dialogManager .showLoading(translate('Connecting...'), onCancel: closeConnection); }); - if (!isWeb) { - WakelockPlus.enable(); - } + WakelockManager.enable(_uniqueKey); _physicalFocusNode.requestFocus(); gFFI.inputModel.listenToMouse(true); gFFI.qualityMonitorModel.checkShowQualityMonitor(sessionId); @@ -146,9 +143,7 @@ class _RemotePageState extends State with WidgetsBindingObserver { gFFI.dialogManager.dismissAll(); await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values); - if (!isWeb) { - await WakelockPlus.disable(); - } + WakelockManager.disable(_uniqueKey); await keyboardSubscription.cancel(); removeSharedStates(widget.id); // `on_voice_call_closed` should be called when the connection is ended. diff --git a/flutter/lib/mobile/pages/view_camera_page.dart b/flutter/lib/mobile/pages/view_camera_page.dart index 018d22980..0898125c4 100644 --- a/flutter/lib/mobile/pages/view_camera_page.dart +++ b/flutter/lib/mobile/pages/view_camera_page.dart @@ -11,7 +11,6 @@ import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart'; import 'package:flutter_svg/svg.dart'; import 'package:get/get.dart'; import 'package:provider/provider.dart'; -import 'package:wakelock_plus/wakelock_plus.dart'; import '../../common.dart'; import '../../common/widgets/overlay.dart'; @@ -62,7 +61,7 @@ class _ViewCameraPageState extends State bool _showGestureHelp = false; Orientation? _currentOrientation; double _viewInsetsBottom = 0; - + final _uniqueKey = UniqueKey(); Timer? _timerDidChangeMetrics; final _blockableOverlayState = BlockableOverlayState(); @@ -100,9 +99,7 @@ class _ViewCameraPageState extends State gFFI.dialogManager .showLoading(translate('Connecting...'), onCancel: closeConnection); }); - if (!isWeb) { - WakelockPlus.enable(); - } + WakelockManager.enable(_uniqueKey); _physicalFocusNode.requestFocus(); gFFI.inputModel.listenToMouse(true); gFFI.qualityMonitorModel.checkShowQualityMonitor(sessionId); @@ -139,9 +136,7 @@ class _ViewCameraPageState extends State gFFI.dialogManager.dismissAll(); await SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: SystemUiOverlay.values); - if (!isWeb) { - await WakelockPlus.disable(); - } + WakelockManager.disable(_uniqueKey); removeSharedStates(widget.id); // `on_voice_call_closed` should be called when the connection is ended. // The inner logic of `on_voice_call_closed` will check if the voice call is active. diff --git a/flutter/lib/models/server_model.dart b/flutter/lib/models/server_model.dart index c3e6fab71..2d834f028 100644 --- a/flutter/lib/models/server_model.dart +++ b/flutter/lib/models/server_model.dart @@ -8,7 +8,6 @@ import 'package:flutter_hbb/mobile/pages/settings_page.dart'; import 'package:flutter_hbb/models/chat_model.dart'; import 'package:flutter_hbb/models/platform_model.dart'; import 'package:get/get.dart'; -import 'package:wakelock_plus/wakelock_plus.dart'; import 'package:window_manager/window_manager.dart'; import '../common.dart'; @@ -51,6 +50,8 @@ class ServerModel with ChangeNotifier { Timer? cmHiddenTimer; + final _wakelockKey = UniqueKey(); + bool get isStart => _isStart; bool get mediaOk => _mediaOk; @@ -466,10 +467,7 @@ class ServerModel with ChangeNotifier { await parent.target?.invokeMethod("stop_service"); await bind.mainStopService(); notifyListeners(); - if (!isLinux) { - // current linux is not supported - WakelockPlus.disable(); - } + WakelockManager.disable(_wakelockKey); } Future setPermanentPassword(String newPW) async { @@ -613,12 +611,12 @@ class ServerModel with ChangeNotifier { void showLoginDialog(Client client) { showClientDialog( client, - client.isFileTransfer - ? "Transfer file" + client.isFileTransfer + ? "Transfer file" : client.isViewCamera ? "View camera" - : client.isTerminal - ? "Terminal" + : client.isTerminal + ? "Terminal" : "Share screen", 'Do you accept?', 'android_new_connection_tip', @@ -797,12 +795,10 @@ class ServerModel with ChangeNotifier { final on = ((keepScreenOn == KeepScreenOn.serviceOn) && _isStart) || (keepScreenOn == KeepScreenOn.duringControlled && _clients.map((e) => !e.disconnected).isNotEmpty); - if (on != await WakelockPlus.enabled) { - if (on) { - WakelockPlus.enable(); - } else { - WakelockPlus.disable(); - } + if (on) { + WakelockManager.enable(_wakelockKey, isServer: true); + } else { + WakelockManager.disable(_wakelockKey); } } } diff --git a/src/server/connection.rs b/src/server/connection.rs index 1f6be7413..f90aad115 100644 --- a/src/server/connection.rs +++ b/src/server/connection.rs @@ -74,6 +74,7 @@ lazy_static::lazy_static! { pub static ref CONTROL_PERMISSIONS_ARRAY: Arc::>> = Default::default(); static ref SWITCH_SIDES_UUID: Arc::>> = Default::default(); static ref WAKELOCK_SENDER: Arc::>> = Arc::new(Mutex::new(start_wakelock_thread())); + static ref WAKELOCK_KEEP_AWAKE_OPTION: Arc::>> = Default::default(); } #[cfg(any(target_os = "windows", target_os = "linux"))] @@ -906,6 +907,7 @@ impl Connection { _ = second_timer.tick() => { #[cfg(windows)] conn.portable_check(); + raii::AuthedConnID::check_wake_lock_on_setting_changed(); if let Some((instant, minute)) = conn.auto_disconnect_timer.as_ref() { if instant.elapsed().as_secs() > minute * 60 { conn.send_close_reason_no_retry("Connection failed due to inactivity").await; @@ -5017,11 +5019,16 @@ fn start_wakelock_thread() -> std::sync::mpsc::Sender<(usize, usize)> { loop { match rx.recv() { Ok((conn_count, remote_count)) => { - let keep_awake = config::Config::get_bool_option("keep-awake-during-incoming-sessions"); - if conn_count == 0 && wakeLock.is_some() { - wakelock = None; - log::info!("drop wakelock"); - } else if keep_awake { + let keep_awake = config::Config::get_bool_option( + keys::OPTION_KEEP_AWAKE_DURING_INCOMING_SESSIONS, + ); + *WAKELOCK_KEEP_AWAKE_OPTION.lock().unwrap() = Some(keep_awake); + if conn_count == 0 || !keep_awake { + if wakelock.is_some() { + wakelock = None; + log::info!("drop wakelock"); + } + } else { let mut display = remote_count > 0; if let Some(_w) = wakelock.as_mut() { if display != last_display { @@ -5331,6 +5338,16 @@ mod raii { .send((conn_count, remote_count))); } + pub fn check_wake_lock_on_setting_changed() { + let current = config::Config::get_bool_option( + keys::OPTION_KEEP_AWAKE_DURING_INCOMING_SESSIONS, + ); + let cached = *WAKELOCK_KEEP_AWAKE_OPTION.lock().unwrap(); + if cached != Some(current) { + Self::check_wake_lock(); + } + } + #[cfg(windows)] pub fn non_port_forward_conn_count() -> usize { AUTHED_CONNS diff --git a/src/ui/index.tis b/src/ui/index.tis index 8dd4da3d4..09aa0c306 100644 --- a/src/ui/index.tis +++ b/src/ui/index.tis @@ -268,6 +268,7 @@ class Enhancements: Reactor.Component {
  • {svg_checkmark}{translate("Adaptive bitrate")} (beta)
  • {translate("Recording")}
  • {support_remove_wallpaper ?
  • {svg_checkmark}{translate("Remove wallpaper during incoming sessions")}
  • : ""} +
  • {svg_checkmark}{translate("keep-awake-during-incoming-sessions-label")}
  • ; } @@ -288,6 +289,13 @@ class Enhancements: Reactor.Component { if (is_opt_fixed) { el.state.disabled = true; } + } else if (el.id == "keep-awake-during-incoming-sessions") { + var enabled = handler.get_option(el.id) != "N"; + el.attributes.toggleClass("selected", enabled); + var is_opt_fixed = handler.is_option_fixed(el.id); + if (is_opt_fixed) { + el.state.disabled = true; + } } } @@ -304,6 +312,8 @@ class Enhancements: Reactor.Component { } } else if (v.indexOf("allow-") == 0) { handler.set_option(v, handler.get_option(v) == 'Y' ? default_option_no : 'Y'); + } else if (v == 'keep-awake-during-incoming-sessions') { + handler.set_option(v, handler.get_option(v) != 'N' ? 'N' : default_option_yes); } else if (v == 'screen-recording') { var show_root_dir = is_win && handler.is_installed(); var user_dir = handler.video_save_directory(false);