Compare commits
17
Commits
@@ -874,7 +874,7 @@ jobs:
|
||||
- name: Test cursor sizing
|
||||
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
|
||||
working-directory: flutter
|
||||
run: flutter test --timeout 60s test/cursor_size_test.dart test/cursor_replay_test.dart test/cursor_default_test.dart
|
||||
run: flutter test --timeout 60s test/cursor_size_test.dart
|
||||
|
||||
- name: Setup vcpkg with Github Actions binary cache
|
||||
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
||||
|
||||
@@ -48,6 +48,20 @@ workspace member. `base::config::keys` re-exports the handful of keys
|
||||
* Do not add dependencies unless needed.
|
||||
* Keep code simple and idiomatic.
|
||||
|
||||
### Logging
|
||||
|
||||
* `debug` and above are written to the log file. A log call that can fire
|
||||
repeatedly (per packet, frame, input event, or loop iteration, or at a rate a
|
||||
peer controls) must not use `debug` or higher unthrottled.
|
||||
* For such a site, pick one:
|
||||
|
||||
* `log::trace!` when the event is expected and the line only helps while
|
||||
actively debugging;
|
||||
* `hbb_common::throttled_log!(interval, level, ...)` when it signals a fault
|
||||
that should still show up in a user's log. It keeps one line per interval
|
||||
with a count of the rest. Use `hbb_common::log_throttle::LogThrottle`
|
||||
directly only when the decision drives more than one log call.
|
||||
|
||||
## Tokio Rules
|
||||
|
||||
* Assume a Tokio runtime already exists.
|
||||
@@ -127,6 +141,15 @@ Before considering any implementation complete, perform a minimization pass over
|
||||
* Before finalizing, explicitly report the regression surface: list the existing files and existing runtime paths whose behavior changed, and explain why each change is unavoidable.
|
||||
* During review, treat an unnecessarily modified legacy path as a review finding even if tests pass and the rewritten behavior appears equivalent.
|
||||
|
||||
### Corner cases raised in review
|
||||
|
||||
A refactor added to cover a corner case rarely converges. Each new counter, timestamp, cache or eviction/expiry rule interacts with state that existing code relies on, and the next review round finds the problems it introduced.
|
||||
|
||||
* A corner case is still worth fixing when the fix is easy and low-risk: a local change of a few lines that adds no state and changes no existing lookup, such as moving a check or refusing bad input earlier.
|
||||
* When the only fix needs new state, a new lifecycle rule or a restructure, and the code already fails cleanly there or behaves as master does, document it as a known limit in the PR instead. Anything beyond the easy fix needs the maintainer's explicit go-ahead first.
|
||||
* Before adding state that reorders, expires or reuses existing data, list every lookup that reads that data and check each one still holds.
|
||||
* Prefer a clean failure, where the operation reports an error, over machinery that tries to make a rare case succeed.
|
||||
|
||||
## Reviewing a PR
|
||||
|
||||
* Review only what the diff introduces. Verify ownership with `gh pr diff` before reporting a finding — if the offending lines are untouched context, it is a pre-existing problem, not this PR's.
|
||||
|
||||
Generated
-7
@@ -7196,7 +7196,6 @@ dependencies = [
|
||||
"wol-rs",
|
||||
"x11-clipboard 0.8.1",
|
||||
"x11rb 0.12.0",
|
||||
"xxhash-rust",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
@@ -10807,12 +10806,6 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
|
||||
|
||||
[[package]]
|
||||
name = "xxhash-rust"
|
||||
version = "0.8.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
|
||||
|
||||
[[package]]
|
||||
name = "yasna"
|
||||
version = "0.5.2"
|
||||
|
||||
@@ -63,7 +63,6 @@ lazy_static = "1.4"
|
||||
sha2 = "0.10"
|
||||
repng = "0.2"
|
||||
zstd = "0.13"
|
||||
xxhash-rust = { version = "0.8", features = ["xxh3"] }
|
||||
parity-tokio-ipc = { git = "https://github.com/rustdesk-org/parity-tokio-ipc" }
|
||||
magnum-opus = { git = "https://github.com/rustdesk-org/magnum-opus" }
|
||||
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
|
||||
|
||||
+50
-277
@@ -58,8 +58,7 @@ const _restartReconnectSilentDelaySecs = 5;
|
||||
class CachedPeerData {
|
||||
Map<String, dynamic> updatePrivacyMode = {};
|
||||
Map<String, dynamic> peerInfo = {};
|
||||
// No shapes: the core keeps them for the session, and the window a tab moves to asks it
|
||||
// for the one in use.
|
||||
List<Map<String, dynamic>> cursorDataList = [];
|
||||
Map<String, dynamic> lastCursorId = {};
|
||||
Map<String, bool> permissions = {};
|
||||
|
||||
@@ -74,6 +73,7 @@ class CachedPeerData {
|
||||
return jsonEncode({
|
||||
'updatePrivacyMode': updatePrivacyMode,
|
||||
'peerInfo': peerInfo,
|
||||
'cursorDataList': cursorDataList,
|
||||
'lastCursorId': lastCursorId,
|
||||
'permissions': permissions,
|
||||
'secure': secure,
|
||||
@@ -88,6 +88,9 @@ class CachedPeerData {
|
||||
final data = CachedPeerData();
|
||||
data.updatePrivacyMode = map['updatePrivacyMode'];
|
||||
data.peerInfo = map['peerInfo'];
|
||||
for (final cursorData in map['cursorDataList']) {
|
||||
data.cursorDataList.add(cursorData);
|
||||
}
|
||||
data.lastCursorId = map['lastCursorId'];
|
||||
map['permissions'].forEach((key, value) {
|
||||
data.permissions[key] = value;
|
||||
@@ -320,6 +323,10 @@ class FfiModel with ChangeNotifier {
|
||||
updatePrivacyMode(data.updatePrivacyMode, sessionId, peerId);
|
||||
setConnectionType(peerId, data.secure, data.direct, data.streamType);
|
||||
await handlePeerInfo(data.peerInfo, peerId, true);
|
||||
for (final element in data.cursorDataList) {
|
||||
updateLastCursorId(element);
|
||||
await handleCursorData(element);
|
||||
}
|
||||
if (data.lastCursorId.isNotEmpty) {
|
||||
updateLastCursorId(data.lastCursorId);
|
||||
handleCursorId(data.lastCursorId);
|
||||
@@ -349,6 +356,9 @@ class FfiModel with ChangeNotifier {
|
||||
} else if (name == 'switch_display') {
|
||||
// switch display is kept for backward compatibility
|
||||
handleSwitchDisplay(evt, sessionId, peerId);
|
||||
} else if (name == 'cursor_data') {
|
||||
updateLastCursorId(evt);
|
||||
await handleCursorData(evt);
|
||||
} else if (name == 'cursor_id') {
|
||||
updateLastCursorId(evt);
|
||||
handleCursorId(evt);
|
||||
@@ -1652,14 +1662,9 @@ class FfiModel with ChangeNotifier {
|
||||
parent.target?.cursorModel.updateCursorId(evt);
|
||||
}
|
||||
|
||||
/// A shape arriving is the shape in use, as a cursor_id is.
|
||||
handleCursorData(String id, int hotx, int hoty, int width, int height,
|
||||
Uint8List colors) async {
|
||||
// The replay selects this last, whatever the order the shapes are replayed in.
|
||||
cachedPeerData.lastCursorId = {'id': id};
|
||||
parent.target?.cursorModel.id = id;
|
||||
await parent.target?.cursorModel
|
||||
.updateCursorData(id, hotx, hoty, width, height, colors);
|
||||
handleCursorData(Map<String, dynamic> evt) async {
|
||||
cachedPeerData.cursorDataList.add(evt);
|
||||
await parent.target?.cursorModel.updateCursorData(evt);
|
||||
}
|
||||
|
||||
/// Handle the peer info synchronization event based on [evt].
|
||||
@@ -2853,13 +2858,12 @@ class CanvasModel with ChangeNotifier {
|
||||
|
||||
// data for cursor
|
||||
class CursorData {
|
||||
// At most 1 MiB of RGBA, including Linux's square cursor padding: twice the largest
|
||||
// accessibility cursor, beyond which a cursor is shown smaller rather than larger.
|
||||
static const _maxRasterSize = 512;
|
||||
// At most 4 MiB of RGBA, including Linux's square cursor padding.
|
||||
static const _maxRasterSize = 1024;
|
||||
|
||||
final String peerId;
|
||||
final String id;
|
||||
img2.Image? _image;
|
||||
final img2.Image image;
|
||||
double scale;
|
||||
Uint8List? data;
|
||||
final double hotxOrigin;
|
||||
@@ -2875,28 +2879,17 @@ class CursorData {
|
||||
int get rasterWidth => _rasterWidth;
|
||||
int get rasterHeight => _rasterHeight;
|
||||
|
||||
img2.Image get image => _image!;
|
||||
|
||||
/// False for a shape not in use; only the shape in use keeps pixels, for a new raster.
|
||||
bool get hasPixels => _image != null;
|
||||
|
||||
void releasePixels() {
|
||||
_image = null;
|
||||
data = null;
|
||||
}
|
||||
|
||||
CursorData({
|
||||
required this.peerId,
|
||||
required this.id,
|
||||
required img2.Image image,
|
||||
required this.image,
|
||||
required this.scale,
|
||||
required this.data,
|
||||
required this.hotxOrigin,
|
||||
required this.hotyOrigin,
|
||||
required this.width,
|
||||
required this.height,
|
||||
}) : _image = image,
|
||||
_rasterWidth = (width * scale).ceil(),
|
||||
}) : _rasterWidth = (width * scale).ceil(),
|
||||
_rasterHeight = (height * scale).ceil(),
|
||||
hotx = hotxOrigin * scale,
|
||||
hoty = hotyOrigin * scale;
|
||||
@@ -2928,13 +2921,6 @@ class CursorData {
|
||||
|
||||
final targetWidth = (width * scale).ceil();
|
||||
final targetHeight = (height * scale).ceil();
|
||||
if ((_rasterWidth != targetWidth || _rasterHeight != targetHeight) &&
|
||||
!hasPixels) {
|
||||
// Nothing to make this raster from; buildCursorOfCache asks for the pixels unless its
|
||||
// native cursor was made before.
|
||||
data = null;
|
||||
return scale;
|
||||
}
|
||||
if (_rasterWidth != targetWidth || _rasterHeight != targetHeight) {
|
||||
if (isWindows) {
|
||||
data = img2
|
||||
@@ -3005,9 +2991,7 @@ class CursorData {
|
||||
|
||||
String updateGetKey(double scale) {
|
||||
scale = _checkUpdateScale(scale);
|
||||
// The raster asked for, not the one made last: a shape without pixels keeps the native
|
||||
// cursors of every raster it was shown at.
|
||||
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}_${(width * scale).ceil()}_${(height * scale).ceil()}';
|
||||
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}_${rasterWidth}_$rasterHeight';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3178,16 +3162,7 @@ class CursorModel with ChangeNotifier {
|
||||
|
||||
get lastIsBlocked => _lastIsBlocked;
|
||||
|
||||
/// The image of the shape in use, or the one shown before until it is back: a switch falls
|
||||
/// back to the default cursor only for a shape the core cannot give. Asks the core for the
|
||||
/// shape in use when it was let go.
|
||||
ui.Image? get image {
|
||||
if (_images[_id] == null && _cacheMap.containsKey(_id)) {
|
||||
restorePixels(_id);
|
||||
}
|
||||
return _image;
|
||||
}
|
||||
|
||||
ui.Image? get image => _image;
|
||||
CursorData? get cache => _cache;
|
||||
|
||||
double get x => _x - _displayOriginX;
|
||||
@@ -3200,10 +3175,7 @@ class CursorModel with ChangeNotifier {
|
||||
double get hotx => _hotx;
|
||||
double get hoty => _hoty;
|
||||
|
||||
set id(String id) {
|
||||
if (_id != id) _unavailable = null;
|
||||
_id = id;
|
||||
}
|
||||
set id(String id) => _id = id;
|
||||
|
||||
bool get isPeerControlProtected =>
|
||||
DateTime.now().difference(_lastPeerMouse).inMilliseconds <
|
||||
@@ -3218,12 +3190,7 @@ class CursorModel with ChangeNotifier {
|
||||
}
|
||||
}
|
||||
|
||||
CursorModel(this.parent) {
|
||||
// Made now, not when first drawn: nothing draws again when their decode lands, so the first
|
||||
// build that needs one would show the shape before in its place.
|
||||
preDefaultCursor.cache;
|
||||
preForbiddenCursor.cache;
|
||||
}
|
||||
CursorModel(this.parent);
|
||||
|
||||
Set<String> get cachedKeys => _cacheKeys;
|
||||
addKey(String key) => _cacheKeys.add(key);
|
||||
@@ -3522,44 +3489,30 @@ class CursorModel with ChangeNotifier {
|
||||
_images.clear();
|
||||
}
|
||||
|
||||
/// Its image is kept with the ones used last, see [_imageLimit]; a shape that does not decode
|
||||
/// is marked as one the core cannot give.
|
||||
Future<void> updateCursorData(String id, int hotxInt, int hotyInt, int width,
|
||||
int height, Uint8List rgba) async {
|
||||
final generation = _generation;
|
||||
if (_unavailable == id) _unavailable = null;
|
||||
final hotx = hotxInt.toDouble();
|
||||
final hoty = hotyInt.toDouble();
|
||||
updateCursorData(Map<String, dynamic> evt) async {
|
||||
final id = evt['id'];
|
||||
final hotx = double.parse(evt['hotx']);
|
||||
final hoty = double.parse(evt['hoty']);
|
||||
final width = int.parse(evt['width']);
|
||||
final height = int.parse(evt['height']);
|
||||
List<dynamic> colors = json.decode(evt['colors']);
|
||||
final rgba = Uint8List.fromList(colors.map((s) => s as int).toList());
|
||||
final image = await img.decodeImageFromPixels(
|
||||
rgba, width, height, ui.PixelFormat.rgba8888);
|
||||
if (image == null) {
|
||||
// It did not decode; painting must not ask for it on every frame.
|
||||
_markUnavailable(generation, id);
|
||||
return;
|
||||
}
|
||||
if (!await _updateCache(
|
||||
generation, rgba, image, id, hotx, hoty, width, height)) {
|
||||
// Not kept, or the session was cleared while it decoded.
|
||||
image.dispose();
|
||||
_markUnavailable(generation, id);
|
||||
return;
|
||||
}
|
||||
final old = _images.remove(id);
|
||||
_images[id] = Tuple3(image, hotx, hoty);
|
||||
if (old != null) {
|
||||
if (identical(old.item1, _image)) _image = image;
|
||||
old.item1.dispose();
|
||||
if (await _updateCache(rgba, image, id, hotx, hoty, width, height)) {
|
||||
_images[id]?.item1.dispose();
|
||||
_images[id] = Tuple3(image, hotx, hoty);
|
||||
}
|
||||
|
||||
// Update last cursor data.
|
||||
// Do not use the previous `image` and `id`, because `_id` may be changed.
|
||||
_updateCurData();
|
||||
final cache = _cacheMap[id];
|
||||
if (id != _id && cache != null) _switchedAway(cache);
|
||||
}
|
||||
|
||||
Future<bool> _updateCache(
|
||||
int generation,
|
||||
Uint8List rgba,
|
||||
ui.Image image,
|
||||
String id,
|
||||
@@ -3570,11 +3523,7 @@ class CursorModel with ChangeNotifier {
|
||||
) async {
|
||||
Uint8List? data;
|
||||
img2.Image imgOrigin = img2.Image.fromBytes(
|
||||
width: w,
|
||||
height: h,
|
||||
bytes: rgba.buffer,
|
||||
bytesOffset: rgba.offsetInBytes,
|
||||
order: img2.ChannelOrder.rgba);
|
||||
width: w, height: h, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
|
||||
if (isWindows) {
|
||||
data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
|
||||
} else {
|
||||
@@ -3607,200 +3556,34 @@ class CursorModel with ChangeNotifier {
|
||||
width: w,
|
||||
height: h,
|
||||
);
|
||||
if (generation != _generation) {
|
||||
return false;
|
||||
}
|
||||
_cacheMap[id] = cache;
|
||||
return true;
|
||||
}
|
||||
|
||||
@visibleForTesting
|
||||
Iterable<String> get shapeIds => _images.keys;
|
||||
|
||||
@visibleForTesting
|
||||
CursorData? cachedShape(String id) => _cacheMap[id];
|
||||
|
||||
final _restoring = <String>{};
|
||||
|
||||
// Tabs in a window share its engine's native cursors, predefined ones included.
|
||||
static int _nextKeyScope = 0;
|
||||
final int _keyScope = _nextKeyScope++;
|
||||
|
||||
String nativeKey(CursorData cache, double scale) {
|
||||
final key = '${_keyScope}_${cache.updateGetKey(scale)}';
|
||||
// A native cursor at another raster does not hold the pixels this one is made from.
|
||||
if (!_cacheKeys.contains(key)) _nativeIds.remove(cache.id);
|
||||
return key;
|
||||
}
|
||||
|
||||
// Native cursors stay for the session, one per raster of each shape, and only [clear]
|
||||
// deletes them, as before; unlike the painted images they have no LRU, for now. A delete
|
||||
// frees nothing on Windows: the engine's `deleteCustomCursor/windows` releases the HCURSOR
|
||||
// with `DeleteObject`, which does not take a cursor. Measured on Windows with 500 cursors
|
||||
// made by `CreateIconIndirect`, as the engine makes them: `DeleteObject` failed all 500 and
|
||||
// left 500 USER objects alive, while `DestroyCursor` or `DestroyIcon` freed all 500. Each
|
||||
// delete leaks its handle until the process exits, and making the cursor again for a raster
|
||||
// or a shape shown once more leaks another, so an LRU would leak more than keeping them.
|
||||
//
|
||||
// Fixing the engine is not cheap. x64 runs our fork, rustdesk/engine, on Flutter 3.24; the
|
||||
// fix is one more patch to rebuild, publish, and carry across every Flutter upgrade. arm64
|
||||
// runs the stock engine of a newer Flutter, which has the same code: fixing it means
|
||||
// porting the fork to that version and building and publishing an arm64 engine as well, or
|
||||
// an upstream fix and waiting for it to reach stable. Once both engines destroy cursors, an
|
||||
// LRU like the painted images' can come back. Content ids keep the count to the shapes the
|
||||
// peer really shows, a few dozen to a couple of hundred.
|
||||
|
||||
/// The shape in use keeps its pixels, so a new raster is made from them at once; the others
|
||||
/// keep none once their native cursor holds them.
|
||||
void registered(CursorData cache, String key) {
|
||||
_nativeIds.add(cache.id);
|
||||
_awaitingNative.remove(cache.id);
|
||||
if (cache.id != _id && identical(_cacheMap[cache.id], cache)) {
|
||||
cache.releasePixels();
|
||||
}
|
||||
}
|
||||
|
||||
// The shapes a native cursor holds, and those keeping their pixels until one does, oldest
|
||||
// first: one decoded after the peer moved on must still get a native cursor when shown
|
||||
// again, rather than be decoded again every time it comes back.
|
||||
final _nativeIds = <String>{};
|
||||
final _awaitingNative = <String>{};
|
||||
|
||||
void _switchedAway(CursorData cache) {
|
||||
_awaitingNative.remove(cache.id);
|
||||
// Mobile only paints the cursor, from its image.
|
||||
if (isMobile || _nativeIds.contains(cache.id)) {
|
||||
cache.releasePixels();
|
||||
return;
|
||||
}
|
||||
_awaitingNative.add(cache.id);
|
||||
while (_awaitingNative.length > kRecentShapes) {
|
||||
final oldest = _awaitingNative.first;
|
||||
_awaitingNative.remove(oldest);
|
||||
if (oldest != _id) _cacheMap[oldest]?.releasePixels();
|
||||
}
|
||||
}
|
||||
|
||||
/// The peer's shapes used last that keep a painted image, and the most that keep their pixels
|
||||
/// waiting for a native cursor; the core rebuilds the others. An animated cursor is a shape per
|
||||
/// frame, 18 for the Windows busy cursor and 23 for KDE's, and a cycle longer than this limit
|
||||
/// would rebuild every frame.
|
||||
static const kRecentShapes = 64;
|
||||
|
||||
/// The native cursor of the shape shown last, shown on while the shape in use is made.
|
||||
String? shownKey;
|
||||
|
||||
void shown(CursorData cache, String key) {
|
||||
// The forbidden cursor shows only while input is off; it is no stand-in for a shape.
|
||||
if (cache.id != kPreForbiddenCursorId) shownKey = key;
|
||||
}
|
||||
|
||||
/// Whether the desktop paints the peer's cursor over the remote image.
|
||||
@protected
|
||||
bool get showsRemoteCursor {
|
||||
final tag = ShowRemoteCursorState.tag(parent.target?.id ?? '');
|
||||
return Get.isRegistered<RxBool>(tag: tag) &&
|
||||
Get.find<RxBool>(tag: tag).value;
|
||||
}
|
||||
|
||||
// Painted images kept: mobile always paints the cursor, a desktop only when it shows the
|
||||
// remote cursor, and otherwise the native cursors show the shapes.
|
||||
int get _imageLimit => isMobile || showsRemoteCursor ? kRecentShapes : 1;
|
||||
|
||||
// `_images` is in order of use. The image painted is kept, whoever's it is.
|
||||
void _evictImages() {
|
||||
var excess = _images.length - _imageLimit;
|
||||
_images.removeWhere((id, shape) {
|
||||
if (excess <= 0 || id == _id || identical(shape.item1, _image)) {
|
||||
return false;
|
||||
}
|
||||
excess--;
|
||||
shape.item1.dispose();
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// The core keeps every shape the peer sent, compressed; see `Session::cursor_shapes`.
|
||||
@protected
|
||||
Future<CursorShape?> fetchCursorShape(String id) {
|
||||
final ffi = parent.target;
|
||||
if (ffi == null) return Future.value(null);
|
||||
return bind.sessionGetCursorShape(sessionId: ffi.sessionId, id: id);
|
||||
}
|
||||
|
||||
// The shape the core could not give, not asked for again while it is the one in use. One
|
||||
// is enough: only the shape in use is asked for on every frame, and the peer's ids must not
|
||||
// accumulate here.
|
||||
String? _unavailable;
|
||||
// Counts session clears, so that a decode finishing after one keeps nothing.
|
||||
int _generation = 0;
|
||||
|
||||
/// Decodes the shape in use again from the core, for a raster its native cursor lacks, for
|
||||
/// painting it, or for a window a tab moved to.
|
||||
void restorePixels(String id) {
|
||||
if (id != _id || _unavailable == id || !_restoring.add(id)) return;
|
||||
final generation = _generation;
|
||||
() async {
|
||||
try {
|
||||
// A throw becomes an error the await hands over later, not during the build that may
|
||||
// have asked: a failure tells the listeners.
|
||||
final shape = await Future.sync(() => fetchCursorShape(id));
|
||||
if (generation != _generation) {
|
||||
return;
|
||||
} else if (shape == null) {
|
||||
_markUnavailable(generation, id);
|
||||
debugPrint('Cursor $id is not kept by the core');
|
||||
} else {
|
||||
// Decoded even if the peer moved on: an animation comes back to it.
|
||||
await updateCursorData(id, shape.hotx, shape.hoty, shape.width,
|
||||
shape.height, shape.colors);
|
||||
}
|
||||
} catch (e) {
|
||||
_markUnavailable(generation, id);
|
||||
debugPrint('Failed to fetch cursor $id: $e');
|
||||
} finally {
|
||||
_restoring.remove(id);
|
||||
}
|
||||
}();
|
||||
}
|
||||
|
||||
void _markUnavailable(int generation, String id) {
|
||||
if (generation != _generation || id != _id) return;
|
||||
_unavailable = id;
|
||||
_updateCurData();
|
||||
}
|
||||
|
||||
bool _updateCurData() {
|
||||
final previous = _cache;
|
||||
final cache = _cacheMap[_id];
|
||||
// A shape not decoded yet leaves the one shown before in place until it is; one the core
|
||||
// cannot give leaves none, so the default cursor shows, as for a shape never sent.
|
||||
if (cache != null || _unavailable == _id) _cache = cache;
|
||||
if (previous != null && !identical(previous, _cache)) {
|
||||
_switchedAway(previous);
|
||||
}
|
||||
final tmp = _images.remove(_id);
|
||||
_cache = _cacheMap[_id];
|
||||
final tmp = _images[_id];
|
||||
if (tmp != null) {
|
||||
_images[_id] = tmp;
|
||||
_image = tmp.item1;
|
||||
_hotx = tmp.item2;
|
||||
_hoty = tmp.item3;
|
||||
} else if (_unavailable == _id) {
|
||||
_image = null;
|
||||
try {
|
||||
// may throw exception, because the listener maybe already dispose
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint(
|
||||
'WARNING: updateCursorId $_id, without notifyListeners(). $e');
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
_evictImages();
|
||||
try {
|
||||
// may throw exception, because the listener maybe already dispose
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
debugPrint('WARNING: updateCursorId $_id, without notifyListeners(). $e');
|
||||
}
|
||||
return tmp != null || cache != null;
|
||||
}
|
||||
|
||||
updateCursorId(Map<String, dynamic> evt) {
|
||||
if (!_updateCurData()) {
|
||||
restorePixels(_id);
|
||||
debugPrint(
|
||||
'WARNING: updateCursorId $_id, cache is ${_cache == null ? "null" : "not null"}. without notifyListeners()');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3853,10 +3636,6 @@ class CursorModel with ChangeNotifier {
|
||||
_clearCache();
|
||||
_cache = null;
|
||||
_cacheMap.clear();
|
||||
_nativeIds.clear();
|
||||
_awaitingNative.clear();
|
||||
_unavailable = null;
|
||||
_generation++;
|
||||
}
|
||||
|
||||
_clearCache() {
|
||||
@@ -3865,8 +3644,6 @@ class CursorModel with ChangeNotifier {
|
||||
debugPrint("deleting cursor with key $k");
|
||||
deleteCustomCursor(k);
|
||||
}
|
||||
_cacheKeys.clear();
|
||||
shownKey = null;
|
||||
resetSystemCursor();
|
||||
}
|
||||
|
||||
@@ -4206,7 +3983,6 @@ class FFI {
|
||||
}
|
||||
|
||||
if (isWeb) {
|
||||
platformFFI.setCursorDataCallback(ffiModel.handleCursorData);
|
||||
platformFFI.setRgbaCallback((int display, Uint8List data) {
|
||||
onEvent2UIRgba();
|
||||
imageModel.onRgba(display, data);
|
||||
@@ -4289,9 +4065,6 @@ class FFI {
|
||||
} else {
|
||||
platformFFI.nextRgba(sessionId, display);
|
||||
}
|
||||
} else if (message is EventToUI_Cursor) {
|
||||
await ffiModel.handleCursorData(message.id, message.hotx,
|
||||
message.hoty, message.width, message.height, message.colors);
|
||||
} else if (message is EventToUI_Texture) {
|
||||
final display = message.field0;
|
||||
final gpuTexture = message.field1;
|
||||
|
||||
@@ -285,10 +285,6 @@ class PlatformFFI {
|
||||
|
||||
void setRgbaCallback(void Function(int, Uint8List) fun) async {}
|
||||
|
||||
// web only
|
||||
void setCursorDataCallback(
|
||||
void Function(String, int, int, int, int, Uint8List) fun) async {}
|
||||
|
||||
// web only, decoded WebCodecs frames arriving as ready-made images
|
||||
void setVideoFrameCallback(
|
||||
Future<void> Function(int, ui.Image, bool Function()) fun) {}
|
||||
|
||||
@@ -189,17 +189,6 @@ class PlatformFFI {
|
||||
};
|
||||
}
|
||||
|
||||
// The web core calls this with a shape's pixels as bytes, as it calls onRgba for a frame.
|
||||
void setCursorDataCallback(
|
||||
void Function(String, int, int, int, int, Uint8List) fun) {
|
||||
context["onCursorData"] = (String id, int hotx, int hoty, int width,
|
||||
int height, Uint8List? rgba) {
|
||||
if (rgba != null) {
|
||||
fun(id, hotx, hoty, width, height, rgba);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
late final WebVideoFrameQueue<JSObject, ui.Image> _videoFrameQueue;
|
||||
|
||||
// Zero-readback video path: the JS decoder hands decoded VideoFrames here
|
||||
|
||||
@@ -16,15 +16,14 @@ resetSystemCursor() {}
|
||||
MouseCursor buildCursorOfCache(
|
||||
CursorModel cursor, double scale, CursorData? cache) {
|
||||
if (cache == null) {
|
||||
return _shownCursor(cursor);
|
||||
return MouseCursor.defer;
|
||||
} else {
|
||||
final key = cursor.nativeKey(cache, scale);
|
||||
final key = cache.updateGetKey(scale);
|
||||
if (!cursor.cachedKeys.contains(key)) {
|
||||
// data should be checked here, because it may be changed after `updateGetKey()`
|
||||
final data = cache.data;
|
||||
if (data == null) {
|
||||
cursor.restorePixels(cache.id);
|
||||
return _shownCursor(cursor);
|
||||
return MouseCursor.defer;
|
||||
}
|
||||
// Square canvases avoid clipping or stray edge pixels on Linux.
|
||||
final width = isLinux && cache.rasterWidth < cache.rasterHeight
|
||||
@@ -49,21 +48,11 @@ MouseCursor buildCursorOfCache(
|
||||
..hotX = cache.hotx
|
||||
..hotY = cache.hoty);
|
||||
cursor.addKey(key);
|
||||
cursor.registered(cache, key);
|
||||
}
|
||||
cursor.shown(cache, key);
|
||||
return FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
}
|
||||
|
||||
// The last shape's cursor stays while the one in use is made, rather than the system one.
|
||||
MouseCursor _shownCursor(CursorModel cursor) {
|
||||
final key = cursor.shownKey;
|
||||
return key == null
|
||||
? MouseCursor.defer
|
||||
: FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
|
||||
Uint8List _padCursor(Uint8List data, int size) {
|
||||
final bitmap = img.decodePng(data);
|
||||
if (bitmap == null) {
|
||||
|
||||
@@ -26,14 +26,6 @@ sealed class EventToUI {
|
||||
int field0,
|
||||
bool field1,
|
||||
) = EventToUI_Texture;
|
||||
const factory EventToUI.cursor({
|
||||
required String id,
|
||||
required int hotx,
|
||||
required int hoty,
|
||||
required int width,
|
||||
required int height,
|
||||
required Uint8List colors,
|
||||
}) = EventToUI_Cursor;
|
||||
}
|
||||
|
||||
class EventToUI_Event implements EventToUI {
|
||||
@@ -58,60 +50,7 @@ class EventToUI_Texture implements EventToUI {
|
||||
bool get field1 => f1;
|
||||
}
|
||||
|
||||
class EventToUI_Cursor implements EventToUI {
|
||||
const EventToUI_Cursor({
|
||||
required this.id,
|
||||
required this.hotx,
|
||||
required this.hoty,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.colors,
|
||||
});
|
||||
final String id;
|
||||
final int hotx;
|
||||
final int hoty;
|
||||
final int width;
|
||||
final int height;
|
||||
final Uint8List colors;
|
||||
}
|
||||
|
||||
class CursorShape {
|
||||
final int hotx;
|
||||
final int hoty;
|
||||
final int width;
|
||||
final int height;
|
||||
final Uint8List colors;
|
||||
|
||||
const CursorShape({
|
||||
required this.hotx,
|
||||
required this.hoty,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required this.colors,
|
||||
});
|
||||
}
|
||||
|
||||
class RustdeskImpl {
|
||||
// The core answers through the callback, before callMethod returns.
|
||||
Future<CursorShape?> sessionGetCursorShape(
|
||||
{required UuidValue sessionId, required String id, dynamic hint}) {
|
||||
final completer = Completer<CursorShape?>();
|
||||
js.context.callMethod('getCursorShape', [
|
||||
id,
|
||||
(int hotx, int hoty, int width, int height, Uint8List? colors) {
|
||||
completer.complete(colors == null
|
||||
? null
|
||||
: CursorShape(
|
||||
hotx: hotx,
|
||||
hoty: hoty,
|
||||
width: width,
|
||||
height: height,
|
||||
colors: colors));
|
||||
}
|
||||
]);
|
||||
return completer.future;
|
||||
}
|
||||
|
||||
Future<void> stopGlobalEventStream({required String appType, dynamic hint}) {
|
||||
throw UnimplementedError("stopGlobalEventStream");
|
||||
}
|
||||
|
||||
@@ -102,15 +102,14 @@ resetSystemCursor() => CursorManager.instance.resetSystemCursor();
|
||||
MouseCursor buildCursorOfCache(
|
||||
model.CursorModel cursor, double scale, model.CursorData? cache) {
|
||||
if (cache == null) {
|
||||
return _shownCursor(cursor);
|
||||
return MouseCursor.defer;
|
||||
} else {
|
||||
final key = cursor.nativeKey(cache, scale);
|
||||
final key = cache.updateGetKey(scale);
|
||||
if (!cursor.cachedKeys.contains(key)) {
|
||||
// data should be checked here, because it may be changed after `updateGetKey()`
|
||||
final data = cache.data;
|
||||
if (data == null) {
|
||||
cursor.restorePixels(cache.id);
|
||||
return _shownCursor(cursor);
|
||||
return MouseCursor.defer;
|
||||
}
|
||||
debugPrint(
|
||||
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
|
||||
@@ -122,17 +121,7 @@ MouseCursor buildCursorOfCache(
|
||||
hotX: cache.hotx,
|
||||
hotY: cache.hoty));
|
||||
cursor.addKey(key);
|
||||
cursor.registered(cache, key);
|
||||
}
|
||||
cursor.shown(cache, key);
|
||||
return FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
}
|
||||
|
||||
// The last shape's cursor stays while the one in use is made, rather than the system one.
|
||||
MouseCursor _shownCursor(model.CursorModel cursor) {
|
||||
final key = cursor.shownKey;
|
||||
return key == null
|
||||
? MouseCursor.defer
|
||||
: FlutterCustomMemoryImageCursor(key: key);
|
||||
}
|
||||
|
||||
@@ -1,66 +0,0 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
// A file of its own: nothing else in this isolate has made the default cursor before the model.
|
||||
|
||||
/// A core that keeps no shape.
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(FFI ffi) : super(WeakReference(ffi));
|
||||
@override
|
||||
Future<CursorShape?> fetchCursorShape(String id) => Future.value(null);
|
||||
@override
|
||||
bool get showsRemoteCursor => false;
|
||||
}
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI() {
|
||||
ffiModel = FfiModel(WeakReference(this));
|
||||
cursorModel = _Cursor(this);
|
||||
}
|
||||
@override
|
||||
final SessionID sessionId = const Uuid().v4obj();
|
||||
@override
|
||||
late final FfiModel ffiModel;
|
||||
@override
|
||||
late final CursorModel cursorModel;
|
||||
}
|
||||
|
||||
String? _key(MouseCursor cursor) =>
|
||||
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
|
||||
|
||||
void main() {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final channel = Platform.isWindows
|
||||
? SystemChannels.mouseCursor
|
||||
: const MethodChannel('flutter_custom_cursor');
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
|
||||
(call) async => (call.arguments as Map<dynamic, dynamic>)['name']);
|
||||
|
||||
test('a shape the core cannot give shows the default cursor at once',
|
||||
() async {
|
||||
final ffi = _FFI();
|
||||
final cursor = ffi.cursorModel;
|
||||
final pixels = Uint8List.fromList(List.generate(8 * 8 * 4, (i) => i % 256));
|
||||
await ffi.ffiModel.handleCursorData('1', 0, 0, 8, 8, pixels);
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
final evt = {'id': '2'};
|
||||
ffi.ffiModel.updateLastCursorId(evt);
|
||||
ffi.ffiModel.handleCursorId(evt);
|
||||
// Not a wait for the default cursor itself: asking for it would make it.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
expect(cursor.cache, isNull);
|
||||
final built = _key(buildCursorOfCache(
|
||||
cursor, 1.0, cursor.cache ?? preDefaultCursor.cache));
|
||||
expect(built, isNot(shown));
|
||||
expect(built, contains('_${kPreDefaultCursorId}_'));
|
||||
cursor.disposeImages();
|
||||
});
|
||||
}
|
||||
@@ -1,683 +0,0 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_custom_cursor/flutter_custom_cursor.dart';
|
||||
import 'package:flutter_hbb/common.dart';
|
||||
import 'package:flutter_hbb/generated_bridge.dart' show CursorShape;
|
||||
import 'package:flutter_hbb/models/model.dart';
|
||||
import 'package:flutter_hbb/native/custom_cursor.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
/// Stands in for the core, which keeps every shape the peer sent.
|
||||
class _Cursor extends CursorModel {
|
||||
_Cursor(FFI ffi) : super(WeakReference(ffi));
|
||||
final core = <String, CursorShape>{};
|
||||
final fetched = <String>[];
|
||||
// While set, a fetch answers only when [answerFetches] is called.
|
||||
bool holdFetches = false;
|
||||
// While set, a fetch throws before it returns a future.
|
||||
bool throwAtOnce = false;
|
||||
final _held = <Completer<CursorShape?>, String>{};
|
||||
@override
|
||||
Future<CursorShape?> fetchCursorShape(String id) {
|
||||
fetched.add(id);
|
||||
if (throwAtOnce) throw StateError('no core');
|
||||
if (!holdFetches) return Future.value(core[id]);
|
||||
final answer = Completer<CursorShape?>();
|
||||
_held[answer] = id;
|
||||
return answer.future;
|
||||
}
|
||||
|
||||
void answerFetches() {
|
||||
final held = Map.of(_held);
|
||||
_held.clear();
|
||||
held.forEach((answer, id) => answer.complete(core[id]));
|
||||
}
|
||||
|
||||
void failFetches() {
|
||||
final held = Map.of(_held);
|
||||
_held.clear();
|
||||
held.forEach((answer, _) => answer.completeError(StateError('failed')));
|
||||
}
|
||||
|
||||
bool showRemoteCursor = false;
|
||||
@override
|
||||
bool get showsRemoteCursor => showRemoteCursor;
|
||||
}
|
||||
|
||||
String? _key(MouseCursor cursor) =>
|
||||
cursor is FlutterCustomMemoryImageCursor ? cursor.key : null;
|
||||
|
||||
class _FFI extends Fake implements FFI {
|
||||
_FFI() {
|
||||
ffiModel = FfiModel(WeakReference(this));
|
||||
cursorModel = _Cursor(this);
|
||||
}
|
||||
@override
|
||||
final SessionID sessionId = const Uuid().v4obj();
|
||||
@override
|
||||
late final FfiModel ffiModel;
|
||||
@override
|
||||
late final CursorModel cursorModel;
|
||||
_Cursor get cursor => cursorModel as _Cursor;
|
||||
}
|
||||
|
||||
Uint8List _pixels(int size, int seed) =>
|
||||
Uint8List.fromList(List.generate(size * size * 4, (i) => (i + seed) % 256));
|
||||
|
||||
/// A shape as the core delivers it, and keeps it.
|
||||
Future<void> _feed(_FFI ffi, String id, {int size = 8, int seed = 0}) {
|
||||
final pixels = _pixels(size, seed);
|
||||
ffi.cursor.core[id] =
|
||||
CursorShape(hotx: 0, hoty: 0, width: size, height: size, colors: pixels);
|
||||
return ffi.ffiModel.handleCursorData(id, 0, 0, size, size, pixels);
|
||||
}
|
||||
|
||||
void _select(_FFI ffi, String id) {
|
||||
final evt = {'id': id};
|
||||
ffi.ffiModel.updateLastCursorId(evt);
|
||||
ffi.ffiModel.handleCursorId(evt);
|
||||
}
|
||||
|
||||
Future<void> _settle() async {
|
||||
for (var i = 0; i < 2; i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
final binding = TestWidgetsFlutterBinding.ensureInitialized();
|
||||
final channel = Platform.isWindows
|
||||
? SystemChannels.mouseCursor
|
||||
: const MethodChannel('flutter_custom_cursor');
|
||||
final registered = <String>[];
|
||||
final deleted = <String>[];
|
||||
late _FFI ffi;
|
||||
setUp(() {
|
||||
registered.clear();
|
||||
deleted.clear();
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel,
|
||||
(call) async {
|
||||
final args = call.arguments as Map<dynamic, dynamic>;
|
||||
if (call.method.startsWith('createCustomCursor')) {
|
||||
registered.add(args['name'] as String);
|
||||
return args['name'];
|
||||
}
|
||||
if (call.method.startsWith('deleteCustomCursor')) {
|
||||
deleted.add(args['name'] as String);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
ffi = _FFI();
|
||||
});
|
||||
tearDown(() {
|
||||
ffi.cursorModel.disposeImages();
|
||||
binding.defaultBinaryMessenger.setMockMethodCallHandler(channel, null);
|
||||
});
|
||||
|
||||
test(
|
||||
'only the shape in use keeps an image, and a shape its native cursor holds '
|
||||
'keeps no pixels', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var round = 0; round < 3; round++) {
|
||||
for (final (id, seed) in [('1', 1), ('2', 2), ('3', 3)]) {
|
||||
await _feed(ffi, id, seed: seed);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
}
|
||||
expect(ffi.cursorModel.shapeIds, ['3']);
|
||||
for (final id in ['1', '2']) {
|
||||
expect(ffi.cursorModel.cachedShape(id)!.hasPixels, isFalse);
|
||||
expect(ffi.cursorModel.cachedShape(id)!.data, isNull);
|
||||
}
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
});
|
||||
|
||||
test('the shape in use keeps its pixels, and a new raster is made at once',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
expect(cursor.cache!.hasPixels, isTrue);
|
||||
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
|
||||
isNot(MouseCursor.defer));
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'nothing had to be decoded');
|
||||
expect(registered.length, 2);
|
||||
expect((cursor.cache!.rasterWidth, cursor.cache!.rasterHeight), (16, 16));
|
||||
|
||||
await _feed(ffi, '2');
|
||||
expect(cursor.cachedShape('1')!.hasPixels, isFalse,
|
||||
reason: 'switched away from, a shape keeps no pixels');
|
||||
_select(ffi, '1');
|
||||
expect(buildCursorOfCache(cursor, 0.5, cursor.cache),
|
||||
isNot(MouseCursor.defer));
|
||||
await _settle();
|
||||
expect(registered.length, 2, reason: 'its native cursor is still there');
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
});
|
||||
|
||||
test('native cursors stay for the session, every raster of every shape',
|
||||
() async {
|
||||
// A delete frees nothing on Windows, so none is deleted before the session ends.
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; i < 100; i++) {
|
||||
await _feed(ffi, '$i', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(deleted, isEmpty);
|
||||
expect(cursor.cachedKeys.length, 100);
|
||||
|
||||
_select(ffi, '0');
|
||||
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)),
|
||||
cursor.nativeKey(cursor.cache!, 1.0));
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'its cursor is still there');
|
||||
expect(registered.length, 100);
|
||||
});
|
||||
|
||||
test(
|
||||
'a raster made before is found again after the shape was switched away from',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, 'A', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
final first = registered.single;
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, 'B');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
final count = registered.length;
|
||||
|
||||
_select(ffi, 'A'); // its pixels went; its cursors at both rasters stay
|
||||
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), first);
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
expect(registered.length, count);
|
||||
});
|
||||
|
||||
test('a new raster of a shape without pixels keeps the cursor shown before',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, '2', size: 32);
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
await _settle();
|
||||
_select(ffi, '1'); // its native cursor held its pixels, so they went
|
||||
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)),
|
||||
cursor.nativeKey(cursor.cache!, 0.5));
|
||||
});
|
||||
|
||||
test('shapes that keep decoding late still get their native cursors',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, 'arrow');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
// A and B arrive, each decoding only after the peer moved on.
|
||||
for (final (id, seed) in [('A', 1), ('B', 2)]) {
|
||||
final pixels = _pixels(8, seed);
|
||||
ffi.cursor.core[id] =
|
||||
CursorShape(hotx: 0, hoty: 0, width: 8, height: 8, colors: pixels);
|
||||
final decoding = ffi.ffiModel.handleCursorData(id, 0, 0, 8, 8, pixels);
|
||||
_select(ffi, 'arrow');
|
||||
await decoding;
|
||||
}
|
||||
// Each fetch answers only after the next switch.
|
||||
ffi.cursor.holdFetches = true;
|
||||
for (var i = 0; i < 6; i++) {
|
||||
_select(ffi, i.isEven ? 'A' : 'B');
|
||||
ffi.cursor.answerFetches();
|
||||
await _settle();
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(registered.where((key) => key.contains('_A_')), isNotEmpty);
|
||||
expect(registered.where((key) => key.contains('_B_')), isNotEmpty);
|
||||
});
|
||||
|
||||
test('a zoom still gets native cursors for shapes that keep decoding late',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
// An animation whose frames have native cursors at 1.0 only.
|
||||
for (final (id, seed) in [('A', 1), ('B', 2)]) {
|
||||
await _feed(ffi, id, size: 32, seed: seed);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
// At 0.5 each frame is fetched again, and each fetch answers after the next switch.
|
||||
ffi.cursor.holdFetches = true;
|
||||
for (var i = 0; i < 6; i++) {
|
||||
_select(ffi, i.isEven ? 'A' : 'B');
|
||||
ffi.cursor.answerFetches();
|
||||
await _settle();
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(
|
||||
registered
|
||||
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
|
||||
isNotEmpty);
|
||||
expect(
|
||||
registered
|
||||
.where((key) => key.contains('_B_') && key.endsWith('_16_16')),
|
||||
isNotEmpty);
|
||||
});
|
||||
|
||||
test(
|
||||
'a raster still missing keeps a late restore, whatever was shown meanwhile',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, 'A', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, 'B');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
|
||||
_select(ffi, 'A');
|
||||
ffi.cursor.holdFetches = true;
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache); // no cursor at 0.5: fetched
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache); // 1.0 has one meanwhile
|
||||
_select(ffi, 'B');
|
||||
ffi.cursor.answerFetches();
|
||||
await _settle();
|
||||
ffi.cursor.fetched.clear();
|
||||
|
||||
_select(ffi, 'A');
|
||||
buildCursorOfCache(cursor, 0.5, cursor.cache);
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty,
|
||||
reason: 'its pixels waited for the cursor at 0.5');
|
||||
expect(
|
||||
registered
|
||||
.where((key) => key.contains('_A_') && key.endsWith('_16_16')),
|
||||
isNotEmpty);
|
||||
});
|
||||
|
||||
test('shapes waiting for a native cursor keep their pixels, within the limit',
|
||||
() async {
|
||||
const max = CursorModel.kRecentShapes;
|
||||
for (var i = 0; i <= max + 1; i++) {
|
||||
await _feed(ffi, '$i');
|
||||
}
|
||||
expect(ffi.cursorModel.cachedShape('0')!.hasPixels, isFalse,
|
||||
reason: 'the one waiting longest is let go');
|
||||
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue);
|
||||
expect(ffi.cursorModel.cachedShape('$max')!.hasPixels, isTrue);
|
||||
});
|
||||
|
||||
test('two animated cursors and the everyday set keep their native cursors',
|
||||
() async {
|
||||
// Each frame is a shape of its own: 18 for the Windows busy cursor, 23 for
|
||||
// KDE Breeze's wait and progress cursors on X11.
|
||||
const frames = 23;
|
||||
const statics = 12;
|
||||
final cursor = ffi.cursorModel;
|
||||
final shapes = [
|
||||
for (var i = 0; i < statics; i++) 's$i',
|
||||
for (var i = 0; i < frames; i++) 'wait$i',
|
||||
for (var i = 0; i < frames; i++) 'progress$i',
|
||||
];
|
||||
for (var i = 0; i < shapes.length; i++) {
|
||||
await _feed(ffi, shapes[i], seed: i);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
ffi.cursor.fetched.clear();
|
||||
for (final id in shapes) {
|
||||
_select(ffi, id);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(ffi.cursor.fetched, isEmpty,
|
||||
reason: 'every shape kept its native cursor');
|
||||
expect(registered.length, shapes.length);
|
||||
expect(deleted, isEmpty);
|
||||
});
|
||||
|
||||
test('a shape painted again is decoded again, the last one shown meanwhile',
|
||||
() async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
_select(ffi, '1');
|
||||
expect(ffi.cursorModel.image?.width, 8, reason: 'shape 2 until 1 is back');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
expect(ffi.cursorModel.image?.width, 16);
|
||||
expect(ffi.cursorModel.shapeIds, ['1']);
|
||||
});
|
||||
|
||||
test('a shape the core gives but that does not decode is asked for once',
|
||||
() async {
|
||||
await _feed(ffi, '1');
|
||||
await _feed(ffi, '2');
|
||||
ffi.cursor.core['1'] = CursorShape(
|
||||
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
|
||||
_select(ffi, '1');
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ffi.cursorModel.image;
|
||||
await _settle();
|
||||
}
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
});
|
||||
|
||||
test('a shape switched away from while it decoded is asked for again',
|
||||
() async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
_select(ffi, '1');
|
||||
ffi.cursorModel.image; // asks the core
|
||||
// The core has answered and the shape is decoding when the peer moves on.
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
_select(ffi, '2');
|
||||
await _settle();
|
||||
expect(ffi.cursorModel.cachedShape('1')!.hasPixels, isTrue,
|
||||
reason:
|
||||
'decoded after the peer moved on, it waits for its native cursor');
|
||||
_select(ffi, '1');
|
||||
ffi.cursorModel.image;
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1', '1']);
|
||||
expect(ffi.cursorModel.image?.width, 16);
|
||||
});
|
||||
|
||||
test('a shape decoded after the session was cleared is not kept', () async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
_select(ffi, '1');
|
||||
ffi.cursorModel.image; // asks the core
|
||||
ffi.cursorModel.clear();
|
||||
await _settle();
|
||||
expect(ffi.cursorModel.shapeIds, isEmpty);
|
||||
expect(ffi.cursorModel.cache, isNull);
|
||||
});
|
||||
|
||||
test('a shape the core does not have is asked for once', () async {
|
||||
await _feed(ffi, '1');
|
||||
await _feed(ffi, '2');
|
||||
ffi.cursor.core.remove('1');
|
||||
_select(ffi, '1');
|
||||
for (var i = 0; i < 5; i++) {
|
||||
ffi.cursorModel.image;
|
||||
await _settle();
|
||||
}
|
||||
expect(ffi.cursor.fetched, ['1']);
|
||||
});
|
||||
|
||||
test('a shape the core lacks is remembered only while it is in use',
|
||||
() async {
|
||||
await _feed(ffi, '1');
|
||||
for (var i = 0; i < 1000; i++) {
|
||||
_select(ffi, 'missing$i');
|
||||
ffi.cursorModel.image;
|
||||
}
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched.length, 1000, reason: 'each is asked for once');
|
||||
_select(ffi, 'missing0');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched.length, 1001,
|
||||
reason: 'nothing is kept for a shape no longer in use');
|
||||
});
|
||||
|
||||
test('a shape the core lacks is asked for again after another was in use',
|
||||
() async {
|
||||
await _feed(ffi, '1');
|
||||
_select(ffi, 'missing0');
|
||||
await _settle();
|
||||
_select(ffi, '1');
|
||||
_select(ffi, 'missing0');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['missing0', 'missing0']);
|
||||
});
|
||||
|
||||
test('a moved tab carries the id in use, and its window asks the core',
|
||||
() async {
|
||||
await _feed(ffi, '1', size: 16);
|
||||
await _feed(ffi, '2');
|
||||
await _feed(ffi, '1', size: 16);
|
||||
final carried = ffi.ffiModel.cachedPeerData.toString();
|
||||
expect(carried, isNot(contains('colors')));
|
||||
expect(CachedPeerData.fromString(carried)!.lastCursorId['id'], '1',
|
||||
reason: 'a shape arriving is the shape in use');
|
||||
|
||||
final moved = _FFI();
|
||||
addTearDown(moved.cursorModel.disposeImages);
|
||||
moved.cursor.core.addAll(ffi.cursor.core);
|
||||
_select(moved, '1');
|
||||
await _settle();
|
||||
expect(moved.cursor.fetched, ['1']);
|
||||
expect(moved.cursorModel.cache?.id, '1');
|
||||
expect(moved.cursorModel.image?.width, 16);
|
||||
});
|
||||
|
||||
test('a shape keeps a native cursor for each raster it was shown at',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1', size: 32);
|
||||
for (final scale in [1.0, 0.5, 1.0, 0.5]) {
|
||||
buildCursorOfCache(cursor, scale, cursor.cache);
|
||||
await _settle();
|
||||
}
|
||||
expect(registered.length, 2, reason: 'a raster returned to is reused');
|
||||
expect(deleted, isEmpty);
|
||||
expect(cursor.cachedKeys, registered.toSet());
|
||||
});
|
||||
|
||||
test('a cleared session forgets the native cursors it deleted', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
cursor.clear();
|
||||
await _settle();
|
||||
expect(deleted, registered);
|
||||
expect(cursor.cachedKeys, isEmpty);
|
||||
});
|
||||
|
||||
test('a tab closing does not delete the cursors of another tab', () async {
|
||||
final other = _FFI();
|
||||
addTearDown(other.cursorModel.disposeImages);
|
||||
while (preDefaultCursor.cache == null) {
|
||||
await _settle();
|
||||
}
|
||||
buildCursorOfCache(ffi.cursorModel, 1.0, preDefaultCursor.cache);
|
||||
buildCursorOfCache(other.cursorModel, 1.0, preDefaultCursor.cache);
|
||||
await _settle();
|
||||
expect(registered.toSet().length, 2, reason: 'each tab has its own');
|
||||
|
||||
ffi.cursorModel.clear();
|
||||
await _settle();
|
||||
expect(other.cursorModel.cachedKeys.single, isNot(isIn(deleted)));
|
||||
});
|
||||
|
||||
test('a shape given as a view into a larger buffer is read from the view',
|
||||
() async {
|
||||
final pixels = _pixels(8, 3);
|
||||
final padded = Uint8List(16 + pixels.length)
|
||||
..setRange(16, 16 + pixels.length, pixels);
|
||||
await ffi.ffiModel
|
||||
.handleCursorData('1', 0, 0, 8, 8, Uint8List.sublistView(padded, 16));
|
||||
final p = ffi.cursorModel.cache!.image.getPixel(0, 0);
|
||||
expect([p.r, p.g, p.b, p.a], [3, 4, 5, 6]);
|
||||
});
|
||||
|
||||
test('a shape still decoding leaves the one shown before in place', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
await _settle();
|
||||
_select(ffi, '2'); // its shape has not decoded yet
|
||||
expect(cursor.cache?.id, '1');
|
||||
expect(_key(buildCursorOfCache(cursor, 1.0, cursor.cache)), shown);
|
||||
expect(cursor.image, isNotNull);
|
||||
await _feed(ffi, '2');
|
||||
expect(cursor.cache?.id, '2');
|
||||
});
|
||||
|
||||
for (final how in ['does not have', 'cannot decode']) {
|
||||
test('a shape the core $how leaves the default cursor, not the one before',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
if (how == 'cannot decode') {
|
||||
ffi.cursor.core['2'] = CursorShape(
|
||||
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
|
||||
}
|
||||
_select(ffi, '2');
|
||||
expect(cursor.cache?.id, '1', reason: 'kept while the shape may come');
|
||||
var notified = 0;
|
||||
cursor.addListener(() => notified++);
|
||||
await _settle();
|
||||
expect(cursor.cache, isNull,
|
||||
reason: 'the desktop shows preDefaultCursor');
|
||||
expect(cursor.image, isNull, reason: 'and so does a painted cursor');
|
||||
expect(notified, greaterThan(0));
|
||||
});
|
||||
}
|
||||
|
||||
test('a shape sent that does not decode leaves the default cursor', () async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
ffi.cursor.core['2'] = CursorShape(
|
||||
hotx: 0, hoty: 0, width: 8, height: 8, colors: Uint8List(3));
|
||||
await ffi.ffiModel.handleCursorData('2', 0, 0, 8, 8, Uint8List(3));
|
||||
expect(cursor.cache, isNull);
|
||||
expect(cursor.image, isNull);
|
||||
_select(ffi, '2');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'it is not asked for either');
|
||||
});
|
||||
|
||||
test('a fetch failing after the session was cleared marks nothing in it',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
ffi.cursor.holdFetches = true;
|
||||
_select(ffi, '1'); // not decoded here yet, so it is asked for
|
||||
cursor.clear();
|
||||
ffi.cursor.failFetches();
|
||||
await _settle();
|
||||
ffi.cursor.holdFetches = false;
|
||||
_select(ffi, '1'); // the same id, now in the new session
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['1', '1']);
|
||||
});
|
||||
|
||||
test('a fetch that throws at once tells the listeners after the build',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
await _feed(ffi, '1');
|
||||
ffi.cursor.throwAtOnce = true;
|
||||
cursor.id = '2';
|
||||
var notified = 0;
|
||||
cursor.addListener(() => notified++);
|
||||
cursor.restorePixels('2');
|
||||
expect(notified, 0, reason: 'a build may be what asked');
|
||||
await _settle();
|
||||
expect(notified, greaterThan(0));
|
||||
expect(cursor.cache, isNull);
|
||||
});
|
||||
|
||||
test('a raster still being made falls back to a shape, not the forbidden one',
|
||||
() async {
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; preForbiddenCursor.cache == null && i < 100; i++) {
|
||||
await _settle();
|
||||
}
|
||||
expect(preForbiddenCursor.cache, isNotNull);
|
||||
await _feed(ffi, '1', size: 32);
|
||||
buildCursorOfCache(cursor, 1.0, cursor.cache);
|
||||
await _settle();
|
||||
await _feed(ffi, '2', size: 32);
|
||||
final shown = _key(buildCursorOfCache(cursor, 1.0, cursor.cache));
|
||||
await _settle();
|
||||
buildCursorOfCache(cursor, 1.0, preForbiddenCursor.cache); // input disabled
|
||||
_select(ffi, '1'); // its native cursor held its pixels, so they went
|
||||
expect(_key(buildCursorOfCache(cursor, 0.5, cursor.cache)), shown);
|
||||
});
|
||||
|
||||
group('a painted cursor', () {
|
||||
void painted(String how) {
|
||||
if (how == 'mobile') {
|
||||
final was = isMobile;
|
||||
isMobile = true;
|
||||
addTearDown(() => isMobile = was);
|
||||
} else {
|
||||
ffi.cursor.showRemoteCursor = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (final how in ['mobile', 'remote cursor shown']) {
|
||||
test('keeps the images of two animations and the everyday set ($how)',
|
||||
() async {
|
||||
painted(how);
|
||||
final cursor = ffi.cursorModel;
|
||||
final shapes = [
|
||||
for (var i = 0; i < 12; i++) 's$i',
|
||||
for (var i = 0; i < 23; i++) 'wait$i',
|
||||
for (var i = 0; i < 23; i++) 'progress$i',
|
||||
];
|
||||
for (var i = 0; i < shapes.length; i++) {
|
||||
await _feed(ffi, shapes[i], seed: i);
|
||||
}
|
||||
for (final id in shapes) {
|
||||
_select(ffi, id);
|
||||
expect(cursor.shapeIds.last, id, reason: 'its image is at hand');
|
||||
}
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty);
|
||||
});
|
||||
}
|
||||
|
||||
test('keeps the images used last, and decodes the others again', () async {
|
||||
painted('mobile');
|
||||
const max = CursorModel.kRecentShapes;
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; i <= max; i++) {
|
||||
await _feed(ffi, '$i');
|
||||
}
|
||||
expect(cursor.shapeIds.length, max);
|
||||
_select(ffi, '$max');
|
||||
_select(ffi, '1');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, isEmpty, reason: 'shape 1 was used lately');
|
||||
_select(ffi, '0');
|
||||
expect(cursor.image, isNotNull, reason: 'shape 1 until 0 is back');
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['0']);
|
||||
expect(cursor.shapeIds.length, max);
|
||||
});
|
||||
|
||||
test('keeps a shape that finished decoding after the peer moved on',
|
||||
() async {
|
||||
painted('mobile');
|
||||
const max = CursorModel.kRecentShapes;
|
||||
final cursor = ffi.cursorModel;
|
||||
for (var i = 0; i <= max; i++) {
|
||||
await _feed(ffi, '$i');
|
||||
}
|
||||
_select(ffi, '0');
|
||||
cursor.image; // let go, so it is asked for
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
_select(ffi, '1');
|
||||
await _settle();
|
||||
_select(ffi, '0');
|
||||
cursor.image;
|
||||
await _settle();
|
||||
expect(ffi.cursor.fetched, ['0'], reason: 'the late one was kept');
|
||||
expect(cursor.shapeIds.last, '0');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
@@ -78,8 +79,6 @@ class _FFI extends Fake implements FFI {
|
||||
final ffiModel = _Peer();
|
||||
@override
|
||||
final inputModel = _Input();
|
||||
@override
|
||||
var id = '';
|
||||
}
|
||||
|
||||
class _Cursor extends CursorModel {
|
||||
@@ -112,7 +111,7 @@ void main() {
|
||||
((1, 64), 0.25, (1, 16)),
|
||||
((8, 8), 0.5, (12, 12)),
|
||||
((4, 64), 1.0, (4, 64)),
|
||||
((1, 512), 10.0, (1, 512)),
|
||||
((1, 512), 10.0, (2, 1024)),
|
||||
]) {
|
||||
test('native cursor size $scenario',
|
||||
() => _checkSize(scenario, registrations));
|
||||
@@ -182,14 +181,15 @@ Future<void> _checkWindowsPeerAlpha(
|
||||
addTearDown(() => _dispose(cursor));
|
||||
addTearDown(cursor.disposeImages);
|
||||
addTearDown(ffi.canvasModel.dispose);
|
||||
await cursor.updateCursorData(
|
||||
'alpha',
|
||||
0,
|
||||
0,
|
||||
sourceSize,
|
||||
sourceSize,
|
||||
Uint8List.fromList(List.generate(sourceSize * sourceSize * channels,
|
||||
(i) => pattern.$1[i % pattern.$1.length])));
|
||||
await cursor.updateCursorData({
|
||||
'id': 'alpha',
|
||||
'hotx': '0',
|
||||
'hoty': '0',
|
||||
'width': '$sourceSize',
|
||||
'height': '$sourceSize',
|
||||
'colors': jsonEncode(List.generate(sourceSize * sourceSize * channels,
|
||||
(i) => pattern.$1[i % pattern.$1.length])),
|
||||
});
|
||||
buildCursorOfCache(cursor, 1.0 / dpr, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final args = registrations.single;
|
||||
@@ -259,7 +259,7 @@ Future<void> _checkRasterTransitions(
|
||||
]) {
|
||||
buildCursorOfCache(cursor, scale, cursor.cache);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final key = cursor.nativeKey(cursor.cache, scale);
|
||||
final key = cursor.cache.updateGetKey(scale);
|
||||
_expectSize(
|
||||
registrations.singleWhere((args) => args['name'] == key), expected);
|
||||
}
|
||||
@@ -268,7 +268,7 @@ Future<void> _checkRasterTransitions(
|
||||
|
||||
Future<void> _checkResizeLimits(
|
||||
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
|
||||
const maxSide = 512;
|
||||
const maxSide = 1024;
|
||||
const sourceLongEdge = 30;
|
||||
const validScale = maxSide / sourceLongEdge;
|
||||
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
|
||||
@@ -361,7 +361,7 @@ Future<void> _checkView(WidgetTester tester, (String, bool) mode,
|
||||
mode.$1 != kRemoteViewStyleOriginal
|
||||
? (sourceSize * (Platform.isWindows ? dpr : 1.0)).ceil()
|
||||
: (size * scale * (Platform.isWindows ? dpr : 1.0)).ceil();
|
||||
final key = cursor.nativeKey(cursor.cache, cursor.cache.scale);
|
||||
final key = cursor.cache.updateGetKey(cursor.cache.scale);
|
||||
_expectSize(registrations.singleWhere((v) => v['name'] == key), (w, w));
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox.shrink());
|
||||
|
||||
@@ -310,9 +310,7 @@ message KeyEvent {
|
||||
}
|
||||
|
||||
message CursorData {
|
||||
// A string in JS: a Windows peer before 1.5.0 sends its cursor handle, sign-extended above
|
||||
// 2^53 when its top bit is set, which a JS number cannot hold.
|
||||
uint64 id = 1 [jstype = JS_STRING];
|
||||
uint64 id = 1;
|
||||
sint32 hotx = 2;
|
||||
sint32 hoty = 3;
|
||||
int32 width = 4;
|
||||
@@ -861,12 +859,6 @@ message Misc {
|
||||
DisplayResolution change_display_resolution = 36;
|
||||
MessageQuery message_query = 37;
|
||||
int32 follow_current_display = 38;
|
||||
// Since 1.5.0: send the CursorData of this id again. No controller sends this yet; it is
|
||||
// here so a controller can one day bound its own shape store and ask for the shape the
|
||||
// peer just selected. The peer answers with what it holds then: a shape its cache dropped
|
||||
// is rebuilt, and held again, the next time it is shown, before any connection names it
|
||||
// by id again, so the shape just selected is always there to give.
|
||||
uint64 request_cursor_data = 39;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1010,7 +1002,7 @@ message Message {
|
||||
AudioFrame audio_frame = 11;
|
||||
CursorData cursor_data = 12;
|
||||
CursorPosition cursor_position = 13;
|
||||
uint64 cursor_id = 14 [jstype = JS_STRING]; // as CursorData.id
|
||||
uint64 cursor_id = 14;
|
||||
KeyEvent key_event = 15;
|
||||
Clipboard clipboard = 16;
|
||||
FileAction file_action = 17;
|
||||
|
||||
@@ -48,6 +48,19 @@ pub struct FileDescription {
|
||||
pub creation_time: SystemTime,
|
||||
pub size: u64,
|
||||
pub perm: u16,
|
||||
/// `file_list_id()` of the list this file came from, sent back in file contents requests
|
||||
#[serde(default)]
|
||||
pub clip_data_id: i32,
|
||||
}
|
||||
|
||||
/// Identifies a file list by its descriptor PDU, which both peers hold, so file contents
|
||||
/// requests can name the list they read from. FNV-1a, same as `wf_cliprdr_file_list_id()`.
|
||||
pub fn file_list_id(file_descriptor_pdu: &[u8]) -> i32 {
|
||||
file_descriptor_pdu
|
||||
.iter()
|
||||
.fold(0x811c_9dc5_u32, |id, byte| {
|
||||
(id ^ *byte as u32).wrapping_mul(0x0100_0193)
|
||||
}) as i32
|
||||
}
|
||||
|
||||
pub(super) fn validate_file_name(name: &str) -> Result<(), CliprdrError> {
|
||||
@@ -69,6 +82,7 @@ impl FileDescription {
|
||||
fn parse_file_descriptor(
|
||||
bytes: &mut Bytes,
|
||||
conn_id: i32,
|
||||
clip_data_id: i32,
|
||||
) -> Result<FileDescription, CliprdrError> {
|
||||
let flags = bytes.get_u32_le();
|
||||
// skip reserved 32 bytes
|
||||
@@ -175,6 +189,7 @@ impl FileDescription {
|
||||
creation_time: last_modified,
|
||||
size,
|
||||
perm,
|
||||
clip_data_id,
|
||||
};
|
||||
|
||||
Ok(desc)
|
||||
@@ -186,6 +201,7 @@ impl FileDescription {
|
||||
file_descriptor_pdu: Vec<u8>,
|
||||
conn_id: i32,
|
||||
) -> Result<Vec<Self>, CliprdrError> {
|
||||
let clip_data_id = file_list_id(&file_descriptor_pdu);
|
||||
let mut data = Bytes::from(file_descriptor_pdu);
|
||||
if data.remaining() < 4 {
|
||||
return Err(CliprdrError::InvalidRequest {
|
||||
@@ -206,7 +222,7 @@ impl FileDescription {
|
||||
|
||||
let mut files = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let desc = Self::parse_file_descriptor(&mut data, conn_id)?;
|
||||
let desc = Self::parse_file_descriptor(&mut data, conn_id, clip_data_id)?;
|
||||
files.push(desc);
|
||||
}
|
||||
|
||||
@@ -282,6 +298,22 @@ mod tests {
|
||||
assert_eq!(files[0].name, PathBuf::from("file.txt"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_list_id_is_fnv1a() {
|
||||
// Reference vectors; the Windows side computes the same id in C.
|
||||
assert_eq!(file_list_id(b"") as u32, 0x811c_9dc5);
|
||||
assert_eq!(file_list_id(b"a") as u32, 0xe40c_292c);
|
||||
assert_eq!(file_list_id(b"foobar") as u32, 0xbf9c_f968);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parsed_files_carry_their_list_id() {
|
||||
let pdu = descriptor_pdu("file.txt");
|
||||
let id = file_list_id(&pdu);
|
||||
let files = FileDescription::parse_file_descriptors(pdu, 0).unwrap();
|
||||
assert_eq!(files[0].clip_data_id, id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_non_terminated_file_name() {
|
||||
let name = "a".repeat(FILE_NAME_CODE_UNITS);
|
||||
|
||||
@@ -549,8 +549,8 @@ impl FuseServer {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested,
|
||||
have_clip_data_id: false,
|
||||
clip_data_id: 0,
|
||||
have_clip_data_id: true,
|
||||
clip_data_id: node.clip_data_id,
|
||||
};
|
||||
|
||||
send_data(node.conn_id, request.clone()).map_err(|e| {
|
||||
@@ -611,6 +611,9 @@ struct FuseNode {
|
||||
/// connection id
|
||||
pub conn_id: i32,
|
||||
|
||||
/// id of the peer's file list this node came from
|
||||
pub clip_data_id: i32,
|
||||
|
||||
/// file index in peer's file list
|
||||
/// NOTE:
|
||||
/// it is NOT the same as inode, this is the index in the file list
|
||||
@@ -634,6 +637,7 @@ impl FuseNode {
|
||||
pub fn from_description(inode: Inode, desc: FileDescription) -> Self {
|
||||
Self {
|
||||
conn_id: desc.conn_id,
|
||||
clip_data_id: desc.clip_data_id,
|
||||
index: inode as usize - 2,
|
||||
name: desc
|
||||
.name
|
||||
@@ -650,6 +654,7 @@ impl FuseNode {
|
||||
pub fn new_root() -> Self {
|
||||
Self {
|
||||
conn_id: 0,
|
||||
clip_data_id: 0,
|
||||
index: 0,
|
||||
name: String::from("/"),
|
||||
parent: None,
|
||||
@@ -898,6 +903,7 @@ mod fuse_test {
|
||||
|
||||
size: 0,
|
||||
perm: 0,
|
||||
clip_data_id: 0,
|
||||
}
|
||||
}
|
||||
fn generate_descriptions(prefix: &str) -> Vec<FileDescription> {
|
||||
|
||||
@@ -617,6 +617,7 @@ impl PasteTaskHandle {
|
||||
};
|
||||
let cb_requested = min(BLOCK_SIZE as u64, file.size - self.progress.offset);
|
||||
let conn_id = file.conn_id;
|
||||
let clip_data_id = file.clip_data_id;
|
||||
|
||||
let (n_position_high, n_position_low) = (
|
||||
(self.progress.offset >> 32) as i32,
|
||||
@@ -629,8 +630,8 @@ impl PasteTaskHandle {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested: cb_requested as _,
|
||||
have_clip_data_id: false,
|
||||
clip_data_id: 0,
|
||||
have_clip_data_id: true,
|
||||
clip_data_id,
|
||||
};
|
||||
allow_err!(send_data(conn_id, request));
|
||||
self.progress.last_sent_time = Instant::now();
|
||||
@@ -703,6 +704,7 @@ mod tests {
|
||||
creation_time: SystemTime::UNIX_EPOCH,
|
||||
size,
|
||||
perm: 0,
|
||||
clip_data_id: 0,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,11 +1,27 @@
|
||||
use super::local_file::LocalFile;
|
||||
use crate::{platform::unix::local_file::construct_file_list, ClipboardFile, CliprdrError};
|
||||
use crate::{
|
||||
platform::unix::{
|
||||
filetype::file_list_id,
|
||||
local_file::{construct_file_list, LocalFile},
|
||||
},
|
||||
ClipboardFile, CliprdrError,
|
||||
};
|
||||
use hbb_common::{
|
||||
bytes::{BufMut, BytesMut},
|
||||
log,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use std::{path::PathBuf, sync::Arc, time::SystemTime, usize};
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
path::PathBuf,
|
||||
sync::{atomic::Ordering, Arc},
|
||||
time::SystemTime,
|
||||
usize,
|
||||
};
|
||||
|
||||
// Our clients request at most this much per range: macOS 4 MiB, FUSE less, and Windows
|
||||
// splits larger reads (WF_CLIPRDR_MAX_RANGE_READ). A larger read is refused, not shortened:
|
||||
// a short response reads as end of file to IStream callers on Windows.
|
||||
const MAX_RANGE_READ: u64 = 16 * 1024 * 1024;
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
// local files are cached, this value should not be changed when copying files
|
||||
@@ -13,8 +29,18 @@ lazy_static::lazy_static! {
|
||||
// We need to keep the file list in the same order as the remote side.
|
||||
// We may add a `FileId` field to `CliprdrFileContentsRequest` in the future.
|
||||
static ref CLIP_FILES: Arc<Mutex<ClipFiles>> = Default::default();
|
||||
// Lists replaced by a newer copy after a peer was sent them, oldest first. The peer's
|
||||
// streams keep reading the list they came from. Lock after `CLIP_FILES`.
|
||||
static ref RETIRED_CLIP_FILES: Mutex<VecDeque<ClipFiles>> = Default::default();
|
||||
}
|
||||
|
||||
const MAX_RETIRED_CLIP_FILES: usize = 4;
|
||||
|
||||
// The first descriptor's `clsid`, inside the 32 reserved bytes every peer skips. A random
|
||||
// nonce there makes each copy's list id distinct, even when two copies have identical
|
||||
// names, sizes and times (the same file in two folders).
|
||||
const LIST_NONCE: std::ops::Range<usize> = 8..24;
|
||||
|
||||
#[derive(Debug)]
|
||||
enum FileContentsRequest {
|
||||
Size {
|
||||
@@ -62,6 +88,10 @@ struct ClipFiles {
|
||||
file_list: Vec<LocalFile>,
|
||||
first_file_index: usize,
|
||||
files_pdu: Vec<u8>,
|
||||
// `file_list_id(files_pdu)`, which peers send back as `clip_data_id`.
|
||||
id: i32,
|
||||
// Connections that were sent `files_pdu`.
|
||||
served_to: Vec<i32>,
|
||||
}
|
||||
|
||||
impl ClipFiles {
|
||||
@@ -71,6 +101,8 @@ impl ClipFiles {
|
||||
self.file_list.clear();
|
||||
self.first_file_index = usize::MAX;
|
||||
self.files_pdu.clear();
|
||||
self.id = 0;
|
||||
self.served_to.clear();
|
||||
}
|
||||
|
||||
fn sync_files(
|
||||
@@ -100,9 +132,54 @@ impl ClipFiles {
|
||||
data.put(file.as_bin()?.as_slice());
|
||||
}
|
||||
self.files_pdu = data.to_vec();
|
||||
if let Some(nonce) = self.files_pdu.get_mut(LIST_NONCE) {
|
||||
nonce.copy_from_slice(&rand::random::<[u8; 16]>());
|
||||
}
|
||||
self.id = file_list_id(&self.files_pdu);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Close files that are not being read, such as the preloaded next file; `read_exact_at`
|
||||
// reopens them on the next read. A file part-way through keeps its handle and offset, so
|
||||
// its remaining bytes come from the same file even if its path is replaced meanwhile.
|
||||
fn release_handles(&mut self) {
|
||||
for file in self.file_list.iter_mut() {
|
||||
if file.offset.load(Ordering::Relaxed) == 0 {
|
||||
file.handle = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A retired list's file is reopened by path once its handle was closed, and the path may now
|
||||
// name a replacement. Check size and modified time on the handle the read will use, and refuse
|
||||
// a file that no longer matches the list.
|
||||
fn check_retired_file(&mut self, request: &FileContentsRequest) -> Result<(), CliprdrError> {
|
||||
let FileContentsRequest::Range { file_idx, .. } = request else {
|
||||
return Ok(());
|
||||
};
|
||||
let Some(file) = self.file_list.get_mut(*file_idx) else {
|
||||
return Ok(());
|
||||
};
|
||||
if file.is_dir {
|
||||
return Ok(());
|
||||
}
|
||||
file.load_handle()?;
|
||||
let unchanged = file
|
||||
.handle
|
||||
.as_ref()
|
||||
.and_then(|handle| handle.get_ref().metadata().ok())
|
||||
.map_or(false, |md| {
|
||||
md.len() == file.size && md.modified().ok() == Some(file.last_write_time)
|
||||
});
|
||||
if unchanged {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(CliprdrError::InvalidRequest {
|
||||
description: format!("file {} changed since its list was sent", file.name),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn get_files_for_audit(&self, request: &FileContentsRequest) -> Option<ClipboardFile> {
|
||||
if let FileContentsRequest::Range {
|
||||
file_idx, offset, ..
|
||||
@@ -213,12 +290,21 @@ impl ClipFiles {
|
||||
),
|
||||
});
|
||||
}
|
||||
let read_size = if offset + length > file.size {
|
||||
let read_size = if length > file.size - offset {
|
||||
file.size - offset
|
||||
} else {
|
||||
length
|
||||
};
|
||||
|
||||
if read_size > MAX_RANGE_READ {
|
||||
return Err(CliprdrError::InvalidRequest {
|
||||
description: format!(
|
||||
"file contents request of {} bytes exceeds the {} byte limit, conn: {}",
|
||||
read_size, MAX_RANGE_READ, conn_id
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
let mut buf = vec![0u8; read_size as usize];
|
||||
|
||||
file.read_exact_at(&mut buf, offset)?;
|
||||
@@ -249,6 +335,44 @@ impl ClipFiles {
|
||||
#[inline]
|
||||
pub fn clear_files() {
|
||||
CLIP_FILES.lock().clear();
|
||||
RETIRED_CLIP_FILES.lock().clear();
|
||||
}
|
||||
|
||||
// The list a request reads from: the one its `clip_data_id` names, else the one last sent to
|
||||
// the connection. A named list that is gone yields `None`. A peer that sends no id and was
|
||||
// never sent a list reads the current one, as before.
|
||||
fn select_clip_files<'a>(
|
||||
current: &'a mut ClipFiles,
|
||||
retired: &'a mut VecDeque<ClipFiles>,
|
||||
conn_id: i32,
|
||||
clip_data_id: Option<i32>,
|
||||
) -> Option<&'a mut ClipFiles> {
|
||||
match clip_data_id {
|
||||
Some(id) if current.id == id => Some(current),
|
||||
Some(id) => retired
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|files| files.id == id && files.served_to.contains(&conn_id)),
|
||||
None if current.served_to.contains(&conn_id) => Some(current),
|
||||
None => retired
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|files| files.served_to.contains(&conn_id))
|
||||
.or(Some(current)),
|
||||
}
|
||||
}
|
||||
|
||||
// Keep a list a peer was sent, so its streams do not read the new copy at the same indexes.
|
||||
fn retire_if_served(mut replaced: ClipFiles) {
|
||||
if replaced.served_to.is_empty() {
|
||||
return;
|
||||
}
|
||||
replaced.release_handles();
|
||||
let mut retired = RETIRED_CLIP_FILES.lock();
|
||||
if retired.len() == MAX_RETIRED_CLIP_FILES {
|
||||
retired.pop_front();
|
||||
}
|
||||
retired.push_back(replaced);
|
||||
}
|
||||
|
||||
pub fn read_file_contents(
|
||||
@@ -259,6 +383,7 @@ pub fn read_file_contents(
|
||||
n_position_low: i32,
|
||||
n_position_high: i32,
|
||||
cb_requested: i32,
|
||||
clip_data_id: Option<i32>,
|
||||
) -> Vec<Result<ClipboardFile, CliprdrError>> {
|
||||
let fcr = if dw_flags == 0x1 {
|
||||
FileContentsRequest::Size {
|
||||
@@ -266,8 +391,11 @@ pub fn read_file_contents(
|
||||
file_idx: list_index as usize,
|
||||
}
|
||||
} else if dw_flags == 0x2 {
|
||||
let offset = (n_position_high as u64) << 32 | n_position_low as u64;
|
||||
let length = cb_requested as u64;
|
||||
// nPositionLow and cbRequested are UINT32s carried in i32 fields. Sign-extending
|
||||
// them rejects offsets whose low word is >= 2 GiB and turns a negative length
|
||||
// into a near-u64::MAX read.
|
||||
let offset = (n_position_high as u64) << 32 | n_position_low as u32 as u64;
|
||||
let length = cb_requested as u32 as u64;
|
||||
|
||||
FileContentsRequest::Range {
|
||||
stream_id,
|
||||
@@ -281,7 +409,23 @@ pub fn read_file_contents(
|
||||
})];
|
||||
};
|
||||
|
||||
let mut clip_files = CLIP_FILES.lock();
|
||||
let mut current = CLIP_FILES.lock();
|
||||
let mut retired = RETIRED_CLIP_FILES.lock();
|
||||
let current_ptr: *const ClipFiles = &*current;
|
||||
let Some(clip_files) = select_clip_files(&mut current, &mut retired, conn_id, clip_data_id)
|
||||
else {
|
||||
return vec![Err(CliprdrError::InvalidRequest {
|
||||
description: format!(
|
||||
"file list {:?} is not available to conn: {}",
|
||||
clip_data_id, conn_id
|
||||
),
|
||||
})];
|
||||
};
|
||||
if !std::ptr::eq(&*clip_files, current_ptr) {
|
||||
if let Err(e) = clip_files.check_retired_file(&fcr) {
|
||||
return vec![Err(e)];
|
||||
}
|
||||
}
|
||||
let mut res = vec![];
|
||||
if let Some(files_res) = clip_files.get_files_for_audit(&fcr) {
|
||||
res.push(Ok(files_res));
|
||||
@@ -301,12 +445,21 @@ pub fn sync_files(files: &[String]) -> Result<(), CliprdrError> {
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
files_lock.sync_files(files, current)?;
|
||||
files_lock.build_file_list_pdu()
|
||||
// Build aside, so a failure leaves the current list in place.
|
||||
let mut next = ClipFiles::default();
|
||||
next.sync_files(files, current)?;
|
||||
next.build_file_list_pdu()?;
|
||||
let replaced = std::mem::replace(&mut *files_lock, next);
|
||||
retire_if_served(replaced);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn get_file_list_pdu() -> Vec<u8> {
|
||||
CLIP_FILES.lock().files_pdu.clone()
|
||||
pub fn get_file_list_pdu(conn_id: i32) -> Vec<u8> {
|
||||
let mut clip_files = CLIP_FILES.lock();
|
||||
if !clip_files.files_pdu.is_empty() && !clip_files.served_to.contains(&conn_id) {
|
||||
clip_files.served_to.push(conn_id);
|
||||
}
|
||||
clip_files.files_pdu.clone()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -343,6 +496,30 @@ mod sig_test {
|
||||
p.to_string_lossy().to_string()
|
||||
}
|
||||
|
||||
// Tests that drive the global CLIP_FILES must not interleave.
|
||||
static CLIP_FILES_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn lock_clip_files() -> std::sync::MutexGuard<'static, ()> {
|
||||
CLIP_FILES_TEST_LOCK
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
// Sparse, so a multi-GiB file costs no disk space.
|
||||
fn write_at(path: &PathBuf, offset: u64, data: &[u8]) {
|
||||
use std::io::{Seek, SeekFrom, Write};
|
||||
let mut f = fs::File::create(path).unwrap();
|
||||
f.seek(SeekFrom::Start(offset)).unwrap();
|
||||
f.write_all(data).unwrap();
|
||||
}
|
||||
|
||||
fn range_data(res: Vec<Result<ClipboardFile, CliprdrError>>) -> Vec<u8> {
|
||||
match res.into_iter().last() {
|
||||
Some(Ok(ClipboardFile::FileContentsResponse { requested_data, .. })) => requested_data,
|
||||
other => panic!("unexpected response: {:?}", other),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_missing_path_is_default() {
|
||||
let tmp = TmpDir::new("missing");
|
||||
@@ -393,7 +570,8 @@ mod sig_test {
|
||||
let files = vec![path_str(&file)];
|
||||
|
||||
// Drive the public, guarded `sync_files` over the global CLIP_FILES;
|
||||
// reset first (this is the only test that touches the global).
|
||||
// reset first.
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
|
||||
sync_files(&files).unwrap();
|
||||
@@ -415,4 +593,329 @@ mod sig_test {
|
||||
|
||||
clear_files(); // leave the global clean for other tests
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_huge_length_is_clamped() {
|
||||
let tmp = TmpDir::new("range");
|
||||
let file = tmp.join("data.bin");
|
||||
fs::write(&file, b"0123456789").unwrap();
|
||||
let files = vec![path_str(&file)];
|
||||
|
||||
let mut clip = ClipFiles::default();
|
||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
||||
let file_idx = clip.first_file_index;
|
||||
|
||||
// offset + length used to wrap to 0, skip the clamp and ask for a u64::MAX buffer.
|
||||
let resp = clip
|
||||
.serve_file_contents(
|
||||
0,
|
||||
FileContentsRequest::Range {
|
||||
stream_id: 0,
|
||||
file_idx,
|
||||
offset: 1,
|
||||
length: u64::MAX,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
match resp {
|
||||
ClipboardFile::FileContentsResponse { requested_data, .. } => {
|
||||
assert_eq!(requested_data, b"123456789");
|
||||
}
|
||||
_ => panic!("unexpected response"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_decodes_wire_fields_as_u32() {
|
||||
let tmp = TmpDir::new("decode");
|
||||
let small = tmp.join("small.bin");
|
||||
fs::write(&small, b"0123456789").unwrap();
|
||||
let large = tmp.join("large.bin");
|
||||
write_at(&large, 0x8000_0000, b"tail");
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&small), path_str(&large)]).unwrap();
|
||||
let small_idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
let large_idx = small_idx + 1;
|
||||
|
||||
// A negative cbRequested is a UINT32 length, clamped to the rest of the file.
|
||||
let res = read_file_contents(0, 0, small_idx, 0x2, 1, 0, -1, None);
|
||||
assert_eq!(range_data(res), b"123456789");
|
||||
|
||||
// An nPositionLow with bit 31 set is an offset past 2 GiB, not a huge one.
|
||||
let res = read_file_contents(0, 0, large_idx, 0x2, 0x8000_0000u32 as i32, 0, 4, None);
|
||||
assert_eq!(range_data(res), b"tail");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn range_request_over_limit_is_rejected() {
|
||||
let tmp = TmpDir::new("limit");
|
||||
let file = tmp.join("big.bin");
|
||||
let size = MAX_RANGE_READ + 1;
|
||||
write_at(&file, size - 1, b"x");
|
||||
let files = vec![path_str(&file)];
|
||||
|
||||
let mut clip = ClipFiles::default();
|
||||
clip.sync_files(&files, fingerprint(&files)).unwrap();
|
||||
let file_idx = clip.first_file_index;
|
||||
|
||||
let res = clip.serve_file_contents(
|
||||
0,
|
||||
FileContentsRequest::Range {
|
||||
stream_id: 0,
|
||||
file_idx,
|
||||
offset: 0,
|
||||
length: u32::MAX as u64,
|
||||
},
|
||||
);
|
||||
assert!(matches!(res, Err(CliprdrError::InvalidRequest { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn host_copy_during_transfer_keeps_serving_the_sent_list() {
|
||||
let tmp = TmpDir::new("recopy_in_flight");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
get_file_list_pdu(1);
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
let read = |offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, None));
|
||||
assert_eq!(read(0), b"AAAA");
|
||||
|
||||
// Copying another file on this side must not redirect the peer's stream.
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
assert_eq!(read(4), b"AAAA");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stream_keeps_its_list_after_a_second_paste() {
|
||||
let tmp = TmpDir::new("repaste_in_flight");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
|
||||
// The peer copies the second file on this side and pastes it while the first
|
||||
// transfer is still reading.
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
let second_id = file_list_id(&get_file_list_pdu(1));
|
||||
assert_ne!(first_id, second_id);
|
||||
|
||||
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
|
||||
assert_eq!(read(first_id), b"AAAA");
|
||||
assert_eq!(read(second_id), b"BBBB");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn named_list_must_have_been_sent_to_the_conn() {
|
||||
let tmp = TmpDir::new("foreign_list");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
|
||||
let refused = |conn_id, id| {
|
||||
matches!(
|
||||
read_file_contents(conn_id, 7, idx, 0x2, 0, 0, 4, Some(id)).last(),
|
||||
Some(Err(CliprdrError::InvalidRequest { .. }))
|
||||
)
|
||||
};
|
||||
// Retired list, asked for by a connection it was never sent to.
|
||||
assert!(refused(2, first_id));
|
||||
// A list id this side never sent.
|
||||
assert!(refused(1, first_id ^ 1));
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failed_recopy_keeps_the_current_list() {
|
||||
let tmp = TmpDir::new("failed_recopy");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let missing = tmp.join("missing.bin");
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let pdu = get_file_list_pdu(1);
|
||||
|
||||
assert!(sync_files(&[path_str(&missing)]).is_err());
|
||||
assert_eq!(get_file_list_pdu(1), pdu);
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
fn file_index(path: &PathBuf) -> i32 {
|
||||
let files = CLIP_FILES.lock();
|
||||
files
|
||||
.file_list
|
||||
.iter()
|
||||
.position(|f| &f.path == path)
|
||||
.unwrap() as i32
|
||||
}
|
||||
|
||||
// Replaces `path` the way editors save: write aside, then rename over it.
|
||||
fn replace_atomically(path: &PathBuf, data: &[u8]) {
|
||||
let aside = path.with_extension("new");
|
||||
fs::write(&aside, data).unwrap();
|
||||
fs::rename(&aside, path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retired_list_closes_only_files_not_being_read() {
|
||||
let tmp = TmpDir::new("retired_handles");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAABBBB").unwrap();
|
||||
let next = tmp.join("next.bin");
|
||||
fs::write(&next, b"CCCCDDDD").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&next)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, next_idx) = (file_index(&first), file_index(&next));
|
||||
let read =
|
||||
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
|
||||
// Leaves `first` open at offset 4, and preloads `next`.
|
||||
assert_eq!(read(first_idx, 0), b"AAAA");
|
||||
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
{
|
||||
let retired = RETIRED_CLIP_FILES.lock();
|
||||
let open = |idx: i32| retired[0].file_list[idx as usize].handle.is_some();
|
||||
assert!(open(first_idx));
|
||||
assert!(!open(next_idx));
|
||||
}
|
||||
assert_eq!(read(first_idx, 4), b"BBBB");
|
||||
assert_eq!(read(next_idx, 0), b"CCCC");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn files_being_read_keep_their_content_when_their_paths_are_replaced() {
|
||||
let tmp = TmpDir::new("replaced_paths");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"1111aaaa").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"2222bbbb").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
|
||||
let read =
|
||||
|idx, offset| range_data(read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id)));
|
||||
// Two files part-way through at once.
|
||||
assert_eq!(read(first_idx, 0), b"1111");
|
||||
assert_eq!(read(second_idx, 0), b"2222");
|
||||
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
replace_atomically(&first, b"3333cccc");
|
||||
replace_atomically(&second, b"4444dddd");
|
||||
|
||||
assert_eq!(read(first_idx, 4), b"aaaa");
|
||||
assert_eq!(read(second_idx, 4), b"bbbb");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_file_metadata_in_another_folder_is_another_list() {
|
||||
let tmp = TmpDir::new("same_metadata");
|
||||
let (dir_a, dir_b) = (tmp.join("a"), tmp.join("b"));
|
||||
fs::create_dir_all(&dir_a).unwrap();
|
||||
fs::create_dir_all(&dir_b).unwrap();
|
||||
let (first, second) = (dir_a.join("report.bin"), dir_b.join("report.bin"));
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
// Same name, size and mtime: the descriptors differ only by the nonce.
|
||||
let mtime = SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_700_000_000);
|
||||
for path in [&first, &second] {
|
||||
fs::File::options()
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap()
|
||||
.set_modified(mtime)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first)]).unwrap();
|
||||
let first_id = file_list_id(&get_file_list_pdu(1));
|
||||
let idx = CLIP_FILES.lock().first_file_index as i32;
|
||||
sync_files(&[path_str(&second)]).unwrap();
|
||||
let second_id = file_list_id(&get_file_list_pdu(1));
|
||||
assert_ne!(first_id, second_id);
|
||||
|
||||
let read = |id| range_data(read_file_contents(1, 7, idx, 0x2, 4, 0, 4, Some(id)));
|
||||
assert_eq!(read(first_id), b"AAAA");
|
||||
assert_eq!(read(second_id), b"BBBB");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retired_list_refuses_a_file_replaced_before_its_read() {
|
||||
let tmp = TmpDir::new("replaced_unread");
|
||||
let first = tmp.join("first.bin");
|
||||
fs::write(&first, b"AAAAAAAA").unwrap();
|
||||
let second = tmp.join("second.bin");
|
||||
fs::write(&second, b"BBBBBBBB").unwrap();
|
||||
let other = tmp.join("other.bin");
|
||||
fs::write(&other, b"EEEEEEEE").unwrap();
|
||||
|
||||
let _guard = lock_clip_files();
|
||||
clear_files();
|
||||
sync_files(&[path_str(&first), path_str(&second)]).unwrap();
|
||||
let id = file_list_id(&get_file_list_pdu(1));
|
||||
let (first_idx, second_idx) = (file_index(&first), file_index(&second));
|
||||
let read = |idx, offset| read_file_contents(1, 7, idx, 0x2, offset, 0, 4, Some(id));
|
||||
assert_eq!(range_data(read(first_idx, 0)), b"AAAA");
|
||||
|
||||
// Retiring closes `second`, which has not been read yet; it is then replaced.
|
||||
sync_files(&[path_str(&other)]).unwrap();
|
||||
replace_atomically(&second, b"CCCCCCCCCC");
|
||||
|
||||
assert!(matches!(
|
||||
read(second_idx, 0).last(),
|
||||
Some(Err(CliprdrError::InvalidRequest { .. }))
|
||||
));
|
||||
// The file part-way through is unaffected.
|
||||
assert_eq!(range_data(read(first_idx, 4)), b"AAAA");
|
||||
|
||||
clear_files();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,6 +54,12 @@
|
||||
/* File clipboard redirection always advertises the descriptor and contents formats. */
|
||||
#define WF_CLIPRDR_FILE_FORMAT_COUNT 2u
|
||||
#define WF_CLIPRDR_COM_LPT_PREFIX_LENGTH 3u
|
||||
/* File lists kept after they were sent, so a transfer still in flight keeps reading its own
|
||||
* files after a later copy or paste replaces them. */
|
||||
#define WF_CLIPRDR_SERVED_FILE_LISTS 4u
|
||||
/* Largest range served in one request, here and by the unix file server (MAX_RANGE_READ in
|
||||
* serv_files.rs). Larger IStream reads are split into requests of this size. */
|
||||
#define WF_CLIPRDR_MAX_RANGE_READ (16u * 1024u * 1024u)
|
||||
static const WCHAR WF_CLIPRDR_SUPERSCRIPT_DIGITS[] = L"\x00B9\x00B2\x00B3";
|
||||
static const WCHAR WF_CLIPRDR_INVALID_FILE_NAME_CHARS[] = L"<>:\"|?*";
|
||||
|
||||
@@ -213,6 +219,21 @@ static BOOL wf_cliprdr_bounded_strlen(const char *value, size_t max_len, size_t
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/* Identifies a file list by its FILEGROUPDESCRIPTORW bytes, which both peers hold, and is
|
||||
* carried as FileContentsRequest.clipDataId. FNV-1a, same as `file_list_id()` on unix. */
|
||||
static UINT32 wf_cliprdr_file_list_id(const BYTE *data, SIZE_T size)
|
||||
{
|
||||
UINT32 id = 2166136261u;
|
||||
SIZE_T i;
|
||||
|
||||
for (i = 0; i < size; i++)
|
||||
{
|
||||
id ^= data[i];
|
||||
id *= 16777619u;
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clipboard Formats
|
||||
*/
|
||||
@@ -358,6 +379,7 @@ struct _CliprdrStream
|
||||
void *m_pData;
|
||||
UINT32 m_connID;
|
||||
UINT32 m_streamId; // unique CLIPRDR streamId; avoids leaking a heap pointer
|
||||
UINT32 m_clipDataId; // id of the file list this stream was created from
|
||||
};
|
||||
typedef struct _CliprdrStream CliprdrStream;
|
||||
|
||||
@@ -377,6 +399,21 @@ struct _CliprdrDataObject
|
||||
};
|
||||
typedef struct _CliprdrDataObject CliprdrDataObject;
|
||||
|
||||
struct wf_served_file_list
|
||||
{
|
||||
UINT32 id;
|
||||
UINT32 *connIDs; // connections the list was sent to
|
||||
size_t nConnIDs;
|
||||
UINT64 last_served; // served_file_list_seq when last sent; the lowest is evicted first
|
||||
size_t nFiles;
|
||||
size_t first_file_index;
|
||||
WCHAR **file_names;
|
||||
UINT64 *file_sizes;
|
||||
BYTE *descriptors; // the FILEGROUPDESCRIPTORW sent, nonce included
|
||||
SIZE_T descriptorsSize;
|
||||
};
|
||||
typedef struct wf_served_file_list wfServedFileList;
|
||||
|
||||
struct wf_clipboard
|
||||
{
|
||||
// wfContext* wfc;
|
||||
@@ -424,6 +461,10 @@ struct wf_clipboard
|
||||
WCHAR **file_names;
|
||||
size_t first_file_index;
|
||||
FILEDESCRIPTORW **fileDescriptor;
|
||||
DWORD file_list_seq; // clipboard sequence number the file list was read at
|
||||
UINT32 file_list_id; // wf_cliprdr_file_list_id() of the file list, 0 while none is valid
|
||||
wfServedFileList served_file_lists[WF_CLIPRDR_SERVED_FILE_LISTS];
|
||||
UINT64 served_file_list_seq;
|
||||
|
||||
BOOL legacyApi;
|
||||
HMODULE hUser32;
|
||||
@@ -451,8 +492,8 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
|
||||
static UINT cliprdr_send_lock(wfClipboard *clipboard);
|
||||
static UINT cliprdr_send_unlock(wfClipboard *clipboard);
|
||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
|
||||
ULONG index, UINT32 flag, DWORD positionhigh,
|
||||
DWORD positionlow, ULONG request);
|
||||
UINT32 clipDataId, ULONG index, UINT32 flag,
|
||||
DWORD positionhigh, DWORD positionlow, ULONG request);
|
||||
|
||||
static BOOL is_file_descriptor_from_remote();
|
||||
static BOOL is_set_by_instance(wfClipboard *clipboard);
|
||||
@@ -464,6 +505,7 @@ static HRESULT CliprdrEnumFORMATETC_New(ULONG nFormats, FORMATETC *pFormatEtc,
|
||||
static void CliprdrEnumFORMATETC_Delete(CliprdrEnumFORMATETC *instance);
|
||||
|
||||
static void CliprdrStream_Delete(CliprdrStream *instance);
|
||||
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead);
|
||||
|
||||
static BOOL try_open_clipboard(HWND hwnd)
|
||||
{
|
||||
@@ -550,7 +592,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
|
||||
if (instance->m_lOffset.QuadPart >= instance->m_lSize.QuadPart)
|
||||
return S_FALSE;
|
||||
|
||||
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId, instance->m_lIndex,
|
||||
if (cb > WF_CLIPRDR_MAX_RANGE_READ)
|
||||
return wf_cliprdr_stream_read_split(This, (BYTE *)pv, cb, pcbRead);
|
||||
|
||||
ret = cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
|
||||
instance->m_clipDataId, instance->m_lIndex,
|
||||
FILECONTENTS_RANGE, instance->m_lOffset.HighPart,
|
||||
instance->m_lOffset.LowPart, cb);
|
||||
|
||||
@@ -591,6 +637,26 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Read(IStream *This, void *pv, ULO
|
||||
return S_OK;
|
||||
}
|
||||
|
||||
static HRESULT wf_cliprdr_stream_read_split(IStream *This, BYTE *pv, ULONG cb, ULONG *pcbRead)
|
||||
{
|
||||
HRESULT hr = S_OK;
|
||||
ULONG total = 0;
|
||||
ULONG chunk;
|
||||
ULONG n;
|
||||
|
||||
while (total < cb && hr == S_OK)
|
||||
{
|
||||
chunk = cb - total < WF_CLIPRDR_MAX_RANGE_READ ? cb - total : WF_CLIPRDR_MAX_RANGE_READ;
|
||||
n = 0;
|
||||
hr = CliprdrStream_Read(This, pv + total, chunk, &n);
|
||||
total += n;
|
||||
}
|
||||
*pcbRead = total;
|
||||
if (FAILED(hr))
|
||||
return hr;
|
||||
return total < cb ? S_FALSE : S_OK;
|
||||
}
|
||||
|
||||
static HRESULT STDMETHODCALLTYPE CliprdrStream_Write(IStream *This, const void *pv, ULONG cb,
|
||||
ULONG *pcbWritten)
|
||||
{
|
||||
@@ -736,7 +802,8 @@ static HRESULT STDMETHODCALLTYPE CliprdrStream_Clone(IStream *This, IStream **pp
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
|
||||
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc)
|
||||
static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData, const FILEDESCRIPTORW *dsc,
|
||||
UINT32 clipDataId)
|
||||
{
|
||||
IStream *iStream = NULL;
|
||||
BOOL success = FALSE;
|
||||
@@ -779,6 +846,7 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
|
||||
instance->m_lOffset.QuadPart = 0;
|
||||
instance->m_connID = connID;
|
||||
instance->m_streamId = (UINT32)InterlockedIncrement(&clipboard->req_f_stream_id_seq);
|
||||
instance->m_clipDataId = clipDataId;
|
||||
|
||||
if (instance->m_Dsc.dwFlags & FD_ATTRIBUTES)
|
||||
{
|
||||
@@ -790,8 +858,8 @@ static CliprdrStream *CliprdrStream_New(UINT32 connID, ULONG index, void *pData,
|
||||
{
|
||||
/* get content size of this stream */
|
||||
if (cliprdr_send_request_filecontents(clipboard, instance->m_connID, instance->m_streamId,
|
||||
instance->m_lIndex, FILECONTENTS_SIZE, 0, 0,
|
||||
8) == CHANNEL_RC_OK)
|
||||
instance->m_clipDataId, instance->m_lIndex,
|
||||
FILECONTENTS_SIZE, 0, 0, 8) == CHANNEL_RC_OK)
|
||||
{
|
||||
success = TRUE;
|
||||
}
|
||||
@@ -1007,6 +1075,7 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
|
||||
IStream **streams = NULL;
|
||||
UINT stream_count = 0;
|
||||
SIZE_T hmem_size;
|
||||
UINT32 clipDataId;
|
||||
// DWORD remote_format_id = get_remote_format_id(clipboard, instance->m_pFormatEtc[idx].cfFormat);
|
||||
// FIXME: origin code may be failed here???
|
||||
if (cliprdr_send_data_request(instance->m_connID, clipboard, instance->m_pFormatEtc[idx].cfFormat) != 0)
|
||||
@@ -1053,10 +1122,11 @@ static HRESULT STDMETHODCALLTYPE CliprdrDataObject_GetData(IDataObject *This, FO
|
||||
return wf_cliprdr_fail_locked_file_descriptor_data(
|
||||
clipboard, pMedium, instance, NULL, 0, E_OUTOFMEMORY);
|
||||
|
||||
clipDataId = wf_cliprdr_file_list_id((const BYTE *)dsc, hmem_size);
|
||||
for (i = 0; i < stream_count; i++)
|
||||
{
|
||||
streams[i] =
|
||||
(IStream *)CliprdrStream_New(instance->m_connID, i, clipboard, &dsc->fgd[i]);
|
||||
streams[i] = (IStream *)CliprdrStream_New(instance->m_connID, i, clipboard,
|
||||
&dsc->fgd[i], clipDataId);
|
||||
if (!streams[i])
|
||||
{
|
||||
return wf_cliprdr_fail_locked_file_descriptor_data(
|
||||
@@ -1996,9 +2066,9 @@ static UINT cliprdr_send_data_request(UINT32 connID, wfClipboard *clipboard, UIN
|
||||
return wait_response_event(connID, clipboard, clipboard->formatDataRespEvent, &clipboard->formatDataRespReceived, &clipboard->hmem);
|
||||
}
|
||||
|
||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId, ULONG index,
|
||||
UINT32 flag, DWORD positionhigh, DWORD positionlow,
|
||||
ULONG nreq)
|
||||
static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 connID, UINT32 streamId,
|
||||
UINT32 clipDataId, ULONG index, UINT32 flag,
|
||||
DWORD positionhigh, DWORD positionlow, ULONG nreq)
|
||||
{
|
||||
UINT rc;
|
||||
CLIPRDR_FILE_CONTENTS_REQUEST fileContentsRequest = { 0 };
|
||||
@@ -2023,7 +2093,8 @@ static UINT cliprdr_send_request_filecontents(wfClipboard *clipboard, UINT32 con
|
||||
fileContentsRequest.nPositionLow = positionlow;
|
||||
fileContentsRequest.nPositionHigh = positionhigh;
|
||||
fileContentsRequest.cbRequested = nreq;
|
||||
fileContentsRequest.clipDataId = 0;
|
||||
fileContentsRequest.haveClipDataId = TRUE;
|
||||
fileContentsRequest.clipDataId = clipDataId;
|
||||
fileContentsRequest.msgFlags = 0;
|
||||
rc = clipboard->context->ClientFileContentsRequest(clipboard->context, &fileContentsRequest);
|
||||
if (rc != ERROR_SUCCESS)
|
||||
@@ -2424,6 +2495,242 @@ error:
|
||||
return res;
|
||||
}
|
||||
|
||||
static void wf_cliprdr_free_served_file_list(wfServedFileList *list)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
if (list->file_names)
|
||||
{
|
||||
for (i = 0; i < list->nFiles; i++)
|
||||
free(list->file_names[i]);
|
||||
free(list->file_names);
|
||||
}
|
||||
free(list->file_sizes);
|
||||
free(list->connIDs);
|
||||
free(list->descriptors);
|
||||
ZeroMemory(list, sizeof(*list));
|
||||
}
|
||||
|
||||
static BOOL wf_cliprdr_served_to(const wfServedFileList *list, UINT32 connID)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < list->nConnIDs; i++)
|
||||
{
|
||||
if (list->connIDs[i] == connID)
|
||||
return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
static void wf_cliprdr_forget_served_file_lists(wfClipboard *clipboard)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
wf_cliprdr_free_served_file_list(&clipboard->served_file_lists[i]);
|
||||
}
|
||||
|
||||
/* Whether a kept list has the current file_names and the same descriptors as dsc, apart
|
||||
* from the nonce in fgd[0].clsid. */
|
||||
static BOOL wf_cliprdr_is_same_file_list(wfClipboard *clipboard, const wfServedFileList *list,
|
||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
||||
{
|
||||
SIZE_T nonce_start = offsetof(FILEGROUPDESCRIPTORW, fgd) + offsetof(FILEDESCRIPTORW, clsid);
|
||||
SIZE_T nonce_end = nonce_start + sizeof(CLSID);
|
||||
size_t i;
|
||||
|
||||
if (!list->file_names || list->nFiles != clipboard->nFiles ||
|
||||
list->descriptorsSize != size || size < nonce_end)
|
||||
return FALSE;
|
||||
for (i = 0; i < list->nFiles; i++)
|
||||
{
|
||||
if (!clipboard->file_names[i] || wcscmp(list->file_names[i], clipboard->file_names[i]) != 0)
|
||||
return FALSE;
|
||||
}
|
||||
return memcmp(list->descriptors, dsc, nonce_start) == 0 &&
|
||||
memcmp(list->descriptors + nonce_end, (const BYTE *)dsc + nonce_end,
|
||||
size - nonce_end) == 0;
|
||||
}
|
||||
|
||||
/* Puts a nonce in fgd[0].clsid, which peers ignore without FD_CLSID. The list id hashes it,
|
||||
* so each copy gets its own id even when two copies have identical names, sizes and times
|
||||
* (the same file in two folders). Re-sending unchanged files keeps their nonce, and id. */
|
||||
static void wf_cliprdr_stamp_file_list(wfClipboard *clipboard, FILEGROUPDESCRIPTORW *dsc,
|
||||
SIZE_T size)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (wf_cliprdr_is_same_file_list(clipboard, &clipboard->served_file_lists[i], dsc, size))
|
||||
{
|
||||
dsc->fgd[0].clsid =
|
||||
((const FILEGROUPDESCRIPTORW *)clipboard->served_file_lists[i].descriptors)
|
||||
->fgd[0]
|
||||
.clsid;
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (FAILED(CoCreateGuid(&dsc->fgd[0].clsid)))
|
||||
ZeroMemory(&dsc->fgd[0].clsid, sizeof(CLSID));
|
||||
}
|
||||
|
||||
static BOOL wf_cliprdr_copy_file_list(wfClipboard *clipboard, wfServedFileList *list,
|
||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
list->file_names = (WCHAR **)calloc(clipboard->nFiles, sizeof(WCHAR *));
|
||||
list->file_sizes = (UINT64 *)calloc(clipboard->nFiles, sizeof(UINT64));
|
||||
list->descriptors = (BYTE *)malloc(size);
|
||||
if (!list->file_names || !list->file_sizes || !list->descriptors)
|
||||
return FALSE;
|
||||
CopyMemory(list->descriptors, dsc, size);
|
||||
list->descriptorsSize = size;
|
||||
list->nFiles = clipboard->nFiles;
|
||||
for (i = 0; i < clipboard->nFiles; i++)
|
||||
{
|
||||
if (!clipboard->file_names[i] ||
|
||||
!(list->file_names[i] = _wcsdup(clipboard->file_names[i])))
|
||||
return FALSE;
|
||||
if (clipboard->fileDescriptor[i])
|
||||
list->file_sizes[i] = ((UINT64)clipboard->fileDescriptor[i]->nFileSizeHigh << 32) |
|
||||
clipboard->fileDescriptor[i]->nFileSizeLow;
|
||||
}
|
||||
list->id = clipboard->file_list_id;
|
||||
list->first_file_index = clipboard->first_file_index;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
/* One slot per list, shared by every connection it was sent to. A full table evicts the list
|
||||
* sent least recently, so a list a transfer has just started on is kept. */
|
||||
static void wf_cliprdr_remember_served_file_list(wfClipboard *clipboard, UINT32 connID,
|
||||
const FILEGROUPDESCRIPTORW *dsc, SIZE_T size)
|
||||
{
|
||||
wfServedFileList *list = NULL;
|
||||
UINT32 *connIDs;
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (clipboard->served_file_lists[i].file_names &&
|
||||
clipboard->served_file_lists[i].id == clipboard->file_list_id)
|
||||
{
|
||||
list = &clipboard->served_file_lists[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!list)
|
||||
{
|
||||
// An empty slot has last_served 0, so it is taken first.
|
||||
list = &clipboard->served_file_lists[0];
|
||||
for (i = 1; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (clipboard->served_file_lists[i].last_served < list->last_served)
|
||||
list = &clipboard->served_file_lists[i];
|
||||
}
|
||||
wf_cliprdr_free_served_file_list(list);
|
||||
if (!wf_cliprdr_copy_file_list(clipboard, list, dsc, size))
|
||||
{
|
||||
wf_cliprdr_free_served_file_list(list);
|
||||
return;
|
||||
}
|
||||
}
|
||||
list->last_served = ++clipboard->served_file_list_seq;
|
||||
|
||||
if (wf_cliprdr_served_to(list, connID))
|
||||
return;
|
||||
connIDs = (UINT32 *)realloc(list->connIDs, (list->nConnIDs + 1) * sizeof(UINT32));
|
||||
if (!connIDs)
|
||||
return;
|
||||
connIDs[list->nConnIDs++] = connID;
|
||||
list->connIDs = connIDs;
|
||||
}
|
||||
|
||||
/* Reads like wf_cliprdr_get_file_contents, but only from the file the list was sent with: a
|
||||
* different size or last-write time means the path now names another file, and the read fails
|
||||
* rather than continuing a transfer with its bytes. */
|
||||
static BOOL wf_cliprdr_get_served_file_contents(const WCHAR *file_name, const FILEDESCRIPTORW *dsc,
|
||||
BYTE *buffer, DWORD positionLow, DWORD positionHigh,
|
||||
DWORD nRequested, DWORD *puSize)
|
||||
{
|
||||
BOOL res = FALSE;
|
||||
HANDLE hFile;
|
||||
LARGE_INTEGER size;
|
||||
LARGE_INTEGER position;
|
||||
FILETIME lastWrite;
|
||||
DWORD nGet;
|
||||
|
||||
hFile = CreateFileW(file_name, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING,
|
||||
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL);
|
||||
if (hFile == INVALID_HANDLE_VALUE)
|
||||
return FALSE;
|
||||
|
||||
if (GetFileSizeEx(hFile, &size) &&
|
||||
(UINT64)size.QuadPart == (((UINT64)dsc->nFileSizeHigh << 32) | dsc->nFileSizeLow) &&
|
||||
(!(dsc->dwFlags & FD_WRITESTIME) ||
|
||||
(GetFileTime(hFile, NULL, NULL, &lastWrite) &&
|
||||
CompareFileTime(&lastWrite, &dsc->ftLastWriteTime) == 0)))
|
||||
{
|
||||
position.LowPart = positionLow;
|
||||
position.HighPart = (LONG)positionHigh;
|
||||
if (SetFilePointerEx(hFile, position, NULL, FILE_BEGIN) &&
|
||||
ReadFile(hFile, buffer, nRequested, &nGet, NULL))
|
||||
{
|
||||
*puSize = nGet;
|
||||
res = TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
CloseHandle(hFile);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Serves a request by path from the file list it names, if that list was sent to the same
|
||||
* connection. An unknown list fails the request rather than falling back to other files. */
|
||||
static BOOL wf_cliprdr_read_served_file_list(wfClipboard *clipboard,
|
||||
const CLIPRDR_FILE_CONTENTS_REQUEST *request,
|
||||
BYTE *data, UINT32 cbRequested, DWORD *puSize)
|
||||
{
|
||||
wfServedFileList *list = NULL;
|
||||
size_t i;
|
||||
|
||||
for (i = 0; i < WF_CLIPRDR_SERVED_FILE_LISTS; i++)
|
||||
{
|
||||
if (clipboard->served_file_lists[i].file_names &&
|
||||
clipboard->served_file_lists[i].id == request->clipDataId &&
|
||||
wf_cliprdr_served_to(&clipboard->served_file_lists[i], request->connID))
|
||||
{
|
||||
list = &clipboard->served_file_lists[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!list || request->listIndex >= list->nFiles)
|
||||
return FALSE;
|
||||
|
||||
if (request->dwFlags == FILECONTENTS_SIZE)
|
||||
{
|
||||
CopyMemory(data, &list->file_sizes[request->listIndex], sizeof(UINT64));
|
||||
*puSize = sizeof(UINT64);
|
||||
return TRUE;
|
||||
}
|
||||
if (request->dwFlags != FILECONTENTS_RANGE)
|
||||
return FALSE;
|
||||
|
||||
if (clipboard->context->HandleClipboardFiles &&
|
||||
request->listIndex == (UINT32)list->first_file_index &&
|
||||
request->nPositionLow == 0 && request->nPositionHigh == 0)
|
||||
{
|
||||
clipboard->context->HandleClipboardFiles(request->connID, list->nFiles, list->file_names);
|
||||
}
|
||||
return wf_cliprdr_get_served_file_contents(
|
||||
list->file_names[request->listIndex],
|
||||
&((const FILEGROUPDESCRIPTORW *)list->descriptors)->fgd[request->listIndex], data,
|
||||
request->nPositionLow, request->nPositionHigh, cbRequested, puSize);
|
||||
}
|
||||
|
||||
/* path_name has a '\' at the end. e.g. c:\newfolder\, file_name is c:\newfolder\new.txt */
|
||||
static FILEDESCRIPTORW *wf_cliprdr_get_file_descriptor(WCHAR *file_name, size_t pathLen)
|
||||
{
|
||||
@@ -3028,6 +3335,8 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
|
||||
STGMEDIUM stg_medium;
|
||||
DROPFILES *dropFiles;
|
||||
FILEGROUPDESCRIPTORW *groupDsc;
|
||||
clipboard->file_list_seq = GetClipboardSequenceNumber();
|
||||
clipboard->file_list_id = 0;
|
||||
result = OleGetClipboard(&dataObj);
|
||||
|
||||
if (FAILED(result))
|
||||
@@ -3164,6 +3473,10 @@ wf_cliprdr_server_format_data_request(CliprdrClientContext *context,
|
||||
|
||||
buff = groupDsc;
|
||||
rc = ERROR_SUCCESS;
|
||||
wf_cliprdr_stamp_file_list(clipboard, groupDsc, size);
|
||||
clipboard->file_list_id = wf_cliprdr_file_list_id((const BYTE *)groupDsc, size);
|
||||
wf_cliprdr_remember_served_file_list(clipboard, formatDataRequest->connID, groupDsc,
|
||||
size);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -3376,6 +3689,18 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
||||
return ERROR_INTERNAL_ERROR;
|
||||
}
|
||||
|
||||
// Refuse an unknown request type, or a range over the cap, before allocating for it. Clients
|
||||
// of this version split larger reads; an older Windows client reading more in one
|
||||
// IStream::Read fails, as with unix owners.
|
||||
if ((fileContentsRequest->dwFlags != FILECONTENTS_SIZE &&
|
||||
fileContentsRequest->dwFlags != FILECONTENTS_RANGE) ||
|
||||
(fileContentsRequest->dwFlags == FILECONTENTS_RANGE &&
|
||||
fileContentsRequest->cbRequested > WF_CLIPRDR_MAX_RANGE_READ))
|
||||
{
|
||||
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
|
||||
goto exit;
|
||||
}
|
||||
|
||||
// If the clipboard is set by the instance, or the file descriptor is from remote,
|
||||
// we should not process the request.
|
||||
// Because this may be the following cases:
|
||||
@@ -3401,6 +3726,22 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
||||
goto exit;
|
||||
}
|
||||
|
||||
// A stream whose list is no longer the current one reads by path from the list it came from.
|
||||
// Only lists sent to this connection are served.
|
||||
if (fileContentsRequest->haveClipDataId &&
|
||||
fileContentsRequest->clipDataId != clipboard->file_list_id)
|
||||
{
|
||||
ZeroMemory(&vStgMedium, sizeof(STGMEDIUM)); // read at exit
|
||||
cbRequested = fileContentsRequest->dwFlags == FILECONTENTS_SIZE
|
||||
? sizeof(UINT64)
|
||||
: fileContentsRequest->cbRequested;
|
||||
pData = (BYTE *)calloc(1, cbRequested);
|
||||
if (pData && wf_cliprdr_read_served_file_list(clipboard, fileContentsRequest, pData,
|
||||
cbRequested, &uSize))
|
||||
rc = CHANNEL_RC_OK;
|
||||
goto exit;
|
||||
}
|
||||
|
||||
cbRequested = fileContentsRequest->cbRequested;
|
||||
if (fileContentsRequest->dwFlags == FILECONTENTS_SIZE)
|
||||
cbRequested = sizeof(UINT64);
|
||||
@@ -3430,7 +3771,13 @@ wf_cliprdr_server_file_contents_request(CliprdrClientContext *context,
|
||||
vFormatEtc.lindex = fileContentsRequest->listIndex;
|
||||
vFormatEtc.ptd = NULL;
|
||||
|
||||
if ((uStreamIdStc != fileContentsRequest->streamId) ||
|
||||
if (GetClipboardSequenceNumber() != clipboard->file_list_seq)
|
||||
{
|
||||
// The clipboard changed after the peer got its file list. The live FileContents
|
||||
// belongs to the new copy, so reading it would splice another file into this one.
|
||||
bIsStreamFile = FALSE;
|
||||
}
|
||||
else if ((uStreamIdStc != fileContentsRequest->streamId) ||
|
||||
(uConnIdStc != fileContentsRequest->connID) || !pStreamStc)
|
||||
{
|
||||
LPENUMFORMATETC pEnumFormatEtc;
|
||||
@@ -3842,6 +4189,7 @@ BOOL wf_cliprdr_uninit(wfClipboard *clipboard, CliprdrClientContext *cliprdr)
|
||||
CloseHandle(clipboard->req_fevent);
|
||||
|
||||
clear_file_array(clipboard);
|
||||
wf_cliprdr_forget_served_file_lists(clipboard);
|
||||
clear_format_map(clipboard);
|
||||
free(clipboard->format_mappings);
|
||||
return TRUE;
|
||||
|
||||
@@ -39,6 +39,17 @@ fn mouse_event(flags: u32, data: u32, dx: i32, dy: i32) -> DWORD {
|
||||
unsafe { SendInput(1, &mut input as LPINPUT, size_of::<INPUT>() as c_int) }
|
||||
}
|
||||
|
||||
// `v` comes from the remote peer unchecked, so scale in i64 to avoid overflow, and clamp to
|
||||
// the 0..=65535 range MOUSEEVENTF_ABSOLUTE takes.
|
||||
// `extent` is 0 when the virtual screen metrics are unavailable.
|
||||
fn to_absolute(v: i32, origin: i32, extent: i32) -> Option<i32> {
|
||||
if extent <= 0 {
|
||||
return None;
|
||||
}
|
||||
let abs = (v as i64 - origin as i64) * 65535 / extent as i64;
|
||||
Some(abs.clamp(0, 65535) as i32)
|
||||
}
|
||||
|
||||
fn keybd_event(mut flags: u32, vk: u16, scan: u16) -> DWORD {
|
||||
let mut scan = scan;
|
||||
unsafe {
|
||||
@@ -126,13 +137,28 @@ impl MouseControllable for Enigo {
|
||||
}
|
||||
|
||||
fn mouse_move_to(&mut self, x: i32, y: i32) {
|
||||
let (left, top, width, height) = unsafe {
|
||||
(
|
||||
GetSystemMetrics(SM_XVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_YVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CXVIRTUALSCREEN),
|
||||
GetSystemMetrics(SM_CYVIRTUALSCREEN),
|
||||
)
|
||||
};
|
||||
let (Some(dx), Some(dy)) = (to_absolute(x, left, width), to_absolute(y, top, height))
|
||||
else {
|
||||
hbb_common::throttled_log!(
|
||||
std::time::Duration::from_secs(60),
|
||||
warn,
|
||||
"mouse_move_to skipped: virtual screen size unavailable"
|
||||
);
|
||||
return;
|
||||
};
|
||||
mouse_event(
|
||||
MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK,
|
||||
0,
|
||||
(x - unsafe { GetSystemMetrics(SM_XVIRTUALSCREEN) }) * 65535
|
||||
/ unsafe { GetSystemMetrics(SM_CXVIRTUALSCREEN) },
|
||||
(y - unsafe { GetSystemMetrics(SM_YVIRTUALSCREEN) }) * 65535
|
||||
/ unsafe { GetSystemMetrics(SM_CYVIRTUALSCREEN) },
|
||||
dx,
|
||||
dy,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+3
-271
@@ -61,7 +61,7 @@ use hbb_common::{
|
||||
use hbb_common::{tokio::sync::Mutex as TokioMutex, ResultType};
|
||||
use scrap::CodecFormat;
|
||||
use std::{
|
||||
collections::{HashMap, HashSet},
|
||||
collections::HashMap,
|
||||
ffi::c_void,
|
||||
num::NonZeroI64,
|
||||
path::PathBuf,
|
||||
@@ -96,7 +96,6 @@ pub struct Remote<T: InvokeUiSession> {
|
||||
chroma: Arc<RwLock<Option<Chroma>>>,
|
||||
last_record_state: bool,
|
||||
sent_close_reason: bool,
|
||||
cursor_dedupe: CursorDedupe,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -146,7 +145,6 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
chroma: Default::default(),
|
||||
last_record_state: false,
|
||||
sent_close_reason: false,
|
||||
cursor_dedupe: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1525,29 +1523,11 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Some(message::Union::CursorData(cd)) if self.dedupes_cursors() => {
|
||||
self.set_cursor_data_by_content(cd);
|
||||
}
|
||||
Some(message::Union::CursorId(id)) if self.dedupes_cursors() => {
|
||||
self.handler
|
||||
.set_cursor_id(self.cursor_dedupe.id(id).to_string());
|
||||
}
|
||||
Some(message::Union::CursorData(cd)) => {
|
||||
let id = cd.id;
|
||||
#[cfg(feature = "flutter")]
|
||||
let compressed = cd.colors.clone();
|
||||
match decode_cursor_data(cd) {
|
||||
Ok(cd) => {
|
||||
#[cfg(feature = "flutter")]
|
||||
self.keep_cursor_shape(cursor_shape(id, &cd, &compressed));
|
||||
self.handler.set_cursor_data(cd)
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!("Rejected cursor {id}: {err}");
|
||||
// The peer shows it now: selected, the UI treats it as a shape it
|
||||
// lacks, as it will when the peer selects it again.
|
||||
self.handler.set_cursor_id(id.to_string());
|
||||
}
|
||||
Ok(cd) => self.handler.set_cursor_data(cd),
|
||||
Err(err) => log::warn!("Rejected cursor {id}: {err}"),
|
||||
}
|
||||
}
|
||||
Some(message::Union::CursorId(id)) => {
|
||||
@@ -2580,69 +2560,6 @@ impl<T: InvokeUiSession> Remote<T> {
|
||||
msg.set_misc(misc);
|
||||
self.sender.send(Data::Message(msg)).ok();
|
||||
}
|
||||
|
||||
/// A shape that decoded, for the UI to ask for again; see `Session::cursor_shapes`.
|
||||
#[cfg(feature = "flutter")]
|
||||
fn keep_cursor_shape(&self, shape: CursorData) {
|
||||
self.handler
|
||||
.cursor_shapes
|
||||
.write()
|
||||
.unwrap()
|
||||
.insert(shape.id, shape);
|
||||
}
|
||||
|
||||
fn dedupes_cursors(&self) -> bool {
|
||||
!crate::is_peer_naming_cursors_by_content(self.handler.lc.read().unwrap().version)
|
||||
}
|
||||
|
||||
/// A shape the UI already has, under whatever handle, is only selected.
|
||||
fn set_cursor_data_by_content(&mut self, cd: CursorData) {
|
||||
let peer_id = cd.id;
|
||||
let id = CursorDedupe::name(&cd);
|
||||
if self.cursor_dedupe.has_decoded(id) {
|
||||
self.cursor_dedupe.record(peer_id, id);
|
||||
self.handler.set_cursor_id(id.to_string());
|
||||
return;
|
||||
}
|
||||
#[cfg(feature = "flutter")]
|
||||
let compressed = cd.colors.clone();
|
||||
match decode_cursor_data(cd) {
|
||||
Ok(mut cd) => {
|
||||
cd.id = id;
|
||||
self.cursor_dedupe.record(peer_id, id);
|
||||
#[cfg(feature = "flutter")]
|
||||
self.keep_cursor_shape(cursor_shape(id, &cd, &compressed));
|
||||
self.handler.set_cursor_data(cd);
|
||||
}
|
||||
Err(err) => {
|
||||
log::warn!("Rejected cursor {peer_id}: {err}");
|
||||
self.handler
|
||||
.set_cursor_id(self.cursor_dedupe.rejected(peer_id, id).to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A shape that decoded, still compressed, under the id the UI knows it by. Copied once it
|
||||
/// decoded: the message's colors may be a slice of a larger received buffer, which a clone
|
||||
/// would keep alive.
|
||||
#[cfg(any(feature = "flutter", test))]
|
||||
fn cursor_shape(id: u64, cd: &CursorData, compressed: &[u8]) -> CursorData {
|
||||
CursorData {
|
||||
id,
|
||||
hotx: cd.hotx,
|
||||
hoty: cd.hoty,
|
||||
width: cd.width,
|
||||
height: cd.height,
|
||||
colors: compressed.to_vec().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// The RGBA of a shape kept by `Session::cursor_shapes`, for the UI to draw it again.
|
||||
#[cfg(any(feature = "flutter", test))]
|
||||
pub(crate) fn kept_cursor_rgba(shape: CursorData) -> hbb_common::ResultType<CursorData> {
|
||||
decode_cursor_data(shape)
|
||||
}
|
||||
|
||||
// Both UI handlers receive validated, uncompressed RGBA from the receive loop.
|
||||
@@ -2686,49 +2603,6 @@ fn decode_cursor_data(data: CursorData) -> hbb_common::ResultType<CursorData> {
|
||||
Ok(cd)
|
||||
}
|
||||
|
||||
/// Gives the UI one id per shape for a peer that names shapes by handle, so the UI decodes and
|
||||
/// keeps a shape once however many handles it arrives under. Nothing is dropped for the
|
||||
/// connection: the peer sends a shape once and may select any handle it named again.
|
||||
#[derive(Default)]
|
||||
struct CursorDedupe {
|
||||
ids: HashMap<u64, u64>,
|
||||
// The shapes given to the UI, by content id: whether one that arrives needs decoding.
|
||||
decoded: HashSet<u64>,
|
||||
}
|
||||
|
||||
impl CursorDedupe {
|
||||
/// Hashes the compressed colors: one peer compresses the same pixels to the same bytes, and
|
||||
/// a shape seen before is then never decompressed again.
|
||||
fn name(cd: &CursorData) -> u64 {
|
||||
crate::cursor_content_id(cd.width, cd.height, cd.hotx, cd.hoty, &cd.colors)
|
||||
}
|
||||
|
||||
fn id(&self, peer_id: u64) -> u64 {
|
||||
self.ids.get(&peer_id).copied().unwrap_or(peer_id)
|
||||
}
|
||||
|
||||
fn has_decoded(&self, id: u64) -> bool {
|
||||
self.decoded.contains(&id)
|
||||
}
|
||||
|
||||
/// Names the handle once its shape decoded, now or before.
|
||||
fn record(&mut self, peer_id: u64, id: u64) {
|
||||
self.ids.insert(peer_id, id);
|
||||
self.decoded.insert(id);
|
||||
}
|
||||
|
||||
/// Names a known handle by the content of a shape that did not decode, which is never
|
||||
/// marked decoded: the UI has no shape under it, now or when the handle is selected again,
|
||||
/// and the shape the handle named before is not shown in its place. A handle never seen is
|
||||
/// not filed, so what a peer sends that does not decode takes no room.
|
||||
fn rejected(&mut self, peer_id: u64, id: u64) -> u64 {
|
||||
if let Some(named) = self.ids.get_mut(&peer_id) {
|
||||
*named = id;
|
||||
}
|
||||
id
|
||||
}
|
||||
}
|
||||
|
||||
struct RemoveJob {
|
||||
files: Vec<FileEntry>,
|
||||
path: String,
|
||||
@@ -2851,145 +2725,3 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cursor_dedupe_tests {
|
||||
use super::*;
|
||||
|
||||
fn shape(id: u64, hotx: i32, colors: &[u8]) -> CursorData {
|
||||
CursorData {
|
||||
id,
|
||||
hotx,
|
||||
width: 2,
|
||||
height: 2,
|
||||
colors: colors.to_vec().into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_sent_under_a_new_handle_keeps_its_id() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
let first = CursorDedupe::name(&shape(1, 0, b"arrow"));
|
||||
assert!(!dedupe.has_decoded(first));
|
||||
dedupe.record(1, first);
|
||||
|
||||
let again = CursorDedupe::name(&shape(2, 0, b"arrow"));
|
||||
assert_eq!(again, first);
|
||||
assert!(dedupe.has_decoded(again));
|
||||
dedupe.record(2, again);
|
||||
assert_eq!(dedupe.id(2), first);
|
||||
assert_eq!(dedupe.id(1), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_hotspot_is_part_of_the_shape() {
|
||||
let a = CursorDedupe::name(&shape(1, 0, b"arrow"));
|
||||
let b = CursorDedupe::name(&shape(2, 1, b"arrow"));
|
||||
assert_ne!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reused_handle_names_its_latest_shape() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
dedupe.record(1, CursorDedupe::name(&shape(1, 0, b"arrow")));
|
||||
let beam = CursorDedupe::name(&shape(1, 0, b"beam"));
|
||||
dedupe.record(1, beam);
|
||||
assert_eq!(dedupe.id(1), beam);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rejected_shape_names_its_handle_and_is_never_decoded() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
let arrow = CursorDedupe::name(&shape(7, 0, b"arrow"));
|
||||
dedupe.record(7, arrow);
|
||||
let beam = CursorDedupe::name(&shape(8, 0, b"beam"));
|
||||
dedupe.record(8, beam);
|
||||
let broken = CursorDedupe::name(&shape(7, 0, b"broken"));
|
||||
assert_eq!(
|
||||
dedupe.rejected(7, broken),
|
||||
broken,
|
||||
"not the shape it named before"
|
||||
);
|
||||
assert_eq!(
|
||||
dedupe.id(7),
|
||||
broken,
|
||||
"nor when the handle is selected again"
|
||||
);
|
||||
assert_eq!(dedupe.id(8), beam, "another handle keeps its shape");
|
||||
assert!(!dedupe.has_decoded(broken));
|
||||
assert!(
|
||||
dedupe.has_decoded(arrow),
|
||||
"kept for a handle that brings it again"
|
||||
);
|
||||
dedupe.record(7, arrow);
|
||||
assert_eq!(dedupe.id(7), arrow);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_shape_rejected_under_handles_never_seen_files_nothing() {
|
||||
let mut dedupe = CursorDedupe::default();
|
||||
let broken = CursorDedupe::name(&shape(0, 0, b"broken"));
|
||||
for handle in 0..1000 {
|
||||
assert_eq!(dedupe.rejected(handle, broken), broken);
|
||||
}
|
||||
assert!(dedupe.ids.is_empty());
|
||||
assert!(!dedupe.has_decoded(broken));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_the_peer_never_sent_is_passed_on() {
|
||||
assert_eq!(CursorDedupe::default().id(7), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peers_from_1_5_0_name_cursors_by_content() {
|
||||
use hbb_common::get_version_number as v;
|
||||
assert!(!crate::is_peer_naming_cursors_by_content(v("1.4.9")));
|
||||
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.0")));
|
||||
assert!(crate::is_peer_naming_cursors_by_content(v("1.5.1")));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod kept_cursor_tests {
|
||||
use super::*;
|
||||
|
||||
fn compressed(width: i32, height: i32) -> CursorData {
|
||||
let rgba = vec![7u8; (width * height * 4) as usize];
|
||||
CursorData {
|
||||
id: 1,
|
||||
width,
|
||||
height,
|
||||
colors: hbb_common::compress::compress(&rgba).into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_shape_is_a_copy_under_the_ui_id() {
|
||||
let mut cd = compressed(4, 4);
|
||||
cd.hotx = 1;
|
||||
let kept = cursor_shape(42, &cd, &cd.colors);
|
||||
assert_eq!(kept.id, 42);
|
||||
assert_eq!((kept.hotx, kept.width, kept.height), (1, 4, 4));
|
||||
assert_eq!(kept.colors, cd.colors);
|
||||
assert_ne!(
|
||||
kept.colors.as_ptr(),
|
||||
cd.colors.as_ptr(),
|
||||
"not a view of the received buffer"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_kept_shape_is_checked_again_when_it_is_read() {
|
||||
assert_eq!(kept_cursor_rgba(compressed(4, 4)).unwrap().colors.len(), 64);
|
||||
assert!(
|
||||
kept_cursor_rgba(compressed(513, 1)).is_err(),
|
||||
"over the size cap"
|
||||
);
|
||||
let mut bomb = compressed(4, 4);
|
||||
bomb.colors = hbb_common::compress::compress(&vec![0u8; 1 << 20]).into();
|
||||
assert!(kept_cursor_rgba(bomb).is_err(), "more pixels than its size");
|
||||
}
|
||||
}
|
||||
|
||||
+10
-3
@@ -314,7 +314,7 @@ pub mod unix_file_clip {
|
||||
requested_format_id: _requested_format_id,
|
||||
} => {
|
||||
log::debug!("requested format id: {}", _requested_format_id);
|
||||
let format_data = serv_files::get_file_list_pdu();
|
||||
let format_data = serv_files::get_file_list_pdu(conn_id);
|
||||
if !format_data.is_empty() {
|
||||
return vec![clip_2_msg(ClipboardFile::FormatDataResponse {
|
||||
msg_flags: 1,
|
||||
@@ -365,7 +365,8 @@ pub mod unix_file_clip {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested,
|
||||
..
|
||||
have_clip_data_id,
|
||||
clip_data_id,
|
||||
} => {
|
||||
log::debug!("file contents request: stream_id: {}, list_index: {}, dw_flags: {}, n_position_low: {}, n_position_high: {}, cb_requested: {}", stream_id, list_index, dw_flags, n_position_low, n_position_high, cb_requested);
|
||||
return serv_files::read_file_contents(
|
||||
@@ -376,12 +377,18 @@ pub mod unix_file_clip {
|
||||
n_position_low,
|
||||
n_position_high,
|
||||
cb_requested,
|
||||
have_clip_data_id.then_some(clip_data_id),
|
||||
)
|
||||
.into_iter()
|
||||
.map(|res| match res {
|
||||
Ok(data) => clip_2_msg(data),
|
||||
Err(e) => {
|
||||
log::error!("failed to read file contents: {:?}", e);
|
||||
hbb_common::throttled_log!(
|
||||
std::time::Duration::from_secs(5),
|
||||
error,
|
||||
"failed to read file contents: {:?}",
|
||||
e
|
||||
);
|
||||
resp_file_contents_fail(stream_id)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -149,24 +149,6 @@ pub fn is_support_multi_ui_session_num(ver: i64) -> bool {
|
||||
ver >= hbb_common::get_version_number(MIN_VER_MULTI_UI_SESSION)
|
||||
}
|
||||
|
||||
/// Peers from the 1.5.0 release name a cursor by `cursor_content_id`; older ones by the
|
||||
/// platform handle, which apps mint anew for the same shape.
|
||||
#[inline]
|
||||
pub fn is_peer_naming_cursors_by_content(ver: i64) -> bool {
|
||||
ver >= hbb_common::get_version_number("1.5.0")
|
||||
}
|
||||
|
||||
/// One id per cursor look, however many handles a platform gives it. Held to 53 bits: the web
|
||||
/// client decodes a u64 into a JS number and drops the whole message when it does not fit.
|
||||
pub fn cursor_content_id(width: i32, height: i32, hotx: i32, hoty: i32, colors: &[u8]) -> u64 {
|
||||
let mut hasher = xxhash_rust::xxh3::Xxh3::new();
|
||||
for v in [width, height, hotx, hoty] {
|
||||
hasher.update(&v.to_le_bytes());
|
||||
}
|
||||
hasher.update(colors);
|
||||
hasher.digest() & ((1 << 53) - 1)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
#[cfg(feature = "unix-file-copy-paste")]
|
||||
pub fn is_support_file_copy_paste(ver: &str) -> bool {
|
||||
@@ -2954,16 +2936,6 @@ mod tests {
|
||||
};
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[test]
|
||||
fn a_cursor_content_id_fits_a_web_client_number() {
|
||||
const MAX_SAFE_INTEGER: u64 = (1 << 53) - 1;
|
||||
for colors in [&b"arrow"[..], b"beam", b"hand", b""] {
|
||||
for hotx in 0..64 {
|
||||
assert!(cursor_content_id(32, 32, hotx, 0, colors) <= MAX_SAFE_INTEGER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn get_timestamp_secs() -> u128 {
|
||||
(std::time::SystemTime::UNIX_EPOCH
|
||||
|
||||
+16
-14
@@ -651,21 +651,23 @@ impl FlutterHandler {
|
||||
}
|
||||
|
||||
impl InvokeUiSession for FlutterHandler {
|
||||
// On the event stream, so that it keeps its order with the cursor_id events around it.
|
||||
fn set_cursor_data(&self, cd: CursorData) {
|
||||
let colors = cd.colors.to_vec();
|
||||
for session in self.session_handlers.read().unwrap().values() {
|
||||
if let Some(stream) = &session.event_stream {
|
||||
stream.add(EventToUI::Cursor {
|
||||
id: cd.id.to_string(),
|
||||
hotx: cd.hotx,
|
||||
hoty: cd.hoty,
|
||||
width: cd.width,
|
||||
height: cd.height,
|
||||
colors: colors.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
let colors = &cd.colors;
|
||||
self.push_event(
|
||||
"cursor_data",
|
||||
&[
|
||||
("id", &cd.id.to_string()),
|
||||
("hotx", &cd.hotx.to_string()),
|
||||
("hoty", &cd.hoty.to_string()),
|
||||
("width", &cd.width.to_string()),
|
||||
("height", &cd.height.to_string()),
|
||||
(
|
||||
"colors",
|
||||
&serde_json::ser::to_string(&colors).unwrap_or("".to_owned()),
|
||||
),
|
||||
],
|
||||
&[],
|
||||
);
|
||||
}
|
||||
|
||||
fn set_cursor_id(&self, id: String) {
|
||||
|
||||
@@ -97,16 +97,6 @@ pub enum EventToUI {
|
||||
Event(String),
|
||||
Rgba(usize),
|
||||
Texture(usize, bool), // (display, gpu_texture)
|
||||
// A shape's RGBA as bytes: as text it was four times the size and parsed on the UI thread.
|
||||
// The id stays text, since the peer's ids can exceed Dart's int.
|
||||
Cursor {
|
||||
id: String,
|
||||
hotx: i32,
|
||||
hoty: i32,
|
||||
width: i32,
|
||||
height: i32,
|
||||
colors: Vec<u8>,
|
||||
},
|
||||
}
|
||||
|
||||
pub fn host_stop_system_key_propagate(_stopped: bool) {
|
||||
@@ -211,34 +201,6 @@ pub fn session_start_with_displays(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// A cursor shape the core keeps, as RGBA, for a window that has to draw it again.
|
||||
pub struct CursorShape {
|
||||
pub hotx: i32,
|
||||
pub hoty: i32,
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
pub colors: Vec<u8>,
|
||||
}
|
||||
|
||||
pub fn session_get_cursor_shape(session_id: SessionID, id: String) -> Option<CursorShape> {
|
||||
let id = id.parse::<u64>().ok()?;
|
||||
let session = sessions::get_session_by_session_id(&session_id)?;
|
||||
let shape = session.cursor_shapes.read().unwrap().get(&id).cloned()?;
|
||||
match crate::client::io_loop::kept_cursor_rgba(shape) {
|
||||
Ok(cd) => Some(CursorShape {
|
||||
hotx: cd.hotx,
|
||||
hoty: cd.hoty,
|
||||
width: cd.width,
|
||||
height: cd.height,
|
||||
colors: cd.colors.to_vec(),
|
||||
}),
|
||||
Err(err) => {
|
||||
log::warn!("Kept cursor {id} failed to decode: {err}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn session_get_remember(session_id: SessionID) -> Option<bool> {
|
||||
if let Some(session) = sessions::get_session_by_session_id(&session_id) {
|
||||
Some(session.get_remember())
|
||||
|
||||
+52
-9
@@ -559,9 +559,6 @@ pub fn get_cursor() -> ResultType<Option<u64>> {
|
||||
autoreleasepool(|| unsafe_get_cursor())
|
||||
}
|
||||
|
||||
// The seed names a change of cursor, not a cursor: the shape is named by its content once
|
||||
// captured, as on every platform. A fingerprint of its size, hotspot and two pixels named the open
|
||||
// and the closed hand alike, and the arrows with a badge, so a switch between them went unsent.
|
||||
fn unsafe_get_cursor() -> ResultType<Option<u64>> {
|
||||
unsafe {
|
||||
let seed = CGSCurrentCursorSeed();
|
||||
@@ -569,8 +566,9 @@ fn unsafe_get_cursor() -> ResultType<Option<u64>> {
|
||||
return Ok(None);
|
||||
}
|
||||
LATEST_SEED = seed;
|
||||
Ok(Some(seed as u32 as u64))
|
||||
}
|
||||
let c = get_cursor_id()?;
|
||||
Ok(Some(c.1))
|
||||
}
|
||||
|
||||
pub fn reset_input_cache() {
|
||||
@@ -579,6 +577,53 @@ pub fn reset_input_cache() {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_cursor_id() -> ResultType<(id, u64)> {
|
||||
unsafe {
|
||||
let c: id = msg_send![class!(NSCursor), currentSystemCursor];
|
||||
if c == nil {
|
||||
bail!("Failed to call [NSCursor currentSystemCursor]");
|
||||
}
|
||||
let hotspot: NSPoint = msg_send![c, hotSpot];
|
||||
let img: id = msg_send![c, image];
|
||||
if img == nil {
|
||||
bail!("Failed to call [NSCursor image]");
|
||||
}
|
||||
let size: NSSize = msg_send![img, size];
|
||||
let tif: id = msg_send![img, TIFFRepresentation];
|
||||
if tif == nil {
|
||||
bail!("Failed to call [NSImage TIFFRepresentation]");
|
||||
}
|
||||
let rep: id = msg_send![class!(NSBitmapImageRep), imageRepWithData: tif];
|
||||
if rep == nil {
|
||||
bail!("Failed to call [NSBitmapImageRep imageRepWithData]");
|
||||
}
|
||||
let rep_size: NSSize = msg_send![rep, size];
|
||||
let mut hcursor =
|
||||
size.width + size.height + hotspot.x + hotspot.y + rep_size.width + rep_size.height;
|
||||
let x = (rep_size.width * hotspot.x / size.width) as usize;
|
||||
let y = (rep_size.height * hotspot.y / size.height) as usize;
|
||||
for i in 0..2 {
|
||||
let mut x2 = x + i;
|
||||
if x2 >= rep_size.width as usize {
|
||||
x2 = rep_size.width as usize - 1;
|
||||
}
|
||||
let mut y2 = y + i;
|
||||
if y2 >= rep_size.height as usize {
|
||||
y2 = rep_size.height as usize - 1;
|
||||
}
|
||||
let color: id = msg_send![rep, colorAtX:x2 y:y2];
|
||||
if color != nil {
|
||||
let r: f64 = msg_send![color, redComponent];
|
||||
let g: f64 = msg_send![color, greenComponent];
|
||||
let b: f64 = msg_send![color, blueComponent];
|
||||
let a: f64 = msg_send![color, alphaComponent];
|
||||
hcursor += (r + g + b + a) * (255 << i) as f64;
|
||||
}
|
||||
}
|
||||
Ok((c, hcursor as _))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
|
||||
autoreleasepool(|| unsafe_get_cursor_data(hcursor))
|
||||
}
|
||||
@@ -586,11 +631,9 @@ pub fn get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
|
||||
// https://github.com/stweil/OSXvnc/blob/master/OSXvnc-server/mousecursor.c
|
||||
fn unsafe_get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
|
||||
unsafe {
|
||||
// The cursor shown is captured even if it changed after get_cursor read the seed: the
|
||||
// content names the shape, and that change moved the seed on, so the next poll captures it.
|
||||
let c: id = msg_send![class!(NSCursor), currentSystemCursor];
|
||||
if c == nil {
|
||||
bail!("Failed to call [NSCursor currentSystemCursor]");
|
||||
let (c, hcursor2) = get_cursor_id()?;
|
||||
if hcursor != hcursor2 {
|
||||
bail!("cursor changed");
|
||||
}
|
||||
let hotspot: NSPoint = msg_send![c, hotSpot];
|
||||
let img: id = msg_send![c, image];
|
||||
|
||||
@@ -228,14 +228,6 @@ mod tests {
|
||||
#[cfg(target_os = "macos")]
|
||||
macos::is_process_trusted(false);
|
||||
}
|
||||
// A macOS capture takes the cursor shown, whatever seed it is asked for.
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
macos::reset_input_cache();
|
||||
if let Some(change) = get_cursor().unwrap() {
|
||||
assert!(get_cursor_data(change.wrapping_add(1)).is_ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn test_get_cursor_pos() {
|
||||
|
||||
@@ -3990,17 +3990,6 @@ impl Connection {
|
||||
self.send(msg_out).await;
|
||||
}
|
||||
}
|
||||
// Only to a connection the cursor service would send the shape to.
|
||||
#[cfg(not(any(target_os = "android", target_os = "ios")))]
|
||||
Some(misc::Union::RequestCursorData(id)) => {
|
||||
if self.is_remote()
|
||||
&& (self.peer_keyboard_enabled() || self.show_remote_cursor)
|
||||
{
|
||||
if let Some(msg) = input_service::cursor_data_message(id) {
|
||||
self.send((*msg).clone()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Some(message::Union::AudioFrame(frame)) => {
|
||||
|
||||
+7
-198
@@ -42,7 +42,6 @@ struct StateCursor {
|
||||
impl super::service::Reset for StateCursor {
|
||||
fn reset(&mut self) {
|
||||
*self = Default::default();
|
||||
CURSOR_SHAPES.lock().unwrap().clear();
|
||||
crate::platform::reset_input_cache();
|
||||
fix_key_down_timeout(true);
|
||||
}
|
||||
@@ -407,7 +406,7 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
||||
super::log::trace!("Cursor data cached, hcursor: {}", hcursor);
|
||||
msg = cached.clone();
|
||||
} else {
|
||||
let data = crate::get_cursor_data(hcursor)?;
|
||||
let mut data = crate::get_cursor_data(hcursor)?;
|
||||
// File the shape under the id ACTUALLY served, not the one requested. Deliberately a
|
||||
// NEW name rather than shadowing `hcursor`: the insert below reads as the requested
|
||||
// id everywhere else in this function, and a cfg-gated shadow would make the two
|
||||
@@ -422,7 +421,10 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
||||
let cache_key = served_id;
|
||||
#[cfg(not(all(target_os = "linux", feature = "drm")))]
|
||||
let cache_key = hcursor;
|
||||
msg = cursor_shape_message(data, hbb_common::compress::compress);
|
||||
data.colors = hbb_common::compress::compress(&data.colors[..]).into();
|
||||
let mut tmp = Message::new();
|
||||
tmp.set_cursor_data(data);
|
||||
msg = Arc::new(tmp);
|
||||
// A DRM cursor id is derived from the shape's pixels plus geometry, so an animated
|
||||
// pointer mints a new id on every shape change and this map would grow for the life
|
||||
// of the service, each entry pinning a compressed cursor message. (Upstream's X11
|
||||
@@ -436,15 +438,8 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
||||
const CURSOR_CACHE_MAX: usize = 64;
|
||||
if state.cached_cursor_data.len() >= CURSOR_CACHE_MAX {
|
||||
state.cached_cursor_data.clear();
|
||||
CURSOR_SHAPES.lock().unwrap().clear();
|
||||
// The shape being sent was kept above; keep it past the clear.
|
||||
shared_cursor_shape(msg.clone());
|
||||
}
|
||||
}
|
||||
limit_cursor_handles(&mut state.cached_cursor_data, &msg);
|
||||
// A macOS seed marks a change, never the same one twice: filing it would only
|
||||
// fill the map.
|
||||
#[cfg(not(target_os = "macos"))]
|
||||
state.cached_cursor_data.insert(cache_key, msg.clone());
|
||||
super::log::trace!("Cursor data updated, hcursor: {}", cache_key);
|
||||
}
|
||||
@@ -456,12 +451,8 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
||||
{
|
||||
state.hcursor = drm_served_id;
|
||||
}
|
||||
// A new handle or seed for the shape already shown changes nothing a controller sees;
|
||||
// a shape is one message however many handles name it.
|
||||
if !Arc::ptr_eq(&msg, &state.cursor_data) {
|
||||
sp.send_shared(msg.clone());
|
||||
state.cursor_data = msg;
|
||||
}
|
||||
sp.send_shared(msg.clone());
|
||||
state.cursor_data = msg;
|
||||
}
|
||||
}
|
||||
sp.snapshot(|sps| {
|
||||
@@ -508,95 +499,6 @@ lazy_static::lazy_static! {
|
||||
static ref RELATIVE_MOUSE_CONNS: Arc<Mutex<std::collections::HashSet<i32>>> = Default::default();
|
||||
}
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
// Every shape the service has sent, by content id, for a controller that asks for one
|
||||
// again. A shape under several handles is one message here, shared with `cached_cursor_data`,
|
||||
// and cleared with it; see `limit_cursor_handles` for the ceilings. A shape dropped is
|
||||
// rebuilt here the next time it is shown, in `run_cursor`, before any connection sends its
|
||||
// `cursor_id`: whatever a controller has just been told to show, it can ask for.
|
||||
static ref CURSOR_SHAPES: Mutex<CursorShapes> = Default::default();
|
||||
}
|
||||
|
||||
/// The shapes sent, by content id, and the bytes they hold compressed.
|
||||
#[derive(Default)]
|
||||
struct CursorShapes {
|
||||
shapes: HashMap<u64, Arc<Message>>,
|
||||
bytes: usize,
|
||||
}
|
||||
|
||||
impl CursorShapes {
|
||||
fn get(&self, id: &u64) -> Option<&Arc<Message>> {
|
||||
self.shapes.get(id)
|
||||
}
|
||||
|
||||
fn clear(&mut self) {
|
||||
self.shapes.clear();
|
||||
self.bytes = 0;
|
||||
}
|
||||
|
||||
/// The message kept for this shape, `msg` if there was none.
|
||||
fn keep(&mut self, cd: &CursorData, msg: &Arc<Message>) -> Arc<Message> {
|
||||
let bytes = &mut self.bytes;
|
||||
self.shapes
|
||||
.entry(cd.id)
|
||||
.or_insert_with(|| {
|
||||
*bytes += cd.colors.len();
|
||||
msg.clone()
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The message for a shape the platform gave, named by content, so the per-connection send sends
|
||||
/// a shape once however many handles the platform gives it; see
|
||||
/// `is_peer_naming_cursors_by_content`. A shape sent before, under any handle, is reused without
|
||||
/// being compressed again.
|
||||
fn cursor_shape_message(
|
||||
mut data: CursorData,
|
||||
compress: impl FnOnce(&[u8]) -> Vec<u8>,
|
||||
) -> Arc<Message> {
|
||||
data.id = crate::cursor_content_id(data.width, data.height, data.hotx, data.hoty, &data.colors);
|
||||
if let Some(msg) = cursor_data_message(data.id) {
|
||||
return msg;
|
||||
}
|
||||
data.colors = compress(&data.colors[..]).into();
|
||||
let mut msg = Message::new();
|
||||
msg.set_cursor_data(data);
|
||||
shared_cursor_shape(Arc::new(msg))
|
||||
}
|
||||
|
||||
// A platform may mint a new handle each time it shows a shape (Chrome, Electron), so the handles
|
||||
// filed would grow for the life of the service, each entry a u64 and an Arc even when every one
|
||||
// names the same shape. Past this many handles, or this many bytes of compressed shapes, however
|
||||
// few, the handles and the shapes start over together: a handle shown again is captured and named
|
||||
// again. macOS files no handles, so there the bytes alone bound the shapes.
|
||||
const CURSOR_HANDLES_MAX: usize = 4096;
|
||||
const CURSOR_SHAPES_BYTES_MAX: usize = 32 << 20;
|
||||
|
||||
fn limit_cursor_handles(handles: &mut HashMap<u64, Arc<Message>>, sending: &Arc<Message>) {
|
||||
if handles.len() >= CURSOR_HANDLES_MAX
|
||||
|| CURSOR_SHAPES.lock().unwrap().bytes >= CURSOR_SHAPES_BYTES_MAX
|
||||
{
|
||||
handles.clear();
|
||||
CURSOR_SHAPES.lock().unwrap().clear();
|
||||
// The shape being sent was kept; keep it past the clear.
|
||||
shared_cursor_shape(sending.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// The message already kept for this shape if there is one, so every handle for it shares it.
|
||||
fn shared_cursor_shape(msg: Arc<Message>) -> Arc<Message> {
|
||||
let Some(message::Union::CursorData(cd)) = &msg.union else {
|
||||
return msg;
|
||||
};
|
||||
CURSOR_SHAPES.lock().unwrap().keep(cd, &msg)
|
||||
}
|
||||
|
||||
/// The CursorData message of a shape the service has sent, for `Misc::request_cursor_data`.
|
||||
pub fn cursor_data_message(id: u64) -> Option<Arc<Message>> {
|
||||
CURSOR_SHAPES.lock().unwrap().get(&id).cloned()
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
lazy_static::lazy_static! {
|
||||
static ref WAYLAND_CLIPBOARD_INPUT_RECORDS: Arc<Mutex<Vec<(Instant, String)>>> =
|
||||
@@ -2631,96 +2533,3 @@ lazy_static::lazy_static! {
|
||||
(ControlKey::Delete, true),
|
||||
].iter().map(|(a, b)| (a.value(), b.clone())).collect();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cursor_shape_tests {
|
||||
use super::*;
|
||||
|
||||
fn shape(id: u64) -> Arc<Message> {
|
||||
let mut msg = Message::new();
|
||||
msg.set_cursor_data(CursorData {
|
||||
id,
|
||||
..Default::default()
|
||||
});
|
||||
Arc::new(msg)
|
||||
}
|
||||
|
||||
// One test, since the shapes are kept process-wide.
|
||||
#[test]
|
||||
fn a_shape_is_kept_once_and_can_be_asked_for_again() {
|
||||
let first = shared_cursor_shape(shape(u64::MAX - 1));
|
||||
let again = shared_cursor_shape(shape(u64::MAX - 1));
|
||||
assert!(Arc::ptr_eq(&first, &again), "a second handle shares it");
|
||||
let asked = cursor_data_message(u64::MAX - 1).expect("a sent shape is kept");
|
||||
assert!(Arc::ptr_eq(&asked, &first));
|
||||
assert!(cursor_data_message(u64::MAX - 2).is_none());
|
||||
|
||||
let raw = |handle| CursorData {
|
||||
id: handle,
|
||||
width: 4,
|
||||
height: 4,
|
||||
colors: vec![9u8; 4 * 4 * 4].into(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut compressed = 0;
|
||||
let mut compress = |rgba: &[u8]| {
|
||||
compressed += 1;
|
||||
hbb_common::compress::compress(rgba)
|
||||
};
|
||||
let shown = cursor_shape_message(raw(1), &mut compress);
|
||||
let again = cursor_shape_message(raw(2), &mut compress);
|
||||
assert!(Arc::ptr_eq(&shown, &again), "a new handle, the same shape");
|
||||
assert_eq!(compressed, 1, "a shape sent before is not compressed again");
|
||||
|
||||
let sending = shared_cursor_shape(shape(u64::MAX - 3));
|
||||
let mut few = HashMap::from([(1, shown.clone())]);
|
||||
limit_cursor_handles(&mut few, &sending);
|
||||
assert_eq!(few.len(), 1, "below the ceiling nothing goes");
|
||||
|
||||
let mut handles: HashMap<u64, Arc<Message>> = (0..CURSOR_HANDLES_MAX as u64)
|
||||
.map(|handle| (handle, shown.clone()))
|
||||
.collect();
|
||||
limit_cursor_handles(&mut handles, &sending);
|
||||
assert!(
|
||||
handles.is_empty(),
|
||||
"past the ceiling the handles start over"
|
||||
);
|
||||
let Some(message::Union::CursorData(cd)) = &shown.union else {
|
||||
panic!("a cursor shape");
|
||||
};
|
||||
assert!(
|
||||
cursor_data_message(cd.id).is_none(),
|
||||
"and the shapes with them"
|
||||
);
|
||||
assert!(
|
||||
cursor_data_message(u64::MAX - 3).is_some(),
|
||||
"but the shape being sent is kept"
|
||||
);
|
||||
|
||||
let big = |id| {
|
||||
let mut msg = Message::new();
|
||||
msg.set_cursor_data(CursorData {
|
||||
id,
|
||||
colors: vec![0u8; CURSOR_SHAPES_BYTES_MAX / 2 + 1].into(),
|
||||
..Default::default()
|
||||
});
|
||||
Arc::new(msg)
|
||||
};
|
||||
shared_cursor_shape(big(u64::MAX - 4));
|
||||
let sending = shared_cursor_shape(big(u64::MAX - 5));
|
||||
let mut few = HashMap::from([(1, shown.clone())]);
|
||||
limit_cursor_handles(&mut few, &sending);
|
||||
assert!(
|
||||
few.is_empty(),
|
||||
"past the byte ceiling the handles start over"
|
||||
);
|
||||
assert!(cursor_data_message(u64::MAX - 4).is_none());
|
||||
assert!(cursor_data_message(u64::MAX - 5).is_some());
|
||||
|
||||
super::super::service::Reset::reset(&mut StateCursor::default());
|
||||
assert!(
|
||||
cursor_data_message(u64::MAX - 1).is_none(),
|
||||
"a reset forgets them"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -72,10 +72,6 @@ pub struct Session<T: InvokeUiSession> {
|
||||
pub reconnect_count: Arc<AtomicUsize>,
|
||||
pub last_audit_note: Arc<Mutex<String>>,
|
||||
pub audit_guid: Arc<Mutex<String>>,
|
||||
// Every cursor shape as the peer sent it, compressed, by the id the UI knows it by. The
|
||||
// peer sends a shape once, and a window asks for it whenever it has to draw it again.
|
||||
#[cfg(feature = "flutter")]
|
||||
pub cursor_shapes: Arc<RwLock<HashMap<u64, CursorData>>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
Reference in New Issue
Block a user