remote_input.dart 18 KB

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