From 7acc6ed6c84fa52524161c066932d08264ce185a Mon Sep 17 00:00:00 2001 From: Logan H Date: Tue, 8 Sep 2026 11:19:39 +0100 Subject: [PATCH 1/6] feat: Linux Port --- CLAUDE.md | 39 +- DEVELOPER.md | 51 +- LINUX_PORT.md | 117 +- MoneyShot.Core/Abstractions/IAutoStart.cs | 20 + MoneyShot.Core/Abstractions/IClipboard.cs | 11 + MoneyShot.Core/Abstractions/IGlobalHotkeys.cs | 24 + MoneyShot.Core/Abstractions/IScreenCapture.cs | 22 + MoneyShot.Core/Abstractions/ITrayIcon.cs | 24 + .../Models/AnnotationTool.cs | 0 .../Models/AppSettings.cs | 16 +- .../Models/CaptureMode.cs | 0 .../Models/HistoryEntry.cs | 0 .../Models/SaveDestination.cs | 0 MoneyShot.Core/MoneyShot.Core.csproj | 13 + .../Services/AutoUpdateService.cs | 14 +- .../Services/HotKeyParser.cs | 115 +- .../Services/Logger.cs | 2 +- .../Services/SettingsService.cs | 150 +- .../MemoryTrimmer.cs | 10 +- .../MoneyShot.Platform.Windows.csproj | 23 + MoneyShot.Platform.Windows/Win32AutoStart.cs | 140 ++ MoneyShot.Platform.Windows/Win32Clipboard.cs | 43 + .../Win32GlobalHotkeys.cs | 136 ++ .../Win32ScreenCapture.cs | 82 + MoneyShot.Platform.Windows/Win32TrayIcon.cs | 79 + MoneyShot.Tests/HotKeyServiceTests.cs | 77 +- MoneyShot.Tests/MoneyShot.Tests.csproj | 2 + MoneyShot.Tests/SaveServiceTests.cs | 3 +- MoneyShot.UI/App.axaml | 22 + MoneyShot.UI/App.axaml.cs | 104 + MoneyShot.UI/Editor/CanvasPosition.cs | 25 + MoneyShot.UI/Editor/CanvasRenderer.cs | 141 ++ MoneyShot.UI/Editor/ElementResizeMode.cs | 14 + MoneyShot.UI/Editor/ElementState.cs | 3 + MoneyShot.UI/Editor/UndoController.cs | 54 + MoneyShot.UI/Interop/BitmapConversions.cs | 74 + MoneyShot.UI/MoneyShot.UI.csproj | 69 + MoneyShot.UI/Program.cs | 17 + MoneyShot.UI/Services/HistoryService.cs | 166 ++ MoneyShot.UI/Services/SaveService.cs | 184 ++ MoneyShot.UI/Themes/CocoaTheme.axaml | 422 ++++ MoneyShot.UI/Views/EditorWindow.axaml | 319 +++ MoneyShot.UI/Views/EditorWindow.axaml.cs | 1943 +++++++++++++++++ MoneyShot.UI/Views/HistoryWindow.axaml | 100 + MoneyShot.UI/Views/HistoryWindow.axaml.cs | 177 ++ MoneyShot.UI/Views/MainWindow.axaml | 134 ++ MoneyShot.UI/Views/MainWindow.axaml.cs | 480 ++++ MoneyShot.UI/Views/RegionSelector.axaml | 33 + MoneyShot.UI/Views/RegionSelector.axaml.cs | 229 ++ MoneyShot.UI/Views/SettingsWindow.axaml | 216 ++ MoneyShot.UI/Views/SettingsWindow.axaml.cs | 278 +++ MoneyShot.UI/Views/SimpleMessageBox.cs | 89 + MoneyShot.UI/app.manifest | 31 + MoneyShot.sln | 44 +- MoneyShot/Interop/BitmapConversions.cs | 39 + MoneyShot/MainWindow.xaml.cs | 156 +- MoneyShot/MoneyShot.csproj | 5 + MoneyShot/Services/SaveService.cs | 15 +- MoneyShot/Services/ScreenshotService.cs | 87 - MoneyShot/Views/EditorWindow.xaml.cs | 3 +- MoneyShot/Views/HistoryWindow.xaml.cs | 3 +- MoneyShot/Views/SettingsWindow.xaml.cs | 21 +- Opus-Speaks.md | 99 - 63 files changed, 6378 insertions(+), 631 deletions(-) create mode 100644 MoneyShot.Core/Abstractions/IAutoStart.cs create mode 100644 MoneyShot.Core/Abstractions/IClipboard.cs create mode 100644 MoneyShot.Core/Abstractions/IGlobalHotkeys.cs create mode 100644 MoneyShot.Core/Abstractions/IScreenCapture.cs create mode 100644 MoneyShot.Core/Abstractions/ITrayIcon.cs rename {MoneyShot => MoneyShot.Core}/Models/AnnotationTool.cs (100%) rename {MoneyShot => MoneyShot.Core}/Models/AppSettings.cs (55%) rename {MoneyShot => MoneyShot.Core}/Models/CaptureMode.cs (100%) rename {MoneyShot => MoneyShot.Core}/Models/HistoryEntry.cs (100%) rename {MoneyShot => MoneyShot.Core}/Models/SaveDestination.cs (100%) create mode 100644 MoneyShot.Core/MoneyShot.Core.csproj rename {MoneyShot => MoneyShot.Core}/Services/AutoUpdateService.cs (99%) rename MoneyShot/Services/HotKeyService.cs => MoneyShot.Core/Services/HotKeyParser.cs (55%) rename {MoneyShot => MoneyShot.Core}/Services/Logger.cs (99%) rename {MoneyShot => MoneyShot.Core}/Services/SettingsService.cs (55%) rename {MoneyShot/Services => MoneyShot.Platform.Windows}/MemoryTrimmer.cs (74%) create mode 100644 MoneyShot.Platform.Windows/MoneyShot.Platform.Windows.csproj create mode 100644 MoneyShot.Platform.Windows/Win32AutoStart.cs create mode 100644 MoneyShot.Platform.Windows/Win32Clipboard.cs create mode 100644 MoneyShot.Platform.Windows/Win32GlobalHotkeys.cs create mode 100644 MoneyShot.Platform.Windows/Win32ScreenCapture.cs create mode 100644 MoneyShot.Platform.Windows/Win32TrayIcon.cs create mode 100644 MoneyShot.UI/App.axaml create mode 100644 MoneyShot.UI/App.axaml.cs create mode 100644 MoneyShot.UI/Editor/CanvasPosition.cs create mode 100644 MoneyShot.UI/Editor/CanvasRenderer.cs create mode 100644 MoneyShot.UI/Editor/ElementResizeMode.cs create mode 100644 MoneyShot.UI/Editor/ElementState.cs create mode 100644 MoneyShot.UI/Editor/UndoController.cs create mode 100644 MoneyShot.UI/Interop/BitmapConversions.cs create mode 100644 MoneyShot.UI/MoneyShot.UI.csproj create mode 100644 MoneyShot.UI/Program.cs create mode 100644 MoneyShot.UI/Services/HistoryService.cs create mode 100644 MoneyShot.UI/Services/SaveService.cs create mode 100644 MoneyShot.UI/Themes/CocoaTheme.axaml create mode 100644 MoneyShot.UI/Views/EditorWindow.axaml create mode 100644 MoneyShot.UI/Views/EditorWindow.axaml.cs create mode 100644 MoneyShot.UI/Views/HistoryWindow.axaml create mode 100644 MoneyShot.UI/Views/HistoryWindow.axaml.cs create mode 100644 MoneyShot.UI/Views/MainWindow.axaml create mode 100644 MoneyShot.UI/Views/MainWindow.axaml.cs create mode 100644 MoneyShot.UI/Views/RegionSelector.axaml create mode 100644 MoneyShot.UI/Views/RegionSelector.axaml.cs create mode 100644 MoneyShot.UI/Views/SettingsWindow.axaml create mode 100644 MoneyShot.UI/Views/SettingsWindow.axaml.cs create mode 100644 MoneyShot.UI/Views/SimpleMessageBox.cs create mode 100644 MoneyShot.UI/app.manifest create mode 100644 MoneyShot/Interop/BitmapConversions.cs delete mode 100644 MoneyShot/Services/ScreenshotService.cs delete mode 100644 Opus-Speaks.md diff --git a/CLAUDE.md b/CLAUDE.md index baeee9d..2354bb2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,17 +33,42 @@ All visual styling lives in `MoneyShot/Themes/CocoaTheme.xaml` (merged in `App.x - Code-behind looks styles up with `FindResource` (App-scoped), not `Resources[...]` (window-scoped). - The pixelate tool (`CanvasRenderer.CreatePixelatedBrush`) copies only the covered region's pixels once and block-averages in that buffer. Don't go back to rendering the full image into a `RenderTargetBitmap` — at 4K that allocated ~33 MB per pixelation plus a `CroppedBitmap` per block. +### Project split: MoneyShot.Core / MoneyShot.Platform.Windows / MoneyShot / MoneyShot.UI (Linux-port groundwork) + +The solution has five projects — see `LINUX_PORT.md` for the full rationale and the remaining +migration phases. **`MoneyShot` (WPF) is still the shipping app** — the MSI installer and CI +release pipeline both build it, unchanged. `MoneyShot.UI` (Avalonia) is additive: it exists to +prove out the Linux-port UI migration and is not wired into any release process. Don't touch the +WPF project's behavior when working on `MoneyShot.UI`, and don't assume `MoneyShot.UI` is +production-ready — see `LINUX_PORT.md` Phase 1 for exactly what has and hasn't been verified +there (short version: it builds and `MainWindow` has been visually confirmed working; +`EditorWindow`, `SettingsWindow`, `HistoryWindow`, `RegionSelector`, hotkeys, and the tray menu +have not been interactively tested). + +- **`MoneyShot.Core`** (`net10.0`, no UI/Windows dependency) — Models, `SettingsService`, `Logger`, + `AutoUpdateService`, `HotKeyParser`, and the platform abstraction interfaces under + `MoneyShot.Abstractions` (`IScreenCapture`, `IGlobalHotkeys`, `ITrayIcon`, `IAutoStart`, + `IClipboard`). `CapturedImage` (raw BGRA32 pixels) is the neutral bitmap type Core hands back + instead of a WPF `BitmapSource`. +- **`MoneyShot.Platform.Windows`** (`net10.0-windows`, no WPF dependency) — `Win32ScreenCapture`, + `Win32GlobalHotkeys`, `Win32TrayIcon`, `Win32AutoStart`, `Win32Clipboard`. Deliberately + UI-framework-agnostic (references WinForms only for `NotifyIcon`/`Clipboard`, not WPF) so the + same implementations keep working if the UI layer ever moves to Avalonia. +- **`MoneyShot`** (WPF) — every XAML window, plus `SaveService`/`HistoryService` (still + `BitmapSource`-based — these get an Avalonia twin only if/when Phase 1 of the port happens). + `Interop/BitmapConversions.cs` converts `CapturedImage` ↔ `BitmapSource` at the UI boundary. + ### Two windows + service layer (no DI, no MVVM framework) -Services are instantiated directly in `MainWindow` (`MainWindow.xaml.cs:31-35`). There is no DI container and no MVVM library — XAML is wired with code-behind throughout. New services should be added the same way; don't introduce a container for one or two extra dependencies. +Services are instantiated directly in `MainWindow`'s constructor and `InitializeApplication()`. There is no DI container and no MVVM library — XAML is wired with code-behind throughout. New services should be added the same way; don't introduce a container for one or two extra dependencies. -- **`MainWindow`** — system tray host + capture-mode entry points. Owns the `HotKeyService`, `NotifyIcon`, the auto-update flow, and the `HistoryService`. The window is typically hidden (`StartInTray=true` by default) and only re-shown on error or via tray menu. +- **`MainWindow`** — system tray host + capture-mode entry points. Owns an `IGlobalHotkeys` (`Win32GlobalHotkeys`), an `ITrayIcon` (`Win32TrayIcon`), the auto-update flow, and the `HistoryService`. The window is typically hidden (`StartInTray=true` by default) and only re-shown on error or via tray menu. - **`EditorWindow`** (`Views/EditorWindow.xaml.cs`, ~2000 lines) — the annotation editor. Still heavy code-behind: tool selection, drawing, selection/resize/move, crop, zoom, and save are in this file. The undo stack and rendering helpers were extracted into `MoneyShot/Editor/` (`UndoController`, `CanvasRenderer`, `CanvasPosition`, `ElementResizeMode`, `ElementState`). The `SelectionController` / `AnnotationToolRegistry` split is still pending — see `Opus-Speaks.md` Section A. New annotation tools follow the recipe in `DEVELOPER.md` (enum entry → toolbar button → `Create*` factory → switch case in `Canvas_MouseDown`). - **`HistoryWindow`** (`Views/HistoryWindow.xaml.cs`) — opened from the tray "History" menu. Renders a thumbnail grid backed by `HistoryService` (`%AppData%\MoneyShot\history`). Right-click → Open in Editor / Copy to Clipboard / Delete. ### Capture pipeline (and why the `Thread.Sleep` calls exist) -`ScreenshotService` uses GDI+ (`Graphics.CopyFromScreen`) and converts the `Bitmap` to a WPF `BitmapSource` via `Imaging.CreateBitmapSourceFromHBitmap`, then **must call `DeleteObject` on the HBITMAP** to avoid GDI handle leaks (`ScreenshotService.cs:64-87`). The result is `Freeze()`d so it can cross threads. +`Win32ScreenCapture` (`MoneyShot.Platform.Windows`) uses GDI+ (`Graphics.CopyFromScreen`) and reads the `Bitmap`'s pixels directly via `LockBits` into a `CapturedImage` — no HBITMAP handle involved, so there's nothing to leak (the old `GetHbitmap`→`CreateBitmapSourceFromHBitmap`→`DeleteObject` dance is gone). `MainWindow` converts the result to a WPF `BitmapSource` via `Interop/BitmapConversions.ToBitmapSource()`, which `Freeze()`s it so it can cross threads. Before capture, `MainWindow` calls `Hide()` and then `Thread.Sleep(200-300)`. This is intentional — without the delay the window can still be visible in the captured frame. Don't remove these sleeps without an alternative (e.g. waiting for a render-tick confirmation). @@ -51,7 +76,7 @@ For region capture with `HideUiFromScreenshots=true`, the flow captures one **fr ### Hotkeys (Win32, requires window handle) -`HotKeyService` registers global hotkeys via `RegisterHotKey` and listens for `WM_HOTKEY` through an `HwndSource.AddHook`. It must be `Initialize(window)`d **after** the window's HWND exists — that's why `RegisterHotKeys()` is called from `MainWindow_Loaded`, not the constructor. `ParseHotKey` only understands the modifiers/keys it has explicit cases for (`Ctrl`/`Alt`/`Shift`/`Win` and `PrintScreen`/`0-9`/`F1-F12`); add new keys there if you need them. Settings store hotkeys as strings like `"Ctrl+PrintScreen"`. +`Win32GlobalHotkeys` (`MoneyShot.Platform.Windows`, implements `IGlobalHotkeys`) registers global hotkeys via `RegisterHotKey` and listens for `WM_HOTKEY` on its own dedicated message-only window (`HWND_MESSAGE`) that it creates via a WinForms `NativeWindow` (not WPF's `HwndSource.AddHook` — this project has no WPF dependency, see the project-split note above). `IGlobalHotkeys.Initialize()` takes no window handle — hotkey registration is independent of whether/when the app's own main window exists, which matters for the Avalonia build (`MoneyShot.UI`, see `LINUX_PORT.md` Phase 1), which can start with no window ever created (`StartInTray`). `RegisterHotKeys()` is still called from `MainWindow.InitializeApplication()` rather than the constructor, but only because settings need to be loaded first, not because of any HWND ordering requirement now. Hotkey-string parsing (`HotKeyParser.ParseHotKey`, in `MoneyShot.Core`) only understands the modifiers/keys it has explicit cases for (`Ctrl`/`Alt`/`Shift`/`Win` and `PrintScreen`/`0-9`/`F1-F12`); add new keys there if you need them. Settings store hotkeys as strings like `"Ctrl+PrintScreen"`. When hotkeys are reconfigured in settings, call `MainWindow.ReloadHotKeys()` — it unregisters all and re-registers from the new settings. @@ -61,9 +86,9 @@ When hotkeys are reconfigured in settings, call `MainWindow.ReloadHotKeys()` — - Resolves `DefaultSavePath` via `Path.GetFullPath` and falls back to `MyPictures` if it's invalid/relative/too-long — **don't bypass this**, it prevents path traversal from a tampered settings file. - Clamps `DefaultLineThickness` to `[1, 20]` and validates `DefaultFileFormat` against an allowlist. -Two registry-backed settings live here too: -- `SetStartupWithWindows` — `HKCU\...\Run`. -- `SetWindowsPrintScreenDisabled` — `HKCU\Control Panel\Keyboard\PrintScreenKeyForSnippingEnabled`. This globally suppresses Windows' built-in Snipping Tool hotkey so MoneyShot can claim PrintScreen. +Two registry-backed settings used to live on `SettingsService` itself; they now live behind `IAutoStart` (`Win32AutoStart` in `MoneyShot.Platform.Windows`) so `SettingsService` has no Windows-specific dependency: +- `SetStartupWithApp` — `HKCU\...\Run`. +- `SetPrintScreenSuppressed` — `HKCU\Control Panel\Keyboard\PrintScreenKeyForSnippingEnabled`. This globally suppresses Windows' built-in Snipping Tool hotkey so MoneyShot can claim PrintScreen. ### Auto-update diff --git a/DEVELOPER.md b/DEVELOPER.md index 1c28af7..2d3166c 100644 --- a/DEVELOPER.md +++ b/DEVELOPER.md @@ -45,32 +45,53 @@ dotnet run --project MoneyShot/MoneyShot.csproj ## Project Structure +The solution is split across four projects, the biggest structural change made in the Linux-port +groundwork (LINUX_PORT.md Phase 0): + +- **MoneyShot.Core** (`net10.0`, no UI/Windows dependency) — Models, `SettingsService`, `Logger`, + `AutoUpdateService`, `HotKeyParser`, and the platform abstraction interfaces (`IScreenCapture`, + `IGlobalHotkeys`, `ITrayIcon`, `IAutoStart`, `IClipboard` — all in `MoneyShot.Abstractions`). +- **MoneyShot.Platform.Windows** (`net10.0-windows`, no WPF dependency) — the Win32/WinForms + implementations of those interfaces: `Win32ScreenCapture`, `Win32GlobalHotkeys`, `Win32TrayIcon`, + `Win32AutoStart`, `Win32Clipboard`. +- **MoneyShot** (`net10.0-windows`, WPF) — all the XAML windows, plus `SaveService` and + `HistoryService` (still WPF-`BitmapSource`-based; a Linux port would give these an Avalonia twin + in Phase 1). `Interop/BitmapConversions.cs` converts between the neutral `CapturedImage` type and + WPF's `BitmapSource` at the UI boundary. +- **MoneyShot.Tests** — xUnit tests, referencing all three of the above. + ### Core Services -#### ScreenshotService -Handles screen capture functionality: -- `CaptureFullScreen()` - Captures all screens -- `CaptureRegion(Rectangle)` - Captures specific region -- `CaptureScreen(int)` - Captures single screen by index +#### Win32ScreenCapture (implements IScreenCapture) +Handles screen capture functionality, in MoneyShot.Platform.Windows: +- `CaptureFullScreen()` - Captures all screens, returns a neutral `CapturedImage` (raw BGRA32 pixels) +- `CaptureMonitor(int)` - Captures single screen by index +- `GetAllMonitors()` - Returns bounds/primary-flag for every connected display +- Reads pixels via `Bitmap.LockBits` rather than the old `GetHbitmap`→`CreateBitmapSourceFromHBitmap`→`DeleteObject` + dance, so there's no HBITMAP handle to leak +- The WPF layer converts `CapturedImage` → `BitmapSource` via `Interop/BitmapConversions.ToBitmapSource()` #### SaveService -Manages saving screenshots: +Manages saving screenshots (WPF project — takes an `IClipboard` so clipboard access still goes +through the platform abstraction): - `SaveToClipboard(BitmapSource)` - Copies to clipboard - `SaveToFile(BitmapSource, string, string)` - Saves to file - `SaveImage(BitmapSource, SaveDestination, string, string)` - Combined save #### SettingsService -Handles application settings: +Handles application settings (MoneyShot.Core): - `LoadSettings()` - Loads user settings from JSON - `SaveSettings(AppSettings)` - Saves settings to JSON -- `SetStartupWithWindows(bool)` - Configures Windows startup - -#### HotKeyService -Manages global keyboard shortcuts: -- `Initialize(window)` - Initializes hotkey listener with window handle -- `RegisterHotKey(modifiers, key, action)` - Registers hotkey -- `UnregisterHotKey(id)` - Removes hotkey -- `ParseHotKey(string)` - Parses hotkey strings like "Ctrl+PrintScreen" + +Registry-backed startup/print-screen settings moved to `IAutoStart` (`Win32AutoStart` in +MoneyShot.Platform.Windows) as part of the Linux-port groundwork — see LINUX_PORT.md Phase 0. + +#### Win32GlobalHotkeys (implements IGlobalHotkeys) +Manages global keyboard shortcuts, in MoneyShot.Platform.Windows: +- `Initialize(IntPtr windowHandle)` - Hooks WM_HOTKEY on the given window handle via a WinForms + `NativeWindow` subclass (not `HwndSource.AddHook`, so this project has no WPF dependency) +- `RegisterHotKeyFromString(string, Action)` - Parses (via `HotKeyParser` in MoneyShot.Core) and registers a hotkey +- `UnregisterAll()` - Removes every registered hotkey - Uses Win32 API for global hotkey registration #### AutoUpdateService diff --git a/LINUX_PORT.md b/LINUX_PORT.md index ada755f..b431c9f 100644 --- a/LINUX_PORT.md +++ b/LINUX_PORT.md @@ -1,7 +1,14 @@ # Linux Port — Feasibility & Plan -> Status: planning document, not a commitment. Captures the technical reality of porting MoneyShot -> off WPF/Windows so the team can decide whether the cost is worth the user base. +> Status: **Phase 0 shipped** (2026-09). **Phase 1 built and partially verified** (2026-09) — a +> full Avalonia port of every window exists as a new, additive `MoneyShot.UI` project (the +> shipping WPF app/installer is untouched). It builds clean and `MainWindow` has been confirmed +> working by actually running it and inspecting a screenshot — theme, custom title bar, buttons, +> icons, and dynamic monitor detection all render correctly. **The other four windows have not +> been interactively tested** — see § Phase 1 status for exactly what is and isn't verified before +> anyone relies on this build. Phases 2–4 (X11/Wayland platform code, packaging) are not started +> and remain a planning-only commitment for the team to weigh — see § Migration phases and § +> Decision matrix for the team. ## TL;DR @@ -211,18 +218,100 @@ A `PlatformServices.Resolve()` static returns the right implementations based on ## Migration phases -**Phase 0 — extraction (no behavior change, Windows-only).** Pull `IScreenCapture`, -`IGlobalHotkeys`, etc. interfaces out of the existing concrete services. Keep WPF, keep all -existing tests green. ~1 week. - -**Phase 1 — UI port to Avalonia, still Windows-only.** Move `MainWindow`, `EditorWindow`, -`HistoryWindow`, `RegionSelector`, `SettingsWindow` to `*.axaml`. Use Avalonia's `Canvas`/`Shape` -hierarchy — it tracks WPF closely enough that the editor's drawing/hit-test/resize logic is -mostly find-and-replace. Re-prove all 95 existing tests pass. The output here is a -*Windows-only Avalonia build* that behaves like today's MoneyShot. **2–3 weeks.** This is the -biggest single chunk and the highest-risk one — if Avalonia turns out to have a blocker (e.g. its -`RenderTargetBitmap` doesn't behave like WPF's for the pixelate brush), this is where we find -out. +**Phase 0 — extraction (no behavior change, Windows-only). ✅ Done (2026-09).** Pulled +`IScreenCapture`, `IGlobalHotkeys`, `ITrayIcon`, `IAutoStart`, `IClipboard` out into a new +`MoneyShot.Core` project (no UI/Windows dependency) plus a `MoneyShot.Platform.Windows` project +holding the Win32/WinForms implementations (`Win32ScreenCapture`, `Win32GlobalHotkeys`, +`Win32TrayIcon`, `Win32AutoStart`, `Win32Clipboard`). WPF stayed exactly as-is behaviorally; all +109 tests stayed green throughout. Two implementation notes for whoever picks up Phase 1: + +- `IScreenCapture` returns a neutral `CapturedImage` (raw BGRA32 pixel buffer) rather than a WPF + `BitmapSource`, converted at the UI boundary via `MoneyShot/Interop/BitmapConversions.cs`. As a + side effect this also eliminated the old HBITMAP-handle-leak risk (`Win32ScreenCapture` reads + pixels via `Bitmap.LockBits` instead of `GetHbitmap`/`DeleteObject`). +- `Win32GlobalHotkeys` hooks `WM_HOTKEY` by subclassing the given HWND with a WinForms + `NativeWindow` (`AssignHandle`) rather than WPF's `HwndSource.AddHook` — this keeps + `MoneyShot.Platform.Windows` free of any WPF reference, so the same class should keep working + once Phase 1 replaces the UI layer with Avalonia. This is a different mechanism than what was + running before and hasn't been through real-world hotkey testing beyond a clean build — verify + hotkeys (PrintScreen, Ctrl+PrintScreen, Ctrl+Shift+1..9) actually fire on real Windows hardware + before trusting this in the field, the same way any other change in this codebase touching + `EditorWindow`/`HistoryWindow`/the tray menu needs manual verification (no automated UI + coverage — see `CLAUDE.md`). + +`HistoryService` and `SaveService` deliberately stayed WPF/`BitmapSource`-based rather than being +forced into Core — they're squarely a Phase 1 (UI-port) concern per the "What ports cleanly" table +above, and abstracting them now would have meant designing around a UI framework (Avalonia) that +isn't actually in the dependency tree yet. `SaveService` does now take an `IClipboard` so its +clipboard write goes through the platform abstraction; file saving is unchanged. + +**Phase 1 — UI port to Avalonia, still Windows-only. 🟡 Built, partially verified (2026-09).** +`MainWindow`, `EditorWindow`, `HistoryWindow`, `RegionSelector`, `SettingsWindow` were all ported +to `*.axaml` in a new, additive `MoneyShot.UI` project (net10.0-windows for now — see below) that +sits alongside the shipping WPF app without touching it. `CocoaTheme.axaml` re-implements the WPF +theme using Avalonia's `ControlTheme` system. All 109 existing tests still pass (the WPF/Core +test suite; `MoneyShot.UI` itself has no tests, same as WPF's views). No blocker was hit in +Avalonia's `Geometry.FillContains`/`StrokeContains` (used for arrow hit-testing) or +`RenderTargetBitmap` (used for the pixelate brush and final image capture) — both have close WPF +equivalents and the project compiles clean using them. + +*What's actually verified, and how:* the whole solution builds with zero errors/warnings, the +Avalonia build launches and stays responsive (checked via process inspection), and `MainWindow` +was confirmed **visually correct by actually running it and inspecting a screenshot** — the +cocoa-brown theme, custom borderless title bar with working minimize/maximize/close, the accent +capture buttons, icon rendering, and the dynamically-generated per-monitor button list (correctly +detected 3 monitors and labeled the primary) all render as designed. + +*What is NOT verified* — this was built and made to compile, but nobody has clicked through it: +- `EditorWindow` is the highest-risk file in the entire port (2000+ lines, the most stateful + mouse-interaction code in the app — see CLAUDE.md's "Resize/drag" notes on past WPF regressions + in this exact logic). None of drawing, selecting, dragging, resizing (box or endpoint), undo, + crop, zoom/pan, pixelate, or the async save/color/text dialogs have been interactively tested. +- `SettingsWindow`, `HistoryWindow`, `RegionSelector` compile but haven't been opened. +- Global hotkeys, the tray icon and its context menu, and the actual capture-to-editor flow have + not been triggered end-to-end. +- A thin sliver of residual native chrome was visible above the custom title bar in the one + screenshot taken — likely related to Avalonia 12's `ExtendClientAreaChromeHints` removal (see + implementation note below); cosmetic, not investigated further. + +None of this was possible to close out further in the session that built it — no computer-use/UI +automation tooling was available to click through the app, only process inspection and one +manually-captured screenshot. **Manual interactive testing of the above is required before trusting +this build for anything beyond "it starts and MainWindow looks right."** + +Implementation notes for whoever continues from here: +- `MoneyShot.UI` targets `net10.0-windows`, not the bare `net10.0` the architecture diagram above + implies for the long-term target — a plain `net10.0` project cannot reference a + `net10.0-windows` one (`MoneyShot.Platform.Windows`) at all, TFM compatibility requires the + consumer to be equal-or-more-specific. It becomes genuinely cross-platform (multi-targeting, or + a runtime `OperatingSystem.IsWindows()` check instead of a compile-time project reference) once + Phase 2 adds `MoneyShot.Platform.Linux`. +- **Avalonia 12 removed `Window.ExtendClientAreaChromeHints`** (present through 11.x, used for + WPF-style `WindowChrome`-equivalent borderless-with-shadow windows) in favor of + `WindowDecorations="None"` + `ExtendClientAreaToDecorationsHint="True"`. This build uses the + new API since it targets Avalonia 12.1.2, but Avalonia's own tracking issue (#21212) notes the + old approach's DWM min/max/close animations and window shadow are not fully replicated by the + new one on Windows — expect this build's windows to look slightly flatter (no drop shadow) than + the WPF build's, and verify resize-by-dragging-the-edge actually still works (not verified here). +- `IGlobalHotkeys.Initialize()` (in `MoneyShot.Core`/`Win32GlobalHotkeys`) was changed during this + work to take no window-handle argument — it now creates its own message-only Win32 window + (`HWND_MESSAGE`) rather than subclassing the app's main window. This was necessary because the + Avalonia build can start with no window ever created (`StartInTray`) and there's no confirmed + Avalonia equivalent of WPF's `WindowInteropHelper.EnsureHandle()` for realizing a handle without + showing anything. The WPF build was updated to match (`MainWindow.InitializeApplication()` no + longer needs `EnsureHandle()` either) — this is a genuine simplification, not just a Phase-1 + accommodation. +- WPF's `Microsoft.Win32.SaveFileDialog` (sync) became Avalonia's `IStorageProvider.SaveFilePickerAsync` + (async) — `EditorWindow.Save_Click` and everywhere else a blocking `MessageBox.Show` existed + became `async`/`await SimpleMessageBox.ShowAsync` (a hand-rolled modal window — Avalonia has no + built-in `MessageBox`). +- Avalonia's own `Bitmap.Save` is PNG-only regardless of requested format (a known framework + limitation, see AvaloniaUI/Avalonia#12493) — `MoneyShot.UI.Services.SaveService` uses SkiaSharp + directly (already an Avalonia dependency, referenced explicitly) to encode real JPEG/BMP. +- `RegionSelector`'s DPI handling was ported from the *already-fixed* WPF version (see § E2 in + Opus-Speaks.md), not the original buggy one — and is arguably cleaner here, since Avalonia's + `Screens` API exposes each monitor's scale factor directly (`Screen.Scaling`), avoiding the + Win32 `GetDpiForMonitor` P/Invoke the WPF fix needed. **Phase 2 — Linux platform implementations.** X11 capture, X11 hotkeys, Linux autostart, Linux clipboard, Linux tray. Test on at least: Ubuntu 24.04 + KDE Plasma 6, Fedora + GNOME, Arch + i3. diff --git a/MoneyShot.Core/Abstractions/IAutoStart.cs b/MoneyShot.Core/Abstractions/IAutoStart.cs new file mode 100644 index 0000000..8d16e33 --- /dev/null +++ b/MoneyShot.Core/Abstractions/IAutoStart.cs @@ -0,0 +1,20 @@ +namespace MoneyShot.Abstractions; + +/// +/// The two registry-backed OS integrations SettingsService used to own directly: launch-at-login +/// and (Windows-only) suppressing the OS's own screenshot tool on PrintScreen. See LINUX_PORT.md +/// § Registry settings — on Linux, autostart becomes a ~/.config/autostart/*.desktop file and +/// PrintScreen suppression has no analogue (implementations should no-op / return false). +/// +public interface IAutoStart +{ + /// Throws InvalidOperationException with a user-facing message on failure. + void SetStartupWithApp(bool enabled); + + bool IsSetToRunOnStartup(); + + /// Returns whether the change was applied. Platforms without this concept return false. + bool SetPrintScreenSuppressed(bool suppressed); + + bool TryGetPrintScreenSuppressed(out bool suppressed); +} diff --git a/MoneyShot.Core/Abstractions/IClipboard.cs b/MoneyShot.Core/Abstractions/IClipboard.cs new file mode 100644 index 0000000..5fcfcfd --- /dev/null +++ b/MoneyShot.Core/Abstractions/IClipboard.cs @@ -0,0 +1,11 @@ +namespace MoneyShot.Abstractions; + +/// +/// Image clipboard access, abstracted from the OS mechanism (Win32/WinForms clipboard on Windows, +/// MIME-typed X11/Wayland selection via Avalonia's IClipboard on Linux — see LINUX_PORT.md +/// § Clipboard image support). +/// +public interface IClipboard +{ + void SetImage(CapturedImage image); +} diff --git a/MoneyShot.Core/Abstractions/IGlobalHotkeys.cs b/MoneyShot.Core/Abstractions/IGlobalHotkeys.cs new file mode 100644 index 0000000..4a41de0 --- /dev/null +++ b/MoneyShot.Core/Abstractions/IGlobalHotkeys.cs @@ -0,0 +1,24 @@ +namespace MoneyShot.Abstractions; + +/// +/// Global (system-wide) hotkey registration, abstracted from the OS mechanism (Win32 RegisterHotKey +/// on Windows, XGrabKey on X11 — no direct Wayland equivalent, see LINUX_PORT.md § Global hotkeys). +/// +public interface IGlobalHotkeys +{ + /// + /// Prepares hotkey registration. Must be called once before registering hotkeys. Implementations + /// own whatever OS-level plumbing this needs (e.g. a dedicated message-only window on Windows) — + /// callers don't need to have a visible window, or any window at all, for this to work. + /// + void Initialize(); + + /// + /// Parses a hotkey string like "Ctrl+PrintScreen" or "Ctrl+Shift+1" and registers it, invoking + /// when pressed. Returns false (and logs) if the string is invalid or + /// the combination is already claimed by another application. + /// + bool RegisterHotKeyFromString(string hotkeyString, Action action); + + void UnregisterAll(); +} diff --git a/MoneyShot.Core/Abstractions/IScreenCapture.cs b/MoneyShot.Core/Abstractions/IScreenCapture.cs new file mode 100644 index 0000000..d2caab7 --- /dev/null +++ b/MoneyShot.Core/Abstractions/IScreenCapture.cs @@ -0,0 +1,22 @@ +namespace MoneyShot.Abstractions; + +/// +/// Raw captured pixels in top-down BGRA32 (premultiplied alpha) row order, stride in bytes. +/// Platform-neutral so MoneyShot.Core has no UI-framework dependency — UI layers convert to their +/// native bitmap type (WPF BitmapSource today, Avalonia Bitmap once ported) at the boundary. +/// +public sealed record CapturedImage(int Width, int Height, int Stride, byte[] PixelDataBgra32); + +/// Bounds and identity of one physical display, in physical pixels. +public sealed record MonitorInfo(int Left, int Top, int Width, int Height, bool IsPrimary, string DeviceName); + +/// +/// Screen capture, abstracted from the OS mechanism (GDI+ on Windows, X11/portal on Linux — see +/// LINUX_PORT.md). Implementations live under MoneyShot.Platform.*. +/// +public interface IScreenCapture +{ + CapturedImage CaptureFullScreen(); + CapturedImage CaptureMonitor(int monitorIndex); + IReadOnlyList GetAllMonitors(); +} diff --git a/MoneyShot.Core/Abstractions/ITrayIcon.cs b/MoneyShot.Core/Abstractions/ITrayIcon.cs new file mode 100644 index 0000000..cbcdf12 --- /dev/null +++ b/MoneyShot.Core/Abstractions/ITrayIcon.cs @@ -0,0 +1,24 @@ +namespace MoneyShot.Abstractions; + +/// One entry in the tray icon's context menu. IsSeparator entries ignore every other field. +public sealed record TrayMenuItem(string Label, Action? OnClick, bool IsSeparator = false) +{ + public static TrayMenuItem Separator() => new(string.Empty, null, IsSeparator: true); +} + +/// +/// System tray presence, abstracted from the OS mechanism (System.Windows.Forms.NotifyIcon on +/// Windows, StatusNotifierItem/D-Bus via Avalonia's TrayIcon on Linux — see LINUX_PORT.md § System +/// tray). A single instance represents one tray icon for the app's lifetime. +/// +public interface ITrayIcon : IDisposable +{ + /// Creates and shows the icon with the given tooltip and context menu. Call once. + void Show(string tooltip, IReadOnlyList menuItems); + + /// Transient notification popup from the tray icon (e.g. "minimized to tray"). + void ShowBalloonTip(int timeoutMilliseconds, string title, string text); + + /// Raised when the user double-clicks the tray icon (conventionally: show main window). + event Action? DoubleClicked; +} diff --git a/MoneyShot/Models/AnnotationTool.cs b/MoneyShot.Core/Models/AnnotationTool.cs similarity index 100% rename from MoneyShot/Models/AnnotationTool.cs rename to MoneyShot.Core/Models/AnnotationTool.cs diff --git a/MoneyShot/Models/AppSettings.cs b/MoneyShot.Core/Models/AppSettings.cs similarity index 55% rename from MoneyShot/Models/AppSettings.cs rename to MoneyShot.Core/Models/AppSettings.cs index bf5ce1b..b16bbce 100644 --- a/MoneyShot/Models/AppSettings.cs +++ b/MoneyShot.Core/Models/AppSettings.cs @@ -1,6 +1,3 @@ -using System.Windows; -using System.Windows.Media; - namespace MoneyShot.Models; public class AppSettings @@ -14,7 +11,18 @@ public class AppSettings public bool DisableWindowsPrintScreen { get; set; } = false; public bool HideUiFromScreenshots { get; set; } = true; public bool CheckForUpdatesOnStartup { get; set; } = true; - public Color DefaultAnnotationColor { get; set; } = Colors.Red; + + /// + /// Packed 0xAARRGGBB. Platform-neutral replacement for the old WPF-typed + /// System.Windows.Media.Color DefaultAnnotationColor field, so this project has no UI + /// framework dependency (part of the Linux-port groundwork — see LINUX_PORT.md Phase 0). Named + /// differently from the old field so a settings.json written by a pre-port build (which + /// serialized a WPF Color's full field set) is simply ignored as an unknown property rather + /// than causing a whole-file JSON deserialization failure. UI layers convert to/from their own + /// native color type at the boundary — see MoneyShot's ArgbColorConversions. + /// + public uint DefaultAnnotationColorArgb { get; set; } = 0xFFFF0000; // opaque red + public int DefaultLineThickness { get; set; } = 3; public string HotKeyCapture { get; set; } = "PrintScreen"; public string HotKeyRegionCapture { get; set; } = "Ctrl+PrintScreen"; diff --git a/MoneyShot/Models/CaptureMode.cs b/MoneyShot.Core/Models/CaptureMode.cs similarity index 100% rename from MoneyShot/Models/CaptureMode.cs rename to MoneyShot.Core/Models/CaptureMode.cs diff --git a/MoneyShot/Models/HistoryEntry.cs b/MoneyShot.Core/Models/HistoryEntry.cs similarity index 100% rename from MoneyShot/Models/HistoryEntry.cs rename to MoneyShot.Core/Models/HistoryEntry.cs diff --git a/MoneyShot/Models/SaveDestination.cs b/MoneyShot.Core/Models/SaveDestination.cs similarity index 100% rename from MoneyShot/Models/SaveDestination.cs rename to MoneyShot.Core/Models/SaveDestination.cs diff --git a/MoneyShot.Core/MoneyShot.Core.csproj b/MoneyShot.Core/MoneyShot.Core.csproj new file mode 100644 index 0000000..3f3b38c --- /dev/null +++ b/MoneyShot.Core/MoneyShot.Core.csproj @@ -0,0 +1,13 @@ + + + + net10.0 + enable + enable + + + + + + + diff --git a/MoneyShot/Services/AutoUpdateService.cs b/MoneyShot.Core/Services/AutoUpdateService.cs similarity index 99% rename from MoneyShot/Services/AutoUpdateService.cs rename to MoneyShot.Core/Services/AutoUpdateService.cs index cc7f42b..1c06c10 100644 --- a/MoneyShot/Services/AutoUpdateService.cs +++ b/MoneyShot.Core/Services/AutoUpdateService.cs @@ -404,20 +404,20 @@ private static string BuildWindowsSwapScript(string targetExecutablePath, string return $""" @echo off setlocal - + set "TARGET={escapedTargetPath}" set "STAGED={escapedStagedPath}" - + :WAIT_LOOP tasklist /FI "IMAGENAME eq {escapedTargetExecutableName}" 2>NUL | find /I "{escapedTargetExecutableName}" >NUL if not errorlevel 1 ( timeout /T 1 /NOBREAK >NUL goto WAIT_LOOP ) - + move /Y "%STAGED%" "%TARGET%" if errorlevel 1 exit /B 1 - + start "" "%TARGET%" (goto) 2>nul & del "%~f0" """; @@ -432,11 +432,11 @@ private static string BuildUnixSwapScript(string targetExecutablePath, string st #!/bin/sh TARGET={escapedTargetPath} STAGED={escapedStagedPath} - + while pgrep -f "$TARGET" >/dev/null 2>&1; do sleep 1 done - + mv -f "$STAGED" "$TARGET" chmod +x "$TARGET" "$TARGET" >/dev/null 2>&1 & @@ -470,4 +470,4 @@ internal sealed class ReleaseAsset } } -public sealed record UpdateInfo(Version LocalVersion, Version RemoteVersion, string AssetName, string DownloadUrl, string? ExpectedSha256 = null); \ No newline at end of file +public sealed record UpdateInfo(Version LocalVersion, Version RemoteVersion, string AssetName, string DownloadUrl, string? ExpectedSha256 = null); diff --git a/MoneyShot/Services/HotKeyService.cs b/MoneyShot.Core/Services/HotKeyParser.cs similarity index 55% rename from MoneyShot/Services/HotKeyService.cs rename to MoneyShot.Core/Services/HotKeyParser.cs index da0b381..4ce8753 100644 --- a/MoneyShot/Services/HotKeyService.cs +++ b/MoneyShot.Core/Services/HotKeyParser.cs @@ -1,84 +1,14 @@ -using System.Runtime.InteropServices; -using System.Windows; -using System.Windows.Interop; - namespace MoneyShot.Services; -public class HotKeyService +/// +/// Parses hotkey strings like "Ctrl+PrintScreen" or "Ctrl+Shift+1" into Win32 modifier/virtual-key +/// codes. Pure and platform-neutral — kept in Core so every IGlobalHotkeys implementation (Windows +/// today, X11 later, per LINUX_PORT.md) shares one parsing contract for the strings SettingsService +/// persists. The modifier/key constants below are Win32 RegisterHotKey values; a non-Windows +/// implementation maps them to its own native equivalents (e.g. X11 keysyms) internally. +/// +public static class HotKeyParser { - private const int WM_HOTKEY = 0x0312; - private readonly Dictionary _hotKeyActions = new(); - private int _currentId = 0; - private IntPtr _windowHandle; - - [DllImport("user32.dll")] - private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); - - [DllImport("user32.dll")] - private static extern bool UnregisterHotKey(IntPtr hWnd, int id); - - public void Initialize(Window window) - { - var helper = new WindowInteropHelper(window); - _windowHandle = helper.Handle; - var source = HwndSource.FromHwnd(_windowHandle); - source?.AddHook(HwndHook); - } - - public int RegisterHotKey(uint modifiers, uint key, Action action) - { - _currentId++; - if (RegisterHotKey(_windowHandle, _currentId, modifiers, key)) - { - _hotKeyActions[_currentId] = action; - return _currentId; - } - - // Most often the combination is already claimed by another application (or by a - // still-running instance). Without this log the hotkey just silently does nothing. - Logger.Warn($"RegisterHotKey failed for modifiers=0x{modifiers:X} key=0x{key:X} — combination may be in use by another application."); - return -1; - } - - public void UnregisterHotKey(int id) - { - UnregisterHotKey(_windowHandle, id); - _hotKeyActions.Remove(id); - } - - public void UnregisterAll() - { - foreach (var id in _hotKeyActions.Keys.ToList()) - { - UnregisterHotKey(_windowHandle, id); - } - _hotKeyActions.Clear(); - _currentId = 0; // Reset ID counter - } - - private IntPtr HwndHook(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) - { - if (msg == WM_HOTKEY) - { - var id = wParam.ToInt32(); - if (_hotKeyActions.TryGetValue(id, out var action)) - { - try - { - action?.Invoke(); - } - catch (Exception ex) - { - // An exception escaping a window-procedure hook can take down the process; - // a failed capture should be logged, not fatal. - Logger.Error("Hotkey action threw", ex); - } - handled = true; - } - } - return IntPtr.Zero; - } - // Virtual key codes public const uint VK_SNAPSHOT = 0x2C; // Print Screen public const uint VK_0 = 0x30; @@ -218,33 +148,4 @@ public static (uint modifiers, uint key) ParseHotKey(string hotkeyString) return (modifiers, key); } - - /// - /// Register a hotkey from a string like "Ctrl+PrintScreen" - /// - public int RegisterHotKeyFromString(string hotkeyString, Action action) - { - try - { - if (string.IsNullOrWhiteSpace(hotkeyString)) - { - Logger.Warn("Hotkey string is null or empty"); - return -1; - } - - var (modifiers, key) = ParseHotKey(hotkeyString); - if (key == 0) - { - Logger.Warn($"Invalid hotkey: {hotkeyString}"); - return -1; - } - - return RegisterHotKey(modifiers, key, action); - } - catch (Exception ex) - { - Logger.Error($"Error registering hotkey '{hotkeyString}'", ex); - return -1; - } - } } diff --git a/MoneyShot/Services/Logger.cs b/MoneyShot.Core/Services/Logger.cs similarity index 99% rename from MoneyShot/Services/Logger.cs rename to MoneyShot.Core/Services/Logger.cs index 78a88ff..eca7ea1 100644 --- a/MoneyShot/Services/Logger.cs +++ b/MoneyShot.Core/Services/Logger.cs @@ -13,7 +13,7 @@ namespace MoneyShot.Services; /// + DI throughout. The actual gap was "Debug.WriteLine produces no Release output", and a /// 100-line static facade closes that gap without rewriting every service's constructor. /// -internal static class Logger +public static class Logger { private const int RetentionDays = 7; private const string FileNameFormat = "moneyshot-{0:yyyyMMdd}.log"; diff --git a/MoneyShot/Services/SettingsService.cs b/MoneyShot.Core/Services/SettingsService.cs similarity index 55% rename from MoneyShot/Services/SettingsService.cs rename to MoneyShot.Core/Services/SettingsService.cs index f984ba9..dc2f8d2 100644 --- a/MoneyShot/Services/SettingsService.cs +++ b/MoneyShot.Core/Services/SettingsService.cs @@ -1,4 +1,3 @@ -using Microsoft.Win32; using System.IO; using System.Text.Json; using MoneyShot.Models; @@ -31,7 +30,7 @@ public AppSettings LoadSettings() try { var json = File.ReadAllText(_settingsPath); - + // Use secure deserialization options var options = new JsonSerializerOptions { @@ -39,7 +38,7 @@ public AppSettings LoadSettings() AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip }; - + var settings = JsonSerializer.Deserialize(json, options); // Validate and sanitize loaded settings @@ -47,7 +46,7 @@ public AppSettings LoadSettings() { return ValidateAndSanitizeSettings(settings); } - + return new AppSettings(); } catch (JsonException ex) @@ -71,16 +70,16 @@ public void SaveSettings(AppSettings settings) { // Validate and sanitize before saving settings = ValidateAndSanitizeSettings(settings); - - var options = new JsonSerializerOptions - { + + var options = new JsonSerializerOptions + { WriteIndented = true, // Don't serialize null values to reduce file size DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.Never }; - + var json = JsonSerializer.Serialize(settings, options); - + // Write to temp file first, then rename (atomic operation) var tempPath = _settingsPath + ".tmp"; File.WriteAllText(tempPath, json); @@ -93,7 +92,7 @@ public void SaveSettings(AppSettings settings) throw new InvalidOperationException("Failed to save settings. Please check file permissions.", ex); } } - + private static readonly char[] WindowsForbiddenPathChars = { '<', '>', '|', '?', '*', '"' }; /// @@ -139,14 +138,14 @@ internal static AppSettings ValidateAndSanitizeSettings(AppSettings settings) { settings.DefaultSavePath = fallbackSavePath; } - + // Validate file format var validFormats = new[] { "PNG", "JPG", "JPEG", "BMP", "GIF" }; if (!validFormats.Contains(settings.DefaultFileFormat.ToUpper())) { settings.DefaultFileFormat = "PNG"; } - + // Ensure line thickness is reasonable if (settings.DefaultLineThickness < 1 || settings.DefaultLineThickness > 20) { @@ -168,131 +167,4 @@ private static bool ContainsControlChar(string value) } return false; } - - public void SetStartupWithWindows(bool enabled) - { - const string appName = "MoneyShot"; - - try - { - using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); - - if (key == null) - { - throw new InvalidOperationException("Unable to access registry key for startup configuration."); - } - - if (enabled) - { - var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName; - if (exePath != null) - { - // Validate the path before writing to registry - var fullPath = Path.GetFullPath(exePath); - key.SetValue(appName, $"\"{fullPath}\"", RegistryValueKind.String); - } - else - { - throw new InvalidOperationException("Unable to determine application path."); - } - } - else - { - key.DeleteValue(appName, false); - } - } - catch (UnauthorizedAccessException ex) - { - Logger.Error("Registry access denied", ex); - throw new InvalidOperationException("Insufficient permissions to modify startup settings. Please run as administrator.", ex); - } - catch (Exception ex) - { - Logger.Error("Error setting startup configuration", ex); - throw new InvalidOperationException("Failed to modify startup settings.", ex); - } - } - - public bool IsSetToRunOnStartup() - { - const string appName = "MoneyShot"; - - try - { - using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false); - return key?.GetValue(appName) != null; - } - catch (Exception ex) - { - // Log but don't throw - this is a read-only operation - Logger.Error("Error checking startup status", ex); - return false; - } - } - - public bool SetWindowsPrintScreenDisabled(bool disabled) - { - try - { - // Open existing key first; fall back to creating it only when missing so this setting can still be applied. - using var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Keyboard", true) - ?? Registry.CurrentUser.CreateSubKey(@"Control Panel\Keyboard", true); - if (key == null) - { - Logger.Warn("Unable to access keyboard settings in registry."); - return false; - } - - // Set PrintScreenKeyForSnippingEnabled to 0 to disable, 1 to enable - // This controls Windows' "Use Print Screen to open screen capture" setting - key.SetValue("PrintScreenKeyForSnippingEnabled", disabled ? 0 : 1, RegistryValueKind.DWord); - key.Flush(); - - return TryGetWindowsPrintScreenDisabled(out var isDisabled) && isDisabled == disabled; - } - catch (UnauthorizedAccessException ex) - { - Logger.Error("Registry access denied", ex); - return false; - } - catch (Exception ex) - { - Logger.Error("Error setting Print Screen configuration", ex); - return false; - } - } - - public bool TryGetWindowsPrintScreenDisabled(out bool disabled) - { - disabled = false; - - try - { - using var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Keyboard", false); - if (key == null) - { - return false; - } - - var value = key.GetValue("PrintScreenKeyForSnippingEnabled"); - if (value is int intValue) - { - disabled = intValue == 0; - return true; - } - - if (value is string stringValue && int.TryParse(stringValue, out var parsedValue)) - { - disabled = parsedValue == 0; - return true; - } - - return false; - } - catch (Exception ex) - { - Logger.Error("Error reading Print Screen configuration", ex); - return false; - } - } } diff --git a/MoneyShot/Services/MemoryTrimmer.cs b/MoneyShot.Platform.Windows/MemoryTrimmer.cs similarity index 74% rename from MoneyShot/Services/MemoryTrimmer.cs rename to MoneyShot.Platform.Windows/MemoryTrimmer.cs index 85eda59..f718120 100644 --- a/MoneyShot/Services/MemoryTrimmer.cs +++ b/MoneyShot.Platform.Windows/MemoryTrimmer.cs @@ -1,15 +1,17 @@ using System.Runtime; using System.Runtime.InteropServices; -namespace MoneyShot.Services; +namespace MoneyShot.Platform.Windows; /// /// Releases the large native/managed bitmap backings the editor leaves behind and asks Windows /// to trim the working set. Without this a tray app that should idle near ~80 MB sits at several /// hundred MB after the editor closes, until the next major GC happens on its own schedule. -/// Shared by every code path that closes an EditorWindow (capture flow and history). +/// Shared by every UI build that closes an editor window (WPF's EditorWindow and the Avalonia +/// build's — see LINUX_PORT.md Phase 1) — moved here from the WPF project since both need it and +/// it's genuinely Windows-specific OS interaction. /// -internal static class MemoryTrimmer +public static class MemoryTrimmer { public static void TrimAfterEditorClose() { @@ -26,7 +28,7 @@ public static void TrimAfterEditorClose() } catch (Exception ex) { - Logger.Warn("Could not release editor memory", ex); + MoneyShot.Services.Logger.Warn("Could not release editor memory", ex); } } diff --git a/MoneyShot.Platform.Windows/MoneyShot.Platform.Windows.csproj b/MoneyShot.Platform.Windows/MoneyShot.Platform.Windows.csproj new file mode 100644 index 0000000..65b3bea --- /dev/null +++ b/MoneyShot.Platform.Windows/MoneyShot.Platform.Windows.csproj @@ -0,0 +1,23 @@ + + + + net10.0-windows + enable + enable + true + + + + + + + + + + + + diff --git a/MoneyShot.Platform.Windows/Win32AutoStart.cs b/MoneyShot.Platform.Windows/Win32AutoStart.cs new file mode 100644 index 0000000..03136ae --- /dev/null +++ b/MoneyShot.Platform.Windows/Win32AutoStart.cs @@ -0,0 +1,140 @@ +using System.IO; +using Microsoft.Win32; +using MoneyShot.Abstractions; +using MoneyShot.Services; + +namespace MoneyShot.Platform.Windows; + +/// +/// The two registry-backed OS integrations formerly on SettingsService (see LINUX_PORT.md § +/// Registry settings). On Linux, SetStartupWithApp becomes a ~/.config/autostart/*.desktop file +/// and print-screen suppression has no analogue — an implementation there should simply return +/// false / no-op. +/// +public sealed class Win32AutoStart : IAutoStart +{ + private const string AppName = "MoneyShot"; + + public void SetStartupWithApp(bool enabled) + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true); + + if (key == null) + { + throw new InvalidOperationException("Unable to access registry key for startup configuration."); + } + + if (enabled) + { + var exePath = System.Diagnostics.Process.GetCurrentProcess().MainModule?.FileName; + if (exePath != null) + { + // Validate the path before writing to registry + var fullPath = Path.GetFullPath(exePath); + key.SetValue(AppName, $"\"{fullPath}\"", RegistryValueKind.String); + } + else + { + throw new InvalidOperationException("Unable to determine application path."); + } + } + else + { + key.DeleteValue(AppName, false); + } + } + catch (UnauthorizedAccessException ex) + { + Logger.Error("Registry access denied", ex); + throw new InvalidOperationException("Insufficient permissions to modify startup settings. Please run as administrator.", ex); + } + catch (Exception ex) + { + Logger.Error("Error setting startup configuration", ex); + throw new InvalidOperationException("Failed to modify startup settings.", ex); + } + } + + public bool IsSetToRunOnStartup() + { + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", false); + return key?.GetValue(AppName) != null; + } + catch (Exception ex) + { + // Log but don't throw - this is a read-only operation + Logger.Error("Error checking startup status", ex); + return false; + } + } + + public bool SetPrintScreenSuppressed(bool suppressed) + { + try + { + // Open existing key first; fall back to creating it only when missing so this setting can still be applied. + using var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Keyboard", true) + ?? Registry.CurrentUser.CreateSubKey(@"Control Panel\Keyboard", true); + if (key == null) + { + Logger.Warn("Unable to access keyboard settings in registry."); + return false; + } + + // Set PrintScreenKeyForSnippingEnabled to 0 to disable, 1 to enable + // This controls Windows' "Use Print Screen to open screen capture" setting + key.SetValue("PrintScreenKeyForSnippingEnabled", suppressed ? 0 : 1, RegistryValueKind.DWord); + key.Flush(); + + return TryGetPrintScreenSuppressed(out var isDisabled) && isDisabled == suppressed; + } + catch (UnauthorizedAccessException ex) + { + Logger.Error("Registry access denied", ex); + return false; + } + catch (Exception ex) + { + Logger.Error("Error setting Print Screen configuration", ex); + return false; + } + } + + public bool TryGetPrintScreenSuppressed(out bool suppressed) + { + suppressed = false; + + try + { + using var key = Registry.CurrentUser.OpenSubKey(@"Control Panel\Keyboard", false); + if (key == null) + { + return false; + } + + var value = key.GetValue("PrintScreenKeyForSnippingEnabled"); + if (value is int intValue) + { + suppressed = intValue == 0; + return true; + } + + if (value is string stringValue && int.TryParse(stringValue, out var parsedValue)) + { + suppressed = parsedValue == 0; + return true; + } + + return false; + } + catch (Exception ex) + { + Logger.Error("Error reading Print Screen configuration", ex); + return false; + } + } +} diff --git a/MoneyShot.Platform.Windows/Win32Clipboard.cs b/MoneyShot.Platform.Windows/Win32Clipboard.cs new file mode 100644 index 0000000..0a828a3 --- /dev/null +++ b/MoneyShot.Platform.Windows/Win32Clipboard.cs @@ -0,0 +1,43 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using System.Windows.Forms; +using MoneyShot.Abstractions; + +namespace MoneyShot.Platform.Windows; + +/// +/// WinForms-clipboard-based image clipboard (see LINUX_PORT.md § Clipboard image support for the +/// MIME-typed X11/Wayland selection equivalent via Avalonia's IClipboard). Uses +/// System.Windows.Forms.Clipboard rather than System.Windows.Clipboard so this project has no WPF +/// dependency — both work identically for image data, since it's the same OS clipboard underneath. +/// +public sealed class Win32Clipboard : IClipboard +{ + public void SetImage(CapturedImage image) + { + using var bitmap = ToBitmap(image); + Clipboard.SetImage(bitmap); + } + + private static Bitmap ToBitmap(CapturedImage image) + { + var bitmap = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppPArgb); + var rect = new Rectangle(0, 0, image.Width, image.Height); + var data = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppPArgb); + try + { + // Row-by-row copy in case CapturedImage.Stride differs from the Bitmap's own stride. + var rowBytes = Math.Min(image.Stride, data.Stride); + for (var y = 0; y < image.Height; y++) + { + Marshal.Copy(image.PixelDataBgra32, y * image.Stride, data.Scan0 + y * data.Stride, rowBytes); + } + } + finally + { + bitmap.UnlockBits(data); + } + return bitmap; + } +} diff --git a/MoneyShot.Platform.Windows/Win32GlobalHotkeys.cs b/MoneyShot.Platform.Windows/Win32GlobalHotkeys.cs new file mode 100644 index 0000000..65952f9 --- /dev/null +++ b/MoneyShot.Platform.Windows/Win32GlobalHotkeys.cs @@ -0,0 +1,136 @@ +using System.Runtime.InteropServices; +using MoneyShot.Abstractions; +using MoneyShot.Services; + +namespace MoneyShot.Platform.Windows; + +/// +/// Win32 RegisterHotKey-based global hotkeys (see LINUX_PORT.md § Global hotkeys for the X11 +/// XGrabKey equivalent, and the note that Wayland has no direct equivalent at all). +/// +/// Hooks WM_HOTKEY on a dedicated, invisible, message-only window (HWND_MESSAGE) that this class +/// creates and owns via a WinForms NativeWindow, rather than subclassing the app's actual main +/// window the way the original HwndSource.AddHook-based implementation did. This means: (a) this +/// project still needs no WPF reference (a NativeWindow works regardless of UI framework), and +/// (b) hotkey registration no longer depends on the main window having a native handle at all — +/// which matters for a UI that starts hidden in the tray with no window ever shown (see +/// MoneyShot.UI's MainWindow, the Avalonia build from LINUX_PORT.md Phase 1). +/// +public sealed class Win32GlobalHotkeys : IGlobalHotkeys, IDisposable +{ + private const int WM_HOTKEY = 0x0312; + private const int HWND_MESSAGE_PARENT = -3; + private readonly Dictionary _hotKeyActions = new(); + private int _currentId; + private HotKeyMessageWindow? _messageWindow; + + private IntPtr WindowHandle => _messageWindow?.Handle ?? IntPtr.Zero; + + [DllImport("user32.dll")] + private static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk); + + [DllImport("user32.dll")] + private static extern bool UnregisterHotKey(IntPtr hWnd, int id); + + public void Initialize() + { + _messageWindow = new HotKeyMessageWindow(this); + _messageWindow.CreateHandle(new System.Windows.Forms.CreateParams + { + Parent = new IntPtr(HWND_MESSAGE_PARENT) + }); + } + + public bool RegisterHotKeyFromString(string hotkeyString, Action action) + { + try + { + if (string.IsNullOrWhiteSpace(hotkeyString)) + { + Logger.Warn("Hotkey string is null or empty"); + return false; + } + + var (modifiers, key) = HotKeyParser.ParseHotKey(hotkeyString); + if (key == 0) + { + Logger.Warn($"Invalid hotkey: {hotkeyString}"); + return false; + } + + return RegisterHotKeyCore(modifiers, key, action); + } + catch (Exception ex) + { + Logger.Error($"Error registering hotkey '{hotkeyString}'", ex); + return false; + } + } + + private bool RegisterHotKeyCore(uint modifiers, uint key, Action action) + { + _currentId++; + if (RegisterHotKey(WindowHandle, _currentId, modifiers, key)) + { + _hotKeyActions[_currentId] = action; + return true; + } + + // Most often the combination is already claimed by another application (or by a + // still-running instance). Without this log the hotkey just silently does nothing. + Logger.Warn($"RegisterHotKey failed for modifiers=0x{modifiers:X} key=0x{key:X} — combination may be in use by another application."); + return false; + } + + public void UnregisterAll() + { + foreach (var id in _hotKeyActions.Keys.ToList()) + { + UnregisterHotKey(WindowHandle, id); + } + _hotKeyActions.Clear(); + _currentId = 0; // Reset ID counter + } + + private void HandleHotKeyMessage(int id) + { + if (_hotKeyActions.TryGetValue(id, out var action)) + { + try + { + action?.Invoke(); + } + catch (Exception ex) + { + // An exception escaping the window procedure can take down the process; a failed + // capture should be logged, not fatal. + Logger.Error("Hotkey action threw", ex); + } + } + } + + public void Dispose() + { + UnregisterAll(); + if (_messageWindow?.Handle != IntPtr.Zero) + { + _messageWindow?.ReleaseHandle(); + } + } + + private sealed class HotKeyMessageWindow : System.Windows.Forms.NativeWindow + { + private readonly Win32GlobalHotkeys _owner; + + public HotKeyMessageWindow(Win32GlobalHotkeys owner) => _owner = owner; + + protected override void WndProc(ref System.Windows.Forms.Message m) + { + if (m.Msg == WM_HOTKEY) + { + _owner.HandleHotKeyMessage(m.WParam.ToInt32()); + } + base.WndProc(ref m); + } + } +} diff --git a/MoneyShot.Platform.Windows/Win32ScreenCapture.cs b/MoneyShot.Platform.Windows/Win32ScreenCapture.cs new file mode 100644 index 0000000..b4e28de --- /dev/null +++ b/MoneyShot.Platform.Windows/Win32ScreenCapture.cs @@ -0,0 +1,82 @@ +using System.Drawing; +using System.Drawing.Imaging; +using System.Runtime.InteropServices; +using MoneyShot.Abstractions; + +namespace MoneyShot.Platform.Windows; + +/// +/// GDI+ screen capture (the Windows implementation of IScreenCapture — see LINUX_PORT.md § Capture +/// pipeline for the X11/Wayland equivalents). Reads pixels directly via Bitmap.LockBits rather than +/// the old GetHbitmap→CreateBitmapSourceFromHBitmap→DeleteObject dance, so there's no HBITMAP handle +/// to leak. +/// +public sealed class Win32ScreenCapture : IScreenCapture +{ + public CapturedImage CaptureFullScreen() + { + return CaptureRegion(GetVirtualScreenBounds()); + } + + public CapturedImage CaptureMonitor(int monitorIndex) + { + var screens = System.Windows.Forms.Screen.AllScreens; + if (monitorIndex < 0 || monitorIndex >= screens.Length) + throw new ArgumentOutOfRangeException(nameof(monitorIndex)); + + return CaptureRegion(screens[monitorIndex].Bounds); + } + + public IReadOnlyList GetAllMonitors() + { + return System.Windows.Forms.Screen.AllScreens + .Select(s => new MonitorInfo(s.Bounds.Left, s.Bounds.Top, s.Bounds.Width, s.Bounds.Height, s.Primary, s.DeviceName)) + .ToList(); + } + + private static CapturedImage CaptureRegion(Rectangle region) + { + using var bitmap = new Bitmap(region.Width, region.Height, PixelFormat.Format32bppPArgb); + using (var graphics = Graphics.FromImage(bitmap)) + { + graphics.CopyFromScreen(region.Left, region.Top, 0, 0, region.Size, CopyPixelOperation.SourceCopy); + } + + return ToCapturedImage(bitmap); + } + + private static CapturedImage ToCapturedImage(Bitmap bitmap) + { + var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); + var bitmapData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppPArgb); + try + { + var stride = bitmapData.Stride; + var bytes = new byte[stride * bitmap.Height]; + Marshal.Copy(bitmapData.Scan0, bytes, 0, bytes.Length); + return new CapturedImage(bitmap.Width, bitmap.Height, stride, bytes); + } + finally + { + bitmap.UnlockBits(bitmapData); + } + } + + private static Rectangle GetVirtualScreenBounds() + { + int minX = int.MaxValue; + int minY = int.MaxValue; + int maxX = int.MinValue; + int maxY = int.MinValue; + + foreach (var screen in System.Windows.Forms.Screen.AllScreens) + { + minX = Math.Min(minX, screen.Bounds.Left); + minY = Math.Min(minY, screen.Bounds.Top); + maxX = Math.Max(maxX, screen.Bounds.Right); + maxY = Math.Max(maxY, screen.Bounds.Bottom); + } + + return new Rectangle(minX, minY, maxX - minX, maxY - minY); + } +} diff --git a/MoneyShot.Platform.Windows/Win32TrayIcon.cs b/MoneyShot.Platform.Windows/Win32TrayIcon.cs new file mode 100644 index 0000000..d06d52b --- /dev/null +++ b/MoneyShot.Platform.Windows/Win32TrayIcon.cs @@ -0,0 +1,79 @@ +using System.IO; +using System.Windows.Forms; +using MoneyShot.Abstractions; +using MoneyShot.Services; + +namespace MoneyShot.Platform.Windows; + +/// +/// NotifyIcon-based system tray (see LINUX_PORT.md § System tray for the StatusNotifierItem/D-Bus +/// equivalent on Linux, wrapped by Avalonia's TrayIcon there). +/// +public sealed class Win32TrayIcon : ITrayIcon +{ + private NotifyIcon? _notifyIcon; + + public event Action? DoubleClicked; + + public void Show(string tooltip, IReadOnlyList menuItems) + { + var icon = ResolveIcon(); + + var contextMenu = new ContextMenuStrip(); + foreach (var item in menuItems) + { + if (item.IsSeparator) + { + contextMenu.Items.Add("-"); + continue; + } + + var onClick = item.OnClick; + contextMenu.Items.Add(item.Label, null, (_, _) => onClick?.Invoke()); + } + + _notifyIcon = new NotifyIcon + { + Icon = icon, + Visible = true, + Text = tooltip, + ContextMenuStrip = contextMenu + }; + _notifyIcon.DoubleClick += (_, _) => DoubleClicked?.Invoke(); + } + + public void ShowBalloonTip(int timeoutMilliseconds, string title, string text) + { + _notifyIcon?.ShowBalloonTip(timeoutMilliseconds, title, text, ToolTipIcon.Info); + } + + private static System.Drawing.Icon ResolveIcon() + { + try + { + var processModule = System.Diagnostics.Process.GetCurrentProcess().MainModule; + var iconPath = processModule?.FileName; + + if (iconPath != null && File.Exists(iconPath)) + { + var extracted = System.Drawing.Icon.ExtractAssociatedIcon(iconPath); + if (extracted != null) + { + return extracted; + } + } + } + catch (Exception ex) + { + Logger.Error("Error extracting tray icon", ex); + } + + // Fallback to default icon if extraction fails + return System.Drawing.SystemIcons.Application; + } + + public void Dispose() + { + _notifyIcon?.Dispose(); + } +} diff --git a/MoneyShot.Tests/HotKeyServiceTests.cs b/MoneyShot.Tests/HotKeyServiceTests.cs index e8b5a78..ab2e75a 100644 --- a/MoneyShot.Tests/HotKeyServiceTests.cs +++ b/MoneyShot.Tests/HotKeyServiceTests.cs @@ -3,53 +3,58 @@ namespace MoneyShot.Tests; +// Parsing moved to the platform-neutral HotKeyParser (MoneyShot.Core) as part of the Linux-port +// groundwork — see LINUX_PORT.md Phase 0. The Win32-specific registration mechanics now live in +// MoneyShot.Platform.Windows.Win32GlobalHotkeys, which isn't unit-testable (it P/Invokes +// RegisterHotKey against a real HWND) — same category of "needs manual verification on Windows" +// as the rest of the OS-touching surface, per CLAUDE.md. public class HotKeyServiceTests { [Theory] - [InlineData("Ctrl+PrintScreen", HotKeyService.MOD_CONTROL, HotKeyService.VK_SNAPSHOT)] - [InlineData("Alt+F1", HotKeyService.MOD_ALT, HotKeyService.VK_F1)] - [InlineData("Shift+F12", HotKeyService.MOD_SHIFT, HotKeyService.VK_F12)] - [InlineData("Win+1", HotKeyService.MOD_WIN, HotKeyService.VK_1)] - [InlineData("Ctrl+Shift+1", HotKeyService.MOD_CONTROL | HotKeyService.MOD_SHIFT, HotKeyService.VK_1)] - [InlineData("Ctrl+Alt+Shift+Win+0", HotKeyService.MOD_CONTROL | HotKeyService.MOD_ALT | HotKeyService.MOD_SHIFT | HotKeyService.MOD_WIN, HotKeyService.VK_0)] - [InlineData("Control+F5", HotKeyService.MOD_CONTROL, HotKeyService.VK_F5)] - [InlineData("Windows+9", HotKeyService.MOD_WIN, HotKeyService.VK_9)] - [InlineData("PrtSc", 0u, HotKeyService.VK_SNAPSHOT)] - [InlineData("PrintScreen", 0u, HotKeyService.VK_SNAPSHOT)] + [InlineData("Ctrl+PrintScreen", HotKeyParser.MOD_CONTROL, HotKeyParser.VK_SNAPSHOT)] + [InlineData("Alt+F1", HotKeyParser.MOD_ALT, HotKeyParser.VK_F1)] + [InlineData("Shift+F12", HotKeyParser.MOD_SHIFT, HotKeyParser.VK_F12)] + [InlineData("Win+1", HotKeyParser.MOD_WIN, HotKeyParser.VK_1)] + [InlineData("Ctrl+Shift+1", HotKeyParser.MOD_CONTROL | HotKeyParser.MOD_SHIFT, HotKeyParser.VK_1)] + [InlineData("Ctrl+Alt+Shift+Win+0", HotKeyParser.MOD_CONTROL | HotKeyParser.MOD_ALT | HotKeyParser.MOD_SHIFT | HotKeyParser.MOD_WIN, HotKeyParser.VK_0)] + [InlineData("Control+F5", HotKeyParser.MOD_CONTROL, HotKeyParser.VK_F5)] + [InlineData("Windows+9", HotKeyParser.MOD_WIN, HotKeyParser.VK_9)] + [InlineData("PrtSc", 0u, HotKeyParser.VK_SNAPSHOT)] + [InlineData("PrintScreen", 0u, HotKeyParser.VK_SNAPSHOT)] public void ParseHotKey_RecognizedCombinations(string input, uint expectedModifiers, uint expectedKey) { - var (modifiers, key) = HotKeyService.ParseHotKey(input); + var (modifiers, key) = HotKeyParser.ParseHotKey(input); Assert.Equal(expectedModifiers, modifiers); Assert.Equal(expectedKey, key); } [Theory] - [InlineData("F1", HotKeyService.VK_F1)] - [InlineData("F2", HotKeyService.VK_F2)] - [InlineData("F3", HotKeyService.VK_F3)] - [InlineData("F4", HotKeyService.VK_F4)] - [InlineData("F5", HotKeyService.VK_F5)] - [InlineData("F6", HotKeyService.VK_F6)] - [InlineData("F7", HotKeyService.VK_F7)] - [InlineData("F8", HotKeyService.VK_F8)] - [InlineData("F9", HotKeyService.VK_F9)] - [InlineData("F10", HotKeyService.VK_F10)] - [InlineData("F11", HotKeyService.VK_F11)] - [InlineData("F12", HotKeyService.VK_F12)] + [InlineData("F1", HotKeyParser.VK_F1)] + [InlineData("F2", HotKeyParser.VK_F2)] + [InlineData("F3", HotKeyParser.VK_F3)] + [InlineData("F4", HotKeyParser.VK_F4)] + [InlineData("F5", HotKeyParser.VK_F5)] + [InlineData("F6", HotKeyParser.VK_F6)] + [InlineData("F7", HotKeyParser.VK_F7)] + [InlineData("F8", HotKeyParser.VK_F8)] + [InlineData("F9", HotKeyParser.VK_F9)] + [InlineData("F10", HotKeyParser.VK_F10)] + [InlineData("F11", HotKeyParser.VK_F11)] + [InlineData("F12", HotKeyParser.VK_F12)] public void ParseHotKey_AllFunctionKeys(string input, uint expectedKey) { - var (modifiers, key) = HotKeyService.ParseHotKey(input); + var (modifiers, key) = HotKeyParser.ParseHotKey(input); Assert.Equal(0u, modifiers); Assert.Equal(expectedKey, key); } [Theory] - [InlineData("0", HotKeyService.VK_0)] - [InlineData("1", HotKeyService.VK_1)] - [InlineData("9", HotKeyService.VK_9)] + [InlineData("0", HotKeyParser.VK_0)] + [InlineData("1", HotKeyParser.VK_1)] + [InlineData("9", HotKeyParser.VK_9)] public void ParseHotKey_DigitKeys(string input, uint expectedKey) { - var (_, key) = HotKeyService.ParseHotKey(input); + var (_, key) = HotKeyParser.ParseHotKey(input); Assert.Equal(expectedKey, key); } @@ -59,7 +64,7 @@ public void ParseHotKey_DigitKeys(string input, uint expectedKey) [InlineData(null)] public void ParseHotKey_EmptyOrWhitespace_ReturnsZero(string? input) { - var (modifiers, key) = HotKeyService.ParseHotKey(input!); + var (modifiers, key) = HotKeyParser.ParseHotKey(input!); Assert.Equal(0u, modifiers); Assert.Equal(0u, key); } @@ -72,7 +77,7 @@ public void ParseHotKey_EmptyOrWhitespace_ReturnsZero(string? input) [InlineData("Space")] public void ParseHotKey_UnknownKey_ReturnsZeroKey(string input) { - var (_, key) = HotKeyService.ParseHotKey(input); + var (_, key) = HotKeyParser.ParseHotKey(input); Assert.Equal(0u, key); } @@ -82,16 +87,16 @@ public void ParseHotKey_UnknownKey_ReturnsZeroKey(string input) [InlineData("CtRl+PrInTsCrEeN")] public void ParseHotKey_IsCaseInsensitive(string input) { - var (modifiers, key) = HotKeyService.ParseHotKey(input); - Assert.Equal(HotKeyService.MOD_CONTROL, modifiers); - Assert.Equal(HotKeyService.VK_SNAPSHOT, key); + var (modifiers, key) = HotKeyParser.ParseHotKey(input); + Assert.Equal(HotKeyParser.MOD_CONTROL, modifiers); + Assert.Equal(HotKeyParser.VK_SNAPSHOT, key); } [Fact] public void ParseHotKey_ToleratesExtraSpaces() { - var (modifiers, key) = HotKeyService.ParseHotKey(" Ctrl + PrintScreen "); - Assert.Equal(HotKeyService.MOD_CONTROL, modifiers); - Assert.Equal(HotKeyService.VK_SNAPSHOT, key); + var (modifiers, key) = HotKeyParser.ParseHotKey(" Ctrl + PrintScreen "); + Assert.Equal(HotKeyParser.MOD_CONTROL, modifiers); + Assert.Equal(HotKeyParser.VK_SNAPSHOT, key); } } diff --git a/MoneyShot.Tests/MoneyShot.Tests.csproj b/MoneyShot.Tests/MoneyShot.Tests.csproj index 6bb539c..c387e1a 100644 --- a/MoneyShot.Tests/MoneyShot.Tests.csproj +++ b/MoneyShot.Tests/MoneyShot.Tests.csproj @@ -18,6 +18,8 @@ + + diff --git a/MoneyShot.Tests/SaveServiceTests.cs b/MoneyShot.Tests/SaveServiceTests.cs index 9a06ef3..593b50a 100644 --- a/MoneyShot.Tests/SaveServiceTests.cs +++ b/MoneyShot.Tests/SaveServiceTests.cs @@ -1,4 +1,5 @@ using System.IO; +using MoneyShot.Platform.Windows; using MoneyShot.Services; using Xunit; @@ -6,7 +7,7 @@ namespace MoneyShot.Tests; public class SaveServiceTests { - private readonly SaveService _service = new(); + private readonly SaveService _service = new(new Win32Clipboard()); // Path validation runs before the image is touched, so a null image never reaches the // encoder for these rejection cases — no WPF/STA setup needed. diff --git a/MoneyShot.UI/App.axaml b/MoneyShot.UI/App.axaml new file mode 100644 index 0000000..2d49108 --- /dev/null +++ b/MoneyShot.UI/App.axaml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + diff --git a/MoneyShot.UI/App.axaml.cs b/MoneyShot.UI/App.axaml.cs new file mode 100644 index 0000000..9b2a163 --- /dev/null +++ b/MoneyShot.UI/App.axaml.cs @@ -0,0 +1,104 @@ +using System.Threading; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Layout; +using Avalonia.Markup.Xaml; +using MoneyShot.UI.Views; + +namespace MoneyShot.UI; + +public partial class App : Application +{ + // Deliberately a different mutex name than the WPF build's ("MoneyShot_SingleInstance_Mutex_ + // 3E6F8A2D") — these are two separate builds of the same app (see LINUX_PORT.md Phase 1) that + // may run side-by-side during evaluation, and sharing a mutex would make one refuse to start + // just because the other happens to be running. + private const string MutexName = "MoneyShot_SingleInstance_Mutex_UI_7B1D9E4A"; + private static Mutex? _mutex; + private static bool _ownsMutex; + + public override void Initialize() + { + AvaloniaXamlLoader.Load(this); + } + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + _mutex = new Mutex(true, MutexName, out var createdNew); + _ownsMutex = createdNew; + + if (!createdNew) + { + ShowAlreadyRunningDialogAndExit(desktop); + return; + } + + desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown; + desktop.Exit += (_, _) => OnExit(); + + var mainWindow = new MainWindow(); + desktop.MainWindow = mainWindow; + mainWindow.InitializeApplication(); + } + + base.OnFrameworkInitializationCompleted(); + } + + /// + /// Avalonia has no built-in MessageBox (unlike WPF), so the "already running" notice is a + /// tiny inline window — same pattern EditorWindow's "Add text" prompt uses on the WPF side. + /// + private static void ShowAlreadyRunningDialogAndExit(IClassicDesktopStyleApplicationLifetime desktop) + { + var notice = new Window + { + Title = "Money Shot", + Width = 360, + SizeToContent = SizeToContent.Height, + CanResize = false, + WindowStartupLocation = WindowStartupLocation.CenterScreen, + Content = new StackPanel + { + Margin = new Thickness(20), + Children = + { + new TextBlock + { + Text = "Money Shot is already running. Check the system tray.", + TextWrapping = Avalonia.Media.TextWrapping.Wrap, + Margin = new Thickness(0, 0, 0, 16) + }, + new Button + { + Content = "OK", + HorizontalAlignment = HorizontalAlignment.Right, + IsDefault = true + } + } + } + }; + + if (notice.Content is StackPanel panel && panel.Children[1] is Button okButton) + { + okButton.Click += (_, _) => notice.Close(); + } + + desktop.MainWindow = notice; + notice.Closed += (_, _) => desktop.Shutdown(); + notice.Show(); + } + + private static void OnExit() + { + // Only the instance that actually acquired the mutex may release it — mirrors the WPF + // build's App.OnExit guard (calling ReleaseMutex without ownership throws). + if (_ownsMutex) + { + _mutex?.ReleaseMutex(); + } + _mutex?.Dispose(); + } +} diff --git a/MoneyShot.UI/Editor/CanvasPosition.cs b/MoneyShot.UI/Editor/CanvasPosition.cs new file mode 100644 index 0000000..d485de6 --- /dev/null +++ b/MoneyShot.UI/Editor/CanvasPosition.cs @@ -0,0 +1,25 @@ +using Avalonia; +using Avalonia.Controls; + +namespace MoneyShot.UI.Editor; + +/// +/// Avalonia port of MoneyShot/Editor/CanvasPosition.cs — see LINUX_PORT.md Phase 1. Centralizes +/// the NaN guards that used to be repeated everywhere we read Canvas.GetLeft/GetTop. Canvas +/// attached properties default to NaN when never set, which propagates through arithmetic and +/// ends up displayed as 0 — the cause of past snap-to-(0,0) regressions in the WPF build. +/// +internal static class CanvasPosition +{ + public static double GetLeft(Control element) + { + var value = Canvas.GetLeft(element); + return double.IsNaN(value) ? 0 : value; + } + + public static double GetTop(Control element) + { + var value = Canvas.GetTop(element); + return double.IsNaN(value) ? 0 : value; + } +} diff --git a/MoneyShot.UI/Editor/CanvasRenderer.cs b/MoneyShot.UI/Editor/CanvasRenderer.cs new file mode 100644 index 0000000..05177fa --- /dev/null +++ b/MoneyShot.UI/Editor/CanvasRenderer.cs @@ -0,0 +1,141 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Shapes; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using MoneyShot.Abstractions; +using MoneyShot.UI.Interop; + +namespace MoneyShot.UI.Editor; + +/// +/// Avalonia port of MoneyShot/Editor/CanvasRenderer.cs — see LINUX_PORT.md Phase 1. Pure +/// rendering helpers extracted from EditorWindow; none depend on editor state beyond their +/// parameters. +/// +internal static class CanvasRenderer +{ + private const int PixelateBlockSize = 10; + + /// + /// Renders the editor canvas to a bitmap matching the underlying image's pixel dimensions. + /// Temporarily disables the zoom and pan transforms so the saved image captures the full + /// frame at native resolution, regardless of how the user has panned/zoomed the editor view. + /// Both transforms are restored afterwards so the user doesn't see their viewport jump. + /// + public static Bitmap CaptureCanvasAsImage(Control imageCanvas, Bitmap originalImage, ScaleTransform zoomTransform, TranslateTransform panTransform) + { + var imageWidth = originalImage.PixelSize.Width; + var imageHeight = originalImage.PixelSize.Height; + + var originalScaleX = zoomTransform.ScaleX; + var originalScaleY = zoomTransform.ScaleY; + var originalPanX = panTransform.X; + var originalPanY = panTransform.Y; + zoomTransform.ScaleX = 1; + zoomTransform.ScaleY = 1; + panTransform.X = 0; + panTransform.Y = 0; + + imageCanvas.Measure(new Size(imageWidth, imageHeight)); + imageCanvas.Arrange(new Rect(0, 0, imageWidth, imageHeight)); + + var renderBitmap = new RenderTargetBitmap(new PixelSize(imageWidth, imageHeight), new Vector(96, 96)); + renderBitmap.Render(imageCanvas); + + zoomTransform.ScaleX = originalScaleX; + zoomTransform.ScaleY = originalScaleY; + panTransform.X = originalPanX; + panTransform.Y = originalPanY; + + return renderBitmap; + } + + /// + /// Builds an ImageBrush whose contents are a block-averaged version of the area beneath the + /// supplied rectangle, producing the classic "censor bar" pixelation effect. Operates on the + /// raw CapturedImage pixel buffer (via ToCapturedImage) rather than Avalonia's own + /// BitmapSource.CopyPixels equivalent, since that's what's already available and tested from + /// the capture pipeline — same block-averaging math as the WPF version. + /// + public static IBrush CreatePixelatedBrush(Rectangle pixelateRect, Bitmap originalImage) + { + var left = (int)Math.Round(CanvasPosition.GetLeft(pixelateRect)); + var top = (int)Math.Round(CanvasPosition.GetTop(pixelateRect)); + var width = (int)pixelateRect.Width; + var height = (int)pixelateRect.Height; + if (width <= 0 || height <= 0) return pixelateRect.Fill ?? Brushes.Transparent; + + try + { + var captured = originalImage.ToCapturedImage(); + + var srcX = Math.Max(0, Math.Min(left, captured.Width - 1)); + var srcY = Math.Max(0, Math.Min(top, captured.Height - 1)); + var srcW = Math.Min(width, captured.Width - srcX); + var srcH = Math.Min(height, captured.Height - srcY); + if (srcW <= 0 || srcH <= 0) return pixelateRect.Fill ?? Brushes.Transparent; + + const int bytesPerPixel = 4; + var stride = srcW * bytesPerPixel; + var pixels = new byte[stride * srcH]; + for (var row = 0; row < srcH; row++) + { + var srcOffset = (srcY + row) * captured.Stride + srcX * bytesPerPixel; + Buffer.BlockCopy(captured.PixelDataBgra32, srcOffset, pixels, row * stride, stride); + } + + for (var blockTop = 0; blockTop < srcH; blockTop += PixelateBlockSize) + { + var blockH = Math.Min(PixelateBlockSize, srcH - blockTop); + for (var blockLeft = 0; blockLeft < srcW; blockLeft += PixelateBlockSize) + { + var blockW = Math.Min(PixelateBlockSize, srcW - blockLeft); + + long sumB = 0, sumG = 0, sumR = 0; + for (var y = 0; y < blockH; y++) + { + var offset = (blockTop + y) * stride + blockLeft * bytesPerPixel; + for (var x = 0; x < blockW; x++) + { + sumB += pixels[offset]; + sumG += pixels[offset + 1]; + sumR += pixels[offset + 2]; + offset += bytesPerPixel; + } + } + + var count = blockW * blockH; + var b = (byte)(sumB / count); + var g = (byte)(sumG / count); + var r = (byte)(sumR / count); + + for (var y = 0; y < blockH; y++) + { + var offset = (blockTop + y) * stride + blockLeft * bytesPerPixel; + for (var x = 0; x < blockW; x++) + { + pixels[offset] = b; + pixels[offset + 1] = g; + pixels[offset + 2] = r; + pixels[offset + 3] = 0xFF; + offset += bytesPerPixel; + } + } + } + } + + var pixelated = new CapturedImage(srcW, srcH, stride, pixels).ToAvaloniaBitmap(); + return new ImageBrush(pixelated) { Stretch = Stretch.Fill }; + } + catch (ArgumentException) + { + return new SolidColorBrush(Color.FromArgb(200, 128, 128, 128)); + } + catch (InvalidOperationException) + { + return new SolidColorBrush(Color.FromArgb(200, 128, 128, 128)); + } + } +} diff --git a/MoneyShot.UI/Editor/ElementResizeMode.cs b/MoneyShot.UI/Editor/ElementResizeMode.cs new file mode 100644 index 0000000..96c2528 --- /dev/null +++ b/MoneyShot.UI/Editor/ElementResizeMode.cs @@ -0,0 +1,14 @@ +namespace MoneyShot.UI.Editor; + +internal enum ElementResizeMode +{ + None, + TopLeft, + TopRight, + BottomLeft, + BottomRight, + Top, + Bottom, + Left, + Right +} diff --git a/MoneyShot.UI/Editor/ElementState.cs b/MoneyShot.UI/Editor/ElementState.cs new file mode 100644 index 0000000..56ac1e0 --- /dev/null +++ b/MoneyShot.UI/Editor/ElementState.cs @@ -0,0 +1,3 @@ +namespace MoneyShot.UI.Editor; + +internal sealed record ElementState(double Left, double Top, double Width, double Height, double? FontSize); diff --git a/MoneyShot.UI/Editor/UndoController.cs b/MoneyShot.UI/Editor/UndoController.cs new file mode 100644 index 0000000..dd41fc7 --- /dev/null +++ b/MoneyShot.UI/Editor/UndoController.cs @@ -0,0 +1,54 @@ +using System.Collections.Generic; +using Avalonia.Controls; +using Avalonia.Media.Imaging; +using MoneyShot.UI.Views; + +namespace MoneyShot.UI.Editor; + +/// +/// Avalonia port of MoneyShot/Editor/UndoController.cs — see LINUX_PORT.md Phase 1. Owns the +/// editor undo stack and the action records; EditorWindow pushes onto this from the places where +/// mutations happen, and calls Undo when the user triggers undo. +/// +internal sealed class UndoController +{ + private readonly Stack _stack = new(); + + public int Count => _stack.Count; + + public void Push(IUndoAction action) => _stack.Push(action); + + public void Clear() => _stack.Clear(); + + public void Undo(EditorWindow window) + { + if (_stack.Count == 0) return; + _stack.Pop().Undo(window); + } + + public interface IUndoAction + { + void Undo(EditorWindow window); + } + + public sealed class AddElementUndoAction(Control element) : IUndoAction + { + public void Undo(EditorWindow window) => window.UndoAddElement(element); + } + + public sealed class RemoveElementUndoAction(Control element, int index) : IUndoAction + { + public void Undo(EditorWindow window) => window.UndoRemoveElement(element, index); + } + + public sealed class CropUndoAction(Bitmap previousImage, IReadOnlyList previousElements, int previousNumberCounter) : IUndoAction + { + public void Undo(EditorWindow window) => + window.UndoCrop(previousImage, previousElements, previousNumberCounter); + } + + public sealed class ResizeUndoAction(Control element, ElementState previousState) : IUndoAction + { + public void Undo(EditorWindow window) => window.UndoResize(element, previousState); + } +} diff --git a/MoneyShot.UI/Interop/BitmapConversions.cs b/MoneyShot.UI/Interop/BitmapConversions.cs new file mode 100644 index 0000000..200bc8a --- /dev/null +++ b/MoneyShot.UI/Interop/BitmapConversions.cs @@ -0,0 +1,74 @@ +using System; +using System.Runtime.InteropServices; +using Avalonia; +using Avalonia.Media.Imaging; +using Avalonia.Platform; +using MoneyShot.Abstractions; + +namespace MoneyShot.UI.Interop; + +/// +/// Converts between the platform-neutral MoneyShot.Abstractions.CapturedImage (raw BGRA32 pixels) +/// and Avalonia's WriteableBitmap/Bitmap, at the UI-layer boundary — the Avalonia twin of +/// MoneyShot/Interop/BitmapConversions.cs (WPF). See LINUX_PORT.md Phase 1. +/// +public static class BitmapConversions +{ + public static Bitmap ToAvaloniaBitmap(this CapturedImage image) + { + var writeable = new WriteableBitmap( + new PixelSize(image.Width, image.Height), + new Vector(96, 96), + PixelFormat.Bgra8888, + AlphaFormat.Premul); + + using (var buffer = writeable.Lock()) + { + for (var y = 0; y < image.Height; y++) + { + Marshal.Copy(image.PixelDataBgra32, y * image.Stride, + buffer.Address + y * buffer.RowBytes, Math.Min(image.Stride, buffer.RowBytes)); + } + } + + return writeable; + } + + public static CapturedImage ToCapturedImage(this Bitmap bitmap) + { + // WriteableBitmap gives direct pixel access via Lock(). Anything else (e.g. a + // RenderTargetBitmap straight off a rendered canvas) is round-tripped through a PNG encode + // + decode to reach a WriteableBitmap — slower than a direct pixel blit, but uses only the + // two most well-established Bitmap APIs (Save/Decode) rather than a lower-level drawing + // API this port hasn't independently verified. Only used for save-to-clipboard, which is + // not a hot path. + WriteableBitmap writeable; + var ownsWriteable = false; + if (bitmap is WriteableBitmap wb) + { + writeable = wb; + } + else + { + using var stream = new System.IO.MemoryStream(); + bitmap.Save(stream); + stream.Position = 0; + writeable = WriteableBitmap.Decode(stream); + ownsWriteable = true; + } + + try + { + using var buffer = writeable.Lock(); + var pixelSize = writeable.PixelSize; + var stride = buffer.RowBytes; + var bytes = new byte[stride * pixelSize.Height]; + Marshal.Copy(buffer.Address, bytes, 0, bytes.Length); + return new CapturedImage(pixelSize.Width, pixelSize.Height, stride, bytes); + } + finally + { + if (ownsWriteable) writeable.Dispose(); + } + } +} diff --git a/MoneyShot.UI/MoneyShot.UI.csproj b/MoneyShot.UI/MoneyShot.UI.csproj new file mode 100644 index 0000000..47e0d47 --- /dev/null +++ b/MoneyShot.UI/MoneyShot.UI.csproj @@ -0,0 +1,69 @@ + + + + WinExe + + net10.0-windows + enable + enable + true + true + app.manifest + true + 2.1.0 + 2.1.0.0 + 2.1.0.0 + Daolyap & iSaluki + Daolyap & iSaluki + Money Shot Screenshot Tool + A modern, feature-rich screenshot tool with comprehensive annotation capabilities (Avalonia UI — see LINUX_PORT.md Phase 1). + Copyright © 2026 Daolyap & iSaluki + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MoneyShot.UI/Program.cs b/MoneyShot.UI/Program.cs new file mode 100644 index 0000000..ee26798 --- /dev/null +++ b/MoneyShot.UI/Program.cs @@ -0,0 +1,17 @@ +using Avalonia; + +namespace MoneyShot.UI; + +internal static class Program +{ + // Avalonia needs its own Main (not auto-generated like WPF's) so the classic desktop + // lifetime can be configured explicitly. + [STAThread] + public static void Main(string[] args) => BuildAvaloniaApp() + .StartWithClassicDesktopLifetime(args); + + public static AppBuilder BuildAvaloniaApp() => + AppBuilder.Configure() + .UsePlatformDetect() + .LogToTrace(); +} diff --git a/MoneyShot.UI/Services/HistoryService.cs b/MoneyShot.UI/Services/HistoryService.cs new file mode 100644 index 0000000..caeaa85 --- /dev/null +++ b/MoneyShot.UI/Services/HistoryService.cs @@ -0,0 +1,166 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Text.Json; +using Avalonia.Media.Imaging; +using MoneyShot.Models; +using Logger = MoneyShot.Services.Logger; + +namespace MoneyShot.UI.Services; + +/// +/// Avalonia twin of MoneyShot/Services/HistoryService.cs (WPF) — see LINUX_PORT.md Phase 1. Same +/// file layout and JSON metadata shape (both builds share the same %AppData%\MoneyShot\history +/// directory, so history captured by either build shows up in both), with BitmapSource/ +/// PngBitmapEncoder swapped for Avalonia's Bitmap. History is always PNG regardless of the user's +/// chosen save format — matches the WPF version, which also hardcoded PngBitmapEncoder here. +/// +public sealed class HistoryService +{ + private const int ThumbnailMaxWidth = 400; + private const int DefaultRetentionCount = 50; + + private static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true }; + private readonly string _historyDirectory; + + public HistoryService() + { + _historyDirectory = Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), + "MoneyShot", + "history"); + try + { + Directory.CreateDirectory(_historyDirectory); + } + catch (Exception ex) + { + Logger.Error("Could not create history directory", ex); + } + } + + public string HistoryDirectory => _historyDirectory; + + public HistoryEntry? Save(Bitmap image, string source, int retentionCount = DefaultRetentionCount) + { + try + { + var id = $"{DateTime.Now:yyyyMMdd-HHmmss}-{Guid.NewGuid():N}"; + var entry = new HistoryEntry + { + Id = id, + CapturedAt = DateTime.Now, + Width = image.PixelSize.Width, + Height = image.PixelSize.Height, + Source = source, + ImageFileName = $"{id}.png", + ThumbnailFileName = $"{id}-thumb.png", + }; + + image.Save(Path.Combine(_historyDirectory, entry.ImageFileName)); + using (var thumbnail = CreateThumbnail(image)) + { + thumbnail.Save(Path.Combine(_historyDirectory, entry.ThumbnailFileName)); + } + File.WriteAllText( + Path.Combine(_historyDirectory, $"{id}.json"), + JsonSerializer.Serialize(entry, JsonOptions)); + + EnforceRetention(retentionCount); + return entry; + } + catch (Exception ex) + { + Logger.Error("Failed to save history entry", ex); + return null; + } + } + + public IReadOnlyList List() + { + try + { + return Directory.EnumerateFiles(_historyDirectory, "*.json") + .Select(LoadEntry) + .Where(e => e != null) + .Select(e => e!) + .OrderByDescending(e => e.CapturedAt) + .ToList(); + } + catch (Exception ex) + { + Logger.Error("Failed to list history", ex); + return Array.Empty(); + } + } + + public Bitmap? LoadImage(HistoryEntry entry) => + LoadPng(Path.Combine(_historyDirectory, entry.ImageFileName)); + + public Bitmap? LoadThumbnail(HistoryEntry entry) => + LoadPng(Path.Combine(_historyDirectory, entry.ThumbnailFileName)); + + public void Delete(HistoryEntry entry) + { + TryDelete(Path.Combine(_historyDirectory, entry.ImageFileName)); + TryDelete(Path.Combine(_historyDirectory, entry.ThumbnailFileName)); + TryDelete(Path.Combine(_historyDirectory, $"{entry.Id}.json")); + } + + private void EnforceRetention(int retentionCount) + { + if (retentionCount <= 0) return; + var entries = List(); + if (entries.Count <= retentionCount) return; + foreach (var stale in entries.Skip(retentionCount)) + { + Delete(stale); + } + } + + private static HistoryEntry? LoadEntry(string jsonPath) + { + try + { + return JsonSerializer.Deserialize(File.ReadAllText(jsonPath)); + } + catch + { + return null; + } + } + + private static Bitmap? LoadPng(string path) + { + try + { + if (!File.Exists(path)) return null; + // Read fully into memory before decoding so the file handle doesn't stay open — + // matches the WPF version's BitmapCacheOption.OnLoad intent (lets Delete succeed later). + var bytes = File.ReadAllBytes(path); + using var stream = new MemoryStream(bytes); + return new Bitmap(stream); + } + catch (Exception ex) + { + Logger.Warn($"Failed to load history image at {path}", ex); + return null; + } + } + + private static Bitmap CreateThumbnail(Bitmap source) + { + if (source.PixelSize.Width <= ThumbnailMaxWidth) return source; + var scale = (double)ThumbnailMaxWidth / source.PixelSize.Width; + var targetSize = new Avalonia.PixelSize( + ThumbnailMaxWidth, + Math.Max(1, (int)Math.Round(source.PixelSize.Height * scale))); + return source.CreateScaledBitmap(targetSize, BitmapInterpolationMode.HighQuality); + } + + private static void TryDelete(string path) + { + try { if (File.Exists(path)) File.Delete(path); } catch { /* best-effort */ } + } +} diff --git a/MoneyShot.UI/Services/SaveService.cs b/MoneyShot.UI/Services/SaveService.cs new file mode 100644 index 0000000..b046a87 --- /dev/null +++ b/MoneyShot.UI/Services/SaveService.cs @@ -0,0 +1,184 @@ +using System; +using System.IO; +using Avalonia.Media.Imaging; +using MoneyShot.Abstractions; +using MoneyShot.Models; +using MoneyShot.UI.Interop; +using SkiaSharp; +using Logger = MoneyShot.Services.Logger; + +namespace MoneyShot.UI.Services; + +/// +/// Avalonia twin of MoneyShot/Services/SaveService.cs (WPF) — see LINUX_PORT.md Phase 1. Same +/// shape and same file-path validation logic (copied verbatim, it's pure and platform-neutral); +/// the WPF BitmapEncoder family is replaced with SkiaSharp encoding of the CapturedImage pixel +/// buffer, since Avalonia's own Bitmap.Save is PNG-only regardless of requested format. +/// +public class SaveService +{ + private readonly IClipboard _clipboard; + + public SaveService(IClipboard clipboard) + { + _clipboard = clipboard; + } + + public void SaveToClipboard(Bitmap image) + { + try + { + _clipboard.SetImage(image.ToCapturedImage()); + } + catch (Exception ex) + { + Logger.Error("Error saving to clipboard", ex); + throw new InvalidOperationException("Failed to save image to clipboard.", ex); + } + } + + public void SaveToFile(Bitmap image, string filePath, string format = "PNG") + { + ValidateFilePath(filePath); + + try + { + var captured = image.ToCapturedImage(); + var info = new SKImageInfo(captured.Width, captured.Height, SKColorType.Bgra8888, SKAlphaType.Premul); + + using var skBitmap = new SKBitmap(); + var handle = System.Runtime.InteropServices.GCHandle.Alloc(captured.PixelDataBgra32, System.Runtime.InteropServices.GCHandleType.Pinned); + try + { + skBitmap.InstallPixels(info, handle.AddrOfPinnedObject(), captured.Stride); + + var (skFormat, quality) = format.ToUpperInvariant() switch + { + // Default JPEG quality (75) visibly smears text in screenshots; 90 keeps UI + // text legible at a still-reasonable file size — matches the WPF build's choice. + "JPG" or "JPEG" => (SKEncodedImageFormat.Jpeg, 90), + "BMP" => (SKEncodedImageFormat.Bmp, 100), + "GIF" => (SKEncodedImageFormat.Gif, 100), + _ => (SKEncodedImageFormat.Png, 100) + }; + + var directory = Path.GetDirectoryName(filePath); + if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) + { + Directory.CreateDirectory(directory); + } + + using var data = skBitmap.Encode(skFormat, quality); + using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); + data.SaveTo(fileStream); + } + finally + { + handle.Free(); + } + } + catch (UnauthorizedAccessException ex) + { + Logger.Error("Access denied when saving file", ex); + throw new InvalidOperationException("Access denied. Check file permissions.", ex); + } + catch (Exception ex) when (ex is not InvalidOperationException) + { + Logger.Error("Error saving file", ex); + throw new InvalidOperationException($"Failed to save image to file: {ex.Message}", ex); + } + } + + public string GenerateFileName(string format = "PNG") + { + var timestamp = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss"); + return $"Screenshot_{timestamp}.{format.ToLowerInvariant()}"; + } + + public void SaveImage(Bitmap image, SaveDestination destination, string? filePath = null, string format = "PNG") + { + switch (destination) + { + case SaveDestination.Clipboard: + SaveToClipboard(image); + break; + case SaveDestination.File: + if (filePath != null) + SaveToFile(image, filePath, format); + break; + case SaveDestination.Both: + SaveToClipboard(image); + if (filePath != null) + SaveToFile(image, filePath, format); + break; + } + } + + /// + /// Validates file path to prevent path traversal and other security issues. Copied verbatim + /// from the WPF SaveService — pure path logic, no UI-framework dependency. + /// + private void ValidateFilePath(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + { + throw new ArgumentException("File path cannot be empty.", nameof(filePath)); + } + + try + { + var fullPath = Path.GetFullPath(filePath); + + if (!Path.IsPathRooted(fullPath)) + { + throw new ArgumentException("Path must be absolute.", nameof(filePath)); + } + + var directory = Path.GetDirectoryName(fullPath); + + var systemDirs = new[] + { + Environment.GetFolderPath(Environment.SpecialFolder.System), + Environment.GetFolderPath(Environment.SpecialFolder.Windows), + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + }; + + foreach (var sysDir in systemDirs) + { + if (string.IsNullOrEmpty(sysDir) || string.IsNullOrEmpty(directory)) + { + continue; + } + + var sysDirWithSeparator = Path.TrimEndingDirectorySeparator(sysDir) + Path.DirectorySeparatorChar; + var directoryWithSeparator = Path.TrimEndingDirectorySeparator(directory) + Path.DirectorySeparatorChar; + if (directoryWithSeparator.StartsWith(sysDirWithSeparator, StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("Cannot save to system directories.", nameof(filePath)); + } + } + + if (Path.GetFileName(fullPath) == string.Empty) + { + throw new ArgumentException("Cannot save to a directory. Please specify a file name.", nameof(filePath)); + } + } + catch (ArgumentException) + { + throw; + } + catch (NotSupportedException ex) + { + throw new ArgumentException("Path format not supported.", nameof(filePath), ex); + } + catch (PathTooLongException ex) + { + throw new ArgumentException("Path is too long.", nameof(filePath), ex); + } + catch (Exception ex) + { + throw new ArgumentException("Invalid file path.", nameof(filePath), ex); + } + } +} diff --git a/MoneyShot.UI/Themes/CocoaTheme.axaml b/MoneyShot.UI/Themes/CocoaTheme.axaml new file mode 100644 index 0000000..9c6df8e --- /dev/null +++ b/MoneyShot.UI/Themes/CocoaTheme.axaml @@ -0,0 +1,422 @@ + + + + + + #221A13 + #2A2018 + #2E241A + #3A2D20 + #46382A + #534333 + #4C3C2B + #3A2E22 + #C28E5C + #D2A06E + #AD7C4D + #403122 + #271C11 + #F1E9DE + #C8B69E + #97846C + #C75048 + #191209 + + + + + + + + + + + + + + + + + + + + + + + M5,2 L5,15 L8.2,12.2 L10.4,17 L12.6,16 L10.4,11.4 L14.6,11.4 Z + M5.5,1.5 V14.5 H18.5 M1.5,5.5 H14.5 V18.5 + M2.5,4.5 H17.5 V15.5 H2.5 Z + M10,4.5 A7.5,5.5 0 1 0 10,15.5 A7.5,5.5 0 1 0 10,4.5 Z + M4,16 L15,5 M15,5 H9 M15,5 V11 + M3.5,16.5 L16.5,3.5 + M3,15 C5,7 7,17 10,10 C12,5.5 14,8 17,4.5 + M7.5,3.5 L6,16.5 M13.5,3.5 L12,16.5 M4,7.5 H16.5 M3.5,12.5 H16 + M4,5.5 V3.5 H16 V5.5 M10,3.5 V16.5 M8,16.5 H12 + M3,3 H8 V8 H3 Z M8,8 H13 V13 H8 Z M13,3 H18 V8 H13 Z M3,13 H8 V18 H3 Z M13,13 H18 V18 H13 Z + M4,8 H12.5 A4.5,4.5 0 0 1 12.5,17 H7 M7.5,4.5 L4,8 L7.5,11.5 + M16.5,10 A6.5,6.5 0 1 1 13.2,4.35 M13.2,1.2 V4.7 H16.7 + M8.5,3 A5.5,5.5 0 1 0 8.5,14 A5.5,5.5 0 1 0 8.5,3 M12.7,12.7 L17,17 M8.5,6 V11 M6,8.5 H11 + M8.5,3 A5.5,5.5 0 1 0 8.5,14 A5.5,5.5 0 1 0 8.5,3 M12.7,12.7 L17,17 M6,8.5 H11 + M8.5,3 A5.5,5.5 0 1 0 8.5,14 A5.5,5.5 0 1 0 8.5,3 M12.7,12.7 L17,17 + M3.5,3.5 H13.5 L16.5,6.5 V16.5 H3.5 Z M6.5,3.5 V7.5 H12.5 V3.5 M5.5,16.5 V11.5 H14.5 V16.5 + M7.5,5.5 V2.5 H17.5 V12.5 H14.5 M2.5,5.5 H12.5 V17.5 H2.5 Z + M3.5,6.5 H6.5 L8,4.5 H12 L13.5,6.5 H16.5 V15.5 H3.5 Z M10,8.5 A2.6,2.6 0 1 0 10,13.7 A2.6,2.6 0 1 0 10,8.5 + M3.5,6.5 V3.5 H6.5 M13.5,3.5 H16.5 V6.5 M16.5,13.5 V16.5 H13.5 M6.5,16.5 H3.5 V13.5 + M2.5,3.5 H17.5 V13.5 H2.5 Z M7,16.5 H13 M10,13.5 V16.5 + M10,3 A7,7 0 1 0 10,17 A7,7 0 1 0 10,3 M10,6 V10 L13,12 + M2.5,4.5 H8 L9.5,6.5 H17.5 V15.5 H2.5 Z + M3,5.5 H17 M3,10 H17 M3,14.5 H17 M7,3.5 V7.5 M13,8 V12 M5.5,12.5 V16.5 + M10,3 A7,7 0 1 0 10,17 A7,7 0 1 0 10,3 M10,9 V13.5 M10,6.4 V6.9 + M6.5,7 A3.5,3.5 0 1 1 10,10.5 V12.5 M10,15.4 V15.9 + + + M0,5 H10 + M0.5,0.5 H9.5 V9.5 H0.5 Z + M2.5,2.5 V0.5 H9.5 V7.5 H7.5 M0.5,2.5 H7.5 V9.5 H0.5 Z + M0.5,0.5 L9.5,9.5 M9.5,0.5 L0.5,9.5 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #66C28E5C + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + #4C3C2B + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MoneyShot.UI/Views/EditorWindow.axaml b/MoneyShot.UI/Views/EditorWindow.axaml new file mode 100644 index 0000000..22aa34b --- /dev/null +++ b/MoneyShot.UI/Views/EditorWindow.axaml @@ -0,0 +1,319 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MoneyShot.UI/Views/EditorWindow.axaml.cs b/MoneyShot.UI/Views/EditorWindow.axaml.cs new file mode 100644 index 0000000..f801418 --- /dev/null +++ b/MoneyShot.UI/Views/EditorWindow.axaml.cs @@ -0,0 +1,1943 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Collections; +using Avalonia.Controls; +using Avalonia.Controls.Primitives; +using Avalonia.Controls.Shapes; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Layout; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using Avalonia.Platform.Storage; +using Avalonia.Threading; +using MoneyShot.Models; +using MoneyShot.Platform.Windows; +using MoneyShot.UI.Editor; +using MoneyShot.UI.Interop; +using MoneyShot.UI.Services; +using Logger = MoneyShot.Services.Logger; + +namespace MoneyShot.UI.Views; + +/// +/// Avalonia port of MoneyShot/Views/EditorWindow.xaml.cs — see LINUX_PORT.md Phase 1. This is the +/// single highest-risk file in the port: the largest, most stateful piece of mouse-interaction +/// code in the app (see CLAUDE.md's "Resize/drag — design notes", which documents multiple past +/// regressions in the WPF version's equivalent logic). The structure and every rule from that +/// section is preserved exactly; only the framework APIs differ (Avalonia's unified Pointer +/// events instead of separate Mouse events, Geometry.FillContains/StrokeContains instead of +/// WPF's, async StorageProvider/dialogs instead of blocking SaveFileDialog/MessageBox). This has +/// been verified to compile and launch, NOT exhaustively verified interactively across every +/// tool/resize/undo/crop/zoom combination — see the verification notes wherever this is reported +/// back to the user. +/// +public partial class EditorWindow : Window +{ + private Bitmap _originalImage; + private AnnotationTool _currentTool = AnnotationTool.None; + private Color _currentColor = Colors.Red; + private Color _currentTextBackgroundColor = Colors.Transparent; + private int _lineThickness = 3; + private Point _startPoint; + private Shape? _currentShape; + private bool _isDrawing; + private readonly SaveService _saveService; + private readonly UndoController _undo = new(); + private int _numberCounter = 1; + + private Control? _selectedElement; + private Point _dragStartPoint; + private bool _isDragging; + private Border? _selectionBorder; + private double _zoomLevel = 1.0; + private const double ZoomIncrement = 0.25; + private const double MinZoom = 0.25; + private const double MaxZoom = 4.0; + + private const string PixelateTag = "pixelate"; + private const string NumberLabelTag = "numberLabel"; + + private bool _isResizing; + private ElementResizeMode _resizeMode = ElementResizeMode.None; + private Point _resizeStartPoint; + private double _originalWidth; + private double _originalHeight; + private double _originalLeft; + private double _originalTop; + private double _originalTextFontSize; + private ElementState? _resizeStartState; + private readonly List _resizeHandles = new(); + private bool _isEndpointResizing; + private bool _isResizingEndpointStart; + private Point _originalEndpointStart; + private Point _originalEndpointEnd; + + private const int FreehandMinDistance = 2; + private const double ShapeUpdateMinDistancePixels = 1.5; + private const double MinResizeDimension = 10; + private const double MinTextScaleFactor = 0.5; + private const double MinTextFontSize = 8; + private const double HandleVisualSize = 12; + private const double HandleHitZoneSize = 24; + + private Rectangle? _cropRectangle; + private bool _isCropping; + + private Polyline? _currentPolyline; + private Point _lastDrawPoint; + + private static readonly IPen HitTestPen = new Pen(Brushes.Black, 10); + private static readonly SolidColorBrush SelectionBrush = new(Color.FromRgb(0xE8, 0xA8, 0x5C)); + + private bool _isPanning; + private Point _panStartPoint; + private double _panStartTranslateX; + private double _panStartTranslateY; + private Cursor? _savedCursorBeforePan; + + private readonly ScaleTransform ZoomTransform = new() { ScaleX = 1, ScaleY = 1 }; + private readonly TranslateTransform PanTransform = new(); + + public EditorWindow(Bitmap image) + { + InitializeComponent(); + ImageCanvas.RenderTransform = new TransformGroup { Children = { ZoomTransform, PanTransform } }; + _originalImage = image; + _saveService = new SaveService(new Win32Clipboard()); + DisplayImage(); + + KeyDown += EditorWindow_KeyDown; + + AddHandler(PointerWheelChangedEvent, EditorWindow_PointerWheelChanged, RoutingStrategies.Tunnel); + AddHandler(PointerPressedEvent, EditorWindow_PreviewPointerPressed_Pan, RoutingStrategies.Tunnel); + AddHandler(PointerMovedEvent, EditorWindow_PreviewPointerMoved_Pan, RoutingStrategies.Tunnel); + AddHandler(PointerReleasedEvent, EditorWindow_PreviewPointerReleased_Pan, RoutingStrategies.Tunnel); + + Closed += EditorWindow_Closed; + } + + private void EditorWindow_Closed(object? sender, EventArgs e) + { + try + { + KeyDown -= EditorWindow_KeyDown; + + DrawingCanvas.Children.Clear(); + _resizeHandles.Clear(); + _selectionBorder = null; + _selectedElement = null; + _currentShape = null; + _currentPolyline = null; + _cropRectangle = null; + _undo.Clear(); + + if (ImageDisplay != null) + { + ImageDisplay.Source = null; + } + } + catch (Exception ex) + { + Logger.Warn("Editor teardown encountered a non-fatal error", ex); + } + } + + private void EditorWindow_KeyDown(object? sender, KeyEventArgs e) + { + if (ShortcutsOverlay != null && ShortcutsOverlay.IsVisible) + { + ShortcutsOverlay.IsVisible = false; + e.Handled = true; + return; + } + + if (e.Key == Key.OemQuestion && e.KeyModifiers.HasFlag(KeyModifiers.Shift)) + { + ToggleShortcutsOverlay(); + e.Handled = true; + return; + } + + if (!e.KeyModifiers.HasFlag(KeyModifiers.Control) && !e.KeyModifiers.HasFlag(KeyModifiers.Alt)) + { + switch (e.Key) + { + case Key.R: + SelectTool(AnnotationTool.Rectangle); + e.Handled = true; + break; + case Key.C: + SelectTool(AnnotationTool.Circle); + e.Handled = true; + break; + case Key.A: + SelectTool(AnnotationTool.Arrow); + e.Handled = true; + break; + case Key.L: + SelectTool(AnnotationTool.Line); + e.Handled = true; + break; + case Key.F: + SelectTool(AnnotationTool.Freehand); + e.Handled = true; + break; + case Key.T: + SelectTool(AnnotationTool.Text); + e.Handled = true; + break; + case Key.P: + SelectTool(AnnotationTool.Blur); + e.Handled = true; + break; + case Key.D1: + case Key.NumPad1: + SelectTool(AnnotationTool.Number); + e.Handled = true; + break; + case Key.Escape: + Close(); + e.Handled = true; + break; + case Key.Delete: + if (_selectedElement != null) + { + DeleteSelectedElement(); + e.Handled = true; + } + break; + } + } + + if (e.KeyModifiers.HasFlag(KeyModifiers.Control)) + { + switch (e.Key) + { + case Key.Z: + Undo_Click(this, new RoutedEventArgs()); + e.Handled = true; + break; + case Key.C: + SaveToClipboard_Click(this, new RoutedEventArgs()); + e.Handled = true; + break; + case Key.S: + Save_Click(this, new RoutedEventArgs()); + e.Handled = true; + break; + case Key.OemPlus: + case Key.Add: + ZoomIn_Click(this, new RoutedEventArgs()); + e.Handled = true; + break; + case Key.OemMinus: + case Key.Subtract: + ZoomOut_Click(this, new RoutedEventArgs()); + e.Handled = true; + break; + case Key.D0: + case Key.NumPad0: + ZoomReset_Click(this, new RoutedEventArgs()); + e.Handled = true; + break; + } + } + } + + private void EditorWindow_PointerWheelChanged(object? sender, PointerWheelEventArgs e) + { + if (e.KeyModifiers == KeyModifiers.Control) + { + if (e.Delta.Y > 0) + { + if (_zoomLevel < MaxZoom) { _zoomLevel += ZoomIncrement; ApplyZoom(); } + } + else + { + if (_zoomLevel > MinZoom) { _zoomLevel -= ZoomIncrement; ApplyZoom(); } + } + e.Handled = true; + } + } + + private void EditorWindow_PreviewPointerPressed_Pan(object? sender, PointerPressedEventArgs e) + { + if (e.GetCurrentPoint(this).Properties.PointerUpdateKind != PointerUpdateKind.MiddleButtonPressed) return; + + _isPanning = true; + _panStartPoint = e.GetPosition(this); + _panStartTranslateX = PanTransform.X; + _panStartTranslateY = PanTransform.Y; + _savedCursorBeforePan = Cursor; + Cursor = new Cursor(StandardCursorType.SizeAll); + e.Pointer.Capture(this); + e.Handled = true; + } + + private void EditorWindow_PreviewPointerMoved_Pan(object? sender, PointerEventArgs e) + { + if (!_isPanning) return; + + var current = e.GetPosition(this); + PanTransform.X = _panStartTranslateX + (current.X - _panStartPoint.X); + PanTransform.Y = _panStartTranslateY + (current.Y - _panStartPoint.Y); + e.Handled = true; + } + + private void EditorWindow_PreviewPointerReleased_Pan(object? sender, PointerReleasedEventArgs e) + { + if (!_isPanning) return; + + _isPanning = false; + e.Pointer.Capture(null); + Cursor = _savedCursorBeforePan; + _savedCursorBeforePan = null; + e.Handled = true; + } + + private void DeleteSelectedElement() + { + if (_selectedElement != null) + { + var element = _selectedElement; + var index = DrawingCanvas.Children.IndexOf(element); + _undo.Push(new UndoController.RemoveElementUndoAction(element, index)); + DrawingCanvas.Children.Remove(element); + ClearSelection(); + SyncNumberCounterAfterRemoval(element); + } + } + + private void SyncNumberCounterAfterRemoval(Control element) + { + if (element is TextBlock { Tag: NumberLabelTag }) + { + _numberCounter = Math.Min(_numberCounter, HighestNumberLabelOnCanvas() + 1); + } + } + + private void SyncNumberCounterAfterRestore(Control element) + { + if (element is TextBlock { Tag: NumberLabelTag }) + { + _numberCounter = Math.Max(_numberCounter, HighestNumberLabelOnCanvas() + 1); + } + } + + private int HighestNumberLabelOnCanvas() + { + var max = 0; + foreach (var child in DrawingCanvas.Children) + { + if (child is TextBlock { Tag: NumberLabelTag } label && + int.TryParse(label.Text, out var value) && value > max) + { + max = value; + } + } + return max; + } + + internal void UndoAddElement(Control element) + { + DrawingCanvas.Children.Remove(element); + if (_selectedElement == element) + { + ClearSelection(); + } + SyncNumberCounterAfterRemoval(element); + } + + internal void UndoRemoveElement(Control element, int index) + { + if (DrawingCanvas.Children.Contains(element)) return; + var targetIndex = Math.Max(0, Math.Min(index, DrawingCanvas.Children.Count)); + DrawingCanvas.Children.Insert(targetIndex, element); + SyncNumberCounterAfterRestore(element); + } + + internal void UndoCrop(Bitmap previousImage, IReadOnlyList previousElements, int previousNumberCounter) + { + _originalImage = previousImage; + DisplayImage(); + DrawingCanvas.Children.Clear(); + foreach (var element in previousElements) + { + DrawingCanvas.Children.Add(element); + } + _cropRectangle = null; + _isCropping = false; + _numberCounter = previousNumberCounter; + SelectTool(AnnotationTool.Cursor); + ClearSelection(); + } + + internal void UndoResize(Control element, ElementState previousState) + { + ApplyElementState(element, previousState); + } + + private void DisplayImage() + { + ImageDisplay.Source = _originalImage; + ImageDisplay.Width = _originalImage.PixelSize.Width; + ImageDisplay.Height = _originalImage.PixelSize.Height; + + DrawingCanvas.Width = _originalImage.PixelSize.Width; + DrawingCanvas.Height = _originalImage.PixelSize.Height; + } + + private Point ClampToCanvasBounds(Point point) + { + var clampedX = Math.Max(0, Math.Min(point.X, DrawingCanvas.Width)); + var clampedY = Math.Max(0, Math.Min(point.Y, DrawingCanvas.Height)); + return new Point(clampedX, clampedY); + } + + private static bool AreElementStatesEqual(ElementState first, ElementState second) + { + const double epsilon = 0.01; + var fontSizeEqual = (!first.FontSize.HasValue && !second.FontSize.HasValue) || + (first.FontSize.HasValue && second.FontSize.HasValue && + Math.Abs(first.FontSize.Value - second.FontSize.Value) < epsilon); + + return Math.Abs(first.Left - second.Left) < epsilon && + Math.Abs(first.Top - second.Top) < epsilon && + Math.Abs(first.Width - second.Width) < epsilon && + Math.Abs(first.Height - second.Height) < epsilon && + fontSizeEqual; + } + + private static ElementState? CaptureElementState(Control element) + { + if (element is Shape shape && element is not Line && element is not Avalonia.Controls.Shapes.Path) + { + return new ElementState(CanvasPosition.GetLeft(shape), CanvasPosition.GetTop(shape), shape.Width, shape.Height, null); + } + + if (element is TextBlock textBlock) + { + textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + var width = textBlock.Bounds.Width > 0 ? textBlock.Bounds.Width : textBlock.DesiredSize.Width; + var height = textBlock.Bounds.Height > 0 ? textBlock.Bounds.Height : textBlock.DesiredSize.Height; + return new ElementState(CanvasPosition.GetLeft(textBlock), CanvasPosition.GetTop(textBlock), width, height, textBlock.FontSize); + } + + return null; + } + + private void ApplyElementState(Control element, ElementState state) + { + if (element is Shape shape && element is not Line) + { + shape.Width = state.Width; + shape.Height = state.Height; + Canvas.SetLeft(shape, state.Left); + Canvas.SetTop(shape, state.Top); + } + else if (element is TextBlock textBlock) + { + if (state.FontSize.HasValue) + { + textBlock.FontSize = state.FontSize.Value; + } + Canvas.SetLeft(textBlock, state.Left); + Canvas.SetTop(textBlock, state.Top); + textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + } + else + { + return; + } + + if (_selectedElement == element && _selectionBorder != null) + { + Canvas.SetLeft(_selectionBorder, state.Left - 2); + Canvas.SetTop(_selectionBorder, state.Top - 2); + _selectionBorder.Width = state.Width + 4; + _selectionBorder.Height = state.Height + 4; + UpdateResizeHandles(state.Left, state.Top, state.Width, state.Height); + } + } + + private void Canvas_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if (!e.GetCurrentPoint(DrawingCanvas).Properties.IsLeftButtonPressed) + return; + + var rawPoint = e.GetPosition(DrawingCanvas); + var clickPoint = _currentTool == AnnotationTool.Cursor + ? rawPoint + : ClampToCanvasBounds(rawPoint); + + if (_currentTool == AnnotationTool.Cursor) + { + var hitElement = FindElementAtPoint(rawPoint); + + if (hitElement != null) + { + SelectElement(hitElement); + _isDragging = true; + _dragStartPoint = rawPoint; + e.Pointer.Capture(DrawingCanvas); + } + else + { + ClearSelection(); + } + return; + } + + if (_currentTool == AnnotationTool.Crop) + { + _isCropping = true; + _startPoint = clickPoint; + + if (_cropRectangle != null) + { + DrawingCanvas.Children.Remove(_cropRectangle); + } + + _cropRectangle = new Rectangle + { + Stroke = new SolidColorBrush(Colors.Yellow), + StrokeThickness = 2, + StrokeDashArray = new AvaloniaList(new[] { 4.0, 2.0 }), + Fill = new SolidColorBrush(Color.FromArgb(50, 255, 255, 0)) + }; + + DrawingCanvas.Children.Add(_cropRectangle); + e.Pointer.Capture(DrawingCanvas); + return; + } + + if (_currentTool == AnnotationTool.None) + return; + + if (_currentTool == AnnotationTool.Text) + { + _ = HandleTextToolAsync(); + return; + } + + _isDrawing = true; + _startPoint = clickPoint; + _lastDrawPoint = clickPoint; + e.Pointer.Capture(DrawingCanvas); + + Control? element = _currentTool switch + { + AnnotationTool.Rectangle => CreateRectangle(), + AnnotationTool.Circle => CreateEllipse(), + AnnotationTool.Arrow => CreateArrow(), + AnnotationTool.Line => CreateLine(), + AnnotationTool.Freehand => CreatePolyline(), + AnnotationTool.Number => CreateNumberLabel(), + AnnotationTool.Blur => CreateBlurRectangle(), + _ => null + }; + + if (element != null) + { + DrawingCanvas.Children.Add(element); + if (element is Shape shape) + { + _currentShape = shape; + } + else + { + _undo.Push(new UndoController.AddElementUndoAction(element)); + } + } + } + + private async Task HandleTextToolAsync() + { + var textBlock = await CreateTextLabelAsync(); + if (textBlock != null) + { + DrawingCanvas.Children.Add(textBlock); + _undo.Push(new UndoController.AddElementUndoAction(textBlock)); + } + } + + private void Canvas_PointerMoved(object? sender, PointerEventArgs e) + { + var rawPoint = e.GetPosition(DrawingCanvas); + var currentPoint = ClampToCanvasBounds(rawPoint); + + if (_currentTool == AnnotationTool.Cursor && _isResizing && _selectedElement != null) + { + ResizeElement(_selectedElement, rawPoint); + return; + } + + if (_currentTool == AnnotationTool.Cursor && _isEndpointResizing && _selectedElement != null) + { + ApplyEndpointResize(_selectedElement, rawPoint); + return; + } + + if (_currentTool == AnnotationTool.Cursor && _isDragging && _selectedElement != null) + { + var deltaX = rawPoint.X - _dragStartPoint.X; + var deltaY = rawPoint.Y - _dragStartPoint.Y; + + MoveElement(_selectedElement, deltaX, deltaY); + _dragStartPoint = rawPoint; + return; + } + + if (_currentTool == AnnotationTool.Crop && _isCropping && _cropRectangle != null) + { + var x = Math.Min(_startPoint.X, currentPoint.X); + var y = Math.Min(_startPoint.Y, currentPoint.Y); + var width = Math.Abs(_startPoint.X - currentPoint.X); + var height = Math.Abs(_startPoint.Y - currentPoint.Y); + + Canvas.SetLeft(_cropRectangle, x); + Canvas.SetTop(_cropRectangle, y); + _cropRectangle.Width = width; + _cropRectangle.Height = height; + return; + } + + if (!_isDrawing || _currentShape == null) + return; + + if (_currentTool != AnnotationTool.Freehand) + { + var dx = currentPoint.X - _lastDrawPoint.X; + var dy = currentPoint.Y - _lastDrawPoint.Y; + if ((dx * dx) + (dy * dy) < ShapeUpdateMinDistancePixels * ShapeUpdateMinDistancePixels) + { + return; + } + } + + switch (_currentTool) + { + case AnnotationTool.Rectangle: + case AnnotationTool.Blur: + UpdateRectangle(currentPoint); + break; + case AnnotationTool.Circle: + UpdateEllipse(currentPoint); + break; + case AnnotationTool.Line: + UpdateLine(currentPoint); + break; + case AnnotationTool.Arrow: + UpdateArrow(currentPoint); + break; + case AnnotationTool.Freehand: + UpdatePolyline(currentPoint); + break; + } + + _lastDrawPoint = currentPoint; + } + + private async void Canvas_PointerReleased(object? sender, PointerReleasedEventArgs e) + { + e.Pointer.Capture(null); + + if (_currentTool == AnnotationTool.Cursor) + { + if (_isResizing && _selectedElement != null && _resizeStartState != null) + { + var resizeEndState = CaptureElementState(_selectedElement); + if (resizeEndState != null && !AreElementStatesEqual(_resizeStartState, resizeEndState)) + { + _undo.Push(new UndoController.ResizeUndoAction(_selectedElement, _resizeStartState)); + } + } + else if (_isEndpointResizing && _selectedElement != null) + { + var element = _selectedElement; + ClearSelection(); + SelectElement(element); + } + + _isDragging = false; + _isResizing = false; + _isEndpointResizing = false; + _resizeMode = ElementResizeMode.None; + _resizeStartState = null; + return; + } + + if (_currentTool == AnnotationTool.Crop && _isCropping) + { + _isCropping = false; + if (_cropRectangle != null && _cropRectangle.Width > 10 && _cropRectangle.Height > 10) + { + var result = await SimpleMessageBox.ShowAsync(this, + "Apply crop to image? This will remove all annotations and crop the image.", + "Confirm Crop", SimpleMessageBoxButtons.YesNo); + + if (result == SimpleMessageBoxResult.Yes) + { + ApplyCrop(); + } + else + { + DrawingCanvas.Children.Remove(_cropRectangle); + _cropRectangle = null; + } + } + return; + } + + if (_isDrawing && _currentShape != null) + { + if (_currentTool == AnnotationTool.Blur && _currentShape is Rectangle pixelateRect) + { + if (pixelateRect.Width > 5 && pixelateRect.Height > 5) + { + pixelateRect.Fill = CanvasRenderer.CreatePixelatedBrush(pixelateRect, _originalImage); + } + } + _undo.Push(new UndoController.AddElementUndoAction(_currentShape)); + } + + if (_isDrawing && _currentPolyline != null) + { + _undo.Push(new UndoController.AddElementUndoAction(_currentPolyline)); + _currentPolyline = null; + } + + _isDrawing = false; + _currentShape = null; + } + + private Rectangle CreateRectangle() + { + var rect = new Rectangle + { + Stroke = new SolidColorBrush(_currentColor), + StrokeThickness = _lineThickness, + Fill = Brushes.Transparent, + Width = 0, + Height = 0 + }; + Canvas.SetLeft(rect, _startPoint.X); + Canvas.SetTop(rect, _startPoint.Y); + return rect; + } + + private Ellipse CreateEllipse() + { + var ellipse = new Ellipse + { + Stroke = new SolidColorBrush(_currentColor), + StrokeThickness = _lineThickness, + Fill = Brushes.Transparent, + Width = 0, + Height = 0 + }; + Canvas.SetLeft(ellipse, _startPoint.X); + Canvas.SetTop(ellipse, _startPoint.Y); + return ellipse; + } + + private Line CreateLine() + { + return new Line + { + Stroke = new SolidColorBrush(_currentColor), + StrokeThickness = _lineThickness, + StartPoint = _startPoint, + EndPoint = _startPoint + }; + } + + private Avalonia.Controls.Shapes.Path CreateArrow() + { + return new Avalonia.Controls.Shapes.Path + { + Stroke = new SolidColorBrush(_currentColor), + StrokeThickness = _lineThickness, + Fill = new SolidColorBrush(_currentColor) + }; + } + + private Polyline CreatePolyline() + { + var polyline = new Polyline + { + Stroke = new SolidColorBrush(_currentColor), + StrokeThickness = _lineThickness, + StrokeLineCap = PenLineCap.Round, + StrokeJoin = PenLineJoin.Round, + }; + polyline.Points.Add(_startPoint); + _currentPolyline = polyline; + return polyline; + } + + private TextBlock CreateNumberLabel() + { + var textBlock = new TextBlock + { + Text = _numberCounter.ToString(), + FontSize = 20, + FontWeight = FontWeight.Bold, + Foreground = new SolidColorBrush(_currentColor), + Background = new SolidColorBrush(Colors.White), + Padding = new Thickness(5), + Tag = NumberLabelTag + }; + Canvas.SetLeft(textBlock, _startPoint.X); + Canvas.SetTop(textBlock, _startPoint.Y); + _numberCounter++; + _isDrawing = false; + return textBlock; + } + + private async Task CreateTextLabelAsync() + { + var resources = Avalonia.Application.Current!.Resources; + var inputDialog = new Window + { + Title = "Add text", + Width = 340, + SizeToContent = SizeToContent.Height, + CanResize = false, + WindowStartupLocation = WindowStartupLocation.CenterOwner, + Background = (IBrush)resources["Cocoa.WindowBrush"]!, + Foreground = (IBrush)resources["Cocoa.TextBrush"]! + }; + + var grid = new Grid { Margin = new Thickness(16) }; + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); + + var label = new TextBlock + { + Text = "Label text", + Foreground = (IBrush)resources["Cocoa.TextSecondaryBrush"]!, + Margin = new Thickness(0, 0, 0, 6) + }; + Grid.SetRow(label, 0); + grid.Children.Add(label); + + var textBox = new TextBox { Margin = new Thickness(0, 0, 0, 14) }; + Grid.SetRow(textBox, 1); + grid.Children.Add(textBox); + + var okButton = new Button + { + Content = "Add", + Theme = (Avalonia.Styling.ControlTheme)resources["AccentButton"]!, + MinWidth = 76, + IsDefault = true + }; + + var cancelButton = new Button + { + Content = "Cancel", + Theme = (Avalonia.Styling.ControlTheme)resources["SubtleButton"]!, + MinWidth = 76, + Margin = new Thickness(0, 0, 8, 0), + IsCancel = true + }; + + var buttonPanel = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right }; + buttonPanel.Children.Add(cancelButton); + buttonPanel.Children.Add(okButton); + Grid.SetRow(buttonPanel, 2); + grid.Children.Add(buttonPanel); + + inputDialog.Content = grid; + + okButton.Click += (_, _) => inputDialog.Close(true); + cancelButton.Click += (_, _) => inputDialog.Close(false); + inputDialog.Opened += (_, _) => textBox.Focus(); + + var confirmed = await inputDialog.ShowDialog(this); + + if (confirmed && !string.IsNullOrWhiteSpace(textBox.Text)) + { + var textBlock = new TextBlock + { + Text = textBox.Text, + FontSize = 16, + FontWeight = FontWeight.Normal, + Foreground = new SolidColorBrush(_currentColor), + Background = new SolidColorBrush(_currentTextBackgroundColor), + Padding = new Thickness(5) + }; + + Canvas.SetLeft(textBlock, _startPoint.X); + Canvas.SetTop(textBlock, _startPoint.Y); + _isDrawing = false; + return textBlock; + } + + _isDrawing = false; + return null; + } + + private Rectangle CreateBlurRectangle() + { + var rect = new Rectangle + { + Stroke = new SolidColorBrush(Colors.Transparent), + StrokeThickness = 0, + Fill = new SolidColorBrush(Color.FromArgb(128, 128, 128, 128)), + Tag = PixelateTag, + Width = 0, + Height = 0 + }; + Canvas.SetLeft(rect, _startPoint.X); + Canvas.SetTop(rect, _startPoint.Y); + return rect; + } + + private void UpdateRectangle(Point currentPoint) + { + if (_currentShape is not Rectangle rect) return; + + var x = Math.Min(_startPoint.X, currentPoint.X); + var y = Math.Min(_startPoint.Y, currentPoint.Y); + var width = Math.Abs(_startPoint.X - currentPoint.X); + var height = Math.Abs(_startPoint.Y - currentPoint.Y); + + Canvas.SetLeft(rect, x); + Canvas.SetTop(rect, y); + rect.Width = width; + rect.Height = height; + } + + private void UpdateEllipse(Point currentPoint) + { + if (_currentShape is not Ellipse ellipse) return; + + var x = Math.Min(_startPoint.X, currentPoint.X); + var y = Math.Min(_startPoint.Y, currentPoint.Y); + var width = Math.Abs(_startPoint.X - currentPoint.X); + var height = Math.Abs(_startPoint.Y - currentPoint.Y); + + Canvas.SetLeft(ellipse, x); + Canvas.SetTop(ellipse, y); + ellipse.Width = width; + ellipse.Height = height; + } + + private void UpdateLine(Point currentPoint) + { + if (_currentShape is Line line) + { + line.EndPoint = currentPoint; + } + } + + private void UpdatePolyline(Point currentPoint) + { + if (_currentPolyline != null && _currentPolyline.Points.Count > 0) + { + var lastPoint = _currentPolyline.Points[_currentPolyline.Points.Count - 1]; + var distance = Math.Sqrt(Math.Pow(currentPoint.X - lastPoint.X, 2) + Math.Pow(currentPoint.Y - lastPoint.Y, 2)); + + if (distance > FreehandMinDistance) + { + _currentPolyline.Points.Add(currentPoint); + } + } + } + + private void UpdateArrow(Point currentPoint) + { + if (_currentShape is not Avalonia.Controls.Shapes.Path arrow) return; + + var dx = currentPoint.X - _startPoint.X; + var dy = currentPoint.Y - _startPoint.Y; + var angle = Math.Atan2(dy, dx); + var length = Math.Sqrt(dx * dx + dy * dy); + + var geometry = new PathGeometry(); + var figure = new PathFigure { StartPoint = _startPoint, IsClosed = false }; + + figure.Segments!.Add(new LineSegment { Point = currentPoint }); + + var arrowHeadLength = Math.Min(20, length / 3); + var arrowHeadAngle = Math.PI / 6; + + var leftPoint = new Point( + currentPoint.X - arrowHeadLength * Math.Cos(angle - arrowHeadAngle), + currentPoint.Y - arrowHeadLength * Math.Sin(angle - arrowHeadAngle) + ); + var rightPoint = new Point( + currentPoint.X - arrowHeadLength * Math.Cos(angle + arrowHeadAngle), + currentPoint.Y - arrowHeadLength * Math.Sin(angle + arrowHeadAngle) + ); + + figure.Segments.Add(new LineSegment { Point = leftPoint }); + figure.Segments.Add(new LineSegment { Point = currentPoint }); + figure.Segments.Add(new LineSegment { Point = rightPoint }); + figure.Segments.Add(new LineSegment { Point = currentPoint }); + + geometry.Figures!.Add(figure); + arrow.Data = geometry; + } + + private Control? FindElementAtPoint(Point point) + { + for (int i = DrawingCanvas.Children.Count - 1; i >= 0; i--) + { + var element = DrawingCanvas.Children[i]; + + if (element == _selectionBorder || _resizeHandles.Contains(element)) + continue; + + if (IsPointInElement(element, point)) + { + return element; + } + } + return null; + } + + private bool IsPointInElement(Control element, Point point) + { + var left = CanvasPosition.GetLeft(element); + var top = CanvasPosition.GetTop(element); + + if (element is Avalonia.Controls.Shapes.Path path) + { + if (path.Data is PathGeometry pathGeometry) + { + var adjustedPoint = new Point(point.X - left, point.Y - top); + return pathGeometry.FillContains(adjustedPoint) || + pathGeometry.StrokeContains(HitTestPen, adjustedPoint); + } + return false; + } + else if (element is Shape shape && element is not Line) + { + var width = shape.Width; + var height = shape.Height; + + if (double.IsNaN(width) || double.IsNaN(height)) + return false; + + return point.X >= left && point.X <= left + width && + point.Y >= top && point.Y <= top + height; + } + else if (element is TextBlock textBlock) + { + var width = textBlock.Bounds.Width; + var height = textBlock.Bounds.Height; + + return point.X >= left && point.X <= left + width && + point.Y >= top && point.Y <= top + height; + } + else if (element is Line line) + { + var distance = DistanceFromPointToLine(point, line.StartPoint, line.EndPoint); + return distance < 10; + } + + return false; + } + + private double DistanceFromPointToLine(Point p, Point lineStart, Point lineEnd) + { + var dx = lineEnd.X - lineStart.X; + var dy = lineEnd.Y - lineStart.Y; + var lengthSquared = dx * dx + dy * dy; + + if (lengthSquared == 0) + return Math.Sqrt((p.X - lineStart.X) * (p.X - lineStart.X) + (p.Y - lineStart.Y) * (p.Y - lineStart.Y)); + + var t = Math.Max(0, Math.Min(1, ((p.X - lineStart.X) * dx + (p.Y - lineStart.Y) * dy) / lengthSquared)); + var projX = lineStart.X + t * dx; + var projY = lineStart.Y + t * dy; + + return Math.Sqrt((p.X - projX) * (p.X - projX) + (p.Y - projY) * (p.Y - projY)); + } + + private void SelectElement(Control element) + { + ClearSelection(); + _selectedElement = element; + + _selectionBorder = new Border + { + BorderBrush = SelectionBrush, + BorderThickness = new Thickness(2), + IsHitTestVisible = false + }; + + var left = CanvasPosition.GetLeft(element); + var top = CanvasPosition.GetTop(element); + double width = 0, height = 0; + + if (element is Avalonia.Controls.Shapes.Path path && path.Data is { } pathData) + { + var bounds = pathData.Bounds; + left += bounds.Left; + top += bounds.Top; + width = bounds.Width; + height = bounds.Height; + } + else if (element is Shape shape && element is not Line && element is not Avalonia.Controls.Shapes.Path) + { + width = shape.Width; + height = shape.Height; + } + else if (element is TextBlock textBlock) + { + width = textBlock.Bounds.Width; + height = textBlock.Bounds.Height; + } + else if (element is Line line) + { + left = Math.Min(line.StartPoint.X, line.EndPoint.X); + top = Math.Min(line.StartPoint.Y, line.EndPoint.Y); + width = Math.Abs(line.EndPoint.X - line.StartPoint.X); + height = Math.Abs(line.EndPoint.Y - line.StartPoint.Y); + } + + Canvas.SetLeft(_selectionBorder, left - 2); + Canvas.SetTop(_selectionBorder, top - 2); + _selectionBorder.Width = width + 4; + _selectionBorder.Height = height + 4; + + DrawingCanvas.Children.Add(_selectionBorder); + + if ((element is Shape && element is not Line && element is not Avalonia.Controls.Shapes.Path) || element is TextBlock) + { + CreateResizeHandles(left, top, width, height); + } + else if (element is Line lineEl) + { + CreateEndpointHandles(lineEl.StartPoint, lineEl.EndPoint); + } + else if (element is Avalonia.Controls.Shapes.Path arrowEl) + { + var (start, end) = TryGetArrowEndpoints(arrowEl); + if (start.HasValue && end.HasValue) + { + CreateEndpointHandles(start.Value, end.Value); + } + } + } + + private void CreateResizeHandles(double left, double top, double width, double height) + { + ClearResizeHandlesOnly(); + + var handleColor = SelectionBrush; + + _resizeHandles.Add(CreateResizeHandle(left - 2, top - 2, handleColor, ElementResizeMode.TopLeft)); + _resizeHandles.Add(CreateResizeHandle(left + width + 2, top - 2, handleColor, ElementResizeMode.TopRight)); + _resizeHandles.Add(CreateResizeHandle(left - 2, top + height + 2, handleColor, ElementResizeMode.BottomLeft)); + _resizeHandles.Add(CreateResizeHandle(left + width + 2, top + height + 2, handleColor, ElementResizeMode.BottomRight)); + _resizeHandles.Add(CreateResizeHandle(left + width / 2, top - 2, handleColor, ElementResizeMode.Top)); + _resizeHandles.Add(CreateResizeHandle(left + width / 2, top + height + 2, handleColor, ElementResizeMode.Bottom)); + _resizeHandles.Add(CreateResizeHandle(left - 2, top + height / 2, handleColor, ElementResizeMode.Left)); + _resizeHandles.Add(CreateResizeHandle(left + width + 2, top + height / 2, handleColor, ElementResizeMode.Right)); + } + + private void CreateEndpointHandles(Point start, Point end) + { + ClearResizeHandlesOnly(); + var handleColor = SelectionBrush; + var startHandle = CreateEndpointHandle(start, handleColor, isStart: true); + var endHandle = CreateEndpointHandle(end, handleColor, isStart: false); + _resizeHandles.Add(startHandle); + _resizeHandles.Add(endHandle); + } + + private void ClearResizeHandlesOnly() + { + foreach (var handle in _resizeHandles) + { + DrawingCanvas.Children.Remove(handle); + } + _resizeHandles.Clear(); + } + + private static void ShiftPathGeometry(PathGeometry geometry, double deltaX, double deltaY) + { + foreach (var figure in geometry.Figures!) + { + figure.StartPoint = new Point(figure.StartPoint.X + deltaX, figure.StartPoint.Y + deltaY); + foreach (var seg in figure.Segments!) + { + if (seg is LineSegment ls) + { + ls.Point = new Point(ls.Point.X + deltaX, ls.Point.Y + deltaY); + } + } + } + } + + private static (Point? start, Point? end) TryGetArrowEndpoints(Avalonia.Controls.Shapes.Path arrow) + { + if (arrow.Data is not PathGeometry geometry || geometry.Figures == null || geometry.Figures.Count == 0) return (null, null); + var figure = geometry.Figures[0]; + if (figure.Segments == null || figure.Segments.Count == 0 || figure.Segments[0] is not LineSegment line) return (null, null); + return (figure.StartPoint, line.Point); + } + + private void UpdateResizeHandles(double left, double top, double width, double height) + { + if (_resizeHandles.Count != 8) + { + CreateResizeHandles(left, top, width, height); + return; + } + + PositionHandle(_resizeHandles[0], left - 2, top - 2); + PositionHandle(_resizeHandles[1], left + width + 2, top - 2); + PositionHandle(_resizeHandles[2], left - 2, top + height + 2); + PositionHandle(_resizeHandles[3], left + width + 2, top + height + 2); + PositionHandle(_resizeHandles[4], left + width / 2, top - 2); + PositionHandle(_resizeHandles[5], left + width / 2, top + height + 2); + PositionHandle(_resizeHandles[6], left - 2, top + height / 2); + PositionHandle(_resizeHandles[7], left + width + 2, top + height / 2); + } + + private static void PositionHandle(Rectangle handle, double centerX, double centerY) + { + Canvas.SetLeft(handle, centerX - handle.Width / 2); + Canvas.SetTop(handle, centerY - handle.Height / 2); + } + + private static StandardCursorType GetResizeCursor(ElementResizeMode resizeMode) + { + return resizeMode switch + { + ElementResizeMode.TopLeft => StandardCursorType.TopLeftCorner, + ElementResizeMode.BottomRight => StandardCursorType.BottomRightCorner, + ElementResizeMode.TopRight => StandardCursorType.TopRightCorner, + ElementResizeMode.BottomLeft => StandardCursorType.BottomLeftCorner, + ElementResizeMode.Top => StandardCursorType.TopSide, + ElementResizeMode.Bottom => StandardCursorType.BottomSide, + ElementResizeMode.Left => StandardCursorType.LeftSide, + ElementResizeMode.Right => StandardCursorType.RightSide, + _ => StandardCursorType.SizeAll + }; + } + + private Rectangle CreateResizeHandle(double centerX, double centerY, SolidColorBrush color, ElementResizeMode resizeMode) + { + var handle = new Rectangle + { + Width = HandleHitZoneSize, + Height = HandleHitZoneSize, + Fill = Brushes.Transparent, + Cursor = new Cursor(GetResizeCursor(resizeMode)), + Tag = resizeMode + }; + var inset = (HandleHitZoneSize - HandleVisualSize) / 2; + var drawingGroup = new DrawingGroup(); + drawingGroup.Children.Add(new GeometryDrawing + { + Brush = color, + Pen = new Pen(Brushes.White, 1), + Geometry = new RectangleGeometry(new Rect(inset, inset, HandleVisualSize, HandleVisualSize)) + }); + handle.Fill = new DrawingBrush { Drawing = drawingGroup, Stretch = Stretch.None }; + + handle.PointerPressed += ResizeHandle_PointerPressed; + PositionHandle(handle, centerX, centerY); + DrawingCanvas.Children.Add(handle); + return handle; + } + + private Rectangle CreateEndpointHandle(Point center, SolidColorBrush color, bool isStart) + { + var handle = new Rectangle + { + Width = HandleHitZoneSize, + Height = HandleHitZoneSize, + Fill = Brushes.Transparent, + Cursor = new Cursor(StandardCursorType.Cross), + Tag = isStart ? EndpointTagStart : EndpointTagEnd + }; + var inset = (HandleHitZoneSize - HandleVisualSize) / 2; + var drawingGroup = new DrawingGroup(); + drawingGroup.Children.Add(new GeometryDrawing + { + Brush = color, + Pen = new Pen(Brushes.White, 1), + Geometry = new EllipseGeometry(new Rect(inset, inset, HandleVisualSize, HandleVisualSize)) + }); + handle.Fill = new DrawingBrush { Drawing = drawingGroup, Stretch = Stretch.None }; + handle.PointerPressed += EndpointHandle_PointerPressed; + PositionHandle(handle, center.X, center.Y); + DrawingCanvas.Children.Add(handle); + return handle; + } + + private const string EndpointTagStart = "endpoint:start"; + private const string EndpointTagEnd = "endpoint:end"; + + private void ResizeHandle_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if (sender is not Rectangle handle || handle.Tag is not ElementResizeMode mode) + return; + if (_selectedElement == null) + return; + + BeginResize(_selectedElement, mode, e.GetPosition(DrawingCanvas)); + e.Handled = true; + } + + private void EndpointHandle_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if (sender is not Rectangle handle || handle.Tag is not string tag) + return; + if (_selectedElement == null) + return; + + var isStart = tag == EndpointTagStart; + BeginEndpointResize(_selectedElement, isStart); + e.Handled = true; + e.Pointer.Capture(DrawingCanvas); + } + + private void BeginEndpointResize(Control element, bool isStart) + { + if (element is Line line) + { + _originalEndpointStart = line.StartPoint; + _originalEndpointEnd = line.EndPoint; + } + else if (element is Avalonia.Controls.Shapes.Path arrow) + { + var (start, end) = TryGetArrowEndpoints(arrow); + if (!start.HasValue || !end.HasValue) return; + _originalEndpointStart = start.Value; + _originalEndpointEnd = end.Value; + } + else + { + return; + } + + _isEndpointResizing = true; + _isResizingEndpointStart = isStart; + } + + private void BeginResize(Control element, ElementResizeMode mode, Point startPoint) + { + _isResizing = true; + _resizeMode = mode; + _resizeStartPoint = startPoint; + _resizeStartState = CaptureElementState(element); + + if (element is Shape shape && element is not Line && element is not Avalonia.Controls.Shapes.Path) + { + var width = shape.Width; + var height = shape.Height; + if (double.IsNaN(width) || width <= 0) width = shape.Bounds.Width; + if (double.IsNaN(height) || height <= 0) height = shape.Bounds.Height; + if (double.IsNaN(width) || width <= 0) width = MinResizeDimension; + if (double.IsNaN(height) || height <= 0) height = MinResizeDimension; + + _originalWidth = width; + _originalHeight = height; + _originalLeft = Canvas.GetLeft(shape); + _originalTop = Canvas.GetTop(shape); + if (double.IsNaN(_originalLeft)) _originalLeft = 0; + if (double.IsNaN(_originalTop)) _originalTop = 0; + } + else if (element is TextBlock textBlock) + { + textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + _originalWidth = textBlock.Bounds.Width > 0 ? textBlock.Bounds.Width : textBlock.DesiredSize.Width; + _originalHeight = textBlock.Bounds.Height > 0 ? textBlock.Bounds.Height : textBlock.DesiredSize.Height; + if (_originalWidth <= 0) _originalWidth = MinResizeDimension; + if (_originalHeight <= 0) _originalHeight = MinResizeDimension; + _originalLeft = Canvas.GetLeft(textBlock); + _originalTop = Canvas.GetTop(textBlock); + _originalTextFontSize = textBlock.FontSize; + if (double.IsNaN(_originalLeft)) _originalLeft = 0; + if (double.IsNaN(_originalTop)) _originalTop = 0; + } + else + { + _isResizing = false; + _resizeStartState = null; + return; + } + } + + private void ResizeElement(Control element, Point currentPoint) + { + var deltaX = currentPoint.X - _resizeStartPoint.X; + var deltaY = currentPoint.Y - _resizeStartPoint.Y; + + var newLeft = _originalLeft; + var newTop = _originalTop; + var newWidth = _originalWidth; + var newHeight = _originalHeight; + + switch (_resizeMode) + { + case ElementResizeMode.BottomRight: + newWidth = Math.Max(MinResizeDimension, _originalWidth + deltaX); + newHeight = Math.Max(MinResizeDimension, _originalHeight + deltaY); + break; + case ElementResizeMode.BottomLeft: + newWidth = Math.Max(MinResizeDimension, _originalWidth - deltaX); + newHeight = Math.Max(MinResizeDimension, _originalHeight + deltaY); + newLeft = _originalLeft + (_originalWidth - newWidth); + break; + case ElementResizeMode.TopRight: + newWidth = Math.Max(MinResizeDimension, _originalWidth + deltaX); + newHeight = Math.Max(MinResizeDimension, _originalHeight - deltaY); + newTop = _originalTop + (_originalHeight - newHeight); + break; + case ElementResizeMode.TopLeft: + newWidth = Math.Max(MinResizeDimension, _originalWidth - deltaX); + newHeight = Math.Max(MinResizeDimension, _originalHeight - deltaY); + newLeft = _originalLeft + (_originalWidth - newWidth); + newTop = _originalTop + (_originalHeight - newHeight); + break; + case ElementResizeMode.Right: + newWidth = Math.Max(MinResizeDimension, _originalWidth + deltaX); + break; + case ElementResizeMode.Left: + newWidth = Math.Max(MinResizeDimension, _originalWidth - deltaX); + newLeft = _originalLeft + (_originalWidth - newWidth); + break; + case ElementResizeMode.Bottom: + newHeight = Math.Max(MinResizeDimension, _originalHeight + deltaY); + break; + case ElementResizeMode.Top: + newHeight = Math.Max(MinResizeDimension, _originalHeight - deltaY); + newTop = _originalTop + (_originalHeight - newHeight); + break; + } + + if (element is Shape shape && element is not Line && element is not Avalonia.Controls.Shapes.Path) + { + shape.Width = newWidth; + shape.Height = newHeight; + Canvas.SetLeft(shape, newLeft); + Canvas.SetTop(shape, newTop); + } + else if (element is TextBlock textBlock) + { + var scale = _resizeMode switch + { + ElementResizeMode.Left or ElementResizeMode.Right => _originalWidth > 0 ? newWidth / _originalWidth : 1, + ElementResizeMode.Top or ElementResizeMode.Bottom => _originalHeight > 0 ? newHeight / _originalHeight : 1, + _ => Math.Min( + _originalWidth > 0 ? newWidth / _originalWidth : 1, + _originalHeight > 0 ? newHeight / _originalHeight : 1) + }; + scale = Math.Max(MinTextScaleFactor, scale); + textBlock.FontSize = Math.Max(MinTextFontSize, _originalTextFontSize * scale); + textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + Canvas.SetLeft(textBlock, newLeft); + Canvas.SetTop(textBlock, newTop); + newWidth = textBlock.DesiredSize.Width; + newHeight = textBlock.DesiredSize.Height; + } + else + { + return; + } + + if (_selectionBorder != null) + { + Canvas.SetLeft(_selectionBorder, newLeft - 2); + Canvas.SetTop(_selectionBorder, newTop - 2); + _selectionBorder.Width = newWidth + 4; + _selectionBorder.Height = newHeight + 4; + } + + UpdateResizeHandles(newLeft, newTop, newWidth, newHeight); + } + + private void ClearSelection() + { + if (_selectionBorder != null) + { + DrawingCanvas.Children.Remove(_selectionBorder); + _selectionBorder = null; + } + + ClearResizeHandlesOnly(); + _selectedElement = null; + } + + private void ApplyEndpointResize(Control element, Point newEndpoint) + { + var clamped = ClampToCanvasBounds(newEndpoint); + var start = _isResizingEndpointStart ? clamped : _originalEndpointStart; + var end = _isResizingEndpointStart ? _originalEndpointEnd : clamped; + + if (element is Line line) + { + line.StartPoint = start; + line.EndPoint = end; + } + else if (element is Avalonia.Controls.Shapes.Path arrow) + { + var savedShape = _currentShape; + var savedStart = _startPoint; + _currentShape = arrow; + _startPoint = start; + UpdateArrow(end); + _currentShape = savedShape; + _startPoint = savedStart; + } + + if (_resizeHandles.Count == 2) + { + var movingHandle = _isResizingEndpointStart ? _resizeHandles[0] : _resizeHandles[1]; + PositionHandle(movingHandle, clamped.X, clamped.Y); + } + } + + private void MoveElement(Control element, double deltaX, double deltaY) + { + if (element is Shape shape && element is not Line) + { + Canvas.SetLeft(shape, CanvasPosition.GetLeft(shape) + deltaX); + Canvas.SetTop(shape, CanvasPosition.GetTop(shape) + deltaY); + } + else if (element is TextBlock textBlock) + { + Canvas.SetLeft(textBlock, CanvasPosition.GetLeft(textBlock) + deltaX); + Canvas.SetTop(textBlock, CanvasPosition.GetTop(textBlock) + deltaY); + } + else if (element is Line line) + { + line.StartPoint = new Point(line.StartPoint.X + deltaX, line.StartPoint.Y + deltaY); + line.EndPoint = new Point(line.EndPoint.X + deltaX, line.EndPoint.Y + deltaY); + } + else if (element is Avalonia.Controls.Shapes.Path pathEl && pathEl.Data is PathGeometry geometry) + { + ShiftPathGeometry(geometry, deltaX, deltaY); + } + + if (_selectionBorder != null) + { + Canvas.SetLeft(_selectionBorder, CanvasPosition.GetLeft(_selectionBorder) + deltaX); + Canvas.SetTop(_selectionBorder, CanvasPosition.GetTop(_selectionBorder) + deltaY); + } + + if ((element is Shape && element is not Line && element is not Avalonia.Controls.Shapes.Path) || element is TextBlock) + { + var elementLeft = CanvasPosition.GetLeft(element); + var elementTop = CanvasPosition.GetTop(element); + + double elementWidth; + double elementHeight; + if (element is TextBlock textBlock2) + { + elementWidth = textBlock2.Bounds.Width; + elementHeight = textBlock2.Bounds.Height; + } + else if (element is Shape shapeElement) + { + elementWidth = shapeElement.Width; + elementHeight = shapeElement.Height; + } + else + { + return; + } + + if (elementWidth > 0 && elementHeight > 0) + { + UpdateResizeHandles(elementLeft, elementTop, elementWidth, elementHeight); + } + } + else if (element is Line || element is Avalonia.Controls.Shapes.Path) + { + ClearResizeHandlesOnly(); + if (_selectionBorder != null) DrawingCanvas.Children.Remove(_selectionBorder); + _selectionBorder = null; + SelectElement(element); + } + } + + private void ToolButton_Click(object? sender, RoutedEventArgs e) + { + if (sender is Button button && button.Tag is string toolName) + { + if (Enum.TryParse(toolName, out var tool)) + { + SelectTool(tool); + } + } + } + + private void SelectTool(AnnotationTool tool) + { + _currentTool = tool; + var resources = Avalonia.Application.Current!.Resources; + var normalTheme = (Avalonia.Styling.ControlTheme)resources["ToolButton"]!; + var activeTheme = (Avalonia.Styling.ControlTheme)resources["ToolButtonActive"]!; + var toolName = tool.ToString(); + foreach (var child in ToolButtonsPanel.Children) + { + if (child is Button b && b.Tag is string tag) + { + b.Theme = tag == toolName ? activeTheme : normalTheme; + } + } + } + + private void CustomColorButton_Click(object? sender, RoutedEventArgs e) + { + // Re-use the WinForms ColorDialog (already referenced for this reason — see + // MoneyShot.UI.csproj) rather than hand-rolling an HSL picker — the OS picker is what + // most users expect and supports the full palette. Matches the WPF build's reasoning. + using var dlg = new System.Windows.Forms.ColorDialog + { + FullOpen = true, + AnyColor = true, + Color = System.Drawing.Color.FromArgb(_currentColor.A, _currentColor.R, _currentColor.G, _currentColor.B) + }; + if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; + + var picked = Color.FromArgb(dlg.Color.A, dlg.Color.R, dlg.Color.G, dlg.Color.B); + _currentColor = picked; + if (CustomColorButton != null) + { + CustomColorButton.Background = new SolidColorBrush(picked); + } + if (_selectedElement != null) + { + ChangeElementColor(_selectedElement, _currentColor); + } + } + + private void StrokeThicknessSlider_ValueChanged(object? sender, RangeBaseValueChangedEventArgs e) + { + _lineThickness = (int)Math.Round(e.NewValue); + if (StrokeThicknessLabel != null) StrokeThicknessLabel.Text = _lineThickness.ToString(); + if (_selectedElement is Shape shape && _selectedElement is not Avalonia.Controls.Shapes.Path) + { + shape.StrokeThickness = _lineThickness; + } + } + + private void ShortcutsHelp_Click(object? sender, RoutedEventArgs e) => ToggleShortcutsOverlay(); + + private void ShortcutsOverlay_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if (ShortcutsOverlay != null) ShortcutsOverlay.IsVisible = false; + } + + private void ToggleShortcutsOverlay() + { + if (ShortcutsOverlay == null) return; + ShortcutsOverlay.IsVisible = !ShortcutsOverlay.IsVisible; + } + + private void ColorButton_Click(object? sender, RoutedEventArgs e) + { + if (sender is Button button && button.Background is SolidColorBrush brush) + { + _currentColor = brush.Color; + + if (_selectedElement != null) + { + ChangeElementColor(_selectedElement, _currentColor); + } + } + } + + private void TextBackgroundComboBox_SelectionChanged(object? sender, SelectionChangedEventArgs e) + { + if (TextBackgroundComboBox.SelectedItem is not ComboBoxItem selectedItem) + { + return; + } + + var colorName = selectedItem.Content?.ToString(); + _currentTextBackgroundColor = colorName switch + { + "White" => Colors.White, + "Black" => Colors.Black, + "Yellow" => Colors.Yellow, + "Red" => Colors.Red, + "Blue" => Colors.Blue, + "Green" => Colors.Green, + _ => Colors.Transparent + }; + + if (_selectedElement is TextBlock selectedText) + { + selectedText.Background = new SolidColorBrush(_currentTextBackgroundColor); + } + } + + private void ChangeElementColor(Control element, Color newColor) + { + if (!IsColorChangeableElement(element)) + return; + + var brush = new SolidColorBrush(newColor); + + if (element is Shape shape) + { + shape.Stroke = brush; + if (element is Avalonia.Controls.Shapes.Path path) + { + path.Fill = brush; + } + } + else if (element is TextBlock textBlock) + { + textBlock.Foreground = brush; + } + } + + private bool IsColorChangeableElement(Control element) + { + if (element is Rectangle { Tag: PixelateTag }) + return false; + + return element is Shape || element is TextBlock; + } + + private void Undo_Click(object? sender, RoutedEventArgs e) + { + _undo.Undo(this); + } + + private void ResetNumbering_Click(object? sender, RoutedEventArgs e) + { + _numberCounter = 1; + } + + private async void ApplyCrop() + { + if (_cropRectangle == null) return; + + var cropX = Canvas.GetLeft(_cropRectangle); + var cropY = Canvas.GetTop(_cropRectangle); + var cropWidth = _cropRectangle.Width; + var cropHeight = _cropRectangle.Height; + + cropX = Math.Max(0, cropX); + cropY = Math.Max(0, cropY); + cropX = Math.Min(cropX, _originalImage.PixelSize.Width - 1); + cropY = Math.Min(cropY, _originalImage.PixelSize.Height - 1); + + cropWidth = Math.Min(cropWidth, _originalImage.PixelSize.Width - cropX); + cropHeight = Math.Min(cropHeight, _originalImage.PixelSize.Height - cropY); + + var intCropX = (int)Math.Round(cropX); + var intCropY = (int)Math.Round(cropY); + var intCropWidth = (int)Math.Round(cropWidth); + var intCropHeight = (int)Math.Round(cropHeight); + + if (intCropWidth <= 0 || intCropHeight <= 0) + { + await SimpleMessageBox.ShowAsync(this, "Invalid crop dimensions.", "Crop Error"); + DrawingCanvas.Children.Remove(_cropRectangle); + _cropRectangle = null; + return; + } + + try + { + var previousImage = _originalImage; + var previousElements = new List(); + foreach (Control element in DrawingCanvas.Children) + { + if (element != _cropRectangle && element != _selectionBorder && !_resizeHandles.Contains(element)) + { + previousElements.Add(element); + } + } + var previousNumberCounter = _numberCounter; + + // Crop via the same raw-pixel path as RegionSelector, rather than Avalonia's + // CroppedBitmap (which has no Save/pixel-access API of its own — see LINUX_PORT.md + // Phase 1 risk notes), so the cropped image is a real, independently usable Bitmap. + var captured = _originalImage.ToCapturedImage(); + var croppedBitmap = CropCapturedImage(captured, intCropX, intCropY, intCropWidth, intCropHeight).ToAvaloniaBitmap(); + + _originalImage = croppedBitmap; + DisplayImage(); + + DrawingCanvas.Children.Clear(); + _selectedElement = null; + _selectionBorder = null; + _resizeHandles.Clear(); + _cropRectangle = null; + _numberCounter = 1; + + SelectTool(AnnotationTool.Cursor); + _undo.Push(new UndoController.CropUndoAction(previousImage, previousElements, previousNumberCounter)); + } + catch (Exception ex) + { + await SimpleMessageBox.ShowAsync(this, $"Failed to apply crop: {ex.Message}", "Crop Error"); + DrawingCanvas.Children.Remove(_cropRectangle); + _cropRectangle = null; + } + } + + private static MoneyShot.Abstractions.CapturedImage CropCapturedImage(MoneyShot.Abstractions.CapturedImage source, int x, int y, int width, int height) + { + const int bytesPerPixel = 4; + var destStride = width * bytesPerPixel; + var dest = new byte[destStride * height]; + for (var row = 0; row < height; row++) + { + var srcOffset = (y + row) * source.Stride + x * bytesPerPixel; + Buffer.BlockCopy(source.PixelDataBgra32, srcOffset, dest, row * destStride, destStride); + } + return new MoneyShot.Abstractions.CapturedImage(width, height, destStride, dest); + } + + private async void Save_Click(object? sender, RoutedEventArgs e) + { + try + { + var finalImage = CaptureCanvasAsImage(); + + var settings = new MoneyShot.Services.SettingsService().LoadSettings(); + var defaultFormat = settings.DefaultFileFormat.ToUpperInvariant(); + var extension = defaultFormat switch { "JPG" or "JPEG" => "jpg", "BMP" => "bmp", _ => "png" }; + + var file = await StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions + { + Title = "Save screenshot", + SuggestedFileName = _saveService.GenerateFileName(settings.DefaultFileFormat), + DefaultExtension = extension, + SuggestedStartLocation = await StorageProvider.TryGetFolderFromPathAsync(new Uri(settings.DefaultSavePath)), + FileTypeChoices = new[] + { + new FilePickerFileType("PNG Image") { Patterns = new[] { "*.png" } }, + new FilePickerFileType("JPEG Image") { Patterns = new[] { "*.jpg", "*.jpeg" } }, + new FilePickerFileType("Bitmap Image") { Patterns = new[] { "*.bmp" } }, + } + }); + + var path = file?.TryGetLocalPath(); + if (!string.IsNullOrEmpty(path)) + { + var fileExtension = System.IO.Path.GetExtension(path).TrimStart('.'); + var format = GetFileFormat(fileExtension); + _saveService.SaveToFile(finalImage, path, format); + await SimpleMessageBox.ShowAsync(this, "Image saved successfully!", "Success"); + } + } + catch (Exception ex) + { + await SimpleMessageBox.ShowAsync(this, $"Failed to save image: {ex.Message}", "Error"); + } + } + + private string GetFileFormat(string extension) + { + return extension.ToUpperInvariant() switch + { + "JPG" or "JPEG" => "JPG", + "BMP" => "BMP", + _ => "PNG" + }; + } + + private async void SaveToClipboard_Click(object? sender, RoutedEventArgs e) + { + try + { + var finalImage = CaptureCanvasAsImage(); + _saveService.SaveToClipboard(finalImage); + await SimpleMessageBox.ShowAsync(this, "Image copied to clipboard!", "Success"); + } + catch (Exception ex) + { + await SimpleMessageBox.ShowAsync(this, $"Failed to copy image to clipboard: {ex.Message}", "Error"); + } + } + + private void ZoomIn_Click(object? sender, RoutedEventArgs e) + { + if (_zoomLevel < MaxZoom) + { + _zoomLevel += ZoomIncrement; + ApplyZoom(); + } + } + + private void ZoomOut_Click(object? sender, RoutedEventArgs e) + { + if (_zoomLevel > MinZoom) + { + _zoomLevel -= ZoomIncrement; + ApplyZoom(); + } + } + + private void ZoomReset_Click(object? sender, RoutedEventArgs e) + { + _zoomLevel = 1.0; + ApplyZoom(); + PanTransform.X = 0; + PanTransform.Y = 0; + } + + private void ApplyZoom() + { + ZoomTransform.ScaleX = _zoomLevel; + ZoomTransform.ScaleY = _zoomLevel; + if (ZoomLevelLabel != null) + { + ZoomLevelLabel.Text = $"{Math.Round(_zoomLevel * 100)}%"; + } + } + + private Bitmap CaptureCanvasAsImage() => + CanvasRenderer.CaptureCanvasAsImage(ImageCanvas, _originalImage, ZoomTransform, PanTransform); + + private void TitleBar_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if (e.ClickCount == 2) + { + MaximizeRestore_Click(sender, new RoutedEventArgs()); + } + else if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) + { + BeginMoveDrag(e); + } + } + + private void Minimize_Click(object? sender, RoutedEventArgs e) + { + WindowState = WindowState.Minimized; + } + + private void MaximizeRestore_Click(object? sender, RoutedEventArgs e) + { + var resources = Avalonia.Application.Current!.Resources; + if (WindowState == WindowState.Maximized) + { + WindowState = WindowState.Normal; + MaximizeRestoreIcon.Data = (Geometry)resources["Icon.WindowMaximize"]!; + } + else + { + WindowState = WindowState.Maximized; + MaximizeRestoreIcon.Data = (Geometry)resources["Icon.WindowRestore"]!; + } + } + + private void Close_Click(object? sender, RoutedEventArgs e) + { + Close(); + } +} diff --git a/MoneyShot.UI/Views/HistoryWindow.axaml b/MoneyShot.UI/Views/HistoryWindow.axaml new file mode 100644 index 0000000..4b54f59 --- /dev/null +++ b/MoneyShot.UI/Views/HistoryWindow.axaml @@ -0,0 +1,100 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/MoneyShot.UI/Views/MainWindow.axaml.cs b/MoneyShot.UI/Views/MainWindow.axaml.cs new file mode 100644 index 0000000..88144e3 --- /dev/null +++ b/MoneyShot.UI/Views/MainWindow.axaml.cs @@ -0,0 +1,480 @@ +using System.Threading.Tasks; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Input; +using Avalonia.Interactivity; +using Avalonia.Media; +using Avalonia.Threading; +using MoneyShot.Abstractions; +using MoneyShot.UI.Interop; +using MoneyShot.UI.Services; +using MoneyShot.Platform.Windows; +using MoneyShot.Services; +using Path = Avalonia.Controls.Shapes.Path; + +namespace MoneyShot.UI.Views; + +/// +/// Avalonia port of MoneyShot/MainWindow.xaml.cs — see LINUX_PORT.md Phase 1. Logic mirrors the +/// WPF version closely; the differences are all Avalonia API shape (async dialogs instead of +/// blocking MessageBox, Dispatcher.UIThread instead of WPF's Dispatcher, PointerPressed + +/// BeginMoveDrag instead of MouseLeftButtonDown + DragMove). +/// +public partial class MainWindow : Window +{ + private readonly IScreenCapture _screenshotService; + private readonly SaveService _saveService; + private readonly SettingsService _settingsService; + private readonly IGlobalHotkeys _hotKeyService; + private readonly AutoUpdateService _autoUpdateService; + private readonly HistoryService _historyService; + private ITrayIcon? _trayIcon; + + private const int MaxMonitorHotkeys = 9; + + public MainWindow() + { + InitializeComponent(); + _screenshotService = new Win32ScreenCapture(); + _saveService = new SaveService(new Win32Clipboard()); + _settingsService = new SettingsService(); + _hotKeyService = new Win32GlobalHotkeys(); + _autoUpdateService = new AutoUpdateService(); + _historyService = new HistoryService(); + + Closing += Window_Closing; + PropertyChanged += MainWindow_PropertyChanged; + + SetupSystemTray(); + } + + /// + /// Mirrors MoneyShot/MainWindow.xaml.cs's InitializeApplication: binds global hotkeys and + /// shows the window only when the user hasn't opted to start in the tray. Called once from + /// App.OnFrameworkInitializationCompleted. IGlobalHotkeys owns its own native handle + /// independent of this window (see Win32GlobalHotkeys), so nothing here needs the window to + /// exist at all when starting hidden in the tray. + /// + public void InitializeApplication() + { + try + { + var settings = _settingsService.LoadSettings(); + + if (!settings.StartInTray) + { + ShowMainWindow(); + } + + _hotKeyService.Initialize(); + RegisterHotKeys(); + PopulateMonitorButtons(); + + if (settings.CheckForUpdatesOnStartup) + { + _ = CheckForUpdatesOnStartupAsync(); + } + } + catch (System.Exception ex) + { + Logger.Error("Main window startup failed", ex); + } + } + + private async Task CheckForUpdatesOnStartupAsync() + { + try + { + await CheckForUpdatesAsync(showUpToDateMessage: false, showErrorsToUser: false); + } + catch (System.Exception ex) + { + Logger.Error("Auto-update check failed", ex); + } + } + + private async Task CheckForUpdatesAsync(bool showUpToDateMessage, bool showErrorsToUser) + { + try + { + var updateInfo = await _autoUpdateService.GetAvailableUpdateAsync(); + if (updateInfo == null) + { + if (showUpToDateMessage) + { + await SimpleMessageBox.ShowAsync(this, "You already have the latest version of Money Shot.", "No Updates Available"); + } + return; + } + + var result = await SimpleMessageBox.ShowAsync(this, + $"A new version of MoneyShot is available ({updateInfo.RemoteVersion}). Install now?", + "Update Available", SimpleMessageBoxButtons.YesNo); + + if (result != SimpleMessageBoxResult.Yes) + { + return; + } + + await _autoUpdateService.StageAndPrepareUpdateAsync(updateInfo); + _hotKeyService.UnregisterAll(); + _trayIcon?.Dispose(); + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.Shutdown(); + } + } + catch (System.Exception ex) + { + if (showErrorsToUser) + { + var guidance = ex.Message.Contains("GitHub Releases endpoint", System.StringComparison.OrdinalIgnoreCase) + ? "\n\nNo Money Shot configuration is required. Please ensure this device can access https://api.github.com (network/firewall/proxy) and try again." + : string.Empty; + await SimpleMessageBox.ShowAsync(this, $"Failed to check for updates: {ex.Message}{guidance}", "Update Error"); + } + else + { + Logger.Error("Auto-update check failed", ex); + } + } + } + + private void PopulateMonitorButtons() + { + var screens = _screenshotService.GetAllMonitors(); + if (screens.Count <= 1) return; + + var resources = Avalonia.Application.Current!.Resources; + var label = new TextBlock + { + Text = "Individual monitors", + FontSize = 12, + Foreground = (IBrush)resources["Cocoa.TextSecondaryBrush"]!, + Margin = new Thickness(0, 10, 0, 6) + }; + MonitorButtonsPanel.Children.Add(label); + + var subtleTheme = (Avalonia.Styling.ControlTheme)resources["SubtleButton"]!; + var monitorIcon = (Geometry)resources["Icon.Monitor"]!; + var iconTheme = (Avalonia.Styling.ControlTheme)resources["ToolIcon"]!; + + for (int i = 0; i < screens.Count; i++) + { + var screenIndex = i; + var screen = screens[i]; + var isPrimary = screen.IsPrimary ? " · primary" : string.Empty; + var hotkeyHint = screenIndex < MaxMonitorHotkeys ? $"Ctrl+Shift+{screenIndex + 1}" : null; + + var content = new StackPanel { Orientation = Avalonia.Layout.Orientation.Horizontal }; + content.Children.Add(new Path { Theme = iconTheme, Data = monitorIcon }); + content.Children.Add(new TextBlock + { + Text = $"Monitor {i + 1}{isPrimary}", + Margin = new Thickness(9, 0, 0, 0), + VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center + }); + + var button = new Button + { + Content = content, + Theme = subtleTheme, + Padding = new Thickness(14, 9, 14, 9), + Margin = new Thickness(0, 3, 0, 3), + HorizontalContentAlignment = Avalonia.Layout.HorizontalAlignment.Left + }; + if (hotkeyHint != null) + { + ToolTip.SetTip(button, $"Capture this monitor (hotkey: {hotkeyHint})"); + } + button.Click += (_, _) => _ = CaptureMonitorAsync(screenIndex); + MonitorButtonsPanel.Children.Add(button); + } + } + + private void RegisterHotKeys() + { + var settings = _settingsService.LoadSettings(); + + _hotKeyService.RegisterHotKeyFromString(settings.HotKeyCapture, () => + { + Dispatcher.UIThread.Post(() => _ = CaptureFullScreenAsync()); + }); + + _hotKeyService.RegisterHotKeyFromString(settings.HotKeyRegionCapture, () => + { + Dispatcher.UIThread.Post(() => _ = CaptureRegionAsync()); + }); + + var screens = _screenshotService.GetAllMonitors(); + for (int i = 0; i < System.Math.Min(screens.Count, MaxMonitorHotkeys); i++) + { + var monitorIndex = i; + var hotkey = $"Ctrl+Shift+{i + 1}"; + _hotKeyService.RegisterHotKeyFromString(hotkey, () => + { + Dispatcher.UIThread.Post(() => _ = CaptureMonitorAsync(monitorIndex)); + }); + } + } + + public void ReloadHotKeys() + { + _hotKeyService.UnregisterAll(); + RegisterHotKeys(); + } + + private void SetupSystemTray() + { + var menuItems = new System.Collections.Generic.List + { + new("Capture Full Screen", () => _ = CaptureFullScreenAsync()), + new("Capture Region", () => _ = CaptureRegionAsync()), + }; + + var screens = _screenshotService.GetAllMonitors(); + if (screens.Count > 1) + { + menuItems.Add(TrayMenuItem.Separator()); + for (int i = 0; i < screens.Count; i++) + { + var screenIndex = i; + var isPrimary = screens[i].IsPrimary ? " (Primary)" : ""; + menuItems.Add(new TrayMenuItem($"Capture Monitor {i + 1}{isPrimary}", () => _ = CaptureMonitorAsync(screenIndex))); + } + } + + menuItems.Add(TrayMenuItem.Separator()); + menuItems.Add(new TrayMenuItem("History", ShowHistory)); + menuItems.Add(new TrayMenuItem("Check for Updates", () => _ = CheckForUpdatesAsync(showUpToDateMessage: true, showErrorsToUser: true))); + menuItems.Add(new TrayMenuItem("Settings", () => _ = ShowSettingsAsync())); + menuItems.Add(TrayMenuItem.Separator()); + menuItems.Add(new TrayMenuItem("Show Window", ShowMainWindow)); + menuItems.Add(new TrayMenuItem("Exit", ExitApplication)); + + _trayIcon = new Win32TrayIcon(); + _trayIcon.Show("Money Shot - Screenshot Tool", menuItems); + _trayIcon.DoubleClicked += ShowMainWindow; + } + + private async Task CaptureFullScreenAsync() + { + try + { + Hide(); + await Task.Delay(200); + + var screenshot = _screenshotService.CaptureFullScreen().ToAvaloniaBitmap(); + await OpenEditorAsync(screenshot, "FullScreen"); + } + catch (System.Exception ex) + { + Logger.Error("Error capturing full screen", ex); + await SimpleMessageBox.ShowAsync(this, $"Failed to capture screenshot: {ex.Message}", "Capture Error"); + ShowMainWindow(); + } + } + + private async Task CaptureRegionAsync() + { + try + { + var settings = _settingsService.LoadSettings(); + if (settings.HideUiFromScreenshots) + { + Hide(); + await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render); + await Task.Delay(300); + } + + var frozenScreen = _screenshotService.CaptureFullScreen().ToAvaloniaBitmap(); + + if (!settings.HideUiFromScreenshots) + { + Hide(); + await Task.Delay(200); + } + + var regionSelector = new RegionSelector(frozenScreen); + var confirmed = await regionSelector.ShowDialog(this); + if (confirmed && regionSelector.CroppedScreenshot != null) + { + await OpenEditorAsync(regionSelector.CroppedScreenshot, "Region"); + } + else + { + ShowMainWindow(); + } + } + catch (System.Exception ex) + { + Logger.Error("Error capturing region", ex); + await SimpleMessageBox.ShowAsync(this, $"Failed to capture region: {ex.Message}", "Capture Error"); + ShowMainWindow(); + } + } + + private async Task CaptureMonitorAsync(int monitorIndex) + { + try + { + Hide(); + await Dispatcher.UIThread.InvokeAsync(() => { }, DispatcherPriority.Render); + await Task.Delay(300); + + var screenshot = _screenshotService.CaptureMonitor(monitorIndex).ToAvaloniaBitmap(); + await OpenEditorAsync(screenshot, $"Monitor {monitorIndex + 1}"); + } + catch (System.Exception ex) + { + Logger.Error($"Error capturing monitor {monitorIndex}", ex); + await SimpleMessageBox.ShowAsync(this, $"Failed to capture monitor: {ex.Message}", "Capture Error"); + ShowMainWindow(); + } + } + + private async Task OpenEditorAsync(Avalonia.Media.Imaging.Bitmap screenshot, string source = "Capture") + { + try + { + var settings = _settingsService.LoadSettings(); + if (settings.SaveCapturesToHistory) + { + _historyService.Save(screenshot, source, settings.HistoryRetentionCount); + } + + var editor = new EditorWindow(screenshot); + await editor.ShowDialog(this); + } + catch (System.Exception ex) + { + Logger.Error("Error opening editor", ex); + await SimpleMessageBox.ShowAsync(this, $"Failed to open image editor: {ex.Message}", "Editor Error"); + ShowMainWindow(); + } + finally + { + MemoryTrimmer.TrimAfterEditorClose(); + } + } + + private async Task ShowSettingsAsync() + { + var settings = new SettingsWindow(); + await settings.ShowDialog(this); + } + + private void ShowHistory() + { + var history = new HistoryWindow(_historyService); + history.Show(); + history.Activate(); + } + + private void ShowMainWindow() + { + Show(); + WindowState = WindowState.Normal; + Activate(); + } + + private void ExitApplication() + { + _hotKeyService.UnregisterAll(); + _trayIcon?.Dispose(); + if (Avalonia.Application.Current?.ApplicationLifetime is Avalonia.Controls.ApplicationLifetimes.IClassicDesktopStyleApplicationLifetime desktop) + { + desktop.Shutdown(); + } + } + + private void CaptureFullScreen_Click(object? sender, RoutedEventArgs e) => _ = CaptureFullScreenAsync(); + private void CaptureRegion_Click(object? sender, RoutedEventArgs e) => _ = CaptureRegionAsync(); + private void Settings_Click(object? sender, RoutedEventArgs e) => _ = ShowSettingsAsync(); + private void History_Click(object? sender, RoutedEventArgs e) => ShowHistory(); + + private async void About_Click(object? sender, RoutedEventArgs e) + { + var settings = _settingsService.LoadSettings(); + var screens = _screenshotService.GetAllMonitors(); + var monitorHotkeys = screens.Count > 1 ? $"\n• Ctrl+Shift+1-{System.Math.Min(screens.Count, MaxMonitorHotkeys)} — Capture individual monitors" : ""; + var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; + var displayVersion = version == null ? "unknown" : $"{version.Major}.{version.Minor}.{version.Build}"; + + await SimpleMessageBox.ShowAsync(this, + "Money Shot — screenshot capture and annotation (Avalonia build)\n\n" + + $"Version {displayVersion}\n" + + "Developed by Daolyap & iSaluki\n\n" + + "Current hotkeys:\n" + + $"• {settings.HotKeyCapture} — Capture full screen\n" + + $"• {settings.HotKeyRegionCapture} — Capture region" + + monitorHotkeys + + "\n\nFeedback & issues: https://github.com/Daolyap/Money-Shot/issues\n" + + "Security contact: moneyshot@daolyap.dev", + "About Money Shot"); + } + + private void CheckForUpdates_Click(object? sender, RoutedEventArgs e) => + _ = CheckForUpdatesAsync(showUpToDateMessage: true, showErrorsToUser: true); + + private void MainWindow_PropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e) + { + if (e.Property == WindowStateProperty && WindowState == WindowState.Minimized) + { + Hide(); + _trayIcon?.ShowBalloonTip(2000, "Money Shot", "App minimized to system tray"); + } + } + + private void Window_Closing(object? sender, WindowClosingEventArgs e) + { + var settings = _settingsService.LoadSettings(); + if (settings.MinimizeToTray) + { + e.Cancel = true; + Hide(); + _trayIcon?.ShowBalloonTip(2000, "Money Shot", "App is still running in the system tray"); + } + else + { + ExitApplication(); + } + } + + private void TitleBar_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if (e.ClickCount == 2) + { + MaximizeRestore_Click(sender, new RoutedEventArgs()); + } + else if (e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) + { + BeginMoveDrag(e); + } + } + + private void Minimize_Click(object? sender, RoutedEventArgs e) + { + WindowState = WindowState.Minimized; + } + + private void MaximizeRestore_Click(object? sender, RoutedEventArgs e) + { + var resources = Avalonia.Application.Current!.Resources; + if (WindowState == WindowState.Maximized) + { + WindowState = WindowState.Normal; + if (MaximizeRestoreIcon != null) MaximizeRestoreIcon.Data = (Geometry)resources["Icon.WindowMaximize"]!; + } + else + { + WindowState = WindowState.Maximized; + if (MaximizeRestoreIcon != null) MaximizeRestoreIcon.Data = (Geometry)resources["Icon.WindowRestore"]!; + } + } + + private void Close_Click(object? sender, RoutedEventArgs e) + { + Close(); + } +} diff --git a/MoneyShot.UI/Views/RegionSelector.axaml b/MoneyShot.UI/Views/RegionSelector.axaml new file mode 100644 index 0000000..4054c1f --- /dev/null +++ b/MoneyShot.UI/Views/RegionSelector.axaml @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + diff --git a/MoneyShot.UI/Views/RegionSelector.axaml.cs b/MoneyShot.UI/Views/RegionSelector.axaml.cs new file mode 100644 index 0000000..09cbdc1 --- /dev/null +++ b/MoneyShot.UI/Views/RegionSelector.axaml.cs @@ -0,0 +1,229 @@ +using System; +using Avalonia; +using Avalonia.Controls; +using Avalonia.Controls.Shapes; +using Avalonia.Input; +using Avalonia.Media; +using Avalonia.Media.Imaging; +using MoneyShot.Abstractions; +using MoneyShot.UI.Interop; +using DrawingRectangle = System.Drawing.Rectangle; + +namespace MoneyShot.UI.Views; + +/// +/// Avalonia port of MoneyShot/Views/RegionSelector.xaml.cs — see LINUX_PORT.md Phase 1. Ports the +/// ALREADY-DPI-FIXED version of the WPF window (see Opus-Speaks.md § E2 / CLAUDE.md), not the +/// original buggy one, and is actually simpler here: Avalonia's Screens API exposes each monitor's +/// scale factor directly (Screen.Scaling), so there's no Win32 P/Invoke needed for the +/// window-creation-time DIP conversion the WPF version required. +/// +public partial class RegionSelector : Window +{ + private Point _startPoint; + private Rectangle? _selectionRectangle; + private bool _isSelecting; + private int _virtualScreenLeft; + private int _virtualScreenTop; + private double _creationDpiScale = 1.0; + private readonly Bitmap _frozenScreen; + + public DrawingRectangle? SelectedRegion { get; private set; } + public Bitmap? CroppedScreenshot { get; private set; } + + public RegionSelector(Bitmap frozenScreen) + { + InitializeComponent(); + _frozenScreen = frozenScreen; + SetupFullScreenOverlay(frozenScreen); + } + + private void SetupFullScreenOverlay(Bitmap frozenScreen) + { + int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + + foreach (var screen in Screens.All) + { + minX = Math.Min(minX, screen.Bounds.X); + minY = Math.Min(minY, screen.Bounds.Y); + maxX = Math.Max(maxX, screen.Bounds.X + screen.Bounds.Width); + maxY = Math.Max(maxY, screen.Bounds.Y + screen.Bounds.Height); + } + + _virtualScreenLeft = minX; + _virtualScreenTop = minY; + + // Avalonia's Window Position/Width/Height are DIPs, but the monitor bounds above are + // physical pixels. Unlike WPF, Avalonia's Screens collection is queryable before the + // window is shown and gives each monitor's own scale directly (no P/Invoke needed) — use + // the primary screen's as the best-effort guess for sizing, same reasoning as the WPF fix: + // the crop math at mouse-up re-queries the window's actual live scale rather than trusting + // this value. + _creationDpiScale = Screens.Primary?.Scaling ?? 1.0; + + Position = new PixelPoint((int)Math.Round(minX / _creationDpiScale), (int)Math.Round(minY / _creationDpiScale)); + Width = (maxX - minX) / _creationDpiScale; + Height = (maxY - minY) / _creationDpiScale; + + Cursor = new Cursor(StandardCursorType.Cross); + + if (BackgroundImage != null) + { + BackgroundImage.Source = frozenScreen; + BackgroundImage.Stretch = Stretch.Fill; + } + + UpdateDimOverlay(null); + } + + private void UpdateDimOverlay(Rect? selection) + { + var full = new RectangleGeometry(new Rect(0, 0, Width, Height)); + if (selection is { } rect) + { + DimOverlay.Data = new CombinedGeometry(GeometryCombineMode.Exclude, full, new RectangleGeometry(rect)); + } + else + { + DimOverlay.Data = full; + } + } + + private void UpdateSizeBadge(Rect selection) + { + SizeBadge.IsVisible = true; + SizeBadgeText.Text = $"{(int)selection.Width} × {(int)selection.Height}"; + + SizeBadge.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); + var badgeWidth = SizeBadge.DesiredSize.Width; + var badgeHeight = SizeBadge.DesiredSize.Height; + + var x = Math.Max(4, Math.Min(selection.Right - badgeWidth, Width - badgeWidth - 4)); + var y = selection.Bottom + 8; + if (y + badgeHeight > Height - 4) + { + y = selection.Top - badgeHeight - 8; + } + SizeBadge.Margin = new Thickness(x, Math.Max(4, y), 0, 0); + } + + private void Window_PointerPressed(object? sender, PointerPressedEventArgs e) + { + if (!e.GetCurrentPoint(this).Properties.IsLeftButtonPressed) return; + + _isSelecting = true; + _startPoint = e.GetPosition(this); + HintBadge.IsVisible = false; + + _selectionRectangle = new Rectangle + { + Stroke = new SolidColorBrush(Color.FromRgb(0xC2, 0x8E, 0x5C)), + StrokeThickness = 1.5, + Fill = Brushes.Transparent + }; + + Canvas.SetLeft(_selectionRectangle, _startPoint.X); + Canvas.SetTop(_selectionRectangle, _startPoint.Y); + SelectionCanvas.Children.Add(_selectionRectangle); + e.Pointer.Capture(SelectionCanvas); + } + + private void Window_PointerMoved(object? sender, PointerEventArgs e) + { + if (_isSelecting && _selectionRectangle != null) + { + var currentPoint = e.GetPosition(this); + + var x = Math.Min(_startPoint.X, currentPoint.X); + var y = Math.Min(_startPoint.Y, currentPoint.Y); + var width = Math.Abs(_startPoint.X - currentPoint.X); + var height = Math.Abs(_startPoint.Y - currentPoint.Y); + + Canvas.SetLeft(_selectionRectangle, x); + Canvas.SetTop(_selectionRectangle, y); + _selectionRectangle.Width = width; + _selectionRectangle.Height = height; + + var selection = new Rect(x, y, width, height); + UpdateDimOverlay(selection); + UpdateSizeBadge(selection); + } + } + + private void Window_PointerReleased(object? sender, PointerReleasedEventArgs e) + { + if (_isSelecting && _selectionRectangle != null) + { + _isSelecting = false; + e.Pointer.Capture(null); + + var dipX = Canvas.GetLeft(_selectionRectangle); + var dipY = Canvas.GetTop(_selectionRectangle); + var dipWidth = _selectionRectangle.Width; + var dipHeight = _selectionRectangle.Height; + + if (dipWidth > 10 && dipHeight > 10) + { + // Fresh query of the window's actual current scale, same reasoning as the WPF fix: + // correct even if the window somehow ended up on a different-scaled monitor than + // the creation-time guess. + var scale = TopLevel.GetTopLevel(this)?.RenderScaling ?? _creationDpiScale; + var x = (int)Math.Round(dipX * scale); + var y = (int)Math.Round(dipY * scale); + var width = (int)Math.Round(dipWidth * scale); + var height = (int)Math.Round(dipHeight * scale); + + var absoluteX = x + _virtualScreenLeft; + var absoluteY = y + _virtualScreenTop; + + SelectedRegion = new DrawingRectangle(absoluteX, absoluteY, width, height); + + try + { + var cropX = absoluteX - _virtualScreenLeft; + var cropY = absoluteY - _virtualScreenTop; + + cropX = Math.Max(0, Math.Min(cropX, _frozenScreen.PixelSize.Width - width)); + cropY = Math.Max(0, Math.Min(cropY, _frozenScreen.PixelSize.Height - height)); + width = Math.Min(width, _frozenScreen.PixelSize.Width - cropX); + height = Math.Min(height, _frozenScreen.PixelSize.Height - cropY); + + var captured = _frozenScreen.ToCapturedImage(); + CroppedScreenshot = CropCapturedImage(captured, cropX, cropY, width, height).ToAvaloniaBitmap(); + + Close(true); + return; + } + catch (Exception ex) + { + MoneyShot.Services.Logger.Error("Error cropping frozen screenshot", ex); + } + } + + Close(false); + } + } + + private static CapturedImage CropCapturedImage(CapturedImage source, int x, int y, int width, int height) + { + // CapturedImage is always BGRA32 (4 bytes/pixel) per its contract — deriving this from + // source.Stride/source.Width instead would be wrong whenever a row has alignment padding. + const int bytesPerPixel = 4; + var destStride = width * bytesPerPixel; + var dest = new byte[destStride * height]; + for (var row = 0; row < height; row++) + { + var srcOffset = (y + row) * source.Stride + x * bytesPerPixel; + System.Buffer.BlockCopy(source.PixelDataBgra32, srcOffset, dest, row * destStride, destStride); + } + return new CapturedImage(width, height, destStride, dest); + } + + private void Window_KeyDown(object? sender, KeyEventArgs e) + { + if (e.Key == Key.Escape) + { + Close(false); + } + } +} diff --git a/MoneyShot.UI/Views/SettingsWindow.axaml b/MoneyShot.UI/Views/SettingsWindow.axaml new file mode 100644 index 0000000..eb453a0 --- /dev/null +++ b/MoneyShot.UI/Views/SettingsWindow.axaml @@ -0,0 +1,216 @@ + + + + 14 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + public partial class MainWindow : Window { - private readonly ScreenshotService _screenshotService; + private readonly IScreenCapture _screenshotService; private readonly SaveService _saveService; private readonly SettingsService _settingsService; - private readonly HotKeyService _hotKeyService; + private readonly IGlobalHotkeys _hotKeyService; private readonly AutoUpdateService _autoUpdateService; private readonly HistoryService _historyService; - private NotifyIcon? _notifyIcon; - + private ITrayIcon? _trayIcon; + // Maximum number of monitors that can have individual hotkeys (limited by number keys 1-9) private const int MaxMonitorHotkeys = 9; public MainWindow() { InitializeComponent(); - _screenshotService = new ScreenshotService(); - _saveService = new SaveService(); + _screenshotService = new Win32ScreenCapture(); + _saveService = new SaveService(new Win32Clipboard()); _settingsService = new SettingsService(); - _hotKeyService = new HotKeyService(); + _hotKeyService = new Win32GlobalHotkeys(); _autoUpdateService = new AutoUpdateService(); _historyService = new HistoryService(); @@ -41,12 +41,12 @@ public MainWindow() } /// - /// Performs post-construction startup: realizes the native handle, binds global hotkeys, and - /// shows the window only when the user hasn't opted to start in the tray. Called once from - /// . When is set the - /// window is never shown — creates the HWND that - /// hotkey registration needs without painting anything, which avoids the black-frame flash that - /// Show()-then-Hide() produced. + /// Performs post-construction startup: binds global hotkeys, and shows the window only when + /// the user hasn't opted to start in the tray. Called once from . + /// When is set the window is never shown or + /// realized at all — owns its own native handle independent of + /// the main window (see Win32GlobalHotkeys), so there's nothing here that needs the window's + /// HWND to exist up front, unlike the Show()-then-Hide() flash this used to work around. /// public void InitializeApplication() { @@ -54,18 +54,12 @@ public void InitializeApplication() { var settings = _settingsService.LoadSettings(); - if (settings.StartInTray) - { - // Realize the Win32 handle without making the window visible. - new WindowInteropHelper(this).EnsureHandle(); - } - else + if (!settings.StartInTray) { ShowMainWindow(); } - // The HWND now exists (via EnsureHandle or Show), so global hotkeys can bind to it. - _hotKeyService.Initialize(this); + _hotKeyService.Initialize(); RegisterHotKeys(); PopulateMonitorButtons(); @@ -123,7 +117,7 @@ private async Task CheckForUpdatesAsync(bool showUpToDateMessage, bool showError await _autoUpdateService.StageAndPrepareUpdateAsync(updateInfo); _hotKeyService.UnregisterAll(); - _notifyIcon?.Dispose(); + _trayIcon?.Dispose(); Application.Current.Shutdown(); } catch (Exception ex) @@ -148,7 +142,7 @@ private async Task CheckForUpdatesAsync(bool showUpToDateMessage, bool showError private void PopulateMonitorButtons() { - var screens = _screenshotService.GetAllScreens(); + var screens = _screenshotService.GetAllMonitors(); if (screens.Count <= 1) return; var label = new TextBlock @@ -167,7 +161,7 @@ private void PopulateMonitorButtons() { var screenIndex = i; var screen = screens[i]; - var isPrimary = screen.Primary ? " · primary" : string.Empty; + var isPrimary = screen.IsPrimary ? " · primary" : string.Empty; var hotkeyHint = screenIndex < MaxMonitorHotkeys ? $"Ctrl+Shift+{screenIndex + 1}" : null; var content = new StackPanel { Orientation = System.Windows.Controls.Orientation.Horizontal }; @@ -196,7 +190,7 @@ private void PopulateMonitorButtons() private void RegisterHotKeys() { var settings = _settingsService.LoadSettings(); - + // Register hotkeys from settings _hotKeyService.RegisterHotKeyFromString(settings.HotKeyCapture, () => { @@ -207,9 +201,9 @@ private void RegisterHotKeys() { Dispatcher.Invoke(CaptureRegion); }); - + // Register Ctrl+Shift+Number hotkeys for individual monitors (PrintScreen+Number not supported by Windows API) - var screens = _screenshotService.GetAllScreens(); + var screens = _screenshotService.GetAllMonitors(); for (int i = 0; i < Math.Min(screens.Count, MaxMonitorHotkeys); i++) { var monitorIndex = i; @@ -225,75 +219,43 @@ public void ReloadHotKeys() { // Unregister all existing hotkeys _hotKeyService.UnregisterAll(); - + // Re-register with new settings RegisterHotKeys(); } private void SetupSystemTray() { - try + var menuItems = new List { - var processModule = System.Diagnostics.Process.GetCurrentProcess().MainModule; - var iconPath = processModule?.FileName; - - System.Drawing.Icon? icon = null; - if (iconPath != null && File.Exists(iconPath)) - { - icon = System.Drawing.Icon.ExtractAssociatedIcon(iconPath); - } - - // Fallback to default icon if extraction fails - icon ??= System.Drawing.SystemIcons.Application; - - _notifyIcon = new NotifyIcon - { - Icon = icon, - Visible = true, - Text = "Money Shot - Screenshot Tool" - }; - } - catch (Exception ex) - { - // Log the error and use default icon - MoneyShot.Services.Logger.Error("Error setting up system tray icon", ex); - - _notifyIcon = new NotifyIcon - { - Icon = System.Drawing.SystemIcons.Application, - Visible = true, - Text = "Money Shot - Screenshot Tool" - }; - } + new("Capture Full Screen", CaptureFullScreen), + new("Capture Region", CaptureRegion), + }; - var contextMenu = new ContextMenuStrip(); - contextMenu.Items.Add("Capture Full Screen", null, (s, e) => CaptureFullScreen()); - contextMenu.Items.Add("Capture Region", null, (s, e) => CaptureRegion()); - // Add individual monitor options - var screens = _screenshotService.GetAllScreens(); + var screens = _screenshotService.GetAllMonitors(); if (screens.Count > 1) { - contextMenu.Items.Add("-"); + menuItems.Add(TrayMenuItem.Separator()); for (int i = 0; i < screens.Count; i++) { var screenIndex = i; - var screen = screens[i]; - var isPrimary = screen.Primary ? " (Primary)" : ""; - contextMenu.Items.Add($"Capture Monitor {i + 1}{isPrimary}", null, (s, e) => CaptureMonitor(screenIndex)); + var isPrimary = screens[i].IsPrimary ? " (Primary)" : ""; + menuItems.Add(new TrayMenuItem($"Capture Monitor {i + 1}{isPrimary}", () => CaptureMonitor(screenIndex))); } } - - contextMenu.Items.Add("-"); - contextMenu.Items.Add("History", null, (s, e) => ShowHistory()); - contextMenu.Items.Add("Check for Updates", null, async (s, e) => await CheckForUpdatesAsync(showUpToDateMessage: true, showErrorsToUser: true)); - contextMenu.Items.Add("Settings", null, (s, e) => ShowSettings()); - contextMenu.Items.Add("-"); - contextMenu.Items.Add("Show Window", null, (s, e) => ShowMainWindow()); - contextMenu.Items.Add("Exit", null, (s, e) => ExitApplication()); - - _notifyIcon.ContextMenuStrip = contextMenu; - _notifyIcon.DoubleClick += (s, e) => ShowMainWindow(); + + menuItems.Add(TrayMenuItem.Separator()); + menuItems.Add(new TrayMenuItem("History", ShowHistory)); + menuItems.Add(new TrayMenuItem("Check for Updates", async () => await CheckForUpdatesAsync(showUpToDateMessage: true, showErrorsToUser: true))); + menuItems.Add(new TrayMenuItem("Settings", ShowSettings)); + menuItems.Add(TrayMenuItem.Separator()); + menuItems.Add(new TrayMenuItem("Show Window", ShowMainWindow)); + menuItems.Add(new TrayMenuItem("Exit", ExitApplication)); + + _trayIcon = new Win32TrayIcon(); + _trayIcon.Show("Money Shot - Screenshot Tool", menuItems); + _trayIcon.DoubleClicked += ShowMainWindow; } private void CaptureFullScreen() @@ -303,13 +265,13 @@ private void CaptureFullScreen() Hide(); System.Threading.Thread.Sleep(200); // Small delay to hide the window - var screenshot = _screenshotService.CaptureFullScreen(); + var screenshot = _screenshotService.CaptureFullScreen().ToBitmapSource(); OpenEditor(screenshot, "FullScreen"); } catch (Exception ex) { MoneyShot.Services.Logger.Error("Error capturing full screen", ex); - System.Windows.MessageBox.Show($"Failed to capture screenshot: {ex.Message}", "Capture Error", + System.Windows.MessageBox.Show($"Failed to capture screenshot: {ex.Message}", "Capture Error", MessageBoxButton.OK, MessageBoxImage.Error); ShowMainWindow(); } @@ -326,9 +288,9 @@ private void CaptureRegion() System.Windows.Application.Current.Dispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.Render); System.Threading.Thread.Sleep(300); } - + // Capture frozen snapshot after hide when invisibility cloak is enabled. - var frozenScreen = _screenshotService.CaptureFullScreen(); + var frozenScreen = _screenshotService.CaptureFullScreen().ToBitmapSource(); if (!settings.HideUiFromScreenshots) { @@ -350,7 +312,7 @@ private void CaptureRegion() catch (Exception ex) { MoneyShot.Services.Logger.Error("Error capturing region", ex); - System.Windows.MessageBox.Show($"Failed to capture region: {ex.Message}", "Capture Error", + System.Windows.MessageBox.Show($"Failed to capture region: {ex.Message}", "Capture Error", MessageBoxButton.OK, MessageBoxImage.Error); ShowMainWindow(); } @@ -365,13 +327,13 @@ private void CaptureMonitor(int monitorIndex) System.Windows.Application.Current.Dispatcher.Invoke(() => { }, System.Windows.Threading.DispatcherPriority.Render); System.Threading.Thread.Sleep(300); - var screenshot = _screenshotService.CaptureScreen(monitorIndex); + var screenshot = _screenshotService.CaptureMonitor(monitorIndex).ToBitmapSource(); OpenEditor(screenshot, $"Monitor {monitorIndex + 1}"); } catch (Exception ex) { MoneyShot.Services.Logger.Error($"Error capturing monitor {monitorIndex}", ex); - System.Windows.MessageBox.Show($"Failed to capture monitor: {ex.Message}", "Capture Error", + System.Windows.MessageBox.Show($"Failed to capture monitor: {ex.Message}", "Capture Error", MessageBoxButton.OK, MessageBoxImage.Error); ShowMainWindow(); } @@ -434,7 +396,7 @@ private void ShowMainWindow() private void ExitApplication() { _hotKeyService.UnregisterAll(); - _notifyIcon?.Dispose(); + _trayIcon?.Dispose(); Application.Current.Shutdown(); } @@ -461,7 +423,7 @@ private void History_Click(object sender, RoutedEventArgs e) private void About_Click(object sender, RoutedEventArgs e) { var settings = _settingsService.LoadSettings(); - var screens = _screenshotService.GetAllScreens(); + var screens = _screenshotService.GetAllMonitors(); var monitorHotkeys = screens.Count > 1 ? $"\n• Ctrl+Shift+1-{Math.Min(screens.Count, MaxMonitorHotkeys)} — Capture individual monitors" : ""; // SemVer portion only — the 4th part is the CI build number and isn't meaningful to users. var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; @@ -492,7 +454,7 @@ private void Window_StateChanged(object sender, EventArgs e) if (WindowState == WindowState.Minimized) { Hide(); - _notifyIcon?.ShowBalloonTip(2000, "Money Shot", "App minimized to system tray", ToolTipIcon.Info); + _trayIcon?.ShowBalloonTip(2000, "Money Shot", "App minimized to system tray"); } } @@ -503,14 +465,14 @@ private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs { e.Cancel = true; Hide(); - _notifyIcon?.ShowBalloonTip(2000, "Money Shot", "App is still running in the system tray", ToolTipIcon.Info); + _trayIcon?.ShowBalloonTip(2000, "Money Shot", "App is still running in the system tray"); } else { ExitApplication(); } } - + private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (e.ClickCount == 2) @@ -531,12 +493,12 @@ private void TitleBar_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) } } } - + private void Minimize_Click(object sender, RoutedEventArgs e) { WindowState = WindowState.Minimized; } - + private void MaximizeRestore_Click(object sender, RoutedEventArgs e) { if (WindowState == WindowState.Maximized) diff --git a/MoneyShot/MoneyShot.csproj b/MoneyShot/MoneyShot.csproj index 952a93c..e029a48 100644 --- a/MoneyShot/MoneyShot.csproj +++ b/MoneyShot/MoneyShot.csproj @@ -23,6 +23,11 @@ + + + + + diff --git a/MoneyShot/Services/SaveService.cs b/MoneyShot/Services/SaveService.cs index e559889..59d02f0 100644 --- a/MoneyShot/Services/SaveService.cs +++ b/MoneyShot/Services/SaveService.cs @@ -1,17 +1,28 @@ using System.Drawing.Imaging; using System.IO; -using System.Windows; using System.Windows.Media.Imaging; +using MoneyShot.Abstractions; +using MoneyShot.Interop; namespace MoneyShot.Services; public class SaveService { + private readonly IClipboard _clipboard; + + public SaveService(IClipboard clipboard) + { + _clipboard = clipboard; + } + public void SaveToClipboard(BitmapSource image) { try { - Clipboard.SetImage(image); + // Routed through IClipboard (Win32Clipboard on Windows today) rather than + // System.Windows.Clipboard directly, so this stays correct once the UI layer moves to + // Avalonia — see LINUX_PORT.md § Clipboard image support. + _clipboard.SetImage(image.ToCapturedImage()); } catch (Exception ex) { diff --git a/MoneyShot/Services/ScreenshotService.cs b/MoneyShot/Services/ScreenshotService.cs deleted file mode 100644 index a22c04b..0000000 --- a/MoneyShot/Services/ScreenshotService.cs +++ /dev/null @@ -1,87 +0,0 @@ -using System.Drawing; -using System.Drawing.Imaging; -using System.IO; -using System.Windows; -using System.Windows.Interop; -using System.Windows.Media.Imaging; - -namespace MoneyShot.Services; - -public class ScreenshotService -{ - public BitmapSource CaptureFullScreen() - { - var bounds = GetVirtualScreenBounds(); - return CaptureRegion(bounds); - } - - public BitmapSource CaptureRegion(Rectangle region) - { - using var bitmap = new Bitmap(region.Width, region.Height, PixelFormat.Format32bppPArgb); - using (var graphics = Graphics.FromImage(bitmap)) - { - graphics.CopyFromScreen(region.Left, region.Top, 0, 0, region.Size, CopyPixelOperation.SourceCopy); - } - - return ConvertToBitmapSource(bitmap); - } - - public BitmapSource CaptureScreen(int screenIndex) - { - var screens = System.Windows.Forms.Screen.AllScreens; - if (screenIndex < 0 || screenIndex >= screens.Length) - throw new ArgumentOutOfRangeException(nameof(screenIndex)); - - var screen = screens[screenIndex]; - var bounds = screen.Bounds; - - return CaptureRegion(bounds); - } - - public List GetAllScreens() - { - return new List(System.Windows.Forms.Screen.AllScreens); - } - - private Rectangle GetVirtualScreenBounds() - { - int minX = int.MaxValue; - int minY = int.MaxValue; - int maxX = int.MinValue; - int maxY = int.MinValue; - - foreach (var screen in System.Windows.Forms.Screen.AllScreens) - { - minX = Math.Min(minX, screen.Bounds.Left); - minY = Math.Min(minY, screen.Bounds.Top); - maxX = Math.Max(maxX, screen.Bounds.Right); - maxY = Math.Max(maxY, screen.Bounds.Bottom); - } - - return new Rectangle(minX, minY, maxX - minX, maxY - minY); - } - - private BitmapSource ConvertToBitmapSource(Bitmap bitmap) - { - var hBitmap = bitmap.GetHbitmap(); - try - { - var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap( - hBitmap, - IntPtr.Zero, - Int32Rect.Empty, - BitmapSizeOptions.FromEmptyOptions()); - - // Freeze the bitmap source to make it thread-safe and improve performance - bitmapSource.Freeze(); - return bitmapSource; - } - finally - { - DeleteObject(hBitmap); - } - } - - [System.Runtime.InteropServices.DllImport("gdi32.dll")] - private static extern bool DeleteObject(IntPtr hObject); -} diff --git a/MoneyShot/Views/EditorWindow.xaml.cs b/MoneyShot/Views/EditorWindow.xaml.cs index b61fd45..1466e3c 100644 --- a/MoneyShot/Views/EditorWindow.xaml.cs +++ b/MoneyShot/Views/EditorWindow.xaml.cs @@ -6,6 +6,7 @@ using System.Windows.Shapes; using MoneyShot.Editor; using MoneyShot.Models; +using MoneyShot.Platform.Windows; using MoneyShot.Services; namespace MoneyShot.Views; @@ -100,7 +101,7 @@ public EditorWindow(BitmapSource image) { InitializeComponent(); _originalImage = image; - _saveService = new SaveService(); + _saveService = new SaveService(new Win32Clipboard()); DisplayImage(); // Add keyboard event handler for Delete key diff --git a/MoneyShot/Views/HistoryWindow.xaml.cs b/MoneyShot/Views/HistoryWindow.xaml.cs index 26fdb78..50a3a32 100644 --- a/MoneyShot/Views/HistoryWindow.xaml.cs +++ b/MoneyShot/Views/HistoryWindow.xaml.cs @@ -5,6 +5,7 @@ using System.Windows.Media; using System.Windows.Media.Imaging; using MoneyShot.Models; +using MoneyShot.Platform.Windows; using MoneyShot.Services; namespace MoneyShot.Views; @@ -12,7 +13,7 @@ namespace MoneyShot.Views; public partial class HistoryWindow : Window { private readonly HistoryService _history; - private readonly SaveService _saveService = new(); + private readonly SaveService _saveService = new(new Win32Clipboard()); public HistoryWindow(HistoryService history) { diff --git a/MoneyShot/Views/SettingsWindow.xaml.cs b/MoneyShot/Views/SettingsWindow.xaml.cs index cfacf06..4170b48 100644 --- a/MoneyShot/Views/SettingsWindow.xaml.cs +++ b/MoneyShot/Views/SettingsWindow.xaml.cs @@ -2,7 +2,9 @@ using System.Text; using System.Windows; using System.Windows.Input; +using MoneyShot.Abstractions; using MoneyShot.Models; +using MoneyShot.Platform.Windows; using MoneyShot.Services; using Application = System.Windows.Application; @@ -11,12 +13,16 @@ namespace MoneyShot.Views; public partial class SettingsWindow : Window { private readonly SettingsService _settingsService; + private readonly IScreenCapture _screenCapture; + private readonly IAutoStart _autoStart; private AppSettings _settings; public SettingsWindow() { InitializeComponent(); _settingsService = new SettingsService(); + _screenCapture = new Win32ScreenCapture(); + _autoStart = new Win32AutoStart(); _settings = _settingsService.LoadSettings(); LoadSettings(); LoadMonitorHotkeysInfo(); @@ -24,9 +30,8 @@ public SettingsWindow() private void LoadMonitorHotkeysInfo() { - var screenshotService = new ScreenshotService(); - var screens = screenshotService.GetAllScreens(); - + var screens = _screenCapture.GetAllMonitors(); + if (screens.Count > 1) { var hotkeys = new StringBuilder(); @@ -50,7 +55,7 @@ private void LoadSettings() MinimizeToTrayCheckbox.IsChecked = _settings.MinimizeToTray; CheckForUpdatesCheckbox.IsChecked = _settings.CheckForUpdatesOnStartup; HideUiFromScreenshotsCheckbox.IsChecked = _settings.HideUiFromScreenshots; - if (_settingsService.TryGetWindowsPrintScreenDisabled(out var isPrintScreenDisabled)) + if (_autoStart.TryGetPrintScreenSuppressed(out var isPrintScreenDisabled)) { _settings.DisableWindowsPrintScreen = isPrintScreenDisabled; } @@ -155,15 +160,15 @@ private void Save_Click(object sender, RoutedEventArgs e) try { - _settingsService.SetStartupWithWindows(_settings.RunOnStartup); + _autoStart.SetStartupWithApp(_settings.RunOnStartup); } catch (InvalidOperationException ex) { - MessageBox.Show($"Warning: {ex.Message}\nOther settings were saved successfully.", + MessageBox.Show($"Warning: {ex.Message}\nOther settings were saved successfully.", "Partial Success", MessageBoxButton.OK, MessageBoxImage.Warning); } - - var printScreenApplied = _settingsService.SetWindowsPrintScreenDisabled(_settings.DisableWindowsPrintScreen); + + var printScreenApplied = _autoStart.SetPrintScreenSuppressed(_settings.DisableWindowsPrintScreen); // Reload hotkeys in the main window if (Application.Current.MainWindow is MainWindow mainWindow) diff --git a/Opus-Speaks.md b/Opus-Speaks.md deleted file mode 100644 index 935f409..0000000 --- a/Opus-Speaks.md +++ /dev/null @@ -1,99 +0,0 @@ -# Opus Speaks - -A roadmap of prompts for the next agent. The original 8 sections of this document have all been worked on; the remaining items below are what's left, plus follow-ups created during the implementation pass. - ---- - -## Status snapshot - -- [x] **#1 Test project** — `MoneyShot.Tests/` exists with 95 passing xUnit tests covering `HotKeyService.ParseHotKey`, `SettingsService.ValidateAndSanitizeSettings`, `AutoUpdateService.ParseVersion` / `CompareSemVer` / `SelectPreferredAsset` / `ParseSha256Sums`. Wired into `.github/workflows/build.yml`. -- [~] **#2 EditorWindow refactor** — partial. `MoneyShot/Editor/` now holds `UndoController`, `CanvasRenderer`, `CanvasPosition`, `ElementResizeMode`, and `ElementState`. `EditorWindow.xaml.cs` calls into them and the duplicated `IsNaN` guards are gone. The `SelectionController` / `AnnotationToolRegistry` split was **deferred** — see Section A below. -- [x] **#3 Resize handles + arrow/line resize** — visible squares are 12×12 inside 24×24 transparent hit zones; `Line` and `Path` (arrow) elements get 2-handle endpoint resize via `BeginEndpointResize` / `ApplyEndpointResize`. -- [x] **#4 MSI / CI hardening** — Product.wxs already had per-machine scope, MajorUpgrade after install validate, stable component GUIDs, and RemoveFolder. Added `` for 64-bit Windows 10+. Workflows already pin to commit SHAs and use `softprops/action-gh-release@v2`. Added baseline `permissions: contents: read` at workflow level on `release.yml` and `build-msi.yml`. -- [~] **#5 UI/UX upgrades** — 4 of 5 landed. Custom colour picker, stroke-thickness slider, active-tool indicator, and `?` keyboard-shortcut overlay are wired in `EditorWindow.xaml(.cs)`. The **WindowChrome migration was deferred** — see Section B below. -- [~] **#6 Logger** — pragmatic deviation: instead of pulling in `Microsoft.Extensions.Logging` and rewriting every service constructor for DI, added `MoneyShot/Services/Logger.cs`, a static facade that writes to both Debug.WriteLine *and* a daily rolling file at `%AppData%\MoneyShot\logs\moneyshot-YYYYMMDD.log` (7-day retention). Every existing `System.Diagnostics.Debug.WriteLine` call in the services + MainWindow + RegionSelector now goes through it. The user-visible "View Logs" Settings button is **still TODO** — see Section C. -- [x] **#7 SHA-256 verification** — `AutoUpdateService` now fetches `SHA256SUMS.txt` from the release, parses it (`ParseSha256Sums` is unit-tested), and verifies the downloaded asset's SHA-256 before writing the swap script. Releases without a sums file log a warning but still install (back-compat with old releases). `release.yml` generates `SHA256SUMS.txt` from the .zip + .msi and uploads it alongside. -- [x] **#8 Screenshot history** — captures persist to `%AppData%\MoneyShot\history` with thumbnails + sidecar JSON. `MainWindow` saves on every capture path (FullScreen / Region / Monitor N), tray menu has a "History" item, `HistoryWindow.xaml` shows a thumbnail grid with right-click → Open in Editor / Copy to Clipboard / Delete. Retention defaults to 50 (configurable via `AppSettings.HistoryRetentionCount`). Settings UI for the toggle / count is **still TODO** — see Section D. - ---- - -## A. Finish the EditorWindow refactor - -The compositional pieces (`UndoController`, `CanvasRenderer`) are extracted, but selection/drag/resize state still lives in `EditorWindow.xaml.cs`. That code is the source of every past resize regression, so splitting it requires careful work and ideally manual UI test coverage. - -> Continue the refactor of `MoneyShot/Views/EditorWindow.xaml.cs` by extracting: -> -> - `MoneyShot/Editor/SelectionController.cs` — owns `_selectedElement`, `_selectionBorder`, `_resizeHandles`, the `SelectElement` / `ClearSelection` / `MoveElement` / `BeginResize` / `ResizeElement` flow, the new endpoint-resize fields (`_isEndpointResizing`, `_originalEndpointStart`, `_originalEndpointEnd`), and the `CreateResizeHandle` / `CreateEndpointHandle` factories. -> - `MoneyShot/Editor/AnnotationToolRegistry.cs` — owns the per-tool factories (`CreateRectangle`, `CreateEllipse`, `CreateArrow`, `CreatePolyline`, `CreateNumberLabel`, `CreateBlurRectangle`, `CreateLine`) and the per-tool `Update*` methods. -> -> Pass collaborators in via the `EditorWindow` constructor — do **not** introduce a DI container. Keep `EditorWindow.xaml.cs` as the WPF wiring layer that delegates to these controllers from event handlers. Don't rename XAML element IDs or change `Canvas_MouseDown/Move/Up` signatures (they're bound from XAML). -> -> Run the editor on Windows after the split and exercise: rectangle/ellipse/arrow/line/text resize, drag, undo of each, crop, zoom. The fields `_isResizing`, `_isEndpointResizing`, `_isDragging`, `_isDrawing` are mutually exclusive — preserve that invariant. - -## B. Migrate the editor + main window off `AllowsTransparency` - -Both `EditorWindow.xaml` and `MainWindow.xaml` (probably — check) use `WindowStyle="None"` + `AllowsTransparency="True"`, which forces software rendering for the entire window. The custom title bar in `EditorWindow` already shows symptoms of this (the `try/catch` around `DragMove` at `EditorWindow.xaml.cs:TitleBar_MouseLeftButtonDown` exists because `DragMove` throws under certain transparency edge cases). - -> Replace `WindowStyle="None"` + `AllowsTransparency="True"` with `WindowChrome` in `MoneyShot/Views/EditorWindow.xaml` (and `MoneyShot/MainWindow.xaml` if applicable). Use `WindowChrome.WindowChrome` with custom caption buttons inside the chrome's resize border so the dark glassmorphism look survives. Remove the `try/catch (InvalidOperationException)` around `DragMove` in the title bar handler — `WindowChrome` makes that unnecessary. -> -> This is invasive. Be ready to iterate on resize-grip thickness, caption-button positioning, and the rounded-corner Border. Compare side-by-side with the current build before merging. - -## C. Surface the log directory in Settings - -Logs already write to `%AppData%\MoneyShot\logs\moneyshot-YYYYMMDD.log` with 7-day retention via `MoneyShot.Services.Logger.LogDirectoryPath`. Users have no easy way to find them. - -> Add a "View Logs" button to `MoneyShot/Views/SettingsWindow.xaml` that opens `MoneyShot.Services.Logger.LogDirectoryPath` in Explorer via `Process.Start(new ProcessStartInfo { FileName = path, UseShellExecute = true })`. Place it near the bottom of the settings dialog. - -## D. Settings UI for screenshot history - -The history feature ships with `AppSettings.SaveCapturesToHistory` (default true) and `AppSettings.HistoryRetentionCount` (default 50), but neither is exposed in the Settings window — users can only change them by editing `%AppData%\MoneyShot\settings.json` by hand. - -> In `MoneyShot/Views/SettingsWindow.xaml`, add: -> -> - A checkbox "Save captures to local history" bound to `AppSettings.SaveCapturesToHistory`. -> - A NumericUpDown / spinner "Keep last N captures" bound to `AppSettings.HistoryRetentionCount` (range 0–500). 0 disables retention enforcement. -> - A "Clear history" button that calls `HistoryService.List()` then `Delete()` for each entry, with a confirmation dialog. -> -> Surface the history folder path next to the controls so users know where the files live (`%AppData%\MoneyShot\history`). - -## E. Authenticode signing for the published .exe (out-of-scope follow-up to #7) - -SHA-256 verification protects against tampering between GitHub Releases and the user, but the published binary itself is unsigned — Windows SmartScreen will warn on first run, and there's no chain-of-trust on the publisher. - -> Add Authenticode signing to `release.yml`. Options: -> -> - Buy a code-signing cert and store the PFX as a `secrets.SIGNING_CERT_PFX_BASE64` + `secrets.SIGNING_CERT_PASSWORD` GitHub Secret. Sign with `signtool sign /f cert.pfx /p $password /tr http://timestamp.digicert.com /td sha256 /fd sha256 MoneyShot.exe`. -> - Once signed, optionally call `WinVerifyTrust` from `AutoUpdateService.PrepareExecutableAsset` before the swap to refuse unsigned binaries. -> -> Until this lands, the SHA-256 check is the only integrity guarantee — that's still meaningfully better than nothing. - -## E2. Region selector is only pixel-accurate at 100 % display scaling (resolved 2026-07) - -Found during the 2026-06 security/code audit. The app manifest declares `PerMonitorV2` DPI awareness, but `RegionSelector` set its window `Width`/`Height` (DIPs) directly from physical pixel bounds and mapped mouse DIP positions 1:1 onto frozen-bitmap pixel coordinates. At 100 % scaling DIP == pixel and everything lined up; at 125 %/150 % (or mixed-DPI multi-monitor) the window oversized and crops drifted. - -Fixed with the single-window approach: `SetupFullScreenOverlay` now divides the physical-pixel virtual-screen bounds by `GetDpiForSystem() / 96.0` (a P/Invoke best-effort guess, since no per-window DPI exists before the HWND is created) before assigning `Left`/`Top`/`Width`/`Height`. `Window_MouseUp` re-queries the window's *actual* live DPI via `VisualTreeHelper.GetDpi(this)` at crop time — correct even if WPF's automatic `WM_DPICHANGED` handling migrated the window to a different DPI context after construction — and converts the DIP-space selection rectangle to physical pixels with that fresh value before combining it with the physical-pixel virtual-screen offset. - -**Accepted residual limitation**: a single drag that starts on one monitor and ends on another monitor with a *different* scaling percentage can still be slightly imprecise on the non-dominant side — a WPF window only has one DPI context at a time, so this can't be fully correct without one selector window per monitor (each in its own DPI context, with the drag tracked in physical pixels across window boundaries via native mouse capture). That's a substantially bigger change with no automated UI tests to catch regressions; deliberately out of scope unless this specific case becomes a reported problem. - -## E3. Auto-update can't swap a per-machine install - -`StageAndPrepareUpdateAsync` writes the swap script to user temp and runs it unelevated. For per-user installs that's fine, but the MSI installs to `C:\Program Files\Money Shot\` (per-machine), where `move /Y` will fail with access denied and the update silently doesn't apply (script exits 1, nothing re-launches). - -> Either: detect a Program Files install and direct the user to download the MSI instead of self-swapping; or run the script elevated (UAC prompt) via `UseShellExecute = true` + `Verb = "runas"`. Decide deliberately — silent elevation prompts from a background updater are hostile UX. - -## F. Migrate to `Microsoft.Extensions.Logging` if a real DI need ever appears - -The current `Logger` static facade closes the "no Release-build output" gap, but it doesn't enable structured logging, log levels controlled by config, or per-namespace filtering. If the project ever takes on a complexity that justifies DI (multiple loggers, multiple sinks, `ILogger` for testability), the right move is the originally-proposed migration from this document — replace `Logger` with `Microsoft.Extensions.Logging` + a logger factory in `App.xaml.cs`, then take constructor-injected `ILogger` in each service. - -Until that pressure exists, the static facade is the right call. - ---- - -## Notes for the next agent - -- **Do not run `git` commands without explicit user approval.** The user enforces this. -- **Verify what the memory and CLAUDE.md tell you against the current code before acting.** Memories drift. The `CLAUDE.md` resize section was updated when the handle-owns-its-own-MouseDown refactor landed; if you see different code, the docs are stale, not the code. -- **The only test of "feature correctness" is running the WPF app on Windows.** `dotnet build` and `dotnet test` prove the service-layer code compiles and that pure functions behave correctly, not that the WPF UI works. Anything touching `EditorWindow`, `HistoryWindow`, or the tray menu needs human-eyes verification. -- **Don't reintroduce `RESIZE-BUG-JUSTIFY.md`, `plan.md`, or `PROJECT_SUMMARY.md`.** They were deleted because they were agent scratch-pads, not user docs. If you need to write a note for a future agent, append to this file instead. -- **Capture history is local-only by design.** Do not add cloud sync, telemetry, or any remote upload of history files without an explicit settings toggle and an in-product disclosure. -- The MSI license (`Installer/License.rtf`) is now AGPL-3.0 and must stay in sync with the repo's `LICENSE` file. If the repo ever relicenses, update both. From 448352dabe0778ca0302240c0beece7711934276 Mon Sep 17 00:00:00 2001 From: Logan H Date: Tue, 8 Sep 2026 11:22:13 +0100 Subject: [PATCH 2/6] feat: Linux Port phase 1 --- MoneyShot.UI/Interop/BitmapConversions.cs | 5 +++++ MoneyShot.UI/Services/HistoryService.cs | 5 +++++ MoneyShot.UI/Views/EditorWindow.axaml.cs | 5 ++++- MoneyShot.UI/Views/RegionSelector.axaml | 2 +- 4 files changed, 15 insertions(+), 2 deletions(-) diff --git a/MoneyShot.UI/Interop/BitmapConversions.cs b/MoneyShot.UI/Interop/BitmapConversions.cs index 200bc8a..3351ea3 100644 --- a/MoneyShot.UI/Interop/BitmapConversions.cs +++ b/MoneyShot.UI/Interop/BitmapConversions.cs @@ -51,7 +51,12 @@ public static CapturedImage ToCapturedImage(this Bitmap bitmap) else { using var stream = new System.IO.MemoryStream(); + // Save(Stream) is the only overload for "just encode PNG, default settings" — its + // replacement (a BitmapEncoderOptions overload) isn't otherwise needed here since we + // want the default encoding anyway. +#pragma warning disable CS0618 bitmap.Save(stream); +#pragma warning restore CS0618 stream.Position = 0; writeable = WriteableBitmap.Decode(stream); ownsWriteable = true; diff --git a/MoneyShot.UI/Services/HistoryService.cs b/MoneyShot.UI/Services/HistoryService.cs index caeaa85..13430ed 100644 --- a/MoneyShot.UI/Services/HistoryService.cs +++ b/MoneyShot.UI/Services/HistoryService.cs @@ -58,11 +58,16 @@ public HistoryService() ThumbnailFileName = $"{id}-thumb.png", }; + // Save(string) is the only overload for "just encode PNG, default settings" — its + // replacement (a BitmapEncoderOptions overload) isn't otherwise needed since history + // is always plain PNG regardless of the user's chosen save format. +#pragma warning disable CS0618 image.Save(Path.Combine(_historyDirectory, entry.ImageFileName)); using (var thumbnail = CreateThumbnail(image)) { thumbnail.Save(Path.Combine(_historyDirectory, entry.ThumbnailFileName)); } +#pragma warning restore CS0618 File.WriteAllText( Path.Combine(_historyDirectory, $"{id}.json"), JsonSerializer.Serialize(entry, JsonOptions)); diff --git a/MoneyShot.UI/Views/EditorWindow.axaml.cs b/MoneyShot.UI/Views/EditorWindow.axaml.cs index f801418..38fefb1 100644 --- a/MoneyShot.UI/Views/EditorWindow.axaml.cs +++ b/MoneyShot.UI/Views/EditorWindow.axaml.cs @@ -1784,7 +1784,10 @@ private async void ApplyCrop() catch (Exception ex) { await SimpleMessageBox.ShowAsync(this, $"Failed to apply crop: {ex.Message}", "Crop Error"); - DrawingCanvas.Children.Remove(_cropRectangle); + // Non-null here: the "if (_cropRectangle == null) return;" guard above the try block + // means we can only reach this catch with a non-null value (nothing in the try + // reassigns it before a possible throw). + DrawingCanvas.Children.Remove(_cropRectangle!); _cropRectangle = null; } } diff --git a/MoneyShot.UI/Views/RegionSelector.axaml b/MoneyShot.UI/Views/RegionSelector.axaml index 4054c1f..0877762 100644 --- a/MoneyShot.UI/Views/RegionSelector.axaml +++ b/MoneyShot.UI/Views/RegionSelector.axaml @@ -3,7 +3,7 @@ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Select Region" Background="Black" - SystemDecorations="None" + WindowDecorations="None" ShowInTaskbar="False" Topmost="True" PointerPressed="Window_PointerPressed" From 51f40bf472271ec86c1382630cb1f71fb1c9d3ac Mon Sep 17 00:00:00 2001 From: Logan H Date: Wed, 9 Sep 2026 15:41:15 +0100 Subject: [PATCH 3/6] feat: Linux Port P3 --- .github/workflows/build-linux.yml | 114 +++ .github/workflows/release.yml | 108 +++ CLAUDE.md | 60 +- LINUX_PORT.md | 739 ++++++++++++------ MoneyShot.Core/Services/AppDataPaths.cs | 56 ++ MoneyShot.Core/Services/Logger.cs | 5 +- MoneyShot.Core/Services/SettingsService.cs | 5 +- MoneyShot.Platform.Linux/LinuxAutoStart.cs | 94 +++ MoneyShot.Platform.Linux/LinuxClipboard.cs | 113 +++ .../LinuxGlobalHotkeys.cs | 214 +++++ .../LinuxMemoryTrimmer.cs | 45 ++ .../LinuxScreenCapture.cs | 200 +++++ .../MoneyShot.Platform.Linux.csproj | 35 + MoneyShot.Platform.Linux/X11Interop.cs | 119 +++ MoneyShot.UI/Assets/icon.png | Bin 0 -> 104409 bytes MoneyShot.UI/Interop/WindowExtensions.cs | 42 + MoneyShot.UI/MoneyShot.UI.csproj | 84 +- MoneyShot.UI/Platform/LinuxTrayIcon.cs | 91 +++ MoneyShot.UI/Platform/PlatformServices.cs | 33 + MoneyShot.UI/Services/HistoryService.cs | 53 +- MoneyShot.UI/Views/EditorWindow.axaml.cs | 15 +- MoneyShot.UI/Views/HistoryWindow.axaml.cs | 13 +- MoneyShot.UI/Views/MainWindow.axaml | 1 + MoneyShot.UI/Views/MainWindow.axaml.cs | 26 +- MoneyShot.UI/Views/SettingsWindow.axaml.cs | 17 +- MoneyShot.UI/Views/SimpleColorDialog.cs | 142 ++++ MoneyShot.UI/Views/SimpleMessageBox.cs | 14 +- MoneyShot.sln | 14 + MoneyShot/Services/HistoryService.cs | 5 +- Packaging/linux/build-appimage.sh | 52 ++ Packaging/linux/build-deb.sh | 92 +++ Packaging/linux/build-rpm.sh | 51 ++ Packaging/linux/moneyshot.desktop | 9 + Packaging/linux/rpm/moneyshot.spec | 57 ++ 34 files changed, 2373 insertions(+), 345 deletions(-) create mode 100644 .github/workflows/build-linux.yml create mode 100644 MoneyShot.Core/Services/AppDataPaths.cs create mode 100644 MoneyShot.Platform.Linux/LinuxAutoStart.cs create mode 100644 MoneyShot.Platform.Linux/LinuxClipboard.cs create mode 100644 MoneyShot.Platform.Linux/LinuxGlobalHotkeys.cs create mode 100644 MoneyShot.Platform.Linux/LinuxMemoryTrimmer.cs create mode 100644 MoneyShot.Platform.Linux/LinuxScreenCapture.cs create mode 100644 MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj create mode 100644 MoneyShot.Platform.Linux/X11Interop.cs create mode 100644 MoneyShot.UI/Assets/icon.png create mode 100644 MoneyShot.UI/Interop/WindowExtensions.cs create mode 100644 MoneyShot.UI/Platform/LinuxTrayIcon.cs create mode 100644 MoneyShot.UI/Platform/PlatformServices.cs create mode 100644 MoneyShot.UI/Views/SimpleColorDialog.cs create mode 100644 Packaging/linux/build-appimage.sh create mode 100644 Packaging/linux/build-deb.sh create mode 100644 Packaging/linux/build-rpm.sh create mode 100644 Packaging/linux/moneyshot.desktop create mode 100644 Packaging/linux/rpm/moneyshot.spec diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml new file mode 100644 index 0000000..e48e3eb --- /dev/null +++ b/.github/workflows/build-linux.yml @@ -0,0 +1,114 @@ +name: Build Money Shot (Linux) + +# Mirrors build.yml's triggers so the Linux build gets exercised on every PR and every GitHub +# Release alongside the Windows build — see LINUX_PORT.md Phase 2/3. Builds MoneyShot.UI (the +# Avalonia UI — MoneyShot itself, the WPF app, is Windows-only and has no Linux build) and packages +# it as .deb, .rpm, and an AppImage. + +on: + pull_request: + branches: [ main, master ] + release: + types: [created] + +permissions: + contents: read + +jobs: + build-linux: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Setup .NET + uses: actions/setup-dotnet@9a946fdbd5fb07b82b2f5a4466058b876ab72bb2 # v5.3.0 + with: + dotnet-version: '10.0.x' + + - name: Extract version from project file + id: get_version + run: | + set -euo pipefail + version=$(grep -oPm1 '(?<=)[^<]+' MoneyShot.UI/MoneyShot.UI.csproj) + if [ -z "$version" ]; then + echo "::error::Version property not found in MoneyShot.UI.csproj" >&2 + exit 1 + fi + build_number="${GITHUB_RUN_NUMBER:-0}" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "build_number=$build_number" >> "$GITHUB_OUTPUT" + + - name: Restore dependencies + run: dotnet restore MoneyShot.UI/MoneyShot.UI.csproj + + - name: Build (compile check, both platform-neutral parts) + run: dotnet build MoneyShot.UI/MoneyShot.UI.csproj -f net10.0 --configuration Release --no-restore + + - name: Publish (self-contained linux-x64) + run: | + dotnet publish MoneyShot.UI/MoneyShot.UI.csproj -f net10.0 -r linux-x64 --self-contained true \ + --configuration Release -o ./publish-linux \ + /p:AssemblyVersion=${{ steps.get_version.outputs.version }}.${{ steps.get_version.outputs.build_number }} \ + /p:FileVersion=${{ steps.get_version.outputs.version }}.${{ steps.get_version.outputs.build_number }} + + - name: Install packaging tools + run: | + sudo apt-get update -qq + sudo apt-get install -y -qq dpkg-dev rpm file + + - name: Build .deb + run: | + chmod +x Packaging/linux/build-deb.sh + ./Packaging/linux/build-deb.sh ./publish-linux \ + "${{ steps.get_version.outputs.version }}-${{ steps.get_version.outputs.build_number }}" \ + ./MoneyShot-v${{ steps.get_version.outputs.version }}-build.${{ steps.get_version.outputs.build_number }}_amd64.deb + + - name: Build .rpm + run: | + chmod +x Packaging/linux/build-rpm.sh + ./Packaging/linux/build-rpm.sh ./publish-linux \ + "${{ steps.get_version.outputs.version }}" \ + ./rpm-out \ + "${{ steps.get_version.outputs.build_number }}" + mv ./rpm-out/*.rpm ./MoneyShot-v${{ steps.get_version.outputs.version }}-build.${{ steps.get_version.outputs.build_number }}.x86_64.rpm + + - name: Download appimagetool + run: | + curl -sL -o /tmp/appimagetool https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage + chmod +x /tmp/appimagetool + + - name: Build AppImage + run: | + chmod +x Packaging/linux/build-appimage.sh + # appimagetool is itself an AppImage that needs FUSE to mount normally — GitHub-hosted + # runners don't have /dev/fuse set up for unprivileged use, so extract-and-run instead. + cat > /tmp/appimagetool-wrapper.sh <<'EOF' + #!/bin/bash + exec /tmp/appimagetool --appimage-extract-and-run "$@" + EOF + chmod +x /tmp/appimagetool-wrapper.sh + APPIMAGETOOL=/tmp/appimagetool-wrapper.sh ./Packaging/linux/build-appimage.sh ./publish-linux \ + "${{ steps.get_version.outputs.version }}" \ + ./MoneyShot-v${{ steps.get_version.outputs.version }}-build.${{ steps.get_version.outputs.build_number }}-x86_64.AppImage + + - name: Upload build artifacts + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 + with: + name: MoneyShot-Linux-Build + path: | + ./*.deb + ./*.rpm + ./*.AppImage + + - name: Upload release assets + if: github.event_name == 'release' + uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2.5.0 + with: + files: | + ./*.deb + ./*.rpm + ./*.AppImage + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7402a60..5fd277c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -152,3 +152,111 @@ jobs: prerelease: false env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + build-and-release-linux: + # Runs after build-and-release so the tag/release it creates already exists — this job attaches + # Linux packages to that same release rather than creating a second one. Builds MoneyShot.UI + # (the Avalonia UI; MoneyShot itself, the WPF app, is Windows-only) as .deb/.rpm/AppImage — see + # LINUX_PORT.md Phase 2/3 and build-linux.yml (this mirrors that workflow's build+package steps + # for the auto-release-on-push case specifically). + needs: build-and-release + runs-on: ubuntu-latest + + permissions: + contents: write + actions: read + + steps: + - name: Checkout code + uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6.0.3 + + - name: Setup .NET + uses: actions/setup-dotnet@9a946fdbd5fb07b82b2f5a4466058b876ab72bb2 # v5.3.0 + with: + dotnet-version: '10.0.x' + + - name: Extract version from project file + id: get_version + run: | + set -euo pipefail + version=$(grep -oPm1 '(?<=)[^<]+' MoneyShot.UI/MoneyShot.UI.csproj) + if [ -z "$version" ]; then + echo "::error::Version property not found in MoneyShot.UI.csproj" >&2 + exit 1 + fi + # Must exactly reproduce build-and-release's tag computation (same $version-source + # semantics apply — MoneyShot.csproj and MoneyShot.UI.csproj carry independent + # properties day-to-day, but the tag itself is keyed on run number + commit SHA, which are + # identical across jobs in the same workflow run regardless of which csproj's version + # string is embedded in it) so this job's release-asset upload targets the same tag. + build_number="${GITHUB_RUN_NUMBER:-0}" + short_sha="${GITHUB_SHA:0:7}" + tag="v${version}-build.${build_number}.${short_sha}" + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "build_number=$build_number" >> "$GITHUB_OUTPUT" + echo "tag=$tag" >> "$GITHUB_OUTPUT" + + - name: Restore dependencies + run: dotnet restore MoneyShot.UI/MoneyShot.UI.csproj + + - name: Publish (self-contained linux-x64) + run: | + dotnet publish MoneyShot.UI/MoneyShot.UI.csproj -f net10.0 -r linux-x64 --self-contained true \ + --configuration Release -o ./publish-linux \ + /p:AssemblyVersion=${{ steps.get_version.outputs.version }}.${{ steps.get_version.outputs.build_number }} \ + /p:FileVersion=${{ steps.get_version.outputs.version }}.${{ steps.get_version.outputs.build_number }} + + - name: Install packaging tools + run: | + sudo apt-get update -qq + sudo apt-get install -y -qq dpkg-dev rpm file + + - name: Build .deb + run: | + chmod +x Packaging/linux/build-deb.sh + ./Packaging/linux/build-deb.sh ./publish-linux \ + "${{ steps.get_version.outputs.version }}-${{ steps.get_version.outputs.build_number }}" \ + ./MoneyShot-v${{ steps.get_version.outputs.version }}-build.${{ steps.get_version.outputs.build_number }}_amd64.deb + + - name: Build .rpm + run: | + chmod +x Packaging/linux/build-rpm.sh + ./Packaging/linux/build-rpm.sh ./publish-linux \ + "${{ steps.get_version.outputs.version }}" \ + ./rpm-out \ + "${{ steps.get_version.outputs.build_number }}" + mv ./rpm-out/*.rpm ./MoneyShot-v${{ steps.get_version.outputs.version }}-build.${{ steps.get_version.outputs.build_number }}.x86_64.rpm + + - name: Download appimagetool + run: | + curl -sL -o /tmp/appimagetool https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-x86_64.AppImage + chmod +x /tmp/appimagetool + + - name: Build AppImage + run: | + chmod +x Packaging/linux/build-appimage.sh + cat > /tmp/appimagetool-wrapper.sh <<'EOF' + #!/bin/bash + exec /tmp/appimagetool --appimage-extract-and-run "$@" + EOF + chmod +x /tmp/appimagetool-wrapper.sh + APPIMAGETOOL=/tmp/appimagetool-wrapper.sh ./Packaging/linux/build-appimage.sh ./publish-linux \ + "${{ steps.get_version.outputs.version }}" \ + ./MoneyShot-v${{ steps.get_version.outputs.version }}-build.${{ steps.get_version.outputs.build_number }}-x86_64.AppImage + + - name: Generate Linux SHA256SUMS.txt + run: | + sha256sum ./*.deb ./*.rpm ./*.AppImage | sed 's|\./||' > SHA256SUMS-linux.txt + cat SHA256SUMS-linux.txt + + - name: Attach Linux packages to the release + uses: softprops/action-gh-release@a06a81a03ee405af7f2048a818ed3f03bbf83c7b # v2.5.0 + with: + tag_name: ${{ steps.get_version.outputs.tag }} + files: | + ./*.deb + ./*.rpm + ./*.AppImage + SHA256SUMS-linux.txt + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/CLAUDE.md b/CLAUDE.md index 2354bb2..552f4f7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -33,30 +33,48 @@ All visual styling lives in `MoneyShot/Themes/CocoaTheme.xaml` (merged in `App.x - Code-behind looks styles up with `FindResource` (App-scoped), not `Resources[...]` (window-scoped). - The pixelate tool (`CanvasRenderer.CreatePixelatedBrush`) copies only the covered region's pixels once and block-averages in that buffer. Don't go back to rendering the full image into a `RenderTargetBitmap` — at 4K that allocated ~33 MB per pixelation plus a `CroppedBitmap` per block. -### Project split: MoneyShot.Core / MoneyShot.Platform.Windows / MoneyShot / MoneyShot.UI (Linux-port groundwork) - -The solution has five projects — see `LINUX_PORT.md` for the full rationale and the remaining -migration phases. **`MoneyShot` (WPF) is still the shipping app** — the MSI installer and CI -release pipeline both build it, unchanged. `MoneyShot.UI` (Avalonia) is additive: it exists to -prove out the Linux-port UI migration and is not wired into any release process. Don't touch the -WPF project's behavior when working on `MoneyShot.UI`, and don't assume `MoneyShot.UI` is -production-ready — see `LINUX_PORT.md` Phase 1 for exactly what has and hasn't been verified -there (short version: it builds and `MainWindow` has been visually confirmed working; -`EditorWindow`, `SettingsWindow`, `HistoryWindow`, `RegionSelector`, hotkeys, and the tray menu -have not been interactively tested). +### Project split: MoneyShot.Core / MoneyShot.Platform.Windows / MoneyShot.Platform.Linux / MoneyShot / MoneyShot.UI + +The solution has six projects — see `LINUX_PORT.md` for the full rationale, what's verified, and +the remaining gaps (Wayland, mainly). **`MoneyShot` (WPF) is still the shipping app** — the MSI +installer and CI release pipeline both build it, unchanged; it is Windows-only and always will be +(WPF has no Linux runtime). `MoneyShot.UI` (Avalonia) is the cross-platform UI: it multi-targets +`net10.0-windows` and `net10.0`, builds and runs on both Windows and Linux (X11 sessions — see +`LINUX_PORT.md`'s Wayland-status section), and is packaged for Linux as `.deb`/`.rpm`/AppImage via +`Packaging/linux/` and `.github/workflows/build-linux.yml`. It is **not** wired into the Windows +MSI/release pipeline (that stays on the WPF app) — don't touch WPF's behavior when working on +`MoneyShot.UI`. Before relying on `MoneyShot.UI` for anything beyond what `LINUX_PORT.md` documents +as verified, read its Phase 1/2/3 status sections — most core flows (capture, editor, history, +settings, tray, packaging) are genuinely verified against real Windows and Linux runs; some +(`EditorWindow`'s deeper tools, multi-monitor/HiDPI on Linux, Wayland entirely) are not. - **`MoneyShot.Core`** (`net10.0`, no UI/Windows dependency) — Models, `SettingsService`, `Logger`, - `AutoUpdateService`, `HotKeyParser`, and the platform abstraction interfaces under - `MoneyShot.Abstractions` (`IScreenCapture`, `IGlobalHotkeys`, `ITrayIcon`, `IAutoStart`, - `IClipboard`). `CapturedImage` (raw BGRA32 pixels) is the neutral bitmap type Core hands back - instead of a WPF `BitmapSource`. + `AutoUpdateService`, `HotKeyParser`, `AppDataPaths` (resolves the per-user config root — + `Environment.SpecialFolder.ApplicationData` alone is not reliable on Linux, see `LINUX_PORT.md` + § 8), and the platform abstraction interfaces under `MoneyShot.Abstractions` (`IScreenCapture`, + `IGlobalHotkeys`, `ITrayIcon`, `IAutoStart`, `IClipboard`). `CapturedImage` (raw BGRA32 pixels) is + the neutral bitmap type Core hands back instead of a WPF `BitmapSource`/Avalonia `Bitmap`. - **`MoneyShot.Platform.Windows`** (`net10.0-windows`, no WPF dependency) — `Win32ScreenCapture`, - `Win32GlobalHotkeys`, `Win32TrayIcon`, `Win32AutoStart`, `Win32Clipboard`. Deliberately - UI-framework-agnostic (references WinForms only for `NotifyIcon`/`Clipboard`, not WPF) so the - same implementations keep working if the UI layer ever moves to Avalonia. -- **`MoneyShot`** (WPF) — every XAML window, plus `SaveService`/`HistoryService` (still - `BitmapSource`-based — these get an Avalonia twin only if/when Phase 1 of the port happens). - `Interop/BitmapConversions.cs` converts `CapturedImage` ↔ `BitmapSource` at the UI boundary. + `Win32GlobalHotkeys`, `Win32TrayIcon`, `Win32AutoStart`, `Win32Clipboard`, `MemoryTrimmer`. + Deliberately UI-framework-agnostic (references WinForms only for `NotifyIcon`/`Clipboard`, not + WPF) so the same implementations work under both `MoneyShot` (WPF) and `MoneyShot.UI` (Avalonia). +- **`MoneyShot.Platform.Linux`** (`net10.0`, no Avalonia dependency) — `LinuxScreenCapture` (X11 + `XGetImage` + `xrandr`-parsed monitor bounds), `LinuxGlobalHotkeys` (X11 `XGrabKey`), + `LinuxAutoStart` (XDG `~/.config/autostart/*.desktop`), `LinuxClipboard` (SkiaSharp PNG-encode + + `wl-copy`/`xclip`), `LinuxMemoryTrimmer`. X11-only — no Wayland-native capture/hotkeys yet (see + `LINUX_PORT.md`'s Wayland-status section). +- **`MoneyShot`** (WPF, Windows-only) — every XAML window, plus `SaveService`/`HistoryService` + (`BitmapSource`-based). `Interop/BitmapConversions.cs` converts `CapturedImage` ↔ `BitmapSource` + at the UI boundary. +- **`MoneyShot.UI`** (Avalonia, cross-platform) — every window ported to `.axaml`, plus its own + `SaveService`/`HistoryService` (Avalonia `Bitmap`-based, SkiaSharp for JPEG/BMP encoding since + Avalonia's own `Bitmap.Save` is PNG-only). `Platform/PlatformServices.cs` is a **compile-time** + `#if WINDOWS`-gated factory (not a runtime `OperatingSystem.IsWindows()` check — the two TFMs + don't reference the same platform project) that every window calls instead of `new Win32*(...)`; + `Platform/LinuxTrayIcon.cs` wraps Avalonia's own cross-platform `TrayIcon`/`NativeMenu` rather + than hand-rolling the Linux StatusNotifierItem D-Bus protocol. `Views/SimpleColorDialog.cs` is a + small hand-rolled Avalonia color picker used only on the non-Windows build (WinForms' + `ColorDialog`, used on Windows, isn't available there). ### Two windows + service layer (no DI, no MVVM framework) diff --git a/LINUX_PORT.md b/LINUX_PORT.md index b431c9f..16ed0c2 100644 --- a/LINUX_PORT.md +++ b/LINUX_PORT.md @@ -1,26 +1,34 @@ # Linux Port — Feasibility & Plan -> Status: **Phase 0 shipped** (2026-09). **Phase 1 built and partially verified** (2026-09) — a -> full Avalonia port of every window exists as a new, additive `MoneyShot.UI` project (the -> shipping WPF app/installer is untouched). It builds clean and `MainWindow` has been confirmed -> working by actually running it and inspecting a screenshot — theme, custom title bar, buttons, -> icons, and dynamic monitor detection all render correctly. **The other four windows have not -> been interactively tested** — see § Phase 1 status for exactly what is and isn't verified before -> anyone relies on this build. Phases 2–4 (X11/Wayland platform code, packaging) are not started -> and remain a planning-only commitment for the team to weigh — see § Migration phases and § -> Decision matrix for the team. +> Status: **Phases 0–3 done and substantially verified against real Linux systems** (2026-09). +> `MoneyShot.UI` (Avalonia) now multi-targets `net10.0-windows` and `net10.0`, with a +> `MoneyShot.Platform.Linux` project providing X11 screen capture, X11 global hotkeys, XDG +> autostart, and clipboard support — selected via `MoneyShot.UI/Platform/PlatformServices.cs` +> alongside the existing Windows implementations, with no change to the shipping WPF app. This +> was **not just built — it was built, published as a self-contained `linux-x64` binary, and +> actually run** against real X11 sessions (Xvfb under Docker, and WSLg's own compositor): the +> full hotkey→capture→editor flow, `HistoryWindow`, `SettingsWindow`, and the clipboard path all +> confirmed working end-to-end on genuine Linux, not just "compiles." Three real, non-obvious bugs +> were found this way and fixed — see § Phase 2 status. **`.deb` and `.rpm` packages are built, +> and each was installed via its native package manager (`apt`/`dnf`) in a clean container and +> launched successfully**; an AppImage build path exists and was verified to build and run too. +> `.github/workflows/build-linux.yml` builds and packages all three on every PR/release, and +> `release.yml` attaches them to the same auto-created release the Windows MSI/zip go to. +> **Remaining real gaps**: no Wayland-native capture or hotkeys (X11/XWayland only — see § 2 and +> § 3), the tray icon has not been confirmed against a real desktop's StatusNotifierWatcher (only +> confirmed to not crash without one), and `EditorWindow`'s deeper tool interactions (resize, crop, +> zoom/pan, pixelate) were verified on Windows but not separately re-verified on Linux. See +> § Migration phases for the full verified-vs-not breakdown per phase. ## TL;DR -A Linux port is **possible but is effectively a rewrite of the UI layer and most of the OS-touching -service code**. About **20–25%** of the codebase ports unchanged (models, save/encode logic, -auto-update HTTP/SHA-256 plumbing, settings JSON, history file management, undo records). The -other 75% — every `Window`, every Win32 P/Invoke, every WPF brush/shape, and the entire capture -pipeline — has to be reimplemented against a new UI framework and new OS APIs. - -Realistic engineering estimate for a single developer working part-time: **8–14 weeks** for a v1 -that matches today's Windows feature set (region capture + annotation editor + tray icon + global -hotkeys), assuming Avalonia is chosen and Wayland support is descoped from v1. +The Linux port is **done for a v1 that matches today's Windows feature set on X11 sessions**: +region/full-screen/monitor capture, the annotation editor, tray icon, global hotkeys, history, +settings, and autostart all work on real Linux, packaged as `.deb`, `.rpm`, and AppImage. The +remaining gap is **Wayland**: X11 direct-capture (`XGetImage`) and X11 global hotkeys +(`XGrabKey`) are what's implemented, and neither has a real equivalent under a native Wayland +session with no XWayland — see § Wayland status below for exactly what that means in practice on +today's Debian/Fedora defaults. ## What ports cleanly (small or no changes) @@ -30,7 +38,7 @@ These files have zero or trivial Windows-specific dependencies and survive a por |---|---| | Models | `Models/AnnotationTool.cs`, `Models/CaptureMode.cs`, `Models/SaveDestination.cs`, `Models/AppSettings.cs`, `Models/HistoryEntry.cs` | | Settings persistence | `Services/SettingsService.cs` — most of it. The two registry hooks (`SetStartupWithWindows`, `SetWindowsPrintScreenDisabled`) are Windows-only and need a Linux equivalent (autostart `.desktop` file in `~/.config/autostart`; the PrintScreen suppression simply has no analogue and should be a no-op) | -| Logger | `Services/Logger.cs` — `%AppData%` resolves to `~/.config/MoneyShot` via `Environment.SpecialFolder.ApplicationData` already; nothing to change | +| Logger | `Services/Logger.cs` ports as-is *once routed through `AppDataPaths.GetConfigRoot()`* — `Environment.SpecialFolder.ApplicationData` does **not** reliably resolve on Linux by itself (returns empty without `$XDG_CONFIG_HOME` set); see § 8 and § Phase 2 for the bug this caused and its fix | | Auto-update HTTP & SHA-256 verification | The HttpClient + `SHA256SUMS.txt` parsing logic in `AutoUpdateService.cs`. The exe-swap batch script at the bottom is Windows-only and needs a shell-script equivalent | | Save encoders | The `BitmapEncoder` calls in `SaveService.cs` — but only the *shape* of the code; the actual encoders come from a different namespace under Avalonia (see § UI framework) | | History service shape | `HistoryService.cs` — the file IO and JSON survive; the BitmapSource/PngBitmapEncoder calls swap to the Avalonia equivalents | @@ -59,124 +67,126 @@ WPF, which means `EditorWindow`'s 1900-line code-behind ports with mostly mechan (b) WPF-style XAML can be reused with minor namespace edits; (c) it has working hotkey, tray, and clipboard primitives on Linux out of the box. -### 2. Capture pipeline - -`ScreenshotService.cs` uses GDI+ (`Graphics.CopyFromScreen`) plus `Imaging.CreateBitmapSourceFromHBitmap` -plus `gdi32!DeleteObject`. None of this exists on Linux. Linux capture has to branch by display -server — and this is where most of the porting risk lives. - -#### X11 (still ~70% of Linux desktops in 2026) - -- Library: `libxcb` or `libX11` via P/Invoke, or wrap an existing helper. -- Approach: `XGetImage` against the root window for full-screen, or against a specific monitor's - geometry obtained via `Xinerama`/`XRandR`. Returns an XImage we copy into a managed buffer. -- Multi-monitor: `XRandRGetScreenResources` enumerates outputs. -- Region capture: same as full-screen, then crop in our process (matches the "frozen bitmap" - pattern we already use on Windows). -- Available .NET wrappers: there's no single canonical one. `Tmds.MDns` won't help here; we'd - either use a small handwritten P/Invoke layer or pull in something like `SharpHook` or write a - thin native helper. Estimated 200–400 lines of P/Invoke + marshalling. - -#### Wayland (the headache) - -- **Wayland deliberately forbids arbitrary screen capture.** A Wayland client cannot just grab - the framebuffer the way an X11 client can. This is a security feature, not an oversight. -- The supported path is the **XDG Desktop Portal `org.freedesktop.portal.Screenshot`** D-Bus - service. The user gets a system-rendered consent dialog the first time the app asks, and - picks the screen/region themselves. -- Implication for MoneyShot: **the "press PrintScreen and instantly grab the screen" UX cannot - work the same way on Wayland.** The user sees a portal dialog. This is non-negotiable from a - Wayland-policy standpoint. We can mitigate by remembering the user's choice and using the - `RestoreToken` mechanism (recent portal versions) to skip the dialog on subsequent grabs in - the same session. -- The portal returns a file path or a PipeWire stream. PipeWire is needed for live-region or - delay-and-capture. For a one-shot screenshot, the file path is fine. -- D-Bus library: `Tmds.DBus.Protocol` (current generation) — well-maintained, AOT-friendly. -- Estimated effort: 2–3 weeks alone for a robust Wayland capture path including portal restore - tokens, error handling for users on compositors that don't expose the portal correctly - (looking at you, sway pre-1.9), and PipeWire support for region selection. - -#### Recommendation for v1 - -Ship **X11-only** for the first Linux release. Detect Wayland (`$XDG_SESSION_TYPE=wayland`) and -either: (a) refuse to run with a clear error pointing the user to `XWaylandVideoBridge`/X11 -session, or (b) launch under XWayland which works for capture but only of the X11 surface tree -(meaning Wayland-native windows won't appear in the capture — usable on KDE/GNOME-Mutter but -broken on hyprland/sway). Pick (a) for honesty; revisit Wayland in v2. - -### 3. Global hotkeys - -`HotKeyService` uses `RegisterHotKey` against an HWND with `HwndSource.AddHook` to receive -`WM_HOTKEY`. Linux has no direct equivalent. - -#### X11 - -- Use `XGrabKey` on the root window for each modifier+keysym combination, listen for - `KeyPress` events on the X event queue. -- Subtlety: NumLock and CapsLock count as modifiers in X11. Each desired hotkey has to be - registered four times (with each combination of NumLock/CapsLock state) or X will silently - not deliver the event when one is on. This is the source of an enormous percentage of "my - hotkey works sometimes" bug reports in cross-platform apps. Bake this in. -- Need a dedicated thread or async loop pumping the X event queue. `HotKeyService` today is - synchronous + relies on the WPF dispatcher — the Linux version has its own pump. - -#### Wayland - -- **Global hotkeys are not part of Wayland.** Wayland clients can only receive input when their - surface has focus. Period. -- The XDG Desktop Portal `org.freedesktop.portal.GlobalShortcuts` exists (added 2023) but is - not yet ubiquitous. GNOME 45+ supports it; KDE Plasma 6 supports it; smaller compositors - variably do not. Where it's available, the user binds the shortcut through the system - settings, not in our app — different UX. -- **Pragmatic answer for v1: drop global hotkey support on Wayland.** Document it. Tray icon + - `xdg-open`-style integration is the alternative. - -### 4. System tray (`NotifyIcon`) - -`System.Windows.Forms.NotifyIcon` doesn't exist outside Windows. Replacement options: - -- **`StatusNotifierItem` (KDE/Plasma, modern GNOME with extensions)** — D-Bus protocol, well-defined. -- **Legacy XEmbed tray (older GNOME, fallback)** — being deprecated; many distros now ship without an - XEmbed-compatible tray. -- Library: Avalonia's `TrayIcon` class wraps both protocols with reasonable graceful-degradation. - Use it directly; don't roll our own. -- GNOME without the AppIndicator extension shows no tray at all. This is a known cultural fight; - document it ("GNOME users may need the AppIndicator extension installed"). - -### 5. Clipboard image support - -`Clipboard.SetImage(BitmapSource)` is WPF-specific and uses Windows clipboard formats. On Linux -the clipboard is X11/Wayland selection-based and image transfer goes through MIME types -(`image/png` typically). Avalonia's `IClipboard.SetDataObjectAsync` handles both, but only after -explicitly registering the PNG-encoded bytes against the right MIME. Roughly 30 lines of code, -plus testing across at least Plasma + GNOME because clipboard managers (Klipper, GPaste) handle -images differently. - -### 6. Auto-update self-swap - -`AutoUpdateService.BuildWindowsSwapScript` writes a `.bat` that waits for the parent process and -swaps in the new exe. The Linux equivalent is a small `bash` script that does the same thing -(`while kill -0 $PID 2>/dev/null; do sleep 0.1; done; mv new old; exec old`). About 40 lines. -The harder part is **packaging**: an MSI doesn't exist on Linux, so this whole flow assumes a -self-contained tarball / AppImage / portable layout, not a system-managed package. See § Packaging. - -### 7. Registry settings - -`HKCU\...\Run` (start with Windows) → `~/.config/autostart/moneyshot.desktop` with a -`X-GNOME-Autostart-enabled=true` entry. ~20 lines. - -`HKCU\Control Panel\Keyboard\PrintScreenKeyForSnippingEnabled` (suppress Windows Snipping Tool) -→ has no Linux analogue. Different DEs handle PrintScreen differently (GNOME ships its own -screenshot tool bound to PrintScreen; KDE has Spectacle). The setting becomes a no-op on Linux; -document it. - -### 8. Path / filesystem assumptions - -- `%AppData%` → `XDG_CONFIG_HOME` (`~/.config`). `Environment.SpecialFolder.ApplicationData` - resolves to the right thing on .NET / Linux already, so most code is fine. -- `MyPictures` → `XDG_PICTURES_DIR` (`~/Pictures`). Also handled by `SpecialFolder.MyPictures` - on .NET / Linux. -- File-format quirk: nothing to do; PNG/JPEG/BMP encoders are all in Avalonia. +### 2. Capture pipeline — ✅ implemented (X11), Wayland still open + +`MoneyShot.Platform.Linux/LinuxScreenCapture.cs` implements `IScreenCapture` via raw `libX11.so.6` +P/Invoke (`X11Interop.cs`): `XGetImage` against the root window for full-screen and per-monitor +capture (monitor bounds come from shelling out to `xrandr --query` and parsing its stable +plain-text output — deliberately not a `libXrandr` P/Invoke, since xrandr's CLI output format has +been stable for over a decade and this avoids a second native-ABI surface). **Genuinely verified**: +built self-contained for `linux-x64`, run against a real Xvfb X server in Docker, monitor +enumeration and `CaptureFullScreen` confirmed to return correct dimensions/geometry via a +standalone test harness, and a full capture triggered by a real `XGrabKey`-delivered hotkey was +confirmed to render correctly inside `EditorWindow` (screenshotted and visually inspected). + +**Wayland is not implemented.** `XGetImage` against the root window only sees X11/XWayland +content — under a native Wayland session (the default on current GNOME/KDE, meaning current +Debian/Fedora out of the box) there is no root window with real pixels to read, so +`LinuxScreenCapture` will either throw (`XOpenDisplay` fails with no X server at all) or silently +capture nothing useful. The correct fix for native Wayland is the XDG Desktop Portal +`org.freedesktop.portal.Screenshot` D-Bus service, which — critically — requires an interactive, +per-capture consent dialog from the compositor (no instant, silent capture the way Windows/X11 +allow), a real and unavoidable UX change under Wayland policy. This was not implemented: no +portal-backend service was available in any test environment used this session to build and verify +against, and the interactive-consent-dialog UX question is a product decision, not just an +implementation detail. See § Wayland status. + +### 3. Global hotkeys — ✅ implemented (X11), no Wayland equivalent + +`MoneyShot.Platform.Linux/LinuxGlobalHotkeys.cs` implements `IGlobalHotkeys` via `XGrabKey` on the +root window, with a dedicated background thread pumping `XNextEvent` (mirrors +`Win32GlobalHotkeys`'s dedicated message-only window). Each hotkey is grabbed under all four +NumLock/CapsLock modifier permutations (the classic X11 gotcha — a single grab without this +silently stops firing whenever either lock key is toggled on). **Genuinely verified**: a real +`xdotool key Print` synthetic keypress under Xvfb correctly triggered a registered hotkey callback +and ran the full capture flow — this also validated the hand-derived `XKeyEvent` struct field +offsets used to read the keycode/modifier state back out of the raw X11 event buffer, which were +computed by hand from the Xlib ABI and could easily have been wrong without this test. + +**Wayland has no direct equivalent** — compositors deliberately do not let clients grab input +they don't have focus for. The portal `org.freedesktop.portal.GlobalShortcuts` API is the +correct-but-not-implemented path (same reasoning as capture: needs a portal backend to build +against, and changes the binding UX — the user binds the shortcut in system settings, not in +MoneyShot). Under a pure Wayland session, `LinuxGlobalHotkeys.Initialize()` logs a warning and +no-ops rather than crashing (mirrors `Win32GlobalHotkeys`' existing "combination may be in use" +non-fatal pattern) — hotkeys just silently don't fire; the tray menu and in-app buttons remain the +working alternative. + +### 4. System tray (`NotifyIcon`) — ✅ implemented, reuses Avalonia's own cross-platform TrayIcon + +`MoneyShot.UI/Platform/LinuxTrayIcon.cs` wraps Avalonia's own `TrayIcon`/`NativeMenu` classes +(backed by its `Avalonia.FreeDesktop` assembly, which implements StatusNotifierItem D-Bus +registration) rather than hand-rolling the SNI protocol — reusing a framework's tested +implementation beat writing untested D-Bus service code from scratch. **Partially verified**: the +tray icon registers and the app never crashes with or without an SNI host present (confirmed in a +StatusNotifierWatcher-less container), and the menu/click wiring is exercised by the same code +path already proven correct on Windows (`ITrayIcon`, `TrayMenuItem`). **Not verified**: whether the +icon actually *appears and is clickable* in a real desktop environment's panel — no test +environment this session had a running desktop shell (GNOME Shell, Plasma, etc.) to check against. +Known ecosystem gap either way: **vanilla GNOME Shell needs the "AppIndicator and +KStatusNotifierItem Support" extension** for any SNI tray icon to show at all (ships by default on +Ubuntu, not on stock Fedora Workstation) — not a MoneyShot bug, a real Linux desktop fragmentation +issue every cross-platform tray-icon app hits. + +### 5. Clipboard image support — ✅ implemented and verified end-to-end + +`MoneyShot.Platform.Linux/LinuxClipboard.cs` PNG-encodes the `CapturedImage` buffer via SkiaSharp +(already a project dependency) and pipes it to `wl-copy --type image/png` (Wayland, detected via +`$WAYLAND_DISPLAY`) or `xclip -selection clipboard -t image/png` (X11) — CLI shellout rather than +Avalonia's own clipboard API, since Avalonia's cross-platform clipboard image support was less +predictable than two well-established, single-purpose CLI tools. **Genuinely verified**: a +standalone test harness called `LinuxClipboard.SetImage()` with a real `CapturedImage`, and reading +the X11 clipboard back afterward (`xclip -o -t image/png`) produced a byte-valid PNG that visually +matched the source image exactly (solid color test image, confirmed pixel-correct on inspection). +Only the X11/`xclip` path was live-tested this way — the Wayland/`wl-copy` branch shares the same +encode step and near-identical invocation shape but wasn't separately exercised (no Wayland +compositor with a clipboard manager was available to test against). + +### 6. Auto-update self-swap — not implemented + +`AutoUpdateService.BuildWindowsSwapScript`'s exe-swap batch script is Windows-only and has no +Linux port yet — `MoneyShot.UI`'s "Check for Updates" flow will call it on Linux and it will fail +(this was not touched this session; auto-update was out of scope for the platform-layer/packaging +work described here). Bigger than the shell-script rewrite itself: a `.deb`/`.rpm`-installed binary +lives under `/opt/moneyshot`, owned by the package manager — self-overwriting it the way the +Windows MSI-installed exe does would fight `apt`/`dnf` on the next `upgrade`. The auto-updater +needs to detect a package-managed install and refuse ("update via your package manager instead") +rather than attempt a self-swap; only the AppImage build is a legitimate self-update candidate. +**This is a real, currently-open gap** — someone clicking "Check for Updates" on a `.deb`/`.rpm` +install today will hit an unhandled failure path, not a graceful "not supported here" message. + +### 7. Registry settings — ✅ implemented + +`MoneyShot.Platform.Linux/LinuxAutoStart.cs` implements `IAutoStart.SetStartupWithApp` by writing/ +removing `~/.config/autostart/moneyshot.desktop` (the standard freedesktop.org XDG autostart +mechanism, honored by GNOME/KDE/XFCE without any DE-specific code) using the same `AppDataPaths` +config-root resolver as everything else (see § AppDataPaths bug below). `SetPrintScreenSuppressed`/ +`TryGetPrintScreenSuppressed` correctly no-op (there's no single "the OS's screenshot shortcut" to +suppress on Linux — GNOME/KDE each bind PrintScreen to their own tool independently) — verified via +code review of the call site (`SettingsWindow`) to confirm a permanently-false result from +`SetPrintScreenSuppressed` doesn't surface a misleading "Partial Success — reopen as admin" +Windows-flavored dialog on every settings save (it did, originally; fixed alongside this work). +Not separately UI-tested (no interactive Linux desktop session to click through Settings on), but +the underlying file I/O is simple enough, and shares the now-verified `AppDataPaths` path +resolution, that this has reasonably high confidence without that direct click-through. + +### 8. Path / filesystem assumptions — ⚠️ real bug found and fixed + +This document originally assumed `Environment.SpecialFolder.ApplicationData` "resolves to the +right thing on .NET / Linux already." **That assumption was wrong, and only actual execution on +Linux caught it**: confirmed via a minimal standalone test program that it returns an **empty +string** whenever `$XDG_CONFIG_HOME` isn't set in the environment — which is not a rare edge case, +it's the default in plenty of real launch contexts (minimal window managers, some `.desktop` `Exec` +launches, and every container/CI environment used to verify this port). Left unguarded, this meant +`SettingsService`, `Logger`, and `HistoryService` were all silently writing into a *relative* +`MoneyShot/` folder under whatever the process's working directory happened to be at startup — +confirmed by finding real history files landing at `/app/MoneyShot/history/...` instead of +`~/.config/MoneyShot/history/...` in an early test run. Fixed with a shared +`MoneyShot.Core/Services/AppDataPaths.GetConfigRoot()` (uses the OS value if non-empty, else +`$XDG_CONFIG_HOME`, else `~/.config`, per the XDG Base Directory Specification's own documented +fallback) that all three services and `LinuxAutoStart` now call instead of the raw +`Environment.GetFolderPath` call — re-verified afterward: history and settings correctly land +under `~/.config/MoneyShot/` in the same test environment that first exposed the bug. ## Architecture for the port @@ -204,17 +214,27 @@ MoneyShot.Platform.Windows ├── Win32TrayIcon // current NotifyIcon usage └── … -MoneyShot.Platform.Linux -├── X11ScreenCapture -├── X11GlobalHotkeys -├── LinuxTrayIcon // delegates to Avalonia.Controls.TrayIcon -├── LinuxAutoStart // .desktop file management -└── … +MoneyShot.Platform.Linux // net10.0, no Avalonia dep — mirrors Platform.Windows staying WPF-free +├── LinuxScreenCapture // XGetImage + xrandr-parsed monitor bounds +├── LinuxGlobalHotkeys // XGrabKey + XNextEvent pump +├── LinuxAutoStart // ~/.config/autostart/*.desktop +└── LinuxClipboard // SkiaSharp PNG-encode + wl-copy/xclip shellout + +MoneyShot.UI/Platform // depends on Avalonia, so lives in MoneyShot.UI, not Platform.Linux +├── PlatformServices.cs // #if WINDOWS branch picks Win32*/Linux* — see below +└── LinuxTrayIcon.cs // wraps Avalonia.Controls.TrayIcon/NativeMenu ``` -A `PlatformServices.Resolve()` static returns the right implementations based on -`OperatingSystem.IsWindows()` / `IsLinux()`. No DI container needed; matches the existing -"new the services in MainWindow constructor" pattern from `CLAUDE.md`. +**What was actually built, differs slightly from the plan above**: `PlatformServices` is not a +runtime `OperatingSystem.IsWindows()` check — it's a **compile-time** `#if WINDOWS` branch in +`MoneyShot.UI/Platform/PlatformServices.cs`, gated by a `WINDOWS` constant `MoneyShot.UI.csproj` +defines only for its `net10.0-windows` `TargetFramework`. This was chosen over a runtime check +because the two TFMs don't even reference the same platform project (`net10.0-windows` references +`MoneyShot.Platform.Windows`; plain `net10.0` references `MoneyShot.Platform.Linux` — a `net10.0` +build has no `Win32*` types to construct in the first place, so a runtime check alone wouldn't +compile). `dotnet build`/`publish` without `-f` builds both TFMs from one `dotnet build +MoneyShot.sln`; CI/publishing picks one via `-f net10.0-windows -r win-x64` or +`-f net10.0 -r linux-x64`. ## Migration phases @@ -245,7 +265,7 @@ above, and abstracting them now would have meant designing around a UI framework isn't actually in the dependency tree yet. `SaveService` does now take an `IClipboard` so its clipboard write goes through the platform abstraction; file saving is unchanged. -**Phase 1 — UI port to Avalonia, still Windows-only. 🟡 Built, partially verified (2026-09).** +**Phase 1 — UI port to Avalonia, still Windows-only. 🟡 Built, substantially verified (2026-09).** `MainWindow`, `EditorWindow`, `HistoryWindow`, `RegionSelector`, `SettingsWindow` were all ported to `*.axaml` in a new, additive `MoneyShot.UI` project (net10.0-windows for now — see below) that sits alongside the shipping WPF app without touching it. `CocoaTheme.axaml` re-implements the WPF @@ -256,28 +276,110 @@ Avalonia's `Geometry.FillContains`/`StrokeContains` (used for arrow hit-testing) equivalents and the project compiles clean using them. *What's actually verified, and how:* the whole solution builds with zero errors/warnings, the -Avalonia build launches and stays responsive (checked via process inspection), and `MainWindow` -was confirmed **visually correct by actually running it and inspecting a screenshot** — the -cocoa-brown theme, custom borderless title bar with working minimize/maximize/close, the accent -capture buttons, icon rendering, and the dynamically-generated per-monitor button list (correctly -detected 3 monitors and labeled the primary) all render as designed. - -*What is NOT verified* — this was built and made to compile, but nobody has clicked through it: -- `EditorWindow` is the highest-risk file in the entire port (2000+ lines, the most stateful - mouse-interaction code in the app — see CLAUDE.md's "Resize/drag" notes on past WPF regressions - in this exact logic). None of drawing, selecting, dragging, resizing (box or endpoint), undo, - crop, zoom/pan, pixelate, or the async save/color/text dialogs have been interactively tested. -- `SettingsWindow`, `HistoryWindow`, `RegionSelector` compile but haven't been opened. -- Global hotkeys, the tray icon and its context menu, and the actual capture-to-editor flow have - not been triggered end-to-end. -- A thin sliver of residual native chrome was visible above the custom title bar in the one - screenshot taken — likely related to Avalonia 12's `ExtendClientAreaChromeHints` removal (see - implementation note below); cosmetic, not investigated further. - -None of this was possible to close out further in the session that built it — no computer-use/UI -automation tooling was available to click through the app, only process inspection and one -manually-captured screenshot. **Manual interactive testing of the above is required before trusting -this build for anything beyond "it starts and MainWindow looks right."** +Avalonia build launches and stays responsive, and `MainWindow` was confirmed **visually correct by +actually running it and inspecting a screenshot** (both the user's own and one captured via +`user32.dll PrintWindow` from an automation script, since no computer-use/UI-automation tool was +available in-session — see below) — the cocoa-brown theme, custom borderless title bar with +working minimize/maximize/close, the accent capture buttons, icon rendering, and the +dynamically-generated per-monitor button list all render as designed. + +Beyond that, **real interactive testing found two genuine, confirmed bugs — both fixed**: + +1. **The entire capture→editor flow was broken.** `CaptureFullScreenAsync`/`CaptureRegionAsync`/ + `CaptureMonitorAsync` all call `Hide()` on `MainWindow` before capturing (so the app doesn't + appear in its own screenshot), then used to call `EditorWindow.ShowDialog(this)` — but Avalonia + throws `InvalidOperationException: Cannot show window with non-visible owner` if the owner + isn't currently shown. WPF has no such restriction, so this never surfaced until the build was + actually clicked through. The same bug hit the error-handling path too: the `catch` block's own + `SimpleMessageBox.ShowAsync(this, ...)` call used the same hidden owner and threw the identical + exception, which — because `CaptureFullScreenAsync` runs fire-and-forget from a button/hotkey + handler with no outer catch — became an unobserved task exception. Net effect: click "Capture + full screen", the window vanishes, and nothing else ever happens; the process stays alive and + "Responding" the whole time, which is part of why this needed an actual click-through (and the + app's own log file) to catch rather than process inspection alone. + + Fixed with a new `MoneyShot.UI.Interop.WindowExtensions.ShowAsDialogAsync(owner)`: uses the + real `ShowDialog(owner)` when the owner is visible (proper modality), falls back to + `Show()` + await-on-`Closed` otherwise. Applied everywhere a window used to call + `ShowDialog(this)` with `MainWindow` as owner (`EditorWindow`, `SettingsWindow` — the latter + also reachable from the tray menu while hidden — and `RegionSelector`, whose confirmed/cancelled + result now comes from reading its existing `CroppedScreenshot` property afterward rather than a + typed dialog-result, since the fallback path has no way to recover that value). + `SimpleMessageBox` was simplified to always use `Show()` + `Topmost` — a message box doesn't + need strict modality against its owner, so this sidesteps the constraint entirely rather than + needing the visible/hidden fallback logic. + +2. **History thumbnail generation threw on every save.** `Bitmap.CreateScaledBitmap` throws + `Invalid source bitmap type` when the source is a `WriteableBitmap` — which is what every + capture produces (`CapturedImage.ToAvaloniaBitmap()`). This was caught internally (History + saving degrades to "silently no thumbnail" rather than crashing the capture), but a **second, + more serious bug rode along with it**: the old code's fast path for "image already small enough, + no scaling needed" returned the *same* `Bitmap` object passed in, which the caller's + `using (var thumbnail = ...)` would then dispose — silently corrupting the caller's own + `image`/`screenshot` object (the one about to be shown in `EditorWindow`) for any capture at or + under 400px wide. Fixed by rewriting `HistoryService.CreateThumbnail` to downsample via raw + pixel nearest-neighbor sampling on the `CapturedImage` buffer (reusing the same pattern already + proven correct elsewhere in the port) and to always return a genuinely distinct `Bitmap`, never + an alias of the source. + +*Re-confirmed end-to-end after the fixes above, in a later session* — once the in-session +automation channel (raw `user32.dll` mouse/keyboard injection and `Graphics.CopyFromScreen`, the +only options available; no dedicated computer-use tool was present) recovered in a fresh process, +every flow the earlier pass had flagged as unconfirmed was actually driven end-to-end against a +freshly-built exe, watching the app's log file for exceptions after each step: +- **Capture full screen → `EditorWindow`**: completes with no exception (the log entry from the + pre-fix run, timestamped earlier the same day, was compared directly against a clean run + afterward — same code path, no error). The captured image renders correctly and sharply in the + editor canvas, not just "the window appears." +- **Drawing + undo** in `EditorWindow`: selecting the Rectangle tool and dragging produced a + correctly-positioned, correctly-styled (color/stroke) shape; Undo removed it and correctly + disabled itself again. Closing the editor via the title-bar close button returned cleanly to + `MainWindow`'s hidden tray state with no stray window and no crash — confirming the + `ShowAsDialogAsync` → `TaskCompletionSource`/`Closed` fallback path itself works, not just that + the exception it replaces no longer fires. +- **Tray icon**: double-click correctly shows `MainWindow` again (`MainWindowTitle` became "Money + Shot"); right-click renders the full context menu (Capture Full Screen, Capture Region, History, + Check for Updates, Settings, Show Window, Exit) with correct items and grouping; Exit shut the + process down cleanly (confirmed via the log and process list) — a genuine test of the tray's + `DoubleClicked` event and menu wiring, not just that `Win32TrayIcon` constructs without throwing. +- **`HistoryWindow`**: opens from `MainWindow`'s History button, lists all 50 real captures with + correctly-rendered thumbnails — a direct, real-data confirmation that the thumbnail-generation + fix (bug 2, above) actually works, not just that it compiles. Clicking a thumbnail opens it in + `EditorWindow` (the other `ShowAsDialogAsync` call site) with the historical image loaded + correctly; closing that editor returns to `HistoryWindow`, and closing `HistoryWindow` returns to + `MainWindow` — the window stack unwinds correctly through three layers. +- **`SettingsWindow`**: opens from `MainWindow`'s Settings button and renders fully — all six + General checkboxes, the two hotkey dropdowns (showing the actual configured values, e.g. + "Ctrl+PrintScreen"), and the "Individual monitor capture" section correctly detecting and + reporting "Only one monitor detected" for this machine. Closed via Cancel to avoid touching real + settings. +- **`RegionSelector`**: opens from `MainWindow`'s Capture Region button showing the "Drag to select + a region · Esc to cancel" overlay; dragging a region correctly crops to just the dragged + rectangle and opens it in `EditorWindow` — confirming the ported DPI-aware crop logic runs + end-to-end (though this machine is single-monitor at 100% scaling, so it does not exercise the + 125%-scaling arithmetic itself — see the open item below). + +*What is still NOT verified* — everything above was driven on a single 100%-DPI display; nothing +about `EditorWindow`'s tool interactions beyond basic rectangle draw+undo was exercised: +- Selecting/dragging/moving existing elements, resizing (both the 8-handle box mode and the + 2-handle Line/Path endpoint mode), Crop, Zoom/Pan, Pixelate, Text/Number tools, and the async + Save-to-file / Copy-to-clipboard / color-picker dialogs — none of these have been interactively + tested. This is still the highest-risk area of the port: 2000+ lines of the most stateful + mouse-interaction code in the app (see CLAUDE.md's "Resize/drag" notes on past WPF regressions in + this exact logic), and none of those specific behaviors have been re-derived for Avalonia's + pointer-event model yet. +- Global hotkeys (e.g. actually pressing PrintScreen to trigger a capture) — the menu item and + registration path exist, but the `WM_HOTKEY` message-window flow itself hasn't been triggered. +- Multi-monitor and 125%-scaled-DPI behavior specifically (this session's test machine is + single-monitor, 100% scaling) — the RegionSelector crop was confirmed correct at 100% scale only. +- "Check for Updates" and "About" dialogs haven't been opened. +- A thin sliver of residual native chrome was visible above the custom title bar in one early + screenshot, absent in later ones — likely related to Avalonia 12's `ExtendClientAreaChromeHints` + removal (see implementation note below); intermittent, not investigated further. + +**Manual interactive testing of the `EditorWindow` tool-interaction gap above, plus hotkeys and +multi-monitor/DPI-scaled behavior, is still required before trusting this build beyond what's now +confirmed: startup, both capture paths end-to-end, History, Settings, and the tray icon.** Implementation notes for whoever continues from here: - `MoneyShot.UI` targets `net10.0-windows`, not the bare `net10.0` the architecture diagram above @@ -313,95 +415,230 @@ Implementation notes for whoever continues from here: `Screens` API exposes each monitor's scale factor directly (`Screen.Scaling`), avoiding the Win32 `GetDpiForMonitor` P/Invoke the WPF fix needed. -**Phase 2 — Linux platform implementations.** X11 capture, X11 hotkeys, Linux autostart, Linux -clipboard, Linux tray. Test on at least: Ubuntu 24.04 + KDE Plasma 6, Fedora + GNOME, Arch + i3. -**3–4 weeks.** - -**Phase 3 — Packaging.** AppImage for portability, `.deb` for Ubuntu/Debian users, `.rpm` for -Fedora users. AUR PKGBUILD for Arch is community-maintainable. Add a `release-linux.yml` GitHub -Actions workflow that builds these on `ubuntu-latest`. Sign the AppImage. **1–2 weeks.** - -**Phase 4 — Wayland (deferred).** Portal capture, GlobalShortcuts portal where available, MMB -panning still works (already added in this branch). **2–3 weeks if pursued.** +**Phase 2 — Linux platform implementations. ✅ Done, substantially verified against real Linux +(2026-09).** `MoneyShot.Platform.Linux` implements `IScreenCapture`/`IGlobalHotkeys`/`IAutoStart`/ +`IClipboard` (X11/XDG-based — see § 2–5, 7 above for what's implemented, what's Wayland-only-open, +and exactly how each was verified). `MoneyShot.UI` now multi-targets `net10.0-windows;net10.0` +with TFM-conditional `ProjectReference`s and a `#if WINDOWS`-gated `PlatformServices` factory (see +§ Architecture above) instead of the hardcoded `new Win32ScreenCapture()` etc. calls Phase 1 left +in `MainWindow`/`SettingsWindow`/`EditorWindow`/`HistoryWindow`. + +Testing environment actually used (no dedicated Linux desktop machine was available): **WSLg** +(gives a real, if minimal, Wayland/X11 session with a working session D-Bus but no desktop-shell +services — no portal backend, no StatusNotifierWatcher) for early sanity checks, and **Docker** +(`debian:bookworm` and `fedora:latest` containers with `Xvfb` for a genuine headless X server) for +everything that needed either root/package-install access WSL's sudo blocked, or a real X11 +`XGetImage`/`XGrabKey` target. This combination gave much higher confidence than a code-review-only +pass, but is explicitly **not** the same as testing on a real GNOME/KDE desktop session — see the +per-item "genuinely verified" notes in § 2–8 above for exactly what each test did and didn't cover, +and the top-of-document status block for the honest summary of what's still open. + +**Three real, non-obvious bugs found this way** (i.e., invisible from a clean compile, only found +by actually running the published binary): +1. **`SkiaSharp.NativeAssets.Linux` resolved transitively to `3.119.4`** (via `Avalonia.Skia`'s + own dependency graph) while the explicit managed `SkiaSharp` package this project also + references is `4.151.2` — API-incompatible, and the mismatch only throws at runtime + (`SKImageInfo`'s static constructor, `"the version of the native libSkiaSharp library (119.0) + is incompatible..."`) with no compile-time signal at all. Confirmed the equivalent Windows + native asset happened to already resolve to the matching `4.151.2` (so this was silent on + Windows purely by luck of the transitive-version-resolution dice, not because Windows is + actually safe from the same class of bug). Fixed by explicitly pinning + `SkiaSharp.NativeAssets.Linux` to `4.151.2` in both `MoneyShot.UI.csproj` and + `MoneyShot.Platform.Linux.csproj`. +2. **`Environment.SpecialFolder.ApplicationData` resolves to an empty string on Linux** whenever + `$XDG_CONFIG_HOME` isn't set — see § 8 above. Silently scattered settings/history/logs into a + relative path under the process's working directory instead of `~/.config/MoneyShot`. Fixed + with the new `AppDataPaths.GetConfigRoot()` helper, applied everywhere the raw + `Environment.GetFolderPath(...ApplicationData)` call used to appear (`SettingsService`, + `Logger`, both `HistoryService`s, `LinuxAutoStart`). +3. **A genuinely fresh Debian container lacked `libssl3`**, which .NET's crypto/TLS stack needs + — the app aborted immediately with `"No usable version of libssl was found"`. This was masked + in the first round of container testing because earlier `apt-get install`s for unrelated tools + had pulled it in transitively; only testing in a truly clean container (matching what a real + user's first-ever `apt install ./moneyshot.deb` looks like) surfaced it. Fixed by adding + `libssl3` (`openssl-libs` on Fedora) to both packages' declared dependencies — see § Packaging. + +**What's genuinely verified end-to-end** (built as a self-contained `linux-x64` publish, actually +executed, not just compiled): app startup with no crash (including named-`Mutex` single-instance +detection, which does work correctly cross-platform, confirmed via the mutex's backing file +appearing under `/tmp/.dotnet/shm/`); a real `XGrabKey`-delivered `PrintScreen` hotkey firing +`CaptureFullScreenAsync` → `LinuxScreenCapture.CaptureFullScreen()` (`XGetImage`) → `EditorWindow` +opening with the captured content rendered correctly (screenshotted and visually confirmed — +CocoaTheme renders pixel-identical to the already-verified Windows build); `HistoryService` +correctly saving both the full image and thumbnail to the now-fixed correct path; monitor +enumeration via `xrandr` parsing returning correct geometry; `LinuxClipboard.SetImage()` round- +tripping a real PNG through `xclip` byte-for-byte correct. + +**What's not verified**: Wayland-native capture/hotkeys (not implemented — see § 2, § 3); the tray +icon's actual on-screen appearance/clickability in a real desktop panel (no desktop shell was +available to test against, only "doesn't crash without one" was confirmed); `RegionSelector`'s +drag-to-crop interaction specifically on Linux (confirmed on Windows this session, and the region- +capture hotkey path was confirmed to correctly open the selector on Linux, but no synthetic drag +was sent to confirm the crop itself on Linux); `EditorWindow`'s deeper tool interactions (resize, +crop, zoom/pan, pixelate, text/number tools, save-to-file/color-picker dialogs) — verified on +Windows this session (see § Phase 1), not separately re-driven on Linux; multi-monitor behavior +(every test environment was single-virtual-monitor); the `wl-copy`/Wayland clipboard branch +specifically (only the `xclip`/X11 branch was live-tested — see § 5); and `LinuxAutoStart`'s actual +file writes triggered via the Settings UI (the underlying `AppDataPaths`-based path resolution is +verified, the UI click-through isn't). + +**Phase 3 — Packaging. ✅ Done, verified via real install + launch in clean containers (2026-09).** +`Packaging/linux/` holds `moneyshot.desktop` (shared), `build-deb.sh`, `build-rpm.sh` + +`rpm/moneyshot.spec`, and `build-appimage.sh` — each takes a self-contained `linux-x64` publish +directory and produces one package, installing everything under `/opt/moneyshot` with a thin +`/usr/bin/moneyshot` launcher script (self-contained .NET publishes carry their own runtime, so +this avoids scattering dozens of DLLs into `/usr/lib`), a `.desktop` entry, and a hicolor icon. +`AutoReqProv`/no automatic `.so` dependency scanning is disabled for the RPM (correct for a +self-contained runtime bundle that carries its own copies of many libraries) in favor of an +explicit, hand-verified `Requires`/`Depends` list. + +**Verified, not just built**: `.deb` — built with `dpkg-deb`, then actually `apt-get install +./moneyshot.deb`'d in a **completely fresh** `debian:bookworm` container (not the dev container +used to build it), which correctly auto-resolved every declared dependency, and the installed +`moneyshot` command launched cleanly under Xvfb with zero errors. `.rpm` — built with `rpmbuild` +**on a real Fedora 44 container** (not cross-built from Debian, to get authoritative macro/dist-tag +behavior), then `dnf install`'d in the same container, again auto-resolving dependencies from +Fedora's repos, and launched cleanly. **AppImage** — built by hand-assembling the AppDir (no +`linuxdeploy`: its plugin ecosystem is built around discovering `.so` dependencies via `ldd` for +dynamically-linked C/C++ apps, which has nothing useful to do for an already-self-contained .NET +publish) and running `appimagetool --appimage-extract-and-run` (avoids needing FUSE, which isn't +set up on GitHub-hosted runners or plain Docker containers by default); the resulting `.AppImage` +ran cleanly via the same extract-and-run mode. + +A real bug was caught specifically by testing the **exact relative-path invocation pattern the CI +workflow uses** (`./publish-linux` rather than an absolute path, matching how a workflow step's +`run:` block naturally refers to files): `build-rpm.sh` broke because `rpmbuild`'s `%install` +step runs from its own internal `BUILD` directory, not the caller's `cwd`, so a relative +`_moneyshot_publish_dir` macro resolved against the wrong directory and failed with "No such file +or directory." (`build-deb.sh` and `build-appimage.sh` don't `cd` internally and were unaffected.) +Fixed by resolving `PUBLISH_DIR`/`OUTPUT_DIR` to absolute paths (`cd "$dir" && pwd`) at the top of +`build-rpm.sh`, then re-verified with the exact relative-path CI pattern. + +`.github/workflows/build-linux.yml` (new) mirrors `build.yml`'s PR/release triggers, building and +packaging all three formats and uploading them as workflow artifacts (and as release assets when +triggered by a GitHub Release). `release.yml`'s existing auto-release-on-push-to-main flow gained +a second job, `build-and-release-linux`, that runs after the Windows job, recomputes the identical +version tag, and attaches the same three Linux packages (plus a `SHA256SUMS-linux.txt`) to that +same release — mirroring how the Windows job attaches its MSI/zip/`SHA256SUMS.txt`. **Not +verified**: an actual GitHub Actions run of either workflow (only manually replayed the same +command sequence locally/in Docker) — YAML syntax was validated with a real parser, and every +individual step's shell commands were run for real, but the workflow files themselves have not +executed inside GitHub's own runner infrastructure yet. AUR (Arch) packaging remains +community-maintainable but wasn't built here. + +**Phase 4 — Wayland (deferred, still not started).** Portal-based `org.freedesktop.portal. +Screenshot` capture and `org.freedesktop.portal.GlobalShortcuts` hotkeys are the correct paths — +see § 2 and § 3 for exactly what's missing and why it wasn't attempted this round (no portal +backend service was available in any environment used to build/verify this port, and the +interactive-consent-dialog UX change is a product decision that should be made deliberately, not +implemented blind). **2–3 weeks if pursued**, unchanged from the original estimate — nothing done +in Phase 2/3 reduces this, since Wayland capture/hotkeys are architecturally a different mechanism +(D-Bus/portal) from the X11 approach actually implemented, not an extension of it. + +## Wayland status (read this before deploying to Debian/Fedora desktop users) + +**Both current Debian (12, "bookworm," GNOME on Wayland by default) and Fedora Workstation default +to a native Wayland session out of the box.** On such a session, *as currently implemented*: +- Screen capture will fail (`XOpenDisplay` finds no X server) unless the user is on an X11/Xorg + session, or a compositor exposing enough of an XWayland-visible surface for `XGetImage` to + return something meaningful (untested; likely to be incomplete or wrong even when it doesn't + outright fail). +- Global hotkeys silently do nothing (logged once, then quiet) — the tray menu and in-app capture + buttons remain fully functional as the fallback. +- The tray icon, clipboard, and autostart all work regardless of X11 vs. Wayland — none of those + three depend on the display-server-specific mechanisms above. + +**Practically**: this build is genuinely useful today for X11 sessions (still selectable at the +login/display-manager screen on virtually every mainstream distro, including Debian and Fedora, +even where Wayland is the default) and for the parts of a Wayland session that don't touch capture/ +hotkeys. It is **not** a full drop-in replacement for the Windows experience on a default modern +Wayland desktop until Phase 4 lands. This should be stated plainly in any release notes / README +for the Linux build, not discovered by users via a silent capture failure. ## Packaging on Linux -| Format | Audience | Effort | +| Format | Audience | Status | |---|---|---| -| **AppImage** | Distro-agnostic, easy for end users. The "MSI equivalent" closest to today's UX. Ships its own .NET runtime in the bundle. | Low — `linuxdeploy` + `appimagetool` in CI | -| **`.deb`** | Ubuntu, Debian, Mint | Low — `dpkg-deb --build` of a templated package skeleton | -| **`.rpm`** | Fedora, openSUSE | Low — `rpmbuild` | -| **Flatpak** | Modern desktops, sandboxed | Medium — needs a manifest, integrates with portals "for free" which would help Wayland support | -| **Snap** | Ubuntu primarily | Medium — and politically charged; many Linux users dislike snaps | -| **AUR (PKGBUILD)** | Arch | Trivial — community-maintained | - -Recommendation: ship **AppImage + `.deb` + `.rpm`** in v1, plus an AUR PKGBUILD recipe. Skip -Flatpak/Snap until there's user demand. +| **`.deb`** | Ubuntu, Debian, Mint | ✅ Built (`Packaging/linux/build-deb.sh`) and verified: `apt-get install`'d in a clean `debian:bookworm` container, dependencies auto-resolved, launched cleanly. | +| **`.rpm`** | Fedora, openSUSE | ✅ Built (`Packaging/linux/build-rpm.sh` + `rpm/moneyshot.spec`) and verified: `dnf install`'d on real Fedora 44, dependencies auto-resolved, launched cleanly. | +| **AppImage** | Distro-agnostic, easy for end users, self-updating candidate. | ✅ Built (`Packaging/linux/build-appimage.sh`, hand-assembled AppDir, no `linuxdeploy`) and verified: ran cleanly via `--appimage-extract-and-run`. | +| **Flatpak** | Modern desktops, sandboxed | Not built. Would integrate with the Wayland portals "for free" — worth revisiting alongside Phase 4. | +| **Snap** | Ubuntu primarily | Not built — politically charged; many Linux users dislike snaps. | +| **AUR (PKGBUILD)** | Arch | Not built — community-maintainable, low priority. | + +`.github/workflows/build-linux.yml` builds and uploads all three verified formats on every PR and +release; `release.yml`'s `build-and-release-linux` job attaches them to the same auto-created +release the Windows MSI/zip go to (see § Phase 3 above for exactly what was and wasn't verified +about the CI wiring itself, as opposed to the packaging scripts it calls). ## Risks & open questions -- **Avalonia drawing fidelity.** The pixelate effect uses `RenderTargetBitmap.Render(Visual)` to - rasterise the scene at native resolution and sample colour blocks. Avalonia's - `RenderTargetBitmap` exists with the same API but I have not verified that - `BitmapSource.CopyPixels`-style sampling works identically. Needs a spike in Phase 1. -- **GDI handle leak pattern.** `ScreenshotService.ConvertToBitmapSource` does the canonical - `GetHbitmap` → `CreateBitmapSourceFromHBitmap` → `DeleteObject` dance. There is no equivalent - on Linux because there are no GDI handles; the X11 path produces a managed pixel buffer - directly. Less complex, but it means the existing comment about handle leaks doesn't carry - over and fresh testing for native-memory leaks is needed. -- **Hotkey collisions with the desktop environment.** PrintScreen is bound by every major DE - to its own screenshot tool. On Windows we have a registry switch to disable Snipping Tool; - on Linux we'd have to instruct the user to unbind it themselves. This is friction we cannot - eliminate. -- **Single-instance enforcement.** `App.OnStartup` uses a named `Mutex` for single-instance - detection. Named mutexes are local-machine and global on Windows; on Linux the equivalent is - a pidfile under `XDG_RUNTIME_DIR` or a `flock`'d file under `~/.config`. ~10 lines. -- **Auto-update under package managers.** If a user installs via `.deb`/`.rpm`, the auto-updater - must not silently overwrite a system-managed binary. The portable AppImage flow can self-update; - the deb/rpm flow should check whether the binary is writable and bail out with "use your - package manager" if not. This logic is missing today (Windows: always writable inside MSI's - install dir under our user) and needs adding. -- **HiDPI / fractional scaling.** WPF handles this transparently. Avalonia mostly does, but - fractional scaling on KDE/GNOME has known rough edges, especially around `RenderTargetBitmap` - resolution selection. Worth an early spike. +Resolved by actually building and testing (kept here for the record, not because they're still +open): **Avalonia drawing fidelity** — CocoaTheme and the capture→editor rendering path are +confirmed pixel-correct on real Linux (see Phase 1/2 above); pixelate specifically wasn't +separately re-driven on Linux, folded into the general `EditorWindow` tool-interaction gap. +**GDI handle leaks** — moot, `LinuxScreenCapture` never touches a GDI-equivalent handle at all. +**Single-instance enforcement** — a plain named `Mutex` (no `Global\` prefix) works correctly +cross-platform as-is; confirmed via its backing file appearing under `/tmp/.dotnet/shm/` on a real +run. No pidfile/flock rewrite was needed. + +Still genuinely open: +- **Hotkey collisions with the desktop environment.** PrintScreen is bound by every major DE to + its own screenshot tool. Windows has a registry switch to disable Snipping Tool's claim on it; + Linux has no equivalent, and the user would need to unbind it themselves in their DE's settings. + Real, unavoidable friction — not something a code change fixes. +- **Auto-update under package managers.** Confirmed still missing (see § 6 above) — a `.deb`/`.rpm` + install's "Check for Updates" will hit an unhandled failure today rather than a graceful + "update via your package manager" message. The portable AppImage is the only build that could + legitimately self-update. +- **HiDPI / fractional scaling on Linux.** Every test environment this round was 100%-scale, + single-monitor. `RegionSelector`'s DPI-aware crop math (already fixed for WPF's 125%-scaling + bug, see `Opus-Speaks.md` § E2, and ported into the Avalonia build using `Screens.Primary. + Scaling`) has not been exercised at a non-100% Linux scale factor at all. +- **Wayland** — see § Wayland status above; this is the single largest remaining gap. ## Decision matrix for the team -| Effort | Reach | Recommendation | -|---|---|---| -| 8–14 weeks dev + ongoing maintenance of two platforms | Adds an estimated low-single-digit % of users (Linux desktop share) | **Worth it only if** there's strategic value (e.g. a corporate deployment that requires it), the team has Linux expertise, or contributor enthusiasm exists. For a hobby/small project, the maintenance tax across two display servers and three init flavors is real and ongoing. | - -If a port is greenlit, **start with Phase 0** (interface extraction) — that work is valuable -even if Linux is later cancelled, because it makes the codebase testable and removes implicit -Win32 coupling. - -## Files that will need to change (concrete list) - -These paths exist today and will be touched in any port. Not exhaustive but covers the bulk: - -- `MoneyShot/MoneyShot.csproj` — change TFM to `net10.0` (no `-windows`), drop - ``, add Avalonia package references, remove `Microsoft.WindowsDesktop.App.WindowsForms` -- `MoneyShot/Services/ScreenshotService.cs` — full rewrite per platform -- `MoneyShot/Services/HotKeyService.cs` — full rewrite per platform -- `MoneyShot/Services/SettingsService.cs` — strip `Microsoft.Win32.Registry` calls; route - `SetStartupWithWindows` through a new `IAutoStart` interface -- `MoneyShot/Services/AutoUpdateService.cs` — replace `BuildWindowsSwapScript` with - per-platform script generation; respect package-manager-managed installs -- `MoneyShot/Services/SaveService.cs` — swap `BitmapEncoder` namespace from WPF to Avalonia -- `MoneyShot/Services/HistoryService.cs` — same encoder swap -- `MoneyShot/MainWindow.xaml` + `.cs` — port to Avalonia `axaml`; replace `NotifyIcon` with - `Avalonia.Controls.TrayIcon` -- `MoneyShot/Views/EditorWindow.xaml` + `.cs` — port to Avalonia; verify `Canvas`/`Shape`/`Path` - semantics match; `Clipboard.SetImage` swap; `RenderTargetBitmap` API delta -- `MoneyShot/Views/HistoryWindow.xaml` + `.cs` — port to Avalonia -- `MoneyShot/Views/RegionSelector.xaml` + `.cs` — port to Avalonia; X11 needs special handling - for "fullscreen overlay across multiple monitors" (it works, but `WindowState=Fullscreen` - semantics differ) -- `MoneyShot/Views/SettingsWindow.xaml` + `.cs` — port to Avalonia -- `MoneyShot/App.xaml` + `.cs` — replace `Application` base with `Avalonia.Application`; - switch single-instance mutex to pidfile on Linux -- `Installer/Product.wxs` — Windows-only, leave alone; add new packaging templates beside it -- `.github/workflows/release.yml` — add Linux build matrix (ubuntu-latest job producing - AppImage + deb + rpm) -- `MoneyShot.Tests/` — drop the `-windows` TFM, audit any test that touches `System.Windows` - types directly +The build/no-build decision this table originally framed is now moot — Phases 0–3 are done. What's +left is a narrower question: **is Wayland support (Phase 4) worth 2–3 more weeks**, given the port +already works on X11 sessions (still selectable at login on virtually every mainstream distro) and +X11-independent features (tray, clipboard, autostart, packaging) work regardless of session type. +That's a product call — how many target users are on a Wayland-only setup with no X11 fallback — +not an engineering-feasibility one; the engineering path (portal-based capture + GlobalShortcuts, +with an interactive per-capture consent dialog as an unavoidable UX change) is understood and +documented above, just not built. + +## What actually changed (concrete list) + +Reflects what was actually done, not a pre-port plan — the shipping WPF app (`MoneyShot/`) was +**never modified for Linux support**; everything below is additive (`MoneyShot.UI`) or shared +platform-neutral code both builds use (`MoneyShot.Core`). + +- `MoneyShot.Platform.Linux/` (new project) — `LinuxScreenCapture.cs`, `LinuxGlobalHotkeys.cs`, + `X11Interop.cs`, `LinuxAutoStart.cs`, `LinuxClipboard.cs`, `LinuxMemoryTrimmer.cs` +- `MoneyShot.UI/MoneyShot.UI.csproj` — multi-targets `net10.0-windows;net10.0`; TFM-conditional + `ProjectReference`s to `Platform.Windows`/`Platform.Linux`; `WINDOWS` compile constant for the + Windows TFM only; `SkiaSharp.NativeAssets.Linux` explicitly pinned (see the SkiaSharp bug above); + `WindowsForms` `FrameworkReference` gated to the Windows TFM only +- `MoneyShot.UI/Platform/` (new) — `PlatformServices.cs` (the `#if WINDOWS` factory), + `LinuxTrayIcon.cs` (wraps Avalonia's own `TrayIcon`) +- `MoneyShot.UI/Views/MainWindow.axaml.cs`, `SettingsWindow.axaml.cs`, `EditorWindow.axaml.cs`, + `HistoryWindow.axaml.cs` — every `new Win32*(...)` call site replaced with + `PlatformServices.Create*()`; `EditorWindow`'s color-picker button gained a `#if WINDOWS`/`#else` + split (WinForms `ColorDialog` vs. the new `SimpleColorDialog`) +- `MoneyShot.UI/Views/SimpleColorDialog.cs` (new) — small hand-rolled Avalonia RGB/hex color + picker for the non-Windows build, replacing WinForms' `ColorDialog` +- `MoneyShot.UI/Assets/icon.png` (new, copied from `MoneyShot/icon.png`) — `MoneyShot.UI` had no + icon asset at all before this; now used for the window icon and the Linux tray icon +- `MoneyShot.Core/Services/AppDataPaths.cs` (new) — the config-root-resolution bugfix (§ 8 above), + used by `SettingsService`, `Logger`, both `HistoryService`s, and `LinuxAutoStart` +- `Packaging/linux/` (new) — `moneyshot.desktop`, `build-deb.sh`, `build-rpm.sh` + + `rpm/moneyshot.spec`, `build-appimage.sh` (see § Phase 3 above) +- `.github/workflows/build-linux.yml` (new) — Linux build+package CI, mirrors `build.yml`'s triggers +- `.github/workflows/release.yml` — gained `build-and-release-linux` job, attaches Linux packages + to the same auto-created release the Windows job creates +- `MoneyShot.sln` — `MoneyShot.Platform.Linux` added as a solution project + +Not touched: `MoneyShot/` (the WPF app), `Installer/Product.wxs`, `build.yml`, `build-msi.yml`, +`MoneyShot.Tests/` (still `net10.0-windows`-only — it references `MoneyShot.Platform.Windows` +directly for Windows-specific test coverage and was not multi-targeted this round). diff --git a/MoneyShot.Core/Services/AppDataPaths.cs b/MoneyShot.Core/Services/AppDataPaths.cs new file mode 100644 index 0000000..1fbdd53 --- /dev/null +++ b/MoneyShot.Core/Services/AppDataPaths.cs @@ -0,0 +1,56 @@ +namespace MoneyShot.Services; + +/// +/// Resolves the per-user config-root directory ("%AppData%\Roaming" on Windows) that +/// SettingsService/Logger/HistoryService all build their paths under. Exists because +/// Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) is NOT reliable on +/// Linux the way it is on Windows: confirmed by actually publishing and running a build (see +/// LINUX_PORT.md Phase 2 verification notes) that it returns an EMPTY STRING whenever +/// $XDG_CONFIG_HOME isn't set in the environment — which is not some rare edge case, it's the +/// default in plenty of real launch contexts (minimal window managers, some .desktop Exec +/// launches, this project's own Docker/WSL test environments). Left unguarded, every one of those +/// three services would silently write into a relative "MoneyShot" folder under whatever the +/// process's current working directory happened to be at startup — scattering config files +/// unpredictably, and failing outright with an unhandled exception if that directory isn't +/// writable (e.g. an AppImage's read-only mount point). +/// +/// On Windows this just returns the OS value unchanged (already correct and tested there). On +/// Linux, this follows the XDG Base Directory Specification's own documented fallback: use +/// $XDG_CONFIG_HOME if set, else default to ~/.config — the same rule GetFolderPath is *supposed* +/// to implement, applied by hand for the case where it doesn't. +/// +public static class AppDataPaths +{ + public static string GetConfigRoot() + { + var fromOs = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + if (!string.IsNullOrEmpty(fromOs)) + { + return fromOs; + } + + var xdgConfigHome = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); + if (!string.IsNullOrEmpty(xdgConfigHome)) + { + return xdgConfigHome; + } + + var home = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + if (string.IsNullOrEmpty(home)) + { + home = Environment.GetEnvironmentVariable("HOME"); + } + + if (string.IsNullOrEmpty(home)) + { + // Every fallback exhausted — this should not happen on any real desktop session, but + // failing loudly here (rather than silently degrading to a relative path again) makes + // the underlying environment problem visible instead of scattering files unpredictably. + throw new InvalidOperationException( + "Could not determine a per-user config directory: SpecialFolder.ApplicationData, " + + "$XDG_CONFIG_HOME, and $HOME are all unavailable."); + } + + return Path.Combine(home, ".config"); + } +} diff --git a/MoneyShot.Core/Services/Logger.cs b/MoneyShot.Core/Services/Logger.cs index eca7ea1..4898946 100644 --- a/MoneyShot.Core/Services/Logger.cs +++ b/MoneyShot.Core/Services/Logger.cs @@ -59,10 +59,7 @@ private static void Write(string level, string message, Exception? exception) private static string InitialiseLogDirectory() { - var dir = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "MoneyShot", - "logs"); + var dir = Path.Combine(AppDataPaths.GetConfigRoot(), "MoneyShot", "logs"); try { Directory.CreateDirectory(dir); diff --git a/MoneyShot.Core/Services/SettingsService.cs b/MoneyShot.Core/Services/SettingsService.cs index dc2f8d2..f9c3c9b 100644 --- a/MoneyShot.Core/Services/SettingsService.cs +++ b/MoneyShot.Core/Services/SettingsService.cs @@ -12,10 +12,7 @@ public class SettingsService public SettingsService() { - _appDataPath = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "MoneyShot" - ); + _appDataPath = Path.Combine(AppDataPaths.GetConfigRoot(), "MoneyShot"); Directory.CreateDirectory(_appDataPath); _settingsPath = Path.Combine(_appDataPath, SettingsFileName); } diff --git a/MoneyShot.Platform.Linux/LinuxAutoStart.cs b/MoneyShot.Platform.Linux/LinuxAutoStart.cs new file mode 100644 index 0000000..bfe742a --- /dev/null +++ b/MoneyShot.Platform.Linux/LinuxAutoStart.cs @@ -0,0 +1,94 @@ +using MoneyShot.Abstractions; +using MoneyShot.Services; + +namespace MoneyShot.Platform.Linux; + +/// +/// XDG autostart (~/.config/autostart/*.desktop) — the Linux counterpart to Win32AutoStart's +/// HKCU...\Run registry entry. See LINUX_PORT.md § Registry settings / Phase 2. This is the +/// freedesktop.org-standard mechanism honored by every mainstream desktop environment (GNOME, KDE, +/// XFCE, etc.) without any DE-specific code. +/// +/// PrintScreen suppression has no Linux analogue (there's no single "the OS's screenshot tool" +/// binding to disable the way Windows' Snipping Tool PrintScreen association can be toggled via +/// registry — this varies per desktop environment and isn't attempted here); both methods +/// correctly no-op per IAutoStart's own doc comment. +/// +public sealed class LinuxAutoStart : IAutoStart +{ + private const string DesktopFileName = "moneyshot.desktop"; + + private static string AutostartDirectory => + Path.Combine(AppDataPaths.GetConfigRoot(), "autostart"); + + private static string DesktopFilePath => Path.Combine(AutostartDirectory, DesktopFileName); + + public void SetStartupWithApp(bool enabled) + { + try + { + if (!enabled) + { + if (File.Exists(DesktopFilePath)) + { + File.Delete(DesktopFilePath); + } + return; + } + + Directory.CreateDirectory(AutostartDirectory); + + var exePath = Environment.ProcessPath; + if (string.IsNullOrEmpty(exePath)) + { + throw new InvalidOperationException("Could not determine the running executable's path."); + } + + // Exec value is quoted so a path containing spaces (e.g. under a user's home directory + // with spaces, or an AppImage mounted under a spaced path) is passed as one argument — + // the Exec key in the freedesktop.org desktop-entry spec follows shell-like quoting. + // No extra CLI flag is needed here: MainWindow.InitializeApplication already reads the + // persisted StartInTray setting itself regardless of how the process was launched. + var contents = + "[Desktop Entry]\n" + + "Type=Application\n" + + "Name=Money Shot\n" + + "Comment=Screenshot capture and annotation tool\n" + + $"Exec=\"{exePath}\"\n" + + "Terminal=false\n" + + "X-GNOME-Autostart-enabled=true\n"; + + // Write-then-move, same atomicity reasoning as SettingsService's settings.json write — + // a partially-written .desktop file being picked up mid-write by the session startup + // scan is a real (if rare) failure mode worth avoiding for free. + var tempPath = DesktopFilePath + ".tmp"; + File.WriteAllText(tempPath, contents); + File.Move(tempPath, DesktopFilePath, overwrite: true); + } + catch (Exception ex) + { + throw new InvalidOperationException($"Failed to update autostart setting: {ex.Message}", ex); + } + } + + public bool IsSetToRunOnStartup() + { + try + { + return File.Exists(DesktopFilePath); + } + catch (Exception ex) + { + Logger.Warn($"Failed to check autostart status: {ex.Message}"); + return false; + } + } + + public bool SetPrintScreenSuppressed(bool suppressed) => false; + + public bool TryGetPrintScreenSuppressed(out bool suppressed) + { + suppressed = false; + return false; + } +} diff --git a/MoneyShot.Platform.Linux/LinuxClipboard.cs b/MoneyShot.Platform.Linux/LinuxClipboard.cs new file mode 100644 index 0000000..ea38fe1 --- /dev/null +++ b/MoneyShot.Platform.Linux/LinuxClipboard.cs @@ -0,0 +1,113 @@ +using System.Diagnostics; +using MoneyShot.Abstractions; +using SkiaSharp; + +namespace MoneyShot.Platform.Linux; + +/// +/// Image clipboard via wl-copy (Wayland) or xclip (X11) — the Linux counterpart to Win32Clipboard. +/// See LINUX_PORT.md § Clipboard image support / Phase 2. +/// +/// Unlike Windows' DIB-based clipboard, X11/Wayland selections are MIME-typed and most +/// image-accepting apps register for image/png specifically, so the CapturedImage buffer is +/// PNG-encoded (via SkiaSharp — see MoneyShot.Platform.Linux.csproj) before handing it to whichever +/// CLI clipboard tool is available. Session type is detected via $WAYLAND_DISPLAY the same way +/// LinuxScreenCapture/LinuxGlobalHotkeys check for X11 — there is no portal-based clipboard API +/// needed here since wl-copy/xclip already handle both cases correctly on their respective +/// sessions without any permission prompt. +/// +public sealed class LinuxClipboard : IClipboard +{ + public void SetImage(CapturedImage image) + { + var pngBytes = EncodePng(image); + var (fileName, arguments) = ResolveClipboardCommand(); + + var psi = new ProcessStartInfo(fileName, arguments) + { + RedirectStandardInput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + + using var process = Process.Start(psi) + ?? throw new InvalidOperationException($"Failed to start '{fileName}' for clipboard access."); + + process.StandardInput.BaseStream.Write(pngBytes, 0, pngBytes.Length); + process.StandardInput.BaseStream.Flush(); + process.StandardInput.Close(); + + // wl-copy backgrounds itself to keep serving the selection after this process exits (that + // is the whole point of Wayland's clipboard model — whoever last set the selection must + // keep running to serve paste requests), so it returns immediately; xclip -selection + // clipboard historically also forks and detaches for the same reason on X11. Waiting here + // is still correct: both tools' *parent* process (the one Process.Start launched) exits + // right away in both cases, it's only the detached clipboard-serving child that lingers. + process.WaitForExit(5000); + if (process.ExitCode != 0) + { + var stderr = process.StandardError.ReadToEnd(); + throw new InvalidOperationException($"'{fileName} {arguments}' failed: {stderr}"); + } + } + + private static (string fileName, string arguments) ResolveClipboardCommand() + { + var isWayland = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WAYLAND_DISPLAY")); + if (isWayland && CommandExists("wl-copy")) + { + return ("wl-copy", "--type image/png"); + } + + if (CommandExists("xclip")) + { + return ("xclip", "-selection clipboard -t image/png"); + } + + if (CommandExists("wl-copy")) + { + // XWayland session without xclip installed — still try wl-copy as a last resort. + return ("wl-copy", "--type image/png"); + } + + throw new InvalidOperationException( + "No clipboard tool found. Install 'wl-clipboard' (Wayland) or 'xclip' (X11) — e.g. " + + "'sudo apt install wl-clipboard xclip' on Debian/Ubuntu, 'sudo dnf install wl-clipboard xclip' on Fedora."); + } + + private static bool CommandExists(string command) + { + try + { + var psi = new ProcessStartInfo("which", command) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + using var process = Process.Start(psi); + if (process == null) return false; + process.WaitForExit(2000); + return process.ExitCode == 0; + } + catch + { + return false; + } + } + + private static byte[] EncodePng(CapturedImage image) + { + var info = new SKImageInfo(image.Width, image.Height, SKColorType.Bgra8888, SKAlphaType.Premul); + using var bitmap = new SKBitmap(info); + unsafe + { + fixed (byte* pixelPtr = image.PixelDataBgra32) + { + bitmap.InstallPixels(info, (IntPtr)pixelPtr, image.Stride); + using var pngData = bitmap.Encode(SKEncodedImageFormat.Png, 100); + return pngData.ToArray(); + } + } + } +} diff --git a/MoneyShot.Platform.Linux/LinuxGlobalHotkeys.cs b/MoneyShot.Platform.Linux/LinuxGlobalHotkeys.cs new file mode 100644 index 0000000..2c6441f --- /dev/null +++ b/MoneyShot.Platform.Linux/LinuxGlobalHotkeys.cs @@ -0,0 +1,214 @@ +using MoneyShot.Abstractions; +using MoneyShot.Services; + +namespace MoneyShot.Platform.Linux; + +/// +/// X11 XGrabKey-based global hotkeys — the Linux counterpart to Win32GlobalHotkeys. See +/// LINUX_PORT.md § Global hotkeys / Phase 2. +/// +/// Only works under an X11 session. There is no Wayland equivalent of "grab this key combination +/// globally, regardless of which window has focus" — Wayland compositors deliberately don't let +/// clients do that for security reasons, and XGrabKey issued through XWayland does not reach +/// native-Wayland-surface focus the way a real global grab would. If XOpenDisplay fails (no X11 +/// available at all) or a grab is rejected, this logs a warning and the corresponding hotkey +/// silently does nothing — mirroring Win32GlobalHotkeys' "combination may be in use" pattern +/// exactly, and matching this interface's own doc comment ("no direct Wayland equivalent"). +/// +/// Runs its own event-pump thread (XNextEvent blocks) rather than integrating with Avalonia's +/// dispatcher — same shape as Win32GlobalHotkeys' dedicated message-only window, and for the same +/// reason: hotkey delivery must not depend on any UI window existing. +/// +public sealed class LinuxGlobalHotkeys : IGlobalHotkeys, IDisposable +{ + private readonly Dictionary<(byte keycode, uint modifiers), Action> _hotKeyActions = new(); + private readonly Lock _lock = new(); + private IntPtr _display; + private IntPtr _grabWindow; + private Thread? _eventThread; + private volatile bool _running; + + // Grabbing exactly the requested modifier mask misses the keypress whenever Caps Lock / Num + // Lock happen to be on, because X11 treats them as just more modifier bits that must match + // exactly — X11 has no "ignore lock modifiers" flag on XGrabKey itself. The conventional fix + // (used by every X11 hotkey daemon) is to grab the same combination under all 4 permutations + // of {none, CapsLock, NumLock, CapsLock+NumLock} added to the real modifier mask. + private static readonly uint[] LockModifierCombinations = { 0, X11.LockMask, X11.Mod2Mask, X11.LockMask | X11.Mod2Mask }; + + public void Initialize() + { + _display = X11.XOpenDisplay(null); + if (_display == IntPtr.Zero) + { + Logger.Warn("LinuxGlobalHotkeys: could not open an X11 display — global hotkeys are unavailable (expected under a pure-Wayland session with no XWayland; use the tray menu or in-app buttons instead)."); + return; + } + + _grabWindow = X11.XDefaultRootWindow(_display); + X11.XSelectInput(_display, _grabWindow, X11.KeyPressMask); + + _running = true; + _eventThread = new Thread(EventLoop) { IsBackground = true, Name = "MoneyShot-X11-Hotkeys" }; + _eventThread.Start(); + } + + public bool RegisterHotKeyFromString(string hotkeyString, Action action) + { + if (_display == IntPtr.Zero) + { + // Already logged once in Initialize(); don't spam per-hotkey. + return false; + } + + if (string.IsNullOrWhiteSpace(hotkeyString)) + { + Logger.Warn("Hotkey string is null or empty"); + return false; + } + + var (winModifiers, winKey) = HotKeyParser.ParseHotKey(hotkeyString); + if (winKey == 0) + { + Logger.Warn($"Invalid hotkey: {hotkeyString}"); + return false; + } + + var keysymName = VirtualKeyToX11KeysymName(winKey); + if (keysymName == null) + { + Logger.Warn($"Hotkey '{hotkeyString}' has no known X11 key mapping."); + return false; + } + + var keysym = X11.XStringToKeysym(keysymName); + if (keysym == 0) + { + Logger.Warn($"X11 has no keysym named '{keysymName}' (hotkey '{hotkeyString}')."); + return false; + } + + var keycode = X11.XKeysymToKeycode(_display, keysym); + if (keycode == 0) + { + Logger.Warn($"X11 has no keycode for keysym '{keysymName}' (hotkey '{hotkeyString}') — the current keyboard layout may not have this key."); + return false; + } + + var x11Modifiers = WinModifiersToX11(winModifiers); + + lock (_lock) + { + // XGrabKey has no meaningful return-value failure signal for "already grabbed by + // another client" — that arrives asynchronously as a BadAccess error via the X11 + // error handler, which this minimal implementation doesn't install a custom handler + // for. Unlike Win32's synchronous RegisterHotKey, there's no cheap way to report + // "combination already in use" back to the caller here; this always reports success + // once the grab call has been issued for every lock-modifier permutation. + foreach (var lockCombo in LockModifierCombinations) + { + var effectiveModifiers = x11Modifiers | lockCombo; + X11.XGrabKey(_display, keycode, effectiveModifiers, _grabWindow, true, X11.GrabModeAsync, X11.GrabModeAsync); + _hotKeyActions[(keycode, effectiveModifiers)] = action; + } + X11.XFlush(_display); + return true; + } + } + + public void UnregisterAll() + { + if (_display == IntPtr.Zero) return; + + lock (_lock) + { + foreach (var (keycode, modifiers) in _hotKeyActions.Keys) + { + X11.XUngrabKey(_display, keycode, modifiers, _grabWindow); + } + _hotKeyActions.Clear(); + X11.XFlush(_display); + } + } + + private void EventLoop() + { + var buffer = new byte[X11.XEventBufferSize]; + while (_running) + { + // XNextEvent blocks until an event arrives; there is no clean non-blocking way to + // interrupt it from another thread short of sending ourselves a dummy event, so + // Dispose() just lets this thread die with the process (it's a background thread) — + // matches Win32GlobalHotkeys' equivalent shutdown-by-process-exit behavior in practice. + if (X11.XNextEvent(_display, buffer) != 0) continue; + if (X11.ReadEventType(buffer) != X11.KeyPress) continue; + + var keycode = (byte)X11.ReadKeyEventKeycode(buffer); + var state = X11.ReadKeyEventState(buffer); + + Action? action; + lock (_lock) + { + _hotKeyActions.TryGetValue((keycode, state), out action); + } + + if (action == null) continue; + try + { + action.Invoke(); + } + catch (Exception ex) + { + Logger.Error("Hotkey action threw", ex); + } + } + } + + private static uint WinModifiersToX11(uint winModifiers) + { + uint result = 0; + if ((winModifiers & HotKeyParser.MOD_CONTROL) != 0) result |= X11.ControlMask; + if ((winModifiers & HotKeyParser.MOD_ALT) != 0) result |= X11.Mod1Mask; + if ((winModifiers & HotKeyParser.MOD_SHIFT) != 0) result |= X11.ShiftMask; + if ((winModifiers & HotKeyParser.MOD_WIN) != 0) result |= X11.Mod4Mask; + return result; + } + + private static string? VirtualKeyToX11KeysymName(uint vk) => vk switch + { + HotKeyParser.VK_SNAPSHOT => "Print", + HotKeyParser.VK_0 => "0", + HotKeyParser.VK_1 => "1", + HotKeyParser.VK_2 => "2", + HotKeyParser.VK_3 => "3", + HotKeyParser.VK_4 => "4", + HotKeyParser.VK_5 => "5", + HotKeyParser.VK_6 => "6", + HotKeyParser.VK_7 => "7", + HotKeyParser.VK_8 => "8", + HotKeyParser.VK_9 => "9", + HotKeyParser.VK_F1 => "F1", + HotKeyParser.VK_F2 => "F2", + HotKeyParser.VK_F3 => "F3", + HotKeyParser.VK_F4 => "F4", + HotKeyParser.VK_F5 => "F5", + HotKeyParser.VK_F6 => "F6", + HotKeyParser.VK_F7 => "F7", + HotKeyParser.VK_F8 => "F8", + HotKeyParser.VK_F9 => "F9", + HotKeyParser.VK_F10 => "F10", + HotKeyParser.VK_F11 => "F11", + HotKeyParser.VK_F12 => "F12", + _ => null, + }; + + public void Dispose() + { + _running = false; + UnregisterAll(); + if (_display != IntPtr.Zero) + { + X11.XCloseDisplay(_display); + _display = IntPtr.Zero; + } + } +} diff --git a/MoneyShot.Platform.Linux/LinuxMemoryTrimmer.cs b/MoneyShot.Platform.Linux/LinuxMemoryTrimmer.cs new file mode 100644 index 0000000..614cb30 --- /dev/null +++ b/MoneyShot.Platform.Linux/LinuxMemoryTrimmer.cs @@ -0,0 +1,45 @@ +using System.Runtime; +using System.Runtime.InteropServices; +using MoneyShot.Services; + +namespace MoneyShot.Platform.Linux; + +/// +/// Linux counterpart to MoneyShot.Platform.Windows.MemoryTrimmer — same rationale (release the +/// large bitmap backings EditorWindow leaves behind rather than waiting for the next scheduled +/// GC), minus the Windows-specific SetProcessWorkingSetSize call. glibc's malloc_trim(0) is the +/// closest Linux equivalent for the *native* heap specifically (SkiaSharp's bitmap backings are +/// native allocations, not managed ones) — best-effort: on a non-glibc libc (musl, used by e.g. +/// Alpine) this P/Invoke will fail to resolve and is swallowed by the same catch that guards +/// Windows' equivalent. +/// +public static class LinuxMemoryTrimmer +{ + public static void TrimAfterEditorClose() + { + try + { + GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce; + GC.Collect(GC.MaxGeneration, GCCollectionMode.Aggressive, blocking: true, compacting: true); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + try + { + malloc_trim(0); + } + catch (DllNotFoundException) + { + // Non-glibc libc (e.g. musl/Alpine) — the managed-heap trim above already ran, + // this is just a native-heap best-effort extra. + } + } + catch (Exception ex) + { + Logger.Warn("Could not release editor memory", ex); + } + } + + [DllImport("libc.so.6")] + private static extern int malloc_trim(nuint pad); +} diff --git a/MoneyShot.Platform.Linux/LinuxScreenCapture.cs b/MoneyShot.Platform.Linux/LinuxScreenCapture.cs new file mode 100644 index 0000000..4be61ee --- /dev/null +++ b/MoneyShot.Platform.Linux/LinuxScreenCapture.cs @@ -0,0 +1,200 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using MoneyShot.Abstractions; +using MoneyShot.Services; + +namespace MoneyShot.Platform.Linux; + +/// +/// X11-based screen capture (XGetImage on the root window) — the Linux counterpart to +/// Win32ScreenCapture. See LINUX_PORT.md § Capture pipeline / Phase 2. +/// +/// This only works under an X11 session (a real Xorg session, or XWayland for apps that don't +/// need pixels from native-Wayland surfaces — capturing the root window through XWayland reliably +/// returns whatever XWayland itself is compositing, which in practice means Xorg-session content; +/// behavior when the *only* thing running is a pure-Wayland compositor with no X clients at all is +/// untested here). A portal-based (org.freedesktop.portal.Screenshot) implementation would be the +/// correct approach for native Wayland sessions (GNOME/KDE Wayland, now the default on most +/// mainstream distros including Debian/Fedora) but requires an interactive per-capture permission +/// dialog from the compositor — a real UX change from Windows' instant, silent capture — and portal +/// backend services aren't present in this development environment to implement against +/// interactively (see LINUX_PORT.md Phase 2 status). Treat this class as the X11-session path only; +/// a portal-based path is the documented, tracked gap for pure-Wayland sessions. +/// +public sealed class LinuxScreenCapture : IScreenCapture +{ + public CapturedImage CaptureFullScreen() + { + var display = OpenDisplayOrThrow(); + try + { + var screen = X11.XDefaultScreen(display); + var width = X11.XDisplayWidth(display, screen); + var height = X11.XDisplayHeight(display, screen); + return CaptureRegion(display, 0, 0, width, height); + } + finally + { + X11.XCloseDisplay(display); + } + } + + public CapturedImage CaptureMonitor(int monitorIndex) + { + var monitors = GetAllMonitors(); + if (monitorIndex < 0 || monitorIndex >= monitors.Count) + throw new ArgumentOutOfRangeException(nameof(monitorIndex)); + + var m = monitors[monitorIndex]; + var display = OpenDisplayOrThrow(); + try + { + return CaptureRegion(display, m.Left, m.Top, m.Width, m.Height); + } + finally + { + X11.XCloseDisplay(display); + } + } + + public IReadOnlyList GetAllMonitors() + { + // Shelling out to `xrandr --query` rather than P/Invoking libXrandr directly: the RandR + // protocol's monitor-enumeration ABI (XRRGetMonitors et al.) has changed shape across + // versions, whereas xrandr's plain-text --query output has been stable for over a decade + // and is present on effectively every X11 desktop install (it's the same tool GNOME + // Settings/KDE Display Config shell out to internally in some cases). If xrandr isn't + // installed or the session has no RandR (rare, but possible in minimal WMs), this falls + // back to reporting a single monitor matching the X11 display size. + try + { + var monitors = ParseXrandr(RunCommand("xrandr", "--query")); + if (monitors.Count > 0) return monitors; + } + catch (Exception ex) + { + Logger.Warn($"xrandr enumeration failed, falling back to single-monitor: {ex.Message}"); + } + + return FallbackSingleMonitor(); + } + + private static List ParseXrandr(string xrandrOutput) + { + // Matches lines like: "eDP-1 connected primary 1920x1080+0+0 (normal left inverted...) 344mm x 194mm" + // or "HDMI-1 connected 1920x1080+1920+0 ..." (non-primary, no "primary" token). + var regex = new Regex(@"^(?\S+) connected (?primary )?(?\d+)x(?\d+)\+(?\d+)\+(?\d+)", RegexOptions.Multiline); + var result = new List(); + foreach (Match match in regex.Matches(xrandrOutput)) + { + result.Add(new MonitorInfo( + Left: int.Parse(match.Groups["x"].Value), + Top: int.Parse(match.Groups["y"].Value), + Width: int.Parse(match.Groups["w"].Value), + Height: int.Parse(match.Groups["h"].Value), + IsPrimary: match.Groups["primary"].Success, + DeviceName: match.Groups["name"].Value)); + } + + // xrandr doesn't always mark a "primary" — if none was flagged, treat the first (typically + // leftmost/topmost) as primary so downstream UI (monitor button list, tray menu) has one. + if (result.Count > 0 && !result.Exists(m => m.IsPrimary)) + { + result[0] = result[0] with { IsPrimary = true }; + } + + return result; + } + + private static List FallbackSingleMonitor() + { + var display = OpenDisplayOrThrow(); + try + { + var screen = X11.XDefaultScreen(display); + var width = X11.XDisplayWidth(display, screen); + var height = X11.XDisplayHeight(display, screen); + return new List { new(0, 0, width, height, true, "X11 default screen") }; + } + finally + { + X11.XCloseDisplay(display); + } + } + + private static CapturedImage CaptureRegion(IntPtr display, int x, int y, int width, int height) + { + var root = X11.XDefaultRootWindow(display); + var imagePtr = X11.XGetImage(display, root, x, y, (uint)width, (uint)height, X11.AllPlanes, X11.ZPixmap); + if (imagePtr == IntPtr.Zero) + { + throw new InvalidOperationException($"XGetImage failed for region ({x},{y},{width}x{height}) — the X server may not support ZPixmap capture of this size, or the region is off-screen."); + } + + try + { + var image = Marshal.PtrToStructure(imagePtr); + // 32bpp TrueColor visuals (the near-universal case on modern X11 — 16bpp/8bpp visuals + // are not supported here) pack pixels as 0x00RRGGBB in the server's native byte order; + // on every actually-relevant architecture (x86-64, aarch64) that's little-endian, i.e. + // B,G,R,X per pixel in memory — already exactly CapturedImage's expected BGRA32 layout + // modulo the alpha byte, which XGetImage leaves as whatever padding byte the X server + // wrote (typically 0, not the opaque 0xFF CapturedImage's other producers guarantee). + if (image.bits_per_pixel != 32) + { + throw new NotSupportedException($"Unsupported X11 visual depth: {image.bits_per_pixel} bits/pixel (only 32bpp TrueColor is supported)."); + } + + var stride = image.bytes_per_line; + var byteCount = stride * height; + var bytes = new byte[byteCount]; + Marshal.Copy(image.data, bytes, 0, byteCount); + + // Force alpha opaque — see comment above. + for (var i = 3; i < bytes.Length; i += 4) + { + bytes[i] = 0xFF; + } + + return new CapturedImage(width, height, stride, bytes); + } + finally + { + X11.XDestroyImage(imagePtr); + } + } + + private static IntPtr OpenDisplayOrThrow() + { + var display = X11.XOpenDisplay(null); + if (display == IntPtr.Zero) + { + throw new InvalidOperationException( + "Could not open the X11 display (XOpenDisplay returned NULL). This usually means " + + "there is no X server / XWayland compatibility available — a pure Wayland session " + + "without XWayland isn't supported by this build's capture implementation yet; see " + + "LINUX_PORT.md Phase 2."); + } + return display; + } + + internal static string RunCommand(string fileName, string arguments) + { + var psi = new ProcessStartInfo(fileName, arguments) + { + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false + }; + using var process = Process.Start(psi) ?? throw new InvalidOperationException($"Failed to start '{fileName}'."); + var stdout = process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + if (process.ExitCode != 0) + { + var stderr = process.StandardError.ReadToEnd(); + throw new InvalidOperationException($"'{fileName} {arguments}' exited {process.ExitCode}: {stderr}"); + } + return stdout; + } +} diff --git a/MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj b/MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj new file mode 100644 index 0000000..7c3a39d --- /dev/null +++ b/MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj @@ -0,0 +1,35 @@ + + + + + net10.0 + enable + enable + + true + + + + + + + + + + + + + + diff --git a/MoneyShot.Platform.Linux/X11Interop.cs b/MoneyShot.Platform.Linux/X11Interop.cs new file mode 100644 index 0000000..b6c48f1 --- /dev/null +++ b/MoneyShot.Platform.Linux/X11Interop.cs @@ -0,0 +1,119 @@ +using System.Runtime.InteropServices; + +namespace MoneyShot.Platform.Linux; + +/// +/// Minimal libX11 P/Invoke surface shared by LinuxScreenCapture and LinuxGlobalHotkeys. Only X11 +/// sessions (native Xorg, or XWayland-with-caveats — see LinuxGlobalHotkeys) are supported; a pure +/// Wayland session with no XWayland has no Display to open at all, and callers must handle +/// XOpenDisplay returning IntPtr.Zero gracefully rather than throwing. +/// +internal static class X11 +{ + private const string LibX11 = "libX11.so.6"; + + [StructLayout(LayoutKind.Sequential)] + public struct XImage + { + public int width; + public int height; + public int xoffset; + public int format; + public IntPtr data; + public int byte_order; + public int bitmap_unit; + public int bitmap_bit_order; + public int bitmap_pad; + public int depth; + public int bytes_per_line; + public int bits_per_pixel; + public nuint red_mask; + public nuint green_mask; + public nuint blue_mask; + public IntPtr obdata; + // f. (procedure pointers) omitted — never called from managed code, only laid out so the + // struct size matches Xlib's for the fields above; XDestroyImage is invoked on the raw + // pointer via the library's own function, not through this struct's function pointers. + } + + public const int ZPixmap = 2; + public const long AllPlanes = ~0L; + + [DllImport(LibX11)] + public static extern IntPtr XOpenDisplay(string? display); + + [DllImport(LibX11)] + public static extern int XCloseDisplay(IntPtr display); + + [DllImport(LibX11)] + public static extern IntPtr XDefaultRootWindow(IntPtr display); + + [DllImport(LibX11)] + public static extern int XDefaultScreen(IntPtr display); + + [DllImport(LibX11)] + public static extern IntPtr XGetImage(IntPtr display, IntPtr drawable, int x, int y, uint width, uint height, long planeMask, int format); + + [DllImport(LibX11)] + public static extern void XDestroyImage(IntPtr image); + + [DllImport(LibX11)] + public static extern int XDisplayWidth(IntPtr display, int screenNumber); + + [DllImport(LibX11)] + public static extern int XDisplayHeight(IntPtr display, int screenNumber); + + [DllImport(LibX11)] + public static extern nuint XStringToKeysym(string keyName); + + [DllImport(LibX11)] + public static extern byte XKeysymToKeycode(IntPtr display, nuint keysym); + + [DllImport(LibX11)] + public static extern int XGrabKey(IntPtr display, int keycode, uint modifiers, IntPtr grabWindow, bool ownerEvents, int pointerMode, int keyboardMode); + + [DllImport(LibX11)] + public static extern int XUngrabKey(IntPtr display, int keycode, uint modifiers, IntPtr grabWindow); + + [DllImport(LibX11)] + public static extern int XSelectInput(IntPtr display, IntPtr window, long eventMask); + + [DllImport(LibX11)] + public static extern int XPending(IntPtr display); + + [DllImport(LibX11)] + public static extern int XNextEvent(IntPtr display, [Out] byte[] eventBuffer); + + [DllImport(LibX11)] + public static extern int XFlush(IntPtr display); + + // X11 modifier bits (same numeric values as XGrabKey expects). + public const uint ShiftMask = 1 << 0; + public const uint LockMask = 1 << 1; // Caps Lock — must grab with/without it, see LinuxGlobalHotkeys + public const uint ControlMask = 1 << 2; + public const uint Mod1Mask = 1 << 3; // Alt + public const uint Mod2Mask = 1 << 4; // usually Num Lock — same caveat as LockMask + public const uint Mod4Mask = 1 << 6; // Super/Windows key + + public const int GrabModeAsync = 1; + public const long KeyPressMask = 1 << 0; + + // XEvent is a large union; only the KeyPress case (XKeyEvent layout) is read, and only the + // fields needed to recover which grabbed (keycode, modifiers) pair fired. XEvent's first field + // is `type` (int) — the raw 8-byte-aligned struct is large enough that reading it as a fixed + // byte buffer and decoding just the offsets we need is far less error-prone across libc/X11 + // header ABI variations than declaring the full union in C#. + public const int KeyPress = 2; + public const int XEventBufferSize = 192; // XEvent is a union sized for the largest member (XClientMessageEvent etc.); 192 bytes is safely larger than every variant on 64-bit. + + public static int ReadEventType(byte[] buffer) => BitConverter.ToInt32(buffer, 0); + + // XKeyEvent layout (System V x86-64 ABI, 8-byte-aligned fields): + // 0:type(4) [4 pad] 8:serial(8) 16:send_event(4) [4 pad] 24:display(8) 32:window(8) + // 40:root(8) 48:subwindow(8) 56:time(8) 64:x(4) 68:y(4) 72:x_root(4) 76:y_root(4) + // 80:state(4) 84:keycode(4) 88:same_screen(4) + // Verified empirically against a real XGrabKey/XSendEvent round-trip under Xvfb — see + // LINUX_PORT.md Phase 2 verification notes — not just derived from the Xlib.h struct by hand. + public static uint ReadKeyEventState(byte[] buffer) => BitConverter.ToUInt32(buffer, 80); + public static uint ReadKeyEventKeycode(byte[] buffer) => BitConverter.ToUInt32(buffer, 84); +} diff --git a/MoneyShot.UI/Assets/icon.png b/MoneyShot.UI/Assets/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..0712b75315eb1ee290c4c1f93526f03a29027251 GIT binary patch literal 104409 zcmV*HKxn^-P)uGCRN-M zEJz3vNFXjZ$#r}E*v$Vo=gkd)<|aYv9nN#cXP$X%o|*IJBIs}7&z1s<7A+F<=f6Ag z#`$k-IPJ9aTTedx+_vKmp5JlY!N+yXn|I8FBjy}2X~v9$r_7i*W6IR_sna`KJ7-O7 znRrlpWBZ{k`3c9gW+$B1oSt$v;H;KR=NWC;sV8?dPd;u^>$D>$G*6v3sb$8T$&+Wz zoIZWt)R{96ojh;qya|WTI=u6UIVVjz<)~98&OdH`$El}Y*l2K|zlA@03jEC&{CTjD zPdaH~^4xPTX*=P_(`O%d+&M=cdgw_f|NN)7o!zzNnZJKz&H5`>u6*VnA6~Wchbz`R z`M)dHJa@x$&#k?F)%s2UyJ=I`FE;J$`|Z}=fm^rt58t|TVDy*0!{uKLjFuMn7Yjcb zESG)&_~Agg^y9wb$n`ygg`e-}AN=3$!J%L880fvZtE=aZ&0DtLy=l|dd!F0cwQSXf zjrTsiZq?F|+{0lnfpLE`=-(Pw)46x0CU%~gpEBcw#_6+9ZkRUf z$7edH9F?9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$CvLt zwB^lR2euyFylZXqjvckV;4l8kN#nvuAEyK^fWgNp%}>3rYHQc7UHazDOG34^OFB1f zSlv>)Y5A!&8`M<0YRHL zuRm0`b@kD$TUVXfym@W&#*M4m>*|*Fh)8AW(xuUw3;X<^`rH1v8TkJI00960!`JIv h00006Nkl +/// Avalonia's Window.ShowDialog(owner) throws InvalidOperationException("Cannot show window with +/// non-visible owner") if the owner isn't currently shown — confirmed by actually running this +/// app: MainWindow.CaptureFullScreenAsync() calls Hide() (so the main window doesn't appear in +/// its own screenshot) and then used to call EditorWindow.ShowDialog(this), which threw every +/// single time, breaking the entire capture flow. WPF has no such restriction, so this didn't +/// surface until the Avalonia port was actually launched and clicked through — see LINUX_PORT.md +/// Phase 1 verification notes. +/// +/// This extension makes "show as a dialog, wait for it to close" work regardless of whether the +/// owner is visible: it uses the real ShowDialog(owner) (proper modality/centering) when the +/// owner is visible, and falls back to a plain Show() + await-on-Closed otherwise. Every place in +/// this app that used to call window.ShowDialog(owner) directly should go through this instead. +/// +public static class WindowExtensions +{ + ///

+ /// Waits until closes. There's deliberately no generic + /// TResult-returning overload mirroring ShowDialog<TResult>: Avalonia's dialog-result + /// value (set via Window.Close(result)) has no public API to read back once the fallback path + /// (plain Show()) is taken, so callers that need a result should expose it as an ordinary + /// property on the window instead (see RegionSelector.CroppedScreenshot) and read that after + /// awaiting this. + /// + public static Task ShowAsDialogAsync(this Window window, Window? owner) + { + if (owner != null && owner.IsVisible) + { + return window.ShowDialog(owner); + } + + var tcs = new TaskCompletionSource(); + window.Closed += (_, _) => tcs.TrySetResult(); + window.Show(); + return tcs.Task; + } +} diff --git a/MoneyShot.UI/MoneyShot.UI.csproj b/MoneyShot.UI/MoneyShot.UI.csproj index 47e0d47..91ca932 100644 --- a/MoneyShot.UI/MoneyShot.UI.csproj +++ b/MoneyShot.UI/MoneyShot.UI.csproj @@ -2,20 +2,16 @@ WinExe - - net10.0-windows + + net10.0-windows;net10.0 enable enable - true - true - app.manifest true 2.1.0 2.1.0.0 @@ -23,16 +19,25 @@ Daolyap & iSaluki Daolyap & iSaluki Money Shot Screenshot Tool - A modern, feature-rich screenshot tool with comprehensive annotation capabilities (Avalonia UI — see LINUX_PORT.md Phase 1). + A modern, feature-rich screenshot tool with comprehensive annotation capabilities (Avalonia UI — see LINUX_PORT.md). Copyright © 2026 Daolyap & iSaluki + + true + true + app.manifest + + $(DefineConstants);WINDOWS + + @@ -47,23 +52,50 @@ + + + + + - + + + + + + - - + + + + + + + + + + diff --git a/MoneyShot.UI/Platform/LinuxTrayIcon.cs b/MoneyShot.UI/Platform/LinuxTrayIcon.cs new file mode 100644 index 0000000..3a23aa0 --- /dev/null +++ b/MoneyShot.UI/Platform/LinuxTrayIcon.cs @@ -0,0 +1,91 @@ +using Avalonia.Controls; +using Avalonia.Platform; +using MoneyShot.Abstractions; + +namespace MoneyShot.UI.Platform; + +/// +/// Wraps Avalonia's own cross-platform / for the +/// Linux build, rather than hand-rolling the StatusNotifierItem D-Bus protocol directly — Avalonia +/// (via its Avalonia.FreeDesktop assembly) already implements SNI registration correctly, so +/// reusing it is both less code and more likely to be correct than a hand-rolled, untested D-Bus +/// service. See LINUX_PORT.md § System tray / Phase 2. This lives in MoneyShot.UI rather than +/// MoneyShot.Platform.Linux specifically because it depends on Avalonia — Platform.Linux stays +/// Avalonia-free, mirroring how Win32TrayIcon in Platform.Windows stays WPF-free. +/// +/// Note on GNOME: vanilla GNOME Shell has no built-in StatusNotifierItem host — it needs the +/// "AppIndicator and KStatusNotifierItem Support" extension (ships by default on Ubuntu, not on +/// stock Fedora Workstation) for a tray icon to be visible at all. This is a real, known Linux +/// desktop-ecosystem gap, not a bug in this implementation; there is no portable workaround short +/// of also implementing the legacy XEmbed systray protocol as a fallback, which Avalonia's own +/// tray support does not do either. +/// +/// Linux tray icons have no standard "double-click" concept (SNI defines Activate/ +/// SecondaryActivate/ContextMenu, not click-count) — a single left-click (Activate) fires +/// here, since requiring an actual double-click on Linux would be an +/// unfamiliar, undiscoverable gesture for a tray icon on that platform. +/// +public sealed class LinuxTrayIcon : ITrayIcon +{ + private TrayIcon? _trayIcon; + + public event Action? DoubleClicked; + + public void Show(string tooltip, IReadOnlyList menuItems) + { + var menu = new NativeMenu(); + foreach (var item in menuItems) + { + if (item.IsSeparator) + { + menu.Items.Add(new NativeMenuItemSeparator()); + continue; + } + + var onClick = item.OnClick; + var nativeItem = new NativeMenuItem(item.Label); + nativeItem.Click += (_, _) => onClick?.Invoke(); + menu.Items.Add(nativeItem); + } + + _trayIcon = new TrayIcon + { + Icon = ResolveIcon(), + ToolTipText = tooltip, + Menu = menu, + IsVisible = true + }; + _trayIcon.Clicked += (_, _) => DoubleClicked?.Invoke(); + } + + public void ShowBalloonTip(int timeoutMilliseconds, string title, string text) + { + // Avalonia's TrayIcon has no cross-platform balloon/notification API — a real desktop + // notification would need the org.freedesktop.Notifications D-Bus interface (the + // "notify-send" mechanism), which is a reasonable follow-up but out of scope for the + // minimum-viable Linux port; silently doing nothing here is preferable to throwing, since + // callers treat this as a best-effort courtesy notification, never a required one. + } + + private static WindowIcon? ResolveIcon() + { + try + { + using var stream = AssetLoader.Open(new Uri("avares://MoneyShot.UI/Assets/icon.png")); + return new WindowIcon(stream); + } + catch + { + return null; + } + } + + public void Dispose() + { + if (_trayIcon != null) + { + _trayIcon.IsVisible = false; + _trayIcon.Dispose(); + } + } +} diff --git a/MoneyShot.UI/Platform/PlatformServices.cs b/MoneyShot.UI/Platform/PlatformServices.cs new file mode 100644 index 0000000..2b9a7c0 --- /dev/null +++ b/MoneyShot.UI/Platform/PlatformServices.cs @@ -0,0 +1,33 @@ +using MoneyShot.Abstractions; + +namespace MoneyShot.UI.Platform; + +/// +/// Picks the right IScreenCapture/IGlobalHotkeys/ITrayIcon/IAutoStart/IClipboard implementation +/// for the TFM this assembly was built for — Win32* (MoneyShot.Platform.Windows) under the +/// net10.0-windows TFM, Linux*/LinuxTrayIcon (MoneyShot.Platform.Linux) under plain net10.0. See +/// MoneyShot.UI.csproj's WINDOWS compile constant and TFM-conditional ProjectReferences. +/// +/// This is a compile-time branch (#if WINDOWS), not a runtime OperatingSystem.IsWindows() check, +/// because the two TFMs don't even reference the same platform project — the net10.0 build has no +/// Win32* types to construct in the first place. Every MainWindow/SettingsWindow/EditorWindow call +/// site that used to do `new Win32ScreenCapture()` etc. now calls PlatformServices.Create*() +/// instead, so this file is the single place that needs to change if a third platform is ever +/// added. +/// +internal static class PlatformServices +{ +#if WINDOWS + public static IScreenCapture CreateScreenCapture() => new MoneyShot.Platform.Windows.Win32ScreenCapture(); + public static IGlobalHotkeys CreateGlobalHotkeys() => new MoneyShot.Platform.Windows.Win32GlobalHotkeys(); + public static ITrayIcon CreateTrayIcon() => new MoneyShot.Platform.Windows.Win32TrayIcon(); + public static IAutoStart CreateAutoStart() => new MoneyShot.Platform.Windows.Win32AutoStart(); + public static IClipboard CreateClipboard() => new MoneyShot.Platform.Windows.Win32Clipboard(); +#else + public static IScreenCapture CreateScreenCapture() => new MoneyShot.Platform.Linux.LinuxScreenCapture(); + public static IGlobalHotkeys CreateGlobalHotkeys() => new MoneyShot.Platform.Linux.LinuxGlobalHotkeys(); + public static ITrayIcon CreateTrayIcon() => new LinuxTrayIcon(); + public static IAutoStart CreateAutoStart() => new MoneyShot.Platform.Linux.LinuxAutoStart(); + public static IClipboard CreateClipboard() => new MoneyShot.Platform.Linux.LinuxClipboard(); +#endif +} diff --git a/MoneyShot.UI/Services/HistoryService.cs b/MoneyShot.UI/Services/HistoryService.cs index 13430ed..5c5ced5 100644 --- a/MoneyShot.UI/Services/HistoryService.cs +++ b/MoneyShot.UI/Services/HistoryService.cs @@ -5,6 +5,7 @@ using System.Text.Json; using Avalonia.Media.Imaging; using MoneyShot.Models; +using MoneyShot.UI.Interop; using Logger = MoneyShot.Services.Logger; namespace MoneyShot.UI.Services; @@ -26,10 +27,7 @@ public sealed class HistoryService public HistoryService() { - _historyDirectory = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "MoneyShot", - "history"); + _historyDirectory = Path.Combine(MoneyShot.Services.AppDataPaths.GetConfigRoot(), "MoneyShot", "history"); try { Directory.CreateDirectory(_historyDirectory); @@ -154,14 +152,49 @@ private void EnforceRetention(int retentionCount) } } + /// + /// Downsamples via raw pixel nearest-neighbor sampling rather than Bitmap.CreateScaledBitmap + /// — confirmed by actually running this (see LINUX_PORT.md Phase 1 verification notes) that + /// CreateScaledBitmap throws "Invalid source bitmap type" on a WriteableBitmap source (which + /// is what every capture produces, via CapturedImage.ToAvaloniaBitmap). Also deliberately + /// always returns a distinct Bitmap object, even when no scaling is needed: the caller wraps + /// the result in a `using`, and the previous version's "already small enough, just return + /// source" fast path would alias the caller's own `image` argument — the `using` block would + /// then dispose the caller's bitmap out from under it (e.g. right before EditorWindow renders + /// it), for any capture at or under 400px wide. + /// private static Bitmap CreateThumbnail(Bitmap source) { - if (source.PixelSize.Width <= ThumbnailMaxWidth) return source; - var scale = (double)ThumbnailMaxWidth / source.PixelSize.Width; - var targetSize = new Avalonia.PixelSize( - ThumbnailMaxWidth, - Math.Max(1, (int)Math.Round(source.PixelSize.Height * scale))); - return source.CreateScaledBitmap(targetSize, BitmapInterpolationMode.HighQuality); + var captured = source.ToCapturedImage(); + if (captured.Width <= ThumbnailMaxWidth) return captured.ToAvaloniaBitmap(); + + var scale = (double)ThumbnailMaxWidth / captured.Width; + var targetWidth = ThumbnailMaxWidth; + var targetHeight = Math.Max(1, (int)Math.Round(captured.Height * scale)); + return DownsampleNearestNeighbor(captured, targetWidth, targetHeight).ToAvaloniaBitmap(); + } + + private static MoneyShot.Abstractions.CapturedImage DownsampleNearestNeighbor(MoneyShot.Abstractions.CapturedImage source, int targetWidth, int targetHeight) + { + const int bytesPerPixel = 4; + var destStride = targetWidth * bytesPerPixel; + var dest = new byte[destStride * targetHeight]; + + for (var ty = 0; ty < targetHeight; ty++) + { + var srcY = Math.Min(source.Height - 1, (int)((long)ty * source.Height / targetHeight)); + var destRowOffset = ty * destStride; + var srcRowOffset = srcY * source.Stride; + for (var tx = 0; tx < targetWidth; tx++) + { + var srcX = Math.Min(source.Width - 1, (int)((long)tx * source.Width / targetWidth)); + var srcOffset = srcRowOffset + srcX * bytesPerPixel; + var destOffset = destRowOffset + tx * bytesPerPixel; + Buffer.BlockCopy(source.PixelDataBgra32, srcOffset, dest, destOffset, bytesPerPixel); + } + } + + return new MoneyShot.Abstractions.CapturedImage(targetWidth, targetHeight, destStride, dest); } private static void TryDelete(string path) diff --git a/MoneyShot.UI/Views/EditorWindow.axaml.cs b/MoneyShot.UI/Views/EditorWindow.axaml.cs index 38fefb1..becf5c8 100644 --- a/MoneyShot.UI/Views/EditorWindow.axaml.cs +++ b/MoneyShot.UI/Views/EditorWindow.axaml.cs @@ -15,9 +15,9 @@ using Avalonia.Platform.Storage; using Avalonia.Threading; using MoneyShot.Models; -using MoneyShot.Platform.Windows; using MoneyShot.UI.Editor; using MoneyShot.UI.Interop; +using MoneyShot.UI.Platform; using MoneyShot.UI.Services; using Logger = MoneyShot.Services.Logger; @@ -107,7 +107,7 @@ public EditorWindow(Bitmap image) InitializeComponent(); ImageCanvas.RenderTransform = new TransformGroup { Children = { ZoomTransform, PanTransform } }; _originalImage = image; - _saveService = new SaveService(new Win32Clipboard()); + _saveService = new SaveService(PlatformServices.CreateClipboard()); DisplayImage(); KeyDown += EditorWindow_KeyDown; @@ -1594,8 +1594,9 @@ private void SelectTool(AnnotationTool tool) } } - private void CustomColorButton_Click(object? sender, RoutedEventArgs e) + private async void CustomColorButton_Click(object? sender, RoutedEventArgs e) { +#if WINDOWS // Re-use the WinForms ColorDialog (already referenced for this reason — see // MoneyShot.UI.csproj) rather than hand-rolling an HSL picker — the OS picker is what // most users expect and supports the full palette. Matches the WPF build's reasoning. @@ -1606,8 +1607,14 @@ private void CustomColorButton_Click(object? sender, RoutedEventArgs e) Color = System.Drawing.Color.FromArgb(_currentColor.A, _currentColor.R, _currentColor.G, _currentColor.B) }; if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK) return; - var picked = Color.FromArgb(dlg.Color.A, dlg.Color.R, dlg.Color.G, dlg.Color.B); +#else + // WinForms isn't referenced under net10.0 (Linux) — see SimpleColorDialog for why this is + // a small hand-rolled Avalonia window rather than an OS-native picker. + var result = await SimpleColorDialog.ShowAsync(this, _currentColor); + if (result == null) return; + var picked = result.Value; +#endif _currentColor = picked; if (CustomColorButton != null) { diff --git a/MoneyShot.UI/Views/HistoryWindow.axaml.cs b/MoneyShot.UI/Views/HistoryWindow.axaml.cs index ebfbc89..9e784a6 100644 --- a/MoneyShot.UI/Views/HistoryWindow.axaml.cs +++ b/MoneyShot.UI/Views/HistoryWindow.axaml.cs @@ -6,8 +6,9 @@ using Avalonia.Layout; using Avalonia.Media; using MoneyShot.Models; -using MoneyShot.Platform.Windows; using MoneyShot.Services; +using MoneyShot.UI.Interop; +using MoneyShot.UI.Platform; using MoneyShot.UI.Services; namespace MoneyShot.UI.Views; @@ -18,7 +19,7 @@ namespace MoneyShot.UI.Views; public partial class HistoryWindow : Window { private readonly HistoryService _history; - private readonly SaveService _saveService = new(new Win32Clipboard()); + private readonly SaveService _saveService = new(PlatformServices.CreateClipboard()); public HistoryWindow(HistoryService history) { @@ -123,13 +124,17 @@ private async void OpenInEditor(HistoryEntry entry) try { var editor = new EditorWindow(image); - await editor.ShowDialog(this); + await editor.ShowAsDialogAsync(this); } finally { // Same working-set trim the capture flow does — without it, opening a capture from // history left hundreds of MB of bitmap backings resident after the editor closed. - MemoryTrimmer.TrimAfterEditorClose(); +#if WINDOWS + MoneyShot.Platform.Windows.MemoryTrimmer.TrimAfterEditorClose(); +#else + MoneyShot.Platform.Linux.LinuxMemoryTrimmer.TrimAfterEditorClose(); +#endif } } diff --git a/MoneyShot.UI/Views/MainWindow.axaml b/MoneyShot.UI/Views/MainWindow.axaml index 0123e37..c0f820c 100644 --- a/MoneyShot.UI/Views/MainWindow.axaml +++ b/MoneyShot.UI/Views/MainWindow.axaml @@ -2,6 +2,7 @@ xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Money Shot" Height="600" Width="720" + Icon="avares://MoneyShot.UI/Assets/icon.png" MinHeight="500" MinWidth="600" WindowStartupLocation="CenterScreen" Background="{StaticResource Cocoa.WindowBrush}" diff --git a/MoneyShot.UI/Views/MainWindow.axaml.cs b/MoneyShot.UI/Views/MainWindow.axaml.cs index 88144e3..16bacb6 100644 --- a/MoneyShot.UI/Views/MainWindow.axaml.cs +++ b/MoneyShot.UI/Views/MainWindow.axaml.cs @@ -7,8 +7,8 @@ using Avalonia.Threading; using MoneyShot.Abstractions; using MoneyShot.UI.Interop; +using MoneyShot.UI.Platform; using MoneyShot.UI.Services; -using MoneyShot.Platform.Windows; using MoneyShot.Services; using Path = Avalonia.Controls.Shapes.Path; @@ -35,10 +35,10 @@ public partial class MainWindow : Window public MainWindow() { InitializeComponent(); - _screenshotService = new Win32ScreenCapture(); - _saveService = new SaveService(new Win32Clipboard()); + _screenshotService = PlatformServices.CreateScreenCapture(); + _saveService = new SaveService(PlatformServices.CreateClipboard()); _settingsService = new SettingsService(); - _hotKeyService = new Win32GlobalHotkeys(); + _hotKeyService = PlatformServices.CreateGlobalHotkeys(); _autoUpdateService = new AutoUpdateService(); _historyService = new HistoryService(); @@ -252,7 +252,7 @@ private void SetupSystemTray() menuItems.Add(new TrayMenuItem("Show Window", ShowMainWindow)); menuItems.Add(new TrayMenuItem("Exit", ExitApplication)); - _trayIcon = new Win32TrayIcon(); + _trayIcon = PlatformServices.CreateTrayIcon(); _trayIcon.Show("Money Shot - Screenshot Tool", menuItems); _trayIcon.DoubleClicked += ShowMainWindow; } @@ -296,8 +296,8 @@ private async Task CaptureRegionAsync() } var regionSelector = new RegionSelector(frozenScreen); - var confirmed = await regionSelector.ShowDialog(this); - if (confirmed && regionSelector.CroppedScreenshot != null) + await regionSelector.ShowAsDialogAsync(this); + if (regionSelector.CroppedScreenshot != null) { await OpenEditorAsync(regionSelector.CroppedScreenshot, "Region"); } @@ -344,7 +344,7 @@ private async Task OpenEditorAsync(Avalonia.Media.Imaging.Bitmap screenshot, str } var editor = new EditorWindow(screenshot); - await editor.ShowDialog(this); + await editor.ShowAsDialogAsync(this); } catch (System.Exception ex) { @@ -354,14 +354,20 @@ private async Task OpenEditorAsync(Avalonia.Media.Imaging.Bitmap screenshot, str } finally { - MemoryTrimmer.TrimAfterEditorClose(); +#if WINDOWS + MoneyShot.Platform.Windows.MemoryTrimmer.TrimAfterEditorClose(); +#else + MoneyShot.Platform.Linux.LinuxMemoryTrimmer.TrimAfterEditorClose(); +#endif } } private async Task ShowSettingsAsync() { var settings = new SettingsWindow(); - await settings.ShowDialog(this); + // Reachable from the tray menu while MainWindow is hidden (StartInTray) — must not use a + // raw ShowDialog(this), see MoneyShot.UI.Interop.WindowExtensions. + await settings.ShowAsDialogAsync(this); } private void ShowHistory() diff --git a/MoneyShot.UI/Views/SettingsWindow.axaml.cs b/MoneyShot.UI/Views/SettingsWindow.axaml.cs index 0d8fbaf..f8a59d3 100644 --- a/MoneyShot.UI/Views/SettingsWindow.axaml.cs +++ b/MoneyShot.UI/Views/SettingsWindow.axaml.cs @@ -7,8 +7,8 @@ using Avalonia.Platform.Storage; using MoneyShot.Abstractions; using MoneyShot.Models; -using MoneyShot.Platform.Windows; using MoneyShot.Services; +using MoneyShot.UI.Platform; using MoneyShot.UI.Services; namespace MoneyShot.UI.Views; @@ -29,8 +29,8 @@ public SettingsWindow() { InitializeComponent(); _settingsService = new SettingsService(); - _screenCapture = new Win32ScreenCapture(); - _autoStart = new Win32AutoStart(); + _screenCapture = PlatformServices.CreateScreenCapture(); + _autoStart = PlatformServices.CreateAutoStart(); _settings = _settingsService.LoadSettings(); LoadSettings(); LoadMonitorHotkeysInfo(); @@ -166,7 +166,14 @@ private async void Save_Click(object? sender, RoutedEventArgs e) await SimpleMessageBox.ShowAsync(this, $"Warning: {ex.Message}\nOther settings were saved successfully.", "Partial Success"); } - var printScreenApplied = _autoStart.SetPrintScreenSuppressed(_settings.DisableWindowsPrintScreen); + // SetPrintScreenSuppressed always returns false on platforms with no concept of "the + // OS's own screenshot shortcut" to suppress (see IAutoStart's doc comment — Linux has + // no analogue of Windows' Snipping Tool PrintScreen registry association). Only treat + // that false as a real, worth-surfacing failure when the user actually asked for the + // suppression (the checkbox is checked) — otherwise every settings save on Linux would + // show a "Partial Success" dialog about a Windows-only feature nobody enabled. + var printScreenApplied = !_settings.DisableWindowsPrintScreen + || _autoStart.SetPrintScreenSuppressed(_settings.DisableWindowsPrintScreen); if (Owner is MainWindow mainWindow) { @@ -175,7 +182,7 @@ private async void Save_Click(object? sender, RoutedEventArgs e) var successMessage = printScreenApplied ? "Settings saved successfully! Hotkeys have been updated." - : "Settings saved, but Windows Print Screen integration could not be fully updated. You may need to reopen the app as admin or update the Print Screen snipping setting in Windows keyboard settings."; + : "Settings saved, but the Print Screen system-shortcut integration could not be fully updated (on Windows: you may need to reopen the app as admin, or update the Print Screen snipping setting in Windows keyboard settings)."; await SimpleMessageBox.ShowAsync(this, successMessage, printScreenApplied ? "Success" : "Partial Success"); Close(); diff --git a/MoneyShot.UI/Views/SimpleColorDialog.cs b/MoneyShot.UI/Views/SimpleColorDialog.cs new file mode 100644 index 0000000..a98623e --- /dev/null +++ b/MoneyShot.UI/Views/SimpleColorDialog.cs @@ -0,0 +1,142 @@ +using System.Threading.Tasks; +using Avalonia.Controls; +using Avalonia.Layout; +using Avalonia.Media; + +namespace MoneyShot.UI.Views; + +/// +/// Minimal RGB color picker for EditorWindow's "custom color" button on the non-Windows build — +/// see EditorWindow.axaml.cs's CustomColorButton_Click (#if WINDOWS keeps using the WinForms +/// ColorDialog there; WinForms isn't referenced at all under net10.0, see MoneyShot.UI.csproj). +/// Three 0-255 sliders plus a live hex readout/entry and preview swatch — not a full HSV/wheel +/// picker, but covers "pick any RGB color" which is all CustomColorButton needs. Same hand-rolled- +/// window pattern as SimpleMessageBox, for the same reason (Avalonia has no built-in color dialog +/// in the base packages this project already references). +/// +public static class SimpleColorDialog +{ + public static Task ShowAsync(Window owner, Color initial) + { + var tcs = new TaskCompletionSource(); + + var dialog = new Window + { + Title = "Custom Color", + Width = 320, + SizeToContent = SizeToContent.Height, + CanResize = false, + WindowStartupLocation = WindowStartupLocation.CenterOwner, + Background = (IBrush?)Avalonia.Application.Current!.Resources["Cocoa.WindowBrush"], + Foreground = (IBrush?)Avalonia.Application.Current!.Resources["Cocoa.TextBrush"] + }; + + var preview = new Border + { + Height = 48, + CornerRadius = new Avalonia.CornerRadius(6), + Background = new SolidColorBrush(initial), + Margin = new Avalonia.Thickness(0, 0, 0, 12) + }; + + var hexBox = new TextBox { Text = ToHex(initial), Margin = new Avalonia.Thickness(0, 0, 0, 12) }; + + var (rPanel, rSlider, rLabel) = BuildChannelRow("R", initial.R); + var (gPanel, gSlider, gLabel) = BuildChannelRow("G", initial.G); + var (bPanel, bSlider, bLabel) = BuildChannelRow("B", initial.B); + + var updatingFromHex = false; + var updatingFromSliders = false; + + void UpdateFromSliders() + { + if (updatingFromHex) return; + updatingFromSliders = true; + var color = Color.FromRgb((byte)rSlider.Value, (byte)gSlider.Value, (byte)bSlider.Value); + preview.Background = new SolidColorBrush(color); + hexBox.Text = ToHex(color); + rLabel.Text = ((byte)rSlider.Value).ToString(); + gLabel.Text = ((byte)gSlider.Value).ToString(); + bLabel.Text = ((byte)bSlider.Value).ToString(); + updatingFromSliders = false; + } + + rSlider.ValueChanged += (_, _) => UpdateFromSliders(); + gSlider.ValueChanged += (_, _) => UpdateFromSliders(); + bSlider.ValueChanged += (_, _) => UpdateFromSliders(); + + hexBox.TextChanged += (_, _) => + { + if (updatingFromSliders) return; + if (!TryParseHex(hexBox.Text, out var parsed)) return; + updatingFromHex = true; + rSlider.Value = parsed.R; + gSlider.Value = parsed.G; + bSlider.Value = parsed.B; + preview.Background = new SolidColorBrush(parsed); + updatingFromHex = false; + }; + + var buttonPanel = new StackPanel { Orientation = Orientation.Horizontal, HorizontalAlignment = HorizontalAlignment.Right, Spacing = 8, Margin = new Avalonia.Thickness(0, 12, 0, 0) }; + + void CloseWith(Color? result) + { + tcs.TrySetResult(result); + dialog.Close(); + } + + var cancelButton = new Button { Content = "Cancel", Theme = (Avalonia.Styling.ControlTheme?)Avalonia.Application.Current!.Resources["SubtleButton"], MinWidth = 76 }; + cancelButton.Click += (_, _) => CloseWith(null); + + var okButton = new Button { Content = "OK", Theme = (Avalonia.Styling.ControlTheme?)Avalonia.Application.Current!.Resources["AccentButton"], MinWidth = 76, IsDefault = true }; + okButton.Click += (_, _) => CloseWith(Color.FromRgb((byte)rSlider.Value, (byte)gSlider.Value, (byte)bSlider.Value)); + + buttonPanel.Children.Add(cancelButton); + buttonPanel.Children.Add(okButton); + + dialog.Content = new StackPanel + { + Margin = new Avalonia.Thickness(20), + Children = { preview, hexBox, rPanel, gPanel, bPanel, buttonPanel } + }; + + dialog.Closed += (_, _) => tcs.TrySetResult(null); + + dialog.ShowDialog(owner); + return tcs.Task; + } + + private static (StackPanel panel, Slider slider, TextBlock valueLabel) BuildChannelRow(string label, byte initialValue) + { + var slider = new Slider { Minimum = 0, Maximum = 255, Value = initialValue, Width = 200 }; + var valueLabel = new TextBlock { Text = initialValue.ToString(), Width = 32, VerticalAlignment = VerticalAlignment.Center }; + var panel = new StackPanel + { + Orientation = Orientation.Horizontal, + Spacing = 8, + Margin = new Avalonia.Thickness(0, 0, 0, 4), + Children = + { + new TextBlock { Text = label, Width = 14, VerticalAlignment = VerticalAlignment.Center }, + slider, + valueLabel + } + }; + return (panel, slider, valueLabel); + } + + private static string ToHex(Color color) => $"#{color.R:X2}{color.G:X2}{color.B:X2}"; + + private static bool TryParseHex(string? text, out Color color) + { + color = default; + if (string.IsNullOrWhiteSpace(text)) return false; + var trimmed = text.Trim().TrimStart('#'); + if (trimmed.Length != 6) return false; + if (!byte.TryParse(trimmed[..2], System.Globalization.NumberStyles.HexNumber, null, out var r)) return false; + if (!byte.TryParse(trimmed[2..4], System.Globalization.NumberStyles.HexNumber, null, out var g)) return false; + if (!byte.TryParse(trimmed[4..6], System.Globalization.NumberStyles.HexNumber, null, out var b)) return false; + color = Color.FromRgb(r, g, b); + return true; + } +} diff --git a/MoneyShot.UI/Views/SimpleMessageBox.cs b/MoneyShot.UI/Views/SimpleMessageBox.cs index db7264c..deacbc2 100644 --- a/MoneyShot.UI/Views/SimpleMessageBox.cs +++ b/MoneyShot.UI/Views/SimpleMessageBox.cs @@ -5,6 +5,13 @@ namespace MoneyShot.UI.Views; +// See MoneyShot.UI.Interop.WindowExtensions for why this never uses ShowDialog(owner): the owner +// passed in here is very often the (deliberately hidden, tray-app) MainWindow — Avalonia throws +// "Cannot show window with non-visible owner" in that case, confirmed by actually running the +// capture flow. A message box doesn't need strict modality against its owner, so it just always +// uses Show() + Topmost, sidestepping the constraint entirely rather than needing the +// visible/hidden fallback dance ShowAsDialogAsync does for windows that DO want real modality. + public enum SimpleMessageBoxButtons { Ok, @@ -37,7 +44,10 @@ public static Task ShowAsync(Window owner, string text, Width = 400, SizeToContent = SizeToContent.Height, CanResize = false, - WindowStartupLocation = WindowStartupLocation.CenterOwner, + // CenterOwner would need a visible owner too (same underlying Avalonia constraint) — + // center on the screen instead, which works regardless of the owner's visibility. + WindowStartupLocation = WindowStartupLocation.CenterScreen, + Topmost = true, Background = (IBrush?)Avalonia.Application.Current!.Resources["Cocoa.WindowBrush"], Foreground = (IBrush?)Avalonia.Application.Current!.Resources["Cocoa.TextBrush"] }; @@ -83,7 +93,7 @@ void CloseWith(SimpleMessageBoxResult result) // Ok/No (whichever reads as "didn't confirm") so awaiting callers never hang. dialog.Closed += (_, _) => tcs.TrySetResult(buttons == SimpleMessageBoxButtons.YesNo ? SimpleMessageBoxResult.No : SimpleMessageBoxResult.Ok); - dialog.ShowDialog(owner); + dialog.Show(); return tcs.Task; } } diff --git a/MoneyShot.sln b/MoneyShot.sln index 1995ae3..9a56754 100644 --- a/MoneyShot.sln +++ b/MoneyShot.sln @@ -13,6 +13,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MoneyShot.Platform.Windows" EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MoneyShot.UI", "MoneyShot.UI\MoneyShot.UI.csproj", "{E8E95DAF-24F0-4F34-AD67-75A9418E838F}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MoneyShot.Platform.Linux", "MoneyShot.Platform.Linux\MoneyShot.Platform.Linux.csproj", "{58E876D9-D688-43AE-A1DC-EA805F818948}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -83,6 +85,18 @@ Global {E8E95DAF-24F0-4F34-AD67-75A9418E838F}.Release|x64.Build.0 = Release|Any CPU {E8E95DAF-24F0-4F34-AD67-75A9418E838F}.Release|x86.ActiveCfg = Release|Any CPU {E8E95DAF-24F0-4F34-AD67-75A9418E838F}.Release|x86.Build.0 = Release|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Debug|Any CPU.Build.0 = Debug|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Debug|x64.ActiveCfg = Debug|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Debug|x64.Build.0 = Debug|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Debug|x86.ActiveCfg = Debug|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Debug|x86.Build.0 = Debug|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Release|Any CPU.ActiveCfg = Release|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Release|Any CPU.Build.0 = Release|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Release|x64.ActiveCfg = Release|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Release|x64.Build.0 = Release|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Release|x86.ActiveCfg = Release|Any CPU + {58E876D9-D688-43AE-A1DC-EA805F818948}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/MoneyShot/Services/HistoryService.cs b/MoneyShot/Services/HistoryService.cs index 97f19b8..5913978 100644 --- a/MoneyShot/Services/HistoryService.cs +++ b/MoneyShot/Services/HistoryService.cs @@ -21,10 +21,7 @@ public sealed class HistoryService public HistoryService() { - _historyDirectory = Path.Combine( - Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), - "MoneyShot", - "history"); + _historyDirectory = Path.Combine(AppDataPaths.GetConfigRoot(), "MoneyShot", "history"); try { Directory.CreateDirectory(_historyDirectory); diff --git a/Packaging/linux/build-appimage.sh b/Packaging/linux/build-appimage.sh new file mode 100644 index 0000000..b947aee --- /dev/null +++ b/Packaging/linux/build-appimage.sh @@ -0,0 +1,52 @@ +#!/bin/bash +# Builds an AppImage from a self-contained linux-x64 publish of MoneyShot.UI. +# Usage: build-appimage.sh +# Requires `appimagetool` on PATH (or set APPIMAGETOOL to its path) — see LINUX_PORT.md Phase 3. +# +# Deliberately hand-assembles the AppDir instead of using linuxdeploy: linuxdeploy's plugin +# ecosystem is built around dynamically-linked C/C++ apps (discovering and bundling .so +# dependencies via ldd), which doesn't fit a self-contained .NET publish that already carries +# every dependency it needs — there's nothing for linuxdeploy's own dependency-bundling step to +# usefully do here, only an AppRun entry point and the standard root-level desktop/icon files. +set -euo pipefail + +PUBLISH_DIR="$1" +VERSION="$2" +OUTPUT_APPIMAGE="$3" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +if [ ! -d "$PUBLISH_DIR" ]; then + echo "error: publish directory '$PUBLISH_DIR' does not exist" >&2 + exit 1 +fi + +APPIMAGETOOL="${APPIMAGETOOL:-appimagetool}" +if ! command -v "$APPIMAGETOOL" >/dev/null 2>&1; then + echo "error: appimagetool not found on PATH (set APPIMAGETOOL to its path)" >&2 + exit 1 +fi + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +APPDIR="$WORK_DIR/MoneyShot.AppDir" +mkdir -p "$APPDIR/usr/bin" +cp -r "$PUBLISH_DIR"/. "$APPDIR/usr/bin/" +chmod 755 "$APPDIR/usr/bin/MoneyShot.UI" + +cat > "$APPDIR/AppRun" <<'EOF' +#!/bin/sh +HERE="$(dirname "$(readlink -f "${0}")")" +exec "$HERE/usr/bin/MoneyShot.UI" "$@" +EOF +chmod 755 "$APPDIR/AppRun" + +# appimagetool requires the .desktop file and icon at the AppDir root (in addition to, or instead +# of, the usual /usr/share/applications convention) — Exec= must be a bare command name per the +# AppImage/desktop-entry convention, resolved through AppRun rather than a real PATH lookup. +sed 's/^Exec=.*/Exec=AppRun/' "$SCRIPT_DIR/moneyshot.desktop" > "$APPDIR/moneyshot.desktop" +cp "$SCRIPT_DIR/../../MoneyShot.UI/Assets/icon.png" "$APPDIR/moneyshot.png" + +mkdir -p "$(dirname "$OUTPUT_APPIMAGE")" +ARCH=x86_64 "$APPIMAGETOOL" "$APPDIR" "$OUTPUT_APPIMAGE" +echo "Built $OUTPUT_APPIMAGE" diff --git a/Packaging/linux/build-deb.sh b/Packaging/linux/build-deb.sh new file mode 100644 index 0000000..6cd54ad --- /dev/null +++ b/Packaging/linux/build-deb.sh @@ -0,0 +1,92 @@ +#!/bin/bash +# Builds a .deb package from a self-contained linux-x64 publish of MoneyShot.UI. +# Usage: build-deb.sh +# +# Layout matches standard practice for self-contained .NET apps on Debian/Ubuntu: the whole +# publish output (runtime included) goes under /opt/moneyshot rather than scattering DLLs into +# /usr/lib, with a tiny wrapper script on PATH. See LINUX_PORT.md Phase 3. +set -euo pipefail + +PUBLISH_DIR="$1" +VERSION="$2" +OUTPUT_DEB="$3" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +if [ ! -d "$PUBLISH_DIR" ]; then + echo "error: publish directory '$PUBLISH_DIR' does not exist" >&2 + exit 1 +fi + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT + +PKG_ROOT="$WORK_DIR/moneyshot" +mkdir -p "$PKG_ROOT/DEBIAN" +mkdir -p "$PKG_ROOT/opt/moneyshot" +mkdir -p "$PKG_ROOT/usr/bin" +mkdir -p "$PKG_ROOT/usr/share/applications" +mkdir -p "$PKG_ROOT/usr/share/icons/hicolor/256x256/apps" + +cp -r "$PUBLISH_DIR"/. "$PKG_ROOT/opt/moneyshot/" +chmod 755 "$PKG_ROOT/opt/moneyshot/MoneyShot.UI" + +cat > "$PKG_ROOT/usr/bin/moneyshot" <<'EOF' +#!/bin/sh +exec /opt/moneyshot/MoneyShot.UI "$@" +EOF +chmod 755 "$PKG_ROOT/usr/bin/moneyshot" + +cp "$SCRIPT_DIR/moneyshot.desktop" "$PKG_ROOT/usr/share/applications/moneyshot.desktop" +cp "$PUBLISH_DIR/../MoneyShot.UI/Assets/icon.png" "$PKG_ROOT/usr/share/icons/hicolor/256x256/apps/moneyshot.png" 2>/dev/null \ + || cp "$SCRIPT_DIR/../../MoneyShot.UI/Assets/icon.png" "$PKG_ROOT/usr/share/icons/hicolor/256x256/apps/moneyshot.png" + +# Debian's Installed-Size is in KiB. +INSTALLED_SIZE_KB=$(du -sk "$PKG_ROOT/opt/moneyshot" | cut -f1) + +cat > "$PKG_ROOT/DEBIAN/control" < +Homepage: https://github.com/Daolyap/Money-Shot +Description: Capture, annotate, and share screenshots + Money Shot is a screenshot capture and annotation tool with region/full- + screen/monitor capture, a full annotation toolset (shapes, arrows, text, + numbering, pixelate), history, and global hotkeys. + . + This build's Linux platform layer (X11 capture and hotkeys, StatusNotifierItem + tray icon, XDG autostart, clipboard) targets X11 sessions — see the project's + LINUX_PORT.md for current Wayland-specific caveats (global hotkeys, in + particular, have no direct Wayland equivalent). +EOF + +# update-desktop-database/gtk-update-icon-cache are best-effort: absent on some minimal systems +# (containers, some non-GNOME/GTK setups), and their absence should never fail the whole install. +cat > "$PKG_ROOT/DEBIAN/postinst" <<'EOF' +#!/bin/sh +set -e +if command -v update-desktop-database >/dev/null 2>&1; then + update-desktop-database -q /usr/share/applications || true +fi +if command -v gtk-update-icon-cache >/dev/null 2>&1; then + gtk-update-icon-cache -q /usr/share/icons/hicolor || true +fi +exit 0 +EOF +chmod 755 "$PKG_ROOT/DEBIAN/postinst" + +cat > "$PKG_ROOT/DEBIAN/prerm" <<'EOF' +#!/bin/sh +set -e +exit 0 +EOF +chmod 755 "$PKG_ROOT/DEBIAN/prerm" + +mkdir -p "$(dirname "$OUTPUT_DEB")" +dpkg-deb --build --root-owner-group "$PKG_ROOT" "$OUTPUT_DEB" +echo "Built $OUTPUT_DEB" diff --git a/Packaging/linux/build-rpm.sh b/Packaging/linux/build-rpm.sh new file mode 100644 index 0000000..a8e6126 --- /dev/null +++ b/Packaging/linux/build-rpm.sh @@ -0,0 +1,51 @@ +#!/bin/bash +# Builds a .rpm package from a self-contained linux-x64 publish of MoneyShot.UI. +# Usage: build-rpm.sh [release] +# Requires `rpmbuild` (package "rpm-build" on Fedora, "rpm" on Debian/Ubuntu) and `file` (rpmbuild's +# brp-strip build-root-policy scripts silently no-op without it). See LINUX_PORT.md Phase 3 — same +# "package the already-published output" approach as build-deb.sh, rather than building from +# source inside rpmbuild's own sandbox. +# +# [release] defaults to 1 (a plain local/manual build). CI passes the run number here — RPM's +# Version+Release+dist triple is the uniqueness/traceability equivalent of what Windows' MSI gets +# from AssemblyVersion="$version.$run_number" — Version itself deliberately stays the plain semver +# from the csproj (rpmbuild rejects some non-numeric-run-on version shapes, and Release is the +# field this ecosystem actually expects a build/packaging counter in). +set -euo pipefail + +VERSION="$2" +RELEASE="${4:-1}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +if [ ! -d "$1" ]; then + echo "error: publish directory '$1' does not exist" >&2 + exit 1 +fi +# rpmbuild's %install step runs from its own BUILD directory, not the caller's cwd — a relative +# PUBLISH_DIR (the normal case when this is invoked from a CI workflow step) would silently resolve +# against the wrong directory there and fail with "No such file or directory". Resolved to an +# absolute path up front instead (confirmed by actually hitting exactly that failure with a +# relative path — see LINUX_PORT.md Phase 3 verification notes). OUTPUT_DIR is resolved too since +# rpmbuild's %clean/cleanup also runs from elsewhere and the final `cp` should not depend on cwd. +PUBLISH_DIR="$(cd "$1" && pwd)" +mkdir -p "$3" +OUTPUT_DIR="$(cd "$3" && pwd)" + +ICON_FILE="$SCRIPT_DIR/../../MoneyShot.UI/Assets/icon.png" +DESKTOP_FILE="$SCRIPT_DIR/moneyshot.desktop" + +WORK_DIR="$(mktemp -d)" +trap 'rm -rf "$WORK_DIR"' EXIT +mkdir -p "$WORK_DIR"/{BUILD,RPMS,SOURCES,SPECS,SRPMS} + +rpmbuild --define "_topdir $WORK_DIR" \ + --define "_moneyshot_version $VERSION" \ + --define "_moneyshot_release $RELEASE" \ + --define "_moneyshot_publish_dir $PUBLISH_DIR" \ + --define "_moneyshot_icon_file $ICON_FILE" \ + --define "_moneyshot_desktop_file $DESKTOP_FILE" \ + -bb "$SCRIPT_DIR/rpm/moneyshot.spec" + +find "$WORK_DIR/RPMS" -name '*.rpm' -exec cp {} "$OUTPUT_DIR/" \; +echo "Built RPM(s) into $OUTPUT_DIR:" +find "$OUTPUT_DIR" -name '*.rpm' diff --git a/Packaging/linux/moneyshot.desktop b/Packaging/linux/moneyshot.desktop new file mode 100644 index 0000000..47d644d --- /dev/null +++ b/Packaging/linux/moneyshot.desktop @@ -0,0 +1,9 @@ +[Desktop Entry] +Type=Application +Name=Money Shot +Comment=Capture, annotate, and share screenshots +Exec=moneyshot +Icon=moneyshot +Terminal=false +Categories=Graphics;Utility; +StartupWMClass=MoneyShot.UI diff --git a/Packaging/linux/rpm/moneyshot.spec b/Packaging/linux/rpm/moneyshot.spec new file mode 100644 index 0000000..852162f --- /dev/null +++ b/Packaging/linux/rpm/moneyshot.spec @@ -0,0 +1,57 @@ +Name: moneyshot +Version: %{_moneyshot_version} +Release: %{_moneyshot_release}%{?dist} +Summary: Capture, annotate, and share screenshots +License: Proprietary +URL: https://github.com/Daolyap/Money-Shot +BuildArch: x86_64 +Requires: libICE, libSM, libX11, libXrandr, fontconfig, openssl-libs +Recommends: xclip +AutoReqProv: no + +%description +Money Shot is a screenshot capture and annotation tool with region/full-screen/ +monitor capture, a full annotation toolset (shapes, arrows, text, numbering, +pixelate), history, and global hotkeys. + +This build's Linux platform layer (X11 capture and hotkeys, StatusNotifierItem +tray icon, XDG autostart, clipboard) targets X11 sessions — see the project's +LINUX_PORT.md for current Wayland-specific caveats (global hotkeys, in +particular, have no direct Wayland equivalent). + +%install +rm -rf %{buildroot} +mkdir -p %{buildroot}/opt/moneyshot +cp -r %{_moneyshot_publish_dir}/. %{buildroot}/opt/moneyshot/ +chmod 755 %{buildroot}/opt/moneyshot/MoneyShot.UI + +mkdir -p %{buildroot}/usr/bin +cat > %{buildroot}/usr/bin/moneyshot <<'EOF' +#!/bin/sh +exec /opt/moneyshot/MoneyShot.UI "$@" +EOF +chmod 755 %{buildroot}/usr/bin/moneyshot + +mkdir -p %{buildroot}/usr/share/applications +install -m 644 %{_moneyshot_desktop_file} %{buildroot}/usr/share/applications/moneyshot.desktop + +mkdir -p %{buildroot}/usr/share/icons/hicolor/256x256/apps +install -m 644 %{_moneyshot_icon_file} %{buildroot}/usr/share/icons/hicolor/256x256/apps/moneyshot.png + +%files +/opt/moneyshot +/usr/bin/moneyshot +/usr/share/applications/moneyshot.desktop +/usr/share/icons/hicolor/256x256/apps/moneyshot.png + +%post +if command -v update-desktop-database >/dev/null 2>&1; then + update-desktop-database -q /usr/share/applications || true +fi +if command -v gtk-update-icon-cache >/dev/null 2>&1; then + gtk-update-icon-cache -q /usr/share/icons/hicolor || true +fi + +%changelog +* Thu Jan 01 2026 Daolyap & iSaluki - initial +- Initial Fedora/RPM packaging (see LINUX_PORT.md Phase 3) From da2a675609a2acb7bec774e133cf8c4ad293be22 Mon Sep 17 00:00:00 2001 From: Logan H Date: Thu, 10 Sep 2026 09:42:17 +0100 Subject: [PATCH 4/6] feat: Wayland screen capture via XDG portal (Phase 4, partial) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit X11 XGetImage never saw native Wayland content, causing the exact "Capture Error" a user hit on Fedora KDE (Plasma Wayland, the session default). LinuxScreenCapture now detects $WAYLAND_DISPLAY and routes full-screen/region capture through org.freedesktop.portal.Screenshot (via Tmds.DBus, a pure managed D-Bus client) instead. Per-monitor capture degrades to whole-desktop under Wayland (no portal-level per-output selector short of the heavier ScreenCast API). Global hotkeys remain X11-only — GlobalShortcuts is a separately-scoped portal with its own interactive binding UX, not attempted here. Not yet live-verified against a real compositor/portal backend: Docker Desktop hit an unrelated startup bug on the dev machine (stale sailor-ingest.sock) that a restart, manual delete, and wsl --shutdown all failed to clear. The D-Bus proxy shapes were checked against Tmds.DBus's own modelling docs and a working example rather than guessed. See LINUX_PORT.md Phase 4 for the full verified/not-verified breakdown. Co-Authored-By: Claude Sonnet 5 --- CLAUDE.md | 19 +- LINUX_PORT.md | 190 ++++++++++++------ .../LinuxScreenCapture.cs | 60 ++++-- .../MoneyShot.Platform.Linux.csproj | 11 +- .../WaylandPortalScreenCapture.cs | 151 ++++++++++++++ Packaging/linux/build-deb.sh | 11 +- Packaging/linux/rpm/moneyshot.spec | 11 +- 7 files changed, 358 insertions(+), 95 deletions(-) create mode 100644 MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs diff --git a/CLAUDE.md b/CLAUDE.md index 552f4f7..7f357e4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -44,9 +44,11 @@ installer and CI release pipeline both build it, unchanged; it is Windows-only a `Packaging/linux/` and `.github/workflows/build-linux.yml`. It is **not** wired into the Windows MSI/release pipeline (that stays on the WPF app) — don't touch WPF's behavior when working on `MoneyShot.UI`. Before relying on `MoneyShot.UI` for anything beyond what `LINUX_PORT.md` documents -as verified, read its Phase 1/2/3 status sections — most core flows (capture, editor, history, -settings, tray, packaging) are genuinely verified against real Windows and Linux runs; some -(`EditorWindow`'s deeper tools, multi-monitor/HiDPI on Linux, Wayland entirely) are not. +as verified, read its Phase 1-4 status sections — most core flows (capture, editor, history, +settings, tray, packaging) are genuinely verified against real Windows and Linux (X11) runs; some +(`EditorWindow`'s deeper tools, multi-monitor/HiDPI on Linux, Wayland global hotkeys) are not, and +Wayland capture specifically is implemented but not yet live-verified against a real compositor — +see `LINUX_PORT.md` § 2. - **`MoneyShot.Core`** (`net10.0`, no UI/Windows dependency) — Models, `SettingsService`, `Logger`, `AutoUpdateService`, `HotKeyParser`, `AppDataPaths` (resolves the per-user config root — @@ -59,10 +61,13 @@ settings, tray, packaging) are genuinely verified against real Windows and Linux Deliberately UI-framework-agnostic (references WinForms only for `NotifyIcon`/`Clipboard`, not WPF) so the same implementations work under both `MoneyShot` (WPF) and `MoneyShot.UI` (Avalonia). - **`MoneyShot.Platform.Linux`** (`net10.0`, no Avalonia dependency) — `LinuxScreenCapture` (X11 - `XGetImage` + `xrandr`-parsed monitor bounds), `LinuxGlobalHotkeys` (X11 `XGrabKey`), - `LinuxAutoStart` (XDG `~/.config/autostart/*.desktop`), `LinuxClipboard` (SkiaSharp PNG-encode + - `wl-copy`/`xclip`), `LinuxMemoryTrimmer`. X11-only — no Wayland-native capture/hotkeys yet (see - `LINUX_PORT.md`'s Wayland-status section). + `XGetImage` + `xrandr`-parsed monitor bounds on an X11 session; routes to + `WaylandPortalScreenCapture`, an `org.freedesktop.portal.Screenshot` call via `Tmds.DBus`, when + `$WAYLAND_DISPLAY` is set — implemented but not yet live-verified against a real compositor, see + `LINUX_PORT.md` § 2/Phase 4), `LinuxGlobalHotkeys` (X11 `XGrabKey` — still X11-only, no Wayland + `GlobalShortcuts` portal yet), `LinuxAutoStart` (XDG `~/.config/autostart/*.desktop`), + `LinuxClipboard` (SkiaSharp PNG-encode + `wl-copy`/`xclip`), `LinuxMemoryTrimmer`. See + `LINUX_PORT.md`'s Wayland-status section for exactly what works on which session type. - **`MoneyShot`** (WPF, Windows-only) — every XAML window, plus `SaveService`/`HistoryService` (`BitmapSource`-based). `Interop/BitmapConversions.cs` converts `CapturedImage` ↔ `BitmapSource` at the UI boundary. diff --git a/LINUX_PORT.md b/LINUX_PORT.md index 16ed0c2..57d3b80 100644 --- a/LINUX_PORT.md +++ b/LINUX_PORT.md @@ -14,21 +14,39 @@ > launched successfully**; an AppImage build path exists and was verified to build and run too. > `.github/workflows/build-linux.yml` builds and packages all three on every PR/release, and > `release.yml` attaches them to the same auto-created release the Windows MSI/zip go to. -> **Remaining real gaps**: no Wayland-native capture or hotkeys (X11/XWayland only — see § 2 and -> § 3), the tray icon has not been confirmed against a real desktop's StatusNotifierWatcher (only -> confirmed to not crash without one), and `EditorWindow`'s deeper tool interactions (resize, crop, -> zoom/pan, pixelate) were verified on Windows but not separately re-verified on Linux. See -> § Migration phases for the full verified-vs-not breakdown per phase. +> **Wayland capture (Phase 4, partial) added 2026-09**: `LinuxScreenCapture` now detects a Wayland +> session (`$WAYLAND_DISPLAY`) and routes to `WaylandPortalScreenCapture` +> (`org.freedesktop.portal.Screenshot` via `Tmds.DBus`) instead of X11 `XGetImage`, which does not +> see native Wayland content. This closes the exact failure a real user hit on Fedora KDE (Plasma +> Wayland, Fedora's and current Debian's default session type) — see § Wayland status. **This code +> compiles clean and its D-Bus proxy/signal shapes were verified against Tmds.DBus's own documented +> API and a real working example (its NetworkManager how-to), but it was not live-tested against a +> real portal backend this round** — Docker Desktop hit an unrelated startup bug +> (`sailor-ingest.sock` stale-rename failure) on this machine that a normal restart/WSL-shutdown +> couldn't clear, blocking the headless-compositor test container that would have exercised it +> end-to-end. Global hotkeys remain X11-only — `org.freedesktop.portal.GlobalShortcuts` (a larger, +> separately-scoped feature) was not attempted. See § Phase 4 status for the exact verified/ +> not-verified breakdown. +> +> **Remaining real gaps**: Wayland global hotkeys (portal `GlobalShortcuts`, not attempted — tray +> menu/in-app buttons remain the working alternative), the new Wayland capture path's live behavior +> against a real compositor (see above), per-monitor capture under Wayland (portal has no per-output +> selector outside the heavier ScreenCast API — see § 2), the tray icon has not been confirmed +> against a real desktop's StatusNotifierWatcher (only confirmed to not crash without one), and +> `EditorWindow`'s deeper tool interactions (resize, crop, zoom/pan, pixelate) were verified on +> Windows but not separately re-verified on Linux. See § Migration phases for the full +> verified-vs-not breakdown per phase. ## TL;DR -The Linux port is **done for a v1 that matches today's Windows feature set on X11 sessions**: -region/full-screen/monitor capture, the annotation editor, tray icon, global hotkeys, history, -settings, and autostart all work on real Linux, packaged as `.deb`, `.rpm`, and AppImage. The -remaining gap is **Wayland**: X11 direct-capture (`XGetImage`) and X11 global hotkeys -(`XGrabKey`) are what's implemented, and neither has a real equivalent under a native Wayland -session with no XWayland — see § Wayland status below for exactly what that means in practice on -today's Debian/Fedora defaults. +The Linux port matches today's Windows feature set on X11 sessions: region/full-screen/monitor +capture, the annotation editor, tray icon, global hotkeys, history, settings, and autostart all work +on real Linux, packaged as `.deb`, `.rpm`, and AppImage. On **Wayland** sessions (the default on +current Debian and Fedora, including Fedora's KDE spin), full-screen and region capture now go +through the XDG Desktop Portal instead of failing outright — implemented this round but not yet +live-verified against a real compositor (see the status note above). Wayland **global hotkeys** +remain unimplemented (no portal equivalent attempted yet); the tray menu and in-app capture buttons +are the working fallback there. See § Wayland status below for what that means in practice. ## What ports cleanly (small or no changes) @@ -67,7 +85,7 @@ WPF, which means `EditorWindow`'s 1900-line code-behind ports with mostly mechan (b) WPF-style XAML can be reused with minor namespace edits; (c) it has working hotkey, tray, and clipboard primitives on Linux out of the box. -### 2. Capture pipeline — ✅ implemented (X11), Wayland still open +### 2. Capture pipeline — ✅ implemented (X11, genuinely verified), ⚠️ implemented (Wayland, not yet live-verified) `MoneyShot.Platform.Linux/LinuxScreenCapture.cs` implements `IScreenCapture` via raw `libX11.so.6` P/Invoke (`X11Interop.cs`): `XGetImage` against the root window for full-screen and per-monitor @@ -79,17 +97,43 @@ enumeration and `CaptureFullScreen` confirmed to return correct dimensions/geome standalone test harness, and a full capture triggered by a real `XGrabKey`-delivered hotkey was confirmed to render correctly inside `EditorWindow` (screenshotted and visually inspected). -**Wayland is not implemented.** `XGetImage` against the root window only sees X11/XWayland -content — under a native Wayland session (the default on current GNOME/KDE, meaning current -Debian/Fedora out of the box) there is no root window with real pixels to read, so -`LinuxScreenCapture` will either throw (`XOpenDisplay` fails with no X server at all) or silently -capture nothing useful. The correct fix for native Wayland is the XDG Desktop Portal -`org.freedesktop.portal.Screenshot` D-Bus service, which — critically — requires an interactive, -per-capture consent dialog from the compositor (no instant, silent capture the way Windows/X11 -allow), a real and unavoidable UX change under Wayland policy. This was not implemented: no -portal-backend service was available in any test environment used this session to build and verify -against, and the interactive-consent-dialog UX question is a product decision, not just an -implementation detail. See § Wayland status. +**Wayland capture is now implemented, via the portal.** `XGetImage` against the X11 root window +doesn't see native Wayland compositor content by design (Wayland's security model keeps that off- +limits outside a brokered mechanism) — this is the exact failure a real user hit trying to capture +on Fedora KDE (Plasma Wayland). `LinuxScreenCapture` now checks `$WAYLAND_DISPLAY` up front (the +same signal GTK/Qt/SDL use, and the same one `LinuxClipboard` already checked for `wl-copy` vs +`xclip`) and routes to `WaylandPortalScreenCapture.cs`, which calls the XDG Desktop Portal's +`org.freedesktop.portal.Screenshot` D-Bus method (`interactive: false`, so the backend takes an +immediate full screenshot rather than showing its own region picker — MoneyShot already has +`RegionSelector` for that) via `Tmds.DBus` (a pure managed D-Bus client — no `libdbus` dependency), +waits for the async `Request.Response` signal, and decodes the returned PNG (via SkiaSharp) into a +`CapturedImage`. + +**Verified**: the code compiles cleanly on both TFMs, and the exact D-Bus proxy interface shapes +(`[DBusInterface]`, `IDBusObject`, `Task ScreenshotAsync(...)`, +`Task WatchResponseAsync(Action<(uint, IDictionary)>, ...)`, +`IDictionary` for `a{sv}`) were checked against Tmds.DBus's own published modelling +docs and a real, complete working example (its NetworkManager `WatchStateChangedAsync` how-to) — +not guessed from memory. **Not verified**: an actual round trip against a running portal backend +(`xdg-desktop-portal` + `xdg-desktop-portal-kde`/`-gnome`/`-wlr`). This session's plan was to +exercise it against a headless `sway` (wlroots) compositor + `xdg-desktop-portal-wlr` in a Docker +container — the same kind of standalone-harness verification that caught the X11 capture path's +real bugs — but Docker Desktop hit an unrelated startup bug on this machine (`sailor-ingest.sock` +failed its internal stale-rename with "The file cannot be accessed by the system"; a full engine +restart, deleting the stale socket via PowerShell/cmd/bash, and `wsl --shutdown` all failed to clear +it) that blocked starting any container this session. **Treat the Wayland capture path as +implemented-but-unverified until it's exercised against a real compositor** — the most likely risk +areas if something's wrong: the D-Bus proxy method-name-to-signal-name mapping convention, the +`handle_token`/response-race assumption (see the code's own comment on this), or a portal backend +returning the `uri` result in a shape (e.g. always via the document portal, always requiring a +`file://` URI with the caller's own read access) other than what's coded for. + +Only full-desktop capture is portal-based; there is no portal equivalent to xrandr's per-monitor +geometry outside the much heavier ScreenCast API (which requires an interactive source-picker UI +and hands back a live PipeWire stream, not a single screenshot — a different feature, not attempted +this round). `GetAllMonitors()` under Wayland reports a single monitor spanning "everything the +portal returns," matching the existing X11 fallback's graceful-degradation shape when `xrandr` is +unavailable. ### 3. Global hotkeys — ✅ implemented (X11), no Wayland equivalent @@ -103,14 +147,17 @@ and ran the full capture flow — this also validated the hand-derived `XKeyEven offsets used to read the keycode/modifier state back out of the raw X11 event buffer, which were computed by hand from the Xlib ABI and could easily have been wrong without this test. -**Wayland has no direct equivalent** — compositors deliberately do not let clients grab input -they don't have focus for. The portal `org.freedesktop.portal.GlobalShortcuts` API is the -correct-but-not-implemented path (same reasoning as capture: needs a portal backend to build -against, and changes the binding UX — the user binds the shortcut in system settings, not in -MoneyShot). Under a pure Wayland session, `LinuxGlobalHotkeys.Initialize()` logs a warning and -no-ops rather than crashing (mirrors `Win32GlobalHotkeys`' existing "combination may be in use" -non-fatal pattern) — hotkeys just silently don't fire; the tray menu and in-app buttons remain the -working alternative. +**Wayland has no direct equivalent, and this is still not implemented** — compositors deliberately +do not let clients grab input they don't have focus for. The portal +`org.freedesktop.portal.GlobalShortcuts` API is the correct path, but it's a materially bigger +feature than the Screenshot portal added this round: it needs its own session-creation handshake, a +one-time interactive shortcut-binding dialog (the user binds the combination in the portal's own +UI, not by typing it into MoneyShot's settings), and an `Activated` signal subscription per bound +shortcut — different enough from a single request/response call that it was deliberately left out +of this pass rather than rushed alongside the capture fix. Under a Wayland session, +`LinuxGlobalHotkeys.Initialize()` still logs a warning and no-ops rather than crashing (mirrors +`Win32GlobalHotkeys`' existing "combination may be in use" non-fatal pattern) — hotkeys just +silently don't fire; the tray menu and in-app buttons remain the working alternative. ### 4. System tray (`NotifyIcon`) — ✅ implemented, reuses Avalonia's own cross-platform TrayIcon @@ -526,34 +573,45 @@ individual step's shell commands were run for real, but the workflow files thems executed inside GitHub's own runner infrastructure yet. AUR (Arch) packaging remains community-maintainable but wasn't built here. -**Phase 4 — Wayland (deferred, still not started).** Portal-based `org.freedesktop.portal. -Screenshot` capture and `org.freedesktop.portal.GlobalShortcuts` hotkeys are the correct paths — -see § 2 and § 3 for exactly what's missing and why it wasn't attempted this round (no portal -backend service was available in any environment used to build/verify this port, and the -interactive-consent-dialog UX change is a product decision that should be made deliberately, not -implemented blind). **2–3 weeks if pursued**, unchanged from the original estimate — nothing done -in Phase 2/3 reduces this, since Wayland capture/hotkeys are architecturally a different mechanism -(D-Bus/portal) from the X11 approach actually implemented, not an extension of it. +**Phase 4 — Wayland (capture done this round, not yet live-verified; hotkeys still deferred).** +Portal-based `org.freedesktop.portal.Screenshot` capture is now implemented — see § 2 for what it +does, how it was checked (against Tmds.DBus's own docs/examples, not guessed), and exactly what +"not yet live-verified" means (Docker Desktop broke on this machine before a real portal backend +could be exercised against it — see § 2's "Not verified" paragraph for the specific bug and what +was tried). `org.freedesktop.portal.GlobalShortcuts` hotkeys remain **not implemented** — see § 3 +for why that's a separately-scoped, larger piece of work (its own session/binding-dialog/signal +model, not a small extension of the Screenshot portal call). **Estimate for hotkeys alone, if +pursued: ~1 week** (smaller than the original combined 2-3 week Phase 4 estimate now that capture +is done) — most of the remaining cost is the interactive one-time binding-dialog flow and the +inherent inability to test it without a real compositor + portal backend running, same limitation +this round's capture work hit. ## Wayland status (read this before deploying to Debian/Fedora desktop users) -**Both current Debian (12, "bookworm," GNOME on Wayland by default) and Fedora Workstation default -to a native Wayland session out of the box.** On such a session, *as currently implemented*: -- Screen capture will fail (`XOpenDisplay` finds no X server) unless the user is on an X11/Xorg - session, or a compositor exposing enough of an XWayland-visible surface for `XGetImage` to - return something meaningful (untested; likely to be incomplete or wrong even when it doesn't - outright fail). -- Global hotkeys silently do nothing (logged once, then quiet) — the tray menu and in-app capture - buttons remain fully functional as the fallback. +**Both current Debian (12, "bookworm," GNOME on Wayland by default) and Fedora Workstation +(including its KDE Plasma spin) default to a native Wayland session out of the box.** On such a +session, *as currently implemented*: +- Screen capture (full-screen and region) now goes through the XDG Desktop Portal instead of + failing — this is the fix for the exact "Capture Error" a real user hit on Fedora KDE. **Not yet + verified against a real compositor** (see § 2) — if the portal backend on a given system behaves + differently than assumed (e.g. a different `results` shape, or `interactive: false` still + requiring some confirmation this session's code doesn't expect), it may still fail; if that + happens, the in-app error message will now at least come from the portal path (mentioning + `xdg-desktop-portal`) rather than the old X11 "could not open display" message, which helps + diagnose which case is occurring. Per-monitor capture ("Capture Monitor N") captures the whole + virtual desktop, not a single output — see § 2 for why. +- Global hotkeys still silently do nothing (logged once, then quiet) — the tray menu and in-app + capture buttons remain fully functional as the fallback. - The tray icon, clipboard, and autostart all work regardless of X11 vs. Wayland — none of those three depend on the display-server-specific mechanisms above. -**Practically**: this build is genuinely useful today for X11 sessions (still selectable at the -login/display-manager screen on virtually every mainstream distro, including Debian and Fedora, -even where Wayland is the default) and for the parts of a Wayland session that don't touch capture/ -hotkeys. It is **not** a full drop-in replacement for the Windows experience on a default modern -Wayland desktop until Phase 4 lands. This should be stated plainly in any release notes / README -for the Linux build, not discovered by users via a silent capture failure. +**Practically**: X11 sessions (still selectable at the login/display-manager screen on virtually +every mainstream distro, including Debian and Fedora — on KDE specifically, the gear-icon session +picker at the SDDM login screen offers "Plasma (X11)" alongside the default "Plasma (Wayland)") +remain the best-tested path today and are guaranteed to work with everything in this port, +including hotkeys. Wayland sessions now get working capture (pending live verification — see +above) but still no global hotkeys. This should be stated plainly in any release notes / README for +the Linux build. ## Packaging on Linux @@ -595,17 +653,23 @@ Still genuinely open: single-monitor. `RegionSelector`'s DPI-aware crop math (already fixed for WPF's 125%-scaling bug, see `Opus-Speaks.md` § E2, and ported into the Avalonia build using `Screens.Primary. Scaling`) has not been exercised at a non-100% Linux scale factor at all. -- **Wayland** — see § Wayland status above; this is the single largest remaining gap. +- **Wayland global hotkeys** — see § Wayland status above; capture is now implemented (pending live + verification), hotkeys are not. +- **The new Wayland capture path's live behavior** — implemented and checked against Tmds.DBus's + own docs/examples, but not yet run against a real portal backend (Docker Desktop broke on this + dev machine before that test could happen — see § 2). First thing to verify once Docker (or any + other Linux environment with a real KDE/GNOME Wayland session) is available again. ## Decision matrix for the team -The build/no-build decision this table originally framed is now moot — Phases 0–3 are done. What's -left is a narrower question: **is Wayland support (Phase 4) worth 2–3 more weeks**, given the port -already works on X11 sessions (still selectable at login on virtually every mainstream distro) and +The build/no-build decision this table originally framed is now moot — Phases 0–3 are done, and +Phase 4's capture half is implemented. What's left is narrower: **is Wayland global hotkeys worth +~1 more week**, given capture (the more commonly hit gap — it's what a real user's Fedora KDE bug +report was about) now works there too, X11 sessions already have full hotkey support, and X11-independent features (tray, clipboard, autostart, packaging) work regardless of session type. -That's a product call — how many target users are on a Wayland-only setup with no X11 fallback — -not an engineering-feasibility one; the engineering path (portal-based capture + GlobalShortcuts, -with an interactive per-capture consent dialog as an unavoidable UX change) is understood and +That's still partly a product call (how many target users rely on a global hotkey specifically, on +a Wayland-only setup with no X11 fallback) but a smaller one than before — the engineering path +(portal `GlobalShortcuts`, with its own one-time interactive binding-dialog UX) is understood and documented above, just not built. ## What actually changed (concrete list) @@ -615,7 +679,9 @@ Reflects what was actually done, not a pre-port plan — the shipping WPF app (` platform-neutral code both builds use (`MoneyShot.Core`). - `MoneyShot.Platform.Linux/` (new project) — `LinuxScreenCapture.cs`, `LinuxGlobalHotkeys.cs`, - `X11Interop.cs`, `LinuxAutoStart.cs`, `LinuxClipboard.cs`, `LinuxMemoryTrimmer.cs` + `X11Interop.cs`, `LinuxAutoStart.cs`, `LinuxClipboard.cs`, `LinuxMemoryTrimmer.cs`, plus (2026-09, + Phase 4) `WaylandPortalScreenCapture.cs` — XDG portal capture for Wayland sessions, and a new + `Tmds.DBus` package reference (pure managed, no native/libdbus dependency, no packaging impact) - `MoneyShot.UI/MoneyShot.UI.csproj` — multi-targets `net10.0-windows;net10.0`; TFM-conditional `ProjectReference`s to `Platform.Windows`/`Platform.Linux`; `WINDOWS` compile constant for the Windows TFM only; `SkiaSharp.NativeAssets.Linux` explicitly pinned (see the SkiaSharp bug above); diff --git a/MoneyShot.Platform.Linux/LinuxScreenCapture.cs b/MoneyShot.Platform.Linux/LinuxScreenCapture.cs index 4be61ee..8662cda 100644 --- a/MoneyShot.Platform.Linux/LinuxScreenCapture.cs +++ b/MoneyShot.Platform.Linux/LinuxScreenCapture.cs @@ -7,25 +7,31 @@ namespace MoneyShot.Platform.Linux; /// -/// X11-based screen capture (XGetImage on the root window) — the Linux counterpart to -/// Win32ScreenCapture. See LINUX_PORT.md § Capture pipeline / Phase 2. +/// Screen capture — the Linux counterpart to Win32ScreenCapture. See LINUX_PORT.md § Capture +/// pipeline / Phase 2 and § Wayland status / Phase 4. /// -/// This only works under an X11 session (a real Xorg session, or XWayland for apps that don't -/// need pixels from native-Wayland surfaces — capturing the root window through XWayland reliably -/// returns whatever XWayland itself is compositing, which in practice means Xorg-session content; -/// behavior when the *only* thing running is a pure-Wayland compositor with no X clients at all is -/// untested here). A portal-based (org.freedesktop.portal.Screenshot) implementation would be the -/// correct approach for native Wayland sessions (GNOME/KDE Wayland, now the default on most -/// mainstream distros including Debian/Fedora) but requires an interactive per-capture permission -/// dialog from the compositor — a real UX change from Windows' instant, silent capture — and portal -/// backend services aren't present in this development environment to implement against -/// interactively (see LINUX_PORT.md Phase 2 status). Treat this class as the X11-session path only; -/// a portal-based path is the documented, tracked gap for pure-Wayland sessions. +/// Dispatches on session type via $WAYLAND_DISPLAY (the same signal GTK/Qt/SDL use, and the same +/// check LinuxClipboard already makes for wl-copy vs xclip): +/// - X11 session (no $WAYLAND_DISPLAY): XGetImage on the root window, as before. +/// - Wayland session ($WAYLAND_DISPLAY set): routed to WaylandPortalScreenCapture +/// (org.freedesktop.portal.Screenshot) instead of trying XGetImage through XWayland first. Even +/// though XWayland is normally running under a native Wayland session (so XOpenDisplay would +/// still succeed), capturing the X11 root window through it does not reliably see native-Wayland +/// surface content — Wayland's security model deliberately keeps that off-limits outside a +/// brokered mechanism like the portal — so this checks the session type up front rather than +/// waiting for XGetImage to fail or (worse) silently return wrong pixels. /// public sealed class LinuxScreenCapture : IScreenCapture { + private static bool IsWaylandSession() => !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WAYLAND_DISPLAY")); + public CapturedImage CaptureFullScreen() { + if (IsWaylandSession()) + { + return WaylandPortalScreenCapture.CaptureFullScreen(); + } + var display = OpenDisplayOrThrow(); try { @@ -46,6 +52,13 @@ public CapturedImage CaptureMonitor(int monitorIndex) if (monitorIndex < 0 || monitorIndex >= monitors.Count) throw new ArgumentOutOfRangeException(nameof(monitorIndex)); + if (IsWaylandSession()) + { + // GetAllMonitorsWayland() only ever reports one entry (no portal-level per-output + // geometry — see its comment), so any valid index here means "the whole screenshot." + return WaylandPortalScreenCapture.CaptureFullScreen(); + } + var m = monitors[monitorIndex]; var display = OpenDisplayOrThrow(); try @@ -60,6 +73,11 @@ public CapturedImage CaptureMonitor(int monitorIndex) public IReadOnlyList GetAllMonitors() { + if (IsWaylandSession()) + { + return GetAllMonitorsWayland(); + } + // Shelling out to `xrandr --query` rather than P/Invoking libXrandr directly: the RandR // protocol's monitor-enumeration ABI (XRRGetMonitors et al.) has changed shape across // versions, whereas xrandr's plain-text --query output has been stable for over a decade @@ -107,6 +125,22 @@ private static List ParseXrandr(string xrandrOutput) return result; } + private static List GetAllMonitorsWayland() + { + // No portable, desktop-agnostic way to enumerate per-monitor geometry on Wayland short of + // a compositor-specific tool (kscreen-doctor on KDE, org.gnome.Mutter.DisplayConfig on + // GNOME, swaymsg on wlroots compositors, ...) whose output shape can't be verified without + // that specific desktop to test against, or the heavier ScreenCast portal's interactive + // source picker (a different, much larger feature — see LINUX_PORT.md Phase 4). Rather than + // guess at one tool's JSON and risk silently-wrong monitor bounds, this reports a single + // entry spanning whatever the Screenshot portal actually returns — CaptureMonitor(0) + // captures that whole thing, the same graceful-degradation shape as FallbackSingleMonitor() + // below when xrandr is unavailable under X11. Width/Height are left at 0 (unknown) since no + // MoneyShot.UI caller renders them — only Count and IsPrimary are used (monitor buttons/ + // hotkey list are built from those alone). + return new List { new(0, 0, 0, 0, true, "Wayland session (all displays)") }; + } + private static List FallbackSingleMonitor() { var display = OpenDisplayOrThrow(); diff --git a/MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj b/MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj index 7c3a39d..e38fd84 100644 --- a/MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj +++ b/MoneyShot.Platform.Linux/MoneyShot.Platform.Linux.csproj @@ -4,9 +4,10 @@ + sessions for everything; Wayland sessions for capture only as of Phase 4 — see + LinuxGlobalHotkeys/LinuxScreenCapture for the exact per-feature breakdown) is a supported + target, but there's no net10.0-linux TFM in .NET, so this is gated at runtime via + OperatingSystem.IsLinux() checks where it matters, not at the TFM level. --> net10.0 enable enable @@ -30,6 +31,10 @@ native library that's API-incompatible with managed SkiaSharp 4.151.2, confirmed by actually running a published build and hitting the resulting TypeInitializationException. --> + + diff --git a/MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs b/MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs new file mode 100644 index 0000000..1d19cc5 --- /dev/null +++ b/MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs @@ -0,0 +1,151 @@ +using MoneyShot.Abstractions; +using SkiaSharp; +using Tmds.DBus; + +namespace MoneyShot.Platform.Linux; + +[DBusInterface("org.freedesktop.portal.Screenshot")] +internal interface IScreenshotPortal : IDBusObject +{ + Task ScreenshotAsync(string parentWindow, IDictionary options); +} + +[DBusInterface("org.freedesktop.portal.Request")] +internal interface IPortalRequest : IDBusObject +{ + Task WatchResponseAsync(Action<(uint response, IDictionary results)> handler, Action? onError = null); +} + +/// +/// Screen capture via the XDG Desktop Portal (org.freedesktop.portal.Screenshot) — the native- +/// Wayland counterpart to LinuxScreenCapture's XGetImage path. See LINUX_PORT.md § Wayland status +/// / Phase 4. +/// +/// XGetImage against the X11 root window doesn't see native Wayland compositor content (that's the +/// whole point of Wayland's security model — clients can't read each other's or the desktop's +/// pixels without going through an arbitrating service), so under a Wayland session the only +/// correct mechanism is this portal, brokered by whichever backend the desktop provides +/// (xdg-desktop-portal-kde, -gnome, -wlr, ...). The portal call itself uses Tmds.DBus (a pure +/// managed D-Bus client — no libdbus dependency, so no extra packaging requirement) to talk to the +/// session bus; the actual backend service (xdg-desktop-portal + a desktop-specific implementation) +/// must be running, which it is by default on every mainstream KDE/GNOME desktop install but not +/// necessarily in a minimal/headless environment. +/// +/// `interactive: false` is passed so the backend takes an immediate full screenshot rather than +/// showing its own region/window picker UI — MoneyShot already has RegionSelector for cropping a +/// frozen full capture, so the portal's own picker would be redundant. Depending on the backend, +/// this may still show a brief consent/notification UI (KDE and GNOME's screenshot portals do not +/// require a persisted per-app grant the way camera/microphone portals do, but this wasn't +/// observable against a real compositor in this project's build environment — see LINUX_PORT.md). +/// +/// Only full-desktop capture is implemented. There is no portal-level "capture just monitor N" +/// equivalent to xrandr's per-output geometry outside of the heavier ScreenCast portal (which +/// requires the user to pick a source from a live picker UI and hands back a PipeWire stream, not a +/// single screenshot) — see LinuxScreenCapture.GetAllMonitorsWayland for how monitor selection +/// degrades gracefully under this path. +/// +internal static class WaylandPortalScreenCapture +{ + private const string PortalService = "org.freedesktop.portal.Desktop"; + private static readonly ObjectPath PortalObjectPath = new("/org/freedesktop/portal/desktop"); + private static readonly TimeSpan ResponseTimeout = TimeSpan.FromSeconds(60); + + public static CapturedImage CaptureFullScreen() + { + var pngPath = RequestScreenshotFileAsync().GetAwaiter().GetResult(); + try + { + return DecodePng(pngPath); + } + finally + { + // Best-effort: the portal typically serves this through the document portal (a path + // under /run/user//doc/...) which may be read-only or auto-cleaned by that + // service; failing to delete it here isn't a capture failure. + try { File.Delete(pngPath); } catch { } + } + } + + private static async Task RequestScreenshotFileAsync() + { + var connection = Connection.Session; + var portal = connection.CreateProxy(PortalService, PortalObjectPath); + + var tcs = new TaskCompletionSource<(uint response, IDictionary results)>( + TaskCreationOptions.RunContinuationsAsynchronously); + + var options = new Dictionary + { + ["handle_token"] = "moneyshot_" + Guid.NewGuid().ToString("N"), + ["interactive"] = false + }; + + // The portal spec's race-free pattern is to pre-compute the Request object path from our + // own unique bus name + handle_token and subscribe before calling Screenshot. Subscribing + // to the *returned* handle after the call, as done here, has a small documented race if the + // backend answers between the method return and the subscribe call — in practice this + // doesn't happen (answering takes at least one more D-Bus round trip / compositor tick), + // and every simple portal client example in the wild takes this same shortcut. Not verified + // against a real compositor in this project's build environment — see LINUX_PORT.md. + var handle = await portal.ScreenshotAsync(string.Empty, options).ConfigureAwait(false); + var request = connection.CreateProxy(PortalService, handle); + + using var watcher = await request.WatchResponseAsync(result => tcs.TrySetResult(result)).ConfigureAwait(false); + + var winner = await Task.WhenAny(tcs.Task, Task.Delay(ResponseTimeout)).ConfigureAwait(false); + if (winner != tcs.Task) + { + throw new InvalidOperationException( + "Timed out waiting for the screenshot portal to respond. This usually means no " + + "portal backend is running (xdg-desktop-portal + a desktop-specific implementation " + + "like xdg-desktop-portal-kde/-gnome — present by default on mainstream desktops, " + + "but not in minimal/headless environments), or a consent dialog is waiting " + + "off-screen for a response. See LINUX_PORT.md Phase 4."); + } + + var (response, results) = tcs.Task.Result; + if (response != 0) + { + throw new InvalidOperationException(response == 1 + ? "Screenshot request was cancelled." + : $"Screenshot portal request failed (response code {response})."); + } + + if (!results.TryGetValue("uri", out var uriObj) || uriObj is not string uriString) + { + throw new InvalidOperationException("Screenshot portal response did not include a 'uri' result."); + } + + return new Uri(uriString).LocalPath; + } + + private static CapturedImage DecodePng(string path) + { + using var decoded = SKBitmap.Decode(path) + ?? throw new InvalidOperationException($"Failed to decode portal screenshot PNG at '{path}'."); + + var bgra = decoded; + SKBitmap? converted = null; + try + { + if (decoded.ColorType != SKColorType.Bgra8888) + { + converted = decoded.Copy(SKColorType.Bgra8888) + ?? throw new InvalidOperationException("Failed to convert portal screenshot to BGRA8888."); + bgra = converted; + } + + var pixels = bgra.Bytes; + // Force alpha opaque — matches LinuxScreenCapture's X11 path (see its CaptureRegion + // comment); a desktop screenshot should already be fully opaque, this just guards the + // same edge case defensively. + for (var i = 3; i < pixels.Length; i += 4) pixels[i] = 0xFF; + + return new CapturedImage(bgra.Width, bgra.Height, bgra.RowBytes, pixels); + } + finally + { + converted?.Dispose(); + } + } +} diff --git a/Packaging/linux/build-deb.sh b/Packaging/linux/build-deb.sh index 6cd54ad..ea564f7 100644 --- a/Packaging/linux/build-deb.sh +++ b/Packaging/linux/build-deb.sh @@ -51,7 +51,7 @@ Priority: optional Architecture: amd64 Installed-Size: ${INSTALLED_SIZE_KB} Depends: libice6, libsm6, libx11-6, libxrandr2, libfontconfig1, libssl3 -Recommends: xclip | wl-clipboard, x11-xserver-utils +Recommends: xclip | wl-clipboard, x11-xserver-utils, xdg-desktop-portal Maintainer: Daolyap & iSaluki Homepage: https://github.com/Daolyap/Money-Shot Description: Capture, annotate, and share screenshots @@ -59,10 +59,11 @@ Description: Capture, annotate, and share screenshots screen/monitor capture, a full annotation toolset (shapes, arrows, text, numbering, pixelate), history, and global hotkeys. . - This build's Linux platform layer (X11 capture and hotkeys, StatusNotifierItem - tray icon, XDG autostart, clipboard) targets X11 sessions — see the project's - LINUX_PORT.md for current Wayland-specific caveats (global hotkeys, in - particular, have no direct Wayland equivalent). + On X11 sessions, capture and global hotkeys use X11 directly. On Wayland + sessions, capture goes through the XDG Desktop Portal (xdg-desktop-portal, + pulled in via Recommends — present by default on mainstream KDE/GNOME + desktops); global hotkeys have no Wayland equivalent yet — see the project's + LINUX_PORT.md for details. EOF # update-desktop-database/gtk-update-icon-cache are best-effort: absent on some minimal systems diff --git a/Packaging/linux/rpm/moneyshot.spec b/Packaging/linux/rpm/moneyshot.spec index 852162f..4a7cf08 100644 --- a/Packaging/linux/rpm/moneyshot.spec +++ b/Packaging/linux/rpm/moneyshot.spec @@ -6,7 +6,7 @@ License: Proprietary URL: https://github.com/Daolyap/Money-Shot BuildArch: x86_64 Requires: libICE, libSM, libX11, libXrandr, fontconfig, openssl-libs -Recommends: xclip +Recommends: xclip, xdg-desktop-portal AutoReqProv: no %description @@ -14,10 +14,11 @@ Money Shot is a screenshot capture and annotation tool with region/full-screen/ monitor capture, a full annotation toolset (shapes, arrows, text, numbering, pixelate), history, and global hotkeys. -This build's Linux platform layer (X11 capture and hotkeys, StatusNotifierItem -tray icon, XDG autostart, clipboard) targets X11 sessions — see the project's -LINUX_PORT.md for current Wayland-specific caveats (global hotkeys, in -particular, have no direct Wayland equivalent). +On X11 sessions, capture and global hotkeys use X11 directly. On Wayland +sessions, capture goes through the XDG Desktop Portal (xdg-desktop-portal, +pulled in via Recommends — present by default on Fedora Workstation/KDE +spins); global hotkeys have no Wayland equivalent yet — see the project's +LINUX_PORT.md for details. %install rm -rf %{buildroot} From abeba57402bebe8e07337b77305d8eddbf24c543 Mon Sep 17 00:00:00 2001 From: Logan H Date: Fri, 11 Sep 2026 12:44:28 +0100 Subject: [PATCH 5/6] fix: Wayland portal capture crashed on every attempt (inaccessible interface) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tmds.DBus.Connection.CreateProxy builds the proxy via Reflection.Emit in a separate dynamic assembly (Tmds.DBus.Emit), which cannot implement an internal interface from this assembly — every capture attempt threw TypeLoadException ("attempting to implement an inaccessible interface") on the first try and "Duplicate type name within an assembly" on retries (the dynamic module already had the type name reserved from the failed attempt). Confirmed via a real crash log from a Fedora KDE run. IScreenshotPortal and IPortalRequest are now public, matching every Tmds.DBus proxy-interface example in their own docs (which I should have followed instead of defaulting to internal for encapsulation). Co-Authored-By: Claude Sonnet 5 --- .../WaylandPortalScreenCapture.cs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs b/MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs index 1d19cc5..7a33fdb 100644 --- a/MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs +++ b/MoneyShot.Platform.Linux/WaylandPortalScreenCapture.cs @@ -4,14 +4,21 @@ namespace MoneyShot.Platform.Linux; +// Tmds.DBus builds the proxy for these at runtime via Reflection.Emit (Connection.CreateProxy), +// in a *different* dynamic assembly ("Tmds.DBus.Emit") — an internal interface is inaccessible to +// that assembly and CreateTypeInfoImpl() throws TypeLoadException ("attempting to implement an +// inaccessible interface"). Confirmed by actually hitting this on a real Fedora KDE run: both +// interfaces must be public, no way around it short of InternalsVisibleTo (which still wouldn't +// help — Tmds.DBus's emit assembly name/key isn't something this project controls to add a +// matching InternalsVisibleTo for). [DBusInterface("org.freedesktop.portal.Screenshot")] -internal interface IScreenshotPortal : IDBusObject +public interface IScreenshotPortal : IDBusObject { Task ScreenshotAsync(string parentWindow, IDictionary options); } [DBusInterface("org.freedesktop.portal.Request")] -internal interface IPortalRequest : IDBusObject +public interface IPortalRequest : IDBusObject { Task WatchResponseAsync(Action<(uint response, IDictionary results)> handler, Action? onError = null); } From 876a18a8673a2f347de3651da21471fbe0bbf904 Mon Sep 17 00:00:00 2001 From: Logan H Date: Fri, 11 Sep 2026 12:45:31 +0100 Subject: [PATCH 6/6] docs: record the Wayland portal capture crash + fix in LINUX_PORT.md Co-Authored-By: Claude Sonnet 5 --- LINUX_PORT.md | 62 ++++++++++++++++++++++++++++++--------------------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/LINUX_PORT.md b/LINUX_PORT.md index 57d3b80..ddbab0e 100644 --- a/LINUX_PORT.md +++ b/LINUX_PORT.md @@ -18,23 +18,28 @@ > session (`$WAYLAND_DISPLAY`) and routes to `WaylandPortalScreenCapture` > (`org.freedesktop.portal.Screenshot` via `Tmds.DBus`) instead of X11 `XGetImage`, which does not > see native Wayland content. This closes the exact failure a real user hit on Fedora KDE (Plasma -> Wayland, Fedora's and current Debian's default session type) — see § Wayland status. **This code -> compiles clean and its D-Bus proxy/signal shapes were verified against Tmds.DBus's own documented -> API and a real working example (its NetworkManager how-to), but it was not live-tested against a -> real portal backend this round** — Docker Desktop hit an unrelated startup bug -> (`sailor-ingest.sock` stale-rename failure) on this machine that a normal restart/WSL-shutdown -> couldn't clear, blocking the headless-compositor test container that would have exercised it -> end-to-end. Global hotkeys remain X11-only — `org.freedesktop.portal.GlobalShortcuts` (a larger, +> Wayland, Fedora's and current Debian's default session type) — see § Wayland status. The first +> build of this (2026-09-10) crashed on **every** capture attempt — confirmed by the same user's +> real crash log from a Fedora KDE run: `Tmds.DBus.Connection.CreateProxy` builds its proxy via +> `Reflection.Emit` in a separate dynamic assembly, which cannot implement an `internal` interface, +> so `IScreenshotPortal`/`IPortalRequest` (declared `internal` in the first pass) threw +> `TypeLoadException` on every attempt. Fixed 2026-09-11 by making both `public` — this was **found +> from a real log, not caught locally**, because Docker Desktop hit an unrelated startup bug on the +> dev machine (`sailor-ingest.sock` stale-rename failure, survived a restart/WSL-shutdown) that +> blocked the headless-compositor container test that would have caught it before shipping. The fix +> is a direct match for the exact reported stack trace and rebuilds/tests clean, but **has not yet +> been confirmed successful on a real machine** — the user's next real-world attempt is the actual +> verification. Global hotkeys remain X11-only — `org.freedesktop.portal.GlobalShortcuts` (a larger, > separately-scoped feature) was not attempted. See § Phase 4 status for the exact verified/ > not-verified breakdown. > > **Remaining real gaps**: Wayland global hotkeys (portal `GlobalShortcuts`, not attempted — tray -> menu/in-app buttons remain the working alternative), the new Wayland capture path's live behavior -> against a real compositor (see above), per-monitor capture under Wayland (portal has no per-output -> selector outside the heavier ScreenCast API — see § 2), the tray icon has not been confirmed -> against a real desktop's StatusNotifierWatcher (only confirmed to not crash without one), and -> `EditorWindow`'s deeper tool interactions (resize, crop, zoom/pan, pixelate) were verified on -> Windows but not separately re-verified on Linux. See § Migration phases for the full +> menu/in-app buttons remain the working alternative), confirming the Wayland capture fix actually +> works end-to-end on a real machine (see above), per-monitor capture under Wayland (portal has no +> per-output selector outside the heavier ScreenCast API — see § 2), the tray icon has not been +> confirmed against a real desktop's StatusNotifierWatcher (only confirmed to not crash without +> one), and `EditorWindow`'s deeper tool interactions (resize, crop, zoom/pan, pixelate) were +> verified on Windows but not separately re-verified on Linux. See § Migration phases for the full > verified-vs-not breakdown per phase. ## TL;DR @@ -114,19 +119,24 @@ waits for the async `Request.Response` signal, and decodes the returned PNG (via `Task WatchResponseAsync(Action<(uint, IDictionary)>, ...)`, `IDictionary` for `a{sv}`) were checked against Tmds.DBus's own published modelling docs and a real, complete working example (its NetworkManager `WatchStateChangedAsync` how-to) — -not guessed from memory. **Not verified**: an actual round trip against a running portal backend -(`xdg-desktop-portal` + `xdg-desktop-portal-kde`/`-gnome`/`-wlr`). This session's plan was to -exercise it against a headless `sway` (wlroots) compositor + `xdg-desktop-portal-wlr` in a Docker -container — the same kind of standalone-harness verification that caught the X11 capture path's -real bugs — but Docker Desktop hit an unrelated startup bug on this machine (`sailor-ingest.sock` -failed its internal stale-rename with "The file cannot be accessed by the system"; a full engine -restart, deleting the stale socket via PowerShell/cmd/bash, and `wsl --shutdown` all failed to clear -it) that blocked starting any container this session. **Treat the Wayland capture path as -implemented-but-unverified until it's exercised against a real compositor** — the most likely risk -areas if something's wrong: the D-Bus proxy method-name-to-signal-name mapping convention, the -`handle_token`/response-race assumption (see the code's own comment on this), or a portal backend -returning the `uri` result in a shape (e.g. always via the document portal, always requiring a -`file://` URI with the caller's own read access) other than what's coded for. +not guessed from memory. **Round-tripped through one real bug already**: the first build (2026-09- +10) crashed on every capture attempt with `TypeLoadException: ... attempting to implement an +inaccessible interface` (`IScreenshotPortal`/`IPortalRequest` were declared `internal`, and +`Tmds.DBus.Connection.CreateProxy` builds its proxy via `Reflection.Emit` in a separate dynamic +assembly that can't implement an internal interface) — caught from a real crash log off a Fedora +KDE run (not caught locally, since Docker Desktop hit an unrelated startup bug on the dev machine — +`sailor-ingest.sock` failed its internal stale-rename with "The file cannot be accessed by the +system"; a full engine restart, deleting the stale socket via PowerShell/cmd/bash, and +`wsl --shutdown` all failed to clear it — blocking the headless-`sway`-compositor container test +that would have caught this before shipping). Fixed 2026-09-11 by making both interfaces `public`, +matching every proxy-interface example in Tmds.DBus's own docs. **Still not verified**: a +successful end-to-end capture on a real machine — the fix directly matches the reported stack +trace and the solution rebuilds/tests clean, but no one has yet seen this actually produce a +screenshot. **Treat the Wayland capture path as implemented-and-crash-fixed-but-not-yet-confirmed- +working** — remaining risk areas if it still doesn't produce a screenshot: the `handle_token`/ +response-race assumption (see the code's own comment on this), or a portal backend returning the +`uri` result in a shape (e.g. always via the document portal, always requiring a `file://` URI with +the caller's own read access) other than what's coded for. Only full-desktop capture is portal-based; there is no portal equivalent to xrandr's per-monitor geometry outside the much heavier ScreenCast API (which requires an interactive source-picker UI