remote_input.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import 'dart:convert';
  2. import 'package:flutter/material.dart';
  3. import 'package:flutter/services.dart';
  4. import 'package:flutter/gestures.dart';
  5. import 'package:flutter_hbb/models/platform_model.dart';
  6. import 'package:flutter_hbb/common.dart';
  7. import 'package:flutter_hbb/consts.dart';
  8. import 'package:flutter_hbb/models/model.dart';
  9. import 'package:flutter_hbb/models/input_model.dart';
  10. import './gestures.dart';
  11. class RawKeyFocusScope extends StatelessWidget {
  12. final FocusNode? focusNode;
  13. final ValueChanged<bool>? onFocusChange;
  14. final InputModel inputModel;
  15. final Widget child;
  16. RawKeyFocusScope({
  17. this.focusNode,
  18. this.onFocusChange,
  19. required this.inputModel,
  20. required this.child,
  21. });
  22. @override
  23. Widget build(BuildContext context) {
  24. // https://github.com/flutter/flutter/issues/154053
  25. final useRawKeyEvents = isLinux && !isWeb;
  26. // FIXME: On Windows, `AltGr` will generate `Alt` and `Control` key events,
  27. // while `Alt` and `Control` are seperated key events for en-US input method.
  28. return FocusScope(
  29. autofocus: true,
  30. child: Focus(
  31. autofocus: true,
  32. canRequestFocus: true,
  33. focusNode: focusNode,
  34. onFocusChange: onFocusChange,
  35. onKey: useRawKeyEvents
  36. ? (FocusNode data, RawKeyEvent event) =>
  37. inputModel.handleRawKeyEvent(event)
  38. : null,
  39. onKeyEvent: useRawKeyEvents
  40. ? null
  41. : (FocusNode node, KeyEvent event) =>
  42. inputModel.handleKeyEvent(event),
  43. child: child));
  44. }
  45. }
  46. class RawTouchGestureDetectorRegion extends StatefulWidget {
  47. final Widget child;
  48. final FFI ffi;
  49. late final InputModel inputModel = ffi.inputModel;
  50. late final FfiModel ffiModel = ffi.ffiModel;
  51. RawTouchGestureDetectorRegion({
  52. required this.child,
  53. required this.ffi,
  54. });
  55. @override
  56. State<RawTouchGestureDetectorRegion> createState() =>
  57. _RawTouchGestureDetectorRegionState();
  58. }
  59. /// touchMode only:
  60. /// LongPress -> right click
  61. /// OneFingerPan -> start/end -> left down start/end
  62. /// onDoubleTapDown -> move to
  63. /// onLongPressDown => move to
  64. ///
  65. /// mouseMode only:
  66. /// DoubleFiner -> right click
  67. /// HoldDrag -> left drag
  68. class _RawTouchGestureDetectorRegionState
  69. extends State<RawTouchGestureDetectorRegion> {
  70. Offset _cacheLongPressPosition = Offset(0, 0);
  71. // Timestamp of the last long press event.
  72. int _cacheLongPressPositionTs = 0;
  73. double _mouseScrollIntegral = 0; // mouse scroll speed controller
  74. double _scale = 1;
  75. // Workaround tap down event when two fingers are used to scale(mobile)
  76. TapDownDetails? _lastTapDownDetails;
  77. PointerDeviceKind? lastDeviceKind;
  78. // For touch mode, onDoubleTap
  79. // `onDoubleTap()` does not provide the position of the tap event.
  80. Offset _lastPosOfDoubleTapDown = Offset.zero;
  81. bool _touchModePanStarted = false;
  82. Offset _doubleFinerTapPosition = Offset.zero;
  83. FFI get ffi => widget.ffi;
  84. FfiModel get ffiModel => widget.ffiModel;
  85. InputModel get inputModel => widget.inputModel;
  86. bool get handleTouch => (isDesktop || isWebDesktop) || ffiModel.touchMode;
  87. SessionID get sessionId => ffi.sessionId;
  88. @override
  89. Widget build(BuildContext context) {
  90. return RawGestureDetector(
  91. child: widget.child,
  92. gestures: makeGestures(context),
  93. );
  94. }
  95. onTapDown(TapDownDetails d) async {
  96. lastDeviceKind = d.kind;
  97. if (lastDeviceKind != PointerDeviceKind.touch) {
  98. return;
  99. }
  100. if (handleTouch) {
  101. _lastPosOfDoubleTapDown = d.localPosition;
  102. // Desktop or mobile "Touch mode"
  103. _lastTapDownDetails = d;
  104. }
  105. }
  106. onTapUp(TapUpDetails d) async {
  107. final TapDownDetails? lastTapDownDetails = _lastTapDownDetails;
  108. _lastTapDownDetails = null;
  109. if (lastDeviceKind != PointerDeviceKind.touch) {
  110. return;
  111. }
  112. if (handleTouch) {
  113. final isMoved =
  114. await ffi.cursorModel.move(d.localPosition.dx, d.localPosition.dy);
  115. if (isMoved) {
  116. if (lastTapDownDetails != null) {
  117. await inputModel.tapDown(MouseButtons.left);
  118. }
  119. await inputModel.tapUp(MouseButtons.left);
  120. }
  121. }
  122. }
  123. onTap() async {
  124. if (lastDeviceKind != PointerDeviceKind.touch) {
  125. return;
  126. }
  127. if (!handleTouch) {
  128. // Mobile, "Mouse mode"
  129. await inputModel.tap(MouseButtons.left);
  130. }
  131. }
  132. onDoubleTapDown(TapDownDetails d) async {
  133. lastDeviceKind = d.kind;
  134. if (lastDeviceKind != PointerDeviceKind.touch) {
  135. return;
  136. }
  137. if (handleTouch) {
  138. _lastPosOfDoubleTapDown = d.localPosition;
  139. await ffi.cursorModel.move(d.localPosition.dx, d.localPosition.dy);
  140. }
  141. }
  142. onDoubleTap() async {
  143. if (lastDeviceKind != PointerDeviceKind.touch) {
  144. return;
  145. }
  146. if (ffiModel.touchMode && ffi.cursorModel.lastIsBlocked) {
  147. return;
  148. }
  149. if (handleTouch &&
  150. !ffi.cursorModel.isInRemoteRect(_lastPosOfDoubleTapDown)) {
  151. return;
  152. }
  153. await inputModel.tap(MouseButtons.left);
  154. await inputModel.tap(MouseButtons.left);
  155. }
  156. onLongPressDown(LongPressDownDetails d) async {
  157. lastDeviceKind = d.kind;
  158. if (lastDeviceKind != PointerDeviceKind.touch) {
  159. return;
  160. }
  161. if (handleTouch) {
  162. _lastPosOfDoubleTapDown = d.localPosition;
  163. _cacheLongPressPosition = d.localPosition;
  164. if (!ffi.cursorModel.isInRemoteRect(d.localPosition)) {
  165. return;
  166. }
  167. _cacheLongPressPositionTs = DateTime.now().millisecondsSinceEpoch;
  168. }
  169. }
  170. onLongPressUp() async {
  171. if (lastDeviceKind != PointerDeviceKind.touch) {
  172. return;
  173. }
  174. if (handleTouch) {
  175. await inputModel.tapUp(MouseButtons.left);
  176. }
  177. }
  178. // for mobiles
  179. onLongPress() async {
  180. if (lastDeviceKind != PointerDeviceKind.touch) {
  181. return;
  182. }
  183. if (handleTouch) {
  184. final isMoved = await ffi.cursorModel
  185. .move(_cacheLongPressPosition.dx, _cacheLongPressPosition.dy);
  186. if (!isMoved) {
  187. return;
  188. }
  189. }
  190. if (!ffi.ffiModel.isPeerMobile) {
  191. await inputModel.tap(MouseButtons.right);
  192. }
  193. }
  194. onDoubleFinerTapDown(TapDownDetails d) async {
  195. lastDeviceKind = d.kind;
  196. if (lastDeviceKind != PointerDeviceKind.touch) {
  197. return;
  198. }
  199. _doubleFinerTapPosition = d.localPosition;
  200. // ignore for desktop and mobile
  201. }
  202. onDoubleFinerTap(TapDownDetails d) async {
  203. lastDeviceKind = d.kind;
  204. if (lastDeviceKind != PointerDeviceKind.touch) {
  205. return;
  206. }
  207. // mobile mouse mode or desktop touch screen
  208. final isMobileMouseMode = isMobile && !ffiModel.touchMode;
  209. // We can't use `d.localPosition` here because it's always (0, 0) on desktop.
  210. final isDesktopInRemoteRect = (isDesktop || isWebDesktop) &&
  211. ffi.cursorModel.isInRemoteRect(_doubleFinerTapPosition);
  212. if (isMobileMouseMode || isDesktopInRemoteRect) {
  213. await inputModel.tap(MouseButtons.right);
  214. }
  215. }
  216. onHoldDragStart(DragStartDetails d) async {
  217. lastDeviceKind = d.kind;
  218. if (lastDeviceKind != PointerDeviceKind.touch) {
  219. return;
  220. }
  221. if (!handleTouch) {
  222. await inputModel.sendMouse('down', MouseButtons.left);
  223. }
  224. }
  225. onHoldDragUpdate(DragUpdateDetails d) async {
  226. if (lastDeviceKind != PointerDeviceKind.touch) {
  227. return;
  228. }
  229. if (!handleTouch) {
  230. await ffi.cursorModel.updatePan(d.delta, d.localPosition, handleTouch);
  231. }
  232. }
  233. onHoldDragEnd(DragEndDetails d) async {
  234. if (lastDeviceKind != PointerDeviceKind.touch) {
  235. return;
  236. }
  237. if (!handleTouch) {
  238. await inputModel.sendMouse('up', MouseButtons.left);
  239. }
  240. }
  241. onOneFingerPanStart(BuildContext context, DragStartDetails d) async {
  242. final TapDownDetails? lastTapDownDetails = _lastTapDownDetails;
  243. _lastTapDownDetails = null;
  244. lastDeviceKind = d.kind ?? lastDeviceKind;
  245. if (lastDeviceKind != PointerDeviceKind.touch) {
  246. return;
  247. }
  248. if (handleTouch) {
  249. if (lastTapDownDetails != null) {
  250. await ffi.cursorModel.move(lastTapDownDetails.localPosition.dx,
  251. lastTapDownDetails.localPosition.dy);
  252. }
  253. if (ffi.cursorModel.shouldBlock(d.localPosition.dx, d.localPosition.dy)) {
  254. return;
  255. }
  256. if (!ffi.cursorModel.isInRemoteRect(d.localPosition)) {
  257. return;
  258. }
  259. _touchModePanStarted = true;
  260. if (isDesktop || isWebDesktop) {
  261. ffi.cursorModel.trySetRemoteWindowCoords();
  262. }
  263. // Workaround for the issue that the first pan event is sent a long time after the start event.
  264. // If the time interval between the start event and the first pan event is less than 500ms,
  265. // we consider to use the long press position as the start position.
  266. //
  267. // TODO: We should find a better way to send the first pan event as soon as possible.
  268. if (DateTime.now().millisecondsSinceEpoch - _cacheLongPressPositionTs <
  269. 500) {
  270. await ffi.cursorModel
  271. .move(_cacheLongPressPosition.dx, _cacheLongPressPosition.dy);
  272. }
  273. await inputModel.sendMouse('down', MouseButtons.left);
  274. await ffi.cursorModel.move(d.localPosition.dx, d.localPosition.dy);
  275. } else {
  276. final offset = ffi.cursorModel.offset;
  277. final cursorX = offset.dx;
  278. final cursorY = offset.dy;
  279. final visible =
  280. ffi.cursorModel.getVisibleRect().inflate(1); // extend edges
  281. final size = MediaQueryData.fromView(View.of(context)).size;
  282. if (!visible.contains(Offset(cursorX, cursorY))) {
  283. await ffi.cursorModel.move(size.width / 2, size.height / 2);
  284. }
  285. }
  286. }
  287. onOneFingerPanUpdate(DragUpdateDetails d) async {
  288. if (lastDeviceKind != PointerDeviceKind.touch) {
  289. return;
  290. }
  291. if (ffi.cursorModel.shouldBlock(d.localPosition.dx, d.localPosition.dy)) {
  292. return;
  293. }
  294. if (handleTouch && !_touchModePanStarted) {
  295. return;
  296. }
  297. await ffi.cursorModel.updatePan(d.delta, d.localPosition, handleTouch);
  298. }
  299. onOneFingerPanEnd(DragEndDetails d) async {
  300. _touchModePanStarted = false;
  301. if (lastDeviceKind != PointerDeviceKind.touch) {
  302. return;
  303. }
  304. if (isDesktop || isWebDesktop) {
  305. ffi.cursorModel.clearRemoteWindowCoords();
  306. }
  307. if (handleTouch) {
  308. await inputModel.sendMouse('up', MouseButtons.left);
  309. }
  310. }
  311. // scale + pan event
  312. onTwoFingerScaleStart(ScaleStartDetails d) {
  313. _lastTapDownDetails = null;
  314. if (lastDeviceKind != PointerDeviceKind.touch) {
  315. return;
  316. }
  317. }
  318. onTwoFingerScaleUpdate(ScaleUpdateDetails d) async {
  319. if (lastDeviceKind != PointerDeviceKind.touch) {
  320. return;
  321. }
  322. if ((isDesktop || isWebDesktop)) {
  323. final scale = ((d.scale - _scale) * 1000).toInt();
  324. _scale = d.scale;
  325. if (scale != 0) {
  326. await bind.sessionSendPointer(
  327. sessionId: sessionId,
  328. msg: json.encode(
  329. PointerEventToRust(kPointerEventKindTouch, 'scale', scale)
  330. .toJson()));
  331. }
  332. } else {
  333. // mobile
  334. ffi.canvasModel.updateScale(d.scale / _scale, d.focalPoint);
  335. _scale = d.scale;
  336. ffi.canvasModel.panX(d.focalPointDelta.dx);
  337. ffi.canvasModel.panY(d.focalPointDelta.dy);
  338. }
  339. }
  340. onTwoFingerScaleEnd(ScaleEndDetails d) async {
  341. if (lastDeviceKind != PointerDeviceKind.touch) {
  342. return;
  343. }
  344. if ((isDesktop || isWebDesktop)) {
  345. await bind.sessionSendPointer(
  346. sessionId: sessionId,
  347. msg: json.encode(
  348. PointerEventToRust(kPointerEventKindTouch, 'scale', 0).toJson()));
  349. } else {
  350. // mobile
  351. _scale = 1;
  352. // No idea why we need to set the view style to "" here.
  353. // bind.sessionSetViewStyle(sessionId: sessionId, value: "");
  354. }
  355. await inputModel.sendMouse('up', MouseButtons.left);
  356. }
  357. get onHoldDragCancel => null;
  358. get onThreeFingerVerticalDragUpdate => ffi.ffiModel.isPeerAndroid
  359. ? null
  360. : (d) {
  361. _mouseScrollIntegral += d.delta.dy / 4;
  362. if (_mouseScrollIntegral > 1) {
  363. inputModel.scroll(1);
  364. _mouseScrollIntegral = 0;
  365. } else if (_mouseScrollIntegral < -1) {
  366. inputModel.scroll(-1);
  367. _mouseScrollIntegral = 0;
  368. }
  369. };
  370. makeGestures(BuildContext context) {
  371. return <Type, GestureRecognizerFactory>{
  372. // Official
  373. TapGestureRecognizer:
  374. GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
  375. () => TapGestureRecognizer(), (instance) {
  376. instance
  377. ..onTapDown = onTapDown
  378. ..onTapUp = onTapUp
  379. ..onTap = onTap;
  380. }),
  381. DoubleTapGestureRecognizer:
  382. GestureRecognizerFactoryWithHandlers<DoubleTapGestureRecognizer>(
  383. () => DoubleTapGestureRecognizer(), (instance) {
  384. instance
  385. ..onDoubleTapDown = onDoubleTapDown
  386. ..onDoubleTap = onDoubleTap;
  387. }),
  388. LongPressGestureRecognizer:
  389. GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
  390. () => LongPressGestureRecognizer(), (instance) {
  391. instance
  392. ..onLongPressDown = onLongPressDown
  393. ..onLongPressUp = onLongPressUp
  394. ..onLongPress = onLongPress;
  395. }),
  396. // Customized
  397. HoldTapMoveGestureRecognizer:
  398. GestureRecognizerFactoryWithHandlers<HoldTapMoveGestureRecognizer>(
  399. () => HoldTapMoveGestureRecognizer(),
  400. (instance) => instance
  401. ..onHoldDragStart = onHoldDragStart
  402. ..onHoldDragUpdate = onHoldDragUpdate
  403. ..onHoldDragCancel = onHoldDragCancel
  404. ..onHoldDragEnd = onHoldDragEnd),
  405. DoubleFinerTapGestureRecognizer:
  406. GestureRecognizerFactoryWithHandlers<DoubleFinerTapGestureRecognizer>(
  407. () => DoubleFinerTapGestureRecognizer(), (instance) {
  408. instance
  409. ..onDoubleFinerTap = onDoubleFinerTap
  410. ..onDoubleFinerTapDown = onDoubleFinerTapDown;
  411. }),
  412. CustomTouchGestureRecognizer:
  413. GestureRecognizerFactoryWithHandlers<CustomTouchGestureRecognizer>(
  414. () => CustomTouchGestureRecognizer(), (instance) {
  415. instance.onOneFingerPanStart =
  416. (DragStartDetails d) => onOneFingerPanStart(context, d);
  417. instance
  418. ..onOneFingerPanUpdate = onOneFingerPanUpdate
  419. ..onOneFingerPanEnd = onOneFingerPanEnd
  420. ..onTwoFingerScaleStart = onTwoFingerScaleStart
  421. ..onTwoFingerScaleUpdate = onTwoFingerScaleUpdate
  422. ..onTwoFingerScaleEnd = onTwoFingerScaleEnd
  423. ..onThreeFingerVerticalDragUpdate = onThreeFingerVerticalDragUpdate;
  424. }),
  425. };
  426. }
  427. }
  428. class RawPointerMouseRegion extends StatelessWidget {
  429. final InputModel inputModel;
  430. final Widget child;
  431. final MouseCursor? cursor;
  432. final PointerEnterEventListener? onEnter;
  433. final PointerExitEventListener? onExit;
  434. final PointerDownEventListener? onPointerDown;
  435. final PointerUpEventListener? onPointerUp;
  436. RawPointerMouseRegion({
  437. this.onEnter,
  438. this.onExit,
  439. this.cursor,
  440. this.onPointerDown,
  441. this.onPointerUp,
  442. required this.inputModel,
  443. required this.child,
  444. });
  445. @override
  446. Widget build(BuildContext context) {
  447. return Listener(
  448. onPointerHover: inputModel.onPointHoverImage,
  449. onPointerDown: (evt) {
  450. onPointerDown?.call(evt);
  451. inputModel.onPointDownImage(evt);
  452. },
  453. onPointerUp: (evt) {
  454. onPointerUp?.call(evt);
  455. inputModel.onPointUpImage(evt);
  456. },
  457. onPointerMove: inputModel.onPointMoveImage,
  458. onPointerSignal: inputModel.onPointerSignalImage,
  459. onPointerPanZoomStart: inputModel.onPointerPanZoomStart,
  460. onPointerPanZoomUpdate: inputModel.onPointerPanZoomUpdate,
  461. onPointerPanZoomEnd: inputModel.onPointerPanZoomEnd,
  462. child: MouseRegion(
  463. cursor: inputModel.isViewOnly
  464. ? MouseCursor.defer
  465. : (cursor ?? MouseCursor.defer),
  466. onEnter: onEnter,
  467. onExit: onExit,
  468. child: child,
  469. ),
  470. );
  471. }
  472. }