Compare commits

...
Author SHA1 Message Date
poli0981 7af21aab09 Merge remote-tracking branch 'origin/main' into chore/dev-data-root 2026-11-03 11:05:13 +07:00
poli0981 e5f2835229 Merge pull request #43 from poli0981/feat/catalog-c2
feat(catalog): Spotify's third-party sign-in hops, and audioPin for calls
2026-11-03 10:53:27 +07:00
poli0981andClaude Opus 5.5 76b27e86ed chore: a development build can use a data root of its own
A Debug build reads OMNIDECK_DATA_ROOT and, when it is set, keeps its
settings, database, web sign-ins and logs there, under a single-instance
name of its own, so it runs beside an installed OmniDeck without touching
that copy's data. Release builds never read the variable.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 10:52:59 +07:00
poli0981 66812dc467 Merge remote-tracking branch 'origin/main' into feat/catalog-c2 2026-11-03 10:49:02 +07:00
poli0981 e82507db2d Merge pull request #53 from poli0981/dependabot/nuget/build-tooling-f93e7cef44
deps: Bump the build-tooling group with 1 update
2026-11-03 10:48:20 +07:00
dependabot[bot] 14f9e63f12 deps: Bump the build-tooling group with 1 update
Bumps Meziantou.Analyzer from 3.0.317 to 3.0.318

---
updated-dependencies:
- dependency-name: Meziantou.Analyzer
  dependency-version: 3.0.318
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: build-tooling
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-11-02 19:19:37 +00:00
poli0981 e279e94056 Merge branch 'main' into feat/catalog-c2 2026-11-02 13:03:35 +07:00
poli0981 d33d6fa442 Merge pull request #52 from poli0981/release/0.2.0-alpha.3
chore: release 0.2.0-alpha.3
2026-11-02 12:54:09 +07:00
poli0981andClaude Opus 5.5 a36c846271 chore: release 0.2.0-alpha.3
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:49:27 +07:00
poli0981 5c769ae082 Merge pull request #51 from poli0981/feat/p2-polish
feat: P2 polish: app icon, Play/Pause state, docs re-baselined
2026-11-02 12:48:57 +07:00
poli0981 e7acfef005 Merge remote-tracking branch 'origin/main' into feat/p2-polish 2026-11-02 12:42:37 +07:00
poli0981andClaude Opus 5.5 60a57b23e0 docs: re-baseline on what P2 built, and record the resource soak
ROADMAP: P2 started on 2 November 2026, as soon as P1 was done; what it
delivered so far, what changed on the way and what was left for later.
Settings import/export shipped in P1, so it leaves P3's list.

README, SPEC, ARCHITECTURE and CONTRIBUTING now describe P2 as built:
pop-out windows, web notifications, permission questions, downloads,
the bug report's flow and contents, Spotify's DRM and Discord's hotkey.

RAM-GOVERNOR: a soak of 21 pop-out and 21 page full-screen round trips
left GDI and USER objects and handles flat.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:42:36 +07:00
poli0981andClaude Opus 5.5 5f1a965153 feat: an application icon, and a Play/Pause button that shows which
OmniDeck had no icon of its own: the executable, its windows, the
taskbar and Velopack's Setup showed defaults. scripts/make-icon.ps1 draws
the monogram the tray icon uses, a bold "O" on Windows' default accent
blue, at the sizes Windows asks for, into Assets/OmniDeck.ico. The
executable carries it (WPF windows take it from there) and vpk pack gets
it with --icon. It stands in until a designed icon replaces the file.

The media player's Play/Pause button always showed Play; it now shows
Pause while playing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:32:38 +07:00
poli0981 b5c629907b Merge pull request #50 from poli0981/fix/p2-media-controls
fix: the media control bar keeps its seek bar and buttons when narrow
2026-11-02 12:30:28 +07:00
poli0981 c3a79402b8 Merge remote-tracking branch 'origin/main' into fix/p2-media-controls 2026-11-02 12:26:25 +07:00
poli0981andClaude Opus 5.5 0c9912cc53 fix: the media control bar keeps its seek bar and buttons when narrow
The bar was one row: beside the queue, at the window's default size, the
seek bar shrank to almost nothing and the queue button was cut off. The
title, time and seek bar now have rows of their own above the buttons, and
the volume slider shrinks before anything is cut off. WPF-UI's Slider style
asks for 104 px, so the volume slider sets MinWidth="0" and its column
decides.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:26:09 +07:00
poli0981 39019f4fb3 Merge pull request #49 from poli0981/feat/p2-pop-out
feat: pop-out windows, and web full screen
2026-11-02 12:24:41 +07:00
poli0981andClaude Opus 5.5 9b8086d925 docs: changelog for pop-out windows and web full screen
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:19:36 +07:00
poli0981 8f7a94973f Merge remote-tracking branch 'origin/main' into feat/p2-pop-out 2026-11-02 12:19:22 +07:00
poli0981andClaude Opus 5.5 1d4babcd41 feat: pop-out windows for modules
Any module can move into a window of its own, from its sidebar menu or
its library tile. The host keeps it active there, out of the governor's
reach, beside whatever the main window shows; asking for it again brings
its window up. Closing the window docks the module back, hidden, and
"Return to main window" shows it in the main window.

The view itself moves, so WPF re-parents a web app's browser and a
video's window: both keep running, without spike #6's track re-selection
and seek. The window lets go of the view before it closes and hands the
windows it owns to the main window, since LibVLCSharp's overlay would
otherwise close for good with it. Pop-outs have their own full screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:19:21 +07:00
poli0981 c21621403b Merge pull request #48 from poli0981/release/0.2.0-alpha.2
chore: release 0.2.0-alpha.2
2026-11-02 12:03:40 +07:00
poli0981andClaude Opus 5.5 311cdf641b chore: release 0.2.0-alpha.2
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:59:45 +07:00
poli0981andClaude Opus 5.5 4925eee1fd feat: a web page's full screen takes the window with it
A page that shows something full screen (a video, say) asks the window
for full screen through OdFullscreen, as the media player does; when the
window leaves first (Esc, another module), the page is told to leave too.

The window cover moves out of the main window into OdWindowCover, with
tests, so pop-out windows can use it next. In full screen the frame now
overlaps the pixels the folded pane's template still keeps, so the module
fills the monitor exactly instead of starting 9 px from the left edge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:59:20 +07:00
poli0981 e2e94c6f5c Merge branch 'main' into feat/catalog-c2 2026-11-02 11:51:25 +07:00
poli0981 6467c87982 Merge pull request #47 from poli0981/feat/p2-media-fullscreen
feat: media full screen and tray controls
2026-11-02 11:46:16 +07:00
poli0981 966e1fb23f Merge remote-tracking branch 'origin/main' into feat/p2-media-fullscreen 2026-11-02 11:41:15 +07:00
poli0981andClaude Opus 5.5 e8ea8aa925 feat: media full screen and tray controls
- OdFullscreen (Core): a view asks for full screen with a bubbling routed
  event raised from itself (its video overlay is a window of its own) and
  learns the answer through an inherited attached property on the stage.
- The main window covers its monitor (OdMonitors, LibraryImport), hides
  the title bar, unlinks it from the navigation view and folds the pane
  to zero width; changing the pane mode would re-template the view and
  re-create the player's video window. Esc, hiding to the tray or showing
  another module ends it.
- The media overlay: a full-screen button, double-click on the picture
  (the overlay is alpha 1 over a picture, so clicks reach it) and Esc;
  the queue steps aside meanwhile.
- IOdMediaControls: while a player has a file loaded, the tray menu shows
  it with Play/Pause, Next and Previous.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:40:33 +07:00
poli0981 f52965cdde Merge pull request #46 from poli0981/feat/p2-media-options
feat: media player options: tracks, subtitles, speed, device, snapshot
2026-11-02 11:33:41 +07:00
poli0981andClaude Opus 5.5 5491f6594f feat: media player options: tracks, subtitles, speed, device, snapshot
The overlay's More menu, built when it opens from the file playing:
- audio and subtitle tracks, and a subtitle file (kept if the file
  reopens, dropped when the next file starts);
- the subtitles' encoding (Automatic, UTF-8, common code pages): libVLC
  reads subsdec-encoding only when a file opens, so a new choice reopens
  the file where it stood;
- speed 0.25x to 4x, put back on each file since libVLC starts each at
  normal speed;
- the audio device, without libVLC's own id-less "Default" next to
  "Windows default";
- a snapshot of the picture in Pictures\OmniDeck, named after the file.
Speed, encoding and device are kept in the module's settings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:29:12 +07:00
poli0981 e52b4d679c Merge pull request #45 from poli0981/ci/sonar-native-wrappers
ci: leave the native-engine wrappers out of Sonar coverage
2026-11-02 11:18:25 +07:00
poli0981andClaude Opus 5.5 fbc2a3c2b6 feat(catalog): Spotify's third-party sign-in hops, and audioPin for calls
- spotify: "Continue with Google / Facebook / Apple" are links to
  accounts.spotify.com/login/<provider>, which redirect the main frame to
  accounts.google.com, www.facebook.com and appleid.apple.com and back.
  The entry lists those hosts and the google-account-domains set (Google's
  SetSID hops), so sign-in no longer leaves for the default browser.
- discord and facebook: audioPin true, so a call that is playing audio is
  never suspended; review rule 5 now allows calls.
- updated: 2026-11-03, so installed 0.2.0-alpha.1 copies, which ship the
  2026-11-02 catalog, take this one at their next daily check.
- Tests follow the catalog's own date and cover the new hosts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 10:52:05 +07:00
61 changed files with 2267 additions and 147 deletions

No files matched your search

+41 -2
View File
@@ -6,11 +6,48 @@ 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.
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
@@ -198,7 +235,9 @@ 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.1...HEAD
[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
+8 -1
View File
@@ -19,6 +19,13 @@ 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.
@@ -43,7 +50,7 @@ dotnet run --project src/OmniDeck.App
## Reporting bugs
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.
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.
## 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.1</Version>
<Version>0.2.0-alpha.3</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.317">
<PackageReference Include="Meziantou.Analyzer" Version="3.0.318">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
+6 -5
View File
@@ -13,12 +13,13 @@ OmniDeck combines a set of lightweight native mini-apps (weather, calculator, st
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.1.0 (phase P1) is the first installable build: the shell, the RAM governor, and the clock, timer and calculator modules. Web apps and the other modules arrive in P2 and 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: 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.
## 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)).
@@ -32,21 +33,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 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.
- **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.
- 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 (from P1 on), review and acknowledge the legal documents (EULA, disclaimer, privacy policy, third-party notices), then pick a UI preset and language.
3. On first run, 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 **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).
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).
## Documentation
+5 -4
View File
@@ -1,7 +1,7 @@
{
"$schema": "./webapps.schema.json",
"schemaVersion": 2,
"updated": "2026-11-02",
"updated": "2026-11-03",
"navAllowSets": {
"google-account-domains": [
"accounts.google.ad",
@@ -198,7 +198,8 @@
"name": "Spotify",
"startUrl": "https://open.spotify.com/",
"profile": "spotify",
"navAllow": ["spotify.com", "spotifycdn.com", "scdn.co"],
"navAllow": ["spotify.com", "spotifycdn.com", "scdn.co", "accounts.google.com", "www.facebook.com", "appleid.apple.com"],
"navAllowSets": ["google-account-domains"],
"popupAllow": ["accounts.spotify.com"],
"notifications": false,
"audioPin": true
@@ -211,7 +212,7 @@
"navAllow": ["discord.com", "discordapp.com", "discord.gg", "discordapp.net"],
"popupAllow": ["discord.com"],
"notifications": true,
"audioPin": false
"audioPin": true
},
{
"id": "youtube",
@@ -276,7 +277,7 @@
"navAllow": ["facebook.com", "fbcdn.net", "fbsbx.com"],
"popupAllow": ["facebook.com"],
"notifications": true,
"audioPin": false
"audioPin": true
}
]
}
+22 -4
View File
@@ -10,7 +10,7 @@ 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
scripts/ pack.ps1 (publish + Velopack), validate-catalog.ps1, make-icon.ps1
src/
OmniDeck.App/ WPF shell: windows, navigation, tray and notifications, command
palette, theme engine, legal gate, onboarding, settings UI,
@@ -22,7 +22,7 @@ src/
Calendar, Stocks, Media — one folder per module (P1)
OmniDeck.Web/ web runner: environment/profile management, catalog loader,
navigation policy, notifications bridge, permissions,
downloads, CDP console capture (P2)
sign-in health, CDP console capture (P2)
tests/
OmniDeck.Tests/ xUnit v3; governor state machine, providers, catalog validation,
scrubber, rate limiter
@@ -64,6 +64,23 @@ public interface IOdModule
`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.
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
@@ -73,12 +90,13 @@ 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` → `NotificationReceived` → `PermissionRequested` → start the CDP console capture → navigate.
- **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`.
@@ -145,4 +163,4 @@ A content dialog cannot cover a web app's browser, which is a native window. So
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.
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).
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.
+11
View File
@@ -12,6 +12,8 @@ The governor is the feature that makes "many apps in one" viable. It moves every
| 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 |
| 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).
## 2. Defaults (all configurable in Settings → Memory)
@@ -70,3 +72,12 @@ As built in P1, the panel sits in Settings → Memory under the threshold fields
## 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).
+15 -6
View File
@@ -3,6 +3,8 @@
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
@@ -39,21 +41,28 @@ Shell (nav, tray, single-instance, command palette), module contract + host, RAM
**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. Carried forward:
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 (11 Jan – 7 Mar 2027)
### P2 — Web runner & core modules (from 2 Nov 2026; planned 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; settings import/export; accessibility pass (text scaling, contrast themes, keyboard nav).
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).
**Exit (0.3.0):** feature-complete against SPEC v1 scope.
@@ -82,9 +91,9 @@ Every version below 1.0.0 is published as a GitHub **pre-release**; 1.0.0 is the
|---|---|---|
| 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 needs a video-output restart and a seek, plus an overlay sizing fix in P2. FlyleafLib is not needed |
| 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). P2 records sign-in health after restarts, and bug reports carry cookie-store counts (never values) |
| 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) |
| 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 |
@@ -98,4 +107,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, multi-point global hotkeys per web app, catalog entries from §4 of WEBAPP-CATALOG, per-module popout window session restore, portable build.
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.
+24 -14
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; full module library behind a "+" view. Sidebar density and item count vary by UI preset.
- **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.
- **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 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.
- **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.
- **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).
@@ -64,24 +64,34 @@ All mini-apps implement the module contract in [ARCHITECTURE](ARCHITECTURE.md) a
- 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** hands the player to the new window by re-selecting the video track and seeking to the current time ([spike #6](spikes/06-libvlcsharp.md)).
- **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 (first part):**
- **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.
- Track, subtitle, device and speed choices, snapshots, fullscreen and the tray controls follow in the second part.
- 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.
## 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 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).
- **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)).
- **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).
@@ -97,9 +107,9 @@ 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 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).
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.
## 7. Reference versions (verified 2026-10-28; Dependabot owns bumps from here)
+5 -5
View File
@@ -35,7 +35,7 @@ OmniDeck deliberately does **not** allow arbitrary user-added URLs in v1: the cu
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. 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.
**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.
## 2. Review rules for new entries (PR checklist)
@@ -43,7 +43,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.
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.
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 +52,14 @@ 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)); the third-party sign-in buttons (Google/Facebook/Apple) are still untested ([spike #2](spikes/02-google-sign-in.md)) |
| discord | discord | no | no global PTT on web; host hotkey partial mitigation |
| 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)) |
| gmail | google | no | |
| gcalendar | google | no | |
| gdrive | google | no | |
| gmaps | google | no | replaces a native map mini-app entirely |
| facebook | meta | no | also Meta's web messaging (`facebook.com/messages`) since messenger.com closed in April 2026; the Messenger entry was removed |
| 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 |
## 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 toggle is part of P0 spike #6; don't ship media pop-out before it passes.
- `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).
- 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.
+93
View File
@@ -0,0 +1,93 @@
<#
.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)"
+2 -1
View File
@@ -94,7 +94,8 @@ try {
--packAuthors poli0981 `
--packVersion $Version `
--packDir $publishDir `
--mainExe OmniDeck.exe
--mainExe OmniDeck.exe `
--icon (Join-Path $repoRoot 'src\OmniDeck.App\Assets\OmniDeck.ico')
if ($LASTEXITCODE -ne 0) { throw "vpk pack failed with exit code $LASTEXITCODE" }
}
finally {
Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

+8 -2
View File
@@ -35,11 +35,13 @@ namespace OmniDeck.App;
public partial class OdApp
{
private readonly OdSingleInstanceGuard _guard;
private readonly OdDataRoot _dataRoot;
private ServiceProvider? _services;
internal OdApp(OdSingleInstanceGuard guard)
internal OdApp(OdSingleInstanceGuard guard, OdDataRoot dataRoot)
{
_guard = guard;
_dataRoot = dataRoot;
}
/// <summary>The legal documents that ship next to the executable.</summary>
@@ -76,10 +78,14 @@ public partial class OdApp
private void Start(string[] args)
{
var startMinimized = args.Contains(OdRunKeyStartup.MinimizedArgument, StringComparer.OrdinalIgnoreCase);
var dataRoot = OdDataRoot.Default;
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);
+17 -1
View File
@@ -76,9 +76,25 @@
TrayBalloonTipClicked="OnTrayNotificationClicked"
TrayLeftMouseUp="OnTrayOpen">
<tb:TaskbarIcon.ContextMenu>
<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>
+187 -3
View File
@@ -15,6 +15,7 @@ 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;
@@ -35,6 +36,9 @@ public partial class OdMainWindow : INavigationViewPageProvider
{
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;
@@ -45,6 +49,11 @@ public partial class OdMainWindow : INavigationViewPageProvider
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();
@@ -64,7 +73,8 @@ public partial class OdMainWindow : INavigationViewPageProvider
IOdAppMeta meta,
IOdQuickTimer quickTimer,
OdBugReportFlow bugReports,
OdBugReportRequests bugReportRequests)
OdBugReportRequests bugReportRequests,
OdModuleHost host)
{
ArgumentNullException.ThrowIfNull(theme);
ArgumentNullException.ThrowIfNull(settingsPage);
@@ -86,6 +96,10 @@ public partial class OdMainWindow : INavigationViewPageProvider
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;
@@ -267,10 +281,16 @@ public partial class OdMainWindow : INavigationViewPageProvider
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, close } };
menu.Opened += (_, _) => pin.Header = OdLocalization.Get(module.IsPinned ? "Shell_Unpin" : "Shell_Pin");
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
{
@@ -290,6 +310,12 @@ public partial class OdMainWindow : INavigationViewPageProvider
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);
}
}
}
@@ -316,6 +342,13 @@ public partial class OdMainWindow : INavigationViewPageProvider
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)
{
@@ -354,6 +387,7 @@ public partial class OdMainWindow : INavigationViewPageProvider
}
e.Cancel = true;
SetFullscreen(on: false);
Hide();
// Say once, ever, where the window went.
@@ -381,4 +415,154 @@ public partial class OdMainWindow : INavigationViewPageProvider
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;
}
}
}
+2
View File
@@ -8,6 +8,8 @@
<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). -->
+17 -2
View File
@@ -19,15 +19,30 @@ internal static class Program
.OnBeforeUninstallFastCallback(_ => OdDataRoot.Default.TryDelete())
.Run();
using var guard = new OdSingleInstanceGuard();
var dataRoot = DataRoot();
using var guard = new OdSingleInstanceGuard(dataRoot.InstanceSuffix);
if (!guard.IsPrimaryInstance)
{
guard.SignalPrimaryInstance();
return 0;
}
var app = new OdApp(guard);
var app = new OdApp(guard, dataRoot);
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
}
}
+18
View File
@@ -43,6 +43,12 @@
<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>
@@ -454,4 +460,16 @@ Support code: {0}
<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>
@@ -68,6 +68,14 @@
Command="{Binding DataContext.OpenCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
Content="{res:OdLoc Shell_Open}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Appearance="Transparent"
AutomationProperties.Name="{res:OdLoc Shell_PopOut}"
Command="{Binding DataContext.PopOutCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
ToolTip="{res:OdLoc Shell_PopOut}">
<ui:SymbolIcon Symbol="WindowNew24" />
</ui:Button>
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Appearance="Transparent"
Command="{Binding DataContext.TogglePinCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
@@ -10,6 +10,10 @@ public sealed partial class OdModuleItemViewModel(OdModuleInfo info) : Observabl
[ObservableProperty]
private bool _isPinned;
/// <summary>Shown in a window of its own rather than in the main window.</summary>
[ObservableProperty]
private bool _isPoppedOut;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsOpen))]
private OdModuleState _state = OdModuleState.Created;
@@ -0,0 +1,6 @@
using System.Windows;
namespace OmniDeck.App.Shell;
/// <summary>How the navigation pane looked before full screen folded it away.</summary>
internal sealed record OdPanePlacement(double OpenLength, double CompactLength, bool ToggleVisible, Thickness FrameMargin);
@@ -0,0 +1,12 @@
using System.Windows;
namespace OmniDeck.App.Shell;
/// <summary>A module's own window, to open with the module's view, bring to the front, or close.</summary>
public sealed class OdPopOutEventArgs(OdModuleItemViewModel item, FrameworkElement? view = null) : EventArgs
{
public OdModuleItemViewModel Item { get; } = item;
/// <summary>The module's view, for a window that opens; null otherwise.</summary>
public FrameworkElement? View { get; } = view;
}
@@ -0,0 +1,26 @@
<ui:FluentWindow x:Class="OmniDeck.App.Shell.OdPopOutWindow"
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"
Width="960"
Height="640"
MinWidth="480"
MinHeight="320"
ExtendsContentIntoTitleBar="True"
PreviewKeyDown="OnPreviewKeyDown"
WindowBackdropType="Mica">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TitleBar x:Name="PopOutTitleBar" Grid.Row="0" />
<!-- The module's view, as on the main window's stage. -->
<ContentControl x:Name="Stage"
Grid.Row="1"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Focusable="False"
Foreground="{DynamicResource TextFillColorPrimaryBrush}" />
</Grid>
</ui:FluentWindow>
@@ -0,0 +1,143 @@
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Threading;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Runtime;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Shell;
/// <summary>
/// A module in a window of its own (docs/ARCHITECTURE.md §2): its view under a title bar with its name,
/// full screen as in the main window. The view moves rather than being built again, so the browser or
/// video it hosts keeps running. Before closing, the window lets go of the view and hands the windows it
/// owns to the main window: LibVLCSharp's video overlay is owned by the window its video is in, and
/// would close for good with it.
/// </summary>
public partial class OdPopOutWindow
{
private readonly Window _home;
private readonly OdWindowCover _cover;
private bool _released;
internal OdPopOutWindow(OdModuleItemViewModel item, FrameworkElement view, Window home)
{
InitializeComponent();
_home = home;
_cover = new OdWindowCover(this);
Title = item.Title;
PopOutTitleBar.Title = item.Title;
PopOutTitleBar.Icon = new SymbolIcon { Symbol = OdSymbolConverter.Parse(item.Info.Icon) };
Stage.Content = view;
AddHandler(OdFullscreen.RequestedEvent, new EventHandler<OdFullscreenRequestedEventArgs>(OnFullscreenRequested));
}
/// <summary>The user closed the window, which has let go of the view: the module goes back to the main window.</summary>
internal event EventHandler? Returned;
/// <summary>Where the window was, out of full screen, when it let go of the view.</summary>
internal Rect LastBounds { get; private set; }
/// <summary>Brings the window to the front, restored.</summary>
internal void Present()
{
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
}
Activate();
}
/// <summary>Lets go of the view and closes: the module returns to the main window, or was closed.</summary>
internal void Release()
{
if (_released)
{
return;
}
LetGo();
Hide();
CloseSoon();
}
protected override void OnClosing(CancelEventArgs e)
{
ArgumentNullException.ThrowIfNull(e);
if (!_released && !Dispatcher.HasShutdownStarted)
{
// The view goes first, and the window closes once it is gone (CloseSoon).
e.Cancel = true;
LetGo();
Returned?.Invoke(this, EventArgs.Empty);
CloseSoon();
}
base.OnClosing(e);
}
private void LetGo()
{
_released = true;
SetFullscreen(on: false);
LastBounds = RestoreBounds;
Stage.Content = null;
}
// At a lower priority than the view's Unloaded, after which a video overlay no longer follows this
// window's closing; the windows it still owns move to the main window.
private void CloseSoon() => _ = Dispatcher.InvokeAsync(
() =>
{
foreach (var owned in OwnedWindows.Cast<Window>().ToList())
{
owned.Owner = _home;
}
Close();
},
DispatcherPriority.ContextIdle);
private void OnFullscreenRequested(object? sender, OdFullscreenRequestedEventArgs e)
{
e.Handled = true;
SetFullscreen(e.On);
}
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape && _cover.IsCovering)
{
e.Handled = true;
SetFullscreen(on: false);
}
}
private void SetFullscreen(bool on)
{
if (on == _cover.IsCovering)
{
return;
}
if (on)
{
if (!_cover.Cover(OdMonitors.BoundsOf(new WindowInteropHelper(this).Handle)))
{
return;
}
PopOutTitleBar.Visibility = Visibility.Collapsed;
}
else
{
_cover.Uncover();
PopOutTitleBar.Visibility = Visibility.Visible;
}
OdFullscreen.SetIsActive(Stage, on);
}
}
+73 -7
View File
@@ -11,10 +11,10 @@ using OmniDeck.Core.Settings;
namespace OmniDeck.App.Shell;
/// <summary>
/// The shell's state: what the sidebar lists, what is showing (a module or the library page) and the
/// view on the module stage. The navigation view is chrome only (docs/WPFUI-CONVENTIONS.md §5): every
/// navigation comes through <see cref="NavigateAsync"/> and the module host runs the module. Used from
/// the UI thread.
/// The shell's state: what the sidebar lists, what is showing (a module or the library page), the
/// view on the module stage, and which modules show in windows of their own. The navigation view is
/// chrome only (docs/WPFUI-CONVENTIONS.md §5): every navigation comes through <see cref="NavigateAsync"/>
/// and the module host runs the module. Used from the UI thread.
/// </summary>
public sealed partial class OdShellViewModel : ObservableObject, IDisposable
{
@@ -58,6 +58,15 @@ public sealed partial class OdShellViewModel : ObservableObject, IDisposable
/// <summary>Raised when a settings tab should come to the front, such as the palette's "Running modules".</summary>
public event EventHandler<OdSettingsSectionEventArgs>? SettingsSectionRequested;
/// <summary>A module moved into a window of its own, which shows <see cref="OdPopOutEventArgs.View"/>.</summary>
public event EventHandler<OdPopOutEventArgs>? PopOutOpened;
/// <summary>A module in a window of its own was asked for: that window comes to the front.</summary>
public event EventHandler<OdPopOutEventArgs>? PopOutActivationRequested;
/// <summary>A module's own window must let go of the view and close: the module returns to the main window, or closed.</summary>
public event EventHandler<OdPopOutEventArgs>? PopOutCloseRequested;
/// <summary>Every module, in registration order: the library page.</summary>
public IReadOnlyList<OdModuleItemViewModel> Library { get; }
@@ -111,7 +120,10 @@ public sealed partial class OdShellViewModel : ObservableObject, IDisposable
return position >= 0 && position < visible.Count ? visible[position].Id : null;
}
/// <summary>Shows <paramref name="target"/>: a module id, or one of the shell's own pages. Other targets are ignored.</summary>
/// <summary>
/// Shows <paramref name="target"/>: a module id, or one of the shell's own pages. A module in a window of
/// its own stays there, and its window comes to the front. Other targets are ignored.
/// </summary>
public async Task NavigateAsync(string target)
{
ArgumentNullException.ThrowIfNull(target);
@@ -121,8 +133,14 @@ public sealed partial class OdShellViewModel : ObservableObject, IDisposable
CurrentView = null;
CurrentTarget = target;
}
else if (_items.ContainsKey(target))
else if (_items.TryGetValue(target, out var item))
{
if (item.IsPoppedOut)
{
PopOutActivationRequested?.Invoke(this, new OdPopOutEventArgs(item));
return;
}
CurrentView = await _host.ShowAsync(target);
CurrentTarget = target;
}
@@ -142,6 +160,13 @@ public sealed partial class OdShellViewModel : ObservableObject, IDisposable
];
}
/// <summary>The user closed a module's own window: the module goes back to the main window, hidden.</summary>
public Task DockAsync(OdModuleItemViewModel item)
{
ArgumentNullException.ThrowIfNull(item);
return _host.DockAsync(item.Id);
}
public void Dispose()
{
_host.StateChanged -= OnModuleStateChanged;
@@ -155,6 +180,40 @@ public sealed partial class OdShellViewModel : ObservableObject, IDisposable
[RelayCommand]
private Task CloseAsync(OdModuleItemViewModel item) => _host.CloseAsync(item.Id);
/// <summary>Moves a module into a window of its own; a main window that showed it shows the library instead.</summary>
[RelayCommand]
private async Task PopOutAsync(OdModuleItemViewModel item)
{
if (item.IsPoppedOut)
{
PopOutActivationRequested?.Invoke(this, new OdPopOutEventArgs(item));
return;
}
if (string.Equals(item.Id, CurrentTarget, StringComparison.Ordinal))
{
// A view is in one window at a time: the main window lets go of it first.
await NavigateAsync(LibraryTarget);
}
var view = await _host.PopOutAsync(item.Id);
PopOutOpened?.Invoke(this, new OdPopOutEventArgs(item, view));
}
/// <summary>Brings a module back from its own window and shows it in the main window.</summary>
[RelayCommand]
private async Task PopInAsync(OdModuleItemViewModel item)
{
if (!item.IsPoppedOut)
{
return;
}
PopOutCloseRequested?.Invoke(this, new OdPopOutEventArgs(item));
await _host.DockAsync(item.Id);
await NavigateAsync(item.Id);
}
[RelayCommand]
private void TogglePin(OdModuleItemViewModel item) => _settings.Update(s => s with
{
@@ -178,11 +237,18 @@ public sealed partial class OdShellViewModel : ObservableObject, IDisposable
return;
}
var wasPoppedOut = item.IsPoppedOut;
item.State = e.Module.State;
item.IsPoppedOut = e.Module.IsPoppedOut;
if (!item.IsOpen)
{
_openOrder.Remove(item);
if (string.Equals(item.Id, CurrentTarget, StringComparison.Ordinal))
if (wasPoppedOut)
{
// Closed in its own window: the window goes too.
PopOutCloseRequested?.Invoke(this, new OdPopOutEventArgs(item));
}
else if (string.Equals(item.Id, CurrentTarget, StringComparison.Ordinal))
{
// Closed while showing: the library takes its place.
CurrentView = null;
+66
View File
@@ -0,0 +1,66 @@
using System.Windows;
using System.Windows.Media;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Shell;
/// <summary>
/// Makes a window cover a monitor, on top with square corners, and puts it back where it was
/// (docs/spikes/06-libvlcsharp.md: the window covers the screen; the player never moves). Hiding the
/// window's own chrome is up to the window.
/// </summary>
internal sealed class OdWindowCover(FluentWindow window)
{
private OdWindowPlacement? _before;
public bool IsCovering => _before is not null;
/// <summary>Covers <paramref name="monitor"/>, in device pixels; false, changing nothing, if it is empty or the window covers one already.</summary>
public bool Cover(Int32Rect monitor)
{
if (_before is not null || monitor.IsEmpty)
{
return false;
}
_before = new OdWindowPlacement(
window.WindowState,
window.Left,
window.Top,
window.Width,
window.Height,
window.Topmost,
window.ResizeMode,
window.WindowCornerPreference);
var dpi = VisualTreeHelper.GetDpi(window);
window.WindowState = WindowState.Normal;
window.WindowCornerPreference = WindowCornerPreference.DoNotRound;
window.ResizeMode = ResizeMode.NoResize;
window.Topmost = true;
window.Left = monitor.X / dpi.DpiScaleX;
window.Top = monitor.Y / dpi.DpiScaleY;
window.Width = monitor.Width / dpi.DpiScaleX;
window.Height = monitor.Height / dpi.DpiScaleY;
return true;
}
/// <summary>Puts the window back as it was; false if it covered nothing.</summary>
public bool Uncover()
{
if (_before is not { } before)
{
return false;
}
_before = null;
window.WindowCornerPreference = before.Corners;
window.Topmost = before.Topmost;
window.ResizeMode = before.Resize;
window.Left = before.Left;
window.Top = before.Top;
window.Width = before.Width;
window.Height = before.Height;
window.WindowState = before.State;
return true;
}
}
@@ -0,0 +1,15 @@
using System.Windows;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Shell;
/// <summary>Where a window was, and how it looked, before it covered the screen.</summary>
internal sealed record OdWindowPlacement(
WindowState State,
double Left,
double Top,
double Width,
double Height,
bool Topmost,
ResizeMode Resize,
WindowCornerPreference Corners);
@@ -0,0 +1,19 @@
namespace OmniDeck.Core.Modules;
/// <summary>
/// A module that plays media, which the tray menu controls while something is loaded
/// (docs/SPEC.md §2: "media controls when playing").
/// </summary>
public interface IOdMediaControls
{
/// <summary>What is loaded and ready to play or pause, or null when nothing is.</summary>
string? NowPlaying { get; }
bool IsPlaying { get; }
void PlayPause();
void Next();
void Previous();
}
+38
View File
@@ -0,0 +1,38 @@
using System.Windows;
namespace OmniDeck.Core.Modules;
/// <summary>
/// How a module's view asks the window it is in to cover the screen, and learns that it does
/// (docs/SPEC.md §3.6: the module's own window covers the monitor). The request bubbles up to the
/// window as a routed event; the window answers by setting <see cref="IsActiveProperty"/> on its
/// module stage, which views inherit. A view raises the request from itself: content it hosts in a
/// window of its own, such as a video overlay, is outside the window's tree.
/// </summary>
public static class OdFullscreen
{
public static readonly RoutedEvent RequestedEvent = EventManager.RegisterRoutedEvent(
"Requested", RoutingStrategy.Bubble, typeof(EventHandler<OdFullscreenRequestedEventArgs>), typeof(OdFullscreen));
public static readonly DependencyProperty IsActiveProperty = DependencyProperty.RegisterAttached(
"IsActive", typeof(bool), typeof(OdFullscreen), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits));
/// <summary>Asks the window holding <paramref name="view"/> to cover the screen, or to stop.</summary>
public static void Request(UIElement view, bool on)
{
ArgumentNullException.ThrowIfNull(view);
view.RaiseEvent(new OdFullscreenRequestedEventArgs(RequestedEvent, view, on));
}
public static bool GetIsActive(DependencyObject element)
{
ArgumentNullException.ThrowIfNull(element);
return (bool)element.GetValue(IsActiveProperty);
}
public static void SetIsActive(DependencyObject element, bool value)
{
ArgumentNullException.ThrowIfNull(element);
element.SetValue(IsActiveProperty, value);
}
}
@@ -0,0 +1,9 @@
using System.Windows;
namespace OmniDeck.Core.Modules;
/// <summary>A view asked to cover the screen (<see cref="On"/>), or to stop.</summary>
public sealed class OdFullscreenRequestedEventArgs(RoutedEvent routedEvent, object source, bool on) : RoutedEventArgs(routedEvent, source)
{
public bool On { get; } = on;
}
@@ -19,6 +19,9 @@ public sealed class OdHostedModule
/// <summary>The module's view; <see langword="null"/> before the first open and after hibernation or closing.</summary>
public FrameworkElement? View { get; internal set; }
/// <summary>Whether the module shows in a window of its own (a pop-out) rather than in the main window.</summary>
public bool IsPoppedOut { get; internal set; }
/// <summary>When the module was last visible: the governor measures how long it has been hidden from here.</summary>
public DateTimeOffset LastActive { get; internal set; }
+87 -14
View File
@@ -7,10 +7,10 @@ using Serilog.Core;
namespace OmniDeck.Core.Modules;
/// <summary>
/// Runs the modules (docs/ARCHITECTURE.md §2): initializes each one on first use, keeps the view of
/// the visible one, and moves the others down the state ladder when the shell or the RAM governor
/// asks. Calls come from the UI thread and run one at a time, so a slow module never interleaves two
/// transitions.
/// Runs the modules (docs/ARCHITECTURE.md §2): initializes each one on first use, keeps the views of
/// the visible ones (the main window's module and those in windows of their own), and moves the
/// others down the state ladder when the shell or the RAM governor asks. Calls come from the UI thread
/// and run one at a time, so a slow module never interleaves two transitions.
/// </summary>
public sealed class OdModuleHost : IDisposable
{
@@ -58,7 +58,7 @@ public sealed class OdModuleHost : IDisposable
/// <summary>Every registered module, in registration order.</summary>
public IReadOnlyList<OdHostedModule> Modules { get; }
/// <summary>The visible module; <see langword="null"/> while the shell shows one of its own pages.</summary>
/// <summary>The module visible in the main window; <see langword="null"/> while the shell shows one of its own pages.</summary>
public OdHostedModule? Current { get; private set; }
public OdHostedModule? Find(string moduleId) => _byId.GetValueOrDefault(moduleId);
@@ -67,7 +67,7 @@ public sealed class OdModuleHost : IDisposable
/// Makes <paramref name="moduleId"/> the visible module: initializes it on first use, builds its
/// view when it has none (first open, or after hibernation) and hides the module shown before.
/// The previous module stays visible until the new one is active, so a module that fails to start
/// leaves the shell as it was.
/// leaves the shell as it was. A module in a window of its own is docked first (<see cref="DockAsync"/>).
/// </summary>
public async Task<FrameworkElement> ShowAsync(string moduleId)
{
@@ -75,19 +75,18 @@ public sealed class OdModuleHost : IDisposable
await _gate.WaitAsync();
try
{
if (hosted.IsPoppedOut)
{
// Its view belongs to the other window until that window lets go of it.
throw new InvalidOperationException($"Module '{moduleId}' shows in a window of its own.");
}
if (hosted == Current && hosted.View is { } shown)
{
return shown;
}
if (!hosted.IsInitialized)
{
await hosted.Module.InitializeAsync(CreateContext(hosted.Info.Id));
hosted.IsInitialized = true;
}
var view = hosted.View ?? hosted.Module.CreateView();
hosted.View = view;
var view = await EnsureViewAsync(hosted);
await hosted.Module.ActivateAsync();
HideCurrent();
Current = hosted;
@@ -101,6 +100,62 @@ public sealed class OdModuleHost : IDisposable
}
}
/// <summary>
/// Moves <paramref name="moduleId"/> into a window of its own (a pop-out). Like <see cref="ShowAsync"/>,
/// it initializes the module and builds its view when it has none; the module stays active, out of
/// the governor's reach, until <see cref="DockAsync"/>. The main window's module stays as it is,
/// unless it is this one, which the main window then no longer shows.
/// </summary>
public async Task<FrameworkElement> PopOutAsync(string moduleId)
{
var hosted = Get(moduleId);
await _gate.WaitAsync();
try
{
var view = await EnsureViewAsync(hosted);
if (hosted.State != OdModuleState.Active)
{
await hosted.Module.ActivateAsync();
}
if (hosted == Current)
{
Current = null;
}
hosted.IsPoppedOut = true;
hosted.LastActive = _time.GetUtcNow();
SetState(hosted, OdModuleState.Active);
return view;
}
finally
{
_gate.Release();
}
}
/// <summary>Its window closed: the module goes back to the main window, hidden, and down the ladder like any hidden module.</summary>
public async Task DockAsync(string moduleId)
{
var hosted = Get(moduleId);
await _gate.WaitAsync();
try
{
if (!hosted.IsPoppedOut)
{
return;
}
hosted.IsPoppedOut = false;
hosted.LastActive = _time.GetUtcNow();
SetState(hosted, OdModuleState.Idle);
}
finally
{
_gate.Release();
}
}
/// <summary>Hides the visible module while the shell shows one of its own pages.</summary>
public async Task HideAsync()
{
@@ -177,9 +232,14 @@ public sealed class OdModuleHost : IDisposable
if (hosted == Current)
{
Current = null;
}
if (hosted.State == OdModuleState.Active)
{
hosted.LastActive = _time.GetUtcNow();
}
hosted.IsPoppedOut = false;
SetState(hosted, OdModuleState.Closed);
}
finally
@@ -219,6 +279,19 @@ public sealed class OdModuleHost : IDisposable
: throw new ArgumentException($"No module has the id '{moduleId}'.", nameof(moduleId));
}
private async Task<FrameworkElement> EnsureViewAsync(OdHostedModule hosted)
{
if (!hosted.IsInitialized)
{
await hosted.Module.InitializeAsync(CreateContext(hosted.Info.Id));
hosted.IsInitialized = true;
}
var view = hosted.View ?? hosted.Module.CreateView();
hosted.View = view;
return view;
}
private OdModuleContext CreateContext(string moduleId) => new(
moduleId,
new OdModuleSettingsStore(_database, moduleId),
+44
View File
@@ -0,0 +1,44 @@
using System.Runtime.InteropServices;
using System.Windows;
namespace OmniDeck.Core.Runtime;
/// <summary>The monitors windows are on, for covering one in full screen.</summary>
public static partial class OdMonitors
{
private const uint DefaultToNearest = 2;
/// <summary>The bounds, in device pixels, of the monitor <paramref name="window"/> is mostly on; empty if Windows cannot say.</summary>
public static Int32Rect BoundsOf(nint window)
{
var info = new MonitorInfo { Size = Marshal.SizeOf<MonitorInfo>() };
return GetMonitorInfo(MonitorFromWindow(window, DefaultToNearest), ref info)
? new Int32Rect(info.Monitor.Left, info.Monitor.Top, info.Monitor.Right - info.Monitor.Left, info.Monitor.Bottom - info.Monitor.Top)
: Int32Rect.Empty;
}
[LibraryImport("user32.dll")]
private static partial nint MonitorFromWindow(nint window, uint flags);
[LibraryImport("user32.dll", EntryPoint = "GetMonitorInfoW")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool GetMonitorInfo(nint monitor, ref MonitorInfo info);
[StructLayout(LayoutKind.Sequential)]
private struct Bounds
{
public int Left;
public int Top;
public int Right;
public int Bottom;
}
[StructLayout(LayoutKind.Sequential)]
private struct MonitorInfo
{
public int Size;
public Bounds Monitor;
public Bounds Work;
public uint Flags;
}
}
+27
View File
@@ -1,3 +1,6 @@
using System.Security.Cryptography;
using System.Text;
namespace OmniDeck.Core.Storage;
/// <summary>
@@ -11,6 +14,13 @@ public sealed class OdDataRoot
/// <summary>The data root's folder name under <c>%LocalAppData%</c>.</summary>
public const string FolderName = "OmniDeck.Data";
/// <summary>
/// The environment variable a Debug build reads to use a data root of its own, so a development
/// copy runs beside an installed OmniDeck without touching its data (CONTRIBUTING.md). Release
/// builds never read it.
/// </summary>
public const string OverrideVariable = "OMNIDECK_DATA_ROOT";
/// <summary>Velopack's install folder name, which the data root must never be.</summary>
private const string InstallFolderName = "OmniDeck";
@@ -28,8 +38,25 @@ public sealed class OdDataRoot
public static OdDataRoot Default { get; } = new(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), FolderName));
/// <summary><paramref name="overridePath"/> when it is set, otherwise <see cref="Default"/>.</summary>
public static OdDataRoot Choose(string? overridePath) =>
string.IsNullOrWhiteSpace(overridePath) ? Default : new OdDataRoot(overridePath);
public string Root { get; }
/// <summary>Whether this is the signed-in user's real data root.</summary>
public bool IsDefault => string.Equals(
Path.TrimEndingDirectorySeparator(Root), Path.TrimEndingDirectorySeparator(Default.Root), StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Tells single-instance guards apart per data root: <see langword="null"/> for the real one and a
/// short hash of the path otherwise, so a development build with a root of its own does not hand
/// off to the installed OmniDeck.
/// </summary>
public string? InstanceSuffix => IsDefault
? null
: "." + Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(Path.TrimEndingDirectorySeparator(Root).ToUpperInvariant())), 0, 4);
public string SettingsFile => Path.Combine(Root, "settings.json");
public string DatabaseFile => Path.Combine(Root, "omnideck.db");
+28 -2
View File
@@ -21,13 +21,39 @@ internal interface IOdMediaPlayer : IDisposable
/// <summary>Whether the file has a picture; an audio file has none.</summary>
bool HasVideo { get; }
/// <summary>The file's audio tracks, libVLC's "Disable" among them.</summary>
IReadOnlyList<OdMediaTrack> AudioTracks { get; }
/// <summary>The file's subtitle tracks, and the ones added from files, libVLC's "Disable" among them.</summary>
IReadOnlyList<OdMediaTrack> SubtitleTracks { get; }
/// <summary>The audio track in use, by id.</summary>
int AudioTrack { get; set; }
/// <summary>The subtitle track shown, by id; -1 shows none.</summary>
int SubtitleTrack { get; set; }
/// <summary>The playback speed; 1 is normal.</summary>
float Rate { get; set; }
IReadOnlyList<OdMediaDevice> AudioDevices { get; }
/// <summary>The audio output device, by libVLC's id; null leaves Windows' default.</summary>
string? AudioDevice { get; set; }
/// <summary>From 0 to 100.</summary>
int Volume { get; set; }
bool Muted { get; set; }
/// <summary>Opens a file and plays it from <paramref name="from"/>, or stands paused there when <paramref name="play"/> is false.</summary>
void Open(string path, TimeSpan from, bool play);
/// <summary>Opens a file, as <paramref name="opening"/> says.</summary>
void Open(string path, OdMediaOpening opening);
/// <summary>Shows a subtitle file with the file playing; false when libVLC cannot take it.</summary>
bool AddSubtitle(string path);
/// <summary>Saves the picture on screen as a PNG; false when there is none.</summary>
bool TakeSnapshot(string path);
void Play();
@@ -0,0 +1,4 @@
namespace OmniDeck.Modules.Media;
/// <summary>An audio output device: libVLC's id for it, and Windows' name.</summary>
public sealed record OdMediaDevice(string Id, string Name);
+35 -2
View File
@@ -1,3 +1,4 @@
using System.IO;
using System.Windows;
using OmniDeck.Core.Modules;
using Serilog;
@@ -11,7 +12,7 @@ namespace OmniDeck.Modules.Media;
/// pinned; suspending lets the player go, and hibernating lets libVLC go too, since playback holds
/// 280–520 MB (docs/spikes/06-libvlcsharp.md).
/// </summary>
public sealed class OdMediaModule : IOdModule
public sealed class OdMediaModule : IOdModule, IOdMediaControls
{
private readonly Func<ILogger, IOdMediaEngine> _engines;
private IOdModuleContext? _context;
@@ -33,6 +34,38 @@ public sealed class OdMediaModule : IOdModule
internal OdMediaSession? Session => _session;
/// <summary>
/// The file loaded in a live player. Without a player there is nothing for the tray to control: starting
/// one while the view is away could make libVLC open a video window of its own.
/// </summary>
public string? NowPlaying => _session is { Player: not null, Queue.CurrentItem: { } path } ? Path.GetFileNameWithoutExtension(path) : null;
public bool IsPlaying => _session?.IsPlaying == true;
public void PlayPause()
{
if (NowPlaying is not null)
{
_session!.Toggle();
}
}
public void Next()
{
if (NowPlaying is not null)
{
_session!.Next();
}
}
public void Previous()
{
if (NowPlaying is not null)
{
_session!.Previous();
}
}
public Task InitializeAsync(IOdModuleContext context)
{
_context = context;
@@ -44,7 +77,7 @@ public sealed class OdMediaModule : IOdModule
var context = _context ?? throw new InvalidOperationException("The host initializes a module before its first view.");
_session ??= new OdMediaSession(new OdMediaStore(context.Database), () => (_engine ??= _engines(context.Log)).CreatePlayer(), context.Log);
var settings = context.Settings.Get(OdModulesJsonContext.Default.OdMediaSettings) ?? new OdMediaSettings();
_viewModel = new OdMediaViewModel(_session, settings, saved => context.Settings.Set(saved, OdModulesJsonContext.Default.OdMediaSettings));
_viewModel = new OdMediaViewModel(_session, settings, saved => context.Settings.Set(saved, OdModulesJsonContext.Default.OdMediaSettings), context.Time);
return new OdMediaView { DataContext = _viewModel };
}
@@ -0,0 +1,8 @@
namespace OmniDeck.Modules.Media;
/// <summary>How a file opens.</summary>
/// <param name="From">Where playback starts.</param>
/// <param name="Play">Whether it plays at once, or stands paused at <paramref name="From"/>.</param>
/// <param name="SubtitleEncoding">The text encoding of its subtitles; empty lets libVLC decide.</param>
/// <param name="Subtitle">A subtitle file to show with it, if the user added one.</param>
internal sealed record OdMediaOpening(TimeSpan From, bool Play, string SubtitleEncoding, string? Subtitle);
+108 -2
View File
@@ -17,6 +17,10 @@ internal sealed class OdMediaSession : IDisposable
private TimeSpan _position;
private int _volume = 80;
private bool _muted;
private float _rate = OdMediaSpeeds.Normal;
private string _subtitleEncoding = OdSubtitleEncodings.Automatic;
private string? _audioDevice;
private string? _subtitle;
public OdMediaSession(OdMediaStore store, Func<IOdMediaPlayer> newPlayer, ILogger log)
{
@@ -68,6 +72,93 @@ internal sealed class OdMediaSession : IDisposable
}
}
/// <summary>The playback speed, from a quarter to four times; it stays for the files that follow.</summary>
public float Rate
{
get => _rate;
set
{
_rate = OdMediaSpeeds.Clamp(value);
_player?.Rate = _rate;
}
}
/// <summary>The subtitles' text encoding; changing it opens the file again where it stood, as libVLC reads it only then.</summary>
public string SubtitleEncoding
{
get => _subtitleEncoding;
set
{
var encoding = OdSubtitleEncodings.Known(value);
if (string.Equals(encoding, _subtitleEncoding, StringComparison.Ordinal))
{
return;
}
_subtitleEncoding = encoding;
if (_player is { State: OdMediaState.Playing or OdMediaState.Paused } player)
{
Start(player.Time, play: player.State == OdMediaState.Playing, keepSubtitle: true);
}
}
}
/// <summary>The audio output device, by libVLC's id; null is Windows' default.</summary>
public string? AudioDevice
{
get => _audioDevice;
set
{
_audioDevice = string.IsNullOrEmpty(value) ? null : value;
_player?.AudioDevice = _audioDevice;
}
}
public IReadOnlyList<OdMediaTrack> AudioTracks => _player?.AudioTracks ?? [];
public IReadOnlyList<OdMediaTrack> SubtitleTracks => _player?.SubtitleTracks ?? [];
public IReadOnlyList<OdMediaDevice> AudioDevices => _player?.AudioDevices ?? [];
public int AudioTrack
{
get => _player?.AudioTrack ?? -1;
set => _player?.AudioTrack = value;
}
public int SubtitleTrack
{
get => _player?.SubtitleTrack ?? -1;
set => _player?.SubtitleTrack = value;
}
public bool HasVideo => _player?.HasVideo == true;
/// <summary>Shows a subtitle file with the file playing, and again if it reopens; false with nothing playing.</summary>
public bool AddSubtitle(string path)
{
if (_player is not { } player || !player.AddSubtitle(path))
{
return false;
}
_subtitle = path;
return true;
}
/// <summary>Saves the picture on screen into <paramref name="folder"/>; returns the file, or null without a picture.</summary>
public string? TakeSnapshot(string folder, DateTimeOffset now)
{
if (_player is not { HasVideo: true } player || Queue.CurrentItem is not { } current)
{
return null;
}
Directory.CreateDirectory(folder);
var path = OdMediaSnapshots.PathFor(folder, Path.GetFileNameWithoutExtension(current), now);
return player.TakeSnapshot(path) ? path : null;
}
/// <summary>Adds files to the queue and saves it; with <paramref name="play"/>, plays the first of them.</summary>
public void Add(IReadOnlyCollection<string> paths, bool play)
{
@@ -194,7 +285,7 @@ internal sealed class OdMediaSession : IDisposable
public void Dispose() => Release();
private void Start(TimeSpan from, bool play)
private void Start(TimeSpan from, bool play, bool keepSubtitle = false)
{
if (Queue.CurrentItem is not { } path)
{
@@ -206,13 +297,24 @@ internal sealed class OdMediaSession : IDisposable
_player = _newPlayer();
_player.StateChanged += OnStateChanged;
_player.TimeChanged += OnTimeChanged;
if (_audioDevice is not null)
{
_player.AudioDevice = _audioDevice;
}
PlayerChanged?.Invoke(this, EventArgs.Empty);
}
// A subtitle file belongs to the file it was added to.
if (!keepSubtitle)
{
_subtitle = null;
}
_player.Volume = _volume;
_player.Muted = _muted;
_position = from;
_player.Open(path, from, play);
_player.Open(path, new OdMediaOpening(from, play, _subtitleEncoding, _subtitle));
Save();
Changed?.Invoke(this, EventArgs.Empty);
}
@@ -236,6 +338,10 @@ internal sealed class OdMediaSession : IDisposable
_position = _player?.Time ?? _position;
Save();
break;
case OdMediaState.Playing when _player is { } player && Math.Abs(player.Rate - _rate) > 0.001f:
// libVLC starts each file at normal speed.
player.Rate = _rate;
break;
}
Changed?.Invoke(this, EventArgs.Empty);
@@ -1,6 +1,6 @@
namespace OmniDeck.Modules.Media;
/// <summary>The media module's settings document: the volume, and whether the queue panel shows.</summary>
/// <summary>The media module's settings document: volume, speed, subtitle encoding, audio device, and whether the queue panel shows.</summary>
public sealed record OdMediaSettings
{
public int Volume { get; init; } = 80;
@@ -8,4 +8,12 @@ public sealed record OdMediaSettings
public bool Muted { get; init; }
public bool QueueVisible { get; init; } = true;
public float Rate { get; init; } = 1f;
/// <summary>libVLC's name for the subtitles' encoding; empty lets libVLC decide.</summary>
public string SubtitleEncoding { get; init; } = "";
/// <summary>libVLC's id for the audio output device; null is Windows' default.</summary>
public string? AudioDevice { get; init; }
}
@@ -0,0 +1,17 @@
using System.Globalization;
using System.IO;
namespace OmniDeck.Modules.Media;
/// <summary>Where snapshots go: Pictures\OmniDeck, named after the file and the moment.</summary>
internal static class OdMediaSnapshots
{
public static string Folder => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "OmniDeck");
public static string PathFor(string folder, string title, DateTimeOffset now)
{
var safe = string.Concat(title.Select(c => Array.IndexOf(Path.GetInvalidFileNameChars(), c) >= 0 ? '_' : c)).Trim();
var name = (safe.Length == 0 ? "OmniDeck" : safe) + " " + now.ToString("yyyy-MM-dd HH-mm-ss", CultureInfo.InvariantCulture) + ".png";
return Path.Combine(folder, name);
}
}
@@ -0,0 +1,16 @@
using System.Globalization;
namespace OmniDeck.Modules.Media;
/// <summary>The playback speeds the player offers, from a quarter to four times (docs/SPEC.md §3.6).</summary>
internal static class OdMediaSpeeds
{
public const float Normal = 1f;
public static IReadOnlyList<float> All { get; } = [0.25f, 0.5f, 0.75f, 1f, 1.25f, 1.5f, 1.75f, 2f, 3f, 4f];
public static float Clamp(float rate) => float.IsFinite(rate) ? Math.Clamp(rate, All[0], All[^1]) : Normal;
/// <summary>"1.5×", in the regional number format.</summary>
public static string Title(float rate) => string.Format(CultureInfo.CurrentCulture, "{0:0.##}×", rate);
}
@@ -0,0 +1,4 @@
namespace OmniDeck.Modules.Media;
/// <summary>An audio or subtitle track as libVLC names it; id -1 is libVLC's "Disable".</summary>
public sealed record OdMediaTrack(int Id, string Name);
+96 -48
View File
@@ -20,13 +20,16 @@
<!-- The video is a native window; its WPF content is drawn in an overlay window above it (docs/spikes/06-libvlcsharp.md). -->
<vlc:VideoView x:Name="Video" Grid.Column="0">
<!-- Opaque where there is no picture: libVLC's video window is blank until a video plays, and stays so for audio. -->
<Grid>
<Grid Focusable="True"
KeyDown="OnVideoKeyDown"
MouseLeftButtonDown="OnVideoMouseDown">
<Grid.Style>
<Style TargetType="Grid">
<Setter Property="Background" Value="{DynamicResource SolidBackgroundFillColorBaseBrush}" />
<Style.Triggers>
<!-- Not quite transparent: a click on a fully clear pixel of the overlay window falls through to the video window. -->
<DataTrigger Binding="{Binding ShowsVideo}" Value="True">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Background" Value="#01000000" />
</DataTrigger>
</Style.Triggers>
</Style>
@@ -44,67 +47,112 @@
<Border Grid.Row="1"
Padding="{DynamicResource Od.Padding.Card}"
Background="{DynamicResource SolidBackgroundFillColorSecondaryBrush}">
<DockPanel>
<StackPanel DockPanel.Dock="Left" Orientation="Horizontal">
<ui:Button AutomationProperties.Name="{res:OdLoc Media_Previous}"
Command="{Binding PreviousCommand}"
Icon="{ui:SymbolIcon Previous24}"
ToolTip="{res:OdLoc Media_Previous}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_PlayPause}"
Command="{Binding PlayPauseCommand}"
Icon="{ui:SymbolIcon Play24}"
ToolTip="{res:OdLoc Media_PlayPause}" />
<ui:Button AutomationProperties.Name="{res:OdLoc Media_Next}"
Command="{Binding NextCommand}"
Icon="{ui:SymbolIcon Next24}"
ToolTip="{res:OdLoc Media_Next}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_Stop}"
Command="{Binding StopCommand}"
Icon="{ui:SymbolIcon Stop24}"
ToolTip="{res:OdLoc Media_Stop}" />
</StackPanel>
<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
<ui:Button AutomationProperties.Name="{res:OdLoc Media_Mute}"
<!-- The seek bar has a row of its own, so it keeps its length beside the queue; when the bar is narrow, the volume slider gives way first. -->
<StackPanel>
<DockPanel>
<TextBlock DockPanel.Dock="Right"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{Binding TimeText}" />
<TextBlock FontWeight="SemiBold"
Text="{Binding Title}"
TextTrimming="CharacterEllipsis" />
</DockPanel>
<Slider AutomationProperties.Name="{res:OdLoc Media_Seek}"
IsMoveToPointEnabled="True"
Maximum="{Binding Length}"
Minimum="0"
Value="{Binding Position, Delay=150}" />
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="3*"
MinWidth="64"
MaxWidth="136" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="0" Orientation="Horizontal">
<ui:Button AutomationProperties.Name="{res:OdLoc Media_Previous}"
Command="{Binding PreviousCommand}"
Icon="{ui:SymbolIcon Previous24}"
ToolTip="{res:OdLoc Media_Previous}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_PlayPause}"
Command="{Binding PlayPauseCommand}"
ToolTip="{res:OdLoc Media_PlayPause}">
<ui:Button.Icon>
<!-- Pause while playing, Play otherwise. -->
<ui:SymbolIcon>
<ui:SymbolIcon.Style>
<Style TargetType="ui:SymbolIcon">
<Setter Property="Symbol" Value="Play24" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsPlaying}" Value="True">
<Setter Property="Symbol" Value="Pause24" />
</DataTrigger>
</Style.Triggers>
</Style>
</ui:SymbolIcon.Style>
</ui:SymbolIcon>
</ui:Button.Icon>
</ui:Button>
<ui:Button AutomationProperties.Name="{res:OdLoc Media_Next}"
Command="{Binding NextCommand}"
Icon="{ui:SymbolIcon Next24}"
ToolTip="{res:OdLoc Media_Next}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_Stop}"
Command="{Binding StopCommand}"
Icon="{ui:SymbolIcon Stop24}"
ToolTip="{res:OdLoc Media_Stop}" />
</StackPanel>
<ui:Button Grid.Column="2"
AutomationProperties.Name="{res:OdLoc Media_Mute}"
Command="{Binding ToggleMuteCommand}"
Icon="{ui:SymbolIcon Speaker224}"
ToolTip="{res:OdLoc Media_Mute}" />
<Slider Width="120"
<!-- MinWidth: WPF-UI's style asks for 104 px, which a narrow column would clip, thumb and all. -->
<Slider Grid.Column="3"
MinWidth="0"
Margin="{DynamicResource Od.Padding.Control}"
VerticalAlignment="Center"
AutomationProperties.Name="{res:OdLoc Media_Volume}"
Maximum="100"
Minimum="0"
Value="{Binding Volume}" />
<ui:Button AutomationProperties.Name="{res:OdLoc Media_Queue}"
Command="{Binding ToggleQueueCommand}"
Icon="{ui:SymbolIcon TextBulletListLtr24}"
ToolTip="{res:OdLoc Media_Queue}" />
</StackPanel>
<StackPanel Margin="{DynamicResource Od.Padding.Control}" VerticalAlignment="Center">
<DockPanel>
<TextBlock DockPanel.Dock="Right"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{Binding TimeText}" />
<TextBlock FontWeight="SemiBold"
Text="{Binding Title}"
TextTrimming="CharacterEllipsis" />
</DockPanel>
<Slider AutomationProperties.Name="{res:OdLoc Media_Seek}"
IsMoveToPointEnabled="True"
Maximum="{Binding Length}"
Minimum="0"
Value="{Binding Position, Delay=150}" />
</StackPanel>
</DockPanel>
<StackPanel Grid.Column="4" Orientation="Horizontal">
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_More}"
Click="OnMoreClick"
Icon="{ui:SymbolIcon MoreHorizontal24}"
ToolTip="{res:OdLoc Media_More}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_Fullscreen}"
Click="OnFullscreenClick"
Icon="{ui:SymbolIcon FullScreenMaximize24}"
ToolTip="{res:OdLoc Media_Fullscreen}"
Visibility="{Binding IsWindowed, Converter={StaticResource Visible}}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_ExitFullscreen}"
Click="OnFullscreenClick"
Icon="{ui:SymbolIcon FullScreenMinimize24}"
ToolTip="{res:OdLoc Media_ExitFullscreen}"
Visibility="{Binding IsFullscreen, Converter={StaticResource Visible}}" />
<ui:Button AutomationProperties.Name="{res:OdLoc Media_Queue}"
Command="{Binding ToggleQueueCommand}"
Icon="{ui:SymbolIcon TextBulletListLtr24}"
ToolTip="{res:OdLoc Media_Queue}" />
</StackPanel>
</Grid>
</StackPanel>
</Border>
</Grid>
</vlc:VideoView>
<DockPanel Grid.Column="1"
Width="300"
Visibility="{Binding QueueVisible, Converter={StaticResource Visible}}">
Visibility="{Binding ShowsQueue, Converter={StaticResource Visible}}">
<WrapPanel Margin="{DynamicResource Od.Padding.Control}" DockPanel.Dock="Top">
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Click="OnAddFiles"
@@ -1,7 +1,10 @@
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using Microsoft.Win32;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
namespace OmniDeck.Modules.Media;
@@ -16,6 +19,16 @@ public partial class OdMediaView
private OdMediaViewModel? ViewModel => DataContext as OdMediaViewModel;
/// <summary>The window covers the screen, or stops: the screen follows.</summary>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == OdFullscreen.IsActiveProperty && ViewModel is { } model)
{
model.IsFullscreen = (bool)e.NewValue;
}
}
private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (e.OldValue is OdMediaViewModel old)
@@ -26,6 +39,7 @@ public partial class OdMediaView
if (e.NewValue is OdMediaViewModel model)
{
model.PlayerChanged += OnPlayerChanged;
model.IsFullscreen = OdFullscreen.GetIsActive(this);
ShowPlayer(model);
}
}
@@ -79,6 +93,87 @@ public partial class OdMediaView
}
}
// The overlay lives in a window of its own: requests go out from the view itself.
private void OnFullscreenClick(object sender, RoutedEventArgs e) => OdFullscreen.Request(this, !OdFullscreen.GetIsActive(this));
private void OnVideoMouseDown(object sender, MouseButtonEventArgs e)
{
// Esc works once the picture was clicked: the overlay is a window of its own.
Keyboard.Focus((IInputElement)sender);
if (e.ClickCount == 2)
{
e.Handled = true;
OdFullscreen.Request(this, !OdFullscreen.GetIsActive(this));
}
}
private void OnVideoKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Escape && OdFullscreen.GetIsActive(this))
{
e.Handled = true;
OdFullscreen.Request(this, on: false);
}
}
// The menu is built when it opens: the tracks and devices are those of the file playing now.
private void OnMoreClick(object sender, RoutedEventArgs e)
{
if (ViewModel is not { } model)
{
return;
}
var subtitles = Submenu(OdLocalization.Get("Media_Subtitles"), model.SubtitleTracks.Select(track => Choice(track.Name, track.Id == model.SubtitleTrack, () => model.SetSubtitleTrack(track.Id))));
subtitles.Items.Add(new Separator());
subtitles.Items.Add(Choice(OdLocalization.Get("Media_AddSubtitle"), isChecked: false, AddSubtitleFile, enabled: model.Player is not null));
subtitles.IsEnabled = true;
IEnumerable<MenuItem> devices =
[
Choice(OdLocalization.Get("Media_DefaultDevice"), model.AudioDevice is null, () => model.SetAudioDevice(null)),
.. model.AudioDevices.Select(device => Choice(device.Name, string.Equals(device.Id, model.AudioDevice, StringComparison.Ordinal), () => model.SetAudioDevice(device.Id))),
];
var menu = new ContextMenu { PlacementTarget = (UIElement)sender, Placement = PlacementMode.Top };
menu.Items.Add(Submenu(OdLocalization.Get("Media_AudioTrack"), model.AudioTracks.Select(track => Choice(track.Name, track.Id == model.AudioTrack, () => model.SetAudioTrack(track.Id)))));
menu.Items.Add(subtitles);
menu.Items.Add(Submenu(OdLocalization.Get("Media_SubtitleEncoding"), OdSubtitleEncodings.All.Select(encoding => Choice(OdSubtitleEncodings.Title(encoding), string.Equals(encoding, model.SubtitleEncoding, StringComparison.Ordinal), () => model.SetSubtitleEncoding(encoding)))));
menu.Items.Add(Submenu(OdLocalization.Get("Media_Speed"), OdMediaSpeeds.All.Select(rate => Choice(OdMediaSpeeds.Title(rate), Math.Abs(rate - model.Rate) < 0.001f, () => model.SetRate(rate)))));
menu.Items.Add(Submenu(OdLocalization.Get("Media_AudioDevice"), devices));
menu.Items.Add(new Separator());
menu.Items.Add(Choice(OdLocalization.Get("Media_Snapshot"), isChecked: false, () => model.TakeSnapshotCommand.Execute(null), enabled: model.ShowsVideo));
menu.IsOpen = true;
}
private static MenuItem Submenu(string header, IEnumerable<MenuItem> items)
{
var submenu = new MenuItem { Header = header };
foreach (var item in items)
{
submenu.Items.Add(item);
}
submenu.IsEnabled = submenu.Items.Count > 0;
return submenu;
}
private static MenuItem Choice(string header, bool isChecked, Action choose, bool enabled = true)
{
var item = new MenuItem { Header = header, IsChecked = isChecked, IsEnabled = enabled };
item.Click += (_, _) => choose();
return item;
}
private void AddSubtitleFile()
{
var dialog = new OpenFileDialog { Filter = OdLocalization.Get("Media_SubtitleFilter") };
if (dialog.ShowDialog(Window.GetWindow(this)) == true)
{
ViewModel?.AddSubtitle(dialog.FileName);
}
}
private void OnDrop(object sender, DragEventArgs e)
{
if (e.Data.GetData(DataFormats.FileDrop) is string[] paths)
+64 -1
View File
@@ -12,6 +12,7 @@ public sealed partial class OdMediaViewModel : ObservableObject, IDisposable
{
private readonly OdMediaSession _session;
private readonly Action<OdMediaSettings> _saveSettings;
private readonly TimeProvider _time;
private OdMediaSettings _settings;
private bool _syncing;
@@ -44,18 +45,29 @@ public sealed partial class OdMediaViewModel : ObservableObject, IDisposable
private bool _muted;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowsQueue))]
private bool _queueVisible;
/// <summary>Whether the window covers the screen for the player; the queue steps aside meanwhile.</summary>
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowsQueue))]
[NotifyPropertyChangedFor(nameof(IsWindowed))]
private bool _isFullscreen;
[ObservableProperty]
private string _message = "";
internal OdMediaViewModel(OdMediaSession session, OdMediaSettings settings, Action<OdMediaSettings> saveSettings)
internal OdMediaViewModel(OdMediaSession session, OdMediaSettings settings, Action<OdMediaSettings> saveSettings, TimeProvider time)
{
_session = session;
_settings = settings;
_saveSettings = saveSettings;
_time = time;
_session.Volume = settings.Volume;
_session.Muted = settings.Muted;
_session.Rate = settings.Rate;
_session.SubtitleEncoding = settings.SubtitleEncoding;
_session.AudioDevice = settings.AudioDevice;
_volume = settings.Volume;
_muted = settings.Muted;
_queueVisible = settings.QueueVisible;
@@ -70,8 +82,54 @@ public sealed partial class OdMediaViewModel : ObservableObject, IDisposable
public ObservableCollection<OdMediaItem> Items { get; } = [];
public bool ShowsQueue => QueueVisible && !IsFullscreen;
public bool IsWindowed => !IsFullscreen;
internal IOdMediaPlayer? Player => _session.Player;
internal IReadOnlyList<OdMediaTrack> AudioTracks => _session.AudioTracks;
internal int AudioTrack => _session.AudioTrack;
internal IReadOnlyList<OdMediaTrack> SubtitleTracks => _session.SubtitleTracks;
internal int SubtitleTrack => _session.SubtitleTrack;
internal IReadOnlyList<OdMediaDevice> AudioDevices => _session.AudioDevices;
internal string? AudioDevice => _session.AudioDevice;
internal string SubtitleEncoding => _session.SubtitleEncoding;
internal float Rate => _session.Rate;
internal void SetAudioTrack(int id) => _session.AudioTrack = id;
internal void SetSubtitleTrack(int id) => _session.SubtitleTrack = id;
internal void SetSubtitleEncoding(string encoding)
{
_session.SubtitleEncoding = encoding;
SaveSettings(_settings with { SubtitleEncoding = _session.SubtitleEncoding });
}
internal void SetRate(float rate)
{
_session.Rate = rate;
SaveSettings(_settings with { Rate = _session.Rate });
}
internal void SetAudioDevice(string? id)
{
_session.AudioDevice = id;
SaveSettings(_settings with { AudioDevice = _session.AudioDevice });
}
/// <summary>Shows a subtitle file with the file playing.</summary>
internal void AddSubtitle(string path) =>
Message = _session.AddSubtitle(path) ? "" : OdLocalization.Format("Media_SubtitleFailed", Path.GetFileName(path));
/// <summary>Adds files, or a playlist's files, and plays the first one added.</summary>
public void Add(IEnumerable<string> paths)
{
@@ -144,6 +202,11 @@ public sealed partial class OdMediaViewModel : ObservableObject, IDisposable
[RelayCommand]
private void Clear() => _session.Clear();
[RelayCommand]
private void TakeSnapshot() => Message = _session.TakeSnapshot(OdMediaSnapshots.Folder, _time.GetLocalNow()) is { } path
? OdLocalization.Format("Media_SnapshotSaved", path)
: OdLocalization.Get("Media_SnapshotFailed");
[RelayCommand]
private void ToggleQueue() => QueueVisible = !QueueVisible;
@@ -0,0 +1,41 @@
using OmniDeck.Core.Localization;
namespace OmniDeck.Modules.Media;
/// <summary>
/// The subtitle encodings the player offers (docs/SPEC.md §3.6): the names libVLC's <c>subsdec-encoding</c>
/// takes, for the scripts subtitle files most often come in when they are not Unicode.
/// </summary>
internal static class OdSubtitleEncodings
{
/// <summary>libVLC decides: UTF-8 when the file reads as such, else the system's code page.</summary>
public const string Automatic = "";
public static IReadOnlyList<string> All { get; } =
[
Automatic, "UTF-8", "Windows-1252", "Windows-1250", "Windows-1251", "Windows-1253", "Windows-1254",
"Windows-1258", "Windows-874", "Shift_JIS", "GB18030", "Big5", "EUC-KR",
];
/// <summary>The encoding as the menu names it.</summary>
public static string Title(string encoding) => encoding switch
{
Automatic => OdLocalization.Get("Media_EncodingAuto"),
"UTF-8" => OdLocalization.Get("Media_EncodingUtf8"),
"Windows-1252" => OdLocalization.Get("Media_EncodingWestern"),
"Windows-1250" => OdLocalization.Get("Media_EncodingCentral"),
"Windows-1251" => OdLocalization.Get("Media_EncodingCyrillic"),
"Windows-1253" => OdLocalization.Get("Media_EncodingGreek"),
"Windows-1254" => OdLocalization.Get("Media_EncodingTurkish"),
"Windows-1258" => OdLocalization.Get("Media_EncodingVietnamese"),
"Windows-874" => OdLocalization.Get("Media_EncodingThai"),
"Shift_JIS" => OdLocalization.Get("Media_EncodingJapanese"),
"GB18030" => OdLocalization.Get("Media_EncodingChineseSimplified"),
"Big5" => OdLocalization.Get("Media_EncodingChineseTraditional"),
"EUC-KR" => OdLocalization.Get("Media_EncodingKorean"),
_ => encoding,
};
/// <summary>A setting a hand-edited file may carry, brought back to one the menu offers.</summary>
public static string Known(string? encoding) => All.FirstOrDefault(known => string.Equals(known, encoding, StringComparison.OrdinalIgnoreCase)) ?? Automatic;
}
+51 -4
View File
@@ -44,6 +44,38 @@ internal sealed class OdVlcPlayer : IOdMediaPlayer
public bool HasVideo => Native.VideoTrackCount > 0;
public IReadOnlyList<OdMediaTrack> AudioTracks => [.. Native.AudioTrackDescription.Select(track => new OdMediaTrack(track.Id, track.Name))];
public IReadOnlyList<OdMediaTrack> SubtitleTracks => [.. Native.SpuDescription.Select(track => new OdMediaTrack(track.Id, track.Name))];
public int AudioTrack
{
get => Native.AudioTrack;
set => Native.SetAudioTrack(value);
}
public int SubtitleTrack
{
get => Native.Spu;
set => Native.SetSpu(value);
}
public float Rate
{
get => Native.Rate;
set => Native.SetRate(value);
}
// libVLC lists its own "Default", with no id; the menu has "Windows default" for that.
public IReadOnlyList<OdMediaDevice> AudioDevices =>
[.. Native.AudioOutputDeviceEnum.Where(device => !string.IsNullOrEmpty(device.DeviceIdentifier)).Select(device => new OdMediaDevice(device.DeviceIdentifier, device.Description))];
public string? AudioDevice
{
get => Native.OutputDevice;
set => Native.SetOutputDevice(value ?? "");
}
public int Volume
{
get => Native.Volume;
@@ -56,19 +88,30 @@ internal sealed class OdVlcPlayer : IOdMediaPlayer
set => Native.Mute = value;
}
public void Open(string path, TimeSpan from, bool play)
public void Open(string path, OdMediaOpening opening)
{
ArgumentNullException.ThrowIfNull(opening);
var media = new VlcMedia(_libVlc, path, FromType.FromPath);
if (from > TimeSpan.Zero)
if (opening.From > TimeSpan.Zero)
{
media.AddOption(":start-time=" + from.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture));
media.AddOption(":start-time=" + opening.From.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture));
}
if (!play)
if (!opening.Play)
{
media.AddOption(":start-paused");
}
if (opening.SubtitleEncoding.Length > 0)
{
media.AddOption(":subsdec-encoding=" + opening.SubtitleEncoding);
}
if (opening.Subtitle is { } subtitle)
{
media.AddSlave(MediaSlaveType.Subtitle, 4, new Uri(subtitle).AbsoluteUri);
}
_media?.Dispose();
_media = media;
State = OdMediaState.Opening;
@@ -83,6 +126,10 @@ internal sealed class OdVlcPlayer : IOdMediaPlayer
public void Seek(TimeSpan time) => Native.Time = (long)time.TotalMilliseconds;
public bool AddSubtitle(string path) => Native.AddSlave(MediaSlaveType.Subtitle, new Uri(path).AbsoluteUri, select: true);
public bool TakeSnapshot(string path) => Native.TakeSnapshot(0, path, 0, 0);
public void Dispose()
{
Native.Stop();
@@ -520,4 +520,88 @@
<data name="Media_PlaylistFilter" xml:space="preserve">
<value>Playlists (*.m3u, *.m3u8)|*.m3u;*.m3u8</value>
</data>
<data name="Media_More" xml:space="preserve">
<value>More</value>
</data>
<data name="Media_AudioTrack" xml:space="preserve">
<value>Audio track</value>
</data>
<data name="Media_Subtitles" xml:space="preserve">
<value>Subtitles</value>
</data>
<data name="Media_AddSubtitle" xml:space="preserve">
<value>Add a subtitle file…</value>
</data>
<data name="Media_SubtitleFilter" xml:space="preserve">
<value>Subtitles (*.srt, *.ass, *.ssa, *.vtt, *.sub)|*.srt;*.ass;*.ssa;*.vtt;*.sub</value>
</data>
<data name="Media_SubtitleFailed" xml:space="preserve">
<value>{0} could not be added as subtitles.</value>
</data>
<data name="Media_SubtitleEncoding" xml:space="preserve">
<value>Subtitle encoding</value>
</data>
<data name="Media_Speed" xml:space="preserve">
<value>Speed</value>
</data>
<data name="Media_AudioDevice" xml:space="preserve">
<value>Audio device</value>
</data>
<data name="Media_DefaultDevice" xml:space="preserve">
<value>Windows default</value>
</data>
<data name="Media_Snapshot" xml:space="preserve">
<value>Take a snapshot</value>
</data>
<data name="Media_SnapshotSaved" xml:space="preserve">
<value>Saved {0}</value>
</data>
<data name="Media_SnapshotFailed" xml:space="preserve">
<value>There is no picture to take a snapshot of.</value>
</data>
<data name="Media_EncodingAuto" xml:space="preserve">
<value>Automatic</value>
</data>
<data name="Media_EncodingUtf8" xml:space="preserve">
<value>Unicode (UTF-8)</value>
</data>
<data name="Media_EncodingWestern" xml:space="preserve">
<value>Western European (Windows-1252)</value>
</data>
<data name="Media_EncodingCentral" xml:space="preserve">
<value>Central European (Windows-1250)</value>
</data>
<data name="Media_EncodingCyrillic" xml:space="preserve">
<value>Cyrillic (Windows-1251)</value>
</data>
<data name="Media_EncodingGreek" xml:space="preserve">
<value>Greek (Windows-1253)</value>
</data>
<data name="Media_EncodingTurkish" xml:space="preserve">
<value>Turkish (Windows-1254)</value>
</data>
<data name="Media_EncodingVietnamese" xml:space="preserve">
<value>Vietnamese (Windows-1258)</value>
</data>
<data name="Media_EncodingThai" xml:space="preserve">
<value>Thai (Windows-874)</value>
</data>
<data name="Media_EncodingJapanese" xml:space="preserve">
<value>Japanese (Shift_JIS)</value>
</data>
<data name="Media_EncodingChineseSimplified" xml:space="preserve">
<value>Chinese, Simplified (GB18030)</value>
</data>
<data name="Media_EncodingChineseTraditional" xml:space="preserve">
<value>Chinese, Traditional (Big5)</value>
</data>
<data name="Media_EncodingKorean" xml:space="preserve">
<value>Korean (EUC-KR)</value>
</data>
<data name="Media_Fullscreen" xml:space="preserve">
<value>Full screen (double-click the video; Esc leaves)</value>
</data>
<data name="Media_ExitFullscreen" xml:space="preserve">
<value>Leave full screen (Esc)</value>
</data>
</root>
+34 -1
View File
@@ -3,6 +3,7 @@ using System.Windows;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
using OmniDeck.Web.Navigation;
using OmniDeck.Web.Runtime;
@@ -11,7 +12,7 @@ namespace OmniDeck.Web.Apps;
/// <summary>
/// A web app's screen (docs/ARCHITECTURE.md §3): WebView2 on the app's catalog profile, with the
/// browser settings, the navigation policy, sign-in popups, notifications, permission questions,
/// crash recovery and the console capture.
/// full screen, crash recovery and the console capture.
/// </summary>
public partial class OdWebAppView : IOdWebSurface
{
@@ -137,6 +138,7 @@ public partial class OdWebAppView : IOdWebSurface
core.NewWindowRequested += OnNewWindowRequested;
core.NavigationCompleted += OnNavigationCompleted;
core.ProcessFailed += OnProcessFailed;
core.ContainsFullScreenElementChanged += OnFullScreenElementChanged;
core.NotificationReceived += OnNotificationReceived;
core.PermissionRequested += OnPermissionRequested;
_ = CaptureConsoleAsync(core);
@@ -230,6 +232,37 @@ public partial class OdWebAppView : IOdWebSurface
}
}
// A page's full screen (a video's, say) fills the monitor: the window covers it (OdFullscreen).
private void OnFullScreenElementChanged(object? sender, object e)
{
if (sender is CoreWebView2 core)
{
OdFullscreen.Request(this, core.ContainsFullScreenElement);
}
}
/// <summary>The window left full screen on its own (Esc, another module): the page leaves it too.</summary>
protected override void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == OdFullscreen.IsActiveProperty && e.NewValue is false && _browser?.CoreWebView2 is { ContainsFullScreenElement: true } core)
{
_ = LeavePageFullScreenAsync(core);
}
}
private async Task LeavePageFullScreenAsync(CoreWebView2 core)
{
try
{
await core.ExecuteScriptAsync("if (document.fullscreenElement) { document.exitFullscreen().catch(() => {}); }");
}
catch (Exception ex) when (ex is COMException or InvalidOperationException)
{
_module.Log.Debug(ex, "The page could not leave full screen");
}
}
private void OnProcessFailed(object? sender, CoreWebView2ProcessFailedEventArgs e)
{
_module.Log.Warning("A web app process failed: {Kind} ({Reason})", e.ProcessFailedKind, e.Reason);
+158 -5
View File
@@ -179,6 +179,138 @@ public sealed class OdMediaTests : IDisposable
Assert.Empty(new OdMediaStore(_database).Load().Queue.Items);
}
[Fact]
public void Options_ReachThePlayer_AndAChangedEncodingReopensWhereItStood()
{
using var session = NewSession();
session.AudioDevice = "speakers";
session.Rate = 9f;
session.Add(["film.mkv", "next.mkv"], play: true);
var player = _engine.Players[0];
Assert.Equal("speakers", player.AudioDevice);
Assert.Equal(4f, session.Rate);
player.Rate = 1f;
player.Raise(OdMediaState.Playing);
Assert.Equal(4f, player.Rate);
player.AudioTracks = [new(-1, "Disable"), new(1, "English")];
player.SubtitleTracks = [new(-1, "Disable"), new(2, "Vietnamese")];
session.AudioTrack = 1;
session.SubtitleTrack = 2;
Assert.Equal((1, 2), (player.AudioTrack, player.SubtitleTrack));
Assert.Equal(2, session.AudioTracks.Count);
Assert.Equal(2, session.SubtitleTracks.Count);
Assert.True(session.AddSubtitle(@"C:\subs\film.vi.srt"));
player.Time = TimeSpan.FromSeconds(42);
session.SubtitleEncoding = "Windows-1258";
Assert.Equal(new OdMediaOpening(TimeSpan.FromSeconds(42), true, "Windows-1258", @"C:\subs\film.vi.srt"), player.LastOpening);
session.SubtitleEncoding = "nonsense";
Assert.Equal("", player.LastOpening?.SubtitleEncoding);
session.Next();
Assert.Null(player.LastOpening?.Subtitle);
Assert.Equal("", session.SubtitleEncoding);
}
[Fact]
public void ASnapshot_NeedsAPicture_AndIsNamedAfterTheFile()
{
using var session = NewSession();
var folder = _temp.Combine("shots");
var now = new DateTimeOffset(2026, 11, 2, 9, 5, 7, TimeSpan.FromHours(7));
Assert.Null(session.TakeSnapshot(folder, now));
session.Add(["My: Film.mkv"], play: true);
Assert.Null(session.TakeSnapshot(folder, now));
_engine.Players[0].HasVideo = true;
Assert.Equal(Path.Combine(folder, "My_ Film 2026-11-02 09-05-07.png"), session.TakeSnapshot(folder, now));
Assert.True(Directory.Exists(folder));
}
[Fact]
public void Encodings_AndSpeeds_AreTheOnesTheMenuOffers()
{
Assert.All(OdSubtitleEncodings.All, encoding => Assert.False(string.IsNullOrEmpty(OdSubtitleEncodings.Title(encoding))));
Assert.Equal(OdSubtitleEncodings.All.Count, OdSubtitleEncodings.All.Distinct(StringComparer.OrdinalIgnoreCase).Count());
Assert.Equal("Vietnamese (Windows-1258)", OdSubtitleEncodings.Title("Windows-1258"));
Assert.Equal("Shift_JIS", OdSubtitleEncodings.Known("shift_jis"));
Assert.Equal("", OdSubtitleEncodings.Known(null));
Assert.Equal(0.25f, OdMediaSpeeds.Clamp(0.1f));
Assert.Equal(1f, OdMediaSpeeds.Clamp(float.NaN));
Assert.Equal(OdMediaSpeeds.All.Count, OdMediaSpeeds.All.Distinct().Count());
}
[Fact]
public void TheScreen_KeepsTheSpeedEncodingAndDevice_InTheSettings() => OdSta.Run(() =>
{
using var session = NewSession();
OdMediaSettings? saved = null;
using var screen = new OdMediaViewModel(session, new OdMediaSettings { Rate = 1.5f, SubtitleEncoding = "Big5" }, settings => saved = settings, TimeProvider.System);
Assert.Equal((1.5f, "Big5"), (session.Rate, session.SubtitleEncoding));
screen.SetRate(2f);
screen.SetSubtitleEncoding("UTF-8");
screen.SetAudioDevice("headphones");
Assert.Equal(2f, saved?.Rate);
Assert.Equal("UTF-8", saved?.SubtitleEncoding);
Assert.Equal("headphones", saved?.AudioDevice);
screen.AddSubtitle(@"C:\subs\film.srt");
Assert.Equal("film.srt could not be added as subtitles.", screen.Message);
return Task.CompletedTask;
});
[Fact]
public void TheTray_ControlsALoadedPlayer_AndNothingElse() => OdSta.Run(async () =>
{
var module = new OdMediaModule(_ => _engine);
IOdMediaControls tray = module;
var time = new FakeTimeProvider(new DateTimeOffset(2026, 11, 2, 3, 0, 0, TimeSpan.Zero));
using var host = new OdModuleHost([module], _database, Logger.None, time, new OdFakeNotifier(), OdTestHttp.Client);
Assert.Null(tray.NowPlaying);
tray.PlayPause();
Assert.Empty(_engine.Players);
await host.ShowAsync("media");
module.Session!.Add([@"C:\Music\01 one.mp3", @"C:\Music\02 two.mp3"], play: true);
Assert.Equal("01 one", tray.NowPlaying);
Assert.True(tray.IsPlaying);
tray.PlayPause();
Assert.False(tray.IsPlaying);
tray.Next();
Assert.Equal("02 two", tray.NowPlaying);
tray.Previous();
Assert.Equal("01 one", tray.NowPlaying);
module.Session.Release();
Assert.Null(tray.NowPlaying);
});
[Fact]
public void InFullScreen_TheQueueStepsAside() => OdSta.Run(() =>
{
using var session = NewSession();
using var screen = new OdMediaViewModel(session, new OdMediaSettings(), _ => { }, TimeProvider.System);
Assert.True(screen.ShowsQueue);
Assert.True(screen.IsWindowed);
screen.IsFullscreen = true;
Assert.False(screen.ShowsQueue);
Assert.False(screen.IsWindowed);
screen.IsFullscreen = false;
screen.ToggleQueueCommand.Execute(null);
Assert.False(screen.ShowsQueue);
return Task.CompletedTask;
});
[Fact]
public void LibVlcNoise_StaysOutOfTheLog()
{
@@ -198,7 +330,7 @@ public sealed class OdMediaTests : IDisposable
File.WriteAllText(Path.Combine(folder, "01 a.mp3"), "");
var playlist = _temp.Combine("list.m3u");
File.WriteAllText(playlist, "c.flac\n");
using var screen = new OdMediaViewModel(session, new OdMediaSettings { Volume = 30 }, settings => saved = settings);
using var screen = new OdMediaViewModel(session, new OdMediaSettings { Volume = 30 }, settings => saved = settings, TimeProvider.System);
Assert.Equal("Nothing to play yet", screen.Title);
screen.Add([folder, playlist, _temp.Combine("notes.txt")]);
@@ -291,19 +423,40 @@ public sealed class OdMediaTests : IDisposable
public bool HasVideo { get; set; }
public IReadOnlyList<OdMediaTrack> AudioTracks { get; set; } = [];
public IReadOnlyList<OdMediaTrack> SubtitleTracks { get; set; } = [];
public int AudioTrack { get; set; }
public int SubtitleTrack { get; set; } = -1;
public float Rate { get; set; } = 1f;
public IReadOnlyList<OdMediaDevice> AudioDevices { get; set; } = [];
public string? AudioDevice { get; set; }
public OdMediaOpening? LastOpening { get; private set; }
public int Volume { get; set; }
public bool Muted { get; set; }
public bool Disposed { get; private set; }
public void Open(string path, TimeSpan from, bool play)
public void Open(string path, OdMediaOpening opening)
{
Calls.Add(string.Create(CultureInfo.InvariantCulture, $"open {Path.GetFileName(path)} {from.TotalSeconds} {play}"));
Time = from;
Raise(play ? OdMediaState.Playing : OdMediaState.Paused);
LastOpening = opening;
Calls.Add(string.Create(CultureInfo.InvariantCulture, $"open {Path.GetFileName(path)} {opening.From.TotalSeconds} {opening.Play}"));
Time = opening.From;
Raise(opening.Play ? OdMediaState.Playing : OdMediaState.Paused);
}
public bool AddSubtitle(string path) => !path.EndsWith("film.srt", StringComparison.Ordinal);
public bool TakeSnapshot(string path) => HasVideo;
public void Play()
{
Calls.Add("play");
@@ -0,0 +1,30 @@
using System.Windows.Controls;
using OmniDeck.Core.Modules;
using OmniDeck.Tests.TestSupport;
namespace OmniDeck.Tests.Modules;
public sealed class OdFullscreenTests
{
[Fact]
public void AViewsRequest_BubblesUpToItsWindow_AndTheAnswerFlowsDownToIt() => OdSta.Run(() =>
{
var view = new Border();
var stage = new ContentControl { Content = view };
var window = new Grid { Children = { stage } };
var requests = new List<bool>();
window.AddHandler(OdFullscreen.RequestedEvent, new EventHandler<OdFullscreenRequestedEventArgs>((_, e) => requests.Add(e.On)));
OdFullscreen.Request(view, on: true);
OdFullscreen.SetIsActive(stage, true);
Assert.Equal(new[] { true }, requests);
Assert.True(OdFullscreen.GetIsActive(view));
OdFullscreen.Request(view, on: false);
OdFullscreen.SetIsActive(stage, false);
Assert.Equal(new[] { true, false }, requests);
Assert.False(OdFullscreen.GetIsActive(view));
return Task.CompletedTask;
});
}
@@ -218,6 +218,72 @@ public sealed class OdModuleHostTests : IDisposable
Assert.Same(database, _clock.Context.Database);
});
[Fact]
public void PopOut_KeepsTheModuleActive_BesideTheMainWindowsModule() => OdSta.Run(async () =>
{
using var host = NewHost();
await host.ShowAsync("clock");
var view = await host.PopOutAsync("timer");
var timer = host.Find("timer")!;
Assert.Same(timer.View, view);
Assert.True(timer.IsPoppedOut);
Assert.Equal(OdModuleState.Active, timer.State);
Assert.Same(host.Find("clock"), host.Current);
Assert.Equal(new[] { "init", "view", "activate" }, _timer.Calls, StringComparer.Ordinal);
Assert.False(await host.SuspendAsync("timer", OdSuspendReason.MemoryPressure));
await Assert.ThrowsAsync<InvalidOperationException>(() => host.ShowAsync("timer"));
});
[Fact]
public void PopOut_OfTheMainWindowsModule_LeavesTheMainWindowEmpty() => OdSta.Run(async () =>
{
using var host = NewHost();
var shown = await host.ShowAsync("clock");
var view = await host.PopOutAsync("clock");
Assert.Same(shown, view);
Assert.Null(host.Current);
Assert.Equal(OdModuleState.Active, host.Find("clock")?.State);
Assert.Equal(new[] { "init", "view", "activate" }, _clock.Calls, StringComparer.Ordinal);
});
[Fact]
public void Dock_HidesTheModule_AndTheLadderAppliesAgain() => OdSta.Run(async () =>
{
using var host = NewHost();
var view = await host.PopOutAsync("clock");
_time.Advance(TimeSpan.FromMinutes(5));
await host.DockAsync("clock");
await host.DockAsync("clock");
var clock = host.Find("clock")!;
Assert.False(clock.IsPoppedOut);
Assert.Equal(OdModuleState.Idle, clock.State);
Assert.Equal(Start.AddMinutes(5), clock.LastActive);
Assert.True(await host.SuspendAsync("clock", OdSuspendReason.Hidden));
Assert.Same(view, await host.ShowAsync("clock"));
});
[Fact]
public void Close_EndsAPopOut() => OdSta.Run(async () =>
{
using var host = NewHost();
await host.PopOutAsync("clock");
_time.Advance(TimeSpan.FromMinutes(2));
await host.CloseAsync("clock");
var clock = host.Find("clock")!;
Assert.False(clock.IsPoppedOut);
Assert.Null(clock.View);
Assert.Equal(OdModuleState.Closed, clock.State);
Assert.Equal(Start.AddMinutes(2), clock.LastActive);
});
private OdModuleHost NewHost(params IOdModule[] more) => new(
[_clock, _timer, .. more],
new OdDatabase(_temp.Combine("omnideck.db"), pooling: false),
@@ -0,0 +1,23 @@
using System.Windows;
using System.Windows.Interop;
using OmniDeck.Core.Runtime;
using OmniDeck.Tests.TestSupport;
namespace OmniDeck.Tests.Runtime;
public sealed class OdMonitorsTests
{
[Fact]
public void BoundsOf_AWindow_IsTheMonitorItIsOn() => OdSta.Run(() =>
{
// A window that is never shown is still near a monitor.
var window = new Window();
var bounds = OdMonitors.BoundsOf(new WindowInteropHelper(window).EnsureHandle());
Assert.False(bounds.IsEmpty);
Assert.True(bounds.Width > 0);
Assert.True(bounds.Height > 0);
window.Close();
return Task.CompletedTask;
});
}
@@ -181,6 +181,97 @@ public sealed class OdShellViewModelTests : IDisposable
Assert.Equal(OdModuleState.Active, shell.Library[2].State);
});
[Fact]
public void PopOut_OfTheModuleOnScreen_LeavesTheLibraryInTheMainWindow() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
var opened = new List<OdPopOutEventArgs>();
shell.PopOutOpened += (_, e) => opened.Add(e);
await shell.NavigateAsync("clock");
await shell.PopOutCommand.ExecuteAsync(shell.Library[0]);
var popOut = Assert.Single(opened);
Assert.Same(shell.Library[0], popOut.Item);
Assert.Same(host.Find("clock")?.View, popOut.View);
Assert.True(shell.Library[0].IsPoppedOut);
Assert.Equal(OdModuleState.Active, shell.Library[0].State);
Assert.Equal(OdShellViewModel.LibraryTarget, shell.CurrentTarget);
Assert.Null(shell.CurrentView);
Assert.Contains(shell.Library[0], shell.Sidebar);
});
[Fact]
public void APoppedOutModule_IsBroughtUpInItsWindow() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
var raised = new List<string>();
shell.PopOutActivationRequested += (_, e) => raised.Add(e.Item.Id);
await shell.NavigateAsync("timer");
await shell.PopOutCommand.ExecuteAsync(shell.Library[0]);
await shell.NavigateAsync("clock");
await shell.PopOutCommand.ExecuteAsync(shell.Library[0]);
Assert.Equal(new[] { "clock", "clock" }, raised, StringComparer.Ordinal);
Assert.Equal("timer", shell.CurrentTarget);
Assert.Same(host.Find("timer"), host.Current);
});
[Fact]
public void PopIn_ClosesTheWindow_AndShowsTheModuleInTheMainWindow() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
var closed = new List<string>();
shell.PopOutCloseRequested += (_, e) => closed.Add(e.Item.Id);
await shell.PopOutCommand.ExecuteAsync(shell.Library[0]);
await shell.PopInCommand.ExecuteAsync(shell.Library[1]);
await shell.PopInCommand.ExecuteAsync(shell.Library[0]);
Assert.Equal(new[] { "clock" }, closed, StringComparer.Ordinal);
Assert.False(shell.Library[0].IsPoppedOut);
Assert.Equal("clock", shell.CurrentTarget);
Assert.Same(host.Find("clock")?.View, shell.CurrentView);
Assert.Same(host.Find("clock"), host.Current);
});
[Fact]
public void ClosingItsWindow_DocksTheModuleHidden() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
await shell.NavigateAsync("timer");
await shell.PopOutCommand.ExecuteAsync(shell.Library[0]);
await shell.DockAsync(shell.Library[0]);
Assert.False(shell.Library[0].IsPoppedOut);
Assert.Equal(OdModuleState.Idle, shell.Library[0].State);
Assert.Equal("timer", shell.CurrentTarget);
Assert.Contains(shell.Library[0], shell.Sidebar);
});
[Fact]
public void ClosingAPoppedOutModule_ClosesItsWindow() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
var closed = new List<string>();
shell.PopOutCloseRequested += (_, e) => closed.Add(e.Item.Id);
await shell.PopOutCommand.ExecuteAsync(shell.Library[0]);
await shell.CloseCommand.ExecuteAsync(shell.Library[0]);
Assert.Equal(new[] { "clock" }, closed, StringComparer.Ordinal);
Assert.False(shell.Library[0].IsPoppedOut);
Assert.DoesNotContain(shell.Library[0], shell.Sidebar);
Assert.Equal(OdShellViewModel.LibraryTarget, shell.CurrentTarget);
});
[Fact]
public void PaletteEntries_OpenModules_ShowTheLibrary_AndQuit() => OdSta.Run(async () =>
{
@@ -0,0 +1,81 @@
using System.Windows;
using OmniDeck.App.Shell;
using OmniDeck.Tests.TestSupport;
using Wpf.Ui.Controls;
namespace OmniDeck.Tests.Shell;
public sealed class OdWindowCoverTests
{
// A monitor left of the primary one: its origin is negative.
private static readonly Int32Rect LeftMonitor = new(-1920, 0, 1920, 1080);
[Fact]
public void Cover_FillsTheMonitorOnTopWithSquareCorners() => OdSta.Run(() =>
{
var window = NewWindow();
var cover = new OdWindowCover(window);
Assert.True(cover.Cover(LeftMonitor));
Assert.True(cover.IsCovering);
Assert.Equal((-1920d, 0d, 1920d, 1080d), (window.Left, window.Top, window.Width, window.Height));
Assert.Equal(WindowState.Normal, window.WindowState);
Assert.True(window.Topmost);
Assert.Equal(ResizeMode.NoResize, window.ResizeMode);
Assert.Equal(WindowCornerPreference.DoNotRound, window.WindowCornerPreference);
window.Close();
return Task.CompletedTask;
});
[Fact]
public void Uncover_PutsTheWindowBackAsItWas() => OdSta.Run(() =>
{
var window = NewWindow();
window.WindowState = WindowState.Maximized;
var cover = new OdWindowCover(window);
cover.Cover(LeftMonitor);
Assert.True(cover.Uncover());
Assert.False(cover.IsCovering);
Assert.Equal((100d, 50d, 800d, 600d), (window.Left, window.Top, window.Width, window.Height));
Assert.Equal(WindowState.Maximized, window.WindowState);
Assert.False(window.Topmost);
Assert.Equal(ResizeMode.CanResize, window.ResizeMode);
Assert.Equal(WindowCornerPreference.Round, window.WindowCornerPreference);
Assert.False(cover.Uncover());
window.Close();
return Task.CompletedTask;
});
[Fact]
public void Cover_RefusesAnEmptyMonitor_AndKeepsTheFirstPlacement() => OdSta.Run(() =>
{
var window = NewWindow();
var cover = new OdWindowCover(window);
Assert.False(cover.Cover(Int32Rect.Empty));
Assert.False(cover.IsCovering);
Assert.Equal(100d, window.Left);
cover.Cover(LeftMonitor);
Assert.False(cover.Cover(new Int32Rect(0, 0, 2560, 1440)));
Assert.Equal(-1920d, window.Left);
cover.Uncover();
Assert.Equal((100d, 50d, 800d, 600d), (window.Left, window.Top, window.Width, window.Height));
window.Close();
return Task.CompletedTask;
});
private static FluentWindow NewWindow() => new()
{
Left = 100,
Top = 50,
Width = 800,
Height = 600,
ResizeMode = ResizeMode.CanResize,
WindowCornerPreference = WindowCornerPreference.Round,
};
}
@@ -34,6 +34,51 @@ public sealed class OdDataRootTests
Assert.Throws<ArgumentException>(() => new OdDataRoot(temp.Combine(name)));
}
[Theory]
[InlineData(null)]
[InlineData("")]
[InlineData(" ")]
public void Choose_WithoutAnOverride_IsTheRealRoot(string? overridePath)
{
var root = OdDataRoot.Choose(overridePath);
Assert.Same(OdDataRoot.Default, root);
Assert.True(root.IsDefault);
Assert.Null(root.InstanceSuffix);
}
[Fact]
public void Choose_WithAnOverride_UsesIt_AndGetsAnInstanceOfItsOwn()
{
using var temp = new OdTempDirectory();
var path = temp.Combine("OmniDeck.Dev");
var root = OdDataRoot.Choose(path);
Assert.Equal(path, root.Root, StringComparer.OrdinalIgnoreCase);
Assert.False(root.IsDefault);
Assert.Matches("^\\.[0-9A-F]{8}$", root.InstanceSuffix);
Assert.Equal(root.InstanceSuffix, OdDataRoot.Choose(path.ToUpperInvariant() + Path.DirectorySeparatorChar).InstanceSuffix, StringComparer.Ordinal);
Assert.NotEqual(root.InstanceSuffix, OdDataRoot.Choose(temp.Combine("OmniDeck.Other")).InstanceSuffix, StringComparer.Ordinal);
}
[Fact]
public void Choose_StillRejectsVelopacksInstallFolder()
{
using var temp = new OdTempDirectory();
Assert.Throws<ArgumentException>(() => OdDataRoot.Choose(temp.Combine("OmniDeck")));
}
[Fact]
public void Choose_TheRealPathItself_CountsAsTheRealRoot()
{
var root = OdDataRoot.Choose(OdDataRoot.Default.Root + Path.DirectorySeparatorChar);
Assert.True(root.IsDefault);
Assert.Null(root.InstanceSuffix);
}
[Fact]
public void EnsureCreated_ThenTryDelete_LeavesNothing()
{
+10 -6
View File
@@ -1,3 +1,4 @@
using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Text.Json;
@@ -97,20 +98,23 @@ public sealed class OdCatalogTests : IDisposable
var bundled = _temp.Combine("bundled.json");
var saved = Path.Combine(_temp.Path, "saved", "webapps.json");
File.WriteAllText(bundled, RepositoryCatalog);
var shipped = OdCatalogJson.Parse(RepositoryCatalog).Updated;
var today = DateOnly.ParseExact(shipped, "yyyy-MM-dd", CultureInfo.InvariantCulture);
var later = today.AddDays(1).ToString("yyyy-MM-dd", CultureInfo.InvariantCulture);
Assert.Equal("2026-11-02", OdCatalogService.Load(bundled, saved, Today, Logger.None).Updated);
Assert.Equal(shipped, OdCatalogService.Load(bundled, saved, today, Logger.None).Updated);
Directory.CreateDirectory(Path.GetDirectoryName(saved)!);
File.WriteAllText(saved, Changed(root => root["updated"] = "2026-11-03"));
Assert.Equal("2026-11-03", OdCatalogService.Load(bundled, saved, Today, Logger.None).Updated);
File.WriteAllText(saved, Changed(root => root["updated"] = later));
Assert.Equal(later, OdCatalogService.Load(bundled, saved, today, Logger.None).Updated);
File.WriteAllText(saved, Changed(root => root["updated"] = "2026-10-01"));
Assert.Equal("2026-11-02", OdCatalogService.Load(bundled, saved, Today, Logger.None).Updated);
Assert.Equal(shipped, OdCatalogService.Load(bundled, saved, today, Logger.None).Updated);
File.WriteAllText(saved, "{ broken");
Assert.Equal("2026-11-02", OdCatalogService.Load(bundled, saved, Today, Logger.None).Updated);
Assert.Equal(shipped, OdCatalogService.Load(bundled, saved, today, Logger.None).Updated);
Assert.Empty(OdCatalogService.Load(_temp.Combine("missing.json"), _temp.Combine("missing-too.json"), Today, Logger.None).Apps);
Assert.Empty(OdCatalogService.Load(_temp.Combine("missing.json"), _temp.Combine("missing-too.json"), today, Logger.None).Apps);
}
[Fact]
+5 -1
View File
@@ -42,7 +42,11 @@ public sealed class OdWebRunnerTests : IDisposable
[InlineData("youtube", "https://www.youtube.com/watch?v=1", OdNavDecision.Allow)]
[InlineData("youtube", "https://accounts.google.com.vn/accounts/SetSID", OdNavDecision.Allow)]
[InlineData("gmail", "https://accounts.google.co.jp/accounts/SetSID", OdNavDecision.Allow)]
[InlineData("spotify", "https://accounts.google.com.vn/accounts/SetSID", OdNavDecision.OpenExternally)]
[InlineData("spotify", "https://accounts.google.com.vn/accounts/SetSID", OdNavDecision.Allow)]
[InlineData("spotify", "https://accounts.google.com/v3/signin/identifier", OdNavDecision.Allow)]
[InlineData("spotify", "https://www.facebook.com/login.php", OdNavDecision.Allow)]
[InlineData("spotify", "https://appleid.apple.com/auth/authorize", OdNavDecision.Allow)]
[InlineData("spotify", "https://mail.google.com/", OdNavDecision.OpenExternally)]
[InlineData("gmail", "https://evilgoogle.com/", OdNavDecision.OpenExternally)]
[InlineData("gmail", "http://mail.google.com/", OdNavDecision.OpenExternally)]
[InlineData("gmail", "mailto:someone@example.com", OdNavDecision.OpenExternally)]