diff --git a/AGENTS.md b/AGENTS.md index 238b5a1..23da758 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,6 +10,16 @@ Openza Reader is a Windows-first, read-only Markdown reader. - Keep remote assets explicit and local app assets bundled; no CDN dependencies. - Preserve the native Windows feel with WinUI 3 controls and system theme behavior. +## Desktop UI Direction +- Treat Openza Reader as a desktop document app, not a mobile-style centered card app. Use the available window space for start, recents, settings, about, and document-management surfaces. +- Avoid narrow centered panels for substantial surfaces. Prefer desktop-width layouts with clear regions, such as a left identity/action column and a flexible main content region, or a full settings/about page when content has multiple sections. +- Use `ContentDialog` only for small blocking decisions or compact information. Do not put multi-section settings, large link collections, recent-file lists, or other page-like experiences into cramped modal layouts. +- Settings should follow WinUI Gallery-style settings layouts: grouped sections, card-like rows, icons where helpful, descriptions, right-aligned controls on wide layouts, and stacked controls on narrow layouts. +- About should feel like a native desktop app identity surface: app icon/name/version, concise purpose, and structured icon rows for documentation, source, issues, security, license, and notices. Avoid loose hyperlink lists. +- Empty states should include a clear primary action and use the rest of the page for useful recovery or continuation content, especially recent files. +- Reading surfaces may center document controls around the reading column when it improves calm focus. App-management workspaces such as Settings, About, and Recents should remain left-aligned and structured like native desktop pages. +- Before finalizing UI changes, check the same surface at full desktop width, portrait/narrow width, and High Contrast. Watch for wasted space, clipped text, duplicated titles, hidden exits, and toolbar/stat/title overlap. + ## Technical Defaults - .NET 10 LTS - Windows App SDK 2.0.x diff --git a/README.md b/README.md index 99c6d5f..3939cca 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,11 @@ Install: [Microsoft Store](https://apps.microsoft.com/detail/9NNPMN0JSSW5?hl=en- - Disable raw HTML in Markdown input - Highlight fenced code blocks with bundled Prism-compatible assets - Show a table of contents from document headings -- Search with WebView2's native Find API -- Zoom, copy selected rendered text, reload, and open in the system editor +- Search with an explicit toolbar button backed by WebView2's native Find API +- Switch between Preview, Raw, and Side by side read-only view modes +- Choose reader theme, remote image policy, and default view mode in Settings +- Open recent files from the empty state +- Zoom, copy selected text, reload, and open the current file with an installed Markdown editor through Windows - Auto reload changed files with debounce - Ship as MSIX with Markdown file associations @@ -29,7 +32,7 @@ Install: [Microsoft Store](https://apps.microsoft.com/detail/9NNPMN0JSSW5?hl=en- - .NET 10 SDK - Windows App SDK 2.0.x -The development build is configured as Windows App SDK self-contained so `dotnet run` can launch without first registering a machine-wide Windows App Runtime. +The development build is configured as Windows App SDK self-contained so `dotnet run` can launch without first registering a machine-wide Windows App Runtime. The app manifest and package minimum target Windows 10 22H2 (`10.0.19045.0`), and the app project produces self-contained `win-x64` build output for release validation. You can install the required WinUI development workload with Microsoft's winget configuration: @@ -49,7 +52,7 @@ For Store packaging, open the solution in Visual Studio and use **Publish > Crea ## Security Posture -Markdown is rendered as untrusted content. Raw HTML is disabled, WebView2 host objects and web messages are disabled, app navigation is intercepted, and external links are launched through the Windows shell instead of inside the embedded WebView. +Markdown is rendered as untrusted content. Raw HTML is disabled, WebView2 host objects and web messages are disabled, app navigation is intercepted, and external links are launched through the Windows shell instead of inside the embedded WebView. Remote images can be blocked from Settings. See [SECURITY.md](SECURITY.md) and [docs/security.md](docs/security.md) for reporting and implementation details. diff --git a/docs/release-readiness-checklist.md b/docs/release-readiness-checklist.md new file mode 100644 index 0000000..51de6c9 --- /dev/null +++ b/docs/release-readiness-checklist.md @@ -0,0 +1,68 @@ +# Openza Reader Release Readiness Checklist + +Use this checklist before a public Store update or GitHub release. It separates developer validation from user-install validation so packaging issues are not hidden by a working development machine. + +## Developer Validation + +- Confirm release blockers are closed or explicitly deferred: + - [ ] #12: self-contained .NET runtime packaging verified. + - [ ] #13: Windows minimum version matches project, source manifest, generated package, README, website, and Store copy. + - [ ] #14: WebView2 missing-runtime behavior verified and documented. + - [ ] #16: this checklist is current for the release. +- Run restore: + +```powershell +dotnet restore src/Openza.Reader.Tests/Openza.Reader.Tests.csproj +``` + +- Run tests: + +```powershell +dotnet test src/Openza.Reader.Tests/Openza.Reader.Tests.csproj -c Release --no-restore +``` + +- Run app build: + +```powershell +dotnet build src/Openza.Reader/Openza.Reader.csproj -c Release --no-restore +``` + +- Run public hygiene scan: + +```powershell +gitleaks detect --source . --verbose +``` + +- Inspect the built runtime config. A self-contained package should not require a separate `Microsoft.NETCore.App` install prompt for normal users. +- Inspect the generated `AppxManifest.xml` or MSIX manifest and confirm `MinVersion="10.0.19045.0"`. +- Confirm package size impact from bundling the .NET runtime and record it in release notes. The 2026-05-23 Release x64 build layout was about 217 MiB before MSIX packaging. +- Generate/update screenshots after the final UI is stable. +- Confirm README, website docs, Store copy, release notes, privacy, security, and third-party notices match shipped behavior. + +## Manual App Smoke Test + +- Open the app from Start and from a Markdown file association. +- Open `.md` and `.markdown` files by file picker, drag/drop, and File Explorer. +- Verify wide tables scroll horizontally without clipping the document. +- Verify Search button and `Ctrl+F` use native WebView2 find. +- Verify Preview, Raw, and Side by side read-only modes. +- Verify TOC behavior in Preview/Side by side and hidden/disabled behavior in Raw. +- Verify recent files open and clear correctly. +- Verify settings persist after restart. +- Verify Editor opens the Windows app picker for installed Markdown-capable applications. +- Verify System, Light, Dark, Sepia, and Windows High Contrast behavior. +- Verify focus mode hides reader chrome, hides TOC, enters fullscreen, and exits with the visible Exit focus button, Esc, and F11. +- Verify zoom, copy, reload, auto reload, local images, remote image policy, and link interception. +- Verify narrow and portrait windows have no clipped labels, title/stat overlap, or broken settings/about layouts. + +## User-Install Validation + +- Create the Release x64 package or Store upload package. +- Install on a clean supported Windows 10 22H2 machine or clean VM without .NET 10 installed. +- Confirm the app launches without a separate .NET 10 runtime install prompt. +- Confirm WebView2 Runtime behavior: + - If runtime is present, Markdown preview renders normally. + - If runtime is missing or broken, the app shows a clear WebView2 Runtime error with the official install/repair link. +- Confirm install, update, and uninstall work cleanly. +- Confirm Store package signing and identity are correct. +- Confirm release notes mention runtime/package-size impact and prerequisite behavior. diff --git a/docs/release.md b/docs/release.md index a68348a..8e0a074 100644 --- a/docs/release.md +++ b/docs/release.md @@ -8,9 +8,19 @@ The first public release is an MVP: - `.md` and `.markdown` file associations work. - File Explorer activation opens one window per file. - Markdown rendering is safe and visually polished. -- TOC, search, zoom, copy selection, reload, external editor, and auto reload work. +- TOC, search button, Preview/Raw/Side by side modes, recents, settings, zoom, copy selection, reload, external editor, and auto reload work. - Unit tests pass. - Manual smoke tests pass on Windows 10 22H2 and Windows 11. +- Release-blocking GitHub issues #12, #13, #14, and #16 are verified or explicitly deferred in release notes. + +See [release-readiness-checklist.md](release-readiness-checklist.md) for the full developer and user-install validation checklist. + +## Release Blockers From GitHub + +- [#12](https://github.com/openza/reader/issues/12): package should be self-contained for the .NET runtime so normal users do not see a separate .NET 10 runtime prompt. +- [#13](https://github.com/openza/reader/issues/13): Windows minimum version must match project, source manifest, generated package, README, website, and Store metadata. +- [#14](https://github.com/openza/reader/issues/14): missing or broken WebView2 Runtime behavior must be verified and user-facing. +- [#16](https://github.com/openza/reader/issues/16): release readiness checklist must be repeatable and current. ## Current Distribution @@ -20,6 +30,15 @@ Openza Reader is live on the Microsoft Store: Microsoft Store remains the trusted public install and update channel for V1. +## Runtime And Platform Notes + +- Supported OS target: Windows 10 22H2 (`10.0.19045.0`) or later, and Windows 11. +- V1 architecture: x64. +- The app project is configured for Windows App SDK self-contained deployment and .NET self-contained build output for `win-x64`. +- The 2026-05-23 Release x64 build output used `includedFrameworks` for `Microsoft.NETCore.App` in `Openza.Reader.runtimeconfig.json` and was about 217 MiB before MSIX packaging. +- Final package validation must still install on a clean machine or VM without .NET 10. +- Openza Reader uses WebView2. Windows 11 normally includes the runtime; if WebView2 is absent or broken, the app surfaces a WebView2 Runtime install/repair link. + ## Out Of Scope - Direct winget publishing before Store availability has been verified diff --git a/docs/roadmap-progress-tracker.md b/docs/roadmap-progress-tracker.md new file mode 100644 index 0000000..90193c7 --- /dev/null +++ b/docs/roadmap-progress-tracker.md @@ -0,0 +1,135 @@ +# Openza Reader Roadmap Progress Tracker + +Last updated: 2026-05-23 + +Use this document as the living tracker for the roadmap batches implemented from the Openza Tasks export and Apostrophe research. Keep adding progress notes here after future implementation, QA, Store work, or product decisions. + +## Status Legend + +- `Done`: implemented and automated verification passed where applicable. +- `Partial`: implemented partly, or code is present but manual/release verification remains. +- `Pending`: not implemented yet. +- `Deferred`: intentionally out of scope for the current plan. + +## Current Snapshot + +| Batch | Status | Notes | +| --- | --- | --- | +| Batch 1: Fix Reading Basics First | Done | Wide table CSS, Search button, and related reading basics are implemented. Automated build/test passed; final manual smoke QA remains before release. | +| Batch 2: Preview / Raw / Side-By-Side Modes | Done | View modes are implemented as a compact toolbar View menu instead of the earlier full-width SelectorBar strip. | +| Batch 3: Settings, About, External Editor, Recents | Done | Desktop in-app settings/about workspaces, Windows editor picker, polished recents, theme/default view/remote image settings are implemented. | +| Batch 4: Reader Polish From Apostrophe Research | Done | Themes, stats, immersive focus mode with visible exit cue, remote image policy, centered reader toolbar, and improved narrow behavior are implemented. Final High Contrast/narrow manual QA remains before release. | +| Batch 5: Public And Store Polish | Partial | README, docs, website docs, Store listing copy, release checklist, and critical GitHub release issues are now tracked. Screenshots/assets, clean-machine install validation, and final release hygiene remain. | +| Deferred: Tabs | Deferred | Tabs remain out of V1 scope unless product decision changes. | + +## Batch Details + +### Batch 1: Fix Reading Basics First + +Status: Done + +- Done: rendered content width and table behavior improved in `src/Openza.Reader/Assets/reader.css`. +- Done: explicit Search button added to the toolbar. +- Done: Search button uses WebView2 native Find behavior. +- Done: zoom, TOC, reload, local/remote images, and link interception were preserved through implementation passes. +- Release QA: wide tables, zoom, TOC, reload, local/remote images, and link interception still need final manual smoke verification. + +### Batch 2: Preview / Raw / Side-By-Side Modes + +Status: Done + +- Done: Preview, Raw, and Side by side view modes added. +- Done: mode switch moved to a compact toolbar View menu using checked `RadioMenuFlyoutItem`s. +- Done: Preview remains default. +- Done: Raw view is selectable, read-only Markdown in a monospaced `TextBox`. +- Done: Side by side shows raw Markdown and preview in equal panes. +- Done: TOC is disabled/hidden in Raw and available in Preview/Side by side. +- Done: copy behavior prefers focused/selected raw text, otherwise selected preview text. + +### Batch 3: Settings, About, External Editor, Recents + +Status: Done + +- Done: Settings moved from a modal dialog to a desktop-width in-app workspace with WinUI Gallery-style rows and immediate persistence. +- Done: Settings include default view mode, reader theme, remote image policy, recents controls, and document stats toggle. +- Done: Editor opens the Windows app picker so the user can choose from installed Markdown-capable applications instead of fixed defaults. +- Done: recent files are local-only and shown on a desktop-width empty-state panel with file icons, folder paths, clear action, and long-text trimming; a toolbar Recent command opens the same recents surface while a document is open. +- Done: About moved from a modal dialog to a desktop-width in-app workspace with app identity, icon link rows for docs/source/issues/security/notices, version, and license/security note. + +### Batch 4: Reader Polish From Apostrophe Research + +Status: Done + +- Done: reader themes: System, Light, Dark, Sepia. +- Done: document stats: word count, estimated read time, heading count. +- Done: immersive focus reading mode enters fullscreen, hides title/toolbar/info/TOC/workspace surfaces, shows a visible Exit focus button, and supports Esc/F11 to exit. +- Done: remote image policy can block remote images and tightens generated CSP. +- Done: TOC hides on narrow windows and the view mode control no longer consumes a full row. +- Done: reader toolbar is centered for the document reading surface; Settings/About/Recents remain left-aligned desktop workspaces. +- Done: toolbar order reviewed and adjusted so Focus sits with reader/view controls. +- Release QA: Windows High Contrast, narrow toolbar behavior, TOC behavior on small windows, and visual polish across real documents still need final manual smoke verification. + +### Batch 5: Public And Store Polish + +Status: Partial + +- Done: README updated for view modes, search, settings, recents, privacy, and themes. +- Done: website docs updated for view modes, security model, rendering, reading workflow, architecture, and Store copy. +- Done: Store listing text updated in docs. +- Done: release readiness checklist added in `docs/release-readiness-checklist.md`. +- Partial: critical GitHub release issues are included in this PR/release gate: + - #12: .NET self-contained packaging is configured and build output runtimeconfig now uses `includedFrameworks`; clean-machine install still needs verification. + - #13: package minimum now aligns with the source manifest/docs at Windows 10 22H2 / `10.0.19045.0`; generated build manifest inspection passed with `MaxVersionTested="10.0.26100.0"`. + - #14: WebView2 initialization now shows a user-facing Runtime install/repair link; missing-runtime behavior still needs clean-machine or VM validation. + - #16: checklist exists and separates developer validation from user-install validation. +- Pending: regenerate Store/listing screenshots after UI stabilizes. +- Pending: verify website copy against the actual shipped behavior after final QA. +- Pending: clean Windows 10 22H2 or Windows 11 VM install test without .NET 10. +- Done: `gitleaks detect --source . --verbose` passed outside the sandbox after PATH verification. + +## Verification Log + +2026-05-22: + +- Passed: `dotnet restore src/Openza.Reader.Tests/Openza.Reader.Tests.csproj` +- Passed: `dotnet test src/Openza.Reader.Tests/Openza.Reader.Tests.csproj -c Release --no-restore` +- Passed: `dotnet build src/Openza.Reader/Openza.Reader.csproj -c Release --no-restore` +- Passed: `ASTRO_TELEMETRY_DISABLED=1 npm run build` from `website/` +- Passed: `git diff --check` with only CRLF warnings +- Blocked: `gitleaks detect --source . --verbose` because `gitleaks` was not found + +2026-05-23: + +- Passed: `dotnet restore src/Openza.Reader.Tests/Openza.Reader.Tests.csproj` +- Passed: `dotnet test src/Openza.Reader.Tests/Openza.Reader.Tests.csproj -c Release --no-restore` +- Passed: `dotnet build src/Openza.Reader/Openza.Reader.csproj -c Release --no-restore` +- Passed: generated build manifest has `MinVersion="10.0.19045.0"` and `MaxVersionTested="10.0.26100.0"`. +- Passed: runtimeconfig uses `includedFrameworks` for `Microsoft.NETCore.App`, indicating self-contained .NET build output. +- Passed: Release x64 build layout measured about 217 MiB before MSIX packaging. +- Passed: `gitleaks detect --source . --verbose` scanned 23 commits and found no leaks. +- Passed: `ASTRO_TELEMETRY_DISABLED=1 npm run build` from `website/`. + +## Manual QA Still Needed + +- Wide tables render with horizontal scrolling and no document clipping. +- Search button and `Ctrl+F` both use native find flow. +- Raw view is read-only and text selection/copy works. +- Side by side mode uses equal panes with independent scrolling. +- TOC works in Preview and Side by side, and stays hidden/disabled in Raw. +- Recent files open correctly and can be cleared. +- Settings persist after restart. +- Editor button shows installed Windows app choices for the current Markdown file. +- Theme switching works for System, Light, Dark, and Sepia. +- Windows High Contrast remains readable. +- Narrow layout has no toolbar/stat/title overlap. +- Drag/drop, reload, auto reload, local images, remote image policy, and link interception still work. + +## Future Progress Notes + +Append dated notes below. + +- 2026-05-22: Initial tracker created after roadmap implementation pass. +- 2026-05-23: Corrected Editor behavior to use the Windows app picker, polished Recent files, moved Settings/About to desktop in-app workspaces, and added visible/Esc exit affordances for Focus mode. +- 2026-05-23: Centered the reader toolbar, fixed toolbar label persistence, added Recent command while documents are open, improved Settings/About alignment, and moved Focus into the reader/view command group. +- 2026-05-23: Added GitHub release blockers #12, #13, #14, and #16 to the release gate; aligned package minimum Windows version to 10.0.19045.0; configured and verified .NET self-contained build output; added WebView2 Runtime unavailable error; added release readiness checklist; passed gitleaks. +- 2026-05-23: Fixed review findings for focus-mode window restoration, narrow Settings row layout, and Editor launch failure handling; Release build and tests passed. diff --git a/docs/security.md b/docs/security.md index 74f1e79..f548e06 100644 --- a/docs/security.md +++ b/docs/security.md @@ -14,9 +14,10 @@ Openza Reader renders local Markdown files that may come from downloads, reposit - `#heading` anchors stay inside the document. - `http`, `https`, and `mailto` open externally. - `javascript:`, arbitrary `file:`, and unknown schemes are blocked. -- Local and remote images are allowed for README compatibility. +- Local images resolve relative to the opened Markdown file. +- Remote images are controlled by the user setting and can be blocked for privacy. +- If WebView2 Runtime is missing or broken, preview rendering cannot start. The app shows a user-facing error with the official WebView2 Runtime install/repair link instead of failing silently. ## Future HTML Compatibility If raw HTML support is added later, it must be allowlist-sanitized before entering the WebView. The allowlist should start with README-safe tags such as `details`, `summary`, `kbd`, `br`, `sub`, `sup`, and restricted `img` attributes. It must block scripts, event handlers, forms, iframes, embedded objects, and arbitrary styles. - diff --git a/docs/store-submission.md b/docs/store-submission.md index 10319ab..f5c9954 100644 --- a/docs/store-submission.md +++ b/docs/store-submission.md @@ -22,9 +22,12 @@ These steps require the project owner's Microsoft Partner Center account: ## Package Notes - Target: Windows 10 22H2 and Windows 11. +- Minimum package version: `10.0.19045.0`. - Architecture: x64 for V1. - Package type: MSIX upload package generated by Visual Studio. - Store signing: handled by Microsoft Store after submission. +- Runtime: build and package as self-contained for normal user installs; verify on a clean machine without .NET 10 before submission. +- WebView2: verify the Runtime is present or that the app shows the WebView2 install/repair prompt if it is missing or broken. - Local test signing keys such as `Openza.Reader_TemporaryKey.pfx` must never be committed. - Visual Studio association with the Store app will update package identity values assigned by Partner Center. @@ -41,9 +44,9 @@ Description: ```text Openza Reader is a native Markdown reader for Windows, built with WinUI 3, WebView2, and MSIX packaging. -Open Markdown files from File Explorer, drag and drop documents into the app, browse headings with a table of contents, search rendered text, adjust zoom, copy selected content, and open the current file in your external editor when you need to make changes. +Open Markdown files from File Explorer, drag and drop documents into the app, reopen recent files, browse headings with a table of contents, search rendered text, adjust zoom, copy selected content, and choose an installed editor from Windows when you need to make changes. -Openza Reader focuses on clean, safe reading. Markdown is treated as untrusted input, raw HTML is escaped, scripts are blocked by construction, and external navigation is handled through the system browser. +Openza Reader focuses on clean, safe reading. Switch between Preview, Raw, and Side by side read-only modes, choose a reader theme, and control remote image loading from Settings. Markdown is treated as untrusted input, raw HTML is escaped, scripts are blocked by construction, and external navigation is handled through the system browser. ``` Keywords: @@ -90,7 +93,10 @@ Free - Open `.md` and `.markdown` files from File Explorer. - Confirm file association. - Confirm drag and drop. -- Confirm TOC, search, zoom, copy, reload, and external editor actions. +- Confirm TOC, search button, Preview/Raw/Side by side modes, settings persistence, recents, themes, remote image policy, zoom, copy, reload, and external editor actions. +- Confirm launch on a clean Windows 10 22H2 or Windows 11 machine without .NET 10 installed. +- Confirm the packaged manifest uses `MinVersion="10.0.19045.0"`. +- Confirm WebView2 Runtime missing/broken behavior before public submission. - Confirm uninstall removes the app cleanly. ## References diff --git a/src/Openza.Reader.Core/Models/DocumentStats.cs b/src/Openza.Reader.Core/Models/DocumentStats.cs new file mode 100644 index 0000000..8dbd300 --- /dev/null +++ b/src/Openza.Reader.Core/Models/DocumentStats.cs @@ -0,0 +1,7 @@ +namespace Openza.Reader.Models; + +public sealed record DocumentStats( + int WordCount, + int EstimatedReadMinutes, + int HeadingCount); + diff --git a/src/Openza.Reader.Core/Models/MarkdownRenderResult.cs b/src/Openza.Reader.Core/Models/MarkdownRenderResult.cs index 4bab53c..09e0293 100644 --- a/src/Openza.Reader.Core/Models/MarkdownRenderResult.cs +++ b/src/Openza.Reader.Core/Models/MarkdownRenderResult.cs @@ -3,5 +3,5 @@ namespace Openza.Reader.Models; public sealed record MarkdownRenderResult( string HtmlBody, IReadOnlyList TocItems, - string? Title); - + string? Title, + DocumentStats Stats); diff --git a/src/Openza.Reader.Core/Services/DocumentStatsCalculator.cs b/src/Openza.Reader.Core/Services/DocumentStatsCalculator.cs new file mode 100644 index 0000000..5edede3 --- /dev/null +++ b/src/Openza.Reader.Core/Services/DocumentStatsCalculator.cs @@ -0,0 +1,27 @@ +using System.Text.RegularExpressions; + +namespace Openza.Reader.Services; + +public static partial class DocumentStatsCalculator +{ + private const int WordsPerMinute = 200; + + public static int CountWords(string text) + { + ArgumentNullException.ThrowIfNull(text); + return WordRegex().Count(text); + } + + public static int EstimateReadMinutes(int wordCount) + { + if (wordCount <= 0) + { + return 0; + } + + return Math.Max(1, (int)Math.Ceiling(wordCount / (double)WordsPerMinute)); + } + + [GeneratedRegex(@"[\p{L}\p{N}]+(?:['-][\p{L}\p{N}]+)?", RegexOptions.CultureInvariant)] + private static partial Regex WordRegex(); +} diff --git a/src/Openza.Reader.Core/Services/ExternalEditorService.cs b/src/Openza.Reader.Core/Services/ExternalEditorService.cs deleted file mode 100644 index 8289285..0000000 --- a/src/Openza.Reader.Core/Services/ExternalEditorService.cs +++ /dev/null @@ -1,50 +0,0 @@ -using System.ComponentModel; -using System.Diagnostics; - -namespace Openza.Reader.Services; - -public sealed class ExternalEditorService -{ - public void Open(string filePath) - { - if (!File.Exists(filePath)) - { - return; - } - - if (TryStart(new ProcessStartInfo(filePath) { UseShellExecute = true, Verb = "edit" })) - { - return; - } - - if (TryStart(new ProcessStartInfo("notepad.exe", Quote(filePath)) { UseShellExecute = true })) - { - return; - } - - _ = TryStart(new ProcessStartInfo(filePath) { UseShellExecute = true }); - } - - private static bool TryStart(ProcessStartInfo info) - { - try - { - using var process = Process.Start(info); - return process is not null; - } - catch (Win32Exception) - { - return false; - } - catch (InvalidOperationException) - { - return false; - } - } - - private static string Quote(string value) - { - return $"\"{value.Replace("\"", "\\\"", StringComparison.Ordinal)}\""; - } -} - diff --git a/src/Openza.Reader.Core/Services/HtmlShellBuilder.cs b/src/Openza.Reader.Core/Services/HtmlShellBuilder.cs index 1121b4c..98c2772 100644 --- a/src/Openza.Reader.Core/Services/HtmlShellBuilder.cs +++ b/src/Openza.Reader.Core/Services/HtmlShellBuilder.cs @@ -16,16 +16,20 @@ public HtmlShellBuilder() _prismJs = ReadAsset("prism.js"); } - public string Build(MarkdownRenderResult result, string documentName) + public string Build(MarkdownRenderResult result, string documentName, string readerTheme, bool allowRemoteImages) { var title = WebUtility.HtmlEncode(result.Title ?? documentName); + var theme = WebUtility.HtmlEncode(readerTheme); + var imgSrc = allowRemoteImages + ? "file: http: https: data:" + : "file: data:"; return $$""" - + - + {{title}} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Openza.Reader/Pages/AboutPage.xaml.cs b/src/Openza.Reader/Pages/AboutPage.xaml.cs new file mode 100644 index 0000000..0e3447d --- /dev/null +++ b/src/Openza.Reader/Pages/AboutPage.xaml.cs @@ -0,0 +1,27 @@ +using Microsoft.UI.Xaml.Controls; +using System.Reflection; +using Windows.ApplicationModel; + +namespace Openza.Reader.Pages; + +public sealed partial class AboutPage : UserControl +{ + public AboutPage() + { + InitializeComponent(); + VersionText.Text = $"Version {GetVersion()}"; + } + + private static string GetVersion() + { + try + { + var version = Package.Current.Id.Version; + return $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"; + } + catch (InvalidOperationException) + { + return Assembly.GetExecutingAssembly().GetName().Version?.ToString() ?? "0.0.0"; + } + } +} diff --git a/src/Openza.Reader/Pages/SettingsPage.xaml b/src/Openza.Reader/Pages/SettingsPage.xaml new file mode 100644 index 0000000..0155dc1 --- /dev/null +++ b/src/Openza.Reader/Pages/SettingsPage.xaml @@ -0,0 +1,224 @@ + + + 4 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Openza.Reader/Shell/ReaderShell.xaml.cs b/src/Openza.Reader/Shell/ReaderShell.xaml.cs new file mode 100644 index 0000000..32c7d86 --- /dev/null +++ b/src/Openza.Reader/Shell/ReaderShell.xaml.cs @@ -0,0 +1,828 @@ +using Microsoft.UI.Dispatching; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Controls.Primitives; +using Microsoft.UI.Xaml.Input; +using Microsoft.Web.WebView2.Core; +using Openza.Reader; +using Openza.Reader.Controls; +using Openza.Reader.Models; +using Openza.Reader.Pages; +using Openza.Reader.Services; +using Openza.Reader.ViewModels; +using System.Globalization; +using System.Text.Json; +using Windows.ApplicationModel.DataTransfer; +using Windows.Storage; +using Windows.Storage.Pickers; +using Windows.System; +using WinRT.Interop; + +namespace Openza.Reader.Shell; + +public sealed partial class ReaderShell : UserControl +{ + private readonly Window _owner; + private readonly MarkdownRenderer _renderer; + private readonly HtmlShellBuilder _shellBuilder; + private readonly TempHtmlDocumentStore _documentStore; + private readonly ExternalEditorService _externalEditor; + private readonly AppSettingsService _settingsService; + private readonly MainWindowViewModel _viewModel = new(); + private readonly Microsoft.UI.Dispatching.DispatcherQueueTimer _reloadTimer; + private ReaderSettings _readerSettings; + private FileSystemWatcher? _watcher; + private string? _currentFilePath; + private Uri? _currentHtmlUri; + private DocumentViewMode _viewMode; + private SettingsPage? _activeSettingsPage; + private ReaderEmptyStateControl? _activeRecentFilesPage; + private bool _isFocusMode; + private double _zoomFactor = 1.0; + + public ReaderShell( + Window owner, + MarkdownRenderer renderer, + HtmlShellBuilder shellBuilder, + TempHtmlDocumentStore documentStore, + ExternalEditorService externalEditor, + AppSettingsService settingsService) + { + _owner = owner; + _renderer = renderer; + _shellBuilder = shellBuilder; + _documentStore = documentStore; + _externalEditor = externalEditor; + _settingsService = settingsService; + _readerSettings = _settingsService.Load(); + _viewMode = _readerSettings.DefaultViewMode; + + InitializeComponent(); + TocPane.TocItemInvoked += OnTocItemInvoked; + EmptyState.OpenFileRequested += OnEmptyStateOpenFileRequested; + EmptyState.ClearRecentFilesRequested += OnEmptyStateClearRecentFilesRequested; + EmptyState.RecentFileInvoked += OnRecentFileInvoked; + AddKeyboardAccelerators(); + RefreshRecentFiles(); + SetViewMode(_viewMode); + + _reloadTimer = DispatcherQueue.CreateTimer(); + _reloadTimer.Interval = TimeSpan.FromMilliseconds(350); + _reloadTimer.Tick += async (_, _) => + { + _reloadTimer.Stop(); + await ReloadAsync(preserveScroll: true); + }; + } + + public FrameworkElement TitleBarElement => AppTitleBar; + + public async Task EnsureWebViewAsync() + { + if (ReaderWebView.CoreWebView2 is not null) + { + return true; + } + + try + { + await ReaderWebView.EnsureCoreWebView2Async(); + } + catch (Exception exception) + { + AppLog.Write(exception); + ShowWebViewRuntimeUnavailable(); + return false; + } + + var core = ReaderWebView.CoreWebView2 ?? throw new InvalidOperationException("WebView2 failed to initialize."); + var settings = core.Settings; + settings.AreDefaultScriptDialogsEnabled = false; + settings.AreHostObjectsAllowed = false; + settings.IsWebMessageEnabled = false; + settings.IsScriptEnabled = true; + settings.IsStatusBarEnabled = false; + settings.AreDevToolsEnabled = false; + core.NavigationStarting += OnNavigationStarting; + return true; + } + + public async Task OpenFileAsync(string filePath) + { + if (!File.Exists(filePath)) + { + ShowInfo("File not found", "The selected Markdown file no longer exists.", InfoBarSeverity.Warning); + return; + } + + _currentFilePath = filePath; + HideWorkspace(); + SetViewMode(_readerSettings.DefaultViewMode); + SetWindowTitle($"{Path.GetFileName(filePath)} - Openza Reader"); + await RenderCurrentFileAsync(preserveScroll: false); + StartWatcher(filePath); + _settingsService.AddRecentFile(filePath); + RefreshRecentFiles(); + } + + public void Close() + { + _watcher?.Dispose(); + } + + private void AddKeyboardAccelerators() + { + var find = new KeyboardAccelerator { Key = VirtualKey.F, Modifiers = VirtualKeyModifiers.Control }; + find.Invoked += async (_, args) => + { + args.Handled = true; + await StartFindAsync(); + }; + KeyboardAccelerators.Add(find); + + var focus = new KeyboardAccelerator { Key = VirtualKey.F11 }; + focus.Invoked += (_, args) => + { + args.Handled = true; + SetFocusMode(!_isFocusMode); + }; + KeyboardAccelerators.Add(focus); + + var exitFocus = new KeyboardAccelerator { Key = VirtualKey.Escape }; + exitFocus.Invoked += (_, args) => + { + if (FocusButton.IsChecked == true) + { + args.Handled = true; + SetFocusMode(false); + } + }; + KeyboardAccelerators.Add(exitFocus); + } + + private void SetWindowTitle(string title) + { + _owner.Title = title; + TitleTextBlock.Text = title; + } + + private async Task RenderCurrentFileAsync(bool preserveScroll) + { + if (_currentFilePath is null) + { + return; + } + + if (!await EnsureWebViewAsync()) + { + return; + } + + var scrollState = preserveScroll ? await CaptureScrollStateAsync() : null; + var markdown = await File.ReadAllTextAsync(_currentFilePath); + var allowRemoteImages = _readerSettings.RemoteImages == RemoteImagePolicy.Allow; + var result = _renderer.Render(markdown, _currentFilePath, allowRemoteImages); + var html = _shellBuilder.Build( + result, + Path.GetFileName(_currentFilePath), + ReaderThemeName(_readerSettings.ReaderTheme), + allowRemoteImages); + _currentHtmlUri = await _documentStore.WriteAsync(_currentFilePath, html); + + RawMarkdownTextBox.Text = markdown; + _viewModel.SetDocument(result); + TocPane.SetItems(_viewModel.TocItems); + EmptyState.Visibility = Visibility.Collapsed; + UpdateStats(result.Stats); + SetTocVisible(_viewModel.TocItems.Count > 0 && ActualWidth >= 900 && CanShowToc()); + ApplyViewMode(); + ReaderWebView.CoreWebView2.Navigate(_currentHtmlUri.AbsoluteUri); + + if (scrollState is not null) + { + ReaderWebView.CoreWebView2.NavigationCompleted += RestoreAfterNavigation; + } + else + { + ReaderWebView.CoreWebView2.NavigationCompleted += ApplyZoomAfterNavigation; + } + + async void RestoreAfterNavigation(CoreWebView2 sender, CoreWebView2NavigationCompletedEventArgs args) + { + sender.NavigationCompleted -= RestoreAfterNavigation; + await ApplyZoomAsync(); + await RestoreScrollStateAsync(scrollState); + } + + async void ApplyZoomAfterNavigation(CoreWebView2 sender, CoreWebView2NavigationCompletedEventArgs args) + { + sender.NavigationCompleted -= ApplyZoomAfterNavigation; + await ApplyZoomAsync(); + } + } + + private void OnNavigationStarting(CoreWebView2 sender, CoreWebView2NavigationStartingEventArgs args) + { + if (!Uri.TryCreate(args.Uri, UriKind.Absolute, out var uri)) + { + args.Cancel = true; + return; + } + + if (IsCurrentGeneratedDocument(uri)) + { + return; + } + + if (uri.Scheme is "http" or "https" or "mailto") + { + args.Cancel = true; + _ = Windows.System.Launcher.LaunchUriAsync(uri); + return; + } + + args.Cancel = true; + } + + private bool IsCurrentGeneratedDocument(Uri uri) + { + return _currentHtmlUri is not null + && uri.IsFile + && string.Equals(uri.LocalPath, _currentHtmlUri.LocalPath, StringComparison.OrdinalIgnoreCase); + } + + private async Task CaptureScrollStateAsync() + { + if (ReaderWebView.CoreWebView2 is null) + { + return null; + } + + return await ReaderWebView.CoreWebView2.ExecuteScriptAsync( + "({ y: window.scrollY, h: Math.max(1, document.documentElement.scrollHeight - window.innerHeight) })"); + } + + private async Task RestoreScrollStateAsync(string? scrollJson) + { + if (string.IsNullOrWhiteSpace(scrollJson) || ReaderWebView.CoreWebView2 is null) + { + return; + } + + var script = """ + (() => { + const rawState = __SCROLL_STATE__; + const state = typeof rawState === 'string' ? JSON.parse(rawState) : rawState; + const max = Math.max(1, document.documentElement.scrollHeight - window.innerHeight); + const ratio = state.h > 0 ? state.y / state.h : 0; + window.scrollTo(0, Math.max(0, max * ratio)); + })(); + """.Replace("__SCROLL_STATE__", scrollJson, StringComparison.Ordinal); + await ReaderWebView.CoreWebView2.ExecuteScriptAsync(script); + } + + private void StartWatcher(string filePath) + { + _watcher?.Dispose(); + var directory = Path.GetDirectoryName(filePath); + var fileName = Path.GetFileName(filePath); + if (directory is null) + { + return; + } + + _watcher = new FileSystemWatcher(directory, fileName) + { + NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.Size + }; + _watcher.Changed += QueueReload; + _watcher.Created += QueueReload; + _watcher.Renamed += QueueReload; + _watcher.Deleted += QueueReload; + _watcher.EnableRaisingEvents = true; + } + + private void QueueReload(object sender, FileSystemEventArgs e) + { + _ = DispatcherQueue.TryEnqueue(() => + { + if (e.ChangeType == WatcherChangeTypes.Deleted) + { + EmptyState.Visibility = Visibility.Visible; + RawMarkdownTextBox.Text = string.Empty; + SetTocVisible(false); + ShowInfo("File deleted", "The current file was deleted outside Openza Reader.", InfoBarSeverity.Warning); + return; + } + + _reloadTimer.Stop(); + _reloadTimer.Start(); + }); + } + + private async Task ReloadAsync(bool preserveScroll) + { + if (_currentFilePath is null) + { + return; + } + + if (File.Exists(_currentFilePath)) + { + await RenderCurrentFileAsync(preserveScroll); + } + else + { + ShowInfo("File not found", "The current file no longer exists.", InfoBarSeverity.Warning); + } + } + + private async void OnOpenClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + await PickAndOpenFileAsync(); + } + + private async Task PickAndOpenFileAsync() + { + var picker = new FileOpenPicker(); + InitializeWithWindow.Initialize(picker, WindowNative.GetWindowHandle(_owner)); + picker.FileTypeFilter.Add(".md"); + picker.FileTypeFilter.Add(".markdown"); + var file = await picker.PickSingleFileAsync(); + if (file is not null) + { + await OpenFileAsync(file.Path); + } + } + + private async void OnReloadClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + await ReloadAsync(preserveScroll: false); + } + + private void OnRecentClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + HideWorkspace(); + var page = CreateRecentFilesPage(); + ShowWorkspace("Recent files", "Open a recent Markdown document or choose another file.", page); + } + + private async void OnSearchClicked(object sender, RoutedEventArgs e) + { + await StartFindAsync(); + } + + private async Task StartFindAsync() + { + if (_viewMode == DocumentViewMode.Raw) + { + RawMarkdownTextBox.Focus(FocusState.Programmatic); + return; + } + + if (!await EnsureWebViewAsync()) + { + return; + } + + if (ReaderWebView.CoreWebView2 is null) + { + return; + } + + var options = ReaderWebView.CoreWebView2.Environment.CreateFindOptions(); + options.FindTerm = string.Empty; + options.ShouldHighlightAllMatches = true; + options.SuppressDefaultFindDialog = false; + await ReaderWebView.CoreWebView2.Find.StartAsync(options); + } + + private void OnToggleTocClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + SetTocVisible(TocPane.Visibility != Visibility.Visible && CanShowToc()); + } + + private void OnZoomOutClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + _zoomFactor = Math.Max(0.5, _zoomFactor - 0.1); + _ = ApplyZoomAsync(); + } + + private void OnZoomInClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + _zoomFactor = Math.Min(2.5, _zoomFactor + 0.1); + _ = ApplyZoomAsync(); + } + + private async Task ApplyZoomAsync() + { + if (ReaderWebView.CoreWebView2 is null) + { + return; + } + + await ReaderWebView.CoreWebView2.ExecuteScriptAsync( + $"document.documentElement.style.zoom = '{_zoomFactor.ToString(CultureInfo.InvariantCulture)}'"); + } + + private async void OnCopyClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + var rawSelection = RawMarkdownTextBox.SelectedText; + if ((_viewMode == DocumentViewMode.Raw || RawMarkdownTextBox.FocusState != FocusState.Unfocused) && + !string.IsNullOrEmpty(rawSelection)) + { + CopyText(rawSelection); + return; + } + + if (ReaderWebView.CoreWebView2 is null) + { + return; + } + + var json = await ReaderWebView.CoreWebView2.ExecuteScriptAsync("window.getSelection().toString()"); + var selectedText = JsonSerializer.Deserialize(json); + if (!string.IsNullOrEmpty(selectedText)) + { + CopyText(selectedText); + } + } + + private async void OnOpenExternalClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + if (_currentFilePath is not null) + { + var launched = await _externalEditor.OpenWithPickerAsync(_currentFilePath); + if (!launched) + { + ShowInfo("Editor unavailable", "Windows could not find an app to edit this Markdown file.", InfoBarSeverity.Warning); + } + } + } + + private void OnFocusClicked(object sender, RoutedEventArgs e) + { + SetFocusMode(FocusButton.IsChecked == true); + } + + private void OnExitFocusClicked(object sender, RoutedEventArgs e) + { + SetFocusMode(false); + } + + private void OnSettingsClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + HideWorkspace(); + var page = new SettingsPage(); + page.Load(_readerSettings, _settingsService.LoadRecentFiles()); + page.SettingsChanged += OnSettingsPageChanged; + page.ClearRecentFilesClicked += (_, _) => + { + _settingsService.ClearRecentFiles(); + RefreshRecentFiles(); + }; + + _activeSettingsPage = page; + ShowWorkspace("Settings", "Reader preferences and local app data.", page); + } + + private async void OnSettingsPageChanged(object? sender, EventArgs e) + { + if (sender is not SettingsPage page) + { + return; + } + + page.ApplyTo(_readerSettings); + _settingsService.Save(_readerSettings); + if (_currentFilePath is not null) + { + await RenderCurrentFileAsync(preserveScroll: true); + } + else + { + UpdateStats(null); + } + } + + private void OnAboutClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + HideWorkspace(); + ShowWorkspace( + "About Openza Reader", + "Version, project links, license, and security information.", + new AboutPage()); + } + + private void OnCloseWorkspaceClicked(object sender, RoutedEventArgs e) + { + HideWorkspace(); + } + + private void OnPreviewModeClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + SetViewMode(DocumentViewMode.Preview); + } + + private void OnRawModeClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + SetViewMode(DocumentViewMode.Raw); + } + + private void OnSideBySideModeClicked(object sender, RoutedEventArgs e) + { + KeepToolbarLabelsVisible(); + SetViewMode(DocumentViewMode.SideBySide); + } + + private void OnReaderCommandBarClosed(object sender, object e) + { + KeepToolbarLabelsVisible(); + } + + private async void OnTocItemInvoked(object? sender, TocEntryViewModel tocItem) + { + if (_currentHtmlUri is null || ReaderWebView.CoreWebView2 is null) + { + return; + } + + var builder = new UriBuilder(_currentHtmlUri) { Fragment = Uri.EscapeDataString(tocItem.Id) }; + ReaderWebView.CoreWebView2.Navigate(builder.Uri.AbsoluteUri); + await Task.CompletedTask; + } + + private async void OnRecentFileInvoked(object? sender, string path) + { + await OpenFileAsync(path); + } + + private async void OnEmptyStateOpenFileRequested(object? sender, EventArgs e) + { + await PickAndOpenFileAsync(); + } + + private void OnEmptyStateClearRecentFilesRequested(object? sender, EventArgs e) + { + _settingsService.ClearRecentFiles(); + RefreshRecentFiles(); + } + + private async void OnDrop(object sender, DragEventArgs e) + { + if (!e.DataView.Contains(StandardDataFormats.StorageItems)) + { + return; + } + + var items = await e.DataView.GetStorageItemsAsync(); + var firstMarkdown = items.OfType() + .FirstOrDefault(file => file.FileType.Equals(".md", StringComparison.OrdinalIgnoreCase) + || file.FileType.Equals(".markdown", StringComparison.OrdinalIgnoreCase)); + if (firstMarkdown is not null) + { + await OpenFileAsync(firstMarkdown.Path); + } + } + + private void OnDragOver(object sender, DragEventArgs e) + { + e.AcceptedOperation = DataPackageOperation.Copy; + } + + private void OnContentSizeChanged(object sender, SizeChangedEventArgs e) + { + if (e.NewSize.Width < 900 && TocPane.Visibility == Visibility.Visible) + { + SetTocVisible(false); + } + } + + private void SetViewMode(DocumentViewMode mode) + { + _viewMode = mode; + SelectViewMode(mode); + ApplyViewMode(); + } + + private void SelectViewMode(DocumentViewMode mode) + { + PreviewModeItem.IsChecked = mode == DocumentViewMode.Preview; + RawModeItem.IsChecked = mode == DocumentViewMode.Raw; + SideBySideModeItem.IsChecked = mode == DocumentViewMode.SideBySide; + ViewModeButton.Label = "View"; + ToolTipService.SetToolTip(ViewModeButton, $"View mode: {ViewModeLabel(mode)}"); + } + + private void ApplyViewMode() + { + switch (_viewMode) + { + case DocumentViewMode.Raw: + RawColumn.Width = new GridLength(1, GridUnitType.Star); + ReaderDividerColumn.Width = new GridLength(0); + PreviewColumn.Width = new GridLength(0); + SearchButton.IsEnabled = false; + TocButton.IsEnabled = false; + SetTocVisible(false); + break; + case DocumentViewMode.SideBySide: + RawColumn.Width = new GridLength(1, GridUnitType.Star); + ReaderDividerColumn.Width = new GridLength(1); + PreviewColumn.Width = new GridLength(1, GridUnitType.Star); + SearchButton.IsEnabled = true; + TocButton.IsEnabled = _viewModel.TocItems.Count > 0; + break; + default: + RawColumn.Width = new GridLength(0); + ReaderDividerColumn.Width = new GridLength(0); + PreviewColumn.Width = new GridLength(1, GridUnitType.Star); + SearchButton.IsEnabled = true; + TocButton.IsEnabled = _viewModel.TocItems.Count > 0; + break; + } + } + + private void SetTocVisible(bool visible) + { + var actualVisible = visible && CanShowToc() && _viewModel.TocItems.Count > 0; + TocPane.Visibility = actualVisible ? Visibility.Visible : Visibility.Collapsed; + TocColumn.Width = actualVisible ? new GridLength(300) : new GridLength(0); + } + + private bool CanShowToc() => _viewMode is DocumentViewMode.Preview or DocumentViewMode.SideBySide; + + private void RefreshRecentFiles() + { + var recent = _settingsService.LoadRecentFiles(); + _viewModel.SetRecentFiles(recent); + EmptyState.SetRecentFiles(_viewModel.RecentFiles); + _activeRecentFilesPage?.SetRecentFiles(_viewModel.RecentFiles); + } + + private void UpdateStats(DocumentStats? stats) + { + if (!_readerSettings.ShowDocumentStats || stats is null) + { + DocumentStatsText.Text = string.Empty; + return; + } + + var readTime = stats.EstimatedReadMinutes == 1 ? "1 min read" : $"{stats.EstimatedReadMinutes} min read"; + DocumentStatsText.Text = $"{stats.WordCount:n0} words - {readTime} - {stats.HeadingCount:n0} headings"; + } + + private void SetFocusMode(bool enabled) + { + if (_isFocusMode == enabled) + { + return; + } + + _isFocusMode = enabled; + FocusButton.IsChecked = enabled; + if (enabled) + { + HideWorkspace(); + } + + TitleBarRow.Height = enabled ? new GridLength(0) : new GridLength(40); + ToolbarRow.Height = enabled ? new GridLength(0) : GridLength.Auto; + InfoBarRow.Height = enabled ? new GridLength(0) : GridLength.Auto; + AppTitleBar.Visibility = enabled ? Visibility.Collapsed : Visibility.Visible; + ToolbarHost.Visibility = enabled ? Visibility.Collapsed : Visibility.Visible; + DocumentInfoBar.Visibility = enabled ? Visibility.Collapsed : Visibility.Visible; + FocusExitButton.Visibility = enabled ? Visibility.Visible : Visibility.Collapsed; + SetTocVisible(false); + + if (_owner is MainWindow mainWindow) + { + mainWindow.SetImmersiveFocus(enabled); + } + + if (!enabled) + { + SetTocVisible(_viewModel.TocItems.Count > 0 && ActualWidth >= 900 && CanShowToc()); + } + } + + private void ShowWorkspace(string title, string subtitle, UIElement content) + { + SetFocusMode(false); + PageWorkspaceTitle.Text = title; + PageWorkspaceSubtitle.Text = subtitle; + PageWorkspaceContent.Content = content; + PageWorkspace.Visibility = Visibility.Visible; + SetTocVisible(false); + } + + private void HideWorkspace() + { + if (_activeSettingsPage is not null) + { + _activeSettingsPage.SettingsChanged -= OnSettingsPageChanged; + _activeSettingsPage = null; + } + + if (_activeRecentFilesPage is not null) + { + _activeRecentFilesPage.OpenFileRequested -= OnEmptyStateOpenFileRequested; + _activeRecentFilesPage.ClearRecentFilesRequested -= OnEmptyStateClearRecentFilesRequested; + _activeRecentFilesPage.RecentFileInvoked -= OnRecentFileInvoked; + _activeRecentFilesPage = null; + } + + PageWorkspaceContent.Content = null; + PageWorkspace.Visibility = Visibility.Collapsed; + SetTocVisible(_viewModel.TocItems.Count > 0 && ActualWidth >= 900 && CanShowToc()); + } + + private ReaderEmptyStateControl CreateRecentFilesPage() + { + var page = new ReaderEmptyStateControl(); + page.OpenFileRequested += OnEmptyStateOpenFileRequested; + page.ClearRecentFilesRequested += OnEmptyStateClearRecentFilesRequested; + page.RecentFileInvoked += OnRecentFileInvoked; + page.SetRecentFiles(_viewModel.RecentFiles); + _activeRecentFilesPage = page; + return page; + } + + private void ShowInfo(string title, string message, InfoBarSeverity severity, ButtonBase? actionButton = null) + { + DocumentInfoBar.Title = title; + DocumentInfoBar.Message = message; + DocumentInfoBar.Severity = severity; + DocumentInfoBar.ActionButton = actionButton; + DocumentInfoBar.IsOpen = true; + } + + private void ShowWebViewRuntimeUnavailable() + { + var runtimeButton = new HyperlinkButton + { + Content = "Get WebView2 Runtime", + NavigateUri = new Uri("https://developer.microsoft.com/microsoft-edge/webview2/") + }; + + ShowInfo( + "WebView2 Runtime unavailable", + "Install or repair Microsoft Edge WebView2 Runtime to render Markdown preview.", + InfoBarSeverity.Error, + runtimeButton); + } + + private void KeepToolbarLabelsVisible() + { + if (_isFocusMode) + { + return; + } + + _ = DispatcherQueue.TryEnqueue(() => + { + ReaderCommandBar.IsSticky = true; + ReaderCommandBar.IsOpen = true; + }); + } + + private static string ReaderThemeName(ReaderThemeKind theme) + { + return theme switch + { + ReaderThemeKind.Light => "light", + ReaderThemeKind.Dark => "dark", + ReaderThemeKind.Sepia => "sepia", + _ => "system" + }; + } + + private static string ViewModeLabel(DocumentViewMode mode) + { + return mode switch + { + DocumentViewMode.Raw => "Raw", + DocumentViewMode.SideBySide => "Side by side", + _ => "Preview" + }; + } + + private static void CopyText(string text) + { + var package = new DataPackage(); + package.SetText(text); + Clipboard.SetContent(package); + } +} diff --git a/src/Openza.Reader/ViewModels/MainWindowViewModel.cs b/src/Openza.Reader/ViewModels/MainWindowViewModel.cs index c0c1072..e56d0ee 100644 --- a/src/Openza.Reader/ViewModels/MainWindowViewModel.cs +++ b/src/Openza.Reader/ViewModels/MainWindowViewModel.cs @@ -11,6 +11,8 @@ public sealed partial class MainWindowViewModel : ObservableObject public ObservableCollection TocItems { get; } = []; + public ObservableCollection RecentFiles { get; } = []; + public void SetDocument(MarkdownRenderResult result) { Title = result.Title; @@ -20,4 +22,13 @@ public void SetDocument(MarkdownRenderResult result) TocItems.Add(TocEntryViewModel.FromModel(item)); } } + + public void SetRecentFiles(IEnumerable files) + { + RecentFiles.Clear(); + foreach (var file in files) + { + RecentFiles.Add(file); + } + } } diff --git a/website/src/content/docs/development/architecture.mdx b/website/src/content/docs/development/architecture.mdx index 5f44013..0a98f64 100644 --- a/website/src/content/docs/development/architecture.mdx +++ b/website/src/content/docs/development/architecture.mdx @@ -5,7 +5,7 @@ description: Understanding the Openza Reader codebase # Architecture -Openza Reader separates Markdown rendering logic from the WinUI shell. +Openza Reader separates Markdown rendering logic from the WinUI shell. The WinUI app is split into a thin window host, a reader shell, pages, controls, services, models, and view models so the main window does not own the whole app surface. ## Project Structure @@ -13,8 +13,13 @@ Openza Reader separates Markdown rendering logic from the WinUI shell. src/ ├── Openza.Reader/ # WinUI 3 packaged app │ ├── App.xaml.cs # App startup and file activation -│ ├── MainWindow.xaml(.cs) # Reader window and WebView orchestration +│ ├── MainWindow.xaml(.cs) # Thin native window host │ ├── Assets/ # Reader CSS and local highlighting assets +│ ├── Controls/ # Reusable TOC and empty-state controls +│ ├── Models/ # App settings and view-mode models +│ ├── Pages/ # Settings and About surfaces +│ ├── Services/ # App settings, recents, and external editor launch +│ ├── Shell/ # Reader shell and WebView orchestration │ └── ViewModels/ # Window and TOC view models │ ├── Openza.Reader.Core/ # Markdown rendering and policies @@ -22,7 +27,7 @@ src/ │ │ ├── MarkdownRenderer.cs │ │ ├── HtmlShellBuilder.cs │ │ ├── LinkPolicy.cs -│ │ └── ExternalEditorService.cs +│ │ └── DocumentStatsCalculator.cs │ └── Models/ │ └── Openza.Reader.Tests/ # Renderer and policy tests diff --git a/website/src/content/docs/development/contributing.mdx b/website/src/content/docs/development/contributing.mdx index 989ea38..ebac96c 100644 --- a/website/src/content/docs/development/contributing.mdx +++ b/website/src/content/docs/development/contributing.mdx @@ -14,7 +14,7 @@ Please keep contributions aligned with the V1 reader scope: - Read-only Markdown viewing - Safe rendering - Native Windows app behavior -- TOC, search, zoom, reload, copy, and external editor workflows +- TOC, view modes, search, settings, recents, zoom, reload, copy, and external editor workflows Editing, tabs, export, Mermaid, math rendering, plugins, sync, accounts, and AI features are out of scope for V1 unless an issue explicitly changes that. diff --git a/website/src/content/docs/features/markdown-rendering.mdx b/website/src/content/docs/features/markdown-rendering.mdx index 18bb2a7..177b9c7 100644 --- a/website/src/content/docs/features/markdown-rendering.mdx +++ b/website/src/content/docs/features/markdown-rendering.mdx @@ -16,7 +16,8 @@ Openza Reader renders Markdown through Markdig and displays the generated HTML i - Fenced code blocks - Blockquotes - Links -- Local and remote images +- Local images +- Optional remote images ## Code Highlighting @@ -27,3 +28,7 @@ Reader bundles small Prism-compatible highlighting assets locally. There is no C Raw HTML inside Markdown files is disabled in V1. HTML-like input is escaped and displayed as text instead of being interpreted by the WebView. Limited sanitized HTML compatibility may be considered later, but it is not part of V1. + +## Reader Themes + +Rendered Markdown supports System, Light, Dark, and Sepia reader themes. Windows High Contrast behavior remains controlled by the operating system. diff --git a/website/src/content/docs/features/navigation-search.mdx b/website/src/content/docs/features/navigation-search.mdx index 9ea6ed9..a9a7a8b 100644 --- a/website/src/content/docs/features/navigation-search.mdx +++ b/website/src/content/docs/features/navigation-search.mdx @@ -7,13 +7,17 @@ description: TOC, search, zoom, and reload behavior Openza Reader keeps the main reading surface quiet while exposing the controls needed for larger Markdown files. +## View Modes + +The toolbar View menu switches between Preview, Raw, and Side by side modes. Preview is the default rendered Markdown view. Raw shows selectable, read-only Markdown text. Side by side shows the raw Markdown and rendered preview in equal panes. + ## Table Of Contents -The table of contents is generated from document headings. It can be shown or hidden from the toolbar and is intended to stay out of the way on narrow windows. +The table of contents is generated from document headings. It can be shown or hidden from the toolbar in Preview and Side by side modes, and it stays hidden in Raw mode. ## Search -Search uses WebView2's native Find API instead of custom page JavaScript. +Search uses WebView2's native Find API instead of custom page JavaScript. The toolbar includes a visible Search button for discoverability, and `Ctrl+F` follows the native WebView2 find flow. ## Zoom diff --git a/website/src/content/docs/features/security-model.mdx b/website/src/content/docs/features/security-model.mdx index 3a1d654..b1ed297 100644 --- a/website/src/content/docs/features/security-model.mdx +++ b/website/src/content/docs/features/security-model.mdx @@ -27,7 +27,7 @@ Openza Reader treats Markdown files as untrusted content. - `http`, `https`, and `mailto` links open externally. - `javascript:`, arbitrary `file:`, and unknown schemes are blocked. - Local images resolve relative to the opened Markdown file. -- Remote images are allowed for README compatibility. +- Remote images are controlled by the user setting and can be blocked for privacy. ## Future HTML Compatibility diff --git a/website/src/content/docs/getting-started/introduction.mdx b/website/src/content/docs/getting-started/introduction.mdx index e783424..e0c65aa 100644 --- a/website/src/content/docs/getting-started/introduction.mdx +++ b/website/src/content/docs/getting-started/introduction.mdx @@ -9,7 +9,7 @@ import { Card, CardGrid } from '@astrojs/starlight/components'; Openza Reader is a Windows-first Markdown reader for people who want to open `.md` and `.markdown` files quickly, read them comfortably, and avoid accidental edits. -It is intentionally small: open a file, render it safely, navigate headings, search text, adjust zoom, and return to your work. +It is intentionally small: open a file, render it safely, switch view modes, navigate headings, search text, adjust zoom, and return to your work. ## What It Does @@ -21,7 +21,7 @@ It is intentionally small: open a file, render it safely, navigate headings, sea A table of contents is generated from Markdown headings. - Typography, zoom controls, and rendered-selection copy are tuned for reading. + Reader themes, view modes, document stats, zoom controls, and copy behavior are tuned for reading. Changed files can be reloaded with a debounce while preserving your approximate position. @@ -30,7 +30,7 @@ It is intentionally small: open a file, render it safely, navigate headings, sea ## V1 Scope -Openza Reader V1 is an MVP focused on Markdown reading. Editing, tabs, export, Mermaid, math rendering, plugins, sync, accounts, and AI features are intentionally out of scope. +Openza Reader V1 is focused on read-only Markdown reading. Editing, tabs, export, Mermaid, math rendering, plugins, sync, accounts, and AI features are intentionally out of scope. ## Status diff --git a/website/src/content/docs/getting-started/reading-markdown.mdx b/website/src/content/docs/getting-started/reading-markdown.mdx index a1aae7d..8613cb0 100644 --- a/website/src/content/docs/getting-started/reading-markdown.mdx +++ b/website/src/content/docs/getting-started/reading-markdown.mdx @@ -19,6 +19,10 @@ You can open Markdown files by: The table of contents is generated from headings in the Markdown document. Select a heading to jump to that section. +## Choose A View + +Use Preview for the rendered reading surface, Raw for selectable read-only Markdown text, or Side by side to compare both views. + ## Search Use the app search command to find text in the rendered document. Search is implemented through WebView2's native Find API. @@ -29,4 +33,8 @@ Use zoom controls to adjust the reading size. Select rendered text and copy it f ## External Editor -Openza Reader stays read-only. Use the external editor command when you want to edit the current file in your system editor. +Openza Reader stays read-only. Use the Editor command when you want Windows to show installed apps that can edit the current Markdown file. + +## Settings And Recents + +Settings include default view mode, reader theme, remote image policy, document stats, and recent file controls. Recent files stay local to the current Windows account. diff --git a/website/src/content/docs/index.mdx b/website/src/content/docs/index.mdx index 2a23e47..9cea988 100644 --- a/website/src/content/docs/index.mdx +++ b/website/src/content/docs/index.mdx @@ -25,12 +25,12 @@ import { Card, CardGrid } from '@astrojs/starlight/components'; A modern WinUI 3 interface built for Windows 10 and Windows 11, packaged with MSIX. - Open Markdown files quickly in a clean reading surface with typography, zoom, and copy support. + Open Markdown files quickly in Preview, Raw, or Side by side read-only modes. Markdown is treated as untrusted input. Raw HTML is escaped and navigation is intercepted. - Use table of contents navigation, search, zoom, reload, copy, and external editor actions. + Use table of contents navigation, search, themes, recents, zoom, reload, copy, and external editor actions. diff --git a/website/src/content/docs/release/store-submission.mdx b/website/src/content/docs/release/store-submission.mdx index 612600c..a13ae16 100644 --- a/website/src/content/docs/release/store-submission.mdx +++ b/website/src/content/docs/release/store-submission.mdx @@ -32,6 +32,16 @@ Short description: Native WinUI 3 Markdown reader for Windows. ``` +Description: + +```text +Openza Reader is a native Markdown reader for Windows, built with WinUI 3, WebView2, and MSIX packaging. + +Open Markdown files from File Explorer, drag and drop documents into the app, reopen recent files, browse headings with a table of contents, search rendered text, adjust zoom, copy selected content, and choose an installed editor from Windows when you need to make changes. + +Openza Reader focuses on clean, safe reading. Switch between Preview, Raw, and Side by side read-only modes, choose a reader theme, and control remote image loading from Settings. Markdown is treated as untrusted input, raw HTML is escaped, scripts are blocked by construction, and external navigation is handled through the system browser. +``` + Support URL: ```text @@ -56,11 +66,24 @@ Category: Productivity ``` +## Package Notes + +- Target: Windows 10 22H2 and Windows 11. +- Minimum package version: `10.0.19045.0`. +- Max tested version in the source and generated manifest: `10.0.26100.0`. +- Architecture: x64 for V1. +- Runtime: build and package as self-contained for normal user installs; verify on a clean machine without .NET 10 before submission. +- WebView2: verify the Runtime is present or that Openza Reader shows the WebView2 install/repair prompt if it is missing or broken. +- Release blockers: GitHub issues #12, #13, #14, and #16 must be verified or explicitly deferred before release. + ## Release Smoke Test - Build Release x64 package. - Install package locally from Visual Studio. - Open the app from Start. - Open `.md` and `.markdown` files from File Explorer. -- Confirm drag and drop, TOC, search, zoom, copy, reload, and external editor actions. +- Confirm drag and drop, TOC, search button, Preview/Raw/Side by side modes, settings persistence, recents, themes, remote image policy, zoom, copy, reload, and external editor actions. +- Confirm launch on a clean Windows 10 22H2 or Windows 11 machine without .NET 10 installed. +- Confirm the packaged manifest uses `MinVersion="10.0.19045.0"` and `MaxVersionTested="10.0.26100.0"`. +- Confirm WebView2 Runtime missing/broken behavior before public submission. - Confirm uninstall removes the app cleanly.