Compare commits
50
Commits
@@ -874,7 +874,7 @@ jobs:
|
|||||||
- name: Test cursor sizing
|
- name: Test cursor sizing
|
||||||
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
|
if: ${{ !inputs.upload-artifact && matrix.job.arch == 'aarch64' }}
|
||||||
working-directory: flutter
|
working-directory: flutter
|
||||||
run: flutter test --timeout 60s test/cursor_size_test.dart
|
run: flutter test --timeout 60s test/cursor_size_test.dart test/cursor_replay_test.dart test/cursor_default_test.dart
|
||||||
|
|
||||||
- name: Setup vcpkg with Github Actions binary cache
|
- name: Setup vcpkg with Github Actions binary cache
|
||||||
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
uses: lukka/run-vcpkg@b1a0dd252f06b9e25b3c022a9a03bd7a427fb6a2 # v11
|
||||||
|
|||||||
Generated
+7
@@ -7196,6 +7196,7 @@ dependencies = [
|
|||||||
"wol-rs",
|
"wol-rs",
|
||||||
"x11-clipboard 0.8.1",
|
"x11-clipboard 0.8.1",
|
||||||
"x11rb 0.12.0",
|
"x11rb 0.12.0",
|
||||||
|
"xxhash-rust",
|
||||||
"zstd",
|
"zstd",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -10806,6 +10807,12 @@ version = "0.2.1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
|
checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "xxhash-rust"
|
||||||
|
version = "0.8.18"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "aee1b19627c7c60102ab80d3a9cbe18de90bfe03bfa6c3715447681f0e8c8af6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "yasna"
|
name = "yasna"
|
||||||
version = "0.5.2"
|
version = "0.5.2"
|
||||||
|
|||||||
@@ -63,6 +63,7 @@ lazy_static = "1.4"
|
|||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
repng = "0.2"
|
repng = "0.2"
|
||||||
zstd = "0.13"
|
zstd = "0.13"
|
||||||
|
xxhash-rust = { version = "0.8", features = ["xxh3"] }
|
||||||
parity-tokio-ipc = { git = "https://github.com/rustdesk-org/parity-tokio-ipc" }
|
parity-tokio-ipc = { git = "https://github.com/rustdesk-org/parity-tokio-ipc" }
|
||||||
magnum-opus = { git = "https://github.com/rustdesk-org/magnum-opus" }
|
magnum-opus = { git = "https://github.com/rustdesk-org/magnum-opus" }
|
||||||
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
|
dasp = { version = "0.11", features = ["signal", "interpolate-linear", "interpolate"], optional = true }
|
||||||
|
|||||||
+277
-50
@@ -58,7 +58,8 @@ const _restartReconnectSilentDelaySecs = 5;
|
|||||||
class CachedPeerData {
|
class CachedPeerData {
|
||||||
Map<String, dynamic> updatePrivacyMode = {};
|
Map<String, dynamic> updatePrivacyMode = {};
|
||||||
Map<String, dynamic> peerInfo = {};
|
Map<String, dynamic> peerInfo = {};
|
||||||
List<Map<String, dynamic>> cursorDataList = [];
|
// No shapes: the core keeps them for the session, and the window a tab moves to asks it
|
||||||
|
// for the one in use.
|
||||||
Map<String, dynamic> lastCursorId = {};
|
Map<String, dynamic> lastCursorId = {};
|
||||||
Map<String, bool> permissions = {};
|
Map<String, bool> permissions = {};
|
||||||
|
|
||||||
@@ -73,7 +74,6 @@ class CachedPeerData {
|
|||||||
return jsonEncode({
|
return jsonEncode({
|
||||||
'updatePrivacyMode': updatePrivacyMode,
|
'updatePrivacyMode': updatePrivacyMode,
|
||||||
'peerInfo': peerInfo,
|
'peerInfo': peerInfo,
|
||||||
'cursorDataList': cursorDataList,
|
|
||||||
'lastCursorId': lastCursorId,
|
'lastCursorId': lastCursorId,
|
||||||
'permissions': permissions,
|
'permissions': permissions,
|
||||||
'secure': secure,
|
'secure': secure,
|
||||||
@@ -88,9 +88,6 @@ class CachedPeerData {
|
|||||||
final data = CachedPeerData();
|
final data = CachedPeerData();
|
||||||
data.updatePrivacyMode = map['updatePrivacyMode'];
|
data.updatePrivacyMode = map['updatePrivacyMode'];
|
||||||
data.peerInfo = map['peerInfo'];
|
data.peerInfo = map['peerInfo'];
|
||||||
for (final cursorData in map['cursorDataList']) {
|
|
||||||
data.cursorDataList.add(cursorData);
|
|
||||||
}
|
|
||||||
data.lastCursorId = map['lastCursorId'];
|
data.lastCursorId = map['lastCursorId'];
|
||||||
map['permissions'].forEach((key, value) {
|
map['permissions'].forEach((key, value) {
|
||||||
data.permissions[key] = value;
|
data.permissions[key] = value;
|
||||||
@@ -323,10 +320,6 @@ class FfiModel with ChangeNotifier {
|
|||||||
updatePrivacyMode(data.updatePrivacyMode, sessionId, peerId);
|
updatePrivacyMode(data.updatePrivacyMode, sessionId, peerId);
|
||||||
setConnectionType(peerId, data.secure, data.direct, data.streamType);
|
setConnectionType(peerId, data.secure, data.direct, data.streamType);
|
||||||
await handlePeerInfo(data.peerInfo, peerId, true);
|
await handlePeerInfo(data.peerInfo, peerId, true);
|
||||||
for (final element in data.cursorDataList) {
|
|
||||||
updateLastCursorId(element);
|
|
||||||
await handleCursorData(element);
|
|
||||||
}
|
|
||||||
if (data.lastCursorId.isNotEmpty) {
|
if (data.lastCursorId.isNotEmpty) {
|
||||||
updateLastCursorId(data.lastCursorId);
|
updateLastCursorId(data.lastCursorId);
|
||||||
handleCursorId(data.lastCursorId);
|
handleCursorId(data.lastCursorId);
|
||||||
@@ -356,9 +349,6 @@ class FfiModel with ChangeNotifier {
|
|||||||
} else if (name == 'switch_display') {
|
} else if (name == 'switch_display') {
|
||||||
// switch display is kept for backward compatibility
|
// switch display is kept for backward compatibility
|
||||||
handleSwitchDisplay(evt, sessionId, peerId);
|
handleSwitchDisplay(evt, sessionId, peerId);
|
||||||
} else if (name == 'cursor_data') {
|
|
||||||
updateLastCursorId(evt);
|
|
||||||
await handleCursorData(evt);
|
|
||||||
} else if (name == 'cursor_id') {
|
} else if (name == 'cursor_id') {
|
||||||
updateLastCursorId(evt);
|
updateLastCursorId(evt);
|
||||||
handleCursorId(evt);
|
handleCursorId(evt);
|
||||||
@@ -1662,9 +1652,14 @@ class FfiModel with ChangeNotifier {
|
|||||||
parent.target?.cursorModel.updateCursorId(evt);
|
parent.target?.cursorModel.updateCursorId(evt);
|
||||||
}
|
}
|
||||||
|
|
||||||
handleCursorData(Map<String, dynamic> evt) async {
|
/// A shape arriving is the shape in use, as a cursor_id is.
|
||||||
cachedPeerData.cursorDataList.add(evt);
|
handleCursorData(String id, int hotx, int hoty, int width, int height,
|
||||||
await parent.target?.cursorModel.updateCursorData(evt);
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Handle the peer info synchronization event based on [evt].
|
/// Handle the peer info synchronization event based on [evt].
|
||||||
@@ -2858,12 +2853,13 @@ class CanvasModel with ChangeNotifier {
|
|||||||
|
|
||||||
// data for cursor
|
// data for cursor
|
||||||
class CursorData {
|
class CursorData {
|
||||||
// At most 4 MiB of RGBA, including Linux's square cursor padding.
|
// At most 1 MiB of RGBA, including Linux's square cursor padding: twice the largest
|
||||||
static const _maxRasterSize = 1024;
|
// accessibility cursor, beyond which a cursor is shown smaller rather than larger.
|
||||||
|
static const _maxRasterSize = 512;
|
||||||
|
|
||||||
final String peerId;
|
final String peerId;
|
||||||
final String id;
|
final String id;
|
||||||
final img2.Image image;
|
img2.Image? _image;
|
||||||
double scale;
|
double scale;
|
||||||
Uint8List? data;
|
Uint8List? data;
|
||||||
final double hotxOrigin;
|
final double hotxOrigin;
|
||||||
@@ -2879,17 +2875,28 @@ class CursorData {
|
|||||||
int get rasterWidth => _rasterWidth;
|
int get rasterWidth => _rasterWidth;
|
||||||
int get rasterHeight => _rasterHeight;
|
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({
|
CursorData({
|
||||||
required this.peerId,
|
required this.peerId,
|
||||||
required this.id,
|
required this.id,
|
||||||
required this.image,
|
required img2.Image image,
|
||||||
required this.scale,
|
required this.scale,
|
||||||
required this.data,
|
required this.data,
|
||||||
required this.hotxOrigin,
|
required this.hotxOrigin,
|
||||||
required this.hotyOrigin,
|
required this.hotyOrigin,
|
||||||
required this.width,
|
required this.width,
|
||||||
required this.height,
|
required this.height,
|
||||||
}) : _rasterWidth = (width * scale).ceil(),
|
}) : _image = image,
|
||||||
|
_rasterWidth = (width * scale).ceil(),
|
||||||
_rasterHeight = (height * scale).ceil(),
|
_rasterHeight = (height * scale).ceil(),
|
||||||
hotx = hotxOrigin * scale,
|
hotx = hotxOrigin * scale,
|
||||||
hoty = hotyOrigin * scale;
|
hoty = hotyOrigin * scale;
|
||||||
@@ -2921,6 +2928,13 @@ class CursorData {
|
|||||||
|
|
||||||
final targetWidth = (width * scale).ceil();
|
final targetWidth = (width * scale).ceil();
|
||||||
final targetHeight = (height * 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 (_rasterWidth != targetWidth || _rasterHeight != targetHeight) {
|
||||||
if (isWindows) {
|
if (isWindows) {
|
||||||
data = img2
|
data = img2
|
||||||
@@ -2991,7 +3005,9 @@ class CursorData {
|
|||||||
|
|
||||||
String updateGetKey(double scale) {
|
String updateGetKey(double scale) {
|
||||||
scale = _checkUpdateScale(scale);
|
scale = _checkUpdateScale(scale);
|
||||||
return '${peerId}_${id}_${_doubleToInt(width * scale)}_${_doubleToInt(height * scale)}_${rasterWidth}_$rasterHeight';
|
// 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()}';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3162,7 +3178,16 @@ class CursorModel with ChangeNotifier {
|
|||||||
|
|
||||||
get lastIsBlocked => _lastIsBlocked;
|
get lastIsBlocked => _lastIsBlocked;
|
||||||
|
|
||||||
ui.Image? get image => _image;
|
/// 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;
|
||||||
|
}
|
||||||
|
|
||||||
CursorData? get cache => _cache;
|
CursorData? get cache => _cache;
|
||||||
|
|
||||||
double get x => _x - _displayOriginX;
|
double get x => _x - _displayOriginX;
|
||||||
@@ -3175,7 +3200,10 @@ class CursorModel with ChangeNotifier {
|
|||||||
double get hotx => _hotx;
|
double get hotx => _hotx;
|
||||||
double get hoty => _hoty;
|
double get hoty => _hoty;
|
||||||
|
|
||||||
set id(String id) => _id = id;
|
set id(String id) {
|
||||||
|
if (_id != id) _unavailable = null;
|
||||||
|
_id = id;
|
||||||
|
}
|
||||||
|
|
||||||
bool get isPeerControlProtected =>
|
bool get isPeerControlProtected =>
|
||||||
DateTime.now().difference(_lastPeerMouse).inMilliseconds <
|
DateTime.now().difference(_lastPeerMouse).inMilliseconds <
|
||||||
@@ -3190,7 +3218,12 @@ class CursorModel with ChangeNotifier {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
CursorModel(this.parent);
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
Set<String> get cachedKeys => _cacheKeys;
|
Set<String> get cachedKeys => _cacheKeys;
|
||||||
addKey(String key) => _cacheKeys.add(key);
|
addKey(String key) => _cacheKeys.add(key);
|
||||||
@@ -3489,30 +3522,44 @@ class CursorModel with ChangeNotifier {
|
|||||||
_images.clear();
|
_images.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
updateCursorData(Map<String, dynamic> evt) async {
|
/// Its image is kept with the ones used last, see [_imageLimit]; a shape that does not decode
|
||||||
final id = evt['id'];
|
/// is marked as one the core cannot give.
|
||||||
final hotx = double.parse(evt['hotx']);
|
Future<void> updateCursorData(String id, int hotxInt, int hotyInt, int width,
|
||||||
final hoty = double.parse(evt['hoty']);
|
int height, Uint8List rgba) async {
|
||||||
final width = int.parse(evt['width']);
|
final generation = _generation;
|
||||||
final height = int.parse(evt['height']);
|
if (_unavailable == id) _unavailable = null;
|
||||||
List<dynamic> colors = json.decode(evt['colors']);
|
final hotx = hotxInt.toDouble();
|
||||||
final rgba = Uint8List.fromList(colors.map((s) => s as int).toList());
|
final hoty = hotyInt.toDouble();
|
||||||
final image = await img.decodeImageFromPixels(
|
final image = await img.decodeImageFromPixels(
|
||||||
rgba, width, height, ui.PixelFormat.rgba8888);
|
rgba, width, height, ui.PixelFormat.rgba8888);
|
||||||
if (image == null) {
|
if (image == null) {
|
||||||
|
// It did not decode; painting must not ask for it on every frame.
|
||||||
|
_markUnavailable(generation, id);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (await _updateCache(rgba, image, id, hotx, hoty, width, height)) {
|
if (!await _updateCache(
|
||||||
_images[id]?.item1.dispose();
|
generation, rgba, image, id, hotx, hoty, width, height)) {
|
||||||
_images[id] = Tuple3(image, hotx, hoty);
|
// 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();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Update last cursor data.
|
// Update last cursor data.
|
||||||
// Do not use the previous `image` and `id`, because `_id` may be changed.
|
// Do not use the previous `image` and `id`, because `_id` may be changed.
|
||||||
_updateCurData();
|
_updateCurData();
|
||||||
|
final cache = _cacheMap[id];
|
||||||
|
if (id != _id && cache != null) _switchedAway(cache);
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<bool> _updateCache(
|
Future<bool> _updateCache(
|
||||||
|
int generation,
|
||||||
Uint8List rgba,
|
Uint8List rgba,
|
||||||
ui.Image image,
|
ui.Image image,
|
||||||
String id,
|
String id,
|
||||||
@@ -3523,7 +3570,11 @@ class CursorModel with ChangeNotifier {
|
|||||||
) async {
|
) async {
|
||||||
Uint8List? data;
|
Uint8List? data;
|
||||||
img2.Image imgOrigin = img2.Image.fromBytes(
|
img2.Image imgOrigin = img2.Image.fromBytes(
|
||||||
width: w, height: h, bytes: rgba.buffer, order: img2.ChannelOrder.rgba);
|
width: w,
|
||||||
|
height: h,
|
||||||
|
bytes: rgba.buffer,
|
||||||
|
bytesOffset: rgba.offsetInBytes,
|
||||||
|
order: img2.ChannelOrder.rgba);
|
||||||
if (isWindows) {
|
if (isWindows) {
|
||||||
data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
|
data = imgOrigin.getBytes(order: img2.ChannelOrder.bgra);
|
||||||
} else {
|
} else {
|
||||||
@@ -3556,34 +3607,200 @@ class CursorModel with ChangeNotifier {
|
|||||||
width: w,
|
width: w,
|
||||||
height: h,
|
height: h,
|
||||||
);
|
);
|
||||||
|
if (generation != _generation) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
_cacheMap[id] = cache;
|
_cacheMap[id] = cache;
|
||||||
return true;
|
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() {
|
bool _updateCurData() {
|
||||||
_cache = _cacheMap[_id];
|
final previous = _cache;
|
||||||
final tmp = _images[_id];
|
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);
|
||||||
if (tmp != null) {
|
if (tmp != null) {
|
||||||
|
_images[_id] = tmp;
|
||||||
_image = tmp.item1;
|
_image = tmp.item1;
|
||||||
_hotx = tmp.item2;
|
_hotx = tmp.item2;
|
||||||
_hoty = tmp.item3;
|
_hoty = tmp.item3;
|
||||||
try {
|
} else if (_unavailable == _id) {
|
||||||
// may throw exception, because the listener maybe already dispose
|
_image = null;
|
||||||
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) {
|
updateCursorId(Map<String, dynamic> evt) {
|
||||||
if (!_updateCurData()) {
|
if (!_updateCurData()) {
|
||||||
debugPrint(
|
restorePixels(_id);
|
||||||
'WARNING: updateCursorId $_id, cache is ${_cache == null ? "null" : "not null"}. without notifyListeners()');
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3636,6 +3853,10 @@ class CursorModel with ChangeNotifier {
|
|||||||
_clearCache();
|
_clearCache();
|
||||||
_cache = null;
|
_cache = null;
|
||||||
_cacheMap.clear();
|
_cacheMap.clear();
|
||||||
|
_nativeIds.clear();
|
||||||
|
_awaitingNative.clear();
|
||||||
|
_unavailable = null;
|
||||||
|
_generation++;
|
||||||
}
|
}
|
||||||
|
|
||||||
_clearCache() {
|
_clearCache() {
|
||||||
@@ -3644,6 +3865,8 @@ class CursorModel with ChangeNotifier {
|
|||||||
debugPrint("deleting cursor with key $k");
|
debugPrint("deleting cursor with key $k");
|
||||||
deleteCustomCursor(k);
|
deleteCustomCursor(k);
|
||||||
}
|
}
|
||||||
|
_cacheKeys.clear();
|
||||||
|
shownKey = null;
|
||||||
resetSystemCursor();
|
resetSystemCursor();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3983,6 +4206,7 @@ class FFI {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isWeb) {
|
if (isWeb) {
|
||||||
|
platformFFI.setCursorDataCallback(ffiModel.handleCursorData);
|
||||||
platformFFI.setRgbaCallback((int display, Uint8List data) {
|
platformFFI.setRgbaCallback((int display, Uint8List data) {
|
||||||
onEvent2UIRgba();
|
onEvent2UIRgba();
|
||||||
imageModel.onRgba(display, data);
|
imageModel.onRgba(display, data);
|
||||||
@@ -4065,6 +4289,9 @@ class FFI {
|
|||||||
} else {
|
} else {
|
||||||
platformFFI.nextRgba(sessionId, display);
|
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) {
|
} else if (message is EventToUI_Texture) {
|
||||||
final display = message.field0;
|
final display = message.field0;
|
||||||
final gpuTexture = message.field1;
|
final gpuTexture = message.field1;
|
||||||
|
|||||||
@@ -285,6 +285,10 @@ class PlatformFFI {
|
|||||||
|
|
||||||
void setRgbaCallback(void Function(int, Uint8List) fun) async {}
|
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
|
// web only, decoded WebCodecs frames arriving as ready-made images
|
||||||
void setVideoFrameCallback(
|
void setVideoFrameCallback(
|
||||||
Future<void> Function(int, ui.Image, bool Function()) fun) {}
|
Future<void> Function(int, ui.Image, bool Function()) fun) {}
|
||||||
|
|||||||
@@ -189,6 +189,17 @@ 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;
|
late final WebVideoFrameQueue<JSObject, ui.Image> _videoFrameQueue;
|
||||||
|
|
||||||
// Zero-readback video path: the JS decoder hands decoded VideoFrames here
|
// Zero-readback video path: the JS decoder hands decoded VideoFrames here
|
||||||
|
|||||||
@@ -16,14 +16,15 @@ resetSystemCursor() {}
|
|||||||
MouseCursor buildCursorOfCache(
|
MouseCursor buildCursorOfCache(
|
||||||
CursorModel cursor, double scale, CursorData? cache) {
|
CursorModel cursor, double scale, CursorData? cache) {
|
||||||
if (cache == null) {
|
if (cache == null) {
|
||||||
return MouseCursor.defer;
|
return _shownCursor(cursor);
|
||||||
} else {
|
} else {
|
||||||
final key = cache.updateGetKey(scale);
|
final key = cursor.nativeKey(cache, scale);
|
||||||
if (!cursor.cachedKeys.contains(key)) {
|
if (!cursor.cachedKeys.contains(key)) {
|
||||||
// data should be checked here, because it may be changed after `updateGetKey()`
|
// data should be checked here, because it may be changed after `updateGetKey()`
|
||||||
final data = cache.data;
|
final data = cache.data;
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
return MouseCursor.defer;
|
cursor.restorePixels(cache.id);
|
||||||
|
return _shownCursor(cursor);
|
||||||
}
|
}
|
||||||
// Square canvases avoid clipping or stray edge pixels on Linux.
|
// Square canvases avoid clipping or stray edge pixels on Linux.
|
||||||
final width = isLinux && cache.rasterWidth < cache.rasterHeight
|
final width = isLinux && cache.rasterWidth < cache.rasterHeight
|
||||||
@@ -48,11 +49,21 @@ MouseCursor buildCursorOfCache(
|
|||||||
..hotX = cache.hotx
|
..hotX = cache.hotx
|
||||||
..hotY = cache.hoty);
|
..hotY = cache.hoty);
|
||||||
cursor.addKey(key);
|
cursor.addKey(key);
|
||||||
|
cursor.registered(cache, key);
|
||||||
}
|
}
|
||||||
|
cursor.shown(cache, key);
|
||||||
return FlutterCustomMemoryImageCursor(key: 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) {
|
Uint8List _padCursor(Uint8List data, int size) {
|
||||||
final bitmap = img.decodePng(data);
|
final bitmap = img.decodePng(data);
|
||||||
if (bitmap == null) {
|
if (bitmap == null) {
|
||||||
|
|||||||
@@ -26,6 +26,14 @@ sealed class EventToUI {
|
|||||||
int field0,
|
int field0,
|
||||||
bool field1,
|
bool field1,
|
||||||
) = EventToUI_Texture;
|
) = 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 {
|
class EventToUI_Event implements EventToUI {
|
||||||
@@ -50,7 +58,60 @@ class EventToUI_Texture implements EventToUI {
|
|||||||
bool get field1 => f1;
|
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 {
|
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}) {
|
Future<void> stopGlobalEventStream({required String appType, dynamic hint}) {
|
||||||
throw UnimplementedError("stopGlobalEventStream");
|
throw UnimplementedError("stopGlobalEventStream");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -102,14 +102,15 @@ resetSystemCursor() => CursorManager.instance.resetSystemCursor();
|
|||||||
MouseCursor buildCursorOfCache(
|
MouseCursor buildCursorOfCache(
|
||||||
model.CursorModel cursor, double scale, model.CursorData? cache) {
|
model.CursorModel cursor, double scale, model.CursorData? cache) {
|
||||||
if (cache == null) {
|
if (cache == null) {
|
||||||
return MouseCursor.defer;
|
return _shownCursor(cursor);
|
||||||
} else {
|
} else {
|
||||||
final key = cache.updateGetKey(scale);
|
final key = cursor.nativeKey(cache, scale);
|
||||||
if (!cursor.cachedKeys.contains(key)) {
|
if (!cursor.cachedKeys.contains(key)) {
|
||||||
// data should be checked here, because it may be changed after `updateGetKey()`
|
// data should be checked here, because it may be changed after `updateGetKey()`
|
||||||
final data = cache.data;
|
final data = cache.data;
|
||||||
if (data == null) {
|
if (data == null) {
|
||||||
return MouseCursor.defer;
|
cursor.restorePixels(cache.id);
|
||||||
|
return _shownCursor(cursor);
|
||||||
}
|
}
|
||||||
debugPrint(
|
debugPrint(
|
||||||
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
|
"Register custom cursor with key $key (${cache.hotx},${cache.hoty})");
|
||||||
@@ -121,7 +122,17 @@ MouseCursor buildCursorOfCache(
|
|||||||
hotX: cache.hotx,
|
hotX: cache.hotx,
|
||||||
hotY: cache.hoty));
|
hotY: cache.hoty));
|
||||||
cursor.addKey(key);
|
cursor.addKey(key);
|
||||||
|
cursor.registered(cache, key);
|
||||||
}
|
}
|
||||||
|
cursor.shown(cache, key);
|
||||||
return FlutterCustomMemoryImageCursor(key: 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);
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,66 @@
|
|||||||
|
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();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,683 @@
|
|||||||
|
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,4 +1,3 @@
|
|||||||
import 'dart:convert';
|
|
||||||
import 'dart:io';
|
import 'dart:io';
|
||||||
import 'dart:ui' as ui;
|
import 'dart:ui' as ui;
|
||||||
|
|
||||||
@@ -79,6 +78,8 @@ class _FFI extends Fake implements FFI {
|
|||||||
final ffiModel = _Peer();
|
final ffiModel = _Peer();
|
||||||
@override
|
@override
|
||||||
final inputModel = _Input();
|
final inputModel = _Input();
|
||||||
|
@override
|
||||||
|
var id = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
class _Cursor extends CursorModel {
|
class _Cursor extends CursorModel {
|
||||||
@@ -111,7 +112,7 @@ void main() {
|
|||||||
((1, 64), 0.25, (1, 16)),
|
((1, 64), 0.25, (1, 16)),
|
||||||
((8, 8), 0.5, (12, 12)),
|
((8, 8), 0.5, (12, 12)),
|
||||||
((4, 64), 1.0, (4, 64)),
|
((4, 64), 1.0, (4, 64)),
|
||||||
((1, 512), 10.0, (2, 1024)),
|
((1, 512), 10.0, (1, 512)),
|
||||||
]) {
|
]) {
|
||||||
test('native cursor size $scenario',
|
test('native cursor size $scenario',
|
||||||
() => _checkSize(scenario, registrations));
|
() => _checkSize(scenario, registrations));
|
||||||
@@ -181,15 +182,14 @@ Future<void> _checkWindowsPeerAlpha(
|
|||||||
addTearDown(() => _dispose(cursor));
|
addTearDown(() => _dispose(cursor));
|
||||||
addTearDown(cursor.disposeImages);
|
addTearDown(cursor.disposeImages);
|
||||||
addTearDown(ffi.canvasModel.dispose);
|
addTearDown(ffi.canvasModel.dispose);
|
||||||
await cursor.updateCursorData({
|
await cursor.updateCursorData(
|
||||||
'id': 'alpha',
|
'alpha',
|
||||||
'hotx': '0',
|
0,
|
||||||
'hoty': '0',
|
0,
|
||||||
'width': '$sourceSize',
|
sourceSize,
|
||||||
'height': '$sourceSize',
|
sourceSize,
|
||||||
'colors': jsonEncode(List.generate(sourceSize * sourceSize * channels,
|
Uint8List.fromList(List.generate(sourceSize * sourceSize * channels,
|
||||||
(i) => pattern.$1[i % pattern.$1.length])),
|
(i) => pattern.$1[i % pattern.$1.length])));
|
||||||
});
|
|
||||||
buildCursorOfCache(cursor, 1.0 / dpr, cursor.cache);
|
buildCursorOfCache(cursor, 1.0 / dpr, cursor.cache);
|
||||||
await Future<void>.delayed(Duration.zero);
|
await Future<void>.delayed(Duration.zero);
|
||||||
final args = registrations.single;
|
final args = registrations.single;
|
||||||
@@ -259,7 +259,7 @@ Future<void> _checkRasterTransitions(
|
|||||||
]) {
|
]) {
|
||||||
buildCursorOfCache(cursor, scale, cursor.cache);
|
buildCursorOfCache(cursor, scale, cursor.cache);
|
||||||
await Future<void>.delayed(Duration.zero);
|
await Future<void>.delayed(Duration.zero);
|
||||||
final key = cursor.cache.updateGetKey(scale);
|
final key = cursor.nativeKey(cursor.cache, scale);
|
||||||
_expectSize(
|
_expectSize(
|
||||||
registrations.singleWhere((args) => args['name'] == key), expected);
|
registrations.singleWhere((args) => args['name'] == key), expected);
|
||||||
}
|
}
|
||||||
@@ -268,7 +268,7 @@ Future<void> _checkRasterTransitions(
|
|||||||
|
|
||||||
Future<void> _checkResizeLimits(
|
Future<void> _checkResizeLimits(
|
||||||
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
|
(int, int) size, List<Map<dynamic, dynamic>> registrations) async {
|
||||||
const maxSide = 1024;
|
const maxSide = 512;
|
||||||
const sourceLongEdge = 30;
|
const sourceLongEdge = 30;
|
||||||
const validScale = maxSide / sourceLongEdge;
|
const validScale = maxSide / sourceLongEdge;
|
||||||
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
|
final ffi = _FFI(_Canvas(kRemoteViewStyleAdaptive));
|
||||||
@@ -361,7 +361,7 @@ Future<void> _checkView(WidgetTester tester, (String, bool) mode,
|
|||||||
mode.$1 != kRemoteViewStyleOriginal
|
mode.$1 != kRemoteViewStyleOriginal
|
||||||
? (sourceSize * (Platform.isWindows ? dpr : 1.0)).ceil()
|
? (sourceSize * (Platform.isWindows ? dpr : 1.0)).ceil()
|
||||||
: (size * scale * (Platform.isWindows ? dpr : 1.0)).ceil();
|
: (size * scale * (Platform.isWindows ? dpr : 1.0)).ceil();
|
||||||
final key = cursor.cache.updateGetKey(cursor.cache.scale);
|
final key = cursor.nativeKey(cursor.cache, cursor.cache.scale);
|
||||||
_expectSize(registrations.singleWhere((v) => v['name'] == key), (w, w));
|
_expectSize(registrations.singleWhere((v) => v['name'] == key), (w, w));
|
||||||
}
|
}
|
||||||
await tester.pumpWidget(const SizedBox.shrink());
|
await tester.pumpWidget(const SizedBox.shrink());
|
||||||
|
|||||||
@@ -310,7 +310,9 @@ message KeyEvent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
message CursorData {
|
message CursorData {
|
||||||
uint64 id = 1;
|
// 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];
|
||||||
sint32 hotx = 2;
|
sint32 hotx = 2;
|
||||||
sint32 hoty = 3;
|
sint32 hoty = 3;
|
||||||
int32 width = 4;
|
int32 width = 4;
|
||||||
@@ -859,6 +861,12 @@ message Misc {
|
|||||||
DisplayResolution change_display_resolution = 36;
|
DisplayResolution change_display_resolution = 36;
|
||||||
MessageQuery message_query = 37;
|
MessageQuery message_query = 37;
|
||||||
int32 follow_current_display = 38;
|
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1002,7 +1010,7 @@ message Message {
|
|||||||
AudioFrame audio_frame = 11;
|
AudioFrame audio_frame = 11;
|
||||||
CursorData cursor_data = 12;
|
CursorData cursor_data = 12;
|
||||||
CursorPosition cursor_position = 13;
|
CursorPosition cursor_position = 13;
|
||||||
uint64 cursor_id = 14;
|
uint64 cursor_id = 14 [jstype = JS_STRING]; // as CursorData.id
|
||||||
KeyEvent key_event = 15;
|
KeyEvent key_event = 15;
|
||||||
Clipboard clipboard = 16;
|
Clipboard clipboard = 16;
|
||||||
FileAction file_action = 17;
|
FileAction file_action = 17;
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ serde = {version="1.0", features=["derive"]}
|
|||||||
[dependencies.winapi]
|
[dependencies.winapi]
|
||||||
version = "0.3"
|
version = "0.3"
|
||||||
default-features = true
|
default-features = true
|
||||||
features = ["dxgi", "dxgi1_2", "dxgi1_5", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
|
features = ["dxgi", "dxgi1_2", "dxgi1_5", "dxgi1_6", "d3d11", "winuser", "winerror", "errhandlingapi", "libloaderapi"]
|
||||||
|
|
||||||
[target.'cfg(target_os = "macos")'.dependencies]
|
[target.'cfg(target_os = "macos")'.dependencies]
|
||||||
block = "0.1"
|
block = "0.1"
|
||||||
|
|||||||
@@ -0,0 +1,629 @@
|
|||||||
|
//! HDR desktop -> SDR normalization for Desktop Duplication frames.
|
||||||
|
//!
|
||||||
|
//! With HDR enabled Windows composes the desktop as linear scRGB in
|
||||||
|
//! R16G16B16A16_FLOAT, and SDR "white" sits at the user's SDR content
|
||||||
|
//! brightness (DISPLAYCONFIG_SDR_WHITE_LEVEL) rather than at 1.0. The legacy
|
||||||
|
//! DuplicateOutput converts that to BGRA8 by clipping, which is the washed-out
|
||||||
|
//! picture reported for HDR hosts. This pass divides by the SDR white level,
|
||||||
|
//! clamps, and applies the sRGB transfer, so SDR content comes out exactly as
|
||||||
|
//! it would from an SDR desktop.
|
||||||
|
//!
|
||||||
|
//! It is a normalization, not a tone map: anything brighter than SDR white
|
||||||
|
//! (HDR video, HDR games) clips to white on the SDR viewer, where the local
|
||||||
|
//! HDR display would show it brighter than white. A roll-off would have to
|
||||||
|
//! move SDR white below 1.0 to make headroom, trading the accuracy of the SDR
|
||||||
|
//! content this pass exists for, so it is deliberately not done.
|
||||||
|
//!
|
||||||
|
//! Windows 11 22H2 also composes Advanced Color SDR (WCG) desktops in FP16,
|
||||||
|
//! but there 1.0 is the display's reference white rather than 80 nits and no
|
||||||
|
//! SDR white level applies. IDXGIOutput6 tells the two apart, and for a
|
||||||
|
//! non-HDR output the pass only applies the scRGB -> sRGB transfer.
|
||||||
|
//!
|
||||||
|
//! The conversion is automatic and stays on the controlled side on purpose:
|
||||||
|
//! the controller renders through Flutter external textures, which are 8-bit
|
||||||
|
//! on every desktop platform, so there is nothing to gain from sending HDR.
|
||||||
|
//! Real HDR pass-through, if the renderer ever supports it, should follow the
|
||||||
|
//! Sunshine/Moonlight pattern instead: an `hdr` capability bit advertised by
|
||||||
|
//! the controller behind an explicit user toggle, negotiated like i444.
|
||||||
|
|
||||||
|
use super::ComPtr;
|
||||||
|
use hbb_common::log;
|
||||||
|
use std::{
|
||||||
|
io, mem, ptr,
|
||||||
|
sync::{atomic::AtomicBool, OnceLock},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use winapi::{
|
||||||
|
ctypes::c_void,
|
||||||
|
shared::{
|
||||||
|
basetsd::SIZE_T,
|
||||||
|
dxgi::{CreateDXGIFactory1, IDXGIFactory1, IID_IDXGIFactory1, DXGI_OUTPUT_DESC},
|
||||||
|
dxgi1_2::IDXGIOutput1,
|
||||||
|
dxgi1_6::{IDXGIOutput6, IID_IDXGIOutput6, DXGI_OUTPUT_DESC1},
|
||||||
|
dxgiformat::DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||||
|
dxgitype::{DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020, DXGI_SAMPLE_DESC},
|
||||||
|
minwindef::{FALSE, LPCVOID, UINT, ULONG},
|
||||||
|
ntdef::{LONG, LPCSTR, WCHAR},
|
||||||
|
winerror::S_OK,
|
||||||
|
},
|
||||||
|
um::{
|
||||||
|
d3d11::*,
|
||||||
|
d3dcommon::{ID3DBlob, ID3DInclude, D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, D3D_SHADER_MACRO},
|
||||||
|
libloaderapi::{GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32},
|
||||||
|
unknwnbase::IUnknown,
|
||||||
|
wingdi::{
|
||||||
|
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME, DISPLAYCONFIG_DEVICE_INFO_HEADER,
|
||||||
|
DISPLAYCONFIG_MODE_INFO, DISPLAYCONFIG_PATH_INFO, DISPLAYCONFIG_SOURCE_DEVICE_NAME,
|
||||||
|
DISPLAYCONFIG_TOPOLOGY_ID,
|
||||||
|
},
|
||||||
|
winnt::HRESULT,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Set once the tone-map can never work in this process (no d3dcompiler, the
|
||||||
|
/// shaders do not compile). Capturers then stop asking DXGI for float frames.
|
||||||
|
/// Device-specific failures are not recorded here; the capturer that hit one
|
||||||
|
/// re-duplicates without the tone-map on its own.
|
||||||
|
pub static UNAVAILABLE: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// Failures no capturer on this machine can recover from, as opposed to
|
||||||
|
/// device-specific ones that a recreated capturer may not hit again.
|
||||||
|
pub fn is_permanent(err: &io::Error) -> bool {
|
||||||
|
err.kind() == io::ErrorKind::Unsupported
|
||||||
|
}
|
||||||
|
|
||||||
|
const VS_SRC: &str = "\
|
||||||
|
float4 main(uint id : SV_VertexID) : SV_Position {
|
||||||
|
float2 uv = float2((id << 1) & 2, id & 2);
|
||||||
|
return float4(uv * float2(2.0, -2.0) + float2(-1.0, 1.0), 0.0, 1.0);
|
||||||
|
}";
|
||||||
|
|
||||||
|
const PS_SRC: &str = "\
|
||||||
|
Texture2D<float4> src : register(t0);
|
||||||
|
cbuffer Params : register(b0) { float inv_sdr_white; float3 pad; };
|
||||||
|
float4 main(float4 pos : SV_Position) : SV_Target {
|
||||||
|
float3 lin = saturate(src.Load(int3(pos.xy, 0)).rgb * inv_sdr_white);
|
||||||
|
float3 lo = lin * 12.92;
|
||||||
|
float3 hi = 1.055 * pow(lin, 1.0 / 2.4) - 0.055;
|
||||||
|
return float4(lerp(hi, lo, step(lin, 0.0031308)), 1.0);
|
||||||
|
}";
|
||||||
|
|
||||||
|
const OUTPUT_STATE_REFRESH: Duration = Duration::from_secs(1);
|
||||||
|
|
||||||
|
pub struct HdrToSdr {
|
||||||
|
device: ComPtr<ID3D11Device>,
|
||||||
|
context: ComPtr<ID3D11DeviceContext>,
|
||||||
|
vs: ComPtr<ID3D11VertexShader>,
|
||||||
|
ps: ComPtr<ID3D11PixelShader>,
|
||||||
|
params: ComPtr<ID3D11Buffer>,
|
||||||
|
target: ComPtr<ID3D11Texture2D>,
|
||||||
|
rtv: ComPtr<ID3D11RenderTargetView>,
|
||||||
|
srv: ComPtr<ID3D11ShaderResourceView>,
|
||||||
|
// Texture `srv` was created for. The view keeps it alive, so the address
|
||||||
|
// cannot be recycled behind our back.
|
||||||
|
srv_source: *mut ID3D11Texture2D,
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
device_name: [WCHAR; 32],
|
||||||
|
// Advanced Color state is read from `output6`, which is re-enumerated from a
|
||||||
|
// fresh factory whenever `factory` stops being current.
|
||||||
|
factory: ComPtr<IDXGIFactory1>,
|
||||||
|
output6: ComPtr<IDXGIOutput6>,
|
||||||
|
is_hdr: bool,
|
||||||
|
// DISPLAYCONFIG units (1000 == 80 nits == scRGB 1.0). `None` when it could
|
||||||
|
// not be read, in which case 80 nits is assumed until it can.
|
||||||
|
sdr_white_level: Option<u32>,
|
||||||
|
queried_at: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl HdrToSdr {
|
||||||
|
pub fn new(
|
||||||
|
device: *mut ID3D11Device,
|
||||||
|
context: *mut ID3D11DeviceContext,
|
||||||
|
output: *mut IDXGIOutput1,
|
||||||
|
device_name: &[WCHAR; 32],
|
||||||
|
) -> io::Result<Self> {
|
||||||
|
unsafe {
|
||||||
|
if device.is_null() || context.is_null() {
|
||||||
|
return Err(other("no d3d11 device"));
|
||||||
|
}
|
||||||
|
(*device).AddRef();
|
||||||
|
let device = ComPtr(device);
|
||||||
|
(*context).AddRef();
|
||||||
|
let context = ComPtr(context);
|
||||||
|
|
||||||
|
let compile = load_d3d_compile()?;
|
||||||
|
let vs_code = compile_shader(compile, VS_SRC, b"vs_4_0\0")?;
|
||||||
|
let ps_code = compile_shader(compile, PS_SRC, b"ps_4_0\0")?;
|
||||||
|
let mut vs = ptr::null_mut();
|
||||||
|
check(
|
||||||
|
(*device.0).CreateVertexShader(
|
||||||
|
(*vs_code.0).GetBufferPointer(),
|
||||||
|
(*vs_code.0).GetBufferSize(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
&mut vs,
|
||||||
|
),
|
||||||
|
"CreateVertexShader",
|
||||||
|
)?;
|
||||||
|
let vs = ComPtr(vs);
|
||||||
|
let mut ps = ptr::null_mut();
|
||||||
|
check(
|
||||||
|
(*device.0).CreatePixelShader(
|
||||||
|
(*ps_code.0).GetBufferPointer(),
|
||||||
|
(*ps_code.0).GetBufferSize(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
&mut ps,
|
||||||
|
),
|
||||||
|
"CreatePixelShader",
|
||||||
|
)?;
|
||||||
|
let ps = ComPtr(ps);
|
||||||
|
|
||||||
|
// Not found leaves the factory null, so the first refresh enumerates
|
||||||
|
// again instead of trusting the capturer's possibly stale output.
|
||||||
|
let (factory, mut output6) = enumerate_output6(device_name);
|
||||||
|
if output6.is_null() {
|
||||||
|
output6 = query_output6(output as *mut IUnknown);
|
||||||
|
}
|
||||||
|
// Float frames are only requested where IDXGIOutput6 exists, so an
|
||||||
|
// unreadable description still comes from an HDR-capable stack.
|
||||||
|
let is_hdr = output_is_hdr(output6.0).unwrap_or(true);
|
||||||
|
let sdr_white_level = if is_hdr {
|
||||||
|
query_sdr_white_level(device_name)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
if is_hdr && sdr_white_level.is_none() {
|
||||||
|
log::warn!(
|
||||||
|
"HDR output but the SDR white level cannot be read (needs Windows 10 1709+), \
|
||||||
|
assuming 80 nits until it can"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let init = params_data(sdr_white_level);
|
||||||
|
let desc = D3D11_BUFFER_DESC {
|
||||||
|
ByteWidth: mem::size_of_val(&init) as _,
|
||||||
|
Usage: D3D11_USAGE_DEFAULT,
|
||||||
|
BindFlags: D3D11_BIND_CONSTANT_BUFFER,
|
||||||
|
CPUAccessFlags: 0,
|
||||||
|
MiscFlags: 0,
|
||||||
|
StructureByteStride: 0,
|
||||||
|
};
|
||||||
|
let data = D3D11_SUBRESOURCE_DATA {
|
||||||
|
pSysMem: init.as_ptr() as _,
|
||||||
|
SysMemPitch: 0,
|
||||||
|
SysMemSlicePitch: 0,
|
||||||
|
};
|
||||||
|
let mut params = ptr::null_mut();
|
||||||
|
check(
|
||||||
|
(*device.0).CreateBuffer(&desc, &data, &mut params),
|
||||||
|
"CreateBuffer",
|
||||||
|
)?;
|
||||||
|
let params = ComPtr(params);
|
||||||
|
log::info!(
|
||||||
|
"scRGB desktop conversion ready, hdr {is_hdr}, sdr white level {sdr_white_level:?}"
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
device,
|
||||||
|
context,
|
||||||
|
vs,
|
||||||
|
ps,
|
||||||
|
params,
|
||||||
|
target: ComPtr(ptr::null_mut()),
|
||||||
|
rtv: ComPtr(ptr::null_mut()),
|
||||||
|
srv: ComPtr(ptr::null_mut()),
|
||||||
|
srv_source: ptr::null_mut(),
|
||||||
|
width: 0,
|
||||||
|
height: 0,
|
||||||
|
device_name: *device_name,
|
||||||
|
factory,
|
||||||
|
output6,
|
||||||
|
is_hdr,
|
||||||
|
sdr_white_level,
|
||||||
|
queried_at: Instant::now(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders `source` (R16G16B16A16_FLOAT) into an owned B8G8R8A8_UNORM
|
||||||
|
/// texture of the same size and returns it. The texture stays valid until
|
||||||
|
/// the next call.
|
||||||
|
pub fn convert(
|
||||||
|
&mut self,
|
||||||
|
source: *mut ID3D11Texture2D,
|
||||||
|
desc: &D3D11_TEXTURE2D_DESC,
|
||||||
|
) -> io::Result<*mut ID3D11Texture2D> {
|
||||||
|
unsafe {
|
||||||
|
self.refresh_output_state();
|
||||||
|
self.ensure_target(desc.Width, desc.Height)?;
|
||||||
|
self.ensure_source_view(source)?;
|
||||||
|
|
||||||
|
let ctx = self.context.0;
|
||||||
|
let rtv = self.rtv.0;
|
||||||
|
let srv = self.srv.0;
|
||||||
|
let params = self.params.0;
|
||||||
|
let viewport = D3D11_VIEWPORT {
|
||||||
|
TopLeftX: 0.0,
|
||||||
|
TopLeftY: 0.0,
|
||||||
|
Width: self.width as f32,
|
||||||
|
Height: self.height as f32,
|
||||||
|
MinDepth: 0.0,
|
||||||
|
MaxDepth: 1.0,
|
||||||
|
};
|
||||||
|
(*ctx).OMSetRenderTargets(1, &rtv, ptr::null_mut());
|
||||||
|
(*ctx).OMSetBlendState(ptr::null_mut(), &[0.0; 4], 0xffff_ffff);
|
||||||
|
(*ctx).OMSetDepthStencilState(ptr::null_mut(), 0);
|
||||||
|
(*ctx).RSSetState(ptr::null_mut());
|
||||||
|
(*ctx).RSSetViewports(1, &viewport);
|
||||||
|
(*ctx).IASetInputLayout(ptr::null_mut());
|
||||||
|
(*ctx).IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
|
||||||
|
(*ctx).VSSetShader(self.vs.0, ptr::null(), 0);
|
||||||
|
(*ctx).PSSetShader(self.ps.0, ptr::null(), 0);
|
||||||
|
(*ctx).PSSetConstantBuffers(0, 1, ¶ms);
|
||||||
|
(*ctx).PSSetShaderResources(0, 1, &srv);
|
||||||
|
(*ctx).Draw(3, 0);
|
||||||
|
// Unbind so the next frame's copy and the encoder never see the
|
||||||
|
// target as a live render target or the desktop image as a bound
|
||||||
|
// shader input.
|
||||||
|
let no_srv: *mut ID3D11ShaderResourceView = ptr::null_mut();
|
||||||
|
(*ctx).PSSetShaderResources(0, 1, &no_srv);
|
||||||
|
(*ctx).OMSetRenderTargets(0, ptr::null(), ptr::null_mut());
|
||||||
|
Ok(self.target.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn ensure_target(&mut self, width: u32, height: u32) -> io::Result<()> {
|
||||||
|
if !self.target.is_null() && self.width == width && self.height == height {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let desc = D3D11_TEXTURE2D_DESC {
|
||||||
|
Width: width,
|
||||||
|
Height: height,
|
||||||
|
MipLevels: 1,
|
||||||
|
ArraySize: 1,
|
||||||
|
Format: DXGI_FORMAT_B8G8R8A8_UNORM,
|
||||||
|
SampleDesc: DXGI_SAMPLE_DESC {
|
||||||
|
Count: 1,
|
||||||
|
Quality: 0,
|
||||||
|
},
|
||||||
|
Usage: D3D11_USAGE_DEFAULT,
|
||||||
|
BindFlags: D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE,
|
||||||
|
CPUAccessFlags: 0,
|
||||||
|
MiscFlags: D3D11_RESOURCE_MISC_SHARED,
|
||||||
|
};
|
||||||
|
let mut target = ptr::null_mut();
|
||||||
|
check(
|
||||||
|
(*self.device.0).CreateTexture2D(&desc, ptr::null(), &mut target),
|
||||||
|
"CreateTexture2D",
|
||||||
|
)?;
|
||||||
|
let target = ComPtr(target);
|
||||||
|
let mut rtv = ptr::null_mut();
|
||||||
|
check(
|
||||||
|
(*self.device.0).CreateRenderTargetView(target.0 as *mut _, ptr::null(), &mut rtv),
|
||||||
|
"CreateRenderTargetView",
|
||||||
|
)?;
|
||||||
|
self.rtv = ComPtr(rtv);
|
||||||
|
self.target = target;
|
||||||
|
self.width = width;
|
||||||
|
self.height = height;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn ensure_source_view(&mut self, source: *mut ID3D11Texture2D) -> io::Result<()> {
|
||||||
|
if !self.srv.is_null() && self.srv_source == source {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let mut srv = ptr::null_mut();
|
||||||
|
check(
|
||||||
|
(*self.device.0).CreateShaderResourceView(source as *mut _, ptr::null(), &mut srv),
|
||||||
|
"CreateShaderResourceView",
|
||||||
|
)?;
|
||||||
|
self.srv = ComPtr(srv);
|
||||||
|
self.srv_source = source;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
// Advanced Color state is dynamic: HDR can be switched on or off, or a WCG
|
||||||
|
// desktop can turn into an HDR one, without the duplication being lost. An
|
||||||
|
// output's description is a snapshot, so once the factory is no longer
|
||||||
|
// current a new factory and output are needed to see the new state, as the
|
||||||
|
// GetDesc1 docs require.
|
||||||
|
unsafe fn refresh_output_state(&mut self) {
|
||||||
|
if self.queried_at.elapsed() < OUTPUT_STATE_REFRESH {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.queried_at = Instant::now();
|
||||||
|
if self.factory.is_null() || (*self.factory.0).IsCurrent() == FALSE {
|
||||||
|
let (factory, output6) = enumerate_output6(&self.device_name);
|
||||||
|
if !output6.is_null() {
|
||||||
|
self.factory = factory;
|
||||||
|
self.output6 = output6;
|
||||||
|
} else {
|
||||||
|
// Keep reading the old output, but enumerate again next time.
|
||||||
|
self.factory = ComPtr(ptr::null_mut());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let is_hdr = output_is_hdr(self.output6.0).unwrap_or(self.is_hdr);
|
||||||
|
let level = if is_hdr {
|
||||||
|
query_sdr_white_level(&self.device_name)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
// A transiently unreadable level keeps the last known one.
|
||||||
|
if is_hdr == self.is_hdr && (level.is_none() || level == self.sdr_white_level) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
log::info!(
|
||||||
|
"output changed: hdr {} -> {is_hdr}, sdr white level {:?} -> {level:?}",
|
||||||
|
self.is_hdr,
|
||||||
|
self.sdr_white_level
|
||||||
|
);
|
||||||
|
if is_hdr && level.is_none() {
|
||||||
|
log::warn!(
|
||||||
|
"HDR output but the SDR white level cannot be read, assuming 80 nits until it can"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
self.is_hdr = is_hdr;
|
||||||
|
self.sdr_white_level = level;
|
||||||
|
let data = params_data(level);
|
||||||
|
(*self.context.0).UpdateSubresource(
|
||||||
|
self.params.0 as *mut _,
|
||||||
|
0,
|
||||||
|
ptr::null(),
|
||||||
|
data.as_ptr() as _,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// `None` is either a non-HDR (WCG) output, where 1.0 already is the display's
|
||||||
|
// reference white, or an HDR output whose level is unknown; both use 1.0.
|
||||||
|
fn params_data(sdr_white_level: Option<u32>) -> [f32; 4] {
|
||||||
|
[
|
||||||
|
1000.0 / sdr_white_level.unwrap_or(1000) as f32,
|
||||||
|
0.0,
|
||||||
|
0.0,
|
||||||
|
0.0,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// FP16 desktop composition means either HDR (scene-referred, 1.0 == 80 nits)
|
||||||
|
// or, since Windows 11 22H2, Advanced Color SDR (display-referred), and only
|
||||||
|
// IDXGIOutput6 (Windows 10 1703) tells them apart. `None` when it cannot be
|
||||||
|
// read right now.
|
||||||
|
unsafe fn output_is_hdr(output6: *mut IDXGIOutput6) -> Option<bool> {
|
||||||
|
if output6.is_null() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut desc: DXGI_OUTPUT_DESC1 = mem::zeroed();
|
||||||
|
if (*output6).GetDesc1(&mut desc) != S_OK {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some(desc.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn query_output6(object: *mut IUnknown) -> ComPtr<IDXGIOutput6> {
|
||||||
|
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
|
||||||
|
if !object.is_null() {
|
||||||
|
(*object).QueryInterface(
|
||||||
|
&IID_IDXGIOutput6,
|
||||||
|
&mut output6 as *mut *mut _ as *mut *mut _,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
ComPtr(output6)
|
||||||
|
}
|
||||||
|
|
||||||
|
// A fresh factory sees the current display configuration; the output is found
|
||||||
|
// by its GDI name because the outputs of a stale factory keep stale descriptions.
|
||||||
|
// Returns both or neither: a non-null factory guarantees the output came from
|
||||||
|
// its topology, so a caller that sees a null factory knows to enumerate again.
|
||||||
|
unsafe fn enumerate_output6(
|
||||||
|
device_name: &[WCHAR; 32],
|
||||||
|
) -> (ComPtr<IDXGIFactory1>, ComPtr<IDXGIOutput6>) {
|
||||||
|
let mut factory: *mut c_void = ptr::null_mut();
|
||||||
|
if CreateDXGIFactory1(&IID_IDXGIFactory1, &mut factory) != S_OK {
|
||||||
|
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
|
||||||
|
}
|
||||||
|
let factory = ComPtr(factory as *mut IDXGIFactory1);
|
||||||
|
let mut adapter_index = 0;
|
||||||
|
loop {
|
||||||
|
let mut adapter = ptr::null_mut();
|
||||||
|
if (*factory.0).EnumAdapters1(adapter_index, &mut adapter) != S_OK {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let adapter = ComPtr(adapter);
|
||||||
|
adapter_index += 1;
|
||||||
|
let mut output_index = 0;
|
||||||
|
loop {
|
||||||
|
let mut output = ptr::null_mut();
|
||||||
|
if (*adapter.0).EnumOutputs(output_index, &mut output) != S_OK {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let output = ComPtr(output);
|
||||||
|
output_index += 1;
|
||||||
|
let mut desc: DXGI_OUTPUT_DESC = mem::zeroed();
|
||||||
|
if (*output.0).GetDesc(&mut desc) == S_OK && wide_eq(&desc.DeviceName, device_name) {
|
||||||
|
let output6 = query_output6(output.0 as *mut IUnknown);
|
||||||
|
if output6.is_null() {
|
||||||
|
return (ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()));
|
||||||
|
}
|
||||||
|
return (factory, output6);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(ComPtr(ptr::null_mut()), ComPtr(ptr::null_mut()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn other(msg: impl Into<String>) -> io::Error {
|
||||||
|
io::Error::new(io::ErrorKind::Other, msg.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(hr: HRESULT, what: &str) -> io::Result<()> {
|
||||||
|
if hr == S_OK {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(other(format!("{what} failed: {hr:#x}")))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// D3DCompile(pSrcData, SrcDataSize, pSourceName, pDefines, pInclude,
|
||||||
|
// pEntrypoint, pTarget, Flags1, Flags2, ppCode, ppErrorMsgs)
|
||||||
|
type D3DCompileFn = unsafe extern "system" fn(
|
||||||
|
LPCVOID,
|
||||||
|
SIZE_T,
|
||||||
|
LPCSTR,
|
||||||
|
*const D3D_SHADER_MACRO,
|
||||||
|
*mut ID3DInclude,
|
||||||
|
LPCSTR,
|
||||||
|
LPCSTR,
|
||||||
|
UINT,
|
||||||
|
UINT,
|
||||||
|
*mut *mut ID3DBlob,
|
||||||
|
*mut *mut ID3DBlob,
|
||||||
|
) -> HRESULT;
|
||||||
|
|
||||||
|
static D3D_COMPILE: OnceLock<Result<D3DCompileFn, String>> = OnceLock::new();
|
||||||
|
|
||||||
|
// Loaded once per process and kept: the compiler DLL is only needed on HDR
|
||||||
|
// desktops, and an import-time link would make every install depend on it.
|
||||||
|
fn load_d3d_compile() -> io::Result<D3DCompileFn> {
|
||||||
|
D3D_COMPILE
|
||||||
|
.get_or_init(|| unsafe { find_d3d_compile() })
|
||||||
|
.clone()
|
||||||
|
.map_err(|e| io::Error::new(io::ErrorKind::Unsupported, e))
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn find_d3d_compile() -> Result<D3DCompileFn, String> {
|
||||||
|
let name: Vec<u16> = "d3dcompiler_47.dll\0".encode_utf16().collect();
|
||||||
|
let module = LoadLibraryExW(name.as_ptr(), ptr::null_mut(), LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||||
|
if module.is_null() {
|
||||||
|
return Err("d3dcompiler_47.dll not available".into());
|
||||||
|
}
|
||||||
|
let f = GetProcAddress(module, b"D3DCompile\0".as_ptr() as _);
|
||||||
|
if f.is_null() {
|
||||||
|
return Err("D3DCompile not exported".into());
|
||||||
|
}
|
||||||
|
Ok(mem::transmute::<_, D3DCompileFn>(f))
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn compile_shader(
|
||||||
|
compile: D3DCompileFn,
|
||||||
|
src: &str,
|
||||||
|
target: &[u8],
|
||||||
|
) -> io::Result<ComPtr<ID3DBlob>> {
|
||||||
|
let mut code = ptr::null_mut();
|
||||||
|
let mut errors = ptr::null_mut();
|
||||||
|
let hr = compile(
|
||||||
|
src.as_ptr() as _,
|
||||||
|
src.len(),
|
||||||
|
ptr::null(),
|
||||||
|
ptr::null(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
b"main\0".as_ptr() as _,
|
||||||
|
target.as_ptr() as _,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
&mut code,
|
||||||
|
&mut errors,
|
||||||
|
);
|
||||||
|
let errors = ComPtr(errors);
|
||||||
|
if hr != S_OK || code.is_null() {
|
||||||
|
let msg = if errors.is_null() {
|
||||||
|
String::new()
|
||||||
|
} else {
|
||||||
|
let bytes = std::slice::from_raw_parts(
|
||||||
|
(*errors.0).GetBufferPointer() as *const u8,
|
||||||
|
(*errors.0).GetBufferSize(),
|
||||||
|
);
|
||||||
|
String::from_utf8_lossy(bytes).into_owned()
|
||||||
|
};
|
||||||
|
if !code.is_null() {
|
||||||
|
(*(code as *mut IUnknown)).Release();
|
||||||
|
}
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::Unsupported,
|
||||||
|
format!("D3DCompile failed: {hr:#x} {msg}"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(ComPtr(code))
|
||||||
|
}
|
||||||
|
|
||||||
|
const DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL: u32 = 11;
|
||||||
|
const QDC_ONLY_ACTIVE_PATHS: u32 = 2;
|
||||||
|
|
||||||
|
#[repr(C)]
|
||||||
|
#[allow(non_snake_case)]
|
||||||
|
struct DISPLAYCONFIG_SDR_WHITE_LEVEL {
|
||||||
|
header: DISPLAYCONFIG_DEVICE_INFO_HEADER,
|
||||||
|
SDRWhiteLevel: ULONG,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[link(name = "user32")]
|
||||||
|
extern "system" {
|
||||||
|
fn GetDisplayConfigBufferSizes(
|
||||||
|
flags: u32,
|
||||||
|
numPathArrayElements: *mut u32,
|
||||||
|
numModeInfoArrayElements: *mut u32,
|
||||||
|
) -> LONG;
|
||||||
|
fn QueryDisplayConfig(
|
||||||
|
flags: u32,
|
||||||
|
numPathArrayElements: *mut u32,
|
||||||
|
pathArray: *mut DISPLAYCONFIG_PATH_INFO,
|
||||||
|
numModeInfoArrayElements: *mut u32,
|
||||||
|
modeInfoArray: *mut DISPLAYCONFIG_MODE_INFO,
|
||||||
|
currentTopologyId: *mut DISPLAYCONFIG_TOPOLOGY_ID,
|
||||||
|
) -> LONG;
|
||||||
|
fn DisplayConfigGetDeviceInfo(requestPacket: *mut DISPLAYCONFIG_DEVICE_INFO_HEADER) -> LONG;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// SDR white level of the output whose GDI name is `device_name`
|
||||||
|
/// (e.g. `\\.\DISPLAY1`), in DISPLAYCONFIG units (1000 == 80 nits). `None`
|
||||||
|
/// when the query fails (before Windows 10 1709) or reports 0.
|
||||||
|
fn query_sdr_white_level(device_name: &[WCHAR; 32]) -> Option<u32> {
|
||||||
|
unsafe {
|
||||||
|
let mut n_paths = 0u32;
|
||||||
|
let mut n_modes = 0u32;
|
||||||
|
if GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &mut n_paths, &mut n_modes) != 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut paths: Vec<DISPLAYCONFIG_PATH_INFO> = vec![mem::zeroed(); n_paths as usize];
|
||||||
|
let mut modes: Vec<DISPLAYCONFIG_MODE_INFO> = vec![mem::zeroed(); n_modes as usize];
|
||||||
|
if QueryDisplayConfig(
|
||||||
|
QDC_ONLY_ACTIVE_PATHS,
|
||||||
|
&mut n_paths,
|
||||||
|
paths.as_mut_ptr(),
|
||||||
|
&mut n_modes,
|
||||||
|
modes.as_mut_ptr(),
|
||||||
|
ptr::null_mut(),
|
||||||
|
) != 0
|
||||||
|
{
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
for path in &paths[..n_paths as usize] {
|
||||||
|
let mut source: DISPLAYCONFIG_SOURCE_DEVICE_NAME = mem::zeroed();
|
||||||
|
source.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
|
||||||
|
source.header.size = mem::size_of::<DISPLAYCONFIG_SOURCE_DEVICE_NAME>() as _;
|
||||||
|
source.header.adapterId = path.sourceInfo.adapterId;
|
||||||
|
source.header.id = path.sourceInfo.id;
|
||||||
|
if DisplayConfigGetDeviceInfo(&mut source.header) != 0
|
||||||
|
|| !wide_eq(&source.viewGdiDeviceName, device_name)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mut white: DISPLAYCONFIG_SDR_WHITE_LEVEL = mem::zeroed();
|
||||||
|
white.header._type = DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL;
|
||||||
|
white.header.size = mem::size_of::<DISPLAYCONFIG_SDR_WHITE_LEVEL>() as _;
|
||||||
|
white.header.adapterId = path.targetInfo.adapterId;
|
||||||
|
white.header.id = path.targetInfo.id;
|
||||||
|
if DisplayConfigGetDeviceInfo(&mut white.header) == 0 && white.SDRWhiteLevel != 0 {
|
||||||
|
return Some(white.SDRWhiteLevel);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn wide_eq(a: &[WCHAR], b: &[WCHAR]) -> bool {
|
||||||
|
let end = |s: &[WCHAR]| s.iter().position(|&c| c == 0).unwrap_or(s.len());
|
||||||
|
a[..end(a)] == b[..end(b)]
|
||||||
|
}
|
||||||
+120
-4
@@ -1,18 +1,20 @@
|
|||||||
use std::{io, mem, ptr, slice};
|
use std::{io, mem, ptr, slice};
|
||||||
pub mod gdi;
|
pub mod gdi;
|
||||||
pub use gdi::CapturerGDI;
|
pub use gdi::CapturerGDI;
|
||||||
|
pub mod hdr;
|
||||||
pub mod mag;
|
pub mod mag;
|
||||||
|
|
||||||
use winapi::{
|
use winapi::{
|
||||||
shared::{
|
shared::{
|
||||||
dxgi::*,
|
dxgi::*,
|
||||||
dxgi1_2::*,
|
dxgi1_2::*,
|
||||||
|
dxgi1_6::*,
|
||||||
|
dxgiformat::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_R16G16B16A16_FLOAT},
|
||||||
dxgitype::*,
|
dxgitype::*,
|
||||||
minwindef::{DWORD, FALSE, TRUE, UINT},
|
minwindef::{DWORD, FALSE, TRUE, UINT},
|
||||||
ntdef::LONG,
|
ntdef::LONG,
|
||||||
windef::{HMONITOR, RECT},
|
windef::{HMONITOR, RECT},
|
||||||
winerror::*,
|
winerror::*,
|
||||||
// dxgiformat::{DXGI_FORMAT, DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_420_OPAQUE},
|
|
||||||
},
|
},
|
||||||
um::{
|
um::{
|
||||||
d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown, wingdi::*,
|
d3d11::*, d3dcommon::D3D_DRIVER_TYPE_UNKNOWN, unknwnbase::IUnknown, wingdi::*,
|
||||||
@@ -66,6 +68,7 @@ pub struct Capturer {
|
|||||||
adapter_desc1: DXGI_ADAPTER_DESC1,
|
adapter_desc1: DXGI_ADAPTER_DESC1,
|
||||||
rotate: Rotate,
|
rotate: Rotate,
|
||||||
frame_state: FrameState,
|
frame_state: FrameState,
|
||||||
|
hdr: Option<hdr::HdrToSdr>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Capturer {
|
impl Capturer {
|
||||||
@@ -113,7 +116,7 @@ impl Capturer {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
res = wrap_hresult(unsafe {
|
res = wrap_hresult(unsafe {
|
||||||
let hres = (*display.inner.0).DuplicateOutput(device.0 as *mut _, &mut duplication);
|
let hres = Self::duplicate_output(&display, device.0, &mut duplication);
|
||||||
if hres != S_OK {
|
if hres != S_OK {
|
||||||
gdi_capturer = display.create_gdi();
|
gdi_capturer = display.create_gdi();
|
||||||
println!("Fallback to GDI");
|
println!("Fallback to GDI");
|
||||||
@@ -169,7 +172,8 @@ impl Capturer {
|
|||||||
device,
|
device,
|
||||||
context,
|
context,
|
||||||
duplication: ComPtr(duplication),
|
duplication: ComPtr(duplication),
|
||||||
fastlane: desc.DesktopImageInSystemMemory == TRUE,
|
fastlane: desc.DesktopImageInSystemMemory == TRUE
|
||||||
|
&& desc.ModeDesc.Format != DXGI_FORMAT_R16G16B16A16_FLOAT,
|
||||||
surface: ComPtr(ptr::null_mut()),
|
surface: ComPtr(ptr::null_mut()),
|
||||||
texture: ComPtr(ptr::null_mut()),
|
texture: ComPtr(ptr::null_mut()),
|
||||||
width: display.width() as usize,
|
width: display.width() as usize,
|
||||||
@@ -183,9 +187,104 @@ impl Capturer {
|
|||||||
adapter_desc1,
|
adapter_desc1,
|
||||||
rotate,
|
rotate,
|
||||||
frame_state: FrameState::Idle,
|
frame_state: FrameState::Idle,
|
||||||
|
hdr: None,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Asks for the float desktop that HDR mode composes so it can be tone-mapped;
|
||||||
|
// the legacy call would hand back DXGI's clipped BGRA8 conversion instead.
|
||||||
|
// Only where IDXGIOutput6 (Windows 10 1703) exists, since that is what later
|
||||||
|
// tells an HDR desktop from a WCG one; Microsoft's duplication sample gates
|
||||||
|
// the float request the same way.
|
||||||
|
unsafe fn duplicate_output(
|
||||||
|
display: &Display,
|
||||||
|
device: *mut ID3D11Device,
|
||||||
|
duplication: &mut *mut IDXGIOutputDuplication,
|
||||||
|
) -> HRESULT {
|
||||||
|
if !hdr::UNAVAILABLE.load(std::sync::atomic::Ordering::Relaxed) {
|
||||||
|
let mut output6: *mut IDXGIOutput6 = ptr::null_mut();
|
||||||
|
(*display.inner.0).QueryInterface(
|
||||||
|
&IID_IDXGIOutput6,
|
||||||
|
&mut output6 as *mut *mut _ as *mut *mut _,
|
||||||
|
);
|
||||||
|
if !output6.is_null() {
|
||||||
|
let output6 = ComPtr(output6);
|
||||||
|
let formats = [DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_B8G8R8A8_UNORM];
|
||||||
|
let hres = (*output6.0).DuplicateOutput1(
|
||||||
|
device as *mut _,
|
||||||
|
0,
|
||||||
|
formats.len() as UINT,
|
||||||
|
formats.as_ptr(),
|
||||||
|
duplication,
|
||||||
|
);
|
||||||
|
if hres == S_OK {
|
||||||
|
return hres;
|
||||||
|
}
|
||||||
|
hbb_common::log::warn!(
|
||||||
|
"HDR DuplicateOutput1 failed: hr={:#x}, fallback=DuplicateOutput",
|
||||||
|
hres as u32
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(*display.inner.0).DuplicateOutput(device as *mut _, duplication)
|
||||||
|
}
|
||||||
|
|
||||||
|
unsafe fn tonemap(
|
||||||
|
&mut self,
|
||||||
|
source: *mut ID3D11Texture2D,
|
||||||
|
desc: &D3D11_TEXTURE2D_DESC,
|
||||||
|
) -> io::Result<*mut ID3D11Texture2D> {
|
||||||
|
if self.hdr.is_none() {
|
||||||
|
match hdr::HdrToSdr::new(
|
||||||
|
self.device.0,
|
||||||
|
self.context.0,
|
||||||
|
self.display.inner.0,
|
||||||
|
&self.display.desc.DeviceName,
|
||||||
|
) {
|
||||||
|
Ok(hdr) => self.hdr = Some(hdr),
|
||||||
|
Err(err) => return self.abandon_tonemap(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let converted = match self.hdr.as_mut() {
|
||||||
|
Some(hdr) => hdr.convert(source, desc),
|
||||||
|
None => Err(io::Error::new(io::ErrorKind::Other, "no tone-map")),
|
||||||
|
};
|
||||||
|
match converted {
|
||||||
|
Ok(texture) => Ok(texture),
|
||||||
|
Err(err) => self.abandon_tonemap(err),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drops the tone-map and re-duplicates the output the legacy way, so DXGI
|
||||||
|
// hands over clipped BGRA8 (the pre-HDR behaviour). If re-duplication fails,
|
||||||
|
// switch to GDI before returning. The caller sees WouldBlock and asks again.
|
||||||
|
unsafe fn abandon_tonemap<T>(&mut self, err: io::Error) -> io::Result<T> {
|
||||||
|
if hdr::is_permanent(&err) {
|
||||||
|
hdr::UNAVAILABLE.store(true, std::sync::atomic::Ordering::Relaxed);
|
||||||
|
}
|
||||||
|
hbb_common::log::error!("HDR tone-map failed, re-duplicating without it: {err}");
|
||||||
|
self.hdr = None;
|
||||||
|
if let Err(release_err) = self.release_frame() {
|
||||||
|
hbb_common::log::warn!("DXGI frame cleanup failed while disabling HDR: {release_err}");
|
||||||
|
}
|
||||||
|
self.duplication = ComPtr(ptr::null_mut());
|
||||||
|
let mut duplication = ptr::null_mut();
|
||||||
|
let result = wrap_hresult(
|
||||||
|
(*self.display.inner.0).DuplicateOutput(self.device.0 as *mut _, &mut duplication),
|
||||||
|
);
|
||||||
|
if let Err(err) = result {
|
||||||
|
if self.set_gdi() {
|
||||||
|
return Err(io::ErrorKind::WouldBlock.into());
|
||||||
|
}
|
||||||
|
return Err(err);
|
||||||
|
}
|
||||||
|
self.duplication = ComPtr(duplication);
|
||||||
|
let mut desc: DXGI_OUTDUPL_DESC = mem::zeroed();
|
||||||
|
(*duplication).GetDesc(&mut desc);
|
||||||
|
self.fastlane = desc.DesktopImageInSystemMemory == TRUE;
|
||||||
|
Err(io::ErrorKind::WouldBlock.into())
|
||||||
|
}
|
||||||
|
|
||||||
fn create_rotations(
|
fn create_rotations(
|
||||||
device: *mut ID3D11Device,
|
device: *mut ID3D11Device,
|
||||||
context: *mut ID3D11DeviceContext,
|
context: *mut ID3D11DeviceContext,
|
||||||
@@ -339,6 +438,9 @@ impl Capturer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<(*const u8, i32)> {
|
unsafe fn load_frame(&mut self, timeout: UINT) -> io::Result<(*const u8, i32)> {
|
||||||
|
if self.duplication.0.is_null() {
|
||||||
|
return Err(io::ErrorKind::AddrNotAvailable.into());
|
||||||
|
}
|
||||||
let mut frame = ptr::null_mut();
|
let mut frame = ptr::null_mut();
|
||||||
#[allow(invalid_value)]
|
#[allow(invalid_value)]
|
||||||
let mut info = mem::MaybeUninit::uninit().assume_init();
|
let mut info = mem::MaybeUninit::uninit().assume_init();
|
||||||
@@ -377,6 +479,12 @@ impl Capturer {
|
|||||||
let mut texture_desc = mem::MaybeUninit::uninit().assume_init();
|
let mut texture_desc = mem::MaybeUninit::uninit().assume_init();
|
||||||
(*texture.0).GetDesc(&mut texture_desc);
|
(*texture.0).GetDesc(&mut texture_desc);
|
||||||
|
|
||||||
|
let mut source = texture.0;
|
||||||
|
if texture_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
|
||||||
|
source = self.tonemap(texture.0, &texture_desc)?;
|
||||||
|
(*source).GetDesc(&mut texture_desc);
|
||||||
|
}
|
||||||
|
|
||||||
texture_desc.Usage = D3D11_USAGE_STAGING;
|
texture_desc.Usage = D3D11_USAGE_STAGING;
|
||||||
texture_desc.BindFlags = 0;
|
texture_desc.BindFlags = 0;
|
||||||
texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
|
texture_desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
|
||||||
@@ -397,7 +505,7 @@ impl Capturer {
|
|||||||
&mut surface as *mut *mut _ as *mut *mut _,
|
&mut surface as *mut *mut _ as *mut *mut _,
|
||||||
);
|
);
|
||||||
|
|
||||||
(*self.context.0).CopyResource(readable.0 as *mut _, texture.0 as *mut _);
|
(*self.context.0).CopyResource(readable.0 as *mut _, source as *mut _);
|
||||||
|
|
||||||
Ok(surface)
|
Ok(surface)
|
||||||
}
|
}
|
||||||
@@ -505,6 +613,14 @@ impl Capturer {
|
|||||||
let texture = ComPtr(texture);
|
let texture = ComPtr(texture);
|
||||||
self.texture = texture;
|
self.texture = texture;
|
||||||
|
|
||||||
|
let mut frame_desc: D3D11_TEXTURE2D_DESC = mem::zeroed();
|
||||||
|
(*self.texture.0).GetDesc(&mut frame_desc);
|
||||||
|
if frame_desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT {
|
||||||
|
let converted = self.tonemap(self.texture.0, &frame_desc)?;
|
||||||
|
(*converted).AddRef();
|
||||||
|
self.texture = ComPtr(converted);
|
||||||
|
}
|
||||||
|
|
||||||
let mut final_texture = self.texture.0 as *mut c_void;
|
let mut final_texture = self.texture.0 as *mut c_void;
|
||||||
let mut rotation = match self.display.rotation() {
|
let mut rotation = match self.display.rotation() {
|
||||||
DXGI_MODE_ROTATION_ROTATE90 => 90,
|
DXGI_MODE_ROTATION_ROTATE90 => 90,
|
||||||
|
|||||||
+271
-3
@@ -61,7 +61,7 @@ use hbb_common::{
|
|||||||
use hbb_common::{tokio::sync::Mutex as TokioMutex, ResultType};
|
use hbb_common::{tokio::sync::Mutex as TokioMutex, ResultType};
|
||||||
use scrap::CodecFormat;
|
use scrap::CodecFormat;
|
||||||
use std::{
|
use std::{
|
||||||
collections::HashMap,
|
collections::{HashMap, HashSet},
|
||||||
ffi::c_void,
|
ffi::c_void,
|
||||||
num::NonZeroI64,
|
num::NonZeroI64,
|
||||||
path::PathBuf,
|
path::PathBuf,
|
||||||
@@ -96,6 +96,7 @@ pub struct Remote<T: InvokeUiSession> {
|
|||||||
chroma: Arc<RwLock<Option<Chroma>>>,
|
chroma: Arc<RwLock<Option<Chroma>>>,
|
||||||
last_record_state: bool,
|
last_record_state: bool,
|
||||||
sent_close_reason: bool,
|
sent_close_reason: bool,
|
||||||
|
cursor_dedupe: CursorDedupe,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
@@ -145,6 +146,7 @@ impl<T: InvokeUiSession> Remote<T> {
|
|||||||
chroma: Default::default(),
|
chroma: Default::default(),
|
||||||
last_record_state: false,
|
last_record_state: false,
|
||||||
sent_close_reason: false,
|
sent_close_reason: false,
|
||||||
|
cursor_dedupe: Default::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1523,11 +1525,29 @@ 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)) => {
|
Some(message::Union::CursorData(cd)) => {
|
||||||
let id = cd.id;
|
let id = cd.id;
|
||||||
|
#[cfg(feature = "flutter")]
|
||||||
|
let compressed = cd.colors.clone();
|
||||||
match decode_cursor_data(cd) {
|
match decode_cursor_data(cd) {
|
||||||
Ok(cd) => self.handler.set_cursor_data(cd),
|
Ok(cd) => {
|
||||||
Err(err) => log::warn!("Rejected cursor {id}: {err}"),
|
#[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());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Some(message::Union::CursorId(id)) => {
|
Some(message::Union::CursorId(id)) => {
|
||||||
@@ -2560,6 +2580,69 @@ impl<T: InvokeUiSession> Remote<T> {
|
|||||||
msg.set_misc(misc);
|
msg.set_misc(misc);
|
||||||
self.sender.send(Data::Message(msg)).ok();
|
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.
|
// Both UI handlers receive validated, uncompressed RGBA from the receive loop.
|
||||||
@@ -2603,6 +2686,49 @@ fn decode_cursor_data(data: CursorData) -> hbb_common::ResultType<CursorData> {
|
|||||||
Ok(cd)
|
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 {
|
struct RemoveJob {
|
||||||
files: Vec<FileEntry>,
|
files: Vec<FileEntry>,
|
||||||
path: String,
|
path: String,
|
||||||
@@ -2725,3 +2851,145 @@ 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");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -149,6 +149,24 @@ pub fn is_support_multi_ui_session_num(ver: i64) -> bool {
|
|||||||
ver >= hbb_common::get_version_number(MIN_VER_MULTI_UI_SESSION)
|
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]
|
#[inline]
|
||||||
#[cfg(feature = "unix-file-copy-paste")]
|
#[cfg(feature = "unix-file-copy-paste")]
|
||||||
pub fn is_support_file_copy_paste(ver: &str) -> bool {
|
pub fn is_support_file_copy_paste(ver: &str) -> bool {
|
||||||
@@ -2936,6 +2954,16 @@ mod tests {
|
|||||||
};
|
};
|
||||||
use std::collections::HashSet;
|
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]
|
#[inline]
|
||||||
fn get_timestamp_secs() -> u128 {
|
fn get_timestamp_secs() -> u128 {
|
||||||
(std::time::SystemTime::UNIX_EPOCH
|
(std::time::SystemTime::UNIX_EPOCH
|
||||||
|
|||||||
+14
-16
@@ -651,23 +651,21 @@ impl FlutterHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl InvokeUiSession for 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) {
|
fn set_cursor_data(&self, cd: CursorData) {
|
||||||
let colors = &cd.colors;
|
let colors = cd.colors.to_vec();
|
||||||
self.push_event(
|
for session in self.session_handlers.read().unwrap().values() {
|
||||||
"cursor_data",
|
if let Some(stream) = &session.event_stream {
|
||||||
&[
|
stream.add(EventToUI::Cursor {
|
||||||
("id", &cd.id.to_string()),
|
id: cd.id.to_string(),
|
||||||
("hotx", &cd.hotx.to_string()),
|
hotx: cd.hotx,
|
||||||
("hoty", &cd.hoty.to_string()),
|
hoty: cd.hoty,
|
||||||
("width", &cd.width.to_string()),
|
width: cd.width,
|
||||||
("height", &cd.height.to_string()),
|
height: cd.height,
|
||||||
(
|
colors: colors.clone(),
|
||||||
"colors",
|
});
|
||||||
&serde_json::ser::to_string(&colors).unwrap_or("".to_owned()),
|
}
|
||||||
),
|
}
|
||||||
],
|
|
||||||
&[],
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn set_cursor_id(&self, id: String) {
|
fn set_cursor_id(&self, id: String) {
|
||||||
|
|||||||
@@ -97,6 +97,16 @@ pub enum EventToUI {
|
|||||||
Event(String),
|
Event(String),
|
||||||
Rgba(usize),
|
Rgba(usize),
|
||||||
Texture(usize, bool), // (display, gpu_texture)
|
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) {
|
pub fn host_stop_system_key_propagate(_stopped: bool) {
|
||||||
@@ -201,6 +211,34 @@ pub fn session_start_with_displays(
|
|||||||
Ok(())
|
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> {
|
pub fn session_get_remember(session_id: SessionID) -> Option<bool> {
|
||||||
if let Some(session) = sessions::get_session_by_session_id(&session_id) {
|
if let Some(session) = sessions::get_session_by_session_id(&session_id) {
|
||||||
Some(session.get_remember())
|
Some(session.get_remember())
|
||||||
|
|||||||
+9
-52
@@ -559,6 +559,9 @@ pub fn get_cursor() -> ResultType<Option<u64>> {
|
|||||||
autoreleasepool(|| unsafe_get_cursor())
|
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>> {
|
fn unsafe_get_cursor() -> ResultType<Option<u64>> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let seed = CGSCurrentCursorSeed();
|
let seed = CGSCurrentCursorSeed();
|
||||||
@@ -566,9 +569,8 @@ fn unsafe_get_cursor() -> ResultType<Option<u64>> {
|
|||||||
return Ok(None);
|
return Ok(None);
|
||||||
}
|
}
|
||||||
LATEST_SEED = seed;
|
LATEST_SEED = seed;
|
||||||
|
Ok(Some(seed as u32 as u64))
|
||||||
}
|
}
|
||||||
let c = get_cursor_id()?;
|
|
||||||
Ok(Some(c.1))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn reset_input_cache() {
|
pub fn reset_input_cache() {
|
||||||
@@ -577,53 +579,6 @@ 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> {
|
pub fn get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
|
||||||
autoreleasepool(|| unsafe_get_cursor_data(hcursor))
|
autoreleasepool(|| unsafe_get_cursor_data(hcursor))
|
||||||
}
|
}
|
||||||
@@ -631,9 +586,11 @@ pub fn get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
|
|||||||
// https://github.com/stweil/OSXvnc/blob/master/OSXvnc-server/mousecursor.c
|
// https://github.com/stweil/OSXvnc/blob/master/OSXvnc-server/mousecursor.c
|
||||||
fn unsafe_get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
|
fn unsafe_get_cursor_data(hcursor: u64) -> ResultType<CursorData> {
|
||||||
unsafe {
|
unsafe {
|
||||||
let (c, hcursor2) = get_cursor_id()?;
|
// The cursor shown is captured even if it changed after get_cursor read the seed: the
|
||||||
if hcursor != hcursor2 {
|
// content names the shape, and that change moved the seed on, so the next poll captures it.
|
||||||
bail!("cursor changed");
|
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 hotspot: NSPoint = msg_send![c, hotSpot];
|
||||||
let img: id = msg_send![c, image];
|
let img: id = msg_send![c, image];
|
||||||
|
|||||||
@@ -228,6 +228,14 @@ mod tests {
|
|||||||
#[cfg(target_os = "macos")]
|
#[cfg(target_os = "macos")]
|
||||||
macos::is_process_trusted(false);
|
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]
|
#[test]
|
||||||
fn test_get_cursor_pos() {
|
fn test_get_cursor_pos() {
|
||||||
|
|||||||
@@ -3990,6 +3990,17 @@ impl Connection {
|
|||||||
self.send(msg_out).await;
|
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)) => {
|
Some(message::Union::AudioFrame(frame)) => {
|
||||||
|
|||||||
+198
-7
@@ -42,6 +42,7 @@ struct StateCursor {
|
|||||||
impl super::service::Reset for StateCursor {
|
impl super::service::Reset for StateCursor {
|
||||||
fn reset(&mut self) {
|
fn reset(&mut self) {
|
||||||
*self = Default::default();
|
*self = Default::default();
|
||||||
|
CURSOR_SHAPES.lock().unwrap().clear();
|
||||||
crate::platform::reset_input_cache();
|
crate::platform::reset_input_cache();
|
||||||
fix_key_down_timeout(true);
|
fix_key_down_timeout(true);
|
||||||
}
|
}
|
||||||
@@ -406,7 +407,7 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
|||||||
super::log::trace!("Cursor data cached, hcursor: {}", hcursor);
|
super::log::trace!("Cursor data cached, hcursor: {}", hcursor);
|
||||||
msg = cached.clone();
|
msg = cached.clone();
|
||||||
} else {
|
} else {
|
||||||
let mut data = crate::get_cursor_data(hcursor)?;
|
let data = crate::get_cursor_data(hcursor)?;
|
||||||
// File the shape under the id ACTUALLY served, not the one requested. Deliberately a
|
// 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
|
// 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
|
// id everywhere else in this function, and a cfg-gated shadow would make the two
|
||||||
@@ -421,10 +422,7 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
|||||||
let cache_key = served_id;
|
let cache_key = served_id;
|
||||||
#[cfg(not(all(target_os = "linux", feature = "drm")))]
|
#[cfg(not(all(target_os = "linux", feature = "drm")))]
|
||||||
let cache_key = hcursor;
|
let cache_key = hcursor;
|
||||||
data.colors = hbb_common::compress::compress(&data.colors[..]).into();
|
msg = cursor_shape_message(data, hbb_common::compress::compress);
|
||||||
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
|
// 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
|
// 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
|
// of the service, each entry pinning a compressed cursor message. (Upstream's X11
|
||||||
@@ -438,8 +436,15 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
|||||||
const CURSOR_CACHE_MAX: usize = 64;
|
const CURSOR_CACHE_MAX: usize = 64;
|
||||||
if state.cached_cursor_data.len() >= CURSOR_CACHE_MAX {
|
if state.cached_cursor_data.len() >= CURSOR_CACHE_MAX {
|
||||||
state.cached_cursor_data.clear();
|
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());
|
state.cached_cursor_data.insert(cache_key, msg.clone());
|
||||||
super::log::trace!("Cursor data updated, hcursor: {}", cache_key);
|
super::log::trace!("Cursor data updated, hcursor: {}", cache_key);
|
||||||
}
|
}
|
||||||
@@ -451,8 +456,12 @@ fn run_cursor(sp: MouseCursorService, state: &mut StateCursor) -> ResultType<()>
|
|||||||
{
|
{
|
||||||
state.hcursor = drm_served_id;
|
state.hcursor = drm_served_id;
|
||||||
}
|
}
|
||||||
sp.send_shared(msg.clone());
|
// A new handle or seed for the shape already shown changes nothing a controller sees;
|
||||||
state.cursor_data = msg;
|
// 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.snapshot(|sps| {
|
sp.snapshot(|sps| {
|
||||||
@@ -499,6 +508,95 @@ lazy_static::lazy_static! {
|
|||||||
static ref RELATIVE_MOUSE_CONNS: Arc<Mutex<std::collections::HashSet<i32>>> = Default::default();
|
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")]
|
#[cfg(target_os = "linux")]
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
static ref WAYLAND_CLIPBOARD_INPUT_RECORDS: Arc<Mutex<Vec<(Instant, String)>>> =
|
static ref WAYLAND_CLIPBOARD_INPUT_RECORDS: Arc<Mutex<Vec<(Instant, String)>>> =
|
||||||
@@ -2533,3 +2631,96 @@ lazy_static::lazy_static! {
|
|||||||
(ControlKey::Delete, true),
|
(ControlKey::Delete, true),
|
||||||
].iter().map(|(a, b)| (a.value(), b.clone())).collect();
|
].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,6 +72,10 @@ pub struct Session<T: InvokeUiSession> {
|
|||||||
pub reconnect_count: Arc<AtomicUsize>,
|
pub reconnect_count: Arc<AtomicUsize>,
|
||||||
pub last_audit_note: Arc<Mutex<String>>,
|
pub last_audit_note: Arc<Mutex<String>>,
|
||||||
pub audit_guid: 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)]
|
#[derive(Clone)]
|
||||||
|
|||||||
Reference in New Issue
Block a user