remote_input.dart 18 KB

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