Interactive 2D wave optics simulator. Turn any image into a refractive scene, add sources, watch waves refract, diffract and interfere. Probes, intensity maps, video export.
C#
WaveDude.WPF: docking shell, model, file association, keyboard-first preview
Alexander Graef713c675fd19c
diff --git a/.editorconfig b/.editorconfigindex 69de051..9b75dd4 100644--- a/.editorconfig+++ b/.editorconfig@@ -10,6 +10,18 @@ trim_trailing_whitespace = trueindent_style = tabindent_size = 4+# No this. qualification; expression bodies for trivial accessors+dotnet_style_qualification_for_field = false:warning+dotnet_style_qualification_for_property = false:warning+dotnet_style_qualification_for_method = false:warning+dotnet_style_qualification_for_event = false:warning+csharp_style_expression_bodied_properties = true:suggestion+csharp_style_expression_bodied_accessors = true:suggestion+csharp_style_expression_bodied_indexers = true:suggestion+csharp_style_expression_bodied_methods = when_on_single_line:suggestion+csharp_prefer_braces = true:suggestion+csharp_new_line_before_open_brace = all+[*.{csproj,sln,resx,config,settings,manifest}]indent_style = spaceindent_size = 2diff --git a/.gitignore b/.gitignoreindex 384ba80..e0ea4a6 100644--- a/.gitignore+++ b/.gitignore@@ -10,3 +10,6 @@ TestResults/# local scratch_tools/smoke.png_tools/*.txt++# Claude Code local permissions+.claude/settings.local.jsondiff --git a/CLAUDE.md b/CLAUDE.mdindex b297ddd..56ca506 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1,69 +1,191 @@# Wave Dude 2D — project notes for Claude-Analysis snapshot: 2026-10-06. Update this file when the facts below change.+Last updated 2026-10-07. Update this file when the facts below change.## What this is**Wave Dude 2D v0.29** — a 2D wave-equation simulator (field + accumulated intensity views,refractive-index scenes from images, point/composite sources, probes with live graphs, video export).Educational tool by Huygens Optics (`[email protected]`, patreon `huygens_optics`).+Licence: **GPL-3.0-or-later, Copyright (C) 2026 JJM Vleggaar (Huygens Optics)** per the headers in the+author's VB source; the C# files do not carry the header yet (see `_tools/VB_SOURCE_AUDIT.md`).-- WinForms, **.NET Framework 4.6.1**, legacy (non-SDK) `.csproj`, root namespace `_2D_wave_sim_V01`,- assembly `Wave_Dude_2D`. Single project in `Wave_Dude_2D.sln`.-- **The C# in this repo started life as ILSpy-decompiled output of a VB.NET build.** As of- 2026-10-07 it has been cleaned up to read like hand-written C#: closure artifacts, VB `WithEvents`- wrappers, `// Token` comments, `checked {}` blocks, `bool flag = …` temps, VB runtime helper- calls and placeholder locals (`num2`, `text3`, …) are gone from all hand-maintained files.- What still betrays the origin: the `My/` namespace + `WindowsFormsApplicationBase` startup, the- `*.Designer.cs` files (left verbatim apart from the field/event-wiring block), `ref` parameters- that are really `out`, and `this.` on every member access.-- Git: repo was just initialised; **nothing is committed yet** and there is **no `.gitignore`**- (`.vs/` is untracked junk that must not be committed).-- No tests. No CI. No README besides this file.+`2D_wave_sim_V01/` is the **author's original VB.NET source**, supplied after the C# port was made. It+is newer than the binary that was decompiled (GPL headers and a GPL Help disclaimer were added after+that build). Treat it as the authority for intent, comments and constant names; `_tools/VB_SOURCE_AUDIT.md`+(2026-10-08) lists everything the decompile lost, file by file, with the C# line each item belongs at.++`Wave_Dude_2D.sln` holds three projects:++| project | what | state |+|---|---|---|+| `Wave_Dude_2D/` | the original WinForms app, **.NET Framework 4.6.1**, legacy csproj, namespace `_2D_wave_sim_V01` | all the real code; builds and runs; **reference implementation, not the future** |+| `WaveDude/` | SDK class library, `net10.0`, nullable + implicit usings | empty; intended home for the UI-independent engine/model code |+| `WaveDude.WPF/` | SDK WPF app, `net10.0-windows`, references `WaveDude` | **the replacement UI**; layout shell only, builds clean (0 warnings) |++WPF shell as it stands:+- `MainWindow` = menu + `AvalonDock.DockingManager` (Project tree pane left, Preview document+ centre, Properties pane right) + status bar. Panes drag/dock/float/auto-hide; nothing is wired to+ data yet. `App.OnStartup` applies the theme before creating the window.+- Docking: `Dirkster.AvalonDock` 4.74.1 + `Dirkster.AvalonDock.Themes.VS2013` (MIT).+- Theming: WPF built-in Fluent theme via `Application.ThemeMode` (experimental API; `WPF0001`+ suppressed in the csproj). `Theming/ThemeController` switches System/Light/Dark, sets the matching+ `Vs2013Dark/LightTheme` on the docking manager (it does not follow Fluent on its own) and darkens+ the native title bar via DWM because WPF only does that on Windows 11. View > Theme drives it; the+ choice is not persisted yet. **Every window that hosts a `DockingManager` must subscribe to+ `ThemeController.Changed`** and re-read `CreateDockTheme()`.+- Preview document: `Panes/PreviewPane` (dummy, 2026-10-08). Two placeholder pictures (field,+ intensity) side by side or stacked (`Orientation`), each centred in its cell, with a `GridSplitter`+ between them (one 3×3 grid; the unused dimension is spanned, so each orientation keeps its own+ ratio; Enter or double-click resets to half). Transport bar with `MediaCommands.Play/Pause`+ (Space toggles), a scrub `Slider` over `Position` 0..`LastFrame`, `FrameCount` bound to+ `Simulation.Steps`/`VisualizeEvery` via `FrameCountConverter`, and an editable speed combo+ (`SpeedPresets` 0.25…4, any value typed; `DoubleTextConverter` ignores text that does not parse+ yet, otherwise every keystroke logs a binding error to the status bar). Numbers follow the Windows+ locale everywhere: `App.OnStartup` overrides `FrameworkElement.Language` with the current culture+ (WPF defaults to en-US), so the preset list and the typed text both say `0,25` on a de-DE machine. Playback is a+ `DispatcherTimer` moving `Position` at `BaseFrameRate` × `Speed`; nothing renders yet. The render+ pipeline will set `FieldImage` / `IntensityImage`. `Editors.xaml` gained the editable-combo text+ box, a `Slider` style and keyboard-focus visuals for combo and slider.+- **Keyboard first.** Every control must be reachable and operable with Tab and the arrow keys and+ show its keyboard focus (accent border); the user tests without the mouse. The preview pane is+ the model: explicit `TabIndex` order, the radio group is one tab stop (`IsTabStop` bound to+ `IsChecked`, arrows handled in code because WPF's directional navigation skips non-tab-stops),+ Play/Pause hand focus to each other when they get disabled, `AutomationProperties.AutomationId`+ on everything a harness needs. Toolbar buttons in `ProjectTree`/`MessagesPane` are still+ `Focusable=False` (reachable only through menus/shortcuts), not yet brought in line.+- File type: `FileAssociation.Register` (called from `App.OnStartup`) registers `.wdproj` → ProgId+ `WaveDude.Project` → `"exe" "%1"` under HKCR when elevated, else HKCU\Software\Classes (same order+ as DTCODataSimulator), idempotently; a double-click arrives as `e.Args[0]` and goes to+ `MainWindow.OpenFile`. That a per-user entry overrides a machine-wide one is intended: a per-user+ install, or a plain copy with no installer, must win over a global installation for that user.+ `assoc`/`ftype` in cmd do not see HKCU registrations; test with a real launch.++History: the C# in `Wave_Dude_2D/` started as ILSpy-decompiled output of a VB.NET binary. It has+since been made to compile, cleaned to idiomatic C#, documented, and partly refactored (details+below). Baseline commit `1266f10` is the first compiling, cleaned, documented state; everything+after it (AVI fix, style pass, engine refactor, WPF shell) is uncommitted at the time of writing.++Repo root also holds runtime data that is tracked on purpose: `ColorSchemeList/` (the shipped colour+schemes, `*.json`) and `Project/` (a sample project root). `.vs/`, `bin/`, `obj/` are ignored.++No automated tests in the solution; two standalone harnesses exist under `_tools/` (see Verification).## Build-- Toolchain found on this machine: Visual Studio 18 (2026) Community. `dotnet` 10 SDK is installed but- the legacy csproj needs full MSBuild:+- Visual Studio 18 (2026) Community and the .NET 10 SDK are installed.+- Whole solution (the legacy csproj needs full MSBuild):```- "C:\Program Files\Microsoft Visual Studio\18\Community\MSBuild\Current\Bin\MSBuild.exe" Wave_Dude_2D.sln -p:Configuration=Debug -v:minimal -nologo -m+ "C:\Program Files\Microsoft Visual Studio\18\Community\MSBuild\Current\Bin\MSBuild.exe" Wave_Dude_2D.sln -restore -p:Configuration=Debug -v:minimal -nologo -m```-- **Current state (2026-10-07): compiles and runs.** 0 errors, 6 cosmetic warnings- (`components` never assigned in the Designer files, unused `_hasRun`, one sign-extension in- `MfVideoWriter`). Smoke test = launch exe, main window appears with title- `2D wave simulation - (new project) *`.-- Standalone compile check that does not touch `bin/obj` (safe to run in parallel with other work):- `_tools/CLEANUP_GUIDE.md` has the full `csc.exe` command line.-- `_tools/` holds the one-off Python scripts used for the decompiler clean-up (`replace_method.py`,- `fix_semantic.py`, `split_form1.py`, …) plus the guide. They are history, not build inputs.+- WPF + library only: `dotnet build WaveDude.WPF/WaveDude.WPF.csproj`.+- Expected result: 0 errors; 6 warnings in `Wave_Dude_2D` that are known and harmless+ (`components` never assigned in the four generated Designer files, unused `Form1._hasRun`, one+ sign-extension in `MfVideoWriter`). `DocumentationFile` is on, so malformed `///` XML or a wrong+ `<param>` name is a build warning — keep it at zero.+- Smoke test: launch `Wave_Dude_2D/bin/Debug/Wave_Dude_2D.exe`; the main window must appear with+ title `2D wave simulation - (new project) *`.+- Standalone compile check that does not touch `bin/obj` (safe while other work is in flight):+ ```+ cd Wave_Dude_2D && "C:\Program Files\Microsoft Visual Studio\18\Community\MSBuild\Current\Bin\Roslyn\csc.exe" -nologo -target:winexe -out:%TEMP%\check.exe -langversion:7.3 -r:System.dll -r:System.Core.dll -r:System.Drawing.dll -r:System.Windows.Forms.dll -r:Microsoft.VisualBasic.dll -r:System.Web.Extensions.dll -nowarn:0168,0649,0414,0675 *.cs My/*.cs My/Resources/*.cs Properties/*.cs+ ```++## Verification harnesses (`_tools/`)++Run these after touching the code they cover; both are console programs compiled with `csc` against+the project sources (same reference list as above, `-target:exe`, `-nowarn:...,1591`).++- `_tools/engine_check/Program.cs` — add `-main:EngineCheck.Program` and all `Wave_Dude_2D` sources.+ Runs `WaveSimulator` and `GpuWaveSimulator` over one scene (image source, continuous / Gaussian-pulsed /+ detaching smoothed-square object sources, an out-of-canvas source that must be dropped, point and+ integrated-line probes with a start step), with both stencils, and requires field, intensity, probe+ samples and line profiles to agree within 1e-3 relative (actual: ~1e-7). Also exercises probe+ re-install, `SetProbes(null)` and double dispose. Prints `skip GPU: …` when no OpenCL device works.+- `_tools/avi_check/Program.cs` — compile with `AviMjpegWriter.cs` only. Writes a 3-frame MJPEG AVI and+ walks the RIFF tree (44 structural checks: header offsets, strh dwQuality = -1, movi size, idx1 offsets, EOF).++- `_tools/ui_check/PreviewCheck.ps1` drives the WPF preview pane end to end (25 checks: play/pause,+ speed incl. locale spelling, scrubber keys, split radios, splitter, tab order, focus hand-off,+ foreground untouched).+ Run `powershell -ExecutionPolicy Bypass -File _tools/ui_check/PreviewCheck.ps1` (`-Trace` adds+ foreground/focus per line); exit code = failures. **How UI harnesses must work here**: the user may+ be using the machine, so no mouse, no `SendKeys`, no `SetForegroundWindow`. Post `WM_KEYDOWN`/+ `WM_CHAR` to the app's HWND (WPF processes them while inactive) and read state back through+ `System.Windows.Automation` properties. Do **not** call UIA *patterns* (`Invoke`, `SetValue`,+ `Select`, `SetFocus`): on this app each one focuses its target and activates the window.+ `PrintWindow(…, PW_RENDERFULLCONTENT)` captures the inactive window. The older scripts in the+ folder (`MessagesCheck`, `ProjectTreeCheck`, `StatusBar*Check`) predate this rule and still use+ patterns/mouse; rewrite them the same way when they are next needed.-## Architecture map+Other files in `_tools/` are one-off scripts from the clean-up (`replace_method.py`, `fix_semantic.py`,+`split_form1.py`, `modernize.py`) and the agent guides (`CLEANUP_GUIDE.md`, `DOC_GUIDE.md`). They are+history, not build inputs. `field_usage.py <Class> …` is still useful: it lists every private+field/const of a class with the methods that use it, flagging single-method ones.++## Architecture (Wave_Dude_2D)```-My/MyApplication.Main -> MyProject.Forms.Form1 (VB "My" application framework; replace with Program.Main)-Form1 (14,473 lines) -> SimulationRunner (own Thread; events ProgressChanged/EngineReady/ProbesUpdated/PreviewReady/Finished)- |- WaveEngineFactory -> IWaveEngine- | |- WaveSimulator CPU, Parallel.For- | '- GpuWaveSimulator OpenCL via OpenClApi (P/Invoke OpenCL.dll), kernels as strings+My/MyApplication.Main -> MyProject.Forms.Form1 (VB "My" application framework; to be replaced by Program.Main)+Form1 (partial, 8 files) -> SimulationRunner (own Thread; events ProgressChanged/EngineReady/ProbesUpdated/PreviewReady/Finished,+ all raised on the worker thread; Form1.PostToUi marshals via BeginInvoke)+ |- WaveEngineFactory -> IWaveEngine (Width/Height/Stride, FieldData, IntensityData, AdvanceOneStep,+ | | PrepareFrame, SetProbes/SampleProbes/TakeProbeSamples/ReadProbeProfiles)+ | |- WaveSimulator CPU, Parallel.For over row bands; IDisposable is a no-op+ | '- GpuWaveSimulator OpenCL via OpenClApi (P/Invoke OpenCL.dll); kernels are C# string literals|- FrameRenderer + ColorLut/ColorScheme float field -> ARGB pixels|- IFrameSink -> MfVideoWriter (Media Foundation SinkWriter P/Invoke, .mp4)- | AviMjpegWriter (.avi fallback)- '- Probe* (Sampler/Collector/Series/Trace/GraphPainter/Overlay)-Persistence: ProjectStore / ProjectConfig / Project (JSON via System.Web.Extensions JavaScriptSerializer)+ | AviFrameSink/AviMjpegWriter (.avi fallback)+ '- Probe* (Sampler/Collector/Series/Trace/Update sampled on the worker; GraphPainter/Overlay paint on the UI thread)+Persistence: ProjectStore / ProjectConfig / Project (JSON via System.Web.Extensions JavaScriptSerializer, snake_case keys)AppSettings -> %AppData%\2D_wave_sim_V01\settings.json- ColorSchemeStore -> *.json colour schemes in a user-chosen folder+ ColorSchemeStore -> *.json colour schemes in a user-chosen folder (ColorSchemeList/ ships the defaults;+ FindDefaultFolder walks up from the exe looking for a *.sln, so a dev build edits the repo copy)Project folder layout: <root>/<project>/configuration.json (+ legacy Configuration.txt), assets/, output_frames/, output_video/-Model classes (plain POCOs, safe to reuse as-is): SceneSettings, SimulationSettings, SourceSettings(+SourceElement, enums), ProbeSettings(+enums), ColorScheme+Model classes (plain POCOs): SceneSettings, SimulationSettings, SourceSettings(+SourceElement, enums), ProbeSettings(+enums), ColorScheme```-UI -> engine marshalling is `Form1.PostToUi(Action)` = `BeginInvoke` guarded by `IsHandleCreated`.-Everything engine-side (`WaveSimulator`, `GpuWaveSimulator`, `OpenClApi`, `Mf*`, `IMF*Native`, `Probe*`,-`FrameRenderer`) is UI-independent and should be left alone during UI work beyond compile fixes.+### Engines (refactored 2026-10-07, verified by `engine_check`)++- `IWaveEngine` does **not** extend `IDisposable`; implementations decide, and `SimulationRunner`+ disposes via `(engine as IDisposable)?.Dispose()`. Both engines have no thread affinity and no+ internal synchronisation: exactly one thread may drive an engine at a time (today the runner's+ worker; the UI thread only reads `FieldData`/`IntensityData` while the run is paused). That is the+ contract to keep when the driving loop becomes `Task`-based.+- Numerics shared through `WaveSimulator`'s `internal static` helpers: `ComputeSubSteps`,+ `LowestSourceLevel`, `IntensityRetention`, `MaxOf`, `NominalDecayLevel`. Units: dx = dt = 1, c in+ cells/step, `c2 = 1/n²`, frequencies in radians/step (`level/255 × 0.5 × scale`), `Time` in steps.+ Scheme: leapfrog, 9-point Laplacian (0.066/0.184/−1) or 4th-order 5-point-per-axis with sub-stepping,+ soft source blending (`u = 0.9u + 0.1v`), two-stage EMA intensity. The docs in both files spell it out.+- `GpuWaveSimulator` keeps device handles in two `Resources` groups (`_scene`: program + kernels ++ buffers for the run; `_probes`: everything `SetProbes` creates, released and rebuilt on every call).+ Kernel arguments are bound at build time; only time (arg 4/11) and the per-sub-step track flag+ (`wave_step` arg 8) change per launch. The object-source kernel has 17 arguments — the table in+ `BuildObjectSourceKernels` is indexed by argument number; an off-by-one there shows up as+ `CL_INVALID_ARG_SIZE`, which the harness catches.+- `WaveSimulator` swaps its two field arrays every sub-step, so `FieldData` must be re-read per frame;+ `GpuWaveSimulator.FieldData` is a stable host array refreshed only by `PrepareFrame`.++### Moving engine code into `WaveDude/` (net10.0, no `-windows`)-## The UI as it stands (the thing to make viable)+Files with no Windows dependency, movable as-is: `WaveSimulator`, `GpuWaveSimulator`, `OpenClApi`,+`GpuDeviceInfo`, `IWaveEngine`, `WaveEngineFactory`, `ProbeSampler`, `ProbeCollector`, `ProbeSeries`,+`ProbeTrace`, `ProbeUpdate`, the `Probe*`/`Source*` enums, `SourceElement`, `SourceSettings`,+`SceneSettings`, `SimulationSettings`, `ProbeSettings`, `MfVideoWriter` + `IMF*Native` (COM, Windows at+runtime but compiles anywhere), `AviMjpegWriter`.+Files that use `System.Drawing` (`Bitmap`/`Graphics`) and need either `net10.0-windows` or an+abstraction first: `SceneData` (`FromImage`), `FrameRenderer` (`ToRgbBytes`/`ToBitmap`),+`SimulationRunner`/`SimulationJob`/`SimulationResult` (carry `Bitmap`s), `ProbeGraphPainter`,+`ProbeOverlay`, `AviFrameSink`, `ColorLut`, `ColorScheme`. Decision pending: target the library at+`net10.0-windows` (simplest; WPF can use `System.Drawing.Common`) or split pixel buffers from GDI++(cleaner for a `WriteableBitmap` preview).+Also pending for the move: `JavaScriptSerializer` → `System.Text.Json` keeping the snake_case keys so+existing `configuration.json`/`settings.json` files load; namespace `_2D_wave_sim_V01` → `WaveDude`+(the AppData folder name must stay, or be migrated).-`Form1` is still a god-class, but it is now a **partial class split along its feature seams**-(~6,500 lines of logic in total, ~347 methods, 161 event handlers, 78 `MessageBox.Show` calls):+## The WinForms UI (reference implementation)++`Form1` is a partial class split along feature seams (~6,500 lines of logic, ~347 methods, 161 event+handlers, 78 `MessageBox.Show` calls):| file | owns ||---|---|@@ -76,85 +198,83 @@ Everything engine-side (`WaveSimulator`, `GpuWaveSimulator`, `OpenClApi`, `Mf*`,| `Form1.Probes.cs` | probes tab (2 hard-wired probes via `ProbeControlSet[]`) || `Form1.Sources.cs` | sources tab |-Controls are plain private fields declared at the bottom of `Form1.Designer.cs`; event handlers are-attached in `InitializeComponent` under the comment `// event wiring (was VB WithEvents/Handles)`.-The VS designer has **not** been verified to open these forms — the Designer files are decompiled-output with `global::` prefixes; expect to regenerate them when the layout is rebuilt (roadmap 5).--`Form1.Designer.cs` (3,564 lines): **318 controls** — 91 Labels / 59 Buttons / 39 NumericUpDowns /-28 CheckBoxes / 15 TextBoxes / 13 GroupBoxes / 13 ComboBoxes / 11 Panels / 10 RadioButtons / 6 ListViews /-2 PictureBoxes; one `TabControl` (`tabMainFunctions`, owner-drawn, tabs gated via `Enabled` until a-project is open) with six pages: **Settings, Sources, Probes, Preview, Manage output, Colors**.-Persistent bottom strip: `grpSimulationControlButtons` (Start / Pause-Resume), `grpShareImage`,-`grpNavigateTabs` (jump buttons), `btnSaveConfiguration`; `MenuStrip1` (File: New / Open / Choose project-root / Set c-value / Save / Exit; Info: Help / About); `StatusStrip1`.--Why it is not viable today:--- **Fixed 1781x989 client size, 297 absolute `Location`s, zero `Dock`/`Anchor`, no `MinimumSize`,- no `TableLayoutPanel`/`FlowLayoutPanel`.** Does not fit a 1080p screen with taskbar; nothing reflows.-- `AutoScaleMode.Font` at 6x13 with **Microsoft Sans Serif** in 7 sizes (9.75–20.25 pt); 2 stray Segoe UI.- No `app.manifest`, no DPI awareness -> blurry/clipped on >100 % scaling.-- Ad-hoc colours (`Azure`, `Gainsboro`, `SystemColors.Menu`), hand-made owner-drawn tabs.-- Secondary UI: `AboutForm` (version string stale: code says 0.27, designer 0.29), `HelpForm` (long- help text as string constants in code), `frmDescription`; `ColorPickerControl` is a code-only- UserControl hard-sized to 423x411; `BrowseForFolder` builds its own folder dialog form by hand;- `SetExplorerWindowViewMode` late-binds `Shell.Application` COM to restyle Explorer windows (fragile).-- Help text in `HelpForm.cs` documents the intended behaviour of every control — use it as the spec.--## Recommended roadmap ("make the UI viable")--Do these in order; each step leaves the app runnable.--0. ~~**Git hygiene**~~ — `.gitignore` added. **Nothing is committed yet**; the pre-cleanup- decompiled baseline is not recoverable from git (only from the original binary).-1. ~~**Make it compile**~~ — done 2026-10-06.-2. **Strip VB residue** — done 2026-10-07 (WithEvents block, Token comments, VB runtime- helpers, placeholder names, control flow), followed by an XML-doc pass: every type and member- in the hand-maintained files has `///` docs (~1,400 members; `DocumentationFile` is on in the- csproj so malformed docs are build warnings). Threading, units and coordinate systems are stated- in the docs — read them before changing anything on the engine/UI boundary.- **Latent issues found while documenting, left unchanged on purpose** (behaviour-preserving pass):- - `AviMjpegWriter`: the header actually written is 236 bytes but the `Pos*` patch offsets assume- 224, so the `movi` size is patched into the BITMAPINFOHEADER and `idx1` offsets are off by 12.- Players may or may not tolerate it; see the class `<remarks>`.- - `WaveEngineFactory.Create`: the "first choice failed" branch is dead (`GpuWaveSimulator.TryCreate`- never returns an engine together with a message).- - `SimulationSettings.FromConfig` per-key fallbacks differ from the constructor defaults- (steps 2500 vs 0, 4th-order false vs true, c 0.563 vs 1.0, decay 10 vs 0).- - `btnRenameProject_Click` re-opens the project from disk, silently discarding unsaved edits.- - `GpuWaveSimulator.SetProbes` leaks earlier probe kernel handles if called twice; `SetProbes(null)`- does not clear an installed sampler (CPU engine does).- - Unused members kept for signature stability: `Form1.ThumbWidth/ThumbHeight/FVM_*`, `_hasRun`,- `SourceElement.DetachRampSteps` (engines use literal 30), `SimulationRunner.JpegQuality`,- `AviMjpegWriter.MaxFileSize`, `AppSettings.LastRootFolder/LastProjectName` (written, never read).- Still open: replace `My/*` with a plain `Program.Main`- (`EnableVisualStyles`, `SetCompatibleTextRenderingDefault`, `SetHighDpiMode`); convert- `ref` parameters that are really `out`; drop the `Microsoft.VisualBasic` reference once nothing- uses it.-3. **Retarget** — recommended: SDK-style csproj on **.NET 8 (or 10) `net8.0-windows` + `UseWindowsForms`**.- Consequences: `JavaScriptSerializer` (System.Web.Extensions) -> `System.Text.Json` with the same- snake_case keys (`last_root_folder`, ...) so existing projects still load; `Microsoft.VisualBasic`- still exists on .NET; P/Invoke code (OpenCL, Media Foundation, shell32, gdi32) ports unchanged.- Fallback if staying on Framework: 4.8 + `app.manifest` with PerMonitorV2.-4. **Split `Form1` by tab** into UserControls (`SettingsPage`, `SourcesPage`, `ProbesPage`,- `PreviewPage`, `OutputPage`, `ColorsPage`) following the existing line-range seams; keep a thin- shell form owning menu, status bar, bottom strip, and the `SimulationRunner` lifecycle. Move- project/scene/simulation state out of the form into a small view-model/service so pages share it.-5. **Layout** — per page: `TableLayoutPanel`/`FlowLayoutPanel`, `Dock`/`Anchor`, `MinimumSize`,- splitter between settings and preview, single font (Segoe UI 9 pt, let DPI scaling do the rest),- drop custom colours and owner-drawn tabs; replace `MessageBox` validation with inline hints / `ErrorProvider`.-6. Only after 1–5: consider moving off WinForms (WPF/Avalonia). Not before — the engine/UI boundary- must be clean first, and WinForms is sufficient for this app's needs.--## Conventions / gotchas when editing here--- Formatting is governed by `.editorconfig` (tabs in `.cs`). In Git Bash, `grep -E` needs `$' '` for- tabs; `grep -P` is broken (locale error).-- Namespace stays `_2D_wave_sim_V01` until step 3 (settings path and resources depend on it).-- `Microsoft.VisualBasic` is still referenced only for `WindowsFormsApplicationBase` in `My/`.+Controls are private fields at the bottom of `Form1.Designer.cs`; handlers are attached in+`InitializeComponent` under `// event wiring (was VB WithEvents/Handles)`. The Designer files are+decompiled output with `global::` prefixes and have not been opened in the VS designer — do not+expect round-tripping. `Form1.Designer.cs` has 318 controls on a fixed 1781×989 form with absolute+positions, no `Dock`/`Anchor`, Microsoft Sans Serif in seven sizes, no DPI manifest — the reason the+UI is being rebuilt in WPF rather than restyled. Six tabs: Settings, Sources, Probes, Preview, Manage+output, Colors; a persistent bottom strip with Start/Pause, share-image and quick-navigate buttons.+`HelpForm.cs` holds the user-facing description of every control and is the closest thing to a+functional spec for the WPF UI.++## Known issues (open)++- `WaveEngineFactory.Create`: the "first choice failed" branch is dead (`GpuWaveSimulator.TryCreate`+ never returns an engine together with a message).+- `SimulationSettings.FromConfig` per-key fallbacks differ from the constructor defaults+ (steps 2500 vs 0, 4th-order false vs true, c 0.563 vs 1.0, decay 10 vs 0). **Not a bug**: the VB+ docs (`SimulationSettings.vb:47-49, 92-119`) say old projects must keep their exact behaviour while new+ projects take the Designer values via `StartNewProject`. The C# `<remarks>` now says so.+- Still from the VB audit, not done: no GPL headers in the C# (deliberately deferred; the C# tree is+ temporary); `AssemblyCopyright` lacks the author's name; decompiler artefacts remain (`MessageBoxIcon`+ aliases, `Keys.Return`, `VBByRefStr ref string` on two OpenCL P/Invokes, `OpenClApi` not `static`,+ nested `*EventHandler` delegates in `SimulationRunner`, `colCreatedOn2` declared in `Form1.Simulation.cs`+ instead of the Designer); the csproj does not copy `ColorSchemeList/` to the output as the vbproj did.+- `btnRenameProject_Click` re-opens the project from disk, silently discarding unsaved edits.+- `AboutForm` code says "Version 0.27", designer says 0.29; `HelpForm` text has typos ("everly").+- Unused members: `Form1._hasRun`, `SimulationRunner.JpegQuality`,+ `AppSettings.LastRootFolder/LastProjectName` (written, never read).+- `My/*` + `WindowsFormsApplicationBase` startup is the only remaining `Microsoft.VisualBasic` use;+ replace with `Program.Main` (`EnableVisualStyles`, `SetCompatibleTextRenderingDefault`) when convenient.+- Private `ref` parameters that are really `out` remain outside the engines (`TryPictureToCanvas`,+ `TryParseInt`, `DampingProblem`, `PromptForCValue`, `ComputeRanges`, `RgbToHsv`, …).+- WPF: theme choice not persisted; panes empty.++Fixed on 2026-10-07 (kept here so nobody re-reports them): `AviMjpegWriter` header/offset mismatch+(header was 236 bytes vs. 224 assumed; now spec-exact, see `avi_check`); `GpuWaveSimulator.SetProbes`+leaking the previous probe set and ignoring `null`; GPU engine carrying 28 buffer fields that existed+only to be released, plus a hand-copied `ComputeSubSteps`; `SourceElement.DetachRampSteps` now used by+both engines instead of a literal 30.++Fixed on 2026-10-08 from the VB audit (`_tools/VB_SOURCE_AUDIT.md`): the author's rationale comments,+Python-provenance notes and wrong C# docs ported into every C# file; folded constants restored+(`ColorScheme.StopCount/EntryCount`, `SceneSettings.Max*`, `Thumb*`, `FVM_*`, hex OpenCL constants,+`4f/3f`-style fractions, local consts); locals renamed where the VB name was clearer. Behaviour+restored to the author's: `AviMjpegWriter` strh `dwQuality` = -1 (new `avi_check` check);+`WaveSimulator.ApplySources` reuses `_levelValue` instead of allocating per step; `ColorSchemeStore`+probes for `*.sln` (was `*.vbproj`, which never matched above the C# exe); NaN-safe `!(a > b)` checks in+`ProbeGraphPainter`/`ProbeSettings`; `ProbeSampler` uses `!= Amplitude`; `Form1.StopRole` parity test;+`HelpForm` disclaimer is the author's GPL wording.++## Roadmap++1. ~~Make it compile~~ · 2. ~~clean up / document~~ · 2b. ~~AVI fix, style pass, engine refactor~~+3. **Extract the engine into `WaveDude/`** (see "Moving engine code" above), with the WinForms app+ referencing it so both UIs run the same code. Replace `JavaScriptSerializer`; decide the+ `System.Drawing` question; turn the two harnesses into real test projects while at it.+4. **Make the engine loop `Task`-based**: `SimulationRunner` becomes an `async` driver+ (`Task.Run` loop, `CancellationToken`, `IProgress<T>`/channels instead of raw events on a worker+ thread), keeping the one-driver-at-a-time engine contract.+5. **WPF UI** in `WaveDude.WPF`: fill the Project / Preview / Properties panes; preview as a+ `WriteableBitmap` fed from `FrameRenderer` pixel buffers; MVVM over the existing settings POCOs;+ persist the theme choice. Use `HelpForm.cs` as the functional spec.+6. Retire `Wave_Dude_2D` once the WPF app covers it.++## Conventions++- Style: modern concise C# — expression-bodied accessors, **no `this.` qualification**, no+ `IDisposable` on interfaces, `out` not `ref` for outputs, private state only for what genuinely+ outlives a method (run `_tools/field_usage.py` when in doubt). `.editorconfig` encodes it.+- Fix bugs you find and prove the fix with a harness; do not just document them.+- Every type and member carries `///` docs stating threading, units and coordinate systems+ (canvas pixels vs picture-box pixels; steps vs seconds; radians vs degrees). Keep that up.+- Formatting: tabs in `.cs`, Allman braces, governed by `.editorconfig`. In Git Bash `grep -P` is+ broken (locale); use `grep -E`.+- Namespace stays `_2D_wave_sim_V01` in `Wave_Dude_2D` (settings path and resources depend on it).- `ColorScheme.StopCount` is 9 and `Form1` asserts the nine `btnColorN` buttons match it.-- Probe count is hard-wired to 2 (`ProbeCount`, duplicated `*2` controls/handlers) — a `ProbeControlSet`- array already abstracts it; generalising is cheap once the UI is split.-- Video export requires Media Foundation (Windows N editions need the Media Feature Pack); AVI/MJPEG is- the fallback. GPU path needs an OpenCL ICD (`OpenCL.dll`); the CPU engine is the fallback.+- Probe count is hard-wired to 2 in the UI (`ProbeCount`, duplicated `*2` controls); the engines and+ `ProbeSampler` take any number.+- Video export needs Media Foundation (Windows N: Media Feature Pack); AVI/MJPEG is the fallback.+ GPU path needs an OpenCL ICD (`OpenCL.dll`); the CPU engine is the fallback. This machine has an+ RTX 2080 with working OpenCL, so `engine_check` exercises both paths here.diff --git a/WaveDude.WPF/App.ico b/WaveDude.WPF/App.iconew file mode 100644index 0000000..daf72c8Binary files /dev/null and b/WaveDude.WPF/App.ico differdiff --git a/WaveDude.WPF/App.xaml b/WaveDude.WPF/App.xamlnew file mode 100644index 0000000..63b518f--- /dev/null+++ b/WaveDude.WPF/App.xaml@@ -0,0 +1,16 @@+<Application x:Class="WaveDude.WPF.App"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">+ <Application.Resources>+ <ResourceDictionary>+ <ResourceDictionary.MergedDictionaries>+ <!-- colour table first (swapped at runtime by ThemeController), then the control styles -->+ <ResourceDictionary Source="Themes/Dark.xaml" />+ <ResourceDictionary Source="Themes/Controls.xaml" />+ <ResourceDictionary Source="Themes/Editors.xaml" />+ <ResourceDictionary Source="Themes/Lists.xaml" />+ <ResourceDictionary Source="Strings/Strings.EN.xaml" />+ </ResourceDictionary.MergedDictionaries>+ </ResourceDictionary>+ </Application.Resources>+</Application>diff --git a/WaveDude.WPF/App.xaml.cs b/WaveDude.WPF/App.xaml.csnew file mode 100644index 0000000..cfa048a--- /dev/null+++ b/WaveDude.WPF/App.xaml.cs@@ -0,0 +1,231 @@+using System.Configuration;+using System.Diagnostics;+using System.IO;+using System.Reflection;+using System.Runtime.InteropServices;+using System.Globalization;+using System.Windows;+using System.Windows.Markup;+using NLog;+using NLog.Config;+using NLog.Targets;+using WaveDude.WPF.Logging;+using WaveDude.WPF.Properties;+using WaveDude.WPF.Theming;++namespace WaveDude.WPF;++/// <summary>+/// Application entry point. Logging is configured by <see cref="SetupLoggingConfig"/> from+/// <c>Program.Main</c>; <see cref="OnStartup"/> records the environment and applies the theme+/// before the main window is created.+/// </summary>+public partial class App : Application+{+ /// <summary>Logger of the application class; other classes get their own via <see cref="LogManager.GetCurrentClassLogger"/>.</summary>+ public static readonly ILogger Logger = LogManager.GetCurrentClassLogger();++ private const string FileLayout =+ "${date:format=yyyy-MM-dd HH\\:mm\\:ss}\t${threadid}\t${level}\t${logger}\t${message}\t${onexception:EXCEPTION\\: ${exception:format=tostring}}";+ private const string DebugLayout =+ "${date:format=HH\\:mm\\:ss} ${threadid} ${level} ${logger:shortName=true}\t${message}\t${onexception:EXCEPTION\\: ${exception:format=tostring}}";++ private const string LogFileName = "WaveDude.WPF.log";++ /// <summary>+ /// Per-user, per-machine data folder (<c>%LocalAppData%\WaveDude</c>, deliberately not the+ /// roaming profile), used for the log when the executable's folder is read-only.+ /// </summary>+ public static string LocalAppDataDirectory { get; } =+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "WaveDude");++ /// <summary>+ /// Path of the current log file. Next to the executable when that folder is writable,+ /// otherwise in <see cref="LocalAppDataDirectory"/>. Set by <see cref="SetupLoggingConfig"/>.+ /// </summary>+ public static string LogFile { get; private set; } = Path.Combine(AppContext.BaseDirectory, LogFileName);++ /// <summary>+ /// Replaces the NLog configuration with the application's targets: a rolling file next to+ /// the executable (everything in Debug builds, Info and up in Release), plus the debugger+ /// and console in Debug builds. Also routes unhandled exceptions of the AppDomain and of+ /// unobserved tasks to the log. Call once, before the application object exists.+ /// </summary>+ public static void SetupLoggingConfig()+ {+ LogFile = Path.Combine(ResolveLogDirectory(), LogFileName);+ var config = new LoggingConfiguration();++ var fileTarget = new FileTarget("logfile")+ {+ FileName = LogFile,+ ArchiveFileName = Path.ChangeExtension(LogFile, "archive.log"), // NLog 6 appends _00, _01 itself+ MaxArchiveFiles = 2,+ ArchiveAboveSize = 8 * 1024 * 1024,+ ArchiveOldFileOnStartup = true,+ KeepFileOpen = true,+ Layout = FileLayout,+ };+ config.AddTarget(fileTarget);++ // status bar: Info and above, warnings on orange, errors on red; attaches to the window once it exists+ var statusBar = new StatusBarTarget+ {+ Name = "statusbar",+ WindowName = nameof(MainWindow),+ ControlName = "txtStatus",+ Layout = "${message}${onexception: (${exception:format=message})}",+ };+ statusBar.ColoringRules.Add(new StatusBarColoringRule("level >= LogLevel.Error", "StatusBarErrorForeground", "StatusBarErrorBackground"));+ statusBar.ColoringRules.Add(new StatusBarColoringRule("level == LogLevel.Warn", "StatusBarWarnForeground", "StatusBarWarnBackground"));+ config.AddTarget(statusBar);+ config.AddRule(LogLevel.Info, LogLevel.Fatal, statusBar);++ // in-memory buffer behind the Messages pane; everything in Debug, Info and up in Release+ var messages = new MessagesTarget { Name = "messages" };+ config.AddTarget(messages);+#if DEBUG+ config.AddRule(LogLevel.Trace, LogLevel.Fatal, messages);+#else+ config.AddRule(LogLevel.Info, LogLevel.Fatal, messages);+#endif+#if DEBUG+ config.AddRule(LogLevel.Trace, LogLevel.Fatal, fileTarget);+ config.AddRule(LogLevel.Trace, LogLevel.Fatal, new DebuggerTarget("debugger") { Layout = DebugLayout });+ config.AddRule(LogLevel.Trace, LogLevel.Fatal, new ColoredConsoleTarget("console") { Layout = DebugLayout });+#else+ config.AddRule(LogLevel.Info, LogLevel.Fatal, fileTarget);+#endif+ LogManager.Configuration = config;++#if DEBUG+ // WPF binding errors go to a trace source, not to exceptions; route them into the log+ PresentationTraceSources.Refresh();+ PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Warning;+ PresentationTraceSources.DataBindingSource.Listeners.Add(new TraceLogListener { Name = "WPF" });+#endif++ AppDomain.CurrentDomain.UnhandledException += (_, args) =>+ Logger.Fatal(args.ExceptionObject as Exception, "AppDomain.UnhandledException");+ TaskScheduler.UnobservedTaskException += (_, args) =>+ Logger.Fatal(args.Exception, "TaskScheduler.UnobservedTaskException");+ }++ /// <summary>The executable's folder if a file can be created there, else <see cref="LocalAppDataDirectory"/>.</summary>+ private static string ResolveLogDirectory()+ {+ if (IsWritable(AppContext.BaseDirectory))+ {+ return AppContext.BaseDirectory;+ }+ Directory.CreateDirectory(LocalAppDataDirectory);+ return LocalAppDataDirectory;+ }++ private static bool IsWritable(string directory)+ {+ try+ {+ string probe = Path.Combine(directory, Path.GetRandomFileName());+ using (new FileStream(probe, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1, FileOptions.DeleteOnClose))+ {+ }+ return true;+ }+ catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)+ {+ return false;+ }+ }++ /// <summary>+ /// Makes the user settings usable: carries them over from the previous version on the+ /// first start after an update, and resets them when <c>user.config</c> is corrupt.+ /// </summary>+ private static void PrepareSettings()+ {+ try+ {+ if (Settings.Default.UpgradeRequired)+ {+ Settings.Default.Upgrade();+ Settings.Default.UpgradeRequired = false;+ Settings.Default.Save();+ Logger.Info("User settings upgraded from the previous version");+ }+ }+ catch (ConfigurationErrorsException ex)+ {+ string? file = (ex.InnerException as ConfigurationErrorsException)?.Filename ?? ex.Filename;+ Logger.Error(ex, "User settings file '{Path}' is unreadable; resetting to defaults", file);+ if (file != null && File.Exists(file))+ {+ File.Delete(file);+ }+ Settings.Default.Reload();+ }+ }++ /// <inheritdoc/>+ protected override void OnStartup(StartupEventArgs e)+ {+ base.OnStartup(e);++ // WPF formats and parses bound numbers with the element's Language, which defaults to en-US+ // regardless of the Windows locale; make every element follow the user's culture instead+ // (a combo listing 0.25 next to a text box showing 1,5 otherwise). Must run before any window.+ FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement),+ new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));++ DispatcherUnhandledException += (_, args) =>+ {+ Logger.Fatal(args.Exception, "Application.DispatcherUnhandledException");+ args.Handled = false; // let it crash so the issue is visible+ };++ Logger.Info("Application: '{Path}'", Environment.ProcessPath);+ Logger.Info("Application Version: {Version}", Assembly.GetExecutingAssembly().GetName().Version);+ Logger.Info("OS: '{OS}'", Environment.OSVersion.VersionString);+ Logger.Info("Runtime: '{Runtime}'", RuntimeInformation.FrameworkDescription);+ Logger.Info("Log file: '{Path}'", LogFile);++ // double-clicking a project file in Explorer then starts this exe with the path as e.Args[0]+ if (Environment.ProcessPath is string executable)+ {+ FileAssociation.Register(WPF.MainWindow.ProjectExtension, executable);+ }++ PrepareSettings();++ ThemeController.Instance.Current = Settings.Default.Theme;+ ThemeController.Instance.PropertyChanged += (_, args) =>+ {+ if (args.PropertyName == nameof(ThemeController.Current))+ {+ Settings.Default.Theme = ThemeController.Instance.Current;+ }+ };+ ThemeController.Instance.Refresh();++ var window = new MainWindow();+ MainWindow = window;+ window.Show();+ // the last start-up line, and so the status bar's first text unless a file is opened below+ Logger.Info("{Title} {Version} ready", FindResource("Title"), Assembly.GetExecutingAssembly().GetName().Version?.ToString(3));+ if (e.Args.Length > 0)+ {+ // launched with a project file (double-click, "open with", command line); after+ // Show so that an error box has the main window behind it+ Logger.Info("Startup arguments: {Args}", string.Join(" ", e.Args));+ window.OpenFile(e.Args[0]);+ }+ }++ /// <inheritdoc/>+ protected override void OnExit(ExitEventArgs e)+ {+ Logger.Info("Application exit, code {Code}", e.ApplicationExitCode);+ base.OnExit(e);+ LogManager.Shutdown();+ }+}diff --git a/WaveDude.WPF/AssemblyInfo.cs b/WaveDude.WPF/AssemblyInfo.csnew file mode 100644index 0000000..eb35a51--- /dev/null+++ b/WaveDude.WPF/AssemblyInfo.cs@@ -0,0 +1,6 @@+using System.Windows;++[assembly: ThemeInfo(+ ResourceDictionaryLocation.None, // theme-specific resource dictionaries: none+ ResourceDictionaryLocation.SourceAssembly // generic resource dictionary: this assembly+)]diff --git a/WaveDude.WPF/Commands/ProjectCommands.cs b/WaveDude.WPF/Commands/ProjectCommands.csnew file mode 100644index 0000000..932d08b--- /dev/null+++ b/WaveDude.WPF/Commands/ProjectCommands.cs@@ -0,0 +1,32 @@+using System.Windows.Input;++namespace WaveDude.WPF.Commands;++/// <summary>+/// Commands that edit the project structure. Bound once on the main window; the parameter is+/// the tree node to act on, or null to act on the current selection. Exposed through the+/// Project pane toolbar, the tree's row buttons, its context menu and its key bindings.+/// </summary>+public static class ProjectCommands+{+ /// <summary>Appends a new source.</summary>+ public static readonly RoutedUICommand AddSource = new("Add source", nameof(AddSource), typeof(ProjectCommands));++ /// <summary>Appends a new probe.</summary>+ public static readonly RoutedUICommand AddProbe = new("Add probe", nameof(AddProbe), typeof(ProjectCommands));++ /// <summary>Appends a new item to the folder node given as parameter.</summary>+ public static readonly RoutedUICommand Add = new("Add", nameof(Add), typeof(ProjectCommands));++ /// <summary>Inserts a copy of a source or probe after the original.</summary>+ public static readonly RoutedUICommand Duplicate = new("Duplicate", nameof(Duplicate), typeof(ProjectCommands));++ /// <summary>Removes a source or probe.</summary>+ public static readonly RoutedUICommand Remove = new("Remove", nameof(Remove), typeof(ProjectCommands));++ /// <summary>Swaps a source or probe with its predecessor.</summary>+ public static readonly RoutedUICommand MoveUp = new("Move up", nameof(MoveUp), typeof(ProjectCommands));++ /// <summary>Swaps a source or probe with its successor.</summary>+ public static readonly RoutedUICommand MoveDown = new("Move down", nameof(MoveDown), typeof(ProjectCommands));+}diff --git a/WaveDude.WPF/Commands/RelayCommand.cs b/WaveDude.WPF/Commands/RelayCommand.csnew file mode 100644index 0000000..47d52e3--- /dev/null+++ b/WaveDude.WPF/Commands/RelayCommand.cs@@ -0,0 +1,38 @@+using System.Windows.Input;++namespace WaveDude.WPF.Commands;++/// <summary>+/// <see cref="ICommand"/> over a delegate with a typed parameter.+/// </summary>+public sealed class RelayCommand<T> : ICommand+{+ private readonly Action<T> _execute;+ private readonly Predicate<T>? _canExecute;++ public RelayCommand(Action<T> execute, Predicate<T>? canExecute = null)+ {+ _execute = execute;+ _canExecute = canExecute;+ }++ /// <inheritdoc/>+ public event EventHandler? CanExecuteChanged+ {+ add => CommandManager.RequerySuggested += value;+ remove => CommandManager.RequerySuggested -= value;+ }++ /// <inheritdoc/>+ public bool CanExecute(object? parameter) =>+ parameter is T value && (_canExecute == null || _canExecute(value));++ /// <inheritdoc/>+ public void Execute(object? parameter)+ {+ if (parameter is T value)+ {+ _execute(value);+ }+ }+}diff --git a/WaveDude.WPF/Controls/FormPanel.cs b/WaveDude.WPF/Controls/FormPanel.csnew file mode 100644index 0000000..c1fd59b--- /dev/null+++ b/WaveDude.WPF/Controls/FormPanel.cs@@ -0,0 +1,177 @@+using System.Windows;+using System.Windows.Controls;++namespace WaveDude.WPF.Controls;++/// <summary>+/// Two-column form layout: children are taken in pairs, label left and editor right, one pair+/// per row. The label column is as wide as the widest label (at least <see cref="LabelWidth"/>),+/// the editor column takes the rest. A child with <see cref="FullWidthProperty"/> set occupies a+/// row of its own across both columns.+/// </summary>+public sealed class FormPanel : Panel+{+ /// <summary>Identifies the <see cref="LabelWidth"/> property.</summary>+ public static readonly DependencyProperty LabelWidthProperty = DependencyProperty.Register(+ nameof(LabelWidth), typeof(double), typeof(FormPanel),+ new FrameworkPropertyMetadata(110.0, FrameworkPropertyMetadataOptions.AffectsMeasure));++ /// <summary>Identifies the <see cref="RowSpacing"/> property.</summary>+ public static readonly DependencyProperty RowSpacingProperty = DependencyProperty.Register(+ nameof(RowSpacing), typeof(double), typeof(FormPanel),+ new FrameworkPropertyMetadata(4.0, FrameworkPropertyMetadataOptions.AffectsMeasure));++ /// <summary>Identifies the <see cref="ColumnSpacing"/> property.</summary>+ public static readonly DependencyProperty ColumnSpacingProperty = DependencyProperty.Register(+ nameof(ColumnSpacing), typeof(double), typeof(FormPanel),+ new FrameworkPropertyMetadata(8.0, FrameworkPropertyMetadataOptions.AffectsMeasure));++ /// <summary>Attached: the child spans both columns on a row of its own.</summary>+ public static readonly DependencyProperty FullWidthProperty = DependencyProperty.RegisterAttached(+ "FullWidth", typeof(bool), typeof(FormPanel),+ new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.AffectsParentMeasure));++ /// <summary>Minimum width of the label column.</summary>+ public double LabelWidth+ {+ get => (double)GetValue(LabelWidthProperty);+ set => SetValue(LabelWidthProperty, value);+ }++ /// <summary>Vertical gap between rows.</summary>+ public double RowSpacing+ {+ get => (double)GetValue(RowSpacingProperty);+ set => SetValue(RowSpacingProperty, value);+ }++ /// <summary>Gap between the label and the editor column.</summary>+ public double ColumnSpacing+ {+ get => (double)GetValue(ColumnSpacingProperty);+ set => SetValue(ColumnSpacingProperty, value);+ }++ /// <summary>Gets <see cref="FullWidthProperty"/>.</summary>+ public static bool GetFullWidth(UIElement element) => (bool)element.GetValue(FullWidthProperty);++ /// <summary>Sets <see cref="FullWidthProperty"/>.</summary>+ public static void SetFullWidth(UIElement element, bool value) => element.SetValue(FullWidthProperty, value);++ /// <inheritdoc/>+ protected override Size MeasureOverride(Size availableSize)+ {+ // first pass: labels at their natural width+ double labelWidth = LabelWidth;+ foreach ((UIElement? label, _) in Rows())+ {+ if (label != null)+ {+ label.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));+ labelWidth = Math.Max(labelWidth, label.DesiredSize.Width);+ }+ }++ double editorWidth = Math.Max(0, availableSize.Width - labelWidth - ColumnSpacing);+ double height = 0;+ double width = 0;+ int rows = 0;+ foreach ((UIElement? label, UIElement? editor) in Rows())+ {+ double rowHeight = 0;+ if (label == null && editor != null)+ {+ editor.Measure(new Size(availableSize.Width, double.PositiveInfinity));+ rowHeight = editor.DesiredSize.Height;+ width = Math.Max(width, editor.DesiredSize.Width);+ }+ else+ {+ if (editor != null)+ {+ editor.Measure(new Size(editorWidth, double.PositiveInfinity));+ rowHeight = editor.DesiredSize.Height;+ width = Math.Max(width, labelWidth + ColumnSpacing + editor.DesiredSize.Width);+ }+ if (label != null)+ {+ rowHeight = Math.Max(rowHeight, label.DesiredSize.Height);+ width = Math.Max(width, labelWidth);+ }+ }+ height += rowHeight;+ rows++;+ }+ if (rows > 1)+ {+ height += (rows - 1) * RowSpacing;+ }+ return new Size(Math.Min(width, availableSize.Width), height);+ }++ /// <inheritdoc/>+ protected override Size ArrangeOverride(Size finalSize)+ {+ double labelWidth = LabelWidth;+ foreach ((UIElement? label, _) in Rows())+ {+ if (label != null)+ {+ labelWidth = Math.Max(labelWidth, label.DesiredSize.Width);+ }+ }+ double editorX = labelWidth + ColumnSpacing;+ double editorWidth = Math.Max(0, finalSize.Width - editorX);+ double y = 0;+ foreach ((UIElement? label, UIElement? editor) in Rows())+ {+ double rowHeight = Math.Max(label?.DesiredSize.Height ?? 0, editor?.DesiredSize.Height ?? 0);+ if (label == null && editor != null)+ {+ editor.Arrange(new Rect(0, y, finalSize.Width, rowHeight));+ }+ else+ {+ label?.Arrange(new Rect(0, y, labelWidth, rowHeight));+ editor?.Arrange(new Rect(editorX, y, editorWidth, rowHeight));+ }+ y += rowHeight + RowSpacing;+ }+ return finalSize;+ }++ /// <summary>Groups the visible children into rows: (label, editor) pairs or (null, full-width child).</summary>+ private IEnumerable<(UIElement? Label, UIElement? Editor)> Rows()+ {+ UIElement? pendingLabel = null;+ foreach (UIElement? child in InternalChildren)+ {+ if (child == null || child.Visibility == Visibility.Collapsed)+ {+ continue;+ }+ if (GetFullWidth(child))+ {+ if (pendingLabel != null)+ {+ yield return (pendingLabel, null);+ pendingLabel = null;+ }+ yield return (null, child);+ }+ else if (pendingLabel == null)+ {+ pendingLabel = child;+ }+ else+ {+ yield return (pendingLabel, child);+ pendingLabel = null;+ }+ }+ if (pendingLabel != null)+ {+ yield return (pendingLabel, null);+ }+ }+}diff --git a/WaveDude.WPF/Controls/InsertionAdorner.cs b/WaveDude.WPF/Controls/InsertionAdorner.csnew file mode 100644index 0000000..80e8656--- /dev/null+++ b/WaveDude.WPF/Controls/InsertionAdorner.cs@@ -0,0 +1,57 @@+using System.Windows;+using System.Windows.Documents;+using System.Windows.Media;++namespace WaveDude.WPF.Controls;++/// <summary>+/// Drop feedback for reordering: a horizontal line above or below the adorned element, or an+/// outline around it when dropping appends to a folder.+/// </summary>+public sealed class InsertionAdorner : Adorner+{+ private readonly Pen _pen;++ /// <param name="adorned">The row the feedback is drawn over.</param>+ /// <param name="brush">Colour of the line or outline.</param>+ /// <param name="placement">Where to draw relative to the row.</param>+ public InsertionAdorner(UIElement adorned, Brush brush, InsertionPlacement placement) : base(adorned)+ {+ _pen = new Pen(brush, 2);+ _pen.Freeze();+ Placement = placement;+ IsHitTestVisible = false;+ }++ /// <summary>Where the feedback is drawn.</summary>+ public InsertionPlacement Placement { get; }++ /// <inheritdoc/>+ protected override void OnRender(DrawingContext drawingContext)+ {+ Size size = AdornedElement.RenderSize;+ switch (Placement)+ {+ case InsertionPlacement.Before:+ drawingContext.DrawLine(_pen, new Point(0, 1), new Point(size.Width, 1));+ break;+ case InsertionPlacement.After:+ drawingContext.DrawLine(_pen, new Point(0, size.Height - 1), new Point(size.Width, size.Height - 1));+ break;+ default:+ drawingContext.DrawRectangle(null, _pen, new Rect(1, 1, Math.Max(0, size.Width - 2), Math.Max(0, size.Height - 2)));+ break;+ }+ }+}++/// <summary>Position of the drop feedback relative to the adorned row.</summary>+public enum InsertionPlacement+{+ /// <summary>Line along the top edge: insert before this item.</summary>+ Before,+ /// <summary>Line along the bottom edge: insert after this item.</summary>+ After,+ /// <summary>Outline: append to this folder.</summary>+ Into,+}diff --git a/WaveDude.WPF/Controls/TreeViewExtensions.cs b/WaveDude.WPF/Controls/TreeViewExtensions.csnew file mode 100644index 0000000..6d24fdd--- /dev/null+++ b/WaveDude.WPF/Controls/TreeViewExtensions.cs@@ -0,0 +1,41 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Controls;++/// <summary>Selection helpers for data-bound <see cref="TreeView"/>s.</summary>+public static class TreeViewExtensions+{+ /// <summary>+ /// Selects and focuses the container of a data item anywhere in the tree, optionally+ /// expanding it. Only realised containers are searched, so call it once the tree has+ /// generated its items. Returns false when the item was not found.+ /// </summary>+ public static bool SetSelectedItem(this TreeView tree, object item, bool expand = false) =>+ SetSelected(tree, item, expand);++ private static bool SetSelected(ItemsControl? parent, object item, bool expand)+ {+ if (parent == null)+ {+ return false;+ }+ if (parent.ItemContainerGenerator.ContainerFromItem(item) is TreeViewItem container)+ {+ container.Focus();+ if (expand)+ {+ container.IsExpanded = true;+ }+ container.IsSelected = true;+ return true;+ }+ foreach (object child in parent.Items)+ {+ if (SetSelected(parent.ItemContainerGenerator.ContainerFromItem(child) as ItemsControl, item, expand))+ {+ return true;+ }+ }+ return false;+ }+}diff --git a/WaveDude.WPF/Converters/DoubleTextConverter.cs b/WaveDude.WPF/Converters/DoubleTextConverter.csnew file mode 100644index 0000000..37ccd3b--- /dev/null+++ b/WaveDude.WPF/Converters/DoubleTextConverter.cs@@ -0,0 +1,22 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Binds the text of an editable field to a <see cref="double"/> without the binding engine's+/// exceptions: text that does not parse yet (empty, a lone minus, "1.") leaves the source alone+/// instead of logging a conversion error on every keystroke. Both directions use the culture+/// the binding passes in, which <c>App.OnStartup</c> makes the user's culture for every element,+/// so the text agrees with how the preset list shows the same values.+/// </summary>+public sealed class DoubleTextConverter : IValueConverter+{+ /// <inheritdoc/>+ public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>+ value is double d ? d.ToString(culture) : value?.ToString();++ /// <inheritdoc/>+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>+ double.TryParse(value as string, NumberStyles.Float, culture, out double d) ? d : Binding.DoNothing;+}diff --git a/WaveDude.WPF/Converters/EnumBooleanConverter.cs b/WaveDude.WPF/Converters/EnumBooleanConverter.csnew file mode 100644index 0000000..75c634f--- /dev/null+++ b/WaveDude.WPF/Converters/EnumBooleanConverter.cs@@ -0,0 +1,20 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Binds one radio button to one value of an enum property: checked when the property equals+/// the converter parameter, and checking it writes the parameter back. Unchecking (which the+/// group does when another button is chosen) writes nothing.+/// </summary>+public sealed class EnumBooleanConverter : IValueConverter+{+ /// <inheritdoc/>+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>+ Equals(value, parameter);++ /// <inheritdoc/>+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>+ value is true && parameter != null ? parameter : Binding.DoNothing;+}diff --git a/WaveDude.WPF/Converters/EnumNameConverter.cs b/WaveDude.WPF/Converters/EnumNameConverter.csnew file mode 100644index 0000000..56c2445--- /dev/null+++ b/WaveDude.WPF/Converters/EnumNameConverter.cs@@ -0,0 +1,27 @@+using System.Globalization;+using System.Text.RegularExpressions;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>Shows an enum value as words: <c>SmoothedSquare</c> becomes "Smoothed square".</summary>+public sealed partial class EnumNameConverter : IValueConverter+{+ [GeneratedRegex("(?<=[a-z0-9])(?=[A-Z])")]+ private static partial Regex WordBoundary();++ /// <inheritdoc/>+ public object? Convert(object? value, Type targetType, object? parameter, CultureInfo culture)+ {+ if (value == null)+ {+ return null;+ }+ string[] words = WordBoundary().Split(value.ToString() ?? "");+ return string.Join(' ', words.Select((w, i) => i == 0 ? w : w.ToLowerInvariant()));+ }++ /// <inheritdoc/>+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}diff --git a/WaveDude.WPF/Converters/EnumerateConverter.cs b/WaveDude.WPF/Converters/EnumerateConverter.csnew file mode 100644index 0000000..808a162--- /dev/null+++ b/WaveDude.WPF/Converters/EnumerateConverter.cs@@ -0,0 +1,19 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Wraps a single object in a one-element sequence, or null in an empty one, so that a lone+/// root object can be the <c>ItemsSource</c> of a tree view.+/// </summary>+public sealed class EnumerateConverter : IValueConverter+{+ /// <inheritdoc/>+ public object Convert(object? value, Type targetType, object? parameter, CultureInfo culture) =>+ value == null ? Array.Empty<object>() : new[] { value };++ /// <inheritdoc/>+ public object ConvertBack(object? value, Type targetType, object? parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}diff --git a/WaveDude.WPF/Converters/EqualityConverter.cs b/WaveDude.WPF/Converters/EqualityConverter.csnew file mode 100644index 0000000..84f8ee4--- /dev/null+++ b/WaveDude.WPF/Converters/EqualityConverter.cs@@ -0,0 +1,28 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Multi-value converter that yields true when all bound values are equal. Used to drive+/// check marks on menu items generated from a list of choices.+/// </summary>+public sealed class EqualityConverter : IMultiValueConverter+{+ /// <inheritdoc/>+ public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)+ {+ for (int i = 1; i < values.Length; i++)+ {+ if (!Equals(values[0], values[i]))+ {+ return false;+ }+ }+ return values.Length > 0;+ }++ /// <inheritdoc/>+ public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}diff --git a/WaveDude.WPF/Converters/FrameCountConverter.cs b/WaveDude.WPF/Converters/FrameCountConverter.csnew file mode 100644index 0000000..556de4e--- /dev/null+++ b/WaveDude.WPF/Converters/FrameCountConverter.cs@@ -0,0 +1,26 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Number of frames a run produces: the step count divided by the visualisation interval,+/// rounded up, at least 1. The inputs are the two integers in that order; anything missing+/// (no project) gives 1.+/// </summary>+public sealed class FrameCountConverter : IMultiValueConverter+{+ /// <inheritdoc/>+ public object Convert(object[] values, Type targetType, object? parameter, CultureInfo culture)+ {+ if (values.Length == 2 && values[0] is int steps && values[1] is int every && steps > 0 && every > 0)+ {+ return (steps + every - 1) / every;+ }+ return 1;+ }++ /// <inheritdoc/>+ public object[] ConvertBack(object value, Type[] targetTypes, object? parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}diff --git a/WaveDude.WPF/Converters/NamedCollectionConverter.cs b/WaveDude.WPF/Converters/NamedCollectionConverter.csnew file mode 100644index 0000000..ad1ab59--- /dev/null+++ b/WaveDude.WPF/Converters/NamedCollectionConverter.cs@@ -0,0 +1,74 @@+using System.Collections;+using System.Globalization;+using System.Windows;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Builds the child list of a tree node from several bindings: a collection becomes a+/// <see cref="NamedCollection"/> folder node labelled by the matching entry of the+/// comma-separated converter parameter, any other non-null value is added as a node of its own.+/// </summary>+/// <example>+/// <c>ConverterParameter=",,Sources,Probes"</c> with bindings to Scene, Simulation, Sources+/// and Probes yields two plain nodes followed by two folders.+/// </example>+public sealed class NamedCollectionConverter : IMultiValueConverter+{+ /// <inheritdoc/>+ public object Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture)+ {+ string[] names = (parameter as string)?.Split(',') ?? [];+ var result = new List<object>(values.Length);+ for (int i = 0; i < values.Length; i++)+ {+ object? value = values[i];+ if (value == null || value == DependencyProperty.UnsetValue)+ {+ continue;+ }+ if (value is IEnumerable items && value is not string)+ {+ string name = i < names.Length ? names[i].Trim() : "";+ result.Add(new NamedCollection(name, items));+ }+ else+ {+ result.Add(value);+ }+ }+ return result;+ }++ /// <inheritdoc/>+ public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}++/// <summary>+/// A labelled folder node wrapping a collection, so that a list such as the project's sources+/// shows as "Sources" with the elements beneath it. Enumerates the wrapped items.+/// </summary>+public sealed class NamedCollection : IEnumerable+{+ /// <param name="label">Header text of the folder node.</param>+ /// <param name="items">The wrapped collection; an observable one keeps the node in sync.</param>+ public NamedCollection(string label, IEnumerable items)+ {+ Label = label;+ Items = items;+ }++ /// <summary>Header text of the folder node.</summary>+ public string Label { get; }++ /// <summary>The wrapped collection.</summary>+ public IEnumerable Items { get; }++ /// <inheritdoc/>+ public IEnumerator GetEnumerator() => Items.GetEnumerator();++ /// <inheritdoc/>+ public override string ToString() => Label;+}diff --git a/WaveDude.WPF/Converters/TitleConverter.cs b/WaveDude.WPF/Converters/TitleConverter.csnew file mode 100644index 0000000..0153a1e--- /dev/null+++ b/WaveDude.WPF/Converters/TitleConverter.cs@@ -0,0 +1,19 @@+using System.Globalization;+using System.Windows.Data;++namespace WaveDude.WPF.Converters;++/// <summary>+/// Joins the non-empty parts of a window title with " - ", for example the application name+/// and the open file, so that a missing file leaves just the name.+/// </summary>+public sealed class TitleConverter : IMultiValueConverter+{+ /// <inheritdoc/>+ public object Convert(object?[] values, Type targetType, object? parameter, CultureInfo culture) =>+ string.Join(" - ", values.Select(v => v?.ToString()).Where(s => !string.IsNullOrEmpty(s)));++ /// <inheritdoc/>+ public object[] ConvertBack(object? value, Type[] targetTypes, object? parameter, CultureInfo culture) =>+ throw new NotSupportedException();+}diff --git a/WaveDude.WPF/Docking/DockCommands.cs b/WaveDude.WPF/Docking/DockCommands.csnew file mode 100644index 0000000..84327e1--- /dev/null+++ b/WaveDude.WPF/Docking/DockCommands.cs@@ -0,0 +1,15 @@+using System.Windows.Input;++namespace WaveDude.WPF.Docking;++/// <summary>+/// Routed commands handled by <see cref="DockGroupControl"/> for the group's active item.+/// </summary>+public static class DockCommands+{+ /// <summary>Moves the active item to the zone given as <see cref="DockSide"/> parameter.</summary>+ public static RoutedUICommand MoveToSide { get; } = new("Move to side", nameof(MoveToSide), typeof(DockCommands));++ /// <summary>Hides the active item.</summary>+ public static RoutedUICommand Close { get; } = new("Close", nameof(Close), typeof(DockCommands));+}diff --git a/WaveDude.WPF/Docking/DockDragManager.cs b/WaveDude.WPF/Docking/DockDragManager.csnew file mode 100644index 0000000..cc69f40--- /dev/null+++ b/WaveDude.WPF/Docking/DockDragManager.cs@@ -0,0 +1,192 @@+using System.Windows;+using System.Windows.Documents;+using System.Windows.Input;++namespace WaveDude.WPF.Docking;++/// <summary>+/// Mouse-driven pane moving for a <see cref="DockHost"/>. A title bar or tab arms a drag on+/// mouse down; once the pointer travels past the system drag threshold the host captures the+/// mouse, a <see cref="DockDropAdorner"/> shows the drop targets, and releasing over one of+/// them performs the move.+/// </summary>+internal sealed class DockDragManager+{+ private readonly DockHost _host;+ private DockGroupControl? _source;+ private DockItem? _sourceItem;+ private Point _armPoint;+ private bool _armed;+ private bool _dragging;+ private bool _finishing;+ private DockDropAdorner? _adorner;++ public DockDragManager(DockHost host)+ {+ _host = host;+ _host.PreviewMouseMove += OnMouseMove;+ _host.PreviewMouseLeftButtonUp += OnMouseUp;+ _host.LostMouseCapture += OnLostMouseCapture;+ }++ /// <summary>+ /// Records a potential drag. <paramref name="item"/> is the single tab being dragged, or+ /// null when the whole group (title bar) is dragged.+ /// </summary>+ public void Arm(DockGroupControl source, DockItem? item, Point hostPoint)+ {+ _source = source;+ _sourceItem = item;+ _armPoint = hostPoint;+ _armed = true;+ }++ private void OnMouseMove(object sender, MouseEventArgs e)+ {+ if (!_armed || _source == null)+ {+ return;+ }+ if (e.LeftButton != MouseButtonState.Pressed)+ {+ Finish();+ return;+ }+ Point point = e.GetPosition(_host);+ if (!_dragging)+ {+ if (Math.Abs(point.X - _armPoint.X) < SystemParameters.MinimumHorizontalDragDistance+ && Math.Abs(point.Y - _armPoint.Y) < SystemParameters.MinimumVerticalDragDistance)+ {+ return;+ }+ AdornerLayer? layer = AdornerLayer.GetAdornerLayer(_host);+ if (layer == null)+ {+ Finish();+ return;+ }+ // State must be complete before capturing: Mouse.Capture re-raises a mouse move+ // synchronously, which re-enters this handler.+ _dragging = true;+ string title = _sourceItem?.Title ?? _source.Group.ActiveItem?.Title ?? string.Empty;+ _adorner = new DockDropAdorner(_host, title);+ layer.Add(_adorner);+ if (!Mouse.Capture(_host))+ {+ Finish();+ return;+ }+ }+ var hovered = _host.HitNode(_host.InputHitTest(point) as DependencyObject);+ _adorner!.Update(point, hovered, _source.Group, _sourceItem);+ e.Handled = true;+ }++ private void OnMouseUp(object sender, MouseButtonEventArgs e)+ {+ if (!_armed)+ {+ return;+ }+ if (!_dragging)+ {+ Finish();+ return;+ }+ DropTarget target = _adorner!.CurrentTarget;+ DockGroupControl source = _source!;+ DockItem? item = _sourceItem;+ Finish();+ Perform(target, source.Group, item);+ e.Handled = true;+ }++ private void OnLostMouseCapture(object sender, MouseEventArgs e)+ {+ if (_dragging && !_finishing)+ {+ Finish();+ }+ }++ private void Finish()+ {+ if (_finishing)+ {+ return;+ }+ _finishing = true;+ _armed = false;+ _dragging = false;+ if (_adorner != null)+ {+ AdornerLayer.GetAdornerLayer(_host)?.Remove(_adorner);+ _adorner = null;+ }+ if (ReferenceEquals(Mouse.Captured, _host))+ {+ _host.ReleaseMouseCapture();+ }+ _source = null;+ _sourceItem = null;+ _finishing = false;+ }++ private void Perform(DropTarget target, DockGroup group, DockItem? item)+ {+ if (target.Kind == DropKind.None)+ {+ return;+ }+ bool wholeGroup = item == null || group.Items.Count == 1;+ switch (target.Kind)+ {+ case DropKind.HostEdge:+ if (wholeGroup)+ {+ _host.DockGroupToEdge(group, target.Side);+ }+ else+ {+ _host.DockToEdge(item!, target.Side);+ }+ break;+ case DropKind.NodeCenter:+ if (wholeGroup)+ {+ _host.MergeGroup(group, (DockGroup)target.Node!);+ }+ else+ {+ _host.MoveToGroup(item!, (DockGroup)target.Node!);+ }+ break;+ case DropKind.NodeSide:+ if (wholeGroup)+ {+ _host.DockGroupRelative(group, target.Node!, target.Side);+ }+ else+ {+ _host.DockRelative(item!, target.Node!, target.Side);+ }+ break;+ }+ }+}++/// <summary>What a drop would do.</summary>+internal enum DropKind+{+ None,+ /// <summary>New pane at the outer edge of the host on <see cref="DropTarget.Side"/>.</summary>+ HostEdge,+ /// <summary>Tab into the group <see cref="DropTarget.Node"/>.</summary>+ NodeCenter,+ /// <summary>New pane next to <see cref="DropTarget.Node"/>, on <see cref="DropTarget.Side"/> of it.</summary>+ NodeSide,+}++/// <summary>A resolved drop target.</summary>+internal readonly record struct DropTarget(DropKind Kind, DockSide Side, DockNode? Node);diff --git a/WaveDude.WPF/Docking/DockDropAdorner.cs b/WaveDude.WPF/Docking/DockDropAdorner.csnew file mode 100644index 0000000..9a2efd5--- /dev/null+++ b/WaveDude.WPF/Docking/DockDropAdorner.cs@@ -0,0 +1,192 @@+using System.Globalization;+using System.Windows;+using System.Windows.Documents;+using System.Windows.Media;++namespace WaveDude.WPF.Docking;++/// <summary>+/// Overlay drawn on the <see cref="DockHost"/> while a pane is dragged: four edge indicators,+/// a five-way cluster (centre plus four sides) on the hovered pane or document area, a+/// translucent preview of the drop area and a ghost label following the pointer. Brushes come+/// from the theme dictionaries.+/// </summary>+internal sealed class DockDropAdorner : Adorner+{+ private const double IndicatorSize = 32;+ private const double EdgeInset = 12;+ private const double ClusterOffset = 36;+ private const double GlyphSize = 10;+ /// <summary>Fraction of the hovered pane the preview covers for a side drop.</summary>+ private const double SidePreviewShare = 1.0 / 3.0;+ /// <summary>Fraction of the host the preview covers for an edge drop.</summary>+ private const double EdgePreviewShare = 0.25;++ private readonly DockHost _host;+ private readonly string _title;+ private readonly List<Indicator> _indicators = new();+ private Rect? _preview;+ private Point _mouse;++ public DockDropAdorner(DockHost host, string title) : base(host)+ {+ _host = host;+ _title = title;+ IsHitTestVisible = false;+ }++ /// <summary>Target under the pointer after the last <see cref="Update"/>.</summary>+ public DropTarget CurrentTarget { get; private set; }++ /// <summary>Recomputes indicators and the hit target for the given pointer position.</summary>+ public void Update(Point mouse, (DockNode Node, FrameworkElement Element)? hovered, DockGroup sourceGroup, DockItem? sourceItem)+ {+ _mouse = mouse;+ _indicators.Clear();+ _preview = null;+ CurrentTarget = default;++ double w = _host.ActualWidth;+ double h = _host.ActualHeight;+ AddIndicator(new Point(EdgeInset + IndicatorSize / 2, h / 2), new DropTarget(DropKind.HostEdge, DockSide.Left, null), DockSide.Left);+ AddIndicator(new Point(w - EdgeInset - IndicatorSize / 2, h / 2), new DropTarget(DropKind.HostEdge, DockSide.Right, null), DockSide.Right);+ AddIndicator(new Point(w / 2, EdgeInset + IndicatorSize / 2), new DropTarget(DropKind.HostEdge, DockSide.Top, null), DockSide.Top);+ AddIndicator(new Point(w / 2, h - EdgeInset - IndicatorSize / 2), new DropTarget(DropKind.HostEdge, DockSide.Bottom, null), DockSide.Bottom);++ Rect? hoveredBounds = null;+ if (hovered is { } hit)+ {+ Rect bounds = new(hit.Element.TranslatePoint(new Point(), _host), hit.Element.RenderSize);+ hoveredBounds = bounds;+ Point centre = new(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2);+ bool wholeGroup = sourceItem == null || sourceGroup.Items.Count == 1;+ bool isSource = ReferenceEquals(hit.Node, sourceGroup);++ // tabbing into a group: not into the document area, not into the group the item already sits in+ if (hit.Node is DockGroup && !isSource)+ {+ AddIndicator(centre, new DropTarget(DropKind.NodeCenter, DockSide.Left, hit.Node), null);+ }+ // splitting next to the hovered node: pointless for a whole group dropped on itself+ if (!(isSource && wholeGroup))+ {+ AddIndicator(new Point(centre.X - ClusterOffset, centre.Y), new DropTarget(DropKind.NodeSide, DockSide.Left, hit.Node), DockSide.Left);+ AddIndicator(new Point(centre.X + ClusterOffset, centre.Y), new DropTarget(DropKind.NodeSide, DockSide.Right, hit.Node), DockSide.Right);+ AddIndicator(new Point(centre.X, centre.Y - ClusterOffset), new DropTarget(DropKind.NodeSide, DockSide.Top, hit.Node), DockSide.Top);+ AddIndicator(new Point(centre.X, centre.Y + ClusterOffset), new DropTarget(DropKind.NodeSide, DockSide.Bottom, hit.Node), DockSide.Bottom);+ }+ }++ foreach (Indicator indicator in _indicators)+ {+ if (indicator.Bounds.Contains(mouse))+ {+ CurrentTarget = indicator.Target;+ _preview = PreviewRect(indicator.Target, hoveredBounds, w, h);+ break;+ }+ }+ InvalidateVisual();+ }++ private void AddIndicator(Point centre, DropTarget target, DockSide? arrow)+ {+ var bounds = new Rect(centre.X - IndicatorSize / 2, centre.Y - IndicatorSize / 2, IndicatorSize, IndicatorSize);+ _indicators.Add(new Indicator(bounds, target, arrow));+ }++ private static Rect PreviewRect(DropTarget target, Rect? hovered, double w, double h)+ {+ switch (target.Kind)+ {+ case DropKind.HostEdge:+ return SideRect(new Rect(0, 0, w, h), target.Side, EdgePreviewShare);+ case DropKind.NodeCenter:+ return hovered ?? Rect.Empty;+ case DropKind.NodeSide:+ return hovered is { } b ? SideRect(b, target.Side, SidePreviewShare) : Rect.Empty;+ default:+ return Rect.Empty;+ }+ }++ private static Rect SideRect(Rect b, DockSide side, double share) => side switch+ {+ DockSide.Left => new Rect(b.X, b.Y, b.Width * share, b.Height),+ DockSide.Right => new Rect(b.X + b.Width * (1 - share), b.Y, b.Width * share, b.Height),+ DockSide.Top => new Rect(b.X, b.Y, b.Width, b.Height * share),+ _ => new Rect(b.X, b.Y + b.Height * (1 - share), b.Width, b.Height * share),+ };++ /// <inheritdoc/>+ protected override void OnRender(DrawingContext dc)+ {+ Brush indicatorBackground = Resource("DropIndicatorBackground", Brushes.DimGray);+ Brush indicatorBorder = Resource("DropIndicatorBorder", Brushes.Gray);+ Brush glyph = Resource("DropIndicatorGlyph", Brushes.White);+ Brush hot = Resource("DropIndicatorHot", Brushes.DodgerBlue);+ Brush previewFill = Resource("DropPreviewFill", new SolidColorBrush(Color.FromArgb(0x60, 0, 0x7A, 0xCC)));+ Brush previewBorder = Resource("DropPreviewBorder", Brushes.DodgerBlue);++ if (_preview is { IsEmpty: false } preview)+ {+ dc.DrawRectangle(previewFill, new Pen(previewBorder, 2), preview);+ }++ foreach (Indicator indicator in _indicators)+ {+ bool isHot = indicator.Bounds.Contains(_mouse);+ dc.DrawRoundedRectangle(indicatorBackground, new Pen(isHot ? hot : indicatorBorder, 1), indicator.Bounds, 2, 2);+ DrawGlyph(dc, indicator, isHot ? hot : glyph);+ }++ var text = new FormattedText(_title, CultureInfo.CurrentUICulture, FlowDirection.LeftToRight,+ new Typeface("Segoe UI"), 12, glyph, VisualTreeHelper.GetDpi(this).PixelsPerDip);+ var ghost = new Rect(_mouse.X + 14, _mouse.Y + 14, text.Width + 16, text.Height + 6);+ dc.DrawRoundedRectangle(indicatorBackground, new Pen(indicatorBorder, 1), ghost, 2, 2);+ dc.DrawText(text, new Point(ghost.X + 8, ghost.Y + 3));+ }++ private static void DrawGlyph(DrawingContext dc, Indicator indicator, Brush brush)+ {+ Rect b = indicator.Bounds;+ double x = b.X + (b.Width - GlyphSize) / 2;+ double y = b.Y + (b.Height - GlyphSize) / 2;+ if (indicator.Arrow == null)+ {+ dc.DrawRectangle(null, new Pen(brush, 1.5), new Rect(x + 0.5, y + 0.5, GlyphSize - 1, GlyphSize - 1));+ return;+ }+ Point a, tip, c;+ switch (indicator.Arrow.Value)+ {+ case DockSide.Left:+ a = new Point(GlyphSize - 1, 0); tip = new Point(1, GlyphSize / 2); c = new Point(GlyphSize - 1, GlyphSize);+ break;+ case DockSide.Right:+ a = new Point(1, 0); tip = new Point(GlyphSize - 1, GlyphSize / 2); c = new Point(1, GlyphSize);+ break;+ case DockSide.Top:+ a = new Point(0, GlyphSize - 1); tip = new Point(GlyphSize / 2, 1); c = new Point(GlyphSize, GlyphSize - 1);+ break;+ default:+ a = new Point(0, 1); tip = new Point(GlyphSize / 2, GlyphSize - 1); c = new Point(GlyphSize, 1);+ break;+ }+ var geometry = new StreamGeometry();+ using (StreamGeometryContext ctx = geometry.Open())+ {+ ctx.BeginFigure(a, true, true);+ ctx.LineTo(tip, false, false);+ ctx.LineTo(c, false, false);+ }+ geometry.Freeze();+ dc.PushTransform(new TranslateTransform(x, y));+ dc.DrawGeometry(brush, null, geometry);+ dc.Pop();+ }++ private Brush Resource(string key, Brush fallback) => _host.TryFindResource(key) as Brush ?? fallback;++ private readonly record struct Indicator(Rect Bounds, DropTarget Target, DockSide? Arrow);+}diff --git a/WaveDude.WPF/Docking/DockGroup.cs b/WaveDude.WPF/Docking/DockGroup.csnew file mode 100644index 0000000..359cba6--- /dev/null+++ b/WaveDude.WPF/Docking/DockGroup.cs@@ -0,0 +1,67 @@+using System.Collections.ObjectModel;+using System.Collections.Specialized;+using System.ComponentModel;+using System.Runtime.CompilerServices;++namespace WaveDude.WPF.Docking;++/// <summary>+/// A tabbed set of <see cref="DockItem"/>s sharing one pane; a leaf of the layout tree.+/// </summary>+public sealed class DockGroup : DockNode, INotifyPropertyChanged+{+ private DockItem? _activeItem;++ public DockGroup()+ {+ Items.CollectionChanged += OnItemsChanged;+ }++ /// <summary>Items in tab order.</summary>+ public ObservableCollection<DockItem> Items { get; } = new();++ /// <summary>The item whose content is shown. Null only while the group is empty.</summary>+ public DockItem? ActiveItem+ {+ get => _activeItem;+ set+ {+ if (!ReferenceEquals(_activeItem, value) && (value == null || Items.Contains(value)))+ {+ _activeItem = value;+ OnPropertyChanged();+ }+ }+ }++ /// <inheritdoc/>+ public event PropertyChangedEventHandler? PropertyChanged;++ private void OnItemsChanged(object? sender, NotifyCollectionChangedEventArgs e)+ {+ if (e.OldItems != null)+ {+ foreach (DockItem item in e.OldItems)+ {+ if (ReferenceEquals(item.Group, this))+ {+ item.Group = null;+ }+ }+ }+ if (e.NewItems != null)+ {+ foreach (DockItem item in e.NewItems)+ {+ item.Group = this;+ }+ }+ if (_activeItem == null || !Items.Contains(_activeItem))+ {+ ActiveItem = Items.Count > 0 ? Items[^1] : null;+ }+ }++ private void OnPropertyChanged([CallerMemberName] string? name = null) =>+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));+}diff --git a/WaveDude.WPF/Docking/DockGroupControl.cs b/WaveDude.WPF/Docking/DockGroupControl.csnew file mode 100644index 0000000..4ad53d8--- /dev/null+++ b/WaveDude.WPF/Docking/DockGroupControl.cs@@ -0,0 +1,145 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Data;+using System.Windows.Input;++namespace WaveDude.WPF.Docking;++/// <summary>+/// Visual for one <see cref="DockGroup"/>: title bar with position menu and close button, the+/// active item's content, and a tab strip when the group holds more than one item. The template+/// lives in <c>Themes/Controls.xaml</c>, binds to <see cref="Group"/> through the templated+/// parent and names the parts used here; its menu items use <see cref="DockCommands"/>, which+/// this control binds. The data context is left untouched so hosted content inherits the+/// window's.+/// </summary>+public sealed class DockGroupControl : Control+{+ public static readonly DependencyProperty IsActiveProperty = DependencyProperty.Register(+ nameof(IsActive), typeof(bool), typeof(DockGroupControl), new PropertyMetadata(false));++ private Border? _titleBar;+ private ListBox? _tabs;+ private ContentPresenter? _content;+ private Button? _menuButton;++ internal DockGroupControl(DockHost host, DockGroup group)+ {+ Host = host;+ Group = group;+ Focusable = false;+ CommandBindings.Add(new CommandBinding(DockCommands.MoveToSide, OnMoveToSide, CanMoveToSide));+ CommandBindings.Add(new CommandBinding(DockCommands.Close, OnClose, CanClose));+ }++ /// <summary>Host this control was built by.</summary>+ public DockHost Host { get; }++ /// <summary>Group this control shows.</summary>+ public DockGroup Group { get; }++ /// <summary>True for the group that last received mouse or keyboard focus.</summary>+ public bool IsActive+ {+ get => (bool)GetValue(IsActiveProperty);+ set => SetValue(IsActiveProperty, value);+ }++ /// <inheritdoc/>+ public override void OnApplyTemplate()+ {+ base.OnApplyTemplate();+ if (_titleBar != null)+ {+ _titleBar.MouseLeftButtonDown -= OnTitleBarMouseDown;+ }+ if (_tabs != null)+ {+ _tabs.PreviewMouseLeftButtonDown -= OnTabMouseDown;+ }+ if (_menuButton != null)+ {+ _menuButton.Click -= OnMenuButtonClick;+ }++ _titleBar = GetTemplateChild("PART_TitleBar") as Border;+ _tabs = GetTemplateChild("PART_Tabs") as ListBox;+ _content = GetTemplateChild("PART_Content") as ContentPresenter;+ _menuButton = GetTemplateChild("PART_MenuButton") as Button;++ if (_titleBar != null)+ {+ _titleBar.MouseLeftButtonDown += OnTitleBarMouseDown;+ }+ if (_tabs != null)+ {+ _tabs.PreviewMouseLeftButtonDown += OnTabMouseDown;+ }+ if (_menuButton != null)+ {+ _menuButton.Click += OnMenuButtonClick;+ }+ }++ /// <summary>Releases the hosted content so a new control can take it after a rebuild.</summary>+ internal void Detach()+ {+ if (_content != null)+ {+ BindingOperations.ClearBinding(_content, ContentPresenter.ContentProperty);+ _content.Content = null;+ }+ }++ private void OnTitleBarMouseDown(object sender, MouseButtonEventArgs e)+ {+ Host.SetActiveGroup(this);+ Host.DragManager.Arm(this, null, e.GetPosition(Host));+ }++ private void OnTabMouseDown(object sender, MouseButtonEventArgs e)+ {+ if (_tabs == null)+ {+ return;+ }+ if (ItemsControl.ContainerFromElement(_tabs, e.OriginalSource as DependencyObject) is ListBoxItem { Content: DockItem item })+ {+ Host.DragManager.Arm(this, item, e.GetPosition(Host));+ }+ }++ /// <summary>The position menu is a context menu opened by a left click on the title bar button.</summary>+ private void OnMenuButtonClick(object sender, RoutedEventArgs e)+ {+ if (_menuButton?.ContextMenu is { } menu)+ {+ menu.PlacementTarget = _menuButton;+ menu.Placement = PlacementMode.Bottom;+ menu.IsOpen = true;+ }+ }++ private void CanMoveToSide(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = e.Parameter is DockSide && Group.ActiveItem != null;++ private void OnMoveToSide(object sender, ExecutedRoutedEventArgs e)+ {+ if (e.Parameter is DockSide side && Group.ActiveItem is { } item)+ {+ Host.DockToEdge(item, side);+ }+ }++ private void CanClose(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = Group.ActiveItem is { CanClose: true };++ private void OnClose(object sender, ExecutedRoutedEventArgs e)+ {+ if (Group.ActiveItem is { } item)+ {+ Host.Hide(item);+ }+ }+}diff --git a/WaveDude.WPF/Docking/DockHost.cs b/WaveDude.WPF/Docking/DockHost.csnew file mode 100644index 0000000..cea87c6--- /dev/null+++ b/WaveDude.WPF/Docking/DockHost.cs@@ -0,0 +1,749 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Input;+using System.Windows.Media;+using WaveDude.WPF.Commands;++namespace WaveDude.WPF.Docking;++/// <summary>+/// Docking surface. The layout is a tree (<see cref="DockNode"/>): nested+/// <see cref="DockSplitNode"/>s with splitters between their children, tabbed+/// <see cref="DockGroup"/>s as leaves, and one <see cref="DockDocumentNode"/> for the centre+/// area. Panes dock relative to any pane, to the document area, or to the outer edges, by drag+/// and drop (see <see cref="DockDragManager"/>) or through the title bar menu. The arrangement+/// round-trips through <see cref="DockLayout"/>.+/// </summary>+/// <remarks>+/// The visual tree is rebuilt from the model after every structural change. Sizes the user+/// dragged are captured back into the model first, so a rebuild never loses them. All members+/// must be used on the UI thread.+/// </remarks>+public sealed class DockHost : Grid+{+ private const double SplitterThickness = 4;+ private const double PaneMinSize = 60;+ private const double DocumentMinSize = 100;+ /// <summary>Share a pane gets when docked next to another pane.</summary>+ private const double RelativeShare = 1.0 / 3.0;+ /// <summary>Share a pane gets when docked at an outer edge.</summary>+ private const double EdgeShare = 0.25;++ private readonly Dictionary<string, DockItem> _items = new();+ private readonly Dictionary<DockNode, FrameworkElement> _elements = new();+ private readonly List<DockGroupControl> _groupControls = new();+ private readonly ContentPresenter _center = new();+ private readonly DockDocumentNode _document = new();+ private DockNode _root;+ private DockGroupControl? _activeGroup;++ public DockHost()+ {+ _root = _document;+ Items = new DockItemCollection(item =>+ {+ if (string.IsNullOrEmpty(item.Id))+ {+ throw new ArgumentException("A dock item needs an id.", nameof(item));+ }+ if (!_items.TryAdd(item.Id, item))+ {+ throw new ArgumentException($"A dock item with id '{item.Id}' is already registered.", nameof(item));+ }+ });+ DragManager = new DockDragManager(this);+ ToggleCommand = new RelayCommand<DockItem>(item =>+ {+ if (item.Group != null)+ {+ Hide(item);+ }+ else+ {+ Show(item);+ }+ });+ AddHandler(PreviewMouseDownEvent, new MouseButtonEventHandler(OnPreviewMouseDown), true);+ AddHandler(PreviewGotKeyboardFocusEvent, new KeyboardFocusChangedEventHandler(OnPreviewGotKeyboardFocus), true);+ Rebuild();+ }++ /// <summary>Content of the centre area (documents, preview).</summary>+ public object? DocumentContent+ {+ get => _center.Content;+ set => _center.Content = value;+ }++ /// <summary>+ /// All registered items in registration order, shown or hidden. Adding registers an item;+ /// XAML can fill it through <c><docking:DockHost.Items></c>.+ /// </summary>+ public DockItemCollection Items { get; }++ /// <summary>The node that marks the centre area.</summary>+ public DockDocumentNode Document => _document;++ /// <summary>Root of the layout tree.</summary>+ public DockNode Root => _root;++ /// <summary>Shows a hidden item or hides a shown one. Parameter: the <see cref="DockItem"/>.</summary>+ public ICommand ToggleCommand { get; }++ /// <summary>Raised after the arrangement changed and the visual tree was rebuilt.</summary>+ public event EventHandler? LayoutChanged;++ internal DockDragManager DragManager { get; }++ /// <summary>Makes an item known to the host without showing it; same as adding it to <see cref="Items"/>.</summary>+ /// <exception cref="ArgumentException">The item has no id, or one that is already registered.</exception>+ public void Register(DockItem item) => Items.Add(item);++ /// <summary>True when the item currently occupies a group.</summary>+ public bool IsShown(DockItem item) => item.Group != null;++ /// <summary>Shows the item: activates it where it is, or docks it at its default edge.</summary>+ public void Show(DockItem item)+ {+ EnsureRegistered(item);+ if (item.Group != null)+ {+ item.Group.ActiveItem = item;+ ActivateGroupOf(item);+ return;+ }+ DockToEdge(item, item.DefaultSide);+ }++ /// <summary>Removes the item from its group. Its content is kept and can be shown again.</summary>+ public void Hide(DockItem item)+ {+ if (item.Group == null)+ {+ return;+ }+ CaptureSizes();+ Detach(item);+ Rebuild();+ }++ /// <summary>Docks the item in a new pane at the outer edge of the host.</summary>+ public void DockToEdge(DockItem item, DockSide side)+ {+ EnsureRegistered(item);+ CaptureSizes();+ Detach(item);+ InsertRelative(NewGroup(item), _root, side, EdgeShare);+ Rebuild();+ ActivateGroupOf(item);+ }++ /// <summary>Docks the item in a new pane next to <paramref name="target"/>, on the given side of it.</summary>+ public void DockRelative(DockItem item, DockNode target, DockSide side)+ {+ EnsureRegistered(item);+ CaptureSizes();+ Detach(item);+ InsertRelative(NewGroup(item), target, side, RelativeShare);+ Rebuild();+ ActivateGroupOf(item);+ }++ /// <summary>Moves the item into <paramref name="target"/> as its active tab.</summary>+ public void MoveToGroup(DockItem item, DockGroup target)+ {+ EnsureRegistered(item);+ if (ReferenceEquals(item.Group, target))+ {+ target.ActiveItem = item;+ ActivateGroupOf(item);+ return;+ }+ CaptureSizes();+ Detach(item);+ target.Items.Add(item);+ target.ActiveItem = item;+ Rebuild();+ ActivateGroupOf(item);+ }++ /// <summary>Docks a whole group at the outer edge of the host.</summary>+ public void DockGroupToEdge(DockGroup group, DockSide side)+ {+ CaptureSizes();+ DetachGroup(group);+ InsertRelative(group, _root, side, EdgeShare);+ Rebuild();+ ActivateGroup(group);+ }++ /// <summary>Docks a whole group next to <paramref name="target"/>, on the given side of it.</summary>+ public void DockGroupRelative(DockGroup group, DockNode target, DockSide side)+ {+ if (ReferenceEquals(group, target))+ {+ return;+ }+ CaptureSizes();+ DetachGroup(group);+ InsertRelative(group, target, side, RelativeShare);+ Rebuild();+ ActivateGroup(group);+ }++ /// <summary>Moves every item of <paramref name="source"/> into <paramref name="target"/>.</summary>+ public void MergeGroup(DockGroup source, DockGroup target)+ {+ if (ReferenceEquals(source, target))+ {+ return;+ }+ CaptureSizes();+ DockItem? active = source.ActiveItem;+ DetachGroup(source);+ while (source.Items.Count > 0)+ {+ DockItem item = source.Items[0];+ source.Items.RemoveAt(0);+ target.Items.Add(item);+ }+ if (active != null)+ {+ target.ActiveItem = active;+ }+ Rebuild();+ ActivateGroup(target);+ }++ /// <summary>Captures the current arrangement, including user-dragged sizes.</summary>+ public DockLayout SaveLayout()+ {+ CaptureSizes();+ return new DockLayout { Root = Export(_root) };+ }++ /// <summary>+ /// Replaces the arrangement with <paramref name="layout"/>. Ids that are not registered are+ /// skipped and registered items the layout does not mention end up hidden. Returns false,+ /// leaving the current arrangement, when the layout has no document node.+ /// </summary>+ public bool LoadLayout(DockLayout layout)+ {+ if (layout.Root == null)+ {+ return false;+ }+ var assigned = new HashSet<DockItem>();+ DockNode? root = Import(layout.Root, assigned);+ if (root == null || !ContainsDocument(root))+ {+ return false;+ }+ foreach (DockGroup group in Groups(_root).ToList())+ {+ while (group.Items.Count > 0)+ {+ DockItem item = group.Items[^1];+ if (!assigned.Contains(item))+ {+ group.Items.RemoveAt(group.Items.Count - 1);+ }+ else+ {+ break;+ }+ }+ }+ _root = root;+ _root.Parent = null;+ NormalizeTree(_root);+ Rebuild();+ return true;+ }++ internal void SetActiveGroup(DockGroupControl? control)+ {+ if (ReferenceEquals(_activeGroup, control))+ {+ return;+ }+ if (_activeGroup != null)+ {+ _activeGroup.IsActive = false;+ }+ _activeGroup = control;+ if (control != null)+ {+ control.IsActive = true;+ }+ }++ /// <summary>Finds the group control that visually contains <paramref name="element"/>.</summary>+ internal static DockGroupControl? FindGroupControl(DependencyObject? element)+ {+ while (element != null)+ {+ if (element is DockGroupControl control)+ {+ return control;+ }+ element = ParentOf(element);+ }+ return null;+ }++ /// <summary>+ /// Resolves the pane or document area under <paramref name="element"/> and the element+ /// that renders it, for drop-target placement.+ /// </summary>+ internal (DockNode Node, FrameworkElement Element)? HitNode(DependencyObject? element)+ {+ while (element != null)+ {+ if (element is DockGroupControl control)+ {+ return (control.Group, control);+ }+ if (ReferenceEquals(element, _center))+ {+ return (_document, _center);+ }+ element = ParentOf(element);+ }+ return null;+ }++ private static DependencyObject? ParentOf(DependencyObject element) =>+ element is Visual or System.Windows.Media.Media3D.Visual3D+ ? VisualTreeHelper.GetParent(element)+ : LogicalTreeHelper.GetParent(element);++ private void EnsureRegistered(DockItem item)+ {+ if (!_items.TryGetValue(item.Id, out DockItem? known) || !ReferenceEquals(known, item))+ {+ throw new InvalidOperationException($"Dock item '{item.Id}' is not registered with this host.");+ }+ }++ // ---- tree mutation ----++ private void Detach(DockItem item)+ {+ DockGroup? group = item.Group;+ if (group == null)+ {+ return;+ }+ group.Items.Remove(item);+ if (group.Items.Count == 0)+ {+ DetachGroup(group);+ }+ }++ /// <summary>Removes the group from the tree and collapses splits left with one child.</summary>+ private void DetachGroup(DockGroup group)+ {+ DockSplitNode? parent = group.Parent;+ if (parent == null)+ {+ return;+ }+ parent.Children.Remove(group);+ Normalize(parent);+ }++ /// <summary>+ /// Inserts <paramref name="node"/> on the given side of <paramref name="target"/>, giving it+ /// <paramref name="share"/> of the space the two then occupy together.+ /// </summary>+ private void InsertRelative(DockNode node, DockNode target, DockSide side, double share)+ {+ Orientation orientation = side is DockSide.Left or DockSide.Right ? Orientation.Horizontal : Orientation.Vertical;+ bool before = side is DockSide.Left or DockSide.Top;+ DockSplitNode? parent = target.Parent;++ if (target is DockSplitNode targetSplit && targetSplit.Orientation == orientation)+ {+ // docking at the edge of a split that already runs this way: become its first or last child+ double total = targetSplit.TotalLength;+ node.Length = total * share / (1 - share);+ targetSplit.Children.Insert(before ? 0 : targetSplit.Children.Count, node);+ return;+ }++ if (parent != null && parent.Orientation == orientation)+ {+ // join the existing split; the newcomer takes its share from the target only+ double taken = target.Length * share;+ target.Length -= taken;+ node.Length = taken;+ int index = parent.Children.IndexOf(target);+ parent.Children.Insert(before ? index : index + 1, node);+ return;+ }++ var split = new DockSplitNode(orientation) { Length = target.Length };+ Replace(target, split);+ target.Length = 1 - share;+ node.Length = share;+ split.Children.Add(before ? node : target);+ split.Children.Add(before ? target : node);+ }++ private void Replace(DockNode old, DockNode replacement)+ {+ DockSplitNode? parent = old.Parent;+ if (parent == null)+ {+ _root = replacement;+ replacement.Parent = null;+ return;+ }+ int index = parent.Children.IndexOf(old);+ parent.Children[index] = replacement;+ }++ /// <summary>Collapses a split with one child and merges same-orientation nesting.</summary>+ private void Normalize(DockSplitNode split)+ {+ if (split.Children.Count == 0)+ {+ DockSplitNode? parent = split.Parent;+ if (parent != null)+ {+ parent.Children.Remove(split);+ Normalize(parent);+ }+ return;+ }+ if (split.Children.Count == 1)+ {+ DockNode only = split.Children[0];+ split.Children.RemoveAt(0);+ only.Length = split.Length;+ Replace(split, only);+ if (only is DockSplitNode inner && inner.Parent is { } outer && inner.Orientation == outer.Orientation)+ {+ Splice(inner, outer);+ }+ return;+ }+ foreach (DockNode child in split.Children.ToList())+ {+ if (child is DockSplitNode inner && inner.Orientation == split.Orientation)+ {+ Splice(inner, split);+ }+ }+ }++ /// <summary>Replaces <paramref name="inner"/> in <paramref name="outer"/> by its children, keeping proportions.</summary>+ private static void Splice(DockSplitNode inner, DockSplitNode outer)+ {+ double total = inner.TotalLength;+ double scale = total > 0 ? inner.Length / total : 1;+ int index = outer.Children.IndexOf(inner);+ outer.Children.RemoveAt(index);+ while (inner.Children.Count > 0)+ {+ DockNode child = inner.Children[^1];+ inner.Children.RemoveAt(inner.Children.Count - 1);+ child.Length *= scale;+ outer.Children.Insert(index, child);+ }+ }++ private void NormalizeTree(DockNode node)+ {+ if (node is not DockSplitNode split)+ {+ return;+ }+ foreach (DockNode child in split.Children.ToList())+ {+ NormalizeTree(child);+ }+ if (split.Parent != null || ReferenceEquals(split, _root))+ {+ Normalize(split);+ }+ }++ private static DockGroup NewGroup(DockItem item)+ {+ var group = new DockGroup();+ group.Items.Add(item);+ return group;+ }++ private static IEnumerable<DockGroup> Groups(DockNode node)+ {+ switch (node)+ {+ case DockGroup group:+ yield return group;+ break;+ case DockSplitNode split:+ foreach (DockNode child in split.Children)+ {+ foreach (DockGroup group in Groups(child))+ {+ yield return group;+ }+ }+ break;+ }+ }++ private static bool ContainsDocument(DockNode node) => node switch+ {+ DockDocumentNode => true,+ DockSplitNode split => split.Children.Any(ContainsDocument),+ _ => false,+ };++ // ---- persistence ----++ private DockLayout.NodeLayout Export(DockNode node) => node switch+ {+ DockSplitNode split => new DockLayout.SplitLayout+ {+ Length = split.Length,+ Orientation = split.Orientation,+ Children = split.Children.Select(Export).ToList(),+ },+ DockGroup group => new DockLayout.GroupLayout+ {+ Length = group.Length,+ Active = group.ActiveItem?.Id,+ Items = group.Items.Select(i => i.Id).ToList(),+ },+ _ => new DockLayout.DocumentLayout { Length = node.Length },+ };++ private DockNode? Import(DockLayout.NodeLayout layout, HashSet<DockItem> assigned)+ {+ double length = layout.Length > 0 ? layout.Length : 1;+ switch (layout)+ {+ case DockLayout.DocumentLayout:+ if (!assigned.Add(DocumentMarker))+ {+ return null; // a second document node is not allowed+ }+ _document.Length = length;+ return _document;++ case DockLayout.GroupLayout groupLayout:+ {+ var group = new DockGroup { Length = length };+ foreach (string id in groupLayout.Items)+ {+ if (_items.TryGetValue(id, out DockItem? item) && assigned.Add(item))+ {+ group.Items.Add(item);+ }+ }+ if (group.Items.Count == 0)+ {+ return null;+ }+ if (groupLayout.Active != null && _items.TryGetValue(groupLayout.Active, out DockItem? active))+ {+ group.ActiveItem = active;+ }+ return group;+ }++ case DockLayout.SplitLayout splitLayout:+ {+ var split = new DockSplitNode(splitLayout.Orientation) { Length = length };+ foreach (DockLayout.NodeLayout childLayout in splitLayout.Children)+ {+ DockNode? child = Import(childLayout, assigned);+ if (child != null)+ {+ split.Children.Add(child);+ }+ }+ return split.Children.Count switch+ {+ 0 => null,+ 1 => Unwrap(split),+ _ => split,+ };+ }++ default:+ return null;+ }+ }++ /// <summary>Placeholder entry in the "assigned" set so a layout can carry only one document node.</summary>+ private static readonly DockItem DocumentMarker = new("\0document", string.Empty, string.Empty);++ private static DockNode Unwrap(DockSplitNode split)+ {+ DockNode only = split.Children[0];+ split.Children.RemoveAt(0);+ only.Length = split.Length;+ return only;+ }++ // ---- visual tree ----++ private void ActivateGroupOf(DockItem item)+ {+ if (item.Group != null)+ {+ ActivateGroup(item.Group);+ }+ }++ private void ActivateGroup(DockGroup group) =>+ SetActiveGroup(_groupControls.FirstOrDefault(c => ReferenceEquals(c.Group, group)));++ private void CaptureSizes()+ {+ foreach ((DockNode node, FrameworkElement element) in _elements)+ {+ if (node.Parent is not { } parent)+ {+ continue;+ }+ double length = parent.Orientation == Orientation.Horizontal ? element.ActualWidth : element.ActualHeight;+ if (length > 0)+ {+ node.Length = length;+ }+ }+ }++ private void Rebuild()+ {+ foreach (DockGroupControl control in _groupControls)+ {+ control.Detach();+ }+ if (VisualTreeHelper.GetParent(_center) is Panel centerParent)+ {+ centerParent.Children.Remove(_center);+ }+ Children.Clear();+ _elements.Clear();+ _groupControls.Clear();++ Children.Add(Build(_root));++ if (_activeGroup != null && !_groupControls.Contains(_activeGroup))+ {+ DockGroup group = _activeGroup.Group;+ _activeGroup = null;+ ActivateGroup(group);+ }+ LayoutChanged?.Invoke(this, EventArgs.Empty);+ }++ private FrameworkElement Build(DockNode node)+ {+ FrameworkElement element;+ switch (node)+ {+ case DockGroup group:+ {+ var control = new DockGroupControl(this, group);+ _groupControls.Add(control);+ element = control;+ break;+ }+ case DockSplitNode split:+ element = BuildSplit(split);+ break;+ default:+ element = _center;+ break;+ }+ _elements[node] = element;+ return element;+ }++ private Grid BuildSplit(DockSplitNode split)+ {+ var grid = new Grid();+ bool columns = split.Orientation == Orientation.Horizontal;+ int slot = 0;+ for (int i = 0; i < split.Children.Count; i++)+ {+ DockNode child = split.Children[i];+ if (i > 0)+ {+ AddDefinition(grid, GridLength.Auto, 0, columns);+ AddSplitter(grid, columns ? 0 : slot, columns ? slot : 0, rows: !columns);+ slot++;+ }+ double min = ContainsDocument(child) ? DocumentMinSize : PaneMinSize;+ AddDefinition(grid, new GridLength(Math.Max(child.Length, 0.01), GridUnitType.Star), min, columns);+ FrameworkElement element = Build(child);+ SetRow(element, columns ? 0 : slot);+ SetColumn(element, columns ? slot : 0);+ grid.Children.Add(element);+ slot++;+ }+ return grid;+ }++ private static void AddDefinition(Grid grid, GridLength length, double min, bool columns)+ {+ if (columns)+ {+ grid.ColumnDefinitions.Add(new ColumnDefinition { Width = length, MinWidth = min });+ }+ else+ {+ grid.RowDefinitions.Add(new RowDefinition { Height = length, MinHeight = min });+ }+ }++ private static void AddSplitter(Grid grid, int row, int column, bool rows)+ {+ var splitter = new GridSplitter+ {+ ResizeBehavior = GridResizeBehavior.PreviousAndNext,+ ResizeDirection = rows ? GridResizeDirection.Rows : GridResizeDirection.Columns,+ HorizontalAlignment = HorizontalAlignment.Stretch,+ VerticalAlignment = VerticalAlignment.Stretch,+ Focusable = false,+ };+ if (rows)+ {+ splitter.Height = SplitterThickness;+ }+ else+ {+ splitter.Width = SplitterThickness;+ }+ SetRow(splitter, row);+ SetColumn(splitter, column);+ grid.Children.Add(splitter);+ }++ private void OnPreviewMouseDown(object sender, MouseButtonEventArgs e)+ {+ DockGroupControl? control = FindGroupControl(e.OriginalSource as DependencyObject);+ if (control != null)+ {+ SetActiveGroup(control);+ }+ }++ private void OnPreviewGotKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)+ {+ DockGroupControl? control = FindGroupControl(e.NewFocus as DependencyObject);+ if (control != null)+ {+ SetActiveGroup(control);+ }+ }+}diff --git a/WaveDude.WPF/Docking/DockItem.cs b/WaveDude.WPF/Docking/DockItem.csnew file mode 100644index 0000000..2a60387--- /dev/null+++ b/WaveDude.WPF/Docking/DockItem.cs@@ -0,0 +1,85 @@+using System.ComponentModel;+using System.Runtime.CompilerServices;+using System.Windows.Markup;++namespace WaveDude.WPF.Docking;++/// <summary>+/// One tool window: a title and a piece of content that can live in any <see cref="DockGroup"/>.+/// Declarable in XAML inside <c>DockHost.Items</c>, with the content as the element body.+/// </summary>+[ContentProperty(nameof(Content))]+public sealed class DockItem : INotifyPropertyChanged+{+ private string _title = "";+ private DockGroup? _group;++ /// <summary>Creates an item whose <see cref="Id"/>, <see cref="Title"/> and <see cref="Content"/> are set afterwards (XAML).</summary>+ public DockItem()+ {+ }++ /// <param name="id">Stable identifier used in saved layouts.</param>+ /// <param name="title">Text shown in the title bar and tab.</param>+ /// <param name="content">The WPF content hosted in the pane.</param>+ public DockItem(string id, string title, object content)+ {+ Id = id;+ _title = title;+ Content = content;+ }++ /// <summary>Stable identifier used in saved layouts; fixed once the item is registered.</summary>+ public string Id { get; set; } = "";++ /// <summary>Text shown in the title bar and tab.</summary>+ public string Title+ {+ get => _title;+ set+ {+ if (_title != value)+ {+ _title = value;+ OnPropertyChanged();+ }+ }+ }++ /// <summary>The WPF content hosted in the pane; set before the item is first shown.</summary>+ public object? Content { get; set; }++ /// <summary>Whether the pane shows a close button. Closing only hides the item.</summary>+ public bool CanClose { get; set; } = true;++ /// <summary>Edge the item is placed at when shown without a saved position.</summary>+ public DockSide DefaultSide { get; set; } = DockSide.Left;++ /// <summary>The group currently containing this item, or null while hidden.</summary>+ public DockGroup? Group+ {+ get => _group;+ internal set+ {+ if (!ReferenceEquals(_group, value))+ {+ bool wasShown = _group != null;+ _group = value;+ OnPropertyChanged();+ if (wasShown != (value != null))+ {+ OnPropertyChanged(nameof(IsShown));+ }+ }+ }+ }++ /// <summary>True while the item occupies a group.</summary>+ public bool IsShown => _group != null;++ /// <inheritdoc/>+ public event PropertyChangedEventHandler? PropertyChanged;++ private void OnPropertyChanged([CallerMemberName] string? name = null) =>+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));+}diff --git a/WaveDude.WPF/Docking/DockItemCollection.cs b/WaveDude.WPF/Docking/DockItemCollection.csnew file mode 100644index 0000000..bcb1d7d--- /dev/null+++ b/WaveDude.WPF/Docking/DockItemCollection.cs@@ -0,0 +1,36 @@+using System.Collections.ObjectModel;++namespace WaveDude.WPF.Docking;++/// <summary>+/// The registered items of a <see cref="DockHost"/>. Adding registers the item with the host;+/// items cannot be replaced or removed once registered, because saved layouts refer to them.+/// </summary>+public sealed class DockItemCollection : ObservableCollection<DockItem>+{+ private readonly Action<DockItem> _register;++ internal DockItemCollection(Action<DockItem> register)+ {+ _register = register;+ }++ /// <inheritdoc/>+ protected override void InsertItem(int index, DockItem item)+ {+ _register(item);+ base.InsertItem(index, item);+ }++ /// <inheritdoc/>+ protected override void SetItem(int index, DockItem item) =>+ throw new NotSupportedException("Dock items cannot be replaced.");++ /// <inheritdoc/>+ protected override void RemoveItem(int index) =>+ throw new NotSupportedException("Dock items cannot be unregistered.");++ /// <inheritdoc/>+ protected override void ClearItems() =>+ throw new NotSupportedException("Dock items cannot be unregistered.");+}diff --git a/WaveDude.WPF/Docking/DockLayout.cs b/WaveDude.WPF/Docking/DockLayout.csnew file mode 100644index 0000000..f88027e--- /dev/null+++ b/WaveDude.WPF/Docking/DockLayout.cs@@ -0,0 +1,87 @@+using System.IO;+using System.Windows.Controls;+using System.Xml;+using System.Xml.Serialization;+using NLog;++namespace WaveDude.WPF.Docking;++/// <summary>+/// Serializable snapshot of a <see cref="DockHost"/> layout tree. Items are referenced by+/// <see cref="DockItem.Id"/>; unknown ids are ignored on load. Persisted with+/// <see cref="XmlSerializer"/>.+/// </summary>+[XmlRoot("DockLayout")]+public sealed class DockLayout+{+ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();+ private static readonly XmlSerializer Serializer = new(typeof(DockLayout));++ /// <summary>Root of the tree: a split, a group, or the document node.</summary>+ [XmlElement("Split", typeof(SplitLayout))]+ [XmlElement("Group", typeof(GroupLayout))]+ [XmlElement("Document", typeof(DocumentLayout))]+ public NodeLayout? Root { get; set; }++ /// <summary>Writes the layout as indented XML.</summary>+ public void Save(Stream stream)+ {+ using var writer = XmlWriter.Create(stream, new XmlWriterSettings+ {+ Indent = true,+ IndentChars = "\t",+ Encoding = new System.Text.UTF8Encoding(false),+ });+ Serializer.Serialize(writer, this, new XmlSerializerNamespaces([XmlQualifiedName.Empty]));+ }++ /// <summary>Reads a layout written by <see cref="Save"/>. Returns null on malformed input.</summary>+ public static DockLayout? Load(Stream stream)+ {+ try+ {+ using var reader = XmlReader.Create(stream);+ return Serializer.Deserialize(reader) as DockLayout;+ }+ catch (InvalidOperationException ex)+ {+ Logger.Warn(ex, "The layout file does not hold a dock layout");+ return null;+ }+ catch (XmlException ex)+ {+ Logger.Warn(ex, "The layout file is not well-formed XML");+ return null;+ }+ }++ public abstract class NodeLayout+ {+ [XmlAttribute]+ public double Length { get; set; } = 1.0;+ }++ public sealed class SplitLayout : NodeLayout+ {+ [XmlAttribute]+ public Orientation Orientation { get; set; }++ [XmlElement("Split", typeof(SplitLayout))]+ [XmlElement("Group", typeof(GroupLayout))]+ [XmlElement("Document", typeof(DocumentLayout))]+ public List<NodeLayout> Children { get; set; } = new();+ }++ public sealed class GroupLayout : NodeLayout+ {+ [XmlAttribute]+ public string? Active { get; set; }++ [XmlElement("Item")]+ public List<string> Items { get; set; } = new();+ }++ public sealed class DocumentLayout : NodeLayout+ {+ }+}diff --git a/WaveDude.WPF/Docking/DockNode.cs b/WaveDude.WPF/Docking/DockNode.csnew file mode 100644index 0000000..52aea13--- /dev/null+++ b/WaveDude.WPF/Docking/DockNode.cs@@ -0,0 +1,73 @@+using System.Collections.ObjectModel;+using System.Collections.Specialized;+using System.Windows.Controls;++namespace WaveDude.WPF.Docking;++/// <summary>+/// Node of the layout tree. The tree is made of <see cref="DockSplitNode"/>s whose children+/// are further splits, tabbed <see cref="DockGroup"/>s, or the single+/// <see cref="DockDocumentNode"/> that marks the centre area.+/// </summary>+public abstract class DockNode+{+ /// <summary>The split containing this node, or null for the root.</summary>+ public DockSplitNode? Parent { get; internal set; }++ /// <summary>+ /// Share of the parent split's extent along its orientation (star weight). After the host+ /// captured sizes this holds rendered pixels; only the ratio between siblings matters.+ /// </summary>+ public double Length { get; set; } = 1.0;+}++/// <summary>+/// A node that lays its children out side by side (<see cref="Orientation.Horizontal"/>) or+/// stacked (<see cref="Orientation.Vertical"/>) with splitters between them.+/// </summary>+public sealed class DockSplitNode : DockNode+{+ public DockSplitNode(Orientation orientation)+ {+ Orientation = orientation;+ Children.CollectionChanged += OnChildrenChanged;+ }++ /// <summary>Horizontal: children are columns. Vertical: children are rows.</summary>+ public Orientation Orientation { get; }++ /// <summary>Children in visual order (left to right, or top to bottom).</summary>+ public ObservableCollection<DockNode> Children { get; } = new();++ /// <summary>Sum of the children's <see cref="DockNode.Length"/> values.</summary>+ public double TotalLength => Children.Sum(c => c.Length);++ private void OnChildrenChanged(object? sender, NotifyCollectionChangedEventArgs e)+ {+ if (e.OldItems != null)+ {+ foreach (DockNode node in e.OldItems)+ {+ if (ReferenceEquals(node.Parent, this))+ {+ node.Parent = null;+ }+ }+ }+ if (e.NewItems != null)+ {+ foreach (DockNode node in e.NewItems)+ {+ node.Parent = this;+ }+ }+ }+}++/// <summary>+/// The centre area of the host. Exactly one exists per host and it is never removed; its+/// content is <see cref="DockHost.DocumentContent"/>.+/// </summary>+public sealed class DockDocumentNode : DockNode+{+}diff --git a/WaveDude.WPF/Docking/DockSide.cs b/WaveDude.WPF/Docking/DockSide.csnew file mode 100644index 0000000..b769a82--- /dev/null+++ b/WaveDude.WPF/Docking/DockSide.cs@@ -0,0 +1,12 @@+namespace WaveDude.WPF.Docking;++/// <summary>+/// Edge of a <see cref="DockHost"/> that a tool window zone is attached to.+/// </summary>+public enum DockSide+{+ Left,+ Right,+ Top,+ Bottom,+}diff --git a/WaveDude.WPF/FileAssociation.cs b/WaveDude.WPF/FileAssociation.csnew file mode 100644index 0000000..9907c74--- /dev/null+++ b/WaveDude.WPF/FileAssociation.cs@@ -0,0 +1,144 @@+using System.IO;+using System.Runtime.InteropServices;+using System.Runtime.Versioning;+using System.Security;+using Microsoft.Win32;+using NLog;++namespace WaveDude.WPF;++/// <summary>+/// Registers the project file extension with Windows Explorer, so that a double-click on a+/// <c>.wdproj</c> file (or "Open with") starts this executable with the file as its first+/// argument; <see cref="App.OnStartup"/> hands that argument to <see cref="MainWindow.OpenFile"/>.+/// </summary>+/// <remarks>+/// Written the way the shell documents file types, a ProgId that the extension points at:+/// <code>+/// classes\.wdproj (Default) = WaveDude.Project+/// classes\WaveDude.Project (Default) = Wave Dude project (Explorer's "Type" column)+/// classes\WaveDude.Project\DefaultIcon (Default) = "exe",0 (the executable's own icon)+/// classes\WaveDude.Project\shell\open\command (Default) = "exe" "%1"+/// </code>+/// <c>classes</c> is <c>HKEY_CLASSES_ROOT</c> (all users; only an elevated process may write it)+/// and otherwise <c>HKEY_CURRENT_USER\Software\Classes</c> (this user, no elevation needed), the+/// same order as DTCODataSimulator. Entries that already point at this executable are left alone,+/// so the Explorer refresh is only triggered when something changed (first run, a build in another+/// folder). The user's own "Open with" choice for the extension is removed, since Explorer lets+/// that override the ProgId. Nothing here throws: a failure is logged and the application starts+/// without the association.+/// </remarks>+[SupportedOSPlatform("windows")]+internal static class FileAssociation+{+ /// <summary>Registry class name of a project file; the extension key points at it.</summary>+ private const string ProgId = "WaveDude.Project";++ /// <summary>What Explorer shows as the file type.</summary>+ private const string TypeDescription = "Wave Dude project";++ /// <summary><c>SHChangeNotify</c> event: the file associations changed, flush the icon and type caches.</summary>+ private const uint SHCNE_ASSOCCHANGED = 0x08000000;++ /// <summary><c>SHChangeNotify</c> flag: the item parameters are ID lists (both null here).</summary>+ private const uint SHCNF_IDLIST = 0x0000;++ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();++ /// <summary>+ /// Makes files with <paramref name="extension"/> (leading dot included) open with+ /// <paramref name="executable"/>, machine-wide when this process may write there, else for the+ /// current user. Call once at start-up; it is cheap when nothing has changed.+ /// </summary>+ public static void Register(string extension, string executable)+ {+ try+ {+ Apply(Registry.ClassesRoot, "HKEY_CLASSES_ROOT", extension, executable);+ return;+ }+ catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or IOException)+ {+ Logger.Debug("No write access to HKEY_CLASSES_ROOT ({Message}); registering {Extension} for the current user only", ex.Message, extension);+ }++ try+ {+ using RegistryKey? classes = Registry.CurrentUser.OpenSubKey(@"Software\Classes", writable: true);+ if (classes == null)+ {+ Logger.Warn("HKEY_CURRENT_USER\\Software\\Classes does not exist; {Extension} not registered", extension);+ return;+ }+ Apply(classes, @"HKEY_CURRENT_USER\Software\Classes", extension, executable);+ }+ catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or IOException)+ {+ Logger.Warn(ex, "Could not register {Extension} for the current user", extension);+ }+ }++ /// <summary>Writes the four keys under <paramref name="classes"/> unless they already hold these values.</summary>+ private static void Apply(RegistryKey classes, string classesName, string extension, string executable)+ {+ string command = $"\"{executable}\" \"%1\"";+ string icon = $"\"{executable}\",0";+ if (IsCurrent(classes, extension, command, icon))+ {+ // HKEY_CLASSES_ROOT is the merged view, so a per-user registration satisfies this check too+ Logger.Debug("{Extension} already opens with '{Executable}' (seen through {Classes})", extension, executable, classesName);+ return;+ }++ using (RegistryKey extensionKey = classes.CreateSubKey(extension))+ {+ extensionKey.SetValue("", ProgId);+ }+ using (RegistryKey progIdKey = classes.CreateSubKey(ProgId))+ {+ progIdKey.SetValue("", TypeDescription);+ using RegistryKey iconKey = progIdKey.CreateSubKey("DefaultIcon");+ iconKey.SetValue("", icon);+ using RegistryKey commandKey = progIdKey.CreateSubKey(@"shell\open\command");+ commandKey.SetValue("", command);+ }++ ClearUserChoice(extension);+ SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);+ Logger.Info("Registered {Extension} under {Classes} to open with '{Executable}'", extension, classesName, executable);+ }++ /// <summary>True when the extension, the open command and the icon already read as expected (read access only).</summary>+ private static bool IsCurrent(RegistryKey classes, string extension, string command, string icon) =>+ ReadDefault(classes, extension) == ProgId+ && ReadDefault(classes, $@"{ProgId}\shell\open\command") == command+ && ReadDefault(classes, $@"{ProgId}\DefaultIcon") == icon;++ private static string? ReadDefault(RegistryKey classes, string subKey)+ {+ using RegistryKey? key = classes.OpenSubKey(subKey);+ return key?.GetValue("") as string;+ }++ /// <summary>+ /// Removes the per-user "Open with" choice Explorer stores for the extension, which would+ /// otherwise keep winning over the ProgId. Deleting the key is allowed where changing its+ /// values is not; a refusal is logged and ignored.+ /// </summary>+ private static void ClearUserChoice(string extension)+ {+ try+ {+ using RegistryKey? fileExtension = Registry.CurrentUser.OpenSubKey(+ $@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\{extension}", writable: true);+ fileExtension?.DeleteSubKey("UserChoice", throwOnMissingSubKey: false);+ }+ catch (Exception ex) when (ex is UnauthorizedAccessException or SecurityException or IOException)+ {+ Logger.Debug("Could not clear the user's 'Open with' choice for {Extension}: {Message}", extension, ex.Message);+ }+ }++ [DllImport("shell32.dll")]+ private static extern void SHChangeNotify(uint wEventId, uint uFlags, IntPtr dwItem1, IntPtr dwItem2);+}diff --git a/WaveDude.WPF/Logging/MessagesTarget.cs b/WaveDude.WPF/Logging/MessagesTarget.csnew file mode 100644index 0000000..8eb0c1b--- /dev/null+++ b/WaveDude.WPF/Logging/MessagesTarget.cs@@ -0,0 +1,97 @@+using System.Collections.Concurrent;+using System.Collections.ObjectModel;+using System.Windows.Threading;+using NLog;+using NLog.Targets;++namespace WaveDude.WPF.Logging;++/// <summary>+/// NLog target that keeps the last <see cref="MaxCount"/> log events in memory for the+/// Messages pane. Events may arrive on any thread; they are queued and moved into+/// <see cref="Entries"/> on the UI thread in batches, so a burst of logging does not stall the+/// UI. Create it on the UI thread (it captures that dispatcher); the pane finds it by name.+/// </summary>+[Target("Messages")]+public sealed class MessagesTarget : Target+{+ private readonly ObservableCollection<LogEntry> _entries = new();+ private readonly ConcurrentQueue<LogEntry> _pending = new();+ private readonly DispatcherTimer _flush;++ public MessagesTarget()+ {+ Entries = new ReadOnlyObservableCollection<LogEntry>(_entries);+ _flush = new DispatcherTimer(DispatcherPriority.Background, Dispatcher.CurrentDispatcher)+ {+ Interval = TimeSpan.FromMilliseconds(100),+ };+ _flush.Tick += (_, _) => Flush();+ }++ /// <summary>Upper bound of kept entries; the oldest are dropped beyond it.</summary>+ public int MaxCount { get; set; } = 5000;++ /// <summary>The kept entries, oldest first. UI thread only.</summary>+ public ReadOnlyObservableCollection<LogEntry> Entries { get; }++ /// <summary>Drops every kept entry. UI thread only.</summary>+ public void Clear()+ {+ while (_pending.TryDequeue(out _))+ {+ }+ _entries.Clear();+ }++ /// <inheritdoc/>+ protected override void Write(LogEventInfo logEvent)+ {+ _pending.Enqueue(new LogEntry(logEvent.TimeStamp, logEvent.Level, logEvent.LoggerName ?? "", logEvent.FormattedMessage, logEvent.Exception?.ToString()));+ if (!_flush.IsEnabled)+ {+ _flush.Start();+ }+ }++ /// <inheritdoc/>+ protected override void CloseTarget()+ {+ _flush.Stop();+ base.CloseTarget();+ }++ private void Flush()+ {+ _flush.Stop();+ while (_pending.TryDequeue(out LogEntry? entry))+ {+ _entries.Add(entry);+ }+ while (_entries.Count > MaxCount)+ {+ _entries.RemoveAt(0);+ }+ }+}++/// <summary>One line of the Messages pane.</summary>+/// <param name="Time">When the event was logged.</param>+/// <param name="Level">Severity.</param>+/// <param name="Logger">Full logger name, usually the class.</param>+/// <param name="Message">The formatted message.</param>+/// <param name="Exception">The exception with stack trace, or null.</param>+public sealed record LogEntry(DateTime Time, LogLevel Level, string Logger, string Message, string? Exception)+{+ /// <summary>Level name as shown in the pane ("Info", "Warn", ...).</summary>+ public string LevelName => Level.Name;++ /// <summary>Logger name without its namespace.</summary>+ public string LoggerShort => Logger[(Logger.LastIndexOf('.') + 1)..];++ /// <summary>Message plus the exception text, for display and copy.</summary>+ public string FullMessage => Exception == null ? Message : $"{Message}\n{Exception}";++ /// <summary>Tab-separated line for the clipboard.</summary>+ public string ToLine() => $"{Time:HH:mm:ss.fff}\t{LevelName}\t{Logger}\t{FullMessage}";+}diff --git a/WaveDude.WPF/Logging/StatusBarTarget.cs b/WaveDude.WPF/Logging/StatusBarTarget.csnew file mode 100644index 0000000..6d02ecd--- /dev/null+++ b/WaveDude.WPF/Logging/StatusBarTarget.cs@@ -0,0 +1,156 @@+using System.ComponentModel;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Media;+using System.Windows.Threading;+using NLog;+using NLog.Common;+using NLog.Conditions;+using NLog.Config;+using NLog.Targets;++namespace WaveDude.WPF.Logging;++/// <summary>+/// NLog target that shows the latest log line in a status bar text block, so the user sees+/// what the application last did ("Opened ...", "Saved ...", errors) without a log window.+/// The text block is found by name in a window of the given type, as in the reference apps,+/// so the target can also come from an NLog configuration file. Colours are theme resource+/// keys chosen per <see cref="ColoringRules"/>; the background goes to the enclosing+/// <see cref="StatusBar"/> so the whole bar changes, Visual Studio style. Safe to call from+/// any thread: updates are posted to the dispatcher of the thread that created the target.+/// The target may be created before any window exists; it attaches to the text block on the+/// first update that finds it, so the last line logged during start-up is what the bar shows.+/// </summary>+[Target("StatusBar")]+public sealed class StatusBarTarget : TargetWithLayout+{+ private readonly Dispatcher _dispatcher = Dispatcher.CurrentDispatcher;+ private TextBlock? _text;+ private StatusBar? _bar;++ /// <summary>Type name of the window holding the text block, for example <c>MainWindow</c>.</summary>+ public string WindowName { get; set; } = "";++ /// <summary>The <c>x:Name</c> of the <see cref="TextBlock"/> that shows the message.</summary>+ public string ControlName { get; set; } = "";++ /// <summary>Resource key of the brush restored for text when no rule matches.</summary>+ [DefaultValue("StatusBarForeground")]+ public string DefaultForeground { get; set; } = "StatusBarForeground";++ /// <summary>Resource key of the brush restored for the bar when no rule matches.</summary>+ [DefaultValue("StatusBarBackground")]+ public string DefaultBackground { get; set; } = "StatusBarBackground";++ /// <summary>Colour rules, first match wins; without a match the defaults apply.</summary>+ [ArrayParameter(typeof(StatusBarColoringRule), "coloring")]+ public IList<StatusBarColoringRule> ColoringRules { get; } = new List<StatusBarColoringRule>();++ /// <inheritdoc/>+ protected override void InitializeTarget()+ {+ base.InitializeTarget();+ if (string.IsNullOrEmpty(WindowName) || string.IsNullOrEmpty(ControlName))+ {+ throw new NLogConfigurationException("StatusBarTarget needs WindowName and ControlName.");+ }+ }++ /// <inheritdoc/>+ protected override void Write(LogEventInfo logEvent)+ {+ string message = RenderLogEvent(Layout, logEvent);+ string? tooltip = logEvent.Exception?.ToString();+ StatusBarColoringRule? rule = ColoringRules.FirstOrDefault(r => r.Matches(logEvent));+ // Loaded priority: during start-up these run after the main window has been created+ _dispatcher.InvokeAsync(() => Show(message, tooltip, rule), DispatcherPriority.Loaded);+ }++ private void Show(string message, string? tooltip, StatusBarColoringRule? rule)+ {+ if (_text == null && !TryAttach())+ {+ return; // no window yet; a later message will try again+ }+ _text!.Text = message;+ _text.ToolTip = tooltip;+ _text.SetResourceReference(TextBlock.ForegroundProperty, rule?.Foreground ?? DefaultForeground);+ _bar ??= FindAncestor<StatusBar>(_text);+ if (_bar != null)+ {+ _bar.SetResourceReference(Control.BackgroundProperty, rule?.Background ?? DefaultBackground);+ }+ else+ {+ _text.SetResourceReference(TextBlock.BackgroundProperty, rule?.Background ?? DefaultBackground);+ }+ }++ /// <summary>Looks for the text block in the named window; false while there is no such window yet.</summary>+ private bool TryAttach()+ {+ if (Application.Current == null)+ {+ return false;+ }+ foreach (Window window in Application.Current.Windows)+ {+ if (window.GetType().Name.Equals(WindowName, StringComparison.OrdinalIgnoreCase)+ && window.FindName(ControlName) is TextBlock text)+ {+ _text = text;+ return true;+ }+ }+ return false;+ }++ private static T? FindAncestor<T>(DependencyObject start) where T : DependencyObject+ {+ for (DependencyObject? d = VisualTreeHelper.GetParent(start); d != null; d = VisualTreeHelper.GetParent(d))+ {+ if (d is T match)+ {+ return match;+ }+ }+ return null;+ }+}++/// <summary>+/// One colour rule of <see cref="StatusBarTarget"/>: an NLog condition such as+/// <c>level >= LogLevel.Error</c> and the theme brush keys to use when it matches.+/// </summary>+[NLogConfigurationItem]+public sealed class StatusBarColoringRule+{+ /// <summary>Creates an empty rule for configuration files.</summary>+ public StatusBarColoringRule()+ {+ }++ /// <param name="condition">NLog condition, for example <c>level == LogLevel.Warn</c>.</param>+ /// <param name="foreground">Theme brush key for the text, or null to keep the default.</param>+ /// <param name="background">Theme brush key for the bar, or null to keep the default.</param>+ public StatusBarColoringRule(string condition, string? foreground, string? background)+ {+ Condition = condition;+ Foreground = foreground;+ Background = background;+ }++ /// <summary>The condition evaluated against each log event; a string converts implicitly.</summary>+ public ConditionExpression? Condition { get; set; }++ /// <summary>Theme brush key for the text; null keeps the target's default.</summary>+ public string? Foreground { get; set; }++ /// <summary>Theme brush key for the bar; null keeps the target's default.</summary>+ public string? Background { get; set; }++ /// <summary>True when the condition holds for the event.</summary>+ public bool Matches(LogEventInfo logEvent) => Condition != null && true.Equals(Condition.Evaluate(logEvent));+}diff --git a/WaveDude.WPF/Logging/TraceLogListener.cs b/WaveDude.WPF/Logging/TraceLogListener.csnew file mode 100644index 0000000..e8ac982--- /dev/null+++ b/WaveDude.WPF/Logging/TraceLogListener.cs@@ -0,0 +1,35 @@+using System.Diagnostics;+using NLog;++namespace WaveDude.WPF.Logging;++/// <summary>+/// Forwards a <see cref="TraceSource"/> into NLog, under the source's name as logger. Used for+/// WPF's data-binding trace, which reports binding errors only this way.+/// </summary>+public sealed class TraceLogListener : TraceListener+{+ /// <inheritdoc/>+ public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string? message) =>+ LogManager.GetLogger(source).Log(ToLevel(eventType), message ?? "");++ /// <inheritdoc/>+ public override void TraceEvent(TraceEventCache? eventCache, string source, TraceEventType eventType, int id, string? format, params object?[]? args) =>+ LogManager.GetLogger(source).Log(ToLevel(eventType), format ?? "", args ?? []);++ /// <inheritdoc/>+ public override void Write(string? message) => LogManager.GetLogger(Name).Debug(message ?? "");++ /// <inheritdoc/>+ public override void WriteLine(string? message) => LogManager.GetLogger(Name).Debug(message ?? "");++ private static LogLevel ToLevel(TraceEventType type) => type switch+ {+ TraceEventType.Critical => LogLevel.Fatal,+ TraceEventType.Error => LogLevel.Error,+ TraceEventType.Warning => LogLevel.Warn,+ TraceEventType.Information => LogLevel.Info,+ TraceEventType.Verbose => LogLevel.Debug,+ _ => LogLevel.Trace,+ };+}diff --git a/WaveDude.WPF/MainWindow.Project.cs b/WaveDude.WPF/MainWindow.Project.csnew file mode 100644index 0000000..8b46c6b--- /dev/null+++ b/WaveDude.WPF/MainWindow.Project.cs@@ -0,0 +1,133 @@+using System.Collections;+using System.Windows.Input;+using WaveDude.Model;+using WaveDude.WPF.Converters;++namespace WaveDude.WPF;++/// <summary>+/// Handlers of <see cref="Commands.ProjectCommands"/>: structural edits of the open project.+/// A command parameter names the node to act on; without one the tree selection is used.+/// </summary>+public partial class MainWindow+{+ private object? Target(object? parameter) => parameter ?? SelectedItem;++ /// <summary>The project list a tree node stands for: a folder's list, or the list containing an item.</summary>+ private IList? ListOf(object? node) => node switch+ {+ NamedCollection folder when ReferenceEquals(folder.Items, Project.Sources) => Project.Sources,+ NamedCollection folder when ReferenceEquals(folder.Items, Project.Probes) => Project.Probes,+ Source => Project.Sources,+ Probe => Project.Probes,+ _ => null,+ };++ private void OnAddSource(object sender, ExecutedRoutedEventArgs e) => Added(Project.AddSource());++ private void OnAddProbe(object sender, ExecutedRoutedEventArgs e) => Added(Project.AddProbe());++ private void CanAdd(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = Target(e.Parameter) is NamedCollection folder && ListOf(folder) != null;++ private void OnAdd(object sender, ExecutedRoutedEventArgs e)+ {+ IList? list = ListOf(Target(e.Parameter) as NamedCollection);+ if (ReferenceEquals(list, Project.Sources))+ {+ Added(Project.AddSource());+ }+ else if (ReferenceEquals(list, Project.Probes))+ {+ Added(Project.AddProbe());+ }+ }++ private void CanEditItem(object sender, CanExecuteRoutedEventArgs e) =>+ e.CanExecute = Target(e.Parameter) is Source or Probe;++ private void OnDuplicate(object sender, ExecutedRoutedEventArgs e)+ {+ switch (Target(e.Parameter))+ {+ case Source source:+ Added(Project.Duplicate(source));+ break;+ case Probe probe:+ Added(Project.Duplicate(probe));+ break;+ }+ }++ private void OnRemove(object sender, ExecutedRoutedEventArgs e)+ {+ object? item = Target(e.Parameter);+ IList? list = ListOf(item);+ if (list == null)+ {+ return;+ }+ int index = list.IndexOf(item);+ switch (item)+ {+ case Source source:+ Project.Remove(source);+ break;+ case Probe probe:+ Project.Remove(probe);+ break;+ }+ // keep the user in place: the item that took the slot, else the folder+ if (list.Count > 0)+ {+ projectTree.Select(list[Math.Min(index, list.Count - 1)]!);+ }+ else+ {+ projectTree.SelectFolder(list);+ }+ }++ private void CanMoveUp(object sender, CanExecuteRoutedEventArgs e)+ {+ object? item = Target(e.Parameter);+ e.CanExecute = ListOf(item) is { } list && item is Source or Probe && list.IndexOf(item) > 0;+ }++ private void CanMoveDown(object sender, CanExecuteRoutedEventArgs e)+ {+ object? item = Target(e.Parameter);+ e.CanExecute = ListOf(item) is { } list && item is Source or Probe && list.IndexOf(item) < list.Count - 1;+ }++ private void OnMoveUp(object sender, ExecutedRoutedEventArgs e) => MoveBy(Target(e.Parameter), -1);++ private void OnMoveDown(object sender, ExecutedRoutedEventArgs e) => MoveBy(Target(e.Parameter), +1);++ private void MoveBy(object? item, int delta)+ {+ IList? list = ListOf(item);+ if (list == null)+ {+ return;+ }+ int index = list.IndexOf(item) + delta;+ bool moved = item switch+ {+ Source source => Project.Move(source, index),+ Probe probe => Project.Move(probe, index),+ _ => false,+ };+ if (moved)+ {+ projectTree.Select(item!);+ }+ }++ /// <summary>Selects a newly added item and puts the caret into its first editor (the name).</summary>+ private void Added(object item)+ {+ projectTree.Select(item);+ propertiesPane.FocusFirstEditor();+ }+}diff --git a/WaveDude.WPF/MainWindow.xaml b/WaveDude.WPF/MainWindow.xamlnew file mode 100644index 0000000..45a4c22--- /dev/null+++ b/WaveDude.WPF/MainWindow.xaml@@ -0,0 +1,165 @@+<Window x:Class="WaveDude.WPF.MainWindow"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:docking="clr-namespace:WaveDude.WPF.Docking"+ xmlns:theming="clr-namespace:WaveDude.WPF.Theming"+ xmlns:converters="clr-namespace:WaveDude.WPF.Converters"+ xmlns:panes="clr-namespace:WaveDude.WPF.Panes"+ xmlns:commands="clr-namespace:WaveDude.WPF.Commands"+ xmlns:p="clr-namespace:WaveDude.WPF.Properties"+ Icon="App.ico"+ DataContext="{Binding RelativeSource={RelativeSource Self}}"+ Width="{Binding Source={x:Static p:Settings.Default}, Path=MainWindow_Width, Mode=TwoWay}"+ Height="{Binding Source={x:Static p:Settings.Default}, Path=MainWindow_Height, Mode=TwoWay}"+ Left="{Binding Source={x:Static p:Settings.Default}, Path=MainWindow_Left, Mode=TwoWay}"+ Top="{Binding Source={x:Static p:Settings.Default}, Path=MainWindow_Top, Mode=TwoWay}"+ WindowState="{Binding Source={x:Static p:Settings.Default}, Path=MainWindow_State, Mode=TwoWay}"+ MinWidth="800" MinHeight="500"+ WindowStartupLocation="CenterScreen"+ ResizeMode="CanResizeWithGrip"+ AllowDrop="True" Drop="OnDrop">++ <Window.Resources>+ <converters:EqualityConverter x:Key="Equality" />+ <converters:TitleConverter x:Key="TitleConverter" />++ <RoutedUICommand x:Key="FileOpenRecent" />+ <RoutedUICommand x:Key="ShowMessages" Text="Show messages" />+ <RoutedUICommand x:Key="FileExit" Text="{StaticResource MenuFileExit}">+ <RoutedUICommand.InputGestures>+ <KeyGesture>Alt+F4</KeyGesture>+ </RoutedUICommand.InputGestures>+ </RoutedUICommand>++ <!-- one entry per recent file: the path as plain text (no mnemonics), click opens it -->+ <Style x:Key="RecentFileMenuItemStyle" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">+ <Setter Property="Header" Value="{Binding}" />+ <Setter Property="HeaderTemplate">+ <Setter.Value>+ <DataTemplate>+ <TextBlock Text="{Binding}" />+ </DataTemplate>+ </Setter.Value>+ </Setter>+ <Setter Property="Command" Value="{StaticResource FileOpenRecent}" />+ <Setter Property="CommandParameter" Value="{Binding}" />+ </Style>++ <!-- one entry per registered pane: check mark follows IsShown, click toggles -->+ <Style x:Key="PaneMenuItemStyle" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">+ <Setter Property="Header" Value="{Binding Title}" />+ <Setter Property="IsChecked" Value="{Binding IsShown, Mode=OneWay}" />+ <Setter Property="Command" Value="{Binding ToggleCommand, ElementName=dockHost}" />+ <Setter Property="CommandParameter" Value="{Binding}" />+ </Style>++ <!-- one entry per theme: check mark follows the current theme, click selects -->+ <Style x:Key="ThemeMenuItemStyle" TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">+ <Setter Property="Header" Value="{Binding}" />+ <Setter Property="Command" Value="{Binding SelectCommand, Source={x:Static theming:ThemeController.Instance}}" />+ <Setter Property="CommandParameter" Value="{Binding}" />+ <Setter Property="IsChecked">+ <Setter.Value>+ <MultiBinding Converter="{StaticResource Equality}" Mode="OneWay">+ <Binding Path="Current" Source="{x:Static theming:ThemeController.Instance}" />+ <Binding />+ </MultiBinding>+ </Setter.Value>+ </Setter>+ </Style>+ </Window.Resources>++ <!-- "Wave Dude - <file>", just the name while no file is open -->+ <Window.Title>+ <MultiBinding Converter="{StaticResource TitleConverter}">+ <Binding Source="{StaticResource Title}" />+ <Binding Path="Filename" />+ </MultiBinding>+ </Window.Title>++ <Window.CommandBindings>+ <CommandBinding Command="ApplicationCommands.New" Executed="OnFileNew" />+ <CommandBinding Command="ApplicationCommands.Open" Executed="OnFileOpen" />+ <CommandBinding Command="{StaticResource FileOpenRecent}" Executed="OnFileOpen" />+ <CommandBinding Command="ApplicationCommands.Save" Executed="OnFileSave" />+ <CommandBinding Command="ApplicationCommands.SaveAs" Executed="OnFileSaveAs" />+ <CommandBinding Command="ApplicationCommands.Close" CanExecute="CanFileClose" Executed="OnFileClose" />+ <CommandBinding Command="{StaticResource FileExit}" Executed="OnFileExit" />+ <CommandBinding Command="{StaticResource ShowMessages}" Executed="OnShowMessages" />++ <!-- project structure; handlers in MainWindow.Project.cs -->+ <CommandBinding Command="{x:Static commands:ProjectCommands.AddSource}" Executed="OnAddSource" />+ <CommandBinding Command="{x:Static commands:ProjectCommands.AddProbe}" Executed="OnAddProbe" />+ <CommandBinding Command="{x:Static commands:ProjectCommands.Add}" CanExecute="CanAdd" Executed="OnAdd" />+ <CommandBinding Command="{x:Static commands:ProjectCommands.Duplicate}" CanExecute="CanEditItem" Executed="OnDuplicate" />+ <CommandBinding Command="{x:Static commands:ProjectCommands.Remove}" CanExecute="CanEditItem" Executed="OnRemove" />+ <CommandBinding Command="{x:Static commands:ProjectCommands.MoveUp}" CanExecute="CanMoveUp" Executed="OnMoveUp" />+ <CommandBinding Command="{x:Static commands:ProjectCommands.MoveDown}" CanExecute="CanMoveDown" Executed="OnMoveDown" />+ </Window.CommandBindings>++ <!-- SaveAs has no default gesture -->+ <Window.InputBindings>+ <KeyBinding Command="ApplicationCommands.SaveAs" Key="S" Modifiers="Ctrl+Shift" />+ </Window.InputBindings>++ <DockPanel>++ <Menu DockPanel.Dock="Top">+ <MenuItem Header="{DynamicResource MenuFile}">+ <MenuItem Command="ApplicationCommands.New" Header="{DynamicResource MenuFileNew}" />+ <MenuItem Command="ApplicationCommands.Open" Header="{DynamicResource MenuFileOpen}" />+ <MenuItem Header="{DynamicResource MenuFileRecent}"+ ItemsSource="{Binding RecentFiles, Source={x:Static p:Settings.Default}}"+ ItemContainerStyle="{StaticResource RecentFileMenuItemStyle}" />+ <Separator />+ <MenuItem Command="ApplicationCommands.Save" Header="{DynamicResource MenuFileSave}" />+ <MenuItem Command="ApplicationCommands.SaveAs" Header="{DynamicResource MenuFileSaveAs}" InputGestureText="Ctrl+Shift+S" />+ <Separator />+ <MenuItem Command="ApplicationCommands.Close" Header="{DynamicResource MenuFileClose}" />+ <Separator />+ <MenuItem Command="{StaticResource FileExit}" Header="{DynamicResource MenuFileExit}" />+ </MenuItem>+ <MenuItem Header="{DynamicResource MenuView}">+ <MenuItem Header="{DynamicResource MenuViewPanes}"+ ItemsSource="{Binding Items, ElementName=dockHost}"+ ItemContainerStyle="{StaticResource PaneMenuItemStyle}" />+ <MenuItem Header="{DynamicResource MenuViewTheme}"+ ItemsSource="{Binding Options, Source={x:Static theming:ThemeController.Instance}}"+ ItemContainerStyle="{StaticResource ThemeMenuItemStyle}" />+ </MenuItem>+ <MenuItem Header="{DynamicResource MenuHelp}">+ <MenuItem Header="{DynamicResource MenuHelpAbout}" />+ </MenuItem>+ </Menu>++ <!-- double-click opens or focuses the Messages pane, like the log window in the reference apps -->+ <StatusBar DockPanel.Dock="Bottom" ToolTip="{DynamicResource TipStatusBar}">+ <StatusBar.InputBindings>+ <MouseBinding Gesture="LeftDoubleClick" Command="{StaticResource ShowMessages}" />+ </StatusBar.InputBindings>+ <StatusBarItem>+ <TextBlock x:Name="txtStatus" Text="{DynamicResource Ready}" />+ </StatusBarItem>+ </StatusBar>++ <docking:DockHost x:Name="dockHost">+ <docking:DockHost.Items>+ <docking:DockItem x:Name="projectDock" Id="project" Title="{StaticResource PaneProject}" DefaultSide="Left">+ <panes:ProjectTree x:Name="projectTree" Project="{Binding Project}" SelectedItemChanged="OnTreeSelectionChanged" />+ </docking:DockItem>+ <docking:DockItem x:Name="propertiesDock" Id="properties" Title="{StaticResource PaneProperties}" DefaultSide="Right">+ <panes:PropertiesPane x:Name="propertiesPane" SelectedObject="{Binding SelectedItem}" />+ </docking:DockItem>+ <docking:DockItem x:Name="messagesDock" Id="messages" Title="{StaticResource PaneMessages}" DefaultSide="Bottom">+ <panes:MessagesPane x:Name="messagesPane" TargetName="messages" />+ </docking:DockItem>+ </docking:DockHost.Items>+ <docking:DockHost.DocumentContent>+ <Border BorderThickness="1" BorderBrush="{DynamicResource ToolWindowBorder}">+ <panes:PreviewPane x:Name="previewPane" Project="{Binding Project}" />+ </Border>+ </docking:DockHost.DocumentContent>+ </docking:DockHost>++ </DockPanel>+</Window>diff --git a/WaveDude.WPF/MainWindow.xaml.cs b/WaveDude.WPF/MainWindow.xaml.csnew file mode 100644index 0000000..f157c0f--- /dev/null+++ b/WaveDude.WPF/MainWindow.xaml.cs@@ -0,0 +1,263 @@+using System.Collections.Specialized;+using System.Configuration;+using System.IO;+using System.Windows;+using System.Windows.Input;+using System.Windows.Shell;+using Microsoft.Win32;+using NLog;+using WaveDude.Model;+using WaveDude.WPF.Docking;+using WaveDude.WPF.Properties;+using WaveDude.WPF.Theming;++namespace WaveDude.WPF;++/// <summary>+/// Shell window: menu, status bar and the <see cref="DockHost"/> with the Project and+/// Properties panes around the preview. The window is its own data context: it owns the open+/// <see cref="Project"/>, its <see cref="Filename"/> and the tree's <see cref="SelectedItem"/>.+/// Window placement is bound two-way to <see cref="Settings"/> in the XAML; the pane+/// arrangement is stored there on closing.+/// </summary>+public partial class MainWindow : Window+{+ /// <summary>Extension of project files written by Save.</summary>+ public const string ProjectExtension = ".wdproj";+ private const int RecentFileCount = 10;++ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();++ /// <summary>Identifies the <see cref="Project"/> property.</summary>+ public static readonly DependencyProperty ProjectProperty = DependencyProperty.Register(+ nameof(Project), typeof(Project), typeof(MainWindow));++ /// <summary>Identifies the <see cref="Filename"/> property.</summary>+ public static readonly DependencyProperty FilenameProperty = DependencyProperty.Register(+ nameof(Filename), typeof(string), typeof(MainWindow),+ new PropertyMetadata(null, (_, _) => CommandManager.InvalidateRequerySuggested()));++ /// <summary>Identifies the <see cref="SelectedItem"/> property.</summary>+ public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register(+ nameof(SelectedItem), typeof(object), typeof(MainWindow),+ new PropertyMetadata(null, (_, _) => CommandManager.InvalidateRequerySuggested()));++ public MainWindow()+ {+ Project = new Project();+ InitializeComponent();++ if (!TryLoadLayout())+ {+ // Messages stays hidden until asked for (View > Panes, status bar double-click)+ dockHost.Show(projectDock);+ dockHost.Show(propertiesDock);+ }++ SourceInitialized += (_, _) => ThemeController.Instance.ApplyTitleBar(this);+ Closing += (_, _) => Settings.Default.Layout = dockHost.SaveLayout();+ }++ /// <summary>The open project. Never null: an empty project while nothing is loaded.</summary>+ public Project Project+ {+ get => (Project)GetValue(ProjectProperty);+ set => SetValue(ProjectProperty, value);+ }++ /// <summary>Full path the project was loaded from or saved to; null for an unsaved project.</summary>+ public string? Filename+ {+ get => (string?)GetValue(FilenameProperty);+ set => SetValue(FilenameProperty, value);+ }++ /// <summary>The model object selected in the project tree, or null.</summary>+ public object? SelectedItem+ {+ get => GetValue(SelectedItemProperty);+ set => SetValue(SelectedItemProperty, value);+ }++ /// <summary>+ /// Loads the project file at <paramref name="fileName"/> and makes it the open project.+ /// Failures are logged and shown to the user; the previous project stays open then.+ /// </summary>+ internal void OpenFile(string fileName)+ {+ try+ {+ fileName = Path.GetFullPath(fileName);+ Project = Project.Load(fileName);+ Filename = fileName;+ Logger.Info("Opened '{Path}'", fileName);+ RememberRecent(fileName);+ projectTree.SelectRoot();+ }+ catch (Exception ex)+ {+ Logger.Error(ex, "Error while opening '{Path}'", fileName);+ ShowError(string.Format((string)FindResource("OpenError"), fileName), ex);+ }+ }++ /// <summary>Writes the open project to <paramref name="fileName"/>; false when that failed.</summary>+ private bool SaveFile(string fileName)+ {+ try+ {+ fileName = Path.GetFullPath(fileName);+ Project.Save(fileName);+ Filename = fileName;+ Logger.Info("Saved '{Path}'", fileName);+ RememberRecent(fileName);+ return true;+ }+ catch (Exception ex)+ {+ Logger.Error(ex, "Error while saving '{Path}'", fileName);+ ShowError(string.Format((string)FindResource("SaveError"), fileName), ex);+ return false;+ }+ }++ /// <summary>Puts the file at the top of the recent list and of the taskbar jump list.</summary>+ private static void RememberRecent(string fileName)+ {+ JumpList.AddToRecentCategory(fileName);++ // a fresh collection so the bound menu sees the change (StringCollection does not notify)+ var recent = new StringCollection { fileName };+ foreach (string? entry in Settings.Default.RecentFiles ?? [])+ {+ if (entry != null && !string.Equals(entry, fileName, StringComparison.OrdinalIgnoreCase) && recent.Count < RecentFileCount)+ {+ recent.Add(entry);+ }+ }+ Settings.Default.RecentFiles = recent;+ SaveSettings();+ }++ private void ShowError(string message, Exception ex) =>+ MessageBox.Show(this, $"{message}\n{ex.Message}", (string)FindResource("Title"), MessageBoxButton.OK, MessageBoxImage.Error);++ private void OnFileNew(object sender, ExecutedRoutedEventArgs e)+ {+ Project = new Project();+ Filename = null;+ projectTree.SelectRoot();+ }++ private void OnFileOpen(object sender, ExecutedRoutedEventArgs e)+ {+ if (e.Parameter is string recent)+ {+ OpenFile(recent);+ return;+ }+ var dialog = new OpenFileDialog+ {+ Filter = (string)FindResource("OpenFileDialogFilter"),+ DefaultExt = ProjectExtension,+ };+ if (dialog.ShowDialog(this) == true)+ {+ OpenFile(dialog.FileName);+ }+ }++ private void OnFileSave(object sender, ExecutedRoutedEventArgs e)+ {+ if (Filename == null)+ {+ OnFileSaveAs(sender, e);+ }+ else+ {+ SaveFile(Filename);+ }+ }++ private void OnFileSaveAs(object sender, ExecutedRoutedEventArgs e)+ {+ var dialog = new SaveFileDialog+ {+ Filter = (string)FindResource("SaveFileDialogFilter"),+ DefaultExt = ProjectExtension,+ AddExtension = true,+ FileName = Filename ?? "",+ };+ if (dialog.ShowDialog(this) == true)+ {+ SaveFile(dialog.FileName);+ }+ }++ private void CanFileClose(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = Filename != null;++ private void OnFileClose(object sender, ExecutedRoutedEventArgs e)+ {+ Project = new Project();+ Filename = null;+ projectTree.SelectRoot();+ }++ private void OnFileExit(object sender, ExecutedRoutedEventArgs e) => Close();++ /// <summary>Shows the Messages pane if hidden, brings it to the front of its group, and gives it keyboard focus.</summary>+ private void OnShowMessages(object sender, ExecutedRoutedEventArgs e)+ {+ dockHost.Show(messagesDock);+ messagesPane.FocusList();+ }++ private void OnDrop(object sender, DragEventArgs e)+ {+ if (e.Data.GetData(DataFormats.FileDrop) is string[] { Length: > 0 } files)+ {+ OpenFile(files[0]);+ }+ }++ private void OnTreeSelectionChanged(object sender, RoutedPropertyChangedEventArgs<object> e) => SelectedItem = e.NewValue;++ /// <inheritdoc/>+ protected override void OnClosed(EventArgs e)+ {+ base.OnClosed(e);+ if (Settings.Default.MainWindow_State == WindowState.Minimized)+ {+ // never start minimized+ Settings.Default.MainWindow_State = WindowState.Normal;+ }+ SaveSettings();+ }++ private static void SaveSettings()+ {+ try+ {+ Settings.Default.Save();+ Logger.Debug("User settings saved");+ }+ catch (ConfigurationErrorsException ex)+ {+ // Losing window placement or the recent list is not worth interrupting the user.+ Logger.Warn(ex, "Could not save the user settings");+ }+ }++ private bool TryLoadLayout()+ {+ DockLayout? layout = Settings.Default.Layout;+ if (layout == null)+ {+ Logger.Debug("No saved layout, using the default arrangement");+ return false;+ }+ bool applied = dockHost.LoadLayout(layout);+ Logger.Debug("Saved layout {Result}", applied ? "restored" : "rejected, using the default arrangement");+ return applied;+ }+}diff --git a/WaveDude.WPF/Markup/EnumValuesExtension.cs b/WaveDude.WPF/Markup/EnumValuesExtension.csnew file mode 100644index 0000000..aebabbf--- /dev/null+++ b/WaveDude.WPF/Markup/EnumValuesExtension.cs@@ -0,0 +1,34 @@+using System.Windows.Markup;+using System.Xaml;++namespace WaveDude.WPF.Markup;++/// <summary>+/// All values of an enum, for an <c>ItemsSource</c>. The type is written with its XAML prefix,+/// for example <c>{meta:EnumValues model:SceneMode}</c>.+/// </summary>+public sealed class EnumValuesExtension : MarkupExtension+{+ /// <param name="type">The enum type with its XAML prefix.</param>+ public EnumValuesExtension(string type)+ {+ Type = type;+ }++ /// <summary>The enum type with its XAML prefix.</summary>+ [ConstructorArgument("type")]+ public string Type { get; set; }++ /// <inheritdoc/>+ public override object ProvideValue(IServiceProvider serviceProvider)+ {+ var resolver = (IXamlTypeResolver?)serviceProvider.GetService(typeof(IXamlTypeResolver))+ ?? throw new InvalidOperationException("No XAML type resolver available.");+ Type type = resolver.Resolve(Type);+ if (!type.IsEnum)+ {+ throw new System.Windows.Markup.XamlParseException($"'{Type}' is not an enum.");+ }+ return Enum.GetValues(type);+ }+}diff --git a/WaveDude.WPF/Markup/ModelMemberExtension.cs b/WaveDude.WPF/Markup/ModelMemberExtension.csnew file mode 100644index 0000000..1c3bdcb--- /dev/null+++ b/WaveDude.WPF/Markup/ModelMemberExtension.cs@@ -0,0 +1,70 @@+using System.ComponentModel;+using System.Reflection;+using System.Windows.Markup;+using System.Xaml;++namespace WaveDude.WPF.Markup;++/// <summary>+/// Base of the markup extensions that read a model property's <see cref="System.ComponentModel"/>+/// metadata, so labels and tooltips in the views come from the one place that defines them.+/// The member is written as <c>prefix:Type.Property</c>, resolved with the XAML namespaces in scope.+/// </summary>+public abstract class ModelMemberExtension : MarkupExtension+{+ /// <param name="member">Type and property, for example <c>model:Scene.Width</c>.</param>+ protected ModelMemberExtension(string member)+ {+ Member = member;+ }++ /// <summary>Type and property, for example <c>model:Scene.Width</c>.</summary>+ [ConstructorArgument("member")]+ public string Member { get; set; }++ /// <inheritdoc/>+ public override object ProvideValue(IServiceProvider serviceProvider)+ {+ int dot = Member.LastIndexOf('.');+ if (dot <= 0 || dot == Member.Length - 1)+ {+ throw new System.Windows.Markup.XamlParseException($"'{Member}' is not of the form prefix:Type.Property.");+ }+ var resolver = (IXamlTypeResolver?)serviceProvider.GetService(typeof(IXamlTypeResolver))+ ?? throw new InvalidOperationException("No XAML type resolver available.");+ Type type = resolver.Resolve(Member[..dot]);+ string name = Member[(dot + 1)..];+ PropertyInfo property = type.GetProperty(name)+ ?? throw new System.Windows.Markup.XamlParseException($"'{type.Name}' has no property '{name}'.");+ return Provide(property);+ }++ /// <summary>Produces the value for the resolved property.</summary>+ protected abstract object Provide(PropertyInfo property);+}++/// <summary>The property's <see cref="DisplayNameAttribute"/>, or its name.</summary>+public sealed class LabelExtension : ModelMemberExtension+{+ /// <inheritdoc/>+ public LabelExtension(string member) : base(member)+ {+ }++ /// <inheritdoc/>+ protected override object Provide(PropertyInfo property) =>+ property.GetCustomAttribute<DisplayNameAttribute>()?.DisplayName ?? property.Name;+}++/// <summary>The property's <see cref="DescriptionAttribute"/> text, or null without one (no tooltip).</summary>+public sealed class HintExtension : ModelMemberExtension+{+ /// <inheritdoc/>+ public HintExtension(string member) : base(member)+ {+ }++ /// <inheritdoc/>+ protected override object Provide(PropertyInfo property) =>+ property.GetCustomAttribute<DescriptionAttribute>()?.Description!;+}diff --git a/WaveDude.WPF/Panes/MessagesPane.xaml b/WaveDude.WPF/Panes/MessagesPane.xamlnew file mode 100644index 0000000..e670770--- /dev/null+++ b/WaveDude.WPF/Panes/MessagesPane.xaml@@ -0,0 +1,169 @@+<UserControl x:Class="WaveDude.WPF.Panes.MessagesPane"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:WaveDude.WPF.Panes"+ xmlns:logging="clr-namespace:WaveDude.WPF.Logging"+ DataContext="{Binding RelativeSource={RelativeSource Self}}">++ <UserControl.Resources>+ <StreamGeometry x:Key="ClearGeometry">M1,2 L9,2 M3,2 L3,9 L7,9 L7,2 M4,0 L6,0</StreamGeometry>++ <Style x:Key="ToolToggle" TargetType="{x:Type ToggleButton}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="Padding" Value="6,1" />+ <Setter Property="Margin" Value="1,0" />+ <Setter Property="MinHeight" Value="20" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ToggleButton}">+ <Border x:Name="Bd" Background="Transparent" BorderBrush="Transparent" BorderThickness="1"+ Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <ContentPresenter VerticalAlignment="Center" RecognizesAccessKey="True" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonBackground}" />+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource ButtonBorder}" />+ </Trigger>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ <Trigger Property="IsChecked" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- one toggle per level, "Level (count)", colour of the level -->+ <DataTemplate DataType="{x:Type local:LevelFilter}">+ <ToggleButton Style="{StaticResource ToolToggle}" IsChecked="{Binding IsVisible, Mode=TwoWay}"+ ToolTip="{DynamicResource TipMessagesLevel}">+ <ToggleButton.Content>+ <TextBlock>+ <Run Text="{Binding Name, Mode=OneWay}" /><Run Text=" (" /><Run Text="{Binding Count, Mode=OneWay}" /><Run Text=")" />+ </TextBlock>+ </ToggleButton.Content>+ </ToggleButton>+ </DataTemplate>+ </UserControl.Resources>++ <UserControl.CommandBindings>+ <CommandBinding Command="ApplicationCommands.Copy" CanExecute="CanCopy" Executed="OnCopy" />+ <CommandBinding Command="{x:Static local:MessagesPane.CopyAll}" CanExecute="CanCopyAll" Executed="OnCopyAll" />+ <CommandBinding Command="{x:Static local:MessagesPane.Clear}" Executed="OnClear" />+ </UserControl.CommandBindings>++ <DockPanel>+ <!-- toolbar: level filters, search, auto-scroll, clear -->+ <Border DockPanel.Dock="Top" BorderBrush="{DynamicResource ToolWindowBorder}" BorderThickness="0,0,0,1" Padding="2,2">+ <DockPanel>+ <Button DockPanel.Dock="Right" Width="18" Height="18" Margin="1,0" Focusable="False" ToolTip="{DynamicResource TipMessagesClear}"+ AutomationProperties.Name="{DynamicResource TipMessagesClear}" Command="{x:Static local:MessagesPane.Clear}">+ <Button.Template>+ <ControlTemplate TargetType="{x:Type Button}">+ <Border x:Name="Bd" Background="Transparent" SnapsToDevicePixels="True">+ <Path Data="{StaticResource ClearGeometry}" Stroke="{DynamicResource WindowForeground}" StrokeThickness="1.2"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Button.Template>+ </Button>+ <ToggleButton DockPanel.Dock="Right" Style="{StaticResource ToolToggle}" Content="{DynamicResource MessagesAutoScroll}"+ ToolTip="{DynamicResource TipMessagesAutoScroll}" IsChecked="{Binding AutoScroll, Mode=TwoWay}" />+ <CheckBox DockPanel.Dock="Right" Content="{DynamicResource MessagesRegex}" ToolTip="{DynamicResource TipMessagesRegex}"+ IsChecked="{Binding UseRegex, Mode=TwoWay}" Margin="6,0" VerticalAlignment="Center" />+ <Grid DockPanel.Dock="Right" Width="180" Margin="6,0,0,0">+ <TextBox x:Name="searchBox" Text="{Binding SearchText, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"+ AutomationProperties.Name="{DynamicResource MessagesSearchHint}" />+ <TextBlock Text="{DynamicResource MessagesSearchHint}" Margin="5,0" VerticalAlignment="Center" IsHitTestVisible="False"+ Foreground="{DynamicResource GrayText}">+ <TextBlock.Style>+ <Style TargetType="{x:Type TextBlock}">+ <Setter Property="Visibility" Value="Collapsed" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding Text, ElementName=searchBox}" Value="">+ <Setter Property="Visibility" Value="Visible" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ </TextBlock.Style>+ </TextBlock>+ </Grid>+ <ItemsControl ItemsSource="{Binding Levels}">+ <ItemsControl.ItemsPanel>+ <ItemsPanelTemplate>+ <StackPanel Orientation="Horizontal" />+ </ItemsPanelTemplate>+ </ItemsControl.ItemsPanel>+ </ItemsControl>+ </DockPanel>+ </Border>++ <ListView x:Name="list" ItemsSource="{Binding View}" SelectionMode="Extended"+ ScrollViewer.HorizontalScrollBarVisibility="Auto" VirtualizingPanel.IsVirtualizing="True">+ <ListView.ItemContainerStyle>+ <Style TargetType="{x:Type ListViewItem}" BasedOn="{StaticResource {x:Type ListViewItem}}">+ <Setter Property="ToolTip" Value="{Binding Exception}" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding LevelName}" Value="Trace">+ <Setter Property="Foreground" Value="{DynamicResource LogTrace}" />+ </DataTrigger>+ <DataTrigger Binding="{Binding LevelName}" Value="Debug">+ <Setter Property="Foreground" Value="{DynamicResource LogDebug}" />+ </DataTrigger>+ <DataTrigger Binding="{Binding LevelName}" Value="Info">+ <Setter Property="Foreground" Value="{DynamicResource LogInfo}" />+ </DataTrigger>+ <DataTrigger Binding="{Binding LevelName}" Value="Warn">+ <Setter Property="Foreground" Value="{DynamicResource LogWarn}" />+ </DataTrigger>+ <DataTrigger Binding="{Binding LevelName}" Value="Error">+ <Setter Property="Foreground" Value="{DynamicResource LogError}" />+ </DataTrigger>+ <DataTrigger Binding="{Binding LevelName}" Value="Fatal">+ <Setter Property="Foreground" Value="{DynamicResource LogFatal}" />+ <Setter Property="FontWeight" Value="Bold" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ </ListView.ItemContainerStyle>+ <ListView.ContextMenu>+ <ContextMenu>+ <MenuItem Header="{DynamicResource MessagesCopy}" Command="ApplicationCommands.Copy" InputGestureText="Ctrl+C" />+ <MenuItem Header="{DynamicResource MessagesCopyAll}" Command="{x:Static local:MessagesPane.CopyAll}" />+ <Separator />+ <MenuItem Header="{DynamicResource MessagesClear}" Command="{x:Static local:MessagesPane.Clear}" />+ </ContextMenu>+ </ListView.ContextMenu>+ <ListView.View>+ <GridView>+ <GridViewColumn Header="{DynamicResource MessagesColumnTime}" Width="90" DisplayMemberBinding="{Binding Time, StringFormat=HH:mm:ss.fff}" />+ <GridViewColumn Header="{DynamicResource MessagesColumnLevel}" Width="55" DisplayMemberBinding="{Binding LevelName}" />+ <GridViewColumn Header="{DynamicResource MessagesColumnLogger}" Width="130">+ <GridViewColumn.CellTemplate>+ <DataTemplate>+ <TextBlock Text="{Binding LoggerShort}" ToolTip="{Binding Logger}" TextTrimming="CharacterEllipsis" />+ </DataTemplate>+ </GridViewColumn.CellTemplate>+ </GridViewColumn>+ <GridViewColumn Header="{DynamicResource MessagesColumnMessage}" Width="900">+ <GridViewColumn.CellTemplate>+ <DataTemplate>+ <TextBlock Text="{Binding Message}" TextTrimming="CharacterEllipsis" />+ </DataTemplate>+ </GridViewColumn.CellTemplate>+ </GridViewColumn>+ </GridView>+ </ListView.View>+ </ListView>+ </DockPanel>+</UserControl>diff --git a/WaveDude.WPF/Panes/MessagesPane.xaml.cs b/WaveDude.WPF/Panes/MessagesPane.xaml.csnew file mode 100644index 0000000..ea68dc6--- /dev/null+++ b/WaveDude.WPF/Panes/MessagesPane.xaml.cs@@ -0,0 +1,364 @@+using System.Collections.ObjectModel;+using System.Collections.Specialized;+using System.ComponentModel;+using System.Runtime.CompilerServices;+using System.Text;+using System.Text.RegularExpressions;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Data;+using System.Windows.Input;+using NLog;+using WaveDude.WPF.Logging;++namespace WaveDude.WPF.Panes;++/// <summary>+/// The Messages pane: the entries kept by a <see cref="MessagesTarget"/>, filtered by level+/// toggles and a text or regex search, coloured per level, with auto-scroll, clear and copy.+/// The target is found by <see cref="TargetName"/> in the NLog configuration when the pane+/// loads, so the pane shows what was logged before it existed.+/// </summary>+public partial class MessagesPane : UserControl, INotifyPropertyChanged+{+ /// <summary>Copies every visible line to the clipboard.</summary>+ public static readonly RoutedUICommand CopyAll = new("Copy all", nameof(CopyAll), typeof(MessagesPane));++ /// <summary>Drops every entry from the target.</summary>+ public static readonly RoutedUICommand Clear = new("Clear", nameof(Clear), typeof(MessagesPane));++ /// <summary>Identifies the <see cref="TargetName"/> property.</summary>+ public static readonly DependencyProperty TargetNameProperty = DependencyProperty.Register(+ nameof(TargetName), typeof(string), typeof(MessagesPane), new PropertyMetadata("messages"));++ private MessagesTarget? _target;+ private string _searchText = "";+ private bool _useRegex;+ private bool _autoScroll = true;+ private Regex? _regex;++ /// <summary>Trace and Debug start visible in Debug builds only; Info and above always do.</summary>+#if DEBUG+ private const bool ShowDiagnosticsByDefault = true;+#else+ private const bool ShowDiagnosticsByDefault = false;+#endif++ public MessagesPane()+ {+ Levels = new ObservableCollection<LevelFilter>(+ new[] { LogLevel.Trace, LogLevel.Debug, LogLevel.Info, LogLevel.Warn, LogLevel.Error, LogLevel.Fatal }+ .Select(level => new LevelFilter(level, visible: ShowDiagnosticsByDefault || level >= LogLevel.Info)));+ foreach (LevelFilter level in Levels)+ {+ level.PropertyChanged += (_, args) =>+ {+ if (args.PropertyName == nameof(LevelFilter.IsVisible))+ {+ RefreshView();+ }+ };+ }+ InitializeComponent();+ Loaded += (_, _) => Attach();+ // the pane can be shown long after the target filled up: start at the newest line+ list.Loaded += (_, _) =>+ {+ if (AutoScroll)+ {+ ScrollToEnd();+ }+ };+ }++ /// <summary>Name of the <see cref="MessagesTarget"/> in the NLog configuration.</summary>+ public string TargetName+ {+ get => (string)GetValue(TargetNameProperty);+ set => SetValue(TargetNameProperty, value);+ }++ /// <summary>One filter per level, in severity order; bound to the toolbar toggles.</summary>+ public ObservableCollection<LevelFilter> Levels { get; }++ /// <summary>The filtered entries the list shows; null until attached.</summary>+ public ICollectionView? View { get; private set; }++ /// <summary>Text every shown entry must contain (message, logger or exception); a regex when <see cref="UseRegex"/>.</summary>+ public string SearchText+ {+ get => _searchText;+ set+ {+ if (Set(ref _searchText, value))+ {+ UpdateSearch();+ }+ }+ }++ /// <summary>Whether <see cref="SearchText"/> is a regular expression.</summary>+ public bool UseRegex+ {+ get => _useRegex;+ set+ {+ if (Set(ref _useRegex, value))+ {+ UpdateSearch();+ }+ }+ }++ /// <summary>Whether the list follows new entries.</summary>+ public bool AutoScroll+ {+ get => _autoScroll;+ set+ {+ if (Set(ref _autoScroll, value) && value)+ {+ ScrollToEnd();+ }+ }+ }++ /// <inheritdoc/>+ public event PropertyChangedEventHandler? PropertyChanged;++ /// <summary>Puts keyboard focus on the list (its newest line when nothing is selected) once the pane is laid out.</summary>+ public void FocusList() =>+ Dispatcher.InvokeAsync(() =>+ {+ if (list.SelectedItem == null && View != null && View.Cast<object>().LastOrDefault() is { } last)+ {+ list.SelectedItem = last;+ }+ if (list.SelectedItem != null && list.ItemContainerGenerator.ContainerFromItem(list.SelectedItem) is ListViewItem row)+ {+ row.Focus();+ }+ else+ {+ list.Focus();+ }+ }, System.Windows.Threading.DispatcherPriority.ContextIdle);++ private void Attach()+ {+ if (_target != null)+ {+ return;+ }+ _target = LogManager.Configuration?.FindTargetByName<MessagesTarget>(TargetName);+ if (_target == null)+ {+ return;+ }+ foreach (LogEntry entry in _target.Entries)+ {+ Count(entry, +1);+ }+ ((INotifyCollectionChanged)_target.Entries).CollectionChanged += OnEntriesChanged;+ View = CollectionViewSource.GetDefaultView(_target.Entries);+ View.Filter = Passes;+ OnPropertyChanged(nameof(View));+ ScrollToEnd();+ }++ private void OnEntriesChanged(object? sender, NotifyCollectionChangedEventArgs e)+ {+ switch (e.Action)+ {+ case NotifyCollectionChangedAction.Add:+ foreach (LogEntry entry in e.NewItems!)+ {+ Count(entry, +1);+ }+ if (AutoScroll)+ {+ ScrollToEnd();+ }+ break;+ case NotifyCollectionChangedAction.Remove:+ foreach (LogEntry entry in e.OldItems!)+ {+ Count(entry, -1);+ }+ break;+ case NotifyCollectionChangedAction.Reset:+ foreach (LevelFilter level in Levels)+ {+ level.Count = 0;+ }+ break;+ }+ }++ private void Count(LogEntry entry, int delta)+ {+ LevelFilter? level = Levels.FirstOrDefault(l => l.Level == entry.Level);+ if (level != null)+ {+ level.Count += delta;+ }+ }++ private bool Passes(object item)+ {+ if (item is not LogEntry entry)+ {+ return false;+ }+ if (Levels.FirstOrDefault(l => l.Level == entry.Level) is { IsVisible: false })+ {+ return false;+ }+ if (_regex != null)+ {+ return _regex.IsMatch(entry.FullMessage) || _regex.IsMatch(entry.Logger);+ }+ return SearchText.Length == 0+ || entry.FullMessage.Contains(SearchText, StringComparison.OrdinalIgnoreCase)+ || entry.Logger.Contains(SearchText, StringComparison.OrdinalIgnoreCase);+ }++ private void UpdateSearch()+ {+ _regex = null;+ if (UseRegex && SearchText.Length > 0)+ {+ try+ {+ _regex = new Regex(SearchText, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);+ }+ catch (ArgumentException)+ {+ // an unfinished pattern while typing: show everything until it parses+ }+ }+ RefreshView();+ }++ /// <summary>Re-applies the filter; a refresh resets the scroll position, so follow the end again when asked to.</summary>+ private void RefreshView()+ {+ View?.Refresh();+ if (AutoScroll)+ {+ ScrollToEnd();+ }+ }++ private void ScrollToEnd()+ {+ if (View == null)+ {+ return;+ }+ Dispatcher.InvokeAsync(() =>+ {+ object? last = View.Cast<object>().LastOrDefault();+ if (last != null)+ {+ list.ScrollIntoView(last);+ }+ }, System.Windows.Threading.DispatcherPriority.ContextIdle);+ }++ private void CanCopy(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = list.SelectedItems.Count > 0;++ private void OnCopy(object sender, ExecutedRoutedEventArgs e) =>+ CopyLines(list.SelectedItems.Cast<LogEntry>().OrderBy(entry => entry.Time));++ private void CanCopyAll(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = View != null && !View.IsEmpty;++ private void OnCopyAll(object sender, ExecutedRoutedEventArgs e)+ {+ if (View != null)+ {+ CopyLines(View.Cast<LogEntry>());+ }+ }++ private static void CopyLines(IEnumerable<LogEntry> entries)+ {+ var text = new StringBuilder();+ foreach (LogEntry entry in entries)+ {+ text.AppendLine(entry.ToLine());+ }+ Clipboard.SetText(text.ToString());+ }++ private void OnClear(object sender, ExecutedRoutedEventArgs e) => _target?.Clear();++ private bool Set<T>(ref T field, T value, [CallerMemberName] string? name = null)+ {+ if (EqualityComparer<T>.Default.Equals(field, value))+ {+ return false;+ }+ field = value;+ OnPropertyChanged(name);+ return true;+ }++ private void OnPropertyChanged([CallerMemberName] string? name = null) =>+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));+}++/// <summary>Visibility toggle and entry count of one log level in the Messages pane.</summary>+public sealed class LevelFilter : INotifyPropertyChanged+{+ private bool _isVisible;+ private int _count;++ /// <param name="level">The level this filter stands for.</param>+ /// <param name="visible">Initial state of the toggle.</param>+ public LevelFilter(LogLevel level, bool visible)+ {+ Level = level;+ _isVisible = visible;+ }++ /// <summary>The level this filter stands for.</summary>+ public LogLevel Level { get; }++ /// <summary>Level name for the toggle caption.</summary>+ public string Name => Level.Name;++ /// <summary>Whether entries of this level are shown.</summary>+ public bool IsVisible+ {+ get => _isVisible;+ set+ {+ if (_isVisible != value)+ {+ _isVisible = value;+ OnPropertyChanged();+ }+ }+ }++ /// <summary>Number of kept entries of this level, shown or not.</summary>+ public int Count+ {+ get => _count;+ set+ {+ if (_count != value)+ {+ _count = value;+ OnPropertyChanged();+ }+ }+ }++ /// <inheritdoc/>+ public event PropertyChangedEventHandler? PropertyChanged;++ private void OnPropertyChanged([CallerMemberName] string? name = null) =>+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));+}diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml b/WaveDude.WPF/Panes/PreviewPane.xamlnew file mode 100644index 0000000..b5a8a50--- /dev/null+++ b/WaveDude.WPF/Panes/PreviewPane.xaml@@ -0,0 +1,241 @@+<UserControl x:Class="WaveDude.WPF.Panes.PreviewPane" x:Name="pane"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:WaveDude.WPF.Panes"+ xmlns:converters="clr-namespace:WaveDude.WPF.Converters"+ Background="{DynamicResource DocumentBackground}" Focusable="True" IsTabStop="False">++ <UserControl.Resources>+ <converters:EnumBooleanConverter x:Key="EnumBoolean" />+ <converters:DoubleTextConverter x:Key="DoubleText" />++ <StreamGeometry x:Key="PlayGeometry">M0,0 L9,5 L0,10 Z</StreamGeometry>+ <StreamGeometry x:Key="PauseGeometry">M0,0 L3,0 L3,10 L0,10 Z M6,0 L9,0 L9,10 L6,10 Z</StreamGeometry>+ <StreamGeometry x:Key="SideBySideGeometry">M0,0 L5,0 L5,10 L0,10 Z M7,0 L12,0 L12,10 L7,10 Z</StreamGeometry>+ <StreamGeometry x:Key="StackedGeometry">M0,0 L12,0 L12,4 L0,4 Z M0,6 L12,6 L12,10 L0,10 Z</StreamGeometry>++ <!-- filled-glyph transport button; Content is the geometry. A tab stop: keyboard focus shows as an accent border -->+ <Style x:Key="TransportButton" TargetType="{x:Type Button}">+ <Setter Property="Width" Value="22" />+ <Setter Property="Height" Value="22" />+ <Setter Property="Margin" Value="1,0" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Button}">+ <Border x:Name="Bd" Background="Transparent" BorderBrush="Transparent" BorderThickness="1" SnapsToDevicePixels="True">+ <Path Data="{TemplateBinding Content}" Fill="{TemplateBinding Foreground}"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonPressed}" />+ <Setter Property="Foreground" Value="White" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ <Setter Property="Opacity" Value="0.5" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- glyph radio button for a choice shown as a row of buttons; the chosen one stays pressed.+ The group is one tab stop; Left/Right move within it (see the StackPanel below) -->+ <Style x:Key="TransportRadio" TargetType="{x:Type RadioButton}">+ <Setter Property="Width" Value="22" />+ <Setter Property="Height" Value="22" />+ <Setter Property="Margin" Value="1,0" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type RadioButton}">+ <Border x:Name="Bd" Background="Transparent" BorderBrush="Transparent" BorderThickness="1" SnapsToDevicePixels="True">+ <Path Data="{TemplateBinding Content}" Fill="{TemplateBinding Foreground}"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonPressed}" />+ <Setter Property="Foreground" Value="White" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ </UserControl.Resources>++ <UserControl.CommandBindings>+ <CommandBinding Command="MediaCommands.Play" CanExecute="CanPlay" Executed="OnPlay" />+ <CommandBinding Command="MediaCommands.Pause" CanExecute="CanPause" Executed="OnPause" />+ <CommandBinding Command="MediaCommands.TogglePlayPause" CanExecute="CanTogglePlayPause" Executed="OnTogglePlayPause" />+ </UserControl.CommandBindings>+ <UserControl.InputBindings>+ <KeyBinding Key="Space" Command="MediaCommands.TogglePlayPause" />+ </UserControl.InputBindings>++ <DockPanel>++ <!-- transport bar: play, pause, scrubber, frame readout, speed, split.+ Tab order (TabIndex) is left to right: play, pause, scrubber, speed, split; the DockPanel+ declares the right-docked items first, so it cannot be the declaration order. -->+ <Border DockPanel.Dock="Bottom" BorderBrush="{DynamicResource ToolWindowBorder}" BorderThickness="0,1,0,0" Padding="4,3">+ <DockPanel KeyboardNavigation.TabNavigation="Local">+ <Button x:Name="playButton" DockPanel.Dock="Left" TabIndex="1" Style="{StaticResource TransportButton}" Content="{StaticResource PlayGeometry}"+ Command="MediaCommands.Play" ToolTip="{DynamicResource TipPreviewPlay}"+ AutomationProperties.Name="{DynamicResource TipPreviewPlay}" AutomationProperties.AutomationId="PreviewPlay" />+ <Button x:Name="pauseButton" DockPanel.Dock="Left" TabIndex="2" Style="{StaticResource TransportButton}" Content="{StaticResource PauseGeometry}"+ Command="MediaCommands.Pause" ToolTip="{DynamicResource TipPreviewPause}"+ AutomationProperties.Name="{DynamicResource TipPreviewPause}" AutomationProperties.AutomationId="PreviewPause" />+ <Rectangle DockPanel.Dock="Left" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />++ <!-- right-docked items: the first declared is the rightmost -->+ <!-- one tab stop, the checked radio (IsTabStop follows IsChecked); the arrow keys move to the+ neighbour and check it, in code, since WPF's directional navigation skips non-tab-stops -->+ <StackPanel x:Name="splitGroup" DockPanel.Dock="Right" Orientation="Horizontal" KeyboardNavigation.TabIndex="5"+ KeyDown="OnSplitGroupKeyDown">+ <RadioButton Style="{StaticResource TransportRadio}" Content="{StaticResource SideBySideGeometry}" GroupName="Split"+ ToolTip="{DynamicResource TipPreviewSideBySide}"+ AutomationProperties.Name="{DynamicResource TipPreviewSideBySide}" AutomationProperties.AutomationId="PreviewSideBySide"+ IsChecked="{Binding Orientation, ElementName=pane, Converter={StaticResource EnumBoolean}, ConverterParameter={x:Static Orientation.Horizontal}}"+ IsTabStop="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay}" />+ <RadioButton Style="{StaticResource TransportRadio}" Content="{StaticResource StackedGeometry}" GroupName="Split"+ ToolTip="{DynamicResource TipPreviewStacked}"+ AutomationProperties.Name="{DynamicResource TipPreviewStacked}" AutomationProperties.AutomationId="PreviewStacked"+ IsChecked="{Binding Orientation, ElementName=pane, Converter={StaticResource EnumBoolean}, ConverterParameter={x:Static Orientation.Vertical}}"+ IsTabStop="{Binding IsChecked, RelativeSource={RelativeSource Self}, Mode=OneWay}" />+ </StackPanel>+ <Rectangle DockPanel.Dock="Right" Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />+ <ComboBox x:Name="speedBox" DockPanel.Dock="Right" TabIndex="4" Width="64" IsEditable="True" ItemsSource="{x:Static local:PreviewPane.SpeedPresets}"+ Text="{Binding Speed, ElementName=pane, Mode=TwoWay, Converter={StaticResource DoubleText}}" ToolTip="{DynamicResource TipPreviewSpeed}"+ AutomationProperties.Name="{DynamicResource LabelPreviewSpeed}" AutomationProperties.AutomationId="PreviewSpeed"+ PreviewKeyDown="OnSpeedBoxPreviewKeyDown" />+ <TextBlock DockPanel.Dock="Right" Style="{StaticResource FormLabel}" Margin="8,0,4,0" Text="{DynamicResource LabelPreviewSpeed}" />+ <TextBlock DockPanel.Dock="Right" Style="{StaticResource FormValue}" MinWidth="90" TextAlignment="Right" ToolTip="{DynamicResource TipPreviewFrame}"+ AutomationProperties.AutomationId="PreviewFrame">+ <TextBlock.Text>+ <MultiBinding StringFormat="{}{0} / {1}">+ <Binding Path="Position" ElementName="pane" />+ <Binding Path="LastFrame" ElementName="pane" />+ </MultiBinding>+ </TextBlock.Text>+ </TextBlock>++ <!-- the scrubber takes what is left; Left/Right step a frame, PageUp/PageDown ten, Home/End to the ends -->+ <Slider TabIndex="3" Margin="4,0" Minimum="0" Maximum="{Binding LastFrame, ElementName=pane}" Value="{Binding Position, ElementName=pane}"+ SmallChange="1" LargeChange="10" ToolTip="{DynamicResource TipPreviewScrub}"+ AutomationProperties.Name="{DynamicResource TipPreviewScrub}" AutomationProperties.AutomationId="PreviewScrub" />+ </DockPanel>+ </Border>++ <!-- the two pictures, side by side (columns 0 and 2) or stacked (rows 0 and 2), with a splitter in+ the middle definition. The unused dimension is bridged by spanning all three of its+ definitions, so a drag in one orientation survives a switch to the other. Each picture is+ centred in its cell. A click here focuses the pane so that Space works. -->+ <Grid x:Name="pictures" Margin="4" Background="Transparent" MouseDown="OnPicturesMouseDown">+ <Grid.Resources>+ <!-- a picture with its section header; Content is the ImageSource, Tag the automation id of the image -->+ <Style x:Key="PictureCell" TargetType="{x:Type HeaderedContentControl}">+ <Setter Property="HorizontalAlignment" Value="Center" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="Margin" Value="4" />+ <Setter Property="Grid.RowSpan" Value="3" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type HeaderedContentControl}">+ <DockPanel>+ <TextBlock DockPanel.Dock="Top" Style="{StaticResource FormSection}" Margin="0,0,0,4" Text="{TemplateBinding Header}" />+ <Image Source="{TemplateBinding Content}" Stretch="Uniform" AutomationProperties.AutomationId="{TemplateBinding Tag}" />+ </DockPanel>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ <Style.Triggers>+ <DataTrigger Binding="{Binding Orientation, ElementName=pane}" Value="{x:Static Orientation.Vertical}">+ <Setter Property="Grid.RowSpan" Value="1" />+ <Setter Property="Grid.ColumnSpan" Value="3" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="SecondPictureCell" TargetType="{x:Type HeaderedContentControl}" BasedOn="{StaticResource PictureCell}">+ <Setter Property="Grid.Column" Value="2" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding Orientation, ElementName=pane}" Value="{x:Static Orientation.Vertical}">+ <Setter Property="Grid.RowSpan" Value="1" />+ <Setter Property="Grid.ColumnSpan" Value="3" />+ <Setter Property="Grid.Column" Value="0" />+ <Setter Property="Grid.Row" Value="2" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <!-- the splitter: a tab stop, arrows move it, Enter or a double-click puts it back in the middle -->+ <Style x:Key="PictureSplitter" TargetType="{x:Type GridSplitter}" BasedOn="{StaticResource {x:Type GridSplitter}}">+ <Setter Property="Grid.Column" Value="1" />+ <Setter Property="Grid.RowSpan" Value="3" />+ <Setter Property="Width" Value="4" />+ <Setter Property="HorizontalAlignment" Value="Center" />+ <Setter Property="VerticalAlignment" Value="Stretch" />+ <Setter Property="ResizeDirection" Value="Columns" />+ <Setter Property="ResizeBehavior" Value="PreviousAndNext" />+ <Setter Property="KeyboardIncrement" Value="10" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding Orientation, ElementName=pane}" Value="{x:Static Orientation.Vertical}">+ <Setter Property="Grid.Column" Value="0" />+ <Setter Property="Grid.Row" Value="1" />+ <Setter Property="Grid.RowSpan" Value="1" />+ <Setter Property="Grid.ColumnSpan" Value="3" />+ <Setter Property="Width" Value="Auto" />+ <Setter Property="Height" Value="4" />+ <Setter Property="HorizontalAlignment" Value="Stretch" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="ResizeDirection" Value="Rows" />+ </DataTrigger>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True">+ <Setter Property="Background" Value="{DynamicResource Accent}" />+ </Trigger>+ </Style.Triggers>+ </Style>+ </Grid.Resources>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" />+ <ColumnDefinition Width="*" />+ </Grid.ColumnDefinitions>+ <Grid.RowDefinitions>+ <RowDefinition Height="*" />+ <RowDefinition Height="Auto" />+ <RowDefinition Height="*" />+ </Grid.RowDefinitions>+ <HeaderedContentControl Style="{StaticResource PictureCell}" Header="{DynamicResource SectionField}"+ Content="{Binding FieldImage, ElementName=pane}" Tag="PreviewFieldImage" />+ <GridSplitter Style="{StaticResource PictureSplitter}" ToolTip="{DynamicResource TipPreviewSplitter}"+ AutomationProperties.Name="{DynamicResource TipPreviewSplitter}" AutomationProperties.AutomationId="PreviewSplitter"+ MouseDoubleClick="OnSplitterMouseDoubleClick" KeyDown="OnSplitterKeyDown" />+ <HeaderedContentControl Style="{StaticResource SecondPictureCell}" Header="{DynamicResource SectionIntensity}"+ Content="{Binding IntensityImage, ElementName=pane}" Tag="PreviewIntensityImage" />+ </Grid>++ </DockPanel>+</UserControl>diff --git a/WaveDude.WPF/Panes/PreviewPane.xaml.cs b/WaveDude.WPF/Panes/PreviewPane.xaml.csnew file mode 100644index 0000000..ea87226--- /dev/null+++ b/WaveDude.WPF/Panes/PreviewPane.xaml.cs@@ -0,0 +1,376 @@+using System.Diagnostics;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Controls.Primitives;+using System.Windows.Data;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Media.Imaging;+using System.Windows.Threading;+using WaveDude.Model;+using WaveDude.WPF.Converters;++namespace WaveDude.WPF.Panes;++/// <summary>+/// The document in the centre: the field and the intensity picture, side by side or stacked,+/// with a transport bar to scrub, play and pause through the frames of a run at a chosen+/// speed. Dummy stage: the pictures are fixed placeholders and playing only advances+/// <see cref="Position"/>; the render pipeline that will feed <see cref="FieldImage"/> and+/// <see cref="IntensityImage"/> per frame does not exist yet. <see cref="FrameCount"/> follows+/// the project's step count and visualisation interval through a binding.+/// </summary>+/// <remarks>+/// Playback runs on a <see cref="DispatcherTimer"/> on the UI thread: a speed of 1 advances+/// <see cref="BaseFrameRate"/> frames per second of wall-clock time, measured with a stopwatch+/// so that a slow tick does not slow the clock. Playing at the last frame restarts at 0.+/// Play, Pause and Space (toggle) are the built-in <see cref="MediaCommands"/>.+/// Keyboard: every transport control is a tab stop (play, pause, scrubber, speed, split, and+/// the splitter between the pictures). The split radios are one stop that lands on the checked+/// one; Left/Right there check the other. Arrows move the splitter; Enter (or a double-click)+/// resets it to the middle. Space toggles playback from anywhere in the pane except the speed+/// text box, and a click on the pictures focuses the pane so Space works after it. Executing+/// Play or Pause from the keyboard moves focus to the other button, because the one just used+/// is about to be disabled.+/// </remarks>+public partial class PreviewPane : UserControl+{+ /// <summary>Frames per second that a playback <see cref="Speed"/> of 1 corresponds to; a placeholder until the pipeline defines the frame clock.</summary>+ public const double BaseFrameRate = 30.0;++ /// <summary>Smallest accepted <see cref="Speed"/>.</summary>+ public const double MinSpeed = 0.01;++ /// <summary>Largest accepted <see cref="Speed"/>.</summary>+ public const double MaxSpeed = 100.0;++ /// <summary>Speed factors offered in the drop-down; any other value can be typed.</summary>+ public static IReadOnlyList<double> SpeedPresets { get; } = [0.25, 0.5, 1.0, 1.5, 2.0, 4.0];++ private static readonly BitmapSource PlaceholderField = CreatePlaceholder(intensity: false);+ private static readonly BitmapSource PlaceholderIntensity = CreatePlaceholder(intensity: true);++ /// <summary>Identifies the <see cref="Project"/> property.</summary>+ public static readonly DependencyProperty ProjectProperty = DependencyProperty.Register(+ nameof(Project), typeof(Project), typeof(PreviewPane));++ /// <summary>Identifies the <see cref="FrameCount"/> property.</summary>+ public static readonly DependencyProperty FrameCountProperty = DependencyProperty.Register(+ nameof(FrameCount), typeof(int), typeof(PreviewPane),+ new PropertyMetadata(1, OnFrameCountChanged, (_, value) => Math.Max(1, (int)value)));++ private static readonly DependencyPropertyKey LastFrameKey = DependencyProperty.RegisterReadOnly(+ nameof(LastFrame), typeof(int), typeof(PreviewPane), new PropertyMetadata(0));++ /// <summary>Identifies the <see cref="LastFrame"/> property.</summary>+ public static readonly DependencyProperty LastFrameProperty = LastFrameKey.DependencyProperty;++ /// <summary>Identifies the <see cref="Position"/> property.</summary>+ public static readonly DependencyProperty PositionProperty = DependencyProperty.Register(+ nameof(Position), typeof(int), typeof(PreviewPane),+ new FrameworkPropertyMetadata(0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoercePosition));++ /// <summary>Identifies the <see cref="IsPlaying"/> property.</summary>+ public static readonly DependencyProperty IsPlayingProperty = DependencyProperty.Register(+ nameof(IsPlaying), typeof(bool), typeof(PreviewPane), new PropertyMetadata(false, OnIsPlayingChanged));++ /// <summary>Identifies the <see cref="Speed"/> property.</summary>+ public static readonly DependencyProperty SpeedProperty = DependencyProperty.Register(+ nameof(Speed), typeof(double), typeof(PreviewPane),+ new FrameworkPropertyMetadata(1.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, null, CoerceSpeed));++ /// <summary>Identifies the <see cref="Orientation"/> property.</summary>+ public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register(+ nameof(Orientation), typeof(Orientation), typeof(PreviewPane),+ new FrameworkPropertyMetadata(Orientation.Horizontal, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));++ /// <summary>Identifies the <see cref="FieldImage"/> property.</summary>+ public static readonly DependencyProperty FieldImageProperty = DependencyProperty.Register(+ nameof(FieldImage), typeof(ImageSource), typeof(PreviewPane), new PropertyMetadata(PlaceholderField));++ /// <summary>Identifies the <see cref="IntensityImage"/> property.</summary>+ public static readonly DependencyProperty IntensityImageProperty = DependencyProperty.Register(+ nameof(IntensityImage), typeof(ImageSource), typeof(PreviewPane), new PropertyMetadata(PlaceholderIntensity));++ private readonly DispatcherTimer _timer;+ private readonly Stopwatch _clock = new();++ /// <summary>Fractional frame advance carried from one tick to the next, so slow speeds still move.</summary>+ private double _carry;++ public PreviewPane()+ {+ InitializeComponent();++ // frames = ceil(steps / visualize every); re-evaluated whenever the project or its settings change+ SetBinding(FrameCountProperty, new MultiBinding+ {+ Converter = new FrameCountConverter(),+ Bindings =+ {+ new Binding($"{nameof(Project)}.{nameof(Model.Project.Simulation)}.{nameof(Simulation.Steps)}") { Source = this },+ new Binding($"{nameof(Project)}.{nameof(Model.Project.Simulation)}.{nameof(Simulation.VisualizeEvery)}") { Source = this },+ },+ });++ _timer = new DispatcherTimer(DispatcherPriority.Render) { Interval = TimeSpan.FromSeconds(1.0 / 60.0) };+ _timer.Tick += OnTick;+ Unloaded += (_, _) => IsPlaying = false;+ }++ /// <summary>The project whose run is shown; null shows the placeholders with a single frame.</summary>+ public Project? Project+ {+ get => (Project?)GetValue(ProjectProperty);+ set => SetValue(ProjectProperty, value);+ }++ /// <summary>Number of frames in the run, at least 1. Bound to the project's steps and visualisation interval.</summary>+ public int FrameCount+ {+ get => (int)GetValue(FrameCountProperty);+ set => SetValue(FrameCountProperty, value);+ }++ /// <summary>Index of the last frame, <see cref="FrameCount"/> - 1; the scrubber's maximum.</summary>+ public int LastFrame+ {+ get => (int)GetValue(LastFrameProperty);+ private set => SetValue(LastFrameKey, value);+ }++ /// <summary>Frame shown, 0 to <see cref="LastFrame"/>. Moved by the scrubber and by playback.</summary>+ public int Position+ {+ get => (int)GetValue(PositionProperty);+ set => SetValue(PositionProperty, value);+ }++ /// <summary>Whether playback is running. Setting it starts or stops the frame clock.</summary>+ public bool IsPlaying+ {+ get => (bool)GetValue(IsPlayingProperty);+ set => SetValue(IsPlayingProperty, value);+ }++ /// <summary>Playback speed factor, <see cref="MinSpeed"/> to <see cref="MaxSpeed"/>; 1 is <see cref="BaseFrameRate"/> frames per second.</summary>+ public double Speed+ {+ get => (double)GetValue(SpeedProperty);+ set => SetValue(SpeedProperty, value);+ }++ /// <summary>How the two pictures are split: <see cref="Orientation.Horizontal"/> side by side, <see cref="Orientation.Vertical"/> field above intensity.</summary>+ public Orientation Orientation+ {+ get => (Orientation)GetValue(OrientationProperty);+ set => SetValue(OrientationProperty, value);+ }++ /// <summary>Picture of the field at <see cref="Position"/>; a placeholder until the render pipeline sets it.</summary>+ public ImageSource? FieldImage+ {+ get => (ImageSource?)GetValue(FieldImageProperty);+ set => SetValue(FieldImageProperty, value);+ }++ /// <summary>Picture of the intensity at <see cref="Position"/>; a placeholder until the render pipeline sets it.</summary>+ public ImageSource? IntensityImage+ {+ get => (ImageSource?)GetValue(IntensityImageProperty);+ set => SetValue(IntensityImageProperty, value);+ }++ private static void OnFrameCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)+ {+ var pane = (PreviewPane)d;+ pane.LastFrame = (int)e.NewValue - 1;+ pane.CoerceValue(PositionProperty);+ CommandManager.InvalidateRequerySuggested();+ }++ private static object CoercePosition(DependencyObject d, object value) =>+ Math.Clamp((int)value, 0, ((PreviewPane)d).LastFrame);++ private static object CoerceSpeed(DependencyObject d, object value)+ {+ double speed = (double)value;+ return double.IsNaN(speed) ? 1.0 : Math.Clamp(speed, MinSpeed, MaxSpeed);+ }++ private static void OnIsPlayingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)+ {+ var pane = (PreviewPane)d;+ if ((bool)e.NewValue)+ {+ if (pane.Position >= pane.LastFrame)+ {+ pane.Position = 0; // play again from the start+ }+ pane._carry = 0.0;+ pane._clock.Restart();+ pane._timer.Start();+ }+ else+ {+ pane._timer.Stop();+ pane._clock.Stop();+ }+ CommandManager.InvalidateRequerySuggested();+ pane.MoveFocusToCounterpart((bool)e.NewValue);+ }++ /// <summary>+ /// When the Play or Pause button has keyboard focus while its command just executed, moves+ /// focus to the other button, since CanExecute is about to disable this one and a disabled+ /// element cannot keep focus. Deferred behind the command re-query so the target is enabled.+ /// </summary>+ private void MoveFocusToCounterpart(bool playing)+ {+ if (playing && playButton.IsKeyboardFocused)+ {+ Dispatcher.BeginInvoke(DispatcherPriority.Background, () => pauseButton.Focus());+ }+ else if (!playing && pauseButton.IsKeyboardFocused)+ {+ Dispatcher.BeginInvoke(DispatcherPriority.Background, () => playButton.Focus());+ }+ }++ /// <summary>Advances <see cref="Position"/> by the frames elapsed since the previous tick; stops at the last frame.</summary>+ private void OnTick(object? sender, EventArgs e)+ {+ double seconds = _clock.Elapsed.TotalSeconds;+ _clock.Restart();+ _carry += seconds * BaseFrameRate * Speed;+ int frames = (int)Math.Floor(_carry);+ if (frames == 0)+ {+ return;+ }+ _carry -= frames;+ int next = Position + frames;+ if (next >= LastFrame)+ {+ Position = LastFrame;+ IsPlaying = false;+ }+ else+ {+ Position = next;+ }+ }++ private void CanPlay(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = !IsPlaying && LastFrame > 0;++ private void OnPlay(object sender, ExecutedRoutedEventArgs e) => IsPlaying = true;++ private void CanPause(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = IsPlaying;++ private void OnPause(object sender, ExecutedRoutedEventArgs e) => IsPlaying = false;++ private void CanTogglePlayPause(object sender, CanExecuteRoutedEventArgs e) => e.CanExecute = LastFrame > 0;++ private void OnTogglePlayPause(object sender, ExecutedRoutedEventArgs e) => IsPlaying = !IsPlaying;++ /// <summary>Space inside the speed text box is neither a digit nor the play/pause toggle: swallowed.</summary>+ private void OnSpeedBoxPreviewKeyDown(object sender, KeyEventArgs e)+ {+ if (e.Key == Key.Space)+ {+ e.Handled = true;+ }+ }++ /// <summary>A click on the pictures gives the pane keyboard focus so that Space toggles playback.</summary>+ private void OnPicturesMouseDown(object sender, MouseButtonEventArgs e) => Focus();++ /// <summary>Puts the splitter back in the middle: both pictures get an equal star share of the split dimension.</summary>+ private void ResetSplit()+ {+ var half = new GridLength(1, GridUnitType.Star);+ if (Orientation == Orientation.Horizontal)+ {+ pictures.ColumnDefinitions[0].Width = half;+ pictures.ColumnDefinitions[2].Width = half;+ }+ else+ {+ pictures.RowDefinitions[0].Height = half;+ pictures.RowDefinitions[2].Height = half;+ }+ }++ private void OnSplitterMouseDoubleClick(object sender, MouseButtonEventArgs e) => ResetSplit();++ /// <summary>Enter on the focused splitter is the keyboard's double-click; the arrow keys move it (built in).</summary>+ private void OnSplitterKeyDown(object sender, KeyEventArgs e)+ {+ if (e.Key == Key.Enter)+ {+ ResetSplit();+ e.Handled = true;+ }+ }++ /// <summary>+ /// The arrow keys inside the split group move to the neighbouring radio and check it, as a+ /// Win32 radio group does (WPF's own directional navigation only moves focus, and skips+ /// elements that are not tab stops). Only the checked radio is a tab stop, so Tab lands on+ /// the current choice. SetCurrentValue keeps the IsChecked binding alive.+ /// </summary>+ private void OnSplitGroupKeyDown(object sender, KeyEventArgs e)+ {+ int step = e.Key switch { Key.Right or Key.Down => 1, Key.Left or Key.Up => -1, _ => 0 };+ if (step == 0 || e.OriginalSource is not RadioButton current)+ {+ return;+ }+ var radios = splitGroup.Children.OfType<RadioButton>().ToList();+ RadioButton next = radios[(radios.IndexOf(current) + step + radios.Count) % radios.Count];+ next.SetCurrentValue(ToggleButton.IsCheckedProperty, true);+ next.Focus();+ e.Handled = true;+ }++ /// <summary>+ /// A 16:9 stand-in picture: decaying ripples from a source near the top-left corner in the+ /// field's red/blue look, or the same source's glow in the intensity's blue look. Frozen so+ /// it can serve as a dependency property default.+ /// </summary>+ private static BitmapSource CreatePlaceholder(bool intensity)+ {+ const int width = 480;+ const int height = 270;+ const double sourceX = 36.0;+ const double sourceY = 36.0;+ var bitmap = new WriteableBitmap(width, height, 96, 96, PixelFormats.Bgr32, null);+ var pixels = new int[width * height];+ for (int y = 0; y < height; y++)+ {+ for (int x = 0; x < width; x++)+ {+ double dx = x - sourceX;+ double dy = y - sourceY;+ double r = Math.Sqrt(dx * dx + dy * dy);+ int pixel;+ if (intensity)+ {+ double v = Math.Exp(-r / 150.0);+ pixel = (16 << 16) | ((int)(150 * v) << 8) | (int)(255 * v);+ }+ else+ {+ double v = Math.Sin(r * 0.7) * Math.Exp(-r / 200.0);+ int red = v > 0 ? (int)(255 * v) : 0;+ int blue = v < 0 ? (int)(-255 * v) : 0;+ pixel = (red << 16) | blue;+ }+ pixels[y * width + x] = pixel;+ }+ }+ bitmap.WritePixels(new Int32Rect(0, 0, width, height), pixels, width * 4, 0);+ bitmap.Freeze();+ return bitmap;+ }+}diff --git a/WaveDude.WPF/Panes/ProjectTree.xaml b/WaveDude.WPF/Panes/ProjectTree.xamlnew file mode 100644index 0000000..0db8a86--- /dev/null+++ b/WaveDude.WPF/Panes/ProjectTree.xaml@@ -0,0 +1,176 @@+<UserControl x:Class="WaveDude.WPF.Panes.ProjectTree"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:WaveDude.WPF.Panes"+ xmlns:commands="clr-namespace:WaveDude.WPF.Commands"+ xmlns:converters="clr-namespace:WaveDude.WPF.Converters"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <UserControl.Resources>+ <converters:EnumerateConverter x:Key="Enumerate" />+ <converters:NamedCollectionConverter x:Key="NamedCollections" />++ <StreamGeometry x:Key="PlusGeometry">M4,0 L4,8 M0,4 L8,4</StreamGeometry>+ <StreamGeometry x:Key="MinusGeometry">M0,4 L8,4</StreamGeometry>+ <StreamGeometry x:Key="ChevronUpGeometry">M0,6 L4,2 L8,6</StreamGeometry>+ <StreamGeometry x:Key="ChevronDownGeometry">M0,2 L4,6 L8,2</StreamGeometry>++ <!-- stroked-glyph button for the rows and the toolbar; Content is the geometry -->+ <Style x:Key="GlyphButton" TargetType="{x:Type Button}">+ <Setter Property="Width" Value="18" />+ <Setter Property="Height" Value="18" />+ <Setter Property="Margin" Value="1,0" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Button}">+ <Border x:Name="Bd" Background="Transparent" SnapsToDevicePixels="True">+ <Path Data="{TemplateBinding Content}" Stroke="{TemplateBinding Foreground}" StrokeThickness="1.2"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ <Setter Property="Opacity" Value="0.5" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="TextButton" TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">+ <Setter Property="Padding" Value="6,0" />+ <Setter Property="MinHeight" Value="20" />+ <Setter Property="Margin" Value="1,0" />+ <Setter Property="Focusable" Value="False" />+ </Style>+ </UserControl.Resources>++ <DockPanel>++ <!-- pane toolbar: acts on the tree selection -->+ <Border DockPanel.Dock="Top" BorderBrush="{DynamicResource ToolWindowBorder}" BorderThickness="0,0,0,1" Padding="2,2">+ <StackPanel Orientation="Horizontal">+ <Button Style="{StaticResource TextButton}" Content="{DynamicResource ToolAddSource}" ToolTip="{DynamicResource TipAddSource}" AutomationProperties.Name="{DynamicResource TipAddSource}"+ Command="{x:Static commands:ProjectCommands.AddSource}" />+ <Button Style="{StaticResource TextButton}" Content="{DynamicResource ToolAddProbe}" ToolTip="{DynamicResource TipAddProbe}" AutomationProperties.Name="{DynamicResource TipAddProbe}"+ Command="{x:Static commands:ProjectCommands.AddProbe}" />+ <Rectangle Width="1" Margin="4,2" Fill="{DynamicResource ToolWindowBorder}" />+ <Button Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronUpGeometry}" ToolTip="{DynamicResource TipMoveUp}" AutomationProperties.Name="{DynamicResource TipMoveUp}"+ Command="{x:Static commands:ProjectCommands.MoveUp}" />+ <Button Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronDownGeometry}" ToolTip="{DynamicResource TipMoveDown}" AutomationProperties.Name="{DynamicResource TipMoveDown}"+ Command="{x:Static commands:ProjectCommands.MoveDown}" />+ <Button Style="{StaticResource GlyphButton}" Content="{StaticResource MinusGeometry}" ToolTip="{DynamicResource TipRemove}" AutomationProperties.Name="{DynamicResource TipRemove}"+ Command="{x:Static commands:ProjectCommands.Remove}" />+ </StackPanel>+ </Border>++ <!-- the root object is wrapped in a one-element list so it shows as the top node -->+ <TreeView x:Name="tree" AllowDrop="True"+ ItemsSource="{Binding Project, RelativeSource={RelativeSource AncestorType={x:Type local:ProjectTree}}, Converter={StaticResource Enumerate}}"+ SelectedItemChanged="OnSelectedItemChanged"+ PreviewMouseLeftButtonDown="OnPreviewMouseLeftButtonDown" PreviewMouseMove="OnPreviewMouseMove"+ DragOver="OnDragOver" DragLeave="OnDragLeave" Drop="OnDrop">++ <!-- keys act on the selection; only while the tree has focus -->+ <TreeView.InputBindings>+ <KeyBinding Key="Delete" Command="{x:Static commands:ProjectCommands.Remove}" />+ <KeyBinding Key="D" Modifiers="Ctrl" Command="{x:Static commands:ProjectCommands.Duplicate}" />+ <KeyBinding Key="Up" Modifiers="Alt" Command="{x:Static commands:ProjectCommands.MoveUp}" />+ <KeyBinding Key="Down" Modifiers="Alt" Command="{x:Static commands:ProjectCommands.MoveDown}" />+ </TreeView.InputBindings>++ <TreeView.ItemContainerStyle>+ <Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource {x:Type TreeViewItem}}">+ <Setter Property="IsExpanded" Value="True" />+ <Setter Property="HorizontalContentAlignment" Value="Stretch" />+ <!-- context menu: the node is the data context, the row is the command target -->+ <Setter Property="ContextMenu">+ <Setter.Value>+ <ContextMenu>+ <ContextMenu.Resources>+ <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">+ <Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />+ <Setter Property="CommandParameter" Value="{Binding}" />+ </Style>+ </ContextMenu.Resources>+ <MenuItem Header="{DynamicResource MenuProjectAddSource}" Command="{x:Static commands:ProjectCommands.AddSource}" />+ <MenuItem Header="{DynamicResource MenuProjectAddProbe}" Command="{x:Static commands:ProjectCommands.AddProbe}" />+ <Separator />+ <MenuItem Header="{DynamicResource MenuProjectDuplicate}" Command="{x:Static commands:ProjectCommands.Duplicate}" InputGestureText="Ctrl+D" />+ <MenuItem Header="{DynamicResource MenuProjectRemove}" Command="{x:Static commands:ProjectCommands.Remove}" InputGestureText="Del" />+ <Separator />+ <MenuItem Header="{DynamicResource MenuProjectMoveUp}" Command="{x:Static commands:ProjectCommands.MoveUp}" InputGestureText="Alt+Up" />+ <MenuItem Header="{DynamicResource MenuProjectMoveDown}" Command="{x:Static commands:ProjectCommands.MoveDown}" InputGestureText="Alt+Down" />+ </ContextMenu>+ </Setter.Value>+ </Setter>+ </Style>+ </TreeView.ItemContainerStyle>++ <TreeView.Resources>+ <!-- one template per model type; children come from the bound properties, lists become folders -->+ <HierarchicalDataTemplate DataType="{x:Type model:Project}">+ <HierarchicalDataTemplate.ItemsSource>+ <MultiBinding Converter="{StaticResource NamedCollections}" ConverterParameter=",,,Sources,Probes">+ <Binding Path="Scene" />+ <Binding Path="Simulation" />+ <Binding Path="Display" />+ <Binding Path="Sources" />+ <Binding Path="Probes" />+ </MultiBinding>+ </HierarchicalDataTemplate.ItemsSource>+ <TextBlock Text="{DynamicResource TreeProject}" />+ </HierarchicalDataTemplate>++ <DataTemplate DataType="{x:Type model:Scene}">+ <TextBlock Text="{DynamicResource TreeScene}" />+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Simulation}">+ <TextBlock Text="{DynamicResource TreeSimulation}" />+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Display}">+ <TextBlock Text="{DynamicResource TreeDisplay}" />+ </DataTemplate>++ <!-- folder row: name and an add button -->+ <HierarchicalDataTemplate DataType="{x:Type converters:NamedCollection}" ItemsSource="{Binding Items}">+ <DockPanel>+ <Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource PlusGeometry}"+ ToolTip="{DynamicResource TipAdd}" AutomationProperties.Name="{DynamicResource TipAdd}" Command="{x:Static commands:ProjectCommands.Add}" CommandParameter="{Binding}" />+ <TextBlock Text="{Binding Label}" VerticalAlignment="Center" />+ </DockPanel>+ </HierarchicalDataTemplate>++ <!-- item rows: name, move up/down and remove -->+ <DataTemplate DataType="{x:Type model:Source}">+ <DockPanel>+ <Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource MinusGeometry}"+ ToolTip="{DynamicResource TipRemove}" AutomationProperties.Name="{DynamicResource TipRemove}" Command="{x:Static commands:ProjectCommands.Remove}" CommandParameter="{Binding}" />+ <Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronDownGeometry}"+ ToolTip="{DynamicResource TipMoveDown}" AutomationProperties.Name="{DynamicResource TipMoveDown}" Command="{x:Static commands:ProjectCommands.MoveDown}" CommandParameter="{Binding}" />+ <Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronUpGeometry}"+ ToolTip="{DynamicResource TipMoveUp}" AutomationProperties.Name="{DynamicResource TipMoveUp}" Command="{x:Static commands:ProjectCommands.MoveUp}" CommandParameter="{Binding}" />+ <TextBlock Text="{Binding Name}" VerticalAlignment="Center" />+ </DockPanel>+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Probe}">+ <DockPanel>+ <Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource MinusGeometry}"+ ToolTip="{DynamicResource TipRemove}" AutomationProperties.Name="{DynamicResource TipRemove}" Command="{x:Static commands:ProjectCommands.Remove}" CommandParameter="{Binding}" />+ <Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronDownGeometry}"+ ToolTip="{DynamicResource TipMoveDown}" AutomationProperties.Name="{DynamicResource TipMoveDown}" Command="{x:Static commands:ProjectCommands.MoveDown}" CommandParameter="{Binding}" />+ <Button DockPanel.Dock="Right" Style="{StaticResource GlyphButton}" Content="{StaticResource ChevronUpGeometry}"+ ToolTip="{DynamicResource TipMoveUp}" AutomationProperties.Name="{DynamicResource TipMoveUp}" Command="{x:Static commands:ProjectCommands.MoveUp}" CommandParameter="{Binding}" />+ <TextBlock Text="{Binding Name}" VerticalAlignment="Center" />+ </DockPanel>+ </DataTemplate>+ </TreeView.Resources>+ </TreeView>+ </DockPanel>+</UserControl>diff --git a/WaveDude.WPF/Panes/ProjectTree.xaml.cs b/WaveDude.WPF/Panes/ProjectTree.xaml.csnew file mode 100644index 0000000..03291eb--- /dev/null+++ b/WaveDude.WPF/Panes/ProjectTree.xaml.cs@@ -0,0 +1,250 @@+using System.Collections;+using System.Windows;+using System.Windows.Controls;+using System.Windows.Documents;+using System.Windows.Input;+using System.Windows.Media;+using System.Windows.Threading;+using WaveDude.Model;+using WaveDude.WPF.Controls;+using WaveDude.WPF.Converters;++namespace WaveDude.WPF.Panes;++/// <summary>+/// The project tree: the <see cref="Project"/> as root with its sections, sources and probes+/// beneath. Nodes are the model objects themselves; the templates in the XAML decide how each+/// type is shown and which properties form its children. Sources and probes can be reordered+/// by dragging a row onto a sibling (line above or below) or onto their folder (append).+/// </summary>+public partial class ProjectTree : UserControl+{+ private const string DragFormat = "WaveDude.ProjectTree.Item";++ /// <summary>Identifies the <see cref="Project"/> property.</summary>+ public static readonly DependencyProperty ProjectProperty = DependencyProperty.Register(+ nameof(Project), typeof(Project), typeof(ProjectTree));++ private static readonly DependencyPropertyKey SelectedItemKey = DependencyProperty.RegisterReadOnly(+ nameof(SelectedItem), typeof(object), typeof(ProjectTree), new PropertyMetadata(null));++ /// <summary>Identifies the <see cref="SelectedItem"/> property.</summary>+ public static readonly DependencyProperty SelectedItemProperty = SelectedItemKey.DependencyProperty;++ private object? _dragCandidate;+ private Point _dragStart;+ private InsertionAdorner? _adorner;++ public ProjectTree()+ {+ InitializeComponent();+ }++ /// <summary>The project shown as the root node; null shows an empty tree.</summary>+ public Project? Project+ {+ get => (Project?)GetValue(ProjectProperty);+ set => SetValue(ProjectProperty, value);+ }++ /// <summary>The model object of the selected node, or null.</summary>+ public object? SelectedItem+ {+ get => GetValue(SelectedItemProperty);+ private set => SetValue(SelectedItemKey, value);+ }++ /// <summary>Raised when <see cref="SelectedItem"/> changes.</summary>+ public event RoutedPropertyChangedEventHandler<object>? SelectedItemChanged;++ /// <summary>Selects the node of a model object once the tree has generated it.</summary>+ public void Select(object item) =>+ Dispatcher.InvokeAsync(() => tree.SetSelectedItem(item, expand: true), DispatcherPriority.Loaded);++ /// <summary>Selects the root node; call after setting <see cref="Project"/>.</summary>+ public void SelectRoot()+ {+ if (Project != null)+ {+ Select(Project);+ }+ }++ /// <summary>Selects the folder node that shows <paramref name="list"/> (the project's sources or probes).</summary>+ public void SelectFolder(IEnumerable list) =>+ Dispatcher.InvokeAsync(() =>+ {+ if (FindNode(tree, node => node is NamedCollection folder && ReferenceEquals(folder.Items, list)) is { } folder)+ {+ tree.SetSelectedItem(folder);+ }+ }, DispatcherPriority.Loaded);++ private static object? FindNode(ItemsControl parent, Func<object, bool> match)+ {+ foreach (object node in parent.Items)+ {+ if (match(node))+ {+ return node;+ }+ if (parent.ItemContainerGenerator.ContainerFromItem(node) is ItemsControl container+ && FindNode(container, match) is { } found)+ {+ return found;+ }+ }+ return null;+ }++ private void OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)+ {+ SelectedItem = e.NewValue;+ SelectedItemChanged?.Invoke(this, e);+ }++ // ----- drag-and-drop reordering -----++ private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)+ {+ _dragCandidate = null;+ var origin = e.OriginalSource as DependencyObject;+ if (FindAncestor<Button>(origin) != null)+ {+ return; // row buttons are clicks, not drags+ }+ if (FindAncestor<TreeViewItem>(origin) is { DataContext: Source or Probe } row)+ {+ _dragCandidate = row.DataContext;+ _dragStart = e.GetPosition(tree);+ }+ }++ private void OnPreviewMouseMove(object sender, MouseEventArgs e)+ {+ if (_dragCandidate == null || e.LeftButton != MouseButtonState.Pressed)+ {+ return;+ }+ Vector moved = e.GetPosition(tree) - _dragStart;+ if (Math.Abs(moved.X) < SystemParameters.MinimumHorizontalDragDistance+ && Math.Abs(moved.Y) < SystemParameters.MinimumVerticalDragDistance)+ {+ return;+ }+ object item = _dragCandidate;+ _dragCandidate = null;+ DragDrop.DoDragDrop(tree, new DataObject(DragFormat, item), DragDropEffects.Move);+ ClearAdorner();+ }++ private void OnDragOver(object sender, DragEventArgs e)+ {+ e.Effects = DragDropEffects.None;+ e.Handled = true;+ ClearAdorner();+ if (e.Data.GetData(DragFormat) is not { } item)+ {+ return;+ }+ DropTarget? target = FindDropTarget(item, e.GetPosition(tree));+ if (target == null)+ {+ return;+ }+ e.Effects = DragDropEffects.Move;+ if (AdornerLayer.GetAdornerLayer(target.Row) is { } layer && tree.TryFindResource("Accent") is Brush brush)+ {+ _adorner = new InsertionAdorner(target.Header, brush, target.Placement);+ layer.Add(_adorner);+ }+ }++ private void OnDragLeave(object sender, DragEventArgs e) => ClearAdorner();++ private void OnDrop(object sender, DragEventArgs e)+ {+ e.Handled = true;+ ClearAdorner();+ if (Project == null || e.Data.GetData(DragFormat) is not { } item)+ {+ return;+ }+ if (FindDropTarget(item, e.GetPosition(tree)) is not { } target)+ {+ return;+ }+ bool moved = item switch+ {+ Source source => Project.Move(source, target.Index),+ Probe probe => Project.Move(probe, target.Index),+ _ => false,+ };+ if (moved)+ {+ Select(item);+ }+ }++ private void ClearAdorner()+ {+ if (_adorner != null)+ {+ AdornerLayer.GetAdornerLayer(_adorner.AdornedElement)?.Remove(_adorner);+ _adorner = null;+ }+ }++ /// <summary>Row under the mouse, where a drop would put the item, and how to show it.</summary>+ private sealed record DropTarget(TreeViewItem Row, FrameworkElement Header, InsertionPlacement Placement, int Index);++ /// <summary>+ /// Resolves a drop position: onto a sibling of the dragged item (before or after, by the+ /// upper or lower half of its row) or onto the item's own folder (append). Null when the+ /// position is not a valid target or would not move anything.+ /// </summary>+ private DropTarget? FindDropTarget(object item, Point position)+ {+ IList? list = ListOf(item);+ if (list == null || tree.InputHitTest(position) is not DependencyObject hit+ || FindAncestor<TreeViewItem>(hit) is not { } row+ || row.Template.FindName("PART_Header", row) is not FrameworkElement header)+ {+ return null;+ }+ int current = list.IndexOf(item);+ if (row.DataContext is NamedCollection folder && ReferenceEquals(folder.Items, list))+ {+ int last = list.Count - 1;+ return current == last ? null : new DropTarget(row, header, InsertionPlacement.Into, last);+ }+ if (row.DataContext == item || ListOf(row.DataContext) != list)+ {+ return null;+ }+ int targetIndex = list.IndexOf(row.DataContext);+ bool before = position.Y < header.TransformToAncestor(tree).Transform(new Point(0, header.ActualHeight / 2)).Y;+ int insert = targetIndex + (before ? 0 : 1); // slot in the list as it is now+ int final = insert - (current < insert ? 1 : 0); // index after the item left its slot+ return final == current ? null : new DropTarget(row, header, before ? InsertionPlacement.Before : InsertionPlacement.After, final);+ }++ private IList? ListOf(object? node) => node switch+ {+ Source => Project?.Sources,+ Probe => Project?.Probes,+ _ => null,+ };++ private static T? FindAncestor<T>(DependencyObject? start) where T : DependencyObject+ {+ for (DependencyObject? d = start; d != null; d = d is Visual or System.Windows.Media.Media3D.Visual3D ? VisualTreeHelper.GetParent(d) : LogicalTreeHelper.GetParent(d))+ {+ if (d is T match)+ {+ return match;+ }+ }+ return null;+ }+}diff --git a/WaveDude.WPF/Panes/PropertiesPane.xaml b/WaveDude.WPF/Panes/PropertiesPane.xamlnew file mode 100644index 0000000..0e28e53--- /dev/null+++ b/WaveDude.WPF/Panes/PropertiesPane.xaml@@ -0,0 +1,50 @@+<UserControl x:Class="WaveDude.WPF.Panes.PropertiesPane"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:WaveDude.WPF.Panes"+ xmlns:views="clr-namespace:WaveDude.WPF.Views"+ xmlns:converters="clr-namespace:WaveDude.WPF.Converters"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <!-- one view per model type; the content control picks the template by the selected object's type -->+ <UserControl.Resources>+ <DataTemplate DataType="{x:Type model:Project}">+ <views:ProjectView />+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Scene}">+ <views:SceneView />+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Simulation}">+ <views:SimulationView />+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Display}">+ <views:DisplayView />+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Source}">+ <views:SourceView />+ </DataTemplate>+ <DataTemplate DataType="{x:Type model:Probe}">+ <views:ProbeView />+ </DataTemplate>+ <DataTemplate DataType="{x:Type converters:NamedCollection}">+ <views:CollectionView />+ </DataTemplate>+ </UserControl.Resources>++ <Grid>+ <ContentControl Focusable="False"+ Content="{Binding SelectedObject, RelativeSource={RelativeSource AncestorType={x:Type local:PropertiesPane}}}" />+ <TextBlock Margin="6" Foreground="{DynamicResource GrayText}" Text="{DynamicResource NoSelection}">+ <TextBlock.Style>+ <Style TargetType="{x:Type TextBlock}">+ <Setter Property="Visibility" Value="Collapsed" />+ <Style.Triggers>+ <DataTrigger Binding="{Binding SelectedObject, RelativeSource={RelativeSource AncestorType={x:Type local:PropertiesPane}}}" Value="{x:Null}">+ <Setter Property="Visibility" Value="Visible" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ </TextBlock.Style>+ </TextBlock>+ </Grid>+</UserControl>diff --git a/WaveDude.WPF/Panes/PropertiesPane.xaml.cs b/WaveDude.WPF/Panes/PropertiesPane.xaml.csnew file mode 100644index 0000000..292717c--- /dev/null+++ b/WaveDude.WPF/Panes/PropertiesPane.xaml.cs@@ -0,0 +1,59 @@+using System.Windows;+using System.Windows.Controls;+using System.Windows.Media;+using System.Windows.Threading;++namespace WaveDude.WPF.Panes;++/// <summary>+/// The Properties pane: shows the editor view that matches the type of+/// <see cref="SelectedObject"/>, mapped by the data templates in the XAML, or a hint when+/// nothing is selected.+/// </summary>+public partial class PropertiesPane : UserControl+{+ /// <summary>Identifies the <see cref="SelectedObject"/> property.</summary>+ public static readonly DependencyProperty SelectedObjectProperty = DependencyProperty.Register(+ nameof(SelectedObject), typeof(object), typeof(PropertiesPane));++ public PropertiesPane()+ {+ InitializeComponent();+ }++ /// <summary>The model object to edit, or null for the empty hint.</summary>+ public object? SelectedObject+ {+ get => GetValue(SelectedObjectProperty);+ set => SetValue(SelectedObjectProperty, value);+ }++ /// <summary>Puts the caret into the first text box of the current view once it is built, selecting its text.</summary>+ public void FocusFirstEditor() =>+ Dispatcher.InvokeAsync(() =>+ {+ if (FirstDescendant<TextBox>(this) is { } box)+ {+ box.Focus();+ box.SelectAll();+ }+ }, DispatcherPriority.Background);++ private static T? FirstDescendant<T>(DependencyObject root) where T : DependencyObject+ {+ int count = VisualTreeHelper.GetChildrenCount(root);+ for (int i = 0; i < count; i++)+ {+ DependencyObject child = VisualTreeHelper.GetChild(root, i);+ if (child is T match)+ {+ return match;+ }+ if (FirstDescendant<T>(child) is { } nested)+ {+ return nested;+ }+ }+ return null;+ }+}diff --git a/WaveDude.WPF/Program.cs b/WaveDude.WPF/Program.csnew file mode 100644index 0000000..c666afd--- /dev/null+++ b/WaveDude.WPF/Program.cs@@ -0,0 +1,15 @@+namespace WaveDude.WPF;++/// <summary>+/// Process entry point. Exists so that logging is configured before the generated+/// <see cref="App.Main"/> parses <c>App.xaml</c>; a failure in there is then still on record.+/// </summary>+internal static class Program+{+ [STAThread]+ private static void Main()+ {+ App.SetupLoggingConfig();+ App.Main();+ }+}diff --git a/WaveDude.WPF/Properties/Settings.Designer.cs b/WaveDude.WPF/Properties/Settings.Designer.csnew file mode 100644index 0000000..1b19edf--- /dev/null+++ b/WaveDude.WPF/Properties/Settings.Designer.cs@@ -0,0 +1,132 @@+//------------------------------------------------------------------------------+// <auto-generated>+// This code was generated by a tool.+// Runtime Version:4.0.30319.42000+//+// Changes to this file may cause incorrect behavior and will be lost if+// the code is regenerated.+// </auto-generated>+//------------------------------------------------------------------------------++namespace WaveDude.WPF.Properties {+++ [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]+ [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "18.10.0.0")]+ internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {++ private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));++ public static Settings Default {+ get {+ return defaultInstance;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("True")]+ public bool UpgradeRequired {+ get {+ return ((bool)(this["UpgradeRequired"]));+ }+ set {+ this["UpgradeRequired"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("1280")]+ public double MainWindow_Width {+ get {+ return ((double)(this["MainWindow_Width"]));+ }+ set {+ this["MainWindow_Width"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("800")]+ public double MainWindow_Height {+ get {+ return ((double)(this["MainWindow_Height"]));+ }+ set {+ this["MainWindow_Height"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("NaN")]+ public double MainWindow_Left {+ get {+ return ((double)(this["MainWindow_Left"]));+ }+ set {+ this["MainWindow_Left"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("NaN")]+ public double MainWindow_Top {+ get {+ return ((double)(this["MainWindow_Top"]));+ }+ set {+ this["MainWindow_Top"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("Normal")]+ public global::System.Windows.WindowState MainWindow_State {+ get {+ return ((global::System.Windows.WindowState)(this["MainWindow_State"]));+ }+ set {+ this["MainWindow_State"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ public global::WaveDude.WPF.Docking.DockLayout Layout {+ get {+ return ((global::WaveDude.WPF.Docking.DockLayout)(this["Layout"]));+ }+ set {+ this["Layout"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ [global::System.Configuration.DefaultSettingValueAttribute("System")]+ public global::WaveDude.WPF.Theming.AppTheme Theme {+ get {+ return ((global::WaveDude.WPF.Theming.AppTheme)(this["Theme"]));+ }+ set {+ this["Theme"] = value;+ }+ }++ [global::System.Configuration.UserScopedSettingAttribute()]+ [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]+ public global::System.Collections.Specialized.StringCollection RecentFiles {+ get {+ return ((global::System.Collections.Specialized.StringCollection)(this["RecentFiles"]));+ }+ set {+ this["RecentFiles"] = value;+ }+ }+ }+}diff --git a/WaveDude.WPF/Properties/Settings.settings b/WaveDude.WPF/Properties/Settings.settingsnew file mode 100644index 0000000..3a6bb94--- /dev/null+++ b/WaveDude.WPF/Properties/Settings.settings@@ -0,0 +1,33 @@+<?xml version='1.0' encoding='utf-8'?>+<SettingsFile xmlns="http://schemas.microsoft.com/VisualStudio/2004/01/settings" CurrentProfile="(Default)" GeneratedClassNamespace="WaveDude.WPF.Properties" GeneratedClassName="Settings">+ <Profiles />+ <Settings>+ <Setting Name="UpgradeRequired" Type="System.Boolean" Scope="User">+ <Value Profile="(Default)">True</Value>+ </Setting>+ <Setting Name="MainWindow_Width" Type="System.Double" Scope="User">+ <Value Profile="(Default)">1280</Value>+ </Setting>+ <Setting Name="MainWindow_Height" Type="System.Double" Scope="User">+ <Value Profile="(Default)">800</Value>+ </Setting>+ <Setting Name="MainWindow_Left" Type="System.Double" Scope="User">+ <Value Profile="(Default)">NaN</Value>+ </Setting>+ <Setting Name="MainWindow_Top" Type="System.Double" Scope="User">+ <Value Profile="(Default)">NaN</Value>+ </Setting>+ <Setting Name="MainWindow_State" Type="System.Windows.WindowState" Scope="User">+ <Value Profile="(Default)">Normal</Value>+ </Setting>+ <Setting Name="Layout" Type="WaveDude.WPF.Docking.DockLayout" Scope="User">+ <Value Profile="(Default)" />+ </Setting>+ <Setting Name="Theme" Type="WaveDude.WPF.Theming.AppTheme" Scope="User">+ <Value Profile="(Default)">System</Value>+ </Setting>+ <Setting Name="RecentFiles" Type="System.Collections.Specialized.StringCollection" Scope="User">+ <Value Profile="(Default)" />+ </Setting>+ </Settings>+</SettingsFile>diff --git a/WaveDude.WPF/Strings/Strings.EN.xaml b/WaveDude.WPF/Strings/Strings.EN.xamlnew file mode 100644index 0000000..f6aceba--- /dev/null+++ b/WaveDude.WPF/Strings/Strings.EN.xaml@@ -0,0 +1,97 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:s="clr-namespace:System;assembly=mscorlib">++ <!-- user-visible text; menu headers carry their mnemonic underscore -->++ <s:String x:Key="Title">Wave Dude</s:String>++ <s:String x:Key="MenuFile">_File</s:String>+ <s:String x:Key="MenuFileNew">_New Project</s:String>+ <s:String x:Key="MenuFileOpen">_Open Project...</s:String>+ <s:String x:Key="MenuFileRecent">_Recent Projects</s:String>+ <s:String x:Key="MenuFileSave">_Save</s:String>+ <s:String x:Key="MenuFileSaveAs">Save _As...</s:String>+ <s:String x:Key="MenuFileClose">_Close Project</s:String>+ <s:String x:Key="MenuFileExit">E_xit</s:String>+ <s:String x:Key="MenuView">_View</s:String>+ <s:String x:Key="MenuViewPanes">_Panes</s:String>+ <s:String x:Key="MenuViewTheme">_Theme</s:String>+ <s:String x:Key="MenuHelp">_Help</s:String>+ <s:String x:Key="MenuHelpAbout">_About Wave Dude</s:String>++ <s:String x:Key="MenuProjectAddSource">Add _source</s:String>+ <s:String x:Key="MenuProjectAddProbe">Add _probe</s:String>+ <s:String x:Key="MenuProjectDuplicate">_Duplicate</s:String>+ <s:String x:Key="MenuProjectRemove">_Remove</s:String>+ <s:String x:Key="MenuProjectMoveUp">Move _up</s:String>+ <s:String x:Key="MenuProjectMoveDown">Move _down</s:String>+ <s:String x:Key="ToolAddSource">+ Source</s:String>+ <s:String x:Key="ToolAddProbe">+ Probe</s:String>+ <s:String x:Key="TipAddSource">Add a source (appended at the end)</s:String>+ <s:String x:Key="TipAddProbe">Add a probe (appended at the end)</s:String>+ <s:String x:Key="TipAdd">Add an item to this folder</s:String>+ <s:String x:Key="TipRemove">Remove (Del)</s:String>+ <s:String x:Key="TipMoveUp">Move up (Alt+Up); drag to reorder</s:String>+ <s:String x:Key="TipMoveDown">Move down (Alt+Down); drag to reorder</s:String>++ <s:String x:Key="PaneMessages">Messages</s:String>+ <s:String x:Key="MessagesSearchHint">Search</s:String>+ <s:String x:Key="MessagesRegex">Regex</s:String>+ <s:String x:Key="MessagesAutoScroll">Auto-scroll</s:String>+ <s:String x:Key="MessagesCopy">_Copy</s:String>+ <s:String x:Key="MessagesCopyAll">Copy _all</s:String>+ <s:String x:Key="MessagesClear">C_lear</s:String>+ <s:String x:Key="MessagesColumnTime">Time</s:String>+ <s:String x:Key="MessagesColumnLevel">Level</s:String>+ <s:String x:Key="MessagesColumnLogger">Source</s:String>+ <s:String x:Key="MessagesColumnMessage">Message</s:String>+ <s:String x:Key="TipMessagesLevel">Show or hide this level</s:String>+ <s:String x:Key="TipMessagesRegex">Treat the search text as a regular expression</s:String>+ <s:String x:Key="TipMessagesAutoScroll">Follow new messages</s:String>+ <s:String x:Key="TipMessagesClear">Clear all messages</s:String>+ <s:String x:Key="TipStatusBar">Double-click to open the Messages pane</s:String>+ <s:String x:Key="PaneProject">Project</s:String>+ <s:String x:Key="PaneProperties">Properties</s:String>+ <s:String x:Key="PanePreview">Preview</s:String>+ <s:String x:Key="TipPreviewPlay">Play (Space)</s:String>+ <s:String x:Key="TipPreviewPause">Pause (Space)</s:String>+ <s:String x:Key="TipPreviewScrub">Drag to scrub through the frames</s:String>+ <s:String x:Key="TipPreviewFrame">Frame shown / last frame</s:String>+ <s:String x:Key="LabelPreviewSpeed">Speed</s:String>+ <s:String x:Key="TipPreviewSpeed">Playback speed: pick a factor or type one</s:String>+ <s:String x:Key="TipPreviewSideBySide">Field and intensity side by side</s:String>+ <s:String x:Key="TipPreviewStacked">Field above intensity</s:String>+ <s:String x:Key="TipPreviewSplitter">Drag or use the arrow keys to resize; double-click or Enter resets to half</s:String>+ <s:String x:Key="Ready">Ready</s:String>+ <s:String x:Key="NoSelection">No selection</s:String>++ <s:String x:Key="TreeProject">Project</s:String>+ <s:String x:Key="TreeScene">Scene</s:String>+ <s:String x:Key="TreeSimulation">Simulation</s:String>+ <s:String x:Key="TreeDisplay">Display</s:String>++ <s:String x:Key="SectionGeneral">General</s:String>+ <s:String x:Key="SectionCanvas">Canvas</s:String>+ <s:String x:Key="SectionImageSources">Sources from the image</s:String>+ <s:String x:Key="SectionRun">Run</s:String>+ <s:String x:Key="SectionSolver">Solver</s:String>+ <s:String x:Key="SectionField">Field</s:String>+ <s:String x:Key="SectionIntensity">Intensity</s:String>+ <s:String x:Key="SectionVideo">Video export</s:String>+ <s:String x:Key="SectionPosition">Position</s:String>+ <s:String x:Key="SectionWave">Wave</s:String>+ <s:String x:Key="SectionTiming">Timing</s:String>+ <s:String x:Key="SectionArray">Array</s:String>+ <s:String x:Key="SectionMeasurement">Measurement</s:String>+ <s:String x:Key="SectionGraph">Graph</s:String>+ <s:String x:Key="SectionAxes">Axes</s:String>+ <s:String x:Key="ButtonNewSeed">_New seed</s:String>+ <s:String x:Key="ItemCountFormat">{0} items</s:String>++ <s:String x:Key="OpenFileDialogFilter">Wave Dude projects (*.wdproj)|*.wdproj|XML files (*.xml)|*.xml|All files (*.*)|*.*</s:String>+ <s:String x:Key="SaveFileDialogFilter">Wave Dude projects (*.wdproj)|*.wdproj|XML files (*.xml)|*.xml</s:String>+ <s:String x:Key="OpenError">Could not open '{0}'.</s:String>+ <s:String x:Key="SaveError">Could not save '{0}'.</s:String>++</ResourceDictionary>diff --git a/WaveDude.WPF/Themes/Controls.xaml b/WaveDude.WPF/Themes/Controls.xamlnew file mode 100644index 0000000..05543ee--- /dev/null+++ b/WaveDude.WPF/Themes/Controls.xaml@@ -0,0 +1,734 @@+<!--+ Control styles for the whole application. Visual Studio look, system font at 9pt, every+ colour taken from the active colour table (Dark.xaml / Light.xaml) via DynamicResource.+-->+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:docking="clr-namespace:WaveDude.WPF.Docking">++ <BooleanToVisibilityConverter x:Key="BoolToVisibility" />++ <!-- glyphs -->+ <StreamGeometry x:Key="ArrowUpGeometry">M0,4 L4,0 L8,4 Z</StreamGeometry>+ <StreamGeometry x:Key="ArrowDownGeometry">M0,0 L8,0 L4,4 Z</StreamGeometry>+ <StreamGeometry x:Key="ArrowLeftGeometry">M4,0 L4,8 L0,4 Z</StreamGeometry>+ <StreamGeometry x:Key="ArrowRightGeometry">M0,0 L4,4 L0,8 Z</StreamGeometry>+ <StreamGeometry x:Key="SubmenuArrowGeometry">M0,0 L4,4 L0,8 Z</StreamGeometry>+ <StreamGeometry x:Key="CheckGeometry">M0,4 L3,7 L8,1</StreamGeometry>+ <StreamGeometry x:Key="ChevronRightGeometry">M0,0 L5,5 L0,10</StreamGeometry>+ <StreamGeometry x:Key="ChevronDownGeometry">M0,0 L5,5 L10,0</StreamGeometry>+ <StreamGeometry x:Key="CloseGeometry">M0,1 L1,0 L4,3 L7,0 L8,1 L5,4 L8,7 L7,8 L4,5 L1,8 L0,7 L3,4 Z</StreamGeometry>+ <StreamGeometry x:Key="DropDownGeometry">M0,0 L8,0 L4,4 Z</StreamGeometry>++ <DrawingBrush x:Key="DockGripInactiveBrush" TileMode="Tile" Viewport="0,0,4,4" ViewportUnits="Absolute" Viewbox="0,0,4,4" ViewboxUnits="Absolute">+ <DrawingBrush.Drawing>+ <GeometryDrawing Brush="{DynamicResource TitleBarDragHandleInactive}" Geometry="M0,0 L1,0 L1,1 L0,1 Z M2,2 L3,2 L3,3 L2,3 Z" />+ </DrawingBrush.Drawing>+ </DrawingBrush>+ <DrawingBrush x:Key="DockGripActiveBrush" TileMode="Tile" Viewport="0,0,4,4" ViewportUnits="Absolute" Viewbox="0,0,4,4" ViewboxUnits="Absolute">+ <DrawingBrush.Drawing>+ <GeometryDrawing Brush="{DynamicResource TitleBarDragHandleActive}" Geometry="M0,0 L1,0 L1,1 L0,1 Z M2,2 L3,2 L3,3 L2,3 Z" />+ </DrawingBrush.Drawing>+ </DrawingBrush>++ <!-- ===================== window ===================== -->+ <Style TargetType="{x:Type Window}">+ <Setter Property="Background" Value="{DynamicResource WindowBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="FontFamily" Value="Segoe UI" />+ <Setter Property="FontSize" Value="12" />+ <Setter Property="TextOptions.TextFormattingMode" Value="Display" />+ <Setter Property="UseLayoutRounding" Value="True" />+ <Setter Property="SnapsToDevicePixels" Value="True" />+ </Style>++ <!-- ===================== menu ===================== -->+ <Style TargetType="{x:Type Menu}">+ <Setter Property="Background" Value="{DynamicResource MenuBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource MenuForeground}" />+ <Setter Property="Padding" Value="2,0" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Menu}">+ <Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}">+ <ItemsPresenter />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <ControlTemplate x:Key="MenuPopupContent" TargetType="{x:Type MenuItem}">+ <Border Background="{DynamicResource MenuPopupBackground}"+ BorderBrush="{DynamicResource MenuPopupBorder}" BorderThickness="1" Padding="2">+ <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" />+ </Border>+ </ControlTemplate>++ <ControlTemplate x:Key="MenuTopLevelHeaderTemplate" TargetType="{x:Type MenuItem}">+ <Border x:Name="Bd" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <Grid>+ <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" VerticalAlignment="Center" />+ <Popup x:Name="PART_Popup" Placement="Bottom" VerticalOffset="1"+ IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}"+ AllowsTransparency="True" Focusable="False" PopupAnimation="None">+ <Border Background="{DynamicResource MenuPopupBackground}"+ BorderBrush="{DynamicResource MenuPopupBorder}" BorderThickness="1" Padding="2">+ <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" />+ </Border>+ </Popup>+ </Grid>+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsHighlighted" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource MenuItemHover}" />+ <Setter Property="Foreground" Value="{DynamicResource MenuItemHoverForeground}" />+ </Trigger>+ <Trigger Property="IsSubmenuOpen" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource MenuPopupBackground}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>++ <ControlTemplate x:Key="MenuTopLevelItemTemplate" TargetType="{x:Type MenuItem}">+ <Border x:Name="Bd" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <ContentPresenter ContentSource="Header" RecognizesAccessKey="True" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsHighlighted" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource MenuItemHover}" />+ <Setter Property="Foreground" Value="{DynamicResource MenuItemHoverForeground}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>++ <ControlTemplate x:Key="MenuSubmenuItemTemplate" TargetType="{x:Type MenuItem}">+ <Border x:Name="Bd" Background="{TemplateBinding Background}" Padding="2" SnapsToDevicePixels="True">+ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="24" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" SharedSizeGroup="MenuItemGestureColumn" />+ <ColumnDefinition Width="16" />+ </Grid.ColumnDefinitions>+ <ContentPresenter x:Name="Icon" ContentSource="Icon" Width="16" Height="16"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ <Path x:Name="CheckGlyph" Data="{StaticResource CheckGeometry}" Stroke="{DynamicResource MenuGlyph}"+ StrokeThickness="1.5" Visibility="Collapsed" HorizontalAlignment="Center" VerticalAlignment="Center" />+ <ContentPresenter Grid.Column="1" ContentSource="Header" RecognizesAccessKey="True"+ Margin="4,2,8,2" VerticalAlignment="Center" />+ <TextBlock Grid.Column="2" Text="{TemplateBinding InputGestureText}" Margin="16,2,4,2"+ VerticalAlignment="Center" Foreground="{DynamicResource GrayText}" />+ </Grid>+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="Icon" Value="{x:Null}">+ <Setter TargetName="Icon" Property="Visibility" Value="Collapsed" />+ </Trigger>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="CheckGlyph" Property="Visibility" Value="Visible" />+ </Trigger>+ <Trigger Property="IsHighlighted" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource MenuItemHover}" />+ <Setter Property="Foreground" Value="{DynamicResource MenuItemHoverForeground}" />+ <Setter TargetName="CheckGlyph" Property="Stroke" Value="{DynamicResource MenuGlyphHover}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>++ <ControlTemplate x:Key="MenuSubmenuHeaderTemplate" TargetType="{x:Type MenuItem}">+ <Border x:Name="Bd" Background="{TemplateBinding Background}" Padding="2" SnapsToDevicePixels="True">+ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="24" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="Auto" SharedSizeGroup="MenuItemGestureColumn" />+ <ColumnDefinition Width="16" />+ </Grid.ColumnDefinitions>+ <ContentPresenter x:Name="Icon" ContentSource="Icon" Width="16" Height="16"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ <ContentPresenter Grid.Column="1" ContentSource="Header" RecognizesAccessKey="True"+ Margin="4,2,8,2" VerticalAlignment="Center" />+ <Path x:Name="Arrow" Grid.Column="3" Data="{StaticResource SubmenuArrowGeometry}"+ Fill="{DynamicResource MenuGlyph}" HorizontalAlignment="Center" VerticalAlignment="Center" />+ <Popup x:Name="PART_Popup" Placement="Right" HorizontalOffset="-1" VerticalOffset="-3"+ IsOpen="{Binding IsSubmenuOpen, RelativeSource={RelativeSource TemplatedParent}}"+ AllowsTransparency="True" Focusable="False" PopupAnimation="None">+ <Border Background="{DynamicResource MenuPopupBackground}"+ BorderBrush="{DynamicResource MenuPopupBorder}" BorderThickness="1" Padding="2">+ <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" />+ </Border>+ </Popup>+ </Grid>+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="Icon" Value="{x:Null}">+ <Setter TargetName="Icon" Property="Visibility" Value="Collapsed" />+ </Trigger>+ <Trigger Property="IsHighlighted" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource MenuItemHover}" />+ <Setter Property="Foreground" Value="{DynamicResource MenuItemHoverForeground}" />+ <Setter TargetName="Arrow" Property="Fill" Value="{DynamicResource MenuGlyphHover}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>++ <Style TargetType="{x:Type MenuItem}">+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Foreground" Value="{DynamicResource MenuForeground}" />+ <Setter Property="Padding" Value="7,3" />+ <Setter Property="Template" Value="{StaticResource MenuSubmenuItemTemplate}" />+ <Style.Triggers>+ <Trigger Property="Role" Value="TopLevelHeader">+ <Setter Property="Template" Value="{StaticResource MenuTopLevelHeaderTemplate}" />+ </Trigger>+ <Trigger Property="Role" Value="TopLevelItem">+ <Setter Property="Template" Value="{StaticResource MenuTopLevelItemTemplate}" />+ </Trigger>+ <Trigger Property="Role" Value="SubmenuHeader">+ <Setter Property="Template" Value="{StaticResource MenuSubmenuHeaderTemplate}" />+ </Trigger>+ </Style.Triggers>+ </Style>++ <Style x:Key="{x:Static MenuItem.SeparatorStyleKey}" TargetType="{x:Type Separator}">+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Separator}">+ <Border Height="1" Margin="26,3,2,3" Background="{DynamicResource MenuSeparator}" SnapsToDevicePixels="True" />+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style TargetType="{x:Type ContextMenu}">+ <Setter Property="Foreground" Value="{DynamicResource MenuForeground}" />+ <Setter Property="HasDropShadow" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ContextMenu}">+ <Border Background="{DynamicResource MenuPopupBackground}"+ BorderBrush="{DynamicResource MenuPopupBorder}" BorderThickness="1" Padding="2">+ <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True" />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- ===================== status bar ===================== -->+ <Style TargetType="{x:Type StatusBar}">+ <Setter Property="Background" Value="{DynamicResource StatusBarBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource StatusBarForeground}" />+ <!-- right padding keeps the window's resize grip clear of the last item -->+ <Setter Property="Padding" Value="4,0,16,0" />+ <Setter Property="MinHeight" Value="22" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type StatusBar}">+ <Border Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}">+ <ItemsPresenter />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style TargetType="{x:Type StatusBarItem}">+ <Setter Property="Padding" Value="4,2" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type StatusBarItem}">+ <Border Padding="{TemplateBinding Padding}">+ <ContentPresenter VerticalAlignment="Center" />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- window resize grip, drawn over the status bar corner: VS-style dot triangle -->+ <Style TargetType="{x:Type ResizeGrip}">+ <Setter Property="Width" Value="16" />+ <Setter Property="Height" Value="16" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ResizeGrip}">+ <Border Background="Transparent">+ <Path Fill="{DynamicResource StatusBarForeground}" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="0,0,3,3"+ Data="M8,0 h2 v2 h-2 z M8,4 h2 v2 h-2 z M8,8 h2 v2 h-2 z M4,4 h2 v2 h-2 z M4,8 h2 v2 h-2 z M0,8 h2 v2 h-2 z" />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- ===================== scroll bars ===================== -->+ <Style x:Key="ScrollBarLineButtonStyle" TargetType="{x:Type RepeatButton}">+ <Setter Property="OverridesDefaultStyle" Value="True" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type RepeatButton}">+ <Border Background="{DynamicResource ScrollBarBackground}">+ <Path x:Name="Glyph" Data="{TemplateBinding Content}" Fill="{DynamicResource ScrollBarArrow}"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Glyph" Property="Fill" Value="{DynamicResource ScrollBarArrowHover}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Glyph" Property="Fill" Value="{DynamicResource ScrollBarArrowPressed}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style x:Key="ScrollBarPageButtonStyle" TargetType="{x:Type RepeatButton}">+ <Setter Property="OverridesDefaultStyle" Value="True" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type RepeatButton}">+ <Border Background="Transparent" />+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style x:Key="ScrollBarThumbStyle" TargetType="{x:Type Thumb}">+ <Setter Property="OverridesDefaultStyle" Value="True" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Thumb}">+ <Border x:Name="Bd" Background="{DynamicResource ScrollBarThumb}" Margin="3" />+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ScrollBarThumbHover}" />+ </Trigger>+ <Trigger Property="IsDragging" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ScrollBarThumbPressed}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <ControlTemplate x:Key="VerticalScrollBarTemplate" TargetType="{x:Type ScrollBar}">+ <Grid Background="{TemplateBinding Background}">+ <Grid.RowDefinitions>+ <RowDefinition Height="14" />+ <RowDefinition Height="*" />+ <RowDefinition Height="14" />+ </Grid.RowDefinitions>+ <RepeatButton Grid.Row="0" Style="{StaticResource ScrollBarLineButtonStyle}"+ Command="{x:Static ScrollBar.LineUpCommand}" Content="{StaticResource ArrowUpGeometry}" />+ <Track x:Name="PART_Track" Grid.Row="1" IsDirectionReversed="True">+ <Track.DecreaseRepeatButton>+ <RepeatButton Style="{StaticResource ScrollBarPageButtonStyle}" Command="{x:Static ScrollBar.PageUpCommand}" />+ </Track.DecreaseRepeatButton>+ <Track.Thumb>+ <Thumb Style="{StaticResource ScrollBarThumbStyle}" />+ </Track.Thumb>+ <Track.IncreaseRepeatButton>+ <RepeatButton Style="{StaticResource ScrollBarPageButtonStyle}" Command="{x:Static ScrollBar.PageDownCommand}" />+ </Track.IncreaseRepeatButton>+ </Track>+ <RepeatButton Grid.Row="2" Style="{StaticResource ScrollBarLineButtonStyle}"+ Command="{x:Static ScrollBar.LineDownCommand}" Content="{StaticResource ArrowDownGeometry}" />+ </Grid>+ </ControlTemplate>++ <ControlTemplate x:Key="HorizontalScrollBarTemplate" TargetType="{x:Type ScrollBar}">+ <Grid Background="{TemplateBinding Background}">+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="14" />+ <ColumnDefinition Width="*" />+ <ColumnDefinition Width="14" />+ </Grid.ColumnDefinitions>+ <RepeatButton Grid.Column="0" Style="{StaticResource ScrollBarLineButtonStyle}"+ Command="{x:Static ScrollBar.LineLeftCommand}" Content="{StaticResource ArrowLeftGeometry}" />+ <Track x:Name="PART_Track" Grid.Column="1" IsDirectionReversed="False">+ <Track.DecreaseRepeatButton>+ <RepeatButton Style="{StaticResource ScrollBarPageButtonStyle}" Command="{x:Static ScrollBar.PageLeftCommand}" />+ </Track.DecreaseRepeatButton>+ <Track.Thumb>+ <Thumb Style="{StaticResource ScrollBarThumbStyle}" />+ </Track.Thumb>+ <Track.IncreaseRepeatButton>+ <RepeatButton Style="{StaticResource ScrollBarPageButtonStyle}" Command="{x:Static ScrollBar.PageRightCommand}" />+ </Track.IncreaseRepeatButton>+ </Track>+ <RepeatButton Grid.Column="2" Style="{StaticResource ScrollBarLineButtonStyle}"+ Command="{x:Static ScrollBar.LineRightCommand}" Content="{StaticResource ArrowRightGeometry}" />+ </Grid>+ </ControlTemplate>++ <Style TargetType="{x:Type ScrollBar}">+ <Setter Property="Background" Value="{DynamicResource ScrollBarBackground}" />+ <Setter Property="Width" Value="14" />+ <Setter Property="MinWidth" Value="14" />+ <Setter Property="Template" Value="{StaticResource VerticalScrollBarTemplate}" />+ <Style.Triggers>+ <Trigger Property="Orientation" Value="Horizontal">+ <Setter Property="Width" Value="Auto" />+ <Setter Property="MinWidth" Value="0" />+ <Setter Property="Height" Value="14" />+ <Setter Property="MinHeight" Value="14" />+ <Setter Property="Template" Value="{StaticResource HorizontalScrollBarTemplate}" />+ </Trigger>+ </Style.Triggers>+ </Style>++ <!-- ===================== tree view ===================== -->+ <Style TargetType="{x:Type TreeView}">+ <Setter Property="Background" Value="{DynamicResource TreeViewBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource TreeViewForeground}" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="Padding" Value="2" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type TreeView}">+ <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}">+ <ScrollViewer Focusable="False" CanContentScroll="False" Padding="{TemplateBinding Padding}"+ HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">+ <ItemsPresenter />+ </ScrollViewer>+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style x:Key="TreeViewToggleStyle" TargetType="{x:Type ToggleButton}">+ <Setter Property="Focusable" Value="False" />+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ToggleButton}">+ <Border Background="Transparent" Width="16" Height="16">+ <Path x:Name="Glyph" Data="{StaticResource ChevronRightGeometry}" Stroke="{DynamicResource TreeViewGlyph}"+ StrokeThickness="1" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="2,0,0,0" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Glyph" Property="Data" Value="{StaticResource ChevronDownGeometry}" />+ <Setter TargetName="Glyph" Property="Margin" Value="0,2,0,0" />+ </Trigger>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Glyph" Property="Stroke" Value="{DynamicResource TreeViewGlyphHover}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style TargetType="{x:Type TreeViewItem}">+ <Setter Property="Foreground" Value="{DynamicResource TreeViewForeground}" />+ <Setter Property="Background" Value="Transparent" />+ <Setter Property="Padding" Value="3,1" />+ <Setter Property="HorizontalContentAlignment" Value="Left" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type TreeViewItem}">+ <Grid>+ <Grid.ColumnDefinitions>+ <ColumnDefinition Width="16" />+ <ColumnDefinition Width="*" />+ </Grid.ColumnDefinitions>+ <Grid.RowDefinitions>+ <RowDefinition Height="Auto" />+ <RowDefinition />+ </Grid.RowDefinitions>+ <ToggleButton x:Name="Expander" Style="{StaticResource TreeViewToggleStyle}" ClickMode="Press"+ IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" />+ <Border x:Name="Bd" Grid.Column="1" Background="{TemplateBinding Background}"+ Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <ContentPresenter x:Name="PART_Header" ContentSource="Header"+ HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" />+ </Border>+ <ItemsPresenter x:Name="ItemsHost" Grid.Row="1" Grid.Column="1" />+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsExpanded" Value="False">+ <Setter TargetName="ItemsHost" Property="Visibility" Value="Collapsed" />+ </Trigger>+ <Trigger Property="HasItems" Value="False">+ <Setter TargetName="Expander" Property="Visibility" Value="Hidden" />+ </Trigger>+ <Trigger SourceName="Bd" Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource TreeViewItemHover}" />+ </Trigger>+ <Trigger Property="IsSelected" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource TreeViewItemSelected}" />+ <Setter Property="Foreground" Value="{DynamicResource TreeViewItemSelectedForeground}" />+ </Trigger>+ <MultiTrigger>+ <MultiTrigger.Conditions>+ <Condition Property="IsSelected" Value="True" />+ <Condition Property="IsSelectionActive" Value="False" />+ </MultiTrigger.Conditions>+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource TreeViewItemSelectedInactive}" />+ <Setter Property="Foreground" Value="{DynamicResource TreeViewItemSelectedInactiveForeground}" />+ </MultiTrigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- ===================== splitter ===================== -->+ <Style TargetType="{x:Type GridSplitter}">+ <Setter Property="Background" Value="{DynamicResource SplitterBackground}" />+ <Setter Property="ShowsPreview" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type GridSplitter}">+ <Border Background="{TemplateBinding Background}" />+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- ===================== buttons ===================== -->+ <Style TargetType="{x:Type Button}">+ <Setter Property="Background" Value="{DynamicResource ButtonBackground}" />+ <Setter Property="BorderBrush" Value="{DynamicResource ButtonBorder}" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="Padding" Value="10,3" />+ <Setter Property="MinHeight" Value="23" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Button}">+ <Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ <Trigger Property="IsPressed" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonPressed}" />+ <Setter Property="Foreground" Value="White" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- 16x16 glyph button for pane title bars. Background = hover colour, Content = geometry. -->+ <Style x:Key="DockHeaderButtonStyle" TargetType="{x:Type Button}">+ <Setter Property="Width" Value="16" />+ <Setter Property="Height" Value="16" />+ <Setter Property="Margin" Value="1,0" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Button}">+ <Border x:Name="Bd" Background="Transparent" SnapsToDevicePixels="True">+ <Path Data="{TemplateBinding Content}" Fill="{TemplateBinding Foreground}"+ HorizontalAlignment="Center" VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{Binding Background, RelativeSource={RelativeSource TemplatedParent}}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- ===================== tool tip ===================== -->+ <Style TargetType="{x:Type ToolTip}">+ <Setter Property="Background" Value="{DynamicResource ToolTipBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="BorderBrush" Value="{DynamicResource ToolTipBorder}" />+ <Setter Property="HasDropShadow" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ToolTip}">+ <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="1" Padding="6,3">+ <ContentPresenter />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- ===================== docking ===================== -->+ <Style x:Key="DockToolTabStripStyle" TargetType="{x:Type ListBox}">+ <Setter Property="Background" Value="{DynamicResource ToolTabBackground}" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="Padding" Value="0" />+ <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled" />+ <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Disabled" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ListBox}">+ <Border Background="{TemplateBinding Background}">+ <ItemsPresenter />+ </Border>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ <Setter Property="ItemsPanel">+ <Setter.Value>+ <ItemsPanelTemplate>+ <StackPanel Orientation="Horizontal" />+ </ItemsPanelTemplate>+ </Setter.Value>+ </Setter>+ <Setter Property="ItemTemplate">+ <Setter.Value>+ <DataTemplate>+ <TextBlock Text="{Binding Title}" />+ </DataTemplate>+ </Setter.Value>+ </Setter>+ <Setter Property="ItemContainerStyle">+ <Setter.Value>+ <Style TargetType="{x:Type ListBoxItem}">+ <Setter Property="Foreground" Value="{DynamicResource ToolTabForeground}" />+ <Setter Property="Padding" Value="6,2" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ListBoxItem}">+ <Border x:Name="Bd" Background="Transparent" BorderBrush="Transparent" BorderThickness="1,0,1,1"+ Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <ContentPresenter />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter Property="Foreground" Value="{DynamicResource ToolTabHoverForeground}" />+ </Trigger>+ <Trigger Property="IsSelected" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ToolTabSelectedBackground}" />+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource ToolWindowBorder}" />+ <Setter Property="Foreground" Value="{DynamicResource ToolTabSelectedForeground}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- Control resets the inherited foreground to the system colour; keep hosted text themed -->+ <Style TargetType="{x:Type UserControl}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ </Style>+ <Style TargetType="{x:Type ContentControl}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ </Style>++ <Style TargetType="{x:Type docking:DockGroupControl}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type docking:DockGroupControl}">+ <Border Background="{DynamicResource ToolWindowBackground}" BorderBrush="{DynamicResource ToolWindowBorder}"+ BorderThickness="1" SnapsToDevicePixels="True">+ <DockPanel>+ <Border x:Name="PART_TitleBar" DockPanel.Dock="Top" Height="21"+ Background="{DynamicResource TitleBarInactiveBackground}"+ TextElement.Foreground="{DynamicResource TitleBarInactiveForeground}">+ <DockPanel Margin="5,0,2,0">+ <StackPanel DockPanel.Dock="Right" Orientation="Horizontal" VerticalAlignment="Center">+ <Button x:Name="PART_MenuButton" Style="{StaticResource DockHeaderButtonStyle}"+ Content="{StaticResource DropDownGeometry}" ToolTip="Window position"+ AutomationProperties.Name="Window position"+ Foreground="{DynamicResource TitleBarInactiveForeground}"+ Background="{DynamicResource TitleBarButtonHoverInactive}">+ <Button.ContextMenu>+ <!-- The popup is outside the visual tree; route the commands to the pane via the placement target. -->+ <ContextMenu>+ <ContextMenu.Resources>+ <Style TargetType="{x:Type MenuItem}" BasedOn="{StaticResource {x:Type MenuItem}}">+ <Setter Property="CommandTarget" Value="{Binding PlacementTarget, RelativeSource={RelativeSource AncestorType={x:Type ContextMenu}}}" />+ </Style>+ </ContextMenu.Resources>+ <MenuItem Header="Move to _Left" Command="{x:Static docking:DockCommands.MoveToSide}" CommandParameter="{x:Static docking:DockSide.Left}" />+ <MenuItem Header="Move to _Right" Command="{x:Static docking:DockCommands.MoveToSide}" CommandParameter="{x:Static docking:DockSide.Right}" />+ <MenuItem Header="Move to _Top" Command="{x:Static docking:DockCommands.MoveToSide}" CommandParameter="{x:Static docking:DockSide.Top}" />+ <MenuItem Header="Move to _Bottom" Command="{x:Static docking:DockCommands.MoveToSide}" CommandParameter="{x:Static docking:DockSide.Bottom}" />+ <Separator />+ <MenuItem Header="_Close" Command="{x:Static docking:DockCommands.Close}" />+ </ContextMenu>+ </Button.ContextMenu>+ </Button>+ <Button x:Name="PART_CloseButton" Style="{StaticResource DockHeaderButtonStyle}"+ Content="{StaticResource CloseGeometry}" ToolTip="Close"+ AutomationProperties.Name="Close"+ Command="{x:Static docking:DockCommands.Close}"+ Foreground="{DynamicResource TitleBarInactiveForeground}"+ Background="{DynamicResource TitleBarButtonHoverInactive}"+ Visibility="{Binding Group.ActiveItem.CanClose, RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource BoolToVisibility}}" />+ </StackPanel>+ <TextBlock DockPanel.Dock="Left" Text="{Binding Group.ActiveItem.Title, RelativeSource={RelativeSource TemplatedParent}}" VerticalAlignment="Center"+ TextTrimming="CharacterEllipsis" />+ <Rectangle x:Name="Grip" Height="5" Margin="6,0,4,0" VerticalAlignment="Center"+ Fill="{StaticResource DockGripInactiveBrush}" />+ </DockPanel>+ </Border>+ <ListBox x:Name="PART_Tabs" DockPanel.Dock="Bottom" Style="{StaticResource DockToolTabStripStyle}"+ ItemsSource="{Binding Group.Items, RelativeSource={RelativeSource TemplatedParent}}" SelectedItem="{Binding Group.ActiveItem, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}" />+ <ContentPresenter x:Name="PART_Content" Content="{Binding Group.ActiveItem.Content, RelativeSource={RelativeSource TemplatedParent}}" />+ </DockPanel>+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsActive" Value="True">+ <Setter TargetName="PART_TitleBar" Property="Background" Value="{DynamicResource TitleBarActiveBackground}" />+ <Setter TargetName="PART_TitleBar" Property="TextElement.Foreground" Value="{DynamicResource TitleBarActiveForeground}" />+ <Setter TargetName="PART_MenuButton" Property="Foreground" Value="{DynamicResource TitleBarActiveForeground}" />+ <Setter TargetName="PART_MenuButton" Property="Background" Value="{DynamicResource TitleBarButtonHoverActive}" />+ <Setter TargetName="PART_CloseButton" Property="Foreground" Value="{DynamicResource TitleBarActiveForeground}" />+ <Setter TargetName="PART_CloseButton" Property="Background" Value="{DynamicResource TitleBarButtonHoverActive}" />+ <Setter TargetName="Grip" Property="Fill" Value="{StaticResource DockGripActiveBrush}" />+ </Trigger>+ <!-- in ControlTemplate.Triggers a binding is evaluated on the templated control, so Self is the control -->+ <DataTrigger Binding="{Binding Group.Items.Count, RelativeSource={RelativeSource Self}}" Value="1">+ <Setter TargetName="PART_Tabs" Property="Visibility" Value="Collapsed" />+ </DataTrigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++</ResourceDictionary>diff --git a/WaveDude.WPF/Themes/Dark.xaml b/WaveDude.WPF/Themes/Dark.xamlnew file mode 100644index 0000000..67cd768--- /dev/null+++ b/WaveDude.WPF/Themes/Dark.xaml@@ -0,0 +1,117 @@+<!-- Dark colour table (Visual Studio dark values). Keys must match Light.xaml exactly. -->+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <!-- window / general -->+ <SolidColorBrush x:Key="WindowBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="WindowForeground" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="GrayText" Color="#FF999999" />+ <SolidColorBrush x:Key="ControlBorder" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="ControlShadow" Color="#71000000" />+ <SolidColorBrush x:Key="Accent" Color="#FF007ACC" />++ <!-- menus -->+ <SolidColorBrush x:Key="MenuBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="MenuForeground" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="MenuPopupBackground" Color="#FF1B1B1C" />+ <SolidColorBrush x:Key="MenuPopupBorder" Color="#FF333337" />+ <SolidColorBrush x:Key="MenuItemHover" Color="#FF333334" />+ <SolidColorBrush x:Key="MenuItemHoverForeground" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="MenuSeparator" Color="#FF333337" />+ <SolidColorBrush x:Key="MenuGlyph" Color="#FF999999" />+ <SolidColorBrush x:Key="MenuGlyphHover" Color="#FF007ACC" />++ <!-- status bar -->+ <SolidColorBrush x:Key="StatusBarBackground" Color="#FF007ACC" />+ <SolidColorBrush x:Key="StatusBarForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="StatusBarWarnForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="StatusBarWarnBackground" Color="#FFCA5100" />+ <SolidColorBrush x:Key="StatusBarErrorForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="StatusBarErrorBackground" Color="#FFB4211D" />++ <!-- tool windows -->+ <SolidColorBrush x:Key="ToolWindowBackground" Color="#FF252526" />+ <SolidColorBrush x:Key="ToolWindowBorder" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="TitleBarActiveBackground" Color="#FF007ACC" />+ <SolidColorBrush x:Key="TitleBarActiveForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="TitleBarInactiveBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="TitleBarInactiveForeground" Color="#FFD0D0D0" />+ <SolidColorBrush x:Key="TitleBarDragHandleActive" Color="#FF59A8DE" />+ <SolidColorBrush x:Key="TitleBarDragHandleInactive" Color="#FF46464A" />+ <SolidColorBrush x:Key="TitleBarButtonHoverActive" Color="#FF1C97EA" />+ <SolidColorBrush x:Key="TitleBarButtonHoverInactive" Color="#FF3E3E40" />++ <!-- tool window tabs (bottom strip) -->+ <SolidColorBrush x:Key="ToolTabBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="ToolTabForeground" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="ToolTabSelectedBackground" Color="#FF252526" />+ <SolidColorBrush x:Key="ToolTabSelectedForeground" Color="#FF0097FB" />+ <SolidColorBrush x:Key="ToolTabHoverForeground" Color="#FF55AAFF" />++ <!-- document tabs (top strip) -->+ <SolidColorBrush x:Key="DocTabBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="DocTabInactiveBackground" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="DocTabInactiveForeground" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="DocTabSelectedBackground" Color="#FF007ACC" />+ <SolidColorBrush x:Key="DocTabSelectedForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="DocTabHotBackground" Color="#FF1C97EA" />+ <SolidColorBrush x:Key="DocTabHotForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="DocumentBackground" Color="#FF1E1E1E" />++ <!-- tree view -->+ <SolidColorBrush x:Key="TreeViewBackground" Color="#FF252526" />+ <SolidColorBrush x:Key="TreeViewForeground" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="TreeViewItemHover" Color="#FF3E3E40" />+ <SolidColorBrush x:Key="TreeViewItemSelected" Color="#FF3399FF" />+ <SolidColorBrush x:Key="TreeViewItemSelectedForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="TreeViewItemSelectedInactive" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="TreeViewItemSelectedInactiveForeground" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="TreeViewGlyph" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="TreeViewGlyphHover" Color="#FF007ACC" />++ <!-- scroll bars -->+ <SolidColorBrush x:Key="ScrollBarBackground" Color="#FF3E3E42" />+ <SolidColorBrush x:Key="ScrollBarThumb" Color="#FF686868" />+ <SolidColorBrush x:Key="ScrollBarThumbHover" Color="#FF9E9E9E" />+ <SolidColorBrush x:Key="ScrollBarThumbPressed" Color="#FFEFEBEF" />+ <SolidColorBrush x:Key="ScrollBarArrow" Color="#FF999999" />+ <SolidColorBrush x:Key="ScrollBarArrowHover" Color="#FF1C97EA" />+ <SolidColorBrush x:Key="ScrollBarArrowPressed" Color="#FF007ACC" />++ <!-- splitters and drag/drop -->+ <SolidColorBrush x:Key="SplitterBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="DropIndicatorBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="DropIndicatorBorder" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="DropIndicatorGlyph" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="DropIndicatorHot" Color="#FF007ACC" />+ <SolidColorBrush x:Key="DropPreviewFill" Color="#60007ACC" />+ <SolidColorBrush x:Key="DropPreviewBorder" Color="#FF007ACC" />++ <!-- buttons / inputs -->+ <SolidColorBrush x:Key="ButtonBackground" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="ButtonBorder" Color="#FF555558" />+ <SolidColorBrush x:Key="ButtonHover" Color="#FF4F4F56" />+ <SolidColorBrush x:Key="ButtonPressed" Color="#FF007ACC" />+ <SolidColorBrush x:Key="ToolTipBackground" Color="#FF2D2D30" />+ <SolidColorBrush x:Key="ToolTipBorder" Color="#FF3F3F46" />++ <!-- editors -->+ <SolidColorBrush x:Key="TextBoxBackground" Color="#FF333337" />+ <SolidColorBrush x:Key="TextBoxBorder" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="TextBoxHoverBorder" Color="#FF5A5A5E" />+ <SolidColorBrush x:Key="ComboBoxBackground" Color="#FF333337" />+ <SolidColorBrush x:Key="ComboBoxBorder" Color="#FF434346" />+ <SolidColorBrush x:Key="ComboBoxHover" Color="#FF3F3F46" />+ <SolidColorBrush x:Key="ComboBoxGlyph" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="CheckBoxBackground" Color="#FF333337" />+ <SolidColorBrush x:Key="CheckBoxBorder" Color="#FF6D6D70" />++ <!-- log levels (Messages pane) -->+ <SolidColorBrush x:Key="LogTrace" Color="#FF808080" />+ <SolidColorBrush x:Key="LogDebug" Color="#FF9B9B9B" />+ <SolidColorBrush x:Key="LogInfo" Color="#FFF1F1F1" />+ <SolidColorBrush x:Key="LogWarn" Color="#FFE5C07B" />+ <SolidColorBrush x:Key="LogError" Color="#FFF14C4C" />+ <SolidColorBrush x:Key="LogFatal" Color="#FFFF3B3B" />++</ResourceDictionary>diff --git a/WaveDude.WPF/Themes/Editors.xaml b/WaveDude.WPF/Themes/Editors.xamlnew file mode 100644index 0000000..2d937ca--- /dev/null+++ b/WaveDude.WPF/Themes/Editors.xaml@@ -0,0 +1,268 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:converters="clr-namespace:WaveDude.WPF.Converters">++ <!-- editors used by the property views: VS look, colours from the theme table -->++ <Style TargetType="{x:Type TextBox}">+ <Setter Property="Background" Value="{DynamicResource TextBoxBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="BorderBrush" Value="{DynamicResource TextBoxBorder}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="Padding" Value="3,2" />+ <Setter Property="MinHeight" Value="22" />+ <Setter Property="VerticalContentAlignment" Value="Center" />+ <Setter Property="CaretBrush" Value="{DynamicResource WindowForeground}" />+ <Setter Property="SelectionBrush" Value="{DynamicResource Accent}" />+ <Setter Property="AllowDrop" Value="True" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type TextBox}">+ <Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">+ <ScrollViewer x:Name="PART_ContentHost" Margin="{TemplateBinding Padding}" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource TextBoxHoverBorder}" />+ </Trigger>+ <Trigger Property="IsKeyboardFocusWithin" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource WindowBackground}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style TargetType="{x:Type CheckBox}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="VerticalContentAlignment" Value="Center" />+ <Setter Property="MinHeight" Value="22" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type CheckBox}">+ <StackPanel Orientation="Horizontal" VerticalAlignment="Center" Background="Transparent">+ <Border x:Name="Box" Width="14" Height="14" Background="{DynamicResource CheckBoxBackground}"+ BorderBrush="{DynamicResource CheckBoxBorder}" BorderThickness="1" SnapsToDevicePixels="True">+ <Path x:Name="Glyph" Data="{StaticResource CheckGeometry}" Stroke="{DynamicResource WindowForeground}"+ StrokeThickness="1.5" Stretch="Uniform" Margin="2" Visibility="Collapsed" />+ </Border>+ <ContentPresenter Margin="6,0,0,0" VerticalAlignment="Center" RecognizesAccessKey="True" />+ </StackPanel>+ <ControlTemplate.Triggers>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Glyph" Property="Visibility" Value="Visible" />+ </Trigger>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Box" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsKeyboardFocused" Value="True">+ <Setter TargetName="Box" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ <Setter TargetName="Glyph" Property="Stroke" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style TargetType="{x:Type ComboBoxItem}">+ <Setter Property="Foreground" Value="{DynamicResource MenuForeground}" />+ <Setter Property="Padding" Value="6,3" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ComboBoxItem}">+ <Border x:Name="Bd" Background="Transparent" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <ContentPresenter VerticalAlignment="Center" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsHighlighted" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource MenuItemHover}" />+ <Setter Property="Foreground" Value="{DynamicResource MenuItemHoverForeground}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style TargetType="{x:Type ComboBox}">+ <Setter Property="Background" Value="{DynamicResource ComboBoxBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="BorderBrush" Value="{DynamicResource ComboBoxBorder}" />+ <Setter Property="BorderThickness" Value="1" />+ <Setter Property="Padding" Value="4,2" />+ <Setter Property="MinHeight" Value="22" />+ <Setter Property="MaxDropDownHeight" Value="300" />+ <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ComboBox}">+ <Grid>+ <ToggleButton x:Name="Toggle" Focusable="False" ClickMode="Press"+ BorderBrush="{Binding BorderBrush, RelativeSource={RelativeSource TemplatedParent}}"+ IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">+ <ToggleButton.Template>+ <ControlTemplate TargetType="{x:Type ToggleButton}">+ <Border x:Name="Bd" Background="{DynamicResource ComboBoxBackground}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="1" SnapsToDevicePixels="True">+ <Path Data="{StaticResource DropDownGeometry}" Fill="{DynamicResource ComboBoxGlyph}"+ HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0,0,6,0" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ComboBoxHover}" />+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource TextBoxHoverBorder}" />+ </Trigger>+ <Trigger Property="IsChecked" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </ToggleButton.Template>+ </ToggleButton>+ <ContentPresenter x:Name="Selection" Content="{TemplateBinding SelectionBoxItem}"+ ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"+ ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}"+ Margin="{TemplateBinding Padding}" VerticalAlignment="Center"+ HorizontalAlignment="Left" IsHitTestVisible="False" />+ <!-- the text box of an editable combo (IsEditable); leaves the drop-down glyph its 18 px on the right -->+ <TextBox x:Name="PART_EditableTextBox" Visibility="Collapsed" Margin="0,0,18,0" BorderThickness="0" Background="Transparent"+ Padding="{TemplateBinding Padding}" IsReadOnly="{TemplateBinding IsReadOnly}" />+ <Popup x:Name="PART_Popup" Placement="Bottom" IsOpen="{TemplateBinding IsDropDownOpen}"+ AllowsTransparency="True" PopupAnimation="None" Focusable="False">+ <Border Background="{DynamicResource MenuPopupBackground}" BorderBrush="{DynamicResource MenuPopupBorder}"+ BorderThickness="1" MinWidth="{TemplateBinding ActualWidth}" MaxHeight="{TemplateBinding MaxDropDownHeight}"+ SnapsToDevicePixels="True">+ <ScrollViewer>+ <ItemsPresenter KeyboardNavigation.DirectionalNavigation="Contained" />+ </ScrollViewer>+ </Border>+ </Popup>+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsEditable" Value="True">+ <Setter TargetName="PART_EditableTextBox" Property="Visibility" Value="Visible" />+ <Setter TargetName="Selection" Property="Visibility" Value="Collapsed" />+ </Trigger>+ <!-- keyboard focus (on the combo or inside its text box) shows like a focused text box -->+ <Trigger Property="IsKeyboardFocusWithin" Value="True">+ <Setter TargetName="Toggle" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- horizontal slider: thin track, flat thumb; a click on the track jumps there -->+ <Style x:Key="SliderTrackButtonStyle" TargetType="{x:Type RepeatButton}">+ <Setter Property="Focusable" Value="False" />+ <Setter Property="IsTabStop" Value="False" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type RepeatButton}">+ <Border Background="Transparent" />+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style x:Key="SliderThumbStyle" TargetType="{x:Type Thumb}">+ <Setter Property="Width" Value="10" />+ <Setter Property="Height" Value="18" />+ <Setter Property="Focusable" Value="False" />+ <Setter Property="BorderBrush" Value="{DynamicResource ButtonBorder}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Thumb}">+ <Border x:Name="Bd" Background="{DynamicResource ButtonBackground}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="1" SnapsToDevicePixels="True" />+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsDragging" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonPressed}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>+ <Style TargetType="{x:Type Slider}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="IsMoveToPointEnabled" Value="True" />+ <Setter Property="MinHeight" Value="22" />+ <Setter Property="FocusVisualStyle" Value="{x:Null}" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type Slider}">+ <Grid Height="18" VerticalAlignment="Center">+ <Border Height="4" VerticalAlignment="Center" Background="{DynamicResource ScrollBarBackground}"+ BorderBrush="{DynamicResource ControlBorder}" BorderThickness="1" SnapsToDevicePixels="True" />+ <Track x:Name="PART_Track">+ <Track.DecreaseRepeatButton>+ <RepeatButton Style="{StaticResource SliderTrackButtonStyle}" Command="Slider.DecreaseLarge" />+ </Track.DecreaseRepeatButton>+ <Track.IncreaseRepeatButton>+ <RepeatButton Style="{StaticResource SliderTrackButtonStyle}" Command="Slider.IncreaseLarge" />+ </Track.IncreaseRepeatButton>+ <Track.Thumb>+ <Thumb x:Name="Thumb" Style="{StaticResource SliderThumbStyle}" />+ </Track.Thumb>+ </Track>+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsKeyboardFocused" Value="True">+ <Setter TargetName="Thumb" Property="BorderBrush" Value="{DynamicResource Accent}" />+ </Trigger>+ <Trigger Property="IsEnabled" Value="False">+ <Setter Property="Opacity" Value="0.5" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- enum pickers show the values as words ("Smoothed square") -->+ <converters:EnumNameConverter x:Key="EnumName" />+ <Style x:Key="EnumComboBox" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">+ <Setter Property="ItemTemplate">+ <Setter.Value>+ <DataTemplate>+ <TextBlock Text="{Binding Converter={StaticResource EnumName}}" />+ </DataTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <!-- property forms -->+ <Style x:Key="FormSection" TargetType="{x:Type TextBlock}">+ <Setter Property="FontWeight" Value="SemiBold" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="Margin" Value="0,10,0,4" />+ </Style>+ <Style x:Key="FormLabel" TargetType="{x:Type TextBlock}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="TextTrimming" Value="CharacterEllipsis" />+ </Style>+ <Style x:Key="FormValue" TargetType="{x:Type TextBlock}">+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ <Setter Property="VerticalAlignment" Value="Center" />+ <Setter Property="Margin" Value="4,0" />+ </Style>++</ResourceDictionary>diff --git a/WaveDude.WPF/Themes/Light.xaml b/WaveDude.WPF/Themes/Light.xamlnew file mode 100644index 0000000..e9731cd--- /dev/null+++ b/WaveDude.WPF/Themes/Light.xaml@@ -0,0 +1,117 @@+<!-- Light colour table (Visual Studio light values). Keys must match Dark.xaml exactly. -->+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <!-- window / general -->+ <SolidColorBrush x:Key="WindowBackground" Color="#FFEEEEF2" />+ <SolidColorBrush x:Key="WindowForeground" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="GrayText" Color="#FFA2A4A5" />+ <SolidColorBrush x:Key="ControlBorder" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="ControlShadow" Color="#40000000" />+ <SolidColorBrush x:Key="Accent" Color="#FF007ACC" />++ <!-- menus -->+ <SolidColorBrush x:Key="MenuBackground" Color="#FFEEEEF2" />+ <SolidColorBrush x:Key="MenuForeground" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="MenuPopupBackground" Color="#FFF6F6F6" />+ <SolidColorBrush x:Key="MenuPopupBorder" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="MenuItemHover" Color="#FFC9DEF5" />+ <SolidColorBrush x:Key="MenuItemHoverForeground" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="MenuSeparator" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="MenuGlyph" Color="#FF717171" />+ <SolidColorBrush x:Key="MenuGlyphHover" Color="#FF007ACC" />++ <!-- status bar -->+ <SolidColorBrush x:Key="StatusBarBackground" Color="#FF007ACC" />+ <SolidColorBrush x:Key="StatusBarForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="StatusBarWarnForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="StatusBarWarnBackground" Color="#FFCA5100" />+ <SolidColorBrush x:Key="StatusBarErrorForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="StatusBarErrorBackground" Color="#FFB4211D" />++ <!-- tool windows -->+ <SolidColorBrush x:Key="ToolWindowBackground" Color="#FFF5F5F5" />+ <SolidColorBrush x:Key="ToolWindowBorder" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="TitleBarActiveBackground" Color="#FF007ACC" />+ <SolidColorBrush x:Key="TitleBarActiveForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="TitleBarInactiveBackground" Color="#FFEEEEF2" />+ <SolidColorBrush x:Key="TitleBarInactiveForeground" Color="#FF444444" />+ <SolidColorBrush x:Key="TitleBarDragHandleActive" Color="#FF59A8DE" />+ <SolidColorBrush x:Key="TitleBarDragHandleInactive" Color="#FF999999" />+ <SolidColorBrush x:Key="TitleBarButtonHoverActive" Color="#FF1C97EA" />+ <SolidColorBrush x:Key="TitleBarButtonHoverInactive" Color="#FFF7F7F9" />++ <!-- tool window tabs (bottom strip) -->+ <SolidColorBrush x:Key="ToolTabBackground" Color="#FFEEEEF2" />+ <SolidColorBrush x:Key="ToolTabForeground" Color="#FF444444" />+ <SolidColorBrush x:Key="ToolTabSelectedBackground" Color="#FFF5F5F5" />+ <SolidColorBrush x:Key="ToolTabSelectedForeground" Color="#FF0E70C0" />+ <SolidColorBrush x:Key="ToolTabHoverForeground" Color="#FF1C97EA" />++ <!-- document tabs (top strip) -->+ <SolidColorBrush x:Key="DocTabBackground" Color="#FFEEEEF2" />+ <SolidColorBrush x:Key="DocTabInactiveBackground" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="DocTabInactiveForeground" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="DocTabSelectedBackground" Color="#FF007ACC" />+ <SolidColorBrush x:Key="DocTabSelectedForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="DocTabHotBackground" Color="#FF1C97EA" />+ <SolidColorBrush x:Key="DocTabHotForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="DocumentBackground" Color="#FFFFFFFF" />++ <!-- tree view -->+ <SolidColorBrush x:Key="TreeViewBackground" Color="#FFF5F5F5" />+ <SolidColorBrush x:Key="TreeViewForeground" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="TreeViewItemHover" Color="#FFE5E5E5" />+ <SolidColorBrush x:Key="TreeViewItemSelected" Color="#FF3399FF" />+ <SolidColorBrush x:Key="TreeViewItemSelectedForeground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="TreeViewItemSelectedInactive" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="TreeViewItemSelectedInactiveForeground" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="TreeViewGlyph" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="TreeViewGlyphHover" Color="#FF007ACC" />++ <!-- scroll bars -->+ <SolidColorBrush x:Key="ScrollBarBackground" Color="#FFE8E8EC" />+ <SolidColorBrush x:Key="ScrollBarThumb" Color="#FFC2C3C9" />+ <SolidColorBrush x:Key="ScrollBarThumbHover" Color="#FF686868" />+ <SolidColorBrush x:Key="ScrollBarThumbPressed" Color="#FF5B5B5B" />+ <SolidColorBrush x:Key="ScrollBarArrow" Color="#FF868999" />+ <SolidColorBrush x:Key="ScrollBarArrowHover" Color="#FF1C97EA" />+ <SolidColorBrush x:Key="ScrollBarArrowPressed" Color="#FF007ACC" />++ <!-- splitters and drag/drop -->+ <SolidColorBrush x:Key="SplitterBackground" Color="#FFEEEEF2" />+ <SolidColorBrush x:Key="DropIndicatorBackground" Color="#FFF6F6F6" />+ <SolidColorBrush x:Key="DropIndicatorBorder" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="DropIndicatorGlyph" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="DropIndicatorHot" Color="#FF007ACC" />+ <SolidColorBrush x:Key="DropPreviewFill" Color="#60007ACC" />+ <SolidColorBrush x:Key="DropPreviewBorder" Color="#FF007ACC" />++ <!-- buttons / inputs -->+ <SolidColorBrush x:Key="ButtonBackground" Color="#FFECECF0" />+ <SolidColorBrush x:Key="ButtonBorder" Color="#FFACACAC" />+ <SolidColorBrush x:Key="ButtonHover" Color="#FFC9DEF5" />+ <SolidColorBrush x:Key="ButtonPressed" Color="#FF007ACC" />+ <SolidColorBrush x:Key="ToolTipBackground" Color="#FFF6F6F6" />+ <SolidColorBrush x:Key="ToolTipBorder" Color="#FFCCCEDB" />++ <!-- editors -->+ <SolidColorBrush x:Key="TextBoxBackground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="TextBoxBorder" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="TextBoxHoverBorder" Color="#FFA0A0A8" />+ <SolidColorBrush x:Key="ComboBoxBackground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="ComboBoxBorder" Color="#FFCCCEDB" />+ <SolidColorBrush x:Key="ComboBoxHover" Color="#FFE6E7ED" />+ <SolidColorBrush x:Key="ComboBoxGlyph" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="CheckBoxBackground" Color="#FFFFFFFF" />+ <SolidColorBrush x:Key="CheckBoxBorder" Color="#FF9A9A9E" />++ <!-- log levels (Messages pane) -->+ <SolidColorBrush x:Key="LogTrace" Color="#FF8A8A8A" />+ <SolidColorBrush x:Key="LogDebug" Color="#FF6E6E6E" />+ <SolidColorBrush x:Key="LogInfo" Color="#FF1E1E1E" />+ <SolidColorBrush x:Key="LogWarn" Color="#FFBF8700" />+ <SolidColorBrush x:Key="LogError" Color="#FFC50500" />+ <SolidColorBrush x:Key="LogFatal" Color="#FFA00000" />++</ResourceDictionary>diff --git a/WaveDude.WPF/Themes/Lists.xaml b/WaveDude.WPF/Themes/Lists.xamlnew file mode 100644index 0000000..857bc9c--- /dev/null+++ b/WaveDude.WPF/Themes/Lists.xaml@@ -0,0 +1,91 @@+<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <!-- list views with grid columns, Visual Studio tool-window look -->++ <Style TargetType="{x:Type ListView}">+ <Setter Property="Background" Value="{DynamicResource ToolWindowBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="BorderThickness" Value="0" />+ <Setter Property="Padding" Value="0" />+ <Setter Property="ScrollViewer.CanContentScroll" Value="True" />+ </Style>++ <Style TargetType="{x:Type ListViewItem}">+ <Setter Property="Foreground" Value="{DynamicResource WindowForeground}" />+ <Setter Property="Padding" Value="2,1" />+ <Setter Property="HorizontalContentAlignment" Value="Stretch" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type ListViewItem}">+ <Border x:Name="Bd" Background="Transparent" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <GridViewRowPresenter Content="{TemplateBinding Content}" Columns="{TemplateBinding GridView.ColumnCollection}" />+ </Border>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource TreeViewItemHover}" />+ </Trigger>+ <Trigger Property="IsSelected" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource TreeViewItemSelectedInactive}" />+ </Trigger>+ <MultiTrigger>+ <MultiTrigger.Conditions>+ <Condition Property="IsSelected" Value="True" />+ <Condition Property="Selector.IsSelectionActive" Value="True" />+ </MultiTrigger.Conditions>+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource TreeViewItemSelected}" />+ <Setter Property="Foreground" Value="{DynamicResource TreeViewItemSelectedForeground}" />+ </MultiTrigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Style>++ <Style TargetType="{x:Type GridViewColumnHeader}">+ <Setter Property="Background" Value="{DynamicResource ToolWindowBackground}" />+ <Setter Property="Foreground" Value="{DynamicResource GrayText}" />+ <Setter Property="BorderBrush" Value="{DynamicResource ControlBorder}" />+ <Setter Property="Padding" Value="4,2" />+ <Setter Property="HorizontalContentAlignment" Value="Left" />+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type GridViewColumnHeader}">+ <Grid>+ <Border x:Name="Bd" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}"+ BorderThickness="0,0,1,1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">+ <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="Center"+ RecognizesAccessKey="True" />+ </Border>+ <!-- the resize handle WPF looks for -->+ <Thumb x:Name="PART_HeaderGripper" HorizontalAlignment="Right" Width="6" Margin="0,0,-3,0" Cursor="SizeWE">+ <Thumb.Template>+ <ControlTemplate TargetType="{x:Type Thumb}">+ <Border Background="Transparent" />+ </ControlTemplate>+ </Thumb.Template>+ </Thumb>+ </Grid>+ <ControlTemplate.Triggers>+ <Trigger Property="IsMouseOver" Value="True">+ <Setter TargetName="Bd" Property="Background" Value="{DynamicResource ButtonHover}" />+ </Trigger>+ </ControlTemplate.Triggers>+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ <Style.Triggers>+ <!-- the filler header after the last column: no border, no gripper -->+ <Trigger Property="Role" Value="Padding">+ <Setter Property="Template">+ <Setter.Value>+ <ControlTemplate TargetType="{x:Type GridViewColumnHeader}">+ <Border Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="0,0,0,1" />+ </ControlTemplate>+ </Setter.Value>+ </Setter>+ </Trigger>+ </Style.Triggers>+ </Style>++</ResourceDictionary>diff --git a/WaveDude.WPF/Theming/AppTheme.cs b/WaveDude.WPF/Theming/AppTheme.csnew file mode 100644index 0000000..e8eec24--- /dev/null+++ b/WaveDude.WPF/Theming/AppTheme.cs@@ -0,0 +1,14 @@+namespace WaveDude.WPF.Theming;++/// <summary>+/// User-selectable colour theme of the application.+/// </summary>+public enum AppTheme+{+ /// <summary>Follow the Windows "app mode" setting.</summary>+ System,+ /// <summary>Always light.</summary>+ Light,+ /// <summary>Always dark.</summary>+ Dark,+}diff --git a/WaveDude.WPF/Theming/ThemeController.cs b/WaveDude.WPF/Theming/ThemeController.csnew file mode 100644index 0000000..ca1a2bf--- /dev/null+++ b/WaveDude.WPF/Theming/ThemeController.cs@@ -0,0 +1,138 @@+using System.ComponentModel;+using System.Runtime.CompilerServices;+using System.Runtime.InteropServices;+using System.Windows;+using System.Windows.Input;+using System.Windows.Interop;+using Microsoft.Win32;+using NLog;+using WaveDude.WPF.Commands;++namespace WaveDude.WPF.Theming;++/// <summary>+/// Application theme state. Switches between the colour tables in <c>Themes/Dark.xaml</c> and+/// <c>Themes/Light.xaml</c> and keeps native window title bars in step. Bind menus to+/// <see cref="Options"/>, <see cref="Current"/> and <see cref="SelectCommand"/>.+/// </summary>+/// <remarks>+/// The colour table is the first merged dictionary of the application resources; every style in+/// <c>Themes/Controls.xaml</c> reads its brushes from it through <c>DynamicResource</c>, so+/// replacing that one dictionary restyles the whole application live.+/// </remarks>+public sealed class ThemeController : INotifyPropertyChanged+{+ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();+ private const string PersonalizeKey = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize";+ private const int DwmwaUseImmersiveDarkMode = 20;+ private const string DarkSource = "/WaveDude.WPF;component/Themes/Dark.xaml";+ private const string LightSource = "/WaveDude.WPF;component/Themes/Light.xaml";++ private AppTheme _current = AppTheme.System;++ private ThemeController()+ {+ SelectCommand = new RelayCommand<AppTheme>(theme => Current = theme);+ }++ /// <summary>The single theme state of the application.</summary>+ public static ThemeController Instance { get; } = new();++ /// <summary>All selectable themes, in menu order.</summary>+ public IReadOnlyList<AppTheme> Options { get; } = Enum.GetValues<AppTheme>();++ /// <summary>Sets <see cref="Current"/> to its parameter.</summary>+ public ICommand SelectCommand { get; }++ /// <summary>The theme selected by the user. Setting it restyles the application.</summary>+ public AppTheme Current+ {+ get => _current;+ set+ {+ if (_current == value)+ {+ return;+ }+ _current = value;+ Logger.Info("Theme changed to {Theme} (dark: {IsDark})", value, IsDark);+ ApplyResources();+ OnPropertyChanged();+ OnPropertyChanged(nameof(IsDark));+ }+ }++ /// <summary>True when the effective theme is dark, resolving <see cref="AppTheme.System"/>.</summary>+ public bool IsDark => _current switch+ {+ AppTheme.Dark => true,+ AppTheme.Light => false,+ _ => !SystemUsesLightTheme(),+ };++ /// <inheritdoc/>+ public event PropertyChangedEventHandler? PropertyChanged;++ /// <summary>Re-applies the resources for <see cref="Current"/>; call once at startup.</summary>+ public void Refresh()+ {+ Logger.Debug("Theme: {Theme} (dark: {IsDark})", _current, IsDark);+ ApplyResources();+ }++ /// <summary>+ /// Makes the native title bar of <paramref name="window"/> follow the effective theme.+ /// Call from <see cref="Window.SourceInitialized"/>; a no-op until the window has a handle.+ /// </summary>+ public void ApplyTitleBar(Window window)+ {+ IntPtr hwnd = new WindowInteropHelper(window).Handle;+ if (hwnd == IntPtr.Zero)+ {+ return;+ }+ int dark = IsDark ? 1 : 0;+ _ = DwmSetWindowAttribute(hwnd, DwmwaUseImmersiveDarkMode, ref dark, sizeof(int));+ }++ private void ApplyResources()+ {+ var table = new ResourceDictionary { Source = new Uri(IsDark ? DarkSource : LightSource, UriKind.Relative) };+ var merged = Application.Current.Resources.MergedDictionaries;+ int index = -1;+ for (int i = 0; i < merged.Count; i++)+ {+ string? source = merged[i].Source?.OriginalString;+ if (source != null && (source.EndsWith("Dark.xaml", StringComparison.OrdinalIgnoreCase)+ || source.EndsWith("Light.xaml", StringComparison.OrdinalIgnoreCase)))+ {+ index = i;+ break;+ }+ }+ if (index >= 0)+ {+ merged[index] = table;+ }+ else+ {+ merged.Insert(0, table);+ }+ foreach (Window window in Application.Current.Windows)+ {+ ApplyTitleBar(window);+ }+ }++ private static bool SystemUsesLightTheme()+ {+ using RegistryKey? key = Registry.CurrentUser.OpenSubKey(PersonalizeKey);+ return key?.GetValue("AppsUseLightTheme") is not int value || value != 0;+ }++ private void OnPropertyChanged([CallerMemberName] string? name = null) =>+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));++ [DllImport("dwmapi.dll")]+ private static extern int DwmSetWindowAttribute(IntPtr hwnd, int attribute, ref int value, int size);+}diff --git a/WaveDude.WPF/Views/CollectionView.xaml b/WaveDude.WPF/Views/CollectionView.xamlnew file mode 100644index 0000000..1ec6c78--- /dev/null+++ b/WaveDude.WPF/Views/CollectionView.xaml@@ -0,0 +1,11 @@+<UserControl x:Class="WaveDude.WPF.Views.CollectionView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">++ <!-- a folder node (Sources, Probes): just the name and the count for now -->+ <StackPanel Margin="8">+ <TextBlock Style="{StaticResource FormSection}" Text="{Binding Label}" Margin="0,2,0,4" />+ <TextBlock Style="{StaticResource FormValue}" Margin="0"+ Text="{Binding Items.Count, StringFormat={StaticResource ItemCountFormat}}" />+ </StackPanel>+</UserControl>diff --git a/WaveDude.WPF/Views/CollectionView.xaml.cs b/WaveDude.WPF/Views/CollectionView.xaml.csnew file mode 100644index 0000000..5535964--- /dev/null+++ b/WaveDude.WPF/Views/CollectionView.xaml.cs@@ -0,0 +1,12 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Views;++/// <summary>View for a folder node (<see cref="WaveDude.WPF.Converters.NamedCollection"/>): name and item count.</summary>+public partial class CollectionView : UserControl+{+ public CollectionView()+ {+ InitializeComponent();+ }+}diff --git a/WaveDude.WPF/Views/DisplayLayerView.xaml b/WaveDude.WPF/Views/DisplayLayerView.xamlnew file mode 100644index 0000000..a0728d9--- /dev/null+++ b/WaveDude.WPF/Views/DisplayLayerView.xaml@@ -0,0 +1,23 @@+<UserControl x:Class="WaveDude.WPF.Views.DisplayLayerView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:meta="clr-namespace:WaveDude.WPF.Markup"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:DisplayLayer.ColorScheme}" />+ <TextBox Text="{Binding ColorScheme, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:DisplayLayer.ColorScheme}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:DisplayLayer.Brightness}" />+ <TextBox Text="{Binding Brightness}" ToolTip="{meta:Hint model:DisplayLayer.Brightness}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:DisplayLayer.BlackLevel}" />+ <TextBox Text="{Binding BlackLevel}" ToolTip="{meta:Hint model:DisplayLayer.BlackLevel}" />++ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:DisplayLayer.Preview}"+ IsChecked="{Binding Preview}" ToolTip="{meta:Hint model:DisplayLayer.Preview}" />+ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:DisplayLayer.Export}"+ IsChecked="{Binding Export}" ToolTip="{meta:Hint model:DisplayLayer.Export}" />+ </controls:FormPanel>+</UserControl>diff --git a/WaveDude.WPF/Views/DisplayLayerView.xaml.cs b/WaveDude.WPF/Views/DisplayLayerView.xaml.csnew file mode 100644index 0000000..6354d8d--- /dev/null+++ b/WaveDude.WPF/Views/DisplayLayerView.xaml.cs@@ -0,0 +1,12 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Views;++/// <summary>Editor for one <see cref="WaveDude.Model.DisplayLayer"/>; used twice by <see cref="DisplayView"/>.</summary>+public partial class DisplayLayerView : UserControl+{+ public DisplayLayerView()+ {+ InitializeComponent();+ }+}diff --git a/WaveDude.WPF/Views/DisplayView.xaml b/WaveDude.WPF/Views/DisplayView.xamlnew file mode 100644index 0000000..ae09ad7--- /dev/null+++ b/WaveDude.WPF/Views/DisplayView.xaml@@ -0,0 +1,27 @@+<UserControl x:Class="WaveDude.WPF.Views.DisplayView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:WaveDude.WPF.Views"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:meta="clr-namespace:WaveDude.WPF.Markup"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">+ <StackPanel Margin="8">+ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionField}" />+ <local:DisplayLayerView DataContext="{Binding Field}" />++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionIntensity}" />+ <local:DisplayLayerView DataContext="{Binding Intensity}" />++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionVideo}" />+ <controls:FormPanel DataContext="{Binding Video}">+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Video.Fps}" />+ <TextBox Text="{Binding Fps}" ToolTip="{meta:Hint model:Video.Fps}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Video.Quality}" />+ <TextBox Text="{Binding Quality}" ToolTip="{meta:Hint model:Video.Quality}" />+ </controls:FormPanel>+ </StackPanel>+ </ScrollViewer>+</UserControl>diff --git a/WaveDude.WPF/Views/DisplayView.xaml.cs b/WaveDude.WPF/Views/DisplayView.xaml.csnew file mode 100644index 0000000..ceeea96--- /dev/null+++ b/WaveDude.WPF/Views/DisplayView.xaml.cs@@ -0,0 +1,12 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Views;++/// <summary>Editor for <see cref="WaveDude.Model.Display"/>: the two output layers and the video encoder.</summary>+public partial class DisplayView : UserControl+{+ public DisplayView()+ {+ InitializeComponent();+ }+}diff --git a/WaveDude.WPF/Views/ProbeView.xaml b/WaveDude.WPF/Views/ProbeView.xamlnew file mode 100644index 0000000..6f12de5--- /dev/null+++ b/WaveDude.WPF/Views/ProbeView.xaml@@ -0,0 +1,112 @@+<UserControl x:Class="WaveDude.WPF.Views.ProbeView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:meta="clr-namespace:WaveDude.WPF.Markup"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <UserControl.Resources>+ <!-- point B and the step axis only apply to line and point probes respectively -->+ <Style x:Key="LineOnly" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Kind}" Value="Point">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="PointOnlyCombo" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource EnumComboBox}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Kind}" Value="Line">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="PointOnlyCheck" TargetType="{x:Type CheckBox}" BasedOn="{StaticResource {x:Type CheckBox}}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Kind}" Value="Line">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ </UserControl.Resources>++ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">+ <StackPanel Margin="8">+ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionGeneral}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.Name}" />+ <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:Probe.Name}" />++ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Probe.Active}"+ IsChecked="{Binding Active}" ToolTip="{meta:Hint model:Probe.Active}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.StartAfter}" />+ <TextBox Text="{Binding StartAfter}" ToolTip="{meta:Hint model:Probe.StartAfter}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionMeasurement}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.Layer}" />+ <ComboBox Style="{StaticResource EnumComboBox}" ItemsSource="{meta:EnumValues model:ProbeLayer}"+ SelectedItem="{Binding Layer}" ToolTip="{meta:Hint model:Probe.Layer}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.Measurement}" />+ <ComboBox Style="{StaticResource EnumComboBox}" ItemsSource="{meta:EnumValues model:ProbeMeasurement}"+ SelectedItem="{Binding Measurement}" ToolTip="{meta:Hint model:Probe.Measurement}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.Kind}" />+ <ComboBox Style="{StaticResource EnumComboBox}" ItemsSource="{meta:EnumValues model:ProbeKind}"+ SelectedItem="{Binding Kind}" ToolTip="{meta:Hint model:Probe.Kind}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionPosition}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.AX}" />+ <TextBox Text="{Binding AX}" ToolTip="{meta:Hint model:Probe.AX}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.AY}" />+ <TextBox Text="{Binding AY}" ToolTip="{meta:Hint model:Probe.AY}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BX}" />+ <TextBox Style="{StaticResource LineOnly}" Text="{Binding BX}" ToolTip="{meta:Hint model:Probe.BX}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BY}" />+ <TextBox Style="{StaticResource LineOnly}" Text="{Binding BY}" ToolTip="{meta:Hint model:Probe.BY}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionGraph}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BoxSize}" />+ <ComboBox Style="{StaticResource EnumComboBox}" ItemsSource="{meta:EnumValues model:ProbeBoxSize}"+ SelectedItem="{Binding BoxSize}" ToolTip="{meta:Hint model:Probe.BoxSize}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BoxX}" />+ <TextBox Text="{Binding BoxX}" ToolTip="{meta:Hint model:Probe.BoxX}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.BoxY}" />+ <TextBox Text="{Binding BoxY}" ToolTip="{meta:Hint model:Probe.BoxY}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionAxes}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.ScaleMode}" />+ <ComboBox Style="{StaticResource PointOnlyCombo}" ItemsSource="{meta:EnumValues model:ProbeScaleMode}"+ SelectedItem="{Binding ScaleMode}" ToolTip="{meta:Hint model:Probe.ScaleMode}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.Window}" />+ <TextBox Text="{Binding Window}" ToolTip="{meta:Hint model:Probe.Window}" />++ <CheckBox controls:FormPanel.FullWidth="True" Style="{StaticResource PointOnlyCheck}" Content="{meta:Label model:Probe.AutoScaleX}"+ IsChecked="{Binding AutoScaleX}" ToolTip="{meta:Hint model:Probe.AutoScaleX}" />+ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Probe.AutoScaleY}"+ IsChecked="{Binding AutoScaleY}" ToolTip="{meta:Hint model:Probe.AutoScaleY}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.YMin}" />+ <TextBox Text="{Binding YMin}" ToolTip="{meta:Hint model:Probe.YMin}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Probe.YMax}" />+ <TextBox Text="{Binding YMax}" ToolTip="{meta:Hint model:Probe.YMax}" />+ </controls:FormPanel>+ </StackPanel>+ </ScrollViewer>+</UserControl>diff --git a/WaveDude.WPF/Views/ProbeView.xaml.cs b/WaveDude.WPF/Views/ProbeView.xaml.csnew file mode 100644index 0000000..e278b7c--- /dev/null+++ b/WaveDude.WPF/Views/ProbeView.xaml.cs@@ -0,0 +1,12 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Views;++/// <summary>Editor for a <see cref="WaveDude.Model.Probe"/>: measurement, position, graph box and axes.</summary>+public partial class ProbeView : UserControl+{+ public ProbeView()+ {+ InitializeComponent();+ }+}diff --git a/WaveDude.WPF/Views/ProjectView.xaml b/WaveDude.WPF/Views/ProjectView.xamlnew file mode 100644index 0000000..a763c1a--- /dev/null+++ b/WaveDude.WPF/Views/ProjectView.xaml@@ -0,0 +1,34 @@+<UserControl x:Class="WaveDude.WPF.Views.ProjectView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:local="clr-namespace:WaveDude.WPF.Views"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:meta="clr-namespace:WaveDude.WPF.Markup"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <UserControl.CommandBindings>+ <CommandBinding Command="{x:Static local:ProjectView.Reseed}" Executed="OnReseed" />+ </UserControl.CommandBindings>++ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">+ <StackPanel Margin="8">+ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionGeneral}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Project.Version}" />+ <TextBlock Style="{StaticResource FormValue}" Text="{Binding Version}" ToolTip="{meta:Hint model:Project.Version}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Project.Seed}" />+ <DockPanel>+ <Button DockPanel.Dock="Right" Margin="6,0,0,0" Content="{DynamicResource ButtonNewSeed}"+ Command="{x:Static local:ProjectView.Reseed}" />+ <TextBox Text="{Binding Seed}" ToolTip="{meta:Hint model:Project.Seed}" />+ </DockPanel>++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Project.Description}" VerticalAlignment="Top" Margin="0,4,0,0" />+ <TextBox Text="{Binding Description, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:Project.Description}"+ AcceptsReturn="True" TextWrapping="Wrap" MinHeight="60" VerticalContentAlignment="Top"+ VerticalScrollBarVisibility="Auto" />+ </controls:FormPanel>+ </StackPanel>+ </ScrollViewer>+</UserControl>diff --git a/WaveDude.WPF/Views/ProjectView.xaml.cs b/WaveDude.WPF/Views/ProjectView.xaml.csnew file mode 100644index 0000000..fb08e15--- /dev/null+++ b/WaveDude.WPF/Views/ProjectView.xaml.cs@@ -0,0 +1,19 @@+using System.Windows.Controls;+using System.Windows.Input;+using WaveDude.Model;++namespace WaveDude.WPF.Views;++/// <summary>Editor for the <see cref="Project"/> root: version, seed and description.</summary>+public partial class ProjectView : UserControl+{+ /// <summary>Draws a new random seed for the project in the data context.</summary>+ public static readonly RoutedUICommand Reseed = new("New seed", nameof(Reseed), typeof(ProjectView));++ public ProjectView()+ {+ InitializeComponent();+ }++ private void OnReseed(object sender, ExecutedRoutedEventArgs e) => (DataContext as Project)?.Reseed();+}diff --git a/WaveDude.WPF/Views/SceneView.xaml b/WaveDude.WPF/Views/SceneView.xamlnew file mode 100644index 0000000..6c70f44--- /dev/null+++ b/WaveDude.WPF/Views/SceneView.xaml@@ -0,0 +1,63 @@+<UserControl x:Class="WaveDude.WPF.Views.SceneView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:meta="clr-namespace:WaveDude.WPF.Markup"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <UserControl.Resources>+ <!-- the size applies to a blank canvas, the image path to an image scene -->+ <Style x:Key="CanvasOnly" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Mode}" Value="Image">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="ImageOnly" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Mode}" Value="Canvas">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ </UserControl.Resources>++ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">+ <StackPanel Margin="8">+ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionCanvas}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.Mode}" />+ <ComboBox Style="{StaticResource EnumComboBox}" ItemsSource="{meta:EnumValues model:SceneMode}"+ SelectedItem="{Binding Mode}" ToolTip="{meta:Hint model:Scene.Mode}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.Image}" />+ <TextBox Style="{StaticResource ImageOnly}" Text="{Binding Image, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:Scene.Image}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.Width}" />+ <TextBox Style="{StaticResource CanvasOnly}" Text="{Binding Width}" ToolTip="{meta:Hint model:Scene.Width}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.Height}" />+ <TextBox Style="{StaticResource CanvasOnly}" Text="{Binding Height}" ToolTip="{meta:Hint model:Scene.Height}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.DampingEdge}" />+ <TextBox Text="{Binding DampingEdge}" ToolTip="{meta:Hint model:Scene.DampingEdge}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.RefractiveIndex}" />+ <TextBox Text="{Binding RefractiveIndex}" ToolTip="{meta:Hint model:Scene.RefractiveIndex}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionImageSources}" />+ <controls:FormPanel>+ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Scene.ImageSources}"+ IsChecked="{Binding ImageSources}" ToolTip="{meta:Hint model:Scene.ImageSources}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Scene.ImageSourceScale}" />+ <TextBox Text="{Binding ImageSourceScale}" IsEnabled="{Binding ImageSources}" ToolTip="{meta:Hint model:Scene.ImageSourceScale}" />++ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Scene.ObjectSources}"+ IsChecked="{Binding ObjectSources}" ToolTip="{meta:Hint model:Scene.ObjectSources}" />+ </controls:FormPanel>+ </StackPanel>+ </ScrollViewer>+</UserControl>diff --git a/WaveDude.WPF/Views/SceneView.xaml.cs b/WaveDude.WPF/Views/SceneView.xaml.csnew file mode 100644index 0000000..f0c4e24--- /dev/null+++ b/WaveDude.WPF/Views/SceneView.xaml.cs@@ -0,0 +1,12 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Views;++/// <summary>Editor for <see cref="WaveDude.Model.Scene"/>: canvas or image, damping edge, image sources.</summary>+public partial class SceneView : UserControl+{+ public SceneView()+ {+ InitializeComponent();+ }+}diff --git a/WaveDude.WPF/Views/SimulationView.xaml b/WaveDude.WPF/Views/SimulationView.xamlnew file mode 100644index 0000000..f5ad91f--- /dev/null+++ b/WaveDude.WPF/Views/SimulationView.xaml@@ -0,0 +1,40 @@+<UserControl x:Class="WaveDude.WPF.Views.SimulationView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:meta="clr-namespace:WaveDude.WPF.Markup"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">+ <StackPanel Margin="8">+ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionRun}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Simulation.Steps}" />+ <TextBox Text="{Binding Steps}" ToolTip="{meta:Hint model:Simulation.Steps}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Simulation.VisualizeEvery}" />+ <TextBox Text="{Binding VisualizeEvery}" ToolTip="{meta:Hint model:Simulation.VisualizeEvery}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionSolver}" />+ <controls:FormPanel>+ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Simulation.Gpu}"+ IsChecked="{Binding Gpu}" ToolTip="{meta:Hint model:Simulation.Gpu}" />+ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Simulation.FourthOrderLaplacian}"+ IsChecked="{Binding FourthOrderLaplacian}" ToolTip="{meta:Hint model:Simulation.FourthOrderLaplacian}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Simulation.WaveSpeed}" />+ <TextBox Text="{Binding WaveSpeed}" ToolTip="{meta:Hint model:Simulation.WaveSpeed}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Simulation.TimeDecay}" />+ <TextBox Text="{Binding TimeDecay}" ToolTip="{meta:Hint model:Simulation.TimeDecay}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Simulation.SourceFrequencyScale}" />+ <TextBox Text="{Binding SourceFrequencyScale}" ToolTip="{meta:Hint model:Simulation.SourceFrequencyScale}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Simulation.IntensityScale}" />+ <TextBox Text="{Binding IntensityScale}" ToolTip="{meta:Hint model:Simulation.IntensityScale}" />+ </controls:FormPanel>+ </StackPanel>+ </ScrollViewer>+</UserControl>diff --git a/WaveDude.WPF/Views/SimulationView.xaml.cs b/WaveDude.WPF/Views/SimulationView.xaml.csnew file mode 100644index 0000000..c86d8a4--- /dev/null+++ b/WaveDude.WPF/Views/SimulationView.xaml.cs@@ -0,0 +1,12 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Views;++/// <summary>Editor for <see cref="WaveDude.Model.Simulation"/>: run length and solver parameters.</summary>+public partial class SimulationView : UserControl+{+ public SimulationView()+ {+ InitializeComponent();+ }+}diff --git a/WaveDude.WPF/Views/SourceView.xaml b/WaveDude.WPF/Views/SourceView.xamlnew file mode 100644index 0000000..84a12c5--- /dev/null+++ b/WaveDude.WPF/Views/SourceView.xaml@@ -0,0 +1,110 @@+<UserControl x:Class="WaveDude.WPF.Views.SourceView"+ xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"+ xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"+ xmlns:controls="clr-namespace:WaveDude.WPF.Controls"+ xmlns:meta="clr-namespace:WaveDude.WPF.Markup"+ xmlns:model="clr-namespace:WaveDude.Model;assembly=WaveDude">++ <UserControl.Resources>+ <!-- pulse settings only matter for a pulsed source -->+ <Style x:Key="PulsedOnlyText" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Mode}" Value="Continuous">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ <Style x:Key="PulsedOnlyCombo" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource EnumComboBox}">+ <Style.Triggers>+ <DataTrigger Binding="{Binding Mode}" Value="Continuous">+ <Setter Property="IsEnabled" Value="False" />+ </DataTrigger>+ </Style.Triggers>+ </Style>+ </UserControl.Resources>++ <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">+ <StackPanel Margin="8">+ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionGeneral}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.Name}" />+ <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" ToolTip="{meta:Hint model:Source.Name}" />++ <CheckBox controls:FormPanel.FullWidth="True" Content="{meta:Label model:Source.Enabled}"+ IsChecked="{Binding Enabled}" ToolTip="{meta:Hint model:Source.Enabled}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionPosition}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.X}" />+ <TextBox Text="{Binding X}" ToolTip="{meta:Hint model:Source.X}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.Y}" />+ <TextBox Text="{Binding Y}" ToolTip="{meta:Hint model:Source.Y}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionWave}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.Frequency}" />+ <TextBox Text="{Binding Frequency}" ToolTip="{meta:Hint model:Source.Frequency}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.Amplitude}" />+ <TextBox Text="{Binding Amplitude}" ToolTip="{meta:Hint model:Source.Amplitude}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.Phase}" />+ <TextBox Text="{Binding Phase}" ToolTip="{meta:Hint model:Source.Phase}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionTiming}" />+ <controls:FormPanel>+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.Mode}" />+ <ComboBox Style="{StaticResource EnumComboBox}" ItemsSource="{meta:EnumValues model:SourceMode}"+ SelectedItem="{Binding Mode}" ToolTip="{meta:Hint model:Source.Mode}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.PulseShape}" />+ <ComboBox Style="{StaticResource PulsedOnlyCombo}" ItemsSource="{meta:EnumValues model:PulseShape}"+ SelectedItem="{Binding PulseShape}" ToolTip="{meta:Hint model:Source.PulseShape}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.PulseWidth}" />+ <TextBox Style="{StaticResource PulsedOnlyText}" Text="{Binding PulseWidth}" ToolTip="{meta:Hint model:Source.PulseWidth}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.OffWidth}" />+ <TextBox Style="{StaticResource PulsedOnlyText}" Text="{Binding OffWidth}" ToolTip="{meta:Hint model:Source.OffWidth}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:Source.DetachAfter}" />+ <TextBox Text="{Binding DetachAfter}" ToolTip="{meta:Hint model:Source.DetachAfter}" />+ </controls:FormPanel>++ <TextBlock Style="{StaticResource FormSection}" Text="{DynamicResource SectionArray}" />+ <CheckBox Content="{meta:Label model:Source.IsComposite}" IsChecked="{Binding IsComposite}"+ ToolTip="{meta:Hint model:Source.IsComposite}" Margin="0,0,0,4" />+ <!-- the array's own settings; empty and disabled while there is no array -->+ <controls:FormPanel DataContext="{Binding Array}"+ IsEnabled="{Binding DataContext.IsComposite, RelativeSource={RelativeSource AncestorType={x:Type UserControl}}}">+ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.SizeX}" />+ <TextBox Text="{Binding SizeX}" ToolTip="{meta:Hint model:SourceArray.SizeX}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.SizeY}" />+ <TextBox Text="{Binding SizeY}" ToolTip="{meta:Hint model:SourceArray.SizeY}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.SpacingX}" />+ <TextBox Text="{Binding SpacingX}" ToolTip="{meta:Hint model:SourceArray.SpacingX}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.SpacingY}" />+ <TextBox Text="{Binding SpacingY}" ToolTip="{meta:Hint model:SourceArray.SpacingY}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.RandomFrequency}" />+ <TextBox Text="{Binding RandomFrequency}" ToolTip="{meta:Hint model:SourceArray.RandomFrequency}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.RandomPhase}" />+ <TextBox Text="{Binding RandomPhase}" ToolTip="{meta:Hint model:SourceArray.RandomPhase}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.RandomOffWidth}" />+ <TextBox Text="{Binding RandomOffWidth}" ToolTip="{meta:Hint model:SourceArray.RandomOffWidth}" />++ <TextBlock Style="{StaticResource FormLabel}" Text="{meta:Label model:SourceArray.RandomPosition}" />+ <TextBox Text="{Binding RandomPosition}" ToolTip="{meta:Hint model:SourceArray.RandomPosition}" />+ </controls:FormPanel>+ </StackPanel>+ </ScrollViewer>+</UserControl>diff --git a/WaveDude.WPF/Views/SourceView.xaml.cs b/WaveDude.WPF/Views/SourceView.xaml.csnew file mode 100644index 0000000..a6ad763--- /dev/null+++ b/WaveDude.WPF/Views/SourceView.xaml.cs@@ -0,0 +1,12 @@+using System.Windows.Controls;++namespace WaveDude.WPF.Views;++/// <summary>Editor for a <see cref="WaveDude.Model.Source"/>, including its optional emitter array.</summary>+public partial class SourceView : UserControl+{+ public SourceView()+ {+ InitializeComponent();+ }+}diff --git a/WaveDude.WPF/WaveDude.WPF.csproj b/WaveDude.WPF/WaveDude.WPF.csprojnew file mode 100644index 0000000..58d2e2d--- /dev/null+++ b/WaveDude.WPF/WaveDude.WPF.csproj@@ -0,0 +1,42 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <OutputType>WinExe</OutputType>+ <TargetFramework>net10.0-windows</TargetFramework>+ <Nullable>enable</Nullable>+ <ImplicitUsings>enable</ImplicitUsings>+ <UseWPF>true</UseWPF>+ <!-- Program.Main configures logging before the generated App.Main runs -->+ <StartupObject>WaveDude.WPF.Program</StartupObject>+ <!-- executable icon (Explorer, taskbar); the window icon is the same file as a resource -->+ <ApplicationIcon>App.ico</ApplicationIcon>+ </PropertyGroup>++ <ItemGroup>+ <Resource Include="App.ico" />+ </ItemGroup>++ <ItemGroup>+ <PackageReference Include="NLog" Version="6.2.1" />+ </ItemGroup>++ <ItemGroup>+ <ProjectReference Include="..\WaveDude\WaveDude.csproj" />+ </ItemGroup>++ <ItemGroup>+ <Compile Update="Properties\Settings.Designer.cs">+ <DesignTimeSharedInput>True</DesignTimeSharedInput>+ <AutoGen>True</AutoGen>+ <DependentUpon>Settings.settings</DependentUpon>+ </Compile>+ </ItemGroup>++ <ItemGroup>+ <None Update="Properties\Settings.settings">+ <Generator>SettingsSingleFileGenerator</Generator>+ <LastGenOutput>Settings.Designer.cs</LastGenOutput>+ </None>+ </ItemGroup>++</Project>diff --git a/WaveDude/Model/Display.cs b/WaveDude/Model/Display.csnew file mode 100644index 0000000..899008b--- /dev/null+++ b/WaveDude/Model/Display.cs@@ -0,0 +1,196 @@+using System.ComponentModel;+using System.Xml.Serialization;++namespace WaveDude.Model;++/// <summary>How the two outputs, field and intensity, are rendered, previewed and exported.</summary>+[TypeConverter(typeof(ExpandableObjectConverter))]+public sealed class Display : ObservableObject+{+ /// <summary>Colour scheme name used for the field when none is given.</summary>+ public const string DefaultFieldColorScheme = "Default_Field";+ /// <summary>Colour scheme name used for the intensity when none is given.</summary>+ public const string DefaultIntensityColorScheme = "Default_intensity";+ /// <summary>Black level of the field layer in a new project.</summary>+ public const double DefaultFieldBlackLevel = -0.05;++ private DisplayLayer _field = new() { ColorScheme = DefaultFieldColorScheme, BlackLevel = DefaultFieldBlackLevel };+ private DisplayLayer _intensity = new() { ColorScheme = DefaultIntensityColorScheme };+ private Video _video = new();++ /// <summary>Rendering of the wave field.</summary>+ [XmlElement]+ [Category("Outputs")]+ [Description("Rendering of the wave field.")]+ public DisplayLayer Field+ {+ get => _field;+ set => SetProperty(ref _field, value);+ }++ /// <summary>Rendering of the accumulated intensity.</summary>+ [XmlElement]+ [Category("Outputs")]+ [Description("Rendering of the accumulated intensity.")]+ public DisplayLayer Intensity+ {+ get => _intensity;+ set => SetProperty(ref _intensity, value);+ }++ /// <summary>Encoder settings of exported videos.</summary>+ [XmlElement]+ [Category("Export")]+ [Description("Encoder settings of exported videos.")]+ public Video Video+ {+ get => _video;+ set => SetProperty(ref _video, value);+ }++ /// <summary>Tells <see cref="XmlSerializer"/> to leave all-default video settings out of the file.</summary>+ public bool ShouldSerializeVideo() => Video.Fps != Video.DefaultFps || Video.Quality != Video.DefaultQuality;++ /// <summary>Clamps every value into its valid range.</summary>+ public void Normalize()+ {+ Field.Normalize(DefaultFieldColorScheme);+ Intensity.Normalize(DefaultIntensityColorScheme);+ Video.Normalize();+ }++ /// <summary>The two colour scheme names, for display in a property grid.</summary>+ public override string ToString() => $"{Field.ColorScheme} / {Intensity.ColorScheme}";+}++/// <summary>Rendering of one output (field or intensity).</summary>+[TypeConverter(typeof(ExpandableObjectConverter))]+public sealed class DisplayLayer : ObservableObject+{+ /// <summary>Default <see cref="Brightness"/>.</summary>+ public const double DefaultBrightness = 30.0;++ private string _colorScheme = "";+ private double _brightness = DefaultBrightness;+ private double _blackLevel;+ private bool _preview = true;+ private bool _export;++ /// <summary>Name of the colour scheme mapped onto the values.</summary>+ [XmlAttribute]+ [Category("Rendering")]+ [DisplayName("Colour scheme")]+ [Description("Name of the colour scheme mapped onto the values.")]+ public string ColorScheme+ {+ get => _colorScheme;+ set => SetProperty(ref _colorScheme, value);+ }++ /// <summary>Gain applied to the values before the colour lookup.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultBrightness)]+ [Category("Rendering")]+ [Description("Gain applied to the values before the colour lookup.")]+ public double Brightness+ {+ get => _brightness;+ set => SetProperty(ref _brightness, value);+ }++ /// <summary>Offset applied before the colour lookup; values at or below it map to the first colour.</summary>+ [XmlAttribute]+ [DefaultValue(0.0)]+ [Category("Rendering")]+ [DisplayName("Black level")]+ [Description("Offset applied before the colour lookup; values at or below it map to the first colour.")]+ public double BlackLevel+ {+ get => _blackLevel;+ set => SetProperty(ref _blackLevel, value);+ }++ /// <summary>Whether the output is shown in the live preview.</summary>+ [XmlAttribute]+ [DefaultValue(true)]+ [Category("Output")]+ [Description("Show this output in the live preview.")]+ public bool Preview+ {+ get => _preview;+ set => SetProperty(ref _preview, value);+ }++ /// <summary>Whether the output's frames are written to a video file.</summary>+ [XmlAttribute]+ [DefaultValue(false)]+ [Category("Output")]+ [Description("Write this output's frames to a video file.")]+ public bool Export+ {+ get => _export;+ set => SetProperty(ref _export, value);+ }++ /// <summary>Clamps every value into its valid range; an empty scheme name falls back to <paramref name="defaultScheme"/>.</summary>+ public void Normalize(string defaultScheme)+ {+ if (string.IsNullOrWhiteSpace(ColorScheme))+ {+ ColorScheme = defaultScheme;+ }+ Brightness = Math.Clamp(Brightness, 1e-4, 1e5);+ BlackLevel = Math.Clamp(BlackLevel, -10.0, 1.0);+ }++ /// <summary>The colour scheme name, for display in a property grid.</summary>+ public override string ToString() => ColorScheme;+}++/// <summary>Encoder settings of exported videos.</summary>+[TypeConverter(typeof(ExpandableObjectConverter))]+public sealed class Video : ObservableObject+{+ /// <summary>Default <see cref="Fps"/>.</summary>+ public const int DefaultFps = 60;+ /// <summary>Largest accepted <see cref="Fps"/>.</summary>+ public const int MaxFps = 240;+ /// <summary>Default <see cref="Quality"/>.</summary>+ public const int DefaultQuality = 70;++ private int _fps = DefaultFps;+ private int _quality = DefaultQuality;++ /// <summary>Frames per second of the exported video.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultFps)]+ [Category("Video")]+ [DisplayName("Frame rate")]+ [Description("Frames per second of the exported video.")]+ public int Fps+ {+ get => _fps;+ set => SetProperty(ref _fps, value);+ }++ /// <summary>Encoder quality, 1 to 100.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultQuality)]+ [Category("Video")]+ [Description("Encoder quality, 1 to 100.")]+ public int Quality+ {+ get => _quality;+ set => SetProperty(ref _quality, value);+ }++ /// <summary>Clamps every value into its valid range.</summary>+ public void Normalize()+ {+ Fps = Math.Clamp(Fps, 1, MaxFps);+ Quality = Math.Clamp(Quality, 1, 100);+ }++ /// <summary>Frame rate and quality, for display in a property grid.</summary>+ public override string ToString() => $"{Fps} fps, quality {Quality}";+}diff --git a/WaveDude/Model/ObservableObject.cs b/WaveDude/Model/ObservableObject.csnew file mode 100644index 0000000..9a2d29c--- /dev/null+++ b/WaveDude/Model/ObservableObject.cs@@ -0,0 +1,45 @@+using System.ComponentModel;+using System.Runtime.CompilerServices;++namespace WaveDude.Model;++/// <summary>+/// Base of the model classes: raises <see cref="PropertyChanged"/> when a property value+/// changes, so bound views (tree headers, editors) follow edits without manual refreshes.+/// Not thread-safe; the model is edited on the UI thread only.+/// </summary>+public abstract class ObservableObject : INotifyPropertyChanged+{+ /// <inheritdoc/>+ public event PropertyChangedEventHandler? PropertyChanged;++ /// <summary>+ /// Stores <paramref name="value"/> in <paramref name="field"/> and raises+ /// <see cref="PropertyChanged"/> when it differs; returns whether it did.+ /// </summary>+ protected bool SetProperty<T>(ref T field, T value, [CallerMemberName] string? name = null)+ {+ if (EqualityComparer<T>.Default.Equals(field, value))+ {+ return false;+ }+ field = value;+ OnPropertyChanged(name);+ return true;+ }++ /// <summary>Raises <see cref="PropertyChanged"/> for <paramref name="name"/>; use for derived properties.</summary>+ protected void OnPropertyChanged([CallerMemberName] string? name = null) =>+ PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));++ /// <summary>+ /// Memberwise copy that does not carry over the <see cref="PropertyChanged"/> subscribers+ /// of the original. Derived classes deep-copy their reference-typed members on top.+ /// </summary>+ protected T ShallowClone<T>() where T : ObservableObject+ {+ var copy = (T)MemberwiseClone();+ copy.PropertyChanged = null;+ return copy;+ }+}diff --git a/WaveDude/Model/Probe.cs b/WaveDude/Model/Probe.csnew file mode 100644index 0000000..4d25617--- /dev/null+++ b/WaveDude/Model/Probe.cs@@ -0,0 +1,348 @@+using System.ComponentModel;+using System.Xml.Serialization;++namespace WaveDude.Model;++/// <summary>Output a probe samples and is drawn on.</summary>+public enum ProbeLayer+{+ /// <summary>The wave field.</summary>+ Field,+ /// <summary>The accumulated intensity.</summary>+ Intensity,+}++/// <summary>Quantity a probe records.</summary>+public enum ProbeMeasurement+{+ /// <summary>Field value at the probe; field layer only.</summary>+ Amplitude,+ /// <summary>Averaged intensity at the probe; intensity layer only.</summary>+ Intensity,+ /// <summary>Intensity summed over the run so far; intensity layer only.</summary>+ IntegratedIntensity,+}++/// <summary>Point probe (position A) or line probe (A to B).</summary>+public enum ProbeKind+{+ /// <summary>Samples one pixel and plots it over time.</summary>+ Point,+ /// <summary>Samples along a line and plots the current profile.</summary>+ Line,+}++/// <summary>Nominal size of the graph box drawn over the output.</summary>+public enum ProbeBoxSize+{+ /// <summary>Smallest box.</summary>+ Tiny,+ /// <summary>Small box.</summary>+ Small,+ /// <summary>Default box.</summary>+ Medium,+ /// <summary>Large box.</summary>+ Large,+ /// <summary>Largest box.</summary>+ ExtraLarge,+}++/// <summary>How the step axis of a point probe's time series is chosen.</summary>+public enum ProbeScaleMode+{+ /// <summary>A sliding window of <see cref="Probe.Window"/> steps.</summary>+ Running,+ /// <summary>The whole run.</summary>+ Full,+}++/// <summary>+/// A measurement point or line on the canvas and the graph that shows its values. Positions are+/// canvas pixels with the origin at the top left.+/// </summary>+public sealed class Probe : ObservableObject+{+ /// <summary>Default <see cref="Window"/> in steps.</summary>+ public const int DefaultWindow = 500;+ /// <summary>Smallest accepted <see cref="Window"/>.</summary>+ public const int MinWindow = 10;+ /// <summary>Largest accepted <see cref="Window"/>.</summary>+ public const int MaxWindow = 1_000_000;++ private string _name = "";+ private bool _active = true;+ private ProbeLayer _layer = ProbeLayer.Field;+ private ProbeMeasurement _measurement = ProbeMeasurement.Amplitude;+ private ProbeKind _kind = ProbeKind.Point;+ private int _aX;+ private int _aY;+ private int _bX;+ private int _bY;+ private ProbeBoxSize _boxSize = ProbeBoxSize.Medium;+ private int _boxX;+ private int _boxY;+ private ProbeScaleMode _scaleMode = ProbeScaleMode.Running;+ private bool _autoScaleX = true;+ private bool _autoScaleY = true;+ private double _yMin = -1.0;+ private double _yMax = 1.0;+ private int _window = DefaultWindow;+ private int _startAfter;++ /// <summary>Name shown in the project tree and in the graph title.</summary>+ [XmlAttribute]+ [Category("General")]+ [Description("Name shown in the project tree and in the graph title.")]+ public string Name+ {+ get => _name;+ set => SetProperty(ref _name, value);+ }++ /// <summary>Whether the probe is sampled and drawn.</summary>+ [XmlAttribute]+ [DefaultValue(true)]+ [Category("General")]+ [Description("Sample and draw this probe.")]+ public bool Active+ {+ get => _active;+ set => SetProperty(ref _active, value);+ }++ /// <summary>Output the probe samples and is drawn on.</summary>+ [XmlAttribute]+ [DefaultValue(ProbeLayer.Field)]+ [Category("Measurement")]+ [Description("Output the probe samples and is drawn on.")]+ public ProbeLayer Layer+ {+ get => _layer;+ set => SetProperty(ref _layer, value);+ }++ /// <summary>Recorded quantity; must fit <see cref="Layer"/>, which <see cref="Normalize"/> enforces.</summary>+ [XmlAttribute]+ [DefaultValue(ProbeMeasurement.Amplitude)]+ [Category("Measurement")]+ [Description("Recorded quantity. The field only offers amplitude; the intensity output offers intensity or integrated intensity.")]+ public ProbeMeasurement Measurement+ {+ get => _measurement;+ set => SetProperty(ref _measurement, value);+ }++ /// <summary>A single point, or a line from A to B.</summary>+ [XmlAttribute]+ [DefaultValue(ProbeKind.Point)]+ [Category("Measurement")]+ [Description("A single point, or a line from A to B.")]+ public ProbeKind Kind+ {+ get => _kind;+ set => SetProperty(ref _kind, value);+ }++ /// <summary>X of the probe pixel, or of the start of the line, in canvas pixels.</summary>+ [XmlAttribute]+ [Category("Position")]+ [DisplayName("A x")]+ [Description("X of the probe pixel, or of the start of the line, in canvas pixels.")]+ public int AX+ {+ get => _aX;+ set => SetProperty(ref _aX, value);+ }++ /// <summary>Y of the probe pixel, or of the start of the line, in canvas pixels.</summary>+ [XmlAttribute]+ [Category("Position")]+ [DisplayName("A y")]+ [Description("Y of the probe pixel, or of the start of the line, in canvas pixels.")]+ public int AY+ {+ get => _aY;+ set => SetProperty(ref _aY, value);+ }++ /// <summary>X of the end of the line in canvas pixels; line probes only, omitted from the file otherwise.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Position")]+ [DisplayName("B x")]+ [Description("X of the end of the line in canvas pixels; line probes only.")]+ public int BX+ {+ get => _bX;+ set => SetProperty(ref _bX, value);+ }++ /// <summary>Y of the end of the line in canvas pixels; line probes only, omitted from the file otherwise.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Position")]+ [DisplayName("B y")]+ [Description("Y of the end of the line in canvas pixels; line probes only.")]+ public int BY+ {+ get => _bY;+ set => SetProperty(ref _bY, value);+ }++ /// <summary>Nominal size of the graph box drawn over the output.</summary>+ [XmlAttribute]+ [DefaultValue(ProbeBoxSize.Medium)]+ [Category("Graph")]+ [DisplayName("Box size")]+ [Description("Nominal size of the graph box drawn over the output.")]+ public ProbeBoxSize BoxSize+ {+ get => _boxSize;+ set => SetProperty(ref _boxSize, value);+ }++ /// <summary>Left edge of the graph box in canvas pixels.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Graph")]+ [DisplayName("Box x")]+ [Description("Left edge of the graph box in canvas pixels.")]+ public int BoxX+ {+ get => _boxX;+ set => SetProperty(ref _boxX, value);+ }++ /// <summary>Top edge of the graph box in canvas pixels.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Graph")]+ [DisplayName("Box y")]+ [Description("Top edge of the graph box in canvas pixels.")]+ public int BoxY+ {+ get => _boxY;+ set => SetProperty(ref _boxY, value);+ }++ /// <summary>Sliding window of the last steps, or the whole run; point probes only.</summary>+ [XmlAttribute]+ [DefaultValue(ProbeScaleMode.Running)]+ [Category("Axes")]+ [DisplayName("Step axis")]+ [Description("Sliding window of the last steps, or the whole run; point probes only.")]+ public ProbeScaleMode ScaleMode+ {+ get => _scaleMode;+ set => SetProperty(ref _scaleMode, value);+ }++ /// <summary>Whether the step axis follows the samples recorded so far; point probes only.</summary>+ [XmlAttribute]+ [DefaultValue(true)]+ [Category("Axes")]+ [DisplayName("Auto-scale steps")]+ [Description("Let the step axis follow the samples recorded so far; point probes only.")]+ public bool AutoScaleX+ {+ get => _autoScaleX;+ set => SetProperty(ref _autoScaleX, value);+ }++ /// <summary>Whether the value axis is fitted to the data instead of <see cref="YMin"/>..<see cref="YMax"/>.</summary>+ [XmlAttribute]+ [DefaultValue(true)]+ [Category("Axes")]+ [DisplayName("Auto-scale values")]+ [Description("Fit the value axis to the data instead of the fixed minimum and maximum.")]+ public bool AutoScaleY+ {+ get => _autoScaleY;+ set => SetProperty(ref _autoScaleY, value);+ }++ /// <summary>Lower bound of the value axis when it is not auto-scaled.</summary>+ [XmlAttribute]+ [DefaultValue(-1.0)]+ [Category("Axes")]+ [DisplayName("Value minimum")]+ [Description("Lower bound of the value axis when it is not auto-scaled.")]+ public double YMin+ {+ get => _yMin;+ set => SetProperty(ref _yMin, value);+ }++ /// <summary>Upper bound of the value axis when it is not auto-scaled; must exceed <see cref="YMin"/>.</summary>+ [XmlAttribute]+ [DefaultValue(1.0)]+ [Category("Axes")]+ [DisplayName("Value maximum")]+ [Description("Upper bound of the value axis when it is not auto-scaled.")]+ public double YMax+ {+ get => _yMax;+ set => SetProperty(ref _yMax, value);+ }++ /// <summary>Width of the sliding step window for <see cref="ProbeScaleMode.Running"/>, in steps.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultWindow)]+ [Category("Axes")]+ [DisplayName("Window")]+ [Description("Width of the sliding step window, in steps.")]+ public int Window+ {+ get => _window;+ set => SetProperty(ref _window, value);+ }++ /// <summary>Step at which recording starts; 0 records from the first step.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("General")]+ [DisplayName("Start after step")]+ [Description("Step at which recording starts; 0 records from the first step.")]+ public int StartAfter+ {+ get => _startAfter;+ set => SetProperty(ref _startAfter, value);+ }++ /// <summary>Tells <see cref="XmlSerializer"/> to write B only for line probes.</summary>+ public bool ShouldSerializeBX() => Kind == ProbeKind.Line;++ /// <summary>Tells <see cref="XmlSerializer"/> to write B only for line probes.</summary>+ public bool ShouldSerializeBY() => Kind == ProbeKind.Line;++ /// <summary>+ /// Forces a consistent state: the field only allows <see cref="ProbeMeasurement.Amplitude"/>,+ /// the intensity output never does; an empty or inverted Y range becomes -1..1; the window+ /// and start step are clamped.+ /// </summary>+ public void Normalize()+ {+ Name ??= "";+ if (Layer == ProbeLayer.Field)+ {+ Measurement = ProbeMeasurement.Amplitude;+ }+ else if (Measurement == ProbeMeasurement.Amplitude)+ {+ Measurement = ProbeMeasurement.Intensity;+ }+ if (YMax <= YMin)+ {+ YMin = -1.0;+ YMax = 1.0;+ }+ Window = Math.Clamp(Window, MinWindow, MaxWindow);+ StartAfter = Math.Max(0, StartAfter);+ }++ /// <summary>A copy with the same settings and no change subscribers.</summary>+ public Probe Clone() => ShallowClone<Probe>();++ /// <summary>The name, for display in the project tree and property grids.</summary>+ public override string ToString() => Name;+}diff --git a/WaveDude/Model/Project.cs b/WaveDude/Model/Project.csnew file mode 100644index 0000000..0f9c046--- /dev/null+++ b/WaveDude/Model/Project.cs@@ -0,0 +1,309 @@+using System.Collections.ObjectModel;+using System.ComponentModel;+using System.Xml;+using System.Xml.Serialization;+using NLog;++namespace WaveDude.Model;++/// <summary>+/// A wave simulation project: the scene, solver and display settings plus the sources and+/// probes. Persisted as sparse XML through <see cref="XmlSerializer"/>: scalars are attributes,+/// sources and probes are repeated <c>Source</c> and <c>Probe</c> elements directly under the+/// root, and values equal to their defaults are left out. Properties carry+/// <see cref="System.ComponentModel"/> metadata for property grids.+/// </summary>+[XmlRoot("Project")]+public sealed class Project : ObservableObject+{+ /// <summary>Format version written to new files; bump when the layout changes incompatibly.</summary>+ public const int CurrentVersion = 1;++ private int _version = CurrentVersion;+ private int _seed = NewSeed();+ private string _description = "";+ private Scene _scene = new();+ private Simulation _simulation = new();+ private Display _display = new();+ private ObservableCollection<Source> _sources = new();+ private ObservableCollection<Probe> _probes = new();++ private static readonly ILogger Logger = LogManager.GetCurrentClassLogger();+ private static readonly XmlSerializer Serializer = new(typeof(Project));+ private static readonly XmlSerializerNamespaces NoNamespaces = new([XmlQualifiedName.Empty]);+ private static readonly XmlWriterSettings WriterSettings = new()+ {+ Indent = true,+ IndentChars = "\t",+ Encoding = new System.Text.UTF8Encoding(false),+ };++ /// <summary>Format version of the file this project was read from, or <see cref="CurrentVersion"/>.</summary>+ [XmlAttribute]+ [Category("General")]+ [DisplayName("Format version")]+ [Description("Version of the project file format.")]+ [ReadOnly(true)]+ public int Version+ {+ get => _version;+ set => SetProperty(ref _version, value);+ }++ /// <summary>+ /// Seed of every random decision in the project: emitter jitter and the engines' per-period+ /// gap randomisation. The same project file therefore always produces the same frames.+ /// A new project gets a fresh seed; use <see cref="Reseed"/> for a different variation.+ /// </summary>+ [XmlAttribute]+ [Category("General")]+ [DisplayName("Random seed")]+ [Description("Seed of all random decisions (emitter jitter, random gaps). The same seed reproduces the same frames.")]+ public int Seed+ {+ get => _seed;+ set => SetProperty(ref _seed, value);+ }++ /// <summary>Free-text notes about the project; omitted from the file when empty.</summary>+ [XmlElement]+ [DefaultValue("")]+ [Category("General")]+ [Description("Free-text notes about the project.")]+ public string Description+ {+ get => _description;+ set => SetProperty(ref _description, value);+ }++ /// <summary>The canvas: its size or image, damping border and image source options.</summary>+ [XmlElement]+ [Category("Scene")]+ [Description("The canvas: its size or image, damping border and image sources.")]+ public Scene Scene+ {+ get => _scene;+ set => SetProperty(ref _scene, value);+ }++ /// <summary>Run length and solver parameters.</summary>+ [XmlElement]+ [Category("Simulation")]+ [Description("Run length and solver parameters.")]+ public Simulation Simulation+ {+ get => _simulation;+ set => SetProperty(ref _simulation, value);+ }++ /// <summary>How the field and intensity outputs are rendered, previewed and exported.</summary>+ [XmlElement]+ [Category("Display")]+ [Description("How the field and intensity outputs are rendered, previewed and exported.")]+ public Display Display+ {+ get => _display;+ set => SetProperty(ref _display, value);+ }++ /// <summary>+ /// Wave sources, in the order they appear in the project tree. Observable so that views+ /// follow additions and removals; always present, empty in a new project.+ /// </summary>+ [XmlElement("Source")]+ [Browsable(false)]+ public ObservableCollection<Source> Sources+ {+ get => _sources;+ set => SetProperty(ref _sources, value);+ }++ /// <summary>+ /// Probes, in the order they appear in the project tree. Observable so that views follow+ /// additions and removals; always present, empty in a new project.+ /// </summary>+ [XmlElement("Probe")]+ [Browsable(false)]+ public ObservableCollection<Probe> Probes+ {+ get => _probes;+ set => SetProperty(ref _probes, value);+ }++ /// <summary>Tells <see cref="XmlSerializer"/> to leave an all-default scene out of the file.</summary>+ public bool ShouldSerializeScene() => !Scene.IsDefault;++ /// <summary>Tells <see cref="XmlSerializer"/> to leave all-default solver settings out of the file.</summary>+ public bool ShouldSerializeSimulation() => !Simulation.IsDefault;++ /// <summary>Draws a new seed.</summary>+ public static int NewSeed() => Random.Shared.Next(1, int.MaxValue);++ /// <summary>Assigns a new <see cref="Seed"/> and regenerates everything derived from it.</summary>+ public void Reseed()+ {+ Seed = NewSeed();+ GenerateElements();+ }++ /// <summary>Regenerates the emitters of every source from the current settings and <see cref="Seed"/>.</summary>+ public void GenerateElements()+ {+ foreach (Source source in Sources)+ {+ source.GenerateElements(Seed);+ }+ }++ /// <summary>Appends a new source named "Source n" with the first free n, and returns it.</summary>+ public Source AddSource()+ {+ var source = new Source { Name = NumberedName("Source", Sources.Select(s => s.Name)) };+ source.GenerateElements(Seed);+ Sources.Add(source);+ return source;+ }++ /// <summary>Appends a new probe named "Probe n" with the first free n, and returns it.</summary>+ public Probe AddProbe()+ {+ var probe = new Probe { Name = NumberedName("Probe", Probes.Select(p => p.Name)) };+ Probes.Add(probe);+ return probe;+ }++ /// <summary>Inserts a copy of <paramref name="source"/> right after it, named "<name> copy", and returns the copy.</summary>+ public Source Duplicate(Source source)+ {+ Source copy = source.Clone();+ copy.Name = CopyName(source.Name, Sources.Select(s => s.Name));+ Sources.Insert(Sources.IndexOf(source) + 1, copy);+ return copy;+ }++ /// <summary>Inserts a copy of <paramref name="probe"/> right after it, named "<name> copy", and returns the copy.</summary>+ public Probe Duplicate(Probe probe)+ {+ Probe copy = probe.Clone();+ copy.Name = CopyName(probe.Name, Probes.Select(p => p.Name));+ Probes.Insert(Probes.IndexOf(probe) + 1, copy);+ return copy;+ }++ /// <summary>Removes the source; false when it was not in the project.</summary>+ public bool Remove(Source source) => Sources.Remove(source);++ /// <summary>Removes the probe; false when it was not in the project.</summary>+ public bool Remove(Probe probe) => Probes.Remove(probe);++ /// <summary>Moves the source so that it ends up at <paramref name="index"/>; false when nothing changed.</summary>+ public bool Move(Source source, int index) => Move(Sources, source, index);++ /// <summary>Moves the probe so that it ends up at <paramref name="index"/>; false when nothing changed.</summary>+ public bool Move(Probe probe, int index) => Move(Probes, probe, index);++ private static bool Move<T>(ObservableCollection<T> list, T item, int index)+ {+ int current = list.IndexOf(item);+ if (current < 0 || index < 0 || index >= list.Count || index == current)+ {+ return false;+ }+ list.Move(current, index);+ return true;+ }++ /// <summary>"stem 1", "stem 2", ... skipping names already in <paramref name="taken"/> (case-insensitive).</summary>+ private static string NumberedName(string stem, IEnumerable<string> taken)+ {+ var names = taken.ToHashSet(StringComparer.OrdinalIgnoreCase);+ for (int n = 1; ; n++)+ {+ string candidate = $"{stem} {n}";+ if (!names.Contains(candidate))+ {+ return candidate;+ }+ }+ }++ /// <summary>"name copy", then "name copy 2", ... skipping names already in <paramref name="taken"/>.</summary>+ private static string CopyName(string name, IEnumerable<string> taken)+ {+ var names = taken.ToHashSet(StringComparer.OrdinalIgnoreCase);+ string stem = $"{name} copy";+ if (!names.Contains(stem))+ {+ return stem;+ }+ for (int n = 2; ; n++)+ {+ string candidate = $"{stem} {n}";+ if (!names.Contains(candidate))+ {+ return candidate;+ }+ }+ }++ /// <summary>Writes the project as indented XML.</summary>+ public void Save(Stream stream)+ {+ using var writer = XmlWriter.Create(stream, WriterSettings);+ Serializer.Serialize(writer, this, NoNamespaces);+ }++ /// <summary>Writes the project to <paramref name="path"/>, replacing an existing file.</summary>+ public void Save(string path)+ {+ Logger.Info("Saving project to '{Path}' ({Sources} sources, {Probes} probes)", path, Sources.Count, Probes.Count);+ using FileStream stream = File.Create(path);+ Save(stream);+ }++ /// <summary>+ /// Reads a project written by <see cref="Save(Stream)"/>. Values are clamped into range and+ /// the source emitters are generated from the settings and the seed.+ /// </summary>+ /// <exception cref="InvalidOperationException">The stream does not hold a project document.</exception>+ public static Project Load(Stream stream)+ {+ using var reader = XmlReader.Create(stream);+ if (Serializer.Deserialize(reader) is not Project project)+ {+ throw new InvalidOperationException("The document is not a Wave Dude project.");+ }+ if (project.Version > CurrentVersion)+ {+ Logger.Warn("Project file version {Version} is newer than the supported {Supported}; unknown settings are ignored", project.Version, CurrentVersion);+ }+ project.Normalize();+ Logger.Debug("Loaded project: version {Version}, seed {Seed}, {Sources} sources, {Probes} probes", project.Version, project.Seed, project.Sources.Count, project.Probes.Count);+ return project;+ }++ /// <summary>Reads the project file at <paramref name="path"/>.</summary>+ public static Project Load(string path)+ {+ Logger.Info("Loading project from '{Path}'", path);+ using FileStream stream = File.OpenRead(path);+ return Load(stream);+ }++ /// <summary>Clamps every setting into its valid range and regenerates the source emitters.</summary>+ public void Normalize()+ {+ Scene.Normalize();+ Simulation.Normalize();+ Display.Normalize();+ foreach (Source source in Sources)+ {+ source.Normalize();+ source.GenerateElements(Seed);+ }+ foreach (Probe probe in Probes)+ {+ probe.Normalize();+ }+ }+}diff --git a/WaveDude/Model/Scene.cs b/WaveDude/Model/Scene.csnew file mode 100644index 0000000..edcabf7--- /dev/null+++ b/WaveDude/Model/Scene.cs@@ -0,0 +1,185 @@+using System.ComponentModel;+using System.Xml.Serialization;++namespace WaveDude.Model;++/// <summary>Where the canvas comes from.</summary>+public enum SceneMode+{+ /// <summary>A blank canvas of <see cref="Scene.Width"/> × <see cref="Scene.Height"/> pixels.</summary>+ Canvas,+ /// <summary>The canvas is built from <see cref="Scene.Image"/>.</summary>+ Image,+}++/// <summary>+/// The simulation canvas: its origin (blank or image), the damping border and the options for+/// sources painted into the image. Positions throughout the project are canvas pixels with the+/// origin at the top left.+/// </summary>+[TypeConverter(typeof(ExpandableObjectConverter))]+public sealed class Scene : ObservableObject+{+ /// <summary>Default <see cref="Width"/> in pixels.</summary>+ public const int DefaultWidth = 1920;+ /// <summary>Default <see cref="Height"/> in pixels.</summary>+ public const int DefaultHeight = 1080;+ /// <summary>Smallest accepted canvas width or height in pixels.</summary>+ public const int MinSize = 8;+ /// <summary>Largest accepted canvas width or height in pixels.</summary>+ public const int MaxSize = 16384;+ /// <summary>Damping frame thickness the editor proposes when the frame is switched on.</summary>+ public const int DefaultDampingEdge = 64;+ /// <summary>Largest accepted <see cref="DampingEdge"/> in pixels.</summary>+ public const int MaxDampingEdge = 8192;+ /// <summary>Default <see cref="ImageSourceScale"/>.</summary>+ public const double DefaultImageSourceScale = 1.0;+ /// <summary>Largest accepted <see cref="ImageSourceScale"/>.</summary>+ public const double MaxImageSourceScale = 1000.0;+ /// <summary>Default <see cref="RefractiveIndex"/>.</summary>+ public const double DefaultRefractiveIndex = 1.0;+ /// <summary>Smallest accepted <see cref="RefractiveIndex"/>.</summary>+ public const double MinRefractiveIndex = 1.0;+ /// <summary>Largest accepted <see cref="RefractiveIndex"/>.</summary>+ public const double MaxRefractiveIndex = 2.55;++ private SceneMode _mode = SceneMode.Canvas;+ private string _image = "";+ private int _width = DefaultWidth;+ private int _height = DefaultHeight;+ private int _dampingEdge;+ private double _refractiveIndex = DefaultRefractiveIndex;+ private bool _imageSources;+ private double _imageSourceScale = DefaultImageSourceScale;+ private bool _objectSources = true;++ /// <summary>Blank canvas of <see cref="Width"/> × <see cref="Height"/>, or a canvas built from <see cref="Image"/>.</summary>+ [XmlAttribute]+ [DefaultValue(SceneMode.Canvas)]+ [Category("Canvas")]+ [Description("Blank canvas of the given size, or a canvas built from the scene image.")]+ public SceneMode Mode+ {+ get => _mode;+ set => SetProperty(ref _mode, value);+ }++ /// <summary>+ /// Scene image path, relative to the project folder when inside it; "" when none. Red is the+ /// refractive index, green marks sources, blue marks damping.+ /// </summary>+ [XmlAttribute]+ [DefaultValue("")]+ [Category("Canvas")]+ [DisplayName("Scene image")]+ [Description("Image the canvas is built from: red = refractive index, green = sources, blue = damping. Relative to the project folder.")]+ public string Image+ {+ get => _image;+ set => SetProperty(ref _image, value);+ }++ /// <summary>Width of a blank canvas in pixels.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultWidth)]+ [Category("Canvas")]+ [Description("Width of a blank canvas in pixels.")]+ public int Width+ {+ get => _width;+ set => SetProperty(ref _width, value);+ }++ /// <summary>Height of a blank canvas in pixels.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultHeight)]+ [Category("Canvas")]+ [Description("Height of a blank canvas in pixels.")]+ public int Height+ {+ get => _height;+ set => SetProperty(ref _height, value);+ }++ /// <summary>Thickness of the absorbing frame around the canvas in pixels; 0 turns it off.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Canvas")]+ [DisplayName("Damping edge")]+ [Description("Thickness in pixels of the absorbing frame around the canvas. 0 turns it off.")]+ public int DampingEdge+ {+ get => _dampingEdge;+ set => SetProperty(ref _dampingEdge, value);+ }++ /// <summary>Refractive index of a blank canvas, 1.0 to 2.55; the wave speed is 1/n cells per step.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultRefractiveIndex)]+ [Category("Canvas")]+ [DisplayName("Refractive index")]+ [Description("Refractive index of a blank canvas, 1.0 to 2.55. The wave speed is 1/n cells per step.")]+ public double RefractiveIndex+ {+ get => _refractiveIndex;+ set => SetProperty(ref _refractiveIndex, value);+ }++ /// <summary>Whether the green channel of the scene image emits waves, the pixel value being the frequency level.</summary>+ [XmlAttribute]+ [DefaultValue(false)]+ [Category("Sources")]+ [DisplayName("Image sources")]+ [Description("Let the green channel of the scene image emit waves; the pixel value is the frequency level.")]+ public bool ImageSources+ {+ get => _imageSources;+ set => SetProperty(ref _imageSources, value);+ }++ /// <summary>Peak amplitude of the image sources.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultImageSourceScale)]+ [Category("Sources")]+ [DisplayName("Image source amplitude")]+ [Description("Peak amplitude of the image sources.")]+ public double ImageSourceScale+ {+ get => _imageSourceScale;+ set => SetProperty(ref _imageSourceScale, value);+ }++ /// <summary>Whether the project's <see cref="Source"/>s take part in the run.</summary>+ [XmlAttribute]+ [DefaultValue(true)]+ [Category("Sources")]+ [DisplayName("Object sources")]+ [Description("Use the sources defined in the project.")]+ public bool ObjectSources+ {+ get => _objectSources;+ set => SetProperty(ref _objectSources, value);+ }++ /// <summary>True when every value is at its default, so the element can be left out of the file.</summary>+ [XmlIgnore]+ [Browsable(false)]+ public bool IsDefault =>+ Mode == SceneMode.Canvas && Image.Length == 0 && Width == DefaultWidth && Height == DefaultHeight+ && DampingEdge == 0 && RefractiveIndex == DefaultRefractiveIndex && !ImageSources+ && ImageSourceScale == DefaultImageSourceScale && ObjectSources;++ /// <summary>Clamps every value into its valid range.</summary>+ public void Normalize()+ {+ Image ??= "";+ Width = Math.Clamp(Width, MinSize, MaxSize);+ Height = Math.Clamp(Height, MinSize, MaxSize);+ DampingEdge = Math.Clamp(DampingEdge, 0, MaxDampingEdge);+ RefractiveIndex = Math.Clamp(RefractiveIndex, MinRefractiveIndex, MaxRefractiveIndex);+ ImageSourceScale = Math.Clamp(ImageSourceScale, 0, MaxImageSourceScale);+ }++ /// <summary>The image path, or the canvas size, for display in a property grid.</summary>+ public override string ToString() => Mode == SceneMode.Image ? Image : $"{Width} × {Height}";+}diff --git a/WaveDude/Model/Simulation.cs b/WaveDude/Model/Simulation.csnew file mode 100644index 0000000..19bf3ae--- /dev/null+++ b/WaveDude/Model/Simulation.cs@@ -0,0 +1,152 @@+using System.ComponentModel;+using System.Xml.Serialization;++namespace WaveDude.Model;++/// <summary>Solver parameters and run length.</summary>+[TypeConverter(typeof(ExpandableObjectConverter))]+public sealed class Simulation : ObservableObject+{+ /// <summary>Default <see cref="Steps"/>.</summary>+ public const int DefaultSteps = 2500;+ /// <summary>Largest accepted <see cref="Steps"/>.</summary>+ public const int MaxSteps = 10_000_000;+ /// <summary>Default <see cref="VisualizeEvery"/>.</summary>+ public const int DefaultVisualizeEvery = 2;+ /// <summary>Largest accepted <see cref="VisualizeEvery"/>.</summary>+ public const int MaxVisualizeEvery = 1000;+ /// <summary>Default <see cref="WaveSpeed"/> in pixels per step.</summary>+ public const double DefaultWaveSpeed = 1.0;+ /// <summary>Default <see cref="TimeDecay"/>.</summary>+ public const double DefaultTimeDecay = 10.0;+ /// <summary>Default <see cref="SourceFrequencyScale"/>.</summary>+ public const double DefaultSourceFrequencyScale = 2.0;+ /// <summary>Default <see cref="IntensityScale"/>.</summary>+ public const double DefaultIntensityScale = 1.0;++ private int _steps = DefaultSteps;+ private int _visualizeEvery = DefaultVisualizeEvery;+ private bool _gpu;+ private bool _fourthOrderLaplacian = true;+ private double _waveSpeed = DefaultWaveSpeed;+ private double _timeDecay = DefaultTimeDecay;+ private double _sourceFrequencyScale = DefaultSourceFrequencyScale;+ private double _intensityScale = DefaultIntensityScale;++ /// <summary>Total number of simulation steps.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultSteps)]+ [Category("Run")]+ [Description("Total number of simulation steps.")]+ public int Steps+ {+ get => _steps;+ set => SetProperty(ref _steps, value);+ }++ /// <summary>Render a frame, export it and sample the probes every this many steps.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultVisualizeEvery)]+ [Category("Run")]+ [DisplayName("Visualize every")]+ [Description("Render a frame, export it and sample the probes every this many steps.")]+ public int VisualizeEvery+ {+ get => _visualizeEvery;+ set => SetProperty(ref _visualizeEvery, value);+ }++ /// <summary>Run on the OpenCL engine when a usable GPU is found; otherwise on the CPU.</summary>+ [XmlAttribute]+ [DefaultValue(false)]+ [Category("Solver")]+ [DisplayName("Use GPU")]+ [Description("Run on the OpenCL engine when a usable GPU is found; otherwise on the CPU.")]+ public bool Gpu+ {+ get => _gpu;+ set => SetProperty(ref _gpu, value);+ }++ /// <summary>Use the 4th-order Laplacian stencil with sub-stepping instead of the 9-point one: more accurate, slower.</summary>+ [XmlAttribute]+ [DefaultValue(true)]+ [Category("Solver")]+ [DisplayName("4th-order Laplacian")]+ [Description("Use the 4th-order stencil with sub-stepping instead of the 9-point stencil. More accurate, slower.")]+ public bool FourthOrderLaplacian+ {+ get => _fourthOrderLaplacian;+ set => SetProperty(ref _fourthOrderLaplacian, value);+ }++ /// <summary>Nominal wave speed in pixels per step; only used to estimate wavelengths in the editor.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultWaveSpeed)]+ [Category("Solver")]+ [DisplayName("Wave speed")]+ [Description("Nominal wave speed in pixels per step; only used to estimate wavelengths in the editor.")]+ public double WaveSpeed+ {+ get => _waveSpeed;+ set => SetProperty(ref _waveSpeed, value);+ }++ /// <summary>Averaging window factor of the intensity: the engine averages over this × 100 / lowest source level steps.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultTimeDecay)]+ [Category("Solver")]+ [DisplayName("Intensity time decay")]+ [Description("Averaging window factor of the intensity: the engine averages over this × 100 / lowest source level steps.")]+ public double TimeDecay+ {+ get => _timeDecay;+ set => SetProperty(ref _timeDecay, value);+ }++ /// <summary>Multiplier of the level-to-frequency mapping: ω = level / 255 × 0.5 × scale, in radians per step.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultSourceFrequencyScale)]+ [Category("Solver")]+ [DisplayName("Source frequency scale")]+ [Description("Multiplier of the level-to-frequency mapping: ω = level / 255 × 0.5 × scale, in radians per step.")]+ public double SourceFrequencyScale+ {+ get => _sourceFrequencyScale;+ set => SetProperty(ref _sourceFrequencyScale, value);+ }++ /// <summary>Multiplier applied to the intensity values the engine produces.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultIntensityScale)]+ [Category("Solver")]+ [DisplayName("Intensity scale")]+ [Description("Multiplier applied to the intensity values the engine produces.")]+ public double IntensityScale+ {+ get => _intensityScale;+ set => SetProperty(ref _intensityScale, value);+ }++ /// <summary>True when every value is at its default, so the element can be left out of the file.</summary>+ [XmlIgnore]+ [Browsable(false)]+ public bool IsDefault =>+ Steps == DefaultSteps && VisualizeEvery == DefaultVisualizeEvery && !Gpu && FourthOrderLaplacian+ && WaveSpeed == DefaultWaveSpeed && TimeDecay == DefaultTimeDecay+ && SourceFrequencyScale == DefaultSourceFrequencyScale && IntensityScale == DefaultIntensityScale;++ /// <summary>Clamps every value into its valid range.</summary>+ public void Normalize()+ {+ Steps = Math.Clamp(Steps, 1, MaxSteps);+ VisualizeEvery = Math.Clamp(VisualizeEvery, 1, MaxVisualizeEvery);+ WaveSpeed = Math.Clamp(WaveSpeed, 1e-6, 1e6);+ TimeDecay = Math.Clamp(TimeDecay, 1.0, 100.0);+ SourceFrequencyScale = Math.Clamp(SourceFrequencyScale, 0.0, 1000.0);+ IntensityScale = Math.Clamp(IntensityScale, 1e-7, 1e6);+ }++ /// <summary>Step count and engine, for display in a property grid.</summary>+ public override string ToString() => $"{Steps} steps, {(Gpu ? "GPU" : "CPU")}";+}diff --git a/WaveDude/Model/Source.cs b/WaveDude/Model/Source.csnew file mode 100644index 0000000..9dcbf25--- /dev/null+++ b/WaveDude/Model/Source.cs@@ -0,0 +1,471 @@+using System.ComponentModel;+using System.Xml.Serialization;++namespace WaveDude.Model;++/// <summary>Continuous or pulsed emission.</summary>+public enum SourceMode+{+ /// <summary>Emits without interruption.</summary>+ Continuous,+ /// <summary>Emits bursts of <see cref="Source.PulseWidth"/> cycles separated by gaps of <see cref="Source.OffWidth"/> cycles.</summary>+ Pulsed,+}++/// <summary>Envelope of each burst in pulsed mode.</summary>+public enum PulseShape+{+ /// <summary>Gaussian bell.</summary>+ Gaussian,+ /// <summary>Flat top with smoothed flanks.</summary>+ SmoothedSquare,+}++/// <summary>+/// One wave source placed on the canvas: a single emitter, or a composite array of emitters+/// when <see cref="Array"/> is set. Units are those of the editor: positions in canvas pixels,+/// frequency as a 1..255 level, amplitude in percent, phase in degrees, widths in cycles of the+/// source frequency, detach time in simulation steps.+/// </summary>+public sealed class Source : ObservableObject+{+ /// <summary>Smallest frequency level.</summary>+ public const int MinLevel = 1;+ /// <summary>Largest frequency level.</summary>+ public const int MaxLevel = 255;+ /// <summary>Default <see cref="Frequency"/>.</summary>+ public const int DefaultLevel = 100;+ /// <summary>Default <see cref="Amplitude"/> in percent.</summary>+ public const int DefaultAmplitude = 100;+ /// <summary>Default <see cref="PulseWidth"/> and <see cref="OffWidth"/> in cycles.</summary>+ public const int DefaultWidth = 10;+ /// <summary>Value of <see cref="DetachAfter"/> meaning the source stays on for the whole run.</summary>+ public const int NeverDetach = -1;++ private string _name = "";+ private bool _enabled = true;+ private int _x;+ private int _y;+ private int _frequency = DefaultLevel;+ private int _amplitude = DefaultAmplitude;+ private int _phase;+ private SourceMode _mode = SourceMode.Continuous;+ private PulseShape _pulseShape = PulseShape.Gaussian;+ private int _pulseWidth = DefaultWidth;+ private int _offWidth = DefaultWidth;+ private int _detachAfter = NeverDetach;+ private SourceArray? _array;++ /// <summary>Name shown in the project tree and on the canvas; must be non-blank.</summary>+ [XmlAttribute]+ [Category("General")]+ [Description("Name shown in the project tree and on the canvas.")]+ public string Name+ {+ get => _name;+ set => SetProperty(ref _name, value);+ }++ /// <summary>Whether the source takes part in simulation runs.</summary>+ [XmlAttribute]+ [DefaultValue(true)]+ [Category("General")]+ [Description("Include the source in simulation runs.")]+ public bool Enabled+ {+ get => _enabled;+ set => SetProperty(ref _enabled, value);+ }++ /// <summary>X of the emitter, or of the array centre, in canvas pixels.</summary>+ [XmlAttribute]+ [Category("Position")]+ [Description("X of the emitter, or of the array centre, in canvas pixels.")]+ public int X+ {+ get => _x;+ set => SetProperty(ref _x, value);+ }++ /// <summary>Y of the emitter, or of the array centre, in canvas pixels.</summary>+ [XmlAttribute]+ [Category("Position")]+ [Description("Y of the emitter, or of the array centre, in canvas pixels.")]+ public int Y+ {+ get => _y;+ set => SetProperty(ref _y, value);+ }++ /// <summary>Frequency as a level 1..255, the same scale as the green channel of image sources (ω = level / 255 × 0.5 × <see cref="Simulation.SourceFrequencyScale"/>).</summary>+ [XmlAttribute]+ [DefaultValue(DefaultLevel)]+ [Category("Wave")]+ [Description("Frequency as a level from 1 to 255, the same scale as the green channel of image sources.")]+ public int Frequency+ {+ get => _frequency;+ set => SetProperty(ref _frequency, value);+ }++ /// <summary>Amplitude in percent, 0 to 100.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultAmplitude)]+ [Category("Wave")]+ [Description("Amplitude in percent, 0 to 100.")]+ public int Amplitude+ {+ get => _amplitude;+ set => SetProperty(ref _amplitude, value);+ }++ /// <summary>Phase offset in degrees, -180 to 180.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Wave")]+ [Description("Phase offset in degrees, -180 to 180.")]+ public int Phase+ {+ get => _phase;+ set => SetProperty(ref _phase, value);+ }++ /// <summary>Emit continuously or in bursts.</summary>+ [XmlAttribute]+ [DefaultValue(SourceMode.Continuous)]+ [Category("Pulsing")]+ [Description("Emit continuously or in bursts.")]+ public SourceMode Mode+ {+ get => _mode;+ set => SetProperty(ref _mode, value);+ }++ /// <summary>Envelope of each burst; pulsed mode only.</summary>+ [XmlAttribute]+ [DefaultValue(PulseShape.Gaussian)]+ [Category("Pulsing")]+ [DisplayName("Pulse shape")]+ [Description("Envelope of each burst; pulsed mode only.")]+ public PulseShape PulseShape+ {+ get => _pulseShape;+ set => SetProperty(ref _pulseShape, value);+ }++ /// <summary>Length of each burst in cycles of the source frequency; pulsed mode only.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultWidth)]+ [Category("Pulsing")]+ [DisplayName("Pulse width")]+ [Description("Length of each burst in cycles of the source frequency; pulsed mode only.")]+ public int PulseWidth+ {+ get => _pulseWidth;+ set => SetProperty(ref _pulseWidth, value);+ }++ /// <summary>Length of the gap between bursts in cycles; pulsed mode only.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultWidth)]+ [Category("Pulsing")]+ [DisplayName("Off width")]+ [Description("Length of the gap between bursts in cycles; pulsed mode only.")]+ public int OffWidth+ {+ get => _offWidth;+ set => SetProperty(ref _offWidth, value);+ }++ /// <summary>Simulation step at which the source fades out; <see cref="NeverDetach"/> keeps it on for the whole run.</summary>+ [XmlAttribute]+ [DefaultValue(NeverDetach)]+ [Category("General")]+ [DisplayName("Detach after step")]+ [Description("Simulation step at which the source fades out; -1 keeps it on for the whole run.")]+ public int DetachAfter+ {+ get => _detachAfter;+ set => SetProperty(ref _detachAfter, value);+ }++ /// <summary>Grid of emitters around the position; null for a single emitter.</summary>+ [XmlElement]+ [Category("Array")]+ [Description("Grid of emitters around the position; empty for a single emitter.")]+ public SourceArray? Array+ {+ get => _array;+ set+ {+ if (SetProperty(ref _array, value))+ {+ OnPropertyChanged(nameof(IsComposite));+ }+ }+ }++ /// <summary>+ /// The emitters generated from the settings by <see cref="GenerateElements"/>. Not stored:+ /// they are a pure function of the settings and the project seed.+ /// </summary>+ [XmlIgnore]+ [Browsable(false)]+ public List<SourceElement> Elements { get; private set; } = new();++ /// <summary>+ /// True for a composite source. Setting it creates a default <see cref="Array"/> or removes+ /// the existing one; the file stores the array itself, not this flag.+ /// </summary>+ [XmlIgnore]+ [Category("Array")]+ [DisplayName("Composite source")]+ [Description("Emit from an array of emitters instead of a single point.")]+ public bool IsComposite+ {+ get => Array != null;+ set+ {+ if (value != IsComposite)+ {+ Array = value ? new SourceArray() : null;+ }+ }+ }++ /// <summary>True when the array applies random per-emitter offsets.</summary>+ [XmlIgnore]+ [Browsable(false)]+ public bool IsRandomized => Array?.IsRandomized == true;++ /// <summary>+ /// Random stream for this source: derived from the project seed and the source name, so+ /// the same name in the same project always jitters the same way regardless of list order.+ /// </summary>+ public Pcg32 CreateRandom(int projectSeed) => new((ulong)(uint)projectSeed, Pcg32.StableHash(Name));++ /// <summary>Clamps every value into its valid range.</summary>+ public void Normalize()+ {+ Name ??= "";+ Frequency = Math.Clamp(Frequency, MinLevel, MaxLevel);+ Amplitude = Math.Clamp(Amplitude, 0, 100);+ Phase = Math.Clamp(Phase, -180, 180);+ PulseWidth = Math.Max(1, PulseWidth);+ OffWidth = Math.Max(1, OffWidth);+ if (DetachAfter < 0)+ {+ DetachAfter = NeverDetach;+ }+ Array?.Normalize();+ }++ /// <summary>+ /// Rebuilds <see cref="Elements"/>: one emitter for a single source, or the array grid+ /// centred on (<see cref="X"/>, <see cref="Y"/>) with the array's random offsets applied.+ /// Deterministic for a given project seed, name and settings.+ /// </summary>+ public void GenerateElements(int projectSeed)+ {+ Normalize();+ Pcg32 rng = CreateRandom(projectSeed);+ var elements = new List<SourceElement>();+ if (Array is not { } array)+ {+ elements.Add(new SourceElement { X = X, Y = Y, Level = Frequency, Phase = Phase, OffWidth = OffWidth });+ }+ else+ {+ for (int row = 0; row < array.SizeY; row++)+ {+ for (int column = 0; column < array.SizeX; column++)+ {+ // grid centred on (X, Y); with an even size the centre falls between two emitters+ int x = X + (int)Math.Round((column - (array.SizeX - 1) / 2.0) * array.SpacingX);+ int y = Y + (int)Math.Round((row - (array.SizeY - 1) / 2.0) * array.SpacingY);+ elements.Add(new SourceElement+ {+ X = x + Jitter(rng, array.RandomPosition),+ Y = y + Jitter(rng, array.RandomPosition),+ Level = Math.Clamp(Frequency + Jitter(rng, array.RandomFrequency), MinLevel, MaxLevel),+ Phase = Math.Clamp(Phase + Jitter(rng, array.RandomPhase), -180, 180),+ OffWidth = Math.Max(1, OffWidth + Jitter(rng, array.RandomOffWidth)),+ });+ }+ }+ }+ Elements = elements;+ }++ /// <summary>Uniform random integer in [-amount, +amount]; 0 when amount is not positive.</summary>+ public static int Jitter(Pcg32 rng, int amount) => amount <= 0 ? 0 : rng.Next(-amount, amount);++ /// <summary>A deep copy with the same settings, its own emitter array and no change subscribers.</summary>+ public Source Clone()+ {+ Source copy = ShallowClone<Source>();+ copy.Array = Array?.Clone();+ copy.Elements = new List<SourceElement>(Elements);+ return copy;+ }++ /// <summary>The name, for display in the project tree and property grids.</summary>+ public override string ToString() => Name;+}++/// <summary>Grid layout of a composite source and its per-emitter randomisation. Amounts of 0 mean off.</summary>+[TypeConverter(typeof(ExpandableObjectConverter))]+public sealed class SourceArray : ObservableObject+{+ /// <summary>Default <see cref="SpacingX"/> and <see cref="SpacingY"/> in pixels.</summary>+ public const int DefaultSpacing = 10;++ private int _sizeX = 1;+ private int _sizeY = 1;+ private int _spacingX = DefaultSpacing;+ private int _spacingY = DefaultSpacing;+ private int _randomFrequency;+ private int _randomPhase;+ private int _randomOffWidth;+ private int _randomPosition;++ /// <summary>Number of emitters across; odd counts keep the centre emitter on the source position.</summary>+ [XmlAttribute]+ [DefaultValue(1)]+ [Category("Grid")]+ [DisplayName("Columns")]+ [Description("Number of emitters across. Odd counts keep the centre emitter on the source position.")]+ public int SizeX+ {+ get => _sizeX;+ set => SetProperty(ref _sizeX, value);+ }++ /// <summary>Number of emitters down.</summary>+ [XmlAttribute]+ [DefaultValue(1)]+ [Category("Grid")]+ [DisplayName("Rows")]+ [Description("Number of emitters down.")]+ public int SizeY+ {+ get => _sizeY;+ set => SetProperty(ref _sizeY, value);+ }++ /// <summary>Distance between neighbouring columns in canvas pixels.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultSpacing)]+ [Category("Grid")]+ [DisplayName("Horizontal spacing")]+ [Description("Distance between neighbouring columns in canvas pixels.")]+ public int SpacingX+ {+ get => _spacingX;+ set => SetProperty(ref _spacingX, value);+ }++ /// <summary>Distance between neighbouring rows in canvas pixels.</summary>+ [XmlAttribute]+ [DefaultValue(DefaultSpacing)]+ [Category("Grid")]+ [DisplayName("Vertical spacing")]+ [Description("Distance between neighbouring rows in canvas pixels.")]+ public int SpacingY+ {+ get => _spacingY;+ set => SetProperty(ref _spacingY, value);+ }++ /// <summary>Half-range of the per-emitter frequency offset in levels; 0 turns it off.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Randomisation")]+ [DisplayName("Frequency")]+ [Description("Each emitter's level is offset by up to ± this amount. 0 turns it off.")]+ public int RandomFrequency+ {+ get => _randomFrequency;+ set => SetProperty(ref _randomFrequency, value);+ }++ /// <summary>Half-range of the per-emitter phase offset in degrees; 0 turns it off.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Randomisation")]+ [DisplayName("Phase")]+ [Description("Each emitter's phase is offset by up to ± this many degrees. 0 turns it off.")]+ public int RandomPhase+ {+ get => _randomPhase;+ set => SetProperty(ref _randomPhase, value);+ }++ /// <summary>Half-range of the gap offset in cycles, re-drawn by the engine every period; 0 turns it off.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Randomisation")]+ [DisplayName("Off width")]+ [Description("Each gap between bursts is offset by up to ± this many cycles, re-drawn every period. 0 turns it off.")]+ public int RandomOffWidth+ {+ get => _randomOffWidth;+ set => SetProperty(ref _randomOffWidth, value);+ }++ /// <summary>Half-range of the per-emitter position jitter in canvas pixels, independent for X and Y; 0 turns it off.</summary>+ [XmlAttribute]+ [DefaultValue(0)]+ [Category("Randomisation")]+ [DisplayName("Position")]+ [Description("Each emitter is moved by up to ± this many pixels in X and in Y. 0 turns it off.")]+ public int RandomPosition+ {+ get => _randomPosition;+ set => SetProperty(ref _randomPosition, value);+ }++ /// <summary>True when any random amount is positive.</summary>+ [XmlIgnore]+ [Browsable(false)]+ public bool IsRandomized => RandomFrequency > 0 || RandomPhase > 0 || RandomOffWidth > 0 || RandomPosition > 0;++ /// <summary>Clamps every value into its valid range.</summary>+ public void Normalize()+ {+ SizeX = Math.Max(1, SizeX);+ SizeY = Math.Max(1, SizeY);+ RandomFrequency = Math.Max(0, RandomFrequency);+ RandomPhase = Math.Max(0, RandomPhase);+ RandomOffWidth = Math.Max(0, RandomOffWidth);+ RandomPosition = Math.Max(0, RandomPosition);+ }++ /// <summary>A copy with the same settings and no change subscribers.</summary>+ public SourceArray Clone() => ShallowClone<SourceArray>();++ /// <summary>The grid size, for display in a property grid.</summary>+ public override string ToString() => $"{SizeX} × {SizeY}";+}++/// <summary>+/// One emitter of a source after generation. Holds only what can differ between the emitters+/// of one source; amplitude, mode, shape, pulse width and detach time come from the source.+/// </summary>+public sealed class SourceElement+{+ /// <summary>X in canvas pixels.</summary>+ public int X { get; init; }++ /// <summary>Y in canvas pixels.</summary>+ public int Y { get; init; }++ /// <summary>Frequency level 1..255.</summary>+ public int Level { get; init; } = Source.DefaultLevel;++ /// <summary>Phase offset in degrees.</summary>+ public int Phase { get; init; }++ /// <summary>Gap between bursts in cycles (pulsed mode).</summary>+ public int OffWidth { get; init; } = Source.DefaultWidth;+}diff --git a/WaveDude/Pcg32.cs b/WaveDude/Pcg32.csnew file mode 100644index 0000000..9163af6--- /dev/null+++ b/WaveDude/Pcg32.cs@@ -0,0 +1,71 @@+namespace WaveDude;++/// <summary>+/// Small deterministic pseudo-random generator (PCG-XSH-RR, 64-bit state, 32-bit output).+/// Used wherever a project needs reproducible randomness, because sequences from a seeded+/// <see cref="Random"/> are not guaranteed to stay identical across .NET versions.+/// </summary>+public sealed class Pcg32+{+ private const ulong Multiplier = 6364136223846793005UL;+ private ulong _state;+ private readonly ulong _increment;++ /// <param name="seed">Starting point of the sequence.</param>+ /// <param name="stream">Selects one of 2^63 independent sequences for the same seed.</param>+ public Pcg32(ulong seed, ulong stream = 0)+ {+ _increment = (stream << 1) | 1;+ _state = 0;+ NextUInt32();+ _state += seed;+ NextUInt32();+ }++ /// <summary>Next value in the full 32-bit range.</summary>+ public uint NextUInt32()+ {+ ulong old = _state;+ _state = old * Multiplier + _increment;+ uint xorShifted = (uint)(((old >> 18) ^ old) >> 27);+ int rotation = (int)(old >> 59);+ return (xorShifted >> rotation) | (xorShifted << ((-rotation) & 31));+ }++ /// <summary>Uniform integer in [<paramref name="minInclusive"/>, <paramref name="maxInclusive"/>].</summary>+ public int Next(int minInclusive, int maxInclusive)+ {+ if (maxInclusive < minInclusive)+ {+ throw new ArgumentOutOfRangeException(nameof(maxInclusive), "Upper bound is below the lower bound.");+ }+ ulong range = (ulong)((long)maxInclusive - minInclusive) + 1;+ // rejection sampling keeps the distribution exactly uniform+ ulong limit = (1UL << 32) - ((1UL << 32) % range);+ uint value;+ do+ {+ value = NextUInt32();+ }+ while (value >= limit);+ return (int)(minInclusive + (long)(value % range));+ }++ /// <summary>Uniform double in [0, 1).</summary>+ public double NextDouble() => (NextUInt32() >> 8) * (1.0 / (1 << 24));++ /// <summary>+ /// Stable 32-bit FNV-1a hash of <paramref name="text"/> over its UTF-16 code units, for+ /// deriving per-object seeds from names. Unlike <see cref="string.GetHashCode()"/> it does+ /// not change between processes.+ /// </summary>+ public static uint StableHash(string text)+ {+ uint hash = 2166136261;+ foreach (char c in text)+ {+ hash = (hash ^ c) * 16777619;+ }+ return hash;+ }+}diff --git a/WaveDude/WaveDude.csproj b/WaveDude/WaveDude.csprojnew file mode 100644index 0000000..3b161a4--- /dev/null+++ b/WaveDude/WaveDude.csproj@@ -0,0 +1,15 @@+<Project Sdk="Microsoft.NET.Sdk">++ <PropertyGroup>+ <TargetFramework>net10.0</TargetFramework>+ <ImplicitUsings>enable</ImplicitUsings>+ <Nullable>enable</Nullable>+ <!-- every public member needs a /// comment; CS1591 flags the ones that lack it -->+ <GenerateDocumentationFile>true</GenerateDocumentationFile>+ </PropertyGroup>++ <ItemGroup>+ <PackageReference Include="NLog" Version="6.2.1" />+ </ItemGroup>++</Project>diff --git a/Wave_Dude_2D.sln b/Wave_Dude_2D.slnindex fa65bab..bfa3aab 100644--- a/Wave_Dude_2D.sln+++ b/Wave_Dude_2D.sln@@ -1,22 +1,79 @@-+Microsoft Visual Studio Solution File, Format Version 12.00-# Visual Studio Version 17-VisualStudioVersion = 17.0.31903.59+# Visual Studio Version 18+VisualStudioVersion = 18.10.12224.181 stableMinimumVisualStudioVersion = 10.0.40219.1Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wave_Dude_2D", "Wave_Dude_2D\Wave_Dude_2D.csproj", "{C3F63FB8-2009-4631-AB8D-4E176E131C5F}"EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WaveDude", "WaveDude\WaveDude.csproj", "{5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}"+EndProject+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WaveDude.WPF", "WaveDude.WPF\WaveDude.WPF.csproj", "{0EACDED4-F7E3-4BCF-B82D-55401711BDAA}"+EndProject+Project("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}") = "2D_wave_sim_V01", "2D_wave_sim_V01\2D_wave_sim_V01.vbproj", "{BF62C6CF-8723-482A-A1E9-784946CFD426}"+EndProjectGlobalGlobalSection(SolutionConfigurationPlatforms) = preSolutionDebug|Any CPU = Debug|Any CPU+ Debug|x64 = Debug|x64+ Debug|x86 = Debug|x86Release|Any CPU = Release|Any CPU+ Release|x64 = Release|x64+ Release|x86 = Release|x86EndGlobalSectionGlobalSection(ProjectConfigurationPlatforms) = postSolution{C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU{C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|x64.ActiveCfg = Debug|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|x64.Build.0 = Debug|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|x86.ActiveCfg = Debug|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Debug|x86.Build.0 = Debug|Any CPU{C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|Any CPU.ActiveCfg = Release|Any CPU{C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|Any CPU.Build.0 = Release|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|x64.ActiveCfg = Release|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|x64.Build.0 = Release|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|x86.ActiveCfg = Release|Any CPU+ {C3F63FB8-2009-4631-AB8D-4E176E131C5F}.Release|x86.Build.0 = Release|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Debug|x64.ActiveCfg = Debug|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Debug|x64.Build.0 = Debug|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Debug|x86.ActiveCfg = Debug|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Debug|x86.Build.0 = Debug|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Release|Any CPU.Build.0 = Release|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Release|x64.ActiveCfg = Release|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Release|x64.Build.0 = Release|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Release|x86.ActiveCfg = Release|Any CPU+ {5F15EA39-6EA9-4352-87C4-B0870C2B9CE5}.Release|x86.Build.0 = Release|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Debug|x64.ActiveCfg = Debug|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Debug|x64.Build.0 = Debug|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Debug|x86.ActiveCfg = Debug|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Debug|x86.Build.0 = Debug|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Release|Any CPU.Build.0 = Release|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Release|x64.ActiveCfg = Release|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Release|x64.Build.0 = Release|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Release|x86.ActiveCfg = Release|Any CPU+ {0EACDED4-F7E3-4BCF-B82D-55401711BDAA}.Release|x86.Build.0 = Release|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Debug|Any CPU.ActiveCfg = Debug|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Debug|Any CPU.Build.0 = Debug|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Debug|x64.ActiveCfg = Debug|x64+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Debug|x64.Build.0 = Debug|x64+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Debug|x86.ActiveCfg = Debug|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Debug|x86.Build.0 = Debug|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Release|Any CPU.ActiveCfg = Release|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Release|Any CPU.Build.0 = Release|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Release|x64.ActiveCfg = Release|x64+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Release|x64.Build.0 = Release|x64+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Release|x86.ActiveCfg = Release|Any CPU+ {BF62C6CF-8723-482A-A1E9-784946CFD426}.Release|x86.Build.0 = Release|Any CPUEndGlobalSectionGlobalSection(SolutionProperties) = preSolutionHideSolutionNode = FALSEEndGlobalSection+ GlobalSection(ExtensibilityGlobals) = postSolution+ SolutionGuid = {83B9D680-B0B2-441D-9B2E-8EE36FE2E69D}+ EndGlobalSectionEndGlobaldiff --git a/_tools/ui_check/MessagesCheck.ps1 b/_tools/ui_check/MessagesCheck.ps1new file mode 100644index 0000000..fb190ef--- /dev/null+++ b/_tools/ui_check/MessagesCheck.ps1@@ -0,0 +1,75 @@+# UI harness for the Messages pane: shows the pane through View > Panes, checks that start-up+# lines are listed, that the level toggles carry counts, that the search box filters, and+# screenshots the result.+param(+ [string]$Dir = (Resolve-Path (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows")).Path,+ [string]$Screenshot = (Join-Path $PSScriptRoot "..\smoke.png")+)++$sample = Join-Path $Dir "sample.wdproj"+@'+<?xml version="1.0" encoding="utf-8"?>+<Project Version="1" Seed="12345">+ <Source Name="Point" X="10" Y="20" />+ <Probe Name="Centre" AX="960" AY="540" />+</Project>+'@ | Set-Content -Path $sample -Encoding utf8++Add-Type -AssemblyName UIAutomationClient+Add-Type -AssemblyName UIAutomationTypes+Add-Type -AssemblyName System.Drawing+Add-Type -AssemblyName System.Windows.Forms+Add-Type @"+using System; using System.Runtime.InteropServices;+public struct RECT { public int L, T, R, B; }+public static class W {+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);+}+"@+$A = [System.Windows.Automation.AutomationElement]+$TS = [System.Windows.Automation.TreeScope]+function ByName($scope, $name) { $scope.FindFirst($TS::Descendants, (New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, $name))) }+function ByType($scope, $type) { $scope.FindAll($TS::Descendants, (New-Object System.Windows.Automation.PropertyCondition($A::ControlTypeProperty, $type))) }+function Expand($e) { $e.GetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern).Expand(); Start-Sleep -Milliseconds 600 }++$p = Start-Process -FilePath (Join-Path $Dir "WaveDude.WPF.exe") -ArgumentList "`"$sample`"" -PassThru+Start-Sleep -Seconds 5+$p.Refresh()+[W]::SetForegroundWindow($p.MainWindowHandle) | Out-Null+$win = $A::RootElement.FindFirst($TS::Children, (New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $p.Id)))++# View > Panes > Messages, unless the saved layout already shows the pane (its search box exists)+if (ByName $win "Search") {+ "pane already shown"+} else {+ Expand (ByName $win "View")+ Expand (ByName $win "Panes")+ (ByName $win "Messages").GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke()+ Start-Sleep -Seconds 2+}++function Rows { ByType $win ([System.Windows.Automation.ControlType]::DataItem) | Where-Object { $_.Current.Name -like "LogEntry*" } }+$rows = @(Rows)+"rows shown: " + $rows.Count+"toggles: " + ((ByType $win ([System.Windows.Automation.ControlType]::Button) | Where-Object { $_.Current.Name -match '^\w+ \(\d+\)$' } | ForEach-Object { $_.Current.Name }) -join ", ")++$search = ByName $win "Search"+$search.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern).SetValue("Opened")+Start-Sleep -Seconds 1+$rows = @(Rows)+"rows for 'Opened': " + $rows.Count + " -> " + (($rows | ForEach-Object { ($_.Current.Name -split "Message = ")[1] -split ", Exception" | Select-Object -First 1 }) -join " | ")++$search.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern).SetValue("")+Start-Sleep -Seconds 1+$r = New-Object RECT+[W]::GetWindowRect($p.MainWindowHandle, [ref]$r) | Out-Null+$bmp = New-Object System.Drawing.Bitmap(($r.R - $r.L), ($r.B - $r.T))+$g = [System.Drawing.Graphics]::FromImage($bmp)+$g.CopyFromScreen($r.L, $r.T, 0, 0, $bmp.Size)+$bmp.Save($Screenshot)+$g.Dispose(); $bmp.Dispose()++$null = $p.CloseMainWindow()+if (-not $p.WaitForExit(5000)) { Stop-Process -Id $p.Id -Force -Confirm:$false }+"exit: " + $p.ExitCodediff --git a/_tools/ui_check/PreviewCheck.ps1 b/_tools/ui_check/PreviewCheck.ps1new file mode 100644index 0000000..7bfe661--- /dev/null+++ b/_tools/ui_check/PreviewCheck.ps1@@ -0,0 +1,234 @@+# Drives the WPF preview pane with keystrokes posted to its window (WM_KEYDOWN/WM_CHAR) and reads+# the result back through UI Automation. Nothing here activates the app window or uses the mouse,+# so it can run while the machine is in use. UI Automation *patterns* (Invoke, SetValue, Select)+# are deliberately not used: on this app each one focuses its target and brings the window to the+# foreground. Prints PASS/FAIL per check and exits with the failure count.+#+# powershell -ExecutionPolicy Bypass -File _tools\ui_check\PreviewCheck.ps1 [-Exe <path>] [-Shot <png>] [-Trace]++param(+ [string]$Exe = (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows\WaveDude.WPF.exe"),+ [string]$Shot = (Join-Path $env:TEMP "wavedude_preview_check.png"),+ [switch]$Trace # append foreground state and focused element to every line+)++Add-Type -AssemblyName UIAutomationClient, UIAutomationTypes, System.Drawing, System.Windows.Forms+Add-Type -ReferencedAssemblies System.Drawing -TypeDefinition @"+using System;+using System.Drawing;+using System.Drawing.Imaging;+using System.Runtime.InteropServices;+public static class Native+{+ [DllImport("user32.dll")] static extern bool PrintWindow(IntPtr hwnd, IntPtr hdc, uint flags);+ [DllImport("user32.dll")] static extern bool GetWindowRect(IntPtr hwnd, out RECT rect);+ [DllImport("user32.dll")] static extern bool PostMessage(IntPtr hwnd, uint msg, IntPtr wParam, IntPtr lParam);+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();+ [StructLayout(LayoutKind.Sequential)] public struct RECT { public int Left, Top, Right, Bottom; }++ // PW_RENDERFULLCONTENT: ask DWM for the composed content, which a hardware-rendered WPF window needs+ public static void Capture(IntPtr hwnd, string path)+ {+ RECT r; GetWindowRect(hwnd, out r);+ using (var bmp = new Bitmap(r.Right - r.Left, r.Bottom - r.Top))+ {+ using (var g = Graphics.FromImage(bmp))+ {+ IntPtr hdc = g.GetHdc();+ PrintWindow(hwnd, hdc, 2);+ g.ReleaseHdc(hdc);+ }+ bmp.Save(path, ImageFormat.Png);+ }+ }++ // WM_KEYDOWN / WM_KEYUP posted straight to the window: no SendInput, no focus change+ public static void Key(IntPtr hwnd, int vk)+ {+ PostMessage(hwnd, 0x0100, (IntPtr)vk, (IntPtr)1);+ PostMessage(hwnd, 0x0101, (IntPtr)vk, (IntPtr)(1 | (1 << 30) | (1 << 31)));+ }++ // WM_CHAR: text input independent of the keyboard layout+ public static void Char(IntPtr hwnd, char c) { PostMessage(hwnd, 0x0102, (IntPtr)c, (IntPtr)1); }+}+"@++$A = [System.Windows.Automation.AutomationElement]+$VK_BACK = 0x08; $VK_TAB = 0x09; $VK_SPACE = 0x20; $VK_END = 0x23; $VK_HOME = 0x24+$VK_LEFT = 0x25; $VK_RIGHT = 0x27; $VK_PRIOR = 0x21; $VK_RETURN = 0x0D; $VK_ESCAPE = 0x1B; $VK_F4 = 0x73+$script:failures = 0++function Check([string]$name, [bool]$ok, [string]$detail = "") {+ $tag = if ($ok) { "PASS" } else { $script:failures++; "FAIL" }+ if ($Trace) { $detail += (" [fg={0} focus={1}]" -f (Foreground), (FocusedId)) }+ Write-Output ("{0} {1} {2}" -f $tag, $name, $detail)+}+function Foreground() {+ $fg = [Native]::GetForegroundWindow()+ if ($fg -eq $hwnd) { "APP" } elseif ($fg -eq $park.Handle) { "harness" } else { "other" }+}+function Find([string]$id) {+ $c = New-Object System.Windows.Automation.PropertyCondition($A::AutomationIdProperty, $id)+ $e = $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c)+ if ($e -eq $null) { throw "element '$id' not found" }+ return $e+}+function Pattern($e, [string]$name) {+ $type = [System.Windows.Automation.InvokePattern].Assembly.GetType("System.Windows.Automation." + $name + "Pattern", $true)+ return $e.GetCurrentPattern($type.GetField("Pattern").GetValue($null))+}+function Frame() { return (Find "PreviewFrame").Current.Name }+function Position() { return [int](((Frame) -split " / ")[0]) }+function Playing() { return (Find "PreviewPause").Current.IsEnabled }+function Selected([string]$id) { return (Pattern (Find $id) "SelectionItem").Current.IsSelected }+function SpeedText() { return (Pattern (Find "PreviewSpeed") "Value").Current.Value }+function Focused([string]$id) { return (Find $id).Current.HasKeyboardFocus }+function FocusedId() {+ foreach ($id in "PreviewPlay", "PreviewPause", "PreviewScrub", "PreviewSpeed", "PreviewSideBySide", "PreviewStacked", "PreviewSplitter") {+ if (Focused $id) { return $id }+ }+ # the editable combo keeps focus in its inner text box+ $c = New-Object System.Windows.Automation.PropertyCondition($A::HasKeyboardFocusProperty, $true)+ if ((Find "PreviewSpeed").FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c) -ne $null) { return "PreviewSpeed" }+ $other = $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, $c)+ if ($other -ne $null) { return "(other: " + $other.Current.ControlType.ProgrammaticName + " '" + $other.Current.Name + "')" }+ return "(none)"+}+function Key([int]$vk, [int]$settle = 150) { [Native]::Key($hwnd, $vk); Start-Sleep -Milliseconds $settle }+# Tab (posted) until the wanted element holds focus; the cycle runs through the whole window+function FocusOn([string]$id) {+ for ($i = 0; $i -lt 60; $i++) {+ if ((FocusedId) -eq $id) { return }+ Key $VK_TAB+ }+ throw "could not reach '$id' with Tab; focus is at $(FocusedId)"+}++# ---------------------------------------------------------------- launch+$p = Start-Process -FilePath $Exe -PassThru+$win = $null+for ($i = 0; $i -lt 100 -and $win -eq $null; $i++) {+ Start-Sleep -Milliseconds 200+ $c = New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $p.Id)+ $win = $A::RootElement.FindFirst([System.Windows.Automation.TreeScope]::Children, $c)+}+if ($win -eq $null) { throw "main window not found" }+$p.Refresh()+$hwnd = $p.MainWindowHandle+Start-Sleep -Milliseconds 800++# Windows may hand a new window the foreground. Park it on an off-screen window of our own (when+# the user is busy elsewhere this silently fails and the foreground stays theirs, which is just as+# good): every check below must then leave the app inactive.+$park = New-Object System.Windows.Forms.Form+$park.StartPosition = "Manual"+$park.Location = New-Object System.Drawing.Point(-3000, -3000)+$park.Size = New-Object System.Drawing.Size(10, 10)+$park.ShowInTaskbar = $false+$park.Show(); $park.Activate(); [System.Windows.Forms.Application]::DoEvents()+Start-Sleep -Milliseconds 500+Write-Output ("window: '{0}' foreground: {1}" -f $win.Current.Name, (Foreground))++try {+ Check "initial readout" ((Frame) -eq "0 / 1249") (Frame)+ Check "play enabled, pause disabled" ((Find "PreviewPlay").Current.IsEnabled -and -not (Playing))++ # ------------------------------------------------------------ transport+ Write-Output ("focus before any key: {0}" -f (FocusedId))+ FocusOn "PreviewPlay"+ Check "Tab reaches play while the window stays inactive" (((FocusedId) -eq "PreviewPlay") -and ((Foreground) -ne "APP")) (FocusedId)+ $order = @()+ for ($i = 0; $i -lt 5; $i++) { Key $VK_TAB 250; $order += (FocusedId) }+ # pause is disabled while not playing and is skipped; the split group is one stop (its checked radio); the splitter; then the pane is left+ Check "tab order play > scrubber > speed > split > splitter > out of the pane" (($order[0..3] -join ",") -eq "PreviewScrub,PreviewSpeed,PreviewSideBySide,PreviewSplitter" -and $order[4] -like "(other*") ($order -join ",")++ FocusOn "PreviewPlay"+ Key $VK_SPACE 2000+ $pos = Position+ Check "Space on play: ~60 frames in 2 s at speed 1" ($pos -ge 45 -and $pos -le 75) "position $pos"+ Check "pause enabled while playing, focus handed to pause" ((Playing) -and -not (Find "PreviewPlay").Current.IsEnabled -and (Focused "PreviewPause")) (FocusedId)+ Key $VK_SPACE 300+ $held = Position+ Start-Sleep -Milliseconds 700+ Check "Space on pause: position holds, focus handed back to play" (-not (Playing) -and (Position) -eq $held -and (Focused "PreviewPlay")) ("position {0}, focus {1}" -f $held, (FocusedId))++ # ------------------------------------------------------------ speed+ FocusOn "PreviewSpeed"+ # the drop-down lists the presets in the user's locale ("0,25" where the decimal separator is a comma)+ $quarter = (0.25).ToString([System.Globalization.CultureInfo]::CurrentCulture)+ Key $VK_F4 400+ $item = $win.FindFirst([System.Windows.Automation.TreeScope]::Descendants, (New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, $quarter)))+ Key $VK_ESCAPE 300+ Check "drop-down lists the presets in the current locale" ($item -ne $null -and $item.Current.ControlType -eq [System.Windows.Automation.ControlType]::ListItem) "looked for '$quarter'"+ $onePointFive = (1.5).ToString([System.Globalization.CultureInfo]::CurrentCulture)+ for ($i = 0; $i -lt 6; $i++) { Key $VK_BACK 30 }+ foreach ($ch in $onePointFive.ToCharArray()) { [Native]::Char($hwnd, $ch) }+ Start-Sleep -Milliseconds 300+ Check "typed 1.5 in the locale's spelling is accepted and shown as typed" ((SpeedText) -eq $onePointFive) ("typed '{0}', shows '{1}'" -f $onePointFive, (SpeedText))+ for ($i = 0; $i -lt 6; $i++) { Key $VK_BACK 30 }+ [Native]::Char($hwnd, [char]"4"); Start-Sleep -Milliseconds 300+ Check "typed speed 4 accepted" ((SpeedText) -eq "4") (SpeedText)+ Key $VK_SPACE 300+ Check "Space in the speed box neither plays nor types" (-not (Playing) -and (SpeedText) -eq "4") (SpeedText)+ $before = Position+ FocusOn "PreviewPlay"+ Key $VK_SPACE 2000+ Key $VK_SPACE 300 # focus was handed to pause+ $delta = (Position) - $before+ Check "speed 4: ~240 frames in 2 s" ($delta -ge 190 -and $delta -le 290) "delta $delta"++ # ------------------------------------------------------------ scrubber+ FocusOn "PreviewScrub"+ Key $VK_END 300+ Check "scrubber End goes to the last frame" ((Frame) -eq "1249 / 1249") (Frame)+ Key $VK_HOME 200+ Key $VK_RIGHT; Key $VK_RIGHT 300+ Check "scrubber Home then Right twice gives frame 2" ((Position) -eq 2) (Frame)+ Key $VK_PRIOR 300+ Check "scrubber PageUp steps 10 frames" ((Position) -eq 12) (Frame)+ Key $VK_SPACE 1000+ $playing = Playing+ Key $VK_SPACE 300+ Check "Space on the scrubber starts playback, Space again pauses" ($playing -and -not (Playing)) (Frame)++ # ------------------------------------------------------------ split+ FocusOn "PreviewSideBySide"+ Key $VK_RIGHT 400+ Check "Right arrow focuses and selects the stacked radio" ((Focused "PreviewStacked") -and (Selected "PreviewStacked") -and -not (Selected "PreviewSideBySide")) (FocusedId)+ # stacked: the intensity picture sits below the field picture, both centred on the same axis+ $fr = (Find "PreviewFieldImage").Current.BoundingRectangle; $ir = (Find "PreviewIntensityImage").Current.BoundingRectangle+ Check "stacked layout: intensity picture below the field picture, same left" ($ir.Top -gt $fr.Bottom -and [math]::Abs($ir.Left - $fr.Left) -lt 2) ("field {0},{1} intensity {2},{3}" -f $fr.Left, $fr.Top, $ir.Left, $ir.Top)+ $cell = (Find "PreviewSplitter").Current.BoundingRectangle+ Check "stacked layout: splitter is a horizontal bar between them" ($cell.Width -gt $cell.Height -and $cell.Top -ge $fr.Bottom -and $cell.Bottom -le $ir.Top) ("splitter {0}x{1} at {2},{3}" -f $cell.Width, $cell.Height, $cell.Left, $cell.Top)+ [Native]::Capture($hwnd, $Shot)+ Write-Output "screenshot: $Shot"+ # Tab must enter the group at the checked radio, which is now the second one+ FocusOn "PreviewScrub"+ Key $VK_TAB; Key $VK_TAB 300+ Check "Tab enters the split group at the checked (stacked) radio" (Focused "PreviewStacked") (FocusedId)+ Key $VK_LEFT 400+ $fr = $field.Current.BoundingRectangle; $ir = $intensity.Current.BoundingRectangle+ $fr = (Find "PreviewFieldImage").Current.BoundingRectangle; $ir = (Find "PreviewIntensityImage").Current.BoundingRectangle+ Check "Left arrow selects side by side again, pictures on one row, same top" ((Selected "PreviewSideBySide") -and (Focused "PreviewSideBySide") -and [math]::Abs($ir.Top - $fr.Top) -lt 2 -and $ir.Left -gt $fr.Right) ("field {0},{1} intensity {2},{3}" -f $fr.Left, $fr.Top, $ir.Left, $ir.Top)++ # ------------------------------------------------------------ splitter+ FocusOn "PreviewSplitter"+ $fw0 = (Find "PreviewFieldImage").Current.BoundingRectangle.Width+ Key $VK_RIGHT; Key $VK_RIGHT; Key $VK_RIGHT 400+ $fw1 = (Find "PreviewFieldImage").Current.BoundingRectangle.Width+ Check "Right arrow on the splitter widens the field picture" ($fw1 -gt $fw0 + 20) ("width {0} -> {1}" -f $fw0, $fw1)+ Key $VK_RETURN 400+ $fw2 = (Find "PreviewFieldImage").Current.BoundingRectangle.Width+ $iw2 = (Find "PreviewIntensityImage").Current.BoundingRectangle.Width+ Check "Enter on the splitter resets to half" ([math]::Abs($fw2 - $iw2) -lt 2 -and [math]::Abs($fw2 - $fw0) -lt 2) ("field {0} intensity {1}" -f $fw2, $iw2)++ Check "the app never took the foreground" ((Foreground) -ne "APP") (Foreground)+}+finally {+ $p.CloseMainWindow() | Out-Null+ if (-not $p.WaitForExit(5000)) { $p.Kill() }+ $park.Close()+ Write-Output ("{0} failure(s)" -f $script:failures)+}+exit $script:failuresdiff --git a/_tools/ui_check/ProjectTreeCheck.ps1 b/_tools/ui_check/ProjectTreeCheck.ps1new file mode 100644index 0000000..00bc4fc--- /dev/null+++ b/_tools/ui_check/ProjectTreeCheck.ps1@@ -0,0 +1,114 @@+# UI harness for the Project pane: drives add, move, duplicate, remove and drag-and-drop+# through UI Automation against the Debug build and prints the tree order after each step.+# Usage: powershell -NoProfile -ExecutionPolicy Bypass -File ProjectTreeCheck.ps1+param(+ [string]$Dir = (Resolve-Path (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows")).Path,+ [string]$Screenshot = (Join-Path $PSScriptRoot "..\smoke.png")+)++$sample = Join-Path $Dir "sample.wdproj"+@'+<?xml version="1.0" encoding="utf-8"?>+<Project Version="1" Seed="12345">+ <Source Name="Array" X="400" Y="300" Phase="15" Mode="Pulsed">+ <Array SizeX="3" SpacingX="12" RandomFrequency="10" RandomPhase="20" RandomPosition="2" />+ </Source>+ <Source Name="Point" X="10" Y="20" />+ <Probe Name="Centre" AX="960" AY="540" />+ <Probe Name="Edge" Kind="Line" AX="0" AY="0" BX="100" BY="100" />+</Project>+'@ | Set-Content -Path $sample -Encoding utf8++$log = Join-Path $Dir "WaveDude.WPF.log"+$before = (Get-Content $log -ErrorAction SilentlyContinue | Measure-Object -Line).Lines++Add-Type -AssemblyName UIAutomationClient+Add-Type -AssemblyName UIAutomationTypes+Add-Type -AssemblyName System.Drawing+Add-Type -AssemblyName System.Windows.Forms+Add-Type @"+using System; using System.Runtime.InteropServices;+public struct RECT { public int L, T, R, B; }+public static class W {+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);+ [DllImport("user32.dll")] public static extern void mouse_event(uint f, int dx, int dy, uint d, UIntPtr e);+}+"@++$A = [System.Windows.Automation.AutomationElement]+$TS = [System.Windows.Automation.TreeScope]+$treeItemCond = New-Object System.Windows.Automation.PropertyCondition($A::ControlTypeProperty, [System.Windows.Automation.ControlType]::TreeItem)++function Items { ($win.FindAll($TS::Descendants, $treeItemCond) | ForEach-Object { $_.Current.Name }) -join ", " }+function Item($name) { $win.FindAll($TS::Descendants, $treeItemCond) | Where-Object { $_.Current.Name -eq $name } | Select-Object -First 1 }+function Btn($scope, $name) { $scope.FindFirst($TS::Descendants, (New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, $name))) }+function Invoke-Btn($b) { $b.GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke(); Start-Sleep -Milliseconds 1200 }+function Selected { ($win.FindAll($TS::Descendants, $treeItemCond) | Where-Object { $_.GetCurrentPattern([System.Windows.Automation.SelectionItemPattern]::Pattern).Current.IsSelected } | ForEach-Object { $_.Current.Name }) -join "," }+function Drag($from, $to) {+ # press on the row centre, glide to 3 px below the top edge of the target row, release+ $sx = [int]($from.Left + 30); $sy = [int]($from.Top + $from.Height / 2)+ $tx = [int]($to.Left + 30); $ty = [int]($to.Top + 3)+ [W]::SetCursorPos($sx, $sy) | Out-Null+ [W]::mouse_event(2, 0, 0, 0, [UIntPtr]::Zero)+ Start-Sleep -Milliseconds 150+ foreach ($i in 1..10) {+ [W]::SetCursorPos($sx + [int](($tx - $sx) * $i / 10), $sy + [int](($ty - $sy) * $i / 10)) | Out-Null+ Start-Sleep -Milliseconds 60+ }+ Start-Sleep -Milliseconds 300+ [W]::mouse_event(4, 0, 0, 0, [UIntPtr]::Zero)+ Start-Sleep -Seconds 1+}++$p = Start-Process -FilePath (Join-Path $Dir "WaveDude.WPF.exe") -ArgumentList "`"$sample`"" -PassThru+Start-Sleep -Seconds 5+$p.Refresh()+[W]::SetForegroundWindow($p.MainWindowHandle) | Out-Null+Start-Sleep -Milliseconds 500+$win = $A::RootElement.FindFirst($TS::Children, (New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $p.Id)))++"0 start: " + (Items)++Invoke-Btn (Btn $win "Add a source (appended at the end)")+"1 add: " + (Items)+$f = $A::FocusedElement+" focused: " + $f.Current.ControlType.ProgrammaticName + " value=" + $f.GetCurrentPattern([System.Windows.Automation.ValuePattern]::Pattern).Current.Value++Invoke-Btn (Btn (Item "Source 1") "Move up (Alt+Up); drag to reorder")+"2 move up: " + (Items)++(Item "Source 1").SetFocus()+Start-Sleep -Milliseconds 500+[System.Windows.Forms.SendKeys]::SendWait("^d")+Start-Sleep -Seconds 1+"3 Ctrl+D: " + (Items)++Invoke-Btn (Btn (Item "Source 1 copy") ("Rem" + "ove (Del)"))+"4 minus: " + (Items)+" selected: " + (Selected)++Drag (Item "Edge").Current.BoundingRectangle (Item "Centre").Current.BoundingRectangle+"5 drag: " + (Items)++(Item "Point").SetFocus()+Start-Sleep -Milliseconds 500+[System.Windows.Forms.SendKeys]::SendWait("{DELETE}")+Start-Sleep -Seconds 1+"6 Del key: " + (Items)+" selected: " + (Selected)++$r = New-Object RECT+[W]::GetWindowRect($p.MainWindowHandle, [ref]$r) | Out-Null+$bmp = New-Object System.Drawing.Bitmap(($r.R - $r.L), ($r.B - $r.T))+$g = [System.Drawing.Graphics]::FromImage($bmp)+$g.CopyFromScreen($r.L, $r.T, 0, 0, $bmp.Size)+$bmp.Save($Screenshot)+$g.Dispose(); $bmp.Dispose()++$null = $p.CloseMainWindow()+if (-not $p.WaitForExit(5000)) { Stop-Process -Id $p.Id -Force -Confirm:$false }+"exit: " + $p.ExitCode+"=== errors this run ==="+Get-Content $log | Select-Object -Skip $before | Where-Object { $_ -match "System.Windows.Data|`tError`t|`tWarn`t|`tFatal`t" } | ForEach-Object { ($_ -split "`t")[2..4] -join " | " } | Select-Object -First 10diff --git a/_tools/ui_check/StatusBarCheck.ps1 b/_tools/ui_check/StatusBarCheck.ps1new file mode 100644index 0000000..6fff960--- /dev/null+++ b/_tools/ui_check/StatusBarCheck.ps1@@ -0,0 +1,81 @@+# UI harness for the status bar log target: starts the Debug build with a good project file+# (expects the "Opened" line in the bar) and with a missing one (expects the error line on red+# behind the message box), and screenshots the second case.+param(+ [string]$Dir = (Resolve-Path (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows")).Path,+ [string]$Screenshot = (Join-Path $PSScriptRoot "..\smoke.png")+)++$sample = Join-Path $Dir "sample.wdproj"+@'+<?xml version="1.0" encoding="utf-8"?>+<Project Version="1" Seed="12345">+ <Source Name="Point" X="10" Y="20" />+ <Probe Name="Centre" AX="960" AY="540" />+</Project>+'@ | Set-Content -Path $sample -Encoding utf8++Add-Type -AssemblyName UIAutomationClient+Add-Type -AssemblyName UIAutomationTypes+Add-Type -AssemblyName System.Drawing+Add-Type -AssemblyName System.Windows.Forms+Add-Type @"+using System; using System.Runtime.InteropServices;+public struct RECT { public int L, T, R, B; }+public static class W {+ [DllImport("user32.dll")] public static extern bool GetWindowRect(IntPtr h, out RECT r);+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);+}+"@+$A = [System.Windows.Automation.AutomationElement]+$TS = [System.Windows.Automation.TreeScope]++function Status($win) {+ $c = New-Object System.Windows.Automation.PropertyCondition($A::AutomationIdProperty, "txtStatus")+ $e = $win.FindFirst($TS::Descendants, $c)+ if ($e) { $e.Current.Name } else { "(status text not found)" }+}+function MainWindowOf($p) {+ $A::RootElement.FindFirst($TS::Children, (New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $p.Id)))+}++# 0. plain start: the closing start-up line+$p = Start-Process -FilePath (Join-Path $Dir "WaveDude.WPF.exe") -PassThru+Start-Sleep -Seconds 5+$win = MainWindowOf $p+"plain start -> status: " + (Status $win)+$null = $p.CloseMainWindow(); $p.WaitForExit(5000) | Out-Null++# 1. good file+$p = Start-Process -FilePath (Join-Path $Dir "WaveDude.WPF.exe") -ArgumentList "`"$sample`"" -PassThru+Start-Sleep -Seconds 5+$win = MainWindowOf $p+"good file -> status: " + (Status $win)+$null = $p.CloseMainWindow(); $p.WaitForExit(5000) | Out-Null++# 2. missing file: the error dialog is up, the bar behind it shows the error+$p = Start-Process -FilePath (Join-Path $Dir "WaveDude.WPF.exe") -ArgumentList "`"$Dir\does-not-exist.wdproj`"" -PassThru+Start-Sleep -Seconds 5+# UI Automation lists the owned message box under the main window, not under the desktop+$main = MainWindowOf $p+$dialog = $main.FindFirst($TS::Children, (New-Object System.Windows.Automation.PropertyCondition($A::ControlTypeProperty, [System.Windows.Automation.ControlType]::Window)))+"missing file -> dialog: " + $(if ($dialog) { $dialog.Current.Name } else { "(none)" })+"missing file -> status: " + (Status $main)+$p.Refresh()+$h = [IntPtr]$main.Current.NativeWindowHandle+$r = New-Object RECT+[W]::GetWindowRect($h, [ref]$r) | Out-Null+$bmp = New-Object System.Drawing.Bitmap(($r.R - $r.L), ($r.B - $r.T))+$g = [System.Drawing.Graphics]::FromImage($bmp)+$g.CopyFromScreen($r.L, $r.T, 0, 0, $bmp.Size)+$bmp.Save($Screenshot)+$g.Dispose(); $bmp.Dispose()+if ($dialog) {+ # the box's buttons are not exposed through this proxy; closing the window is the same as OK here+ $dialog.GetCurrentPattern([System.Windows.Automation.WindowPattern]::Pattern).Close()+ Start-Sleep -Seconds 1+ $p.Refresh()+}+$null = $p.CloseMainWindow()+if (-not $p.WaitForExit(5000)) { Stop-Process -Id $p.Id -Force -Confirm:$false }+"exit: " + $p.ExitCodediff --git a/_tools/ui_check/StatusBarDoubleClickCheck.ps1 b/_tools/ui_check/StatusBarDoubleClickCheck.ps1new file mode 100644index 0000000..cb0d3b8--- /dev/null+++ b/_tools/ui_check/StatusBarDoubleClickCheck.ps1@@ -0,0 +1,58 @@+# UI harness: double-clicking the status bar opens the Messages pane when hidden and focuses+# it when shown. Hides the pane first via View > Panes if needed.+param(+ [string]$Dir = (Resolve-Path (Join-Path $PSScriptRoot "..\..\WaveDude.WPF\bin\Debug\net10.0-windows")).Path+)++Add-Type -AssemblyName UIAutomationClient+Add-Type -AssemblyName UIAutomationTypes+Add-Type @"+using System; using System.Runtime.InteropServices;+public static class W {+ [DllImport("user32.dll")] public static extern bool SetForegroundWindow(IntPtr h);+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);+ [DllImport("user32.dll")] public static extern void mouse_event(uint f, int dx, int dy, uint d, UIntPtr e);+}+"@+$A = [System.Windows.Automation.AutomationElement]+$TS = [System.Windows.Automation.TreeScope]+function ByName($scope, $name) { $scope.FindFirst($TS::Descendants, (New-Object System.Windows.Automation.PropertyCondition($A::NameProperty, $name))) }+function ById($scope, $id) { $scope.FindFirst($TS::Descendants, (New-Object System.Windows.Automation.PropertyCondition($A::AutomationIdProperty, $id))) }+function Expand($e) { $e.GetCurrentPattern([System.Windows.Automation.ExpandCollapsePattern]::Pattern).Expand(); Start-Sleep -Milliseconds 600 }+function DoubleClickStatus {+ $r = (ById $win "txtStatus").Current.BoundingRectangle+ [W]::SetCursorPos([int]($r.Left + 20), [int]($r.Top + $r.Height / 2)) | Out-Null+ foreach ($i in 1..2) { [W]::mouse_event(2, 0, 0, 0, [UIntPtr]::Zero); [W]::mouse_event(4, 0, 0, 0, [UIntPtr]::Zero); Start-Sleep -Milliseconds 80 }+ Start-Sleep -Seconds 2+}+function PaneShown { (ByName $win "Search") -ne $null }+function Focused {+ $f = $A::FocusedElement+ $f.Current.ControlType.ProgrammaticName + " '" + $f.Current.Name.Substring(0, [Math]::Min(40, $f.Current.Name.Length)) + "'"+}++$p = Start-Process -FilePath (Join-Path $Dir "WaveDude.WPF.exe") -PassThru+Start-Sleep -Seconds 5+$p.Refresh()+[W]::SetForegroundWindow($p.MainWindowHandle) | Out-Null+$win = $A::RootElement.FindFirst($TS::Children, (New-Object System.Windows.Automation.PropertyCondition($A::ProcessIdProperty, $p.Id)))++if (PaneShown) {+ Expand (ByName $win "View")+ Expand (ByName $win "Panes")+ (ByName $win "Messages").GetCurrentPattern([System.Windows.Automation.InvokePattern]::Pattern).Invoke()+ Start-Sleep -Seconds 1+}+"before: pane shown = " + (PaneShown)+DoubleClickStatus+"after 1st dbl: pane shown = " + (PaneShown) + ", focus = " + (Focused)+(ById $win "txtStatus") | Out-Null+(ByName $win "Search").SetFocus()+Start-Sleep -Milliseconds 500+"focus moved: " + (Focused)+DoubleClickStatus+"after 2nd dbl: pane shown = " + (PaneShown) + ", focus = " + (Focused)++$null = $p.CloseMainWindow()+if (-not $p.WaitForExit(5000)) { Stop-Process -Id $p.Id -Force -Confirm:$false }+"exit: " + $p.ExitCode