model.dart 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:math';
  4. import 'dart:typed_data';
  5. import 'dart:ui' as ui;
  6. import 'package:bot_toast/bot_toast.dart';
  7. import 'package:desktop_multi_window/desktop_multi_window.dart';
  8. import 'package:flutter/gestures.dart';
  9. import 'package:flutter/material.dart';
  10. import 'package:flutter/services.dart';
  11. import 'package:flutter/widgets.dart';
  12. import 'package:flutter_hbb/common/widgets/peers_view.dart';
  13. import 'package:flutter_hbb/consts.dart';
  14. import 'package:flutter_hbb/models/ab_model.dart';
  15. import 'package:flutter_hbb/models/chat_model.dart';
  16. import 'package:flutter_hbb/models/cm_file_model.dart';
  17. import 'package:flutter_hbb/models/file_model.dart';
  18. import 'package:flutter_hbb/models/group_model.dart';
  19. import 'package:flutter_hbb/models/peer_model.dart';
  20. import 'package:flutter_hbb/models/peer_tab_model.dart';
  21. import 'package:flutter_hbb/models/server_model.dart';
  22. import 'package:flutter_hbb/models/user_model.dart';
  23. import 'package:flutter_hbb/models/state_model.dart';
  24. import 'package:flutter_hbb/models/desktop_render_texture.dart';
  25. import 'package:flutter_hbb/plugin/event.dart';
  26. import 'package:flutter_hbb/plugin/manager.dart';
  27. import 'package:flutter_hbb/plugin/widgets/desc_ui.dart';
  28. import 'package:flutter_hbb/common/shared_state.dart';
  29. import 'package:flutter_hbb/utils/multi_window_manager.dart';
  30. import 'package:tuple/tuple.dart';
  31. import 'package:image/image.dart' as img2;
  32. import 'package:flutter_svg/flutter_svg.dart';
  33. import 'package:get/get.dart';
  34. import 'package:uuid/uuid.dart';
  35. import 'package:window_manager/window_manager.dart';
  36. import '../common.dart';
  37. import '../utils/image.dart' as img;
  38. import '../common/widgets/dialog.dart';
  39. import 'input_model.dart';
  40. import 'platform_model.dart';
  41. import 'package:flutter_hbb/generated_bridge.dart'
  42. if (dart.library.html) 'package:flutter_hbb/web/bridge.dart';
  43. import 'package:flutter_hbb/native/custom_cursor.dart'
  44. if (dart.library.html) 'package:flutter_hbb/web/custom_cursor.dart';
  45. typedef HandleMsgBox = Function(Map<String, dynamic> evt, String id);
  46. typedef ReconnectHandle = Function(OverlayDialogManager, SessionID, bool);
  47. final _constSessionId = Uuid().v4obj();
  48. class CachedPeerData {
  49. Map<String, dynamic> updatePrivacyMode = {};
  50. Map<String, dynamic> peerInfo = {};
  51. List<Map<String, dynamic>> cursorDataList = [];
  52. Map<String, dynamic> lastCursorId = {};
  53. Map<String, bool> permissions = {};
  54. bool secure = false;
  55. bool direct = false;
  56. CachedPeerData();
  57. @override
  58. String toString() {
  59. return jsonEncode({
  60. 'updatePrivacyMode': updatePrivacyMode,
  61. 'peerInfo': peerInfo,
  62. 'cursorDataList': cursorDataList,
  63. 'lastCursorId': lastCursorId,
  64. 'permissions': permissions,
  65. 'secure': secure,
  66. 'direct': direct,
  67. });
  68. }
  69. static CachedPeerData? fromString(String s) {
  70. try {
  71. final map = jsonDecode(s);
  72. final data = CachedPeerData();
  73. data.updatePrivacyMode = map['updatePrivacyMode'];
  74. data.peerInfo = map['peerInfo'];
  75. for (final cursorData in map['cursorDataList']) {
  76. data.cursorDataList.add(cursorData);
  77. }
  78. data.lastCursorId = map['lastCursorId'];
  79. map['permissions'].forEach((key, value) {
  80. data.permissions[key] = value;
  81. });
  82. data.secure = map['secure'];
  83. data.direct = map['direct'];
  84. return data;
  85. } catch (e) {
  86. debugPrint('Failed to parse CachedPeerData: $e');
  87. return null;
  88. }
  89. }
  90. }
  91. class FfiModel with ChangeNotifier {
  92. CachedPeerData cachedPeerData = CachedPeerData();
  93. PeerInfo _pi = PeerInfo();
  94. Rect? _rect;
  95. var _inputBlocked = false;
  96. final _permissions = <String, bool>{};
  97. bool? _secure;
  98. bool? _direct;
  99. bool _touchMode = false;
  100. Timer? _timer;
  101. var _reconnects = 1;
  102. bool _viewOnly = false;
  103. WeakReference<FFI> parent;
  104. late final SessionID sessionId;
  105. RxBool waitForImageDialogShow = true.obs;
  106. Timer? waitForImageTimer;
  107. RxBool waitForFirstImage = true.obs;
  108. bool isRefreshing = false;
  109. Rect? get rect => _rect;
  110. bool get isOriginalResolutionSet =>
  111. _pi.tryGetDisplayIfNotAllDisplay()?.isOriginalResolutionSet ?? false;
  112. bool get isVirtualDisplayResolution =>
  113. _pi.tryGetDisplayIfNotAllDisplay()?.isVirtualDisplayResolution ?? false;
  114. bool get isOriginalResolution =>
  115. _pi.tryGetDisplayIfNotAllDisplay()?.isOriginalResolution ?? false;
  116. Map<String, bool> get permissions => _permissions;
  117. setPermissions(Map<String, bool> permissions) {
  118. _permissions.clear();
  119. _permissions.addAll(permissions);
  120. }
  121. bool? get secure => _secure;
  122. bool? get direct => _direct;
  123. PeerInfo get pi => _pi;
  124. bool get inputBlocked => _inputBlocked;
  125. bool get touchMode => _touchMode;
  126. bool get isPeerAndroid => _pi.platform == kPeerPlatformAndroid;
  127. bool get isPeerMobile => isPeerAndroid;
  128. bool get viewOnly => _viewOnly;
  129. set inputBlocked(v) {
  130. _inputBlocked = v;
  131. }
  132. FfiModel(this.parent) {
  133. clear();
  134. sessionId = parent.target!.sessionId;
  135. cachedPeerData.permissions = _permissions;
  136. }
  137. Rect? globalDisplaysRect() => _getDisplaysRect(_pi.displays, true);
  138. Rect? displaysRect() => _getDisplaysRect(_pi.getCurDisplays(), false);
  139. Rect? _getDisplaysRect(List<Display> displays, bool useDisplayScale) {
  140. if (displays.isEmpty) {
  141. return null;
  142. }
  143. int scale(int len, double s) {
  144. if (useDisplayScale) {
  145. return len.toDouble() ~/ s;
  146. } else {
  147. return len;
  148. }
  149. }
  150. double l = displays[0].x;
  151. double t = displays[0].y;
  152. double r = displays[0].x + scale(displays[0].width, displays[0].scale);
  153. double b = displays[0].y + scale(displays[0].height, displays[0].scale);
  154. for (var display in displays.sublist(1)) {
  155. l = min(l, display.x);
  156. t = min(t, display.y);
  157. r = max(r, display.x + scale(display.width, display.scale));
  158. b = max(b, display.y + scale(display.height, display.scale));
  159. }
  160. return Rect.fromLTRB(l, t, r, b);
  161. }
  162. toggleTouchMode() {
  163. if (!isPeerAndroid) {
  164. _touchMode = !_touchMode;
  165. notifyListeners();
  166. }
  167. }
  168. updatePermission(Map<String, dynamic> evt, String id) {
  169. evt.forEach((k, v) {
  170. if (k == 'name' || k.isEmpty) return;
  171. _permissions[k] = v == 'true';
  172. });
  173. // Only inited at remote page
  174. if (parent.target?.connType == ConnType.defaultConn) {
  175. KeyboardEnabledState.find(id).value = _permissions['keyboard'] != false;
  176. }
  177. debugPrint('updatePermission: $_permissions');
  178. notifyListeners();
  179. }
  180. bool get keyboard => _permissions['keyboard'] != false;
  181. clear() {
  182. _pi = PeerInfo();
  183. _secure = null;
  184. _direct = null;
  185. _inputBlocked = false;
  186. _timer?.cancel();
  187. _timer = null;
  188. clearPermissions();
  189. waitForImageTimer?.cancel();
  190. }
  191. setConnectionType(String peerId, bool secure, bool direct) {
  192. cachedPeerData.secure = secure;
  193. cachedPeerData.direct = direct;
  194. _secure = secure;
  195. _direct = direct;
  196. try {
  197. var connectionType = ConnectionTypeState.find(peerId);
  198. connectionType.setSecure(secure);
  199. connectionType.setDirect(direct);
  200. } catch (e) {
  201. //
  202. }
  203. }
  204. Widget? getConnectionImage() {
  205. if (secure == null || direct == null) {
  206. return null;
  207. } else {
  208. final icon =
  209. '${secure == true ? 'secure' : 'insecure'}${direct == true ? '' : '_relay'}';
  210. return SvgPicture.asset('assets/$icon.svg', width: 48, height: 48);
  211. }
  212. }
  213. clearPermissions() {
  214. _inputBlocked = false;
  215. _permissions.clear();
  216. }
  217. handleCachedPeerData(CachedPeerData data, String peerId) async {
  218. handleMsgBox({
  219. 'type': 'success',
  220. 'title': 'Successful',
  221. 'text': kMsgboxTextWaitingForImage,
  222. 'link': '',
  223. }, sessionId, peerId);
  224. updatePrivacyMode(data.updatePrivacyMode, sessionId, peerId);
  225. setConnectionType(peerId, data.secure, data.direct);
  226. await handlePeerInfo(data.peerInfo, peerId, true);
  227. for (final element in data.cursorDataList) {
  228. updateLastCursorId(element);
  229. await handleCursorData(element);
  230. }
  231. if (data.lastCursorId.isNotEmpty) {
  232. updateLastCursorId(data.lastCursorId);
  233. handleCursorId(data.lastCursorId);
  234. }
  235. }
  236. // todo: why called by two position
  237. StreamEventHandler startEventListener(SessionID sessionId, String peerId) {
  238. return (evt) async {
  239. var name = evt['name'];
  240. if (name == 'msgbox') {
  241. handleMsgBox(evt, sessionId, peerId);
  242. } else if (name == 'toast') {
  243. handleToast(evt, sessionId, peerId);
  244. } else if (name == 'set_multiple_windows_session') {
  245. handleMultipleWindowsSession(evt, sessionId, peerId);
  246. } else if (name == 'peer_info') {
  247. handlePeerInfo(evt, peerId, false);
  248. } else if (name == 'sync_peer_info') {
  249. handleSyncPeerInfo(evt, sessionId, peerId);
  250. } else if (name == 'sync_platform_additions') {
  251. handlePlatformAdditions(evt, sessionId, peerId);
  252. } else if (name == 'connection_ready') {
  253. setConnectionType(
  254. peerId, evt['secure'] == 'true', evt['direct'] == 'true');
  255. } else if (name == 'switch_display') {
  256. // switch display is kept for backward compatibility
  257. handleSwitchDisplay(evt, sessionId, peerId);
  258. } else if (name == 'cursor_data') {
  259. updateLastCursorId(evt);
  260. await handleCursorData(evt);
  261. } else if (name == 'cursor_id') {
  262. updateLastCursorId(evt);
  263. handleCursorId(evt);
  264. } else if (name == 'cursor_position') {
  265. await parent.target?.cursorModel.updateCursorPosition(evt, peerId);
  266. } else if (name == 'clipboard') {
  267. Clipboard.setData(ClipboardData(text: evt['content']));
  268. } else if (name == 'permission') {
  269. updatePermission(evt, peerId);
  270. } else if (name == 'chat_client_mode') {
  271. parent.target?.chatModel
  272. .receive(ChatModel.clientModeID, evt['text'] ?? '');
  273. } else if (name == 'chat_server_mode') {
  274. parent.target?.chatModel
  275. .receive(int.parse(evt['id'] as String), evt['text'] ?? '');
  276. } else if (name == 'file_dir') {
  277. parent.target?.fileModel.receiveFileDir(evt);
  278. } else if (name == 'job_progress') {
  279. parent.target?.fileModel.jobController.tryUpdateJobProgress(evt);
  280. } else if (name == 'job_done') {
  281. bool? refresh =
  282. await parent.target?.fileModel.jobController.jobDone(evt);
  283. if (refresh == true) {
  284. // many job done for delete directory
  285. // todo: refresh may not work when confirm delete local directory
  286. parent.target?.fileModel.refreshAll();
  287. }
  288. } else if (name == 'job_error') {
  289. parent.target?.fileModel.jobController.jobError(evt);
  290. } else if (name == 'override_file_confirm') {
  291. parent.target?.fileModel.postOverrideFileConfirm(evt);
  292. } else if (name == 'load_last_job') {
  293. parent.target?.fileModel.jobController.loadLastJob(evt);
  294. } else if (name == 'update_folder_files') {
  295. parent.target?.fileModel.jobController.updateFolderFiles(evt);
  296. } else if (name == 'add_connection') {
  297. parent.target?.serverModel.addConnection(evt);
  298. } else if (name == 'on_client_remove') {
  299. parent.target?.serverModel.onClientRemove(evt);
  300. } else if (name == 'update_quality_status') {
  301. parent.target?.qualityMonitorModel.updateQualityStatus(evt);
  302. } else if (name == 'update_block_input_state') {
  303. updateBlockInputState(evt, peerId);
  304. } else if (name == 'update_privacy_mode') {
  305. updatePrivacyMode(evt, sessionId, peerId);
  306. } else if (name == 'show_elevation') {
  307. final show = evt['show'].toString() == 'true';
  308. parent.target?.serverModel.setShowElevation(show);
  309. } else if (name == 'cancel_msgbox') {
  310. cancelMsgBox(evt, sessionId);
  311. } else if (name == 'switch_back') {
  312. final peer_id = evt['peer_id'].toString();
  313. await bind.sessionSwitchSides(sessionId: sessionId);
  314. closeConnection(id: peer_id);
  315. } else if (name == 'portable_service_running') {
  316. _handlePortableServiceRunning(peerId, evt);
  317. } else if (name == 'on_url_scheme_received') {
  318. // currently comes from "_url" ipc of mac and dbus of linux
  319. onUrlSchemeReceived(evt);
  320. } else if (name == 'on_voice_call_waiting') {
  321. // Waiting for the response from the peer.
  322. parent.target?.chatModel.onVoiceCallWaiting();
  323. } else if (name == 'on_voice_call_started') {
  324. // Voice call is connected.
  325. parent.target?.chatModel.onVoiceCallStarted();
  326. } else if (name == 'on_voice_call_closed') {
  327. // Voice call is closed with reason.
  328. final reason = evt['reason'].toString();
  329. parent.target?.chatModel.onVoiceCallClosed(reason);
  330. } else if (name == 'on_voice_call_incoming') {
  331. // Voice call is requested by the peer.
  332. parent.target?.chatModel.onVoiceCallIncoming();
  333. } else if (name == 'update_voice_call_state') {
  334. parent.target?.serverModel.updateVoiceCallState(evt);
  335. } else if (name == 'fingerprint') {
  336. FingerprintState.find(peerId).value = evt['fingerprint'] ?? '';
  337. } else if (name == 'plugin_manager') {
  338. pluginManager.handleEvent(evt);
  339. } else if (name == 'plugin_event') {
  340. handlePluginEvent(evt,
  341. (Map<String, dynamic> e) => handleMsgBox(e, sessionId, peerId));
  342. } else if (name == 'plugin_reload') {
  343. handleReloading(evt);
  344. } else if (name == 'plugin_option') {
  345. handleOption(evt);
  346. } else if (name == "sync_peer_hash_password_to_personal_ab") {
  347. if (desktopType == DesktopType.main || isWeb || isMobile) {
  348. final id = evt['id'];
  349. final hash = evt['hash'];
  350. if (id != null && hash != null) {
  351. gFFI.abModel
  352. .changePersonalHashPassword(id.toString(), hash.toString());
  353. }
  354. }
  355. } else if (name == "cm_file_transfer_log") {
  356. if (isDesktop) {
  357. gFFI.cmFileModel.onFileTransferLog(evt);
  358. }
  359. } else if (name == 'sync_peer_option') {
  360. _handleSyncPeerOption(evt, peerId);
  361. } else if (name == 'follow_current_display') {
  362. handleFollowCurrentDisplay(evt, sessionId, peerId);
  363. } else if (name == 'use_texture_render') {
  364. _handleUseTextureRender(evt, sessionId, peerId);
  365. } else if (name == "selected_files") {
  366. if (isWeb) {
  367. parent.target?.fileModel.onSelectedFiles(evt);
  368. }
  369. } else if (name == "record_status") {
  370. if (desktopType == DesktopType.remote || isMobile) {
  371. parent.target?.recordingModel.updateStatus(evt['start'] == 'true');
  372. }
  373. } else {
  374. debugPrint('Event is not handled in the fixed branch: $name');
  375. }
  376. };
  377. }
  378. _handleUseTextureRender(
  379. Map<String, dynamic> evt, SessionID sessionId, String peerId) {
  380. parent.target?.imageModel.setUseTextureRender(evt['v'] == 'Y');
  381. waitForFirstImage.value = true;
  382. isRefreshing = true;
  383. showConnectedWaitingForImage(parent.target!.dialogManager, sessionId,
  384. 'success', 'Successful', kMsgboxTextWaitingForImage);
  385. }
  386. _handleSyncPeerOption(Map<String, dynamic> evt, String peer) {
  387. final k = evt['k'];
  388. final v = evt['v'];
  389. if (k == kOptionToggleViewOnly) {
  390. setViewOnly(peer, v as bool);
  391. } else if (k == 'keyboard_mode') {
  392. parent.target?.inputModel.updateKeyboardMode();
  393. } else if (k == 'input_source') {
  394. stateGlobal.getInputSource(force: true);
  395. }
  396. }
  397. onUrlSchemeReceived(Map<String, dynamic> evt) {
  398. final url = evt['url'].toString().trim();
  399. if (url.startsWith(bind.mainUriPrefixSync()) &&
  400. handleUriLink(uriString: url)) {
  401. return;
  402. }
  403. switch (url) {
  404. case kUrlActionClose:
  405. debugPrint("closing all instances");
  406. Future.microtask(() async {
  407. await rustDeskWinManager.closeAllSubWindows();
  408. windowManager.close();
  409. });
  410. break;
  411. default:
  412. windowOnTop(null);
  413. break;
  414. }
  415. }
  416. /// Bind the event listener to receive events from the Rust core.
  417. updateEventListener(SessionID sessionId, String peerId) {
  418. platformFFI.setEventCallback(startEventListener(sessionId, peerId));
  419. }
  420. _handlePortableServiceRunning(String peerId, Map<String, dynamic> evt) {
  421. final running = evt['running'] == 'true';
  422. parent.target?.elevationModel.onPortableServiceRunning(running);
  423. }
  424. handleAliasChanged(Map<String, dynamic> evt) {
  425. if (!(isDesktop || isWebDesktop)) return;
  426. final String peerId = evt['id'];
  427. final String alias = evt['alias'];
  428. String label = getDesktopTabLabel(peerId, alias);
  429. final rxTabLabel = PeerStringOption.find(evt['id'], 'tabLabel');
  430. if (rxTabLabel.value != label) {
  431. rxTabLabel.value = label;
  432. }
  433. }
  434. updateCurDisplay(SessionID sessionId, {updateCursorPos = false}) {
  435. final newRect = displaysRect();
  436. if (newRect == null) {
  437. return;
  438. }
  439. if (newRect != _rect) {
  440. if (newRect.left != _rect?.left || newRect.top != _rect?.top) {
  441. parent.target?.cursorModel.updateDisplayOrigin(
  442. newRect.left, newRect.top,
  443. updateCursorPos: updateCursorPos);
  444. }
  445. _rect = newRect;
  446. parent.target?.canvasModel
  447. .updateViewStyle(refreshMousePos: updateCursorPos);
  448. _updateSessionWidthHeight(sessionId);
  449. }
  450. }
  451. handleSwitchDisplay(
  452. Map<String, dynamic> evt, SessionID sessionId, String peerId) {
  453. final display = int.parse(evt['display']);
  454. if (_pi.currentDisplay != kAllDisplayValue) {
  455. if (bind.peerGetDefaultSessionsCount(id: peerId) > 1) {
  456. if (display != _pi.currentDisplay) {
  457. return;
  458. }
  459. }
  460. if (!_pi.isSupportMultiUiSession) {
  461. _pi.currentDisplay = display;
  462. }
  463. // If `isSupportMultiUiSession` is true, the switch display message should not be used to update current display.
  464. // It is only used to update the display info.
  465. }
  466. var newDisplay = Display();
  467. newDisplay.x = double.tryParse(evt['x']) ?? newDisplay.x;
  468. newDisplay.y = double.tryParse(evt['y']) ?? newDisplay.y;
  469. newDisplay.width = int.tryParse(evt['width']) ?? newDisplay.width;
  470. newDisplay.height = int.tryParse(evt['height']) ?? newDisplay.height;
  471. newDisplay.cursorEmbedded = int.tryParse(evt['cursor_embedded']) == 1;
  472. newDisplay.originalWidth = int.tryParse(
  473. evt['original_width'] ?? kInvalidResolutionValue.toString()) ??
  474. kInvalidResolutionValue;
  475. newDisplay.originalHeight = int.tryParse(
  476. evt['original_height'] ?? kInvalidResolutionValue.toString()) ??
  477. kInvalidResolutionValue;
  478. newDisplay._scale = _pi.scaleOfDisplay(display);
  479. _pi.displays[display] = newDisplay;
  480. if (!_pi.isSupportMultiUiSession || _pi.currentDisplay == display) {
  481. updateCurDisplay(sessionId);
  482. }
  483. if (!_pi.isSupportMultiUiSession) {
  484. try {
  485. CurrentDisplayState.find(peerId).value = display;
  486. } catch (e) {
  487. //
  488. }
  489. }
  490. if (!_pi.isSupportMultiUiSession || _pi.currentDisplay == display) {
  491. handleResolutions(peerId, evt['resolutions']);
  492. }
  493. notifyListeners();
  494. }
  495. cancelMsgBox(Map<String, dynamic> evt, SessionID sessionId) {
  496. if (parent.target == null) return;
  497. final dialogManager = parent.target!.dialogManager;
  498. final tag = '$sessionId-${evt['tag']}';
  499. dialogManager.dismissByTag(tag);
  500. }
  501. handleMultipleWindowsSession(
  502. Map<String, dynamic> evt, SessionID sessionId, String peerId) {
  503. if (parent.target == null) return;
  504. final dialogManager = parent.target!.dialogManager;
  505. final sessions = evt['windows_sessions'];
  506. final title = translate('Multiple Windows sessions found');
  507. final text = translate('Please select the session you want to connect to');
  508. final type = "";
  509. showWindowsSessionsDialog(
  510. type, title, text, dialogManager, sessionId, peerId, sessions);
  511. }
  512. /// Handle the message box event based on [evt] and [id].
  513. handleMsgBox(Map<String, dynamic> evt, SessionID sessionId, String peerId) {
  514. if (parent.target == null) return;
  515. final dialogManager = parent.target!.dialogManager;
  516. final type = evt['type'];
  517. final title = evt['title'];
  518. final text = evt['text'];
  519. final link = evt['link'];
  520. if (type == 're-input-password') {
  521. wrongPasswordDialog(sessionId, dialogManager, type, title, text);
  522. } else if (type == 'input-2fa') {
  523. enter2FaDialog(sessionId, dialogManager);
  524. } else if (type == 'input-password') {
  525. enterPasswordDialog(sessionId, dialogManager);
  526. } else if (type == 'session-login' || type == 'session-re-login') {
  527. enterUserLoginDialog(sessionId, dialogManager);
  528. } else if (type == 'session-login-password' ||
  529. type == 'session-login-password') {
  530. enterUserLoginAndPasswordDialog(sessionId, dialogManager);
  531. } else if (type == 'restarting') {
  532. showMsgBox(sessionId, type, title, text, link, false, dialogManager,
  533. hasCancel: false);
  534. } else if (type == 'wait-remote-accept-nook') {
  535. showWaitAcceptDialog(sessionId, type, title, text, dialogManager);
  536. } else if (type == 'on-uac' || type == 'on-foreground-elevated') {
  537. showOnBlockDialog(sessionId, type, title, text, dialogManager);
  538. } else if (type == 'wait-uac') {
  539. showWaitUacDialog(sessionId, dialogManager, type);
  540. } else if (type == 'elevation-error') {
  541. showElevationError(sessionId, type, title, text, dialogManager);
  542. } else if (type == 'relay-hint' || type == 'relay-hint2') {
  543. showRelayHintDialog(sessionId, type, title, text, dialogManager, peerId);
  544. } else if (text == kMsgboxTextWaitingForImage) {
  545. showConnectedWaitingForImage(dialogManager, sessionId, type, title, text);
  546. } else if (title == 'Privacy mode') {
  547. final hasRetry = evt['hasRetry'] == 'true';
  548. showPrivacyFailedDialog(
  549. sessionId, type, title, text, link, hasRetry, dialogManager);
  550. } else {
  551. final hasRetry = evt['hasRetry'] == 'true';
  552. showMsgBox(sessionId, type, title, text, link, hasRetry, dialogManager);
  553. }
  554. }
  555. handleToast(Map<String, dynamic> evt, SessionID sessionId, String peerId) {
  556. final type = evt['type'] ?? 'info';
  557. final text = evt['text'] ?? '';
  558. final durMsc = evt['dur_msec'] ?? 2000;
  559. final duration = Duration(milliseconds: durMsc);
  560. if ((text).isEmpty) {
  561. BotToast.showLoading(
  562. duration: duration,
  563. clickClose: true,
  564. allowClick: true,
  565. );
  566. } else {
  567. if (type.contains('error')) {
  568. BotToast.showText(
  569. contentColor: Colors.red,
  570. text: translate(text),
  571. duration: duration,
  572. clickClose: true,
  573. onlyOne: true,
  574. );
  575. } else {
  576. BotToast.showText(
  577. text: translate(text),
  578. duration: duration,
  579. clickClose: true,
  580. onlyOne: true,
  581. );
  582. }
  583. }
  584. }
  585. /// Show a message box with [type], [title] and [text].
  586. showMsgBox(SessionID sessionId, String type, String title, String text,
  587. String link, bool hasRetry, OverlayDialogManager dialogManager,
  588. {bool? hasCancel}) {
  589. msgBox(sessionId, type, title, text, link, dialogManager,
  590. hasCancel: hasCancel,
  591. reconnect: hasRetry ? reconnect : null,
  592. reconnectTimeout: hasRetry ? _reconnects : null);
  593. _timer?.cancel();
  594. if (hasRetry) {
  595. _timer = Timer(Duration(seconds: _reconnects), () {
  596. reconnect(dialogManager, sessionId, false);
  597. });
  598. _reconnects *= 2;
  599. } else {
  600. _reconnects = 1;
  601. }
  602. }
  603. void reconnect(OverlayDialogManager dialogManager, SessionID sessionId,
  604. bool forceRelay) {
  605. bind.sessionReconnect(sessionId: sessionId, forceRelay: forceRelay);
  606. clearPermissions();
  607. dialogManager.dismissAll();
  608. dialogManager.showLoading(translate('Connecting...'),
  609. onCancel: closeConnection);
  610. }
  611. void showRelayHintDialog(SessionID sessionId, String type, String title,
  612. String text, OverlayDialogManager dialogManager, String peerId) {
  613. dialogManager.show(tag: '$sessionId-$type', (setState, close, context) {
  614. onClose() {
  615. closeConnection();
  616. close();
  617. }
  618. final style =
  619. ElevatedButton.styleFrom(backgroundColor: Colors.green[700]);
  620. var hint = "\n\n${translate('relay_hint_tip')}";
  621. if (text.contains("10054") || text.contains("104")) {
  622. hint = "";
  623. }
  624. return CustomAlertDialog(
  625. title: null,
  626. content: msgboxContent(type, title, "${translate(text)}$hint"),
  627. actions: [
  628. dialogButton('Close', onPressed: onClose, isOutline: true),
  629. if (type == 'relay-hint')
  630. dialogButton('Connect via relay',
  631. onPressed: () => reconnect(dialogManager, sessionId, true),
  632. buttonStyle: style,
  633. isOutline: true),
  634. dialogButton('Retry',
  635. onPressed: () => reconnect(dialogManager, sessionId, false)),
  636. if (type == 'relay-hint2')
  637. dialogButton('Connect via relay',
  638. onPressed: () => reconnect(dialogManager, sessionId, true),
  639. buttonStyle: style),
  640. ],
  641. onCancel: onClose,
  642. );
  643. });
  644. }
  645. void showConnectedWaitingForImage(OverlayDialogManager dialogManager,
  646. SessionID sessionId, String type, String title, String text) {
  647. onClose() {
  648. closeConnection();
  649. }
  650. if (waitForFirstImage.isFalse) return;
  651. dialogManager.show(
  652. (setState, close, context) => CustomAlertDialog(
  653. title: null,
  654. content: SelectionArea(child: msgboxContent(type, title, text)),
  655. actions: [
  656. dialogButton("Cancel", onPressed: onClose, isOutline: true)
  657. ],
  658. onCancel: onClose),
  659. tag: '$sessionId-waiting-for-image',
  660. );
  661. waitForImageDialogShow.value = true;
  662. waitForImageTimer = Timer(Duration(milliseconds: 1500), () {
  663. if (waitForFirstImage.isTrue && !isRefreshing) {
  664. bind.sessionInputOsPassword(sessionId: sessionId, value: '');
  665. }
  666. });
  667. bind.sessionOnWaitingForImageDialogShow(sessionId: sessionId);
  668. }
  669. void showPrivacyFailedDialog(
  670. SessionID sessionId,
  671. String type,
  672. String title,
  673. String text,
  674. String link,
  675. bool hasRetry,
  676. OverlayDialogManager dialogManager) {
  677. if (text == 'no_need_privacy_mode_no_physical_displays_tip' ||
  678. text == 'Enter privacy mode') {
  679. // There are display changes on the remote side,
  680. // which will cause some messages to refresh the canvas and dismiss dialogs.
  681. // So we add a delay here to ensure the dialog is displayed.
  682. Future.delayed(Duration(milliseconds: 3000), () {
  683. showMsgBox(sessionId, type, title, text, link, hasRetry, dialogManager);
  684. });
  685. } else {
  686. showMsgBox(sessionId, type, title, text, link, hasRetry, dialogManager);
  687. }
  688. }
  689. _updateSessionWidthHeight(SessionID sessionId) {
  690. if (_rect == null) return;
  691. if (_rect!.width <= 0 || _rect!.height <= 0) {
  692. debugPrintStack(
  693. label: 'invalid display size (${_rect!.width},${_rect!.height})');
  694. } else {
  695. final displays = _pi.getCurDisplays();
  696. if (displays.length == 1) {
  697. bind.sessionSetSize(
  698. sessionId: sessionId,
  699. display:
  700. pi.currentDisplay == kAllDisplayValue ? 0 : pi.currentDisplay,
  701. width: _rect!.width.toInt(),
  702. height: _rect!.height.toInt(),
  703. );
  704. } else {
  705. for (int i = 0; i < displays.length; ++i) {
  706. bind.sessionSetSize(
  707. sessionId: sessionId,
  708. display: i,
  709. width: displays[i].width.toInt(),
  710. height: displays[i].height.toInt(),
  711. );
  712. }
  713. }
  714. }
  715. }
  716. /// Handle the peer info event based on [evt].
  717. handlePeerInfo(Map<String, dynamic> evt, String peerId, bool isCache) async {
  718. parent.target?.chatModel.voiceCallStatus.value = VoiceCallStatus.notStarted;
  719. // This call is to ensuer the keyboard mode is updated depending on the peer version.
  720. parent.target?.inputModel.updateKeyboardMode();
  721. // Map clone is required here, otherwise "evt" may be changed by other threads through the reference.
  722. // Because this function is asynchronous, there's an "await" in this function.
  723. cachedPeerData.peerInfo = {...evt};
  724. // Do not cache resolutions, because a new display connection have different resolutions.
  725. cachedPeerData.peerInfo.remove('resolutions');
  726. // Recent peer is updated by handle_peer_info(ui_session_interface.rs) --> handle_peer_info(client.rs) --> save_config(client.rs)
  727. bind.mainLoadRecentPeers();
  728. parent.target?.dialogManager.dismissAll();
  729. _pi.version = evt['version'];
  730. _pi.isSupportMultiUiSession =
  731. bind.isSupportMultiUiSession(version: _pi.version);
  732. _pi.username = evt['username'];
  733. _pi.hostname = evt['hostname'];
  734. _pi.platform = evt['platform'];
  735. _pi.sasEnabled = evt['sas_enabled'] == 'true';
  736. final currentDisplay = int.parse(evt['current_display']);
  737. if (_pi.primaryDisplay == kInvalidDisplayIndex) {
  738. _pi.primaryDisplay = currentDisplay;
  739. }
  740. if (bind.peerGetDefaultSessionsCount(id: peerId) <= 1) {
  741. _pi.currentDisplay = currentDisplay;
  742. }
  743. try {
  744. CurrentDisplayState.find(peerId).value = _pi.currentDisplay;
  745. } catch (e) {
  746. //
  747. }
  748. final connType = parent.target?.connType;
  749. if (isPeerAndroid) {
  750. _touchMode = true;
  751. } else {
  752. _touchMode = await bind.sessionGetOption(
  753. sessionId: sessionId, arg: kOptionTouchMode) !=
  754. '';
  755. }
  756. if (connType == ConnType.fileTransfer) {
  757. parent.target?.fileModel.onReady();
  758. } else if (connType == ConnType.defaultConn) {
  759. List<Display> newDisplays = [];
  760. List<dynamic> displays = json.decode(evt['displays']);
  761. for (int i = 0; i < displays.length; ++i) {
  762. newDisplays.add(evtToDisplay(displays[i]));
  763. }
  764. _pi.displays.value = newDisplays;
  765. _pi.displaysCount.value = _pi.displays.length;
  766. if (_pi.currentDisplay < _pi.displays.length) {
  767. // now replaced to _updateCurDisplay
  768. updateCurDisplay(sessionId);
  769. }
  770. if (displays.isNotEmpty) {
  771. _reconnects = 1;
  772. waitForFirstImage.value = true;
  773. isRefreshing = false;
  774. }
  775. Map<String, dynamic> features = json.decode(evt['features']);
  776. _pi.features.privacyMode = features['privacy_mode'] == true;
  777. if (!isCache) {
  778. handleResolutions(peerId, evt["resolutions"]);
  779. }
  780. parent.target?.elevationModel.onPeerInfo(_pi);
  781. }
  782. if (connType == ConnType.defaultConn) {
  783. setViewOnly(
  784. peerId,
  785. bind.sessionGetToggleOptionSync(
  786. sessionId: sessionId, arg: kOptionToggleViewOnly));
  787. }
  788. if (connType == ConnType.defaultConn) {
  789. final platformAdditions = evt['platform_additions'];
  790. if (platformAdditions != null && platformAdditions != '') {
  791. try {
  792. _pi.platformAdditions = json.decode(platformAdditions);
  793. } catch (e) {
  794. debugPrint('Failed to decode platformAdditions $e');
  795. }
  796. }
  797. }
  798. _pi.isSet.value = true;
  799. stateGlobal.resetLastResolutionGroupValues(peerId);
  800. if (isDesktop || isWebDesktop) {
  801. checkDesktopKeyboardMode();
  802. }
  803. notifyListeners();
  804. if (!isCache) {
  805. tryUseAllMyDisplaysForTheRemoteSession(peerId);
  806. }
  807. }
  808. checkDesktopKeyboardMode() async {
  809. if (isInputSourceFlutter) {
  810. // Local side, flutter keyboard input source
  811. // Currently only map mode is supported, legacy mode is used for compatibility.
  812. for (final mode in [kKeyMapMode, kKeyLegacyMode]) {
  813. if (bind.sessionIsKeyboardModeSupported(
  814. sessionId: sessionId, mode: mode)) {
  815. await bind.sessionSetKeyboardMode(sessionId: sessionId, value: mode);
  816. break;
  817. }
  818. }
  819. } else {
  820. final curMode = await bind.sessionGetKeyboardMode(sessionId: sessionId);
  821. if (curMode != null) {
  822. if (bind.sessionIsKeyboardModeSupported(
  823. sessionId: sessionId, mode: curMode)) {
  824. return;
  825. }
  826. }
  827. // If current keyboard mode is not supported, change to another one.
  828. for (final mode in [kKeyMapMode, kKeyTranslateMode, kKeyLegacyMode]) {
  829. if (bind.sessionIsKeyboardModeSupported(
  830. sessionId: sessionId, mode: mode)) {
  831. bind.sessionSetKeyboardMode(sessionId: sessionId, value: mode);
  832. break;
  833. }
  834. }
  835. }
  836. }
  837. tryUseAllMyDisplaysForTheRemoteSession(String peerId) async {
  838. if (bind.sessionGetUseAllMyDisplaysForTheRemoteSession(
  839. sessionId: sessionId) !=
  840. 'Y') {
  841. return;
  842. }
  843. if (!_pi.isSupportMultiDisplay || _pi.displays.length <= 1) {
  844. return;
  845. }
  846. final screenRectList = await getScreenRectList();
  847. if (screenRectList.length <= 1) {
  848. return;
  849. }
  850. // to-do: peer currentDisplay is the primary display, but the primary display may not be the first display.
  851. // local primary display also may not be the first display.
  852. //
  853. // 0 is assumed to be the primary display here, for now.
  854. // move to the first display and set fullscreen
  855. bind.sessionSwitchDisplay(
  856. isDesktop: isDesktop,
  857. sessionId: sessionId,
  858. value: Int32List.fromList([0]),
  859. );
  860. _pi.currentDisplay = 0;
  861. try {
  862. CurrentDisplayState.find(peerId).value = _pi.currentDisplay;
  863. } catch (e) {
  864. //
  865. }
  866. await tryMoveToScreenAndSetFullscreen(screenRectList[0]);
  867. final length = _pi.displays.length < screenRectList.length
  868. ? _pi.displays.length
  869. : screenRectList.length;
  870. for (var i = 1; i < length; i++) {
  871. openMonitorInNewTabOrWindow(i, peerId, _pi,
  872. screenRect: screenRectList[i]);
  873. }
  874. }
  875. tryShowAndroidActionsOverlay({int delayMSecs = 10}) {
  876. if (isPeerAndroid) {
  877. if (parent.target?.connType == ConnType.defaultConn &&
  878. parent.target != null &&
  879. parent.target!.ffiModel.permissions['keyboard'] != false) {
  880. Timer(Duration(milliseconds: delayMSecs), () {
  881. if (parent.target!.dialogManager.mobileActionsOverlayVisible.isTrue) {
  882. parent.target!.dialogManager
  883. .showMobileActionsOverlay(ffi: parent.target!);
  884. }
  885. });
  886. }
  887. }
  888. }
  889. handleResolutions(String id, dynamic resolutions) {
  890. try {
  891. final resolutionsObj = json.decode(resolutions as String);
  892. late List<dynamic> dynamicArray;
  893. if (resolutionsObj is Map) {
  894. // The web version
  895. dynamicArray = (resolutionsObj as Map<String, dynamic>)['resolutions']
  896. as List<dynamic>;
  897. } else {
  898. // The rust version
  899. dynamicArray = resolutionsObj as List<dynamic>;
  900. }
  901. List<Resolution> arr = List.empty(growable: true);
  902. for (int i = 0; i < dynamicArray.length; i++) {
  903. var width = dynamicArray[i]["width"];
  904. var height = dynamicArray[i]["height"];
  905. if (width is int && width > 0 && height is int && height > 0) {
  906. arr.add(Resolution(width, height));
  907. }
  908. }
  909. arr.sort((a, b) {
  910. if (b.width != a.width) {
  911. return b.width - a.width;
  912. } else {
  913. return b.height - a.height;
  914. }
  915. });
  916. _pi.resolutions = arr;
  917. } catch (e) {
  918. debugPrint("Failed to parse resolutions:$e");
  919. }
  920. }
  921. Display evtToDisplay(Map<String, dynamic> evt) {
  922. var d = Display();
  923. d.x = evt['x']?.toDouble() ?? d.x;
  924. d.y = evt['y']?.toDouble() ?? d.y;
  925. d.width = evt['width'] ?? d.width;
  926. d.height = evt['height'] ?? d.height;
  927. d.cursorEmbedded = evt['cursor_embedded'] == 1;
  928. d.originalWidth = evt['original_width'] ?? kInvalidResolutionValue;
  929. d.originalHeight = evt['original_height'] ?? kInvalidResolutionValue;
  930. double v = (evt['scale']?.toDouble() ?? 100.0) / 100;
  931. d._scale = v > 1.0 ? v : 1.0;
  932. return d;
  933. }
  934. updateLastCursorId(Map<String, dynamic> evt) {
  935. // int.parse(evt['id']) may cause FormatException
  936. // Unhandled Exception: FormatException: Positive input exceeds the limit of integer 18446744071749110741
  937. parent.target?.cursorModel.id = evt['id'];
  938. }
  939. handleCursorId(Map<String, dynamic> evt) {
  940. cachedPeerData.lastCursorId = evt;
  941. parent.target?.cursorModel.updateCursorId(evt);
  942. }
  943. handleCursorData(Map<String, dynamic> evt) async {
  944. cachedPeerData.cursorDataList.add(evt);
  945. await parent.target?.cursorModel.updateCursorData(evt);
  946. }
  947. /// Handle the peer info synchronization event based on [evt].
  948. handleSyncPeerInfo(
  949. Map<String, dynamic> evt, SessionID sessionId, String peerId) async {
  950. if (evt['displays'] != null) {
  951. cachedPeerData.peerInfo['displays'] = evt['displays'];
  952. List<dynamic> displays = json.decode(evt['displays']);
  953. List<Display> newDisplays = [];
  954. for (int i = 0; i < displays.length; ++i) {
  955. newDisplays.add(evtToDisplay(displays[i]));
  956. }
  957. _pi.displays.value = newDisplays;
  958. _pi.displaysCount.value = _pi.displays.length;
  959. if (_pi.currentDisplay == kAllDisplayValue) {
  960. updateCurDisplay(sessionId);
  961. // to-do: What if the displays are changed?
  962. } else {
  963. if (_pi.currentDisplay >= 0 &&
  964. _pi.currentDisplay < _pi.displays.length) {
  965. updateCurDisplay(sessionId);
  966. } else {
  967. if (_pi.displays.isNotEmpty) {
  968. // Notify to switch display
  969. msgBox(sessionId, 'custom-nook-nocancel-hasclose-info', 'Prompt',
  970. 'display_is_plugged_out_msg', '', parent.target!.dialogManager);
  971. final isPeerPrimaryDisplayValid =
  972. pi.primaryDisplay == kInvalidDisplayIndex ||
  973. pi.primaryDisplay >= pi.displays.length;
  974. final newDisplay =
  975. isPeerPrimaryDisplayValid ? 0 : pi.primaryDisplay;
  976. bind.sessionSwitchDisplay(
  977. isDesktop: isDesktop,
  978. sessionId: sessionId,
  979. value: Int32List.fromList([newDisplay]),
  980. );
  981. if (_pi.isSupportMultiUiSession) {
  982. // If the peer supports multi-ui-session, no switch display message will be send back.
  983. // We need to update the display manually.
  984. switchToNewDisplay(newDisplay, sessionId, peerId);
  985. }
  986. } else {
  987. msgBox(sessionId, 'nocancel-error', 'Prompt', 'No Displays', '',
  988. parent.target!.dialogManager);
  989. }
  990. }
  991. }
  992. }
  993. parent.target!.canvasModel
  994. .tryUpdateScrollStyle(Duration(milliseconds: 300), null);
  995. notifyListeners();
  996. }
  997. handlePlatformAdditions(
  998. Map<String, dynamic> evt, SessionID sessionId, String peerId) async {
  999. final updateData = evt['platform_additions'] as String?;
  1000. if (updateData == null) {
  1001. return;
  1002. }
  1003. if (updateData.isEmpty) {
  1004. _pi.platformAdditions.remove(kPlatformAdditionsRustDeskVirtualDisplays);
  1005. _pi.platformAdditions.remove(kPlatformAdditionsAmyuniVirtualDisplays);
  1006. } else {
  1007. try {
  1008. final updateJson = json.decode(updateData) as Map<String, dynamic>;
  1009. for (final key in updateJson.keys) {
  1010. _pi.platformAdditions[key] = updateJson[key];
  1011. }
  1012. if (!updateJson
  1013. .containsKey(kPlatformAdditionsRustDeskVirtualDisplays)) {
  1014. _pi.platformAdditions
  1015. .remove(kPlatformAdditionsRustDeskVirtualDisplays);
  1016. }
  1017. if (!updateJson.containsKey(kPlatformAdditionsAmyuniVirtualDisplays)) {
  1018. _pi.platformAdditions.remove(kPlatformAdditionsAmyuniVirtualDisplays);
  1019. }
  1020. } catch (e) {
  1021. debugPrint('Failed to decode platformAdditions $e');
  1022. }
  1023. }
  1024. cachedPeerData.peerInfo['platform_additions'] =
  1025. json.encode(_pi.platformAdditions);
  1026. }
  1027. handleFollowCurrentDisplay(
  1028. Map<String, dynamic> evt, SessionID sessionId, String peerId) async {
  1029. if (evt['display_idx'] != null) {
  1030. if (pi.currentDisplay == kAllDisplayValue) {
  1031. return;
  1032. }
  1033. _pi.currentDisplay = int.parse(evt['display_idx']);
  1034. try {
  1035. CurrentDisplayState.find(peerId).value = _pi.currentDisplay;
  1036. } catch (e) {
  1037. //
  1038. }
  1039. bind.sessionSwitchDisplay(
  1040. isDesktop: isDesktop,
  1041. sessionId: sessionId,
  1042. value: Int32List.fromList([_pi.currentDisplay]),
  1043. );
  1044. }
  1045. notifyListeners();
  1046. }
  1047. // Directly switch to the new display without waiting for the response.
  1048. switchToNewDisplay(int display, SessionID sessionId, String peerId,
  1049. {bool updateCursorPos = false}) {
  1050. // no need to wait for the response
  1051. pi.currentDisplay = display;
  1052. updateCurDisplay(sessionId, updateCursorPos: updateCursorPos);
  1053. try {
  1054. CurrentDisplayState.find(peerId).value = display;
  1055. } catch (e) {
  1056. //
  1057. }
  1058. }
  1059. updateBlockInputState(Map<String, dynamic> evt, String peerId) {
  1060. _inputBlocked = evt['input_state'] == 'on';
  1061. notifyListeners();
  1062. try {
  1063. BlockInputState.find(peerId).value = evt['input_state'] == 'on';
  1064. } catch (e) {
  1065. //
  1066. }
  1067. }
  1068. updatePrivacyMode(
  1069. Map<String, dynamic> evt, SessionID sessionId, String peerId) async {
  1070. notifyListeners();
  1071. try {
  1072. final isOn = bind.sessionGetToggleOptionSync(
  1073. sessionId: sessionId, arg: 'privacy-mode');
  1074. if (isOn) {
  1075. var privacyModeImpl = await bind.sessionGetOption(
  1076. sessionId: sessionId, arg: 'privacy-mode-impl-key');
  1077. // For compatibility, version < 1.2.4, the default value is 'privacy_mode_impl_mag'.
  1078. final initDefaultPrivacyMode = 'privacy_mode_impl_mag';
  1079. PrivacyModeState.find(peerId).value =
  1080. privacyModeImpl ?? initDefaultPrivacyMode;
  1081. } else {
  1082. PrivacyModeState.find(peerId).value = '';
  1083. }
  1084. } catch (e) {
  1085. //
  1086. }
  1087. }
  1088. void setViewOnly(String id, bool value) {
  1089. if (versionCmp(_pi.version, '1.2.0') < 0) return;
  1090. // tmp fix for https://github.com/rustdesk/rustdesk/pull/3706#issuecomment-1481242389
  1091. // because below rx not used in mobile version, so not initialized, below code will cause crash
  1092. // current our flutter code quality is fucking shit now. !!!!!!!!!!!!!!!!
  1093. try {
  1094. if (value) {
  1095. ShowRemoteCursorState.find(id).value = value;
  1096. } else {
  1097. ShowRemoteCursorState.find(id).value = bind.sessionGetToggleOptionSync(
  1098. sessionId: sessionId, arg: 'show-remote-cursor');
  1099. }
  1100. } catch (e) {
  1101. //
  1102. }
  1103. if (_viewOnly != value) {
  1104. _viewOnly = value;
  1105. notifyListeners();
  1106. }
  1107. }
  1108. }
  1109. class ImageModel with ChangeNotifier {
  1110. ui.Image? _image;
  1111. ui.Image? get image => _image;
  1112. String id = '';
  1113. late final SessionID sessionId;
  1114. bool _useTextureRender = false;
  1115. WeakReference<FFI> parent;
  1116. final List<Function(String)> callbacksOnFirstImage = [];
  1117. ImageModel(this.parent) {
  1118. sessionId = parent.target!.sessionId;
  1119. }
  1120. get useTextureRender => _useTextureRender;
  1121. addCallbackOnFirstImage(Function(String) cb) => callbacksOnFirstImage.add(cb);
  1122. clearImage() => _image = null;
  1123. bool _webDecodingRgba = false;
  1124. final List<Uint8List> _webRgbaList = List.empty(growable: true);
  1125. webOnRgba(int display, Uint8List rgba) async {
  1126. // deep copy needed, otherwise "instantiateCodec failed: TypeError: Cannot perform Construct on a detached ArrayBuffer"
  1127. _webRgbaList.add(Uint8List.fromList(rgba));
  1128. if (_webDecodingRgba) {
  1129. return;
  1130. }
  1131. _webDecodingRgba = true;
  1132. try {
  1133. while (_webRgbaList.isNotEmpty) {
  1134. final rgba2 = _webRgbaList.last;
  1135. _webRgbaList.clear();
  1136. await decodeAndUpdate(display, rgba2);
  1137. }
  1138. } catch (e) {
  1139. debugPrint('onRgba error: $e');
  1140. }
  1141. _webDecodingRgba = false;
  1142. }
  1143. onRgba(int display, Uint8List rgba) async {
  1144. try {
  1145. await decodeAndUpdate(display, rgba);
  1146. } catch (e) {
  1147. debugPrint('onRgba error: $e');
  1148. }
  1149. platformFFI.nextRgba(sessionId, display);
  1150. }
  1151. decodeAndUpdate(int display, Uint8List rgba) async {
  1152. final pid = parent.target?.id;
  1153. final rect = parent.target?.ffiModel.pi.getDisplayRect(display);
  1154. final image = await img.decodeImageFromPixels(
  1155. rgba,
  1156. rect?.width.toInt() ?? 0,
  1157. rect?.height.toInt() ?? 0,
  1158. isWeb ? ui.PixelFormat.rgba8888 : ui.PixelFormat.bgra8888,
  1159. );
  1160. if (parent.target?.id != pid) return;
  1161. await update(image);
  1162. }
  1163. update(ui.Image? image) async {
  1164. if (_image == null && image != null) {
  1165. if (isDesktop || isWebDesktop) {
  1166. await parent.target?.canvasModel.updateViewStyle();
  1167. await parent.target?.canvasModel.updateScrollStyle();
  1168. }
  1169. if (parent.target != null) {
  1170. await initializeCursorAndCanvas(parent.target!);
  1171. }
  1172. }
  1173. _image?.dispose();
  1174. _image = image;
  1175. if (image != null) notifyListeners();
  1176. }
  1177. // mobile only
  1178. double get maxScale {
  1179. if (_image == null) return 1.5;
  1180. final size = parent.target!.canvasModel.getSize();
  1181. final xscale = size.width / _image!.width;
  1182. final yscale = size.height / _image!.height;
  1183. return max(1.5, max(xscale, yscale));
  1184. }
  1185. // mobile only
  1186. double get minScale {
  1187. if (_image == null) return 1.5;
  1188. final size = parent.target!.canvasModel.getSize();
  1189. final xscale = size.width / _image!.width;
  1190. final yscale = size.height / _image!.height;
  1191. return min(xscale, yscale) / 1.5;
  1192. }
  1193. updateUserTextureRender() {
  1194. final preValue = _useTextureRender;
  1195. _useTextureRender = isDesktop && bind.mainGetUseTextureRender();
  1196. if (preValue != _useTextureRender) {
  1197. notifyListeners();
  1198. }
  1199. }
  1200. setUseTextureRender(bool value) {
  1201. _useTextureRender = value;
  1202. notifyListeners();
  1203. }
  1204. void disposeImage() {
  1205. _image?.dispose();
  1206. _image = null;
  1207. }
  1208. }
  1209. enum ScrollStyle {
  1210. scrollbar,
  1211. scrollauto,
  1212. }
  1213. class ViewStyle {
  1214. final String style;
  1215. final double width;
  1216. final double height;
  1217. final int displayWidth;
  1218. final int displayHeight;
  1219. ViewStyle({
  1220. required this.style,
  1221. required this.width,
  1222. required this.height,
  1223. required this.displayWidth,
  1224. required this.displayHeight,
  1225. });
  1226. static defaultViewStyle() {
  1227. final desktop = (isDesktop || isWebDesktop);
  1228. final w =
  1229. desktop ? kDesktopDefaultDisplayWidth : kMobileDefaultDisplayWidth;
  1230. final h =
  1231. desktop ? kDesktopDefaultDisplayHeight : kMobileDefaultDisplayHeight;
  1232. return ViewStyle(
  1233. style: '',
  1234. width: w.toDouble(),
  1235. height: h.toDouble(),
  1236. displayWidth: w,
  1237. displayHeight: h,
  1238. );
  1239. }
  1240. static int _double2Int(double v) => (v * 100).round().toInt();
  1241. @override
  1242. bool operator ==(Object other) =>
  1243. other is ViewStyle &&
  1244. other.runtimeType == runtimeType &&
  1245. _innerEqual(other);
  1246. bool _innerEqual(ViewStyle other) {
  1247. return style == other.style &&
  1248. ViewStyle._double2Int(other.width) == ViewStyle._double2Int(width) &&
  1249. ViewStyle._double2Int(other.height) == ViewStyle._double2Int(height) &&
  1250. other.displayWidth == displayWidth &&
  1251. other.displayHeight == displayHeight;
  1252. }
  1253. @override
  1254. int get hashCode => Object.hash(
  1255. style,
  1256. ViewStyle._double2Int(width),
  1257. ViewStyle._double2Int(height),
  1258. displayWidth,
  1259. displayHeight,
  1260. ).hashCode;
  1261. double get scale {
  1262. double s = 1.0;
  1263. if (style == kRemoteViewStyleAdaptive) {
  1264. if (width != 0 &&
  1265. height != 0 &&
  1266. displayWidth != 0 &&
  1267. displayHeight != 0) {
  1268. final s1 = width / displayWidth;
  1269. final s2 = height / displayHeight;
  1270. s = s1 < s2 ? s1 : s2;
  1271. }
  1272. }
  1273. return s;
  1274. }
  1275. }
  1276. class CanvasModel with ChangeNotifier {
  1277. // image offset of canvas
  1278. double _x = 0;
  1279. // image offset of canvas
  1280. double _y = 0;
  1281. // image scale
  1282. double _scale = 1.0;
  1283. double _devicePixelRatio = 1.0;
  1284. Size _size = Size.zero;
  1285. // the tabbar over the image
  1286. // double tabBarHeight = 0.0;
  1287. // the window border's width
  1288. // double windowBorderWidth = 0.0;
  1289. // remote id
  1290. String id = '';
  1291. late final SessionID sessionId;
  1292. // scroll offset x percent
  1293. double _scrollX = 0.0;
  1294. // scroll offset y percent
  1295. double _scrollY = 0.0;
  1296. ScrollStyle _scrollStyle = ScrollStyle.scrollauto;
  1297. ViewStyle _lastViewStyle = ViewStyle.defaultViewStyle();
  1298. Timer? _timerMobileFocusCanvasCursor;
  1299. // `isMobileCanvasChanged` is used to avoid canvas reset when changing the input method
  1300. // after showing the soft keyboard.
  1301. bool isMobileCanvasChanged = false;
  1302. final ScrollController _horizontal = ScrollController();
  1303. final ScrollController _vertical = ScrollController();
  1304. final _imageOverflow = false.obs;
  1305. WeakReference<FFI> parent;
  1306. CanvasModel(this.parent) {
  1307. sessionId = parent.target!.sessionId;
  1308. }
  1309. double get x => _x;
  1310. double get y => _y;
  1311. double get scale => _scale;
  1312. double get devicePixelRatio => _devicePixelRatio;
  1313. Size get size => _size;
  1314. ScrollStyle get scrollStyle => _scrollStyle;
  1315. ViewStyle get viewStyle => _lastViewStyle;
  1316. RxBool get imageOverflow => _imageOverflow;
  1317. _resetScroll() => setScrollPercent(0.0, 0.0);
  1318. setScrollPercent(double x, double y) {
  1319. _scrollX = x;
  1320. _scrollY = y;
  1321. }
  1322. ScrollController get scrollHorizontal => _horizontal;
  1323. ScrollController get scrollVertical => _vertical;
  1324. double get scrollX => _scrollX;
  1325. double get scrollY => _scrollY;
  1326. static double get leftToEdge =>
  1327. isDesktop ? windowBorderWidth + kDragToResizeAreaPadding.left : 0;
  1328. static double get rightToEdge =>
  1329. isDesktop ? windowBorderWidth + kDragToResizeAreaPadding.right : 0;
  1330. static double get topToEdge => isDesktop
  1331. ? tabBarHeight + windowBorderWidth + kDragToResizeAreaPadding.top
  1332. : 0;
  1333. static double get bottomToEdge =>
  1334. isDesktop ? windowBorderWidth + kDragToResizeAreaPadding.bottom : 0;
  1335. Size getSize() {
  1336. final mediaData = MediaQueryData.fromView(ui.window);
  1337. final size = mediaData.size;
  1338. // If minimized, w or h may be negative here.
  1339. double w = size.width - leftToEdge - rightToEdge;
  1340. double h = size.height - topToEdge - bottomToEdge;
  1341. if (isMobile) {
  1342. h = h -
  1343. mediaData.viewInsets.bottom -
  1344. (parent.target?.cursorModel.keyHelpToolsRectToAdjustCanvas?.bottom ??
  1345. 0);
  1346. }
  1347. return Size(w < 0 ? 0 : w, h < 0 ? 0 : h);
  1348. }
  1349. // mobile only
  1350. double getAdjustY() {
  1351. final bottom =
  1352. parent.target?.cursorModel.keyHelpToolsRectToAdjustCanvas?.bottom ?? 0;
  1353. return max(bottom - MediaQueryData.fromView(ui.window).padding.top, 0);
  1354. }
  1355. updateViewStyle({refreshMousePos = true, notify = true}) async {
  1356. final style = await bind.sessionGetViewStyle(sessionId: sessionId);
  1357. if (style == null) {
  1358. return;
  1359. }
  1360. _size = getSize();
  1361. final displayWidth = getDisplayWidth();
  1362. final displayHeight = getDisplayHeight();
  1363. final viewStyle = ViewStyle(
  1364. style: style,
  1365. width: size.width,
  1366. height: size.height,
  1367. displayWidth: displayWidth,
  1368. displayHeight: displayHeight,
  1369. );
  1370. if (_lastViewStyle == viewStyle) {
  1371. return;
  1372. }
  1373. if (_lastViewStyle.style != viewStyle.style) {
  1374. _resetScroll();
  1375. }
  1376. _lastViewStyle = viewStyle;
  1377. _scale = viewStyle.scale;
  1378. _devicePixelRatio = ui.window.devicePixelRatio;
  1379. if (kIgnoreDpi && style == kRemoteViewStyleOriginal) {
  1380. _scale = 1.0 / _devicePixelRatio;
  1381. }
  1382. _resetCanvasOffset(displayWidth, displayHeight);
  1383. _imageOverflow.value = _x < 0 || y < 0;
  1384. if (notify) {
  1385. notifyListeners();
  1386. }
  1387. if (!isMobile && refreshMousePos) {
  1388. parent.target?.inputModel.refreshMousePos();
  1389. }
  1390. tryUpdateScrollStyle(Duration.zero, style);
  1391. }
  1392. _resetCanvasOffset(int displayWidth, int displayHeight) {
  1393. _x = (size.width - displayWidth * _scale) / 2;
  1394. _y = (size.height - displayHeight * _scale) / 2;
  1395. if (isMobile && _lastViewStyle.style == kRemoteViewStyleOriginal) {
  1396. _moveToCenterCursor();
  1397. }
  1398. }
  1399. tryUpdateScrollStyle(Duration duration, String? style) async {
  1400. if (_scrollStyle != ScrollStyle.scrollbar) return;
  1401. style ??= await bind.sessionGetViewStyle(sessionId: sessionId);
  1402. if (style != kRemoteViewStyleOriginal) {
  1403. return;
  1404. }
  1405. _resetScroll();
  1406. Future.delayed(duration, () async {
  1407. updateScrollPercent();
  1408. });
  1409. }
  1410. updateScrollStyle() async {
  1411. final style = await bind.sessionGetScrollStyle(sessionId: sessionId);
  1412. if (style == kRemoteScrollStyleBar) {
  1413. _scrollStyle = ScrollStyle.scrollbar;
  1414. _resetScroll();
  1415. } else {
  1416. _scrollStyle = ScrollStyle.scrollauto;
  1417. }
  1418. notifyListeners();
  1419. }
  1420. update(double x, double y, double scale) {
  1421. _x = x;
  1422. _y = y;
  1423. _scale = scale;
  1424. notifyListeners();
  1425. }
  1426. bool get cursorEmbedded =>
  1427. parent.target?.ffiModel._pi.cursorEmbedded ?? false;
  1428. int getDisplayWidth() {
  1429. final defaultWidth = (isDesktop || isWebDesktop)
  1430. ? kDesktopDefaultDisplayWidth
  1431. : kMobileDefaultDisplayWidth;
  1432. return parent.target?.ffiModel.rect?.width.toInt() ?? defaultWidth;
  1433. }
  1434. int getDisplayHeight() {
  1435. final defaultHeight = (isDesktop || isWebDesktop)
  1436. ? kDesktopDefaultDisplayHeight
  1437. : kMobileDefaultDisplayHeight;
  1438. return parent.target?.ffiModel.rect?.height.toInt() ?? defaultHeight;
  1439. }
  1440. static double get windowBorderWidth => stateGlobal.windowBorderWidth.value;
  1441. static double get tabBarHeight => stateGlobal.tabBarHeight;
  1442. moveDesktopMouse(double x, double y) {
  1443. if (size.width == 0 || size.height == 0) {
  1444. return;
  1445. }
  1446. // On mobile platforms, move the canvas with the cursor.
  1447. final dw = getDisplayWidth() * _scale;
  1448. final dh = getDisplayHeight() * _scale;
  1449. var dxOffset = 0;
  1450. var dyOffset = 0;
  1451. try {
  1452. if (dw > size.width) {
  1453. dxOffset = (x - dw * (x / size.width) - _x).toInt();
  1454. }
  1455. if (dh > size.height) {
  1456. dyOffset = (y - dh * (y / size.height) - _y).toInt();
  1457. }
  1458. } catch (e) {
  1459. debugPrintStack(
  1460. label:
  1461. '(x,y) ($x,$y), (_x,_y) ($_x,$_y), _scale $_scale, display size (${getDisplayWidth()},${getDisplayHeight()}), size $size, , $e');
  1462. return;
  1463. }
  1464. _x += dxOffset;
  1465. _y += dyOffset;
  1466. if (dxOffset != 0 || dyOffset != 0) {
  1467. notifyListeners();
  1468. }
  1469. // If keyboard is not permitted, do not move cursor when mouse is moving.
  1470. if (parent.target != null && parent.target!.ffiModel.keyboard) {
  1471. // Draw cursor if is not desktop.
  1472. if (!(isDesktop || isWebDesktop)) {
  1473. parent.target!.cursorModel.moveLocal(x, y);
  1474. } else {
  1475. try {
  1476. RemoteCursorMovedState.find(id).value = false;
  1477. } catch (e) {
  1478. //
  1479. }
  1480. }
  1481. }
  1482. }
  1483. set scale(v) {
  1484. _scale = v;
  1485. notifyListeners();
  1486. }
  1487. panX(double dx) {
  1488. _x += dx;
  1489. if (isMobile) {
  1490. isMobileCanvasChanged = true;
  1491. }
  1492. notifyListeners();
  1493. }
  1494. resetOffset() {
  1495. if (isWebDesktop) {
  1496. updateViewStyle();
  1497. } else {
  1498. _resetCanvasOffset(getDisplayWidth(), getDisplayHeight());
  1499. }
  1500. notifyListeners();
  1501. }
  1502. panY(double dy) {
  1503. _y += dy;
  1504. if (isMobile) {
  1505. isMobileCanvasChanged = true;
  1506. }
  1507. notifyListeners();
  1508. }
  1509. // mobile only
  1510. updateScale(double v, Offset focalPoint) {
  1511. if (parent.target?.imageModel.image == null) return;
  1512. final s = _scale;
  1513. _scale *= v;
  1514. final maxs = parent.target?.imageModel.maxScale ?? 1;
  1515. final mins = parent.target?.imageModel.minScale ?? 1;
  1516. if (_scale > maxs) _scale = maxs;
  1517. if (_scale < mins) _scale = mins;
  1518. // (focalPoint.dx - _x_1) / s1 + displayOriginX = (focalPoint.dx - _x_2) / s2 + displayOriginX
  1519. // _x_2 = focalPoint.dx - (focalPoint.dx - _x_1) / s1 * s2
  1520. _x = focalPoint.dx - (focalPoint.dx - _x) / s * _scale;
  1521. final adjust = getAdjustY();
  1522. // (focalPoint.dy - _y_1 - adjust) / s1 + displayOriginY = (focalPoint.dy - _y_2 - adjust) / s2 + displayOriginY
  1523. // _y_2 = focalPoint.dy - adjust - (focalPoint.dy - _y_1 - adjust) / s1 * s2
  1524. _y = focalPoint.dy - adjust - (focalPoint.dy - _y - adjust) / s * _scale;
  1525. if (isMobile) {
  1526. isMobileCanvasChanged = true;
  1527. }
  1528. notifyListeners();
  1529. }
  1530. // For reset canvas to the last view style
  1531. reset() {
  1532. _scale = _lastViewStyle.scale;
  1533. _devicePixelRatio = ui.window.devicePixelRatio;
  1534. if (kIgnoreDpi && _lastViewStyle.style == kRemoteViewStyleOriginal) {
  1535. _scale = 1.0 / _devicePixelRatio;
  1536. }
  1537. _resetCanvasOffset(getDisplayWidth(), getDisplayHeight());
  1538. bind.sessionSetViewStyle(sessionId: sessionId, value: _lastViewStyle.style);
  1539. notifyListeners();
  1540. }
  1541. clear() {
  1542. _x = 0;
  1543. _y = 0;
  1544. _scale = 1.0;
  1545. _lastViewStyle = ViewStyle.defaultViewStyle();
  1546. _timerMobileFocusCanvasCursor?.cancel();
  1547. }
  1548. updateScrollPercent() {
  1549. final percentX = _horizontal.hasClients
  1550. ? _horizontal.position.extentBefore /
  1551. (_horizontal.position.extentBefore +
  1552. _horizontal.position.extentInside +
  1553. _horizontal.position.extentAfter)
  1554. : 0.0;
  1555. final percentY = _vertical.hasClients
  1556. ? _vertical.position.extentBefore /
  1557. (_vertical.position.extentBefore +
  1558. _vertical.position.extentInside +
  1559. _vertical.position.extentAfter)
  1560. : 0.0;
  1561. setScrollPercent(percentX, percentY);
  1562. }
  1563. void mobileFocusCanvasCursor() {
  1564. _timerMobileFocusCanvasCursor?.cancel();
  1565. _timerMobileFocusCanvasCursor =
  1566. Timer(Duration(milliseconds: 100), () async {
  1567. await updateViewStyle(refreshMousePos: false, notify: false);
  1568. notifyListeners();
  1569. });
  1570. }
  1571. // mobile only
  1572. // Move the canvas to make the cursor visible(center) on the screen.
  1573. void _moveToCenterCursor() {
  1574. Rect? imageRect = parent.target?.ffiModel.rect;
  1575. if (imageRect == null) {
  1576. // unreachable
  1577. return;
  1578. }
  1579. final maxX = 0.0;
  1580. final minX = _size.width + (imageRect.left - imageRect.right) * _scale;
  1581. final maxY = 0.0;
  1582. final minY = _size.height + (imageRect.top - imageRect.bottom) * _scale;
  1583. Offset offsetToCenter =
  1584. parent.target?.cursorModel.getCanvasOffsetToCenterCursor() ??
  1585. Offset.zero;
  1586. if (minX < 0) {
  1587. _x = min(max(offsetToCenter.dx, minX), maxX);
  1588. } else {
  1589. // _size.width > (imageRect.right, imageRect.left) * _scale, we should not change _x
  1590. }
  1591. if (minY < 0) {
  1592. _y = min(max(offsetToCenter.dy, minY), maxY);
  1593. } else {
  1594. // _size.height > (imageRect.bottom - imageRect.top) * _scale, , we should not change _y
  1595. }
  1596. }
  1597. }
  1598. // data for cursor
  1599. class CursorData {
  1600. final String peerId;
  1601. final String id;
  1602. final img2.Image image;
  1603. double scale;
  1604. Uint8List? data;
  1605. final double hotxOrigin;
  1606. final double hotyOrigin;
  1607. double hotx;
  1608. double hoty;
  1609. final int width;
  1610. final int height;
  1611. CursorData({
  1612. required this.peerId,
  1613. required this.id,
  1614. required this.image,
  1615. required this.scale,
  1616. required this.data,
  1617. required this.hotxOrigin,
  1618. required this.hotyOrigin,
  1619. required this.width,
  1620. required this.height,
  1621. }) : hotx = hotxOrigin * scale,
  1622. hoty = hotxOrigin * scale;
  1623. int _doubleToInt(double v) => (v * 10e6).round().toInt();
  1624. double _checkUpdateScale(double scale) {
  1625. double oldScale = this.scale;
  1626. if (scale != 1.0) {
  1627. // Update data if scale changed.
  1628. final tgtWidth = (width * scale).toInt();
  1629. final tgtHeight = (width * scale).toInt();
  1630. if (tgtWidth < kMinCursorSize || tgtHeight < kMinCursorSize) {
  1631. double sw = kMinCursorSize.toDouble() / width;
  1632. double sh = kMinCursorSize.toDouble() / height;
  1633. scale = sw < sh ? sh : sw;
  1634. }
  1635. }
  1636. if (_doubleToInt(oldScale) != _doubleToInt(scale)) {
  1637. if (isWindows) {
  1638. data = img2
  1639. .copyResize(
  1640. image,
  1641. width: (width * scale).toInt(),
  1642. height: (height * scale).toInt(),
  1643. interpolation: img2.Interpolation.average,
  1644. )
  1645. .getBytes(order: img2.ChannelOrder.bgra);
  1646. } else {
  1647. data = Uint8List.fromList(
  1648. img2.encodePng(
  1649. img2.copyResize(
  1650. image,
  1651. width: (width * scale).toInt(),
  1652. height: (height * scale).toInt(),
  1653. interpolation: img2.Interpolation.average,
  1654. ),
  1655. ),
  1656. );
  1657. }
  1658. }
  1659. this.scale = scale;
  1660. hotx = hotxOrigin * scale;
  1661. hoty = hotyOrigin * scale;
  1662. return scale;
  1663. }
  1664. String updateGetKey(double scale) {
  1665. scale = _checkUpdateScale(scale);
  1666. return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}';
  1667. }
  1668. }
  1669. const _forbiddenCursorPng =
  1670. 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAAAXNSR0IB2cksfwAAAAlwSFlzAAALEwAACxMBAJqcGAAAAkZQTFRFAAAA2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4G2B4GWAwCAAAAAAAA2B4GAAAAMTExAAAAAAAA2B4G2B4G2B4GAAAAmZmZkZGRAQEBAAAA2B4G2B4G2B4G////oKCgAwMDag8D2B4G2B4G2B4Gra2tBgYGbg8D2B4G2B4Gubm5CQkJTwsCVgwC2B4GxcXFDg4OAAAAAAAA2B4G2B4Gz8/PFBQUAAAAAAAA2B4G2B4G2B4G2B4G2B4G2B4G2B4GDgIA2NjYGxsbAAAAAAAA2B4GFwMB4eHhIyMjAAAAAAAA2B4G6OjoLCwsAAAAAAAA2B4G2B4G2B4G2B4G2B4GCQEA4ODgv7+/iYmJY2NjAgICAAAA9PT0Ojo6AAAAAAAAAAAA+/v7SkpKhYWFr6+vAAAAAAAA8/PzOTk5ERER9fX1KCgoAAAAgYGBKioqAAAAAAAApqamlpaWAAAAAAAAAAAAAAAAAAAAAAAALi4u/v7+GRkZAAAAAAAAAAAAAAAAAAAAfn5+AAAAAAAAV1dXkJCQAAAAAAAAAQEBAAAAAAAAAAAA7Hz6BAAAAMJ0Uk5TAAIWEwEynNz6//fVkCAatP2fDUHs6cDD8d0mPfT5fiEskiIR584A0gejr3AZ+P4plfALf5ZiTL85a4ziD6697fzN3UYE4v/4TwrNHuT///tdRKZh///+1U/ZBv///yjb///eAVL//50Cocv//6oFBbPvpGZCbfT//7cIhv///8INM///zBEcWYSZmO7//////1P////ts/////8vBv//////gv//R/z///QQz9sevP///2waXhNO/+fc//8mev/5gAe2r90MAAAByUlEQVR4nGNggANGJmYWBpyAlY2dg5OTi5uHF6s0H78AJxRwCAphyguLgKRExcQlQLSkFLq8tAwnp6ycPNABjAqKQKNElVDllVU4OVVhVquJA81Q10BRoAkUUYbJa4Edoo0sr6PLqaePLG/AyWlohKTAmJPTBFnelAFoixmSAnNOTgsUeQZLTk4rJAXWnJw2EHlbiDyDPCenHZICe04HFrh+RydnBgYWPU5uJAWinJwucPNd3dw9GDw5Ob2QFHBzcnrD7ffx9fMPCOTkDEINhmC4+3x8Q0LDwlEDIoKTMzIKKg9SEBIdE8sZh6SAJZ6Tkx0qD1YQkpCYlIwclCng0AXLQxSEpKalZyCryATKZwkhKQjJzsnNQ1KQXwBUUVhUXBJYWgZREFJeUVmFpMKlWg+anmqgCkJq6+obkG1pLEBTENLU3NKKrIKhrb2js8u4G6Kgpze0r3/CRAZMAHbkpJDJU6ZMmTqtFbuC6TNmhsyaMnsOFlmwgrnzpsxfELJwEXZ5Bp/FS3yWLlsesmLlKuwKVk9Ys5Zh3foN0zduwq5g85atDAzbpqSGbN9RhV0FGOzctWH3lD14FOzdt3H/gQw8Cg4u2gQPAwBYDXXdIH+wqAAAAABJRU5ErkJggg==';
  1671. const _defaultCursorPng =
  1672. 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARzQklUCAgICHwIZIgAAAFmSURBVFiF7dWxSlxREMbx34QFDRowYBchZSxSCWlMCOwD5FGEFHap06UI7KPsAyyEEIQFqxRaCqYTsqCJFsKkuAeRXb17wrqV918dztw55zszc2fo6Oh47MR/e3zO1/iAHWmznHKGQwx9ip/LEbCfazbsoY8j/JLOhcC6sCW9wsjEwJf483AC9nPNc1+lFRwI13d+l3rYFS799rFGxJMqARv2pBXh+72XQ7gWvklPS7TmMl9Ak/M+DqrENvxAv/guKKApuKPWl0/TROK4+LbSqzhuB+OZ3fRSeFPWY+Fkyn56Y29hfgTSpnQ+s98cvorVey66uPlNFxKwZOYLCGfCs5n9NMYVrsp6mvXSoFqpqYFDvMBkStgJJe93dZOwVXxbqUnBENulydSReqUrDhcX0PT2EXarBYS3GNXMhboinBgIl9K71kg0L3+PvyYGdVpruT2MwrF0iotiXfIwus0Dj+OOjo6Of+e7ab74RkpgAAAAAElFTkSuQmCC';
  1673. const kPreForbiddenCursorId = "-2";
  1674. final preForbiddenCursor = PredefinedCursor(
  1675. png: _forbiddenCursorPng,
  1676. id: kPreForbiddenCursorId,
  1677. );
  1678. const kPreDefaultCursorId = "-1";
  1679. final preDefaultCursor = PredefinedCursor(
  1680. png: _defaultCursorPng,
  1681. id: kPreDefaultCursorId,
  1682. hotxGetter: (double w) => w / 2,
  1683. hotyGetter: (double h) => h / 2,
  1684. );
  1685. class PredefinedCursor {
  1686. ui.Image? _image;
  1687. img2.Image? _image2;
  1688. CursorData? _cache;
  1689. String png;
  1690. String id;
  1691. double Function(double)? hotxGetter;
  1692. double Function(double)? hotyGetter;
  1693. PredefinedCursor(
  1694. {required this.png, required this.id, this.hotxGetter, this.hotyGetter}) {
  1695. init();
  1696. }
  1697. ui.Image? get image => _image;
  1698. CursorData? get cache => _cache;
  1699. init() {
  1700. _image2 = img2.decodePng(base64Decode(png));
  1701. if (_image2 != null) {
  1702. // The png type of forbidden cursor image is `PngColorType.indexed`.
  1703. if (id == kPreForbiddenCursorId) {
  1704. _image2 = _image2!.convert(format: img2.Format.uint8, numChannels: 4);
  1705. }
  1706. () async {
  1707. final defaultImg = _image2!;
  1708. // This function is called only one time, no need to care about the performance.
  1709. Uint8List data = defaultImg.getBytes(order: img2.ChannelOrder.rgba);
  1710. _image?.dispose();
  1711. _image = await img.decodeImageFromPixels(
  1712. data, defaultImg.width, defaultImg.height, ui.PixelFormat.rgba8888);
  1713. if (_image == null) {
  1714. print("decodeImageFromPixels failed, pre-defined cursor $id");
  1715. return;
  1716. }
  1717. double scale = 1.0;
  1718. if (isWindows) {
  1719. data = _image2!.getBytes(order: img2.ChannelOrder.bgra);
  1720. } else {
  1721. data = Uint8List.fromList(img2.encodePng(_image2!));
  1722. }
  1723. _cache = CursorData(
  1724. peerId: '',
  1725. id: id,
  1726. image: _image2!.clone(),
  1727. scale: scale,
  1728. data: data,
  1729. hotxOrigin:
  1730. hotxGetter != null ? hotxGetter!(_image2!.width.toDouble()) : 0,
  1731. hotyOrigin:
  1732. hotyGetter != null ? hotyGetter!(_image2!.height.toDouble()) : 0,
  1733. width: _image2!.width,
  1734. height: _image2!.height,
  1735. );
  1736. }();
  1737. }
  1738. }
  1739. }
  1740. class CursorModel with ChangeNotifier {
  1741. ui.Image? _image;
  1742. final _images = <String, Tuple3<ui.Image, double, double>>{};
  1743. CursorData? _cache;
  1744. final _cacheMap = <String, CursorData>{};
  1745. final _cacheKeys = <String>{};
  1746. double _x = -10000;
  1747. double _y = -10000;
  1748. // int.parse(evt['id']) may cause FormatException
  1749. // So we use String here.
  1750. String _id = "-1";
  1751. double _hotx = 0;
  1752. double _hoty = 0;
  1753. double _displayOriginX = 0;
  1754. double _displayOriginY = 0;
  1755. DateTime? _firstUpdateMouseTime;
  1756. Rect? _windowRect;
  1757. List<RemoteWindowCoords> _remoteWindowCoords = [];
  1758. bool gotMouseControl = true;
  1759. DateTime _lastPeerMouse = DateTime.now()
  1760. .subtract(Duration(milliseconds: 3000 * kMouseControlTimeoutMSec));
  1761. String peerId = '';
  1762. WeakReference<FFI> parent;
  1763. // Only for mobile, touch mode
  1764. // To block touch event above the KeyHelpTools
  1765. //
  1766. // A better way is to not listen events from the KeyHelpTools.
  1767. // But we're now using a Container(child: Stack(...)) to wrap the KeyHelpTools,
  1768. // and the listener is on the Container.
  1769. Rect? _keyHelpToolsRect;
  1770. // `lastIsBlocked` is only used in common/widgets/remote_input.dart -> _RawTouchGestureDetectorRegionState -> onDoubleTap()
  1771. // Because onDoubleTap() doesn't have the `event` parameter, we can't get the touch event's position.
  1772. bool _lastIsBlocked = false;
  1773. bool _lastKeyboardIsVisible = false;
  1774. bool get lastKeyboardIsVisible => _lastKeyboardIsVisible;
  1775. Rect? get keyHelpToolsRectToAdjustCanvas =>
  1776. _lastKeyboardIsVisible ? _keyHelpToolsRect : null;
  1777. keyHelpToolsVisibilityChanged(Rect? r, bool keyboardIsVisible) {
  1778. _keyHelpToolsRect = r;
  1779. if (r == null) {
  1780. _lastIsBlocked = false;
  1781. } else {
  1782. // Block the touch event is safe here.
  1783. // `lastIsBlocked` is only used in onDoubleTap() to block the touch event from the KeyHelpTools.
  1784. // `lastIsBlocked` will be set when the cursor is moving or touch somewhere else.
  1785. _lastIsBlocked = true;
  1786. }
  1787. if (isMobile && _lastKeyboardIsVisible != keyboardIsVisible) {
  1788. parent.target?.canvasModel.mobileFocusCanvasCursor();
  1789. parent.target?.canvasModel.isMobileCanvasChanged = false;
  1790. }
  1791. _lastKeyboardIsVisible = keyboardIsVisible;
  1792. }
  1793. get lastIsBlocked => _lastIsBlocked;
  1794. ui.Image? get image => _image;
  1795. CursorData? get cache => _cache;
  1796. double get x => _x - _displayOriginX;
  1797. double get y => _y - _displayOriginY;
  1798. double get devicePixelRatio => parent.target!.canvasModel.devicePixelRatio;
  1799. Offset get offset => Offset(_x, _y);
  1800. double get hotx => _hotx;
  1801. double get hoty => _hoty;
  1802. set id(String id) => _id = id;
  1803. bool get isPeerControlProtected =>
  1804. DateTime.now().difference(_lastPeerMouse).inMilliseconds <
  1805. kMouseControlTimeoutMSec;
  1806. bool isConnIn2Secs() {
  1807. if (_firstUpdateMouseTime == null) {
  1808. _firstUpdateMouseTime = DateTime.now();
  1809. return true;
  1810. } else {
  1811. return DateTime.now().difference(_firstUpdateMouseTime!).inSeconds < 2;
  1812. }
  1813. }
  1814. CursorModel(this.parent);
  1815. Set<String> get cachedKeys => _cacheKeys;
  1816. addKey(String key) => _cacheKeys.add(key);
  1817. // remote physical display coordinate
  1818. // For update pan (mobile), onOneFingerPanStart, onOneFingerPanUpdate, onHoldDragUpdate
  1819. Rect getVisibleRect() {
  1820. final size = parent.target?.canvasModel.getSize() ??
  1821. MediaQueryData.fromView(ui.window).size;
  1822. final xoffset = parent.target?.canvasModel.x ?? 0;
  1823. final yoffset = parent.target?.canvasModel.y ?? 0;
  1824. final scale = parent.target?.canvasModel.scale ?? 1;
  1825. final x0 = _displayOriginX - xoffset / scale;
  1826. final y0 = _displayOriginY - yoffset / scale;
  1827. return Rect.fromLTWH(x0, y0, size.width / scale, size.height / scale);
  1828. }
  1829. Offset getCanvasOffsetToCenterCursor() {
  1830. // Cursor should be at the center of the visible rect.
  1831. // _x = rect.left + rect.width / 2
  1832. // _y = rect.right + rect.height / 2
  1833. // See `getVisibleRect()`
  1834. // _x = _displayOriginX - xoffset / scale + size.width / scale * 0.5;
  1835. // _y = _displayOriginY - yoffset / scale + size.height / scale * 0.5;
  1836. final size = parent.target?.canvasModel.getSize() ??
  1837. MediaQueryData.fromView(ui.window).size;
  1838. final xoffset = (_displayOriginX - _x) * scale + size.width * 0.5;
  1839. final yoffset = (_displayOriginY - _y) * scale + size.height * 0.5;
  1840. return Offset(xoffset, yoffset);
  1841. }
  1842. get scale => parent.target?.canvasModel.scale ?? 1.0;
  1843. // mobile Soft keyboard, block touch event from the KeyHelpTools
  1844. shouldBlock(double x, double y) {
  1845. if (!(parent.target?.ffiModel.touchMode ?? false)) {
  1846. return false;
  1847. }
  1848. if (_keyHelpToolsRect == null) {
  1849. return false;
  1850. }
  1851. if (isPointInRect(Offset(x, y), _keyHelpToolsRect!)) {
  1852. return true;
  1853. }
  1854. return false;
  1855. }
  1856. // For touch mode
  1857. Future<bool> move(double x, double y) async {
  1858. if (shouldBlock(x, y)) {
  1859. _lastIsBlocked = true;
  1860. return false;
  1861. }
  1862. _lastIsBlocked = false;
  1863. if (!_moveLocalIfInRemoteRect(x, y)) {
  1864. return false;
  1865. }
  1866. await parent.target?.inputModel.moveMouse(_x, _y);
  1867. return true;
  1868. }
  1869. bool isInRemoteRect(Offset offset) {
  1870. return getRemotePosInRect(offset) != null;
  1871. }
  1872. Offset? getRemotePosInRect(Offset offset) {
  1873. final adjust = parent.target?.canvasModel.getAdjustY() ?? 0;
  1874. final newPos = _getNewPos(offset.dx, offset.dy, adjust);
  1875. final visibleRect = getVisibleRect();
  1876. if (!isPointInRect(newPos, visibleRect)) {
  1877. return null;
  1878. }
  1879. final rect = parent.target?.ffiModel.rect;
  1880. if (rect != null) {
  1881. if (!isPointInRect(newPos, rect)) {
  1882. return null;
  1883. }
  1884. }
  1885. return newPos;
  1886. }
  1887. Offset _getNewPos(double x, double y, double adjust) {
  1888. final xoffset = parent.target?.canvasModel.x ?? 0;
  1889. final yoffset = parent.target?.canvasModel.y ?? 0;
  1890. final newX = (x - xoffset) / scale + _displayOriginX;
  1891. final newY = (y - yoffset - adjust) / scale + _displayOriginY;
  1892. return Offset(newX, newY);
  1893. }
  1894. bool _moveLocalIfInRemoteRect(double x, double y) {
  1895. final newPos = getRemotePosInRect(Offset(x, y));
  1896. if (newPos == null) {
  1897. return false;
  1898. }
  1899. _x = newPos.dx;
  1900. _y = newPos.dy;
  1901. notifyListeners();
  1902. return true;
  1903. }
  1904. moveLocal(double x, double y, {double adjust = 0}) {
  1905. final newPos = _getNewPos(x, y, adjust);
  1906. _x = newPos.dx;
  1907. _y = newPos.dy;
  1908. notifyListeners();
  1909. }
  1910. reset() {
  1911. _x = _displayOriginX;
  1912. _y = _displayOriginY;
  1913. parent.target?.inputModel.moveMouse(_x, _y);
  1914. parent.target?.canvasModel.reset();
  1915. notifyListeners();
  1916. }
  1917. updatePan(Offset delta, Offset localPosition, bool touchMode) async {
  1918. if (touchMode) {
  1919. await _handleTouchMode(delta, localPosition);
  1920. return;
  1921. }
  1922. double dx = delta.dx;
  1923. double dy = delta.dy;
  1924. if (parent.target?.imageModel.image == null) return;
  1925. final scale = parent.target?.canvasModel.scale ?? 1.0;
  1926. dx /= scale;
  1927. dy /= scale;
  1928. final r = getVisibleRect();
  1929. var cx = r.center.dx;
  1930. var cy = r.center.dy;
  1931. var tryMoveCanvasX = false;
  1932. if (dx > 0) {
  1933. final maxCanvasCanMove = _displayOriginX +
  1934. (parent.target?.imageModel.image!.width ?? 1280) -
  1935. r.right.roundToDouble();
  1936. tryMoveCanvasX = _x + dx > cx && maxCanvasCanMove > 0;
  1937. if (tryMoveCanvasX) {
  1938. dx = min(dx, maxCanvasCanMove);
  1939. } else {
  1940. final maxCursorCanMove = r.right - _x;
  1941. dx = min(dx, maxCursorCanMove);
  1942. }
  1943. } else if (dx < 0) {
  1944. final maxCanvasCanMove = _displayOriginX - r.left.roundToDouble();
  1945. tryMoveCanvasX = _x + dx < cx && maxCanvasCanMove < 0;
  1946. if (tryMoveCanvasX) {
  1947. dx = max(dx, maxCanvasCanMove);
  1948. } else {
  1949. final maxCursorCanMove = r.left - _x;
  1950. dx = max(dx, maxCursorCanMove);
  1951. }
  1952. }
  1953. var tryMoveCanvasY = false;
  1954. if (dy > 0) {
  1955. final mayCanvasCanMove = _displayOriginY +
  1956. (parent.target?.imageModel.image!.height ?? 720) -
  1957. r.bottom.roundToDouble();
  1958. tryMoveCanvasY = _y + dy > cy && mayCanvasCanMove > 0;
  1959. if (tryMoveCanvasY) {
  1960. dy = min(dy, mayCanvasCanMove);
  1961. } else {
  1962. final mayCursorCanMove = r.bottom - _y;
  1963. dy = min(dy, mayCursorCanMove);
  1964. }
  1965. } else if (dy < 0) {
  1966. final mayCanvasCanMove = _displayOriginY - r.top.roundToDouble();
  1967. tryMoveCanvasY = _y + dy < cy && mayCanvasCanMove < 0;
  1968. if (tryMoveCanvasY) {
  1969. dy = max(dy, mayCanvasCanMove);
  1970. } else {
  1971. final mayCursorCanMove = r.top - _y;
  1972. dy = max(dy, mayCursorCanMove);
  1973. }
  1974. }
  1975. if (dx == 0 && dy == 0) return;
  1976. Point? newPos;
  1977. final rect = parent.target?.ffiModel.rect;
  1978. if (rect == null) {
  1979. // unreachable
  1980. return;
  1981. }
  1982. newPos = InputModel.getPointInRemoteRect(
  1983. false,
  1984. parent.target?.ffiModel.pi.platform,
  1985. kPointerEventKindMouse,
  1986. kMouseEventTypeDefault,
  1987. (_x + dx).toInt(),
  1988. (_y + dy).toInt(),
  1989. rect,
  1990. buttons: kPrimaryButton);
  1991. if (newPos == null) {
  1992. return;
  1993. }
  1994. dx = newPos.x - _x;
  1995. dy = newPos.y - _y;
  1996. _x = newPos.x.toDouble();
  1997. _y = newPos.y.toDouble();
  1998. if (tryMoveCanvasX && dx != 0) {
  1999. parent.target?.canvasModel.panX(-dx * scale);
  2000. }
  2001. if (tryMoveCanvasY && dy != 0) {
  2002. parent.target?.canvasModel.panY(-dy * scale);
  2003. }
  2004. parent.target?.inputModel.moveMouse(_x, _y);
  2005. notifyListeners();
  2006. }
  2007. bool _isInCurrentWindow(double x, double y) {
  2008. final w = _windowRect!.width / devicePixelRatio;
  2009. final h = _windowRect!.width / devicePixelRatio;
  2010. return x >= 0 && y >= 0 && x <= w && y <= h;
  2011. }
  2012. _handleTouchMode(Offset delta, Offset localPosition) async {
  2013. bool isMoved = false;
  2014. if (_remoteWindowCoords.isNotEmpty &&
  2015. _windowRect != null &&
  2016. !_isInCurrentWindow(localPosition.dx, localPosition.dy)) {
  2017. final coords = InputModel.findRemoteCoords(localPosition.dx,
  2018. localPosition.dy, _remoteWindowCoords, devicePixelRatio);
  2019. if (coords != null) {
  2020. double x2 =
  2021. (localPosition.dx - coords.relativeOffset.dx / devicePixelRatio) /
  2022. coords.canvas.scale;
  2023. double y2 =
  2024. (localPosition.dy - coords.relativeOffset.dy / devicePixelRatio) /
  2025. coords.canvas.scale;
  2026. x2 += coords.cursor.offset.dx;
  2027. y2 += coords.cursor.offset.dy;
  2028. await parent.target?.inputModel.moveMouse(x2, y2);
  2029. isMoved = true;
  2030. }
  2031. }
  2032. if (!isMoved) {
  2033. final rect = parent.target?.ffiModel.rect;
  2034. if (rect == null) {
  2035. // unreachable
  2036. return;
  2037. }
  2038. Offset? movementInRect(double x, double y, Rect r) {
  2039. final isXInRect = x >= r.left && x <= r.right;
  2040. final isYInRect = y >= r.top && y <= r.bottom;
  2041. if (!(isXInRect || isYInRect)) {
  2042. return null;
  2043. }
  2044. if (x < r.left) {
  2045. x = r.left;
  2046. } else if (x > r.right) {
  2047. x = r.right;
  2048. }
  2049. if (y < r.top) {
  2050. y = r.top;
  2051. } else if (y > r.bottom) {
  2052. y = r.bottom;
  2053. }
  2054. return Offset(x, y);
  2055. }
  2056. final scale = parent.target?.canvasModel.scale ?? 1.0;
  2057. var movement =
  2058. movementInRect(_x + delta.dx / scale, _y + delta.dy / scale, rect);
  2059. if (movement == null) {
  2060. return;
  2061. }
  2062. movement = movementInRect(movement.dx, movement.dy, getVisibleRect());
  2063. if (movement == null) {
  2064. return;
  2065. }
  2066. _x = movement.dx;
  2067. _y = movement.dy;
  2068. await parent.target?.inputModel.moveMouse(_x, _y);
  2069. }
  2070. notifyListeners();
  2071. }
  2072. disposeImages() {
  2073. _images.forEach((_, v) => v.item1.dispose());
  2074. _images.clear();
  2075. }
  2076. updateCursorData(Map<String, dynamic> evt) async {
  2077. final id = evt['id'];
  2078. final hotx = double.parse(evt['hotx']);
  2079. final hoty = double.parse(evt['hoty']);
  2080. final width = int.parse(evt['width']);
  2081. final height = int.parse(evt['height']);
  2082. List<dynamic> colors = json.decode(evt['colors']);
  2083. final rgba = Uint8List.fromList(colors.map((s) => s as int).toList());
  2084. final image = await img.decodeImageFromPixels(
  2085. rgba, width, height, ui.PixelFormat.rgba8888);
  2086. if (image == null) {
  2087. return;
  2088. }
  2089. if (await _updateCache(rgba, image, id, hotx, hoty, width, height)) {
  2090. _images[id]?.item1.dispose();
  2091. _images[id] = Tuple3(image, hotx, hoty);
  2092. }
  2093. // Update last cursor data.
  2094. // Do not use the previous `image` and `id`, because `_id` may be changed.
  2095. _updateCurData();
  2096. }
  2097. Future<bool> _updateCache(
  2098. Uint8List rgba,
  2099. ui.Image image,
  2100. String id,
  2101. double hotx,
  2102. double hoty,
  2103. int w,
  2104. int h,
  2105. ) async {
  2106. Uint8List? data;
  2107. img2.Image imgOrigin = img2.Image.fromBytes(
  2108. width: w, height: h, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
  2109. if (isWindows) {
  2110. data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
  2111. } else {
  2112. ByteData? imgBytes =
  2113. await image.toByteData(format: ui.ImageByteFormat.png);
  2114. if (imgBytes == null) {
  2115. return false;
  2116. }
  2117. data = imgBytes.buffer.asUint8List();
  2118. }
  2119. final cache = CursorData(
  2120. peerId: peerId,
  2121. id: id,
  2122. image: imgOrigin,
  2123. scale: 1.0,
  2124. data: data,
  2125. hotxOrigin: hotx,
  2126. hotyOrigin: hoty,
  2127. width: w,
  2128. height: h,
  2129. );
  2130. _cacheMap[id] = cache;
  2131. return true;
  2132. }
  2133. bool _updateCurData() {
  2134. _cache = _cacheMap[_id];
  2135. final tmp = _images[_id];
  2136. if (tmp != null) {
  2137. _image = tmp.item1;
  2138. _hotx = tmp.item2;
  2139. _hoty = tmp.item3;
  2140. try {
  2141. // may throw exception, because the listener maybe already dispose
  2142. notifyListeners();
  2143. } catch (e) {
  2144. debugPrint(
  2145. 'WARNING: updateCursorId $_id, without notifyListeners(). $e');
  2146. }
  2147. return true;
  2148. } else {
  2149. return false;
  2150. }
  2151. }
  2152. updateCursorId(Map<String, dynamic> evt) {
  2153. if (!_updateCurData()) {
  2154. debugPrint(
  2155. 'WARNING: updateCursorId $_id, cache is ${_cache == null ? "null" : "not null"}. without notifyListeners()');
  2156. }
  2157. }
  2158. /// Update the cursor position.
  2159. updateCursorPosition(Map<String, dynamic> evt, String id) async {
  2160. if (!isConnIn2Secs()) {
  2161. gotMouseControl = false;
  2162. _lastPeerMouse = DateTime.now();
  2163. }
  2164. _x = double.parse(evt['x']);
  2165. _y = double.parse(evt['y']);
  2166. try {
  2167. RemoteCursorMovedState.find(id).value = true;
  2168. } catch (e) {
  2169. //
  2170. }
  2171. notifyListeners();
  2172. }
  2173. updateDisplayOrigin(double x, double y, {updateCursorPos = true}) {
  2174. _displayOriginX = x;
  2175. _displayOriginY = y;
  2176. if (updateCursorPos) {
  2177. _x = x + 1;
  2178. _y = y + 1;
  2179. parent.target?.inputModel.moveMouse(x, y);
  2180. }
  2181. parent.target?.canvasModel.resetOffset();
  2182. notifyListeners();
  2183. }
  2184. updateDisplayOriginWithCursor(
  2185. double x, double y, double xCursor, double yCursor) {
  2186. _displayOriginX = x;
  2187. _displayOriginY = y;
  2188. _x = xCursor;
  2189. _y = yCursor;
  2190. parent.target?.inputModel.moveMouse(x, y);
  2191. notifyListeners();
  2192. }
  2193. clear() {
  2194. _x = -10000;
  2195. _x = -10000;
  2196. _image = null;
  2197. disposeImages();
  2198. _clearCache();
  2199. _cache = null;
  2200. _cacheMap.clear();
  2201. }
  2202. _clearCache() {
  2203. final keys = {...cachedKeys};
  2204. for (var k in keys) {
  2205. debugPrint("deleting cursor with key $k");
  2206. deleteCustomCursor(k);
  2207. }
  2208. resetSystemCursor();
  2209. }
  2210. trySetRemoteWindowCoords() {
  2211. Future.delayed(Duration.zero, () async {
  2212. _windowRect =
  2213. await InputModel.fillRemoteCoordsAndGetCurFrame(_remoteWindowCoords);
  2214. });
  2215. }
  2216. clearRemoteWindowCoords() {
  2217. _windowRect = null;
  2218. _remoteWindowCoords.clear();
  2219. }
  2220. }
  2221. class QualityMonitorData {
  2222. String? speed;
  2223. String? fps;
  2224. String? delay;
  2225. String? targetBitrate;
  2226. String? codecFormat;
  2227. String? chroma;
  2228. }
  2229. class QualityMonitorModel with ChangeNotifier {
  2230. WeakReference<FFI> parent;
  2231. QualityMonitorModel(this.parent);
  2232. var _show = false;
  2233. final _data = QualityMonitorData();
  2234. bool get show => _show;
  2235. QualityMonitorData get data => _data;
  2236. checkShowQualityMonitor(SessionID sessionId) async {
  2237. final show = await bind.sessionGetToggleOption(
  2238. sessionId: sessionId, arg: 'show-quality-monitor') ==
  2239. true;
  2240. if (_show != show) {
  2241. _show = show;
  2242. notifyListeners();
  2243. }
  2244. }
  2245. updateQualityStatus(Map<String, dynamic> evt) {
  2246. try {
  2247. if (evt.containsKey('speed') && (evt['speed'] as String).isNotEmpty) {
  2248. _data.speed = evt['speed'];
  2249. }
  2250. if (evt.containsKey('fps') && (evt['fps'] as String).isNotEmpty) {
  2251. final fps = jsonDecode(evt['fps']) as Map<String, dynamic>;
  2252. final pi = parent.target?.ffiModel.pi;
  2253. if (pi != null) {
  2254. final currentDisplay = pi.currentDisplay;
  2255. if (currentDisplay != kAllDisplayValue) {
  2256. final fps2 = fps[currentDisplay.toString()];
  2257. if (fps2 != null) {
  2258. _data.fps = fps2.toString();
  2259. }
  2260. } else if (fps.isNotEmpty) {
  2261. final fpsList = [];
  2262. for (var i = 0; i < pi.displays.length; i++) {
  2263. fpsList.add((fps[i.toString()] ?? 0).toString());
  2264. }
  2265. _data.fps = fpsList.join(' ');
  2266. }
  2267. } else {
  2268. _data.fps = null;
  2269. }
  2270. }
  2271. if (evt.containsKey('delay') && (evt['delay'] as String).isNotEmpty) {
  2272. _data.delay = evt['delay'];
  2273. }
  2274. if (evt.containsKey('target_bitrate') &&
  2275. (evt['target_bitrate'] as String).isNotEmpty) {
  2276. _data.targetBitrate = evt['target_bitrate'];
  2277. }
  2278. if (evt.containsKey('codec_format') &&
  2279. (evt['codec_format'] as String).isNotEmpty) {
  2280. _data.codecFormat = evt['codec_format'];
  2281. }
  2282. if (evt.containsKey('chroma') && (evt['chroma'] as String).isNotEmpty) {
  2283. _data.chroma = evt['chroma'];
  2284. }
  2285. notifyListeners();
  2286. } catch (e) {
  2287. //
  2288. }
  2289. }
  2290. }
  2291. class RecordingModel with ChangeNotifier {
  2292. WeakReference<FFI> parent;
  2293. RecordingModel(this.parent);
  2294. bool _start = false;
  2295. bool get start => _start;
  2296. toggle() async {
  2297. if (isIOS) return;
  2298. final sessionId = parent.target?.sessionId;
  2299. if (sessionId == null) return;
  2300. final pi = parent.target?.ffiModel.pi;
  2301. if (pi == null) return;
  2302. bool value = !_start;
  2303. if (value) {
  2304. await sessionRefreshVideo(sessionId, pi);
  2305. }
  2306. await bind.sessionRecordScreen(sessionId: sessionId, start: value);
  2307. }
  2308. updateStatus(bool status) {
  2309. _start = status;
  2310. notifyListeners();
  2311. }
  2312. }
  2313. class ElevationModel with ChangeNotifier {
  2314. WeakReference<FFI> parent;
  2315. ElevationModel(this.parent);
  2316. bool _running = false;
  2317. bool _canElevate = false;
  2318. bool get showRequestMenu => _canElevate && !_running;
  2319. onPeerInfo(PeerInfo pi) {
  2320. _canElevate = pi.platform == kPeerPlatformWindows && pi.sasEnabled == false;
  2321. _running = false;
  2322. }
  2323. onPortableServiceRunning(bool running) => _running = running;
  2324. }
  2325. enum ConnType { defaultConn, fileTransfer, portForward, rdp }
  2326. /// Flutter state manager and data communication with the Rust core.
  2327. class FFI {
  2328. var id = '';
  2329. var version = '';
  2330. var connType = ConnType.defaultConn;
  2331. var closed = false;
  2332. var auditNote = '';
  2333. /// dialogManager use late to ensure init after main page binding [globalKey]
  2334. late final dialogManager = OverlayDialogManager();
  2335. late final SessionID sessionId;
  2336. late final ImageModel imageModel; // session
  2337. late final FfiModel ffiModel; // session
  2338. late final CursorModel cursorModel; // session
  2339. late final CanvasModel canvasModel; // session
  2340. late final ServerModel serverModel; // global
  2341. late final ChatModel chatModel; // session
  2342. late final FileModel fileModel; // session
  2343. late final AbModel abModel; // global
  2344. late final GroupModel groupModel; // global
  2345. late final UserModel userModel; // global
  2346. late final PeerTabModel peerTabModel; // global
  2347. late final QualityMonitorModel qualityMonitorModel; // session
  2348. late final RecordingModel recordingModel; // session
  2349. late final InputModel inputModel; // session
  2350. late final ElevationModel elevationModel; // session
  2351. late final CmFileModel cmFileModel; // cm
  2352. late final TextureModel textureModel; //session
  2353. late final Peers recentPeersModel; // global
  2354. late final Peers favoritePeersModel; // global
  2355. late final Peers lanPeersModel; // global
  2356. FFI(SessionID? sId) {
  2357. sessionId = sId ?? (isDesktop ? Uuid().v4obj() : _constSessionId);
  2358. imageModel = ImageModel(WeakReference(this));
  2359. ffiModel = FfiModel(WeakReference(this));
  2360. cursorModel = CursorModel(WeakReference(this));
  2361. canvasModel = CanvasModel(WeakReference(this));
  2362. serverModel = ServerModel(WeakReference(this));
  2363. chatModel = ChatModel(WeakReference(this));
  2364. fileModel = FileModel(WeakReference(this));
  2365. userModel = UserModel(WeakReference(this));
  2366. peerTabModel = PeerTabModel(WeakReference(this));
  2367. abModel = AbModel(WeakReference(this));
  2368. groupModel = GroupModel(WeakReference(this));
  2369. qualityMonitorModel = QualityMonitorModel(WeakReference(this));
  2370. recordingModel = RecordingModel(WeakReference(this));
  2371. inputModel = InputModel(WeakReference(this));
  2372. elevationModel = ElevationModel(WeakReference(this));
  2373. cmFileModel = CmFileModel(WeakReference(this));
  2374. textureModel = TextureModel(WeakReference(this));
  2375. recentPeersModel = Peers(
  2376. name: PeersModelName.recent,
  2377. loadEvent: LoadEvent.recent,
  2378. getInitPeers: null);
  2379. favoritePeersModel = Peers(
  2380. name: PeersModelName.favorite,
  2381. loadEvent: LoadEvent.favorite,
  2382. getInitPeers: null);
  2383. lanPeersModel = Peers(
  2384. name: PeersModelName.lan, loadEvent: LoadEvent.lan, getInitPeers: null);
  2385. }
  2386. /// Mobile reuse FFI
  2387. void mobileReset() {
  2388. ffiModel.waitForFirstImage.value = true;
  2389. ffiModel.isRefreshing = false;
  2390. ffiModel.waitForImageDialogShow.value = true;
  2391. ffiModel.waitForImageTimer?.cancel();
  2392. ffiModel.waitForImageTimer = null;
  2393. }
  2394. /// Start with the given [id]. Only transfer file if [isFileTransfer], only port forward if [isPortForward].
  2395. void start(
  2396. String id, {
  2397. bool isFileTransfer = false,
  2398. bool isPortForward = false,
  2399. bool isRdp = false,
  2400. String? switchUuid,
  2401. String? password,
  2402. bool? isSharedPassword,
  2403. String? connToken,
  2404. bool? forceRelay,
  2405. int? tabWindowId,
  2406. int? display,
  2407. List<int>? displays,
  2408. }) {
  2409. closed = false;
  2410. auditNote = '';
  2411. if (isMobile) mobileReset();
  2412. assert(!(isFileTransfer && isPortForward), 'more than one connect type');
  2413. if (isFileTransfer) {
  2414. connType = ConnType.fileTransfer;
  2415. } else if (isPortForward) {
  2416. connType = ConnType.portForward;
  2417. } else {
  2418. chatModel.resetClientMode();
  2419. connType = ConnType.defaultConn;
  2420. canvasModel.id = id;
  2421. imageModel.id = id;
  2422. cursorModel.peerId = id;
  2423. }
  2424. final isNewPeer = tabWindowId == null;
  2425. // If tabWindowId != null, this session is a "tab -> window" one.
  2426. // Else this session is a new one.
  2427. if (isNewPeer) {
  2428. // ignore: unused_local_variable
  2429. final addRes = bind.sessionAddSync(
  2430. sessionId: sessionId,
  2431. id: id,
  2432. isFileTransfer: isFileTransfer,
  2433. isPortForward: isPortForward,
  2434. isRdp: isRdp,
  2435. switchUuid: switchUuid ?? '',
  2436. forceRelay: forceRelay ?? false,
  2437. password: password ?? '',
  2438. isSharedPassword: isSharedPassword ?? false,
  2439. connToken: connToken,
  2440. );
  2441. } else if (display != null) {
  2442. if (displays == null) {
  2443. debugPrint(
  2444. 'Unreachable, failed to add existed session to $id, the displays is null while display is $display');
  2445. return;
  2446. }
  2447. final addRes = bind.sessionAddExistedSync(
  2448. id: id, sessionId: sessionId, displays: Int32List.fromList(displays));
  2449. if (addRes != '') {
  2450. debugPrint(
  2451. 'Unreachable, failed to add existed session to $id, $addRes');
  2452. return;
  2453. }
  2454. ffiModel.pi.currentDisplay = display;
  2455. }
  2456. if (isDesktop && connType == ConnType.defaultConn) {
  2457. textureModel.updateCurrentDisplay(display ?? 0);
  2458. }
  2459. // CAUTION: `sessionStart()` and `sessionStartWithDisplays()` are an async functions.
  2460. // Though the stream is returned immediately, the stream may not be ready.
  2461. // Any operations that depend on the stream should be carefully handled.
  2462. late final Stream<EventToUI> stream;
  2463. if (isNewPeer || display == null || displays == null) {
  2464. stream = bind.sessionStart(sessionId: sessionId, id: id);
  2465. } else {
  2466. // We have to put displays in `sessionStart()` to make sure the stream is ready
  2467. // and then the displays' capturing requests can be sent.
  2468. stream = bind.sessionStartWithDisplays(
  2469. sessionId: sessionId, id: id, displays: Int32List.fromList(displays));
  2470. }
  2471. if (isWeb) {
  2472. platformFFI.setRgbaCallback((int display, Uint8List data) {
  2473. onEvent2UIRgba();
  2474. imageModel.onRgba(display, data);
  2475. });
  2476. this.id = id;
  2477. return;
  2478. }
  2479. final cb = ffiModel.startEventListener(sessionId, id);
  2480. imageModel.updateUserTextureRender();
  2481. final hasGpuTextureRender = bind.mainHasGpuTextureRender();
  2482. final SimpleWrapper<bool> isToNewWindowNotified = SimpleWrapper(false);
  2483. // Preserved for the rgba data.
  2484. stream.listen((message) {
  2485. if (closed) return;
  2486. if (tabWindowId != null && !isToNewWindowNotified.value) {
  2487. // Session is read to be moved to a new window.
  2488. // Get the cached data and handle the cached data.
  2489. Future.delayed(Duration.zero, () async {
  2490. final args = jsonEncode({'id': id, 'close': display == null});
  2491. final cachedData = await DesktopMultiWindow.invokeMethod(
  2492. tabWindowId, kWindowEventGetCachedSessionData, args);
  2493. if (cachedData == null) {
  2494. // unreachable
  2495. debugPrint('Unreachable, the cached data is empty.');
  2496. return;
  2497. }
  2498. final data = CachedPeerData.fromString(cachedData);
  2499. if (data == null) {
  2500. debugPrint('Unreachable, the cached data cannot be decoded.');
  2501. return;
  2502. }
  2503. ffiModel.setPermissions(data.permissions);
  2504. await ffiModel.handleCachedPeerData(data, id);
  2505. await sessionRefreshVideo(sessionId, ffiModel.pi);
  2506. await bind.sessionRequestNewDisplayInitMsgs(
  2507. sessionId: sessionId, display: ffiModel.pi.currentDisplay);
  2508. });
  2509. isToNewWindowNotified.value = true;
  2510. }
  2511. () async {
  2512. if (message is EventToUI_Event) {
  2513. if (message.field0 == "close") {
  2514. closed = true;
  2515. debugPrint('Exit session event loop');
  2516. return;
  2517. }
  2518. Map<String, dynamic>? event;
  2519. try {
  2520. event = json.decode(message.field0);
  2521. } catch (e) {
  2522. debugPrint('json.decode fail1(): $e, ${message.field0}');
  2523. }
  2524. if (event != null) {
  2525. await cb(event);
  2526. }
  2527. } else if (message is EventToUI_Rgba) {
  2528. final display = message.field0;
  2529. // Fetch the image buffer from rust codes.
  2530. final sz = platformFFI.getRgbaSize(sessionId, display);
  2531. if (sz == 0) {
  2532. platformFFI.nextRgba(sessionId, display);
  2533. return;
  2534. }
  2535. final rgba = platformFFI.getRgba(sessionId, display, sz);
  2536. if (rgba != null) {
  2537. onEvent2UIRgba();
  2538. await imageModel.onRgba(display, rgba);
  2539. } else {
  2540. platformFFI.nextRgba(sessionId, display);
  2541. }
  2542. } else if (message is EventToUI_Texture) {
  2543. final display = message.field0;
  2544. final gpuTexture = message.field1;
  2545. debugPrint(
  2546. "EventToUI_Texture display:$display, gpuTexture:$gpuTexture");
  2547. if (gpuTexture && !hasGpuTextureRender) {
  2548. debugPrint('the gpuTexture is not supported.');
  2549. return;
  2550. }
  2551. textureModel.setTextureType(display: display, gpuTexture: gpuTexture);
  2552. onEvent2UIRgba();
  2553. }
  2554. }();
  2555. });
  2556. // every instance will bind a stream
  2557. this.id = id;
  2558. }
  2559. void onEvent2UIRgba() async {
  2560. if (ffiModel.waitForImageDialogShow.isTrue) {
  2561. ffiModel.waitForImageDialogShow.value = false;
  2562. ffiModel.waitForImageTimer?.cancel();
  2563. clearWaitingForImage(dialogManager, sessionId);
  2564. }
  2565. if (ffiModel.waitForFirstImage.value == true) {
  2566. ffiModel.waitForFirstImage.value = false;
  2567. dialogManager.dismissAll();
  2568. await canvasModel.updateViewStyle();
  2569. await canvasModel.updateScrollStyle();
  2570. for (final cb in imageModel.callbacksOnFirstImage) {
  2571. cb(id);
  2572. }
  2573. }
  2574. }
  2575. /// Login with [password], choose if the client should [remember] it.
  2576. void login(String osUsername, String osPassword, SessionID sessionId,
  2577. String password, bool remember) {
  2578. bind.sessionLogin(
  2579. sessionId: sessionId,
  2580. osUsername: osUsername,
  2581. osPassword: osPassword,
  2582. password: password,
  2583. remember: remember);
  2584. }
  2585. void send2FA(SessionID sessionId, String code, bool trustThisDevice) {
  2586. bind.sessionSend2Fa(
  2587. sessionId: sessionId, code: code, trustThisDevice: trustThisDevice);
  2588. }
  2589. /// Close the remote session.
  2590. Future<void> close({bool closeSession = true}) async {
  2591. closed = true;
  2592. chatModel.close();
  2593. if (imageModel.image != null && !isWebDesktop) {
  2594. await setCanvasConfig(
  2595. sessionId,
  2596. cursorModel.x,
  2597. cursorModel.y,
  2598. canvasModel.x,
  2599. canvasModel.y,
  2600. canvasModel.scale,
  2601. ffiModel.pi.currentDisplay);
  2602. }
  2603. await imageModel.update(null);
  2604. cursorModel.clear();
  2605. ffiModel.clear();
  2606. canvasModel.clear();
  2607. inputModel.resetModifiers();
  2608. if (closeSession) {
  2609. await bind.sessionClose(sessionId: sessionId);
  2610. }
  2611. debugPrint('model $id closed');
  2612. id = '';
  2613. }
  2614. void setMethodCallHandler(FMethod callback) {
  2615. platformFFI.setMethodCallHandler(callback);
  2616. }
  2617. Future<bool> invokeMethod(String method, [dynamic arguments]) async {
  2618. return await platformFFI.invokeMethod(method, arguments);
  2619. }
  2620. }
  2621. const kInvalidResolutionValue = -1;
  2622. const kVirtualDisplayResolutionValue = 0;
  2623. class Display {
  2624. double x = 0;
  2625. double y = 0;
  2626. int width = 0;
  2627. int height = 0;
  2628. bool cursorEmbedded = false;
  2629. int originalWidth = kInvalidResolutionValue;
  2630. int originalHeight = kInvalidResolutionValue;
  2631. double _scale = 1.0;
  2632. double get scale => _scale > 1.0 ? _scale : 1.0;
  2633. Display() {
  2634. width = (isDesktop || isWebDesktop)
  2635. ? kDesktopDefaultDisplayWidth
  2636. : kMobileDefaultDisplayWidth;
  2637. height = (isDesktop || isWebDesktop)
  2638. ? kDesktopDefaultDisplayHeight
  2639. : kMobileDefaultDisplayHeight;
  2640. }
  2641. @override
  2642. bool operator ==(Object other) =>
  2643. other is Display &&
  2644. other.runtimeType == runtimeType &&
  2645. _innerEqual(other);
  2646. bool _innerEqual(Display other) =>
  2647. other.x == x &&
  2648. other.y == y &&
  2649. other.width == width &&
  2650. other.height == height &&
  2651. other.cursorEmbedded == cursorEmbedded;
  2652. bool get isOriginalResolutionSet =>
  2653. originalWidth != kInvalidResolutionValue &&
  2654. originalHeight != kInvalidResolutionValue;
  2655. bool get isVirtualDisplayResolution =>
  2656. originalWidth == kVirtualDisplayResolutionValue &&
  2657. originalHeight == kVirtualDisplayResolutionValue;
  2658. bool get isOriginalResolution =>
  2659. width == originalWidth && height == originalHeight;
  2660. }
  2661. class Resolution {
  2662. int width = 0;
  2663. int height = 0;
  2664. Resolution(this.width, this.height);
  2665. @override
  2666. String toString() {
  2667. return 'Resolution($width,$height)';
  2668. }
  2669. }
  2670. class Features {
  2671. bool privacyMode = false;
  2672. }
  2673. const kInvalidDisplayIndex = -1;
  2674. class PeerInfo with ChangeNotifier {
  2675. String version = '';
  2676. String username = '';
  2677. String hostname = '';
  2678. String platform = '';
  2679. bool sasEnabled = false;
  2680. bool isSupportMultiUiSession = false;
  2681. int currentDisplay = 0;
  2682. int primaryDisplay = kInvalidDisplayIndex;
  2683. RxList<Display> displays = <Display>[].obs;
  2684. Features features = Features();
  2685. List<Resolution> resolutions = [];
  2686. Map<String, dynamic> platformAdditions = {};
  2687. RxInt displaysCount = 0.obs;
  2688. RxBool isSet = false.obs;
  2689. bool get isWayland => platformAdditions[kPlatformAdditionsIsWayland] == true;
  2690. bool get isHeadless => platformAdditions[kPlatformAdditionsHeadless] == true;
  2691. bool get isInstalled =>
  2692. platform != kPeerPlatformWindows ||
  2693. platformAdditions[kPlatformAdditionsIsInstalled] == true;
  2694. List<int> get RustDeskVirtualDisplays => List<int>.from(
  2695. platformAdditions[kPlatformAdditionsRustDeskVirtualDisplays] ?? []);
  2696. int get amyuniVirtualDisplayCount =>
  2697. platformAdditions[kPlatformAdditionsAmyuniVirtualDisplays] ?? 0;
  2698. bool get isSupportMultiDisplay =>
  2699. (isDesktop || isWebDesktop) && isSupportMultiUiSession;
  2700. bool get forceTextureRender => currentDisplay == kAllDisplayValue;
  2701. bool get cursorEmbedded => tryGetDisplay()?.cursorEmbedded ?? false;
  2702. bool get isRustDeskIdd =>
  2703. platformAdditions[kPlatformAdditionsIddImpl] == 'rustdesk_idd';
  2704. bool get isAmyuniIdd =>
  2705. platformAdditions[kPlatformAdditionsIddImpl] == 'amyuni_idd';
  2706. Display? tryGetDisplay({int? display}) {
  2707. if (displays.isEmpty) {
  2708. return null;
  2709. }
  2710. display ??= currentDisplay;
  2711. if (display == kAllDisplayValue) {
  2712. return displays[0];
  2713. } else {
  2714. if (display > 0 && display < displays.length) {
  2715. return displays[display];
  2716. } else {
  2717. return displays[0];
  2718. }
  2719. }
  2720. }
  2721. Display? tryGetDisplayIfNotAllDisplay({int? display}) {
  2722. if (displays.isEmpty) {
  2723. return null;
  2724. }
  2725. display ??= currentDisplay;
  2726. if (display == kAllDisplayValue) {
  2727. return null;
  2728. }
  2729. if (display >= 0 && display < displays.length) {
  2730. return displays[display];
  2731. } else {
  2732. return null;
  2733. }
  2734. }
  2735. List<Display> getCurDisplays() {
  2736. if (currentDisplay == kAllDisplayValue) {
  2737. return displays;
  2738. } else {
  2739. if (currentDisplay >= 0 && currentDisplay < displays.length) {
  2740. return [displays[currentDisplay]];
  2741. } else {
  2742. return [];
  2743. }
  2744. }
  2745. }
  2746. double scaleOfDisplay(int display) {
  2747. if (display >= 0 && display < displays.length) {
  2748. return displays[display].scale;
  2749. }
  2750. return 1.0;
  2751. }
  2752. Rect? getDisplayRect(int display) {
  2753. final d = tryGetDisplayIfNotAllDisplay(display: display);
  2754. if (d == null) return null;
  2755. return Rect.fromLTWH(d.x, d.y, d.width.toDouble(), d.height.toDouble());
  2756. }
  2757. }
  2758. const canvasKey = 'canvas';
  2759. Future<void> setCanvasConfig(
  2760. SessionID sessionId,
  2761. double xCursor,
  2762. double yCursor,
  2763. double xCanvas,
  2764. double yCanvas,
  2765. double scale,
  2766. int currentDisplay) async {
  2767. final p = <String, dynamic>{};
  2768. p['xCursor'] = xCursor;
  2769. p['yCursor'] = yCursor;
  2770. p['xCanvas'] = xCanvas;
  2771. p['yCanvas'] = yCanvas;
  2772. p['scale'] = scale;
  2773. p['currentDisplay'] = currentDisplay;
  2774. await bind.sessionSetFlutterOption(
  2775. sessionId: sessionId, k: canvasKey, v: jsonEncode(p));
  2776. }
  2777. Future<Map<String, dynamic>?> getCanvasConfig(SessionID sessionId) async {
  2778. if (!isWebDesktop) return null;
  2779. var p =
  2780. await bind.sessionGetFlutterOption(sessionId: sessionId, k: canvasKey);
  2781. if (p == null || p.isEmpty) return null;
  2782. try {
  2783. Map<String, dynamic> m = json.decode(p);
  2784. return m;
  2785. } catch (e) {
  2786. return null;
  2787. }
  2788. }
  2789. Future<void> initializeCursorAndCanvas(FFI ffi) async {
  2790. var p = await getCanvasConfig(ffi.sessionId);
  2791. int currentDisplay = 0;
  2792. if (p != null) {
  2793. currentDisplay = p['currentDisplay'];
  2794. }
  2795. if (p == null || currentDisplay != ffi.ffiModel.pi.currentDisplay) {
  2796. ffi.cursorModel.updateDisplayOrigin(
  2797. ffi.ffiModel.rect?.left ?? 0, ffi.ffiModel.rect?.top ?? 0);
  2798. return;
  2799. }
  2800. double xCursor = p['xCursor'];
  2801. double yCursor = p['yCursor'];
  2802. double xCanvas = p['xCanvas'];
  2803. double yCanvas = p['yCanvas'];
  2804. double scale = p['scale'];
  2805. ffi.cursorModel.updateDisplayOriginWithCursor(ffi.ffiModel.rect?.left ?? 0,
  2806. ffi.ffiModel.rect?.top ?? 0, xCursor, yCursor);
  2807. ffi.canvasModel.update(xCanvas, yCanvas, scale);
  2808. }
  2809. clearWaitingForImage(OverlayDialogManager? dialogManager, SessionID sessionId) {
  2810. dialogManager?.dismissByTag('$sessionId-waiting-for-image');
  2811. }