From 4b5870f67c2ec84c751c800787b4d4053b076d0b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:48:07 +0000 Subject: [PATCH 01/10] WinForms: MathEditBox and MathView for Windows Forms, drawn with SkiaSharp [no-new-version] The controls of WPF for Windows Forms (net10.0-windows, net481), over the view of Rendering: Skia draws the equation into a bitmap that the window shows (no GDI+ drawing), each glyph a path of its outline; the floating bar is a form that never takes the focus, drawn with Skia too. Tests and a demo, on Windows only. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- .github/workflows/ci.yml | 11 + AGENTS.md | 15 +- README.md | 14 +- SharpEquations.slnx | 3 + docs/EDITOR.md | 24 + .../SharpEquations.WinForms.Demo/Program.cs | 37 + .../SharpEquations.WinForms.Demo.csproj | 18 + src/SharpEquations.WinForms/MathCanvas.cs | 203 ++++ src/SharpEquations.WinForms/MathEditBox.cs | 1016 +++++++++++++++++ .../MathEditBoxAccessibleObject.cs | 49 + src/SharpEquations.WinForms/MathFonts.cs | 43 + src/SharpEquations.WinForms/MathSurface.cs | 54 + src/SharpEquations.WinForms/MathView.cs | 217 ++++ src/SharpEquations.WinForms/MathViewMode.cs | 61 + .../PublicAPI.Shipped.txt | 1 + .../PublicAPI.Unshipped.txt | 137 +++ src/SharpEquations.WinForms/QuickBar.cs | 267 +++++ .../SharpEquations.WinForms.csproj | 43 + .../EditBoxTests.cs | 325 ++++++ .../SharpEquations.WinForms.Tests.csproj | 23 + tests/SharpEquations.WinForms.Tests/Ui.cs | 89 ++ .../ViewTests.cs | 45 + 22 files changed, 2692 insertions(+), 3 deletions(-) create mode 100644 samples/SharpEquations.WinForms.Demo/Program.cs create mode 100644 samples/SharpEquations.WinForms.Demo/SharpEquations.WinForms.Demo.csproj create mode 100644 src/SharpEquations.WinForms/MathCanvas.cs create mode 100644 src/SharpEquations.WinForms/MathEditBox.cs create mode 100644 src/SharpEquations.WinForms/MathEditBoxAccessibleObject.cs create mode 100644 src/SharpEquations.WinForms/MathFonts.cs create mode 100644 src/SharpEquations.WinForms/MathSurface.cs create mode 100644 src/SharpEquations.WinForms/MathView.cs create mode 100644 src/SharpEquations.WinForms/MathViewMode.cs create mode 100644 src/SharpEquations.WinForms/PublicAPI.Shipped.txt create mode 100644 src/SharpEquations.WinForms/PublicAPI.Unshipped.txt create mode 100644 src/SharpEquations.WinForms/QuickBar.cs create mode 100644 src/SharpEquations.WinForms/SharpEquations.WinForms.csproj create mode 100644 tests/SharpEquations.WinForms.Tests/EditBoxTests.cs create mode 100644 tests/SharpEquations.WinForms.Tests/SharpEquations.WinForms.Tests.csproj create mode 100644 tests/SharpEquations.WinForms.Tests/Ui.cs create mode 100644 tests/SharpEquations.WinForms.Tests/ViewTests.cs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ded0965..ef0016f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -29,11 +29,13 @@ env: src/SharpEquations.Avalonia/SharpEquations.Avalonia.csproj src/SharpEquations.Uno/SharpEquations.Uno.csproj src/SharpEquations.Wpf/SharpEquations.Wpf.csproj + src/SharpEquations.WinForms/SharpEquations.WinForms.csproj TEST_PROJECT: tests/SharpEquations.Tests/SharpEquations.Tests.csproj EDITOR_TEST_PROJECT: tests/SharpEquations.Avalonia.Tests/SharpEquations.Avalonia.Tests.csproj MATH_TOOLS_TEST_PROJECT: tests/SharpEquations.MathTools.Tests/SharpEquations.MathTools.Tests.csproj UNO_TEST_PROJECT: tests/SharpEquations.Uno.Tests/SharpEquations.Uno.Tests.csproj WPF_TEST_PROJECT: tests/SharpEquations.Wpf.Tests/SharpEquations.Wpf.Tests.csproj + WINFORMS_TEST_PROJECT: tests/SharpEquations.WinForms.Tests/SharpEquations.WinForms.Tests.csproj FEED_URL: https://nuget.pkg.github.com/${{ github.repository_owner }}/index.json # Stages: Resolve Version -> Test (Linux, Windows, macOS) -> Pack NuGet @@ -203,6 +205,15 @@ jobs: --report-trx --report-trx-filename "${{ matrix.rid }}.wpf.net10.0.trx" \ --results-directory "$GITHUB_WORKSPACE/TestResults" + # the controls of Windows Forms in a form, on Windows only (they build everywhere, with EnableWindowsTargeting) + - name: Run Windows Forms tests + if: runner.os == 'Windows' + shell: bash + run: | + dotnet run --project "$WINFORMS_TEST_PROJECT" -c Release -f net10.0-windows --no-build -- \ + --report-trx --report-trx-filename "${{ matrix.rid }}.winforms.net10.0.trx" \ + --results-directory "$GITHUB_WORKSPACE/TestResults" + - name: Upload test results if: always() uses: actions/upload-artifact@v7 diff --git a/AGENTS.md b/AGENTS.md index d633d69..b1b4c8b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,8 +20,10 @@ generated parser, on netstandard2.0): keep it so, and keep containers and other | `src/SharpEquations.Uno/` | The same controls for Uno Platform (`Uno.Sdk` of `global.json`), of the elements every renderer of Uno has: glyphs as paths from their outlines, shapes, a transparent `TextBox` for the input | | `samples/SharpEquations.Avalonia.Demo/` | A window with the editor (`DemoView`, shared with the web demo) | | `src/SharpEquations.Wpf/` | The same controls for WPF (net10.0-windows, net481), drawn in `OnRender`: glyphs as geometries from their outlines; it builds on every system (`EnableWindowsTargeting`) | +| `src/SharpEquations.WinForms/` | The same controls for Windows Forms (net10.0-windows, net481), drawn with SkiaSharp into a bitmap that the window shows (no GDI+ drawing): glyphs as paths from their outlines; it builds on every system | | `samples/SharpEquations.Uno.Demo/` | A window with the editor of `SharpEquations.Uno`, on the desktop (Skia) | | `samples/SharpEquations.Wpf.Demo/` | A window with the editor of `SharpEquations.Wpf` (Windows) | +| `samples/SharpEquations.WinForms.Demo/` | A form with the editor of `SharpEquations.WinForms` (Windows) | | `samples/SharpEquations.Avalonia.Browser.Demo/` | The same demo on WebAssembly (needs the `wasm-tools` workload, so not in the solution; `.github/workflows/demo.yml` publishes it to GitHub Pages) | | `samples/SharpEquations.Avalonia.MathTools.Demo/` | A second app, math tools around the editor: its views (`MathToolsView`, a page each: the scientific keypad, the library of formulas, whose Graph button draws a formula on the graphs page, the unit converter, the solver of triangles, the graphs: `GraphsPage` on a `GraphView`, a slider for each parameter; the graphs in space: `Graphs3DPage` on a `Graph3DView`, OpenGL through Silk.NET where there is a context and the Skia painter elsewhere, in the browser too; the worksheet: `WorksheetPage`) and the desktop window | | `samples/SharpEquations.MathTools.Core/` | The math tools without a user interface: `ICasEngine` (`AngouriMathEngine`, through `MathReader`, which reads what the normalized presentation MathML means: in radians or degrees, systems of equations, definitions `a≔5`), the formulas (a `GraphPreset` for those with a graph: the equation drawn and its parameters at their starting values, Greek letters too), the units (NIST factors) and triangles, the equations of the graphs in space (`SurfacePlot`: z=f(x,y) or a curve x,y,z of t, with their parameters), the `Worksheet` (the history of what was computed, kept as JSON in the settings, its definitions made again when it is read back), and the services the views ask the platform for (`ISettingsStore`: a file on the desktop, the local storage in the browser) | @@ -32,6 +34,7 @@ generated parser, on netstandard2.0): keep it so, and keep containers and other | `tests/SharpEquations.Avalonia.Tests/` | TUnit tests of the editor (Editing, Rendering, and the controls in a headless Avalonia session with Skia), and of the views of the math tools | | `tests/SharpEquations.Uno.Tests/` | TUnit tests of the controls of `SharpEquations.Uno` in a real Uno app on the desktop (`Program` starts the app, then runs TUnit; the tests work on its thread through `Ui.Run`); it needs a display: `xvfb-run` on Linux | | `tests/SharpEquations.Wpf.Tests/` | TUnit tests of the controls of `SharpEquations.Wpf` in a window on a thread of its own (`Ui`: STA, with its dispatcher); they build everywhere and run on Windows only | +| `tests/SharpEquations.WinForms.Tests/` | TUnit tests of the controls of `SharpEquations.WinForms` in a form on a thread of its own (`Ui`: STA, with its message loop); they build everywhere and run on Windows only | | `tests/SharpEquations.MathTools.Tests/` | TUnit tests of `SharpEquations.MathTools.Core` and `.Graphing` (net10.0), with the reference tests of the computer algebra and the units (`tests/data/mathtools/`: cases compared by their value, the ones not reached yet `pending` with the reason; a change makes no passing case fail) | | `tests/data/` | Test data and its provenance (`tests/data/README.md`) | @@ -138,6 +141,14 @@ net10.0 with no package, as the core). clipboard methods are synchronous (`Copy`, `Cut`, `Paste`, `CopyAs`), as those of `TextBox`. `tests/SharpEquations.Wpf.Tests` shows the controls in a window of an STA thread of its own (`Ui.Run`), through the internal `Type`, `HandleKey` and `PressAt`; they run on Windows only, and the CI runs them there. +- `WinForms`: `MathEditBox` and `MathView` draw with SkiaSharp (the version of Avalonia, given in the project with + `VersionOverride` and not pinned for the repository, since Uno takes a newer one) through `MathCanvas` over an + `SKCanvas`, each glyph an `SKPath` of its outline cached for each font, into the pixels of `MathSurface`, which + `OnPaint` copies to the window: no GDI+ drawing. The selection and the equation are recorded in an `SKPicture`, + drawn again under the caret as it blinks. Their coordinates are device-independent pixels, scaled by `DeviceDpi`. + The floating bar is a form that never takes the focus (`WS_EX_NOACTIVATE`), drawn with Skia too; the context menu a + `ContextMenuStrip`, on `WM_CONTEXTMENU`. With `AutoSize` the height of the editor follows the equation, as that of a + `TextBox`. `tests/SharpEquations.WinForms.Tests` runs on Windows only, and the CI runs it there. - The core's `EquationCommands` (public) lists the control words of UnicodeMath and the commands of LaTeX with their symbols, for the completion of the editor; `PublicApi/EquationCommandsTests` checks that the parsers read them. @@ -149,7 +160,7 @@ dotnet test --solution SharpEquations.slnx ``` On Linux, the tests of Uno need a display: `xvfb-run -a dotnet test --solution SharpEquations.slnx`. The tests of WPF -run on Windows only. +run on Windows only, as those of Windows Forms. The tests run on net10.0 against the net10.0 build, and against the netstandard2.0 build on net8.0 (Linux, macOS) or net481 (Windows, where the test project targets net10.0 and net481). The 738 examples of @@ -165,7 +176,7 @@ packages is tracked in their `PublicAPI.*.txt`, as that of the core. ## Releases `.github/workflows/ci.yml`, the same pipeline as SharpMediaInfo and Letra200bSharp: it tests on Linux (net10.0, net8.0), -Windows (net10.0, net481) and macOS (net10.0), packs the six packages (`SharpEquations` and the editor's `SharpEquations.Editing`, `.Rendering`, `.Avalonia`, `.Uno`, `.Wpf`, +Windows (net10.0, net481) and macOS (net10.0), packs the seven packages (`SharpEquations` and the editor's `SharpEquations.Editing`, `.Rendering`, `.Avalonia`, `.Uno`, `.Wpf`, `.WinForms`, with one version), publishes a `pr--…` pre-release for each pull request (deleted on close by `prerelease-cleanup.yml`) and, on `main`, tags `v` of `BuildVersion.props`, creates the GitHub release and pushes the package to GitHub Packages and nuget.org (Trusted Publishing, repository variable `NUGET_USER`). A change diff --git a/README.md b/README.md index 4dbc6a0..d28e3ce 100644 --- a/README.md +++ b/README.md @@ -105,11 +105,23 @@ var editor = new SharpEquations.Wpf.MathEditBox { FontSize = 28 }; editor.EquationChanged += (_, e) => Console.WriteLine(e.Equation?.ToString(EquationFormat.MathML)); ``` +### Windows Forms + +`SharpEquations.WinForms` has them for Windows Forms (.NET 10 and .NET Framework 4.8.1), drawn with SkiaSharp rather +than GDI+: the glyphs of Libertinus Math (embedded) as paths from their outlines, or of another math font read from its +file (`MathFonts.FromFile`). The height of the editor follows the equation, as that of a `TextBox` follows its font. +`samples/SharpEquations.WinForms.Demo` is a form with it. + +```csharp +var editor = new SharpEquations.WinForms.MathEditBox { FontSize = 28, Width = 600 }; +editor.EquationChanged += (_, e) => Console.WriteLine(e.Equation?.ToString(EquationFormat.MathML)); +``` + `MathView` shows an equation without editing it. Both lay out MathML after MathML Core with the OpenType MATH table of a math font: Cambria Math on Windows, and Libertinus Math (SIL Open Font License), embedded, elsewhere. The editor is three projects, so that the core keeps no dependency: `SharpEquations.Editing` (the editing model, no user interface), `SharpEquations.Rendering` (the layout and the view of an editor, no user interface) and `SharpEquations.Avalonia`, -`SharpEquations.Uno` or `SharpEquations.Wpf` (the controls, adapters of that view to their toolkit). The design is in +`SharpEquations.Uno`, `SharpEquations.Wpf` or `SharpEquations.WinForms` (the controls, adapters of that view to their toolkit). The design is in [docs/EDITOR.md](docs/EDITOR.md); `samples/SharpEquations.Avalonia.Demo` is a window with the editor and its MathML, UnicodeMath and LaTeX, and `samples/SharpEquations.Avalonia.Browser.Demo` the same demo in the browser, on WebAssembly (published to GitHub Pages from `main`; to run it locally: `dotnet workload install wasm-tools`, then diff --git a/SharpEquations.slnx b/SharpEquations.slnx index 6ef2d83..954f993 100644 --- a/SharpEquations.slnx +++ b/SharpEquations.slnx @@ -12,6 +12,7 @@ + @@ -29,6 +30,7 @@ + @@ -41,6 +43,7 @@ + diff --git a/docs/EDITOR.md b/docs/EDITOR.md index f85c801..029ce06 100644 --- a/docs/EDITOR.md +++ b/docs/EDITOR.md @@ -304,6 +304,30 @@ Avalonia, for net10.0-windows and net481 (Editing and Rendering are netstandard2 - **Clipboard**: the text in `CopyTextFormat` and the MathML of Word (`MathML`, UTF-8), read back first on a paste. - **Accessibility**: `MathEditBoxAutomationPeer`, the value pattern with the equation in UnicodeMath. +## The controls for Windows Forms (`SharpEquations.WinForms`) + +`MathEditBox` and `MathView` (each a `Control`) with the API of those of WPF, as far as Windows Forms allows (colours +as `Color` properties, the font size in device-independent pixels, by default that of `Font`), for net10.0-windows and +net481; the project builds on every system (`EnableWindowsTargeting`) and runs on Windows: + +- **Drawing**: with SkiaSharp, not GDI+. `MathCanvas` over an `SKCanvas` draws the shapes as they are and each glyph + as an `SKPath` of its outline, made once for each glyph of a font in the units of its design and scaled where it is + drawn. `MathSurface` keeps the pixels of the control (BGRA, premultiplied), which `OnPaint` copies to the window as a + bitmap over the same memory. The selection and the equation are recorded once in an `SKPicture`, so that the caret + blinks over it without laying out or drawing the equation again. The view works in device-independent pixels, scaled + by `DeviceDpi` (per monitor). +- **Size**: with `AutoSize` (the default) the height of the editor follows the equation and its width is the one it is + given, as for a `TextBox`; a `MathView` takes the size of its equation. +- **Font**: Libertinus Math, embedded and read by `OpenTypeMathFont`, or another math font by its file + (`MathFonts.FromFile`). +- **Input**: `OnKeyPress` (the surrogate pairs joined; the control characters left to the keys), `OnKeyDown` with the + keys mapped to `MathKey`; the arrows are input keys, and Tab, Enter and Escape go to the editor first, to the form + when the editor does not use them. The context menu on `WM_CONTEXTMENU` (a right click, the Menu key, Shift+F10), a + `ContextMenuStrip` built by `CreateContextMenu`. The floating bar is a form of its own that never takes the focus + (`WS_EX_NOACTIVATE`, `MA_NOACTIVATE`), its items drawn with Skia in Segoe UI, with a fallback font for the symbols. +- **Clipboard**: the text in `CopyTextFormat` and the MathML of Word (`MathML`, UTF-8), read back first on a paste. +- **Accessibility**: `MathEditBoxAccessibleObject`, editable text whose value is the equation in UnicodeMath. + ## Plan | Phase | Content | State | diff --git a/samples/SharpEquations.WinForms.Demo/Program.cs b/samples/SharpEquations.WinForms.Demo/Program.cs new file mode 100644 index 0000000..e0c5459 --- /dev/null +++ b/samples/SharpEquations.WinForms.Demo/Program.cs @@ -0,0 +1,37 @@ +namespace SharpEquations.WinForms.Demo +{ + using System; + using System.Drawing; + using System.Windows.Forms; + using SharpEquations; + + /// A form with the editor, the equation as UnicodeMath and LaTeX, and a view of it. + public static class Program + { + [STAThread] + public static void Main() + { + ApplicationConfiguration.Initialize(); + var panel = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, WrapContents = false, Padding = new Padding(24), AutoScroll = true }; + var hint = new Label { Text = "Type UnicodeMath or LaTeX: a space or an operator builds it up.", AutoSize = true, ForeColor = Color.DimGray, Margin = new Padding(0, 0, 0, 8) }; + var editor = new MathEditBox { FontSize = 28, Width = 720, Margin = new Padding(0, 0, 0, 12) }; + var unicodeMath = new Label { AutoSize = true, MaximumSize = new Size(720, 0) }; + var latex = new Label { AutoSize = true, MaximumSize = new Size(720, 0) }; + var viewLabel = new Label { Text = "MathView:", AutoSize = true, ForeColor = Color.DimGray, Margin = new Padding(0, 8, 0, 4) }; + var view = new MathView { FontSize = 22, IsDisplay = true, BackColor = Color.White }; + editor.EquationChanged += (_, e) => + { + unicodeMath.Text = "UnicodeMath: " + (e.Equation?.ToString(EquationFormat.UnicodeMath) ?? string.Empty); + latex.Text = "LaTeX: " + (e.Equation?.ToString(EquationFormat.LaTeX) ?? string.Empty); + view.Equation = e.Equation; + }; + panel.Controls.AddRange(new Control[] { hint, editor, unicodeMath, latex, viewLabel, view }); + if (Environment.GetEnvironmentVariable("SHARPEQUATIONS_DEMO_EQUATION") is { Length: > 0 } initial) + editor.Equation = Equation.Parse(initial, EquationFormat.UnicodeMath, new EquationOptions { Display = true }); + var form = new Form { Text = "SharpEquations for Windows Forms", Width = 800, Height = 500, BackColor = Color.White }; + form.Controls.Add(panel); + form.Shown += (_, _) => editor.Focus(); + Application.Run(form); + } + } +} diff --git a/samples/SharpEquations.WinForms.Demo/SharpEquations.WinForms.Demo.csproj b/samples/SharpEquations.WinForms.Demo/SharpEquations.WinForms.Demo.csproj new file mode 100644 index 0000000..25275a7 --- /dev/null +++ b/samples/SharpEquations.WinForms.Demo/SharpEquations.WinForms.Demo.csproj @@ -0,0 +1,18 @@ + + + + + net10.0-windows + WinExe + true + true + PerMonitorV2 + false + enable + + + + + + + diff --git a/src/SharpEquations.WinForms/MathCanvas.cs b/src/SharpEquations.WinForms/MathCanvas.cs new file mode 100644 index 0000000..d48a4e5 --- /dev/null +++ b/src/SharpEquations.WinForms/MathCanvas.cs @@ -0,0 +1,203 @@ +namespace SharpEquations.WinForms +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Runtime.CompilerServices; + using SharpEquations.Rendering; + using SkiaSharp; + + /// The colours an equation is drawn with, one for each ; null draws nothing. + internal readonly struct MathColors + { + public MathColors(SKColor? foreground, SKColor? placeholder = null, SKColor? error = null, SKColor? selection = null, SKColor? caret = null) + { + Foreground = foreground; + Placeholder = placeholder; + Error = error; + Selection = selection; + Caret = caret; + } + + public SKColor? Foreground { get; } + + public SKColor? Placeholder { get; } + + public SKColor? Error { get; } + + public SKColor? Selection { get; } + + public SKColor? Caret { get; } + } + + /// + /// An as the canvas of the views of Rendering: the shapes drawn as they are, and the glyphs as + /// paths from their outlines (), made once for each glyph of a font in the + /// units of its design and scaled where they are drawn. + /// + internal sealed class MathCanvas : IMathCanvas, IDisposable + { + private static readonly ConditionalWeakTable> Paths = new ConditionalWeakTable>(); + private static readonly Dictionary NamedColors = new Dictionary(StringComparer.OrdinalIgnoreCase); + private static readonly float[] Dashes = { 2f, 2f }; + private readonly SKCanvas canvas; + private readonly MathColors colors; + private readonly SKPaint paint = new SKPaint { IsAntialias = true }; + + public MathCanvas(SKCanvas canvas, MathColors colors) + { + this.canvas = canvas; + this.colors = colors; + } + + public void Dispose() => paint.Dispose(); + + public void FillRectangle(MathRect rect, MathPaint paint, string? color) + { + if (Color(paint, color) is { } c) + canvas.DrawRect(SKRect.Create((float)rect.X, (float)rect.Y, (float)Math.Max(0, rect.Width), (float)Math.Max(0, rect.Height)), Fill(c)); + } + + public void DrawRectangle(MathRect rect, double thickness, bool dashed, MathPaint paint, string? color) + { + if (Color(paint, color) is not { } c) + return; + var half = thickness / 2; + using var dashes = dashed ? SKPathEffect.CreateDash(Dashes, 0) : null; + var stroke = Stroke(c, thickness); + stroke.PathEffect = dashes; + canvas.DrawRect(SKRect.Create((float)(rect.X + half), (float)(rect.Y + half), (float)Math.Max(0, rect.Width - thickness), (float)Math.Max(0, rect.Height - thickness)), stroke); + stroke.PathEffect = null; + } + + public void DrawLine(double x1, double y1, double x2, double y2, double thickness, MathPaint paint, string? color) + { + if (Color(paint, color) is { } c) + canvas.DrawLine((float)x1, (float)y1, (float)x2, (float)y2, Stroke(c, thickness)); + } + + public void DrawEllipse(MathRect rect, double thickness, MathPaint paint, string? color) + { + if (Color(paint, color) is { } c) + canvas.DrawOval(SKRect.Create((float)rect.X, (float)rect.Y, (float)rect.Width, (float)rect.Height), Stroke(c, thickness)); + } + + public void DrawGlyphs(MathLayout layout, double x, double y) + { + foreach (var glyph in layout.Glyphs) + { + if (glyph.Font is not OpenTypeMathFont font || (Parse(glyph.Color) ?? colors.Foreground) is not { } c || Path(font, glyph.Glyph) is not { } path) + continue; + var scale = (float)(glyph.Size / font.UnitsPerEm); + canvas.Save(); + canvas.Translate((float)(x + glyph.X), (float)(y + glyph.Y)); + canvas.Scale(scale, -scale); + canvas.DrawPath(path, Fill(c)); + canvas.Restore(); + } + } + + /// The path of a glyph in the units of the design of its font, y up; null for a glyph with no outline. + internal static SKPath? Path(OpenTypeMathFont font, ushort glyph) + { + var cache = Paths.GetValue(font, _ => new Dictionary()); + lock (cache) + { + if (!cache.TryGetValue(glyph, out var path)) + cache[glyph] = path = CreatePath(font.GetOutline(glyph)); + return path; + } + } + + /// The colour of mathcolor or mathbackground (#rgb, #rrggbb, #aarrggbb, a name); null otherwise. + internal static SKColor? Parse(string? color) + { + if (color == null) + return null; + lock (NamedColors) + { + if (!NamedColors.TryGetValue(color, out var parsed)) + NamedColors[color] = parsed = ParseColor(color.Trim()); + return parsed; + } + } + + internal static SKColor ToSkia(System.Drawing.Color color) => new SKColor(color.R, color.G, color.B, color.A); + + private static SKPath? CreatePath(IReadOnlyList outline) + { + if (outline.Count == 0) + return null; + var path = new SKPath { FillType = SKPathFillType.Winding }; + var open = false; + foreach (var command in outline) + { + switch (command.Kind) + { + case MathPathCommandKind.MoveTo: + if (open) + path.Close(); + path.MoveTo((float)command.X, (float)command.Y); + open = true; + break; + case MathPathCommandKind.LineTo: + path.LineTo((float)command.X, (float)command.Y); + break; + case MathPathCommandKind.QuadraticTo: + path.QuadTo((float)command.X1, (float)command.Y1, (float)command.X, (float)command.Y); + break; + case MathPathCommandKind.CubicTo: + path.CubicTo((float)command.X1, (float)command.Y1, (float)command.X2, (float)command.Y2, (float)command.X, (float)command.Y); + break; + } + } + if (open) + path.Close(); + return path; + } + + private static SKColor? ParseColor(string text) + { + if (text.Length > 0 && text[0] == '#') + { + var hex = text.Substring(1); + if (!uint.TryParse(hex, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var v)) + return null; + return hex.Length switch + { + 3 => new SKColor((byte)((v >> 8 & 0xF) * 17), (byte)((v >> 4 & 0xF) * 17), (byte)((v & 0xF) * 17)), + 6 => new SKColor((byte)(v >> 16), (byte)(v >> 8), (byte)v), + 8 => new SKColor((byte)(v >> 16), (byte)(v >> 8), (byte)v, (byte)(v >> 24)), + _ => null, + }; + } + var known = System.Drawing.Color.FromName(text); + return known.IsKnownColor ? ToSkia(known) : null; + } + + private SKPaint Fill(SKColor color) + { + paint.Style = SKPaintStyle.Fill; + paint.Color = color; + return paint; + } + + private SKPaint Stroke(SKColor color, double thickness) + { + paint.Style = SKPaintStyle.Stroke; + paint.StrokeWidth = (float)thickness; + paint.Color = color; + return paint; + } + + private SKColor? Color(MathPaint paint, string? color) => Parse(color) ?? paint switch + { + MathPaint.Foreground => colors.Foreground, + MathPaint.Placeholder => colors.Placeholder, + MathPaint.Error => colors.Error, + MathPaint.Selection => colors.Selection, + MathPaint.Caret => colors.Caret, + _ => null, + }; + } +} diff --git a/src/SharpEquations.WinForms/MathEditBox.cs b/src/SharpEquations.WinForms/MathEditBox.cs new file mode 100644 index 0000000..12a6b8d --- /dev/null +++ b/src/SharpEquations.WinForms/MathEditBox.cs @@ -0,0 +1,1016 @@ +namespace SharpEquations.WinForms +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Drawing; + using System.IO; + using System.Windows.Forms; + using SharpEquations.Editing; + using SharpEquations.Rendering; + using SkiaSharp; + + /// + /// A real-time equation editor for Windows Forms, in the manner of the RichEditBox of WinUI in math mode and of the + /// math zones of Word: UnicodeMath or LaTeX typed at the caret builds up into the equation when a space or an operator + /// ends an argument, and the content is read and written as MathML (, ) or + /// as an . It is drawn with Skia, and adapts the view of Rendering + /// (), which does the rest. With (the default) its height follows the + /// equation, as that of a follows its font. + /// + public class MathEditBox : Control + { + /// The format of MathML on the clipboard of Windows, which Word reads and writes as UTF-8 (). + public const string MathMLClipboardFormat = "MathML"; + + private const int WM_CONTEXTMENU = 0x007B; + private static readonly SKColor ErrorColor = new SKColor(0xFF, 0xE4, 0xE1); + private readonly MathSurface surface = new MathSurface(); + private readonly Timer blink; + private QuickBar? quickBar; + private Form? quickBarOwner; + private MathAutoCorrect autoCorrect; + private SKPicture? content; + private ContextMenuStrip? openMenu; + private char pendingHighSurrogate; + private bool updatingEquation; + private Equation? equation; + private EquationFormat inputFormat = EquationFormat.UnicodeMath; + private MathViewMode viewMode; + private bool isDisplay = true; + private bool isReadOnly; + private bool isQuickBarEnabled = true; + private bool isAutoCorrectEnabled = true; + private EquationFormat? copyTextFormat; + private Color selectionColor = Color.FromArgb(0x60, 0x33, 0x99, 0xFF); + private Color caretColor = Color.Empty; + private Color placeholderColor = Color.Gray; + private Color borderColor = Color.Gray; + private int borderWidth = 1; + private OpenTypeMathFont? mathFont; + private double? fontSize; + + /// An empty editor. + public MathEditBox() + { + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.Opaque | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); + SetStyle(ControlStyles.StandardDoubleClick, false); + TabStop = true; + Cursor = Cursors.IBeam; + BackColor = SystemColors.Window; + ForeColor = SystemColors.WindowText; + Padding = new Padding(6, 4, 6, 4); + base.AutoSize = true; + + Editor = new MathEditor { IsDisplay = true }; + Editor.ContentChanged += OnEditorContentChanged; + View = new MathEditorView(Editor); + View.Changed += OnViewChanged; + autoCorrect = Editor.AutoCorrect ?? new MathAutoCorrect(); + + blink = new Timer { Interval = (int)MathEditorView.CaretBlinkInterval.TotalMilliseconds }; + blink.Tick += (_, _) => + { + View.BlinkCaret(); + InvalidateCaret(); + }; + Size = new Size(200, 40); + } + + /// + /// Raised when the selection is copied, before it goes to the clipboard: a handler can add formats to the data + /// (OMML, a picture...) or cancel the copy. + /// + public event EventHandler? Copying; + + /// Raised when the equation changes, by an edit or by . + public event EventHandler? EquationChanged; + + /// + /// Raised before the context menu opens, with the menu of : a handler can add, + /// remove or change items, or cancel it. + /// + public event EventHandler? MathContextMenuOpening; + + /// The editing model: the tree of the equation, the caret and the selection, and the commands. + [Browsable(false)] + public MathEditor Editor { get; } + + /// + /// The view of the editor without a toolkit, which the control is built on: the layout and where it is drawn, the + /// pointer, the floating bar, the context menu and the clipboard. Its coordinates are device-independent pixels. + /// + [Browsable(false)] + public MathEditorView View { get; } + + /// The equation edited, with what is not built up yet built up where it parses; null when empty. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Equation? Equation + { + get => equation; + set + { + if (ReferenceEquals(equation, value)) + return; + equation = value; + if (updatingEquation) + return; + Editor.Load(value); + if (value != null) + IsDisplay = value.IsDisplay; + } + } + + /// The format of what is typed: UnicodeMath (the default) or LaTeX. + /// The format is neither UnicodeMath nor LaTeX. + [DefaultValue(EquationFormat.UnicodeMath)] + public EquationFormat InputFormat + { + get => inputFormat; + set + { + if (value is not (EquationFormat.UnicodeMath or EquationFormat.LaTeX)) + throw new ArgumentOutOfRangeException(nameof(value), "What is typed is UnicodeMath or LaTeX."); + inputFormat = value; + Editor.InputFormat = value; + } + } + + /// Whether the equation is shown built up or as linear text. + [DefaultValue(MathViewMode.Professional)] + public MathViewMode ViewMode + { + get => viewMode; + set + { + if (viewMode == value) + return; + viewMode = value; + Editor.SetLinear(value == MathViewMode.Linear); + } + } + + /// Whether the equation is a display equation rather than inline. + [DefaultValue(true)] + public bool IsDisplay + { + get => isDisplay; + set + { + isDisplay = value; + Editor.IsDisplay = value; + } + } + + /// Whether the user cannot change the equation. + [DefaultValue(false)] + public bool IsReadOnly + { + get => isReadOnly; + set + { + isReadOnly = value; + View.IsReadOnly = value; + InvalidateCaret(); + UpdateQuickBar(); + } + } + + /// The colour of the selection. + public Color SelectionColor + { + get => selectionColor; + set + { + selectionColor = value; + InvalidateContent(); + } + } + + /// The colour of the caret; for the foreground. + public Color CaretColor + { + get => caretColor; + set + { + caretColor = value; + InvalidateCaret(); + } + } + + /// The colour of the boxes of the empty slots. + public Color PlaceholderColor + { + get => placeholderColor; + set + { + placeholderColor = value; + InvalidateContent(); + } + } + + /// The colour of the border; for none. + public Color BorderColor + { + get => borderColor; + set + { + borderColor = value; + Invalidate(); + } + } + + /// The width of the border, in device-independent pixels; 1 by default. + [DefaultValue(1)] + public int BorderWidth + { + get => borderWidth; + set + { + borderWidth = Math.Max(0, value); + Relayout(); + } + } + + /// The math font; null for . + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OpenTypeMathFont? MathFont + { + get => mathFont; + set + { + mathFont = value; + Relayout(); + } + } + + /// The size of the font, in device-independent pixels; by default that of . + public double FontSize + { + get => fontSize ?? Font.SizeInPoints * 96 / 72; + set + { + if (!(value > 0)) + throw new ArgumentOutOfRangeException(nameof(value), "The size of the font is positive."); + fontSize = value; + Relayout(); + } + } + + /// Whether the height of the control follows the equation; true by default. The width is the one it is given. + [DefaultValue(true)] + [Browsable(true)] + [EditorBrowsable(EditorBrowsableState.Always)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] + public override bool AutoSize + { + get => base.AutoSize; + set + { + base.AutoSize = value; + Relayout(); + } + } + + /// Whether the floating bar shows completions, structures, table commands and symbols at the caret. + [DefaultValue(true)] + public bool IsQuickBarEnabled + { + get => isQuickBarEnabled; + set + { + isQuickBarEnabled = value; + View.IsQuickBarEnabled = value; + UpdateQuickBar(); + } + } + + /// Whether the floating bar is open. + [Browsable(false)] + public bool IsQuickBarOpen => quickBar is { Visible: true }; + + /// The symbols the floating bar offers in an empty slot. + [Browsable(false)] + public IList QuickSymbols { get; } = new List { "α", "β", "θ", "π", "∞", "±", "×", "≤", "≥", "≠", "≈", "→", "∈", "∂", "∑", "∫" }; + + /// Whether the editor opens its context menu. + [DefaultValue(true)] + public bool IsContextMenuEnabled { get; set; } = true; + + /// The context menu while it is open, or null. + [Browsable(false)] + public ContextMenuStrip? OpenContextMenu => openMenu is { Visible: true } ? openMenu : null; + + /// + /// The format of the text that puts on the clipboard; null (the default) for the input format. + /// MathML pastes as an equation into Word. + /// + /// The format is MTEF, which is read only. + [DefaultValue(null)] + public EquationFormat? CopyTextFormat + { + get => copyTextFormat; + set => copyTextFormat = value is EquationFormat.Mtef ? throw new ArgumentOutOfRangeException(nameof(value), "MTEF is read only.") : value; + } + + /// + /// The rules of the math autocorrect (): -> becomes → and + /// \alpha and a space α as they are typed; turns it off. + /// + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public MathAutoCorrect AutoCorrect + { + get => autoCorrect; + set + { + autoCorrect = value ?? throw new ArgumentNullException(nameof(value)); + Editor.AutoCorrect = IsAutoCorrectEnabled ? value : null; + } + } + + /// Whether the math autocorrect () replaces sequences as they are typed; true by default. + [DefaultValue(true)] + public bool IsAutoCorrectEnabled + { + get => isAutoCorrectEnabled; + set + { + isAutoCorrectEnabled = value; + Editor.AutoCorrect = value ? autoCorrect : null; + } + } + + /// The number of the equation, shown at the right of its line; null without one (). + [DefaultValue(null)] + public string? EquationNumber + { + get => Editor.EquationNumber; + set => Editor.SetEquationNumber(value); + } + + /// The layout of the equation, after a measure, in device-independent pixels. + [Browsable(false)] + public MathLayout? EquationLayout => View.Layout; + + /// The scale of the device-independent pixels of the view to the pixels of the screen. + internal float DpiScale => DeviceDpi / 96f; + + internal MathSurface Surface => surface; + + internal QuickBar? QuickBarWindow => quickBar; + + /// The MathML of the equation, as RichEditTextDocument.GetMath. + public string GetMath() => Editor.ToMathML().ToString(System.Xml.Linq.SaveOptions.DisableFormatting); + + /// Replaces the equation with MathML, as RichEditTextDocument.SetMath. + /// The MathML is not valid. + public void SetMath(string mathML) => Editor.Load(string.IsNullOrWhiteSpace(mathML) ? null : Equation.Parse(mathML, EquationFormat.MathML)); + + /// The equation in a format; for LaTeX, the LaTeX of Word. + public string GetText(EquationFormat format) => Editor.GetText(format); + + /// Builds up all that is typed and not built up yet. + public void BuildUp() => Editor.BuildUpAll(); + + /// Builds down the selection, or the whole equation, into linear text. + public void BuildDown() => Editor.BuildDown(); + + /// + /// The selection in a format, or null when nothing is selected: UnicodeMath, LaTeX (as Word writes it unless the + /// options say otherwise), MathML or OMML. + /// + public string? GetSelectedText(EquationFormat format, EquationOptions? options = null) => Editor.GetSelectedText(format, options); + + /// + /// Copies the selection to the clipboard: as text in (the input format by default) + /// and as MathML (), with the formats a handler of adds. + /// + public void Copy() + { + if (!View.TryGetCopy(CopyTextFormat, out var copied, out var text, out var mathML)) + return; + var data = new DataObject(); + data.SetText(text); + data.SetData(MathMLClipboardFormat, new MemoryStream(MathClipboard.Encode(mathML))); + var args = new MathCopyingEventArgs(copied, data); + Copying?.Invoke(this, args); + if (!args.Cancel) + Clipboard.SetDataObject(data, true); + } + + /// Copies the selection to the clipboard and deletes it. + public void Cut() + { + if (IsReadOnly) + return; + Copy(); + Editor.DeleteSelection(); + } + + /// Pastes the clipboard: MathML, or text read in the input format (or as MathML), or plain text. + public void Paste() + { + if (IsReadOnly) + return; + var data = Clipboard.GetDataObject(); + if (data != null && data.GetDataPresent(MathMLClipboardFormat) && Bytes(data.GetData(MathMLClipboardFormat)) is { Length: > 0 } bytes + && View.PasteMathML(MathClipboard.Decode(bytes))) + { + return; + } + if (Clipboard.ContainsText() && Clipboard.GetText() is { Length: > 0 } text) + View.PasteText(text); + } + + /// + /// Copies the selection, or the whole equation when nothing is selected, to the clipboard as text in a format + /// (LaTeX as Word writes it); MathML goes also as the MathML of the clipboard (). + /// + public void CopyAs(EquationFormat format) + { + if (View.GetCopyAsText(format) is not { } text) + return; + var data = new DataObject(); + data.SetText(text); + if (format == EquationFormat.MathML) + data.SetData(MathMLClipboardFormat, new MemoryStream(MathClipboard.Encode(text))); + Clipboard.SetDataObject(data, true); + } + + /// + /// Opens the context menu at a point of the editor, in pixels, or at the caret: a point outside the selection + /// moves the caret there first, as text editors do. Returns whether a menu opened. + /// + public bool ShowContextMenu(Point? point = null) + { + if (!IsContextMenuEnabled) + return false; + Focus(); + var scale = DpiScale; + var at = View.PrepareContextMenu(point?.X / (double)scale, point?.Y / (double)scale); + openMenu?.Close(); + var menu = CreateContextMenu(); + var args = new MathContextMenuEventArgs(menu); + MathContextMenuOpening?.Invoke(this, args); + if (args.Cancel || menu.Items.Count == 0) + { + menu.Dispose(); + return false; + } + menu.Closed += (_, _) => BeginInvoke(new Action(menu.Dispose)); + openMenu = menu; + var location = at is { } rect ? new Point((int)(rect.X * scale), (int)Math.Ceiling(rect.Bottom * scale)) : point ?? Point.Empty; + menu.Show(this, location); + return true; + } + + /// + /// The context menu of the editor, built anew each time it opens, for the state of the editor + /// (). The tag of each item names its command: undo, + /// redo, cut, copy, paste, copy-as (with copy-as-mathml, + /// copy-as-unicodemath, copy-as-latex, copy-as-omml), select-all, view, + /// build-up, build-down, new-line, number, table (with row-above, + /// row-below, column-left, column-right, delete-row, delete-column). + /// + protected virtual ContextMenuStrip CreateContextMenu() + { + var menu = new ContextMenuStrip(); + foreach (var item in View.GetContextMenu()) + menu.Items.Add(Item(item)); + return menu; + } + + /// + public override Size GetPreferredSize(Size proposedSize) + { + var scale = DpiScale; + var width = proposedSize.Width is > 0 and < int.MaxValue ? proposedSize.Width : Width; + var size = Measure(width); + return new Size(width, (int)Math.Ceiling(size.Height * scale)); + } + + /// + protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) + { + if (AutoSize && View.Font != null) + height = (int)Math.Ceiling(Measure(width).Height * DpiScale); + base.SetBoundsCore(x, y, width, height, specified); + } + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + blink.Dispose(); + quickBar?.Dispose(); + openMenu?.Dispose(); + content?.Dispose(); + surface.Dispose(); + SetQuickBarOwner(null); + } + base.Dispose(disposing); + } + + /// + protected override AccessibleObject CreateAccessibilityInstance() => new MathEditBoxAccessibleObject(this); + + /// + protected override void OnHandleCreated(EventArgs e) + { + base.OnHandleCreated(e); + Relayout(); + } + + /// + protected override void OnHandleDestroyed(EventArgs e) + { + base.OnHandleDestroyed(e); + blink.Stop(); + quickBar?.Hide(); + InvalidateContent(); + View.Reset(); + } + + /// + protected override void OnPaint(PaintEventArgs e) + { + var scale = DpiScale; + if (View.Layout == null) + Measure(Width); + View.Arrange(ClientSize.Width / scale, ClientSize.Height / scale); + using (var canvas = surface.Begin(ClientSize, MathCanvas.ToSkia(BackColor), scale)) + { + var thickness = View.BorderThickness; + if (thickness > 0 && !borderColor.IsEmpty) + { + using var pen = new SKPaint { Style = SKPaintStyle.Stroke, StrokeWidth = (float)thickness, Color = MathCanvas.ToSkia(borderColor) }; + var half = (float)thickness / 2; + canvas.DrawRect(half, half, Math.Max(0, ClientSize.Width / scale - (float)thickness), Math.Max(0, ClientSize.Height / scale - (float)thickness), pen); + } + canvas.DrawPicture(content ??= RecordContent()); + using var caret = new MathCanvas(canvas, new MathColors(Foreground, caret: caretColor.IsEmpty ? Foreground : MathCanvas.ToSkia(caretColor))); + View.RenderCaret(caret); + } + surface.Present(e.Graphics); + } + + /// + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + InvalidateContent(); + UpdateQuickBar(); + } + + /// + protected override void OnFontChanged(EventArgs e) + { + base.OnFontChanged(e); + Relayout(); + } + + /// + protected override void OnPaddingChanged(EventArgs e) + { + base.OnPaddingChanged(e); + Relayout(); + } + + /// + protected override void OnForeColorChanged(EventArgs e) + { + base.OnForeColorChanged(e); + InvalidateContent(); + } + + /// + protected override void OnDpiChangedAfterParent(EventArgs e) + { + base.OnDpiChangedAfterParent(e); + Relayout(); + } + + /// + protected override void OnGotFocus(EventArgs e) + { + base.OnGotFocus(e); + OnFocusChanged(true); + } + + /// + protected override void OnLostFocus(EventArgs e) + { + base.OnLostFocus(e); + OnFocusChanged(false); + } + + /// + protected override bool IsInputKey(Keys keyData) => (keyData & Keys.KeyCode) switch + { + Keys.Left or Keys.Right or Keys.Up or Keys.Down or Keys.Home or Keys.End => true, + _ => base.IsInputKey(keyData), + }; + + /// + protected override bool ProcessDialogKey(Keys keyData) + { + // Tab, Enter and Escape go to the editor first (the next slot, a new row, the completions), then to the form + if ((keyData & Keys.KeyCode) is Keys.Tab or Keys.Enter or Keys.Escape && HandleKey(keyData & Keys.KeyCode, Modifiers(keyData))) + return true; + return base.ProcessDialogKey(keyData); + } + + /// + protected override void OnKeyDown(KeyEventArgs e) + { + base.OnKeyDown(e); + if (!e.Handled && HandleKey(e.KeyCode, Modifiers(e.KeyData))) + { + e.Handled = true; + e.SuppressKeyPress = true; + } + } + + /// + protected override void OnKeyPress(KeyPressEventArgs e) + { + base.OnKeyPress(e); + if (e.Handled) + return; + var ch = e.KeyChar; + if (char.IsHighSurrogate(ch)) + { + pendingHighSurrogate = ch; + e.Handled = true; + return; + } + var text = char.IsLowSurrogate(ch) && pendingHighSurrogate != '\0' ? new string(new[] { pendingHighSurrogate, ch }) : ch.ToString(); + pendingHighSurrogate = '\0'; + e.Handled = Type(text); + } + + /// + protected override void OnMouseDown(MouseEventArgs e) + { + base.OnMouseDown(e); + if (e.Button != MouseButtons.Left) + return; + PressAt(e.X / DpiScale, e.Y / DpiScale, (ModifierKeys & Keys.Shift) != 0); + } + + /// + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + View.PointerMoved(e.X / DpiScale, e.Y / DpiScale); + } + + /// + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (e.Button == MouseButtons.Left && View.PointerReleased()) + Capture = false; + } + + /// + protected override void WndProc(ref Message m) + { + // a right click, the Menu key or Shift+F10: the keyboard sends no point (-1, -1), and the menu opens at the caret + if (m.Msg == WM_CONTEXTMENU) + { + var lParam = unchecked((int)(long)m.LParam); + Point? point = lParam == -1 ? null : PointToClient(new Point(unchecked((short)(lParam & 0xFFFF)), unchecked((short)((lParam >> 16) & 0xFFFF)))); + ShowContextMenu(point); + return; + } + base.WndProc(ref m); + } + + /// The main button pressed at a point of the control, in device-independent pixels: it takes the focus and the caret goes there. + internal void PressAt(double x, double y, bool extend) + { + Focus(); + View.PointerPressed(x, y, extend); + } + + /// Text typed, as a keyboard or an input method types it: the control characters of the keys are left to them. + /// Whether the text was used. + internal bool Type(string text) + { + if (IsReadOnly || string.IsNullOrEmpty(text)) + return false; + foreach (var ch in text) + { + if (ch < ' ' || ch == '\u007F') + return false; + } + Editor.Insert(text); + return true; + } + + /// Acts on a key pressed with modifiers: the floating bar, the shortcuts, then the editor. + /// Whether the key was used. + internal bool HandleKey(Keys key, MathKeyModifiers modifiers) + { + var control = (modifiers & MathKeyModifiers.Control) != 0; + var shift = (modifiers & MathKeyModifiers.Shift) != 0; + + var mathKey = ToMathKey(key); + if (IsQuickBarOpen && mathKey is { } quickBarKey && View.ProcessQuickBarKey(quickBarKey, modifiers)) + { + UpdateQuickBar(); + return true; + } + + switch (key) + { + case Keys.L when control && shift: + ToggleViewMode(); + return true; + case Keys.C when control: + case Keys.Insert when control: + Copy(); + return true; + case Keys.X when control: + case Keys.Delete when shift && !control: + Cut(); + return true; + case Keys.V when control: + case Keys.Insert when shift && !control: + Paste(); + return true; + case Keys.Z when control && shift && !IsReadOnly: + case Keys.Y when control && !IsReadOnly: + Editor.Redo(); + return true; + case Keys.Z when control && !IsReadOnly: + Editor.Undo(); + return true; + case Keys.A when control: + Editor.SelectAll(); + return true; + default: + return mathKey is { } editorKey && Editor.ProcessKey(editorKey, modifiers, EquationLayout, IsReadOnly); + } + } + + /// Draws the selection and the equation into a picture, which each paint draws again under the caret. + private SKPicture RecordContent() + { + using var recorder = new SKPictureRecorder(); + var canvas = recorder.BeginRecording(SKRect.Create(0, 0, (float)View.Size.Width, (float)View.Size.Height)); + using (var math = new MathCanvas(canvas, new MathColors(Foreground, MathCanvas.ToSkia(placeholderColor), ErrorColor, MathCanvas.ToSkia(selectionColor)))) + View.Render(math); + return recorder.EndRecording(); + } + + private SKColor Foreground => MathCanvas.ToSkia(ForeColor); + + private static MathKey? ToMathKey(Keys key) => key switch + { + Keys.Left => MathKey.Left, + Keys.Right => MathKey.Right, + Keys.Up => MathKey.Up, + Keys.Down => MathKey.Down, + Keys.Home => MathKey.Home, + Keys.End => MathKey.End, + Keys.Back => MathKey.Backspace, + Keys.Delete => MathKey.Delete, + Keys.Tab => MathKey.Tab, + Keys.Enter => MathKey.Enter, + Keys.Escape => MathKey.Escape, + _ => null, + }; + + private static MathKeyModifiers Modifiers(Keys keyData) => + ((keyData & Keys.Shift) != 0 ? MathKeyModifiers.Shift : MathKeyModifiers.None) + | ((keyData & Keys.Control) != 0 ? MathKeyModifiers.Control : MathKeyModifiers.None) + | ((keyData & Keys.Alt) != 0 ? MathKeyModifiers.Alt : MathKeyModifiers.None); + + private static byte[]? Bytes(object? data) => data switch + { + byte[] bytes => bytes, + MemoryStream stream => stream.ToArray(), + Stream stream => ReadAll(stream), + string text => MathClipboard.Encode(text), + _ => null, + }; + + private static byte[] ReadAll(Stream stream) + { + using var copy = new MemoryStream(); + stream.CopyTo(copy); + return copy.ToArray(); + } + + private static string Gesture(string command) => command switch + { + "undo" => "Ctrl+Z", + "redo" => "Ctrl+Y", + "cut" => "Ctrl+X", + "copy" => "Ctrl+C", + "paste" => "Ctrl+V", + "select-all" => "Ctrl+A", + "view" => "Ctrl+Shift+L", + "new-line" => "Shift+Enter", + _ => string.Empty, + }; + + /// Gives the view its font, size, padding and border, and lays out the equation for a width in pixels. + private MathSize Measure(int width) + { + var scale = DpiScale; + View.Font = MathFont ?? MathFonts.Default; + View.FontSize = FontSize; + View.Padding = new MathThickness(Padding.Left / scale, Padding.Top / scale, Padding.Right / scale, Padding.Bottom / scale); + View.BorderThickness = borderWidth; + return View.Measure(width > 0 ? width / (double)scale : double.PositiveInfinity); + } + + /// Lays out the equation again, and gives the control the height it takes. + private void Relayout() + { + var size = Measure(Width); + if (AutoSize) + { + var height = (int)Math.Ceiling(size.Height * DpiScale); + if (height != Height) + Height = height; + } + InvalidateContent(); + UpdateQuickBar(); + } + + private void InvalidateContent() + { + content?.Dispose(); + content = null; + Invalidate(); + } + + private void InvalidateCaret() + { + if (View.GetCaretRect() is not { } caret) + { + Invalidate(); + return; + } + var scale = DpiScale; + Invalidate(new Rectangle((int)Math.Floor((caret.X - 2) * scale), (int)Math.Floor((caret.Y - 1) * scale), (int)Math.Ceiling(5 * scale), (int)Math.Ceiling((caret.Height + 2) * scale))); + } + + private bool ShouldSerializeSelectionColor() => selectionColor != Color.FromArgb(0x60, 0x33, 0x99, 0xFF); + + private void ResetSelectionColor() => SelectionColor = Color.FromArgb(0x60, 0x33, 0x99, 0xFF); + + private bool ShouldSerializeCaretColor() => !caretColor.IsEmpty; + + private void ResetCaretColor() => CaretColor = Color.Empty; + + private bool ShouldSerializePlaceholderColor() => placeholderColor != Color.Gray; + + private void ResetPlaceholderColor() => PlaceholderColor = Color.Gray; + + private bool ShouldSerializeBorderColor() => borderColor != Color.Gray; + + private void ResetBorderColor() => BorderColor = Color.Gray; + + private bool ShouldSerializeFontSize() => fontSize.HasValue; + + private void ResetFontSize() + { + fontSize = null; + Relayout(); + } + + private void ToggleViewMode() => ViewMode = ViewMode == MathViewMode.Linear ? MathViewMode.Professional : MathViewMode.Linear; + + private ToolStripItem Item(MathMenuItem item) + { + if (item.IsSeparator) + return new ToolStripSeparator(); + var command = item.Command!; + var menuItem = new ToolStripMenuItem(item.Header) { Tag = command, Enabled = item.IsEnabled, ShortcutKeyDisplayString = Gesture(command) }; + if (item.Items.Count > 0) + { + foreach (var child in item.Items) + menuItem.DropDownItems.Add(Item(child)); + return menuItem; + } + menuItem.Click += (_, _) => + { + Execute(command); + Focus(); + }; + return menuItem; + } + + /// Does a command of the context menu: those of the clipboard and the view here, the others on the editor (). + private void Execute(string command) + { + switch (command) + { + case "cut": + Cut(); + break; + case "copy": + Copy(); + break; + case "paste": + Paste(); + break; + case "view": + ToggleViewMode(); + break; + case var _ when MathEditorView.CopyAsFormat(command) is { } format: + CopyAs(format); + break; + default: + View.ExecuteCommand(command); + break; + } + } + + private void OnFocusChanged(bool focused) + { + View.IsFocused = focused; + if (focused) + blink.Start(); + else + blink.Stop(); + InvalidateCaret(); + UpdateQuickBar(); + } + + private void OnEditorContentChanged(object? sender, EventArgs e) + { + var edited = Editor.ToEquation(); + updatingEquation = true; + try + { + Equation = edited; + } + finally + { + updatingEquation = false; + } + if (ViewMode == MathViewMode.Linear != Editor.IsLinear) + viewMode = Editor.IsLinear ? MathViewMode.Linear : MathViewMode.Professional; + EquationChanged?.Invoke(this, new EquationChangedEventArgs(edited)); + } + + private void OnViewChanged(object? sender, MathEditorViewChangedEventArgs e) + { + if ((e.Changes & MathEditorViewChanges.Measure) != 0) + Relayout(); + else if ((e.Changes & MathEditorViewChanges.Render) != 0) + InvalidateContent(); + if ((e.Changes & MathEditorViewChanges.Caret) != 0) + Invalidate(); + if ((e.Changes & MathEditorViewChanges.QuickBar) != 0 && IsHandleCreated) + BeginInvoke(new Action(UpdateQuickBar)); + } + + /// Opens the floating bar under the equation, at the caret, with what fits the place of the caret, or closes it. + private void UpdateQuickBar() + { + if (!IsHandleCreated || IsDisposed) + return; + var refill = View.UpdateQuickBar() || View.QuickBar.Mode != MathQuickBarMode.Completions; + if (View.QuickBarAnchor is not { } anchor || FindForm() is not { Visible: true } form) + { + quickBar?.Hide(); + return; + } + var bar = quickBar ??= new QuickBar(); + SetQuickBarOwner(form); + var completions = View.QuickBar.Mode == MathQuickBarMode.Completions; + if (refill || bar.Count == 0) + bar.Fill(View.QuickBar.GetItems(QuickSymbols), completions, completions ? 130 : View.QuickBar.Mode == MathQuickBarMode.Symbols ? 26 : 36); + bar.Highlight(completions ? View.QuickBar.SelectedIndex : -1); + var scale = DpiScale; + bar.Location = PointToScreen(new Point((int)(anchor.X * scale), (int)Math.Ceiling(anchor.Bottom * scale))); + if (!bar.Visible) + bar.Show(form); + } + + /// Follows the form the floating bar belongs to: the bar moves with it. + private void SetQuickBarOwner(Form? form) + { + if (ReferenceEquals(quickBarOwner, form)) + return; + if (quickBarOwner != null) + quickBarOwner.Move -= OnOwnerMoved; + quickBarOwner = form; + if (form != null) + form.Move += OnOwnerMoved; + } + + private void OnOwnerMoved(object? sender, EventArgs e) => UpdateQuickBar(); + } +} diff --git a/src/SharpEquations.WinForms/MathEditBoxAccessibleObject.cs b/src/SharpEquations.WinForms/MathEditBoxAccessibleObject.cs new file mode 100644 index 0000000..58c74b9 --- /dev/null +++ b/src/SharpEquations.WinForms/MathEditBoxAccessibleObject.cs @@ -0,0 +1,49 @@ +namespace SharpEquations.WinForms +{ + using System.Windows.Forms; + + /// + /// The accessible object of : an editable text whose value is the equation in UnicodeMath, + /// as screen readers read the equations of Word; setting the value reads it in the input format. + /// + public class MathEditBoxAccessibleObject : Control.ControlAccessibleObject + { + private readonly MathEditBox editor; + + /// The accessible object of an editor. + public MathEditBoxAccessibleObject(MathEditBox owner) + : base(owner) => editor = owner; + + /// + public override AccessibleRole Role => editor.AccessibleRole != AccessibleRole.Default ? editor.AccessibleRole : AccessibleRole.Text; + + /// + public override string? Name + { + get => base.Name is { Length: > 0 } name ? name : "Equation"; + set => base.Name = value; + } + + /// + public override AccessibleStates State => base.State | (editor.IsReadOnly ? AccessibleStates.ReadOnly : AccessibleStates.None); + + /// +#if NET + [System.Diagnostics.CodeAnalysis.AllowNull] +#endif + public override string Value + { + get => editor.GetText(EquationFormat.UnicodeMath); + set + { + if (editor.IsReadOnly) + return; + editor.Editor.SelectAll(); + if (string.IsNullOrEmpty(value)) + editor.Editor.DeleteSelection(); + else + editor.Editor.Paste(value, editor.InputFormat); + } + } + } +} diff --git a/src/SharpEquations.WinForms/MathFonts.cs b/src/SharpEquations.WinForms/MathFonts.cs new file mode 100644 index 0000000..bcdb19a --- /dev/null +++ b/src/SharpEquations.WinForms/MathFonts.cs @@ -0,0 +1,43 @@ +namespace SharpEquations.WinForms +{ + using System; + using System.IO; + using SharpEquations.Rendering; + + /// + /// The math font of the controls: Libertinus Math (SIL Open Font License), embedded in this assembly and read from its + /// file, so that it is the same on every system; its glyphs are drawn as paths from their outlines. + /// + public static class MathFonts + { + private static readonly Lazy Libertinus = new Lazy(() => + { + using var stream = typeof(MathFonts).Assembly.GetManifestResourceStream("SharpEquations.WinForms.LibertinusMath-Regular.otf") + ?? throw new InvalidOperationException("The embedded Libertinus Math font is missing."); + using var copy = new MemoryStream(); + stream.CopyTo(copy); + return new OpenTypeMathFont(copy.ToArray()); + }); + + /// The embedded Libertinus Math. + public static OpenTypeMathFont LibertinusMath => Libertinus.Value; + + /// The default math font: Libertinus Math. + public static OpenTypeMathFont Default => Libertinus.Value; + + /// A math font read from the bytes of its file (an OpenType font with a MATH table), for MathFont. + /// The bytes are not an OpenType font, or it has no MATH table. + public static OpenTypeMathFont FromFile(byte[] data) + { + var font = new OpenTypeMathFont(data); + return font.Math != null ? font : throw new FormatException("The font has no MATH table."); + } + + /// + /// A math font read from its file (an OpenType font with a MATH table), for MathFont; of a collection, the + /// face with the MATH table: Cambria Math of C:\Windows\Fonts\cambria.ttc. + /// + /// The file is not an OpenType font, or it has no MATH table. + public static OpenTypeMathFont FromFile(string path) => FromFile(File.ReadAllBytes(path)); + } +} diff --git a/src/SharpEquations.WinForms/MathSurface.cs b/src/SharpEquations.WinForms/MathSurface.cs new file mode 100644 index 0000000..6919d4d --- /dev/null +++ b/src/SharpEquations.WinForms/MathSurface.cs @@ -0,0 +1,54 @@ +namespace SharpEquations.WinForms +{ + using System; + using System.Drawing; + using System.Drawing.Imaging; + using SkiaSharp; + + /// + /// The pixels a control draws into with Skia, in its size in pixels, copied to its window as they are: Skia draws + /// everything, and Windows Forms only puts the bitmap on the screen. + /// + internal sealed class MathSurface : IDisposable + { + private SKBitmap? bitmap; + private Bitmap? image; + + /// A canvas over the pixels, of a size in pixels, cleared with a colour and scaled from device-independent pixels. + public SKCanvas Begin(Size size, SKColor background, float scale) + { + var width = Math.Max(1, size.Width); + var height = Math.Max(1, size.Height); + if (bitmap == null || bitmap.Width != width || bitmap.Height != height) + { + Release(); + bitmap = new SKBitmap(new SKImageInfo(width, height, SKColorType.Bgra8888, SKAlphaType.Premul)); + image = new Bitmap(width, height, bitmap.RowBytes, PixelFormat.Format32bppPArgb, bitmap.GetPixels()); + } + var canvas = new SKCanvas(bitmap); + canvas.Clear(background); + canvas.Scale(scale); + return canvas; + } + + /// Puts the pixels drawn on the graphics of the window. + public void Present(Graphics graphics) + { + if (image != null) + graphics.DrawImageUnscaled(image, 0, 0); + } + + /// The pixels drawn, as bytes in the order blue, green, red, alpha, premultiplied (for the tests). + internal SKBitmap? Pixels => bitmap; + + public void Dispose() => Release(); + + private void Release() + { + image?.Dispose(); + image = null; + bitmap?.Dispose(); + bitmap = null; + } + } +} diff --git a/src/SharpEquations.WinForms/MathView.cs b/src/SharpEquations.WinForms/MathView.cs new file mode 100644 index 0000000..5a9cc26 --- /dev/null +++ b/src/SharpEquations.WinForms/MathView.cs @@ -0,0 +1,217 @@ +namespace SharpEquations.WinForms +{ + using System; + using System.ComponentModel; + using System.Drawing; + using System.Windows.Forms; + using SharpEquations.Editing; + using SharpEquations.Rendering; + using SkiaSharp; + + /// + /// Shows an equation, laid out after MathML Core with a math font and drawn with Skia, its glyphs as paths from their + /// outlines. With (the default) the control takes the size of the equation. + /// + public class MathView : Control + { + private static readonly SKColor ErrorColor = new SKColor(0xFF, 0xE4, 0xE1); + private readonly MathLayoutCache layoutCache = new MathLayoutCache(); + private readonly MathSurface surface = new MathSurface(); + private (Equation Equation, MathNode Root)? tree; + private Equation? equation; + private bool isDisplay; + private OpenTypeMathFont? mathFont; + private double? fontSize; + + /// A view with no equation. + public MathView() + { + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.Opaque | ControlStyles.ResizeRedraw, true); + SetStyle(ControlStyles.Selectable, false); + TabStop = false; + base.AutoSize = true; + } + + /// The equation shown. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public Equation? Equation + { + get => equation; + set + { + if (ReferenceEquals(equation, value)) + return; + equation = value; + Relayout(); + } + } + + /// The MathML of the equation shown; setting it reads the MathML. + /// The MathML is not valid. + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public string? MathML + { + get => Equation?.ToString(EquationFormat.MathML); + set => Equation = string.IsNullOrEmpty(value) ? null : Equation.Parse(value!, EquationFormat.MathML); + } + + /// Whether the equation is laid out in display style even if it is inline. + [DefaultValue(false)] + public bool IsDisplay + { + get => isDisplay; + set + { + if (isDisplay == value) + return; + isDisplay = value; + Relayout(); + } + } + + /// The math font; null for . + [Browsable(false)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] + public OpenTypeMathFont? MathFont + { + get => mathFont; + set + { + mathFont = value; + Relayout(); + } + } + + /// The size of the font, in device-independent pixels; by default that of . + public double FontSize + { + get => fontSize ?? Font.SizeInPoints * 96 / 72; + set + { + if (!(value > 0)) + throw new ArgumentOutOfRangeException(nameof(value), "The size of the font is positive."); + fontSize = value; + Relayout(); + } + } + + /// Whether the control takes the size of the equation; true by default. + [DefaultValue(true)] + [Browsable(true)] + [EditorBrowsable(EditorBrowsableState.Always)] + [DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)] + public override bool AutoSize + { + get => base.AutoSize; + set + { + base.AutoSize = value; + Relayout(); + } + } + + /// The layout of the equation, in device-independent pixels; null without an equation. + [Browsable(false)] + public MathLayout? EquationLayout { get; private set; } + + /// The scale of the device-independent pixels of the layout to the pixels of the screen. + internal float DpiScale => DeviceDpi / 96f; + + internal MathSurface Surface => surface; + + /// + public override Size GetPreferredSize(Size proposedSize) + { + if (UpdateLayout(proposedSize.Width is > 0 and < int.MaxValue ? proposedSize.Width : (int?)null) is not { } layout) + return Size.Empty; + return new Size((int)Math.Ceiling(layout.Width * DpiScale), (int)Math.Ceiling(layout.Height * DpiScale)); + } + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + surface.Dispose(); + base.Dispose(disposing); + } + + /// + protected override void OnPaint(PaintEventArgs e) + { + var canvas = surface.Begin(ClientSize, MathCanvas.ToSkia(BackColor), DpiScale); + using (canvas) + { + if ((EquationLayout ?? UpdateLayout(AutoSize ? null : ClientSize.Width)) is { } layout) + { + using var math = new MathCanvas(canvas, new MathColors(MathCanvas.ToSkia(ForeColor), error: ErrorColor)); + layout.Draw(math, 0, 0); + } + } + surface.Present(e.Graphics); + } + + /// + protected override void OnFontChanged(EventArgs e) + { + base.OnFontChanged(e); + Relayout(); + } + + /// + protected override void OnDpiChangedAfterParent(EventArgs e) + { + base.OnDpiChangedAfterParent(e); + Relayout(); + } + + /// + protected override void OnHandleDestroyed(EventArgs e) + { + base.OnHandleDestroyed(e); + tree = null; + EquationLayout = null; + layoutCache.Clear(); + } + + /// + protected override void OnResize(EventArgs e) + { + base.OnResize(e); + if (!AutoSize) + EquationLayout = null; + } + + private bool ShouldSerializeFontSize() => fontSize.HasValue; + + private void ResetFontSize() + { + fontSize = null; + Relayout(); + } + + private void Relayout() + { + EquationLayout = null; + if (AutoSize) + { + var size = GetPreferredSize(Size.Empty); + if (size != Size) + Size = size; + } + Invalidate(); + } + + /// Lays out the equation for a width in pixels, or for no limit. + private MathLayout? UpdateLayout(int? width) + { + if (Equation is not { } current) + return EquationLayout = null; + if (tree is not { } cached || !ReferenceEquals(cached.Equation, current)) + tree = cached = (current, MathNode.FromMathML(current.ToMathML())); + var options = new MathLayoutOptions { FontSize = FontSize, Display = IsDisplay, LineWidth = width / (double)DpiScale }; + return EquationLayout = MathLayoutEngine.Layout(cached.Root, MathFont ?? MathFonts.Default, options, layoutCache); + } + } +} diff --git a/src/SharpEquations.WinForms/MathViewMode.cs b/src/SharpEquations.WinForms/MathViewMode.cs new file mode 100644 index 0000000..f483949 --- /dev/null +++ b/src/SharpEquations.WinForms/MathViewMode.cs @@ -0,0 +1,61 @@ +namespace SharpEquations.WinForms +{ + using System; + using System.Windows.Forms; + + /// Whether an equation is shown built up or as linear text, as the math zones of Word. + public enum MathViewMode + { + /// Built up: fractions, scripts, radicals. + Professional, + + /// As the linear text of the input format. + Linear, + } + + /// The arguments of . + public sealed class EquationChangedEventArgs : EventArgs + { + /// Arguments with the new equation. + public EquationChangedEventArgs(Equation? equation) => Equation = equation; + + /// The equation; null when the editor is empty. + public Equation? Equation { get; } + } + + /// The arguments of . + public sealed class MathCopyingEventArgs : EventArgs + { + /// Arguments with the equation copied and the data of the clipboard. + public MathCopyingEventArgs(Equation equation, DataObject data) + { + Equation = equation; + Data = data; + } + + /// The selection copied. + public Equation Equation { get; } + + /// The data that goes to the clipboard, with the text and the MathML; a handler can add formats. + public DataObject Data { get; } + + /// Set to true to copy nothing. + public bool Cancel { get; set; } + } + + /// The arguments of . + public sealed class MathContextMenuEventArgs : EventArgs + { + /// Arguments with the menu about to open. + public MathContextMenuEventArgs(ContextMenuStrip menu) => Menu = menu; + + /// + /// The menu, which a handler can change: its items have a tag () that names their command (cut, copy, + /// paste, copy-as...; see ). + /// + public ContextMenuStrip Menu { get; } + + /// Set to true to open no menu. + public bool Cancel { get; set; } + } +} diff --git a/src/SharpEquations.WinForms/PublicAPI.Shipped.txt b/src/SharpEquations.WinForms/PublicAPI.Shipped.txt new file mode 100644 index 0000000..7dc5c58 --- /dev/null +++ b/src/SharpEquations.WinForms/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/SharpEquations.WinForms/PublicAPI.Unshipped.txt b/src/SharpEquations.WinForms/PublicAPI.Unshipped.txt new file mode 100644 index 0000000..9f08388 --- /dev/null +++ b/src/SharpEquations.WinForms/PublicAPI.Unshipped.txt @@ -0,0 +1,137 @@ +#nullable enable +SharpEquations.WinForms.EquationChangedEventArgs +SharpEquations.WinForms.EquationChangedEventArgs.Equation.get -> SharpEquations.Equation? +SharpEquations.WinForms.EquationChangedEventArgs.EquationChangedEventArgs(SharpEquations.Equation? equation) -> void +SharpEquations.WinForms.MathContextMenuEventArgs +SharpEquations.WinForms.MathContextMenuEventArgs.Cancel.get -> bool +SharpEquations.WinForms.MathContextMenuEventArgs.Cancel.set -> void +SharpEquations.WinForms.MathContextMenuEventArgs.MathContextMenuEventArgs(System.Windows.Forms.ContextMenuStrip! menu) -> void +SharpEquations.WinForms.MathContextMenuEventArgs.Menu.get -> System.Windows.Forms.ContextMenuStrip! +SharpEquations.WinForms.MathCopyingEventArgs +SharpEquations.WinForms.MathCopyingEventArgs.Cancel.get -> bool +SharpEquations.WinForms.MathCopyingEventArgs.Cancel.set -> void +SharpEquations.WinForms.MathCopyingEventArgs.Data.get -> System.Windows.Forms.DataObject! +SharpEquations.WinForms.MathCopyingEventArgs.Equation.get -> SharpEquations.Equation! +SharpEquations.WinForms.MathCopyingEventArgs.MathCopyingEventArgs(SharpEquations.Equation! equation, System.Windows.Forms.DataObject! data) -> void +SharpEquations.WinForms.MathEditBox +SharpEquations.WinForms.MathEditBox.AutoCorrect.get -> SharpEquations.Editing.MathAutoCorrect! +SharpEquations.WinForms.MathEditBox.AutoCorrect.set -> void +SharpEquations.WinForms.MathEditBox.BorderColor.get -> System.Drawing.Color +SharpEquations.WinForms.MathEditBox.BorderColor.set -> void +SharpEquations.WinForms.MathEditBox.BorderWidth.get -> int +SharpEquations.WinForms.MathEditBox.BorderWidth.set -> void +SharpEquations.WinForms.MathEditBox.BuildDown() -> void +SharpEquations.WinForms.MathEditBox.BuildUp() -> void +SharpEquations.WinForms.MathEditBox.CaretColor.get -> System.Drawing.Color +SharpEquations.WinForms.MathEditBox.CaretColor.set -> void +SharpEquations.WinForms.MathEditBox.Copy() -> void +SharpEquations.WinForms.MathEditBox.CopyAs(SharpEquations.EquationFormat format) -> void +SharpEquations.WinForms.MathEditBox.CopyTextFormat.get -> SharpEquations.EquationFormat? +SharpEquations.WinForms.MathEditBox.CopyTextFormat.set -> void +SharpEquations.WinForms.MathEditBox.Copying -> System.EventHandler? +SharpEquations.WinForms.MathEditBox.Cut() -> void +SharpEquations.WinForms.MathEditBox.Editor.get -> SharpEquations.Editing.MathEditor! +SharpEquations.WinForms.MathEditBox.Equation.get -> SharpEquations.Equation? +SharpEquations.WinForms.MathEditBox.Equation.set -> void +SharpEquations.WinForms.MathEditBox.EquationChanged -> System.EventHandler? +SharpEquations.WinForms.MathEditBox.EquationLayout.get -> SharpEquations.Rendering.MathLayout? +SharpEquations.WinForms.MathEditBox.EquationNumber.get -> string? +SharpEquations.WinForms.MathEditBox.EquationNumber.set -> void +SharpEquations.WinForms.MathEditBox.FontSize.get -> double +SharpEquations.WinForms.MathEditBox.FontSize.set -> void +SharpEquations.WinForms.MathEditBox.GetMath() -> string! +SharpEquations.WinForms.MathEditBox.GetSelectedText(SharpEquations.EquationFormat format, SharpEquations.EquationOptions? options = null) -> string? +SharpEquations.WinForms.MathEditBox.GetText(SharpEquations.EquationFormat format) -> string! +SharpEquations.WinForms.MathEditBox.InputFormat.get -> SharpEquations.EquationFormat +SharpEquations.WinForms.MathEditBox.InputFormat.set -> void +SharpEquations.WinForms.MathEditBox.IsAutoCorrectEnabled.get -> bool +SharpEquations.WinForms.MathEditBox.IsAutoCorrectEnabled.set -> void +SharpEquations.WinForms.MathEditBox.IsContextMenuEnabled.get -> bool +SharpEquations.WinForms.MathEditBox.IsContextMenuEnabled.set -> void +SharpEquations.WinForms.MathEditBox.IsDisplay.get -> bool +SharpEquations.WinForms.MathEditBox.IsDisplay.set -> void +SharpEquations.WinForms.MathEditBox.IsQuickBarEnabled.get -> bool +SharpEquations.WinForms.MathEditBox.IsQuickBarEnabled.set -> void +SharpEquations.WinForms.MathEditBox.IsQuickBarOpen.get -> bool +SharpEquations.WinForms.MathEditBox.IsReadOnly.get -> bool +SharpEquations.WinForms.MathEditBox.IsReadOnly.set -> void +SharpEquations.WinForms.MathEditBox.MathContextMenuOpening -> System.EventHandler? +SharpEquations.WinForms.MathEditBox.MathEditBox() -> void +SharpEquations.WinForms.MathEditBox.MathFont.get -> SharpEquations.Rendering.OpenTypeMathFont? +SharpEquations.WinForms.MathEditBox.MathFont.set -> void +SharpEquations.WinForms.MathEditBox.OpenContextMenu.get -> System.Windows.Forms.ContextMenuStrip? +SharpEquations.WinForms.MathEditBox.Paste() -> void +SharpEquations.WinForms.MathEditBox.PlaceholderColor.get -> System.Drawing.Color +SharpEquations.WinForms.MathEditBox.PlaceholderColor.set -> void +SharpEquations.WinForms.MathEditBox.QuickSymbols.get -> System.Collections.Generic.IList! +SharpEquations.WinForms.MathEditBox.SelectionColor.get -> System.Drawing.Color +SharpEquations.WinForms.MathEditBox.SelectionColor.set -> void +SharpEquations.WinForms.MathEditBox.SetMath(string! mathML) -> void +SharpEquations.WinForms.MathEditBox.ShowContextMenu(System.Drawing.Point? point = null) -> bool +SharpEquations.WinForms.MathEditBox.View.get -> SharpEquations.Rendering.MathEditorView! +SharpEquations.WinForms.MathEditBox.ViewMode.get -> SharpEquations.WinForms.MathViewMode +SharpEquations.WinForms.MathEditBox.ViewMode.set -> void +SharpEquations.WinForms.MathEditBoxAccessibleObject +SharpEquations.WinForms.MathEditBoxAccessibleObject.MathEditBoxAccessibleObject(SharpEquations.WinForms.MathEditBox! owner) -> void +SharpEquations.WinForms.MathFonts +SharpEquations.WinForms.MathView +SharpEquations.WinForms.MathView.Equation.get -> SharpEquations.Equation? +SharpEquations.WinForms.MathView.Equation.set -> void +SharpEquations.WinForms.MathView.EquationLayout.get -> SharpEquations.Rendering.MathLayout? +SharpEquations.WinForms.MathView.FontSize.get -> double +SharpEquations.WinForms.MathView.FontSize.set -> void +SharpEquations.WinForms.MathView.IsDisplay.get -> bool +SharpEquations.WinForms.MathView.IsDisplay.set -> void +SharpEquations.WinForms.MathView.MathFont.get -> SharpEquations.Rendering.OpenTypeMathFont? +SharpEquations.WinForms.MathView.MathFont.set -> void +SharpEquations.WinForms.MathView.MathML.get -> string? +SharpEquations.WinForms.MathView.MathML.set -> void +SharpEquations.WinForms.MathView.MathView() -> void +SharpEquations.WinForms.MathViewMode +SharpEquations.WinForms.MathViewMode.Linear = 1 -> SharpEquations.WinForms.MathViewMode +SharpEquations.WinForms.MathViewMode.Professional = 0 -> SharpEquations.WinForms.MathViewMode +const SharpEquations.WinForms.MathEditBox.MathMLClipboardFormat = "MathML" -> string! +override SharpEquations.WinForms.MathEditBox.AutoSize.get -> bool +override SharpEquations.WinForms.MathEditBox.AutoSize.set -> void +override SharpEquations.WinForms.MathEditBox.CreateAccessibilityInstance() -> System.Windows.Forms.AccessibleObject! +override SharpEquations.WinForms.MathEditBox.Dispose(bool disposing) -> void +override SharpEquations.WinForms.MathEditBox.GetPreferredSize(System.Drawing.Size proposedSize) -> System.Drawing.Size +override SharpEquations.WinForms.MathEditBox.IsInputKey(System.Windows.Forms.Keys keyData) -> bool +override SharpEquations.WinForms.MathEditBox.OnDpiChangedAfterParent(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnFontChanged(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnForeColorChanged(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnGotFocus(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnHandleCreated(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnHandleDestroyed(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnKeyDown(System.Windows.Forms.KeyEventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnKeyPress(System.Windows.Forms.KeyPressEventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnLostFocus(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnMouseDown(System.Windows.Forms.MouseEventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnMouseMove(System.Windows.Forms.MouseEventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnMouseUp(System.Windows.Forms.MouseEventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnPaddingChanged(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnPaint(System.Windows.Forms.PaintEventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.OnResize(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathEditBox.ProcessDialogKey(System.Windows.Forms.Keys keyData) -> bool +override SharpEquations.WinForms.MathEditBox.SetBoundsCore(int x, int y, int width, int height, System.Windows.Forms.BoundsSpecified specified) -> void +override SharpEquations.WinForms.MathEditBox.WndProc(ref System.Windows.Forms.Message m) -> void +override SharpEquations.WinForms.MathEditBoxAccessibleObject.Name.get -> string? +override SharpEquations.WinForms.MathEditBoxAccessibleObject.Name.set -> void +override SharpEquations.WinForms.MathEditBoxAccessibleObject.Role.get -> System.Windows.Forms.AccessibleRole +override SharpEquations.WinForms.MathEditBoxAccessibleObject.State.get -> System.Windows.Forms.AccessibleStates +override SharpEquations.WinForms.MathEditBoxAccessibleObject.Value.get -> string! +override SharpEquations.WinForms.MathEditBoxAccessibleObject.Value.set -> void +override SharpEquations.WinForms.MathView.AutoSize.get -> bool +override SharpEquations.WinForms.MathView.AutoSize.set -> void +override SharpEquations.WinForms.MathView.Dispose(bool disposing) -> void +override SharpEquations.WinForms.MathView.GetPreferredSize(System.Drawing.Size proposedSize) -> System.Drawing.Size +override SharpEquations.WinForms.MathView.OnDpiChangedAfterParent(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathView.OnFontChanged(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathView.OnHandleDestroyed(System.EventArgs! e) -> void +override SharpEquations.WinForms.MathView.OnPaint(System.Windows.Forms.PaintEventArgs! e) -> void +override SharpEquations.WinForms.MathView.OnResize(System.EventArgs! e) -> void +static SharpEquations.WinForms.MathFonts.Default.get -> SharpEquations.Rendering.OpenTypeMathFont! +static SharpEquations.WinForms.MathFonts.FromFile(byte[]! data) -> SharpEquations.Rendering.OpenTypeMathFont! +static SharpEquations.WinForms.MathFonts.FromFile(string! path) -> SharpEquations.Rendering.OpenTypeMathFont! +static SharpEquations.WinForms.MathFonts.LibertinusMath.get -> SharpEquations.Rendering.OpenTypeMathFont! +virtual SharpEquations.WinForms.MathEditBox.CreateContextMenu() -> System.Windows.Forms.ContextMenuStrip! diff --git a/src/SharpEquations.WinForms/QuickBar.cs b/src/SharpEquations.WinForms/QuickBar.cs new file mode 100644 index 0000000..65e9cba --- /dev/null +++ b/src/SharpEquations.WinForms/QuickBar.cs @@ -0,0 +1,267 @@ +namespace SharpEquations.WinForms +{ + using System; + using System.Collections.Generic; + using System.Drawing; + using System.Windows.Forms; + using SharpEquations.Editing; + using SkiaSharp; + + /// + /// The floating bar of the editor: a window of its own that never takes the focus (so that typing goes on in the + /// editor), its items drawn with Skia in the user interface font, with a fallback font for the symbols it lacks. + /// + internal sealed class QuickBar : Form + { + private const int WS_EX_NOACTIVATE = 0x08000000; + private const int WS_EX_TOOLWINDOW = 0x00000080; + private const int WM_MOUSEACTIVATE = 0x0021; + private const int MA_NOACTIVATE = 3; + private const float TextSize = 12f * 96 / 72; + private static readonly SKColor BackgroundColor = new SKColor(0xFB, 0xFB, 0xFD); + private static readonly SKColor BorderColor = new SKColor(0xA0, 0xA0, 0xA0); + private static readonly SKColor HighlightColor = new SKColor(0x33, 0x99, 0xFF, 0x40); + private static readonly SKColor HoverColor = new SKColor(0x80, 0x80, 0x80, 0x30); + private static readonly SKTypeface UiTypeface = SKTypeface.FromFamilyName("Segoe UI") ?? SKTypeface.Default; + private readonly MathSurface surface = new MathSurface(); + private readonly ToolTip toolTip = new ToolTip(); + private readonly List<(MathQuickBarItem Item, RectangleF Bounds)> items = new List<(MathQuickBarItem, RectangleF)>(); + private int hovered = -1; + private int tipped = -1; + private bool column; + + public QuickBar() + { + FormBorderStyle = FormBorderStyle.None; + ShowInTaskbar = false; + StartPosition = FormStartPosition.Manual; + ControlBox = false; + MinimizeBox = false; + MaximizeBox = false; + AutoScaleMode = AutoScaleMode.None; + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.Opaque, true); + } + + /// The items shown. + public int Count => items.Count; + + /// The item that Tab or Enter takes, highlighted; -1 for none. + public int Selected { get; private set; } = -1; + + /// + protected override bool ShowWithoutActivation => true; + + /// + protected override CreateParams CreateParams + { + get + { + var parameters = base.CreateParams; + parameters.ExStyle |= WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW; + return parameters; + } + } + + private float DpiScale => DeviceDpi / 96f; + + /// Puts items in the bar, in a column (the completions) or in a row, and sizes it for them. + public void Fill(IReadOnlyList list, bool column, float minWidth) + { + items.Clear(); + this.column = column; + hovered = -1; + Selected = -1; + using var font = new SKFont(UiTypeface, TextSize); + float x = 4, y = 4, width = 0; + var height = TextSize * 1.6f; + foreach (var item in list) + { + var w = Math.Max(minWidth, Measure(item.Text, font) + 12); + if (column) + { + items.Add((item, new RectangleF(4, y, w, height))); + y += height + 2; + width = Math.Max(width, w); + } + else + { + items.Add((item, new RectangleF(x, 4, w, height))); + x += w + 2; + } + } + if (column) + { + for (var i = 0; i < items.Count; i++) + items[i] = (items[i].Item, new RectangleF(4, items[i].Bounds.Y, width, height)); + } + var size = column ? new SizeF(width + 8, y + 2) : new SizeF(x + 2, height + 8); + Size = new Size((int)Math.Ceiling(size.Width * DpiScale), (int)Math.Ceiling(size.Height * DpiScale)); + Invalidate(); + } + + /// Highlights an item; -1 for none. + public void Highlight(int index) + { + if (index == Selected) + return; + Selected = index; + Invalidate(); + } + + /// Invokes the item at a point of the bar, in pixels, as a click does. + internal bool ClickAt(Point point) + { + var index = IndexAt(point); + if (index < 0) + return false; + items[index].Item.Invoke(); + return true; + } + + /// + protected override void WndProc(ref Message m) + { + // a click on the bar invokes an item, and leaves the focus in the editor + if (m.Msg == WM_MOUSEACTIVATE) + { + m.Result = (IntPtr)MA_NOACTIVATE; + return; + } + base.WndProc(ref m); + } + + /// + protected override void OnPaint(PaintEventArgs e) + { + var scale = DpiScale; + using (var canvas = surface.Begin(ClientSize, BackgroundColor, scale)) + using (var paint = new SKPaint { IsAntialias = true }) + using (var font = new SKFont(UiTypeface, TextSize) { Edging = SKFontEdging.SubpixelAntialias }) + { + paint.Style = SKPaintStyle.Stroke; + paint.Color = BorderColor; + canvas.DrawRect(0.5f, 0.5f, ClientSize.Width / scale - 1, ClientSize.Height / scale - 1, paint); + paint.Style = SKPaintStyle.Fill; + for (var i = 0; i < items.Count; i++) + { + var (item, bounds) = items[i]; + var rect = SKRect.Create(bounds.X, bounds.Y, bounds.Width, bounds.Height); + if (i == Selected || i == hovered) + { + paint.Color = i == Selected ? HighlightColor : HoverColor; + canvas.DrawRoundRect(rect, 3, 3, paint); + } + paint.Color = SKColors.Black; + var width = Measure(item.Text, font); + var x = column ? rect.Left + 6 : rect.MidX - width / 2; + font.GetFontMetrics(out var metrics); + Draw(canvas, item.Text, x, rect.MidY - (metrics.Ascent + metrics.Descent) / 2, font, paint); + } + } + surface.Present(e.Graphics); + } + + /// + protected override void OnMouseMove(MouseEventArgs e) + { + base.OnMouseMove(e); + var index = IndexAt(e.Location); + if (index != hovered) + { + hovered = index; + Invalidate(); + } + if (index != tipped) + { + tipped = index; + if (index >= 0 && items[index].Item.ToolTip is { Length: > 0 } tip) + toolTip.Show(tip, this, e.X, e.Y + (int)(TextSize * 2 * DpiScale), 3000); + else + toolTip.Hide(this); + } + } + + /// + protected override void OnMouseLeave(EventArgs e) + { + base.OnMouseLeave(e); + hovered = tipped = -1; + toolTip.Hide(this); + Invalidate(); + } + + /// + protected override void OnMouseUp(MouseEventArgs e) + { + base.OnMouseUp(e); + if (e.Button == MouseButtons.Left) + ClickAt(e.Location); + } + + /// + protected override void Dispose(bool disposing) + { + if (disposing) + { + surface.Dispose(); + toolTip.Dispose(); + } + base.Dispose(disposing); + } + + /// The width of a text, each code point in the user interface font or the first font that has it. + private static float Measure(string text, SKFont font) + { + var width = 0f; + foreach (var (run, typeface) in Runs(text)) + { + font.Typeface = typeface; + width += font.MeasureText(run); + } + font.Typeface = UiTypeface; + return width; + } + + private static void Draw(SKCanvas canvas, string text, float x, float y, SKFont font, SKPaint paint) + { + foreach (var (run, typeface) in Runs(text)) + { + font.Typeface = typeface; + canvas.DrawText(run, x, y, font, paint); + x += font.MeasureText(run); + } + font.Typeface = UiTypeface; + } + + /// The text in runs of one typeface: the user interface font where it has the glyph, a fallback elsewhere. + private static IEnumerable<(string Run, SKTypeface Typeface)> Runs(string text) + { + var start = 0; + SKTypeface? current = null; + for (var i = 0; i < text.Length; i += char.IsSurrogatePair(text, i) ? 2 : 1) + { + var codePoint = char.ConvertToUtf32(text, i); + var typeface = UiTypeface.ContainsGlyph(codePoint) ? UiTypeface : SKFontManager.Default.MatchCharacter(codePoint) ?? UiTypeface; + if (current == null) + { + current = typeface; + } + else if (typeface.FamilyName != current.FamilyName) + { + yield return (text.Substring(start, i - start), current); + start = i; + current = typeface; + } + } + if (current != null) + yield return (text.Substring(start), current); + } + + private int IndexAt(Point point) + { + var scale = DpiScale; + var p = new PointF(point.X / scale, point.Y / scale); + return items.FindIndex(i => i.Bounds.Contains(p)); + } + } +} diff --git a/src/SharpEquations.WinForms/SharpEquations.WinForms.csproj b/src/SharpEquations.WinForms/SharpEquations.WinForms.csproj new file mode 100644 index 0000000..457db03 --- /dev/null +++ b/src/SharpEquations.WinForms/SharpEquations.WinForms.csproj @@ -0,0 +1,43 @@ + + + + + net10.0-windows;net481 + true + true + SharpEquations.WinForms + SharpEquations.WinForms + SharpEquations.WinForms + A real-time equation editor (MathEditBox) and viewer (MathView) for Windows Forms, drawn with SkiaSharp: UnicodeMath or LaTeX typed and built up as in Word, the equation read and written as MathML through SharpEquations. + equation math mathml editor winforms windows-forms skia unicodemath latex richeditbox + enable + true + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tests/SharpEquations.WinForms.Tests/EditBoxTests.cs b/tests/SharpEquations.WinForms.Tests/EditBoxTests.cs new file mode 100644 index 0000000..4909fdb --- /dev/null +++ b/tests/SharpEquations.WinForms.Tests/EditBoxTests.cs @@ -0,0 +1,325 @@ +namespace SharpEquations.WinForms.Tests +{ + using System.Linq; + using System.Threading.Tasks; + using System.Windows.Forms; + using SharpEquations.Editing; + using SharpEquations.Rendering; + using SkiaSharp; + + /// The editor of Windows Forms in a form: drawing, typing, keys, pointer, caret, floating bar, context menu. + [NotInParallel("ui")] + public class EditBoxTests + { + private static Equation U(string unicodeMath) => Equation.Parse(unicodeMath, EquationFormat.UnicodeMath, new EquationOptions { Display = true }); + + private static async Task Show(string? unicodeMath = null, bool focus = true) + { + var editor = new MathEditBox { FontSize = 28 }; + if (unicodeMath != null) + editor.Equation = U(unicodeMath); + await Ui.Show(editor); + if (focus) + { + editor.Focus(); + await Ui.Settle(); + } + return editor; + } + + /// The dark pixels Skia drew for the control, in its last paint. + internal static int DarkPixels(SKBitmap? pixels) + { + if (pixels == null) + return 0; + var count = 0; + for (var y = 0; y < pixels.Height; y++) + { + for (var x = 0; x < pixels.Width; x++) + { + var c = pixels.GetPixel(x, y); + if (c.Alpha > 200 && c.Red < 80 && c.Green < 80 && c.Blue < 80) + count++; + } + } + return count; + } + + [Test] + public async Task DrawsInk() + { + var (width, height, dark, empty) = await Ui.Run(async () => + { + var editor = await Show("x=(-b±√(b^2-4ac))/2a", focus: false); + editor.Refresh(); + var (w, h, ink) = (editor.Width, editor.Height, DarkPixels(editor.Surface.Pixels)); + var blank = await Show(focus: false); + blank.Refresh(); + return (w, h, ink, DarkPixels(blank.Surface.Pixels)); + }); + await Assert.That(width).IsGreaterThan(100); + await Assert.That(height).IsGreaterThan(60); + await Assert.That(dark).IsGreaterThan(200); + await Assert.That(empty).IsLessThan(dark / 4); + } + + [Test] + public async Task HeightFollowsTheEquation() + { + var (flat, tall) = await Ui.Run(async () => + { + var editor = await Show("x", focus: false); + var before = editor.Height; + editor.Equation = U("(a/b)/(c/d)"); + await Ui.Settle(); + return (before, editor.Height); + }); + await Assert.That(tall).IsGreaterThan(flat); + } + + [Test] + public async Task GlyphsArePathsOfTheirOutlines() + { + var (x, space) = await Ui.Run(() => + { + var font = MathFonts.Default; + font.TryGetGlyph('x', out var xGlyph); + font.TryGetGlyph(' ', out var spaceGlyph); + return (MathCanvas.Path(font, xGlyph)!.Bounds, MathCanvas.Path(font, spaceGlyph)); + }); + await Assert.That(x.Width).IsGreaterThan(100); + await Assert.That(x.Bottom).IsGreaterThan(300); + await Assert.That(space).IsNull(); + } + + [Test] + public async Task TypingBuildsUp() + { + var (equation, changed) = await Ui.Run(async () => + { + var editor = await Show(); + Equation? last = null; + editor.EquationChanged += (_, e) => last = e.Equation; + foreach (var ch in "a/b+x^2 ") + editor.Type(ch.ToString()); + await Ui.Settle(); + return (editor.Equation, last); + }); + await Assert.That(equation).IsEqualTo(U("a/b+x^2")); + await Assert.That(changed).IsEqualTo(equation); + } + + [Test] + public async Task ControlCharactersAreKeys() + { + var (backspace, text) = await Ui.Run(async () => + { + var editor = await Show(); + return (editor.Type("\b"), editor.Type("x")); + }); + await Assert.That(backspace).IsFalse(); + await Assert.That(text).IsTrue(); + } + + [Test] + public async Task KeysEditAndUndo() + { + var (deleted, undone, selected, linear) = await Ui.Run(async () => + { + var editor = await Show(); + editor.Type("x+y"); + editor.HandleKey(Keys.Back, MathKeyModifiers.None); + var afterDelete = editor.Equation; + editor.HandleKey(Keys.Z, MathKeyModifiers.Control); + var afterUndo = editor.Equation; + editor.HandleKey(Keys.Left, MathKeyModifiers.Shift); + var selection = editor.Editor.Selection != null; + editor.HandleKey(Keys.L, MathKeyModifiers.Control | MathKeyModifiers.Shift); + return (afterDelete, afterUndo, selection, editor.ViewMode); + }); + await Assert.That(deleted).IsEqualTo(U("x+")); + await Assert.That(undone).IsEqualTo(U("x+y")); + await Assert.That(selected).IsTrue(); + await Assert.That(linear).IsEqualTo(MathViewMode.Linear); + } + + [Test] + public async Task CaretOnlyWhenFocusedAndEditable() + { + var (unfocused, focused, readOnly) = await Ui.Run(async () => + { + var editor = await Show("a+b", focus: false); + var before = editor.View.IsFocused; + editor.Focus(); + await Ui.Settle(); + var after = editor.Focused && editor.View.IsFocused && editor.View.IsCaretVisible; + editor.IsReadOnly = true; + return (before, after, editor.View.IsReadOnly); + }); + await Assert.That(unfocused).IsFalse(); + await Assert.That(focused).IsTrue(); + await Assert.That(readOnly).IsTrue(); + } + + [Test] + public async Task QuickBarCompletesACommand() + { + var (open, items, focusKept, equation, closed) = await Ui.Run(async () => + { + var editor = await Show(); + editor.Type("x+\\al"); + await Ui.Settle(); + var wasOpen = editor.IsQuickBarOpen; + var count = editor.QuickBarWindow?.Count ?? 0; + var focus = editor.Focused; + var alpha = editor.View.QuickBar.Completions.ToList().FindIndex(c => c.Name == "alpha"); + for (var i = 0; i < alpha; i++) + editor.HandleKey(Keys.Down, MathKeyModifiers.None); + editor.HandleKey(Keys.Tab, MathKeyModifiers.None); + editor.Type(" "); + await Ui.Settle(); + return (wasOpen, count, focus, editor.Equation, !editor.IsQuickBarOpen); + }); + await Assert.That(open).IsTrue(); + await Assert.That(items).IsGreaterThan(1); + await Assert.That(focusKept).IsTrue(); + await Assert.That(equation).IsEqualTo(U("x+α")); + await Assert.That(closed).IsTrue(); + } + + [Test] + public async Task EscapeClosesTheCompletions() + { + var (open, closed) = await Ui.Run(async () => + { + var editor = await Show(); + editor.Type("\\su"); + await Ui.Settle(); + var wasOpen = editor.IsQuickBarOpen; + editor.HandleKey(Keys.Escape, MathKeyModifiers.None); + await Ui.Settle(); + return (wasOpen, !editor.IsQuickBarOpen); + }); + await Assert.That(open).IsTrue(); + await Assert.That(closed).IsTrue(); + } + + [Test] + public async Task StructuresForTheSelection() + { + var (open, items, equation) = await Ui.Run(async () => + { + var editor = await Show("a+b"); + editor.Editor.SelectAll(); + await Ui.Settle(); + var wasOpen = editor.IsQuickBarOpen; + var count = editor.QuickBarWindow?.Count ?? 0; + editor.View.QuickBar.GetItems(editor.QuickSymbols).First(i => i.Text == "√x").Invoke(); + await Ui.Settle(); + return (wasOpen, count, editor.Equation); + }); + await Assert.That(open).IsTrue(); + await Assert.That(items).IsEqualTo(10); + await Assert.That(equation).IsEqualTo(U("√(a+b)")); + } + + [Test] + public async Task PointerPutsTheCaret() + { + var (offset, focused) = await Ui.Run(async () => + { + var editor = await Show("a+b", focus: false); + editor.Editor.MoveHome(); + var start = editor.View.GetCaretRect()!.Value; + editor.Editor.MoveEnd(); + editor.PressAt(start.X, start.Y + start.Height / 2, false); + editor.View.PointerReleased(); + await Ui.Settle(); + return (editor.Editor.Caret.Offset, editor.View.IsFocused); + }); + await Assert.That(offset).IsEqualTo(0); + await Assert.That(focused).IsTrue(); + } + + [Test] + public async Task ContextMenuForTheState() + { + var (tags, readOnlyTags, undoKey, cancelled) = await Ui.Run(async () => + { + var editor = new MenuEditBox { FontSize = 28, Equation = U("a+b") }; + await Ui.Show(editor); + using var menu = editor.Menu(); + var all = menu.Items.Cast().Select(i => i.Tag as string).OfType().ToList(); + var undo = menu.Items.OfType().First(i => (string?)i.Tag == "undo").ShortcutKeyDisplayString; + editor.IsReadOnly = true; + using var readOnlyMenu = editor.Menu(); + var readOnly = readOnlyMenu.Items.Cast().Select(i => i.Tag as string).OfType().ToList(); + editor.MathContextMenuOpening += (_, e) => e.Cancel = true; + return (all, readOnly, undo, !editor.ShowContextMenu()); + }); + await Assert.That(tags).Contains("undo"); + await Assert.That(tags).Contains("copy-as"); + await Assert.That(tags).Contains("number"); + await Assert.That(readOnlyTags).IsEquivalentTo(new[] { "copy", "copy-as", "select-all" }); + await Assert.That(undoKey).IsEqualTo("Ctrl+Z"); + await Assert.That(cancelled).IsTrue(); + } + + [Test] + public async Task CopyPutsTextAndMathML() + { + var (text, mathML, pasted) = await Ui.Run(async () => + { + var editor = await Show("a/b"); + editor.Editor.SelectAll(); + editor.Copy(); + var data = Clipboard.GetDataObject()!; + var copiedText = Clipboard.GetText(); + var bytes = ((System.IO.MemoryStream)data.GetData(MathEditBox.MathMLClipboardFormat)!).ToArray(); + editor.Editor.SelectAll(); + editor.Editor.DeleteSelection(); + editor.Paste(); + return (copiedText, MathClipboard.Decode(bytes), editor.Equation); + }); + await Assert.That(Equation.Parse(text, EquationFormat.UnicodeMath)).IsEqualTo(Equation.Parse("a/b", EquationFormat.UnicodeMath)); + await Assert.That(mathML).Contains("mfrac"); + await Assert.That(pasted).IsEqualTo(U("a/b")); + } + + [Test] + public async Task MathMLInAndOut() + { + var (mathML, equation) = await Ui.Run(async () => + { + var editor = await Show(focus: false); + editor.SetMath("x"); + await Ui.Settle(); + return (editor.GetMath(), editor.Equation); + }); + await Assert.That(mathML).Contains("msqrt"); + await Assert.That(equation).IsEqualTo(Equation.Parse("√x", EquationFormat.UnicodeMath)); + } + + [Test] + public async Task ScreenReadersReadUnicodeMath() + { + var (role, value, set) = await Ui.Run(async () => + { + var editor = await Show("a/b", focus: false); + var accessible = editor.AccessibilityObject; + var before = accessible.Value; + accessible.Value = "x^2"; + return (accessible.Role, before, editor.Equation); + }); + await Assert.That(role).IsEqualTo(AccessibleRole.Text); + await Assert.That(Equation.Parse(value!, EquationFormat.UnicodeMath)).IsEqualTo(Equation.Parse("a/b", EquationFormat.UnicodeMath)); + await Assert.That(set).IsEqualTo(U("x^2")); + } + + /// The editor with its context menu at hand. + private sealed class MenuEditBox : MathEditBox + { + public ContextMenuStrip Menu() => CreateContextMenu(); + } + } +} diff --git a/tests/SharpEquations.WinForms.Tests/SharpEquations.WinForms.Tests.csproj b/tests/SharpEquations.WinForms.Tests/SharpEquations.WinForms.Tests.csproj new file mode 100644 index 0000000..5e1e305 --- /dev/null +++ b/tests/SharpEquations.WinForms.Tests/SharpEquations.WinForms.Tests.csproj @@ -0,0 +1,23 @@ + + + + + net10.0-windows + true + true + Exe + false + SharpEquations.WinForms.Tests + enable + + + + + + + + + + + diff --git a/tests/SharpEquations.WinForms.Tests/Ui.cs b/tests/SharpEquations.WinForms.Tests/Ui.cs new file mode 100644 index 0000000..f685dbe --- /dev/null +++ b/tests/SharpEquations.WinForms.Tests/Ui.cs @@ -0,0 +1,89 @@ +namespace SharpEquations.WinForms.Tests +{ + using System; + using System.Drawing; + using System.Threading; + using System.Threading.Tasks; + using System.Windows.Forms; + + /// The thread of the user interface of the tests (STA, with its message loop), and its form. + internal static class Ui + { + private static readonly Lazy
Thread = new Lazy(Start); + + private static Form Start() + { + var ready = new TaskCompletionSource(); + var thread = new System.Threading.Thread(() => + { + Application.SetHighDpiMode(HighDpiMode.PerMonitorV2); + Application.EnableVisualStyles(); + var form = new Form + { + Width = 640, + Height = 400, + Left = 40, + Top = 40, + StartPosition = FormStartPosition.Manual, + Text = "SharpEquations.WinForms.Tests", + BackColor = Color.White, + }; + form.Shown += (_, _) => ready.SetResult(form); + Application.Run(form); + }) + { + IsBackground = true, + Name = "UI", + }; + thread.SetApartmentState(ApartmentState.STA); + thread.Start(); + return ready.Task.GetAwaiter().GetResult(); + } + + /// Runs work on the thread of the user interface, and gives its result. + public static Task Run(Func> work) + { + var result = new TaskCompletionSource(); + Thread.Value.BeginInvoke(new Action(async () => + { + try + { + result.SetResult(await work().ConfigureAwait(true)); + } + catch (Exception e) + { + result.SetException(e); + } + })); + return result.Task; + } + + public static Task Run(Func work) => Run(() => Task.FromResult(work())); + + /// Shows a control alone in the form, and waits for it to be laid out and painted. + public static async Task Show(Control control) + { + var form = Thread.Value; + foreach (Control old in form.Controls) + old.Dispose(); + form.Controls.Clear(); + control.Location = new Point(20, 20); + if (control is MathEditBox) + control.Width = 560; + form.Controls.Add(control); + form.Activate(); + await Settle().ConfigureAwait(true); + } + + /// Lets the message loop run what is queued: a layout, a paint, the floating bar. + public static async Task Settle() + { + for (var i = 0; i < 3; i++) + { + Thread.Value.Refresh(); + await Task.Delay(20).ConfigureAwait(true); + Application.DoEvents(); + } + } + } +} diff --git a/tests/SharpEquations.WinForms.Tests/ViewTests.cs b/tests/SharpEquations.WinForms.Tests/ViewTests.cs new file mode 100644 index 0000000..d80bb22 --- /dev/null +++ b/tests/SharpEquations.WinForms.Tests/ViewTests.cs @@ -0,0 +1,45 @@ +namespace SharpEquations.WinForms.Tests +{ + using System.Linq; + using System.Threading.Tasks; + using SkiaSharp; + + /// The view of an equation, and the colours of MathML. + [NotInParallel("ui")] + public class ViewTests + { + [Test] + public async Task ShowsAnEquation() + { + var (width, height, glyphs, dark) = await Ui.Run(async () => + { + var view = new MathView { FontSize = 24, Equation = Equation.Parse("a/b", EquationFormat.UnicodeMath) }; + await Ui.Show(view); + view.Refresh(); + return (view.Width, view.Height, view.EquationLayout!.Glyphs.Count, EditBoxTests.DarkPixels(view.Surface.Pixels)); + }); + await Assert.That(width).IsGreaterThan(5); + await Assert.That(height).IsGreaterThan(20); + await Assert.That(glyphs).IsEqualTo(2); + await Assert.That(dark).IsGreaterThan(10); + } + + [Test] + public async Task ColorsOfMathColor() + { + var colors = new[] { "#f00", "#ff0000", "#ffff0000", "red", "nonsense" }.Select(MathCanvas.Parse).ToArray(); + await Assert.That(colors[0]).IsEqualTo(SKColors.Red); + await Assert.That(colors[1]).IsEqualTo(SKColors.Red); + await Assert.That(colors[2]).IsEqualTo(SKColors.Red); + await Assert.That(colors[3]).IsEqualTo(SKColors.Red); + await Assert.That(colors[4]).IsNull(); + } + + [Test] + public async Task EmbeddedFontHasAMathTable() + { + await Assert.That(MathFonts.Default.Math).IsNotNull(); + await Assert.That(MathFonts.Default.TryGetGlyph('∑', out _)).IsTrue(); + } + } +} From 68cf3df28b8d8cf699e7c8b60c11839c834b9f52 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 15:59:58 +0000 Subject: [PATCH 02/10] WinUI from SharpEquations.Uno; SkiaSharp 4 everywhere [no-new-version] SharpEquations.Uno targets WinUI 3 of the Windows App SDK as well (net10.0-windows10.0.19041): the same code, against Microsoft.WinUI. The target builds on every system, so that the package packed on Linux has it; the GlobalStaticResources of the XAML generator of Uno are in an API file of the Uno targets only. The demo runs on WinUI too (Windows only). SkiaSharp 4.156.0 and HarfBuzzSharp 14.4.0.100 are pinned for the whole repository, Avalonia included (it brought SkiaSharp 3), and for the native libraries that Uno.Sdk adds by itself. Windows Forms uses SKPathBuilder. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- AGENTS.md | 14 ++++++++---- Directory.Packages.props | 18 +++++++++++++++ README.md | 6 +++-- docs/EDITOR.md | 8 ++++++- .../Platforms/Windows/Program.cs | 22 +++++++++++++++++++ .../SharpEquations.Uno.Demo.csproj | 10 ++++++++- .../PublicAPI.Unshipped.txt | 5 ----- .../PublicAPI/Uno/PublicAPI.Shipped.txt | 1 + .../PublicAPI/Uno/PublicAPI.Unshipped.txt | 6 +++++ .../SharpEquations.Uno.csproj | 13 ++++++++--- src/SharpEquations.WinForms/MathCanvas.cs | 16 +++++++------- src/SharpEquations.WinForms/QuickBar.cs | 5 +++-- .../SharpEquations.WinForms.csproj | 3 +-- 13 files changed, 99 insertions(+), 28 deletions(-) create mode 100644 samples/SharpEquations.Uno.Demo/Platforms/Windows/Program.cs create mode 100644 src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Shipped.txt create mode 100644 src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Unshipped.txt diff --git a/AGENTS.md b/AGENTS.md index b1b4c8b..af7cd8a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -17,11 +17,11 @@ generated parser, on netstandard2.0): keep it so, and keep containers and other | `src/SharpEquations.Editing/` | The equation editor's model, no user interface: `MathNode` tree, caret, selection, undo, build up and build down | | `src/SharpEquations.Rendering/` | The layout of MathML Core over the OpenType MATH table, no user interface: `MathLayoutEngine`, `MathLayout`; the view of an editor without a toolkit (`MathEditorView`, drawn on an `IMathCanvas`), which the controls adapt | | `src/SharpEquations.Avalonia/` | The controls for Avalonia: `MathEditBox` (the editor), `MathView`; embeds Libertinus Math | -| `src/SharpEquations.Uno/` | The same controls for Uno Platform (`Uno.Sdk` of `global.json`), of the elements every renderer of Uno has: glyphs as paths from their outlines, shapes, a transparent `TextBox` for the input | +| `src/SharpEquations.Uno/` | The same controls for Uno Platform (`Uno.Sdk` of `global.json`) and for WinUI 3 (`net10.0-windows10.0.19041`, the same code against the Windows App SDK), of the elements every renderer of Uno has: glyphs as paths from their outlines, shapes, a transparent `TextBox` for the input | | `samples/SharpEquations.Avalonia.Demo/` | A window with the editor (`DemoView`, shared with the web demo) | | `src/SharpEquations.Wpf/` | The same controls for WPF (net10.0-windows, net481), drawn in `OnRender`: glyphs as geometries from their outlines; it builds on every system (`EnableWindowsTargeting`) | | `src/SharpEquations.WinForms/` | The same controls for Windows Forms (net10.0-windows, net481), drawn with SkiaSharp into a bitmap that the window shows (no GDI+ drawing): glyphs as paths from their outlines; it builds on every system | -| `samples/SharpEquations.Uno.Demo/` | A window with the editor of `SharpEquations.Uno`, on the desktop (Skia) | +| `samples/SharpEquations.Uno.Demo/` | A window with the editor of `SharpEquations.Uno`, on the desktop (Skia), and on WinUI 3 (Windows only) | | `samples/SharpEquations.Wpf.Demo/` | A window with the editor of `SharpEquations.Wpf` (Windows) | | `samples/SharpEquations.WinForms.Demo/` | A form with the editor of `SharpEquations.WinForms` (Windows) | | `samples/SharpEquations.Avalonia.Browser.Demo/` | The same demo on WebAssembly (needs the `wasm-tools` workload, so not in the solution; `.github/workflows/demo.yml` publishes it to GitHub Pages) | @@ -134,6 +134,9 @@ net10.0 with no package, as the core). of the real events call, and check the shapes drawn and the pixels (`RenderTargetBitmap`). Run them with `xvfb-run -a dotnet run --project tests/SharpEquations.Uno.Tests -f net10.0-desktop` on Linux; without a display the app stops at once ("No platform host could be selected"). The CI runs them on Linux. + The library targets WinUI 3 as well: the target of the Windows App SDK builds on every system + (`UnoDisableRemoveUnsupportedTargetFrameworks`), its public API is that of Uno without `GlobalStaticResources` + (`PublicAPI/Uno/`, the targets of Uno only); the demo builds for it on Windows only (`mt.exe`, `makepri.exe`). - `Wpf`: `MathEditBox` (a `Control` without a template) and `MathView` draw in `OnRender` through `MathCanvas` over the `DrawingContext`, each glyph a frozen `StreamGeometry` of its outline cached for each font; the font is Libertinus Math embedded, as for Uno, or a file (`MathFonts.FromFile`, a collection such as `cambria.ttc` too). The @@ -141,8 +144,7 @@ net10.0 with no package, as the core). clipboard methods are synchronous (`Copy`, `Cut`, `Paste`, `CopyAs`), as those of `TextBox`. `tests/SharpEquations.Wpf.Tests` shows the controls in a window of an STA thread of its own (`Ui.Run`), through the internal `Type`, `HandleKey` and `PressAt`; they run on Windows only, and the CI runs them there. -- `WinForms`: `MathEditBox` and `MathView` draw with SkiaSharp (the version of Avalonia, given in the project with - `VersionOverride` and not pinned for the repository, since Uno takes a newer one) through `MathCanvas` over an +- `WinForms`: `MathEditBox` and `MathView` draw with SkiaSharp through `MathCanvas` over an `SKCanvas`, each glyph an `SKPath` of its outline cached for each font, into the pixels of `MathSurface`, which `OnPaint` copies to the window: no GDI+ drawing. The selection and the equation are recorded in an `SKPicture`, drawn again under the caret as it blinks. Their coordinates are device-independent pixels, scaled by `DeviceDpi`. @@ -152,6 +154,10 @@ net10.0 with no package, as the core). - The core's `EquationCommands` (public) lists the control words of UnicodeMath and the commands of LaTeX with their symbols, for the completion of the editor; `PublicApi/EquationCommandsTests` checks that the parsers read them. +- SkiaSharp is version 4 everywhere, with its HarfBuzzSharp: `Directory.Packages.props` pins the whole family (Avalonia + 12 brings SkiaSharp 3; with transitive pinning it runs on 4) and sets `SkiaSharpVersion` and `HarfBuzzSharpVersion`, + which Uno.Sdk uses for the native libraries it adds to an app by itself. A new version changes all of them together. + ## Building and Testing ```bash diff --git a/Directory.Packages.props b/Directory.Packages.props index acbd295..6d9c582 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -2,6 +2,9 @@ true true + + 4.156.0 + 14.4.0.100 @@ -12,6 +15,21 @@ + + + + + + + + + + + + + + diff --git a/README.md b/README.md index d28e3ce..a84144a 100644 --- a/README.md +++ b/README.md @@ -85,8 +85,10 @@ the version of `SharpEquations`. `SharpEquations.Uno` has the same `MathEditBox` and `MathView` for Uno Platform, built only of the elements every renderer of Uno has: the glyphs of Libertinus Math (embedded) are drawn as paths from their outlines, the structures as shapes, and what is typed goes through a transparent `TextBox`, so that input methods and the keyboards of touch screens -work. `samples/SharpEquations.Uno.Demo` is a window with it on the desktop -(`dotnet run --project samples/SharpEquations.Uno.Demo`). +work. The same package targets WinUI 3 of the Windows App SDK (`net10.0-windows10.0.19041`), so a WinUI app on Windows +uses it as it is. `samples/SharpEquations.Uno.Demo` is a window with it on the desktop +(`dotnet run --project samples/SharpEquations.Uno.Demo`), and on Windows with WinUI too +(`dotnet run --project samples/SharpEquations.Uno.Demo -f net10.0-windows10.0.19041`). ```csharp var editor = new SharpEquations.Uno.MathEditBox { FontSize = 28, InputFormat = EquationFormat.LaTeX }; diff --git a/docs/EDITOR.md b/docs/EDITOR.md index 029ce06..0a47e6b 100644 --- a/docs/EDITOR.md +++ b/docs/EDITOR.md @@ -270,7 +270,13 @@ public class MathView : Control // read-only: Equati `MathEditBox` and `MathView` with the API of those of Avalonia, as far as WinUI allows (dependency properties; `Foreground`, `Background`, `BorderBrush`, `BorderThickness`, `Padding` and `FontSize` of `Control`; a `MenuFlyout` for the context menu; a `Popup` for the floating bar). They run wherever Uno runs, since they are built only of what -every renderer of Uno has, and the build fails on an API Uno does not implement (Uno0001): +every renderer of Uno has, and the build fails on an API Uno does not implement (Uno0001). Since they use only the API +of WinUI, the same code builds for WinUI 3 of the Windows App SDK (`net10.0-windows10.0.19041`, against +`Microsoft.WinUI`): the package has both, and the target of WinUI builds on every system (Uno.Sdk would leave it out +off Windows; `UnoDisableRemoveUnsupportedTargetFrameworks` keeps it, since a library needs none of the tools of Windows +that an app does). The class that the XAML generator of Uno adds to a library (`GlobalStaticResources`) exists on the +targets of Uno only, so its public API is in `PublicAPI/Uno/`. The demo runs on WinUI too, without a package and with +the Windows App SDK in it (its own `Main` in `Platforms/Windows`, since the app has no XAML); it builds on Windows only. - **Drawing**: `MathCanvas` turns the `IMathCanvas` of the view into the children of a `Canvas`: rectangles, lines and ellipses as shapes, each glyph as a `Path` from its outline (`OpenTypeMathFont.GetOutline`: the charstrings of CFF, diff --git a/samples/SharpEquations.Uno.Demo/Platforms/Windows/Program.cs b/samples/SharpEquations.Uno.Demo/Platforms/Windows/Program.cs new file mode 100644 index 0000000..ffab95b --- /dev/null +++ b/samples/SharpEquations.Uno.Demo/Platforms/Windows/Program.cs @@ -0,0 +1,22 @@ +namespace SharpEquations.Uno.Demo +{ + using System; + using Microsoft.UI.Dispatching; + using Microsoft.UI.Xaml; + + /// The entry point of the app on WinUI 3 of the Windows App SDK. + internal static class Program + { + [STAThread] + public static void Main(string[] args) + { + WinRT.ComWrappersSupport.InitializeComWrappers(); + Application.Start(parameters => + { + var context = new DispatcherQueueSynchronizationContext(DispatcherQueue.GetForCurrentThread()); + System.Threading.SynchronizationContext.SetSynchronizationContext(context); + _ = new App(); + }); + } + } +} diff --git a/samples/SharpEquations.Uno.Demo/SharpEquations.Uno.Demo.csproj b/samples/SharpEquations.Uno.Demo/SharpEquations.Uno.Demo.csproj index 054c345..d080bbc 100644 --- a/samples/SharpEquations.Uno.Demo/SharpEquations.Uno.Demo.csproj +++ b/samples/SharpEquations.Uno.Demo/SharpEquations.Uno.Demo.csproj @@ -3,7 +3,7 @@ - net10.0-desktop + net10.0-desktop;net10.0-windows10.0.19041 Exe true SharpEquations.Uno.Demo @@ -19,6 +19,14 @@ $(NoWarn);CA1016 + + + None + true + $(DefineConstants);DISABLE_XAML_GENERATED_MAIN + + diff --git a/src/SharpEquations.Uno/PublicAPI.Unshipped.txt b/src/SharpEquations.Uno/PublicAPI.Unshipped.txt index 178ad30..58a211a 100644 --- a/src/SharpEquations.Uno/PublicAPI.Unshipped.txt +++ b/src/SharpEquations.Uno/PublicAPI.Unshipped.txt @@ -2,8 +2,6 @@ SharpEquations.Uno.EquationChangedEventArgs SharpEquations.Uno.EquationChangedEventArgs.Equation.get -> SharpEquations.Equation? SharpEquations.Uno.EquationChangedEventArgs.EquationChangedEventArgs(SharpEquations.Equation? equation) -> void -SharpEquations.Uno.GlobalStaticResources -SharpEquations.Uno.GlobalStaticResources.GlobalStaticResources() -> void SharpEquations.Uno.MathContextMenuEventArgs SharpEquations.Uno.MathContextMenuEventArgs.Cancel.get -> bool SharpEquations.Uno.MathContextMenuEventArgs.Cancel.set -> void @@ -69,9 +67,6 @@ SharpEquations.Uno.MathViewMode.Professional = 0 -> SharpEquations.Uno.MathViewM override SharpEquations.Uno.MathEditBox.ArrangeOverride(Windows.Foundation.Size finalSize) -> Windows.Foundation.Size override SharpEquations.Uno.MathEditBox.MeasureOverride(Windows.Foundation.Size availableSize) -> Windows.Foundation.Size override SharpEquations.Uno.MathView.MeasureOverride(Windows.Foundation.Size availableSize) -> Windows.Foundation.Size -static SharpEquations.Uno.GlobalStaticResources.Initialize() -> void -static SharpEquations.Uno.GlobalStaticResources.RegisterDefaultStyles() -> void -static SharpEquations.Uno.GlobalStaticResources.RegisterResourceDictionariesBySource() -> void static SharpEquations.Uno.MathFonts.Default.get -> SharpEquations.Rendering.OpenTypeMathFont! static SharpEquations.Uno.MathFonts.FromFile(byte[]! data) -> SharpEquations.Rendering.OpenTypeMathFont! static SharpEquations.Uno.MathFonts.LibertinusMath.get -> SharpEquations.Rendering.OpenTypeMathFont! diff --git a/src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Shipped.txt b/src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Shipped.txt new file mode 100644 index 0000000..7dc5c58 --- /dev/null +++ b/src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Shipped.txt @@ -0,0 +1 @@ +#nullable enable diff --git a/src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Unshipped.txt b/src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Unshipped.txt new file mode 100644 index 0000000..eb14895 --- /dev/null +++ b/src/SharpEquations.Uno/PublicAPI/Uno/PublicAPI.Unshipped.txt @@ -0,0 +1,6 @@ +#nullable enable +SharpEquations.Uno.GlobalStaticResources +SharpEquations.Uno.GlobalStaticResources.GlobalStaticResources() -> void +static SharpEquations.Uno.GlobalStaticResources.Initialize() -> void +static SharpEquations.Uno.GlobalStaticResources.RegisterDefaultStyles() -> void +static SharpEquations.Uno.GlobalStaticResources.RegisterResourceDictionariesBySource() -> void diff --git a/src/SharpEquations.Uno/SharpEquations.Uno.csproj b/src/SharpEquations.Uno/SharpEquations.Uno.csproj index 24bcb1f..f2476d4 100644 --- a/src/SharpEquations.Uno/SharpEquations.Uno.csproj +++ b/src/SharpEquations.Uno/SharpEquations.Uno.csproj @@ -1,12 +1,17 @@ - + License, embedded) drawn as paths from their outlines. The same code builds for Uno (net10.0) and for WinUI 3 of + the Windows App SDK (net10.0-windows10.0.19041), which Uno.Sdk builds on Windows only. --> - net10.0 + net10.0;net10.0-windows10.0.19041 Library false + + true + true SharpEquations.Uno SharpEquations.Uno SharpEquations.Uno @@ -26,6 +31,8 @@ + + diff --git a/src/SharpEquations.WinForms/MathCanvas.cs b/src/SharpEquations.WinForms/MathCanvas.cs index d48a4e5..1db16f1 100644 --- a/src/SharpEquations.WinForms/MathCanvas.cs +++ b/src/SharpEquations.WinForms/MathCanvas.cs @@ -128,7 +128,7 @@ public void DrawGlyphs(MathLayout layout, double x, double y) { if (outline.Count == 0) return null; - var path = new SKPath { FillType = SKPathFillType.Winding }; + using var builder = new SKPathBuilder { FillType = SKPathFillType.Winding }; var open = false; foreach (var command in outline) { @@ -136,24 +136,24 @@ public void DrawGlyphs(MathLayout layout, double x, double y) { case MathPathCommandKind.MoveTo: if (open) - path.Close(); - path.MoveTo((float)command.X, (float)command.Y); + builder.Close(); + builder.MoveTo((float)command.X, (float)command.Y); open = true; break; case MathPathCommandKind.LineTo: - path.LineTo((float)command.X, (float)command.Y); + builder.LineTo((float)command.X, (float)command.Y); break; case MathPathCommandKind.QuadraticTo: - path.QuadTo((float)command.X1, (float)command.Y1, (float)command.X, (float)command.Y); + builder.QuadTo((float)command.X1, (float)command.Y1, (float)command.X, (float)command.Y); break; case MathPathCommandKind.CubicTo: - path.CubicTo((float)command.X1, (float)command.Y1, (float)command.X2, (float)command.Y2, (float)command.X, (float)command.Y); + builder.CubicTo((float)command.X1, (float)command.Y1, (float)command.X2, (float)command.Y2, (float)command.X, (float)command.Y); break; } } if (open) - path.Close(); - return path; + builder.Close(); + return builder.Detach(); } private static SKColor? ParseColor(string text) diff --git a/src/SharpEquations.WinForms/QuickBar.cs b/src/SharpEquations.WinForms/QuickBar.cs index 65e9cba..e616da4 100644 --- a/src/SharpEquations.WinForms/QuickBar.cs +++ b/src/SharpEquations.WinForms/QuickBar.cs @@ -23,6 +23,7 @@ internal sealed class QuickBar : Form private static readonly SKColor HighlightColor = new SKColor(0x33, 0x99, 0xFF, 0x40); private static readonly SKColor HoverColor = new SKColor(0x80, 0x80, 0x80, 0x30); private static readonly SKTypeface UiTypeface = SKTypeface.FromFamilyName("Segoe UI") ?? SKTypeface.Default; + private static readonly SKFont UiFont = new SKFont(UiTypeface); private readonly MathSurface surface = new MathSurface(); private readonly ToolTip toolTip = new ToolTip(); private readonly List<(MathQuickBarItem Item, RectangleF Bounds)> items = new List<(MathQuickBarItem, RectangleF)>(); @@ -227,7 +228,7 @@ private static void Draw(SKCanvas canvas, string text, float x, float y, SKFont foreach (var (run, typeface) in Runs(text)) { font.Typeface = typeface; - canvas.DrawText(run, x, y, font, paint); + canvas.DrawText(run, x, y, SKTextAlign.Left, font, paint); x += font.MeasureText(run); } font.Typeface = UiTypeface; @@ -241,7 +242,7 @@ private static void Draw(SKCanvas canvas, string text, float x, float y, SKFont for (var i = 0; i < text.Length; i += char.IsSurrogatePair(text, i) ? 2 : 1) { var codePoint = char.ConvertToUtf32(text, i); - var typeface = UiTypeface.ContainsGlyph(codePoint) ? UiTypeface : SKFontManager.Default.MatchCharacter(codePoint) ?? UiTypeface; + var typeface = UiFont.GetGlyph(codePoint) != 0 ? UiTypeface : SKFontManager.Default.MatchCharacter(codePoint) ?? UiTypeface; if (current == null) { current = typeface; diff --git a/src/SharpEquations.WinForms/SharpEquations.WinForms.csproj b/src/SharpEquations.WinForms/SharpEquations.WinForms.csproj index 457db03..353e454 100644 --- a/src/SharpEquations.WinForms/SharpEquations.WinForms.csproj +++ b/src/SharpEquations.WinForms/SharpEquations.WinForms.csproj @@ -29,8 +29,7 @@ - - + From 79fe8d052f91cbc61ba343190a504fe8854704bf Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:31:03 +0000 Subject: [PATCH 03/10] WinForms: the editor makes its view before the padding lays it out [no-new-version] Setting Padding in the constructor of MathEditBox laid out the equation through OnPaddingChanged before View was made, and every editor failed with a NullReferenceException. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- src/SharpEquations.WinForms/MathEditBox.cs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/SharpEquations.WinForms/MathEditBox.cs b/src/SharpEquations.WinForms/MathEditBox.cs index 12a6b8d..d598d44 100644 --- a/src/SharpEquations.WinForms/MathEditBox.cs +++ b/src/SharpEquations.WinForms/MathEditBox.cs @@ -53,15 +53,7 @@ public class MathEditBox : Control /// An empty editor. public MathEditBox() { - SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.Opaque | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); - SetStyle(ControlStyles.StandardDoubleClick, false); - TabStop = true; - Cursor = Cursors.IBeam; - BackColor = SystemColors.Window; - ForeColor = SystemColors.WindowText; - Padding = new Padding(6, 4, 6, 4); - base.AutoSize = true; - + // the model and the view first: setting the padding and the colours below lays out and draws again Editor = new MathEditor { IsDisplay = true }; Editor.ContentChanged += OnEditorContentChanged; View = new MathEditorView(Editor); @@ -74,6 +66,15 @@ public MathEditBox() View.BlinkCaret(); InvalidateCaret(); }; + + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.Opaque | ControlStyles.ResizeRedraw | ControlStyles.Selectable, true); + SetStyle(ControlStyles.StandardDoubleClick, false); + TabStop = true; + Cursor = Cursors.IBeam; + BackColor = SystemColors.Window; + ForeColor = SystemColors.WindowText; + Padding = new Padding(6, 4, 6, 4); + base.AutoSize = true; Size = new Size(200, 40); } From 7479b0471bfc426b6f0c70927c562d08520227e7 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:38:02 +0000 Subject: [PATCH 04/10] Editing: the other limit typed after one built by a space goes to the same n-ary operator [no-new-version] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ∑^2, a space, then _2 gave the subscript of the whole sum, 〖∑^2〗_2 (the same for ∫, and for x^2 then _3), which no UnicodeMath reads: the second script began a run of its own whose base was the built structure. A _ or ^ typed just after a structure that has only the other script now takes the structure back as linear text into its run, so that both build up together, as when they are typed in one go. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- src/SharpEquations.Editing/MathEditor.cs | 36 +++++++++++++++++++ .../Controls/MathEditBoxTests.cs | 16 +++++++++ .../Editing/BuildUpTests.cs | 28 +++++++++++++++ 3 files changed, 80 insertions(+) diff --git a/src/SharpEquations.Editing/MathEditor.cs b/src/SharpEquations.Editing/MathEditor.cs index 7c08eee..bb28a6c 100644 --- a/src/SharpEquations.Editing/MathEditor.cs +++ b/src/SharpEquations.Editing/MathEditor.cs @@ -233,7 +233,10 @@ public void Insert(string text) deferredAt = null; InsertRune(rune); if (!IsLinear) + { + ReopenScriptBase(rune); built |= TypedAtCaret(rune, resumes); + } } typingAt = built ? null : Caret; OnChanged(true); @@ -955,6 +958,39 @@ private void InsertRune(Rune rune) } } + /// + /// A script typed just after a structure that has only the other script (_ after ∑^2 or + /// x^2 built up by a space, ^ after ∫_0) goes to the same base, as if both had been typed + /// together: the structure goes back to its linear text, in the run of the script, which builds up again with it. + /// + private void ReopenScriptBase(Rune rune) + { + var caret = Caret; + if (rune.Value is not ('_' or '^') || caret.Offset != 1 || caret.Path.Count == 0 + || MathTree.Get(Root, caret.Path) is not { IsRun: true } run) + return; + var j = caret.Path[caret.Path.Count - 1]; + var rowPath = MathTree.Parent(caret.Path); + var row = MathTree.Get(Root, rowPath); + if (j == 0) + return; + var lacksScript = row.Children[j - 1].Name switch + { + "msup" or "mover" => rune.Value == '_', + "msub" or "munder" => rune.Value == '^', + _ => false, + }; + if (!lacksScript || BuildUp.ToEquation(new[] { row.Children[j - 1] }, IsDisplay) is not { } equation) + return; + + var linear = BuildUp.ToLinear(equation, InputFormat); + var children = row.Children.ToList(); + children[j] = MathNode.Run(linear + run.Text); + children.RemoveAt(j - 1); + Root = MathTree.Replace(Root, rowPath, row.WithChildren(children)); + Caret = Anchor = new MathPosition(MathTree.Append(rowPath, j - 1), CodePointText.Length(linear) + 1); + } + /// /// Corrects and builds up what the character just typed ends: the autocorrect first, then the build up of a /// trigger, as one edit with the autocorrect, so that an undo gives back what was typed. A trigger that starts a diff --git a/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs b/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs index 6829546..b9c7c03 100644 --- a/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs +++ b/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs @@ -45,6 +45,22 @@ public async Task TypingBuildsUp() await Assert.That(events).IsGreaterThan(0); } + /// The limits of a sum and of an integral, each ended by a space, one key at a time as a keyboard types them. + [Test] + [Arguments("∑^2 _2 ", "∑_2^2")] + [Arguments("\\int^1 _0 ", "∫_0^1")] + [Arguments("x^2+b+\\int^1 _1 ", "x^2+b+∫_1^1")] + public async Task LimitsOfAnNaryOperator(string typed, string expected) + { + var equation = await Headless.Run(() => WithEditor((window, editor) => + { + foreach (var rune in typed.EnumerateRunes()) + window.KeyTextInput(rune.ToString()); + return editor.Equation; + })); + await Assert.That(equation).IsEqualTo(Display(expected)); + } + [Test] public async Task LaTeXInput() { diff --git a/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs b/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs index f52e08f..5eb0ac4 100644 --- a/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs +++ b/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs @@ -46,6 +46,34 @@ public async Task LaTeX(string typed, string expected) await Assert.That(editor.ToEquation()).IsEqualTo(Equation.Parse(expected, EquationFormat.UnicodeMath)); } + /// + /// The other script typed after a script built up by a space goes to the same base, as if both were typed + /// together: the lower limit of an n-ary operator whose upper limit is built, not a script of the whole. + /// + [Test] + [Arguments("∑^2 _2 ", "∑_2^2")] + [Arguments("∑_1 ^n ", "∑_1^n")] + [Arguments("∫^1 _0 ", "∫_0^1")] + [Arguments("\\int^1 _0 ", "∫_0^1")] + [Arguments("\\sum ^2 _2 ", "∑_2^2")] + [Arguments("x^2 _3 ", "x_3^2")] + [Arguments("x_3 ^2 ", "x_3^2")] + public async Task OtherScriptAfterABuiltScript(string typed, string expected) + { + var editor = Type(typed); + await Assert.That(editor.Root.Children[0].Children.Any(c => c.IsRun)).IsFalse().Because(Built(editor)); + await Assert.That(editor.ToEquation()).IsEqualTo(Equation.Parse(expected, EquationFormat.UnicodeMath)); + } + + [Test] + [Arguments("\\sum^2 _2 ", "\\sum_2^2")] + [Arguments("\\int_0 ^1 ", "\\int_0^1")] + public async Task OtherScriptAfterABuiltScriptInLaTeX(string typed, string expected) + { + var editor = Type(typed, EquationFormat.LaTeX); + await Assert.That(editor.ToEquation()).IsEqualTo(Equation.Parse(expected, EquationFormat.LaTeX)); + } + [Test] public async Task ArgumentStillToComeDoesNotBuildUp() { From 6f31e17f3a2c32fce867addd7fe211d34e165bce Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:50:18 +0000 Subject: [PATCH 05/10] WinForms: draw again what is laid out, also when the parent measured the editor first [no-new-version] The picture of the equation was recorded again only when the view asked for a measure. A parent with a layout of its own (the FlowLayoutPanel of the demo, whose labels change at each key) measured the editor before its view heard of the edit, so the view asked only for the caret: the caret moved, and the text typed was not drawn until it built up. The picture is now recorded again whenever the layout it was made of is not that of the view. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- src/SharpEquations.WinForms/MathEditBox.cs | 15 +++++++-- .../EditBoxTests.cs | 33 +++++++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/src/SharpEquations.WinForms/MathEditBox.cs b/src/SharpEquations.WinForms/MathEditBox.cs index d598d44..20842ae 100644 --- a/src/SharpEquations.WinForms/MathEditBox.cs +++ b/src/SharpEquations.WinForms/MathEditBox.cs @@ -31,6 +31,7 @@ public class MathEditBox : Control private Form? quickBarOwner; private MathAutoCorrect autoCorrect; private SKPicture? content; + private MathLayout? recorded; private ContextMenuStrip? openMenu; private char pendingHighSurrogate; private bool updatingEquation; @@ -552,7 +553,14 @@ protected override void OnPaint(PaintEventArgs e) var half = (float)thickness / 2; canvas.DrawRect(half, half, Math.Max(0, ClientSize.Width / scale - (float)thickness), Math.Max(0, ClientSize.Height / scale - (float)thickness), pen); } - canvas.DrawPicture(content ??= RecordContent()); + // the layout can change without a change of the view (a measure of the parent's layout): draw what is laid out + if (content == null || !ReferenceEquals(recorded, View.Layout)) + { + content?.Dispose(); + content = RecordContent(); + recorded = View.Layout; + } + canvas.DrawPicture(content); using var caret = new MathCanvas(canvas, new MathColors(Foreground, caret: caretColor.IsEmpty ? Foreground : MathCanvas.ToSkia(caretColor))); View.RenderCaret(caret); } @@ -830,7 +838,10 @@ private MathSize Measure(int width) View.FontSize = FontSize; View.Padding = new MathThickness(Padding.Left / scale, Padding.Top / scale, Padding.Right / scale, Padding.Bottom / scale); View.BorderThickness = borderWidth; - return View.Measure(width > 0 ? width / (double)scale : double.PositiveInfinity); + var size = View.Measure(width > 0 ? width / (double)scale : double.PositiveInfinity); + if (!ReferenceEquals(recorded, View.Layout)) + Invalidate(); + return size; } /// Lays out the equation again, and gives the control the height it takes. diff --git a/tests/SharpEquations.WinForms.Tests/EditBoxTests.cs b/tests/SharpEquations.WinForms.Tests/EditBoxTests.cs index 4909fdb..46a68dd 100644 --- a/tests/SharpEquations.WinForms.Tests/EditBoxTests.cs +++ b/tests/SharpEquations.WinForms.Tests/EditBoxTests.cs @@ -63,6 +63,39 @@ public async Task DrawsInk() await Assert.That(empty).IsLessThan(dark / 4); } + /// + /// Text not built up yet is drawn as it is typed, also when the layout of the parent measures the editor again + /// before its view hears of the edit (a label that shows the equation, as in the demo). + /// + [Test] + public async Task TypedTextIsDrawnBeforeItBuildsUp() + { + var (before, after) = await Ui.Run(async () => + { + var editor = new MathEditBox { FontSize = 28, Width = 560 }; + var label = new Label { AutoSize = true }; + editor.EquationChanged += (_, e) => label.Text = e.Equation?.ToString(EquationFormat.UnicodeMath) ?? string.Empty; + var panel = new FlowLayoutPanel { FlowDirection = FlowDirection.TopDown, WrapContents = false, Width = 600, Height = 300 }; + panel.Controls.Add(editor); + panel.Controls.Add(label); + await Ui.Show(panel); + editor.Focus(); + foreach (var ch in "x^2 ") + editor.Type(ch.ToString()); + await Ui.Settle(); + editor.Refresh(); + var ink = DarkPixels(editor.Surface.Pixels); + foreach (var ch in "aaaa") + { + editor.Type(ch.ToString()); + await Ui.Settle(); + } + editor.Refresh(); + return (ink, DarkPixels(editor.Surface.Pixels)); + }); + await Assert.That(after).IsGreaterThan(before + 100); + } + [Test] public async Task HeightFollowsTheEquation() { From bf06e170f4ded7e67316edbed4b377dca8e9601d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:50:18 +0000 Subject: [PATCH 06/10] Rendering: the limits of a large operator at its top and its bottom [no-new-version] The scripts of an msubsup whose base is a token took no account of the height and the depth of the base, as for a letter (TeX, rule 18a): the lower limit of an integral in display, which is made larger and centred on the axis, was halfway down it. A large operator is a box of its own (TeX, rule 13): its scripts drop from its top and its bottom. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- src/SharpEquations.Rendering/Layout/Engine.cs | 5 ++-- .../Rendering/LayoutTests.cs | 25 +++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/SharpEquations.Rendering/Layout/Engine.cs b/src/SharpEquations.Rendering/Layout/Engine.cs index 71d6e97..9741044 100644 --- a/src/SharpEquations.Rendering/Layout/Engine.cs +++ b/src/SharpEquations.Rendering/Layout/Engine.cs @@ -1157,7 +1157,8 @@ private Box AttachScripts(Box baseBox, List<(Box? Sub, Box? Sup)> post, List<(Bo if (sub != null) subShift = Math.Max(subShift, sub.Height - C(MathConstant.SubscriptTopMax, style)); } - if (!baseBox.IsToken) + // a large operator is a box of its own, made larger and centred on the axis, not a character (TeX, rule 13) + if (!baseBox.IsToken || baseBox.IsLargeOp) subShift = Math.Max(subShift, baseBox.Depth + C(MathConstant.SubscriptBaselineDropMin, style)); } if (hasSup) @@ -1168,7 +1169,7 @@ private Box AttachScripts(Box baseBox, List<(Box? Sub, Box? Sup)> post, List<(Bo if (sup != null) supShift = Math.Max(supShift, sup.Depth + C(MathConstant.SuperscriptBottomMin, style)); } - if (!baseBox.IsToken) + if (!baseBox.IsToken || baseBox.IsLargeOp) supShift = Math.Max(supShift, baseBox.Height - C(MathConstant.SuperscriptBaselineDropMax, style)); } if (hasSub && hasSup) diff --git a/tests/SharpEquations.Avalonia.Tests/Rendering/LayoutTests.cs b/tests/SharpEquations.Avalonia.Tests/Rendering/LayoutTests.cs index c346320..9b1c718 100644 --- a/tests/SharpEquations.Avalonia.Tests/Rendering/LayoutTests.cs +++ b/tests/SharpEquations.Avalonia.Tests/Rendering/LayoutTests.cs @@ -48,6 +48,31 @@ public async Task CorpusLaysOut() await Assert.That(failures).IsEmpty(); } + /// + /// The limits of an integral in display, a large operator, go to its top and its bottom (TeX, rule 13), not to + /// the place of the scripts of a letter: the lower limit is not halfway down the integral. + /// + [Test] + public async Task LimitsOfALargeIntegralAtItsEnds() + { + var (integral, letter, height) = await Headless.Run(() => + { + double Spread(string unicodeMath, out double operatorHeight) + { + var layout = MathLayoutEngine.Layout(Equation.Parse(unicodeMath, EquationFormat.UnicodeMath, new EquationOptions { Display = true }), MathFonts.Default, Options); + var size = layout.Glyphs.Max(g => g.Size); + var scripts = layout.Glyphs.Where(g => g.Size < size).ToList(); + operatorHeight = layout.Height; + return scripts.Max(g => g.Y) - scripts.Min(g => g.Y); + } + + var i = Spread("∫_0^1", out var h); + return (i, Spread("x_0^1", out _), h); + }); + await Assert.That(integral).IsGreaterThan(letter * 1.5); + await Assert.That(integral).IsGreaterThan(height * 0.5); + } + [Test] public async Task FractionIsTallerThanItsParts() { From 69ec9666739492055bced87345672377d73fab32 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 17:51:58 +0000 Subject: [PATCH 07/10] Uno demo: WinUI 3 finds the types of XamlControlsResources [no-new-version] On WinUI 3 the app without App.xaml had no XAML metadata provider, which the XAML compiler writes for one: XamlControlsResources could not resolve its own types and failed with 'Cannot find a resource with the given key: AcrylicBackgroundFillColorDefaultBrush'. The App hands WinUI the metadata provider of the controls on Windows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- samples/SharpEquations.Uno.Demo/App.cs | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/samples/SharpEquations.Uno.Demo/App.cs b/samples/SharpEquations.Uno.Demo/App.cs index dda5ef5..9022e29 100644 --- a/samples/SharpEquations.Uno.Demo/App.cs +++ b/samples/SharpEquations.Uno.Demo/App.cs @@ -7,9 +7,28 @@ namespace SharpEquations.Uno.Demo /// A window with the editor, the equation as MathML, UnicodeMath and LaTeX, and a view of it. public sealed class App : Application +#if WINDOWS + , Microsoft.UI.Xaml.Markup.IXamlMetadataProvider +#endif { +#if WINDOWS + // WinUI 3 finds the types of XamlControlsResources through the metadata provider of the app, which the XAML + // compiler writes for an App.xaml: this app has none, so it hands the one of the controls to WinUI itself + private readonly Microsoft.UI.Xaml.XamlTypeInfo.XamlControlsXamlMetaDataProvider provider = new(); +#endif private Window? window; +#if WINDOWS + /// + public Microsoft.UI.Xaml.Markup.IXamlType GetXamlType(System.Type type) => provider.GetXamlType(type); + + /// + public Microsoft.UI.Xaml.Markup.IXamlType GetXamlType(string fullName) => provider.GetXamlType(fullName); + + /// + public Microsoft.UI.Xaml.Markup.XmlnsDefinition[] GetXmlnsDefinitions() => provider.GetXmlnsDefinitions(); +#endif + protected override void OnLaunched(LaunchActivatedEventArgs args) { Resources.MergedDictionaries.Add(new XamlControlsResources()); From 5cb7bd1216f33f1a4f752cb2275f791da6a2a1de Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:07:37 +0000 Subject: [PATCH 08/10] Editing: an n-ary operator built up before its operand takes the limits of its kind [no-new-version] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ∑_(i=1)^n typed and built up by a space, before its operand, was read by UnicodeMath as an operator with scripts: the limits went at its right, and the LaTeX wrote \sum\nolimits, while the same equation built down and up again had them under and over it. The run is read again with an empty operand, and the operator takes the limits it has there: under and over a sum in display, at the right of an integral. A limit over or under it, reopened when the other limit is typed, goes back to the text it was typed as (∑^2, not ∑┴2). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- src/SharpEquations.Editing/BuildUp.cs | 28 +++++++++++++++++++ src/SharpEquations.Editing/MathEditor.cs | 7 ++++- .../Controls/MathEditBoxTests.cs | 14 ++++++---- .../Editing/BuildUpTests.cs | 25 +++++++++++++++++ 4 files changed, 68 insertions(+), 6 deletions(-) diff --git a/src/SharpEquations.Editing/BuildUp.cs b/src/SharpEquations.Editing/BuildUp.cs index a1ec447..ca4ed8c 100644 --- a/src/SharpEquations.Editing/BuildUp.cs +++ b/src/SharpEquations.Editing/BuildUp.cs @@ -232,6 +232,8 @@ public static bool IsBalanced(string text, EquationFormat format) return null; var elements = equation.ToMathML().Elements().ToList(); + if (!line && format == EquationFormat.UnicodeMath) + elements = NaryWithItsLimits(elements, source, display); if (line) { if (elements.Count != 1 || elements[0].Elements().ToList() is not { Count: 1 } rows || rows[0].Elements().ToList() is not { Count: 1 } cells) @@ -251,6 +253,32 @@ public static bool IsBalanced(string text, EquationFormat format) return used.All(u => u) ? nodes : null; } + /// + /// An n-ary operator built up with its limits before its operand is typed (∑_(i=1)^n): UnicodeMath reads it + /// as an operator with scripts, while the same operator with an operand takes the limits of its kind (under and + /// over a sum in display, at the right of an integral). The text is read again with an empty operand, and the + /// operator takes the limits it has there, as when the whole equation is built up. + /// + private static List NaryWithItsLimits(List elements, string source, bool display) + { + if (elements.Count == 0 || elements[elements.Count - 1] is not { } last + || last.Name.LocalName is not ("msub" or "msup" or "msubsup") || last.Elements().FirstOrDefault()?.Name.LocalName != "mo") + return elements; + if (!Equation.TryParse(source + "▒〖〗", EquationFormat.UnicodeMath, new EquationOptions { Display = display }, out var withOperand) || withOperand == null) + return elements; + + // the operator and its empty operand, alone or in a row of their own + var others = withOperand.ToMathML().Elements().ToList(); + if (others.Count > 0 && others[others.Count - 1] is { } row && row.Name.LocalName == "mrow" && row.Elements().Count() == 2) + others = others.Take(others.Count - 1).Concat(row.Elements()).ToList(); + if (others.Count != elements.Count + 1 || others[others.Count - 2] is not { } nary + || nary.Name.LocalName is not ("munder" or "mover" or "munderover")) + return elements; + var result = elements.Take(elements.Count - 1).ToList(); + result.Add(nary); + return result; + } + /// /// Where the nodes a run at an index of a row builds up with start: after the opening fence when the row is a pair /// of fences and the run is between them, since the opening fence alone does not always parse (|x). diff --git a/src/SharpEquations.Editing/MathEditor.cs b/src/SharpEquations.Editing/MathEditor.cs index bb28a6c..925d06b 100644 --- a/src/SharpEquations.Editing/MathEditor.cs +++ b/src/SharpEquations.Editing/MathEditor.cs @@ -980,7 +980,12 @@ private void ReopenScriptBase(Rune rune) "msub" or "munder" => rune.Value == '^', _ => false, }; - if (!lacksScript || BuildUp.ToEquation(new[] { row.Children[j - 1] }, IsDisplay) is not { } equation) + // the limit over or under an n-ary operator goes back to the text it was typed as (∑^2, not ∑┴2) + var structure = row.Children[j - 1]; + if (structure.Name is "mover" or "munder" && structure.Children[0] is { } nary + && (nary.Name == "mo" || nary.IsRow && nary.Children.Count == 1 && nary.Children[0].Name == "mo")) + structure = MathNode.Element(structure.Name == "mover" ? "msup" : "msub", structure.Children, structure.Attributes); + if (!lacksScript || BuildUp.ToEquation(new[] { structure }, IsDisplay) is not { } equation) return; var linear = BuildUp.ToLinear(equation, InputFormat); diff --git a/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs b/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs index b9c7c03..9dba303 100644 --- a/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs +++ b/tests/SharpEquations.Avalonia.Tests/Controls/MathEditBoxTests.cs @@ -45,11 +45,14 @@ public async Task TypingBuildsUp() await Assert.That(events).IsGreaterThan(0); } - /// The limits of a sum and of an integral, each ended by a space, one key at a time as a keyboard types them. + /// + /// The limits of a sum and of an integral, each ended by a space, one key at a time as a keyboard types them: under + /// and over the sum in display, at the right of the integral. + /// [Test] - [Arguments("∑^2 _2 ", "∑_2^2")] - [Arguments("\\int^1 _0 ", "∫_0^1")] - [Arguments("x^2+b+\\int^1 _1 ", "x^2+b+∫_1^1")] + [Arguments("∑^2 _2 ", "\\sum_2^2")] + [Arguments("\\int^1 _0 ", "\\int_0^1")] + [Arguments("x^2+b+\\int^1 _1 ", "x^2+b+\\int_1^1")] public async Task LimitsOfAnNaryOperator(string typed, string expected) { var equation = await Headless.Run(() => WithEditor((window, editor) => @@ -58,7 +61,8 @@ public async Task LimitsOfAnNaryOperator(string typed, string expected) window.KeyTextInput(rune.ToString()); return editor.Equation; })); - await Assert.That(equation).IsEqualTo(Display(expected)); + // the expected equation in LaTeX, which reads the limits of a sum alone under and over it, as with an operand + await Assert.That(equation).IsEqualTo(Equation.Parse(expected, EquationFormat.LaTeX, new EquationOptions { Display = true })); } [Test] diff --git a/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs b/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs index 5eb0ac4..afb1b86 100644 --- a/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs +++ b/tests/SharpEquations.Avalonia.Tests/Editing/BuildUpTests.cs @@ -74,6 +74,31 @@ public async Task OtherScriptAfterABuiltScriptInLaTeX(string typed, string expec await Assert.That(editor.ToEquation()).IsEqualTo(Equation.Parse(expected, EquationFormat.LaTeX)); } + /// + /// An n-ary operator built up with its limits before its operand is typed takes the limits the operator has with + /// an operand: under and over a sum in display, at the right of an integral, as the whole text built up again. + /// + [Test] + [Arguments("\\sum_(i=1)^n i^2 ")] + [Arguments("∑_(i=1)^n i^2 ")] + [Arguments("∏_k a_k ")] + [Arguments("∑^2 x ")] + [Arguments("a+∑_k k ")] + [Arguments("∫_0^1 x dx ")] + [Arguments("∯_S f ")] + public async Task NaryLimitsAsWhenBuiltUpWhole(string typed) + { + static string Limits(MathEditor editor) => editor.ToMathML().Descendants() + .First(e => e.Name.LocalName is "msub" or "msup" or "msubsup" or "munder" or "mover" or "munderover").Name.LocalName; + + var editor = new MathEditor { IsDisplay = true }; + editor.Insert(typed); + var built = Limits(editor); + editor.BuildDown(); + editor.BuildUpAll(); + await Assert.That(built).IsEqualTo(Limits(editor)); + } + [Test] public async Task ArgumentStillToComeDoesNotBuildUp() { From 63a34a10e64eb03ebd07e9f1e2dc85fe960b9de5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:07:37 +0000 Subject: [PATCH 09/10] WPF: the floating bar in the font of the system, not in the size of the equation [no-new-version] The popup of the bar inherited the font size of the editor (28 in the demo), and its buttons were much larger than the rest of the user interface. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- src/SharpEquations.Wpf/MathEditBox.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/SharpEquations.Wpf/MathEditBox.cs b/src/SharpEquations.Wpf/MathEditBox.cs index 7572b80..841dfe4 100644 --- a/src/SharpEquations.Wpf/MathEditBox.cs +++ b/src/SharpEquations.Wpf/MathEditBox.cs @@ -7,6 +7,7 @@ namespace SharpEquations.Wpf using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Controls.Primitives; + using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Threading; @@ -131,6 +132,11 @@ public MathEditBox() }, }; + // the bar is the user interface, not the equation: the font of the system, not the size of the editor's, which + // the popup would inherit from it + quickBar.SetValue(TextElement.FontSizeProperty, SystemFonts.MessageFontSize); + quickBar.SetValue(TextElement.FontFamilyProperty, SystemFonts.MessageFontFamily); + blink = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher) { Interval = MathEditorView.CaretBlinkInterval }; blink.Tick += (_, _) => { From 92db6b5c3f7c435da5a8f20ff5bc10569faed49d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 14 Nov 2026 22:07:37 +0000 Subject: [PATCH 10/10] Uno demo: the white page in the light theme on WinUI [no-new-version] With the dark theme of Windows, WinUI wrote the text of the demo, the equation included, white on its white page: nothing typed could be seen. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01SyVioB8cEKzWWZ7KQGzLfe --- samples/SharpEquations.Uno.Demo/App.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/samples/SharpEquations.Uno.Demo/App.cs b/samples/SharpEquations.Uno.Demo/App.cs index 9022e29..bc5fcfd 100644 --- a/samples/SharpEquations.Uno.Demo/App.cs +++ b/samples/SharpEquations.Uno.Demo/App.cs @@ -51,7 +51,8 @@ protected override void OnLaunched(LaunchActivatedEventArgs args) panel.Children.Add(view); if (System.Environment.GetEnvironmentVariable("SHARPEQUATIONS_DEMO_EQUATION") is { Length: > 0 } initial) editor.Equation = Equation.Parse(initial, EquationFormat.UnicodeMath, new EquationOptions { Display = true }); - window = new Window { Content = new Grid { Background = new SolidColorBrush(Microsoft.UI.Colors.White), Children = { panel } } }; + // a white page in the light theme: with the dark theme of the system, WinUI would write the text white on it + window = new Window { Content = new Grid { Background = new SolidColorBrush(Microsoft.UI.Colors.White), RequestedTheme = ElementTheme.Light, Children = { panel } } }; window.Activate(); editor.Loaded += (_, _) => editor.FocusEditor(); }