remote_input.dart 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. if (ffiModel.isPeerMobile) {
  169. await ffi.cursorModel
  170. .move(_cacheLongPressPosition.dx, _cacheLongPressPosition.dy);
  171. await inputModel.tapDown(MouseButtons.left);
  172. }
  173. }
  174. }
  175. onLongPressUp() async {
  176. if (lastDeviceKind != PointerDeviceKind.touch) {
  177. return;
  178. }
  179. if (handleTouch) {
  180. await inputModel.tapUp(MouseButtons.left);
  181. }
  182. }
  183. // for mobiles
  184. onLongPress() async {
  185. if (lastDeviceKind != PointerDeviceKind.touch) {
  186. return;
  187. }
  188. if (!ffi.ffiModel.isPeerMobile) {
  189. if (handleTouch) {
  190. final isMoved = await ffi.cursorModel
  191. .move(_cacheLongPressPosition.dx, _cacheLongPressPosition.dy);
  192. if (!isMoved) {
  193. return;
  194. }
  195. }
  196. await inputModel.tap(MouseButtons.right);
  197. } else {
  198. // It's better to send a message to tell the controlled device that the long press event is triggered.
  199. // We're now using a `TimerTask` in `InputService.kt` to decide whether to trigger the long press event.
  200. // It's not accurate and it's better to use the same detection logic in the controlling side.
  201. }
  202. }
  203. onLongPressMoveUpdate(LongPressMoveUpdateDetails d) async {
  204. if (!ffiModel.isPeerMobile || lastDeviceKind != PointerDeviceKind.touch) {
  205. return;
  206. }
  207. if (handleTouch) {
  208. if (!ffi.cursorModel.isInRemoteRect(d.localPosition)) {
  209. return;
  210. }
  211. await ffi.cursorModel.move(d.localPosition.dx, d.localPosition.dy);
  212. }
  213. }
  214. onDoubleFinerTapDown(TapDownDetails d) async {
  215. lastDeviceKind = d.kind;
  216. if (lastDeviceKind != PointerDeviceKind.touch) {
  217. return;
  218. }
  219. _doubleFinerTapPosition = d.localPosition;
  220. // ignore for desktop and mobile
  221. }
  222. onDoubleFinerTap(TapDownDetails d) async {
  223. lastDeviceKind = d.kind;
  224. if (lastDeviceKind != PointerDeviceKind.touch) {
  225. return;
  226. }
  227. // mobile mouse mode or desktop touch screen
  228. final isMobileMouseMode = isMobile && !ffiModel.touchMode;
  229. // We can't use `d.localPosition` here because it's always (0, 0) on desktop.
  230. final isDesktopInRemoteRect = (isDesktop || isWebDesktop) &&
  231. ffi.cursorModel.isInRemoteRect(_doubleFinerTapPosition);
  232. if (isMobileMouseMode || isDesktopInRemoteRect) {
  233. await inputModel.tap(MouseButtons.right);
  234. }
  235. }
  236. onHoldDragStart(DragStartDetails d) async {
  237. lastDeviceKind = d.kind;
  238. if (lastDeviceKind != PointerDeviceKind.touch) {
  239. return;
  240. }
  241. if (!handleTouch) {
  242. await inputModel.sendMouse('down', MouseButtons.left);
  243. }
  244. }
  245. onHoldDragUpdate(DragUpdateDetails d) async {
  246. if (lastDeviceKind != PointerDeviceKind.touch) {
  247. return;
  248. }
  249. if (!handleTouch) {
  250. await ffi.cursorModel.updatePan(d.delta, d.localPosition, handleTouch);
  251. }
  252. }
  253. onHoldDragEnd(DragEndDetails d) async {
  254. if (lastDeviceKind != PointerDeviceKind.touch) {
  255. return;
  256. }
  257. if (!handleTouch) {
  258. await inputModel.sendMouse('up', MouseButtons.left);
  259. }
  260. }
  261. onOneFingerPanStart(BuildContext context, DragStartDetails d) async {
  262. final TapDownDetails? lastTapDownDetails = _lastTapDownDetails;
  263. _lastTapDownDetails = null;
  264. lastDeviceKind = d.kind ?? lastDeviceKind;
  265. if (lastDeviceKind != PointerDeviceKind.touch) {
  266. return;
  267. }
  268. if (handleTouch) {
  269. if (lastTapDownDetails != null) {
  270. await ffi.cursorModel.move(lastTapDownDetails.localPosition.dx,
  271. lastTapDownDetails.localPosition.dy);
  272. }
  273. if (ffi.cursorModel.shouldBlock(d.localPosition.dx, d.localPosition.dy)) {
  274. return;
  275. }
  276. if (!ffi.cursorModel.isInRemoteRect(d.localPosition)) {
  277. return;
  278. }
  279. _touchModePanStarted = true;
  280. if (isDesktop || isWebDesktop) {
  281. ffi.cursorModel.trySetRemoteWindowCoords();
  282. }
  283. // Workaround for the issue that the first pan event is sent a long time after the start event.
  284. // If the time interval between the start event and the first pan event is less than 500ms,
  285. // we consider to use the long press position as the start position.
  286. //
  287. // TODO: We should find a better way to send the first pan event as soon as possible.
  288. if (DateTime.now().millisecondsSinceEpoch - _cacheLongPressPositionTs <
  289. 500) {
  290. await ffi.cursorModel
  291. .move(_cacheLongPressPosition.dx, _cacheLongPressPosition.dy);
  292. }
  293. await inputModel.sendMouse('down', MouseButtons.left);
  294. await ffi.cursorModel.move(d.localPosition.dx, d.localPosition.dy);
  295. } else {
  296. final offset = ffi.cursorModel.offset;
  297. final cursorX = offset.dx;
  298. final cursorY = offset.dy;
  299. final visible =
  300. ffi.cursorModel.getVisibleRect().inflate(1); // extend edges
  301. final size = MediaQueryData.fromView(View.of(context)).size;
  302. if (!visible.contains(Offset(cursorX, cursorY))) {
  303. await ffi.cursorModel.move(size.width / 2, size.height / 2);
  304. }
  305. }
  306. }
  307. onOneFingerPanUpdate(DragUpdateDetails d) async {
  308. if (lastDeviceKind != PointerDeviceKind.touch) {
  309. return;
  310. }
  311. if (ffi.cursorModel.shouldBlock(d.localPosition.dx, d.localPosition.dy)) {
  312. return;
  313. }
  314. if (handleTouch && !_touchModePanStarted) {
  315. return;
  316. }
  317. await ffi.cursorModel.updatePan(d.delta, d.localPosition, handleTouch);
  318. }
  319. onOneFingerPanEnd(DragEndDetails d) async {
  320. _touchModePanStarted = false;
  321. if (lastDeviceKind != PointerDeviceKind.touch) {
  322. return;
  323. }
  324. if (isDesktop || isWebDesktop) {
  325. ffi.cursorModel.clearRemoteWindowCoords();
  326. }
  327. if (handleTouch) {
  328. await inputModel.sendMouse('up', MouseButtons.left);
  329. }
  330. }
  331. // scale + pan event
  332. onTwoFingerScaleStart(ScaleStartDetails d) {
  333. _lastTapDownDetails = null;
  334. if (lastDeviceKind != PointerDeviceKind.touch) {
  335. return;
  336. }
  337. }
  338. onTwoFingerScaleUpdate(ScaleUpdateDetails d) async {
  339. if (lastDeviceKind != PointerDeviceKind.touch) {
  340. return;
  341. }
  342. if ((isDesktop || isWebDesktop)) {
  343. final scale = ((d.scale - _scale) * 1000).toInt();
  344. _scale = d.scale;
  345. if (scale != 0) {
  346. await bind.sessionSendPointer(
  347. sessionId: sessionId,
  348. msg: json.encode(
  349. PointerEventToRust(kPointerEventKindTouch, 'scale', scale)
  350. .toJson()));
  351. }
  352. } else {
  353. // mobile
  354. ffi.canvasModel.updateScale(d.scale / _scale, d.focalPoint);
  355. _scale = d.scale;
  356. ffi.canvasModel.panX(d.focalPointDelta.dx);
  357. ffi.canvasModel.panY(d.focalPointDelta.dy);
  358. }
  359. }
  360. onTwoFingerScaleEnd(ScaleEndDetails d) async {
  361. if (lastDeviceKind != PointerDeviceKind.touch) {
  362. return;
  363. }
  364. if ((isDesktop || isWebDesktop)) {
  365. await bind.sessionSendPointer(
  366. sessionId: sessionId,
  367. msg: json.encode(
  368. PointerEventToRust(kPointerEventKindTouch, 'scale', 0).toJson()));
  369. } else {
  370. // mobile
  371. _scale = 1;
  372. // No idea why we need to set the view style to "" here.
  373. // bind.sessionSetViewStyle(sessionId: sessionId, value: "");
  374. }
  375. await inputModel.sendMouse('up', MouseButtons.left);
  376. }
  377. get onHoldDragCancel => null;
  378. get onThreeFingerVerticalDragUpdate => ffi.ffiModel.isPeerAndroid
  379. ? null
  380. : (d) {
  381. _mouseScrollIntegral += d.delta.dy / 4;
  382. if (_mouseScrollIntegral > 1) {
  383. inputModel.scroll(1);
  384. _mouseScrollIntegral = 0;
  385. } else if (_mouseScrollIntegral < -1) {
  386. inputModel.scroll(-1);
  387. _mouseScrollIntegral = 0;
  388. }
  389. };
  390. makeGestures(BuildContext context) {
  391. return <Type, GestureRecognizerFactory>{
  392. // Official
  393. TapGestureRecognizer:
  394. GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
  395. () => TapGestureRecognizer(), (instance) {
  396. instance
  397. ..onTapDown = onTapDown
  398. ..onTapUp = onTapUp
  399. ..onTap = onTap;
  400. }),
  401. DoubleTapGestureRecognizer:
  402. GestureRecognizerFactoryWithHandlers<DoubleTapGestureRecognizer>(
  403. () => DoubleTapGestureRecognizer(), (instance) {
  404. instance
  405. ..onDoubleTapDown = onDoubleTapDown
  406. ..onDoubleTap = onDoubleTap;
  407. }),
  408. LongPressGestureRecognizer:
  409. GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
  410. () => LongPressGestureRecognizer(), (instance) {
  411. instance
  412. ..onLongPressDown = onLongPressDown
  413. ..onLongPressUp = onLongPressUp
  414. ..onLongPress = onLongPress
  415. ..onLongPressMoveUpdate = onLongPressMoveUpdate;
  416. }),
  417. // Customized
  418. HoldTapMoveGestureRecognizer:
  419. GestureRecognizerFactoryWithHandlers<HoldTapMoveGestureRecognizer>(
  420. () => HoldTapMoveGestureRecognizer(),
  421. (instance) => instance
  422. ..onHoldDragStart = onHoldDragStart
  423. ..onHoldDragUpdate = onHoldDragUpdate
  424. ..onHoldDragCancel = onHoldDragCancel
  425. ..onHoldDragEnd = onHoldDragEnd),
  426. DoubleFinerTapGestureRecognizer:
  427. GestureRecognizerFactoryWithHandlers<DoubleFinerTapGestureRecognizer>(
  428. () => DoubleFinerTapGestureRecognizer(), (instance) {
  429. instance
  430. ..onDoubleFinerTap = onDoubleFinerTap
  431. ..onDoubleFinerTapDown = onDoubleFinerTapDown;
  432. }),
  433. CustomTouchGestureRecognizer:
  434. GestureRecognizerFactoryWithHandlers<CustomTouchGestureRecognizer>(
  435. () => CustomTouchGestureRecognizer(), (instance) {
  436. instance.onOneFingerPanStart =
  437. (DragStartDetails d) => onOneFingerPanStart(context, d);
  438. instance
  439. ..onOneFingerPanUpdate = onOneFingerPanUpdate
  440. ..onOneFingerPanEnd = onOneFingerPanEnd
  441. ..onTwoFingerScaleStart = onTwoFingerScaleStart
  442. ..onTwoFingerScaleUpdate = onTwoFingerScaleUpdate
  443. ..onTwoFingerScaleEnd = onTwoFingerScaleEnd
  444. ..onThreeFingerVerticalDragUpdate = onThreeFingerVerticalDragUpdate;
  445. }),
  446. };
  447. }
  448. }
  449. class RawPointerMouseRegion extends StatelessWidget {
  450. final InputModel inputModel;
  451. final Widget child;
  452. final MouseCursor? cursor;
  453. final PointerEnterEventListener? onEnter;
  454. final PointerExitEventListener? onExit;
  455. final PointerDownEventListener? onPointerDown;
  456. final PointerUpEventListener? onPointerUp;
  457. RawPointerMouseRegion({
  458. this.onEnter,
  459. this.onExit,
  460. this.cursor,
  461. this.onPointerDown,
  462. this.onPointerUp,
  463. required this.inputModel,
  464. required this.child,
  465. });
  466. @override
  467. Widget build(BuildContext context) {
  468. return Listener(
  469. onPointerHover: inputModel.onPointHoverImage,
  470. onPointerDown: (evt) {
  471. onPointerDown?.call(evt);
  472. inputModel.onPointDownImage(evt);
  473. },
  474. onPointerUp: (evt) {
  475. onPointerUp?.call(evt);
  476. inputModel.onPointUpImage(evt);
  477. },
  478. onPointerMove: inputModel.onPointMoveImage,
  479. onPointerSignal: inputModel.onPointerSignalImage,
  480. onPointerPanZoomStart: inputModel.onPointerPanZoomStart,
  481. onPointerPanZoomUpdate: inputModel.onPointerPanZoomUpdate,
  482. onPointerPanZoomEnd: inputModel.onPointerPanZoomEnd,
  483. child: MouseRegion(
  484. cursor: inputModel.isViewOnly
  485. ? MouseCursor.defer
  486. : (cursor ?? MouseCursor.defer),
  487. onEnter: onEnter,
  488. onExit: onExit,
  489. child: child,
  490. ),
  491. );
  492. }
  493. }