16 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
36 changed files with 1304 additions and 188 deletions

No files matched your search

+1 -1
View File
@@ -1,6 +1,6 @@
# 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`.
+1
View File
@@ -17,6 +17,7 @@ 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",
+62 -90
View File
@@ -1,8 +1,8 @@
//! The card grid: all the cards a list shows, in rows of the same count, only the visible rows
//! built. It is its own view because it owns the scrolling and the hover of its cards, 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.
//! 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;
@@ -16,33 +16,16 @@ use gpui_kit::*;
use crate::card::{Card, Reason, card};
use crate::card_images::{self, CardImages};
actions!(card_grid, [NextCard, PreviousCard]);
/// The grid's key context, where Tab and Shift-Tab move between its cards.
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)),
]);
}
mod focus;
pub use focus::init;
use focus::{CONTEXT, CardFocus, NextCard, PreviousCard};
mod geometry;
use geometry::{MAX_COLUMNS, Metrics};
pub use geometry::{MAX_WIDTH, TAKEN_DROP, row_height};
use geometry::{MAX_COLUMNS, Metrics, rows_in_view};
pub use geometry::{MAX_WIDTH, TAKEN_DROP};
mod layout;
pub use layout::{CardHovered, DrawnCard, DrawnCards, PutDown};
/// What makes one card reachable with the keyboard: its handle, and the subscriptions that lift
/// it while the keyboard is on it.
struct CardFocus {
handle: FocusHandle,
_subscriptions: [Subscription; 2],
}
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
@@ -65,6 +48,9 @@ pub struct CardGrid {
/// 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.
@@ -78,6 +64,7 @@ pub struct CardGrid {
impl EventEmitter<CardHovered> for CardGrid {}
impl EventEmitter<PutDown> for CardGrid {}
impl EventEmitter<RevealRow> for CardGrid {}
impl CardGrid {
pub fn new() -> CardGrid {
@@ -91,6 +78,7 @@ impl CardGrid {
focus: HashMap::new(),
focus_stale: false,
fit_content: false,
paged: None,
images: None,
#[cfg(test)]
renders: 0,
@@ -110,7 +98,18 @@ impl CardGrid {
}
}
pub fn hand_height(&self, window_width: Pixels) -> Option<Pixels> {
/// 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))
@@ -131,33 +130,6 @@ 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.
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);
}
});
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);
}
}
fn set_hovered(&mut self, id: u32, hovered: bool, cx: &mut Context<Self>) {
let next = match (hovered, self.hovered) {
(true, _) => Some(id),
@@ -203,37 +175,6 @@ impl CardGrid {
}
}
/// Moves the focus `step` cards on in the grid's order, scrolling its row into view since
/// only the visible rows are built. At either end the key goes on, to leave the grid.
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.fit_content {
let columns = Metrics::of(window.viewport_size().width).columns;
self.scroll
.scroll_to_item(target / columns, ScrollStrategy::Nearest);
}
window.focus(&handle, cx);
}
/// 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 {
@@ -364,7 +305,13 @@ impl CardGrid {
.w_full()
.h(px(metrics.card_height + metrics.gap))
.pb(px(metrics.gap))
.pr(Scrollbar::width())
// 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, _| {
@@ -401,9 +348,11 @@ impl CardGrid {
// 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 is moved by its
// parent's scrolling instead, which it cannot see.
let moved = grid.fit_content || grid.scrolled_to() != grid.drawn_scroll;
// 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);
}
@@ -454,6 +403,29 @@ impl Render for CardGrid {
.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(
+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 });
}
}
+21 -5
View File
@@ -1,5 +1,5 @@
use gpui_kit::Pixels;
use gpui_kit::component::scroll::Scrollbar;
use gpui_kit::{Pixels, px};
use crate::card::ASPECT;
use crate::page::PAGE_PADDING;
@@ -60,8 +60,24 @@ impl Metrics {
}
}
/// How tall a row of cards is in a window `window_width` wide: the least height that shows a
/// whole row, for a grid that shares its column with other sections.
pub fn row_height(window_width: Pixels) -> Pixels {
px(Metrics::of(window_width).row_height())
/// 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)
}
+20 -2
View File
@@ -1,8 +1,8 @@
use std::cell::RefCell;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;
use gpui_kit::{Bounds, Pixels};
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)]
@@ -17,6 +17,24 @@ pub struct CardHovered {
#[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)]
+18 -1
View File
@@ -1,7 +1,7 @@
use gpui_kit::px;
// Explicit imports: a glob of `gpui_kit` would shadow the built-in `#[test]`.
use super::geometry::{Metrics, columns};
use super::geometry::{Metrics, columns, rows_in_view};
use crate::card::ASPECT;
#[test]
@@ -21,6 +21,23 @@ fn the_columns_follow_the_mockups_breakpoints() {
}
}
#[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;
+2 -1
View File
@@ -1,5 +1,6 @@
//! 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).
//! 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
+85 -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,9 @@ 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,
@@ -62,11 +66,25 @@ 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();
}
}
/// Replaces the rows (already filtered) and keeps them sorted.
pub fn set_rows(&mut self, rows: Vec<ChampionRow>, in_season: bool) {
self.rows = rows;
@@ -74,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()
@@ -232,11 +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,
@@ -265,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()
@@ -321,6 +348,62 @@ pub(crate) mod tests {
}
}
// 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");
+2
View File
@@ -8,6 +8,7 @@ mod card_lift;
mod card_order;
mod champion_table;
mod logon;
mod minimized;
mod motion;
mod page;
#[cfg(feature = "profile")]
@@ -342,6 +343,7 @@ fn main() {
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 {
+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) }
}
+16 -5
View File
@@ -3,7 +3,7 @@
use crate::banner_art::BannerArt;
use crate::card::Card;
use crate::card_grid::{CardGrid, CardHovered};
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};
@@ -22,6 +22,7 @@ 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;
@@ -37,6 +38,7 @@ mod hover;
mod lifecycle;
mod playback;
mod profiling;
mod scrollbar;
mod setup;
mod statistics;
mod worker_messages;
@@ -289,13 +291,18 @@ pub struct Page {
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, as the home's.
/// 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 », and lifts it; its grid
/// is made again at each fold.
others_hover: [Subscription; 2],
/// 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<()>,
}
@@ -400,6 +407,10 @@ impl Page {
// 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));
}
}
+3 -1
View File
@@ -71,8 +71,10 @@ impl Page {
self.forget_home();
self.stored = None;
self.reorder();
// A new champ select starts with « Autres champions » folded and searchless.
// 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.
+37 -3
View File
@@ -1,5 +1,5 @@
use crate::card::Card;
use crate::card_grid::CardGrid;
use crate::card_grid::{CardGrid, RevealRow};
use crate::page::{Page, home};
use arena_tracker_core::{ChampSelect, ChampionRow, ChampionSearch};
use gpui_kit::*;
@@ -10,12 +10,46 @@ impl Page {
/// 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();
self.others_grid = cx.new(|_| CardGrid::new());
self.others_hover = Self::light_on_hover(&self.others_grid, cx);
// 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()
}
+44 -16
View File
@@ -1,5 +1,4 @@
use super::UNKNOWN_ANVIL;
use crate::card_grid::row_height;
use crate::page::{
Page,
home::{StatsNotice, count_badge, notice_line},
@@ -7,6 +6,7 @@ use crate::page::{
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::*;
@@ -42,6 +42,8 @@ impl Page {
div()
.v_flex()
.gap_3()
// The scrollbar's lane: the sort selector does not go under it.
.pr(Scrollbar::width())
.child(
div()
.h_flex()
@@ -71,7 +73,7 @@ impl Page {
div()
.w_full()
.debug_selector(|| "anvil-row".into())
.child(match self.anvil_grid.read(cx).hand_height(window_width) {
.child(match self.anvil_grid.read(cx).rows_height(window_width) {
Some(height) => self
.anvil_grid
.clone()
@@ -101,9 +103,10 @@ impl Page {
/// « 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. `window_width`
/// gives the cards' size: the grid is never shorter than a whole row, and in a small window
/// the column scrolls instead.
/// 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,
@@ -128,7 +131,7 @@ impl Page {
.v_flex()
.w_full()
.gap_3()
.when(open, |section| section.flex_1())
.pr(Scrollbar::width())
.child(
BaseButton::new("others-toggle")
.track_focus(&self.others_focus)
@@ -159,17 +162,42 @@ impl Page {
.min_w(px(150.)),
),
)
.child(
// Cached, as the home's grid: hovering elsewhere does not draw its
// cards again. Its size comes from this style.
self.others_grid.clone().cached(
StyleRefinement::default()
.w_full()
.flex_1()
.min_h(row_height(window_width)),
),
)
.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)
}
}
+18 -5
View File
@@ -150,8 +150,8 @@ impl Page {
}
if self.in_champ_select() {
// The champ select takes the place of the grid, its filters and its search: the
// column may be taller than the window, and scrolls then. « Autres champions »
// takes what is left of the height, and scrolls by itself while open.
// 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));
}
@@ -159,10 +159,23 @@ impl Page {
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![
column
.id("champ-select")
.overflow_y_scroll()
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(),
];
}
+4 -2
View File
@@ -10,8 +10,8 @@ impl Page {
}
/// The page gives way to another screen (« Paramètres »): what it shows is given back, the
/// grids' portraits and the banner's splash, in memory and in the window's atlas. They load
/// again when it is drawn.
/// 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);
@@ -22,6 +22,8 @@ impl Page {
}
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 ».
+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))
}
}
+15 -3
View File
@@ -1,9 +1,10 @@
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;
use crate::card_grid::{CardGrid, Paging};
use crate::card_lift::Lifts;
use crate::champion_table::ChampionTable;
use crate::motion::AnimationSetting;
@@ -15,7 +16,9 @@ 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;
@@ -70,11 +73,18 @@ impl Page {
let anvil_grid = cx.new(|_| CardGrid::fit_content());
let others_search_input =
cx.new(|cx| InputState::new(window, cx).placeholder("Rechercher"));
let others_grid = cx.new(|_| CardGrid::new());
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_on_hover(&others_grid, 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));
@@ -274,6 +284,8 @@ impl Page {
others_search: ChampionSearch::new(""),
others_search_input,
others_grid,
paging,
champ_select_scrollbar,
others_focus,
others_hover,
_subscriptions: subscriptions,
+1
View File
@@ -8,6 +8,7 @@ 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;
@@ -327,6 +327,8 @@ 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
@@ -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:?}"
);
}
+13 -15
View File
@@ -1,9 +1,10 @@
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, send, tracker_with_portraits,
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, row_height};
use crate::card_grid::CardGrid;
use crate::card_images::tests::{PORTRAIT_JPEG, TestDir};
use crate::page::{Page, Tab};
@@ -90,6 +91,7 @@ async fn folding_others_frees_its_portraits(cx: &mut TestAppContext) {
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);
@@ -185,23 +187,18 @@ async fn a_grid_that_is_not_shown_gives_its_portraits_back(cx: &mut TestAppConte
assert_eq!(held(&anvil, &mut window), 0);
}
// « Autres champions » is open in a column that also scrolls: its grid keeps at least a
// whole row, not the sliver the Anvil row leaves it in a 860 px window.
// « 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_shows_a_whole_row(cx: &mut TestAppContext) {
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);
draw(&mut window);
let list = window
.debug_bounds("card-list")
scroll_champ_select_down(&mut window);
let card = window
.debug_bounds("card-103")
.expect("the open section's grid is not drawn");
let row = row_height(px(1280.));
assert!(
list.size.height >= row,
"{:?} tall for a row of {row:?}",
list.size.height
);
assert!(window.debug_bounds("card-103").is_some());
assert!(card.size.height > px(200.), "{card:?}");
assert!(card.bottom() <= px(860.), "{card:?}");
assert!(others_open(&page, &mut window));
}
@@ -304,6 +301,7 @@ async fn a_reason_appearing_on_a_card_of_others_is_drawn_without_moving_it(
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())
};
+9 -9
View File
@@ -94,13 +94,13 @@ fn update_context() -> Option<(PathBuf, Vec<u8>, &'static str)> {
}
/// Keeps the newest release of `channel` downloaded and authenticated in the updates folder and
/// returns its version. A failed check only means no update is ready; the next launch checks
/// again.
pub fn download_update(channel: UpdateChannel) -> Option<String> {
let (dir, key, version) = update_context()?;
/// 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)
.ok()
.flatten()
.map_err(|e| e.to_string())
}
/// Before the app loads, in the single instance only: hands the kept update of the chosen
@@ -148,9 +148,9 @@ fn installer() -> io::Result<PathBuf> {
Ok(root.ok_or(io::ErrorKind::NotFound)?.join("Update.exe"))
}
/// Starts Velopack's installer on an authenticated package, which it reads in place: it waits
/// for this process to exit, 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
/// 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> {
+48 -5
View File
@@ -52,7 +52,10 @@ pub struct KeyForm {
notice_shown: Sender<()>,
/// « Mise à jour prête » with the version downloaded and authenticated for the chosen channel.
ready: Option<SharedString>,
/// One update check at a time: once per launch, then once per channel change.
/// 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],
@@ -130,6 +133,7 @@ impl KeyForm {
logon_launch,
notice_shown,
ready: None,
check_outcome: None,
update_checks: RefreshGate::default(),
updates,
_subscriptions: [subscription, appearance],
@@ -157,21 +161,58 @@ impl KeyForm {
}
}
/// Only a check of the channel chosen now can make an update ready.
/// « 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()) {
let ready = (checked.ready)
.map(|version| format!("Mise à jour prête : version {version}").into());
self.set_ready(ready, cx);
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;
@@ -191,6 +232,7 @@ impl KeyForm {
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();
}
@@ -221,6 +263,7 @@ impl KeyForm {
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
+12 -2
View File
@@ -6,7 +6,7 @@ use gpui_kit::component::{ActiveTheme as _, Disableable as _, StyledExt as _};
use gpui_kit::*;
use super::KeyForm;
use crate::release::channel;
use crate::release::{self, channel};
const THEMES: [(ThemePreference, &str); 3] = [
(ThemePreference::System, "Système"),
@@ -107,8 +107,18 @@ impl KeyForm {
);
})),
)
.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.update_status()
[self.check_status(), self.update_status()]
.into_iter()
.flatten()
.map(|status| div().text_color(muted).child(status)),
)
.children(self.can_restart().then(|| {
+69 -2
View File
@@ -48,14 +48,14 @@ fn the_chosen_channel_is_saved_and_only_its_check_offers_a_restart(cx: &mut Test
// A stable check that ends after the change to Bêta stays out of sight.
let late = UpdateChecked {
channel: UpdateChannel::Stable,
ready: Some("1.0.1".into()),
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,
ready: Some("1.1.0-beta.3".into()),
result: Ok(Some("1.1.0-beta.3".into())),
};
form.update_checked(checked, cx);
assert!(form.update_ready());
@@ -73,13 +73,80 @@ fn the_chosen_channel_is_saved_and_only_its_check_offers_a_restart(cx: &mut Test
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);
+1 -1
View File
@@ -50,7 +50,7 @@ fn a_ready_update_adds_a_title_bar_button_that_opens_the_settings(cx: &mut TestA
form.update(cx, |form, cx| {
let checked = UpdateChecked {
channel: UpdateChannel::Stable,
ready: Some("1.0.1".into()),
result: Ok(Some("1.0.1".into())),
};
form.update_checked(checked, cx);
});
+6 -5
View File
@@ -290,21 +290,22 @@ pub fn spawn_follower(tracker: Arc<Tracker>, fallback_riot_id: String, tx: Sende
});
}
/// What an update check for `channel` kept ready: the version, if any.
/// 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 ready: Option<String>,
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,
ready: None,
result: Err("la vérification s’est interrompue".into()),
};
spawn_guarded(tx, crashed, move |tx| {
let ready = crate::release::download_update(channel);
let _ = tx.try_send(UpdateChecked { channel, ready });
let result = crate::release::download_update(channel);
let _ = tx.try_send(UpdateChecked { channel, result });
});
}
+55
View File
@@ -0,0 +1,55 @@
# Guide d’utilisation
## Installer
Les versions se téléchargent sans compte depuis la page [Releases](https://gitea.nessar.fr/nessar/arena-tracker/releases) :
- **Stable** : `ArenaTracker-stable-Setup.exe`, dans la dernière Release qui n’est pas une préversion.
- **Bêta** : `ArenaTracker-beta-Setup.exe`, dans la dernière préversion.
L’installateur ne demande pas de droits d’administrateur. Il installe Arena Tracker pour le compte Windows courant et ajoute **Arena Tracker** au menu Démarrer. Au premier lancement, l’application demande une clé API Riot, à obtenir sur le [portail développeur Riot](https://developer.riotgames.com).
L’installateur ne porte pas de signature Authenticode : Windows peut afficher un avertissement SmartScreen avant de l’ouvrir. Cet avertissement ne dit rien des mises à jour : Arena Tracker vérifie lui-même la signature de chaque paquet téléchargé et refuse un paquet altéré.
## Choisir Stable ou Bêta
Dans **Paramètres** (roue dentée de la barre de titre), section **Mises à jour** :
- **Stable** ne reçoit que les versions stables.
- **Bêta** reçoit chaque nouvelle bêta, avant la stable qui suivra.
Sans choix enregistré, le canal est celui de l’installateur utilisé. Une mise à jour ne change jamais le canal choisi. Repasser à Stable depuis une bêta ne revient pas à une version plus ancienne : la bêta reste en place jusqu’à la stable suivante, et les Paramètres l’indiquent.
## Mises à jour
Au démarrage, et après un changement de canal, Arena Tracker cherche une version plus récente du canal choisi et la télécharge en arrière-plan. Le bouton « Rechercher une mise à jour » des Paramètres lance la même recherche à la demande, et les Paramètres indiquent comment s’est terminée la dernière : « Recherche en cours… », « Vous avez la dernière version », ou la raison de l’échec. L’application reste utilisable pendant ce temps. Sans réseau ou en cas d’échec, rien ne change : une mise à jour déjà prête le reste.
Une flèche verte, « Mise à jour prête », apparaît dans la barre de titre une fois le paquet téléchargé et sa signature vérifiée. Elle ouvre les Paramètres, qui indiquent la version et proposent « Redémarrer » :
- « Redémarrer » ferme Arena Tracker, installe la mise à jour (une fenêtre de progression s’affiche) et ouvre la nouvelle version.
- Sinon, la mise à jour s’installe au lancement qui suit « Quitter », même hors ligne.
Si l’installation échoue, la version précédente s’ouvre avec un bandeau qui le signale. « Redémarrer » permet de réessayer.
## Fermer la fenêtre
Par défaut, le bouton de fermeture cache la fenêtre dans la zone de notification, et Arena Tracker continue de suivre les Parties. Un clic sur son icône rouvre la fenêtre ; un clic droit propose « Ouvrir » et « Quitter ». L’option **Fermer dans la zone de notification** des Paramètres désactive ce comportement : la fermeture quitte alors l’application.
Relancer Arena Tracker depuis le menu Démarrer pendant qu’il tourne ramène simplement sa fenêtre. Au début d’une Sélection des champions Arena, la fenêtre réduite ou cachée se rouvre d’elle-même, sans prendre le focus.
## Données
La clé Riot, les préférences, les Parties et les Saisons sont dans `%APPDATA%\arena-tracker` :
| Fichier | Contenu |
| --- | --- |
| `config.toml` | Clé API Riot, préférences et canal choisi |
| `arena-tracker.db` | Parties importées |
| `seasons.toml` | Table des Saisons, modifiable, relue au lancement |
| `portraits` | Portraits des champions |
Les mises à jour, la désinstallation et la réinstallation conservent ce dossier. Le paquet de mise à jour téléchargé est conservé à part, dans `%LOCALAPPDATA%\arena-tracker\updates`. Pour tout effacer, supprimer ces deux dossiers après la désinstallation.
## Désinstaller
**Paramètres Windows → Applications → Applications installées → Arena Tracker → Désinstaller.** Le dossier des données reste en place.
+1 -1
View File
@@ -34,7 +34,7 @@ Au survol ou au focus clavier, la fiche du champion apparaît en glissant sur la
### Pendant la sélection Arena
1. La détection d’une sélection Arena affiche automatiquement la rangée de cartes dans la fenêtre existante, sous la bannière de sélection. Le joueur garde le focus dans League : une fenêtre réduite ou cachée dans la zone de notification se rouvre à l’entrée en sélection, sans prendre le focus, et reste ouverte à la fin de la sélection. Ce comportement n’a pas de réglage.
2. La rangée « Champions de l’Enclume » contient **tous** les champions marqués d’une enclume dans la sélection en cours, dans le tri choisi. Au-dessous, « Autres champions » est replié par défaut. L’ouvrir affiche tous les champions sans enclume, avec le même tri et les mêmes cartes. Sa recherche par nom filtre uniquement cette section.
2. La rangée « Champions de l’Enclume » contient **tous** les champions marqués d’une enclume dans la sélection en cours, dans le tri choisi. Au-dessous, « Autres champions » est replié par défaut. L’ouvrir affiche tous les champions sans enclume, avec le même tri et les mêmes cartes. Sa recherche par nom filtre uniquement cette section. La sélection défile comme une seule page (bannière, enclumes, « Autres champions »), avec une seule barre de défilement.
3. Dans les deux sections, les cartes gardent leur place lorsqu’un champion est validé, banni ou pris par un allié (dans la main, une carte prise par un allié s’abaisse seulement de 8 px). Son portrait est grisé et la carte indique les raisons applicables : « Validé », « Banni », « Pris par un allié », et « Indisponible » pour un champion que le client ne propose pas (non possédé ou désactivé). Un champion validé et banni porte les deux indications.
4. Une présélection alliée laisse la carte dans son état courant. « Pris par un allié » apparaît à la confirmation du choix. Les bans et les choix alliés expirent avec la sélection : ils n’affectent ni les coches personnelles, ni le compteur du Défi, ni la sélection suivante.
+97
View File
@@ -0,0 +1,97 @@
# Livraison 1.0
Recette de la 1.0 (#62) : les versions et commits essayés, les essais Windows et leurs résultats, le contrôle de performance et la publication. Une case vide est un essai pas encore fait. La 1.0 est livrée quand toutes les cases sont remplies et le contrôle de performance validé.
## Versions essayées
| Rôle | Version | Commit | Release |
| --- | --- | --- | --- |
| A | 1.0.0-beta.3 | `2c9ca45` | Préversion publiée le 2026-11-22 |
| B | 1.0.0-beta.4 | `1ad36bd` | Préversion publiée le 2026-11-23 |
| C | 1.0.0-beta.5 | `995f454` | Préversion publiée le 2026-11-23 |
| Stable | 1.0.0 | | |
Les bêtas se publient depuis develop par `scripts/publish beta` ([Publication](publication.md)). Le poste de build a B installée et C publiée : les essais 3 à 5 se font d’abord, sur B. Pour retrouver ensuite une mise à jour prête (essais 2, 7 à 12) : désinstaller, supprimer `%LOCALAPPDATA%\arena-tracker\updates` (la trace d’une mise à jour déjà appliquée y serait lue comme un échec), réinstaller A depuis l’installateur de sa Release, puis lancer en ligne jusqu’à « Mise à jour prête ». A passe directement à la dernière bêta. La stable 1.0.0 se publie depuis le commit de la dernière bêta validée.
## Accès pendant les essais
Le dépôt est public depuis le 2026-11-20 (#58), avant le début de ces essais, qui prévoyaient un accès privé. Les bêtas d’essai sont donc des préversions publiques. Le canal Bêta les lit sans compte ni jeton ; le canal Stable ne les voit pas. L’application ne contient que la clé publique de vérification. Le jeton Gitea n’existe que dans le terminal du mainteneur pendant `scripts/publish`, qui le retire de l’environnement avant la compilation.
Le 2026-11-21, depuis WSL et sans authentification, l’API des préversions a renvoyé `v1.0.0-beta.1` avec ses quatre fichiers. Leur téléchargement a abouti, et le SHA-256 du paquet correspondait au manifeste. L’`arena-tracker.exe` du paquet a accepté la Release (`--verify-release`, code 0) et refusé une copie dont un bit du paquet était inversé (code 1). `Get-AuthenticodeSignature` a renvoyé `NotSigned` sur l’installateur. L’API des versions stables ne renvoyait encore aucune Release.
## Conditions des essais Windows
- Un compte Windows standard, non administrateur, dont la configuration contient une clé Riot, des Parties importées et une Saison personnalisée dans `seasons.toml`.
- Les installateurs et paquets des Releases, jamais une compilation locale.
Les essais du 2026-11-23 ont été pilotés depuis WSL sur le poste de build (Ryzen 7 7800X3D), sur le compte du mainteneur, **administrateur**, avec ses vraies données (485 Parties, Saison personnalisée « Saison 2 · 2026 »). Les clics étaient des messages postés à la fenêtre, et « Quitter » la commande du menu de la zone de notification ; chaque résultat a été lu sur une capture de la fenêtre et dans l’état des fichiers et des processus. Les désinstallations ont utilisé la commande silencieuse de l’entrée **Applications installées** (`Update.exe --uninstall --silent`), et les installations l’installateur de A téléchargé avec `curl.exe`.
- La notification de la zone de notification a déjà été vue une fois : elle écrit `tray_notice_shown` dans `config.toml`.
- Avant et après chaque essai, la même fenêtre : Compte, Saison personnalisée, compteur du Défi et Parties affichées. Hors préférences modifiées pendant l’essai, `config.toml` et `seasons.toml` restent identiques :
```powershell
$d = "$env:APPDATA\arena-tracker"; Get-FileHash "$d\config.toml", "$d\seasons.toml" | Format-Table Hash, Path
```
Version installée : `(Get-Item "$env:LOCALAPPDATA\ArenaTracker\current\arena-tracker.exe").VersionInfo.ProductVersion`. Installateur Velopack en cours : `Get-Process Update -ErrorAction SilentlyContinue | Where-Object Path -like "$env:LOCALAPPDATA\ArenaTracker\*"`. Journal de Velopack : `%LOCALAPPDATA%\velopack\velopack_ArenaTracker.log`.
## Essais
| # | Essai | Attendu | Résultat |
| --- | --- | --- | --- |
| 1 | A installée, canal Bêta, B publiée : lancer, puis « Redémarrer » | « Mise à jour prête » puis « Mise à jour prête : version 1.0.0-beta.4 » dans les Paramètres. Après « Redémarrer », la fenêtre de progression, puis B s’ouvre une seule fois. Données conservées | 2026-11-23 08:49 : B appliquée par « Redémarrer » (journal Velopack, `Restart: true`). Le même chemin, données comparées, est l’essai 5 |
| 2 | Après les essais 3 à 5, retrouver une mise à jour prête (ci-dessus). « Quitter » dans la zone de notification, couper le réseau, relancer par le menu Démarrer | C s’installe et s’ouvre hors ligne. Données conservées | 2026-11-23, en ligne : la coupure réseau a été écartée. A → C installée au lancement qui suit « Quitter » (essai 8) |
| 3 | Sur B, canal Bêta, C publiée : choisir Stable, puis relancer | Pas de « Mise à jour prête ». Les Paramètres indiquent « La bêta installée reste en place jusqu’à une version stable plus récente. » | 2026-11-23 : réussi. Dès le choix de Stable : « Vous avez la dernière version (1.0.0-beta.4) » et le message attendu ; de même après « Quitter » et relance |
| 4 | Revenir à Bêta jusqu’à « Mise à jour prête » pour C. Choisir Stable, puis « Quitter » et relancer | « Mise à jour prête » et « Redémarrer » disparaissent. Le lancement suivant n’installe pas C, et le dossier `updates\beta-1.0.0-beta.5` disparaît à la vérification suivante | 2026-11-23 : réussi. « Mise à jour prête : version 1.0.0-beta.5 » après le retour à Bêta. Au choix de Stable, la flèche, le message et « Redémarrer » disparaissent, et le dossier `beta-1.0.0-beta.5` aussi, sans attendre la relance. La relance garde B |
| 5 | Revenir à Bêta, puis « Redémarrer » | C s’ouvre : deux bêtas successives reçues (A → B → C) | 2026-11-23 : réussi. C ouverte moins d’une seconde après « Redémarrer », une seule fois. A → B (08:49) → C. Empreintes de `config.toml` et `seasons.toml` identiques, même fenêtre |
| 6 | Après publication de la 1.0.0 : sur C, choisir Stable et relancer | 1.0.0 proposée puis installée ; jamais une version plus ancienne. La clé de C a accepté la stable | |
| 7 | Une mise à jour prête : relancer par le menu Démarrer avec la fenêtre visible, réduite, puis cachée dans la zone de notification | La même fenêtre revient ; un seul `arena-tracker.exe` (`Get-Process arena-tracker`), aucun installateur en cours | 2026-11-23 : réussi. A installée, C prête : la fenêtre revient dans les trois cas, un seul `arena-tracker.exe`, aucun installateur, A reste en place |
| 8 | Une mise à jour prête : « Quitter », puis deux lancements rapprochés par le menu Démarrer | Un seul installateur en cours, une seule fenêtre à la fin | 2026-11-23 : réussi. Au plus un installateur et un `arena-tracker.exe` à la fois (relevé toutes les 100 ms). À la fin, C ouverte dans une seule fenêtre |
| 9 | Lancer sans réseau (mode Avion) | Pas de « Mise à jour prête » ; l’application et les Parties restent consultables | Écarté le 2026-11-23 : pas de coupure réseau pendant ces essais |
| 10 | Pendant un téléchargement, quand `updates\partial` contient le paquet incomplet : couper le réseau, ou arrêter Arena Tracker dans le Gestionnaire des tâches. Puis relancer en ligne | Rien n’est prêt avec le paquet incomplet. Au lancement suivant, il est retéléchargé puis prêt. L’essai ne compte que si le paquet incomplet a été vu | 2026-11-23 : réussi, par arrêt du processus. Arrêté à 1 129 789 octets sur 16 614 628, seul `partial` existait. Au lancement suivant, le paquet a été retéléchargé en entier, puis « Mise à jour prête » |
| 11 | Une mise à jour prête : inverser un bit du paquet conservé (commande ci-dessous), puis « Redémarrer » | « Mise à jour refusée : condensat du paquet différent. » La version installée reste utilisable ; le paquet est retéléchargé et de nouveau prêt | 2026-11-23 : réussi. Message affiché en rouge sous « Redémarrer », A reste ouverte. Le paquet est aussitôt retéléchargé et de nouveau prêt ; son SHA-256 correspond au manifeste |
| 12 | Une mise à jour prête : verrouiller un fichier de `current` (commande ci-dessous), « Redémarrer », puis libérer le fichier | L’ancienne version se rouvre avec le bandeau « La mise à jour vers la version … n’a pas pu être installée ; la version actuelle reste en place. » « Redémarrer » réussit ensuite | 2026-11-23 : réussi. Velopack a réessayé pendant 5 s (`Access is denied`), puis A s’est rouverte 9 s après le clic avec le bandeau, pour 1.0.0-beta.5. Le fichier libéré, « Redémarrer » a ouvert C en 3 s |
| 13 | Désinstaller, réinstaller, relancer, puis désinstaller de nouveau | Le dossier d’installation, le raccourci et l’entrée **Applications installées** disparaissent à la désinstallation ; les données restent identiques | 2026-11-23 : réussi, trois désinstallations. Après chacune : ni `current`, ni raccourci, ni entrée **Applications installées**, ni lancement à l’ouverture de session. Empreintes identiques. Une réinstallation désactive « Lancer à l’ouverture de session Windows », comme prévu ; l’option a été réactivée à la fin |
| 14 | Télécharger l’installateur stable avec un navigateur, puis l’ouvrir | Consigner ce qu’affiche Windows (SmartScreen, éditeur) et `Get-AuthenticodeSignature`. L’installateur n’a pas de signature Authenticode ([Signature reconnue par Windows](paquets-windows.md#signature-reconnue-par-windows)) | |
Essai 11, depuis PowerShell :
```powershell
$p = (Get-ChildItem "$env:LOCALAPPDATA\arena-tracker\updates\*-*\*.nupkg" | Select-Object -First 1).FullName
$b = [IO.File]::ReadAllBytes($p); $i = [int]($b.Length / 2); $b[$i] = $b[$i] -bxor 1; [IO.File]::WriteAllBytes($p, $b)
```
Essai 12, depuis PowerShell, laissé ouvert pendant « Redémarrer », puis `$h.Close()`. Un nouveau fichier, et non `sq.version`, que Velopack lit avant de commencer :
```powershell
$h = [IO.File]::Open("$env:LOCALAPPDATA\ArenaTracker\current\verrou.tmp", 'CreateNew', 'ReadWrite', 'None')
```
## Contrôle de performance
La 1.0 est une version majeure : son feu vert dépend du benchmark complet de #32, à l’étape 1 de [Publier une stable](publication.md#publier-une-stable). Les chiffres et leur date sont dans le [tableau des budgets](performance.md#budgets).
| Commit mesuré | Date | Résultat |
| --- | --- | --- |
| `995f454` (1.0.0-beta.5) | 2026-11-23 | budgets 1, 2, 3 (fenêtre minimisée) et 4 dépassés : pas de feu vert |
| `b8e4927` | 2026-11-23 | budgets 3 et 4 corrigés ; limites des budgets 1, 2 et 3 ramenées aux planchers de GPUI par décision du mainteneur : les cinq budgets tenus, feu vert |
## Publication publique
1. Feu vert de performance sur le commit à livrer.
2. Promotion vers main, contrôles CI, puis `scripts/publish stable` ([Publier une stable](publication.md#publier-une-stable)).
3. Depuis un poste sans authentification Gitea, depuis WSL :
```bash
base=https://gitea.nessar.fr; mkdir -p rel
curl -sS "$base/api/v1/repos/nessar/arena-tracker/releases?draft=false&pre-release=false&limit=10" | python3 -c "import json, sys; print([r['tag_name'] for r in json.load(sys.stdin)])"
for f in ArenaTracker-1.0.0-stable-full.nupkg ArenaTracker-stable-Setup.exe release-stable.json release-stable.sig; do curl -sSfL -o "rel/$f" "$base/nessar/arena-tracker/releases/download/v1.0.0/$f"; done
unzip -p rel/ArenaTracker-1.0.0-stable-full.nupkg lib/app/arena-tracker.exe > arena-tracker.exe && chmod +x arena-tracker.exe
./arena-tracker.exe --verify-release "$(wslpath -w rel)"; echo "code $?"
```
Attendu : `['v1.0.0']`, quatre téléchargements, `code 0`. L’exécutable du paquet vérifie avec sa propre clé ; la vérification par une installation antérieure est l’essai 6. Puis ouvrir la page [Releases](https://gitea.nessar.fr/nessar/arena-tracker/releases) dans une fenêtre de navigation privée et télécharger l’installateur.
| Étape | Date | Résultat |
| --- | --- | --- |
| Tag `v1.0.0` publié | | |
| Flux et signature vérifiés sans authentification | | |
+1 -1
View File
@@ -41,7 +41,7 @@ Les fichiers sont téléchargés dans `%LOCALAPPDATA%\arena-tracker\updates\part
## Application de la mise à jour
« Redémarrer », dans les Paramètres, et le lancement qui suit « Quitter » appliquent le même paquet : le dossier du canal choisi dont la version dépasse la version installée, vérifié de nouveau par `verify_release`. L’application lance alors, depuis la racine de l’installation, `Update.exe apply --waitPid <pid> --package <paquet>` sur le fichier qui vient d’être vérifié dans `%LOCALAPPDATA%\arena-tracker\updates`, puis se ferme comme avec « Quitter », sans passer par la zone de notification. Velopack 1.2.161 lit ce fichier sur place, sans le copier dans `packages`. Il attend la fin du processus (60 s au plus, puis il arrête tout programme lancé depuis l’installation), extrait le paquet, remplace `current` et ouvre une seule fois la nouvelle version, ou de nouveau l’ancienne en cas d’échec. Il affiche sa fenêtre de progression et journalise dans `%LOCALAPPDATA%\velopack\velopack_ArenaTracker.log`. [Commande apply](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/commands/apply.rs) · [Remplacement sous Windows](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/commands/apply_windows_impl.rs)
« Redémarrer », dans les Paramètres, et le lancement qui suit « Quitter » appliquent le même paquet : le dossier du canal choisi dont la version dépasse la version installée, vérifié de nouveau par `verify_release`. L’application lance alors, depuis la racine de l’installation, `Update.exe apply --waitPid <pid> --package <paquet>` sur le fichier qui vient d’être vérifié dans `%LOCALAPPDATA%\arena-tracker\updates`, puis se ferme comme avec « Quitter », sans passer par la zone de notification. Velopack 1.2.161 lit ce fichier sur place, sans le copier dans `packages`. Il doit attendre la fin du processus (60 s au plus), puis arrêter tout programme encore lancé depuis l’installation. En pratique, il n’attend pas : à chaque application observée, son journal indique `Failed to wait for process (<pid>) to exit (Access is denied.)`, alors que le processus de l’application s’attend bien avec le droit `SYNCHRONIZE` (vérifié le 2026-11-23). Il passe donc directement à l’arrêt forcé, environ 0,3 s plus tard, et l’application quitte avant : seul `Update.exe` restait dans l’installation. Un arrêt forcé ne perd pas de données : `config.toml` s’écrit à côté puis se renomme, et les Parties sont dans SQLite, en transactions. Ensuite, il extrait le paquet, remplace `current` et ouvre une seule fois la nouvelle version, ou de nouveau l’ancienne en cas d’échec. Il affiche sa fenêtre de progression et journalise dans `%LOCALAPPDATA%\velopack\velopack_ArenaTracker.log`. [Commande apply](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/commands/apply.rs) · [Remplacement sous Windows](https://github.com/velopack/velopack/blob/1.2.161/src/bins/src/commands/apply_windows_impl.rs)
Au lancement, cette décision suit l’élection de l’instance unique et précède toute fenêtre. Un raccourci lancé pendant qu’Arena Tracker tourne, visible, réduit ou caché dans la zone de notification, ramène seulement sa fenêtre (#50) : ni second suivi, ni recherche, ni installation. Avant de lancer `Update.exe`, l’application crée `<canal>-<version>.attempt` à côté du dossier du paquet, puis y inscrit l’identifiant du processus. Ce fichier survit à un nouveau téléchargement de la même version. Un lancement qui le trouve ne relance jamais l’installation lui-même ; seule une version plus récente repart de zéro. Si ce processus `Update.exe` tourne encore (lancement rapproché, ou ancienne version rouverte par Velopack après un échec), il attend sa fin, 3 min au plus. Un code de sortie 0 laisse la place à la version que Velopack ouvre ; sinon l’application s’ouvre dans sa version actuelle et signale l’échec une fois, dans un bandeau. « Redémarrer » permet de réessayer. Un paquet altéré depuis son téléchargement est refusé et signalé ; la vérification suivante le télécharge de nouveau. Si la configuration est illisible, le canal choisi est inconnu et rien n’est appliqué.
+30 -9
View File
@@ -10,13 +10,22 @@ Measured on the **reference machine**, on a **release build** (`scripts/prod run
| # | Budget | Limit | Current value | Status |
| --- | --- | --- | --- | --- |
| 1 | Interactions (hover, scroll, sort, filter, moving or resizing the window): cost of one frame | at most **2 ms** at the 99th percentile, aiming for 1 ms | 5–7 ms for a full frame of the statistics page; a window move redraws one, 5–8 ms per move at the 95th percentile (before #31) | over budget; to re-measure since #31 |
| 2 | Idle, window visible: CPU | at most **0.5 %** of one core on average | 0.3–1.4 % (about 0.8 %) | over budget |
| 3 | Window minimised or hidden | **no rendering**, CPU close to 0, outside an import | not measured | unknown |
| 4 | Memory, with the full page loaded (every champion and portrait) | at most **150 MB** working set | 120 MB working set, 99 MB private | within budget |
| 5 | Background work (import, following the game client) | threads at **low priority**, never more than **one core** | not measured | unknown |
| 1 | Interactions (hover, scroll, sort, filter, moving or resizing the window): cost of one frame | at most **6 ms** at the 99th percentile for a frame drawn (profile build): the 1.0 value, set on 2026-11-23 (#32), to lower after 1.0 (#106); it was 2 ms, aiming for 1 ms | every interaction draws a full frame: 2.8–3.3 ms at the median, 5.3–5.9 ms at the 99th percentile, plus 0.4–0.5 ms of presentation (profile build); single frames up to 8 ms while scrolling; a window move holds the UI thread 3.3 ms at the 95th percentile, 4.4–4.5 ms at the 99th (release) | within budget, close to the limit |
| 2 | Idle, window visible: CPU | at most **1.1 %** of one core on average: GPUI's floor, set on 2026-11-23 (#32); it was 0.5 % | 0.88–1.08 % over three phases of 30 s, no frame drawn; floor set by GPUI's vsync thread, see below | within budget, close to the limit |
| 3 | Window minimised or hidden | **no rendering**; CPU at most **1.1 %** of one core minimised and **0.35 %** hidden, outside an import: GPUI's floor, set on 2026-11-23 (#32); it was « close to 0 » | no frame drawn either way; minimised 0.98–1.03 %, hidden in the notification area 0.34 % | within budget |
| 4 | Memory, with the full page loaded (every champion and portrait) | at most **150 MB** working set | 146–149 MB working set, 122–123 MB private, at the end of the memory scenario; « Défi » with the home grid scrolled to its end holds 170–174 MB, and 159–163 MB at start | within budget, at the scenario's point only |
| 5 | Background work (import, following the game client) | threads at **low priority**, never more than **one core** | import of 466 Matches with the client open: at most 16.6 % of one core in a sample, the work on below-normal threads (4.8 s of CPU, against 0.4 s on normal-priority threads, none above 1.6 % in a sample) | within budget |
Current values measured on 2026-11-16 and 2026-11-17 (issue #17). For information, #31 made a full frame about a third cheaper on the manual checks machine (drawing it: 2.37 → 1.57 ms at the median, 3.72 → 2.50 ms at the 99th percentile, plus 0.22 ms of presentation); its value here is still to measure.
Values of the 1.0 release benchmark: 2026-11-23, reference machine, release build of `b8e4927` (the 1.0's code) and its `--features profile` build for the frame breakdown, scenarios and details below. A first run on `995f454` (1.0.0-beta.5) failed budgets 1 to 4; the app was fixed for budgets 3 (`f53db09`) and 4 (`b8e4927`), and the user set budgets 1, 2 and 3's limits to the floors GPUI sets. No limit was beaten, so none is lowered. The previous values (2026-11-16 and 2026-11-17, issue #17) were 5–7 ms per full frame, 0.3–1.4 % idle and 120 MB working set, before the identity (#80) added the banner, its splash and the portrait cards.
### Release benchmark 1.0 (2026-11-23)
- **Budget 1.** Nothing a frame is asked for is cheap: each window move, hovered row or wheel step draws the whole window, at 60 frames per second (`request_layout` 0.7–1.0 ms, `prepaint` 1.6–2.2 ms, `paint` 0.7–1.3 ms at the median). On « Défi » the card grid's own prepaint takes 1.6–1.8 ms per frame, whether the window moves or the grid scrolls; on « Statistiques » the table's prepaint takes 0.8–1.0 ms and the charts' cached paint 0.3–0.4 ms; the page's layout 0.6 ms when it renders again; the rest is GPUI's own work, in pieces under the 0.5 ms the profile records. Hovering the table costs as much as moving the window: 31 % of one core at 240 moves per second, input waiting up to 5.2 ms at the 99th percentile. Scrolling the home grid draws a frame per wheel step at 4.0 ms median and 5.8–6.0 ms at the 99th percentile. An empty page costs GPUI itself 0.76 ms at the median and 1.41 ms at the 99th percentile (« Défi » with every part hidden, under the move probe); « Défi » without the card grid, 3.58 ms at the 99th percentile. A window move calls GPUI's `Window::bounds_changed`, which refreshes the whole window and bypasses every cached view. 2 ms could not be held without simplifying the page or changing GPUI's behaviour: the user set the limit to the 1.0 value, 6 ms at the 99th percentile, to lower after 1.0 (#106).
- **Budget 2.** The cause of each wake-up, window visible and nothing drawn: GPUI's `VSyncProvider` thread (`gpui-pre-windows`, `platform.rs`) waits on `DwmFlush` at each vsync (61 wakes per second, about 0.3 % of one core) and invalidates every window with `RedrawWindow`; the UI thread then takes a `WM_PAINT` at each vsync (67 wakes per second, 0.4–0.7 %), runs GPUI's frame callback, finds nothing to draw and draws nothing. The app's own threads wake about once per second (under 0.05 %). This floor, 0.7–1.1 %, cannot be lowered without modifying GPUI (ADR-0004): as #32 provides, it became budget 2 on 2026-11-23, by the user's decision. It is lowered as soon as GPUI's floor drops (ratchet).
- **Budget 3.** Hidden in the notification area, the UI thread never wakes; GPUI's vsync thread alone still does, 61 times per second (0.24–0.29 %). Minimised, the vsync thread keeps invalidating the window (it only skips the frame signal for an iconic window) and the UI thread wakes about 89 times per second without drawing: 1.2–1.7 %, more than visible. Fixed after the benchmark: while the window is minimised, a subclass validates each `WM_PAINT` before GPUI sees it (`minimized.rs`), as GPUI has no frame to draw then. On the manual checks machine (240 Hz, for information), minimised: 3.03 % of one core before, 0.22 % after, the UI thread 469 ms then 31 ms over 21 s; to measure again on the reference machine. On the reference laptop, `b8e4927`: minimised 0.98–1.03 %, the UI thread still woken 65–66 times per second, about 85 µs per wake against about 5 µs on the manual checks machine: the paint is skipped, not the wake GPUI's vsync thread causes. Minimised now costs what visible idle does, GPUI's floor: by the user's decision, the limit is 1.1 % minimised and 0.35 % hidden. Hiding the window when minimised would remove its taskbar button and its Alt+Tab entry, and was not taken.
- **Budget 4.** With the full page loaded, the process commits about 108 MB of GPU memory, held in system memory on this integrated GPU (86–94 MB shared). Hiding parts with the profile build (`ARENA_TRACKER_HIDE`) splits the private memory: about 40 MB for the home grid's portraits, about 25 MB for the champion table, and 106 MB with both hidden, mostly GPUI's renderer (swap chain, atlases). The working set keeps 177 MB while the window is hidden. Fixed after the benchmark: the champion table read its 128 px portraits through GPUI's app-wide cache, which keeps every image it loaded; it reads them through its own `CardImages` now (`b8e4927`). On the reference laptop, the scenario's end went from 164–169 MB to 146–149 MB working set (122–123 MB private). The scenario ends on « Statistiques », where the home grid's portraits are given back: « Défi » with the grid scrolled to its end still holds 170–174 MB, and 159–163 MB at start.
- **Budget 5.** Following the client (open throughout) and importing a whole history into an empty data folder, with its 175 card portraits and splashes: the work ran on the two follower threads and the art download thread, all below normal. Threads at normal priority showed at most 1.1 % in a sample; threads born and gone between two samples (up to 5 % in a sample, priority unknown) match the short DNS thread `ureq` starts per request, which `worker.rs` already notes runs at normal priority.
- **Not measured: scrolling a champ select.** It needs a live Arena champ select in the game client; the captured one replays only in GPUI's test context, which draws nothing. Scrolling the home grid, which shares its cost structure, is the nearest value: 4.0 ms per frame at the median, 6.0 ms at the 99th percentile. To measure at the next champ select (see Measuring).
### Ratchet
@@ -33,14 +42,26 @@ A measurement means something only with its machine and build: the probes print
Budgets are checked by a **full benchmark before each major release** (X.0.0; other stables and betas run no probes): every probe below, on a release build, on the reference machine, with the results recorded in the budgets table above. Single changes are not measured, unless the user asks; a release that fails a budget is fixed before it ships, and the probes below (with `--features profile`) find the cause.
- **Window moves and idle CPU**: `powershell.exe -ExecutionPolicy Bypass -File scripts/move-probe.ps1 -Title "Arena Tracker"` from WSL, with the app open. It moves the window 240 times per second without touching the mouse, after an idle phase. `MOVE block` is the time each move holds the UI thread, close to the cost of the frame it causes; `IDLE cpu` is budget 2. Compare with File Explorer with `-Class CabinetWClass`. A real title-bar drag (Windows' modal move loop) is not covered: check it by hand.
- **Window moves and idle CPU**: `powershell.exe -ExecutionPolicy Bypass -File scripts/move-probe.ps1 -Title "Arena Tracker"` from WSL, with the app open. It moves the window 240 times per second without touching the mouse, after an idle phase. `MOVE block` is the time each move holds the UI thread, close to the cost of the frame it causes; `IDLE cpu` reads higher than budget 2, as the probe's own pings wake the UI thread: budget 2 is measured by `scripts/budget-probe.ps1` (Release benchmark scenarios, below). Compare with File Explorer with `-Class CabinetWClass`. A real title-bar drag (Windows' modal move loop) is not covered: check it by hand.
- **Champion table hover**: `powershell.exe -ExecutionPolicy Bypass -File scripts/hover-probe.ps1 -Title "Arena Tracker"` from WSL, with the « Statistiques » tab showing the table under the default band (adjust `-Top` and `-Bottom` otherwise). The app opens on « Défi »: open « Statistiques » first, as the band targets its table. After an idle phase, it posts synthetic mouse moves across table rows 240 times per second without touching the real cursor. Compare `HOVER cpu` with `IDLE cpu`; `HOVER ping` shows how long input waits behind the UI thread while hovering (budget 1). The default band is `-X 0.25 -Top 0.62 -Bottom 0.95 -Step 0.04` (fractions of the client area, about one row per move in a window at least 800 px tall). Leave the real cursor still over the window, outside the table: when it is outside the window, GPUI sees each synthetic move as the mouse entering then leaving, and refreshes the whole window, bypassing cached views.
- **Where a frame goes**: build with `scripts/prod build --features profile` (never for everyday use) and start the app with `ARENA_TRACKER_PROFILE=<file.csv>` (from WSL, pass it through `WSLENV`, e.g. `WSLENV=ARENA_TRACKER_PROFILE/p:ARENA_TRACKER_HIDE`). Every second it appends the frames GPUI drew (`draw`: total, `request_layout`, `prepaint`, `paint` in ms), their presentation (`present`) and the views' own time (`view`, recorded by GPUI from 0.5 ms). `ARENA_TRACKER_HIDE=<parts>`, read at start, removes parts of the page so that a part's cost is the difference with the full page under the hover probe: `header`, `banners` (both tabs), then for « Statistiques » `statistics-title` (the page title), `tiles`, `placements`, `completed`, `attempts` (the three charts keep their height), `tabs`, `table`, and for « Défi » `banner` (the banner, on the home and during a champ select: ring, Season, counter-title, its two lines and the splash; it replaces `home-header`, and is not `banners`, the status messages), `home-tools` (the heading row: title, count, filters and search), `cards` (the card grid), and during an Arena champ select `anvil` (the Anvil champions heading and row, which take the place of `home-tools` and `cards`), then `others` (the « Autres champions » section: its header and, when open, its search and grid).
- **Memory**: working set of `arena-tracker.exe` in Task Manager, or `Get-Process arena-tracker` in PowerShell, once the page is fully loaded.
- **CI cannot check budgets**: its runner is Linux without a GPU, and the app only builds on Windows (ADR-0003). When a change relies on cached views to stay within budget, a structural test (for example, "hovering the table does not render the charts") guards it instead of a timed test. The charts row is a cached view (#31), and « Défi » never renders it (a structural test guards that too). The home's card grid is the second (#72) and the « Autres champions » grid, while the section is open, the third: their size comes from their style, and structural tests check that hovering outside it does not render its cards and that hovering or scrolling it recomputes no statistics. Each card grid reads its portraits through its own image cache, never GPUI's app-wide one, and keeps only those of the cards it paints (#77): structural tests check that scrolling drops the others, from the GPU atlas too, and that hovering outside the grid drops none; a grid that stops being shown (the home grid under « Statistiques » or during a champ select, the Anvil champions row once it ends) gives all its portraits back. The banner's ring is the fourth (#84), as wide as the window width gives: structural tests check that hovering or scrolling the grid draws it again only for the tick that lights up or goes out, that drawing it alone neither draws the grid nor builds a card, and that its fixed shapes are tessellated once per set of ticks and size, a hover tessellating only the lit tick and a scroll that moves it none. The banner decodes its splash itself, never through GPUI's app-wide cache, one at a time on GPUI's low-priority queue at below-normal thread priority: structural tests check that it holds two at most (the one shown and the one decoding; a splash asked for meanwhile waits), gives back the one replaced, from the GPU atlas too, and holds none under « Statistiques », behind « Paramètres » (with the grids' portraits), scrolled out of view in a low window, or without an illustration. A cached view is laid out from its style alone, never its content, so only a part whose size does not depend on its content can be one. A view that is not cached renders again with its parent and saves nothing, while its state must be kept in sync; a window move bypasses every cache.
- **Memory**: working set of `arena-tracker.exe` in Task Manager, or `Get-Process arena-tracker` in PowerShell, once the page is fully loaded; for budget 4, the memory scenario below.
- **CI cannot check budgets**: its runner is Linux without a GPU, and the app only builds on Windows (ADR-0003). When a change relies on cached views to stay within budget, a structural test (for example, "hovering the table does not render the charts") guards it instead of a timed test. The charts row is a cached view (#31), and « Défi » never renders it (a structural test guards that too). The home's card grid is the second (#72) and the « Autres champions » grid, while the section is open, the third: their size comes from their style, and structural tests check that hovering outside it does not render its cards and that hovering or scrolling it recomputes no statistics. The champ select scrolls as one page: the « Autres champions » grid is as tall as all its rows and holds no scrolling of its own, it builds only the rows the page's scrolling has in view (read at its own render, after the page's scrolling is held within its content), and a structural test checks that a scroll to the end builds at most a few rows of cards. A grid wholly below the window keeps its first row built, for the keyboard to enter by (the page then scrolls to the card focused). Scrolling is no longer free of the page, though: a cached view is reused only while its bounds stay the same, and a scroll moves them, so each wheel step renders the page and draws again the ring, the Anvil hand and the « Autres champions » grid (as it already did in a window too short for the column); the scrollbar is its own view, so its fade draws no more than itself. The release benchmark must measure scrolling a champ select, and ratchet or fix the cost it finds. Each card grid reads its portraits through its own image cache, never GPUI's app-wide one, and keeps only those of the cards it paints (#77): structural tests check that scrolling drops the others, from the GPU atlas too, and that hovering outside the grid drops none; a grid that stops being shown (the home grid under « Statistiques » or during a champ select, the Anvil champions row once it ends) gives all its portraits back. The banner's ring is the fourth (#84), as wide as the window width gives: structural tests check that hovering or scrolling the grid draws it again only for the tick that lights up or goes out, that drawing it alone neither draws the grid nor builds a card, and that its fixed shapes are tessellated once per set of ticks and size, a hover tessellating only the lit tick and a scroll that moves it none. The banner decodes its splash itself, never through GPUI's app-wide cache, one at a time on GPUI's low-priority queue at below-normal thread priority: structural tests check that it holds two at most (the one shown and the one decoding; a splash asked for meanwhile waits), gives back the one replaced, from the GPU atlas too, and holds none under « Statistiques », behind « Paramètres » (with the grids' portraits), scrolled out of view in a low window, or without an illustration. A cached view is laid out from its style alone, never its content, so only a part whose size does not depend on its content can be one. A view that is not cached renders again with its parent and saves nothing, while its state must be kept in sync; a window move bypasses every cache.
GPUI and gpui-component are not modified to meet a budget: the app's own rendering cost is the lever (ADR-0004).
### Release benchmark scenarios
The release benchmark runs these scenarios, in this order, on the reference machine (#32). Builds come from `scripts/prod build`, then `scripts/prod build --features profile`; each `arena-tracker.exe` is copied out of the target directory before the next build overwrites it, and started from that copy. `scripts/budget-probe.ps1` (from WSL: `powershell.exe -ExecutionPolicy Bypass -File scripts/budget-probe.ps1 <action>`) reads the app's own counters (process CPU time, each thread's CPU time and context switches, process GPU time and memory), never system-wide ones, and drives the window with posted messages.
- **Conditions.** Each probe prints the machine and the build first: check the CPU is the Ryzen 5 7640U and the build is the copy meant. The laptop is on mains power, the user is away (`info` prints the time since their last input) and no game runs; stop and wait otherwise. The data folder (`%APPDATA%\arena-tracker`) holds a Riot key, the imported Matches and the portraits: an empty page measures nothing. Each phase lasts under a minute; split a longer scenario into phases.
- **Idle, window visible (budget 2).** Start the release build, wait 30 s, `front`, then `cursor -X 0.5 -Y 0.012` (the real cursor still over the title). Run `sample -Seconds 30` twice on « Défi » and once on « Statistiques » (`click -X 0.095 -Y 0.068`; « Défi » is at `-X 0.03`). The budget is the process CPU; the table names each thread waking. The `IDLE cpu` line of the move and hover probes is not this budget: their ping thread wakes the UI thread hundreds of times per second.
- **Interactions (budget 1).** On « Défi »: the move probe with `-Seconds 20`, then `wheel -X 0.5 -Y 0.75 -Count 300` (300 steps down at 20 per second) and the same with `-Delta 120` back up. On « Statistiques »: the hover probe and the move probe, `-Seconds 20` each. Then again on the profile build, started with `ARENA_TRACKER_PROFILE`, noting the CSV's line count at each phase's start and end to cut it into phases.
- **Minimised and hidden (budget 3).** `minimize`, wait 3 s, `sample -Seconds 30` twice; `restore`, then `close` (the window goes to the notification area, as `close_to_tray` is on), wait 3 s, `sample -Seconds 30`. Starting the app again shows the window again. On the profile build, the CSV shows no frame drawn during these phases.
- **Memory, full page loaded (budget 4).** From a fresh start, wait 15 s, `front`; scroll the home grid to its end (`wheel -X 0.5 -Y 0.75 -Count 150`), open « Statistiques » and scroll the table to its end (`wheel -X 0.5 -Y 0.85 -Count 120`), wait 10 s, then `memory`. Run it twice. To split the memory, the profile build runs the same scenario with `ARENA_TRACKER_HIDE` set to `cards`, `banner`, then `table,cards`.
- **Background work (budget 5).** Stop the app, copy `config.toml` and `seasons.toml` to an empty `<folder>\arena-tracker`, and start the release build with `APPDATA=<folder>` while the game client runs and is signed in: the app imports the whole history and downloads the portraits and splashes. Run `trace -Seconds 50` from the start, then again until the page shows the Matches imported. A sample's process CPU must stay under 100 % (one core), and the CPU must go to the `low` column. Delete the folder afterwards: it holds a copy of the Riot key.
- **Scrolling a champ select.** During a live Arena champ select, with « Autres champions » open: the profile build, then `wheel -X 0.5 -Y 0.75 -Count 100` down and the same back up, 20 steps per second, in two phases. The frames per wheel step and their cost are the figures, as for the home grid.
### Animations and splashes
The identity (ring, banner, animations; `docs/interface.md`) follows the same rule:
+1 -1
View File
@@ -52,7 +52,7 @@ Pour une cible 1.1.0, les bêtas reçoivent les versions 1.1.0-beta.1, 1.1.0-bet
## Publier une stable
1. Choisir le commit de develop à livrer, en général celui de la dernière bêta validée. Pour une **version majeure** (X.0.0), le feu vert dépend du benchmark complet de [docs/performance.md](performance.md) (#32) : toutes les sondes, sur une version de production de ce commit, sur la machine de référence. Les chiffres sont consignés dans `docs/performance.md`, et un budget dépassé bloque la livraison. Les autres stables et les bêtas ne lancent pas les sondes.
1. Choisir le commit de develop à livrer, en général celui de la dernière bêta validée. Pour une **version majeure** (X.0.0), le feu vert dépend du benchmark complet de [docs/performance.md](performance.md) (#32) : toutes les sondes, sur une version de production de ce commit, sur la machine de référence. Les chiffres sont consignés dans `docs/performance.md`, et un budget dépassé bloque la livraison. Les autres stables et les bêtas ne lancent pas les sondes. Pour la 1.0, la recette, les versions essayées et ce contrôle sont consignés dans [Livraison 1.0](livraison-1.0.md).
2. Le promouvoir vers main, en fast-forward : `git push origin <commit>:refs/heads/main`, ou `git push origin origin/develop:refs/heads/main` pour le dernier commit de develop. Ni squash ni commit de fusion.
3. Attendre la fin des contrôles CI de ce push sur main.
4. Publier :
+287
View File
@@ -0,0 +1,287 @@
# Release benchmark helper for budgets 2 to 5 (issue #32, rule #1 in docs/performance.md): the
# app's own metrics only (process CPU time, per-thread CPU time and context switches, process GPU
# engine time and memory), never system-wide ones. Window lookups happen in C#: PowerShell would
# pass $null strings as "".
#
# Usage, from WSL at the repository root, with the app open (scenarios in docs/performance.md):
# powershell.exe -ExecutionPolicy Bypass -File scripts/budget-probe.ps1 info
# ... sample -Seconds 30 -Label idle CPU, GPU and memory over one phase; each thread's CPU and wakes
# ... trace -Seconds 50 -Label import one line per sample: CPU by kind of thread and priority
# ... memory working set, private bytes and GPU memory of the process
# ... front | minimize | restore | close (close hides to the notification area)
# ... click -X 0.1 -Y 0.07 posted click at fractions of the client area
# ... wheel -X 0.5 -Y 0.75 -Delta -120 -Count 150 -Rate 20
# ... cursor -X 0.5 -Y 0.012 puts the real cursor still over the window (the title)
# ... shot -Out C:\path\shot.png capture of the window's rectangle on screen
# Every phase lasts -Seconds of wall time: keep it under a minute and split longer scenarios.
param(
[Parameter(Position = 0)][string]$Action = 'info',
[double]$Seconds = 30,
[string]$Label = '',
[double]$X = 0.5,
[double]$Y = 0.5,
[int]$Delta = -120,
[int]$Count = 1,
[double]$Rate = 20,
[string]$Out = ''
)
$ErrorActionPreference = 'Stop'
# The output is usually read from WSL, which expects UTF-8 (the file itself has a BOM for the
# same reason: Windows PowerShell 5.1 reads scripts without one as ANSI).
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
Add-Type -ReferencedAssemblies System.Drawing -Language CSharp -TypeDefinition @'
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
public static class BudgetProbe {
[StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }
[StructLayout(LayoutKind.Sequential)] public struct POINT { public int X, Y; }
[StructLayout(LayoutKind.Sequential)] struct LASTINPUTINFO { public uint cbSize; public uint dwTime; }
delegate bool EnumProc(IntPtr h, IntPtr l);
[DllImport("user32.dll")] static extern bool EnumWindows(EnumProc cb, IntPtr l);
[DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern IntPtr GetPropW(IntPtr h, string name);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] static extern int GetWindowTextW(IntPtr h, StringBuilder s, int n);
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr h);
[DllImport("user32.dll")] static extern bool IsIconic(IntPtr h);
[DllImport("user32.dll")] static extern bool ShowWindow(IntPtr h, int cmd);
[DllImport("user32.dll")] static extern bool SetForegroundWindow(IntPtr h);
[DllImport("user32.dll")] static extern bool GetClientRect(IntPtr h, out RECT r);
[DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr h, out RECT r);
[DllImport("user32.dll")] static extern bool ClientToScreen(IntPtr h, ref POINT p);
[DllImport("user32.dll")] static extern bool PostMessageW(IntPtr h, uint m, IntPtr w, IntPtr l);
[DllImport("user32.dll")] static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll")] static extern bool GetLastInputInfo(ref LASTINPUTINFO info);
[DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
// Seconds since the user last touched the keyboard or mouse: measuring waits while they use
// the machine.
public static double UserIdleSeconds() {
var info = new LASTINPUTINFO(); info.cbSize = 8; GetLastInputInfo(ref info);
return (Environment.TickCount - (int)info.dwTime) / 1000.0;
}
// The app's main window, shown or hidden: the window of an arena-tracker process carrying the
// single-instance marker, else the one titled "Arena Tracker".
public static IntPtr Find() {
var pids = new HashSet<uint>();
foreach (var p in Process.GetProcessesByName("arena-tracker")) pids.Add((uint)p.Id);
IntPtr marked = IntPtr.Zero, titled = IntPtr.Zero;
EnumWindows((h, l) => {
uint pid; GetWindowThreadProcessId(h, out pid);
if (!pids.Contains(pid)) return true;
if (GetPropW(h, "nessar.arena-tracker.main-window") != IntPtr.Zero) { marked = h; return false; }
var title = new StringBuilder(256); GetWindowTextW(h, title, 256);
if (title.ToString() == "Arena Tracker" && titled == IntPtr.Zero) titled = h;
return true;
}, IntPtr.Zero);
return marked != IntPtr.Zero ? marked : titled;
}
public static IntPtr Need() {
var h = Find();
if (h == IntPtr.Zero) throw new Exception("Erreur : aucune fenêtre Arena Tracker.");
return h;
}
public static uint Pid(IntPtr h) { uint pid; GetWindowThreadProcessId(h, out pid); return pid; }
public static uint UiThread(IntPtr h) { uint pid; return GetWindowThreadProcessId(h, out pid); }
public static string State(IntPtr h) {
RECT r; GetClientRect(h, out r);
return String.Format("pid {0}, UI thread {1}, visible {2}, minimised {3}, client {4}x{5}",
Pid(h), UiThread(h), IsWindowVisible(h), IsIconic(h), r.Right, r.Bottom);
}
public static void Show(IntPtr h, int cmd) { ShowWindow(h, cmd); }
public static void Front(IntPtr h) { ShowWindow(h, 9 /* SW_RESTORE */); SetForegroundWindow(h); }
public static void Close(IntPtr h) { PostMessageW(h, 0x0010 /* WM_CLOSE */, IntPtr.Zero, IntPtr.Zero); }
static POINT ClientPoint(IntPtr h, double fx, double fy) {
RECT r; GetClientRect(h, out r);
var p = new POINT(); p.X = (int)(r.Right * fx); p.Y = (int)(r.Bottom * fy);
return p;
}
static IntPtr LParam(int x, int y) { return new IntPtr((x & 0xffff) | ((y & 0xffff) << 16)); }
public static void Click(IntPtr h, double fx, double fy) {
var p = ClientPoint(h, fx, fy);
PostMessageW(h, 0x0200 /* WM_MOUSEMOVE */, IntPtr.Zero, LParam(p.X, p.Y));
Thread.Sleep(30);
PostMessageW(h, 0x0201 /* WM_LBUTTONDOWN */, new IntPtr(1), LParam(p.X, p.Y));
Thread.Sleep(30);
PostMessageW(h, 0x0202 /* WM_LBUTTONUP */, IntPtr.Zero, LParam(p.X, p.Y));
}
public static void Cursor(IntPtr h, double fx, double fy) {
var p = ClientPoint(h, fx, fy); ClientToScreen(h, ref p); SetCursorPos(p.X, p.Y);
}
// WM_MOUSEWHEEL carries screen coordinates.
public static void Wheel(IntPtr h, double fx, double fy, int delta, int count, double rate) {
var p = ClientPoint(h, fx, fy); ClientToScreen(h, ref p);
for (int i = 0; i < count; i++) {
PostMessageW(h, 0x020A, new IntPtr((delta & 0xffff) << 16), LParam(p.X, p.Y));
Thread.Sleep((int)(1000 / rate));
}
}
public static void Shot(IntPtr h, string path) {
RECT r; GetWindowRect(h, out r);
using (var bitmap = new Bitmap(r.Right - r.Left, r.Bottom - r.Top)) {
using (var g = Graphics.FromImage(bitmap)) g.CopyFromScreen(r.Left, r.Top, 0, 0, bitmap.Size);
bitmap.Save(path, System.Drawing.Imaging.ImageFormat.Png);
}
}
}
'@
[BudgetProbe]::SetProcessDPIAware() | Out-Null
# Raw counters of the process: CPU time, each thread's CPU time (100 ns units), context switches
# and priorities, GPU engine running time and memory.
function Snapshot($procId) {
$p = Get-Process -Id $procId
$threads = @{}
foreach ($t in Get-CimInstance Win32_PerfRawData_PerfProc_Thread -Filter "IDProcess=$procId") {
$threads[[uint32]$t.IDThread] = $t
}
$gpu = 0
foreach ($e in Get-CimInstance Win32_PerfRawData_GPUPerformanceCounters_GPUEngine -Filter "Name LIKE 'pid_$($procId)_%'") {
$gpu += [double]$e.RunningTime
}
[pscustomobject]@{
At = [Diagnostics.Stopwatch]::GetTimestamp(); Cpu = $p.TotalProcessorTime.TotalMilliseconds
Threads = $threads; GpuMs = $gpu / 10000.0; Ws = $p.WorkingSet64; Private = $p.PrivateMemorySize64
Count = $p.Threads.Count
}
}
function Seconds($a, $b) { ($b.At - $a.At) / [Diagnostics.Stopwatch]::Frequency }
# A measurement only means something on a known machine and build (docs/performance.md).
function Machine($procId) {
$cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name.Trim()
$game = [bool](Get-Process 'League of Legends' -ErrorAction SilentlyContinue)
"Machine: $cpu; user idle for $([Math]::Round([BudgetProbe]::UserIdleSeconds())) s; game running: $game"
if ($procId) { "Build: $((Get-Process -Id $procId).Path)" }
}
function Memory($procId) {
$p = Get-Process -Id $procId
$g = Get-CimInstance Win32_PerfRawData_GPUPerformanceCounters_GPUProcessMemory -Filter "Name LIKE 'pid_$($procId)_%'"
"Memory: working set {0:F1} MB, private {1:F1} MB, peak working set {2:F1} MB; GPU shared {3:F1} MB, dedicated {4:F1} MB, committed {5:F1} MB" -f `
($p.WorkingSet64 / 1MB), ($p.PrivateMemorySize64 / 1MB), ($p.PeakWorkingSet64 / 1MB),
(($g | Measure-Object SharedUsage -Sum).Sum / 1MB), (($g | Measure-Object DedicatedUsage -Sum).Sum / 1MB),
(($g | Measure-Object TotalCommitted -Sum).Sum / 1MB)
}
function AppPid() {
$h = [BudgetProbe]::Find()
if ($h -ne [IntPtr]::Zero) { return [BudgetProbe]::Pid($h) }
$p = Get-Process arena-tracker -ErrorAction SilentlyContinue | Select-Object -First 1
if (-not $p) { throw "Erreur : Arena Tracker n'est pas lancé." }
$p.Id
}
switch ($Action) {
'info' {
$procId = AppPid
Machine $procId
$h = [BudgetProbe]::Find()
if ($h -ne [IntPtr]::Zero) { "Window: $([BudgetProbe]::State($h))" }
Memory $procId
}
'memory' { Memory (AppPid) }
'sample' {
$procId = AppPid
Machine $procId
$h = [BudgetProbe]::Need(); $ui = [BudgetProbe]::UiThread($h)
"Window: $([BudgetProbe]::State($h))"
$a = Snapshot $procId
Start-Sleep -Milliseconds ([int]($Seconds * 1000))
$b = Snapshot $procId
$s = Seconds $a $b; $cpu = $b.Cpu - $a.Cpu
"[$Label] over {0:F1} s: process CPU {1:F0} ms ({2:F2}% of one core), GPU {3:F1} ms, working set {4:F1} MB, private {5:F1} MB, {6} threads" -f `
$s, $cpu, ($cpu / ($s * 10)), ($b.GpuMs - $a.GpuMs), ($b.Ws / 1MB), ($b.Private / 1MB), $b.Count
# Wakes are context switches: a thread waking 60 times a second follows the display.
$rows = foreach ($id in $b.Threads.Keys) {
$tb = $b.Threads[$id]; $ta = $a.Threads[$id]
$cpu0 = 0; $wakes0 = 0
if ($ta) { $cpu0 = [double]$ta.PercentProcessorTime; $wakes0 = [double]$ta.ContextSwitchesPersec }
$wakes = [double]$tb.ContextSwitchesPersec - $wakes0
[pscustomobject]@{
Thread = $id; UI = ($id -eq $ui); CpuMs = [Math]::Round(([double]$tb.PercentProcessorTime - $cpu0) / 10000.0, 1)
Wakes = $wakes; PerSecond = [Math]::Round($wakes / $s, 1)
BasePriority = $tb.PriorityBase; CurrentPriority = $tb.PriorityCurrent; New = (-not $ta)
}
}
$rows | Where-Object { $_.Wakes -gt 0 -or $_.CpuMs -gt 0 } | Sort-Object CpuMs, Wakes -Descending |
Format-Table -AutoSize | Out-String -Width 200
"Threads without activity: $(@($rows | Where-Object { $_.Wakes -eq 0 -and $_.CpuMs -eq 0 }).Count)"
}
'trace' {
# One line per sample, each about 2 to 3 s apart (the counter queries take time): process
# CPU, then CPU by kind of thread. ui = the window's thread; vsync = a thread at current
# priority 15 waking more than 40 times a second (GPUI's VSyncProvider); low = base
# priority below normal; normal = the others. "unseen" is CPU of threads born and gone
# between two samples, whose priority is unknown.
$procId = AppPid
Machine $procId
$h = [BudgetProbe]::Find(); $ui = 0
if ($h -ne [IntPtr]::Zero) { $ui = [BudgetProbe]::UiThread($h) }
$prev = Snapshot $procId
$deadline = $prev.At + [long]($Seconds * [Diagnostics.Stopwatch]::Frequency)
$low = 0; $normal = 0; $maxProcess = 0; $maxThread = 0; $normalThreads = @{}
while ([Diagnostics.Stopwatch]::GetTimestamp() -lt $deadline) {
Start-Sleep -Milliseconds 1000
$cur = Snapshot $procId
$s = Seconds $prev $cur
$process = ($cur.Cpu - $prev.Cpu) / ($s * 10)
$kind = @{ ui = 0.0; vsync = 0.0; low = 0.0; normal = 0.0 }; $top = 0.0; $lowCount = 0
foreach ($id in $cur.Threads.Keys) {
$tb = $cur.Threads[$id]; $ta = $prev.Threads[$id]
$cpu0 = 0; $wakes0 = 0
if ($ta) { $cpu0 = [double]$ta.PercentProcessorTime; $wakes0 = [double]$ta.ContextSwitchesPersec }
$percent = ([double]$tb.PercentProcessorTime - $cpu0) / 100000.0 / $s
$wakes = ([double]$tb.ContextSwitchesPersec - $wakes0) / $s
if ($percent -gt $top) { $top = $percent }
if ($id -eq $ui) { $kind.ui += $percent }
elseif ($tb.PriorityCurrent -ge 15 -and $wakes -gt 40) { $kind.vsync += $percent }
elseif ([int]$tb.PriorityBase -lt 8) { $kind.low += $percent; if ($percent -gt 0) { $lowCount++ } }
else {
$kind.normal += $percent
if ($percent -gt 0) { $normalThreads[$id] = [Math]::Max([double]$normalThreads[$id], $percent) }
}
}
$unseen = [Math]::Max(0, $process - ($kind.ui + $kind.vsync + $kind.low + $kind.normal))
"process {0,5:F1}% ui {1,4:F1} vsync {2,4:F1} low {3,5:F1} ({4} threads) normal {5,4:F1} unseen {6,4:F1} top thread {7,4:F1}% working set {8:F0} MB" -f `
$process, $kind.ui, $kind.vsync, $kind.low, $lowCount, $kind.normal, $unseen, $top, ($cur.Ws / 1MB)
$low += $kind.low * $s / 100; $normal += $kind.normal * $s / 100
if ($process -gt $maxProcess) { $maxProcess = $process }
if ($top -gt $maxThread) { $maxThread = $top }
$prev = $cur
}
"[$Label] highest sample: process {0:F1}% of one core, one thread {1:F1}%; background CPU time at low priority {2:F2} s, at normal priority {3:F2} s" -f `
$maxProcess, $maxThread, $low, $normal
if ($normalThreads.Count) {
"Normal-priority threads with CPU (thread: highest %): " + (($normalThreads.GetEnumerator() | ForEach-Object { "$($_.Key): {0:F1}" -f $_.Value }) -join ', ')
}
}
'front' { [BudgetProbe]::Front([BudgetProbe]::Need()); [BudgetProbe]::State([BudgetProbe]::Need()) }
'minimize' { [BudgetProbe]::Show([BudgetProbe]::Need(), 6 <# SW_MINIMIZE #>); [BudgetProbe]::State([BudgetProbe]::Need()) }
'restore' { [BudgetProbe]::Show([BudgetProbe]::Need(), 9 <# SW_RESTORE #>); [BudgetProbe]::State([BudgetProbe]::Need()) }
'close' { [BudgetProbe]::Close([BudgetProbe]::Need()); Start-Sleep 1; [BudgetProbe]::State([BudgetProbe]::Need()) }
'click' { [BudgetProbe]::Click([BudgetProbe]::Need(), $X, $Y) }
'cursor' { [BudgetProbe]::Cursor([BudgetProbe]::Need(), $X, $Y) }
'wheel' { [BudgetProbe]::Wheel([BudgetProbe]::Need(), $X, $Y, $Delta, $Count, $Rate) }
'shot' { [BudgetProbe]::Shot([BudgetProbe]::Need(), $Out); "Saved $Out" }
default { throw "Erreur : action inconnue '$Action'." }
}