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
poli0981 763cc93de0 Merge remote-tracking branch 'origin/main' into ci/sonar-native-wrappers 2026-11-02 11:13:29 +07:00
poli0981 be89c978a6 Merge pull request #44 from poli0981/feat/p2-media
feat: add the media player, first part
2026-11-02 11:13:10 +07:00
poli0981andClaude Opus 5.5 16d6e64b0c ci: leave the native-engine wrappers out of Sonar coverage
OdWebRuntime wraps the WebView2 runtime and OdVlcEngine/OdVlcPlayer wrap
libVLC; like the views, they only run against engines CI does not load,
which kept PRs #38 and #39 just under the 80 % new-code coverage gate
(77.3 % and 76.6 %, no issues). The logic around them stays covered, and
the memory reporter's path before any web app opens gets a test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:11:53 +07:00
poli0981andClaude Opus 5.5 6b898994a3 feat: add the media player, first part
- OdMediaModule (Heavy): local audio and video through LibVLCSharp 3.10.2
  and libVLC 3.0.24. libVLC starts with the first file played.
- Files, folders and .m3u playlists from the buttons or dropped on the
  player; the queue can be saved as .m3u. The queue and where playback
  stood live in media_playlists (migration 0005) and survive restarts.
- Pinned while playing; suspending lets the player go and keeps the
  position, hibernating lets libVLC go too (spike #6: 280-520 MB).
- libVLC events are posted to the UI thread; only its errors reach the
  log, as warnings, less the three known harmless messages.
- The overlay covers libVLC's blank video window until a picture plays.
- Packaging: x64 only, the SPEC plugin folders without the network access
  plugins (about 80 MB raw) in libvlc\win-x64.
- Third-party notices: LibVLCSharp and libVLC move to bundled, with the
  LGPL-2.1 and GPL-2.0 texts (pre-approved P2 entries).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:08:27 +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
poli0981 df161596f8 Merge pull request #42 from poli0981/feat/p2-bug-report
feat: report a bug from About or the error dialog
2026-11-02 10:47:38 +07:00
poli0981 7e6d0f474a Merge pull request #41 from poli0981/release/0.2.0-alpha.1
release: 0.2.0-alpha.1
2026-11-02 10:39:00 +07:00
81 changed files with 4743 additions and 90 deletions

No files matched your search

+3 -1
View File
@@ -102,7 +102,9 @@ jobs:
'/d:sonar.cs.vstest.reportsPaths=TestResults/*.trx',
'/d:sonar.cs.roslyn.ignoreIssues=true',
'/d:sonar.exclusions=**/bin/**,**/obj/**,**/TestResults/**,publish/**,Releases/**',
'/d:sonar.coverage.exclusions=**/*.xaml.cs,**/Program.cs,scripts/**,.github/**'
# Views, and the thin wrappers over the native engines (the WebView2 runtime, libVLC), run only
# against those engines, which CI does not load; the logic around them is tested on its own.
'/d:sonar.coverage.exclusions=**/*.xaml.cs,**/Program.cs,**/OdWebRuntime.cs,**/OdVlcEngine.cs,**/OdVlcPlayer.cs,scripts/**,.github/**'
)
dotnet sonarscanner @scannerArgs
if ($LASTEXITCODE -ne 0) { throw "SonarScanner begin failed with exit code $LASTEXITCODE." }
+44 -1
View File
@@ -6,7 +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. 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
@@ -194,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
}
]
}
+23 -5
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`.
@@ -143,6 +161,6 @@ A content dialog cannot cover a web app's browser, which is a native window. So
## 7. Updates & packaging
Velopack, per-user, GitHub Releases channel, delta updates; update check on About open and once per day in the background (notify-only, never auto-restart). Builds below 1.0 are GitHub pre-releases, so their update check includes pre-releases. In code: `OdVelopackUpdateService` behind `IOdUpdateService`; Settings → About checks when opened and offers *Download and restart*, and `OdUpdateWatcher` checks a few minutes after start, then daily, and notifies once per new version. A development build is not installed, so it does neither.
Velopack, per-user, GitHub Releases channel, delta updates. 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.
+29 -12
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,17 +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:**
- The player opens local files, folders and .m3u playlists, from its buttons or dropped on it, and saves the queue as an .m3u.
- The queue and where playback stood live in the database (`media_playlists`), so they survive restarts.
- It has transport controls, a seek bar, volume and mute.
- libVLC ships in `libvlc\win-x64` next to OmniDeck.exe, with these plugin folders: access, audio_filter, audio_mixer, audio_output, codec, demux, misc, packetizer, spu, stream_filter, text_renderer, video_chroma, video_filter and video_output. The network access plugins (http, https, ftp, sftp, smb, rtp, srt) are left out, which comes to about 80 MB raw.
- Only libVLC's errors reach the app log, as warnings, less the three known harmless ones.
- The overlay's More menu has:
- the audio track and the subtitle track;
- a subtitle file (libVLC also picks one up from beside the video, with the same name);
- the subtitles' encoding, from Automatic, UTF-8 and the common code pages. libVLC reads it only when a file opens, so a new choice reopens the file where it stood;
- the speed, from 0.25× to 4×, kept for the files that follow;
- the audio device (Windows' default, or one libVLC lists);
- a snapshot of the picture, saved in Pictures\OmniDeck.
- Speed, encoding and device live in the module's settings document.
- Full screen: the button in the overlay, or a double-click on the picture, makes the main window cover its monitor (chrome hidden, square corners, topmost). Esc, or showing another module, puts it back. The player never moves, so its video window stays the same. The overlay is not fully transparent over a picture (alpha 1), because a click on a fully clear pixel of a layered window falls through to libVLC's window.
- While a player has a file loaded, the tray menu shows the file with Play or Pause, Next and Previous (`IOdMediaControls`). Without a player there is nothing to control: starting one while the view is away could make libVLC open a video window of its own.
## 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).
@@ -90,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.
+822 -4
View File
@@ -25,17 +25,17 @@ OmniDeck is licensed under GPL-3.0. This file lists the third-party components O
| Ical.Net | 5.2.3 | MIT | calendar repeats and .ics import/export |
| NodaTime (with the IANA time zone database, public domain) | 3.2.2 | Apache-2.0 | time zones for Ical.Net |
| Microsoft.Web.WebView2 (Core, WPF and WinForms bindings, WebView2Loader) | 1.0.4314.35 | BSD-3-Clause | web app engine bindings; the WebView2 Runtime itself is not bundled (§3) |
| LibVLCSharp + LibVLCSharp.WPF | 3.10.2 | LGPL-2.1-or-later | media player bindings |
| libVLC (`VideoLAN.LibVLC.Windows`: libvlc, libvlccore and the plugins in `libvlc\win-x64`) | 3.0.24 | LGPL-2.1-or-later core and most plugins; some plugins GPL-2.0-or-later | media engine |
libVLC note: OmniDeck redistributes the libVLC 3.0.24 binaries unmodified, as separate files in `libvlc\win-x64` that can be replaced, with the plugin folders listed in docs/SPEC.md §3.6. Source for that exact version is available from VideoLAN (https://download.videolan.org/pub/videolan/vlc/3.0.24/) and LibVLCSharp's from https://code.videolan.org/videolan/LibVLCSharp. The combination is distributed under GPL-3.0 terms, compatible with the LGPL-2.1+ and GPL-2.0+ components.
## 2. Planned components (bundled from the version that introduces them)
| Component | License | Role | Phase |
|---|---|---|---|
| LibVLCSharp.WPF | LGPL-2.1-or-later | media bindings | P2 |
| libVLC (`VideoLAN.LibVLC.Windows`) | LGPL-2.1-or-later core; some plugins GPL-2.0-or-later | media engine | P2 |
| ScottPlot.WPF (+ SkiaSharp, OpenTK) | MIT | stock charts | P3 |
libVLC note: once the media player ships, OmniDeck redistributes libVLC binaries unmodified. Source for the exact libVLC version shipped is available from VideoLAN; the combination is distributed under GPL-3.0 terms, compatible with the LGPL-2.1+ and GPL-2.0+ components.
## 3. Not bundled
- **Microsoft Edge WebView2 Runtime** — ships with Windows 11 and is updated by Microsoft under Microsoft's license terms; OmniDeck does not redistribute it.
@@ -338,6 +338,824 @@ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
```
### GNU Lesser General Public License, version 2.1
Applies to LibVLCSharp and LibVLCSharp.WPF (Copyright (C) VideoLAN and the LibVLCSharp authors), and to libVLC and its LGPL plugins (Copyright (C) the VLC authors and VideoLAN). Each is offered under version 2.1 of this license or, at your option, any later version.
```
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts as
the successor of the GNU Library Public License, version 2, hence the
version number 2.1.]
Preamble
The licenses for most software are designed to take away your freedom to
share and change it. By contrast, the GNU General Public Licenses are
intended to guarantee your freedom to share and change free software--to
make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some specially
designated software packages--typically libraries--of the Free Software
Foundation and other authors who decide to use it. You can use it too, but
we suggest you first think carefully about whether this license or the
ordinary General Public License is the better strategy to use in any
particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use, not
price. Our General Public Licenses are designed to make sure that you have
the freedom to distribute copies of free software (and charge for this
service if you wish); that you receive source code or can get it if you want
it; that you can change the software and use pieces of it in new free
programs; and that you are informed that you can do these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for you if
you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis or for
a fee, you must give the recipients all the rights that we gave you. You
must make sure that they, too, receive or can get the source code. If you
link other code with the library, you must provide complete object files to
the recipients, so that they can relink them with the library after making
changes to the library and recompiling it. And you must show them these
terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the library,
and (2) we offer you this license, which gives you legal permission to copy,
distribute and/or modify the library.
To protect each distributor, we want to make it very clear that there is no
warranty for the free library. Also, if the library is modified by someone
else and passed on, the recipients should know that what they have is not
the original version, so that the original author's reputation will not be
affected by problems that might be introduced by others.
Finally, software patents pose a constant threat to the existence of any
free program. We wish to make sure that a company cannot effectively
restrict the users of a free program by obtaining a restrictive license from
a patent holder. Therefore, we insist that any patent license obtained for a
version of the library must be consistent with the full freedom of use
specified in this license.
Most GNU software, including some libraries, is covered by the ordinary GNU
General Public License. This license, the GNU Lesser General Public License,
applies to certain designated libraries, and is quite different from the
ordinary General Public License. We use this license for certain libraries
in order to permit linking those libraries into non-free programs.
When a program is linked with a library, whether statically or using a
shared library, the combination of the two is legally speaking a combined
work, a derivative of the original library. The ordinary General Public
License therefore permits such linking only if the entire combination fits
its criteria of freedom. The Lesser General Public License permits more lax
criteria for linking other code with the library.
We call this license the "Lesser" General Public License because it does
Less to protect the user's freedom than the ordinary General Public License.
It also provides other free software developers Less of an advantage over
competing non-free programs. These disadvantages are the reason we use the
ordinary General Public License for many libraries. However, the Lesser
license provides advantages in certain special circumstances.
For example, on rare occasions, there may be a special need to encourage the
widest possible use of a certain library, so that it becomes a de-facto
standard. To achieve this, non-free programs must be allowed to use the
library. A more frequent case is that a free library does the same job as
widely used non-free libraries. In this case, there is little to gain by
limiting the free library to free software only, so we use the Lesser
General Public License.
In other cases, permission to use a particular library in non-free programs
enables a greater number of people to use a large body of free software. For
example, permission to use the GNU C Library in non-free programs enables
many more people to use the whole GNU operating system, as well as its
variant, the GNU/Linux operating system.
Although the Lesser General Public License is Less protective of the users'
freedom, it does ensure that the user of a program that is linked with the
Library has the freedom and the wherewithal to run that program using a
modified version of the Library.
The precise terms and conditions for copying, distribution and modification
follow. Pay close attention to the difference between a "work based on the
library" and a "work that uses the library". The former contains code
derived from the library, whereas the latter must be combined with the
library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other program
which contains a notice placed by the copyright holder or other authorized
party saying it may be distributed under the terms of this Lesser General
Public License (also called "this License"). Each licensee is addressed as
"you".
A "library" means a collection of software functions and/or data prepared so
as to be conveniently linked with application programs (which use some of
those functions and data) to form executables.
The "Library", below, refers to any such software library or work which has
been distributed under these terms. A "work based on the Library" means
either the Library or any derivative work under copyright law: that is to
say, a work containing the Library or a portion of it, either verbatim or
with modifications and/or translated straightforwardly into another
language. (Hereinafter, translation is included without limitation in the
term "modification".)
"Source code" for a work means the preferred form of the work for making
modifications to it. For a library, complete source code means all the
source code for all modules it contains, plus any associated interface
definition files, plus the scripts used to control compilation and
installation of the library.
Activities other than copying, distribution and modification are not covered
by this License; they are outside its scope. The act of running a program
using the Library is not restricted, and output from such a program is
covered only if its contents constitute a work based on the Library
(independent of the use of the Library in a tool for writing it). Whether
that is true depends on what the Library does and what the program that uses
the Library does.
1. You may copy and distribute verbatim copies of the Library's complete
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the notices
that refer to this License and to the absence of any warranty; and
distribute a copy of this License along with the Library.
You may charge a fee for the physical act of transferring a copy, and you
may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Library or any portion of it,
thus forming a work based on the Library, and copy and distribute such
modifications or work under the terms of Section 1 above, provided that you
also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices stating
that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no charge to
all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses the
facility, other than as an argument passed when the facility is
invoked, then you must make a good faith effort to ensure that, in the
event an application does not supply such function or table, the
facility still operates, and performs whatever part of its purpose
remains meaningful.
(For example, a function in a library to compute square roots has a purpose
that is entirely well-defined independent of the application. Therefore,
Subsection 2d requires that any application-supplied function or table used
by this function must be optional: if the application does not supply it,
the square root function must still compute square roots.)
These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Library, and can be
reasonably considered independent and separate works in themselves, then
this License, and its terms, do not apply to those sections when you
distribute them as separate works. But when you distribute the same sections
as part of a whole which is a work based on the Library, the distribution of
the whole must be on the terms of this License, whose permissions for other
licensees extend to the entire whole, and thus to each and every part
regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your
rights to work written entirely by you; rather, the intent is to exercise
the right to control the distribution of derivative or collective works
based on the Library.
In addition, mere aggregation of another work not based on the Library with
the Library (or with a work based on the Library) on a volume of a storage
or distribution medium does not bring the other work under the scope of this
License.
3. You may opt to apply the terms of the ordinary GNU General Public License
instead of this License to a given copy of the Library. To do this, you must
alter all the notices that refer to this License, so that they refer to the
ordinary GNU General Public License, version 2, instead of to this License.
(If a newer version than version 2 of the ordinary GNU General Public
License has appeared, then you can specify that version instead if you
wish.) Do not make any other change in these notices.
Once this change is made in a given copy, it is irreversible for that copy,
so the ordinary GNU General Public License applies to all subsequent copies
and derivative works made from that copy.
This option is useful when you wish to copy part of the code of the Library
into a program that is not a library.
4. You may copy and distribute the Library (or a portion or derivative of
it, under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you accompany it with the complete
corresponding machine-readable source code, which must be distributed under
the terms of Sections 1 and 2 above on a medium customarily used for
software interchange.
If distribution of object code is made by offering access to copy from a
designated place, then offering equivalent access to copy the source code
from the same place satisfies the requirement to distribute the source code,
even though third parties are not compelled to copy the source along with
the object code.
5. A program that contains no derivative of any portion of the Library, but
is designed to work with the Library by being compiled or linked with it, is
called a "work that uses the Library". Such a work, in isolation, is not a
derivative work of the Library, and therefore falls outside the scope of
this License.
However, linking a "work that uses the Library" with the Library creates an
executable that is a derivative of the Library (because it contains portions
of the Library), rather than a "work that uses the library". The executable
is therefore covered by this License. Section 6 states terms for
distribution of such executables.
When a "work that uses the Library" uses material from a header file that is
part of the Library, the object code for the work may be a derivative work
of the Library even though the source code is not. Whether this is true is
especially significant if the work can be linked without the Library, or if
the work is itself a library. The threshold for this to be true is not
precisely defined by law.
If such an object file uses only numerical parameters, data structure
layouts and accessors, and small macros and small inline functions (ten
lines or less in length), then the use of the object file is unrestricted,
regardless of whether it is legally a derivative work. (Executables
containing this object code plus portions of the Library will still fall
under Section 6.)
Otherwise, if the work is a derivative of the Library, you may distribute
the object code for the work under the terms of Section 6. Any executables
containing that work also fall under Section 6, whether or not they are
linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or link a
"work that uses the Library" with the Library to produce a work containing
portions of the Library, and distribute that work under terms of your
choice, provided that the terms permit modification of the work for the
customer's own use and reverse engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the Library
is used in it and that the Library and its use are covered by this License.
You must supply a copy of this License. If the work during execution
displays copyright notices, you must include the copyright notice for the
Library among them, as well as a reference directing the user to the copy of
this License. Also, you must do one of these things:
a) Accompany the work with the complete corresponding machine-readable
source code for the Library including whatever changes were used in the
work (which must be distributed under Sections 1 and 2 above); and, if
the work is an executable linked with the Library, with the complete
machine-readable "work that uses the Library", as object code and/or
source code, so that the user can modify the Library and then relink to
produce a modified executable containing the modified Library. (It is
understood that the user who changes the contents of definitions files
in the Library will not necessarily be able to recompile the
application to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a copy
of the library already present on the user's computer system, rather
than copying library functions into the executable, and (2) will
operate properly with a modified version of the library, if the user
installs one, as long as the modified version is interface-compatible
with the version that the work was made with.
c) Accompany the work with a written offer, valid for at least three
years, to give the same user the materials specified in Subsection 6a,
above, for a charge no more than the cost of performing this
distribution.
d) If distribution of the work is made by offering access to copy from
a designated place, offer equivalent access to copy the above specified
materials from the same place.
e) Verify that the user has already received a copy of these materials
or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the Library"
must include any data and utility programs needed for reproducing the
executable from it. However, as a special exception, the materials to be
distributed need not include anything that is normally distributed (in
either source or binary form) with the major components (compiler, kernel,
and so on) of the operating system on which the executable runs, unless that
component itself accompanies the executable.
It may happen that this requirement contradicts the license restrictions of
other proprietary libraries that do not normally accompany the operating
system. Such a contradiction means you cannot use both them and the Library
together in an executable that you distribute.
7. You may place library facilities that are a work based on the Library
side-by-side in a single library together with other library facilities not
covered by this License, and distribute such a combined library, provided
that the separate distribution of the work based on the Library and of the
other library facilities is otherwise permitted, and provided that you do
these two things:
a) Accompany the combined library with a copy of the same work based on
the Library, uncombined with any other library facilities. This must be
distributed under the terms of the Sections above.
b) Give prominent notice with the combined library of the fact that
part of it is a work based on the Library, and explaining where to find
the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute the
Library except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense, link with, or distribute the Library
is void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such parties
remain in full compliance.
9. You are not required to accept this License, since you have not signed
it. However, nothing else grants you permission to modify or distribute the
Library or its derivative works. These actions are prohibited by law if you
do not accept this License. Therefore, by modifying or distributing the
Library (or any work based on the Library), you indicate your acceptance of
this License to do so, and all its terms and conditions for copying,
distributing or modifying the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the original
licensor to copy, distribute, link with or modify the Library subject to
these terms and conditions. You may not impose any further restrictions on
the recipients' exercise of the rights granted herein. You are not
responsible for enforcing compliance by third parties with this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot distribute so
as to satisfy simultaneously your obligations under this License and any
other pertinent obligations, then as a consequence you may not distribute
the Library at all. For example, if a patent license would not permit
royalty-free redistribution of the Library by all those who receive copies
directly or indirectly through you, then the only way you could satisfy both
it and this License would be to refrain entirely from distribution of the
Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents
or other property right claims or to contest validity of any such claims;
this section has the sole purpose of protecting the integrity of the free
software distribution system which is implemented by public license
practices. Many people have made generous contributions to the wide range of
software distributed through that system in reliance on consistent
application of that system; it is up to the author/donor to decide if he or
she is willing to distribute software through any other system and a
licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a
consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in certain
countries either by patents or by copyrighted interfaces, the original
copyright holder who places the Library under this License may add an
explicit geographical distribution limitation excluding those countries, so
that distribution is permitted only in or among countries not thus excluded.
In such case, this License incorporates the limitation as if written in the
body of this License.
13. The Free Software Foundation may publish revised and/or new versions of
the Lesser General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Library does not specify a license version
number, you may choose any version ever published by the Free Software
Foundation.
14. If you wish to incorporate parts of the Library into other free programs
whose distribution conditions are incompatible with these, write to the
author to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals of
preserving the free status of all derivatives of our free software and of
promoting the sharing and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR
THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY
PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO
LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER
SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest possible
use to the public, we recommend making it free software that everyone can
redistribute and change. You can do so by permitting redistribution under
these terms (or, alternatively, under the terms of the ordinary General
Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
one line to give the library's name and an idea of what it does.
Copyright (C) year name of author
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
This library is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA Also add information on how to contact you by
electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in
the library `Frob' (a library for tweaking knobs) written
by James Random Hacker.
signature of Ty Coon, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
```
### GNU General Public License, version 2
Applies to the libVLC plugins licensed GPL-2.0-or-later (Copyright (C) the VLC authors and VideoLAN), offered under version 2 of this license or, at your option, any later version. OmniDeck itself is GPL-3.0 (see LICENSE).
```
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your freedom to
share and change it. By contrast, the GNU General Public License is intended
to guarantee your freedom to share and change free software--to make sure
the software is free for all its users. This General Public License applies
to most of the Free Software Foundation's software and to any other program
whose authors commit to using it. (Some other Free Software Foundation
software is covered by the GNU Lesser General Public License instead.) You
can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our
General Public Licenses are designed to make sure that you have the freedom
to distribute copies of free software (and charge for this service if you
wish), that you receive source code or can get it if you want it, that you
can change the software or use pieces of it in new free programs; and that
you know you can do these things.
To protect your rights, we need to make restrictions that forbid anyone to
deny you these rights or to ask you to surrender the rights. These
restrictions translate to certain responsibilities for you if you distribute
copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether gratis or
for a fee, you must give the recipients all the rights that you have. You
must make sure that they, too, receive or can get the source code. And you
must show them these terms so they know their rights.
We protect your rights with two steps: (1) copyright the software, and (2)
offer you this license which gives you legal permission to copy, distribute
and/or modify the software.
Also, for each author's protection and ours, we want to make certain that
everyone understands that there is no warranty for this free software. If
the software is modified by someone else and passed on, we want its
recipients to know that what they have is not the original, so that any
problems introduced by others will not reflect on the original authors'
reputations.
Finally, any free program is threatened constantly by software patents. We
wish to avoid the danger that redistributors of a free program will
individually obtain patent licenses, in effect making the program
proprietary. To prevent this, we have made it clear that any patent must be
licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and modification
follow.
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains a notice
placed by the copyright holder saying it may be distributed under the terms
of this General Public License. The "Program", below, refers to any such
program or work, and a "work based on the Program" means either the Program
or any derivative work under copyright law: that is to say, a work
containing the Program or a portion of it, either verbatim or with
modifications and/or translated into another language. (Hereinafter,
translation is included without limitation in the term "modification".) Each
licensee is addressed as "you".
Activities other than copying, distribution and modification are not covered
by this License; they are outside its scope. The act of running the Program
is not restricted, and the output from the Program is covered only if its
contents constitute a work based on the Program (independent of having been
made by running the Program). Whether that is true depends on what the
Program does.
1. You may copy and distribute verbatim copies of the Program's source code
as you receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice and
disclaimer of warranty; keep intact all the notices that refer to this
License and to the absence of any warranty; and give any other recipients of
the Program a copy of this License along with the Program.
You may charge a fee for the physical act of transferring a copy, and you
may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion of it,
thus forming a work based on the Program, and copy and distribute such
modifications or work under the terms of Section 1 above, provided that you
also meet all of these conditions:
a) You must cause the modified files to carry prominent notices stating
that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any part
thereof, to be licensed as a whole at no charge to all third parties
under the terms of this License.
c) If the modified program normally reads commands interactively when
run, you must cause it, when started running for such interactive use
in the most ordinary way, to print or display an announcement including
an appropriate copyright notice and a notice that there is no warranty
(or else, saying that you provide a warranty) and that users may
redistribute the program under these conditions, and telling the user
how to view a copy of this License. (Exception: if the Program itself
is interactive but does not normally print such an announcement, your
work based on the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Program, and can be
reasonably considered independent and separate works in themselves, then
this License, and its terms, do not apply to those sections when you
distribute them as separate works. But when you distribute the same sections
as part of a whole which is a work based on the Program, the distribution of
the whole must be on the terms of this License, whose permissions for other
licensees extend to the entire whole, and thus to each and every part
regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your
rights to work written entirely by you; rather, the intent is to exercise
the right to control the distribution of derivative or collective works
based on the Program.
In addition, mere aggregation of another work not based on the Program with
the Program (or with a work based on the Program) on a volume of a storage
or distribution medium does not bring the other work under the scope of this
License.
3. You may copy and distribute the Program (or a work based on it, under
Section 2) in object code or executable form under the terms of Sections 1
and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable source
code, which must be distributed under the terms of Sections 1 and 2
above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years,
to give any third party, for a charge no more than your cost of
physically performing source distribution, a complete machine-readable
copy of the corresponding source code, to be distributed under the
terms of Sections 1 and 2 above on a medium customarily used for
software interchange; or,
c) Accompany it with the information you received as to the offer to
distribute corresponding source code. (This alternative is allowed only
for noncommercial distribution and only if you received the program in
object code or executable form with such an offer, in accord with
Subsection b above.)
The source code for a work means the preferred form of the work for making
modifications to it. For an executable work, complete source code means all
the source code for all modules it contains, plus any associated interface
definition files, plus the scripts used to control compilation and
installation of the executable. However, as a special exception, the source
code distributed need not include anything that is normally distributed (in
either source or binary form) with the major components (compiler, kernel,
and so on) of the operating system on which the executable runs, unless that
component itself accompanies the executable.
If distribution of executable or object code is made by offering access to
copy from a designated place, then offering equivalent access to copy the
source code from the same place counts as distribution of the source code,
even though third parties are not compelled to copy the source along with
the object code.
4. You may not copy, modify, sublicense, or distribute the Program except as
expressly provided under this License. Any attempt otherwise to copy,
modify, sublicense or distribute the Program is void, and will automatically
terminate your rights under this License. However, parties who have received
copies, or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not signed
it. However, nothing else grants you permission to modify or distribute the
Program or its derivative works. These actions are prohibited by law if you
do not accept this License. Therefore, by modifying or distributing the
Program (or any work based on the Program), you indicate your acceptance of
this License to do so, and all its terms and conditions for copying,
distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the original
licensor to copy, distribute or modify the Program subject to these terms
and conditions. You may not impose any further restrictions on the
recipients' exercise of the rights granted herein. You are not responsible
for enforcing compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot distribute so
as to satisfy simultaneously your obligations under this License and any
other pertinent obligations, then as a consequence you may not distribute
the Program at all. For example, if a patent license would not permit
royalty-free redistribution of the Program by all those who receive copies
directly or indirectly through you, then the only way you could satisfy both
it and this License would be to refrain entirely from distribution of the
Program.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply and
the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any patents
or other property right claims or to contest validity of any such claims;
this section has the sole purpose of protecting the integrity of the free
software distribution system, which is implemented by public license
practices. Many people have made generous contributions to the wide range of
software distributed through that system in reliance on consistent
application of that system; it is up to the author/donor to decide if he or
she is willing to distribute software through any other system and a
licensee cannot impose that choice.
This section is intended to make thoroughly clear what is believed to be a
consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in certain
countries either by patents or by copyrighted interfaces, the original
copyright holder who places the Program under this License may add an
explicit geographical distribution limitation excluding those countries, so
that distribution is permitted only in or among countries not thus excluded.
In such case, this License incorporates the limitation as if written in the
body of this License.
9. The Free Software Foundation may publish revised and/or new versions of
the General Public License from time to time. Such new versions will be
similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free programs
whose distribution conditions are different, write to the author to ask for
permission. For software which is copyrighted by the Free Software
Foundation, write to the Free Software Foundation; we sometimes make
exceptions for this. Our decision will be guided by the two goals of
preserving the free status of all derivatives of our free software and of
promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR
THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM
PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO
LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR
THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible
use to the public, the best way to achieve this is to make it free software
which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively convey the
exclusion of warranty; and each file should have at least the "copyright"
line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Also add
information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this when
it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author Gnomovision
comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is
free software, and you are welcome to redistribute it under certain
conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may be
called something other than `show w' and `show c'; they could even be mouse-
clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James
Hacker.
signature of Ty Coon, 1 April 1989 Ty Coon, President of Vice
```
### SQLite
SQLite, shipped as the `e_sqlite3` native library, is in the public domain: "The author disclaims copyright to this source code." (see https://sqlite.org/copyright.html).
+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;
}
}
}
+22
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). -->
@@ -40,6 +42,26 @@
<PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup>
<!-- libVLC for the media player (docs/SPEC.md §3.6), copied to libvlc\win-x64 next to OmniDeck.exe:
x64 only, and only the plugins the player needs (docs/spikes/06-libvlcsharp.md). -->
<PropertyGroup>
<VlcWindowsX86Enabled>false</VlcWindowsX86Enabled>
<VlcWindowsArm64Enabled>false</VlcWindowsArm64Enabled>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="VideoLAN.LibVLC.Windows" Version="3.0.24" />
</ItemGroup>
<ItemGroup>
<VlcWindowsX64IncludeFiles Include="libvlc.dll;libvlccore.dll" />
<VlcWindowsX64IncludeFiles Include="plugins\access\%2A;plugins\audio_filter\%2A;plugins\audio_mixer\%2A;plugins\audio_output\%2A" />
<VlcWindowsX64IncludeFiles Include="plugins\codec\%2A;plugins\demux\%2A;plugins\packetizer\%2A;plugins\stream_filter\%2A" />
<VlcWindowsX64IncludeFiles Include="plugins\text_renderer\%2A;plugins\spu\%2A;plugins\video_chroma\%2A;plugins\video_filter\%2A;plugins\video_output\%2A;plugins\misc\%2A" />
<!-- The player opens local files: no network streaming. -->
<VlcWindowsX64ExcludeFiles Include="plugins\access\libaccess_srt_plugin.dll;plugins\access\libftp_plugin.dll;plugins\access\libhttp_plugin.dll;plugins\access\libhttps_plugin.dll;plugins\access\librtp_plugin.dll;plugins\access\libsftp_plugin.dll;plugins\access\libsmb_plugin.dll" />
</ItemGroup>
<!-- The license and legal documents travel with every build: the self-contained app
redistributes MIT/BSD code whose notices must ship with it, and the P1 legal gate shows them. -->
<ItemGroup>
+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;
}
}
@@ -0,0 +1,9 @@
-- The media module's queue (docs/SPEC.md §3.6): one row per named list, "queue" being the one the
-- player works through. items is a JSON array of file paths; position_ms is where the current one
-- stood when playback last stopped.
CREATE TABLE IF NOT EXISTS media_playlists (
name TEXT PRIMARY KEY,
items TEXT NOT NULL,
current INTEGER NOT NULL DEFAULT 0,
position_ms INTEGER NOT NULL DEFAULT 0
);
+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");
@@ -0,0 +1,7 @@
namespace OmniDeck.Modules.Media;
/// <summary>Makes players: libVLC in the app (<see cref="OdVlcEngine"/>). Disposing it lets libVLC go.</summary>
internal interface IOdMediaEngine : IDisposable
{
IOdMediaPlayer CreatePlayer();
}
@@ -0,0 +1,65 @@
namespace OmniDeck.Modules.Media;
/// <summary>
/// One player as the media module uses it: libVLC's in the app (<see cref="OdVlcPlayer"/>), a fake in
/// tests. Its events arrive on the thread that created it, the UI thread.
/// </summary>
internal interface IOdMediaPlayer : IDisposable
{
/// <summary>The player started, paused, stopped, reached the end, or failed.</summary>
event EventHandler? StateChanged;
/// <summary>Playback moved on, or the length became known; a few times a second while playing.</summary>
event EventHandler? TimeChanged;
OdMediaState State { get; }
TimeSpan Time { get; }
TimeSpan Length { get; }
/// <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, 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();
void Pause();
void Stop();
void Seek(TimeSpan time);
}
+40
View File
@@ -0,0 +1,40 @@
using System.IO;
using System.Text;
namespace OmniDeck.Modules.Media;
/// <summary>Reads and writes .m3u playlists: one path per line, <c>#</c> lines are comments or extended info.</summary>
internal static class OdM3u
{
/// <summary>The paths in <paramref name="text"/>; a relative one is taken from <paramref name="folder"/>, and URLs are skipped.</summary>
public static IReadOnlyList<string> Parse(string text, string folder)
{
ArgumentNullException.ThrowIfNull(text);
var paths = new List<string>();
foreach (var raw in text.Split('\n'))
{
var line = raw.Trim();
if (line.Length == 0 || line.StartsWith('#') || line.Contains("://", StringComparison.Ordinal))
{
continue;
}
paths.Add(Path.GetFullPath(Path.IsPathRooted(line) ? line : Path.Combine(folder, line)));
}
return paths;
}
/// <summary>An extended .m3u holding <paramref name="paths"/>, each named after its file.</summary>
public static string Write(IEnumerable<string> paths)
{
ArgumentNullException.ThrowIfNull(paths);
var text = new StringBuilder("#EXTM3U\n");
foreach (var path in paths)
{
text.Append("#EXTINF:-1,").Append(Path.GetFileNameWithoutExtension(path)).Append('\n').Append(path).Append('\n');
}
return text.ToString();
}
}
@@ -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);
@@ -0,0 +1,7 @@
namespace OmniDeck.Modules.Media;
/// <summary>A file could not be played; <see cref="File"/> is its name.</summary>
internal sealed class OdMediaFailedEventArgs(string file) : EventArgs
{
public string File { get; } = file;
}
@@ -0,0 +1,28 @@
using System.IO;
namespace OmniDeck.Modules.Media;
/// <summary>The files the media module plays (docs/SPEC.md §3.6): local audio and video, and .m3u playlists.</summary>
internal static class OdMediaFiles
{
/// <summary>The extensions it accepts, audio first.</summary>
public static readonly string[] Extensions =
[
".mp3", ".flac", ".wav", ".ogg", ".opus", ".m4a", ".aac", ".wma",
".mp4", ".mkv", ".webm", ".avi", ".mov", ".wmv", ".m4v", ".ts",
];
public static bool IsMedia(string path) => Extensions.Contains(Path.GetExtension(path), StringComparer.OrdinalIgnoreCase);
public static bool IsPlaylist(string path) =>
Path.GetExtension(path) is { } extension
&& (string.Equals(extension, ".m3u", StringComparison.OrdinalIgnoreCase) || string.Equals(extension, ".m3u8", StringComparison.OrdinalIgnoreCase));
/// <summary>The media files directly in <paramref name="folder"/>, by name.</summary>
public static IReadOnlyList<string> InFolder(string folder) =>
[.. Directory.EnumerateFiles(folder).Where(IsMedia).Order(StringComparer.OrdinalIgnoreCase)];
/// <summary>The file dialog's filter: every accepted extension, then everything.</summary>
public static string Filter(string mediaLabel, string allLabel) =>
$"{mediaLabel}|{string.Join(';', Extensions.Select(extension => "*" + extension))}|{allLabel}|*.*";
}
+12
View File
@@ -0,0 +1,12 @@
namespace OmniDeck.Modules.Media;
/// <summary>One file in the queue, as the list shows it.</summary>
/// <param name="Index">Its place in the queue.</param>
/// <param name="Path">The file.</param>
/// <param name="IsCurrent">Whether it is the one playing, or next to play.</param>
public sealed record OdMediaItem(int Index, string Path, bool IsCurrent)
{
public string Title => System.IO.Path.GetFileNameWithoutExtension(Path);
public override string ToString() => Title;
}
+112
View File
@@ -0,0 +1,112 @@
using System.IO;
using System.Windows;
using OmniDeck.Core.Modules;
using Serilog;
using Wpf.Ui.Controls;
namespace OmniDeck.Modules.Media;
/// <summary>
/// The media player (docs/SPEC.md §3.6): local audio and video through libVLC, with a queue that
/// survives restarts. libVLC starts with the first file played. While something plays the module is
/// 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, IOdMediaControls
{
private readonly Func<ILogger, IOdMediaEngine> _engines;
private IOdModuleContext? _context;
private IOdMediaEngine? _engine;
private OdMediaSession? _session;
private OdMediaViewModel? _viewModel;
public OdMediaModule()
: this(log => new OdVlcEngine(log))
{
}
internal OdMediaModule(Func<ILogger, IOdMediaEngine> engines)
{
_engines = engines;
}
public OdModuleInfo Info { get; } = new("media", "Media_Name", nameof(SymbolRegular.MoviesAndTv24), "Category_Media", OdRamClass.Heavy);
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;
return Task.CompletedTask;
}
public FrameworkElement CreateView()
{
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), context.Time);
return new OdMediaView { DataContext = _viewModel };
}
public Task ActivateAsync() => Task.CompletedTask;
/// <summary>Pinned while something plays (docs/RAM-GOVERNOR.md §3).</summary>
public Task<bool> CanSuspendAsync() => Task.FromResult(_session?.IsPlaying != true);
/// <summary>Lets the player go; libVLC stays loaded, so playing again starts at once.</summary>
public Task SuspendAsync(OdSuspendReason reason)
{
_session?.Release();
return Task.CompletedTask;
}
public Task HibernateAsync()
{
_session?.Release();
_viewModel?.Dispose();
_viewModel = null;
_engine?.Dispose();
_engine = null;
return Task.CompletedTask;
}
public async Task CloseAsync()
{
await HibernateAsync();
_session?.Dispose();
_session = null;
}
}
@@ -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);
@@ -0,0 +1,78 @@
namespace OmniDeck.Modules.Media;
/// <summary>The files the player works through, in order, and which one is current.</summary>
internal sealed class OdMediaQueue
{
private readonly List<string> _items = [];
public OdMediaQueue(IEnumerable<string> items, int current)
{
_items.AddRange(items);
Current = _items.Count == 0 ? -1 : Math.Clamp(current, 0, _items.Count - 1);
}
public IReadOnlyList<string> Items => _items;
/// <summary>The index of the current file; -1 while the queue is empty.</summary>
public int Current { get; private set; }
public string? CurrentItem => Current >= 0 ? _items[Current] : null;
public bool HasNext => Current + 1 < _items.Count;
public bool HasPrevious => Current > 0;
/// <summary>Adds files at the end; the first file added to an empty queue becomes current. Returns the index of the first one.</summary>
public int Add(IEnumerable<string> paths)
{
var first = _items.Count;
_items.AddRange(paths);
if (Current < 0 && _items.Count > 0)
{
Current = 0;
}
return first;
}
public bool MoveTo(int index)
{
if (index < 0 || index >= _items.Count)
{
return false;
}
Current = index;
return true;
}
public bool Next() => MoveTo(Current + 1);
public bool Previous() => MoveTo(Current - 1);
/// <summary>Removes one file; the current one stays current unless it was the one removed.</summary>
public void RemoveAt(int index)
{
if (index < 0 || index >= _items.Count)
{
return;
}
_items.RemoveAt(index);
if (index < Current || Current >= _items.Count)
{
Current--;
}
if (_items.Count == 0)
{
Current = -1;
}
}
public void Clear()
{
_items.Clear();
Current = -1;
}
}
@@ -0,0 +1,353 @@
using System.IO;
using Serilog;
namespace OmniDeck.Modules.Media;
/// <summary>
/// What the media module keeps between views (docs/SPEC.md §3.6): the queue, where playback stands,
/// and the player while there is one. The player starts with the first file played; <see cref="Release"/>
/// lets it go and keeps the position, so the module can step down while paused. Used on the UI thread.
/// </summary>
internal sealed class OdMediaSession : IDisposable
{
private readonly OdMediaStore _store;
private readonly Func<IOdMediaPlayer> _newPlayer;
private readonly ILogger _log;
private IOdMediaPlayer? _player;
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)
{
_store = store;
_newPlayer = newPlayer;
_log = log;
(Queue, _position) = store.Load();
}
/// <summary>The queue, the player or where playback stands changed.</summary>
public event EventHandler? Changed;
/// <summary>The player came or went: the view shows the new one, or none.</summary>
public event EventHandler? PlayerChanged;
/// <summary>A file could not be played.</summary>
public event EventHandler<OdMediaFailedEventArgs>? Failed;
public OdMediaQueue Queue { get; }
public IOdMediaPlayer? Player => _player;
public OdMediaState State => _player?.State ?? OdMediaState.Idle;
/// <summary>Whether something is playing: the module is pinned meanwhile (docs/RAM-GOVERNOR.md §3).</summary>
public bool IsPlaying => State is OdMediaState.Opening or OdMediaState.Playing;
public TimeSpan Time => _player?.Time ?? _position;
public TimeSpan Length => _player?.Length ?? TimeSpan.Zero;
public int Volume
{
get => _volume;
set
{
_volume = Math.Clamp(value, 0, 100);
_player?.Volume = _volume;
}
}
public bool Muted
{
get => _muted;
set
{
_muted = value;
_player?.Muted = value;
}
}
/// <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)
{
if (paths.Count == 0)
{
return;
}
var first = Queue.Add(paths);
Save();
if (play)
{
PlayAt(first);
}
else
{
Changed?.Invoke(this, EventArgs.Empty);
}
}
public void PlayAt(int index)
{
if (Queue.MoveTo(index))
{
Start(TimeSpan.Zero, play: true);
}
}
/// <summary>Plays or pauses; with no player yet, opens the current file where playback stood.</summary>
public void Toggle()
{
switch (State)
{
case OdMediaState.Playing or OdMediaState.Opening:
_player!.Pause();
break;
case OdMediaState.Paused:
_player!.Play();
break;
default:
if (Queue.CurrentItem is not null)
{
Start(State == OdMediaState.Ended ? TimeSpan.Zero : _position, play: true);
}
break;
}
}
public void Next()
{
if (Queue.Next())
{
Start(TimeSpan.Zero, play: true);
}
}
public void Previous()
{
// Like a music player: past the first seconds, Previous starts the file over.
if (Time > TimeSpan.FromSeconds(3) || !Queue.Previous())
{
Seek(TimeSpan.Zero);
return;
}
Start(TimeSpan.Zero, play: true);
}
public void Seek(TimeSpan time)
{
_position = time;
_player?.Seek(time);
Changed?.Invoke(this, EventArgs.Empty);
}
public void Stop()
{
_position = TimeSpan.Zero;
_player?.Stop();
Save();
}
public void RemoveAt(int index)
{
var wasCurrent = index == Queue.Current;
Queue.RemoveAt(index);
if (wasCurrent)
{
Release();
_position = TimeSpan.Zero;
}
Save();
Changed?.Invoke(this, EventArgs.Empty);
}
public void Clear()
{
Release();
Queue.Clear();
_position = TimeSpan.Zero;
Save();
Changed?.Invoke(this, EventArgs.Empty);
}
/// <summary>Lets the player go and keeps where playback stood: suspending, hibernating, closing.</summary>
public void Release()
{
if (_player is not { } player)
{
return;
}
_position = player.State is OdMediaState.Ended or OdMediaState.Stopped ? TimeSpan.Zero : player.Time;
_player = null;
player.StateChanged -= OnStateChanged;
player.TimeChanged -= OnTimeChanged;
player.Dispose();
Save();
PlayerChanged?.Invoke(this, EventArgs.Empty);
Changed?.Invoke(this, EventArgs.Empty);
}
public void Dispose() => Release();
private void Start(TimeSpan from, bool play, bool keepSubtitle = false)
{
if (Queue.CurrentItem is not { } path)
{
return;
}
if (_player is null)
{
_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, new OdMediaOpening(from, play, _subtitleEncoding, _subtitle));
Save();
Changed?.Invoke(this, EventArgs.Empty);
}
private void OnStateChanged(object? sender, EventArgs e)
{
switch (State)
{
case OdMediaState.Ended when Queue.HasNext:
Next();
return;
case OdMediaState.Ended:
_position = TimeSpan.Zero;
Save();
break;
case OdMediaState.Failed:
_log.Warning("A media file could not be played");
Failed?.Invoke(this, new OdMediaFailedEventArgs(Path.GetFileName(Queue.CurrentItem ?? "")));
break;
case OdMediaState.Paused:
_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);
}
private void OnTimeChanged(object? sender, EventArgs e) => Changed?.Invoke(this, EventArgs.Empty);
private void Save() => _store.Save(Queue, _position);
}
@@ -0,0 +1,19 @@
namespace OmniDeck.Modules.Media;
/// <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;
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,13 @@
namespace OmniDeck.Modules.Media;
/// <summary>Where a player stands.</summary>
internal enum OdMediaState
{
Idle,
Opening,
Playing,
Paused,
Stopped,
Ended,
Failed,
}
@@ -0,0 +1,44 @@
using System.Text.Json;
using Dapper;
using OmniDeck.Core.Storage;
namespace OmniDeck.Modules.Media;
/// <summary>Where the media module keeps its queue between sessions: the <c>media_playlists</c> table.</summary>
internal sealed class OdMediaStore(OdDatabase database)
{
private const string Queue = "queue";
/// <summary>The queue as last saved, and where playback stood; empty the first time.</summary>
public (OdMediaQueue Queue, TimeSpan Position) Load()
{
using var connection = database.Open();
var row = connection.QuerySingleOrDefault<(string Items, long Current, long PositionMs)>(
"SELECT items, current, position_ms FROM media_playlists WHERE name = @name", new { name = Queue });
if (row.Items is null)
{
return (new OdMediaQueue([], 0), TimeSpan.Zero);
}
var items = JsonSerializer.Deserialize(row.Items, OdModulesJsonContext.Default.StringArray) ?? [];
return (new OdMediaQueue(items, (int)row.Current), TimeSpan.FromMilliseconds(row.PositionMs));
}
public void Save(OdMediaQueue queue, TimeSpan position)
{
ArgumentNullException.ThrowIfNull(queue);
using var connection = database.Open();
connection.Execute(
"""
INSERT INTO media_playlists (name, items, current, position_ms) VALUES (@name, @items, @current, @position)
ON CONFLICT (name) DO UPDATE SET items = excluded.items, current = excluded.current, position_ms = excluded.position_ms
""",
new
{
name = Queue,
items = JsonSerializer.Serialize([.. queue.Items], OdModulesJsonContext.Default.StringArray),
current = queue.Current,
position = (long)position.TotalMilliseconds,
});
}
}
@@ -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);
+215
View File
@@ -0,0 +1,215 @@
<UserControl x:Class="OmniDeck.Modules.Media.OdMediaView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:media="clr-namespace:OmniDeck.Modules.Media"
xmlns:res="clr-namespace:OmniDeck.Core.Localization;assembly=OmniDeck.Core"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:vlc="clr-namespace:LibVLCSharp.WPF;assembly=LibVLCSharp.WPF"
AllowDrop="True"
Drop="OnDrop"
Foreground="{DynamicResource TextFillColorPrimaryBrush}">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="Visible" />
</UserControl.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- 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 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="#01000000" />
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Style>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{Binding Message}"
TextWrapping="Wrap" />
<Border Grid.Row="1"
Padding="{DynamicResource Od.Padding.Card}"
Background="{DynamicResource SolidBackgroundFillColorSecondaryBrush}">
<!-- 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}" />
<!-- 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}" />
<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 ShowsQueue, Converter={StaticResource Visible}}">
<WrapPanel Margin="{DynamicResource Od.Padding.Control}" DockPanel.Dock="Top">
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Click="OnAddFiles"
Content="{res:OdLoc Media_AddFiles}"
Icon="{ui:SymbolIcon Add24}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Click="OnAddFolder"
Content="{res:OdLoc Media_AddFolder}"
Icon="{ui:SymbolIcon Folder24}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Click="OnSavePlaylist"
Content="{res:OdLoc Media_SavePlaylist}"
Icon="{ui:SymbolIcon Save24}"
IsEnabled="{Binding HasItems}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Command="{Binding ClearCommand}"
Content="{res:OdLoc Media_Clear}"
Icon="{ui:SymbolIcon Delete24}"
IsEnabled="{Binding HasItems}" />
</WrapPanel>
<TextBlock Margin="{DynamicResource Od.Margin.Item}"
DockPanel.Dock="Top"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{res:OdLoc Media_Hint}"
TextWrapping="Wrap" />
<ListBox x:Name="Queue"
AutomationProperties.Name="{res:OdLoc Media_Queue}"
ItemsSource="{Binding Items}"
MouseDoubleClick="OnQueueDoubleClick">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type media:OdMediaItem}">
<DockPanel>
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
AutomationProperties.Name="{res:OdLoc Media_Remove}"
Command="{Binding DataContext.RemoveItemCommand, RelativeSource={RelativeSource AncestorType=ListBox}}"
CommandParameter="{Binding}"
DockPanel.Dock="Right"
Icon="{ui:SymbolIcon Dismiss24}"
ToolTip="{res:OdLoc Media_Remove}" />
<TextBlock VerticalAlignment="Center"
Text="{Binding Title}"
TextTrimming="CharacterEllipsis">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding IsCurrent}" Value="True">
<Setter Property="FontWeight" Value="SemiBold" />
<Setter Property="Foreground" Value="{DynamicResource AccentTextFillColorPrimaryBrush}" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Grid>
</UserControl>
@@ -0,0 +1,184 @@
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;
/// <summary>The media player's view: libVLC's video, its controls, and the queue. The file dialogs live here.</summary>
public partial class OdMediaView
{
public OdMediaView()
{
InitializeComponent();
DataContextChanged += OnDataContextChanged;
}
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)
{
old.PlayerChanged -= OnPlayerChanged;
}
if (e.NewValue is OdMediaViewModel model)
{
model.PlayerChanged += OnPlayerChanged;
model.IsFullscreen = OdFullscreen.GetIsActive(this);
ShowPlayer(model);
}
}
private void OnPlayerChanged(object? sender, EventArgs e)
{
if (ViewModel is { } model)
{
ShowPlayer(model);
}
}
private void ShowPlayer(OdMediaViewModel model) => Video.MediaPlayer = (model.Player as OdVlcPlayer)?.Native;
private void OnAddFiles(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog
{
Multiselect = true,
Filter = OdMediaFiles.Filter(OdLocalization.Get("Media_FilesFilter"), OdLocalization.Get("Media_AllFilter")) + "|" + OdLocalization.Get("Media_PlaylistFilter"),
};
if (dialog.ShowDialog(Window.GetWindow(this)) == true)
{
ViewModel?.Add(dialog.FileNames);
}
}
private void OnAddFolder(object sender, RoutedEventArgs e)
{
var dialog = new OpenFolderDialog();
if (dialog.ShowDialog(Window.GetWindow(this)) == true)
{
ViewModel?.Add([dialog.FolderName]);
}
}
private void OnSavePlaylist(object sender, RoutedEventArgs e)
{
var dialog = new SaveFileDialog { Filter = OdLocalization.Get("Media_PlaylistFilter"), FileName = "OmniDeck.m3u" };
if (dialog.ShowDialog(Window.GetWindow(this)) == true)
{
ViewModel?.SavePlaylist(dialog.FileName);
}
}
private void OnQueueDoubleClick(object sender, MouseButtonEventArgs e)
{
if (Queue.SelectedItem is OdMediaItem item)
{
ViewModel?.PlayItemCommand.Execute(item);
}
}
// 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)
{
ViewModel?.Add(paths);
}
}
}
@@ -0,0 +1,284 @@
using System.Collections.ObjectModel;
using System.Globalization;
using System.IO;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OmniDeck.Core.Localization;
namespace OmniDeck.Modules.Media;
/// <summary>The media player's screen: the queue, the transport controls and the time. Used from the UI thread.</summary>
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;
[ObservableProperty]
private string _title = "";
[ObservableProperty]
private string _timeText = "";
[ObservableProperty]
private double _position;
[ObservableProperty]
private double _length;
[ObservableProperty]
private bool _isPlaying;
/// <summary>Whether a picture shows; otherwise the screen covers libVLC's empty video window.</summary>
[ObservableProperty]
private bool _showsVideo;
[ObservableProperty]
private bool _hasItems;
[ObservableProperty]
private double _volume;
[ObservableProperty]
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, 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;
_session.Changed += OnSessionChanged;
_session.PlayerChanged += OnPlayerChanged;
_session.Failed += OnFailed;
Refresh();
}
/// <summary>The player came or went: the view hands it to its <c>VideoView</c>.</summary>
public event EventHandler? PlayerChanged;
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)
{
ArgumentNullException.ThrowIfNull(paths);
var files = new List<string>();
foreach (var path in paths)
{
if (OdMediaFiles.IsPlaylist(path))
{
files.AddRange(OdM3u.Parse(File.ReadAllText(path), Path.GetDirectoryName(path) ?? ""));
}
else if (Directory.Exists(path))
{
files.AddRange(OdMediaFiles.InFolder(path));
}
else if (OdMediaFiles.IsMedia(path))
{
files.Add(path);
}
}
Message = files.Count == 0 ? OdLocalization.Get("Media_NothingToPlay") : "";
_session.Add(files, play: true);
}
/// <summary>Writes the queue to <paramref name="path"/> as an .m3u playlist.</summary>
public void SavePlaylist(string path) => File.WriteAllText(path, OdM3u.Write(_session.Queue.Items));
public void Dispose()
{
_session.Changed -= OnSessionChanged;
_session.PlayerChanged -= OnPlayerChanged;
_session.Failed -= OnFailed;
}
internal static string Clock(TimeSpan time) => time.TotalHours >= 1
? time.ToString(@"h\:mm\:ss", CultureInfo.InvariantCulture)
: time.ToString(@"m\:ss", CultureInfo.InvariantCulture);
[RelayCommand]
private void PlayPause() => _session.Toggle();
[RelayCommand]
private void Stop() => _session.Stop();
[RelayCommand]
private void Next() => _session.Next();
[RelayCommand]
private void Previous() => _session.Previous();
[RelayCommand]
private void PlayItem(OdMediaItem? item)
{
if (item is not null)
{
_session.PlayAt(item.Index);
}
}
[RelayCommand]
private void RemoveItem(OdMediaItem? item)
{
if (item is not null)
{
_session.RemoveAt(item.Index);
}
}
[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;
[RelayCommand]
private void ToggleMute() => Muted = !Muted;
partial void OnPositionChanged(double value)
{
if (!_syncing)
{
_session.Seek(TimeSpan.FromSeconds(value));
}
}
partial void OnVolumeChanged(double value)
{
_session.Volume = (int)Math.Round(value);
SaveSettings(_settings with { Volume = _session.Volume });
}
partial void OnMutedChanged(bool value)
{
_session.Muted = value;
SaveSettings(_settings with { Muted = value });
}
partial void OnQueueVisibleChanged(bool value) => SaveSettings(_settings with { QueueVisible = value });
private void SaveSettings(OdMediaSettings settings)
{
if (settings != _settings)
{
_settings = settings;
_saveSettings(settings);
}
}
private void OnSessionChanged(object? sender, EventArgs e) => Refresh();
private void OnPlayerChanged(object? sender, EventArgs e) => PlayerChanged?.Invoke(this, EventArgs.Empty);
private void OnFailed(object? sender, OdMediaFailedEventArgs e) => Message = OdLocalization.Format("Media_Failed", e.File);
private void Refresh()
{
var queue = _session.Queue;
if (Items.Count != queue.Items.Count || Items.Any(item => item.IsCurrent != (item.Index == queue.Current)))
{
Items.Clear();
for (var i = 0; i < queue.Items.Count; i++)
{
Items.Add(new OdMediaItem(i, queue.Items[i], i == queue.Current));
}
}
HasItems = queue.Items.Count > 0;
Title = queue.CurrentItem is { } path ? Path.GetFileNameWithoutExtension(path) : OdLocalization.Get("Media_Empty");
IsPlaying = _session.IsPlaying;
ShowsVideo = _session.Player is { HasVideo: true, State: not (OdMediaState.Stopped or OdMediaState.Ended or OdMediaState.Failed) };
var time = _session.Time;
var length = _session.Length;
_syncing = true;
try
{
Length = Math.Max(length.TotalSeconds, 0);
Position = Math.Min(time.TotalSeconds, Length);
}
finally
{
_syncing = false;
}
TimeText = length > TimeSpan.Zero ? Clock(time) + " / " + Clock(length) : Clock(time);
}
}
@@ -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;
}
+52
View File
@@ -0,0 +1,52 @@
using LibVLCSharp.Shared;
using Serilog;
using Serilog.Events;
namespace OmniDeck.Modules.Media;
/// <summary>
/// libVLC for the media module, started with the first player it makes; disposing it lets libVLC go
/// (docs/spikes/06-libvlcsharp.md: playback holds 280–520 MB). Its errors go to the app log as
/// warnings, less the known noise. Used on the UI thread.
/// </summary>
internal sealed class OdVlcEngine(ILogger log) : IOdMediaEngine
{
private readonly ILogger _log = log.ForContext<OdVlcEngine>();
private LibVLC? _libVlc;
public IOdMediaPlayer CreatePlayer()
{
var ui = SynchronizationContext.Current ?? throw new InvalidOperationException("Players are made on the UI thread.");
_libVlc ??= Start();
return new OdVlcPlayer(_libVlc, ui);
}
public void Dispose()
{
if (_libVlc is { } libVlc)
{
_libVlc = null;
libVlc.Log -= OnLog;
libVlc.Dispose();
_log.Information("libVLC let go");
}
}
private LibVLC Start()
{
// Loads libvlc.dll from libvlc\win-x64 next to the app; a second call does nothing.
LibVLCSharp.Shared.Core.Initialize();
var libVlc = new LibVLC("--no-video-title-show");
libVlc.Log += OnLog;
_log.Information("libVLC {Version} ready", libVlc.Version);
return libVlc;
}
private void OnLog(object? sender, LogEventArgs e)
{
if (e.Level == LogLevel.Error && OdVlcLog.Keep(e.Message))
{
_log.Write(LogEventLevel.Warning, "libVLC {Module}: {Message}", e.Module, e.Message);
}
}
}
+9
View File
@@ -0,0 +1,9 @@
namespace OmniDeck.Modules.Media;
/// <summary>Which libVLC messages reach the app log: not the three harmless ones docs/spikes/06-libvlcsharp.md lists.</summary>
internal static class OdVlcLog
{
private static readonly string[] Noise = ["option quiet does not exist", "SetThumbNailClip failed", "not enough decoding slices"];
public static bool Keep(string message) => !Noise.Any(noise => message.Contains(noise, StringComparison.OrdinalIgnoreCase));
}
+148
View File
@@ -0,0 +1,148 @@
using System.Globalization;
using LibVLCSharp.Shared;
using VlcMedia = LibVLCSharp.Shared.Media;
namespace OmniDeck.Modules.Media;
/// <summary>
/// libVLC's player. Its events arrive on libVLC's threads, where calling back into the player can
/// deadlock, so they are posted to the UI thread first.
/// </summary>
internal sealed class OdVlcPlayer : IOdMediaPlayer
{
private readonly LibVLC _libVlc;
private readonly SynchronizationContext _ui;
private VlcMedia? _media;
public OdVlcPlayer(LibVLC libVlc, SynchronizationContext ui)
{
_libVlc = libVlc;
_ui = ui;
Native = new MediaPlayer(libVlc) { EnableHardwareDecoding = true };
Native.Opening += (_, _) => Post(OdMediaState.Opening);
Native.Playing += (_, _) => Post(OdMediaState.Playing);
Native.Paused += (_, _) => Post(OdMediaState.Paused);
Native.Stopped += (_, _) => Post(OdMediaState.Stopped);
Native.EndReached += (_, _) => Post(OdMediaState.Ended);
Native.EncounteredError += (_, _) => Post(OdMediaState.Failed);
Native.TimeChanged += (_, _) => _ui.Post(_ => TimeChanged?.Invoke(this, EventArgs.Empty), null);
Native.LengthChanged += (_, _) => _ui.Post(_ => TimeChanged?.Invoke(this, EventArgs.Empty), null);
}
public event EventHandler? StateChanged;
public event EventHandler? TimeChanged;
/// <summary>The player the view's <c>VideoView</c> shows.</summary>
public MediaPlayer Native { get; }
public OdMediaState State { get; private set; }
public TimeSpan Time => TimeSpan.FromMilliseconds(Math.Max(0, Native.Time));
public TimeSpan Length => TimeSpan.FromMilliseconds(Math.Max(0, Native.Length));
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;
set => Native.Volume = Math.Clamp(value, 0, 100);
}
public bool Muted
{
get => Native.Mute;
set => Native.Mute = value;
}
public void Open(string path, OdMediaOpening opening)
{
ArgumentNullException.ThrowIfNull(opening);
var media = new VlcMedia(_libVlc, path, FromType.FromPath);
if (opening.From > TimeSpan.Zero)
{
media.AddOption(":start-time=" + opening.From.TotalSeconds.ToString("0.###", CultureInfo.InvariantCulture));
}
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;
Native.Play(media);
}
public void Play() => Native.SetPause(false);
public void Pause() => Native.SetPause(true);
public void Stop() => Native.Stop();
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();
Native.Dispose();
_media?.Dispose();
_media = null;
}
private void Post(OdMediaState state) => _ui.Post(
_ =>
{
State = state;
StateChanged?.Invoke(this, EventArgs.Empty);
},
null);
}
@@ -1,6 +1,7 @@
using System.Text.Json.Serialization;
using OmniDeck.Modules.Calculator;
using OmniDeck.Modules.Clock;
using OmniDeck.Modules.Media;
using OmniDeck.Modules.Weather;
namespace OmniDeck.Modules;
@@ -10,4 +11,6 @@ namespace OmniDeck.Modules;
[JsonSerializable(typeof(OdClockSettings))]
[JsonSerializable(typeof(OdCalculatorSettings))]
[JsonSerializable(typeof(OdWeatherSettings))]
[JsonSerializable(typeof(OdMediaSettings))]
[JsonSerializable(typeof(string[]))]
internal sealed partial class OdModulesJsonContext : JsonSerializerContext;
@@ -3,6 +3,7 @@ using OmniDeck.Core.Modules;
using OmniDeck.Modules.Calculator;
using OmniDeck.Modules.Calendar;
using OmniDeck.Modules.Clock;
using OmniDeck.Modules.Media;
using OmniDeck.Modules.Timer;
using OmniDeck.Modules.Weather;
@@ -28,6 +29,7 @@ public static class OdModulesServiceCollectionExtensions
services.AddSingleton<IOdModule, OdCalculatorModule>();
services.AddSingleton<IOdModule, OdWeatherModule>();
services.AddSingleton<IOdModule, OdCalendarModule>();
services.AddSingleton<IOdModule, OdMediaModule>();
return services;
}
}
@@ -20,6 +20,7 @@
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageReference Include="Ical.Net" Version="5.2.3" />
<PackageReference Include="LibVLCSharp.WPF" Version="3.10.2" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup>
+150
View File
@@ -454,4 +454,154 @@
<data name="Calendar_ReminderAllDay" xml:space="preserve">
<value>{0}, all day</value>
</data>
<data name="Category_Media" xml:space="preserve">
<value>Media</value>
</data>
<data name="Media_Name" xml:space="preserve">
<value>Media</value>
</data>
<data name="Media_Empty" xml:space="preserve">
<value>Nothing to play yet</value>
</data>
<data name="Media_Hint" xml:space="preserve">
<value>Add files or a folder, open an .m3u playlist, or drop files here. Double-click a file to play it.</value>
</data>
<data name="Media_NothingToPlay" xml:space="preserve">
<value>None of those are files the player can open.</value>
</data>
<data name="Media_Failed" xml:space="preserve">
<value>{0} could not be played.</value>
</data>
<data name="Media_AddFiles" xml:space="preserve">
<value>Add files</value>
</data>
<data name="Media_AddFolder" xml:space="preserve">
<value>Add folder</value>
</data>
<data name="Media_SavePlaylist" xml:space="preserve">
<value>Save playlist</value>
</data>
<data name="Media_Clear" xml:space="preserve">
<value>Clear</value>
</data>
<data name="Media_Queue" xml:space="preserve">
<value>Queue</value>
</data>
<data name="Media_Remove" xml:space="preserve">
<value>Remove from the queue</value>
</data>
<data name="Media_PlayPause" xml:space="preserve">
<value>Play or pause</value>
</data>
<data name="Media_Previous" xml:space="preserve">
<value>Previous</value>
</data>
<data name="Media_Next" xml:space="preserve">
<value>Next</value>
</data>
<data name="Media_Stop" xml:space="preserve">
<value>Stop</value>
</data>
<data name="Media_Mute" xml:space="preserve">
<value>Mute</value>
</data>
<data name="Media_Volume" xml:space="preserve">
<value>Volume</value>
</data>
<data name="Media_Seek" xml:space="preserve">
<value>Position</value>
</data>
<data name="Media_FilesFilter" xml:space="preserve">
<value>Audio and video</value>
</data>
<data name="Media_AllFilter" xml:space="preserve">
<value>All files</value>
</data>
<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);
@@ -33,7 +33,7 @@ public sealed class OdCompositionTests
Assert.NotNull(provider.GetRequiredService<OdCrashHandler>());
Assert.StartsWith("OmniDeck/", provider.GetRequiredService<HttpClient>().DefaultRequestHeaders.UserAgent.ToString(), StringComparison.Ordinal);
Assert.Same(provider.GetRequiredService<OdTrayNotifier>(), provider.GetRequiredService<IOdNotifier>());
Assert.Equal(new[] { "clock", "timer", "calculator", "weather", "calendar" }, provider.GetRequiredService<OdModuleHost>().Modules.Select(m => m.Info.Id), StringComparer.Ordinal);
Assert.Equal(new[] { "clock", "timer", "calculator", "weather", "calendar", "media" }, provider.GetRequiredService<OdModuleHost>().Modules.Select(m => m.Info.Id), StringComparer.Ordinal);
}
[Fact]
@@ -50,8 +50,8 @@ public sealed class OdCompositionTests
var modules = provider.GetRequiredService<OdModuleHost>().Modules;
Assert.Equal(5 + catalog.Apps.Count, modules.Count);
Assert.Equal(catalog.Apps.Select(app => app.Id), modules.Skip(5).Select(module => module.Info.Id), StringComparer.Ordinal);
Assert.Equal(6 + catalog.Apps.Count, modules.Count);
Assert.Equal(catalog.Apps.Select(app => app.Id), modules.Skip(6).Select(module => module.Info.Id), StringComparer.Ordinal);
Assert.Equal("Gmail", modules.Single(module => string.Equals(module.Info.Id, "gmail", StringComparison.Ordinal)).Info.Title);
}
@@ -10,6 +10,7 @@ using OmniDeck.Core.Theming;
using OmniDeck.Modules.Calculator;
using OmniDeck.Modules.Calendar;
using OmniDeck.Modules.Clock;
using OmniDeck.Modules.Media;
using OmniDeck.Modules.Resources;
using OmniDeck.Modules.Timer;
using OmniDeck.Modules.Weather;
@@ -111,7 +112,7 @@ public sealed partial class OdResxKeyTests
// Names and categories travel as keys in OdModuleInfo; the shell resolves them.
using var timers = new OdTimerService(TimeProvider.System, new OdFakeNotifier());
var calendar = new OdCalendarModule(new OdCalendarStore(new OdDatabase(Path.Combine(Path.GetTempPath(), "unused.db"), pooling: false)));
IOdModule[] modules = [new OdClockModule(), new OdTimerModule(timers), new OdCalculatorModule(), new OdWeatherModule(), calendar];
IOdModule[] modules = [new OdClockModule(), new OdTimerModule(timers), new OdCalculatorModule(), new OdWeatherModule(), calendar, new OdMediaModule()];
keys.UnionWith(modules.SelectMany(module => new[] { module.Info.NameKey, module.Info.CategoryKey }));
}
@@ -0,0 +1,493 @@
using System.Globalization;
using Microsoft.Extensions.Time.Testing;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Storage;
using OmniDeck.Modules.Media;
using OmniDeck.Tests.Modules;
using OmniDeck.Tests.TestSupport;
using Serilog.Core;
namespace OmniDeck.Tests.ModuleApps;
public sealed class OdMediaTests : IDisposable
{
private readonly OdTempDirectory _temp = new();
private readonly OdDatabase _database;
private readonly OdFakeMediaEngine _engine = new();
public OdMediaTests()
{
_database = new OdDatabase(_temp.Combine("omnideck.db"), pooling: false);
_database.Migrate(OdCoreMigrations.All);
}
public void Dispose() => _temp.Dispose();
[Fact]
public void Playlists_ReadPathsAndSkipCommentsAndUrls_AndWriteThemBack()
{
var folder = _temp.Combine("music");
var text = "#EXTM3U\r\n#EXTINF:-1,One\r\none.mp3\r\n\r\nC:\\Music\\two.flac\r\nhttps://example.com/stream.mp3\r\n";
var paths = OdM3u.Parse(text, folder);
Assert.Equal(new[] { Path.Combine(folder, "one.mp3"), @"C:\Music\two.flac" }, paths, StringComparer.Ordinal);
Assert.Equal("#EXTM3U\n#EXTINF:-1,one\n" + paths[0] + "\n#EXTINF:-1,two\nC:\\Music\\two.flac\n", OdM3u.Write(paths));
Assert.Equal(paths, OdM3u.Parse(OdM3u.Write(paths), folder), StringComparer.Ordinal);
}
[Fact]
public void Files_AreTakenByExtension_AndAFolderByName()
{
var folder = Directory.CreateDirectory(_temp.Combine("folder")).FullName;
foreach (var name in new[] { "b.MP3", "a.mkv", "notes.txt", "c.m3u" })
{
File.WriteAllText(Path.Combine(folder, name), "");
}
Assert.True(OdMediaFiles.IsMedia("x.Flac"));
Assert.False(OdMediaFiles.IsMedia("x.txt"));
Assert.True(OdMediaFiles.IsPlaylist("list.M3U8"));
Assert.Equal(new[] { "a.mkv", "b.MP3" }, OdMediaFiles.InFolder(folder).Select(Path.GetFileName), StringComparer.Ordinal);
Assert.StartsWith("Media|*.mp3;*.flac;", OdMediaFiles.Filter("Media", "All"), StringComparison.Ordinal);
Assert.EndsWith("|All|*.*", OdMediaFiles.Filter("Media", "All"), StringComparison.Ordinal);
}
[Fact]
public void TheQueue_KeepsItsPlace_AsFilesComeAndGo()
{
var queue = new OdMediaQueue([], 0);
Assert.Equal(-1, queue.Current);
Assert.Equal(0, queue.Add(["a", "b", "c"]));
Assert.Equal("a", queue.CurrentItem);
Assert.True(queue.Next());
Assert.True(queue.HasNext);
Assert.True(queue.HasPrevious);
queue.RemoveAt(0);
Assert.Equal(("b", 0), (queue.CurrentItem, queue.Current));
queue.RemoveAt(0);
Assert.Equal("c", queue.CurrentItem);
Assert.False(queue.Next());
queue.RemoveAt(0);
Assert.Equal(-1, queue.Current);
Assert.Null(queue.CurrentItem);
Assert.Equal(1, new OdMediaQueue(["a", "b"], 7).Current);
}
[Fact]
public void TheQueue_IsSaved_WithWherePlaybackStood()
{
var store = new OdMediaStore(_database);
Assert.Empty(store.Load().Queue.Items);
store.Save(new OdMediaQueue([@"C:\a.mp3", @"C:\b.mp3"], 1), TimeSpan.FromSeconds(42));
var (queue, position) = store.Load();
Assert.Equal(new[] { @"C:\a.mp3", @"C:\b.mp3" }, queue.Items, StringComparer.Ordinal);
Assert.Equal(1, queue.Current);
Assert.Equal(TimeSpan.FromSeconds(42), position);
}
[Fact]
public void Playing_StartsAPlayer_MovesOnAtTheEnd_AndStopsAfterTheLast()
{
using var session = NewSession();
var playerChanges = 0;
session.PlayerChanged += (_, _) => playerChanges++;
session.Add(["one.mp3", "two.mp3"], play: true);
var player = Assert.Single(_engine.Players);
Assert.True(session.IsPlaying);
Assert.Equal(1, playerChanges);
Assert.Equal(80, player.Volume);
session.Toggle();
Assert.Equal(OdMediaState.Paused, session.State);
Assert.False(session.IsPlaying);
session.Toggle();
Assert.True(session.IsPlaying);
player.Raise(OdMediaState.Ended);
Assert.Equal(1, session.Queue.Current);
Assert.Contains("open two.mp3 0 True", player.Calls, StringComparer.Ordinal);
player.Raise(OdMediaState.Ended);
Assert.False(session.IsPlaying);
Assert.Equal(TimeSpan.Zero, new OdMediaStore(_database).Load().Position);
}
[Fact]
public void Releasing_KeepsThePosition_AndTheNextPlayStartsThere()
{
using (var session = NewSession())
{
session.Add(["one.mp3"], play: true);
var first = _engine.Players[0];
first.Time = TimeSpan.FromSeconds(30);
session.Toggle();
session.Release();
Assert.True(first.Disposed);
Assert.Null(session.Player);
Assert.Equal(TimeSpan.FromSeconds(30), session.Time);
}
using var restarted = NewSession();
Assert.Equal(TimeSpan.FromSeconds(30), restarted.Time);
restarted.Toggle();
Assert.Contains("open one.mp3 30 True", _engine.Players[1].Calls, StringComparer.Ordinal);
}
[Fact]
public void Previous_StartsTheFileOver_PastItsFirstSeconds()
{
using var session = NewSession();
session.Add(["one.mp3", "two.mp3"], play: true);
session.Next();
var player = _engine.Players[0];
player.Time = TimeSpan.FromSeconds(10);
session.Previous();
Assert.Equal(1, session.Queue.Current);
Assert.Equal("seek 0", player.Calls[^1]);
player.Time = TimeSpan.FromSeconds(1);
session.Previous();
Assert.Equal(0, session.Queue.Current);
}
[Fact]
public void AFileThatFails_IsNamed_AndRemovingTheCurrentFileLetsThePlayerGo()
{
using var session = NewSession();
string? failed = null;
session.Failed += (_, e) => failed = e.File;
session.Add([@"C:\Music\broken.mp3", @"C:\Music\fine.mp3"], play: true);
_engine.Players[0].Raise(OdMediaState.Failed);
Assert.Equal("broken.mp3", failed);
session.RemoveAt(0);
Assert.True(_engine.Players[0].Disposed);
Assert.Equal(@"C:\Music\fine.mp3", session.Queue.CurrentItem);
session.Clear();
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()
{
Assert.False(OdVlcLog.Keep("main libvlc: option quiet does not exist"));
Assert.False(OdVlcLog.Keep("direct3d11: SetThumbNailClip failed: 0x800706f4"));
Assert.False(OdVlcLog.Keep("avcodec decoder: Not enough decoding slices"));
Assert.True(OdVlcLog.Keep("filesystem: cannot open file"));
}
[Fact]
public void TheScreen_ShowsTheQueueAndTheTime_AndKeepsTheVolume() => OdSta.Run(() =>
{
using var session = NewSession();
OdMediaSettings? saved = null;
var folder = Directory.CreateDirectory(_temp.Combine("album")).FullName;
File.WriteAllText(Path.Combine(folder, "02 b.mp3"), "");
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, TimeProvider.System);
Assert.Equal("Nothing to play yet", screen.Title);
screen.Add([folder, playlist, _temp.Combine("notes.txt")]);
Assert.Equal(new[] { "01 a", "02 b", "c" }, screen.Items.Select(item => item.Title), StringComparer.Ordinal);
Assert.True(screen.Items[0].IsCurrent);
Assert.Equal("01 a", screen.Title);
Assert.True(screen.IsPlaying);
Assert.Equal(30, _engine.Players[0].Volume);
var player = _engine.Players[0];
player.Length = TimeSpan.FromMinutes(3);
player.Time = TimeSpan.FromSeconds(65);
player.Raise(OdMediaState.Playing);
Assert.Equal("1:05 / 3:00", screen.TimeText);
Assert.False(screen.ShowsVideo);
player.HasVideo = true;
player.Raise(OdMediaState.Playing);
Assert.True(screen.ShowsVideo);
Assert.Equal(180, screen.Length);
screen.Position = 90;
Assert.Equal("seek 90", player.Calls[^1]);
screen.Volume = 55;
Assert.Equal(55, saved?.Volume);
screen.ToggleQueueCommand.Execute(null);
Assert.False(saved?.QueueVisible);
screen.Add([_temp.Combine("notes.txt")]);
Assert.Equal("None of those are files the player can open.", screen.Message);
Assert.Equal("1:01:01", OdMediaViewModel.Clock(new TimeSpan(1, 1, 1)));
return Task.CompletedTask;
});
[Fact]
public void TheModule_IsPinnedWhilePlaying_AndLetsLibVlcGoWhenHibernated() => OdSta.Run(async () =>
{
var module = new OdMediaModule(_ => _engine);
var time = new FakeTimeProvider(new DateTimeOffset(2026, 11, 2, 3, 0, 0, TimeSpan.Zero));
using var host = new OdModuleHost([module, new OdFakeModule("clock")], _database, Logger.None, time, new OdFakeNotifier(), OdTestHttp.Client);
await host.ShowAsync("media");
module.Session!.Add(["one.mp3"], play: true);
await host.ShowAsync("clock");
Assert.False(await host.HibernateAsync("media"));
Assert.False(_engine.Disposed);
module.Session.Toggle();
Assert.True(await host.SuspendAsync("media", OdSuspendReason.Hidden));
Assert.True(_engine.Players[0].Disposed);
Assert.False(_engine.Disposed);
Assert.True(await host.HibernateAsync("media"));
Assert.True(_engine.Disposed);
Assert.Equal(OdRamClass.Heavy, module.Info.RamClass);
});
private OdMediaSession NewSession() => new(new OdMediaStore(_database), _engine.CreatePlayer, Logger.None);
private sealed class OdFakeMediaEngine : IOdMediaEngine
{
public List<OdFakeMediaPlayer> Players { get; } = [];
public bool Disposed { get; private set; }
public IOdMediaPlayer CreatePlayer()
{
var player = new OdFakeMediaPlayer();
Players.Add(player);
return player;
}
public void Dispose() => Disposed = true;
}
private sealed class OdFakeMediaPlayer : IOdMediaPlayer
{
public event EventHandler? StateChanged;
public event EventHandler? TimeChanged;
public List<string> Calls { get; } = [];
public OdMediaState State { get; private set; }
public TimeSpan Time { get; set; }
public TimeSpan Length { get; set; }
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, OdMediaOpening opening)
{
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");
Raise(OdMediaState.Playing);
}
public void Pause()
{
Calls.Add("pause");
Raise(OdMediaState.Paused);
}
public void Stop()
{
Calls.Add("stop");
Raise(OdMediaState.Stopped);
}
public void Seek(TimeSpan time)
{
Calls.Add(string.Create(CultureInfo.InvariantCulture, $"seek {time.TotalSeconds}"));
Time = time;
TimeChanged?.Invoke(this, EventArgs.Empty);
}
public void Raise(OdMediaState state)
{
State = state;
StateChanged?.Invoke(this, EventArgs.Empty);
}
public void Dispose() => Disposed = true;
}
}
@@ -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()
{
@@ -24,7 +24,7 @@ public sealed class OdDatabaseTests
var versions = OdCoreMigrations.All.Select(m => m.Version).ToList();
Assert.Equal(Enumerable.Range(1, versions.Count), versions);
Assert.Equal(new[] { "app_meta", "module_settings", "weather_cache", "calendar_events" }, OdCoreMigrations.All.Select(m => m.Name), StringComparer.Ordinal);
Assert.Equal(new[] { "app_meta", "module_settings", "weather_cache", "calendar_events", "media_playlists" }, OdCoreMigrations.All.Select(m => m.Name), StringComparer.Ordinal);
}
[Fact]
+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]
@@ -1,4 +1,8 @@
using OmniDeck.Core.Governor;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
using OmniDeck.Web.Runtime;
using Serilog.Core;
namespace OmniDeck.Tests.Web;
@@ -32,6 +36,18 @@ public sealed class OdWebMemoryTests
Assert.Equal(sizes.Values.Sum(), report.SharedBytes + report.Modules.Values.Sum());
}
[Fact]
public async Task BeforeAnyWebAppOpens_ThereIsNothingToReport()
{
using var temp = new OdTempDirectory();
var runtime = new OdWebRuntime(new OdDataRoot(temp.Path), new OdWebOptions(), Logger.None);
var report = await new OdWebMemoryReporter(runtime, Logger.None).ReportAsync();
Assert.Same(OdMemoryReport.None, report);
Assert.Null(runtime.Current);
}
[Fact]
public void AHostTwoAppsShow_IsLeftShared_AndOpenAppsStillGetAFigure()
{
+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)]