remote_input.dart 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  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. await inputModel.sendMouse('up', MouseButtons.left);
  308. }
  309. // scale + pan event
  310. onTwoFingerScaleStart(ScaleStartDetails d) {
  311. _lastTapDownDetails = null;
  312. if (lastDeviceKind != PointerDeviceKind.touch) {
  313. return;
  314. }
  315. }
  316. onTwoFingerScaleUpdate(ScaleUpdateDetails d) async {
  317. if (lastDeviceKind != PointerDeviceKind.touch) {
  318. return;
  319. }
  320. if ((isDesktop || isWebDesktop)) {
  321. final scale = ((d.scale - _scale) * 1000).toInt();
  322. _scale = d.scale;
  323. if (scale != 0) {
  324. await bind.sessionSendPointer(
  325. sessionId: sessionId,
  326. msg: json.encode(
  327. PointerEventToRust(kPointerEventKindTouch, 'scale', scale)
  328. .toJson()));
  329. }
  330. } else {
  331. // mobile
  332. ffi.canvasModel.updateScale(d.scale / _scale, d.focalPoint);
  333. _scale = d.scale;
  334. ffi.canvasModel.panX(d.focalPointDelta.dx);
  335. ffi.canvasModel.panY(d.focalPointDelta.dy);
  336. }
  337. }
  338. onTwoFingerScaleEnd(ScaleEndDetails d) async {
  339. if (lastDeviceKind != PointerDeviceKind.touch) {
  340. return;
  341. }
  342. if ((isDesktop || isWebDesktop)) {
  343. await bind.sessionSendPointer(
  344. sessionId: sessionId,
  345. msg: json.encode(
  346. PointerEventToRust(kPointerEventKindTouch, 'scale', 0).toJson()));
  347. } else {
  348. // mobile
  349. _scale = 1;
  350. // No idea why we need to set the view style to "" here.
  351. // bind.sessionSetViewStyle(sessionId: sessionId, value: "");
  352. }
  353. await inputModel.sendMouse('up', MouseButtons.left);
  354. }
  355. get onHoldDragCancel => null;
  356. get onThreeFingerVerticalDragUpdate => ffi.ffiModel.isPeerAndroid
  357. ? null
  358. : (d) {
  359. _mouseScrollIntegral += d.delta.dy / 4;
  360. if (_mouseScrollIntegral > 1) {
  361. inputModel.scroll(1);
  362. _mouseScrollIntegral = 0;
  363. } else if (_mouseScrollIntegral < -1) {
  364. inputModel.scroll(-1);
  365. _mouseScrollIntegral = 0;
  366. }
  367. };
  368. makeGestures(BuildContext context) {
  369. return <Type, GestureRecognizerFactory>{
  370. // Official
  371. TapGestureRecognizer:
  372. GestureRecognizerFactoryWithHandlers<TapGestureRecognizer>(
  373. () => TapGestureRecognizer(), (instance) {
  374. instance
  375. ..onTapDown = onTapDown
  376. ..onTapUp = onTapUp
  377. ..onTap = onTap;
  378. }),
  379. DoubleTapGestureRecognizer:
  380. GestureRecognizerFactoryWithHandlers<DoubleTapGestureRecognizer>(
  381. () => DoubleTapGestureRecognizer(), (instance) {
  382. instance
  383. ..onDoubleTapDown = onDoubleTapDown
  384. ..onDoubleTap = onDoubleTap;
  385. }),
  386. LongPressGestureRecognizer:
  387. GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
  388. () => LongPressGestureRecognizer(), (instance) {
  389. instance
  390. ..onLongPressDown = onLongPressDown
  391. ..onLongPressUp = onLongPressUp
  392. ..onLongPress = onLongPress;
  393. }),
  394. // Customized
  395. HoldTapMoveGestureRecognizer:
  396. GestureRecognizerFactoryWithHandlers<HoldTapMoveGestureRecognizer>(
  397. () => HoldTapMoveGestureRecognizer(),
  398. (instance) => instance
  399. ..onHoldDragStart = onHoldDragStart
  400. ..onHoldDragUpdate = onHoldDragUpdate
  401. ..onHoldDragCancel = onHoldDragCancel
  402. ..onHoldDragEnd = onHoldDragEnd),
  403. DoubleFinerTapGestureRecognizer:
  404. GestureRecognizerFactoryWithHandlers<DoubleFinerTapGestureRecognizer>(
  405. () => DoubleFinerTapGestureRecognizer(), (instance) {
  406. instance
  407. ..onDoubleFinerTap = onDoubleFinerTap
  408. ..onDoubleFinerTapDown = onDoubleFinerTapDown;
  409. }),
  410. CustomTouchGestureRecognizer:
  411. GestureRecognizerFactoryWithHandlers<CustomTouchGestureRecognizer>(
  412. () => CustomTouchGestureRecognizer(), (instance) {
  413. instance.onOneFingerPanStart =
  414. (DragStartDetails d) => onOneFingerPanStart(context, d);
  415. instance
  416. ..onOneFingerPanUpdate = onOneFingerPanUpdate
  417. ..onOneFingerPanEnd = onOneFingerPanEnd
  418. ..onTwoFingerScaleStart = onTwoFingerScaleStart
  419. ..onTwoFingerScaleUpdate = onTwoFingerScaleUpdate
  420. ..onTwoFingerScaleEnd = onTwoFingerScaleEnd
  421. ..onThreeFingerVerticalDragUpdate = onThreeFingerVerticalDragUpdate;
  422. }),
  423. };
  424. }
  425. }
  426. class RawPointerMouseRegion extends StatelessWidget {
  427. final InputModel inputModel;
  428. final Widget child;
  429. final MouseCursor? cursor;
  430. final PointerEnterEventListener? onEnter;
  431. final PointerExitEventListener? onExit;
  432. final PointerDownEventListener? onPointerDown;
  433. final PointerUpEventListener? onPointerUp;
  434. RawPointerMouseRegion({
  435. this.onEnter,
  436. this.onExit,
  437. this.cursor,
  438. this.onPointerDown,
  439. this.onPointerUp,
  440. required this.inputModel,
  441. required this.child,
  442. });
  443. @override
  444. Widget build(BuildContext context) {
  445. return Listener(
  446. onPointerHover: inputModel.onPointHoverImage,
  447. onPointerDown: (evt) {
  448. onPointerDown?.call(evt);
  449. inputModel.onPointDownImage(evt);
  450. },
  451. onPointerUp: (evt) {
  452. onPointerUp?.call(evt);
  453. inputModel.onPointUpImage(evt);
  454. },
  455. onPointerMove: inputModel.onPointMoveImage,
  456. onPointerSignal: inputModel.onPointerSignalImage,
  457. onPointerPanZoomStart: inputModel.onPointerPanZoomStart,
  458. onPointerPanZoomUpdate: inputModel.onPointerPanZoomUpdate,
  459. onPointerPanZoomEnd: inputModel.onPointerPanZoomEnd,
  460. child: MouseRegion(
  461. cursor: inputModel.isViewOnly
  462. ? MouseCursor.defer
  463. : (cursor ?? MouseCursor.defer),
  464. onEnter: onEnter,
  465. onExit: onExit,
  466. child: child,
  467. ),
  468. );
  469. }
  470. }