Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b145c8165e
|
||
|
|
2814ee1d33
|
No files matched your search
+8
-4
@@ -67,6 +67,10 @@ The same keys are in the user guide, [The screens](guide/07-screens.md#keyboard-
|
||||
|
||||
- **Light, dark, or the same as Windows** (Settings ▸ Theme). FrameLedger takes every colour from the theme, and every
|
||||
text is measured against what is painted under it, in both themes.
|
||||
- **Windows contrast themes** (Settings ▸ Accessibility ▸ Contrast themes) — Aquatic, Desert, Dusk, Night sky, or one
|
||||
whose colours you changed: every colour in the window becomes one of the theme's, whatever Settings ▸ Theme says, as
|
||||
soon as you turn one on, edit it or turn it off. The charts draw in its colours too, their lines and marks still told
|
||||
apart by pattern, and Settings ▸ Theme says a contrast theme is in use.
|
||||
- **The colour a game's picture lends its page** is used only as far as every text on it still reads, and never under a
|
||||
contrast theme.
|
||||
- **Windows display scaling** at any size, on every screen; **Magnifier** (Windows logo key + Plus) works as with any
|
||||
@@ -88,12 +92,14 @@ from the same translations. The documents — the user guide, this page, the leg
|
||||
reader inside a control, no two buttons in a list share a name; each thing that appears is said once, in its words;
|
||||
every page has one first-level heading and every section title a level; no chart tells two series apart by colour
|
||||
alone; a chart's keys move it and stay its own; every control that shows no text has a name; no colour is written
|
||||
into a screen; every text reads against its background in both themes and after a theme switch; **Esc** closes the
|
||||
into a screen; every text reads against its background in both themes and after a theme switch, and under Windows'
|
||||
four contrast themes and two edited ones is drawn in the theme's own colours at 4.5:1 or better; **Esc** closes the
|
||||
open dialog without an answer; **Ctrl+1** … **Ctrl+5** open the pages in their order; the program declares it follows
|
||||
each screen's scaling.
|
||||
- **By hand**: the owner's pass of 2026-11-09 above, repeated for each release that changes a screen.
|
||||
- **Not tested yet**: NVDA, JAWS, Voice Access, touch, Windows 10, and other people's PCs. They should work through the
|
||||
same Windows interface Narrator uses, but nobody has checked.
|
||||
same Windows interface Narrator uses, but nobody has checked. Contrast themes are checked by the tests above and have
|
||||
not yet been looked at on a screen.
|
||||
|
||||
## Known limitations
|
||||
|
||||
@@ -104,8 +110,6 @@ Each one with what to do instead. A barrier that is not on this list is worth re
|
||||
and the list of changes under a trend chart, and **File ▸ Export ▸ Session CSV** or **Session JSON**.
|
||||
- **In the user guide and the other documents the app shows, headings are read as ordinary text**: Windows' document
|
||||
view gives them no heading role. Their links and their order work as on any page.
|
||||
- **Windows contrast themes are not followed.** With Settings ▸ Theme on *System*, a contrast theme can give parts of
|
||||
the window the wrong colours. Choose **Light** or **Dark** there: both keep their contrast.
|
||||
- **The short messages at the bottom of the window close after four seconds**, and cannot be read again once closed. A
|
||||
screen reader is told each one as it appears.
|
||||
- **Windows' text size setting** (Settings ▸ Accessibility ▸ Text size) **is not followed.** Use display scaling
|
||||
|
||||
@@ -73,9 +73,26 @@ numeric core and does not move; the heading is the full version — corrected 20
|
||||
chart tells two series apart by colour alone any more: Compare's five sessions, the GPU's temperature and its hot spot,
|
||||
the two kinds of stutter, the two lows and the two limits each have their own line pattern, marker or hatch.
|
||||
|
||||
- **Windows contrast themes are followed** (owner decision D91). With a contrast theme on — Aquatic, Desert, Dusk, Night
|
||||
sky, or one whose colours were edited, on Windows 10 or 11 — every colour in FrameLedger's windows is one of that
|
||||
theme's, whatever Settings ▸ Theme says, and it changes the moment the theme is turned on, edited or turned off;
|
||||
Settings ▸ Theme says so under its box. Before, *System* could apply WPF UI's own high-contrast files, most of whose
|
||||
colours are a red placeholder, and the next window opened put the light or the dark theme back. The charts draw in the
|
||||
theme's colours, their patterns telling the series apart; the frame-generation, ray-tracing and upscaler chips are the
|
||||
theme's highlight and its text (WPF UI's files put the window text there, 1.26–1.78:1); a destructive button is the
|
||||
theme's own button; a pressed menu item is no longer white on white; nothing is drawn translucent, and a game's picture
|
||||
lends its page no colour, as before.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **A double-click on a chart shows all of it again**, as the user guide said; it toggled ScottPlot's render-time overlay.
|
||||
- **The capture agent's state in the title bar reads in the light theme.** It was drawn on WPF UI's fixed green, blue,
|
||||
orange and red under white — 2.78, 2.63, 2.16 and 3.68:1 — and is on the theme's own success, caution and critical
|
||||
fills now, as the notices are; its words say the state.
|
||||
- **The short messages at the bottom of the window read.** A *done* or a *warning* message was white on a fixed green or
|
||||
orange, 2.78:1 and 2.16:1 in both themes; every message is in the theme's colours now, its icon saying which kind.
|
||||
- **A destructive button's label reads in the dark theme** — Remove on a game's page, Delete in the confirmations: the
|
||||
theme's dark text on the red, 5.3:1 and 5.7:1, where white read 3.68:1.
|
||||
|
||||
### Changed
|
||||
|
||||
|
||||
@@ -210,7 +210,6 @@ a barrier is on its own page: [Accessibility](ACCESSIBILITY.md) (in the app: Hel
|
||||
- **A chart's points cannot be read one by one.** A screen reader hears its name and where its numbers are written —
|
||||
the session's figures, the tables, **File ▸ Export**; its keys move it.
|
||||
- **Windows' text size setting is not followed** — use display scaling or Magnifier.
|
||||
- **Windows contrast themes are not followed yet** — choose **Light** or **Dark** in Settings ▸ Theme.
|
||||
|
||||
## Play
|
||||
|
||||
|
||||
+43
-4
@@ -3,7 +3,7 @@
|
||||
WPF + **WPF UI (Wpf.Ui, Fluent)**. Shell = `ui:FluentWindow` with custom `ui:TitleBar`, a thin classic **Menu bar** (file-level operations), and a left **`ui:NavigationView`** (`PaneDisplayMode="LeftFluent"`) as primary navigation *(since beta.34, D86, its items use
|
||||
our copy of WPF UI 4.3.0's LeftFluent item template — `FlLeftFluentNavigationViewItemTemplate` in `Styles/FrameLedger.xaml` —
|
||||
whose only change is that the selected page keeps its label; WPF UI's animates it away, and the owner's screenshot of
|
||||
Compare showed the icon alone)*. Light/Dark/System themes via `ApplicationThemeManager` + `SystemThemeWatcher`; Mica backdrop on Windows 11 with automatic solid fallback on Windows 10. All XAML follows `16_WPFUI_SYNTAX.md` — that doc is mandatory reading before writing views.
|
||||
Compare showed the icon alone)*. Light/Dark/System themes via `ApplicationThemeManager` + `SystemThemeWatcher`; Mica backdrop on Windows 11 with automatic solid fallback on Windows 10. *(beta.35, D91: a Windows contrast theme wins over all three while it is on — §Contrast.)* All XAML follows `16_WPFUI_SYNTAX.md` — that doc is mandatory reading before writing views.
|
||||
|
||||
## Shell
|
||||
|
||||
@@ -883,7 +883,7 @@ Tail view of `ui-*.log` / `agent-*.log` (toggle), level filter, search (`ui:Auto
|
||||
> (`Settings_RemoveUninstalled_Applied`), not at the next session — the detection sweep reads it at every pass. Tests:
|
||||
> `ViewerModeTests.EverySettingTheAgentReadsIsOffInAViewer`, `GuideDocumentsTests.TheSettingsPageOfTheGuideNamesEverySetting`.
|
||||
|
||||
Sections per FR-10 using the WPF UI settings idiom: `ui:CardControl`/`ui:CardExpander` rows with `ToggleSwitch`, `ComboBox`, `ui:NumberBox` (numeric inputs — min session length, sensor interval, retention). Language switch applies immediately (09_I18N). Theme selector (Light/Dark/System) drives `ApplicationThemeManager` (16 §Theming). **Capture section (top, most important):** the global **hooking kill switch** (`ToggleSwitch`, prominent) with a one-line summary of what it does; a list of games currently hook-enabled with a per-game revoke; Vulkan layer registration state + Register/Unregister; a link to the safety documentation. Turning the global switch off must take effect immediately, including for the Vulkan layer.
|
||||
Sections per FR-10 using the WPF UI settings idiom: `ui:CardControl`/`ui:CardExpander` rows with `ToggleSwitch`, `ComboBox`, `ui:NumberBox` (numeric inputs — min session length, sensor interval, retention). Language switch applies immediately (09_I18N). Theme selector (Light/Dark/System) drives `ApplicationThemeManager` (16 §Theming) *(beta.35, D91: a Windows contrast theme wins while it is on, §Contrast, and a line under the selector says so, bound to `ContrastTheme.IsOn` so it comes and goes with the page shown)*. **Capture section (top, most important):** the global **hooking kill switch** (`ToggleSwitch`, prominent) with a one-line summary of what it does; a list of games currently hook-enabled with a per-game revoke; Vulkan layer registration state + Register/Unregister; a link to the safety documentation. Turning the global switch off must take effect immediately, including for the Vulkan layer.
|
||||
|
||||
**System (2026-09-21, FR "show the user's hardware"):** a card above Legal stating this PC as a session's hardware snapshot would record it right now — processor, graphics card, graphics driver, memory, Windows build, primary display — through the same `IHardwareSnapshotSource` the Agent stamps sessions with, read on the thread pool when the page opens, a field that could not be read as N/A, with **Copy** (the same lines as text) and a note that nothing is sent anywhere and what CPU temperature needs. Its own `SystemInfoViewModel`, not `SettingsViewModel`'s. The same snapshot is one tertiary line under the session summary's header (it was loaded for the export and shown nowhere), and `--diag` prints it; the bug bundle's `sysinfo.json` is deliberately NOT given it — its keys are the issue link's prefill.
|
||||
|
||||
@@ -1190,6 +1190,45 @@ theme's background, as it was before; the badge and the list carry its informati
|
||||
> under it, in both themes. `EveryTextFollowsAThemeSwitch` hosts its pages in the presenter too since, and went red with
|
||||
> them: a page made after a switch stayed black. All three went red on the unfixed XAML before they went green.
|
||||
|
||||
> **Windows contrast themes, followed (beta.35, owner decision D91).** WPF UI 4.3.0 cannot be asked to do it:
|
||||
> `ApplicationTheme.HighContrast` names no dictionary; its four high-contrast files (HC1 Dusk, HC2 Night sky, HCBlack
|
||||
> Aquatic, HCWhite Desert) each hold 84 red `#FFFF0000` placeholders among 97 colours and 17 brushes that throw when the
|
||||
> file is read alone; their colours are Windows 11's defaults, not the user's; and they put the window text on the accent.
|
||||
> So while `SystemParameters.HighContrast` is on, `Services/WpfThemeApplier` applies the light or the dark Fluent theme as
|
||||
> the contrast theme is (by its window colour), with no Mica and no `SystemThemeWatcher`, and `Services/ContrastOverlay`
|
||||
> over it: every key of those four files in the user's colour for its role (`Services/ContrastRoles` — a key's role is the
|
||||
> colour it has in all four, opaque colours only, because inside the App a brush that throws alone falls back to the
|
||||
> Fluent theme's translucent fill: `MenuBarItemBackgroundPressed` read as the white of the window text, and a pressed menu
|
||||
> item was white on white; ties and placeholders by the key's name), the keys transparent there transparent, three
|
||||
> Fluent-only keys by role, the 21 accent keys WPF UI writes into the application's resources as the highlight, and the
|
||||
> text on the accent as the highlight's text. The colours are `SystemColors` (`ContrastPalette.FromSystem`) — the user's
|
||||
> own, edited or not, Windows 10's as well — and turning a theme on, editing it or turning it off is followed at once
|
||||
> (`SystemContrastSource`). What the App draws itself reads `ContrastTheme.Active`: the charts (`ChartPalette.ForContrast`,
|
||||
> the theme's colours only, the series told apart by `ChartPatterns`), a badge's text (`ChartTheme.TextOn`, the theme's
|
||||
> colour that reads best on the fill), the mix bar, the artwork band (no tint), the Import list (no dimmed rows), the
|
||||
> unsigned-update footer (the secondary text style, not an opacity). WPF UI's Danger button paints a fixed `#F44336` in its
|
||||
> style, out of any resource's reach, so every `ui:Button` takes the App's implicit style (`Styles/FrameLedger.xaml`): a
|
||||
> Danger button is the theme's own button while one is on, the message boxes' Delete included. Held by `ContrastThemeTests` — the four files still placeholders; every key a role or
|
||||
> transparent, none red; the roles the same over either Fluent theme; with each default theme's own colours the overlay
|
||||
> is WPF UI's colours key for key, the text on the accent apart; an edited theme's colours reach every key; every Fluent
|
||||
> colour key covered; every resource the App reads resolves; `ThemePlan`; the applier on and off at once — and
|
||||
> `PagesLoadTests.EveryTextIsInTheContrastThemesColoursAndReadable`: every surface rendered under the four default themes
|
||||
> and two edited ones, every text the theme's colour on the theme's colour at 4.5:1 or better. It went red first on the
|
||||
> chips (window text on the highlight, 1.26–1.78:1), the Remove button (3.06–4.42:1 on `#F44336`) and the badges' black.
|
||||
|
||||
> **A sixth hole, closed 2026-11-09 (beta.35), found by measuring what no sweep renders.** The title bar and the snackbars
|
||||
> are no surface, and the 3:1 sweep let 3.68:1 pass. The capture agent's pill was a `ui:Badge` whose appearance was
|
||||
> BOUND — Success, Info, Caution, Danger, WPF UI's `Palette*Brush` under `BadgeForeground` — so `ContrastTests`, which reads
|
||||
> literal attributes, never saw it: in the light theme 2.78, 2.63, 2.16 and 3.68:1. It is `AgentPill` now (a `Pill` on
|
||||
> `SystemFillColor{Success,Caution,Critical}BackgroundBrush`, the theme's text), and a bound badge appearance is refused.
|
||||
> WPF UI's Success and Caution snackbars are fixed colours under white in both themes, 2.78:1 and 2.16:1: the strip shows
|
||||
> every message as Secondary, the theme's, 13.97:1 and 16.53:1, its icon saying the kind. And a Danger button's text was
|
||||
> the theme's button text on `#F44336` — white in the dark theme, 3.68:1: the App's implicit button style puts
|
||||
> `TextFillColorDarkPrimaryBrush` there, 5.3:1 and 5.7:1. `ContrastThemeTests.TheTitleBarsMarksReadInEveryState`,
|
||||
> `ADangerButtonReadsInBothThemesAndIsTheThemesOwnButtonUnderAContrastTheme`,
|
||||
> `NoButtonOrBadgeTakesAnAppearanceThatPaintsAFixedColour` and
|
||||
> `AnnouncementsTests.EveryMessageOfTheStripIsDrawnInTheThemesOwnColours` hold the three.
|
||||
|
||||
### DPI
|
||||
|
||||
`app.manifest` declares Per-Monitor V2 (`AccessibilityTests.TheManifestIsPerMonitorV2`). A chart reads the pointer
|
||||
@@ -1215,6 +1254,6 @@ ScottPlot reads once when the control is made, before it has a window.
|
||||
chart, the FPS readout, the RT/PT/RR chips, the game's artwork — is a Tab stop Narrator says nothing about; text inside
|
||||
a control template (the safety notices' title and message, the readout, the chips) is hidden from the control view;
|
||||
nothing is announced; no text is a heading; several charts tell series apart by colour alone~~ *(closed the same day,
|
||||
§Screen readers above)*; page transitions play with Windows' animation effects off; Windows contrast themes are not
|
||||
followed. `ACCESSIBILITY.md` §Known limitations
|
||||
§Screen readers above)*; page transitions play with Windows' animation effects off; ~~Windows contrast themes are not
|
||||
followed~~ *(followed since beta.35, D91 — §Contrast)*. `ACCESSIBILITY.md` §Known limitations
|
||||
states each to users with what to do instead.
|
||||
+27
-1
@@ -62,6 +62,7 @@ private static readonly IHost _host = Host.CreateDefaultBuilder()
|
||||
Theme rules:
|
||||
- Manual Light/Dark: `ApplicationThemeManager.Apply(ApplicationTheme.Dark)`.
|
||||
- System: `SystemThemeWatcher.Watch(mainWindow)` — call it in the window's `Loaded` handler (needs an HWND), and unwatch when switching to manual.
|
||||
- A Windows contrast theme (beta.35, D91): wins over all three while it is on, and is never left to the watcher, which would apply WPF UI's own high-contrast files (§Gotchas). `Services/ThemePlan.For` is the table, `Services/WpfThemeApplier` applies it.
|
||||
- Persist the choice in `settings`; re-apply before the main window shows to avoid a flash. **Measured 2026-09-13: this is a correctness rule, not a cosmetic one** — `ApplicationThemeManager.Apply(theme, backdrop, updateAccent: true)` is what registers the `SystemAccentColor*` resources the control templates `StaticResource` at first Measure; a `FluentWindow` shown before any `Apply` throws `XamlParseException: Cannot find resource named 'SystemAccentColorPrimary'`. The shell applies the theme in its constructor before `InitializeComponent()` and again from `Loaded` for the watcher.
|
||||
- Subscribe `ApplicationThemeManager.Changed` once, centrally, to re-theme ScottPlot (below).
|
||||
|
||||
@@ -172,6 +173,22 @@ Native `Menu`, `TabControl`, `ComboBox`, `Slider`~~, `ListView`~~ are fine — t
|
||||
WCAG contrast, black in both themes. The chart reads `ChartTheme.Current` at every render; the WPF chip in the list
|
||||
(`Controls/ChangeBadge`) follows a switch through the same resource reference as `ArtTint` and `FgMixBar`
|
||||
(`ChartPalette.ForBackground`). No colour in XAML.
|
||||
- Third exception (beta.35, D91): **a Windows contrast theme's colours**, read from `SystemColors` in one place
|
||||
(`Services/ContrastPalette.FromSystem`) and laid over the theme by `Services/ContrastOverlay` — never written in XAML. A
|
||||
colour the App works out itself reads `Services.ContrastTheme.Active` first (the charts, the badges, the artwork band);
|
||||
XAML that must change with it binds `{Binding Path=(services:ContrastTheme.IsOn)}`, a static property WPF hears through
|
||||
its `StaticPropertyChanged` event.
|
||||
- **`ui:Button Appearance="Danger"` / `Info` / `Success` / `Caution` / `Dark` / `Light` paint fixed colours** — values in
|
||||
WPF UI 4.3.0's button style (`#F44336` for Danger), not resources, so no theme and no contrast theme reaches them, under
|
||||
the theme's button text (white on the red in the dark theme, 3.68:1). Danger is the one the App uses: its implicit
|
||||
`ui:Button` style (`Styles/FrameLedger.xaml`) puts the theme's dark text on the red, and the theme's own button under a
|
||||
contrast theme — message boxes' buttons included. The other five are refused
|
||||
(`ContrastThemeTests.NoButtonOrBadgeTakesAnAppearanceThatPaintsAFixedColour`).
|
||||
- **A snackbar's appearances are fixed colours too** (`ISnackbarService.Show`): Success, Caution, Info, Danger, Primary,
|
||||
Dark and Light are values under white or black text — Success 2.78:1, Caution 2.16:1 in both themes. Only Secondary is
|
||||
the theme's: `Services/SnackbarStrip`, the one place a snackbar is shown, uses it for every message.
|
||||
- **A `ui:Badge` with a BOUND palette appearance** is the same hole as a literal one, and no XAML scan of literals sees it
|
||||
(the agent's pill, beta.35: `AgentPill` now). A bound badge appearance is refused by the same test.
|
||||
|
||||
## FlowDocument (rendered documents, beta.12)
|
||||
|
||||
@@ -242,7 +259,9 @@ On startup and on `ApplicationThemeManager.Changed`: for every live plot set fig
|
||||
> `ChartTheme.Attach` adds `Charts/ChartKeys` (arrows and A marked handled after ScottPlot's class handler has acted — an
|
||||
> instance handler runs after it) and `ResetOnDoubleClick` (`DoubleLeftClickBenchmark(false)` and a `DoubleClickResponse` on
|
||||
> the left button that autoscales). A series takes `ChartPatterns.Line` / `Points` / `Hatch` by its index — a new series
|
||||
> without one is red in `NoChartTellsTwoSeriesApartByColourAlone`.
|
||||
> without one is red in `NoChartTellsTwoSeriesApartByColourAlone`. Under a Windows contrast theme `ChartTheme.Current` is
|
||||
> `ChartPalette.ForContrast(ContrastTheme.Active)` — the theme's window under every plot, its text, link, highlight,
|
||||
> button text and disabled text for the rest — and the patterns carry the series apart (D91).
|
||||
>
|
||||
> **The trend's change markers, beta.30 (D70):** `Charts/ChangeMarkerPlottable`, an `IPlottable` + `IRenderLast` added
|
||||
> with `Add.Plottable` (which assigns no axes: the chart sets `Axes.XAxis`/`YAxis` itself), draws the dashed lines in
|
||||
@@ -264,6 +283,13 @@ On startup and on `ApplicationThemeManager.Changed`: for every live plot set fig
|
||||
- [ ] **`WpfPlot.DisplayScale` is read once, in the constructor**, from `VisualTreeHelper.GetDpi` before the control has
|
||||
a window. Read a pointer with `GetPlotPixelPosition(e)` (the element's DPI now); ScottPlot's pixels are device
|
||||
pixels while no `Plot.ScaleFactor` is set, and none is.
|
||||
- [ ] **WPF UI 4.3.0's high-contrast theme cannot be applied as it is** (beta.35, D91). `ApplicationTheme.HighContrast` has
|
||||
no dictionary (the watcher picks HC1/HC2/HCBlack/HCWhite by Windows' theme name); each of those holds 84 `#FFFF0000`
|
||||
placeholders among 97 colours and 17 brushes (`SystemFillColor*Brush`, `MenuBar*`) that throw when the file is read
|
||||
alone — inside the App their forward references fall back to the application's resources and read as the Fluent
|
||||
theme's fills; their colours are Windows 11's defaults, not the user's; their text on the accent is the window text.
|
||||
Never let `SystemThemeWatcher` watch while a contrast theme is on: it would apply them. The App reads them for each
|
||||
key's role only (§Theming & brushes; `08_UI` §Contrast).
|
||||
- [ ] `SystemThemeWatcher.Watch` after HWND exists (`Loaded`), not in the constructor — but `ApplicationThemeManager.Apply(…, updateAccent: true)` BEFORE the first window's XAML loads, or the accent resources are missing at first Measure (§App bootstrap).
|
||||
- [ ] Menu row lives **outside** `ui:TitleBar` (its area is the drag region; a Menu inside becomes undraggable/unclickable territory).
|
||||
- [ ] Don't set `AllowsTransparency`/`WindowStyle` on `FluentWindow` — it manages its own chrome.
|
||||
|
||||
@@ -41,7 +41,7 @@ The link under them, *Read what the hook does and does not do*, opens the safety
|
||||
|
||||
| Setting | What it does | Default |
|
||||
|---|---|---|
|
||||
| **Theme** | Follow system, Light or Dark. Applies at once. | Follow system |
|
||||
| **Theme** | Follow system, Light or Dark. Applies at once. While a Windows contrast theme is on, FrameLedger uses that theme's colours whatever you choose here, and says so under the box. | Follow system |
|
||||
| **Language** | English, Tiếng Việt or 日本語. The window is rebuilt in the new language at once, and stays on Settings (since 0.1.0-beta.34; before, it could open on the last game you looked at). | English |
|
||||
|
||||
## Games
|
||||
|
||||
@@ -329,6 +329,7 @@ public partial class App : System.Windows.Application
|
||||
builder.Services.AddSingleton(appearance);
|
||||
builder.Services.AddSingleton(registered);
|
||||
builder.Services.AddSingleton(closePolicy);
|
||||
builder.Services.AddSingleton<IContrastSource, SystemContrastSource>(); // beta.35 (D91): a contrast theme wins
|
||||
builder.Services.AddSingleton<IThemeApplier, WpfThemeApplier>();
|
||||
|
||||
// The Agent link, the Run entry, the Agent's maintenance flags and the updater: a viewer's composition holds none of
|
||||
|
||||
@@ -62,8 +62,26 @@ public sealed record ChartPalette(
|
||||
/// element drawn in the chart colours follows a theme switch: a resource reference to <c>ApplicationBackgroundColor</c>,
|
||||
/// read here (<c>FgMixBar</c>, <c>ChangeBadge</c>).
|
||||
/// </summary>
|
||||
public static ChartPalette ForBackground(System.Windows.Media.Color background) =>
|
||||
For(Services.ColorMath.Luminance(background) < 0.5 ? ApplicationTheme.Dark : ApplicationTheme.Light);
|
||||
public static ChartPalette ForBackground(System.Windows.Media.Color background) => Services.ContrastTheme.Active is { } contrast
|
||||
? ForContrast(contrast)
|
||||
: For(Services.ColorMath.Luminance(background) < 0.5 ? ApplicationTheme.Dark : ApplicationTheme.Light);
|
||||
|
||||
/// <summary>
|
||||
/// The palette under a Windows contrast theme (beta.35, D91): only the theme's own colours — the window under every plot,
|
||||
/// its text for the axes and the first series, then the link, the highlight, the button text and the disabled text in
|
||||
/// turn — the series told apart by their patterns as well (<see cref="ChartPatterns"/>), since a contrast theme has few.
|
||||
/// </summary>
|
||||
public static ChartPalette ForContrast(Services.ContrastPalette contrast)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(contrast);
|
||||
Color window = ChartTheme.ToScottPlot(contrast.Window);
|
||||
Color text = ChartTheme.ToScottPlot(contrast.WindowText);
|
||||
Color link = ChartTheme.ToScottPlot(contrast.HotTrack);
|
||||
Color highlight = ChartTheme.ToScottPlot(contrast.Highlight);
|
||||
Color button = ChartTheme.ToScottPlot(contrast.ButtonText);
|
||||
Color gray = ChartTheme.ToScottPlot(contrast.GrayText);
|
||||
return new ChartPalette(window, window, text, gray, text, link, highlight, link, text, link, highlight, highlight, text, button, gray, button);
|
||||
}
|
||||
|
||||
/// <summary>A palette from any dictionary carrying the keys (the tests hand in a parsed file).</summary>
|
||||
public static ChartPalette FromDictionary(ResourceDictionary dictionary)
|
||||
|
||||
@@ -20,8 +20,8 @@ public static class ChartTheme
|
||||
private static readonly Lock _lock = new();
|
||||
private static bool _subscribed;
|
||||
|
||||
/// <summary>The palette of the theme WPF UI has applied.</summary>
|
||||
public static ChartPalette Current => ChartPalette.For(ApplicationThemeManager.GetAppTheme());
|
||||
/// <summary>The palette of the theme WPF UI has applied — or, under a Windows contrast theme, of its colours (beta.35, D91).</summary>
|
||||
public static ChartPalette Current => Services.ContrastTheme.Active is { } contrast ? ChartPalette.ForContrast(contrast) : ChartPalette.For(ApplicationThemeManager.GetAppTheme());
|
||||
|
||||
/// <summary>Colours one plot for the current theme; the series keep their own palette colours.</summary>
|
||||
public static void Apply(Plot plot)
|
||||
@@ -48,7 +48,8 @@ public static class ChartTheme
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(path);
|
||||
Color figure = plot.FigureBackground.Color;
|
||||
Color data = plot.DataBackground.Color;
|
||||
Color window = ApplicationThemeManager.GetAppTheme() == ApplicationTheme.Light ? Color.FromHex("#F3F3F3") : Color.FromHex("#202020");
|
||||
Color window = Services.ContrastTheme.Active is { } contrast ? ToScottPlot(contrast.Window)
|
||||
: ApplicationThemeManager.GetAppTheme() == ApplicationTheme.Light ? Color.FromHex("#F3F3F3") : Color.FromHex("#202020");
|
||||
try
|
||||
{
|
||||
plot.FigureBackground.Color = Over(figure, window);
|
||||
@@ -70,6 +71,12 @@ public static class ChartTheme
|
||||
internal static Color TextOn(Color fill)
|
||||
{
|
||||
System.Windows.Media.Color under = ToWpf(fill);
|
||||
if (Services.ContrastTheme.Active is { } contrast)
|
||||
{
|
||||
// beta.35 (D91): under a contrast theme the text is one of its colours too — the one that reads best on the fill.
|
||||
return ToScottPlot(contrast.Colors.MaxBy(c => Services.ColorMath.Contrast(c, under)));
|
||||
}
|
||||
|
||||
return Services.ColorMath.Contrast(System.Windows.Media.Colors.Black, under) >= Services.ColorMath.Contrast(System.Windows.Media.Colors.White, under)
|
||||
? Colors.Black
|
||||
: Colors.White;
|
||||
@@ -78,6 +85,9 @@ public static class ChartTheme
|
||||
/// <summary>A chart colour as WPF's.</summary>
|
||||
internal static System.Windows.Media.Color ToWpf(Color c) => System.Windows.Media.Color.FromArgb(c.A, c.R, c.G, c.B);
|
||||
|
||||
/// <summary>A WPF colour as ScottPlot draws it (a contrast theme's colours, beta.35).</summary>
|
||||
internal static Color ToScottPlot(System.Windows.Media.Color c) => new(c.R, c.G, c.B, c.A);
|
||||
|
||||
/// <summary>Source-over: <paramref name="top"/> composited on an opaque <paramref name="under"/>.</summary>
|
||||
internal static Color Over(Color top, Color under)
|
||||
{
|
||||
|
||||
@@ -96,7 +96,7 @@ public static class ArtTint
|
||||
return;
|
||||
}
|
||||
|
||||
if (GetColor(band) is { } dominant && !SystemParameters.HighContrast && BandColour(band, dominant) is { } colour)
|
||||
if (GetColor(band) is { } dominant && !SystemParameters.HighContrast && Services.ContrastTheme.Active is null && BandColour(band, dominant) is { } colour)
|
||||
{
|
||||
var brush = new SolidColorBrush(colour);
|
||||
brush.Freeze();
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
<DataGrid.RowStyle>
|
||||
<Style TargetType="DataGridRow" BasedOn="{StaticResource DefaultDataGridRowStyle}">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsExisting}" Value="True">
|
||||
<DataTrigger Binding="{Binding IsDimmed}" Value="True">
|
||||
<Setter Property="Opacity" Value="0.55" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
|
||||
@@ -53,10 +53,10 @@
|
||||
Content="{x:Static res:Strings.Alpha_Badge}"
|
||||
ToolTip="{Binding ViewModel.AlphaBadgeTooltip}"
|
||||
Visibility="{Binding ViewModel.IsAlpha, Mode=OneTime, Converter={StaticResource BoolToVis}}" />
|
||||
<ui:Badge Margin="0,0,12,0"
|
||||
VerticalAlignment="Center"
|
||||
Appearance="{Binding ViewModel.AgentStatusAppearance}"
|
||||
Content="{Binding ViewModel.AgentStatusText}" />
|
||||
<!-- beta.35: the theme's own fills under its text, never WPF UI's palette badge (Styles/FrameLedger.xaml, AgentPill). -->
|
||||
<Border DataContext="{Binding ViewModel}" Style="{StaticResource AgentPill}">
|
||||
<TextBlock Foreground="{DynamicResource TextFillColorPrimaryBrush}" Text="{Binding AgentStatusText}" />
|
||||
</Border>
|
||||
</StackPanel>
|
||||
</ui:TitleBar.TrailingContent>
|
||||
</ui:TitleBar>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
xmlns:res="clr-namespace:FrameLedger.App"
|
||||
xmlns:services="clr-namespace:FrameLedger.App.Services"
|
||||
xmlns:vm="clr-namespace:FrameLedger.App.ViewModels"
|
||||
Title="{x:Static res:Strings.Settings_Header}"
|
||||
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
|
||||
@@ -290,6 +291,10 @@
|
||||
SelectedValue="{Binding ViewModel.SelectedTheme, Mode=TwoWay}"
|
||||
SelectedValuePath="Value" />
|
||||
</ui:CardControl>
|
||||
<!-- beta.35 (D91): a Windows contrast theme's colours win; this says so while one is on, and goes when it is off. -->
|
||||
<ui:TextBlock Margin="12,4,0,0" Style="{StaticResource SecondaryText}" TextWrapping="Wrap"
|
||||
Text="{x:Static res:Strings.Settings_Theme_ContrastOn}"
|
||||
Visibility="{Binding Path=(services:ContrastTheme.IsOn), Converter={StaticResource BoolToVis}}" />
|
||||
<ui:CardControl Margin="0,8,0,0" Header="{x:Static vm:SettingsViewModel.LanguageLabel}" Icon="{ui:SymbolIcon LocalLanguage24}">
|
||||
<ComboBox MinWidth="180"
|
||||
AutomationProperties.Name="{x:Static vm:SettingsViewModel.LanguageLabel}"
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// A contrast theme's colours over the App's Fluent theme (beta.35, D91): every WPF UI theme resource given the user's colour
|
||||
/// for its role (<see cref="ContrastRoles"/>), as one merged dictionary on top of the theme — the light or the dark one, as
|
||||
/// the contrast theme is light or dark — and the accent's resources, which WPF UI's accent manager writes straight into the
|
||||
/// application's resources and which outrank any merged dictionary, written there too. Removing it leaves the Fluent theme;
|
||||
/// <c>ApplicationThemeManager.Apply(…, updateAccent: true)</c> then writes the accent back.
|
||||
/// </summary>
|
||||
public static class ContrastOverlay
|
||||
{
|
||||
/// <summary>
|
||||
/// The accent's resources: the 21 WPF UI 4.3.0's <c>ApplicationAccentColorManager</c> sets in the application's own
|
||||
/// resources (measured 2026-11-09), each with its role.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> AccentKeys { get; } = new Dictionary<string, (ContrastRole, bool)>(StringComparer.Ordinal)
|
||||
{
|
||||
["SystemAccentColor"] = (ContrastRole.Highlight, false),
|
||||
["SystemAccentColorPrimary"] = (ContrastRole.Highlight, false),
|
||||
["SystemAccentColorSecondary"] = (ContrastRole.Highlight, false),
|
||||
["SystemAccentColorTertiary"] = (ContrastRole.Highlight, false),
|
||||
["SystemAccentBrush"] = (ContrastRole.Highlight, true),
|
||||
["SystemFillColorAttentionBrush"] = (ContrastRole.Highlight, true),
|
||||
["AccentFillColorDefault"] = (ContrastRole.Highlight, false),
|
||||
["AccentFillColorSecondary"] = (ContrastRole.Highlight, false),
|
||||
["AccentFillColorTertiary"] = (ContrastRole.Highlight, false),
|
||||
["AccentFillColorDefaultBrush"] = (ContrastRole.Highlight, true),
|
||||
["AccentFillColorSecondaryBrush"] = (ContrastRole.Highlight, true),
|
||||
["AccentFillColorTertiaryBrush"] = (ContrastRole.Highlight, true),
|
||||
["AccentFillColorSelectedTextBackgroundBrush"] = (ContrastRole.Highlight, true),
|
||||
["AccentTextFillColorPrimaryBrush"] = (ContrastRole.HotTrack, true),
|
||||
["AccentTextFillColorSecondaryBrush"] = (ContrastRole.HotTrack, true),
|
||||
["AccentTextFillColorTertiaryBrush"] = (ContrastRole.HotTrack, true),
|
||||
["AccentTextFillColorDisabled"] = (ContrastRole.GrayText, false),
|
||||
["TextOnAccentFillColorPrimary"] = (ContrastRole.HighlightText, false),
|
||||
["TextOnAccentFillColorSecondary"] = (ContrastRole.HighlightText, false),
|
||||
["TextOnAccentFillColorSelectedText"] = (ContrastRole.HighlightText, false),
|
||||
["TextOnAccentFillColorDisabled"] = (ContrastRole.GrayText, false),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The colours of WPF UI 4.3.0's Fluent themes that none of its contrast dictionaries has (measured 2026-11-09), each with a
|
||||
/// role: the navigation pane's separator, a gradient there, a line in the window text; the snowflake effect's two, the window.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> FluentOnlyKeys { get; } = new Dictionary<string, (ContrastRole, bool)>(StringComparer.Ordinal)
|
||||
{
|
||||
["LeftNavigationViewSeparatorBrush"] = (ContrastRole.WindowText, true),
|
||||
["SnowflakeGradientTop"] = (ContrastRole.Window, false),
|
||||
["SnowflakeGradientBottom"] = (ContrastRole.Window, false),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The text on the accent, which the overlay makes the highlight: the highlight's text. WPF UI's contrast dictionaries make
|
||||
/// it the window text over an accent they leave as Windows' (measured 2026-11-09: white on Dusk's highlight, 1.62:1, in
|
||||
/// every chip the App draws on the accent), so these are the App's roles, not inferred ones.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> OnAccentKeys { get; } = new Dictionary<string, (ContrastRole, bool)>(StringComparer.Ordinal)
|
||||
{
|
||||
["TextOnAccentFillColorPrimary"] = (ContrastRole.HighlightText, false),
|
||||
["TextOnAccentFillColorPrimaryBrush"] = (ContrastRole.HighlightText, true),
|
||||
["TextOnAccentFillColorSecondary"] = (ContrastRole.HighlightText, false),
|
||||
["TextOnAccentFillColorSecondaryBrush"] = (ContrastRole.HighlightText, true),
|
||||
["TextOnAccentFillColorSelectedText"] = (ContrastRole.HighlightText, false),
|
||||
["TextOnAccentFillColorSelectedTextBrush"] = (ContrastRole.HighlightText, true),
|
||||
};
|
||||
|
||||
/// <summary>The overlay: every role-mapped key in the palette's colour for its role, and the transparent keys transparent.</summary>
|
||||
public static ResourceDictionary Build(ContrastPalette palette)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(palette);
|
||||
var overlay = new Overlay();
|
||||
foreach ((string key, (ContrastRole role, bool brush)) in ContrastRoles.Map)
|
||||
{
|
||||
overlay[key] = Value(palette.Of(role), brush);
|
||||
}
|
||||
|
||||
foreach ((string key, (ContrastRole role, bool brush)) in OnAccentKeys)
|
||||
{
|
||||
overlay[key] = Value(palette.Of(role), brush);
|
||||
}
|
||||
|
||||
foreach ((string key, bool brush) in ContrastRoles.Clear)
|
||||
{
|
||||
overlay[key] = Value(Colors.Transparent, brush);
|
||||
}
|
||||
|
||||
foreach ((string key, (ContrastRole role, bool brush)) in FluentOnlyKeys.Where(k => !overlay.Contains(k.Key)))
|
||||
{
|
||||
overlay[key] = Value(palette.Of(role), brush);
|
||||
}
|
||||
|
||||
return overlay;
|
||||
}
|
||||
|
||||
/// <summary>Puts the palette over <paramref name="resources"/> (the application's), replacing an earlier overlay.</summary>
|
||||
public static void Install(ResourceDictionary resources, ContrastPalette palette)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(resources);
|
||||
ArgumentNullException.ThrowIfNull(palette);
|
||||
TakeOff(resources);
|
||||
ContrastTheme.Active = palette;
|
||||
resources.MergedDictionaries.Add(Build(palette));
|
||||
foreach ((string key, (ContrastRole role, bool brush)) in AccentKeys)
|
||||
{
|
||||
resources[key] = Value(palette.Of(role), brush);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Takes the overlay away; the accent's own resources are the theme manager's to write back.</summary>
|
||||
public static void Remove(ResourceDictionary resources)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(resources);
|
||||
TakeOff(resources);
|
||||
ContrastTheme.Active = null;
|
||||
}
|
||||
|
||||
/// <summary>Whether an overlay is on <paramref name="resources"/>.</summary>
|
||||
public static bool IsInstalled(ResourceDictionary resources)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(resources);
|
||||
return resources.MergedDictionaries.OfType<Overlay>().Any();
|
||||
}
|
||||
|
||||
// The overlays only: a palette replaced by another is never "off" in between.
|
||||
private static void TakeOff(ResourceDictionary resources)
|
||||
{
|
||||
foreach (ResourceDictionary overlay in resources.MergedDictionaries.OfType<Overlay>().ToList())
|
||||
{
|
||||
_ = resources.MergedDictionaries.Remove(overlay);
|
||||
}
|
||||
}
|
||||
|
||||
private static object Value(Color colour, bool brush)
|
||||
{
|
||||
if (!brush)
|
||||
{
|
||||
return colour;
|
||||
}
|
||||
|
||||
var solid = new SolidColorBrush(colour);
|
||||
solid.Freeze();
|
||||
return solid;
|
||||
}
|
||||
|
||||
/// <summary>The overlay's own type, so it can be found and taken away again.</summary>
|
||||
private sealed class Overlay : ResourceDictionary;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// A Windows contrast theme's colours (beta.35, D91): the eight the user sees — and may edit — in Settings ▸ Accessibility ▸
|
||||
/// Contrast themes. <see cref="FromSystem"/> reads the ones Windows has on now; a test builds its own.
|
||||
/// </summary>
|
||||
public sealed record ContrastPalette(Color Window, Color WindowText, Color Highlight, Color HighlightText, Color HotTrack, Color GrayText, Color ButtonFace, Color ButtonText)
|
||||
{
|
||||
/// <summary>The theme Windows has on now — the user's colours, edited or not, on Windows 10 and 11 alike.</summary>
|
||||
public static ContrastPalette FromSystem() => new(
|
||||
SystemColors.WindowColor, SystemColors.WindowTextColor, SystemColors.HighlightColor, SystemColors.HighlightTextColor,
|
||||
SystemColors.HotTrackColor, SystemColors.GrayTextColor, SystemColors.ControlColor, SystemColors.ControlTextColor);
|
||||
|
||||
/// <summary>A dark window (Aquatic, Dusk, Night sky) rather than a light one (Desert): which Fluent theme lies under it.</summary>
|
||||
public bool IsDark => ColorMath.Luminance(Window) < 0.5;
|
||||
|
||||
/// <summary>The colour of a role, fully opaque — a contrast theme has no translucent colours.</summary>
|
||||
public Color Of(ContrastRole role)
|
||||
{
|
||||
Color c = role switch
|
||||
{
|
||||
ContrastRole.Window => Window,
|
||||
ContrastRole.WindowText => WindowText,
|
||||
ContrastRole.Highlight => Highlight,
|
||||
ContrastRole.HighlightText => HighlightText,
|
||||
ContrastRole.HotTrack => HotTrack,
|
||||
ContrastRole.GrayText => GrayText,
|
||||
ContrastRole.ButtonFace => ButtonFace,
|
||||
ContrastRole.ButtonText => ButtonText,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(role), role, "not a contrast role"),
|
||||
};
|
||||
return Color.FromRgb(c.R, c.G, c.B);
|
||||
}
|
||||
|
||||
/// <summary>Every colour of the palette, in role order.</summary>
|
||||
public IReadOnlyList<Color> Colors => [.. Enum.GetValues<ContrastRole>().Select(Of)];
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The eight colours a Windows contrast theme is made of (beta.35, D91) — what Settings ▸ Accessibility ▸ Contrast themes
|
||||
/// lets the user edit, and what every colour of a contrast-themed window is one of.
|
||||
/// </summary>
|
||||
public enum ContrastRole
|
||||
{
|
||||
/// <summary>The background of a window and of what is in it.</summary>
|
||||
Window,
|
||||
|
||||
/// <summary>Text on <see cref="Window"/>; also borders and strokes.</summary>
|
||||
WindowText,
|
||||
|
||||
/// <summary>A selected item's background; an accent's fill.</summary>
|
||||
Highlight,
|
||||
|
||||
/// <summary>Text on <see cref="Highlight"/>.</summary>
|
||||
HighlightText,
|
||||
|
||||
/// <summary>A link (Windows' "hyperlink" colour).</summary>
|
||||
HotTrack,
|
||||
|
||||
/// <summary>Disabled text and controls.</summary>
|
||||
GrayText,
|
||||
|
||||
/// <summary>A button's background.</summary>
|
||||
ButtonFace,
|
||||
|
||||
/// <summary>A button's text.</summary>
|
||||
ButtonText,
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Which of a contrast theme's eight colours every WPF UI theme resource stands for (beta.35, D91), read from WPF UI 4.3.0's
|
||||
/// own four high-contrast dictionaries (HC1 Dusk, HC2 Night sky, HCBlack Aquatic, HCWhite Desert).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// <b>Why not apply those dictionaries.</b> Measured 2026-11-09: each holds 459 keys, of which 84 of its 97 colours are a
|
||||
/// <c>#FFFF0000</c> placeholder and 17 brushes (<c>SystemFillColor*Brush</c>, <c>MenuBar*</c>) throw when read; and their
|
||||
/// colours are Windows 11's defaults, so a theme the user edited — or Windows 10's — would not be followed.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>What they are good for</b> is the role of each key: every brush there is one of the theme's eight colours (in HC1, 113
|
||||
/// are the window colour, 68 the window text, 56 the highlight …). A key's role is the colour it has in all four — a key
|
||||
/// that is the button face in one and the window in another is a button face — ties broken by its name, and a key with no
|
||||
/// role colour anywhere (a placeholder, a throw) takes its brush twin's or its name's. <see cref="ContrastOverlay"/> then
|
||||
/// gives every key the user's own colour for its role, and keeps the keys transparent there transparent.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// <b>Only an opaque colour is evidence.</b> A brush that throws when its file is read alone does not throw in the App: its
|
||||
/// forward reference falls back to the application's resources, and it reads as the Fluent theme's own fill — measured
|
||||
/// 2026-11-09, <c>MenuBarItemBackgroundPressed</c> read <c>#0AFFFFFF</c> under the dark theme, the white of the window text
|
||||
/// in three of the four, which made a pressed menu item white on white. A contrast theme has no translucent colour, so a
|
||||
/// translucent one says nothing about a role, and the roles come out the same whichever Fluent theme lies under them.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public static class ContrastRoles
|
||||
{
|
||||
/// <summary>WPF UI 4.3.0's high-contrast theme files (<c>Resources/Theme/*.xaml</c>).</summary>
|
||||
public static readonly IReadOnlyList<string> ThemeNames = ["HC1", "HC2", "HCBlack", "HCWhite"];
|
||||
|
||||
private static readonly Color _placeholder = Color.FromArgb(0xFF, 0xFF, 0, 0);
|
||||
private static readonly Lazy<(IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> Roles, IReadOnlyDictionary<string, bool> Clear)> _inferred =
|
||||
new(static () => Infer([.. ThemeNames.Select(Load)]));
|
||||
|
||||
/// <summary>Every key's role, and whether it is a brush (else a colour); keys transparent in a theme are in <see cref="Clear"/>.</summary>
|
||||
public static IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> Map => _inferred.Value.Roles;
|
||||
|
||||
/// <summary>The keys transparent in one of the themes (true for a brush): the overlay keeps them transparent, so no colour of the Fluent theme under it shows through.</summary>
|
||||
public static IReadOnlyDictionary<string, bool> Clear => _inferred.Value.Clear;
|
||||
|
||||
/// <summary>One of WPF UI's high-contrast dictionaries, read for its keys and colours — never applied.</summary>
|
||||
public static ResourceDictionary Load(string theme)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(theme);
|
||||
return new ResourceDictionary { Source = new Uri($"pack://application:,,,/Wpf.Ui;component/Resources/Theme/{theme}.xaml", UriKind.Absolute) };
|
||||
}
|
||||
|
||||
/// <summary>The eight colours a high-contrast dictionary defines for itself (its <c>SystemColor*Color</c> keys).</summary>
|
||||
public static ContrastPalette PaletteOf(ResourceDictionary dictionary)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dictionary);
|
||||
return new ContrastPalette(
|
||||
Read(dictionary, "SystemColorWindowColor"), Read(dictionary, "SystemColorWindowTextColor"),
|
||||
Read(dictionary, "SystemColorHighlightColor"), Read(dictionary, "SystemColorHighlightTextColor"),
|
||||
Read(dictionary, "SystemColorHotlightColor"), Read(dictionary, "SystemColorGrayTextColor"),
|
||||
Read(dictionary, "SystemColorButtonFaceColor"), Read(dictionary, "SystemColorButtonTextColor"));
|
||||
}
|
||||
|
||||
/// <summary>Every key's role across the dictionaries given (the four, in the App; a test's own, in a test), and the keys transparent in one.</summary>
|
||||
public static (IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> Roles, IReadOnlyDictionary<string, bool> Clear) Infer(IReadOnlyList<ResourceDictionary> dictionaries)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(dictionaries);
|
||||
var seen = new Dictionary<string, List<HashSet<ContrastRole>>>(StringComparer.Ordinal);
|
||||
var brush = new Dictionary<string, bool>(StringComparer.Ordinal);
|
||||
var transparent = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (ResourceDictionary dictionary in dictionaries)
|
||||
{
|
||||
ContrastPalette palette = PaletteOf(dictionary);
|
||||
foreach (string key in dictionary.Keys.OfType<string>())
|
||||
{
|
||||
object? value = TryRead(dictionary, key);
|
||||
brush[key] = brush.GetValueOrDefault(key) || value is not Color;
|
||||
Color? colour = value switch
|
||||
{
|
||||
Color c => c,
|
||||
SolidColorBrush b => b.Color,
|
||||
_ => null,
|
||||
};
|
||||
if (colour is { A: 0 })
|
||||
{
|
||||
_ = transparent.Add(key);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!seen.TryGetValue(key, out List<HashSet<ContrastRole>>? sets))
|
||||
{
|
||||
sets = [];
|
||||
seen[key] = sets;
|
||||
}
|
||||
|
||||
// Opaque only: a translucent colour is a Fluent fill a forward reference fell back to, never a contrast colour.
|
||||
if (colour is { A: 0xFF } known && known != _placeholder)
|
||||
{
|
||||
sets.Add([.. Enum.GetValues<ContrastRole>().Where(r => palette.Of(r) == Color.FromRgb(known.R, known.G, known.B))]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var roles = new Dictionary<string, (ContrastRole, bool)>(StringComparer.Ordinal);
|
||||
foreach ((string key, List<HashSet<ContrastRole>> sets) in seen.Where(p => !transparent.Contains(p.Key)))
|
||||
{
|
||||
if (FromColours(key, sets) is { } role)
|
||||
{
|
||||
roles[key] = (role, brush[key]);
|
||||
}
|
||||
}
|
||||
|
||||
// A colour key with no role colour anywhere (a placeholder) takes the role of its brush twin; then the name decides.
|
||||
foreach (string key in seen.Keys.Where(k => !transparent.Contains(k) && !roles.ContainsKey(k)))
|
||||
{
|
||||
roles[key] = (roles.TryGetValue(key + "Brush", out (ContrastRole Role, bool) twin) ? twin.Role : ByName(key), brush[key]);
|
||||
}
|
||||
|
||||
return (roles, transparent.ToDictionary(static k => k, k => brush[k], StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
/// <summary>The role every dictionary agrees on, a tie broken by the name; null when no dictionary gave a role colour.</summary>
|
||||
private static ContrastRole? FromColours(string key, List<HashSet<ContrastRole>> sets)
|
||||
{
|
||||
List<HashSet<ContrastRole>> informative = [.. sets.Where(static s => s.Count > 0)];
|
||||
if (informative.Count == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
HashSet<ContrastRole> common = [.. informative[0]];
|
||||
foreach (HashSet<ContrastRole> set in informative.Skip(1))
|
||||
{
|
||||
common.IntersectWith(set);
|
||||
}
|
||||
|
||||
HashSet<ContrastRole> choices = common.Count > 0 ? common : [.. informative.SelectMany(static s => s)];
|
||||
return choices.Count == 1 ? choices.First() : Prefer(key, choices);
|
||||
}
|
||||
|
||||
/// <summary>Of several roles a colour fits, the one the key's name points at; a button's before a window's.</summary>
|
||||
private static ContrastRole Prefer(string key, HashSet<ContrastRole> choices)
|
||||
{
|
||||
bool button = key.Contains("Button", StringComparison.Ordinal);
|
||||
ContrastRole[] order = button
|
||||
? [ContrastRole.ButtonFace, ContrastRole.ButtonText, ContrastRole.Window, ContrastRole.WindowText, ContrastRole.Highlight, ContrastRole.HighlightText, ContrastRole.HotTrack, ContrastRole.GrayText]
|
||||
: [ContrastRole.Window, ContrastRole.WindowText, ContrastRole.Highlight, ContrastRole.HighlightText, ContrastRole.HotTrack, ContrastRole.GrayText, ContrastRole.ButtonFace, ContrastRole.ButtonText];
|
||||
ContrastRole named = ByName(key);
|
||||
if (choices.Contains(named))
|
||||
{
|
||||
return named;
|
||||
}
|
||||
|
||||
return order.First(choices.Contains);
|
||||
}
|
||||
|
||||
/// <summary>A role from the key's name alone — for a placeholder, or a brush that would not even load.</summary>
|
||||
internal static ContrastRole ByName(string key)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(key);
|
||||
bool Has(string part) => key.Contains(part, StringComparison.Ordinal);
|
||||
bool text = Has("TextFill") || Has("Foreground") || Has("Glyph") || (Has("Text") && !Has("Background"));
|
||||
if (Has("Disabled"))
|
||||
{
|
||||
return ContrastRole.GrayText;
|
||||
}
|
||||
|
||||
if (Has("OnAccent") || (text && (Has("Selected") || Has("Pressed"))))
|
||||
{
|
||||
return ContrastRole.HighlightText;
|
||||
}
|
||||
|
||||
if (Has("AccentText") || Has("Hyperlink") || Has("Hotlight"))
|
||||
{
|
||||
return ContrastRole.HotTrack;
|
||||
}
|
||||
|
||||
if (Has("Accent") || ((Has("Background") || Has("Fill")) && (Has("Selected") || Has("Pressed"))))
|
||||
{
|
||||
return ContrastRole.Highlight;
|
||||
}
|
||||
|
||||
if (text)
|
||||
{
|
||||
return Has("Button") ? ContrastRole.ButtonText : ContrastRole.WindowText;
|
||||
}
|
||||
|
||||
if (Has("Stroke") || (Has("Border") && !Has("MenuBar")))
|
||||
{
|
||||
return ContrastRole.WindowText;
|
||||
}
|
||||
|
||||
// A system fill with no Background in its name is an icon's or a mark's colour: the text colour.
|
||||
if (Has("SystemFillColor") && !Has("Background"))
|
||||
{
|
||||
return ContrastRole.WindowText;
|
||||
}
|
||||
|
||||
return Has("Button") ? ContrastRole.ButtonFace : ContrastRole.Window;
|
||||
}
|
||||
|
||||
private static object? TryRead(ResourceDictionary dictionary, string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
return dictionary[key];
|
||||
}
|
||||
catch (Exception ex) when (ex is ResourceReferenceKeyNotFoundException or InvalidOperationException or System.Windows.Markup.XamlParseException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Color Read(ResourceDictionary dictionary, string key) =>
|
||||
TryRead(dictionary, key) is Color colour ? colour : throw new InvalidOperationException($"the high-contrast dictionary has no colour {key}");
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// The contrast theme the App's own colours follow now (beta.35, D91): set while <see cref="ContrastOverlay"/> is installed,
|
||||
/// null otherwise. What WPF UI's theme resources cannot carry reads it — the charts' palette, the frame-generation bar, the
|
||||
/// change badges, the artwork's tint. The UI thread's: set and read there.
|
||||
/// </summary>
|
||||
public static class ContrastTheme
|
||||
{
|
||||
private static ContrastPalette? _active;
|
||||
|
||||
/// <summary>WPF's change notice for a static property: what a binding to <see cref="IsOn"/> listens to, weakly.</summary>
|
||||
public static event EventHandler<PropertyChangedEventArgs>? StaticPropertyChanged;
|
||||
|
||||
/// <summary>The palette, or null while no contrast theme is followed.</summary>
|
||||
public static ContrastPalette? Active
|
||||
{
|
||||
get => _active;
|
||||
internal set
|
||||
{
|
||||
if (Equals(_active, value))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
bool was = IsOn;
|
||||
_active = value;
|
||||
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(nameof(Active)));
|
||||
if (was != IsOn)
|
||||
{
|
||||
StaticPropertyChanged?.Invoke(null, new PropertyChangedEventArgs(nameof(IsOn)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A contrast theme is followed now — what XAML binds to, <c>{Binding Path=(services:ContrastTheme.IsOn)}</c>, to change
|
||||
/// while it is shown: the Remove button's look (<c>DangerButton</c>), the line under Settings ▸ Theme.
|
||||
/// </summary>
|
||||
public static bool IsOn => _active is not null;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>Whether Windows has a contrast theme on, its colours, and when either changes (beta.35, D91).</summary>
|
||||
public interface IContrastSource
|
||||
{
|
||||
/// <summary>A contrast theme is on (Settings ▸ Accessibility ▸ Contrast themes).</summary>
|
||||
bool IsOn { get; }
|
||||
|
||||
/// <summary>Its colours, as Windows has them now — the user's own if edited.</summary>
|
||||
ContrastPalette Palette { get; }
|
||||
|
||||
/// <summary>A contrast theme was turned on or off, or its colours were edited.</summary>
|
||||
event EventHandler? Changed;
|
||||
}
|
||||
@@ -11,6 +11,11 @@ namespace FrameLedger.App.Services;
|
||||
/// reader as it is shown: a message at the bottom of the window that closes after four seconds was never heard. Every
|
||||
/// transient message goes through here (<c>AccessibilityTests.OnlyTheStripShowsASnackbar</c>).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Every message is drawn in the theme's colours (beta.35), its icon saying which kind it is. WPF UI 4.3.0's Success and
|
||||
/// Caution appearances are fixed colours under white text, 2.78:1 and 2.16:1 in both themes, and no Windows contrast theme
|
||||
/// reaches them; its Secondary one is the theme's, 13.97:1 dark and 16.53:1 light (measured 2026-11-09).
|
||||
/// </remarks>
|
||||
public sealed class SnackbarStrip : IMessageStrip
|
||||
{
|
||||
private static readonly TimeSpan _duration = TimeSpan.FromSeconds(4);
|
||||
@@ -23,15 +28,15 @@ public sealed class SnackbarStrip : IMessageStrip
|
||||
_announcer = announcer ?? NoAnnouncer.Instance;
|
||||
}
|
||||
|
||||
public void Info(string title, string body) => Show(title, body, ControlAppearance.Secondary, SymbolRegular.Info24, AnnouncementKind.Status);
|
||||
public void Info(string title, string body) => Show(title, body, SymbolRegular.Info24, AnnouncementKind.Status);
|
||||
|
||||
public void Success(string title, string body) => Show(title, body, ControlAppearance.Success, SymbolRegular.Checkmark24, AnnouncementKind.Status);
|
||||
public void Success(string title, string body) => Show(title, body, SymbolRegular.Checkmark24, AnnouncementKind.Status);
|
||||
|
||||
public void Warn(string title, string body) => Show(title, body, ControlAppearance.Caution, SymbolRegular.Warning24, AnnouncementKind.Alert);
|
||||
public void Warn(string title, string body) => Show(title, body, SymbolRegular.Warning24, AnnouncementKind.Alert);
|
||||
|
||||
private void Show(string title, string body, ControlAppearance appearance, SymbolRegular icon, AnnouncementKind kind)
|
||||
private void Show(string title, string body, SymbolRegular icon, AnnouncementKind kind)
|
||||
{
|
||||
_snackbar.Show(title, body, appearance, new SymbolIcon(icon), _duration);
|
||||
_snackbar.Show(title, body, ControlAppearance.Secondary, new SymbolIcon(icon), _duration);
|
||||
_announcer.Announce(SpokenText.TitleAndBody(title, body), kind, "Strip");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IContrastSource"/> over Windows (beta.35, D91): <see cref="SystemParameters.HighContrast"/>, which WPF updates
|
||||
/// and announces on Windows' setting change, and the user-preference event Windows raises when a contrast theme's colours
|
||||
/// are edited while it is on.
|
||||
/// </summary>
|
||||
public sealed class SystemContrastSource : IContrastSource, IDisposable
|
||||
{
|
||||
public SystemContrastSource()
|
||||
{
|
||||
SystemParameters.StaticPropertyChanged += OnSystemParameterChanged;
|
||||
SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
|
||||
}
|
||||
|
||||
public event EventHandler? Changed;
|
||||
|
||||
public bool IsOn => SystemParameters.HighContrast;
|
||||
|
||||
public ContrastPalette Palette => ContrastPalette.FromSystem();
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
SystemParameters.StaticPropertyChanged -= OnSystemParameterChanged;
|
||||
SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged;
|
||||
}
|
||||
|
||||
private void OnSystemParameterChanged(object? sender, PropertyChangedEventArgs e)
|
||||
{
|
||||
if (string.Equals(e.PropertyName, nameof(SystemParameters.HighContrast), StringComparison.Ordinal))
|
||||
{
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnUserPreferenceChanged(object? sender, UserPreferenceChangedEventArgs e)
|
||||
{
|
||||
if (IsOn && e.Category is UserPreferenceCategory.Color or UserPreferenceCategory.Accessibility or UserPreferenceCategory.VisualStyle)
|
||||
{
|
||||
Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using Wpf.Ui.Appearance;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
namespace FrameLedger.App.Services;
|
||||
|
||||
/// <summary>
|
||||
/// What a theme choice comes to (beta.35, D91): the Fluent theme, the windows' backdrop, whether WPF UI watches Windows'
|
||||
/// own theme, and whether a contrast theme's colours go over it. A contrast theme wins over the App's choice while it is on —
|
||||
/// the theme under it is the light or the dark one as the contrast theme is, with no Mica — and the choice applies again
|
||||
/// when it is off.
|
||||
/// </summary>
|
||||
public readonly record struct ThemePlan(ApplicationTheme Theme, WindowBackdropType Backdrop, bool WatchSystem, bool Contrast)
|
||||
{
|
||||
/// <summary>The plan for a choice in a state of Windows.</summary>
|
||||
/// <param name="choice">Settings ▸ Theme.</param>
|
||||
/// <param name="contrastOn">A Windows contrast theme is on.</param>
|
||||
/// <param name="contrastDark">That contrast theme is a dark one (its window colour).</param>
|
||||
/// <param name="systemDark">Windows' own app mode is dark (for <see cref="AppTheme.System"/>).</param>
|
||||
public static ThemePlan For(AppTheme choice, bool contrastOn, bool contrastDark, bool systemDark)
|
||||
{
|
||||
if (contrastOn)
|
||||
{
|
||||
return new(contrastDark ? ApplicationTheme.Dark : ApplicationTheme.Light, WindowBackdropType.None, WatchSystem: false, Contrast: true);
|
||||
}
|
||||
|
||||
return choice switch
|
||||
{
|
||||
AppTheme.System => new(systemDark ? ApplicationTheme.Dark : ApplicationTheme.Light, WindowBackdropType.Mica, WatchSystem: true, Contrast: false),
|
||||
AppTheme.Light => new(ApplicationTheme.Light, WindowBackdropType.Mica, WatchSystem: false, Contrast: false),
|
||||
AppTheme.Dark => new(ApplicationTheme.Dark, WindowBackdropType.Mica, WatchSystem: false, Contrast: false),
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(choice), choice, "not a theme"),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,9 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Windows;
|
||||
using System.Windows.Threading;
|
||||
using Wpf.Ui.Appearance;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
@@ -12,33 +14,109 @@ namespace FrameLedger.App.Services;
|
||||
/// through <c>SystemThemeWatcher.Watch</c> on the window — which needs an HWND, so the caller passes the window
|
||||
/// from its <c>Loaded</c> handler and never from a constructor — and <c>UnWatch</c> when switching to manual.
|
||||
/// </summary>
|
||||
public sealed class WpfThemeApplier : IThemeApplier
|
||||
/// <remarks>
|
||||
/// <b>A Windows contrast theme wins (beta.35, owner decision D91).</b> While one is on, the App's colours are its colours —
|
||||
/// the light or the dark Fluent theme as the contrast theme is, under <see cref="ContrastOverlay"/>, with no Mica and no
|
||||
/// system-theme watcher (WPF UI's would apply its own high-contrast dictionaries, 84 of whose 97 colours are a red
|
||||
/// placeholder) — whatever Settings ▸ Theme says; the choice applies again when it is turned off. A switch in Windows is
|
||||
/// followed at once (<see cref="IContrastSource.Changed"/>), and each call is the same for the same state, so the windows that
|
||||
/// call it from their constructors change nothing.
|
||||
/// </remarks>
|
||||
public sealed class WpfThemeApplier : IThemeApplier, IDisposable
|
||||
{
|
||||
private readonly IContrastSource _contrast;
|
||||
private AppTheme _theme = AppTheme.System;
|
||||
private WeakReference<Window>? _window;
|
||||
|
||||
public WpfThemeApplier(IContrastSource contrast)
|
||||
{
|
||||
_contrast = contrast ?? throw new ArgumentNullException(nameof(contrast));
|
||||
_contrast.Changed += OnContrastChanged;
|
||||
}
|
||||
|
||||
public void Apply(AppTheme theme, Window? window)
|
||||
{
|
||||
switch (theme)
|
||||
_theme = theme;
|
||||
if (window is not null)
|
||||
{
|
||||
case AppTheme.System:
|
||||
ApplicationThemeManager.Apply(SystemIsDark() ? ApplicationTheme.Dark : ApplicationTheme.Light, WindowBackdropType.Mica, true);
|
||||
if (window is { IsLoaded: true })
|
||||
{
|
||||
SystemThemeWatcher.Watch(window, WindowBackdropType.Mica, true);
|
||||
}
|
||||
_window = new WeakReference<Window>(window);
|
||||
}
|
||||
|
||||
break;
|
||||
case AppTheme.Light:
|
||||
case AppTheme.Dark:
|
||||
if (window is not null)
|
||||
{
|
||||
SystemThemeWatcher.UnWatch(window);
|
||||
}
|
||||
Window? watched = window ?? (_window?.TryGetTarget(out Window? last) == true ? last : null);
|
||||
bool contrastOn = _contrast.IsOn;
|
||||
ContrastPalette? palette = contrastOn ? _contrast.Palette : null;
|
||||
ThemePlan plan = ThemePlan.For(theme, contrastOn, palette?.IsDark ?? false, SystemIsDark());
|
||||
ResourceDictionary resources = System.Windows.Application.Current.Resources;
|
||||
if (plan.Contrast && palette is not null)
|
||||
{
|
||||
if (watched is not null)
|
||||
{
|
||||
SystemThemeWatcher.UnWatch(watched);
|
||||
}
|
||||
|
||||
ApplicationThemeManager.Apply(theme == AppTheme.Dark ? ApplicationTheme.Dark : ApplicationTheme.Light, WindowBackdropType.Mica, true);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(theme), theme, "not a theme");
|
||||
// The charts re-read their palette on the theme manager's Changed, which Apply raises: say the contrast first.
|
||||
ContrastTheme.Active = palette;
|
||||
ApplicationThemeManager.Apply(plan.Theme, plan.Backdrop, updateAccent: false);
|
||||
ContrastOverlay.Install(resources, palette);
|
||||
Backdrops(plan.Backdrop);
|
||||
return;
|
||||
}
|
||||
|
||||
bool wasContrast = ContrastOverlay.IsInstalled(resources);
|
||||
ContrastOverlay.Remove(resources);
|
||||
if (plan.WatchSystem)
|
||||
{
|
||||
ApplicationThemeManager.Apply(plan.Theme, plan.Backdrop, true);
|
||||
if (watched is { IsLoaded: true })
|
||||
{
|
||||
SystemThemeWatcher.Watch(watched, plan.Backdrop, true);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (watched is not null)
|
||||
{
|
||||
SystemThemeWatcher.UnWatch(watched);
|
||||
}
|
||||
|
||||
ApplicationThemeManager.Apply(plan.Theme, plan.Backdrop, true);
|
||||
}
|
||||
|
||||
if (wasContrast)
|
||||
{
|
||||
Backdrops(plan.Backdrop);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() => _contrast.Changed -= OnContrastChanged;
|
||||
|
||||
private static bool SystemIsDark() => ApplicationThemeManager.GetSystemTheme() is SystemTheme.Dark or SystemTheme.HCBlack or SystemTheme.Glow or SystemTheme.CapturedMotion;
|
||||
|
||||
/// <summary>Every FluentWindow's backdrop now, and again once a window being built has set its own from its XAML.</summary>
|
||||
[SuppressMessage("Usage", "VSTHRD001:Avoid legacy thread switching APIs", Justification = "a WPF application has no JoinableTaskFactory; this posts to the windows' own dispatcher, after a window being built has loaded its XAML, and never waits (ScrollBarHiding does the same)")]
|
||||
private static void Backdrops(WindowBackdropType backdrop)
|
||||
{
|
||||
static void Sweep(WindowBackdropType type)
|
||||
{
|
||||
foreach (FluentWindow window in System.Windows.Application.Current?.Windows.OfType<FluentWindow>() ?? [])
|
||||
{
|
||||
window.WindowBackdropType = type;
|
||||
}
|
||||
}
|
||||
|
||||
Sweep(backdrop);
|
||||
_ = System.Windows.Application.Current?.Dispatcher.BeginInvoke(DispatcherPriority.Loaded, () => Sweep(backdrop));
|
||||
}
|
||||
|
||||
[SuppressMessage("Usage", "VSTHRD001:Avoid legacy thread switching APIs", Justification = "Windows' setting change can arrive off the UI thread; the theme is the dispatcher's to change, posted and never waited on")]
|
||||
private void OnContrastChanged(object? sender, EventArgs e)
|
||||
{
|
||||
Dispatcher? dispatcher = System.Windows.Application.Current?.Dispatcher;
|
||||
if (dispatcher is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_ = dispatcher.BeginInvoke(() => Apply(_theme, _window?.TryGetTarget(out Window? window) == true ? window : null));
|
||||
}
|
||||
}
|
||||
Generated
+3
@@ -1033,6 +1033,7 @@ public static class Strings
|
||||
nameof(Settings_System_Copy),
|
||||
nameof(Settings_System_Header),
|
||||
nameof(Settings_System_Note),
|
||||
nameof(Settings_Theme_ContrastOn),
|
||||
nameof(Settings_Theme_Dark),
|
||||
nameof(Settings_Theme_Label),
|
||||
nameof(Settings_Theme_Light),
|
||||
@@ -3269,6 +3270,8 @@ public static class Strings
|
||||
|
||||
public static string Settings_System_Note => ResourceManager.GetString(nameof(Settings_System_Note), Culture) ?? nameof(Settings_System_Note);
|
||||
|
||||
public static string Settings_Theme_ContrastOn => ResourceManager.GetString(nameof(Settings_Theme_ContrastOn), Culture) ?? nameof(Settings_Theme_ContrastOn);
|
||||
|
||||
public static string Settings_Theme_Dark => ResourceManager.GetString(nameof(Settings_Theme_Dark), Culture) ?? nameof(Settings_Theme_Dark);
|
||||
|
||||
public static string Settings_Theme_Label => ResourceManager.GetString(nameof(Settings_Theme_Label), Culture) ?? nameof(Settings_Theme_Label);
|
||||
|
||||
@@ -425,6 +425,10 @@
|
||||
<value>テーマ</value>
|
||||
<comment>review</comment>
|
||||
</data>
|
||||
<data name="Settings_Theme_ContrastOn" xml:space="preserve">
|
||||
<value>Windows のコントラスト テーマがオンのため、FrameLedger はその色を使います。ここでの選択は、テーマをオフにすると再び適用されます。</value>
|
||||
<comment>review</comment>
|
||||
</data>
|
||||
<data name="Settings_Theme_Light" xml:space="preserve">
|
||||
<value>ライト</value>
|
||||
<comment>review</comment>
|
||||
|
||||
@@ -324,6 +324,9 @@
|
||||
<data name="Settings_Theme_Label" xml:space="preserve">
|
||||
<value>Theme</value>
|
||||
</data>
|
||||
<data name="Settings_Theme_ContrastOn" xml:space="preserve">
|
||||
<value>A Windows contrast theme is on, so FrameLedger uses its colours. The choice here applies again when it is off.</value>
|
||||
</data>
|
||||
<data name="Settings_Theme_Light" xml:space="preserve">
|
||||
<value>Light</value>
|
||||
</data>
|
||||
|
||||
@@ -319,6 +319,9 @@
|
||||
<data name="Settings_Theme_Label" xml:space="preserve">
|
||||
<value>Chủ đề</value>
|
||||
</data>
|
||||
<data name="Settings_Theme_ContrastOn" xml:space="preserve">
|
||||
<value>Một contrast theme của Windows đang bật nên FrameLedger dùng màu của nó. Lựa chọn ở đây sẽ áp dụng lại khi tắt contrast theme.</value>
|
||||
</data>
|
||||
<data name="Settings_Theme_Light" xml:space="preserve">
|
||||
<value>Sáng</value>
|
||||
</data>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
|
||||
xmlns:controls="clr-namespace:FrameLedger.App.Controls"
|
||||
xmlns:converters="clr-namespace:FrameLedger.App.Converters"
|
||||
xmlns:services="clr-namespace:FrameLedger.App.Services"
|
||||
xmlns:res="clr-namespace:FrameLedger.App">
|
||||
<!--
|
||||
Our styles, merged LAST (16_WPFUI_SYNTAX §App bootstrap). Colours only through theme brushes with
|
||||
@@ -22,6 +23,47 @@
|
||||
<converters:NotNullConverter x:Key="NotNull" />
|
||||
<converters:ZeroToVisibleConverter x:Key="ZeroToVisible" />
|
||||
|
||||
<!--
|
||||
Every ui:Button: WPF UI's style and two changes (beta.35). WPF UI 4.3.0's Danger appearance paints a fixed #F44336 — a
|
||||
value in its button style, not a resource — under the button's own text, white in the dark theme: 3.68:1. A Danger
|
||||
button's text is the theme's dark text on that red instead, 5.3:1 and 5.7:1 in the two themes. Under a Windows contrast
|
||||
theme (D91), where no resource reaches that red, it is the theme's own button, as every button there is; its words and
|
||||
its icon still say what it does. Implicit, so the buttons of WPF UI's message boxes get it too (Remove game, Delete
|
||||
sessions, Database maintenance).
|
||||
-->
|
||||
<Style TargetType="ui:Button" BasedOn="{StaticResource {x:Type ui:Button}}">
|
||||
<Style.Triggers>
|
||||
<Trigger Property="Appearance" Value="Danger">
|
||||
<Setter Property="Foreground" Value="{DynamicResource TextFillColorDarkPrimaryBrush}" />
|
||||
<Setter Property="PressedForeground" Value="{DynamicResource TextFillColorDarkPrimaryBrush}" />
|
||||
</Trigger>
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding Appearance, RelativeSource={RelativeSource Self}}" Value="Danger" />
|
||||
<Condition Binding="{Binding Path=(services:ContrastTheme.IsOn)}" Value="True" />
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="Background" Value="{DynamicResource ButtonBackground}" />
|
||||
<Setter Property="MouseOverBackground" Value="{DynamicResource ButtonBackgroundPointerOver}" />
|
||||
<Setter Property="PressedBackground" Value="{DynamicResource ButtonBackgroundPressed}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
|
||||
<Setter Property="PressedForeground" Value="{DynamicResource ButtonForegroundPressed}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource ControlElevationBorderBrush}" />
|
||||
<Setter Property="MouseOverBorderBrush" Value="{DynamicResource ControlElevationBorderBrush}" />
|
||||
<Setter Property="PressedBorderBrush" Value="{DynamicResource ButtonBorderBrushPressed}" />
|
||||
</MultiDataTrigger>
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding Appearance, RelativeSource={RelativeSource Self}}" Value="Danger" />
|
||||
<Condition Binding="{Binding Path=(services:ContrastTheme.IsOn)}" Value="True" />
|
||||
<Condition Binding="{Binding IsEnabled, RelativeSource={RelativeSource Self}}" Value="False" />
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
|
||||
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
|
||||
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
|
||||
</MultiDataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<Style x:Key="PageRoot" TargetType="StackPanel">
|
||||
<Setter Property="Margin" Value="28,20,28,20" />
|
||||
</Style>
|
||||
@@ -114,6 +156,27 @@
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!--
|
||||
The agent's state in the title bar (beta.35). It was a ui:Badge with the Success, Info, Caution and Danger appearances,
|
||||
WPF UI's fixed Material palette under the badge's own text: in the light theme 2.78, 2.63, 2.16 and 3.68:1. Now the
|
||||
theme's own fills — success, caution, critical, and the neutral one while it is on its way — under the theme's text,
|
||||
as the InfoBars are; under a contrast theme those are the theme's colours too. Its words say the state.
|
||||
-->
|
||||
<Style x:Key="AgentPill" TargetType="Border" BasedOn="{StaticResource Pill}">
|
||||
<Setter Property="Margin" Value="0,0,12,0" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding AgentStatusAppearance}" Value="Success">
|
||||
<Setter Property="Background" Value="{DynamicResource SystemFillColorSuccessBackgroundBrush}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding AgentStatusAppearance}" Value="Caution">
|
||||
<Setter Property="Background" Value="{DynamicResource SystemFillColorCautionBackgroundBrush}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding AgentStatusAppearance}" Value="Danger">
|
||||
<Setter Property="Background" Value="{DynamicResource SystemFillColorCriticalBackgroundBrush}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
|
||||
<!--
|
||||
ui:InfoBar, re-templated (16_WPFUI_SYNTAX §Gotchas). WPF UI 4.3.0's own template has no ContentPresenter,
|
||||
so an InfoBar's Content (the action button 08_UI §Notifications policy puts on every persistent banner)
|
||||
|
||||
@@ -37,7 +37,10 @@ public sealed class UpdatePrompts(IUrlOpener urls, BugReportFlow bugReports) : I
|
||||
body.Children.Add(notes);
|
||||
}
|
||||
|
||||
body.Children.Add(new System.Windows.Controls.TextBlock { Text = Strings.Update_Unsigned_Footer, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 12, 0, 0), Opacity = 0.7 });
|
||||
// beta.35 (D91): the muted text style, not an opacity — under a contrast theme a translucent text is no theme colour.
|
||||
var footer = new System.Windows.Controls.TextBlock { Text = Strings.Update_Unsigned_Footer, TextWrapping = TextWrapping.Wrap, Margin = new Thickness(0, 12, 0, 0) };
|
||||
footer.SetResourceReference(FrameworkElement.StyleProperty, "SecondaryText");
|
||||
body.Children.Add(footer);
|
||||
var box = new MessageBox
|
||||
{
|
||||
Title = string.Format(CultureInfo.CurrentCulture, Strings.Update_Available_Title_Format, candidate.Version),
|
||||
|
||||
@@ -34,6 +34,12 @@ public sealed partial class ImportCandidateViewModel : ObservableObject
|
||||
/// </summary>
|
||||
public bool IsExisting => Candidate.AlreadyInLibrary || Candidate.MovedFrom is not null;
|
||||
|
||||
/// <summary>
|
||||
/// The row is drawn dimmed: one already in the library, except under a Windows contrast theme (beta.35, D91), where a
|
||||
/// translucent row is no theme colour and the note column says it already is.
|
||||
/// </summary>
|
||||
public bool IsDimmed => IsExisting && Services.ContrastTheme.Active is null;
|
||||
|
||||
public string PlatformText => Formats.Platform(Candidate.Game.Platform);
|
||||
|
||||
public string Name => Candidate.Game.Name;
|
||||
|
||||
@@ -37,6 +37,26 @@ public sealed class AnnouncementsTests
|
||||
public void Show(string title, string message, ControlAppearance appearance, IconElement? icon, TimeSpan timeout) => Shown.Add((title, message, appearance));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// beta.35: every message is drawn in the theme's colours, its icon saying which kind it is — WPF UI's Success and Caution
|
||||
/// snackbars are white on fixed green and orange, 2.78:1 and 2.16:1 in both themes, and no contrast theme reaches them.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task EveryMessageOfTheStripIsDrawnInTheThemesOwnColours()
|
||||
{
|
||||
var snackbar = new FakeSnackbar();
|
||||
await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
var strip = new SnackbarStrip(snackbar);
|
||||
strip.Info("a", "b");
|
||||
strip.Success("c", "d");
|
||||
strip.Warn("e", "f");
|
||||
return 0;
|
||||
});
|
||||
|
||||
snackbar.Shown.Select(static s => s.Appearance).Should().Equal(ControlAppearance.Secondary, ControlAppearance.Secondary, ControlAppearance.Secondary);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EveryMessageOfTheStripIsSaidAsItIsShownAndAWarningIsAnAlert()
|
||||
{
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.ComponentModel;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Xml.Linq;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.App.Charts;
|
||||
using FrameLedger.App.Controls;
|
||||
using FrameLedger.App.Services;
|
||||
using FrameLedger.Domain.Metrics;
|
||||
using Wpf.Ui.Appearance;
|
||||
using Wpf.Ui.Controls;
|
||||
|
||||
namespace FrameLedger.App.Tests;
|
||||
|
||||
/// <summary>What the App draws itself under a contrast theme (beta.35, D91): the badges, the mix bar, the Remove button.</summary>
|
||||
public sealed partial class ContrastThemeTests
|
||||
{
|
||||
// Danger is not here: the App's implicit button style makes it read, and the theme's own button under a contrast theme.
|
||||
private static readonly string[] _fixedColourAppearances = ["Info", "Success", "Caution", "Dark", "Light"];
|
||||
|
||||
/// <summary>
|
||||
/// The change badge and the frame-generation bar repaint when a contrast theme comes on even if its window colour is the
|
||||
/// Fluent theme's — Aquatic's <c>#202020</c> is the dark theme's own. They hear a theme through a resource reference to
|
||||
/// <c>ApplicationBackgroundColor</c>, and measured 2026-11-09 the overlay going on re-reads it and calls them though the
|
||||
/// colour is the same; this holds that, so no second signal is needed.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TheBadgeAndTheMixBarRepaintWhenAContrastThemeKeepsTheWindowColour()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() => Visuals.UnderTheme(ApplicationTheme.Dark, () =>
|
||||
{
|
||||
ResourceDictionary resources = System.Windows.Application.Current.Resources;
|
||||
ContrastPalette same = EditedDark with { Window = (Color)System.Windows.Application.Current.FindResource("ApplicationBackgroundColor") };
|
||||
var badge = new ChangeBadge { Text = "1" };
|
||||
var bar = new FgMixBar { Segments = [new FgMixSegment(FgMixKind.None, null, 1)], Width = 60, Height = 14 };
|
||||
var panel = new System.Windows.Controls.StackPanel();
|
||||
panel.Children.Add(badge);
|
||||
panel.Children.Add(bar);
|
||||
var host = new FluentWindow { Content = panel, Width = 200, Height = 120, ShowActivated = false, WindowStartupLocation = WindowStartupLocation.Manual, Left = -10000, Top = -10000 };
|
||||
host.Show();
|
||||
try
|
||||
{
|
||||
Visuals.Pump();
|
||||
Color before = ((SolidColorBrush)badge.Background).Color;
|
||||
Color barBefore = Pixel(panel, bar);
|
||||
ContrastOverlay.Install(resources, same);
|
||||
try
|
||||
{
|
||||
Visuals.Pump();
|
||||
return (Before: before, During: ((SolidColorBrush)badge.Background).Color, Text: ((SolidColorBrush)badge.Foreground).Color,
|
||||
BarBefore: barBefore, BarDuring: Pixel(panel, bar), Palette: same);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ContrastOverlay.Remove(resources);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
host.Close();
|
||||
}
|
||||
}));
|
||||
|
||||
facts.During.Should().NotBe(facts.Before, "the badge heard the contrast theme though the window colour stayed");
|
||||
facts.Palette.Colors.Should().Contain(facts.During).And.Contain(facts.Text);
|
||||
facts.BarDuring.Should().NotBe(facts.BarBefore, "and the bar redrew");
|
||||
facts.Palette.Colors.Should().Contain(facts.BarDuring);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// WPF UI 4.3.0 paints its Info, Success, Caution, Dark and Light buttons a fixed colour under white text that no theme
|
||||
/// reaches, and a badge with a bound appearance escapes <c>ContrastTests</c>' look at the literal ones — the agent's pill was
|
||||
/// one, 2.16:1 in the light theme. Danger is allowed: the App's own button style makes it read (below).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void NoButtonOrBadgeTakesAnAppearanceThatPaintsAFixedColour()
|
||||
{
|
||||
var offenders = new List<string>();
|
||||
foreach ((string file, XDocument xaml) in AccessibilityTests.AppXaml())
|
||||
{
|
||||
foreach (XElement element in xaml.Descendants())
|
||||
{
|
||||
string name = element.Name.LocalName;
|
||||
string? appearance = element.Attribute("Appearance")?.Value;
|
||||
if (appearance is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (name.EndsWith("Button", StringComparison.Ordinal) && _fixedColourAppearances.Contains(appearance, StringComparer.Ordinal))
|
||||
{
|
||||
offenders.Add($"{file}: {name} Appearance=\"{appearance}\"");
|
||||
}
|
||||
|
||||
if (string.Equals(name, "Badge", StringComparison.Ordinal) && appearance.StartsWith('{'))
|
||||
{
|
||||
offenders.Add($"{file}: a Badge whose appearance is bound, {appearance}");
|
||||
}
|
||||
}
|
||||
|
||||
foreach (XElement setter in xaml.Descendants().Where(static e => string.Equals(e.Name.LocalName, "Setter", StringComparison.Ordinal)
|
||||
&& string.Equals(e.Attribute("Property")?.Value, "Appearance", StringComparison.Ordinal)))
|
||||
{
|
||||
if (setter.Attribute("Value")?.Value is { } value && _fixedColourAppearances.Contains(value, StringComparer.Ordinal))
|
||||
{
|
||||
offenders.Add($"{file}: a style sets Appearance=\"{value}\"");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
offenders.Should().BeEmpty("a fixed colour under white text reads below 3:1 in a theme and is no contrast theme's colour");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A Danger button — the game page's Remove, the message boxes' Delete — reads in both themes (the App's implicit button
|
||||
/// style puts the theme's dark text on WPF UI's fixed red, where its own white read 3.68:1 in the dark theme) and is the
|
||||
/// theme's own button while a contrast theme is on, changing at once.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task ADangerButtonReadsInBothThemesAndIsTheThemesOwnButtonUnderAContrastTheme()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
static (Color Face, Color Text) Drawn(Wpf.Ui.Controls.Button b) => (((SolidColorBrush)b.Background).Color, ((SolidColorBrush)b.Foreground).Color);
|
||||
(Color Face, Color Text) Under(ApplicationTheme theme, Func<Wpf.Ui.Controls.Button, (Color, Color)> read) => Visuals.UnderTheme(theme, () =>
|
||||
{
|
||||
var button = new Wpf.Ui.Controls.Button { Content = "Remove…", Appearance = ControlAppearance.Danger };
|
||||
var host = new FluentWindow { Content = button, Width = 200, Height = 120, ShowActivated = false, WindowStartupLocation = WindowStartupLocation.Manual, Left = -10000, Top = -10000 };
|
||||
host.Show();
|
||||
try
|
||||
{
|
||||
Visuals.Pump();
|
||||
return read(button);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ContrastOverlay.Remove(System.Windows.Application.Current.Resources);
|
||||
host.Close();
|
||||
}
|
||||
});
|
||||
|
||||
(Color Face, Color Text) dark = Under(ApplicationTheme.Dark, Drawn);
|
||||
(Color Face, Color Text) light = Under(ApplicationTheme.Light, Drawn);
|
||||
(Color, Color) on = default;
|
||||
(Color, Color) off = Under(ApplicationTheme.Dark, b =>
|
||||
{
|
||||
ContrastOverlay.Install(System.Windows.Application.Current.Resources, EditedDark);
|
||||
Visuals.Pump();
|
||||
on = Drawn(b);
|
||||
ContrastOverlay.Remove(System.Windows.Application.Current.Resources);
|
||||
Visuals.Pump();
|
||||
return Drawn(b);
|
||||
});
|
||||
return (dark, light, on, off);
|
||||
});
|
||||
|
||||
ColorMath.Contrast(facts.dark.Text, facts.dark.Face).Should().BeGreaterThanOrEqualTo(4.5, "the dark theme's white read 3.68:1 on #F44336");
|
||||
ColorMath.Contrast(facts.light.Text, facts.light.Face).Should().BeGreaterThanOrEqualTo(4.5);
|
||||
facts.on.Should().Be((EditedDark.ButtonFace, EditedDark.ButtonText), "turned on while the button is shown, it is the theme's button at once");
|
||||
facts.off.Should().Be(facts.dark, "and turned off, the red one again");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The title bar's two marks read in every state, in both themes and under a contrast theme: the agent's state on the
|
||||
/// theme's own fills (<c>AgentPill</c>, which replaced a palette badge: 2.78, 2.63, 2.16 and 3.68:1 in the light theme)
|
||||
/// and the alpha build's badge, the accent under its own text.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("Dark")]
|
||||
[InlineData("Light")]
|
||||
[InlineData("HC1")]
|
||||
[InlineData("HCWhite")]
|
||||
[InlineData("EditedLight")]
|
||||
public async Task TheTitleBarsMarksReadInEveryState(string name)
|
||||
{
|
||||
ControlAppearance[] states = [ControlAppearance.Success, ControlAppearance.Info, ControlAppearance.Caution, ControlAppearance.Danger];
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
ContrastPalette? palette = name is "Dark" or "Light" ? null : Named(name);
|
||||
List<(string Mark, Color Text, Color Under)> Measure()
|
||||
{
|
||||
var panel = new System.Windows.Controls.StackPanel();
|
||||
var marks = new List<(string Mark, System.Windows.Controls.TextBlock Text)>();
|
||||
foreach (ControlAppearance state in states)
|
||||
{
|
||||
var text = new System.Windows.Controls.TextBlock { Text = state.ToString() };
|
||||
text.SetResourceReference(System.Windows.Controls.TextBlock.ForegroundProperty, "TextFillColorPrimaryBrush");
|
||||
panel.Children.Add(new System.Windows.Controls.Border
|
||||
{
|
||||
Style = (Style)System.Windows.Application.Current.FindResource("AgentPill"),
|
||||
DataContext = new { AgentStatusAppearance = state },
|
||||
Child = text,
|
||||
});
|
||||
marks.Add(("agent " + state, text));
|
||||
}
|
||||
|
||||
var alpha = new Badge { Appearance = ControlAppearance.Primary, Content = "Alpha" };
|
||||
panel.Children.Add(alpha);
|
||||
var host = new FluentWindow { Content = panel, Width = 300, Height = 300, ShowActivated = false, WindowStartupLocation = WindowStartupLocation.Manual, Left = -10000, Top = -10000 };
|
||||
host.Show();
|
||||
try
|
||||
{
|
||||
Visuals.Pump();
|
||||
marks.Add(("alpha badge", Visuals.FindAll<System.Windows.Controls.TextBlock>(alpha).Single()));
|
||||
Color window = (Color)System.Windows.Application.Current.FindResource("ApplicationBackgroundColor");
|
||||
return [.. marks.Select(m =>
|
||||
{
|
||||
Color under = Visuals.PaintedUnder(m.Text, panel, window);
|
||||
return (m.Mark, Visuals.TextOver(m.Text, under), under);
|
||||
})];
|
||||
}
|
||||
finally
|
||||
{
|
||||
host.Close();
|
||||
}
|
||||
}
|
||||
|
||||
if (palette is null)
|
||||
{
|
||||
return Visuals.UnderTheme(Enum.Parse<ApplicationTheme>(name), Measure);
|
||||
}
|
||||
|
||||
List<(string Mark, Color Text, Color Under)> drawn = Visuals.UnderContrast(palette, Measure);
|
||||
return [.. drawn.Select(m => (palette.Colors.Contains(m.Text) && palette.Colors.Contains(m.Under) ? m.Mark : m.Mark + " (not the theme's colours)", m.Text, m.Under))];
|
||||
});
|
||||
|
||||
facts.Should().HaveCount(5);
|
||||
facts.Where(static m => ColorMath.Contrast(m.Text, m.Under) < 4.5 || m.Mark.EndsWith(')')).Select(static m => $"{m.Mark}: {m.Text} on {m.Under}, {ColorMath.Contrast(m.Text, m.Under):0.00}:1")
|
||||
.Should().BeEmpty($"every mark in the title bar reads at 4.5:1 under {name}");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheContrastThemeSaysWhenItComesAndGoes()
|
||||
{
|
||||
// Heard on the STA thread inside the one work item: the other tests' contrast themes come and go on it too.
|
||||
(List<string> heard, bool on) = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
var said = new List<string>();
|
||||
void Heard(object? sender, PropertyChangedEventArgs e) => said.Add(e.PropertyName!);
|
||||
ContrastTheme.StaticPropertyChanged += Heard;
|
||||
try
|
||||
{
|
||||
var resources = new ResourceDictionary();
|
||||
ContrastOverlay.Install(resources, EditedDark);
|
||||
ContrastOverlay.Install(resources, EditedDark);
|
||||
ContrastOverlay.Install(resources, EditedLight);
|
||||
ContrastOverlay.Remove(resources);
|
||||
return (said, ContrastTheme.IsOn);
|
||||
}
|
||||
finally
|
||||
{
|
||||
ContrastTheme.StaticPropertyChanged -= Heard;
|
||||
}
|
||||
});
|
||||
|
||||
heard.Should().Equal(["Active", "IsOn", "Active", "Active", "IsOn"], "on, another palette while on, off — the same palette twice says nothing, and a palette replaced is never off between");
|
||||
on.Should().BeFalse();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnderAContrastThemeAChartBadgesTextIsTheThemesColourThatReadsBest()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
var resources = new ResourceDictionary();
|
||||
ContrastOverlay.Install(resources, EditedLight);
|
||||
try
|
||||
{
|
||||
return (OnHotTrack: ChartTheme.ToWpf(ChartTheme.TextOn(ChartTheme.ToScottPlot(EditedLight.HotTrack))),
|
||||
OnWindow: ChartTheme.ToWpf(ChartTheme.TextOn(ChartTheme.ToScottPlot(EditedLight.Window))));
|
||||
}
|
||||
finally
|
||||
{
|
||||
ContrastOverlay.Remove(resources);
|
||||
}
|
||||
});
|
||||
|
||||
facts.OnHotTrack.Should().Be(EditedLight.Window, "white reads best on the edited theme's dark blue link colour, and white is its window");
|
||||
facts.OnWindow.Should().Be(EditedLight.WindowText);
|
||||
}
|
||||
|
||||
/// <summary>The colour drawn at the middle of <paramref name="element"/>, rendered as part of <paramref name="root"/>.</summary>
|
||||
private static Color Pixel(FrameworkElement root, FrameworkElement element)
|
||||
{
|
||||
var bitmap = new RenderTargetBitmap((int)Math.Ceiling(root.ActualWidth), (int)Math.Ceiling(root.ActualHeight), 96, 96, PixelFormats.Pbgra32);
|
||||
bitmap.Render(root);
|
||||
Point middle = element.TranslatePoint(new Point(element.ActualWidth / 2, element.ActualHeight / 2), root);
|
||||
byte[] pixel = new byte[4];
|
||||
bitmap.CopyPixels(new Int32Rect((int)middle.X, (int)middle.Y, 1, 1), pixel, 4, 0);
|
||||
return Color.FromArgb(pixel[3], pixel[2], pixel[1], pixel[0]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
// SPDX-License-Identifier: GPL-3.0-only
|
||||
// Copyright (C) 2026 poli0981 - additional terms under GPLv3 section 7: see NOTICE
|
||||
|
||||
using System.IO;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Windows;
|
||||
using System.Windows.Media;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.App.Charts;
|
||||
using FrameLedger.App.Services;
|
||||
using Wpf.Ui.Appearance;
|
||||
using Wpf.Ui.Controls;
|
||||
using Wpf.Ui.Markup;
|
||||
|
||||
namespace FrameLedger.App.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Windows contrast themes, followed (beta.35, owner decision D91): every WPF UI theme resource gets the user's colour for
|
||||
/// its role, read from WPF UI's own four high-contrast dictionaries; the App's own colours — the charts', the bar's, the
|
||||
/// badges' — come from the same eight; a theme choice gives way to a contrast theme while it is on. A test cannot turn a
|
||||
/// contrast theme on in Windows, so the palettes are WPF UI's four defaults and two the user might have edited.
|
||||
/// </summary>
|
||||
public sealed partial class ContrastThemeTests
|
||||
{
|
||||
/// <summary>A dark contrast theme with every colour edited — the button face no longer the window's.</summary>
|
||||
internal static readonly ContrastPalette EditedDark = new(Color.FromRgb(0x10, 0x10, 0x18), Color.FromRgb(0xFF, 0xFF, 0x00), Color.FromRgb(0x1A, 0xEB, 0xFF),
|
||||
Color.FromRgb(0x00, 0x00, 0x00), Color.FromRgb(0x75, 0xE1, 0xFF), Color.FromRgb(0x3F, 0xF2, 0x3F), Color.FromRgb(0x20, 0x20, 0x40), Color.FromRgb(0xFF, 0xFF, 0xFF));
|
||||
|
||||
/// <summary>A light one, edited the same way.</summary>
|
||||
internal static readonly ContrastPalette EditedLight = new(Color.FromRgb(0xFF, 0xFF, 0xFF), Color.FromRgb(0x10, 0x10, 0x10), Color.FromRgb(0x37, 0x00, 0x6E),
|
||||
Color.FromRgb(0xFF, 0xFF, 0xFF), Color.FromRgb(0x00, 0x00, 0x9F), Color.FromRgb(0x60, 0x00, 0x00), Color.FromRgb(0xF0, 0xF0, 0xE0), Color.FromRgb(0x20, 0x20, 0x20));
|
||||
|
||||
private static readonly Color _red = Color.FromArgb(0xFF, 0xFF, 0, 0);
|
||||
|
||||
private static readonly string[] _fluentThemes = ["Dark", "Light"];
|
||||
|
||||
[GeneratedRegex(@"(?:DynamicResource|StaticResource)\s+(?<key>[A-Za-z]\w+)\}|(?:SetResourceReference\([^,]+,\s*|FindResource\(|TryFindResource\()""(?<key>[A-Za-z]\w+)""", RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant, 1000)]
|
||||
private static partial Regex ResourceKey();
|
||||
|
||||
/// <summary>A named palette for a theory: WPF UI's four defaults by file name, and the two edited ones.</summary>
|
||||
internal static ContrastPalette Named(string name) => name switch
|
||||
{
|
||||
"EditedDark" => EditedDark,
|
||||
"EditedLight" => EditedLight,
|
||||
_ => ContrastRoles.PaletteOf(ContrastRoles.Load(name)),
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The reason the App does not apply WPF UI's high-contrast dictionaries, pinned: the theme name has no file, and each
|
||||
/// file's colours are mostly placeholders. When WPF UI fixes them this goes red, and the overlay may not be needed.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task WpfUisHighContrastThemeIsStillPlaceholdersAndAMissingFile()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
string missing;
|
||||
try
|
||||
{
|
||||
_ = new ThemesDictionary { Theme = ApplicationTheme.HighContrast };
|
||||
missing = "loaded";
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or System.Windows.Markup.XamlParseException or InvalidOperationException)
|
||||
{
|
||||
missing = ex.GetType().Name;
|
||||
}
|
||||
|
||||
int red = 0;
|
||||
foreach (string theme in ContrastRoles.ThemeNames)
|
||||
{
|
||||
ResourceDictionary d = ContrastRoles.Load(theme);
|
||||
red += d.Keys.OfType<string>().Count(k => TryRead(d, k) is Color c && c == _red);
|
||||
}
|
||||
|
||||
return (missing, red);
|
||||
});
|
||||
|
||||
facts.missing.Should().NotBe("loaded", "WPF UI 4.3.0 names a HighContrast theme it has no dictionary for");
|
||||
facts.red.Should().BeGreaterThan(200, "84 of 97 colours of each high-contrast dictionary are a red placeholder (2026-11-09)");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EveryKeyOfWpfUisContrastThemesHasARoleAndThePlaceholdersTooAndNoneIsRed()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> roles = ContrastRoles.Map;
|
||||
var missing = new List<string>();
|
||||
foreach (string theme in ContrastRoles.ThemeNames)
|
||||
{
|
||||
ResourceDictionary d = ContrastRoles.Load(theme);
|
||||
missing.AddRange(d.Keys.OfType<string>().Where(k => !roles.ContainsKey(k) && !ContrastRoles.Clear.ContainsKey(k)).Select(k => theme + ": " + k));
|
||||
}
|
||||
|
||||
ResourceDictionary overlay = ContrastOverlay.Build(EditedDark);
|
||||
string[] red = [.. overlay.Keys.OfType<string>().Where(k => ColourOf(overlay[k]) == _red)];
|
||||
return (roles.Count, Missing: missing.Distinct(StringComparer.Ordinal).ToList(), Red: red, Clear: ContrastRoles.Clear.Keys.ToList(),
|
||||
Pressed: roles["MenuBarItemBackgroundPressed"].Role, PressedText: roles["MenuBarItemTextForegroundPressed"].Role,
|
||||
Critical: roles["SystemFillColorCriticalBrush"].Role, Text: roles["TextFillColorSecondary"].Role);
|
||||
});
|
||||
|
||||
facts.Count.Should().BeGreaterThan(400);
|
||||
facts.Missing.Should().BeEmpty("every key stands for one of the theme's colours or is transparent");
|
||||
facts.Red.Should().BeEmpty("no placeholder survives the overlay");
|
||||
facts.Clear.Should().Contain(["MenuBarBackground", "ControlFillColorTransparentBrush", "SubtleFillColorTransparentBrush"]);
|
||||
facts.Pressed.Should().Be(ContrastRole.Highlight, "a brush WPF UI's file cannot load alone, read in the App as a translucent Fluent fill, takes its role from its name");
|
||||
facts.PressedText.Should().Be(ContrastRole.HighlightText, "so a pressed menu item is the highlight's text on the highlight, not white on white");
|
||||
facts.Critical.Should().Be(ContrastRole.WindowText, "a system fill with no Background in its name is an icon's colour");
|
||||
facts.Text.Should().Be(ContrastRole.WindowText, "a placeholder colour takes its brush twin's role");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The roles do not depend on the Fluent theme lying under the App when they are first read: the brushes that throw when
|
||||
/// WPF UI's file is read alone fall back to the application's resources — the Fluent theme's fills — inside the App.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TheRolesAreTheSameWhicheverFluentThemeLiesUnderThem()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
static (IReadOnlyDictionary<string, (ContrastRole Role, bool Brush)> Roles, IReadOnlyDictionary<string, bool> Clear) Read() =>
|
||||
ContrastRoles.Infer([.. ContrastRoles.ThemeNames.Select(ContrastRoles.Load)]);
|
||||
var dark = Visuals.UnderTheme(ApplicationTheme.Dark, Read);
|
||||
var light = Visuals.UnderTheme(ApplicationTheme.Light, Read);
|
||||
return (Dark: dark.Roles.OrderBy(static p => p.Key, StringComparer.Ordinal).Select(static p => $"{p.Key}={p.Value}").ToList(),
|
||||
Light: light.Roles.OrderBy(static p => p.Key, StringComparer.Ordinal).Select(static p => $"{p.Key}={p.Value}").ToList(),
|
||||
DarkClear: dark.Clear.Keys.Order(StringComparer.Ordinal).ToList(), LightClear: light.Clear.Keys.Order(StringComparer.Ordinal).ToList());
|
||||
});
|
||||
|
||||
facts.Light.Should().Equal(facts.Dark);
|
||||
facts.LightClear.Should().Equal(facts.DarkClear);
|
||||
}
|
||||
|
||||
/// <summary>No colour of a Fluent theme shows through: every colour key the light and the dark themes have, the overlay has.</summary>
|
||||
[Fact]
|
||||
public async Task EveryColourOfTheFluentThemesIsOneTheOverlayGives()
|
||||
{
|
||||
List<string> uncovered = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
ResourceDictionary overlay = ContrastOverlay.Build(EditedDark);
|
||||
var found = new List<string>();
|
||||
foreach (string theme in _fluentThemes)
|
||||
{
|
||||
var d = new ResourceDictionary { Source = new Uri($"pack://application:,,,/Wpf.Ui;component/Resources/Theme/{theme}.xaml", UriKind.Absolute) };
|
||||
found.AddRange(d.Keys.OfType<string>().Where(k => TryRead(d, k) is Color or Brush && !overlay.Contains(k) && !ContrastOverlay.AccentKeys.ContainsKey(k)).Select(k => theme + ": " + k));
|
||||
}
|
||||
|
||||
return found;
|
||||
});
|
||||
|
||||
uncovered.Should().BeEmpty("a key the Fluent themes colour and no contrast dictionary has goes in ContrastOverlay.FluentOnlyKeys with its role");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// With each default theme's own colours, the overlay gives every key the colour WPF UI's file gives it — but the text on
|
||||
/// the accent, which the App departs from on purpose (<see cref="TheTextOnTheAccentIsTheHighlightsText"/>).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task OnEachDefaultThemeTheOverlayGivesEveryKeyTheColourWpfUiGivesIt()
|
||||
{
|
||||
List<string> different = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
var found = new List<string>();
|
||||
foreach (string theme in ContrastRoles.ThemeNames)
|
||||
{
|
||||
ResourceDictionary d = ContrastRoles.Load(theme);
|
||||
ContrastPalette palette = ContrastRoles.PaletteOf(d);
|
||||
ResourceDictionary overlay = ContrastOverlay.Build(palette);
|
||||
foreach (string key in overlay.Keys.OfType<string>().Where(static k => !ContrastOverlay.OnAccentKeys.ContainsKey(k)))
|
||||
{
|
||||
if (ColourOf(TryRead(d, key)) is { A: 0xFF } wpfUi && palette.Colors.Contains(wpfUi) && ColourOf(overlay[key]) is { } ours
|
||||
&& Color.FromRgb(ours.R, ours.G, ours.B) != Color.FromRgb(wpfUi.R, wpfUi.G, wpfUi.B))
|
||||
{
|
||||
found.Add($"{theme}: {key} is {ours} in the overlay, {wpfUi} in WPF UI's file");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return found;
|
||||
});
|
||||
|
||||
string.Join(Environment.NewLine, different).Should().BeEmpty("on Windows' own default contrast themes the overlay is WPF UI's colours, key for key");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The chips the App draws on the accent — the frame-generation factor, RT/PT/RR, the upscaler — read under a contrast
|
||||
/// theme: the accent is the highlight there, so its text is the highlight's text, where WPF UI's files say the window's.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TheTextOnTheAccentIsTheHighlightsText()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
ResourceDictionary hc1 = ContrastRoles.Load("HC1");
|
||||
ContrastPalette palette = ContrastRoles.PaletteOf(hc1);
|
||||
ResourceDictionary overlay = ContrastOverlay.Build(palette);
|
||||
return (Ours: ColourOf(overlay["TextOnAccentFillColorPrimaryBrush"]), WpfUi: ColourOf(TryRead(hc1, "TextOnAccentFillColorPrimaryBrush")), palette.HighlightText, palette.WindowText,
|
||||
Ratio: ColorMath.Contrast(palette.HighlightText, palette.Highlight), WpfUiRatio: ColorMath.Contrast(palette.WindowText, palette.Highlight));
|
||||
});
|
||||
|
||||
facts.Ours.Should().Be(facts.HighlightText);
|
||||
facts.WpfUi.Should().Be(facts.WindowText, "WPF UI 4.3.0's contrast files put the window text on the accent");
|
||||
facts.Ratio.Should().BeGreaterThanOrEqualTo(4.5);
|
||||
facts.WpfUiRatio.Should().BeLessThan(3, "white on Dusk's highlight, 1.62:1 — what the chips read before");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("EditedDark")]
|
||||
[InlineData("EditedLight")]
|
||||
public async Task AnEditedThemesColoursReachEveryKey(string name)
|
||||
{
|
||||
List<string> foreign = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
ContrastPalette palette = Named(name);
|
||||
ResourceDictionary overlay = ContrastOverlay.Build(palette);
|
||||
return overlay.Keys.OfType<string>().Where(k => ColourOf(overlay[k]) is not { } c || !(palette.Colors.Contains(c) || (c.A == 0 && ContrastRoles.Clear.ContainsKey(k)))).ToList();
|
||||
});
|
||||
|
||||
foreign.Should().BeEmpty("every colour of the overlay is one of the user's eight, or transparent where WPF UI's contrast themes are");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task InstallPutsTheColoursAndTheAccentOnAndRemoveTakesThemOff()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() =>
|
||||
{
|
||||
var resources = new ResourceDictionary();
|
||||
ContrastOverlay.Install(resources, EditedDark);
|
||||
var on = (Installed: ContrastOverlay.IsInstalled(resources), Active: ContrastTheme.Active, Accent: ColourOf(resources["AccentFillColorDefaultBrush"]),
|
||||
OnAccent: ColourOf(resources["TextOnAccentFillColorPrimary"]), Merged: resources.MergedDictionaries.Count);
|
||||
ContrastOverlay.Install(resources, EditedLight);
|
||||
int again = resources.MergedDictionaries.Count;
|
||||
ContrastOverlay.Remove(resources);
|
||||
return (on, again, Off: ContrastOverlay.IsInstalled(resources), ActiveOff: ContrastTheme.Active);
|
||||
});
|
||||
|
||||
facts.on.Installed.Should().BeTrue();
|
||||
facts.on.Active.Should().Be(EditedDark);
|
||||
facts.on.Accent.Should().Be(EditedDark.Highlight, "the accent the theme manager writes into the application's resources becomes the highlight");
|
||||
facts.on.OnAccent.Should().Be(EditedDark.HighlightText);
|
||||
facts.again.Should().Be(1, "installing again replaces the overlay");
|
||||
facts.Off.Should().BeFalse();
|
||||
facts.ActiveOff.Should().BeNull();
|
||||
}
|
||||
|
||||
/// <summary>Every resource the App's XAML and code read resolves under a contrast theme, and to no placeholder.</summary>
|
||||
[Theory]
|
||||
[InlineData("HC1")]
|
||||
[InlineData("HCWhite")]
|
||||
[InlineData("EditedDark")]
|
||||
public async Task EveryResourceTheAppReadsResolvesUnderAContrastTheme(string name)
|
||||
{
|
||||
string app = Path.Combine(AccessibilityTests.RepoRoot(), "src", "FrameLedger.App");
|
||||
HashSet<string> keys = new(Directory.EnumerateFiles(app, "*.*", SearchOption.AllDirectories)
|
||||
.Where(static f => (f.EndsWith(".xaml", StringComparison.Ordinal) || f.EndsWith(".cs", StringComparison.Ordinal))
|
||||
&& !f.Contains(Path.DirectorySeparatorChar + "obj" + Path.DirectorySeparatorChar, StringComparison.Ordinal))
|
||||
.SelectMany(static f => ResourceKey().Matches(File.ReadAllText(f)).Select(static m => m.Groups["key"].Value)), StringComparer.Ordinal);
|
||||
|
||||
List<string> broken = await PagesLoadTests.OnStaAsync(() => Visuals.UnderContrast(Named(name), () =>
|
||||
keys.Where(k => System.Windows.Application.Current.TryFindResource(k) is var v && (v is null || ColourOf(v) == _red)).Order(StringComparer.Ordinal).ToList()));
|
||||
|
||||
keys.Should().HaveCountGreaterThan(40);
|
||||
string.Join(", ", broken).Should().BeEmpty("a resource the App reads either resolves under a contrast theme or is not one the App reads");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AContrastThemeWinsOverTheChoiceAndTheChoiceComesBack()
|
||||
{
|
||||
ThemePlan.For(AppTheme.Light, contrastOn: true, contrastDark: true, systemDark: false)
|
||||
.Should().Be(new ThemePlan(ApplicationTheme.Dark, WindowBackdropType.None, WatchSystem: false, Contrast: true), "a dark contrast theme lies over the dark Fluent theme, whatever the choice");
|
||||
ThemePlan.For(AppTheme.Dark, contrastOn: true, contrastDark: false, systemDark: true).Theme.Should().Be(ApplicationTheme.Light);
|
||||
ThemePlan.For(AppTheme.System, contrastOn: true, contrastDark: false, systemDark: true).WatchSystem.Should().BeFalse("WPF UI's watcher would apply its own high-contrast files");
|
||||
ThemePlan.For(AppTheme.System, contrastOn: false, contrastDark: false, systemDark: true)
|
||||
.Should().Be(new ThemePlan(ApplicationTheme.Dark, WindowBackdropType.Mica, WatchSystem: true, Contrast: false));
|
||||
ThemePlan.For(AppTheme.Light, contrastOn: false, contrastDark: true, systemDark: true)
|
||||
.Should().Be(new ThemePlan(ApplicationTheme.Light, WindowBackdropType.Mica, WatchSystem: false, Contrast: false), "off again, the choice applies");
|
||||
FluentActions.Invoking(static () => ThemePlan.For((AppTheme)99, false, false, false)).Should().Throw<ArgumentOutOfRangeException>();
|
||||
}
|
||||
|
||||
private sealed class FakeContrast : IContrastSource
|
||||
{
|
||||
public event EventHandler? Changed;
|
||||
|
||||
public bool IsOn { get; set; }
|
||||
|
||||
public ContrastPalette Palette { get; set; } = EditedDark;
|
||||
|
||||
public void Raise() => Changed?.Invoke(this, EventArgs.Empty);
|
||||
}
|
||||
|
||||
/// <summary>The applier follows a contrast theme on and off as Windows reports it, whatever Settings ▸ Theme says.</summary>
|
||||
[Fact]
|
||||
public async Task TheApplierFollowsAContrastThemeOnAndOffAtOnce()
|
||||
{
|
||||
var facts = await PagesLoadTests.OnStaAsync(() => Visuals.UnderTheme(ApplicationTheme.Dark, () =>
|
||||
{
|
||||
var source = new FakeContrast { IsOn = true, Palette = EditedLight };
|
||||
using var applier = new WpfThemeApplier(source);
|
||||
ResourceDictionary resources = System.Windows.Application.Current.Resources;
|
||||
applier.Apply(AppTheme.Dark, null);
|
||||
bool on = ContrastOverlay.IsInstalled(resources);
|
||||
ApplicationTheme under = ApplicationThemeManager.GetAppTheme();
|
||||
ChartPalette chart = ChartTheme.Current;
|
||||
source.IsOn = false;
|
||||
source.Raise();
|
||||
Visuals.Pump();
|
||||
return (on, under, chart.Figure, Off: ContrastOverlay.IsInstalled(resources), Active: ContrastTheme.Active, After: ApplicationThemeManager.GetAppTheme());
|
||||
}));
|
||||
|
||||
facts.on.Should().BeTrue();
|
||||
facts.under.Should().Be(ApplicationTheme.Light, "a light contrast theme lies over the light Fluent theme, though the choice is Dark");
|
||||
facts.Figure.Should().Be(ChartTheme.ToScottPlot(EditedLight.Window), "the charts take the contrast theme's window colour");
|
||||
facts.Off.Should().BeFalse("turned off in Windows, the overlay comes off at once");
|
||||
facts.Active.Should().BeNull();
|
||||
facts.After.Should().Be(ApplicationTheme.Dark, "and the choice applies again");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("HC1")]
|
||||
[InlineData("EditedLight")]
|
||||
public async Task UnderAContrastThemeEveryChartColourIsOneOfTheThemes(string name)
|
||||
{
|
||||
ContrastPalette palette = await PagesLoadTests.OnStaAsync(() => Named(name));
|
||||
ChartPalette chart = ChartPalette.ForContrast(palette);
|
||||
HashSet<Color> allowed = [.. palette.Colors];
|
||||
|
||||
ChartPalette.Keys.Select(k => (Key: k, Colour: ChartTheme.ToWpf(chart.ByKey(k)))).Where(p => !allowed.Contains(p.Colour)).Select(static p => p.Key)
|
||||
.Should().BeEmpty("under a contrast theme a chart is drawn in the theme's colours only");
|
||||
}
|
||||
|
||||
private static object? TryRead(ResourceDictionary dictionary, string key)
|
||||
{
|
||||
try
|
||||
{
|
||||
return dictionary[key];
|
||||
}
|
||||
catch (Exception ex) when (ex is ResourceReferenceKeyNotFoundException or InvalidOperationException or System.Windows.Markup.XamlParseException)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private static Color? ColourOf(object? value) => value switch
|
||||
{
|
||||
Color c => c,
|
||||
SolidColorBrush b => b.Color,
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,7 @@ using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Media;
|
||||
using FluentAssertions;
|
||||
using FrameLedger.App.Services;
|
||||
using Wpf.Ui.Appearance;
|
||||
using Wpf.Ui.Markup;
|
||||
|
||||
@@ -68,6 +69,109 @@ public sealed partial class PagesLoadTests
|
||||
string.Join(Environment.NewLine, result.Faint).Should().BeEmpty($"every text the App shows reads at {_readableAtLeast}:1 or better in the {theme} theme");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Under a Windows contrast theme (beta.35, owner decision D91) every text is drawn in one of the theme's own colours over
|
||||
/// one of them — nothing of the Fluent theme under it, nothing made translucent — and reads at 4.5:1 or better: WPF UI's
|
||||
/// four default themes, and two the user edited (<see cref="ContrastThemeTests.EditedDark"/>, <see cref="ContrastThemeTests.EditedLight"/>).
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("HC1")]
|
||||
[InlineData("HC2")]
|
||||
[InlineData("HCBlack")]
|
||||
[InlineData("HCWhite")]
|
||||
[InlineData("EditedDark")]
|
||||
[InlineData("EditedLight")]
|
||||
public async Task EveryTextIsInTheContrastThemesColoursAndReadable(string name)
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
using Surfaces surfaces = await Surfaces.LoadAsync(s);
|
||||
|
||||
(int Texts, List<string> Wrong) result = await OnStaAsync(() =>
|
||||
{
|
||||
ContrastPalette palette = ContrastThemeTests.Named(name);
|
||||
return Visuals.UnderContrast(palette, () =>
|
||||
{
|
||||
HashSet<Color> colours = [.. palette.Colors];
|
||||
int texts = 0;
|
||||
var wrong = new List<string>();
|
||||
foreach ((string surface, Func<FrameworkElement> build) in surfaces.All())
|
||||
{
|
||||
(Window host, FrameworkElement root) = Hosted(build);
|
||||
try
|
||||
{
|
||||
Lay(root);
|
||||
foreach (TextBlock text in ShownTexts(root))
|
||||
{
|
||||
texts++;
|
||||
Color under = Visuals.PaintedUnder(text, root, palette.Window);
|
||||
Color drawn = Visuals.TextOver(text, under);
|
||||
double ratio = Wcag.Ratio(drawn, under);
|
||||
if (!colours.Contains(drawn) || !colours.Contains(under) || ratio < Wcag.AA)
|
||||
{
|
||||
wrong.Add(string.Create(CultureInfo.InvariantCulture, $"{surface}: \"{text.Text}\" {drawn} on {under}, {ratio:0.00}:1"));
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
host.Close();
|
||||
}
|
||||
}
|
||||
|
||||
return (texts, wrong);
|
||||
});
|
||||
});
|
||||
|
||||
result.Texts.Should().BeGreaterThan(300, "every surface was rendered and holds text");
|
||||
string.Join(Environment.NewLine, result.Wrong).Should().BeEmpty($"under the {name} contrast theme every text is the theme's colour on the theme's colour, at {Wcag.AA}:1 or better");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The line under Settings ▸ Theme says a contrast theme's colours are used while one is on, and goes when it is off — on
|
||||
/// the page as it is shown, without visiting it again (beta.35, D91).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task TheSettingsPageSaysAContrastThemeIsOnWhileItIs()
|
||||
{
|
||||
await using ScratchLedger s = await ScratchLedger.OpenAsync();
|
||||
using Surfaces surfaces = await Surfaces.LoadAsync(s);
|
||||
|
||||
var facts = await OnStaAsync(() => Visuals.UnderTheme(ApplicationTheme.Dark, () =>
|
||||
{
|
||||
Func<FrameworkElement> build = surfaces.All().Single(static p => string.Equals(p.Item1, "Settings", StringComparison.Ordinal)).Item2;
|
||||
(Window host, FrameworkElement root) = Hosted(build);
|
||||
try
|
||||
{
|
||||
Lay(root);
|
||||
TextBlock note = Visuals.FindAll<TextBlock>(root).Single(static t => string.Equals(t.Text, Strings.Settings_Theme_ContrastOn, StringComparison.Ordinal));
|
||||
Visibility off = note.Visibility;
|
||||
ResourceDictionary resources = System.Windows.Application.Current.Resources;
|
||||
ContrastOverlay.Install(resources, ContrastThemeTests.EditedDark);
|
||||
Visibility on;
|
||||
try
|
||||
{
|
||||
Visuals.Pump();
|
||||
on = note.Visibility;
|
||||
}
|
||||
finally
|
||||
{
|
||||
ContrastOverlay.Remove(resources);
|
||||
}
|
||||
|
||||
Visuals.Pump();
|
||||
return (off, on, Again: note.Visibility);
|
||||
}
|
||||
finally
|
||||
{
|
||||
host.Close();
|
||||
}
|
||||
}));
|
||||
|
||||
facts.off.Should().Be(Visibility.Collapsed);
|
||||
facts.on.Should().Be(Visibility.Visible);
|
||||
facts.Again.Should().Be(Visibility.Collapsed);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The non-empty texts under <paramref name="root"/> that a user can see and is meant to read: no collapsed or hidden
|
||||
/// element above them, and none disabled (WCAG asks nothing of an inactive control's text).
|
||||
|
||||
@@ -121,6 +121,29 @@ internal static class Visuals
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runs <paramref name="work"/> under a Windows contrast theme the way the App follows one (beta.35, D91): the light or
|
||||
/// the dark Fluent theme as the contrast theme is, under <c>ContrastOverlay</c> with its colours, and <c>ContrastTheme.Active</c>
|
||||
/// set — then everything put back as <see cref="UnderTheme{T}"/> puts it back.
|
||||
/// </summary>
|
||||
public static T UnderContrast<T>(FrameLedger.App.Services.ContrastPalette palette, Func<T> work)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(palette);
|
||||
return UnderTheme(palette.IsDark ? ApplicationTheme.Dark : ApplicationTheme.Light, () =>
|
||||
{
|
||||
ResourceDictionary resources = System.Windows.Application.Current.Resources;
|
||||
FrameLedger.App.Services.ContrastOverlay.Install(resources, palette);
|
||||
try
|
||||
{
|
||||
return work();
|
||||
}
|
||||
finally
|
||||
{
|
||||
FrameLedger.App.Services.ContrastOverlay.Remove(resources);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The colour painted under <paramref name="element"/>: every Border's and Panel's background from <paramref name="root"/>
|
||||
/// down to the element, composited over <paramref name="window"/> — what a template's parts draw, which is what the eye sees.
|
||||
|
||||
Reference in new issue
Block a user