Compare commits

..
Author SHA1 Message Date
poli0981andClaude Opus 5.5 eb40696d71 spike: a shapes probe for the Twelve Data answers P3 has not seen
`dotnet run --project spikes/ProviderProbe -- shapes [429]`, with
OD_TWELVEDATA_KEY set, asks about ten credits' worth of the cases the P3
parser handles defensively but no real key has shown: a batch with an
unknown symbol, a batch with a plan-limited listing (SAP:XETR), the
mic_code form, a single unknown symbol, a trailing comma, a dotted symbol
(BRK.B) and an unknown series; "429" adds a burst over the minute's eight.

It prints structure only: HTTP status, the answer's shape, field names,
error codes and Twelve Data's messages, and which credit headers came
back. It never prints a figure or the key, and saves nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:10:45 +07:00
poli0981andClaude Opus 5.5 2a87046461 spike: add MediaLab for LibVLCSharp in a FluentWindow
MediaLab (spike #6, issue #7) hosts LibVLCSharp's VideoView in a WPF-UI
FluentWindow with Mica, with overlay controls, fullscreen in place,
fullscreen in its own window, a pop-out, and a tray-style hide. It
captures the screen at each step, since only a screen capture shows
airspace problems, and logs memory, CPU and frame statistics. `--auto`
runs everything unattended. `--auto-move --seek-on-move` checks the
player hand-over to another window. `-p:TrimVlc=true` builds the SPEC
plugin set to measure what libVLC adds to the installer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:15:36 +07:00
poli0981andClaude Opus 5.5 3eae21ef5a spike: check sign-ins after a restart, and run single-app ladders
`--check-signed-in` reopens Gmail, YouTube, Spotify, Facebook and
Discord on their saved profiles and asks each page whether it is
signed in. Gmail then reloads with CDP capture on. `--ladder=ids` runs
only the governor ladder for the listed apps, checking the sign-in
before and after.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:54:31 +07:00
poli0981andClaude Opus 5.5 6c60b86c78 spike: probe cookie persistence across host shutdowns
After the interactive sign-in session was closed, every cookie it had
set was gone from all four profiles, while cookies from scripted runs
survived. `--cookie-set=NAME [--exit=clean]` and `--cookie-check` set
a one-year cookie on a lab page, wait past the 30 s commit interval,
and read it back after a restart. It survived a clean exit, a window
close, a host kill, and a hard kill of the whole WebView2 tree, so the
loss is not explained by how the host shut down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:34:37 +07:00
poli0981andClaude Opus 5.5 ec79454d38 spike: measure the ladder on signed-in apps
`WebLab --measure [--phase=60]` drives spikes #3 and #4 on the
profiles signed in by hand: a governor ladder for Discord, YouTube and
Gmail, every catalog app open at once (Messenger excluded, since
messenger.com closed in April 2026), then CDP capture on Gmail,
Discord and Spotify: cost with capture off and on, and a reload with
Runtime.enable on. Logged page titles have email addresses redacted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 13:02:00 +07:00
poli0981andClaude Opus 5.5 6e8694a68d spike: freeze the Twelve Data response models
TwelveDataModels.cs holds the shapes spike #7 (issue #8) settles on:
quote (single and batch), time series, symbol search with the plan
each listing needs, API usage and errors. Numbers arrive as JSON
strings, so the shared options read numbers from strings and use
snake_case names. `verify-models` deserializes the newest saved
responses with them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 12:20:30 +07:00
poli0981andClaude Opus 5.5 0fe4b12a0c spike: add WebLab for the WebView2 spikes
WebLab (spikes #1-#4, issues #2-#5) hosts catalog apps on one shared
WebView2 environment with one profile per catalog profile group and
the catalog's navAllow/popupAllow policy (logged, query strings
redacted). Per slot it runs the governor's steps: hide, TrySuspendAsync
+ Low, resume, dispose with only {url} kept, and reopen.

A 2 s sampler records private commit, private working set and working
set for every WebView2 process, attributes renderers to apps through
GetProcessExtendedInfosAsync, and writes CSV with phase marks; "Run
ladder" scripts the state sequence. Lab pages probe EME key systems
and the user agent, and test whether a page can detect CDP console
capture, which runs with the DevTools UI disabled.

`--auto` runs the unattended checks: EME, CDP capture and detection,
the environment baseline, and a short ladder on YouTube.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 12:03:19 +07:00
poli0981andClaude Opus 5.5 840c511618 spike: add ThemeLab for the runtime preset swap
ThemeLab (spike #5, issue #6) swaps a code-built Od.* preset layer in
Application.Resources on top of WPF-UI 4.3, next to the Light/Dark
axis. It probes which WPF-UI keys follow a swap, benchmarks the swap
with and without 3,000+ elements, compares the registry and WinRT
text scale sources, and tries a DynamicResource inside a style
storyboard. `--auto` runs every unattended measurement and writes the
log under %LocalAppData%\OmniDeck.Spikes\theme.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:53:43 +07:00
poli0981andClaude Opus 5.5 74339a552c spike: scaffold the P0 spike solution and ProviderProbe
spikes/ holds throwaway proof-of-concept code for the P0 spikes on
this branch, which is never merged. Its Directory.Build.props stands
alone (no repository analyzer set) but keeps NuGet Audit.

ProviderProbe (spike #7, issue #8) sends single plain requests to
Stooq and Twelve Data and keeps the raw responses under
%LocalAppData%\OmniDeck.Spikes\providers. The Twelve Data key comes
from OD_TWELVEDATA_KEY and travels in the Authorization header only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:47:48 +07:00
414 changed files with 3302 additions and 27028 deletions

No files matched your search

+2 -10
View File
@@ -51,14 +51,6 @@ dotnet_diagnostic.IDE0005.severity = warning # unnecessary using
dotnet_diagnostic.CA1848.severity = none # LoggerMessage delegates: overkill here
dotnet_diagnostic.MA0026.severity = suggestion # TODO comments: SonarCloud (S1135) already tracks them
[src/{OmniDeck.App,OmniDeck.Modules,OmniDeck.Web}/**.cs]
# UI code (the shell, the modules and the web runner) must resume on the dispatcher thread, so ConfigureAwait(false) is wrong here.
dotnet_diagnostic.MA0004.severity = none
[src/OmniDeck.Core/{Modules,Governor}/**.cs]
# The module host and the governor drive module views from the dispatcher thread as well.
dotnet_diagnostic.MA0004.severity = none
[tests/**.cs]
# Tests await on the STA dispatcher (OdSta) or in xUnit's own context; xUnit1030 forbids ConfigureAwait(false) there.
[src/OmniDeck.App/**.cs]
# UI code must resume on the dispatcher thread, so ConfigureAwait(false) is wrong here.
dotnet_diagnostic.MA0004.severity = none
+5 -11
View File
@@ -51,30 +51,24 @@ jobs:
- name: Restore pinned tools
run: dotnet tool restore
# dotnet format loads the app with the XAML markup compiler, which needs OmniDeck.Core.dll on
# disk to resolve {res:OdLoc ...}; without it the window classes lose their generated half and
# the analyzers report phantom findings.
- name: Build Core for the XAML compiler
run: dotnet build src/OmniDeck.Core/OmniDeck.Core.csproj --no-restore
- name: Verify C# formatting
run: dotnet format OmniDeck.slnx --verify-no-changes --no-restore
- name: Verify XAML formatting (XamlStyler)
run: dotnet xstyler -c Settings.XamlStyler -d src -r -p
- name: Design tokens only in module and web views
- name: Design tokens only in module views
shell: pwsh
run: |
# docs/UI-MODES.md §2: module and web-runner views consume Od.* tokens, never a literal FontSize.
# docs/UI-MODES.md §2: module views consume Od.* tokens, never a literal FontSize.
$hits = Get-ChildItem -Path src -Recurse -Filter *.xaml |
Where-Object { $_.FullName -match '[\\/]OmniDeck\.(Modules|Web)[\\/]' } |
Where-Object { $_.FullName -match '[\\/]OmniDeck\.Modules[\\/]' } |
Select-String -Pattern 'FontSize\s*=\s*"\s*\d'
if ($hits) {
$hits | ForEach-Object { Write-Host "::error file=$($_.Path),line=$($_.LineNumber)::Literal FontSize in a module or web view; use an Od.* token." }
$hits | ForEach-Object { Write-Host "::error file=$($_.Path),line=$($_.LineNumber)::Literal FontSize in a module view; use an Od.* token." }
exit 1
}
Write-Host 'No literal FontSize in module or web views.'
Write-Host 'No literal FontSize in module views.'
- name: Build (Release, warnings are errors)
run: dotnet build OmniDeck.slnx -c Release --no-restore
+1 -3
View File
@@ -102,9 +102,7 @@ jobs:
'/d:sonar.cs.vstest.reportsPaths=TestResults/*.trx',
'/d:sonar.cs.roslyn.ignoreIssues=true',
'/d:sonar.exclusions=**/bin/**,**/obj/**,**/TestResults/**,publish/**,Releases/**',
# Views, and the thin wrappers over the native engines (the WebView2 runtime, libVLC), run only
# against those engines, which CI does not load; the logic around them is tested on its own.
'/d:sonar.coverage.exclusions=**/*.xaml.cs,**/Program.cs,**/OdWebRuntime.cs,**/OdVlcEngine.cs,**/OdVlcPlayer.cs,scripts/**,.github/**'
'/d:sonar.coverage.exclusions=**/*.xaml.cs,**/Program.cs,scripts/**,.github/**'
)
dotnet sonarscanner @scannerArgs
if ($LASTEXITCODE -ne 0) { throw "SonarScanner begin failed with exit code $LASTEXITCODE." }
-4
View File
@@ -25,9 +25,5 @@ bugreport-*.zip
*.DotSettings.user
.nuget/
# Python bytecode (CI helper scripts under .github/scripts)
__pycache__/
*.py[cod]
# Personal Claude Code settings (.claude/settings.json is shared and committed)
.claude/settings.local.json
+1 -213
View File
@@ -6,211 +6,6 @@ All notable changes to OmniDeck are documented here. The format follows
## [Unreleased]
## [0.2.0-alpha.3] — 2026-11-02
Third P2 alpha, the build to try out before 0.2.0: pop-out windows, web pages in full screen, an icon
of its own, and fixes to the media player's controls.
### Added
- Any module can open in a window of its own: choose "Open in new window" in its sidebar menu, or the
window button on its library tile. It runs there beside whatever the main window shows, and OmniDeck
never puts it to sleep while its window is open. Closing the window puts it back in the sidebar;
"Return to main window" shows it there. Web apps and videos keep playing through the move, and the
module's window goes full screen like the main window.
- Web apps: a video, or anything else a page shows full screen, now fills the screen, and Esc goes
back.
- OmniDeck has an icon of its own, a white "O" on blue: on the program, its windows, the taskbar and
the installer.
### Changed
- Media: the Play/Pause button shows Pause while something plays.
- The roadmap is re-baselined: P2 started on 2 November 2026, as soon as P1 was done. The README,
the spec and the architecture notes now describe what P2 built.
### Fixed
- Media: in full screen the picture started a few pixels from the left edge of the screen. It now
fills the screen.
- Media: beside the queue, the seek bar shrank to almost nothing, and at the window's default size
the queue button was cut off. The seek bar now has a row of its own, and the volume slider gets
shorter before anything is cut off.
## [0.2.0-alpha.2] — 2026-11-02
Second P2 alpha: the media player and the bug report join the web apps of alpha.1. Pop-out windows
and the final polish come before 0.2.0.
### Added
- Media: play your own music and videos. Add files, a folder or an .m3u playlist, or drop them on the
player; the queue and where you stopped are kept for next time, and the queue can be saved as an
.m3u. OmniDeck keeps the player running while something plays, and frees its memory once it has
been paused and out of sight for a while. Its More menu picks the audio and subtitle tracks, adds
a subtitle file and sets its encoding, plays from a quarter to four times the speed, sends the
sound to another device, and saves a snapshot of the picture in Pictures\OmniDeck. A double-click
on the video, or its full-screen button, fills the screen, and Esc goes back. While something is
loaded, the tray menu names it and offers play or pause, next and previous.
- Report a bug from Settings → About, or from the dialog that shows an error. OmniDeck shows the
issue text first, then saves a report on this PC: the issue text, the version and Windows build,
the modules and the memory they use, the end of the log and, for a web app, its console. It then
opens a new GitHub issue in your browser with the short fields filled in. Nothing is sent: attach
the report yourself. Addresses keep no query, and tokens, cookies, email addresses, long ids and
your user name are taken out first. The ten newest reports are kept.
### Fixed
- A dialog that opened while a web app was on screen could hide behind the page. The page now steps
aside while a dialog is open.
## [0.2.0-alpha.1] — 2026-11-02
First P2 alpha, for trying the web apps out. The eight apps of the catalog run inside OmniDeck on
Microsoft Edge WebView2, with their notifications, site permissions and memory figures, and Weather
and Calendar join the built-in modules. The bug report, Media, pop-out windows and the final polish
arrive in the next alphas.
### Added
- Weather: forecasts from Open-Meteo for the places you save, found by searching for a city. It
shows the conditions now, the next 48 hours and the next 7 days, in the units your region uses or
the ones you pick. A forecast is fetched again at most every half hour, and only while Weather is
on screen; without a connection it shows the last forecast and says how old it is.
- Calendar: your own events in a month grid, a week list or a 30-day agenda, with repeats (daily,
weekly, monthly or yearly, every so many, until a date) and reminders, which appear while OmniDeck
is running. Import and export .ics files; repeats written by other calendar apps are kept as they
are. One date of a series can be deleted without touching the rest.
- OmniDeck keeps its list of web apps up to date: once a day it checks the list in this repository and,
when there is a newer valid one, uses it from the next start.
- Web apps: Spotify, Discord, YouTube, Gmail, Google Calendar, Google Drive, Google Maps and Facebook
open inside OmniDeck like the built-in modules. The Google apps share one sign-in; every other app
keeps its own. A link to another site opens in your default browser, while sign-in popups stay in
the app. A web app that sleeps or is closed down to save memory comes back on the page it showed;
one whose page crashes reloads by itself. Downloads go to your Downloads folder.
- Web app notifications appear as Windows notifications under the app's name. Clicking one opens the
app on what it was about. Settings → Web apps turns them on or off for each app. An app with
notifications on keeps running while hidden, so it can still notify you; OmniDeck closes it only
when memory runs short, and tells you when it does.
- When a web app asks for your camera, microphone, location, clipboard or a similar permission,
OmniDeck asks you above the app and remembers your answer for that app. Settings → Web apps lists
the answers, lets an app ask again, and clears a group of apps' sign-in data.
### Changed
- Clicking a notification opens the module that raised it: a finished timer opens Timer.
- Settings → Memory shows what each open web app uses, and the browser processes they share in a row
of their own. The memory limits count the web apps' processes too. When OmniDeck must free memory,
it picks the app that uses more among those hidden for as long. When the shared processes alone
keep it over the limit, OmniDeck says so instead of closing apps that would free nothing.
- Quitting closes every open module first, so each one can save its state before OmniDeck exits. With
web apps open, it also waits a moment for the browser to save its cookies, so you stay signed in.
- OmniDeck re-styles its windows only when Windows' dark or light mode, accent color, High Contrast or
animation setting changes, not on every settings broadcast from Windows.
## [0.1.1] — 2026-11-02
A fix release for 0.1.0. Picking accent colors, or Windows changing a theme setting, could make
OmniDeck run out of Windows graphics handles, show "A generic error occurred in GDI+" over and over,
and stop drawing its window. Installed copies find this update in Settings → About, and say so in a
notification within a day.
### Fixed
- Changing the accent color no longer ends in "Something went wrong… A generic error occurred in
GDI+". The notification-area icon leaked a Windows graphics handle every time it was redrawn in a
new color, and each change redrew it more often than the last, so after enough color or theme
changes OmniDeck ran out of handles and could stop drawing its window. The icon is now drawn by
OmniDeck itself and redrawn only when the color actually changes.
- Toggle switches take a newly picked accent color at once. Before, they kept the previous color
until the next change.
- An error that keeps repeating is now reported once a minute, with a count of the repeats, instead
of every time, so a single fault can no longer stack error dialogs or fill the logs.
- Logs are kept for seven days, as the privacy policy says. Before, a burst of errors could push out
the whole week of logs before it.
## [0.1.0] — 2026-10-30
The first installable OmniDeck, closing phase P1. It brings the shell with its sidebar, module
library, command palette and notification-area icon, plus the RAM governor and its panel. It also
has the clock, timer and calculator, the settings, legal documents and onboarding, and updates from
inside the app. The 0.1.0-alpha.1 and 0.1.0-alpha.2 notes list all of it in detail. Web apps,
weather, calendar, stocks and media arrive in P2 and P3.
### Added
- Keyboard shortcuts: Ctrl+1 to Ctrl+9 open the modules in the sidebar, in order, and Ctrl+, opens
Settings; Ctrl+K still opens the command palette.
- Installed copies check for updates a few minutes after starting and then once a day, and say so in
a notification when a new version is out. Opening Settings → About checks too. Nothing downloads
until you choose to.
### Changed
- The sidebar follows the layout preset as you switch: Dynamic shows icons only, with each name in a
tooltip, and Comfort shows at most six modules, always including the one on screen.
### Fixed
- The command palette shrinks to fit a short list of results.
- With High Contrast on, Windows' colors win over a custom accent color.
- Lines and borders in the legal documents follow the theme, High Contrast included.
- Screen readers announce the layout presets and settings choices by their names.
## [0.1.0-alpha.2] — 2026-10-30
Second alpha: the settings pages, the legal gate and onboarding. It is also the first build that can
update itself. 0.1.0-alpha.1 cannot, so install this one over it with its `Setup.exe` and choose to
overwrite; your settings and data stay. From here on, Settings → About → Check for updates finds new
releases.
### Added
- First run: the license agreement, disclaimer, privacy policy and third-party notices, shown from the
app's `legal` folder, to acknowledge before OmniDeck opens (again after each legal update). Then a
short setup picks the language and the layout preset.
- Settings: General (language, keep running in the notification area, start with Windows), Appearance
(theme, layout preset, text size, animations, accent color), Memory (the governor's thresholds and
the running modules), Data (open the data folder, export and import settings) and About (version,
update check, links, the legal documents).
- Starting with Windows opens OmniDeck straight to the notification area.
### Changed
- Running modules moved from the sidebar into Settings → Memory; the command palette opens it too.
## [0.1.0-alpha.1] — 2026-10-30
First alpha, for trying OmniDeck out: the shell, the RAM governor and three built-in modules. Web
apps, weather, calendar, stocks and media arrive in P2–P3, and the settings pages, legal gate and
onboarding in the next alpha.
### Added
- One OmniDeck per Windows session: starting it again brings the running window to the front.
- Settings stored in `%LocalAppData%\OmniDeck.Data\settings.json`, written atomically. A damaged
file is set aside and defaults take over.
- Local log files in `%LocalAppData%\OmniDeck.Data\logs`, kept for seven days, plus crash handling
that shows a support code and keeps OmniDeck running.
- Uninstalling removes `%LocalAppData%\OmniDeck.Data`, as the privacy policy promises.
- A local database, `%LocalAppData%\OmniDeck.Data\omnideck.db`, with a versioned schema that
upgrades itself at startup.
- The window follows Windows: light or dark mode, the accent color, High Contrast and the text size.
- The shell: a sidebar with pinned and open modules, a module library to open and pin them from,
and a command palette (Ctrl+K, or the search box in the title bar) that finds modules and commands.
- Closing the window keeps OmniDeck running in the notification area; its icon's menu opens or quits
it. Modules can raise Windows notifications from there.
- The RAM governor: modules hidden for 5 minutes are suspended and after 30 minutes hibernated.
Above a soft memory limit the least recently used one is hibernated; above a hard limit as many as
it takes, with a notification. The limits default to min(4.5 GB, 35 % of RAM) and min(6 GB, 50 %).
- Running modules (the sidebar's Memory item): every module's state and last use, memory in use
against the limits, and Suspend, Hibernate, Close and Keep running controls.
- Clock: local time and any number of world clocks, in 12- or 24-hour time, with each zone's offset
from here. The zones are remembered.
- Timer: countdowns with presets (1, 5, 10 and 25 minutes) or a custom length and name, and a
stopwatch with laps. A finished countdown raises a Windows notification, also from the
notification area, and the tray menu starts a 5-minute timer. Timers run only while OmniDeck
runs, as the module says.
- Calculator: standard and scientific keypads (degrees or radians), keyboard input, the session's
history, and copying the result.
### Changed
- Stocks: Twelve Data with the user's own API key is now the only provider. Stooq was dropped because
its download endpoints now block scripted clients (P0 spike #7). The free Twelve Data plan covers US
listings; home-market EU listings and indices need a paid plan.
- Legal documents (EULA, disclaimer, privacy policy) are now version 1.1, and the third-party notices
follow: Stooq and Messenger are no longer mentioned.
### Removed
- Messenger from the web app catalog: Meta closed messenger.com on 15 April 2026 and sends web
users to `facebook.com/messages`, which the Facebook entry already covers.
## [0.0.1-alpha.1] — 2026-10-28
Kickoff build. It proves the build, packaging, and release pipeline end to end and has no
@@ -235,12 +30,5 @@ user-facing features yet: the window only shows the version.
- Supported platform narrowed to Windows 11 (24H2 or later), x64.
- App data moves to `%LocalAppData%\OmniDeck.Data`, outside Velopack's install folder.
[Unreleased]: https://github.com/poli0981/OmniDeck/compare/v0.2.0-alpha.3...HEAD
[0.2.0-alpha.3]: https://github.com/poli0981/OmniDeck/compare/v0.2.0-alpha.2...v0.2.0-alpha.3
[0.2.0-alpha.2]: https://github.com/poli0981/OmniDeck/compare/v0.2.0-alpha.1...v0.2.0-alpha.2
[0.2.0-alpha.1]: https://github.com/poli0981/OmniDeck/compare/v0.1.1...v0.2.0-alpha.1
[0.1.1]: https://github.com/poli0981/OmniDeck/compare/v0.1.0...v0.1.1
[0.1.0]: https://github.com/poli0981/OmniDeck/compare/v0.1.0-alpha.2...v0.1.0
[0.1.0-alpha.2]: https://github.com/poli0981/OmniDeck/compare/v0.1.0-alpha.1...v0.1.0-alpha.2
[0.1.0-alpha.1]: https://github.com/poli0981/OmniDeck/compare/v0.0.1-alpha.1...v0.1.0-alpha.1
[Unreleased]: https://github.com/poli0981/OmniDeck/compare/v0.0.1-alpha.1...HEAD
[0.0.1-alpha.1]: https://github.com/poli0981/OmniDeck/releases/tag/v0.0.1-alpha.1
+1 -8
View File
@@ -19,13 +19,6 @@ dotnet test OmniDeck.slnx
dotnet run --project src/OmniDeck.App
```
To run a development build beside an installed OmniDeck, give it a data root of its own. Only Debug builds read the variable, so the installed copy keeps its settings, sign-ins and database, and the two run side by side:
```powershell
$env:OMNIDECK_DATA_ROOT = "$env:TEMP\OmniDeck.Dev"
dotnet run --project src/OmniDeck.App
```
## Code style & quality gates (enforced in CI)
- `.editorconfig` is authoritative. `dotnet format OmniDeck.slnx --verify-no-changes` must pass.
@@ -50,7 +43,7 @@ dotnet run --project src/OmniDeck.App
## Reporting bugs
Prefer the in-app **Settings → About → Report a bug** flow — it captures the console errors and logs the template asks for. For web app issues, include the console errors it captured; "it doesn't work" without details is triaged last.
Prefer the in-app **About → Report bug** flow (from P2) — it captures the console errors and logs the template asks for. For web app issues, include the console errors it captured; "it doesn't work" without details is triaged last.
## Contact
+2 -2
View File
@@ -47,7 +47,7 @@
<RepositoryUrl>https://github.com/poli0981/OmniDeck</RepositoryUrl>
<PackageProjectUrl>https://github.com/poli0981/OmniDeck</PackageProjectUrl>
<RepositoryType>git</RepositoryType>
<Version>0.2.0-alpha.3</Version>
<Version>0.0.1-alpha.1</Version>
</PropertyGroup>
<!-- Build-time analyzers (warnings are errors). They live here rather than in each .csproj:
@@ -63,7 +63,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Meziantou.Analyzer" Version="3.0.318">
<PackageReference Include="Meziantou.Analyzer" Version="3.0.317">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
-2
View File
@@ -2,8 +2,6 @@
<Folder Name="/src/">
<Project Path="src/OmniDeck.App/OmniDeck.App.csproj" />
<Project Path="src/OmniDeck.Core/OmniDeck.Core.csproj" />
<Project Path="src/OmniDeck.Modules/OmniDeck.Modules.csproj" />
<Project Path="src/OmniDeck.Web/OmniDeck.Web.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/OmniDeck.Tests/OmniDeck.Tests.csproj" />
+7 -8
View File
@@ -2,24 +2,23 @@
> One deck for your everyday apps — a Windows 11 host for native mini-apps and curated web apps.
[![Status](https://img.shields.io/badge/status-alpha-orange)](docs/ROADMAP.md)
[![Status](https://img.shields.io/badge/status-pre--alpha-red)](docs/ROADMAP.md)
[![Platform](https://img.shields.io/badge/platform-Windows%2011%20x64-blue)](#install)
[![License](https://img.shields.io/badge/license-GPL--3.0-green)](LICENSE)
[![.NET](https://img.shields.io/badge/.NET-10%20LTS-purple)](https://dotnet.microsoft.com/)
[![CI](https://github.com/poli0981/OmniDeck/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/poli0981/OmniDeck/actions/workflows/ci.yml)
[![Quality Gate](https://sonarcloud.io/api/project_badges/measure?project=poli0981_OmniDeck&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=poli0981_OmniDeck)
OmniDeck combines a set of lightweight native mini-apps (weather, calculator, stocks, media player, clock, timer, calendar) with a curated runner for popular web apps (Spotify, Discord, YouTube, Gmail, Google Calendar, Google Drive, Google Maps, Facebook) — no separate installs, one window, one tray icon.
OmniDeck combines a set of lightweight native mini-apps (weather, calculator, stocks, media player, clock, timer, calendar) with a curated runner for popular web apps (Spotify, Discord, YouTube, Gmail, Google Calendar, Google Drive, Google Maps, Facebook, Messenger) — no separate installs, one window, one tray icon.
It is built on WPF (.NET 10 LTS) and **WebView2**, which reuses the Edge runtime that ships with Windows 11 instead of bundling a browser engine. That is what keeps the installer small while still running full web apps.
**Project status: alpha.** 0.2.0-alpha.2 (phase P2) runs the curated web apps beside the clock, timer, calculator, weather, calendar and media player, with pop-out windows and an in-app bug report. Stocks, the polished Dynamic and Comfort presets, and the Vietnamese and Japanese translations come in P3; the 0.9 public beta is planned for April 2027 and v1.0 for May 2027 ([roadmap](docs/ROADMAP.md)). Until then, expect missing features and changes between versions.
**Project status: pre-alpha.** Development starts with phase P0 on 2 November 2026; the 0.9 public beta is planned for April 2027 and v1.0 for May 2027 ([roadmap](docs/ROADMAP.md)). Builds published before then are pipeline and development builds without the features below — follow along, but don't install them expecting a working app yet.
## Planned features (v1.0)
- **Native mini-apps** — clock & world clocks, countdown timer, calculator, weather (Open-Meteo), local calendar with `.ics` import/export, stock watchlist with candlestick charts (US/EU markets), and a full-codec media player (libVLC).
- **Curated web apps** — each runs in its own WebView2 profile with a per-app navigation allowlist. Web notifications become Windows toasts. Adding a new app is a JSON entry, not a release ([catalog docs](docs/WEBAPP-CATALOG.md)).
- **Pop-out windows** — any module can move into a window of its own, and go full screen there.
- **RAM governor** — inactive modules are automatically suspended and then hibernated, with a hard memory cap. A built-in task-manager panel shows per-module RAM with manual suspend/kill ([details](docs/RAM-GOVERNOR.md)).
- **Three UI presets** — Dynamic, Standard, and Comfort, implemented as design-token presets over one theme engine, with per-token overrides ([details](docs/UI-MODES.md)).
- **Privacy** — zero telemetry, zero data collection. Everything is stored locally ([privacy policy](docs/legal/PRIVACY.md)).
@@ -33,21 +32,21 @@ Running web apps means running Chromium processes. OmniDeck manages this aggress
These are properties of the web versions of the services, documented here so they are not reported as OmniDeck bugs:
- **Spotify** runs the Web Player: audio quality is lower than the desktop app, and playback relies on DRM (Widevine), which ships with the WebView2 runtime (P0 spike #1). If a future runtime drops it, the entry is disabled with an explanation (see the [ROADMAP](docs/ROADMAP.md) risk register).
- **Discord** web has no native global push-to-talk and limited screen sharing. A host-side global hotkey is on the roadmap's backlog.
- **Spotify** runs the Web Player: audio quality is lower than the desktop app, and playback requires DRM (Widevine) support in the WebView2 runtime. A P0 spike decides whether the entry ships; if DRM is unavailable, it ships disabled with an explanation (see the [ROADMAP](docs/ROADMAP.md) risk register).
- **Discord** web has no native global push-to-talk and limited screen sharing. OmniDeck provides a host-side global hotkey as partial mitigation.
- Web app availability, layout, and sign-in flows are controlled by the respective service providers and can change or break at any time.
## Install
1. Requirements: **Windows 11 (24H2 or later), x64.** Windows 10 is not supported. The Microsoft Edge **WebView2 Runtime** ships with Windows 11.
2. Download a build from [Releases](https://github.com/poli0981/OmniDeck/releases) and run `OmniDeck-win-Setup.exe` (per-user, no admin required). Every version before 1.0 is published as a **pre-release** for testing.
3. On first run, review and acknowledge the legal documents (EULA, disclaimer, privacy policy, third-party notices), then pick a UI preset and language.
3. On first run (from P1 on), review and acknowledge the legal documents (EULA, disclaimer, privacy policy, third-party notices), then pick a UI preset and language.
Updates are delivered in-app via Velopack; you can also check manually from **About**. Builds are not yet Authenticode-signed, so Windows SmartScreen may warn about an unknown publisher — see [SECURITY](SECURITY.md) for how to verify a download.
## Reporting bugs
Use **Settings → About → Report a bug** inside the app, or **Report bug** on an error dialog. OmniDeck shows the report first, then saves a `bugreport-*.zip` to `%LocalAppData%\OmniDeck.Data\reports` (the issue text, the version and Windows build, the modules and their memory, the end of the log and, for a web app, its console), shows it in Explorer, and opens a GitHub issue with the short fields filled in. Nothing is uploaded: attach the zip yourself. Addresses lose their query strings, and tokens, cookies, email addresses, long ids and your user name are taken out first. You can also file manually with the [bug template](https://github.com/poli0981/OmniDeck/issues/new?template=bug_report.yml).
Use **About → Report bug** inside the app (from P2). It pre-fills a GitHub issue with the app version, OS build, active modules, and captured console errors from the affected web app, and saves a `bugreport-*.zip` (logs) to `%LocalAppData%\OmniDeck.Data\reports` that you can attach. Sensitive values (query strings, cookies, tokens) are scrubbed before packaging. You can also file manually with the [bug template](https://github.com/poli0981/OmniDeck/issues/new?template=bug_report.yml).
## Documentation
+1 -1
View File
@@ -21,7 +21,7 @@ These are design requirements from the [SPEC](docs/SPEC.md); each one is enforce
- Web apps run only from the reviewed catalog: per-app navigation allowlists, per-app cookie profiles, SSO popups restricted to listed identity domains, everything else opens in your default browser.
- Release builds disable the WebView2 DevTools UI and browser password autosave/autofill; OmniDeck never sees or stores web credentials.
- The only secret the app stores (optional Twelve Data API key) is encrypted with Windows DPAPI, current-user scope.
- All service calls (Open-Meteo, Twelve Data, GitHub) are HTTPS-only.
- All service calls (Open-Meteo, Stooq, Twelve Data, GitHub) are HTTPS-only.
- Bug reports scrub query strings, cookie values, and token-shaped strings before packaging; nothing is ever uploaded automatically — you attach the zip yourself.
- No telemetry, no analytics, no crash auto-upload (see [PRIVACY](docs/legal/PRIVACY.md)).
+15 -201
View File
@@ -1,205 +1,14 @@
{
"$schema": "./webapps.schema.json",
"schemaVersion": 2,
"updated": "2026-11-03",
"navAllowSets": {
"google-account-domains": [
"accounts.google.ad",
"accounts.google.ae",
"accounts.google.al",
"accounts.google.am",
"accounts.google.as",
"accounts.google.at",
"accounts.google.az",
"accounts.google.ba",
"accounts.google.be",
"accounts.google.bf",
"accounts.google.bg",
"accounts.google.bi",
"accounts.google.bj",
"accounts.google.bs",
"accounts.google.bt",
"accounts.google.by",
"accounts.google.ca",
"accounts.google.cat",
"accounts.google.cd",
"accounts.google.cf",
"accounts.google.cg",
"accounts.google.ch",
"accounts.google.ci",
"accounts.google.cl",
"accounts.google.cm",
"accounts.google.cn",
"accounts.google.co.ao",
"accounts.google.co.bw",
"accounts.google.co.ck",
"accounts.google.co.cr",
"accounts.google.co.id",
"accounts.google.co.il",
"accounts.google.co.in",
"accounts.google.co.jp",
"accounts.google.co.ke",
"accounts.google.co.kr",
"accounts.google.co.ls",
"accounts.google.co.ma",
"accounts.google.co.mz",
"accounts.google.co.nz",
"accounts.google.co.th",
"accounts.google.co.tz",
"accounts.google.co.ug",
"accounts.google.co.uk",
"accounts.google.co.uz",
"accounts.google.co.ve",
"accounts.google.co.vi",
"accounts.google.co.za",
"accounts.google.co.zm",
"accounts.google.co.zw",
"accounts.google.com.af",
"accounts.google.com.ag",
"accounts.google.com.ar",
"accounts.google.com.au",
"accounts.google.com.bd",
"accounts.google.com.bh",
"accounts.google.com.bn",
"accounts.google.com.bo",
"accounts.google.com.br",
"accounts.google.com.bz",
"accounts.google.com.co",
"accounts.google.com.cu",
"accounts.google.com.cy",
"accounts.google.com.do",
"accounts.google.com.ec",
"accounts.google.com.eg",
"accounts.google.com.et",
"accounts.google.com.fj",
"accounts.google.com.gh",
"accounts.google.com.gi",
"accounts.google.com.gt",
"accounts.google.com.hk",
"accounts.google.com.jm",
"accounts.google.com.kh",
"accounts.google.com.kw",
"accounts.google.com.lb",
"accounts.google.com.ly",
"accounts.google.com.mm",
"accounts.google.com.mt",
"accounts.google.com.mx",
"accounts.google.com.my",
"accounts.google.com.na",
"accounts.google.com.ng",
"accounts.google.com.ni",
"accounts.google.com.np",
"accounts.google.com.om",
"accounts.google.com.pa",
"accounts.google.com.pe",
"accounts.google.com.pg",
"accounts.google.com.ph",
"accounts.google.com.pk",
"accounts.google.com.pr",
"accounts.google.com.py",
"accounts.google.com.qa",
"accounts.google.com.sa",
"accounts.google.com.sb",
"accounts.google.com.sg",
"accounts.google.com.sl",
"accounts.google.com.sv",
"accounts.google.com.tj",
"accounts.google.com.tr",
"accounts.google.com.tw",
"accounts.google.com.ua",
"accounts.google.com.uy",
"accounts.google.com.vc",
"accounts.google.com.vn",
"accounts.google.cv",
"accounts.google.cz",
"accounts.google.de",
"accounts.google.dj",
"accounts.google.dk",
"accounts.google.dm",
"accounts.google.dz",
"accounts.google.ee",
"accounts.google.es",
"accounts.google.fi",
"accounts.google.fm",
"accounts.google.fr",
"accounts.google.ga",
"accounts.google.ge",
"accounts.google.gg",
"accounts.google.gl",
"accounts.google.gm",
"accounts.google.gr",
"accounts.google.gy",
"accounts.google.hn",
"accounts.google.hr",
"accounts.google.ht",
"accounts.google.hu",
"accounts.google.ie",
"accounts.google.im",
"accounts.google.iq",
"accounts.google.is",
"accounts.google.it",
"accounts.google.je",
"accounts.google.jo",
"accounts.google.kg",
"accounts.google.ki",
"accounts.google.kz",
"accounts.google.la",
"accounts.google.li",
"accounts.google.lk",
"accounts.google.lt",
"accounts.google.lu",
"accounts.google.lv",
"accounts.google.md",
"accounts.google.me",
"accounts.google.mg",
"accounts.google.mk",
"accounts.google.ml",
"accounts.google.mn",
"accounts.google.mu",
"accounts.google.mv",
"accounts.google.mw",
"accounts.google.ne",
"accounts.google.nl",
"accounts.google.no",
"accounts.google.nr",
"accounts.google.nu",
"accounts.google.pl",
"accounts.google.pn",
"accounts.google.ps",
"accounts.google.pt",
"accounts.google.ro",
"accounts.google.rs",
"accounts.google.ru",
"accounts.google.rw",
"accounts.google.sc",
"accounts.google.se",
"accounts.google.sh",
"accounts.google.si",
"accounts.google.sk",
"accounts.google.sm",
"accounts.google.sn",
"accounts.google.so",
"accounts.google.sr",
"accounts.google.st",
"accounts.google.td",
"accounts.google.tg",
"accounts.google.tl",
"accounts.google.tm",
"accounts.google.tn",
"accounts.google.to",
"accounts.google.tt",
"accounts.google.vu",
"accounts.google.ws"
]
},
"schemaVersion": 1,
"updated": "2026-07-17",
"apps": [
{
"id": "spotify",
"name": "Spotify",
"startUrl": "https://open.spotify.com/",
"profile": "spotify",
"navAllow": ["spotify.com", "spotifycdn.com", "scdn.co", "accounts.google.com", "www.facebook.com", "appleid.apple.com"],
"navAllowSets": ["google-account-domains"],
"navAllow": ["spotify.com", "spotifycdn.com", "scdn.co"],
"popupAllow": ["accounts.spotify.com"],
"notifications": false,
"audioPin": true
@@ -212,7 +21,7 @@
"navAllow": ["discord.com", "discordapp.com", "discord.gg", "discordapp.net"],
"popupAllow": ["discord.com"],
"notifications": true,
"audioPin": true
"audioPin": false
},
{
"id": "youtube",
@@ -220,7 +29,6 @@
"startUrl": "https://www.youtube.com/",
"profile": "google",
"navAllow": ["youtube.com", "google.com", "googlevideo.com", "ytimg.com", "ggpht.com", "gstatic.com"],
"navAllowSets": ["google-account-domains"],
"popupAllow": ["accounts.google.com"],
"notifications": true,
"audioPin": true
@@ -231,7 +39,6 @@
"startUrl": "https://mail.google.com/",
"profile": "google",
"navAllow": ["google.com", "googleusercontent.com", "gstatic.com"],
"navAllowSets": ["google-account-domains"],
"popupAllow": ["accounts.google.com"],
"notifications": true,
"audioPin": false
@@ -242,7 +49,6 @@
"startUrl": "https://calendar.google.com/",
"profile": "google",
"navAllow": ["google.com", "googleusercontent.com", "gstatic.com"],
"navAllowSets": ["google-account-domains"],
"popupAllow": ["accounts.google.com"],
"notifications": true,
"audioPin": false
@@ -253,7 +59,6 @@
"startUrl": "https://drive.google.com/",
"profile": "google",
"navAllow": ["google.com", "googleusercontent.com", "gstatic.com"],
"navAllowSets": ["google-account-domains"],
"popupAllow": ["accounts.google.com"],
"notifications": true,
"audioPin": false
@@ -264,7 +69,6 @@
"startUrl": "https://www.google.com/maps",
"profile": "google",
"navAllow": ["google.com", "googleusercontent.com", "gstatic.com", "googleapis.com"],
"navAllowSets": ["google-account-domains"],
"popupAllow": ["accounts.google.com"],
"notifications": false,
"audioPin": false
@@ -277,7 +81,17 @@
"navAllow": ["facebook.com", "fbcdn.net", "fbsbx.com"],
"popupAllow": ["facebook.com"],
"notifications": true,
"audioPin": true
"audioPin": false
},
{
"id": "messenger",
"name": "Messenger",
"startUrl": "https://www.messenger.com/",
"profile": "meta",
"navAllow": ["messenger.com", "facebook.com", "fbcdn.net", "fbsbx.com"],
"popupAllow": ["facebook.com", "messenger.com"],
"notifications": true,
"audioPin": false
}
]
}
+1 -19
View File
@@ -11,24 +11,13 @@
"description": "Editor hint pointing at this schema; ignored by the app."
},
"schemaVersion": {
"const": 2
"const": 1
},
"updated": {
"type": "string",
"description": "Date of the last content change (yyyy-MM-dd).",
"pattern": "^\\d{4}-\\d{2}-\\d{2}$"
},
"navAllowSets": {
"type": "object",
"description": "Named lists of domains that entries add to their navAllow by name, for lists too long to repeat in each entry.",
"propertyNames": { "$ref": "#/$defs/slug" },
"additionalProperties": {
"type": "array",
"minItems": 1,
"uniqueItems": true,
"items": { "$ref": "#/$defs/domain" }
}
},
"apps": {
"type": "array",
"minItems": 1,
@@ -78,13 +67,6 @@
"uniqueItems": true,
"items": { "$ref": "#/$defs/domain" }
},
"navAllowSets": {
"type": "array",
"description": "Names of top-level navAllowSets whose domains the main frame may also navigate to.",
"minItems": 1,
"uniqueItems": true,
"items": { "$ref": "#/$defs/slug" }
},
"popupAllow": {
"type": "array",
"description": "Domains whose popups open in-app on the same profile (SSO flows).",
+21 -90
View File
@@ -10,19 +10,18 @@ Directory.Build.props shared build settings: nullable, warnings as errors, anal
NuGet Audit, product metadata and dev-build version
global.json pinned .NET SDK
.config/ dotnet-tools.json: vpk, dotnet-sonarscanner, XamlStyler
scripts/ pack.ps1 (publish + Velopack), validate-catalog.ps1, make-icon.ps1
scripts/ pack.ps1 (publish + Velopack), validate-catalog.ps1
src/
OmniDeck.App/ WPF shell: windows, navigation, tray and notifications, command
palette, theme engine, legal gate, onboarding, settings UI,
task-manager panel, update service (Velopack)
OmniDeck.Core/ contracts (IOdModule, IOdNotifier, IOdQuoteProvider, ...), module
host, RAM governor, storage (SQLite/Dapper, settings), theme
tokens, legal acknowledgment, bug-report composer, i18n helpers
OmniDeck.App/ WPF shell: windows, navigation, tray, command palette,
theme engine, legal gate, settings UI, task-manager panel
OmniDeck.Core/ contracts (IOdModule, IOdQuoteProvider, ...), RAM governor,
storage (SQLite/Dapper, settings), toast service,
bug-report composer, update service (Velopack), i18n helpers
OmniDeck.Modules/ built-in mini-apps: Clock, Timer, Calculator, Weather,
Calendar, Stocks, Media — one folder per module (P1)
OmniDeck.Web/ web runner: environment/profile management, catalog loader,
navigation policy, notifications bridge, permissions,
sign-in health, CDP console capture (P2)
downloads, CDP console capture (P2)
tests/
OmniDeck.Tests/ xUnit v3; governor state machine, providers, catalog validation,
scrubber, rate limiter
@@ -31,14 +30,12 @@ catalog/
webapps.schema.json its JSON Schema (CI validation, editor completion)
```
State at kickoff: `OmniDeck.App` (Velopack bootstrap + a placeholder `FluentWindow`), `OmniDeck.Core` (`OdVersionInfo`) and `OmniDeck.Tests` exist. `OmniDeck.Modules` and `OmniDeck.Web` are created when their first real code lands (P1/P2), so the build never carries empty projects. `OmniDeck.Modules` arrived in P1 with Clock, Timer and Calculator: it references Core (and WPF-UI for its views) but never the app, registers its modules with `AddOmniDeckModules()`, and keeps its own string table. `OmniDeck.Web` arrived in P2 the same way: it references Core, the WebView2 SDK and WPF-UI but never the app or `OmniDeck.Modules`, and `AddOmniDeckWeb(catalog, options)` registers the catalog service, the runtime and one module per catalog entry, after the built-in modules. Durable module state lives outside the views, in a service (`OdTimerService`), a view model the module keeps (the calculator's history), or the module's settings document (the clock's zones), so hibernating a view loses nothing.
State at kickoff: `OmniDeck.App` (Velopack bootstrap + a placeholder `FluentWindow`), `OmniDeck.Core` (`OdVersionInfo`) and `OmniDeck.Tests` exist. `OmniDeck.Modules` and `OmniDeck.Web` are created when their first real code lands (P1/P2), so the build never carries empty projects.
Naming: namespace `OmniDeck.*`, public type prefix `Od*` (`OdModuleHost`, `OdRamGovernor`, `OdWebRunner`, `OdCatalogEntry`), interfaces `IOd*`. The WPF application class is `OdApp` (`OdApp.xaml`), started from `Program.Main` after Velopack's hooks; the executable is `OmniDeck.exe`.
Patterns: MVVM via CommunityToolkit.Mvvm; constructor DI via `Microsoft.Extensions.DependencyInjection`; no service locator.
Startup, as built in P1: `Program.Main` runs Velopack's hooks first (the uninstall hook deletes the data root), then the single-instance guard: a session-local mutex, and a second launch signals the first to show its window and exits. `OdApp` builds the container (`ServiceCollection` with `ValidateOnBuild`), installs the crash handler and starts the theme engine. It then shows the legal gate when the acknowledged legal version is not the current one, and onboarding on first run. Next it creates the main window, which owns the tray icon and therefore exists even when Windows starts OmniDeck in the tray (`--minimized`). Last come the governor and the daily update check. Shutdown is explicit: closing the window hides it in the tray unless the user turned that off, and otherwise only Quit ends the process. Notifications are tray balloons behind `IOdNotifier`, which Windows 11 shows as toasts, so the app needs no Windows-specific target framework or WinRT projection. The tray icon's image, a bold "O" on the accent color, is drawn in code (`OdTrayIcon`) and loaded from ICO bytes so that it owns its handle. H.NotifyIcon's `GeneratedIconSource` is avoided: in 2.4.1 it leaks an icon handle on every redraw and adds a redraw handler on every brush change, which used up the process's GDI objects after a few accent changes (fixed in 0.1.1). The Velopack update service lives in the app, because Core must not reference Velopack.
## 2. Module contract
```csharp
@@ -47,7 +44,7 @@ public enum OdModuleState { Created, Active, Idle, Suspended, Hibernated, Closed
public interface IOdModule
{
OdModuleInfo Info { get; } // Id, NameKey, Icon, CategoryKey, RamClass
OdModuleInfo Info { get; } // Id, Name, Icon, Category, RamClass
FrameworkElement CreateView(); // called on Activate after hibernation
Task InitializeAsync(IOdModuleContext ctx); // once per process lifetime
Task ActivateAsync(); // became visible
@@ -58,68 +55,24 @@ public interface IOdModule
}
```
`IOdModuleContext` gives modules their own settings document (one JSON row per module in the `module_settings` table), the notifier (tray balloons, which Windows 11 shows as toasts; clicking one opens the module that raised it), a logger, the clock, the shared HTTP client and the database for the module's own tables. The HTTP client (`OdHttp`) is one `HttpClient` for OmniDeck's own features: it names OmniDeck in its User-Agent, keeps no cookies and gives up after 15 seconds. Module tables are migrated with Core's migrations, so one schema version covers the database. Modules never construct these themselves. Quitting closes every open module first (`OdModuleHost.CloseAllAsync`), so each one can save its state and let go of what it holds.
`IOdModuleContext` gives modules storage (scoped SQLite access + settings section), the toast service, logger, and the HTTP client factory — modules never construct these themselves.
`CreateView()` returns a WPF `FrameworkElement`, so wherever `IOdModule` lives must reference WPF. P1 decided to let `OmniDeck.Core` take that dependency (`UseWPF`) rather than add an abstractions project. Core holds the contract, `OdModuleHost` and the localization layer (`OdLocalization`, `{res:OdLoc Key}`), so modules depend on Core alone; Core still never references the app, Velopack or WPF-UI (an architecture test checks it), which is why `OdModuleInfo.Icon` is a `SymbolRegular` name rather than a symbol.
`OdModuleHost` runs the contract. It initializes a module on first open, builds its view when it has none (first open, or after hibernation), keeps the view of the visible module, and moves hidden ones down the ladder when the shell or the governor asks; it refuses to suspend or hibernate a module whose `CanSuspendAsync` returns false. Calls run one at a time on the UI thread. The shell's navigation view is chrome only: every module item navigates to one shared stage page, whose content is the view the host hands back, so the control never creates or caches module views.
A view asks for full screen with `OdFullscreen.Request(view, on)`, a bubbling routed event raised from the view itself, since content it hosts in a window of its own (a video overlay) is outside the main window's tree. The main window then:
- covers the monitor it is on (`OdMonitors.BoundsOf`, `OdWindowCover`), and keeps where it was;
- hides the title bar;
- folds the navigation pane to zero width. Changing its display mode would re-template the navigation view and re-create the stage, and with it any native child window;
- sets `OdFullscreen.IsActive` on the stage, which views inherit.
Esc, hiding to the tray, or showing another module ends it. A module that plays media implements `IOdMediaControls`, which the tray menu uses while something is loaded.
A module can also show in a window of its own (`OdPopOutWindow`), opened from its sidebar menu or its library tile:
- The host keeps the module active there (`OdModuleHost.PopOutAsync`), so the governor leaves it alone. If the main window showed it, the main window shows the library instead. Asking for the module again brings its window to the front.
- The view itself moves, so a web app's browser and a video keep running: WPF re-parents their native windows rather than creating new ones. Spike #6's hand-over to a second video view, with its track re-selection and seek, is not needed.
- Closing the window docks the module back into the main window, hidden (`DockAsync`), and the time ladder applies again. "Return to main window" in the sidebar menu also shows it there.
- Before closing, the window lets go of the view and hands the windows it still owns to the main window. LibVLCSharp's video overlay is owned by the window its video is in and would otherwise close for good with it.
- A pop-out goes full screen as the main window does, and opens where it was last time in the session.
`CreateView()` returns a WPF `FrameworkElement`, so wherever `IOdModule` lives must reference WPF. P1 decides between letting `OmniDeck.Core` take that dependency (it already targets `net10.0-windows`) and moving the contract into a small WPF-aware abstractions project.
Native modules run in-process. True RAM release for them means honoring `SuspendAsync`/`HibernateAsync`: dispose charts, bitmaps, timers, caches; the governor follows up with a GC. Web modules get real process-level release for free because WebView2 is out-of-process by design.
## 3. Web runner internals
As built in P2 (`OmniDeck.Web`):
- **Environment** (`OdWebRuntime`): one `CoreWebView2Environment` for the whole app, so the browser and GPU processes are shared across web apps. It is created when the first web app opens, with its user data folder in the data root's `WebView2\` folder. The runtime counts open browsers: after the last one closes, the shared browser process exits and writes its cookies out, and a web app opened meanwhile waits for that exit (up to 3 s), because a controller created during it stalls for seconds (docs/spikes/03-memory.md). Quitting closes every module, then waits the same way before the process ends. Without an installed WebView2 Runtime, a web app shows a notice whose button opens Microsoft's download page.
- **Profiles:** one WebView2 profile per catalog `profile` value (`CoreWebView2ControllerOptions.ProfileName`). `google` is shared (one sign-in for Gmail/Calendar/Drive/Maps/YouTube); every other app is isolated. Cookies live in the profile, which is what lets **hibernate = full dispose** without losing sessions.
- **Modules:** each catalog entry is an `OdWebAppModule` (Heavy, titled with the brand name, which is never translated). Its view (`OdWebAppView`) hosts the WPF `WebView2` control; notices sit above the browser rather than over it, because no WPF element can cover the browser's native window.
- **Per-app pipeline on creation:** apply settings (`AreDevToolsEnabled=false` in Release, `IsPasswordAutosaveEnabled=false`, `IsGeneralAutofillEnabled=false`) → attach `NavigationStarting` → `NewWindowRequested` → `ProcessFailed` → `ContainsFullScreenElementChanged` → `NotificationReceived` → `PermissionRequested` → start the CDP console capture → navigate.
- **Navigation policy** (`OdNavPolicy`, a pure function of the entry and the catalog): a main-frame navigation stays in the app when it is HTTPS to a host that `navAllow` or one of the entry's `navAllowSets` covers (whole-label suffix match, case-insensitive), or an `about:`, `data:` or `blob:` page. Other web and `mailto:` links open in the default browser; every other scheme is blocked and only the scheme is logged. Frames inside a page are not filtered. A popup (`NewWindowRequested`) to a `popupAllow` host opens in an in-app window (`OdWebPopupWindow`) on the same profile, so a sign-in popup lands in the app's cookies; any other popup goes to the default browser.
- **Link loop guard** (`OdExternalLinks`): the same link (scheme, host and path) opens in the browser at most 3 times in 30 s; after that it is held back and the app shows a notice, once per 30 s. In P0, Google retried a blocked sign-in hop 15 times in 40 seconds (docs/spikes/02-google-sign-in.md).
- **Suspend path:** set `MemoryUsageTargetLevel = Low` → `TrySuspendAsync()` (WebView2 refuses while the control is visible; that is logged at Debug). **Resume:** set target `Normal`, and `Resume()` if still suspended.
- **Hibernate path:** the module keeps the page on screen in memory, then disposes the control, which releases the app's processes. Reopening creates a new control on the same profile and navigates to that page. Closing the module forgets the page, and so does a restart: the next session opens `startUrl`.
- **Crash recovery:** `ProcessFailed` for the page or the browser reloads the app once, on the page it showed; a second failure within a minute shows a notice with a Reload button instead. Frame, GPU and helper process failures recover on their own and are only logged.
- **Full screen:** when the page shows something full screen (a video, say), the view asks for the window's full screen (§2). When the window leaves it first (Esc, another module), the page is told to leave too (`document.exitFullscreen()`).
- **Console capture:** CDP `Runtime.consoleAPICalled`, `Runtime.exceptionThrown` and `Log.entryAdded` feed two rings kept by the module (`OdConsoleLog`: the last 200 entries and the last 50 errors), so they survive hibernation. They are formatted like DevTools (`%s`, `%d`, `%c`), held only for the session, and are there for the bug report.
- **Notifications:** `NotificationReceived` is always marked handled, so WebView2 never shows its own notification window.
- When the app's notifications are on, the notification becomes a tray notification: "‹App›: ‹title›" with the body below, cut to what a balloon holds. That switch is in Settings → Web apps and defaults to the catalog's `notifications`.
- Then `ReportShown` runs. Clicking the notification opens the app and calls `ReportClicked`, so the page can open the conversation.
- The Notifications permission follows the same switch, without asking.
- An app with notifications on is resident: the governor never suspends it for being hidden (RAM-GOVERNOR.md §3).
- Only non-persistent notifications (`new Notification(...)` from a page) reach WebView2's event. Service-worker push does not.
- **Permissions** (`OdWebPermissions`, `OdWebPreferences`):
- Kinds that reach the user's devices or data are asked about once per app: camera, microphone, location, clipboard reading, motion sensors, several downloads at once, file access, local fonts, MIDI system-exclusive messages and window placement.
- The question shows in a bar above the browser, because a content dialog cannot cover the browser's native window. The page waits on a deferral until the user answers.
- The answer is kept in `settings.json` (`web.apps.<id>.permissions`). `SavesInProfile` is false, so the profile keeps no answers of its own.
- Autoplay and persistent storage are left to the browser. Any other kind is refused.
- Settings → Web apps lists each app's answers; "Ask again" forgets them.
- **Downloads:** WebView2's own download flyout. It saves to the user's Downloads folder and handles SmartScreen verdicts and dangerous-file prompts, which a download row of OmniDeck's own would have to repeat.
- **Clearing data:** Settings → Web apps → Clear data, per profile group:
- It closes the group's apps, then clears the profile's browsing data (`ClearBrowsingDataAsync`) through a hidden browser on that profile, hosted by the main window.
- It also tells sign-in health that an empty profile is expected.
- **Sign-in health** (`OdSignInHealth`): when an app closes or hibernates, and at the first load of each profile in a session, it counts the cookies the profile holds for the app's start page (the number only, never a name or value), keeps the count in `app_meta` (`web.cookies.<profile>`) and logs it. A profile that had cookies at the last close and comes back with none is logged as a warning. Starting OmniDeck with `--wv2-logging` also turns on Chromium's own logging (`--enable-logging --v=0`) in the WebView2 folder, for chasing a lost sign-in while dogfooding.
- **Catalog refresh** (`OdCatalogService`, as built in P2): each build carries the catalog as of its commit (`catalog\webapps.json` next to the executable), and the session uses the newer of that copy and the last one fetched (`%LocalAppData%\OmniDeck.Data\catalog\webapps.json`), by `updated`. A minute after startup, and then at most once a day, it fetches `main`'s copy from the repository's raw URL over HTTPS with `If-None-Match`. It parses strictly (unknown or missing properties are errors) and applies the same rules as `validate-catalog.ps1` (`OdCatalogValidator`, tested against the repository's file). A valid catalog replaces the last fetched one atomically and takes effect at the next start, so the modules on screen never change mid-session; anything else is logged and dropped. Requests are never retried before the next daily check.
- **Environment:** one `CoreWebView2Environment` for the whole app → browser/GPU processes are shared across web apps. Created lazily on first web app open.
- **Profiles:** `CoreWebView2Profile` per catalog `profile` value. `google` is shared (one sign-in for Gmail/Calendar/Drive/Maps/YouTube); every other app is isolated. Cookies live in the profile, which is what lets **hibernate = full dispose** without losing sessions.
- **Per-app pipeline on creation:** apply settings (`AreDevToolsEnabled=false` in Release, `IsPasswordAutosaveEnabled=false`, `IsGeneralAutofillEnabled=false`) → attach `NavigationStarting` (navAllow suffix check) → `NewWindowRequested` (popupAllow → in-app popup on same profile; else default browser) → `PermissionRequested` → `NotificationReceived` → `DownloadStarting` → start CDP console capture (`Runtime.enable`, `Log.enable`).
- **Suspend path:** hide the control → `TrySuspendAsync()` → set `MemoryUsageTargetLevel = Low`. **Resume:** set target `Normal`, show; WebView2 resumes automatically on visibility.
- **Hibernate path:** persist `{ url }`, `Dispose()` the control and `CoreWebView2`. Reopen = new control on the same profile navigating to the saved URL.
- **Catalog refresh:** at most daily, fetch `catalog/webapps.json` from this repo's raw URL over HTTPS; validate against schema version; on any validation failure keep the bundled copy.
## 4. RAM governor (summary — full spec in RAM-GOVERNOR.md)
A single scheduler owns all state transitions. Inputs: per-module visibility + last-interaction time, pin status (`CanSuspendAsync` / `IsDocumentPlayingAudio`), and total footprint = private commit (`Process.PrivateMemorySize64`) of the shell plus the WebView2 processes, which the web runner reports per app (`IOdMemoryReporter`, renderers matched to apps through `GetProcessExtendedInfosAsync`) with the browser, GPU and utility processes as one shared figure. Policies: idle timers demote Active→Idle→Suspended→Hibernated; soft cap demotes LRU modules early; hard cap force-hibernates and toasts. The task-manager panel is a read/write view over the same scheduler (manual suspend/kill). In code: `OdRamGovernor` in `OmniDeck.Core/Governor`, polling every 10 s on the UI thread through `OdModuleHost`, behind `IOdMemory` so tests drive it with a fake gauge and `FakeTimeProvider`.
A single scheduler owns all state transitions. Inputs: per-module visibility + last-interaction time, pin status (`CanSuspendAsync` / `IsDocumentPlayingAudio`), and total footprint = shell `Process.WorkingSet64` + `CoreWebView2Environment.GetProcessInfos()` working sets. Policies: idle timers demote Active→Idle→Suspended→Hibernated; soft cap demotes LRU modules early; hard cap force-hibernates and toasts. The task-manager panel is a read/write view over the same scheduler (manual suspend/kill).
## 5. Storage
@@ -135,32 +88,10 @@ Why not `%LocalAppData%\OmniDeck`: that is Velopack's install folder (packId `Om
## 6. Logging & failure handling
Serilog rolling files, kept for 7 days by age (a burst of errors rolls a new file every 10 MB, so a file count alone could push out the week before it). Global handlers (`DispatcherUnhandledException`, `AppDomain.UnhandledException`, `TaskScheduler.UnobservedTaskException`) log, show a friendly dialog, and offer the bug-report flow. A failure that repeats is reported once a minute, with the number of repeats in between, so one fault in a loop can neither stack dialogs nor flood the logs. When a web app's page or browser process fails, the app reloads once by itself; a second failure within a minute shows a notice with a Reload button (§3).
**Bug reports**, as built in P2. Two buttons open the same dialog: About → Report a bug, and Report bug on the error dialog, which also passes in the error it showed.
- **What the report holds:**
- OmniDeck's version and commit, Windows' version and build, and the UI preset;
- each module's state, how long it has been hidden, and the memory it uses;
- the last 500 lines of the logs;
- the sign-in cookie count of each profile;
- for a web app, its console capture.
- **Scrubbing** (`OdScrubber` in `OmniDeck.Core/Reports`, a pure function) runs over every file before it is written. It replaces the user's profile folder with `%USERPROFILE%`, cuts URLs back to scheme, host and path, and removes:
- cookie values;
- bearer tokens, JWTs, and long hex or base64 runs;
- email addresses;
- numeric ids of 15 digits or more.
- **Preview:** the dialog shows the issue text the report will carry. Picking another subject composes the report again.
- **On Save:**
- `OdBugReports` writes `reports\bugreport-‹stamp›.zip` (issue.md, system.json, logs.txt and console-‹app›.txt for a web app) and keeps the ten newest.
- File Explorer opens with the zip selected.
- The browser opens the bug form with only the short fields (version, Windows, preset, module) in its query.
- Nothing is uploaded (PRIVACY §3).
A content dialog cannot cover a web app's browser, which is a native window. So while any dialog is open, the main window hides the module stage, and with it the browser.
Serilog rolling files (7-day retention). Global handlers (`DispatcherUnhandledException`, `AppDomain.UnhandledException`, `TaskScheduler.UnobservedTaskException`) log, show a friendly dialog, and offer the bug-report flow. `CoreWebView2.ProcessFailed` triggers an automatic single reload of that app before surfacing an error tab.
## 7. Updates & packaging
Velopack, per-user, GitHub Releases channel, delta updates. The package carries libVLC for the media player in `libvlc\win-x64` next to OmniDeck.exe (x64 only, with the plugin set in SPEC §3.6), and LibVLCSharp loads it on the first play. Update check on About open and once per day in the background (notify-only, never auto-restart). Builds below 1.0 are GitHub pre-releases, so their update check includes pre-releases. In code: `OdVelopackUpdateService` behind `IOdUpdateService`; Settings → About checks when opened and offers *Download and restart*, and `OdUpdateWatcher` checks a few minutes after start, then daily, and notifies once per new version. A development build is not installed, so it does neither.
Velopack, per-user, GitHub Releases channel, delta updates; update check on About open and once per day in the background (notify-only, never auto-restart). Builds below 1.0 are GitHub pre-releases, so their update check includes pre-releases.
Releases are built by [`release.yml`](../.github/workflows/release.yml), self-contained in this repository: a GPG-signed `vX.Y.Z[-suffix]` tag on `main` runs `scripts/pack.ps1` (self-contained `win-x64` publish + `vpk pack`), build-provenance attestations, a draft GitHub Release with an SPDX SBOM and SHA-256 checksums, release notes from CHANGELOG, publication, and a Discord announcement — see [RELEASING](../RELEASING.md). The WebView2 Runtime ships with Windows 11; if it is ever missing, a web app says so and links to Microsoft's download page (§3). Velopack's `--framework webview2` bootstrapper was considered in P2 and left out for that reason. The executable, its windows and Setup carry `src/OmniDeck.App/Assets/OmniDeck.ico`, drawn by `scripts/make-icon.ps1` until a designed icon replaces it.
Releases are built by [`release.yml`](../.github/workflows/release.yml), self-contained in this repository: a GPG-signed `vX.Y.Z[-suffix]` tag on `main` runs `scripts/pack.ps1` (self-contained `win-x64` publish + `vpk pack`), build-provenance attestations, a draft GitHub Release with an SPDX SBOM and SHA-256 checksums, release notes from CHANGELOG, publication, and a Discord announcement — see [RELEASING](../RELEASING.md). The WebView2 Runtime ships with Windows 11; if it is ever missing, Velopack's `--framework webview2` bootstrapper can install it (evaluate in P2).
+13 -40
View File
@@ -4,17 +4,15 @@ The governor is the feature that makes "many apps in one" viable. It moves every
## 1. State ladder
| State | Entered when | Native module | Web app | Measured web-app cost (committed, P0 spike #3) |
| State | Entered when | Native module | Web app | Typical web-app RAM |
|---|---|---|---|---|
| Active | visible / interacted | full UI | full WebView2 | app 250–450 MB, plus 170–270 MB of shared browser, GPU and utility processes |
| Idle | hidden < `IdleAfter` | keep view, stop animations/timers | hidden, still live | 15–31 % less, as Chromium drops the hidden page's caches |
| Suspended | hidden ≥ `IdleAfter` | `SuspendAsync`: drop caches, charts, bitmaps; GC follows | `TrySuspendAsync` + `MemoryUsageTargetLevel.Low` | 85–95 % of Idle. The working set is trimmed by about 65 %, so this rung saves CPU and power, not memory |
| Hibernated | hidden ≥ `HibernateAfter`, or cap pressure | `HibernateAsync`: view + everything released, tiny state blob kept | `Dispose()`; only `{url}` kept, session lives in profile cookies | 0. Disposing the *last* web app also ends the shared processes |
| Active | visible / interacted | full UI | full WebView2 | 300–700 MB |
| Idle | hidden < `IdleAfter` | keep view, stop animations/timers | hidden, still live | unchanged |
| Suspended | hidden ≥ `IdleAfter` | `SuspendAsync`: drop caches, charts, bitmaps; GC follows | `TrySuspendAsync` + `MemoryUsageTargetLevel.Low` | tens of MB |
| Hibernated | hidden ≥ `HibernateAfter`, or cap pressure | `HibernateAsync`: view + everything released, tiny state blob kept | `Dispose()`; only `{url}` kept, session lives in profile cookies | ≈ 0 |
| Closed | user closes | released | released | 0 |
A module in a window of its own (a pop-out) is visible while that window is open, so it stays Active whatever the main window shows; closing the window puts it back on the ladder as a hidden module.
Reactivation from Suspended is instant. From Hibernated it is a cold open (view rebuild and page reload, about 0.6–2.5 s); that is acceptable because the profile keeps the user signed in. After the last web app has been hibernated, the next one also restarts the browser process (about 160 ms).
Reactivation from Suspended is instant; from Hibernated it is a cold open (view rebuild / page reload) — acceptable because the profile keeps the user signed in.
## 2. Defaults (all configurable in Settings → Memory)
@@ -22,8 +20,8 @@ Reactivation from Suspended is instant. From Hibernated it is a cold open (view
|---|---|
| `IdleAfter` | 5 min hidden |
| `HibernateAfter` | 30 min hidden |
| `SoftCapBytes` | min(4.5 GiB, 35 % of physical RAM) |
| `HardCapBytes` | min(6.0 GiB, 50 % of physical RAM) |
| `SoftCapBytes` | 4.5 GiB |
| `HardCapBytes` | 6.0 GiB |
| `PollInterval` | 10 s |
## 3. Pinning
@@ -34,32 +32,18 @@ A module is **pinned** (governor must not demote it below its current state) whe
- the web app's `IsDocumentPlayingAudio` is true **and** its catalog entry has `audioPin: true` (Spotify, YouTube);
- the user pinned it manually in the task-manager panel.
A module that works while hidden is **resident** (`IOdResidency`): in P2, a web app with notifications on, which would stop notifying once suspended. The time ladder skips it; the caps may still hibernate it, after every other victim, and then OmniDeck shows a notification naming the app, which reopens it when clicked.
Pinned modules are skipped by cap enforcement; if the hard cap is exceeded purely by pinned modules, the governor toasts a warning instead of killing audio.
## 4. Cap enforcement
Total footprint = shell process + Σ all WebView2 processes, sampled every `PollInterval`.
Total footprint = shell process + Σ all WebView2 processes (`CoreWebView2Environment.GetProcessInfos()` → PID), sampled every `PollInterval`.
**Metric: private commit** (`Process.PrivateMemorySize64`), summed over the shell and every WebView2 process. P0 spike #3 ([note](spikes/03-memory.md)) chose it for three reasons:
- Summing `Process.WorkingSet64` over-counts, because Chromium processes share DLL and shared-memory pages and each one reports them again.
- Working sets drop whenever pages are trimmed. Suspend + `Low` cut the private working set by 65–70 % but committed memory by only 5–15 %, so a working-set cap would reward exactly the page shuffling the honesty note below rejects.
- Private commit needs no process handle.
**Metric — chosen by P0 spike #3.** Summing `Process.WorkingSet64` over-counts: Chromium processes share DLL and shared-memory pages, and each process reports them again. Working set also drops whenever pages are trimmed (for example by `MemoryUsageTargetLevel.Low`), so a working-set cap would reward exactly the page shuffling the honesty note below rejects. The spike compares private commit (`Process.PrivateMemorySize64`) with private working set and fixes one metric; the caps, the toasts, and the task-manager panel all use it.
The caps, the toasts and the task-manager panel all use it. The panel may show the private working set beside it, since that is the figure Task Manager shows. Renderer processes are attributed to apps through `GetProcessExtendedInfosAsync`. The shared browser, GPU and utility processes form one "WebView2 (shared)" row and are never a demotion target.
- **> SoftCap:** demote the least-recently-used unpinned module one step down the ladder; repeat next tick if still above.
- **> HardCap:** force-hibernate LRU unpinned modules until below, then raise one toast summarizing what was hibernated.
- **> SoftCap:** hibernate the least-recently-used unpinned module, since Suspended frees almost no memory. Repeat on the next tick if still above.
- **> HardCap:** force-hibernate LRU unpinned modules until below, then raise one toast summarizing what was hibernated. If the shared WebView2 processes alone keep the total above the cap (the GPU process grows with video), the toast says so instead of hibernating apps that would free nothing.
Ordering hint: `RamClass.Heavy` modules (web apps, media, stocks charts) are preferred victims over `Light` ones at equal recency. Recency counts in poll intervals, so modules hidden within the same interval are equally recent.
As built in P2:
- **Measuring.** `IOdMemory` measures the shell; every `IOdMemoryReporter` adds the processes it follows. The web runner's `OdWebMemoryReporter` lists the WebView2 processes with `GetProcessExtendedInfosAsync` on each pass. A renderer counts for the app whose page it hosts: matched by main frame id (`CoreWebView2.FrameId`), or by host when only one open app shows that host. A renderer hosting pages of several apps is split evenly between them. The browser, GPU and utility processes, and pages no open app shows, count as shared. A reporter that fails is left out of that pass.
- **Victim order:** resident modules last, then least recently used, then `Heavy` first, then the module that uses more.
- **After a hibernation:** a web app's processes take a moment to exit. The pass therefore counts its figure as gone at once (and the shared processes too, when it was the last web app), and the next pass measures again. This keeps the hard-cap loop from hibernating more apps than needed.
- **Shared processes at the hard cap:** the governor checks whether the shell, the shared processes and the web apps that are not victims (on screen, kept running, or refusing) are above the hard cap on their own. If they are, it hibernates nothing and its one notification for that excursion says why.
Ordering hint: `RamClass.Heavy` modules (web apps, media, stocks charts) are preferred victims over `Light` ones at equal recency.
Honesty note: for in-process native modules the real win comes from modules *actually releasing* resources in `SuspendAsync`/`HibernateAsync`. The governor performs a `GC.Collect` + LOH compaction after demotions, and deliberately does **not** call `EmptyWorkingSet` tricks — those only shuffle pages to standby and fake the numbers.
@@ -67,17 +51,6 @@ Honesty note: for in-process native modules the real win comes from modules *act
Settings → Memory → "Running modules": live table of every module with state, memory estimate (the governor metric), last-used time, pin toggle, and Suspend / Hibernate / Close buttons. This is both a user feature and the primary debugging tool for the governor itself; the panel reads and writes the same scheduler, no side channel.
As built in P1, the panel sits in Settings → Memory under the threshold fields, and the command palette's "Running modules" opens it. Native modules share the shell process, so the panel shows OmniDeck's total against both caps rather than a per-module figure. Since P2, each open web app's row shows its own figure, and a "Shared web processes" row after the modules shows the shared ones. That row has no buttons, because the governor never demotes it. The pin toggle is labelled "Keep running", so it is not confused with pinning a module to the sidebar, and it is stored in `settings.json` (`memory.keepRunning`) next to the thresholds.
## 6. Testing
The scheduler is pure logic over an injected clock and an injected memory sampler — unit-test every transition, cap scenario, and pinning rule in `OmniDeck.Tests` without touching real WebView2.
**Resource soak, P2** (2 November 2026, Release build, one 2560×1440 monitor at 100 %):
- Idle on the library page, the shell held 103 MB of private commit, 32 GDI and 36 USER objects and 735 handles.
- 21 pop-out round trips (Clock into a window of its own and back) left the GDI and USER objects and handles flat after the first one: 39, 45 and 762.
- 21 page full-screen round trips on Discord's sign-in page also left them flat: 40, 49 and 798.
- With that page open, the seven WebView2 processes held 508 MB. The first full screen raised them to about 725 MB, mostly the GPU process's surfaces for the larger window, and they stayed there.
A signed-in day of use is the P2 exit's dogfooding ([ROADMAP](ROADMAP.md) §1).
+11 -37
View File
@@ -3,8 +3,6 @@
Solo-developer plan, ~29 weeks from the start of P0 (2 November 2026). Each phase has exit criteria; slipping triggers the cut order in §4, never a death march.
> **Re-baselined 2026-10-28.** The first draft assumed a 20 July 2026 start and a January 2027 release. Development actually starts on 2 November 2026, so every phase keeps its original length and moves; P2 gains one buffer week for Tết (Lunar New Year, 6 February 2027). Windows 10 support was dropped at the same time ([SPEC](SPEC.md) §1).
>
> **Re-baselined 2026-11-02.** P0 and P1 both finished early, on 30 October 2026, so P2 started on 2 November 2026 instead of 11 January 2027. P3 and P4 keep their dates until P2 exits, and are re-baselined then.
## 1. Phases
@@ -12,7 +10,7 @@ Solo-developer plan, ~29 weeks from the start of P0 (2 November 2026). Each phas
Repository foundation: documentation suite; solution skeleton (`OmniDeck.App`, `OmniDeck.Core`, `OmniDeck.Tests`); self-contained CI (build, tests, formatting, analyzers as errors, NuGet Audit, catalog validation, workflow and link linting, CodeQL, SonarCloud, Dependency Review, OpenSSF Scorecard); protected `main` and release tags; the Velopack release pipeline proven end to end with the `0.0.1-alpha.1` pre-release.
### P0 — Spikes (2 – 15 Nov 2026) — done early, 30 Oct 2026
### P0 — Spikes (2 – 15 Nov 2026)
De-risk everything that could invalidate the design, on real hardware:
@@ -24,45 +22,23 @@ De-risk everything that could invalidate the design, on real hardware:
6. **LibVLCSharp WPF:** airspace behavior — overlay controls + fullscreen toggle over `VideoView`. If blocked, evaluate FlyleafLib as the fallback engine.
7. **Providers:** hit Stooq CSV and Twelve Data free endpoints; freeze response models.
**Exit:** a written go/no-go note per spike in [`docs/spikes/`](spikes/README.md). The proof-of-concept code stays on the unmerged `spike/p0` branch, so spike-only packages never reach `main`'s dependency graph or the release SBOM.
**Exit:** written go/no-go note per spike committed to `docs/spikes/`.
**Result:** all seven notes are in. #1, #3 and #4 are GO; #2, #5, #6 and #7 are GO with conditions:
- #1 DRM: Widevine ships with the runtime.
- #2 sign-in: works and persists; Google's country-code hop needs `navAllowSets` in P2.
- #3 memory: the governor metric is private commit; suspend trims, only hibernate frees.
- #4 CDP capture: always on.
- #5 presets: code-built, with `Od` styles over WPF-UI's static keys.
- #6 libVLC: fullscreen in place; pop-out needs a vout restart and a seek.
- #7 providers: Twelve Data with the user's own key; Stooq dropped.
### P1 — Shell & skeleton (16 Nov 2026 – 10 Jan 2027) — done early, 30 Oct 2026
### P1 — Shell & skeleton (16 Nov 2026 – 10 Jan 2027)
Shell (nav, tray, single-instance, command palette), module contract + host, RAM governor v1 with task-manager panel, theme engine + three presets (Standard polished, others functional), legal gate + About, settings + storage layer (data root, Velopack uninstall hook), and the three trivial modules: clock, timer, calculator.
**Exit (0.1.0):** installable Velopack build; governor demotes/restores the trivial modules correctly; unit tests for governor + storage green.
As delivered: eight work packages (PRs #20–#25, #27 and #29) and three releases (`0.1.0-alpha.1`, `0.1.0-alpha.2`, `0.1.0`), all three exit criteria met. Settings import/export, planned for P3, shipped with it. Carried forward:
- **P3 presets:** Comfort's AAA body text and Dynamic's gradient accents (docs/UI-MODES.md §2).
- **P3 accessibility:** UI Automation exposes WPF-UI 4.3's navigation items as data items with no Invoke or Select pattern; keyboard users reach them with Tab and Enter. The accent swatches are announced by their hex codes.
- **P2:** pop-out module windows, deferred by the P1 plan.
### P2 — Web runner & core modules (from 2 Nov 2026; planned 11 Jan – 7 Mar 2027)
### P2 — Web runner & core modules (11 Jan – 7 Mar 2027)
Full web runner (profiles, nav policy, SSO popups, notifications→toast, permissions, downloads, suspend/hibernate, catalog fetch) with the v1 catalog; weather; calendar (local + .ics); media player v1 on LibVLCSharp. Bug-report flow end to end (CDP capture → scrubber → prefilled issue + zip).
**Exit (0.2.0):** dogfood daily — Gmail + Discord + YouTube stay signed in across hibernation; a full day's use stays under the hard cap.
As delivered so far: the `0.1.1` hotfix (a tray icon that leaked GDI objects), then the plan's ten work packages and two catalog pull requests, released as `0.2.0-alpha.1` and `0.2.0-alpha.2` on 2 November 2026. `0.2.0` follows about a week of dogfooding against the exit criterion. Changed on the way:
- Downloads use WebView2's own flyout rather than a progress row of OmniDeck's, and permission questions sit in a bar above the page, because no dialog can cover WebView2 ([SPEC](SPEC.md) §4).
- Web apps with notifications on stay resident: the time ladder skips them ([RAM-GOVERNOR](RAM-GOVERNOR.md) §3).
- Pop-out windows move the module's view, so web pages and videos keep running through the move ([ARCHITECTURE](ARCHITECTURE.md) §2).
- Left for later: web app favicons, `.ics` subscriptions (they would need a privacy policy update) and Discord's global push-to-talk hotkey (all in §5), and the weather charts, which wait for ScottPlot in P3.
### P3 — Stocks, presets, i18n (8 Mar – 11 Apr 2027)
Stocks module (Twelve Data with the user's own key, which spike #7 left as the only provider; watchlist, candlesticks); Dynamic and Comfort presets polished to spec (UI-MODES token table); VI + JA translations; accessibility pass (text scaling, contrast themes, keyboard nav).
Stocks module (Stooq default + Twelve Data BYO key, watchlist, candlesticks); Dynamic and Comfort presets polished to spec (UI-MODES token table); VI + JA translations; settings import/export; accessibility pass (text scaling, contrast themes, keyboard nav).
**Exit (0.3.0):** feature-complete against SPEC v1 scope.
@@ -75,8 +51,7 @@ Stocks module (Twelve Data with the user's own key, which spike #7 left as the o
| Milestone | Version |
|---|---|
| Kickoff build | `0.0.1-alpha.1` |
| P0 — spikes | no build: the app does not change |
| Interim builds during phase N (P1–P3) | `0.N.0-alpha.M` |
| Interim builds during phase N | `0.N.0-alpha.M` |
| P1 exit — first installable shell | `0.1.0` |
| P2 exit | `0.2.0` |
| P3 exit — feature-complete | `0.3.0` |
@@ -89,11 +64,10 @@ Every version below 1.0.0 is published as a GitHub **pre-release**; 1.0.0 is the
| Risk | Impact | Mitigation |
|---|---|---|
| Widevine unavailable in WebView2 on target machines | Spotify won't play | **Retired by spike #1:** the evergreen runtime ships Widevine and Spotify plays without flags. If a future runtime breaks EME, the bug report's EME self-check shows it. Fallback unchanged: ship the Spotify entry disabled with a note |
| Google blocks sign-in in WebView2 | Google group unusable | **Spike #2:** sign-in works with the default user agent, and one sign-in covers the `google` group. Google's hop to country-code domains needs `navAllowSets` (P2). Client hints name WebView2, so Google could still block it later; fallback: treat it as an upstream limitation, documented |
| LibVLCSharp airspace friction in WPF | Media UX degraded | **Retired by spike #6:** overlay controls and fullscreen in place work in a `FluentWindow`. Pop-out, in P2, moves the same view, so the video keeps playing and the overlay follows. FlyleafLib is not needed |
| Free API tiers change (Twelve Data/Stooq) | Stocks degraded | **Materialized for Stooq** (2026-10-30), which now blocks scripted clients. Spike #7 leaves Twelve Data with the user's own key as the only provider; its free plan covers US listings. The provider abstraction stays; Stocks is first in the cut order (§4) |
| Web sessions lost across restarts | Users signed out of web apps | Seen once in P0 and not reproduced (spike #2). Since P2, quitting closes the web apps cleanly so the browser writes its cookies out; sign-in health logs each profile's cookie count at close and at first load and warns when it drops to none; bug reports carry the counts (never values) |
| Widevine unavailable in WebView2 on target machines | Spotify won't play | P0 spike gates the catalog entry; fallback: ship Spotify entry disabled with an explanatory note, YouTube covers music for many users |
| Google blocks sign-in in WebView2 | Google group unusable | P0 spike; fallback: session import guidance / treat as upstream limitation, documented |
| LibVLCSharp airspace friction in WPF | Media UX degraded | P0 spike; fallback engine FlyleafLib |
| Free API tiers change (Twelve Data/Stooq) | Stocks degraded | provider abstraction; BYO-key model isolates OmniDeck from quota policy |
| User data stored in Velopack's install folder | Uninstall or reinstall wipes data and sign-ins | data root `%LocalAppData%\OmniDeck.Data`, never `%LocalAppData%\OmniDeck` ([ARCHITECTURE](ARCHITECTURE.md) §5) |
| Solo bandwidth vs. other projects | Schedule slip | cut order below; phases sized with buffer |
@@ -107,4 +81,4 @@ The web runner, governor, legal gate, and the trivial modules are never cut —
## 5. Post-v1 backlog (unordered)
Finnhub provider (real-time US), Google Calendar native sync, `.ics` calendar subscriptions, multi-point global hotkeys per web app (Discord's push-to-talk among them), web app favicons in the sidebar, catalog entries from §4 of WEBAPP-CATALOG, per-module popout window session restore, portable build.
Finnhub provider (real-time US), Google Calendar native sync, multi-point global hotkeys per web app, catalog entries from §4 of WEBAPP-CATALOG, per-module popout window session restore, portable build.
+18 -38
View File
@@ -22,11 +22,11 @@ Status: draft for v1.0 (target May 2027) · Applies to: Windows 11 (24H2 or late
## 2. Shell
- **Navigation:** left sidebar listing pinned modules, then the other open ones; the full module library is a page of its own (Library). Sidebar density and item count vary by UI preset.
- **Navigation:** left sidebar listing pinned modules; full module library behind a "+" view. Sidebar density and item count vary by UI preset.
- **Command palette:** `Ctrl+K` opens a fuzzy launcher for every module, web app, and settings page.
- **Tray:** single-instance app with tray icon; closing the window minimizes to tray (configurable). Tray menu: open, quick timer, media controls while the player has something loaded, quit.
- **Windowing:** modules open in the main window one at a time, and stay in the sidebar while open; any module can move into a top-level window of its own (pop-out) and back ([ARCHITECTURE](ARCHITECTURE.md) §2).
- **Settings:** general (language EN/VI/JA, startup, tray behavior), appearance (preset + per-token overrides), memory (governor thresholds), web apps (each app's notifications and permissions, clearing a group's sign-in data, the catalog in use), data (export/import settings JSON, open data folder), about.
- **Tray:** single-instance app with tray icon; closing the window minimizes to tray (configurable). Tray menu: open, quick timer, media controls when playing, quit.
- **Windowing:** modules open as tabs in the main window; any module can be popped out into its own top-level window.
- **Settings:** general (language EN/VI/JA, startup, tray behavior), appearance (preset + per-token overrides), memory (governor thresholds), per-module settings, data (export/import settings JSON, open data folder), about.
- **Legal gate:** on first run and whenever the acknowledged legal-doc version differs from the shipped version, show EULA, Disclaimer, Privacy Policy, and Third-Party Notices (shipped in the app's `legal\` folder, with links to this repo). The user acknowledges having read them; the acknowledgment (doc version + timestamp) is stored locally and the app stays on the gate until then. It is an acknowledgment, not a condition of the license: GPL-3.0 §9 does not require accepting the license to run the program.
- **About:** app version + commit hash, update check (Velopack), links (GitHub, Discussions, Discord), credits, **Report bug** button (§6).
@@ -54,46 +54,26 @@ All mini-apps implement the module contract in [ARCHITECTURE](ARCHITECTURE.md) a
### 3.5 Stocks (US/EU)
- **Watchlist** with quote, day change, sparkline; detail view with candlestick/OHLC + volume charts (ScottPlot 5), range 1M/6M/1Y/5Y.
- **Provider** behind `IOdQuoteProvider`: `TwelveData`, with the user's own API key (free Basic plan or paid). The module asks for the key on first use; it is stored via **DPAPI**, never in plaintext or logs.
- **Coverage depends on the user's plan.** The free plan covers US stocks, ETFs and US-listed ADRs. Home-market EU listings need Grow, and indices need Pro. Symbol search (`show_plan=true`, free) labels each listing with the plan it needs, and a plan error reads "not available on your Twelve Data plan".
- **Stooq was dropped** in P0 because it now blocks scripted clients ([spike #7](spikes/07-providers.md)).
- Client-side **sliding-window rate limiting**: ≤ 8 credits per rolling 60 s and the plan's daily budget, counting failed calls. Watchlist refreshes use batch quotes. On limit or error, keep the last cached values and show `N/A` for missing fields; never delete cached data on network failure.
- **Providers** behind `IOdQuoteProvider`:
- `Stooq` (default, keyless): end-of-day CSV for US and major EU tickers and indices. Zero configuration.
- `TwelveData` (optional, user-supplied free API key): delayed intraday quotes and time series, US + international coverage. Key stored via **DPAPI**, never in plaintext or logs.
- Client-side **sliding-window rate limiting** per provider; on limit or error, keep last cached values and show `N/A` for missing fields (never delete cached data on network failure).
- Every stocks screen carries the data disclaimer footer ("delayed/indicative data — not investment advice"), mirrored in [DISCLAIMER](legal/DISCLAIMER.md).
### 3.6 Media player
- Engine: **LibVLCSharp + VideoLAN.LibVLC.Windows (x64)**, plugins trimmed to codecs/demux/audio/video output.
- Local files and folders, playlist (m3u load/save), subtitles (embedded + external `.srt`/`.ass`, encoding selection), audio track & device selection, speed 0.25–4×, snapshot.
- libVLC initializes lazily on first open; the player counts as **pinned** while playback is active (governor may not suspend it). Suspend stops and disposes the player, and hibernate disposes libVLC too: playback holds 280–520 MB committed.
- **Fullscreen** makes the module's own window cover the monitor. **Pop-out** moves the player's view, video window included, into the new window, so playback goes on; the track re-selection and seek that a second video view would need ([spike #6](spikes/06-libvlcsharp.md)) are not used.
- **Build:** x64 only (`VlcWindowsX86Enabled` and `VlcWindowsArm64Enabled` set to false), with the trimmed plugin set: about 86 MB raw, 39 MB compressed.
- **As built in P2:**
- The player opens local files, folders and .m3u playlists, from its buttons or dropped on it, and saves the queue as an .m3u.
- The queue and where playback stood live in the database (`media_playlists`), so they survive restarts.
- It has transport controls, a seek bar, volume and mute.
- libVLC ships in `libvlc\win-x64` next to OmniDeck.exe, with these plugin folders: access, audio_filter, audio_mixer, audio_output, codec, demux, misc, packetizer, spu, stream_filter, text_renderer, video_chroma, video_filter and video_output. The network access plugins (http, https, ftp, sftp, smb, rtp, srt) are left out, which comes to about 80 MB raw.
- Only libVLC's errors reach the app log, as warnings, less the three known harmless ones.
- The overlay's More menu has:
- the audio track and the subtitle track;
- a subtitle file (libVLC also picks one up from beside the video, with the same name);
- the subtitles' encoding, from Automatic, UTF-8 and the common code pages. libVLC reads it only when a file opens, so a new choice reopens the file where it stood;
- the speed, from 0.25× to 4×, kept for the files that follow;
- the audio device (Windows' default, or one libVLC lists);
- a snapshot of the picture, saved in Pictures\OmniDeck.
- Speed, encoding and device live in the module's settings document.
- Full screen: the button in the overlay, or a double-click on the picture, makes the main window cover its monitor (chrome hidden, square corners, topmost). Esc, or showing another module, puts it back. The player never moves, so its video window stays the same. The overlay is not fully transparent over a picture (alpha 1), because a click on a fully clear pixel of a layered window falls through to libVLC's window.
- While a player has a file loaded, the tray menu shows the file with Play or Pause, Next and Previous (`IOdMediaControls`). Without a player there is nothing to control: starting one while the view is away could make libVLC open a video window of its own.
- libVLC initializes lazily on first open; the player counts as **pinned** while playback is active (governor may not suspend it).
## 4. Web runner
- One shared `CoreWebView2Environment` (user data under `%LocalAppData%\OmniDeck.Data\WebView2`); one `CoreWebView2Profile` per catalog `profile` group (the `google` group is shared across Google apps for single sign-on; all others are isolated).
- **Navigation policy:** top-level navigation outside the entry's `navAllow` suffix list opens in the system default browser. `NewWindowRequested` to a `popupAllow` domain opens an in-app popup on the same profile (SSO); everything else goes to the default browser.
- **Notifications:** `NotificationReceived` is intercepted and shown as a Windows notification under the app's name; each app's switch in Settings → Web apps defaults to the catalog's `notifications`. An app with notifications on keeps running while hidden ([RAM-GOVERNOR](RAM-GOVERNOR.md) §3).
- **Permissions:** `PermissionRequested` for the user's devices and data (camera, microphone, location, clipboard reading and the like) asks once per app, in a bar above the page, since no dialog can cover WebView2. The answer is remembered per app and reviewable in Settings → Web apps.
- **Downloads:** WebView2's own download flyout saves to the user's Downloads folder; it already handles SmartScreen verdicts and dangerous-file prompts.
- **Full screen:** a page that goes full screen (a video, say) takes the window full screen with it, as the media player does; Esc or showing another module ends both.
- **Media pinning:** while `IsDocumentPlayingAudio` is true and the entry has `audioPin`, the module is pinned (see RAM-GOVERNOR).
- **Lifecycle:** hidden web apps are suspended via `TrySuspendAsync` + `MemoryUsageTargetLevel.Low`, later disposed entirely (session survives via profile cookies). Disposing the last web app ends the shared browser process. Full state machine in [RAM-GOVERNOR](RAM-GOVERNOR.md).
- **Google account domains:** Google's sign-in sets cookies on country-code domains (for example `accounts.google.com.vn`). The `google` entries allow them through the catalog's `google-account-domains` set (schema v2 `navAllowSets`, decided on 2 November 2026; [WEBAPP-CATALOG](WEBAPP-CATALOG.md) §1, [spike #2](spikes/02-google-sign-in.md)).
- **Notifications:** `NotificationReceived` is intercepted and re-raised as a Windows toast tagged with the app name; per-app opt-out in settings.
- **Permissions:** `PermissionRequested` (mic/camera/clipboard/geolocation) shows a native prompt; the decision is remembered per app and reviewable in settings.
- **Downloads:** routed through `DownloadStarting` to the user's Downloads folder with an in-shell progress row.
- **Media pinning:** while `IsDocumentPlayingAudio` is true, the module is pinned (see RAM-GOVERNOR).
- **Lifecycle:** hidden web apps are suspended via `TrySuspendAsync` + `MemoryUsageTargetLevel.Low`, later disposed entirely (session survives via profile cookies). Full state machine in [RAM-GOVERNOR](RAM-GOVERNOR.md).
- **Catalog:** shipped in `catalog/webapps.json`, refreshed from this repo's raw URL at most once per day; schema and rules in [WEBAPP-CATALOG](WEBAPP-CATALOG.md).
## 5. Cross-cutting requirements
@@ -106,10 +86,10 @@ All mini-apps implement the module contract in [ARCHITECTURE](ARCHITECTURE.md) a
## 6. Bug reporting flow
1. A DevTools Protocol session per web app (`Runtime` + `Log`, always on, DevTools UI still disabled) subscribes to `Runtime.consoleAPICalled`, `Runtime.exceptionThrown` and `Log.entryAdded`. It keeps a 200-entry ring buffer per app, plus a 50-entry errors-only ring so chatty apps cannot evict errors ([spike #4](spikes/04-cdp-console.md)). .NET unhandled exceptions and the Serilog tail are collected shell-side.
2. **Report a bug** (Settings → About, or Report bug on the error dialog) composes: version and commit, Windows build, UI preset, the modules with their states and memory, the last 500 log lines, the console rings of the web app picked as the subject, and each web profile's cookie count (never values).
3. Before anything is shown or saved, a scrubber removes query strings and fragments, cookie values, bearer, JWT and other long hex or base64 tokens, email addresses, ids of 15 digits or more, and the user name in profile paths.
4. A dialog previews the issue text. Saving writes `bugreport-<timestamp>.zip` (issue.md, system.json, logs.txt and the console) to `%LocalAppData%\OmniDeck.Data\reports`, keeps the ten newest, shows it in Explorer, and opens a GitHub issue (bug template) with the short fields filled in; long logs travel in the zip, since issue URLs have a length limit. Nothing is uploaded.
1. A DevTools Protocol session per web app subscribes to `Runtime.consoleAPICalled` and `Log.entryAdded`, keeping a 200-entry ring buffer per app. .NET unhandled exceptions and the Serilog tail are collected shell-side.
2. **Report bug** composes: version, Windows build, UI preset, active modules + RAM snapshot, the relevant console ring buffer, and last log lines.
3. Before packaging, a scrubber strips query strings, cookie values, and bearer-token-shaped strings.
4. The app opens a pre-filled GitHub issue (bug template) and writes `bugreport-<timestamp>.zip` to `%LocalAppData%\OmniDeck.Data\reports` for the user to attach (issue-URL prefill has a length limit, so long logs travel in the zip).
## 7. Reference versions (verified 2026-10-28; Dependabot owns bumps from here)
-2
View File
@@ -28,8 +28,6 @@ Presets are named by their character, never by age, both in the UI and in code:
Rules for module authors: never hardcode a font size, padding, radius, or animation duration — consume tokens. CI includes a XAML lint pass (XamlStyler + a grep rule) that flags literal `FontSize=` in module views.
As built in P1, the font, density, hit-target, corner-radius and motion tokens and both `Od.Nav.*` tokens drive the shell. Dynamic closes the sidebar to icons, with each name in a tooltip; Comfort shows at most six modules, always including the one on screen, and the rest stay in the library and the palette. `Od.Contrast.Target` and `Od.Accent.Saturation` are not tokens yet: every preset uses WPF-UI's palette, which meets AA. Comfort's AAA body text and Dynamic's gradient accents come with the P3 preset work, and `Od.Chart.LineWeight` with the first chart (Stocks, P3).
## 3. User overrides
Appearance settings expose the presets as three cards plus granular overrides on top: font-size slider (0.85–1.4× of preset base), motion on/off, accent color. Overrides persist independently of preset choice, so switching presets keeps the user's font preference.
+9 -11
View File
@@ -26,16 +26,13 @@ OmniDeck deliberately does **not** allow arbitrary user-added URLs in v1: the cu
| `startUrl` | https URL | initial navigation target |
| `profile` | string | cookie/profile group; entries sharing a value share sign-in. Reserved group: `google`. Anything else should be unique per app unless sharing is intentional |
| `navAllow` | string[] | domains the main frame may navigate to; anything else opens in the system default browser |
| `navAllowSets` | string[], optional | names of top-level `navAllowSets` whose domains this entry's main frame may also navigate to; for lists too long to repeat in each entry |
| `popupAllow` | string[] | domains whose `window.open` popups open **in-app on the same profile** (SSO flows); all other popups go to the default browser |
| `notifications` | bool | whether web notifications are bridged to Windows toasts by default; the user can switch it per app in Settings → Web apps. An app with notifications on stays running while hidden (RAM-GOVERNOR.md §3) |
| `notifications` | bool | whether web notifications are bridged to Windows toasts (user can still disable per app) |
| `audioPin` | bool | if true, the governor treats the app as pinned while it is playing audio |
**Domain matching.** `navAllow` and `popupAllow` entries are lowercase domains or subdomains — no scheme, port, path, or wildcard. A host matches an entry when it equals it or ends with `.` + the entry, on whole DNS labels: `google.com` matches `mail.google.com`, never `evilgoogle.com`. `navAllow` governs **top-level (main-frame) navigations only**; subresource requests (scripts, images, media, API calls to CDNs) are never filtered by it, so a CDN belongs in `navAllow` only when the app really navigates the main frame there (a file download or a media viewer, for example). The `startUrl` host must be covered by `navAllow`, and every `popupAllow` entry by `navAllow` or the entry's sets.
**Domain matching.** `navAllow` and `popupAllow` entries are lowercase domains or subdomains — no scheme, port, path, or wildcard. A host matches an entry when it equals it or ends with `.` + the entry, on whole DNS labels: `google.com` matches `mail.google.com`, never `evilgoogle.com`. `navAllow` governs **top-level (main-frame) navigations only**; subresource requests (scripts, images, media, API calls to CDNs) are never filtered by it, so a CDN belongs in `navAllow` only when the app really navigates the main frame there (a file download or a media viewer, for example). The `startUrl` host and every `popupAllow` entry must be covered by `navAllow`.
Top-level file fields: `$schema` (optional editor hint), `schemaVersion` (int, currently 2), `updated` (ISO date of the last content change), `navAllowSets` (optional: named lists of domains, each name `[a-z0-9-]`), `apps` (array).
**Named domain sets.** `google-account-domains` lists Google's account host on every country-code domain, `accounts.google.<ccTLD>`, taken from `https://www.google.com/supported_domains` (186 domains; `google.com` itself is already in each entry's `navAllow`). Google's sign-in hops there to set its cookies, for example `accounts.google.com.vn/accounts/SetSID`. Every `google` entry uses the set, because they share one sign-in, and so does `spotify`: its "Continue with Google" signs in to Google on Spotify's own profile, and goes through the same hops. The list lives in the catalog rather than in the app, so a change is a catalog pull request, not a release. Schema v2 (2 November 2026) added `navAllowSets`; no released build read v1, and the app reads v2 only. The JSON Schema is [`catalog/webapps.schema.json`](../catalog/webapps.schema.json); `scripts/validate-catalog.ps1` checks it plus the rules a schema can't express (unique `id` and `name`, every set an entry names exists and every set is used, the coverage rules above, `updated` not in the future), and CI runs it on every pull request. The app checks every catalog it loads or fetches against the same rules (`OdCatalogValidator`, whose test runs on this repository's file), rejects any whose `schemaVersion` it does not understand or that fails them, and keeps the copy it has. A fetched catalog takes effect from the next start.
Top-level file fields: `$schema` (optional editor hint), `schemaVersion` (int), `updated` (ISO date of the last content change), `apps` (array). The JSON Schema is [`catalog/webapps.schema.json`](../catalog/webapps.schema.json); `scripts/validate-catalog.ps1` checks it plus the rules a schema can't express (unique `id` and `name`, the coverage rules above, `updated` not in the future), and CI runs it on every pull request. The app rejects any fetched catalog whose `schemaVersion` it does not understand or that fails validation, and keeps the bundled copy.
## 2. Review rules for new entries (PR checklist)
@@ -43,7 +40,7 @@ Top-level file fields: `$schema` (optional editor hint), `schemaVersion` (int, c
2. `navAllow` is the *minimal* set of domains the app's main frame genuinely navigates to — test sign-in redirects, core flows, and downloads; do not add ad/tracking domains just to silence the default-browser handoff, and do not add CDN/asset domains that are only loaded as subresources.
3. `popupAllow` contains only identity/SSO domains actually used by the sign-in flow.
4. Isolated `profile` unless there is a concrete single-sign-on reason to share.
5. `audioPin: true` only for apps whose primary function is audio/video playback, or voice and video calls (`discord`, `facebook`): a call must not be suspended while it is in progress.
5. `audioPin: true` only for apps whose primary function is audio/video playback.
6. No services that primarily distribute illegal content, and nothing requiring DRM schemes known not to work in WebView2 (see ROADMAP risk register).
7. State in the PR description which flows you manually tested inside OmniDeck (or a WebView2 sample) — sign-in, notifications, a core action.
8. `pwsh scripts/validate-catalog.ps1` passes locally (CI runs it too).
@@ -52,14 +49,15 @@ Top-level file fields: `$schema` (optional editor hint), `schemaVersion` (int, c
| id | profile | audioPin | Notes |
|---|---|---|---|
| spotify | spotify | yes | Web Player; DRM works in the runtime ([spike #1](spikes/01-drm-widevine.md)). "Continue with Google / Facebook / Apple" move the main frame to `accounts.google.com`, `www.facebook.com` and `appleid.apple.com` and back, so those hosts and the `google-account-domains` set are listed (each hop checked up to the provider's sign-in page on 2 November 2026) |
| discord | discord | yes | pinned while a voice or video call plays audio; no global PTT on web; host hotkey partial mitigation |
| youtube | google | yes | sign-in hops to Google's country-code domains, allowed through the `google-account-domains` set like every `google` entry ([spike #2](spikes/02-google-sign-in.md)) |
| spotify | spotify | yes | Web Player; requires DRM in the runtime — gated on the P0 spike result; third-party sign-in buttons (Google/Facebook/Apple) untested until then |
| discord | discord | no | no global PTT on web; host hotkey partial mitigation |
| youtube | google | yes | |
| gmail | google | no | |
| gcalendar | google | no | |
| gdrive | google | no | |
| gmaps | google | no | replaces a native map mini-app entirely |
| facebook | meta | yes | pinned while a call or video plays audio; also Meta's web messaging (`facebook.com/messages`) since messenger.com closed in April 2026; the Messenger entry was removed |
| facebook | meta | no | |
| messenger | meta | no | shares `meta` profile with Facebook for one sign-in |
## 4. Known-good candidates for post-v1 PRs
+1 -1
View File
@@ -105,5 +105,5 @@ WPF-UI ships Fluent System Icons (MIT). **Segoe Fluent Icons cannot be redistrib
- `ui:` controls subclass their native counterparts — code and tests targeting base types (`ButtonBase`, `TextBoxBase`) keep working; don't duplicate logic per control flavor.
- XamlStyler formats everything, including `ui:` attributes (upstream uses XamlStyler themselves).
- High Contrast: when active, WPF-UI/system colors win over presets ([UI-MODES](UI-MODES.md) §4) — verify in the P3 accessibility pass.
- `FluentWindow` chrome + child-HWND content (LibVLCSharp `VideoView`): fullscreen passed P0 spike #6, and media pop-out passed in P2 by moving the same view, whose overlay must not be owned by a closing window ([ARCHITECTURE](ARCHITECTURE.md) §2).
- `FluentWindow` chrome + child-HWND content (LibVLCSharp `VideoView`): fullscreen toggle is part of P0 spike #6; don't ship media pop-out before it passes.
- Version bumps of `WPF-UI*` packages are Dependabot PRs like any other, but read the release notes first — v3→v4 proved this library will rename APIs between majors.
+3 -3
View File
@@ -1,6 +1,6 @@
# OmniDeck — Disclaimer
Version 1.1 — effective from the first release after 0.0.1-alpha.1. Changes since 1.0: the Stooq stock data service is no longer used, and Messenger is no longer in the web app catalog.
Version 1.0 — effective from the first public release (0.0.1-alpha.1).
## Pre-release software
@@ -8,7 +8,7 @@ OmniDeck is pre-release (alpha/beta) software provided **as is**, without warran
## Financial data — not investment advice
The stocks module displays market data obtained from a third-party provider (Twelve Data, using your own API key). This data may be **delayed, incomplete, or inaccurate**, and it is not suitable for time-sensitive decisions. Nothing displayed by OmniDeck constitutes financial, investment, legal, or tax advice, and no fitness for trading purposes is implied. Any decisions you make based on this data are entirely your own responsibility. Verify figures with your broker or an official exchange source before acting.
The stocks module displays market data obtained from third-party providers (Stooq; optionally Twelve Data). This data may be **delayed, incomplete, or inaccurate**, and end-of-day sources are not suitable for time-sensitive decisions. Nothing displayed by OmniDeck constitutes financial, investment, legal, or tax advice, and no fitness for trading purposes is implied. Any decisions you make based on this data are entirely your own responsibility. Verify figures with your broker or an official exchange source before acting.
## Weather data
@@ -16,7 +16,7 @@ Weather information comes from Open-Meteo and is provided for general planning o
## Third-party web applications and services
Web apps accessible through OmniDeck (Spotify, Discord, YouTube, Google services, Facebook, and others in the catalog) are operated entirely by their respective providers. Their availability, functionality, sign-in behavior, and content may change or cease at any time without notice, and some capabilities differ from those providers' native desktop apps (documented in the README). OmniDeck has no control over, and assumes no responsibility for, those services or their content. Your use of them is subject to their own terms.
Web apps accessible through OmniDeck (Spotify, Discord, YouTube, Google services, Facebook, Messenger, and others in the catalog) are operated entirely by their respective providers. Their availability, functionality, sign-in behavior, and content may change or cease at any time without notice, and some capabilities differ from those providers' native desktop apps (documented in the README). OmniDeck has no control over, and assumes no responsibility for, those services or their content. Your use of them is subject to their own terms.
## Trademarks
+2 -2
View File
@@ -1,6 +1,6 @@
# OmniDeck — End User License Agreement (EULA)
Version 1.1 — effective from the first release after 0.0.1-alpha.1. Changes since 1.0: the Stooq stock data service is no longer used, and Messenger is no longer in the web app catalog.
Version 1.0 — effective from the first public release (0.0.1-alpha.1).
By installing or using OmniDeck ("the Software"), you acknowledge the terms below. If you do not agree with them, do not install or use the Software.
@@ -10,7 +10,7 @@ The Software is free software licensed under the **GNU General Public License v3
## 2. Third-party components and services
The Software bundles third-party components (such as the .NET runtime, WPF-UI, Velopack and, in later versions, libVLC) that are governed by their own licenses, listed in THIRD-PARTY-NOTICES.md. It relies on the Microsoft Edge WebView2 Runtime that ships with Windows 11; the runtime is not bundled with the Software and is governed by Microsoft's license terms. The Software also loads third-party **web applications and data services** (e.g., Spotify, Discord, Google services, Open-Meteo, Twelve Data). Your use of those services is governed solely by their own terms of service and privacy policies; you are responsible for complying with them. OmniDeck is not affiliated with, endorsed by, or sponsored by any of these providers, and their trademarks belong to their respective owners.
The Software bundles third-party components (such as the .NET runtime, WPF-UI, Velopack and, in later versions, libVLC) that are governed by their own licenses, listed in THIRD-PARTY-NOTICES.md. It relies on the Microsoft Edge WebView2 Runtime that ships with Windows 11; the runtime is not bundled with the Software and is governed by Microsoft's license terms. The Software also loads third-party **web applications and data services** (e.g., Spotify, Discord, Google services, Open-Meteo, Stooq, Twelve Data). Your use of those services is governed solely by their own terms of service and privacy policies; you are responsible for complying with them. OmniDeck is not affiliated with, endorsed by, or sponsored by any of these providers, and their trademarks belong to their respective owners.
## 3. Your responsibilities
+2 -2
View File
@@ -1,6 +1,6 @@
# OmniDeck — Privacy Policy
Version 1.1 — effective from the first release after 0.0.1-alpha.1. Changes since 1.0: the Stooq stock data service is no longer used, and Messenger is no longer in the web app catalog.
Version 1.0 — effective from the first public release (0.0.1-alpha.1).
**Short version: OmniDeck collects nothing.** There is no telemetry, no analytics, no account, no crash auto-upload, and no server operated by the OmniDeck project that receives your data.
@@ -21,7 +21,7 @@ The app itself is installed separately, in `%LocalAppData%\OmniDeck`. Uninstalli
OmniDeck only talks to the internet for the features you use:
- **Open-Meteo** — weather forecasts and geocoding for your saved locations.
- **Twelve Data**, only after you enter your own API key: stock quotes, price history and symbol search for the stocks module.
- **Stooq** and (only if you configure a key) **Twelve Data** — stock quotes for tickers on your watchlist.
- **GitHub** — update checks/downloads (Velopack) and the daily web-app catalog refresh; opening a pre-filled bug-report issue happens in your browser and only if you choose to.
- **Microsoft Edge WebView2 Runtime** — the Microsoft component that renders the web apps may contact Microsoft services on its own, for example Microsoft Defender SmartScreen reputation checks for the pages you visit and the runtime's own updates and diagnostic data. That traffic is governed by Microsoft's privacy statement and your Windows diagnostic-data settings; OmniDeck does not enable any additional reporting.
- **The third-party web apps you open** (Spotify, Discord, Google services, Facebook, etc.) — these connections go directly from your device to those providers. Their handling of your data is governed by **their** privacy policies, not this one. OmniDeck does not inject analytics into, read the contents of, or proxy these sessions.
File diff suppressed because it is too large. Load diff
-53
View File
@@ -1,53 +0,0 @@
# Spike 01 — DRM / Widevine in WebView2
**Question:** does WebView2 play Widevine-protected media — concretely, does the Spotify Web Player play?
**Decision:** GO. The evergreen WebView2 Runtime ships its own Widevine CDM. With default settings and no browser arguments, EME offers Widevine (software) and PlayReady, and the Spotify Web Player played after sign-in.
**Measured:** 2026-10-30 on `spike/p0` at `0fe4b12` (`spikes/WebLab`: the `--auto` EME probe, plus a session where the maintainer signed in by hand). Issue [#2](https://github.com/poli0981/OmniDeck/issues/2).
## Environment
- WebView2 Runtime 156.0.4314.50, evergreen and machine-wide, with WebView2 SDK 1.0.4314.35.
- The runtime folder contains `WidevineCdm\_platform_specific\win_x64\widevinecdm.dll` (CDM 4.10.3050.1, with its `.sig`), and VMP signature files sit next to `msedgewebview2.exe` and `msedge.dll`.
- Windows Insider build 29648, RTX 5080.
- Spotify: the maintainer's own account, signed in with Spotify credentials.
## Method
- **EME probe page** (`spikes/WebLab/LabPages/eme.html`): on a bare profile with default environment options, call `navigator.requestMediaKeySystemAccess` and then `createMediaKeys` for each key system and robustness, with H.264 video and AAC audio.
- **Shaka Player** support page, checked by eye.
- **Spotify Web Player** on its own profile: sign in, then play, pause, resume and change tracks over about 20 minutes. WebLab logs `IsDocumentPlayingAudioChanged`; processes were checked in Task Manager.
## Results
| Key system | Robustness | Available |
|---|---|---|
| `com.widevine.alpha` | (none) | yes |
| `com.widevine.alpha` | `SW_SECURE_CRYPTO` | yes |
| `com.widevine.alpha` | `HW_SECURE_ALL` | no |
| `com.microsoft.playready.recommendation` | (none) | yes |
| `com.microsoft.playready.recommendation` | `3000` | no |
| `com.microsoft.playready` | (none) | yes |
| `org.w3.clearkey` | (none) | yes |
- **Spotify plays.**
- Sign-in stayed inside `accounts.spotify.com`.
- Playback started 11 s after landing on `open.spotify.com` and kept going for about 20 minutes. `IsDocumentPlayingAudio` toggled at each track change.
- Task Manager showed three "WebView2 Utility: Widevine" processes of 52–58 MB each (private working set) while Spotify, YouTube and the EME probe page were open.
- **No setup needed:** no browser argument or setting was required.
- **Hardware-backed DRM** (Widevine `HW_SECURE_ALL`, PlayReady SL3000) is not offered. That limits HD playback on services that demand it. None of those are in the catalog.
## Consequences
- The `spotify` entry stays in the v1 catalog. The "gated on the P0 spike" note in [WEBAPP-CATALOG](../WEBAPP-CATALOG.md#3-initial-catalog-v1) §3 can go at P0 exit.
- **Governor:** the Widevine processes are utility processes that count toward the footprint while media plays. `audioPin` already keeps Spotify active during playback.
- **Future runtimes:** the CDM ships with the runtime and updates with it. If a future runtime breaks EME, the bug-report flow should be able to tell; an EME self-check (the probe page's logic) is a cheap addition to the report.
- **Spotify's third-party sign-in buttons** (Google, Facebook, Apple) belong to spike #2.
## Reproduce
On `spike/p0`:
```powershell
dotnet run --project spikes/WebLab -- --auto # EME results in %LocalAppData%\OmniDeck.Spikes\weblab\*.log
dotnet run --project spikes/WebLab # open "spotify", sign in, play
```
-67
View File
@@ -1,67 +0,0 @@
# Spike 02 — Google sign-in and SSO popups
**Question:** can users sign in to Google inside WebView2 with the default user agent, and do the SSO flows the catalog relies on work?
**Decision:** GO with conditions. Google, Spotify, Discord and Facebook sign-ins all completed inside WebView2 with the default user agent, one Google sign-in covered every app on the shared `google` profile, and in a controlled re-test all five sign-ins survived a restart. Two conditions remain for P2:
- Google's sign-in hops through country-code Google domains, and today's `navAllow` blocks that hop.
- One session lost every cookie it had set, and the cause is still unknown.
**Measured:** 2026-10-30. Two sessions where the maintainer signed in by hand, in WebLab on `spike/p0`: the first at `0fe4b12`, the re-test at `3eae21e` with Chromium logging on. Between them, the `--measure` run (`ec79454`) and the cookie probes (`6c60b86`). Issue [#3](https://github.com/poli0981/OmniDeck/issues/3).
## Environment
- **User agent:** WebView2 Runtime 156.0.4314.50 with its default user agent, `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36 Edg/156.0.0.0`. The string is identical to Edge's, but `navigator.userAgentData.brands` also lists **Microsoft Edge WebView2 156**, so sites can see the embedding through client hints.
- **Policy:** the catalog's `navAllow` / `popupAllow` were enforced. A navigation outside them was cancelled and logged; the product would hand it to the default browser.
- **Profiles:** one environment, one profile per catalog `profile` group.
- **Location:** Vietnam.
## Results
### Sign-in flows (main frame)
| App (profile) | Flow | Result |
|---|---|---|
| YouTube (`google`) | `youtube.com` → `accounts.google.com` sign-in → passkey-enrollment prompt → `CheckCookie` → Google's prompts (a home-address prompt the first time, identity verification by selfie on the re-test) → `accounts.youtube.com/accounts/SetSID` → **`accounts.google.com.vn/accounts/SetSID`** | The credentials were accepted. The main-frame hop to `google.com.vn` falls outside `navAllow` and was cancelled. Google retried it 15 times in about 40 s the first time and 6 times on the re-test, a loop the user can only leave by navigating away. The `.google.com.vn` sign-in cookies were set anyway, through subresource requests. |
| Gmail, Drive, Calendar, Maps (`google`) | `mail.google.com` → `accounts.google.com/ServiceLogin` → `<service>/accounts/SetOSID` → app | Signed in with no prompt. One sign-in covers the group. |
| Spotify (`spotify`) | `open.spotify.com` → `accounts.spotify.com/login` → back | Signed in with Spotify credentials; playback works (spike #1) |
| Discord (`discord`) | inside `discord.com/app` | Signed in |
| Facebook (`meta`) | `facebook.com` → `/checkpoint/…` → `/auth_platform/afad/` → home | Facebook's new-device checkpoint, completed in the app, both times |
Other observations:
- Google offered passkey enrollment. It was skipped, so WebAuthn was not exercised.
- YouTube and Facebook asked for the Notifications permission. P2 bridges these requests through `PermissionRequested`.
### Sessions across restarts
- **First session (12:35–13:01, 11 windows, about 25 minutes):**
- At the next start, Google, Spotify and Facebook were signed out. Not a single cookie set during that session was left in any of the four profiles: neither the auth cookies nor tracking cookies such as `datr`, `sp_t` and `__dcfduid`.
- Cookies set by an earlier scripted run in the same `google` profile were still there.
- Discord stayed signed in, because its token lives in localStorage, which survived.
- **Cookie probes:** a one-year cookie set from a lab page survived a clean exit, a window close, a host kill, and a hard kill of the whole WebView2 tree 55 s after it was set. How the host shut down does not explain the loss.
- **Controlled re-test** (Chromium logging on: sign in, wait, close with the window's X): the auth cookies were on disk right after closing: Google `SID`/`SAPISID`/`__Secure-*PSID`, Spotify `sp_dc`/`sp_key`, Facebook `c_user`/`xs`. On restart, `--check-signed-in` found **Gmail, YouTube, Spotify, Facebook and Discord all signed in**. Gmail was still signed in after a reload with CDP capture on (spike #4). The Chromium log shows no cookie-store or decryption errors.
- **One clue:** in the first session the `google` profile wrote nothing to its preferences diagnostics. The other profiles logged every 10 s. Not enough to name a cause.
### Not tested
Spotify's "Continue with Google / Facebook / Apple" buttons were not tried; the maintainer used Spotify credentials. `spotify`'s `navAllow` lists only Spotify's domains, so if those buttons move the main frame to `accounts.google.com`, `facebook.com` or `appleid.apple.com`, the product would hand them to the default browser and sign-in would fail. They must be tested in P2 before the entry's lists are final ([WEBAPP-CATALOG](../WEBAPP-CATALOG.md#2-review-rules-for-new-entries-pr-checklist) §2).
## Consequences
- **Google's account domains on every country-code TLD.** Google lists them at `https://www.google.com/supported_domains`. Enumerating about 190 domains in each `google` entry would be unreadable. The proposal is a catalog schema v2 field, `navAllowSets: ["google-account-domains"]`, which the app resolves from a list it bundles. A narrower rule in code would only allow `accounts.google.<ccTLD>/accounts/SetSID`. Either way this changes the catalog or its schema, so it is decided in P2 with the maintainer's approval. **Decided on 2 November 2026:** the first option, with the set defined in the catalog itself instead of bundled with the app, so it changes with a catalog pull request ([WEBAPP-CATALOG](../WEBAPP-CATALOG.md) §1).
- **Sessions must be checked, not assumed.** The P2 exit criterion "stays signed in across hibernation" makes the unexplained loss a real risk:
- P2 dogfoods with Chromium logging available;
- the web runner records whether each app comes back signed in after a restart. The `--check-signed-in` probes become a debug-only health check;
- the bug report includes per-profile cookie-store counts, never cookie values.
- If the loss comes back, it gets investigated before 0.2.0.
- **Default user agent only:** this works today, and there is no spoofing. Because client hints name WebView2, Google could block it later. The roadmap's mitigation still applies: document it as an upstream limitation.
- **New-device flows** (Facebook's checkpoint, Google's prompts including the selfie check) need full in-app navigation within the entry's domains, which works.
## Reproduce
On `spike/p0`:
```powershell
dotnet run --project spikes/WebLab -- "--wv2-args=--enable-logging --v=0" # sign in by hand, then close
dotnet run --project spikes/WebLab -- --check-signed-in # SIGNED-IN lines in weblab\*.log
dotnet run --project spikes/WebLab -- --cookie-set=probe1 # then --cookie-check
```
-114
View File
@@ -1,114 +0,0 @@
# Spike 03 — Memory reality check and governor metric
**Question:** what do web apps really cost in each governor state, and which memory metric do the caps use?
**Decision:** GO. The governor measures **private commit** (`Process.PrivateMemorySize64`), summed over the shell and every WebView2 process. Suspension mostly trims the working set rather than freeing memory, so a working-set metric would reward exactly that trimming. The ladder's real memory saving comes from hibernation.
**Measured:** 2026-10-30 on `spike/p0`: the `WebLab --measure` run at `ec79454` (60 s phases, a sample every 2 s), the signed-in Gmail ladder at `3eae21e`, and the maintainer's own interactive session. Issue [#4](https://github.com/poli0981/OmniDeck/issues/4).
## Environment
- Windows Insider build 29648, i7-14700KF, 32 GB RAM, RTX 5080.
- WebView2 Runtime 156.0.4314.50. One shared environment and one profile per catalog `profile` group, hosted in WebLab, a plain WPF window standing in for the shell.
- Caveat: Chromium's memory heuristics depend on physical RAM, so absolute numbers on an 8 GB machine will differ.
## Method
- **Sampler.** Every 2 s, it reads the shell and each process from `CoreWebView2Environment.GetProcessInfos()`. For each process it records:
- private commit (`Process.PrivateMemorySize64`);
- private working set (`GetProcessMemoryInfo` → `PROCESS_MEMORY_COUNTERS_EX2.PrivateWorkingSetSize`, the figure Task Manager's Memory column shows);
- working set;
- CPU time.
Renderers are attributed to apps through `GetProcessExtendedInfosAsync`, from each frame's root frame id and host.
- **Ladder per app.** Active → hidden → `TrySuspendAsync` + `MemoryUsageTargetLevel.Low` → resumed (`Normal` + `Resume` + shown) → disposed, keeping only `{url}` → reopened. The active, suspended and reopened phases last 60 s; the others last 30 s. Each figure is the mean of the phase's samples after the first two.
- **Everything at once.** All 8 catalog apps open, then every app except the visible one suspended, then all disposed.
- **Real use.** The maintainer's session: 11 app windows (Gmail three times), signed in, with Spotify and YouTube playing, for about 20 minutes.
## Results
### Ladder (MB)
"App" counts the processes attributed to the app. "Shared" counts the browser, GPU and utility processes.
**Discord, signed in**
| State | App commit | App private WS | Shared commit | Shared private WS | CPU (ms/s) |
|---|---|---|---|---|---|
| Active | 443 | 394 | 222 | 107 | 15.0 |
| Hidden | 307 | 268 | 171 | 96 | 2.6 |
| Suspended + Low | 291 | 93 | 170 | 49 | 2.0 |
| Resumed | 294 | 61 | 218 | 37 | 0.7 |
| Disposed | 0 | 0 | 0 | 0 | 0 |
| Reopened | 403 | 356 | 203 | 100 | 10.4 |
**YouTube home, signed out** (see [Open items](#open-items))
| State | App commit | App private WS | Shared commit | Shared private WS | CPU (ms/s) |
|---|---|---|---|---|---|
| Active | 206 | 182 | 260 | 124 | 14.8 |
| Hidden | 168 | 144 | 242 | 114 | 2.6 |
| Suspended + Low | 145 | 49 | 241 | 56 | 2.6 |
| Resumed | 165 | 57 | 258 | 40 | 4.6 |
| Disposed | 0 | 0 | 0 | 0 | 0 |
| Reopened | 180 | 164 | 263 | 123 | 3.1 |
**Gmail, signed in** (measured after the sign-in re-test in spike #2; still signed in after the reopen)
| State | App commit | App private WS | Shared commit | Shared private WS | CPU (ms/s) |
|---|---|---|---|---|---|
| Active | 253 | 234 | 269 | 130 | 19.4 |
| Hidden | 214 | 198 | 248 | 119 | 1.3 |
| Suspended + Low | 196 | 65 | 248 | 58 | 0.3 |
| Resumed | 221 | 148 | 261 | 39 | 17.6 |
| Disposed | 0 | 0 | 0 | 0 | 0 |
| Reopened | 255 | 236 | 254 | 122 | 25.7 |
- **Shell:** the WPF window itself used 93–130 MB of private commit throughout.
- **Suspend and resume:** `TrySuspendAsync` returned `true` in 0–4 ms, and resuming took 1–5 ms.
- **Reopen after dispose:** 155–176 ms until the controller was ready, and 590–900 ms until the first `NavigationCompleted` (2.5 s for signed-in Gmail).
- **One stall:** creating a controller while the previous browser process was still shutting down took 5.2 s once.
### Everything at once (MB)
| Scenario | Processes | Σ private commit | Σ private WS (≈ Task Manager) |
|---|---|---|---|
| 8 catalog apps open, idle (Discord signed in; Google, Spotify and Facebook signed out, see spike #2) | 17 | 2,246 | 1,552 |
| the same, with 7 of them suspended + Low | 17 | 2,103 | 853 |
| all disposed | 1 (shell) | 130 | 72 |
| maintainer's session: 11 windows signed in, 2 playing | 26 | 4,429 (peak 5,022) | 3,037 |
In the maintainer's session:
- The GPU process alone held 955 MB of private commit but only 335 MB of private working set.
- Widevine ran in three utility processes of 52–58 MB each.
- Task Manager showed 3,085 MB for the WebView2 group while the sampler read 2,960 MB of private working set for the WebView2 processes. The sampler matches what users see.
## Analysis
- **Hiding** a web app already releases 15–31 % of its committed memory, because Chromium drops caches for hidden pages.
- **Suspend + Low** cuts the private working set by 65–70 % but committed memory by only 5–15 %. The pages move to the standby list or the page file; they are not released. After resume the working set stays low until those pages are touched again.
A working-set metric would therefore read low exactly when nothing has been freed. That is the page shuffling [RAM-GOVERNOR](../RAM-GOVERNOR.md#4-cap-enforcement) §4 rejects.
- **Only disposal releases memory.** Disposing the *last* web app ends the whole WebView2 browser process. That is the only way the shared overhead goes away: 170–260 MB when idle, and about 1.5 GB of commit (mostly GPU) in the maintainer's media session.
- **The ladder's assumption was wrong:** RAM-GOVERNOR §1 assumed "tens of MB" for a suspended web app. Measured, its committed memory stays at 85–95 % of the hidden state.
## Consequences
- **Metric:** private commit, summed over the shell and every WebView2 process. `Process.PrivateMemorySize64` needs no process handle. The task-manager panel labels the figure as committed memory and may show the private working set beside it, since that is the number Task Manager users know.
- **Victims:** cap enforcement picks apps by their attributed commit. Shared processes appear as a separate "WebView2 (shared)" row and are never demoted.
- **Ladder:** the Suspended rung saves CPU and power (2 ms/s instead of about 15 ms/s), not memory. Memory pressure goes straight to Hibernate. RAM-GOVERNOR §1 and §4 are updated at P0 exit.
- **Caps:** the maintainer's real session reached 4.4–5.0 GB committed, right at the 4.5 GiB soft cap. That is fine on 32 GB but not on 8 GB. Proposal for P1: default caps relative to physical memory, for example soft = min(4.5 GiB, 35 % of RAM) and hard = min(6 GiB, 50 %), re-checked while dogfooding in P2.
- **Last app:** hibernating the last web app costs a browser restart on the next open (about 160 ms plus the page load). The web runner should avoid disposing the last app and immediately opening another, where a 5 s stall was seen.
- **GPU process:** its commit balloons with video (955 MB), and it is shared, so it inflates the total without being something the governor can demote. When shared processes alone push the total over the hard cap, the hard-cap toast says so instead of hibernating apps that would free nothing.
## Open items
- ~~**Gmail:** Gmail signed in was not measured, because the profile had lost its session (spike #2).~~ Done after the sign-in re-test; see the Gmail table above. The same pattern holds: hiding −15 % commit, suspend + Low −8 % more commit but −67 % private working set.
- **8 GB machines:** every number here comes from a 32 GB machine. Re-measure on a GA build of Windows 11 with 8 GB of RAM during P2 dogfooding.
## Reproduce
On `spike/p0`:
```powershell
dotnet run --project spikes/WebLab -- --measure --phase=60 # CSV in %LocalAppData%\OmniDeck.Spikes\memory\
```
-58
View File
@@ -1,58 +0,0 @@
# Spike 04 — CDP console capture
**Question:** can the web runner keep a per-app console ring buffer through the DevTools Protocol, safely and cheaply?
**Decision:** GO. Capture through `Runtime.enable` + `Log.enable` works with the DevTools UI disabled. The widely used page-side check did not detect it, its cost was too small to measure, and signed-in apps kept working with it on. Capture stays on for every web app.
**Measured:** 2026-10-30 on `spike/p0`: the `WebLab --auto` run (`0fe4b12`), the `--measure` run (`ec79454`) and the `--check-signed-in` run (`3eae21e`). Issue [#5](https://github.com/poli0981/OmniDeck/issues/5).
## Environment
- WebView2 Runtime 156.0.4314.50, with `AreDevToolsEnabled = false` (the release setting) on every view.
- The capture subscribes to `Runtime.consoleAPICalled`, `Runtime.exceptionThrown` and `Log.entryAdded` through `GetDevToolsProtocolEventReceiver`, after `CallDevToolsProtocolMethodAsync("Runtime.enable" / "Log.enable")`.
- It feeds a 200-entry ring buffer per app.
## Method
- **Detection page** (`LabPages/cdp-detect.html`): logs an `Error` whose `stack` getter has a side effect. Only a DevTools client that serializes console arguments would read it. The page then emits `console.log`, `console.warn`, an uncaught exception and a failing fetch. It is checked with capture off, with Runtime + Log, and with Log only.
- **Signed-in apps:**
- Discord, Gmail and Spotify run with capture off for 60 s, on for 60 s, then reload with capture on;
- separately, signed-in Gmail reloads with capture on.
## Results
| Mode | Detected by the page? | Captured |
|---|---|---|
| off | no | nothing |
| Runtime + Log | **no** | `console.debug/log/warn/error`, uncaught exceptions (`Runtime.exceptionThrown`), network errors such as a 404 (`Log.entryAdded`) |
| Log only | no | network and browser messages only; **not** `console.*` calls |
- **DevTools UI:** capture works with it disabled. Turning capture on took 4–24 ms per app (230 ms once, on Spotify).
- **Signed-in apps:**
- Discord, signed in, reloaded fine with capture on;
- Gmail, signed in, reloaded with capture on and stayed signed in, with 12 entries captured;
- no captcha or sign-out appeared.
- **Cost:**
- Across the three apps, committed memory was 1,057 MB with capture off, 1,041 MB with it on, and 988 MB after the reloads. The difference is within noise.
- CPU was dominated by the apps themselves.
- The buffer itself is at most 200 short strings per app.
- **Volume:**
- Discord logged 86 entries in about 2 minutes, mostly debug lines styled with `%c` CSS arguments. A 200-entry ring holds about 4–5 minutes of Discord.
- Gmail and Spotify were far quieter: interventions, and Tracking Prevention warnings on Spotify's login page.
- **Personal data:** console lines carry it. Discord logs the user's numeric ID, for example.
- **Not the alternative:** Chromium's own `--enable-logging` also records console messages, but in one global file shared by every app, including personal data. It is a diagnostic switch, not the capture mechanism.
## Consequences
- **Always on:** the web runner enables `Runtime` + `Log` for each web app when its view is created, and keeps the DevTools UI disabled. Capture stops with the view when it is disposed.
- **Two buffers per app:** a 200-entry ring for everything, and a 50-entry ring for errors and uncaught exceptions only, so debug chatter cannot evict the lines a bug report needs.
- **Formatting:** apply `%c` / `%s` format arguments when rendering, and drop the CSS.
- **Privacy:** console lines go through the bug-report scrubber (SPEC §6) like the logs do. Nothing is captured to disk until the user starts a report.
- **Watch:** this held on runtime 156. If a provider starts flagging `Runtime.enable` (captchas, sign-outs), the fallback is to enable capture only while a bug report is being recorded.
## Reproduce
On `spike/p0`:
```powershell
dotnet run --project spikes/WebLab -- --auto # detection and capture modes
dotnet run --project spikes/WebLab -- --check-signed-in # signed-in Gmail reload with capture on
```
-71
View File
@@ -1,71 +0,0 @@
# Spike 05 — Runtime preset swap
**Question:** can the three UI presets (`Od.*` token dictionaries) be swapped at runtime on top of WPF-UI 4.3 without visual artifacts?
**Decision:** GO with conditions. Replacing a code-built preset dictionary in place is fast and showed no visual artifacts. Three conditions apply: any size WPF-UI reads through `StaticResource` goes through our own `Od*` styles, motion is driven from code, and the Windows text size is read from the registry rather than through WinRT.
**Measured:** 2026-10-30 on `spike/p0` at `840c511` (`spikes/ThemeLab`: an `--auto` run, plus a visual check by the maintainer). Issue [#6](https://github.com/poli0981/OmniDeck/issues/6).
## Environment
- Windows Insider build 29648, 32 GB RAM, RTX 5080.
- .NET 10.0.14, WPF-UI 4.3.0.
- Dark theme with the Mica backdrop; text size 100 %, Windows animation effects on, high contrast off.
## Method
ThemeLab is a `FluentWindow` with Mica. It builds each preset's `ResourceDictionary` in code from the [UI-MODES](../UI-MODES.md#2-token-table) table and replaces it in place in `Application.Resources.MergedDictionaries`, after WPF-UI's `ThemesDictionary` and `ControlsDictionary`. The `--auto` run does four things:
1. Under each preset, probes default `ui:Button`, `ui:TextBox` and `ui:Card` controls next to `Od`-styled ones, recording `ActualHeight`, `Padding`, `FontSize` and the template's `CornerRadius`.
2. Times 30 swaps up to `Loaded` dispatcher priority (that is, after layout and render), at 307 and at 3,426 visual elements.
3. Switches Light and Dark with `ApplicationThemeManager.Apply` and checks that the preset layer is still merged.
4. Applies a style whose storyboard uses `{DynamicResource Od.Motion.Duration}`.
The maintainer then switched presets and themes by hand and hovered the motion tile, looking for flicker, Mica glitches and layout jumps. Separately, WPF-UI 4.3's control XAML (tag `4.3.0`) was read to see which keys each control uses through `StaticResource` and which through `DynamicResource`.
## Results
### Which sizes follow a swap
| Control | Dynamic | Standard | Comfort | Follows? |
|---|---|---|---|---|
| default `ui:Button`: padding | 11,5,11,6 | 11,5,11,6 | 11,5,11,6 | no: `ButtonPadding` is a `StaticResource` |
| default `ui:Button`: font size / corner | 13.5 / 8 | 15.5 / 6 | 19 / 6 | yes: `ControlContentThemeFontSize` and `ControlCornerRadius` are dynamic |
| default `ui:Card`: padding | 14,16,14,16 | 14,16,14,16 | 14,16,14,16 | no: `CardPadding` is a `StaticResource` |
| `Od` button (BasedOn `DefaultUiButtonStyle`): height / padding | 32 / 8,4 | 36 / 12,6 | 47 / 20,10 | yes |
| `Od` text box (BasedOn `DefaultUiTextBoxStyle`): height / padding | 32 / 8,4 | 36 / 12,6 | 47 / 20,10 | yes |
The preset layer also redefined `ButtonPadding` and `CardPadding`. WPF-UI's own value won anyway, because those references are resolved inside `ControlsDictionary`. In the 4.3 sources, `ButtonPadding`, `ButtonBorderThemeThickness`, `CardPadding`, `TextBoxBorderThemeThickness` and the text box icon margins are `StaticResource`. `ControlCornerRadius`, `ControlContentThemeFontSize`, `TextControlThemePadding`, `TextControlThemeMinHeight` and `TextControlThemeMinWidth` are `DynamicResource`.
### Swap time (30 swaps each)
| Visual elements | min | median | p90 | max |
|---|---|---|---|---|
| 307 | 6.3 ms | 7.0 ms | 7.8 ms | 18.2 ms |
| 3,426 | 51.3 ms | 62.5 ms | 70.2 ms | 73.3 ms |
The cost is roughly 18 µs per element, so a shell of 1,000–2,000 elements should swap in about 20–40 ms, one or two frames.
### Theme, motion, text size
- **Light/Dark:** `ApplicationThemeManager.Apply` took about 125 ms at 3,426 elements. The preset layer stayed merged both ways, so presets and theme really are independent axes.
- **Motion:** a `DynamicResource` inside a style storyboard throws `InvalidOperationException: Cannot freeze this Storyboard timeline tree for use across threads.` ThemeLab's `OdMotion` behavior avoids this: it reads `Od.Motion.Duration` when each animation starts, skips the animation when the value is 0 or Windows animation effects are off, and follows a swap from the next hover on.
- **Text size:** WPF ignores the Windows text size setting. It can be read from two places, and both returned 1.00 here:
- the registry, `HKCU\Software\Microsoft\Accessibility\TextScaleFactor` (a percentage; missing means 100);
- WinRT, `UISettings.TextScaleFactor`. This needs a Windows-versioned target framework, which puts `Microsoft.Windows.SDK.NET.dll` (26.3 MB) in the output.
- **Visual check (maintainer):** no flicker, Mica glitch or layout jump when switching presets or themes, and the motion tile behaved as expected.
## Consequences
- **Theme engine (P1):** build the preset dictionary in code, since it needs the OS text scale and the user's overrides anyway. Swap that one merged dictionary in place, and keep WPF-UI's dictionaries first.
- **`Od` styles:** for each control that reads a size through `StaticResource`, ship an implicit style BasedOn the WPF-UI default with `DynamicResource` setters bound to `Od.*` tokens. Dynamic WPF-UI keys can be overridden directly in the preset layer, with a comment on each override ([WPFUI-CONVENTIONS](../WPFUI-CONVENTIONS.md#6-theming-with-od-tokens) §6).
- **Motion:** no token-driven storyboards in XAML styles. Animations go through a small behavior that reads `Od.Motion.*` when it starts and honors `SystemParameters.ClientAreaAnimation`.
- **Text size:** read the registry value at startup, and read it again on `WM_SETTINGCHANGE` and whenever the window is activated. This needs no Windows-versioned target framework, which saves about 26 MB. This spike did not observe which notification fires on a live change; re-reading on activation covers both cases.
- **Budget:** swaps only happen when the user picks a preset, so 20–70 ms is fine; keep the shell's visual tree lean. High Contrast and text sizes above 100 % are checked in the P3 accessibility pass.
## Reproduce
On `spike/p0`:
```powershell
dotnet run --project spikes/ThemeLab -- --auto # log in %LocalAppData%\OmniDeck.Spikes\theme\
dotnet run --project spikes/ThemeLab # interactive
```
-90
View File
@@ -1,90 +0,0 @@
# Spike 06 — LibVLCSharp in WPF (airspace, fullscreen)
**Question:** does LibVLCSharp's `VideoView` work inside a WPF-UI `FluentWindow` with overlay controls and a fullscreen toggle?
**Decision:** GO with conditions. Inside a Mica `FluentWindow`, `VideoView` plays with hardware decoding, and WPF overlay controls and subtitles draw correctly above the video. Fullscreen works by resizing the shell window over the monitor. FlyleafLib is not needed. Three conditions:
- moving a playing player to another window (pop-out) needs a video-output restart plus a seek;
- the pop-out's overlay was clipped once;
- with the SPEC plugin set, libVLC adds about 39 MB compressed to the installer.
**Measured:** 2026-10-30 on `spike/p0` at `2a87046` (`spikes/MediaLab`): the `--auto` and `--auto-move` runs on the trimmed plugin build, with every screen capture checked by eye. Issue [#7](https://github.com/poli0981/OmniDeck/issues/7).
## Environment
- LibVLCSharp.WPF 3.10.2 and VideoLAN.LibVLC.Windows 3.0.24 (libVLC 3.0.24 "Vetinari"); WPF-UI 4.3.0; .NET 10.0.14.
- One 2560×1440 monitor at 100 % scale; RTX 5080 (D3D11VA); Windows Insider build 29648.
- Test media, generated locally with ffmpeg so nothing was downloaded:
- H.264/AAC 1080p30, 60 s;
- H.264/AAC 2160p60, 20 s;
- an external `.srt` with Vietnamese and Japanese text.
## Method
MediaLab is a `FluentWindow` (Mica, `ui:TitleBar`) holding a `VideoView`. The view's WPF content is a badge in the top-right corner and a control bar (`ui:Button`, `Slider`, time).
The `--auto` run:
1. plays the 1080p clip and adds the `.srt`;
2. toggles fullscreen in place;
3. opens a fullscreen window and a pop-out, each with and without restarting the video output;
4. hides and shows the main window;
5. plays the 2160p60 clip.
At every step it captures the screen as DWM composited it, because the video and the overlay are separate windows and only the screen shows how they combine. It also logs libVLC warnings, frame statistics, CPU and private commit. `--auto-move` repeats the hand-over to another window with a seek, capturing at 0.5 s and 2 s.
## Results
| Check | Result |
|---|---|
| WPF overlay above the video (airspace) | OK. LibVLCSharp's overlay window draws the WPF controls above the video, translucent backgrounds included |
| External subtitles (`.srt`, UTF-8, Vietnamese and Japanese) | OK |
| Fullscreen in place: shell window resized to the monitor, chrome hidden, corners square | OK, playback never interrupted |
| Hand-over to another window, as is | **No.** The video keeps drawing into the original window, and the new window stays black |
| … after re-selecting the video track | The new window shows video, corrupted until the next keyframe (several seconds) |
| … after re-selecting the track and seeking to the current time | **OK.** A clean picture within 0.5 s, in both directions |
| Pop-out into a second `FluentWindow` | Video OK. The overlay button was clipped on its right side once |
| Hide and show (tray) | Overlay and playback come back |
| Hardware decoding (D3D11VA) | 1080p30 and 2160p60 with 0 lost frames, at under 1 % CPU (of 28 logical cores) |
**Memory** (private commit; libVLC runs inside the shell process):
| Moment | Private commit |
|---|---|
| before libVLC loads | 45 MB |
| libVLC loaded | 116 MB |
| playing 1080p30 | 284 MB |
| playing 2160p60 | 522 MB |
| after `Stop` | 324 MB |
**Size**, x64 only. The package also copies its x86 and ARM64 builds unless `VlcWindowsX86Enabled` and `VlcWindowsArm64Enabled` are set to `false`.
| Plugin set | Raw | Zip (deflate, level 9) |
|---|---|---|
| Full (321 plugins) | 106 MB | 48 MB |
| SPEC set (267 plugins) | 86 MB | 39 MB |
The SPEC set keeps the plugin folders access, audio filter, audio mixer, audio output, codec, demux, packetizer, stream filter, text renderer, spu, video chroma, video filter, video output and misc. The largest files are `libavcodec` (18 MB), `access/srt` (4 MB; network streaming only, removable for local files), `libass` (3.4 MB) and `freetype` (3 MB).
## Consequences
- **Engine:** LibVLCSharp with libVLC 3.0.x, as [SPEC](../SPEC.md#36-media-player) §3.6 says. FlyleafLib stays unused.
- **Fullscreen:** the module's own window (main or pop-out) covers the monitor; the player never moves to a separate fullscreen window. This passes the fullscreen part of [WPFUI-CONVENTIONS](../WPFUI-CONVENTIONS.md#8-hard-rules) §8.
- **Pop-out:** move the player to the new `VideoView`, re-select the video track, and seek to the current time. Pop-out ships only after P2 fixes the overlay's sizing in a newly created window and re-tests it, as §8 requires.
- **Build:**
- set `VlcWindowsX86Enabled` and `VlcWindowsArm64Enabled` to `false` and use the SPEC include list;
- consider dropping the network access plugins (srt and others), since playback is local-file only;
- libVLC is the largest single component in the installer, at about 39 MB compressed. THIRD-PARTY-NOTICES gets its entry in P2, with approval.
- **Governor:** playback holds 280–520 MB committed in the shell process, and `Stop` alone kept 324 MB. `SuspendAsync` therefore stops and disposes the `MediaPlayer`, and `HibernateAsync` disposes the `LibVLC` instance as well.
- **Not tested:** a second monitor and per-monitor DPI changes, because only one monitor was available. Check them in P2 once the media module exists.
- **Log noise:** filter these harmless libVLC messages out of the app log:
- `option quiet does not exist`;
- `SetThumbNailClip failed` (a fullscreen window without a taskbar button);
- `not enough decoding slices`.
## Reproduce
On `spike/p0`, with the test clips from `spikes/README.md`:
```powershell
dotnet build spikes/MediaLab -c Release -p:TrimVlc=true
spikes\MediaLab\bin\Release\net10.0-windows\win-x64\MediaLab.exe --auto
spikes\MediaLab\bin\Release\net10.0-windows\win-x64\MediaLab.exe --auto-move --seek-on-move
```
-143
View File
@@ -1,143 +0,0 @@
# Spike 07 — Stock data providers
**Question:** which data sources can the stocks module rely on, and what do their responses look like?
**Decision:** GO with conditions. In v1 the only provider is Twelve Data, with the user's own key; Stooq is dropped. The free plan covers US listings (stocks, ETFs and the US listings of foreign companies). Home-market EU listings and indices need a paid Twelve Data plan.
**Measured:** 2026-10-30 on `spike/p0` at `6e8694a` (`spikes/ProviderProbe`). Issue [#8](https://github.com/poli0981/OmniDeck/issues/8).
## Environment
- **Client:** `ProviderProbe`, a .NET 10 console app using `HttpClient`. Requests are plain, carry a descriptive `User-Agent`, are never retried and solve no challenges.
- **Key:** read from the `OD_TWELVEDATA_KEY` environment variable and sent as `Authorization: apikey …`, never in a URL.
- **Account:** a free Twelve Data account; `api_usage` reports `plan_category: basic`.
- **Network:** a residential connection in Vietnam.
## Method
- **Stooq:** one GET each to the daily-history CSV endpoint and the quote CSV endpoint.
- **Twelve Data:** 12 calls paced 10 s apart, recording `api-credits-used` / `api-credits-left` from each response:
- a quote and a 3-symbol batch quote;
- time series for the 1M, 6M and 1Y ranges (daily bars) and 5Y (weekly bars);
- symbol search;
- quotes for three home-market EU listings and for an index;
- `api_usage`.
- **Plan check:** one more `symbol_search` with `show_plan=true`.
- **Model check:** `ProviderProbe verify-models` deserializes the saved responses with the models below.
- **Raw responses:** kept locally under `%LocalAppData%\OmniDeck.Spikes\providers` and not committed, because the provider's terms cover redistribution of its data. Any free key reproduces them.
## Results
### Stooq: NO-GO
| Endpoint | Result |
|---|---|
| `/q/d/l/?s=aapl.us&i=d` (daily history CSV) | HTTP 200 `text/html`: a JavaScript proof-of-work page ("This site requires JavaScript to verify your browser"), no CSV |
| `/q/l/?s=aapl.us&f=sd2t2ohlcv&h&e=csv` (quote CSV) | HTTP 404 "The page you requested does not exist or has been moved" |
Community reports add that since March 2026 downloads also need a per-user API key, obtained through a captcha ([pandas-datareader #1012](https://github.com/pydata/pandas-datareader/issues/1012)). OmniDeck does not solve bot challenges, so the app cannot use Stooq at all.
### Twelve Data, free (Basic) plan
| Call | Credits | Result |
|---|---|---|
| `quote?symbol=AAPL` | 1 | OK |
| `quote?symbol=AAPL,MSFT,SPY` | 3 | OK: a JSON object keyed by symbol |
| `time_series`, `1day` × 22 / 126 / 252 (1M / 6M / 1Y) | 1 each | OK |
| `time_series`, `1week` × 261 (5Y, back to 2021-11-01) | 1 | OK |
| `symbol_search?symbol=SAP` | 0 | OK: 30 listings |
| `quote`: SAP on XETR, VOD on LSE, ASML on Euronext | 1 each | 404 "available starting with the Grow or Venture plan" |
| `quote?symbol=SPX` (S&P 500 index) | 1 | 404 "available starting with the Pro or Venture plan" |
| `api_usage` | 1 | OK: 8 credits per minute, 800 per day |
What this means for the client:
- **Credits:**
- A quote costs 1 credit per symbol, so a batch of N costs N.
- A time series costs 1 credit whatever its length.
- Calls that fail still cost a credit.
- `symbol_search` costs nothing.
- **Limits:** the per-minute quota is restored at the start of each minute, and going over it returns 429 ([API credits](https://support.twelvedata.com/en/articles/5194820-api-credits-limits)). A client-side limiter allowing ≤ 8 credits per rolling 60 s therefore never trips it.
- **Plan per listing:** `symbol_search` with `show_plan=true` returns `access: { global, plan }` for each listing. For SAP, the NYSE ADR needs Basic, XETR needs Grow and JSE needs Pro. The app can therefore show which listings a free key can use before spending a credit.
- **No key:** a request without a key gets HTTP 401 with a JSON error body.
- **Latency:** 280–630 ms per call.
- **Budget example:** a watchlist of 20 US symbols refreshed every 15 minutes through a US trading day costs 26 × 20 = 520 credits. That leaves 280 for charts. Because of the per-minute limit, each refresh spreads over three minutes.
### Response models (frozen for P3)
Numbers arrive as JSON strings and names are snake_case, so one set of options covers every call. `verify-models` parses all saved responses with these records:
```csharp
static readonly JsonSerializerOptions TwelveDataJson = new(JsonSerializerDefaults.Web)
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
};
// GET /quote. The batch form (symbol=A,B,C) returns Dictionary<string, TdQuote>.
internal sealed record TdQuote(
string Symbol, string Name, string Exchange, string MicCode, string Currency, string Datetime, long Timestamp,
long? LastQuoteAt, decimal Open, decimal High, decimal Low, decimal Close, long? Volume, decimal PreviousClose,
decimal Change, decimal PercentChange, bool IsMarketOpen, TdFiftyTwoWeek? FiftyTwoWeek);
internal sealed record TdFiftyTwoWeek(decimal Low, decimal High, string Range);
// GET /time_series. Values are newest first; Datetime is a date for 1day/1week bars.
internal sealed record TdTimeSeries(TdSeriesMeta Meta, IReadOnlyList<TdBar> Values, string Status);
internal sealed record TdSeriesMeta(
string Symbol, string Interval, string Currency, string ExchangeTimezone, string Exchange, string MicCode, string Type);
internal sealed record TdBar(string Datetime, decimal Open, decimal High, decimal Low, decimal Close, long? Volume);
// GET /symbol_search?show_plan=true (free).
internal sealed record TdSymbolSearch(IReadOnlyList<TdListing> Data, string Status);
internal sealed record TdListing(
string Symbol, string InstrumentName, string Exchange, string MicCode, string ExchangeTimezone,
string InstrumentType, string Country, string Currency, TdAccess? Access);
internal sealed record TdAccess(string Global, string Plan);
// GET /api_usage (1 credit), and any error (Code mirrors the HTTP status: 401, 404, 429).
internal sealed record TdApiUsage(string Timestamp, int CurrentUsage, int PlanLimit, int DailyUsage, int PlanDailyLimit, string PlanCategory);
internal sealed record TdError(int Code, string Message, string Status);
```
### Alternative considered: Alpha Vantage
This was desk research only; no account was created.
- **Limits:** a free key allows 25 requests per day and 5 per minute ([Macroption](https://www.macroption.com/alpha-vantage-api-limits/)).
- **Coverage:** the free key does reach home-market EU listings at end of day, such as `TSCO.LON` and `MBG.DEX` ([documentation](https://www.alphavantage.co/documentation/)).
- **Limitations:**
- a free key returns only the latest 100 daily bars (the "full" output is premium);
- each quote call covers a single symbol.
That is too little to drive a watchlist, and a second key doubles the setup. It stays on the post-v1 list as a possible add-on for EU end-of-day data.
## Consequences
- **Provider:** Twelve Data only, with the user's own key on any plan. The key is still stored with DPAPI.
- The stocks module now needs setup once. Its first screen explains how to get a free key and where to paste it.
- Stocks with zero configuration is gone.
- **Coverage:** with a free key, US stocks, ETFs and US-listed ADRs. EU companies are reachable through their US listings, and EU exposure through US-listed ETFs.
- Grow unlocks home-market EU listings; Pro unlocks indices.
- Search labels each listing with the plan it needs, compared with `api_usage.plan_category`.
- The 404 plan error is shown as "not available on your Twelve Data plan", never as a failure.
- **Rate limiting:**
- ≤ 8 credits per rolling 60 s, plus a daily budget of 800 that counts failed calls;
- watchlist refreshes use batch quotes;
- daily and weekly bars are cached until the next trading day.
- **Docs, at P0 exit:**
- SPEC §3.5: providers and coverage;
- SECURITY.md: the list of services the app calls;
- ROADMAP: the P3 text and the risk register.
- **Legal docs, only after the maintainer approves:**
- PRIVACY.md: the network list;
- THIRD-PARTY-NOTICES.md: the Stooq row;
- the Stooq mentions in DISCLAIMER.md and EULA.md.
- **Cut order unchanged:** Stocks is still the first thing to move to v1.1 if the schedule slips.
## Reproduce
On `spike/p0`, with `OD_TWELVEDATA_KEY` set to a free key:
```powershell
dotnet run --project spikes/ProviderProbe -- stooq
dotnet run --project spikes/ProviderProbe -- twelvedata
dotnet run --project spikes/ProviderProbe -- verify-models
```
-52
View File
@@ -1,52 +0,0 @@
# OmniDeck — P0 Spikes
P0 runs from 2 to 15 November 2026 ([ROADMAP](../ROADMAP.md#1-phases)). Its job is to de-risk everything that could invalidate the design before P1 builds on it. Each spike answers one question on real hardware and ends in a note in this folder with an explicit decision. P0 exits when all seven notes are merged. Progress is tracked in the [P0 milestone](https://github.com/poli0981/OmniDeck/milestone/1).
## 1. Rules
- **Spike code stays off `main`.** Proof-of-concept projects live on the `spike/p0` branch, which is pushed but never merged. The release SBOM is generated from `main`'s dependency graph ([`release.yml`](../../.github/workflows/release.yml)), and spike-only packages must not show up there, in Dependabot, or in dependency review. Each note names the commit it measured.
- **Spike data stays out of the repository.** WebView2 profiles (cookies, sign-ins), logs and measurements live under `%LocalAppData%\OmniDeck.Spikes`. They never go in the working tree, and never in the app's data root `%LocalAppData%\OmniDeck.Data`.
- **Secrets come from environment variables** (for example `OD_TWELVEDATA_KEY`). They are never committed, logged, or pasted into a note.
- **No circumvention.** No user-agent spoofing to get past sign-in checks, and no solving of bot challenges. If a service blocks an embedded browser or a scripted client, that is the result to record.
- **Sign-ins are done by hand** by the maintainer, in the spike app's window.
- **Record the environment.** Every note states the Windows build, the WebView2 Runtime version, the package versions and the hardware. The development machine runs a Windows Insider build with 32 GB of RAM, which is not what most users have, so memory numbers are re-measured on a GA build of Windows 11 if they look off.
## 2. Status
| # | Spike | Blocks | Decision | Note |
|---|---|---|---|---|
| 1 | DRM / Widevine in WebView2 | P2: Spotify catalog entry | **GO:** the runtime ships Widevine and Spotify plays, with no flags | [01-drm-widevine.md](01-drm-widevine.md) |
| 2 | Google sign-in and SSO popups | P2: `google` profile group, Spotify sign-in | **GO with conditions:** sign-ins work and persist; Google's ccTLD hop needs `navAllow` support; one unexplained session loss is watched in P2 | [02-google-sign-in.md](02-google-sign-in.md) |
| 3 | Memory reality check and governor metric | **P1**: RAM governor ([§4](../RAM-GOVERNOR.md#4-cap-enforcement)) | **GO:** the metric is private commit; suspend trims, only hibernate frees memory | [03-memory.md](03-memory.md) |
| 4 | CDP console capture | P2: bug-report flow | **GO:** always on, works with the DevTools UI disabled, not detected, no measurable cost | [04-cdp-console.md](04-cdp-console.md) |
| 5 | Runtime preset swap | **P1**: theme engine | **GO with conditions:** `Od` styles for WPF-UI's static keys, motion driven from code, text size from the registry | [05-theme-swap.md](05-theme-swap.md) |
| 6 | LibVLCSharp in WPF (airspace, fullscreen) | P2: media player | **GO with conditions:** overlay and fullscreen in place work; pop-out needs a vout restart + seek; about 39 MB compressed | [06-libvlcsharp.md](06-libvlcsharp.md) |
| 7 | Stock data providers | P3: stocks | **GO with conditions:** Twelve Data with the user's key is the only provider; Stooq NO-GO | [07-providers.md](07-providers.md) |
The two spikes that block P1 (#3 and #5) go first. A spike that only blocks P2 or P3 may run on into the first weeks of P1, but its note still has to land before the phase it blocks starts.
## 3. Note template
Notes are named `NN-<slug>.md`. When a note is merged, its row in the table above links to it and records the decision, and the spike's issue is closed.
~~~markdown
# Spike NN — <title>
**Question:** the one thing this spike decides.
**Decision:** GO | GO with conditions | NO-GO, in one sentence.
**Measured:** YYYY-MM-DD on `spike/p0` at `<commit>`.
## Environment
Windows build, WebView2 Runtime, package versions, CPU / RAM / GPU.
## Method
What was run and how, in enough detail to repeat it.
## Results
Raw numbers (tables, or a CSV next to the note) and observations.
## Consequences
What changes in the spec, architecture, governor, catalog or roadmap, and any follow-up issues.
Changes to `docs/legal/**` and `catalog/webapps.json` are proposed here and made only after the
maintainer approves them.
~~~
-93
View File
@@ -1,93 +0,0 @@
<#
.SYNOPSIS
Draws OmniDeck's application icon: the monogram "O" on a blue rounded square, as the tray icon
draws it (src/OmniDeck.App/Shell/OdTrayIcon.cs), at the sizes Windows asks for.
.DESCRIPTION
Writes src/OmniDeck.App/Assets/OmniDeck.ico, which the executable, its windows and Velopack's
Setup use. It stands in until a designed icon exists: replacing that file is enough, and this
script need not run again. WPF draws the images, so run it in an STA thread, as pwsh does.
.EXAMPLE
pwsh scripts/make-icon.ps1
#>
[CmdletBinding()]
param(
[string]$OutFile = (Join-Path $PSScriptRoot '..\src\OmniDeck.App\Assets\OmniDeck.ico')
)
$ErrorActionPreference = 'Stop'
Add-Type -AssemblyName PresentationCore, PresentationFramework, WindowsBase
# Windows' default accent, which the tray icon also falls back to.
$background = [System.Windows.Media.SolidColorBrush]::new([System.Windows.Media.Color]::FromRgb(0x00, 0x67, 0xC0))
$foreground = [System.Windows.Media.Brushes]::White
$sizes = @(16, 20, 24, 32, 40, 48, 64, 256)
function New-IconImage([int]$Size) {
$visual = [System.Windows.Media.DrawingVisual]::new()
$context = $visual.RenderOpen()
$corner = $Size / 8.0
$context.DrawRoundedRectangle($background, $null, [System.Windows.Rect]::new(0, 0, $Size, $Size), $corner, $corner)
$typeface = [System.Windows.Media.Typeface]::new(
[System.Windows.SystemFonts]::MessageFontFamily,
[System.Windows.FontStyles]::Normal,
[System.Windows.FontWeights]::Bold,
[System.Windows.FontStretches]::Normal)
$text = [System.Windows.Media.FormattedText]::new(
'O',
[Globalization.CultureInfo]::InvariantCulture,
[System.Windows.FlowDirection]::LeftToRight,
$typeface,
$Size * 0.8,
$foreground,
1.0)
$glyph = $text.BuildGeometry([System.Windows.Point]::new(0, 0))
$bounds = $glyph.Bounds
$context.PushTransform([System.Windows.Media.TranslateTransform]::new((($Size - $bounds.Width) / 2) - $bounds.X, (($Size - $bounds.Height) / 2) - $bounds.Y))
$context.DrawGeometry($foreground, $null, $glyph)
$context.Pop()
$context.Close()
$bitmap = [System.Windows.Media.Imaging.RenderTargetBitmap]::new($Size, $Size, 96, 96, [System.Windows.Media.PixelFormats]::Pbgra32)
$bitmap.Render($visual)
$encoder = [System.Windows.Media.Imaging.PngBitmapEncoder]::new()
$encoder.Frames.Add([System.Windows.Media.Imaging.BitmapFrame]::Create($bitmap))
$png = [IO.MemoryStream]::new()
$encoder.Save($png)
return , $png.ToArray()
}
$images = foreach ($size in $sizes) { , (New-IconImage $size) }
# ICO: the directory, one entry per image, then the images, PNG-compressed (Windows reads those).
$ico = [IO.MemoryStream]::new()
$writer = [IO.BinaryWriter]::new($ico)
$writer.Write([uint16]0)
$writer.Write([uint16]1)
$writer.Write([uint16]$sizes.Count)
$offset = 6 + (16 * $sizes.Count)
for ($i = 0; $i -lt $sizes.Count; $i++) {
# Width and height are one byte each: 0 means 256.
$dimension = [byte]($sizes[$i] % 256)
$writer.Write($dimension)
$writer.Write($dimension)
$writer.Write([byte]0)
$writer.Write([byte]0)
$writer.Write([uint16]1)
$writer.Write([uint16]32)
$writer.Write([uint32]$images[$i].Length)
$writer.Write([uint32]$offset)
$offset += $images[$i].Length
}
foreach ($image in $images) {
$writer.Write([byte[]]$image)
}
$writer.Flush()
$OutFile = [IO.Path]::GetFullPath($OutFile)
New-Item -ItemType Directory -Force -Path (Split-Path $OutFile) | Out-Null
[IO.File]::WriteAllBytes($OutFile, $ico.ToArray())
Write-Host "Wrote $OutFile ($($sizes -join ', ') px)"
+1 -2
View File
@@ -94,8 +94,7 @@ try {
--packAuthors poli0981 `
--packVersion $Version `
--packDir $publishDir `
--mainExe OmniDeck.exe `
--icon (Join-Path $repoRoot 'src\OmniDeck.App\Assets\OmniDeck.ico')
--mainExe OmniDeck.exe
if ($LASTEXITCODE -ne 0) { throw "vpk pack failed with exit code $LASTEXITCODE" }
}
finally {
+4 -33
View File
@@ -8,9 +8,8 @@
CI runs this script on every pull request. Checks (docs/WEBAPP-CATALOG.md §1–§2):
- the file matches catalog/webapps.schema.json (types, required fields, formats, HTTPS);
- app ids and names are unique;
- every navAllowSets name an app uses exists, and every set is used;
- the startUrl host is covered by navAllow, and every popupAllow entry by navAllow or the app's
sets, matching whole DNS labels (google.com covers mail.google.com, never evilgoogle.com);
- the startUrl host and every popupAllow entry are covered by navAllow, matching whole DNS
labels (google.com covers mail.google.com, never evilgoogle.com);
- updated is a real date and not in the future.
Exits with code 1 and one line per problem when anything fails.
@@ -85,16 +84,6 @@ else {
$problems.Add("updated: $updatedText is in the future")
}
$sets = @{}
$unusedSets = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
$setsProperty = [System.Text.Json.JsonElement]::new()
if ($root.TryGetProperty('navAllowSets', [ref] $setsProperty)) {
foreach ($set in $setsProperty.EnumerateObject()) {
$sets[$set.Name] = [string[]] @($set.Value.EnumerateArray() | ForEach-Object { $_.GetString() })
[void] $unusedSets.Add($set.Name)
}
}
$ids = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
$names = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($app in $root.GetProperty('apps').EnumerateArray()) {
@@ -109,31 +98,13 @@ else {
if (-not (Test-DomainCover $startHost $navAllow)) {
$problems.Add("apps[$id]: startUrl host '$startHost' is not covered by navAllow")
}
$allowed = [System.Collections.Generic.List[string]]::new($navAllow)
$appSets = [System.Text.Json.JsonElement]::new()
if ($app.TryGetProperty('navAllowSets', [ref] $appSets)) {
foreach ($setName in @($appSets.EnumerateArray() | ForEach-Object { $_.GetString() })) {
if ($sets.ContainsKey($setName)) {
$allowed.AddRange($sets[$setName])
[void] $unusedSets.Remove($setName)
}
else {
$problems.Add("apps[$id]: navAllowSets '$setName' is not defined")
}
}
}
foreach ($popup in $app.GetProperty('popupAllow').EnumerateArray()) {
$popupDomain = $popup.GetString()
if (-not (Test-DomainCover $popupDomain $allowed.ToArray())) {
$problems.Add("apps[$id]: popupAllow '$popupDomain' is not covered by navAllow or its navAllowSets")
if (-not (Test-DomainCover $popupDomain $navAllow)) {
$problems.Add("apps[$id]: popupAllow '$popupDomain' is not covered by navAllow")
}
}
}
foreach ($unused in $unusedSets) {
$problems.Add("navAllowSets[$unused]: no app uses this set")
}
}
finally {
$document.Dispose()
+17
View File
@@ -0,0 +1,17 @@
<Project>
<!--
Spike projects only. The spike/p0 branch is pushed but never merged (docs/spikes/README.md on
main). This file deliberately does not import the repository's Directory.Build.props: throwaway
proof-of-concept code skips the analyzer set and warnings-as-errors, but keeps NuGet Audit.
-->
<PropertyGroup>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
<NuGetAudit>true</NuGetAudit>
<NuGetAuditMode>all</NuGetAuditMode>
<Product>OmniDeck spikes</Product>
</PropertyGroup>
</Project>
+15
View File
@@ -0,0 +1,15 @@
<Application
x:Class="MediaLab.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
</Application>
+3
View File
@@ -0,0 +1,3 @@
namespace MediaLab;
public partial class App : Application;
+8
View File
@@ -0,0 +1,8 @@
// The WPF SDK's implicit usings stop at System.* (and leave out System.IO because of Shapes.Path).
global using System.IO;
global using System.Windows;
global using System.Windows.Controls;
global using System.Windows.Media;
global using LibVLCSharp.Shared;
global using Path = System.IO.Path;
global using MediaPlayer = LibVLCSharp.Shared.MediaPlayer;
+69
View File
@@ -0,0 +1,69 @@
<ui:FluentWindow
x:Class="MediaLab.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vlc="clr-namespace:LibVLCSharp.WPF;assembly=LibVLCSharp.WPF"
Title="MediaLab — spike #6"
Width="1280"
Height="860"
ExtendsContentIntoTitleBar="True"
WindowBackdropType="Mica"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
<RowDefinition x:Name="LogRow" Height="170" />
</Grid.RowDefinitions>
<ui:TitleBar x:Name="TitleBarControl" Title="MediaLab — spike #6: LibVLCSharp in a FluentWindow" Grid.Row="0" />
<Grid Grid.Row="1" Background="Black">
<vlc:VideoView x:Name="Video">
<!-- Overlay content: LibVLCSharp.WPF renders it in its own window above the video HWND. -->
<Grid>
<TextBlock
Margin="12"
Padding="8,4"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Background="#CCC42B1C"
Foreground="White"
Text="WPF overlay above the video" />
<Border Padding="10,6" VerticalAlignment="Bottom" Background="#B0000000">
<DockPanel LastChildFill="True">
<ui:Button Margin="0,0,8,0" Click="OnPlayPause" Content="Play / Pause" DockPanel.Dock="Left" />
<ui:Button Margin="8,0,0,0" Click="OnFullscreenInPlace" Content="Fullscreen" DockPanel.Dock="Right" />
<TextBlock x:Name="TimeText" Margin="8,0,0,0" VerticalAlignment="Center" DockPanel.Dock="Right" Foreground="White" Text="0:00 / 0:00" />
<Slider x:Name="SeekSlider" VerticalAlignment="Center" Maximum="1" Minimum="0" PreviewMouseDown="OnSeekPressed" PreviewMouseUp="OnSeekReleased" />
</DockPanel>
</Border>
</Grid>
</vlc:VideoView>
</Grid>
<WrapPanel x:Name="LabBar" Grid.Row="2" Margin="8,6">
<Button Margin="0,0,6,0" Padding="10,2" Click="OnOpenFile" Content="Open file…" />
<Button Margin="0,0,6,0" Padding="10,2" Click="OnOpen1080" Content="Test 1080p30" />
<Button Margin="0,0,6,0" Padding="10,2" Click="OnOpen2160" Content="Test 2160p60" />
<Button Margin="0,0,12,0" Padding="10,2" Click="OnAddSubtitle" Content="Add .srt" />
<Button Margin="0,0,6,0" Padding="10,2" Click="OnFullscreenInPlace" Content="Fullscreen: in place" />
<Button Margin="0,0,6,0" Padding="10,2" Click="OnFullscreenWindow" Content="Fullscreen: own window" />
<Button Margin="0,0,6,0" Padding="10,2" Click="OnPopOut" Content="Pop out" />
<Button Margin="0,0,12,0" Padding="10,2" Click="OnHideShow" Content="Hide 3 s (tray)" />
<Button Margin="0,0,6,0" Padding="10,2" Click="OnCapture" Content="Capture screen" />
<Button Margin="0,0,6,0" Padding="10,2" Click="OnMemory" Content="Memory + stats" />
</WrapPanel>
<TextBox
x:Name="LogBox"
Grid.Row="3"
Margin="8,0,8,8"
FontFamily="Cascadia Mono, Consolas"
HorizontalScrollBarVisibility="Auto"
IsReadOnly="True"
VerticalScrollBarVisibility="Auto" />
</Grid>
</ui:FluentWindow>
+476
View File
@@ -0,0 +1,476 @@
using System.Diagnostics;
using System.Globalization;
using System.Windows.Threading;
using LibVLCSharp.WPF;
using Microsoft.Win32;
using Wpf.Ui.Controls;
namespace MediaLab;
/// <summary>
/// Spike #6 (issue #7). A FluentWindow (Mica, custom title bar) hosting LibVLCSharp's VideoView with
/// WPF overlay controls, two fullscreen strategies, a pop-out, a tray-style hide, screen captures
/// (the only way to see airspace problems) and memory/CPU readings. `--auto` runs it all unattended.
/// </summary>
public partial class MainWindow
{
private static readonly string DataRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes");
private static readonly string MediaDir = Path.Combine(DataRoot, "media");
private readonly string _outDir = Path.Combine(DataRoot, "medialab", DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture));
private readonly DispatcherTimer _ui = new() { Interval = TimeSpan.FromMilliseconds(250) };
private readonly StreamWriter _logFile;
private LibVLC? _libVlc;
private MediaPlayer? _player;
private FullscreenState? _saved;
private Window? _otherWindow;
private VideoView? _otherView;
private bool _seeking;
private int _captures;
private (TimeSpan Cpu, DateTime Wall) _cpuMark;
public MainWindow()
{
InitializeComponent();
Directory.CreateDirectory(_outDir);
_logFile = new StreamWriter(Path.Combine(_outDir, "medialab.log")) { AutoFlush = true };
Log($"MediaLab started; output in {_outDir}");
LogMemory("before libVLC");
Loaded += OnLoaded;
Closed += (_, _) =>
{
_ui.Stop();
_player?.Stop();
_player?.Dispose();
_libVlc?.Dispose();
_logFile.Dispose();
};
DpiChanged += (_, e) => Log($"DpiChanged {e.OldDpi.PixelsPerDip:0.00} → {e.NewDpi.PixelsPerDip:0.00}");
StateChanged += (_, _) => Log($"WindowState → {WindowState}");
}
private sealed record FullscreenState(
System.Windows.WindowState State, double Left, double Top, double Width, double Height, bool Topmost,
ResizeMode Resize, GridLength LogHeight, WindowCornerPreference Corners);
private void OnLoaded(object sender, RoutedEventArgs e)
{
var sw = Stopwatch.StartNew();
Core.Initialize();
_libVlc = new LibVLC(enableDebugLogs: false);
_libVlc.Log += (_, args) =>
{
if (args.Level >= LogLevel.Warning)
{
Dispatcher.InvokeAsync(() => Log($"libvlc {args.Level} [{args.Module}] {args.Message}"));
}
};
_player = new MediaPlayer(_libVlc);
_player.EncounteredError += (_, _) => Dispatcher.InvokeAsync(() => Log("MediaPlayer: EncounteredError"));
Video.MediaPlayer = _player;
Log($"libVLC {_libVlc.Version} ready in {sw.ElapsedMilliseconds} ms");
LogMemory("libVLC idle");
_ui.Tick += (_, _) => UpdateTime();
_ui.Start();
if (Environment.GetCommandLineArgs().Contains("--auto"))
{
Dispatcher.InvokeAsync(RunAutoAsync, DispatcherPriority.ContextIdle);
}
else if (Environment.GetCommandLineArgs().Contains("--auto-move"))
{
Dispatcher.InvokeAsync(RunMoveCheckAsync, DispatcherPriority.ContextIdle);
}
}
// ---- Playback ------------------------------------------------------------------------------
private void Play(string path)
{
using var media = new Media(_libVlc!, new Uri(path));
_player!.Play(media);
_cpuMark = (Process.GetCurrentProcess().TotalProcessorTime, DateTime.UtcNow);
Log($"play {Path.GetFileName(path)}");
}
private void UpdateTime()
{
if (_player is not { Length: > 0 })
{
return;
}
TimeText.Text = $"{Fmt(_player.Time)} / {Fmt(_player.Length)}";
if (!_seeking)
{
SeekSlider.Value = _player.Position;
}
static string Fmt(long ms) => TimeSpan.FromMilliseconds(ms).ToString(@"m\:ss", CultureInfo.InvariantCulture);
}
private void LogPlayback(string label)
{
var stats = _player!.Media?.Statistics;
var process = Process.GetCurrentProcess();
var (cpu0, wall0) = _cpuMark;
var cpuPercent = (process.TotalProcessorTime - cpu0).TotalMilliseconds / (DateTime.UtcNow - wall0).TotalMilliseconds / Environment.ProcessorCount * 100;
_cpuMark = (process.TotalProcessorTime, DateTime.UtcNow);
_player.Size(0, ref Unsafe.Width, ref Unsafe.Height);
Log($"{label}: playing={_player.IsPlaying} time={_player.Time} ms state={_player.State} video={Unsafe.Width}x{Unsafe.Height} "
+ $"displayed={stats?.DisplayedPictures} lost={stats?.LostPictures} cpu={cpuPercent:0.0}% of all cores");
}
// libVLC's Size() takes refs; a tiny holder keeps the call site readable.
private static class Unsafe
{
public static uint Width;
public static uint Height;
}
// ---- Fullscreen: in place (the shell window covers the monitor) -----------------------------
private void ToggleFullscreenInPlace()
{
if (_saved is { } s)
{
WindowCornerPreference = s.Corners;
Topmost = s.Topmost;
ResizeMode = s.Resize;
Left = s.Left;
Top = s.Top;
Width = s.Width;
Height = s.Height;
WindowState = s.State;
LogRow.Height = s.LogHeight;
TitleBarControl.Visibility = Visibility.Visible;
LabBar.Visibility = Visibility.Visible;
LogBox.Visibility = Visibility.Visible;
_saved = null;
Log("fullscreen in place: off");
return;
}
_saved = new FullscreenState(WindowState, Left, Top, Width, Height, Topmost, ResizeMode, LogRow.Height, WindowCornerPreference);
TitleBarControl.Visibility = Visibility.Collapsed;
LabBar.Visibility = Visibility.Collapsed;
LogBox.Visibility = Visibility.Collapsed;
LogRow.Height = new GridLength(0);
var px = Native.MonitorBounds(this);
var dpi = VisualTreeHelper.GetDpi(this);
WindowState = System.Windows.WindowState.Normal;
WindowCornerPreference = WindowCornerPreference.DoNotRound;
ResizeMode = ResizeMode.NoResize;
Topmost = true;
Left = px.X / dpi.DpiScaleX;
Top = px.Y / dpi.DpiScaleY;
Width = px.Width / dpi.DpiScaleX;
Height = px.Height / dpi.DpiScaleY;
Log($"fullscreen in place: on, monitor {px.Width}x{px.Height} px at ({px.X},{px.Y}), scale {dpi.DpiScaleX:0.00}");
}
// ---- Fullscreen in its own window, and pop-out: the player moves to another VideoView -------
private void OpenOtherWindow(bool fullscreen, bool restartVout)
{
if (_otherWindow is not null)
{
CloseOtherWindow(restartVout);
return;
}
var view = new VideoView();
var back = new Wpf.Ui.Controls.Button { Content = fullscreen ? "Exit fullscreen" : "Back to main window", Margin = new Thickness(16), HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top };
back.Click += (_, _) => CloseOtherWindow(restartVout);
view.Content = new Grid { Children = { back } };
_otherView = view;
if (fullscreen)
{
var px = Native.MonitorBounds(this);
var dpi = VisualTreeHelper.GetDpi(this);
_otherWindow = new Window
{
WindowStyle = WindowStyle.None,
ResizeMode = ResizeMode.NoResize,
Topmost = true,
ShowInTaskbar = false,
Background = Brushes.Black,
Left = px.X / dpi.DpiScaleX,
Top = px.Y / dpi.DpiScaleY,
Width = px.Width / dpi.DpiScaleX,
Height = px.Height / dpi.DpiScaleY,
Content = view,
};
}
else
{
_otherWindow = new FluentWindow
{
Title = "MediaLab pop-out",
Width = 800,
Height = 480,
ExtendsContentIntoTitleBar = true,
WindowBackdropType = WindowBackdropType.Mica,
Content = new Grid
{
RowDefinitions = { new RowDefinition { Height = GridLength.Auto }, new RowDefinition() },
Children = { new TitleBar { Title = "MediaLab pop-out" }, view },
},
};
Grid.SetRow(view, 1);
}
_otherWindow.KeyDown += (_, e) =>
{
if (e.Key == System.Windows.Input.Key.Escape)
{
CloseOtherWindow(restartVout);
}
};
view.Loaded += (_, _) => MovePlayer(Video, view, restartVout);
_otherWindow.Show();
Log($"{(fullscreen ? "fullscreen window" : "pop-out")} opened (restart vout: {restartVout})");
}
private void CloseOtherWindow(bool restartVout)
{
if (_otherWindow is null || _otherView is null)
{
return;
}
MovePlayer(_otherView, Video, restartVout);
_otherWindow.Close();
_otherWindow = null;
_otherView = null;
Log("other window closed; player back in the main window");
}
private void MovePlayer(VideoView from, VideoView to, bool restartVout)
{
var time = _player!.Time;
from.MediaPlayer = null;
to.MediaPlayer = _player;
if (restartVout && _player.VideoTrack is var track and >= 0)
{
// libVLC 3 keeps drawing into the window it started with; re-selecting the video track
// makes it create a new video output on the new HWND. The decoder then restarts
// mid-GOP, so seek to the current time to resume from a keyframe (with --seek-on-move).
_player.SetVideoTrack(-1);
_player.SetVideoTrack(track);
if (Environment.GetCommandLineArgs().Contains("--seek-on-move"))
{
_player.Time = time;
}
}
Log($"player moved at {time} ms (restart vout: {restartVout}); playing={_player.IsPlaying}");
}
// ---- Captures and readings -----------------------------------------------------------------
private string Capture(string label, Window? window = null)
{
var path = Path.Combine(_outDir, $"{++_captures:00}-{label}.png");
Native.CaptureScreen(Native.WindowBounds(window ?? this), path);
Log($"captured {Path.GetFileName(path)}");
return path;
}
private void LogMemory(string label)
{
using var p = Process.GetCurrentProcess();
Log($"memory {label}: private commit {p.PrivateMemorySize64 / 1048576.0:F0} MB, working set {p.WorkingSet64 / 1048576.0:F0} MB");
}
private void Log(string line)
{
var stamped = $"{DateTime.Now:HH:mm:ss.fff} {line}";
_logFile.WriteLine(stamped);
LogBox.AppendText(stamped + Environment.NewLine);
LogBox.ScrollToEnd();
}
// ---- Unattended run: `MediaLab.exe --auto` -----------------------------------------------------
// `--auto-move`: only the player hand-over to another window, captured at 0.5 s and 2 s.
private async Task RunMoveCheckAsync()
{
try
{
await Task.Delay(1000);
Play(Path.Combine(MediaDir, "test-1080p30.mp4"));
await Task.Delay(4500);
OpenOtherWindow(fullscreen: true, restartVout: true);
await Task.Delay(500);
Capture("move-0.5s", _otherWindow);
await Task.Delay(1500);
Capture("move-2s", _otherWindow);
LogPlayback("after the move");
CloseOtherWindow(restartVout: true);
await Task.Delay(500);
Capture("move-back-0.5s");
}
catch (Exception ex)
{
Log($"MOVE FAILED: {ex}");
}
finally
{
await Task.Delay(500);
Close();
}
}
private async Task RunAutoAsync()
{
var media1080 = Path.Combine(MediaDir, "test-1080p30.mp4");
var media2160 = Path.Combine(MediaDir, "test-2160p60.mp4");
try
{
await Task.Delay(1000);
Play(media1080);
await Task.Delay(4000);
LogPlayback("1080p30 in the window");
LogMemory("1080p30 playing");
Capture("1080p-window");
_player!.AddSlave(MediaSlaveType.Subtitle, new Uri(Path.ChangeExtension(media1080, ".srt")).AbsoluteUri, true);
await Task.Delay(2500);
Capture("1080p-subtitle");
ToggleFullscreenInPlace();
await Task.Delay(2500);
LogPlayback("fullscreen in place");
Capture("fullscreen-in-place");
ToggleFullscreenInPlace();
await Task.Delay(2000);
Capture("back-from-fullscreen");
foreach (var restart in new[] { false, true })
{
OpenOtherWindow(fullscreen: true, restartVout: restart);
await Task.Delay(3000);
LogPlayback($"own fullscreen window, restart={restart}");
Capture($"own-window-restart-{restart}", _otherWindow);
CloseOtherWindow(restart);
await Task.Delay(2500);
LogPlayback($"back in the main window, restart={restart}");
Capture($"back-from-own-window-restart-{restart}");
}
OpenOtherWindow(fullscreen: false, restartVout: true);
await Task.Delay(3000);
Capture("popout", _otherWindow);
CloseOtherWindow(restartVout: true);
await Task.Delay(2000);
Hide();
await Task.Delay(2000);
Show();
Activate();
await Task.Delay(2000);
LogPlayback("after hide/show");
Capture("after-hide-show");
Play(media2160);
await Task.Delay(6000);
LogPlayback("2160p60 in the window");
LogMemory("2160p60 playing");
Capture("2160p60-window");
_player.Stop();
await Task.Delay(1500);
LogMemory("stopped");
}
catch (Exception ex)
{
Log($"AUTO FAILED: {ex}");
}
finally
{
await Task.Delay(500);
Close();
}
}
// ---- UI handlers ---------------------------------------------------------------------------
private void OnPlayPause(object sender, RoutedEventArgs e)
{
if (_player is null)
{
return;
}
if (_player.IsPlaying)
{
_player.Pause();
}
else
{
_player.Play();
}
}
private void OnSeekPressed(object sender, System.Windows.Input.MouseButtonEventArgs e) => _seeking = true;
private void OnSeekReleased(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
_seeking = false;
if (_player is not null)
{
_player.Position = (float)SeekSlider.Value;
}
}
private void OnOpenFile(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = "Media|*.mp4;*.mkv;*.webm;*.avi;*.mov;*.mp3;*.flac;*.m4a|All files|*.*" };
if (dialog.ShowDialog(this) == true)
{
Play(dialog.FileName);
}
}
private void OnOpen1080(object sender, RoutedEventArgs e) => Play(Path.Combine(MediaDir, "test-1080p30.mp4"));
private void OnOpen2160(object sender, RoutedEventArgs e) => Play(Path.Combine(MediaDir, "test-2160p60.mp4"));
private void OnAddSubtitle(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog { Filter = "Subtitles|*.srt;*.ass;*.ssa;*.vtt", InitialDirectory = MediaDir };
if (dialog.ShowDialog(this) == true)
{
_player?.AddSlave(MediaSlaveType.Subtitle, new Uri(dialog.FileName).AbsoluteUri, true);
Log($"subtitle {Path.GetFileName(dialog.FileName)}");
}
}
private void OnFullscreenInPlace(object sender, RoutedEventArgs e) => ToggleFullscreenInPlace();
private void OnFullscreenWindow(object sender, RoutedEventArgs e) => OpenOtherWindow(fullscreen: true, restartVout: true);
private void OnPopOut(object sender, RoutedEventArgs e) => OpenOtherWindow(fullscreen: false, restartVout: true);
private async void OnHideShow(object sender, RoutedEventArgs e)
{
Hide();
await Task.Delay(3000);
Show();
Activate();
LogPlayback("after hide/show");
}
private void OnCapture(object sender, RoutedEventArgs e) => Capture("manual", _otherWindow);
private void OnMemory(object sender, RoutedEventArgs e)
{
LogMemory("now");
if (_player is not null)
{
LogPlayback("now");
}
}
}
+32
View File
@@ -0,0 +1,32 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Spike #6 (issue #7): LibVLCSharp's VideoView inside a WPF-UI FluentWindow: airspace, overlay
controls, fullscreen, pop-out, and what libVLC adds to the install size. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<!-- x64 only, like OmniDeck: keeps the win-x86 libVLC copy out of the output. -->
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<!-- The libVLC package picks architectures from $(Platform); AnyCPU would copy all three. -->
<VlcWindowsX86Enabled>false</VlcWindowsX86Enabled>
<VlcWindowsArm64Enabled>false</VlcWindowsArm64Enabled>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="LibVLCSharp.WPF" Version="3.10.2" />
<PackageReference Include="VideoLAN.LibVLC.Windows" Version="3.0.24" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup>
<!-- `-p:TrimVlc=true`: the plugin set SPEC §3.6 asks for (codecs, demux, audio/video output,
subtitles), to measure the size the installer would really carry. -->
<ItemGroup Condition="'$(TrimVlc)' == 'true'">
<VlcWindowsX64IncludeFiles Include="libvlc.dll;libvlccore.dll" />
<VlcWindowsX64IncludeFiles Include="plugins\access\%2A;plugins\audio_filter\%2A;plugins\audio_mixer\%2A;plugins\audio_output\%2A" />
<VlcWindowsX64IncludeFiles Include="plugins\codec\%2A;plugins\demux\%2A;plugins\packetizer\%2A;plugins\stream_filter\%2A" />
<VlcWindowsX64IncludeFiles Include="plugins\text_renderer\%2A;plugins\spu\%2A;plugins\video_chroma\%2A;plugins\video_filter\%2A;plugins\video_output\%2A;plugins\misc\%2A" />
</ItemGroup>
</Project>
+117
View File
@@ -0,0 +1,117 @@
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
namespace MediaLab;
/// <summary>Monitor bounds for fullscreen, and screen captures that show what the user really sees.</summary>
internal static class Native
{
/// <summary>The bounds, in device pixels, of the monitor the window is mostly on.</summary>
public static Int32Rect MonitorBounds(Window window)
{
var monitor = MonitorFromWindow(new WindowInteropHelper(window).Handle, MonitorDefaultToNearest);
var info = new MonitorInfo { Size = Marshal.SizeOf<MonitorInfo>() };
GetMonitorInfo(monitor, ref info);
return new Int32Rect(info.Monitor.Left, info.Monitor.Top, info.Monitor.Right - info.Monitor.Left, info.Monitor.Bottom - info.Monitor.Top);
}
/// <summary>The window's on-screen rectangle in device pixels (DWM extended frame bounds).</summary>
public static Int32Rect WindowBounds(Window window)
{
var hwnd = new WindowInteropHelper(window).Handle;
if (DwmGetWindowAttribute(hwnd, DwmwaExtendedFrameBounds, out var r, Marshal.SizeOf<Rect>()) != 0)
{
GetWindowRect(hwnd, out r);
}
return new Int32Rect(r.Left, r.Top, r.Right - r.Left, r.Bottom - r.Top);
}
/// <summary>
/// Copies a screen rectangle (composited by DWM, layered windows included) to a PNG. The video HWND
/// and LibVLCSharp's overlay window are separate windows, so only a screen capture shows airspace.
/// </summary>
public static void CaptureScreen(Int32Rect area, string pngPath)
{
var screenDc = GetDC(IntPtr.Zero);
var memDc = CreateCompatibleDC(screenDc);
var bitmap = CreateCompatibleBitmap(screenDc, area.Width, area.Height);
var old = SelectObject(memDc, bitmap);
try
{
BitBlt(memDc, 0, 0, area.Width, area.Height, screenDc, area.X, area.Y, SrcCopy | CaptureBlt);
var source = Imaging.CreateBitmapSourceFromHBitmap(bitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
var encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
using var file = File.Create(pngPath);
encoder.Save(file);
}
finally
{
SelectObject(memDc, old);
DeleteObject(bitmap);
DeleteDC(memDc);
_ = ReleaseDC(IntPtr.Zero, screenDc);
}
}
private const uint MonitorDefaultToNearest = 2;
private const int DwmwaExtendedFrameBounds = 9;
private const uint SrcCopy = 0x00CC0020;
private const uint CaptureBlt = 0x40000000;
[StructLayout(LayoutKind.Sequential)]
private struct Rect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct MonitorInfo
{
public int Size;
public Rect Monitor;
public Rect Work;
public uint Flags;
}
[DllImport("user32.dll")]
private static extern IntPtr MonitorFromWindow(IntPtr hwnd, uint flags);
[DllImport("user32.dll")]
private static extern bool GetMonitorInfo(IntPtr monitor, ref MonitorInfo info);
[DllImport("user32.dll")]
private static extern bool GetWindowRect(IntPtr hwnd, out Rect rect);
[DllImport("dwmapi.dll")]
private static extern int DwmGetWindowAttribute(IntPtr hwnd, int attribute, out Rect value, int size);
[DllImport("user32.dll")]
private static extern IntPtr GetDC(IntPtr hwnd);
[DllImport("user32.dll")]
private static extern int ReleaseDC(IntPtr hwnd, IntPtr dc);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleDC(IntPtr dc);
[DllImport("gdi32.dll")]
private static extern IntPtr CreateCompatibleBitmap(IntPtr dc, int width, int height);
[DllImport("gdi32.dll")]
private static extern IntPtr SelectObject(IntPtr dc, IntPtr obj);
[DllImport("gdi32.dll")]
private static extern bool BitBlt(IntPtr dest, int x, int y, int w, int h, IntPtr src, int sx, int sy, uint rop);
[DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr obj);
[DllImport("gdi32.dll")]
private static extern bool DeleteDC(IntPtr dc);
}
+6
View File
@@ -0,0 +1,6 @@
<Solution>
<Project Path="MediaLab/MediaLab.csproj" />
<Project Path="ProviderProbe/ProviderProbe.csproj" />
<Project Path="ThemeLab/ThemeLab.csproj" />
<Project Path="WebLab/WebLab.csproj" />
</Solution>
+280
View File
@@ -0,0 +1,280 @@
// Spike #7 (issue #8): probe stock data providers and keep the raw responses for freezing models.
//
// dotnet run --project spikes/ProviderProbe -- stooq
// dotnet run --project spikes/ProviderProbe -- twelvedata
//
// Output goes to %LocalAppData%\OmniDeck.Spikes\providers\. Rules (docs/spikes/README.md): single
// plain requests, no bot-challenge solving. The Twelve Data key comes from OD_TWELVEDATA_KEY, is
// sent in the Authorization header (never in a URL) and is never printed or written to disk.
using System.Diagnostics;
using System.Text;
using System.Text.Json;
var outDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes", "providers");
Directory.CreateDirectory(outDir);
var stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss");
using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
http.DefaultRequestHeaders.UserAgent.ParseAdd("OmniDeck-Spike/0.1 (+https://github.com/poli0981/OmniDeck)");
var rows = new List<string>();
switch (args.FirstOrDefault())
{
case "stooq":
await ProbeAsync("stooq-history", "https://stooq.com/q/d/l/?s=aapl.us&i=d", apiKey: null);
await ProbeAsync("stooq-quote", "https://stooq.com/q/l/?s=aapl.us&f=sd2t2ohlcv&h&e=csv", apiKey: null);
break;
case "twelvedata":
var key = Environment.GetEnvironmentVariable("OD_TWELVEDATA_KEY");
if (string.IsNullOrWhiteSpace(key))
{
Console.Error.WriteLine("Set OD_TWELVEDATA_KEY (a free key from https://twelvedata.com/pricing) first.");
return 2;
}
// Free plan: 8 credits per minute. Calls are paced 10 s apart so even the 3-symbol batch
// (3 credits) never pushes a minute over the limit.
(string Name, string Path)[] calls =
[
("quote-aapl", "quote?symbol=AAPL"),
("quote-batch3", "quote?symbol=AAPL,MSFT,SPY"),
("ts-1m-daily", "time_series?symbol=AAPL&interval=1day&outputsize=22"),
("ts-6m-daily", "time_series?symbol=AAPL&interval=1day&outputsize=126"),
("ts-1y-daily", "time_series?symbol=AAPL&interval=1day&outputsize=252"),
("ts-5y-weekly", "time_series?symbol=AAPL&interval=1week&outputsize=261"),
("search-sap", "symbol_search?symbol=SAP"),
("quote-sap-xetr", "quote?symbol=SAP&exchange=XETR"),
("quote-vod-lse", "quote?symbol=VOD&exchange=LSE"),
("quote-asml-euronext", "quote?symbol=ASML&exchange=Euronext"),
("quote-spx-index", "quote?symbol=SPX"),
("api-usage", "api_usage"),
];
for (var i = 0; i < calls.Length; i++)
{
if (i > 0)
{
await Task.Delay(TimeSpan.FromSeconds(10));
}
await ProbeAsync($"td-{calls[i].Name}", $"https://api.twelvedata.com/{calls[i].Path}", key);
}
break;
case "shapes":
// P3 addendum to docs/spikes/07-providers.md: the answers OmniDeck's parser has not seen from a
// real key. Prints structure only (HTTP status, shape, field names, error codes and messages,
// which credit headers came back), never a figure or the key, and saves nothing.
// dotnet run --project spikes/ProviderProbe -- shapes [429]
var shapesKey = Environment.GetEnvironmentVariable("OD_TWELVEDATA_KEY");
if (string.IsNullOrWhiteSpace(shapesKey))
{
Console.Error.WriteLine("Set OD_TWELVEDATA_KEY first; the key is only sent to Twelve Data, never printed.");
return 2;
}
// About 10 credits, paced 10 s apart to stay under 8 per minute.
(string Name, string Path)[] shapes =
[
("batch-with-unknown", "quote?symbol=AAPL,ZZZZQX"),
("batch-with-plan-gated", "quote?symbol=AAPL,SAP:XETR"),
("mic-code-form", "quote?symbol=SAP&mic_code=XETR"),
("single-unknown", "quote?symbol=ZZZZQX"),
("trailing-comma", "quote?symbol=AAPL,"),
("dotted-symbol", "quote?symbol=BRK.B"),
("series-unknown", "time_series?symbol=ZZZZQX&interval=1day&outputsize=5"),
];
for (var i = 0; i < shapes.Length; i++)
{
if (i > 0)
{
await Task.Delay(TimeSpan.FromSeconds(10));
}
await ShapeAsync(shapes[i].Name, $"https://api.twelvedata.com/{shapes[i].Path}", shapesKey);
}
if (args.Contains("429"))
{
// Nine more credits at once, to see what going over the minute's eight looks like.
Console.WriteLine("Waiting a minute, then nine quotes at once...");
await Task.Delay(TimeSpan.FromSeconds(61));
for (var i = 0; i < 9; i++)
{
await ShapeAsync($"burst-{i + 1}", "https://api.twelvedata.com/quote?symbol=AAPL", shapesKey);
}
}
return 0;
case "verify-models":
// Deserializes the newest saved Twelve Data responses with the frozen models.
string Latest(string name) => Directory.GetFiles(outDir, $"*-td-{name}.json").Max()!;
T Read<T>(string name) => JsonSerializer.Deserialize<T>(File.ReadAllText(Latest(name)), TwelveData.Json)!;
var quote = Read<TdQuote>("quote-aapl");
Console.WriteLine($"quote: {quote.Symbol} {quote.Close} {quote.Currency} ({quote.PercentChange:+0.00;-0.00}%), 52w {quote.FiftyTwoWeek?.Low}-{quote.FiftyTwoWeek?.High}, market open {quote.IsMarketOpen}");
var batch = Read<Dictionary<string, TdQuote>>("quote-batch3");
Console.WriteLine($"batch: {string.Join(", ", batch.Select(kv => $"{kv.Key} {kv.Value.Close}"))}");
foreach (var range in new[] { "ts-1m-daily", "ts-6m-daily", "ts-1y-daily", "ts-5y-weekly" })
{
var series = Read<TdTimeSeries>(range);
Console.WriteLine($"{range}: {series.Values.Count} bars {series.Meta.Interval}, {series.Values[^1].Datetime} -> {series.Values[0].Datetime}, last close {series.Values[0].Close}, tz {series.Meta.ExchangeTimezone}");
}
var search = Read<TdSymbolSearch>("search-sap-showplan");
Console.WriteLine($"search: {string.Join("; ", search.Data.Take(4).Select(l => $"{l.Symbol}@{l.MicCode} {l.InstrumentType} needs {l.Access?.Plan}"))}");
var usage = Read<TdApiUsage>("api-usage");
Console.WriteLine($"usage: {usage.DailyUsage}/{usage.PlanDailyLimit} today, {usage.CurrentUsage}/{usage.PlanLimit} this minute, plan {usage.PlanCategory}");
var error = Read<TdError>("quote-sap-xetr");
Console.WriteLine($"error: {error.Code} {error.Message[..60]}...");
return 0;
default:
Console.Error.WriteLine("usage: ProviderProbe stooq | twelvedata | shapes [429] | verify-models");
return 1;
}
var summary = Path.Combine(outDir, $"{stamp}-{args[0]}-summary.md");
await File.WriteAllLinesAsync(summary,
[
"| Call | HTTP | Content-Type | ms | Credits used/left | Verdict |",
"|---|---|---|---|---|---|",
.. rows,
]);
Console.WriteLine($"\nSummary: {summary}");
return 0;
async Task ProbeAsync(string name, string url, string? apiKey)
{
using var request = new HttpRequestMessage(HttpMethod.Get, url);
if (apiKey is not null)
{
request.Headers.TryAddWithoutValidation("Authorization", $"apikey {apiKey}");
}
var sw = Stopwatch.StartNew();
using var response = await http.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
sw.Stop();
var contentType = response.Content.Headers.ContentType?.ToString() ?? "-";
var credits = Header(response, "api-credits-used") is { } used ? $"{used}/{Header(response, "api-credits-left")}" : "-";
var verdict = Classify(body);
var ext = contentType.Contains("json", StringComparison.OrdinalIgnoreCase) ? "json"
: contentType.Contains("csv", StringComparison.OrdinalIgnoreCase) ? "csv" : "txt";
await File.WriteAllTextAsync(Path.Combine(outDir, $"{stamp}-{name}.{ext}"), body, Encoding.UTF8);
rows.Add($"| `{name}` | {(int)response.StatusCode} | {contentType} | {sw.ElapsedMilliseconds} | {credits} | {verdict} |");
Console.WriteLine($"{name,-22} {(int)response.StatusCode} {sw.ElapsedMilliseconds,5} ms {credits,-9} {verdict}");
}
async Task ShapeAsync(string name, string url, string apiKey)
{
using var request = new HttpRequestMessage(HttpMethod.Get, url);
request.Headers.TryAddWithoutValidation("Authorization", $"apikey {apiKey}");
using var response = await http.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
var credits = string.Join(", ", new[] { "api-credits-used", "api-credits-left" }.Where(response.Headers.Contains));
Console.WriteLine($"{name,-24} HTTP {(int)response.StatusCode} credit headers: {(credits.Length == 0 ? "none" : credits)}");
Console.WriteLine(" " + Describe(body));
}
static string Describe(string body)
{
try
{
using var document = JsonDocument.Parse(body);
return Shape(document.RootElement);
}
catch (JsonException)
{
return "not JSON";
}
}
static string Shape(JsonElement element)
{
if (element.ValueKind != JsonValueKind.Object)
{
return element.ValueKind.ToString();
}
if (ErrorOf(element) is { } error)
{
return error;
}
static string Fields(JsonElement value) => string.Join(",", value.EnumerateObject().Select(p => p.Name).Order(StringComparer.Ordinal));
if (element.TryGetProperty("symbol", out _))
{
return "flat quote; fields: " + Fields(element);
}
if (element.TryGetProperty("values", out _))
{
return "series; fields: " + Fields(element);
}
return "keyed by symbol: " + string.Join("; ", element.EnumerateObject().Select(p => $"{p.Name} => {(ErrorOf(p.Value) ?? (p.Value.ValueKind == JsonValueKind.Object ? "quote" : p.Value.ValueKind.ToString()))}"));
}
static string? ErrorOf(JsonElement element) =>
element.ValueKind == JsonValueKind.Object && element.TryGetProperty("status", out var status) && status.ValueKind == JsonValueKind.String && status.GetString() == "error"
? $"error code={(element.TryGetProperty("code", out var code) ? code.ToString() : "?")} message=\"{(element.TryGetProperty("message", out var message) ? message.GetString() : "")}\""
: null;
static string? Header(HttpResponseMessage response, string name) =>
response.Headers.TryGetValues(name, out var values) ? values.FirstOrDefault() : null;
static string Classify(string body)
{
var head = body.Length > 600 ? body[..600] : body;
if (head.StartsWith("Date,", StringComparison.Ordinal) || head.StartsWith("Symbol,", StringComparison.Ordinal))
{
return "CSV data";
}
if (head.Contains("verify your browser", StringComparison.OrdinalIgnoreCase))
{
return "browser check (JavaScript proof of work)";
}
if (head.Contains("apikey", StringComparison.OrdinalIgnoreCase) && !head.TrimStart().StartsWith('{'))
{
return "API key required";
}
if (head.Contains("Exceeded the daily hits limit", StringComparison.OrdinalIgnoreCase))
{
return "daily limit";
}
if (head.TrimStart().StartsWith('{') || head.TrimStart().StartsWith('['))
{
try
{
using var doc = JsonDocument.Parse(body);
if (doc.RootElement.ValueKind == JsonValueKind.Object
&& doc.RootElement.TryGetProperty("status", out var status) && status.GetString() == "error")
{
var code = doc.RootElement.TryGetProperty("code", out var c) ? c.ToString() : "?";
var message = doc.RootElement.TryGetProperty("message", out var m) ? m.GetString() : "";
return $"error {code}: {Truncate(message, 90)}";
}
return "JSON data";
}
catch (JsonException)
{
return "malformed JSON";
}
}
return $"other: {Truncate(head.ReplaceLineEndings(" "), 60)}";
}
static string Truncate(string? text, int max) =>
text is null ? "" : text.Length <= max ? text.Replace("|", "\\|") : text[..max].Replace("|", "\\|") + "…";
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Spike #7 (issue #8): stock data providers. -->
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
</PropertyGroup>
</Project>
+44
View File
@@ -0,0 +1,44 @@
using System.Text.Json;
using System.Text.Json.Serialization;
// The Twelve Data response shapes frozen by spike #7 (docs/spikes/07-providers.md). Numbers arrive as
// JSON strings, so the options read numbers from strings; names are snake_case.
internal static class TwelveData
{
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web)
{
PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
};
}
/// <summary>GET /quote. The batch form (symbol=A,B,C) returns an object keyed by symbol.</summary>
internal sealed record TdQuote(
string Symbol, string Name, string Exchange, string MicCode, string Currency, string Datetime, long Timestamp,
long? LastQuoteAt, decimal Open, decimal High, decimal Low, decimal Close, long? Volume, decimal PreviousClose,
decimal Change, decimal PercentChange, bool IsMarketOpen, TdFiftyTwoWeek? FiftyTwoWeek);
internal sealed record TdFiftyTwoWeek(decimal Low, decimal High, string Range);
/// <summary>GET /time_series. Values are newest first; Datetime is a date for 1day/1week bars.</summary>
internal sealed record TdTimeSeries(TdSeriesMeta Meta, IReadOnlyList<TdBar> Values, string Status);
internal sealed record TdSeriesMeta(
string Symbol, string Interval, string Currency, string ExchangeTimezone, string Exchange, string MicCode, string Type);
internal sealed record TdBar(string Datetime, decimal Open, decimal High, decimal Low, decimal Close, long? Volume);
/// <summary>GET /symbol_search (free). With show_plan=true each listing carries the plan it needs.</summary>
internal sealed record TdSymbolSearch(IReadOnlyList<TdListing> Data, string Status);
internal sealed record TdListing(
string Symbol, string InstrumentName, string Exchange, string MicCode, string ExchangeTimezone,
string InstrumentType, string Country, string Currency, TdAccess? Access);
internal sealed record TdAccess(string Global, string Plan);
/// <summary>GET /api_usage (1 credit).</summary>
internal sealed record TdApiUsage(string Timestamp, int CurrentUsage, int PlanLimit, int DailyUsage, int PlanDailyLimit, string PlanCategory);
/// <summary>Any error; the HTTP status is mirrored in Code (401 no key, 404 symbol/plan, 429 credits).</summary>
internal sealed record TdError(int Code, string Message, string Status);
+33
View File
@@ -0,0 +1,33 @@
# OmniDeck P0 spike harnesses
This is the `spike/p0` branch: throwaway proof-of-concept code for the P0 spikes. It is pushed but
**never merged**. Notes and decisions live on `main` in `docs/spikes/`, and each note names the commit
of this branch that it measured.
- Build: `dotnet build spikes/OmniDeck.Spikes.slnx`. The solution is separate from `OmniDeck.slnx`,
and `spikes/Directory.Build.props` replaces the repository's analyzer set.
- Data: `%LocalAppData%\OmniDeck.Spikes\` (WebView2 profiles, CSV samples, raw responses, logs). Never
in the working tree.
- Secrets: environment variables only.
| Harness | Spikes | Run |
|---|---|---|
| `ProviderProbe` | #7 providers | `dotnet run --project spikes/ProviderProbe -- stooq` · `-- twelvedata` (needs `OD_TWELVEDATA_KEY`) · `-- verify-models` (frozen models vs. saved responses) |
| `ThemeLab` | #5 preset swap | `dotnet run --project spikes/ThemeLab` (interactive) · `-- --auto` (measurements → `theme\*.log`) |
| `WebLab` | #1 DRM · #2 sign-in · #3 memory · #4 CDP | `dotnet run --project spikes/WebLab` (interactive) · `-- --auto` (EME, CDP and a short ladder) · `-- --wv2-args=...` (browser arguments) |
WebLab keeps WebView2 profiles in `%LocalAppData%\OmniDeck.Spikes\WebView2` (one profile per catalog
`profile` group, so sign-ins persist across runs), memory samples in `memory\*.csv` (one row per process
per 2 s sample, with the current phase) and its log in `weblab\*.log`. Sign-ins are done by hand in its
window; the lab never touches the user agent.
| `MediaLab` | #6 LibVLCSharp | `dotnet run --project spikes/MediaLab` (interactive) · `-- --auto` · `-- --auto-move --seek-on-move` · `dotnet build spikes/MediaLab -c Release -p:TrimVlc=true` (SPEC plugin set) |
MediaLab plays local test clips from `%LocalAppData%\OmniDeck.Spikes\media\`, generated with ffmpeg
(nothing is downloaded):
```powershell
ffmpeg -f lavfi -i "testsrc=size=1920x1080:rate=30" -f lavfi -i "sine=frequency=440" -t 60 -c:v libx264 -pix_fmt yuv420p -c:a aac -shortest test-1080p30.mp4
ffmpeg -f lavfi -i "testsrc2=size=3840x2160:rate=60" -f lavfi -i "sine=frequency=660" -t 20 -c:v libx264 -preset ultrafast -pix_fmt yuv420p -c:a aac -shortest test-2160p60.mp4
```
Screen captures and the log land in `medialab\<timestamp>\`.
+38
View File
@@ -0,0 +1,38 @@
<Application
x:Class="ThemeLab.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
StartupUri="MainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
<!-- The preset layer is appended (and later replaced in place) by PresetEngine. -->
</ResourceDictionary.MergedDictionaries>
<!--
Od styles: BasedOn the WPF-UI defaults, but every size comes from an Od.* token through
DynamicResource. WPF-UI 4.3 sets Padding from StaticResource ButtonPadding, which a preset
swap cannot change; these setters can.
-->
<Style
x:Key="OdButtonStyle"
BasedOn="{StaticResource DefaultUiButtonStyle}"
TargetType="{x:Type ui:Button}">
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Control}" />
<Setter Property="MinHeight" Value="{DynamicResource Od.HitTarget.Min}" />
<Setter Property="FontSize" Value="{DynamicResource Od.Font.Body}" />
</Style>
<Style
x:Key="OdTextBoxStyle"
BasedOn="{StaticResource DefaultUiTextBoxStyle}"
TargetType="{x:Type ui:TextBox}">
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Control}" />
<Setter Property="MinHeight" Value="{DynamicResource Od.HitTarget.Min}" />
<Setter Property="FontSize" Value="{DynamicResource Od.Font.Body}" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
+11
View File
@@ -0,0 +1,11 @@
namespace ThemeLab;
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
// The preset layer must exist before the first window resolves its DynamicResource tokens.
PresetEngine.Apply(PresetEngine.Build(Preset.Standard, textScale: 1.0));
base.OnStartup(e);
}
}
+4
View File
@@ -0,0 +1,4 @@
// The WPF SDK's implicit usings stop at System.*; the WPF namespaces this lab uses everywhere.
global using System.Windows;
global using System.Windows.Controls;
global using System.Windows.Media;
+124
View File
@@ -0,0 +1,124 @@
<ui:FluentWindow
x:Class="ThemeLab.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ThemeLab"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="ThemeLab — spike #5"
Width="1320"
Height="900"
ExtendsContentIntoTitleBar="True"
WindowBackdropType="Mica"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="230" />
</Grid.RowDefinitions>
<ui:TitleBar Title="ThemeLab — spike #5: runtime preset swap" Grid.Row="0" />
<Grid Grid.Row="1" Margin="12,0,12,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="300" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<!-- Lab controls use fixed defaults on purpose: they must not move while presets swap. -->
<StackPanel Grid.Column="0" Margin="0,0,12,0">
<TextBlock FontWeight="SemiBold" Text="Preset" />
<RadioButton Checked="OnPresetChecked" Content="Dynamic" GroupName="preset" Tag="Dynamic" />
<RadioButton Checked="OnPresetChecked" Content="Standard" GroupName="preset" IsChecked="True" Tag="Standard" />
<RadioButton Checked="OnPresetChecked" Content="Comfort" GroupName="preset" Tag="Comfort" />
<TextBlock Margin="0,12,0,0" FontWeight="SemiBold" Text="Theme (independent axis)" />
<RadioButton Checked="OnThemeChecked" Content="Dark" GroupName="theme" IsChecked="True" Tag="Dark" />
<RadioButton Checked="OnThemeChecked" Content="Light" GroupName="theme" Tag="Light" />
<RadioButton Checked="OnThemeChecked" Content="Follow Windows" GroupName="theme" Tag="System" />
<CheckBox x:Name="ApplyTextScale" Margin="0,12,0,0" Checked="OnTextScaleToggled" Content="Apply Windows text size" Unchecked="OnTextScaleToggled" />
<TextBlock x:Name="TextScaleInfo" TextWrapping="Wrap" />
<Button Margin="0,12,0,0" HorizontalAlignment="Stretch" Click="OnBenchmark" Content="Benchmark: swap presets ×30" />
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnStress" Content="Stress: add 300 controls" />
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnProbe" Content="Probe controls under each preset" />
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnFrozenStoryboardTest" Content="Test DynamicResource in a style storyboard" />
<Button Margin="0,6,0,0" HorizontalAlignment="Stretch" Click="OnCopyLog" Content="Copy log" />
</StackPanel>
<!-- Sample surface: everything here consumes Od.* tokens or WPF-UI defaults. -->
<ScrollViewer Grid.Column="1" VerticalScrollBarVisibility="Auto">
<StackPanel>
<TextBlock FontSize="{DynamicResource Od.Font.H1}" FontWeight="SemiBold" Text="Heading 1 (Od.Font.H1)" />
<TextBlock FontSize="{DynamicResource Od.Font.H2}" FontWeight="SemiBold" Text="Heading 2 (Od.Font.H2)" />
<TextBlock
Margin="{DynamicResource Od.Margin.Item}"
FontSize="{DynamicResource Od.Font.Body}"
Text="Body text (Od.Font.Body). The quick brown fox jumps over the lazy dog; Đồng hồ, máy tính, thời tiết; 時計と電卓。"
TextWrapping="Wrap" />
<ui:Card x:Name="ProbeCard" Margin="{DynamicResource Od.Margin.Item}">
<StackPanel>
<TextBlock FontSize="{DynamicResource Od.Font.Caption}" Text="WPF-UI defaults (no Od style): Padding comes from StaticResource ButtonPadding" />
<WrapPanel Margin="0,8,0,0">
<ui:Button x:Name="ProbeDefaultButton" Margin="0,0,8,8" Content="Default ui:Button" />
<ui:Button Margin="0,0,8,8" Appearance="Primary" Content="Primary" />
<ui:TextBox x:Name="ProbeDefaultTextBox" Width="220" Margin="0,0,8,8" PlaceholderText="Default ui:TextBox" />
<ui:ToggleSwitch Margin="0,0,8,8" Content="Toggle" />
<ComboBox Width="160" Margin="0,0,8,8" SelectedIndex="0">
<ComboBoxItem Content="ComboBox" />
<ComboBoxItem Content="Second" />
</ComboBox>
<ui:NumberBox Width="160" Margin="0,0,8,8" Value="5" />
</WrapPanel>
</StackPanel>
</ui:Card>
<ui:Card Margin="{DynamicResource Od.Margin.Item}">
<StackPanel>
<TextBlock FontSize="{DynamicResource Od.Font.Caption}" Text="Od styles: BasedOn WPF-UI, sizes from Od.* via DynamicResource" />
<WrapPanel Margin="0,8,0,0">
<ui:Button x:Name="ProbeOdButton" Margin="0,0,8,8" Content="Od ui:Button" Style="{StaticResource OdButtonStyle}" />
<ui:TextBox x:Name="ProbeOdTextBox" Width="220" Margin="0,0,8,8" PlaceholderText="Od ui:TextBox" Style="{StaticResource OdTextBoxStyle}" />
</WrapPanel>
</StackPanel>
</ui:Card>
<Border
Width="260"
Margin="{DynamicResource Od.Margin.Item}"
Padding="{DynamicResource Od.Padding.Card}"
HorizontalAlignment="Left"
local:OdMotion.HoverScale="True"
Background="{DynamicResource CardBackground}"
BorderBrush="{DynamicResource CardBorderBrush}"
BorderThickness="1"
CornerRadius="{DynamicResource Od.Corner.Radius}">
<TextBlock FontSize="{DynamicResource Od.Font.Body}" Text="Hover me (Od.Motion via code)" />
</Border>
<ui:InfoBar
Title="Stale data"
Margin="{DynamicResource Od.Margin.Item}"
IsClosable="False"
IsOpen="True"
Message="ui:InfoBar under the current preset."
Severity="Warning" />
<WrapPanel x:Name="StressHost" />
</StackPanel>
</ScrollViewer>
</Grid>
<TextBox
x:Name="LogBox"
Grid.Row="2"
Margin="12,0,12,12"
AcceptsReturn="True"
FontFamily="Cascadia Mono, Consolas"
HorizontalScrollBarVisibility="Auto"
IsReadOnly="True"
VerticalScrollBarVisibility="Auto" />
</Grid>
</ui:FluentWindow>
+280
View File
@@ -0,0 +1,280 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Threading;
using Microsoft.Win32;
using Wpf.Ui.Appearance;
using UiButton = Wpf.Ui.Controls.Button;
using UiCard = Wpf.Ui.Controls.Card;
using UiTextBox = Wpf.Ui.Controls.TextBox;
namespace ThemeLab;
public partial class MainWindow
{
private const int WmSettingChange = 0x001A;
// Kept alive for its TextScaleFactorChanged event.
private readonly Windows.UI.ViewManagement.UISettings _uiSettings = new();
private Preset _preset = Preset.Standard;
public MainWindow()
{
InitializeComponent();
Loaded += OnLoaded;
}
private double CurrentTextScale => ApplyTextScale.IsChecked == true ? TextScale.FromWinRt(_uiSettings) : 1.0;
private void OnLoaded(object sender, RoutedEventArgs e)
{
HwndSource.FromHwnd(new WindowInteropHelper(this).Handle)?.AddHook(WndProc);
_uiSettings.TextScaleFactorChanged += (_, _) => Dispatcher.InvokeAsync(() =>
{
Log($"UISettings.TextScaleFactorChanged -> {TextScale.FromWinRt(_uiSettings):0.00}");
OnTextScaleChanged();
});
SystemEvents.UserPreferenceChanged += (_, args) => Dispatcher.InvokeAsync(() => Log($"SystemEvents.UserPreferenceChanged: {args.Category}"));
UpdateTextScaleInfo();
Log($"Started. Elements: {CountElements(this)}; preset {_preset.Name}; theme {ApplicationThemeManager.GetAppTheme()}; "
+ $"OS animations {(SystemParameters.ClientAreaAnimation ? "on" : "off")}; high contrast {(SystemParameters.HighContrast ? "on" : "off")}; "
+ $"text scale registry {TextScale.FromRegistry():0.00} / WinRT {TextScale.FromWinRt(_uiSettings):0.00}");
if (Environment.GetCommandLineArgs().Contains("--auto"))
{
Dispatcher.InvokeAsync(RunAutomatedAsync, DispatcherPriority.ContextIdle);
}
}
// `ThemeLab.exe --auto`: every measurement the lab can take without a human, written to
// %LocalAppData%\OmniDeck.Spikes\theme\. Flicker and Mica artifacts still need eyes on the window.
private async Task RunAutomatedAsync()
{
await ProbeAsync();
await BenchmarkAsync();
OnStress(this, new RoutedEventArgs());
await Dispatcher.InvokeAsync(() => { }, DispatcherPriority.ContextIdle);
await BenchmarkAsync();
foreach (var theme in new[] { "Light", "Dark" })
{
OnThemeChecked(new FrameworkElement { Tag = theme }, new RoutedEventArgs());
await Task.Delay(500);
}
OnFrozenStoryboardTest(this, new RoutedEventArgs());
await Task.Delay(500);
var dir = System.IO.Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes", "theme");
System.IO.Directory.CreateDirectory(dir);
var file = System.IO.Path.Combine(dir, $"{DateTime.UtcNow:yyyyMMdd-HHmmss}-auto.log");
await System.IO.File.WriteAllTextAsync(file, LogBox.Text);
Close();
}
private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
{
if (msg == WmSettingChange)
{
var area = lParam == IntPtr.Zero ? "(null)" : Marshal.PtrToStringUni(lParam);
Log($"WM_SETTINGCHANGE wParam={wParam} lParam=\"{area}\"; registry text scale now {TextScale.FromRegistry():0.00}");
}
return IntPtr.Zero;
}
private async void OnPresetChecked(object sender, RoutedEventArgs e)
{
if (!IsLoaded || sender is not FrameworkElement { Tag: string name })
{
return;
}
_preset = Preset.All.First(p => p.Name == name);
var ms = await ApplyPresetAsync(_preset);
Log($"Preset -> {_preset.Name}: {ms:F1} ms to layout/render ({CountElements(this)} elements)");
}
private async Task<double> ApplyPresetAsync(Preset preset)
{
var sw = Stopwatch.StartNew();
PresetEngine.Apply(PresetEngine.Build(preset, CurrentTextScale));
// Loaded priority runs after the pending layout and render passes.
await Dispatcher.InvokeAsync(() => { }, DispatcherPriority.Loaded);
return sw.Elapsed.TotalMilliseconds;
}
private void OnThemeChecked(object sender, RoutedEventArgs e)
{
if (!IsLoaded || sender is not FrameworkElement { Tag: string tag })
{
return;
}
var sw = Stopwatch.StartNew();
if (tag == "System")
{
SystemThemeWatcher.Watch(this);
ApplicationThemeManager.ApplySystemTheme();
}
else
{
SystemThemeWatcher.UnWatch(this);
ApplicationThemeManager.Apply(tag == "Light" ? ApplicationTheme.Light : ApplicationTheme.Dark);
}
var presetStillMerged = Application.Current.Resources.MergedDictionaries.Any(d => d.Contains("Od.Preset.Name"));
Log($"Theme -> {tag} ({ApplicationThemeManager.GetAppTheme()}) in {sw.Elapsed.TotalMilliseconds:F1} ms; preset layer still merged: {presetStillMerged}");
}
private async void OnTextScaleToggled(object sender, RoutedEventArgs e)
{
if (!IsLoaded)
{
return;
}
await ApplyPresetAsync(_preset);
UpdateTextScaleInfo();
Log($"Text scale applied: {CurrentTextScale:0.00}");
}
private async void OnTextScaleChanged()
{
UpdateTextScaleInfo();
if (ApplyTextScale.IsChecked == true)
{
await ApplyPresetAsync(_preset);
}
}
private void UpdateTextScaleInfo() =>
TextScaleInfo.Text = $"Registry: {TextScale.FromRegistry():0.00} · WinRT: {TextScale.FromWinRt(_uiSettings):0.00}";
private async void OnBenchmark(object sender, RoutedEventArgs e) => await BenchmarkAsync();
private async Task BenchmarkAsync()
{
var times = new List<double>();
for (var i = 0; i < 30; i++)
{
times.Add(await ApplyPresetAsync(Preset.All[i % Preset.All.Length]));
}
await ApplyPresetAsync(_preset);
times.Sort();
Log($"Benchmark x30 ({CountElements(this)} elements): min {times[0]:F1} ms, median {times[times.Count / 2]:F1} ms, "
+ $"p90 {times[(int)(times.Count * 0.9)]:F1} ms, max {times[^1]:F1} ms");
}
private void OnStress(object sender, RoutedEventArgs e)
{
for (var i = 0; i < 100; i++)
{
var panel = new StackPanel();
panel.Children.Add(new TextBlock { Text = $"Card {i}" });
panel.Children.Add(new UiButton { Content = "Od button", Style = (Style)FindResource("OdButtonStyle") });
panel.Children.Add(new UiTextBox { PlaceholderText = "Od text box", Style = (Style)FindResource("OdTextBoxStyle") });
var card = new UiCard { Width = 220, Content = panel };
card.SetResourceReference(MarginProperty, "Od.Margin.Item");
StressHost.Children.Add(card);
}
Dispatcher.InvokeAsync(() => Log($"Stress: {StressHost.Children.Count} cards, {CountElements(this)} elements"), DispatcherPriority.Loaded);
}
private async void OnProbe(object sender, RoutedEventArgs e) => await ProbeAsync();
private async Task ProbeAsync()
{
Log("Probe: preset | control | ActualHeight | Padding | FontSize | template CornerRadius");
foreach (var preset in Preset.All)
{
await ApplyPresetAsync(preset);
foreach (var (name, control) in new (string, Control)[]
{
("default ui:Button", ProbeDefaultButton), ("Od ui:Button", ProbeOdButton),
("default ui:TextBox", ProbeDefaultTextBox), ("Od ui:TextBox", ProbeOdTextBox), ("ui:Card", ProbeCard),
})
{
var border = FindFirst<Border>(control);
Log($" {preset.Name,-8} | {name,-18} | {control.ActualHeight,6:F1} | {control.Padding} | {control.FontSize,5:F1} | {border?.CornerRadius.ToString() ?? "-"}");
}
}
await ApplyPresetAsync(_preset);
}
private void OnFrozenStoryboardTest(object sender, RoutedEventArgs e)
{
const string xaml = """
<Style xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" TargetType="Button">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Trigger.EnterActions>
<BeginStoryboard>
<Storyboard>
<DoubleAnimation Storyboard.TargetProperty="Opacity" To="0.5" Duration="{DynamicResource Od.Motion.Duration}" />
</Storyboard>
</BeginStoryboard>
</Trigger.EnterActions>
</Trigger>
</Style.Triggers>
</Style>
""";
try
{
var style = (Style)XamlReader.Parse(xaml);
var button = new System.Windows.Controls.Button { Content = "Storyboard test", Style = style };
StressHost.Children.Add(button);
button.UpdateLayout();
Log("Storyboard test: no exception (a DynamicResource in a style storyboard was accepted)");
}
catch (Exception ex)
{
Log($"Storyboard test: {ex.GetType().Name}: {ex.Message}");
}
}
private void OnCopyLog(object sender, RoutedEventArgs e) => Clipboard.SetText(LogBox.Text);
private void Log(string line)
{
LogBox.AppendText($"{DateTime.Now:HH:mm:ss.fff} {line}{Environment.NewLine}");
LogBox.ScrollToEnd();
}
private static int CountElements(DependencyObject root)
{
var count = 1;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
count += CountElements(VisualTreeHelper.GetChild(root, i));
}
return count;
}
private static T? FindFirst<T>(DependencyObject root)
where T : DependencyObject
{
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(root); i++)
{
var child = VisualTreeHelper.GetChild(root, i);
if (child is T match)
{
return match;
}
if (FindFirst<T>(child) is { } nested)
{
return nested;
}
}
return null;
}
}
+49
View File
@@ -0,0 +1,49 @@
using System.Windows.Media.Animation;
namespace ThemeLab;
/// <summary>
/// Code-driven motion: storyboards inside styles are frozen and cannot take DynamicResource, so the
/// animation reads Od.Motion.Duration when it starts. A preset swap applies to the very next hover,
/// and the OS "animation effects" switch (SystemParameters.ClientAreaAnimation) forces motion off.
/// </summary>
public static class OdMotion
{
public static readonly DependencyProperty HoverScaleProperty = DependencyProperty.RegisterAttached(
"HoverScale", typeof(bool), typeof(OdMotion), new PropertyMetadata(false, OnHoverScaleChanged));
public static bool GetHoverScale(DependencyObject element) => (bool)element.GetValue(HoverScaleProperty);
public static void SetHoverScale(DependencyObject element, bool value) => element.SetValue(HoverScaleProperty, value);
private static void OnHoverScaleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not FrameworkElement element || e.NewValue is not true)
{
return;
}
element.RenderTransformOrigin = new Point(0.5, 0.5);
element.RenderTransform = new ScaleTransform(1, 1);
element.MouseEnter += (_, _) => Animate(element, 1.04);
element.MouseLeave += (_, _) => Animate(element, 1.0);
}
private static void Animate(FrameworkElement element, double to)
{
var transform = (ScaleTransform)element.RenderTransform;
var duration = element.TryFindResource("Od.Motion.Duration") is Duration d ? d : new Duration(TimeSpan.Zero);
if (!SystemParameters.ClientAreaAnimation || duration.TimeSpan == TimeSpan.Zero)
{
transform.BeginAnimation(ScaleTransform.ScaleXProperty, null);
transform.BeginAnimation(ScaleTransform.ScaleYProperty, null);
transform.ScaleX = to;
transform.ScaleY = to;
return;
}
var animation = new DoubleAnimation(to, duration) { EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } };
transform.BeginAnimation(ScaleTransform.ScaleXProperty, animation);
transform.BeginAnimation(ScaleTransform.ScaleYProperty, animation);
}
}
+66
View File
@@ -0,0 +1,66 @@
namespace ThemeLab;
/// <summary>One row set of the token table in docs/UI-MODES.md §2.</summary>
public sealed record Preset(
string Name, double FontBase, double FontScale, double Density, double HitTargetMin, double Corner, int MotionMs, double ChartLineWeight)
{
public static readonly Preset Dynamic = new("Dynamic", 13.5, 1.35, 4, 32, 8, 180, 1.5);
public static readonly Preset Standard = new("Standard", 15.5, 1.30, 6, 36, 6, 100, 2);
public static readonly Preset Comfort = new("Comfort", 19, 1.25, 10, 44, 6, 0, 3);
public static readonly Preset[] All = [Dynamic, Standard, Comfort];
}
/// <summary>
/// Builds the preset layer in code (derived tokens need the OS text scale and user overrides anyway)
/// and swaps it in place inside Application.Resources.MergedDictionaries.
/// </summary>
public static class PresetEngine
{
private const string MarkerKey = "Od.Preset.Name";
public static ResourceDictionary Build(Preset p, double textScale)
{
var body = p.FontBase * textScale;
var d = p.Density;
return new ResourceDictionary
{
[MarkerKey] = p.Name,
["Od.Font.Body"] = body,
["Od.Font.H2"] = body * p.FontScale,
["Od.Font.H1"] = body * p.FontScale * p.FontScale,
["Od.Font.Caption"] = body * 0.85,
["Od.Padding.Control"] = new Thickness(d * 2, d, d * 2, d),
["Od.Padding.Card"] = new Thickness(d * 3),
["Od.Margin.Item"] = new Thickness(0, 0, 0, d * 2),
["Od.HitTarget.Min"] = p.HitTargetMin,
["Od.Corner.Radius"] = new CornerRadius(p.Corner),
["Od.Motion.Duration"] = new Duration(TimeSpan.FromMilliseconds(p.MotionMs)),
["Od.Chart.LineWeight"] = p.ChartLineWeight,
// Deliberate WPF-UI overrides, to see which ones follow a runtime swap. In WPF-UI 4.3
// templates ControlCornerRadius, ControlContentThemeFontSize and TextControlThemeMinHeight
// are DynamicResource; ButtonPadding and CardPadding are StaticResource.
["ControlCornerRadius"] = new CornerRadius(p.Corner),
["ControlContentThemeFontSize"] = body,
["TextControlThemeMinHeight"] = p.HitTargetMin,
["ButtonPadding"] = new Thickness(d * 2, d, d * 2, d),
["CardPadding"] = new Thickness(d * 3),
};
}
public static void Apply(ResourceDictionary preset)
{
var merged = Application.Current.Resources.MergedDictionaries;
for (var i = 0; i < merged.Count; i++)
{
if (merged[i].Contains(MarkerKey))
{
merged[i] = preset;
return;
}
}
merged.Add(preset);
}
}
+19
View File
@@ -0,0 +1,19 @@
using Microsoft.Win32;
namespace ThemeLab;
/// <summary>
/// Windows "Text size" (Settings → Accessibility). WPF ignores it, so OmniDeck has to read it and
/// multiply Od.Font.* itself. Two sources are compared: the registry (no WinRT projection needed)
/// and UISettings.TextScaleFactor (needs a Windows-versioned target framework).
/// </summary>
public static class TextScale
{
public static double FromRegistry()
{
using var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Accessibility");
return key?.GetValue("TextScaleFactor") is int percent ? percent / 100.0 : 1.0;
}
public static double FromWinRt(Windows.UI.ViewManagement.UISettings settings) => settings.TextScaleFactor;
}
+15
View File
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Spike #5 (issue #6): runtime preset swap on WPF-UI 4.3. The Windows-versioned TFM is only here
to compare UISettings.TextScaleFactor (WinRT) with the registry value. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows10.0.26100.0</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup>
</Project>
+5
View File
@@ -0,0 +1,5 @@
<Application
x:Class="WebLab.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
StartupUri="MainWindow.xaml" />
+3
View File
@@ -0,0 +1,3 @@
namespace WebLab;
public partial class App : Application;
+35
View File
@@ -0,0 +1,35 @@
using System.Text.Json;
namespace WebLab;
public sealed record CatalogEntry(
string Id, string Name, string StartUrl, string Profile, string[] NavAllow, string[] PopupAllow, bool Notifications, bool AudioPin);
public static class Catalog
{
/// <summary>Reads catalog/webapps.json from the repository this harness was built in.</summary>
public static IReadOnlyList<CatalogEntry> Load()
{
for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent)
{
var file = Path.Combine(dir.FullName, "catalog", "webapps.json");
if (File.Exists(file))
{
using var doc = JsonDocument.Parse(File.ReadAllText(file));
var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true };
return doc.RootElement.GetProperty("apps").Deserialize<CatalogEntry[]>(options) ?? [];
}
}
return [];
}
/// <summary>docs/WEBAPP-CATALOG.md §1: equal to an entry, or a subdomain of it on whole labels.</summary>
public static bool Matches(string host, IEnumerable<string> domains) =>
domains.Any(d => host.Equals(d, StringComparison.OrdinalIgnoreCase)
|| host.EndsWith("." + d, StringComparison.OrdinalIgnoreCase));
/// <summary>Scheme, host and path only: sign-in URLs carry tokens in their query strings.</summary>
public static string Redact(string uri) =>
Uri.TryCreate(uri, UriKind.Absolute, out var u) ? $"{u.Scheme}://{u.Host}{u.AbsolutePath}" : uri;
}
+7
View File
@@ -0,0 +1,7 @@
// The WPF SDK's implicit usings stop at System.* (and leave out System.IO because of Shapes.Path).
global using System.IO;
global using System.Windows;
global using System.Windows.Controls;
global using Microsoft.Web.WebView2.Core;
global using Microsoft.Web.WebView2.Wpf;
global using Path = System.IO.Path;
+35
View File
@@ -0,0 +1,35 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebLab · CDP detection (spike #4)</title>
<style>body { font: 14px/1.5 "Segoe UI", sans-serif; margin: 24px; } .big { font-size: 28px; font-weight: 600; }</style>
</head>
<body>
<h1>Can this page tell that the DevTools Protocol Runtime domain is on?</h1>
<p>The widely used check: log an Error whose <code>stack</code> getter has a side effect. Only a
DevTools client that serializes console arguments (Runtime.enable) reads it. Spike #4 (issue #5).</p>
<p class="big" id="verdict">checking…</p>
<button onclick="check()">Check again</button>
<p>Console traffic for the ring buffer:
<button onclick="console.log('log', {a: 1}, [1, 2])">console.log</button>
<button onclick="console.warn('warn message')">console.warn</button>
<button onclick="console.error(new Error('error object'))">console.error</button>
<button onclick="setTimeout(() => { throw new Error('uncaught exception'); })">throw</button>
<button onclick="fetch('https://weblab.example/missing.json').catch(() => {})">404 fetch</button>
</p>
<script>
function check() {
let read = false;
const e = new Error('probe');
Object.defineProperty(e, 'stack', { get() { read = true; return ''; } });
console.debug(e);
setTimeout(() => {
document.getElementById('verdict').textContent = read ? 'DETECTED: Runtime domain is enabled' : 'not detected';
window.chrome?.webview?.postMessage({ probe: 'cdp-detect', detected: read });
}, 200);
}
check();
</script>
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebLab · cookie persistence</title>
</head>
<body style="font: 14px/1.5 'Segoe UI', sans-serif; margin: 24px">
<h1>Cookie persistence probe</h1>
<p>Lists the cookies this origin already has, then (with <code>?set=NAME</code>) sets a one-year
cookie named NAME. Used to tell which ways of closing the host keep cookies across restarts.</p>
<pre id="out"></pre>
<script>
const before = document.cookie;
const name = new URLSearchParams(location.search).get('set');
if (name) {
document.cookie = `${name}=${Date.now()}; max-age=31536000; path=/; secure; samesite=lax`;
}
const result = { probe: 'cookie', before, after: document.cookie, set: name };
document.getElementById('out').textContent = JSON.stringify(result, null, 2);
window.chrome?.webview?.postMessage(result);
</script>
</body>
</html>
+60
View File
@@ -0,0 +1,60 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>WebLab · EME probe (spike #1)</title>
<style>
body { font: 14px/1.5 "Segoe UI", sans-serif; margin: 24px; }
table { border-collapse: collapse; } td, th { border: 1px solid #8884; padding: 4px 10px; text-align: left; }
.yes { color: #0a7d32; font-weight: 600; } .no { color: #b3261e; font-weight: 600; }
pre { background: #8881; padding: 8px; white-space: pre-wrap; }
</style>
</head>
<body>
<h1>EME probe</h1>
<p>Spike #1 (issue #2): which key systems this WebView2 exposes. Results are also posted to the host log.</p>
<table id="results"><tr><th>Key system</th><th>Robustness</th><th>Available</th><th>Detail</th></tr></table>
<h2>User agent</h2>
<pre id="ua"></pre>
<script>
const video = [{ contentType: 'video/mp4; codecs="avc1.42E01E"' }];
const audio = [{ contentType: 'audio/mp4; codecs="mp4a.40.2"' }];
const probes = [
['com.widevine.alpha', ''], ['com.widevine.alpha', 'SW_SECURE_CRYPTO'], ['com.widevine.alpha', 'HW_SECURE_ALL'],
['com.microsoft.playready.recommendation', ''], ['com.microsoft.playready.recommendation', '3000'],
['com.microsoft.playready', ''], ['org.w3.clearkey', ''],
];
async function probe([keySystem, robustness]) {
const withRobustness = caps => caps.map(c => robustness ? { ...c, robustness } : c);
const config = [{ initDataTypes: ['cenc'], videoCapabilities: withRobustness(video), audioCapabilities: withRobustness(audio) }];
try {
const access = await navigator.requestMediaKeySystemAccess(keySystem, config);
const keys = await access.createMediaKeys();
return { keySystem, robustness, available: true, detail: `createMediaKeys ok (${keys.constructor.name})` };
} catch (e) {
return { keySystem, robustness, available: false, detail: `${e.name}: ${e.message}` };
}
}
(async () => {
const results = [];
for (const p of probes) {
const r = await probe(p);
results.push(r);
const row = document.getElementById('results').insertRow();
row.insertCell().textContent = r.keySystem;
row.insertCell().textContent = r.robustness || '(none)';
const cell = row.insertCell(); cell.textContent = r.available ? 'yes' : 'no'; cell.className = r.available ? 'yes' : 'no';
row.insertCell().textContent = r.detail;
}
let brands = null, high = null;
if (navigator.userAgentData) {
brands = navigator.userAgentData.brands;
try { high = await navigator.userAgentData.getHighEntropyValues(['fullVersionList', 'platformVersion']); } catch {}
}
const ua = { userAgent: navigator.userAgent, brands, fullVersionList: high?.fullVersionList, platformVersion: high?.platformVersion };
document.getElementById('ua').textContent = JSON.stringify(ua, null, 2);
window.chrome?.webview?.postMessage({ probe: 'eme', results, ua });
})();
</script>
</body>
</html>
+98
View File
@@ -0,0 +1,98 @@
namespace WebLab;
/// <summary>
/// `--check-signed-in`: reopen the catalog apps on their saved profiles and ask each page whether it
/// is signed in, to tell whether sign-ins survived the last shutdown (spike #2). Gmail then reloads
/// with CDP capture on, to check that a signed-in app still loads with Runtime.enable (spike #4).
/// `--ladder=gmail,...`: only the governor ladder, for the listed apps.
/// </summary>
public partial class MainWindow
{
// Each expression returns "in" or "out". It only reads the page's own state.
private static readonly Dictionary<string, string> SignedInProbes = new()
{
["gmail"] = "location.host === 'mail.google.com' ? 'in' : 'out'",
["youtube"] = "document.querySelector('#avatar-btn') ? 'in' : 'out'",
["spotify"] = "document.querySelector('[data-testid=\"login-button\"]') ? 'out' : 'in'",
["facebook"] = "document.querySelector('input[name=\"email\"]') ? 'out' : 'in'",
["discord"] = "location.pathname.startsWith('/channels') ? 'in' : 'out'",
};
private async Task RunSignedInCheckAsync()
{
var targets = ((List<Target>)Targets.ItemsSource).Where(t => t.Entry is not null && SignedInProbes.ContainsKey(t.Entry.Id)).ToList();
try
{
foreach (var target in targets)
{
var slot = await OpenAsync(target);
await Task.Delay(TimeSpan.FromSeconds(12));
await LogSignedInAsync(slot);
}
var gmail = _slots.First(s => s.Id == "gmail");
ShowOnly(gmail);
await SetCaptureAsync(gmail, runtime: true, log: true);
var done = new TaskCompletionSource<bool>();
gmail.View!.CoreWebView2.NavigationCompleted += (_, e) => done.TrySetResult(e.IsSuccess);
gmail.View.CoreWebView2.Reload();
await done.Task.WaitAsync(TimeSpan.FromSeconds(60));
await Task.Delay(TimeSpan.FromSeconds(10));
Log("[gmail] after a reload with capture on:");
await LogSignedInAsync(gmail);
Log($"[gmail] ring buffer holds {gmail.ConsoleRing.Count} entries");
}
catch (Exception ex)
{
Log($"CHECK FAILED: {ex}");
}
finally
{
foreach (var slot in _slots.ToList())
{
Hibernate(slot);
}
await Task.Delay(TimeSpan.FromSeconds(3));
Close();
}
}
private async Task LogSignedInAsync(Slot slot)
{
var id = slot.Entry!.Id;
var result = await slot.View!.CoreWebView2.ExecuteScriptAsync(SignedInProbes[id]);
Log($"SIGNED-IN {id}: {result.Trim('"')} at {Catalog.Redact(slot.View.CoreWebView2.Source)}");
}
private async Task RunLaddersOnlyAsync(string ids)
{
var targets = (List<Target>)Targets.ItemsSource;
var phase = TimeSpan.FromSeconds(int.TryParse(Arg("--phase"), out var s) && s > 0 ? s : 60);
try
{
StartCsv();
foreach (var id in ids.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var slot = await OpenAsync(targets.First(t => t.Entry?.Id == id));
await Task.Delay(TimeSpan.FromSeconds(12));
await LogSignedInAsync(slot);
await RunLadderAsync(slot, phase);
await LogSignedInAsync(slot);
Hibernate(slot);
_slots.Remove(slot);
await Task.Delay(TimeSpan.FromSeconds(10));
}
}
catch (Exception ex)
{
Log($"LADDER FAILED: {ex}");
}
finally
{
StopCsv();
await Task.Delay(500);
Close();
}
}
}
+62
View File
@@ -0,0 +1,62 @@
namespace WebLab;
/// <summary>
/// Cookie persistence across host shutdowns (spike #2 follow-up): sign-ins made in an interactive
/// session were gone after the host was closed, while cookies from a run that disposed every view
/// first survived.
/// `--cookie-set=NAME [--exit=clean]`: set a one-year cookie, wait past the cookie store's commit
/// interval, then either dispose every view and exit (clean) or wait to be closed from outside.
/// `--cookie-check`: list the cookies the probe page can see, then exit cleanly.
/// </summary>
public partial class MainWindow
{
private async Task RunCookieProbeAsync()
{
var page = new Target("lab · cookie probe", $"https://{LabHost}/cookie.html", "lab", null);
try
{
if (Arg("--cookie-set") is { } name)
{
var wait = WaitForMessageAsync("cookie");
await OpenAsync(page with { Url = page.Url + "?set=" + Uri.EscapeDataString(name) });
var result = await wait;
Log($"COOKIE set '{name}'; before: \"{result.GetProperty("before").GetString()}\"");
await Task.Delay(TimeSpan.FromSeconds(45)); // past the 30 s commit interval
if (Arg("--exit") == "clean")
{
foreach (var slot in _slots.ToList())
{
Hibernate(slot);
}
await Task.Delay(TimeSpan.FromSeconds(3));
Log("COOKIE exit: clean (views disposed first)");
Close();
}
else
{
Log("COOKIE ready to be closed from outside");
}
}
else
{
var wait = WaitForMessageAsync("cookie");
await OpenAsync(page);
var result = await wait;
Log($"COOKIE check: \"{result.GetProperty("before").GetString()}\"");
foreach (var slot in _slots.ToList())
{
Hibernate(slot);
}
await Task.Delay(TimeSpan.FromSeconds(3));
Close();
}
}
catch (Exception ex)
{
Log($"COOKIE FAILED: {ex}");
Close();
}
}
}
+122
View File
@@ -0,0 +1,122 @@
using System.Text.RegularExpressions;
namespace WebLab;
/// <summary>
/// `WebLab.exe --measure [--phase=60]`: spikes #3 and #4 on the profiles signed in by hand earlier.
/// A governor ladder per app (Discord, YouTube, Gmail), every catalog app open at once, then CDP
/// capture overhead and whether signed-in apps still load with Runtime.enable on.
/// </summary>
public partial class MainWindow
{
private static readonly string[] LadderApps = ["discord", "youtube", "gmail"];
private async Task RunMeasureAsync()
{
// Messenger is left out: messenger.com closed in April 2026.
var targets = ((List<Target>)Targets.ItemsSource).Where(t => t.Entry is { Id: not "messenger" }).ToList();
var phase = TimeSpan.FromSeconds(int.TryParse(Arg("--phase"), out var s) && s > 0 ? s : 60);
Target App(string id) => targets.First(t => t.Entry!.Id == id);
try
{
StartCsv();
Mark("measure:shell-only");
await Task.Delay(TimeSpan.FromSeconds(10));
foreach (var id in LadderApps)
{
var slot = await OpenAsync(App(id));
await RunLadderAsync(slot, phase);
LogTitle(slot);
Hibernate(slot);
_slots.Remove(slot);
Mark("measure:gap");
await Task.Delay(TimeSpan.FromSeconds(10));
}
// Every catalog app at once; the last one opened stays visible, the others are hidden.
var all = new List<Slot>();
foreach (var target in targets)
{
all.Add(await OpenAsync(target));
await Task.Delay(TimeSpan.FromSeconds(3));
}
Mark("all:open");
await Task.Delay(phase * 1.5);
all.ForEach(LogTitle);
foreach (var slot in all.Take(all.Count - 1))
{
await SuspendAsync(slot);
}
Mark("all:suspended");
await Task.Delay(phase);
all.ForEach(Hibernate);
Mark("all:hibernated");
await Task.Delay(phase / 2);
all.ForEach(slot => _slots.Remove(slot));
// CDP capture on signed-in apps: cost, and whether they still load with Runtime.enable on.
var cdp = new List<Slot>();
foreach (var id in new[] { "gmail", "discord", "spotify" })
{
cdp.Add(await OpenAsync(App(id)));
}
Mark("cdp:off");
await Task.Delay(phase);
foreach (var slot in cdp)
{
await SetCaptureAsync(slot, runtime: true, log: true);
}
Mark("cdp:on");
await Task.Delay(phase);
foreach (var slot in cdp)
{
var done = new TaskCompletionSource<bool>();
slot.View!.CoreWebView2.NavigationCompleted += (_, e) => done.TrySetResult(e.IsSuccess);
slot.View.CoreWebView2.Reload();
Log($"[{slot.Id}] reload with capture on: {(await done.Task.WaitAsync(TimeSpan.FromSeconds(60)) ? "ok" : "failed")}");
}
Mark("cdp:on-reloaded");
await Task.Delay(phase);
foreach (var slot in cdp)
{
LogTitle(slot);
Log($"[{slot.Id}] ring buffer holds {slot.ConsoleRing.Count} entries; last 10:");
foreach (var line in slot.ConsoleRing.TakeLast(10))
{
Log($"[{slot.Id}] {RedactEmails(line)}");
}
}
}
catch (Exception ex)
{
Log($"MEASURE FAILED: {ex}");
}
finally
{
StopCsv();
await Task.Delay(500);
Close();
}
}
// Titles show whether an app is still signed in; addresses in them stay out of the log.
private void LogTitle(Slot slot)
{
try
{
Log($"[{slot.Id}] title \"{RedactEmails(slot.View?.CoreWebView2?.DocumentTitle ?? "")}\" at {Catalog.Redact(slot.View?.CoreWebView2?.Source ?? "")}");
}
catch (InvalidOperationException)
{
// The view is being torn down.
}
}
private static string RedactEmails(string text) => Regex.Replace(text, @"[^\s@""']+@[^\s@""']+", "<email>");
}
+71
View File
@@ -0,0 +1,71 @@
<Window
x:Class="WebLab.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WebLab — spikes #1–#4 (WebView2)"
Width="1560"
Height="960"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="210" />
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0" Margin="6">
<ComboBox x:Name="Targets" Width="280" Margin="0,0,6,0" DisplayMemberPath="Label" />
<Button Margin="0,0,12,0" Padding="10,2" Click="OnOpen" Content="Open" />
<CheckBox x:Name="EnforcePolicy" Margin="0,4,12,0" Content="Enforce navAllow / popupAllow" IsChecked="True" />
<CheckBox x:Name="DevToolsEnabled" Margin="0,4,12,0" Content="DevTools UI enabled (new slots)" />
<TextBlock Margin="0,4,4,0" Text="Ladder phase (s):" />
<TextBox x:Name="PhaseSeconds" Width="40" Margin="0,0,12,0" Text="60" />
<Button x:Name="RecordButton" Margin="0,0,6,0" Padding="10,2" Click="OnRecord" Content="Start CSV" />
<TextBox x:Name="MarkText" Width="160" Margin="0,0,4,0" />
<Button Margin="0,0,12,0" Padding="10,2" Click="OnMark" Content="Mark phase" />
<TextBlock x:Name="EnvInfo" Margin="0,4,0,0" />
</WrapPanel>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="280" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="470" />
</Grid.ColumnDefinitions>
<DockPanel Grid.Column="0" Margin="6,0,6,0">
<UniformGrid DockPanel.Dock="Bottom" Columns="2">
<Button Margin="2" Click="OnShow" Content="Show" />
<Button Margin="2" Click="OnHide" Content="Hide" />
<Button Margin="2" Click="OnSuspend" Content="Suspend (+Low)" />
<Button Margin="2" Click="OnResume" Content="Resume" />
<Button Margin="2" Click="OnHibernate" Content="Dispose (hibernate)" />
<Button Margin="2" Click="OnReopen" Content="Reopen" />
<Button Margin="2" Click="OnCaptureFull" Content="Console: Runtime+Log" />
<Button Margin="2" Click="OnCaptureLogOnly" Content="Console: Log only" />
<Button Margin="2" Click="OnCaptureOff" Content="Console off" />
<Button Margin="2" Click="OnCloseSlot" Content="Close slot" />
<Button Margin="2" Click="OnLadder" Content="Run ladder" />
<Button Margin="2" Click="OnHibernateAll" Content="Dispose all" />
</UniformGrid>
<ListBox x:Name="SlotList" SelectionChanged="OnSlotSelected" />
</DockPanel>
<Grid x:Name="Host" Grid.Column="1" />
<DockPanel Grid.Column="2" Margin="6,0,6,0">
<TextBlock x:Name="Totals" Margin="0,0,0,4" DockPanel.Dock="Top" TextWrapping="Wrap" />
<DataGrid x:Name="MemGrid" AutoGenerateColumns="True" HeadersVisibility="Column" IsReadOnly="True" />
</DockPanel>
</Grid>
<Grid Grid.Row="2" Margin="6">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="2*" />
</Grid.ColumnDefinitions>
<TextBox x:Name="LogBox" Grid.Column="0" Margin="0,0,6,0" FontFamily="Cascadia Mono, Consolas" HorizontalScrollBarVisibility="Auto" IsReadOnly="True" VerticalScrollBarVisibility="Auto" />
<TextBox x:Name="ConsoleBox" Grid.Column="1" FontFamily="Cascadia Mono, Consolas" HorizontalScrollBarVisibility="Auto" IsReadOnly="True" VerticalScrollBarVisibility="Auto" />
</Grid>
</Grid>
</Window>
+749
View File
@@ -0,0 +1,749 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.Text.Json;
using System.Windows.Threading;
namespace WebLab;
public sealed record Target(string Label, string Url, string Profile, CatalogEntry? Entry);
/// <summary>
/// The WebView2 lab for spikes #1–#4. One shared environment, one profile per catalog profile group,
/// the catalog's navigation policy, the governor's lifecycle steps, a per-process memory sampler and
/// CDP console capture. `--auto` runs the unattended checks; `--wv2-args=...` passes browser arguments.
/// </summary>
public partial class MainWindow
{
private const string LabHost = "weblab.example";
private static readonly string DataRoot = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "OmniDeck.Spikes");
private static readonly string LabPages = Path.Combine(AppContext.BaseDirectory, "LabPages");
private readonly ObservableCollection<Slot> _slots = [];
private readonly DispatcherTimer _sampler = new() { Interval = TimeSpan.FromSeconds(2) };
private readonly string _stamp = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
private readonly StreamWriter _logFile;
private readonly Dictionary<string, TaskCompletionSource<JsonElement>> _waiters = [];
private CoreWebView2Environment? _env;
private StreamWriter? _csv;
private string _phase = "-";
private bool _sampling;
private bool _browserGone;
public MainWindow()
{
InitializeComponent();
Directory.CreateDirectory(Path.Combine(DataRoot, "weblab"));
_logFile = new StreamWriter(Path.Combine(DataRoot, "weblab", $"{_stamp}.log")) { AutoFlush = true };
SlotList.ItemsSource = _slots;
Targets.ItemsSource = BuildTargets();
Targets.SelectedIndex = 0;
_sampler.Tick += async (_, _) => await SampleAsync();
_sampler.Start();
Closed += (_, _) =>
{
_csv?.Dispose();
_logFile.Dispose();
};
Log($"WebLab started. Windows {Environment.OSVersion.Version}, {Environment.ProcessorCount} logical CPUs, "
+ $"{GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / (1024.0 * 1024 * 1024):F1} GiB RAM. Data under {DataRoot}");
if (Environment.GetCommandLineArgs().Contains("--auto"))
{
Loaded += async (_, _) => await RunAutoAsync();
}
else if (Environment.GetCommandLineArgs().Contains("--measure"))
{
Loaded += async (_, _) => await RunMeasureAsync();
}
else if (Arg("--cookie-set") is not null || Environment.GetCommandLineArgs().Contains("--cookie-check"))
{
Loaded += async (_, _) => await RunCookieProbeAsync();
}
else if (Environment.GetCommandLineArgs().Contains("--check-signed-in"))
{
Loaded += async (_, _) => await RunSignedInCheckAsync();
}
else if (Arg("--ladder") is { } ladderApps)
{
Loaded += async (_, _) => await RunLaddersOnlyAsync(ladderApps);
}
}
private Slot? Selected => SlotList.SelectedItem as Slot;
private static List<Target> BuildTargets()
{
var targets = new List<Target>
{
new("lab · EME probe (#1)", $"https://{LabHost}/eme.html", "lab", null),
new("lab · Shaka support page (#1)", "https://shaka-player-demo.appspot.com/support.html", "lab", null),
new("lab · CDP detection (#4)", $"https://{LabHost}/cdp-detect.html", "lab", null),
};
targets.AddRange(Catalog.Load().Select(e => new Target($"{e.Id} · {e.Name} [{e.Profile}]", e.StartUrl, e.Profile, e)));
return targets;
}
private static string? Arg(string name) =>
Environment.GetCommandLineArgs().FirstOrDefault(a => a.StartsWith(name + "=", StringComparison.Ordinal))?[(name.Length + 1)..];
// ---- Environment and views -------------------------------------------------------------------
private async Task<CoreWebView2Environment> EnsureEnvironmentAsync()
{
if (_env is not null)
{
return _env;
}
var args = Arg("--wv2-args");
var options = new CoreWebView2EnvironmentOptions(additionalBrowserArguments: args);
_env = await CoreWebView2Environment.CreateAsync(null, Path.Combine(DataRoot, "WebView2"), options);
Log($"Environment: WebView2 Runtime {_env.BrowserVersionString}; user data {_env.UserDataFolder}; browser args '{args ?? ""}'");
EnvInfo.Text = $"WebView2 Runtime {_env.BrowserVersionString}";
return _env;
}
private async Task<WebView2> CreateViewAsync(Slot slot, string url, Action<CoreWebView2>? beforeNavigate = null)
{
var env = await EnsureEnvironmentAsync();
var view = new WebView2();
Host.Children.Add(view);
var options = env.CreateCoreWebView2ControllerOptions();
options.ProfileName = slot.Profile;
await view.EnsureCoreWebView2Async(env, options);
Configure(view.CoreWebView2, slot);
beforeNavigate?.Invoke(view.CoreWebView2);
view.CoreWebView2.Navigate(url);
return view;
}
private void Configure(CoreWebView2 core, Slot slot)
{
// docs/ARCHITECTURE.md §3 per-app pipeline. The user agent is never touched.
core.Settings.AreDevToolsEnabled = DevToolsEnabled.IsChecked == true;
core.Settings.IsPasswordAutosaveEnabled = false;
core.Settings.IsGeneralAutofillEnabled = false;
core.SetVirtualHostNameToFolderMapping(LabHost, LabPages, CoreWebView2HostResourceAccessKind.Allow);
core.NavigationStarting += (_, e) =>
{
var host = Uri.TryCreate(e.Uri, UriKind.Absolute, out var u) ? u.Host : "";
var allowed = slot.Entry is null || Catalog.Matches(host, slot.Entry.NavAllow);
Log($"[{slot.Id}] {(e.IsRedirected ? "redirect" : "navigate")} {Catalog.Redact(e.Uri)}"
+ $"{(e.IsUserInitiated ? " (user)" : "")}{(allowed ? "" : " — OUTSIDE navAllow")}");
if (!allowed && EnforcePolicy.IsChecked == true)
{
e.Cancel = true;
Log($"[{slot.Id}] cancelled: the product would open this in the default browser");
}
};
core.NavigationCompleted += (_, e) =>
Log($"[{slot.Id}] completed {(e.IsSuccess ? "ok" : e.WebErrorStatus.ToString())} {Catalog.Redact(core.Source)}");
core.NewWindowRequested += (_, e) => OnNewWindowRequested(slot, e);
core.IsDocumentPlayingAudioChanged += (_, _) => Log($"[{slot.Id}] playing audio: {core.IsDocumentPlayingAudio}");
core.ProcessFailed += (_, e) => Log($"[{slot.Id}] ProcessFailed {e.ProcessFailedKind}, reason {e.Reason}, exit {e.ExitCode}");
core.PermissionRequested += (_, e) => Log($"[{slot.Id}] permission {e.PermissionKind} for {Catalog.Redact(e.Uri)} (default handling)");
core.WebMessageReceived += (_, e) => OnWebMessage(slot, e.WebMessageAsJson);
}
private async void OnNewWindowRequested(Slot slot, CoreWebView2NewWindowRequestedEventArgs e)
{
var host = Uri.TryCreate(e.Uri, UriKind.Absolute, out var u) ? u.Host : "";
var inApp = slot.Entry is null || EnforcePolicy.IsChecked != true || Catalog.Matches(host, slot.Entry.PopupAllow);
Log($"[{slot.Id}] popup {Catalog.Redact(e.Uri)} → "
+ (inApp ? "in-app popup on the same profile" : "blocked: the product would open it in the default browser"));
if (!inApp)
{
e.Handled = true;
return;
}
var deferral = e.GetDeferral();
try
{
var view = new WebView2();
var features = e.WindowFeatures;
var window = new Window
{
Title = $"{slot.Id} · popup",
Owner = this,
Content = view,
Width = features.HasSize ? features.Width : 520,
Height = features.HasSize ? features.Height : 700,
};
window.Show();
var options = _env!.CreateCoreWebView2ControllerOptions();
options.ProfileName = slot.Profile;
await view.EnsureCoreWebView2Async(_env, options);
Configure(view.CoreWebView2, new Slot { Id = slot.Id + ":popup", Profile = slot.Profile, StartUrl = e.Uri, Entry = slot.Entry });
view.CoreWebView2.WindowCloseRequested += (_, _) => window.Close();
window.Closed += (_, _) => view.Dispose();
e.NewWindow = view.CoreWebView2;
e.Handled = true;
}
finally
{
deferral.Complete();
}
}
private void OnWebMessage(Slot slot, string json)
{
Log($"[{slot.Id}] page says: {json}");
using var doc = JsonDocument.Parse(json);
if (doc.RootElement.ValueKind == JsonValueKind.Object
&& doc.RootElement.TryGetProperty("probe", out var probe)
&& _waiters.Remove(probe.GetString() ?? "", out var waiter))
{
waiter.TrySetResult(doc.RootElement.Clone());
}
}
private Task<JsonElement> WaitForMessageAsync(string probe)
{
var tcs = new TaskCompletionSource<JsonElement>();
_waiters[probe] = tcs;
return tcs.Task.WaitAsync(TimeSpan.FromSeconds(45));
}
// ---- Governor lifecycle steps ----------------------------------------------------------------
private async Task<Slot> OpenAsync(Target target)
{
var baseId = target.Entry?.Id ?? "lab";
var n = _slots.Count(s => s.Id == baseId || s.Id.StartsWith(baseId + "#", StringComparison.Ordinal));
var slot = new Slot { Id = n == 0 ? baseId : $"{baseId}#{n + 1}", Profile = target.Profile, StartUrl = target.Url, Entry = target.Entry };
_slots.Add(slot);
var sw = Stopwatch.StartNew();
slot.View = await CreateViewAsync(slot, target.Url);
slot.State = "Active";
SlotList.SelectedItem = slot;
ShowOnly(slot);
Log($"[{slot.Id}] opened on profile '{slot.Profile}', controller ready in {sw.ElapsedMilliseconds} ms");
return slot;
}
private void ShowOnly(Slot slot)
{
foreach (var s in _slots.Where(s => s.View is not null))
{
var visible = ReferenceEquals(s, slot);
s.View!.Visibility = visible ? Visibility.Visible : Visibility.Collapsed;
if (visible)
{
s.State = "Active";
}
else if (s.State == "Active")
{
s.State = "Hidden";
}
}
SlotList.Items.Refresh();
}
private void Hide(Slot slot)
{
slot.View!.Visibility = Visibility.Collapsed;
slot.State = "Hidden";
SlotList.Items.Refresh();
}
private async Task SuspendAsync(Slot slot)
{
var core = slot.View!.CoreWebView2;
Hide(slot);
await Dispatcher.InvokeAsync(() => { }, DispatcherPriority.Background); // let IsVisible reach the controller
var sw = Stopwatch.StartNew();
var ok = await core.TrySuspendAsync();
core.MemoryUsageTargetLevel = CoreWebView2MemoryUsageTargetLevel.Low;
slot.State = ok ? "Suspended" : "Hidden (suspend refused)";
SlotList.Items.Refresh();
Log($"[{slot.Id}] TrySuspendAsync → {ok} in {sw.ElapsedMilliseconds} ms; MemoryUsageTargetLevel = Low");
}
private void Resume(Slot slot)
{
var core = slot.View!.CoreWebView2;
var sw = Stopwatch.StartNew();
core.MemoryUsageTargetLevel = CoreWebView2MemoryUsageTargetLevel.Normal;
core.Resume();
ShowOnly(slot);
Log($"[{slot.Id}] resumed (Normal + Resume + show) in {sw.Elapsed.TotalMilliseconds:F1} ms");
}
private void Hibernate(Slot slot)
{
if (slot.View is null)
{
return;
}
slot.SavedUrl = slot.View.CoreWebView2?.Source ?? slot.StartUrl;
Host.Children.Remove(slot.View);
slot.View.Dispose();
slot.View = null;
slot.ConsoleReceiver = null;
slot.LogReceiver = null;
slot.Capturing = false;
slot.State = "Hibernated";
SlotList.Items.Refresh();
Log($"[{slot.Id}] disposed; kept {{url}} = {Catalog.Redact(slot.SavedUrl)}");
}
private async Task ReopenAsync(Slot slot)
{
if (slot.View is not null)
{
return;
}
var sw = Stopwatch.StartNew();
var first = new TaskCompletionSource<bool>();
slot.View = await CreateViewAsync(slot, slot.SavedUrl ?? slot.StartUrl,
core => core.NavigationCompleted += (_, e) => first.TrySetResult(e.IsSuccess));
var controllerMs = sw.ElapsedMilliseconds;
ShowOnly(slot);
var ok = await first.Task.WaitAsync(TimeSpan.FromSeconds(60));
Log($"[{slot.Id}] reopened: controller {controllerMs} ms, first NavigationCompleted ({(ok ? "ok" : "failed")}) {sw.ElapsedMilliseconds} ms");
}
// ---- CDP console capture (spike #4) ----------------------------------------------------------
private async Task SetCaptureAsync(Slot slot, bool runtime, bool log)
{
if (slot.View?.CoreWebView2 is not { } core)
{
return;
}
if (slot.ConsoleReceiver is null)
{
slot.ConsoleReceiver = core.GetDevToolsProtocolEventReceiver("Runtime.consoleAPICalled");
slot.ConsoleReceiver.DevToolsProtocolEventReceived += (_, e) => AddConsole(slot, "console", e.ParameterObjectAsJson);
slot.LogReceiver = core.GetDevToolsProtocolEventReceiver("Log.entryAdded");
slot.LogReceiver.DevToolsProtocolEventReceived += (_, e) => AddConsole(slot, "log", e.ParameterObjectAsJson);
core.GetDevToolsProtocolEventReceiver("Runtime.exceptionThrown").DevToolsProtocolEventReceived +=
(_, e) => AddConsole(slot, "exception", e.ParameterObjectAsJson);
}
var sw = Stopwatch.StartNew();
await core.CallDevToolsProtocolMethodAsync(runtime ? "Runtime.enable" : "Runtime.disable", "{}");
await core.CallDevToolsProtocolMethodAsync(log ? "Log.enable" : "Log.disable", "{}");
slot.Capturing = runtime || log;
Log($"[{slot.Id}] console capture: Runtime {(runtime ? "on" : "off")}, Log {(log ? "on" : "off")} in {sw.ElapsedMilliseconds} ms "
+ $"(DevTools UI {(core.Settings.AreDevToolsEnabled ? "enabled" : "disabled")})");
}
private void AddConsole(Slot slot, string source, string json)
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
var text = source switch
{
"console" => $"{Str(root, "type")}: " + string.Join(" ", root.GetProperty("args").EnumerateArray()
.Select(a => a.TryGetProperty("value", out var v) ? v.ToString() : Str(a, "description"))),
"log" => $"[{Str(root.GetProperty("entry"), "source")}/{Str(root.GetProperty("entry"), "level")}] {Str(root.GetProperty("entry"), "text")}",
_ => $"uncaught: {Str(root.GetProperty("exceptionDetails"), "text")} "
+ (root.GetProperty("exceptionDetails").TryGetProperty("exception", out var ex) ? Str(ex, "description") : ""),
};
slot.AddConsole($"{DateTime.Now:HH:mm:ss.fff} {source,-9} {text}");
if (ReferenceEquals(slot, Selected))
{
ConsoleBox.Text = string.Join(Environment.NewLine, slot.ConsoleRing);
ConsoleBox.ScrollToEnd();
}
static string Str(JsonElement e, string name) => e.TryGetProperty(name, out var v) ? v.ToString() : "";
}
// ---- Memory sampling (spike #3) --------------------------------------------------------------
private async Task SampleAsync()
{
if (_sampling)
{
return;
}
_sampling = true;
try
{
var rows = new List<ProcessSample>();
if (MemorySampler.Sample(Environment.ProcessId, "Shell", "shell") is { } shell)
{
rows.Add(shell);
}
if (_env is not null)
{
try
{
var owners = await AttributeAsync();
foreach (var info in _env.GetProcessInfos())
{
if (MemorySampler.Sample(info.ProcessId, info.Kind.ToString(), owners.GetValueOrDefault(info.ProcessId, "shared")) is { } row)
{
rows.Add(row);
}
}
_browserGone = false;
}
catch (Exception ex) when (ex is FileNotFoundException or System.Runtime.InteropServices.COMException or InvalidOperationException)
{
// With every controller closed the browser process exits; the environment object stays.
if (!_browserGone)
{
Log($"No WebView2 browser process ({ex.GetType().Name}: {ex.Message.Trim()})");
_browserGone = true;
}
}
}
foreach (var slot in _slots)
{
slot.AttributedMb = rows.Where(r => r.Attributed.Split('+').Contains(slot.Id)).Sum(r => r.PrivateCommitMb);
}
MemGrid.ItemsSource = rows;
Totals.Text = $"{rows.Count} processes · Σ private commit {rows.Sum(r => r.PrivateCommitMb):F0} MB · "
+ $"Σ private WS {rows.Sum(r => r.PrivateWsMb):F0} MB · Σ WS {rows.Sum(r => r.WsMb):F0} MB · phase '{_phase}'";
if (_csv is not null)
{
var time = DateTime.Now.ToString("HH:mm:ss.fff", CultureInfo.InvariantCulture);
foreach (var r in rows)
{
_csv.WriteLine(string.Join(',', time, _phase, r.Pid, r.Kind, r.Attributed.Replace(',', ';'),
F(r.PrivateCommitMb), F(r.PrivateWsMb), F(r.WsMb), F(r.SharedCommitMb), F(r.CpuMs)));
}
}
SlotList.Items.Refresh();
}
finally
{
_sampling = false;
}
static string F(double v) => v.ToString("F1", CultureInfo.InvariantCulture);
}
/// <summary>Renderer and OOPIF processes → slot, by each frame's root (main frame) id, then by host.</summary>
private async Task<Dictionary<int, string>> AttributeAsync()
{
var owners = new Dictionary<int, string>();
foreach (var info in await _env!.GetProcessExtendedInfosAsync())
{
var names = new SortedSet<string>(StringComparer.Ordinal);
foreach (var frame in info.AssociatedFrameInfos)
{
var root = frame;
while (root.ParentFrameInfo is not null)
{
root = root.ParentFrameInfo;
}
names.Add(OwnerOf(root));
}
if (names.Count > 0)
{
owners[info.ProcessInfo.ProcessId] = string.Join('+', names);
}
else if (info.ProcessInfo.Kind == CoreWebView2ProcessKind.Renderer)
{
owners[info.ProcessInfo.ProcessId] = "renderer (no frames)";
}
}
return owners;
}
private string OwnerOf(CoreWebView2FrameInfo root)
{
var rootHost = Uri.TryCreate(root.Source, UriKind.Absolute, out var u) ? u.Host : "";
Slot? byHost = null;
foreach (var slot in _slots)
{
try
{
if (slot.View?.CoreWebView2 is not { } core)
{
continue;
}
var sameHost = Uri.TryCreate(core.Source, UriKind.Absolute, out var s) && s.Host == rootHost;
if (sameHost && core.FrameId == root.FrameId)
{
return slot.Id;
}
byHost ??= sameHost ? slot : null;
}
catch (InvalidOperationException)
{
// The view is being torn down.
}
}
return byHost?.Id ?? $"?{rootHost}";
}
private void Mark(string phase)
{
_phase = phase;
Log($"PHASE → {phase}");
}
private void StartCsv()
{
if (_csv is not null)
{
return;
}
Directory.CreateDirectory(Path.Combine(DataRoot, "memory"));
var file = Path.Combine(DataRoot, "memory", $"{DateTime.UtcNow:yyyyMMdd-HHmmss}-samples.csv");
_csv = new StreamWriter(file) { AutoFlush = true };
_csv.WriteLine("time,phase,pid,kind,attributed,private_commit_mb,private_ws_mb,ws_mb,shared_commit_mb,cpu_ms");
RecordButton.Content = "Stop CSV";
Log($"CSV → {file}");
}
private void StopCsv()
{
_csv?.Dispose();
_csv = null;
RecordButton.Content = "Start CSV";
Log("CSV stopped");
}
private async Task RunLadderAsync(Slot slot, TimeSpan phase)
{
StartCsv();
Mark($"{slot.Id}:active");
ShowOnly(slot);
await Task.Delay(phase);
Mark($"{slot.Id}:hidden");
Hide(slot);
await Task.Delay(phase / 2);
Mark($"{slot.Id}:suspended");
await SuspendAsync(slot);
await Task.Delay(phase);
Mark($"{slot.Id}:resumed");
Resume(slot);
await Task.Delay(phase / 2);
Mark($"{slot.Id}:hibernated");
Hibernate(slot);
await Task.Delay(phase / 2);
Mark($"{slot.Id}:reopened");
await ReopenAsync(slot);
await Task.Delay(phase);
Mark("-");
Log($"[{slot.Id}] ladder done");
}
// ---- Unattended checks: `WebLab.exe --auto` ---------------------------------------------------
private async Task RunAutoAsync()
{
var targets = (List<Target>)Targets.ItemsSource;
try
{
StartCsv();
Mark("auto:shell-only");
await Task.Delay(TimeSpan.FromSeconds(6));
// Spike #1: which key systems the runtime exposes.
Mark("auto:eme");
var emeWait = WaitForMessageAsync("eme");
var eme = await OpenAsync(targets[0]);
var emeResult = await emeWait;
foreach (var r in emeResult.GetProperty("results").EnumerateArray())
{
Log($"EME {r.GetProperty("keySystem").GetString()} [{r.GetProperty("robustness").GetString()}]: "
+ $"{(r.GetProperty("available").GetBoolean() ? "AVAILABLE" : "no")} — {r.GetProperty("detail").GetString()}");
}
// Spike #4: detection and capture with DevTools UI disabled (the release setting).
Mark("auto:cdp");
var cdpWait = WaitForMessageAsync("cdp-detect");
var cdp = await OpenAsync(targets[2]);
Log($"CDP detect, capture off: {(await cdpWait).GetProperty("detected")}");
foreach (var (runtime, log, label) in new[] { (true, true, "Runtime+Log"), (false, true, "Log only"), (false, false, "off") })
{
await SetCaptureAsync(cdp, runtime, log);
var before = cdp.ConsoleRing.Count;
var wait = WaitForMessageAsync("cdp-detect");
await cdp.View!.CoreWebView2.ExecuteScriptAsync(
"check(); console.log('ring-test', 42); console.warn('ring-warn'); setTimeout(() => { throw new Error('ring-throw'); });"
+ "fetch('https://weblab.example/missing.json').catch(() => {});");
var detected = (await wait).GetProperty("detected");
await Task.Delay(1000);
Log($"CDP detect, capture {label}: {detected}; ring buffer +{cdp.ConsoleRing.Count - before} entries");
}
Log("Ring buffer contents:" + Environment.NewLine + string.Join(Environment.NewLine, cdp.ConsoleRing));
// Spike #3 dry run: environment baseline and a short ladder on a public page (not signed in).
Hibernate(eme);
Hibernate(cdp);
Mark("auto:env-only");
await Task.Delay(TimeSpan.FromSeconds(10));
var youtube = targets.FirstOrDefault(t => t.Entry?.Id == "youtube");
if (youtube is not null)
{
await RunLadderAsync(await OpenAsync(youtube), TimeSpan.FromSeconds(20));
}
}
catch (Exception ex)
{
Log($"AUTO FAILED: {ex}");
}
finally
{
StopCsv();
await Task.Delay(500);
Close();
}
}
// ---- UI handlers -----------------------------------------------------------------------------
private async void OnOpen(object sender, RoutedEventArgs e)
{
if (Targets.SelectedItem is Target target)
{
await OpenAsync(target);
}
}
private void OnShow(object sender, RoutedEventArgs e)
{
if (Selected is { View: not null } slot)
{
ShowOnly(slot);
}
}
private void OnHide(object sender, RoutedEventArgs e)
{
if (Selected is { View: not null } slot)
{
Hide(slot);
}
}
private async void OnSuspend(object sender, RoutedEventArgs e)
{
if (Selected is { View: not null } slot)
{
await SuspendAsync(slot);
}
}
private void OnResume(object sender, RoutedEventArgs e)
{
if (Selected is { View: not null } slot)
{
Resume(slot);
}
}
private void OnHibernate(object sender, RoutedEventArgs e)
{
if (Selected is { } slot)
{
Hibernate(slot);
}
}
private async void OnReopen(object sender, RoutedEventArgs e)
{
if (Selected is { View: null } slot)
{
await ReopenAsync(slot);
}
}
private async void OnCaptureFull(object sender, RoutedEventArgs e)
{
if (Selected is { } slot)
{
await SetCaptureAsync(slot, runtime: true, log: true);
}
}
private async void OnCaptureLogOnly(object sender, RoutedEventArgs e)
{
if (Selected is { } slot)
{
await SetCaptureAsync(slot, runtime: false, log: true);
}
}
private async void OnCaptureOff(object sender, RoutedEventArgs e)
{
if (Selected is { } slot)
{
await SetCaptureAsync(slot, runtime: false, log: false);
}
}
private void OnCloseSlot(object sender, RoutedEventArgs e)
{
if (Selected is { } slot)
{
Hibernate(slot);
_slots.Remove(slot);
}
}
private async void OnLadder(object sender, RoutedEventArgs e)
{
if (Selected is not { View: not null } slot)
{
Log("Select an open slot first.");
return;
}
var seconds = int.TryParse(PhaseSeconds.Text, out var s) && s > 0 ? s : 60;
await RunLadderAsync(slot, TimeSpan.FromSeconds(seconds));
}
private void OnHibernateAll(object sender, RoutedEventArgs e)
{
foreach (var slot in _slots)
{
Hibernate(slot);
}
}
private void OnRecord(object sender, RoutedEventArgs e)
{
if (_csv is null)
{
StartCsv();
}
else
{
StopCsv();
}
}
private void OnMark(object sender, RoutedEventArgs e) => Mark(string.IsNullOrWhiteSpace(MarkText.Text) ? "-" : MarkText.Text.Trim());
private void OnSlotSelected(object sender, SelectionChangedEventArgs e) =>
ConsoleBox.Text = Selected is { } slot ? string.Join(Environment.NewLine, slot.ConsoleRing) : "";
private void Log(string line)
{
var stamped = $"{DateTime.Now:HH:mm:ss.fff} {line}";
_logFile.WriteLine(stamped);
LogBox.AppendText(stamped + Environment.NewLine);
LogBox.ScrollToEnd();
}
}
+82
View File
@@ -0,0 +1,82 @@
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace WebLab;
/// <summary>One process in one sample. All sizes in MiB.</summary>
public sealed record ProcessSample(
int Pid, string Kind, string Attributed, double PrivateCommitMb, double PrivateWsMb, double WsMb, double SharedCommitMb, double CpuMs);
/// <summary>
/// The three candidate governor metrics side by side (docs/RAM-GOVERNOR.md §4): private commit
/// (Process.PrivateMemorySize64), private working set (PROCESS_MEMORY_COUNTERS_EX2) and working set.
/// </summary>
public static class MemorySampler
{
private const uint ProcessQueryLimitedInformation = 0x1000;
private const uint ProcessVmRead = 0x0010;
private const double MiB = 1024 * 1024;
public static ProcessSample? Sample(int pid, string kind, string attributed)
{
try
{
using var process = Process.GetProcessById(pid);
var privateCommit = process.PrivateMemorySize64 / MiB;
var ws = process.WorkingSet64 / MiB;
double privateWs = double.NaN, sharedCommit = double.NaN, cpuMs = double.NaN;
using var handle = OpenProcess(ProcessQueryLimitedInformation | ProcessVmRead, false, pid) is { IsInvalid: false } h
? h
: OpenProcess(ProcessQueryLimitedInformation, false, pid);
if (!handle.IsInvalid)
{
var counters = new ProcessMemoryCountersEx2 { Cb = (uint)Marshal.SizeOf<ProcessMemoryCountersEx2>() };
if (GetProcessMemoryInfo(handle, ref counters, counters.Cb))
{
privateWs = counters.PrivateWorkingSetSize / MiB;
sharedCommit = counters.SharedCommitUsage / MiB;
}
if (GetProcessTimes(handle, out _, out _, out var kernel, out var user))
{
cpuMs = (kernel + user) / 10_000.0;
}
}
return new ProcessSample(pid, kind, attributed, privateCommit, privateWs, ws, sharedCommit, cpuMs);
}
catch (Exception ex) when (ex is ArgumentException or InvalidOperationException or System.ComponentModel.Win32Exception)
{
return null; // exited between enumeration and sampling
}
}
[StructLayout(LayoutKind.Sequential)]
private struct ProcessMemoryCountersEx2
{
public uint Cb;
public uint PageFaultCount;
public nuint PeakWorkingSetSize;
public nuint WorkingSetSize;
public nuint QuotaPeakPagedPoolUsage;
public nuint QuotaPagedPoolUsage;
public nuint QuotaPeakNonPagedPoolUsage;
public nuint QuotaNonPagedPoolUsage;
public nuint PagefileUsage;
public nuint PeakPagefileUsage;
public nuint PrivateUsage;
public nuint PrivateWorkingSetSize;
public ulong SharedCommitUsage;
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern SafeProcessHandle OpenProcess(uint desiredAccess, bool inheritHandle, int processId);
[DllImport("psapi.dll", SetLastError = true)]
private static extern bool GetProcessMemoryInfo(SafeProcessHandle process, ref ProcessMemoryCountersEx2 counters, uint size);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool GetProcessTimes(SafeProcessHandle process, out long creation, out long exit, out long kernel, out long user);
}
+43
View File
@@ -0,0 +1,43 @@
namespace WebLab;
/// <summary>One open web app: the lab's stand-in for a governed web module.</summary>
public sealed class Slot
{
public required string Id { get; init; }
public required string Profile { get; init; }
public required string StartUrl { get; init; }
public CatalogEntry? Entry { get; init; }
public WebView2? View { get; set; }
public string State { get; set; } = "Created";
/// <summary>The only thing kept across hibernation (docs/RAM-GOVERNOR.md §1).</summary>
public string? SavedUrl { get; set; }
public bool Capturing { get; set; }
public CoreWebView2DevToolsProtocolEventReceiver? ConsoleReceiver { get; set; }
public CoreWebView2DevToolsProtocolEventReceiver? LogReceiver { get; set; }
public Queue<string> ConsoleRing { get; } = new();
public double AttributedMb { get; set; }
public void AddConsole(string line)
{
// The SPEC's 200-entry ring buffer per app.
if (ConsoleRing.Count == 200)
{
ConsoleRing.Dequeue();
}
ConsoleRing.Enqueue(line);
}
public override string ToString() => $"{Id} [{Profile}] {State} · {AttributedMb:F0} MB";
}
+19
View File
@@ -0,0 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk">
<!-- Spikes #1–#4 (issues #2–#5): DRM, sign-in, memory ladder, CDP console capture in WebView2. -->
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net10.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.4314.35" />
</ItemGroup>
<ItemGroup>
<None Update="LabPages\**\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
</Project>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

@@ -1,77 +0,0 @@
using System.Windows;
using System.Windows.Interop;
using Microsoft.Extensions.DependencyInjection;
using OmniDeck.App.Diagnostics;
using OmniDeck.App.Settings;
using OmniDeck.App.Shell;
using OmniDeck.App.Theming;
using OmniDeck.App.Updates;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Reports;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Web.Apps;
using OmniDeck.Web.Catalog;
using OmniDeck.Web.Diagnostics;
using OmniDeck.Web.Runtime;
using Serilog;
using Wpf.Ui;
namespace OmniDeck.App.Composition;
/// <summary>Registers the WPF shell's services on top of <c>AddOmniDeckCore</c>.</summary>
internal static class OdAppServiceCollectionExtensions
{
public static IServiceCollection AddOmniDeckApp(this IServiceCollection services)
{
// WPF-UI's dialog and snackbar services; the main window hands them their hosts.
services.AddSingleton<IContentDialogService, ContentDialogService>();
services.AddSingleton<ISnackbarService, SnackbarService>();
services.AddSingleton<OdDialogs>();
services.AddSingleton<OdBugReportRequests>();
services.AddSingleton<OdBugReports>();
services.AddSingleton<OdBugReporter>();
services.AddSingleton<OdBugReportFlow>();
services.AddSingleton<OdMessageBoxErrorPresenter>();
services.AddSingleton<IOdErrorPresenter, OdDialogErrorPresenter>();
services.AddSingleton<OdCrashHandler>();
services.AddSingleton<OdThemeEngine>();
services.AddSingleton<OdTrayNotifier>();
services.AddSingleton<IOdNotifier>(provider => provider.GetRequiredService<OdTrayNotifier>());
services.AddSingleton<IOdAppLifetime, OdAppLifetime>();
services.AddSingleton<OdShellViewModel>();
services.AddSingleton<OdMemoryViewModel>();
services.AddSingleton<IOdUpdateService, OdVelopackUpdateService>();
services.AddSingleton<OdUpdateWatcher>();
services.AddSingleton<IOdStartupRegistration>(_ => new OdRunKeyStartup());
services.AddSingleton(provider => new OdAboutViewModel(provider.GetRequiredService<IOdUpdateService>(), OdExternal.Open));
services.AddSingleton(provider => new OdWebAppsViewModel(
provider.GetRequiredService<OdCatalogService>(),
provider.GetRequiredService<OdWebPreferences>(),
provider.GetRequiredService<IOdSettingsService>(),
provider.GetRequiredService<OdModuleHost>(),
provider.GetRequiredService<OdSignInHealth>(),
profile => provider.GetRequiredService<OdWebRuntime>().ClearProfileAsync(profile, MainWindowHandle()),
apps => provider.GetRequiredService<OdDialogs>().ConfirmAsync(
OdLocalization.Get("WebApps_ClearTitle"),
OdLocalization.Format("WebApps_ClearMessage", apps),
OdLocalization.Get("WebApps_ClearConfirm")),
provider.GetRequiredService<ILogger>()));
services.AddSingleton(provider => new OdSettingsViewModel(
provider.GetRequiredService<IOdSettingsService>(),
provider.GetRequiredService<IOdStartupRegistration>(),
provider.GetRequiredService<OdDataRoot>(),
provider.GetRequiredService<OdMemoryViewModel>(),
provider.GetRequiredService<OdWebAppsViewModel>(),
provider.GetRequiredService<OdAboutViewModel>(),
OdExternal.OpenFolder));
services.AddSingleton<OdMainWindow>();
return services;
}
// The hidden browser that clears a profile needs a window; Settings is in the main one.
private static nint MainWindowHandle() => new WindowInteropHelper(Application.Current.MainWindow).Handle;
}
@@ -1,10 +0,0 @@
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Shows the user that something failed: an in-window dialog once the main window is up
/// (<see cref="OdDialogErrorPresenter"/>), a message box before that.
/// </summary>
internal interface IOdErrorPresenter
{
void Show(string message);
}
@@ -1,72 +0,0 @@
using System.ComponentModel;
using System.IO;
using OmniDeck.App.Settings;
using OmniDeck.App.Shell;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Reports;
using Serilog;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Reporting a bug (docs/legal/PRIVACY.md §3): the report is previewed in a dialog. On the user's
/// say-so it is saved as a zip, File Explorer shows it, and the browser opens a new GitHub issue with
/// the form's short fields filled in. Nothing is uploaded: the user attaches the zip.
/// </summary>
public sealed class OdBugReportFlow(OdDialogs dialogs, OdBugReporter reporter, OdBugReports reports, OdModuleHost host, ILogger log)
{
/// <summary>Where new issues are filed.</summary>
public const string NewIssue = OdAboutViewModel.Repository + "/issues/new";
private readonly ILogger _log = log.ForContext<OdBugReportFlow>();
/// <summary>The new-issue page with the form's short fields filled in; the long ones are in the zip's issue.md.</summary>
public static Uri IssueUrl(OdBugReport report)
{
ArgumentNullException.ThrowIfNull(report);
return new Uri(NewIssue
+ "?template=bug_report.yml"
+ "&version=" + Uri.EscapeDataString(report.Version)
+ "&os=" + Uri.EscapeDataString(report.Windows)
+ "&preset=" + Uri.EscapeDataString(report.Preset)
+ "&module=" + Uri.EscapeDataString(report.Subject));
}
/// <summary>Shows the dialog; <paramref name="error"/> is the error OmniDeck showed, when the report comes from it.</summary>
public async Task ShowAsync(string? error)
{
if (!dialogs.CanShow)
{
return;
}
var model = new OdBugReportViewModel(reporter, host.Current?.Info.Id ?? "", error);
var answer = await dialogs.ShowAsync(new ContentDialog
{
Title = OdLocalization.Get("Report_Title"),
Content = new OdBugReportView { DataContext = model },
PrimaryButtonText = OdLocalization.Get("Report_Save"),
CloseButtonText = OdLocalization.Get("Dialog_Cancel"),
DefaultButton = ContentDialogButton.Primary,
DialogMaxWidth = 760,
});
if (answer != ContentDialogResult.Primary)
{
return;
}
try
{
var path = reports.Save(model.Report);
_log.Information("Saved a bug report as {File}", Path.GetFileName(path));
OdExternal.ShowFile(path);
OdExternal.Open(IssueUrl(model.Report));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or Win32Exception)
{
_log.Warning(ex, "The bug report could not be saved or shown");
}
}
}
@@ -1,7 +0,0 @@
namespace OmniDeck.App.Diagnostics;
/// <summary>A bug report was asked for, about <see cref="Error"/> when it came from the error dialog.</summary>
public sealed class OdBugReportRequestedEventArgs(string? error) : EventArgs
{
public string? Error { get; } = error;
}
@@ -1,12 +0,0 @@
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Where the error dialog asks for a bug report about the error it showed; the main window, which
/// shows the report dialog, answers. It keeps the crash handler free of the report's many services.
/// </summary>
public sealed class OdBugReportRequests
{
public event EventHandler<OdBugReportRequestedEventArgs>? Requested;
public void Request(string? error) => Requested?.Invoke(this, new OdBugReportRequestedEventArgs(error));
}
@@ -1,25 +0,0 @@
<UserControl x:Class="OmniDeck.App.Diagnostics.OdBugReportView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:res="clr-namespace:OmniDeck.Core.Localization;assembly=OmniDeck.Core">
<StackPanel>
<TextBlock Margin="{DynamicResource Od.Margin.Item}"
Text="{res:OdLoc Report_Intro}"
TextWrapping="Wrap" />
<TextBlock Margin="{DynamicResource Od.Padding.Control}" Text="{res:OdLoc Report_Subject}" />
<ComboBox Margin="{DynamicResource Od.Margin.Item}"
AutomationProperties.Name="{res:OdLoc Report_Subject}"
ItemsSource="{Binding Subjects}"
SelectedValue="{Binding Subject}"
SelectedValuePath="Value" />
<TextBlock Margin="{DynamicResource Od.Padding.Control}" Text="{res:OdLoc Report_Preview}" />
<TextBox Height="280"
AutomationProperties.Name="{res:OdLoc Report_Preview}"
FontFamily="Consolas"
HorizontalScrollBarVisibility="Auto"
IsReadOnly="True"
Text="{Binding Preview, Mode=OneWay}"
TextWrapping="NoWrap"
VerticalScrollBarVisibility="Auto" />
</StackPanel>
</UserControl>
@@ -1,10 +0,0 @@
namespace OmniDeck.App.Diagnostics;
/// <summary>The bug-report dialog's content, bound to <see cref="OdBugReportViewModel"/>.</summary>
public partial class OdBugReportView
{
public OdBugReportView()
{
InitializeComponent();
}
}
@@ -1,44 +0,0 @@
using CommunityToolkit.Mvvm.ComponentModel;
using OmniDeck.App.Settings;
using OmniDeck.Core.Reports;
namespace OmniDeck.App.Diagnostics;
/// <summary>The bug-report dialog: what the report is about, and the issue text it will carry.</summary>
public sealed partial class OdBugReportViewModel : ObservableObject
{
private readonly OdBugReporter _reporter;
private readonly string? _error;
[ObservableProperty]
private string _subject;
[ObservableProperty]
private string _preview;
/// <summary>The dialog's model, about <paramref name="subject"/> to begin with.</summary>
/// <param name="reporter">Composes the report.</param>
/// <param name="subject">The module the report starts out about; empty for OmniDeck in general.</param>
/// <param name="error">The error OmniDeck showed, when the report comes from the error dialog.</param>
public OdBugReportViewModel(OdBugReporter reporter, string subject, string? error)
{
ArgumentNullException.ThrowIfNull(reporter);
_reporter = reporter;
_error = error;
Subjects = reporter.Subjects();
_subject = Subjects.Any(choice => string.Equals(choice.Value, subject, StringComparison.Ordinal)) ? subject : "";
Report = reporter.Compose(_subject, error);
_preview = Report.Issue;
}
public IReadOnlyList<OdChoice<string>> Subjects { get; }
/// <summary>The report as it stands, for the subject chosen.</summary>
public OdBugReport Report { get; private set; }
partial void OnSubjectChanged(string value)
{
Report = _reporter.Compose(value, _error);
Preview = Report.Issue;
}
}
@@ -1,200 +0,0 @@
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.Json;
using Microsoft.Win32;
using OmniDeck.App.Settings;
using OmniDeck.Core;
using OmniDeck.Core.Governor;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Reports;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Web.Apps;
using OmniDeck.Web.Catalog;
using OmniDeck.Web.Diagnostics;
using OmniDeck.Web.Runtime;
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Puts a bug report together (docs/legal/PRIVACY.md §3): OmniDeck's version, Windows' build, the UI
/// preset, the modules and what they use, the end of the log and, for a web app, its console, each
/// passed through <see cref="OdScrubber"/>. Used from the UI thread.
/// </summary>
public sealed class OdBugReporter(
IOdSettingsService settings,
OdModuleHost host,
OdRamGovernor governor,
OdDataRoot dataRoot,
OdCatalog catalog,
OdSignInHealth health,
TimeProvider time)
{
/// <summary>How many log lines a report carries.</summary>
public const int LogLines = 500;
private static readonly OdVersionInfo Version = OdVersionInfo.FromAssembly(typeof(OdBugReporter).Assembly);
/// <summary>What a report can be about: OmniDeck in general, then each module.</summary>
public IReadOnlyList<OdChoice<string>> Subjects() =>
[new("", OdLocalization.Get("Report_General")), .. host.Modules.Select(hosted => new OdChoice<string>(hosted.Info.Id, hosted.Info.Title))];
/// <summary>A report about the module <paramref name="subjectId"/> (empty: OmniDeck in general), with the error OmniDeck showed, if any.</summary>
public OdBugReport Compose(string subjectId, string? error)
{
ArgumentNullException.ThrowIfNull(subjectId);
var hosted = subjectId.Length > 0 ? host.Find(subjectId) : null;
var web = hosted?.Module as OdWebAppModule;
var subject = hosted?.Info.Title ?? OdLocalization.Get("Report_General");
var windows = WindowsVersion();
var preset = settings.Current.Preset;
var errors = web is null ? "" : OdConsoleLog.Write(web.Console.Errors);
return new OdBugReport
{
Version = Version.DisplayText,
Windows = windows,
Preset = preset,
Subject = subject,
Issue = OdScrubber.Scrub(Issue(windows, preset, subject, errors, error)),
SystemInfo = OdScrubber.Scrub(SystemInfo(windows, preset)),
Logs = OdScrubber.Scrub(LogTail()),
ConsoleLog = web is null ? null : OdScrubber.Scrub(OdConsoleLog.Write(web.Console.All)),
ConsoleOf = web?.Info.Id,
};
}
/// <summary>Windows' version and build, as the bug form asks for them.</summary>
internal static string WindowsVersion()
{
using var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
var display = key?.GetValue("DisplayVersion") as string;
var build = key?.GetValue("CurrentBuild") as string ?? Environment.OSVersion.Version.Build.ToString(CultureInfo.InvariantCulture);
var revision = key?.GetValue("UBR") is int ubr ? "." + ubr.ToString(CultureInfo.InvariantCulture) : "";
return string.IsNullOrEmpty(display) ? $"Windows 11 ({build}{revision})" : $"Windows 11 {display} ({build}{revision})";
}
private string Issue(string windows, string preset, string subject, string consoleErrors, string? error)
{
var issue = new StringBuilder();
Section(issue, "OmniDeck version", Version.DisplayText);
Section(issue, "Windows version / build", windows);
Section(issue, "UI preset", preset);
Section(issue, "Affected module / web app", subject);
Section(issue, "What happened, and what did you expect?", "_What you did, what happened, and what you expected instead._");
Section(issue, "Console errors", consoleErrors.Length == 0 ? "_None captured._" : "```text\n" + consoleErrors + "\n```");
if (error is not null)
{
Section(issue, "The error OmniDeck showed", "```text\n" + error + "\n```");
}
var snapshot = governor.Snapshot;
var now = time.GetUtcNow();
var modules = new StringBuilder("| Module | State | Hidden for | Memory |\n|---|---|---|---|\n");
foreach (var module in host.Modules.Where(module => module.State != OdModuleState.Created))
{
var hidden = module.State == OdModuleState.Active ? "" : ((int)(now - module.LastActive).TotalMinutes).ToString(CultureInfo.InvariantCulture) + " min";
var memory = snapshot?.For(module.Info.Id) is { } bytes ? OdBytes.Format(bytes) : "";
modules.Append(CultureInfo.InvariantCulture, $"| {module.Info.Title} | {module.State} | {hidden} | {memory} |\n");
}
Section(issue, "Modules", modules.ToString().TrimEnd());
return issue.ToString();
}
private static void Section(StringBuilder issue, string heading, string body) =>
issue.Append("### ").Append(heading).Append("\n\n").Append(body).Append("\n\n");
private string SystemInfo(string windows, string preset)
{
using var stream = new MemoryStream();
using (var json = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
json.WriteStartObject();
json.WriteString("version", Version.Version);
json.WriteString("commit", Version.Commit);
json.WriteString("windows", windows);
json.WriteString("webView2", OdWebRuntime.InstalledVersion());
json.WriteString("preset", preset);
json.WriteString("language", CultureInfo.CurrentUICulture.Name);
json.WriteString("catalog", catalog.Updated);
WriteMemory(json);
json.WriteStartArray("modules");
var now = time.GetUtcNow();
foreach (var module in host.Modules)
{
json.WriteStartObject();
json.WriteString("id", module.Info.Id);
json.WriteString("state", module.State.ToString());
json.WriteNumber("hiddenMinutes", module.State is OdModuleState.Created or OdModuleState.Active ? 0 : (int)(now - module.LastActive).TotalMinutes);
if (governor.Snapshot?.For(module.Info.Id) is { } bytes)
{
json.WriteNumber("memoryBytes", bytes);
}
json.WriteEndObject();
}
json.WriteEndArray();
json.WriteStartObject("signInCookies");
foreach (var profile in catalog.Apps.Select(app => app.Profile).Distinct(StringComparer.Ordinal))
{
if (health.Kept(profile) is { } count)
{
json.WriteNumber(profile, count);
}
}
json.WriteEndObject();
json.WriteEndObject();
}
return Encoding.UTF8.GetString(stream.ToArray());
}
private void WriteMemory(Utf8JsonWriter json)
{
var options = governor.Options;
json.WriteStartObject("memory");
json.WriteNumber("committedBytes", governor.CommittedBytes);
if (governor.Snapshot is { } snapshot)
{
json.WriteNumber("shellBytes", snapshot.ShellBytes);
json.WriteNumber("sharedBytes", snapshot.SharedBytes);
}
json.WriteNumber("softCapBytes", options.SoftCapBytes);
json.WriteNumber("hardCapBytes", options.HardCapBytes);
json.WriteEndObject();
}
/// <summary>The last <see cref="LogLines"/> lines of the logs, newest file last.</summary>
private string LogTail()
{
var lines = new List<string>();
var files = Directory.Exists(dataRoot.LogsDirectory)
? Directory.GetFiles(dataRoot.LogsDirectory, "omnideck-*.log").OrderByDescending(File.GetLastWriteTimeUtc).ToList()
: [];
foreach (var file in files.TakeWhile(_ => lines.Count < LogLines))
{
lines.InsertRange(0, ReadShared(file).TakeLast(LogLines - lines.Count));
}
return string.Join("\n", lines);
}
// The log is open for writing; read it without getting in the way.
private static List<string> ReadShared(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
using var reader = new StreamReader(stream);
var lines = new List<string>();
while (reader.ReadLine() is { } line)
{
lines.Add(line);
}
return lines;
}
}
@@ -1,148 +0,0 @@
using System.Globalization;
using System.Windows;
using OmniDeck.Core.Localization;
using Serilog;
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Global failure handling (docs/ARCHITECTURE.md §6): every unhandled exception is logged; one on the
/// UI thread is shown with a support code that matches the log entry, and OmniDeck keeps running.
/// A failure that repeats is reported once per <see cref="RepeatWindow"/> and only counted in between:
/// a control stuck in a loop once threw the same exception thousands of times a second, and each one
/// was logged in full and wanted a dialog of its own. The bug-report flow (P2) hangs off the same dialog.
/// </summary>
internal sealed class OdCrashHandler
{
/// <summary>How long a repeat of a reported failure is only counted.</summary>
internal static readonly TimeSpan RepeatWindow = TimeSpan.FromMinutes(1);
private readonly ILogger _log;
private readonly IOdErrorPresenter _presenter;
private readonly TimeProvider _time;
private readonly Lock _gate = new();
private readonly Dictionary<uint, Reported> _reported = [];
private int _showing;
public OdCrashHandler(ILogger log, IOdErrorPresenter presenter, TimeProvider time)
{
_log = log.ForContext<OdCrashHandler>();
_presenter = presenter;
_time = time;
}
public void Hook(Application app)
{
app.DispatcherUnhandledException += (_, e) =>
{
HandleUiException(e.Exception);
e.Handled = true;
};
AppDomain.CurrentDomain.UnhandledException += (_, e) => HandleFatal(e.ExceptionObject as Exception, e.IsTerminating);
TaskScheduler.UnobservedTaskException += (_, e) =>
{
HandleUnobserved(e.Exception);
e.SetObserved();
};
}
/// <summary>A short code the user can quote; it is logged next to the exception.</summary>
internal static string SupportCode(Exception exception, DateTimeOffset when) =>
string.Create(CultureInfo.InvariantCulture, $"{when:yyMMdd-HHmm}-{Fingerprint(exception) % 0x10000:X4}");
/// <summary>A UI-thread failure: logged, shown with its support code; the app keeps running.</summary>
/// <returns>The support code.</returns>
internal string HandleUiException(Exception exception)
{
var now = _time.GetLocalNow();
var code = SupportCode(exception, now);
if (!ShouldReport(exception, now, out var repeats))
{
return code;
}
if (repeats > 0)
{
_log.Error(exception, "Unhandled UI exception, support code {SupportCode}; it repeated {Repeats} times since the last report", code, repeats);
}
else
{
_log.Error(exception, "Unhandled UI exception, support code {SupportCode}", code);
}
// A failure inside the dialog itself must not stack dialogs.
if (Interlocked.Exchange(ref _showing, 1) == 0)
{
try
{
_presenter.Show(OdLocalization.Format("Error_UiMessage", code, exception.Message));
}
finally
{
Volatile.Write(ref _showing, 0);
}
}
return code;
}
internal void HandleFatal(Exception? exception, bool terminating)
{
_log.Fatal(exception, "Unhandled exception (terminating: {Terminating})", terminating);
Log.CloseAndFlush();
}
internal void HandleUnobserved(Exception exception)
{
if (!ShouldReport(exception, _time.GetLocalNow(), out var repeats))
{
return;
}
if (repeats > 0)
{
_log.Error(exception, "Unobserved task exception; it repeated {Repeats} times since the last report", repeats);
}
else
{
_log.Error(exception, "Unobserved task exception");
}
}
// FNV-1a over the exception type and message: stable for the same failure, cheap, and free of
// anything personal.
private static uint Fingerprint(Exception exception)
{
var hash = 2166136261u;
foreach (var c in exception.GetType().FullName + exception.Message)
{
hash = (hash ^ c) * 16777619u;
}
return hash;
}
/// <summary>
/// Whether to report <paramref name="exception"/> now. A repeat within <see cref="RepeatWindow"/> of
/// its last report is only counted; <paramref name="repeats"/> is the count since that report.
/// </summary>
private bool ShouldReport(Exception exception, DateTimeOffset now, out int repeats)
{
var fingerprint = Fingerprint(exception);
lock (_gate)
{
if (_reported.TryGetValue(fingerprint, out var last) && now - last.At < RepeatWindow)
{
_reported[fingerprint] = last with { Repeats = last.Repeats + 1 };
repeats = 0;
return false;
}
repeats = last?.Repeats ?? 0;
_reported[fingerprint] = new Reported(now, 0);
return true;
}
}
private sealed record Reported(DateTimeOffset At, int Repeats);
}
@@ -1,36 +0,0 @@
using OmniDeck.App.Shell;
using OmniDeck.Core.Localization;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Diagnostics;
/// <summary>Shows errors in an in-window dialog, or in a message box while no dialog can show.</summary>
internal sealed class OdDialogErrorPresenter(OdDialogs dialogs, OdMessageBoxErrorPresenter fallback, OdBugReportRequests reports) : IOdErrorPresenter
{
public void Show(string message)
{
if (!dialogs.CanShow)
{
fallback.Show(message);
return;
}
_ = ShowAsync(message);
}
private async Task ShowAsync(string message)
{
var answer = await dialogs.ShowAsync(new ContentDialog
{
Title = OdLocalization.Get("Error_Title"),
Content = message,
SecondaryButtonText = OdLocalization.Get("Error_Report"),
CloseButtonText = OdLocalization.Get("Dialog_OK"),
DefaultButton = ContentDialogButton.Close,
});
if (answer == ContentDialogResult.Secondary)
{
reports.Request(message);
}
}
}
-35
View File
@@ -1,35 +0,0 @@
using OmniDeck.Core.Storage;
using Serilog;
using Serilog.Events;
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Serilog to rolling files under the data root's <c>logs\</c> folder, kept for seven days
/// (docs/SPEC.md §5). The age limit decides what goes: a count limit alone would let a burst of
/// errors, which rolls a new file every 10 MB, push out the week before it. Nothing leaves the
/// machine; bug reports attach a tail of these files only when the user asks for one.
/// </summary>
internal static class OdLogging
{
private const string Template = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}";
public static ILogger CreateLogger(OdDataRoot dataRoot) =>
new LoggerConfiguration()
#if DEBUG
.MinimumLevel.Debug()
#else
.MinimumLevel.Information()
#endif
.MinimumLevel.Override("System", LogEventLevel.Warning)
.WriteTo.File(
System.IO.Path.Combine(dataRoot.LogsDirectory, "omnideck-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 31,
retainedFileTimeLimit: TimeSpan.FromDays(7),
fileSizeLimitBytes: 10 * 1024 * 1024,
rollOnFileSizeLimit: true,
outputTemplate: Template,
formatProvider: System.Globalization.CultureInfo.InvariantCulture)
.CreateLogger();
}
@@ -1,10 +0,0 @@
using System.Windows;
namespace OmniDeck.App.Diagnostics;
/// <summary>The fallback presenter: a plain message box, which works before any window exists.</summary>
internal sealed class OdMessageBoxErrorPresenter : IOdErrorPresenter
{
public void Show(string message) =>
MessageBox.Show(message, "OmniDeck", MessageBoxButton.OK, MessageBoxImage.Warning);
}
-4
View File
@@ -1,4 +0,0 @@
namespace OmniDeck.App.Legal;
/// <summary>One legal document as the gate shows it: its title and its Markdown text.</summary>
public sealed record OdLegalPage(string Title, string Markdown);
@@ -1,64 +0,0 @@
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OmniDeck.Core.Legal;
using OmniDeck.Core.Localization;
namespace OmniDeck.App.Legal;
/// <summary>
/// The legal gate (docs/SPEC.md §2): the shipped documents, a "read them" check, and Continue or
/// Quit. Continue records the acknowledgment; it is not a condition of the GPL. With
/// <c>readOnly</c>, the same documents open from About, with nothing to acknowledge.
/// </summary>
public sealed partial class OdLegalViewModel : ObservableObject
{
private readonly OdLegalGate _gate;
[ObservableProperty]
[NotifyCanExecuteChangedFor(nameof(ContinueCommand))]
private bool _hasRead;
public OdLegalViewModel(OdLegalGate gate, string legalFolder, bool readOnly = false)
{
ArgumentNullException.ThrowIfNull(gate);
ArgumentNullException.ThrowIfNull(legalFolder);
_gate = gate;
IsReadOnly = readOnly;
Pages = [.. OdLegal.Documents.Select(document => new OdLegalPage(OdLocalization.Get(document.TitleKey), Read(Path.Combine(legalFolder, document.FileName))))];
}
/// <summary>Raised when the user continues or quits; <see cref="Accepted"/> says which.</summary>
public event EventHandler? Finished;
public IReadOnlyList<OdLegalPage> Pages { get; }
public bool IsReadOnly { get; }
public bool AsksForAcknowledgment => !IsReadOnly;
/// <summary>"Quit" at the gate; "Close" when the documents were opened to read them again.</summary>
public string QuitText => IsReadOnly ? OdLocalization.Get("Legal_Close") : OdLocalization.Get("Legal_Quit");
/// <summary>True after Continue, false after Quit, null while undecided.</summary>
public bool? Accepted { get; private set; }
private static string Read(string path) =>
File.Exists(path) ? File.ReadAllText(path) : OdLocalization.Format("Legal_Missing", Path.GetFileName(path));
[RelayCommand(CanExecute = nameof(HasRead))]
private void Continue()
{
_gate.Acknowledge();
Finish(accepted: true);
}
[RelayCommand]
private void Quit() => Finish(accepted: false);
private void Finish(bool accepted)
{
Accepted = accepted;
Finished?.Invoke(this, EventArgs.Empty);
}
}
-65
View File
@@ -1,65 +0,0 @@
<ui:FluentWindow x:Class="OmniDeck.App.Legal.OdLegalWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:legal="clr-namespace:OmniDeck.App.Legal"
xmlns:res="clr-namespace:OmniDeck.Core.Localization;assembly=OmniDeck.Core"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="{res:OdLoc Legal_Title}"
Width="860"
Height="680"
MinWidth="560"
MinHeight="420"
ExtendsContentIntoTitleBar="True"
WindowBackdropType="Mica"
WindowStartupLocation="CenterScreen">
<ui:FluentWindow.Resources>
<legal:OdMarkdownConverter x:Key="Markdown" />
<BooleanToVisibilityConverter x:Key="Visible" />
</ui:FluentWindow.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ui:TitleBar Title="{res:OdLoc Legal_Title}" Grid.Row="0" />
<TextBlock Grid.Row="1"
Margin="{DynamicResource Od.Padding.Card}"
Text="{res:OdLoc Legal_Intro}"
TextWrapping="Wrap" />
<TabControl Grid.Row="2"
Margin="{DynamicResource Od.Padding.Control}"
ItemsSource="{Binding Pages}"
SelectedIndex="0">
<TabControl.ItemTemplate>
<DataTemplate DataType="{x:Type legal:OdLegalPage}">
<TextBlock Text="{Binding Title}" />
</DataTemplate>
</TabControl.ItemTemplate>
<TabControl.ContentTemplate>
<DataTemplate DataType="{x:Type legal:OdLegalPage}">
<FlowDocumentScrollViewer Document="{Binding Markdown, Converter={StaticResource Markdown}}"
IsToolBarVisible="False"
VerticalScrollBarVisibility="Auto" />
</DataTemplate>
</TabControl.ContentTemplate>
</TabControl>
<DockPanel Grid.Row="3" Margin="{DynamicResource Od.Padding.Card}">
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Appearance="Primary"
Command="{Binding ContinueCommand}"
Content="{res:OdLoc Legal_Continue}"
Visibility="{Binding AsksForAcknowledgment, Converter={StaticResource Visible}}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Command="{Binding QuitCommand}"
Content="{Binding QuitText}" />
</StackPanel>
<CheckBox VerticalAlignment="Center"
Content="{res:OdLoc Legal_HaveRead}"
IsChecked="{Binding HasRead}"
Visibility="{Binding AsksForAcknowledgment, Converter={StaticResource Visible}}" />
</DockPanel>
</Grid>
</ui:FluentWindow>
@@ -1,35 +0,0 @@
namespace OmniDeck.App.Legal;
/// <summary>
/// Shows the legal documents: as the gate before the main window (first run, and after each legal
/// update), or opened again from About to read them.
/// </summary>
public partial class OdLegalWindow
{
private bool _isGate;
public OdLegalWindow(OdLegalViewModel viewModel)
{
ArgumentNullException.ThrowIfNull(viewModel);
InitializeComponent();
DataContext = viewModel;
viewModel.Finished += (_, _) =>
{
if (_isGate)
{
DialogResult = viewModel.Accepted;
}
else
{
Close();
}
};
}
/// <summary>Shows the gate and waits: true once the user continued; closing the window counts as Quit.</summary>
public bool ShowGate()
{
_isGate = true;
return ShowDialog() == true;
}
}
@@ -1,16 +0,0 @@
using System.Globalization;
using System.Windows.Data;
using System.Windows.Documents;
using OmniDeck.App.Shell;
namespace OmniDeck.App.Legal;
/// <summary>Binds Markdown text to a <c>FlowDocumentScrollViewer</c>; links open in the default browser.</summary>
[ValueConversion(typeof(string), typeof(FlowDocument))]
public sealed class OdMarkdownConverter : IValueConverter
{
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>
OdMarkdownRenderer.Render(value as string ?? "", OdExternal.Open);
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => Binding.DoNothing;
}
@@ -1,241 +0,0 @@
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;
using Markdig;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
using OmniDeck.Core.Theming;
using MdBlock = Markdig.Syntax.Block;
using MdInline = Markdig.Syntax.Inlines.Inline;
using MdTable = Markdig.Extensions.Tables.Table;
using MdTableCell = Markdig.Extensions.Tables.TableCell;
using MdTableRow = Markdig.Extensions.Tables.TableRow;
using WpfBlock = System.Windows.Documents.Block;
using WpfInline = System.Windows.Documents.Inline;
using WpfTable = System.Windows.Documents.Table;
namespace OmniDeck.App.Legal;
/// <summary>
/// Turns the legal documents' Markdown into a <see cref="FlowDocument"/>. It covers what docs/legal
/// uses: headings, paragraphs, emphasis, inline code, links, lists, pipe tables, quotes, code blocks
/// and rules. Text sizes follow the <c>Od.*</c> font tokens; links go to the caller, which opens them.
/// </summary>
internal static class OdMarkdownRenderer
{
private static readonly MarkdownPipeline Pipeline = new MarkdownPipelineBuilder().UsePipeTables().Build();
private static readonly FontFamily Monospace = new("Cascadia Mono, Consolas, Courier New");
// Theme brushes rather than fixed colors, so lines follow light, dark and High Contrast.
private const string DividerBrush = "DividerStrokeColorDefaultBrush";
private const string QuoteBrush = "ControlStrongStrokeColorDefaultBrush";
public static FlowDocument Render(string markdown, Action<Uri> openLink)
{
ArgumentNullException.ThrowIfNull(markdown);
ArgumentNullException.ThrowIfNull(openLink);
// A FlowDocument defaults to a serif reading font and justified text; the app's own font reads better here.
var document = new FlowDocument
{
PagePadding = new Thickness(0),
FontFamily = SystemFonts.MessageFontFamily,
TextAlignment = TextAlignment.Left,
};
document.SetResourceReference(FlowDocument.FontSizeProperty, OdTokenKeys.FontBase);
document.SetResourceReference(FlowDocument.ForegroundProperty, "TextFillColorPrimaryBrush");
foreach (var block in Markdown.Parse(markdown, Pipeline))
{
if (RenderBlock(block, openLink) is { } rendered)
{
document.Blocks.Add(rendered);
}
}
return document;
}
private static WpfBlock? RenderBlock(MdBlock block, Action<Uri> openLink) => block switch
{
HeadingBlock heading => Heading(heading, openLink),
ParagraphBlock paragraph => Paragraph(paragraph.Inline, openLink),
ListBlock list => List(list, openLink),
MdTable table => Table(table, openLink),
QuoteBlock quote => Quote(quote, openLink),
CodeBlock code => Code(code),
ThematicBreakBlock => Bordered(new Paragraph(), new Thickness(0, 0, 0, 1), DividerBrush),
_ => null,
};
private static Paragraph Heading(HeadingBlock heading, Action<Uri> openLink)
{
var paragraph = Paragraph(heading.Inline, openLink);
paragraph.FontWeight = FontWeights.SemiBold;
paragraph.Margin = new Thickness(0, heading.Level == 1 ? 0 : 12, 0, 4);
paragraph.SetResourceReference(
TextElement.FontSizeProperty,
heading.Level switch
{
1 => OdTokenKeys.FontH1,
2 => OdTokenKeys.FontH2,
_ => OdTokenKeys.FontBase,
});
return paragraph;
}
private static Paragraph Paragraph(ContainerInline? inlines, Action<Uri> openLink)
{
var paragraph = new Paragraph { Margin = new Thickness(0, 0, 0, 8) };
AddInlines(paragraph.Inlines, inlines, openLink);
return paragraph;
}
private static List List(ListBlock list, Action<Uri> openLink)
{
var rendered = new List
{
MarkerStyle = list.IsOrdered ? TextMarkerStyle.Decimal : TextMarkerStyle.Disc,
Margin = new Thickness(0, 0, 0, 8),
};
foreach (var item in list.OfType<ListItemBlock>())
{
var listItem = new ListItem();
foreach (var child in item)
{
if (RenderBlock(child, openLink) is { } block)
{
block.Margin = new Thickness(0);
listItem.Blocks.Add(block);
}
}
rendered.ListItems.Add(listItem);
}
return rendered;
}
private static WpfTable Table(MdTable table, Action<Uri> openLink)
{
var rendered = new WpfTable { CellSpacing = 0, Margin = new Thickness(0, 0, 0, 8) };
var rows = new TableRowGroup();
foreach (var row in table.OfType<MdTableRow>())
{
var renderedRow = new TableRow();
foreach (var cell in row.OfType<MdTableCell>())
{
var renderedCell = new TableCell { BorderThickness = new Thickness(0, 0, 0, 1), Padding = new Thickness(4, 2, 8, 2) };
renderedCell.SetResourceReference(TableCell.BorderBrushProperty, DividerBrush);
foreach (var block in cell)
{
if (RenderBlock(block, openLink) is { } content)
{
content.Margin = new Thickness(0);
renderedCell.Blocks.Add(content);
}
}
if (row.IsHeader)
{
renderedCell.FontWeight = FontWeights.SemiBold;
}
renderedRow.Cells.Add(renderedCell);
}
rows.Rows.Add(renderedRow);
}
rendered.RowGroups.Add(rows);
return rendered;
}
private static T Bordered<T>(T block, Thickness thickness, string brushKey)
where T : WpfBlock
{
block.BorderThickness = thickness;
block.SetResourceReference(WpfBlock.BorderBrushProperty, brushKey);
return block;
}
private static Section Quote(QuoteBlock quote, Action<Uri> openLink)
{
var section = Bordered(new Section { Padding = new Thickness(8, 0, 0, 0) }, new Thickness(3, 0, 0, 0), QuoteBrush);
foreach (var child in quote)
{
if (RenderBlock(child, openLink) is { } block)
{
section.Blocks.Add(block);
}
}
return section;
}
private static Paragraph Code(CodeBlock code) =>
new(new Run(code.Lines.ToString())) { FontFamily = Monospace, Margin = new Thickness(0, 0, 0, 8) };
private static void AddInlines(InlineCollection target, ContainerInline? container, Action<Uri> openLink)
{
for (var inline = container?.FirstChild; inline is not null; inline = inline.NextSibling)
{
if (RenderInline(inline, openLink) is { } rendered)
{
target.Add(rendered);
}
}
}
private static WpfInline? RenderInline(MdInline inline, Action<Uri> openLink)
{
switch (inline)
{
case LiteralInline literal:
return new Run(literal.Content.ToString());
case CodeInline code:
return new Run(code.Content) { FontFamily = Monospace };
case LineBreakInline lineBreak:
return lineBreak.IsHard ? new LineBreak() : new Run(" ");
case LinkInline { IsImage: false } link:
return Link(link.Url, link, openLink);
case AutolinkInline autolink:
return Link(autolink.Url, null, openLink, autolink.Url);
case EmphasisInline emphasis:
Span span = emphasis.DelimiterCount >= 2 ? new Bold() : new Italic();
AddInlines(span.Inlines, emphasis, openLink);
return span;
case ContainerInline container:
var group = new Span();
AddInlines(group.Inlines, container, openLink);
return group;
default:
return null;
}
}
private static WpfInline Link(string? url, ContainerInline? content, Action<Uri> openLink, string? text = null)
{
var span = new Span();
if (content is not null)
{
AddInlines(span.Inlines, content, openLink);
}
else
{
span.Inlines.Add(new Run(text ?? url ?? ""));
}
// Only absolute web and mail links open; relative links point into the source repository.
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || uri.Scheme is not ("https" or "http" or "mailto"))
{
return span;
}
var hyperlink = new Hyperlink(span) { NavigateUri = uri };
hyperlink.RequestNavigate += (_, e) =>
{
openLink(e.Uri);
e.Handled = true;
};
return hyperlink;
}
}
+3 -3
View File
@@ -1,14 +1,14 @@
<Application x:Class="OmniDeck.App.OdApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
StartupUri="OdMainWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- WPF-UI dictionaries first, then our implicit styles; OdThemeEngine adds the Od.* preset layer last (docs/UI-MODES.md). -->
<!-- WPF-UI dictionaries first; the Od.* preset layer goes on top in P1 (docs/UI-MODES.md). -->
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
<ResourceDictionary Source="Theming/OdStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
-160
View File
@@ -1,160 +0,0 @@
using System.IO;
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using OmniDeck.App.Composition;
using OmniDeck.App.Diagnostics;
using OmniDeck.App.Legal;
using OmniDeck.App.Resources;
using OmniDeck.App.Settings;
using OmniDeck.App.Shell;
using OmniDeck.App.Theming;
using OmniDeck.App.Updates;
using OmniDeck.Core;
using OmniDeck.Core.Governor;
using OmniDeck.Core.Legal;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Runtime;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Modules;
using OmniDeck.Modules.Calendar;
using OmniDeck.Modules.Resources;
using OmniDeck.Web;
using OmniDeck.Web.Catalog;
using OmniDeck.Web.Resources;
using OmniDeck.Web.Runtime;
using Serilog;
namespace OmniDeck.App;
/// <summary>
/// The WPF application: builds the data root, the logger and the service container, hooks crash
/// handling, then shows the main window. Shutdown is explicit because the tray keeps OmniDeck
/// running after its window closes.
/// </summary>
public partial class OdApp
{
private readonly OdSingleInstanceGuard _guard;
private readonly OdDataRoot _dataRoot;
private ServiceProvider? _services;
internal OdApp(OdSingleInstanceGuard guard, OdDataRoot dataRoot)
{
_guard = guard;
_dataRoot = dataRoot;
}
/// <summary>The legal documents that ship next to the executable.</summary>
public static string LegalFolder => Path.Combine(AppContext.BaseDirectory, "legal");
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ShutdownMode = ShutdownMode.OnExplicitShutdown;
OdLocalization.Instance.Register(OdAppStrings.Resources);
OdLocalization.Instance.Register(OdModuleStrings.Resources);
OdLocalization.Instance.Register(OdWebStrings.Resources);
try
{
Start(e.Args);
}
catch (Exception ex)
{
Log.ForContext<OdApp>().Fatal(ex, "OmniDeck could not start");
MessageBox.Show(OdLocalization.Format("Error_StartFailed", ex.Message), OdLocalization.Get("App_Name"), MessageBoxButton.OK, MessageBoxImage.Error);
Shutdown(1);
}
}
protected override void OnExit(ExitEventArgs e)
{
Log.ForContext<OdApp>().Information("OmniDeck exiting with code {ExitCode}", e.ApplicationExitCode);
_services?.Dispose();
OdDatabase.ReleaseAll();
Log.CloseAndFlush();
base.OnExit(e);
}
private void Start(string[] args)
{
var startMinimized = args.Contains(OdRunKeyStartup.MinimizedArgument, StringComparer.OrdinalIgnoreCase);
var dataRoot = _dataRoot;
dataRoot.EnsureCreated();
Log.Logger = OdLogging.CreateLogger(dataRoot);
Log.ForContext<OdApp>().Information("OmniDeck {Version} starting", OdVersionInfo.FromAssembly(typeof(OdApp).Assembly).DisplayText);
if (!dataRoot.IsDefault)
{
Log.ForContext<OdApp>().Warning("Development data root in use: {DataRoot}", dataRoot.Root);
}
// The catalog decides which web-app modules exist, so it loads before the container is built.
var catalog = OdCatalogService.LoadInstalled(dataRoot, TimeProvider.System, Log.Logger);
var webOptions = new OdWebOptions(ChromiumLogging: args.Contains(OdWebOptions.LoggingSwitch, StringComparer.OrdinalIgnoreCase));
_services = new ServiceCollection()
.AddOmniDeckCore(dataRoot, Log.Logger)
.AddOmniDeckModules()
.AddOmniDeckWeb(catalog, webOptions)
.AddOmniDeckApp()
.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true });
_services.GetRequiredService<OdCrashHandler>().Hook(this);
var applied = _services.GetRequiredService<OdDatabase>().Migrate(OdCoreMigrations.All);
Log.ForContext<OdApp>().Information("Database ready ({Applied} migrations applied)", applied);
var settings = _services.GetRequiredService<IOdSettingsService>();
OdLocalization.Instance.SetCulture(OdLocalization.Instance.ResolveCulture(settings.Current.Language));
OdLocalization.Instance.TrackWindowLanguage();
settings.Changed += (_, e) => Dispatcher.Invoke(() => OdLocalization.Instance.SetCulture(OdLocalization.Instance.ResolveCulture(e.Settings.Language)));
_services.GetRequiredService<OdThemeEngine>().Start(this);
// The legal gate comes first, on the first run and after each legal update; Quit ends here.
var legal = _services.GetRequiredService<OdLegalGate>();
if (!legal.IsAcknowledged && !new OdLegalWindow(new OdLegalViewModel(legal, LegalFolder)).ShowGate())
{
Log.ForContext<OdApp>().Information("Legal documents not acknowledged; quitting");
Shutdown(0);
return;
}
var meta = _services.GetRequiredService<IOdAppMeta>();
if (OdOnboardingViewModel.IsNeeded(meta))
{
new OdOnboardingWindow(new OdOnboardingViewModel(settings, meta)).ShowDialog();
}
// Only now may a second launch bring the window up: never past the gate.
_guard.StartListening(() => _ = Dispatcher.InvokeAsync(() => MainShell().Present()));
var window = MainShell();
if (!startMinimized)
{
window.Present();
}
_services.GetRequiredService<OdRamGovernor>().Start();
_services.GetRequiredService<OdUpdateWatcher>().Start();
_services.GetRequiredService<OdReminderService>().Start();
_services.GetRequiredService<OdCatalogService>().Start();
}
/// <summary>The main window, created once. It owns the tray icon, so it exists even while hidden.</summary>
private OdMainWindow MainShell()
{
if (MainWindow is not OdMainWindow window)
{
window = _services!.GetRequiredService<OdMainWindow>();
MainWindow = window;
// A real close (tray off, or Quit) ends the app; otherwise closing only hides the window.
var lifetime = _services!.GetRequiredService<IOdAppLifetime>();
window.Closed += (_, _) =>
{
if (!lifetime.IsQuitting)
{
_ = lifetime.QuitAsync();
}
};
}
return window;
}
}
+16 -90
View File
@@ -1,17 +1,11 @@
<ui:FluentWindow x:Class="OmniDeck.App.OdMainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:res="clr-namespace:OmniDeck.Core.Localization;assembly=OmniDeck.Core"
xmlns:tb="clr-namespace:H.NotifyIcon;assembly=H.NotifyIcon.Wpf"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="{res:OdLoc App_Name}"
Width="1100"
Height="720"
MinWidth="640"
MinHeight="420"
Closing="OnClosing"
Title="OmniDeck"
Width="960"
Height="600"
ExtendsContentIntoTitleBar="True"
PreviewKeyDown="OnPreviewKeyDown"
WindowBackdropType="Mica"
WindowStartupLocation="CenterScreen">
<Grid>
@@ -19,86 +13,18 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TitleBar x:Name="AppTitleBar"
Title="{res:OdLoc App_Name}"
Grid.Row="0">
<!-- Looks like a search box; opens the command palette, as Ctrl+K does. -->
<ui:TitleBar.CenterContent>
<ui:Button Width="360"
Margin="16,0,0,0"
HorizontalContentAlignment="Left"
AutomationProperties.Name="{res:OdLoc Shell_Search}"
Click="OnSearchClick"
ToolTip="Ctrl+K">
<DockPanel>
<ui:SymbolIcon Margin="0,0,8,0"
DockPanel.Dock="Left"
Symbol="Search24" />
<TextBlock VerticalAlignment="Center"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{res:OdLoc Shell_Search}"
TextTrimming="CharacterEllipsis" />
</DockPanel>
</ui:Button>
</ui:TitleBar.CenterContent>
</ui:TitleBar>
<!-- Chrome only: items are built in code from OdShellViewModel.Sidebar and every navigation goes through it. -->
<ui:NavigationView x:Name="RootNavigation"
Grid.Row="1"
FrameMargin="0"
IsBackButtonVisible="Collapsed"
IsPaneToggleVisible="True"
OpenPaneLength="240"
PaneDisplayMode="Left"
TitleBar="{Binding ElementName=AppTitleBar, Mode=OneWay}">
<ui:NavigationView.ContentOverlay>
<Grid>
<ui:SnackbarPresenter x:Name="RootSnackbar" VerticalAlignment="Bottom" />
</Grid>
</ui:NavigationView.ContentOverlay>
</ui:NavigationView>
<!-- In-window dialogs cover the whole window, title bar included. -->
<ui:ContentDialogHost x:Name="RootDialogHost"
Grid.Row="0"
Grid.RowSpan="2" />
<!--
The tray icon lives as long as this window, which closing only hides (docs/SPEC.md §2).
Its image is drawn in code (OdTrayIcon), never with GeneratedIconSource.
-->
<tb:TaskbarIcon x:Name="TrayIcon"
Grid.Row="0"
NoLeftClickDelay="True"
ToolTipText="{res:OdLoc App_Name}"
TrayBalloonTipClicked="OnTrayNotificationClicked"
TrayLeftMouseUp="OnTrayOpen">
<tb:TaskbarIcon.ContextMenu>
<ContextMenu Opened="OnTrayMenuOpened">
<MenuItem Click="OnTrayOpen" Header="{res:OdLoc Tray_Open}" />
<MenuItem Click="OnTrayQuickTimer" Header="{res:OdLoc Tray_QuickTimer}" />
<!-- Shown while a media module has something loaded (docs/SPEC.md §2). -->
<Separator x:Name="TrayMediaSeparator" Visibility="Collapsed" />
<MenuItem x:Name="TrayNowPlaying"
IsEnabled="False"
Visibility="Collapsed" />
<MenuItem x:Name="TrayPlayPause"
Click="OnTrayPlayPause"
Visibility="Collapsed" />
<MenuItem x:Name="TrayNext"
Click="OnTrayNext"
Header="{res:OdLoc Tray_Next}"
Visibility="Collapsed" />
<MenuItem x:Name="TrayPrevious"
Click="OnTrayPrevious"
Header="{res:OdLoc Tray_Previous}"
Visibility="Collapsed" />
<Separator />
<MenuItem Click="OnTrayQuit" Header="{res:OdLoc Tray_Quit}" />
</ContextMenu>
</tb:TaskbarIcon.ContextMenu>
</tb:TaskbarIcon>
<ui:TitleBar Title="OmniDeck" Grid.Row="0" />
<!-- Kickoff placeholder: the real shell (navigation, module host) arrives in P1. -->
<StackPanel Grid.Row="1"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ui:TextBlock HorizontalAlignment="Center"
FontTypography="Title"
Text="OmniDeck" />
<ui:TextBlock x:Name="VersionText"
Margin="0,8,0,0"
HorizontalAlignment="Center"
Appearance="Secondary" />
</StackPanel>
</Grid>
</ui:FluentWindow>
+5 -560
View File
@@ -1,568 +1,13 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using H.NotifyIcon.Core;
using OmniDeck.App.Diagnostics;
using OmniDeck.App.Legal;
using OmniDeck.App.Settings;
using OmniDeck.App.Shell;
using OmniDeck.App.Theming;
using OmniDeck.Core.Legal;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Runtime;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Core.Theming;
using OmniDeck.Modules.Timer;
using Wpf.Ui;
using Wpf.Ui.Abstractions;
using Wpf.Ui.Controls;
using MenuItem = System.Windows.Controls.MenuItem;
using OmniDeck.Core;
namespace OmniDeck.App;
/// <summary>
/// The shell window: the title bar with the palette button, the navigation view as sidebar chrome,
/// the module stage, in-window dialogs and snackbars, and the tray icon. Closing hides it into the
/// tray unless the user turned that off or is quitting.
/// </summary>
public partial class OdMainWindow : INavigationViewPageProvider
/// <summary>Placeholder shell window of the kickoff build; the real shell arrives in P1.</summary>
public partial class OdMainWindow
{
private const int WmSettingChange = 0x001A;
// How far below and right of this window's corner a module's own window first opens.
private const double PopOutOffset = 48;
private readonly OdShellViewModel _shell;
private readonly OdDialogs _dialogs;
private readonly OdTrayNotifier _notifier;
private readonly IOdSettingsService _settings;
private readonly IOdAppLifetime _lifetime;
private readonly IOdAppMeta _meta;
private readonly IOdQuickTimer _quickTimer;
private readonly OdLibraryPage _library;
private readonly OdSettingsPage _settingsPage;
private readonly OdModuleStage _stage;
private readonly OdModuleHost _host;
private readonly OdWindowCover _cover;
private readonly Dictionary<string, OdPopOutWindow> _popOuts = new(StringComparer.Ordinal);
private readonly Dictionary<string, Rect> _popOutBounds = new(StringComparer.Ordinal);
private OdPanePlacement? _paneBeforeFullscreen;
private readonly Dictionary<string, NavigationViewItem> _moduleItems = new(StringComparer.Ordinal);
private readonly NavigationViewItemSeparator _pinnedSeparator = new();
private readonly OdTrayIcon _trayIcon = new();
private bool? _navLabels;
private int _navMax = -1;
public OdMainWindow(
OdThemeEngine theme,
OdShellViewModel shell,
OdSettingsViewModel settingsPage,
OdLegalGate legalGate,
OdDialogs dialogs,
ISnackbarService snackbars,
OdTrayNotifier notifier,
IOdSettingsService settings,
IOdAppLifetime lifetime,
IOdAppMeta meta,
IOdQuickTimer quickTimer,
OdBugReportFlow bugReports,
OdBugReportRequests bugReportRequests,
OdModuleHost host)
public OdMainWindow()
{
ArgumentNullException.ThrowIfNull(theme);
ArgumentNullException.ThrowIfNull(settingsPage);
ArgumentNullException.ThrowIfNull(snackbars);
InitializeComponent();
_shell = shell;
_dialogs = dialogs;
_notifier = notifier;
_settings = settings;
_lifetime = lifetime;
_meta = meta;
_quickTimer = quickTimer;
DataContext = shell;
_library = new OdLibraryPage { DataContext = shell };
_settingsPage = new OdSettingsPage { DataContext = settingsPage };
shell.SettingsSectionRequested += (_, e) => settingsPage.ShowSection(e.Section);
settingsPage.About.LegalRequested += (_, _) =>
new OdLegalWindow(new OdLegalViewModel(legalGate, OdApp.LegalFolder, readOnly: true)) { Owner = this }.Show();
settingsPage.About.BugReportRequested += (sender, args) => _ = bugReports.ShowAsync(error: null);
bugReportRequests.Requested += (sender, args) => _ = bugReports.ShowAsync(args.Error);
_stage = new OdModuleStage { DataContext = shell };
_host = host;
_cover = new OdWindowCover(this);
ListenForFullscreen(shell);
ListenForPopOuts(shell);
// A web app's browser is a native window over the stage that no dialog can cover: hide it meanwhile.
dialogs.OpenChanged += (_, _) => _stage.Visibility = dialogs.IsOpen ? Visibility.Hidden : Visibility.Visible;
dialogs.SetHost(RootDialogHost);
snackbars.SetSnackbarPresenter(RootSnackbar);
// Created now, so the icon exists even if the window never shows; no Efficiency Mode, which
// would throttle the whole process while timers run in the background. The image comes first,
// so the icon never appears blank.
UpdateTrayIcon();
TrayIcon.ForceCreate(enablesEfficiencyMode: false);
notifier.Attach((title, message) => _ = Dispatcher.InvokeAsync(() => TrayIcon.ShowNotification(title, message, NotificationIcon.Info)));
notifier.Clicked += OnNotificationClicked;
Closed += (_, _) =>
{
notifier.Clicked -= OnNotificationClicked;
TrayIcon.Dispose();
};
SetUpNavigation(theme);
// WPF ignores the Windows text size; re-read it when it may have changed (docs/UI-MODES.md §4).
Activated += (_, _) => theme.RefreshTextScale();
SourceInitialized += (_, _) => HwndSource.FromHwnd(new WindowInteropHelper(this).Handle)?.AddHook(
(IntPtr _, int msg, IntPtr _, IntPtr _, ref bool _) =>
{
if (msg == WmSettingChange)
{
theme.RefreshTextScale();
}
return IntPtr.Zero;
});
}
/// <summary>Shows the window from the tray or the taskbar, restored and in front.</summary>
public void Present()
{
Show();
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
}
Activate();
}
object? INavigationViewPageProvider.GetPage(Type pageType)
{
if (pageType == typeof(OdLibraryPage))
{
return _library;
}
if (pageType == typeof(OdSettingsPage))
{
return _settingsPage;
}
return pageType == typeof(OdModuleStage) ? _stage : null;
}
private void SetUpNavigation(OdThemeEngine theme)
{
RootNavigation.SetPageProviderService(this);
RootNavigation.FooterMenuItems.Add(ShellItem(OdShellViewModel.SettingsTarget, Localized("Settings_Nav"), SymbolRegular.Settings24, typeof(OdSettingsPage)));
RootNavigation.FooterMenuItems.Add(ShellItem(OdShellViewModel.LibraryTarget, Localized("Shell_Library"), SymbolRegular.Apps24, typeof(OdLibraryPage)));
SyncSidebar();
_shell.Sidebar.CollectionChanged += (_, _) => SyncSidebar();
_shell.PropertyChanged += OnShellPropertyChanged;
RootNavigation.SelectionChanged += OnNavigationSelectionChanged;
RootNavigation.Navigating += (_, _) => RootNavigation.TransitionDuration = (int)OdMotion.DurationFor(this).TotalMilliseconds;
RootNavigation.PaneOpened += (_, _) => UpdateToolTips();
RootNavigation.PaneClosed += (_, _) => UpdateToolTips();
theme.Applied += OnThemeApplied;
Closed += (_, _) => theme.Applied -= OnThemeApplied;
Loaded += (_, _) =>
{
ApplyNavTokens();
UpdateToolTips();
RootNavigation.Navigate(_shell.CurrentTarget);
};
}
private static Binding Localized(string key) => new($"[{key}]") { Source = OdLocalization.Instance, Mode = BindingMode.OneWay };
private static NavigationViewItem ShellItem(string target, Binding title, SymbolRegular icon, Type pageType)
{
var item = new NavigationViewItem
{
Icon = new SymbolIcon { Symbol = icon },
TargetPageTag = target,
TargetPageType = pageType,
};
item.SetBinding(ContentControl.ContentProperty, title);
item.SetBinding(AutomationProperties.NameProperty, title);
item.SetBinding(ToolTipProperty, title);
return item;
}
/// <summary>
/// Mirrors the sidebar, with a separator between pinned and merely open modules. Each module keeps
/// one item for the window's lifetime: the navigation view never forgets an item's tag, so a
/// re-added module must come back as the same item.
/// </summary>
private void SyncSidebar()
{
RootNavigation.MenuItems.Clear();
var previousPinned = false;
foreach (var module in _shell.VisibleSidebar(NavMaxVisibleItems))
{
if (previousPinned && !module.IsPinned)
{
RootNavigation.MenuItems.Add(_pinnedSeparator);
}
if (!_moduleItems.TryGetValue(module.Id, out var item))
{
item = ModuleItem(module);
_moduleItems[module.Id] = item;
}
RootNavigation.MenuItems.Add(item);
previousPinned = module.IsPinned;
}
UpdateToolTips();
}
private int NavMaxVisibleItems => TryFindResource(OdTokenKeys.NavMaxVisibleItems) is int max ? max : 0;
private void OnThemeApplied(object? sender, EventArgs e)
{
ApplyNavTokens();
UpdateTrayIcon();
}
/// <summary>Redraws the tray icon when the accent changed; the taskbar icon disposes the one it replaces.</summary>
private void UpdateTrayIcon()
{
if (_trayIcon.Update(TryFindResource("AccentFillColorDefaultBrush") as Brush, TryFindResource("TextOnAccentFillColorPrimaryBrush") as Brush) is { } icon)
{
TrayIcon.Icon = icon;
}
}
/// <summary>
/// Follows the preset's sidebar tokens (docs/UI-MODES.md §2): labels or icons only, and how many modules
/// it shows. Only a change of preset opens or closes the pane; otherwise the user's own toggle stands.
/// </summary>
private void ApplyNavTokens()
{
var labels = TryFindResource(OdTokenKeys.NavShowLabels) is not false;
if (_navLabels != labels)
{
_navLabels = labels;
RootNavigation.IsPaneOpen = labels;
}
var max = NavMaxVisibleItems;
if (_navMax != max)
{
_navMax = max;
SyncSidebar();
}
}
/// <summary>With the pane closed the sidebar shows icons only, so each item's label moves into its tooltip.</summary>
private void UpdateToolTips()
{
var show = !RootNavigation.IsPaneOpen;
foreach (var item in RootNavigation.MenuItems.OfType<NavigationViewItem>().Concat(RootNavigation.FooterMenuItems.OfType<NavigationViewItem>()))
{
ToolTipService.SetIsEnabled(item, show);
}
}
private NavigationViewItem ModuleItem(OdModuleItemViewModel module)
{
var pin = new MenuItem { Command = _shell.TogglePinCommand, CommandParameter = module };
var popOut = new MenuItem { CommandParameter = module };
var close = new MenuItem { Command = _shell.CloseCommand, CommandParameter = module };
close.SetBinding(HeaderedItemsControl.HeaderProperty, Localized("Shell_Close"));
var menu = new ContextMenu { Items = { pin, popOut, close } };
menu.Opened += (_, _) =>
{
pin.Header = OdLocalization.Get(module.IsPinned ? "Shell_Unpin" : "Shell_Pin");
popOut.Header = module.IsPoppedOut ? OdLocalization.Get("Shell_PopIn") : OdLocalization.Get("Shell_PopOut");
popOut.Command = module.IsPoppedOut ? _shell.PopInCommand : _shell.PopOutCommand;
};
var item = new NavigationViewItem
{
Icon = new SymbolIcon { Symbol = OdSymbolConverter.Parse(module.Info.Icon) },
TargetPageTag = module.Id,
TargetPageType = typeof(OdModuleStage),
ContextMenu = menu,
};
item.SetBinding(ContentControl.ContentProperty, new Binding(nameof(OdModuleItemViewModel.Title)) { Source = module });
item.SetBinding(AutomationProperties.NameProperty, new Binding(nameof(OdModuleItemViewModel.Title)) { Source = module });
item.SetBinding(ToolTipProperty, new Binding(nameof(OdModuleItemViewModel.Title)) { Source = module });
return item;
}
private async void OnNavigationSelectionChanged(NavigationView sender, RoutedEventArgs args)
{
if (sender.SelectedItem is NavigationViewItem { TargetPageTag: { Length: > 0 } target })
{
await _shell.NavigateAsync(target);
// A module in a window of its own stays there: the selection goes back to what this window shows.
if (!string.Equals(target, _shell.CurrentTarget, StringComparison.Ordinal))
{
RootNavigation.Navigate(_shell.CurrentTarget);
}
}
}
private void OnShellPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (!string.Equals(e.PropertyName, nameof(OdShellViewModel.CurrentTarget), StringComparison.Ordinal))
{
return;
}
// A capped sidebar must make room for the module now on screen before it can be selected.
var max = NavMaxVisibleItems;
if (max > 0 && _shell.Sidebar.Count > max)
{
SyncSidebar();
}
var selected = (RootNavigation.SelectedItem as NavigationViewItem)?.TargetPageTag;
if (!string.Equals(selected, _shell.CurrentTarget, StringComparison.Ordinal))
{
RootNavigation.Navigate(_shell.CurrentTarget);
}
}
private async void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape && _cover.IsCovering)
{
e.Handled = true;
SetFullscreen(on: false);
return;
}
// Exactly Ctrl: AltGr arrives as Ctrl+Alt, and must type its character rather than run a shortcut.
if (Keyboard.Modifiers != ModifierKeys.Control || _dialogs.IsOpen)
{
return;
}
if (e.Key == Key.K)
{
e.Handled = true;
await OpenPaletteAsync();
}
else if (_shell.ShortcutTarget(e.Key, NavMaxVisibleItems) is { } target)
{
e.Handled = true;
await _shell.NavigateAsync(target);
}
}
private async void OnSearchClick(object sender, RoutedEventArgs e) => await OpenPaletteAsync();
private async Task OpenPaletteAsync()
{
var palette = new OdCommandPaletteViewModel(_shell.PaletteEntries());
new OdCommandPaletteWindow(palette, this).ShowDialog();
if (palette.Chosen is { } chosen)
{
await chosen.RunAsync();
}
}
private void OnClosing(object? sender, CancelEventArgs e)
{
if (_lifetime.IsQuitting || !_settings.Current.CloseToTray)
{
return;
}
e.Cancel = true;
SetFullscreen(on: false);
Hide();
// Say once, ever, where the window went.
if (_meta.Get(OdAppMetaKeys.TrayHintShown) is null)
{
_meta.Set(OdAppMetaKeys.TrayHintShown, "1");
_notifier.Notify(OdLocalization.Get("Tray_StillRunningTitle"), OdLocalization.Get("Tray_StillRunningMessage"));
}
}
private void OnTrayOpen(object sender, RoutedEventArgs e) => Present();
private void OnTrayNotificationClicked(object sender, RoutedEventArgs e) => _notifier.OnClicked();
/// <summary>A click on a notification brings the window up, on the module that raised it.</summary>
private async void OnNotificationClicked(object? sender, OdNotificationClickedEventArgs e)
{
Present();
if (e.Target is { } target)
{
await _shell.NavigateAsync(target);
}
}
private async void OnTrayQuit(object sender, RoutedEventArgs e) => await _lifetime.QuitAsync();
private void OnTrayQuickTimer(object sender, RoutedEventArgs e) => _quickTimer.StartQuick(TimeSpan.FromMinutes(5));
private IOdMediaControls? LoadedMedia() =>
_host.Modules.Select(hosted => hosted.Module).OfType<IOdMediaControls>().FirstOrDefault(media => media.NowPlaying is not null);
/// <summary>The media items show only while a media module has something loaded.</summary>
private void OnTrayMenuOpened(object sender, RoutedEventArgs e)
{
var media = LoadedMedia();
var visibility = media is null ? Visibility.Collapsed : Visibility.Visible;
foreach (var item in new FrameworkElement[] { TrayMediaSeparator, TrayNowPlaying, TrayPlayPause, TrayNext, TrayPrevious })
{
item.Visibility = visibility;
}
if (media is not null)
{
TrayNowPlaying.Header = media.NowPlaying;
TrayPlayPause.Header = media.IsPlaying ? OdLocalization.Get("Tray_Pause") : OdLocalization.Get("Tray_Play");
}
}
private void OnTrayPlayPause(object sender, RoutedEventArgs e) => LoadedMedia()?.PlayPause();
private void OnTrayNext(object sender, RoutedEventArgs e) => LoadedMedia()?.Next();
private void OnTrayPrevious(object sender, RoutedEventArgs e) => LoadedMedia()?.Previous();
private void ListenForFullscreen(OdShellViewModel shell)
{
AddHandler(OdFullscreen.RequestedEvent, new EventHandler<OdFullscreenRequestedEventArgs>(OnFullscreenRequested));
shell.PropertyChanged += (_, e) =>
{
// Full screen belongs to the module on screen: showing another one ends it.
if (string.Equals(e.PropertyName, nameof(OdShellViewModel.CurrentView), StringComparison.Ordinal))
{
SetFullscreen(on: false);
}
};
}
private void ListenForPopOuts(OdShellViewModel shell)
{
shell.PopOutOpened += (_, e) => OpenPopOut(e.Item, e.View!);
shell.PopOutActivationRequested += (_, e) => _popOuts.GetValueOrDefault(e.Item.Id)?.Present();
shell.PopOutCloseRequested += (_, e) =>
{
if (_popOuts.Remove(e.Item.Id, out var window))
{
window.Release();
_popOutBounds[e.Item.Id] = window.LastBounds;
}
};
}
/// <summary>Opens a module's own window where it was last in this session, or beside this window.</summary>
private void OpenPopOut(OdModuleItemViewModel item, FrameworkElement view)
{
var window = new OdPopOutWindow(item, view, this);
if (_popOutBounds.TryGetValue(item.Id, out var bounds))
{
window.Left = bounds.Left;
window.Top = bounds.Top;
window.Width = bounds.Width;
window.Height = bounds.Height;
}
else if (IsVisible && WindowState == WindowState.Normal)
{
window.Left = Left + PopOutOffset;
window.Top = Top + PopOutOffset;
}
else
{
window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
}
window.Returned += async (_, _) =>
{
_popOuts.Remove(item.Id);
_popOutBounds[item.Id] = window.LastBounds;
await _shell.DockAsync(item);
};
_popOuts[item.Id] = window;
window.Show();
}
private void OnFullscreenRequested(object? sender, OdFullscreenRequestedEventArgs e)
{
e.Handled = true;
SetFullscreen(e.On);
}
/// <summary>Covers the monitor the window is on, chrome hidden, or puts the window back where it was.</summary>
private void SetFullscreen(bool on)
{
if (on == _cover.IsCovering)
{
return;
}
if (on)
{
if (!_cover.Cover(OdMonitors.BoundsOf(new WindowInteropHelper(this).Handle)))
{
return;
}
FoldChrome();
}
else
{
_cover.Uncover();
UnfoldChrome();
}
OdFullscreen.SetIsActive(_stage, on);
}
private void FoldChrome()
{
_paneBeforeFullscreen = new OdPanePlacement(RootNavigation.OpenPaneLength, RootNavigation.CompactPaneLength, RootNavigation.IsPaneToggleVisible, RootNavigation.FrameMargin);
AppTitleBar.Visibility = Visibility.Collapsed;
RootNavigation.TitleBar = null;
// The pane folds to nothing: changing its display mode would re-template the navigation view and
// re-create the stage, and with it a player's video window.
RootNavigation.IsPaneToggleVisible = false;
RootNavigation.OpenPaneLength = 0;
RootNavigation.CompactPaneLength = 0;
// The folded pane's template still keeps a few pixels (its margins, the frame's border): the frame
// overlaps them. Clearing the title bar has just reset the frame's margin, so it is read only now.
UpdateLayout();
var offset = _stage.TranslatePoint(default, this);
var frame = RootNavigation.FrameMargin;
RootNavigation.FrameMargin = new Thickness(frame.Left - offset.X, frame.Top - offset.Y, frame.Right, frame.Bottom);
}
private void UnfoldChrome()
{
AppTitleBar.Visibility = Visibility.Visible;
RootNavigation.TitleBar = AppTitleBar;
if (_paneBeforeFullscreen is { } pane)
{
_paneBeforeFullscreen = null;
RootNavigation.OpenPaneLength = pane.OpenLength;
RootNavigation.CompactPaneLength = pane.CompactLength;
RootNavigation.IsPaneToggleVisible = pane.ToggleVisible;
RootNavigation.FrameMargin = pane.FrameMargin;
}
VersionText.Text = OdVersionInfo.FromAssembly(typeof(OdMainWindow).Assembly).DisplayText;
}
}
+6 -43
View File
@@ -8,60 +8,28 @@
<AssemblyName>OmniDeck</AssemblyName>
<RootNamespace>OmniDeck.App</RootNamespace>
<ApplicationManifest>app.manifest</ApplicationManifest>
<!-- The executable's icon, which its windows, shortcuts and Explorer show (scripts/make-icon.ps1). -->
<ApplicationIcon>Assets\OmniDeck.ico</ApplicationIcon>
<!-- Custom entry point: Velopack's hooks must run before WPF loads OdApp.xaml resources. -->
<StartupObject>OmniDeck.App.Program</StartupObject>
<!-- Ship only the UI languages OmniDeck supports (EN neutral, VI, JA). -->
<SatelliteResourceLanguages>en;vi;ja</SatelliteResourceLanguages>
<!-- Resources/Strings.resx is English; the resource manager never probes for an "en" satellite. -->
<NeutralLanguage>en</NeutralLanguage>
</PropertyGroup>
<!-- The application class is OdApp, not App: types carry the Od prefix, and Meziantou MA0049
rejects a type named like its namespace. OdApp.xaml stays a plain Page (no ApplicationDefinition),
so WPF generates no Main of its own: Program.Main creates OdApp with the single-instance guard. -->
<ItemGroup>
<!-- The application class is OdApp, not App: types carry the Od prefix, and Meziantou MA0049
rejects a type named like its namespace. -->
<Page Remove="OdApp.xaml" />
<ApplicationDefinition Include="OdApp.xaml" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\OmniDeck.Core\OmniDeck.Core.csproj" />
<ProjectReference Include="..\OmniDeck.Modules\OmniDeck.Modules.csproj" />
<ProjectReference Include="..\OmniDeck.Web\OmniDeck.Web.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="OmniDeck.Tests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageReference Include="H.NotifyIcon.Wpf" Version="2.4.1" />
<PackageReference Include="Markdig" Version="1.5.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.14" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="Velopack" Version="1.2.161" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup>
<!-- libVLC for the media player (docs/SPEC.md §3.6), copied to libvlc\win-x64 next to OmniDeck.exe:
x64 only, and only the plugins the player needs (docs/spikes/06-libvlcsharp.md). -->
<PropertyGroup>
<VlcWindowsX86Enabled>false</VlcWindowsX86Enabled>
<VlcWindowsArm64Enabled>false</VlcWindowsArm64Enabled>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="VideoLAN.LibVLC.Windows" Version="3.0.24" />
</ItemGroup>
<ItemGroup>
<VlcWindowsX64IncludeFiles Include="libvlc.dll;libvlccore.dll" />
<VlcWindowsX64IncludeFiles Include="plugins\access\%2A;plugins\audio_filter\%2A;plugins\audio_mixer\%2A;plugins\audio_output\%2A" />
<VlcWindowsX64IncludeFiles Include="plugins\codec\%2A;plugins\demux\%2A;plugins\packetizer\%2A;plugins\stream_filter\%2A" />
<VlcWindowsX64IncludeFiles Include="plugins\text_renderer\%2A;plugins\spu\%2A;plugins\video_chroma\%2A;plugins\video_filter\%2A;plugins\video_output\%2A;plugins\misc\%2A" />
<!-- The player opens local files: no network streaming. -->
<VlcWindowsX64ExcludeFiles Include="plugins\access\libaccess_srt_plugin.dll;plugins\access\libftp_plugin.dll;plugins\access\libhttp_plugin.dll;plugins\access\libhttps_plugin.dll;plugins\access\librtp_plugin.dll;plugins\access\libsftp_plugin.dll;plugins\access\libsmb_plugin.dll" />
</ItemGroup>
<!-- The license and legal documents travel with every build: the self-contained app
redistributes MIT/BSD code whose notices must ship with it, and the P1 legal gate shows them. -->
<ItemGroup>
@@ -69,11 +37,6 @@
<None Include="..\..\docs\legal\*.md" Link="legal\%(Filename)%(Extension)" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<!-- The web-app catalog as of this build; a newer one fetched from main replaces it (docs/WEBAPP-CATALOG.md). -->
<ItemGroup>
<None Include="..\..\catalog\webapps.json" Link="catalog\webapps.json" CopyToOutputDirectory="PreserveNewest" CopyToPublishDirectory="PreserveNewest" />
</ItemGroup>
<!-- A self-contained publish redistributes the .NET and Windows Desktop runtimes: their license
and third-party notices ship too, under legal\<framework>\ (THIRD-PARTY-NOTICES.md points there). -->
<Target Name="OdCopyRuntimeNotices" AfterTargets="Publish" Condition="'$(SelfContained)' == 'true'">
+4 -31
View File
@@ -1,48 +1,21 @@
using OmniDeck.Core.Runtime;
using OmniDeck.Core.Storage;
using Velopack;
namespace OmniDeck.App;
/// <summary>
/// Process entry point. Velopack's install/update/uninstall hooks run first (they may exit the
/// process and must not wait for WPF to load OdApp.xaml resources); then a second OmniDeck hands off
/// to the first one and exits; only then is the WPF <see cref="OdApp"/> created.
/// process and must not wait for WPF to load OdApp.xaml resources); only then is the WPF
/// <see cref="OdApp"/> created.
/// </summary>
internal static class Program
{
[STAThread]
private static int Main()
{
VelopackApp.Build()
// The privacy policy promises that uninstalling removes everything OmniDeck stored.
.OnBeforeUninstallFastCallback(_ => OdDataRoot.Default.TryDelete())
.Run();
VelopackApp.Build().Run();
var dataRoot = DataRoot();
using var guard = new OdSingleInstanceGuard(dataRoot.InstanceSuffix);
if (!guard.IsPrimaryInstance)
{
guard.SignalPrimaryInstance();
return 0;
}
var app = new OdApp(guard, dataRoot);
var app = new OdApp();
app.InitializeComponent();
return app.Run();
}
/// <summary>
/// The signed-in user's data root. A Debug build can be pointed elsewhere with
/// <see cref="OdDataRoot.OverrideVariable"/>, so it runs beside an installed OmniDeck without
/// touching its data; a Release build never reads the variable.
/// </summary>
private static OdDataRoot DataRoot()
{
#if DEBUG
return OdDataRoot.Choose(Environment.GetEnvironmentVariable(OdDataRoot.OverrideVariable));
#else
return OdDataRoot.Default;
#endif
}
}
@@ -1,9 +0,0 @@
using System.Resources;
namespace OmniDeck.App.Resources;
/// <summary>The shell's string table, <c>Resources/Strings.resx</c>; <c>OdApp</c> registers it with <c>OdLocalization</c>.</summary>
internal static class OdAppStrings
{
public static ResourceManager Resources { get; } = new("OmniDeck.App.Resources.Strings", typeof(OdAppStrings).Assembly);
}
-475
View File
@@ -1,475 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!-- The shell's UI strings, English (neutral). Vietnamese and Japanese satellites arrive in P3. -->
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="App_Name" xml:space="preserve">
<value>OmniDeck</value>
</data>
<data name="Shell_Search" xml:space="preserve">
<value>Search modules and commands</value>
</data>
<data name="Shell_Library" xml:space="preserve">
<value>Library</value>
</data>
<data name="Shell_LibraryTitle" xml:space="preserve">
<value>Module library</value>
</data>
<data name="Shell_LibraryIntro" xml:space="preserve">
<value>Open a module, or pin it to keep it in the sidebar.</value>
</data>
<data name="Shell_LibraryEmpty" xml:space="preserve">
<value>No modules are available yet.</value>
</data>
<data name="Shell_Open" xml:space="preserve">
<value>Open</value>
</data>
<data name="Shell_Pin" xml:space="preserve">
<value>Pin to sidebar</value>
</data>
<data name="Shell_Unpin" xml:space="preserve">
<value>Unpin from sidebar</value>
</data>
<data name="Shell_Close" xml:space="preserve">
<value>Close</value>
</data>
<data name="Shell_PopOut" xml:space="preserve">
<value>Open in new window</value>
</data>
<data name="Shell_PopIn" xml:space="preserve">
<value>Return to main window</value>
</data>
<data name="Shell_PaletteCommand" xml:space="preserve">
<value>Command</value>
</data>
<data name="Shell_Quit" xml:space="preserve">
<value>Quit OmniDeck</value>
</data>
<data name="Tray_Open" xml:space="preserve">
<value>Open OmniDeck</value>
</data>
<data name="Tray_QuickTimer" xml:space="preserve">
<value>Start a 5-minute timer</value>
</data>
<data name="Tray_Quit" xml:space="preserve">
<value>Quit</value>
</data>
<data name="Tray_StillRunningTitle" xml:space="preserve">
<value>OmniDeck is still running</value>
</data>
<data name="Tray_StillRunningMessage" xml:space="preserve">
<value>It keeps running in the notification area. To exit, choose Quit from its icon's menu.</value>
</data>
<data name="Error_Title" xml:space="preserve">
<value>Something went wrong</value>
</data>
<data name="Error_UiMessage" xml:space="preserve">
<value>Something went wrong, but OmniDeck is still running.
Support code: {0}
{1}</value>
</data>
<data name="Error_StartFailed" xml:space="preserve">
<value>OmniDeck could not start.
{0}</value>
</data>
<data name="Memory_Title" xml:space="preserve">
<value>Running modules</value>
</data>
<data name="Memory_Intro" xml:space="preserve">
<value>Hidden modules step down over time to save memory: idle, then suspended, then hibernated. Keep a module running to exempt it.</value>
</data>
<data name="Memory_InUse" xml:space="preserve">
<value>In use: {0}</value>
</data>
<data name="Memory_Limits" xml:space="preserve">
<value>Soft limit {0} · hard limit {1}</value>
</data>
<data name="Memory_SharedNote" xml:space="preserve">
<value>Built-in modules share OmniDeck's own process, so only web apps have a figure of their own.</value>
</data>
<data name="Memory_SharedTitle" xml:space="preserve">
<value>Shared web processes</value>
</data>
<data name="Memory_SharedDescription" xml:space="preserve">
<value>The browser, graphics and helper processes every web app uses. They close with the last web app.</value>
</data>
<data name="Memory_KeepRunning" xml:space="preserve">
<value>Keep running</value>
</data>
<data name="Memory_Suspend" xml:space="preserve">
<value>Suspend</value>
</data>
<data name="Memory_Hibernate" xml:space="preserve">
<value>Hibernate</value>
</data>
<data name="Memory_UsedNow" xml:space="preserve">
<value>On screen</value>
</data>
<data name="Memory_UsedJustNow" xml:space="preserve">
<value>Used just now</value>
</data>
<data name="Memory_UsedMinutesAgo" xml:space="preserve">
<value>Used {0} min ago</value>
</data>
<data name="Memory_UsedHoursAgo" xml:space="preserve">
<value>Used {0} h ago</value>
</data>
<data name="State_Created" xml:space="preserve">
<value>Not started</value>
</data>
<data name="State_Active" xml:space="preserve">
<value>Active</value>
</data>
<data name="State_Idle" xml:space="preserve">
<value>Idle</value>
</data>
<data name="State_Suspended" xml:space="preserve">
<value>Suspended</value>
</data>
<data name="State_Hibernated" xml:space="preserve">
<value>Hibernated</value>
</data>
<data name="State_Closed" xml:space="preserve">
<value>Closed</value>
</data>
<data name="Governor_HardCapTitle" xml:space="preserve">
<value>OmniDeck is using a lot of memory</value>
</data>
<data name="Governor_HardCapHibernatedOne" xml:space="preserve">
<value>It hibernated a module to stay under its {0} limit.</value>
</data>
<data name="Governor_HardCapHibernated" xml:space="preserve">
<value>It hibernated {0} modules to stay under its {1} limit.</value>
</data>
<data name="Governor_HardCapKept" xml:space="preserve">
<value>It is above its {0} limit, and nothing more can be hibernated: the open modules are in use or kept running.</value>
</data>
<data name="Governor_HardCapShared" xml:space="preserve">
<value>It is above its {0} limit because the processes the open web apps share use {1}, mostly for graphics. Hibernating other modules would not bring that down.</value>
</data>
<data name="Governor_ResidentHibernatedTitle" xml:space="preserve">
<value>{0} was hibernated to save memory</value>
</data>
<data name="Governor_ResidentHibernated" xml:space="preserve">
<value>It shows no notifications until you open it again. Click here to open it.</value>
</data>
<data name="Settings_Nav" xml:space="preserve">
<value>Settings</value>
</data>
<data name="Settings_Title" xml:space="preserve">
<value>Settings</value>
</data>
<data name="Settings_General" xml:space="preserve">
<value>General</value>
</data>
<data name="Settings_Appearance" xml:space="preserve">
<value>Appearance</value>
</data>
<data name="Settings_Memory" xml:space="preserve">
<value>Memory</value>
</data>
<data name="Settings_Data" xml:space="preserve">
<value>Data</value>
</data>
<data name="Settings_About" xml:space="preserve">
<value>About</value>
</data>
<data name="Settings_Language" xml:space="preserve">
<value>Language</value>
</data>
<data name="Settings_CloseToTray" xml:space="preserve">
<value>Keep running in the notification area when the window closes</value>
</data>
<data name="Settings_StartWithWindows" xml:space="preserve">
<value>Start OmniDeck when I sign in to Windows</value>
</data>
<data name="Settings_Theme" xml:space="preserve">
<value>Theme</value>
</data>
<data name="Settings_Preset" xml:space="preserve">
<value>Layout</value>
</data>
<data name="Settings_FontScale" xml:space="preserve">
<value>Text size</value>
</data>
<data name="Settings_Motion" xml:space="preserve">
<value>Animations</value>
</data>
<data name="Settings_AccentSystem" xml:space="preserve">
<value>Use the Windows accent color</value>
</data>
<data name="Settings_IdleAfter" xml:space="preserve">
<value>Suspend hidden modules after (minutes)</value>
</data>
<data name="Settings_HibernateAfter" xml:space="preserve">
<value>Hibernate hidden modules after (minutes)</value>
</data>
<data name="Settings_SoftCap" xml:space="preserve">
<value>Soft memory limit in MB (0: automatic)</value>
</data>
<data name="Settings_HardCap" xml:space="preserve">
<value>Hard memory limit in MB (0: automatic)</value>
</data>
<data name="Settings_DataFolder" xml:space="preserve">
<value>Data folder</value>
</data>
<data name="Settings_OpenDataFolder" xml:space="preserve">
<value>Open</value>
</data>
<data name="Settings_Export" xml:space="preserve">
<value>Export settings…</value>
</data>
<data name="Settings_Import" xml:space="preserve">
<value>Import settings…</value>
</data>
<data name="Settings_FileFilter" xml:space="preserve">
<value>OmniDeck settings (*.json)|*.json</value>
</data>
<data name="Settings_Exported" xml:space="preserve">
<value>Settings exported.</value>
</data>
<data name="Settings_Imported" xml:space="preserve">
<value>Settings imported.</value>
</data>
<data name="Settings_ImportFailed" xml:space="preserve">
<value>That file is not an OmniDeck settings file.</value>
</data>
<data name="Language_System" xml:space="preserve">
<value>Follow Windows</value>
</data>
<data name="Language_English" xml:space="preserve">
<value>English</value>
</data>
<data name="Theme_System" xml:space="preserve">
<value>Follow Windows</value>
</data>
<data name="Theme_Light" xml:space="preserve">
<value>Light</value>
</data>
<data name="Theme_Dark" xml:space="preserve">
<value>Dark</value>
</data>
<data name="Preset_Dynamic" xml:space="preserve">
<value>Dynamic</value>
</data>
<data name="Preset_DynamicHint" xml:space="preserve">
<value>Compact and lively: smaller text, more motion.</value>
</data>
<data name="Preset_Standard" xml:space="preserve">
<value>Standard</value>
</data>
<data name="Preset_StandardHint" xml:space="preserve">
<value>Balanced, for most people.</value>
</data>
<data name="Preset_Comfort" xml:space="preserve">
<value>Comfort</value>
</data>
<data name="Preset_ComfortHint" xml:space="preserve">
<value>Larger text and targets, no motion.</value>
</data>
<data name="Onboarding_Title" xml:space="preserve">
<value>Welcome to OmniDeck</value>
</data>
<data name="Onboarding_Intro" xml:space="preserve">
<value>Pick a language and a layout. The layout applies as you choose it.</value>
</data>
<data name="Onboarding_Later" xml:space="preserve">
<value>You can change both later in Settings.</value>
</data>
<data name="Onboarding_Done" xml:space="preserve">
<value>Get started</value>
</data>
<data name="Legal_Title" xml:space="preserve">
<value>Before you start</value>
</data>
<data name="Legal_Intro" xml:space="preserve">
<value>OmniDeck is free software under the GNU General Public License v3. Please read these documents: continuing records that you have read them. It is not a condition of the license.</value>
</data>
<data name="Legal_Eula" xml:space="preserve">
<value>License agreement</value>
</data>
<data name="Legal_Disclaimer" xml:space="preserve">
<value>Disclaimer</value>
</data>
<data name="Legal_Privacy" xml:space="preserve">
<value>Privacy policy</value>
</data>
<data name="Legal_Notices" xml:space="preserve">
<value>Third-party notices</value>
</data>
<data name="Legal_HaveRead" xml:space="preserve">
<value>I have read these documents</value>
</data>
<data name="Legal_Continue" xml:space="preserve">
<value>Continue</value>
</data>
<data name="Legal_Quit" xml:space="preserve">
<value>Quit</value>
</data>
<data name="Legal_Close" xml:space="preserve">
<value>Close</value>
</data>
<data name="Legal_Missing" xml:space="preserve">
<value>{0} is missing from this copy of OmniDeck.</value>
</data>
<data name="About_Version" xml:space="preserve">
<value>Version {0}</value>
</data>
<data name="About_CheckUpdates" xml:space="preserve">
<value>Check for updates</value>
</data>
<data name="About_Checking" xml:space="preserve">
<value>Checking for updates…</value>
</data>
<data name="About_UpToDate" xml:space="preserve">
<value>OmniDeck is up to date.</value>
</data>
<data name="About_Available" xml:space="preserve">
<value>Version {0} is available.</value>
</data>
<data name="About_Download" xml:space="preserve">
<value>Download and restart</value>
</data>
<data name="About_Downloading" xml:space="preserve">
<value>Downloading the update: {0} %</value>
</data>
<data name="About_Failed" xml:space="preserve">
<value>Could not update: {0}</value>
</data>
<data name="About_NotInstalled" xml:space="preserve">
<value>Updates work in installed copies of OmniDeck, not in development builds.</value>
</data>
<data name="About_Links" xml:space="preserve">
<value>Links</value>
</data>
<data name="About_GitHub" xml:space="preserve">
<value>Source code on GitHub</value>
</data>
<data name="About_Discussions" xml:space="preserve">
<value>Discussions</value>
</data>
<data name="About_Discord" xml:space="preserve">
<value>Discord</value>
</data>
<data name="About_Legal" xml:space="preserve">
<value>License and legal documents</value>
</data>
<data name="About_Credits" xml:space="preserve">
<value>OmniDeck is built with .NET, WPF-UI, Velopack, CommunityToolkit.Mvvm, H.NotifyIcon, Serilog, Dapper, SQLite and Markdig. The third-party notices list them all.</value>
</data>
<data name="Update_AvailableTitle" xml:space="preserve">
<value>OmniDeck {0} is available</value>
</data>
<data name="Update_AvailableMessage" xml:space="preserve">
<value>Open Settings → About to install it.</value>
</data>
<data name="Dialog_OK" xml:space="preserve">
<value>OK</value>
</data>
<data name="Dialog_Cancel" xml:space="preserve">
<value>Cancel</value>
</data>
<data name="Settings_WebApps" xml:space="preserve">
<value>Web apps</value>
</data>
<data name="WebApps_Intro" xml:space="preserve">
<value>Choose which web apps may show notifications. An app with notifications on keeps running while hidden, so that it can notify you; it is closed only when OmniDeck runs short of memory.</value>
</data>
<data name="WebApps_Notifications" xml:space="preserve">
<value>Notifications</value>
</data>
<data name="WebApps_NoPermissions" xml:space="preserve">
<value>No permissions asked yet</value>
</data>
<data name="WebApps_Allowed" xml:space="preserve">
<value>{0} allowed</value>
</data>
<data name="WebApps_Blocked" xml:space="preserve">
<value>{0} blocked</value>
</data>
<data name="WebApps_ResetPermissions" xml:space="preserve">
<value>Ask again</value>
</data>
<data name="WebApps_DataTitle" xml:space="preserve">
<value>Sign-in data</value>
</data>
<data name="WebApps_DataIntro" xml:space="preserve">
<value>The apps in a group share one sign-in. Clearing a group's data signs you out of all of them and closes them.</value>
</data>
<data name="WebApps_ClearData" xml:space="preserve">
<value>Clear data</value>
</data>
<data name="WebApps_ClearTitle" xml:space="preserve">
<value>Clear sign-in data?</value>
</data>
<data name="WebApps_ClearMessage" xml:space="preserve">
<value>You will be signed out of {0}. Their cookies, site data and cached pages are deleted.</value>
</data>
<data name="WebApps_ClearConfirm" xml:space="preserve">
<value>Clear data</value>
</data>
<data name="WebApps_Cleared" xml:space="preserve">
<value>Cleared the data of {0}.</value>
</data>
<data name="WebApps_ClearFailed" xml:space="preserve">
<value>The data could not be cleared. Try again after restarting OmniDeck.</value>
</data>
<data name="WebApps_Catalog" xml:space="preserve">
<value>Web app catalog of {0}, with {1} apps.</value>
</data>
<data name="WebApps_Checked" xml:space="preserve">
<value>Last checked for a newer catalog on {0}.</value>
</data>
<data name="WebApps_NotChecked" xml:space="preserve">
<value>Not checked for a newer catalog yet.</value>
</data>
<data name="About_ReportBug" xml:space="preserve">
<value>Report a bug</value>
</data>
<data name="Error_Report" xml:space="preserve">
<value>Report bug</value>
</data>
<data name="Report_Title" xml:space="preserve">
<value>Report a bug</value>
</data>
<data name="Report_Intro" xml:space="preserve">
<value>OmniDeck saves a report on this PC and opens a new GitHub issue in your browser, with the short fields filled in. Nothing is sent: attach the report to the issue yourself. Web addresses keep no query, and tokens, cookies, email addresses, long ids and your user name are taken out first.</value>
</data>
<data name="Report_Subject" xml:space="preserve">
<value>What is it about?</value>
</data>
<data name="Report_General" xml:space="preserve">
<value>OmniDeck in general</value>
</data>
<data name="Report_Preview" xml:space="preserve">
<value>The issue text, also in the report as issue.md</value>
</data>
<data name="Report_Save" xml:space="preserve">
<value>Save and open GitHub</value>
</data>
<data name="Tray_Play" xml:space="preserve">
<value>Play</value>
</data>
<data name="Tray_Pause" xml:space="preserve">
<value>Pause</value>
</data>
<data name="Tray_Next" xml:space="preserve">
<value>Next</value>
</data>
<data name="Tray_Previous" xml:space="preserve">
<value>Previous</value>
</data>
</root>
Loaded 100 of 414 files, more files were not shown because too many files have changed in this diff. Show more