Merge pull request #4747 from dignow/fix/mobile_connection_login_state

Fix/mobile connection login state
This commit is contained in:
RustDesk 2023-06-23 17:43:42 +08:00 committed by GitHub
commit 74dc8536be
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
13 changed files with 170 additions and 122 deletions

View File

@ -1,7 +1,6 @@
// main window right pane // main window right pane
import 'dart:async'; import 'dart:async';
import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'package:auto_size_text/auto_size_text.dart'; import 'package:auto_size_text/auto_size_text.dart';
@ -9,7 +8,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_hbb/consts.dart'; import 'package:flutter_hbb/consts.dart';
import 'package:flutter_hbb/desktop/widgets/scroll_wrapper.dart'; import 'package:flutter_hbb/desktop/widgets/scroll_wrapper.dart';
import 'package:flutter_hbb/models/state_model.dart'; import 'package:flutter_hbb/models/state_model.dart';
import 'package:flutter_hbb/models/user_model.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import 'package:url_launcher/url_launcher_string.dart'; import 'package:url_launcher/url_launcher_string.dart';
import 'package:window_manager/window_manager.dart'; import 'package:window_manager/window_manager.dart';
@ -37,13 +35,12 @@ class _ConnectionPageState extends State<ConnectionPage>
/// Nested scroll controller /// Nested scroll controller
final _scrollController = ScrollController(); final _scrollController = ScrollController();
Timer? _updateTimer; Timer? _svcStatusTimer;
final RxBool _idInputFocused = false.obs; final RxBool _idInputFocused = false.obs;
final FocusNode _idFocusNode = FocusNode(); final FocusNode _idFocusNode = FocusNode();
var svcStopped = Get.find<RxBool>(tag: 'stop-service'); var svcStopped = Get.find<RxBool>(tag: 'stop-service');
var svcIsUsingPublicServer = true.obs;
bool isWindowMinimized = false; bool isWindowMinimized = false;
@ -60,8 +57,8 @@ class _ConnectionPageState extends State<ConnectionPage>
} }
}(); }();
} }
_updateTimer = periodic_immediate(Duration(seconds: 1), () async { _svcStatusTimer = periodic_immediate(Duration(seconds: 1), () async {
updateStatus(); stateGlobal.updateSvcStatus();
}); });
_idFocusNode.addListener(() { _idFocusNode.addListener(() {
_idInputFocused.value = _idFocusNode.hasFocus; _idInputFocused.value = _idFocusNode.hasFocus;
@ -75,7 +72,8 @@ class _ConnectionPageState extends State<ConnectionPage>
@override @override
void dispose() { void dispose() {
_idController.dispose(); _idController.dispose();
_updateTimer?.cancel(); _svcStatusTimer?.cancel();
_svcStatusTimer = null;
windowManager.removeListener(this); windowManager.removeListener(this);
super.dispose(); super.dispose();
} }
@ -288,7 +286,7 @@ class _ConnectionPageState extends State<ConnectionPage>
child: Offstage( child: Offstage(
offstage: !(!svcStopped.value && offstage: !(!svcStopped.value &&
stateGlobal.svcStatus.value == SvcStatus.ready && stateGlobal.svcStatus.value == SvcStatus.ready &&
svcIsUsingPublicServer.value), stateGlobal.svcIsUsingPublicServer.value),
child: Row( child: Row(
crossAxisAlignment: CrossAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center,
children: [ children: [
@ -327,31 +325,4 @@ class _ConnectionPageState extends State<ConnectionPage>
} }
}); });
} }
updateStatus() async {
final status =
jsonDecode(await bind.mainGetConnectStatus()) as Map<String, dynamic>;
final statusNum = status['status_num'] as int;
final preStatus = stateGlobal.svcStatus.value;
if (statusNum == 0) {
stateGlobal.svcStatus.value = SvcStatus.connecting;
} else if (statusNum == -1) {
stateGlobal.svcStatus.value = SvcStatus.notReady;
} else if (statusNum == 1) {
stateGlobal.svcStatus.value = SvcStatus.ready;
if (preStatus != SvcStatus.ready) {
gFFI.userModel.refreshCurrentUser();
}
} else {
stateGlobal.svcStatus.value = SvcStatus.notReady;
}
if (stateGlobal.svcStatus.value != SvcStatus.ready) {
gFFI.userModel.isAdmin.value = false;
gFFI.groupModel.reset();
}
if (preStatus != stateGlobal.svcStatus.value) {
UserModel.updateOtherModels();
}
svcIsUsingPublicServer.value = await bind.mainIsUsingPublicServer();
}
} }

View File

@ -151,6 +151,7 @@ void runMobileApp() async {
await initEnv(kAppTypeMain); await initEnv(kAppTypeMain);
if (isAndroid) androidChannelInit(); if (isAndroid) androidChannelInit();
platformFFI.syncAndroidServiceAppDirConfigPath(); platformFFI.syncAndroidServiceAppDirConfigPath();
gFFI.userModel.refreshCurrentUser();
runApp(App()); runApp(App());
} }

View File

@ -11,6 +11,7 @@ import '../../common/widgets/dialog.dart';
import '../../consts.dart'; import '../../consts.dart';
import '../../models/platform_model.dart'; import '../../models/platform_model.dart';
import '../../models/server_model.dart'; import '../../models/server_model.dart';
import '../../models/state_model.dart';
import 'home_page.dart'; import 'home_page.dart';
class ServerPage extends StatefulWidget implements PageShape { class ServerPage extends StatefulWidget implements PageShape {
@ -200,7 +201,6 @@ class ServerInfo extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final isPermanent = model.verificationMethod == kUsePermanentPassword; final isPermanent = model.verificationMethod == kUsePermanentPassword;
final serverModel = Provider.of<ServerModel>(context);
const Color colorPositive = Colors.green; const Color colorPositive = Colors.green;
const Color colorNegative = Colors.red; const Color colorNegative = Colors.red;
@ -216,28 +216,29 @@ class ServerInfo extends StatelessWidget {
showToast(translate('Copied')); showToast(translate('Copied'));
} }
Widget ConnectionStateNotification() { Widget ConnectionStateNotification() => Obx(() {
if (serverModel.connectStatus == -1) { if (stateGlobal.svcStatus.value == SvcStatus.notReady) {
return Row(children: [ return Row(children: [
const Icon(Icons.warning_amber_sharp, const Icon(Icons.warning_amber_sharp,
color: colorNegative, size: iconSize) color: colorNegative, size: iconSize)
.marginOnly(right: iconMarginRight), .marginOnly(right: iconMarginRight),
Expanded(child: Text(translate('not_ready_status'))) Expanded(child: Text(translate('not_ready_status')))
]); ]);
} else if (serverModel.connectStatus == 0) { } else if (stateGlobal.svcStatus.value == SvcStatus.connecting) {
return Row(children: [ return Row(children: [
SizedBox(width: 20, height: 20, child: CircularProgressIndicator()) SizedBox(
.marginOnly(left: 4, right: iconMarginRight), width: 20, height: 20, child: CircularProgressIndicator())
Expanded(child: Text(translate('connecting_status'))) .marginOnly(left: 4, right: iconMarginRight),
]); Expanded(child: Text(translate('connecting_status')))
} else { ]);
return Row(children: [ } else {
const Icon(Icons.check, color: colorPositive, size: iconSize) return Row(children: [
.marginOnly(right: iconMarginRight), const Icon(Icons.check, color: colorPositive, size: iconSize)
Expanded(child: Text(translate('Ready'))) .marginOnly(right: iconMarginRight),
]); Expanded(child: Text(translate('Ready')))
} ]);
} }
});
return PaddingCard( return PaddingCard(
title: translate('Your Device'), title: translate('Your Device'),

View File

@ -15,7 +15,8 @@ import '../common/formatter/id_formatter.dart';
import '../desktop/pages/server_page.dart' as desktop; import '../desktop/pages/server_page.dart' as desktop;
import '../desktop/widgets/tabbar_widget.dart'; import '../desktop/widgets/tabbar_widget.dart';
import '../mobile/pages/server_page.dart'; import '../mobile/pages/server_page.dart';
import 'model.dart'; import './model.dart';
import './state_model.dart';
const kLoginDialogTag = "LOGIN"; const kLoginDialogTag = "LOGIN";
@ -31,7 +32,6 @@ class ServerModel with ChangeNotifier {
bool _fileOk = false; bool _fileOk = false;
bool _showElevation = false; bool _showElevation = false;
bool _hideCm = false; bool _hideCm = false;
int _connectStatus = 0; // Rendezvous Server status
String _verificationMethod = ""; String _verificationMethod = "";
String _temporaryPasswordLength = ""; String _temporaryPasswordLength = "";
String _approveMode = ""; String _approveMode = "";
@ -61,8 +61,6 @@ class ServerModel with ChangeNotifier {
bool get hideCm => _hideCm; bool get hideCm => _hideCm;
int get connectStatus => _connectStatus;
String get verificationMethod { String get verificationMethod {
final index = [ final index = [
kUseTemporaryPassword, kUseTemporaryPassword,
@ -120,15 +118,7 @@ class ServerModel with ChangeNotifier {
_serverId = IDTextEditingController(text: _emptyIdShow); _serverId = IDTextEditingController(text: _emptyIdShow);
timerCallback() async { timerCallback() async {
var status = await bind.mainGetOnlineStatue(); stateGlobal.updateSvcStatus();
if (status > 0) {
status = 1;
}
if (status != _connectStatus) {
_connectStatus = status;
notifyListeners();
}
if (desktopType == DesktopType.cm) { if (desktopType == DesktopType.cm) {
final res = await bind.cmCheckClientsLength(length: _clients.length); final res = await bind.cmCheckClientsLength(length: _clients.length);
if (res != null) { if (res != null) {

View File

@ -1,10 +1,15 @@
import 'dart:convert';
import 'dart:io'; import 'dart:io';
import 'dart:async';
import 'package:desktop_multi_window/desktop_multi_window.dart'; import 'package:desktop_multi_window/desktop_multi_window.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:get/get.dart'; import 'package:get/get.dart';
import '../consts.dart'; import '../consts.dart';
import '../common.dart';
import './platform_model.dart';
enum SvcStatus { notReady, connecting, ready } enum SvcStatus { notReady, connecting, ready }
@ -18,7 +23,9 @@ class StateGlobal {
final RxDouble _windowBorderWidth = RxDouble(kWindowBorderWidth); final RxDouble _windowBorderWidth = RxDouble(kWindowBorderWidth);
final RxBool showRemoteToolBar = false.obs; final RxBool showRemoteToolBar = false.obs;
final RxInt displaysCount = 0.obs; final RxInt displaysCount = 0.obs;
final svcStatus = SvcStatus.notReady.obs; final svcStatus = SvcStatus.notReady.obs;
final svcIsUsingPublicServer = true.obs;
// Use for desktop -> remote toolbar -> resolution // Use for desktop -> remote toolbar -> resolution
final Map<String, Map<int, String?>> _lastResolutionGroupValues = {}; final Map<String, Map<int, String?>> _lastResolutionGroupValues = {};
@ -84,6 +91,31 @@ class StateGlobal {
} }
} }
updateSvcStatus() async {
final status =
jsonDecode(await bind.mainGetConnectStatus()) as Map<String, dynamic>;
final statusNum = status['status_num'] as int;
final preStatus = stateGlobal.svcStatus.value;
if (statusNum == 0) {
stateGlobal.svcStatus.value = SvcStatus.connecting;
} else if (statusNum == -1) {
stateGlobal.svcStatus.value = SvcStatus.notReady;
} else if (statusNum == 1) {
stateGlobal.svcStatus.value = SvcStatus.ready;
if (preStatus != SvcStatus.ready) {
gFFI.userModel.refreshCurrentUser();
}
} else {
stateGlobal.svcStatus.value = SvcStatus.notReady;
}
if (stateGlobal.svcStatus.value != SvcStatus.ready) {
gFFI.userModel.isAdmin.value = false;
gFFI.groupModel.reset();
}
stateGlobal.svcIsUsingPublicServer.value =
await bind.mainIsUsingPublicServer();
}
StateGlobal._(); StateGlobal._();
static final StateGlobal instance = StateGlobal._(); static final StateGlobal instance = StateGlobal._();

View File

@ -44,7 +44,7 @@ lazy_static::lazy_static! {
static ref CONFIG: Arc<RwLock<Config>> = Arc::new(RwLock::new(Config::load())); static ref CONFIG: Arc<RwLock<Config>> = Arc::new(RwLock::new(Config::load()));
static ref CONFIG2: Arc<RwLock<Config2>> = Arc::new(RwLock::new(Config2::load())); static ref CONFIG2: Arc<RwLock<Config2>> = Arc::new(RwLock::new(Config2::load()));
static ref LOCAL_CONFIG: Arc<RwLock<LocalConfig>> = Arc::new(RwLock::new(LocalConfig::load())); static ref LOCAL_CONFIG: Arc<RwLock<LocalConfig>> = Arc::new(RwLock::new(LocalConfig::load()));
pub static ref ONLINE: Arc<Mutex<HashMap<String, i64>>> = Default::default(); static ref ONLINE: Arc<Mutex<HashMap<String, i64>>> = Default::default();
pub static ref PROD_RENDEZVOUS_SERVER: Arc<RwLock<String>> = Arc::new(RwLock::new(match option_env!("RENDEZVOUS_SERVER") { pub static ref PROD_RENDEZVOUS_SERVER: Arc<RwLock<String>> = Arc::new(RwLock::new(match option_env!("RENDEZVOUS_SERVER") {
Some(key) if !key.is_empty() => key, Some(key) if !key.is_empty() => key,
_ => "", _ => "",
@ -309,6 +309,11 @@ pub struct TransferSerde {
pub read_jobs: Vec<String>, pub read_jobs: Vec<String>,
} }
#[inline]
pub fn get_online_statue() -> i64 {
*ONLINE.lock().unwrap().values().max().unwrap_or(&0)
}
#[cfg(not(any(target_os = "android", target_os = "ios")))] #[cfg(not(any(target_os = "android", target_os = "ios")))]
fn patch(path: PathBuf) -> PathBuf { fn patch(path: PathBuf) -> PathBuf {
if let Some(_tmp) = path.to_str() { if let Some(_tmp) = path.to_str() {

View File

@ -14,12 +14,11 @@ use flutter_rust_bridge::{StreamSink, SyncReturn};
#[cfg(not(any(target_os = "android", target_os = "ios")))] #[cfg(not(any(target_os = "android", target_os = "ios")))]
use hbb_common::allow_err; use hbb_common::allow_err;
use hbb_common::{ use hbb_common::{
config::{self, LocalConfig, PeerConfig, PeerInfoSerde, ONLINE}, config::{self, LocalConfig, PeerConfig, PeerInfoSerde},
fs, log, fs, log,
message_proto::KeyboardMode, message_proto::KeyboardMode,
ResultType, ResultType,
}; };
use serde_json::json;
use std::{ use std::{
collections::HashMap, collections::HashMap,
ffi::{CStr, CString}, ffi::{CStr, CString},
@ -680,14 +679,18 @@ pub fn main_get_lan_peers() -> String {
} }
pub fn main_get_connect_status() -> String { pub fn main_get_connect_status() -> String {
let status = get_connect_status(); #[cfg(not(any(target_os = "android", target_os = "ios")))]
// (status_num, key_confirmed, mouse_time, id) {
let mut m = serde_json::Map::new(); serde_json::to_string(&get_connect_status()).unwrap_or("".to_string())
m.insert("status_num".to_string(), json!(status.0)); }
m.insert("key_confirmed".to_string(), json!(status.1)); #[cfg(any(target_os = "android", target_os = "ios"))]
m.insert("mouse_time".to_string(), json!(status.2)); {
m.insert("id".to_string(), json!(status.3)); let mut state = hbb_common::config::get_online_statue();
serde_json::to_string(&m).unwrap_or("".to_string()) if state > 0 {
state = 1;
}
serde_json::json!({ "status_num": state }).to_string()
}
} }
pub fn main_check_connect_status() { pub fn main_check_connect_status() {
@ -995,10 +998,6 @@ pub fn main_get_fingerprint() -> String {
get_fingerprint() get_fingerprint()
} }
pub fn main_get_online_statue() -> i64 {
ONLINE.lock().unwrap().values().max().unwrap_or(&0).clone()
}
pub fn cm_get_clients_state() -> String { pub fn cm_get_clients_state() -> String {
crate::ui_cm_interface::get_clients_state() crate::ui_cm_interface::get_clients_state()
} }
@ -1194,7 +1193,14 @@ pub fn main_check_mouse_time() {
} }
pub fn main_get_mouse_time() -> f64 { pub fn main_get_mouse_time() -> f64 {
get_mouse_time() #[cfg(not(any(target_os = "android", target_os = "ios")))]
{
get_mouse_time()
}
#[cfg(any(target_os = "android", target_os = "ios"))]
{
0.0
}
} }
pub fn main_wol(id: String) { pub fn main_wol(id: String) {

View File

@ -216,7 +216,7 @@ impl OidcSession {
let query_timeout = OIDC_SESSION.read().unwrap().query_timeout; let query_timeout = OIDC_SESSION.read().unwrap().query_timeout;
while OIDC_SESSION.read().unwrap().keep_querying && begin.elapsed() < query_timeout { while OIDC_SESSION.read().unwrap().keep_querying && begin.elapsed() < query_timeout {
match Self::query(&code_url.code, &id, &uuid) { match Self::query(&code_url.code, &id, &uuid) {
Ok(HbbHttpResponse::<_>::Data(mut auth_body)) => { Ok(HbbHttpResponse::<_>::Data(auth_body)) => {
if remember_me { if remember_me {
LocalConfig::set_option( LocalConfig::set_option(
"access_token".to_owned(), "access_token".to_owned(),

View File

@ -186,6 +186,7 @@ pub enum Data {
}, },
SystemInfo(Option<String>), SystemInfo(Option<String>),
ClickTime(i64), ClickTime(i64),
#[cfg(not(any(target_os = "android", target_os = "ios")))]
MouseMoveTime(i64), MouseMoveTime(i64),
Authorize, Authorize,
Close, Close,
@ -332,6 +333,7 @@ async fn handle(data: Data, stream: &mut Connection) {
let t = crate::server::CLICK_TIME.load(Ordering::SeqCst); let t = crate::server::CLICK_TIME.load(Ordering::SeqCst);
allow_err!(stream.send(&Data::ClickTime(t)).await); allow_err!(stream.send(&Data::ClickTime(t)).await);
} }
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Data::MouseMoveTime(_) => { Data::MouseMoveTime(_) => {
let t = crate::server::MOUSE_MOVE_TIME.load(Ordering::SeqCst); let t = crate::server::MOUSE_MOVE_TIME.load(Ordering::SeqCst);
allow_err!(stream.send(&Data::MouseMoveTime(t)).await); allow_err!(stream.send(&Data::MouseMoveTime(t)).await);
@ -345,13 +347,7 @@ async fn handle(data: Data, stream: &mut Connection) {
} }
} }
Data::OnlineStatus(_) => { Data::OnlineStatus(_) => {
let x = config::ONLINE let x = config::get_online_statue();
.lock()
.unwrap()
.values()
.max()
.unwrap_or(&0)
.clone();
let confirmed = Config::get_key_confirmed(); let confirmed = Config::get_key_confirmed();
allow_err!(stream.send(&Data::OnlineStatus(Some((x, confirmed)))).await); allow_err!(stream.send(&Data::OnlineStatus(Some((x, confirmed)))).await);
} }

View File

@ -63,6 +63,7 @@ lazy_static::lazy_static! {
static ref SWITCH_SIDES_UUID: Arc::<Mutex<HashMap<String, (Instant, uuid::Uuid)>>> = Default::default(); static ref SWITCH_SIDES_UUID: Arc::<Mutex<HashMap<String, (Instant, uuid::Uuid)>>> = Default::default();
} }
pub static CLICK_TIME: AtomicI64 = AtomicI64::new(0); pub static CLICK_TIME: AtomicI64 = AtomicI64::new(0);
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub static MOUSE_MOVE_TIME: AtomicI64 = AtomicI64::new(0); pub static MOUSE_MOVE_TIME: AtomicI64 = AtomicI64::new(0);
#[cfg(all(feature = "flutter", feature = "plugin_framework"))] #[cfg(all(feature = "flutter", feature = "plugin_framework"))]
@ -163,6 +164,7 @@ pub struct Connection {
// by peer // by peer
disable_audio: bool, disable_audio: bool,
// by peer // by peer
#[cfg(windows)]
enable_file_transfer: bool, enable_file_transfer: bool,
// by peer // by peer
audio_sender: Option<MediaSender>, audio_sender: Option<MediaSender>,
@ -291,6 +293,7 @@ impl Connection {
show_remote_cursor: false, show_remote_cursor: false,
ip: "".to_owned(), ip: "".to_owned(),
disable_audio: false, disable_audio: false,
#[cfg(windows)]
enable_file_transfer: false, enable_file_transfer: false,
disable_clipboard: false, disable_clipboard: false,
disable_keyboard: false, disable_keyboard: false,
@ -1112,6 +1115,7 @@ impl Connection {
self.audio && !self.disable_audio self.audio && !self.disable_audio
} }
#[cfg(windows)]
fn file_transfer_enabled(&self) -> bool { fn file_transfer_enabled(&self) -> bool {
self.file && self.enable_file_transfer self.file && self.enable_file_transfer
} }

View File

@ -362,9 +362,9 @@ impl UI {
fn get_connect_status(&mut self) -> Value { fn get_connect_status(&mut self) -> Value {
let mut v = Value::array(0); let mut v = Value::array(0);
let x = get_connect_status(); let x = get_connect_status();
v.push(x.0); v.push(x.status_num);
v.push(x.1); v.push(x.key_confirmed);
v.push(x.3); v.push(x.id);
v v
} }

View File

@ -454,10 +454,10 @@ impl<T: InvokeUiCM> IpcTaskRunner<T> {
} }
} }
Some(data) = self.rx.recv() => { Some(data) = self.rx.recv() => {
if let Data::SwitchPermission{name, enabled} = &data { if let Data::SwitchPermission{name: _name, enabled: _enabled} = &data {
#[cfg(windows)] #[cfg(windows)]
if name == "file" { if _name == "file" {
self.file_transfer_enabled = *enabled; self.file_transfer_enabled = *_enabled;
} }
} }
if self.stream.send(&data).await.is_err() { if self.stream.send(&data).await.is_err() {

View File

@ -1,9 +1,3 @@
use std::{
collections::HashMap,
process::Child,
sync::{Arc, Mutex},
};
#[cfg(any(target_os = "android", target_os = "ios"))] #[cfg(any(target_os = "android", target_os = "ios"))]
use hbb_common::password_security; use hbb_common::password_security;
use hbb_common::{ use hbb_common::{
@ -16,6 +10,12 @@ use hbb_common::{
sleep, sleep,
tokio::{sync::mpsc, time}, tokio::{sync::mpsc, time},
}; };
use serde_derive::Serialize;
use std::{
collections::HashMap,
process::Child,
sync::{Arc, Mutex},
};
use hbb_common::{ use hbb_common::{
config::{CONNECT_TIMEOUT, RENDEZVOUS_PORT}, config::{CONNECT_TIMEOUT, RENDEZVOUS_PORT},
@ -32,10 +32,28 @@ use crate::ipc;
type Message = RendezvousMessage; type Message = RendezvousMessage;
pub type Children = Arc<Mutex<(bool, HashMap<(String, String), Child>)>>; pub type Children = Arc<Mutex<(bool, HashMap<(String, String), Child>)>>;
type Status = (i32, bool, i64, String); // (status_num, key_confirmed, mouse_time, id)
#[derive(Clone, Debug, Serialize)]
pub struct UiStatus {
pub status_num: i32,
#[cfg(not(feature = "flutter"))]
pub key_confirmed: bool,
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub mouse_time: i64,
#[cfg(not(feature = "flutter"))]
pub id: String,
}
lazy_static::lazy_static! { lazy_static::lazy_static! {
static ref UI_STATUS : Arc<Mutex<Status>> = Arc::new(Mutex::new((0, false, 0, "".to_owned()))); static ref UI_STATUS : Arc<Mutex<UiStatus>> = Arc::new(Mutex::new(UiStatus{
status_num: 0,
#[cfg(not(feature = "flutter"))]
key_confirmed: false,
#[cfg(not(any(target_os = "android", target_os = "ios")))]
mouse_time: 0,
#[cfg(not(feature = "flutter"))]
id: "".to_owned(),
}));
static ref OPTIONS : Arc<Mutex<HashMap<String, String>>> = Arc::new(Mutex::new(Config::get_options())); static ref OPTIONS : Arc<Mutex<HashMap<String, String>>> = Arc::new(Mutex::new(Config::get_options()));
static ref ASYNC_JOB_STATUS : Arc<Mutex<String>> = Default::default(); static ref ASYNC_JOB_STATUS : Arc<Mutex<String>> = Default::default();
static ref TEMPORARY_PASSWD : Arc<Mutex<String>> = Arc::new(Mutex::new("".to_owned())); static ref TEMPORARY_PASSWD : Arc<Mutex<String>> = Arc::new(Mutex::new("".to_owned()));
@ -393,10 +411,9 @@ pub fn is_installed_lower_version() -> bool {
} }
#[inline] #[inline]
#[cfg(not(any(target_os = "android", target_os = "ios")))]
pub fn get_mouse_time() -> f64 { pub fn get_mouse_time() -> f64 {
let ui_status = UI_STATUS.lock().unwrap(); UI_STATUS.lock().unwrap().mouse_time as f64
let res = ui_status.2 as f64;
return res;
} }
#[inline] #[inline]
@ -409,10 +426,9 @@ pub fn check_mouse_time() {
} }
#[inline] #[inline]
pub fn get_connect_status() -> Status { #[cfg(not(any(target_os = "android", target_os = "ios")))]
let ui_statue = UI_STATUS.lock().unwrap(); pub fn get_connect_status() -> UiStatus {
let res = ui_statue.clone(); UI_STATUS.lock().unwrap().clone()
res
} }
#[inline] #[inline]
@ -857,10 +873,13 @@ pub fn get_hostname() -> String {
#[cfg(not(any(target_os = "android", target_os = "ios")))] #[cfg(not(any(target_os = "android", target_os = "ios")))]
#[tokio::main(flavor = "current_thread")] #[tokio::main(flavor = "current_thread")]
async fn check_connect_status_(reconnect: bool, rx: mpsc::UnboundedReceiver<ipc::Data>) { async fn check_connect_status_(reconnect: bool, rx: mpsc::UnboundedReceiver<ipc::Data>) {
#[cfg(not(feature = "flutter"))]
let mut key_confirmed = false; let mut key_confirmed = false;
let mut rx = rx; let mut rx = rx;
let mut mouse_time = 0; let mut mouse_time = 0;
#[cfg(not(feature = "flutter"))]
let mut id = "".to_owned(); let mut id = "".to_owned();
#[cfg(target_os = "windows")]
let mut enable_file_transfer = "".to_owned(); let mut enable_file_transfer = "".to_owned();
loop { loop {
@ -874,9 +893,10 @@ async fn check_connect_status_(reconnect: bool, rx: mpsc::UnboundedReceiver<ipc:
log::error!("ipc connection closed: {}", err); log::error!("ipc connection closed: {}", err);
break; break;
} }
#[cfg(not(any(target_os = "android", target_os = "ios")))]
Ok(Some(ipc::Data::MouseMoveTime(v))) => { Ok(Some(ipc::Data::MouseMoveTime(v))) => {
mouse_time = v; mouse_time = v;
UI_STATUS.lock().unwrap().2 = v; UI_STATUS.lock().unwrap().mouse_time = v;
} }
Ok(Some(ipc::Data::Options(Some(v)))) => { Ok(Some(ipc::Data::Options(Some(v)))) => {
*OPTIONS.lock().unwrap() = v; *OPTIONS.lock().unwrap() = v;
@ -893,17 +913,31 @@ async fn check_connect_status_(reconnect: bool, rx: mpsc::UnboundedReceiver<ipc:
} }
Ok(Some(ipc::Data::Config((name, Some(value))))) => { Ok(Some(ipc::Data::Config((name, Some(value))))) => {
if name == "id" { if name == "id" {
id = value; #[cfg(not(feature = "flutter"))]
{
id = value;
}
} else if name == "temporary-password" { } else if name == "temporary-password" {
*TEMPORARY_PASSWD.lock().unwrap() = value; *TEMPORARY_PASSWD.lock().unwrap() = value;
} }
} }
Ok(Some(ipc::Data::OnlineStatus(Some((mut x, c))))) => { Ok(Some(ipc::Data::OnlineStatus(Some((mut x, _c))))) => {
if x > 0 { if x > 0 {
x = 1 x = 1
} }
key_confirmed = c; #[cfg(not(feature = "flutter"))]
*UI_STATUS.lock().unwrap() = (x as _, key_confirmed, mouse_time, id.clone()); {
key_confirmed = _c;
}
*UI_STATUS.lock().unwrap() = UiStatus {
status_num: x as _,
#[cfg(not(feature = "flutter"))]
key_confirmed: _c,
#[cfg(not(any(target_os = "android", target_os = "ios")))]
mouse_time,
#[cfg(not(feature = "flutter"))]
id: id.clone(),
};
} }
_ => {} _ => {}
} }
@ -927,7 +961,15 @@ async fn check_connect_status_(reconnect: bool, rx: mpsc::UnboundedReceiver<ipc:
.insert("ipc-closed".to_owned(), "Y".to_owned()); .insert("ipc-closed".to_owned(), "Y".to_owned());
break; break;
} }
*UI_STATUS.lock().unwrap() = (-1, key_confirmed, mouse_time, id.clone()); *UI_STATUS.lock().unwrap() = UiStatus {
status_num: -1,
#[cfg(not(feature = "flutter"))]
key_confirmed,
#[cfg(not(any(target_os = "android", target_os = "ios")))]
mouse_time,
#[cfg(not(feature = "flutter"))]
id: id.clone(),
};
sleep(1.).await; sleep(1.).await;
} }
} }