Compare commits

...
Author SHA1 Message Date
poli0981andClaude Opus 5.5 944e45950a ci: build Core before dotnet format loads the app's XAML
The window XAML now resolves {res:OdLoc ...} from OmniDeck.Core. dotnet
format runs before the build, so the markup compiler found no Core
assembly, the windows lost their generated base class and fields, and
the analyzers flagged code that compiles fine (IDE0060, S2325, S1125).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:55:07 +07:00
poli0981 bc44fa5554 Merge remote-tracking branch 'origin/main' into feat/p1-shell 2026-10-30 15:38:38 +07:00
poli0981andClaude Opus 5.5 b11568d6bb feat: add the shell, the module contract and host, the palette and the tray
P1 WP4. The module contract from docs/ARCHITECTURE.md §2 lands in Core,
which now takes the WPF dependency, together with OdModuleHost: it
initializes a module once, builds its view on first open and after
hibernation, keeps the visible one and demotes hidden ones on request,
refusing when CanSuspendAsync says no. Each module gets its own settings
document in the new module_settings table.

The shell window is rebuilt around it. The navigation view is chrome
only: pinned modules, then open ones, then the library page; every
module item navigates to one shared stage whose content the host
supplies. Ctrl+K (or the title-bar search box) opens a fuzzy command
palette over modules and shell commands. Closing the window hides it in
the tray (H.NotifyIcon), whose balloons carry module notifications; a
second launch brings it back. Errors now show in an in-window dialog.

UI strings move to Resources/Strings.resx behind OdLocalization and
{res:OdLoc Key}, which live in Core so modules can use them too; a test
keeps the string table and the sources in step. The theme engine now
re-applies the look only when an appearance setting changes.

Third-party notices list CommunityToolkit.Mvvm and H.NotifyIcon, as
approved for P1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 15:38:37 +07:00
poli0981 196538d62d Merge pull request #22 from poli0981/feat/p1-theme
feat: add the theme engine and the Od.* preset tokens (WP3)
2026-10-30 15:00:01 +07:00
poli0981 1567bcae25 Merge remote-tracking branch 'origin/main' into feat/p1-theme 2026-10-30 14:56:58 +07:00
poli0981andClaude Opus 5.5 3ea5a1c665 feat: add the theme engine and the Od.* preset tokens
The theme engine follows docs/UI-MODES.md and spike #5:

- Core: OdPreset holds the UI-MODES §2 token table (Dynamic, Standard,
  Comfort). OdTokens.Compute applies the user's font scale
  (0.85–1.4), the Windows text size (up to 225%) and the motion switch
  as plain, tested arithmetic. OdTokenKeys names the Od.* resource
  keys. Settings gain FontScale, MotionEnabled and AccentColor, all
  normalized.
- App: OdThemeEngine runs two independent axes.
  - Light/Dark/System goes through WPF-UI's ApplicationThemeManager;
    High Contrast follows the system, and an optional accent color
    applies.
  - The preset layer is a code-built ResourceDictionary, replaced in
    place whenever the settings, the Windows text size (registry,
    re-read on WM_SETTINGCHANGE and window activation) or user
    preferences change.
  - OdStyles.xaml adds implicit styles where WPF-UI 4.3 reads sizes
    through StaticResource. Keys it reads dynamically are overridden
    in the preset layer.
  - OdMotion runs token-driven animation from code, since a style
    storyboard cannot take a DynamicResource.
- Tests: preset values against the table, heading scale, the
  multiplication and clamping of text and font scale, motion off,
  preset fallback, settings normalization, the published resource
  types, in-place replacement and the registry text-scale parsing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:56:45 +07:00
poli0981 4181d9d754 Merge pull request #21 from poli0981/feat/p1-storage
feat: add the local database and schema migrations (WP2)
2026-10-30 14:56:39 +07:00
poli0981andClaude Opus 5.5 769756c060 test: cover logging and crash handling
SonarCloud put WP1's new-code coverage at 76.9%: the logger setup and
the crash handler had no tests. The crash handler now takes an
IOdErrorPresenter (a message box until the shell's dialog host lands
in WP4) and a TimeProvider. Its UI, fatal and unobserved paths are
plain methods that tests can call without a WPF Application.

New tests: the logger writes daily files under the data root; a UI
failure is logged and shown with its support code; a failure while
the dialog is showing is logged but not stacked; fatal and unobserved
exceptions are logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:52:39 +07:00
poli0981 2b84a874d0 Merge remote-tracking branch 'origin/main' into feat/p1-storage 2026-10-30 14:51:09 +07:00
poli0981 3a481b9ad6 Merge pull request #20 from poli0981/feat/p1-foundation
feat: lay the P1 foundation (WP1)
2026-10-30 14:50:39 +07:00
poli0981andClaude Opus 5.5 ff4378c701 docs: list Dapper and SQLite in the third-party notices
Dapper, Microsoft.Data.Sqlite, SQLitePCLRaw and the public-domain
SQLite library now ship in the app, so they move from planned to
bundled with their versions and copyright notices. Approved by the
maintainer for the P1 packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:50:05 +07:00
poli0981andClaude Opus 5.5 2ab2fba933 feat: add the local database and schema migrations
OdDatabase opens omnideck.db in the data root (SQLite through Dapper,
WAL journal, foreign keys on) and brings the schema up to date at
startup. Migrations are SQL files embedded in Core and named
NNNN_name.sql. Each applies once, in order, inside its own
transaction, and app_meta records the version. A failing step rolls
back and leaves the version where it was.

app_meta holds app-wide facts behind IOdAppMeta; the legal-gate
acknowledgment keys are already defined. Pools are cleared on exit, so
the database file is released.

Tests: version 0 when empty, contiguous core versions, each step
applied once, rollback on failure, duplicate versions rejected, and
app_meta set and overwrite.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:50:04 +07:00
poli0981andClaude Opus 5.5 05a9def6b4 docs: list DI and Serilog in the third-party notices
Microsoft.Extensions.DependencyInjection (+ .Abstractions) and Serilog
with Serilog.Sinks.File now ship in the app, so they move from planned
to bundled. The Apache License 2.0 text joins the license section for
Serilog. The maintainer approved notice updates for the P1 packages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:46:54 +07:00
poli0981andClaude Opus 5.5 7f14eb8f07 feat: lay the P1 foundation
- Startup: Program.Main runs Velopack's hooks first. Uninstalling now
  deletes %LocalAppData%\OmniDeck.Data, as PRIVACY promises. A
  single-instance guard follows (named mutex plus an activation event):
  a second OmniDeck brings the first one forward and exits. OdApp then
  builds the data root, the logger and the service container
  (ValidateOnBuild), and shows the window. OdApp.xaml is now a plain
  page, so WPF no longer generates a Main of its own.
- Core:
  - OdDataRoot, which refuses to point at Velopack's install folder;
  - OdJsonFile: atomic writes, and corrupt files set aside;
  - OdSettings (an immutable record with source-generated JSON) behind
    IOdSettingsService;
  - OdSingleInstanceGuard;
  - AddOmniDeckCore.
- App:
  - Serilog to rolling files in the data root, kept for seven days;
  - OdCrashHandler, which logs every unhandled exception and shows a
    support code for UI-thread failures while the app keeps running;
  - AddOmniDeckApp.
- Tests: data root, JSON file, settings, the single-instance guard,
  container validation, the Core-must-not-reference-the-shell rule, and
  support codes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:46:53 +07:00
poli0981 e551838319 Merge pull request #19 from poli0981/docs/legal-1.1
docs: legal documents 1.1, without Stooq and Messenger
2026-10-30 14:34:59 +07:00
poli0981 e5c80d41e8 Merge remote-tracking branch 'origin/main' into docs/legal-1.1 2026-10-30 14:31:29 +07:00
poli0981 5813e2dd82 Merge pull request #18 from poli0981/docs/p0-exit
docs: fold the P0 spike results into the design docs
2026-10-30 14:31:24 +07:00
poli0981andClaude Opus 5.5 c63b5da92b docs: legal documents 1.1, without Stooq and Messenger
The maintainer approved these edits (rule 9 of CLAUDE.md).

- EULA, DISCLAIMER, PRIVACY: version 1.1, effective from the first
  release after 0.0.1-alpha.1, with a one-line note of what changed.
- PRIVACY: the network list names only Twelve Data, contacted only
  after the user enters their own API key.
- DISCLAIMER: market data comes from Twelve Data with the user's key;
  Messenger is gone from the list of web apps.
- EULA: Stooq is gone from the example data services.
- THIRD-PARTY-NOTICES: the Stooq row is removed, the Twelve Data row
  says what it provides, and Messenger is gone from the catalog list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 14:24:20 +07:00
106 changed files with 5106 additions and 54 deletions

No files matched your search

+8
View File
@@ -54,3 +54,11 @@ dotnet_diagnostic.MA0026.severity = suggestion # TODO comments: SonarCloud (S113
[src/OmniDeck.App/**.cs]
# UI code must resume on the dispatcher thread, so ConfigureAwait(false) is wrong here.
dotnet_diagnostic.MA0004.severity = none
[src/OmniDeck.Core/Modules/**.cs]
# The module host drives module views from the dispatcher thread as well.
dotnet_diagnostic.MA0004.severity = none
[tests/**.cs]
# Tests await on the STA dispatcher (OdSta) or in xUnit's own context; xUnit1030 forbids ConfigureAwait(false) there.
dotnet_diagnostic.MA0004.severity = none
+6
View File
@@ -51,6 +51,12 @@ jobs:
- name: Restore pinned tools
run: dotnet tool restore
# dotnet format loads the app with the XAML markup compiler, which needs OmniDeck.Core.dll on
# disk to resolve {res:OdLoc ...}; without it the window classes lose their generated half and
# the analyzers report phantom findings.
- name: Build Core for the XAML compiler
run: dotnet build src/OmniDeck.Core/OmniDeck.Core.csproj --no-restore
- name: Verify C# formatting
run: dotnet format OmniDeck.slnx --verify-no-changes --no-restore
+17
View File
@@ -6,10 +6,27 @@ All notable changes to OmniDeck are documented here. The format follows
## [Unreleased]
### Added
- One OmniDeck per Windows session: starting it again brings the running window to the front.
- Settings stored in `%LocalAppData%\OmniDeck.Data\settings.json`, written atomically. A damaged
file is set aside and defaults take over.
- Local log files in `%LocalAppData%\OmniDeck.Data\logs`, kept for seven days, plus crash handling
that shows a support code and keeps OmniDeck running.
- Uninstalling removes `%LocalAppData%\OmniDeck.Data`, as the privacy policy promises.
- A local database, `%LocalAppData%\OmniDeck.Data\omnideck.db`, with a versioned schema that
upgrades itself at startup.
- The window follows Windows: light or dark mode, the accent color, High Contrast and the text size.
- The shell: a sidebar with pinned and open modules, a module library to open and pin them from,
and a command palette (Ctrl+K, or the search box in the title bar) that finds modules and commands.
- Closing the window keeps OmniDeck running in the notification area; its icon's menu opens or quits
it. Modules can raise Windows notifications from there.
### Changed
- Stocks: Twelve Data with the user's own API key is now the only provider. Stooq was dropped because
its download endpoints now block scripted clients (P0 spike #7). The free Twelve Data plan covers US
listings; home-market EU listings and indices need a paid plan.
- Legal documents (EULA, disclaimer, privacy policy) are now version 1.1, and the third-party notices
follow: Stooq and Messenger are no longer mentioned.
### Removed
- Messenger from the web app catalog: Meta closed messenger.com on 15 April 2026 and sends web
+5 -3
View File
@@ -44,7 +44,7 @@ public enum OdModuleState { Created, Active, Idle, Suspended, Hibernated, Closed
public interface IOdModule
{
OdModuleInfo Info { get; } // Id, Name, Icon, Category, RamClass
OdModuleInfo Info { get; } // Id, NameKey, Icon, CategoryKey, RamClass
FrameworkElement CreateView(); // called on Activate after hibernation
Task InitializeAsync(IOdModuleContext ctx); // once per process lifetime
Task ActivateAsync(); // became visible
@@ -55,9 +55,11 @@ public interface IOdModule
}
```
`IOdModuleContext` gives modules storage (scoped SQLite access + settings section), the toast service, logger, and the HTTP client factory — modules never construct these themselves.
`IOdModuleContext` gives modules their own settings document (one JSON row per module in the `module_settings` table), the notifier (tray balloons, which Windows 11 shows as toasts), a logger and the clock; the HTTP client factory joins it with the first module that goes online (P2). Modules never construct these themselves.
`CreateView()` returns a WPF `FrameworkElement`, so wherever `IOdModule` lives must reference WPF. P1 decides between letting `OmniDeck.Core` take that dependency (it already targets `net10.0-windows`) and moving the contract into a small WPF-aware abstractions project.
`CreateView()` returns a WPF `FrameworkElement`, so wherever `IOdModule` lives must reference WPF. P1 decided to let `OmniDeck.Core` take that dependency (`UseWPF`) rather than add an abstractions project. Core holds the contract, `OdModuleHost` and the localization layer (`OdLocalization`, `{res:OdLoc Key}`), so modules depend on Core alone; Core still never references the app, Velopack or WPF-UI (an architecture test checks it), which is why `OdModuleInfo.Icon` is a `SymbolRegular` name rather than a symbol.
`OdModuleHost` runs the contract. It initializes a module on first open, builds its view when it has none (first open, or after hibernation), keeps the view of the visible module, and moves hidden ones down the ladder when the shell or the governor asks; it refuses to suspend or hibernate a module whose `CanSuspendAsync` returns false. Calls run one at a time on the UI thread. The shell's navigation view is chrome only: every module item navigates to one shared stage page, whose content is the view the host hands back, so the control never creates or caches module views.
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 -3
View File
@@ -1,6 +1,6 @@
# OmniDeck — Disclaimer
Version 1.0 — effective from the first public release (0.0.1-alpha.1).
Version 1.1 — effective from the first release after 0.0.1-alpha.1. Changes since 1.0: the Stooq stock data service is no longer used, and Messenger is no longer in the web app catalog.
## Pre-release software
@@ -8,7 +8,7 @@ OmniDeck is pre-release (alpha/beta) software provided **as is**, without warran
## Financial data — not investment advice
The stocks module displays market data obtained from third-party providers (Stooq; optionally Twelve Data). This data may be **delayed, incomplete, or inaccurate**, and end-of-day sources are not suitable for time-sensitive decisions. Nothing displayed by OmniDeck constitutes financial, investment, legal, or tax advice, and no fitness for trading purposes is implied. Any decisions you make based on this data are entirely your own responsibility. Verify figures with your broker or an official exchange source before acting.
The stocks module displays market data obtained from a third-party provider (Twelve Data, using your own API key). This data may be **delayed, incomplete, or inaccurate**, and it is not suitable for time-sensitive decisions. Nothing displayed by OmniDeck constitutes financial, investment, legal, or tax advice, and no fitness for trading purposes is implied. Any decisions you make based on this data are entirely your own responsibility. Verify figures with your broker or an official exchange source before acting.
## Weather data
@@ -16,7 +16,7 @@ Weather information comes from Open-Meteo and is provided for general planning o
## Third-party web applications and services
Web apps accessible through OmniDeck (Spotify, Discord, YouTube, Google services, Facebook, Messenger, and others in the catalog) are operated entirely by their respective providers. Their availability, functionality, sign-in behavior, and content may change or cease at any time without notice, and some capabilities differ from those providers' native desktop apps (documented in the README). OmniDeck has no control over, and assumes no responsibility for, those services or their content. Your use of them is subject to their own terms.
Web apps accessible through OmniDeck (Spotify, Discord, YouTube, Google services, Facebook, and others in the catalog) are operated entirely by their respective providers. Their availability, functionality, sign-in behavior, and content may change or cease at any time without notice, and some capabilities differ from those providers' native desktop apps (documented in the README). OmniDeck has no control over, and assumes no responsibility for, those services or their content. Your use of them is subject to their own terms.
## Trademarks
+2 -2
View File
@@ -1,6 +1,6 @@
# OmniDeck — End User License Agreement (EULA)
Version 1.0 — effective from the first public release (0.0.1-alpha.1).
Version 1.1 — effective from the first release after 0.0.1-alpha.1. Changes since 1.0: the Stooq stock data service is no longer used, and Messenger is no longer in the web app catalog.
By installing or using OmniDeck ("the Software"), you acknowledge the terms below. If you do not agree with them, do not install or use the Software.
@@ -10,7 +10,7 @@ The Software is free software licensed under the **GNU General Public License v3
## 2. Third-party components and services
The Software bundles third-party components (such as the .NET runtime, WPF-UI, Velopack and, in later versions, libVLC) that are governed by their own licenses, listed in THIRD-PARTY-NOTICES.md. It relies on the Microsoft Edge WebView2 Runtime that ships with Windows 11; the runtime is not bundled with the Software and is governed by Microsoft's license terms. The Software also loads third-party **web applications and data services** (e.g., Spotify, Discord, Google services, Open-Meteo, Stooq, Twelve Data). Your use of those services is governed solely by their own terms of service and privacy policies; you are responsible for complying with them. OmniDeck is not affiliated with, endorsed by, or sponsored by any of these providers, and their trademarks belong to their respective owners.
The Software bundles third-party components (such as the .NET runtime, WPF-UI, Velopack and, in later versions, libVLC) that are governed by their own licenses, listed in THIRD-PARTY-NOTICES.md. It relies on the Microsoft Edge WebView2 Runtime that ships with Windows 11; the runtime is not bundled with the Software and is governed by Microsoft's license terms. The Software also loads third-party **web applications and data services** (e.g., Spotify, Discord, Google services, Open-Meteo, Twelve Data). Your use of those services is governed solely by their own terms of service and privacy policies; you are responsible for complying with them. OmniDeck is not affiliated with, endorsed by, or sponsored by any of these providers, and their trademarks belong to their respective owners.
## 3. Your responsibilities
+2 -2
View File
@@ -1,6 +1,6 @@
# OmniDeck — Privacy Policy
Version 1.0 — effective from the first public release (0.0.1-alpha.1).
Version 1.1 — effective from the first release after 0.0.1-alpha.1. Changes since 1.0: the Stooq stock data service is no longer used, and Messenger is no longer in the web app catalog.
**Short version: OmniDeck collects nothing.** There is no telemetry, no analytics, no account, no crash auto-upload, and no server operated by the OmniDeck project that receives your data.
@@ -21,7 +21,7 @@ The app itself is installed separately, in `%LocalAppData%\OmniDeck`. Uninstalli
OmniDeck only talks to the internet for the features you use:
- **Open-Meteo** — weather forecasts and geocoding for your saved locations.
- **Stooq** and (only if you configure a key) **Twelve Data** — stock quotes for tickers on your watchlist.
- **Twelve Data**, only after you enter your own API key: stock quotes, price history and symbol search for the stocks module.
- **GitHub** — update checks/downloads (Velopack) and the daily web-app catalog refresh; opening a pre-filled bug-report issue happens in your browser and only if you choose to.
- **Microsoft Edge WebView2 Runtime** — the Microsoft component that renders the web apps may contact Microsoft services on its own, for example Microsoft Defender SmartScreen reputation checks for the pages you visit and the runtime's own updates and diagnostic data. That traffic is governed by Microsoft's privacy statement and your Windows diagnostic-data settings; OmniDeck does not enable any additional reporting.
- **The third-party web apps you open** (Spotify, Discord, Google services, Facebook, etc.) — these connections go directly from your device to those providers. Their handling of your data is governed by **their** privacy policies, not this one. OmniDeck does not inject analytics into, read the contents of, or proxy these sessions.
+206 -10
View File
@@ -13,17 +13,19 @@ OmniDeck is licensed under GPL-3.0. This file lists the third-party components O
| WPF-UI + WPF-UI.Abstractions (lepoco) | 4.3.0 | MIT | Fluent controls and theme |
| Fluent UI System Icons (inside WPF-UI) | — | MIT | icon font |
| Velopack | 1.2.161 | MIT | installer & updates |
| Microsoft.Extensions.DependencyInjection (+ .Abstractions) | 10.0.14 | MIT | dependency injection |
| CommunityToolkit.Mvvm | 8.4.2 | MIT | MVVM infrastructure |
| H.NotifyIcon.Wpf + H.NotifyIcon + H.GeneratedIcons.System.Drawing | 2.4.1 | MIT | tray icon and notifications |
| Serilog + Serilog.Sinks.File | 4.4.0 / 7.0.0 | Apache-2.0 | logging to local files |
| Dapper | 2.1.89 | Apache-2.0 | data access |
| Microsoft.Data.Sqlite (+ .Core) | 10.0.14 | MIT | SQLite provider |
| SQLitePCLRaw (bundle_e_sqlite3, core, provider.e_sqlite3, lib.e_sqlite3) | 2.1.13 | Apache-2.0 | SQLite bindings |
| SQLite (the `e_sqlite3` native library) | bundled with SQLitePCLRaw 2.1.13 | public domain | local database engine |
## 2. Planned components (bundled from the version that introduces them)
| Component | License | Role | Phase |
|---|---|---|---|
| CommunityToolkit.Mvvm | MIT | MVVM infrastructure | P1 |
| Microsoft.Extensions.DependencyInjection | MIT | dependency injection | P1 |
| Serilog + Serilog.Sinks.File | Apache-2.0 | logging | P1 |
| Dapper | Apache-2.0 | data access | P1 |
| Microsoft.Data.Sqlite / SQLitePCLRaw / e_sqlite3 (SQLite) | MIT / Apache-2.0 / public domain | local database | P1 |
| H.NotifyIcon.Wpf | MIT | tray icon | P1 |
| Microsoft.Web.WebView2 (SDK) | BSD-3-Clause (Microsoft) | web app engine bindings | P2 |
| Ical.Net (+ NodaTime) | MIT (+ Apache-2.0) | iCalendar import/export | P2 |
| LibVLCSharp.WPF | LGPL-2.1-or-later | media bindings | P2 |
@@ -42,24 +44,27 @@ libVLC note: once the media player ships, OmniDeck redistributes libVLC binaries
| Service | Terms | Use |
|---|---|---|
| Open-Meteo | open API; attribution appreciated, non-commercial free tier | weather & geocoding — "Weather data by Open-Meteo.com" shown in the module footer |
| Stooq | free quotes per stooq.com terms | default EOD stock data |
| Twelve Data | user's own API key under Twelve Data's terms | optional intraday stock data |
| Twelve Data | user's own API key under Twelve Data's terms | stock quotes, price history and symbol search (only with the user's key) |
| GitHub | GitHub Terms of Service | releases, catalog refresh, issues |
## 5. Third-party web applications
Web apps in the catalog (Spotify, Discord, YouTube, Gmail, Google Calendar, Google Drive, Google Maps, Facebook, Messenger) are loaded from their providers' own servers and are not components of OmniDeck. All associated trademarks belong to their respective owners; see DISCLAIMER.md.
Web apps in the catalog (Spotify, Discord, YouTube, Gmail, Google Calendar, Google Drive, Google Maps, Facebook) are loaded from their providers' own servers and are not components of OmniDeck. All associated trademarks belong to their respective owners; see DISCLAIMER.md.
## 6. License texts
### MIT License
Applies to the components in §1, with these copyright notices:
Applies to the MIT-licensed components in §1, with these copyright notices:
- .NET runtime and Windows Desktop runtime (WPF): Copyright (c) .NET Foundation and Contributors
- WPF-UI and WPF-UI.Abstractions: Copyright (C) 2021-2026 Leszek Pomianowski and WPF UI Contributors
- Fluent UI System Icons: Copyright (c) 2020 Microsoft Corporation
- Velopack: Copyright © 2021 Caelan Sayler; Copyright © 2024 Velopack Ltd.
- Microsoft.Extensions.DependencyInjection and .Abstractions: Copyright (c) .NET Foundation and Contributors
- Microsoft.Data.Sqlite and Microsoft.Data.Sqlite.Core: Copyright (c) .NET Foundation and Contributors
- CommunityToolkit.Mvvm: Copyright © .NET Foundation and Contributors
- H.NotifyIcon, H.NotifyIcon.Wpf and H.GeneratedIcons.System.Drawing: Copyright (c) 2020 havendv; they continue Hardcodet NotifyIcon for WPF, Copyright (c) Philipp Sumi (MIT)
```
Permission is hereby granted, free of charge, to any person obtaining a copy
@@ -83,6 +88,197 @@ SOFTWARE.
The .NET runtime's full license and third-party notices: `legal\Microsoft.NETCore.App\LICENSE.TXT`, `legal\Microsoft.NETCore.App\THIRD-PARTY-NOTICES.TXT`, and `legal\Microsoft.WindowsDesktop.App\LICENSE` in the app folder.
### Apache License 2.0
Applies to these components in §1, with their copyright notices:
- Serilog and Serilog.Sinks.File: Copyright © Serilog Contributors
- Dapper: Copyright © 2019 Stack Exchange, Inc.
- SQLitePCLRaw: Copyright 2014-2024 SourceGear, LLC
```
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
```
### 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).
## Contact
Licensing or attribution concerns: copyright@poli0981.dev.
@@ -0,0 +1,32 @@
using Microsoft.Extensions.DependencyInjection;
using OmniDeck.App.Diagnostics;
using OmniDeck.App.Shell;
using OmniDeck.App.Theming;
using OmniDeck.Core.Modules;
using Wpf.Ui;
namespace OmniDeck.App.Composition;
/// <summary>Registers the WPF shell's services on top of <c>AddOmniDeckCore</c>.</summary>
internal static class OdAppServiceCollectionExtensions
{
public static IServiceCollection AddOmniDeckApp(this IServiceCollection services)
{
// WPF-UI's dialog and snackbar services; the main window hands them their hosts.
services.AddSingleton<IContentDialogService, ContentDialogService>();
services.AddSingleton<ISnackbarService, SnackbarService>();
services.AddSingleton<OdDialogs>();
services.AddSingleton<OdMessageBoxErrorPresenter>();
services.AddSingleton<IOdErrorPresenter, OdDialogErrorPresenter>();
services.AddSingleton<OdCrashHandler>();
services.AddSingleton<OdThemeEngine>();
services.AddSingleton<OdTrayNotifier>();
services.AddSingleton<IOdNotifier>(provider => provider.GetRequiredService<OdTrayNotifier>());
services.AddSingleton<IOdAppLifetime, OdAppLifetime>();
services.AddSingleton<OdShellViewModel>();
services.AddSingleton<OdMainWindow>();
return services;
}
}
@@ -0,0 +1,7 @@
namespace OmniDeck.App.Diagnostics;
/// <summary>Shows the user that something failed; the shell swaps in an in-window dialog in WP4.</summary>
internal interface IOdErrorPresenter
{
void Show(string message);
}
@@ -0,0 +1,86 @@
using System.Globalization;
using System.Windows;
using OmniDeck.Core.Localization;
using Serilog;
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Global failure handling (docs/ARCHITECTURE.md §6): every unhandled exception is logged; one on the
/// UI thread is shown with a support code that matches the log entry, and OmniDeck keeps running.
/// The bug-report flow (P2) hangs off the same dialog.
/// </summary>
internal sealed class OdCrashHandler
{
private readonly ILogger _log;
private readonly IOdErrorPresenter _presenter;
private readonly TimeProvider _time;
private int _showing;
public OdCrashHandler(ILogger log, IOdErrorPresenter presenter, TimeProvider time)
{
_log = log.ForContext<OdCrashHandler>();
_presenter = presenter;
_time = time;
}
public void Hook(Application app)
{
app.DispatcherUnhandledException += (_, e) =>
{
HandleUiException(e.Exception);
e.Handled = true;
};
AppDomain.CurrentDomain.UnhandledException += (_, e) => HandleFatal(e.ExceptionObject as Exception, e.IsTerminating);
TaskScheduler.UnobservedTaskException += (_, e) =>
{
HandleUnobserved(e.Exception);
e.SetObserved();
};
}
/// <summary>A short code the user can quote; it is logged next to the exception.</summary>
internal static string SupportCode(Exception exception, DateTimeOffset when)
{
// FNV-1a over the exception type and message: stable for the same failure, cheap, and free of
// anything personal.
var hash = 2166136261u;
foreach (var c in exception.GetType().FullName + exception.Message)
{
hash = (hash ^ c) * 16777619u;
}
return string.Create(CultureInfo.InvariantCulture, $"{when:yyMMdd-HHmm}-{hash % 0x10000:X4}");
}
/// <summary>A UI-thread failure: logged, shown with its support code; the app keeps running.</summary>
/// <returns>The support code.</returns>
internal string HandleUiException(Exception exception)
{
var code = SupportCode(exception, _time.GetLocalNow());
_log.Error(exception, "Unhandled UI exception, support code {SupportCode}", code);
// A failure inside the dialog itself must not stack dialogs.
if (Interlocked.Exchange(ref _showing, 1) == 0)
{
try
{
_presenter.Show(OdLocalization.Format("Error_UiMessage", code, exception.Message));
}
finally
{
Volatile.Write(ref _showing, 0);
}
}
return code;
}
internal void HandleFatal(Exception? exception, bool terminating)
{
_log.Fatal(exception, "Unhandled exception (terminating: {Terminating})", terminating);
Log.CloseAndFlush();
}
internal void HandleUnobserved(Exception exception) => _log.Error(exception, "Unobserved task exception");
}
@@ -0,0 +1,26 @@
using OmniDeck.App.Shell;
using OmniDeck.Core.Localization;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Diagnostics;
/// <summary>Shows errors in an in-window dialog, or in a message box while no dialog can show.</summary>
internal sealed class OdDialogErrorPresenter(OdDialogs dialogs, OdMessageBoxErrorPresenter fallback) : IOdErrorPresenter
{
public void Show(string message)
{
if (!dialogs.CanShow)
{
fallback.Show(message);
return;
}
_ = dialogs.ShowAsync(new ContentDialog
{
Title = OdLocalization.Get("Error_Title"),
Content = message,
CloseButtonText = OdLocalization.Get("Dialog_OK"),
DefaultButton = ContentDialogButton.Close,
});
}
}
+33
View File
@@ -0,0 +1,33 @@
using OmniDeck.Core.Storage;
using Serilog;
using Serilog.Events;
namespace OmniDeck.App.Diagnostics;
/// <summary>
/// Serilog to rolling files under the data root's <c>logs\</c> folder, kept for seven days
/// (docs/SPEC.md §5). Nothing leaves the machine; bug reports attach a tail of these files only when
/// the user asks for one.
/// </summary>
internal static class OdLogging
{
private const string Template = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {SourceContext}: {Message:lj}{NewLine}{Exception}";
public static ILogger CreateLogger(OdDataRoot dataRoot) =>
new LoggerConfiguration()
#if DEBUG
.MinimumLevel.Debug()
#else
.MinimumLevel.Information()
#endif
.MinimumLevel.Override("System", LogEventLevel.Warning)
.WriteTo.File(
System.IO.Path.Combine(dataRoot.LogsDirectory, "omnideck-.log"),
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 7,
fileSizeLimitBytes: 10 * 1024 * 1024,
rollOnFileSizeLimit: true,
outputTemplate: Template,
formatProvider: System.Globalization.CultureInfo.InvariantCulture)
.CreateLogger();
}
@@ -0,0 +1,10 @@
using System.Windows;
namespace OmniDeck.App.Diagnostics;
/// <summary>The fallback presenter: a plain message box, which works before any window exists.</summary>
internal sealed class OdMessageBoxErrorPresenter : IOdErrorPresenter
{
public void Show(string message) =>
MessageBox.Show(message, "OmniDeck", MessageBoxButton.OK, MessageBoxImage.Warning);
}
+3 -3
View File
@@ -1,14 +1,14 @@
<Application x:Class="OmniDeck.App.OdApp"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
StartupUri="OdMainWindow.xaml">
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<!-- WPF-UI dictionaries first; the Od.* preset layer goes on top in P1 (docs/UI-MODES.md). -->
<!-- WPF-UI dictionaries first, then our implicit styles; OdThemeEngine adds the Od.* preset layer last (docs/UI-MODES.md). -->
<ui:ThemesDictionary Theme="Dark" />
<ui:ControlsDictionary />
<ResourceDictionary Source="Theming/OdStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
+103
View File
@@ -0,0 +1,103 @@
using System.Windows;
using Microsoft.Extensions.DependencyInjection;
using OmniDeck.App.Composition;
using OmniDeck.App.Diagnostics;
using OmniDeck.App.Resources;
using OmniDeck.App.Shell;
using OmniDeck.App.Theming;
using OmniDeck.Core;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Runtime;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using Serilog;
namespace OmniDeck.App;
/// <summary>
/// The WPF application: builds the data root, the logger and the service container, hooks crash
/// handling, then shows the main window. Shutdown is explicit because the tray keeps OmniDeck
/// running after its window closes.
/// </summary>
public partial class OdApp
{
private readonly OdSingleInstanceGuard _guard;
private ServiceProvider? _services;
internal OdApp(OdSingleInstanceGuard guard)
{
_guard = guard;
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
ShutdownMode = ShutdownMode.OnExplicitShutdown;
OdLocalization.Instance.Register(OdAppStrings.Resources);
try
{
Start();
}
catch (Exception ex)
{
Log.ForContext<OdApp>().Fatal(ex, "OmniDeck could not start");
MessageBox.Show(OdLocalization.Format("Error_StartFailed", ex.Message), OdLocalization.Get("App_Name"), MessageBoxButton.OK, MessageBoxImage.Error);
Shutdown(1);
}
}
protected override void OnExit(ExitEventArgs e)
{
Log.ForContext<OdApp>().Information("OmniDeck exiting with code {ExitCode}", e.ApplicationExitCode);
_services?.Dispose();
OdDatabase.ReleaseAll();
Log.CloseAndFlush();
base.OnExit(e);
}
private void Start()
{
var dataRoot = OdDataRoot.Default;
dataRoot.EnsureCreated();
Log.Logger = OdLogging.CreateLogger(dataRoot);
Log.ForContext<OdApp>().Information("OmniDeck {Version} starting", OdVersionInfo.FromAssembly(typeof(OdApp).Assembly).DisplayText);
_services = new ServiceCollection()
.AddOmniDeckCore(dataRoot, Log.Logger)
.AddOmniDeckApp()
.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true });
_services.GetRequiredService<OdCrashHandler>().Hook(this);
var applied = _services.GetRequiredService<OdDatabase>().Migrate(OdCoreMigrations.All);
Log.ForContext<OdApp>().Information("Database ready ({Applied} migrations applied)", applied);
var settings = _services.GetRequiredService<IOdSettingsService>();
OdLocalization.Instance.SetCulture(OdLocalization.Instance.ResolveCulture(settings.Current.Language));
OdLocalization.Instance.TrackWindowLanguage();
settings.Changed += (_, e) => Dispatcher.Invoke(() => OdLocalization.Instance.SetCulture(OdLocalization.Instance.ResolveCulture(e.Settings.Language)));
_services.GetRequiredService<OdThemeEngine>().Start(this);
_guard.StartListening(() => _ = Dispatcher.InvokeAsync(ShowMainWindow));
ShowMainWindow();
}
private void ShowMainWindow()
{
if (MainWindow is not OdMainWindow window)
{
window = _services!.GetRequiredService<OdMainWindow>();
MainWindow = window;
// A real close (tray off, or Quit) ends the app; otherwise closing only hides the window.
var lifetime = _services!.GetRequiredService<IOdAppLifetime>();
window.Closed += (_, _) =>
{
if (!lifetime.IsQuitting)
{
lifetime.Quit();
}
};
}
window.Present();
}
}
+75 -16
View File
@@ -1,11 +1,17 @@
<ui:FluentWindow x:Class="OmniDeck.App.OdMainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:res="clr-namespace:OmniDeck.Core.Localization;assembly=OmniDeck.Core"
xmlns:tb="clr-namespace:H.NotifyIcon;assembly=H.NotifyIcon.Wpf"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="OmniDeck"
Width="960"
Height="600"
Title="{res:OdLoc App_Name}"
Width="1100"
Height="720"
MinWidth="640"
MinHeight="420"
Closing="OnClosing"
ExtendsContentIntoTitleBar="True"
PreviewKeyDown="OnPreviewKeyDown"
WindowBackdropType="Mica"
WindowStartupLocation="CenterScreen">
<Grid>
@@ -13,18 +19,71 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TitleBar Title="OmniDeck" Grid.Row="0" />
<!-- Kickoff placeholder: the real shell (navigation, module host) arrives in P1. -->
<StackPanel Grid.Row="1"
HorizontalAlignment="Center"
VerticalAlignment="Center">
<ui:TextBlock HorizontalAlignment="Center"
FontTypography="Title"
Text="OmniDeck" />
<ui:TextBlock x:Name="VersionText"
Margin="0,8,0,0"
HorizontalAlignment="Center"
Appearance="Secondary" />
</StackPanel>
<ui:TitleBar x:Name="AppTitleBar"
Title="{res:OdLoc App_Name}"
Grid.Row="0">
<!-- Looks like a search box; opens the command palette, as Ctrl+K does. -->
<ui:TitleBar.CenterContent>
<ui:Button Width="360"
Margin="16,0,0,0"
HorizontalContentAlignment="Left"
AutomationProperties.Name="{res:OdLoc Shell_Search}"
Click="OnSearchClick"
ToolTip="Ctrl+K">
<DockPanel>
<ui:SymbolIcon Margin="0,0,8,0"
DockPanel.Dock="Left"
Symbol="Search24" />
<TextBlock VerticalAlignment="Center"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{res:OdLoc Shell_Search}"
TextTrimming="CharacterEllipsis" />
</DockPanel>
</ui:Button>
</ui:TitleBar.CenterContent>
</ui:TitleBar>
<!-- Chrome only: items are built in code from OdShellViewModel.Sidebar and every navigation goes through it. -->
<ui:NavigationView x:Name="RootNavigation"
Grid.Row="1"
FrameMargin="0"
IsBackButtonVisible="Collapsed"
IsPaneToggleVisible="True"
OpenPaneLength="240"
PaneDisplayMode="Left"
TitleBar="{Binding ElementName=AppTitleBar, Mode=OneWay}">
<ui:NavigationView.ContentOverlay>
<Grid>
<ui:SnackbarPresenter x:Name="RootSnackbar" VerticalAlignment="Bottom" />
</Grid>
</ui:NavigationView.ContentOverlay>
</ui:NavigationView>
<!-- In-window dialogs cover the whole window, title bar included. -->
<ui:ContentDialogHost x:Name="RootDialogHost"
Grid.Row="0"
Grid.RowSpan="2" />
<!-- The tray icon lives as long as this window, which closing only hides (docs/SPEC.md §2). -->
<tb:TaskbarIcon x:Name="TrayIcon"
Grid.Row="0"
NoLeftClickDelay="True"
ToolTipText="{res:OdLoc App_Name}"
TrayLeftMouseUp="OnTrayOpen">
<tb:TaskbarIcon.IconSource>
<tb:GeneratedIconSource Background="{DynamicResource AccentFillColorDefaultBrush}"
FontWeight="Bold"
Foreground="{DynamicResource TextOnAccentFillColorPrimaryBrush}"
Text="O" />
</tb:TaskbarIcon.IconSource>
<tb:TaskbarIcon.ContextMenu>
<ContextMenu>
<MenuItem Click="OnTrayOpen" Header="{res:OdLoc Tray_Open}" />
<Separator />
<MenuItem Click="OnTrayQuit" Header="{res:OdLoc Tray_Quit}" />
</ContextMenu>
</tb:TaskbarIcon.ContextMenu>
</tb:TaskbarIcon>
</Grid>
</ui:FluentWindow>
+244 -5
View File
@@ -1,13 +1,252 @@
using OmniDeck.Core;
using System.ComponentModel;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Interop;
using H.NotifyIcon.Core;
using OmniDeck.App.Shell;
using OmniDeck.App.Theming;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Core.Theming;
using Wpf.Ui;
using Wpf.Ui.Abstractions;
using Wpf.Ui.Controls;
using MenuItem = System.Windows.Controls.MenuItem;
namespace OmniDeck.App;
/// <summary>Placeholder shell window of the kickoff build; the real shell arrives in P1.</summary>
public partial class OdMainWindow
/// <summary>
/// The shell window: the title bar with the palette button, the navigation view as sidebar chrome,
/// the module stage, in-window dialogs and snackbars, and the tray icon. Closing hides it into the
/// tray unless the user turned that off or is quitting.
/// </summary>
public partial class OdMainWindow : INavigationViewPageProvider
{
public OdMainWindow()
private const int WmSettingChange = 0x001A;
private readonly OdShellViewModel _shell;
private readonly OdDialogs _dialogs;
private readonly OdTrayNotifier _notifier;
private readonly IOdSettingsService _settings;
private readonly IOdAppLifetime _lifetime;
private readonly IOdAppMeta _meta;
private readonly OdLibraryPage _library;
private readonly OdModuleStage _stage;
private readonly Dictionary<string, NavigationViewItem> _moduleItems = new(StringComparer.Ordinal);
private readonly NavigationViewItemSeparator _pinnedSeparator = new();
public OdMainWindow(
OdThemeEngine theme,
OdShellViewModel shell,
OdDialogs dialogs,
ISnackbarService snackbars,
OdTrayNotifier notifier,
IOdSettingsService settings,
IOdAppLifetime lifetime,
IOdAppMeta meta)
{
ArgumentNullException.ThrowIfNull(theme);
ArgumentNullException.ThrowIfNull(snackbars);
InitializeComponent();
VersionText.Text = OdVersionInfo.FromAssembly(typeof(OdMainWindow).Assembly).DisplayText;
_shell = shell;
_dialogs = dialogs;
_notifier = notifier;
_settings = settings;
_lifetime = lifetime;
_meta = meta;
DataContext = shell;
_library = new OdLibraryPage { DataContext = shell };
_stage = new OdModuleStage { DataContext = shell };
dialogs.SetHost(RootDialogHost);
snackbars.SetSnackbarPresenter(RootSnackbar);
// Created now, so the icon exists even if the window never shows; no Efficiency Mode, which
// would throttle the whole process while timers run in the background.
TrayIcon.ForceCreate(enablesEfficiencyMode: false);
notifier.Attach((title, message) => _ = Dispatcher.InvokeAsync(() => TrayIcon.ShowNotification(title, message, NotificationIcon.Info)));
Closed += (_, _) => TrayIcon.Dispose();
RootNavigation.SetPageProviderService(this);
RootNavigation.FooterMenuItems.Add(LibraryItem());
SyncSidebar();
shell.Sidebar.CollectionChanged += (_, _) => SyncSidebar();
shell.PropertyChanged += OnShellPropertyChanged;
RootNavigation.SelectionChanged += OnNavigationSelectionChanged;
RootNavigation.Navigating += (_, _) => RootNavigation.TransitionDuration = (int)OdMotion.DurationFor(this).TotalMilliseconds;
Loaded += (_, _) =>
{
RootNavigation.IsPaneOpen = TryFindResource(OdTokenKeys.NavShowLabels) is not false;
RootNavigation.Navigate(shell.CurrentTarget);
};
// WPF ignores the Windows text size; re-read it when it may have changed (docs/UI-MODES.md §4).
Activated += (_, _) => theme.RefreshTextScale();
SourceInitialized += (_, _) => HwndSource.FromHwnd(new WindowInteropHelper(this).Handle)?.AddHook(
(IntPtr _, int msg, IntPtr _, IntPtr _, ref bool _) =>
{
if (msg == WmSettingChange)
{
theme.RefreshTextScale();
}
return IntPtr.Zero;
});
}
/// <summary>Shows the window from the tray or the taskbar, restored and in front.</summary>
public void Present()
{
Show();
if (WindowState == WindowState.Minimized)
{
WindowState = WindowState.Normal;
}
Activate();
}
object? INavigationViewPageProvider.GetPage(Type pageType)
{
if (pageType == typeof(OdLibraryPage))
{
return _library;
}
return pageType == typeof(OdModuleStage) ? _stage : null;
}
private static Binding Localized(string key) => new($"[{key}]") { Source = OdLocalization.Instance, Mode = BindingMode.OneWay };
private static NavigationViewItem LibraryItem()
{
var item = new NavigationViewItem
{
Icon = new SymbolIcon { Symbol = SymbolRegular.Apps24 },
TargetPageTag = OdShellViewModel.LibraryTarget,
TargetPageType = typeof(OdLibraryPage),
};
item.SetBinding(ContentControl.ContentProperty, Localized("Shell_Library"));
item.SetBinding(AutomationProperties.NameProperty, Localized("Shell_Library"));
return item;
}
/// <summary>
/// Mirrors the sidebar, with a separator between pinned and merely open modules. Each module keeps
/// one item for the window's lifetime: the navigation view never forgets an item's tag, so a
/// re-added module must come back as the same item.
/// </summary>
private void SyncSidebar()
{
RootNavigation.MenuItems.Clear();
var previousPinned = false;
foreach (var module in _shell.Sidebar)
{
if (previousPinned && !module.IsPinned)
{
RootNavigation.MenuItems.Add(_pinnedSeparator);
}
if (!_moduleItems.TryGetValue(module.Id, out var item))
{
item = ModuleItem(module);
_moduleItems[module.Id] = item;
}
RootNavigation.MenuItems.Add(item);
previousPinned = module.IsPinned;
}
}
private NavigationViewItem ModuleItem(OdModuleItemViewModel module)
{
var pin = new MenuItem { Command = _shell.TogglePinCommand, 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 item = new NavigationViewItem
{
Icon = new SymbolIcon { Symbol = OdSymbolConverter.Parse(module.Info.Icon) },
TargetPageTag = module.Id,
TargetPageType = typeof(OdModuleStage),
ContextMenu = menu,
};
item.SetBinding(ContentControl.ContentProperty, new Binding(nameof(OdModuleItemViewModel.Title)) { Source = module });
item.SetBinding(AutomationProperties.NameProperty, new Binding(nameof(OdModuleItemViewModel.Title)) { Source = module });
return item;
}
private async void OnNavigationSelectionChanged(NavigationView sender, RoutedEventArgs args)
{
if (sender.SelectedItem is NavigationViewItem { TargetPageTag: { Length: > 0 } target })
{
await _shell.NavigateAsync(target);
}
}
private void OnShellPropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (!string.Equals(e.PropertyName, nameof(OdShellViewModel.CurrentTarget), StringComparison.Ordinal))
{
return;
}
var selected = (RootNavigation.SelectedItem as NavigationViewItem)?.TargetPageTag;
if (!string.Equals(selected, _shell.CurrentTarget, StringComparison.Ordinal))
{
RootNavigation.Navigate(_shell.CurrentTarget);
}
}
private async void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
// Exactly Ctrl: AltGr arrives as Ctrl+Alt, and must type its character rather than open the palette.
if (e.Key != Key.K || Keyboard.Modifiers != ModifierKeys.Control || _dialogs.IsOpen)
{
return;
}
e.Handled = true;
await OpenPaletteAsync();
}
private async void OnSearchClick(object sender, RoutedEventArgs e) => await OpenPaletteAsync();
private async Task OpenPaletteAsync()
{
var palette = new OdCommandPaletteViewModel(_shell.PaletteEntries());
new OdCommandPaletteWindow(palette, this).ShowDialog();
if (palette.Chosen is { } chosen)
{
await chosen.RunAsync();
}
}
private void OnClosing(object? sender, CancelEventArgs e)
{
if (_lifetime.IsQuitting || !_settings.Current.CloseToTray)
{
return;
}
e.Cancel = true;
Hide();
// Say once, ever, where the window went.
if (_meta.Get(OdAppMetaKeys.TrayHintShown) is null)
{
_meta.Set(OdAppMetaKeys.TrayHintShown, "1");
_notifier.Notify(OdLocalization.Get("Tray_StillRunningTitle"), OdLocalization.Get("Tray_StillRunningMessage"));
}
}
private void OnTrayOpen(object sender, RoutedEventArgs e) => Present();
private void OnTrayQuit(object sender, RoutedEventArgs e) => _lifetime.Quit();
}
+13 -6
View File
@@ -12,20 +12,27 @@
<StartupObject>OmniDeck.App.Program</StartupObject>
<!-- Ship only the UI languages OmniDeck supports (EN neutral, VI, JA). -->
<SatelliteResourceLanguages>en;vi;ja</SatelliteResourceLanguages>
<!-- Resources/Strings.resx is English; the resource manager never probes for an "en" satellite. -->
<NeutralLanguage>en</NeutralLanguage>
</PropertyGroup>
<ItemGroup>
<!-- The application class is OdApp, not App: types carry the Od prefix, and Meziantou MA0049
rejects a type named like its namespace. -->
<Page Remove="OdApp.xaml" />
<ApplicationDefinition Include="OdApp.xaml" />
</ItemGroup>
<!-- The application class is OdApp, not App: types carry the Od prefix, and Meziantou MA0049
rejects a type named like its namespace. OdApp.xaml stays a plain Page (no ApplicationDefinition),
so WPF generates no Main of its own: Program.Main creates OdApp with the single-instance guard. -->
<ItemGroup>
<ProjectReference Include="..\OmniDeck.Core\OmniDeck.Core.csproj" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="OmniDeck.Tests" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2" />
<PackageReference Include="H.NotifyIcon.Wpf" Version="2.4.1" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="10.0.14" />
<PackageReference Include="Serilog.Sinks.File" Version="7.0.0" />
<PackageReference Include="Velopack" Version="1.2.161" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
</ItemGroup>
+16 -4
View File
@@ -1,20 +1,32 @@
using OmniDeck.Core.Runtime;
using OmniDeck.Core.Storage;
using Velopack;
namespace OmniDeck.App;
/// <summary>
/// Process entry point. Velopack's install/update/uninstall hooks run first (they may exit the
/// process and must not wait for WPF to load OdApp.xaml resources); only then is the WPF
/// <see cref="OdApp"/> created.
/// process and must not wait for WPF to load OdApp.xaml resources); then a second OmniDeck hands off
/// to the first one and exits; only then is the WPF <see cref="OdApp"/> created.
/// </summary>
internal static class Program
{
[STAThread]
private static int Main()
{
VelopackApp.Build().Run();
VelopackApp.Build()
// The privacy policy promises that uninstalling removes everything OmniDeck stored.
.OnBeforeUninstallFastCallback(_ => OdDataRoot.Default.TryDelete())
.Run();
var app = new OdApp();
using var guard = new OdSingleInstanceGuard();
if (!guard.IsPrimaryInstance)
{
guard.SignalPrimaryInstance();
return 0;
}
var app = new OdApp(guard);
app.InitializeComponent();
return app.Run();
}
@@ -0,0 +1,9 @@
using System.Resources;
namespace OmniDeck.App.Resources;
/// <summary>The shell's string table, <c>Resources/Strings.resx</c>; <c>OdApp</c> registers it with <c>OdLocalization</c>.</summary>
internal static class OdAppStrings
{
public static ResourceManager Resources { get; } = new("OmniDeck.App.Resources.Strings", typeof(OdAppStrings).Assembly);
}
+82
View File
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!-- The shell's UI strings, English (neutral). Vietnamese and Japanese satellites arrive in P3. -->
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="App_Name" xml:space="preserve">
<value>OmniDeck</value>
</data>
<data name="Shell_Search" xml:space="preserve">
<value>Search modules and commands</value>
</data>
<data name="Shell_Library" xml:space="preserve">
<value>Library</value>
</data>
<data name="Shell_LibraryTitle" xml:space="preserve">
<value>Module library</value>
</data>
<data name="Shell_LibraryIntro" xml:space="preserve">
<value>Open a module, or pin it to keep it in the sidebar.</value>
</data>
<data name="Shell_LibraryEmpty" xml:space="preserve">
<value>No modules are available yet.</value>
</data>
<data name="Shell_Open" xml:space="preserve">
<value>Open</value>
</data>
<data name="Shell_Pin" xml:space="preserve">
<value>Pin to sidebar</value>
</data>
<data name="Shell_Unpin" xml:space="preserve">
<value>Unpin from sidebar</value>
</data>
<data name="Shell_Close" xml:space="preserve">
<value>Close</value>
</data>
<data name="Shell_PaletteCommand" xml:space="preserve">
<value>Command</value>
</data>
<data name="Shell_Quit" xml:space="preserve">
<value>Quit OmniDeck</value>
</data>
<data name="Tray_Open" xml:space="preserve">
<value>Open OmniDeck</value>
</data>
<data name="Tray_Quit" xml:space="preserve">
<value>Quit</value>
</data>
<data name="Tray_StillRunningTitle" xml:space="preserve">
<value>OmniDeck is still running</value>
</data>
<data name="Tray_StillRunningMessage" xml:space="preserve">
<value>It keeps running in the notification area. To exit, choose Quit from its icon's menu.</value>
</data>
<data name="Error_Title" xml:space="preserve">
<value>Something went wrong</value>
</data>
<data name="Error_UiMessage" xml:space="preserve">
<value>Something went wrong, but OmniDeck is still running.
Support code: {0}
{1}</value>
</data>
<data name="Error_StartFailed" xml:space="preserve">
<value>OmniDeck could not start.
{0}</value>
</data>
<data name="Dialog_OK" xml:space="preserve">
<value>OK</value>
</data>
</root>
+10
View File
@@ -0,0 +1,10 @@
namespace OmniDeck.App.Shell;
/// <summary>Ends the app on purpose, as opposed to closing its window into the tray.</summary>
public interface IOdAppLifetime
{
/// <summary>Set once <see cref="Quit"/> runs: window closing must not turn into hiding.</summary>
bool IsQuitting { get; }
void Quit();
}
+15
View File
@@ -0,0 +1,15 @@
using System.Windows;
namespace OmniDeck.App.Shell;
/// <summary><see cref="IOdAppLifetime"/> over the WPF application, whose shutdown mode is explicit.</summary>
internal sealed class OdAppLifetime : IOdAppLifetime
{
public bool IsQuitting { get; private set; }
public void Quit()
{
IsQuitting = true;
Application.Current?.Shutdown();
}
}
@@ -0,0 +1,70 @@
using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OmniDeck.Core.Search;
namespace OmniDeck.App.Shell;
/// <summary>The command palette (Ctrl+K, docs/SPEC.md §2): fuzzy search over modules and shell commands.</summary>
public sealed partial class OdCommandPaletteViewModel : ObservableObject
{
private readonly IReadOnlyList<OdPaletteEntry> _entries;
[ObservableProperty]
private string _query = "";
[ObservableProperty]
private OdPaletteEntry? _selected;
public OdCommandPaletteViewModel(IReadOnlyList<OdPaletteEntry> entries)
{
ArgumentNullException.ThrowIfNull(entries);
_entries = entries;
Filter();
}
/// <summary>Raised when the user accepts <see cref="Chosen"/>.</summary>
public event EventHandler? Accepted;
public ObservableCollection<OdPaletteEntry> Results { get; } = [];
/// <summary>The accepted entry; <see langword="null"/> while the palette is open or after it was dismissed.</summary>
public OdPaletteEntry? Chosen { get; private set; }
/// <summary>Moves the selection by <paramref name="delta"/> rows, stopping at either end.</summary>
public void MoveSelection(int delta)
{
if (Results.Count == 0)
{
return;
}
var current = Selected is null ? -1 : Results.IndexOf(Selected);
Selected = Results[Math.Clamp(current + delta, 0, Results.Count - 1)];
}
partial void OnQueryChanged(string value) => Filter();
[RelayCommand]
private void Accept()
{
if (Selected is null)
{
return;
}
Chosen = Selected;
Accepted?.Invoke(this, EventArgs.Empty);
}
private void Filter()
{
Results.Clear();
foreach (var entry in OdFuzzyMatcher.Rank(Query, _entries, entry => entry.Title))
{
Results.Add(entry);
}
Selected = Results.Count > 0 ? Results[0] : null;
}
}
@@ -0,0 +1,69 @@
<ui:FluentWindow x:Class="OmniDeck.App.Shell.OdCommandPaletteWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:res="clr-namespace:OmniDeck.Core.Localization;assembly=OmniDeck.Core"
xmlns:shell="clr-namespace:OmniDeck.App.Shell"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="{res:OdLoc Shell_Search}"
Width="600"
ExtendsContentIntoTitleBar="True"
PreviewKeyDown="OnPreviewKeyDown"
ResizeMode="NoResize"
ShowInTaskbar="False"
SizeToContent="Height"
WindowBackdropType="Acrylic"
WindowCornerPreference="Round"
WindowStartupLocation="Manual">
<!-- A borderless overlay without a title bar: type, arrow keys, Enter; Esc or clicking away closes it. -->
<ui:FluentWindow.Resources>
<shell:OdSymbolConverter x:Key="Symbol" />
</ui:FluentWindow.Resources>
<DockPanel Margin="{DynamicResource Od.Padding.Card}">
<ui:TextBox x:Name="SearchBox"
AutomationProperties.Name="{res:OdLoc Shell_Search}"
ClearButtonEnabled="True"
DockPanel.Dock="Top"
FontSize="{DynamicResource Od.Font.H2}"
PlaceholderText="{res:OdLoc Shell_Search}"
Text="{Binding Query, UpdateSourceTrigger=PropertyChanged}">
<ui:TextBox.Icon>
<ui:SymbolIcon Symbol="Search24" />
</ui:TextBox.Icon>
</ui:TextBox>
<ListBox x:Name="ResultsList"
MaxHeight="420"
Margin="{DynamicResource Od.Margin.Item}"
HorizontalContentAlignment="Stretch"
AutomationProperties.Name="{res:OdLoc Shell_Search}"
Background="Transparent"
BorderThickness="0"
ItemsSource="{Binding Results}"
MouseDoubleClick="OnResultDoubleClick"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
SelectedItem="{Binding Selected}">
<ListBox.ItemContainerStyle>
<Style BasedOn="{StaticResource {x:Type ListBoxItem}}" TargetType="ListBoxItem">
<Setter Property="AutomationProperties.Name" Value="{Binding Title}" />
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type shell:OdPaletteEntry}">
<DockPanel>
<ui:SymbolIcon Margin="{DynamicResource Od.Padding.Control}"
VerticalAlignment="Center"
DockPanel.Dock="Left"
FontSize="{DynamicResource Od.Font.H2}"
Symbol="{Binding Icon, Converter={StaticResource Symbol}}" />
<StackPanel VerticalAlignment="Center">
<TextBlock Text="{Binding Title}" TextTrimming="CharacterEllipsis" />
<TextBlock FontSize="{DynamicResource Od.Font.Caption}"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{Binding Detail}"
TextTrimming="CharacterEllipsis" />
</StackPanel>
</DockPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</ui:FluentWindow>
@@ -0,0 +1,82 @@
using System.Windows;
using System.Windows.Input;
namespace OmniDeck.App.Shell;
/// <summary>The command palette overlay (Ctrl+K). After it closes, <see cref="OdCommandPaletteViewModel.Chosen"/> holds the pick.</summary>
public partial class OdCommandPaletteWindow
{
// Sits near the top of its owner, where a search box is expected.
private const double TopOffset = 72;
private readonly OdCommandPaletteViewModel _viewModel;
private bool _closing;
public OdCommandPaletteWindow(OdCommandPaletteViewModel viewModel, Window owner)
{
ArgumentNullException.ThrowIfNull(viewModel);
ArgumentNullException.ThrowIfNull(owner);
InitializeComponent();
_viewModel = viewModel;
DataContext = viewModel;
Owner = owner;
viewModel.Accepted += (_, _) => RequestClose();
Loaded += (_, _) =>
{
var bounds = owner.WindowState == WindowState.Maximized ? owner.RestoreBounds : new Rect(owner.Left, owner.Top, owner.ActualWidth, owner.ActualHeight);
Left = bounds.Left + ((bounds.Width - ActualWidth) / 2);
Top = bounds.Top + TopOffset;
SearchBox.Focus();
};
// Clicking away closes it. Closing deactivates the window too, whoever closes it (Esc, Alt+F4,
// the owner), so a close already under way must not be started again.
Closing += (_, _) => _closing = true;
Deactivated += (_, _) => RequestClose();
}
private void RequestClose()
{
if (_closing)
{
return;
}
_closing = true;
Close();
}
private void OnResultDoubleClick(object sender, MouseButtonEventArgs e) => _viewModel.AcceptCommand.Execute(null);
private void OnPreviewKeyDown(object sender, KeyEventArgs e)
{
switch (e.Key)
{
case Key.Escape:
RequestClose();
break;
case Key.Enter:
_viewModel.AcceptCommand.Execute(null);
break;
case Key.Down:
MoveSelection(1);
break;
case Key.Up:
MoveSelection(-1);
break;
default:
return;
}
e.Handled = true;
}
private void MoveSelection(int delta)
{
_viewModel.MoveSelection(delta);
if (_viewModel.Selected is { } selected)
{
ResultsList.ScrollIntoView(selected);
}
}
}
+43
View File
@@ -0,0 +1,43 @@
using System.Windows;
using Wpf.Ui;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Shell;
/// <summary>
/// In-window content dialogs, one at a time. Callers check <see cref="CanShow"/> and fall back (a
/// message box, or a safe default) before the main window is up or while another dialog is open.
/// </summary>
public sealed class OdDialogs(IContentDialogService service)
{
private bool _hostReady;
private int _open;
/// <summary>Whether a dialog is showing.</summary>
public bool IsOpen => _open > 0;
/// <summary>Whether a dialog can show now: the main window is visible and no other dialog is open.</summary>
public bool CanShow => _hostReady && !IsOpen && Application.Current?.MainWindow is { IsVisible: true };
/// <summary>Called once by the main window with its dialog host.</summary>
public void SetHost(ContentDialogHost host)
{
ArgumentNullException.ThrowIfNull(host);
service.SetDialogHost(host);
_hostReady = true;
}
public async Task<ContentDialogResult> ShowAsync(ContentDialog dialog)
{
ArgumentNullException.ThrowIfNull(dialog);
_open++;
try
{
return await service.ShowAsync(dialog, CancellationToken.None);
}
finally
{
_open--;
}
}
}
+108
View File
@@ -0,0 +1,108 @@
<UserControl x:Class="OmniDeck.App.Shell.OdLibraryPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:res="clr-namespace:OmniDeck.Core.Localization;assembly=OmniDeck.Core"
xmlns:shell="clr-namespace:OmniDeck.App.Shell"
xmlns:theme="clr-namespace:OmniDeck.App.Theming"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Foreground="{DynamicResource TextFillColorPrimaryBrush}">
<!-- The navigation view's frame does not pass the window's text color down: pages set their own. -->
<UserControl.Resources>
<shell:OdSymbolConverter x:Key="Symbol" />
</UserControl.Resources>
<ScrollViewer HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Auto">
<StackPanel Margin="{DynamicResource Od.Padding.Card}">
<TextBlock FontSize="{DynamicResource Od.Font.H1}"
FontWeight="SemiBold"
Text="{res:OdLoc Shell_LibraryTitle}" />
<TextBlock Margin="{DynamicResource Od.Margin.Item}"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{res:OdLoc Shell_LibraryIntro}"
TextWrapping="Wrap" />
<TextBlock Foreground="{DynamicResource TextFillColorTertiaryBrush}" Text="{res:OdLoc Shell_LibraryEmpty}">
<TextBlock.Style>
<Style BasedOn="{StaticResource {x:Type TextBlock}}" TargetType="TextBlock">
<Setter Property="Visibility" Value="Collapsed" />
<Style.Triggers>
<DataTrigger Binding="{Binding HasModules}" Value="False">
<Setter Property="Visibility" Value="Visible" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
<ItemsControl Focusable="False" ItemsSource="{Binding Library}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type shell:OdModuleItemViewModel}">
<ui:Card Width="260"
Margin="{DynamicResource Od.Margin.Tile}"
VerticalAlignment="Stretch"
theme:OdMotion.HoverScale="True">
<DockPanel LastChildFill="False">
<DockPanel DockPanel.Dock="Top">
<ui:SymbolIcon Margin="{DynamicResource Od.Padding.Control}"
VerticalAlignment="Center"
DockPanel.Dock="Left"
FontSize="{DynamicResource Od.Font.H1}"
Symbol="{Binding Info.Icon, Converter={StaticResource Symbol}}" />
<StackPanel VerticalAlignment="Center">
<TextBlock FontSize="{DynamicResource Od.Font.H2}"
FontWeight="SemiBold"
Text="{Binding Title}"
TextTrimming="CharacterEllipsis" />
<TextBlock FontSize="{DynamicResource Od.Font.Caption}"
Foreground="{DynamicResource TextFillColorSecondaryBrush}"
Text="{Binding Category}"
TextTrimming="CharacterEllipsis" />
</StackPanel>
</DockPanel>
<StackPanel Margin="{DynamicResource Od.Padding.Control}"
DockPanel.Dock="Bottom"
Orientation="Horizontal">
<ui:Button Appearance="Primary"
Command="{Binding DataContext.OpenCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}"
Content="{res:OdLoc Shell_Open}" />
<ui:Button Margin="{DynamicResource Od.Padding.Control}"
Appearance="Transparent"
Command="{Binding DataContext.TogglePinCommand, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
CommandParameter="{Binding}">
<ui:Button.Style>
<Style BasedOn="{StaticResource {x:Type ui:Button}}" TargetType="ui:Button">
<Setter Property="ToolTip" Value="{res:OdLoc Shell_Pin}" />
<Setter Property="AutomationProperties.Name" Value="{res:OdLoc Shell_Pin}" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsPinned}" Value="True">
<Setter Property="ToolTip" Value="{res:OdLoc Shell_Unpin}" />
<Setter Property="AutomationProperties.Name" Value="{res:OdLoc Shell_Unpin}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ui:Button.Style>
<ui:SymbolIcon>
<ui:SymbolIcon.Style>
<Style TargetType="ui:SymbolIcon">
<Setter Property="Symbol" Value="Pin24" />
<Style.Triggers>
<DataTrigger Binding="{Binding IsPinned}" Value="True">
<Setter Property="Symbol" Value="PinOff24" />
</DataTrigger>
</Style.Triggers>
</Style>
</ui:SymbolIcon.Style>
</ui:SymbolIcon>
</ui:Button>
</StackPanel>
</DockPanel>
</ui:Card>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</ScrollViewer>
</UserControl>
@@ -0,0 +1,10 @@
namespace OmniDeck.App.Shell;
/// <summary>The "+" page: every module, with Open and pin buttons. Bound to <see cref="OdShellViewModel"/>.</summary>
public partial class OdLibraryPage
{
public OdLibraryPage()
{
InitializeComponent();
}
}
@@ -0,0 +1,37 @@
using CommunityToolkit.Mvvm.ComponentModel;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
namespace OmniDeck.App.Shell;
/// <summary>A module as the sidebar, the library and the palette show it.</summary>
public sealed partial class OdModuleItemViewModel(OdModuleInfo info) : ObservableObject
{
[ObservableProperty]
private bool _isPinned;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(IsOpen))]
private OdModuleState _state = OdModuleState.Created;
public OdModuleInfo Info { get; } = info;
public string Id => Info.Id;
public string Title => OdLocalization.Get(Info.NameKey);
public string Category => OdLocalization.Get(Info.CategoryKey);
/// <summary>Opened and not closed since: it keeps a sidebar entry even when unpinned, like a tab.</summary>
public bool IsOpen => State is not (OdModuleState.Created or OdModuleState.Closed);
/// <summary>The name screen readers announce for the module's library tile and palette row.</summary>
public override string ToString() => Title;
/// <summary>Re-reads the localized texts after a language change.</summary>
public void RefreshTexts()
{
OnPropertyChanged(nameof(Title));
OnPropertyChanged(nameof(Category));
}
}
@@ -0,0 +1,8 @@
<ContentControl x:Class="OmniDeck.App.Shell.OdModuleStage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Content="{Binding CurrentView}"
Focusable="False"
Foreground="{DynamicResource TextFillColorPrimaryBrush}" />
@@ -0,0 +1,13 @@
namespace OmniDeck.App.Shell;
/// <summary>
/// The one page every module item navigates to: it shows <see cref="OdShellViewModel.CurrentView"/>,
/// so the navigation view never creates, caches or keeps a module view (docs/WPFUI-CONVENTIONS.md §5).
/// </summary>
public partial class OdModuleStage
{
public OdModuleStage()
{
InitializeComponent();
}
}
+8
View File
@@ -0,0 +1,8 @@
namespace OmniDeck.App.Shell;
/// <summary>One command palette result: a module to open, or a shell command.</summary>
/// <param name="Title">What the palette matches and shows.</param>
/// <param name="Detail">The second line: the module's category, or "Command".</param>
/// <param name="Icon">A WPF-UI <c>SymbolRegular</c> name.</param>
/// <param name="RunAsync">What choosing the entry does.</param>
public sealed record OdPaletteEntry(string Title, string Detail, string Icon, Func<Task> RunAsync);
+186
View File
@@ -0,0 +1,186 @@
using System.Collections.ObjectModel;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using OmniDeck.Core.Localization;
using OmniDeck.Core.Modules;
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.
/// </summary>
public sealed partial class OdShellViewModel : ObservableObject, IDisposable
{
/// <summary>The navigation target of the library page; module ids are the other targets.</summary>
public const string LibraryTarget = "library";
private readonly OdModuleHost _host;
private readonly IOdSettingsService _settings;
private readonly IOdAppLifetime _lifetime;
private readonly Dictionary<string, OdModuleItemViewModel> _items;
private readonly List<OdModuleItemViewModel> _openOrder = [];
private IReadOnlyList<string> _pinned = [];
private string _sidebarShape = "";
[ObservableProperty]
private string _currentTarget = LibraryTarget;
[ObservableProperty]
private FrameworkElement? _currentView;
public OdShellViewModel(OdModuleHost host, IOdSettingsService settings, IOdAppLifetime lifetime)
{
ArgumentNullException.ThrowIfNull(host);
ArgumentNullException.ThrowIfNull(settings);
_host = host;
_settings = settings;
_lifetime = lifetime;
Library = [.. host.Modules.Select(hosted => new OdModuleItemViewModel(hosted.Info) { State = hosted.State })];
_items = Library.ToDictionary(item => item.Id, StringComparer.Ordinal);
ApplyPins(settings.Current.PinnedModules);
host.StateChanged += OnModuleStateChanged;
settings.Changed += OnSettingsChanged;
OdLocalization.Instance.CultureChanged += OnCultureChanged;
}
/// <summary>Every module, in registration order: the library page.</summary>
public IReadOnlyList<OdModuleItemViewModel> Library { get; }
public bool HasModules => Library.Count > 0;
/// <summary>
/// The sidebar: pinned modules in pin order, then open unpinned ones in the order they were opened.
/// It is rebuilt whenever its order or a pin changes, so the window can draw the pinned group.
/// </summary>
public ObservableCollection<OdModuleItemViewModel> Sidebar { get; } = [];
/// <summary>Shows <paramref name="target"/>, a module id or <see cref="LibraryTarget"/>; other targets are ignored.</summary>
public async Task NavigateAsync(string target)
{
ArgumentNullException.ThrowIfNull(target);
if (string.Equals(target, LibraryTarget, StringComparison.Ordinal))
{
await _host.HideAsync();
CurrentView = null;
CurrentTarget = LibraryTarget;
}
else if (_items.ContainsKey(target))
{
CurrentView = await _host.ShowAsync(target);
CurrentTarget = target;
}
}
/// <summary>The palette's entries in the current language: every module, then the shell commands.</summary>
public IReadOnlyList<OdPaletteEntry> PaletteEntries()
{
var command = OdLocalization.Get("Shell_PaletteCommand");
return
[
.. Library.Select(item => new OdPaletteEntry(item.Title, item.Category, item.Info.Icon, () => NavigateAsync(item.Id))),
new(OdLocalization.Get("Shell_LibraryTitle"), command, "Apps24", () => NavigateAsync(LibraryTarget)),
new(OdLocalization.Get("Shell_Quit"), command, "Power24", QuitAsync),
];
}
public void Dispose()
{
_host.StateChanged -= OnModuleStateChanged;
_settings.Changed -= OnSettingsChanged;
OdLocalization.Instance.CultureChanged -= OnCultureChanged;
}
[RelayCommand]
private Task OpenAsync(OdModuleItemViewModel item) => NavigateAsync(item.Id);
[RelayCommand]
private Task CloseAsync(OdModuleItemViewModel item) => _host.CloseAsync(item.Id);
[RelayCommand]
private void TogglePin(OdModuleItemViewModel item) => _settings.Update(s => s with
{
PinnedModules = item.IsPinned
? [.. s.PinnedModules.Where(id => !string.Equals(id, item.Id, StringComparison.Ordinal))]
: [.. s.PinnedModules, item.Id],
});
private Task QuitAsync()
{
_lifetime.Quit();
return Task.CompletedTask;
}
private void OnModuleStateChanged(object? sender, OdModuleStateChangedEventArgs e)
{
if (!_items.TryGetValue(e.Module.Info.Id, out var item))
{
return;
}
item.State = e.Module.State;
if (!item.IsOpen)
{
_openOrder.Remove(item);
if (string.Equals(item.Id, CurrentTarget, StringComparison.Ordinal))
{
// Closed while showing: the library takes its place.
CurrentView = null;
CurrentTarget = LibraryTarget;
}
}
else if (!_openOrder.Contains(item))
{
_openOrder.Add(item);
}
UpdateSidebar();
}
private void OnSettingsChanged(object? sender, OdSettingsChangedEventArgs e) => ApplyPins(e.Settings.PinnedModules);
private void OnCultureChanged(object? sender, EventArgs e)
{
foreach (var item in Library)
{
item.RefreshTexts();
}
}
private void ApplyPins(IReadOnlyList<string> pinned)
{
_pinned = pinned;
foreach (var item in Library)
{
item.IsPinned = pinned.Contains(item.Id, StringComparer.Ordinal);
}
UpdateSidebar();
}
private void UpdateSidebar()
{
// Pins may name modules this build does not have (a web app taken out of the catalog): skip them.
OdModuleItemViewModel[] wanted =
[
.. _pinned.Select(id => _items.GetValueOrDefault(id)).OfType<OdModuleItemViewModel>(),
.. _openOrder.Where(item => !item.IsPinned),
];
var shape = string.Join(' ', wanted.Select(item => item.IsPinned ? "+" + item.Id : item.Id));
if (string.Equals(shape, _sidebarShape, StringComparison.Ordinal))
{
return;
}
_sidebarShape = shape;
Sidebar.Clear();
foreach (var item in wanted)
{
Sidebar.Add(item);
}
}
}
@@ -0,0 +1,20 @@
using System.Globalization;
using System.Windows.Data;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Shell;
/// <summary>
/// Turns the icon names modules declare (Core stays free of WPF-UI) into Fluent symbols; an unknown
/// name shows a generic app glyph rather than nothing.
/// </summary>
[ValueConversion(typeof(string), typeof(SymbolRegular))]
public sealed class OdSymbolConverter : IValueConverter
{
public static SymbolRegular Parse(string? name) =>
Enum.TryParse<SymbolRegular>(name, ignoreCase: false, out var symbol) && Enum.IsDefined(symbol) ? symbol : SymbolRegular.Apps24;
public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) => Parse(value as string);
public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) => Binding.DoNothing;
}
+33
View File
@@ -0,0 +1,33 @@
using OmniDeck.Core.Modules;
using Serilog;
namespace OmniDeck.App.Shell;
/// <summary>
/// <see cref="IOdNotifier"/> through the tray icon's balloon, which Windows 11 shows as a toast.
/// WinRT toasts would need a Windows-versioned target framework and its 26 MB projection assembly
/// (docs/spikes/05-theme-swap.md). The main window attaches the icon; until then notifications are
/// only logged.
/// </summary>
public sealed class OdTrayNotifier(ILogger log) : IOdNotifier
{
private readonly ILogger _log = log.ForContext<OdTrayNotifier>();
private Action<string, string>? _show;
public void Attach(Action<string, string> show)
{
ArgumentNullException.ThrowIfNull(show);
_show = show;
}
public void Notify(string title, string message)
{
if (_show is null)
{
_log.Information("Notification before the tray icon exists: {Title}", title);
return;
}
_show(title, message);
}
}
+74
View File
@@ -0,0 +1,74 @@
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Animation;
using OmniDeck.Core.Theming;
namespace OmniDeck.App.Theming;
/// <summary>
/// Token-driven motion. Storyboards inside styles are frozen and cannot take a DynamicResource, so
/// animations run from code and read <c>Od.Motion.Duration</c> when they start: a preset change applies
/// to the next animation, and a zero duration (Comfort, the user's switch, or Windows' animation
/// effects off) jumps straight to the end state (docs/spikes/05-theme-swap.md).
/// </summary>
public static class OdMotion
{
public static readonly DependencyProperty HoverScaleProperty = DependencyProperty.RegisterAttached(
"HoverScale", typeof(bool), typeof(OdMotion), new PropertyMetadata(defaultValue: false, OnHoverScaleChanged));
public static bool GetHoverScale(DependencyObject element)
{
ArgumentNullException.ThrowIfNull(element);
return (bool)element.GetValue(HoverScaleProperty);
}
public static void SetHoverScale(DependencyObject element, bool value)
{
ArgumentNullException.ThrowIfNull(element);
element.SetValue(HoverScaleProperty, value);
}
/// <summary>The current motion duration for <paramref name="element"/>; zero means no animation.</summary>
public static TimeSpan DurationFor(FrameworkElement element)
{
ArgumentNullException.ThrowIfNull(element);
return element.TryFindResource(OdTokenKeys.MotionDuration) is Duration { HasTimeSpan: true } duration
? duration.TimeSpan
: TimeSpan.Zero;
}
private static void OnHoverScaleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not FrameworkElement element || e.NewValue is not true)
{
return;
}
element.RenderTransformOrigin = new Point(0.5, 0.5);
element.RenderTransform = new ScaleTransform(1, 1);
element.MouseEnter += (_, _) => AnimateScale(element, 1.03);
element.MouseLeave += (_, _) => AnimateScale(element, 1.0);
}
private static void AnimateScale(FrameworkElement element, double to)
{
if (element.RenderTransform is not ScaleTransform transform)
{
return;
}
var duration = DurationFor(element);
if (duration == TimeSpan.Zero)
{
transform.BeginAnimation(ScaleTransform.ScaleXProperty, null);
transform.BeginAnimation(ScaleTransform.ScaleYProperty, null);
transform.ScaleX = to;
transform.ScaleY = to;
return;
}
var animation = new DoubleAnimation(to, new Duration(duration)) { EasingFunction = new CubicEase { EasingMode = EasingMode.EaseOut } };
transform.BeginAnimation(ScaleTransform.ScaleXProperty, animation);
transform.BeginAnimation(ScaleTransform.ScaleYProperty, animation);
}
}
+24
View File
@@ -0,0 +1,24 @@
<ResourceDictionary 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">
<!--
WPF-UI 4.3 sets these controls' sizes through StaticResource (ButtonPadding, CardPadding,
CardControlPadding), which a preset swap cannot reach. These implicit styles keep the stock
look and read the Od.* tokens instead (docs/spikes/05-theme-swap.md). Keys WPF-UI reads through
DynamicResource are overridden in the preset layer itself (OdThemeResources).
-->
<Style BasedOn="{StaticResource DefaultUiButtonStyle}" TargetType="{x:Type ui:Button}">
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Control}" />
<Setter Property="MinHeight" Value="{DynamicResource Od.HitTarget.Min}" />
</Style>
<Style BasedOn="{StaticResource DefaultButtonStyle}" TargetType="{x:Type Button}">
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Control}" />
<Setter Property="MinHeight" Value="{DynamicResource Od.HitTarget.Min}" />
</Style>
<Style BasedOn="{StaticResource {x:Type ui:Card}}" TargetType="{x:Type ui:Card}">
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Card}" />
</Style>
<Style BasedOn="{StaticResource DefaultUiCardControlStyle}" TargetType="{x:Type ui:CardControl}">
<Setter Property="Padding" Value="{DynamicResource Od.Padding.Card}" />
</Style>
</ResourceDictionary>
+24
View File
@@ -0,0 +1,24 @@
using Microsoft.Win32;
namespace OmniDeck.App.Theming;
/// <summary>
/// The Windows "Text size" setting (Settings → Accessibility). WPF ignores it, so OmniDeck reads it
/// itself and multiplies the font tokens (docs/UI-MODES.md §4). The registry is read rather than
/// WinRT's UISettings, which would need a Windows-versioned target framework and its 26 MB projection
/// assembly (docs/spikes/05-theme-swap.md).
/// </summary>
internal static class OdTextScale
{
private const string KeyPath = @"Software\Microsoft\Accessibility";
public static double Read()
{
using var key = Registry.CurrentUser.OpenSubKey(KeyPath);
return FromRegistryValue(key?.GetValue("TextScaleFactor"));
}
/// <summary>The value is a percentage from 100 to 225; anything else means 100 %.</summary>
internal static double FromRegistryValue(object? value) =>
value is int percent and >= 100 and <= 225 ? percent / 100.0 : 1.0;
}
+131
View File
@@ -0,0 +1,131 @@
using System.Windows;
using System.Windows.Media;
using Microsoft.Win32;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Theming;
using Serilog;
using Wpf.Ui.Appearance;
using Wpf.Ui.Controls;
namespace OmniDeck.App.Theming;
/// <summary>
/// The theme engine (docs/UI-MODES.md): two independent axes, dark/light through WPF-UI's
/// <see cref="ApplicationThemeManager"/> and the UI preset through the <c>Od.*</c> token layer, both
/// following the settings, the Windows app mode, High Contrast and the Windows text size.
/// </summary>
public sealed class OdThemeEngine : IDisposable
{
private readonly IOdSettingsService _settings;
private readonly ILogger _log;
private Application? _app;
private OdSettings? _applied;
private double _textScale = 1.0;
public OdThemeEngine(IOdSettingsService settings, ILogger log)
{
_settings = settings;
_log = log.ForContext<OdThemeEngine>();
Current = OdTokens.Compute(OdPreset.Standard, 1.0, 1.0, motionEnabled: true);
}
/// <summary>The tokens in effect.</summary>
public OdTokens Current { get; private set; }
/// <summary>Applies the theme and the preset layer to <paramref name="app"/> and starts following changes.</summary>
public void Start(Application app)
{
ArgumentNullException.ThrowIfNull(app);
_app = app;
_applied = _settings.Current;
_textScale = OdTextScale.Read();
ApplyTheme();
ApplyTokens();
_settings.Changed += OnSettingsChanged;
SystemEvents.UserPreferenceChanged += OnUserPreferenceChanged;
}
/// <summary>Re-reads the Windows text size; windows call this on WM_SETTINGCHANGE and on activation.</summary>
public void RefreshTextScale()
{
var now = OdTextScale.Read();
if (Math.Abs(now - _textScale) > 0.001)
{
_textScale = now;
ApplyTokens();
}
}
public void Dispose()
{
_settings.Changed -= OnSettingsChanged;
SystemEvents.UserPreferenceChanged -= OnUserPreferenceChanged;
}
private void ApplyTokens()
{
if (_app is null)
{
return;
}
var settings = _settings.Current;
Current = OdTokens.Compute(
OdPreset.FromName(settings.Preset),
_textScale,
settings.FontScale,
settings.MotionEnabled && SystemParameters.ClientAreaAnimation);
OdThemeResources.Apply(_app.Resources, OdThemeResources.Build(Current));
_log.Debug("Preset {Preset} applied (text scale {TextScale}, font scale {FontScale})", Current.PresetName, _textScale, settings.FontScale);
}
private void ApplyTheme()
{
var settings = _settings.Current;
var useAccent = settings.AccentColor.Length == 0;
if (settings.Theme == OdThemeMode.System || SystemParameters.HighContrast)
{
// High Contrast: palette tokens defer to the system entirely (docs/UI-MODES.md §4).
ApplicationThemeManager.ApplySystemTheme(updateAccent: useAccent);
}
else
{
var theme = settings.Theme == OdThemeMode.Light ? ApplicationTheme.Light : ApplicationTheme.Dark;
ApplicationThemeManager.Apply(theme, WindowBackdropType.Mica, updateAccent: useAccent);
}
if (!useAccent && ColorConverter.ConvertFromString(settings.AccentColor) is Color accent)
{
ApplicationAccentColorManager.Apply(accent, ApplicationThemeManager.GetAppTheme());
}
}
private void OnSettingsChanged(object? sender, OdSettingsChangedEventArgs e)
{
// Pins, the language and other settings leave the look alone; re-applying it would re-style every window.
if (_applied?.LooksLike(e.Settings) == true)
{
return;
}
_applied = e.Settings;
_app?.Dispatcher.Invoke(() =>
{
ApplyTheme();
ApplyTokens();
});
}
private void OnUserPreferenceChanged(object? sender, UserPreferenceChangedEventArgs e)
{
if (e.Category is UserPreferenceCategory.General or UserPreferenceCategory.Color or UserPreferenceCategory.Accessibility or UserPreferenceCategory.VisualStyle)
{
_ = _app?.Dispatcher.InvokeAsync(() =>
{
ApplyTheme();
RefreshTextScale();
ApplyTokens();
});
}
}
}
@@ -0,0 +1,62 @@
using System.Windows;
using OmniDeck.Core.Theming;
namespace OmniDeck.App.Theming;
/// <summary>
/// Turns resolved tokens into the preset layer: one <see cref="ResourceDictionary"/> merged after
/// WPF-UI's dictionaries and replaced in place when the preset, the user's overrides or the Windows
/// text size change (docs/spikes/05-theme-swap.md).
/// </summary>
internal static class OdThemeResources
{
public static ResourceDictionary Build(OdTokens tokens)
{
ArgumentNullException.ThrowIfNull(tokens);
var d = tokens.Density;
var controlPadding = new Thickness(d * 2, d, d * 2, d);
return new ResourceDictionary
{
[OdTokenKeys.PresetMarker] = tokens.PresetName,
[OdTokenKeys.FontBase] = tokens.FontBase,
[OdTokenKeys.FontH1] = tokens.FontH1,
[OdTokenKeys.FontH2] = tokens.FontH2,
[OdTokenKeys.FontCaption] = tokens.FontCaption,
[OdTokenKeys.Density] = d,
[OdTokenKeys.PaddingControl] = controlPadding,
[OdTokenKeys.PaddingCard] = new Thickness(d * 3),
[OdTokenKeys.MarginItem] = new Thickness(0, 0, 0, d * 2),
[OdTokenKeys.MarginTile] = new Thickness(0, 0, d * 2, d * 2),
[OdTokenKeys.HitTargetMin] = tokens.HitTargetMin,
[OdTokenKeys.CornerRadius] = new CornerRadius(tokens.CornerRadius),
[OdTokenKeys.MotionDuration] = new Duration(TimeSpan.FromMilliseconds(tokens.MotionMilliseconds)),
[OdTokenKeys.ChartLineWeight] = tokens.ChartLineWeight,
[OdTokenKeys.NavMaxVisibleItems] = tokens.NavMaxVisibleItems,
[OdTokenKeys.NavShowLabels] = tokens.NavShowLabels,
// Deliberate WPF-UI overrides (docs/WPFUI-CONVENTIONS.md §6): WPF-UI 4.3 templates read these
// keys through DynamicResource, so stock controls follow the preset without a style of ours.
["ControlCornerRadius"] = new CornerRadius(tokens.CornerRadius),
["ControlContentThemeFontSize"] = tokens.FontBase,
["TextControlThemePadding"] = controlPadding,
["TextControlThemeMinHeight"] = tokens.HitTargetMin,
};
}
/// <summary>Puts <paramref name="preset"/> in place of the current preset layer, or adds it last.</summary>
public static void Apply(ResourceDictionary target, ResourceDictionary preset)
{
ArgumentNullException.ThrowIfNull(target);
var merged = target.MergedDictionaries;
for (var i = 0; i < merged.Count; i++)
{
if (merged[i].Contains(OdTokenKeys.PresetMarker))
{
merged[i] = preset;
return;
}
}
merged.Add(preset);
}
}
@@ -0,0 +1,27 @@
using System.Windows.Data;
using System.Windows.Markup;
namespace OmniDeck.Core.Localization;
/// <summary>
/// <c>{res:OdLoc Key}</c>: a one-way binding to <see cref="OdLocalization"/>'s indexer, so the text
/// follows the UI language live.
/// </summary>
[MarkupExtensionReturnType(typeof(string))]
public sealed class OdLocExtension : MarkupExtension
{
public OdLocExtension()
{
}
public OdLocExtension(string key)
{
Key = key;
}
[ConstructorArgument("key")]
public string Key { get; set; } = "";
public override object ProvideValue(IServiceProvider serviceProvider) =>
new Binding($"[{Key}]") { Source = OdLocalization.Instance, Mode = BindingMode.OneWay }.ProvideValue(serviceProvider);
}
@@ -0,0 +1,129 @@
using System.ComponentModel;
using System.Globalization;
using System.Resources;
using System.Windows;
using System.Windows.Markup;
namespace OmniDeck.Core.Localization;
/// <summary>
/// The live source of UI strings. XAML binds to this singleton's indexer through
/// <see cref="OdLocExtension"/>, so <see cref="SetCulture"/> updates every bound string without a
/// restart; code reads <see cref="Get"/> and re-reads on <see cref="CultureChanged"/>. Each assembly
/// with UI strings (the shell, the modules) adds its resources once with <see cref="Register"/>.
/// </summary>
public sealed class OdLocalization : INotifyPropertyChanged
{
private ResourceManager[] _resources = [];
private OdLocalization()
{
}
public event EventHandler? CultureChanged;
public event PropertyChangedEventHandler? PropertyChanged;
/// <summary>The instance XAML binds to.</summary>
public static OdLocalization Instance { get; } = new();
/// <summary>The UI language in effect.</summary>
public CultureInfo Culture { get; private set; } = CultureInfo.CurrentUICulture;
/// <summary>The Windows display language, captured before any <see cref="SetCulture"/>: what "follow Windows" means.</summary>
public CultureInfo SystemCulture { get; } = CultureInfo.CurrentUICulture;
/// <summary>The string for <paramref name="key"/> in the current language; the key itself when no resources have it.</summary>
public string this[string key] => Array.ConvertAll(_resources, resources => resources.GetString(key, Culture))
.FirstOrDefault(text => text is not null) ?? key;
public static string Get(string key) => Instance[key];
/// <summary>Fills a format string; numbers and dates follow the regional format, not the UI language.</summary>
public static string Format(string key, params object?[] args) =>
string.Format(CultureInfo.CurrentCulture, Instance[key], args);
/// <summary>The culture a <c>Language</c> setting names; empty or unknown names follow Windows.</summary>
public CultureInfo ResolveCulture(string? name)
{
if (string.IsNullOrWhiteSpace(name))
{
return SystemCulture;
}
try
{
return CultureInfo.GetCultureInfo(name.Trim(), predefinedOnly: true);
}
catch (CultureNotFoundException)
{
return SystemCulture;
}
}
/// <summary>Adds an assembly's string table; earlier tables win when two share a key.</summary>
public void Register(ResourceManager resources)
{
ArgumentNullException.ThrowIfNull(resources);
if (!_resources.Contains(resources))
{
_resources = [.. _resources, resources];
}
}
/// <summary>
/// Switches the UI language and refreshes every bound string. Only the UI culture changes:
/// number and date formats keep following the user's regional settings.
/// </summary>
public void SetCulture(CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(culture);
if (string.Equals(culture.Name, Culture.Name, StringComparison.OrdinalIgnoreCase))
{
return;
}
Culture = culture;
CultureInfo.CurrentUICulture = culture;
CultureInfo.DefaultThreadCurrentUICulture = culture;
TagOpenWindows();
// "Item[]" tells WPF to re-read every indexer binding on this source.
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Item[]"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Culture)));
CultureChanged?.Invoke(this, EventArgs.Empty);
}
/// <summary>
/// Tags every window, open now or later, with the UI language (xml:lang): WPF picks Han glyph
/// shapes from it, so Japanese text is not drawn with Chinese glyphs.
/// </summary>
public void TrackWindowLanguage()
{
EventManager.RegisterClassHandler(
typeof(Window),
FrameworkElement.LoadedEvent,
new RoutedEventHandler((sender, _) =>
{
if (sender is Window window)
{
window.Language = XmlLanguage.GetLanguage(Culture.IetfLanguageTag);
}
}));
TagOpenWindows();
}
private void TagOpenWindows()
{
if (Application.Current is not { } app)
{
return;
}
var language = XmlLanguage.GetLanguage(Culture.IetfLanguageTag);
foreach (Window window in app.Windows)
{
window.Language = language;
}
}
}
+34
View File
@@ -0,0 +1,34 @@
using System.Windows;
namespace OmniDeck.Core.Modules;
/// <summary>
/// The module contract (docs/ARCHITECTURE.md §2). The shell's module host calls these in order; the
/// RAM governor decides when to suspend and hibernate. Durable state belongs in services, not views,
/// so hibernating a view never loses it.
/// </summary>
public interface IOdModule
{
OdModuleInfo Info { get; }
/// <summary>Called once per process lifetime, before the first view.</summary>
Task InitializeAsync(IOdModuleContext context);
/// <summary>Called on first open and again after every hibernation.</summary>
FrameworkElement CreateView();
/// <summary>The module became visible.</summary>
Task ActivateAsync();
/// <summary>Returning <see langword="false"/> pins the module, for example while media plays.</summary>
Task<bool> CanSuspendAsync();
/// <summary>Hidden or under memory pressure: drop caches, charts and bitmaps; stop timers and animations.</summary>
Task SuspendAsync(OdSuspendReason reason);
/// <summary>Release everything, view included; keep only a tiny state blob.</summary>
Task HibernateAsync();
/// <summary>The user closed the module.</summary>
Task CloseAsync();
}
@@ -0,0 +1,19 @@
using Serilog;
namespace OmniDeck.Core.Modules;
/// <summary>What the shell gives each module; modules never construct these themselves.</summary>
public interface IOdModuleContext
{
string ModuleId { get; }
/// <summary>The settings document that belongs to this module.</summary>
IOdModuleSettings Settings { get; }
ILogger Log { get; }
TimeProvider Time { get; }
/// <summary>Windows notifications, raised from the tray icon so they work while minimized.</summary>
IOdNotifier Notifier { get; }
}
@@ -0,0 +1,13 @@
using System.Text.Json.Serialization.Metadata;
namespace OmniDeck.Core.Modules;
/// <summary>One JSON document per module, kept in the <c>module_settings</c> table.</summary>
public interface IOdModuleSettings
{
/// <summary>The stored document, or <see langword="null"/> if there is none or it no longer parses.</summary>
T? Get<T>(JsonTypeInfo<T> typeInfo)
where T : class;
void Set<T>(T value, JsonTypeInfo<T> typeInfo);
}
+7
View File
@@ -0,0 +1,7 @@
namespace OmniDeck.Core.Modules;
/// <summary>Raises a Windows notification under OmniDeck's name.</summary>
public interface IOdNotifier
{
void Notify(string title, string message);
}
@@ -0,0 +1,26 @@
using System.Windows;
namespace OmniDeck.Core.Modules;
/// <summary>A module as <see cref="OdModuleHost"/> runs it: its state, its view while it has one, and when it was last seen.</summary>
public sealed class OdHostedModule
{
internal OdHostedModule(IOdModule module)
{
Module = module;
}
public IOdModule Module { get; }
public OdModuleInfo Info => Module.Info;
public OdModuleState State { get; internal set; } = OdModuleState.Created;
/// <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>When the module was last visible: the governor measures how long it has been hidden from here.</summary>
public DateTimeOffset LastActive { get; internal set; }
internal bool IsInitialized { get; set; }
}
@@ -0,0 +1,7 @@
using Serilog;
namespace OmniDeck.Core.Modules;
/// <summary>The context <see cref="OdModuleHost"/> hands a module when it initializes.</summary>
internal sealed record OdModuleContext(string ModuleId, IOdModuleSettings Settings, ILogger Log, TimeProvider Time, IOdNotifier Notifier)
: IOdModuleContext;
+208
View File
@@ -0,0 +1,208 @@
using System.Windows;
using OmniDeck.Core.Storage;
using Serilog;
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.
/// </summary>
public sealed class OdModuleHost : IDisposable
{
private readonly Dictionary<string, OdHostedModule> _byId;
private readonly OdDatabase _database;
private readonly ILogger _baseLog;
private readonly ILogger _log;
private readonly TimeProvider _time;
private readonly IOdNotifier _notifier;
private readonly SemaphoreSlim _gate = new(1, 1);
public OdModuleHost(IEnumerable<IOdModule> modules, OdDatabase database, ILogger log, TimeProvider time, IOdNotifier notifier)
{
ArgumentNullException.ThrowIfNull(modules);
ArgumentNullException.ThrowIfNull(log);
_database = database;
_baseLog = log;
_log = log.ForContext<OdModuleHost>();
_time = time;
_notifier = notifier;
Modules = [.. modules.Select(module => new OdHostedModule(module))];
// Throws on a repeated id: two modules would share one settings document.
_byId = Modules.ToDictionary(hosted => hosted.Info.Id, StringComparer.Ordinal);
}
public event EventHandler<OdModuleStateChangedEventArgs>? StateChanged;
/// <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>
public OdHostedModule? Current { get; private set; }
public OdHostedModule? Find(string moduleId) => _byId.GetValueOrDefault(moduleId);
/// <summary>
/// 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.
/// </summary>
public async Task<FrameworkElement> ShowAsync(string moduleId)
{
var hosted = Get(moduleId);
await _gate.WaitAsync();
try
{
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;
HideCurrent();
await hosted.Module.ActivateAsync();
Current = hosted;
hosted.LastActive = _time.GetUtcNow();
SetState(hosted, OdModuleState.Active);
return view;
}
finally
{
_gate.Release();
}
}
/// <summary>Hides the visible module while the shell shows one of its own pages.</summary>
public async Task HideAsync()
{
await _gate.WaitAsync();
try
{
HideCurrent();
}
finally
{
_gate.Release();
}
}
/// <summary>Suspends a hidden module; <see langword="false"/> when it is visible, already further down, or pinned.</summary>
public async Task<bool> SuspendAsync(string moduleId, OdSuspendReason reason)
{
var hosted = Get(moduleId);
await _gate.WaitAsync();
try
{
if (hosted.State != OdModuleState.Idle || !await hosted.Module.CanSuspendAsync())
{
return false;
}
await hosted.Module.SuspendAsync(reason);
SetState(hosted, OdModuleState.Suspended);
return true;
}
finally
{
_gate.Release();
}
}
/// <summary>Hibernates a hidden module and lets go of its view; <see langword="false"/> when it is visible, not running, or pinned.</summary>
public async Task<bool> HibernateAsync(string moduleId)
{
var hosted = Get(moduleId);
await _gate.WaitAsync();
try
{
if (hosted.State is not (OdModuleState.Idle or OdModuleState.Suspended) || !await hosted.Module.CanSuspendAsync())
{
return false;
}
await hosted.Module.HibernateAsync();
hosted.View = null;
SetState(hosted, OdModuleState.Hibernated);
return true;
}
finally
{
_gate.Release();
}
}
/// <summary>Closes a module at the user's request, visible or not; reopening it builds a new view.</summary>
public async Task CloseAsync(string moduleId)
{
var hosted = Get(moduleId);
await _gate.WaitAsync();
try
{
if (hosted.State is OdModuleState.Created or OdModuleState.Closed)
{
return;
}
await hosted.Module.CloseAsync();
hosted.View = null;
if (hosted == Current)
{
Current = null;
hosted.LastActive = _time.GetUtcNow();
}
SetState(hosted, OdModuleState.Closed);
}
finally
{
_gate.Release();
}
}
public void Dispose() => _gate.Dispose();
private OdHostedModule Get(string moduleId)
{
ArgumentNullException.ThrowIfNull(moduleId);
return _byId.TryGetValue(moduleId, out var hosted)
? hosted
: throw new ArgumentException($"No module has the id '{moduleId}'.", nameof(moduleId));
}
private OdModuleContext CreateContext(string moduleId) => new(
moduleId,
new OdModuleSettingsStore(_database, moduleId),
_baseLog.ForContext(Constants.SourceContextPropertyName, "Module." + moduleId),
_time,
_notifier);
private void HideCurrent()
{
if (Current is not { } previous)
{
return;
}
Current = null;
previous.LastActive = _time.GetUtcNow();
SetState(previous, OdModuleState.Idle);
}
private void SetState(OdHostedModule hosted, OdModuleState state)
{
var previous = hosted.State;
hosted.State = state;
_log.Debug("Module {ModuleId}: {Previous} -> {State}", hosted.Info.Id, previous, state);
StateChanged?.Invoke(this, new OdModuleStateChangedEventArgs(hosted, previous));
}
}
@@ -0,0 +1,9 @@
namespace OmniDeck.Core.Modules;
/// <summary>What the shell shows about a module.</summary>
/// <param name="Id">Stable identifier, also the settings key: <c>[a-z0-9-]</c>.</param>
/// <param name="NameKey">The resource key of the module's localized name.</param>
/// <param name="Icon">A WPF-UI <c>SymbolRegular</c> name such as <c>Clock24</c>; Core stays free of WPF-UI.</param>
/// <param name="CategoryKey">The resource key of the localized category the library shows under the name.</param>
/// <param name="RamClass">The governor's priority hint.</param>
public sealed record OdModuleInfo(string Id, string NameKey, string Icon, string CategoryKey, OdRamClass RamClass);
@@ -0,0 +1,39 @@
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Dapper;
using OmniDeck.Core.Storage;
namespace OmniDeck.Core.Modules;
/// <summary><see cref="IOdModuleSettings"/> for one module over the <c>module_settings</c> table.</summary>
public sealed class OdModuleSettingsStore(OdDatabase database, string moduleId) : IOdModuleSettings
{
public T? Get<T>(JsonTypeInfo<T> typeInfo)
where T : class
{
using var connection = database.Open();
var json = connection.ExecuteScalar<string?>("SELECT json FROM module_settings WHERE module_id = @moduleId", new { moduleId });
if (json is null)
{
return null;
}
try
{
return JsonSerializer.Deserialize(json, typeInfo);
}
catch (JsonException)
{
return null;
}
}
public void Set<T>(T value, JsonTypeInfo<T> typeInfo)
{
var json = JsonSerializer.Serialize(value, typeInfo);
using var connection = database.Open();
connection.Execute(
"INSERT INTO module_settings (module_id, json) VALUES (@moduleId, @json) ON CONFLICT (module_id) DO UPDATE SET json = excluded.json",
new { moduleId, json });
}
}
@@ -0,0 +1,23 @@
namespace OmniDeck.Core.Modules;
/// <summary>The governor's ladder (docs/RAM-GOVERNOR.md §1).</summary>
public enum OdModuleState
{
/// <summary>Known to the shell but never opened.</summary>
Created,
/// <summary>Visible, or interacted with.</summary>
Active,
/// <summary>Hidden for less than <c>IdleAfter</c>; still live.</summary>
Idle,
/// <summary>Hidden for longer: caches, timers and animations released.</summary>
Suspended,
/// <summary>View and everything else released; only a tiny state blob is kept.</summary>
Hibernated,
/// <summary>Closed by the user.</summary>
Closed,
}
@@ -0,0 +1,9 @@
namespace OmniDeck.Core.Modules;
/// <summary>A module moved to another rung of the state ladder.</summary>
public sealed class OdModuleStateChangedEventArgs(OdHostedModule module, OdModuleState previous) : EventArgs
{
public OdHostedModule Module { get; } = module;
public OdModuleState Previous { get; } = previous;
}
+8
View File
@@ -0,0 +1,8 @@
namespace OmniDeck.Core.Modules;
/// <summary>The governor's priority hint: heavy modules are demoted first at equal recency.</summary>
public enum OdRamClass
{
Light,
Heavy,
}
@@ -0,0 +1,14 @@
namespace OmniDeck.Core.Modules;
/// <summary>Why a module is being suspended.</summary>
public enum OdSuspendReason
{
/// <summary>It has been hidden for <c>IdleAfter</c>.</summary>
Hidden,
/// <summary>The governor needs memory back.</summary>
MemoryPressure,
/// <summary>The user asked, from the task-manager panel.</summary>
User,
}
@@ -0,0 +1,25 @@
using Microsoft.Extensions.DependencyInjection;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
namespace OmniDeck.Core;
/// <summary>Registers the UI-independent services. The app adds its own with <c>AddOmniDeckApp</c>.</summary>
public static class OdCoreServiceCollectionExtensions
{
public static IServiceCollection AddOmniDeckCore(this IServiceCollection services, OdDataRoot dataRoot, Serilog.ILogger log)
{
ArgumentNullException.ThrowIfNull(services);
services.AddSingleton(dataRoot);
services.AddSingleton(log);
services.AddSingleton(TimeProvider.System);
services.AddSingleton<IOdSettingsService, OdSettingsService>();
services.AddSingleton<OdDatabase>();
services.AddSingleton<IOdAppMeta, OdAppMeta>();
// Modules register as IOdModule; the app supplies IOdNotifier (the tray).
services.AddSingleton<OdModuleHost>();
return services;
}
}
+22
View File
@@ -3,6 +3,28 @@
<PropertyGroup>
<!-- Windows-only from the start: DPAPI, toasts and the update service land here in P1. -->
<TargetFramework>net10.0-windows</TargetFramework>
<!-- IOdModule.CreateView returns a FrameworkElement (docs/ARCHITECTURE.md §2). -->
<UseWPF>true</UseWPF>
<!-- Only for source-generated P/Invoke ([LibraryImport]); no hand-written unsafe code. -->
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<InternalsVisibleTo Include="OmniDeck.Tests" />
<!-- UseWPF drops System.IO from the implicit usings (Shapes.Path clash); Core draws no shapes. -->
<Using Include="System.IO" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dapper" Version="2.1.89" />
<PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.14" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="10.0.14" />
<PackageReference Include="Serilog" Version="4.4.0" />
</ItemGroup>
<!-- Schema migrations ship inside the assembly, ordered by their numeric prefix. -->
<ItemGroup>
<EmbeddedResource Include="Storage\Migrations\*.sql" />
</ItemGroup>
</Project>
@@ -0,0 +1,79 @@
using System.Runtime.InteropServices;
namespace OmniDeck.Core.Runtime;
/// <summary>
/// One OmniDeck per Windows session (docs/SPEC.md §2). The first instance owns a named mutex and
/// waits on a named event; a second instance sets the event, lets the first one take the foreground,
/// and exits.
/// </summary>
public sealed partial class OdSingleInstanceGuard : IDisposable
{
private const int AsfwAny = -1;
private readonly Mutex _mutex;
private readonly EventWaitHandle _activate;
private readonly ManualResetEvent _stop = new(initialState: false);
private Thread? _listener;
/// <summary>Claims the instance if no other OmniDeck holds it.</summary>
/// <param name="nameSuffix">Isolates tests from each other and from a running OmniDeck.</param>
public OdSingleInstanceGuard(string? nameSuffix = null)
{
var name = $@"Local\OmniDeck.SingleInstance{nameSuffix}";
_mutex = new Mutex(initiallyOwned: true, name, out var createdNew);
IsPrimaryInstance = createdNew;
_activate = new EventWaitHandle(initialState: false, EventResetMode.AutoReset, name + ".Activate");
}
public bool IsPrimaryInstance { get; }
/// <summary>From a second instance: asks the first one to show itself.</summary>
public void SignalPrimaryInstance()
{
AllowSetForegroundWindow(AsfwAny);
_activate.Set();
}
/// <summary>From the first instance: runs <paramref name="onActivate"/> whenever a second one starts.</summary>
public void StartListening(Action onActivate)
{
ArgumentNullException.ThrowIfNull(onActivate);
if (!IsPrimaryInstance || _listener is not null)
{
return;
}
_listener = new Thread(() =>
{
WaitHandle[] handles = [_activate, _stop];
while (WaitHandle.WaitAny(handles) == 0)
{
onActivate();
}
})
{
IsBackground = true,
Name = "OmniDeck single-instance listener",
};
_listener.Start();
}
public void Dispose()
{
_stop.Set();
_listener?.Join(TimeSpan.FromSeconds(2));
if (IsPrimaryInstance)
{
_mutex.ReleaseMutex();
}
_mutex.Dispose();
_activate.Dispose();
_stop.Dispose();
}
[LibraryImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
private static partial bool AllowSetForegroundWindow(int processId);
}
@@ -0,0 +1,79 @@
namespace OmniDeck.Core.Search;
/// <summary>
/// The command palette's matcher (docs/SPEC.md §2): every query character must appear in order;
/// matches at the start, after a word break and in a row score higher, so "cal" ranks
/// "Calculator" and "Calendar" above "Local time".
/// </summary>
public static class OdFuzzyMatcher
{
/// <summary>The match score, or <see langword="null"/> when <paramref name="text"/> does not match.</summary>
public static int? Score(string query, string text)
{
ArgumentNullException.ThrowIfNull(query);
ArgumentNullException.ThrowIfNull(text);
if (query.Length == 0)
{
return 0;
}
var score = 0;
var position = 0;
var previousMatch = -2;
foreach (var q in query)
{
var found = IndexOfIgnoreCase(text, q, position);
if (found < 0)
{
return null;
}
score += 1 + BoundaryBonus(text, found) + (found == previousMatch + 1 ? 3 : 0);
previousMatch = found;
position = found + 1;
}
// Shorter candidates win ties: "Timer" before "Timer settings" for "timer".
return (score * 100) - text.Length;
}
/// <summary>The items that match, best first; ties keep their original order.</summary>
public static IReadOnlyList<T> Rank<T>(string query, IEnumerable<T> items, Func<T, string> text)
{
ArgumentNullException.ThrowIfNull(query);
ArgumentNullException.ThrowIfNull(items);
ArgumentNullException.ThrowIfNull(text);
var trimmed = query.Trim();
return [.. items
.Select((item, index) => (item, index, score: Score(trimmed, text(item))))
.Where(x => x.score is not null)
.OrderByDescending(x => x.score)
.ThenBy(x => x.index)
.Select(x => x.item)];
}
private static int BoundaryBonus(string text, int index)
{
if (index == 0)
{
return 8;
}
var previous = text[index - 1];
return !char.IsLetterOrDigit(previous) || (char.IsUpper(text[index]) && char.IsLower(previous)) ? 5 : 0;
}
private static int IndexOfIgnoreCase(string text, char c, int start)
{
var lower = char.ToLowerInvariant(c);
for (var i = start; i < text.Length; i++)
{
if (char.ToLowerInvariant(text[i]) == lower)
{
return i;
}
}
return -1;
}
}
@@ -0,0 +1,13 @@
namespace OmniDeck.Core.Settings;
/// <summary>The app's settings: read anywhere, changed through <see cref="Update"/>, saved at once.</summary>
public interface IOdSettingsService
{
/// <summary>Raised after every change, with the new settings.</summary>
event EventHandler<OdSettingsChangedEventArgs>? Changed;
OdSettings Current { get; }
/// <summary>Applies <paramref name="change"/>, normalizes the result, saves it and raises <see cref="Changed"/>.</summary>
void Update(Func<OdSettings, OdSettings> change);
}
+89
View File
@@ -0,0 +1,89 @@
namespace OmniDeck.Core.Settings;
/// <summary>
/// The typed settings tree persisted to <c>settings.json</c> in the data root. Immutable: changes go
/// through <see cref="IOdSettingsService.Update"/> with a <c>with</c> expression.
/// </summary>
public sealed record OdSettings
{
/// <summary>The version of this file's shape, for future migrations.</summary>
public const int CurrentSchemaVersion = 1;
public int SchemaVersion { get; init; } = CurrentSchemaVersion;
/// <summary>UI culture name such as <c>en</c>; empty follows Windows.</summary>
public string Language { get; init; } = "";
public OdThemeMode Theme { get; init; } = OdThemeMode.System;
/// <summary>The UI preset: <c>Dynamic</c>, <c>Standard</c> or <c>Comfort</c> (docs/UI-MODES.md).</summary>
public string Preset { get; init; } = DefaultPreset;
/// <summary>Closing the main window keeps OmniDeck running in the tray.</summary>
public bool CloseToTray { get; init; } = true;
public bool StartWithWindows { get; init; }
/// <summary>The user's font-size slider, a factor on the preset's base size (0.85–1.4).</summary>
public double FontScale { get; init; } = 1.0;
/// <summary>Animations on or off; Windows' own "animation effects" switch can still turn them off.</summary>
public bool MotionEnabled { get; init; } = true;
/// <summary>An accent color as <c>#RRGGBB</c>; empty uses the Windows accent.</summary>
public string AccentColor { get; init; } = "";
/// <summary>
/// The modules pinned to the sidebar, in sidebar order. Record equality compares this list by
/// reference: change it by assigning a new list.
/// </summary>
public IReadOnlyList<string> PinnedModules { get; init; } = [];
internal const string DefaultPreset = "Standard";
internal static readonly string[] KnownPresets = ["Dynamic", "Standard", "Comfort"];
private static readonly System.Buffers.SearchValues<char> HexDigits = System.Buffers.SearchValues.Create("0123456789abcdefABCDEF");
/// <summary>Whether <paramref name="other"/> looks the same: theme, preset, font scale, motion and accent.</summary>
public bool LooksLike(OdSettings other)
{
ArgumentNullException.ThrowIfNull(other);
return Theme == other.Theme
&& string.Equals(Preset, other.Preset, StringComparison.Ordinal)
&& Math.Abs(FontScale - other.FontScale) < 0.0001
&& MotionEnabled == other.MotionEnabled
&& string.Equals(AccentColor, other.AccentColor, StringComparison.Ordinal);
}
/// <summary>Repairs values a hand-edited or older file may carry.</summary>
public OdSettings Normalized() => this with
{
SchemaVersion = CurrentSchemaVersion,
Language = string.IsNullOrWhiteSpace(Language) ? "" : Language.Trim(),
Theme = Enum.IsDefined(Theme) ? Theme : OdThemeMode.System,
Preset = KnownPresets.FirstOrDefault(p => string.Equals(p, Preset, StringComparison.OrdinalIgnoreCase)) ?? DefaultPreset,
FontScale = double.IsFinite(FontScale) ? Math.Clamp(FontScale, Theming.OdTokens.MinFontScale, Theming.OdTokens.MaxFontScale) : 1.0,
AccentColor = IsHexColor(AccentColor) ? AccentColor.ToUpperInvariant() : "",
PinnedModules = DistinctIds(PinnedModules),
};
private static bool IsHexColor(string? value) =>
value is { Length: 7 } && value[0] == '#' && !value.AsSpan(1).ContainsAnyExcept(HexDigits);
/// <summary>
/// Drops blank and repeated ids. A list that needs no repair comes back as the same instance, so
/// record equality (and with it "no change, no save") keeps working.
/// </summary>
private static IReadOnlyList<string> DistinctIds(IReadOnlyList<string>? ids)
{
if (ids is null)
{
return [];
}
string[] clean = [.. ids.Where(id => !string.IsNullOrWhiteSpace(id)).Select(id => id.Trim()).Distinct(StringComparer.Ordinal)];
return clean.SequenceEqual(ids, StringComparer.Ordinal) ? ids : clean;
}
}
@@ -0,0 +1,7 @@
namespace OmniDeck.Core.Settings;
/// <summary>Carries the settings as they are after a change.</summary>
public sealed class OdSettingsChangedEventArgs(OdSettings settings) : EventArgs
{
public OdSettings Settings { get; } = settings;
}
@@ -0,0 +1,8 @@
using System.Text.Json.Serialization;
namespace OmniDeck.Core.Settings;
/// <summary>Source-generated serializer for <see cref="OdSettings"/>: no reflection, readable output.</summary>
[JsonSourceGenerationOptions(WriteIndented = true, UseStringEnumConverter = true, PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(OdSettings))]
internal sealed partial class OdSettingsJsonContext : JsonSerializerContext;
@@ -0,0 +1,51 @@
using OmniDeck.Core.Storage;
using Serilog;
namespace OmniDeck.Core.Settings;
/// <summary>
/// <see cref="IOdSettingsService"/> over <c>settings.json</c> in the data root. A missing file means
/// defaults; a corrupt one is set aside (see <see cref="OdJsonFile"/>) and defaults take over.
/// </summary>
public sealed class OdSettingsService : IOdSettingsService
{
private readonly string _path;
private readonly Lock _gate = new();
public OdSettingsService(OdDataRoot dataRoot, ILogger log)
{
ArgumentNullException.ThrowIfNull(dataRoot);
ArgumentNullException.ThrowIfNull(log);
_path = dataRoot.SettingsFile;
var loaded = OdJsonFile.Read(_path, OdSettingsJsonContext.Default.OdSettings, out var status);
if (status == OdJsonReadStatus.Quarantined)
{
log.ForContext<OdSettingsService>().Warning("settings.json could not be read; it was set aside and defaults are in use");
}
Current = (loaded ?? new OdSettings()).Normalized();
}
public event EventHandler<OdSettingsChangedEventArgs>? Changed;
public OdSettings Current { get; private set; }
public void Update(Func<OdSettings, OdSettings> change)
{
ArgumentNullException.ThrowIfNull(change);
OdSettings next;
lock (_gate)
{
next = change(Current).Normalized();
if (next == Current)
{
return;
}
OdJsonFile.Write(_path, next, OdSettingsJsonContext.Default.OdSettings);
Current = next;
}
Changed?.Invoke(this, new OdSettingsChangedEventArgs(next));
}
}
+12
View File
@@ -0,0 +1,12 @@
namespace OmniDeck.Core.Settings;
/// <summary>The dark/light axis, independent of the UI preset (docs/UI-MODES.md §6).</summary>
public enum OdThemeMode
{
/// <summary>Follow the Windows app mode (the default).</summary>
System,
Light,
Dark,
}
+9
View File
@@ -0,0 +1,9 @@
namespace OmniDeck.Core.Storage;
/// <summary>App-wide facts kept in the database rather than in settings, such as the legal acknowledgment.</summary>
public interface IOdAppMeta
{
string? Get(string key);
void Set(string key, string value);
}
@@ -0,0 +1,5 @@
-- App-wide key/value facts: the schema version and the legal acknowledgment (docs/ARCHITECTURE.md §5).
CREATE TABLE IF NOT EXISTS app_meta (
key TEXT NOT NULL PRIMARY KEY,
value TEXT NOT NULL
) WITHOUT ROWID;
@@ -0,0 +1,5 @@
-- One JSON document per module: the "settings section" IOdModuleContext hands each module.
CREATE TABLE IF NOT EXISTS module_settings (
module_id TEXT NOT NULL PRIMARY KEY,
json TEXT NOT NULL
) WITHOUT ROWID;
+23
View File
@@ -0,0 +1,23 @@
using Dapper;
namespace OmniDeck.Core.Storage;
/// <summary><see cref="IOdAppMeta"/> over the <c>app_meta</c> table.</summary>
public sealed class OdAppMeta(OdDatabase database) : IOdAppMeta
{
public string? Get(string key)
{
using var connection = database.Open();
return connection.ExecuteScalar<string?>("SELECT value FROM app_meta WHERE key = @key", new { key });
}
public void Set(string key, string value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(key);
ArgumentNullException.ThrowIfNull(value);
using var connection = database.Open();
connection.Execute(
"INSERT INTO app_meta (key, value) VALUES (@key, @value) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
new { key, value });
}
}
@@ -0,0 +1,16 @@
namespace OmniDeck.Core.Storage;
/// <summary>The keys of <c>app_meta</c>.</summary>
public static class OdAppMetaKeys
{
public const string SchemaVersion = "schema_version";
/// <summary>The legal-document version the user acknowledged (docs/SPEC.md §2).</summary>
public const string LegalAcknowledgedVersion = "legal.acknowledged_version";
/// <summary>When it was acknowledged, as an ISO 8601 UTC timestamp.</summary>
public const string LegalAcknowledgedAt = "legal.acknowledged_at";
/// <summary>Set once the user was told that closing the window keeps OmniDeck in the tray.</summary>
public const string TrayHintShown = "shell.tray_hint_shown";
}
@@ -0,0 +1,36 @@
using System.Globalization;
using System.Reflection;
namespace OmniDeck.Core.Storage;
/// <summary>
/// The core schema: <c>Storage/Migrations/NNNN_name.sql</c> files embedded in this assembly. A new
/// step is a new file with the next number; shipped files never change.
/// </summary>
public static class OdCoreMigrations
{
private const string Prefix = "OmniDeck.Core.Storage.Migrations.";
public static IReadOnlyList<OdMigration> All { get; } = Load(typeof(OdCoreMigrations).Assembly);
internal static IReadOnlyList<OdMigration> Load(Assembly assembly)
{
var migrations = new List<OdMigration>();
foreach (var resource in assembly.GetManifestResourceNames())
{
if (!resource.StartsWith(Prefix, StringComparison.Ordinal) || !resource.EndsWith(".sql", StringComparison.Ordinal))
{
continue;
}
var fileName = resource[Prefix.Length..^".sql".Length];
var underscore = fileName.IndexOf('_', StringComparison.Ordinal);
var version = int.Parse(fileName[..underscore], NumberStyles.None, CultureInfo.InvariantCulture);
using var stream = assembly.GetManifestResourceStream(resource)!;
using var reader = new StreamReader(stream);
migrations.Add(new OdMigration(version, fileName[(underscore + 1)..], reader.ReadToEnd()));
}
return [.. migrations.OrderBy(m => m.Version)];
}
}
+71
View File
@@ -0,0 +1,71 @@
namespace OmniDeck.Core.Storage;
/// <summary>
/// The data root, <c>%LocalAppData%\OmniDeck.Data</c>: everything the user owns lives here (settings,
/// database, WebView2 profiles, logs, bug reports). It is a sibling of Velopack's install folder
/// <c>%LocalAppData%\OmniDeck</c>, which is wiped on uninstall and reinstall, so nothing here may ever
/// move into it (docs/ARCHITECTURE.md §5).
/// </summary>
public sealed class OdDataRoot
{
/// <summary>The data root's folder name under <c>%LocalAppData%</c>.</summary>
public const string FolderName = "OmniDeck.Data";
/// <summary>Velopack's install folder name, which the data root must never be.</summary>
private const string InstallFolderName = "OmniDeck";
public OdDataRoot(string root)
{
ArgumentException.ThrowIfNullOrWhiteSpace(root);
Root = Path.GetFullPath(root);
if (string.Equals(Path.GetFileName(Path.TrimEndingDirectorySeparator(Root)), InstallFolderName, StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("The data root must not be Velopack's install folder.", nameof(root));
}
}
/// <summary>The real data root of the signed-in user.</summary>
public static OdDataRoot Default { get; } = new(Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), FolderName));
public string Root { get; }
public string SettingsFile => Path.Combine(Root, "settings.json");
public string DatabaseFile => Path.Combine(Root, "omnideck.db");
public string LogsDirectory => Path.Combine(Root, "logs");
public string ReportsDirectory => Path.Combine(Root, "reports");
public string WebView2Directory => Path.Combine(Root, "WebView2");
/// <summary>Creates the root and the folders the app writes to from the first second.</summary>
public void EnsureCreated()
{
Directory.CreateDirectory(Root);
Directory.CreateDirectory(LogsDirectory);
}
/// <summary>
/// Deletes the whole data root. Called from Velopack's uninstall hook, as the privacy policy
/// promises; it must never throw, because a failing hook would leave the uninstall half done.
/// </summary>
/// <returns><see langword="true"/> when nothing is left behind.</returns>
public bool TryDelete()
{
try
{
if (Directory.Exists(Root))
{
Directory.Delete(Root, recursive: true);
}
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
return false;
}
}
}
+91
View File
@@ -0,0 +1,91 @@
using System.Globalization;
using Dapper;
using Microsoft.Data.Sqlite;
namespace OmniDeck.Core.Storage;
/// <summary>
/// <c>omnideck.db</c> in the data root: SQLite through Dapper (docs/ARCHITECTURE.md §5). Hands out
/// open connections and brings the schema up to date with ordered, idempotent migrations.
/// </summary>
public sealed class OdDatabase
{
private readonly string _connectionString;
public OdDatabase(OdDataRoot dataRoot)
: this(dataRoot?.DatabaseFile ?? throw new ArgumentNullException(nameof(dataRoot)), pooling: true)
{
}
/// <summary>A database at an explicit path.</summary>
/// <param name="path">The database file.</param>
/// <param name="pooling">Off in tests, so their temp folders can be deleted right away.</param>
internal OdDatabase(string path, bool pooling)
{
_connectionString = new SqliteConnectionStringBuilder
{
DataSource = path,
Mode = SqliteOpenMode.ReadWriteCreate,
Pooling = pooling,
}.ToString();
}
/// <summary>Releases every pooled connection, and with it the file; called on exit.</summary>
public static void ReleaseAll() => SqliteConnection.ClearAllPools();
public SqliteConnection Open()
{
var connection = new SqliteConnection(_connectionString);
connection.Open();
connection.Execute("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
return connection;
}
/// <summary>The schema version recorded in <c>app_meta</c>; 0 for an empty database.</summary>
public int SchemaVersion()
{
using var connection = Open();
return ReadSchemaVersion(connection);
}
/// <summary>Applies every migration newer than the current schema, each in its own transaction.</summary>
/// <returns>How many migrations ran.</returns>
public int Migrate(IReadOnlyList<OdMigration> migrations)
{
ArgumentNullException.ThrowIfNull(migrations);
var duplicate = migrations.GroupBy(m => m.Version).FirstOrDefault(g => g.Count() > 1);
if (duplicate is not null)
{
throw new ArgumentException($"Two migrations share version {duplicate.Key}.", nameof(migrations));
}
using var connection = Open();
var current = ReadSchemaVersion(connection);
var applied = 0;
foreach (var migration in migrations.Where(m => m.Version > current).OrderBy(m => m.Version))
{
using var transaction = connection.BeginTransaction();
connection.Execute(migration.Sql, transaction: transaction);
connection.Execute(
"INSERT INTO app_meta (key, value) VALUES (@key, @value) ON CONFLICT (key) DO UPDATE SET value = excluded.value",
new { key = OdAppMetaKeys.SchemaVersion, value = migration.Version.ToString(CultureInfo.InvariantCulture) },
transaction);
transaction.Commit();
applied++;
}
return applied;
}
private static int ReadSchemaVersion(SqliteConnection connection)
{
var hasMeta = connection.ExecuteScalar<long>("SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'app_meta'") > 0;
if (!hasMeta)
{
return 0;
}
var value = connection.ExecuteScalar<string?>("SELECT value FROM app_meta WHERE key = @key", new { key = OdAppMetaKeys.SchemaVersion });
return value is null ? 0 : int.Parse(value, NumberStyles.None, CultureInfo.InvariantCulture);
}
}
+71
View File
@@ -0,0 +1,71 @@
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace OmniDeck.Core.Storage;
/// <summary>
/// Small JSON files under the data root: written atomically (a temp file next to the target, then a
/// rename), so a crash or power loss never leaves half a file; read leniently, so a corrupt file is
/// set aside for inspection instead of crashing the app.
/// </summary>
public static class OdJsonFile
{
public static T? Read<T>(string path, JsonTypeInfo<T> typeInfo, out OdJsonReadStatus status)
where T : class
{
ArgumentNullException.ThrowIfNull(typeInfo);
if (!File.Exists(path))
{
status = OdJsonReadStatus.Missing;
return null;
}
try
{
using var stream = File.OpenRead(path);
var value = JsonSerializer.Deserialize(stream, typeInfo);
if (value is not null)
{
status = OdJsonReadStatus.Loaded;
return value;
}
}
catch (JsonException)
{
// Falls through to the quarantine below.
}
Quarantine(path);
status = OdJsonReadStatus.Quarantined;
return null;
}
public static void Write<T>(string path, T value, JsonTypeInfo<T> typeInfo)
{
ArgumentNullException.ThrowIfNull(typeInfo);
var directory = Path.GetDirectoryName(Path.GetFullPath(path))!;
Directory.CreateDirectory(directory);
var temp = Path.Combine(directory, $".{Path.GetFileName(path)}.{Guid.NewGuid():N}.tmp");
try
{
using (var stream = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 4096, FileOptions.WriteThrough))
{
JsonSerializer.Serialize(stream, value, typeInfo);
}
File.Move(temp, path, overwrite: true);
}
finally
{
File.Delete(temp);
}
}
private static void Quarantine(string path)
{
var stamp = DateTime.UtcNow.ToString("yyyyMMddHHmmss", CultureInfo.InvariantCulture);
var target = Path.ChangeExtension(path, $".corrupt-{stamp}.json");
File.Move(path, target, overwrite: true);
}
}
@@ -0,0 +1,14 @@
namespace OmniDeck.Core.Storage;
/// <summary>The outcome of <see cref="OdJsonFile.Read{T}"/>.</summary>
public enum OdJsonReadStatus
{
/// <summary>The file was read.</summary>
Loaded,
/// <summary>There was no file.</summary>
Missing,
/// <summary>The file could not be parsed and was renamed to <c>*.corrupt-&lt;timestamp&gt;.json</c>.</summary>
Quarantined,
}
+4
View File
@@ -0,0 +1,4 @@
namespace OmniDeck.Core.Storage;
/// <summary>One schema step: applied once, in <see cref="Version"/> order, inside a transaction.</summary>
public sealed record OdMigration(int Version, string Name, string Sql);
+33
View File
@@ -0,0 +1,33 @@
namespace OmniDeck.Core.Theming;
/// <summary>
/// One column of the token table in docs/UI-MODES.md §2: the base values a UI preset starts from
/// before the user's overrides and the Windows text size are applied (see <see cref="OdTokens"/>).
/// </summary>
public sealed record OdPreset(
string Name,
double FontBase,
double FontScale,
double Density,
double HitTargetMin,
double CornerRadius,
int MotionMilliseconds,
double ChartLineWeight,
int NavMaxVisibleItems,
bool NavShowLabels)
{
/// <summary>Dense, vivid, animated.</summary>
public static readonly OdPreset Dynamic = new("Dynamic", 13.5, 1.35, 4, 32, 8, 180, 1.5, 0, NavShowLabels: false);
/// <summary>The default, balanced.</summary>
public static readonly OdPreset Standard = new("Standard", 15.5, 1.30, 6, 36, 6, 100, 2, 0, NavShowLabels: true);
/// <summary>Large type, calm, no motion.</summary>
public static readonly OdPreset Comfort = new("Comfort", 19, 1.25, 10, 44, 6, 0, 3, 6, NavShowLabels: true);
public static IReadOnlyList<OdPreset> All { get; } = [Dynamic, Standard, Comfort];
/// <summary>The preset with this name, or <see cref="Standard"/>.</summary>
public static OdPreset FromName(string? name) =>
All.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)) ?? Standard;
}
+30
View File
@@ -0,0 +1,30 @@
namespace OmniDeck.Core.Theming;
/// <summary>
/// The resource keys of the <c>Od.*</c> tokens. Views consume them through <c>DynamicResource</c>;
/// a literal font size, padding, radius or animation duration in a module view is a CI failure.
/// </summary>
public static class OdTokenKeys
{
public const string FontBase = "Od.Font.Base";
public const string FontH1 = "Od.Font.H1";
public const string FontH2 = "Od.Font.H2";
public const string FontCaption = "Od.Font.Caption";
public const string Density = "Od.Density";
public const string PaddingControl = "Od.Padding.Control";
public const string PaddingCard = "Od.Padding.Card";
public const string MarginItem = "Od.Margin.Item";
/// <summary>The gap after a tile in a wrapping grid, such as the module library.</summary>
public const string MarginTile = "Od.Margin.Tile";
public const string HitTargetMin = "Od.HitTarget.Min";
public const string CornerRadius = "Od.Corner.Radius";
public const string MotionDuration = "Od.Motion.Duration";
public const string ChartLineWeight = "Od.Chart.LineWeight";
public const string NavMaxVisibleItems = "Od.Nav.MaxVisibleItems";
public const string NavShowLabels = "Od.Nav.ShowLabels";
/// <summary>Marks the preset dictionary inside the merged dictionaries; its value is the preset name.</summary>
public const string PresetMarker = "Od.Preset";
}
+54
View File
@@ -0,0 +1,54 @@
namespace OmniDeck.Core.Theming;
/// <summary>
/// The resolved <c>Od.*</c> design tokens the shell publishes as resources (docs/UI-MODES.md). Plain
/// numbers, so the arithmetic is testable without WPF; the app turns them into <c>Thickness</c>,
/// <c>CornerRadius</c> and <c>Duration</c> values.
/// </summary>
public sealed record OdTokens(
string PresetName,
double FontBase,
double FontH1,
double FontH2,
double FontCaption,
double Density,
double HitTargetMin,
double CornerRadius,
int MotionMilliseconds,
double ChartLineWeight,
int NavMaxVisibleItems,
bool NavShowLabels)
{
/// <summary>The range of the user's font-size slider (docs/UI-MODES.md §3).</summary>
public const double MinFontScale = 0.85;
public const double MaxFontScale = 1.4;
/// <summary>Windows text size runs from 100 % to 225 %.</summary>
public const double MaxTextScale = 2.25;
/// <summary>
/// Applies the user's font scale and the Windows text size on top of <paramref name="preset"/>
/// (docs/UI-MODES.md §3–4). Motion is off when the user or Windows turned it off, or the preset has none.
/// </summary>
public static OdTokens Compute(OdPreset preset, double textScale, double fontScale, bool motionEnabled)
{
ArgumentNullException.ThrowIfNull(preset);
var size = preset.FontBase * Math.Clamp(fontScale, MinFontScale, MaxFontScale) * Math.Clamp(textScale, 1, MaxTextScale);
return new OdTokens(
preset.Name,
FontBase: Round(size),
FontH1: Round(size * preset.FontScale * preset.FontScale),
FontH2: Round(size * preset.FontScale),
FontCaption: Round(size * 0.85),
preset.Density,
preset.HitTargetMin,
preset.CornerRadius,
MotionMilliseconds: motionEnabled ? preset.MotionMilliseconds : 0,
preset.ChartLineWeight,
preset.NavMaxVisibleItems,
preset.NavShowLabels);
}
private static double Round(double value) => Math.Round(value, 2, MidpointRounding.AwayFromZero);
}
@@ -0,0 +1,60 @@
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using OmniDeck.App;
using OmniDeck.App.Composition;
using OmniDeck.App.Diagnostics;
using OmniDeck.App.Shell;
using OmniDeck.Core;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
using Serilog.Core;
namespace OmniDeck.Tests.Composition;
public sealed class OdCompositionTests
{
[Fact]
public void Container_ValidatesOnBuild()
{
using var temp = new OdTempDirectory();
var services = new ServiceCollection()
.AddOmniDeckCore(new OdDataRoot(temp.Path), Logger.None)
.AddOmniDeckApp();
using var provider = services.BuildServiceProvider(new ServiceProviderOptions { ValidateOnBuild = true, ValidateScopes = true });
Assert.NotNull(provider.GetRequiredService<OdCrashHandler>());
Assert.Same(provider.GetRequiredService<OdTrayNotifier>(), provider.GetRequiredService<IOdNotifier>());
}
[Fact]
public void Core_DoesNotDependOnTheShell()
{
var references = typeof(OdDataRoot).Assembly.GetReferencedAssemblies().Select(a => a.Name).ToList();
Assert.DoesNotContain(typeof(OdApp).Assembly.GetName().Name, references, StringComparer.Ordinal);
Assert.DoesNotContain("Velopack", references, StringComparer.Ordinal);
Assert.DoesNotContain("Wpf.Ui", references, StringComparer.Ordinal);
}
[Fact]
public void SupportCode_IsStableForTheSameFailure()
{
var when = new DateTimeOffset(2026, 10, 30, 14, 5, 0, TimeSpan.FromHours(7));
var exception = new InvalidOperationException("boom");
var code = OdCrashHandler.SupportCode(exception, when);
Assert.Equal(code, OdCrashHandler.SupportCode(new InvalidOperationException("boom"), when));
Assert.Matches(@"^261030-1405-[0-9A-F]{4}$", code);
Assert.NotEqual(code, OdCrashHandler.SupportCode(new InvalidOperationException("other"), when), StringComparer.Ordinal);
}
[Fact]
public void Program_IsTheEntryPoint()
{
Assert.Equal("Program", typeof(OdApp).Assembly.EntryPoint?.DeclaringType?.Name);
Assert.Null(typeof(OdApp).GetMethod("Main", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic));
}
}
@@ -0,0 +1,93 @@
using OmniDeck.App.Diagnostics;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
using Serilog.Core;
using Serilog.Events;
namespace OmniDeck.Tests.Diagnostics;
public sealed class OdDiagnosticsTests
{
[Fact]
public void Logger_WritesDailyFilesUnderTheDataRoot()
{
using var temp = new OdTempDirectory();
var root = new OdDataRoot(temp.Path);
root.EnsureCreated();
using (var logger = (Logger)OdLogging.CreateLogger(root))
{
logger.Information("hello {Name}", "OmniDeck");
}
var file = Assert.Single(Directory.GetFiles(root.LogsDirectory, "omnideck-*.log"));
Assert.Contains("[INF]", File.ReadAllText(file), StringComparison.Ordinal);
Assert.Contains("hello OmniDeck", File.ReadAllText(file), StringComparison.Ordinal);
}
[Fact]
public void UiException_IsLoggedAndShownWithItsSupportCode()
{
var sink = new ListSink();
var presenter = new RecordingPresenter();
var handler = new OdCrashHandler(new LoggerConfigurationFor(sink).Logger, presenter, TimeProvider.System);
var code = handler.HandleUiException(new InvalidOperationException("boom"));
var shown = Assert.Single(presenter.Messages);
Assert.Contains(code, shown, StringComparison.Ordinal);
Assert.Contains("boom", shown, StringComparison.Ordinal);
Assert.Equal(LogEventLevel.Error, Assert.Single(sink.Events).Level);
}
[Fact]
public void AFailureWhileShowing_IsLoggedButNotStacked()
{
var presenter = new RecordingPresenter();
var sink = new ListSink();
var handler = new OdCrashHandler(new LoggerConfigurationFor(sink).Logger, presenter, TimeProvider.System);
presenter.OnShow = () => handler.HandleUiException(new InvalidOperationException("inside the dialog"));
handler.HandleUiException(new InvalidOperationException("first"));
Assert.Single(presenter.Messages);
Assert.Equal(2, sink.Events.Count);
}
[Fact]
public void FatalAndUnobservedExceptions_AreLogged()
{
var sink = new ListSink();
var handler = new OdCrashHandler(new LoggerConfigurationFor(sink).Logger, new RecordingPresenter(), TimeProvider.System);
handler.HandleUnobserved(new TimeoutException("late"));
handler.HandleFatal(new InvalidOperationException("fatal"), terminating: false);
Assert.Equal(new[] { LogEventLevel.Error, LogEventLevel.Fatal }, sink.Events.Select(e => e.Level));
}
private sealed class RecordingPresenter : IOdErrorPresenter
{
public List<string> Messages { get; } = [];
public Action? OnShow { get; set; }
public void Show(string message)
{
Messages.Add(message);
OnShow?.Invoke();
}
}
private sealed class ListSink : ILogEventSink
{
public List<LogEvent> Events { get; } = [];
public void Emit(LogEvent logEvent) => Events.Add(logEvent);
}
private sealed class LoggerConfigurationFor(ILogEventSink sink)
{
public Serilog.ILogger Logger { get; } = new Serilog.LoggerConfiguration().MinimumLevel.Verbose().WriteTo.Sink(sink).CreateLogger();
}
}
@@ -0,0 +1,12 @@
namespace OmniDeck.Tests.Localization;
/// <summary>Tests that switch the process-wide UI culture run alone, after the parallel ones.</summary>
[CollectionDefinition(Name, DisableParallelization = true)]
public sealed class OdCultureCollection
{
public const string Name = "Culture";
private OdCultureCollection()
{
}
}
@@ -0,0 +1,90 @@
using System.ComponentModel;
using System.Globalization;
using System.Windows.Data;
using OmniDeck.App.Resources;
using OmniDeck.Core.Localization;
namespace OmniDeck.Tests.Localization;
[Collection(OdCultureCollection.Name)]
public sealed class OdLocalizationTests
{
[Fact]
public void Indexer_ReadsTheRegisteredTables_AndFallsBackToTheKey()
{
OdLocalization.Instance.Register(OdAppStrings.Resources);
Assert.Equal("OmniDeck", OdLocalization.Instance["App_Name"]);
Assert.Equal("Library", OdLocalization.Get("Shell_Library"));
Assert.Equal("No_Such_Key", OdLocalization.Get("No_Such_Key"));
Assert.Contains("boom", OdLocalization.Format("Error_StartFailed", "boom"), StringComparison.Ordinal);
}
[Theory]
[InlineData("", null)]
[InlineData(" ", null)]
[InlineData("not a culture", null)]
[InlineData("vi", "vi")]
[InlineData(" ja ", "ja")]
public void ResolveCulture_FollowsWindowsForEmptyOrUnknownNames(string setting, string? expected)
{
var culture = OdLocalization.Instance.ResolveCulture(setting);
Assert.Equal(expected ?? OdLocalization.Instance.SystemCulture.Name, culture.Name);
}
[Fact]
public void SetCulture_RefreshesBindings_OnlyWhenTheLanguageChanges()
{
var localization = OdLocalization.Instance;
var original = localization.Culture;
var properties = new List<string?>();
var cultureChanges = 0;
void OnPropertyChanged(object? sender, PropertyChangedEventArgs e) => properties.Add(e.PropertyName);
void OnCultureChanged(object? sender, EventArgs e)
{
cultureChanges++;
}
localization.PropertyChanged += OnPropertyChanged;
localization.CultureChanged += OnCultureChanged;
try
{
var other = string.Equals(original.Name, "ja", StringComparison.Ordinal) ? CultureInfo.GetCultureInfo("vi") : CultureInfo.GetCultureInfo("ja");
localization.SetCulture(other);
localization.SetCulture(other);
Assert.Equal(new[] { "Item[]", "Culture" }, properties, StringComparer.Ordinal);
Assert.Equal(1, cultureChanges);
Assert.Equal(other, CultureInfo.CurrentUICulture);
// Only English ships in P1: other languages fall back to the neutral strings.
Assert.Equal("Library", localization["Shell_Library"]);
}
finally
{
localization.PropertyChanged -= OnPropertyChanged;
localization.CultureChanged -= OnCultureChanged;
localization.SetCulture(original);
}
}
[Fact]
public void LocExtension_BindsToTheIndexer()
{
var binding = Assert.IsType<Binding>(new OdLocExtension("Shell_Library").ProvideValue(null!));
Assert.Equal("[Shell_Library]", binding.Path.Path);
Assert.Same(OdLocalization.Instance, binding.Source);
Assert.Equal(BindingMode.OneWay, binding.Mode);
Assert.Equal("", new OdLocExtension().Key);
}
[Fact]
public void TrackWindowLanguage_WorksWithoutAnApplication()
{
OdLocalization.Instance.TrackWindowLanguage();
Assert.NotNull(OdLocalization.Instance.Culture);
}
}
@@ -0,0 +1,66 @@
using System.Collections;
using System.Globalization;
using System.Resources;
using System.Text.RegularExpressions;
using OmniDeck.App.Resources;
using OmniDeck.Tests.TestSupport;
namespace OmniDeck.Tests.Localization;
/// <summary>
/// Cross-checks the shell's sources against <c>Resources/Strings.resx</c>: a key the UI uses must
/// exist, and a key nothing uses is dead weight for every translator.
/// </summary>
public sealed partial class OdResxKeyTests
{
private static readonly string[] ScannedProjects = ["OmniDeck.App", "OmniDeck.Core"];
private static readonly char[] Separators = [Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar];
[Fact]
public void EveryKeyTheShellUses_IsInTheStringTable()
{
var table = StringTable();
var missing = UsedKeys().Where(key => !table.ContainsKey(key)).ToList();
Assert.True(UsedKeys().Count > 15, "The scan should find the shell's keys.");
Assert.Empty(missing);
}
[Fact]
public void EveryKeyInTheStringTable_IsUsed()
{
var used = UsedKeys();
Assert.DoesNotContain(StringTable().Keys, key => !used.Contains(key));
}
private static Dictionary<string, string> StringTable()
{
// A manager of our own: disposing the set must not touch the one OdLocalization reads from.
var manager = new ResourceManager("OmniDeck.App.Resources.Strings", typeof(OdAppStrings).Assembly);
using var set = manager.GetResourceSet(CultureInfo.InvariantCulture, createIfNotExists: true, tryParents: true)
?? throw new InvalidOperationException("The shell's string table is missing.");
return set.Cast<DictionaryEntry>().ToDictionary(entry => (string)entry.Key, entry => (string)entry.Value!, StringComparer.Ordinal);
}
private static SortedSet<string> UsedKeys()
{
var keys = new SortedSet<string>(StringComparer.Ordinal);
var files = ScannedProjects
.SelectMany(project => Directory.EnumerateFiles(Path.Combine(OdRepository.Root, "src", project), "*.*", SearchOption.AllDirectories))
.Where(path => path.EndsWith(".cs", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".xaml", StringComparison.OrdinalIgnoreCase))
.Where(path => !path.Split(Separators).Any(part => part is "bin" or "obj"));
foreach (var match in files.SelectMany(File.ReadLines).SelectMany(line => UiKey().Matches(line)))
{
keys.Add(match.Groups["key"].Value);
}
return keys;
}
// {res:OdLoc Key} in XAML; OdLocalization.Get("Key"), .Format("Key", ...) and Localized("Key") in code.
[GeneratedRegex(@"(?:OdLoc\s+|(?:Get|Format|Localized)\("")(?<key>[A-Z][A-Za-z]*_[A-Za-z_]+)\b", RegexOptions.CultureInvariant, matchTimeoutMilliseconds: 2000)]
private static partial Regex UiKey();
}
@@ -0,0 +1,58 @@
using System.Windows;
using System.Windows.Controls;
using OmniDeck.Core.Modules;
namespace OmniDeck.Tests.Modules;
/// <summary>A module that records what the host asks of it.</summary>
public sealed class OdFakeModule(string id, OdRamClass ramClass = OdRamClass.Light) : IOdModule
{
public OdModuleInfo Info { get; } = new(id, "Module_" + id, "Apps24", "Test", ramClass);
public IList<string> Calls { get; } = [];
/// <summary>What <see cref="CanSuspendAsync"/> answers; false behaves like a playing media module.</summary>
public bool CanSuspend { get; set; } = true;
public IOdModuleContext? Context { get; private set; }
public Task InitializeAsync(IOdModuleContext context)
{
Context = context;
Calls.Add("init");
return Task.CompletedTask;
}
public FrameworkElement CreateView()
{
Calls.Add("view");
return new Border();
}
public async Task ActivateAsync()
{
// A real await, so the host's one-at-a-time gate is exercised across a dispatcher turn.
await Task.Yield();
Calls.Add("activate");
}
public Task<bool> CanSuspendAsync() => Task.FromResult(CanSuspend);
public Task SuspendAsync(OdSuspendReason reason)
{
Calls.Add("suspend:" + reason);
return Task.CompletedTask;
}
public Task HibernateAsync()
{
Calls.Add("hibernate");
return Task.CompletedTask;
}
public Task CloseAsync()
{
Calls.Add("close");
return Task.CompletedTask;
}
}
@@ -0,0 +1,11 @@
using OmniDeck.Core.Modules;
namespace OmniDeck.Tests.Modules;
/// <summary>Collects notifications instead of showing them.</summary>
public sealed class OdFakeNotifier : IOdNotifier
{
public IList<(string Title, string Message)> Shown { get; } = [];
public void Notify(string title, string message) => Shown.Add((title, message));
}
@@ -0,0 +1,188 @@
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Microsoft.Extensions.Time.Testing;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
using Serilog.Core;
namespace OmniDeck.Tests.Modules;
public sealed class OdModuleHostTests : IDisposable
{
private static readonly DateTimeOffset Start = new(2026, 10, 30, 8, 0, 0, TimeSpan.Zero);
private readonly OdTempDirectory _temp = new();
private readonly FakeTimeProvider _time = new(Start);
private readonly OdFakeModule _clock = new("clock");
private readonly OdFakeModule _timer = new("timer");
public void Dispose() => _temp.Dispose();
[Fact]
public void Show_InitializesOnce_BuildsTheView_AndActivates() => OdSta.Run(async () =>
{
using var host = NewHost();
var view = await host.ShowAsync("clock");
var again = await host.ShowAsync("clock");
Assert.Same(view, again);
Assert.Equal(new[] { "init", "view", "activate" }, _clock.Calls, StringComparer.Ordinal);
Assert.Equal(OdModuleState.Active, host.Find("clock")?.State);
Assert.Same(host.Find("clock"), host.Current);
Assert.Equal("clock", _clock.Context?.ModuleId);
Assert.Same(_time, _clock.Context?.Time);
});
[Fact]
public void Show_HidesThePreviousModule() => OdSta.Run(async () =>
{
using var host = NewHost();
var changes = new List<string>();
host.StateChanged += (_, e) => changes.Add($"{e.Module.Info.Id}:{e.Previous}>{e.Module.State}");
await host.ShowAsync("clock");
_time.Advance(TimeSpan.FromMinutes(3));
await host.ShowAsync("timer");
var clock = host.Find("clock")!;
Assert.Equal(OdModuleState.Idle, clock.State);
Assert.Equal(Start.AddMinutes(3), clock.LastActive);
Assert.NotNull(clock.View);
Assert.Same(host.Find("timer"), host.Current);
Assert.Equal(new[] { "clock:Created>Active", "clock:Active>Idle", "timer:Created>Active" }, changes, StringComparer.Ordinal);
});
[Fact]
public void Hide_LeavesNoModuleVisible() => OdSta.Run(async () =>
{
using var host = NewHost();
await host.ShowAsync("clock");
await host.HideAsync();
await host.HideAsync();
Assert.Null(host.Current);
Assert.Equal(OdModuleState.Idle, host.Find("clock")?.State);
});
[Fact]
public void Suspend_OnlyMovesHiddenModules() => OdSta.Run(async () =>
{
using var host = NewHost();
await host.ShowAsync("clock");
Assert.False(await host.SuspendAsync("clock", OdSuspendReason.Hidden));
Assert.False(await host.SuspendAsync("timer", OdSuspendReason.Hidden));
await host.ShowAsync("timer");
Assert.True(await host.SuspendAsync("clock", OdSuspendReason.Hidden));
Assert.False(await host.SuspendAsync("clock", OdSuspendReason.MemoryPressure));
Assert.Equal(OdModuleState.Suspended, host.Find("clock")?.State);
Assert.Equal(new[] { "init", "view", "activate", "suspend:Hidden" }, _clock.Calls, StringComparer.Ordinal);
});
[Fact]
public void PinnedModules_AreNeitherSuspendedNorHibernated() => OdSta.Run(async () =>
{
using var host = NewHost();
await host.ShowAsync("clock");
await host.ShowAsync("timer");
_clock.CanSuspend = false;
Assert.False(await host.SuspendAsync("clock", OdSuspendReason.MemoryPressure));
Assert.False(await host.HibernateAsync("clock"));
Assert.Equal(OdModuleState.Idle, host.Find("clock")?.State);
Assert.NotNull(host.Find("clock")?.View);
});
[Fact]
public void Hibernate_DropsTheView_AndShowRebuildsIt() => OdSta.Run(async () =>
{
using var host = NewHost();
var first = await host.ShowAsync("clock");
await host.ShowAsync("timer");
await host.SuspendAsync("clock", OdSuspendReason.Hidden);
Assert.True(await host.HibernateAsync("clock"));
Assert.Null(host.Find("clock")?.View);
Assert.Equal(OdModuleState.Hibernated, host.Find("clock")?.State);
Assert.False(await host.HibernateAsync("clock"));
var second = await host.ShowAsync("clock");
Assert.NotSame(first, second);
Assert.Equal(new[] { "init", "view", "activate", "suspend:Hidden", "hibernate", "view", "activate" }, _clock.Calls, StringComparer.Ordinal);
});
[Fact]
public void Close_ReleasesTheVisibleModule_AndReopeningSkipsInitialization() => OdSta.Run(async () =>
{
using var host = NewHost();
await host.ShowAsync("clock");
_time.Advance(TimeSpan.FromSeconds(30));
await host.CloseAsync("clock");
await host.CloseAsync("clock");
await host.CloseAsync("timer");
var clock = host.Find("clock")!;
Assert.Null(host.Current);
Assert.Null(clock.View);
Assert.Equal(OdModuleState.Closed, clock.State);
Assert.Equal(Start.AddSeconds(30), clock.LastActive);
Assert.Empty(_timer.Calls);
await host.ShowAsync("clock");
Assert.Equal(new[] { "init", "view", "activate", "close", "view", "activate" }, _clock.Calls, StringComparer.Ordinal);
});
[Fact]
public void UnknownModules_AreRejected() => OdSta.Run(async () =>
{
using var host = NewHost();
await Assert.ThrowsAsync<ArgumentException>(() => host.ShowAsync("nope"));
Assert.Null(host.Find("nope"));
Assert.Equal(new[] { "clock", "timer" }, host.Modules.Select(m => m.Info.Id), StringComparer.Ordinal);
});
[Fact]
public void RepeatedIds_AreRejected()
{
Assert.Throws<ArgumentException>(() => new OdModuleHost(
[new OdFakeModule("clock"), new OdFakeModule("clock")],
new OdDatabase(_temp.Combine("omnideck.db"), pooling: false),
Logger.None,
_time,
new OdFakeNotifier()));
}
[Fact]
public void Context_GivesEachModuleItsOwnSettingsAndTheNotifier() => OdSta.Run(async () =>
{
var database = new OdDatabase(_temp.Combine("omnideck.db"), pooling: false);
database.Migrate(OdCoreMigrations.All);
var notifier = new OdFakeNotifier();
using var host = new OdModuleHost([_clock, _timer], database, Logger.None, _time, notifier);
var zones = (JsonTypeInfo<string[]>)JsonSerializerOptions.Default.GetTypeInfo(typeof(string[]));
await host.ShowAsync("clock");
await host.ShowAsync("timer");
_clock.Context!.Settings.Set(["Asia/Ho_Chi_Minh"], zones);
_clock.Context.Notifier.Notify("Timer", "Done");
Assert.Equal(new[] { "Asia/Ho_Chi_Minh" }, _clock.Context.Settings.Get(zones));
Assert.Null(_timer.Context!.Settings.Get(zones));
Assert.Equal(new[] { ("Timer", "Done") }, notifier.Shown);
});
private OdModuleHost NewHost() => new(
[_clock, _timer],
new OdDatabase(_temp.Combine("omnideck.db"), pooling: false),
Logger.None,
_time,
new OdFakeNotifier());
}
@@ -0,0 +1,53 @@
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
using Dapper;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
namespace OmniDeck.Tests.Modules;
public sealed class OdModuleSettingsStoreTests : IDisposable
{
private static readonly JsonTypeInfo<string[]> Zones = (JsonTypeInfo<string[]>)JsonSerializerOptions.Default.GetTypeInfo(typeof(string[]));
private readonly OdTempDirectory _temp = new();
private readonly OdDatabase _database;
public OdModuleSettingsStoreTests()
{
_database = new OdDatabase(_temp.Combine("omnideck.db"), pooling: false);
_database.Migrate(OdCoreMigrations.All);
}
public void Dispose() => _temp.Dispose();
[Fact]
public void NothingStored_GivesNull()
{
Assert.Null(new OdModuleSettingsStore(_database, "clock").Get(Zones));
}
[Fact]
public void Set_RoundTrips_AndOverwrites()
{
var store = new OdModuleSettingsStore(_database, "clock");
store.Set(["Europe/Paris"], Zones);
store.Set(["Asia/Tokyo", "UTC"], Zones);
Assert.Equal(new[] { "Asia/Tokyo", "UTC" }, new OdModuleSettingsStore(_database, "clock").Get(Zones));
Assert.Null(new OdModuleSettingsStore(_database, "timer").Get(Zones));
}
[Fact]
public void ADocumentThatNoLongerParses_GivesNull()
{
using (var connection = _database.Open())
{
connection.Execute("INSERT INTO module_settings (module_id, json) VALUES ('clock', '{ broken')");
}
Assert.Null(new OdModuleSettingsStore(_database, "clock").Get(Zones));
}
}
@@ -9,6 +9,7 @@
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="10.1.0" />
<PackageReference Include="Microsoft.Extensions.TimeProvider.Testing" Version="10.11.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<PackageReference Include="xunit.v3.mtp-off" Version="4.0.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="4.0.1" />
@@ -19,6 +20,7 @@
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\OmniDeck.App\OmniDeck.App.csproj" />
<ProjectReference Include="..\..\src\OmniDeck.Core\OmniDeck.Core.csproj" />
</ItemGroup>
@@ -0,0 +1,44 @@
using OmniDeck.Core.Runtime;
namespace OmniDeck.Tests.Runtime;
public sealed class OdSingleInstanceGuardTests
{
[Fact]
public void FirstGuardIsPrimary_SecondIsNot()
{
var suffix = $".test-{Guid.NewGuid():N}";
using var first = new OdSingleInstanceGuard(suffix);
using var second = new OdSingleInstanceGuard(suffix);
Assert.True(first.IsPrimaryInstance);
Assert.False(second.IsPrimaryInstance);
}
[Fact]
public void Signal_FromASecondInstance_ActivatesTheFirst()
{
var suffix = $".test-{Guid.NewGuid():N}";
using var activated = new ManualResetEventSlim();
using var first = new OdSingleInstanceGuard(suffix);
first.StartListening(activated.Set);
using (var second = new OdSingleInstanceGuard(suffix))
{
second.SignalPrimaryInstance();
}
Assert.True(activated.Wait(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken));
}
[Fact]
public void AfterTheFirstIsDisposed_ANewGuardIsPrimary()
{
var suffix = $".test-{Guid.NewGuid():N}";
new OdSingleInstanceGuard(suffix).Dispose();
using var next = new OdSingleInstanceGuard(suffix);
Assert.True(next.IsPrimaryInstance);
}
}
@@ -0,0 +1,47 @@
using OmniDeck.Core.Search;
namespace OmniDeck.Tests.Search;
public sealed class OdFuzzyMatcherTests
{
[Theory]
[InlineData("clk", "Clock")]
[InlineData("CALC", "calculator")]
[InlineData("wt", "World time")]
[InlineData("", "anything")]
public void Matches_CharactersInOrder_IgnoringCase(string query, string text)
{
Assert.NotNull(OdFuzzyMatcher.Score(query, text));
}
[Theory]
[InlineData("kc", "Clock")]
[InlineData("timers", "Timer")]
[InlineData("x", "")]
public void Rejects_MissingOrReorderedCharacters(string query, string text)
{
Assert.Null(OdFuzzyMatcher.Score(query, text));
}
[Theory]
[InlineData("cal", "Calculator", "Local time")]
[InlineData("t", "World time", "Stocks")]
[InlineData("ws", "WebSearch", "Wikis")]
[InlineData("ab", "abx", "axb")]
[InlineData("timer", "Timer", "Timer settings")]
public void RanksStartsWordBreaksRunsAndShorterTextsFirst(string query, string better, string worse)
{
Assert.True(OdFuzzyMatcher.Score(query, better) > OdFuzzyMatcher.Score(query, worse));
}
[Fact]
public void Rank_DropsMisses_SortsByScore_AndKeepsTheOrderOfTies()
{
string[] items = ["Stocks", "Calendar", "Local time", "Calculator", "Media"];
var ranked = OdFuzzyMatcher.Rank(" cal ", items, item => item);
Assert.Equal(new[] { "Calendar", "Calculator", "Local time" }, ranked);
Assert.Equal(items, OdFuzzyMatcher.Rank("", items, item => item));
}
}
@@ -0,0 +1,120 @@
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
using Serilog.Core;
namespace OmniDeck.Tests.Settings;
public sealed class OdSettingsServiceTests
{
[Fact]
public void NoFile_GivesDefaults()
{
using var temp = new OdTempDirectory();
var service = new OdSettingsService(new OdDataRoot(temp.Path), Logger.None);
Assert.Equal(new OdSettings(), service.Current);
Assert.Equal("Standard", service.Current.Preset);
Assert.True(service.Current.CloseToTray);
}
[Fact]
public void Update_SavesAtOnce_AndANewServiceReadsItBack()
{
using var temp = new OdTempDirectory();
var root = new OdDataRoot(temp.Path);
var service = new OdSettingsService(root, Logger.None);
OdSettings? raised = null;
service.Changed += (_, e) => raised = e.Settings;
service.Update(s => s with { Theme = OdThemeMode.Dark, Preset = "Dynamic" });
Assert.Equal(OdThemeMode.Dark, raised?.Theme);
var reloaded = new OdSettingsService(root, Logger.None).Current;
Assert.Equal(OdThemeMode.Dark, reloaded.Theme);
Assert.Equal("Dynamic", reloaded.Preset);
}
[Fact]
public void Update_WithNoChange_DoesNotRaise()
{
using var temp = new OdTempDirectory();
var service = new OdSettingsService(new OdDataRoot(temp.Path), Logger.None);
var raised = 0;
service.Changed += (_, _) => raised++;
service.Update(s => s with { });
Assert.Equal(0, raised);
Assert.False(File.Exists(temp.Combine("settings.json")));
}
[Fact]
public void CorruptFile_FallsBackToDefaults()
{
using var temp = new OdTempDirectory();
var root = new OdDataRoot(temp.Path);
File.WriteAllText(root.SettingsFile, "{ broken");
var service = new OdSettingsService(root, Logger.None);
Assert.Equal(new OdSettings(), service.Current);
Assert.Single(Directory.GetFiles(temp.Path, "settings.corrupt-*.json"));
}
[Theory]
[InlineData("comfort", "Comfort")]
[InlineData("Unknown", "Standard")]
[InlineData("", "Standard")]
public void Normalized_RepairsThePreset(string stored, string expected)
{
Assert.Equal(expected, new OdSettings { Preset = stored }.Normalized().Preset);
}
[Fact]
public void Normalized_RepairsUnknownThemesAndBlankLanguage()
{
var repaired = new OdSettings { Theme = (OdThemeMode)42, Language = " " }.Normalized();
Assert.Equal(OdThemeMode.System, repaired.Theme);
Assert.Equal("", repaired.Language);
}
[Fact]
public void LooksLike_IgnoresEverythingButTheAppearance()
{
var settings = new OdSettings();
Assert.True(settings.LooksLike(settings with { PinnedModules = ["clock"], Language = "vi", CloseToTray = false }));
Assert.False(settings.LooksLike(settings with { Theme = OdThemeMode.Dark }));
Assert.False(settings.LooksLike(settings with { Preset = "Comfort" }));
Assert.False(settings.LooksLike(settings with { FontScale = 1.2 }));
Assert.False(settings.LooksLike(settings with { MotionEnabled = false }));
Assert.False(settings.LooksLike(settings with { AccentColor = "#FF8800" }));
}
[Fact]
public void Normalized_DropsBlankAndRepeatedPins_AndKeepsACleanListAsIs()
{
IReadOnlyList<string> clean = ["clock", "timer"];
var repaired = new OdSettings { PinnedModules = ["clock", " timer ", "", "clock"] }.Normalized();
Assert.Equal(new[] { "clock", "timer" }, repaired.PinnedModules);
Assert.Same(clean, new OdSettings { PinnedModules = clean }.Normalized().PinnedModules);
}
[Fact]
public void PinnedModules_KeepTheirOrder_AndANullListReadsAsEmpty()
{
using var temp = new OdTempDirectory();
var root = new OdDataRoot(temp.Path);
new OdSettingsService(root, Logger.None).Update(s => s with { PinnedModules = ["timer", "clock"] });
Assert.Equal(new[] { "timer", "clock" }, new OdSettingsService(root, Logger.None).Current.PinnedModules);
File.WriteAllText(root.SettingsFile, """{ "pinnedModules": null }""");
Assert.Empty(new OdSettingsService(root, Logger.None).Current.PinnedModules);
}
}
@@ -0,0 +1,83 @@
using OmniDeck.App.Shell;
namespace OmniDeck.Tests.Shell;
public sealed class OdCommandPaletteViewModelTests
{
private static readonly OdPaletteEntry[] Entries =
[
Entry("Clock"),
Entry("Timer"),
Entry("Calculator"),
Entry("Module library"),
Entry("Quit OmniDeck"),
];
[Fact]
public void StartsWithEverything_AndTheFirstEntrySelected()
{
var palette = new OdCommandPaletteViewModel(Entries);
Assert.Equal(Entries, palette.Results);
Assert.Same(Entries[0], palette.Selected);
Assert.Null(palette.Chosen);
}
[Fact]
public void Query_FiltersAndRanks()
{
var palette = new OdCommandPaletteViewModel(Entries) { Query = "cl" };
Assert.Equal(new[] { "Clock", "Calculator" }, palette.Results.Select(e => e.Title), StringComparer.Ordinal);
Assert.Same(palette.Results[0], palette.Selected);
palette.Query = "zzz";
Assert.Empty(palette.Results);
Assert.Null(palette.Selected);
}
[Fact]
public void MoveSelection_StopsAtBothEnds()
{
var palette = new OdCommandPaletteViewModel(Entries);
palette.MoveSelection(-1);
Assert.Same(Entries[0], palette.Selected);
palette.MoveSelection(2);
Assert.Same(Entries[2], palette.Selected);
palette.MoveSelection(10);
Assert.Same(Entries[^1], palette.Selected);
palette.Query = "zzz";
palette.MoveSelection(1);
Assert.Null(palette.Selected);
}
[Fact]
public void Accept_ChoosesTheSelection_AndAnnouncesIt()
{
var palette = new OdCommandPaletteViewModel(Entries) { Query = "tim" };
var accepted = 0;
palette.Accepted += (_, _) => accepted++;
palette.AcceptCommand.Execute(null);
Assert.Same(Entries[1], palette.Chosen);
Assert.Equal(1, accepted);
}
[Fact]
public void Accept_WithNoResult_DoesNothing()
{
var palette = new OdCommandPaletteViewModel(Entries) { Query = "zzz" };
var accepted = 0;
palette.Accepted += (_, _) => accepted++;
palette.AcceptCommand.Execute(null);
Assert.Null(palette.Chosen);
Assert.Equal(0, accepted);
}
private static OdPaletteEntry Entry(string title) => new(title, "Module", "Apps24", () => Task.CompletedTask);
}
@@ -0,0 +1,100 @@
using System.Globalization;
using System.Windows.Controls;
using System.Windows.Data;
using OmniDeck.App.Shell;
using OmniDeck.Tests.TestSupport;
using Serilog.Core;
using Wpf.Ui;
using Wpf.Ui.Controls;
namespace OmniDeck.Tests.Shell;
public sealed class OdShellServicesTests
{
[Theory]
[InlineData("Clock24", SymbolRegular.Clock24)]
[InlineData("NoSuchIcon", SymbolRegular.Apps24)]
[InlineData("12345", SymbolRegular.Apps24)]
[InlineData(null, SymbolRegular.Apps24)]
public void SymbolNames_FallBackToTheAppGlyph(string? name, SymbolRegular expected)
{
var converter = new OdSymbolConverter();
Assert.Equal(expected, OdSymbolConverter.Parse(name));
Assert.Equal(expected, converter.Convert(name, typeof(SymbolRegular), null, CultureInfo.InvariantCulture));
Assert.Same(Binding.DoNothing, converter.ConvertBack(expected, typeof(string), null, CultureInfo.InvariantCulture));
}
[Fact]
public void TrayNotifier_OnlyLogsUntilTheIconIsAttached()
{
var notifier = new OdTrayNotifier(Logger.None);
var shown = new List<string>();
notifier.Notify("Timer", "Before the icon");
notifier.Attach((title, message) => shown.Add(title + ": " + message));
notifier.Notify("Timer", "Done");
Assert.Equal(new[] { "Timer: Done" }, shown, StringComparer.Ordinal);
}
[Fact]
public void Lifetime_RemembersThatTheUserQuit()
{
var lifetime = new OdAppLifetime();
Assert.False(lifetime.IsQuitting);
lifetime.Quit();
Assert.True(lifetime.IsQuitting);
}
[Fact]
public void Dialogs_NeedAHost_AndCountOpenDialogs() => OdSta.Run(async () =>
{
var service = new OdFakeDialogService();
var dialogs = new OdDialogs(service);
Assert.False(dialogs.CanShow);
var host = new ContentDialogHost();
dialogs.SetHost(host);
var showing = dialogs.ShowAsync(new ContentDialog());
Assert.Same(host, service.Host);
Assert.True(dialogs.IsOpen);
Assert.False(dialogs.CanShow);
service.Close(ContentDialogResult.Primary);
Assert.Equal(ContentDialogResult.Primary, await showing);
Assert.False(dialogs.IsOpen);
// No visible main window in a test run: errors fall back to a message box, never a dialog.
Assert.False(dialogs.CanShow);
});
private sealed class OdFakeDialogService : IContentDialogService
{
private TaskCompletionSource<ContentDialogResult> _result = new();
public ContentDialogHost? Host { get; private set; }
public void Close(ContentDialogResult result) => _result.SetResult(result);
public void SetDialogHost(ContentPresenter dialogHost) => throw new NotSupportedException();
public void SetDialogHost(ContentDialogHost dialogHost) => Host = dialogHost;
public void SetContentPresenter(ContentPresenter contentPresenter) => throw new NotSupportedException();
public ContentPresenter? GetContentPresenter() => null;
public ContentPresenter? GetDialogHost() => null;
public ContentDialogHost? GetDialogHostEx() => Host;
public Task<ContentDialogResult> ShowAsync(ContentDialog dialog, CancellationToken cancellationToken)
{
_result = new TaskCompletionSource<ContentDialogResult>();
return _result.Task;
}
}
}
@@ -0,0 +1,211 @@
using System.ComponentModel;
using Microsoft.Extensions.Time.Testing;
using OmniDeck.App.Shell;
using OmniDeck.Core.Modules;
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.Modules;
using OmniDeck.Tests.TestSupport;
using Serilog.Core;
namespace OmniDeck.Tests.Shell;
public sealed class OdShellViewModelTests : IDisposable
{
private readonly OdTempDirectory _temp = new();
private readonly OdSettingsService _settings;
private readonly OdFakeLifetime _lifetime = new();
public OdShellViewModelTests()
{
_settings = new OdSettingsService(new OdDataRoot(_temp.Path), Logger.None);
}
public void Dispose() => _temp.Dispose();
[Fact]
public void Library_ListsEveryModuleInRegistrationOrder() => OdSta.Run(() =>
{
using var host = NewHost();
using var shell = NewShell(host);
Assert.True(shell.HasModules);
Assert.Equal(new[] { "clock", "timer", "calc" }, shell.Library.Select(item => item.Id), StringComparer.Ordinal);
Assert.Equal("Module_clock", shell.Library[0].Title);
Assert.Equal("Test", shell.Library[0].Category);
Assert.Empty(shell.Sidebar);
Assert.Equal(OdShellViewModel.LibraryTarget, shell.CurrentTarget);
return Task.CompletedTask;
});
[Fact]
public void Navigate_ShowsTheModule_AndListsItWhileOpen() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
await shell.NavigateAsync("timer");
await shell.NavigateAsync("clock");
Assert.Equal("clock", shell.CurrentTarget);
Assert.Same(host.Find("clock")?.View, shell.CurrentView);
Assert.Equal(new[] { "timer", "clock" }, shell.Sidebar.Select(item => item.Id), StringComparer.Ordinal);
Assert.Equal(OdModuleState.Idle, shell.Library[1].State);
Assert.True(shell.Library[1].IsOpen);
await shell.NavigateAsync(OdShellViewModel.LibraryTarget);
await shell.NavigateAsync("not-a-module");
Assert.Equal(OdShellViewModel.LibraryTarget, shell.CurrentTarget);
Assert.Null(shell.CurrentView);
Assert.Null(host.Current);
Assert.Equal(2, shell.Sidebar.Count);
});
[Fact]
public void Pins_ComeFirstInPinOrder_AndUnknownPinsAreSkipped() => OdSta.Run(async () =>
{
_settings.Update(s => s with { PinnedModules = ["calc", "web-app-gone", "clock"] });
using var host = NewHost();
using var shell = NewShell(host);
await shell.NavigateAsync("timer");
Assert.Equal(new[] { "calc", "clock", "timer" }, shell.Sidebar.Select(item => item.Id), StringComparer.Ordinal);
Assert.True(shell.Library[0].IsPinned);
Assert.False(shell.Library[1].IsPinned);
});
[Fact]
public void TogglePin_PinsAndUnpinsThroughTheSettings() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
var clock = shell.Library[0];
var timer = shell.Library[1];
shell.TogglePinCommand.Execute(clock);
shell.TogglePinCommand.Execute(timer);
Assert.Equal(new[] { "clock", "timer" }, _settings.Current.PinnedModules, StringComparer.Ordinal);
Assert.Equal(new[] { "clock", "timer" }, shell.Sidebar.Select(item => item.Id), StringComparer.Ordinal);
await shell.NavigateAsync("clock");
shell.TogglePinCommand.Execute(clock);
shell.TogglePinCommand.Execute(timer);
// Unpinned but open, the clock keeps its place like a tab; the timer was never opened.
Assert.Empty(_settings.Current.PinnedModules);
Assert.Equal(new[] { "clock" }, shell.Sidebar.Select(item => item.Id), StringComparer.Ordinal);
});
[Fact]
public void ChangingOnlyAPin_StillRebuildsTheSidebar() => OdSta.Run(async () =>
{
_settings.Update(s => s with { PinnedModules = ["clock"] });
using var host = NewHost();
using var shell = NewShell(host);
await shell.NavigateAsync("clock");
await shell.NavigateAsync("timer");
var rebuilds = 0;
shell.Sidebar.CollectionChanged += (_, e) => rebuilds += e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset ? 1 : 0;
// Same order either way (clock, then timer); only the pinned group changes.
shell.TogglePinCommand.Execute(shell.Library[0]);
Assert.Equal(1, rebuilds);
Assert.Equal(new[] { "clock", "timer" }, shell.Sidebar.Select(item => item.Id), StringComparer.Ordinal);
});
[Fact]
public void Close_RemovesAnUnpinnedModule_AndShowsTheLibraryInstead() => OdSta.Run(async () =>
{
_settings.Update(s => s with { PinnedModules = ["timer"] });
using var host = NewHost();
using var shell = NewShell(host);
await shell.NavigateAsync("timer");
await shell.NavigateAsync("clock");
await shell.CloseCommand.ExecuteAsync(shell.Library[0]);
await shell.CloseCommand.ExecuteAsync(shell.Library[1]);
Assert.Equal(OdShellViewModel.LibraryTarget, shell.CurrentTarget);
Assert.Null(shell.CurrentView);
Assert.Equal(new[] { "timer" }, shell.Sidebar.Select(item => item.Id), StringComparer.Ordinal);
Assert.Equal(OdModuleState.Closed, shell.Library[1].State);
Assert.False(shell.Library[1].IsOpen);
});
[Fact]
public void Open_NavigatesToTheModule() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
await shell.OpenCommand.ExecuteAsync(shell.Library[2]);
Assert.Equal("calc", shell.CurrentTarget);
Assert.Equal(OdModuleState.Active, shell.Library[2].State);
});
[Fact]
public void PaletteEntries_OpenModules_ShowTheLibrary_AndQuit() => OdSta.Run(async () =>
{
using var host = NewHost();
using var shell = NewShell(host);
var entries = shell.PaletteEntries();
Assert.Equal(new[] { "Module_clock", "Module_timer", "Module_calc", "Module library", "Quit OmniDeck" }, entries.Select(e => e.Title), StringComparer.Ordinal);
Assert.Equal("Command", entries[^1].Detail);
await entries[1].RunAsync();
Assert.Equal("timer", shell.CurrentTarget);
await entries[3].RunAsync();
Assert.Equal(OdShellViewModel.LibraryTarget, shell.CurrentTarget);
Assert.False(_lifetime.IsQuitting);
await entries[4].RunAsync();
Assert.True(_lifetime.IsQuitting);
});
[Fact]
public void RefreshTexts_AnnouncesTheLocalizedProperties() => OdSta.Run(() =>
{
using var host = NewHost();
using var shell = NewShell(host);
var changed = new List<string?>();
((INotifyPropertyChanged)shell.Library[0]).PropertyChanged += (_, e) => changed.Add(e.PropertyName);
shell.Library[0].RefreshTexts();
Assert.Equal(new[] { "Title", "Category" }, changed, StringComparer.Ordinal);
return Task.CompletedTask;
});
[Fact]
public void Dispose_StopsFollowingTheSettings() => OdSta.Run(() =>
{
using var host = NewHost();
var shell = NewShell(host);
shell.Dispose();
_settings.Update(s => s with { PinnedModules = ["clock"] });
Assert.Empty(shell.Sidebar);
return Task.CompletedTask;
});
private OdModuleHost NewHost() => new(
[new OdFakeModule("clock"), new OdFakeModule("timer"), new OdFakeModule("calc")],
new OdDatabase(_temp.Combine("omnideck.db"), pooling: false),
Logger.None,
new FakeTimeProvider(),
new OdFakeNotifier());
private OdShellViewModel NewShell(OdModuleHost host) => new(host, _settings, _lifetime);
private sealed class OdFakeLifetime : IOdAppLifetime
{
public bool IsQuitting { get; private set; }
public void Quit() => IsQuitting = true;
}
}
@@ -0,0 +1,51 @@
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
namespace OmniDeck.Tests.Storage;
public sealed class OdDataRootTests
{
[Fact]
public void Default_IsTheDataFolderUnderLocalAppData_NotVelopacksInstallFolder()
{
var local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
Assert.Equal(Path.Combine(local, "OmniDeck.Data"), OdDataRoot.Default.Root);
}
[Fact]
public void Paths_AllLiveUnderTheRoot()
{
using var temp = new OdTempDirectory();
var root = new OdDataRoot(temp.Path);
Assert.All(
[root.SettingsFile, root.DatabaseFile, root.LogsDirectory, root.ReportsDirectory, root.WebView2Directory],
path => Assert.StartsWith(temp.Path, path, StringComparison.OrdinalIgnoreCase));
}
[Theory]
[InlineData("OmniDeck")]
[InlineData("omnideck")]
public void Constructor_RejectsVelopacksInstallFolder(string name)
{
using var temp = new OdTempDirectory();
Assert.Throws<ArgumentException>(() => new OdDataRoot(temp.Combine(name)));
}
[Fact]
public void EnsureCreated_ThenTryDelete_LeavesNothing()
{
using var temp = new OdTempDirectory();
var root = new OdDataRoot(temp.Combine("OmniDeck.Data"));
root.EnsureCreated();
File.WriteAllText(root.SettingsFile, "{}");
Assert.True(Directory.Exists(root.LogsDirectory));
Assert.True(root.TryDelete());
Assert.False(Directory.Exists(root.Root));
Assert.True(root.TryDelete());
}
}
@@ -0,0 +1,82 @@
using System.Globalization;
using Dapper;
using Microsoft.Data.Sqlite;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
namespace OmniDeck.Tests.Storage;
public sealed class OdDatabaseTests
{
private static readonly OdMigration Notes = new(OdCoreMigrations.All.Count + 1, "notes", "CREATE TABLE notes (id INTEGER PRIMARY KEY, text TEXT NOT NULL);");
[Fact]
public void EmptyDatabase_IsVersionZero()
{
using var temp = new OdTempDirectory();
Assert.Equal(0, NewDatabase(temp).SchemaVersion());
}
[Fact]
public void CoreMigrations_StartAtOne_AndHaveNoGaps()
{
var versions = OdCoreMigrations.All.Select(m => m.Version).ToList();
Assert.Equal(Enumerable.Range(1, versions.Count), versions);
Assert.Equal(new[] { "app_meta", "module_settings" }, OdCoreMigrations.All.Select(m => m.Name), StringComparer.Ordinal);
}
[Fact]
public void Migrate_AppliesEachStepOnce()
{
using var temp = new OdTempDirectory();
var database = NewDatabase(temp);
OdMigration[] migrations = [.. OdCoreMigrations.All, Notes];
Assert.Equal(migrations.Length, database.Migrate(migrations));
Assert.Equal(0, database.Migrate(migrations));
Assert.Equal(Notes.Version, database.SchemaVersion());
}
[Fact]
public void Migrate_AFailingStep_RollsBackAndKeepsTheVersion()
{
using var temp = new OdTempDirectory();
var database = NewDatabase(temp);
database.Migrate([.. OdCoreMigrations.All, Notes]);
var broken = new OdMigration(Notes.Version + 1, "broken", "CREATE TABLE half (id INTEGER); INSERT INTO nowhere VALUES (1);");
Assert.Throws<SqliteException>(() => database.Migrate([.. OdCoreMigrations.All, Notes, broken]));
Assert.Equal(Notes.Version, database.SchemaVersion());
using var connection = database.Open();
Assert.Equal(0, connection.ExecuteScalar<long>("SELECT COUNT(*) FROM sqlite_master WHERE name = 'half'"));
}
[Fact]
public void Migrate_RejectsDuplicateVersions()
{
using var temp = new OdTempDirectory();
Assert.Throws<ArgumentException>(() => NewDatabase(temp).Migrate([.. OdCoreMigrations.All, Notes, Notes with { Name = "again" }]));
}
[Fact]
public void AppMeta_SetsAndOverwritesValues()
{
using var temp = new OdTempDirectory();
var database = NewDatabase(temp);
database.Migrate(OdCoreMigrations.All);
var meta = new OdAppMeta(database);
Assert.Null(meta.Get(OdAppMetaKeys.LegalAcknowledgedVersion));
meta.Set(OdAppMetaKeys.LegalAcknowledgedVersion, "1.0");
meta.Set(OdAppMetaKeys.LegalAcknowledgedVersion, "1.1");
Assert.Equal("1.1", meta.Get(OdAppMetaKeys.LegalAcknowledgedVersion));
Assert.Equal(OdCoreMigrations.All.Count.ToString(CultureInfo.InvariantCulture), meta.Get(OdAppMetaKeys.SchemaVersion));
}
private static OdDatabase NewDatabase(OdTempDirectory temp) => new(temp.Combine("omnideck.db"), pooling: false);
}
@@ -0,0 +1,52 @@
using OmniDeck.Core.Settings;
using OmniDeck.Core.Storage;
using OmniDeck.Tests.TestSupport;
namespace OmniDeck.Tests.Storage;
public sealed class OdJsonFileTests
{
[Fact]
public void Write_ThenRead_RoundTrips_AndLeavesNoTempFiles()
{
using var temp = new OdTempDirectory();
var path = temp.Combine("settings.json");
var settings = new OdSettings { Preset = "Comfort", CloseToTray = false };
OdJsonFile.Write(path, settings, OdSettingsJsonContext.Default.OdSettings);
var read = OdJsonFile.Read(path, OdSettingsJsonContext.Default.OdSettings, out var status);
Assert.Equal(OdJsonReadStatus.Loaded, status);
Assert.Equivalent(settings, read, strict: true);
Assert.Equal("settings.json", Path.GetFileName(Assert.Single(Directory.GetFiles(temp.Path))));
}
[Fact]
public void Read_MissingFile_ReturnsNull()
{
using var temp = new OdTempDirectory();
var read = OdJsonFile.Read(temp.Combine("nothing.json"), OdSettingsJsonContext.Default.OdSettings, out var status);
Assert.Null(read);
Assert.Equal(OdJsonReadStatus.Missing, status);
}
[Theory]
[InlineData("{ not json")]
[InlineData("null")]
public void Read_CorruptFile_IsSetAside(string content)
{
using var temp = new OdTempDirectory();
var path = temp.Combine("settings.json");
File.WriteAllText(path, content);
var read = OdJsonFile.Read(path, OdSettingsJsonContext.Default.OdSettings, out var status);
Assert.Null(read);
Assert.Equal(OdJsonReadStatus.Quarantined, status);
Assert.False(File.Exists(path));
var quarantined = Assert.Single(Directory.GetFiles(temp.Path, "settings.corrupt-*.json"));
Assert.Equal(content, File.ReadAllText(quarantined));
}
}
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff. Show more