diff --git a/AGENTS.md b/AGENTS.md
index af7cd8a..badb5ce 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,7 +25,7 @@ generated parser, on netstandard2.0): keep it so, and keep containers and other
| `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.Avalonia.MathTools.Demo/` | A second app, math tools around the editor, in MVVM: the view models (`ViewModels/`: `MathToolsViewModel` and one for each page, over a small `ObservableObject` and `RelayCommand`, no package; the tests drive them) and the views in AXAML with compiled bindings (`Views/`: `MathToolsView`, with the brushes, the styles and the `Card` of the pages, 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) |
| `samples/SharpEquations.MathTools.Graphing/` | The graphs of the math tools without a user interface: the region shown (`Viewport`), the marks of the axes, the points of a curve (`Sampler`: closer where it bends, broken at asymptotes and steps) and where a relation of x and y holds (`Contours`); in space, the meshes and curves in a cube (`Scene3D`), the camera turning around it (`OrbitCamera`) and the painter's algorithm that draws them without a graphics card (`Painter3D`) |
| `samples/SharpEquations.Avalonia.Browser.MathTools.Demo/` | The math tools on WebAssembly (as the web demo, not in the solution build; `demo.yml` publishes them under `math/`) |
diff --git a/docs/EDITOR.md b/docs/EDITOR.md
index 0808fd8..92f5d8e 100644
--- a/docs/EDITOR.md
+++ b/docs/EDITOR.md
@@ -280,7 +280,7 @@ of WinUI, the same code builds for WinUI 3 of the Windows App SDK (`net10.0-wind
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.
+the Windows App SDK in it; 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.Avalonia.Browser.MathTools.Demo/SharpEquations.Avalonia.Browser.MathTools.Demo.csproj b/samples/SharpEquations.Avalonia.Browser.MathTools.Demo/SharpEquations.Avalonia.Browser.MathTools.Demo.csproj
index 5c8d0af..9e778cf 100644
--- a/samples/SharpEquations.Avalonia.Browser.MathTools.Demo/SharpEquations.Avalonia.Browser.MathTools.Demo.csproj
+++ b/samples/SharpEquations.Avalonia.Browser.MathTools.Demo/SharpEquations.Avalonia.Browser.MathTools.Demo.csproj
@@ -13,13 +13,15 @@
true
true
false
+ true
true
-
-
+
+
+
diff --git a/samples/SharpEquations.Avalonia.Demo/App.axaml b/samples/SharpEquations.Avalonia.Demo/App.axaml
new file mode 100644
index 0000000..881249d
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.Demo/App.axaml
@@ -0,0 +1,5 @@
+
diff --git a/samples/SharpEquations.Avalonia.Demo/App.axaml.cs b/samples/SharpEquations.Avalonia.Demo/App.axaml.cs
new file mode 100644
index 0000000..16cf89d
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.Demo/App.axaml.cs
@@ -0,0 +1,23 @@
+namespace SharpEquations.Avalonia.Demo
+{
+ using global::Avalonia;
+ using global::Avalonia.Controls.ApplicationLifetimes;
+ using global::Avalonia.Markup.Xaml;
+
+ /// The app of the desktop demo: the theme the WebAssembly demo has too, and .
+ public sealed partial class App : Application
+ {
+ public override void Initialize()
+ {
+ AvaloniaXamlLoader.Load(this);
+ DemoTheme.Apply(this);
+ }
+
+ public override void OnFrameworkInitializationCompleted()
+ {
+ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
+ desktop.MainWindow = new MainWindow();
+ base.OnFrameworkInitializationCompleted();
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.Demo/MainWindow.axaml b/samples/SharpEquations.Avalonia.Demo/MainWindow.axaml
new file mode 100644
index 0000000..2af273d
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.Demo/MainWindow.axaml
@@ -0,0 +1,9 @@
+
+
+
diff --git a/samples/SharpEquations.Avalonia.Demo/MainWindow.axaml.cs b/samples/SharpEquations.Avalonia.Demo/MainWindow.axaml.cs
new file mode 100644
index 0000000..9858e0b
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.Demo/MainWindow.axaml.cs
@@ -0,0 +1,10 @@
+namespace SharpEquations.Avalonia.Demo
+{
+ using global::Avalonia.Controls;
+
+ /// The window of the desktop demo: the view the WebAssembly demo shows too.
+ public sealed partial class MainWindow : Window
+ {
+ public MainWindow() => InitializeComponent();
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.Demo/MainWindow.cs b/samples/SharpEquations.Avalonia.Demo/MainWindow.cs
deleted file mode 100644
index 83211e2..0000000
--- a/samples/SharpEquations.Avalonia.Demo/MainWindow.cs
+++ /dev/null
@@ -1,16 +0,0 @@
-namespace SharpEquations.Avalonia.Demo
-{
- using global::Avalonia.Controls;
-
- /// The window of the desktop demo: the view the WebAssembly demo shows too.
- public sealed class MainWindow : Window
- {
- public MainWindow()
- {
- Title = "SharpEquations — equation editor";
- Width = 1240;
- Height = 900;
- Content = new DemoView();
- }
- }
-}
diff --git a/samples/SharpEquations.Avalonia.Demo/Program.cs b/samples/SharpEquations.Avalonia.Demo/Program.cs
index 748386a..41b61b6 100644
--- a/samples/SharpEquations.Avalonia.Demo/Program.cs
+++ b/samples/SharpEquations.Avalonia.Demo/Program.cs
@@ -2,7 +2,6 @@ namespace SharpEquations.Avalonia.Demo
{
using System;
using global::Avalonia;
- using global::Avalonia.Controls.ApplicationLifetimes;
public static class Program
{
@@ -11,16 +10,4 @@ public static class Program
public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure().UsePlatformDetect();
}
-
- public sealed class App : Application
- {
- public override void Initialize() => DemoTheme.Apply(this);
-
- public override void OnFrameworkInitializationCompleted()
- {
- if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- desktop.MainWindow = new MainWindow();
- base.OnFrameworkInitializationCompleted();
- }
- }
}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/AlgebraPanel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/AlgebraPanel.cs
deleted file mode 100644
index de916a3..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/AlgebraPanel.cs
+++ /dev/null
@@ -1,375 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Input;
- using global::Avalonia.Layout;
- using global::Avalonia.Threading;
- using SharpEquations;
- using SharpEquations.MathTools;
- using SharpEquations.Rendering;
-
- ///
- /// What the calculator computes from the equation of the editor, with a computer algebra system ( ):
- /// its value as it is typed, and on a click its solutions, its simplified, expanded or factored form, its derivative
- /// and its integral, each result drawn and ready to go back to the editor.
- ///
- public sealed class AlgebraPanel : UserControl
- {
- private static readonly TimeSpan Delay = TimeSpan.FromMilliseconds(300);
- private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
-
- private static readonly (CasAction Action, string Face, string Tip)[] Buttons =
- {
- (CasAction.Solve, "Solve", "The solutions of the equation, or where the expression is 0"),
- (CasAction.Simplify, "Simplify", "The expression in a simpler form"),
- (CasAction.Expand, "Expand", "Products and powers multiplied out"),
- (CasAction.Factor, "Factor", "The expression as a product"),
- (CasAction.Differentiate, "d/dx", "The derivative by the letter chosen"),
- (CasAction.Integrate, "∫ dx", "An antiderivative by the letter chosen"),
- (CasAction.Define, "Define", "Gives the letter before ≔ its value, for what is computed next: a≔5 (type a:=5)"),
- };
-
- private readonly MathEditBox editor;
- private readonly ICasEngine engine;
- private readonly MathView answer = new MathView { FontSize = 26, HorizontalAlignment = HorizontalAlignment.Left };
- private readonly TextBlock answerNote = Ui.Muted("", 12.5);
- private readonly StackPanel results = new StackPanel { Spacing = 12 };
- private readonly WrapPanel definitions = new WrapPanel { ItemSpacing = 14, LineSpacing = 6, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(10, 0, 0, 0) };
- private readonly DockPanel definitionsRow;
- private readonly DispatcherTimer timer;
- private int version;
-
- public AlgebraPanel(MathEditBox editor, ICasEngine engine)
- {
- this.editor = editor;
- this.engine = engine;
- Letter = new ComboBox { MinWidth = 70 };
- timer = new DispatcherTimer { Interval = Delay };
- timer.Tick += async (_, _) =>
- {
- timer.Stop();
- await RefreshAnswer().ConfigureAwait(true);
- };
- editor.EquationChanged += (_, _) =>
- {
- timer.Stop();
- timer.Start();
- };
-
- var buttons = new List();
- foreach (var (action, face, tip) in Buttons)
- {
- var button = new Button { Content = face, CornerRadius = new CornerRadius(8), Padding = new Thickness(12, 5) };
- ToolTip.SetTip(button, tip);
- button.Click += async (_, _) => await RunAsync(action).ConfigureAwait(true);
- buttons.Add(button);
- }
- var graph = new Button { Content = "Graph", CornerRadius = new CornerRadius(8), Padding = new Thickness(12, 5) };
- ToolTip.SetTip(graph, "Draws the equation on the page of the graphs");
- graph.Click += (_, _) => RequestGraph();
- buttons.Add(graph);
- var forLabel = Ui.Muted("by", 12.5);
- buttons.Add(forLabel);
- buttons.Add(Letter);
- Angles = new ComboBox { ItemsSource = new[] { "Radians", "Degrees" }, SelectedIndex = engine.Angles == AngleUnit.Degrees ? 1 : 0, MinWidth = 110 };
- ToolTip.SetTip(Angles, "The unit of the angles of sin, cos, tan and their inverses");
- Angles.SelectionChanged += async (_, _) =>
- {
- engine.Angles = Angles.SelectedIndex == 1 ? AngleUnit.Degrees : AngleUnit.Radians;
- await RefreshAnswer().ConfigureAwait(true);
- };
- buttons.Add(Angles);
-
- var forget = new Button { Content = "Forget", CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 3) };
- ToolTip.SetTip(forget, "Forgets the letters defined");
- forget.Click += async (_, _) =>
- {
- engine.ClearDefinitions();
- ShowDefinitions();
- await RefreshAnswer().ConfigureAwait(true);
- };
- definitionsRow = new DockPanel { Children = { Ui.Docked(forget, Dock.Right), Ui.Docked(Ui.Muted("Defined:", 12.5), Dock.Left), definitions } };
-
- var answerFrame = new Border
- {
- CornerRadius = new CornerRadius(12),
- Padding = new Thickness(18, 12),
- MinHeight = 60,
- Child = new StackPanel { Spacing = 4, Children = { answer, answerNote } },
- };
- answerFrame.Bind(Border.BackgroundProperty, answerFrame.GetResourceObservable("CodeBrush"));
- answerFrame.ContextMenu = new ContextMenu();
- answerFrame.ContextMenu.Opening += (_, e) =>
- {
- if (Answer == null)
- {
- e.Cancel = true;
- return;
- }
- answerFrame.ContextMenu.ItemsSource = MenuItems(Answer);
- };
-
- Content = new StackPanel { Spacing = 14, Children = { answerFrame, Ui.Row(buttons.ToArray()), definitionsRow, results } };
- ShowDefinitions();
- ShowAnswer(null, "The value of what is typed shows here.");
- }
-
- /// Raised by the Graph button, with the equation of the editor to draw.
- public event EventHandler? GraphRequested;
-
- /// Sends the equation of the editor to be drawn, as the Graph button does; false when it cannot be read.
- public bool RequestGraph()
- {
- if (!TryRead(out var equation, out _, out var error))
- {
- AddMessage(error!);
- return false;
- }
- GraphRequested?.Invoke(this, equation!);
- return true;
- }
-
- /// The letter to solve for, and to differentiate and integrate by.
- public ComboBox Letter { get; }
-
- /// The computer algebra system, with the letters defined.
- public ICasEngine Engine => engine;
-
- /// The unit of the angles: radians or degrees.
- public ComboBox Angles { get; }
-
- /// The value of the equation of the editor, as it was last computed.
- public CasResult? Answer { get; private set; }
-
- /// The results of the actions, the last first.
- public IReadOnlyList Results => history;
-
- private readonly List history = new List();
-
- /// Computes the value of the equation of the editor now, as typing does after a pause.
- public async Task RefreshAnswer()
- {
- timer.Stop();
- var current = ++version;
- if (!TryRead(out var equation, out var letters, out var error))
- {
- UpdateLetters(Array.Empty());
- ShowAnswer(null, error);
- return;
- }
- UpdateLetters(letters);
- var (result, message) = await Compute(CasAction.Evaluate, equation!, null).ConfigureAwait(true);
- if (current == version)
- ShowAnswer(result, message);
- }
-
- /// Does an action to the equation of the editor, as its button does, and adds the result to the list.
- public async Task RunAsync(CasAction action)
- {
- if (!TryRead(out var equation, out _, out var error))
- {
- AddMessage(error!);
- return null;
- }
- var letter = Letter.SelectedItem as string;
- var (result, message) = await Compute(action, equation!, letter).ConfigureAwait(true);
- if (result == null)
- {
- AddMessage(message!);
- return null;
- }
- if (action == CasAction.Define)
- {
- ShowDefinitions();
- await RefreshAnswer().ConfigureAwait(true);
- }
- history.Insert(0, result);
- results.Children.Insert(0, ResultCard(result, Label(action, letter ?? "x")));
- while (results.Children.Count > 8)
- results.Children.RemoveAt(results.Children.Count - 1);
- return result;
- }
-
- private bool TryRead(out Equation? equation, out IReadOnlyList letters, out string? error)
- {
- letters = Array.Empty();
- error = null;
- equation = editor.Equation;
- if (equation == null)
- {
- error = "The value of what is typed shows here.";
- return false;
- }
- if (equation.ToMathML().Descendants().Any(e => e.Name.LocalName == "merror"))
- {
- error = "Not built up yet: finish the argument, or press Build up (Enter).";
- return false;
- }
- try
- {
- letters = engine.Variables(equation);
- return true;
- }
- catch (NotSupportedException e)
- {
- error = e.Message;
- return false;
- }
- }
-
- // on another thread, since the engine can take long (it cannot be stopped: a result too late is dropped)
- private async Task<(CasResult? Result, string? Message)> Compute(CasAction action, Equation equation, string? letter)
- {
- var work = Task.Run(() => engine.Run(action, equation, letter));
- if (await Task.WhenAny(work, Task.Delay(Timeout)).ConfigureAwait(true) != work)
- return (null, "It takes too long: " + engine.Name + " found no result in " + Timeout.TotalSeconds + " seconds.");
- try
- {
- return (await work.ConfigureAwait(true), null);
- }
-#pragma warning disable CA1031 // what the engine cannot do, it says with exceptions of many kinds
- catch (Exception e)
-#pragma warning restore CA1031
- {
- return (null, engine.Name + " cannot do it: " + e.Message);
- }
- }
-
- private void UpdateLetters(IReadOnlyList letters)
- {
- var selected = Letter.SelectedItem as string;
- if (Letter.ItemsSource is IReadOnlyList old && old.SequenceEqual(letters))
- return;
- Letter.ItemsSource = letters;
- Letter.SelectedItem = selected != null && letters.Contains(selected) ? selected : letters.Count > 0 ? letters[0] : null;
- }
-
- private void ShowAnswer(CasResult? result, string? message)
- {
- Answer = result;
- answer.Equation = result?.Math;
- answer.IsVisible = result?.Math != null;
- answerNote.Text = result == null ? message : result.Math == null ? result.Text : null;
- answerNote.IsVisible = !string.IsNullOrEmpty(answerNote.Text);
- }
-
- // the letters defined, as a definition each: a ≔ 3
- private void ShowDefinitions()
- {
- definitions.Children.Clear();
- foreach (var (name, value) in engine.Definitions.OrderBy(d => d.Key, StringComparer.Ordinal))
- {
- var text = name + "≔" + value.ToString(EquationFormat.UnicodeMath);
- definitions.Children.Add(Equation.TryParse(text, EquationFormat.UnicodeMath, out var equation)
- ? new MathView { FontSize = 17, Equation = equation }
- : Ui.Muted(text, 13));
- }
- definitionsRow.IsVisible = definitions.Children.Count > 0;
- }
-
- private void AddMessage(string message)
- {
- results.Children.Insert(0, Ui.Muted(message, 13));
- while (results.Children.Count > 8)
- results.Children.RemoveAt(results.Children.Count - 1);
- }
-
- private Border ResultCard(CasResult result, string label)
- {
- Control math = result.Math != null
- ? new MathView { FontSize = 22, Equation = result.Math, HorizontalAlignment = HorizontalAlignment.Left }
- : new SelectableTextBlock { Text = result.Text, FontSize = 14, TextWrapping = global::Avalonia.Media.TextWrapping.Wrap };
- var body = new StackPanel { Spacing = 6, Children = { math } };
- if (result.ApproximateText != null)
- {
- body.Children.Add(result.Approximate != null
- ? new MathView { FontSize = 18, Equation = result.Approximate, HorizontalAlignment = HorizontalAlignment.Left }
- : new SelectableTextBlock { Text = result.ApproximateText, FontSize = 14, TextWrapping = global::Avalonia.Media.TextWrapping.Wrap });
- }
-
- var copy = new Button { Content = "Copy", CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 3) };
- ToolTip.SetTip(copy, "Copy the result, as text and as MathML (right-click for more)");
- copy.Click += async (_, _) => await CopyAsync(result.Math, result.Text, null).ConfigureAwait(true);
- var use = new Button { Content = "To the editor", CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 3), IsEnabled = result.Math != null };
- use.Click += (_, _) => ToEditor(result.Math);
- var top = new DockPanel { Children = { Ui.Docked(use, Dock.Right), Ui.Docked(copy, Dock.Right), Ui.Small(label) } };
- copy.Margin = new Thickness(0, 0, 6, 0);
- var card = new Border
- {
- CornerRadius = new CornerRadius(12),
- Padding = new Thickness(16, 10),
- Child = new StackPanel { Spacing = 8, Children = { top, body } },
- ContextMenu = new ContextMenu { ItemsSource = MenuItems(result) },
- };
- card.Bind(Border.BackgroundProperty, card.GetResourceObservable("CodeBrush"));
- return card;
- }
-
- // the right-click menu of a result: copy it as text, LaTeX or MathML, its decimal values, or put it in the editor
- private List MenuItems(CasResult result)
- {
- var items = new List
- {
- Item("Copy", () => CopyAsync(result.Math, result.Text, null)),
- Item("Copy as LaTeX", () => CopyAsync(result.Math, result.Text, EquationFormat.LaTeX), result.Math != null),
- Item("Copy as MathML", () => CopyAsync(result.Math, result.Text, EquationFormat.MathML), result.Math != null),
- };
- if (result.ApproximateText != null)
- items.Add(Item("Copy decimal values", () => CopyAsync(result.Approximate, result.ApproximateText, null)));
- items.Add(Item("To the editor", () => { ToEditor(result.Math); return Task.CompletedTask; }, result.Math != null));
- if (result.Approximate != null)
- items.Add(Item("Decimal values to the editor", () => { ToEditor(result.Approximate); return Task.CompletedTask; }));
- items.Add(Item("Paste into the editor", PasteAsync));
- return items;
- }
-
- private static MenuItem Item(string header, Func action, bool enabled = true)
- {
- var item = new MenuItem { Header = header, IsEnabled = enabled };
- item.Click += async (_, _) => await action().ConfigureAwait(true);
- return item;
- }
-
- private void ToEditor(Equation? math)
- {
- if (math == null)
- return;
- editor.Equation = math;
- editor.Focus();
- }
-
- private async Task PasteAsync()
- {
- editor.Focus();
- await editor.PasteAsync().ConfigureAwait(true);
- }
-
- // the result on the clipboard: as text (UnicodeMath, or the format asked) and as MathML for Word and the editor
- private async Task CopyAsync(Equation? math, string text, EquationFormat? format)
- {
- if (TopLevel.GetTopLevel(this)?.Clipboard is not { } clipboard)
- return;
- var item = new DataTransferItem();
- item.SetText(math == null ? text : math.ToString(format ?? EquationFormat.UnicodeMath));
- if (math != null)
- item.Set(MathEditBox.MathMLClipboardFormat, MathClipboard.Encode(math.ToString(EquationFormat.MathML)));
- var data = new DataTransfer();
- data.Add(item);
- await clipboard.SetDataAsync(data).ConfigureAwait(true);
- }
-
- private static string Label(CasAction action, string letter) => action switch
- {
- CasAction.Solve => "Solve for " + letter,
- CasAction.Differentiate => "Derivative by " + letter,
- CasAction.Integrate => "Antiderivative by " + letter,
- CasAction.Define => "Defined",
- _ => action.ToString(),
- };
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/App.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/App.axaml
new file mode 100644
index 0000000..d3f027c
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/App.axaml
@@ -0,0 +1,5 @@
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/App.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/App.axaml.cs
new file mode 100644
index 0000000..aea3af1
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/App.axaml.cs
@@ -0,0 +1,24 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using global::Avalonia;
+ using global::Avalonia.Controls.ApplicationLifetimes;
+ using global::Avalonia.Markup.Xaml;
+ using SharpEquations.MathTools;
+
+ /// The desktop app: the theme the WebAssembly page has too, and with its settings in a file.
+ public sealed partial class App : Application
+ {
+ public override void Initialize()
+ {
+ AvaloniaXamlLoader.Load(this);
+ MathToolsTheme.Apply(this);
+ }
+
+ public override void OnFrameworkInitializationCompleted()
+ {
+ if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
+ desktop.MainWindow = new MainWindow(new FileSettingsStore(FileSettingsStore.DefaultPath));
+ base.OnFrameworkInitializationCompleted();
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/CalculatorPage.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/CalculatorPage.cs
deleted file mode 100644
index 7cd6a38..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/CalculatorPage.cs
+++ /dev/null
@@ -1,156 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System.Collections.Generic;
- using System.Linq;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Controls.Primitives;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The scientific keypad: the keys type into the equation editor, which the keyboard types into too; what the
- /// equation means is computed as it is typed, and the equation is shown as UnicodeMath and LaTeX.
- ///
- public sealed class CalculatorPage : UserControl
- {
- private readonly TextBox unicodeMath = Code();
- private readonly TextBox latex = Code();
-
- public CalculatorPage(ICasEngine engine)
- {
- Editor = new MathEditBox
- {
- FontSize = 34,
- MinHeight = 110,
- Padding = new Thickness(22, 18),
- BorderThickness = 0,
- };
- Editor.Bind(MathEditBox.BackgroundProperty, Editor.GetResourceObservable("EditorBrush"));
- Editor.EquationChanged += (_, _) => Refresh();
-
- var frame = new Border
- {
- CornerRadius = new CornerRadius(12),
- BorderThickness = new Thickness(1.5),
- ClipToBounds = true,
- Child = Editor,
- };
- frame.Bind(Border.BorderBrushProperty, frame.GetResourceObservable("EditorBorderBrush"));
-
- var keypad = new WrapPanel
- {
- Orientation = Orientation.Horizontal,
- ItemSpacing = 18,
- LineSpacing = 12,
- Children =
- {
- Keys(CalculatorKeys.Functions, 6, "KeyBrush"),
- Keys(CalculatorKeys.Numbers, 5, "DigitBrush"),
- },
- };
- var editing = new WrapPanel { Orientation = Orientation.Horizontal, ItemSpacing = 8, LineSpacing = 8 };
- foreach (var key in CalculatorKeys.Editing)
- editing.Children.Add(Key(key, "KeyBrush"));
-
- Solver = new AlgebraPanel(Editor, engine);
-
- var formats = new Grid
- {
- ColumnDefinitions = new ColumnDefinitions("*,16,*"),
- Children = { Labelled("UnicodeMath", unicodeMath, 0), Labelled("LaTeX", latex, 2) },
- };
-
- Content = new StackPanel
- {
- Spacing = 20,
- Children =
- {
- Ui.Card("Calculator", "The keys type into the editor as the keyboard does: sin( waits for its argument, x² squares what is before the caret, a/b and √ take the selection", new StackPanel
- {
- Spacing = 16,
- Children = { frame, keypad, editing },
- }),
- Ui.Card("Compute", "With " + engine.Name + ": the value of what is typed, and its solutions, simpler forms, derivative and antiderivative", Solver),
- Ui.Card("As text", "The equation in the linear formats, as it is typed", formats),
- },
- };
- }
-
- /// The equation editor the keys type into.
- public MathEditBox Editor { get; }
-
- /// What is computed from the equation of the editor.
- public AlgebraPanel Solver { get; }
-
- /// Presses a key, as a click on it does.
- public void Press(CalculatorKey key)
- {
- key.Press(Editor.Editor);
- Editor.Focus();
- }
-
- private UniformGrid Keys(IReadOnlyList keys, int columns, string brush)
- {
- var grid = new UniformGrid { Columns = columns, ColumnSpacing = 6, RowSpacing = 6 };
- foreach (var key in keys)
- grid.Children.Add(Key(key, brush));
- return grid;
- }
-
- private Button Key(CalculatorKey key, string brush)
- {
- var button = new Button
- {
- MinWidth = 58,
- MinHeight = 46,
- Padding = new Thickness(8, 4),
- CornerRadius = new CornerRadius(10),
- BorderThickness = new Thickness(1),
- Focusable = false,
- HorizontalAlignment = HorizontalAlignment.Stretch,
- VerticalAlignment = VerticalAlignment.Stretch,
- HorizontalContentAlignment = HorizontalAlignment.Center,
- VerticalContentAlignment = VerticalAlignment.Center,
- Content = key.IsMath
- ? Ui.Math(key.Face, 18)
- : new TextBlock { Text = key.Face, FontSize = 15 },
- };
- button.Bind(Button.BackgroundProperty, button.GetResourceObservable(brush));
- button.Bind(Button.BorderBrushProperty, button.GetResourceObservable("CardBorderBrush"));
- ToolTip.SetTip(button, key.Tip);
- button.Click += (_, _) => Press(key);
- return button;
- }
-
- private void Refresh()
- {
- // text that is not built up yet (sin( waiting for its argument) is an merror of the equation
- var equation = Editor.Equation;
- var complete = equation != null && !equation.ToMathML().Descendants().Any(e => e.Name.LocalName == "merror");
- unicodeMath.Text = complete ? equation!.ToString(EquationFormat.UnicodeMath) : null;
- latex.Text = complete ? equation!.ToString(EquationFormat.LaTeX) : null;
- }
-
- private static StackPanel Labelled(string label, Control control, int column)
- {
- var panel = new StackPanel { Spacing = 6, Children = { Ui.Muted(label), control } };
- Grid.SetColumn(panel, column);
- return panel;
- }
-
- private static TextBox Code() => new TextBox
- {
- IsReadOnly = true,
- TextWrapping = TextWrapping.Wrap,
- FontFamily = new FontFamily("Cascadia Mono,Consolas,Menlo,DejaVu Sans Mono,monospace"),
- FontSize = 13,
- MinHeight = 44,
- Padding = new Thickness(12, 10),
- CornerRadius = new CornerRadius(10),
- PlaceholderText = "Not built up yet: finish the argument, or press Build up (Enter)",
- };
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/FormulasPage.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/FormulasPage.cs
deleted file mode 100644
index 4322b0e..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/FormulasPage.cs
+++ /dev/null
@@ -1,146 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Controls.Primitives;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The library of formulas: each one drawn by a , filtered by subject and by name, and opened in
- /// the calculator with a click; the ones with a graph drawn on the page of the graphs with their button.
- ///
- public sealed class FormulasPage : UserControl
- {
- private static readonly EquationOptions Display = new EquationOptions { Display = true };
-
- private readonly Action open;
- private readonly Action? graph;
- private readonly List<(Formula Formula, Control Card)> cards = new List<(Formula, Control)>();
- private readonly List subjects = new List();
- private string? subject;
-
- /// Opens a formula in the calculator.
- /// Draws the graph of a formula; without it, the formulas have no button for their graph.
- public FormulasPage(Action open, Action? graph = null)
- {
- this.open = open;
- this.graph = graph;
-
- Search = new TextBox { PlaceholderText = "Search a formula", Width = 260 };
- // the property, not TextChanged, which Avalonia raises later, on the dispatcher
- Search.PropertyChanged += (_, e) =>
- {
- if (e.Property == TextBox.TextProperty)
- Filter();
- };
-
- var chips = Ui.Row(Search);
- foreach (var name in new string?[] { null }.Concat(Formulas.Subjects))
- {
- var chip = new ToggleButton
- {
- Content = name ?? "All",
- IsChecked = name == null,
- CornerRadius = new CornerRadius(16),
- Padding = new Thickness(14, 5),
- };
- chip.Click += (_, _) => ShowSubject(name);
- subjects.Add(chip);
- chips.Children.Add(chip);
- }
-
- var list = new WrapPanel { Orientation = Orientation.Horizontal, ItemSpacing = 12, LineSpacing = 12 };
- foreach (var formula in Formulas.All)
- {
- var card = Card(formula);
- cards.Add((formula, card));
- list.Children.Add(card);
- }
-
- Content = Ui.Card("Formulas", "A library of formulas of algebra, geometry, trigonometry, calculus, statistics and physics: click one to open it in the calculator, or draw its graph", new StackPanel
- {
- Spacing = 16,
- Children = { chips, list },
- });
- }
-
- /// The search box: the formulas whose name or subject contain its text.
- public TextBox Search { get; }
-
- /// The formulas shown, after the subject and the search.
- public IEnumerable Shown => cards.Where(c => c.Card.IsVisible).Select(c => c.Formula);
-
- /// Shows the formulas of a subject, or all of them for null.
- public void ShowSubject(string? name)
- {
- subject = name;
- for (var i = 0; i < subjects.Count; i++)
- subjects[i].IsChecked = (i == 0 ? null : Formulas.Subjects[i - 1]) == name;
- Filter();
- }
-
- /// Opens a formula in the calculator, as a click on it does.
- public void Open(Formula formula) => open(Equation.Parse(formula.UnicodeMath, EquationFormat.UnicodeMath, Display));
-
- /// Draws the graph of a formula, as its button does; false if it has none or the page draws no graphs.
- public bool Graph(Formula formula)
- {
- if (formula.Graph == null || graph == null)
- return false;
- graph(formula.Graph);
- return true;
- }
-
- private void Filter()
- {
- var shown = new HashSet(Formulas.Find(subject, Search.Text));
- foreach (var (formula, card) in cards)
- card.IsVisible = shown.Contains(formula);
- }
-
- private Control Card(Formula formula)
- {
- var caption = Ui.Muted(formula.Subject.ToUpperInvariant() + " · " + formula.Name, 11.5);
- var view = Ui.Math(formula.UnicodeMath, 19, display: true);
- view.HorizontalAlignment = HorizontalAlignment.Left;
- var button = new Button
- {
- Width = 352,
- MinHeight = 108,
- CornerRadius = new CornerRadius(12),
- Padding = new Thickness(14, 10),
- BorderThickness = new Thickness(1),
- Focusable = false,
- HorizontalContentAlignment = HorizontalAlignment.Stretch,
- VerticalContentAlignment = VerticalAlignment.Top,
- Content = new StackPanel { Spacing = 8, Children = { caption, view } },
- };
- button.Bind(Button.BackgroundProperty, button.GetResourceObservable("CodeBrush"));
- button.Bind(Button.BorderBrushProperty, button.GetResourceObservable("CardBorderBrush"));
- ToolTip.SetTip(button, "Open in the calculator");
- button.Click += (_, _) => Open(formula);
- if (formula.Graph == null || graph == null)
- return button;
-
- var draw = new Button
- {
- Content = "Graph",
- FontSize = 12,
- CornerRadius = new CornerRadius(10),
- Padding = new Thickness(10, 2),
- Margin = new Thickness(0, 8, 10, 0),
- HorizontalAlignment = HorizontalAlignment.Right,
- VerticalAlignment = VerticalAlignment.Top,
- };
- ToolTip.SetTip(draw, "Draw on the page of the graphs, with a slider for each parameter");
- draw.Click += (_, _) => Graph(formula);
- return new Panel { Children = { button, draw } };
- }
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Graphs3DPage.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Graphs3DPage.cs
deleted file mode 100644
index 04daab8..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/Graphs3DPage.cs
+++ /dev/null
@@ -1,266 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Threading.Tasks;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Input.Platform;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using global::Avalonia.Media.Imaging;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The graphs in space: surfaces z=f(x,y) and curves x=f(t), y=g(t), z=h(t) typed in an editor and drawn together in a
- /// box the camera turns around, each in its color, with a slider for each of their parameters.
- ///
- public sealed class Graphs3DPage : UserControl
- {
- private static readonly Color[] Palette =
- {
- Color.FromRgb(0x25, 0x63, 0xEB),
- Color.FromRgb(0xDC, 0x26, 0x26),
- Color.FromRgb(0x05, 0x96, 0x69),
- Color.FromRgb(0xD9, 0x77, 0x06),
- Color.FromRgb(0x7C, 0x3A, 0xED),
- Color.FromRgb(0xDB, 0x27, 0x77),
- };
-
- private static readonly EquationOptions Display = new EquationOptions { Display = true };
-
- private readonly StackPanel list = new StackPanel { Spacing = 10 };
- private readonly TextBlock message = Ui.Muted("", 12.5);
- private int added;
- private bool sharing;
- private RenderTargetBitmap? copied;
-
- /// The computer algebra system whose unit of angles and letters defined the Add button takes.
- public Graphs3DPage(ICasEngine? engine = null)
- {
- Editor = new MathEditBox
- {
- FontSize = 26,
- MinHeight = 70,
- Padding = new Thickness(16, 10),
- BorderThickness = 0,
- Equation = Equation.Parse("z=sin x cos y", EquationFormat.UnicodeMath, Display),
- };
- Editor.Bind(MathEditBox.BackgroundProperty, Editor.GetResourceObservable("EditorBrush"));
- var frame = new Border
- {
- CornerRadius = new CornerRadius(12),
- BorderThickness = new Thickness(1.5),
- ClipToBounds = true,
- Child = Editor,
- };
- frame.Bind(Border.BorderBrushProperty, frame.GetResourceObservable("EditorBorderBrush"));
-
- var add = new Button { Content = "Add", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(add, "Draws the equation of the editor");
- add.Click += (_, _) =>
- {
- if (Editor.Equation is { } equation)
- AddEquation(equation, engine?.Angles ?? AngleUnit.Radians, engine?.Definitions);
- };
- var clear = new Button { Content = "Clear", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(clear, "Removes every graph");
- clear.Click += (_, _) => Clear();
- var reset = new Button { Content = "Reset view", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(reset, "Turns the box back and shows the region around the origin (a double click on the graph does the same)");
-
- var copy = new Button { Content = "Copy image", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(copy, "Copies the graphs as an image");
- copy.Click += async (_, _) => await CopyImageAsync().ConfigureAwait(true);
- SharedParameters = new CheckBox { Content = "Same parameters for every graph", IsChecked = false };
- ToolTip.SetTip(SharedParameters, "A letter is one parameter for all the graphs with it, or one per graph");
- SharedParameters.IsCheckedChanged += (_, _) =>
- {
- if (SharedParameters.IsChecked == true)
- {
- foreach (var name in Sliders.Keys.Select(k => k.Parameter).Distinct().ToList())
- Share(name, Sliders.First(s => s.Key.Parameter == name).Value.Value);
- }
- };
-
- Space = new Graph3DView { Height = 480, ForceSoftware = OperatingSystem.IsBrowser() };
- reset.Click += (_, _) => Space.Reset();
- var spaceFrame = new Border { CornerRadius = new CornerRadius(12), BorderThickness = new Thickness(1), ClipToBounds = true, Child = Space };
- spaceFrame.ContextMenu = new ContextMenu
- {
- ItemsSource = new[]
- {
- Item("Copy image", CopyImageAsync),
- Item("Reset view", () =>
- {
- Space.Reset();
- return Task.CompletedTask;
- }),
- },
- };
- spaceFrame.Bind(Border.BorderBrushProperty, spaceFrame.GetResourceObservable("CardBorderBrush"));
-
- Content = new StackPanel
- {
- Spacing = 20,
- Children =
- {
- Ui.Card("Graphs in space", Ui.Caption("$z=f(x,y)$, or $x=f(t)$, $y=g(t)$ and $z=h(t)$ on three lines, $t$ from $0$ to $2π$: the other letters are parameters, with a slider each"), new StackPanel
- {
- Spacing = 12,
- Children = { frame, Ui.Row(add, clear, reset, copy, SharedParameters), message, list },
- }),
- Ui.Card("Space", "Drag to turn, the wheel to zoom the region of x and y, a double click to start again", spaceFrame),
- },
- };
- }
-
- /// The editor of the equation to add.
- public MathEditBox Editor { get; }
-
- /// The box the graphs are drawn in.
- public Graph3DView Space { get; }
-
- /// Whether a letter is one parameter for every graph with it (its sliders move together) or one per graph.
- public CheckBox SharedParameters { get; }
-
- /// Why the last equation was not drawn, or null.
- public string? Error { get; private set; }
-
- /// The sliders of the parameters, by graph and parameter.
- public IDictionary<(SurfaceGraph Graph, string Parameter), Slider> Sliders { get; } = new Dictionary<(SurfaceGraph, string), Slider>();
-
- /// Draws an equation; false, with , when it has no graph in space.
- public bool AddEquation(Equation equation, AngleUnit angles = AngleUnit.Radians, IReadOnlyDictionary? definitions = null)
- {
- SurfacePlot plot;
- try
- {
- plot = SurfacePlot.FromEquation(equation, angles, definitions);
- }
-#pragma warning disable CA1031 // what the equation cannot draw is told, whatever it is
- catch (Exception e)
-#pragma warning restore CA1031
- {
- Error = e is NotSupportedException ? e.Message : "This equation has no graph in space.";
- message.Text = Error;
- return false;
- }
-
- Error = null;
- message.Text = "";
- var graph = new SurfaceGraph(equation, plot, Palette[added++ % Palette.Length]);
- Space.Surfaces.Add(graph);
- list.Children.Add(Row(graph));
- if (SharedParameters.IsChecked == true)
- {
- // a letter already drawn keeps its value
- foreach (var name in plot.Parameters)
- {
- if (Sliders.FirstOrDefault(s => s.Key.Parameter == name && s.Key.Graph != graph).Value is { } other)
- Sliders[(graph, name)].Value = other.Value;
- }
- }
- return true;
- }
-
- /// Removes every graph.
- public void Clear()
- {
- Space.Surfaces.Clear();
- list.Children.Clear();
- Sliders.Clear();
- added = 0;
- }
-
- private StackPanel Row(SurfaceGraph graph)
- {
- var swatch = new Border { Width = 16, Height = 16, CornerRadius = new CornerRadius(8), Background = new SolidColorBrush(graph.Color), VerticalAlignment = VerticalAlignment.Center };
- var view = new MathView { FontSize = 18, Equation = graph.Equation, VerticalAlignment = VerticalAlignment.Center };
- var remove = new Button { Content = "×", CornerRadius = new CornerRadius(8), Padding = new Thickness(8, 2), VerticalAlignment = VerticalAlignment.Center };
- ToolTip.SetTip(remove, "Removes this graph");
-
- var parameters = new StackPanel { Spacing = 4, Margin = new Thickness(28, 0, 0, 0) };
- foreach (var name in graph.Plot.Parameters)
- {
- var value = Ui.Muted(Value(name, graph.Plot[name]), 12.5);
- value.MinWidth = 90;
- value.VerticalAlignment = VerticalAlignment.Center;
- var slider = new Slider { Minimum = -10, Maximum = 10, Value = graph.Plot[name], SmallChange = 0.1, LargeChange = 1, MinWidth = 240 };
- var parameter = name;
- slider.PropertyChanged += (_, e) =>
- {
- if (e.Property != Slider.ValueProperty)
- return;
- graph.Plot[parameter] = slider.Value;
- value.Text = Value(parameter, slider.Value);
- if (!sharing && SharedParameters.IsChecked == true)
- Share(parameter, slider.Value);
- // sampling the surfaces again is slow: it waits for the slider to stop
- Space.RedrawSoon();
- };
- Sliders[(graph, name)] = slider;
- parameters.Children.Add(new DockPanel { Children = { Ui.Docked(value, Dock.Left), slider } });
- }
-
- var row = new StackPanel
- {
- Spacing = 4,
- Children =
- {
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, Children = { swatch, view, remove } },
- parameters,
- },
- };
- remove.Click += (_, _) =>
- {
- Space.Surfaces.Remove(graph);
- list.Children.Remove(row);
- foreach (var name in graph.Plot.Parameters)
- Sliders.Remove((graph, name));
- };
- return row;
- }
-
- // the sliders of a letter, on every graph, to a value
- private void Share(string parameter, double value)
- {
- sharing = true;
- try
- {
- foreach (var slider in Sliders.Where(s => s.Key.Parameter == parameter).Select(s => s.Value))
- {
- if (slider.Value != value)
- slider.Value = value;
- }
- }
- finally
- {
- sharing = false;
- }
- }
-
- /// Copies the graphs to the clipboard as an image.
- public async Task CopyImageAsync()
- {
- if (TopLevel.GetTopLevel(this)?.Clipboard is not { } clipboard)
- return;
- // the clipboard may read the image later: the last one copied is kept until the next
- copied?.Dispose();
- copied = Space.Snapshot();
- await clipboard.SetBitmapAsync(copied).ConfigureAwait(true);
- }
-
- private static MenuItem Item(string header, Func action)
- {
- var item = new MenuItem { Header = header };
- item.Click += async (_, _) => await action().ConfigureAwait(true);
- return item;
- }
-
- private static string Value(string name, double value) => name + " = " + value.ToString("0.##", CultureInfo.InvariantCulture);
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/GraphsPage.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/GraphsPage.cs
deleted file mode 100644
index e9dfd01..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/GraphsPage.cs
+++ /dev/null
@@ -1,292 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Threading.Tasks;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Input.Platform;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using global::Avalonia.Media.Imaging;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The graphs: equations typed in an editor (or sent by the calculator) drawn together, each in its color, with a
- /// slider for each of their parameters, the letters that are not variables of the graph.
- ///
- public sealed class GraphsPage : UserControl
- {
- private static readonly Color[] Palette =
- {
- Color.FromRgb(0x25, 0x63, 0xEB),
- Color.FromRgb(0xDC, 0x26, 0x26),
- Color.FromRgb(0x05, 0x96, 0x69),
- Color.FromRgb(0xD9, 0x77, 0x06),
- Color.FromRgb(0x7C, 0x3A, 0xED),
- Color.FromRgb(0xDB, 0x27, 0x77),
- };
-
- private static readonly EquationOptions Display = new EquationOptions { Display = true };
-
- private readonly StackPanel list = new StackPanel { Spacing = 10 };
- private readonly TextBlock message = Ui.Muted("", 12.5);
- private readonly ICasEngine? engine;
- private int added;
- private bool sharing;
- private RenderTargetBitmap? copied;
-
- /// The computer algebra system whose unit of angles and letters defined the Add button takes.
- public GraphsPage(ICasEngine? engine = null)
- {
- this.engine = engine;
- Editor = new MathEditBox
- {
- FontSize = 26,
- MinHeight = 70,
- Padding = new Thickness(16, 10),
- BorderThickness = 0,
- Equation = Equation.Parse("y=sin(a x)", EquationFormat.UnicodeMath, Display),
- };
- Editor.Bind(MathEditBox.BackgroundProperty, Editor.GetResourceObservable("EditorBrush"));
- var frame = new Border
- {
- CornerRadius = new CornerRadius(12),
- BorderThickness = new Thickness(1.5),
- ClipToBounds = true,
- Child = Editor,
- };
- frame.Bind(Border.BorderBrushProperty, frame.GetResourceObservable("EditorBorderBrush"));
-
- var add = new Button { Content = "Add", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(add, "Draws the equation of the editor");
- add.Click += (_, _) =>
- {
- if (Editor.Equation is { } equation)
- AddEquation(equation, engine?.Angles ?? AngleUnit.Radians, engine?.Definitions);
- };
- var clear = new Button { Content = "Clear", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(clear, "Removes every graph");
- clear.Click += (_, _) => Clear();
- var reset = new Button { Content = "Reset view", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(reset, "Shows the region around the origin (a double click on the graph does the same)");
-
- var copy = new Button { Content = "Copy image", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(copy, "Copies the graphs as an image");
- copy.Click += async (_, _) => await CopyImageAsync().ConfigureAwait(true);
- SharedParameters = new CheckBox { Content = "Same parameters for every graph", IsChecked = false };
- ToolTip.SetTip(SharedParameters, "A letter is one parameter for all the graphs with it, or one per graph");
- SharedParameters.IsCheckedChanged += (_, _) =>
- {
- if (SharedParameters.IsChecked == true)
- {
- foreach (var name in Sliders.Keys.Select(k => k.Parameter).Distinct().ToList())
- Share(name, Sliders.First(s => s.Key.Parameter == name).Value.Value);
- }
- };
-
- Graph = new GraphView { Height = 480 };
- reset.Click += (_, _) => Graph.Reset();
- var graphFrame = new Border { CornerRadius = new CornerRadius(12), BorderThickness = new Thickness(1), ClipToBounds = true, Child = Graph };
- graphFrame.ContextMenu = new ContextMenu
- {
- ItemsSource = new[]
- {
- Item("Copy image", CopyImageAsync),
- Item("Reset view", () =>
- {
- Graph.Reset();
- return Task.CompletedTask;
- }),
- },
- };
- graphFrame.Bind(Border.BorderBrushProperty, graphFrame.GetResourceObservable("CardBorderBrush"));
-
- Content = new StackPanel
- {
- Spacing = 20,
- Children =
- {
- Ui.Card("Graphs", Ui.Caption("$y=f(x)$, $r=f(θ)$, $x=f(t)$ and $y=g(t)$ on two lines, or a relation of x and y such as $x^2+y^2=25$: the other letters are parameters, with a slider each"), new StackPanel
- {
- Spacing = 12,
- Children = { frame, Ui.Row(add, clear, reset, copy, SharedParameters), message, list },
- }),
- Ui.Card("Plane", "Drag to move, the wheel to zoom where the pointer is, a double click to start again", graphFrame),
- },
- };
- }
-
- /// The editor of the equation to add.
- public MathEditBox Editor { get; }
-
- /// The plane the graphs are drawn on.
- public GraphView Graph { get; }
-
- /// Whether a letter is one parameter for every graph with it (its sliders move together) or one per graph.
- public CheckBox SharedParameters { get; }
-
- /// Why the last equation was not drawn, or null.
- public string? Error { get; private set; }
-
- /// The sliders of the parameters, by graph and parameter.
- public IDictionary<(GraphCurve Curve, string Parameter), Slider> Sliders { get; } = new Dictionary<(GraphCurve, string), Slider>();
-
- /// Draws an equation; false, with , when it has no graph.
- public bool AddEquation(Equation equation, AngleUnit angles = AngleUnit.Radians, IReadOnlyDictionary? definitions = null)
- {
- GraphPlot plot;
- try
- {
- plot = GraphPlot.FromEquation(equation, angles, definitions);
- }
-#pragma warning disable CA1031 // what the equation cannot draw is told, whatever it is
- catch (Exception e)
-#pragma warning restore CA1031
- {
- Error = e is NotSupportedException ? e.Message : "This equation has no graph.";
- message.Text = Error;
- return false;
- }
-
- Error = null;
- message.Text = "";
- var curve = new GraphCurve(equation, plot, Palette[added++ % Palette.Length]);
- Graph.Curves.Add(curve);
- list.Children.Add(Row(curve));
- if (SharedParameters.IsChecked == true)
- {
- // a letter already drawn keeps its value
- foreach (var name in plot.Parameters)
- {
- if (Sliders.FirstOrDefault(s => s.Key.Parameter == name && s.Key.Curve != curve).Value is { } other)
- Sliders[(curve, name)].Value = other.Value;
- }
- }
- return true;
- }
-
- ///
- /// Draws the graph of a formula of the library, with its parameters (and their sliders) at their starting values;
- /// false, with , when it has no graph.
- ///
- public bool AddPreset(GraphPreset preset, AngleUnit angles = AngleUnit.Radians)
- {
- ArgumentNullException.ThrowIfNull(preset);
- if (!AddEquation(Equation.Parse(preset.UnicodeMath, EquationFormat.UnicodeMath, Display), angles))
- return false;
- var curve = Graph.Curves[^1];
- foreach (var (parameter, value) in preset.Values)
- {
- var name = MathReader.Symbol(parameter);
- if (Sliders.TryGetValue((curve, name), out var slider))
- {
- slider.Minimum = Math.Min(slider.Minimum, value);
- slider.Maximum = Math.Max(slider.Maximum, value);
- slider.Value = value;
- }
- curve.Plot[name] = value;
- }
- Graph.Redraw();
- return true;
- }
-
- /// Removes every graph.
- public void Clear()
- {
- Graph.Curves.Clear();
- list.Children.Clear();
- Sliders.Clear();
- added = 0;
- }
-
- private StackPanel Row(GraphCurve curve)
- {
- var swatch = new Border { Width = 16, Height = 16, CornerRadius = new CornerRadius(8), Background = new SolidColorBrush(curve.Color), VerticalAlignment = VerticalAlignment.Center };
- var view = new MathView { FontSize = 18, Equation = curve.Equation, VerticalAlignment = VerticalAlignment.Center };
- var remove = new Button { Content = "×", CornerRadius = new CornerRadius(8), Padding = new Thickness(8, 2), VerticalAlignment = VerticalAlignment.Center };
- ToolTip.SetTip(remove, "Removes this graph");
-
- var parameters = new StackPanel { Spacing = 4, Margin = new Thickness(28, 0, 0, 0) };
- foreach (var name in curve.Plot.Parameters)
- {
- var value = Ui.Muted(Value(name, curve.Plot[name]), 12.5);
- value.MinWidth = 90;
- value.VerticalAlignment = VerticalAlignment.Center;
- var slider = new Slider { Minimum = -10, Maximum = 10, Value = curve.Plot[name], SmallChange = 0.1, LargeChange = 1, MinWidth = 240 };
- var parameter = name;
- slider.PropertyChanged += (_, e) =>
- {
- if (e.Property != Slider.ValueProperty)
- return;
- curve.Plot[parameter] = slider.Value;
- value.Text = Value(parameter, slider.Value);
- if (!sharing && SharedParameters.IsChecked == true)
- Share(parameter, slider.Value);
- Graph.Redraw();
- };
- Sliders[(curve, name)] = slider;
- parameters.Children.Add(new DockPanel { Children = { Ui.Docked(value, Dock.Left), slider } });
- }
-
- var row = new StackPanel
- {
- Spacing = 4,
- Children =
- {
- new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, Children = { swatch, view, remove } },
- parameters,
- },
- };
- remove.Click += (_, _) =>
- {
- Graph.Curves.Remove(curve);
- list.Children.Remove(row);
- foreach (var name in curve.Plot.Parameters)
- Sliders.Remove((curve, name));
- };
- return row;
- }
-
- // the sliders of a letter, on every graph, to a value
- private void Share(string parameter, double value)
- {
- sharing = true;
- try
- {
- foreach (var slider in Sliders.Where(s => s.Key.Parameter == parameter).Select(s => s.Value))
- {
- if (slider.Value != value)
- slider.Value = value;
- }
- }
- finally
- {
- sharing = false;
- }
- }
-
- /// Copies the graphs to the clipboard as an image.
- public async Task CopyImageAsync()
- {
- if (TopLevel.GetTopLevel(this)?.Clipboard is not { } clipboard)
- return;
- // the clipboard may read the image later: the last one copied is kept until the next
- copied?.Dispose();
- copied = Graph.Snapshot();
- await clipboard.SetBitmapAsync(copied).ConfigureAwait(true);
- }
-
- private static MenuItem Item(string header, Func action)
- {
- var item = new MenuItem { Header = header };
- item.Click += async (_, _) => await action().ConfigureAwait(true);
- return item;
- }
-
- private static string Value(string name, double value) => name + " = " + value.ToString("0.##", CultureInfo.InvariantCulture);
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.axaml
new file mode 100644
index 0000000..2f4304e
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.axaml
@@ -0,0 +1,10 @@
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.axaml.cs
new file mode 100644
index 0000000..abf86db
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.axaml.cs
@@ -0,0 +1,21 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using global::Avalonia.Controls;
+ using SharpEquations.MathTools;
+
+ /// The window of the desktop app: the view the WebAssembly page shows too, with the settings kept where the store says.
+ public sealed partial class MainWindow : Window
+ {
+ public MainWindow()
+ : this(null)
+ {
+ }
+
+ /// Where the settings are kept; in memory by default.
+ public MainWindow(ISettingsStore? settings)
+ {
+ InitializeComponent();
+ DataContext = new MathToolsViewModel(settings);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.cs
deleted file mode 100644
index ec1bdbc..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/MainWindow.cs
+++ /dev/null
@@ -1,17 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using global::Avalonia.Controls;
- using SharpEquations.MathTools;
-
- /// The window of the desktop app: the view the WebAssembly page shows too, with the settings kept where the store says (none by default).
- public sealed class MainWindow : Window
- {
- public MainWindow(ISettingsStore? settings = null)
- {
- Title = "SharpEquations Math Tools";
- Width = 1180;
- Height = 860;
- Content = new MathToolsView(settings);
- }
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/MathToolsView.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/MathToolsView.cs
deleted file mode 100644
index da7385b..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/MathToolsView.cs
+++ /dev/null
@@ -1,223 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System;
- using System.Globalization;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using global::Avalonia.Styling;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The math tools, a page each: the scientific keypad around the equation editor, the library of formulas, the
- /// unit converter, the solver of triangles, the graphs, the graphs in space and the worksheet. The desktop window and the WebAssembly page show the same view, each
- /// with the services of its platform: where the settings are kept (the page shown, the equation of the calculator,
- /// the unit of angles, the theme), and the computer algebra system.
- ///
- public sealed class MathToolsView : UserControl
- {
- private const string RepositoryUrl = "https://github.com/simonebortolin/SharpEquations";
-
- private const int GraphsTab = 4;
-
- private const string TabKey = "tab";
- private const string EquationKey = "equation";
- private const string ThemeKey = "theme";
- private const string AnglesKey = "angles";
-
- private readonly ISettingsStore settings;
-
- public MathToolsView(ISettingsStore? settings = null, ICasEngine? engine = null)
- {
- this.settings = settings ?? new MemorySettingsStore();
- Engine = engine ?? new AngouriMathEngine();
- Ui.AddBrushes(Resources);
- Calculator = new CalculatorPage(Engine);
- Converter = new UnitsPage();
- TriangleSolver = new TrianglePage();
- Graphs = new GraphsPage(Engine);
- Space = new Graphs3DPage(Engine);
- Worksheet = new WorksheetPage(Engine, this.settings);
- Tabs = new TabControl { Margin = new Thickness(20, 12, 20, 0) };
- FormulaLibrary = new FormulasPage(equation =>
- {
- Calculator.Editor.Equation = equation;
- Tabs.SelectedIndex = 0;
- Calculator.Editor.Focus();
- }, preset =>
- {
- Graphs.AddPreset(preset, Engine.Angles);
- Tabs.SelectedIndex = GraphsTab;
- });
- Tabs.ItemsSource = new[]
- {
- Tab("Calculator", Calculator),
- Tab("Formulas", FormulaLibrary),
- Tab("Units", Converter),
- Tab("Triangles", TriangleSolver),
- Tab("Graphs", Graphs),
- Tab("3D", Space),
- Tab("Worksheet", Worksheet),
- };
- Calculator.Solver.GraphRequested += (_, equation) => ShowGraph(equation);
- Worksheet.GraphRequested += (_, equation) => ShowGraph(equation);
-
- Restore();
- Tabs.SelectionChanged += (_, _) => this.settings.Set(TabKey, Tabs.SelectedIndex.ToString(CultureInfo.InvariantCulture));
- Calculator.Solver.Angles.SelectionChanged += (_, _) => this.settings.Set(AnglesKey, Calculator.Solver.Angles.SelectedIndex == 1 ? "degrees" : "radians");
- Calculator.Editor.EquationChanged += (_, _) => this.settings.Set(EquationKey, Calculator.Editor.Equation?.ToString(EquationFormat.UnicodeMath));
-
- var root = new DockPanel { Children = { Ui.Docked(Header(), Dock.Top), Tabs } };
- root.Bind(Panel.BackgroundProperty, root.GetResourceObservable("PageBrush"));
- Content = root;
- }
-
- /// The worksheet, the history of what was computed.
- public WorksheetPage Worksheet { get; }
-
- /// The computer algebra system of the calculator.
- public ICasEngine Engine { get; }
-
- /// The page of the scientific keypad.
- public CalculatorPage Calculator { get; }
-
- /// The page of the library of formulas.
- public FormulasPage FormulaLibrary { get; }
-
- /// The page of the unit converter.
- public UnitsPage Converter { get; }
-
- /// The page of the solver of triangles.
- public TrianglePage TriangleSolver { get; }
-
- /// The page of the graphs.
- public GraphsPage Graphs { get; }
-
- /// The page of the graphs in space.
- public Graphs3DPage Space { get; }
-
- /// The tabs of the pages.
- public TabControl Tabs { get; }
-
- // the page, the equation and the theme of the last session
- private void Restore()
- {
- if (int.TryParse(settings.Get(TabKey), NumberStyles.None, CultureInfo.InvariantCulture, out var tab) && tab < Tabs.ItemCount)
- Tabs.SelectedIndex = tab;
- if (settings.Get(EquationKey) is { } text && Equation.TryParse(text, EquationFormat.UnicodeMath, new EquationOptions { Display = true }, out var equation))
- Calculator.Editor.Equation = equation;
- if (settings.Get(AnglesKey) == "degrees")
- Calculator.Solver.Angles.SelectedIndex = 1;
- if (Application.Current is { } app && settings.Get(ThemeKey) is { } theme)
- app.RequestedThemeVariant = theme == "dark" ? ThemeVariant.Dark : ThemeVariant.Light;
- }
-
- private void ShowGraph(Equation equation)
- {
- Graphs.AddEquation(equation, Engine.Angles, Engine.Definitions);
- Tabs.SelectedIndex = GraphsTab;
- }
-
- private static TabItem Tab(string header, Control page) => new TabItem
- {
- Header = new TextBlock { Text = header, FontSize = 15, FontWeight = FontWeight.SemiBold },
- Content = new ScrollViewer
- {
- Content = new Border { Padding = new Thickness(0, 12, 0, 32), MaxWidth = 1180, Child = page },
- HorizontalScrollBarVisibility = global::Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,
- },
- };
-
- private Border Header()
- {
- var title = new StackPanel
- {
- Spacing = 4,
- VerticalAlignment = VerticalAlignment.Center,
- Children =
- {
- new TextBlock { Text = "SharpEquations Math Tools", FontSize = 26, FontWeight = FontWeight.Bold, Foreground = Brushes.White },
- new TextBlock
- {
- Text = "A scientific keypad, formulas, units, triangles, graphs and a worksheet around a real-time equation editor in .NET.",
- FontSize = 14,
- Foreground = new SolidColorBrush(Colors.White, 0.85),
- TextWrapping = TextWrapping.Wrap,
- },
- },
- };
-
- var hero = new MathView
- {
- FontSize = 24,
- Foreground = Brushes.White,
- VerticalAlignment = VerticalAlignment.Center,
- Margin = new Thickness(24, 0),
- Equation = Equation.Parse("∑_(k=1)^∞ 1/k^2=π^2/6", EquationFormat.UnicodeMath, new EquationOptions { Display = true }),
- };
-
- var theme = HeaderButton("Theme", "Light or dark theme");
- theme.Click += (_, _) =>
- {
- if (Application.Current is { } app)
- {
- var dark = app.ActualThemeVariant != ThemeVariant.Dark;
- app.RequestedThemeVariant = dark ? ThemeVariant.Dark : ThemeVariant.Light;
- settings.Set(ThemeKey, dark ? "dark" : "light");
- }
- };
- var github = HeaderButton("GitHub ↗", RepositoryUrl);
- github.Click += async (_, _) =>
- {
- if (TopLevel.GetTopLevel(this)?.Launcher is { } launcher)
- await launcher.LaunchUriAsync(new Uri(RepositoryUrl)).ConfigureAwait(true);
- };
-
- var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, VerticalAlignment = VerticalAlignment.Center, Children = { theme, github } };
- var bar = new DockPanel { Children = { Ui.Docked(buttons, Dock.Right), Ui.Docked(hero, Dock.Right), title } };
- bar.SizeChanged += (_, e) =>
- {
- var narrow = e.NewSize.Width < 640;
- hero.IsVisible = e.NewSize.Width > 900;
- DockPanel.SetDock(buttons, narrow ? Dock.Bottom : Dock.Right);
- buttons.HorizontalAlignment = narrow ? HorizontalAlignment.Left : HorizontalAlignment.Right;
- buttons.Margin = narrow ? new Thickness(0, 14, 0, 0) : default;
- };
-
- return new Border
- {
- Padding = new Thickness(28, 20),
- Background = new LinearGradientBrush
- {
- StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
- EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
- GradientStops =
- {
- new GradientStop(Color.FromRgb(0x0F, 0x76, 0x6E), 0),
- new GradientStop(Color.FromRgb(0x08, 0x91, 0xB2), 0.55),
- new GradientStop(Color.FromRgb(0x25, 0x63, 0xEB), 1),
- },
- },
- Child = bar,
- };
- }
-
- private static Button HeaderButton(string text, string tip)
- {
- var button = new Button
- {
- Content = text,
- Foreground = Brushes.White,
- Background = new SolidColorBrush(Colors.White, 0.16),
- BorderBrush = new SolidColorBrush(Colors.White, 0.35),
- BorderThickness = new Thickness(1),
- CornerRadius = new CornerRadius(18),
- Padding = new Thickness(14, 6),
- };
- ToolTip.SetTip(button, tip);
- return button;
- }
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Program.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Program.cs
index 6ab154a..9ec533f 100644
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/Program.cs
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Program.cs
@@ -2,8 +2,6 @@ namespace SharpEquations.Avalonia.MathTools
{
using System;
using global::Avalonia;
- using global::Avalonia.Controls.ApplicationLifetimes;
- using SharpEquations.MathTools;
public static class Program
{
@@ -12,16 +10,4 @@ public static class Program
public static AppBuilder BuildAvaloniaApp() => AppBuilder.Configure().UsePlatformDetect();
}
-
- public sealed class App : Application
- {
- public override void Initialize() => MathToolsTheme.Apply(this);
-
- public override void OnFrameworkInitializationCompleted()
- {
- if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
- desktop.MainWindow = new MainWindow(new FileSettingsStore(FileSettingsStore.DefaultPath));
- base.OnFrameworkInitializationCompleted();
- }
- }
}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/SharpEquations.Avalonia.MathTools.Demo.csproj b/samples/SharpEquations.Avalonia.MathTools.Demo/SharpEquations.Avalonia.MathTools.Demo.csproj
index 683ea8b..ab86959 100644
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/SharpEquations.Avalonia.MathTools.Demo.csproj
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/SharpEquations.Avalonia.MathTools.Demo.csproj
@@ -1,7 +1,7 @@
-
+
WinExe
net10.0
@@ -10,6 +10,7 @@
SharpEquations.Avalonia.MathTools
true
+ true
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/TrianglePage.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/TrianglePage.cs
deleted file mode 100644
index 0044faf..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/TrianglePage.cs
+++ /dev/null
@@ -1,290 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Controls.Shapes;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The solver of triangles: three of the sides and angles give the others, the area, the perimeter and the radii of
- /// the circles, with the laws used, written in UnicodeMath and drawn by s, and the triangle
- /// drawn to scale.
- ///
- public sealed class TrianglePage : UserControl
- {
- private const double DrawingWidth = 300;
- private const double DrawingHeight = 210;
-
- private static readonly Color Accent = Color.FromRgb(0x0D, 0x94, 0x88);
-
- private static readonly (string Name, string[] Values)[] Examples =
- {
- ("3, 4, 5", new[] { "3", "4", "5", "", "", "" }),
- ("SAS", new[] { "7", "", "9", "", "60", "" }),
- ("ASA", new[] { "", "", "10", "45", "75", "" }),
- ("Two triangles", new[] { "6", "8", "", "40", "", "" }),
- ("No triangle", new[] { "1", "2", "4", "", "", "" }),
- };
-
- private static readonly string[] Empty = { "", "", "", "", "", "" };
-
- private readonly StackPanel results = new StackPanel { Spacing = 18 };
- private readonly StackPanel steps = new StackPanel { Spacing = 10 };
- private bool updating;
-
- public TrianglePage()
- {
- Inputs = Triangles.SideNames.Concat(Triangles.AngleNames).Select(_ => new TextBox { Width = 92, PlaceholderText = "?" }).ToArray();
- foreach (var input in Inputs)
- {
- input.PropertyChanged += (_, e) =>
- {
- if (e.Property == TextBox.TextProperty)
- Solve();
- };
- }
-
- var clear = new Button { Content = "Clear", CornerRadius = new CornerRadius(8) };
- clear.Click += (_, _) => Fill(Empty);
- var examples = new List { Ui.Muted("Examples", 12.5) };
- foreach (var (name, values) in Examples)
- {
- var button = new Button { Content = name, CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 4) };
- button.Click += (_, _) => Fill(values);
- examples.Add(button);
- }
- examples.Add(clear);
-
- var sides = Ui.Row(Enumerable.Range(0, 3).Select(i => Field(Triangles.SideNames[i], Inputs[i], "")).ToArray());
- var angles = Ui.Row(Enumerable.Range(0, 3).Select(i => Field(Triangles.AngleNames[i], Inputs[i + 3], "°")).ToArray());
-
- Content = new StackPanel
- {
- Spacing = 20,
- Children =
- {
- Ui.Card("Triangles", "Three of the sides and angles, at least one of them a side; each angle is opposite the side of its letter", new StackPanel
- {
- Spacing = 14,
- Children =
- {
- new Grid
- {
- ColumnDefinitions = new ColumnDefinitions("Auto,*"),
- RowDefinitions = new RowDefinitions("Auto,Auto"),
- ColumnSpacing = 14,
- RowSpacing = 10,
- Children = { Label("Sides", 0), At(sides, 0, 1), Label("Angles", 1), At(angles, 1, 1) },
- },
- Ui.Row(examples.ToArray()),
- },
- }),
- Ui.Card("Solution", "The values found, the area, the perimeter and the radii of the circles through the vertices and inside", results),
- Ui.Card("How", "The laws that give the values found", steps),
- },
- };
- Fill(Examples[0].Values);
- }
-
- /// The fields of a, b, c, α, β and γ.
- public IReadOnlyList Inputs { get; }
-
- /// The solution of the values in the fields.
- public TriangleSolution? Solution { get; private set; }
-
- /// Fills the fields, as the examples do.
- public void Fill(IReadOnlyList values)
- {
- updating = true;
- for (var i = 0; i < Inputs.Count; i++)
- Inputs[i].Text = values[i];
- updating = false;
- Solve();
- }
-
- private void Solve()
- {
- if (updating)
- return;
-
- var values = new double?[Inputs.Count];
- for (var i = 0; i < Inputs.Count; i++)
- {
- var text = Inputs[i].Text;
- if (string.IsNullOrWhiteSpace(text))
- continue;
- if (!Units.TryParse(text!.TrimEnd('°', ' '), out var value))
- {
- Show(new TriangleSolution(null, Array.Empty(), Array.Empty(), "“" + text + "” is not a number."));
- return;
- }
- values[i] = value;
- }
- Show(Triangles.Solve(values[0], values[1], values[2], values[3], values[4], values[5]));
- }
-
- private void Show(TriangleSolution solution)
- {
- Solution = solution;
- results.Children.Clear();
- steps.Children.Clear();
-
- if (solution.Error != null)
- results.Children.Add(Ui.Muted(solution.Error, 14));
- if (solution.Triangles.Count == 2)
- results.Children.Add(Ui.Muted("The angle given is opposite the shorter side: two triangles have these values.", 13));
- foreach (var (triangle, index) in solution.Triangles.Select((t, i) => (t, i)))
- results.Children.Add(Result(triangle, solution.Triangles.Count == 2 ? "Triangle " + (index + 1) : null));
-
- if (solution.Case != null)
- steps.Children.Add(Ui.Muted("Case " + solution.Case + " (" + CaseName(solution.Case) + ")", 13));
- foreach (var step in solution.Steps)
- {
- var math = Ui.Math(step, 19);
- math.HorizontalAlignment = HorizontalAlignment.Left;
- steps.Children.Add(math);
- }
- if (solution.Steps.Count == 0)
- steps.Children.Add(Ui.Muted("Give three values, at least one of them a side.", 13));
- }
-
- private static Grid Result(Triangle triangle, string? title)
- {
- var (sides, angles) = Triangles.Describe(triangle);
- var values = new StackPanel { Spacing = 10, VerticalAlignment = VerticalAlignment.Center };
- if (title != null)
- values.Children.Add(Ui.Small(title));
- values.Children.Add(Left(Ui.Math(sides, 21)));
- values.Children.Add(Left(Ui.Math(angles, 21)));
- values.Children.Add(Measures(triangle));
-
- var drawing = Drawing(triangle);
- Grid.SetColumn(values, 1);
- return new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 24, Children = { drawing, values } };
- }
-
- private static Grid Measures(Triangle triangle)
- {
- var rows = new (string Name, string Value)[]
- {
- ("Area", Units.Format(triangle.Area)),
- ("Perimeter", Units.Format(triangle.Perimeter)),
- ("Circumradius", "R=" + Units.Format(triangle.Circumradius)),
- ("Inradius", "r=" + Units.Format(triangle.Inradius)),
- };
- var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("130,*"), RowSpacing = 8, Margin = new Thickness(0, 6, 0, 0) };
- foreach (var (row, (name, value)) in rows.Select((r, i) => (i, r)))
- {
- grid.RowDefinitions.Add(new RowDefinition(GridLength.Auto));
- var label = Ui.Muted(name, 13);
- label.VerticalAlignment = VerticalAlignment.Center;
- grid.Children.Add(At(label, row, 0));
- grid.Children.Add(At(Left(Ui.Math(value, 17)), row, 1));
- }
- return grid;
- }
-
- /// The triangle to scale: A at the left of the base c, B at its right, C above.
- private static Border Drawing(Triangle triangle)
- {
- var alpha = Triangles.Radians(triangle.Alpha);
- var points = new[] { (X: 0.0, Y: 0.0), (X: triangle.C, Y: 0.0), (X: triangle.B * Math.Cos(alpha), Y: triangle.B * Math.Sin(alpha)) };
- double minX = points.Min(p => p.X), maxX = points.Max(p => p.X), maxY = points.Max(p => p.Y);
- const double margin = 26;
- var scale = Math.Min((DrawingWidth - 2 * margin) / (maxX - minX), (DrawingHeight - 2 * margin) / maxY);
- var offsetX = (DrawingWidth - (maxX - minX) * scale) / 2;
- var offsetY = (DrawingHeight + maxY * scale) / 2;
- var screen = points.Select(p => new Point(offsetX + (p.X - minX) * scale, offsetY - p.Y * scale)).ToArray();
-
- var canvas = new Canvas { Width = DrawingWidth, Height = DrawingHeight };
- var shape = new Polygon
- {
- Points = screen,
- StrokeThickness = 2,
- StrokeJoin = PenLineJoin.Round,
- Stroke = new SolidColorBrush(Accent),
- Fill = new SolidColorBrush(Accent, 0.14),
- };
- canvas.Children.Add(shape);
-
- var center = new Point(screen.Average(p => p.X), screen.Average(p => p.Y));
- for (var i = 0; i < 3; i++)
- {
- // the vertex, away from the center, and the side opposite it, at its middle, away from the center too
- Label(canvas, ((char)('A' + i)).ToString(), Away(screen[i], center, 14), FontWeight.SemiBold);
- var middle = (screen[(i + 1) % 3] + screen[(i + 2) % 3]) / 2;
- Label(canvas, Triangles.SideNames[i], Away(middle, center, 12), FontWeight.Normal);
- }
-
- var frame = new Border { CornerRadius = new CornerRadius(12), Child = canvas, VerticalAlignment = VerticalAlignment.Top };
- frame.Bind(Border.BackgroundProperty, frame.GetResourceObservable("CodeBrush"));
- return frame;
- }
-
- private static Point Away(Point point, Point center, double distance)
- {
- var direction = point - center;
- var length = Math.Sqrt(direction.X * direction.X + direction.Y * direction.Y);
- return length < 1e-9 ? point : point + direction * (distance / length);
- }
-
- private static void Label(Canvas canvas, string text, Point at, FontWeight weight)
- {
- var label = new TextBlock { Text = text, FontStyle = FontStyle.Italic, FontSize = 15, FontWeight = weight };
- label.Measure(Size.Infinity);
- Canvas.SetLeft(label, at.X - label.DesiredSize.Width / 2);
- Canvas.SetTop(label, at.Y - label.DesiredSize.Height / 2);
- canvas.Children.Add(label);
- }
-
- private static string CaseName(string kind) => kind switch
- {
- "SSS" => "three sides",
- "SAS" => "two sides and the angle between them",
- "SSA" => "two sides and an angle not between them",
- "ASA" => "two angles and the side between them",
- _ => "two angles and a side not between them",
- };
-
- private static StackPanel Field(string name, TextBox input, string unit)
- {
- var label = Ui.Math(name, 19);
- label.VerticalAlignment = VerticalAlignment.Center;
- label.Width = 18;
- var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { label, input } };
- if (unit.Length > 0)
- panel.Children.Add(new TextBlock { Text = unit, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(-4, 0, 6, 0) });
- else
- panel.Margin = new Thickness(0, 0, 12, 0);
- return panel;
- }
-
- private static TextBlock Label(string text, int row)
- {
- var label = Ui.Small(text);
- label.VerticalAlignment = VerticalAlignment.Center;
- return At(label, row, 0);
- }
-
- private static T Left(T control)
- where T : Control
- {
- control.HorizontalAlignment = HorizontalAlignment.Left;
- return control;
- }
-
- private static T At(T control, int row, int column)
- where T : Control
- {
- Grid.SetRow(control, row);
- Grid.SetColumn(control, column);
- return control;
- }
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Ui.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Ui.cs
deleted file mode 100644
index 3a17965..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/Ui.cs
+++ /dev/null
@@ -1,125 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using global::Avalonia.Media.Immutable;
- using global::Avalonia.Styling;
- using SharpEquations;
-
- /// The pieces of the pages: cards, labels, rows, and the brushes of the light and the dark theme.
- internal static class Ui
- {
- public static void AddBrushes(IResourceDictionary resources)
- {
- resources.ThemeDictionaries[ThemeVariant.Light] = new ResourceDictionary
- {
- ["PageBrush"] = Solid(0xF2F6F5),
- ["CardBrush"] = Solid(0xFFFFFF),
- ["CardBorderBrush"] = Solid(0xDDE7E5),
- ["MutedBrush"] = Solid(0x64748B),
- ["EditorBrush"] = Solid(0xFBFEFD),
- ["CodeBrush"] = Solid(0xF4F8F7),
- ["KeyBrush"] = Solid(0xF1F5F4),
- ["DigitBrush"] = Solid(0xFFFFFF),
- ["EditorBorderBrush"] = Solid(0x14B8A6),
- ["GraphBrush"] = Solid(0xFFFFFF),
- ["GridBrush"] = Solid(0xE6EDEC),
- ["AxisBrush"] = Solid(0x475569),
- };
- resources.ThemeDictionaries[ThemeVariant.Dark] = new ResourceDictionary
- {
- ["PageBrush"] = Solid(0x0B1113),
- ["CardBrush"] = Solid(0x141C1F),
- ["CardBorderBrush"] = Solid(0x24302F),
- ["MutedBrush"] = Solid(0x94A3B8),
- ["EditorBrush"] = Solid(0x0F1618),
- ["CodeBrush"] = Solid(0x0F1517),
- ["KeyBrush"] = Solid(0x1A2427),
- ["DigitBrush"] = Solid(0x222E31),
- ["EditorBorderBrush"] = Solid(0x0D9488),
- ["GraphBrush"] = Solid(0x0F1618),
- ["GridBrush"] = Solid(0x1E292C),
- ["AxisBrush"] = Solid(0x94A3B8),
- };
- }
-
- public static Border Card(string title, string subtitle, Control content) => Card(title, Muted(subtitle, 12.5), content);
-
- /// A card whose caption is a control, such as : text and formulas.
- public static Border Card(string title, Control caption, Control content)
- {
- var heading = new TextBlock { Text = title, FontSize = 17, FontWeight = FontWeight.SemiBold };
- var card = new Border
- {
- CornerRadius = new CornerRadius(16),
- BorderThickness = new Thickness(1),
- Padding = new Thickness(22, 18, 22, 22),
- BoxShadow = BoxShadows.Parse("0 6 28 0 #12000000"),
- Child = new StackPanel
- {
- Spacing = 14,
- Children = { new StackPanel { Spacing = 2, Children = { heading, caption } }, content },
- },
- };
- card.Bind(Border.BackgroundProperty, card.GetResourceObservable("CardBrush"));
- card.Bind(Border.BorderBrushProperty, card.GetResourceObservable("CardBorderBrush"));
- return card;
- }
-
- public static TextBlock Muted(string text, double size = 12)
- {
- var block = new TextBlock { Text = text, FontSize = size, TextWrapping = TextWrapping.Wrap };
- block.Bind(TextBlock.ForegroundProperty, block.GetResourceObservable("MutedBrush"));
- return block;
- }
-
- public static TextBlock Small(string text) => new TextBlock { Text = text, FontSize = 13, FontWeight = FontWeight.SemiBold };
-
- public static MathView Math(string unicodeMath, double size, bool display = false) => new MathView
- {
- FontSize = size,
- IsHitTestVisible = false,
- Equation = Equation.Parse(unicodeMath, EquationFormat.UnicodeMath, new EquationOptions { Display = display }),
- };
-
- ///
- /// A caption of text and formulas in a row: the parts in $…$ are UnicodeMath, drawn as formulas; the
- /// rest is muted text.
- ///
- public static WrapPanel Caption(string text)
- {
- var row = new WrapPanel { Orientation = Orientation.Horizontal, ItemSpacing = 4, LineSpacing = 2 };
- var parts = text.Split('$');
- for (var i = 0; i < parts.Length; i++)
- {
- if (parts[i].Length == 0)
- continue;
- Control part = i % 2 == 1 ? Math(parts[i], 14) : Muted(parts[i].Trim(), 12.5);
- part.VerticalAlignment = VerticalAlignment.Center;
- row.Children.Add(part);
- }
- return row;
- }
-
- public static Control Docked(Control control, Dock dock)
- {
- DockPanel.SetDock(control, dock);
- return control;
- }
-
- public static WrapPanel Row(params Control[] children)
- {
- var row = new WrapPanel { Orientation = Orientation.Horizontal, ItemSpacing = 8, LineSpacing = 8 };
- foreach (var child in children)
- {
- child.VerticalAlignment = VerticalAlignment.Center;
- row.Children.Add(child);
- }
- return row;
- }
-
- public static ImmutableSolidColorBrush Solid(uint rgb) => new ImmutableSolidColorBrush(Color.FromUInt32(0xFF000000 | rgb));
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/UnitsPage.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/UnitsPage.cs
deleted file mode 100644
index 2dfed11..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/UnitsPage.cs
+++ /dev/null
@@ -1,142 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System.Collections.Generic;
- using System.Linq;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Layout;
- using global::Avalonia.Media;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The unit converter: a value in a unit of a quantity, in another unit and in all of them, the results written in
- /// UnicodeMath and drawn by a .
- ///
- public sealed class UnitsPage : UserControl
- {
- private readonly MathView result = new MathView { FontSize = 30, HorizontalAlignment = HorizontalAlignment.Left };
- private readonly StackPanel table = new StackPanel { Spacing = 2 };
- private bool updating;
-
- public UnitsPage()
- {
- Quantity = new ComboBox { ItemsSource = Units.All, SelectedIndex = 0, MinWidth = 160 };
- Value = new TextBox { Text = "1", Width = 150, PlaceholderText = "A number" };
- From = new ComboBox { MinWidth = 220 };
- To = new ComboBox { MinWidth = 220 };
- var swap = new Button { Content = "⇄", FontSize = 17, Padding = new Thickness(12, 2), CornerRadius = new CornerRadius(8) };
- ToolTip.SetTip(swap, "Swap the units");
-
- Quantity.SelectionChanged += (_, _) => ShowQuantity();
- Value.PropertyChanged += (_, e) =>
- {
- if (e.Property == TextBox.TextProperty)
- Refresh();
- };
- From.SelectionChanged += (_, _) => Refresh();
- To.SelectionChanged += (_, _) => Refresh();
- swap.Click += (_, _) => Swap();
-
- var resultFrame = new Border { CornerRadius = new CornerRadius(12), Padding = new Thickness(18, 14), MinHeight = 76, Child = result };
- resultFrame.Bind(Border.BackgroundProperty, resultFrame.GetResourceObservable("CodeBrush"));
-
- Content = new StackPanel
- {
- Spacing = 20,
- Children =
- {
- Ui.Card("Units", "A value in a unit, in another: length, area, volume, mass, time, speed, temperature, energy, pressure, angle and data", new StackPanel
- {
- Spacing = 16,
- Children =
- {
- Ui.Row(Field("Quantity", Quantity), Field("Value", Value), Field("From", From), swap, Field("To", To)),
- resultFrame,
- },
- }),
- Ui.Card("In every unit", "The value in all the units of the quantity", table),
- },
- };
- ShowQuantity();
- }
-
- public ComboBox Quantity { get; }
-
- public TextBox Value { get; }
-
- public ComboBox From { get; }
-
- public ComboBox To { get; }
-
- /// The result, as UnicodeMath (1 " km"=0.621371 " mi" , with no-break spaces in the text), or null when the value is not a number.
- public string? Result { get; private set; }
-
- /// Swaps the units, as the ⇄ button does.
- public void Swap()
- {
- var from = From.SelectedIndex;
- updating = true;
- From.SelectedIndex = To.SelectedIndex;
- updating = false;
- To.SelectedIndex = from;
- }
-
- private Quantity Selected => (Quantity)Quantity.SelectedItem!;
-
- private void ShowQuantity()
- {
- updating = true;
- From.ItemsSource = Selected.Units;
- To.ItemsSource = Selected.Units;
- From.SelectedIndex = 0;
- To.SelectedIndex = 1;
- updating = false;
- Refresh();
- }
-
- private void Refresh()
- {
- if (updating || From.SelectedItem is not Unit from || To.SelectedItem is not Unit to)
- return;
-
- table.Children.Clear();
- if (!Units.TryParse(Value.Text, out var value))
- {
- Result = null;
- result.Equation = null;
- table.Children.Add(Ui.Muted("Type a number, such as 12.5 or 1.5e3."));
- return;
- }
-
- Result = Units.Format(value) + " " + Text(from.Symbol) + "=" + Units.Format(Units.Convert(value, from, to)) + " " + Text(to.Symbol);
- result.Equation = Equation.Parse(Result, EquationFormat.UnicodeMath, new EquationOptions { Display = true });
- foreach (var unit in Selected.Units)
- table.Children.Add(Line(unit, Units.Convert(value, from, unit), unit == from || unit == to));
- }
-
- private static Grid Line(Unit unit, double value, bool highlighted)
- {
- var name = new TextBlock { Text = unit.Name, FontSize = 13.5, VerticalAlignment = VerticalAlignment.Center };
- if (highlighted)
- name.FontWeight = FontWeight.SemiBold;
- var math = Ui.Math(Units.Format(value) + " " + Text(unit.Symbol), 17);
- math.HorizontalAlignment = HorizontalAlignment.Left;
- math.VerticalAlignment = VerticalAlignment.Center;
- Grid.SetColumn(math, 1);
- return new Grid { ColumnDefinitions = new ColumnDefinitions("220,*"), MinHeight = 32, Children = { name, math } };
- }
-
- // a symbol as text of UnicodeMath, upright and kept as it is (a quote in it is not in any symbol), after a
- // no-break space that separates it from the number (the space of UnicodeMath before it ends an exponent, and is
- // not drawn)
- private static string Text(string symbol) => "\"\u00A0" + symbol + "\"";
-
- private static StackPanel Field(string label, Control control)
- {
- var text = Ui.Muted(label, 12.5);
- text.VerticalAlignment = VerticalAlignment.Center;
- return new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Children = { text, control } };
- }
- }
-}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/AlgebraViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/AlgebraViewModel.cs
new file mode 100644
index 0000000..fd21c80
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/AlgebraViewModel.cs
@@ -0,0 +1,352 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using System.Windows.Input;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ /// A letter defined, as a definition: a ≔ 3, drawn when it can be read and written otherwise.
+ public sealed record AlgebraDefinition(Equation? Math, string Text);
+
+ /// A line of the results of the calculator: the result of an action with its label, or why there is none.
+ public sealed class AlgebraItem
+ {
+ internal AlgebraItem(string message) => Message = message;
+
+ internal AlgebraItem(CasResult result, string label)
+ {
+ Result = result;
+ Label = label;
+ }
+
+ /// Why there is no result, or null.
+ public string? Message { get; }
+
+ /// The result, or null for a message.
+ public CasResult? Result { get; }
+
+ /// What was done: Solve for x.
+ public string? Label { get; }
+
+ public bool IsResult => Result != null;
+
+ /// The result, to draw; null when it is only text.
+ public Equation? Math => Result?.Math;
+
+ /// The result as text, when it cannot be drawn.
+ public string? Text => Result is { Math: null } ? Result.Text : null;
+
+ /// The decimal values of the result, to draw.
+ public Equation? Approximate => Result?.Approximate;
+
+ /// The decimal values as text, when they cannot be drawn.
+ public string? ApproximateText => Result is { Approximate: null } ? Result.ApproximateText : null;
+ }
+
+ ///
+ /// What the calculator computes from the equation of the editor, with a computer algebra system ( ):
+ /// its value as it is typed, and on demand its solutions, its simplified, expanded or factored form, its derivative
+ /// and its integral, each result ready to go back to the editor.
+ ///
+ public sealed class AlgebraViewModel : ObservableObject
+ {
+ private const int Kept = 8;
+
+ private static readonly TimeSpan Delay = TimeSpan.FromMilliseconds(300);
+ private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
+
+ private readonly List history = new List();
+ private Equation? equation;
+ private IReadOnlyList letters = Array.Empty();
+ private string? letter;
+ private int angleIndex;
+ private CasResult? answer;
+ private string? answerNote;
+ private IReadOnlyList definitions = Array.Empty();
+ private int version;
+ private int scheduled;
+
+ public AlgebraViewModel(ICasEngine engine)
+ {
+ Engine = engine;
+ angleIndex = engine.Angles == AngleUnit.Degrees ? 1 : 0;
+ RunCommand = new RelayCommand(async action => await RunAsync((CasAction)action!).ConfigureAwait(true));
+ GraphCommand = new RelayCommand(() => RequestGraph());
+ ForgetCommand = new RelayCommand(async () =>
+ {
+ Engine.ClearDefinitions();
+ ShowDefinitions();
+ await RefreshAnswer().ConfigureAwait(true);
+ });
+ UseCommand = new RelayCommand(math => Use(math as Equation));
+ ShowDefinitions();
+ ShowAnswer(null, "The value of what is typed shows here.");
+ }
+
+ /// Raised by the Graph button, with the equation of the editor to draw.
+ public event EventHandler? GraphRequested;
+
+ /// Raised with a result to put in the editor.
+ public event EventHandler? EditorRequested;
+
+ /// The computer algebra system, with the letters defined.
+ public ICasEngine Engine { get; }
+
+ /// The equation of the editor: its value is computed a moment after it changes.
+ public Equation? Equation
+ {
+ get => equation;
+ set
+ {
+ if (Set(ref equation, value))
+ Schedule();
+ }
+ }
+
+ /// The letters of the equation.
+ public IReadOnlyList Letters
+ {
+ get => letters;
+ private set => Set(ref letters, value);
+ }
+
+ /// The letter to solve for, and to differentiate and integrate by.
+ public string? Letter
+ {
+ get => letter;
+ set => Set(ref letter, value);
+ }
+
+ /// The units of the angles.
+ public IReadOnlyList AngleUnits { get; } = new[] { "Radians", "Degrees" };
+
+ /// The unit of the angles of sin, cos, tan and their inverses: 0 for radians, 1 for degrees.
+ public int AngleIndex
+ {
+ get => angleIndex;
+ set
+ {
+ if (value < 0 || !Set(ref angleIndex, value))
+ return;
+ Engine.Angles = value == 1 ? AngleUnit.Degrees : AngleUnit.Radians;
+ _ = RefreshAnswer();
+ }
+ }
+
+ /// The value of the equation of the editor, as it was last computed.
+ public CasResult? Answer
+ {
+ get => answer;
+ private set
+ {
+ if (Set(ref answer, value))
+ OnPropertyChanged(nameof(AnswerMath));
+ }
+ }
+
+ /// The value, to draw.
+ public Equation? AnswerMath => answer?.Math;
+
+ /// The value as text when it cannot be drawn, or why there is none.
+ public string? AnswerNote
+ {
+ get => answerNote;
+ private set => Set(ref answerNote, value);
+ }
+
+ /// The letters defined.
+ public IReadOnlyList Definitions
+ {
+ get => definitions;
+ private set
+ {
+ if (Set(ref definitions, value))
+ OnPropertyChanged(nameof(HasDefinitions));
+ }
+ }
+
+ public bool HasDefinitions => definitions.Count > 0;
+
+ /// The results of the actions and the messages, the last first.
+ public ObservableCollection Items { get; } = new ObservableCollection();
+
+ /// The results of the actions, the last first.
+ public IReadOnlyList Results => history;
+
+ /// Does an action (a ) to the equation of the editor.
+ public ICommand RunCommand { get; }
+
+ /// Sends the equation of the editor to be drawn.
+ public ICommand GraphCommand { get; }
+
+ /// Forgets the letters defined.
+ public ICommand ForgetCommand { get; }
+
+ /// Puts a result (an ) in the editor.
+ public ICommand UseCommand { get; }
+
+ /// Sends the equation of the editor to be drawn, as the Graph button does; false when it cannot be read.
+ public bool RequestGraph()
+ {
+ if (!TryRead(out var read, out _, out var error))
+ {
+ AddMessage(error!);
+ return false;
+ }
+ GraphRequested?.Invoke(this, read!);
+ return true;
+ }
+
+ /// Puts a result in the editor.
+ public void Use(Equation? math)
+ {
+ if (math != null)
+ EditorRequested?.Invoke(this, math);
+ }
+
+ /// Computes the value of the equation of the editor now, as typing does after a pause.
+ public async Task RefreshAnswer()
+ {
+ scheduled++;
+ var current = ++version;
+ if (!TryRead(out var read, out var found, out var error))
+ {
+ UpdateLetters(Array.Empty());
+ ShowAnswer(null, error);
+ return;
+ }
+ UpdateLetters(found);
+ var (result, message) = await Compute(CasAction.Evaluate, read!, null).ConfigureAwait(true);
+ if (current == version)
+ ShowAnswer(result, message);
+ }
+
+ /// Does an action to the equation of the editor, as its button does, and adds the result to the list.
+ public async Task RunAsync(CasAction action)
+ {
+ if (!TryRead(out var read, out _, out var error))
+ {
+ AddMessage(error!);
+ return null;
+ }
+ var by = letter;
+ var (result, message) = await Compute(action, read!, by).ConfigureAwait(true);
+ if (result == null)
+ {
+ AddMessage(message!);
+ return null;
+ }
+ if (action == CasAction.Define)
+ {
+ ShowDefinitions();
+ await RefreshAnswer().ConfigureAwait(true);
+ }
+ history.Insert(0, result);
+ Add(new AlgebraItem(result, Label(action, by ?? "x")));
+ return result;
+ }
+
+ // the value, a moment after the last change of the equation
+ private async void Schedule()
+ {
+ var current = ++scheduled;
+ await Task.Delay(Delay).ConfigureAwait(true);
+ if (current == scheduled)
+ await RefreshAnswer().ConfigureAwait(true);
+ }
+
+ private bool TryRead(out Equation? read, out IReadOnlyList found, out string? error)
+ {
+ found = Array.Empty();
+ error = null;
+ read = equation;
+ if (read == null)
+ {
+ error = "The value of what is typed shows here.";
+ return false;
+ }
+ if (read.ToMathML().Descendants().Any(e => e.Name.LocalName == "merror"))
+ {
+ error = "Not built up yet: finish the argument, or press Build up (Enter).";
+ return false;
+ }
+ try
+ {
+ found = Engine.Variables(read);
+ return true;
+ }
+ catch (NotSupportedException e)
+ {
+ error = e.Message;
+ return false;
+ }
+ }
+
+ // on another thread, since the engine can take long (it cannot be stopped: a result too late is dropped)
+ private async Task<(CasResult? Result, string? Message)> Compute(CasAction action, Equation read, string? by)
+ {
+ var work = Task.Run(() => Engine.Run(action, read, by));
+ if (await Task.WhenAny(work, Task.Delay(Timeout)).ConfigureAwait(true) != work)
+ return (null, "It takes too long: " + Engine.Name + " found no result in " + Timeout.TotalSeconds + " seconds.");
+ try
+ {
+ return (await work.ConfigureAwait(true), null);
+ }
+#pragma warning disable CA1031 // what the engine cannot do, it says with exceptions of many kinds
+ catch (Exception e)
+#pragma warning restore CA1031
+ {
+ return (null, Engine.Name + " cannot do it: " + e.Message);
+ }
+ }
+
+ private void UpdateLetters(IReadOnlyList found)
+ {
+ if (letters.SequenceEqual(found))
+ return;
+ // the list of the view forgets its letter when its letters change: the letter is given again after them
+ var selected = letter != null && found.Contains(letter) ? letter : found.Count > 0 ? found[0] : null;
+ Letters = found;
+ letter = selected;
+ OnPropertyChanged(nameof(Letter));
+ }
+
+ private void ShowAnswer(CasResult? result, string? message)
+ {
+ Answer = result;
+ AnswerNote = result == null ? message : result.Math == null ? result.Text : null;
+ }
+
+ // the letters defined, as a definition each: a ≔ 3
+ private void ShowDefinitions()
+ {
+ Definitions = Engine.Definitions.OrderBy(d => d.Key, StringComparer.Ordinal).Select(d =>
+ {
+ var text = d.Key + "≔" + d.Value.ToString(EquationFormat.UnicodeMath);
+ return new AlgebraDefinition(SharpEquations.Equation.TryParse(text, EquationFormat.UnicodeMath, out var math) ? math : null, text);
+ }).ToList();
+ }
+
+ private void AddMessage(string message) => Add(new AlgebraItem(message));
+
+ private void Add(AlgebraItem item)
+ {
+ Items.Insert(0, item);
+ while (Items.Count > Kept)
+ Items.RemoveAt(Items.Count - 1);
+ }
+
+ private static string Label(CasAction action, string by) => action switch
+ {
+ CasAction.Solve => "Solve for " + by,
+ CasAction.Differentiate => "Derivative by " + by,
+ CasAction.Integrate => "Antiderivative by " + by,
+ CasAction.Define => "Defined",
+ _ => action.ToString(),
+ };
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/CalculatorKeys.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/CalculatorKeys.cs
similarity index 95%
rename from samples/SharpEquations.Avalonia.MathTools.Demo/CalculatorKeys.cs
rename to samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/CalculatorKeys.cs
index 5faec2b..f87b8a4 100644
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/CalculatorKeys.cs
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/CalculatorKeys.cs
@@ -23,6 +23,11 @@ public CalculatorKey(string face, string tip, Action press, bool isM
public Action Press { get; }
public bool IsMath { get; }
+
+ /// The face of the key as an equation, to draw; null when it is plain text.
+ public SharpEquations.Equation? Math => math ??= IsMath ? SharpEquations.Equation.Parse(Face, SharpEquations.EquationFormat.UnicodeMath) : null;
+
+ private SharpEquations.Equation? math;
}
///
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/CalculatorViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/CalculatorViewModel.cs
new file mode 100644
index 0000000..f889a0a
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/CalculatorViewModel.cs
@@ -0,0 +1,82 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ ///
+ /// The scientific keypad: the keys the view types into its equation editor, the equation as UnicodeMath and LaTeX,
+ /// and what is computed from it.
+ ///
+ public sealed class CalculatorViewModel : ObservableObject
+ {
+ private Equation? equation;
+ private string? unicodeMath;
+ private string? latex;
+
+ public CalculatorViewModel(ICasEngine engine)
+ {
+ ArgumentNullException.ThrowIfNull(engine);
+ Solver = new AlgebraViewModel(engine);
+ Solver.EditorRequested += (_, math) => Open(math);
+ ComputeCaption = "With " + engine.Name + ": the value of what is typed, and its solutions, simpler forms, derivative and antiderivative";
+ }
+
+ /// Raised when the editor should take the focus: an equation was put in it.
+ public event EventHandler? FocusRequested;
+
+ /// The functions, powers, structures and constants.
+ public IReadOnlyList Functions { get; } = CalculatorKeys.Functions;
+
+ /// The digits, the operators, the brackets and the variables.
+ public IReadOnlyList Numbers { get; } = CalculatorKeys.Numbers;
+
+ /// The keys that move the caret, delete, undo and build up.
+ public IReadOnlyList Editing { get; } = CalculatorKeys.Editing;
+
+ /// What is computed from the equation.
+ public AlgebraViewModel Solver { get; }
+
+ /// What the computer algebra system does, with its name.
+ public string ComputeCaption { get; }
+
+ /// The equation of the editor.
+ public Equation? Equation
+ {
+ get => equation;
+ set
+ {
+ if (!Set(ref equation, value))
+ return;
+ // text that is not built up yet (sin( waiting for its argument) is an merror of the equation
+ var complete = value != null && !value.ToMathML().Descendants().Any(e => e.Name.LocalName == "merror");
+ UnicodeMath = complete ? value!.ToString(EquationFormat.UnicodeMath) : null;
+ LaTeX = complete ? value!.ToString(EquationFormat.LaTeX) : null;
+ Solver.Equation = value;
+ }
+ }
+
+ /// The equation as UnicodeMath, or null while it is not built up.
+ public string? UnicodeMath
+ {
+ get => unicodeMath;
+ private set => Set(ref unicodeMath, value);
+ }
+
+ /// The equation as LaTeX, or null while it is not built up.
+ public string? LaTeX
+ {
+ get => latex;
+ private set => Set(ref latex, value);
+ }
+
+ /// Puts an equation in the editor, which takes the focus.
+ public void Open(Equation? math)
+ {
+ Equation = math;
+ FocusRequested?.Invoke(this, EventArgs.Empty);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/FormulasViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/FormulasViewModel.cs
new file mode 100644
index 0000000..a4726e9
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/FormulasViewModel.cs
@@ -0,0 +1,143 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Windows.Input;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ /// A subject of the library, or all of them (no name).
+ public sealed record FormulaSubject(string? Name)
+ {
+ /// The name shown.
+ public string Title => Name ?? "All";
+ }
+
+ /// A formula of the library as the page shows it.
+ public sealed class FormulaItem : ObservableObject
+ {
+ private bool isVisible = true;
+
+ internal FormulaItem(Formula formula, bool hasGraph, ICommand openCommand, ICommand graphCommand)
+ {
+ Formula = formula;
+ Caption = formula.Subject.ToUpperInvariant() + " · " + formula.Name;
+ Equation = Equation.Parse(formula.UnicodeMath, EquationFormat.UnicodeMath, new EquationOptions { Display = true });
+ HasGraph = hasGraph;
+ OpenCommand = openCommand;
+ GraphCommand = graphCommand;
+ }
+
+ public Formula Formula { get; }
+
+ /// The subject and the name of the formula.
+ public string Caption { get; }
+
+ /// The formula, to draw.
+ public Equation Equation { get; }
+
+ /// Whether the formula has a graph the page can draw.
+ public bool HasGraph { get; }
+
+ /// Opens the formula in the calculator.
+ public ICommand OpenCommand { get; }
+
+ /// Draws the graph of the formula.
+ public ICommand GraphCommand { get; }
+
+ /// Whether the subject and the search show the formula.
+ public bool IsVisible
+ {
+ get => isVisible;
+ internal set => Set(ref isVisible, value);
+ }
+ }
+
+ ///
+ /// The library of formulas, filtered by subject and by name: one opens in the calculator, and the ones with a graph
+ /// are drawn on the page of the graphs.
+ ///
+ public sealed class FormulasViewModel : ObservableObject
+ {
+ private static readonly EquationOptions Display = new EquationOptions { Display = true };
+
+ private readonly bool graphs;
+ private FormulaSubject subject;
+ private string? search;
+
+ /// Whether the graphs of the formulas can be drawn; without it, no formula has a button for its graph.
+ public FormulasViewModel(bool graphs = true)
+ {
+ this.graphs = graphs;
+ Subjects = new[] { new FormulaSubject(null) }.Concat(Formulas.Subjects.Select(name => new FormulaSubject(name))).ToList();
+ subject = Subjects[0];
+ Items = Formulas.All.Select(formula => new FormulaItem(formula, graphs && formula.Graph != null, new RelayCommand(() => Open(formula)), new RelayCommand(() => Graph(formula)))).ToList();
+ }
+
+ /// Raised with the formula to open in the calculator.
+ public event EventHandler? OpenRequested;
+
+ /// Raised with the graph of a formula to draw.
+ public event EventHandler? GraphRequested;
+
+ /// All the subjects, then each of them.
+ public IReadOnlyList Subjects { get; }
+
+ /// The subject shown.
+ public FormulaSubject Subject
+ {
+ get => subject;
+ set
+ {
+ if (value != null && Set(ref subject, value))
+ Filter();
+ }
+ }
+
+ /// The text searched: the formulas whose name or subject contain it are shown.
+ public string? Search
+ {
+ get => search;
+ set
+ {
+ if (Set(ref search, value))
+ Filter();
+ }
+ }
+
+ /// The formulas.
+ public IReadOnlyList Items { get; }
+
+ /// The formulas shown, after the subject and the search.
+ public IEnumerable Shown => Items.Where(item => item.IsVisible).Select(item => item.Formula);
+
+
+ /// Shows the formulas of a subject, or all of them for null.
+ public void ShowSubject(string? name) => Subject = Subjects.Single(s => s.Name == name);
+
+ /// Opens a formula in the calculator, as a click on it does.
+ public void Open(Formula formula)
+ {
+ ArgumentNullException.ThrowIfNull(formula);
+ OpenRequested?.Invoke(this, Equation.Parse(formula.UnicodeMath, EquationFormat.UnicodeMath, Display));
+ }
+
+ /// Draws the graph of a formula, as its button does; false if it has none or the page draws no graphs.
+ public bool Graph(Formula formula)
+ {
+ ArgumentNullException.ThrowIfNull(formula);
+ if (formula.Graph == null || !graphs)
+ return false;
+ GraphRequested?.Invoke(this, formula.Graph);
+ return true;
+ }
+
+ private void Filter()
+ {
+ var shown = new HashSet(Formulas.Find(subject.Name, search));
+ foreach (var item in Items)
+ item.IsVisible = shown.Contains(item.Formula);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/MathToolsViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/MathToolsViewModel.cs
new file mode 100644
index 0000000..4025605
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/MathToolsViewModel.cs
@@ -0,0 +1,128 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System.Globalization;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ ///
+ /// The math tools, a page each: the scientific keypad around the equation editor, the library of formulas, the
+ /// unit converter, the solver of triangles, the graphs, the graphs in space and the worksheet. The desktop window
+ /// and the WebAssembly page show it with the services of their platform: where the settings are kept (the page
+ /// shown, the equation of the calculator, the unit of angles, the theme), and the computer algebra system.
+ ///
+ public sealed class MathToolsViewModel : ObservableObject
+ {
+ private const int CalculatorTab = 0;
+ private const int GraphsTab = 4;
+ private const int TabCount = 7;
+
+ private const string TabKey = "tab";
+ private const string EquationKey = "equation";
+ private const string ThemeKey = "theme";
+ private const string AnglesKey = "angles";
+
+ private readonly ISettingsStore settings;
+ private int selectedTab;
+
+ public MathToolsViewModel(ISettingsStore? settings = null, ICasEngine? engine = null)
+ {
+ this.settings = settings ?? new MemorySettingsStore();
+ Engine = engine ?? new AngouriMathEngine();
+ Calculator = new CalculatorViewModel(Engine);
+ FormulaLibrary = new FormulasViewModel();
+ Converter = new UnitsViewModel();
+ TriangleSolver = new TrianglesViewModel();
+ Graphs = new GraphsViewModel(Engine);
+ Space = new Graphs3DViewModel(Engine);
+ Worksheet = new WorksheetViewModel(Engine, this.settings);
+
+ FormulaLibrary.OpenRequested += (_, equation) =>
+ {
+ SelectedTab = CalculatorTab;
+ Calculator.Open(equation);
+ };
+ FormulaLibrary.GraphRequested += (_, preset) =>
+ {
+ Graphs.AddPreset(preset, Engine.Angles);
+ SelectedTab = GraphsTab;
+ };
+ Calculator.Solver.GraphRequested += (_, equation) => ShowGraph(equation);
+ Worksheet.GraphRequested += (_, equation) => ShowGraph(equation);
+
+ Restore();
+ Calculator.PropertyChanged += (_, e) =>
+ {
+ if (e.PropertyName == nameof(CalculatorViewModel.Equation))
+ this.settings.Set(EquationKey, Calculator.Equation?.ToString(EquationFormat.UnicodeMath));
+ };
+ Calculator.Solver.PropertyChanged += (_, e) =>
+ {
+ if (e.PropertyName == nameof(AlgebraViewModel.AngleIndex))
+ this.settings.Set(AnglesKey, Calculator.Solver.AngleIndex == 1 ? "degrees" : "radians");
+ };
+ }
+
+ /// The computer algebra system of the calculator.
+ public ICasEngine Engine { get; }
+
+ /// The scientific keypad.
+ public CalculatorViewModel Calculator { get; }
+
+ /// The library of formulas.
+ public FormulasViewModel FormulaLibrary { get; }
+
+ /// The unit converter.
+ public UnitsViewModel Converter { get; }
+
+ /// The solver of triangles.
+ public TrianglesViewModel TriangleSolver { get; }
+
+ /// The graphs.
+ public GraphsViewModel Graphs { get; }
+
+ /// The graphs in space.
+ public Graphs3DViewModel Space { get; }
+
+ /// The worksheet, the history of what was computed.
+ public WorksheetViewModel Worksheet { get; }
+
+ /// The page shown.
+ public int SelectedTab
+ {
+ get => selectedTab;
+ set
+ {
+ if (value >= 0 && Set(ref selectedTab, value))
+ settings.Set(TabKey, value.ToString(CultureInfo.InvariantCulture));
+ }
+ }
+
+ /// The theme of the last session: dark, light, or null for the one of the system.
+ public bool? IsDark => settings.Get(ThemeKey) switch
+ {
+ "dark" => true,
+ "light" => false,
+ _ => null,
+ };
+
+ /// Keeps the theme chosen for the next session.
+ public void KeepTheme(bool dark) => settings.Set(ThemeKey, dark ? "dark" : "light");
+
+ // the page, the equation and the unit of the angles of the last session
+ private void Restore()
+ {
+ if (int.TryParse(settings.Get(TabKey), NumberStyles.None, CultureInfo.InvariantCulture, out var tab) && tab < TabCount)
+ selectedTab = tab;
+ if (settings.Get(EquationKey) is { } text && Equation.TryParse(text, EquationFormat.UnicodeMath, new EquationOptions { Display = true }, out var equation))
+ Calculator.Equation = equation;
+ if (settings.Get(AnglesKey) == "degrees")
+ Calculator.Solver.AngleIndex = 1;
+ }
+
+ private void ShowGraph(Equation equation)
+ {
+ Graphs.AddEquation(equation, Engine.Angles, Engine.Definitions);
+ SelectedTab = GraphsTab;
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/ObservableObject.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/ObservableObject.cs
new file mode 100644
index 0000000..67fcb87
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/ObservableObject.cs
@@ -0,0 +1,53 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.ComponentModel;
+ using System.Runtime.CompilerServices;
+ using System.Windows.Input;
+
+ /// The base of the view models: it tells the view which of its properties changed.
+ public abstract class ObservableObject : INotifyPropertyChanged
+ {
+ ///
+ public event PropertyChangedEventHandler? PropertyChanged;
+
+ protected void OnPropertyChanged([CallerMemberName] string? name = null) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
+
+ /// Gives a field its new value; true, after telling the view, when it changed.
+ protected bool Set(ref T field, T value, [CallerMemberName] string? name = null)
+ {
+ if (EqualityComparer.Default.Equals(field, value))
+ return false;
+ field = value;
+ OnPropertyChanged(name);
+ return true;
+ }
+ }
+
+ /// A command of a view model: what a button of the view does, with the parameter the view gives it.
+ public sealed class RelayCommand : ICommand
+ {
+ private readonly Action execute;
+
+ public RelayCommand(Action execute)
+ : this(_ => execute())
+ {
+ }
+
+ public RelayCommand(Action execute) => this.execute = execute;
+
+ ///
+ public event EventHandler? CanExecuteChanged
+ {
+ add { }
+ remove { }
+ }
+
+ ///
+ public bool CanExecute(object? parameter) => true;
+
+ ///
+ public void Execute(object? parameter) => execute(parameter);
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/PlotsViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/PlotsViewModel.cs
new file mode 100644
index 0000000..27060ea
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/PlotsViewModel.cs
@@ -0,0 +1,312 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Collections.ObjectModel;
+ using System.Globalization;
+ using System.Linq;
+ using System.Windows.Input;
+ using global::Avalonia.Media;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ /// A parameter of a graph, a letter that is not one of its variables: the slider of the view moves its value.
+ public sealed class PlotParameter : ObservableObject
+ {
+ private readonly Action changed;
+ private double minimum = -10;
+ private double maximum = 10;
+ private double value;
+
+ internal PlotParameter(string name, double value, Action changed)
+ {
+ Name = name;
+ this.value = value;
+ this.changed = changed;
+ }
+
+ public string Name { get; }
+
+ public double Minimum
+ {
+ get => minimum;
+ set => Set(ref minimum, value);
+ }
+
+ public double Maximum
+ {
+ get => maximum;
+ set => Set(ref maximum, value);
+ }
+
+ public double Value
+ {
+ get => value;
+ set
+ {
+ if (!Set(ref this.value, value))
+ return;
+ OnPropertyChanged(nameof(Text));
+ changed(this);
+ }
+ }
+
+ /// The parameter and its value: a = 0.5.
+ public string Text => Name + " = " + value.ToString("0.##", CultureInfo.InvariantCulture);
+ }
+
+ /// A graph drawn: its equation, its color and its parameters.
+ public sealed class PlotItem
+ {
+ internal PlotItem(object graph, Equation equation, Color color, IReadOnlyList parameters, ICommand removeCommand)
+ {
+ Graph = graph;
+ Equation = equation;
+ Color = color;
+ Parameters = parameters;
+ RemoveCommand = removeCommand;
+ }
+
+ /// What the view draws: a in the plane, a in space.
+ public object Graph { get; }
+
+ public Equation Equation { get; }
+
+ public Color Color { get; }
+
+ /// The color, to fill the mark of the graph.
+ public IBrush Brush => new global::Avalonia.Media.Immutable.ImmutableSolidColorBrush(Color);
+
+ public IReadOnlyList Parameters { get; }
+
+ /// Removes the graph.
+ public ICommand RemoveCommand { get; }
+
+ /// The parameter of a letter.
+ public PlotParameter this[string name] => Parameters.Single(p => p.Name == name);
+ }
+
+ ///
+ /// Graphs drawn together: equations typed in an editor (or sent by the calculator), each in its color, with a
+ /// parameter for each of their letters that are not variables of the graph.
+ ///
+ public abstract class PlotsViewModel : ObservableObject
+ {
+ private static readonly Color[] Palette =
+ {
+ Color.FromRgb(0x25, 0x63, 0xEB),
+ Color.FromRgb(0xDC, 0x26, 0x26),
+ Color.FromRgb(0x05, 0x96, 0x69),
+ Color.FromRgb(0xD9, 0x77, 0x06),
+ Color.FromRgb(0x7C, 0x3A, 0xED),
+ Color.FromRgb(0xDB, 0x27, 0x77),
+ };
+
+ private readonly ICasEngine? engine;
+ private readonly string noGraph;
+ private Equation? equation;
+ private bool sharedParameters;
+ private string? error;
+ private int added;
+ private bool sharing;
+
+ /// The computer algebra system whose unit of angles and letters defined the Add command takes.
+ /// The equation of the editor at first, as UnicodeMath.
+ /// What is told of an equation that has no graph.
+ protected PlotsViewModel(ICasEngine? engine, string initial, string noGraph)
+ {
+ this.engine = engine;
+ this.noGraph = noGraph;
+ equation = Equation.Parse(initial, EquationFormat.UnicodeMath, Display);
+ AddCommand = new RelayCommand(() =>
+ {
+ if (Equation is { } typed)
+ AddEquation(typed, engine?.Angles ?? AngleUnit.Radians, engine?.Definitions);
+ });
+ ClearCommand = new RelayCommand(Clear);
+ ResetCommand = new RelayCommand(() => ResetRequested?.Invoke(this, EventArgs.Empty));
+ }
+
+ /// Raised when the graphs are to be drawn again: a parameter changed.
+ public event EventHandler? RedrawRequested;
+
+ /// Raised when the view is to show the region around the origin again.
+ public event EventHandler? ResetRequested;
+
+ /// The equation of the editor, the one to add.
+ public Equation? Equation
+ {
+ get => equation;
+ set => Set(ref equation, value);
+ }
+
+ /// The graphs drawn.
+ public ObservableCollection Items { get; } = new ObservableCollection();
+
+ /// Whether a letter is one parameter for every graph with it (its values move together) or one per graph.
+ public bool SharedParameters
+ {
+ get => sharedParameters;
+ set
+ {
+ if (!Set(ref sharedParameters, value) || !value)
+ return;
+ foreach (var first in Items.SelectMany(i => i.Parameters).GroupBy(p => p.Name).Select(g => g.First()).ToList())
+ Share(first.Name, first.Value);
+ }
+ }
+
+ /// Why the last equation was not drawn, or null.
+ public string? Error
+ {
+ get => error;
+ private set => Set(ref error, value);
+ }
+
+ /// Draws the equation of the editor.
+ public ICommand AddCommand { get; }
+
+ /// Removes every graph.
+ public ICommand ClearCommand { get; }
+
+ /// Shows the region around the origin again.
+ public ICommand ResetCommand { get; }
+
+ protected static EquationOptions Display { get; } = new EquationOptions { Display = true };
+
+ /// Draws an equation; false, with , when it has no graph.
+ public bool AddEquation(Equation equation, AngleUnit angles = AngleUnit.Radians, IReadOnlyDictionary? definitions = null)
+ {
+ ArgumentNullException.ThrowIfNull(equation);
+ var color = Palette[added % Palette.Length];
+ object graph;
+ IReadOnlyList names;
+ Func get;
+ Action set;
+ try
+ {
+ (graph, names, get, set) = Create(equation, angles, definitions, color);
+ }
+#pragma warning disable CA1031 // what the equation cannot draw is told, whatever it is
+ catch (Exception e)
+#pragma warning restore CA1031
+ {
+ Error = e is NotSupportedException ? e.Message : noGraph;
+ return false;
+ }
+
+ Error = null;
+ added++;
+ var parameters = names.Select(name => new PlotParameter(name, get(name), parameter =>
+ {
+ set(parameter.Name, parameter.Value);
+ if (!sharing && sharedParameters)
+ Share(parameter.Name, parameter.Value);
+ RedrawRequested?.Invoke(this, EventArgs.Empty);
+ })).ToList();
+ PlotItem? item = null;
+ item = new PlotItem(graph, equation, color, parameters, new RelayCommand(() => Items.Remove(item!)));
+ if (sharedParameters)
+ {
+ // a letter already drawn keeps its value
+ foreach (var parameter in parameters)
+ {
+ if (Items.SelectMany(i => i.Parameters).FirstOrDefault(p => p.Name == parameter.Name) is { } other)
+ parameter.Value = other.Value;
+ }
+ }
+ Items.Add(item);
+ return true;
+ }
+
+ /// Removes every graph.
+ public void Clear()
+ {
+ Items.Clear();
+ added = 0;
+ }
+
+ /// Asks the view to draw the graphs again.
+ protected void Redraw() => RedrawRequested?.Invoke(this, EventArgs.Empty);
+
+ ///
+ /// Reads an equation as a graph in a color: what the view draws, the letters that are its parameters, and how
+ /// the value of one is read and changed. It throws when the equation has no graph.
+ ///
+ protected abstract (object Graph, IReadOnlyList Parameters, Func Get, Action Set) Create(
+ Equation equation, AngleUnit angles, IReadOnlyDictionary? definitions, Color color);
+
+ // the parameters of a letter, on every graph, to a value
+ private void Share(string name, double value)
+ {
+ sharing = true;
+ try
+ {
+ foreach (var parameter in Items.SelectMany(i => i.Parameters).Where(p => p.Name == name))
+ parameter.Value = value;
+ }
+ finally
+ {
+ sharing = false;
+ }
+ }
+ }
+
+ /// The graphs in the plane.
+ public sealed class GraphsViewModel : PlotsViewModel
+ {
+ public GraphsViewModel(ICasEngine? engine = null)
+ : base(engine, "y=sin(a x)", "This equation has no graph.")
+ {
+ }
+
+ ///
+ /// Draws the graph of a formula of the library, with its parameters at their starting values; false, with
+ /// , when it has no graph.
+ ///
+ public bool AddPreset(GraphPreset preset, AngleUnit angles = AngleUnit.Radians)
+ {
+ ArgumentNullException.ThrowIfNull(preset);
+ if (!AddEquation(Equation.Parse(preset.UnicodeMath, EquationFormat.UnicodeMath, Display), angles))
+ return false;
+ var item = Items[^1];
+ var curve = (GraphCurve)item.Graph;
+ foreach (var (parameter, value) in preset.Values)
+ {
+ var name = MathReader.Symbol(parameter);
+ if (item.Parameters.FirstOrDefault(p => p.Name == name) is { } slider)
+ {
+ slider.Minimum = Math.Min(slider.Minimum, value);
+ slider.Maximum = Math.Max(slider.Maximum, value);
+ slider.Value = value;
+ }
+ curve.Plot[name] = value;
+ }
+ Redraw();
+ return true;
+ }
+
+ protected override (object Graph, IReadOnlyList Parameters, Func Get, Action Set) Create(
+ Equation equation, AngleUnit angles, IReadOnlyDictionary? definitions, Color color)
+ {
+ var plot = GraphPlot.FromEquation(equation, angles, definitions);
+ return (new GraphCurve(equation, plot, color), plot.Parameters, name => plot[name], (name, value) => plot[name] = value);
+ }
+ }
+
+ /// The graphs in space.
+ public sealed class Graphs3DViewModel : PlotsViewModel
+ {
+ public Graphs3DViewModel(ICasEngine? engine = null)
+ : base(engine, "z=sin x cos y", "This equation has no graph in space.")
+ {
+ }
+
+ protected override (object Graph, IReadOnlyList Parameters, Func Get, Action Set) Create(
+ Equation equation, AngleUnit angles, IReadOnlyDictionary? definitions, Color color)
+ {
+ var plot = SurfacePlot.FromEquation(equation, angles, definitions);
+ return (new SurfaceGraph(equation, plot, color), plot.Parameters, name => plot[name], (name, value) => plot[name] = value);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/TrianglesViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/TrianglesViewModel.cs
new file mode 100644
index 0000000..9eaf4d0
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/TrianglesViewModel.cs
@@ -0,0 +1,199 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Windows.Input;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ /// A field of the solver of triangles: a side or an angle, with its letter and what is typed in it.
+ public sealed class TriangleInput : ObservableObject
+ {
+ private readonly Action changed;
+ private string? text;
+
+ internal TriangleInput(string name, string unit, Action changed)
+ {
+ Name = Equation.Parse(name, EquationFormat.UnicodeMath);
+ Unit = unit;
+ this.changed = changed;
+ }
+
+ /// The letter of the side or of the angle.
+ public Equation Name { get; }
+
+ /// The unit written after the field: ° for an angle.
+ public string Unit { get; }
+
+ /// What is typed.
+ public string? Text
+ {
+ get => text;
+ set
+ {
+ if (Set(ref text, value))
+ changed();
+ }
+ }
+ }
+
+ /// Values that fill the fields of the solver.
+ public sealed record TriangleExample(string Name, IReadOnlyList Values, ICommand FillCommand);
+
+ /// A measure of a triangle found: its name and its value.
+ public sealed record TriangleMeasure(string Name, Equation Value);
+
+ /// A triangle found: its sides, its angles and its measures, and the triangle to draw.
+ public sealed record TriangleResult(string? Title, Equation Sides, Equation Angles, IReadOnlyList Measures, Triangle Triangle);
+
+ ///
+ /// The solver of triangles: three of the sides and angles give the others, the area, the perimeter and the radii of
+ /// the circles, with the laws used, written in UnicodeMath for the view to draw.
+ ///
+ public sealed class TrianglesViewModel : ObservableObject
+ {
+ private static readonly string[] Empty = { "", "", "", "", "", "" };
+
+ private TriangleSolution? solution;
+ private IReadOnlyList results = Array.Empty();
+ private IReadOnlyList steps = Array.Empty();
+ private bool updating;
+
+ public TrianglesViewModel()
+ {
+ Sides = Triangles.SideNames.Select(name => new TriangleInput(name, "", Solve)).ToList();
+ Angles = Triangles.AngleNames.Select(name => new TriangleInput(name, "°", Solve)).ToList();
+ Inputs = Sides.Concat(Angles).ToList();
+ ClearCommand = new RelayCommand(() => Fill(Empty));
+ Examples = new[]
+ {
+ Example("3, 4, 5", "3", "4", "5", "", "", ""),
+ Example("SAS", "7", "", "9", "", "60", ""),
+ Example("ASA", "", "", "10", "45", "75", ""),
+ Example("Two triangles", "6", "8", "", "40", "", ""),
+ Example("No triangle", "1", "2", "4", "", "", ""),
+ };
+ Fill(Examples[0].Values);
+ }
+
+ private TriangleExample Example(string name, params string[] values) => new TriangleExample(name, values, new RelayCommand(() => Fill(values)));
+
+ /// The fields of a, b and c.
+ public IReadOnlyList Sides { get; }
+
+ /// The fields of α, β and γ.
+ public IReadOnlyList Angles { get; }
+
+ /// The fields of a, b, c, α, β and γ.
+ public IReadOnlyList Inputs { get; }
+
+ /// The examples that fill the fields.
+ public IReadOnlyList Examples { get; }
+
+ /// Empties the fields.
+ public ICommand ClearCommand { get; }
+
+ /// The solution of the values in the fields.
+ public TriangleSolution? Solution
+ {
+ get => solution;
+ private set
+ {
+ if (!Set(ref solution, value))
+ return;
+ OnPropertyChanged(nameof(Error));
+ OnPropertyChanged(nameof(HasTwoTriangles));
+ OnPropertyChanged(nameof(Case));
+ OnPropertyChanged(nameof(HasNoSteps));
+ }
+ }
+
+ /// Why there is no triangle, or null.
+ public string? Error => solution?.Error;
+
+ /// Whether two triangles have the values given.
+ public bool HasTwoTriangles => solution?.Triangles.Count == 2;
+
+ /// The case solved, with its name, or null.
+ public string? Case => solution?.Case is { } kind ? "Case " + kind + " (" + CaseName(kind) + ")" : null;
+
+ /// Whether no law was used: too few values.
+ public bool HasNoSteps => solution == null || solution.Steps.Count == 0;
+
+ /// The triangles found.
+ public IReadOnlyList Results
+ {
+ get => results;
+ private set => Set(ref results, value);
+ }
+
+ /// The laws that give the values found.
+ public IReadOnlyList Steps
+ {
+ get => steps;
+ private set => Set(ref steps, value);
+ }
+
+ /// Fills the fields, as the examples do.
+ public void Fill(IReadOnlyList values)
+ {
+ updating = true;
+ for (var i = 0; i < Inputs.Count; i++)
+ Inputs[i].Text = values[i];
+ updating = false;
+ Solve();
+ }
+
+ private void Solve()
+ {
+ if (updating)
+ return;
+
+ var values = new double?[Inputs.Count];
+ for (var i = 0; i < Inputs.Count; i++)
+ {
+ var text = Inputs[i].Text;
+ if (string.IsNullOrWhiteSpace(text))
+ continue;
+ if (!Units.TryParse(text!.TrimEnd('°', ' '), out var value))
+ {
+ Show(new TriangleSolution(null, Array.Empty(), Array.Empty(), "“" + text + "” is not a number."));
+ return;
+ }
+ values[i] = value;
+ }
+ Show(Triangles.Solve(values[0], values[1], values[2], values[3], values[4], values[5]));
+ }
+
+ private void Show(TriangleSolution found)
+ {
+ Results = found.Triangles.Select((triangle, index) => Result(triangle, found.Triangles.Count == 2 ? "Triangle " + (index + 1) : null)).ToList();
+ Steps = found.Steps.Select(Math).ToList();
+ Solution = found;
+ }
+
+ private static TriangleResult Result(Triangle triangle, string? title)
+ {
+ var (sides, angles) = Triangles.Describe(triangle);
+ return new TriangleResult(title, Math(sides), Math(angles), new[]
+ {
+ new TriangleMeasure("Area", Math(Units.Format(triangle.Area))),
+ new TriangleMeasure("Perimeter", Math(Units.Format(triangle.Perimeter))),
+ new TriangleMeasure("Circumradius", Math("R=" + Units.Format(triangle.Circumradius))),
+ new TriangleMeasure("Inradius", Math("r=" + Units.Format(triangle.Inradius))),
+ }, triangle);
+ }
+
+ private static Equation Math(string unicodeMath) => Equation.Parse(unicodeMath, EquationFormat.UnicodeMath);
+
+ private static string CaseName(string kind) => kind switch
+ {
+ "SSS" => "three sides",
+ "SAS" => "two sides and the angle between them",
+ "SSA" => "two sides and an angle not between them",
+ "ASA" => "two angles and the side between them",
+ _ => "two angles and a side not between them",
+ };
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/UnitsViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/UnitsViewModel.cs
new file mode 100644
index 0000000..644d9b2
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/UnitsViewModel.cs
@@ -0,0 +1,166 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Windows.Input;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ /// A line of the table of the converter: a unit, the value in it, and whether it is one of the two chosen.
+ public sealed record UnitLine(string Name, Equation Value, bool IsHighlighted);
+
+ ///
+ /// The unit converter: a value in a unit of a quantity, in another unit and in all of them, the results written in
+ /// UnicodeMath for the view to draw.
+ ///
+ public sealed class UnitsViewModel : ObservableObject
+ {
+ private static readonly EquationOptions Display = new EquationOptions { Display = true };
+
+ private Quantity quantity = Units.All[0];
+ private Unit? from;
+ private Unit? to;
+ private string? value = "1";
+ private string? result;
+ private Equation? resultEquation;
+ private IReadOnlyList lines = Array.Empty();
+ private string? message;
+ private bool updating;
+
+ public UnitsViewModel()
+ {
+ SwapCommand = new RelayCommand(Swap);
+ ShowQuantity();
+ }
+
+ /// The quantities: length, area, volume...
+ public IReadOnlyList Quantities { get; } = Units.All;
+
+ /// The quantity converted.
+ public Quantity Quantity
+ {
+ get => quantity;
+ set
+ {
+ // a list that changes its items gives null for a moment
+ if (value != null && Set(ref quantity, value))
+ ShowQuantity();
+ }
+ }
+
+ /// The units of the quantity.
+ public IReadOnlyList UnitList => quantity.Units;
+
+ /// The value, as it is typed.
+ public string? Value
+ {
+ get => value;
+ set
+ {
+ if (Set(ref this.value, value))
+ Refresh();
+ }
+ }
+
+ /// The unit of the value.
+ public Unit? From
+ {
+ get => from;
+ set
+ {
+ if (Set(ref from, value))
+ Refresh();
+ }
+ }
+
+ /// The unit the value is converted to.
+ public Unit? To
+ {
+ get => to;
+ set
+ {
+ if (Set(ref to, value))
+ Refresh();
+ }
+ }
+
+ /// The result, as UnicodeMath (1 " km"=0.621371 " mi" , with no-break spaces in the text), or null when the value is not a number.
+ public string? Result
+ {
+ get => result;
+ private set => Set(ref result, value);
+ }
+
+ /// The result, to draw.
+ public Equation? ResultEquation
+ {
+ get => resultEquation;
+ private set => Set(ref resultEquation, value);
+ }
+
+ /// The value in every unit of the quantity.
+ public IReadOnlyList Lines
+ {
+ get => lines;
+ private set => Set(ref lines, value);
+ }
+
+ /// What to type, when the value is not a number.
+ public string? Message
+ {
+ get => message;
+ private set => Set(ref message, value);
+ }
+
+ /// Swaps the units.
+ public ICommand SwapCommand { get; }
+
+ /// Swaps the units, as the ⇄ button does.
+ public void Swap()
+ {
+ var first = from;
+ updating = true;
+ From = to;
+ updating = false;
+ To = first;
+ }
+
+ private void ShowQuantity()
+ {
+ updating = true;
+ OnPropertyChanged(nameof(UnitList));
+ From = quantity.Units[0];
+ To = quantity.Units[1];
+ updating = false;
+ Refresh();
+ }
+
+ private void Refresh()
+ {
+ if (updating || from == null || to == null)
+ return;
+
+ if (!Units.TryParse(value, out var number))
+ {
+ Result = null;
+ ResultEquation = null;
+ Lines = Array.Empty();
+ Message = "Type a number, such as 12.5 or 1.5e3.";
+ return;
+ }
+
+ Message = null;
+ Result = Units.Format(number) + " " + Text(from.Symbol) + "=" + Units.Format(Units.Convert(number, from, to)) + " " + Text(to.Symbol);
+ ResultEquation = Equation.Parse(Result, EquationFormat.UnicodeMath, Display);
+ Lines = quantity.Units
+ .Select(unit => new UnitLine(unit.Name, Equation.Parse(Units.Format(Units.Convert(number, from, unit)) + " " + Text(unit.Symbol), EquationFormat.UnicodeMath), unit == from || unit == to))
+ .ToList();
+ }
+
+ // a symbol as text of UnicodeMath, upright and kept as it is (a quote in it is not in any symbol), after a
+ // no-break space that separates it from the number (the space of UnicodeMath before it ends an exponent, and is
+ // not drawn)
+ private static string Text(string symbol) => "\" " + symbol + "\"";
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/WorksheetViewModel.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/WorksheetViewModel.cs
new file mode 100644
index 0000000..a0fd5a4
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/ViewModels/WorksheetViewModel.cs
@@ -0,0 +1,245 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.Linq;
+ using System.Threading.Tasks;
+ using System.Windows.Input;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+
+ /// An entry of the worksheet as the page shows it: what was typed, what was done to it and the result.
+ public sealed class WorksheetItem
+ {
+ internal WorksheetItem(WorksheetEntry entry, int number, ICommand useCommand, ICommand graphCommand, ICommand removeCommand)
+ {
+ Entry = entry;
+ Title = number + ". " + entry.Label;
+ Input = entry.InputEquation;
+ Output = entry.OutputEquation;
+ UseCommand = useCommand;
+ GraphCommand = graphCommand;
+ RemoveCommand = removeCommand;
+ }
+
+ public WorksheetEntry Entry { get; }
+
+ /// The number of the entry and what was done: 2. Solve for x.
+ public string Title { get; }
+
+ /// What was typed, to draw.
+ public Equation Input { get; }
+
+ /// The result, to draw; null when it is only text.
+ public Equation? Output { get; }
+
+ public bool HasOutput => Output != null;
+
+ /// The result as text, when it cannot be drawn.
+ public string Text => Entry.Text;
+
+ /// How strong the text is written: paler for an entry that failed.
+ public double TextOpacity => Entry.Failed ? 0.75 : 1;
+
+ /// Puts the result in the editor.
+ public ICommand UseCommand { get; }
+
+ /// Draws what was typed on the page of the graphs.
+ public ICommand GraphCommand { get; }
+
+ /// Removes the entry.
+ public ICommand RemoveCommand { get; }
+ }
+
+ ///
+ /// The worksheet: what is computed, one entry after the other as on paper, each with what was typed, what was done
+ /// to it and the result, ready to go back to the editor or to be drawn. It is kept between sessions, with the
+ /// definitions it made.
+ ///
+ public sealed class WorksheetViewModel : ObservableObject
+ {
+ /// The key of the settings the worksheet is kept under.
+ public const string SettingsKey = "worksheet";
+
+ private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
+ private static readonly EquationOptions Display = new EquationOptions { Display = true };
+
+ private static readonly (CasAction Action, string Face)[] Faces =
+ {
+ (CasAction.Evaluate, "Evaluate"),
+ (CasAction.Solve, "Solve"),
+ (CasAction.Simplify, "Simplify"),
+ (CasAction.Expand, "Expand"),
+ (CasAction.Factor, "Factor"),
+ (CasAction.Differentiate, "Derivative"),
+ (CasAction.Integrate, "Antiderivative"),
+ (CasAction.Define, "Define"),
+ };
+
+ private readonly ICasEngine engine;
+ private Equation? equation = Equation.Parse("x^2-5x+6=0", EquationFormat.UnicodeMath, Display);
+ private int actionIndex = 1;
+ private IReadOnlyList letters = Array.Empty();
+ private string? letter;
+ private string message = "";
+ private IReadOnlyList items = Array.Empty();
+
+ public WorksheetViewModel(ICasEngine engine, ISettingsStore? settings = null)
+ {
+ this.engine = engine;
+ var store = settings ?? new MemorySettingsStore();
+ Sheet = Worksheet.Deserialize(store.Get(SettingsKey));
+ Sheet.Replay(engine);
+ Sheet.Changed += (_, _) =>
+ {
+ store.Set(SettingsKey, Sheet.Entries.Count == 0 ? null : Sheet.Serialize());
+ Show();
+ };
+ EnterCommand = new RelayCommand(async () => await EnterAsync().ConfigureAwait(true));
+ ClearCommand = new RelayCommand(Sheet.Clear);
+ UpdateLetters();
+ Show();
+ }
+
+ /// Raised by the Graph button of an entry, with the equation to draw.
+ public event EventHandler? GraphRequested;
+
+ /// Raised when the editor should take the focus: a result was put in it.
+ public event EventHandler? FocusRequested;
+
+ /// The entries.
+ public Worksheet Sheet { get; }
+
+ /// The equation of the editor, the next entry.
+ public Equation? Equation
+ {
+ get => equation;
+ set
+ {
+ if (Set(ref equation, value))
+ UpdateLetters();
+ }
+ }
+
+ /// What can be done to the equation of the editor.
+ public IReadOnlyList Actions { get; } = Faces.Select(f => f.Face).ToArray();
+
+ /// What is done to the equation of the editor, in .
+ public int ActionIndex
+ {
+ get => actionIndex;
+ set
+ {
+ if (value >= 0 && Set(ref actionIndex, value))
+ OnPropertyChanged(nameof(SelectedAction));
+ }
+ }
+
+ /// The action chosen.
+ public CasAction SelectedAction
+ {
+ get => Faces[actionIndex].Action;
+ set => ActionIndex = Array.FindIndex(Faces, f => f.Action == value);
+ }
+
+ /// The letters of the equation.
+ public IReadOnlyList Letters
+ {
+ get => letters;
+ private set => Set(ref letters, value);
+ }
+
+ /// The letter to solve for, and to differentiate and integrate by.
+ public string? Letter
+ {
+ get => letter;
+ set => Set(ref letter, value);
+ }
+
+ /// Why the last entry was not added, or empty.
+ public string Message
+ {
+ get => message;
+ private set => Set(ref message, value);
+ }
+
+ /// The entries, as the page shows them.
+ public IReadOnlyList Items
+ {
+ get => items;
+ private set
+ {
+ if (Set(ref items, value))
+ OnPropertyChanged(nameof(IsEmpty));
+ }
+ }
+
+ /// Whether nothing was computed yet.
+ public bool IsEmpty => items.Count == 0;
+
+ /// Computes the equation of the editor and adds the entry.
+ public ICommand EnterCommand { get; }
+
+ /// Removes every entry (the letters defined stay).
+ public ICommand ClearCommand { get; }
+
+ /// Computes the equation of the editor and adds the entry, as the Enter button does; null when nothing was added.
+ public async Task EnterAsync()
+ {
+ var typed = equation;
+ if (typed == null)
+ return Fail("Type something first.");
+ if (typed.ToMathML().Descendants().Any(e => e.Name.LocalName == "merror"))
+ return Fail("Not built up yet: finish the argument, or press Build up (Enter).");
+ var action = SelectedAction;
+ var by = letter;
+ // on another thread, since the engine can take long (it cannot be stopped: a result too late is dropped)
+ var work = Task.Run(() => Worksheet.Compute(engine, action, typed, by));
+ if (await Task.WhenAny(work, Task.Delay(Timeout)).ConfigureAwait(true) != work)
+ return Fail("It takes too long: " + engine.Name + " found no result in " + Timeout.TotalSeconds + " seconds.");
+ Message = "";
+ var entry = Sheet.Add(await work.ConfigureAwait(true));
+ UpdateLetters();
+ return entry;
+ }
+
+ private WorksheetEntry? Fail(string text)
+ {
+ Message = text;
+ return null;
+ }
+
+ private void UpdateLetters()
+ {
+ IReadOnlyList found;
+ try
+ {
+ found = equation is { } typed ? engine.Variables(typed) : Array.Empty();
+ }
+#pragma warning disable CA1031 // what cannot be read has no letters
+ catch (Exception)
+#pragma warning restore CA1031
+ {
+ found = Array.Empty();
+ }
+ if (letters.SequenceEqual(found))
+ return;
+ // the list of the view forgets its letter when its letters change: the letter is given again after them
+ var selected = letter != null && found.Contains(letter) ? letter : found.Count > 0 ? found[0] : null;
+ Letters = found;
+ letter = selected;
+ OnPropertyChanged(nameof(Letter));
+ }
+
+ private void Show() => Items = Sheet.Entries.Select((entry, index) => new WorksheetItem(
+ entry,
+ index + 1,
+ new RelayCommand(() =>
+ {
+ Equation = entry.OutputEquation;
+ FocusRequested?.Invoke(this, EventArgs.Empty);
+ }),
+ new RelayCommand(() => GraphRequested?.Invoke(this, entry.InputEquation)),
+ new RelayCommand(() => Sheet.Remove(entry)))).ToList();
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/AlgebraPanel.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/AlgebraPanel.axaml
new file mode 100644
index 0000000..60eef68
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/AlgebraPanel.axaml
@@ -0,0 +1,125 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/AlgebraPanel.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/AlgebraPanel.axaml.cs
new file mode 100644
index 0000000..5f22c9e
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/AlgebraPanel.axaml.cs
@@ -0,0 +1,113 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Generic;
+ using System.ComponentModel;
+ using System.Threading.Tasks;
+ using global::Avalonia.Controls;
+ using global::Avalonia.Input;
+ using global::Avalonia.Interactivity;
+ using SharpEquations;
+ using SharpEquations.MathTools;
+ using SharpEquations.Rendering;
+
+ ///
+ /// What the calculator computes from the equation of the editor ( ): its value, and the
+ /// results of the actions, each ready to be copied or to go back to the editor.
+ ///
+ public sealed partial class AlgebraPanel : UserControl
+ {
+ public AlgebraPanel() => InitializeComponent();
+
+ /// The view model: the value and the results.
+ public AlgebraViewModel? ViewModel => DataContext as AlgebraViewModel;
+
+ /// The editor the results are pasted into.
+ public MathEditBox? Editor { get; set; }
+
+ private void OnUseClick(object? sender, RoutedEventArgs e)
+ {
+ if (sender is Button { DataContext: AlgebraItem item })
+ ViewModel?.Use(item.Math);
+ }
+
+ private async void OnCopyClick(object? sender, RoutedEventArgs e)
+ {
+ if (sender is Button { DataContext: AlgebraItem { Result: { } result } })
+ await CopyAsync(result.Math, result.Text, null).ConfigureAwait(true);
+ }
+
+ private void OnAnswerMenuOpening(object? sender, CancelEventArgs e)
+ {
+ if (sender is not ContextMenu menu || ViewModel?.Answer is not { } answer)
+ {
+ e.Cancel = true;
+ return;
+ }
+ menu.ItemsSource = MenuItems(answer);
+ }
+
+ private void OnResultMenuOpening(object? sender, CancelEventArgs e)
+ {
+ if (sender is not ContextMenu menu || (menu.PlacementTarget?.DataContext ?? menu.DataContext) is not AlgebraItem { Result: { } result })
+ {
+ e.Cancel = true;
+ return;
+ }
+ menu.ItemsSource = MenuItems(result);
+ }
+
+ // the right-click menu of a result: copy it as text, LaTeX or MathML, its decimal values, or put it in the editor
+ private List MenuItems(CasResult result)
+ {
+ var items = new List
+ {
+ Item("Copy", () => CopyAsync(result.Math, result.Text, null)),
+ Item("Copy as LaTeX", () => CopyAsync(result.Math, result.Text, EquationFormat.LaTeX), result.Math != null),
+ Item("Copy as MathML", () => CopyAsync(result.Math, result.Text, EquationFormat.MathML), result.Math != null),
+ };
+ if (result.ApproximateText != null)
+ items.Add(Item("Copy decimal values", () => CopyAsync(result.Approximate, result.ApproximateText, null)));
+ items.Add(Item("To the editor", () => Use(result.Math), result.Math != null));
+ if (result.Approximate != null)
+ items.Add(Item("Decimal values to the editor", () => Use(result.Approximate)));
+ items.Add(Item("Paste into the editor", PasteAsync));
+ return items;
+ }
+
+ private static MenuItem Item(string header, Func action, bool enabled = true)
+ {
+ var item = new MenuItem { Header = header, IsEnabled = enabled };
+ item.Click += async (_, _) => await action().ConfigureAwait(true);
+ return item;
+ }
+
+ private Task Use(Equation? math)
+ {
+ ViewModel?.Use(math);
+ return Task.CompletedTask;
+ }
+
+ private async Task PasteAsync()
+ {
+ if (Editor == null)
+ return;
+ Editor.Focus();
+ await Editor.PasteAsync().ConfigureAwait(true);
+ }
+
+ // the result on the clipboard: as text (UnicodeMath, or the format asked) and as MathML for Word and the editor
+ private async Task CopyAsync(Equation? math, string text, EquationFormat? format)
+ {
+ if (TopLevel.GetTopLevel(this)?.Clipboard is not { } clipboard)
+ return;
+ var item = new DataTransferItem();
+ item.SetText(math == null ? text : math.ToString(format ?? EquationFormat.UnicodeMath));
+ if (math != null)
+ item.Set(MathEditBox.MathMLClipboardFormat, MathClipboard.Encode(math.ToString(EquationFormat.MathML)));
+ var data = new DataTransfer();
+ data.Add(item);
+ await clipboard.SetDataAsync(data).ConfigureAwait(true);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/CalculatorPage.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/CalculatorPage.axaml
new file mode 100644
index 0000000..13b33c5
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/CalculatorPage.axaml
@@ -0,0 +1,104 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/CalculatorPage.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/CalculatorPage.axaml.cs
new file mode 100644
index 0000000..2826dfb
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/CalculatorPage.axaml.cs
@@ -0,0 +1,56 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using global::Avalonia.Controls;
+ using global::Avalonia.Interactivity;
+
+ ///
+ /// The page of the scientific keypad ( ): the keys type into the equation editor,
+ /// which the keyboard types into too.
+ ///
+ public sealed partial class CalculatorPage : UserControl
+ {
+ private CalculatorViewModel? shown;
+
+ public CalculatorPage()
+ {
+ InitializeComponent();
+ SolverView.Editor = EquationEditor;
+ }
+
+ /// The view model: the keys, the equation and what is computed from it.
+ public CalculatorViewModel? ViewModel => DataContext as CalculatorViewModel;
+
+ /// The equation editor the keys type into.
+ public MathEditBox Editor => EquationEditor;
+
+ /// What is computed from the equation of the editor.
+ public AlgebraPanel Solver => SolverView;
+
+ /// Presses a key, as a click on it does.
+ public void Press(CalculatorKey key)
+ {
+ ArgumentNullException.ThrowIfNull(key);
+ key.Press(EquationEditor.Editor);
+ EquationEditor.Focus();
+ }
+
+ protected override void OnDataContextChanged(EventArgs e)
+ {
+ base.OnDataContextChanged(e);
+ if (shown != null)
+ shown.FocusRequested -= OnFocusRequested;
+ shown = ViewModel;
+ if (shown != null)
+ shown.FocusRequested += OnFocusRequested;
+ }
+
+ private void OnFocusRequested(object? sender, EventArgs e) => EquationEditor.Focus();
+
+ private void OnKeyClick(object? sender, RoutedEventArgs e)
+ {
+ if (sender is Button { DataContext: CalculatorKey key })
+ Press(key);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Card.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Card.cs
new file mode 100644
index 0000000..e3605d2
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Card.cs
@@ -0,0 +1,27 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using global::Avalonia;
+ using global::Avalonia.Controls;
+
+ /// A card of a page: a title, a caption (text, or a control with text and formulas) and its content.
+ public class Card : ContentControl
+ {
+ public static readonly StyledProperty TitleProperty =
+ AvaloniaProperty.Register(nameof(Title));
+
+ public static readonly StyledProperty CaptionProperty =
+ AvaloniaProperty.Register(nameof(Caption));
+
+ public string? Title
+ {
+ get => GetValue(TitleProperty);
+ set => SetValue(TitleProperty, value);
+ }
+
+ public object? Caption
+ {
+ get => GetValue(CaptionProperty);
+ set => SetValue(CaptionProperty, value);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/FormulasPage.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/FormulasPage.axaml
new file mode 100644
index 0000000..bf8841a
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/FormulasPage.axaml
@@ -0,0 +1,90 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/FormulasPage.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/FormulasPage.axaml.cs
new file mode 100644
index 0000000..3dcb4e0
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/FormulasPage.axaml.cs
@@ -0,0 +1,13 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using global::Avalonia.Controls;
+
+ /// The page of the library of formulas ( )
+ public sealed partial class FormulasPage : UserControl
+ {
+ public FormulasPage() => InitializeComponent();
+
+ /// each one drawn, filtered by subject and by name.:The view model: the formulas, the subject and the search.
+ public FormulasViewModel? ViewModel => DataContext as FormulasViewModel;
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Graph3DView.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graph3DView.cs
similarity index 100%
rename from samples/SharpEquations.Avalonia.MathTools.Demo/Graph3DView.cs
rename to samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graph3DView.cs
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/GraphView.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphView.cs
similarity index 100%
rename from samples/SharpEquations.Avalonia.MathTools.Demo/GraphView.cs
rename to samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphView.cs
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graphs3DPage.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graphs3DPage.axaml
new file mode 100644
index 0000000..397ed1c
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graphs3DPage.axaml
@@ -0,0 +1,82 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graphs3DPage.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graphs3DPage.axaml.cs
new file mode 100644
index 0000000..8dd4e3d
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/Graphs3DPage.axaml.cs
@@ -0,0 +1,86 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Specialized;
+ using System.Threading.Tasks;
+ using global::Avalonia.Controls;
+ using global::Avalonia.Input.Platform;
+ using global::Avalonia.Interactivity;
+ using global::Avalonia.Media.Imaging;
+
+ ///
+ /// The page of the graphs in space ( ): the equations of the view model drawn together in a
+ /// box the camera turns around, each in its color, with a slider for each of their parameters.
+ ///
+ public sealed partial class Graphs3DPage : UserControl
+ {
+ private Graphs3DViewModel? shown;
+ private RenderTargetBitmap? copied;
+
+ public Graphs3DPage()
+ {
+ InitializeComponent();
+ Box.ForceSoftware = OperatingSystem.IsBrowser();
+ }
+
+ /// The view model: the graphs and their parameters.
+ public Graphs3DViewModel? ViewModel => DataContext as Graphs3DViewModel;
+
+ /// The editor of the equation to add.
+ public MathEditBox Editor => EquationEditor;
+
+ /// The box the graphs are drawn in.
+ public Graph3DView Space => Box;
+
+ /// Copies the graphs to the clipboard as an image.
+ public async Task CopyImageAsync()
+ {
+ if (TopLevel.GetTopLevel(this)?.Clipboard is not { } clipboard)
+ return;
+ // the clipboard may read the image later: the last one copied is kept until the next
+ copied?.Dispose();
+ copied = Box.Snapshot();
+ await clipboard.SetBitmapAsync(copied).ConfigureAwait(true);
+ }
+
+ protected override void OnDataContextChanged(EventArgs e)
+ {
+ base.OnDataContextChanged(e);
+ if (shown != null)
+ {
+ shown.Items.CollectionChanged -= OnItemsChanged;
+ shown.RedrawRequested -= OnRedrawRequested;
+ shown.ResetRequested -= OnResetRequested;
+ }
+ shown = ViewModel;
+ if (shown != null)
+ {
+ shown.Items.CollectionChanged += OnItemsChanged;
+ shown.RedrawRequested += OnRedrawRequested;
+ shown.ResetRequested += OnResetRequested;
+ }
+ Draw();
+ }
+
+ private void OnItemsChanged(object? sender, NotifyCollectionChangedEventArgs e) => Draw();
+
+ // sampling the surfaces again is slow: it waits for the slider to stop
+ private void OnRedrawRequested(object? sender, EventArgs e) => Box.RedrawSoon();
+
+ private void OnResetRequested(object? sender, EventArgs e) => Box.Reset();
+
+ private void OnResetViewClick(object? sender, RoutedEventArgs e) => Box.Reset();
+
+ private async void OnCopyImageClick(object? sender, RoutedEventArgs e) => await CopyImageAsync().ConfigureAwait(true);
+
+ // the surfaces and curves of the box are the graphs of the view model, in their order
+ private void Draw()
+ {
+ Box.Surfaces.Clear();
+ if (shown == null)
+ return;
+ foreach (var item in shown.Items)
+ Box.Surfaces.Add((SurfaceGraph)item.Graph);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphsPage.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphsPage.axaml
new file mode 100644
index 0000000..2060515
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphsPage.axaml
@@ -0,0 +1,78 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphsPage.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphsPage.axaml.cs
new file mode 100644
index 0000000..57eb7a6
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/GraphsPage.axaml.cs
@@ -0,0 +1,81 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Collections.Specialized;
+ using System.Threading.Tasks;
+ using global::Avalonia.Controls;
+ using global::Avalonia.Input.Platform;
+ using global::Avalonia.Interactivity;
+ using global::Avalonia.Media.Imaging;
+
+ ///
+ /// The page of the graphs ( ): the equations of the view model drawn together on a
+ /// plane, each in its color, with a slider for each of their parameters.
+ ///
+ public sealed partial class GraphsPage : UserControl
+ {
+ private GraphsViewModel? shown;
+ private RenderTargetBitmap? copied;
+
+ public GraphsPage() => InitializeComponent();
+
+ /// The view model: the graphs and their parameters.
+ public GraphsViewModel? ViewModel => DataContext as GraphsViewModel;
+
+ /// The editor of the equation to add.
+ public MathEditBox Editor => EquationEditor;
+
+ /// The plane the graphs are drawn on.
+ public GraphView Graph => Plane;
+
+ /// Copies the graphs to the clipboard as an image.
+ public async Task CopyImageAsync()
+ {
+ if (TopLevel.GetTopLevel(this)?.Clipboard is not { } clipboard)
+ return;
+ // the clipboard may read the image later: the last one copied is kept until the next
+ copied?.Dispose();
+ copied = Plane.Snapshot();
+ await clipboard.SetBitmapAsync(copied).ConfigureAwait(true);
+ }
+
+ protected override void OnDataContextChanged(EventArgs e)
+ {
+ base.OnDataContextChanged(e);
+ if (shown != null)
+ {
+ shown.Items.CollectionChanged -= OnItemsChanged;
+ shown.RedrawRequested -= OnRedrawRequested;
+ shown.ResetRequested -= OnResetRequested;
+ }
+ shown = ViewModel;
+ if (shown != null)
+ {
+ shown.Items.CollectionChanged += OnItemsChanged;
+ shown.RedrawRequested += OnRedrawRequested;
+ shown.ResetRequested += OnResetRequested;
+ }
+ Draw();
+ }
+
+ private void OnItemsChanged(object? sender, NotifyCollectionChangedEventArgs e) => Draw();
+
+ private void OnRedrawRequested(object? sender, EventArgs e) => Plane.Redraw();
+
+ private void OnResetRequested(object? sender, EventArgs e) => Plane.Reset();
+
+ private void OnResetViewClick(object? sender, RoutedEventArgs e) => Plane.Reset();
+
+ private async void OnCopyImageClick(object? sender, RoutedEventArgs e) => await CopyImageAsync().ConfigureAwait(true);
+
+ // the curves of the plane are the graphs of the view model, in their order
+ private void Draw()
+ {
+ Plane.Curves.Clear();
+ if (shown == null)
+ return;
+ foreach (var item in shown.Items)
+ Plane.Curves.Add((GraphCurve)item.Graph);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/MathToolsView.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/MathToolsView.axaml
new file mode 100644
index 0000000..a36f70f
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/MathToolsView.axaml
@@ -0,0 +1,286 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/MathToolsView.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/MathToolsView.axaml.cs
new file mode 100644
index 0000000..7b66dc7
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/MathToolsView.axaml.cs
@@ -0,0 +1,89 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using global::Avalonia;
+ using global::Avalonia.Controls;
+ using global::Avalonia.Interactivity;
+ using global::Avalonia.Layout;
+ using global::Avalonia.Styling;
+ using SharpEquations.MathTools;
+
+ ///
+ /// The view of the math tools ( ): a header and a page for each tool. The desktop
+ /// window and the WebAssembly page show the same view.
+ ///
+ public sealed partial class MathToolsView : UserControl
+ {
+ private const string RepositoryUrl = "https://github.com/simonebortolin/SharpEquations";
+
+ public MathToolsView() => InitializeComponent();
+
+ /// Where the settings are kept; in memory by default.
+ /// The computer algebra system; AngouriMath by default.
+ public MathToolsView(ISettingsStore? settings, ICasEngine? engine = null)
+ : this()
+ {
+ DataContext = new MathToolsViewModel(settings, engine);
+ }
+
+ /// The view model: the tools, and the settings of the session.
+ public MathToolsViewModel? ViewModel => DataContext as MathToolsViewModel;
+
+ /// The tabs of the pages.
+ public TabControl Tabs => Pages;
+
+ /// The page of the scientific keypad.
+ public CalculatorPage Calculator => CalculatorView;
+
+ /// The page of the library of formulas.
+ public FormulasPage FormulaLibrary => FormulasView;
+
+ /// The page of the unit converter.
+ public UnitsPage Converter => UnitsView;
+
+ /// The page of the solver of triangles.
+ public TrianglePage TriangleSolver => TrianglesView;
+
+ /// The page of the graphs.
+ public GraphsPage Graphs => GraphsView;
+
+ /// The page of the graphs in space.
+ public Graphs3DPage Space => SpaceView;
+
+ /// The page of the worksheet.
+ public WorksheetPage Worksheet => WorksheetView;
+
+ protected override void OnDataContextChanged(EventArgs e)
+ {
+ base.OnDataContextChanged(e);
+ // the theme of the last session
+ if (Application.Current is { } app && ViewModel?.IsDark is { } dark)
+ app.RequestedThemeVariant = dark ? ThemeVariant.Dark : ThemeVariant.Light;
+ }
+
+ private void OnThemeClick(object? sender, RoutedEventArgs e)
+ {
+ if (Application.Current is not { } app)
+ return;
+ var dark = app.ActualThemeVariant != ThemeVariant.Dark;
+ app.RequestedThemeVariant = dark ? ThemeVariant.Dark : ThemeVariant.Light;
+ ViewModel?.KeepTheme(dark);
+ }
+
+ private async void OnGitHubClick(object? sender, RoutedEventArgs e)
+ {
+ if (TopLevel.GetTopLevel(this)?.Launcher is { } launcher)
+ await launcher.LaunchUriAsync(new Uri(RepositoryUrl)).ConfigureAwait(true);
+ }
+
+ // a narrow header has no formula, and its buttons under the title
+ private void OnHeaderSizeChanged(object? sender, SizeChangedEventArgs e)
+ {
+ var narrow = e.NewSize.Width < 640;
+ Hero.IsVisible = e.NewSize.Width > 900;
+ DockPanel.SetDock(HeaderButtons, narrow ? Dock.Bottom : Dock.Right);
+ HeaderButtons.HorizontalAlignment = narrow ? HorizontalAlignment.Left : HorizontalAlignment.Right;
+ HeaderButtons.Margin = narrow ? new Thickness(0, 14, 0, 0) : default;
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TrianglePage.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TrianglePage.axaml
new file mode 100644
index 0000000..b04f183
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TrianglePage.axaml
@@ -0,0 +1,119 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TrianglePage.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TrianglePage.axaml.cs
new file mode 100644
index 0000000..d8e3fa6
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TrianglePage.axaml.cs
@@ -0,0 +1,13 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using global::Avalonia.Controls;
+
+ /// The page of the solver of triangles ( ), with each triangle drawn to scale.
+ public sealed partial class TrianglePage : UserControl
+ {
+ public TrianglePage() => InitializeComponent();
+
+ /// The view model: the fields and the solution.
+ public TrianglesViewModel? ViewModel => DataContext as TrianglesViewModel;
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TriangleView.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TriangleView.cs
new file mode 100644
index 0000000..30127a4
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/TriangleView.cs
@@ -0,0 +1,83 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using System.Linq;
+ using global::Avalonia;
+ using global::Avalonia.Controls;
+ using global::Avalonia.Controls.Shapes;
+ using global::Avalonia.Media;
+ using SharpEquations.MathTools;
+
+ /// A triangle drawn to scale: A at the left of the base c, B at its right, C above.
+ public sealed class TriangleView : Decorator
+ {
+ public static readonly StyledProperty TriangleProperty =
+ AvaloniaProperty.Register(nameof(Triangle));
+
+ private const double DrawingWidth = 300;
+ private const double DrawingHeight = 210;
+
+ private static readonly Color Accent = Color.FromRgb(0x0D, 0x94, 0x88);
+
+ public Triangle? Triangle
+ {
+ get => GetValue(TriangleProperty);
+ set => SetValue(TriangleProperty, value);
+ }
+
+ protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
+ {
+ base.OnPropertyChanged(change);
+ if (change.Property == TriangleProperty)
+ Child = Triangle is { } triangle ? Drawing(triangle) : null;
+ }
+
+ private static Canvas Drawing(Triangle triangle)
+ {
+ var alpha = Triangles.Radians(triangle.Alpha);
+ var points = new[] { (X: 0.0, Y: 0.0), (X: triangle.C, Y: 0.0), (X: triangle.B * Math.Cos(alpha), Y: triangle.B * Math.Sin(alpha)) };
+ double minX = points.Min(p => p.X), maxX = points.Max(p => p.X), maxY = points.Max(p => p.Y);
+ const double margin = 26;
+ var scale = Math.Min((DrawingWidth - 2 * margin) / (maxX - minX), (DrawingHeight - 2 * margin) / maxY);
+ var offsetX = (DrawingWidth - (maxX - minX) * scale) / 2;
+ var offsetY = (DrawingHeight + maxY * scale) / 2;
+ var screen = points.Select(p => new Point(offsetX + (p.X - minX) * scale, offsetY - p.Y * scale)).ToArray();
+
+ var canvas = new Canvas { Width = DrawingWidth, Height = DrawingHeight };
+ canvas.Children.Add(new Polygon
+ {
+ Points = screen,
+ StrokeThickness = 2,
+ StrokeJoin = PenLineJoin.Round,
+ Stroke = new SolidColorBrush(Accent),
+ Fill = new SolidColorBrush(Accent, 0.14),
+ });
+
+ var center = new Point(screen.Average(p => p.X), screen.Average(p => p.Y));
+ for (var i = 0; i < 3; i++)
+ {
+ // the vertex, away from the center, and the side opposite it, at its middle, away from the center too
+ Label(canvas, ((char)('A' + i)).ToString(), Away(screen[i], center, 14), FontWeight.SemiBold);
+ var middle = (screen[(i + 1) % 3] + screen[(i + 2) % 3]) / 2;
+ Label(canvas, Triangles.SideNames[i], Away(middle, center, 12), FontWeight.Normal);
+ }
+ return canvas;
+ }
+
+ private static Point Away(Point point, Point center, double distance)
+ {
+ var direction = point - center;
+ var length = Math.Sqrt(direction.X * direction.X + direction.Y * direction.Y);
+ return length < 1e-9 ? point : point + direction * (distance / length);
+ }
+
+ private static void Label(Canvas canvas, string text, Point at, FontWeight weight)
+ {
+ var label = new TextBlock { Text = text, FontStyle = FontStyle.Italic, FontSize = 15, FontWeight = weight };
+ label.Measure(Size.Infinity);
+ Canvas.SetLeft(label, at.X - label.DesiredSize.Width / 2);
+ Canvas.SetTop(label, at.Y - label.DesiredSize.Height / 2);
+ canvas.Children.Add(label);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnicodeMathExtension.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnicodeMathExtension.cs
new file mode 100644
index 0000000..e7aec92
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnicodeMathExtension.cs
@@ -0,0 +1,26 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using global::Avalonia.Markup.Xaml;
+ using SharpEquations;
+
+ /// An equation written in the markup as UnicodeMath: Equation="{local:UnicodeMath 'x^2+y^2=25'}" .
+ public sealed class UnicodeMathExtension : MarkupExtension
+ {
+ public UnicodeMathExtension()
+ {
+ }
+
+ public UnicodeMathExtension(string text) => Text = text;
+
+ /// The equation, as UnicodeMath.
+ public string Text { get; set; } = "";
+
+ /// Whether the equation is on a line of its own.
+ public bool Display { get; set; }
+
+ ///
+ public override object ProvideValue(IServiceProvider serviceProvider) =>
+ Equation.Parse(Text, EquationFormat.UnicodeMath, new EquationOptions { Display = Display });
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnitsPage.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnitsPage.axaml
new file mode 100644
index 0000000..91abbfb
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnitsPage.axaml
@@ -0,0 +1,62 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnitsPage.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnitsPage.axaml.cs
new file mode 100644
index 0000000..b3ddaf2
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/UnitsPage.axaml.cs
@@ -0,0 +1,13 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using global::Avalonia.Controls;
+
+ /// The page of the unit converter ( ).
+ public sealed partial class UnitsPage : UserControl
+ {
+ public UnitsPage() => InitializeComponent();
+
+ /// The view model: the value, the units and the results.
+ public UnitsViewModel? ViewModel => DataContext as UnitsViewModel;
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/WorksheetPage.axaml b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/WorksheetPage.axaml
new file mode 100644
index 0000000..532de32
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/WorksheetPage.axaml
@@ -0,0 +1,87 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/Views/WorksheetPage.axaml.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/WorksheetPage.axaml.cs
new file mode 100644
index 0000000..12c5461
--- /dev/null
+++ b/samples/SharpEquations.Avalonia.MathTools.Demo/Views/WorksheetPage.axaml.cs
@@ -0,0 +1,45 @@
+namespace SharpEquations.Avalonia.MathTools
+{
+ using System;
+ using global::Avalonia.Controls;
+ using global::Avalonia.Input;
+
+ ///
+ /// The page of the worksheet ( ): the entries one after the other as on paper, and
+ /// the editor of the next one.
+ ///
+ public sealed partial class WorksheetPage : UserControl
+ {
+ private WorksheetViewModel? shown;
+
+ public WorksheetPage() => InitializeComponent();
+
+ /// The view model: the entries, and what is done to the equation of the editor.
+ public WorksheetViewModel? ViewModel => DataContext as WorksheetViewModel;
+
+ /// The editor of the next entry.
+ public MathEditBox Editor => EquationEditor;
+
+ protected override void OnDataContextChanged(EventArgs e)
+ {
+ base.OnDataContextChanged(e);
+ if (shown != null)
+ shown.FocusRequested -= OnFocusRequested;
+ shown = ViewModel;
+ if (shown != null)
+ shown.FocusRequested += OnFocusRequested;
+ }
+
+ private void OnFocusRequested(object? sender, EventArgs e) => EquationEditor.Focus();
+
+ // Ctrl+Enter adds the entry, as the Enter button does
+ private void OnEditorKeyDown(object? sender, KeyEventArgs e)
+ {
+ if (e.Key == Key.Enter && e.KeyModifiers.HasFlag(KeyModifiers.Control) && ViewModel is { } model)
+ {
+ e.Handled = true;
+ model.EnterCommand.Execute(null);
+ }
+ }
+ }
+}
diff --git a/samples/SharpEquations.Avalonia.MathTools.Demo/WorksheetPage.cs b/samples/SharpEquations.Avalonia.MathTools.Demo/WorksheetPage.cs
deleted file mode 100644
index bc33c8f..0000000
--- a/samples/SharpEquations.Avalonia.MathTools.Demo/WorksheetPage.cs
+++ /dev/null
@@ -1,230 +0,0 @@
-namespace SharpEquations.Avalonia.MathTools
-{
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using global::Avalonia;
- using global::Avalonia.Controls;
- using global::Avalonia.Input;
- using global::Avalonia.Layout;
- using SharpEquations;
- using SharpEquations.MathTools;
-
- ///
- /// The worksheet: what is computed, one entry after the other as on paper, each with what was typed, what was done
- /// to it and the result, ready to go back to the editor or to be drawn. It is kept between sessions, with the
- /// definitions it made.
- ///
- public sealed class WorksheetPage : UserControl
- {
- /// The key of the settings the worksheet is kept under.
- public const string SettingsKey = "worksheet";
-
- private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10);
- private static readonly EquationOptions Display = new EquationOptions { Display = true };
-
- private static readonly (CasAction Action, string Face)[] Actions =
- {
- (CasAction.Evaluate, "Evaluate"),
- (CasAction.Solve, "Solve"),
- (CasAction.Simplify, "Simplify"),
- (CasAction.Expand, "Expand"),
- (CasAction.Factor, "Factor"),
- (CasAction.Differentiate, "Derivative"),
- (CasAction.Integrate, "Antiderivative"),
- (CasAction.Define, "Define"),
- };
-
- private readonly ICasEngine engine;
- private readonly ISettingsStore settings;
- private readonly StackPanel list = new StackPanel { Spacing = 10 };
- private readonly TextBlock message = Ui.Muted("", 12.5);
- private readonly TextBlock empty = Ui.Muted("Nothing computed yet: type below and press Enter.", 13);
-
- public WorksheetPage(ICasEngine engine, ISettingsStore? settings = null)
- {
- this.engine = engine;
- this.settings = settings ?? new MemorySettingsStore();
- Sheet = Worksheet.Deserialize(this.settings.Get(SettingsKey));
- Sheet.Replay(engine);
- Sheet.Changed += (_, _) => this.settings.Set(SettingsKey, Sheet.Entries.Count == 0 ? null : Sheet.Serialize());
-
- Editor = new MathEditBox
- {
- FontSize = 26,
- MinHeight = 70,
- Padding = new Thickness(16, 10),
- BorderThickness = 0,
- Equation = Equation.Parse("x^2-5x+6=0", EquationFormat.UnicodeMath, Display),
- };
- Editor.Bind(MathEditBox.BackgroundProperty, Editor.GetResourceObservable("EditorBrush"));
- var frame = new Border { CornerRadius = new CornerRadius(12), BorderThickness = new Thickness(1.5), ClipToBounds = true, Child = Editor };
- frame.Bind(Border.BorderBrushProperty, frame.GetResourceObservable("EditorBorderBrush"));
-
- Action = new ComboBox { ItemsSource = Actions.Select(a => a.Face).ToArray(), SelectedIndex = 1, MinWidth = 150 };
- ToolTip.SetTip(Action, "What is done to the equation");
- Letter = new ComboBox { MinWidth = 70 };
- ToolTip.SetTip(Letter, "The letter to solve for, and to differentiate and integrate by");
- Editor.EquationChanged += (_, _) => UpdateLetters();
- UpdateLetters();
-
- var enter = new Button { Content = "Enter", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(enter, "Computes and adds the entry to the worksheet (Ctrl+Enter)");
- enter.Click += async (_, _) => await EnterAsync().ConfigureAwait(true);
- Editor.KeyDown += async (_, e) =>
- {
- if (e.Key == Key.Enter && e.KeyModifiers.HasFlag(KeyModifiers.Control))
- {
- e.Handled = true;
- await EnterAsync().ConfigureAwait(true);
- }
- };
- var clear = new Button { Content = "Clear worksheet", CornerRadius = new CornerRadius(8), Padding = new Thickness(16, 6) };
- ToolTip.SetTip(clear, "Removes every entry (the letters defined stay)");
- clear.Click += (_, _) => Sheet.Clear();
-
- Sheet.Changed += (_, _) => Show();
- Show();
-
- Content = new StackPanel
- {
- Spacing = 20,
- Children =
- {
- Ui.Card("Worksheet", "Each entry what was typed, what was done and its result, kept from one session to the next", new StackPanel { Spacing = 10, Children = { empty, list } }),
- Ui.Card("Input", "Type an equation or an expression, choose what to do, and press Enter", new StackPanel
- {
- Spacing = 12,
- Children = { frame, Ui.Row(Action, Ui.Muted("by", 12.5), Letter, enter, clear), message },
- }),
- },
- };
- }
-
- /// Raised by the Graph button of an entry, with the equation to draw.
- public event EventHandler? GraphRequested;
-
- /// The entries.
- public Worksheet Sheet { get; }
-
- /// The editor of the next entry.
- public MathEditBox Editor { get; }
-
- /// What is done to the equation of the editor.
- public ComboBox Action { get; }
-
- /// The letter to solve for, and to differentiate and integrate by.
- public ComboBox Letter { get; }
-
- /// Why the last entry was not added, or empty.
- public string Message => message.Text ?? "";
-
- /// The action chosen.
- public CasAction SelectedAction
- {
- get => Actions[Math.Max(0, Action.SelectedIndex)].Action;
- set => Action.SelectedIndex = Array.FindIndex(Actions, a => a.Action == value);
- }
-
- /// Computes the equation of the editor and adds the entry, as the Enter button does; null when nothing was added.
- public async Task EnterAsync()
- {
- var equation = Editor.Equation;
- if (equation == null)
- return Fail("Type something first.");
- if (equation.ToMathML().Descendants().Any(e => e.Name.LocalName == "merror"))
- return Fail("Not built up yet: finish the argument, or press Build up (Enter).");
- var action = SelectedAction;
- var letter = Letter.SelectedItem as string;
- // on another thread, since the engine can take long (it cannot be stopped: a result too late is dropped)
- var work = Task.Run(() => Worksheet.Compute(engine, action, equation, letter));
- if (await Task.WhenAny(work, Task.Delay(Timeout)).ConfigureAwait(true) != work)
- return Fail("It takes too long: " + engine.Name + " found no result in " + Timeout.TotalSeconds + " seconds.");
- message.Text = "";
- var entry = Sheet.Add(await work.ConfigureAwait(true));
- UpdateLetters();
- return entry;
- }
-
- private WorksheetEntry? Fail(string text)
- {
- message.Text = text;
- return null;
- }
-
- private void UpdateLetters()
- {
- IReadOnlyList letters;
- try
- {
- letters = Editor.Equation is { } equation ? engine.Variables(equation) : Array.Empty();
- }
-#pragma warning disable CA1031 // what cannot be read has no letters
- catch (Exception)
-#pragma warning restore CA1031
- {
- letters = Array.Empty();
- }
- var selected = Letter.SelectedItem as string;
- if (Letter.ItemsSource is IReadOnlyList old && old.SequenceEqual(letters))
- return;
- Letter.ItemsSource = letters;
- Letter.SelectedItem = selected != null && letters.Contains(selected) ? selected : letters.Count > 0 ? letters[0] : null;
- }
-
- private void Show()
- {
- list.Children.Clear();
- var number = 0;
- foreach (var entry in Sheet.Entries)
- list.Children.Add(Card(entry, ++number));
- empty.IsVisible = Sheet.Entries.Count == 0;
- }
-
- private Border Card(WorksheetEntry entry, int number)
- {
- var input = new MathView { FontSize = 20, Equation = entry.InputEquation, HorizontalAlignment = HorizontalAlignment.Left };
- var outputEquation = entry.OutputEquation;
- Control output = outputEquation != null
- ? new MathView { FontSize = 22, Equation = outputEquation, HorizontalAlignment = HorizontalAlignment.Left }
- : new SelectableTextBlock { Text = entry.Text, FontSize = 14, TextWrapping = global::Avalonia.Media.TextWrapping.Wrap, Opacity = entry.Failed ? 0.75 : 1 };
-
- var use = new Button { Content = "To the editor", CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 3), IsEnabled = outputEquation != null };
- ToolTip.SetTip(use, "Puts the result in the editor");
- use.Click += (_, _) =>
- {
- Editor.Equation = outputEquation;
- Editor.Focus();
- };
- var graph = new Button { Content = "Graph", CornerRadius = new CornerRadius(8), Padding = new Thickness(10, 3) };
- ToolTip.SetTip(graph, "Draws what was typed on the page of the graphs");
- graph.Click += (_, _) => GraphRequested?.Invoke(this, entry.InputEquation);
- var remove = new Button { Content = "×", CornerRadius = new CornerRadius(8), Padding = new Thickness(8, 2) };
- ToolTip.SetTip(remove, "Removes this entry");
- remove.Click += (_, _) => Sheet.Remove(entry);
-
- var buttons = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, Children = { use, graph, remove } };
- var top = new DockPanel { Children = { Ui.Docked(buttons, Dock.Right), Ui.Small(number + ". " + entry.Label) } };
- var arrow = Ui.Muted("→", 18);
- arrow.VerticalAlignment = VerticalAlignment.Center;
- var card = new Border
- {
- CornerRadius = new CornerRadius(12),
- Padding = new Thickness(16, 10),
- Child = new StackPanel
- {
- Spacing = 8,
- Children =
- {
- top,
- input,
- new DockPanel { Children = { Ui.Docked(arrow, Dock.Left), Ui.Docked(new Border { Width = 10 }, Dock.Left), output } },
- },
- },
- };
- card.Bind(Border.BackgroundProperty, card.GetResourceObservable("CodeBrush"));
- return card;
- }
- }
-}
diff --git a/samples/SharpEquations.Uno.Demo/App.cs b/samples/SharpEquations.Uno.Demo/App.cs
deleted file mode 100644
index bc5fcfd..0000000
--- a/samples/SharpEquations.Uno.Demo/App.cs
+++ /dev/null
@@ -1,60 +0,0 @@
-namespace SharpEquations.Uno.Demo
-{
- using Microsoft.UI.Xaml;
- using Microsoft.UI.Xaml.Controls;
- using Microsoft.UI.Xaml.Media;
- using SharpEquations;
-
- /// 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());
- var editor = new MathEditBox { FontSize = 28, Margin = new Thickness(0, 0, 0, 12) };
- var unicodeMath = new TextBlock { TextWrapping = TextWrapping.Wrap };
- var latex = new TextBlock { TextWrapping = TextWrapping.Wrap };
- var view = new MathView { FontSize = 22, IsDisplay = true };
- 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;
- };
- var panel = new StackPanel { Padding = new Thickness(24), Spacing = 8 };
- panel.Children.Add(new TextBlock { Text = "Type UnicodeMath or LaTeX: a space or an operator builds it up.", Opacity = 0.7 });
- panel.Children.Add(editor);
- panel.Children.Add(unicodeMath);
- panel.Children.Add(latex);
- panel.Children.Add(new TextBlock { Text = "MathView:", Opacity = 0.7 });
- 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 });
- // 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();
- }
- }
-}
diff --git a/samples/SharpEquations.Uno.Demo/App.xaml b/samples/SharpEquations.Uno.Demo/App.xaml
new file mode 100644
index 0000000..4287592
--- /dev/null
+++ b/samples/SharpEquations.Uno.Demo/App.xaml
@@ -0,0 +1,11 @@
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Uno.Demo/App.xaml.cs b/samples/SharpEquations.Uno.Demo/App.xaml.cs
new file mode 100644
index 0000000..80b16ec
--- /dev/null
+++ b/samples/SharpEquations.Uno.Demo/App.xaml.cs
@@ -0,0 +1,18 @@
+namespace SharpEquations.Uno.Demo
+{
+ using Microsoft.UI.Xaml;
+
+ /// The app of the demo: a window with .
+ public sealed partial class App : Application
+ {
+ private Window? window;
+
+ public App() => InitializeComponent();
+
+ protected override void OnLaunched(LaunchActivatedEventArgs args)
+ {
+ window = new Window { Content = new MainPage() };
+ window.Activate();
+ }
+ }
+}
diff --git a/samples/SharpEquations.Uno.Demo/MainPage.xaml b/samples/SharpEquations.Uno.Demo/MainPage.xaml
new file mode 100644
index 0000000..8587920
--- /dev/null
+++ b/samples/SharpEquations.Uno.Demo/MainPage.xaml
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Uno.Demo/MainPage.xaml.cs b/samples/SharpEquations.Uno.Demo/MainPage.xaml.cs
new file mode 100644
index 0000000..639b4e8
--- /dev/null
+++ b/samples/SharpEquations.Uno.Demo/MainPage.xaml.cs
@@ -0,0 +1,23 @@
+namespace SharpEquations.Uno.Demo
+{
+ using Microsoft.UI.Xaml.Controls;
+ using SharpEquations;
+
+ /// A page with the editor, the equation as UnicodeMath and LaTeX, and a view of it.
+ public sealed partial class MainPage : Page
+ {
+ public MainPage()
+ {
+ InitializeComponent();
+ if (System.Environment.GetEnvironmentVariable("SHARPEQUATIONS_DEMO_EQUATION") is { Length: > 0 } initial)
+ Editor.Equation = Equation.Parse(initial, EquationFormat.UnicodeMath, new EquationOptions { Display = true });
+ Editor.Loaded += (_, _) => Editor.FocusEditor();
+ }
+
+ private void OnEquationChanged(object? sender, EquationChangedEventArgs e)
+ {
+ UnicodeMath.Text = "UnicodeMath: " + (e.Equation?.ToString(EquationFormat.UnicodeMath) ?? string.Empty);
+ LaTeX.Text = "LaTeX: " + (e.Equation?.ToString(EquationFormat.LaTeX) ?? string.Empty);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Uno.Demo/Platforms/Windows/Program.cs b/samples/SharpEquations.Uno.Demo/Platforms/Windows/Program.cs
deleted file mode 100644
index ffab95b..0000000
--- a/samples/SharpEquations.Uno.Demo/Platforms/Windows/Program.cs
+++ /dev/null
@@ -1,22 +0,0 @@
-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 d080bbc..d745f4f 100644
--- a/samples/SharpEquations.Uno.Demo/SharpEquations.Uno.Demo.csproj
+++ b/samples/SharpEquations.Uno.Demo/SharpEquations.Uno.Demo.csproj
@@ -19,12 +19,10 @@
$(NoWarn);CA1016
-
+
None
true
- $(DefineConstants);DISABLE_XAML_GENERATED_MAIN
diff --git a/samples/SharpEquations.Wpf.Demo/App.xaml b/samples/SharpEquations.Wpf.Demo/App.xaml
new file mode 100644
index 0000000..511a3d2
--- /dev/null
+++ b/samples/SharpEquations.Wpf.Demo/App.xaml
@@ -0,0 +1,4 @@
+
diff --git a/samples/SharpEquations.Wpf.Demo/App.xaml.cs b/samples/SharpEquations.Wpf.Demo/App.xaml.cs
new file mode 100644
index 0000000..d0641ac
--- /dev/null
+++ b/samples/SharpEquations.Wpf.Demo/App.xaml.cs
@@ -0,0 +1,9 @@
+namespace SharpEquations.Wpf.Demo
+{
+ using System.Windows;
+
+ /// The app of the demo: it opens .
+ public partial class App : Application
+ {
+ }
+}
diff --git a/samples/SharpEquations.Wpf.Demo/MainWindow.xaml b/samples/SharpEquations.Wpf.Demo/MainWindow.xaml
new file mode 100644
index 0000000..a6e1b0b
--- /dev/null
+++ b/samples/SharpEquations.Wpf.Demo/MainWindow.xaml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/samples/SharpEquations.Wpf.Demo/MainWindow.xaml.cs b/samples/SharpEquations.Wpf.Demo/MainWindow.xaml.cs
new file mode 100644
index 0000000..21b6209
--- /dev/null
+++ b/samples/SharpEquations.Wpf.Demo/MainWindow.xaml.cs
@@ -0,0 +1,24 @@
+namespace SharpEquations.Wpf.Demo
+{
+ using System;
+ using System.Windows;
+ using SharpEquations;
+
+ /// A window with the editor, the equation as UnicodeMath and LaTeX, and a view of it.
+ public partial class MainWindow : Window
+ {
+ public MainWindow()
+ {
+ InitializeComponent();
+ if (Environment.GetEnvironmentVariable("SHARPEQUATIONS_DEMO_EQUATION") is { Length: > 0 } initial)
+ Editor.Equation = Equation.Parse(initial, EquationFormat.UnicodeMath, new EquationOptions { Display = true });
+ Editor.Loaded += (_, _) => Editor.Focus();
+ }
+
+ private void OnEquationChanged(object? sender, EquationChangedEventArgs e)
+ {
+ UnicodeMath.Text = "UnicodeMath: " + (e.Equation?.ToString(EquationFormat.UnicodeMath) ?? string.Empty);
+ LaTeX.Text = "LaTeX: " + (e.Equation?.ToString(EquationFormat.LaTeX) ?? string.Empty);
+ }
+ }
+}
diff --git a/samples/SharpEquations.Wpf.Demo/Program.cs b/samples/SharpEquations.Wpf.Demo/Program.cs
deleted file mode 100644
index 54d4d81..0000000
--- a/samples/SharpEquations.Wpf.Demo/Program.cs
+++ /dev/null
@@ -1,46 +0,0 @@
-namespace SharpEquations.Wpf.Demo
-{
- using System;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media;
- using SharpEquations;
-
- /// A window with the editor, the equation as UnicodeMath and LaTeX, and a view of it.
- public static class Program
- {
- [STAThread]
- public static void Main()
- {
- var editor = new MathEditBox { FontSize = 28, Margin = new Thickness(0, 0, 0, 12) };
- var unicodeMath = new TextBlock { TextWrapping = TextWrapping.Wrap };
- var latex = new TextBlock { TextWrapping = TextWrapping.Wrap };
- var view = new MathView { FontSize = 22, IsDisplay = true, HorizontalAlignment = HorizontalAlignment.Left };
- 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;
- };
- var panel = new StackPanel { Margin = new Thickness(24) };
- panel.Children.Add(new TextBlock { Text = "Type UnicodeMath or LaTeX: a space or an operator builds it up.", Opacity = 0.7, Margin = new Thickness(0, 0, 0, 8) });
- panel.Children.Add(editor);
- panel.Children.Add(unicodeMath);
- panel.Children.Add(latex);
- panel.Children.Add(new TextBlock { Text = "MathView:", Opacity = 0.7, Margin = new Thickness(0, 8, 0, 4) });
- panel.Children.Add(view);
- if (Environment.GetEnvironmentVariable("SHARPEQUATIONS_DEMO_EQUATION") is { Length: > 0 } initial)
- editor.Equation = Equation.Parse(initial, EquationFormat.UnicodeMath, new EquationOptions { Display = true });
- var window = new Window
- {
- Title = "SharpEquations for WPF",
- Width = 800,
- Height = 500,
- Background = Brushes.White,
- Content = panel,
- };
- editor.Loaded += (_, _) => editor.Focus();
- new Application().Run(window);
- }
- }
-}
diff --git a/tests/SharpEquations.Avalonia.Tests/MathTools/MathToolsWindowTests.cs b/tests/SharpEquations.Avalonia.Tests/MathTools/MathToolsWindowTests.cs
index 2a91944..5ec90be 100644
--- a/tests/SharpEquations.Avalonia.Tests/MathTools/MathToolsWindowTests.cs
+++ b/tests/SharpEquations.Avalonia.Tests/MathTools/MathToolsWindowTests.cs
@@ -81,10 +81,10 @@ public async Task FormulaOpensInTheCalculator()
window.Show();
var view = window.GetVisualDescendants().OfType().Single();
view.Tabs.SelectedIndex = 1;
- view.FormulaLibrary.Search.Text = "law";
+ view.ViewModel!.FormulaLibrary.Search = "law";
Save(window, "math-tools-formulas");
- var names = view.FormulaLibrary.Shown.Select(f => f.Name).ToList();
- view.FormulaLibrary.Open(Formulas.All.Single(f => f.Name == "Law of cosines"));
+ var names = view.ViewModel!.FormulaLibrary.Shown.Select(f => f.Name).ToList();
+ view.ViewModel!.FormulaLibrary.Open(Formulas.All.Single(f => f.Name == "Law of cosines"));
var result = (names, view.Calculator.Editor.Equation, view.Tabs.SelectedIndex);
window.Close();
return result;
@@ -104,21 +104,21 @@ public async Task UnitsConvert()
window.Show();
var view = window.GetVisualDescendants().OfType().Single();
view.Tabs.SelectedIndex = 2;
- var page = view.Converter;
- page.Value.Text = "42.195";
- page.From.SelectedItem = Units.Get("Length")["km"];
- page.To.SelectedItem = Units.Get("Length")["mi"];
+ var page = view.ViewModel!.Converter;
+ page.Value = "42.195";
+ page.From = Units.Get("Length")["km"];
+ page.To = Units.Get("Length")["mi"];
window.UpdateLayout();
var first = page.Result;
Save(window, "math-tools-units");
page.Swap();
var second = page.Result;
- page.Quantity.SelectedItem = Units.Get("Temperature");
- page.Value.Text = "98.6";
- page.From.SelectedItem = Units.Get("Temperature")["°F"];
- page.To.SelectedItem = Units.Get("Temperature")["°C"];
+ page.Quantity = Units.Get("Temperature");
+ page.Value = "98.6";
+ page.From = Units.Get("Temperature")["°F"];
+ page.To = Units.Get("Temperature")["°C"];
var third = page.Result;
- page.Value.Text = "abc";
+ page.Value = "abc";
var fourth = page.Result;
window.Close();
return (first, second, third, fourth);
@@ -138,7 +138,7 @@ public async Task TrianglesSolve()
window.Show();
var view = window.GetVisualDescendants().OfType().Single();
view.Tabs.SelectedIndex = 3;
- var page = view.TriangleSolver;
+ var page = view.ViewModel!.TriangleSolver;
window.UpdateLayout();
var first = page.Solution;
page.Fill(new[] { "6", "8", "", "40", "", "" });
@@ -167,19 +167,19 @@ public async Task CalculatorComputes()
var page = window.GetVisualDescendants().OfType().Single();
var display = new EquationOptions { Display = true };
page.Editor.Equation = Equation.Parse("√2+1/3", EquationFormat.UnicodeMath, display);
- await page.Solver.RefreshAnswer();
- var first = page.Solver.Answer;
+ await page.ViewModel!.Solver.RefreshAnswer();
+ var first = page.ViewModel!.Solver.Answer;
page.Editor.Equation = Equation.Parse("x^2-5x+6=0", EquationFormat.UnicodeMath, display);
- await page.Solver.RefreshAnswer();
- var second = await page.Solver.RunAsync(CasAction.Solve);
+ await page.ViewModel!.Solver.RefreshAnswer();
+ var second = await page.ViewModel!.Solver.RunAsync(CasAction.Solve);
page.Editor.Equation = Equation.Parse("x^3 sin x", EquationFormat.UnicodeMath, display);
- await page.Solver.RefreshAnswer();
- var third = await page.Solver.RunAsync(CasAction.Differentiate);
+ await page.ViewModel!.Solver.RefreshAnswer();
+ var third = await page.ViewModel!.Solver.RunAsync(CasAction.Differentiate);
window.Height = 1500;
Save(window, "math-tools-compute");
page.Editor.Equation = Equation.Parse("\"text\"", EquationFormat.UnicodeMath, display);
- await page.Solver.RefreshAnswer();
- var fourth = page.Solver.Answer;
+ await page.ViewModel!.Solver.RefreshAnswer();
+ var fourth = page.ViewModel!.Solver.Answer;
window.Close();
return (first, second, third, fourth);
});
@@ -203,15 +203,15 @@ public async Task CalculatorDefinesLettersAndTakesDegrees()
var page = window.GetVisualDescendants().OfType().Single();
var display = new EquationOptions { Display = true };
page.Editor.Equation = Equation.Parse("a≔3", EquationFormat.UnicodeMath, display);
- await page.Solver.RunAsync(CasAction.Define);
- var names = page.Solver.Engine.Definitions.Keys.ToList();
+ await page.ViewModel!.Solver.RunAsync(CasAction.Define);
+ var names = page.ViewModel!.Solver.Engine.Definitions.Keys.ToList();
page.Editor.Equation = Equation.Parse("a^2+1", EquationFormat.UnicodeMath, display);
- await page.Solver.RefreshAnswer();
- var first = page.Solver.Answer;
- page.Solver.Angles.SelectedIndex = 1;
+ await page.ViewModel!.Solver.RefreshAnswer();
+ var first = page.ViewModel!.Solver.Answer;
+ page.ViewModel!.Solver.AngleIndex = 1;
page.Editor.Equation = Equation.Parse("sin 30", EquationFormat.UnicodeMath, display);
- await page.Solver.RefreshAnswer();
- var second = page.Solver.Answer;
+ await page.ViewModel!.Solver.RefreshAnswer();
+ var second = page.ViewModel!.Solver.Answer;
window.Height = 1500;
Save(window, "math-tools-define");
window.Close();
@@ -235,28 +235,29 @@ public async Task GraphsDraw()
view.Tabs.SelectedIndex = 4;
var page = view.Graphs;
var display = new EquationOptions { Display = true };
- page.Clear();
- page.AddEquation(Equation.Parse("y=a x^2", EquationFormat.UnicodeMath, display));
- page.AddEquation(Equation.Parse("x^2+y^2=25", EquationFormat.UnicodeMath, display));
- page.AddEquation(Equation.Parse("r=1+cos θ", EquationFormat.UnicodeMath, display));
- var slider = page.Sliders.Single();
- slider.Value.Value = 0.5;
- var value = page.Graph.Curves[0].Plot[slider.Key.Parameter];
- var failed = page.AddEquation(Equation.Parse("2=3", EquationFormat.UnicodeMath, display));
+ var model = page.ViewModel!;
+ model.Clear();
+ model.AddEquation(Equation.Parse("y=a x^2", EquationFormat.UnicodeMath, display));
+ model.AddEquation(Equation.Parse("x^2+y^2=25", EquationFormat.UnicodeMath, display));
+ model.AddEquation(Equation.Parse("r=1+cos θ", EquationFormat.UnicodeMath, display));
+ var slider = model.Items.SelectMany(i => i.Parameters).Single();
+ slider.Value = 0.5;
+ var value = page.Graph.Curves[0].Plot[slider.Name];
+ var failed = model.AddEquation(Equation.Parse("2=3", EquationFormat.UnicodeMath, display));
window.Height = 1300;
Save(window, "math-tools-graphs");
var count = page.Graph.Curves.Count;
var shown = page.Graph.Curves.Select(c => c.Plot.Kind).ToList();
- var message = page.Error;
+ var message = model.Error;
view.Tabs.SelectedIndex = 0;
view.Calculator.Editor.Equation = Equation.Parse("y=sin x", EquationFormat.UnicodeMath, display);
- var requested = view.Calculator.Solver.RequestGraph();
- var result = (count, (slider.Key.Parameter, value), shown, failed, message, (requested, page.Graph.Curves.Count), view.Tabs.SelectedIndex);
+ var requested = view.Calculator.ViewModel!.Solver.RequestGraph();
+ var result = (count, (slider.Name, value), shown, failed, message, (requested, page.Graph.Curves.Count), view.Tabs.SelectedIndex);
window.Close();
return result;
});
await Assert.That(curves).IsEqualTo(3);
- await Assert.That(parameters.Parameter).IsEqualTo("a");
+ await Assert.That(parameters.Name).IsEqualTo("a");
await Assert.That(parameters.value).IsEqualTo(0.5);
await Assert.That(kinds).IsEquivalentTo(new[] { GraphKind.Function, GraphKind.Implicit, GraphKind.Polar });
await Assert.That(none).IsFalse();
@@ -278,20 +279,21 @@ public async Task GraphsInSpaceDraw()
view.Tabs.SelectedIndex = 5;
var page = view.Space;
var display = new EquationOptions { Display = true };
- page.Clear();
- page.AddEquation(Equation.Parse("z=a sin x cos y", EquationFormat.UnicodeMath, display));
- page.AddEquation(Equation.Parse("x=cos t, y=sin t, z=t/5", EquationFormat.UnicodeMath, display));
- var slider = page.Sliders.Single();
- slider.Value.Value = 2;
+ var model = page.ViewModel!;
+ model.Clear();
+ model.AddEquation(Equation.Parse("z=a sin x cos y", EquationFormat.UnicodeMath, display));
+ model.AddEquation(Equation.Parse("x=cos t, y=sin t, z=t/5", EquationFormat.UnicodeMath, display));
+ var slider = model.Items.SelectMany(i => i.Parameters).Single();
+ slider.Value = 2;
var value = page.Space.Surfaces[0].Plot["a"];
- var failed = page.AddEquation(Equation.Parse("y=x^2", EquationFormat.UnicodeMath, display));
+ var failed = model.AddEquation(Equation.Parse("y=x^2", EquationFormat.UnicodeMath, display));
window.Height = 1300;
Save(window, "math-tools-space");
var camera = page.Space.Camera;
page.Space.Camera = camera.Rotate(1, 0);
var turned = page.Space.Camera != camera;
page.Space.Reset();
- var result = (page.Space.Surfaces.Count, page.Space.Surfaces.Select(s => s.Plot.Kind).ToList(), slider.Key.Parameter, value, failed, page.Error,
+ var result = (page.Space.Surfaces.Count, page.Space.Surfaces.Select(s => s.Plot.Kind).ToList(), slider.Name, value, failed, model.Error,
page.Space.Renderer, (page.Space.Scene.Surfaces.Count, page.Space.Scene.Curves.Count), turned && page.Space.Camera == OrbitCamera.Default);
window.Close();
return result;
@@ -318,19 +320,20 @@ public async Task GraphsInSpaceShareParametersAndWait()
view.Tabs.SelectedIndex = 5;
var page = view.Space;
var display = new EquationOptions { Display = true };
- page.Clear();
- page.AddEquation(Equation.Parse("z=a x y", EquationFormat.UnicodeMath, display));
- page.AddEquation(Equation.Parse("z=a sin x", EquationFormat.UnicodeMath, display));
- var a = page.Sliders.Where(s => s.Key.Parameter == "a").ToList();
- a[0].Value.Value = 2;
+ var model = page.ViewModel!;
+ model.Clear();
+ model.AddEquation(Equation.Parse("z=a x y", EquationFormat.UnicodeMath, display));
+ model.AddEquation(Equation.Parse("z=a sin x", EquationFormat.UnicodeMath, display));
+ var a = model.Items.SelectMany(i => i.Parameters).Where(p => p.Name == "a").ToList();
+ a[0].Value = 2;
var pending = page.Space.IsRedrawPending;
page.Space.Redraw();
var drawn = !page.Space.IsRedrawPending;
var separate = page.Space.Surfaces[1].Plot["a"];
- page.SharedParameters.IsChecked = true;
+ model.SharedParameters = true;
var shared = page.Space.Surfaces[1].Plot["a"];
- a[0].Value.Value = 3;
- page.AddEquation(Equation.Parse("z=a+x", EquationFormat.UnicodeMath, display));
+ a[0].Value = 3;
+ model.AddEquation(Equation.Parse("z=a+x", EquationFormat.UnicodeMath, display));
var added = page.Space.Surfaces.Select(s => s.Plot["a"]).ToList();
window.UpdateLayout();
using var image = page.Space.Snapshot(2);
@@ -356,17 +359,17 @@ public async Task FormulaDrawsItsGraph()
var window = new MainWindow();
window.Show();
var view = window.GetVisualDescendants().OfType().Single();
- view.Graphs.Clear();
+ view.ViewModel!.Graphs.Clear();
view.Tabs.SelectedIndex = 1;
- view.FormulaLibrary.ShowSubject("Physics");
+ view.ViewModel!.FormulaLibrary.ShowSubject("Physics");
window.Height = 1300;
Save(window, "math-tools-formulas-physics");
- var drawn = view.FormulaLibrary.Graph(Formulas.All.Single(f => f.Name == "Damped oscillation"));
+ var drawn = view.ViewModel!.FormulaLibrary.Graph(Formulas.All.Single(f => f.Name == "Damped oscillation"));
Save(window, "math-tools-formula-graph");
var curve = view.Graphs.Graph.Curves.Single();
- var sliders = view.Graphs.Sliders.Keys.Select(k => k.Parameter).OrderBy(p => p, StringComparer.Ordinal).ToList();
- var values = (view.Graphs.Sliders[(curve, "γ")].Value, curve.Plot["γ"], curve.Plot["A"]);
- var none = view.FormulaLibrary.Graph(Formulas.All.Single(f => f.Name == "Law of cosines"));
+ var sliders = view.ViewModel!.Graphs.Items.SelectMany(i => i.Parameters).Select(p => p.Name).OrderBy(p => p, StringComparer.Ordinal).ToList();
+ var values = (view.ViewModel!.Graphs.Items.Single()["γ"].Value, curve.Plot["γ"], curve.Plot["A"]);
+ var none = view.ViewModel!.FormulaLibrary.Graph(Formulas.All.Single(f => f.Name == "Law of cosines"));
var result = (drawn, view.Tabs.SelectedIndex, sliders, values, none);
window.Close();
return result;
@@ -393,34 +396,34 @@ public async Task WorksheetComputesAndIsKept()
var page = view.Worksheet;
var display = new EquationOptions { Display = true };
page.Editor.Equation = Equation.Parse("b≔3", EquationFormat.UnicodeMath, display);
- page.SelectedAction = CasAction.Define;
- await page.EnterAsync();
+ page.ViewModel!.SelectedAction = CasAction.Define;
+ await page.ViewModel!.EnterAsync();
page.Editor.Equation = Equation.Parse("x^2-5x+6=0", EquationFormat.UnicodeMath, display);
- page.SelectedAction = CasAction.Solve;
- await page.EnterAsync();
+ page.ViewModel!.SelectedAction = CasAction.Solve;
+ await page.ViewModel!.EnterAsync();
page.Editor.Equation = Equation.Parse("sin(b t)", EquationFormat.UnicodeMath, display);
- page.SelectedAction = CasAction.Differentiate;
- page.Letter.SelectedItem = "t";
- await page.EnterAsync();
+ page.ViewModel!.SelectedAction = CasAction.Differentiate;
+ page.ViewModel!.Letter = "t";
+ await page.ViewModel!.EnterAsync();
page.Editor.Equation = Equation.Parse("(x+1)^3", EquationFormat.UnicodeMath, display);
- page.SelectedAction = CasAction.Expand;
- await page.EnterAsync();
+ page.ViewModel!.SelectedAction = CasAction.Expand;
+ await page.ViewModel!.EnterAsync();
page.Editor.Equation = null;
- var none = await page.EnterAsync();
+ var none = await page.ViewModel!.EnterAsync();
page.Editor.Equation = Equation.Parse("y=2x+1", EquationFormat.UnicodeMath, display);
window.Height = 1400;
Save(window, "math-tools-worksheet");
- var labels = page.Sheet.Entries.Select(e => e.Label).ToList();
+ var labels = page.ViewModel!.Sheet.Entries.Select(e => e.Label).ToList();
var curves = view.Graphs.Graph.Curves.Count;
var graph = window.GetVisualDescendants().OfType().Last(b => Equals(b.Content, "Graph") && b.FindAncestorOfType() != null);
- graph.RaiseEvent(new global::Avalonia.Interactivity.RoutedEventArgs(Button.ClickEvent));
- var result = (page.Sheet.Entries.Count, labels, none == null && page.Message.Length > 0, view.Graphs.Graph.Curves.Count - curves, view.Tabs.SelectedIndex, settings.Get("worksheet"), 0);
+ graph.Command!.Execute(graph.CommandParameter);
+ var result = (page.ViewModel!.Sheet.Entries.Count, labels, none == null && page.ViewModel!.Message.Length > 0, view.Graphs.Graph.Curves.Count - curves, view.Tabs.SelectedIndex, settings.Get("worksheet"), 0);
window.Close();
// a new window over the same settings has the worksheet back, and the letter defined
var again = new MainWindow(settings);
var back = again.GetVisualDescendants().OfType().SingleOrDefault() ?? (MathToolsView)again.Content!;
- result.Item7 = back.Worksheet.Sheet.Entries.Count + (back.Engine.Definitions.ContainsKey("b") ? 100 : 0);
+ result.Item7 = back.ViewModel!.Worksheet.Sheet.Entries.Count + (back.ViewModel!.Engine.Definitions.ContainsKey("b") ? 100 : 0);
return result;
});
await Assert.That(count).IsEqualTo(4);
@@ -443,17 +446,18 @@ public async Task GraphsShareParameters()
view.Tabs.SelectedIndex = 4;
var page = view.Graphs;
var display = new EquationOptions { Display = true };
- page.Clear();
- page.SharedParameters.IsChecked = false;
- page.AddEquation(Equation.Parse("y=a x", EquationFormat.UnicodeMath, display));
- page.AddEquation(Equation.Parse("y=a x^2", EquationFormat.UnicodeMath, display));
- var first = page.Sliders.First(s => s.Key.Curve == page.Graph.Curves[0]).Value;
+ var model = page.ViewModel!;
+ model.Clear();
+ model.SharedParameters = false;
+ model.AddEquation(Equation.Parse("y=a x", EquationFormat.UnicodeMath, display));
+ model.AddEquation(Equation.Parse("y=a x^2", EquationFormat.UnicodeMath, display));
+ var first = model.Items[0]["a"];
first.Value = 2;
var separate = page.Graph.Curves[1].Plot["a"];
- page.SharedParameters.IsChecked = true;
+ model.SharedParameters = true;
var shared = page.Graph.Curves[1].Plot["a"];
first.Value = 3;
- page.AddEquation(Equation.Parse("y=a+x", EquationFormat.UnicodeMath, display));
+ model.AddEquation(Equation.Parse("y=a+x", EquationFormat.UnicodeMath, display));
var values = page.Graph.Curves.Select(c => c.Plot["a"]).ToList();
window.UpdateLayout();
using var image = page.Graph.Snapshot(2);
diff --git a/tests/SharpEquations.Uno.Tests/Ui.cs b/tests/SharpEquations.Uno.Tests/Ui.cs
index 279c3d9..e535a62 100644
--- a/tests/SharpEquations.Uno.Tests/Ui.cs
+++ b/tests/SharpEquations.Uno.Tests/Ui.cs
@@ -50,6 +50,7 @@ public static async Task Show(FrameworkElement element)
window!.Content = new Grid
{
Background = new SolidColorBrush(Microsoft.UI.Colors.White),
+ RequestedTheme = ElementTheme.Light,
Padding = new Thickness(20),
Children = { new StackPanel { Children = { element } } },
};