Signed-off-by: 21pages <sunboeasy@gmail.com>
This commit is contained in:
21pages
2026-01-19 21:08:43 +08:00
parent c1288845a3
commit b78e5f7175
8 changed files with 93 additions and 59 deletions

View File

@@ -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<T> {
/// This manager handles multiple tabs within the same isolate.
class WakelockManager {
static final Set<UniqueKey> _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;
}
}
}

View File

@@ -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',

View File

@@ -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<FileManagerPage> {
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<FileManagerPage> {
.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<FileManagerPage> {
model.close().whenComplete(() {
gFFI.close();
gFFI.dialogManager.dismissAll();
WakelockPlus.disable();
WakelockManager.disable(_uniqueKey);
});
model.jobController.clear();
super.dispose();

View File

@@ -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<RemotePage> 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<RemotePage> 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<RemotePage> 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.

View File

@@ -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<ViewCameraPage>
bool _showGestureHelp = false;
Orientation? _currentOrientation;
double _viewInsetsBottom = 0;
final _uniqueKey = UniqueKey();
Timer? _timerDidChangeMetrics;
final _blockableOverlayState = BlockableOverlayState();
@@ -100,9 +99,7 @@ class _ViewCameraPageState extends State<ViewCameraPage>
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<ViewCameraPage>
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.

View File

@@ -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<bool> 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);
}
}
}

View File

@@ -74,6 +74,7 @@ lazy_static::lazy_static! {
pub static ref CONTROL_PERMISSIONS_ARRAY: Arc::<Mutex<Vec<(i32, ControlPermissions)>>> = Default::default();
static ref SWITCH_SIDES_UUID: Arc::<Mutex<HashMap<String, (Instant, uuid::Uuid)>>> = Default::default();
static ref WAKELOCK_SENDER: Arc::<Mutex<std::sync::mpsc::Sender<(usize, usize)>>> = Arc::new(Mutex::new(start_wakelock_thread()));
static ref WAKELOCK_KEEP_AWAKE_OPTION: Arc::<Mutex<Option<bool>>> = 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

View File

@@ -268,6 +268,7 @@ class Enhancements: Reactor.Component {
<li #enable-abr><span>{svg_checkmark}</span>{translate("Adaptive bitrate")} (beta)</li>
<li #screen-recording>{translate("Recording")}</li>
{support_remove_wallpaper ? <li #allow-remove-wallpaper><span>{svg_checkmark}</span>{translate("Remove wallpaper during incoming sessions")}</li> : ""}
<li #keep-awake-during-incoming-sessions><span>{svg_checkmark}</span>{translate("keep-awake-during-incoming-sessions-label")}</li>
</menu>
</li>;
}
@@ -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);