108 Commits
Author SHA1 Message Date
nessarandClaude Opus 5.5 6d2605adfa Record the final 1.0 benchmark and GPUI's floor for budget 3 (#32)
CI / core (push) Successful in 1m36s
On the reference laptop, the release build of b8e4927 holds the five
budgets. Minimised, the app skips the paint but GPUI's vsync thread still
wakes the window: by the user's decision, budget 3's CPU limit is GPUI's
floor, 1.1 % minimised and 0.35 % hidden. Budget 4 passes at the
scenario's point only: « Défi » with the grid scrolled to its end still
holds 170-174 MB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:58:01 +01:00
nessarandClaude Opus 5.5 a6b396ab1e Make the 1.0 frame cost budget 1 (#32)
CI / core (push) Successful in 1m33s
An empty page costs GPUI 1.41 ms at the 99th percentile on the reference
laptop, and a window move redraws the whole page without its cached
views: 2 ms could not be held without simplifying the page or changing
GPUI's behaviour. By the user's decision, the limit is the 1.0 value,
6 ms at the 99th percentile for a frame drawn, to lower after 1.0 (#106).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:31:39 +01:00
nessarandClaude Opus 5.5 b8e49276ab Hold only the table's shown portraits (#32)
CI / core (push) Successful in 1m37s
The champion table drew its 128 px portraits through GPUI's app-wide
image cache, which keeps every image it ever loaded: once « Statistiques »
had been scrolled through, all 173 stayed decoded and in the atlas, about
25 MB on the reference laptop (budget 4). The table now reads them
through its own CardImages, as the card grids do: only the rows it paints
keep theirs, and it gives them back when « Défi » or « Paramètres » is
shown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:20:30 +01:00
nessarandClaude Opus 5.5 f53db09d3e Skip GPUI's paint while the window is minimised (#32)
CI / core (push) Successful in 1m37s
GPUI's vsync thread invalidates the window at every vsync, minimised too,
and each WM_PAINT went through GPUI, which has no frame to draw then, and
DefWindowProc: the UI thread spent more minimised than visible (budget 3).
A subclass validates the paint while the window is iconic. On the manual
checks machine (240 Hz), minimised: 3.03 % of one core before, 0.22 %
after; the window draws again on restore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:17:10 +01:00
nessarandClaude Opus 5.5 6311f01b49 Make GPUI's idle floor budget 2 (#32)
Idle with the window visible, every wake-up is GPUI's vsync thread and
the paint it asks for: 0.7 to 1.1 % of one core on the reference laptop,
which cannot be lowered without modifying GPUI (ADR-0004). As #32
provides, and by the user's decision, the floor becomes the limit:
1.1 %, lowered again as soon as GPUI's floor drops.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:17:10 +01:00
nessarandClaude Opus 5.5 245d8ac64a Record the Windows trials of 2026-11-23 (#62)
Trials 1 to 5, 7, 8 and 10 to 13 pass on the build PC, driven from WSL
by posted clicks and window captures, on the maintainer's administrator
account with real data. Trial 9 and the network cut of trial 2 were set
aside; trials 6 and 14 wait for the 1.0.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:16:45 +01:00
nessarandClaude Opus 5.5 c97b9cb4cb Say that Velopack stops the app instead of waiting for it (#62)
Velopack 1.2.161 logs « Access is denied » when it waits for the app at
each apply, although the process can be waited on with SYNCHRONIZE, and
goes straight to force-stopping what runs from the installation. The app
has quit by then, and a forced stop loses no data: config.toml is written
aside then renamed, and Matches are in SQLite transactions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:16:45 +01:00
nessarandClaude Opus 5.5 f6973b162b Record beta 5 (#62)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 10:16:45 +01:00
nessarandClaude Opus 5.5 2b40dcf2d3 Record the 1.0 release benchmark on the reference laptop (#32)
Measured 995f454 (1.0.0-beta.5) on the Ryzen 5 7640U, release build and
its profile build. Budgets 1, 2, 4 and the minimised CPU of budget 3 are
over; budget 5 and the no-rendering part of budget 3 hold. Idle CPU has
a floor set by GPUI's vsync thread, recorded without changing the limit.
The scenarios are written down under Measuring, with
scripts/budget-probe.ps1 to repeat them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3E5kSZykyLnuoXsBC2
2026-11-23 09:52:20 +01:00
nessarandClaude Opus 5.5 995f454a9c Run the channel trials on the installed beta first (#62)
CI / core (pull_request) Successful in 1m32s
CI / core (push) Successful in 1m37s
The build PC already went from beta 3 to beta 4 by « Redémarrer », and
runs beta 4: trials 3 to 5 use it with beta 5 published. Trials that need
a ready update then reinstall A, which updates straight to the latest beta.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 08:55:11 +01:00
nessarandClaude Opus 5.5 9c85104161 Try the update path with betas 3, 4 and 5 (#62)
CI / core (pull_request) Successful in 1m34s
Beta 3 was already published when beta 4 was, so beta 1 would now update
straight to beta 4. A is beta 3, B beta 4 and C beta 5, published after
trial 2; B and C carry the on-demand update check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 08:49:22 +01:00
nessarandClaude Opus 5.5 70baa311ae Record beta 2 and document the update check button (#62)
CI / core (pull_request) Successful in 1m34s
B is 1.0.0-beta.2, published on 2026-11-22 with its four files. The user
guide now says that « Rechercher une mise à jour » runs the check on demand
and that a failed check leaves a ready update ready.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0192He3DgZBggc9wJG9c1nqA
2026-11-23 08:46:35 +01:00
nessarandClaude Opus 5.5 fe5683bc59 Document the user guide and the 1.0 release record (#62)
Add a user guide (install, channel choice, « Mise à jour prête »,
« Redémarrer », closing to the notification area, data kept) and the 1.0
release record: versions tried, the access used for trials, the Windows
test protocol with empty results, the #32 gate and the unauthenticated
check of the public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 08:46:15 +01:00
nessarandClaude Sonnet 5.5 1ad36bdd5a Add a button to check for an update from the settings
CI / core (pull_request) Successful in 1m40s
CI / core (push) Successful in 1m42s
The check ran only at launch and on a channel change, so an app left
open never saw a release published since. « Rechercher une mise à jour »
runs the same check on demand, through the same gate, and the settings
now say how the last check ended: running, up to date, or why it failed.
A failed check leaves a ready update ready.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-23 08:40:24 +01:00
nessarandClaude Sonnet 5.5 2c9ca4552c Address review of the champ select page scroll
CI / core (pull_request) Successful in 47s
CI / core (push) Successful in 45s
- Draw the section's grid again once the draw that moved it is over: a notify
  inside a draw dirties nothing for the next one, so its rows stayed those of
  the former place.
- Keep the first row of a grid wholly below the window built, so that Tab from
  the search enters it, and scroll the page to any card the keyboard focuses.
- Leave the scrollbar its own lane in the Anvil and « Autres champions »
  sections, so it no longer covers the sort selector, and make it a view of
  its own so that its fade does not draw the whole page.
- Store the page's Paging once; correct the performance notes on scrolling.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 19:18:35 +01:00
nessarandClaude Sonnet 5.5 15feaee8bf Scroll the whole champ select as one page
The banner, the Anvil champions and « Autres champions » now move together
on one wheel and one scrollbar. The section's grid holds no scrolling of its
own: it is as tall as all its rows and builds only those the page has in view,
read at its own render, so portraits stay in proportion to what is shown.
Its keyboard code moves to card_grid/focus.rs to keep card_grid.rs under 500
lines.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 19:01:55 +01:00
nessarandClaude Opus 5.5 e7ff365069 Settle names and module homes after third review (#103)
CI / core (pull_request) Successful in 1m34s
CI / core (push) Successful in 1m35s
- Rename CardPosition/CardPositions/positions() to DrawnCard/DrawnCards/
  drawn_cards(): "position" is a word CONTEXT.md avoids for Placement.
- Move the Account and status queries from page/statistics/scope.rs to
  page/displayed.rs, since the whole page uses them.
- Move the home's own statistics state (settle_home_scope, set_home_result,
  forget_home, home_is_current) to page/home/data.rs, leaving home.rs to
  queries and rendering.
- Move the profiling flag shown() from display.rs to page/profiling.rs.
- Narrow Page::new to pub(crate), and restore the domain phrase in the
  same_riot_id doc comment and the page.rs module doc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 18:16:00 +01:00
nessar 242ecc4f28 Tighten module organization after second review (#103)
CI / core (pull_request) Successful in 1m35s
2026-11-22 18:06:44 +01:00
nessar e56da040e5 Address module split review on #103
CI / core (pull_request) Successful in 1m37s
2026-11-22 17:20:58 +01:00
nessar e43dd4510b Document Rust test layout
CI / core (pull_request) Successful in 1m31s
2026-11-22 16:58:12 +01:00
nessar c716c2c759 Group core integration tests by behavior (#102) 2026-11-22 16:49:32 +01:00
nessar 4548b6ac64 Split large core modules into focused child modules (#102) 2026-11-22 16:49:32 +01:00
nessar b9023c1d15 Split large application modules and their tests (#102) 2026-11-22 16:49:32 +01:00
nessar d0311888bb Split Page code and test suites by responsibility (#102) 2026-11-22 16:49:32 +01:00
nessar fb9c2b3cf7 Extract league client and ring test modules (#102) 2026-11-22 16:32:09 +01:00
nessar 40e8f88a98 Require focused Rust modules as files grow
CI / core (push) Successful in 1m38s
2026-11-22 16:20:40 +01:00
nessarandClaude Opus 5.5 3965b7bcc2 Let each card leave from where it is and build no card out of sight (#87)
CI / core (pull_request) Successful in 1m36s
CI / core (push) Successful in 1m36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:15:41 +01:00
nessarandClaude Opus 5.5 debf3c5232 Let the hand leave from where it is and keep the pointer's last word (#87)
Review of PR #100:
- an exit during the deal takes the moving cards down from where they are;
- an ally's confirmation lowers and greys a card lifted under the pointer too;
- the pointer moving forgets the card the keyboard waited for;
- the band of light crosses the whole window, title bar included, over the
  hand's moving cards;
- no sort, copy of a card or search of the hand per frame;
- one helper prepaints a card for both overlays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:12:24 +01:00
nessarandClaude Opus 5.5 b1c5c3a8cc Deal the hand at a champ select's entry and let it leave at its end (#87)
The entry plays once the window shows the champ select (not behind
« Paramètres »): a band of gold light sweeps the page in 900 ms, the
title comes in rising 8 px, and the Anvil champions come up from the
bottom of the window, the first at 380 ms then one every 110 ms. A card
still dealt is lifted once in its place; reasons arriving meanwhile show
on their card without dealing again, and cards arriving late with the
statistics are dealt from then.

An ally's confirmation lowers its card of the hand 8 px as it greys,
where it then rests. At the end, the hand leaves from the last card,
then the veil of the tabs covers the champ select and the end is applied
under it, the home coming back as #74 leaves it.

The moving cards are drawn by the page over the cached hand, from where
the grid placed them (`stage.rs`, as `card_lift`): the grid is never
drawn again for them, no statistics are computed, and no frame is asked
at rest. The Windows setting off, a hidden window or a covered page show
the end state at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-22 16:12:05 +01:00
nessarandClaude Opus 5.5 ee2ab5cc33 Prepare the held grid on arrival and keep the followed game apart from older Matches (#89)
CI / core (pull_request) Successful in 1m33s
CI / core (push) Successful in 1m36s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:06:03 +01:00
nessarandClaude Opus 5.5 44c2d10b3b Play the strongest Match on its own champion and report every followed game (#89)
CI / core (pull_request) Successful in 1m40s
From the review of PR #99:
- Of several followed Matches waiting, the strongest plays on its own
  champion (tick, card and splash), the most recent among equals. The
  comet no longer flies to one champion's tick with another's splash.
- A game the client gave no id for, or seen before any Match gave the
  platform, is reported when the sync stores it: the client's id when
  it has one, else the newest Match newer than every one stored. A
  first import without that id stays history.
- What a Match brought comes from the Challenge's own Marks, with and
  without it, instead of a second set of rules in SQL; `fetch_and_store`
  is back to fetching and storing. `MatchEnd::Completed` takes the
  glossary's word, and its variants are documented again.
- Only the count of the banner's title rolls in, from 10 px below, as
  in the prototype; the « Dernière Partie » line still fades in.
- The Windows setting is checked where a Match is queued, and the tests
  now go through the follower round and the statistics; a test checks
  that the end state is what a reload shows.
- The Match's state is one `MatchPlayback`, ended in one place; the
  durations are named; `MarkFill`, `Changing` and `RevealFrame` replace
  bare tuples; a splash that cannot be read ends its reveal.
- `follow_client_with` takes the report itself, without a forwarding
  function. docs/performance.md describes the Match animation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 15:16:04 +01:00
nessar 126912fd09 Animate the Challenge after a live Match ends (#89) 2026-11-22 15:16:04 +01:00
nessarandClaude Opus 5.5 aac2f4212c Offer to launch Arena Tracker at Windows logon (#67)
CI / core (pull_request) Successful in 1m38s
CI / core (push) Successful in 1m33s
Windows alone holds the choice: the Run entry, unless the Task Manager
disabled it under StartupApproved\Run. The settings read both when they
open; switching on writes the entry and approves it again.

Started with --logon, the app opens hidden in the notification area, or
minimized when there is no tray icon, and paints no page in the first
frame, so no portrait is decoded before the window is shown. An update
ready at logon is applied silently and reopens hidden. Installing or
uninstalling removes the entry; updates keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 00:50:07 +01:00
nessarandClaude Opus 5.5 2770a39760 Let a whole card of the first row rise out of the list (#88)
CI / core (pull_request) Successful in 1m44s
CI / core (push) Successful in 1m37s
A lifted card was cut where its grid cuts it unless the grid showed it
whole, tested as `visible.intersect(&bounds) == bounds`. With columns of
a fractional width, the intersection rebuilds the size by subtraction
and misses the card's own by a rounding error: the first row's lifted
card was cut at the list's top edge. The test now allows a pixel of
slack on each side.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-22 00:04:55 +01:00
nessarandClaude Opus 5.5 95bc4f6664 Read the lifted card from the grid and put it down more often (#88)
CI / core (pull_request) Successful in 1m38s
From the review of PR #97:
- A grid no longer shown, a card filtered out, or a wheel at either end
  of the list puts the grid's cards down at once (`PutDown`): no frame
  is asked for a card no longer drawn, and a wheel always puts it down
  while its tick stays lit under the pointer.
- The lifts hold card ids only. The grid records each placed card's
  index while it builds its rows, and the layer draws the grid's card as
  it is now: no search or copy per hover, and a lifted card shows a new
  top 1 or reason at once.
- A card the keyboard lifted goes down as soon as the pointer moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 23:29:48 +01:00
nessarandClaude Opus 5.5 162e689a40 Say that a hover no longer draws the home grid (#88)
CI / core (pull_request) Successful in 1m38s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 19:42:53 +01:00
nessarandClaude Opus 5.5 b78be1ff0b Lift the hovered card over a cached grid (#88)
The card under the pointer or the keyboard rises over its grid in about
0.35 s: 10 px with a gold glow, 4 px without for a greyed card, the
illustration zooming to 107 % inside it while the caption fades and the
sheet slides up over the lower half. Leaving it mid-way starts from where
it is; a wheel drops it at once; in the hand a veil lays on the other
cards. With Windows animations off the sheet shows without sliding and
the card stays put.

The grids never change on hover or focus any more: they record where
they placed their visible cards, and the page draws the lifted cards in
a deferred layer over them, asking for frames only while one moves.
Structural tests check that a hover, through its animation, draws no
grid, builds no card and computes no statistics.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 19:18:31 +01:00
nessarandClaude Opus 5.5 c2d6296723 Cache the table, prepare a screen when shown, keep the header still (#86)
CI / core (pull_request) Successful in 1m38s
CI / core (push) Successful in 1m39s
From the review of PR #96: the champion table becomes a cached view, so
the veil's frames no longer draw it; the screen arriving is prepared
only once shown, so a switch undone under the veil prepares nothing;
turning the Windows setting off drops the animation waiting as soon as
Windows says so; the Season and Format selectors move to the title row
of « Statistiques », under the veil, so the header keeps its height.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 18:51:42 +01:00
nessarandClaude Opus 5.5 d7f5e23aea End a transition when animations are turned off, read the screen drawn (#86)
From the review: the Windows setting turned off during a transition
ends it and drops the animation waiting; the errors and the official
count follow the screen drawn rather than the tab chosen; clearer names
for the veil's phases and the frames it asks for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 18:51:33 +01:00
nessarandClaude Opus 5.5 2ede37c521 Lay the animation foundation and veil the switch between tabs (#86)
Follow the Windows « Show animations » setting at start and on its
change, keep the strongest animation asked for while « Défi » is not
visible until it shows again, and switch tabs under a veil of the
page's background instead of fading or sliding the screen, which would
draw the cached views again at every frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 18:51:33 +01:00
nessarandClaude Opus 5.5 0f860fda15 Keep the ring lit without a list and test the banner on the real capture (#85)
CI / core (pull_request) Successful in 1m35s
CI / core (push) Successful in 1m37s
A champ select whose Anvil list the client did not send no longer dims every
tick of the ring. k takes the singular at 0 and 1, and the line uses the same
apostrophe as the row and its fallback message. Both banners write a default
split Season as « SAISON 2 · 2026 ».

The replay test now checks the capture's own hand (k stays at 1 across the
ally's confirmation), the default and hovered illustrations, the cards'
places and the ring's Anvil list. A unit test checks which ticks stay bright.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 18:37:06 +01:00
nessar d74da1bee1 Show the Arena champ select in the banner (#85)
CI / core (pull_request) Successful in 1m35s
2026-11-21 18:15:19 +01:00
nessarandClaude Opus 5.5 411d139a75 Keep the ring's shapes on scroll, free a hidden splash, keep the hover's grid (#84)
CI / core (pull_request) Successful in 1m42s
CI / core (push) Successful in 1m40s
From the second review of PR #94:
- The ring's fixed shapes are made at the origin and moved where it is
  painted: a scroll that moves the ring tessellates nothing.
- The banner's splash is neither decoded nor held while the banner is
  scrolled out of view, and is given back, from the atlas too.
- The tick follows the grid that lit it: another grid saying none of its
  cards is under the pointer, or « Autres champions » folding, leaves it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 17:53:46 +01:00
nessarandClaude Opus 5.5 4fb8b37509 Lighten the ring and the splash and follow the pointer and the scope (#84)
CI / core (pull_request) Successful in 1m36s
From the review of PR #94:
- The ring tessellates its fixed shapes once per set of ticks and size;
  a hover tessellates only the lit tick.
- The banner decodes its splash itself, one at a time, on GPUI's
  low-priority queue at below-normal thread priority: a splash asked
  for while another decodes waits, so two at most are ever held.
- Opening « Paramètres » gives back the splash and the grids' portraits.
- The grid has one hover transition: a card that leaves the grid puts
  its tick out, and a wheel that moves no card keeps it.
- The home column scrolls in a low window, so the grid stays reachable.
- Entering or leaving a champ select clears the banner until the new
  scope's statistics arrive.
- Tests: drawing the ring alone draws no grid and builds no card.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 15:50:58 +01:00
nessarandClaude Opus 5.5 d256dd61d2 Replace the home header with the banner and the ring (#84)
CI / core (pull_request) Successful in 1m32s
The banner shows the ring, a cached view with one tick per champion of
the Challenge in a fixed order, the Season, the « N / total champions
validés » title, the last Completed champion and the last Match, over
the splash of the last Completed champion, faded into the band. In a
narrow window the ring goes above the text and the splash covers the
banner. Hovering a card lights its tick.

The banner reads its splash through its own cache: two at most, the
one replaced given back from the GPU atlas too, none while
« Statistiques » is shown or without an illustration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 15:33:57 +01:00
nessarandClaude Opus 5.5 e28aefc3bc Expose the order of the completions and the Season's last Match (#84)
The Challenge's chronological pass that counts the Attempts now also
records the Completed champions in the order of their first top 1, and
what the Season's latest Match, all Formats, did to its champion: an
Attempt, the completing Match, or one played after completion.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01WYQB8paBcLk67XoAUYARBK
2026-11-21 15:33:57 +01:00
nessar cee9ff2989 Save splashes when loading art is missing and restore art notifications (#83)
CI / core (pull_request) Successful in 1m31s
CI / core (push) Successful in 1m40s
2026-11-21 14:26:59 +01:00
nessar e440d155fc Download champion splashes and cache their banner focus (#83)
CI / core (pull_request) Successful in 1m31s
2026-11-21 14:16:58 +01:00
nessar 3de8fd527c Document focus contrast and set row highlight opacity explicitly (#82)
CI / core (pull_request) Successful in 1m37s
CI / core (push) Successful in 1m32s
2026-11-21 13:56:57 +01:00
nessar eb21db17ad Strengthen theme contrast and cover the heading font fallback (#82)
CI / core (pull_request) Successful in 1m31s
2026-11-21 12:36:56 +01:00
nessar bfb29e02fe Apply the logo palette and Unbounded headings across the app (#82)
CI / core (pull_request) Successful in 1m33s
2026-11-21 12:14:04 +01:00
nessarandClaude Sonnet 5.5 48729f83ad Document the green-CI requirement to merge into develop and main
CI / core (pull_request) Successful in 1m38s
CI / core (push) Successful in 1m34s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 11:42:05 +01:00
nessarandClaude Sonnet 5.5 d42125724e Document the L'Anneau identity and version its reference page (#81)
CI / core (pull_request) Successful in 1m37s
CI / core (push) Successful in 1m31s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 11:33:12 +01:00
nessarandClaude Opus 5.5 8784c6eb6c Say how a champion absent from Riot's mastery list counts (#76)
CI / core (pull_request) Successful in 1m42s
CI / core (push) Successful in 1m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:28 +01:00
nessarandClaude Opus 5.5 72f7a239c0 Tell why the home has no cards yet and tidy the cards code after review (#72)
Without statistics the home said « Aucun champion trouvé » under a count of
0; it now shows the same notice as the champ select (loading, no Account),
from a small StatsNotice enum instead of compared strings.

Also from the review: a structural test that hovering or scrolling
« Autres champions » recomputes no statistics, as docs/performance.md says;
English comments; one card aspect (core's CARD_ASPECT) and one cards_dir;
one builder for the champ select cards, one count badge, one test temp dir;
clearer names (with_cards_behaviour, home_has_own_scope).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 213d693ab8 Record the fourth greying reason and what the redesign established (#74)
The spec gains « Indisponible », agreed for a champion the client does not
offer, and records what #74 and #76 established about the Anvil champions
list and the Mastery Points, with what is left to the Windows check.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 4612d89a3d Keep a whole row in "Autres champions" and tidy the cards code (#75)
- "Autres champions" grid is never shorter than one card row.
- A Format change keeps the home's statistics (#71); the home cards
  are built when "Defi" is shown again; hidden grids give back their
  decoded portraits; the card holds its portrait as Arc<Path>.
- Unavailability becomes Unpickable (glossary), "selection" becomes
  "champ select" in comments (#74); the statistics error is shown by
  the banner only during a champ select.
- Column breakpoints follow the mockup's max-width rules, the home
  tools row is search, filters, sort; stale comments fixed.
- Tests: whole row, hidden grids, stats scopes, error shown once, and
  the capture's reasons end to end in the open section.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 2cd8b2c545 Document the third cached grid and the portraits given back (#77)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 18b06f8ea6 Read the portraits folders once and stop the card pass offline (#77)
The statistics list the portraits folder and its cards subfolder once
instead of checking about 340 files. The tall-portrait pass is skipped
when the catalog refresh failed and stops at the first network error;
the core tells after each attempt whether a portrait was saved, so the
worker's throttle can tell the page after any attempt, not only saves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 485d7b9065 Show a missing-statistics notice once during a champ select (#75)
With the statistics missing, the Anvil area no longer repeats « Aucune Saison
en cours » when the header already says it, and « Autres champions » is not
offered since there is nothing to browse.

Test tidy-ups: the saved-portraits assertion message says what is checked,
main.rs tests use card_images' TestDir instead of their own TempDir, and the
test-only accessors of Page move after the last method so choose_sort reads
with its doc comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 28d86d48b7 Drop the champ select helpers the text view used (#74)
ChampSelect::remaining and current_row only served the text champ select
view that #74 removed. The follow test now looks the current pick up in the
statistics rows and builds the pickable, not Completed set from can_pick.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 a457a19fe5 Sort the cards by Mastery Points or A to Z and remember the choice (#76)
The statistics rows carry the Mastery Points: None for an Account whose
points were never fetched, Some(0) for a champion missing from the last
list. One card order, computed only when the statistics or the preference
change, feeds the home grid, the Anvil row and « Autres champions ». The
sort selector stays visible during a champ select, the choice is saved
with the other preferences, and the sheet shows the Mastery Points
(unknown ones after the known, and not as zero).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 02:26:14 +01:00
nessarandClaude Opus 5.5 815daf33cb Show the tall portraits on the cards, decoded only while shown (#77)
The champions thread downloads the card portraits after the square ones
and tells the page at most once a second while they arrive, plus once at
the end, so each shows without a restart. A card shows its tall portrait,
the square icon while it is missing, else its plain background.

Each card grid reads its portraits through its own image cache: only the
cards it paints are loaded, and what its previous render did not paint is
dropped at its next render, from the GPU atlas too, and all of it with the
grid.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:43:02 +01:00
nessarandClaude Opus 5.5 f1e8808082 Add the folding « Autres champions » section to the Arena champ select (#75)
Folded at each new selection, it lists the champions without an anvil (all of
them, as « Tous les champions », when the client gave no Anvil list) with the
anvil row's cards, order and greyed reasons. Its own search filters only this
section. Its cards are built only while it is open, in a cached virtualized
grid. The `others` profiling part is documented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:39:43 +01:00
nessarandClaude Opus 5.5 6f2a6244cc Show the Anvil champions as cards during an Arena champ select (#74)
The home takes the selection: the Challenge of the signed-in Account for the
current Season, then a row of the Anvil champions in the home grid's order with
the reasons Validé, Banni, Pris par un allié and Indisponible. The old text view
is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:32:51 +01:00
nessarandClaude Opus 5.5 05b8cc6d60 Hide the hovered sheet when the grid scrolls (#73)
A wheel scroll moves cards under a still pointer without a hover event, so
the sheet could stay on a card no longer under it. The grid now forgets the
hovered card on scroll; the next mouse move hovers the right one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:32:01 +01:00
nessarandClaude Opus 5.5 796fae11b7 Show the champion's sheet on hover and keyboard focus (#73)
The sheet covers the card with the Season's Matches, Wins, best Placement
and Attempts, and the date of the first top 1 for a Completed champion. Its
lines are prepared in Card::from_row; only the shown cards build it. The
grid keeps the hovered card and one focus handle per card id, and handles
Tab and Shift-Tab itself, scrolling the next card's row into view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:30:50 +01:00
nessarandClaude Opus 5.5 bd9f1c7c98 Show the home's champions as a grid of cards with Played and Win marks (#72)
Add the champion card (portrait, name, "Joué" and "Victoire" marks, greyed with
"Validé" once completed) and a cached, virtualised card grid that replaces the
home's table. Columns follow the window width as in the mockup. Cards are built
once per statistics change; hovering or scrolling only redraws the grid.
Profiling part `home-list` becomes `cards`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:21:16 +01:00
nessarandClaude Opus 5.5 bd4de1ec05 Tell why a champ select makes a champion unavailable (#74)
Split the excluded set into banned and taken_by_ally, add
ChampSelect::unavailability (banned, taken_by_ally, not_offered; never for
the player's own pick) and make the anvil list an Option so an unreadable
list is not read as an empty one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 9c13e14072 Document the profiling parts and the hover probe for the two tabs (#71)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 43a6b05f56 Split the home Challenge from the Statistics tab (#71)
The app opens on « Défi »: the Season of the Challenge, a one-line
counter with a thin progress line, and the champion table filtered by
Tous / Restants / Validés and a search of its own. A navigation of two
keyboard-focusable buttons leads to « Statistiques », which keeps the
analysis, with the charts now ordered curve, Placements, Attempts.

The home follows the Season chosen on Statistiques (the current one for
all Seasons) and ignores the Format. Its statistics come from the same
worker job as the Statistics tab's, and are only computed apart when the
two scopes differ. The home renders no chart and the hidden tab's table
is not rebuilt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 6c1a62cf6a Move the statistics rendering into page/statistics.rs (#71)
Move only, no behaviour change: the tiles, the charts row and the table
section leave the page, which keeps the shared state, the header row, the
banners and the champ select view.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 0350f66cfd Rename the statistics page module to page (#71)
Rename only, no behaviour change: the page is about to hold two tabs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:12:42 +01:00
nessarandClaude Opus 5.5 5ce8c777c4 Fetch Mastery Points from the Riot API and add the champion sort preference (#76)
The tracker asks Riot for each Account's champion mastery (platform host) right
after a successful sync, and after a Match fetched by id is added, so no new
polling. Lists are stored per Account in one transaction and read back with
Tracker::mastery (None = never fetched). A failed fetch keeps the last values
and records no problem. Preferences gain champion_sort (mastery or name).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:09:18 +01:00
nessarandClaude Opus 5.5 50c0427958 Keep tall card portraits cropped to the card size (#77)
Add ChampionSource::card_portrait (Data Dragon loading art) and
Tracker::refresh_card_portraits, which downloads the missing ones, crops them
to the card's 0.68 aspect at the mockup's 24 % focus, shrinks them to
308 x 453 px and saves them as JPEG in portraits/cards via a .part file.
ChampionRow gains card_portrait.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:08:57 +01:00
nessarandClaude Opus 5.5 34e8fb8a50 Expose the Season Challenge figures of each champion card (#72)
Add ChampionChallenge (Matches, Wins, best Placement, date of the first
top 1) and Marks (Played, Won, Completed) on ChampionRow::challenge. They
cover one Account and one Season across all Formats, so the Format filter
never changes them. Computed in the existing chronological pass.

The first top 1 date (#73) comes from the first top 1 by start time, with
the same day convention as the progress curve, so a later or out-of-order
import never changes it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 21:07:52 +01:00
nessarandClaude Opus 5.5 209059cf10 Define the major release that needs the full benchmark as X.0.0 (#61)
CI / core (pull_request) Successful in 37s
CI / core (push) Successful in 34s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:53:18 +01:00
nessarandClaude Opus 5.5 400ac154f9 Ignore the files Gitea lists when it creates a draft (#61)
CI / core (pull_request) Successful in 1m18s
On a private test repository, a stable whose tag only existed locally
stopped before publishing: Gitea 28.1 lists unrelated files in its reply
to the draft creation when it does not have the tag yet, and the command
tried to remove them (HTTP 404, nothing published). A new draft has no
files, so only a draft found by its tag is emptied. Record the stable
run: refusals, an older main commit, a local-only tag, reruns, the next
beta and the channel queries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:44:45 +01:00
nessarandClaude Opus 5.5 5f4332a79f Publish a stable of main from the build PC (#61)
CI / core (pull_request) Successful in 1m18s
scripts/publish-beta becomes scripts/publish with a channel argument.
`scripts/publish stable [commit]` publishes the Cargo.toml version of a
commit on main whose CI checks passed: it builds with scripts/package,
checks the signed files against the tag and commit before creating
anything, tags vX.Y.Z on that commit, then publishes a complete draft as
a normal Release. A stable tag never moves; reruns reuse, complete or
refuse as for betas. Releases now name their target commit, so a tag
that only exists locally is never created on the default branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 19:27:53 +01:00
nessarandClaude Opus 5.5 19c4cf940d Publish betas from the build PC instead of a CI runner (#60)
CI / core (pull_request) Successful in 1m19s
CI / core (push) Successful in 35s
A runner on the build PC would run pull request code without isolation
next to the signing key, and only that PC has the Windows toolchain.
scripts/publish-beta now runs there: it fetches develop and the beta
tags, refuses a commit absent from develop on Gitea or whose CI checks
did not pass, and keeps the numbering, draft-then-publish and reruns.
The key stays in its file; the beta job and its secret are gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:52:32 +01:00
nessarandClaude Opus 5.5 5e757d2a63 Record the beta publication run and the runner 6 setup (#60)
CI / core (pull_request) Successful in 1m14s
CI / beta (pull_request) Skipped
A private test repository went through a main push, develop creation, a
two-commit push, two close pushes, a failing check, reruns of a complete
and of an interrupted publication, and a job cancelled mid-build; the five
betas verify with their own executables, and a pull request token is
refused write access.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 18:14:26 +01:00
nessarandClaude Opus 5.5 9b87492b43 Publish a numbered beta after each validated push to develop (#60)
The beta job runs after the core checks on a host-mode WSL runner with the
Windows toolchain, builds the push's commit with scripts/package and
publishes it as a prerelease: tag, draft, the four files, then publish.
The cycle target is the workspace version (1.0.0); beta tags are the
counter, created atomically after the build. A rerun reuses or completes
its own publication; a single runner serializes the jobs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 16:29:50 +01:00
nessarandClaude Opus 5.5 093078731e Test that a release newer than a failed one is applied at launch (#59)
CI / core (pull_request) Successful in 36s
CI / core (push) Successful in 1m20s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:11:15 +01:00
nessarandClaude Opus 5.5 ab3c6964a5 Apply the update through « Redémarrer » or at the next launch (#59)
The settings show « Redémarrer » next to « Mise à jour prête ». It
verifies the kept package of the chosen channel again, hands exactly
that file to Velopack with `Update.exe apply --waitPid <pid> --package
<file>`, then quits as « Quitter » does (WM_QUIT, never hidden in the
notification area). Velopack 1.2.161 reads the file in place, waits for
the app to exit, replaces current\ and opens the new version once, or
the old one again after a failure.

After « Quitter », the next launch does the same before loading the
app, offline too, but only in the single instance: a shortcut launched
while the app runs still just brings its window back (#50).

An attempt record, <channel>-<version>.attempt next to the package
folder, holds the installer's process id. A launch that finds it never
retries on its own: it waits for a running installer (a close second
launch, or the old version reopened after a failure), then either
leaves the app to the new version or opens the current one with a
one-time notice. « Redémarrer » retries; a newer release starts fresh.
The record survives a new download of the same version, since Velopack
deletes a package it cannot open.

Velopack's swap has no rollback between its two renames; this residual
risk is recorded in ADR-0005 and docs/paquets-windows.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 14:02:57 +01:00
nessarandClaude Opus 5.5 8e12abf7f4 Choose the update channel and download authenticated updates (#58)
CI / core (pull_request) Successful in 35s
CI / core (push) Successful in 1m16s
The settings offer Stable or Bêta. The choice is saved only once made;
until then the installed version's channel applies, so the beta
installer follows Bêta. Updates never change a saved choice.

Each launch, and each channel change, runs one check on a below-normal
thread. It lists the channel's Releases through the public Gitea API
(betas are pre-releases) and takes the highest version above the
installed one. The package is downloaded into
%LOCALAPPDATA%\arena-tracker\updates\partial, verified with
verify_release, then kept as <channel>-<version>; another channel's
package is removed before any network access. Only then does a green
title-bar button show « Mise à jour prête » and open the settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 12:14:25 +01:00
nessarandClaude Opus 5.5 24aca3c93d Reopen the window without focus when an Arena champ select starts (#63)
CI / core (pull_request) Successful in 45s
CI / core (push) Successful in 46s
A minimized window, or one hidden in the notification area, comes back above
the other windows while League keeps the keyboard. An already visible window is
left alone, and the window stays open after the champ select.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:57:53 +01:00
nessarandClaude Opus 5.5 c5ed246668 Record the Windows packaging decisions and today's install run (#57)
CI / core (pull_request) Successful in 1m18s
CI / core (push) Successful in 1m20s
ADR-0005: Velopack packer only, our own Ed25519 manifest, full packages,
accepted root-launcher path (same-user write), static C runtime.
The guide records the 1.0.0 run: non-elevated silent install, Start Menu
shortcut opening the installed exe with existing data, uninstall and
reinstall keeping config, Seasons and Parties, tampered package refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:53:48 +01:00
nessarandClaude Opus 5.5 611a19ce28 Link the C runtime statically instead of shipping vcruntime140.dll (#57)
The installed app then depends only on Windows libraries, whatever Visual
Studio redistributable the build machine has.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:47:54 +01:00
nessarandClaude Opus 5.5 18e9db54fc Verify the whole release folder in core and rebuild packaged sources (#57)
Address the code review of the carried-over work:
- scripts/package extracts the snapshot with fresh mtimes, so the shared
  target never reuses a workspace crate built from other sources.
- core::verify_release owns the release-folder contract (file names, size
  limits, signature, identity, digest) and returns Error::InvalidUpdate; it is
  tested natively with real folders, oversized manifests and missing files.
- The app's --verify-release only adds the build identity and commit check.
- French script messages, clearer path helpers, accurate Velopack stub facts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:43:02 +01:00
nessarandClaude Opus 5.5 f90ae109b9 Package a per-user Windows installer and signed full update packages (#57)
Work in progress carried over from the main checkout: scripts/package builds
one version from one commit, packs it with vpk 1.2.161 (full packages only),
signs a manifest with Ed25519 and checks the result with the built executable.
The core verifies the signed manifest and package digest before any unpacking.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 10:34:14 +01:00
nessarandClaude Opus 5.5 6d07a9641f Address single-instance review findings (#50)
CI / core (pull_request) Successful in 35s
CI / core (push) Successful in 39s
- Reopen the window even when the relaunch's ack event is gone.
- Exit quietly instead of panicking on timeout or Win32 error; bound the startup gate wait.
- Fail softly in accept_relaunches; name the locks (Primary, HeldMutex).
- Share window_hwnd, derive REOPEN from TRAY_MESSAGE, name the marker.
- Test a crashed primary and a relaunch that finds no window.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 23:09:47 +01:00
nessar a11bc277f2 Restore the existing window on relaunch (#50)
Elect one process per Windows session before starting GPUI or opening the database. Let the existing window handle reopen requests and preserve its current state.
2026-11-19 23:09:47 +01:00
nessar fac082e51f Documenter la refonte d’Arena Tracker et sa maquette interactive
CI / core (pull_request) Successful in 38s
CI / core (push) Successful in 1m19s
2026-11-19 23:08:13 +01:00
nessar 304d958c72 Fix the final champ select review findings (#13)
CI / core (pull_request) Successful in 51s
CI / core (push) Successful in 49s
2026-11-19 22:17:14 +01:00
nessarandClaude Opus 5.5 cf15eeeb8f Decode client events from their data and keep the draft on a timeout (#13)
Event frames are [8, topic, {data, eventType, uri}]; decode_event returned the
whole envelope, so the cached session had no localPlayerCellId and the
pickable/disabled/anvil lists ignored the update until a fresh GET. It now
returns the envelope's data (null on Delete, which the cache already ignores).
The tests use enveloped frames, including one from raw text to the cached state.

transport_error mapped every non-TLS error to Absent, so one request timing out
while the client loads the draft sent the page back to statistics. A timeout or
an I/O error other than connection refused is now Other, which champ_select_with
treats as transient. Other readers of ClientError only use .ok(), so nothing
else changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:17:14 +01:00
nessar 5ba3251875 Fix champ select review findings (#13)
- redraw the page on hover and lock-in changes, and reset the settings form
  when champ select takes the window away
- keep the current pick when a client read fails; only a real answer that
  the draft is over ends it
- read the client once per wake and share it between the follower and the
  live selection, reuse session event payloads, and touch only the cached
  champion list an event concerns
- replay the captured raw client responses in the fake and cover the list
  cache, event updates and the anvil-champion read
- name the five champions anvil champions and the set pickable, document
  them, and prepare redraw strings ahead of render
2026-11-19 22:17:14 +01:00
nessar f4a9e5e7a8 Show live Arena champion picks and crowd favorites (#13) 2026-11-19 22:17:14 +01:00
nessar fabaa8a60f Record the five anvil champions from the same Arena session 2026-11-19 22:17:14 +01:00
nessar 9d9b67666b Capture Arena 3x6 bans, hovers and lock-in for #13 2026-11-19 22:17:14 +01:00
nessarandClaude Opus 5.5 650dfd4bfa Address Inter font review findings (#52)
CI / core (pull_request) Successful in 38s
CI / core (push) Successful in 1m14s
- Set Inter only when DirectWrite resolves its family, so a name
  mismatch keeps the system font instead of a fallback on every run.
- Rename init to init_theme and share the family name as a constant.
- Make the test prove a semibold face: its glyphs are wider.
- Ship the license from the same Inter release as the font.
- Shorten the search placeholder so it fits at the minimum width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 22:10:16 +01:00
nessar 1016b68e41 Use Inter as the interface font
CI / core (pull_request) Successful in 40s
2026-11-19 21:56:16 +01:00
nessar a537999229 research
CI / core (push) Successful in 50s
2026-11-19 20:09:16 +01:00
nessarandClaude Opus 5.5 ad3f491f45 Refine the title bar and add a one-time tray notice (#24)
CI / core (pull_request) Successful in 1m8s
CI / core (push) Successful in 1m17s
- Drop the out-of-scope responsive stats page and scrolling settings
  form; keep the minimum window size.
- A refresh keeps the following mode: a followed Account stays followed,
  a pinned one stays pinned.
- Flat 32 px title bar with full-height buttons, so Fermer is reachable
  in the screen corner when maximized; Windows close colours on hover.
- Read the maximized state directly instead of caching it; split the
  crash arms; share the window-button styling.
- Keep close to tray on by default.
- Notify once, the first time closing hides the app in the notification
  area; recorded as tray_notice_shown in config.toml.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 00:24:16 +01:00
nessar 797b7e83e0 Address title-bar review findings (#24)
CI / core (pull_request) Successful in 1m9s
2026-11-18 23:24:23 +01:00
nessar 23eb933a68 Add a custom Windows title bar (#24)
CI / core (pull_request) Successful in 1m17s
2026-11-18 21:11:21 +01:00
nessar a2d58c000c Préciser les dégâts observables par objet et amélioration (#23)
CI / core (pull_request) Successful in 42s
CI / core (push) Successful in 40s
2026-11-18 00:45:52 +01:00
nessar 21212a11a2 Document Arena match statistics and post-game availability (#23) 2026-11-18 00:45:52 +01:00
nessar d7bd69c35d Add tray and theme settings (#21)
CI / core (pull_request) Successful in 1m13s
CI / core (push) Successful in 44s
2026-11-18 00:36:15 +01:00
173 changed files with 29350 additions and 4979 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# Link the MSVC C runtime into the executable: the installer ships no vcruntime140.dll (ADR-0005).
[target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"]
+9
View File
@@ -1,4 +1,5 @@
# Only the core crate is checked: the app crate (GPUI) only builds on Windows (ADR-0003).
# Betas of develop and stables of main are published from the build PC once these checks pass (docs/publication.md).
name: CI
on:
@@ -6,6 +7,11 @@ on:
push:
branches:
- main
- develop
# CI never publishes: a read-only job token is enough.
permissions:
contents: read
jobs:
core:
@@ -26,3 +32,6 @@ jobs:
- name: Tests
run: cargo test -p arena-tracker-core --locked
- name: Publication tests
run: python3 scripts/test_publish.py
+1
View File
@@ -1,3 +1,4 @@
/target
*.local.toml
.env
__pycache__/
+11
View File
@@ -7,6 +7,17 @@ The app must stay as fluid and light as possible: it never feels slow and never
- Do not modify GPUI or gpui-component to meet a budget: reduce the app's own rendering cost (ADR-0004).
- A part of the page gets its own view for a reason: it owns state that changes on its own (the champion table: sort, selection, scroll, hover), or it is a cached view with a structural test (`docs/performance.md`), its gain checked at the next release benchmark. Other parts render as functions in their parent's render.
## Rule #2: focused modules
When adding behavior or tests would grow a Rust file and leave it above 500 lines, counting inline tests, extract a cohesive responsibility or test suite into a focused module in the same change. Use Rust modules and render functions for these splits and follow Rule #1 for GPUI view boundaries.
### Rust test layout
- Keep small unit-test suites next to the implementation in an inline `#[cfg(test)] mod tests { ... }`. The child module can access private items in its parent.
- Move larger unit-test suites to a child file such as `src/ring/tests.rs`, declared with `#[cfg(test)] mod tests;`. Split suites by behavior as they grow.
- Group integration tests by behavior in the package's top-level `tests/` directory and exercise the public API.
- When documenting a runnable API example, use a Rust code block in the item's `///` comments so `cargo test` checks it.
## Agent skills
### Issue tracker
+29
View File
@@ -8,6 +8,10 @@ Personal tracking of League of Legends Arena matches, centred on progress throug
A finished Arena game played by an Account with one champion, in one Format.
_Avoid_: Game, session
**Match Recap**:
The available statistics for a Match and its participants.
_Avoid_: Match report
**Format**:
A variant of Arena with its own team structure and rules, such as Arena 3x6 or Bravery Arena; it filters statistics but does not split the Challenge.
_Avoid_: Mode, type, queue
@@ -28,6 +32,13 @@ _Avoid_: Victory
The goal of getting a top 1 with every champion in the game in as few Attempts as possible, scoped to one Account and one Season across all Formats, mirroring how the game client counts it.
_Avoid_: Checklist, goal, Arena God
**Mark**:
One of three milestones for a champion within a Challenge, earned for the first Match, the first Win, and the first top 1 respectively. A first Match ending in a top 1 earns all three Marks at once.
_Avoid_: Point, Fame
**Mastery Points**:
The champion mastery score that League of Legends gives an Account for a particular champion.
**Completed**:
The state of a champion that has at least one top 1 within a given Challenge.
_Avoid_: Done, validated, won
@@ -48,6 +59,18 @@ _Avoid_: Split, run
A League of Legends account; the active Account is the one signed in to the game client.
_Avoid_: Player, profile, summoner
**Champ select**:
The draft before an Arena Match, where each player bans and picks a champion; only an Arena champ select opens the champ select view.
_Avoid_: Draft, selection
**Anvil champions**:
The five champions the game favours in the current Arena patch and shows during champ select; the game client calls them crowd favorites.
_Avoid_: Crowd favorites, favorites
**Pickable**:
A champion the local player can still pick in the current Arena champ select: offered by the client, not disabled, and neither banned nor taken by another player.
_Avoid_: Available, owned
**Official Progress**:
The game's own per-Season count of champions it considers completed, used only to cross-check a Challenge.
_Avoid_: Riot challenge, tracker
@@ -59,12 +82,18 @@ The interface is in French. Each glossary term has one French word in user-facin
| Term | In the interface |
| --- | --- |
| Match | Partie |
| Match Recap | Récapitulatif de partie |
| Challenge | Défi |
| Mark | Marque |
| Mastery Points | Points de maîtrise |
| Attempt | Tentative |
| First Try | du premier coup |
| Completed | validé |
| Win | Victoire |
| Season | Saison |
| Account | Compte |
| Champ select | Sélection des champions |
| Anvil champions | Champions de l'Enclume |
| Pickable | Disponible |
| Official Progress | Progression officielle |
| Placement, Format, Top N | unchanged |
Generated
+9 -2
View File
@@ -219,19 +219,26 @@ dependencies = [
[[package]]
name = "arena-tracker"
version = "0.1.0"
version = "1.0.0"
dependencies = [
"arena-tracker-core",
"base64 0.23.1",
"embed-resource",
"gpui-kit",
"gpui-pre",
"image",
"raw-window-handle",
"serde_json",
"windows 0.62.2",
]
[[package]]
name = "arena-tracker-core"
version = "0.1.0"
version = "1.0.0"
dependencies = [
"base64 0.23.1",
"image",
"ring",
"rusqlite",
"rustls",
"serde",
+1 -1
View File
@@ -6,4 +6,4 @@ default-members = ["crates/core"]
[workspace.package]
edition = "2024"
rust-version = "1.98"
version = "0.1.0"
version = "1.0.0"
+5 -1
View File
@@ -1,9 +1,11 @@
# Arena Tracker
Application de bureau Windows qui suit les Parties d'Arena de League of Legends. Le vocabulaire du domaine est dans `CONTEXT.md` et les décisions d'architecture dans `docs/adr/`.
Application de bureau Windows qui suit les Parties d'Arena de League of Legends. Pour l'installer et l'utiliser : [guide d'utilisation](docs/guide-utilisation.md). Le vocabulaire du domaine est dans `CONTEXT.md` et les décisions d'architecture dans `docs/adr/`.
Règle n°1 : l'application reste fluide et légère, sans jamais donner l'impression de ralentir ni l'application ni l'ordinateur. Ses budgets mesurables (temps par image, CPU au repos, mémoire, travail de fond) et la façon de les mesurer sont dans `docs/performance.md`.
L’installateur par utilisateur et la commande de construction des paquets Stable et Bêta sont décrits dans le [guide des paquets Windows](docs/paquets-windows.md). Les branches main et develop, la cible du cycle et la publication des bêtas et des stables sont décrites dans [Publication](docs/publication.md).
## Prérequis
- Windows avec la chaîne d'outils Rust (rustup), version 1.98 ou plus récente, accessible depuis WSL sous le nom `cargo.exe`.
@@ -42,6 +44,8 @@ region = "europe" # facultatif, "europe" par défaut
Le Compte connecté au client de League of Legends est suivi automatiquement. `riot_id` ne sert que de repli, quand le client est fermé au premier lancement.
L'application y écrit aussi ses préférences (`close_to_tray`, `theme`, `update_channel` : `stable` ou `beta`, absent tant que le canal de la version installée s'applique, `champion_sort` : `mastery` ou `name`, absent tant que le joueur n'a pas choisi, le tri se faisant alors par points de maîtrise) et `tray_notice_shown`, qui passe à `true` une fois affichée la notification indiquant que la fenêtre fermée continue dans la zone de notification. Le remettre à `false` la fait réapparaître à la prochaine fermeture.
La base des Parties, `arena-tracker.db`, est créée dans le même dossier, ainsi que `seasons.toml`, la table des Saisons : elle peut être modifiée, et les changements sont pris en compte au lancement suivant. La clé API ne doit jamais être commitée.
## Tests
+17
View File
@@ -9,12 +9,29 @@ profile = ["gpui-kit/profiler"]
[dependencies]
arena-tracker-core = { path = "../core" }
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
gpui-kit = "=0.9.1"
# Decodes the banner's splash at low priority (the same version as GPUI's and the core's).
image = { version = "0.25.10", default-features = false, features = ["jpeg"] }
[target.'cfg(windows)'.dependencies]
raw-window-handle = "0.6"
windows = { version = "0.62", features = [
"Win32_Graphics_Gdi",
"Win32_Security",
"Win32_System_LibraryLoader",
"Win32_System_Registry",
"Win32_System_Threading",
"Win32_UI_Shell",
"Win32_UI_WindowsAndMessaging",
] }
[dev-dependencies]
# The GPUI that gpui-kit pins (upgrade them together), for its test context. Not gpui-kit's own
# test-support: its gpui-fast features would force older wgpu and others into Cargo.lock.
gpui = { package = "gpui-pre", version = "=0.3.12", features = ["test-support"] }
# Splits the Arena champ select capture into its frames (the same version as the core's).
serde_json = "1.0.154"
[build-dependencies]
embed-resource = "3.0.12"
+92
View File
@@ -0,0 +1,92 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2022 The Unbounded Project Authors (https://github.com/googlefonts/unbounded)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
+22
View File
@@ -1,2 +1,24 @@
// GPUI loads icon resource 1 for the window and its taskbar entry; File Explorer shows it too.
1 ICON "icon.ico"
#ifdef ARENA_RELEASE
#include "release-version.h"
1 VERSIONINFO
FILEVERSION ARENA_VERSION_NUMBERS
PRODUCTVERSION ARENA_VERSION_NUMBERS
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904B0"
BEGIN
VALUE "ProductName", "Arena Tracker"
VALUE "FileVersion", ARENA_VERSION_TEXT
VALUE "ProductVersion", ARENA_VERSION_TEXT
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x0409, 1200
END
END
#endif
+3
View File
@@ -0,0 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="48 48 160 160" width="48" height="48">
<path fill="currentColor" d="M68 186 L52 86 L98 126 L128 66 L158 126 L204 86 L188 186 Z"/>
</svg>

After

Width:  |  Height:  |  Size: 188 B

+323
View File
@@ -0,0 +1,323 @@
//! The banner's illustration: the splash of one champion, decoded off the UI thread at low
//! priority and held by the banner alone, never by GPUI's app-wide asset cache (rule #1: memory in
//! proportion to what is shown, background work at low priority).
//!
//! It holds two splashes at most: the one shown and the one replacing it, which shows once
//! decoded. The one it replaces is then given back, in memory and in the windows' atlas, as the
//! card portraits are (#77). A decode cannot be stopped once started, so only one runs at a time:
//! a splash asked for meanwhile waits for its end.
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use arena_tracker_core::{Splash, SplashFocus};
use gpui_kit::*;
use crate::motion::MATCH_SETTLE;
use crate::worker::BelowNormal;
const FADE: Duration = Duration::from_millis(500);
/// The splash of a champion just Completed settles in (#89): it waits for its image, then comes
/// in enlarged and shrinks back.
enum Reveal {
AwaitingImage,
Settling(Instant),
}
/// The incoming splash's frame during a reveal.
#[derive(Clone, Copy)]
pub(crate) struct RevealFrame {
/// 1 at rest, above while it settles.
pub zoom: f32,
pub opacity: f32,
}
impl RevealFrame {
const REST: RevealFrame = RevealFrame {
zoom: 1.,
opacity: 1.,
};
}
pub struct BannerArt {
pub(crate) target: Option<Rc<Splash>>,
reveal: Option<Reveal>,
previous: Option<(Rc<Splash>, Arc<RenderImage>, Instant)>,
/// The splash shown, and its image; none when it could not be read.
shown: Option<(Rc<Splash>, Option<Arc<RenderImage>>)>,
/// The decode running, of which splash.
decoding: Option<(Rc<Splash>, Task<()>)>,
/// The splash the banner shows next: decoded when the running decode ends, if it is not
/// that one. None while the banner shows no illustration.
wanted: Option<Rc<Splash>>,
/// Decodes started.
#[cfg(test)]
pub(crate) loads: usize,
}
impl BannerArt {
pub fn new(cx: &mut App) -> Entity<BannerArt> {
let art = cx.new(|_| BannerArt {
target: None,
reveal: None,
previous: None,
shown: None,
decoding: None,
wanted: None,
#[cfg(test)]
loads: 0,
});
// The page is gone: so is the splash, from every window's atlas too.
cx.observe_release(&art, |art, cx| {
art.drop_previous(None, cx);
art.drop_shown(None, cx);
})
.detach();
art
}
/// A splash is settling in.
#[cfg(test)]
pub(crate) fn revealing(&self) -> bool {
self.reveal.is_some()
}
/// Shows `target` as the splash of a champion just Completed: it settles in.
pub(crate) fn reveal(&mut self, target: Option<Rc<Splash>>, cx: &mut Context<Self>) {
self.set_target(target, cx);
self.reveal = self.target.as_ref().map(|_| Reveal::AwaitingImage);
cx.notify();
}
/// The incoming splash's frame now, asking for the next while it settles. It starts at its
/// first decoded frame, even on a slow disk; one that cannot be read has nothing to settle.
pub(crate) fn reveal_frame(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> RevealFrame {
if cx.reduce_motion() {
self.reveal = None;
}
let Some(reveal) = &mut self.reveal else {
return RevealFrame::REST;
};
let now = cx.background_executor().now();
let start = match *reveal {
Reveal::Settling(start) => start,
Reveal::AwaitingImage => match &self.shown {
Some((shown, image)) if Some(shown) == self.target.as_ref() => {
if image.is_none() {
self.reveal = None;
return RevealFrame::REST;
}
*reveal = Reveal::Settling(now);
now
}
_ => return RevealFrame::REST,
},
};
let elapsed = now.duration_since(start).as_secs_f32();
let t = elapsed / MATCH_SETTLE;
if t >= 1. {
self.reveal = None;
return RevealFrame::REST;
}
window.request_animation_frame();
RevealFrame {
zoom: 1. + 0.1 * (1. - t).powi(2),
opacity: if self.previous.is_some() {
1.
} else {
(elapsed / FADE.as_secs_f32()).min(1.)
},
}
}
pub fn set_target(&mut self, target: Option<Rc<Splash>>, cx: &mut Context<Self>) {
if self.target != target {
self.reveal = None;
self.target = target;
self.wanted = None;
cx.notify();
}
}
/// The outgoing image is painted over the new one with decreasing opacity.
pub(crate) fn previous_opacity(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<f32> {
let (_, _, start) = self.previous.as_ref()?;
let elapsed = cx.background_executor().now().duration_since(*start);
if elapsed >= FADE || cx.reduce_motion() {
self.drop_previous(Some(window), cx);
return None;
}
window.request_animation_frame();
Some(1. - elapsed.as_secs_f32() / FADE.as_secs_f32())
}
pub(crate) fn previous_image(&self) -> Option<(Arc<RenderImage>, SplashFocus)> {
self.previous
.as_ref()
.map(|(splash, image, _)| (image.clone(), splash.focus))
}
fn drop_previous(&mut self, window: Option<&mut Window>, cx: &mut App) {
if let Some((_, image, _)) = self.previous.take() {
cx.drop_image(image, window);
}
}
/// For the paint of `splash`: the image to paint and its focus. That is `splash` once
/// decoded, and until then the splash shown before it. The art notifies when it changes. A
/// splash that cannot be read shows nothing.
pub fn image(
&mut self,
splash: &Rc<Splash>,
cx: &mut Context<Self>,
) -> Option<(Arc<RenderImage>, SplashFocus)> {
if self.wanted.as_ref() != Some(splash) {
self.wanted = Some(splash.clone());
}
let shown_wanted = self
.shown
.as_ref()
.is_some_and(|(shown, _)| shown == splash);
if !shown_wanted && self.decoding.is_none() && self.previous.is_none() {
self.decode(splash.clone(), cx);
}
let (shown, image) = self.shown.as_ref()?;
Some((image.clone()?, shown.focus))
}
fn decode(&mut self, splash: Rc<Splash>, cx: &mut Context<Self>) {
#[cfg(test)]
{
self.loads += 1;
}
let path = splash.path.clone();
let task = cx.spawn(async move |art, cx| {
let image = cx
.background_executor()
.spawn_with_priority(Priority::Low, async move { decode(&path) })
.await;
let _ = art.update(cx, |art, cx| art.decoded(image, cx));
});
self.decoding = Some((splash, task));
}
/// The running decode ended: its splash replaces the one shown if the banner still wants
/// it, else it is dropped (it was never painted) and the wanted one decodes.
fn decoded(&mut self, image: Option<Arc<RenderImage>>, cx: &mut Context<Self>) {
let Some((splash, _)) = self.decoding.take() else {
return;
};
if self.wanted.as_ref() == Some(&splash) {
if image.is_some()
&& !cx.reduce_motion()
&& animations_enabled()
&& let Some((old, Some(previous))) = self.shown.take()
{
self.previous = Some((old, previous, cx.background_executor().now()));
} else {
self.drop_shown(None, cx);
}
self.shown = Some((splash, image));
cx.notify();
} else if let Some(wanted) = self.wanted.clone()
&& self
.shown
.as_ref()
.is_none_or(|(shown, _)| *shown != wanted)
{
drop(image);
self.decode(wanted, cx);
}
}
/// Gives back the splash shown, from `window`'s atlas and every other window's.
fn drop_shown(&mut self, window: Option<&mut Window>, cx: &mut App) {
if let Some((_, Some(image))) = self.shown.take() {
cx.drop_image(image, window);
}
}
/// Drops the splash, in memory and in the window's atlas, for a banner that is not shown or
/// has no illustration. A decode running ends unused.
pub fn release(&mut self, window: &mut Window, cx: &mut App) {
self.reveal = None;
self.wanted = None;
self.drop_previous(Some(window), cx);
self.drop_shown(Some(window), cx);
}
/// The splashes held: shown, or decoding.
#[cfg(test)]
pub(crate) fn held(&self) -> Vec<std::path::PathBuf> {
let shown = self.shown.as_ref().map(|(splash, _)| splash);
let decoding = self.decoding.as_ref().map(|(splash, _)| splash);
[
self.previous.as_ref().map(|(splash, _, _)| splash),
shown,
decoding,
]
.into_iter()
.flatten()
.map(|splash| splash.path.clone())
.collect()
}
/// The splash decoded and shown.
#[cfg(test)]
pub(crate) fn loaded(&self) -> Vec<Arc<RenderImage>> {
self.shown
.iter()
.filter_map(|(_, image)| image.clone())
.chain(self.previous.iter().map(|(_, image, _)| image.clone()))
.collect()
}
}
/// Reads and decodes a stored splash (a JPEG) into what the GPU takes, BGRA, at below-normal
/// priority. None when it cannot be read.
fn decode(path: &Path) -> Option<Arc<RenderImage>> {
let _below = BelowNormal::enter();
let bytes = std::fs::read(path).ok()?;
let mut pixels = image::load_from_memory_with_format(&bytes, image::ImageFormat::Jpeg)
.ok()?
.into_rgba8();
for pixel in pixels.as_chunks_mut::<4>().0 {
pixel.swap(0, 2);
}
Some(Arc::new(RenderImage::new(vec![image::Frame::new(pixels)])))
}
#[cfg(all(windows, not(test)))]
fn animations_enabled() -> bool {
use windows::Win32::UI::WindowsAndMessaging::{
SPI_GETCLIENTAREAANIMATION, SystemParametersInfoW,
};
let mut enabled = windows::core::BOOL::default();
// SPI_GETCLIENTAREAANIMATION writes one BOOL to the supplied pointer.
unsafe {
SystemParametersInfoW(
SPI_GETCLIENTAREAANIMATION,
0,
Some((&raw mut enabled).cast()),
Default::default(),
)
.is_ok()
&& enabled.as_bool()
}
}
#[cfg(any(not(windows), test))]
fn animations_enabled() -> bool {
true
}
+420
View File
@@ -0,0 +1,420 @@
//! The champion card: the one representation of a champion, on the home and in the Arena champ
//! select. A `Card` is built once when the statistics change; `card` only lays it out.
mod detail;
use detail::{caption, reasons, shade, sheet};
use std::path::Path;
use std::sync::{Arc, LazyLock};
use arena_tracker_core::{ChampionRow, Marks, Unpickable};
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::text::{ordinal, thousands};
use crate::theme::{LOGO_GOLD, ON_GOLD, gold_glow, surface};
/// Width over height: the ratio the stored portraits are cropped to.
pub const ASPECT: f32 = arena_tracker_core::CARD_ASPECT as f32;
const RADIUS: f32 = 10.;
/// The border is inside the radius: the layers it holds are rounded one pixel less.
const INNER_RADIUS: f32 = RADIUS - 1.;
// The caption and badges sit on the dark shade, in both themes: their colours are fixed.
const MARK_ON: u32 = 0xffffff;
const MARK_OFF: u32 = 0xd3d4db;
const MARK_OFF_RING: u32 = 0xbfc1cd;
const BADGE_BG: u32 = 0x11152aee;
const BADGE_TEXT: u32 = 0xffa0a0;
// The sheet is dark in both themes, like the shade it replaces.
const SHEET_BG: u32 = 0x0d1021f5;
const SHEET_LABEL: u32 = 0xc5cbe0;
// The sheet's lines, in order.
const PLAYED: &str = "Parties";
const WINS: &str = "Victoires";
const BEST_PLACEMENT: &str = "Meilleur Placement";
const ATTEMPTS: &str = "Tentatives";
const MASTERY: &str = "Points de maîtrise";
const UNKNOWN: &str = "Inconnus";
/// Only on a Completed champion.
pub const FIRST_TOP_1: &str = "Premier top 1";
const NONE: &str = "—";
/// Why a card is greyed out, in the order the badges are shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reason {
/// At least one top 1 in the Season.
Completed,
/// Banned in the champ select.
Banned,
/// Confirmed by an ally in the champ select.
TakenByAlly,
/// The champ select does not offer the champion.
NotOffered,
}
impl Reason {
pub fn label(self) -> &'static str {
match self {
Reason::Completed => "Validé",
Reason::Banned => "Banni",
Reason::TakenByAlly => "Pris par un allié",
Reason::NotOffered => "Indisponible",
}
}
fn badge(self, id: u32) -> Div {
let badge = div()
.h_flex()
.items_center()
.gap(px(4.))
.px(px(6.))
.py(px(3.))
.rounded(px(4.))
.text_size(px(10.))
.font_weight(FontWeight::SEMIBOLD)
.debug_selector(move || format!("reason-{id}-{}", self.label()));
let ordinary = |badge: Div, icon: IconName| {
badge
.bg(rgba(BADGE_BG))
.text_color(rgb(BADGE_TEXT))
.child(Icon::new(icon).size(px(12.)))
};
let badge = match self {
Reason::Completed => {
static CROWN: LazyLock<Arc<Image>> = LazyLock::new(|| {
let svg = include_str!("../assets/crown.svg")
.replace("currentColor", &format!("#{ON_GOLD:06x}"));
Arc::new(Image::from_bytes(ImageFormat::Svg, svg.into_bytes()))
});
badge
.bg(rgb(LOGO_GOLD))
.text_color(rgb(ON_GOLD))
.child(img(CROWN.clone()).size(px(12.)))
}
Reason::Banned => ordinary(badge, IconName::Ban),
Reason::TakenByAlly => ordinary(badge, IconName::User),
Reason::NotOffered => ordinary(badge, IconName::EyeOff),
};
badge.child(self.label())
}
}
#[derive(Clone, Debug, PartialEq)]
pub struct Card {
pub id: u32,
pub name: SharedString,
/// The tall portrait, else the square icon while the tall one is not downloaded yet.
/// Shared, so drawing the card clones a pointer rather than a path.
pub portrait: Option<Arc<Path>>,
pub marks: Marks,
/// In display order. A card with any reason is greyed.
pub reasons: Vec<Reason>,
/// The lines of the sheet shown on hover and focus, as label and value, prepared with the
/// card so showing it reads nothing.
pub sheet: Vec<(&'static str, SharedString)>,
}
/// How far a card is lifted over its grid (#88), drawn over it while the pointer or the keyboard
/// is on it: it rises, its illustration zooms in, its caption fades and its sheet slides up from
/// the bottom.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pose {
/// The Marks the end of a followed Match has just given, filling in gold (#89).
pub mark_fill: Option<MarkFill>,
/// 0 at rest, 1 lifted all the way.
pub progress: f32,
/// The hand's veil on this card: 0 to 1.
pub veil: f32,
/// Off with the Windows « Show animations » setting: the sheet shows, the card stays put.
pub moves: bool,
}
/// A card's Marks before the end of a followed Match, and how far the gold of those it gained has
/// filled in: 0 to 1.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MarkFill {
pub before: Marks,
pub progress: f32,
}
impl MarkFill {
/// The opacity of a Mark's gold: filling in when just gained, full when it was already on.
fn opacity(fill: Option<MarkFill>, was_on: fn(&Marks) -> bool) -> f32 {
fill.filter(|f| !was_on(&f.before))
.map_or(1., |f| f.progress)
}
}
/// How high a card rises: less for a greyed one, which cannot be picked.
const RISE: f32 = 10.;
const GREYED_RISE: f32 = 4.;
/// How much the illustration zooms in, inside the card.
const ZOOM: f32 = 0.07;
/// How far the sheet slides up, and the caption down.
const SHEET_SLIDE: f32 = 14.;
const CAPTION_SLIDE: f32 = 6.;
const CAPTION_BOTTOM: f32 = 12.;
/// The hand's veil on the other cards, as the mockup's `rgba(9, 11, 24, .42)`.
const VEIL: u32 = 0x090b18;
const VEIL_OPACITY: f32 = 0.42;
impl Pose {
/// How many pixels the card is above its place.
pub fn rise(&self, card: &Card) -> f32 {
if !self.moves {
return 0.;
}
self.progress * if card.greyed() { GREYED_RISE } else { RISE }
}
fn zoom(&self) -> f32 {
if self.moves { self.progress * ZOOM } else { 0. }
}
}
/// The hand's veil on a card at rest in it, `veil` from 0 to 1.
pub fn veil_color(veil: f32) -> Hsla {
Hsla::from(rgb(VEIL)).opacity(VEIL_OPACITY * veil)
}
/// The radius of a card, for what is drawn over one.
pub const CARD_RADIUS: f32 = RADIUS;
impl Card {
/// A row without a Challenge (no Season) has no Marks.
pub fn from_row(row: &ChampionRow) -> Card {
let marks = row.challenge.map_or(
Marks {
played: false,
won: false,
completed: false,
},
|challenge| challenge.marks(),
);
Card {
id: row.champion.id,
name: row.champion.name.clone().into(),
portrait: row
.card_portrait
.as_deref()
.or(row.portrait.as_deref())
.map(Arc::from),
marks,
reasons: if marks.completed {
vec![Reason::Completed]
} else {
Vec::new()
},
sheet: sheet_lines(row),
}
}
/// Adds the champ select's reasons after the Season's. The player's own pick has none.
pub fn with_unpickable(mut self, unpickable: Unpickable) -> Card {
let Unpickable {
banned,
taken_by_ally,
not_offered,
} = unpickable;
for (applies, reason) in [
(banned, Reason::Banned),
(taken_by_ally, Reason::TakenByAlly),
(not_offered, Reason::NotOffered),
] {
if applies {
self.reasons.push(reason);
}
}
self
}
pub fn greyed(&self) -> bool {
!self.reasons.is_empty()
}
}
/// The sheet's figures for the Season, all Formats; « — » where there is none (no Season, or no
/// Match). The date is only there once the champion is Completed.
fn sheet_lines(row: &ChampionRow) -> Vec<(&'static str, SharedString)> {
let challenge = row.challenge;
let count = |n: Option<usize>| -> SharedString {
n.map_or_else(|| NONE.into(), |n| n.to_string().into())
};
let mut lines = vec![
(PLAYED, count(challenge.map(|c| c.matches))),
(WINS, count(challenge.map(|c| c.wins))),
(
BEST_PLACEMENT,
challenge
.and_then(|c| c.best_placement)
.map_or_else(|| NONE.into(), |placement| ordinal(placement).into()),
),
(ATTEMPTS, count(row.attempts)),
// Unknown is not zero: the points were never fetched for this Account.
(
MASTERY,
row.mastery_points
.map_or_else(|| UNKNOWN.into(), |points| thousands(points).into()),
),
];
if let Some(date) = challenge.and_then(|c| c.completed_on) {
lines.push((FIRST_TOP_1, date.to_string().into()));
}
lines
}
/// One card at rest, as wide as its parent gives it, `ASPECT` wide over tall. Nothing about it
/// changes on hover or focus, so a grid of them stays cached: the card under the pointer or the
/// keyboard is drawn again over it, lifted (`lifted`). A focus handle makes it a tab stop. The
/// caller adds its own listeners.
pub fn card(card: &Card, focus: Option<&FocusHandle>, cx: &App) -> Stateful<Div> {
let id = card.id;
let root = div().flex_1().min_w_0().aspect_ratio(ASPECT);
face(root, card, None, cx)
.id(("card", id))
.when_some(focus, |el, handle| el.track_focus(handle))
.debug_selector(|| format!("card-{id}"))
}
/// The card drawn over its grid in `pose`, `size` as its place there; the caller sets it
/// `pose.rise` above. It has no listener: the pointer still meets the card at rest under it.
pub fn lifted(card: &Card, pose: Pose, size: Size<Pixels>, cx: &App) -> Div {
let theme = cx.theme();
let progress = pose.progress;
let shadows = if !pose.moves || progress == 0. {
Vec::new()
} else if card.greyed() {
vec![drop_shadow(12., 24., -14., 0.6 * progress)]
} else {
vec![
drop_shadow(18., 34., -14., 0.65 * progress),
BoxShadow {
color: gold_glow(theme).opacity(progress),
offset: point(px(0.), px(0.)),
blur_radius: px(28.),
spread_radius: px(-8.),
inset: false,
},
]
};
let id = card.id;
face(div().w(size.width).h(size.height), card, Some(pose), cx)
.shadow(shadows)
.debug_selector(move || format!("lifted-{id}"))
}
/// The card at rest drawn over its grid, `size` as its place there, under the hand's `veil`
/// (0 to 1): the champ select's motion (#87) moves it while the grid stays put. It has no
/// listener.
pub fn moving(card: &Card, veil: f32, size: Size<Pixels>, cx: &App) -> Div {
let id = card.id;
let pose = (veil > 0.).then_some(Pose {
mark_fill: None,
progress: 0.,
veil,
moves: true,
});
face(div().w(size.width).h(size.height), card, pose, cx)
.debug_selector(move || format!("moving-{id}"))
}
fn drop_shadow(y: f32, blur: f32, spread: f32, opacity: f32) -> BoxShadow {
BoxShadow {
color: hsla(0., 0., 0., opacity),
offset: point(px(0.), px(y)),
blur_radius: px(blur),
spread_radius: px(spread),
inset: false,
}
}
/// What a card shows, at rest (`None`) or lifted, in `root`.
fn face(root: Div, card: &Card, pose: Option<Pose>, cx: &App) -> Div {
let theme = cx.theme();
let greyed = card.greyed();
let id = card.id;
let progress = pose.map_or(0., |pose| pose.progress);
let zoom = pose.map_or(0., |pose| pose.zoom());
// Towards the accent as the card rises, as the hover and focus border did.
let border = theme.border.blend(theme.ring.opacity(progress));
root.relative()
.overflow_hidden()
.rounded(px(RADIUS))
.border_1()
.border_color(border)
.bg(surface(theme))
.children(card.portrait.as_ref().map(|path| {
// Zoomed in, the illustration overflows the card on every side, and is cut square:
// `corners` rounds it again.
img(path.clone())
.absolute()
.left(relative(-zoom / 2.))
.top(relative(-zoom / 2.))
.w(relative(1. + zoom))
.h(relative(1. + zoom))
.rounded(px(INNER_RADIUS))
.object_fit(ObjectFit::Cover)
.grayscale(greyed)
}))
// Stands for the mockup's `brightness(.72)`, which the image element cannot do.
.when(greyed, |el| {
el.child(
div()
.absolute()
.inset_0()
.rounded(px(INNER_RADIUS))
.bg(hsla(0., 0., 0., 0.28)),
)
})
.child(shade())
.when(greyed, |el| el.child(reasons(id, &card.reasons)))
.when(progress < 1., |el| {
let slide = if pose.is_some_and(|pose| pose.moves) {
CAPTION_SLIDE * progress
} else {
0.
};
el.child(
caption(card, pose.and_then(|p| p.mark_fill))
.bottom(px(CAPTION_BOTTOM - slide))
.opacity(1. - progress),
)
})
.when(progress > 0., |el| {
let slide = if pose.is_some_and(|pose| pose.moves) {
SHEET_SLIDE * (1. - progress)
} else {
0.
};
el.child(sheet(card).bottom(px(-slide)).opacity(progress))
})
.when(zoom > 0., |el| el.child(corners(theme.background)))
.children(pose.filter(|pose| pose.veil > 0.).map(|pose| {
div()
.absolute()
.inset_0()
.rounded(px(INNER_RADIUS))
.bg(veil_color(pose.veil))
}))
}
/// What lies outside the card's rounded corners, in `background`: a frame whose inner edge is
/// the card's radius, of which only the corners fall inside the card.
fn corners(background: Hsla) -> Div {
let width = RADIUS;
div()
.absolute()
.top(px(-width))
.left(px(-width))
.right(px(-width))
.bottom(px(-width))
.rounded(px(RADIUS + width))
.border(px(width))
.border_color(background)
}
#[cfg(test)]
mod tests;
+148
View File
@@ -0,0 +1,148 @@
use gpui_kit::component::{Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{
CAPTION_BOTTOM, Card, INNER_RADIUS, MARK_OFF, MARK_OFF_RING, MARK_ON, MarkFill, Reason,
SHEET_BG, SHEET_LABEL,
};
use crate::theme::{LOGO_GOLD, ON_GOLD};
/// Over the lower half of the card, as the mockup's `.sheet`: the name, then a line per figure,
/// on a shade that darkens from its top. Only a lifted card builds it.
pub(super) fn sheet(card: &Card) -> Div {
let id = card.id;
let clear = rgba(SHEET_BG & 0xffffff00);
div()
.absolute()
.left_0()
.right_0()
.rounded_b(px(INNER_RADIUS))
.v_flex()
.justify_end()
.pt(px(44.))
.px(px(12.))
.pb(px(12.))
.bg(linear_gradient(
180.,
linear_color_stop(clear, 0.),
linear_color_stop(rgba(SHEET_BG), 0.34),
))
.text_size(px(12.))
.text_color(rgb(SHEET_LABEL))
.debug_selector(|| format!("sheet-{id}"))
.child(
div()
.mb(px(6.))
.text_size(px(17.))
.font_weight(FontWeight::SEMIBOLD)
.text_color(white())
.child(card.name.clone()),
)
.children(card.sheet.iter().map(|(label, value)| {
div()
.h_flex()
.justify_between()
.gap(px(4.))
.py(px(1.5))
.debug_selector(|| format!("sheet-{id}-{label}"))
.child(*label)
.child(
div()
.font_weight(FontWeight::SEMIBOLD)
.text_color(white())
.child(value.clone()),
)
}))
}
/// Keeps the caption readable on any portrait.
pub(super) fn shade() -> Div {
let clear = rgba(0x090b1800);
let dark = rgba(0x090b18f2);
div()
.absolute()
.inset_0()
.rounded(px(INNER_RADIUS))
.bg(linear_gradient(
180.,
linear_color_stop(clear, 0.5),
linear_color_stop(dark, 0.92),
))
}
pub(super) fn reasons(id: u32, reasons: &[Reason]) -> Div {
div()
.absolute()
.top(px(9.))
.left(px(8.))
.right(px(8.))
.h_flex()
.items_start()
.flex_wrap()
.gap(px(3.))
.children(reasons.iter().map(|reason| reason.badge(id)))
}
pub(super) fn caption(card: &Card, fill: Option<MarkFill>) -> Div {
div()
.absolute()
.left(px(12.))
.right(px(8.))
.bottom(px(CAPTION_BOTTOM))
.v_flex()
.child(
div()
.text_size(px(18.))
.font_weight(FontWeight::SEMIBOLD)
.line_height(relative(1.18))
.text_color(white())
.child(card.name.clone()),
)
.child(
div()
.h_flex()
.items_center()
.flex_wrap()
.mt(px(7.))
.gap_x(px(10.))
.gap_y(px(4.))
.child(mark(
"Joué",
card.marks.played,
MarkFill::opacity(fill, |m| m.played),
))
.child(mark(
"Victoire",
card.marks.won,
MarkFill::opacity(fill, |m| m.won),
)),
)
}
/// A dot, filled with a check when on, its gold at `fill` opacity, and its label.
fn mark(label: &'static str, on: bool, fill: f32) -> Div {
div()
.h_flex()
.items_center()
.gap(px(4.))
.text_size(px(10.))
.font_weight(FontWeight::SEMIBOLD)
.text_color(rgb(if on { MARK_ON } else { MARK_OFF }))
.child(
div()
.flex()
.items_center()
.justify_center()
.size(px(11.))
.rounded_full()
.border_1()
.border_color(rgb(if on { LOGO_GOLD } else { MARK_OFF_RING }))
.when(on, |dot| {
dot.bg(Hsla::from(rgb(LOGO_GOLD)).opacity(fill))
.text_color(rgb(ON_GOLD))
.child(Icon::new(IconName::Check).size(px(8.)))
}),
)
.child(label)
}
+283
View File
@@ -0,0 +1,283 @@
use std::path::PathBuf;
use arena_tracker_core::{Champion, ChampionChallenge, ChampionRow, Date, Unpickable};
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
use super::{Card, FIRST_TOP_1, Reason};
fn row(challenge: Option<ChampionChallenge>) -> ChampionRow {
ChampionRow {
champion: Champion {
id: 4,
key: "TwistedFate".into(),
name: "Twisted Fate".into(),
},
portrait: None,
card_portrait: None,
splash: None,
matches: 0,
best_placement: None,
top1: 0,
wins: 0,
average_placement: None,
last_match_ms: None,
attempts: None,
state: None,
challenge,
mastery_points: Some(154_320),
}
}
fn day() -> Date {
Date {
year: 2026,
month: 3,
day: 2,
}
}
fn marks(card: &Card) -> (bool, bool) {
(card.marks.played, card.marks.won)
}
#[test]
fn a_champion_never_played_has_no_mark_and_keeps_its_colours() {
let card = Card::from_row(&row(Some(ChampionChallenge::default())));
assert_eq!(marks(&card), (false, false));
assert!(card.reasons.is_empty());
assert!(!card.greyed());
}
#[test]
fn a_champion_played_without_a_win_has_only_the_played_mark() {
let challenge = ChampionChallenge {
matches: 3,
best_placement: Some(4),
..Default::default()
};
let card = Card::from_row(&row(Some(challenge)));
assert_eq!(marks(&card), (true, false));
assert!(!card.greyed());
}
#[test]
fn a_champion_with_a_win_but_no_top_1_is_in_colour_with_both_marks() {
let challenge = ChampionChallenge {
matches: 2,
wins: 1,
best_placement: Some(2),
completed_on: None,
};
let card = Card::from_row(&row(Some(challenge)));
assert_eq!(marks(&card), (true, true));
assert!(!card.marks.completed);
assert!(!card.greyed());
}
#[test]
fn a_completed_champion_is_greyed_with_the_validated_reason() {
let challenge = ChampionChallenge {
matches: 4,
wins: 2,
best_placement: Some(1),
completed_on: Some(day()),
};
let card = Card::from_row(&row(Some(challenge)));
assert_eq!(marks(&card), (true, true));
assert_eq!(card.reasons, [Reason::Completed]);
assert_eq!(card.reasons[0].label(), "Validé");
assert!(card.greyed());
assert_eq!(card.name.as_ref(), "Twisted Fate");
}
fn lines(card: &Card) -> Vec<(&'static str, String)> {
card.sheet
.iter()
.map(|(label, value)| (*label, value.to_string()))
.collect()
}
#[test]
fn the_sheet_of_a_champion_never_played_is_empty_figures_without_a_date() {
let mut row = row(Some(ChampionChallenge::default()));
row.attempts = Some(0);
assert_eq!(
lines(&Card::from_row(&row)),
[
("Parties", "0".to_string()),
("Victoires", "0".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "0".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
#[test]
fn the_sheet_of_a_remaining_champion_has_its_best_placement_and_no_date() {
let challenge = ChampionChallenge {
matches: 5,
wins: 2,
best_placement: Some(2),
completed_on: None,
};
let mut row = row(Some(challenge));
row.attempts = Some(5);
let card = Card::from_row(&row);
assert_eq!(
lines(&card),
[
("Parties", "5".to_string()),
("Victoires", "2".into()),
("Meilleur Placement", "2ᵉ".into()),
("Tentatives", "5".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
assert!(card.sheet.iter().all(|(label, _)| *label != FIRST_TOP_1));
}
#[test]
fn the_sheet_of_a_completed_champion_has_the_date_of_its_first_top_1() {
let challenge = ChampionChallenge {
matches: 6,
wins: 3,
best_placement: Some(1),
completed_on: Some(day()),
};
let mut row = row(Some(challenge));
row.attempts = Some(4);
assert_eq!(
lines(&Card::from_row(&row)),
[
("Parties", "6".to_string()),
("Victoires", "3".into()),
("Meilleur Placement", "1ᵉʳ".into()),
("Tentatives", "4".into()),
("Points de maîtrise", "154\u{202f}320".into()),
("Premier top 1", "02/03/2026".into()),
]
);
}
#[test]
fn the_sheet_of_a_row_without_a_season_has_dashes_and_no_date() {
let card = Card::from_row(&row(None));
assert_eq!(
lines(&card),
[
("Parties", "—".to_string()),
("Victoires", "—".into()),
("Meilleur Placement", "—".into()),
("Tentatives", "—".into()),
("Points de maîtrise", "154\u{202f}320".into()),
]
);
}
#[test]
fn the_sheet_shows_zero_points_as_zero_and_unknown_points_as_unknown() {
let mut row = row(None);
row.mastery_points = Some(0);
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "0".to_string())
);
row.mastery_points = None;
let card = Card::from_row(&row);
assert_eq!(
lines(&card).last().unwrap(),
&("Points de maîtrise", "Inconnus".to_string())
);
}
#[test]
fn a_row_without_a_challenge_has_no_marks() {
let card = Card::from_row(&row(None));
assert_eq!(marks(&card), (false, false));
assert!(!card.greyed());
}
#[test]
fn the_tall_portrait_is_shown_and_the_square_icon_stands_in_while_it_is_missing() {
let tall = PathBuf::from("portraits/cards/TwistedFate.jpg");
let square = PathBuf::from("portraits/TwistedFate.png");
let both = ChampionRow {
portrait: Some(square.clone()),
card_portrait: Some(tall.clone()),
..row(None)
};
assert_eq!(
Card::from_row(&both).portrait.as_deref(),
Some(tall.as_path())
);
let downloading = ChampionRow {
card_portrait: None,
..both
};
assert_eq!(
Card::from_row(&downloading).portrait.as_deref(),
Some(square.as_path())
);
// Neither: the card keeps its plain background.
assert_eq!(Card::from_row(&row(None)).portrait, None);
}
fn completed_row() -> ChampionRow {
row(Some(ChampionChallenge {
matches: 1,
wins: 1,
best_placement: Some(1),
completed_on: Some(day()),
}))
}
fn reasons_of(banned: bool, taken_by_ally: bool, not_offered: bool) -> Unpickable {
Unpickable {
banned,
taken_by_ally,
not_offered,
}
}
#[test]
fn the_champ_selects_reasons_add_up_in_a_fixed_order() {
let all = reasons_of(true, true, true);
let card = Card::from_row(&completed_row()).with_unpickable(all);
assert_eq!(
card.reasons,
[
Reason::Completed,
Reason::Banned,
Reason::TakenByAlly,
Reason::NotOffered
]
);
let labels: Vec<_> = card.reasons.iter().map(|r| r.label()).collect();
assert_eq!(
labels,
["Validé", "Banni", "Pris par un allié", "Indisponible"]
);
let card = Card::from_row(&row(None)).with_unpickable(reasons_of(false, true, false));
assert_eq!(card.reasons, [Reason::TakenByAlly]);
let card = Card::from_row(&completed_row()).with_unpickable(reasons_of(true, false, false));
assert_eq!(card.reasons, [Reason::Completed, Reason::Banned]);
}
#[test]
fn a_champion_the_champ_select_does_not_hold_back_is_not_greyed_by_it() {
let card = Card::from_row(&row(None)).with_unpickable(Unpickable::default());
assert!(card.reasons.is_empty());
assert!(!card.greyed());
// The player's own pick has no reason from the champ select, but a Completed one stays.
let card = Card::from_row(&completed_row()).with_unpickable(Unpickable::default());
assert_eq!(card.reasons, [Reason::Completed]);
assert!(card.greyed());
let card = Card::from_row(&row(None)).with_unpickable(reasons_of(false, false, true));
assert!(card.greyed());
}
+458
View File
@@ -0,0 +1,458 @@
//! The card grid: all the cards a list shows, in rows of the same count, only the visible rows
//! built (a grid that scrolls by itself, or one the page scrolls). It is its own view because it
//! owns the hover of its cards, the scrolling of its list when it has one, and the portraits they
//! show (`card_images`). Its cards never change on hover or focus: the card under the pointer or
//! the keyboard is drawn lifted over the grid (`card_lift`), from where the grid last placed it.
use std::collections::HashMap;
use std::ops::Range;
use std::rc::Rc;
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::card::{Card, Reason, card};
use crate::card_images::{self, CardImages};
mod focus;
pub use focus::init;
use focus::{CONTEXT, CardFocus, NextCard, PreviousCard};
mod geometry;
use geometry::{MAX_COLUMNS, Metrics, rows_in_view};
pub use geometry::{MAX_WIDTH, TAKEN_DROP};
mod layout;
pub use layout::{CardHovered, DrawnCard, DrawnCards, Paging, PutDown, RevealRow};
pub struct CardGrid {
/// All the cards in the order the page gives (the chosen sort); replaced when the statistics
/// or the sort change.
cards: Rc<[Card]>,
/// Indices into `cards`, after the filter and the search.
shown: Vec<usize>,
scroll: UniformListScrollHandle,
/// The card under the pointer or the keyboard, which is lifted.
hovered: Option<u32>,
/// Where the visible cards were drawn last.
drawn_cards: DrawnCards,
/// How far the list was scrolled when last drawn: a wheel that leaves it there (at either
/// end) moves no card from under the pointer.
drawn_scroll: Pixels,
/// One per card id, kept across `set_cards` and dropped with the card.
focus: HashMap<u32, CardFocus>,
/// The cards changed since the focus handles were last matched to them.
focus_stale: bool,
/// All the rows built as a plain column, with no scrolling of its own: for a short list
/// whose height comes from its content (the Anvil champions row of a champ select).
fit_content: bool,
/// For a grid the page scrolls: where that scrolling has it, which says the rows built. The
/// grid is as tall as all its rows, and holds no scrolling of its own.
paged: Option<Paging>,
/// The portraits of the cards it paints, its own: made by its first render.
images: Option<Entity<CardImages>>,
/// Guard the light rendering in tests.
#[cfg(test)]
pub(crate) renders: usize,
#[cfg(test)]
pub(crate) card_builds: usize,
#[cfg(test)]
pub(crate) set_cards_calls: usize,
}
impl EventEmitter<CardHovered> for CardGrid {}
impl EventEmitter<PutDown> for CardGrid {}
impl EventEmitter<RevealRow> for CardGrid {}
impl CardGrid {
pub fn new() -> CardGrid {
CardGrid {
cards: Rc::new([]),
shown: Vec::new(),
scroll: UniformListScrollHandle::new(),
hovered: None,
drawn_cards: DrawnCards::default(),
drawn_scroll: Pixels::ZERO,
focus: HashMap::new(),
focus_stale: false,
fit_content: false,
paged: None,
images: None,
#[cfg(test)]
renders: 0,
#[cfg(test)]
card_builds: 0,
#[cfg(test)]
set_cards_calls: 0,
}
}
/// A grid that is as tall as its rows and builds them all. It has the home grid's cards and
/// metrics. The parent uses the same row height to lay out the cached hand.
pub fn fit_content() -> CardGrid {
CardGrid {
fit_content: true,
..CardGrid::new()
}
}
/// A grid as tall as all its rows, whose scrolling is the page's: it builds the rows that
/// scrolling has in view of the window.
pub fn paged(paging: Paging) -> CardGrid {
CardGrid {
paged: Some(paging),
..CardGrid::new()
}
}
/// How tall the grid is with all its rows, none for an empty one: what a grid that is
/// as tall as its rows (the hand, a paged grid) is given.
pub fn rows_height(&self, window_width: Pixels) -> Option<Pixels> {
let metrics = Metrics::of(window_width);
let rows = self.shown.len().div_ceil(metrics.columns);
(rows > 0).then(|| px(metrics.row_height() * rows as f32))
}
/// Replaces the cards; the grid is drawn again only when they differ (reloads keep coming
/// during an import). `set_shown` follows, as the indices belong to the cards.
pub fn set_cards(&mut self, cards: Rc<[Card]>, cx: &mut Context<Self>) {
#[cfg(test)]
{
self.set_cards_calls += 1;
}
if *self.cards != *cards {
self.cards = cards;
self.focus_stale = true;
self.forget_hover_if_gone(cx);
cx.notify();
}
}
fn set_hovered(&mut self, id: u32, hovered: bool, cx: &mut Context<Self>) {
let next = match (hovered, self.hovered) {
(true, _) => Some(id),
(false, Some(current)) if current == id => None,
(false, current) => current,
};
self.hover(next, cx);
}
/// The one change of the card under the pointer or the keyboard: it is told (the ring
/// lights that card's tick, the card is lifted over the grid), and the grid is not drawn
/// again.
fn hover(&mut self, next: Option<u32>, cx: &mut Context<Self>) {
self.hover_by(next, false, cx);
}
fn hover_by(&mut self, next: Option<u32>, by_keyboard: bool, cx: &mut Context<Self>) {
if next != self.hovered {
self.hovered = next;
cx.emit(CardHovered {
id: next,
by_keyboard,
});
}
}
/// The pointer moved while the keyboard had lifted a card, or the pointer went to another
/// grid: none of its cards is under the pointer or the keyboard any more.
pub fn put_down(&mut self, cx: &mut Context<Self>) {
self.hover(None, cx);
}
/// The card under the pointer is no longer shown (filtered out, or gone with new cards):
/// none is hovered until the pointer moves again.
fn forget_hover_if_gone(&mut self, cx: &mut Context<Self>) {
let shown = |id| {
(self.shown.iter()).any(|&ix| self.cards.get(ix).is_some_and(|card| card.id == id))
};
if self.hovered.is_some_and(|id| !shown(id)) {
self.hover(None, cx);
// It would settle back where it is no longer drawn.
cx.emit(PutDown);
}
}
/// How far down the list is scrolled, as its next layout will put it: a wheel past either end
/// is held there.
fn scrolled_to(&self) -> Pixels {
let handle = &self.scroll.0.borrow().base_handle;
handle
.offset()
.y
.max(-handle.max_offset().y)
.min(Pixels::ZERO)
}
/// The grid is not shown any more: its portraits are given back, in memory and in the
/// window's atlas, and load again when it is drawn.
pub fn release_images(&mut self, window: &mut Window, cx: &mut Context<Self>) {
// Nor is any of its cards under the pointer: the ring's tick goes out.
self.hover(None, cx);
cx.emit(PutDown);
self.drawn_cards.borrow_mut().clear();
let released = self
.images
.as_ref()
.is_some_and(|images| images.update(cx, |images, cx| images.release(window, cx)));
if released {
// A cached view replays its last paint unless it is drawn again.
cx.notify();
}
}
/// The indices of the cards shown, in order.
pub fn shown(&self) -> &[usize] {
&self.shown
}
pub fn set_shown(&mut self, shown: Vec<usize>, cx: &mut Context<Self>) {
if self.shown != shown {
self.shown = shown;
self.forget_hover_if_gone(cx);
cx.notify();
}
}
#[cfg(test)]
pub(crate) fn names(&self) -> Vec<SharedString> {
self.shown
.iter()
.filter_map(|&ix| self.cards.get(ix))
.map(|card| card.name.clone())
.collect()
}
/// The cards shown, in order.
#[cfg(test)]
pub(crate) fn shown_cards(&self) -> Vec<Card> {
self.shown
.iter()
.filter_map(|&ix| self.cards.get(ix))
.cloned()
.collect()
}
/// The card under the pointer or the keyboard.
pub fn hovered(&self) -> Option<u32> {
self.hovered
}
/// The portraits its cards show, for a card drawn over it.
pub fn images(&self) -> Option<&Entity<CardImages>> {
self.images.as_ref()
}
/// Where its visible cards were drawn last.
pub fn drawn_cards(&self) -> &DrawnCards {
&self.drawn_cards
}
/// All its cards, which `DrawnCard::ix` indexes.
pub fn cards(&self) -> &Rc<[Card]> {
&self.cards
}
/// A grid as tall as its rows: the hand of a champ select.
pub fn is_hand(&self) -> bool {
self.fit_content
}
/// How far the grid is scrolled down.
#[cfg(test)]
pub(crate) fn scrolled(&self) -> Pixels {
-self.scroll.0.borrow().base_handle.offset().y
}
fn row(&mut self, ix: usize, metrics: Metrics, cx: &mut Context<Self>) -> AnyElement {
let start = ix * metrics.columns;
// The id and index of the card in each slot, for the row to record where it drew them.
let mut in_slots = [None; MAX_COLUMNS];
let mut slots = Vec::with_capacity(metrics.columns);
for (column, slot) in (start..start + metrics.columns).enumerate() {
// A stale index shows nothing rather than panicking.
let shown = self.shown.get(slot).copied();
match shown.and_then(|c| Some((c, self.cards.get(c)?))) {
Some((c, data)) => {
#[cfg(test)]
{
self.card_builds += 1;
}
let id = data.id;
in_slots[column] = Some((id, c));
let focus = self.focus.get(&id).map(|focus| &focus.handle);
// In the hand, a card an ally took rests a little lower than the others.
let lowered = self.is_hand() && data.reasons.contains(&Reason::TakenByAlly);
slots.push(
card(data, focus, cx)
.when(lowered, |card| card.top(px(TAKEN_DROP)))
.on_hover(cx.listener(move |grid, hovered: &bool, _, cx| {
grid.set_hovered(id, *hovered, cx)
}))
.into_any_element(),
);
}
// The last row keeps every card the same width.
None => slots.push(div().flex_1().min_w_0().into_any_element()),
}
}
let drawn_cards = self.drawn_cards.clone();
div()
.h_flex()
.items_start()
.w_full()
.h(px(metrics.card_height + metrics.gap))
.pb(px(metrics.gap))
// The lane of the list's scrollbar; the page's column leaves its own to the grids it
// scrolls.
.pr(if self.fit_content || self.paged.is_some() {
Pixels::ZERO
} else {
Scrollbar::width()
})
.gap(px(metrics.gap))
// Only a row painted is laid out here, not one `uniform_list` merely measures.
.on_children_prepainted(move |bounds, window, _| {
let visible = window.content_mask().bounds;
let mut drawn_cards = drawn_cards.borrow_mut();
for (slot, bounds) in in_slots.iter().zip(bounds) {
if let Some((id, ix)) = *slot {
drawn_cards.insert(
id,
DrawnCard {
bounds,
visible,
ix,
},
);
}
}
})
.children(slots)
.into_any_element()
}
}
impl CardGrid {
/// The grid's key context, its portraits and what it reacts to besides its cards.
fn with_cards_behaviour(
&self,
root: Div,
images: Entity<CardImages>,
cx: &mut Context<Self>,
) -> Div {
card_images::provide(root, images)
.key_context(CONTEXT)
// A wheel scroll moves cards under a still pointer without a hover event: the
// sheet of the card that was under it would stay. The next mouse move hovers again.
.on_scroll(cx.listener(|grid, _: &ScrollEvent, _, cx| {
// The list has scrolled first. A grid that fits its content, or that the page
// scrolls, is moved by its parent's scrolling instead, which it cannot see.
let moved = grid.fit_content
|| grid.paged.is_some()
|| grid.scrolled_to() != grid.drawn_scroll;
if moved {
grid.hover(None, cx);
}
// Even at either end of the list, no card stays lifted after a wheel; one that
// stays under the pointer keeps its tick lit.
cx.emit(PutDown);
}))
.on_action(cx.listener(|grid, _: &NextCard, window, cx| grid.move_focus(1, window, cx)))
.on_action(
cx.listener(|grid, _: &PreviousCard, window, cx| grid.move_focus(-1, window, cx)),
)
}
}
impl Render for CardGrid {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
if self.focus_stale {
self.sync_focus(window, cx);
}
self.drawn_scroll = self.scrolled_to();
// Only the rows drawn now place their cards.
self.drawn_cards.borrow_mut().clear();
let images = (self.images)
.get_or_insert_with(|| CardImages::new(cx))
.clone();
images.update(cx, |images, cx| images.start_render(window, cx));
if self.shown.is_empty() {
let muted = cx.theme().muted_foreground;
return div()
.w_full()
.debug_selector(|| "no-champion".into())
.py(px(30.))
.text_color(muted)
.child("Aucun champion trouvé")
.into_any_element();
}
let metrics = Metrics::of(window.viewport_size().width);
let rows = self.shown.len().div_ceil(metrics.columns);
if self.fit_content {
// The same rows and cards (sheet, hover, keyboard focus), all built, as a column.
let rows: Vec<_> = (0..rows).map(|ix| self.row(ix, metrics, cx)).collect();
return self
.with_cards_behaviour(div().v_flex().w_full(), images, cx)
.children(rows)
.into_any_element();
}
if let Some(paging) = self.paged.clone() {
// Read now, not when the page was drawn: the page's scrolling has been held within its
// content since. Not laid out yet, the grid is taken to start at the top of the window,
// where the header clicked to open it leaves it: the next frame knows.
let scrolled = -paging.scroll.offset().y;
let last_height = paging.scroll.bounds().size.height;
let viewport = if last_height > Pixels::ZERO {
last_height
} else {
window.viewport_size().height
};
let top = paging.top.get().unwrap_or(scrolled);
let in_view = rows_in_view(rows, px(metrics.row_height()), top, scrolled, viewport);
// Rows that are not in view are left out, as a space above the first one built.
let space = px(metrics.row_height() * in_view.start as f32);
let rows: Vec<_> = in_view.map(|ix| self.row(ix, metrics, cx)).collect();
return self
.with_cards_behaviour(div().v_flex().w_full(), images, cx)
.debug_selector(|| "card-list".into())
.pt(space)
.children(rows)
.into_any_element();
}
self.with_cards_behaviour(div().relative().size_full(), images, cx)
.debug_selector(|| "card-list".into())
.child(
uniform_list(
"cards",
rows,
cx.processor(move |grid, range: Range<usize>, _, cx| {
range
.map(|ix| grid.row(ix, metrics, cx))
.collect::<Vec<_>>()
}),
)
.size_full()
.track_scroll(&self.scroll),
)
.child(
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(Scrollbar::width())
.child(Scrollbar::vertical(&self.scroll)),
)
.into_any_element()
}
}
#[cfg(test)]
mod tests;
+112
View File
@@ -0,0 +1,112 @@
//! The grid's keyboard: each card has a focus handle, and Tab and Shift-Tab move between the
//! cards, bringing the row of the one reached into view.
use gpui_kit::*;
use super::geometry::Metrics;
use super::{CardGrid, RevealRow};
use crate::card::Card;
actions!(card_grid, [NextCard, PreviousCard]);
/// The grid's key context, where Tab and Shift-Tab move between its cards.
pub(super) const CONTEXT: &str = "CardGrid";
/// Binds Tab and Shift-Tab in the grid's context, where they win over gpui-kit's root: the
/// rows are virtual, so the next card may not be built yet and the root cannot reach it.
pub fn init(cx: &mut App) {
cx.bind_keys([
KeyBinding::new("tab", NextCard, Some(CONTEXT)),
KeyBinding::new("shift-tab", PreviousCard, Some(CONTEXT)),
]);
}
/// What makes one card reachable with the keyboard: its handle, and the subscriptions that lift
/// it while the keyboard is on it.
pub(super) struct CardFocus {
pub(super) handle: FocusHandle,
_subscriptions: [Subscription; 2],
}
impl CardGrid {
/// Gives every card a focus handle, reusing the ones of the ids already there. It runs when
/// the grid is drawn after `set_cards`, as subscribing needs the window.
pub(super) fn sync_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.focus_stale = false;
let mut previous = std::mem::take(&mut self.focus);
for card in self.cards.iter() {
let id = card.id;
let focus = previous.remove(&id).unwrap_or_else(|| {
let handle = cx.focus_handle().tab_stop(true);
// As `:focus-visible`: a card focused by a click is already under the pointer.
let gained = cx.on_focus_in(&handle, window, move |grid, window, cx| {
if window.last_input_was_keyboard() {
grid.hover_by(Some(id), true, cx);
// Tab came from outside the grid too: the page is to show the card.
let position = grid.position_of(id);
grid.reveal_in_page(position, window, cx);
}
});
let lost = cx.on_focus_out(&handle, window, move |grid, _, _, cx| {
grid.set_hovered(id, false, cx);
});
CardFocus {
handle,
_subscriptions: [gained, lost],
}
});
self.focus.insert(id, focus);
}
}
/// Moves the focus `step` cards on in the grid's order, scrolling its row into view since
/// only the visible rows are built (a paged grid asks the page to). At either end the key
/// goes on, to leave the grid.
pub(super) fn move_focus(&mut self, step: isize, window: &mut Window, cx: &mut Context<Self>) {
let focused = |card: &Card| {
self.focus
.get(&card.id)
.is_some_and(|focus| focus.handle.is_focused(window))
};
let current = self
.shown
.iter()
.position(|&ix| self.cards.get(ix).is_some_and(focused));
let target = current
.and_then(|current| current.checked_add_signed(step))
.filter(|&target| target < self.shown.len());
let handle = target.and_then(|target| {
let card = self.cards.get(*self.shown.get(target)?)?;
Some((target, self.focus.get(&card.id)?.handle.clone()))
});
let Some((target, handle)) = handle else {
cx.propagate();
return;
};
if self.paged.is_some() {
self.reveal_in_page(Some(target), window, cx);
} else if !self.fit_content {
let columns = Metrics::of(window.viewport_size().width).columns;
self.scroll
.scroll_to_item(target / columns, ScrollStrategy::Nearest);
}
window.focus(&handle, cx);
}
/// Where the card with this id is among the cards shown.
fn position_of(&self, id: u32) -> Option<usize> {
let is_it = |&ix: &usize| self.cards.get(ix).is_some_and(|card| card.id == id);
self.shown.iter().position(is_it)
}
/// A paged grid asks the page to scroll to the row of the card at this position.
fn reveal_in_page(&mut self, position: Option<usize>, window: &Window, cx: &mut Context<Self>) {
let (Some(position), true) = (position, self.paged.is_some()) else {
return;
};
let metrics = Metrics::of(window.viewport_size().width);
let top = px(metrics.row_height() * (position / metrics.columns) as f32);
let bottom = top + px(metrics.card_height);
cx.emit(RevealRow { top, bottom });
}
}
+83
View File
@@ -0,0 +1,83 @@
use gpui_kit::Pixels;
use gpui_kit::component::scroll::Scrollbar;
use crate::card::ASPECT;
use crate::page::PAGE_PADDING;
/// The widest content column of the home, as in the mockup.
pub const MAX_WIDTH: f32 = 1264.;
/// How much lower than the others a card of the hand taken by an ally rests (#87).
pub const TAKEN_DROP: f32 = 8.;
/// The most cards a row holds.
pub(super) const MAX_COLUMNS: usize = 6;
/// How many cards fit a row of a window `width` wide, with the mockup's breakpoints: its
/// `max-width` rules apply up to and including 1000, 720 and 480 px.
pub(super) fn columns(width: Pixels) -> usize {
match width.as_f32() {
w if w > 1000. => MAX_COLUMNS,
w if w > 720. => 4,
w if w > 480. => 3,
_ => 2,
}
}
/// Smaller gaps in the narrow layouts, as in the mockup.
fn gap(columns: usize) -> f32 {
if columns >= 4 { 14. } else { 10. }
}
/// What a frame needs to know, from the window width alone: `uniform_list` measures its first
/// row without knowing the list's width, so the row height cannot come from the layout.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) struct Metrics {
pub(super) columns: usize,
pub(super) gap: f32,
/// A card's height; a row is this plus a gap tall.
pub(super) card_height: f32,
}
impl Metrics {
pub(super) fn of(window_width: Pixels) -> Metrics {
let columns = columns(window_width);
let gap = gap(columns);
// The column the page centres, minus the scrollbar's lane.
let content = (window_width.as_f32() - 2. * PAGE_PADDING).min(MAX_WIDTH)
- Scrollbar::width().as_f32();
let card_width = (content - gap * (columns - 1) as f32) / columns as f32;
Metrics {
columns,
gap,
card_height: (card_width / ASPECT).max(0.),
}
}
/// What one row of the list takes: a card and the gap under it.
pub(super) fn row_height(&self) -> f32 {
self.card_height + self.gap
}
}
/// Which rows of a grid of `rows` rows, `row_height` tall each, a viewport shows: the grid's top
/// is `top` down the scrolled content, which is scrolled `scrolled`, and the viewport is
/// `viewport` tall. A row shown in part counts. A grid wholly below the window keeps its first
/// row built: the keyboard enters the grid there (Tab from the search), and the page scrolls to it.
pub(super) fn rows_in_view(
rows: usize,
row_height: Pixels,
top: Pixels,
scrolled: Pixels,
viewport: Pixels,
) -> std::ops::Range<usize> {
let row_height = row_height.as_f32().max(1.);
let above = (scrolled - top).as_f32();
let below = above + viewport.as_f32();
if below <= 0. {
return 0..rows.min(1);
}
let first = ((above.max(0.) / row_height).floor() as usize).min(rows);
let last = ((below.max(0.) / row_height).ceil() as usize).min(rows);
first..last.max(first)
}
+48
View File
@@ -0,0 +1,48 @@
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use gpui_kit::{Bounds, Pixels, ScrollHandle};
/// The card under the pointer, or the one the keyboard is on, changed: its id, or none.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CardHovered {
pub id: Option<u32>,
/// The keyboard brought it: the pointer moving puts it down.
pub by_keyboard: bool,
}
/// None of the grid's cards stays lifted, at once: a wheel turned over them, or they are no
/// longer shown.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PutDown;
/// What a grid the page scrolls reads to know which of its rows are in view: the page's scrolling
/// and where the grid starts in it.
#[derive(Clone)]
pub struct Paging {
pub scroll: ScrollHandle,
/// How far down the scrolled content the grid starts, as its last layout put it; none until
/// it was laid out.
pub top: Rc<Cell<Option<Pixels>>>,
}
/// The keyboard went to a card of a paged grid, whose scrolling is the page's: this row, as
/// the distances of its top and its bottom from the grid's top, is to be scrolled into view.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct RevealRow {
pub top: Pixels,
pub bottom: Pixels,
}
/// Where the grid last drew a card, in the window, the part of the window it showed of it, and
/// its index in the grid's cards.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DrawnCard {
pub bounds: Bounds<Pixels>,
pub visible: Bounds<Pixels>,
pub ix: usize,
}
/// The cards the grid drew last, by id: filled as its rows are laid out, read between its draws.
pub type DrawnCards = Rc<RefCell<HashMap<u32, DrawnCard>>>;
+55
View File
@@ -0,0 +1,55 @@
use gpui_kit::px;
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
use super::geometry::{Metrics, columns, rows_in_view};
use crate::card::ASPECT;
#[test]
fn the_columns_follow_the_mockups_breakpoints() {
for (width, expected) in [
(2560., 6),
(1280., 6),
(1001., 6),
(1000., 4),
(721., 4),
(720., 3),
(481., 3),
(480., 2),
(300., 2),
] {
assert_eq!(columns(px(width)), expected, "{width} px");
}
}
#[test]
fn the_rows_in_view_are_those_the_window_shows_even_in_part() {
// 10 rows of 100 px, the grid starting 250 px down the content, in a 400 px window.
let rows = |scrolled: f32| rows_in_view(10, px(100.), px(250.), px(scrolled), px(400.));
// Above it: the window ends 150 px into the grid, in its second row.
assert_eq!(rows(0.), 0..2);
assert_eq!(rows(100.), 0..3);
// Inside it: the rows cut by either edge count.
assert_eq!(rows(400.), 1..6);
// Wholly below the window: its first row, for the keyboard to enter by.
assert_eq!(rows_in_view(10, px(100.), px(900.), px(0.), px(400.)), 0..1);
// Past its end: nothing.
assert_eq!(rows(2000.), 10..10);
// No row.
assert_eq!(rows_in_view(0, px(100.), px(0.), px(0.), px(400.)), 0..0);
}
#[test]
fn the_cards_fill_the_column_the_page_centres() {
use gpui_kit::component::scroll::Scrollbar;
for (window, column) in [(1280., 1256.), (3000., 1264.), (800., 776.), (500., 476.)] {
let metrics = Metrics::of(px(window));
let card_width = metrics.card_height * ASPECT;
let row = card_width * metrics.columns as f32
+ metrics.gap * (metrics.columns - 1) as f32
+ Scrollbar::width().as_f32();
assert!(
(row - column).abs() < 0.01,
"{window} px: {row} vs {column}"
);
}
}
+156
View File
@@ -0,0 +1,156 @@
//! The portraits of a card grid: decoded only for the cards it paints, and freed, in memory and
//! on the GPU, once it paints them no more (rule #1: memory in proportion to what is shown). The
//! champion table holds its rows' portraits the same way.
//!
//! Each grid owns one `CardImages`, which its cards' `img` elements read through (`provide`),
//! never through GPUI's app-wide asset cache, which keeps every image it ever loaded. A grid may
//! be a cached view: while it is not rendered again, its last paint is replayed with the images
//! it used. So the cache only changes in the grid's own render: each one starts with
//! `start_render`, which drops what the previous render did not paint, as no frame shows it.
use std::collections::HashMap;
use std::sync::Arc;
use gpui_kit::*;
struct Entry {
/// The image, or its load while it runs, or why it failed.
item: ImageCacheItem,
/// The last render that painted it.
painted: u64,
}
pub struct CardImages {
entries: HashMap<Resource, Entry>,
/// The grid's render being drawn.
render: u64,
/// The grid is painting: `uniform_list` also lays rows out only to measure them, and a row
/// that is not painted is not shown, so its portraits are neither loaded nor kept.
painting: bool,
/// Loads started, to guard against retrying a failed one every frame.
#[cfg(test)]
pub(crate) loads: usize,
}
impl CardImages {
pub fn new(cx: &mut App) -> Entity<CardImages> {
let images = cx.new(|_| CardImages {
entries: HashMap::new(),
render: 0,
painting: false,
#[cfg(test)]
loads: 0,
});
// The grid is gone: so are its portraits, from every window's atlas too.
cx.observe_release(&images, |images, cx| {
for (_, entry) in images.entries.drain() {
if let Some(Ok(image)) = entry.item.get() {
cx.drop_image(image, None);
}
}
})
.detach();
images
}
/// Drops every portrait, in memory and in the window's atlas, for a grid that is no longer
/// shown: they load again when it is drawn. A load still running is cancelled. True when
/// something was held.
pub fn release(&mut self, window: &mut Window, cx: &mut App) -> bool {
let held = !self.entries.is_empty();
for (_, entry) in self.entries.drain() {
if let Some(Ok(image)) = entry.item.get() {
cx.drop_image(image, Some(window));
}
}
held
}
/// Called first in each render of the grid. The frame on screen shows what the previous
/// render painted, and the frame being drawn shows only what this one will paint: anything
/// else is dropped, in memory and in the window's atlas. A load still running is cancelled.
pub fn start_render(&mut self, window: &mut Window, cx: &mut App) {
let previous = self.render;
self.entries.retain(|_, entry| {
if entry.painted == previous {
return true;
}
if let Some(Ok(image)) = entry.item.get() {
cx.drop_image(image, Some(window));
}
false
});
self.render += 1;
self.painting = false;
}
}
impl ImageCache for CardImages {
/// While the grid lays out, an image already there is given back and nothing is loaded.
/// While it paints, a missing image starts loading off the UI thread, and its end draws the
/// grid again. A failed load is kept, so it is not tried again while the card stays shown.
fn load(
&mut self,
resource: &Resource,
window: &mut Window,
cx: &mut App,
) -> Option<Result<Arc<RenderImage>, ImageCacheError>> {
if !self.painting {
return self
.entries
.get(resource)
.and_then(|entry| entry.item.get());
}
let render = self.render;
let entry = self.entries.entry(resource.clone()).or_insert_with(|| {
#[cfg(test)]
{
self.loads += 1;
}
Entry {
item: ImageCacheItem::new(resource, cx),
painted: render,
}
});
entry.painted = render;
entry.item.use_image(window)
}
}
/// `root`, whose `img` elements read through `images`. `root` gets its children after this:
/// a mark painted before them tells `images` that the grid paints.
pub fn provide(root: Div, images: Entity<CardImages>) -> Div {
let painting = images.clone();
root.image_cache(images).child(
canvas(
|_, _, _| {},
move |_, _, _, cx| painting.update(cx, |images, _| images.painting = true),
)
.absolute(),
)
}
#[cfg(test)]
impl CardImages {
/// The portraits held, loaded or not, sorted.
pub(crate) fn held(&self) -> Vec<std::path::PathBuf> {
let mut paths: Vec<_> = (self.entries.keys())
.filter_map(|resource| match resource {
Resource::Path(path) => Some(path.to_path_buf()),
_ => None,
})
.collect();
paths.sort();
paths
}
/// The images decoded.
pub(crate) fn loaded(&self) -> Vec<Arc<RenderImage>> {
(self.entries.values())
.filter_map(|entry| entry.item.get()?.ok())
.collect()
}
}
#[cfg(test)]
pub(crate) mod tests;
+298
View File
@@ -0,0 +1,298 @@
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use arena_tracker_core::Marks;
use gpui_kit::{
AppContext as _, Bounds, Context, Entity, ImageSource, InteractiveElement as _, IntoElement,
Modifiers, ParentElement as _, Render, RenderImage, ScrollDelta, ScrollEvent, StyleRefinement,
Styled as _, TestAppContext, VisualTestContext, Window, WindowBounds, WindowOptions, div,
point, px, red, size,
};
use super::CardImages;
use crate::card::Card;
use crate::card_grid::CardGrid;
/// A 68 x 100 JPEG, as the core stores the card portraits (smaller).
pub(crate) const PORTRAIT_JPEG: &[u8] = include_bytes!("../../tests/fixtures/portrait.jpg");
/// A folder of its own in the system's temporary folder, removed with the value.
pub(crate) struct TestDir(PathBuf);
impl TestDir {
pub(crate) fn new(name: &str) -> TestDir {
static NEXT: AtomicUsize = AtomicUsize::new(0);
let path = std::env::temp_dir().join(format!(
"arena-tracker-{name}-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::SeqCst)
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
TestDir(path)
}
pub(crate) fn path(&self) -> &Path {
&self.0
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A bar with a button, as the page's header, above the grid as the home has it: cached.
struct Host {
grid: Option<Entity<CardGrid>>,
}
impl Render for Host {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.size_full()
.flex()
.flex_col()
.child(
div().h(px(60.)).flex_shrink_0().child(
div()
.id("outside")
.debug_selector(|| "outside".into())
.w(px(200.))
.h_full()
.hover(|style| style.bg(red())),
),
)
.children(self.grid.clone().map(|grid| {
grid.cached(StyleRefinement::default().w_full().flex_1().min_h(px(240.)))
}))
}
}
fn portrait(dir: &Path, id: u32) -> PathBuf {
dir.join(format!("{id}.jpg"))
}
/// A 1280 x 860 window, as the page tests', on `count` cards whose portraits are in `dir`,
/// written there when `write`.
fn open_grid(
cx: &mut TestAppContext,
dir: &Path,
count: u32,
write: bool,
) -> (Entity<Host>, Entity<CardGrid>, VisualTestContext) {
cx.update(gpui_kit::init);
let cards: Rc<[Card]> = (1..=count)
.map(|id| {
let path = portrait(dir, id);
if write {
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
}
Card {
id,
name: format!("Champion {id:03}").into(),
portrait: Some(path.into()),
marks: Marks {
played: false,
won: false,
completed: false,
},
reasons: Vec::new(),
sheet: Vec::new(),
}
})
.collect();
let (window, host) = cx.update(|cx| {
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
})),
..Default::default()
};
gpui_kit::open_window(options, cx, |_, cx| {
let grid = cx.new(|cx| {
let mut grid = CardGrid::new();
grid.set_cards(cards, cx);
grid.set_shown((0..count as usize).collect(), cx);
grid
});
cx.new(|_| Host { grid: Some(grid) })
})
.unwrap()
});
let grid = cx.read(|cx| host.read(cx).grid.clone().unwrap());
(host, grid, VisualTestContext::from_window(window, cx))
}
fn draw(cx: &mut VisualTestContext) {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
/// Draws, lets the started loads end, and draws what they drew again.
fn draw_loaded(cx: &mut VisualTestContext) {
draw(cx);
cx.run_until_parked();
draw(cx);
}
fn images(grid: &Entity<CardGrid>, cx: &mut VisualTestContext) -> Entity<CardImages> {
grid.read_with(cx, |grid, _| grid.images().cloned())
.expect("the grid was not rendered")
}
/// The ids of the cards drawn in the last frame.
fn drawn(cx: &mut VisualTestContext, count: u32) -> Vec<u32> {
(1..=count)
.filter(|id| {
cx.debug_bounds(Box::leak(format!("card-{id}").into_boxed_str()))
.is_some()
})
.collect()
}
fn portraits(dir: &Path, ids: &[u32]) -> Vec<PathBuf> {
let mut paths: Vec<_> = ids.iter().map(|&id| portrait(dir, id)).collect();
paths.sort();
paths
}
fn in_atlas(cx: &mut VisualTestContext, image: &RenderImage) -> bool {
cx.update(|window, _| window.has_image_atlas_entry(image))
}
fn scroll(cx: &mut VisualTestContext, by: f32) {
cx.simulate_event(ScrollEvent {
position: point(px(640.), px(400.)),
delta: ScrollDelta::Pixels(point(px(0.), px(by))),
..Default::default()
});
}
#[gpui::test]
fn only_the_portraits_of_the_drawn_cards_are_kept(cx: &mut TestAppContext) {
let dir = TestDir::new("drawn-portraits");
let (_host, grid, mut window) = open_grid(cx, dir.path(), 170, true);
let cx = &mut window;
draw_loaded(cx);
let top = drawn(cx, 170);
// A few rows of 6, not the 170 cards; the first row is measured on every render, and
// its portraits are not kept for that.
assert!(top.contains(&1) && top.len() <= 6 * 4, "{top:?}");
let images = images(&grid, cx);
assert_eq!(
images.read_with(cx, |images, _| images.held()),
portraits(dir.path(), &top)
);
let first = images.read_with(cx, |images, _| images.loaded());
assert_eq!(first.len(), top.len(), "the portraits were not decoded");
assert!(first.iter().all(|image| in_atlas(cx, image)));
// Never through the app-wide asset cache, which would keep them.
cx.update(|_, cx| {
for &id in &top {
let source = ImageSource::from(portrait(dir.path(), id));
assert!(!source.is_asset_cached(cx), "card {id}");
}
});
// To the end: the last rows' portraits are loaded, and the first rows' ones are dropped,
// from the GPU atlas too.
scroll(cx, -100_000.);
draw_loaded(cx);
let bottom = drawn(cx, 170);
assert!(bottom.contains(&170) && !bottom.contains(&1), "{bottom:?}");
assert_eq!(
images.read_with(cx, |images, _| images.held()),
portraits(dir.path(), &bottom)
);
assert_eq!(
images.read_with(cx, |images, _| images.loaded()).len(),
bottom.len()
);
assert!(first.iter().all(|image| !in_atlas(cx, image)));
// Back to the top: loaded again.
let loads = images.read_with(cx, |images, _| images.loads);
scroll(cx, 100_000.);
draw_loaded(cx);
assert_eq!(drawn(cx, 170), top);
assert_eq!(
images.read_with(cx, |images, _| images.held()),
portraits(dir.path(), &top)
);
assert_eq!(
images.read_with(cx, |images, _| images.loads),
loads + top.len()
);
}
// The grid is a cached view: a frame that replays its last paint must keep its images.
#[gpui::test]
fn hovering_outside_the_grid_drops_no_portrait(cx: &mut TestAppContext) {
let dir = TestDir::new("hover-outside");
let (_host, grid, mut window) = open_grid(cx, dir.path(), 170, true);
let cx = &mut window;
draw_loaded(cx);
let images = images(&grid, cx);
let held = images.read_with(cx, |images, _| images.held());
let loaded = images.read_with(cx, |images, _| images.loaded());
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(!loaded.is_empty());
let button = cx.debug_bounds("outside").unwrap().center();
for _ in 0..2 {
cx.simulate_mouse_move(button, None, Modifiers::none());
draw(cx);
cx.simulate_mouse_move(point(px(1000.), px(30.)), None, Modifiers::none());
draw(cx);
}
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
assert_eq!(images.read_with(cx, |images, _| images.held()), held);
assert!(loaded.iter().all(|image| in_atlas(cx, image)));
}
#[gpui::test]
fn a_missing_portrait_leaves_the_card_readable_and_is_tried_once(cx: &mut TestAppContext) {
let dir = TestDir::new("missing-portraits");
let (_host, grid, mut window) = open_grid(cx, dir.path(), 30, false);
let cx = &mut window;
draw_loaded(cx);
let shown = drawn(cx, 30);
assert!(shown.contains(&1), "{shown:?}");
let images = images(&grid, cx);
assert!(images.read_with(cx, |images, _| images.loaded()).is_empty());
let loads = images.read_with(cx, |images, _| images.loads);
assert_eq!(loads, shown.len());
// Drawing the grid again, as a hover over its cards does, tries none of them again.
for _ in 0..3 {
grid.update(cx, |_, cx| cx.notify());
draw_loaded(cx);
}
assert_eq!(drawn(cx, 30), shown);
assert_eq!(images.read_with(cx, |images, _| images.loads), loads);
}
#[gpui::test]
fn the_portraits_are_freed_with_their_grid(cx: &mut TestAppContext) {
let dir = TestDir::new("freed-portraits");
let (host, grid, mut window) = open_grid(cx, dir.path(), 30, true);
let cx = &mut window;
draw_loaded(cx);
let loaded: Vec<Arc<RenderImage>> =
images(&grid, cx).read_with(cx, |images, _| images.loaded());
assert!(!loaded.is_empty());
assert!(loaded.iter().all(|image| in_atlas(cx, image)));
host.update(cx, |host, cx| {
host.grid = None;
cx.notify();
});
drop(grid);
draw(cx);
cx.run_until_parked();
assert!(loaded.iter().all(|image| !in_atlas(cx, image)));
}
+366
View File
@@ -0,0 +1,366 @@
//! The lift of the card under the pointer or the keyboard (#88): which cards are lifted, and how
//! far, in each grid. A card rises when the pointer or the keyboard comes to it and settles back
//! when it leaves, each time from where it is; in the hand, a veil lays on the other cards.
use std::rc::Rc;
use std::time::{Duration, Instant};
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::*;
use crate::card::{CARD_RADIUS, Card, MarkFill, Pose, lifted, veil_color};
use crate::card_grid::{DrawnCard, DrawnCards};
use crate::card_images::CardImages;
use crate::motion::{MATCH_SETTLE, ease_out};
/// How long a card takes to rise all the way, or to settle back.
const RISE: Duration = Duration::from_millis(350);
/// How long the hand's veil takes to lay on its cards, or to lift.
const VEIL: Duration = Duration::from_millis(300);
/// A value moving to `to`, from where it was when asked to.
#[derive(Clone, Copy, Debug)]
struct Tween {
from: f32,
to: f32,
start: Instant,
duration: Duration,
}
impl Tween {
fn value(&self, now: Instant) -> f32 {
self.from + (self.to - self.from) * ease_out(self.progress(now))
}
fn progress(&self, now: Instant) -> f32 {
if self.duration.is_zero() {
return 1.;
}
let elapsed = now.saturating_duration_since(self.start);
(elapsed.as_secs_f32() / self.duration.as_secs_f32()).min(1.)
}
fn done(&self, now: Instant) -> bool {
self.progress(now) >= 1.
}
/// Towards `to` from where it is now, over the part of `full` that is left to go.
fn toward(&self, to: f32, full: Duration, now: Instant) -> Tween {
let from = self.value(now);
Tween {
from,
to,
start: now,
duration: full.mul_f32((to - from).abs()),
}
}
fn rest(value: f32, now: Instant) -> Tween {
Tween {
from: value,
to: value,
start: now,
duration: Duration::ZERO,
}
}
}
/// A card lifted, or settling back, over grid `G`.
struct Entry<G> {
grid: G,
id: u32,
lift: Tween,
}
/// A card as it is drawn now: `progress` is 0 at rest and 1 lifted all the way.
pub(crate) struct Lifted {
pub id: u32,
pub progress: f32,
}
/// Which cards are lifted, by id: what they show is the grid's card as it is when drawn.
pub(crate) struct Lifts<G> {
/// In paint order: the card rising last.
cards: Vec<Entry<G>>,
/// The veil of each hand, while it is not lifted.
veils: Vec<(G, Tween)>,
}
impl<G: Copy + PartialEq> Lifts<G> {
pub fn new() -> Self {
Lifts {
cards: Vec::new(),
veils: Vec::new(),
}
}
/// The card under the pointer or the keyboard in `grid` is now `id`, or none: it rises,
/// and the one it replaces in that grid settles back.
/// In a hand (`veiled`), a veil lays on its other cards while one is lifted.
pub fn hover(&mut self, grid: G, id: Option<u32>, veiled: bool, now: Instant) {
if veiled {
let to = if id.is_some() { 1. } else { 0. };
match self.veils.iter_mut().find(|(hand, _)| *hand == grid) {
Some((_, veil)) if veil.to != to => *veil = veil.toward(to, VEIL, now),
Some(_) => {}
None => self
.veils
.push((grid, Tween::rest(0., now).toward(to, VEIL, now))),
}
}
for entry in self.cards.iter_mut() {
if entry.grid == grid && Some(entry.id) != id && entry.lift.to != 0. {
entry.lift = entry.lift.toward(0., RISE, now);
}
}
if let Some(id) = id {
// A card settling back rises again from where it is, drawn over the others.
let settling =
(self.cards.iter()).position(|entry| entry.grid == grid && entry.id == id);
let lift = match settling.map(|ix| self.cards.remove(ix)) {
Some(entry) if entry.lift.to == 1. => entry.lift,
Some(entry) => entry.lift.toward(1., RISE, now),
None => Tween::rest(0., now).toward(1., RISE, now),
};
self.cards.push(Entry { grid, id, lift });
}
}
/// The cards of `grid` moved under a still pointer (a wheel): none stays lifted, nor does
/// its veil, at once.
pub fn drop_grid(&mut self, grid: G) {
self.cards.retain(|entry| entry.grid != grid);
self.veils.retain(|(hand, _)| *hand != grid);
}
/// No card lifted any more, at once: the grids are no longer shown.
pub fn clear(&mut self) {
self.cards.clear();
self.veils.clear();
}
/// Every card and veil where it was going, at once: nothing to animate.
pub fn finish(&mut self, now: Instant) {
for entry in self.cards.iter_mut() {
entry.lift = Tween::rest(entry.lift.to, now);
}
for (_, veil) in self.veils.iter_mut() {
*veil = Tween::rest(veil.to, now);
}
self.tidy(now);
}
/// Forgets the cards back at rest: they are the grid's own again.
pub fn tidy(&mut self, now: Instant) {
self.cards
.retain(|entry| !(entry.lift.to == 0. && entry.lift.done(now)));
self.veils
.retain(|(_, veil)| !(veil.to == 0. && veil.done(now)));
}
/// Whether a card still moves.
pub fn animating(&self, now: Instant) -> bool {
self.cards.iter().any(|entry| !entry.lift.done(now))
|| self.veils.iter().any(|(_, veil)| !veil.done(now))
}
/// How far the veil lays on the cards of `grid`, 0 to 1.
pub fn veil(&self, grid: G, now: Instant) -> f32 {
(self.veils.iter())
.find(|(hand, _)| *hand == grid)
.map_or(0., |(_, veil)| veil.value(now))
}
/// The cards of `grid` to draw over it, in paint order.
pub fn lifted(&self, grid: G, now: Instant) -> impl Iterator<Item = Lifted> + '_ {
self.cards
.iter()
.filter(move |entry| entry.grid == grid)
.map(move |entry| Lifted {
id: entry.id,
progress: entry.lift.value(now),
})
}
}
/// The card of the champion a followed Match has just changed, drawn over its grid like a lifted
/// one at rest while it changes in place (#89).
pub(crate) struct Changing {
/// The card before the Match.
pub before: Rc<Card>,
/// Seconds since the comet landed (since the start without one): negative while it flies.
pub since_landing: f32,
}
/// A lifted card of the hand an ally just took (`stage::Taken`): it goes down to its place as
/// it greys, the card as it was fading over it.
pub(crate) struct Lowered {
pub id: u32,
/// How far above its place it still is.
pub above: f32,
pub before: Rc<Card>,
/// The opacity of the card as it was.
pub opacity: f32,
}
/// What changes on the lifted cards of a grid as they are drawn: the card of the home a followed
/// Match changes (#89), or the cards of the hand an ally just took (#87).
pub(crate) enum Changes {
Match(Changing),
Taken(Vec<Lowered>),
}
/// Draws the lifted cards of a grid over it, `lifted` in paint order with how far each is, and
/// the hand's `veil` over the others, where the grid last placed them and as `cards` holds them
/// now: the grid is not drawn again, and the pointer still meets its cards. Painted after the
/// rest of the page, so a card rises over what is above it; a card the grid shows only in part
/// stays cut where it is. The cards `changes` names show their change.
pub(crate) fn layer(
cards: Rc<[Card]>,
drawn_cards: DrawnCards,
images: Option<Entity<CardImages>>,
lifted_cards: Vec<Lifted>,
changes: Changes,
veil: f32,
moves: bool,
) -> AnyElement {
deferred(
canvas(
move |_, window, cx| {
let drawn_cards = drawn_cards.borrow();
let background = cx.theme().background;
let mut layers = Vec::new();
if veil > 0. {
for (id, drawn) in drawn_cards.iter() {
if !lifted_cards.iter().any(|lifted| lifted.id == *id) {
layers.push(Layer::Quad(drawn.bounds, veil_color(veil), drawn.visible));
}
}
}
for &Lifted { id, progress } in &lifted_cards {
let drawn = drawn_cards.get(&id);
let card = drawn.and_then(|drawn| cards.get(drawn.ix));
let (Some(drawn), Some(card)) = (drawn, card) else {
continue;
};
let change = match &changes {
Changes::Match(change) if change.before.id == id => Some(change),
_ => None,
};
// The card as it was until the comet lands.
let card = change
.filter(|c| c.since_landing < 0.)
.map_or(card, |c| c.before.as_ref());
let pose = Pose {
mark_fill: change.map(|c| MarkFill {
before: c.before.marks,
progress: (c.since_landing / MATCH_SETTLE).clamp(0., 1.),
}),
progress,
// Settling back, it goes under the veil of the cards at rest.
veil: veil * (1. - progress),
moves,
};
// Its place in the grid, where the card at rest is not to be seen.
layers.push(Layer::Quad(drawn.bounds, background, drawn.visible));
let mask = cut(drawn).map(|bounds| ContentMask { bounds });
let lowered = match &changes {
Changes::Taken(lowered) => lowered.iter().find(|lowered| lowered.id == id),
Changes::Match(_) => None,
};
let above = lowered.map_or(0., |lowered| lowered.above);
let size = drawn.bounds.size;
let before = lowered
.filter(|lowered| lowered.opacity > 0.)
.map(|lowered| {
let before = &*lowered.before;
let element = self::lifted(before, pose, size, cx)
.opacity(lowered.opacity)
.debug_selector(move || format!("lifted-before-{id}"));
(before, element)
});
let now = Some((card, self::lifted(card, pose, size, cx)));
for (card, element) in [now, before].into_iter().flatten() {
let origin =
drawn.bounds.origin - point(px(0.), px(pose.rise(card) + above));
layers.push(prepaint_card(
element,
images.as_ref(),
origin,
size,
mask,
window,
cx,
));
}
}
layers
},
|_, layers, window, cx| paint(layers, window, cx),
)
.absolute(),
)
.into_any_element()
}
/// Where a lifted card is cut: nowhere when its grid shows it whole, so it rises out of a
/// scrolling list, else where the grid cuts it. A fraction of a pixel of layout or scrolling
/// does not cut a card flush with the list's edge.
pub(crate) fn cut(drawn: &DrawnCard) -> Option<Bounds<Pixels>> {
const SLACK: f32 = 1.;
let (card, shown) = (drawn.bounds, drawn.visible);
let whole = card.top().as_f32() >= shown.top().as_f32() - SLACK
&& card.bottom().as_f32() <= shown.bottom().as_f32() + SLACK
&& card.left().as_f32() >= shown.left().as_f32() - SLACK
&& card.right().as_f32() <= shown.right().as_f32() + SLACK;
(!whole).then_some(shown)
}
/// Prepaints `element`, a card of `size` drawn at `origin` over a grid and cut by `mask`, with
/// the grid's `images`.
pub(crate) fn prepaint_card(
mut element: Div,
images: Option<&Entity<CardImages>>,
origin: Point<Pixels>,
size: Size<Pixels>,
mask: Option<ContentMask<Pixels>>,
window: &mut Window,
cx: &mut App,
) -> Layer {
if let Some(images) = images {
element = element.image_cache(images.clone());
}
let mut element = element.into_any_element();
window.with_content_mask(mask, |window| {
element.prepaint_as_root(origin, size.into(), window, cx)
});
Layer::Card(element, mask)
}
/// What a layer over a grid paints, in order.
pub(crate) enum Layer {
/// A rounded quad over a card's place, cut to what the grid shows of it.
Quad(Bounds<Pixels>, Hsla, Bounds<Pixels>),
/// A card prepainted where it is drawn, cut by its mask.
Card(AnyElement, Option<ContentMask<Pixels>>),
}
/// Paints the layers prepainted over a grid, in order.
pub(crate) fn paint(layers: Vec<Layer>, window: &mut Window, cx: &mut App) {
for layer in layers {
match layer {
Layer::Quad(bounds, color, visible) => {
let mask = ContentMask { bounds: visible };
window.with_content_mask(Some(mask), |window| {
window.paint_quad(fill(bounds, color).corner_radii(px(CARD_RADIUS)))
});
}
Layer::Card(mut element, mask) => {
window.with_content_mask(mask, |window| element.paint(window, cx));
}
}
}
}
#[cfg(test)]
mod tests;
+174
View File
@@ -0,0 +1,174 @@
use std::time::{Duration, Instant};
use gpui_kit::{Bounds, point, px, size};
use super::{Lifts, cut};
use crate::card_grid::DrawnCard;
const GRID: u32 = 1;
fn at(start: Instant, ms: u64) -> Instant {
start + Duration::from_millis(ms)
}
fn on(id: u32) -> Option<u32> {
Some(id)
}
fn progress(lifts: &Lifts<u32>, id: u32, now: Instant) -> Option<f32> {
lifts
.lifted(GRID, now)
.find(|lifted| lifted.id == id)
.map(|lifted| lifted.progress)
}
#[test]
fn a_hovered_card_rises_in_350_ms_and_settles_back_in_as_long_once_left() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), false, start);
assert_eq!(progress(&lifts, 7, start), Some(0.));
let half = progress(&lifts, 7, at(start, 175)).unwrap();
// Fast at first, then settling, as the reference's cubic-bezier(.2, .8, .2, 1).
assert!(half > 0.5 && half < 1., "{half}");
assert_eq!(progress(&lifts, 7, at(start, 350)), Some(1.));
assert!(lifts.animating(at(start, 349)));
assert!(!lifts.animating(at(start, 350)));
lifts.hover(GRID, None, false, at(start, 400));
assert_eq!(progress(&lifts, 7, at(start, 400)), Some(1.));
assert!(progress(&lifts, 7, at(start, 600)).unwrap() > 0.);
assert_eq!(progress(&lifts, 7, at(start, 750)), Some(0.));
// Back at rest, the card is the grid's own again.
lifts.tidy(at(start, 750));
assert_eq!(progress(&lifts, 7, at(start, 750)), None);
assert!(!lifts.animating(at(start, 750)));
}
#[test]
fn a_card_left_or_taken_back_during_its_animation_starts_from_where_it_is() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), false, start);
let midway = progress(&lifts, 7, at(start, 100)).unwrap();
// Left on its way up: it settles from there, with no jump, and sooner than from the top.
lifts.hover(GRID, None, false, at(start, 100));
assert_eq!(progress(&lifts, 7, at(start, 100)), Some(midway));
let back = at(start, 100 + (350. * midway).ceil() as u64);
assert_eq!(progress(&lifts, 7, back), Some(0.));
// Taken back on its way down: it rises again from there, still one card.
lifts.hover(GRID, on(7), false, at(start, 200));
lifts.hover(GRID, None, false, at(start, 200));
lifts.hover(GRID, on(7), false, at(start, 200));
let low = progress(&lifts, 7, at(start, 200)).unwrap();
assert!(low > 0. && low < midway, "{low}");
assert_eq!(lifts.lifted(GRID, at(start, 200)).count(), 1);
assert_eq!(progress(&lifts, 7, at(start, 550)), Some(1.));
}
#[test]
fn the_card_rising_is_drawn_over_the_one_settling_and_each_grid_keeps_its_own() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), false, start);
lifts.hover(GRID, on(8), false, at(start, 350));
lifts.hover(GRID, on(7), false, at(start, 400));
let order: Vec<_> = (lifts.lifted(GRID, at(start, 400)))
.map(|lifted| lifted.id)
.collect();
assert_eq!(order, [8, 7]);
// Another grid saying none of its cards is under the pointer leaves this one's.
lifts.hover(2, None, false, at(start, 400));
lifts.hover(2, on(9), false, at(start, 400));
assert_eq!(progress(&lifts, 7, at(start, 750)), Some(1.));
assert_eq!(lifts.lifted(2, at(start, 400)).count(), 1);
}
#[test]
fn in_the_hand_a_veil_lays_on_the_other_cards_while_one_is_lifted() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), true, start);
assert_eq!(lifts.veil(GRID, start), 0.);
assert!(lifts.veil(GRID, at(start, 150)) > 0.);
assert_eq!(lifts.veil(GRID, at(start, 300)), 1.);
assert!(lifts.animating(at(start, 340)));
// From card to card, it stays.
lifts.hover(GRID, on(8), true, at(start, 400));
assert_eq!(lifts.veil(GRID, at(start, 500)), 1.);
lifts.hover(GRID, None, true, at(start, 800));
assert!(lifts.veil(GRID, at(start, 900)) > 0.);
assert_eq!(lifts.veil(GRID, at(start, 1100)), 0.);
// Elsewhere than in the hand, none.
lifts.hover(2, on(9), false, at(start, 1200));
assert_eq!(lifts.veil(2, at(start, 1600)), 0.);
}
#[test]
fn a_wheel_over_a_grid_drops_its_cards_at_once() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), true, start);
lifts.hover(2, on(9), false, start);
lifts.drop_grid(GRID);
assert_eq!(lifts.lifted(GRID, start).count(), 0);
assert_eq!(lifts.veil(GRID, start), 0.);
assert_eq!(lifts.lifted(2, start).count(), 1);
}
#[test]
fn finishing_shows_the_end_state_at_once_and_nothing_moves_any_more() {
let start = Instant::now();
let mut lifts = Lifts::new();
lifts.hover(GRID, on(7), true, start);
lifts.hover(GRID, on(8), true, at(start, 100));
lifts.finish(at(start, 100));
assert!(!lifts.animating(at(start, 100)));
assert_eq!(progress(&lifts, 8, at(start, 100)), Some(1.));
// The card left is back at rest, and the grid's own again.
assert_eq!(progress(&lifts, 7, at(start, 100)), None);
assert_eq!(lifts.veil(GRID, at(start, 100)), 1.);
lifts.clear();
assert_eq!(lifts.lifted(GRID, start).count(), 0);
assert_eq!(lifts.veil(GRID, start), 0.);
}
fn drawn_card(top: f32, list_top: f32) -> DrawnCard {
DrawnCard {
bounds: Bounds::new(point(px(12.), px(top)), size(px(240.), px(350.))),
visible: Bounds::new(point(px(12.), px(list_top)), size(px(1256.), px(480.))),
ix: 0,
}
}
#[test]
fn a_card_the_list_shows_whole_rises_out_of_it() {
// The first row, flush with the list's top edge, give or take a fraction of a pixel of
// layout or scrolling.
assert_eq!(cut(&drawn_card(583., 583.)), None);
assert_eq!(cut(&drawn_card(582.7, 583.)), None);
assert_eq!(cut(&drawn_card(583.3, 583.)), None);
// A column of a fractional width: the bounds' intersection with the list differs from
// the card by a rounding error, which cut the first row's lifted card (#88).
let column = DrawnCard {
bounds: Bounds::new(point(px(533.3333), px(583.)), size(px(240.66666), px(357.))),
..drawn_card(583., 583.)
};
assert_ne!(column.visible.intersect(&column.bounds), column.bounds);
assert_eq!(cut(&column), None);
}
#[test]
fn a_card_the_list_shows_in_part_stays_cut_where_it_is() {
let half_scrolled = drawn_card(400., 583.);
assert_eq!(cut(&half_scrolled), Some(half_scrolled.visible));
let below = drawn_card(900., 583.);
assert_eq!(cut(&below), Some(below.visible));
}
+91
View File
@@ -0,0 +1,91 @@
//! The one order every section of cards follows: the chosen sort applied to the statistics' rows.
use arena_tracker_core::{ChampionRow, ChampionSort};
/// The positions of `rows` in display order. `rows` come A to Z (French collation), and every
/// sort is stable, so that order breaks every tie.
///
/// - `Name`: the rows' own order.
/// - `Mastery`: the champions with known points by points descending, then the ones whose points
/// are unknown (an unknown value is not a zero). When no row has a known value, the rows' own
/// order: the sort falls back to A to Z, and the player's preference stays as it is.
pub fn card_order(rows: &[ChampionRow], sort: ChampionSort) -> Vec<usize> {
let mut order: Vec<usize> = (0..rows.len()).collect();
if sort == ChampionSort::Mastery && rows.iter().any(|row| row.mastery_points.is_some()) {
// `None` sorts before every `Some`: reversed, the known values come first, highest first.
order.sort_by_key(|&ix| std::cmp::Reverse(rows[ix].mastery_points));
}
order
}
#[cfg(test)]
mod tests {
use arena_tracker_core::{Champion, ChampionRow, ChampionSort};
use super::card_order;
use crate::champion_table::tests::row;
/// Rows A to Z, as the statistics give them, each with its points.
fn rows(points: &[(&str, Option<u64>)]) -> Vec<ChampionRow> {
points
.iter()
.enumerate()
.map(|(id, (name, points))| ChampionRow {
champion: Champion {
id: id as u32 + 1,
..row(name).champion
},
mastery_points: *points,
..row(name)
})
.collect()
}
fn names(rows: &[ChampionRow], order: &[usize]) -> Vec<String> {
order
.iter()
.map(|&ix| rows[ix].champion.name.clone())
.collect()
}
#[test]
fn mastery_sorts_by_points_descending_then_by_name() {
let rows = rows(&[
("Ahri", Some(500)),
("Brand", Some(9_000)),
("Garen", Some(500)),
("Jinx", Some(0)),
("Zed", Some(500)),
]);
let order = card_order(&rows, ChampionSort::Mastery);
assert_eq!(
names(&rows, &order),
["Brand", "Ahri", "Garen", "Zed", "Jinx"]
);
}
#[test]
fn an_unknown_value_comes_after_the_known_ones_even_zero() {
let rows = rows(&[
("Ahri", None),
("Brand", Some(0)),
("Garen", None),
("Jinx", Some(12)),
]);
let order = card_order(&rows, ChampionSort::Mastery);
assert_eq!(names(&rows, &order), ["Jinx", "Brand", "Ahri", "Garen"]);
}
#[test]
fn without_any_known_value_the_cards_are_sorted_a_to_z() {
let rows = rows(&[("Ahri", None), ("Brand", None), ("Zed", None)]);
assert_eq!(card_order(&rows, ChampionSort::Mastery), [0, 1, 2]);
}
#[test]
fn the_name_sort_keeps_the_rows_order_whatever_the_points() {
let rows = rows(&[("Ahri", Some(1)), ("Brand", None), ("Zed", Some(900))]);
assert_eq!(card_order(&rows, ChampionSort::Name), [0, 1, 2]);
assert!(card_order(&[], ChampionSort::Mastery).is_empty());
}
}
+98 -2
View File
@@ -9,6 +9,7 @@ use gpui_kit::component::{ActiveTheme as _, Icon, IconName, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use crate::card_images::{self, CardImages};
use crate::text::{decimal, state_label};
struct Spec {
@@ -49,6 +50,12 @@ pub struct ChampionTable {
/// The clicked champion's id: it stays selected through sorting and reloads.
selected: Option<u32>,
scroll: UniformListScrollHandle,
/// The portraits of the rows painted, never GPUI's app-wide cache, which would keep every
/// one scrolled past (budget 4). Created at the first render.
images: Option<Entity<CardImages>>,
/// Guards the cache in tests.
#[cfg(test)]
pub(crate) renders: usize,
}
impl ChampionTable {
@@ -59,6 +66,22 @@ impl ChampionTable {
sort: None,
selected: None,
scroll: UniformListScrollHandle::new(),
images: None,
#[cfg(test)]
renders: 0,
}
}
/// The table is not shown any more: its portraits are given back, in memory and in the
/// window's atlas, and load again when it is drawn.
pub fn release_images(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let released = self
.images
.as_ref()
.is_some_and(|images| images.update(cx, |images, cx| images.release(window, cx)));
if released {
// A cached view replays its last paint unless it is drawn again.
cx.notify();
}
}
@@ -69,6 +92,11 @@ impl ChampionTable {
self.resort();
}
#[cfg(test)]
pub(crate) fn images(&self) -> Option<&Entity<CardImages>> {
self.images.as_ref()
}
#[cfg(test)]
pub(crate) fn names(&self) -> Vec<String> {
self.rows.iter().map(|r| r.champion.name.clone()).collect()
@@ -227,7 +255,15 @@ fn cell_text(row: &ChampionRow, key: SortKey) -> String {
}
impl Render for ChampionTable {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let images = (self.images)
.get_or_insert_with(|| CardImages::new(cx))
.clone();
images.update(cx, |images, cx| images.start_render(window, cx));
let theme = cx.theme();
let (background, border, radius, muted) = (
theme.table,
@@ -256,7 +292,7 @@ impl Render for ChampionTable {
.track_scroll(&self.scroll)
.into_any_element()
};
div()
card_images::provide(div(), images)
.v_flex()
.relative()
.size_full()
@@ -297,6 +333,8 @@ pub(crate) mod tests {
name: name.into(),
},
portrait: None,
card_portrait: None,
splash: None,
matches: 0,
best_placement: None,
top1: 0,
@@ -305,9 +343,67 @@ pub(crate) mod tests {
last_match_ms: None,
attempts: None,
state: None,
challenge: None,
mastery_points: None,
}
}
// Only the rows painted keep their portraits, and none is kept once the table is not shown.
#[gpui::test]
fn the_table_holds_only_the_portraits_of_the_rows_it_paints(cx: &mut gpui_kit::TestAppContext) {
use gpui_kit::{
AppContext as _, Bounds, VisualTestContext, WindowBounds, WindowOptions, point, px,
size,
};
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
let dir = TestDir::new("table-portraits");
let rows: Vec<ChampionRow> = (1..=170)
.map(|id| {
let path = dir.path().join(format!("{id}.jpg"));
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
let mut row = row(&format!("Champion {id:03}"));
row.champion.id = id;
row.portrait = Some(path);
row
})
.collect();
cx.update(gpui_kit::init);
let (window, table) = cx.update(|cx| {
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
})),
..Default::default()
};
gpui_kit::open_window(options, cx, |_, cx| {
cx.new(|_| {
let mut table = ChampionTable::new();
table.set_rows(rows, false);
table
})
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.run_until_parked();
cx.update(|window, cx| window.draw(cx).clear(cx));
let images = table.read_with(cx, |table, _| table.images().cloned().unwrap());
let held = images.read_with(cx, |images, _| images.loaded().len());
// The rows in the window's 860 px at 32 px each, not the 170.
assert!((10..=30).contains(&held), "{held} portraits held");
// Checked before the next frame: here the table is still the window, and draws again.
cx.update(|window, cx| {
table.update(cx, |table, cx| table.release_images(window, cx));
assert!(images.read(cx).held().is_empty());
});
}
#[test]
fn missing_values_show_a_dash() {
let row = row("Ahri");
+285
View File
@@ -0,0 +1,285 @@
//! Launching Arena Tracker at the user's Windows logon (#67).
//!
//! Windows alone holds the choice, never `config.toml`: the logon starts the command of an
//! entry under `Run` unless the Task Manager's « Applications de démarrage » disabled it, which
//! it records under `StartupApproved\Run` without deleting the entry. Enabling the launch here
//! approves the entry again: the latest explicit choice wins.
use std::path::Path;
use windows::Win32::Foundation::{ERROR_FILE_NOT_FOUND, ERROR_SUCCESS};
use windows::Win32::System::Registry::{
HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_BINARY, REG_OPTION_NON_VOLATILE, REG_SZ,
REG_VALUE_TYPE, RRF_RT_REG_BINARY, RRF_RT_REG_SZ, RegCloseKey, RegCreateKeyExW,
RegDeleteKeyValueW, RegGetValueW, RegSetValueExW,
};
use windows::core::{HSTRING, Result, w};
use crate::release;
/// Given by the entry's command: the app starts hidden (`tray::start_hidden`).
pub const ARG: &str = "--logon";
/// The entry's value name in both keys.
const NAME: windows::core::PCWSTR = w!("ArenaTracker");
/// What the Task Manager writes for an enabled entry; an odd first byte disables it.
const APPROVED: [u8; 12] = [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
/// Whether Windows started this process at logon.
pub fn launched_at_logon() -> bool {
std::env::args_os().nth(1).is_some_and(|arg| arg == ARG)
}
/// The two keys of the entry, under `HKEY_CURRENT_USER`.
struct Keys {
run: HSTRING,
approved: HSTRING,
}
impl Keys {
fn current_user() -> Keys {
Keys::under(r"Software\Microsoft\Windows\CurrentVersion")
}
/// `Run` and `Explorer\StartupApproved\Run` under `root`, as Windows lays them out.
fn under(root: &str) -> Keys {
Keys {
run: format!(r"{root}\Run").into(),
approved: format!(r"{root}\Explorer\StartupApproved\Run").into(),
}
}
/// Removes the entry and its approval, if they exist.
fn remove(&self) -> Result<()> {
for key in [&self.run, &self.approved] {
let deleted = unsafe { RegDeleteKeyValueW(HKEY_CURRENT_USER, key, NAME) };
if deleted != ERROR_SUCCESS && deleted != ERROR_FILE_NOT_FOUND {
return Err(deleted.into());
}
}
Ok(())
}
}
/// The launch at the user's Windows logon.
pub struct LogonLaunch {
keys: Keys,
/// `None` outside an installed version: nothing to start that would outlive this build.
command: Option<String>,
}
impl LogonLaunch {
/// The entry of this Windows user, starting the installed executable.
pub fn installed() -> LogonLaunch {
LogonLaunch {
keys: Keys::current_user(),
command: std::env::current_exe()
.ok()
.and_then(|exe| installed_command(release::VERSION, &exe)),
}
}
/// Only an installed version offers the launch.
pub fn available(&self) -> bool {
self.command.is_some()
}
/// Whether the logon starts Arena Tracker: an entry the Task Manager did not
/// disable. Two registry reads, done when the settings are shown, never per frame.
pub fn enabled(&self) -> bool {
let found = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
&self.keys.run,
NAME,
RRF_RT_REG_SZ,
None,
None,
None,
)
};
if found != ERROR_SUCCESS {
return false;
}
let mut data = [0u8; 64];
let mut size = data.len() as u32;
let read = unsafe {
RegGetValueW(
HKEY_CURRENT_USER,
&self.keys.approved,
NAME,
RRF_RT_REG_BINARY,
None,
Some(data.as_mut_ptr().cast()),
Some(&mut size),
)
};
// No approval: the Task Manager never touched the entry. A value longer than any it
// writes is not one of its choices either.
read != ERROR_SUCCESS || approved(&data[..size as usize])
}
/// Writes or removes the entry. Enabling also approves it, undoing a Task Manager choice.
pub fn set(&self, enabled: bool) -> Result<()> {
if !enabled {
return self.keys.remove();
}
let Some(command) = &self.command else {
return Err(ERROR_FILE_NOT_FOUND.into());
};
let text: Vec<u8> = (command.encode_utf16().chain([0]))
.flat_map(u16::to_le_bytes)
.collect();
set_value(&self.keys.run, REG_SZ, &text)?;
set_value(&self.keys.approved, REG_BINARY, &APPROVED)
}
}
/// Removes this user's entry: an installation, or an uninstallation, starts without it.
pub fn forget() -> Result<()> {
Keys::current_user().remove()
}
/// The entry's command for an installed version: its executable in `current\`, a path that
/// Velopack keeps across updates. A development build has no version and runs elsewhere.
fn installed_command(version: Option<&str>, exe: &Path) -> Option<String> {
version?;
if exe.parent()?.file_name()? != "current" {
return None;
}
Some(format!("\"{}\" {ARG}", exe.to_str()?))
}
/// The Task Manager marks a disabled entry with an odd first byte (3, or 7 for some entries).
fn approved(value: &[u8]) -> bool {
value.first().is_none_or(|byte| byte & 1 == 0)
}
fn set_value(subkey: &HSTRING, kind: REG_VALUE_TYPE, data: &[u8]) -> Result<()> {
let mut key = HKEY::default();
unsafe {
RegCreateKeyExW(
HKEY_CURRENT_USER,
subkey,
None,
None,
REG_OPTION_NON_VOLATILE,
KEY_SET_VALUE,
None,
&mut key,
None,
)
.ok()?;
let written = RegSetValueExW(key, NAME, None, kind, Some(data));
let _ = RegCloseKey(key);
written.ok()
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::path::Path;
use windows::Win32::System::Registry::{HKEY_CURRENT_USER, RegDeleteTreeW};
use windows::core::HSTRING;
use super::{Keys, LogonLaunch, REG_BINARY, approved, installed_command, set_value};
/// A scratch copy of the two keys under the current user, removed when dropped.
pub(crate) struct Scratch {
root: HSTRING,
approved: HSTRING,
}
impl Scratch {
/// The launch of an installed version (`installed`) or of a development build, on
/// scratch keys named after the test.
pub(crate) fn launch(name: &str, installed: bool) -> (Scratch, LogonLaunch) {
let root = format!(
r"Software\nessar-arena-tracker-tests\{name}-{}",
std::process::id()
);
let keys = Keys::under(&root);
let scratch = Scratch {
root: root.as_str().into(),
approved: keys.approved.clone(),
};
scratch.drop_tree();
let command = installed.then_some(r#""C:\Arena\current\arena-tracker.exe" --logon"#);
let launch = LogonLaunch {
keys,
command: command.map(String::from),
};
(scratch, launch)
}
/// « Désactiver » in the Task Manager's « Applications de démarrage ».
pub(crate) fn disable_in_task_manager(&self) {
let disabled = [3, 0, 0, 0, 0xa0, 0x6e, 0x4b, 0x2c, 0x5e, 0x4d, 0xdb, 0x01];
set_value(&self.approved, REG_BINARY, &disabled).unwrap();
}
fn drop_tree(&self) {
let _ = unsafe { RegDeleteTreeW(HKEY_CURRENT_USER, &self.root) };
}
}
impl Drop for Scratch {
fn drop(&mut self) {
self.drop_tree();
}
}
#[test]
fn the_entry_follows_the_switch_and_the_task_manager_choice() {
let (scratch, launch) = Scratch::launch("follows", true);
assert!(!launch.enabled(), "a first installation starts disabled");
launch.set(true).unwrap();
assert!(launch.enabled());
scratch.disable_in_task_manager();
assert!(
!launch.enabled(),
"the settings show the Task Manager's choice"
);
launch.set(true).unwrap();
assert!(launch.enabled(), "enabling here approves the entry again");
launch.set(false).unwrap();
assert!(!launch.enabled());
// Nothing left behind, and removing what is gone is not an error.
launch.set(false).unwrap();
}
#[test]
fn a_build_outside_an_installation_cannot_enable_the_launch() {
let (_scratch, launch) = Scratch::launch("unavailable", false);
assert!(!launch.available());
assert!(launch.set(true).is_err());
assert!(!launch.enabled());
}
#[test]
fn only_an_installed_version_in_current_gets_a_command() {
let installed =
Path::new(r"C:\Users\A\AppData\Local\ArenaTracker\current\arena-tracker.exe");
assert_eq!(
installed_command(Some("1.0.0"), installed).as_deref(),
Some(r#""C:\Users\A\AppData\Local\ArenaTracker\current\arena-tracker.exe" --logon"#)
);
assert_eq!(installed_command(None, installed), None);
let built =
Path::new(r"C:\Users\A\AppData\Local\arena-tracker\target\release\arena-tracker.exe");
assert_eq!(installed_command(Some("1.0.0"), built), None);
}
#[test]
fn an_odd_first_byte_marks_a_disabled_entry() {
assert!(approved(&[2, 0, 0]));
assert!(approved(&[6, 0]));
assert!(approved(&[]));
assert!(!approved(&[3, 0, 0]));
assert!(!approved(&[7]));
}
}
+229 -72
View File
@@ -1,24 +1,42 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod banner_art;
mod card;
mod card_grid;
mod card_images;
mod card_lift;
mod card_order;
mod champion_table;
mod logon;
mod minimized;
mod motion;
mod page;
#[cfg(feature = "profile")]
mod profile;
mod release;
mod ring;
mod settings;
mod stats_page;
mod single_instance;
mod stage;
mod text;
mod theme;
mod title_bar;
mod tray;
mod worker;
use std::{rc::Rc, sync::Arc};
use std::{ops::ControlFlow, sync::Arc};
use arena_tracker_core::{
Config, DataDragon, LeagueClient, RiotApi, Tracker, data_dir, default_seasons, load_seasons,
Config, DataDragon, LeagueClient, Preferences, RiotApi, Tracker, data_dir, default_seasons,
load_seasons,
};
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::component::*;
use gpui_kit::*;
use settings::{KeyEvent, KeyForm, KeyStore};
use stats_page::{PageEvent, StatsPage};
use page::{ChampionSortChosen, Launch, Page};
use settings::{KeyEvent, KeyForm, KeyStore, apply_theme};
use title_bar::{MIN_WINDOW_SIZE, refresh_button, settings_button, title_bar, update_button};
use worker::{Msg, spawn_follower};
#[derive(Clone, Copy, PartialEq)]
@@ -30,18 +48,24 @@ enum Screen {
}
struct RootView {
page: Entity<StatsPage>,
page: Entity<Page>,
form: Entity<KeyForm>,
focus: FocusHandle,
screen: Screen,
tracker: Arc<Tracker>,
/// The configured Riot ID, used when the game client is closed on first launch.
fallback_riot_id: String,
tx: Sender<Msg>,
_subscriptions: Vec<Subscription>,
/// Started hidden at logon: the first frame, which GPUI draws as the window
/// opens, paints no page, so no portrait is decoded before the window is shown.
blank: bool,
_form_events: Subscription,
_champ_select: Subscription,
_sort: Subscription,
}
impl RootView {
fn new(setup: Setup, window: &mut Window, cx: &mut Context<Self>) -> Self {
fn new(setup: Setup, hidden: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
let Setup {
tracker,
riot_id,
@@ -51,12 +75,16 @@ impl RootView {
// Without a key the page still shows what is stored; only a true first launch (no key
// and nothing stored) has nothing to show, so the key form stands in for the page.
let first_launch = !store.has_key() && tracker.accounts().unwrap_or_default().is_empty();
let champion_sort = store.preferences().champion_sort;
let (tx, rx) = unbounded();
let page = cx.new(|cx| {
StatsPage::new(
Page::new(
tracker.clone(),
notice,
!first_launch,
Launch {
notice,
following: !first_launch,
champion_sort,
},
rx,
tx.clone(),
window,
@@ -64,19 +92,8 @@ impl RootView {
)
});
let form = cx.new(|cx| KeyForm::new(store, first_launch, window, cx));
let subscriptions = vec![
cx.subscribe_in(
&page,
window,
|this, _, event: &PageEvent, window, cx| match event {
PageEvent::OpenSettings => {
this.form.update(cx, |form, cx| form.reset(window, cx));
this.screen = Screen::Settings;
cx.notify();
}
},
),
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, _, cx| {
let form_events =
cx.subscribe_in(&form, window, |this, _, event: &KeyEvent, window, cx| {
match event {
KeyEvent::Saved if this.screen == Screen::Prompt => {
// Nothing is imported before a key exists: the follower starts now.
@@ -85,55 +102,161 @@ impl RootView {
spawn_follower(tracker, riot_id, this.tx.clone());
this.page.update(cx, |page, cx| page.following(cx));
}
KeyEvent::Saved => this.page.update(cx, |page, cx| page.begin_refresh(cx)),
KeyEvent::Saved => this.page.update(cx, |page, cx| page.request_refresh(cx)),
KeyEvent::Back => {}
// Only the title bar changes.
KeyEvent::UpdateReady => return cx.notify(),
}
this.screen = Screen::Page;
cx.notify();
}),
];
this.show_page(window, cx);
});
let champ_select = cx.subscribe_in(
&page,
window,
|this, _, transition: &page::ChampSelectTransition, window, cx| {
// Only on entry: the window stays open after the champ select.
if transition.entered
&& let Some(hwnd) = tray::window_hwnd(window)
{
// Outside this update: the native calls resize the window through GPUI.
cx.spawn(async move |_, _| tray::reveal(hwnd)).detach();
}
if this.screen == Screen::Settings {
// Champ select takes the window away: do not bring back half-typed edits.
this.show_page(window, cx);
}
},
);
// Saved with the other preferences; a failure keeps the choice for the session.
let sort = cx.subscribe(
&page,
|this, _, ChampionSortChosen(sort): &ChampionSortChosen, cx| {
this.form
.update(cx, |form, cx| form.save_champion_sort(*sort, cx));
},
);
let screen = if first_launch {
Screen::Prompt
} else {
spawn_follower(tracker.clone(), riot_id.clone(), tx.clone());
Screen::Page
};
if hidden {
// Runs once GPUI's first frame is drawn. A hidden or minimized window gets no
// other frame: the page is painted when the window is shown.
cx.defer_in(window, |this, _, cx| {
this.blank = false;
cx.notify();
});
}
RootView {
page,
form,
focus: initial_focus(window, cx),
screen,
tracker,
fallback_riot_id: riot_id,
tx,
_subscriptions: subscriptions,
blank: hidden,
_form_events: form_events,
_champ_select: champ_select,
_sort: sort,
}
}
fn can_refresh(&self, cx: &App) -> bool {
self.screen != Screen::Prompt && self.form.read(cx).has_key() && !self.page.read(cx).busy()
}
fn open_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.screen == Screen::Page {
self.screen = Screen::Settings;
// Windows holds the launch at logon: read it as the settings open.
self.form.update(cx, |form, _| form.read_logon_launch());
self.page.update(cx, |page, cx| page.hidden(window, cx));
self.focus.focus(window, cx);
cx.notify();
}
}
/// Leaves the key form for the page, discarding half-typed edits.
fn show_page(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.form.update(cx, |form, cx| form.reset(window, cx));
self.screen = Screen::Page;
self.page.update(cx, |page, cx| page.uncovered(window, cx));
self.focus.focus(window, cx);
cx.notify();
}
}
impl Render for RootView {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let refresh =
refresh_button(self.can_refresh(cx), cx).on_click(cx.listener(|this, _, _, cx| {
if this.can_refresh(cx) {
this.page.update(cx, |page, cx| page.request_refresh(cx));
}
}));
let on_page = self.screen == Screen::Page;
let settings = settings_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)));
// The settings show the ready version next to « Redémarrer ».
let update = self.form.read(cx).update_ready().then(|| {
update_button(on_page, cx)
.on_click(cx.listener(|this, _, window, cx| this.open_settings(window, cx)))
});
let content = match self.screen {
_ if self.blank => div().into_any_element(),
Screen::Page => self.page.clone().into_any_element(),
Screen::Prompt | Screen::Settings => self.form.clone().into_any_element(),
};
div().size_full().child(content)
div()
.id("arena-tracker")
.track_focus(&self.focus)
.v_flex()
.size_full()
.child(title_bar(refresh, settings, update, window, cx))
.child(div().flex_1().min_h_0().child(content))
}
}
/// Shown instead of the app when the configuration or the database cannot be loaded.
struct Unavailable(Vec<String>);
struct Unavailable {
lines: Vec<String>,
focus: FocusHandle,
}
impl Render for Unavailable {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
div()
.id("unavailable")
.track_focus(&self.focus)
.v_flex()
.size_full()
.items_center()
.justify_center()
.children(self.0.clone())
.child(title_bar(
refresh_button(false, cx),
settings_button(false, cx),
None,
window,
cx,
))
.child(
div()
.v_flex()
.flex_1()
.items_center()
.justify_center()
.children(self.lines.clone()),
)
}
}
fn initial_focus(window: &mut Window, cx: &mut App) -> FocusHandle {
// Tab dispatch needs a focused element inside gpui-kit's root key context.
let focus = cx.focus_handle();
focus.focus(window, cx);
focus
}
struct Setup {
tracker: Arc<Tracker>,
riot_id: String,
@@ -143,12 +266,15 @@ struct Setup {
/// Loads the configuration and opens the database, or gives the lines to show instead. A
/// missing config file is fine: the app then asks for the key.
fn startup() -> Result<Setup, Vec<String>> {
fn startup() -> Result<Setup, (Vec<String>, Preferences)> {
let bad_config = |error: String| {
vec![
format!("Configuration introuvable ou invalide : {error}"),
"Corrigez ou supprimez %APPDATA%\\arena-tracker\\config.toml.".into(),
]
(
vec![
format!("Configuration introuvable ou invalide : {error}"),
"Corrigez ou supprimez %APPDATA%\\arena-tracker\\config.toml.".into(),
],
Preferences::default(),
)
};
let dir =
data_dir().ok_or_else(|| bad_config("la variable APPDATA n'est pas définie.".into()))?;
@@ -164,7 +290,7 @@ fn startup() -> Result<Setup, Vec<String>> {
};
let api = Arc::new(RiotApi::new(config.riot_api_key.clone(), &config.region));
let tracker = Tracker::open(&dir.join("arena-tracker.db"), Box::new(api.clone()))
.map_err(|e| vec![e.to_string()])?
.map_err(|e| (vec![e.to_string()], config.preferences))?
.with_seasons(seasons)
.with_champions(Box::new(DataDragon::new()), dir.join("portraits"))
.with_client(Box::new(LeagueClient::new()));
@@ -176,51 +302,82 @@ fn startup() -> Result<Setup, Vec<String>> {
})
}
fn follow_system_appearance(window: &mut Window, cx: &mut App) {
let sync = |window: &mut Window, cx: &mut App| {
let mode = ThemeMode::from(window.appearance());
if cx.theme().mode != mode {
Theme::sync_system_appearance(Some(window), cx);
debug_assert_eq!(cx.theme().mode, mode);
}
};
sync(window, cx);
window.observe_window_appearance(sync).detach();
}
fn main() {
release::handle_command();
let Some(single_instance::Primary {
instance: _instance,
starting,
}) = single_instance::launch()
else {
return;
};
// Started by the logon entry: hidden, or minimized (#67).
let at_logon = logon::launched_at_logon();
// Only the single instance gets here: a launch relayed to a running one installs nothing.
let ControlFlow::Continue(update_notice) = release::update_at_launch(at_logon) else {
return;
};
let app = gpui_kit::application().with_assets(gpui_kit::assets::Assets);
app.run(move |cx| {
gpui_kit::init(cx);
// The default dark table header text has low contrast against its background.
let dark = Rc::make_mut(&mut Theme::global_mut(cx).dark_theme);
dark.colors.table_head_foreground = dark.colors.muted_foreground.clone();
card_grid::init(cx);
theme::init(cx);
#[cfg(feature = "profile")]
profile::start(cx);
let bounds = Bounds::centered(None, size(px(1280.), px(860.)), cx);
let options = WindowOptions {
titlebar: Some(TitlebarOptions {
title: Some("Arena Tracker".into()),
..Default::default()
..TitleBar::title_bar_options()
}),
window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
None,
size(px(1280.), px(860.)),
cx,
))),
window_bounds: Some(WindowBounds::Windowed(bounds)),
window_min_size: Some(MIN_WINDOW_SIZE),
show: !at_logon,
focus: !at_logon,
..Default::default()
};
match startup() {
Ok(setup) => gpui_kit::open_window(options, cx, |window, cx| {
follow_system_appearance(window, cx);
cx.new(|cx| RootView::new(setup, window, cx))
})
.map(drop),
Err(lines) => gpui_kit::open_window(options, cx, |window, cx| {
follow_system_appearance(window, cx);
cx.new(|_| Unavailable(lines))
Ok(mut setup) => {
setup.notice = (update_notice.into_iter().chain(setup.notice))
.reduce(|update, seasons| format!("{update}\n{seasons}"));
gpui_kit::open_window(options, cx, |window, cx| {
single_instance::accept_relaunches(window);
motion::follow_windows_setting(window, cx);
minimized::skip_paint_while_minimized(window);
// The settings form installs the tray that hides the window.
let root = cx.new(|cx| RootView::new(setup, at_logon, window, cx));
if at_logon {
tray::start_hidden(window, bounds);
}
root
})
.map(drop)
}
Err((mut lines, preferences)) => gpui_kit::open_window(options, cx, |window, cx| {
lines.extend(update_notice);
single_instance::accept_relaunches(window);
apply_theme(preferences.theme, window, cx);
window
.observe_window_appearance(move |window, cx| {
apply_theme(preferences.theme, window, cx);
})
.detach();
// Without a readable configuration the one-time notice could not be recorded.
tray::Tray::install_saved(window, preferences.close_to_tray, None, cx);
if at_logon {
tray::start_hidden(window, bounds);
}
cx.new(|cx| Unavailable {
lines,
focus: initial_focus(window, cx),
})
})
.map(drop),
}
.expect("Failed to open window");
drop(starting);
});
}
#[cfg(test)]
mod tests;
+44
View File
@@ -0,0 +1,44 @@
//! A minimised window draws nothing, yet GPUI's vsync thread invalidates it at each vsync, and
//! each WM_PAINT went through GPUI, which has no frame to draw while minimised, then
//! DefWindowProc: the UI thread spent more minimised than visible (budget 3,
//! `docs/performance.md`). The paint is validated here instead, before GPUI sees it.
use gpui_kit::Window;
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::Graphics::Gdi::ValidateRect;
use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass};
use windows::Win32::UI::WindowsAndMessaging::{IsIconic, WM_NCDESTROY, WM_PAINT};
use crate::tray::window_hwnd;
/// Subclass ids are per procedure.
const MINIMIZED_SUBCLASS: usize = 0;
pub(crate) fn skip_paint_while_minimized(window: &Window) {
if let Some(hwnd) = window_hwnd(window) {
// Without the subclass, GPUI handles these paints as before.
let _ = unsafe { SetWindowSubclass(hwnd, Some(paint_proc), MINIMIZED_SUBCLASS, 0) };
}
}
unsafe extern "system" fn paint_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
_id: usize,
_data: usize,
) -> LRESULT {
match message {
// GPUI gives its frame callback back at the restore's WM_SIZE, and draws then.
WM_PAINT if unsafe { IsIconic(hwnd) }.as_bool() => {
let _ = unsafe { ValidateRect(Some(hwnd), None) };
return LRESULT(0);
}
WM_NCDESTROY => {
let _ = unsafe { RemoveWindowSubclass(hwnd, Some(paint_proc), MINIMIZED_SUBCLASS) };
}
_ => {}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
+334
View File
@@ -0,0 +1,334 @@
//! What decides whether the app animates, and when (#86): the Windows setting followed into
//! `App::reduce_motion`, the animations waiting for « Défi » to be visible, and the veil of the
//! switch between tabs. The page says when « Défi » is visible.
use std::time::{Duration, Instant};
use gpui_kit::base::apply_system_reduce_motion;
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::{App, Global, Window};
use windows::Win32::Foundation::{HWND, LPARAM, LRESULT, WPARAM};
use windows::Win32::UI::Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass};
use windows::Win32::UI::WindowsAndMessaging::{
SPI_SETCLIENTAREAANIMATION, WM_NCDESTROY, WM_SETTINGCHANGE,
};
use crate::tray::window_hwnd;
/// How long the screen leaving takes to go under the veil.
const FADE_OUT: Duration = Duration::from_millis(130);
/// How long the screen arriving takes to come out of it.
const FADE_IN: Duration = Duration::from_millis(280);
pub(crate) use arena_tracker_core::MatchEnd;
/// The comet's flight to the nearest tick, just after noon.
const COMET_SHORTEST: f32 = 0.65;
/// What the flight takes longer per turn of the ring, up to the last tick.
const COMET_PER_TURN: f32 = 0.55;
/// How long the tick, the card and the splash take to settle once the comet lands, or from the
/// start without a comet, in seconds.
pub(crate) const MATCH_SETTLE: f32 = 1.2;
/// How long the counter's roll and the fade in of the « Dernière Partie » line take, in seconds.
pub(crate) const COUNTER_ROLL: f32 = 0.7;
/// The end of a followed Match being played: what it brought, on which tick, from when. Fixed
/// when it starts; the ring, the banner and the card read their frame from it.
#[derive(Clone, Copy)]
pub(crate) struct MatchAnimation {
pub start: Instant,
pub end: MatchEnd,
pub champion_id: u32,
/// The champion's tick, among `count`.
pub index: usize,
pub count: usize,
pub state: arena_tracker_core::ChampionState,
}
impl MatchAnimation {
/// A champion Completed sends the comet first; anything else settles from the start.
pub fn has_comet(self) -> bool {
self.end == MatchEnd::Completed
}
/// How long the comet flies: in proportion to how far round the ring the tick is.
pub fn flight(self) -> f32 {
if self.has_comet() {
COMET_SHORTEST + COMET_PER_TURN * self.index as f32 / self.count as f32
} else {
0.
}
}
pub fn elapsed(self, now: Instant) -> f32 {
now.saturating_duration_since(self.start).as_secs_f32()
}
/// Seconds since the comet landed (since the start without one): negative while it flies.
pub fn since_landing(self, now: Instant) -> f32 {
self.elapsed(now) - self.flight()
}
pub fn finished(self, now: Instant) -> bool {
self.since_landing(now) >= MATCH_SETTLE
}
}
/// Animations asked for while « Défi » is not in front of the player: only the strongest is
/// kept, and it plays once « Défi » shows again.
pub(crate) struct Deferred<A> {
waiting: Option<A>,
}
impl<A> Default for Deferred<A> {
fn default() -> Self {
Deferred { waiting: None }
}
}
impl<A: Ord> Deferred<A> {
/// The animation waiting, if any.
pub fn waiting(&self) -> Option<&A> {
self.waiting.as_ref()
}
/// Gives back the animation to play now when « Défi » is visible, else keeps it if it is the
/// strongest waiting.
pub fn request(&mut self, animation: A, visible: bool) -> Option<A> {
if visible {
return Some(animation);
}
if self
.waiting
.as_ref()
.is_none_or(|waiting| animation > *waiting)
{
self.waiting = Some(animation);
}
None
}
/// « Défi » shows again: the animation waiting, if any, to play now.
pub fn shown(&mut self) -> Option<A> {
self.waiting.take()
}
}
/// The screen leaving « Défi » or « Statistiques » goes under a veil of the page's background,
/// then the one arriving comes out of it. A veil rather than the content's own opacity or
/// position: either is part of a cached view's key, so fading or sliding the content would draw
/// the grid, the ring and the charts again at each frame and build the cards again (rule #1).
pub(crate) struct Fade {
phase: FadePhase,
/// The veil's opacity when the phase started: a switch during a transition starts again from
/// where the veil is.
from: f32,
start: Instant,
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(crate) enum FadePhase {
/// The screen leaving goes under the veil.
Out,
/// The screen arriving comes out of it.
In,
}
impl Fade {
pub fn covering(from: f32, start: Instant) -> Self {
Fade {
phase: FadePhase::Out,
from,
start,
}
}
pub fn uncovering(from: f32, start: Instant) -> Self {
Fade {
phase: FadePhase::In,
from,
start,
}
}
pub fn phase(&self) -> FadePhase {
self.phase
}
/// The veil's opacity, 0 to 1.
pub fn veil(&self, now: Instant) -> f32 {
let progress = self.progress(now);
match self.phase {
FadePhase::Out => self.from + (1. - self.from) * ease_in(progress),
FadePhase::In => self.from * (1. - ease_out(progress)),
}
}
pub fn finished(&self, now: Instant) -> bool {
self.progress(now) >= 1.
}
fn duration(&self) -> Duration {
match self.phase {
FadePhase::Out => FADE_OUT,
FadePhase::In => FADE_IN,
}
}
fn progress(&self, now: Instant) -> f32 {
let elapsed = now.saturating_duration_since(self.start);
(elapsed.as_secs_f32() / self.duration().as_secs_f32()).min(1.)
}
}
/// Close to CSS's `ease-in`.
pub(crate) fn ease_in(t: f32) -> f32 {
t * t
}
/// Close to the reference's `cubic-bezier(.2, .8, .2, 1)`.
pub(crate) fn ease_out(t: f32) -> f32 {
1. - (1. - t).powi(3)
}
/// Follows the Windows « Show animations » setting while the app runs. gpui-base reads it into
/// `App::reduce_motion` at start (`gpui_kit::init`) but not on its change, which Windows
/// broadcasts to every top-level window: the window's own messages are watched for it, with no
/// polling.
pub(crate) fn follow_windows_setting(window: &Window, cx: &mut App) {
let Some(hwnd) = window_hwnd(window) else {
return;
};
let (tx, rx) = unbounded::<()>();
let data = Box::into_raw(Box::new(tx));
// The subclass owns the sender until WM_NCDESTROY. This window belongs to the UI thread.
if !unsafe { SetWindowSubclass(hwnd, Some(setting_proc), SETTING_SUBCLASS, data as usize) }
.as_bool()
{
drop(unsafe { Box::from_raw(data) });
return;
}
cx.spawn(async move |cx| {
while rx.recv().await.is_ok() {
cx.update(|cx| {
apply_system_reduce_motion(cx);
cx.set_global(AnimationSetting);
});
}
})
.detach();
}
/// Set again each time the Windows setting is read again, for the page to observe: turned off,
/// nothing animates any more and nothing waits.
#[derive(Default)]
pub(crate) struct AnimationSetting;
impl Global for AnimationSetting {}
/// The tray's subclass is 0.
const SETTING_SUBCLASS: usize = 1;
unsafe extern "system" fn setting_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
_id: usize,
data: usize,
) -> LRESULT {
let sender = data as *mut Sender<()>;
if animation_setting_changed(message, wparam.0) {
// Applied outside the window procedure, by the task above.
let _ = unsafe { &*sender }.try_send(());
} else if message == WM_NCDESTROY {
unsafe {
let _ = RemoveWindowSubclass(hwnd, Some(setting_proc), SETTING_SUBCLASS);
drop(Box::from_raw(sender));
}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
/// Whether a window message says the Windows « Show animations » setting changed.
fn animation_setting_changed(message: u32, wparam: usize) -> bool {
message == WM_SETTINGCHANGE && wparam == SPI_SETCLIENTAREAANIMATION.0 as usize
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use windows::Win32::UI::WindowsAndMessaging::{
SPI_SETCLIENTAREAANIMATION, SPI_SETMOUSESPEED, WM_SETTINGCHANGE, WM_SIZE,
};
use super::{Deferred, Fade, animation_setting_changed};
#[test]
fn an_animation_asked_for_while_visible_plays_at_once() {
let mut deferred = Deferred::default();
assert_eq!(deferred.request(1, true), Some(1));
}
#[test]
fn of_the_animations_asked_for_while_hidden_only_the_strongest_plays_once_shown() {
let mut deferred = Deferred::default();
assert_eq!(deferred.request(1, false), None);
assert_eq!(deferred.request(3, false), None);
assert_eq!(deferred.request(2, false), None);
assert_eq!(deferred.shown(), Some(3));
// It plays once.
assert_eq!(deferred.shown(), None);
}
fn at(start: Instant, ms: u64) -> Instant {
start + Duration::from_millis(ms)
}
#[test]
fn the_veil_covers_the_screen_leaving_in_130_ms_and_uncovers_the_one_arriving_in_280_ms() {
let start = Instant::now();
let out = Fade::covering(0., start);
assert_eq!(out.veil(start), 0.);
assert!(!out.finished(at(start, 129)));
assert!(out.finished(at(start, 130)));
assert_eq!(out.veil(at(start, 130)), 1.);
// Slow at first, as the reference's ease-in.
assert!(out.veil(at(start, 65)) < 0.5);
let arrival = Fade::uncovering(1., start);
assert_eq!(arrival.veil(start), 1.);
assert!(!arrival.finished(at(start, 279)));
assert!(arrival.finished(at(start, 280)));
assert_eq!(arrival.veil(at(start, 280)), 0.);
// Fast at first, then settling.
assert!(arrival.veil(at(start, 140)) < 0.5);
}
#[test]
fn a_switch_during_a_transition_starts_from_where_the_veil_is() {
let start = Instant::now();
assert_eq!(Fade::covering(0.4, start).veil(start), 0.4);
assert_eq!(Fade::uncovering(0.4, start).veil(start), 0.4);
assert_eq!(Fade::uncovering(0.4, start).veil(at(start, 280)), 0.);
}
#[test]
fn only_a_change_of_the_animations_setting_is_read_again() {
assert!(animation_setting_changed(
WM_SETTINGCHANGE,
SPI_SETCLIENTAREAANIMATION.0 as usize
));
// The theme (no parameter) or another setting.
assert!(!animation_setting_changed(WM_SETTINGCHANGE, 0));
assert!(!animation_setting_changed(
WM_SETTINGCHANGE,
SPI_SETMOUSESPEED.0 as usize
));
assert!(!animation_setting_changed(
WM_SIZE,
SPI_SETCLIENTAREAANIMATION.0 as usize
));
}
}
+461
View File
@@ -0,0 +1,461 @@
//! The page and its two tabs: the shared state and the navigation. `display` renders the header
//! row and the alerts; `home`, `champ_select` and `statistics` render the content under them.
use crate::banner_art::BannerArt;
use crate::card::Card;
use crate::card_grid::{CardGrid, CardHovered, Paging};
use crate::card_lift::Lifts;
use crate::champion_table::ChampionTable;
use crate::motion::{Deferred, Fade, FadePhase, MatchAnimation, MatchEnd};
use crate::ring::Ring;
use crate::stage::{Entry, Leave, Taken};
use crate::worker::{LiveChampSelect, Msg, RefreshGate};
use arena_tracker_core::{
Account, ChampionSearch, ChampionSort, Format, Scope, SeasonScope, StateFilter, Statistics,
Status, SyncProgress, Tracker,
};
use gpui_kit::base::Button as BaseButton;
use gpui_kit::base::async_util::Sender;
use gpui_kit::component::input::InputState;
use gpui_kit::component::select::{SelectItem, SelectState};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use profiling::shown;
use scrollbar::PageScrollbar;
use statistics::ChartsRow;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
mod cards;
mod champ_select;
mod display;
mod displayed;
mod home;
mod hover;
mod lifecycle;
mod playback;
mod profiling;
mod scrollbar;
mod setup;
mod statistics;
mod worker_messages;
#[cfg(test)]
mod tests;
/// The page's padding on every side: the card grid derives its width from it.
pub(crate) const PAGE_PADDING: f32 = 12.;
const ALL_SEASONS: &str = "Toutes les Saisons";
const ALL_FORMATS: &str = "Tous les Formats";
/// The sorts on offer, in the selector's order.
const SORTS: [(ChampionSort, &str); 2] = [
(ChampionSort::Mastery, "Maîtrise"),
(ChampionSort::Name, "A–Z"),
];
/// While an import runs, the page is recomputed at most this often.
const RELOAD_EVERY: Duration = Duration::from_secs(1);
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |d| d.as_millis() as i64)
}
/// One Account in the selector; its value is the puuid.
#[derive(Clone, PartialEq)]
struct AccountItem {
puuid: String,
title: SharedString,
}
impl SelectItem for AccountItem {
type Value = String;
fn title(&self) -> SharedString {
self.title.clone()
}
fn value(&self) -> &String {
&self.puuid
}
}
/// What the page starts from.
pub struct Launch {
pub notice: Option<String>,
/// A follower thread is already running, its first round is pending.
pub following: bool,
/// The sort saved by an earlier run.
pub champion_sort: Option<ChampionSort>,
}
/// The page entered or left an Arena champ select.
pub struct ChampSelectTransition {
pub entered: bool,
}
impl EventEmitter<ChampSelectTransition> for Page {}
/// The player chose a sort for the cards: to be saved with the other preferences.
pub struct ChampionSortChosen(pub ChampionSort);
impl EventEmitter<ChampionSortChosen> for Page {}
/// The two pages the navigation switches between.
#[derive(Clone, Copy, PartialEq, Debug)]
enum Tab {
/// « Défi », the home: the Challenge of one Season.
Challenge,
/// « Statistiques »: the analysis by Account, Season and Format.
Statistics,
}
/// A followed Match waiting to play: of several, the strongest plays, and the most recent of the
/// strongest. The order of the fields is that ranking (derived `Ord`).
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
struct WaitingMatch {
end: MatchEnd,
started_at_ms: i64,
champion_id: u32,
}
/// The end of a followed Match on « Défi », from the round that stored it to the end of its
/// animation; `Page::end_match` drops it all.
#[derive(Default)]
struct MatchPlayback {
/// The Match to play once the statistics with it are shown and « Défi » is in front: it
/// waits there whatever hides « Défi » meanwhile.
waiting: Deferred<WaitingMatch>,
/// The statistics shown do not hold the queued Match yet.
stats_pending: bool,
/// The animation running, fixed when it started.
animation: Option<MatchAnimation>,
/// The banner before the Match: its text until the comet lands, its splash under the comet.
previous_banner: Option<home::BannerContent>,
/// The champion's card before the Match, drawn until its change lands.
previous_card: Option<Rc<Card>>,
/// The champion whose card the grid showed: it stays shown until the animation ends, even
/// if the filter now leaves it out, so that it changes in place.
kept_card: Option<u32>,
}
impl MatchPlayback {
fn active(&self) -> bool {
self.waiting.waiting().is_some() || self.animation.is_some()
}
}
/// The home grid of new statistics that arrived while the pointer held it still, prepared on
/// their arrival: the pointer leaving only puts it in place (rule #1).
struct NextHome {
order: Vec<usize>,
cards: Rc<[Card]>,
shown: Vec<usize>,
count: SharedString,
}
pub struct Page {
tracker: Arc<Tracker>,
tx: Sender<Msg>,
notice: Option<String>,
/// As of the last follower round or refresh.
status: Status,
champ_select: LiveChampSelect,
/// The Account of `champ_select`, resolved when its Riot ID changes.
champ_select_account: Option<String>,
/// The Riot ID `champ_select_account` was resolved for.
champ_select_riot_id: Option<String>,
accounts: Vec<Account>,
last_active: Option<Account>,
/// The Account the user picked instead of following the one being updated.
pinned: Option<String>,
/// The Account of the last requested statistics.
shown: Option<String>,
progress: Option<SyncProgress>,
refresh: RefreshGate,
stats_job: RefreshGate,
stats_generation: u64,
/// Until the follower's first round ends.
pending_round: bool,
crashed: bool,
last_reload: Instant,
current_season: Option<String>,
/// The tab the navigation shows as chosen. Not persisted: the app opens on the Challenge.
/// The screen drawn (`shown_tab`) follows it once the screen leaving is under the veil.
tab: Tab,
/// The tab whose screen is drawn.
shown_tab: Tab,
/// The transition between the tabs, while it runs.
fade: Option<Fade>,
/// A frame of the transition is asked for.
frame_asked: bool,
/// The cards lifted over their grid, by grid: the one under the pointer or the keyboard, and
/// those settling back (#88).
lifts: Lifts<EntityId>,
/// The grid whose card the keyboard lifted: the pointer moving puts it down.
lifted_by_keyboard: Option<WeakEntity<CardGrid>>,
/// « Paramètres » stands in for the page.
covered: bool,
/// The end of a followed Match, from its round to the end of its animation.
playback: MatchPlayback,
/// The pointer was on the home grid when a followed Match changed it: its cards change in
/// place, and the order, the filter and the count wait for the pointer to leave so that
/// nothing moves under it.
hold_grid: bool,
/// While `hold_grid`, the grid it waits to show, once the statistics are there.
next_home: Option<NextHome>,
/// The champ select's entry (#87), from when the window shows it until its hand is dealt.
entry: Option<Entry>,
/// A champ select started while the window or the page was not in front: its entry plays
/// once they are.
entry_waiting: bool,
/// The hand leaving at the end of a champ select. The end itself is applied once the veil
/// of the tabs covers the screen (`finish_exit`), so the champ select stays drawn until then.
leave: Option<Leave>,
/// The cards of the hand an ally just took, going down to their place.
taken: Vec<Taken>,
/// The card of the hand under the pointer or the keyboard while it is still dealt: it is
/// lifted once in its place.
hover_waiting: Option<CardHovered>,
/// A frame of the champ select's motion is asked for.
stage_frame_asked: bool,
/// The animations played, in order.
#[cfg(test)]
played: Vec<MatchEnd>,
/// The Season of the Statistics tab.
season: SeasonScope,
format: Option<Format>,
filter: StateFilter,
/// Kept and reapplied whenever the table's rows are rebuilt.
search: ChampionSearch,
search_input: Entity<InputState>,
stats: Option<Statistics>,
stats_error: Option<String>,
/// The Season whose Challenge the home shows: the one chosen on the Statistics tab, else the
/// current one. None when there is no such Season.
home_season: Option<SharedString>,
/// The home's scope when it differs from the Statistics tab's, else the home reads `stats`.
home_scope: Option<Scope>,
/// Only for a `home_scope`.
home_stats: Option<Statistics>,
home_error: Option<String>,
/// The Account and scope `home_stats` or `home_error` were computed for: the home does not
/// depend on the Format, so a change of Format keeps them.
home_computed: Option<(String, Scope)>,
/// What the banner shows, prepared when the statistics change.
banner: home::BannerContent,
champ_select_splashes: HashMap<u32, Rc<arena_tracker_core::Splash>>,
/// The banner's ring: a cached view.
ring: Entity<Ring>,
/// The grid whose card lit the ring's tick.
lit_by: Option<EntityId>,
/// The banner's illustration, its own: given back while the banner is not shown.
banner_art: Entity<BannerArt>,
/// The home's own filter and search: never persisted, « Tous » at each launch.
home_filter: StateFilter,
home_search: ChampionSearch,
home_search_input: Entity<InputState>,
/// The sort the player chose, saved with the preferences; `None` until one is chosen, which
/// sorts by Mastery Points.
champion_sort: Option<ChampionSort>,
sort_select: Entity<SelectState<Vec<SharedString>>>,
/// The positions of the home statistics' rows in the cards' order, which every section
/// follows. Computed again only when those statistics or the sort change (`reorder`).
order: Vec<usize>,
/// How many times `order` was computed.
#[cfg(test)]
reorders: usize,
stored: Option<usize>,
account_select: Entity<SelectState<Vec<AccountItem>>>,
account_items: Vec<AccountItem>,
season_select: Entity<SelectState<Vec<SharedString>>>,
format_select: Entity<SelectState<Vec<SharedString>>>,
format_names: Vec<SharedString>,
charts: Entity<ChartsRow>,
table: Entity<ChampionTable>,
/// The home's champions, one card each.
home_grid: Entity<CardGrid>,
/// The home's cards were not rebuilt for the latest statistics, as the home was not shown.
home_cards_stale: bool,
/// How many cards the grid shows, prepared when the filter or search change.
home_shown_count: SharedString,
/// The Anvil champions of the champ select, one card each in the home grid's order, with
/// the reasons the champ select gives. Only drawn during a champ select.
anvil_grid: Entity<CardGrid>,
/// How many Anvil champions the row shows, prepared with the cards.
anvil_count: SharedString,
/// « Autres champions »: folded at each new champ select. While it is, it holds no card.
others_open: bool,
/// Filters this section only; emptied with each new champ select.
others_search: ChampionSearch,
others_search_input: Entity<InputState>,
/// The champions without an Anvil (all of them when the list is unknown), only built while
/// the section is open: a virtualized grid, which the champ select's scrolling moves.
others_grid: Entity<CardGrid>,
/// The scrolling of the whole champ select (the banner, the Anvil champions and the section),
/// and where the section's grid starts in it, which says the rows of the grid in view.
paging: Paging,
/// Its scrollbar, a view of its own for the fade.
champ_select_scrollbar: Entity<PageScrollbar>,
/// The section's header button, which the keyboard reaches.
others_focus: FocusHandle,
/// Lights the ring's tick of the card hovered in « Autres champions », lifts it, and scrolls the
/// champ select to the card the keyboard reaches; its grid is made again at each fold.
others_hover: [Subscription; 3],
_subscriptions: Vec<Subscription>,
_listener: Task<()>,
}
impl Page {
/// The two tabs as buttons: they take the keyboard focus, and Enter or Space activates them.
fn navigation(&self, cx: &mut Context<Self>) -> impl IntoElement {
let theme = cx.theme();
let (ring, muted, active, active_foreground, hover, hover_foreground) = (
theme.ring,
theme.tab_foreground,
theme.tab_active,
theme.tab_active_foreground,
theme.accent,
theme.accent_foreground,
);
let tabs = [
("tab-challenge", "Défi", Tab::Challenge),
("tab-statistics", "Statistiques", Tab::Statistics),
];
div()
.h_flex()
.gap_1()
.flex_shrink_0()
.children(tabs.map(|(id, label, tab)| {
let current = self.tab == tab;
// The champ select takes the window: « Statistiques » waits for its end.
let disabled = tab == Tab::Statistics && self.in_champ_select();
BaseButton::new(id)
.disabled(disabled)
.px_3()
.py_1()
.rounded_md()
.text_sm()
.font_weight(FontWeight::SEMIBOLD)
// Always bordered, so the focus ring does not shift the label.
.border_1()
.border_color(transparent_black())
.focus_visible(|style| {
style.border_color(if current { active_foreground } else { ring })
})
.text_color(if current { active_foreground } else { muted })
.when(current, |button| button.bg(active))
.when(!current && !disabled, |button| {
button.hover(|style| style.bg(hover).text_color(hover_foreground))
})
.when(disabled, |button| button.opacity(0.5))
.accessibility_label(label)
.debug_selector(|| id.into())
.child(label)
.on_click(cx.listener(move |this, _, window, cx| this.set_tab(tab, window, cx)))
}))
}
fn set_tab(&mut self, tab: Tab, window: &mut Window, cx: &mut Context<Self>) {
// The champ select takes the window: the Statistics tab waits for its end.
if tab == Tab::Statistics && self.in_champ_select() {
return;
}
if self.tab != tab {
self.tab = tab;
// The grids leave under the veil: no card stays lifted over it.
self.lifts.clear();
if cx.reduce_motion() || !window.is_visible() {
// Nothing to see: the end state at once.
self.end_fade(window, cx);
} else {
// From where the veil is: a switch during a transition does not wait for it.
let now = cx.background_executor().now();
let veil = self.veil(cx);
self.fade = Some(if self.shown_tab == tab {
Fade::uncovering(veil, now)
} else {
Fade::covering(veil, now)
});
self.next_fade_frame(window, cx);
}
cx.notify();
}
}
/// Draws the screen of the tab chosen.
fn show_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.shown_tab == self.tab {
return;
}
self.shown_tab = self.tab;
// The home grid is no longer under the pointer.
self.release_home(cx);
// The screen arriving was not kept up to date while hidden, and is prepared only now: a
// switch undone under the veil prepares nothing.
self.refresh_table(cx);
if self.home_cards_stale {
self.prepare_home_cards(cx);
}
self.refresh_home(cx);
if self.shown_tab == Tab::Statistics {
// The home grid is not shown: its portraits are given back, and come back with the
// grid.
self.home_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
// Nor is the banner: its illustration too.
self.banner_art
.update(cx, |art, cx| art.release(window, cx));
} else {
// Nor is the table: its portraits.
self.table
.update(cx, |table, cx| table.release_images(window, cx));
}
}
/// Shows the end of the transition, if one runs, at once.
fn end_fade(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.fade = None;
if self.leave.is_some() {
self.finish_exit(window, cx);
}
self.show_tab(window, cx);
self.play_waiting(window, cx);
cx.notify();
}
/// Asks for the transition's next frame, once.
fn next_fade_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if !self.frame_asked {
self.frame_asked = true;
cx.on_next_frame(window, |page, window, cx| page.fade_frame(window, cx));
}
}
/// One frame of the transition: the screen arriving replaces the one leaving under the full
/// veil, and no frame is asked for once the veil is lifted.
fn fade_frame(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.frame_asked = false;
let Some(fade) = &self.fade else {
return;
};
let now = cx.background_executor().now();
if fade.finished(now) {
match fade.phase() {
FadePhase::Out => {
self.show_tab(window, cx);
// The champ select that ended leaves under the full veil: the home comes
// out of it, as after a switch of tabs.
if self.leave.is_some() {
self.finish_exit(window, cx);
}
self.fade = Some(Fade::uncovering(1., now));
}
FadePhase::In => return self.end_fade(window, cx),
}
}
self.next_fade_frame(window, cx);
cx.notify();
}
}
+164
View File
@@ -0,0 +1,164 @@
use super::{ChampionSortChosen, Page, Tab};
use crate::card::Card;
use crate::card_order::card_order;
use arena_tracker_core::{ChampionRow, ChampionSearch, ChampionSort, StateFilter};
use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// Computes the cards' order again: for when the home statistics (the champ select's during
/// a champ select) or the sort change, and for nothing else.
pub(in crate::page) fn reorder(&mut self) {
self.order = self.sorted_order();
}
/// The cards' order for the home statistics and the sort.
pub(in crate::page) fn sorted_order(&mut self) -> Vec<usize> {
#[cfg(test)]
{
self.reorders += 1;
}
let sort = self.champion_sort.unwrap_or(ChampionSort::Mastery);
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
card_order(rows, sort)
}
/// The pointer left the home grid it held still: the grid prepared when the statistics
/// arrived takes its place, built and sorted already.
pub(in crate::page) fn release_home(&mut self, cx: &mut Context<Self>) {
let held = std::mem::take(&mut self.hold_grid);
let Some(next) = self.next_home.take().filter(|_| held) else {
return;
};
self.order = next.order;
self.home_shown_count = next.count;
self.home_grid.update(cx, |grid, cx| {
grid.set_cards(next.cards, cx);
grid.set_shown(next.shown, cx);
});
}
/// The player changed the home's filter or search: the grid follows at once, even under the
/// pointer or with a card kept for its Match.
pub(in crate::page) fn home_filtered(&mut self, cx: &mut Context<Self>) {
self.release_home(cx);
self.playback.kept_card = None;
self.refresh_home(cx);
}
/// The home grid no longer waits for the pointer to leave: what comes next rebuilds it.
pub(in crate::page) fn stop_holding(&mut self) {
self.hold_grid = false;
self.next_home = None;
}
/// The home statistics' rows in the cards' order: the single iteration the home grid, the
/// Anvil champions and « Autres champions » all follow.
pub(in crate::page) fn ordered_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
self.order.iter().filter_map(move |&ix| rows.get(ix))
}
/// The player chose a sort: the cards of every section follow it, and it is saved.
pub(crate) fn choose_sort(&mut self, sort: ChampionSort, cx: &mut Context<Self>) {
if self.champion_sort == Some(sort) {
return;
}
self.stop_holding();
self.champion_sort = Some(sort);
self.reorder();
if self.in_champ_select() {
self.prepare_champ_select(cx);
} else {
self.prepare_home_cards(cx);
self.refresh_home(cx);
}
cx.emit(ChampionSortChosen(sort));
cx.notify();
}
/// One card per champion, in the cards' order, for when the statistics or the sort change.
/// While the home is not shown the next switch to it does (`home_cards_stale`).
pub(in crate::page) fn prepare_home_cards(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Challenge {
self.home_cards_stale = true;
return;
}
self.home_cards_stale = false;
let cards: Rc<[Card]> = self.ordered_rows().map(Card::from_row).collect();
self.home_grid
.update(cx, |grid, cx| grid.set_cards(cards, cx));
}
/// At the end of a champ select the home is as at launch: « Tous » and an empty search. The
/// Account and Season viewed were never touched.
pub(in crate::page) fn reset_home_view(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.home_filter = StateFilter::All;
self.home_search = ChampionSearch::new("");
self.home_search_input
.update(cx, |input, cx| input.set_value("", window, cx));
}
/// Rebuilds the Statistics tab's rows; while it is not shown, the next switch does.
pub(in crate::page) fn refresh_table(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Statistics {
return;
}
let rows = self.stats.iter().flat_map(|s| &s.rows);
let rows = rows
.filter(|row| self.filter.keeps(row) && self.search.matches(&row.champion))
.cloned()
.collect();
let in_season = self.in_season();
self.table.update(cx, |table, cx| {
table.set_rows(rows, in_season);
cx.notify();
});
}
/// Recomputes which cards the home shows from its own filter and search, with the total
/// untouched; while the home is not shown, the next switch does.
pub(in crate::page) fn refresh_home(&mut self, cx: &mut Context<Self>) {
if self.shown_tab != Tab::Challenge || self.in_champ_select() {
return;
}
if self.hold_grid {
// Nothing moves under the pointer: the grid it leaves for follows instead.
let shown = (self.next_home.as_ref()).map(|next| self.home_shown(&next.order));
if let (Some(next), Some(shown)) = (self.next_home.as_mut(), shown) {
next.count = shown.len().to_string().into();
next.shown = shown;
}
return;
}
let shown = self.home_shown(&self.order);
self.home_shown_count = shown.len().to_string().into();
self.home_grid
.update(cx, |grid, cx| grid.set_shown(shown, cx));
}
/// The cards the home's filter and search keep, as indices of its cards in `order`. The
/// card of a followed Match's champion that was shown stays until its animation ends, so
/// that it changes in place (#89).
pub(in crate::page) fn home_shown(&self, order: &[usize]) -> Vec<usize> {
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
let changing = self.playback.kept_card;
// The cards are the rows in the cards' order: a card's index is its position.
order
.iter()
.filter_map(|&ix| rows.get(ix))
.enumerate()
.filter(|(_, row)| {
Some(row.champion.id) == changing
|| (self.home_filter.keeps(row) && self.home_search.matches(&row.champion))
})
.map(|(ix, _)| ix)
.collect()
}
}
+98
View File
@@ -0,0 +1,98 @@
use super::{ChampSelectTransition, Page, Tab};
use crate::worker::LiveChampSelect;
use arena_tracker_core::{account_riot_id, same_riot_id};
use gpui_kit::*;
pub(in crate::page) const UNKNOWN_ANVIL: &str =
"Champions de l'Enclume non communiqués par le client";
mod cards;
mod motion;
mod render;
impl Page {
/// The Account of the live champ select. Resolved when the signed-in Riot ID changes (or the
/// Accounts do), so preparing statistics builds no Riot ID per Account every time.
pub(in crate::page) fn champ_select_account(&mut self) -> Option<String> {
let id = self.champ_select.as_ref().map(|(id, _)| id.as_str())?;
if self.champ_select_riot_id.as_deref() != Some(id) {
self.champ_select_riot_id = Some(id.into());
self.champ_select_account = self
.accounts
.iter()
.find(|a| same_riot_id(&account_riot_id(a), id))
.map(|a| a.puuid.clone());
}
self.champ_select_account.clone()
}
/// The champ select the client reports changed: entered, left, another one, or the same
/// one with new picks and bans.
pub(in crate::page) fn change_champ_select(
&mut self,
champ_select: LiveChampSelect,
window: &mut Window,
cx: &mut Context<Self>,
) {
let previous = self.champ_select.as_ref();
let next = champ_select.as_ref();
let changed_page = previous.is_some() != next.is_some();
let switch = changed_page || previous.map(|(id, _)| id) != next.map(|(id, _)| id);
self.champ_select = champ_select;
if changed_page {
if self.in_champ_select() {
// The champ select is about the Challenge, whatever tab was open.
self.tab = Tab::Challenge;
// Nothing plays during a champ select: what waited is no longer news.
self.stop_holding();
self.end_match(cx);
self.end_fade(window, cx);
// The home grid gives way to the champ select's sections.
self.home_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
// Its entry plays once the window shows it (#63 reveals it without focus).
self.entry_waiting = true;
} else {
self.forget_stage();
self.reset_home_view(window, cx);
self.anvil_grid
.update(cx, |grid, cx| grid.release_images(window, cx));
// An animation asked for during the champ select plays on the home.
self.playback.stats_pending = self.playback.active();
}
}
if switch {
// The Account belongs to the signed-in Riot ID: resolve it once, not on every
// statistics preparation.
self.champ_select_riot_id = None;
self.stats_generation += 1;
self.stats = None;
self.stats_error = None;
self.forget_home();
self.stored = None;
self.reorder();
// A new champ select starts with « Autres champions » folded and searchless, at the
// top of the page.
self.fold_others(window, cx);
self.paging.scroll.set_offset(point(px(0.), px(0.)));
self.reload_in_background(window, cx);
// Nor does the banner keep the previous scope's Challenge while the new one
// loads: its Season, its ticks and its splash go with the statistics.
self.prepare_banner(cx);
}
if changed_page {
cx.emit(ChampSelectTransition {
entered: self.in_champ_select(),
});
}
// The hand as it was, to see which card an ally just took.
let before = (!switch).then(|| self.anvil_grid.read(cx).cards().clone());
// Any change (a hover or a lock-in too) changes the reasons of the cards. Only
// the client's events get here: no polling.
self.prepare_champ_select(cx);
if let Some(before) = before {
self.lower_taken(&before, window, cx);
}
self.start_entry(window, cx);
}
}
+176
View File
@@ -0,0 +1,176 @@
use crate::card::Card;
use crate::card_grid::{CardGrid, RevealRow};
use crate::page::{Page, home};
use arena_tracker_core::{ChampSelect, ChampionRow, ChampionSearch};
use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// A new grid for « Autres champions », whose hover lights the ring as the others do. The
/// one it replaces puts out the tick it lit.
fn new_others_grid(&mut self, cx: &mut Context<Self>) {
let replaced = self.others_grid.entity_id();
// The new grid is not laid out: the old one's place is not its own.
self.paging.top.set(None);
let paging = self.paging.clone();
self.others_grid = cx.new(|_| CardGrid::paged(paging));
self.others_hover = Self::light_and_reveal(&self.others_grid, cx);
self.lifts.drop_grid(replaced);
self.light(replaced, None, cx);
}
/// What `light_on_hover` does for the grid of « Autres champions », and scrolls the champ
/// select to the row the keyboard reaches: the grid holds no scrolling of its own.
pub(in crate::page) fn light_and_reveal(
grid: &Entity<CardGrid>,
cx: &mut Context<Self>,
) -> [Subscription; 3] {
let [hovered, put_down] = Self::light_on_hover(grid, cx);
let reveal = cx.subscribe(grid, |this, _, row: &RevealRow, cx| this.reveal(*row, cx));
[hovered, put_down, reveal]
}
/// Scrolls the champ select the least that shows the row of « Autres champions » the
/// keyboard reached.
fn reveal(&mut self, row: RevealRow, cx: &mut Context<Self>) {
let Some(grid_top) = self.paging.top.get() else {
return;
};
let scroll = &self.paging.scroll;
let (top, bottom) = (grid_top + row.top, grid_top + row.bottom);
let (scrolled, viewport) = (-scroll.offset().y, scroll.bounds().size.height);
let to = if top < scrolled {
top
} else if bottom > scrolled + viewport {
bottom - viewport
} else {
return;
};
scroll.set_offset(point(scroll.offset().x, -to));
cx.notify();
}
pub(in crate::page) fn in_champ_select(&self) -> bool {
self.champ_select.is_some()
}
pub(in crate::page) fn live_champ_select(&self) -> Option<&ChampSelect> {
self.champ_select.as_ref().map(|(_, pick)| pick)
}
/// The cards of the Anvil champions row (`stats_notice` says why there are none when the
/// statistics are missing). For when the champ select, the statistics or the status change.
pub(in crate::page) fn prepare_champ_select(&mut self, cx: &mut Context<Self>) {
// The same rows in the same order as the home grid (`ordered_rows`): the
// cards keep their place whatever the champ select does. An id the rows do not know is
// skipped.
let champ_select = self.live_champ_select();
let anvil = champ_select.and_then(|pick| pick.anvil_champions.as_deref());
let ids = anvil.unwrap_or_default();
let cards = self.champ_select_cards(
self.ordered_rows()
.filter(|row| ids.contains(&row.champion.id)),
);
// A list the client did not send dims no tick: the ring would look empty.
self.ring.update(cx, |ring, cx| ring.set_anvil(anvil, cx));
if champ_select.is_some() {
let remaining_pickable = cards.iter().filter(|card| !card.greyed());
let first = remaining_pickable.clone().next().or_else(|| cards.first());
let splash = first
.and_then(|card| self.champ_select_splashes.get(&card.id))
.cloned();
self.banner = home::BannerContent::champ_select(
self.home_season.as_ref(),
self.home_statistics(),
anvil.is_some(),
remaining_pickable.count(),
splash,
);
self.select_art(self.ring.read(cx).lit(), cx);
}
self.anvil_count = cards.len().to_string().into();
let shown = (0..cards.len()).collect();
// The hand's cards are dealt once they come: the statistics load at each entry.
if let Some(entry) = &mut self.entry
&& !cards.is_empty()
{
entry.cards_arrived(cx.background_executor().now());
}
self.anvil_grid.update(cx, |grid, cx| {
grid.set_cards(cards, cx);
grid.set_shown(shown, cx);
});
self.prepare_others(cx);
}
/// The cards of `rows` during the champ select, each with the reasons it cannot be picked;
/// none outside a champ select.
fn champ_select_cards<'a>(&self, rows: impl Iterator<Item = &'a ChampionRow>) -> Rc<[Card]> {
match self.live_champ_select() {
Some(pick) => rows
.map(|row| Card::from_row(row).with_unpickable(pick.unpickable(row.champion.id)))
.collect(),
None => Rc::new([]),
}
}
/// The rows of « Autres champions »: those whose id is not an Anvil one, in the master
/// order; all of them when the client gave no list.
fn other_rows(&self) -> impl Iterator<Item = &ChampionRow> {
let anvil = self
.live_champ_select()
.and_then(|pick| pick.anvil_champions.as_deref());
self.ordered_rows()
.filter(move |row| anvil.is_none_or(|ids| !ids.contains(&row.champion.id)))
}
/// Builds the cards of « Autres champions », for when the section opens or the champ select
/// or the statistics change; while it is folded, nothing is built.
fn prepare_others(&mut self, cx: &mut Context<Self>) {
if !self.others_open {
return;
}
let cards = self.champ_select_cards(self.other_rows());
self.others_grid
.update(cx, |grid, cx| grid.set_cards(cards, cx));
self.refresh_others(cx);
}
/// Recomputes which cards of « Autres champions » its search keeps: the cards are the rows
/// of `other_rows`, in the same order.
pub(in crate::page) fn refresh_others(&mut self, cx: &mut Context<Self>) {
if !self.others_open {
return;
}
let shown: Vec<usize> = self
.other_rows()
.enumerate()
.filter(|(_, row)| self.others_search.matches(&row.champion))
.map(|(ix, _)| ix)
.collect();
self.others_grid
.update(cx, |grid, cx| grid.set_shown(shown, cx));
}
/// Opens or folds « Autres champions »; folded, it gives its cards back.
pub(in crate::page) fn toggle_others(&mut self, cx: &mut Context<Self>) {
self.others_open = !self.others_open;
if self.others_open {
self.prepare_others(cx);
} else {
self.new_others_grid(cx);
}
cx.notify();
}
/// Folds « Autres champions » and empties its search, for a new champ select.
pub(in crate::page) fn fold_others(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.others_open {
self.others_open = false;
self.new_others_grid(cx);
}
self.others_search = ChampionSearch::new("");
self.others_search_input
.update(cx, |input, cx| input.set_value("", window, cx));
}
}
+235
View File
@@ -0,0 +1,235 @@
use crate::card::{Card, Reason};
use crate::card_grid::CardGrid;
use crate::motion::Fade;
use crate::page::Page;
use crate::stage::{self, BEFORE_VEIL, Entry, HandAt, HandMotion, Leave, Taken};
use gpui_kit::*;
use std::rc::Rc;
use std::time::Instant;
impl Page {
/// Whether the page is in front of the player and may animate: the window shown, not
/// behind « Paramètres », and the Windows « Show animations » setting on.
pub(in crate::page) fn may_animate(&self, window: &Window, cx: &App) -> bool {
!cx.reduce_motion() && window.is_visible() && !self.covered
}
/// Plays the entry of the champ select waiting for it, if the page is in front: the band of
/// light, the title, then the hand dealt once it has its cards. With the Windows setting off
/// the hand is simply there.
pub(in crate::page) fn start_entry(&mut self, window: &Window, cx: &mut Context<Self>) {
if !self.entry_waiting || !self.in_champ_select() {
return;
}
if cx.reduce_motion() {
self.entry_waiting = false;
return;
}
if !self.may_animate(window, cx) {
return;
}
self.entry_waiting = false;
let now = cx.background_executor().now();
let mut entry = Entry::new(now);
if !self.anvil_grid.read(cx).cards().is_empty() {
entry.cards_arrived(now);
}
self.entry = Some(entry);
cx.notify();
}
/// The champ select's motion shows its end at once: the window is hidden, the page covered
/// or the setting turned off. A card the pointer waited for is lifted now.
pub(in crate::page) fn end_stage(&mut self, cx: &mut Context<Self>) {
self.entry = None;
self.taken.clear();
self.land_hover(cx.background_executor().now(), cx);
}
/// No entry played or waiting, no card going down or waited for: the champ select ends.
pub(in crate::page) fn forget_stage(&mut self) {
self.entry = None;
self.entry_waiting = false;
self.taken.clear();
self.hover_waiting = None;
}
/// The champ select ended: the hand leaves, the last card first, then the veil of the tabs
/// covers the screen and the end is applied under it (`finish_exit`).
pub(in crate::page) fn start_exit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let now = cx.background_executor().now();
let hand = self.anvil_grid.entity_id();
let lifted: Vec<_> = self.lifts.lifted(hand, now).collect();
// Each card leaves from where it is: on its way, lifted, under the veil or going down
// after an ally's confirmation. Those not dealt yet stay out of sight.
let hand_at = HandAt {
entry: self.entry.filter(Entry::dealing),
lifted: &lifted,
veil: self.lifts.veil(hand, now),
taken: &self.taken,
};
let grid = self.anvil_grid.read(cx);
let cards = grid.cards().len();
let leave = Leave::new(grid.cards(), hand_at, now);
self.forget_stage();
// No card stays lifted over the hand leaving.
self.lifts.clear();
self.lifted_by_keyboard = None;
self.leave = Some(leave);
let veil_from = if cards == 0 { now } else { now + BEFORE_VEIL };
self.fade = Some(Fade::covering(0., veil_from));
self.next_fade_frame(window, cx);
cx.notify();
}
/// Applies the end of the champ select that was leaving: the home comes back as #74 leaves
/// it.
pub(in crate::page) fn finish_exit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.leave = None;
self.change_champ_select(None, window, cx);
}
/// An ally confirmed a champion of the hand: its card goes down to its place, a little
/// lower than the others, as it greys. A card still dealt goes straight to that place.
pub(in crate::page) fn lower_taken(
&mut self,
before: &[Card],
window: &Window,
cx: &mut Context<Self>,
) {
if !self.may_animate(window, cx) {
return;
}
let now = cx.background_executor().now();
let taken = |card: &Card| card.reasons.contains(&Reason::TakenByAlly);
let lowered: Vec<_> = (self.anvil_grid.read(cx).cards().iter().enumerate())
.filter(|(ix, card)| {
taken(card) && self.entry.is_none_or(|entry| entry.landed(*ix, now))
})
.filter_map(|(_, card)| {
let was = before.iter().find(|was| was.id == card.id)?;
(!taken(was)).then(|| Taken::new(card.id, Rc::new(was.clone()), now))
})
.collect();
for card in lowered {
self.taken.retain(|taken| taken.id != card.id);
self.taken.push(card);
}
cx.notify();
}
/// Whether card `id` of `grid` is the hand's and still on its way there at `now`.
pub(in crate::page) fn dealing(
&self,
grid: &Entity<CardGrid>,
id: u32,
now: Instant,
cx: &App,
) -> bool {
if grid.entity_id() != self.anvil_grid.entity_id() {
return false;
}
let Some(entry) = self.entry else {
return false;
};
// A card under the pointer or the keyboard is drawn: the grid knows where it is.
let ix = grid
.read(cx)
.drawn_cards()
.borrow()
.get(&id)
.map(|drawn| drawn.ix);
ix.is_some_and(|ix| !entry.landed(ix, now))
}
/// The card of the hand the pointer waited for is in its place at `now`: lifted if it is
/// still under the pointer or the keyboard.
fn land_hover(&mut self, now: Instant, cx: &mut Context<Self>) {
let Some(waiting) = self.hover_waiting else {
return;
};
let grid = self.anvil_grid.clone();
if waiting
.id
.is_some_and(|id| self.dealing(&grid, id, now, cx))
{
return;
}
self.hover_waiting = None;
if grid.read(cx).hovered() == waiting.id {
self.hovered(&grid, waiting, cx);
}
}
/// Whether the champ select's motion asks for frames: its entry, a card going down, or a
/// card the pointer waits for, until a frame finds it in its place. Nothing is read on the
/// home or « Statistiques ».
pub(in crate::page) fn stage_moving(&self, cx: &App) -> bool {
if !self.taken.is_empty() || self.hover_waiting.is_some() {
return true;
}
let Some(entry) = self.entry else {
return false;
};
let now = cx.background_executor().now();
entry.animating(self.anvil_grid.read(cx).cards().len(), now)
}
/// Asks for the champ select's next frame, once.
pub(in crate::page) fn next_stage_frame(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
if !self.stage_frame_asked {
self.stage_frame_asked = true;
cx.on_next_frame(window, |page, _, cx| page.stage_frame(cx));
}
}
/// One frame of the champ select's motion: what is over is forgotten, a card dealt under
/// the pointer is lifted, and the page draws the rest where it is now.
fn stage_frame(&mut self, cx: &mut Context<Self>) {
self.stage_frame_asked = false;
let now = cx.background_executor().now();
let cards = self.anvil_grid.read(cx).cards().len();
if self.entry.is_some_and(|entry| entry.over(cards, now)) {
self.entry = None;
}
self.taken.retain(|taken| !taken.done(now));
self.land_hover(now, cx);
cx.notify();
}
/// The hand's cards moving over its grid, if any.
pub(in crate::page) fn hand_layer(&self, cx: &App) -> Option<AnyElement> {
// An entry whose hand has no card yet hides none.
let entry = self.entry.filter(Entry::dealing);
if entry.is_none() && self.leave.is_none() && self.taken.is_empty() {
return None;
}
let now = cx.background_executor().now();
let id = self.anvil_grid.entity_id();
let motion = HandMotion {
entry,
leave: self.leave.clone(),
taken: self.taken.clone(),
lifted: self.lifts.lifted(id, now).map(|lifted| lifted.id).collect(),
unveiled: 1. - self.veil(cx),
now,
};
let grid = self.anvil_grid.read(cx);
Some(stage::hand_layer(
grid.cards().clone(),
grid.drawn_cards().clone(),
grid.images().cloned(),
motion,
))
}
/// The title's opacity and how far below its place it is, while the entry brings it in.
pub(in crate::page) fn title_pose(&self, cx: &App) -> Option<(f32, f32)> {
let entry = self.entry?;
Some(entry.title_pose(cx.background_executor().now()))
}
}
+203
View File
@@ -0,0 +1,203 @@
use super::UNKNOWN_ANVIL;
use crate::page::{
Page,
home::{StatsNotice, count_badge, notice_line},
};
use crate::theme::heading;
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::input::Input;
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
impl Page {
/// What stands in place of the Anvil champions row, if anything: the statistics are missing,
/// or the client gave no list (which does not make any champion without an anvil), or an
/// empty one.
pub(in crate::page) fn anvil_line(&self) -> Option<SharedString> {
if let Some(notice) = self.stats_notice() {
return Some(notice.label(self.error().map(String::as_str)));
}
match &self.live_champ_select()?.anvil_champions {
None => Some(UNKNOWN_ANVIL.into()),
Some(ids) if ids.is_empty() => {
Some("Aucun Champion de l'Enclume dans cette sélection".into())
}
Some(_) => None,
}
}
/// « Champions de l'Enclume » with how many there are, and the row of their cards.
pub(in crate::page) fn anvil_area(
&self,
window_width: Pixels,
cx: &mut Context<Page>,
) -> impl IntoElement {
let theme = cx.theme();
let (muted, border) = (theme.muted_foreground, theme.border);
let row = self.anvil_line();
let said_elsewhere = self.stats_notice().is_some_and(StatsNotice::said_elsewhere)
|| row.as_deref() == Some(UNKNOWN_ANVIL);
div()
.v_flex()
.gap_3()
// The scrollbar's lane: the sort selector does not go under it.
.pr(Scrollbar::width())
.child(
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.child(
div()
.h_flex()
.items_center()
.gap(px(6.))
.child(heading(cx).text_xl().child("Champions de l'Enclume"))
.when(row.is_none(), |heading| {
heading.child(count_badge(self.anvil_count.clone(), muted, border))
}),
)
.child(self.sort_selector(cx)),
)
.children(match row {
// The header already says there is no Season, and a banner the statistics' error:
// not twice.
Some(_) if said_elsewhere => None,
Some(line) => Some(notice_line("anvil-notice", line, muted)),
None => Some(
div()
.w_full()
.debug_selector(|| "anvil-row".into())
.child(match self.anvil_grid.read(cx).rows_height(window_width) {
Some(height) => self
.anvil_grid
.clone()
.cached(StyleRefinement::default().w_full().h(height))
.into_any_element(),
None => self.anvil_grid.clone().into_any_element(),
})
.children(self.lift_layer(&self.anvil_grid, cx))
.children(self.hand_layer(cx))
.into_any_element(),
),
})
}
/// « Autres champions » when the client gave the Anvil champions, so that these are the ones
/// without an anvil; « Tous les champions » when it did not, as the section then lists all.
pub(in crate::page) fn others_title(&self) -> &'static str {
let known = self
.live_champ_select()
.is_some_and(|pick| pick.anvil_champions.is_some());
if known {
"Autres champions"
} else {
"Tous les champions"
}
}
/// « Autres champions »: a header that folds the section, and open, its search and its
/// cards. Folded, no card is built and the grid is not even drawn. They are the champions
/// without an anvil only when the client gave the list: else they are all of them. The
/// grid is as tall as all its cards, and the champ select's scrolling moves it: it builds
/// only the rows that scrolling has in view of the window (`window_width` gives the cards'
/// size).
pub(in crate::page) fn others_area(
&self,
window_width: Pixels,
cx: &mut Context<Page>,
) -> impl IntoElement {
let theme = cx.theme();
let (muted, border, ring, hover, hover_foreground) = (
theme.muted_foreground,
theme.border,
theme.ring,
theme.accent,
theme.accent_foreground,
);
let title = self.others_title();
let open = self.others_open;
let chevron = if open {
IconName::ChevronDown
} else {
IconName::ChevronRight
};
div()
.v_flex()
.w_full()
.gap_3()
.pr(Scrollbar::width())
.child(
BaseButton::new("others-toggle")
.track_focus(&self.others_focus)
.w_full()
.justify_start()
.gap_2()
.px_1()
.py_2()
.border_t_1()
.border_b_1()
.border_color(border)
.focus_visible(|style| style.border_color(ring))
.hover(|style| style.bg(hover).text_color(hover_foreground))
.text_lg()
.accessibility_label(title)
.debug_selector(|| "others-toggle".into())
.child(Icon::new(chevron).small().text_color(muted))
.child(heading(cx).child(title))
.on_click(cx.listener(|this, _, _, cx| this.toggle_others(cx))),
)
.when(open, |section| {
section
.child(
div().h_flex().child(
Input::new(&self.others_search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
),
)
.child(self.others_cards(window_width, cx))
.children(self.lift_layer(&self.others_grid, cx))
})
}
/// The grid of « Autres champions », and where it starts in the page's scrolling, which it
/// reads to know its rows in view: recorded after each layout, and the grid is drawn again
/// when that place changes.
fn others_cards(&self, window_width: Pixels, cx: &mut Context<Page>) -> impl IntoElement {
let grid = self.others_grid.clone();
// Cached, as the home's grid: hovering elsewhere does not draw its cards again. Its size
// comes from this style, all its rows tall (an empty one says so, in its own height).
let shown = match grid.read(cx).rows_height(window_width) {
Some(height) => grid
.clone()
.cached(StyleRefinement::default().w_full().h(height))
.into_any_element(),
None => grid.clone().into_any_element(),
};
let (paging, grid) = (self.paging.clone(), grid.downgrade());
div()
.w_full()
.on_children_prepainted(move |bounds, window, cx| {
let Some(bounds) = bounds.first() else { return };
let (scroll, top) = (&paging.scroll, &paging.top);
let now = bounds.origin.y - scroll.bounds().origin.y - scroll.offset().y;
if top.get().is_none_or(|was| (was - now).abs() > px(0.5)) {
top.set(Some(now));
// The grid built its rows from the former place: it is drawn again, once this
// draw is over, as a change noted during a draw dirties nothing for the next.
let grid = grid.clone();
window.defer(cx, move |_, cx| {
grid.update(cx, |_, cx| cx.notify()).ok();
});
}
})
.child(shown)
}
}
+191
View File
@@ -0,0 +1,191 @@
use super::{PAGE_PADDING, Page, Tab, shown};
use crate::stage;
use crate::text::{CLIENT_ABSENT, official_differs, sync_line};
#[cfg(test)]
use arena_tracker_core::{ChampionSort, StateFilter};
use arena_tracker_core::{ProgressCheck, UpdateProblem};
use gpui_kit::component::alert::Alert;
use gpui_kit::component::select::Select;
use gpui_kit::component::{ActiveTheme as _, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
impl Page {
/// One line each, the most important first; the stored data stays visible under all.
fn status_alerts(&self) -> Vec<AnyElement> {
let mut banners = Vec::new();
if let Some(problem) = &self.status.problem {
let message = problem.message();
banners.push(match problem {
UpdateProblem::MatchPending
| UpdateProblem::RateLimited
| UpdateProblem::NoAccount => Alert::warning("problem", message),
_ => Alert::error("problem", message),
});
}
if let Some(ProgressCheck::Differs { app, official }) = self.official() {
banners.push(Alert::warning(
"official",
official_differs(*app, *official),
));
}
if !self.pending_round && !self.status.client_running {
banners.push(Alert::info("client", CLIENT_ABSENT));
}
if let Some(notice) = &self.notice {
banners.push(Alert::warning("notice", notice.clone()));
}
if let Some(error) = self.error() {
banners.push(Alert::error("stats", error.clone()));
}
banners
.into_iter()
.map(|alert| alert.small().into_any_element())
.collect()
}
/// The veil's opacity over the screen shown, 0 at rest.
pub(in crate::page) fn veil(&self, cx: &App) -> f32 {
self.fade
.as_ref()
.map_or(0., |fade| fade.veil(cx.background_executor().now()))
}
#[cfg(test)]
pub(crate) fn champion_sort(&self) -> Option<ChampionSort> {
self.champion_sort
}
#[cfg(test)]
pub(crate) fn home_filter(&self) -> StateFilter {
self.home_filter
}
}
impl Render for Page {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
// A card lifting or settling asks for the next frame, and none once they are still.
let now = cx.background_executor().now();
if let Some(animation) = self.playback.animation {
if animation.finished(now) || cx.reduce_motion() || !self.challenge_visible(window) {
self.end_match(cx);
} else {
// The comet lands: the splash of the champion just validé settles in, when it is
// the banner's, the last champion validé. A validation older than the banner's
// (its Match arrived late) leaves the banner as a reload shows it.
if animation.has_comet()
&& animation.since_landing(now) >= 0.
&& self.playback.previous_banner.take().is_some()
{
let last_validated = (self.home_statistics())
.and_then(|s| s.challenge.as_ref())
.and_then(|c| c.completion_order.last().copied());
let splash = self.banner.splash.clone();
self.banner_art.update(cx, |art, cx| {
if last_validated == Some(animation.champion_id) {
art.reveal(splash, cx);
} else {
art.set_target(splash, cx);
}
});
}
window.request_animation_frame();
}
}
self.lifts.tidy(now);
if self.lifts.animating(now) {
window.request_animation_frame();
}
if self.stage_moving(cx) {
self.next_stage_frame(window, cx);
}
let sweep = (self.entry)
.and_then(|entry| entry.sweep(now))
.map(|progress| stage::sweep(progress, window.viewport_size(), cx));
let muted = cx.theme().muted_foreground;
let busy = self.busy();
let status_line = sync_line(busy, self.progress, self.crashed, self.stored);
div()
// The pointer takes over from the keyboard: the card it lifted goes down.
.on_mouse_move(cx.listener(|page, _: &MouseMoveEvent, _, cx| {
if let Some(grid) = page.lifted_by_keyboard.take().and_then(|g| g.upgrade()) {
grid.update(cx, |grid, cx| grid.put_down(cx));
}
}))
.relative()
.v_flex()
.size_full()
.gap_3()
.p(px(PAGE_PADDING))
.when(shown("header"), |page| {
page.child(
// The selectors give way first (down to their minimum width), then the status
// wraps onto a second line: nothing is ever clipped.
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.child(
div()
.h_flex()
.items_center()
.gap_3()
.min_w_0()
.child(self.navigation(cx))
.child(
Select::new(&self.account_select)
.id("account")
.placeholder("Aucun Compte")
// The champ select is about the signed-in Account.
.disabled(self.in_champ_select())
.w(px(260.))
.min_w(px(150.)),
)
.children(self.stale().then(|| {
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child("Non mis à jour")
})),
)
.child(
div().h_flex().items_center().gap_3().flex_shrink_0().child(
div()
.text_sm()
.whitespace_nowrap()
.text_color(muted)
.child(status_line),
),
),
)
})
.when(shown("banners"), |page| {
page.child(div().v_flex().gap_1().children(self.status_alerts()))
})
.child(
// The screen under the header, which does not move: the veil of the transition
// covers it alone.
div()
.relative()
.v_flex()
.flex_1()
.min_h_0()
.gap_3()
.children(match self.shown_tab {
Tab::Challenge => self.home_content(window, cx),
Tab::Statistics => self.statistics_content(cx),
})
.when(self.fade.is_some(), |screen| {
let veil = cx.theme().background.opacity(self.veil(cx));
screen.child(div().absolute().inset_0().bg(veil))
}),
)
// The band of light of a champ select's entry, over the whole window.
.children(sweep)
}
}
+75
View File
@@ -0,0 +1,75 @@
//! What the page displays: the Account, whether its data is stale, the official count, the
//! error to show and the scope its statistics are computed for.
use crate::page::{Page, Tab};
use arena_tracker_core::{Account, ProgressCheck, Scope, SeasonScope};
impl Page {
/// The Account shown: the pinned one, else the one being updated.
pub(in crate::page) fn viewed(&self) -> Option<&Account> {
self.pinned
.as_ref()
.and_then(|puuid| self.accounts.iter().find(|a| a.puuid == *puuid))
.or(self.status.updating.as_ref())
.or(self.last_active.as_ref())
.or(self.accounts.first())
}
/// The Account whose data the page shows: during a champ select the one signed in to the
/// client, whatever the pinned or followed one is, else `viewed`.
pub(in crate::page) fn displayed(&self) -> Option<&Account> {
if self.in_champ_select() {
let puuid = self.champ_select_account.as_deref()?;
return self.accounts.iter().find(|a| a.puuid == puuid);
}
self.viewed()
}
/// Whether the Account shown is not the one being updated (or none is), so only stored
/// data is shown. Unknown until the follower's first round has reported.
pub(in crate::page) fn stale(&self) -> bool {
!self.pending_round
&& self.displayed().is_some_and(|viewed| {
self.status
.updating
.as_ref()
.is_none_or(|updating| updating.puuid != viewed.puuid)
})
}
/// The game's own count, only meaningful for the Account being updated in the current Season,
/// whether the page shows it as the home's Challenge or as the selected Season.
pub(in crate::page) fn official(&self) -> Option<&ProgressCheck> {
let updated = matches!((self.displayed(), &self.status.updating), (Some(v), Some(u)) if v.puuid == u.puuid);
let shown = match (self.shown_tab, &self.season) {
(Tab::Challenge, _) => self.home_season.as_deref(),
(Tab::Statistics, SeasonScope::Season(season)) => Some(season.as_str()),
(Tab::Statistics, SeasonScope::AllSeasons) => None,
};
let current = shown.is_some() && shown == self.current_season.as_deref();
(updated && current).then_some(&self.status.official_progress)
}
/// The tab's own statistics error: the home may have computed its own.
pub(in crate::page) fn error(&self) -> Option<&String> {
match (self.shown_tab, &self.home_scope) {
(Tab::Challenge, Some(_)) => self.home_error.as_ref(),
_ => self.stats_error.as_ref(),
}
}
pub(in crate::page) fn statistics_scope(&self) -> Scope {
if self.in_champ_select()
&& let Some(season) = &self.current_season
{
return Scope {
season: SeasonScope::Season(season.clone()),
format: None,
};
}
Scope {
season: self.season.clone(),
format: self.format,
}
}
}
+286
View File
@@ -0,0 +1,286 @@
//! The « Défi » tab, the home: the Challenge of one Season, and its champions.
use arena_tracker_core::{SeasonScope, StateFilter, Statistics};
use gpui_kit::component::input::Input;
use gpui_kit::component::select::Select;
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
use gpui_kit::*;
mod banner;
mod content;
mod data;
pub(in crate::page) use content::{BannerContent, Line};
use super::{Page, shown};
use crate::card_grid::MAX_WIDTH;
use crate::theme::heading;
/// The filters on offer, whatever the Season.
pub(in crate::page) const FILTERS: [(&str, StateFilter); 3] = [
("Tous", StateFilter::All),
("Restants", StateFilter::Remaining),
("Validés", StateFilter::Completed),
];
const NO_SEASON: &str = "Aucune Saison en cours";
/// Why the home has no statistics to browse yet. The home and the champ select say it the same
/// way (`label`).
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(in crate::page) enum StatsNotice {
/// There is no Season to read: the banner already says so.
NoSeason,
/// No Account to read.
NoAccount,
/// The statistics job has not returned yet.
Loading,
/// The job failed: the banner already says so.
Error,
}
impl StatsNotice {
/// The French text, `error` being the statistics' error for `Error`.
pub(in crate::page) fn label(self, error: Option<&str>) -> SharedString {
match self {
Self::NoSeason => NO_SEASON.into(),
Self::NoAccount => "Compte indisponible".into(),
Self::Loading => "Chargement des statistiques…".into(),
Self::Error => error.unwrap_or_default().to_string().into(),
}
}
/// Whether something else on the page already says it: the notice stays silent then.
pub(in crate::page) fn said_elsewhere(self) -> bool {
matches!(self, Self::NoSeason | Self::Error)
}
}
/// A sober line in muted text, for what stands in place of the cards.
pub(in crate::page) fn notice_line(
selector: &'static str,
text: SharedString,
muted: Hsla,
) -> AnyElement {
div()
.text_sm()
.text_color(muted)
.debug_selector(move || selector.into())
.child(text)
.into_any_element()
}
/// The small bordered count beside a heading.
pub(in crate::page) fn count_badge(
count: SharedString,
muted: Hsla,
border: Hsla,
) -> impl IntoElement {
div()
.px(px(7.))
.py(px(2.))
.border_1()
.border_color(border)
.rounded(px(6.))
.text_xs()
.text_color(muted)
.child(count)
}
impl Page {
/// Whether one Season is selected, rather than all of them: only a Season has a Challenge.
pub(in crate::page) fn in_season(&self) -> bool {
matches!(self.season, SeasonScope::Season(_))
}
/// What the home reads: its own statistics when its scope differs, else the Statistics tab's.
pub(in crate::page) fn home_statistics(&self) -> Option<&Statistics> {
self.home_season.as_ref()?;
match self.home_scope {
Some(_) => self.home_stats.as_ref(),
None => self.stats.as_ref(),
}
}
/// Why the home has no statistics to show yet, if it has none: the same for the Défi tab
/// and the champ select. Cheap enough to ask at each render.
pub(in crate::page) fn stats_notice(&self) -> Option<StatsNotice> {
if self.error().is_some() {
return Some(StatsNotice::Error);
}
if self.home_statistics().is_some() {
return None;
}
if self.home_season.is_none() {
return Some(StatsNotice::NoSeason);
}
// During a champ select the Account is the one signed in to the client, known by the
// follower's status; else it is the one viewed.
let no_account = if self.in_champ_select() {
self.status.updating.is_none()
} else {
self.viewed().is_none()
};
Some(if no_account {
StatsNotice::NoAccount
} else {
StatsNotice::Loading
})
}
/// Under the status messages: the banner, then the heading with the filters and
/// search, and the cards. It holds no chart (#71): the cached charts row only belongs to the
/// Statistics tab. Everything is one centred column, as wide as the mockup's.
pub(in crate::page) fn home_content(
&self,
window: &mut Window,
cx: &mut Context<Page>,
) -> Vec<AnyElement> {
let mut column = div()
.v_flex()
.flex_1()
.min_h_0()
.w_full()
.max_w(px(MAX_WIDTH))
.mx_auto()
.gap_3();
if shown("banner") {
column = column.child(self.banner(window, cx));
}
if self.in_champ_select() {
// The champ select takes the place of the grid, its filters and its search: the
// column is taller than the window, and scrolls then, « Autres champions » with it
// (its grid builds only the rows in view).
if shown("anvil") {
column = column.child(self.anvil_area(window.viewport_size().width, cx));
}
// With the statistics missing there is nothing to browse: the notice stands alone.
if shown("others") && self.stats_notice().is_none() {
column = column.child(self.others_area(window.viewport_size().width, cx));
}
// One scrolling for all of it, with its scrollbar in the lane the sections leave.
return vec![
div()
.relative()
.flex_1()
.min_h_0()
.w_full()
.max_w(px(MAX_WIDTH))
.mx_auto()
.child(
column
.id("champ-select")
.size_full()
.overflow_y_scroll()
.track_scroll(&self.paging.scroll),
)
.child(self.champ_select_scrollbar.clone())
.into_any_element(),
];
}
if self.home_season.is_some() {
match self.stats_notice() {
None => {
if shown("home-tools") {
column = column.child(self.home_heading(cx));
}
if shown("cards") {
// Cached: only a change to the cards, the filter, the search or a
// scroll over them draws the grid again; the card hovered is drawn
// lifted over it. Its size comes from this style.
column = column
.child(self.home_grid.clone().cached(
StyleRefinement::default().w_full().flex_1().min_h(px(240.)),
))
.children(self.lift_layer(&self.home_grid, cx));
}
}
// Without statistics the heading would count « 0 » and the grid would say no
// champion matches: say why there are no cards instead (the banner has the
// error, the header the missing Season).
Some(notice) if notice.said_elsewhere() => {}
Some(notice) => {
let muted = cx.theme().muted_foreground;
column = column.child(notice_line(
"home-notice",
notice.label(self.error().map(String::as_str)),
muted,
));
}
}
}
// In a low window the banner leaves the grid less than its least height: the column
// scrolls then, as the champ select's does.
vec![column.id("home").overflow_y_scroll().into_any_element()]
}
/// The sort selector: a sort icon and the choice, « Maîtrise » or « A–Z ». It stays on the
/// home and during a champ select, and applies to every section of cards.
pub(in crate::page) fn sort_selector(&self, cx: &App) -> impl IntoElement {
let muted = cx.theme().muted_foreground;
div()
.h_flex()
.items_center()
.gap_1()
.debug_selector(|| "sort".into())
.child(Icon::new(IconName::SortAscending).small().text_color(muted))
.child(
Select::new(&self.sort_select)
.id("sort")
.accessibility_label("Trier les cartes")
.w(px(140.))
.min_w(px(110.)),
)
}
/// « Mes champions » with how many cards are shown, and on the right the search, the filters
/// and the sort, as the mockup's `.tools`.
fn home_heading(&self, cx: &mut Context<Page>) -> impl IntoElement {
let theme = cx.theme();
let (muted, border) = (theme.muted_foreground, theme.border);
let selected = FILTERS.iter().position(|(_, f)| *f == self.home_filter);
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_x_3()
.gap_y_2()
.debug_selector(|| "home-tools".into())
.child(
div()
.h_flex()
.items_center()
.gap(px(6.))
.child(heading(cx).text_xl().child("Mes champions"))
.child(count_badge(self.home_shown_count.clone(), muted, border)),
)
.child(
div()
.h_flex()
.items_center()
.gap_3()
.child(
Input::new(&self.home_search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
)
.child(
TabBar::new("home-filter")
.pill()
.selected_index(selected.unwrap_or(0))
.children(FILTERS.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
if let Some((_, filter)) = FILTERS.get(*ix) {
this.home_filter = *filter;
this.home_filtered(cx);
cx.notify();
}
})),
)
.child(self.sort_selector(cx)),
)
}
}
+402
View File
@@ -0,0 +1,402 @@
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{BannerContent, Line, NO_SEASON, Page};
use crate::banner_art::BannerArt;
use crate::motion::{COUNTER_ROLL, ease_out};
use crate::ring::{self, Tick};
use crate::theme::{banner_band, gold_ink, heading};
use std::rc::Rc;
impl Page {
/// The banner, on the home and during a champ select: the ring, then the Season, the
/// Challenge's count and its two lines, over the splash of the last champion Completed. In a
/// narrow window the ring goes above the text, and the splash covers the whole banner under a
/// stronger fade.
pub(super) fn banner(&self, window: &mut Window, cx: &mut Context<Page>) -> impl IntoElement {
let layout = BannerLayout::of(window.viewport_size().width);
let now = cx.background_executor().now();
let animation = self.playback.animation;
// Seconds since the comet landed, or since the start without one.
let landed = animation.map(|a| a.since_landing(now));
// The banner says what it said before the Match until the comet lands.
let text = self
.playback
.previous_banner
.as_ref()
.filter(|_| landed.is_some_and(|t| t < 0.))
.unwrap_or(&self.banner);
// The count of champions validés rolls in once the comet lands: 0 to 1.
let roll = animation
.filter(|a| a.has_comet())
.and(landed)
.filter(|t| (0. ..COUNTER_ROLL).contains(t))
.map(|t| t / COUNTER_ROLL);
let theme = cx.theme();
let (band, muted, foreground, ink) = (
banner_band(theme),
theme.muted_foreground,
theme.foreground,
gold_ink(theme),
);
let name = |line: &Line| {
StyledText::new(line.text.clone()).with_highlights([(
line.bold.clone(),
HighlightStyle {
color: Some(foreground),
font_weight: Some(FontWeight::SEMIBOLD),
..Default::default()
},
)])
};
let copy = div()
.v_flex()
.min_w_0()
.when(!layout.narrow, |copy| copy.max_w(relative(0.46)))
.children((!text.season.is_empty()).then(|| {
div()
.text_xs()
.font_weight(FontWeight::SEMIBOLD)
.text_color(ink)
.child(text.season.clone())
}))
.children(self.home_season.is_none().then(|| {
div()
.text_sm()
.text_color(muted)
.debug_selector(|| "no-season".into())
.child(NO_SEASON)
.into_any_element()
}))
.children((!text.title.text.is_empty()).then(|| {
div()
.v_flex()
.gap(px(3.))
.child({
let title = StyledText::new(text.title.text.clone()).with_highlights([(
text.title.bold.clone(),
HighlightStyle {
// Rolling, the count is drawn over its place.
color: Some(ink.opacity(if roll.is_some() { 0. } else { 1. })),
..Default::default()
},
)]);
let rolling = roll.map(|t| {
rolling_count(title.layout().clone(), text.title.clone(), ink, t)
});
heading(cx)
.relative()
.mt(px(8.))
.mb(px(7.))
// The champ select's title comes in, rising, at its entry.
.when_some(self.title_pose(cx), |title, (opacity, below)| {
title.opacity(opacity).relative().top(px(below))
})
.text_size(px(layout.title))
.line_height(relative(1.12))
.debug_selector(|| "banner-title".into())
.child(title)
.children(rolling)
})
.child(div().text_sm().text_color(muted).child(name(&text.detail)))
.children(text.last_match.as_ref().map(|line| {
div()
// The new line fades in once the comet lands; the old one stays.
.opacity(
(landed.filter(|t| *t >= 0.))
.map_or(1., |t| (t / COUNTER_ROLL).min(1.)),
)
.text_sm()
.text_color(muted)
.child(name(line))
}))
.into_any_element()
}));
div()
.relative()
.flex()
.w_full()
.flex_shrink_0()
.min_h(px(layout.min_height))
.rounded(px(RADIUS))
.overflow_hidden()
.bg(band)
.map(|banner| {
if layout.narrow {
banner.flex_col().items_start()
} else {
banner.flex_row().items_center()
}
})
.gap(px(layout.gap))
.px(px(layout.padding))
.py(px(24.))
.debug_selector(|| "banner".into())
.child(self.banner_art.clone())
.child(
// Cached: only a change of its ticks or of the lit one draws it again.
div()
.relative()
.size(px(layout.ring))
.flex_none()
.child(
self.ring
.clone()
.cached(StyleRefinement::default().size_full()),
)
.children(
animation.map(|a| self.ring.read(cx).match_layer(a, a.elapsed(now), cx)),
),
)
.child(copy)
}
}
/// The banner's rounded corners.
const RADIUS: f32 = 16.;
/// The banner's measures, from the window width as the reference page's `clamp` and `vw` give
/// them.
#[derive(Clone, Copy, Debug, PartialEq)]
struct BannerLayout {
/// At most 680 px: the ring goes above the text.
narrow: bool,
min_height: f32,
gap: f32,
padding: f32,
ring: f32,
title: f32,
}
impl BannerLayout {
fn of(window_width: Pixels) -> BannerLayout {
let vw = window_width.as_f32() / 100.;
BannerLayout {
narrow: window_width.as_f32() <= 680.,
min_height: (26. * vw).clamp(220., 310.),
gap: (3. * vw).clamp(16., 40.),
padding: (3. * vw).clamp(16., 36.),
ring: (16. * vw).clamp(120., 200.),
title: (2.8 * vw).clamp(22., 34.),
}
}
}
/// The count at the start of `title`, `t` (0 to 1) into its roll: it rises from 10 px below its
/// place and fades in, painted over the title laid out with it transparent (`layout`). The text
/// style is the title's own, which the element inherits.
fn rolling_count(layout: TextLayout, title: Line, ink: Hsla, t: f32) -> impl IntoElement {
canvas(
|_, _, _| {},
move |_, _, window, cx| {
let Some(origin) = layout.position_for_index(title.bold.start) else {
return;
};
let style = window.text_style();
let font_size = style.font_size.to_pixels(window.rem_size());
let count = title.text[title.bold.clone()].to_string();
let run = TextRun {
len: count.len(),
font: style.font(),
color: ink.opacity(t),
background_color: None,
underline: None,
strikethrough: None,
};
let line = window
.text_system()
.shape_line(count.into(), font_size, &[run], None);
let rise = px(10. * (1. - ease_out(t)));
let _ = line.paint(
origin + point(px(0.), rise),
layout.line_height(),
TextAlign::Left,
None,
window,
cx,
);
},
)
.absolute()
.inset_0()
}
/// The splash, framed on the champion (#83), in the banner's illustration area: its right 72 %,
/// or all of it in a narrow window. It fades into the band on the text's side.
impl Render for BannerArt {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let Some(splash) = self.target.clone() else {
self.release(window, cx);
return div().absolute().into_any_element();
};
let layout = BannerLayout::of(window.viewport_size().width);
let band = banner_band(cx.theme());
let art = cx.entity();
let corners = if layout.narrow {
Corners::all(px(RADIUS))
} else {
Corners {
top_right: px(RADIUS),
bottom_right: px(RADIUS),
..Corners::default()
}
};
let reveal = self.reveal_frame(window, cx);
let layer = |previous: bool| {
let art = art.clone();
let splash = splash.clone();
canvas(
|_, _, _| {},
move |bounds, _, window, cx| {
// Scrolled entirely out of the column (a low window): nothing to show, so nothing
// decoded nor held, and it comes back with the banner.
let visible = bounds.intersect(&window.content_mask().bounds);
if visible.size.width <= Pixels::ZERO || visible.size.height <= Pixels::ZERO {
art.update(cx, |art, cx| art.release(window, cx));
return;
}
let image = if previous {
art.read(cx).previous_image()
} else {
art.update(cx, |art, cx| art.image(&splash, cx))
};
let Some((image, focus)) = image else {
return;
};
let frame =
focus.banner_frame(bounds.size.width.as_f32(), bounds.size.height.as_f32());
let zoom = if previous { 1. } else { reveal.zoom };
let frame = Bounds {
origin: bounds.origin + point(px(frame.left * zoom), px(frame.top * zoom))
- point(bounds.size.width, bounds.size.height) * ((zoom - 1.) / 2.),
size: size(px(frame.width * zoom), px(frame.height * zoom)),
};
let _ = window.paint_image(bounds, frame, corners, image, 0, false);
},
)
.size_full()
};
let area = div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.debug_selector(|| "banner-art".into())
.child(layer(false).opacity(reveal.opacity))
.children(self.previous_opacity(window, cx).map(|opacity| {
div()
.absolute()
.inset_0()
.opacity(opacity)
.child(layer(true))
}));
// A layer of the band over the splash, from `from` to `to` opacity in the gradient's
// direction (`angle`: 0 to the top, 90 to the right, 180 to the bottom).
let fade = |angle: f32, (from, at): (f32, f32), to: f32| {
div().absolute().bg(linear_gradient(
angle,
linear_color_stop(band.opacity(from), at),
linear_color_stop(band.opacity(to), 1.),
))
};
if layout.narrow {
// From the bottom: the band, then a fade to the splash at the top.
area.left_0()
.child(
fade(180., (0., 0.), 0.4)
.left_0()
.right_0()
.top_0()
.h(relative(0.25)),
)
.child(
fade(180., (0.4, 0.), 1.)
.left_0()
.right_0()
.top(relative(0.25))
.h(relative(0.35)),
)
.child(
fade(180., (1., 0.), 1.)
.left_0()
.right_0()
.bottom_0()
.h(relative(0.4))
.rounded_b(px(RADIUS)),
)
.into_any_element()
} else {
// The banner's fade, solid to its 30 %, 72 % at its 46 %, none from its 74 %, in the
// area that starts at its 28 %; and a lighter one from the bottom.
area.w(relative(0.72))
.child(
fade(90., (1., 0.11), 0.72)
.top_0()
.bottom_0()
.left_0()
.w(relative(0.25)),
)
.child(
fade(90., (0.72, 0.), 0.)
.top_0()
.bottom_0()
.left(relative(0.25))
.w(relative(0.39)),
)
.child(
fade(0., (0.55, 0.), 0.)
.left_0()
.right_0()
.bottom_0()
.h(relative(0.45))
.rounded_br(px(RADIUS)),
)
.into_any_element()
}
}
}
impl Page {
/// The banner's text and the ring's ticks, for when the home statistics change. Neither
/// follows the Format, the filter, the search nor the sort.
pub(in crate::page) fn prepare_banner(&mut self, cx: &mut Context<Self>) {
let stats = self.home_statistics();
let champ_select = self.in_champ_select();
let splashes = stats
.filter(|_| champ_select)
.into_iter()
.flat_map(|s| &s.rows)
.filter_map(|row| Some((row.champion.id, Rc::new(row.splash.clone()?))))
.collect();
let ticks: Rc<[Tick]> = stats
.and_then(|s| {
Some(ring::ticks(
&s.rows,
&s.challenge.as_ref()?.completion_order,
))
})
.unwrap_or_default()
.into();
if !champ_select {
self.banner = BannerContent::new(self.home_season.as_ref(), stats);
if !self.playback.active() {
self.banner_art
.update(cx, |art, cx| art.set_target(self.banner.splash.clone(), cx));
}
}
self.champ_select_splashes = splashes;
self.ring.update(cx, |ring, cx| ring.set_ticks(ticks, cx));
}
}
impl Page {
pub(in crate::page) fn select_art(&self, hovered: Option<u32>, cx: &mut Context<Self>) {
let splash = match hovered {
Some(id) => self.champ_select_splashes.get(&id),
None => self.banner.splash.as_ref(),
};
self.banner_art
.update(cx, |art, cx| art.set_target(splash.cloned(), cx));
}
}
+159
View File
@@ -0,0 +1,159 @@
use std::ops::Range;
use std::rc::Rc;
use arena_tracker_core::{MatchOutcome, Splash, Statistics};
use gpui_kit::SharedString;
use crate::page::champ_select::UNKNOWN_ANVIL;
use crate::text::{attempt_ordinal, ordinal, short_date};
/// A line of the banner, the champion's name (or the count) set apart.
#[derive(Clone, Debug, Default, PartialEq)]
pub(in crate::page) struct Line {
pub(in crate::page) text: SharedString,
pub(in crate::page) bold: Range<usize>,
}
impl Line {
/// `before`, then `bold`, then `after`.
fn new(before: &str, bold: &str, after: &str) -> Line {
Line {
text: format!("{before}{bold}{after}").into(),
bold: before.len()..before.len() + bold.len(),
}
}
fn plain(text: &str) -> Line {
Line {
text: text.to_owned().into(),
bold: 0..0,
}
}
}
/// The Season as both banners' overline writes it: upper case, and a default split Season, named
/// « Saison 2 2026 » in the stored data, as « SAISON 2 · 2026 ».
fn overline(season: &SharedString) -> String {
let season = season.to_uppercase();
if let Some((split, year)) = season.rsplit_once(' ')
&& year.len() == 4
&& year.bytes().all(|b| b.is_ascii_digit())
&& split
.strip_prefix("SAISON ")
.is_some_and(|n| n.parse::<u32>().is_ok())
{
return format!("{split} · {year}");
}
season
}
/// What the banner shows, prepared when the home statistics change: it follows the home's Season,
/// never the Format, the filter nor the search.
#[derive(Clone, Debug, Default, PartialEq)]
pub(in crate::page) struct BannerContent {
/// The Season, as the overline writes it; empty without a Season.
pub(in crate::page) season: SharedString,
/// The home counter or the champ select title.
pub(in crate::page) title: Line,
/// Last completion at home, Anvil availability during champ select.
pub(in crate::page) detail: Line,
/// « Dernière Partie : … », from the stored Matches; none without a Match in the Season.
pub(in crate::page) last_match: Option<Line>,
/// The illustration when no card is hovered.
pub(in crate::page) splash: Option<Rc<Splash>>,
}
impl BannerContent {
pub(in crate::page) fn champ_select(
season: Option<&SharedString>,
stats: Option<&Statistics>,
known: bool,
count: usize,
splash: Option<Rc<Splash>>,
) -> Self {
let mut season = season.map(overline).unwrap_or_default();
if let Some(challenge) = stats.and_then(|s| s.challenge.as_ref()) {
use std::fmt::Write;
if !season.is_empty() {
season.push_str(" · ");
}
write!(
season,
"{} / {} validés",
challenge.completed, challenge.total
)
.unwrap();
}
let detail = if !known {
Line::plain(UNKNOWN_ANVIL)
} else if stats.is_some() {
// 0 and 1 take the singular in French.
let available = if count > 1 {
" à valider et disponibles"
} else {
" à valider et disponible"
};
Line::new("Champions de l'Enclume · ", &count.to_string(), available)
} else {
Line::default()
};
Self {
season: season.into(),
title: Line::plain("Sélection des champions"),
detail,
last_match: None,
splash,
}
}
pub(in crate::page) fn new(
season: Option<&SharedString>,
stats: Option<&Statistics>,
) -> BannerContent {
let season = season.map_or_else(SharedString::default, |name| overline(name).into());
let Some((stats, challenge)) = stats.and_then(|s| Some((s, s.challenge.as_ref()?))) else {
return BannerContent {
season,
..BannerContent::default()
};
};
let row = |id: u32| stats.rows.iter().find(|row| row.champion.id == id);
let last = challenge.completion_order.last().and_then(|&id| row(id));
let detail = match last {
Some(row) => {
let day = row
.challenge
.and_then(|c| c.completed_on)
.map(|day| format!(", le {}", short_date(day)))
.unwrap_or_default();
Line::new("Dernier champion validé : ", &row.champion.name, &day)
}
None => Line::plain("Aucun champion validé pour l’instant."),
};
let last_match = challenge.last_match.and_then(|m| {
let name = &row(m.champion_id)?.champion.name;
let detail = match m.outcome {
MatchOutcome::Attempt(n) => format!(" · {} Tentative", attempt_ordinal(n)),
MatchOutcome::Completed(1) => " · validé du premier coup".into(),
MatchOutcome::Completed(n) => format!(" · validé en {n} Tentatives"),
MatchOutcome::AfterCompletion => String::new(),
};
Some(Line::new(
"Dernière Partie : ",
name,
&format!(", {}{detail}", ordinal(m.placement)),
))
});
let count = challenge.completed.to_string();
BannerContent {
season,
title: Line {
text: format!("{count} / {} champions validés", challenge.total).into(),
bold: 0..count.len(),
},
detail,
last_match,
splash: last.and_then(|row| row.splash.clone()).map(Rc::new),
}
}
}
+54
View File
@@ -0,0 +1,54 @@
//! The home's own statistics: the scope it computes them for, and what was computed.
use arena_tracker_core::{Scope, SeasonScope, Statistics};
use crate::page::Page;
impl Page {
/// The Season of the home's Challenge, and the scope to compute for it when the Statistics
/// tab's does not already cover it. The Format never applies to the home.
pub(in crate::page) fn settle_home_scope(&mut self) {
let season = match &self.season {
SeasonScope::Season(name) => Some(name),
// A Challenge belongs to one Season: the current one stands in.
SeasonScope::AllSeasons => self.current_season.as_ref(),
};
self.home_season = season.map(|name| name.clone().into());
let home = season.map(|name| Scope {
season: SeasonScope::Season(name.clone()),
format: None,
});
self.home_scope = home.filter(|home| *home != self.statistics_scope());
}
/// Keeps what was computed for the home's own scope, if it had one, and for which Account.
pub(in crate::page) fn set_home_result(
&mut self,
home: Option<Box<Result<Statistics, String>>>,
) {
self.home_computed = home
.as_ref()
.and_then(|_| self.shown.clone().zip(self.home_scope.clone()));
(self.home_stats, self.home_error) = match home.map(|result| *result) {
Some(Ok(stats)) => (Some(stats), None),
Some(Err(error)) => (None, Some(error)),
None => (None, None),
};
}
pub(in crate::page) fn forget_home(&mut self) {
self.home_stats = None;
self.home_error = None;
self.home_computed = None;
}
/// Whether the home's own statistics were computed for the Account and scope it has now.
pub(in crate::page) fn home_is_current(&self) -> bool {
match (&self.shown, &self.home_scope, &self.home_computed) {
(Some(puuid), Some(scope), Some((computed_puuid, computed_scope))) => {
puuid == computed_puuid && scope == computed_scope
}
_ => false,
}
}
}
+157
View File
@@ -0,0 +1,157 @@
use super::Page;
use crate::card_grid::{CardGrid, CardHovered, PutDown};
use crate::card_lift::{Changes, Changing};
use crate::motion::MatchEnd;
use gpui_kit::*;
impl Page {
/// Lifts the card under the pointer or the keyboard in `grid`, and lights its ring's tick.
/// A wheel over the grid drops its cards at once.
pub(in crate::page) fn light_on_hover(
grid: &Entity<CardGrid>,
cx: &mut Context<Self>,
) -> [Subscription; 2] {
[
cx.subscribe(grid, |this, grid, hovered: &CardHovered, cx| {
let mut hovered = *hovered;
if grid.entity_id() == this.anvil_grid.entity_id() {
this.hover_waiting = None;
}
// A card of the hand still dealt is taken into account once in its place.
let now = cx.background_executor().now();
let waiting = hovered
.id
.is_some_and(|id| this.dealing(&grid, id, now, cx));
if waiting {
this.hover_waiting = Some(hovered);
hovered.id = None;
}
this.hovered(&grid, hovered, cx);
// The pointer moving puts the card the keyboard waits for down, as a lifted
// one: it is not lifted once in its place.
if waiting && hovered.by_keyboard {
this.lifted_by_keyboard = Some(grid.downgrade());
}
}),
cx.subscribe(grid, |this, grid, _: &PutDown, cx| {
this.lifts.drop_grid(grid.entity_id());
cx.notify();
}),
]
}
/// The card under the pointer or the keyboard in `grid` changed: it is lifted, and its tick
/// lit.
pub(in crate::page) fn hovered(
&mut self,
grid: &Entity<CardGrid>,
hovered: CardHovered,
cx: &mut Context<Self>,
) {
let CardHovered { id, by_keyboard } = hovered;
if by_keyboard && id.is_some() {
self.lifted_by_keyboard = Some(grid.downgrade());
} else if (self.lifted_by_keyboard.as_ref())
.is_some_and(|lifted| lifted.entity_id() == grid.entity_id())
{
self.lifted_by_keyboard = None;
}
self.lift(grid, id, cx);
self.light(grid.entity_id(), id, cx);
}
/// The card under the pointer or the keyboard in `grid` is now `id`: it rises over the grid,
/// and the one it replaces settles back. With the Windows « Show animations » setting off,
/// each is where it goes at once.
fn lift(&mut self, grid: &Entity<CardGrid>, id: Option<u32>, cx: &mut Context<Self>) {
// The hand leaving at the end of a champ select lifts nothing.
if self.leave.is_some() {
return;
}
let now = cx.background_executor().now();
let hand = grid.read(cx).is_hand();
self.lifts.hover(grid.entity_id(), id, hand, now);
if cx.reduce_motion() {
self.lifts.finish(now);
}
cx.notify();
}
/// The cards lifted over `grid`, if any: drawn after it, as long as it is.
pub(in crate::page) fn lift_layer(
&self,
grid: &Entity<CardGrid>,
cx: &App,
) -> Option<AnyElement> {
let now = cx.background_executor().now();
let id = grid.entity_id();
let mut lifted: Vec<_> = self.lifts.lifted(id, now).collect();
// The card of the champion changes in place; once the comet lands, « Validé » is the
// grid's own card.
let changing = (self.playback.animation)
.filter(|a| id == self.home_grid.entity_id() && a.end != MatchEnd::Nothing)
.and_then(|a| {
let since_landing = a.since_landing(now);
let before = self.playback.previous_card.clone()?;
if since_landing >= 0. && a.has_comet() {
return None;
}
if !lifted.iter().any(|card| card.id == before.id) {
lifted.insert(
0,
crate::card_lift::Lifted {
id: before.id,
progress: 0.,
},
);
}
Some(Changing {
before,
since_landing,
})
});
let veil = self.lifts.veil(id, now);
if lifted.is_empty() && veil == 0. {
return None;
}
// A lifted card of the hand an ally just took goes down as it greys all the same.
let hand = id == self.anvil_grid.entity_id();
let lowered = (self.taken.iter())
.filter(|taken| hand && lifted.iter().any(|lifted| lifted.id == taken.id))
.map(|taken| taken.lowered(now))
.collect();
let grid = grid.read(cx);
Some(crate::card_lift::layer(
grid.cards().clone(),
grid.drawn_cards().clone(),
grid.images().cloned(),
lifted,
changing.map_or(Changes::Taken(lowered), Changes::Match),
veil,
!cx.reduce_motion(),
))
}
/// The card under the pointer in `grid` changed to `id`. The tick follows the grid that lit
/// it: another grid saying that none of its cards is under the pointer (the pointer went from
/// it to this one, or it was folded) leaves the tick lit.
pub(in crate::page) fn light(
&mut self,
grid: EntityId,
id: Option<u32>,
cx: &mut Context<Self>,
) {
match id {
Some(_) => self.lit_by = Some(grid),
None if self.lit_by == Some(grid) => self.lit_by = None,
None => return,
}
if id.is_none() && grid == self.home_grid.entity_id() {
self.release_home(cx);
}
self.ring.update(cx, |ring, cx| ring.set_lit(id, cx));
if self.in_champ_select() {
self.select_art(id, cx);
}
}
}
+47
View File
@@ -0,0 +1,47 @@
use super::Page;
use crate::worker::spawn_refresh;
use gpui_kit::*;
impl Page {
/// The follower thread was just started.
pub(crate) fn following(&mut self, cx: &mut Context<Self>) {
self.pending_round = true;
cx.notify();
}
/// The page gives way to another screen (« Paramètres »): what it shows is given back, the
/// grids' and the table's portraits and the banner's splash, in memory and in the window's
/// atlas. They load again when it is drawn.
pub(crate) fn hidden(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.covered = true;
self.end_stage(cx);
self.lifts.clear();
self.end_fade(window, cx);
for grid in [&self.home_grid, &self.anvil_grid, &self.others_grid] {
grid.update(cx, |grid, cx| grid.release_images(window, cx));
}
self.banner_art
.update(cx, |art, cx| art.release(window, cx));
self.table
.update(cx, |table, cx| table.release_images(window, cx));
}
/// The page is back in front of « Paramètres ».
pub(crate) fn uncovered(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.covered = false;
self.play_waiting(window, cx);
self.start_entry(window, cx);
}
/// Starts a refresh, or queues one behind the refresh already running.
pub(crate) fn request_refresh(&mut self, cx: &mut Context<Self>) {
if self.refresh.request() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
cx.notify();
}
pub(crate) fn busy(&self) -> bool {
self.progress.is_some() || self.refresh.running() || self.pending_round
}
}
+102
View File
@@ -0,0 +1,102 @@
use super::{MatchPlayback, Page, Tab, WaitingMatch, home};
use crate::motion::MatchAnimation;
use arena_tracker_core::FollowedMatch;
use gpui_kit::*;
use std::rc::Rc;
impl Page {
/// Ends the end of a followed Match, waiting or playing: the banner shows its splash again,
/// and the champion's card leaves the grid if the filter or the search leave it out.
pub(in crate::page) fn end_match(&mut self, cx: &mut Context<Self>) {
// A Match the ring had no tick for left only its kept card.
let active = self.playback.active() || self.playback.kept_card.is_some();
self.playback = MatchPlayback::default();
if active {
self.banner_art.update(cx, |art, cx| {
art.set_target(self.banner.splash.clone(), cx);
});
self.refresh_home(cx);
}
}
/// The end of a followed Match: it plays once the statistics with it are shown and « Défi »
/// is in front. Of several meanwhile, the strongest plays, on its own champion; the most
/// recent of the strongest. With the Windows « Show animations » setting off, the end state
/// is all there is.
pub(in crate::page) fn queue_match(&mut self, event: FollowedMatch, cx: &mut Context<Self>) {
if cx.reduce_motion() {
return;
}
if self.playback.animation.is_some() {
self.end_match(cx);
}
if self.playback.waiting.waiting().is_none() {
self.playback.previous_banner = Some(if self.in_champ_select() {
home::BannerContent::new(self.home_season.as_ref(), self.home_statistics())
} else {
self.banner.clone()
});
}
self.playback.stats_pending = true;
let waiting = WaitingMatch {
end: event.end,
started_at_ms: event.started_at_ms,
champion_id: event.champion_id,
};
self.playback.waiting.request(waiting, false);
if self.playback.waiting.waiting() == Some(&waiting) {
let grid = self.home_grid.read(cx);
let card = (grid.cards().iter()).position(|c| c.id == event.champion_id);
self.playback.previous_card = card.map(|ix| Rc::new(grid.cards()[ix].clone()));
self.playback.kept_card = card
.filter(|ix| grid.shown().contains(ix))
.map(|_| event.champion_id);
}
}
/// Whether « Défi » is in front of the player. A window merely covered by another cannot
/// be told on Windows (GPUI's `WindowVisibility`): visible then means shown and not
/// minimised.
pub(in crate::page) fn challenge_visible(&self, window: &Window) -> bool {
window.is_visible()
&& !self.covered
&& self.tab == Tab::Challenge
&& self.shown_tab == Tab::Challenge
&& self.fade.is_none()
&& !self.in_champ_select()
}
/// « Défi » may have become visible: the animation waiting, if any, plays.
pub(in crate::page) fn play_waiting(&mut self, window: &Window, cx: &mut Context<Self>) {
if self.challenge_visible(window)
&& !cx.reduce_motion()
&& !self.playback.stats_pending
&& let Some(waiting) = self.playback.waiting.shown()
{
#[cfg(test)]
self.played.push(waiting.end);
self.playback.animation = self.ring.read(cx).animation(
waiting.champion_id,
waiting.end,
cx.background_executor().now(),
);
// Under the comet, the splash of the champion validé before.
let target = (self.playback.previous_banner.as_ref())
.filter(|_| {
self.playback
.animation
.is_some_and(MatchAnimation::has_comet)
})
.unwrap_or(&self.banner)
.splash
.clone();
self.banner_art
.update(cx, |art, cx| art.set_target(target, cx));
if self.playback.animation.is_none() {
// The ring has no tick for it: nothing plays.
self.end_match(cx);
}
cx.notify();
}
}
}
+27
View File
@@ -0,0 +1,27 @@
//! Measurement aid for issue #27: page parts hidden with `--features profile`.
/// Hides page parts for issue #27 measurements only with `--features profile`.
#[inline]
pub(in crate::page) fn shown(part: &str) -> bool {
#[cfg(feature = "profile")]
{
static HIDDEN: std::sync::OnceLock<Vec<String>> = std::sync::OnceLock::new();
!HIDDEN
.get_or_init(|| {
std::env::var("ARENA_TRACKER_HIDE")
.unwrap_or_default()
.split(',')
.map(str::trim)
.filter(|part| !part.is_empty())
.map(str::to_owned)
.collect()
})
.iter()
.any(|hidden| hidden == part)
}
#[cfg(not(feature = "profile"))]
{
let _ = part;
true
}
}
+21
View File
@@ -0,0 +1,21 @@
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::*;
/// The scrollbar of the champ select's scrolling, in the lane on the right of its column. It is
/// its own view for the scrollbar's fade: the frames it asks for are drawn for this view, not the
/// whole page.
pub(in crate::page) struct PageScrollbar {
pub(in crate::page) scroll: ScrollHandle,
}
impl Render for PageScrollbar {
fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
div()
.absolute()
.top_0()
.right_0()
.bottom_0()
.w(Scrollbar::width())
.child(Scrollbar::vertical(&self.scroll))
}
}
+297
View File
@@ -0,0 +1,297 @@
use super::scrollbar::PageScrollbar;
use super::statistics::ChartsRow;
use super::{
ALL_FORMATS, ALL_SEASONS, AccountItem, Launch, MatchPlayback, Page, SORTS, Tab, home, now_ms,
};
use crate::banner_art::BannerArt;
use crate::card_grid::{CardGrid, Paging};
use crate::card_lift::Lifts;
use crate::champion_table::ChampionTable;
use crate::motion::AnimationSetting;
use crate::ring::Ring;
use crate::worker::{Msg, RefreshGate};
use arena_tracker_core::{ChampionSearch, SeasonScope, StateFilter, Tracker};
use gpui_kit::base::async_util::{Receiver, Sender};
use gpui_kit::component::IndexPath;
use gpui_kit::component::input::{InputEvent, InputState};
use gpui_kit::component::select::{SelectEvent, SelectState};
use gpui_kit::*;
use std::cell::Cell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Instant;
impl Page {
pub(crate) fn new(
tracker: Arc<Tracker>,
launch: Launch,
rx: Receiver<Msg>,
tx: Sender<Msg>,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let Launch {
notice,
following,
champion_sort,
} = launch;
let seasons: Vec<SharedString> = tracker
.seasons()
.into_iter()
.rev()
.map(|s| s.name.into())
.chain([ALL_SEASONS.into()])
.collect();
let current_season = tracker.current_season(now_ms()).map(|s| s.name);
let season = current_season
.clone()
.map_or(SeasonScope::AllSeasons, SeasonScope::Season);
let selected = match &season {
SeasonScope::Season(name) => seasons.iter().position(|s| s.as_ref() == name.as_str()),
SeasonScope::AllSeasons => Some(seasons.len() - 1),
};
let account_select =
cx.new(|cx| SelectState::new(Vec::<AccountItem>::new(), None, window, cx));
let season_select =
cx.new(|cx| SelectState::new(seasons, selected.map(IndexPath::new), window, cx));
let format_names = vec![SharedString::from(ALL_FORMATS)];
let format_select = cx
.new(|cx| SelectState::new(format_names.clone(), Some(IndexPath::new(0)), window, cx));
let sorts: Vec<SharedString> = SORTS.iter().map(|(_, label)| (*label).into()).collect();
let chosen = SORTS
.iter()
.position(|(sort, _)| Some(*sort) == champion_sort)
.unwrap_or(0);
let sort_select =
cx.new(|cx| SelectState::new(sorts, Some(IndexPath::new(chosen)), window, cx));
let search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let charts = cx.new(|_| ChartsRow::new());
let home_search_input = cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let table = cx.new(|_| ChampionTable::new());
let home_grid = cx.new(|_| CardGrid::new());
let anvil_grid = cx.new(|_| CardGrid::fit_content());
let others_search_input =
cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let paging = Paging {
scroll: ScrollHandle::new(),
top: Rc::new(Cell::new(None)),
};
let champ_select_scrollbar = cx.new(|_| PageScrollbar {
scroll: paging.scroll.clone(),
});
let others_grid = cx.new(|_| CardGrid::paged(paging.clone()));
let others_focus = cx.focus_handle().tab_stop(true);
let ring = cx.new(|_| Ring::new());
let banner_art = BannerArt::new(cx);
let others_hover = Self::light_and_reveal(&others_grid, cx);
let mut subscriptions = Vec::new();
subscriptions.extend(Self::light_on_hover(&home_grid, cx));
subscriptions.extend(Self::light_on_hover(&anvil_grid, cx));
subscriptions.extend([
// The Windows setting turned off: a transition running ends, a card lifting is
// lifted, and nothing waits.
cx.observe_global_in::<AnimationSetting>(window, |this, window, cx| {
if cx.reduce_motion() {
this.end_match(cx);
this.entry_waiting = false;
this.end_stage(cx);
this.lifts.finish(cx.background_executor().now());
this.end_fade(window, cx);
}
}),
// Minimised or hidden in the notification area, the window draws nothing: a
// transition ends at once, and an animation waits for it to show again.
cx.observe_window_visibility(window, |this, visibility, window, cx| {
if visibility.is_visible() {
this.play_waiting(window, cx);
this.start_entry(window, cx);
} else {
this.end_stage(cx);
this.lifts.finish(cx.background_executor().now());
this.end_fade(window, cx);
}
}),
cx.subscribe(&search_input, |this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.search = ChampionSearch::new(&input.read(cx).value());
this.refresh_table(cx);
}
}),
cx.subscribe(&home_search_input, |this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.home_search = ChampionSearch::new(&input.read(cx).value());
this.home_filtered(cx);
}
}),
cx.subscribe(
&others_search_input,
|this, input, event: &InputEvent, cx| {
if matches!(event, InputEvent::Change) {
this.others_search = ChampionSearch::new(&input.read(cx).value());
this.refresh_others(cx);
}
},
),
cx.subscribe_in(
&account_select,
window,
|this, _, event: &SelectEvent<Vec<AccountItem>>, window, cx| {
let SelectEvent::Confirm(Some(puuid)) = event else {
return;
};
// Picking the Account being updated is following it again.
let following = this
.status
.updating
.as_ref()
.is_some_and(|a| a.puuid == *puuid);
this.pinned = (!following).then(|| puuid.clone());
this.reload(window, cx);
},
),
cx.subscribe_in(
&season_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
this.season = if name.as_ref() == ALL_SEASONS {
SeasonScope::AllSeasons
} else {
SeasonScope::Season(name.to_string())
};
this.recompute(window, cx);
},
),
cx.subscribe(
&sort_select,
|this, _, event: &SelectEvent<Vec<SharedString>>, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
if let Some((sort, _)) = SORTS.iter().find(|(_, label)| *label == name.as_ref())
{
this.choose_sort(*sort, cx);
}
},
),
cx.subscribe_in(
&format_select,
window,
|this, _, event: &SelectEvent<Vec<SharedString>>, window, cx| {
let SelectEvent::Confirm(Some(name)) = event else {
return;
};
let formats = this.stats.iter().flat_map(|s| s.formats.iter());
this.format = formats.copied().find(|f| f.name() == name.as_ref());
this.recompute(window, cx);
},
),
]);
// gpui-kit's async channel wakes the page on sends, with no timer or extra dependency.
let listener = cx.spawn_in(window, async move |this, cx| {
while let Ok(msg) = rx.recv().await {
let applied = cx
.update(|window, app| this.update(app, |page, cx| page.apply(msg, window, cx)));
// The window or the page is gone: nothing left to update.
if !matches!(applied, Ok(Ok(()))) {
return;
}
}
});
let mut page = Page {
status: tracker.status(),
tracker,
tx,
notice,
champ_select: None,
champ_select_account: None,
champ_select_riot_id: None,
accounts: Vec::new(),
last_active: None,
pinned: None,
shown: None,
progress: None,
refresh: RefreshGate::default(),
stats_job: RefreshGate::default(),
stats_generation: 0,
pending_round: following,
crashed: false,
last_reload: Instant::now(),
current_season,
tab: Tab::Challenge,
shown_tab: Tab::Challenge,
fade: None,
frame_asked: false,
lifts: Lifts::new(),
lifted_by_keyboard: None,
covered: false,
playback: MatchPlayback::default(),
hold_grid: false,
next_home: None,
entry: None,
entry_waiting: false,
leave: None,
taken: Vec::new(),
hover_waiting: None,
stage_frame_asked: false,
#[cfg(test)]
played: Vec::new(),
season,
format: None,
filter: StateFilter::All,
search: ChampionSearch::new(""),
search_input,
stats: None,
stats_error: None,
home_season: None,
home_scope: None,
home_stats: None,
home_error: None,
home_computed: None,
banner: home::BannerContent::default(),
champ_select_splashes: HashMap::new(),
ring,
lit_by: None,
banner_art,
home_filter: StateFilter::All,
home_search: ChampionSearch::new(""),
home_search_input,
champion_sort,
sort_select,
order: Vec::new(),
#[cfg(test)]
reorders: 0,
stored: None,
account_select,
account_items: Vec::new(),
season_select,
format_select,
format_names,
charts,
table,
home_grid,
home_cards_stale: false,
home_shown_count: SharedString::default(),
anvil_grid,
anvil_count: SharedString::default(),
others_open: false,
others_search: ChampionSearch::new(""),
others_search_input,
others_grid,
paging,
champ_select_scrollbar,
others_focus,
others_hover,
_subscriptions: subscriptions,
_listener: listener,
};
page.reload(window, cx);
page
}
}
+394
View File
@@ -0,0 +1,394 @@
//! The « Statistiques » tab: the analysis of one Account, Season and Format.
mod data;
use arena_tracker_core::{ChallengeSummary, Charts, ProgressCheck, StateFilter};
use gpui_kit::component::chart::{AreaChart, BarChart};
use gpui_kit::component::input::Input;
use gpui_kit::component::select::Select;
use gpui_kit::component::tab::{Tab, TabBar};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _, Theme};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use super::{Page, shown};
use crate::text::{decimal, official_note};
use crate::theme::{heading, surface};
const NO_MATCH: &str = "Aucune Partie";
/// Fixed, as a cached view's height must be. With `card`'s padding, gap and title, it leaves
/// each chart 150 px: change them together.
const CHARTS_HEIGHT: f32 = 206.;
/// The state filters on offer: the Challenge ones only make sense in a Season.
fn filters(in_season: bool) -> &'static [(&'static str, StateFilter)] {
const SEASON: [(&str, StateFilter); 4] = [
("Tous", StateFilter::All),
("Validés", StateFilter::Completed),
("Restants", StateFilter::Remaining),
("Jamais joués", StateFilter::NeverPlayed),
];
if in_season {
&SEASON
} else {
&[SEASON[0], SEASON[3]]
}
}
fn tile(
label: &'static str,
value: String,
note: Option<String>,
theme: &Theme,
) -> impl IntoElement {
div()
.v_flex()
.flex_1()
.gap_1()
.p_3()
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.rounded_md()
.child(
div()
.text_sm()
.text_color(theme.muted_foreground)
.child(label),
)
.child(
div()
.text_xl()
.font_weight(FontWeight::SEMIBOLD)
.child(value),
)
.children(note.map(|note| {
div()
.text_xs()
.text_color(theme.muted_foreground)
.child(note)
}))
}
fn challenge_tiles(
c: &ChallengeSummary,
official: Option<&ProgressCheck>,
theme: &Theme,
) -> impl IntoElement {
let average = c.average_attempts.map_or("-".into(), |a| decimal(a, 2));
// Next to the count whether the app agrees or not; the banner covers the difference.
let note = match official {
Some(ProgressCheck::Agrees(n)) | Some(ProgressCheck::Differs { official: n, .. }) => {
Some(official_note(*n))
}
_ => None,
};
div()
.h_flex()
.gap_3()
.child(tile(
"Champions validés",
format!("{} / {}", c.completed, c.total),
note,
theme,
))
.child(tile("Tentatives", c.attempts.to_string(), None, theme))
.child(tile("Tentatives par champion validé", average, None, theme))
.child(tile(
"Du premier coup",
c.first_tries.to_string(),
None,
theme,
))
}
/// A titled card holding a chart, or `empty` in its place.
fn card(
title: Div,
chart: Option<AnyElement>,
empty: &'static str,
theme: &Theme,
) -> impl IntoElement {
let body = chart.unwrap_or_else(|| {
div()
.size_full()
.flex()
.items_center()
.justify_center()
.text_color(theme.muted_foreground)
.child(empty)
.into_any_element()
});
div()
.v_flex()
.flex_1()
.min_w_0()
.h_full()
.gap_2()
.p_3()
.bg(surface(theme))
.border_1()
.border_color(theme.border)
.rounded_md()
.child(title.text_sm())
.child(div().flex_1().min_h_0().w_full().children(Some(body)))
}
/// The charts, a cached view: hovering the table, which redraws the page, does not draw them
/// again (#31). The page updates it from `show_statistics`.
pub(in crate::page) struct ChartsRow {
/// Empty when there are no statistics.
charts: Charts,
in_season: bool,
/// Guards the cache in tests.
#[cfg(test)]
pub(in crate::page) renders: usize,
}
impl ChartsRow {
pub(in crate::page) fn new() -> ChartsRow {
ChartsRow {
charts: Charts {
placements: vec![],
completed_over_time: vec![],
attempts_to_complete: [0; 5],
},
in_season: false,
#[cfg(test)]
renders: 0,
}
}
/// Shows `charts`, or none; drawing them again only when they changed, since reloads keep
/// coming during an import.
pub(in crate::page) fn set(
&mut self,
charts: Option<&Charts>,
in_season: bool,
cx: &mut Context<Self>,
) {
let charts = charts.cloned().unwrap_or_else(|| ChartsRow::new().charts);
if (&self.charts, self.in_season) != (&charts, in_season) {
self.charts = charts;
self.in_season = in_season;
cx.notify();
}
}
}
impl Render for ChartsRow {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let theme = cx.theme();
let charts = &self.charts;
let mut cards = Vec::new();
// The curve first: it is the Season's story, the others detail it.
if self.in_season {
cards.push(
card(
heading(cx).child("Champions validés au fil de la Saison"),
if shown("completed") {
completed_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
theme,
)
.into_any_element(),
);
}
cards.push(
card(
heading(cx).child("Répartition des Placements"),
if shown("placements") {
placements_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
NO_MATCH,
theme,
)
.into_any_element(),
);
if self.in_season {
cards.push(
card(
heading(cx).child("Tentatives pour valider"),
if shown("attempts") {
attempts_chart(charts)
} else {
Some(div().size_full().into_any_element())
},
"Aucun champion validé",
theme,
)
.into_any_element(),
);
}
div().h_flex().size_full().gap_3().children(cards)
}
}
fn placements_chart(charts: &Charts) -> Option<AnyElement> {
(!charts.placements.is_empty()).then(|| {
BarChart::new(charts.placements.clone())
.id("placements")
.band(|(placement, _)| placement.to_string())
.value(|(_, count)| *count as f64)
.label(|(_, count)| count.to_string())
.name("Parties")
.into_any_element()
})
}
fn completed_chart(charts: &Charts) -> Option<AnyElement> {
let points: Vec<(String, f64)> = charts
.completed_over_time
.iter()
.map(|(day, count)| (day.to_string(), *count as f64))
.collect();
// The counts only grow, so the last one is the highest. The y axis runs from 0 to a
// multiple of 4 in four steps with no padding: every tick is then a whole number.
let top = charts.completed_over_time.last().map_or(0, |(_, n)| *n);
let top = top.div_ceil(4).max(1) * 4;
(!points.is_empty()).then(|| {
AreaChart::new(points)
.id("completed")
.x(|(day, _)| day.clone())
.y(|(_, count)| *count)
.linear()
.x_tick_count(3)
.y_axis(true)
.y_domain(0., top as f64)
.y_padding(0., 0.)
.y_tick_count(5)
.name("Champions validés")
.into_any_element()
})
}
fn attempts_chart(charts: &Charts) -> Option<AnyElement> {
const LABELS: [&str; 5] = ["1", "2", "3", "4", "5+"];
let bars: Vec<(&str, usize)> = LABELS
.into_iter()
.zip(charts.attempts_to_complete)
.collect();
bars.iter().any(|(_, count)| *count > 0).then(|| {
BarChart::new(bars)
.id("attempts")
.band(|(label, _)| *label)
.value(|(_, count)| *count as f64)
.label(|(_, count)| count.to_string())
.name("Champions")
.into_any_element()
})
}
impl Page {
/// The Season and Format selectors, which only the statistics have.
fn statistics_selectors(&self) -> [AnyElement; 2] {
[
Select::new(&self.season_select)
.id("season")
.w(px(220.))
.min_w(px(130.))
.into_any_element(),
Select::new(&self.format_select)
.id("format")
.w(px(220.))
.min_w(px(130.))
.into_any_element(),
]
}
/// Under the banners: the Challenge tiles, the charts, the filters and the table.
pub(in crate::page) fn statistics_content(&self, cx: &mut Context<Page>) -> Vec<AnyElement> {
let options = filters(self.in_season());
let selected = options.iter().position(|(_, f)| *f == self.filter);
let challenge = self.stats.as_ref().and_then(|s| s.challenge.as_ref());
let mut content = Vec::new();
// The Season and Format only exist where they are analysed: with the title, under the
// transition's veil, so the header does not change while the screen leaving is visible.
content.push(
div()
.h_flex()
.flex_wrap()
.items_center()
.justify_between()
.gap_3()
.when(shown("statistics-title"), |row| {
row.child(heading(cx).text_3xl().child("Statistiques"))
})
.child(
div()
.h_flex()
.items_center()
.gap_3()
.min_w_0()
.children(self.statistics_selectors()),
)
.into_any_element(),
);
if shown("tiles")
&& let Some(c) = challenge
{
content.push(challenge_tiles(c, self.official(), cx.theme()).into_any_element());
}
content.push(
self.charts
.clone()
.cached(StyleRefinement::default().w_full().h(px(CHARTS_HEIGHT)))
.into_any_element(),
);
if shown("tabs") {
content.push(
div()
.h_flex()
.items_center()
.justify_between()
.gap_3()
.child(
TabBar::new("state-filter")
.pill()
.selected_index(selected.unwrap_or(0))
.children(options.iter().map(|(label, _)| Tab::new().label(*label)))
.on_click(cx.listener(|this, ix: &usize, _, cx| {
if let Some((_, filter)) = filters(this.in_season()).get(*ix) {
this.filter = *filter;
this.refresh_table(cx);
cx.notify();
}
})),
)
.child(
Input::new(&self.search_input)
.cleanable(true)
.w(px(260.))
.min_w(px(150.)),
)
.into_any_element(),
);
}
if shown("table") {
content.push(
div()
.flex_1()
.min_h(px(240.))
// A cached view, laid out by the space the page gives it: the veil of a
// transition, which draws the page again at each frame, does not draw it.
.child(
self.table
.clone()
.cached(StyleRefinement::default().size_full()),
)
.into_any_element(),
);
}
content
}
}
+251
View File
@@ -0,0 +1,251 @@
use crate::card::Card;
use crate::page::{ALL_FORMATS, AccountItem, NextHome, Page, now_ms};
use crate::worker::{compute_statistics, spawn_statistics};
use arena_tracker_core::{SeasonScope, StateFilter, account_riot_id};
use gpui_kit::component::IndexPath;
use gpui_kit::*;
use std::time::Instant;
impl Page {
/// A worker's reload: the Accounts now, the statistics on a below-normal worker, so neither a
/// visible nor a hidden window waits for them (rule #1).
pub(in crate::page) fn reload_in_background(
&mut self,
window: &mut Window,
cx: &mut Context<Self>,
) {
self.reload_accounts(window, cx);
let start_job = self.stats_job.request();
self.recompute_in_background(start_job, window, cx);
}
/// Re-reads the Accounts, then the statistics of the one shown.
pub(in crate::page) fn reload(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.reload_accounts(window, cx);
self.recompute(window, cx);
}
/// Re-reads the Accounts and selects the one shown.
fn reload_accounts(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.accounts = self.tracker.accounts().unwrap_or_default();
self.last_active = self.tracker.last_active_account().ok().flatten();
if self.pinned.as_ref() == self.status.updating.as_ref().map(|a| &a.puuid) {
self.pinned = None;
}
let items: Vec<AccountItem> = self
.accounts
.iter()
.map(|a| AccountItem {
puuid: a.puuid.clone(),
title: account_riot_id(a).into(),
})
.collect();
let changed = items != self.account_items;
self.account_items = items.clone();
if changed {
// The live champ select's Account may now be in the list: resolve it again.
self.champ_select_riot_id = None;
}
// During a champ select the selector (disabled) shows the signed-in Account.
let viewed = if self.in_champ_select() {
self.champ_select_account()
} else {
self.viewed().map(|a| a.puuid.clone())
};
self.account_select.update(cx, |select, cx| {
if changed {
select.set_items(items, window, cx);
}
if let Some(puuid) = &viewed
&& select.selected_value() != Some(puuid)
{
select.set_selected_value(puuid, window, cx);
}
});
}
/// Settles the scope of the next statistics. Earlier results become stale when they are
/// computed again (`computing`) or when the viewed Account changed; a request merely queued
/// behind a running job keeps that job's result for the same scope.
fn prepare_statistics(
&mut self,
computing: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Option<String> {
self.last_reload = Instant::now();
if self.in_champ_select() {
if computing {
self.stats_generation += 1;
}
// The home is the champ select's: its Challenge is the current Season's, which is
// the Statistics scope for the whole champ select.
self.home_scope = None;
self.current_season = self.tracker.current_season(now_ms()).map(|s| s.name);
self.home_season = self.current_season.clone().map(Into::into);
let puuid = self.champ_select_account()?;
return self.current_season.is_some().then_some(puuid);
}
if matches!(self.season, SeasonScope::AllSeasons)
&& !matches!(self.filter, StateFilter::All | StateFilter::NeverPlayed)
{
self.filter = StateFilter::All;
}
let previous_season = self.home_season.clone();
self.settle_home_scope();
let viewed = self.viewed().map(|a| a.puuid.clone());
if previous_season != self.home_season || viewed != self.shown {
self.stop_holding();
self.end_match(cx);
}
if computing || viewed != self.shown {
self.stats_generation += 1;
}
if viewed != self.shown {
// Another Account may not have played the selected Format.
self.shown = viewed.clone();
if self.format.take().is_some() {
self.format_select.update(cx, |select, cx| {
select.set_selected_index(Some(IndexPath::new(0)), window, cx)
});
}
}
viewed
}
/// Requests the statistics from a worker (`start_job`: none is running), or shows none when no
/// Account is viewed.
pub(in crate::page) fn recompute_in_background(
&mut self,
start_job: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
let viewed = self.prepare_statistics(start_job, window, cx);
if let Some(puuid) = viewed {
if start_job {
let scope = self.statistics_scope();
// A below-normal worker keeps hidden and visible windows responsive (rule #1).
spawn_statistics(
self.tracker.clone(),
puuid,
scope,
self.home_scope.clone(),
self.stats_generation,
self.tx.clone(),
);
}
} else {
if start_job {
self.stats_job.reset();
}
self.stats = None;
self.stats_error = None;
self.forget_home();
self.stored = None;
self.show_statistics(window, cx);
}
}
/// Recomputes the statistics for the current scope; never called while rendering. The home's
/// own statistics are kept when they were computed for the same Account and scope (a change
/// of Format leaves them as they are).
pub(in crate::page) fn recompute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let viewed = self.prepare_statistics(true, window, cx);
self.stats = None;
self.stats_error = None;
self.stored = None;
let keep_home = !self.playback.stats_pending && viewed.is_some() && self.home_is_current();
if !keep_home {
self.forget_home();
}
if let Some(puuid) = &viewed {
let scope = self.statistics_scope();
match compute_statistics(&self.tracker, puuid, &scope) {
Ok(stats) => self.stats = Some(stats),
Err(error) => self.stats_error = Some(error),
}
if !keep_home {
let home = (self.home_scope.clone())
.map(|home| Box::new(compute_statistics(&self.tracker, puuid, &home)));
self.set_home_result(home);
}
self.stored = self.tracker.match_count(puuid).ok();
}
self.show_statistics(window, cx);
}
/// Shows `stats`: the Format choices, the charts and the table.
pub(in crate::page) fn show_statistics(&mut self, window: &mut Window, cx: &mut Context<Self>) {
if self.hold_grid {
// Row indices are reusable only while the catalog has the same champions.
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
let cards = self.home_grid.read(cx).cards();
let same = rows.len() == cards.len()
&& self.order.len() == rows.len()
&& self
.order
.iter()
.zip(cards.iter())
.all(|(&ix, c)| rows.get(ix).is_some_and(|r| r.champion.id == c.id));
if !same || self.in_champ_select() {
self.stop_holding();
}
}
if !self.hold_grid {
self.reorder();
}
if self.in_champ_select() {
// Neither the charts, the table nor the home grid are shown during a champ select.
self.prepare_banner(cx);
self.prepare_champ_select(cx);
cx.notify();
return;
}
self.prepare_banner(cx);
self.prepare_home_cards(cx);
let charts = self.stats.as_ref().map(|s| &s.charts);
let in_season = self.in_season();
self.charts
.update(cx, |row, cx| row.set(charts, in_season, cx));
let mut names = vec![SharedString::from(ALL_FORMATS)];
names.extend(
self.stats
.iter()
.flat_map(|s| s.formats.iter().map(|f| SharedString::from(f.name()))),
);
if names != self.format_names {
self.format_names = names.clone();
self.format_select
.update(cx, |select, cx| select.set_items(names, window, cx));
}
self.refresh_table(cx);
if self.hold_grid {
// The cards changed in place; their order, which are shown and their count wait for
// the pointer to leave, prepared now.
let order = self.sorted_order();
let rows = self
.home_statistics()
.map_or(&[][..], |s| s.rows.as_slice());
let cards = order
.iter()
.filter_map(|&ix| rows.get(ix))
.map(Card::from_row)
.collect();
let shown = self.home_shown(&order);
self.next_home = Some(NextHome {
count: shown.len().to_string().into(),
order,
cards,
shown,
});
} else {
self.refresh_home(cx);
}
self.playback.stats_pending = false;
self.play_waiting(window, cx);
cx.notify();
}
}
+19
View File
@@ -0,0 +1,19 @@
mod account;
mod banner;
mod banner_fixtures;
mod banner_scope;
mod card_sheet;
mod champ_select_browsing;
mod champ_select_capture;
mod champ_select_fixtures;
mod champ_select_motion;
mod champ_select_others;
mod champ_select_scroll;
mod grid;
mod home;
mod match_animation;
mod navigation;
mod page_fixtures;
mod portraits;
mod sorting;
mod sorting_fixtures;
+243
View File
@@ -0,0 +1,243 @@
use super::champ_select_fixtures::finish_motion;
use super::page_fixtures::{
RefreshHistory, open_page, open_page_with_tracker, refresh_towards_bob, switch_tab,
};
use crate::champion_table::tests::row;
use crate::page::Tab;
use arena_tracker_core::{
Champion, ChampionRow, ChampionState, Charts, Format, StateFilter, Statistics, Tracker,
};
use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, point, px};
use std::cell::{Cell, RefCell};
use std::path::Path;
use std::rc::Rc;
#[gpui::test]
async fn a_refresh_keeps_following_the_account_being_updated(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, false).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned, None);
assert_eq!(page.viewed().unwrap().puuid, "Bob");
// Another Account may not have played the Format: the filter is dropped
// (`prepare_statistics`), whatever the refresh.
assert_eq!(page.format, None);
});
}
#[gpui::test]
async fn a_refresh_keeps_a_pinned_account_and_format(cx: &mut TestAppContext) {
let page = refresh_towards_bob(cx, true).await;
page.read_with(cx, |page, _| {
assert_eq!(page.status.updating.as_ref().unwrap().puuid, "Bob");
assert_eq!(page.pinned.as_deref(), Some("Alice"));
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.format, Some(Format::Arena3x6));
});
}
#[gpui::test]
async fn champ_select_uses_the_signed_in_accounts_challenge_and_restores_the_pinned_page(
cx: &mut TestAppContext,
) {
use crate::worker::Msg;
use arena_tracker_core::{ChampSelect, SeasonScope};
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
tracker.sync("Bob#EUW", &mut |_| {}).unwrap();
tracker.follow_client(0, Some("Alice#EUW"), &mut |_| {});
let (page, mut window) = open_page_with_tracker(cx, tracker);
let pick = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.set_tab(Tab::Statistics, w, cx);
p.pinned = Some("Bob".into());
p.season = SeasonScope::AllSeasons;
p.filter = StateFilter::NeverPlayed;
p.reload(w, cx);
assert!(p.stats.as_ref().unwrap().rows.is_empty());
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), pick))), w, cx);
})
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
// The champ select takes the home, about the signed-in Account's current Season.
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.displayed().unwrap().puuid, "Alice");
assert_eq!(p.home_season, p.current_season.clone().map(Into::into));
assert!(p.home_season.is_some());
assert_eq!(p.anvil_grid.read(cx).names(), ["Irelia"]);
});
// A hover change touches neither the Account nor the pool: the card follows it.
let next = ChampSelect::new(None, [39].into(), Some(vec![39]));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(Some(("Alice#EUW".into(), next))), w, cx);
})
});
page.read_with(cx, |p, cx| {
assert_eq!(p.anvil_grid.read(cx).names(), ["Irelia"]);
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(Msg::ChampSelect(None), w, cx);
})
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
page.read_with(cx, |p, cx| {
assert_eq!(p.viewed().unwrap().puuid, "Bob");
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.filter, StateFilter::NeverPlayed);
assert_eq!(p.tab, Tab::Challenge);
assert!(p.table.read(cx).names().is_empty());
});
}
#[gpui::test]
fn only_entering_a_champ_select_is_reported_as_an_entry(cx: &mut TestAppContext) {
use crate::worker::Msg;
use arena_tracker_core::ChampSelect;
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory)).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
let entered = Rc::new(RefCell::new(Vec::new()));
let _events = window.update(|_, cx| {
let entered = entered.clone();
cx.subscribe(
&page,
move |_, transition: &crate::page::ChampSelectTransition, _| {
entered.borrow_mut().push(transition.entered)
},
)
});
let hovered = |current| ChampSelect::new(current, [39].into(), Some(vec![39]));
for champ_select in [
None,
Some(("Alice#EUW".into(), hovered(Some(39)))),
Some(("Alice#EUW".into(), hovered(None))),
None,
None,
] {
window.update(|w, cx| {
page.update(cx, |p, cx| p.apply(Msg::ChampSelect(champ_select), w, cx))
});
}
// The champ select ends once its hand has left.
finish_motion(&page, &mut window);
assert_eq!(*entered.borrow(), [true, false]);
}
#[gpui::test]
fn typing_in_the_search_field_filters_the_table(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
let champion = |id, key: &str, name: &str| ChampionRow {
champion: Champion {
id,
key: key.into(),
name: name.into(),
},
..row(name)
};
page.update(cx, |page, _| {
page.stats = Some(Statistics {
challenge: None,
rows: vec![
ChampionRow {
state: Some(ChampionState::Completed),
..champion(4, "TwistedFate", "Twisted Fate")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
..champion(86, "Garen", "Garen")
},
ChampionRow {
state: Some(ChampionState::NeverPlayed),
matches: 5,
..champion(107, "Rengar", "Rengar")
},
],
charts: Charts {
placements: Vec::new(),
completed_over_time: Vec::new(),
attempts_to_complete: [0; 5],
},
formats: Vec::new(),
});
});
// The search field of the Statistics tab is only there on that tab.
switch_tab(&page, cx, Tab::Statistics);
cx.update(|window, cx| window.draw(cx).clear(cx));
let (input, table) = page.read_with(cx, |p, _| (p.search_input.clone(), p.table.clone()));
let names = |cx: &mut VisualTestContext| table.read_with(cx, |table, _| table.names());
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("ren");
assert_eq!(names(cx), ["Rengar", "Garen"]);
// The clear button's own path: it empties the field and the table follows.
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(names(cx).len(), 3);
cx.simulate_input("TF");
assert_eq!(names(cx), ["Twisted Fate"]);
cx.simulate_input("z");
assert!(names(cx).is_empty());
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input(" ");
assert_eq!(names(cx).len(), 3);
// Combined with a state filter, the table keeps its sort (most Matches first).
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
cx.simulate_input("ren");
page.update(cx, |page, cx| {
page.filter = StateFilter::Completed;
page.refresh_table(cx);
});
assert!(names(cx).is_empty());
page.update(cx, |page, cx| {
page.filter = StateFilter::NeverPlayed;
page.refresh_table(cx);
});
assert_eq!(names(cx), ["Rengar", "Garen"]);
}
// No test can time a frame: this guards the cache that keeps hovering cheap instead (rule #1,
// #31). It runs with the app's tests on Windows; CI only builds the core.
#[gpui::test]
fn hovering_the_table_does_not_render_the_charts(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
// The table hovered is the Statistics tab's: the app opens on the Challenge.
switch_tab(&page, cx, Tab::Statistics);
let (table, charts) = page.read_with(cx, |page, _| (page.table.clone(), page.charts.clone()));
// Enough rows to fill the table, under the points hovered below.
table.update(cx, |table, cx| {
let rows = (1..=20).map(|n| row(&format!("Champion {n}")));
table.set_rows(rows.collect(), false);
cx.notify();
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let renders = charts.read_with(cx, |charts, _| charts.renders);
assert!(renders > 0);
// A row's hover style notifies the table, which redraws the page.
let hovers = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let hovers = hovers.clone();
cx.observe(&table, move |_, _| hovers.set(hovers.get() + 1))
});
for y in [700., 740.] {
cx.simulate_mouse_move(point(px(300.), px(y)), None, Modifiers::none());
cx.update(|window, cx| window.draw(cx).clear(cx));
}
assert!(hovers.get() > 0, "no row was hovered");
assert_eq!(charts.read_with(cx, |charts, _| charts.renders), renders);
// The count does move when the charts change.
charts.update(cx, |_, cx| cx.notify());
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(
charts.read_with(cx, |charts, _| charts.renders),
renders + 1
);
}
+488
View File
@@ -0,0 +1,488 @@
use super::banner_fixtures::{
banner, banner_champion, banner_rows, banner_statistics, bold, draw_loaded, held_splashes,
in_atlas, loaded_splashes, on, ring_renders, ring_ticks, rows_with_splashes, splash,
};
use super::page_fixtures::{
center, champions, draw, open_page_in_season, show, statistics, switch_tab,
};
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
use crate::page::Tab;
use arena_tracker_core::{
ChampionChallenge, ChampionRow, ChampionSort, ChampionState, LastMatch, MatchOutcome,
StateFilter,
};
use gpui_kit::{
Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px, size,
};
use std::cell::Cell;
use std::rc::Rc;
#[gpui::test]
fn the_banner_says_the_count_the_last_completion_and_the_last_match(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let last_match = |champion_id, placement, outcome| {
Some(LastMatch {
champion_id,
placement,
outcome,
})
};
let cases = [
// Not yet Completed: its Attempt, the first one feminine.
(
last_match(3, 4, MatchOutcome::Attempt(3)),
"Dernière Partie : Zyra, 4ᵉ · 3ᵉ Tentative",
),
(
last_match(3, 2, MatchOutcome::Attempt(1)),
"Dernière Partie : Zyra, 2ᵉ · 1ʳᵉ Tentative",
),
// The Match that completes it.
(
last_match(1, 1, MatchOutcome::Completed(3)),
"Dernière Partie : Ahri, 1ᵉʳ · validé en 3 Tentatives",
),
(
last_match(1, 1, MatchOutcome::Completed(1)),
"Dernière Partie : Ahri, 1ᵉʳ · validé du premier coup",
),
// Already Completed.
(
last_match(2, 4, MatchOutcome::AfterCompletion),
"Dernière Partie : Brand, 4ᵉ",
),
];
for (last, expected) in cases {
show(
&page,
cx,
banner_statistics(banner_rows(), vec![2, 1], last),
);
draw(cx);
let text = banner(&page, cx);
assert_eq!(text.season.as_ref(), "SAISON");
assert_eq!(text.title.text.as_ref(), "2 / 5 champions validés");
assert_eq!(bold(&text.title), "2");
assert_eq!(
text.detail.text.as_ref(),
"Dernier champion validé : Ahri, le 20 nov."
);
assert_eq!(bold(&text.detail), "Ahri");
let line = text.last_match.expect("no last Match line");
assert_eq!(line.text.as_ref(), expected);
let champion = expected["Dernière Partie : ".len()..].split(',').next();
assert_eq!(Some(bold(&line)), champion);
assert!(cx.debug_bounds("banner-title").is_some());
}
// A Season without a Completed champion nor a Match.
let never: Vec<_> = banner_rows()
.into_iter()
.map(|row| ChampionRow {
state: Some(ChampionState::NeverPlayed),
challenge: Some(ChampionChallenge::default()),
..row
})
.collect();
show(&page, cx, banner_statistics(never, Vec::new(), None));
draw(cx);
let text = banner(&page, cx);
assert_eq!(text.title.text.as_ref(), "0 / 5 champions validés");
assert_eq!(
text.detail.text.as_ref(),
"Aucun champion validé pour l’instant."
);
assert_eq!(text.last_match, None);
assert_eq!(text.splash, None);
assert!(cx.debug_bounds("banner-title").is_some());
assert!(cx.debug_bounds("banner-art").is_none());
}
#[gpui::test]
fn the_ring_keeps_its_fixed_order_whatever_the_sort(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
banner_statistics(banner_rows(), vec![2, 1], None),
);
draw(cx);
let expected = [
(2, ChampionState::Completed),
(1, ChampionState::Completed),
(4, ChampionState::InProgress),
(3, ChampionState::InProgress),
(5, ChampionState::NeverPlayed),
];
assert_eq!(ring_ticks(&page, cx), expected);
assert!(cx.debug_bounds("ring").is_some());
let renders = ring_renders(&page, cx);
// The cards follow the sort; the ring does not, and is not drawn again.
page.update(cx, |page, cx| page.choose_sort(ChampionSort::Name, cx));
draw(cx);
assert_eq!(ring_ticks(&page, cx), expected);
assert_eq!(ring_renders(&page, cx), renders);
}
// The ring is a cached view (rule #1): hovering the grid draws it again only when a tick
// lights up or goes out, and builds no card.
#[gpui::test]
fn hovering_the_grid_draws_the_ring_only_for_the_tick_that_lights_or_goes_out(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = ring_renders(&page, cx);
assert!(renders > 0);
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let hover = |cx: &mut VisualTestContext, at: gpui_kit::Point<gpui_kit::Pixels>| {
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
};
let card = cx.debug_bounds("card-1").unwrap();
hover(cx, card.center());
assert_eq!(lit(cx), Some(1));
assert_eq!(ring_renders(&page, cx), renders + 1);
// Elsewhere on the same card: nothing changes.
hover(cx, card.center() + point(px(10.), px(10.)));
assert_eq!(ring_renders(&page, cx), renders + 1);
let at = center(cx, "card-2");
hover(cx, at);
assert_eq!(lit(cx), Some(2));
assert_eq!(ring_renders(&page, cx), renders + 2);
// Off the grid, over a button whose hover draws the page: the tick goes out once.
let at = center(cx, "tab-statistics");
hover(cx, at);
assert_eq!(lit(cx), None);
assert_eq!(ring_renders(&page, cx), renders + 3);
hover(cx, point(px(5.), px(5.)));
let at = center(cx, "tab-statistics");
hover(cx, at);
assert_eq!(ring_renders(&page, cx), renders + 3);
// Scrolling moves the cards under a still pointer: the ring is drawn again only when
// that changes the lit tick, at most once a frame.
let at = center(cx, "card-1");
hover(cx, at);
assert_eq!(ring_renders(&page, cx), renders + 4);
// The grid tells each change of the card under the pointer, and only a change.
let changes = Rc::new(Cell::new(0));
let _subscription = cx.update(|_, cx| {
let changes = changes.clone();
cx.subscribe(&grid, move |_, _: &crate::card_grid::CardHovered, _| {
changes.set(changes.get() + 1)
})
});
for _ in 0..3 {
let (was_changed, was_drawn) = (changes.get(), ring_renders(&page, cx));
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(-200.))),
..Default::default()
});
draw(cx);
assert_eq!(
ring_renders(&page, cx) - was_drawn,
changes.get() - was_changed
);
}
assert!(
changes.get() > 0,
"no scroll changed the card under the pointer"
);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
// A grid that is no longer shown has no card under the pointer.
hover(cx, point(px(5.), px(5.)));
hover(cx, at);
assert!(lit(cx).is_some());
switch_tab(&page, cx, Tab::Statistics);
assert_eq!(lit(cx), None);
}
#[gpui::test]
fn the_banner_holds_two_splashes_at_most_and_gives_back_the_one_replaced(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-splashes");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
// Ahri was Completed last: its splash is the illustration.
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
);
draw_loaded(cx);
assert!(cx.debug_bounds("banner-art").is_some());
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
let ahri = loaded_splashes(&page, cx);
assert_eq!(ahri.len(), 1, "the splash was not decoded");
assert!(in_atlas(cx, &ahri[0]));
// Never through the app-wide asset cache, which would keep it.
let source = gpui_kit::ImageSource::from(dir.path().join("Ahri.50.30.jpg"));
assert!(!cx.update(|_, cx| source.is_asset_cached(cx)));
// Brand is now the last: Ahri stays shown while Brand decodes, then is given back.
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![1, 2], None),
);
draw(cx);
assert_eq!(
held_splashes(&page, cx),
["Ahri.50.30.jpg", "Brand.50.30.jpg"]
);
assert!(loaded_splashes(&page, cx).len() <= 2);
cx.run_until_parked();
draw(cx);
assert_eq!(loaded_splashes(&page, cx).len(), 2);
assert!(in_atlas(cx, &ahri[0]));
cx.update(|_, cx| {
cx.background_executor()
.advance_clock(std::time::Duration::from_millis(501))
});
draw(cx);
assert_eq!(held_splashes(&page, cx), ["Brand.50.30.jpg"]);
let brand = loaded_splashes(&page, cx);
assert_eq!(brand.len(), 1);
assert!(in_atlas(cx, &brand[0]));
assert!(!in_atlas(cx, &ahri[0]));
// « Statistiques » has no banner: its splash is given back, and comes back with it.
switch_tab(&page, cx, Tab::Statistics);
draw(cx);
assert!(held_splashes(&page, cx).is_empty());
assert!(!in_atlas(cx, &brand[0]));
switch_tab(&page, cx, Tab::Challenge);
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx), ["Brand.50.30.jpg"]);
}
#[gpui::test]
fn a_banner_without_splash_has_no_illustration(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-no-splash");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
);
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx).len(), 1);
// The last Completed champion's splash is not downloaded yet: no illustration, and the
// one shown before is given back.
let mut rows = rows_with_splashes(dir.path());
rows[0].splash = None;
show(&page, cx, banner_statistics(rows, vec![2, 1], None));
draw(cx);
assert!(cx.debug_bounds("banner").is_some());
assert!(cx.debug_bounds("banner-title").is_some());
assert!(cx.debug_bounds("banner-art").is_none());
assert!(held_splashes(&page, cx).is_empty());
}
#[gpui::test]
fn in_a_narrow_window_the_ring_goes_above_the_text_and_the_splash_covers_the_banner(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("banner-narrow");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
);
draw(cx);
let bounds = |cx: &mut VisualTestContext| {
["banner", "ring", "banner-title", "banner-art"].map(|id| cx.debug_bounds(id).unwrap())
};
// Wide: the ring beside the text, the splash on the right.
let [banner, ring, title, art] = bounds(cx);
assert!(ring.right() <= title.left(), "{ring:?} {title:?}");
assert!((art.size.width.as_f32() - 0.72 * banner.size.width.as_f32()).abs() < 1.);
assert_eq!(art.right(), banner.right());
cx.simulate_resize(size(px(600.), px(860.)));
draw(cx);
let [banner, ring, title, art] = bounds(cx);
assert!(ring.bottom() <= title.top(), "{ring:?} {title:?}");
assert_eq!(art.size.width, banner.size.width);
assert_eq!(art.size.height, banner.size.height);
}
// Only the ring is invalidated: the grid is not drawn again, no card is built, and its fixed
// shapes are not tessellated again for a new lit tick.
#[gpui::test]
fn lighting_a_tick_draws_the_ring_alone_and_tessellates_only_that_tick(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let (ring, grid) = page.read_with(cx, |p, _| (p.ring.clone(), p.home_grid.clone()));
let grid_state = |cx: &mut VisualTestContext| {
grid.read_with(cx, |grid, _| {
(grid.renders, grid.card_builds, grid.set_cards_calls)
})
};
let tessellations =
|cx: &mut VisualTestContext| ring.read_with(cx, |ring, _| ring.tessellations.get());
let before = grid_state(cx);
let shapes = tessellations(cx);
let renders = ring_renders(&page, cx);
for lit in [Some(5), Some(90), None] {
ring.update(cx, |ring, cx| ring.set_lit(lit, cx));
draw(cx);
}
assert_eq!(ring_renders(&page, cx), renders + 3);
assert_eq!(grid_state(cx), before);
assert_eq!(tessellations(cx), shapes);
// New ticks are tessellated once.
show(&page, cx, statistics(0, 171, champions(171)));
draw(cx);
assert_eq!(tessellations(cx), shapes + 1);
}
#[gpui::test]
fn a_splash_asked_for_while_another_decodes_waits_for_it(cx: &mut TestAppContext) {
cx.update(|cx| cx.set_reduce_motion(true));
let dir = TestDir::new("banner-queue");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let mut rows = rows_with_splashes(dir.path());
rows[2] = banner_champion(4, "Garen", 2, Some(on(11, 21)), 900);
rows[2].splash = Some(splash(dir.path(), "Garen"));
let last = |order: Vec<u32>| banner_statistics(rows.clone(), order, None);
show(&page, cx, last(vec![2, 1]));
draw_loaded(cx);
let ahri = loaded_splashes(&page, cx);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
// Brand starts decoding; Garen is asked for before it ends, and waits.
show(&page, cx, last(vec![1, 2]));
draw(cx);
show(&page, cx, last(vec![1, 2, 4]));
draw(cx);
assert_eq!(
held_splashes(&page, cx),
["Ahri.50.30.jpg", "Brand.50.30.jpg"]
);
cx.run_until_parked();
draw(cx);
assert_eq!(held_splashes(&page, cx), ["Garen.50.30.jpg"]);
assert!(!in_atlas(cx, &ahri[0]));
let loads = page.read_with(cx, |p, cx| p.banner_art.read(cx).loads);
assert_eq!(loads, 3);
}
#[gpui::test]
fn opening_another_screen_gives_back_the_splash_and_the_portraits(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-hidden");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let mut rows = rows_with_splashes(dir.path());
for row in &mut rows {
let path = dir.path().join(format!("{}.card.jpg", row.champion.key));
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
row.card_portrait = Some(path);
}
show(&page, cx, banner_statistics(rows, vec![2, 1], None));
draw_loaded(cx);
let images = page.read_with(cx, |p, cx| p.home_grid.read(cx).images().cloned().unwrap());
let portraits = images.read_with(cx, |images, _| images.loaded());
let splash = loaded_splashes(&page, cx);
assert!(!portraits.is_empty() && splash.len() == 1);
// Checked before any frame: here the page is the window's root and would be drawn
// again, where the app shows « Paramètres » in its place.
let (held, portraits_held, in_atlas) = cx.update(|window, cx| {
page.update(cx, |page, cx| page.hidden(window, cx));
let held = page.read(cx).banner_art.read(cx).held();
let portraits_held = images.read(cx).held();
let in_atlas = (portraits.iter().chain(&splash))
.filter(|image| window.has_image_atlas_entry(image))
.count();
(held, portraits_held, in_atlas)
});
assert!(held.is_empty(), "{held:?}");
assert!(portraits_held.is_empty(), "{portraits_held:?}");
assert_eq!(in_atlas, 0);
}
#[gpui::test]
fn in_a_low_window_the_home_scrolls_to_its_grid(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 30, champions(30)));
cx.simulate_resize(size(px(600.), px(340.)));
draw(cx);
let visible = |cx: &mut VisualTestContext| {
cx.debug_bounds("card-1")
.is_some_and(|b| b.top() < px(340.))
};
assert!(!visible(cx));
let banner = center(cx, "banner");
cx.simulate_event(ScrollEvent {
position: banner,
delta: ScrollDelta::Pixels(point(px(0.), px(-2000.))),
..Default::default()
});
draw(cx);
assert!(visible(cx));
let at = center(cx, "card-1");
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(1));
}
#[gpui::test]
fn the_tick_follows_the_card_actually_under_the_pointer(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let at = center(cx, "card-1");
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
assert_eq!(lit(cx), Some(1));
// A wheel at the top of the list moves no card: the tick stays, the ring is not drawn.
let renders = ring_renders(&page, cx);
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(400.))),
..Default::default()
});
draw(cx);
assert_eq!(lit(cx), Some(1));
assert_eq!(ring_renders(&page, cx), renders);
// The card leaves the grid (« Validés » here): its tick goes out.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Completed;
p.refresh_home(cx);
});
draw(cx);
assert_eq!(lit(cx), None);
}
@@ -0,0 +1,145 @@
use super::page_fixtures::{draw, statistics};
use crate::card_images::tests::PORTRAIT_JPEG;
use crate::champion_table::tests::row;
use crate::page::Page;
use crate::ring::Tick;
use arena_tracker_core::{
Champion, ChampionChallenge, ChampionRow, ChampionState, Date, LastMatch, Splash, SplashFocus,
Statistics,
};
use gpui_kit::{Entity, VisualTestContext};
use std::path::Path;
use std::sync::Arc;
pub(super) fn on(month: u8, day: u8) -> Date {
Date {
year: 2026,
month,
day,
}
}
/// One champion of the banner's tests: `completed_on` makes it Completed, `matches` played.
pub(super) fn banner_champion(
id: u32,
name: &str,
matches: usize,
completed_on: Option<Date>,
points: u64,
) -> ChampionRow {
let state = match (completed_on, matches) {
(Some(_), _) => ChampionState::Completed,
(None, 0) => ChampionState::NeverPlayed,
(None, _) => ChampionState::InProgress,
};
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
state: Some(state),
challenge: Some(ChampionChallenge {
matches,
completed_on,
..Default::default()
}),
mastery_points: Some(points),
..row(name)
}
}
/// Brand then Ahri Completed, Garen and Zyra played, Lux never played; A to Z.
pub(super) fn banner_rows() -> Vec<ChampionRow> {
vec![
banner_champion(1, "Ahri", 3, Some(on(11, 20)), 100),
banner_champion(2, "Brand", 1, Some(on(11, 3)), 5),
banner_champion(4, "Garen", 2, None, 900),
banner_champion(5, "Lux", 0, None, 10),
banner_champion(3, "Zyra", 4, None, 50),
]
}
pub(super) fn banner_statistics(
rows: Vec<ChampionRow>,
completion_order: Vec<u32>,
last_match: Option<LastMatch>,
) -> Statistics {
let mut stats = statistics(completion_order.len(), rows.len(), rows);
let challenge = stats.challenge.as_mut().unwrap();
challenge.completion_order = completion_order;
challenge.last_match = last_match;
stats
}
pub(super) fn banner(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> crate::page::home::BannerContent {
page.read_with(cx, |page, _| page.banner.clone())
}
pub(super) fn bold(line: &crate::page::home::Line) -> &str {
&line.text[line.bold.clone()]
}
pub(super) fn ring_ticks(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Vec<(u32, ChampionState)> {
page.read_with(cx, |page, cx| {
page.ring
.read(cx)
.ticks()
.iter()
.map(|tick: &Tick| (tick.id, tick.state))
.collect()
})
}
pub(super) fn ring_renders(page: &Entity<Page>, cx: &mut VisualTestContext) -> usize {
page.read_with(cx, |page, cx| page.ring.read(cx).renders)
}
pub(super) fn splash(dir: &Path, key: &str) -> Splash {
let path = dir.join(format!("{key}.50.30.jpg"));
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
Splash {
path,
focus: SplashFocus { x: 50, y: 30 },
}
}
/// `banner_rows`, Ahri and Brand with a splash each.
pub(super) fn rows_with_splashes(dir: &Path) -> Vec<ChampionRow> {
let mut rows = banner_rows();
rows[0].splash = Some(splash(dir, "Ahri"));
rows[1].splash = Some(splash(dir, "Brand"));
rows
}
pub(super) fn draw_loaded(cx: &mut VisualTestContext) {
draw(cx);
cx.run_until_parked();
draw(cx);
}
pub(super) fn held_splashes(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<String> {
page.read_with(cx, |page, cx| {
let held = page.banner_art.read(cx).held();
held.iter()
.map(|path| path.file_name().unwrap().to_string_lossy().into_owned())
.collect()
})
}
pub(super) fn loaded_splashes(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Vec<Arc<gpui_kit::RenderImage>> {
page.read_with(cx, |page, cx| page.banner_art.read(cx).loaded())
}
pub(super) fn in_atlas(cx: &mut VisualTestContext, image: &gpui_kit::RenderImage) -> bool {
cx.update(|window, _| window.has_image_atlas_entry(image))
}
+196
View File
@@ -0,0 +1,196 @@
use super::banner_fixtures::{
banner, banner_statistics, draw_loaded, held_splashes, in_atlas, loaded_splashes, ring_ticks,
rows_with_splashes, splash,
};
use super::champ_select_fixtures::{
ANVIL_CARDS, activate, click_others, frames, joueur_tracker, others_open, page_in_champ_select,
send, with_bans_and_ally,
};
use super::page_fixtures::{center, draw, open_page_in_season, open_page_with_tracker, show};
use crate::card_images::tests::TestDir;
use gpui_kit::{
Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px, size,
};
#[gpui::test]
async fn the_banner_forgets_the_previous_scope_while_the_champ_select_loads(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("banner-scope");
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
cx.condition(&page, |p, _| p.stats.is_some()).await;
show(
&page,
&mut window,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
);
assert_eq!(
banner(&page, &mut window).title.text.as_ref(),
"2 / 5 champions validés"
);
send(&page, &mut window, &frames()[0]);
let text = banner(&page, &mut window);
assert_eq!(text.title.text.as_ref(), "Sélection des champions");
assert!(!text.season.contains('/'));
assert_eq!(text.splash, None);
assert!(ring_ticks(&page, &mut window).is_empty());
// Its own statistics arrive.
cx.condition(&page, |p, _| p.stats.is_some()).await;
assert!(banner(&page, &mut window).season.contains("1 / 9"));
}
#[gpui::test]
fn scrolling_the_home_moves_the_ring_as_it_is_and_gives_back_a_splash_out_of_view(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("banner-scrolled");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
banner_statistics(rows_with_splashes(dir.path()), vec![2, 1], None),
);
cx.simulate_resize(size(px(600.), px(340.)));
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
let splash = loaded_splashes(&page, cx);
let ring = page.read_with(cx, |p, _| p.ring.clone());
let tessellations =
|cx: &mut VisualTestContext| ring.read_with(cx, |ring, _| ring.tessellations.get());
let shapes = tessellations(cx);
let scroll = |cx: &mut VisualTestContext, by: f32| {
let at = center(cx, "banner");
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(by))),
..Default::default()
});
draw(cx);
};
// The ring moves with the column, as it is.
let top = cx.debug_bounds("ring").unwrap().top();
scroll(cx, -30.);
assert!(cx.debug_bounds("ring").unwrap().top() < top);
assert_eq!(tessellations(cx), shapes);
// Down to the grid: the banner is out of view, and so is its splash, from the atlas too.
scroll(cx, -2000.);
assert!(held_splashes(&page, cx).is_empty());
assert!(!in_atlas(cx, &splash[0]));
// Back up: it comes back.
let at = center(cx, "card-1");
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(4000.))),
..Default::default()
});
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
}
#[gpui::test]
async fn the_champ_select_splash_follows_the_hand_and_other_champions(cx: &mut TestAppContext) {
let dir = TestDir::new("champ-select-splashes");
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
let mut stats = page.read_with(cx, |p, _| p.home_statistics().unwrap().clone());
for row in &mut stats.rows {
row.splash = Some(splash(dir.path(), &row.champion.key));
}
show(&page, cx, stats);
cx.simulate_resize(size(px(1280.), px(1300.)));
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx), ["Briar.50.30.jpg"]);
click_others(cx);
let hover = |cx: &mut VisualTestContext, card| {
let at = center(cx, card);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw_loaded(cx);
};
let finish_fade = |cx: &mut VisualTestContext| {
cx.update(|_, cx| {
cx.background_executor()
.advance_clock(std::time::Duration::from_millis(501))
});
draw_loaded(cx);
};
// The first hover starts a fade. Crossing the rest of the hand leaves
// those two images intact until it ends, even over an Other champion.
for card in ANVIL_CARDS[1..].iter().copied().chain(["card-103"]) {
hover(cx, card);
assert_eq!(
held_splashes(&page, cx),
["Briar.50.30.jpg", "LeeSin.50.30.jpg"]
);
}
let builds = page.read_with(cx, |p, cx| p.anvil_grid.read(cx).card_builds);
finish_fade(cx);
assert_eq!(
held_splashes(&page, cx),
["LeeSin.50.30.jpg", "Ahri.50.30.jpg"]
);
finish_fade(cx);
assert_eq!(held_splashes(&page, cx), ["Ahri.50.30.jpg"]);
assert_eq!(
page.read_with(cx, |p, cx| p.anvil_grid.read(cx).card_builds),
builds
);
hover(cx, "banner-title");
finish_fade(cx);
assert_eq!(held_splashes(&page, cx), ["Briar.50.30.jpg"]);
// With every card grey, the first card in the chosen sort supplies the art.
let mut pick = with_bans_and_ally(&[233], 233);
pick.anvil_champions = Some(vec![16, 64]);
send(&page, cx, &pick);
draw_loaded(cx);
assert_eq!(held_splashes(&page, cx).last().unwrap(), "LeeSin.50.30.jpg");
}
#[gpui::test]
async fn the_tick_stays_with_the_grid_that_lit_it(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
cx.simulate_resize(size(px(1280.), px(1300.)));
draw(cx);
click_others(cx);
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
let hover = |cx: &mut VisualTestContext, id: &'static str| {
let at = center(cx, id);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
};
// From an Anvil champion straight to a card of « Autres champions », and back.
hover(cx, "card-233");
assert_eq!(lit(cx), Some(233));
hover(cx, "card-103");
assert_eq!(lit(cx), Some(103));
hover(cx, "card-233");
assert_eq!(lit(cx), Some(233));
// Folding « Autres champions » under a still pointer leaves the Anvil champion's tick
// lit: the grid it replaces only puts out a tick it lit.
page.update(cx, |page, cx| page.toggle_others(cx));
draw(cx);
assert!(!others_open(&page, cx));
assert_eq!(lit(cx), Some(233));
// A key press ends every hover for GPUI until the pointer moves (the card's sheet goes
// too): the tick follows the card.
cx.update(|window, cx| {
let focus = page.read(cx).others_focus.clone();
focus.focus(window, cx);
});
activate(cx, "enter");
assert!(others_open(&page, cx));
assert_eq!(lit(cx), None);
hover(cx, "card-233");
assert_eq!(lit(cx), Some(233));
}
+351
View File
@@ -0,0 +1,351 @@
use super::page_fixtures::{
animations, center, draw, focus_sort, frame_after, hover, open_page_in_season, press, rise,
settle, sheet, sheet_champions, sheet_ids, show, statistics,
};
use arena_tracker_core::ChampionState;
use gpui_kit::{Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px};
#[gpui::test]
fn the_sheet_shows_on_hover_with_the_date_of_a_completed_champion_only(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
assert!(sheet_ids(cx, 12).is_empty(), "a sheet is built at rest");
let completed = center(cx, "card-1");
cx.simulate_mouse_move(completed, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 12), [1]);
assert_eq!(sheet(cx, 1), Some(true));
let remaining = center(cx, "card-2");
cx.simulate_mouse_move(remaining, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 12), [2]);
assert_eq!(sheet(cx, 2), Some(false));
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
assert!(
sheet_ids(cx, 12).is_empty(),
"the sheet stays after the pointer left"
);
}
// The card under the pointer rises over the grid, from where the grid placed it, and settles
// back once left: the grid stays cached through it all, no card is built and no statistics
// are computed, and no frame is asked for once the cards are still.
#[gpui::test]
fn hovering_a_card_lifts_it_over_the_grid_which_is_not_drawn_again(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
settle(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let generation = page.read_with(cx, |page, _| page.stats_generation);
let built = |cx: &mut VisualTestContext| {
grid.read_with(cx, |grid, _| {
(grid.renders, grid.card_builds, grid.set_cards_calls)
})
};
let at_rest = built(cx);
hover(cx, "card-2");
assert_eq!(rise(cx, 2), Some(0.), "it jumped");
frame_after(cx, 100);
let rising = rise(cx, 2).expect("the card is not lifted");
assert!(rising > 0. && rising < 10., "{rising}");
// Its sheet slides up while it rises.
assert!(cx.debug_bounds("sheet-2").is_some());
settle(cx);
assert_eq!(rise(cx, 2), Some(10.));
// To the next card: it rises while the one left settles back.
hover(cx, "card-3");
frame_after(cx, 100);
assert!(rise(cx, 2).is_some_and(|rise| rise > 0. && rise < 10.));
assert!(rise(cx, 3).is_some_and(|rise| rise > 0. && rise < 10.));
settle(cx);
assert_eq!(rise(cx, 2), None, "the card left stayed lifted");
assert_eq!(rise(cx, 3), Some(10.));
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
settle(cx);
assert_eq!(rise(cx, 3), None);
frame_after(cx, 16);
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(asked, 0, "a frame is asked for at rest");
assert_eq!(built(cx), at_rest, "the grid was drawn again");
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
#[gpui::test]
fn a_greyed_card_rises_less_with_the_same_sheet(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
// The first champion is Completed: greyed.
hover(cx, "card-1");
assert_eq!(sheet_ids(cx, 12), [1]);
assert_eq!(sheet(cx, 1), Some(true));
assert_eq!(rise(cx, 1), Some(4.));
}
#[gpui::test]
fn without_animations_the_sheet_shows_at_once_and_the_card_stays_put(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
settle(cx);
animations(cx, false);
draw(cx);
hover(cx, "card-2");
assert_eq!(rise(cx, 2), Some(0.));
assert!(cx.debug_bounds("sheet-2").is_some(), "the sheet waits");
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(asked, 0, "a frame is asked for");
// Left, it is gone at once.
hover(cx, "card-3");
assert_eq!(rise(cx, 2), None);
assert_eq!(rise(cx, 3), Some(0.));
}
// A lifted card shows the grid's card as it is now: a first top 1 meanwhile greys it and
// dates its sheet.
#[gpui::test]
fn a_lifted_card_shows_its_figures_as_they_change(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
hover(cx, "card-2");
assert_eq!(sheet_ids(cx, 12), [2]);
assert_eq!(sheet(cx, 2), Some(false));
assert_eq!(rise(cx, 2), Some(10.));
let mut rows = sheet_champions(12);
rows[1].state = Some(ChampionState::Completed);
rows[1].challenge = rows[0].challenge;
show(&page, cx, statistics(2, 12, rows));
draw(cx);
assert_eq!(sheet_ids(cx, 12), [2]);
assert_eq!(sheet(cx, 2), Some(true));
assert_eq!(rise(cx, 2), Some(4.));
}
// A card the keyboard lifted goes down as soon as the pointer moves.
#[gpui::test]
fn the_pointer_takes_over_from_the_keyboard(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
focus_sort(&page, cx);
press(cx, "tab");
assert_eq!(sheet_ids(cx, 12), [1]);
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
assert!(
sheet_ids(cx, 12).is_empty(),
"the keyboard's card stayed lifted"
);
}
// A wheel at the top of the list moves no card: the card is put down all the same, while
// its tick stays lit as it is still under the pointer.
#[gpui::test]
fn a_wheel_puts_the_card_down_even_at_the_end_of_the_list(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
hover(cx, "card-2");
settle(cx);
assert_eq!(rise(cx, 2), Some(10.));
let at = center(cx, "card-2");
cx.simulate_event(ScrollEvent {
position: at,
delta: ScrollDelta::Pixels(point(px(0.), px(400.))),
..Default::default()
});
draw(cx);
assert_eq!(rise(cx, 2), None);
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(2));
}
#[gpui::test]
fn turning_animations_off_puts_a_rising_card_where_it_goes(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 12, sheet_champions(12)));
draw(cx);
hover(cx, "card-2");
frame_after(cx, 50);
animations(cx, false);
draw(cx);
assert_eq!(rise(cx, 2), Some(0.));
assert!(cx.debug_bounds("sheet-2").is_some());
// The frame asked for before is the last.
frame_after(cx, 16);
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(asked, 0, "a frame is asked for");
}
#[gpui::test]
fn scrolling_the_grid_hides_the_sheet_of_the_card_that_was_under_the_pointer(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
let over = center(cx, "card-1");
cx.simulate_mouse_move(over, None, Modifiers::none());
draw(cx);
assert_eq!(sheet_ids(cx, 170), [1]);
cx.simulate_event(ScrollEvent {
position: over,
delta: ScrollDelta::Pixels(point(px(0.), px(-20.))),
..Default::default()
});
draw(cx);
// At once, with no card settling back from where it was.
assert!(
cx.debug_bounds("lifted-1").is_none(),
"the card stayed lifted"
);
assert!(sheet_ids(cx, 170).is_empty(), "the sheet stuck to its card");
}
#[gpui::test]
fn the_sheet_shows_on_keyboard_focus_and_follows_tab(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 40, sheet_champions(40)));
draw(cx);
focus_sort(&page, cx);
draw(cx);
assert!(sheet_ids(cx, 40).is_empty());
// From the sort selector, the last stop before the cards, Tab reaches the first card, the Completed one.
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [1]);
assert_eq!(sheet(cx, 1), Some(true));
// The next card: the previous sheet goes, the remaining champion has no date.
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [2]);
assert_eq!(sheet(cx, 2), Some(false));
press(cx, "tab");
assert_eq!(sheet_ids(cx, 40), [3]);
// Shift-Tab goes back.
press(cx, "shift-tab");
press(cx, "shift-tab");
assert_eq!(sheet_ids(cx, 40), [1]);
assert_eq!(sheet(cx, 1), Some(true));
}
#[gpui::test]
fn tab_scrolls_the_row_of_the_next_card_into_view(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
focus_sort(&page, cx);
draw(cx);
assert!(
cx.debug_bounds("card-25").is_none(),
"card 25 is already built"
);
assert_eq!(grid.read_with(cx, |grid, _| grid.scrolled()), px(0.));
// Rows of 6: the 25th card opens the 5th row, below what 860 px shows.
for _ in 0..25 {
press(cx, "tab");
}
assert_eq!(sheet_ids(cx, 170), [25]);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
let bounds = cx.debug_bounds("card-25").expect("the row was not built");
assert!(bounds.bottom() <= px(860.), "{bounds:?}");
// Back across the row boundary, upwards.
for _ in 0..6 {
press(cx, "shift-tab");
}
assert_eq!(sheet_ids(cx, 170), [19]);
let bounds = cx.debug_bounds("card-19").expect("the row was not built");
assert!(bounds.origin.y >= px(0.), "{bounds:?}");
}
#[gpui::test]
fn tab_leaves_the_grid_after_its_last_card(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 3, sheet_champions(3)));
draw(cx);
focus_sort(&page, cx);
for _ in 0..3 {
press(cx, "tab");
}
assert_eq!(sheet_ids(cx, 3), [3]);
press(cx, "tab");
assert!(sheet_ids(cx, 3).is_empty(), "the focus stayed in the grid");
}
// Hovering the cards does not draw the grid again; tabbing over them does (GPUI draws the
// whole window when the focus moves). Neither builds the cards again nor computes any
// statistics.
#[gpui::test]
fn showing_a_sheet_does_not_rebuild_the_cards_nor_recompute_the_statistics(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 170, sheet_champions(170)));
draw(cx);
// The Completed card's crown is loaded, which draws the grid again.
settle(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let generation = page.read_with(cx, |page, _| page.stats_generation);
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = grid.read_with(cx, |grid, _| grid.renders);
for id in ["card-1", "card-2", "card-1"] {
let card = center(cx, id);
cx.simulate_mouse_move(card, None, Modifiers::none());
draw(cx);
}
settle(cx);
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
focus_sort(&page, cx);
for _ in 0..10 {
press(cx, "tab");
}
// The key presses ended the pointer's hover: the focused card alone shows its sheet.
assert_eq!(sheet_ids(cx, 170), [10]);
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
@@ -0,0 +1,224 @@
use super::champ_select_fixtures::{
ANVIL_A_TO_Z, OTHERS_A_TO_Z, anvil_cards, capture, click_others, frames, ids, leave,
others_cards, others_open, page_in_champ_select, read_champ_select, scroll_champ_select_down,
search_others, send,
};
use super::page_fixtures::{
center, champions, count_hovers, draw, grid_names, open_page_in_season, settle, show,
statistics,
};
use crate::champion_table::tests::row;
use crate::page::Tab;
use arena_tracker_core::ChampSelectReader;
use gpui_kit::{Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px};
use std::cell::RefCell;
use std::rc::Rc;
// As the home grid's test: hovering the cards of « Autres champions » does not draw its grid
// again, and neither it nor scrolling costs statistics or cards. (The capture's catalog is too short for
// the list to scroll: the wheel still reaches the grid, which is what clears its hover.)
#[gpui::test]
async fn hovering_or_scrolling_others_does_not_recompute_the_statistics(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
click_others(&mut window);
scroll_champ_select_down(&mut window);
let cx = &mut window;
let grid = page.read_with(cx, |p, _| p.others_grid.clone());
let generation = page.read_with(cx, |p, _| p.stats_generation);
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(set_cards > 0 && renders > 0);
let hovers = count_hovers(&grid, cx);
for id in ["card-103", "card-12", "card-103"] {
let card = center(cx, id);
cx.simulate_mouse_move(card, None, Modifiers::none());
draw(cx);
}
settle(cx);
assert!(hovers.get() > 0, "no card was hovered");
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
let over = center(cx, "card-103");
cx.simulate_event(ScrollEvent {
position: over,
delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
..Default::default()
});
draw(cx);
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
assert_eq!(
page.read_with(cx, |p, _| p.stats_generation),
generation,
"the statistics were computed again"
);
assert!(!page.read_with(cx, |p, _| p.stats_job.running()));
}
#[gpui::test]
async fn the_search_of_others_filters_only_that_section(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
click_others(&mut window);
let anvil_before = anvil_cards(&page, &mut window);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
search_others(&page, &mut window, "ahr");
assert_eq!(grid_names(&grid, &mut window), ["Ahri"]);
// By alias: « cow » is Alistar's.
search_others(&page, &mut window, "cow");
assert_eq!(grid_names(&grid, &mut window), ["Alistar"]);
// An Anvil champion is not in this section, whoever searches for it.
search_others(&page, &mut window, "xz");
assert!(grid_names(&grid, &mut window).is_empty());
assert!(window.debug_bounds("no-champion").is_some());
// The anvil row and the home's search are intact.
assert_eq!(anvil_cards(&page, &mut window), anvil_before);
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
page.read_with(&window, |p, cx| {
assert!(p.home_search_input.read(cx).value().is_empty())
});
search_others(&page, &mut window, "");
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
}
#[gpui::test]
async fn a_new_champ_select_folds_others_and_empties_its_search(cx: &mut TestAppContext) {
let frames = frames();
let (page, mut window) = page_in_champ_select(cx, &frames[0]).await;
let fresh = |window: &mut VisualTestContext| {
page.read_with(window, |p, cx| {
assert!(!p.others_open);
assert!(p.others_search_input.read(cx).value().is_empty());
assert_eq!(p.others_grid.read(cx).renders, 0);
assert!(p.others_grid.read(cx).shown_cards().is_empty());
})
};
// The frames of the same champ select keep it open, with its search.
click_others(&mut window);
search_others(&page, &mut window, "ahr");
send(&page, &mut window, &frames[1]);
draw(&mut window);
assert!(others_open(&page, &mut window));
assert_eq!(others_cards(&page, &mut window).len(), 1);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
assert_eq!(grid_names(&grid, &mut window), ["Ahri"]);
// Leaving, then entering again.
leave(&page, &mut window);
draw(&mut window);
fresh(&mut window);
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
fresh(&mut window);
assert!(window.debug_bounds("others-toggle").is_some());
assert!(window.debug_bounds("card-103").is_none());
// The champ select of another Riot ID.
click_others(&mut window);
search_others(&page, &mut window, "cow");
let live = Some(("Autre#EUW".to_string(), frames[0].clone()));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(live), w, cx)
})
});
fresh(&mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
fresh(&mut window);
assert!(window.debug_bounds("card-103").is_none());
}
#[gpui::test]
async fn others_lists_every_champion_when_the_anvil_list_is_unknown(cx: &mut TestAppContext) {
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(&ChampSelectReader::default(), session, None);
let (page, mut window) = page_in_champ_select(cx, &pick).await;
page.read_with(&window, |p, _| {
assert_eq!(p.others_title(), "Tous les champions")
});
click_others(&mut window);
let all: Vec<u32> = page.read_with(&window, |p, _| {
p.stats
.as_ref()
.unwrap()
.rows
.iter()
.map(|r| r.champion.id)
.collect()
});
assert_eq!(all.len(), 9);
assert_eq!(ids(&others_cards(&page, &mut window)), all);
assert!(anvil_cards(&page, &mut window).is_empty());
assert!(window.debug_bounds("card-233").is_some());
}
#[gpui::test]
fn others_builds_only_the_visible_cards_and_hovering_elsewhere_does_not_draw_them(
cx: &mut TestAppContext,
) {
let (page, mut window) = open_page_in_season(cx);
send(&page, &mut window, &frames()[0]);
// The statistics of the Account, as the worker would give them: 170 champions, most
// of them without an anvil.
show(&page, &mut window, statistics(0, 170, champions(170)));
draw(&mut window);
click_others(&mut window);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
let (built, renders) = grid.read_with(&window, |grid, _| (grid.card_builds, grid.renders));
// 170 champions less the Anvil ones the statistics know: 5, 16, 64 and 68.
assert_eq!(
grid.read_with(&window, |grid, _| grid.shown_cards().len()),
166
);
assert!(built > 0 && built <= 8 * 6, "{built} cards built for 170");
assert!(renders > 0);
// Hovering the header, outside the cards, draws the page and not the cards.
let toggle = center(&mut window, "others-toggle");
for dx in 0..5 {
window.simulate_mouse_move(
point(toggle.x + px(dx as f32 * 7.), toggle.y),
None,
Modifiers::none(),
);
draw(&mut window);
}
assert_eq!(grid.read_with(&window, |grid, _| grid.renders), renders);
}
#[gpui::test]
fn no_champ_select_changes_nothing(cx: &mut TestAppContext) {
let (page, mut window) = open_page_in_season(cx);
let entered = Rc::new(RefCell::new(Vec::new()));
let _events = window.update(|_, cx| {
let entered = entered.clone();
cx.subscribe(
&page,
move |_, transition: &crate::page::ChampSelectTransition, _| {
entered.borrow_mut().push(transition.entered)
},
)
});
show(&page, &mut window, statistics(0, 1, vec![row("Ahri")]));
let generation = page.read_with(&window, |p, _| p.stats_generation);
leave(&page, &mut window);
draw(&mut window);
assert!(entered.borrow().is_empty());
page.read_with(&window, |p, _| {
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.stats_generation, generation);
assert_eq!(p.anvil_line(), None);
});
assert!(window.debug_bounds("home-tools").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
}
@@ -0,0 +1,372 @@
use super::banner_fixtures::{banner, splash};
use super::champ_select_fixtures::{
ANVIL, ANVIL_A_TO_Z, anvil_cards, bounds, capture, frames, ids, joueur_tracker,
joueur_tracker_with, leave, page_in_champ_select, places, read_champ_select, reasons, send,
with_bans_and_ally,
};
use super::page_fixtures::{center, draw, open_page, open_page_with_tracker, show, switch_tab};
use crate::card::{ASPECT, Reason};
use crate::card_images::tests::TestDir;
use crate::page::Tab;
use arena_tracker_core::{ChampSelectReader, StateFilter};
use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, point, px};
#[gpui::test]
async fn the_champ_select_banner_follows_the_arena_capture(cx: &mut TestAppContext) {
let dir = TestDir::new("champ-select-banner");
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let mut stats = page.read_with(&window, |p, _| p.home_statistics().unwrap().clone());
for row in &mut stats.rows {
row.splash = Some(splash(dir.path(), &row.champion.key));
}
show(&page, &mut window, stats);
page.update(&mut window, |p, cx| {
p.home_season = Some("Saison 2 2026".into());
p.prepare_champ_select(cx);
});
// The splash the banner shows, or fades to.
let art = |window: &mut VisualTestContext| {
page.read_with(window, |p, cx| {
let target = p.banner_art.read(cx).target.clone()?;
Some(target.path.file_name()?.to_string_lossy().into_owned())
})
};
let ring_anvil = |window: &mut VisualTestContext| {
page.read_with(window, |p, cx| p.ring.read(cx).anvil().map(<[u32]>::to_vec))
};
let check = |window: &mut VisualTestContext, frame: usize, k: usize, splash: &str| {
let text = banner(&page, window);
assert_eq!(
text.season.as_ref(),
"SAISON 2 · 2026 · 1 / 9 validés",
"frame {frame}"
);
assert_eq!(text.title.text.as_ref(), "Sélection des champions");
let plural = if k > 1 { "s" } else { "" };
assert_eq!(
text.detail.text.as_ref(),
format!("Champions de l'Enclume · {k} à valider et disponible{plural}"),
"frame {frame}"
);
assert!(text.last_match.is_none());
assert_eq!(
art(window).as_deref(),
Some(format!("{splash}.50.30.jpg").as_str()),
"frame {frame}"
);
};
// The capture's own hand: Soraka is validated, Lee Sin, Rumble and Xin Zhao are not
// offered, so only Briar is left. The bans (Alistar, Swain) and the ally's Morgana are
// not in the hand: k stays at 1, before and after the ally's confirmation.
draw(&mut window);
let first = bounds(&mut window);
for (frame, pick) in frames().iter().enumerate() {
send(&page, &mut window, pick);
draw(&mut window);
check(&mut window, frame, 1, "Briar");
let places = places(&page, &mut window, &first, &ANVIL_A_TO_Z);
assert_eq!(bounds(&mut window), places, "frame {frame}");
assert_eq!(ring_anvil(&mut window), Some(ANVIL.to_vec()));
}
// A hovered card supplies the illustration; without one, the default comes back.
let at = center(&mut window, "card-64");
window.simulate_mouse_move(at, None, Modifiers::none());
draw(&mut window);
assert_eq!(art(&mut window).as_deref(), Some("LeeSin.50.30.jpg"));
window.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(&mut window);
assert_eq!(art(&mut window).as_deref(), Some("Briar.50.30.jpg"));
// The same frames with the banned Alistar and the ally's Morgana in the hand (A to Z:
// Alistar, Briar, Morgana, Soraka): Alistar's ban, then Morgana's confirmation, lower k
// and move the default illustration on. The cards stay.
let hand = [12, 16, 25, 233];
let cards = ["card-12", "card-233", "card-25", "card-16"];
let mut picks = frames();
for pick in &mut picks {
pick.anvil_champions = Some(hand.to_vec());
}
let hand_bounds = |window: &mut VisualTestContext| -> Vec<_> {
cards
.iter()
.map(|id| window.debug_bounds(id).expect("the card is not drawn"))
.collect()
};
send(&page, &mut window, &picks[0]);
draw(&mut window);
let first = hand_bounds(&mut window);
let expected = [
(3, "Alistar"),
(2, "Briar"),
(2, "Briar"),
(1, "Briar"),
(1, "Briar"),
];
for (frame, (pick, (k, splash))) in picks.iter().zip(expected).enumerate() {
send(&page, &mut window, pick);
draw(&mut window);
check(&mut window, frame, k, splash);
let places = places(&page, &mut window, &first, &[12, 233, 25, 16]);
assert_eq!(hand_bounds(&mut window), places, "frame {frame}");
assert_eq!(ring_anvil(&mut window), Some(hand.to_vec()));
}
// A list the client does not send: #74's message, and no tick dimmed.
let mut unknown = picks[4].clone();
unknown.anvil_champions = None;
send(&page, &mut window, &unknown);
assert_eq!(
banner(&page, &mut window).detail.text.as_ref(),
"Champions de l'Enclume non communiqués par le client"
);
assert_eq!(ring_anvil(&mut window), None);
leave(&page, &mut window);
assert_eq!(ring_anvil(&mut window), None);
}
#[gpui::test]
async fn the_arena_capture_fills_the_anvil_row_in_the_homes_order(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
// The home's own order, which the row follows.
let home_order: Vec<u32> = page.read_with(&window, |p, _| {
let rows = p.stats.as_ref().unwrap().rows.iter();
rows.map(|row| row.champion.id)
.filter(|id| ANVIL.contains(id))
.collect()
});
assert_eq!(home_order, ANVIL_A_TO_Z);
let frames = frames();
assert_eq!(frames.len(), 5);
send(&page, &mut window, &frames[0]);
// Until the statistics are there, the row is replaced by what is missing.
page.read_with(&window, |p, _| {
assert_eq!(p.anvil_line().as_deref(), Some("Compte indisponible"))
});
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
let first = bounds(&mut window);
// Never greyed by the champ select: 233 and 16 are offered, the rest is not offered.
let baseline = [
(233, vec![]),
(64, vec![Reason::NotOffered]),
(68, vec![Reason::NotOffered]),
(16, vec![Reason::Completed]),
(5, vec![Reason::NotOffered]),
];
for (frame, pick) in frames.iter().enumerate() {
if frame > 0 {
send(&page, &mut window, pick);
}
draw(&mut window);
let cards = anvil_cards(&page, &mut window);
// 12 (banned), 25 (ally) and 50 (banned) are not Anvil champions: never in the row.
assert_eq!(ids(&cards), ANVIL_A_TO_Z, "frame {frame}");
for (id, expected) in &baseline {
assert_eq!(
&reasons(&cards, *id),
expected,
"frame {frame}, champion {id}"
);
}
// The cards keep their place.
let places = places(&page, &mut window, &first, &ANVIL_A_TO_Z);
assert_eq!(bounds(&mut window), places, "frame {frame}");
}
// The marks come with the Challenge of the signed-in Account.
let cards = anvil_cards(&page, &mut window);
let mark = |id| cards.iter().find(|c| c.id == id).unwrap().marks;
assert!(mark(16).completed && mark(16).won);
assert!(mark(233).played && !mark(233).completed);
assert!(!mark(64).played);
// Reasons add up: 16 is Completed and banned, 233 banned and confirmed by an ally. The
// labels change and the cards stay.
send(&page, &mut window, &with_bans_and_ally(&[16, 233, 12], 233));
draw(&mut window);
let cards = anvil_cards(&page, &mut window);
assert_eq!(ids(&cards), ANVIL_A_TO_Z);
assert_eq!(reasons(&cards, 16), [Reason::Completed, Reason::Banned]);
assert_eq!(reasons(&cards, 233), [Reason::Banned, Reason::TakenByAlly]);
assert_eq!(reasons(&cards, 64), [Reason::NotOffered]);
// Briar, taken by an ally, rests 8 px lower than the others, which do not move.
let mut lowered = first.clone();
lowered[0].origin.y += px(8.);
assert_eq!(bounds(&mut window), lowered);
// The cards are as big as the home's, on one row of six at 1280 px.
let (width, height) = (first[0].size.width.as_f32(), first[0].size.height.as_f32());
assert!((height - width / ASPECT).abs() < 1., "{width} x {height}");
assert_eq!(first[0].origin.y, first[1].origin.y);
let gap = (first[1].origin.x - first[0].origin.x).as_f32() - width;
assert!((gap - 14.).abs() < 1., "gap {gap}");
}
#[gpui::test]
async fn the_champ_select_takes_the_home_and_gives_it_back_as_it_was(cx: &mut TestAppContext) {
use arena_tracker_core::SeasonScope;
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let (input, home_grid) = page.read_with(&window, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
window.update(|w, cx| {
page.update(cx, |p, cx| {
// Autre, on « Toutes les Saisons », with a filter and a search on the home.
p.set_tab(Tab::Statistics, w, cx);
p.pinned = Some("Autre".into());
p.season = SeasonScope::AllSeasons;
p.home_filter = StateFilter::Completed;
p.reload(w, cx);
});
input.update(cx, |input, cx| input.set_value("ah", w, cx));
});
page.read_with(&window, |p, _| {
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.tab, Tab::Statistics);
});
draw(&mut window);
let frames = frames();
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
// The Challenge of the signed-in Account in the current Season, whatever the
// Statistics tab shows.
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.displayed().unwrap().puuid, "Joueur");
assert_eq!(p.home_season.as_deref(), Some("Saison"));
assert_eq!(p.banner.season.as_ref(), "SAISON · 1 / 9 validés");
assert_eq!(p.banner.title.text.as_ref(), "Sélection des champions");
assert!(p.stats.as_ref().unwrap().challenge.is_some());
});
// The row is there; the grid, its filters and its search are not.
assert!(window.debug_bounds("anvil-row").is_some());
assert!(window.debug_bounds("card-233").is_some());
assert!(window.debug_bounds("home-tools").is_none());
assert!(window.debug_bounds("card-103").is_none());
// « Statistiques » is out of reach during the champ select.
let statistics = center(&mut window, "tab-statistics");
window.simulate_click(statistics, Modifiers::none());
switch_tab(&page, &mut window, Tab::Statistics);
assert_eq!(page.read_with(&window, |p, _| p.tab), Tab::Challenge);
// Bans and ally picks are the champ select's.
send(&page, &mut window, &with_bans_and_ally(&[16, 233], 233));
let cards = anvil_cards(&page, &mut window);
assert_eq!(reasons(&cards, 233), [Reason::Banned, Reason::TakenByAlly]);
leave(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, cx| {
// As before the champ select, with « Tous » and no search on the home.
assert_eq!(p.viewed().unwrap().puuid, "Autre");
assert_eq!(p.season, SeasonScope::AllSeasons);
assert_eq!(p.tab, Tab::Challenge);
assert_eq!(p.home_filter, StateFilter::All);
assert!(p.home_search_input.read(cx).value().is_empty());
assert_eq!(p.home_shown_count.as_ref(), "9");
assert_eq!(p.home_grid.read(cx).names().len(), 9);
assert_eq!(p.banner.title.text.as_ref(), "0 / 9 champions validés");
assert!(p.anvil_grid.read(cx).names().is_empty());
});
assert_eq!(
home_grid.read_with(&window, |grid, _| grid.names().len()),
9
);
assert!(window.debug_bounds("home-tools").is_some());
assert!(window.debug_bounds("card-103").is_some());
assert!(window.debug_bounds("anvil-row").is_none());
// Another champ select starts clean.
send(&page, &mut window, &frames[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
let cards = anvil_cards(&page, &mut window);
assert_eq!(reasons(&cards, 16), [Reason::Completed]);
assert_eq!(reasons(&cards, 233), []);
assert_eq!(ids(&cards), ANVIL_A_TO_Z);
}
#[gpui::test]
async fn an_unknown_or_empty_anvil_list_is_said_soberly(cx: &mut TestAppContext) {
cx.executor().allow_parking();
for (anvil, line) in [
(None, "Champions de l'Enclume non communiqués par le client"),
(
Some("[]"),
"Aucun Champion de l'Enclume dans cette sélection",
),
] {
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(
&ChampSelectReader::default(),
session,
anvil.map(str::to_string),
);
send(&page, &mut window, &pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.anvil_line().as_deref(), Some(line))
});
// No row, and no champion is presented as without an anvil.
assert!(anvil_cards(&page, &mut window).is_empty());
assert_eq!(
window.debug_bounds("anvil-notice").is_some(),
anvil.is_some()
);
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("card-103").is_none());
assert!(window.debug_bounds("card-16").is_none());
}
}
#[gpui::test]
async fn missing_statistics_are_said_once_and_leave_nothing_to_browse(cx: &mut TestAppContext) {
cx.executor().allow_parking();
// No current Season: the header says so, and the Anvil area does not say it again.
let (page, mut window) = open_page(cx);
send(&page, &mut window, &frames()[0]);
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(
p.stats_notice(),
Some(crate::page::home::StatsNotice::NoSeason)
);
});
assert!(window.debug_bounds("no-season").is_some());
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("others-toggle").is_none());
// The statistics are on their way: the area says so, and there is nothing to browse yet.
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker_with(true));
send(&page, &mut window, &frames()[0]);
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(
p.anvil_line().as_deref(),
Some("Chargement des statistiques…")
);
});
assert!(window.debug_bounds("no-season").is_none());
assert!(window.debug_bounds("anvil-notice").is_some());
assert!(window.debug_bounds("others-toggle").is_none());
// Once they are there, the section is offered.
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("others-toggle").is_some());
}
@@ -0,0 +1,473 @@
use super::page_fixtures::{MATCH_1750, center, draw, frame_after, open_page_with_tracker, season};
use crate::card::{Card, Reason};
use crate::card_images::tests::PORTRAIT_JPEG;
use crate::page::Page;
use arena_tracker_core::{
Account, ChampSelect, ChampSelectReader, Champion, ChampionCatalog, ChampionSource,
ClientError, MatchHistorySource, SourceError, Tracker,
};
use gpui_kit::{
Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, ScrollDelta, ScrollEvent,
TestAppContext, VisualTestContext, WindowVisibility, point, px,
};
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
pub(super) const JOUEUR: &str = "Joueur#EUW";
pub(super) const ANVIL: [u32; 5] = [233, 64, 5, 16, 68];
/// The Anvil champions of the capture in the order of the home: A to Z by name.
pub(super) const ANVIL_A_TO_Z: [u32; 5] = [233, 64, 68, 16, 5];
pub(super) const ANVIL_CARDS: [&str; 5] = ["card-233", "card-64", "card-68", "card-16", "card-5"];
/// (id, key, name): the champions of the capture.
pub(super) const CATALOG: [(u32, &str, &str); 9] = [
(12, "Alistar", "Alistar"),
(16, "Soraka", "Soraka"),
(25, "Morgana", "Morgana"),
(50, "Swain", "Swain"),
(64, "LeeSin", "Lee Sin"),
(5, "XinZhao", "Xin Zhao"),
(68, "Rumble", "Rumble"),
(103, "Ahri", "Ahri"),
(233, "Briar", "Briar"),
];
/// Joueur completed 16 (a top 1) and played 233 (a 4th place).
pub(super) struct JoueurHistory;
impl MatchHistorySource for JoueurHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: game_name.into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
})
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
Ok(if puuid == "Joueur" && queue_id == 1750 && start == 0 {
vec!["EUW1_1".into(), "EUW1_2".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, id: &str) -> Result<String, SourceError> {
let (champion, name, placement) = match id {
"EUW1_1" => (16, "Soraka", 1),
"EUW1_2" => (233, "Briar", 4),
_ => return Err(SourceError::NotFound),
};
let raw = MATCH_1750.replace("fixture-puuid-self", "Joueur");
let mut payload: Value = serde_json::from_str(&raw).unwrap();
payload["metadata"]["matchId"] = id.into();
for player in payload["info"]["participants"].as_array_mut().unwrap() {
if player["puuid"] == "Joueur" {
player["championId"] = champion.into();
player["championName"] = name.into();
player["placement"] = placement.into();
player["win"] = (placement <= 3).into();
}
}
Ok(payload.to_string())
}
fn champion_mastery(&self, _: &str, puuid: &str) -> Result<Vec<(u32, u64)>, SourceError> {
Ok(if puuid == "Joueur" {
MASTERY.to_vec()
} else {
Vec::new()
})
}
}
/// Joueur's Mastery Points. Xin Zhao (5) and Morgana (25) are missing from the list: known,
/// no points.
pub(super) const MASTERY: [(u32, u64); 7] = [
(64, 120_000),
(16, 40_000),
(50, 9_000),
(233, 5_000),
(68, 900),
(12, 300),
(103, 100),
];
/// The Anvil champions of the capture by Mastery Points, then those without an anvil.
pub(super) const ANVIL_BY_MASTERY: [u32; 5] = [64, 16, 233, 68, 5];
pub(super) const OTHERS_BY_MASTERY: [u32; 4] = [50, 12, 103, 25];
pub(super) const ALL_A_TO_Z: [&str; 9] = [
"Ahri", "Alistar", "Briar", "Lee Sin", "Morgana", "Rumble", "Soraka", "Swain", "Xin Zhao",
];
pub(super) struct Catalog;
impl ChampionSource for Catalog {
fn latest_version(&self) -> Result<String, SourceError> {
Ok("1.0".into())
}
fn catalog(&self, version: &str) -> Result<ChampionCatalog, SourceError> {
Ok(ChampionCatalog {
version: version.into(),
champions: CATALOG
.iter()
.map(|&(id, key, name)| Champion {
id,
key: key.into(),
name: name.into(),
})
.collect(),
})
}
fn portrait(&self, _: &str, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
fn card_portrait(&self, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
fn splash(&self, _: &str) -> Result<Vec<u8>, SourceError> {
Err(SourceError::NotFound)
}
}
/// The tracker of Joueur (and of Autre, who has played nothing), on the catalog.
pub(super) fn joueur_tracker() -> Tracker {
joueur_tracker_with(false)
}
/// `mastery`: Joueur is the Account being followed and its points were fetched.
pub(super) fn joueur_tracker_with(mastery: bool) -> Tracker {
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
// One folder per tracker (the tests run in parallel), removed once the catalog is stored.
let portraits = crate::card_images::tests::TestDir::new("page-tracker");
let tracker = tracker.with_champions(Box::new(Catalog), portraits.path().to_path_buf());
tracker.refresh_champions().unwrap();
if mastery {
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
// Without a client, a round adopts the Riot ID it is given, then asks for the points.
tracker.follow_client(0, Some(JOUEUR), &mut |_| {});
assert!(tracker.mastery("Joueur").unwrap().is_some());
} else {
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
tracker.sync("Autre#EUW", &mut |_| {}).unwrap();
}
tracker
}
pub(super) fn capture() -> Value {
serde_json::from_str(include_str!(
"../../../../core/tests/fixtures/client/arena_champ_select.json"
))
.unwrap()
}
/// The champ select as the page gets it from a session, the lists being those of the capture
/// but the Anvil one.
pub(super) fn read_champ_select(
reader: &ChampSelectReader,
session: Value,
anvil: Option<String>,
) -> ChampSelect {
let capture = capture();
reader.set_session(session);
reader
.read(
|| Err(ClientError::Absent),
|| {
Ok((
capture["pickableChampionIds"].to_string(),
capture["disabledChampionIds"].to_string(),
anvil,
))
},
)
.unwrap()
}
/// The five frames of the capture, read through one reader as the follower does.
pub(super) fn frames() -> Vec<ChampSelect> {
let capture = capture();
let reader = ChampSelectReader::default();
capture["sessions"]
.as_array()
.unwrap()
.iter()
.map(|session| {
let anvil = Some(capture["crowdFavoriteChampionIds"].to_string());
read_champ_select(&reader, session.clone(), anvil)
})
.collect()
}
/// Frame 0 with these completed bans, and `ally` confirmed.
pub(super) fn with_bans_and_ally(bans: &[u32], ally: u32) -> ChampSelect {
let capture = capture();
let mut session = capture["sessions"][0].clone();
session["actions"] = json!([bans
.iter()
.map(|id| json!({"type": "ban", "championId": id, "completed": true}))
.collect::<Vec<_>>()]);
session["myTeam"][1]["championId"] = ally.into();
let anvil = Some(capture["crowdFavoriteChampionIds"].to_string());
read_champ_select(&ChampSelectReader::default(), session, anvil)
}
pub(super) fn send(page: &Entity<Page>, window: &mut VisualTestContext, pick: &ChampSelect) {
let live = Some((JOUEUR.to_string(), pick.clone()));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(live), w, cx)
})
});
}
/// Ends the champ select, and lets the hand leave and the home come back.
pub(super) fn leave(page: &Entity<Page>, window: &mut VisualTestContext) {
start_leaving(page, window);
finish_motion(page, window);
}
/// Ends the champ select, without waiting for the hand to leave.
pub(super) fn start_leaving(page: &Entity<Page>, window: &mut VisualTestContext) {
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(None), w, cx)
})
});
}
/// Lets the champ select's entry or exit end, and the veil lift.
pub(super) fn finish_motion(page: &Entity<Page>, window: &mut VisualTestContext) {
for _ in 0..60 {
let moving = page.read_with(window, |p, cx| {
p.leave.is_some() || p.fade.is_some() || p.stage_moving(cx)
});
if !moving {
return;
}
frame_after(window, 50);
}
panic!("the champ select's motion did not end");
}
pub(super) fn anvil_cards(page: &Entity<Page>, window: &mut VisualTestContext) -> Vec<Card> {
let grid = page.read_with(window, |p, _| p.anvil_grid.clone());
grid.read_with(window, |grid, _| grid.shown_cards())
}
pub(super) fn ids(cards: &[Card]) -> Vec<u32> {
cards.iter().map(|card| card.id).collect()
}
pub(super) fn reasons(cards: &[Card], id: u32) -> Vec<Reason> {
cards.iter().find(|c| c.id == id).unwrap().reasons.clone()
}
/// Where the hand's cards `ids` rest, from `first`: in their place, but a card an ally took,
/// 8 px lower (#87).
pub(super) fn places(
page: &Entity<Page>,
window: &mut VisualTestContext,
first: &[gpui_kit::Bounds<gpui_kit::Pixels>],
ids: &[u32],
) -> Vec<gpui_kit::Bounds<gpui_kit::Pixels>> {
let cards = anvil_cards(page, window);
first
.iter()
.zip(ids)
.map(|(place, id)| {
let taken = reasons(&cards, *id).contains(&Reason::TakenByAlly);
let mut place = *place;
if taken {
place.origin.y += px(crate::card_grid::TAKEN_DROP);
}
place
})
.collect()
}
pub(super) fn bounds(window: &mut VisualTestContext) -> Vec<gpui_kit::Bounds<gpui_kit::Pixels>> {
ANVIL_CARDS
.iter()
.map(|id| window.debug_bounds(id).expect("the card is not drawn"))
.collect()
}
/// What the non-anvil champions of the capture are, in the home's order (A to Z by name).
pub(super) const OTHERS_A_TO_Z: [u32; 4] = [103, 12, 25, 50];
pub(super) fn others_cards(page: &Entity<Page>, window: &mut VisualTestContext) -> Vec<Card> {
let grid = page.read_with(window, |p, _| p.others_grid.clone());
grid.read_with(window, |grid, _| grid.shown_cards())
}
pub(super) fn others_open(page: &Entity<Page>, window: &mut VisualTestContext) -> bool {
page.read_with(window, |p, _| p.others_open)
}
pub(super) fn click_others(window: &mut VisualTestContext) {
let toggle = center(window, "others-toggle");
window.simulate_click(toggle, Modifiers::none());
draw(window);
// The section's first layout says where its grid is: the frame after it builds the rows.
draw(window);
}
/// Scrolls the champ select's column to its end, over the banner: the open « Autres
/// champions » starts under the window's bottom edge.
pub(super) fn scroll_champ_select_down(window: &mut VisualTestContext) {
let banner = center(window, "banner");
window.simulate_event(ScrollEvent {
position: banner,
delta: ScrollDelta::Pixels(point(px(0.), px(-5000.))),
..Default::default()
});
draw(window);
}
/// Presses and releases `key` on the focused element, as the navigation's test does.
pub(super) fn activate(window: &mut VisualTestContext, key: &str) {
let keystroke =
window.update(|_, cx| Keystroke::parse_with_os(key, cx.platform_info().os).unwrap());
window.simulate_event(KeyDownEvent {
keystroke: keystroke.clone(),
is_held: false,
prefer_character_input: false,
});
window.simulate_event(KeyUpEvent { keystroke });
draw(window);
}
/// Tab, until the section's header has the focus.
pub(super) fn focus_others_toggle(page: &Entity<Page>, window: &mut VisualTestContext) {
for _ in 0..60 {
window.update(|w, cx| w.focus_next(cx));
draw(window);
if window.update(|w, cx| page.read(cx).others_focus.is_focused(w)) {
return;
}
}
panic!("Tab never reached « Autres champions »");
}
pub(super) fn search_others(page: &Entity<Page>, window: &mut VisualTestContext, text: &str) {
let input = page.read_with(window, |p, _| p.others_search_input.clone());
window.update(|w, cx| {
input.update(cx, |input, cx| {
input.focus(w, cx);
input.clean(w, cx);
})
});
if !text.is_empty() {
window.simulate_input(text);
}
draw(window);
}
/// The page in the first frame of the capture, once its statistics are there.
pub(super) async fn page_in_champ_select(
cx: &mut TestAppContext,
pick: &ChampSelect,
) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
send(&page, &mut window, pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
// The hand is dealt.
finish_motion(&page, &mut window);
(page, window)
}
/// Enters the champ select of `pick` with the window hidden in the notification area, then
/// shows it once the statistics are loaded, as #63 does: the entry starts at the test
/// clock's present, the hand already holding its cards.
pub(super) async fn entering(
cx: &mut TestAppContext,
pick: &ChampSelect,
) -> (Entity<Page>, VisualTestContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
window.simulate_visibility_change(WindowVisibility::Hidden);
send(&page, &mut window, pick);
cx.condition(&page, |p, _| p.stats.is_some()).await;
window.run_until_parked();
window.simulate_visibility_change(WindowVisibility::Visible);
draw(&mut window);
// The portraits looked for once (the catalog has none) draw the hand's grid again.
window.run_until_parked();
draw(&mut window);
(page, window)
}
/// How far below its place card `id` of the hand is drawn while it moves (above when
/// negative), if it is.
pub(super) fn below(cx: &mut VisualTestContext, id: u32) -> Option<f32> {
let moving = cx.debug_bounds(Box::leak(format!("moving-{id}").into_boxed_str()))?;
let place = cx
.debug_bounds(Box::leak(format!("card-{id}").into_boxed_str()))
.unwrap();
assert_eq!(moving.size, place.size, "the card changed size");
assert_eq!(moving.origin.x, place.origin.x, "the card left its column");
Some((moving.origin.y - place.origin.y).as_f32())
}
/// What the entry must not do again at each frame: compute the statistics, sort the cards,
/// draw the hand's grid or build its cards.
pub(super) fn computed(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> (u64, usize, bool, usize, usize) {
let hand = page.read_with(cx, |p, _| p.anvil_grid.clone());
let (renders, builds) = hand.read_with(cx, |grid, _| (grid.renders, grid.card_builds));
page.read_with(cx, |p, _| {
(
p.stats_generation,
p.reorders,
p.stats_job.running(),
renders,
builds,
)
})
}
/// Joueur's tracker on the catalog, with the card portraits of `keys` on disk under `dir`.
pub(super) fn tracker_with_portraits(dir: &Path, keys: &[&str]) -> Tracker {
let portraits = dir.join("portraits");
let tracker = Tracker::open(Path::new(":memory:"), Box::new(JoueurHistory))
.unwrap()
.with_seasons(vec![season("Saison", 2020)])
.with_champions(Box::new(Catalog), portraits.clone());
tracker.refresh_champions().unwrap();
tracker.sync(JOUEUR, &mut |_| {}).unwrap();
let cards = portraits.join("cards");
std::fs::create_dir_all(&cards).unwrap();
for key in keys {
std::fs::write(cards.join(format!("{key}.jpg")), PORTRAIT_JPEG).unwrap();
}
tracker
}
pub(super) fn card_portrait(dir: &Path, key: &str) -> PathBuf {
dir.join("portraits")
.join("cards")
.join(format!("{key}.jpg"))
}
@@ -0,0 +1,467 @@
use super::champ_select_fixtures::{
ANVIL_A_TO_Z, anvil_cards, below, bounds, click_others, computed, entering, finish_motion,
frames, ids, joueur_tracker, leave, page_in_champ_select, reasons, scroll_champ_select_down,
send, start_leaving, with_bans_and_ally,
};
use super::page_fixtures::{
animations, assert_at_rest, draw, focus_sort, frame_after, hover, open_page_with_tracker,
press, rise, settle, shown_tab, switch_tab, veil,
};
use crate::card::Reason;
use crate::page::Tab;
use arena_tracker_core::StateFilter;
use gpui_kit::{
Bounds, Modifiers, TestAppContext, VisualTestContext, WindowVisibility, point, px, size,
};
use std::time::Duration;
// #87 on the Arena capture, step by step: the band of light and the title at once, then
// the Anvil champions (A to Z: Briar, Lee Sin, Rumble, Soraka, Xin Zhao) from the bottom of
// the window, the first at 380 ms then one every 110 ms, each in 700 ms. The hand's grid
// stays cached through it all, and nothing is computed again.
#[gpui::test]
async fn the_entry_sweeps_the_window_brings_the_title_in_and_deals_the_hand(
cx: &mut TestAppContext,
) {
let (page, mut window) = entering(cx, &frames()[0]).await;
let cx = &mut window;
let at_start = computed(&page, cx);
let title = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.title_pose(cx));
// Over the whole window, the title bar included.
let window_bounds = cx.update(|window, _| Bounds {
origin: point(px(0.), px(0.)),
size: window.viewport_size(),
});
assert_eq!(cx.debug_bounds("sweep"), Some(window_bounds));
assert_eq!(title(cx), Some((0., 8.)));
for id in ANVIL_A_TO_Z {
assert_eq!(below(cx, id), None, "{id} is dealt already");
}
// 400 ms: Briar comes up from the bottom of the window, Lee Sin waits.
frame_after(cx, 400);
let briar = below(cx, 233).expect("Briar is not dealt");
assert!(briar > 100., "{briar}");
assert_eq!(below(cx, 64), None);
let (opacity, rise) = title(cx).unwrap();
assert!(opacity > 0.5 && rise < 4., "{opacity} {rise}");
// 500 ms: Briar is higher, Lee Sin on its way.
frame_after(cx, 100);
assert!(below(cx, 233).unwrap() < briar);
assert!(below(cx, 64).is_some());
// 900 ms: the band of light is gone, the title in its place.
frame_after(cx, 400);
assert!(cx.debug_bounds("sweep").is_none());
assert_eq!(title(cx), Some((1., 0.)));
// 1100 ms: Briar is in its place, the grid's own card; Xin Zhao is still on its way.
frame_after(cx, 200);
assert_eq!(below(cx, 233), None);
assert!(below(cx, 5).is_some());
// 1600 ms: the whole hand is dealt, and the entry over.
frame_after(cx, 500);
for id in ANVIL_A_TO_Z {
assert_eq!(below(cx, id), None, "{id} is still moving");
}
assert_eq!(computed(&page, cx), at_start, "the entry computed again");
assert_at_rest(cx);
assert!(page.read_with(cx, |p, _| p.entry.is_none()));
}
#[gpui::test]
async fn a_card_still_dealt_is_lifted_once_in_its_place(cx: &mut TestAppContext) {
let (page, mut window) = entering(cx, &frames()[0]).await;
let cx = &mut window;
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
// Xin Zhao, the last card, leaves the bottom at 820 ms and is in its place at 1520.
frame_after(cx, 400);
hover(cx, "card-5");
frame_after(cx, 800);
assert_eq!(rise(cx, 5), None);
assert_eq!(lit(cx), None);
frame_after(cx, 400);
settle(cx);
// Not offered: greyed, it rises less.
assert_eq!(rise(cx, 5), Some(4.));
assert_eq!(lit(cx), Some(5));
}
// The last card lands between the frame that looks for it and the draw after it: a card
// the pointer waits for asks for frames until one finds it in its place.
#[gpui::test]
async fn a_card_waited_for_is_lifted_even_when_it_lands_just_after_a_frame(
cx: &mut TestAppContext,
) {
let (page, mut window) = entering(cx, &frames()[0]).await;
let cx = &mut window;
frame_after(cx, 400);
hover(cx, "card-5");
// Xin Zhao is in its place at 1520 ms: the frame reads 1519, the draw 1520.
cx.executor().advance_clock(Duration::from_millis(1119));
cx.update(|window, cx| {
window.simulate_next_frame(cx);
cx.background_executor()
.advance_clock(Duration::from_millis(1));
});
assert!(page.read_with(cx, |p, _| p.hover_waiting.is_some()));
frame_after(cx, 16);
assert!(page.read_with(cx, |p, _| p.hover_waiting.is_none()));
settle(cx);
assert_eq!(rise(cx, 5), Some(4.));
assert_eq!(page.read_with(cx, |p, cx| p.ring.read(cx).lit()), Some(5));
}
// In a low window the hand is under the bottom edge: its cards dealt there are not built,
// until the column is scrolled to them.
#[gpui::test]
async fn a_card_dealt_out_of_sight_is_not_built(cx: &mut TestAppContext) {
let (_page, mut window) = entering(cx, &frames()[0]).await;
let cx = &mut window;
cx.simulate_resize(size(px(600.), px(340.)));
draw(cx);
let hand = bounds(cx);
assert!(hand.iter().all(|card| card.top() >= px(340.)), "{hand:?}");
// 700 ms: Briar, Lee Sin and Rumble on their way, out of sight.
frame_after(cx, 700);
for id in ANVIL_A_TO_Z {
assert_eq!(below(cx, id), None, "{id} is built out of sight");
}
scroll_champ_select_down(cx);
frame_after(cx, 16);
assert!(ANVIL_A_TO_Z.iter().any(|id| below(cx, *id).is_some()));
}
// The keyboard reaches a card still dealt, then the pointer moves: the pointer has the
// last word, and the card is not lifted once in its place.
#[gpui::test]
async fn the_pointer_moving_cancels_the_card_the_keyboard_waits_for(cx: &mut TestAppContext) {
let (page, mut window) = entering(cx, &frames()[0]).await;
let cx = &mut window;
let lit = |cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.ring.read(cx).lit());
// 400 ms: Briar, the first card, is on its way.
frame_after(cx, 400);
focus_sort(&page, cx);
press(cx, "tab");
assert!(page.read_with(cx, |p, _| p.hover_waiting.is_some()));
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
assert!(page.read_with(cx, |p, _| p.hover_waiting.is_none()));
finish_motion(&page, cx);
settle(cx);
assert_eq!(rise(cx, 233), None);
assert_eq!(cx.debug_bounds("sheet-233"), None);
assert_eq!(lit(cx), None);
}
#[gpui::test]
async fn reasons_coming_during_the_deal_show_on_their_card_without_dealing_again(
cx: &mut TestAppContext,
) {
let (page, mut window) = entering(cx, &frames()[0]).await;
let cx = &mut window;
frame_after(cx, 450);
let entry = page.read_with(cx, |p, _| p.entry);
let briar = below(cx, 233).unwrap();
// Briar banned and taken by an ally while on its way.
send(&page, cx, &with_bans_and_ally(&[16, 233, 12], 233));
draw(cx);
assert_eq!(page.read_with(cx, |p, _| p.entry), entry);
assert_eq!(
reasons(&anvil_cards(&page, cx), 233),
[Reason::Banned, Reason::TakenByAlly]
);
// Still on its way, in its column, to its place 8 px lower: it goes straight there.
let lower = below(cx, 233).unwrap();
assert!(lower > 0. && lower < briar, "{briar} {lower}");
assert!(page.read_with(cx, |p, _| p.taken.is_empty()));
finish_motion(&page, cx);
assert_eq!(below(cx, 233), None);
}
#[gpui::test]
async fn an_allys_confirmation_lowers_its_card_8_px_and_nothing_else_moves(
cx: &mut TestAppContext,
) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
let hand = page.read_with(cx, |p, _| p.anvil_grid.clone());
let place = bounds(cx);
send(&page, cx, &with_bans_and_ally(&[], 233));
draw(cx);
let renders = hand.read_with(cx, |grid, _| grid.renders);
// Briar now rests 8 px lower, and goes down there from where it was.
let mut lowered = place.clone();
lowered[0].origin.y += px(8.);
assert_eq!(bounds(cx), lowered);
assert_eq!(below(cx, 233), Some(-8.));
for id in [64, 68, 16, 5] {
assert_eq!(below(cx, id), None, "{id} moved");
}
frame_after(cx, 175);
let halfway = below(cx, 233).unwrap();
assert!(halfway > -8. && halfway < 0., "{halfway}");
frame_after(cx, 350);
assert_eq!(below(cx, 233), None);
assert_eq!(hand.read_with(cx, |grid, _| grid.renders), renders);
assert_at_rest(cx);
}
// The card under the pointer goes down and greys all the same, still lifted, the card as it
// was fading over it.
#[gpui::test]
async fn an_allys_confirmation_lowers_the_card_under_the_pointer_too(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
hover(cx, "card-233");
settle(cx);
// Offered, it rises 10 px.
assert_eq!(rise(cx, 233), Some(10.));
send(&page, cx, &with_bans_and_ally(&[], 233));
draw(cx);
// Greyed, it rises 4 px, from 8 px above its new place; as it was, where it was.
assert_eq!(rise(cx, 233), Some(12.));
let before = cx
.debug_bounds("lifted-before-233")
.expect("the card as it was");
let place = cx.debug_bounds("card-233").unwrap();
assert_eq!((place.origin.y - before.origin.y).as_f32(), 18.);
frame_after(cx, 175);
let halfway = rise(cx, 233).unwrap();
assert!(halfway > 4. && halfway < 12., "{halfway}");
frame_after(cx, 350);
assert_eq!(rise(cx, 233), Some(4.));
assert!(cx.debug_bounds("lifted-before-233").is_none());
assert_at_rest(cx);
}
// The end of a champ select: the hand leaves, Xin Zhao first and Briar last, then the home
// comes back under the veil of the tabs, as #74 leaves it.
#[gpui::test]
async fn the_hand_leaves_from_the_last_card_then_the_home_comes_back_under_the_veil(
app: &mut TestAppContext,
) {
let (page, mut window) = page_in_champ_select(app, &frames()[0]).await;
let cx = &mut window;
start_leaving(&page, cx);
draw(cx);
assert!(page.read_with(cx, |p, _| p.in_champ_select()));
frame_after(cx, 100);
assert!(below(cx, 5).unwrap() > 0.);
assert_eq!(below(cx, 233), Some(0.));
assert_eq!(veil(&page, cx), 0.);
// No card rises while the hand leaves.
hover(cx, "card-64");
assert_eq!(rise(cx, 64), None);
// From 240 ms, the veil covers the champ select; at 370 ms the home is under it.
frame_after(cx, 200);
assert!(veil(&page, cx) > 0.);
assert!(cx.debug_bounds("anvil-row").is_some());
frame_after(cx, 100);
assert!(!page.read_with(cx, |p, _| p.in_champ_select()));
assert!(cx.debug_bounds("anvil-row").is_none());
assert!(veil(&page, cx) > 0.5);
finish_motion(&page, cx);
assert_eq!(veil(&page, cx), 0.);
assert_eq!(page.read_with(cx, |p, _| p.home_filter), StateFilter::All);
// Once the home has its statistics (and its banner its splash), nothing moves.
app.condition(&page, |p, _| p.stats.is_some()).await;
assert_at_rest(cx);
}
// A champ select that ends while its hand is dealt: the cards on their way go down from
// where they are, those not dealt yet are not seen.
#[gpui::test]
async fn the_cards_on_their_way_leave_from_where_they_are(cx: &mut TestAppContext) {
let (page, mut window) = entering(cx, &frames()[0]).await;
let cx = &mut window;
// 700 ms: Briar, Lee Sin and Rumble on their way, Soraka and Xin Zhao waiting.
frame_after(cx, 700);
let on_their_way = [233, 64, 68].map(|id| below(cx, id).expect("not on its way"));
for id in [16, 5] {
assert_eq!(below(cx, id), None, "{id} is dealt already");
}
start_leaving(&page, cx);
draw(cx);
// Where they were, at once.
assert_eq!(
[233, 64, 68].map(|id| below(cx, id)),
on_their_way.map(Some)
);
frame_after(cx, 200);
for (id, was) in [233, 64, 68].into_iter().zip(on_their_way) {
let now = below(cx, id).unwrap_or_else(|| panic!("{id} is no longer seen"));
assert!(now > was, "{id} did not go down: {was} then {now}");
}
for id in [16, 5] {
assert_eq!(below(cx, id), None, "{id} is seen leaving");
}
finish_motion(&page, cx);
assert!(!page.read_with(cx, |p, _| p.in_champ_select()));
}
// A champ select that ends with a card lifted, and another going down after an ally's
// confirmation: each leaves from where it is, the first still lifted.
#[gpui::test]
async fn a_lifted_or_lowered_card_leaves_from_where_it_is(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
hover(cx, "card-64");
settle(cx);
// Greyed, Lee Sin rises 4 px.
assert_eq!(rise(cx, 64), Some(4.));
// Briar taken by an ally 100 ms before the end: still above its new place.
send(&page, cx, &with_bans_and_ally(&[], 233));
draw(cx);
frame_after(cx, 100);
let lowering = below(cx, 233).unwrap();
assert!(lowering < 0. && lowering > -8., "{lowering}");
start_leaving(&page, cx);
draw(cx);
// Where they were, at once.
assert_eq!(rise(cx, 64), Some(4.));
assert_eq!(below(cx, 233), Some(lowering));
// Then down from there.
frame_after(cx, 200);
let lee_sin = rise(cx, 64).expect("Lee Sin is no longer seen");
assert!(lee_sin < 4., "{lee_sin}");
let briar = below(cx, 233).expect("Briar is no longer seen");
assert!(briar > lowering, "{lowering} then {briar}");
finish_motion(&page, cx);
assert!(!page.read_with(cx, |p, _| p.in_champ_select()));
}
#[gpui::test]
async fn without_animations_the_hand_is_there_at_once_and_leaves_at_once(app: &mut TestAppContext) {
app.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(app, joueur_tracker());
let cx = &mut window;
animations(cx, false);
send(&page, cx, &frames()[0]);
app.condition(&page, |p, _| p.stats.is_some()).await;
draw(cx);
assert!(page.read_with(cx, |p, _| p.entry.is_none()));
assert!(cx.debug_bounds("sweep").is_none());
assert_eq!(page.read_with(cx, |p, cx| p.title_pose(cx)), None);
assert_eq!(below(cx, 233), None);
hover(cx, "card-5");
assert!(rise(cx, 5).is_some());
start_leaving(&page, cx);
draw(cx);
assert!(!page.read_with(cx, |p, _| p.in_champ_select()));
assert!(page.read_with(cx, |p, _| p.fade.is_none()));
app.condition(&page, |p, _| p.stats.is_some()).await;
assert_at_rest(cx);
}
// #63: the window shows itself at the entry without taking the focus; the entry plays only
// once it is visible, and not behind « Paramètres ».
#[gpui::test]
async fn the_entry_waits_for_the_window_and_the_page_to_be_in_front(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let cx = &mut window;
let entry = |cx: &mut VisualTestContext| page.read_with(cx, |p, _| p.entry.is_some());
cx.simulate_visibility_change(WindowVisibility::Hidden);
send(&page, cx, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
assert!(!entry(cx));
cx.simulate_visibility_change(WindowVisibility::Visible);
assert!(entry(cx));
draw(cx);
assert!(cx.debug_bounds("sweep").is_some());
// Hidden during the entry: it ends, the hand in its place.
frame_after(cx, 450);
cx.simulate_visibility_change(WindowVisibility::Hidden);
assert!(!entry(cx));
// And the end of the champ select, hidden, is at once.
start_leaving(&page, cx);
assert!(!page.read_with(cx, |p, _| p.in_champ_select()));
// Behind « Paramètres »; and from « Statistiques », « Défi » first.
cx.simulate_visibility_change(WindowVisibility::Visible);
switch_tab(&page, cx, Tab::Statistics);
cx.update(|window, cx| page.update(cx, |page, cx| page.hidden(window, cx)));
send(&page, cx, &frames()[0]);
assert!(!entry(cx));
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
cx.update(|window, cx| page.update(cx, |page, cx| page.uncovered(window, cx)));
assert!(entry(cx));
finish_motion(&page, cx);
assert_at_rest(cx);
}
// One card at most is lifted: the pointer going from the hand to « Autres champions » puts
// the hand's card down and lifts its veil.
#[gpui::test]
async fn one_card_is_lifted_at_a_time_across_the_grids(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
click_others(cx);
scroll_champ_select_down(cx);
settle(cx);
let hand = page.read_with(cx, |p, _| p.anvil_grid.clone());
let id = ids(&anvil_cards(&page, cx))[0];
let veil = |cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| {
p.lifts
.veil(hand.entity_id(), cx.background_executor().now())
})
};
hover(cx, Box::leak(format!("card-{id}").into_boxed_str()));
settle(cx);
assert_eq!(rise(cx, id), Some(10.));
hover(cx, "card-103");
settle(cx);
assert_eq!(rise(cx, 103), Some(10.));
assert_eq!(rise(cx, id), None, "the hand's card stayed lifted");
assert_eq!(veil(cx), 0.);
}
// The hand gives way when the champ select ends: its lifted card goes at once, and no frame
// is asked for a card no longer shown.
#[gpui::test]
async fn a_grid_no_longer_shown_asks_for_no_frame(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
settle(cx);
let id = ids(&anvil_cards(&page, cx))[0];
hover(cx, Box::leak(format!("card-{id}").into_boxed_str()));
settle(cx);
leave(&page, cx);
draw(cx);
let lifting = page.read_with(cx, |p, cx| {
let now = cx.background_executor().now();
let hand = p.anvil_grid.entity_id();
(p.lifts.lifted(hand, now).count(), p.lifts.veil(hand, now))
});
assert_eq!(lifting, (0, 0.));
// The home's card now under the still pointer rises in its turn, then nothing moves.
settle(cx);
frame_after(cx, 16);
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
assert_eq!(asked, 0, "a frame is asked for");
}
@@ -0,0 +1,131 @@
use super::champ_select_fixtures::{
OTHERS_A_TO_Z, activate, anvil_cards, capture, click_others, focus_others_toggle, frames, ids,
others_cards, others_open, page_in_champ_select, read_champ_select, reasons,
scroll_champ_select_down, send, with_bans_and_ally,
};
use super::page_fixtures::{draw, hover, rise, settle};
use crate::card::Reason;
use crate::card_grid::CardGrid;
use arena_tracker_core::ChampSelectReader;
use gpui_kit::{Entity, Modifiers, TestAppContext, VisualTestContext, point, px};
#[gpui::test]
async fn others_is_folded_at_entry_and_builds_no_card(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
assert!(!others_open(&page, &mut window));
assert!(window.debug_bounds("others-toggle").is_some());
assert!(window.debug_bounds("anvil-row").is_some());
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
grid.read_with(&window, |grid, _| {
assert_eq!(grid.renders, 0);
assert_eq!(grid.card_builds, 0);
assert_eq!(grid.set_cards_calls, 0);
});
assert!(window.debug_bounds("card-103").is_none());
// The frames and the statistics keep coming while it is folded: still nothing.
for pick in &frames()[1..] {
send(&page, &mut window, pick);
draw(&mut window);
}
grid.read_with(&window, |grid, _| {
assert_eq!((grid.renders, grid.set_cards_calls), (0, 0));
});
page.read_with(&window, |p, _| {
assert_eq!(p.others_title(), "Autres champions")
});
}
#[gpui::test]
async fn others_opens_and_closes_with_the_mouse_and_the_keyboard(cx: &mut TestAppContext) {
let pick = with_bans_and_ally(&[12, 50], 25);
let (page, mut window) = page_in_champ_select(cx, &pick).await;
let anvil_before = anvil_cards(&page, &mut window);
click_others(&mut window);
assert!(others_open(&page, &mut window));
// Every champion without an anvil, banned or taken ones included, in the home's order.
let cards = others_cards(&page, &mut window);
assert_eq!(ids(&cards), OTHERS_A_TO_Z);
assert_eq!(reasons(&cards, 103), []);
assert_eq!(reasons(&cards, 12), [Reason::Banned]);
assert_eq!(reasons(&cards, 25), [Reason::TakenByAlly]);
assert_eq!(reasons(&cards, 50), [Reason::Banned]);
assert!(window.debug_bounds("card-103").is_some());
assert!(window.debug_bounds("card-12").is_some());
// The anvil row is untouched.
assert_eq!(anvil_cards(&page, &mut window), anvil_before);
click_others(&mut window);
assert!(!others_open(&page, &mut window));
assert!(window.debug_bounds("card-103").is_none());
assert!(others_cards(&page, &mut window).is_empty());
// With the keyboard: Tab reaches the header, Enter opens it and Space folds it.
focus_others_toggle(&page, &mut window);
activate(&mut window, "enter");
assert!(others_open(&page, &mut window));
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
activate(&mut window, "space");
assert!(!others_open(&page, &mut window));
activate(&mut window, "enter");
assert!(others_open(&page, &mut window));
// The lock-ins of the champ select reach the open section, which keeps its place.
send(&page, &mut window, &with_bans_and_ally(&[103], 25));
draw(&mut window);
let cards = others_cards(&page, &mut window);
assert_eq!(ids(&cards), OTHERS_A_TO_Z);
assert_eq!(reasons(&cards, 103), [Reason::Banned]);
assert_eq!(reasons(&cards, 12), []);
}
#[gpui::test]
async fn others_shows_the_completed_champions_it_holds(cx: &mut TestAppContext) {
// 16 is Completed; with only 233 an Anvil champion it is one of the others.
let session = capture()["sessions"][0].clone();
let pick = read_champ_select(&ChampSelectReader::default(), session, Some("[233]".into()));
let (page, mut window) = page_in_champ_select(cx, &pick).await;
click_others(&mut window);
let cards = others_cards(&page, &mut window);
assert_eq!(ids(&cards), [103, 12, 64, 25, 68, 16, 50, 5]);
assert_eq!(reasons(&cards, 16), [Reason::Completed]);
assert_eq!(reasons(&cards, 64), [Reason::NotOffered]);
assert_eq!(ids(&anvil_cards(&page, &mut window)), [233]);
}
// In the hand alone, a veil lays on the other cards while one is lifted; the hand is not
// drawn again.
#[gpui::test]
async fn in_the_hand_a_veil_lays_on_the_other_cards(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let cx = &mut window;
settle(cx);
let hand = page.read_with(cx, |p, _| p.anvil_grid.clone());
let renders = hand.read_with(cx, |grid, _| grid.renders);
let id = ids(&anvil_cards(&page, cx))[0];
let veil = |cx: &mut VisualTestContext, grid: &Entity<CardGrid>| {
page.read_with(cx, |p, cx| {
p.lifts
.veil(grid.entity_id(), cx.background_executor().now())
})
};
hover(cx, Box::leak(format!("card-{id}").into_boxed_str()));
settle(cx);
assert_eq!(rise(cx, id), Some(10.));
assert_eq!(veil(cx, &hand), 1.);
assert_eq!(hand.read_with(cx, |grid, _| grid.renders), renders);
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
settle(cx);
assert_eq!(veil(cx, &hand), 0.);
// « Autres champions » has none.
click_others(cx);
scroll_champ_select_down(cx);
let others = page.read_with(cx, |p, _| p.others_grid.clone());
hover(cx, "card-103");
settle(cx);
assert_eq!(rise(cx, 103), Some(10.));
assert_eq!(veil(cx, &others), 0.);
}
@@ -0,0 +1,145 @@
//! The champ select scrolls as one page: the banner, the Anvil champions and « Autres
//! champions » move together, and the grid of the section builds only the rows in view.
use super::champ_select_fixtures::{click_others, frames, send};
use super::page_fixtures::{champions, draw, open_page_in_season, press, show, statistics};
use crate::card_grid::RevealRow;
use crate::page::Page;
use gpui_kit::{
Entity, Pixels, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px,
};
/// A champ select with 170 champions, « Autres champions » open and laid out.
fn open_others(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
let (page, mut window) = open_page_in_season(cx);
send(&page, &mut window, &frames()[0]);
show(&page, &mut window, statistics(0, 170, champions(170)));
draw(&mut window);
click_others(&mut window);
(page, window)
}
fn wheel(window: &mut VisualTestContext, y: f32) {
window.simulate_event(ScrollEvent {
position: point(px(640.), px(400.)),
delta: ScrollDelta::Pixels(point(px(0.), px(y))),
..Default::default()
});
draw(window);
}
fn scrolled(page: &Entity<Page>, window: &mut VisualTestContext) -> Pixels {
page.read_with(window, |p, _| -p.paging.scroll.offset().y)
}
#[gpui::test]
async fn the_whole_champ_select_scrolls_as_one(cx: &mut TestAppContext) {
let (page, mut window) = open_others(cx);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
assert_eq!(scrolled(&page, &mut window), px(0.));
assert!(window.debug_bounds("anvil-row").is_some());
// A wheel anywhere moves the page, the Anvil row with the cards, and not the grid alone.
wheel(&mut window, -300.);
assert_eq!(scrolled(&page, &mut window), px(300.));
assert_eq!(grid.read_with(&window, |grid, _| grid.scrolled()), px(0.));
// To the end: the last champion, with only the rows in view built.
wheel(&mut window, -100_000.);
let height = window.update(|window, _| window.viewport_size().height);
let last = window
.debug_bounds("card-170")
.expect("the end is not shown");
assert!(last.bottom() <= height, "{last:?} in {height:?}");
assert!(window.debug_bounds("card-1").is_none());
let drawn = grid.read_with(&window, |grid, _| grid.drawn_cards().borrow().len());
assert!(drawn > 0 && drawn <= 6 * 5, "{drawn} cards drawn for 166");
// And back to the top.
wheel(&mut window, 100_000.);
assert_eq!(scrolled(&page, &mut window), px(0.));
assert!(window.debug_bounds("anvil-row").is_some());
assert!(window.debug_bounds("card-170").is_none());
}
#[gpui::test]
async fn a_new_champ_select_starts_at_the_top(cx: &mut TestAppContext) {
let (page, mut window) = open_others(cx);
wheel(&mut window, -400.);
assert_eq!(scrolled(&page, &mut window), px(400.));
let live = Some(("Autre#EUW".to_string(), frames()[0].clone()));
window.update(|w, cx| {
page.update(cx, |p, cx| {
p.apply(crate::worker::Msg::ChampSelect(live), w, cx)
})
});
draw(&mut window);
assert_eq!(scrolled(&page, &mut window), px(0.));
}
#[gpui::test]
async fn the_keyboard_reaches_a_row_the_page_scrolls_to(cx: &mut TestAppContext) {
let (page, mut window) = open_others(cx);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
let top = page
.read_with(&window, |p, _| p.paging.top.get())
.expect("the grid was not laid out");
let viewport = page.read_with(&window, |p, _| p.paging.scroll.bounds().size.height);
let reach = |window: &mut VisualTestContext, top: f32, bottom: f32| {
window.update(|_, cx| {
grid.update(cx, |_, cx| {
cx.emit(RevealRow {
top: px(top),
bottom: px(bottom),
})
})
});
};
// A row below the window: its bottom edge comes to the window's.
reach(&mut window, 3000., 3300.);
assert_eq!(scrolled(&page, &mut window), top + px(3300.) - viewport);
// One above it: its top edge comes to the window's.
reach(&mut window, 0., 300.);
assert_eq!(scrolled(&page, &mut window), top);
// One already in view: nothing moves.
reach(&mut window, 100., 400.);
assert_eq!(scrolled(&page, &mut window), top);
}
// The grid starts under the window: it keeps its first row built, so that Tab from the search
// reaches a card, and the page scrolls to it.
#[gpui::test]
async fn tab_from_the_search_enters_a_grid_below_the_window(cx: &mut TestAppContext) {
let (page, mut window) = open_others(cx);
let (top, viewport) = page.read_with(&window, |p, _| {
(
p.paging.top.get().unwrap(),
p.paging.scroll.bounds().size.height,
)
});
assert!(
top > viewport,
"the grid is in view: {top:?} in {viewport:?}"
);
assert_eq!(scrolled(&page, &mut window), px(0.));
let input = page.read_with(&window, |p, _| p.others_search_input.clone());
window.update(|w, cx| input.update(cx, |input, cx| input.focus(w, cx)));
for _ in 0..3 {
if scrolled(&page, &mut window) > px(0.) {
break;
}
press(&mut window, "tab");
}
draw(&mut window);
assert!(scrolled(&page, &mut window) > px(0.));
let card = window
.debug_bounds("card-1")
.expect("the card is not shown");
let height = window.update(|window, _| window.viewport_size().height);
assert!(
card.origin.y >= px(0.) && card.bottom() <= height,
"{card:?}"
);
}
+256
View File
@@ -0,0 +1,256 @@
use super::page_fixtures::{
center, champions, count_hovers, draw, grid_names, open_page_in_season, settle, show,
statistics, switch_tab,
};
use crate::card::ASPECT;
use crate::champion_table::tests::row;
use crate::page::Tab;
use arena_tracker_core::{
Champion, ChampionChallenge, ChampionRow, ChampionState, Date, StateFilter,
};
use gpui_kit::{Modifiers, ScrollDelta, ScrollEvent, TestAppContext, VisualTestContext, point, px};
#[gpui::test]
fn the_grid_follows_the_alias_search_and_the_filters(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let champion = |id, key: &str, name: &str, state, matches, completed: bool| ChampionRow {
champion: Champion {
id,
key: key.into(),
name: name.into(),
},
state: Some(state),
matches,
challenge: Some(ChampionChallenge {
matches,
completed_on: completed.then_some(Date {
year: 2026,
month: 3,
day: 2,
}),
..Default::default()
}),
..row(name)
};
// As the statistics give them: A to Z, the accented name where French collation puts it.
show(
&page,
cx,
statistics(
1,
4,
vec![
champion(86, "Garen", "Garen", ChampionState::NeverPlayed, 0, false),
champion(107, "Rengar", "Rengar", ChampionState::InProgress, 5, false),
champion(
4,
"TwistedFate",
"Twisted Fate",
ChampionState::Completed,
3,
true,
),
champion(238, "Zed", "Éd", ChampionState::NeverPlayed, 0, false),
],
),
);
draw(cx);
let (input, grid) = page.read_with(cx, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let shown_count =
|cx: &mut VisualTestContext| page.read_with(cx, |p, _| p.home_shown_count.to_string());
// « Tous »: everything, never played and completed ones included, in the given order.
assert_eq!(
grid_names(&grid, cx),
["Garen", "Rengar", "Twisted Fate", "Éd"]
);
assert_eq!(shown_count(cx), "4");
draw(cx);
assert!(cx.debug_bounds("no-champion").is_none());
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("TF");
assert_eq!(grid_names(&grid, cx), ["Twisted Fate"]);
assert_eq!(shown_count(cx), "1");
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(grid_names(&grid, cx).len(), 4);
cx.simulate_input("ren");
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(grid_names(&grid, cx), ["Garen", "Rengar"]);
// Nothing completed matches: the grid says so.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Completed;
p.refresh_home(cx);
});
assert!(grid_names(&grid, cx).is_empty());
assert_eq!(shown_count(cx), "0");
draw(cx);
assert!(cx.debug_bounds("no-champion").is_some());
assert!(cx.debug_bounds("card-4").is_none());
// « Validés » alone brings the completed card back.
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
assert_eq!(grid_names(&grid, cx), ["Twisted Fate"]);
draw(cx);
assert!(cx.debug_bounds("card-4").is_some());
assert!(cx.debug_bounds("no-champion").is_none());
}
#[gpui::test]
fn the_cards_keep_the_aspect_and_the_rows_their_pitch_and_a_card_without_a_portrait_renders(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 30, champions(30)));
draw(cx);
let first = cx
.debug_bounds("card-1")
.expect("the first card is not drawn");
let second = cx.debug_bounds("card-2").unwrap();
let next_row = cx.debug_bounds("card-7").unwrap();
// 6 columns at 1280 px, as tall as the aspect says.
assert_eq!(first.origin.y, second.origin.y);
assert!(next_row.origin.x == first.origin.x);
let (width, height) = (first.size.width.as_f32(), first.size.height.as_f32());
assert!((height - width / ASPECT).abs() < 1., "{width} x {height}");
// The first-row measure sizes every row: the next one starts a card and a gap lower.
let step = (next_row.origin.y - first.origin.y).as_f32();
assert!(
(step - (height + 14.)).abs() < 1.,
"step {step}, card {height}"
);
assert!(
((second.origin.x - first.origin.x).as_f32() - width - 14.).abs() < 1.,
"gap between columns"
);
// None of these cards has a portrait.
page.read_with(cx, |page, cx| {
assert!(
page.home_grid
.read(cx)
.names()
.contains(&"Champion 001".into())
);
});
}
#[gpui::test]
fn only_the_visible_cards_are_built(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let built = grid.read_with(cx, |grid, _| grid.card_builds);
// A few rows of 6 under 860 px, the first measured again: far from the 170 cards.
assert!(built > 0);
assert!(built <= 8 * 6, "{built} cards built for 170");
}
// While « Statistiques » is shown the home is not: its cards wait for the next switch to it.
#[gpui::test]
fn the_home_cards_are_not_built_while_statistiques_is_shown(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let built = |cx: &mut VisualTestContext| grid.read_with(cx, |grid, _| grid.set_cards_calls);
let calls = built(cx);
assert!(calls > 0);
switch_tab(&page, cx, Tab::Statistics);
show(&page, cx, statistics(0, 8, champions(8)));
assert_eq!(built(cx), calls, "the cards were built while hidden");
assert!(page.read_with(cx, |page, _| page.home_cards_stale));
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(built(cx), calls + 1);
assert!(!page.read_with(cx, |page, _| page.home_cards_stale));
assert_eq!(grid_names(&grid, cx).len(), 8);
// Nothing changed meanwhile: coming back builds nothing more.
switch_tab(&page, cx, Tab::Statistics);
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(built(cx), calls + 1);
}
// Hovering outside the grid draws the page again, not the cards: the grid is a cached view
// (rule #1), like the charts row.
#[gpui::test]
fn hovering_outside_the_grid_does_not_render_the_cards(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(renders > 0);
// A navigation button's hover style redraws the window.
for _ in 0..2 {
let button = center(cx, "tab-statistics");
cx.simulate_mouse_move(button, None, Modifiers::none());
draw(cx);
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
}
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
// The count does move when the grid changes.
grid.update(cx, |_, cx| cx.notify());
draw(cx);
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders + 1);
}
// Hovering a card draws it lifted over the grid, which is not drawn again; scrolling the grid
// draws it again. Neither computes the statistics again nor builds the cards again.
#[gpui::test]
fn scrolling_or_hovering_the_grid_does_not_recompute_the_statistics(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let grid = page.read_with(cx, |page, _| page.home_grid.clone());
let generation = page.read_with(cx, |page, _| page.stats_generation);
let set_cards = grid.read_with(cx, |grid, _| grid.set_cards_calls);
let renders = grid.read_with(cx, |grid, _| grid.renders);
assert!(set_cards > 0);
let hovers = count_hovers(&grid, cx);
for id in ["card-1", "card-2"] {
let card = center(cx, id);
cx.simulate_mouse_move(card, None, Modifiers::none());
draw(cx);
}
settle(cx);
assert!(hovers.get() > 0, "no card was hovered");
assert_eq!(grid.read_with(cx, |grid, _| grid.renders), renders);
let over = center(cx, "card-1");
cx.simulate_event(ScrollEvent {
position: over,
delta: ScrollDelta::Pixels(point(px(0.), px(-400.))),
..Default::default()
});
draw(cx);
assert!(grid.read_with(cx, |grid, _| grid.scrolled()) > px(0.));
assert_eq!(
grid.read_with(cx, |grid, _| grid.set_cards_calls),
set_cards,
"the cards were built again"
);
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
+255
View File
@@ -0,0 +1,255 @@
use super::banner_fixtures::banner;
use super::champ_select_fixtures::joueur_tracker;
use super::page_fixtures::{
RefreshHistory, assert_home_says, champions, draw, grid_names, open_page, open_page_in_season,
open_page_with_tracker, season, show, statistics, switch_tab,
};
use crate::champion_table::tests::row;
use crate::page::{Page, Tab};
use arena_tracker_core::{ChampionRow, ChampionState, Format, SeasonScope, StateFilter, Tracker};
use gpui_kit::{TestAppContext, VisualTestContext};
use std::path::Path;
#[gpui::test]
fn the_app_opens_on_the_challenge_with_all_champions_selected(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
page.read_with(cx, |page, _| {
assert_eq!(page.tab, Tab::Challenge);
assert_eq!(page.home_filter, StateFilter::All);
assert_eq!(crate::page::home::FILTERS[0].0, "Tous");
assert_eq!(page.home_season.as_deref(), Some("Saison"));
});
}
#[gpui::test]
fn without_a_current_season_the_home_has_no_challenge(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
show(&page, cx, statistics(1, 3, vec![row("Ahri")]));
cx.update(|window, cx| window.draw(cx).clear(cx));
page.read_with(cx, |page, cx| {
// « Toutes les Saisons », and no current Season to stand in.
assert_eq!(page.season, SeasonScope::AllSeasons);
assert_eq!(page.home_season, None);
assert!(page.home_statistics().is_none());
assert!(page.banner.title.text.is_empty());
assert!(page.home_grid.read(cx).names().is_empty());
});
}
#[gpui::test]
fn the_home_says_why_it_has_no_cards_until_the_statistics_arrive(cx: &mut TestAppContext) {
use crate::page::home::StatsNotice;
// A Season but no Account at all.
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
page.read_with(cx, |p, _| {
assert_eq!(p.stats_notice(), Some(StatsNotice::NoAccount));
assert_eq!(
p.anvil_line().as_deref(),
Some("Compte indisponible"),
"the champ select says it the same way"
);
});
assert_home_says(cx, StatsNotice::NoAccount);
// The statistics arrive: the heading and the grid show, and the notice goes.
show(&page, cx, statistics(0, 3, champions(3)));
draw(cx);
page.read_with(cx, |p, _| assert_eq!(p.stats_notice(), None));
assert!(cx.debug_bounds("home-notice").is_none());
assert!(cx.debug_bounds("home-tools").is_some());
assert!(cx.debug_bounds("card-1").is_some());
assert!(cx.debug_bounds("no-champion").is_none());
}
#[gpui::test]
async fn the_home_says_the_statistics_are_loading(cx: &mut TestAppContext) {
use crate::page::home::StatsNotice;
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
cx.condition(&page, |p, _| p.stats.is_some()).await;
// The job of an Account is running: nothing is there yet.
window.update(|_, cx| {
page.update(cx, |p, cx| {
p.stats = None;
p.stats_error = None;
p.prepare_home_cards(cx);
cx.notify();
})
});
page.read_with(&window, |p, _| {
assert!(p.home_season.is_some());
assert_eq!(p.stats_notice(), Some(StatsNotice::Loading));
assert_eq!(
p.stats_notice().map(|n| n.label(None)).as_deref(),
Some("Chargement des statistiques…")
);
});
assert_home_says(&mut window, StatsNotice::Loading);
// Its error is the banner's alone.
window.update(|_, cx| {
page.update(cx, |p, cx| {
p.stats_error = Some("Statistiques indisponibles : disque plein".into());
cx.notify();
})
});
page.read_with(&window, |p, _| {
assert_eq!(p.stats_notice(), Some(StatsNotice::Error));
});
assert_home_says(&mut window, StatsNotice::Error);
}
#[gpui::test]
fn the_counter_keeps_its_total_while_a_search_and_a_filter_reduce_the_list(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let champion = |name: &str, state| ChampionRow {
state: Some(state),
..row(name)
};
show(
&page,
cx,
statistics(
1,
4,
vec![
champion("Ahri", ChampionState::Completed),
champion("Annie", ChampionState::InProgress),
champion("Akali", ChampionState::NeverPlayed),
champion("Zed", ChampionState::NeverPlayed),
],
),
);
cx.update(|window, cx| window.draw(cx).clear(cx));
let (input, grid) = page.read_with(cx, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let names = |cx: &mut VisualTestContext| {
let mut names = grid_names(&grid, cx);
names.sort();
names
};
let counter =
|cx: &mut VisualTestContext| page.read_with(cx, |p, _| p.banner.title.text.to_string());
assert_eq!(names(cx), ["Ahri", "Akali", "Annie", "Zed"]);
assert_eq!(counter(cx), "1 / 4 champions validés");
// The home's search is its own: the Statistics tab's is untouched.
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("an");
assert_eq!(names(cx), ["Annie"]);
assert_eq!(counter(cx), "1 / 4 champions validés");
assert!(page.read_with(cx, |p, _| p.search.matches(&row("Zed").champion)));
cx.update(|window, cx| input.update(cx, |input, cx| input.clean(window, cx)));
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(names(cx), ["Akali", "Annie", "Zed"]);
cx.simulate_input("a");
assert_eq!(names(cx), ["Akali", "Annie"]);
assert_eq!(counter(cx), "1 / 4 champions validés");
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Completed;
p.refresh_home(cx);
});
assert_eq!(names(cx), ["Ahri"]);
assert_eq!(counter(cx), "1 / 4 champions validés");
}
#[gpui::test]
fn the_home_follows_the_season_of_the_statistics_but_not_their_format(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory))
.unwrap()
.with_seasons(vec![season("Ancienne", 2020), season("Récente", 2026)]);
tracker.sync("Alice#EUW", &mut |_| {}).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
let recompute = |window: &mut VisualTestContext, change: &dyn Fn(&mut Page)| {
window.update(|window, cx| {
page.update(cx, |page, cx| {
change(page);
page.recompute(window, cx);
})
});
};
let home = |cx: &mut VisualTestContext| {
page.read_with(cx, |page, _| {
(
page.home_season.clone(),
page.home_scope.is_some(),
page.home_statistics().cloned(),
)
})
};
// The current Season, with no Format: the home reads the Statistics tab's result.
let (season, apart, current) = home(&mut window);
assert_eq!(season.as_deref(), Some("Récente"));
assert!(!apart);
assert_eq!(banner(&page, &mut window).season.as_ref(), "RÉCENTE");
let current = current.unwrap();
assert_eq!(current.rows.iter().map(|r| r.matches).sum::<usize>(), 1);
// Another Format on the Statistics tab: the home keeps its Challenge.
recompute(&mut window, &|page| {
page.tab = Tab::Statistics;
page.shown_tab = Tab::Statistics;
page.format = Some(Format::Arena3x6);
});
let (season, apart, same) = home(&mut window);
assert_eq!(season.as_deref(), Some("Récente"));
assert!(apart);
assert_eq!(same.as_ref(), Some(&current));
let text = banner(&page, &mut window);
assert_eq!(
(text.season.as_ref(), text.title.text.as_ref()),
("RÉCENTE", "0 / 1 champions validés")
);
// Another Season: the home follows.
recompute(&mut window, &|page| {
page.format = None;
page.season = SeasonScope::Season("Ancienne".into());
});
let (season, apart, other) = home(&mut window);
assert_eq!(season.as_deref(), Some("Ancienne"));
assert!(!apart);
assert_eq!(banner(&page, &mut window).season.as_ref(), "ANCIENNE");
let other = other.unwrap();
assert_ne!(other, current);
assert_eq!(other.rows.iter().map(|r| r.matches).sum::<usize>(), 0);
// « Toutes les Saisons » has no Challenge: the current Season stands in for the home.
recompute(&mut window, &|page| page.season = SeasonScope::AllSeasons);
let (season, apart, all) = home(&mut window);
assert_eq!(season.as_deref(), Some("Récente"));
assert!(apart);
assert_eq!(all.as_ref(), Some(&current));
assert!(page.read_with(&window, |page, _| {
page.stats.as_ref().unwrap().challenge.is_none()
}));
}
// Guards the home's one rule of rule #1: it draws no chart (the cached row is not in its tree).
#[gpui::test]
fn the_home_does_not_render_the_charts(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 1, vec![row("Ahri")]));
let charts = page.read_with(cx, |page, _| page.charts.clone());
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(charts.read_with(cx, |charts, _| charts.renders), 0);
switch_tab(&page, cx, Tab::Statistics);
cx.update(|window, cx| window.draw(cx).clear(cx));
assert!(charts.read_with(cx, |charts, _| charts.renders) > 0);
}
@@ -0,0 +1,383 @@
use super::banner_fixtures::{
banner_champion, banner_rows, banner_statistics, on, rows_with_splashes,
};
use super::page_fixtures::{
animate, animations, assert_at_rest, champions, draw, frame_after, home_names, hover,
open_page_in_season, played, round_with_matches, settle, show, shown_tab, start_switch,
statistics, statistics_arrive, switch_tab, until_landed,
};
use crate::card_images::tests::TestDir;
use crate::motion::MatchEnd;
use crate::page::Tab;
use arena_tracker_core::{ChampionRow, LastMatch, MatchOutcome, StateFilter};
use gpui_kit::{Modifiers, TestAppContext, VisualTestContext, WindowVisibility, point, px};
use std::rc::Rc;
#[gpui::test]
fn an_animation_waits_for_the_challenge_to_show_and_only_the_strongest_plays(
cx: &mut TestAppContext,
) {
use MatchEnd::{Completed, Mark, Nothing};
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
animate(&page, cx, Mark);
assert_eq!(played(&page, cx), [Mark]);
// Minimised, or hidden in the notification area.
cx.simulate_visibility_change(WindowVisibility::Hidden);
for end in [Nothing, Completed, Mark] {
animate(&page, cx, end);
}
assert_eq!(played(&page, cx), [Mark]);
cx.simulate_visibility_change(WindowVisibility::Visible);
assert_eq!(played(&page, cx), [Mark, Completed]);
// Under « Statistiques »: it plays once « Défi » is back, at the end of the transition.
switch_tab(&page, cx, Tab::Statistics);
animate(&page, cx, Nothing);
start_switch(&page, cx, Tab::Challenge);
frame_after(cx, 200);
assert_eq!(played(&page, cx), [Mark, Completed]);
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(played(&page, cx), [Mark, Completed, Nothing]);
// Behind « Paramètres ».
cx.update(|window, cx| page.update(cx, |page, cx| page.hidden(window, cx)));
animate(&page, cx, Mark);
assert_eq!(played(&page, cx).len(), 3);
cx.update(|window, cx| page.update(cx, |page, cx| page.uncovered(window, cx)));
assert_eq!(played(&page, cx), [Mark, Completed, Nothing, Mark]);
}
#[gpui::test]
fn the_strongest_hidden_match_plays_on_its_own_tick_without_rebuilding_the_grid_or_statistics(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
cx.simulate_visibility_change(WindowVisibility::Hidden);
// Champion 1 validé, then a new Mark for champion 4.
round_with_matches(
&page,
cx,
&[(1, MatchEnd::Completed, 1), (4, MatchEnd::Mark, 4)],
);
cx.simulate_visibility_change(WindowVisibility::Visible);
assert!(
played(&page, cx).is_empty(),
"the new statistics are still loading"
);
let mut rows = champions(5);
rows[0] = banner_champion(1, "A", 1, Some(on(11, 20)), 0);
rows[3] = banner_champion(4, "D", 1, None, 0);
statistics_arrive(
&page,
cx,
Some(banner_statistics(
rows,
vec![1],
Some(LastMatch {
champion_id: 4,
placement: 5,
outcome: MatchOutcome::Attempt(1),
}),
)),
);
draw(cx);
let baseline = |cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| {
(
p.stats_generation,
p.reorders,
p.home_grid.read(cx).set_cards_calls,
p.ring.read(cx).renders,
// The bouncing crown is the ring's own, moved.
p.ring.read(cx).tessellations.get(),
)
})
};
// Deliver the statistics update's queued grid invalidation before measuring playback.
frame_after(cx, 16);
let first = baseline(cx);
// The comet flies to champion 1's tick, the one validé.
page.read_with(cx, |p, cx| {
let animation = p.playback.animation.unwrap();
let tick = p
.ring
.read(cx)
.animation(1, MatchEnd::Completed, animation.start);
assert_eq!(
(animation.index, animation.count, animation.end),
(tick.unwrap().index, 5, MatchEnd::Completed)
);
assert_eq!(p.playback.previous_card.as_ref().map(|c| c.id), Some(1));
});
let grid_renders =
|cx: &mut VisualTestContext| page.read_with(cx, |p, cx| p.home_grid.read(cx).renders);
let in_flight = grid_renders(cx);
for _ in 0..3 {
frame_after(cx, 200);
}
assert_eq!(grid_renders(cx), in_flight);
// The first last-Match line can change the banner's height once, at arrival.
frame_after(cx, 200);
let arrived = grid_renders(cx);
for _ in 0..10 {
frame_after(cx, 200);
}
assert_eq!(grid_renders(cx), arrived);
assert_eq!(baseline(cx), first);
assert!(page.read_with(cx, |p, _| p.playback.animation.is_none()));
assert_eq!(played(&page, cx), [MatchEnd::Completed]);
assert_at_rest(cx);
// The ring, the counter, the banner and the card end as a reload shows them.
let end_state = |cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| {
(
p.banner.clone(),
p.banner_art.read(cx).target.clone(),
p.ring.read(cx).ticks().to_vec(),
p.home_grid.read(cx).cards().to_vec(),
)
})
};
let ended = end_state(cx);
statistics_arrive(&page, cx, None);
draw(cx);
assert_eq!(end_state(cx), ended);
}
// The pointer on the grid when a followed Match changes it: the cards change in place, and
// the order, the cards and the filter prepared when the statistics arrive take their place
// once it leaves. Leaving sorts nothing and builds no card (rule #1).
#[gpui::test]
fn leaving_a_grid_a_match_held_still_puts_the_prepared_grid_in_place(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(
&page,
cx,
banner_statistics(banner_rows(), vec![2, 1], None),
);
draw(cx);
settle(cx);
let before = ["Garen", "Ahri", "Zyra", "Lux", "Brand"];
assert_eq!(home_names(&page, cx), before);
hover(cx, "card-2");
round_with_matches(&page, cx, &[(2, MatchEnd::Mark, 1)]);
let mut rows = banner_rows();
rows[1].mastery_points = Some(1000);
statistics_arrive(&page, cx, Some(banner_statistics(rows, vec![2, 1], None)));
draw(cx);
assert_eq!(
home_names(&page, cx),
before,
"the grid moved under the pointer"
);
let (reorders, prepared) = page.read_with(cx, |p, _| {
(
p.reorders,
p.next_home.as_ref().map(|next| next.cards.clone()),
)
});
let prepared = prepared.expect("nothing was prepared");
cx.simulate_mouse_move(point(px(5.), px(5.)), None, Modifiers::none());
draw(cx);
assert_eq!(
home_names(&page, cx),
["Brand", "Garen", "Ahri", "Zyra", "Lux"]
);
page.read_with(cx, |p, cx| {
assert_eq!(p.reorders, reorders, "leaving sorted the cards");
assert!(
Rc::ptr_eq(p.home_grid.read(cx).cards(), &prepared),
"leaving built the cards"
);
assert!(!p.hold_grid && p.next_home.is_none());
});
}
// « Restants » shown, a champion validé keeps its card until « Validé » has landed on it;
// then the filter leaves it out, as a reload does.
#[gpui::test]
fn a_card_the_filter_leaves_out_stays_until_its_match_has_played(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let mut rows = banner_rows();
rows[2] = banner_champion(4, "Garen", 2, None, 900);
show(&page, cx, banner_statistics(rows.clone(), vec![2, 1], None));
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
draw(cx);
assert_eq!(home_names(&page, cx), ["Garen", "Zyra", "Lux"]);
round_with_matches(&page, cx, &[(4, MatchEnd::Completed, 1)]);
rows[2] = banner_champion(4, "Garen", 3, Some(on(11, 21)), 900);
statistics_arrive(
&page,
cx,
Some(banner_statistics(rows, vec![2, 1, 4], None)),
);
draw(cx);
assert_eq!(home_names(&page, cx), ["Garen", "Zyra", "Lux"]);
until_landed(&page, cx);
assert_eq!(home_names(&page, cx), ["Garen", "Zyra", "Lux"]);
for _ in 0..10 {
frame_after(cx, 200);
}
assert!(page.read_with(cx, |p, _| p.playback.animation.is_none()));
assert_eq!(home_names(&page, cx), ["Zyra", "Lux"]);
assert_eq!(page.read_with(cx, |p, _| p.home_shown_count.clone()), "2");
draw(cx);
assert_at_rest(cx);
// A card the filter did not show is not added for its Match.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Completed;
p.home_filtered(cx);
});
assert_eq!(home_names(&page, cx), ["Garen", "Ahri", "Brand"]);
round_with_matches(&page, cx, &[(3, MatchEnd::Mark, 2)]);
statistics_arrive(&page, cx, None);
draw(cx);
assert_eq!(home_names(&page, cx), ["Garen", "Ahri", "Brand"]);
}
// The banner shows the last champion validé. The splash of a champion validé settles in when
// it is that one; a validation older than the banner's, whose Match arrived late, leaves the
// banner on the splash a reload shows.
#[gpui::test]
fn only_the_last_champion_validated_settles_into_the_banner(cx: &mut TestAppContext) {
let dir = TestDir::new("banner-late-validation");
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let shown_splash = |cx: &mut VisualTestContext| {
page.read_with(cx, |p, cx| {
let art = p.banner_art.read(cx);
let name = (art.target.as_ref())
.map(|s| s.path.file_name().unwrap().to_string_lossy().into_owned());
(name, art.revealing())
})
};
for (order, expected) in [
(vec![2, 1], ("Ahri.50.30.jpg", true)),
(vec![1, 2], ("Brand.50.30.jpg", false)),
] {
let mut rows = rows_with_splashes(dir.path());
rows[0] = ChampionRow {
splash: rows[0].splash.clone(),
..banner_champion(1, "Ahri", 2, None, 100)
};
show(&page, cx, banner_statistics(rows, vec![2], None));
draw(cx);
round_with_matches(&page, cx, &[(1, MatchEnd::Completed, 1)]);
statistics_arrive(
&page,
cx,
Some(banner_statistics(
rows_with_splashes(dir.path()),
order,
None,
)),
);
draw(cx);
until_landed(&page, cx);
let (name, revealing) = shown_splash(cx);
assert_eq!((name.as_deref(), revealing), (Some(expected.0), expected.1));
for _ in 0..10 {
frame_after(cx, 200);
}
}
}
#[gpui::test]
async fn a_champ_select_that_starts_abandons_the_animation_waiting(app: &mut TestAppContext) {
use crate::worker::Msg;
use arena_tracker_core::ChampSelect;
// The champ select's statistics are read on a worker thread.
app.executor().allow_parking();
let (page, cx) = open_page_in_season(app);
let cx = &mut { cx };
switch_tab(&page, cx, Tab::Statistics);
animate(&page, cx, MatchEnd::Completed);
let champ_select = ChampSelect::new(Some(39), [39].into(), Some(vec![39]));
cx.update(|window, cx| {
page.update(cx, |page, cx| {
page.apply(
Msg::ChampSelect(Some(("Alice#EUW".into(), champ_select))),
window,
cx,
)
})
});
app.condition(&page, |p, _| !p.stats_job.running()).await;
cx.update(|window, cx| {
page.update(cx, |page, cx| {
page.apply(Msg::ChampSelect(None), window, cx)
})
});
app.condition(&page, |p, _| !p.stats_job.running()).await;
draw(cx);
assert_eq!(played(&page, cx), []);
}
#[gpui::test]
fn without_animations_nothing_waits_nor_plays(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
animations(cx, false);
animate(&page, cx, MatchEnd::Mark);
cx.simulate_visibility_change(WindowVisibility::Hidden);
animate(&page, cx, MatchEnd::Completed);
cx.simulate_visibility_change(WindowVisibility::Visible);
assert_eq!(played(&page, cx), []);
page.read_with(cx, |p, _| {
assert!(!p.playback.active() && !p.playback.stats_pending);
});
// Nothing was kept for when the setting comes back.
animations(cx, true);
cx.simulate_visibility_change(WindowVisibility::Hidden);
cx.simulate_visibility_change(WindowVisibility::Visible);
assert_eq!(played(&page, cx), []);
}
#[gpui::test]
fn the_setting_turned_off_drops_the_animation_waiting(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
switch_tab(&page, cx, Tab::Statistics);
animate(&page, cx, MatchEnd::Completed);
// Off then on again, with nothing asked for meanwhile.
animations(cx, false);
animations(cx, true);
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(played(&page, cx), []);
}
#[gpui::test]
fn the_setting_turned_off_during_a_transition_ends_it(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
start_switch(&page, cx, Tab::Statistics);
frame_after(cx, 30);
animations(cx, false);
assert_eq!(shown_tab(&page, cx), Tab::Statistics);
assert!(page.read_with(cx, |page, _| page.fade.is_none()));
assert_at_rest(cx);
}
+224
View File
@@ -0,0 +1,224 @@
use super::page_fixtures::{
animations, assert_at_rest, center, champions, draw, frame_after, open_page,
open_page_in_season, show, shown_tab, start_switch, statistics, switch_tab, veil,
};
use crate::page::Tab;
use gpui_kit::{
KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext, VisualTestContext,
WindowVisibility,
};
#[gpui::test]
fn the_navigation_switches_tabs_with_the_mouse(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
let tab = |cx: &mut VisualTestContext| page.read_with(cx, |page, _| page.tab);
cx.update(|window, cx| window.draw(cx).clear(cx));
assert_eq!(tab(cx), Tab::Challenge);
let statistics = center(cx, "tab-statistics");
cx.simulate_click(statistics, Modifiers::none());
assert_eq!(tab(cx), Tab::Statistics);
cx.update(|window, cx| window.draw(cx).clear(cx));
let challenge = center(cx, "tab-challenge");
cx.simulate_click(challenge, Modifiers::none());
assert_eq!(tab(cx), Tab::Challenge);
}
#[gpui::test]
fn the_navigation_switches_tabs_with_the_keyboard(cx: &mut TestAppContext) {
let (page, cx) = open_page(cx);
let cx = &mut { cx };
cx.update(|window, cx| window.draw(cx).clear(cx));
// Tab reaches « Défi » first, then « Statistiques ».
cx.update(|window, cx| {
window.focus_next(cx);
window.focus_next(cx);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
let enter =
cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
cx.simulate_event(KeyDownEvent {
keystroke: enter.clone(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent { keystroke: enter });
assert_eq!(page.read_with(cx, |page, _| page.tab), Tab::Statistics);
}
#[gpui::test]
fn switching_tabs_veils_the_screen_leaving_then_unveils_the_one_arriving(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
start_switch(&page, cx, Tab::Statistics);
// The navigation follows at once; the screen leaving stays, going under the veil.
assert_eq!(page.read_with(cx, |page, _| page.tab), Tab::Statistics);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
frame_after(cx, 65);
let halfway = veil(&page, cx);
assert!(halfway > 0. && halfway < 1., "{halfway}");
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
// After 130 ms the other screen is under a full veil, which lifts in 280 ms.
frame_after(cx, 70);
assert_eq!(shown_tab(&page, cx), Tab::Statistics);
assert!(veil(&page, cx) > 0.9);
frame_after(cx, 280);
assert_eq!(veil(&page, cx), 0.);
assert_at_rest(cx);
}
#[gpui::test]
fn without_animations_or_with_the_window_hidden_the_other_screen_shows_at_once(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
// The Windows « Show animations » setting is off.
animations(cx, false);
start_switch(&page, cx, Tab::Statistics);
assert_eq!(shown_tab(&page, cx), Tab::Statistics);
assert!(page.read_with(cx, |page, _| page.fade.is_none()));
assert_at_rest(cx);
animations(cx, true);
cx.simulate_visibility_change(WindowVisibility::Hidden);
start_switch(&page, cx, Tab::Challenge);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
assert!(page.read_with(cx, |page, _| page.fade.is_none()));
assert_at_rest(cx);
}
#[gpui::test]
fn a_window_hidden_during_a_transition_ends_it(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
start_switch(&page, cx, Tab::Statistics);
frame_after(cx, 30);
cx.simulate_visibility_change(WindowVisibility::Hidden);
assert_eq!(shown_tab(&page, cx), Tab::Statistics);
assert!(page.read_with(cx, |page, _| page.fade.is_none()));
assert_at_rest(cx);
}
#[gpui::test]
fn a_switch_back_during_a_transition_starts_from_where_the_veil_is(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
start_switch(&page, cx, Tab::Statistics);
frame_after(cx, 100);
let before = veil(&page, cx);
assert!(before > 0.);
// « Défi » is still the screen shown: it comes back out of the veil, without a jump.
start_switch(&page, cx, Tab::Challenge);
assert_eq!(veil(&page, cx), before);
frame_after(cx, 280);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
assert_eq!(veil(&page, cx), 0.);
}
// The transition only lays a veil over the screen: under it, the cached views are drawn
// from their cache, and nothing is computed again (rule #1).
#[gpui::test]
fn a_transition_neither_builds_the_cards_again_nor_recomputes_the_statistics(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 170, champions(170)));
draw(cx);
let (grid, ring, table) = page.read_with(cx, |page, _| {
(
page.home_grid.clone(),
page.ring.clone(),
page.table.clone(),
)
});
let table_renders = |cx: &mut VisualTestContext| table.read_with(cx, |table, _| table.renders);
let generation = page.read_with(cx, |page, _| page.stats_generation);
let built = |cx: &mut VisualTestContext| {
let ring = ring.read_with(cx, |ring, _| ring.renders);
grid.read_with(cx, |grid, _| {
(grid.renders, grid.card_builds, grid.set_cards_calls, ring)
})
};
let home = built(cx);
// « Défi » leaves under the veil without its grid or its ring being drawn again.
start_switch(&page, cx, Tab::Statistics);
for _ in 0..5 {
frame_after(cx, 30);
}
assert_eq!(shown_tab(&page, cx), Tab::Statistics);
assert_eq!(built(cx), home, "the cards were built again");
// « Statistiques » arrives: its table is drawn once, not at each frame of the veil. (The
// charts arriving play their own short entry, as after any switch.)
let arrived = table_renders(cx);
for _ in 0..8 {
frame_after(cx, 40);
}
assert_eq!(veil(&page, cx), 0.);
assert_eq!(
table_renders(cx),
arrived,
"the table was drawn at each frame"
);
// Back to « Défi »: the table leaves without being drawn again; the grid and the ring
// are drawn once, then not again.
start_switch(&page, cx, Tab::Challenge);
for _ in 0..4 {
frame_after(cx, 30);
}
assert_eq!(
table_renders(cx),
arrived,
"the table was drawn at each frame"
);
frame_after(cx, 30);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
let back = built(cx);
for _ in 0..8 {
frame_after(cx, 40);
}
assert_eq!(veil(&page, cx), 0.);
assert_eq!(built(cx), back, "the cards were built again");
assert_eq!(
page.read_with(cx, |page, _| page.stats_generation),
generation
);
assert!(!page.read_with(cx, |page, _| page.stats_job.running()));
}
#[gpui::test]
fn a_switch_undone_under_the_veil_prepares_nothing(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 5, champions(5)));
draw(cx);
let table = page.read_with(cx, |page, _| page.table.clone());
start_switch(&page, cx, Tab::Statistics);
frame_after(cx, 60);
switch_tab(&page, cx, Tab::Challenge);
assert_eq!(shown_tab(&page, cx), Tab::Challenge);
// « Statistiques » was never shown: its rows were neither copied nor sorted.
assert!(table.read_with(cx, |table, _| table.names()).is_empty());
switch_tab(&page, cx, Tab::Statistics);
assert_eq!(table.read_with(cx, |table, _| table.names()).len(), 5);
}
+490
View File
@@ -0,0 +1,490 @@
use crate::card_grid::CardGrid;
use crate::champion_table::tests::row;
use crate::motion::MatchEnd;
use crate::page::{Page, Tab};
use arena_tracker_core::{
Account, ChallengeSummary, Champion, ChampionChallenge, ChampionRow, ChampionSort,
ChampionState, Charts, Date, FollowedMatch, Format, MatchHistorySource, RiotApi, Season,
SourceError, Statistics, Status, Tracker,
};
use gpui_kit::base::async_util::unbounded;
use gpui_kit::{
AppContext, Bounds, Entity, Focusable, Modifiers, TestAppContext, VisualTestContext,
WindowBounds, WindowOptions, point, px, size,
};
use std::cell::Cell;
use std::path::Path;
use std::rc::Rc;
use std::sync::Arc;
use std::time::Duration;
pub(super) const MATCH_1750: &str =
include_str!("../../../../core/tests/fixtures/riot/match_1750_EUW1_9000000006.json");
/// Switches to a tab, and lets its transition end.
pub(super) fn switch_tab(page: &Entity<Page>, cx: &mut VisualTestContext, tab: Tab) {
cx.update(|window, cx| page.update(cx, |page, cx| page.set_tab(tab, window, cx)));
for _ in 0..10 {
if page.read_with(cx, |page, _| page.fade.is_none()) {
return;
}
frame_after(cx, 50);
}
panic!("the transition did not end");
}
pub(super) fn open_page(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
open_page_with_tracker(
cx,
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
)
}
pub(super) fn open_page_with_tracker(
cx: &mut TestAppContext,
tracker: Tracker,
) -> (Entity<Page>, VisualTestContext) {
open_page_with_sort(cx, tracker, None)
}
/// `champion_sort`: the sort saved by an earlier run.
pub(super) fn open_page_with_sort(
cx: &mut TestAppContext,
tracker: Tracker,
champion_sort: Option<ChampionSort>,
) -> (Entity<Page>, VisualTestContext) {
cx.update(gpui_kit::init);
cx.update(crate::card_grid::init);
let tracker = Arc::new(tracker);
let (window, page) = cx.update(|cx| {
let (tx, rx) = unbounded();
let bounds = Bounds {
origin: point(px(0.), px(0.)),
size: size(px(1280.), px(860.)),
};
let options = WindowOptions {
window_bounds: Some(WindowBounds::Windowed(bounds)),
..Default::default()
};
gpui_kit::open_window(options, cx, |window, cx| {
cx.new(|cx| {
Page::new(
tracker,
crate::page::Launch {
notice: None,
following: false,
champion_sort,
},
rx,
tx,
window,
cx,
)
})
})
.unwrap()
});
(page, VisualTestContext::from_window(window, cx))
}
pub(super) struct RefreshHistory;
impl MatchHistorySource for RefreshHistory {
fn resolve_account(&self, game_name: &str, tag_line: &str) -> Result<Account, SourceError> {
Ok(Account {
puuid: game_name.into(),
game_name: game_name.into(),
tag_line: tag_line.into(),
})
}
fn match_ids(
&self,
puuid: &str,
queue_id: u32,
start: usize,
_: usize,
_: Option<i64>,
) -> Result<Vec<String>, SourceError> {
Ok(if puuid == "Alice" && queue_id == 1750 && start == 0 {
vec!["EUW1_9000000006".into()]
} else {
Vec::new()
})
}
fn fetch_match(&self, _: &str) -> Result<String, SourceError> {
Ok(MATCH_1750.replace("fixture-puuid-self", "Alice"))
}
}
/// A page on Alice's 3x6 statistics with the Format filter set, whose refresh worker meets Bob
/// (the client adopted another Account) before the UI does.
pub(super) async fn refresh_towards_bob(cx: &mut TestAppContext, pin_alice: bool) -> Entity<Page> {
cx.executor().allow_parking();
let tracker = Tracker::open(Path::new(":memory:"), Box::new(RefreshHistory))
.unwrap()
.with_seasons(Vec::new());
tracker.sync("Alice#EUW", &mut |_| {}).unwrap();
let (page, mut window) = open_page_with_tracker(cx, tracker);
window.update(|window, cx| {
page.update(cx, |page, cx| {
assert_eq!(page.viewed().unwrap().puuid, "Alice");
assert_eq!(page.stats.as_ref().unwrap().formats, [Format::Arena3x6]);
if pin_alice {
page.pinned = Some("Alice".into());
}
page.format = Some(Format::Arena3x6);
page.recompute(window, cx);
page.tracker.follow_client(0, Some("Bob#EUW"), &mut |_| {});
page.request_refresh(cx);
});
});
cx.condition(&page, |page, _| !page.busy()).await;
page
}
pub(super) fn season(name: &str, year: i32) -> Season {
Season {
name: name.into(),
start: Date {
year,
month: 1,
day: 1,
},
official_track: None,
}
}
/// A page with a current Season (and no Account), on made-up statistics.
pub(super) fn open_page_in_season(cx: &mut TestAppContext) -> (Entity<Page>, VisualTestContext) {
open_page_with_tracker(
cx,
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season("Saison", 2020)]),
)
}
pub(super) fn statistics(completed: usize, total: usize, rows: Vec<ChampionRow>) -> Statistics {
Statistics {
challenge: Some(ChallengeSummary {
completed,
total,
attempts: 0,
average_attempts: None,
first_tries: 0,
completion_order: Vec::new(),
last_match: None,
}),
rows,
charts: Charts {
// Not empty, so the charts row has something new to draw.
placements: vec![(1, 2)],
completed_over_time: Vec::new(),
attempts_to_complete: [0; 5],
},
formats: Vec::new(),
}
}
pub(super) fn show(page: &Entity<Page>, cx: &mut VisualTestContext, stats: Statistics) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
page.stats = Some(stats);
page.show_statistics(window, cx);
})
});
}
/// Without statistics the home says why there is nothing, rather than count « 0 » champions
/// above a grid that says none matches.
pub(super) fn assert_home_says(
window: &mut VisualTestContext,
notice: crate::page::home::StatsNotice,
) {
draw(window);
assert_eq!(
window.debug_bounds("home-notice").is_some(),
!matches!(notice, crate::page::home::StatsNotice::Error)
);
assert!(window.debug_bounds("home-tools").is_none());
assert!(window.debug_bounds("card-list").is_none());
assert!(window.debug_bounds("no-champion").is_none());
}
pub(super) fn grid_names(grid: &Entity<CardGrid>, cx: &mut VisualTestContext) -> Vec<String> {
grid.read_with(cx, |grid, _| {
grid.names().iter().map(|name| name.to_string()).collect()
})
}
pub(super) fn draw(cx: &mut VisualTestContext) {
cx.update(|window, cx| window.draw(cx).clear(cx));
}
/// Never played champions with distinct ids, in A to Z order.
pub(super) fn champions(count: u32) -> Vec<ChampionRow> {
(1..=count)
.map(|id| ChampionRow {
champion: Champion {
id,
key: format!("Champion{id}"),
name: format!("Champion {id:03}"),
},
state: Some(ChampionState::NeverPlayed),
challenge: Some(ChampionChallenge::default()),
..row("")
})
.collect()
}
/// How many times the card under the pointer or the keyboard changes in `grid`.
pub(super) fn count_hovers(grid: &Entity<CardGrid>, cx: &mut VisualTestContext) -> Rc<Cell<usize>> {
let hovers = Rc::new(Cell::new(0));
let counted = hovers.clone();
cx.update(|_, cx| {
cx.subscribe(grid, move |_, _: &crate::card_grid::CardHovered, _| {
counted.set(counted.get() + 1)
})
.detach()
});
hovers
}
pub(super) fn center(
cx: &mut VisualTestContext,
id: &'static str,
) -> gpui_kit::Point<gpui_kit::Pixels> {
cx.debug_bounds(id).unwrap().center()
}
/// `champions`, the first one Completed (first top 1 on 2 March 2026) and the second one
/// remaining with a 2nd place.
pub(super) fn sheet_champions(count: u32) -> Vec<ChampionRow> {
let mut rows = champions(count);
rows[0].state = Some(ChampionState::Completed);
rows[0].attempts = Some(3);
rows[0].challenge = Some(ChampionChallenge {
matches: 4,
wins: 2,
best_placement: Some(1),
completed_on: Some(Date {
year: 2026,
month: 3,
day: 2,
}),
});
rows[1].state = Some(ChampionState::InProgress);
rows[1].attempts = Some(2);
rows[1].challenge = Some(ChampionChallenge {
matches: 2,
wins: 1,
best_placement: Some(2),
completed_on: None,
});
rows
}
pub(super) const DATE: &str = "Premier top 1";
/// Whether the card's sheet was built in the last draw, and then whether it has the date.
pub(super) fn sheet(cx: &mut VisualTestContext, id: u32) -> Option<bool> {
cx.debug_bounds(Box::leak(format!("sheet-{id}").into_boxed_str()))?;
Some(
cx.debug_bounds(Box::leak(format!("sheet-{id}-{DATE}").into_boxed_str()))
.is_some(),
)
}
/// The cards showing their sheet once their lift has played.
pub(super) fn sheet_ids(cx: &mut VisualTestContext, count: u32) -> Vec<u32> {
settle(cx);
(1..=count).filter(|&id| sheet(cx, id).is_some()).collect()
}
/// How far the lifted card `id` stands above its place in the grid, if it is drawn lifted.
pub(super) fn rise(cx: &mut VisualTestContext, id: u32) -> Option<f32> {
let lifted = cx.debug_bounds(Box::leak(format!("lifted-{id}").into_boxed_str()))?;
let place = cx
.debug_bounds(Box::leak(format!("card-{id}").into_boxed_str()))
.unwrap();
assert_eq!(lifted.size, place.size, "the lifted card changed size");
Some((place.origin.y - lifted.origin.y).as_f32())
}
pub(super) fn hover(cx: &mut VisualTestContext, id: &'static str) {
let at = center(cx, id);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
}
/// The focus on the sort selector, the last stop of the home's tools before the cards, in
/// the window in front: the focus moves only there.
pub(super) fn focus_sort(page: &Entity<Page>, cx: &mut VisualTestContext) {
let select = page.read_with(cx, |p, _| p.sort_select.clone());
cx.update(|window, cx| {
window.activate_window();
let handle = select.read(cx).focus_handle(cx);
window.focus(&handle, cx)
});
draw(cx);
}
pub(super) fn press(cx: &mut VisualTestContext, keys: &str) {
cx.simulate_keystrokes(keys);
draw(cx);
}
/// Lets the cards lifting or settling back reach where they go.
pub(super) fn settle(cx: &mut VisualTestContext) {
frame_after(cx, 400);
}
/// Moves the test clock on, then delivers the next frame as the display would.
pub(super) fn frame_after(cx: &mut VisualTestContext, ms: u64) {
cx.executor().advance_clock(Duration::from_millis(ms));
cx.update(|window, cx| {
window.simulate_next_frame(cx);
window.draw(cx).clear(cx);
});
}
pub(super) fn veil(page: &Entity<Page>, cx: &mut VisualTestContext) -> f32 {
page.read_with(cx, |page, cx| page.veil(cx))
}
pub(super) fn shown_tab(page: &Entity<Page>, cx: &mut VisualTestContext) -> Tab {
page.read_with(cx, |page, _| page.shown_tab)
}
/// Turns the Windows « Show animations » setting on or off, as its window message does.
pub(super) fn animations(cx: &mut VisualTestContext, on: bool) {
cx.update(|_, cx| {
cx.set_reduce_motion(!on);
cx.set_global(crate::motion::AnimationSetting);
});
}
/// Asks for a tab, without waiting for its transition.
pub(super) fn start_switch(page: &Entity<Page>, cx: &mut VisualTestContext, tab: Tab) {
cx.update(|window, cx| page.update(cx, |page, cx| page.set_tab(tab, window, cx)));
draw(cx);
}
/// A follower round reports Matches of the viewed Account, as (champion, what it brought,
/// start), the way the follower does.
pub(super) fn round_with_matches(
page: &Entity<Page>,
cx: &mut VisualTestContext,
matches: &[(u32, MatchEnd, i64)],
) {
use crate::worker::Msg;
let matches = matches
.iter()
.map(|&(champion_id, end, started_at_ms)| FollowedMatch {
puuid: "p".into(),
season: "Saison".into(),
champion_id,
started_at_ms,
end,
})
.collect();
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let status = Status {
updating: Some(Account {
puuid: "p".into(),
game_name: "Alice".into(),
tag_line: "EUW".into(),
}),
..page.status.clone()
};
page.apply(
Msg::Round {
status,
reload: false,
matches,
},
window,
cx,
)
})
});
}
/// The statistics job the round started ends with `stats`, else with those shown.
pub(super) fn statistics_arrive(
page: &Entity<Page>,
cx: &mut VisualTestContext,
stats: Option<Statistics>,
) {
cx.update(|window, cx| {
page.update(cx, |page, cx| {
let stats = stats
.or_else(|| page.stats.clone())
.unwrap_or_else(|| statistics(0, 5, champions(5)));
page.apply(
crate::worker::Msg::Statistics {
generation: page.stats_generation,
stats: Ok(stats),
home: None,
stored: Some(1),
},
window,
cx,
)
})
});
}
/// The end of a followed Match with champion 1, through the round and the statistics.
pub(super) fn animate(page: &Entity<Page>, cx: &mut VisualTestContext, end: MatchEnd) {
round_with_matches(page, cx, &[(1, end, 0)]);
statistics_arrive(page, cx, None);
}
pub(super) fn played(page: &Entity<Page>, cx: &mut VisualTestContext) -> Vec<MatchEnd> {
page.read_with(cx, |page, _| page.played.clone())
}
pub(super) fn home_names(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Vec<gpui_kit::SharedString> {
page.read_with(cx, |p, cx| p.home_grid.read(cx).names())
}
/// Frames until the comet of the animation playing lands.
pub(super) fn until_landed(page: &Entity<Page>, cx: &mut VisualTestContext) {
for _ in 0..20 {
frame_after(cx, 100);
if page.read_with(cx, |p, _| p.playback.previous_banner.is_none()) {
return;
}
}
panic!("the comet never landed");
}
/// Nothing is drawn at rest: once gpui-kit's own short animations are over (the filters'
/// pill arrives with « Statistiques »), no frame is asked for.
pub(super) fn assert_at_rest(cx: &mut VisualTestContext) {
frame_after(cx, 1000);
let asked: Vec<usize> = (0..3)
.map(|_| {
cx.executor().advance_clock(Duration::from_millis(100));
let asked = cx.update(|window, cx| window.simulate_next_frame(cx));
draw(cx);
asked
})
.collect();
assert_eq!(asked, [0; 3]);
}
+350
View File
@@ -0,0 +1,350 @@
use super::champ_select_fixtures::{
ANVIL, OTHERS_A_TO_Z, card_portrait, click_others, frames, ids, joueur_tracker, leave,
others_cards, others_open, page_in_champ_select, scroll_champ_select_down, send,
tracker_with_portraits,
};
use super::page_fixtures::{draw, open_page_with_tracker, switch_tab};
use crate::card_grid::CardGrid;
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
use crate::page::{Page, Tab};
use arena_tracker_core::{Format, SeasonScope};
use gpui_kit::{Entity, TestAppContext, VisualTestContext, px};
// The worker saves a portrait, then tells the page: the card shows it without a restart.
#[gpui::test]
async fn a_card_portrait_saved_while_the_app_runs_shows_once_the_worker_tells(
cx: &mut TestAppContext,
) {
cx.executor().allow_parking();
let dir = TestDir::new("portrait-arrives");
let (page, mut window) = open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &[]));
let grid = page.read_with(&window, |p, _| p.home_grid.clone());
let ahri = |grid: &CardGrid| {
let cards = grid.shown_cards().into_iter();
cards
.filter(|card| card.id == 103)
.map(|card| card.portrait.map(|path| path.to_path_buf()))
.next()
};
assert_eq!(grid.read_with(&window, |grid, _| ahri(grid)), Some(None));
draw(&mut window);
let path = card_portrait(dir.path(), "Ahri");
std::fs::write(&path, PORTRAIT_JPEG).unwrap();
window.update(|w, cx| page.update(cx, |p, cx| p.apply(crate::worker::Msg::Champions, w, cx)));
cx.condition(&grid, |grid, _| ahri(grid) == Some(Some(path.clone())))
.await;
// Drawn, through the grid's own cache.
draw(&mut window);
window.run_until_parked();
draw(&mut window);
let images = grid.read_with(&window, |grid, _| grid.images().cloned());
let images = images.expect("the grid was not drawn");
assert_eq!(images.read_with(&window, |i, _| i.held()), [path]);
assert_eq!(images.read_with(&window, |i, _| i.loaded()).len(), 1);
}
// The Anvil row is a grid of its own, not cached, with no `uniform_list`: its portraits go
// through its own cache too, never through the app-wide one.
#[gpui::test]
async fn the_anvil_row_reads_its_portraits_through_its_own_cache(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("anvil-portraits");
let keys = ["Briar", "LeeSin", "Rumble", "Soraka", "XinZhao"];
let (page, mut window) = open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
window.run_until_parked();
draw(&mut window);
let grid = page.read_with(&window, |p, _| p.anvil_grid.clone());
let images = grid.read_with(&window, |grid, _| grid.images().cloned());
let images = images.expect("the row was not drawn");
let mut expected: Vec<_> = keys
.iter()
.map(|key| card_portrait(dir.path(), key))
.collect();
expected.sort();
assert_eq!(images.read_with(&window, |i, _| i.held()), expected);
let loaded = images.read_with(&window, |i, _| i.loaded());
assert_eq!(loaded.len(), keys.len());
window.update(|w, cx| {
assert!(loaded.iter().all(|image| w.has_image_atlas_entry(image)));
for path in &expected {
let source = gpui_kit::ImageSource::from(path.clone());
assert!(!source.is_asset_cached(cx), "{path:?}");
}
});
}
// Folding « Autres champions » drops its grid, and with it its portraits, on the GPU too.
#[gpui::test]
async fn folding_others_frees_its_portraits(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("others-portraits");
let keys = ["Ahri", "Alistar", "Morgana", "Swain"];
let (page, mut window) = open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
click_others(&mut window);
scroll_champ_select_down(&mut window);
window.run_until_parked();
draw(&mut window);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
let grid = page.read_with(&window, |p, _| p.others_grid.clone());
let images = grid.read_with(&window, |grid, _| grid.images().cloned());
let images = images.expect("the section was not drawn");
let loaded = images.read_with(&window, |i, _| i.loaded());
assert_eq!(loaded.len(), keys.len());
let in_atlas = |window: &mut VisualTestContext| {
window.update(|w, _| {
(loaded.iter())
.filter(|image| w.has_image_atlas_entry(image))
.count()
})
};
assert_eq!(in_atlas(&mut window), keys.len());
let weak = images.downgrade();
drop((images, grid));
click_others(&mut window);
assert!(!others_open(&page, &mut window));
window.run_until_parked();
assert!(weak.upgrade().is_none(), "the folded grid's cache is kept");
assert_eq!(in_atlas(&mut window), 0);
}
// A grid that is not shown gives its portraits back, on the GPU too, and loads them again
// when it is shown.
#[gpui::test]
async fn a_grid_that_is_not_shown_gives_its_portraits_back(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let dir = TestDir::new("hidden-portraits");
let keys = [
"Ahri", "Alistar", "Briar", "LeeSin", "Morgana", "Rumble", "Soraka", "Swain", "XinZhao",
];
let (page, mut window) = open_page_with_tracker(cx, tracker_with_portraits(dir.path(), &keys));
let load = |window: &mut VisualTestContext| {
draw(window);
window.run_until_parked();
draw(window);
};
let held = |grid: &Entity<CardGrid>, window: &mut VisualTestContext| {
let images = grid.read_with(window, |grid, _| grid.images().cloned());
let images = images.expect("the grid was never drawn");
images.read_with(window, |images, _| images.held().len())
};
let home = page.read_with(&window, |p, _| p.home_grid.clone());
load(&mut window);
assert_eq!(held(&home, &mut window), keys.len());
let images = home.read_with(&window, |grid, _| grid.images().cloned().unwrap());
let loaded = images.read_with(&window, |i, _| i.loaded());
assert_eq!(loaded.len(), keys.len());
let in_atlas = |window: &mut VisualTestContext| {
window.update(|w, _| {
(loaded.iter())
.filter(|image| w.has_image_atlas_entry(image))
.count()
})
};
assert_eq!(in_atlas(&mut window), keys.len());
// « Statistiques » shows no card.
switch_tab(&page, &mut window, Tab::Statistics);
draw(&mut window);
assert_eq!(held(&home, &mut window), 0);
assert!(images.read_with(&window, |i, _| i.loaded()).is_empty());
assert_eq!(in_atlas(&mut window), 0);
// Back on « Défi » they load again.
switch_tab(&page, &mut window, Tab::Challenge);
load(&mut window);
assert_eq!(held(&home, &mut window), keys.len());
assert_eq!(
images.read_with(&window, |i, _| i.loaded()).len(),
keys.len()
);
// A champ select takes the home's place with its own sections.
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| p.stats.is_some()).await;
load(&mut window);
assert_eq!(held(&home, &mut window), 0);
let anvil = page.read_with(&window, |p, _| p.anvil_grid.clone());
assert_eq!(held(&anvil, &mut window), ANVIL.len());
// And gives the Anvil row up when it ends.
leave(&page, &mut window);
assert_eq!(held(&anvil, &mut window), 0);
cx.condition(&page, |p, _| p.stats.is_some()).await;
load(&mut window);
assert_eq!(held(&home, &mut window), keys.len());
assert_eq!(held(&anvil, &mut window), 0);
}
// « Autres champions » opens under the Anvil row, in the page's scrolling: its cards are built
// whole, in a 860 px window, where the page is scrolled to them.
#[gpui::test]
async fn the_open_others_grid_builds_whole_cards_in_the_page(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
click_others(&mut window);
scroll_champ_select_down(&mut window);
let card = window
.debug_bounds("card-103")
.expect("the open section's grid is not drawn");
assert!(card.size.height > px(200.), "{card:?}");
assert!(card.bottom() <= px(860.), "{card:?}");
assert!(others_open(&page, &mut window));
}
/// The statistics' error is the banner's alone during a champ select: the Anvil area does
/// not repeat it, and nothing is left to browse.
#[gpui::test]
async fn a_statistics_error_is_said_once_during_a_champ_select(cx: &mut TestAppContext) {
let (page, mut window) = page_in_champ_select(cx, &frames()[0]).await;
let error = "Statistiques indisponibles : disque plein";
window.update(|_, cx| {
page.update(cx, |p, cx| {
p.stats = None;
p.stats_error = Some(error.into());
p.prepare_champ_select(cx);
cx.notify();
})
});
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(
p.stats_notice(),
Some(crate::page::home::StatsNotice::Error)
);
assert_eq!(p.error().map(String::as_str), Some(error));
});
// The banner says it; the area says nothing and offers nothing to browse.
assert!(window.debug_bounds("anvil-notice").is_none());
assert!(window.debug_bounds("anvil-row").is_none());
assert!(window.debug_bounds("others-toggle").is_none());
assert!(window.debug_bounds("no-season").is_none());
}
// The Season's statistics are computed once while the Format changes: it does not apply to
// the home.
#[gpui::test]
async fn changing_the_format_recomputes_only_the_statistics_scope(cx: &mut TestAppContext) {
use crate::worker::COMPUTED;
use arena_tracker_core::Scope;
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker());
let scope = |season: SeasonScope, format| Scope { season, format };
let saison = || SeasonScope::Season("Saison".into());
let computed = |window: &mut VisualTestContext, change: &dyn Fn(&mut Page)| {
COMPUTED.with(|computed| computed.borrow_mut().clear());
window.update(|w, cx| {
page.update(cx, |p, cx| {
change(p);
p.recompute(w, cx)
})
});
COMPUTED.with(|computed| computed.borrow().clone())
};
// A Format: the statistics for it, and the home's, which were read from the former.
let first = computed(&mut window, &|p| p.format = Some(Format::Arena3x6));
assert_eq!(
first,
[
scope(saison(), Some(Format::Arena3x6)),
scope(saison(), None)
]
);
// Another Format: the home's statistics are kept.
let kept = page.read_with(&window, |p, _| p.home_stats.clone());
let second = computed(&mut window, &|p| p.format = Some(Format::BraveryArena));
assert_eq!(second, [scope(saison(), Some(Format::BraveryArena))]);
page.read_with(&window, |p, _| {
assert!(p.home_stats.is_some() && p.home_stats == kept);
});
// All the Seasons while the current one is the home's: same scope, kept.
let third = computed(&mut window, &|p| p.season = SeasonScope::AllSeasons);
assert_eq!(
third,
[scope(SeasonScope::AllSeasons, Some(Format::BraveryArena))]
);
// Back to « Tous les Formats » on the current Season: the statistics are the home's.
let fourth = computed(&mut window, &|p| {
p.season = saison();
p.format = None;
});
assert_eq!(fourth, [scope(saison(), None)]);
page.read_with(&window, |p, _| assert!(p.home_stats.is_none()));
// A Format again: the home's statistics were the Statistics tab's, and are computed.
let fifth = computed(&mut window, &|p| {
p.format = Some(Format::Arena3x6);
});
assert_eq!(
fifth,
[
scope(saison(), Some(Format::Arena3x6)),
scope(saison(), None)
]
);
}
/// The reasons of the capture on the cards of « Autres champions », drawn end to end.
#[gpui::test]
async fn a_reason_appearing_on_a_card_of_others_is_drawn_without_moving_it(
cx: &mut TestAppContext,
) {
let frames = frames();
let (page, mut window) = page_in_champ_select(cx, &frames[0]).await;
click_others(&mut window);
scroll_champ_select_down(&mut window);
let name = |prefix: &str, id: u32, label: &str| -> &'static str {
Box::leak(format!("{prefix}-{id}{label}").into_boxed_str())
};
let badge = |window: &mut VisualTestContext, id: u32, label: &str| {
window
.debug_bounds(name("reason", id, &format!("-{label}")))
.is_some()
};
let places = |window: &mut VisualTestContext| {
OTHERS_A_TO_Z.map(|id| {
window
.debug_bounds(name("card", id, ""))
.expect("not drawn")
})
};
let first = places(&mut window);
for id in OTHERS_A_TO_Z {
assert!(!badge(&mut window, id, "Banni"), "frame 0, {id}");
}
// Frame 1: 12 is banned; 25 is only an ally's pre-pick, which leaves it as it is.
send(&page, &mut window, &frames[1]);
draw(&mut window);
assert!(badge(&mut window, 12, "Banni"));
assert!(!badge(&mut window, 25, "Pris par un allié"));
assert!(!badge(&mut window, 25, "Banni"));
assert!(!badge(&mut window, 50, "Banni"));
assert_eq!(places(&mut window), first);
// Frame 2: 50 too.
send(&page, &mut window, &frames[2]);
draw(&mut window);
assert!(badge(&mut window, 12, "Banni") && badge(&mut window, 50, "Banni"));
assert!(!badge(&mut window, 25, "Pris par un allié"));
assert_eq!(places(&mut window), first);
// Frame 3: the ally confirms 25.
for frame in [&frames[3], &frames[4]] {
send(&page, &mut window, frame);
draw(&mut window);
assert!(badge(&mut window, 25, "Pris par un allié"));
assert!(badge(&mut window, 12, "Banni") && badge(&mut window, 50, "Banni"));
assert!(!badge(&mut window, 103, "Banni"));
assert_eq!(places(&mut window), first);
}
}
+250
View File
@@ -0,0 +1,250 @@
use super::champ_select_fixtures::{
ALL_A_TO_Z, ANVIL_A_TO_Z, ANVIL_BY_MASTERY, OTHERS_A_TO_Z, OTHERS_BY_MASTERY, anvil_cards,
click_others, frames, ids, joueur_tracker_with, leave, others_cards, reasons, send,
};
use super::page_fixtures::{
center, draw, grid_names, open_page_in_season, open_page_with_sort, open_page_with_tracker,
season, show, statistics,
};
use super::sorting_fixtures::{
A_TO_Z, BY_MASTERY, pick_sort, record_sorts, reorders, rows_with_points,
};
use crate::card::Reason;
use arena_tracker_core::{ChampionRow, ChampionSort, RiotApi, StateFilter, Tracker};
use gpui_kit::{Modifiers, TestAppContext, VisualTestContext};
use std::path::Path;
#[gpui::test]
fn the_home_follows_the_mastery_points_until_another_sort_is_chosen(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let chosen = record_sorts(&page, cx);
show(&page, cx, statistics(0, 6, rows_with_points()));
draw(cx);
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
// Nothing chosen: Mastery Points descending, ties by name, unknown ones last.
assert_eq!(page.read_with(cx, |p, _| p.champion_sort), None);
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
assert!(cx.debug_bounds("sort").is_some());
let generation = page.read_with(cx, |p, _| p.stats_generation);
let before = reorders(&page, cx);
pick_sort(&page, cx, "A–Z");
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(*chosen.borrow(), [ChampionSort::Name]);
page.read_with(cx, |p, _| {
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
// The statistics are as they were: only the cards moved.
assert_eq!(p.stats_generation, generation);
let rows = p.stats.as_ref().unwrap().rows.iter();
assert_eq!(
rows.map(|r| r.champion.name.as_str()).collect::<Vec<_>>(),
A_TO_Z
);
});
assert_eq!(reorders(&page, cx), before + 1);
// The filter and the search apply to the new order.
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(grid_names(&grid, cx), A_TO_Z);
pick_sort(&page, cx, "Maîtrise");
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
assert_eq!(
*chosen.borrow(),
[ChampionSort::Name, ChampionSort::Mastery]
);
// Choosing what is already chosen reports nothing.
pick_sort(&page, cx, "Maîtrise");
assert_eq!(chosen.borrow().len(), 2);
}
#[gpui::test]
fn without_any_known_value_the_cards_are_a_to_z_and_the_preference_is_untouched(
cx: &mut TestAppContext,
) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
let chosen = record_sorts(&page, cx);
let unknown: Vec<ChampionRow> = rows_with_points()
.into_iter()
.map(|row| ChampionRow {
mastery_points: None,
..row
})
.collect();
show(&page, cx, statistics(0, 6, unknown));
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(page.read_with(cx, |p, _| p.champion_sort), None);
assert!(chosen.borrow().is_empty());
// The cards say it: unknown, not zero.
let sheets = grid.read_with(cx, |grid, _| grid.shown_cards());
assert!(sheets.iter().all(|card| {
card.sheet
.iter()
.any(|(label, value)| *label == "Points de maîtrise" && value == "Inconnus")
}));
// Mastery chosen on purpose is still A to Z while nothing is known, and is saved.
pick_sort(&page, cx, "Maîtrise");
assert_eq!(grid_names(&grid, cx), A_TO_Z);
assert_eq!(*chosen.borrow(), [ChampionSort::Mastery]);
// The points arrive: the preference now applies.
show(&page, cx, statistics(0, 6, rows_with_points()));
assert_eq!(grid_names(&grid, cx), BY_MASTERY);
}
#[gpui::test]
fn a_saved_sort_is_there_at_the_first_draw(cx: &mut TestAppContext) {
let tracker = Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(vec![season("Saison", 2020)]);
let (page, cx) = open_page_with_sort(cx, tracker, Some(ChampionSort::Name));
let cx = &mut { cx };
show(&page, cx, statistics(0, 6, rows_with_points()));
let grid = page.read_with(cx, |p, _| p.home_grid.clone());
assert_eq!(grid_names(&grid, cx), A_TO_Z);
page.read_with(cx, |p, _| {
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
assert_eq!(p.home_filter, StateFilter::All);
});
}
#[gpui::test]
fn the_cards_are_sorted_again_only_when_the_data_or_the_preference_change(cx: &mut TestAppContext) {
let (page, cx) = open_page_in_season(cx);
let cx = &mut { cx };
show(&page, cx, statistics(0, 6, rows_with_points()));
draw(cx);
let (input, grid) = page.read_with(cx, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let count = reorders(&page, cx);
// Hovering a card, the search, the filter and the champ-select-less rounds change
// neither the data nor the preference.
let card = grid.read_with(cx, |grid, _| grid.shown_cards()[0].id);
let id: &'static str = Box::leak(format!("card-{card}").into_boxed_str());
let at = center(cx, id);
cx.simulate_mouse_move(at, None, Modifiers::none());
draw(cx);
cx.update(|window, cx| input.update(cx, |input, cx| input.focus(window, cx)));
cx.simulate_input("r");
page.update(cx, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
draw(cx);
assert_eq!(reorders(&page, cx), count);
show(&page, cx, statistics(0, 6, rows_with_points()));
assert_eq!(reorders(&page, cx), count + 1, "new data");
pick_sort(&page, cx, "A–Z");
assert_eq!(reorders(&page, cx), count + 2, "new preference");
pick_sort(&page, cx, "A–Z");
assert_eq!(reorders(&page, cx), count + 2, "same preference");
}
#[gpui::test]
async fn alias_filters_sort_and_the_champ_select_all_follow_one_order(cx: &mut TestAppContext) {
cx.executor().allow_parking();
let (page, mut window) = open_page_with_tracker(cx, joueur_tracker_with(true));
let chosen = record_sorts(&page, &mut window);
let (input, home_grid) = page.read_with(&window, |p, _| {
(p.home_search_input.clone(), p.home_grid.clone())
});
let type_search = |window: &mut VisualTestContext, text: &str| {
window.update(|w, cx| {
input.update(cx, |input, cx| {
input.focus(w, cx);
input.clean(w, cx);
})
});
window.simulate_input(text);
};
// Soraka, Swain, Briar, Rumble... by Mastery Points, the zeros by name.
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[64, 16, 50, 233, 68, 12, 103, 25, 5]
);
// An alias.
type_search(&mut window, "srk");
assert_eq!(grid_names(&home_grid, &mut window), ["Soraka"]);
// A name part and a filter: Soraka is Completed, so « Restants » drops it.
type_search(&mut window, "a");
page.update(&mut window, |p, cx| {
p.home_filter = StateFilter::Remaining;
p.refresh_home(cx);
});
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[50, 233, 12, 103, 25, 5]
);
pick_sort(&page, &mut window, "A–Z");
assert_eq!(
ids(&home_grid.read_with(&window, |g, _| g.shown_cards())),
[103, 12, 233, 25, 50, 5]
);
// Entering a champ select: the Anvil row follows the sort, so does « Autres champions »,
// and the selector stays.
send(&page, &mut window, &frames()[0]);
cx.condition(&page, |p, _| {
p.stats.as_ref().is_some_and(|s| s.rows.len() == 9)
})
.await;
draw(&mut window);
assert!(window.debug_bounds("sort").is_some());
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
click_others(&mut window);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_A_TO_Z);
pick_sort(&page, &mut window, "Maîtrise");
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_BY_MASTERY);
assert_eq!(ids(&others_cards(&page, &mut window)), OTHERS_BY_MASTERY);
// Reasons still go with their cards.
assert_eq!(
reasons(&anvil_cards(&page, &mut window), 16),
[Reason::Completed]
);
// The statistics themselves stay A to Z.
page.read_with(&window, |p, _| {
let rows = p.stats.as_ref().unwrap().rows.iter();
let names: Vec<_> = rows.map(|row| row.champion.name.as_str()).collect();
assert_eq!(names, ALL_A_TO_Z);
});
pick_sort(&page, &mut window, "A–Z");
assert_eq!(ids(&anvil_cards(&page, &mut window)), ANVIL_A_TO_Z);
// Leaving gives back « Tous » and an empty search, with the sort kept.
leave(&page, &mut window);
cx.condition(&page, |p, _| p.stats.is_some()).await;
draw(&mut window);
page.read_with(&window, |p, _| {
assert_eq!(p.home_filter, StateFilter::All);
assert_eq!(p.champion_sort, Some(ChampionSort::Name));
});
assert_eq!(
*chosen.borrow(),
[
ChampionSort::Name,
ChampionSort::Mastery,
ChampionSort::Name
]
);
assert_eq!(grid_names(&home_grid, &mut window), ALL_A_TO_Z);
}
@@ -0,0 +1,72 @@
use super::page_fixtures::draw;
use crate::champion_table::tests::row;
use crate::page::{ChampionSortChosen, Page};
use arena_tracker_core::{Champion, ChampionChallenge, ChampionRow, ChampionSort, ChampionState};
use gpui_kit::component::select::SelectEvent;
use gpui_kit::{Entity, VisualTestContext};
use std::cell::RefCell;
use std::rc::Rc;
// The sort of the cards (#76).
/// A row with a name, an id and its Mastery Points.
pub(super) fn with_points(id: u32, name: &str, points: Option<u64>) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
key: name.into(),
name: name.into(),
},
state: Some(ChampionState::NeverPlayed),
challenge: Some(ChampionChallenge::default()),
mastery_points: points,
..row(name)
}
}
/// A to Z, as the statistics give them.
pub(super) fn rows_with_points() -> Vec<ChampionRow> {
vec![
with_points(1, "Ahri", None),
with_points(2, "Brand", Some(500)),
with_points(3, "Garen", Some(9_000)),
with_points(4, "Jinx", Some(500)),
with_points(5, "Lux", Some(0)),
with_points(6, "Zed", None),
]
}
pub(super) const BY_MASTERY: [&str; 6] = ["Garen", "Brand", "Jinx", "Lux", "Ahri", "Zed"];
pub(super) const A_TO_Z: [&str; 6] = ["Ahri", "Brand", "Garen", "Jinx", "Lux", "Zed"];
/// The sorts the page reports, in order.
pub(super) fn record_sorts(
page: &Entity<Page>,
cx: &mut VisualTestContext,
) -> Rc<RefCell<Vec<ChampionSort>>> {
let chosen = Rc::new(RefCell::new(Vec::new()));
let events = chosen.clone();
cx.update(|_, cx| {
cx.subscribe(page, move |_, event: &ChampionSortChosen, _| {
events.borrow_mut().push(event.0)
})
.detach()
});
chosen
}
/// The player picks `label` in the sort selector.
pub(super) fn pick_sort(page: &Entity<Page>, cx: &mut VisualTestContext, label: &'static str) {
let select = page.read_with(cx, |p, _| p.sort_select.clone());
cx.update(|_, cx| {
select.update(cx, |_, cx| {
cx.emit(SelectEvent::Confirm(Some(label.into())))
})
});
draw(cx);
}
pub(super) fn reorders(page: &Entity<Page>, cx: &mut VisualTestContext) -> usize {
page.read_with(cx, |p, _| p.reorders)
}
+111
View File
@@ -0,0 +1,111 @@
use super::{Page, RELOAD_EVERY};
use crate::worker::{Msg, spawn_refresh};
use gpui_kit::*;
impl Page {
pub(in crate::page) fn apply(&mut self, msg: Msg, window: &mut Window, cx: &mut Context<Self>) {
match msg {
Msg::Progress(progress) => {
self.progress = Some(progress);
if self.last_reload.elapsed() >= RELOAD_EVERY {
self.reload_in_background(window, cx);
}
}
Msg::Champions => self.reload_in_background(window, cx),
Msg::ChampSelect(champ_select) => {
if self.leave.is_some() {
if champ_select.is_none() {
// Already leaving.
return;
}
// The champ select leaving ends at once: the next one starts from the home.
self.finish_exit(window, cx);
}
if self.champ_select == champ_select {
return;
}
if champ_select.is_none() && self.in_champ_select() && self.may_animate(window, cx)
{
self.start_exit(window, cx);
} else {
self.change_champ_select(champ_select, window, cx);
}
}
Msg::Round {
status,
reload,
matches,
} => {
// A follower round that changes nothing shown must not rebuild the page (they keep coming).
if status == self.status
&& !reload
&& matches.is_empty()
&& !self.pending_round
&& self.progress.is_none()
&& !self.crashed
{
return;
}
self.status = status;
self.pending_round = false;
self.progress = None;
self.crashed = false;
for event in matches {
if self.viewed().is_some_and(|a| a.puuid == event.puuid)
&& self.home_season.as_deref() == Some(event.season.as_str())
{
self.hold_grid |= self.lit_by == Some(self.home_grid.entity_id());
self.queue_match(event, cx);
// A statistics job already running may predate the insertion.
self.stats_generation += 1;
}
}
if reload {
self.reload_in_background(window, cx);
}
if self.in_champ_select() {
self.prepare_champ_select(cx);
}
}
Msg::Refreshed(status) => {
self.status = status;
self.progress = None;
self.crashed = false;
self.reload_in_background(window, cx);
// A request made while this one ran (a key saved meanwhile) is served now.
if self.refresh.finished() {
spawn_refresh(self.tracker.clone(), self.tx.clone());
}
}
Msg::Statistics {
generation,
stats,
home,
stored,
} => {
if generation == self.stats_generation {
self.stats_error = stats.as_ref().err().cloned();
self.stats = stats.ok();
self.set_home_result(home);
self.stored = stored;
self.show_statistics(window, cx);
}
if self.stats_job.finished() {
self.recompute_in_background(true, window, cx);
}
}
Msg::Crashed => self.mark_crashed(),
Msg::RefreshCrashed => {
self.refresh.reset();
self.mark_crashed();
}
}
cx.notify();
}
fn mark_crashed(&mut self) {
self.pending_round = false;
self.progress = None;
self.crashed = true;
}
}
+223
View File
@@ -0,0 +1,223 @@
use std::io;
use std::ops::ControlFlow;
use std::os::windows::io::AsRawHandle;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::Command;
use arena_tracker_core::{Config, Preferences, UpdateChannel, data_dir};
use base64::prelude::{BASE64_STANDARD, Engine};
use windows::Win32::Foundation::{HANDLE, WAIT_OBJECT_0};
use windows::Win32::System::Threading::{
CREATE_NO_WINDOW, GetExitCodeProcess, OpenProcess, PROCESS_NAME_WIN32,
PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_SYNCHRONIZE, QueryFullProcessImageNameW,
WaitForSingleObject,
};
use windows::core::PWSTR;
use crate::logon;
use crate::single_instance::owned;
/// This executable's release version; `None` for a development build, which never updates.
pub const VERSION: Option<&str> = option_env!("ARENA_RELEASE_VERSION");
const CHANNEL: Option<&str> = option_env!("ARENA_RELEASE_CHANNEL");
const PUBLIC_KEY: Option<&str> = option_env!("ARENA_RELEASE_PUBLIC_KEY");
/// Public: read without a Gitea account or token.
const RELEASES: &str = "https://gitea.nessar.fr/api/v1/repos/nessar/arena-tracker/releases";
/// Velopack 1.2.161 waits up to 60 s for the app to exit, 15 s for each hook and about 40 s
/// for the folder swap: an installer still running after this counts as failed.
const INSTALLER_WAIT_MS: u32 = 180_000;
/// The Windows installer invokes these fast callbacks and waits for the process to exit.
/// The SDK's ordinary startup path opens cached packages even with auto-apply disabled.
pub fn handle_command() {
let mut args = std::env::args_os().skip(1);
let Some(command) = args.next() else { return };
match command.to_str() {
Some("--veloapp-updated" | "--veloapp-obsolete") => {
std::process::exit(0);
}
Some("--veloapp-install" | "--veloapp-uninstall") => {
// Otherwise each logon would start a deleted executable, and a reinstallation, even
// over an installation its uninstallation did not clean, would launch at logon
// before anyone chose it. An update keeps the choice: `current\` keeps its path.
let _ = logon::forget();
std::process::exit(0);
}
Some("--verify-release") => {
let ok = args.next().is_some_and(|dir| {
verify_release(Path::new(&dir))
.inspect_err(|err| eprintln!("{err}"))
.is_ok()
});
std::process::exit(if ok { 0 } else { 1 });
}
_ => {}
}
}
/// Checks a release folder with the identity this executable was built with.
fn verify_release(dir: &Path) -> Result<(), String> {
let (Some(channel), Some(version), Some(key), Some(commit)) = (
CHANNEL,
VERSION,
PUBLIC_KEY,
option_env!("ARENA_RELEASE_COMMIT"),
) else {
return Err("Exécutable construit sans identité de version.".into());
};
let key = BASE64_STANDARD.decode(key).map_err(|e| e.to_string())?;
let signed_commit = arena_tracker_core::verify_release(dir, &key, channel, version)
.map_err(|e| e.to_string())?;
if signed_commit != commit {
return Err("Commit de la version inattendu.".into());
}
Ok(())
}
/// The saved choice, or until the player chooses, the installed version's channel: Stable for a
/// development build.
pub fn channel(preferences: Preferences) -> UpdateChannel {
(preferences.update_channel).unwrap_or(if CHANNEL == Some("beta") {
UpdateChannel::Beta
} else {
UpdateChannel::Stable
})
}
/// What every update step needs: the folder of kept updates,
/// `%LOCALAPPDATA%\arena-tracker\updates`, outside the installation and Velopack's cache; the
/// public key; the installed version. `None` for a development build.
fn update_context() -> Option<(PathBuf, Vec<u8>, &'static str)> {
let dir = PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("arena-tracker/updates");
Some((dir, BASE64_STANDARD.decode(PUBLIC_KEY?).ok()?, VERSION?))
}
/// Keeps the newest release of `channel` downloaded and authenticated in the updates folder and
/// returns its version, or `None` when there is no newer one. A failed check changes nothing on
/// disk: the kept package stays, and the next check (launch, channel change or the settings'
/// button) tries again.
pub fn download_update(channel: UpdateChannel) -> Result<Option<String>, String> {
let (dir, key, version) = update_context().ok_or("Cette version ne se met pas à jour.")?;
arena_tracker_core::download_update(RELEASES, &dir, &key, channel, version)
.map_err(|e| e.to_string())
}
/// Before the app loads, in the single instance only: hands the kept update of the chosen
/// channel to Update.exe once. `Break`: Update.exe replaces this version and opens the app.
/// `Continue`: load the app, with the notice to show if there is one. At logon, the version
/// Update.exe opens, new or this one again, starts hidden too.
pub fn update_at_launch(at_logon: bool) -> ControlFlow<(), Option<String>> {
let Some((dir, key, version)) = update_context() else {
return ControlFlow::Continue(None);
};
// Without a readable configuration the chosen channel is unknown; the app then says why.
// shortcut: startup() reads config.toml again, a few hundred bytes; pass it along if that
// file ever grows.
let config =
data_dir().and_then(|data| Config::load_or_default(&data.join("config.toml")).ok());
let Some(config) = config else {
return ControlFlow::Continue(None);
};
let channel = channel(config.preferences);
arena_tracker_core::update_at_launch(
&dir,
&key,
channel,
version,
|package| start_installer(package, at_logon),
installer_exit,
)
.map_continue(|error| error.map(|error| error.to_string()))
}
/// « Redémarrer »: hands the kept update of `channel` to Update.exe; the app must then quit.
/// Hashes the package on the calling thread: a few tens of milliseconds for a full package.
pub fn restart_to_update(channel: UpdateChannel) -> Result<(), String> {
let (dir, key, version) = update_context().ok_or("Cette version ne se met pas à jour.")?;
arena_tracker_core::restart_to_update(&dir, &key, channel, version, |package| {
start_installer(package, false)
})
.map_err(|e| e.to_string())
}
/// Update.exe at the installation's root, next to `current\arena-tracker.exe`.
fn installer() -> io::Result<PathBuf> {
let exe = std::env::current_exe()?;
let root = exe.parent().and_then(Path::parent);
Ok(root.ok_or(io::ErrorKind::NotFound)?.join("Update.exe"))
}
/// Starts Velopack's installer on an authenticated package, which it reads in place: it stops
/// this process if it still runs (1.2.161 fails to wait for it), replaces `current\` and opens
/// the app once, this version again if it fails (ADR-0005, `docs/paquets-windows.md`). At logon, Velopack 1.2.161
/// shows neither its progress window nor its dialogs (`--silent`, which must come before
/// `--`), and hands the arguments after `--` to the version it opens, in both cases.
fn start_installer(package: &Path, at_logon: bool) -> io::Result<u32> {
let mut command = Command::new(installer()?);
command
.args([
"apply",
"--waitPid",
&std::process::id().to_string(),
"--package",
])
.arg(package);
if at_logon {
command.args(["--silent", "--", logon::ARG]);
}
let child = command.creation_flags(CREATE_NO_WINDOW.0).spawn()?;
Ok(child.id())
}
/// The exit code of the installer an earlier launch started as `pid`, once it ends. A launch
/// waiting here runs from the installation, so Velopack stops it before replacing `current\`.
fn installer_exit(pid: u32) -> Option<u32> {
process_exit(pid, &installer().ok()?)
}
/// Waits for process `pid` and returns its exit code; `None` when no such process runs from
/// `image` (the id may belong to another program by now), or when it still runs after the wait.
// shortcut: compares path spellings, as current_exe() gives them to both launches; compare file
// identities if an 8.3 or `\\?\` spelling ever shows up there.
fn process_exit(pid: u32, image: &Path) -> Option<u32> {
let access = PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_SYNCHRONIZE;
let process = owned(unsafe { OpenProcess(access, false, pid) }.ok()?);
let handle = HANDLE(process.as_raw_handle());
let mut name = [0u16; 1024];
let mut len = name.len() as u32;
let name_ptr = PWSTR(name.as_mut_ptr());
unsafe { QueryFullProcessImageNameW(handle, PROCESS_NAME_WIN32, name_ptr, &mut len) }.ok()?;
let name = String::from_utf16_lossy(&name[..len as usize]);
if !name.eq_ignore_ascii_case(&image.to_string_lossy())
|| unsafe { WaitForSingleObject(handle, INSTALLER_WAIT_MS) } != WAIT_OBJECT_0
{
return None;
}
let mut code = 0;
unsafe { GetExitCodeProcess(handle, &mut code) }.ok()?;
Some(code)
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use std::process::Command;
use super::process_exit;
#[test]
fn the_installers_exit_code_is_read_only_from_its_own_image() {
let windows = PathBuf::from(std::env::var_os("SystemRoot").unwrap());
let cmd = windows.join("System32").join("cmd.exe");
// Kept until the end: its open handle stops the id from going to another process.
let child = Command::new(&cmd).args(["/c", "exit 3"]).spawn().unwrap();
assert_eq!(
process_exit(child.id(), Path::new("C:\\Other\\Update.exe")),
None
);
// SystemRoot and the process image differ in case.
assert_eq!(process_exit(child.id(), &cmd), Some(3));
drop(child);
}
}
+460
View File
@@ -0,0 +1,460 @@
//! The ring: the logo enlarged, with one tick per champion of the Challenge around the crown. It
//! is a gauge in a fixed order, never the chosen sort: the Completed champions in the order of
//! their first top 1, turning from noon, then the played ones, then the never played ones, these
//! two by Mastery Points (A to Z while the points are unknown, as the cards).
//!
//! A cached view (rule #1): laid out from the style its parent gives, drawn again only when its
//! ticks or the lit one change, never by a hover or a scroll elsewhere.
use std::cell::RefCell;
use std::f32::consts::{FRAC_PI_2, TAU};
use std::rc::Rc;
use arena_tracker_core::ChampionState;
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::*;
use crate::motion::{MATCH_SETTLE, MatchAnimation, MatchEnd, ease_out};
use crate::theme::{ring_never, ring_played};
mod ticks;
pub use ticks::{Tick, ticks};
// The reference page's geometry, in the units of its SVG: the ring is drawn in a square
// `BOX` wide, its centre `PAD + C` from the edges.
const C: f32 = 260.;
const R1: f32 = 214.;
const R2: f32 = 246.;
const PAD: f32 = 20.;
const BOX: f32 = 2. * (C + PAD);
/// The disc under the crown.
const DISC: f32 = R1 - 18.;
/// The crown of the logo, in its own 256 wide square, placed as the reference page does.
const CROWN: [(f32, f32); 7] = [
(68., 186.),
(52., 86.),
(98., 126.),
(128., 66.),
(158., 126.),
(204., 86.),
(188., 186.),
];
const CROWN_SCALE: f32 = 0.64;
const CROWN_AT: (f32, f32) = (C - 82., C - 92.);
/// From and to which radius the tick of a champion in `state` runs, and how wide it is.
fn shape(state: ChampionState) -> (f32, f32, f32) {
match state {
ChampionState::Completed => (R1, R2, 4.),
ChampionState::InProgress => (R1 + 10., R2 - 6., 3.),
ChampionState::NeverPlayed => (R1 + 18., R1 + 21., 3.),
}
}
/// Maps the reference page's units into `bounds`.
#[derive(Clone, Copy)]
struct Frame {
origin: Point<Pixels>,
scale: f32,
}
impl Frame {
fn of(bounds: Bounds<Pixels>) -> Frame {
Frame {
origin: bounds.origin,
scale: bounds.size.width.min(bounds.size.height).as_f32() / BOX,
}
}
fn point(self, x: f32, y: f32) -> Point<Pixels> {
self.origin + point(px((x + PAD) * self.scale), px((y + PAD) * self.scale))
}
/// Adds the tick `index` of `count` to `path`: a segment with round ends, as a filled shape.
fn add_tick(
self,
path: &mut PathBuilder,
index: usize,
count: usize,
state: ChampionState,
width: f32,
) {
let angle = -FRAC_PI_2 + (index as f32 + 0.5) * TAU / count as f32;
let (from, to, _) = shape(state);
let (cos, sin) = (angle.cos(), angle.sin());
let half = width / 2.;
// Along the tick, and across it.
let at = |radius: f32, side: f32| {
self.point(C + radius * cos - side * sin, C + radius * sin + side * cos)
};
let cap = point(px(half * self.scale), px(half * self.scale));
path.move_to(at(from, half));
path.line_to(at(to, half));
path.arc_to(cap, px(0.), false, false, at(to, -half));
path.line_to(at(from, -half));
path.arc_to(cap, px(0.), false, false, at(from, half));
path.close();
}
}
/// The ring's fixed shapes for one size and one set of ticks: tessellated once, painted again as
/// they are when only the lit tick changes.
struct Geometry {
/// The size it was made for: it is made at the origin, and moved where the ring is painted,
/// so a scroll that moves the ring does not make it again.
size: Size<Pixels>,
/// One path per state of tick, bright or dimmed (`true`) during a champ select.
ticks: Vec<(ChampionState, bool, Path<Pixels>)>,
crown: Option<Path<Pixels>>,
}
impl Geometry {
fn new(size: Size<Pixels>, ticks: &[Tick], anvil: Option<&[u32]>) -> Geometry {
let frame = Frame::of(Bounds {
origin: Point::default(),
size,
});
let count = ticks.len();
let states = [
ChampionState::Completed,
ChampionState::InProgress,
ChampionState::NeverPlayed,
];
let ticks = states
.into_iter()
.flat_map(|state| [(state, false), (state, true)])
.filter_map(|(state, dim)| {
if dim && anvil.is_none() {
return None;
}
let mut path = PathBuilder::fill();
let mut any = false;
for (index, tick) in ticks.iter().enumerate() {
if tick.state == state
&& dim == anvil.is_some_and(|ids| !ids.contains(&tick.id))
{
frame.add_tick(
&mut path,
index,
count,
state,
if anvil.is_some() && !dim {
7.
} else {
shape(state).2
},
);
any = true;
}
}
Some((state, dim, path.build().ok().filter(|_| any)?))
})
.collect();
Geometry {
size,
ticks,
crown: crown(frame),
}
}
}
/// The crown of the logo in `frame`.
fn crown(frame: Frame) -> Option<Path<Pixels>> {
let mut crown = PathBuilder::fill();
let points: Vec<_> = CROWN
.iter()
.map(|&(x, y)| frame.point(CROWN_AT.0 + x * CROWN_SCALE, CROWN_AT.1 + y * CROWN_SCALE))
.collect();
crown.add_polygon(&points, true);
crown.build().ok()
}
/// A copy of `path`, made at the origin, moved `by`.
fn moved(path: &Path<Pixels>, by: Point<Pixels>) -> Path<Pixels> {
let mut path = path.clone();
path.bounds.origin += by;
for vertex in &mut path.vertices {
vertex.xy_position += by;
}
path
}
pub struct Ring {
anvil: Option<Rc<[u32]>>,
ticks: Rc<[Tick]>,
/// The champion whose card is under the pointer.
lit: Option<u32>,
/// Made by the paint, for its size; forgotten with the ticks.
geometry: Rc<RefCell<Option<Geometry>>>,
/// How many times it was drawn: the tests check it stays light.
#[cfg(test)]
pub(crate) renders: usize,
/// How many times its fixed shapes were tessellated.
#[cfg(test)]
pub(crate) tessellations: Rc<std::cell::Cell<usize>>,
}
impl Ring {
pub fn new() -> Ring {
Ring {
ticks: Rc::new([]),
anvil: None,
lit: None,
geometry: Rc::default(),
#[cfg(test)]
renders: 0,
#[cfg(test)]
tessellations: Rc::default(),
}
}
/// The end of a followed Match on this champion's tick, from `start`; `None` when the ring
/// has no tick for it.
pub fn animation(
&self,
id: u32,
end: MatchEnd,
start: std::time::Instant,
) -> Option<MatchAnimation> {
let index = self.ticks.iter().position(|tick| tick.id == id)?;
Some(MatchAnimation {
start,
end,
champion_id: id,
index,
count: self.ticks.len(),
state: self.ticks[index].state,
})
}
/// Replaces the ticks; the ring is drawn again only when they differ.
pub fn set_ticks(&mut self, ticks: Rc<[Tick]>, cx: &mut Context<Self>) {
if *self.ticks != *ticks {
self.ticks = ticks;
self.geometry.replace(None);
cx.notify();
}
}
/// During a champ select whose Anvil list is known: only these champions' ticks stay bright,
/// the others are dimmed. None dims no tick.
pub fn set_anvil(&mut self, ids: Option<&[u32]>, cx: &mut Context<Self>) {
if self.anvil.as_deref() != ids {
self.anvil = ids.map(Rc::from);
self.geometry.replace(None);
cx.notify();
}
}
/// Lights the tick of the card under the pointer, or none.
pub fn set_lit(&mut self, lit: Option<u32>, cx: &mut Context<Self>) {
if self.lit != lit {
self.lit = lit;
cx.notify();
}
}
#[cfg(test)]
pub(crate) fn ticks(&self) -> &[Tick] {
&self.ticks
}
#[cfg(test)]
pub(crate) fn anvil(&self) -> Option<&[u32]> {
self.anvil.as_deref()
}
pub(crate) fn lit(&self) -> Option<u32> {
self.lit
}
}
impl Ring {
/// The end of a followed Match, `elapsed` seconds in, over the cached ring: only the moving
/// shapes, a function of the page's render so that the ring is not drawn again (rule #1). The
/// comet and its trail fly from noon to the tick; then the tick flares, gold for a new Mark,
/// bright otherwise, and for a champion Completed the crown bounces: the ring's own crown,
/// moved, not tessellated again.
pub fn match_layer(
&self,
animation: MatchAnimation,
elapsed: f32,
cx: &App,
) -> impl IntoElement {
let theme = cx.theme();
let (gold, bright, disc) = (theme.primary, theme.foreground, theme.background);
let geometry = self.geometry.clone();
#[cfg(test)]
let tessellations = self.tessellations.clone();
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let frame = Frame::of(bounds);
let flight = animation.flight();
if elapsed < flight {
let arc = TAU * (animation.index as f32 + 0.5) / animation.count as f32
* ease_out(elapsed / flight);
let radius = (R1 + R2) * 0.5;
let at = |angle: f32| {
frame.point(C + radius * angle.sin(), C - radius * angle.cos())
};
let mut trail = PathBuilder::stroke(px(4. * frame.scale));
let tail = (arc - 0.8).max(0.);
trail.move_to(at(tail));
for i in 1..=12 {
trail.line_to(at(tail + (arc - tail) * i as f32 / 12.));
}
if let Ok(path) = trail.build() {
window.paint_path(path, gold);
}
let dot = px(8. * frame.scale);
window.paint_quad(
fill(
Bounds::centered_at(at(arc), size(dot * 2., dot * 2.)),
bright,
)
.corner_radii(dot),
);
return;
}
let t = ((elapsed - flight) / MATCH_SETTLE).clamp(0., 1.);
let pulse = (std::f32::consts::PI * t).sin();
let mut tick = PathBuilder::fill();
frame.add_tick(
&mut tick,
animation.index,
animation.count,
animation.state,
shape(animation.state).2 + 6. * pulse,
);
if let Ok(path) = tick.build() {
let ink = if animation.end == MatchEnd::Mark {
gold
} else {
bright
};
window.paint_path(path, ink.opacity(pulse));
}
if animation.has_comet() {
// Cover the resting crown inside the disc, then draw it at its bouncing height.
let radius = px(DISC * frame.scale);
window.paint_quad(
fill(
Bounds::centered_at(frame.point(C, C), size(radius * 2., radius * 2.)),
disc,
)
.corner_radii(radius),
);
let rise = 25. * (1. - t).powi(2) * (std::f32::consts::TAU * t).sin();
let by = bounds.origin - point(px(0.), px(rise * frame.scale));
// The ring painted its crown at this size, unless the layout just changed.
let geometry = geometry.borrow();
let made = geometry.as_ref().filter(|g| g.size == bounds.size);
let made_crown;
let crown = match made {
Some(made) => made.crown.as_ref(),
None => {
#[cfg(test)]
tessellations.set(tessellations.get() + 1);
made_crown = crown(Frame::of(Bounds {
origin: Point::default(),
size: bounds.size,
}));
made_crown.as_ref()
}
};
if let Some(path) = crown {
window.paint_path(moved(path, by), gold);
}
}
},
)
.absolute()
.inset_0()
}
}
impl Render for Ring {
fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
#[cfg(test)]
{
self.renders += 1;
}
let theme = cx.theme();
let color = |state| match state {
ChampionState::Completed => theme.primary,
ChampionState::InProgress => ring_played(theme),
ChampionState::NeverPlayed => ring_never(theme),
};
let colors = [
ChampionState::Completed,
ChampionState::InProgress,
ChampionState::NeverPlayed,
]
.map(|state| (state, color(state)));
let (disc, crown, lit_color) = (theme.background, theme.primary, theme.foreground);
let ticks = self.ticks.clone();
let geometry = self.geometry.clone();
let anvil = self.anvil.clone();
#[cfg(test)]
let tessellations = self.tessellations.clone();
// The lit tick, and where it is.
let lit = (self.ticks.iter().enumerate())
.find(|(_, tick)| Some(tick.id) == self.lit)
.map(|(index, tick)| (index, tick.state));
div().size_full().debug_selector(|| "ring".into()).child(
canvas(
|_, _, _| {},
move |bounds, _, window, _| {
let frame = Frame::of(bounds);
let radius = px(DISC * frame.scale);
let centre = frame.point(C, C);
let disc_bounds = Bounds::centered_at(centre, size(radius * 2., radius * 2.));
window.paint_quad(fill(disc_bounds, disc).corner_radii(radius));
let mut geometry = geometry.borrow_mut();
if geometry.as_ref().is_none_or(|g| g.size != bounds.size) {
#[cfg(test)]
tessellations.set(tessellations.get() + 1);
*geometry = Some(Geometry::new(bounds.size, &ticks, anvil.as_deref()));
}
let Some(geometry) = geometry.as_ref() else {
return;
};
for (state, dim, path) in &geometry.ticks {
let color = colors.iter().find(|(s, _)| s == state).map(|(_, c)| *c);
let color = color.unwrap_or(crown);
window.paint_path(
moved(path, bounds.origin),
if *dim { color.opacity(0.16) } else { color },
);
}
if let Some(path) = &geometry.crown {
window.paint_path(moved(path, bounds.origin), crown);
}
// Only the lit tick is tessellated when the pointer changes card.
if let Some((index, state)) = lit {
let mut path = PathBuilder::fill();
frame.add_tick(&mut path, index, ticks.len(), state, 7.);
if let Ok(path) = path.build() {
let dim = anvil
.as_ref()
.is_some_and(|ids| !ids.contains(&ticks[index].id));
window.paint_path(
path,
if dim {
lit_color.opacity(0.16)
} else {
lit_color
},
);
}
}
},
)
.size_full(),
)
}
}
#[cfg(test)]
mod tests;
+112
View File
@@ -0,0 +1,112 @@
use arena_tracker_core::{Champion, ChampionRow, ChampionState};
use gpui_kit::{px, size};
use super::{Geometry, Tick, ticks};
use crate::champion_table::tests::row;
fn champion(id: u32, name: &str, state: ChampionState, points: Option<u64>) -> ChampionRow {
ChampionRow {
champion: Champion {
id,
..row(name).champion
},
state: Some(state),
mastery_points: points,
..row(name)
}
}
fn order(ticks: &[Tick]) -> Vec<(u32, ChampionState)> {
ticks.iter().map(|tick| (tick.id, tick.state)).collect()
}
#[test]
fn completed_by_first_top_1_then_played_then_never_played_by_mastery() {
use ChampionState::*;
// A to Z, as the statistics give them.
let rows = [
champion(1, "Ahri", NeverPlayed, Some(10)),
champion(2, "Brand", Completed, Some(5)),
champion(3, "Garen", InProgress, Some(100)),
champion(4, "Jinx", Completed, Some(900)),
champion(5, "Lux", InProgress, Some(700)),
champion(6, "Zed", NeverPlayed, Some(800)),
];
assert_eq!(
order(&ticks(&rows, &[2, 4])),
[
(2, Completed),
(4, Completed),
(5, InProgress),
(3, InProgress),
(6, NeverPlayed),
(1, NeverPlayed),
]
);
// Unknown points: A to Z, as the cards. An id the rows do not know is skipped.
let unknown: Vec<_> = rows
.iter()
.cloned()
.map(|row| ChampionRow {
mastery_points: None,
..row
})
.collect();
assert_eq!(
order(&ticks(&unknown, &[4, 99, 2])),
[
(4, Completed),
(2, Completed),
(3, InProgress),
(5, InProgress),
(1, NeverPlayed),
(6, NeverPlayed),
]
);
}
/// Which shapes the ring paints: per state, bright or dimmed.
fn painted(ticks: &[Tick], anvil: Option<&[u32]>) -> Vec<(ChampionState, bool)> {
Geometry::new(size(px(200.), px(200.)), ticks, anvil)
.ticks
.iter()
.map(|(state, dim, _)| (*state, *dim))
.collect()
}
#[test]
fn only_the_anvil_champions_ticks_stay_bright() {
use ChampionState::*;
let tick = |id, state| Tick { id, state };
let ring = [
tick(1, Completed),
tick(2, Completed),
tick(3, InProgress),
tick(4, NeverPlayed),
];
// At home, and in a champ select whose list the client did not send: nothing dimmed.
assert_eq!(
painted(&ring, None),
[
(Completed, false),
(InProgress, false),
(NeverPlayed, false)
]
);
// The hand is 1 and 4: 2 and 3 fade.
assert_eq!(
painted(&ring, Some(&[1, 4])),
[
(Completed, false),
(Completed, true),
(InProgress, true),
(NeverPlayed, false),
]
);
// An empty hand: every tick fades.
assert_eq!(
painted(&ring, Some(&[])),
[(Completed, true), (InProgress, true), (NeverPlayed, true)]
);
}
+38
View File
@@ -0,0 +1,38 @@
use arena_tracker_core::{ChampionRow, ChampionSort, ChampionState};
use crate::card_order::card_order;
/// A champion's tick: long and gold when Completed, pale gold when played, short and faint when
/// never played.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Tick {
pub id: u32,
pub state: ChampionState,
}
/// The ticks of `rows` in the ring's order. `completion_order` lists the Completed champions'
/// ids by their first top 1; an id the rows do not know is skipped.
pub fn ticks(rows: &[ChampionRow], completion_order: &[u32]) -> Vec<Tick> {
let completed = completion_order
.iter()
.filter(|&&id| rows.iter().any(|row| row.champion.id == id))
.map(|&id| Tick {
id,
state: ChampionState::Completed,
});
let by_mastery = card_order(rows, ChampionSort::Mastery);
let of_state = |state: ChampionState| {
by_mastery
.iter()
.map(|&ix| &rows[ix])
.filter(move |row| row.state == Some(state))
.map(move |row| Tick {
id: row.champion.id,
state,
})
};
completed
.chain(of_state(ChampionState::InProgress))
.chain(of_state(ChampionState::NeverPlayed))
.collect()
}
+278 -34
View File
@@ -1,48 +1,39 @@
//! The Riot API key form: the first-launch prompt and the settings view.
//! The first-launch Riot API key prompt and the settings view.
use std::path::PathBuf;
use std::sync::Arc;
use std::rc::Rc;
use arena_tracker_core::{Config, Error, RiotApi};
use arena_tracker_core::{ChampionSort, Preferences, UpdateChannel};
use gpui_kit::base::async_util::{Sender, unbounded};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::{ActiveTheme as _, StyledExt as _};
use gpui_kit::*;
use crate::logon::LogonLaunch;
use crate::release::{self, channel};
use crate::tray::{Tray, UNAVAILABLE};
use crate::worker::{RefreshGate, UpdateChecked, spawn_update_check};
const PLACEHOLDER_SAVED: &str = "Clé enregistrée";
const PLACEHOLDER_EMPTY: &str = "Clé API Riot";
const STABLE_AFTER_BETA: &str =
"La bêta installée reste en place jusqu’à une version stable plus récente.";
const LOGON_ERROR: &str = "Impossible de modifier le lancement à l’ouverture de session.";
/// Where the key lives: the config file, and the running Riot client that uses it.
pub struct KeyStore {
path: PathBuf,
config: Config,
api: Arc<RiotApi>,
}
mod appearance;
pub use appearance::apply_theme;
#[cfg(test)]
use appearance::theme_mode;
impl KeyStore {
pub fn new(path: PathBuf, config: Config, api: Arc<RiotApi>) -> KeyStore {
KeyStore { path, config, api }
}
pub fn has_key(&self) -> bool {
!self.config.riot_api_key.is_empty()
}
/// Writes the key to the config file and hands it to the Riot client, no restart needed.
fn save(&mut self, key: &str) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string());
if let Err(e) = self.config.save(&self.path) {
self.config.riot_api_key = previous;
return Err(e);
}
self.api.set_key(key.to_string());
Ok(())
}
}
mod preferences;
mod store;
pub use store::KeyStore;
pub enum KeyEvent {
Saved,
Back,
/// An update became ready or stopped being ready: the title bar shows it.
UpdateReady,
}
pub struct KeyForm {
@@ -51,18 +42,69 @@ pub struct KeyForm {
/// The first-launch prompt (no key and nothing stored yet) has no way back.
first_launch: bool,
error: Option<String>,
_subscription: Subscription,
preference_error: Option<SharedString>,
tray: Option<Rc<Tray>>,
logon_launch: LogonLaunch,
/// What Windows said when the settings were last shown or changed: it holds the choice.
/// Read only then, not at launch: the settings always open through `read_logon_launch`.
launches_at_logon: bool,
/// The tray reports here that it showed its one-time notice.
notice_shown: Sender<()>,
/// « Mise à jour prête » with the version downloaded and authenticated for the chosen channel.
ready: Option<SharedString>,
/// How the last check of the chosen channel ended, besides a ready update: up to date, or
/// why it failed. Cleared when the settings are left, as it ages while the app runs.
check_outcome: Option<SharedString>,
/// One update check at a time: at launch, on a channel change and on « Rechercher une mise à jour ».
update_checks: RefreshGate,
updates: Sender<UpdateChecked>,
_subscriptions: [Subscription; 2],
_notice_listener: Task<()>,
_update_listener: Task<()>,
}
impl EventEmitter<KeyEvent> for KeyForm {}
impl KeyForm {
pub fn has_key(&self) -> bool {
self.store.has_key()
}
pub fn new(
store: KeyStore,
first_launch: bool,
window: &mut Window,
cx: &mut Context<Self>,
) -> Self {
let preferences = store.preferences();
apply_theme(preferences.theme, window, cx);
let (notice_shown, notices) = unbounded();
let notice_listener = cx.spawn(async move |this, cx| {
while notices.recv().await.is_ok() {
if this
.update(cx, |form, _| form.store.record_tray_notice())
.is_err()
{
return;
}
}
});
let (updates, results) = unbounded();
let update_listener = cx.spawn(async move |this, cx| {
while let Ok(checked) = results.recv().await {
if this
.update(cx, |form, cx| form.update_checked(checked, cx))
.is_err()
{
return;
}
}
});
let notice = (!store.tray_notice_shown()).then(|| notice_shown.clone());
let tray = Tray::install_saved(window, preferences.close_to_tray, notice, cx);
let appearance = cx.observe_window_appearance(window, |this, window, cx| {
apply_theme(this.store.preferences().theme, window, cx);
});
let placeholder = if store.has_key() {
PLACEHOLDER_SAVED
} else {
@@ -79,22 +121,214 @@ impl KeyForm {
this.save(window, cx);
}
});
KeyForm {
let logon_launch = LogonLaunch::installed();
let mut form = KeyForm {
first_launch,
store,
input,
error: None,
_subscription: subscription,
preference_error: None,
tray,
launches_at_logon: false,
logon_launch,
notice_shown,
ready: None,
check_outcome: None,
update_checks: RefreshGate::default(),
updates,
_subscriptions: [subscription, appearance],
_notice_listener: notice_listener,
_update_listener: update_listener,
};
form.check_updates();
form
}
pub fn update_ready(&self) -> bool {
self.ready.is_some()
}
/// Not while a check runs: it may replace the folder of the package being handed over.
fn can_restart(&self) -> bool {
self.update_ready() && !self.update_checks.running()
}
/// Checks the chosen channel in the background, after the running check if there is one.
fn check_updates(&mut self) {
if release::VERSION.is_some() && self.update_checks.request() {
let channel = channel(self.store.preferences());
spawn_update_check(channel, self.updates.clone());
}
}
/// « Rechercher une mise à jour ».
fn check_updates_now(&mut self, cx: &mut Context<Self>) {
self.check_outcome = None;
self.check_updates();
cx.notify();
}
/// Only a check of the channel chosen now can make an update ready or change what is said
/// about the last check. A failure leaves a ready update ready: its package is still kept.
pub(crate) fn update_checked(&mut self, checked: UpdateChecked, cx: &mut Context<Self>) {
if self.update_checks.finished() {
let channel = channel(self.store.preferences());
spawn_update_check(channel, self.updates.clone());
}
if checked.channel == channel(self.store.preferences()) {
match checked.result {
Ok(Some(version)) => {
self.check_outcome = None;
self.set_ready(
Some(format!("Mise à jour prête : version {version}").into()),
cx,
);
}
Ok(None) => {
let version = release::VERSION.map(|version| format!(" ({version})"));
self.check_outcome = Some(
format!(
"Vous avez la dernière version{}",
version.unwrap_or_default()
)
.into(),
);
self.set_ready(None, cx);
}
Err(error) => {
self.check_outcome =
Some(format!("Impossible de vérifier les mises à jour : {error}").into());
}
}
}
// « Redémarrer » waits for the end of the check.
cx.notify();
}
/// « Recherche en cours… » while a check runs, then how the last one ended.
fn check_status(&self) -> Option<SharedString> {
if self.update_checks.running() {
return Some("Recherche en cours…".into());
}
self.check_outcome.clone()
}
fn set_ready(&mut self, ready: Option<SharedString>, cx: &mut Context<Self>) {
if self.ready != ready {
self.ready = ready;
cx.emit(KeyEvent::UpdateReady);
cx.notify();
}
}
/// « Mise à jour prête », or why an installed beta stays on the stable channel.
fn update_status(&self) -> Option<SharedString> {
let beta = release::VERSION.is_some_and(|version| version.contains("-beta."));
let stable = channel(self.store.preferences()) == UpdateChannel::Stable;
(self.ready.clone()).or_else(|| (beta && stable).then_some(STABLE_AFTER_BETA.into()))
}
/// Back to an empty field, as when the form is opened again.
pub fn reset(&mut self, window: &mut Window, cx: &mut Context<Self>) {
self.error = None;
self.preference_error = None;
self.check_outcome = None;
self.clear(window, cx);
cx.notify();
}
fn set_preferences(
&mut self,
preferences: Preferences,
window: &mut Window,
cx: &mut Context<Self>,
) {
let previous = self.store.preferences();
if previous == preferences {
return;
}
if preferences.close_to_tray && !previous.close_to_tray {
let notice = (!self.store.tray_notice_shown()).then(|| self.notice_shown.clone());
self.tray = Tray::install(window, notice, cx);
if self.tray.is_none() {
self.preference_error = Some(UNAVAILABLE.into());
cx.notify();
return;
}
}
self.preference_error = if self.store.save_preferences(preferences).is_err() {
Some("Impossible d’enregistrer les préférences.".into())
} else {
apply_theme(preferences.theme, window, cx);
if channel(preferences) != channel(previous) {
// The other channel's update must not show as ready, even if its check ends late.
self.set_ready(None, cx);
self.check_outcome = None;
self.check_updates();
}
None
};
if !self.store.preferences().close_to_tray
&& let Some(tray) = self.tray.take()
{
tray.uninstall();
}
cx.notify();
}
/// Reads the choice again: the Task Manager may have changed it since.
pub fn read_logon_launch(&mut self) {
self.launches_at_logon = self.logon_launch.enabled();
}
/// Writes the choice to Windows. On a refusal the switch shows what Windows holds.
fn set_logon_launch(&mut self, enabled: bool, cx: &mut Context<Self>) {
let written = self.logon_launch.set(enabled);
self.read_logon_launch();
self.preference_error = written.is_err().then(|| LOGON_ERROR.into());
cx.notify();
}
/// Saves the cards' sort with the other preferences. Nothing else changes, and a failed
/// write only shows the usual message in the settings: the page keeps the choice.
pub fn save_champion_sort(&mut self, sort: ChampionSort, cx: &mut Context<Self>) {
let preferences = Preferences {
champion_sort: Some(sort),
..self.store.preferences()
};
if preferences == self.store.preferences() {
return;
}
self.preference_error = self
.store
.save_preferences(preferences)
.is_err()
.then(|| "Impossible d’enregistrer les préférences.".into());
cx.notify();
}
/// Hands the ready update to the installer, then quits as « Quitter » does: never hidden in
/// the notification area, the single instance is free when the new version opens.
fn restart(&mut self, cx: &mut Context<Self>) {
// A second click queued before the quit must not start a second installer.
if !self.can_restart() {
return;
}
match release::restart_to_update(channel(self.store.preferences())) {
Ok(()) => {
self.set_ready(None, cx);
cx.quit();
}
Err(error) => {
self.preference_error = Some(error.into());
// Checked again, and downloaded again if the kept package was altered.
self.set_ready(None, cx);
self.check_updates();
cx.notify();
}
}
}
fn clear(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let placeholder = if self.store.has_key() {
PLACEHOLDER_SAVED
@@ -147,7 +381,11 @@ impl Render for KeyForm {
.child(
Button::new("save")
.primary()
.label("Enregistrer")
.label(if self.first_launch {
"Enregistrer"
} else {
"Enregistrer la clé"
})
.on_click(cx.listener(|this, _, window, cx| this.save(window, cx))),
)
.children((!self.first_launch).then(|| {
@@ -164,6 +402,8 @@ impl Render for KeyForm {
div()
.v_flex()
.w(px(520.))
.max_w_full()
.px_4()
.gap_3()
.child(
div()
@@ -171,6 +411,7 @@ impl Render for KeyForm {
.font_weight(FontWeight::SEMIBOLD)
.child(title),
)
.children((!self.first_launch).then(|| self.preferences(cx)))
.child(div().text_color(muted).child(explanation))
.child(Input::new(&self.input).mask_toggle())
.children(
@@ -182,3 +423,6 @@ impl Render for KeyForm {
)
}
}
#[cfg(test)]
mod tests;
+18
View File
@@ -0,0 +1,18 @@
use arena_tracker_core::ThemePreference;
use gpui_kit::component::{ActiveTheme as _, Theme, ThemeMode};
use gpui_kit::{App, Window};
pub(super) fn theme_mode(preference: ThemePreference, system: ThemeMode) -> ThemeMode {
match preference {
ThemePreference::System => system,
ThemePreference::Light => ThemeMode::Light,
ThemePreference::Dark => ThemeMode::Dark,
}
}
pub fn apply_theme(preference: ThemePreference, window: &mut Window, cx: &mut App) {
let mode = theme_mode(preference, ThemeMode::from(window.appearance()));
if cx.theme().mode != mode {
Theme::change(mode, Some(window), cx);
}
}
+136
View File
@@ -0,0 +1,136 @@
use arena_tracker_core::{Preferences, ThemePreference, UpdateChannel};
use gpui_kit::component::button::Button;
use gpui_kit::component::radio::RadioGroup;
use gpui_kit::component::switch::Switch;
use gpui_kit::component::{ActiveTheme as _, Disableable as _, StyledExt as _};
use gpui_kit::*;
use super::KeyForm;
use crate::release::{self, channel};
const THEMES: [(ThemePreference, &str); 3] = [
(ThemePreference::System, "Système"),
(ThemePreference::Light, "Clair"),
(ThemePreference::Dark, "Sombre"),
];
const CHANNELS: [(UpdateChannel, &str); 2] = [
(UpdateChannel::Stable, "Stable"),
(UpdateChannel::Beta, "Bêta"),
];
const LOGON_LABEL: &str = "Lancer à l’ouverture de session Windows";
// Not « Disponible »: the interface word of a Pickable champion (CONTEXT.md).
const LOGON_UNAVAILABLE: &str = "Réservé à la version installée.";
impl KeyForm {
pub(super) fn preferences(&self, cx: &mut Context<Self>) -> impl IntoElement {
let preferences = self.store.preferences();
let (muted, danger) = (cx.theme().muted_foreground, cx.theme().danger);
let logon_available = self.logon_launch.available();
div()
.v_flex()
.gap_3()
.child(
div()
.v_flex()
.gap_1()
.child(
Switch::new("launch-at-logon")
.label(LOGON_LABEL)
.checked(self.launches_at_logon)
.disabled(!logon_available)
.on_change(cx.listener(|this, enabled, _, cx| {
this.set_logon_launch(*enabled, cx);
})),
)
.children(
(!logon_available)
.then(|| div().text_color(muted).child(LOGON_UNAVAILABLE)),
),
)
.child(
Switch::new("close-to-tray")
.label("Fermer dans la zone de notification")
.checked(preferences.close_to_tray)
.on_change(cx.listener(|this, enabled, window, cx| {
this.set_preferences(
Preferences {
close_to_tray: *enabled,
..this.store.preferences()
},
window,
cx,
);
})),
)
.child(
div().v_flex().gap_1().child("Thème").child(
RadioGroup::horizontal("theme")
.children(THEMES.map(|(_, label)| label))
.selected_index(
THEMES
.iter()
.position(|(theme, _)| *theme == preferences.theme),
)
.on_change(cx.listener(|this, index: &usize, window, cx| {
this.set_preferences(
Preferences {
theme: THEMES[*index].0,
..this.store.preferences()
},
window,
cx,
);
})),
),
)
.child(
div()
.v_flex()
.gap_1()
.child("Mises à jour")
.child(
RadioGroup::horizontal("update-channel")
.children(CHANNELS.map(|(_, label)| label))
.selected_index(
CHANNELS
.iter()
.position(|(choice, _)| *choice == channel(preferences)),
)
.on_change(cx.listener(|this, index: &usize, window, cx| {
this.set_preferences(
Preferences {
update_channel: Some(CHANNELS[*index].0),
..this.store.preferences()
},
window,
cx,
);
})),
)
.children(release::VERSION.is_some().then(|| {
div().h_flex().child(
Button::new("check-update")
.label("Rechercher une mise à jour")
.disabled(self.update_checks.running())
.on_click(cx.listener(|this, _, _, cx| this.check_updates_now(cx))),
)
}))
.children(
[self.check_status(), self.update_status()]
.into_iter()
.flatten()
.map(|status| div().text_color(muted).child(status)),
)
.children(self.can_restart().then(|| {
div().h_flex().child(
Button::new("restart")
.label("Redémarrer")
.on_click(cx.listener(|this, _, _, cx| this.restart(cx))),
)
})),
)
.children(
(self.preference_error.clone()).map(|error| div().text_color(danger).child(error)),
)
}
}
+55
View File
@@ -0,0 +1,55 @@
use std::path::PathBuf;
use std::sync::Arc;
use arena_tracker_core::{Config, Error, Preferences, RiotApi};
/// The local config file and the running Riot client that uses its key.
pub struct KeyStore {
path: PathBuf,
config: Config,
api: Arc<RiotApi>,
}
impl KeyStore {
pub fn new(path: PathBuf, config: Config, api: Arc<RiotApi>) -> KeyStore {
KeyStore { path, config, api }
}
pub fn has_key(&self) -> bool {
!self.config.riot_api_key.is_empty()
}
pub fn preferences(&self) -> Preferences {
self.config.preferences
}
pub(super) fn tray_notice_shown(&self) -> bool {
self.config.tray_notice_shown
}
/// Writes the key to the config file and hands it to the Riot client, no restart needed.
pub(super) fn save(&mut self, key: &str) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.riot_api_key, key.to_string());
if let Err(e) = self.config.save(&self.path) {
self.config.riot_api_key = previous;
return Err(e);
}
self.api.set_key(key.to_string());
Ok(())
}
/// A failed write only means the notice is shown again at the next launch.
pub(super) fn record_tray_notice(&mut self) {
self.config.tray_notice_shown = true;
let _ = self.config.save(&self.path);
}
pub(super) fn save_preferences(&mut self, preferences: Preferences) -> Result<(), Error> {
let previous = std::mem::replace(&mut self.config.preferences, preferences);
if let Err(error) = self.config.save(&self.path) {
self.config.preferences = previous;
return Err(error);
}
Ok(())
}
}
+206
View File
@@ -0,0 +1,206 @@
use std::sync::Arc;
use arena_tracker_core::{Config, Preferences, RiotApi, ThemePreference, UpdateChannel};
use gpui_kit::component::ThemeMode;
use gpui_kit::{AppContext as _, TestAppContext, VisualTestContext, WindowOptions};
use super::{KeyForm, KeyStore, theme_mode};
use crate::logon::tests::Scratch;
use crate::worker::UpdateChecked;
#[gpui::test]
fn the_chosen_channel_is_saved_and_only_its_check_offers_a_restart(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let dir = std::env::temp_dir().join(format!("arena-channel-{}", std::process::id()));
let path = dir.join("config.toml");
let _ = std::fs::remove_dir_all(&dir);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(&path).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new(path.clone(), config, api);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, false, window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
let choose = |channel, cx: &mut VisualTestContext| {
cx.update(|window, cx| {
form.update(cx, |form, cx| {
let preferences = Preferences {
update_channel: Some(channel),
..form.store.preferences()
};
form.set_preferences(preferences, window, cx);
})
})
};
let saved = |channel| Preferences {
update_channel: Some(channel),
..Preferences::default()
};
choose(UpdateChannel::Beta, cx);
let loaded = Config::load(&path).unwrap().preferences;
assert_eq!(loaded, saved(UpdateChannel::Beta));
form.update(cx, |form, cx| {
// A stable check that ends after the change to Bêta stays out of sight.
let late = UpdateChecked {
channel: UpdateChannel::Stable,
result: Ok(Some("1.0.1".into())),
};
form.update_checked(late, cx);
assert!(!form.update_ready());
assert_eq!(form.update_status(), None);
let checked = UpdateChecked {
channel: UpdateChannel::Beta,
result: Ok(Some("1.1.0-beta.3".into())),
};
form.update_checked(checked, cx);
assert!(form.update_ready());
assert_eq!(
form.update_status().as_deref(),
Some("Mise à jour prête : version 1.1.0-beta.3")
);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
form.update(cx, |form, cx| {
// A development build has no installer: « Redémarrer » says so and the app stays.
form.restart(cx);
assert!(!form.update_ready());
let error = form.preference_error.as_deref();
assert_eq!(error, Some("Cette version ne se met pas à jour."));
});
form.update(cx, |form, cx| {
let checked = UpdateChecked {
channel: UpdateChannel::Beta,
result: Ok(None),
};
form.update_checked(checked, cx);
assert!(form.check_status().is_some());
});
choose(UpdateChannel::Stable, cx);
assert_eq!(form.read_with(cx, |form, _| form.check_status()), None);
assert!(!form.read_with(cx, |form, _| form.update_ready()));
let loaded = Config::load(&path).unwrap().preferences;
assert_eq!(loaded, saved(UpdateChannel::Stable));
std::fs::remove_dir_all(&dir).unwrap();
}
#[gpui::test]
fn the_last_check_is_told_until_the_settings_are_shown_again(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new("unused.toml".into(), config, api);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, false, window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
let checked = |result| UpdateChecked {
channel: UpdateChannel::Stable,
result,
};
form.update(cx, |form, cx| {
assert_eq!(form.check_status(), None);
assert!(form.update_checks.request());
assert_eq!(form.check_status().as_deref(), Some("Recherche en cours…"));
form.update_checked(checked(Ok(Some("1.0.1".into()))), cx);
assert!(form.update_ready());
assert_eq!(form.check_status(), None);
// A failed check leaves the kept package ready and says why.
form.update_checked(checked(Err("réseau".into())), cx);
assert!(form.update_ready());
assert_eq!(
form.check_status().as_deref(),
Some("Impossible de vérifier les mises à jour : réseau")
);
// A check of the other channel that ends late says nothing about this one.
let other = UpdateChecked {
channel: UpdateChannel::Beta,
result: Err("autre canal".into()),
};
form.update_checked(other, cx);
assert!(form.check_status().as_deref().unwrap().ends_with("réseau"));
// Nothing newer: the kept package is gone and the settings say so.
form.update_checked(checked(Ok(None)), cx);
assert!(!form.update_ready());
assert_eq!(
form.check_status().as_deref(),
Some("Vous avez la dernière version")
);
});
cx.update(|window, cx| {
form.update(cx, |form, cx| {
form.reset(window, cx);
assert_eq!(form.check_status(), None);
})
});
}
#[gpui::test]
fn the_logon_switch_shows_what_windows_holds(cx: &mut TestAppContext) {
cx.update(gpui_kit::init);
let (window, form) = cx.update(|cx| {
let config = Config::load_or_default(std::path::Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let store = KeyStore::new("unused.toml".into(), config, api);
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| KeyForm::new(store, false, window, cx))
})
.unwrap()
});
let cx = &mut VisualTestContext::from_window(window, cx);
let (scratch, installed) = Scratch::launch("settings", true);
let (_dev_scratch, development) = Scratch::launch("settings-dev", false);
form.update(cx, |form, cx| {
form.logon_launch = installed;
form.read_logon_launch();
assert!(
!form.launches_at_logon,
"a first installation starts disabled"
);
form.set_logon_launch(true, cx);
assert!(form.launches_at_logon);
assert_eq!(form.preference_error, None);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
// Disabled in the Task Manager while the settings were closed, then opened again.
scratch.disable_in_task_manager();
form.update(cx, |form, cx| {
form.read_logon_launch();
assert!(!form.launches_at_logon);
form.set_logon_launch(true, cx);
assert!(form.launches_at_logon, "switching it on approves it again");
form.set_logon_launch(false, cx);
assert!(!form.launches_at_logon);
});
// Windows refuses: the switch shows what it holds, and the settings say so.
form.update(cx, |form, cx| {
form.logon_launch = development;
form.set_logon_launch(true, cx);
assert!(!form.launches_at_logon);
assert_eq!(form.preference_error.as_deref(), Some(super::LOGON_ERROR));
});
cx.update(|window, cx| window.draw(cx).clear(cx));
}
#[test]
fn system_tracks_the_current_appearance_and_manual_choices_override_it() {
for system in [ThemeMode::Light, ThemeMode::Dark] {
assert_eq!(theme_mode(ThemePreference::System, system), system);
assert_eq!(theme_mode(ThemePreference::Light, system), ThemeMode::Light);
assert_eq!(theme_mode(ThemePreference::Dark, system), ThemeMode::Dark);
}
}
+299
View File
@@ -0,0 +1,299 @@
//! Elects one primary process per Windows session and relays launches to its window.
use std::marker::PhantomData;
use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
use gpui_kit::Window;
use windows::Win32::{
Foundation::{
HANDLE, HWND, LPARAM, LRESULT, WAIT_ABANDONED, WAIT_EVENT, WAIT_OBJECT_0, WAIT_TIMEOUT,
WPARAM,
},
System::Threading::{
CreateEventW, CreateMutexW, EVENT_MODIFY_STATE, OpenEventW, ReleaseMutex, SetEvent,
WaitForMultipleObjects, WaitForSingleObject,
},
UI::{
Shell::{DefSubclassProc, RemoveWindowSubclass, SetWindowSubclass},
WindowsAndMessaging::*,
},
};
use windows::core::{BOOL, Error, HSTRING, PCWSTR, Result, w};
const STARTING: PCWSTR = w!("Local\\nessar.arena-tracker.starting");
const INSTANCE: PCWSTR = w!("Local\\nessar.arena-tracker.instance");
const WINDOW_MARKER: PCWSTR = w!("nessar.arena-tracker.main-window");
// The marker is only a presence flag, its value is never read.
const MARKED: HANDLE = HANDLE(1 as _);
const REOPEN_SUBCLASS: usize = 0;
// Past this wait another instance is alive, so the launch gives up quietly.
const LAUNCH_TIMEOUT_MS: u32 = 5_000;
// Shares the window's WM_APP message space with the tray's message.
const REOPEN: u32 = crate::tray::TRAY_MESSAGE + 1;
// The acknowledgement event is the second object in the wait list.
const REOPENED: WAIT_EVENT = WAIT_EVENT(WAIT_OBJECT_0.0 + 1);
// Windows requires a mutex to be released on the thread that acquired it.
pub struct HeldMutex(OwnedHandle, PhantomData<*mut ()>);
impl HeldMutex {
/// `None` when the wait timed out. An abandoned mutex (crashed owner) counts as acquired.
fn from_wait(handle: OwnedHandle, status: WAIT_EVENT) -> Result<Option<Self>> {
match status {
WAIT_OBJECT_0 | WAIT_ABANDONED => Ok(Some(Self(handle, PhantomData))),
WAIT_TIMEOUT => Ok(None),
_ => Err(Error::from_thread()),
}
}
}
impl Drop for HeldMutex {
fn drop(&mut self) {
let _ = unsafe { ReleaseMutex(HANDLE(self.0.as_raw_handle())) };
}
}
pub struct Primary {
/// Held for the whole life of the app.
pub instance: HeldMutex,
/// Held until the first window is open, so that relaunches find it.
pub starting: HeldMutex,
}
pub(crate) fn owned(handle: HANDLE) -> OwnedHandle {
unsafe { OwnedHandle::from_raw_handle(handle.0) }
}
fn marked(hwnd: HWND) -> bool {
!unsafe { GetPropW(hwnd, WINDOW_MARKER) }.is_invalid()
}
/// `None` means exit without starting: the launch was relayed, or another instance is alive.
pub fn launch() -> Option<Primary> {
claim(STARTING, INSTANCE, relay).unwrap_or_else(|error| {
eprintln!("Failed to check for a running instance: {error}");
None
})
}
fn claim(
starting_name: PCWSTR,
instance_name: PCWSTR,
relay: impl FnOnce() -> Result<Option<OwnedHandle>>,
) -> Result<Option<Primary>> {
// Serialize launches until the winner has a window. Keep its other lock through app teardown.
let gate = owned(unsafe { CreateMutexW(None, false, starting_name)? });
let status = unsafe { WaitForSingleObject(HANDLE(gate.as_raw_handle()), LAUNCH_TIMEOUT_MS) };
let Some(starting) = HeldMutex::from_wait(gate, status)? else {
return Ok(None);
};
let mutex = owned(unsafe { CreateMutexW(None, false, instance_name)? });
let handle = HANDLE(mutex.as_raw_handle());
let status = match unsafe { WaitForSingleObject(handle, 0) } {
WAIT_TIMEOUT => match relay()? {
// If the window closes before acknowledging, take over when the owner exits.
Some(event) => unsafe {
WaitForMultipleObjects(
&[handle, HANDLE(event.as_raw_handle())],
false,
LAUNCH_TIMEOUT_MS,
)
},
None => unsafe { WaitForSingleObject(handle, LAUNCH_TIMEOUT_MS) },
},
status => status,
};
if status == REOPENED {
return Ok(None);
}
Ok(HeldMutex::from_wait(mutex, status)?.map(|instance| Primary { instance, starting }))
}
fn reply_name(pid: u32) -> HSTRING {
HSTRING::from(format!("Local\\nessar.arena-tracker.reopened.{pid}"))
}
fn relay() -> Result<Option<OwnedHandle>> {
unsafe extern "system" fn find(hwnd: HWND, output: LPARAM) -> BOOL {
if !marked(hwnd) {
return true.into();
}
unsafe { *(output.0 as *mut HWND) = hwnd };
false.into()
}
let mut hwnd = HWND::default();
let _ = unsafe { EnumWindows(Some(find), LPARAM((&mut hwnd as *mut HWND) as isize)) };
if hwnd.is_invalid() {
return Ok(None);
}
let mut pid = 0;
if unsafe { GetWindowThreadProcessId(hwnd, Some(&mut pid)) } == 0 {
return Ok(None);
}
let sender = std::process::id();
let event = owned(unsafe { CreateEventW(None, false, false, &reply_name(sender))? });
let posted = unsafe {
let _ = AllowSetForegroundWindow(pid);
// A posted reopen runs after any close already in the window's message queue.
PostMessageW(Some(hwnd), REOPEN, WPARAM(sender as usize), LPARAM(0))
};
Ok(posted.is_ok().then_some(event))
}
pub fn accept_relaunches(window: &Window) {
let Some(hwnd) = crate::tray::window_hwnd(window) else {
eprintln!("Failed to get the window handle for relaunches");
return;
};
unsafe {
if !SetWindowSubclass(hwnd, Some(window_proc), REOPEN_SUBCLASS, 0).as_bool() {
eprintln!("Failed to install the window reopen handler");
return;
}
if let Err(error) = SetPropW(hwnd, WINDOW_MARKER, Some(MARKED)) {
eprintln!("Failed to publish the window: {error}");
}
}
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
_: usize,
) -> LRESULT {
match message {
REOPEN => {
if marked(hwnd) {
crate::tray::reopen(hwnd);
// The relaunching process may have timed out and exited, taking its event along.
if marked(hwnd)
&& let Ok(event) = unsafe {
OpenEventW(EVENT_MODIFY_STATE, false, &reply_name(wparam.0 as u32))
}
{
let _event = owned(event);
let _ = unsafe { SetEvent(event) };
}
}
return LRESULT(0);
}
WM_DESTROY => {
let _ = unsafe { RemovePropW(hwnd, WINDOW_MARKER) };
}
WM_NCDESTROY => {
let _ = unsafe { RemoveWindowSubclass(hwnd, Some(window_proc), id) };
}
_ => {}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
#[cfg(test)]
mod tests {
use std::{mem, sync::mpsc, thread, time::Duration};
use super::*;
/// Per-pid mutex names, so that tests never meet a real instance or each other.
fn names(test: &str) -> (HSTRING, HSTRING) {
let pid = std::process::id();
(
HSTRING::from(format!("Local\\arena-tracker.test.{test}.starting.{pid}")),
HSTRING::from(format!("Local\\arena-tracker.test.{test}.instance.{pid}")),
)
}
fn claim_with(
(starting, instance): &(HSTRING, HSTRING),
relay: impl FnOnce() -> Result<Option<OwnedHandle>>,
) -> Result<Option<Primary>> {
claim(PCWSTR(starting.as_ptr()), PCWSTR(instance.as_ptr()), relay)
}
fn event(signaled: bool) -> Result<Option<OwnedHandle>> {
let event = unsafe { CreateEventW(None, false, signaled, PCWSTR::null())? };
Ok(Some(owned(event)))
}
#[test]
fn launch_relays_to_a_running_instance_and_takes_over_after_shutdown() {
let names = names("relay");
let Primary {
instance: primary,
starting: initializing,
} = claim_with(&names, || panic!("First launch has no window to relay to"))
.unwrap()
.unwrap();
let names = &names;
thread::scope(|scope| {
let secondary = scope.spawn(|| {
assert!(claim_with(names, || event(true)).unwrap().is_none());
});
drop(initializing);
secondary.join().unwrap();
let (relaying, attempted) = mpsc::channel();
let successor = scope.spawn(move || {
let result = claim_with(names, || {
relaying.send(()).unwrap();
event(false)
});
assert!(result.unwrap().is_some());
});
let result = attempted.recv_timeout(Duration::from_secs(5));
drop(primary);
result.unwrap();
successor.join().unwrap();
});
}
#[test]
fn launch_takes_over_from_a_crashed_primary() {
let names = names("crashed");
thread::scope(|scope| {
scope
.spawn(|| {
let primary = claim_with(&names, || panic!("No window yet"))
.unwrap()
.unwrap();
// Exiting while owning both mutexes abandons them, as a crash would.
mem::forget(primary);
})
.join()
.unwrap();
});
let result = claim_with(&names, || panic!("The crashed primary left no window"));
assert!(result.unwrap().is_some());
}
#[test]
fn launch_without_a_window_takes_over_once_the_owner_exits() {
let names = names("no-window");
let Primary { instance, starting } = claim_with(&names, || panic!("No window yet"))
.unwrap()
.unwrap();
drop(starting);
let names = &names;
thread::scope(|scope| {
let (relaying, attempted) = mpsc::channel();
let successor = scope.spawn(move || {
let result = claim_with(names, || {
relaying.send(()).unwrap();
Ok(None)
});
assert!(result.unwrap().is_some());
});
let result = attempted.recv_timeout(Duration::from_secs(5));
drop(instance);
result.unwrap();
successor.join().unwrap();
});
}
}
+14
View File
@@ -0,0 +1,14 @@
//! The champ select's own motion (#87): its entry (a band of gold light sweeping the window, the
//! title coming in, the Anvil champions dealt from the bottom one after another), an ally's
//! confirmation lowering its card, and its exit (the hand leaving before the home comes back
//! under the veil of the tabs). The hand's cards move over its cached grid, from where the grid
//! last placed them, as a lifted card does (`card_lift`): the grid itself is never drawn again.
mod hand;
mod motion;
pub(crate) use hand::{HandMotion, hand_layer};
pub(crate) use motion::{BEFORE_VEIL, Entry, HandAt, Leave, Taken, sweep};
#[cfg(test)]
mod tests;
+172
View File
@@ -0,0 +1,172 @@
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::*;
use super::motion::Leaving;
use super::{Entry, Leave, Taken};
use crate::card::{self, Card, Pose};
use crate::card_grid::DrawnCards;
use crate::card_images::CardImages;
use crate::card_lift::{self, Layer};
use std::time::Instant;
/// What moves in the hand at a frame.
pub(crate) struct HandMotion {
pub entry: Option<Entry>,
pub leave: Option<Leave>,
pub taken: Vec<Taken>,
/// The cards lifted over the grid (`card_lift`): theirs is the last word.
pub lifted: Vec<u32>,
/// The leaving cards' opacity under the veil of the tabs, 1 without it.
pub unveiled: f32,
pub now: Instant,
}
/// A card of the hand drawn over its grid at a frame: lifted as `pose` says, `down` below its
/// place (above when negative).
struct Drawn<'a> {
card: &'a Card,
pose: Pose,
down: f32,
opacity: f32,
}
impl<'a> Drawn<'a> {
/// A card at rest, not lifted and under no veil.
fn at_rest(card: &'a Card, down: f32, opacity: f32) -> Drawn<'a> {
let pose = Pose {
mark_fill: None,
progress: 0.,
veil: 0.,
moves: true,
};
Drawn {
card,
pose,
down,
opacity,
}
}
}
/// Draws the hand's cards that move over its grid, where the grid last placed them and as
/// `cards` holds them now; their places are covered with the page's background. A card is cut
/// where the page shows the hand, so a card dealt comes up from the bottom of the window, and a
/// card out of sight is not built. Painted after the rest of the page, as the lifted cards are.
pub(crate) fn hand_layer(
cards: std::rc::Rc<[Card]>,
drawn_cards: DrawnCards,
images: Option<Entity<CardImages>>,
motion: HandMotion,
) -> AnyElement {
deferred(
canvas(
move |_, window, cx| {
let background = cx.theme().background;
let drawn_cards = drawn_cards.borrow();
let now = motion.now;
let mut quads = Vec::new();
let mut moving = Vec::new();
// In the hand's order: the cards dealt later go over the earlier ones.
for (ix, card) in cards.iter().enumerate() {
let Some(drawn) = drawn_cards.get(&card.id) else {
continue;
};
// How far a card dealt comes from: the bottom of the window.
let from = || {
(drawn.visible.bottom() - drawn.bounds.top())
.as_f32()
.max(drawn.bounds.size.height.as_f32())
};
// At most two: the card, and the card as it was fading over it.
let mut draw: [Option<Drawn>; 2] = [None, None];
if let Some(leave) = &motion.leave {
// Where it was when the champ select ended. A card that was not in the
// hand then is not seen: its place stays covered.
let Some((ix, was)) = leave.card(card.id, ix) else {
if drawn.bounds.intersects(&drawn.visible) {
quads.push(Layer::Quad(drawn.bounds, background, drawn.visible));
}
continue;
};
let Leaving { down, opacity } = leave.pose(ix, now);
let kept = opacity * motion.unveiled;
let down = from() * was.left + down;
let pose = was.pose;
draw = [
Some(Drawn {
card,
pose,
down: down - was.above,
opacity: was.opacity * kept,
}),
was.before.as_ref().map(|before| Drawn {
card: &before.card,
pose,
down: down - before.above,
opacity: before.opacity * kept,
}),
];
} else if let Some(entry) = motion.entry
&& !entry.landed(ix, now)
{
let (left, opacity) = entry.dealt(ix, now).pose();
draw[0] = Some(Drawn::at_rest(card, from() * left, opacity));
} else if let Some(taken) =
motion.taken.iter().find(|taken| taken.id == card.id)
// A lifted card is lowered by its own layer (`card_lift`).
&& !motion.lifted.contains(&card.id)
{
let above = -taken.above(now);
draw = [
Some(Drawn::at_rest(card, above, 1.)),
Some(Drawn::at_rest(&taken.before, above, taken.before(now))),
];
}
if draw[0].is_none() {
continue;
}
if drawn.bounds.intersects(&drawn.visible) {
quads.push(Layer::Quad(drawn.bounds, background, drawn.visible));
}
let size = drawn.bounds.size;
for Drawn {
card,
pose,
down,
opacity,
} in draw.into_iter().flatten()
{
let origin = drawn.bounds.origin + point(px(0.), px(down));
// Out of sight, as a card still under the bottom of the window: GPUI
// would cut it whole, so it is not built (rule #1).
if opacity <= 0. || !Bounds::new(origin, size).intersects(&drawn.visible) {
continue;
}
// A lifted card is cut as its own layer cuts it: not at all when the grid
// shows it whole, so it is still over the list's edge.
let (element, cut) = if pose.progress > 0. {
(card::lifted(card, pose, size, cx), card_lift::cut(drawn))
} else {
(card::moving(card, pose.veil, size, cx), Some(drawn.visible))
};
let mask = cut.map(|bounds| ContentMask { bounds });
moving.push(card_lift::prepaint_card(
element.opacity(opacity),
images.as_ref(),
origin,
size,
mask,
window,
cx,
));
}
}
quads.extend(moving);
quads
},
|_, layers, window, cx| card_lift::paint(layers, window, cx),
)
.absolute(),
)
.into_any_element()
}
+373
View File
@@ -0,0 +1,373 @@
use std::rc::Rc;
use std::time::{Duration, Instant};
use gpui_kit::base::Easing;
use gpui_kit::component::ActiveTheme as _;
use gpui_kit::*;
use crate::card::{Card, Pose};
use crate::card_grid::TAKEN_DROP;
use crate::card_lift::{Lifted, Lowered};
use crate::motion::{ease_in, ease_out};
use crate::theme::gold_soft;
/// How long the band of light takes to cross the window, fading as it goes.
const SWEEP: Duration = Duration::from_millis(900);
/// How long the title takes to come in, rising.
const TITLE: Duration = Duration::from_millis(700);
/// How far below its place the title starts.
const TITLE_RISE: f32 = 8.;
/// When the first card of the hand leaves the bottom of the window.
const FIRST_DEAL: Duration = Duration::from_millis(380);
/// How long after the card before it each next card leaves.
const DEAL_EVERY: Duration = Duration::from_millis(110);
/// How long a card takes from the bottom of the window to its place.
const DEAL: Duration = Duration::from_millis(700);
/// How long a card of the hand takes to leave, the last one first.
const LEAVE: Duration = Duration::from_millis(320);
/// How long after the card after it each card leaves.
const LEAVE_EVERY: Duration = Duration::from_millis(35);
/// How far down a card of the hand goes as it leaves.
const LEAVE_DROP: f32 = 48.;
/// How long the hand leaves alone before the veil of the tabs starts covering the screen.
pub(crate) const BEFORE_VEIL: Duration = Duration::from_millis(240);
/// How long a card an ally just took takes to go down to its place (`card_grid::TAKEN_DROP`).
const TAKEN: Duration = Duration::from_millis(350);
/// How long it takes to grey, its new badge coming in.
const TAKEN_FADE: Duration = Duration::from_millis(500);
/// The band of light's curve, as CSS's `ease-out`.
const SWEEP_CURVE: Easing = Easing::EaseOut;
/// A card dealt's curve, the reference's `cubic-bezier(.2, 1.25, .35, 1)`: it goes a little past
/// its place before settling there.
const DEAL_CURVE: Easing = Easing::CubicBezier {
x1: 0.2,
y1: 1.25,
x2: 0.35,
y2: 1.,
};
/// How far an animation of `duration` started at `start` is, 0 to 1; 0 before it starts.
fn progress(start: Instant, duration: Duration, now: Instant) -> f32 {
let elapsed = now.saturating_duration_since(start);
(elapsed.as_secs_f32() / duration.as_secs_f32()).min(1.)
}
/// The entry into a champ select, from the moment the window shows it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Entry {
start: Instant,
/// When the deal's clock started: the entry's own start, or later when the hand's cards come
/// after the first one should have left (the statistics load at each new champ select).
deal: Option<Instant>,
}
/// Where a card of the hand is in the deal.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Dealt {
/// Not dealt yet: its place is empty.
Waiting,
/// On its way, 0 to 1.
Moving(f32),
/// In its place: the grid's own card.
Landed,
}
impl Dealt {
/// How much of the way it still has to go (as `deal_pose`), and its opacity: a card not
/// dealt yet is out of sight.
pub fn pose(self) -> (f32, f32) {
match self {
Dealt::Waiting => (0., 0.),
Dealt::Moving(progress) => deal_pose(progress),
Dealt::Landed => (0., 1.),
}
}
}
impl Entry {
/// An entry starting `now`, its hand waiting for its cards.
pub fn new(now: Instant) -> Entry {
Entry {
start: now,
deal: None,
}
}
/// The hand has its cards: they are dealt on the entry's clock, or from now on when they
/// come late. Their reasons changing later deals nothing again.
pub fn cards_arrived(&mut self, now: Instant) {
if self.deal.is_none() {
let late = now.checked_sub(FIRST_DEAL).unwrap_or(self.start);
self.deal = Some(late.max(self.start));
}
}
/// How far the band of light has crossed, 0 to 1, while it does; as CSS's `ease-out`.
pub fn sweep(&self, now: Instant) -> Option<f32> {
let progress = progress(self.start, SWEEP, now);
(progress < 1.).then(|| SWEEP_CURVE.sample(progress))
}
/// How far the title has come in, 0 to 1.
pub fn title(&self, now: Instant) -> f32 {
ease_out(progress(self.start, TITLE, now))
}
/// Where card `ix` of the hand (in the hand's order) is in the deal.
pub fn dealt(&self, ix: usize, now: Instant) -> Dealt {
let Some(deal) = self.deal else {
// No card yet: none to hide.
return Dealt::Landed;
};
let leaves = deal + FIRST_DEAL + DEAL_EVERY * ix as u32;
if now < leaves {
return Dealt::Waiting;
}
match progress(leaves, DEAL, now) {
1. => Dealt::Landed,
progress => Dealt::Moving(progress),
}
}
/// Whether the hand has its cards, dealt or being dealt.
pub fn dealing(&self) -> bool {
self.deal.is_some()
}
/// Whether card `ix` of the hand is in its place.
pub fn landed(&self, ix: usize, now: Instant) -> bool {
self.dealt(ix, now) == Dealt::Landed
}
/// Whether anything of the entry still moves, the hand holding `cards`. Waiting for the
/// hand's cards moves nothing. The time gone is enough: no curve is solved.
pub fn animating(&self, cards: usize, now: Instant) -> bool {
now < self.start + SWEEP.max(TITLE) || (cards > 0 && !self.landed(cards - 1, now))
}
/// Whether the entry is over: the hand had its cards, and they are all in their place.
pub fn over(&self, cards: usize, now: Instant) -> bool {
self.deal.is_some() && !self.animating(cards, now)
}
/// The title's opacity and how far below its place it is.
pub fn title_pose(&self, now: Instant) -> (f32, f32) {
let progress = self.title(now);
(progress, TITLE_RISE * (1. - progress))
}
}
/// A card on its way from the bottom of the window: how much of the way is left (below 0 past
/// its place, as the reference's curve goes beyond it before settling), and its opacity.
fn deal_pose(progress: f32) -> (f32, f32) {
let done = DEAL_CURVE.sample(progress);
(1. - done, done.clamp(0., 1.))
}
/// The exit from a champ select: the hand's cards go down and fade, the last one first, each
/// from where it was when the champ select ended.
#[derive(Clone, Debug)]
pub(crate) struct Leave {
start: Instant,
/// Where each card of the hand was, in the hand's order: read once, when the champ select
/// ended.
cards: Rc<[CardAtEnd]>,
}
/// Where a card of the hand was when the champ select ended, as it was drawn then.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct CardAtEnd {
pub id: u32,
/// How much of the deal's way it still had to go (as `deal_pose`), 0 once in its place.
pub left: f32,
/// Its opacity: 0 for a card not dealt yet, which stays out of sight.
pub opacity: f32,
/// How far it was lifted (`card_lift`), and the hand's veil on it.
pub pose: Pose,
/// How far above its place it was: its rise, and an ally's confirmation not over.
pub above: f32,
/// The card as it was before an ally's confirmation not over, fading over it.
pub before: Option<Before>,
}
/// The card as it was before an ally's confirmation, over the card now.
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Before {
pub card: Rc<Card>,
pub above: f32,
pub opacity: f32,
}
/// How far a card of the hand went from where it was.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Leaving {
/// How far down.
pub down: f32,
/// How much of its opacity it keeps: 1 at first, 0 once gone.
pub opacity: f32,
}
/// What the hand looked like when the champ select ended.
pub(crate) struct HandAt<'a> {
/// The entry it was in, if its cards were still dealt.
pub entry: Option<Entry>,
/// Its cards lifted or settling back (`card_lift`).
pub lifted: &'a [Lifted],
/// The hand's veil on the others.
pub veil: f32,
/// Its cards going down after an ally's confirmation.
pub taken: &'a [Taken],
}
impl Leave {
/// The hand of `cards` leaving from `now`, each card from where `hand` shows it.
pub fn new(cards: &[Card], hand: HandAt, now: Instant) -> Leave {
let cards = cards
.iter()
.enumerate()
.map(|(ix, card)| {
let dealt = hand.entry.map_or(Dealt::Landed, |e| e.dealt(ix, now));
let (left, opacity) = dealt.pose();
let progress = (hand.lifted.iter())
.find(|lifted| lifted.id == card.id)
.map_or(0., |lifted| lifted.progress);
let pose = Pose {
mark_fill: None,
progress,
// Settling back, it goes under the veil, as `card_lift` draws it.
veil: hand.veil * (1. - progress),
// The hand leaves only when the Windows setting lets it move.
moves: true,
};
let taken = hand.taken.iter().find(|taken| taken.id == card.id);
let lowered = taken.map_or(0., |taken| taken.above(now));
CardAtEnd {
id: card.id,
left,
opacity,
pose,
above: pose.rise(card) + lowered,
before: taken.map(|taken| Before {
above: pose.rise(&taken.before) + lowered,
card: taken.before.clone(),
opacity: taken.before(now),
}),
}
})
.collect();
Leave { start: now, cards }
}
/// Where card `id` was when the champ select ended, and its index in the hand then, if it
/// was there: `ix`, its index now, is looked at first. The hand may change as it leaves
/// (statistics reloaded).
pub fn card(&self, id: u32, ix: usize) -> Option<(usize, &CardAtEnd)> {
match self.cards.get(ix) {
Some(was) if was.id == id => Some((ix, was)),
_ => (self.cards.iter().enumerate()).find(|(_, was)| was.id == id),
}
}
/// How far card `ix` of the hand, as it was when the champ select ended, went from where
/// it was.
pub fn pose(&self, ix: usize, now: Instant) -> Leaving {
let after = self.cards.len().saturating_sub(ix + 1) as u32;
let done = ease_in(progress(self.start + LEAVE_EVERY * after, LEAVE, now));
Leaving {
down: LEAVE_DROP * done,
opacity: 1. - done,
}
}
}
/// A card of the hand an ally just took: it goes down to its place, lower than the others, and
/// greys as its badge comes in, the card as it was fading over it.
#[derive(Clone, Debug)]
pub(crate) struct Taken {
pub id: u32,
/// Shared by every frame that draws it.
pub(super) before: Rc<Card>,
start: Instant,
}
impl Taken {
/// Card `id` taken `now`, `before` being how it looked until then.
pub fn new(id: u32, before: Rc<Card>, now: Instant) -> Taken {
Taken {
id,
before,
start: now,
}
}
/// How far above its place the card is.
pub fn above(&self, now: Instant) -> f32 {
TAKEN_DROP * (1. - ease_out(progress(self.start, TAKEN, now)))
}
/// The opacity of the card as it was, over the one it is now.
pub fn before(&self, now: Instant) -> f32 {
1. - progress(self.start, TAKEN_FADE, now)
}
/// Whether it is in its place and greyed.
pub fn done(&self, now: Instant) -> bool {
progress(self.start, TAKEN_FADE, now) >= 1.
}
/// The card as a lifted one draws it: it goes down to its place as it greys.
pub fn lowered(&self, now: Instant) -> Lowered {
Lowered {
id: self.id,
above: self.above(now),
before: self.before.clone(),
opacity: self.before(now),
}
}
}
/// The band of gold light crossing the window, `progress` 0 to 1, `window` its size: it goes
/// from left to right and fades as it goes, as the reference's gradient (GPUI's gradients have
/// two stops: the band is four of them side by side). Over the whole window, the title bar
/// included, and painted after everything else, the hand's moving cards too. It catches no
/// pointer.
pub(crate) fn sweep(progress: f32, window: Size<Pixels>, cx: &App) -> AnyElement {
let width = window.width.as_f32();
let gold = gold_soft(cx.theme());
let clear = gold.opacity(0.);
let light = hsla(0., 0., 1., 0.16);
// The reference's band, 28 % of a gradient three windows wide: 0.375 of a window to gold,
// then 0.045 to the white of its middle, and back.
let (outer, inner) = (0.375 * width, 0.045 * width);
let middle = -0.5 * width + 2. * width * progress;
let parts = [
(middle - inner - outer, outer, clear, gold),
(middle - inner, inner, gold, light),
(middle, inner, light, gold),
(middle + inner, outer, gold, clear),
];
let band = div()
.relative()
.w(window.width)
.h(window.height)
.overflow_hidden()
.opacity(1. - progress)
.debug_selector(|| "sweep".into())
.children(parts.map(|(left, part, from, to)| {
div()
.absolute()
.top_0()
.bottom_0()
.left(px(left))
.w(px(part))
.bg(linear_gradient(
90.,
linear_color_stop(from, 0.),
linear_color_stop(to, 1.),
))
}));
// Over the deferred layers of the hand and of the lifted cards (priority 0).
deferred(anchored().position(point(px(0.), px(0.))).child(band))
.with_priority(1)
.into_any_element()
}
+219
View File
@@ -0,0 +1,219 @@
use std::time::{Duration, Instant};
use std::rc::Rc;
use super::motion::{Dealt, Leaving};
use super::{Entry, HandAt, Leave, Taken};
use crate::card::Card;
use crate::card_lift::Lifted;
fn at(start: Instant, ms: u64) -> Instant {
start + Duration::from_millis(ms)
}
#[test]
fn the_band_crosses_in_900_ms_and_the_title_comes_in_in_700() {
let start = Instant::now();
let entry = Entry::new(start);
assert_eq!(entry.sweep(start), Some(0.));
let halfway = entry.sweep(at(start, 450)).unwrap();
// Fast at first, then slowing, as CSS's ease-out.
assert!(halfway > 0.5 && halfway < 1., "{halfway}");
assert_eq!(entry.sweep(at(start, 900)), None);
assert_eq!(entry.title_pose(start), (0., 8.));
let (opacity, below) = entry.title_pose(at(start, 350));
assert!(opacity > 0.5 && below < 4., "{opacity} {below}");
assert_eq!(entry.title_pose(at(start, 700)), (1., 0.));
}
#[test]
fn the_cards_leave_the_bottom_from_380_ms_then_every_110_ms() {
let start = Instant::now();
let mut entry = Entry::new(start);
entry.cards_arrived(start);
assert_eq!(entry.dealt(0, at(start, 379)), Dealt::Waiting);
assert_eq!(entry.dealt(0, at(start, 380)), Dealt::Moving(0.));
assert_eq!(entry.dealt(1, at(start, 489)), Dealt::Waiting);
assert_eq!(entry.dealt(1, at(start, 490)), Dealt::Moving(0.));
// Each takes 700 ms to its place.
assert!(matches!(entry.dealt(0, at(start, 1079)), Dealt::Moving(_)));
assert_eq!(entry.dealt(0, at(start, 1080)), Dealt::Landed);
// The fifth lands last, and the entry is over with it.
assert!(entry.animating(5, at(start, 1519)));
assert_eq!(entry.dealt(4, at(start, 1520)), Dealt::Landed);
assert!(!entry.animating(5, at(start, 1520)));
}
#[test]
fn cards_coming_late_are_dealt_from_then_and_only_once() {
let start = Instant::now();
let mut entry = Entry::new(start);
// The hand is empty while the statistics load: nothing waits for it.
assert!(!entry.animating(0, at(start, 900)));
assert_eq!(entry.dealt(0, at(start, 900)), Dealt::Landed);
entry.cards_arrived(at(start, 1000));
assert_eq!(entry.dealt(0, at(start, 1000)), Dealt::Moving(0.));
assert_eq!(entry.dealt(1, at(start, 1000)), Dealt::Waiting);
// New reasons on the cards do not deal them again.
entry.cards_arrived(at(start, 1500));
assert_eq!(entry.dealt(0, at(start, 1700)), Dealt::Landed);
// Cards coming before the first should leave keep the entry's clock.
let mut early = Entry::new(start);
early.cards_arrived(at(start, 200));
assert_eq!(early.dealt(0, at(start, 380)), Dealt::Moving(0.));
}
#[test]
fn a_card_dealt_comes_from_below_goes_a_little_past_its_place_and_settles() {
assert_eq!(Dealt::Moving(0.).pose(), (1., 0.));
// Fast at first: most of the way in a quarter of the time.
let (left, opacity) = Dealt::Moving(0.25).pose();
assert!(left > 0. && left < 0.5 && opacity > 0.5, "{left} {opacity}");
let past = (30..100)
.map(|i| Dealt::Moving(i as f32 / 100.).pose().0)
.fold(1f32, f32::min);
assert!(past < 0., "{past}");
let (left, opacity) = Dealt::Moving(1.).pose();
assert!(left.abs() < 1e-4 && opacity == 1.);
}
fn card(id: u32) -> Card {
Card {
id,
name: format!("Card {id}").into(),
portrait: None,
marks: arena_tracker_core::Marks {
played: false,
won: false,
completed: false,
},
reasons: Vec::new(),
sheet: Vec::new(),
}
}
fn hand(count: u32) -> Vec<Card> {
(1..=count).map(card).collect()
}
/// The hand at rest: dealt, nothing lifted, no veil, no confirmation going on.
fn at_rest<'a>() -> HandAt<'a> {
HandAt {
entry: None,
lifted: &[],
veil: 0.,
taken: &[],
}
}
fn leaving(down: f32, opacity: f32) -> Leaving {
Leaving { down, opacity }
}
#[test]
fn the_hand_leaves_from_the_last_card_to_the_first_in_about_a_third_of_a_second() {
let start = Instant::now();
let leave = Leave::new(&hand(5), at_rest(), start);
assert_eq!(leave.pose(4, start), leaving(0., 1.));
let Leaving { down, opacity } = leave.pose(4, at(start, 160));
assert!(down > 0. && opacity < 1.);
// The first card starts 4 × 35 ms later.
assert_eq!(leave.pose(0, at(start, 140)), leaving(0., 1.));
assert_eq!(leave.pose(4, at(start, 320)), leaving(48., 0.));
assert_eq!(leave.pose(0, at(start, 460)), leaving(48., 0.));
// In its place, seen whole.
let first = leave.card(1, 0).unwrap().1;
assert_eq!((first.left, first.opacity, first.above), (0., 1., 0.));
}
// The hand changes as it leaves (its statistics reloaded): each card is still found where
// it was, in its order then; one that was not there is not.
#[test]
fn a_card_of_the_hand_is_found_where_it_was_whatever_its_index_now() {
let leave = Leave::new(&hand(3), at_rest(), Instant::now());
assert_eq!(leave.card(3, 0).map(|(ix, was)| (ix, was.id)), Some((2, 3)));
assert_eq!(leave.card(1, 0).map(|(ix, was)| (ix, was.id)), Some((0, 1)));
assert!(leave.card(9, 1).is_none());
}
#[test]
fn a_hand_ended_during_its_deal_leaves_from_where_each_card_was() {
let start = Instant::now();
let mut entry = Entry::new(start);
entry.cards_arrived(start);
// 700 ms: Briar, Lee Sin and Rumble on their way, the two others waiting.
let end = at(start, 700);
let hand_at = HandAt {
entry: Some(entry),
..at_rest()
};
let leave = Leave::new(&hand(5), hand_at, end);
for ix in 0..3 {
let Dealt::Moving(progress) = entry.dealt(ix, end) else {
panic!("card {ix} is not on its way");
};
let (left, opacity) = Dealt::Moving(progress).pose();
assert!(opacity > 0., "card {ix} is not seen");
// Where it was, read once.
let was = leave.card(ix as u32 + 1, ix).unwrap().1;
assert_eq!((was.left, was.opacity), (left, opacity));
}
for ix in 3..5 {
assert_eq!(
leave.card(ix as u32 + 1, ix).unwrap().1.opacity,
0.,
"card {ix} is seen"
);
}
}
// A card lifted leaves from its height, lifted, under no veil; the others under the veil
// as it was. A card an ally's confirmation was lowering leaves from where it was, the card
// as it was still fading over it.
#[test]
fn a_lifted_or_lowered_card_leaves_from_where_it_was() {
let start = Instant::now();
let mut cards = hand(3);
let before = Rc::new(cards[2].clone());
cards[2].reasons.push(crate::card::Reason::TakenByAlly);
let lifted = [Lifted {
id: 1,
progress: 1.,
}];
let taken = [Taken::new(3, before.clone(), start)];
let hand_at = HandAt {
entry: None,
lifted: &lifted,
veil: 1.,
taken: &taken,
};
let end = at(start, 100);
let leave = Leave::new(&cards, hand_at, end);
let lifted = leave.card(1, 0).unwrap().1;
assert_eq!((lifted.pose.progress, lifted.pose.veil), (1., 0.));
assert_eq!(lifted.above, 10.);
assert_eq!(leave.card(2, 1).unwrap().1.pose.veil, 1.);
let lowered = leave.card(3, 2).unwrap().1;
let above = taken[0].above(end);
assert!(above > 0. && above < 8., "{above}");
assert_eq!(lowered.above, above);
let was = lowered.before.as_ref().expect("the card as it was");
assert_eq!(was.card, before);
assert_eq!((was.above, was.opacity), (above, taken[0].before(end)));
}
#[test]
fn a_card_taken_by_an_ally_goes_down_8_px_while_it_greys() {
let start = Instant::now();
let taken = Taken::new(7, Rc::new(card(7)), start);
assert_eq!((taken.above(start), taken.before(start)), (8., 1.));
assert_eq!(taken.above(at(start, 350)), 0.);
assert!(taken.before(at(start, 350)) > 0.);
assert!(!taken.done(at(start, 499)));
assert_eq!(taken.before(at(start, 500)), 0.);
assert!(taken.done(at(start, 500)));
}
File diff suppressed because it is too large. Load diff
+142
View File
@@ -0,0 +1,142 @@
use std::path::Path;
use std::sync::Arc;
use arena_tracker_core::{ChampionSort, Config, RiotApi, Tracker, UpdateChannel};
use gpui_kit::{
AppContext as _, Entity, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers, TestAppContext,
VisualTestContext, WindowOptions, point,
};
use super::{KeyStore, RootView, Screen, Setup};
use crate::card_images::tests::TestDir;
use crate::title_bar::{BAR_HEIGHT, BUTTON_WIDTH};
use crate::worker::UpdateChecked;
/// A first launch: no key and nothing stored.
fn first_launch(cx: &mut TestAppContext) -> (VisualTestContext, Entity<RootView>) {
cx.update(gpui_kit::init);
let (window, root) = cx.update(|cx| {
let config = Config::load_or_default(Path::new(":memory:")).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let setup = Setup {
tracker: Arc::new(Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap()),
riot_id: String::new(),
notice: None,
store: KeyStore::new("unused.toml".into(), config, api),
};
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| RootView::new(setup, false, window, cx))
})
.unwrap()
});
(VisualTestContext::from_window(window, cx), root)
}
#[gpui::test]
fn a_ready_update_adds_a_title_bar_button_that_opens_the_settings(cx: &mut TestAppContext) {
let (mut cx, root) = first_launch(cx);
let cx = &mut cx;
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
// Centre of the third action button, title-bar drag area until an update is ready.
let update = point(BUTTON_WIDTH * 2.5, BAR_HEIGHT / 2.);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(update, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Page));
let form = root.read_with(cx, |root, _| root.form.clone());
form.update(cx, |form, cx| {
let checked = UpdateChecked {
channel: UpdateChannel::Stable,
result: Ok(Some("1.0.1".into())),
};
form.update_checked(checked, cx);
});
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(update, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
}
#[gpui::test]
fn settings_in_the_title_bar_respects_the_initial_key_prompt(cx: &mut TestAppContext) {
let (mut cx, root) = first_launch(cx);
let cx = &mut cx;
// Centre of the second action button.
let settings = point(BUTTON_WIDTH * 1.5, BAR_HEIGHT / 2.);
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_click(settings, Modifiers::none());
assert!(root.read_with(cx, |root, _| root.screen == Screen::Prompt));
// Model a keyless launch with stored data, where Settings is available.
root.update(cx, |root, cx| {
root.screen = Screen::Page;
cx.notify();
});
assert!(!root.read_with(cx, |root, cx| root.can_refresh(cx)));
cx.update(|window, cx| window.draw(cx).clear(cx));
cx.simulate_keystrokes("tab");
let enter =
cx.update(|_, cx| Keystroke::parse_with_os("enter", cx.platform_info().os).unwrap());
cx.simulate_event(KeyDownEvent {
keystroke: enter.clone(),
is_held: false,
prefer_character_input: false,
});
cx.simulate_event(KeyUpEvent { keystroke: enter });
assert!(root.read_with(cx, |root, _| root.screen == Screen::Settings));
}
/// The app opened on the config file at `path` (the file is read, or missing).
fn open_app(
cx: &mut TestAppContext,
path: &Path,
load: fn(&Path) -> Result<Config, arena_tracker_core::Error>,
) -> (VisualTestContext, Entity<RootView>) {
cx.update(gpui_kit::init);
let (window, root) = cx.update(|cx| {
let config = load(path).unwrap();
let api = Arc::new(RiotApi::new(String::new(), &config.region));
let setup = Setup {
tracker: Arc::new(Tracker::open(Path::new(":memory:"), Box::new(api.clone())).unwrap()),
riot_id: String::new(),
notice: None,
store: KeyStore::new(path.to_path_buf(), config, api),
};
gpui_kit::open_window(WindowOptions::default(), cx, |window, cx| {
cx.new(|cx| RootView::new(setup, false, window, cx))
})
.unwrap()
});
(VisualTestContext::from_window(window, cx), root)
}
#[gpui::test]
fn the_chosen_sort_is_saved_with_the_preferences_and_found_again_at_the_next_launch(
cx: &mut TestAppContext,
) {
let dir = TestDir::new("sort-76");
let path = dir.path().join("config.toml");
let (mut window, root) = open_app(cx, &path, Config::load_or_default);
let page = root.read_with(&window, |root, _| root.page.clone());
assert_eq!(
page.read_with(&window, |page, _| page.champion_sort()),
None
);
page.update(&mut window, |page, cx| {
page.choose_sort(ChampionSort::Name, cx)
});
let saved = std::fs::read_to_string(&path).unwrap();
assert!(saved.contains("champion_sort = \"name\""), "{saved}");
drop((window, root, page));
// The app opened again, from the file.
let (window, root) = open_app(cx, &path, Config::load);
let page = root.read_with(&window, |root, _| root.page.clone());
page.read_with(&window, |page, _| {
assert_eq!(page.champion_sort(), Some(ChampionSort::Name));
assert_eq!(page.home_filter(), arena_tracker_core::StateFilter::All);
});
}
+75 -18
View File
@@ -1,6 +1,6 @@
//! French display helpers shared by the page and the table.
use arena_tracker_core::{Account, ChampionState, SyncProgress};
use arena_tracker_core::{ChampionState, Date, SyncProgress};
/// Fixed decimals with a decimal comma: `1,96`.
pub fn decimal(value: f64, digits: usize) -> String {
@@ -16,6 +16,49 @@ pub fn stored(count: usize) -> String {
}
}
/// An integer in French format: groups of three digits separated by a narrow no-break space
/// (U+202F), as `toLocaleString('fr-FR')` writes it: `154 320`.
pub fn thousands(value: u64) -> String {
let digits = value.to_string();
let mut out = String::with_capacity(digits.len() + digits.len() / 3);
for (i, digit) in digits.chars().enumerate() {
if i > 0 && (digits.len() - i).is_multiple_of(3) {
out.push('\u{202f}');
}
out.push(digit);
}
out
}
/// A Placement as the sheet writes it: « 1ᵉʳ », « 2ᵉ », « 3ᵉ »…
pub fn ordinal(placement: u8) -> String {
match placement {
1 => "1ᵉʳ".into(),
n => format!("{n}ᵉ"),
}
}
/// An Attempt's rank, feminine: « 1ʳᵉ », « 2ᵉ »…
pub fn attempt_ordinal(attempt: usize) -> String {
match attempt {
1 => "1ʳᵉ".into(),
n => format!("{n}ᵉ"),
}
}
/// A day as the banner writes it: « 20 nov. », « 3 mai ».
pub fn short_date(date: Date) -> String {
const MONTHS: [&str; 12] = [
"janv.", "févr.", "mars", "avr.", "mai", "juin", "juil.", "août", "sept.", "oct.", "nov.",
"déc.",
];
let month = MONTHS
.get(usize::from(date.month).wrapping_sub(1))
.copied()
.unwrap_or_default();
format!("{} {month}", date.day)
}
pub fn state_label(state: Option<ChampionState>) -> &'static str {
match state {
Some(ChampionState::Completed) => "Validé",
@@ -29,10 +72,6 @@ pub const CLIENT_ABSENT: &str =
"Client League of Legends non détecté : affichage des données enregistrées.";
const INTERNAL_ERROR: &str = "Mise à jour impossible : erreur interne.";
pub fn riot_id(account: &Account) -> String {
format!("{}#{}", account.game_name, account.tag_line)
}
/// The discreet line under the Challenge tile.
pub fn official_note(official: u32) -> String {
format!("Progression officielle : {official}")
@@ -73,6 +112,37 @@ mod tests {
assert_eq!(decimal(2.0 / 3.0, 1), "0,7");
}
#[test]
fn thousands_are_grouped_with_a_narrow_no_break_space() {
assert_eq!(thousands(0), "0");
assert_eq!(thousands(999), "999");
assert_eq!(thousands(1_000), "1\u{202f}000");
assert_eq!(thousands(154_320), "154\u{202f}320");
assert_eq!(thousands(1_234_567), "1\u{202f}234\u{202f}567");
}
#[test]
fn placements_are_written_as_french_ordinals() {
assert_eq!(ordinal(1), "1ᵉʳ");
assert_eq!(ordinal(2), "2ᵉ");
assert_eq!(ordinal(8), "8ᵉ");
assert_eq!(attempt_ordinal(1), "1ʳᵉ");
assert_eq!(attempt_ordinal(3), "3ᵉ");
}
#[test]
fn short_dates_have_the_french_month_abbreviations() {
let date = |month, day| Date {
year: 2026,
month,
day,
};
assert_eq!(short_date(date(11, 20)), "20 nov.");
assert_eq!(short_date(date(2, 1)), "1 févr.");
assert_eq!(short_date(date(5, 3)), "3 mai");
assert_eq!(short_date(date(8, 31)), "31 août");
}
#[test]
fn stored_matches_are_pluralised() {
assert_eq!(stored(0), "Aucune Partie enregistrée");
@@ -88,19 +158,6 @@ mod tests {
assert_eq!(state_label(None), "");
}
fn account(name: &str, tag: &str) -> Account {
Account {
puuid: "p".into(),
game_name: name.into(),
tag_line: tag.into(),
}
}
#[test]
fn riot_ids_join_name_and_tag() {
assert_eq!(riot_id(&account("Joueur", "EUW")), "Joueur#EUW");
}
#[test]
fn official_progress_texts() {
assert_eq!(official_note(52), "Progression officielle : 52");
+283
View File
@@ -0,0 +1,283 @@
//! Arena Tracker's two palettes and the fonts registered once at startup.
use std::{borrow::Cow, rc::Rc};
use gpui_kit::component::{ActiveTheme as _, Theme};
use gpui_kit::*;
/// DirectWrite exposes Inter's text optical size as its own family.
const INTER: &str = "Inter Variable Text";
const UNBOUNDED: &str = "Unbounded";
/// Gold on the logo and on dark portrait overlays in either theme.
pub const LOGO_GOLD: u32 = 0xf5b83d;
const LIGHT_GOLD: u32 = 0xe3a21a;
/// Dark ink for text and icons on a solid gold fill.
pub const ON_GOLD: u32 = 0x161b2e;
/// Background of a card or statistics tile.
pub fn surface(theme: &Theme) -> Hsla {
theme.muted
}
/// Background of the home and champ select headers.
pub fn banner_band(theme: &Theme) -> Hsla {
theme.title_bar
}
/// Gold for text on a neutral surface, darker in the light theme.
pub fn gold_ink(theme: &Theme) -> Hsla {
theme.link
}
/// The gold glow around a card lifted under the pointer.
pub fn gold_glow(theme: &Theme) -> Hsla {
if theme.mode.is_dark() {
Hsla::from(rgb(LOGO_GOLD)).opacity(0.55)
} else {
Hsla::from(rgb(LIGHT_GOLD)).opacity(0.45)
}
}
/// The pale gold of a played champion's tick on the ring.
pub fn ring_played(theme: &Theme) -> Hsla {
gold_soft(theme)
}
/// The reference's soft gold: a played champion's tick, the light sweeping the window.
pub fn gold_soft(theme: &Theme) -> Hsla {
if theme.mode.is_dark() {
Hsla::from(rgb(LOGO_GOLD)).opacity(0.34)
} else {
Hsla::from(rgb(0xd4920e)).opacity(0.4)
}
}
/// The faint tick of a never played champion.
pub fn ring_never(theme: &Theme) -> Hsla {
theme.switch
}
struct HeadingFamily(SharedString);
impl Global for HeadingFamily {}
/// Builds a semibold heading with the family selected at startup.
pub fn heading(cx: &App) -> Div {
let family = cx
.try_global::<HeadingFamily>()
.map_or_else(|| &cx.theme().font_family, |heading| &heading.0);
div()
.font_family(family.clone())
.font_weight(FontWeight::SEMIBOLD)
}
/// Registers the embedded face and checks that the platform resolves the requested weight.
fn load_font(cx: &App, bytes: &'static [u8], family: &'static str, weight: FontWeight) -> bool {
let text = cx.text_system();
if let Err(error) = text.add_fonts(vec![Cow::Borrowed(bytes)]) {
eprintln!("Failed to load {family}: {error}");
return false;
}
// Naming a missing family incurs a fallback lookup on every text run.
let mut requested = font(family);
requested.weight = weight;
text.get_font_for_id(text.resolve_font(&requested)) == Some(requested)
}
/// Sets up the app palettes and fonts after `gpui_kit::init`.
pub fn init(cx: &mut App) {
init_with_heading_font(cx, include_bytes!("../assets/Unbounded-SemiBold.ttf"));
}
fn init_with_heading_font(cx: &mut App, heading_bytes: &'static [u8]) {
let inter = load_font(
cx,
include_bytes!("../assets/InterVariable.ttf"),
INTER,
FontWeight::NORMAL,
);
let heading = if load_font(cx, heading_bytes, UNBOUNDED, FontWeight::SEMIBOLD) {
UNBOUNDED.into()
} else {
cx.theme().font_family.clone()
};
cx.set_global(HeadingFamily(heading));
let theme = Theme::global_mut(cx);
for config in [&mut theme.light_theme, &mut theme.dark_theme] {
let config = Rc::make_mut(config);
if inter {
config.font_family = Some(INTER.into());
}
// Several kit tokens share each palette role. Register them on the saved configs
// so changing appearance reapplies the same palette as startup.
macro_rules! role {
($dark:expr, $light:expr => $($token:ident),+ ) => {{
let value = if config.mode.is_dark() { $dark } else { $light };
let hex = SharedString::from(format!("#{value:06x}"));
$(config.colors.$token = Some(hex.clone());)+
}};
}
role!(0x11152a, 0xeef0f7 => background);
role!(0x151a33, 0xe5e8f3 => title_bar, table_head, list_head);
role!(0x181e38, 0xffffff => table, list, popover, muted, button, list_even, table_even);
role!(0x20274a, 0xe4e8f4 => secondary, secondary_hover, accent, button_hover, table_hover,
list_hover, tab_bar, tab_bar_segmented);
role!(0x283053, 0xd2d7e9 => border, input, title_bar_border, window_border, table_row_border,
chart_grid, secondary_active, button_active);
role!(0xedeaf7, ON_GOLD => foreground, popover_foreground, accent_foreground, secondary_foreground);
role!(0x8b91b1, 0x596082 => muted_foreground, tab_foreground, table_head_foreground, scrollbar_thumb_hover);
role!(0x3a4166, 0xc5cbe0 => switch, scrollbar_thumb);
role!(LOGO_GOLD, LIGHT_GOLD => primary, tab_active, chart_1, chart_2, chart_3, chart_4, chart_5, slider_bar, progress_bar);
role!(LOGO_GOLD, 0x8f5d00 => link, link_hover, link_active, caret, warning, ring, drag_border, list_active_border, table_active_border);
role!(0xff7a7a, 0xc62f2f => danger);
role!(0x67e8f9, 0x11667b => info);
role!(0x4ade80, 0x196638 => success);
role!(ON_GOLD, ON_GOLD => primary_foreground, tab_active_foreground);
let gold = if config.mode.is_dark() {
LOGO_GOLD
} else {
LIGHT_GOLD
};
let tint = |alpha: u8| Some(SharedString::from(format!("#{gold:06x}{alpha:02x}")));
config.colors.selection = tint(0x38);
// The kit caps row highlights at 20% opacity.
config.colors.list_active = tint(0x33);
config.colors.table_active = config.colors.list_active.clone();
// Let the kit derive pressed and hovered primary buttons from our gold.
config.colors.primary_active = None;
config.colors.primary_hover = None;
}
Theme::change(theme.mode, None, cx);
}
#[cfg(test)]
mod tests {
use super::{INTER, UNBOUNDED, banner_band, gold_ink, heading, surface};
use gpui_kit::component::{Theme, ThemeMode};
use gpui_kit::{FontWeight, Hsla, Styled as _, TestAppContext, font, px};
// GPUI's usual test text system is a no-op. These tests exercise DirectWrite.
fn windows_context() -> TestAppContext {
let platform = gpui_kit::platform::current_platform(false);
TestAppContext::build_with_text_system(
gpui::TestDispatcher::new(0),
None,
platform.text_system(),
)
}
#[test]
fn unreadable_unbounded_keeps_the_system_heading_in_both_themes() {
windows_context().update(|cx| {
gpui_kit::init(cx);
let system = Theme::global(cx).font_family.clone();
super::init_with_heading_font(cx, b"invalid font file");
for mode in [ThemeMode::Dark, ThemeMode::Light] {
Theme::change(mode, None, cx);
assert_eq!(Theme::global(cx).font_family.as_str(), INTER);
assert_eq!(heading(cx).text_style().font_family.as_ref(), Some(&system));
}
});
}
#[track_caller]
fn assert_contrast(ink: Hsla, background: Hsla, minimum: f32) {
let [a, b] = [ink, background].map(|color| {
let rgb = color.to_rgb();
let [r, g, b] = [rgb.r, rgb.g, rgb.b].map(|v| {
if v <= 0.04045 {
v / 12.92
} else {
((v + 0.055) / 1.055).powf(2.4)
}
});
0.2126 * r + 0.7152 * g + 0.0722 * b
});
let ratio = (a.max(b) + 0.05) / (a.min(b) + 0.05);
assert!(
ratio >= minimum,
"{ink:?} on {background:?}: {ratio:.2}:1 < {minimum}:1"
);
}
#[test]
fn identity_fonts_and_colors_are_used_in_both_themes() {
let cx = windows_context();
cx.update(|cx| {
gpui_kit::init(cx);
super::init(cx);
assert_eq!(
Theme::global(cx).background,
if Theme::global(cx).mode.is_dark() {
gpui::rgb(0x11152a)
} else {
gpui::rgb(0xeef0f7)
}
.into()
);
for mode in [ThemeMode::Light, ThemeMode::Dark] {
Theme::change(mode, None, cx);
let theme = Theme::global(cx);
assert_eq!(theme.font_family.as_str(), INTER);
let style = heading(cx).text_style().clone();
let family = style.font_family.unwrap();
assert_eq!(family.as_str(), UNBOUNDED);
let mut face = font(family);
face.weight = style.font_weight.unwrap();
assert_eq!(face.weight, FontWeight::SEMIBOLD);
let text = cx.text_system();
assert_eq!(text.get_font_for_id(text.resolve_font(&face)), Some(face));
macro_rules! colors {
($dark:literal, $light:literal => $($token:ident),+) => {{
let expected: Hsla = gpui::rgb(if mode.is_dark() { $dark } else { $light }).into();
$(assert_eq!(theme.colors.$token, expected, "{} {mode:?}", stringify!($token));)+
}};
}
colors!(0x11152a, 0xeef0f7 => background);
colors!(0x151a33, 0xe5e8f3 => title_bar, table_head, list_head);
colors!(0x181e38, 0xffffff => table, list, popover, muted, button, list_even, table_even);
colors!(0x20274a, 0xe4e8f4 => secondary, secondary_hover, accent, button_hover, table_hover,
list_hover, tab_bar, tab_bar_segmented);
colors!(0x283053, 0xd2d7e9 => border, input, title_bar_border, window_border, table_row_border,
chart_grid, secondary_active, button_active);
colors!(0xedeaf7, 0x161b2e => foreground, popover_foreground, accent_foreground, secondary_foreground);
colors!(0x8b91b1, 0x596082 => muted_foreground, tab_foreground, table_head_foreground, scrollbar_thumb_hover);
colors!(0x3a4166, 0xc5cbe0 => switch, scrollbar_thumb);
colors!(0xf5b83d, 0xe3a21a => primary, tab_active, chart_1, chart_2, chart_3, chart_4, chart_5, slider_bar, progress_bar);
colors!(0xf5b83d, 0x8f5d00 => link, link_hover, link_active, warning, caret, ring, drag_border, list_active_border, table_active_border);
colors!(0xff7a7a, 0xc62f2f => danger);
colors!(0x67e8f9, 0x11667b => info);
colors!(0x4ade80, 0x196638 => success);
colors!(0x161b2e, 0x161b2e => primary_foreground, button_primary_foreground, tab_active_foreground);
let selection: Hsla = gpui::rgba(if mode.is_dark() { 0xf5b83d38 } else { 0xe3a21a38 }).into();
assert_eq!(theme.selection, selection);
// The kit caps selected rows at 20% opacity.
assert_eq!(theme.list_active, theme.primary.opacity(0.2));
assert_eq!(theme.table_active, theme.primary.opacity(0.2));
for bg in [theme.background, banner_band(theme), surface(theme), theme.secondary] {
for ink in [theme.foreground, theme.muted_foreground, gold_ink(theme)] {
assert_contrast(ink, bg, 4.5);
}
assert_contrast(theme.ring, bg, 3.);
}
assert_contrast(theme.primary_foreground, theme.primary, 4.5);
for ink in [theme.warning, theme.danger, theme.info, theme.success] {
// Alert paints its text over a 4% tint of the same colour.
assert_contrast(ink, theme.background.blend(ink.opacity(0.04)), 4.5);
}
}
// DirectWrite returns the nearest weight, so only a wider glyph proves a semibold face.
let text = cx.text_system();
let [regular, semibold] = [FontWeight::NORMAL, FontWeight::SEMIBOLD].map(|weight| {
let mut requested = font(INTER);
requested.weight = weight;
let id = text.resolve_font(&requested);
assert_eq!(text.get_font_for_id(id), Some(requested));
text.advance(id, px(14.), 'm').unwrap().width
});
assert!(semibold > regular, "{semibold:?} <= {regular:?}");
});
}
}
+174
View File
@@ -0,0 +1,174 @@
use gpui_kit::base::Button as BaseButton;
use gpui_kit::component::tooltip::Tooltip;
use gpui_kit::component::{ActiveTheme as _, Icon, IconName, Sizable as _, StyledExt as _};
use gpui_kit::prelude::FluentBuilder as _;
use gpui_kit::*;
use windows::Win32::{
Foundation::{LPARAM, WPARAM},
UI::WindowsAndMessaging::{PostMessageW, SC_CLOSE, SC_MAXIMIZE, SC_RESTORE, WM_SYSCOMMAND},
};
// Windows 11 caption metrics.
pub(crate) const BUTTON_WIDTH: Pixels = px(46.);
pub(crate) const BAR_HEIGHT: Pixels = px(32.);
// Six button widths plus room for the centered title, in narrow Windows Snap zones. A ready
// update adds a seventh in place of the title's left padding.
pub const MIN_WINDOW_SIZE: Size<Pixels> = size(px(380.), px(216.));
/// A flat button filling the bar's height, so that when the window is maximized the screen
/// edge (and for Fermer, the top-right corner) still hits it. Only hover and press show.
fn bar_button(id: &'static str, icon: IconName, label: &'static str, cx: &App) -> BaseButton {
BaseButton::new(id)
.w(BUTTON_WIDTH)
.h_full()
.flex_shrink_0()
// Always bordered, so the focus ring does not shift the icon.
.border_1()
.border_color(transparent_black())
.focus_visible(|style| style.border_color(cx.theme().ring))
.child(Icon::new(icon).small())
.accessibility_label(label)
.tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
}
fn neutral(button: BaseButton, cx: &App) -> BaseButton {
let theme = cx.theme();
button
.hover(|style| style.bg(theme.accent).text_color(theme.accent_foreground))
.active(|style| style.bg(theme.secondary_active))
}
fn action_button(
id: &'static str,
icon: IconName,
label: &'static str,
enabled: bool,
cx: &App,
) -> BaseButton {
let button = bar_button(id, icon, label, cx).disabled(!enabled);
if enabled {
neutral(button, cx)
} else {
button.text_color(cx.theme().muted_foreground)
}
}
pub fn refresh_button(enabled: bool, cx: &App) -> BaseButton {
action_button("refresh", IconName::RefreshCw, "Actualiser", enabled, cx)
}
pub fn settings_button(enabled: bool, cx: &App) -> BaseButton {
action_button("settings", IconName::Settings, "Paramètres", enabled, cx)
}
/// Shown only while an update is ready, in green so it is noticed.
pub fn update_button(enabled: bool, cx: &App) -> BaseButton {
let button = action_button(
"update",
IconName::ArrowUp,
"Mise à jour prête",
enabled,
cx,
);
if enabled {
button.text_color(cx.theme().success)
} else {
button
}
}
/// `update` is the update button, while one is ready.
pub fn title_bar(
refresh: BaseButton,
settings: BaseButton,
update: Option<BaseButton>,
window: &Window,
cx: &App,
) -> impl IntoElement {
let theme = cx.theme();
let balanced = update.is_some();
let (icon, label) = if window.is_maximized() {
(IconName::WindowRestore, "Restaurer")
} else {
(IconName::WindowMaximize, "Agrandir")
};
div()
.h_flex()
.w_full()
.h(BAR_HEIGHT)
.flex_shrink_0()
.bg(theme.title_bar)
.border_b_1()
.border_color(theme.title_bar_border)
.child(refresh)
.child(settings)
.children(update)
.child(
crate::theme::heading(cx)
.h_flex()
.h_full()
.flex_1()
.min_w_0()
// Without the update button, this padding balances the third button on the right.
.when(!balanced, |title| title.pl(BUTTON_WIDTH))
.justify_center()
.text_xs()
.window_control_area(WindowControlArea::Drag)
.child(Text::new("window-title".into(), "Arena Tracker".into())),
)
.child(
neutral(
bar_button("minimize", IconName::WindowMinimize, "Réduire", cx),
cx,
)
.on_click(|_, window, _| window.minimize_window()),
)
.child(
neutral(bar_button("maximize", icon, label, cx), cx)
.window_control_area(WindowControlArea::Max)
.on_click(|event, window, _| {
// GPUI's native hit target handles mouse clicks and Snap Layouts.
if !matches!(event, ClickEvent::Mouse(_)) {
toggle_maximize(window);
}
})
.on_a11y_action(AccessibleAction::Click, |_, window, _| {
toggle_maximize(window);
}),
)
.child(
// No window_control_area: the click stays in Rust and SC_CLOSE keeps Alt+F4
// semantics. Enter, Space and the accessibility Click (a synthesized mouse
// click) all reach on_click.
bar_button("close", IconName::WindowClose, "Fermer", cx)
// Windows' own close colours: the theme's danger pair is meant for text and
// gives a red-on-red icon in the dark theme.
.hover(|style| style.bg(rgb(0xC42B1C)).text_color(white()))
.active(|style| style.bg(rgba(0xC42B1CE6)).text_color(white()))
.on_click(|_, window, _| window_command(window, SC_CLOSE)),
)
}
fn toggle_maximize(window: &Window) {
let command = if window.is_maximized() {
SC_RESTORE
} else {
SC_MAXIMIZE
};
window_command(window, command);
}
fn window_command(window: &Window, command: u32) {
if let Some(hwnd) = crate::tray::window_hwnd(window) {
// Post so the native command runs after GPUI finishes dispatching this click.
let _ = unsafe {
PostMessageW(
Some(hwnd),
WM_SYSCOMMAND,
WPARAM(command as usize),
LPARAM(0),
)
};
}
}
+431
View File
@@ -0,0 +1,431 @@
//! Keeps the existing GPUI window alive while it is hidden in the Windows notification area.
use std::{
cell::Cell,
rc::{Rc, Weak},
};
use gpui_kit::base::async_util::Sender;
use gpui_kit::{App, Bounds, Pixels, PromptLevel, Subscription, Window};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
use windows::Win32::{
Foundation::{HINSTANCE, HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},
System::LibraryLoader::GetModuleHandleW,
UI::{
Shell::{
DefSubclassProc, GetWindowSubclass, NIF_ICON, NIF_INFO, NIF_MESSAGE, NIF_SHOWTIP,
NIF_TIP, NIIF_INFO, NIM_ADD, NIM_DELETE, NIM_MODIFY, NIM_SETFOCUS, NIM_SETVERSION,
NIN_SELECT, NOTIFYICON_VERSION_4, NOTIFYICONDATAW, NOTIFYICONIDENTIFIER,
RemoveWindowSubclass, SetWindowSubclass, Shell_NotifyIconGetRect, Shell_NotifyIconW,
},
WindowsAndMessaging::*,
},
};
use windows::core::{PCWSTR, w};
const TRAY_SUBCLASS: usize = 0;
pub(crate) const TRAY_MESSAGE: u32 = WM_APP + 1;
const ICON_ID: u32 = 1;
const OPEN: u32 = 1;
const QUIT: u32 = 2;
const NIN_KEYSELECT: u32 = NIN_SELECT | 1;
pub const UNAVAILABLE: &str =
"La zone de notification est indisponible. La fenêtre reste accessible.";
const NOTICE_TITLE: &str = "Arena Tracker reste ouvert";
const NOTICE_TEXT: &str = "L’application continue dans la zone de notification. Cliquez sur \
son icône pour la rouvrir, ou faites un clic droit pour la quitter.";
pub(crate) fn window_hwnd(window: &Window) -> Option<HWND> {
let RawWindowHandle::Win32(handle) = HasWindowHandle::window_handle(window).ok()?.as_raw()
else {
return None;
};
Some(HWND(handle.hwnd.get() as _))
}
pub struct Tray {
hwnd: HWND,
taskbar_created: u32,
enabled: Cell<bool>,
hidden: Cell<bool>,
/// Until the one-time notice is shown: told when it is, so that it can be recorded.
notice: Cell<Option<Sender<()>>>,
_quit: Subscription,
}
impl Tray {
pub fn install_saved(
window: &mut Window,
enabled: bool,
notice: Option<Sender<()>>,
cx: &mut App,
) -> Option<Rc<Self>> {
if !enabled {
return None;
}
let tray = Self::install(window, notice, cx);
if tray.is_none() {
window.defer(cx, |window, cx| {
drop(window.prompt(PromptLevel::Warning, UNAVAILABLE, None, &["OK"], cx));
});
}
tray
}
pub fn install(window: &Window, notice: Option<Sender<()>>, cx: &App) -> Option<Rc<Self>> {
let hwnd = window_hwnd(window)?;
let taskbar_created = unsafe { RegisterWindowMessageW(w!("TaskbarCreated")) };
if taskbar_created == 0 {
return None;
}
let tray = Rc::new_cyclic(|weak: &Weak<Self>| {
let weak = weak.clone();
let quit = cx.on_app_quit(move |_| {
if let Some(tray) = weak.upgrade() {
tray.remove_icon();
}
async {}
});
Self {
hwnd,
taskbar_created,
enabled: Cell::new(true),
hidden: Cell::new(false),
notice: Cell::new(notice),
_quit: quit,
}
});
// The subclass owns one reference until WM_NCDESTROY. This window belongs to the UI thread.
let data = Rc::into_raw(tray.clone());
if !unsafe { SetWindowSubclass(hwnd, Some(window_proc), TRAY_SUBCLASS, data as usize) }
.as_bool()
{
drop(unsafe { Rc::from_raw(data) });
return None;
}
Some(tray)
}
pub fn uninstall(self: Rc<Self>) {
self.enabled.set(false);
let data = Rc::as_ptr(&self);
if unsafe { RemoveWindowSubclass(self.hwnd, Some(window_proc), TRAY_SUBCLASS) }.as_bool() {
drop(unsafe { Rc::from_raw(data) });
}
}
fn icon_data(&self) -> NOTIFYICONDATAW {
NOTIFYICONDATAW {
cbSize: size_of::<NOTIFYICONDATAW>() as u32,
hWnd: self.hwnd,
uID: ICON_ID,
..Default::default()
}
}
fn add_icon(&self) -> bool {
unsafe {
let icon = GetModuleHandleW(None)
.and_then(|module| LoadIconW(Some(HINSTANCE(module.0)), PCWSTR(1 as _)))
.or_else(|_| LoadIconW(None, IDI_APPLICATION));
let Ok(icon) = icon else { return false };
let mut data = NOTIFYICONDATAW {
uFlags: NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP,
uCallbackMessage: TRAY_MESSAGE,
hIcon: icon,
..self.icon_data()
};
fill(&mut data.szTip, "Arena Tracker");
if !Shell_NotifyIconW(NIM_ADD, &data).as_bool() {
return false;
}
data.Anonymous.uVersion = NOTIFYICON_VERSION_4;
if !Shell_NotifyIconW(NIM_SETVERSION, &data).as_bool() {
let _ = Shell_NotifyIconW(NIM_DELETE, &data);
return false;
}
true
}
}
/// Says once, as a Windows notification, that closing kept the app running here.
fn show_notice(&self) {
let Some(shown) = self.notice.take() else {
return;
};
let mut data = NOTIFYICONDATAW {
uFlags: NIF_INFO,
dwInfoFlags: NIIF_INFO,
..self.icon_data()
};
fill(&mut data.szInfoTitle, NOTICE_TITLE);
fill(&mut data.szInfo, NOTICE_TEXT);
if unsafe { Shell_NotifyIconW(NIM_MODIFY, &data) }.as_bool() {
// Recorded by the settings form, outside this window procedure.
let _ = shown.try_send(());
} else {
self.notice.set(Some(shown));
}
}
fn remove_icon(&self) {
if self.hidden.replace(false) {
let _ = unsafe { Shell_NotifyIconW(NIM_DELETE, &self.icon_data()) };
}
}
fn open(&self) {
self.remove_icon();
foreground(self.hwnd);
}
fn report_unavailable(&self) {
let message: Vec<_> = UNAVAILABLE.encode_utf16().chain([0]).collect();
unsafe {
MessageBoxW(
Some(self.hwnd),
PCWSTR(message.as_ptr()),
w!("Arena Tracker"),
MB_OK | MB_ICONWARNING,
);
}
}
fn show_menu(&self) {
unsafe {
let Ok(menu) = CreatePopupMenu() else { return };
let result = (|| {
AppendMenuW(menu, MF_STRING, OPEN as usize, w!("Ouvrir"))?;
AppendMenuW(menu, MF_STRING, QUIT as usize, w!("Quitter"))?;
let icon = NOTIFYICONIDENTIFIER {
cbSize: size_of::<NOTIFYICONIDENTIFIER>() as u32,
hWnd: self.hwnd,
uID: ICON_ID,
..Default::default()
};
let point = match Shell_NotifyIconGetRect(&icon) {
Ok(rect) => POINT {
x: rect.left,
y: rect.top,
},
Err(_) => {
let mut point = POINT::default();
GetCursorPos(&mut point)?;
point
}
};
let _ = SetForegroundWindow(self.hwnd);
Ok::<_, windows::core::Error>(
TrackPopupMenu(
menu,
TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON,
point.x,
point.y,
None,
self.hwnd,
None,
)
.0 as u32,
)
})();
let _ = DestroyMenu(menu);
let _ = PostMessageW(Some(self.hwnd), WM_NULL, WPARAM(0), LPARAM(0));
match result {
Ok(OPEN) => self.open(),
Ok(QUIT) => {
// Destroying the window takes GPUI's normal exit path without another close request.
let _ = DestroyWindow(self.hwnd);
}
_ if self.hidden.get() => {
let _ = Shell_NotifyIconW(NIM_SETFOCUS, &self.icon_data());
}
_ => {}
}
}
}
}
/// Copies `text` into a fixed Win32 string field, truncated, always ending with a NUL.
fn fill(field: &mut [u16], text: &str) {
let room = field.len() - 1;
for (unit, letter) in field[..room].iter_mut().zip(text.encode_utf16()) {
*unit = letter;
}
}
/// The window's tray, while it is installed.
fn installed_tray(hwnd: HWND) -> Option<Rc<Tray>> {
let mut data = 0;
unsafe { GetWindowSubclass(hwnd, Some(window_proc), TRAY_SUBCLASS, Some(&mut data)) }
.as_bool()
.then(|| unsafe { retain(data as *const Tray) })
}
/// Leaves a window opened hidden at logon (`show: false`) in the notification
/// area, without the one-time notice, or minimized in the taskbar when the icon cannot be added:
/// no tray, or a taskbar not created yet. Never running with neither icon nor window.
pub fn start_hidden(window: &Window, bounds: Bounds<Pixels>) {
let Some(hwnd) = window_hwnd(window) else {
// Nothing to hide it with: shown and placed by GPUI, rather than out of reach.
window.activate_window();
return;
};
let in_tray = installed_tray(hwnd).is_some_and(|tray| {
let added = tray.add_icon();
tray.hidden.set(added);
added
});
let command = if in_tray { SW_HIDE } else { SW_SHOWMINNOACTIVE };
let placed =
normal_placement(hwnd, bounds, window.scale_factor()).is_some_and(|mut placement| {
placement.showCmd = command.0 as u32;
unsafe { SetWindowPlacement(hwnd, &placement) }.is_ok()
});
if !placed && !in_tray {
let _ = unsafe { ShowWindow(hwnd, SW_SHOWMINNOACTIVE) };
}
}
/// GPUI places a window opened hidden only when it activates it, which the notification area
/// and the champ select never ask for: its normal place is `bounds` here, set as GPUI sets it
/// (`retrieve_window_placement`), with the frame around the client area split on both sides.
fn normal_placement(hwnd: HWND, bounds: Bounds<Pixels>, scale: f32) -> Option<WINDOWPLACEMENT> {
let mut placement = WINDOWPLACEMENT {
length: size_of::<WINDOWPLACEMENT>() as u32,
..Default::default()
};
let (mut frame, mut client) = (RECT::default(), RECT::default());
unsafe {
GetWindowPlacement(hwnd, &mut placement).ok()?;
GetWindowRect(hwnd, &mut frame).ok()?;
GetClientRect(hwnd, &mut client).ok()?;
}
let width = (frame.right - frame.left) - (client.right - client.left);
let height = (frame.bottom - frame.top) - (client.bottom - client.top);
let bounds = bounds.to_device_pixels(scale);
placement.rcNormalPosition = RECT {
left: bounds.left().0 - width / 2,
top: bounds.top().0 - height / 2,
right: bounds.right().0 + (width - width / 2),
bottom: bounds.bottom().0 + (height - height / 2),
};
Some(placement)
}
pub fn reopen(hwnd: HWND) {
match installed_tray(hwnd) {
Some(tray) => tray.open(),
None => foreground(hwnd),
}
}
/// Brings a minimized window, or one hidden in the notification area, back above the other
/// windows while the foreground app keeps the keyboard. A window already shown is left alone.
pub fn reveal(hwnd: HWND) {
unsafe {
let iconic = IsIconic(hwnd).as_bool();
if IsWindowVisible(hwnd).as_bool() && !iconic {
return;
}
if let Some(tray) = installed_tray(hwnd) {
tray.remove_icon();
}
if iconic {
// shortcut: a window minimized from maximized may come back at its normal size, as no
// show command maximizes without activating; revisit if the Windows check shows it.
let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);
}
let _ = SetWindowPos(
hwnd,
Some(HWND_TOP),
0,
0,
0,
0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_SHOWWINDOW,
);
}
}
/// A native call can destroy the window and release the subclass's reference, so take our own.
unsafe fn retain(data: *const Tray) -> Rc<Tray> {
unsafe {
Rc::increment_strong_count(data);
Rc::from_raw(data)
}
}
fn foreground(hwnd: HWND) {
unsafe {
let command = if IsIconic(hwnd).as_bool() {
SW_RESTORE
} else {
SW_SHOW
};
let _ = ShowWindow(hwnd, command);
let _ = SetForegroundWindow(hwnd);
}
}
unsafe extern "system" fn window_proc(
hwnd: HWND,
message: u32,
wparam: WPARAM,
lparam: LPARAM,
id: usize,
data: usize,
) -> LRESULT {
let data = data as *const Tray;
// Native calls can dispatch nested messages, including destruction. Keep our own reference
// for the messages we handle and leave the high-frequency messages on the default path.
let taskbar_created = unsafe { (*data).taskbar_created };
if !matches!(
message,
WM_CLOSE | WM_ENDSESSION | WM_NCDESTROY | TRAY_MESSAGE
) && message != taskbar_created
{
return unsafe { DefSubclassProc(hwnd, message, wparam, lparam) };
}
let tray = unsafe { retain(data) };
match message {
WM_CLOSE if tray.enabled.get() => {
if !tray.hidden.get() {
if tray.add_icon() {
tray.hidden.set(true);
let _ = unsafe { ShowWindow(hwnd, SW_HIDE) };
tray.show_notice();
} else {
tray.report_unavailable();
}
}
return LRESULT(0);
}
TRAY_MESSAGE => {
if tray.hidden.get() && (lparam.0 as u32 >> 16) == ICON_ID {
match lparam.0 as u32 & 0xffff {
WM_CONTEXTMENU => tray.show_menu(),
NIN_SELECT | NIN_KEYSELECT => tray.open(),
_ => {}
}
}
return LRESULT(0);
}
WM_ENDSESSION if wparam.0 != 0 => tray.remove_icon(),
WM_NCDESTROY => unsafe {
tray.remove_icon();
let _ = RemoveWindowSubclass(hwnd, Some(window_proc), id);
drop(Rc::from_raw(data));
},
message if message == taskbar_created && tray.hidden.get() => {
// Explorer discards notification icons when it recreates the taskbar.
if !tray.add_icon() {
tray.open();
tray.report_unavailable();
}
return LRESULT(0);
}
_ => {}
}
unsafe { DefSubclassProc(hwnd, message, wparam, lparam) }
}
+239 -142
View File
@@ -1,31 +1,47 @@
//! Background threads: following the game client, refreshing and computing statistics.
//! They talk to the page through `Msg`.
//! Background threads: following the game client, refreshing, computing statistics and
//! downloading updates. They talk to the page through `Msg`, and to the settings through
//! `UpdateChecked`.
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::thread;
use std::time::{SystemTime, UNIX_EPOCH};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arena_tracker_core::{Scope, Statistics, Status, SyncProgress, Tracker};
use arena_tracker_core::{
ChampSelect, ClientEvent, Scope, Statistics, Status, SyncProgress, Tracker, UpdateChannel,
};
use gpui_kit::base::async_util::Sender;
/// The signed-in Riot ID and its pick, or none outside an Arena champ select.
pub type LiveChampSelect = Option<(String, ChampSelect)>;
pub enum Msg {
ChampSelect(LiveChampSelect),
/// A sync is fetching Matches.
Progress(SyncProgress),
/// The champion catalog and portraits were refreshed.
/// The champion catalog or portraits changed on disk: the statistics carry them.
Champions,
/// A follower round ended; `reload` when the stored data may have changed.
Round { status: Status, reload: bool },
Round {
status: Status,
reload: bool,
matches: Vec<arena_tracker_core::FollowedMatch>,
},
/// A refresh ended.
Refreshed(Status),
/// Statistics for a requested scope were computed.
/// Statistics for a requested scope were computed, with those of the home's own scope when it
/// differs (`home`: none when it does not).
Statistics {
generation: u64,
stats: Result<Statistics, String>,
// Boxed: the enum is as large as its largest message.
home: Option<Box<Result<Statistics, String>>>,
stored: Option<usize>,
},
/// A worker thread panicked.
Crashed,
/// The refresh worker panicked.
RefreshCrashed,
}
/// At most one job at a time. A request made while one runs is served once, when it reports back.
@@ -62,6 +78,49 @@ impl RefreshGate {
}
}
/// While cards and splashes keep arriving, how often the page is told: each time, it reloads its
/// statistics to show them.
const ART_TOLD_EVERY: Duration = Duration::from_secs(1);
/// Spaces out what saved images cause: the first save is told at once, the next ones when
/// `every` has passed since the last message, and one still untold when the pass ends is told
/// then. No timer: each attempt of the pass, saved or not, and its end are what tell.
struct Throttle {
every: Duration,
last_told: Option<Instant>,
untold: bool,
}
impl Throttle {
fn new(every: Duration) -> Throttle {
Throttle {
every,
last_told: None,
untold: false,
}
}
/// An attempt ended at `now`, with an image saved or not: true when the page must be told
/// now, as a save is untold and `every` has passed since the last message.
fn attempted(&mut self, saved: bool, now: Instant) -> bool {
self.untold |= saved;
let due = self
.last_told
.is_none_or(|last| now.duration_since(last) >= self.every);
if self.untold && due {
self.last_told = Some(now);
self.untold = false;
return true;
}
false
}
/// The pass ended: true when a save is still untold.
fn finished(self) -> bool {
self.untold
}
}
fn now_ms() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
@@ -76,7 +135,6 @@ const THREAD_PRIORITY_BELOW_NORMAL: i32 = -1;
unsafe extern "system" {
fn GetCurrentThread() -> *mut core::ffi::c_void;
fn SetThreadPriority(thread: *mut core::ffi::c_void, priority: i32) -> i32;
#[cfg(test)]
fn GetThreadPriority(thread: *mut core::ffi::c_void) -> i32;
}
@@ -91,47 +149,169 @@ fn lower_priority() {
}
}
/// Below-normal priority for the calling thread until dropped, which gives the previous one back:
/// for short work on a thread of GPUI's pool, which other tasks share (decoding a splash).
pub(crate) struct BelowNormal {
#[cfg(windows)]
previous: i32,
}
impl BelowNormal {
pub(crate) fn enter() -> BelowNormal {
#[cfg(windows)]
{
let previous = unsafe { GetThreadPriority(GetCurrentThread()) };
lower_priority();
BelowNormal { previous }
}
#[cfg(not(windows))]
BelowNormal {}
}
}
impl Drop for BelowNormal {
fn drop(&mut self) {
#[cfg(windows)]
unsafe {
SetThreadPriority(GetCurrentThread(), self.previous);
}
}
}
/// Runs `body` on its own thread; a panic is reported instead of leaving the page waiting.
fn spawn_guarded(tx: Sender<Msg>, body: impl FnOnce(&Sender<Msg>) + Send + 'static) {
fn spawn_guarded<T: Send + 'static>(
tx: Sender<T>,
on_panic: T,
body: impl FnOnce(&Sender<T>) + Send + 'static,
) {
thread::spawn(move || {
lower_priority();
if catch_unwind(AssertUnwindSafe(|| body(&tx))).is_err() {
let _ = tx.try_send(Msg::Crashed);
let _ = tx.try_send(on_panic);
}
});
}
/// Keeps the active Account up to date for as long as the app runs: one thread, rounds of
/// `follow_client` separated by `wait_for_client`. `fallback_riot_id` is the configured Riot ID.
/// Keeps the active Account up to date for as long as the app runs: event-driven follower rounds
/// and a live champ select subscription. Each wake reads the client once and shares that read with
/// both. `fallback_riot_id` is the configured Riot ID.
/// The champion catalog and portraits are fetched on another thread, so a first launch's
/// import never waits for them.
pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sender<Msg>) {
let champions = tracker.clone();
spawn_guarded(tx.clone(), move |tx| {
let _ = champions.refresh_champions();
let _ = tx.try_send(Msg::Champions);
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
let mut throttle = Throttle::new(ART_TOLD_EVERY);
let notify = || {
let _ = tx.try_send(Msg::Champions);
};
let _ = champions.refresh_champion_art(notify, &mut |saved| {
if throttle.attempted(saved, Instant::now()) {
notify();
}
});
if throttle.finished() {
notify();
}
});
spawn_guarded(tx, move |tx| {
// Coalesce history updates while Riot is busy; the WebSocket keeps delivering live picks.
let (wake, rounds) = std::sync::mpsc::sync_channel(1);
let latest = Arc::new(std::sync::Mutex::new(None));
let history = tracker.clone();
let history_latest = latest.clone();
spawn_guarded(tx.clone(), Msg::Crashed, move |tx| {
let fallback = Some(fallback_riot_id.as_str()).filter(|id| !id.trim().is_empty());
let mut first = true;
loop {
let changed = tracker.follow_client(now_ms(), fallback, &mut |progress| {
for () in rounds {
// Another wake landed while this one's round ran: its read is newer and already
// queued, so this round has nothing of its own to do.
let Some(snapshot) = history_latest.lock().unwrap().take() else {
continue;
};
let mut progress = |progress| {
let _ = tx.try_send(Msg::Progress(progress));
});
let status = tracker.status();
let _ = tx.try_send(Msg::Round {
status,
reload: changed || first,
});
};
let mut matches = Vec::new();
let changed = history.follow_client_with(
now_ms(),
fallback,
&snapshot,
&mut progress,
&mut |event| matches.push(event),
);
if tx
.try_send(Msg::Round {
status: history.status(),
reload: changed || first,
matches,
})
.is_err()
{
break;
}
first = false;
tracker.wait_for_client();
}
});
spawn_guarded(tx, Msg::Crashed, move |tx| {
let mut previous = None;
let mut snapshot = tracker.client_snapshot();
let mut needs_snapshot = true;
while !tx.is_closed() {
// The follower round uses the same read as the live champ select: one gameflow
// request per wake, and none for a champ select event.
if needs_snapshot {
*latest.lock().unwrap() = Some(snapshot.clone());
if matches!(
wake.try_send(()),
Err(std::sync::mpsc::TrySendError::Disconnected(()))
) {
break;
}
}
match tracker.champ_select_with(&snapshot) {
Ok(champ_select) if champ_select != previous => {
if tx.try_send(Msg::ChampSelect(champ_select.clone())).is_err() {
break;
}
previous = champ_select;
}
Ok(_) => {}
// A failed read is not the champ select ending: keep what the page shows.
Err(_) => {}
}
// A champ select event costs no request once a read has answered: only a gameflow
// event, or a read that failed, needs a fresh one. The gameflow event that starts
// the champ select is that event.
needs_snapshot =
tracker.wait_for_client() == ClientEvent::Other || snapshot.gameflow.is_err();
if needs_snapshot {
snapshot = tracker.client_snapshot();
}
}
});
}
/// What an update check for `channel` ended with: the version kept ready, `None` when there is
/// no newer one, or why the check failed.
pub struct UpdateChecked {
pub channel: UpdateChannel,
pub result: Result<Option<String>, String>,
}
/// Downloads and authenticates the newest release of `channel`, as one below-normal thread.
pub fn spawn_update_check(channel: UpdateChannel, tx: Sender<UpdateChecked>) {
let crashed = UpdateChecked {
channel,
result: Err("la vérification s’est interrompue".into()),
};
spawn_guarded(tx, crashed, move |tx| {
let result = crate::release::download_update(channel);
let _ = tx.try_send(UpdateChecked { channel, result });
});
}
/// The refresh button: one sync of the Account being kept up to date.
pub fn spawn_refresh(tracker: Arc<Tracker>, tx: Sender<Msg>) {
spawn_guarded(tx, move |tx| {
spawn_guarded(tx, Msg::RefreshCrashed, move |tx| {
// A failure is recorded in the status, which the page shows as a banner.
let _ = tracker.refresh(&mut |progress| {
let _ = tx.try_send(Msg::Progress(progress));
@@ -140,143 +320,60 @@ pub fn spawn_refresh(tracker: Arc<Tracker>, tx: Sender<Msg>) {
});
}
/// Computes the statistics of `puuid` for `scope` on a below-normal worker.
#[cfg(test)]
thread_local! {
/// The scopes computed on this thread, to check what a change makes the page compute.
pub static COMPUTED: std::cell::RefCell<Vec<Scope>> = const { std::cell::RefCell::new(Vec::new()) };
}
/// The statistics of `puuid` for `scope`, with the error as the page shows it.
pub fn compute_statistics(
tracker: &Tracker,
puuid: &str,
scope: &Scope,
) -> Result<Statistics, String> {
#[cfg(test)]
COMPUTED.with(|computed| computed.borrow_mut().push(scope.clone()));
tracker
.statistics(puuid, scope)
.map_err(|e| format!("Statistiques indisponibles : {e}"))
}
/// Computes the statistics of `puuid` for `scope`, and for `home_scope` when it differs, on a
/// below-normal worker: one job, so the page has one result to wait for.
pub fn spawn_statistics(
tracker: Arc<Tracker>,
puuid: String,
scope: Scope,
home_scope: Option<Scope>,
generation: u64,
tx: Sender<Msg>,
) {
spawn_guarded(tx, move |tx| {
spawn_guarded(tx, Msg::Crashed, move |tx| {
// A panic is reported as this job's result, not as `Crashed`: the page's statistics job
// must end with a result whatever happens, and a crash banner is for the other workers.
let (stats, stored) = catch_unwind(AssertUnwindSafe(|| {
let stats = tracker
.statistics(&puuid, &scope)
.map_err(|e| format!("Statistiques indisponibles : {e}"));
(stats, tracker.match_count(&puuid).ok())
let home_has_own_scope = home_scope.is_some();
let (stats, home, stored) = catch_unwind(AssertUnwindSafe(|| {
let stats = compute_statistics(&tracker, &puuid, &scope);
let home = home_scope.map(|home| Box::new(compute_statistics(&tracker, &puuid, &home)));
(stats, home, tracker.match_count(&puuid).ok())
}))
.unwrap_or_else(|_| {
let error = || "Statistiques indisponibles : erreur interne".to_string();
(
Err("Statistiques indisponibles : erreur interne".into()),
Err(error()),
home_has_own_scope.then(|| Box::new(Err(error()))),
None,
)
});
let _ = tx.try_send(Msg::Statistics {
generation,
stats,
home,
stored,
});
});
}
#[cfg(test)]
mod tests {
use std::path::Path;
use arena_tracker_core::{RiotApi, SeasonScope};
use gpui_kit::base::async_util::unbounded;
use super::*;
#[test]
fn guarded_workers_deliver_messages_and_report_panics() {
let (tx, rx) = unbounded();
spawn_guarded(tx.clone(), |tx| {
let _ = tx.try_send(Msg::Champions);
});
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Champions)));
spawn_guarded(tx, |_| panic!("worker panic"));
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Crashed)));
assert!(gpui_kit::block_on(rx.recv()).is_err());
}
#[test]
fn statistics_workers_deliver_the_generation_count_and_errors() {
let tracker = Arc::new(
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
);
let (tx, rx) = unbounded();
spawn_statistics(
tracker.clone(),
"account".into(),
Scope {
season: SeasonScope::AllSeasons,
format: None,
},
42,
tx.clone(),
);
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::Statistics {
generation: 42,
stats: Ok(stats),
stored: Some(0),
}) if stats.rows.is_empty() && stats.challenge.is_none()
));
spawn_statistics(
tracker,
"account".into(),
Scope {
season: SeasonScope::Season("missing".into()),
format: None,
},
43,
tx,
);
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::Statistics {
generation: 43,
stats: Err(error),
stored: Some(0),
}) if error.starts_with("Statistiques indisponibles : ")
));
}
#[test]
fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() {
let mut gate = RefreshGate::default();
assert!(gate.request());
assert!(gate.running());
assert!(!gate.request());
assert!(!gate.request());
// The running one ends: one queued refresh starts, however many were asked.
assert!(gate.finished());
assert!(gate.running());
assert!(!gate.finished());
assert!(!gate.running());
assert!(gate.request());
}
#[test]
fn a_crash_forgets_the_queue() {
let mut gate = RefreshGate::default();
assert!(gate.request());
assert!(!gate.request());
gate.reset();
assert!(!gate.running());
assert!(!gate.finished());
}
#[cfg(windows)]
#[test]
fn guarded_threads_run_below_normal_priority() {
let (tx, _rx) = unbounded();
let (priority_tx, priority_rx) = std::sync::mpsc::channel();
spawn_guarded(tx, move |_| {
let priority = unsafe { GetThreadPriority(GetCurrentThread()) };
priority_tx.send(priority).unwrap();
});
assert_eq!(priority_rx.recv().unwrap(), THREAD_PRIORITY_BELOW_NORMAL);
}
}
mod tests;
+190
View File
@@ -0,0 +1,190 @@
use std::path::Path;
use arena_tracker_core::{RiotApi, SeasonScope};
use gpui_kit::base::async_util::unbounded;
use super::*;
#[test]
fn guarded_workers_deliver_messages_and_report_panics() {
let (tx, rx) = unbounded();
spawn_guarded(tx.clone(), Msg::Crashed, |tx| {
let _ = tx.try_send(Msg::Champions);
});
assert!(matches!(gpui_kit::block_on(rx.recv()), Ok(Msg::Champions)));
spawn_guarded(tx, Msg::RefreshCrashed, |_| panic!("worker panic"));
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::RefreshCrashed)
));
assert!(gpui_kit::block_on(rx.recv()).is_err());
}
#[test]
fn statistics_workers_deliver_the_generation_count_and_errors() {
let tracker = Arc::new(
Tracker::open(
Path::new(":memory:"),
Box::new(RiotApi::new(String::new(), "europe")),
)
.unwrap()
.with_seasons(Vec::new()),
);
let (tx, rx) = unbounded();
spawn_statistics(
tracker.clone(),
"account".into(),
Scope {
season: SeasonScope::AllSeasons,
format: None,
},
None,
42,
tx.clone(),
);
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::Statistics {
generation: 42,
stats: Ok(stats),
home: None,
stored: Some(0),
}) if stats.rows.is_empty() && stats.challenge.is_none()
));
spawn_statistics(
tracker.clone(),
"account".into(),
Scope {
season: SeasonScope::Season("missing".into()),
format: None,
},
None,
43,
tx.clone(),
);
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::Statistics {
generation: 43,
stats: Err(error),
home: None,
stored: Some(0),
}) if error.starts_with("Statistiques indisponibles : ")
));
// A home scope of its own is computed by the same job, and fails on its own.
let missing = |season: &str| Scope {
season: SeasonScope::Season(season.into()),
format: None,
};
spawn_statistics(
tracker,
"account".into(),
Scope {
season: SeasonScope::AllSeasons,
format: None,
},
Some(missing("missing")),
44,
tx,
);
assert!(matches!(
gpui_kit::block_on(rx.recv()),
Ok(Msg::Statistics {
generation: 44,
stats: Ok(_),
home: Some(home),
stored: Some(0),
}) if home.is_err()
));
}
#[test]
fn saved_art_is_told_once_a_second_after_any_attempt_and_the_last_ones_at_the_end() {
let start = Instant::now();
let at = |ms: u64| start + Duration::from_millis(ms);
let mut throttle = Throttle::new(Duration::from_secs(1));
assert!(
throttle.attempted(true, at(0)),
"the first save is told at once"
);
assert!(!throttle.attempted(true, at(300)));
assert!(!throttle.attempted(true, at(999)));
assert!(throttle.attempted(true, at(1000)));
assert!(!throttle.attempted(true, at(1500)));
// A failed attempt tells nothing before the second is over, then the save at 1.5 s is.
assert!(!throttle.attempted(false, at(1900)));
assert!(throttle.attempted(false, at(2000)));
assert!(
!throttle.attempted(false, at(5000)),
"nothing is untold any more"
);
assert!(!throttle.finished());
// The last save was told late or never: the end of the pass tells it.
let mut throttle = Throttle::new(Duration::from_secs(1));
assert!(throttle.attempted(true, at(0)));
assert!(!throttle.attempted(true, at(10)));
assert!(!throttle.attempted(false, at(20)));
assert!(throttle.finished());
// Nothing saved, nothing told.
let mut throttle = Throttle::new(Duration::from_secs(1));
assert!(!throttle.attempted(false, at(0)));
assert!(!throttle.attempted(false, at(5000)));
assert!(!throttle.finished());
}
#[test]
fn a_request_while_a_refresh_runs_waits_for_it_and_is_served_once() {
let mut gate = RefreshGate::default();
assert!(gate.request());
assert!(gate.running());
assert!(!gate.request());
assert!(!gate.request());
// The running one ends: one queued refresh starts, however many were asked.
assert!(gate.finished());
assert!(gate.running());
assert!(!gate.finished());
assert!(!gate.running());
assert!(gate.request());
}
#[test]
fn a_crash_forgets_the_queue() {
let mut gate = RefreshGate::default();
assert!(gate.request());
assert!(!gate.request());
gate.reset();
assert!(!gate.running());
assert!(!gate.finished());
}
#[cfg(windows)]
#[test]
fn guarded_threads_run_below_normal_priority() {
let (tx, _rx) = unbounded();
let (priority_tx, priority_rx) = std::sync::mpsc::channel();
spawn_guarded(tx, Msg::Crashed, move |_| {
let priority = unsafe { GetThreadPriority(GetCurrentThread()) };
priority_tx.send(priority).unwrap();
});
assert_eq!(priority_rx.recv().unwrap(), THREAD_PRIORITY_BELOW_NORMAL);
}
#[test]
fn below_normal_lasts_until_dropped() {
std::thread::spawn(|| {
let priority = || unsafe { GetThreadPriority(GetCurrentThread()) };
let before = priority();
assert_ne!(before, THREAD_PRIORITY_BELOW_NORMAL);
let below = super::BelowNormal::enter();
assert_eq!(priority(), THREAD_PRIORITY_BELOW_NORMAL);
drop(below);
assert_eq!(priority(), before);
})
.join()
.unwrap();
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 473 B

+2
View File
@@ -6,6 +6,8 @@ version.workspace = true
[dependencies]
base64 = { version = "0.23.1", default-features = false, features = ["std"] }
image = { version = "0.25", default-features = false, features = ["jpeg"] }
ring = "0.17.14"
rusqlite = { version = "0.43.0", features = ["bundled"] }
rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "tls12"] }
serde = { version = "1.0.229", features = ["derive"] }
+324
View File
@@ -0,0 +1,324 @@
//! The local player's pick and the champions offered during an Arena champ select.
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
use serde_json::Value;
use crate::ClientError;
use crate::client::Gameflow;
use crate::league_client::{lock, parse};
pub(crate) const PICKABLE_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_pickable-champion-ids";
pub(crate) const DISABLED_EVENT: &str = "OnJsonApiEvent_lol-champ-select_v1_disabled-champion-ids";
pub(crate) const ANVIL_EVENT: &str =
"OnJsonApiEvent_lol-lobby-team-builder_champ-select_v1_crowd-favorite-champion-list";
/// The local player's live pick and the champions they can still pick.
#[derive(Clone, Debug)]
pub struct ChampSelect {
pub current: Option<u32>,
/// The five anvil champions, in the order the client gives them; the client calls them
/// crowd favorites. `None` when the client gave no readable list for this champ select,
/// `Some` of an empty list when it said there are none: its list request fails (HTTP
/// error, unreadable body) when the list is absent, answers `[]` for a known empty list,
/// and its Update events carry a list while a Delete carries `null`.
pub anvil_champions: Option<Vec<u32>>,
/// The champions the champ select offers, before its bans and the other players' picks.
/// Shared with the client's cache instead of cloned on every session event.
pickable: Arc<HashSet<u32>>,
/// Banned in this champ select: the completed ban actions and both teams' ban lists.
banned: HashSet<u32>,
/// Confirmed by another player of the local team in this champ select. A pre-pick (the
/// client's pick intent) is not part of it.
taken_by_ally: HashSet<u32>,
}
/// Why the local player cannot pick a champion: the reasons add up, and a Pickable champion
/// has none. Whether the champion is Completed is not part of it.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Unpickable {
pub banned: bool,
pub taken_by_ally: bool,
/// The client does not offer the champion (not pickable, or disabled), and neither a ban
/// nor an ally explains it.
pub not_offered: bool,
}
impl PartialEq for ChampSelect {
fn eq(&self, other: &Self) -> bool {
self.current == other.current
&& self.anvil_champions == other.anvil_champions
&& self.same_pickable(other)
}
}
fn champion_id(value: &Value) -> Option<u32> {
u32::try_from(value.as_u64()?).ok().filter(|id| *id != 0)
}
fn array(value: &Value) -> Result<&[Value], ClientError> {
value
.as_array()
.map(Vec::as_slice)
.ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))
}
fn ids(body: &str) -> Result<HashSet<u32>, ClientError> {
let value = parse(body)?;
let ids =
ids_in(&value).ok_or_else(|| ClientError::Other("Liste de champions illisible".into()))?;
Ok(ids.into_iter().collect())
}
/// The champion ids of a list, from a body or from an event's data.
fn ids_in(value: &Value) -> Option<Vec<u32>> {
value
.as_array()
.map(|ids| ids.iter().filter_map(champion_id).collect())
}
impl ChampSelect {
/// A champ select with nothing banned or taken, for callers with a ready pool.
pub fn new(
current: Option<u32>,
pickable: HashSet<u32>,
anvil_champions: Option<Vec<u32>>,
) -> Self {
Self {
current,
anvil_champions,
pickable: Arc::new(pickable),
banned: HashSet::new(),
taken_by_ally: HashSet::new(),
}
}
fn from_session(
session: &Value,
pickable: Arc<HashSet<u32>>,
anvil_champions: Option<Vec<u32>>,
) -> Result<Self, ClientError> {
let local = session["localPlayerCellId"]
.as_i64()
.ok_or(ClientError::Absent)?;
let team = array(&session["myTeam"])?;
let me = team
.iter()
.find(|p| p["cellId"] == local)
.ok_or(ClientError::Absent)?;
let current =
champion_id(&me["championId"]).or_else(|| champion_id(&me["championPickIntent"]));
let mut taken_by_ally = HashSet::new();
let mut banned = HashSet::new();
for player in team
.iter()
.filter(|p| p["cellId"] != local && p["team"] == me["team"])
{
if let Some(id) = champion_id(&player["championId"]) {
taken_by_ally.insert(id);
}
}
// In Arena the confirmed bans were in actions while both team ban lists were empty.
for turn in array(&session["actions"])? {
for action in array(turn)? {
if action["type"] == "ban"
&& action["completed"] == true
&& let Some(id) = champion_id(&action["championId"])
{
banned.insert(id);
}
}
}
for key in ["myTeamBans", "theirTeamBans"] {
if let Some(bans) = session["bans"][key].as_array() {
banned.extend(bans.iter().filter_map(champion_id));
}
}
Ok(Self {
current,
anvil_champions,
pickable,
banned,
taken_by_ally,
})
}
/// Whether the local player can still pick this champion. Their own pick always stays
/// pickable.
pub fn can_pick(&self, id: u32) -> bool {
self.current == Some(id)
|| (self.pickable.contains(&id)
&& !self.banned.contains(&id)
&& !self.taken_by_ally.contains(&id))
}
/// Why the local player cannot pick this champion. The player's own pick, hovered or
/// locked, is never unpickable.
pub fn unpickable(&self, id: u32) -> Unpickable {
if self.current == Some(id) {
return Unpickable::default();
}
let banned = self.banned.contains(&id);
let taken_by_ally = self.taken_by_ally.contains(&id);
Unpickable {
banned,
taken_by_ally,
not_offered: !banned && !taken_by_ally && !self.pickable.contains(&id),
}
}
/// Whether both champ selects offer the same champions, whatever the current pick. The
/// shared set makes the common case a pointer comparison.
pub fn same_pickable(&self, other: &Self) -> bool {
(Arc::ptr_eq(&self.pickable, &other.pickable) || self.pickable == other.pickable)
&& self.banned == other.banned
&& self.taken_by_ally == other.taken_by_ally
}
}
/// The live champ select, read the one way both the real client and the tests read it: the
/// session the client sent as an event, else its answer to a session request, and the champion
/// lists read once per champ select.
#[derive(Default)]
pub struct ChampSelectReader {
lists: Mutex<Option<ChampSelectLists>>,
/// The latest session the client sent as an event, taken by the next read.
session: Mutex<Option<Value>>,
}
impl ChampSelectReader {
/// Forgets the champ select: the next read belongs to a new one.
pub(crate) fn reset(&self) {
*lock(&self.lists) = None;
*lock(&self.session) = None;
}
/// Follows a gameflow read: anything but an Arena champ select ends the cached one, whose
/// lists must not leak into the next.
pub fn reset_unless_arena_champ_select(&self, flow: &Gameflow) {
if !flow.is_arena_champ_select() {
self.reset();
}
}
/// Keeps the session the client sent as an event for the next read, which then needs no
/// session request.
pub fn set_session(&self, session: Value) {
if session.is_object() {
*lock(&self.session) = Some(session);
}
}
/// Reads the live champ select. `session` and `lists` make the requests; they run only when
/// the event session or the champion lists are missing, and never under a lock.
pub fn read(
&self,
session: impl FnOnce() -> Result<String, ClientError>,
lists: impl FnOnce() -> Result<(String, String, Option<String>), ClientError>,
) -> Result<ChampSelect, ClientError> {
let session = match lock(&self.session).take() {
Some(session) => session,
None => parse(&session()?)?,
};
if lock(&self.lists).is_none() {
let (pickable, disabled, anvil) = lists()?;
let lists = ChampSelectLists::from_bodies(&pickable, &disabled, anvil.as_deref())?;
*lock(&self.lists) = Some(lists);
}
let lists = lock(&self.lists);
let lists = lists.as_ref().expect("set just above");
ChampSelect::from_session(
&session,
lists.pickable(),
lists.anvil().map(<[u32]>::to_vec),
)
}
/// Applies the client's pickable list event.
pub(crate) fn set_pickable(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_pickable(data);
}
}
/// Applies the client's disabled list event.
pub(crate) fn set_disabled(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_disabled(data);
}
}
/// Applies the client's anvil champions event.
pub(crate) fn set_anvil(&self, data: &Value) {
if let Some(lists) = lock(&self.lists).as_mut() {
lists.set_anvil(data);
}
}
}
/// The champion lists of a champ select: read once, then updated from the client's events.
#[derive(Debug, Default)]
pub(crate) struct ChampSelectLists {
/// The client's pickable list, before the disabled champions are removed.
offered: HashSet<u32>,
disabled: HashSet<u32>,
/// `None` until the client gives a readable list.
anvil: Option<Vec<u32>>,
/// `offered` minus `disabled`, rebuilt only when either list changes.
pickable: Arc<HashSet<u32>>,
}
impl ChampSelectLists {
pub(crate) fn from_bodies(
pickable: &str,
disabled: &str,
anvil: Option<&str>,
) -> Result<Self, ClientError> {
let mut lists = Self {
offered: ids(pickable)?,
disabled: ids(disabled)?,
..Self::default()
};
// A missing or unreadable body leaves the list unknown; `[]` is a known empty list.
lists.anvil = anvil
.and_then(|body| parse(body).ok())
.and_then(|value| ids_in(&value));
lists.rebuild();
Ok(lists)
}
fn rebuild(&mut self) {
self.pickable = Arc::new(self.offered.difference(&self.disabled).copied().collect());
}
pub(crate) fn pickable(&self) -> Arc<HashSet<u32>> {
self.pickable.clone()
}
pub(crate) fn anvil(&self) -> Option<&[u32]> {
self.anvil.as_deref()
}
fn set_pickable(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.offered = ids.into_iter().collect();
self.rebuild();
}
}
fn set_disabled(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.disabled = ids.into_iter().collect();
self.rebuild();
}
}
fn set_anvil(&mut self, data: &Value) {
if let Some(ids) = ids_in(data) {
self.anvil = Some(ids);
}
}
}
#[cfg(test)]
mod tests;
Loaded 100 of 173 files, more files were not shown because too many files have changed in this diff. Show more