main.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:io';
  4. import 'package:bot_toast/bot_toast.dart';
  5. import 'package:desktop_multi_window/desktop_multi_window.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:flutter_hbb/common/widgets/overlay.dart';
  9. import 'package:flutter_hbb/desktop/pages/desktop_tab_page.dart';
  10. import 'package:flutter_hbb/desktop/pages/install_page.dart';
  11. import 'package:flutter_hbb/desktop/pages/server_page.dart';
  12. import 'package:flutter_hbb/desktop/screen/desktop_file_transfer_screen.dart';
  13. import 'package:flutter_hbb/desktop/screen/desktop_port_forward_screen.dart';
  14. import 'package:flutter_hbb/desktop/screen/desktop_remote_screen.dart';
  15. import 'package:flutter_hbb/desktop/widgets/refresh_wrapper.dart';
  16. import 'package:flutter_hbb/models/state_model.dart';
  17. import 'package:flutter_hbb/utils/multi_window_manager.dart';
  18. import 'package:flutter_localizations/flutter_localizations.dart';
  19. import 'package:get/get.dart';
  20. import 'package:provider/provider.dart';
  21. import 'package:window_manager/window_manager.dart';
  22. import 'common.dart';
  23. import 'consts.dart';
  24. import 'mobile/pages/home_page.dart';
  25. import 'mobile/pages/server_page.dart';
  26. import 'models/platform_model.dart';
  27. import 'package:flutter_hbb/plugin/handlers.dart'
  28. if (dart.library.html) 'package:flutter_hbb/web/plugin/handlers.dart';
  29. /// Basic window and launch properties.
  30. int? kWindowId;
  31. WindowType? kWindowType;
  32. late List<String> kBootArgs;
  33. Future<void> main(List<String> args) async {
  34. earlyAssert();
  35. WidgetsFlutterBinding.ensureInitialized();
  36. debugPrint("launch args: $args");
  37. kBootArgs = List.from(args);
  38. if (!isDesktop) {
  39. runMobileApp();
  40. return;
  41. }
  42. // main window
  43. if (args.isNotEmpty && args.first == 'multi_window') {
  44. kWindowId = int.parse(args[1]);
  45. stateGlobal.setWindowId(kWindowId!);
  46. if (!isMacOS) {
  47. WindowController.fromWindowId(kWindowId!).showTitleBar(false);
  48. }
  49. final argument = args[2].isEmpty
  50. ? <String, dynamic>{}
  51. : jsonDecode(args[2]) as Map<String, dynamic>;
  52. int type = argument['type'] ?? -1;
  53. // to-do: No need to parse window id ?
  54. // Because stateGlobal.windowId is a global value.
  55. argument['windowId'] = kWindowId;
  56. kWindowType = type.windowType;
  57. switch (kWindowType) {
  58. case WindowType.RemoteDesktop:
  59. desktopType = DesktopType.remote;
  60. runMultiWindow(
  61. argument,
  62. kAppTypeDesktopRemote,
  63. );
  64. break;
  65. case WindowType.FileTransfer:
  66. desktopType = DesktopType.fileTransfer;
  67. runMultiWindow(
  68. argument,
  69. kAppTypeDesktopFileTransfer,
  70. );
  71. break;
  72. case WindowType.PortForward:
  73. desktopType = DesktopType.portForward;
  74. runMultiWindow(
  75. argument,
  76. kAppTypeDesktopPortForward,
  77. );
  78. break;
  79. default:
  80. break;
  81. }
  82. } else if (args.isNotEmpty && args.first == '--cm') {
  83. debugPrint("--cm started");
  84. desktopType = DesktopType.cm;
  85. await windowManager.ensureInitialized();
  86. runConnectionManagerScreen();
  87. } else if (args.contains('--install')) {
  88. runInstallPage();
  89. } else {
  90. desktopType = DesktopType.main;
  91. await windowManager.ensureInitialized();
  92. windowManager.setPreventClose(true);
  93. if (isMacOS) {
  94. disableWindowMovable(kWindowId);
  95. }
  96. runMainApp(true);
  97. }
  98. }
  99. Future<void> initEnv(String appType) async {
  100. // global shared preference
  101. await platformFFI.init(appType);
  102. // global FFI, use this **ONLY** for global configuration
  103. // for convenience, use global FFI on mobile platform
  104. // focus on multi-ffi on desktop first
  105. await initGlobalFFI();
  106. // await Firebase.initializeApp();
  107. _registerEventHandler();
  108. // Update the system theme.
  109. updateSystemWindowTheme();
  110. }
  111. void runMainApp(bool startService) async {
  112. // register uni links
  113. await initEnv(kAppTypeMain);
  114. // trigger connection status updater
  115. await bind.mainCheckConnectStatus();
  116. if (startService) {
  117. gFFI.serverModel.startService();
  118. bind.pluginSyncUi(syncTo: kAppTypeMain);
  119. bind.pluginListReload();
  120. }
  121. await Future.wait([gFFI.abModel.loadCache(), gFFI.groupModel.loadCache()]);
  122. gFFI.userModel.refreshCurrentUser();
  123. runApp(App());
  124. // Set window option.
  125. WindowOptions windowOptions = getHiddenTitleBarWindowOptions();
  126. windowManager.waitUntilReadyToShow(windowOptions, () async {
  127. // Restore the location of the main window before window hide or show.
  128. await restoreWindowPosition(WindowType.Main);
  129. // Check the startup argument, if we successfully handle the argument, we keep the main window hidden.
  130. final handledByUniLinks = await initUniLinks();
  131. debugPrint("handled by uni links: $handledByUniLinks");
  132. if (handledByUniLinks || handleUriLink(cmdArgs: kBootArgs)) {
  133. windowManager.hide();
  134. } else {
  135. windowManager.show();
  136. windowManager.focus();
  137. // Move registration of active main window here to prevent from async visible check.
  138. rustDeskWinManager.registerActiveWindow(kWindowMainId);
  139. }
  140. windowManager.setOpacity(1);
  141. windowManager.setTitle(getWindowName());
  142. // Do not use `windowManager.setResizable()` here.
  143. setResizable(!bind.isIncomingOnly());
  144. });
  145. }
  146. void runMobileApp() async {
  147. await initEnv(kAppTypeMain);
  148. if (isAndroid) androidChannelInit();
  149. if (isAndroid) platformFFI.syncAndroidServiceAppDirConfigPath();
  150. draggablePositions.load();
  151. await Future.wait([gFFI.abModel.loadCache(), gFFI.groupModel.loadCache()]);
  152. gFFI.userModel.refreshCurrentUser();
  153. runApp(App());
  154. await initUniLinks();
  155. }
  156. void runMultiWindow(
  157. Map<String, dynamic> argument,
  158. String appType,
  159. ) async {
  160. await initEnv(appType);
  161. final title = getWindowName();
  162. // set prevent close to true, we handle close event manually
  163. WindowController.fromWindowId(kWindowId!).setPreventClose(true);
  164. if (isMacOS) {
  165. disableWindowMovable(kWindowId);
  166. }
  167. late Widget widget;
  168. switch (appType) {
  169. case kAppTypeDesktopRemote:
  170. draggablePositions.load();
  171. widget = DesktopRemoteScreen(
  172. params: argument,
  173. );
  174. break;
  175. case kAppTypeDesktopFileTransfer:
  176. widget = DesktopFileTransferScreen(
  177. params: argument,
  178. );
  179. break;
  180. case kAppTypeDesktopPortForward:
  181. widget = DesktopPortForwardScreen(
  182. params: argument,
  183. );
  184. break;
  185. default:
  186. // no such appType
  187. exit(0);
  188. }
  189. _runApp(
  190. title,
  191. widget,
  192. MyTheme.currentThemeMode(),
  193. );
  194. // we do not hide titlebar on win7 because of the frame overflow.
  195. if (kUseCompatibleUiMode) {
  196. WindowController.fromWindowId(kWindowId!).showTitleBar(true);
  197. }
  198. switch (appType) {
  199. case kAppTypeDesktopRemote:
  200. // If screen rect is set, the window will be moved to the target screen and then set fullscreen.
  201. if (argument['screen_rect'] == null) {
  202. // display can be used to control the offset of the window.
  203. await restoreWindowPosition(
  204. WindowType.RemoteDesktop,
  205. windowId: kWindowId!,
  206. peerId: argument['id'] as String?,
  207. display: argument['display'] as int?,
  208. );
  209. }
  210. break;
  211. case kAppTypeDesktopFileTransfer:
  212. await restoreWindowPosition(WindowType.FileTransfer,
  213. windowId: kWindowId!);
  214. break;
  215. case kAppTypeDesktopPortForward:
  216. await restoreWindowPosition(WindowType.PortForward, windowId: kWindowId!);
  217. break;
  218. default:
  219. // no such appType
  220. exit(0);
  221. }
  222. // show window from hidden status
  223. WindowController.fromWindowId(kWindowId!).show();
  224. }
  225. void runConnectionManagerScreen() async {
  226. await initEnv(kAppTypeConnectionManager);
  227. _runApp(
  228. '',
  229. const DesktopServerPage(),
  230. MyTheme.currentThemeMode(),
  231. );
  232. final hide = await bind.cmGetConfig(name: "hide_cm") == 'true';
  233. gFFI.serverModel.hideCm = hide;
  234. if (hide) {
  235. await hideCmWindow(isStartup: true);
  236. } else {
  237. await showCmWindow(isStartup: true);
  238. }
  239. setResizable(false);
  240. // Start the uni links handler and redirect links to Native, not for Flutter.
  241. listenUniLinks(handleByFlutter: false);
  242. }
  243. bool _isCmReadyToShow = false;
  244. showCmWindow({bool isStartup = false}) async {
  245. if (isStartup) {
  246. WindowOptions windowOptions = getHiddenTitleBarWindowOptions(
  247. size: kConnectionManagerWindowSizeClosedChat, alwaysOnTop: true);
  248. await windowManager.waitUntilReadyToShow(windowOptions, null);
  249. bind.mainHideDock();
  250. await Future.wait([
  251. windowManager.show(),
  252. windowManager.focus(),
  253. windowManager.setOpacity(1)
  254. ]);
  255. // ensure initial window size to be changed
  256. await windowManager.setSizeAlignment(
  257. kConnectionManagerWindowSizeClosedChat, Alignment.topRight);
  258. _isCmReadyToShow = true;
  259. } else if (_isCmReadyToShow) {
  260. if (await windowManager.getOpacity() != 1) {
  261. await windowManager.setOpacity(1);
  262. await windowManager.focus();
  263. await windowManager.minimize(); //needed
  264. await windowManager.setSizeAlignment(
  265. kConnectionManagerWindowSizeClosedChat, Alignment.topRight);
  266. windowOnTop(null);
  267. }
  268. }
  269. }
  270. hideCmWindow({bool isStartup = false}) async {
  271. if (isStartup) {
  272. WindowOptions windowOptions = getHiddenTitleBarWindowOptions(
  273. size: kConnectionManagerWindowSizeClosedChat);
  274. windowManager.setOpacity(0);
  275. await windowManager.waitUntilReadyToShow(windowOptions, null);
  276. bind.mainHideDock();
  277. await windowManager.minimize();
  278. await windowManager.hide();
  279. _isCmReadyToShow = true;
  280. } else if (_isCmReadyToShow) {
  281. if (await windowManager.getOpacity() != 0) {
  282. await windowManager.setOpacity(0);
  283. bind.mainHideDock();
  284. await windowManager.minimize();
  285. await windowManager.hide();
  286. }
  287. }
  288. }
  289. void _runApp(
  290. String title,
  291. Widget home,
  292. ThemeMode themeMode,
  293. ) {
  294. final botToastBuilder = BotToastInit();
  295. runApp(RefreshWrapper(
  296. builder: (context) => GetMaterialApp(
  297. navigatorKey: globalKey,
  298. debugShowCheckedModeBanner: false,
  299. title: title,
  300. theme: MyTheme.lightTheme,
  301. darkTheme: MyTheme.darkTheme,
  302. themeMode: themeMode,
  303. home: home,
  304. localizationsDelegates: const [
  305. GlobalMaterialLocalizations.delegate,
  306. GlobalWidgetsLocalizations.delegate,
  307. GlobalCupertinoLocalizations.delegate,
  308. ],
  309. supportedLocales: supportedLocales,
  310. navigatorObservers: [
  311. // FirebaseAnalyticsObserver(analytics: analytics),
  312. BotToastNavigatorObserver(),
  313. ],
  314. builder: (context, child) {
  315. child = _keepScaleBuilder(context, child);
  316. child = botToastBuilder(context, child);
  317. return child;
  318. },
  319. ),
  320. ));
  321. }
  322. void runInstallPage() async {
  323. await windowManager.ensureInitialized();
  324. await initEnv(kAppTypeMain);
  325. _runApp('', const InstallPage(), MyTheme.currentThemeMode());
  326. WindowOptions windowOptions =
  327. getHiddenTitleBarWindowOptions(size: Size(800, 600), center: true);
  328. windowManager.waitUntilReadyToShow(windowOptions, () async {
  329. windowManager.show();
  330. windowManager.focus();
  331. windowManager.setOpacity(1);
  332. windowManager.setAlignment(Alignment.center); // ensure
  333. });
  334. }
  335. WindowOptions getHiddenTitleBarWindowOptions(
  336. {Size? size, bool center = false, bool? alwaysOnTop}) {
  337. var defaultTitleBarStyle = TitleBarStyle.hidden;
  338. // we do not hide titlebar on win7 because of the frame overflow.
  339. if (kUseCompatibleUiMode) {
  340. defaultTitleBarStyle = TitleBarStyle.normal;
  341. }
  342. return WindowOptions(
  343. size: size,
  344. center: center,
  345. backgroundColor: Colors.transparent,
  346. skipTaskbar: false,
  347. titleBarStyle: defaultTitleBarStyle,
  348. alwaysOnTop: alwaysOnTop,
  349. );
  350. }
  351. class App extends StatefulWidget {
  352. @override
  353. State<App> createState() => _AppState();
  354. }
  355. class _AppState extends State<App> with WidgetsBindingObserver {
  356. @override
  357. void initState() {
  358. super.initState();
  359. WidgetsBinding.instance.window.onPlatformBrightnessChanged = () {
  360. final userPreference = MyTheme.getThemeModePreference();
  361. if (userPreference != ThemeMode.system) return;
  362. WidgetsBinding.instance.handlePlatformBrightnessChanged();
  363. final systemIsDark =
  364. WidgetsBinding.instance.platformDispatcher.platformBrightness ==
  365. Brightness.dark;
  366. final ThemeMode to;
  367. if (systemIsDark) {
  368. to = ThemeMode.dark;
  369. } else {
  370. to = ThemeMode.light;
  371. }
  372. Get.changeThemeMode(to);
  373. // Synchronize the window theme of the system.
  374. updateSystemWindowTheme();
  375. if (desktopType == DesktopType.main) {
  376. bind.mainChangeTheme(dark: to.toShortString());
  377. }
  378. };
  379. WidgetsBinding.instance.addObserver(this);
  380. WidgetsBinding.instance.addPostFrameCallback((_) => _updateOrientation());
  381. }
  382. @override
  383. void dispose() {
  384. WidgetsBinding.instance.removeObserver(this);
  385. super.dispose();
  386. }
  387. @override
  388. void didChangeMetrics() {
  389. _updateOrientation();
  390. }
  391. void _updateOrientation() {
  392. if (isDesktop) return;
  393. // Don't use `MediaQuery.of(context).orientation` in `didChangeMetrics()`,
  394. // my test (Flutter 3.19.6, Android 14) is always the reverse value.
  395. // https://github.com/flutter/flutter/issues/60899
  396. // stateGlobal.isPortrait.value =
  397. // MediaQuery.of(context).orientation == Orientation.portrait;
  398. final orientation = View.of(context).physicalSize.aspectRatio > 1
  399. ? Orientation.landscape
  400. : Orientation.portrait;
  401. stateGlobal.isPortrait.value = orientation == Orientation.portrait;
  402. }
  403. @override
  404. Widget build(BuildContext context) {
  405. // final analytics = FirebaseAnalytics.instance;
  406. final botToastBuilder = BotToastInit();
  407. return RefreshWrapper(builder: (context) {
  408. return MultiProvider(
  409. providers: [
  410. // global configuration
  411. // use session related FFI when in remote control or file transfer page
  412. ChangeNotifierProvider.value(value: gFFI.ffiModel),
  413. ChangeNotifierProvider.value(value: gFFI.imageModel),
  414. ChangeNotifierProvider.value(value: gFFI.cursorModel),
  415. ChangeNotifierProvider.value(value: gFFI.canvasModel),
  416. ChangeNotifierProvider.value(value: gFFI.peerTabModel),
  417. ],
  418. child: GetMaterialApp(
  419. navigatorKey: globalKey,
  420. debugShowCheckedModeBanner: false,
  421. title: isWeb
  422. ? '${bind.mainGetAppNameSync()} Web Client V2 (Preview)'
  423. : bind.mainGetAppNameSync(),
  424. theme: MyTheme.lightTheme,
  425. darkTheme: MyTheme.darkTheme,
  426. themeMode: MyTheme.currentThemeMode(),
  427. home: isDesktop
  428. ? const DesktopTabPage()
  429. : isWeb
  430. ? WebHomePage()
  431. : HomePage(),
  432. localizationsDelegates: const [
  433. GlobalMaterialLocalizations.delegate,
  434. GlobalWidgetsLocalizations.delegate,
  435. GlobalCupertinoLocalizations.delegate,
  436. ],
  437. supportedLocales: supportedLocales,
  438. navigatorObservers: [
  439. // FirebaseAnalyticsObserver(analytics: analytics),
  440. BotToastNavigatorObserver(),
  441. ],
  442. builder: isAndroid
  443. ? (context, child) => AccessibilityListener(
  444. child: MediaQuery(
  445. data: MediaQuery.of(context).copyWith(
  446. textScaler: TextScaler.linear(1.0),
  447. ),
  448. child: child ?? Container(),
  449. ),
  450. )
  451. : (context, child) {
  452. child = _keepScaleBuilder(context, child);
  453. child = botToastBuilder(context, child);
  454. if ((isDesktop && desktopType == DesktopType.main) ||
  455. isWebDesktop) {
  456. child = keyListenerBuilder(context, child);
  457. }
  458. if (isLinux) {
  459. child = buildVirtualWindowFrame(context, child);
  460. }
  461. return child;
  462. },
  463. ),
  464. );
  465. });
  466. }
  467. }
  468. Widget _keepScaleBuilder(BuildContext context, Widget? child) {
  469. return MediaQuery(
  470. data: MediaQuery.of(context).copyWith(
  471. textScaler: TextScaler.linear(1.0),
  472. ),
  473. child: child ?? Container(),
  474. );
  475. }
  476. _registerEventHandler() {
  477. if (isDesktop && desktopType != DesktopType.main) {
  478. platformFFI.registerEventHandler('theme', 'theme', (evt) async {
  479. String? dark = evt['dark'];
  480. if (dark != null) {
  481. await MyTheme.changeDarkMode(MyTheme.themeModeFromString(dark));
  482. }
  483. });
  484. platformFFI.registerEventHandler('language', 'language', (_) async {
  485. reloadAllWindows();
  486. });
  487. }
  488. // Register native handlers.
  489. if (isDesktop) {
  490. platformFFI.registerEventHandler('native_ui', 'native_ui', (evt) async {
  491. NativeUiHandler.instance.onEvent(evt);
  492. });
  493. }
  494. }
  495. Widget keyListenerBuilder(BuildContext context, Widget? child) {
  496. return RawKeyboardListener(
  497. focusNode: FocusNode(),
  498. child: child ?? Container(),
  499. onKey: (RawKeyEvent event) {
  500. if (event.logicalKey == LogicalKeyboardKey.shiftLeft) {
  501. if (event is RawKeyDownEvent) {
  502. gFFI.peerTabModel.setShiftDown(true);
  503. } else if (event is RawKeyUpEvent) {
  504. gFFI.peerTabModel.setShiftDown(false);
  505. }
  506. }
  507. },
  508. );
  509. }