Files
rustdesk/flutter/test/cursor_replay_test.dart
RustDeskandClaude Opus 5.5 e9ddbd8f46 cursor: bound the decoded cursor caches on the Flutter client (#16304)
* cursor: name a shape by what it looks like, not by its handle

A cursor id was the platform's handle for the shape: HCURSOR on
Windows, the XFixes serial on X11. Apps mint a new handle for a shape
they have shown before (Chrome, Electron, Qt custom cursors), and an
X11 animated cursor gets one per frame, so one arrow arrived under
thousands of ids over a session. The controlled side cached and sent
it again under each, and the controller decoded, rendered and kept it
again under each, and grew by gigabytes over weeks of connection.

The controlled side now names a shape by an xxh3 hash of its size,
hotspot and pixels, taken once when a handle is first seen, before
the pixels are compressed. The per-connection send already sends a
shape once and afterwards only its id, so a shape now crosses once
however many handles it has. The id is opaque in the protocol, so
controllers of any version accept it. The DRM backend already named
shapes by content with FNV-1a; it uses the same hash now.

A peer before 1.5.0 still names shapes by handle, and the fix has to
work against every deployed peer. For those peers the controller
hashes each CursorData's compressed colors with its geometry: one
peer compresses the same pixels to the same bytes, so a shape seen
before is recognised without being decompressed. The UI gets that
shape once, under one id, and every later handle for it is passed on
as a cursor_id of that id. The map from the peer's ids is kept for the
connection, unbounded, since the peer sends a shape once and may
select any id it named again; an entry is two integers. From 1.5.0
the controller passes the peer's ids through unchanged, on the old
path.

The web core in flutter/web does the same in its own tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: hold a content id to what the web client can read

The web client decodes a u64 into a JS number and throws on a value
past 2^53, which drops the whole message. A full 64-bit xxh3 id is
almost always past it, so a web client connected to a peer on this
build would never have been given a cursor shape. DRM's ids were
already full width, so web clients lost the cursor on DRM peers too;
the controlled side now renames those as well.

The id keeps the hash's low 53 bits. Two of ten thousand distinct
shapes then collide with a chance of about one in two hundred million.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: hand the UI a shape's pixels as they are, not as text

A shape's pixels went to the Flutter UI as a JSON array of integers
inside the cursor_data event: the core serialised a 1 MiB shape into
up to 4 MiB of text on the receive loop, and the UI parsed that into a
million-element list and copied it into bytes, on the UI thread. The
event, text and all, was then kept for the session so that a tab
moved to another window could replay it, and a reconnect, on which the
peer sends every shape again, appended another copy of each.

The core now sends a shape as an EventToUI::Cursor variant carrying
Vec<u8>, which flutter_rust_bridge hands to Dart as a Uint8List, on
the same per-session stream as the events so that it keeps its order
with the cursor_id events around it. The web core calls onCursorData
with the Uint8Array, as it calls onRgba for a frame. The id stays
text, since the peer's ids can exceed Dart's int.

The replay keeps each shape's pixels once, by id, and encodes them as
base64 only when a tab moves. A shape arriving is also recorded as the
last one selected, since the replay goes in first-seen order; before,
a tab moved right after a new shape came back on the previous one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let a controller ask the peer for a shape again

A peer sends each shape once per connection and afterwards only its
id, so a controller must keep every shape it was sent for as long as
it is connected. The controlled side now answers
Misc::request_cursor_data with the CursorData of that id, from the
shapes it has sent, and only to a connection the cursor service
would send it to. A controller from 1.5.0 on can then bound what it
keeps and ask again for a shape it let go. None asks yet: the peer has
to have the answer before a controller can rely on it, and peers are
updated last.

The shapes are kept by content id, and every handle for a shape
shares its one message, where each handle used to keep its own copy.
They are dropped with the service's own cache.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep a shape as its ui.Image and nothing else

Each shape the UI had been sent stayed in four copies for the session:
the pixels for a tab move, an image package copy to resize from (on a
macOS or Linux controller of a Windows or Linux peer, a second one
decoded back from a PNG), the bytes handed to the native cursor, and
the ui.Image painted when the peer moves the pointer.

A shape now keeps only its ui.Image. The resize source and the native
bytes exist while a native cursor is being registered and are dropped
once it is; a shape shown again at a raster it was registered at needs
neither. For a raster it lacks, the pixels are read back from the
ui.Image, which returns them exactly as they came. A tab move reads
every shape back the same way, and the moved window decodes them as
it would have on arrival.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: pin that a released shape keeps neither its pixels nor its bytes

The shape in use once registered, the shapes not in use, and the
pixels read back for a moved tab are all dropped; the tests now say so,
so that a later change keeping one of them fails.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep one native cursor per shape, and each tab its own

A shape got a native cursor for every raster it was shown at, and all
of them stayed until the session ended, so every zoom or DPR change
added a native cursor for each shape in use. A shape now keeps the one
at its current raster; the one it replaces is deleted the next time a
cursor already registered is built, by when its successor has been
activated. A raster returned to before that takes its cursor back
instead of registering another under the same name.

The native cursors of a window's engine are shared by its tabs, and
the predefined cursors had one name in all of them, so a tab closing
deleted the default and forbidden cursors the other tabs still showed.
Names are now scoped to the tab's cursor model.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep the shapes compressed in the core, and only the one in use in the UI

The UI kept every shape as a ui.Image, one raw copy each, for as long
as the session lasted, because the peer sends a shape once and a
shape might have to be drawn again. The core receives the shapes
compressed, at a few hundredths of that, and now keeps them so:
Session::cursor_shapes holds each shape that decoded, as the peer sent
it, under the id the UI knows it by. The colors are copied, since the
message's may be a slice of a larger received buffer.

The UI keeps a ui.Image for the shape in use alone. A shape shown
again at a raster its native cursor has needs no pixels at all; for a
raster it lacks, for painting it, or for the window a tab moved to,
the UI asks the core through session_get_cursor_shape, which
decompresses and checks the shape again with decode_cursor_data, the
same size and decompression limits as on arrival. A shape the core
cannot give is not asked for again until the peer sends it. A tab
move now carries only the id in use, and nothing is read back from
the GPU.

The web core keeps the shapes the same way and gives them back through
getCursorShape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a decode that finishes after the session clears keeps nothing

A shape asked of the core while a tab closed was decoded after the
cursor model had been cleared and stored in it, where nothing disposed
of its ui.Image again; a shape whose cache failed to build left its
ui.Image undisposed as well. A clear now starts a new generation, and a
fetch or decode from an earlier one disposes what it made. A shape the
core gave but that did not decode is not asked for again on every
frame it is painted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep a native cursor for the shape in use alone

Every shape the peer showed kept a native cursor for the session, each
a raster the size of the shape as displayed. A shape switched away
from now gives its native cursor up the way a replaced raster does:
deleted the next time a cursor already registered is built, taken back
if the shape returns first. A shape shown again after that is rebuilt
from the compressed copy the core keeps. The predefined cursors are
not the peer's shapes and stay registered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep the native cursors of the 16 shapes used last

Keeping a native cursor for the shape in use alone rebuilt one on
nearly every switch, since the pointer moves among a few shapes: the
arrow, text, hand, four resize arrows, wait. The native cursors of the
peer's shapes are now kept in order of use, 16 of them, and the one
used longest ago gives its cursor up the way a replaced raster does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: forget the native cursors a session clear deletes

The clear deleted every registered native cursor but kept their names,
so a cursor model used again, as the mobile client's is, took each
name for registered and showed a cursor that no longer existed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: hold a native cursor to 512 pixels a side

A native cursor could be registered up to 1024 pixels a side, four
MiB of pixels each, which with sixteen kept made 64 MiB at worst. The
largest cursor a system shows is 256 pixels (Windows' largest pointer
size), so a raster twice that is shown no larger: the cursor is drawn
smaller rather than rejected, and sixteen kept come to 16 MiB at most.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a shape switched away from while it decodes is not marked lost

A shape asked of the core was taken for undecodable when it was no
longer kept once its decode finished, but a shape the peer switched
away from in the meantime is let go on purpose, and marking it made
every later request for it be skipped: its native cursor stayed
deferred and its painted cursor missing for the rest of the session.
The decode now reports whether it decoded, and only a failure marks
the shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* flutter: leave two untouched signatures as they were

dart format had rewrapped registerEventHandler and sessionSetCommon
next to the cursor additions.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: read a shape's pixels from where its view starts

The pixels used to be copied out of the JSON event into a fresh list,
so the list's buffer began at its first pixel. Now they come straight
from the core, native or web, as whatever Uint8List it hands over, and
img2's fromBytes takes the buffer, not the list, so a view into a
larger buffer would have been read from the buffer's start. Neither
core gives a view today; this stops depending on that.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a DRM cache reset keeps the shape it was making room for

The shape being sent was filed in CURSOR_SHAPES before the DRM ceiling
cleared it with everything else, so a controller asking for the shape
on screen got nothing until the next new shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: delete a replaced native cursor at the next build that shows one

A replaced native cursor was deleted only by a build of a cursor
already registered, so a run of new shapes, each shown once, left
every replaced cursor registered: 16 on the books, all of them in the
system. Now every build that shows a cursor deletes the ones replaced
before it, right before it registers or takes one back; what replaced
them was activated in an earlier frame, so they are off screen. A
build that has to ask for pixels shows nothing new and deletes
nothing, so a raster returned to right after being replaced still
takes its cursor back; one returned to later registers again.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: a shape that does not decode leaves no handle and no copy

CursorDedupe named a handle as it hashed the shape, before the shape
was checked, so a peer sending shapes that fail the checks under new
handles grew the map with nothing the UI could ever select, and such
a shape took over the handle of one that had decoded. The handle is
now named once its shape decoded, or was shown before.

The flutter build also copied a shape's compressed colors out of the
message before the checks, so a message with a small size and huge
colors was copied whole before being rejected. The copy is made once
the shape decoded; until then the message's own bytes are held.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: remember the shape the core lacks only while it is in use

Every id the core could not give was kept in a set for the session,
so a peer sending cursor_id after cursor_id of shapes it never sent
grew it by a string each, at a few bytes of traffic per entry. The
mark exists so that painting does not ask for the shape in use on
every frame, and the shape in use is one, so one mark is kept: the
peer selecting another shape forgets it, and selecting a lost shape
again asks once more.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: forget the shape the core lacks once the peer selects another

The mark was replaced only by another shape the core lacked, so a
lost shape selected again after a known one was still not asked for.
Selecting any other shape now clears it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: leave the DRM cursor's own id as it was

The wire id is cursor_content_id whatever the platform, set in
run_cursor over the shape's pixels, so the id the DRM reader derives
for itself only tells one hardware cursor from the next and keys the
service's cache. Which hash it uses does not reach a controller; the
change to xxh3 and the dependency it brought to scrap go.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: say the 1.5.0 gate means the release

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: say why the peer answers request_cursor_data with what it holds

No controller sends it yet, and a review asked for it to go because a
cache reset on the peer could leave a request unanswered. A shape the
peer's cache dropped is rebuilt, and indexed again, the next time it
is shown, before any connection names it by id, so the shape a
controller has just been told to show is always there to give; that
is the contract a future bounded controller relies on.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: drop the tests nothing can fail

a_handle_is_named_once_its_shape_is_shown dates from when `name`
wrote the handle map. `name` is pure now, so its last assertion
cannot fail, and the others repeat two neighbours.
every_handle_the_peer_named_stays_for_the_connection fails only for
a bound added on purpose, which the struct's doc rules out. The Dart
arrival test is covered by the first test of its file.

The kept-shape test now asserts what `cursor_shape` is for, a copy
rather than a view of the received buffer, in place of the unknown
fields it drops. The content-id test moves out from between two
`use` lines.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let the kept-shape tests run without the flutter feature

CI's cargo test builds the default features, and the two functions
under test are pure, so they compile for every test build and the
module loses its feature gate.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep native cursors for every frame of an animated cursor

An animated cursor is a shape per frame, 18 for the Windows busy cursor
and 23 for KDE's wait cursor. With 16 native cursors a cycle longer than
that missed on every frame: fetched from the core, decoded, registered
again and the replaced cursor deleted, about thirty times a second for
as long as the peer was busy. 64 holds two such animations and the
everyday set besides.

The tests settle in 10 ms instead of 100 ms, so the ones that fill the
limit stay quick.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: release only the shapes that can hold pixels

Selecting a cursor swept every shape of the session to release pixels,
though only two can hold any: the shape selected before, and a shape
that finished decoding after the peer moved on. Release those, so a
cursor_id costs the same however many shapes the peer has shown.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: show the native cursor limit holds two animations and the everyday set

64 is a working set, not the longest animation: KDE's wait and progress
cursors are 23 frames each, and a session that meets both plus a dozen
static shapes must keep them all, or every turn rebuilds.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let the shape in use keep its pixels for a new raster

Dropping them once the native cursor was registered meant every scale
change, zooming with the cursor zoomed or crossing to a display of
another scale, showed the system arrow while the core gave the shape
back and it decoded again. The shape in use now keeps them and makes the
new raster at once; a shape switched away from still keeps none.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: never fall back to the default cursor on a switch

A switch to a shape without its image, or without a native cursor at
its raster, showed the default arrow until the core gave the shape back
and it decoded: the painted cursor on every switch back, the native one
after an eviction or while a new shape decoded.

- The shape shown before stays, image, hotspot and native cursor, until
  the one in use is ready.
- Where the cursor is painted, on mobile or with the remote cursor
  shown, the images of the 64 shapes used last are kept, like the native
  cursors, so an animation does not decode a frame per turn. Elsewhere
  only the shape in use keeps one.
- A shape that finishes decoding after the peer moved on is kept with
  them instead of dropped, so a fast animation fills them at all.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: name the dedupe's content-id set for what it holds

`shown` read as the shape on screen. It is the shapes decoded and given
to the UI, keyed by content id, so a shape arriving under a new handle
is looked up once instead of scanning the handle map: `decoded`,
`has_decoded`, and `record` for the call that fills both maps. The web
mirror is renamed the same way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: keep native cursors for the session, as before

Evicting native cursors and deleting a shape's replaced raster made
Windows leak more than master. The engine's deleteCustomCursor/windows
frees the HCURSOR with DeleteObject, which does not take a cursor, so a
delete frees nothing and each cursor made again for a raster, or for a
shape shown once more, leaks another handle. Keeping every raster of
every shape until the session is cleared creates each one once, as
master does.

Fixing the engine instead is not cheap: x64 runs our fork on Flutter
3.24, where the fix is one more patch to rebuild and carry across every
upgrade; arm64 runs the stock engine of a newer Flutter with the same
code, where it means porting the fork and publishing an arm64 engine
too, or waiting for an upstream fix to reach stable. Content ids keep
the count to the shapes the peer really shows.

The painted images, the compressed shapes in the core, and a switch
showing the cursor shown before are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: record the Windows measurement behind keeping native cursors

A measurement on Windows confirmed what the engine source implied: of
500 cursors made by CreateIconIndirect, DeleteObject freed none and
left 500 USER objects alive, while DestroyCursor and DestroyIcon freed
all 500. The comment now says so, that native cursors have no LRU for
that reason only, and that one can come back once both engines destroy
cursors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: look a native cursor up by the raster asked for

The key ended in the raster made last. A shape switched away from keeps
no pixels, so its raster stays where it was, and going back to a raster
it was shown at before looked up the wrong key: A at 1.0, A at 0.5, then
B, then A at 1.0 again missed the 32x32 cursor that was still there,
fetched A from the core, and showed B meanwhile. With native cursors
kept for every raster, the key now ends in the raster asked for; with
pixels, that is the raster made, as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let a shape keep its pixels until a native cursor holds them

A shape switched away from, or decoded after the peer moved on, let its
pixels go whether or not it had a native cursor, and a native cursor is
made only for the shape in use. A shape whose restore kept finishing
after the next switch, as an animation's frames can, was fetched and
decoded again every time it came back and never got a native cursor.

A shape without one now keeps its pixels until one is made, at most
kRecentShapes of them, the one waiting longest let go first. Mobile
only paints the cursor, so it lets them go as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* proto: keep cursor ids as strings in JS

A Windows peer before 1.5.0 names a cursor by its handle, sign-extended
above 2^53 when its top bit is set. The web client decodes u64 fields
into JS numbers, and ts-proto throws on a value a number cannot hold,
so each such cursor_data or cursor_id was dropped whole and the web
cursor stayed on the shape before. [jstype = JS_STRING] makes ts-proto
generate these two fields as strings; the wire format, the Rust code
generated and every other client are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: wait for a native cursor at the raster asked for, not any raster

A shape let its pixels go once it had a native cursor at some raster.
After a zoom, or on a display of another scale, an animation's frames
had native cursors at the old raster only; each was fetched again at
the new one, and a restore that finished after the next switch let its
pixels go at once, so the frames never got a native cursor at the new
raster and the cursor stayed on the one shown before. A lookup that
finds no native cursor at the raster asked for now counts the shape as
waiting for one, so a late restore keeps its pixels until it has one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: count a shape held again when its asked raster has a native cursor

A lookup that missed took the shape out of _nativeIds, but one that hit
did not put it back. A shape asked at a new raster, then at one it has a
native cursor for, still counted as waiting: a restore finishing after
the switch away kept its pixels in _awaitingNative instead of letting
them go. The set now says whether the raster asked last has a native
cursor, either way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* Revert "cursor: count a shape held again when its asked raster has a native cursor"

This reverts commit 7cefbfc7a.

_nativeIds is meant as "no raster of this shape is still missing its
native cursor", not "the raster asked last has one". A shape asked at a
new raster whose restore is on its way, then shown at a raster it has a
cursor for, still waits for the new one; counting it held let the late
restore's pixels go, so going back to the new raster fetched it again,
and with an animation's frames and a scale that keeps changing, the
loop 1e4388771 fixed could come back. Keeping the pixels costs at most
a waiting slot, within the 64. A test now locks this: a raster still
missing keeps a late restore whatever was shown meanwhile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: reuse a shape sent before without compressing it again

A handle not seen before sent the service through the whole path:
capture the pixels, name them by content, compress them, and only then
find the shape already in CURSOR_SHAPES and drop what it compressed. An
app that mints a new handle for the same cursor, as Chrome and Electron
do, paid a compress per handle, a few ms for an enlarged cursor. The
content id is now looked up first, and only a new shape is compressed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: bound the handles the service files, and the shapes with them

A platform may mint a new handle each time it shows a shape, as Chrome
and Electron do, so cached_cursor_data grew by an entry per handle for
the life of the service, even when every one named the same shape; and
the compressed shapes in CURSOR_SHAPES were bounded by nothing but the
handles. Past 4096 handles, or 32 MiB of compressed shapes however few
the handles, both start over together, keeping the shape being sent: a
handle shown again is captured and named again. On every platform; the
DRM build's own 64-entry ceiling is unchanged and comes first there.

CURSOR_SHAPES keeps the bytes it holds beside the shapes, cleared with
them, so every path that clears it resets the count.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: let the macOS seed report a change, and the content name the cursor

macOS named a cursor by a fingerprint of its size, hotspot and two
pixels near the hotspot. It collides between standard cursors: the open
and the closed hand give one value, and the arrows with a badge (copy,
not allowed, contextual menu, disappearing item) another, so a switch
between them was never sent, or a cached shape of the other was.
CGSCurrentCursorSeed already says when the cursor changed; get_cursor
now reports the seed, and the shape is named by its content, as on
every platform. The fingerprint is gone.

get_cursor_data checks the seed before and after the capture. The seed
was taken before capturing, so a capture that found the cursor changed
again lost the change; it now leaves it for the next poll.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: file no macOS seeds, and send nothing for the shape already shown

A macOS seed marks a change and never comes back, so filing it as a
handle only filled the map; the byte ceiling still bounds the shapes
there. A new handle or seed for the shape already shown, which a seed
change without a new shape or an app minting handles gives, sent every
connection a cursor_id for what it already showed; a shape is one
message however many handles name it, so the same message is not sent
again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: capture the macOS cursor shown without checking the seed around it

Every macOS seed change is now captured, pixel by pixel, and a seed
that moved during that capture failed it; the service then logged an
error and slept a second, so the controller's cursor lagged while it
changed. The check guarded nothing: the shape is named by its content,
not the seed, and a change after get_cursor read the seed moves it on,
so the next poll captures it anyway. Resetting the seed on a failed
check was not needed for the same reason.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: fall back to the default cursor for a shape the core cannot give

The shape shown before stays while the one in use decodes, so a switch
does not flash the default cursor. It also stayed once the shape in use
was known to be lost (rejected by the core, or not decoding): the
controller kept drawing, say, an I-beam for a pointer it never got,
until the peer changed shape. Both the native and the painted cursor
now leave the default one, as master did for the native cursor. A shape
that does not decode is marked in updateCursorData, whether it was sent
or fetched again, so both paths agree.

The client also selects a shape it rejects as it arrives. It showed the
shape before until the peer selected the rejected one again, and the
default cursor from then on; it now looks the same both times. Sciter
ignores an id it has no shape for, as it did.

The default and forbidden cursors are made with the model. They were
made the first time a build asked for one, and their decode lands
later with nothing to draw again, so that first build showed the shape
before in their place.

A fetch failing after the session was cleared marks nothing in the new
one, and a fetch that throws at once tells the listeners after the
build that asked for it, not during it.

The forbidden cursor, shown while input is off, became the cursor shown
last, so a raster made after input came back showed it until the
shape's pixels were fetched, or for good if they never came. Only a
shape stands in for a shape now; CursorModel.shown keeps the rule for
both builders.

_checkView asks for a single registration again: every native cursor
is made once per session, and one made twice leaks an HCURSOR on
Windows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: name a handle by the shape rejected under it, not the one before

A shape the client rejects is selected as it arrives, so that it shows
the default cursor then as it does later. Under a handle reused for it,
the dedupe still named the shape the handle had brought before, and
selecting that switched the pointer to an old shape: A under handle 7,
then B under 8, then a rejected C under 7 showed A in place of B, and
again whenever the peer selected 7.

The handle now names the rejected content, which is never marked
decoded, since only a shape not decoded before reaches the decode: the
UI has no shape under it and shows the default cursor, then and when
the handle is selected again. The shape the handle named before stays
kept for the other handles naming it, and a handle that brings it again
names it again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: file no handle for a shape that is rejected under it

A shape rejected under a handle named the handle by the rejected
content, so that a known handle does not show the shape it brought
before. A handle never seen was filed the same way, so a peer sending
shapes that do not decode under new handles grew the map with each,
where a rejected shape used to leave nothing. Only a known handle is
renamed now; one never seen is not filed and is passed on as unknown,
which the UI shows as the default cursor.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

* cursor: say what Future.sync defers, and give the default cursor time on a slow runner

The comment on the fetch in restorePixels read as if the fetch were put
off; it runs at once, and Future.sync only turns its throw into an error
the await hands over later, which is what keeps the notify out of the
build.

cursor_default_test gave the default cursor 100 ms to decode, which a
slow runner may miss. It cannot wait for the cursor itself, since asking
for it would make it; it now waits 500 ms.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EZ49AbZJYfm8NTp5yDPMab

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 12:09:46 +08:00

684 lines
23 KiB
Dart

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');
});
});
}