diff --git a/src/GraphTUI/App.cs b/src/GraphTUI/App.cs index f9aa4b3..5b8de19 100644 --- a/src/GraphTUI/App.cs +++ b/src/GraphTUI/App.cs @@ -65,7 +65,9 @@ public sealed class App if (!arg.StartsWith('-')) { ColorRgb color = ColorRgb.Palette[(_nextFunctionId - 1) % ColorRgb.Palette.Length]; - _functions.Add(new GraphFunction(_nextFunctionId++, arg, color)); + var fn = new GraphFunction(_nextFunctionId++, arg, color); + _functions.Add(fn); + AutoDiscoverParameters(fn); } } } @@ -73,8 +75,12 @@ public sealed class App if (_functions.Count == 0) { // Default introductory functions - _functions.Add(new GraphFunction(_nextFunctionId++, "sin(x)", ColorRgb.Cyan)); - _functions.Add(new GraphFunction(_nextFunctionId++, "0.5*x", ColorRgb.Yellow)); + var f1 = new GraphFunction(_nextFunctionId++, "sin(x)", ColorRgb.Cyan); + var f2 = new GraphFunction(_nextFunctionId++, "0.5*x", ColorRgb.Yellow); + _functions.Add(f1); + _functions.Add(f2); + AutoDiscoverParameters(f1); + AutoDiscoverParameters(f2); } } @@ -82,6 +88,7 @@ public sealed class App { Console.OutputEncoding = System.Text.Encoding.UTF8; Console.Write(AnsiCodes.EnterAltScreen); + Console.Write(AnsiCodes.DisableAutoWrap); Console.Write(AnsiCodes.HideCursor); Console.Write(AnsiCodes.EnableMouse); @@ -118,6 +125,7 @@ public sealed class App { Console.Write(AnsiCodes.DisableMouse); Console.Write(AnsiCodes.ShowCursor); + Console.Write(AnsiCodes.EnableAutoWrap); Console.Write(AnsiCodes.ExitAltScreen); Console.Write(AnsiCodes.Reset); } @@ -148,6 +156,95 @@ public sealed class App return param?.Value ?? 0.0; } + public bool EvaluateUserFunction(string name, double[] args, in EvaluationContext callerCtx, out double result) + { + result = double.NaN; + if (callerCtx.CallDepth >= 64) return true; + + var fn = _functions.FirstOrDefault(f => f.IsDefinition && + f.DefinitionName != null && + f.DefinitionName.Equals(name, StringComparison.OrdinalIgnoreCase) && + f.DefinitionArgs != null && + f.DefinitionArgs.Length == args.Length); + if (fn?.DefinitionBody == null || fn.DefinitionArgs == null) + return false; + + Func localParamLookup = varName => + { + for (int i = 0; i < fn.DefinitionArgs.Length; i++) + { + if (fn.DefinitionArgs[i].Equals(varName, StringComparison.OrdinalIgnoreCase)) + return args[i]; + } + return GetParamValue(varName); + }; + + var ctx = new EvaluationContext( + x: args.Length > 0 ? args[0] : 0, + y: args.Length > 1 ? args[1] : 0, + parameterLookup: localParamLookup, + userFunctionLookup: EvaluateUserFunction, + callDepth: callerCtx.CallDepth + 1); + + result = fn.DefinitionBody.Evaluate(in ctx); + return true; + } + + private GraphFunction? GetActiveFunction() + { + if (_functions.Count == 0) return null; + int idx = System.Math.Clamp(_functionListView.SelectedIndex, 0, _functions.Count - 1); + var selected = _functions[idx]; + if (selected.IsVisible && selected.IsGraphable && selected.CompilationError == null) + return selected; + + return _functions.FirstOrDefault(f => f.IsVisible && f.IsGraphable && f.CompilationError == null); + } + + private void CycleTraceFunction(int direction) + { + var graphable = _functions.Where(f => f.IsVisible && f.IsGraphable && f.CompilationError == null).ToList(); + if (graphable.Count <= 1) return; + + var current = GetActiveFunction(); + int curIdx = current != null ? graphable.IndexOf(current) : 0; + int nextIdx = (curIdx + direction + graphable.Count) % graphable.Count; + var nextFn = graphable[nextIdx]; + + int listIdx = _functions.IndexOf(nextFn); + if (listIdx >= 0) + { + _functionListView.SelectedIndex = listIdx; + } + + UpdateTraceY(); + SetStatus($"Tracing curve #{nextFn.Id}: {nextFn.GetDisplayFormula()}"); + } + + private void AutoDiscoverParameters(GraphFunction fn) + { + var vars = new HashSet(StringComparer.OrdinalIgnoreCase); + fn.Evaluator?.Root.CollectVariables(vars); + fn.EvaluatorY?.Root.CollectVariables(vars); + fn.EvaluatorLhs?.Root.CollectVariables(vars); + fn.EvaluatorRhs?.Root.CollectVariables(vars); + fn.DefinitionBody?.CollectVariables(vars); + + string[] excluded = ["x", "y", "t", "theta", "th", "pi", "e", "tau", "phi"]; + var defArgs = fn.DefinitionArgs ?? []; + + foreach (var v in vars) + { + if (excluded.Contains(v, StringComparer.OrdinalIgnoreCase)) continue; + if (defArgs.Contains(v, StringComparer.OrdinalIgnoreCase)) continue; + if (_parameters.Any(p => p.Name.Equals(v, StringComparison.OrdinalIgnoreCase))) continue; + if (_functions.Any(f => f.IsDefinition && f.DefinitionName != null && f.DefinitionName.Equals(v, StringComparison.OrdinalIgnoreCase))) continue; + + _parameters.Add(new Parameter(v, 1.0, -10.0, 10.0, 0.1)); + SetStatus($"Created slider for parameter '{v}'"); + } + } + private void ProcessInput() { while (Console.KeyAvailable) @@ -237,7 +334,7 @@ public sealed class App if (key.Code == KeyCode.F3 || (key.Code == KeyCode.Char && key.KeyChar is 'c' or 'C' && _layout.CurrentFocus == FocusArea.Canvas)) { - var activeFn = _functions.FirstOrDefault(f => f.IsVisible && f.CompilationError == null); + var activeFn = GetActiveFunction(); _calculusModal.Open(activeFn, _viewport, GetParamValue); return; } @@ -284,7 +381,9 @@ public sealed class App break; case FocusArea.Sliders: - _slidersView.HandleKey(key, _parameters, () => { }); + _slidersView.HandleKey(key, _parameters, () => { }, + onAddNew: PromptAddParameter, + onEdit: PromptEditParameter); break; } } @@ -295,7 +394,7 @@ public sealed class App switch (key.Code) { - // Viewport Panning + // Viewport Panning & Trace Gliding case KeyCode.Left: case KeyCode.Char when key.KeyChar == 'h': if (_traceMode) @@ -324,12 +423,26 @@ public sealed class App case KeyCode.Up: case KeyCode.Char when key.KeyChar == 'k': - _viewport.PanByFraction(0, panFrac); + if (_traceMode) + { + CycleTraceFunction(-1); + } + else + { + _viewport.PanByFraction(0, panFrac); + } break; case KeyCode.Down: case KeyCode.Char when key.KeyChar == 'j': - _viewport.PanByFraction(0, -panFrac); + if (_traceMode) + { + CycleTraceFunction(1); + } + else + { + _viewport.PanByFraction(0, -panFrac); + } break; // Zooming @@ -355,7 +468,7 @@ public sealed class App if (_traceMode) { UpdateTraceY(); - SetStatus("Trace mode enabled. Use Left/Right to glide along curve."); + SetStatus("Trace mode enabled. Left/Right: Glide | Up/Down: Switch curve"); } else { @@ -371,16 +484,16 @@ public sealed class App private void UpdateTraceY() { - var fn = _functions.FirstOrDefault(f => f.IsVisible && f.CompilationError == null); + var fn = GetActiveFunction(); if (fn?.Evaluator != null) { if (fn.Type == FunctionType.Cartesian) { - _crosshairY = fn.Evaluator.Evaluate(_crosshairX, GetParamValue); + _crosshairY = fn.Evaluator.Evaluate(_crosshairX, GetParamValue, EvaluateUserFunction); } else if (fn.Type == FunctionType.CartesianX) { - _crosshairX = fn.Evaluator.EvaluateY(_crosshairY, GetParamValue); + _crosshairX = fn.Evaluator.EvaluateY(_crosshairY, GetParamValue, EvaluateUserFunction); } } } @@ -395,6 +508,7 @@ public sealed class App ColorRgb color = ColorRgb.Palette[(_nextFunctionId - 1) % ColorRgb.Palette.Length]; var fn = new GraphFunction(_nextFunctionId++, expr, color); _functions.Add(fn); + AutoDiscoverParameters(fn); SetStatus($"Loaded from cheatsheet: {fn.GetDisplayFormula()}"); }); return; @@ -440,7 +554,10 @@ public sealed class App if (mouse.Row >= _layout.SlidersTop && mouse.Row < _layout.SidebarTop + _layout.SidebarHeight) { _layout.CurrentFocus = FocusArea.Sliders; - _slidersView.HandleMouse(mouse, _layout.SidebarLeft, _layout.SlidersTop, _layout.SidebarWidth, _layout.SlidersHeight, _parameters, () => { }); + _slidersView.HandleMouse(mouse, _layout.SidebarLeft, _layout.SlidersTop, _layout.SidebarWidth, _layout.SlidersHeight, _parameters, + onStateChanged: () => { }, + onAddNew: PromptAddParameter, + onEdit: PromptEditParameter); return; } } @@ -516,14 +633,15 @@ public sealed class App private void PromptAddFunction() { - _commandBar.Open("Add equation (e.g. y=sin(x), y^2=x, y^2=sin(x)): ", "", expr => + _commandBar.Open("Add equation / definition (e.g. y=sin(x), f(x)=x^2+5, y^2=x): ", "", expr => { if (!string.IsNullOrWhiteSpace(expr)) { ColorRgb color = ColorRgb.Palette[(_nextFunctionId - 1) % ColorRgb.Palette.Length]; var fn = new GraphFunction(_nextFunctionId++, expr, color); _functions.Add(fn); - SetStatus($"Added: {fn.GetDisplayFormula()}"); + AutoDiscoverParameters(fn); + SetStatus(fn.IsDefinition ? $"Defined function: {fn.GetDisplayFormula()}" : $"Added: {fn.GetDisplayFormula()}"); } }); } @@ -535,11 +653,102 @@ public sealed class App if (!string.IsNullOrWhiteSpace(expr)) { fn.SetExpressions(expr, fn.ParametricY); + AutoDiscoverParameters(fn); SetStatus($"Updated: {fn.GetDisplayFormula()}"); } }); } + private void PromptAddParameter() + { + _commandBar.Open("Add param (name [val] [min] [max] [step]): ", "", input => + { + if (string.IsNullOrWhiteSpace(input)) return; + var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) return; + + string name = parts[0]; + double val = parts.Length > 1 && double.TryParse(parts[1], out double v) ? v : 1.0; + double min = parts.Length > 2 && double.TryParse(parts[2], out double mn) ? mn : -10.0; + double max = parts.Length > 3 && double.TryParse(parts[3], out double mx) ? mx : 10.0; + double step = parts.Length > 4 && double.TryParse(parts[4], out double st) ? st : 0.1; + + var existing = _parameters.FirstOrDefault(p => p.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + { + existing.SetRange(min, max, step); + existing.SetValue(val); + SetStatus($"Updated parameter '{name}' = {val:F2} [{min}, {max}]"); + } + else + { + _parameters.Add(new Parameter(name, val, min, max, step)); + SetStatus($"Added parameter '{name}' = {val:F2} [{min}, {max}]"); + } + }); + } + + private void PromptEditParameter(Parameter p) + { + _commandBar.Open($"Edit param '{p.Name}' (val min max [step]): ", $"{p.Value} {p.Min} {p.Max} {p.Step}", input => + { + if (string.IsNullOrWhiteSpace(input)) return; + var parts = input.Split(' ', StringSplitOptions.RemoveEmptyEntries); + if (parts.Length == 0) return; + + if (double.TryParse(parts[0], out double val)) + { + double min = parts.Length > 1 && double.TryParse(parts[1], out double mn) ? mn : p.Min; + double max = parts.Length > 2 && double.TryParse(parts[2], out double mx) ? mx : p.Max; + double step = parts.Length > 3 && double.TryParse(parts[3], out double st) ? st : p.Step; + + p.SetRange(min, max, step); + p.SetValue(val); + SetStatus($"Updated parameter '{p.Name}' = {val:F2} [{min}, {max}]"); + } + }); + } + + private static bool TryParseColor(string nameOrHex, out ColorRgb color) + { + color = ColorRgb.Cyan; + if (string.IsNullOrWhiteSpace(nameOrHex)) return false; + + string s = nameOrHex.Trim().ToLowerInvariant(); + switch (s) + { + case "red": color = ColorRgb.Red; return true; + case "green": color = ColorRgb.Green; return true; + case "blue": color = ColorRgb.Blue; return true; + case "yellow": color = ColorRgb.Yellow; return true; + case "cyan": color = ColorRgb.Cyan; return true; + case "magenta": color = ColorRgb.Magenta; return true; + case "orange": color = ColorRgb.Orange; return true; + case "purple": color = ColorRgb.Purple; return true; + case "white": color = ColorRgb.White; return true; + case "gray" or "grey": color = ColorRgb.Gray; return true; + case "darkgray" or "darkgrey": color = ColorRgb.DarkGray; return true; + } + + if (s.StartsWith('#') && s.Length == 7) + { + try + { + byte r = Convert.ToByte(s.Substring(1, 2), 16); + byte g = Convert.ToByte(s.Substring(3, 2), 16); + byte b = Convert.ToByte(s.Substring(5, 2), 16); + color = new ColorRgb(r, g, b); + return true; + } + catch + { + return false; + } + } + + return false; + } + private void LoadPreset(PresetDefinition preset) { _functions.Clear(); @@ -557,12 +766,15 @@ public sealed class App ThetaMax = preset.ThetaMax }; _functions.Add(fn); + AutoDiscoverParameters(fn); _viewport.Reset(); } private void ExecuteCommand(string input) { - string[] parts = input.Trim().Split(' ', StringSplitOptions.RemoveEmptyEntries); + string raw = input.Trim(); + if (raw.StartsWith(':')) raw = raw[1..].Trim(); + string[] parts = raw.Split(' ', StringSplitOptions.RemoveEmptyEntries); if (parts.Length == 0) return; string cmd = parts[0].ToLowerInvariant(); @@ -574,6 +786,169 @@ public sealed class App _isRunning = false; break; + case "del" or "rm": + if (int.TryParse(arg, out int delId)) + { + int removed = _functions.RemoveAll(f => f.Id == delId); + if (removed > 0) + { + SetStatus($"Deleted function #{delId}"); + if (_functionListView.SelectedIndex >= _functions.Count && _functionListView.SelectedIndex > 0) + _functionListView.SelectedIndex--; + } + else SetStatus($"Function #{delId} not found"); + } + else if (_functions.Count > 0) + { + int selIdx = System.Math.Clamp(_functionListView.SelectedIndex, 0, _functions.Count - 1); + int id = _functions[selIdx].Id; + _functions.RemoveAt(selIdx); + if (_functionListView.SelectedIndex >= _functions.Count && _functionListView.SelectedIndex > 0) + _functionListView.SelectedIndex--; + SetStatus($"Deleted function #{id}"); + } + break; + + case "show": + if (int.TryParse(arg, out int showId)) + { + var target = _functions.FirstOrDefault(f => f.Id == showId); + if (target != null) { target.IsVisible = true; SetStatus($"Function #{showId} shown"); } + else SetStatus($"Function #{showId} not found"); + } + break; + + case "hide": + if (int.TryParse(arg, out int hideId)) + { + var target = _functions.FirstOrDefault(f => f.Id == hideId); + if (target != null) { target.IsVisible = false; SetStatus($"Function #{hideId} hidden"); } + else SetStatus($"Function #{hideId} not found"); + } + break; + + case "toggle": + if (int.TryParse(arg, out int togId)) + { + var target = _functions.FirstOrDefault(f => f.Id == togId); + if (target != null) { target.IsVisible = !target.IsVisible; SetStatus($"Function #{togId} visibility: {target.IsVisible}"); } + else SetStatus($"Function #{togId} not found"); + } + else if (_functions.Count > 0) + { + var sel = _functions[System.Math.Clamp(_functionListView.SelectedIndex, 0, _functions.Count - 1)]; + sel.IsVisible = !sel.IsVisible; + SetStatus($"Function #{sel.Id} visibility: {sel.IsVisible}"); + } + break; + + case "color": + if (parts.Length >= 3 && int.TryParse(parts[1], out int colId)) + { + var target = _functions.FirstOrDefault(f => f.Id == colId); + if (target != null && TryParseColor(parts[2], out ColorRgb parsedCol)) + { + target.Color = parsedCol; + SetStatus($"Color of #{colId} updated"); + } + else SetStatus("Invalid color or function ID"); + } + else if (parts.Length >= 2 && _functions.Count > 0 && TryParseColor(parts[1], out ColorRgb parsedCol2)) + { + var sel = _functions[System.Math.Clamp(_functionListView.SelectedIndex, 0, _functions.Count - 1)]; + sel.Color = parsedCol2; + SetStatus($"Color of #{sel.Id} updated"); + } + break; + + case "edit": + if (int.TryParse(arg, out int editId)) + { + var target = _functions.FirstOrDefault(f => f.Id == editId); + if (target != null) EditFunction(target); + else SetStatus($"Function #{editId} not found"); + } + else if (_functions.Count > 0) + { + EditFunction(_functions[System.Math.Clamp(_functionListView.SelectedIndex, 0, _functions.Count - 1)]); + } + break; + + case "param": + if (parts.Length >= 3 && double.TryParse(parts[2], out double pVal)) + { + string pName = parts[1]; + double pMin = parts.Length > 3 && double.TryParse(parts[3], out double mn) ? mn : -10.0; + double pMax = parts.Length > 4 && double.TryParse(parts[4], out double mx) ? mx : 10.0; + double pStep = parts.Length > 5 && double.TryParse(parts[5], out double st) ? st : 0.1; + + var existing = _parameters.FirstOrDefault(p => p.Name.Equals(pName, StringComparison.OrdinalIgnoreCase)); + if (existing != null) + { + existing.SetRange(pMin, pMax, pStep); + existing.SetValue(pVal); + SetStatus($"Updated parameter '{pName}' = {pVal:F2} [{pMin}, {pMax}]"); + } + else + { + _parameters.Add(new Parameter(pName, pVal, pMin, pMax, pStep)); + SetStatus($"Added parameter '{pName}' = {pVal:F2} [{pMin}, {pMax}]"); + } + } + else + { + PromptAddParameter(); + } + break; + + case "delparam" or "rmparam": + if (!string.IsNullOrWhiteSpace(arg)) + { + int removed = _parameters.RemoveAll(p => p.Name.Equals(arg.Trim(), StringComparison.OrdinalIgnoreCase)); + if (removed > 0) SetStatus($"Deleted parameter '{arg.Trim()}'"); + else SetStatus($"Parameter '{arg.Trim()}' not found"); + } + break; + + case "view": + if (parts.Length >= 5 && + double.TryParse(parts[1], out double vxMin) && + double.TryParse(parts[2], out double vxMax) && + double.TryParse(parts[3], out double vyMin) && + double.TryParse(parts[4], out double vyMax)) + { + _viewport.XMin = vxMin; + _viewport.XMax = vxMax; + _viewport.YMin = vyMin; + _viewport.YMax = vyMax; + SetStatus($"Viewport set to [{vxMin}, {vxMax}] x [{vyMin}, {vyMax}]"); + } + else + { + SetStatus("Usage: :view "); + } + break; + + case "zoom": + if (parts.Length >= 2 && double.TryParse(parts[1], out double zFactor) && zFactor > 0) + { + _viewport.Zoom(1.0 / zFactor, _crosshairX, _crosshairY); + SetStatus($"Zoomed by factor {zFactor}"); + } + break; + + case "pan": + if (parts.Length >= 3 && double.TryParse(parts[1], out double pdx) && double.TryParse(parts[2], out double pdy)) + { + _viewport.Pan(pdx, pdy); + SetStatus($"Panned by ({pdx}, {pdy})"); + } + break; + + case "calc" or "calculus": + _calculusModal.Open(GetActiveFunction(), _viewport, GetParamValue); + break; + case "save": string savePath = string.IsNullOrWhiteSpace(arg) ? "session.json" : arg; SaveSession(savePath); @@ -620,11 +995,12 @@ public sealed class App break; default: - // Treat input as a formula to add + // Treat input as a formula or definition to add ColorRgb color = ColorRgb.Palette[(_nextFunctionId - 1) % ColorRgb.Palette.Length]; var fn = new GraphFunction(_nextFunctionId++, input, color); _functions.Add(fn); - SetStatus($"Added: {fn.GetDisplayFormula()}"); + AutoDiscoverParameters(fn); + SetStatus(fn.IsDefinition ? $"Defined function: {fn.GetDisplayFormula()}" : $"Added: {fn.GetDisplayFormula()}"); break; } } @@ -746,7 +1122,7 @@ public sealed class App { if (filename.EndsWith(".svg", StringComparison.OrdinalIgnoreCase)) { - string svg = SvgExporter.Export(_viewport, _functions, GetParamValue); + string svg = SvgExporter.Export(_viewport, _functions, GetParamValue, userFuncLookup: EvaluateUserFunction); File.WriteAllText(filename, svg); SetStatus($"Exported vector graph to {filename}"); } @@ -801,7 +1177,8 @@ public sealed class App showGrid: true, showCrosshair: _traceMode, crosshairX: _crosshairX, - crosshairY: _crosshairY); + crosshairY: _crosshairY, + userFuncLookup: EvaluateUserFunction); _screen.BlitBraille(_canvas, _layout.CanvasLeft, _layout.CanvasTop); @@ -863,10 +1240,20 @@ public sealed class App // Line 1: Status notification and viewport coordinates _screen.DrawText(0, row1, new string(' ', _layout.ScreenWidth), ColorRgb.White, ColorRgb.SidebarBg); + var activeFn = GetActiveFunction(); string vpInfo = $"X:[{_viewport.XMin:F2}, {_viewport.XMax:F2}] Y:[{_viewport.YMin:F2}, {_viewport.YMax:F2}]"; - string coordInfo = _traceMode - ? $"Trace: ({_crosshairX:F3}, {_crosshairY:F3}) dy/dx={Calculus.Derivative(x => _functions.FirstOrDefault(f => f.IsVisible)?.Evaluator?.Evaluate(x, GetParamValue) ?? 0, _crosshairX):F3}" - : $"Cursor: ({_crosshairX:F2}, {_crosshairY:F2})"; + string coordInfo; + + if (_traceMode && activeFn?.Evaluator != null) + { + double deriv = Calculus.Derivative(x => activeFn.Evaluator.Evaluate(x, GetParamValue, EvaluateUserFunction), _crosshairX); + string derivStr = double.IsNaN(deriv) ? "N/A" : deriv.ToString("F3"); + coordInfo = $"Trace [f{activeFn.Id}]: ({_crosshairX:F3}, {_crosshairY:F3}) dy/dx={derivStr}"; + } + else + { + coordInfo = $"Cursor: ({_crosshairX:F2}, {_crosshairY:F2})"; + } string leftStatus = (DateTime.UtcNow - _notificationTime).TotalSeconds < 10 ? _statusNotification @@ -881,7 +1268,15 @@ public sealed class App { _screen.DrawText(0, row2, new string(' ', _layout.ScreenWidth), ColorRgb.White, ColorRgb.DarkGray); string focusTag = $"[Focus: {_layout.CurrentFocus}]"; - string guide = "h/j/k/l: Pan | +/-: Zoom | a: Add | Spc: Toggle | c: Color | e: Edit | d: Del | q: Quit"; + string guide = _layout.CurrentFocus switch + { + FocusArea.Canvas => _traceMode + ? "Left/Right: Glide | Up/Down: Switch curve | +/-: Zoom | c: Calc | Esc: Exit trace" + : "h/j/k/l: Pan | +/-: Zoom | t: Trace | c: Calc | p: Presets | : cmd | Tab: Focus", + FocusArea.FunctionList => "Up/Down: Select | a: Add | e/Enter: Edit | Spc: Toggle | c: Color | d: Del | Tab: Focus", + FocusArea.Sliders => "Up/Down: Select | Left/Right: Adjust | a: Add | e/Enter: Edit Range | d: Del | Tab: Focus", + _ => "Tab: Cycle Focus | : cmd | ?: Help | q: Quit" + }; _screen.DrawText(2, row2, focusTag, ColorRgb.Accent, ColorRgb.DarkGray); _screen.DrawText(focusTag.Length + 4, row2, guide, ColorRgb.White, ColorRgb.DarkGray, _layout.ScreenWidth - focusTag.Length - 6); diff --git a/src/GraphTUI/Core/Math/AstNodes.cs b/src/GraphTUI/Core/Math/AstNodes.cs index 2611979..43336d3 100644 --- a/src/GraphTUI/Core/Math/AstNodes.cs +++ b/src/GraphTUI/Core/Math/AstNodes.cs @@ -28,6 +28,8 @@ public sealed class LocalScope } } +public delegate bool UserFunctionEvaluator(string name, double[] args, in EvaluationContext callerCtx, out double result); + public readonly struct EvaluationContext { public double X { get; } @@ -36,6 +38,8 @@ public readonly struct EvaluationContext public double Theta { get; } public LocalScope? Scope { get; } public Func? ParameterLookup { get; } + public UserFunctionEvaluator? UserFunctionLookup { get; } + public int CallDepth { get; } public EvaluationContext( double x = 0, @@ -43,7 +47,9 @@ public readonly struct EvaluationContext double t = 0, double theta = 0, LocalScope? scope = null, - Func? parameterLookup = null) + Func? parameterLookup = null, + UserFunctionEvaluator? userFunctionLookup = null, + int callDepth = 0) { X = x; Y = y; @@ -51,12 +57,19 @@ public readonly struct EvaluationContext Theta = theta; Scope = scope; ParameterLookup = parameterLookup; + UserFunctionLookup = userFunctionLookup; + CallDepth = callDepth; } public EvaluationContext WithScope(string name, double value) { var newScope = new LocalScope(name, value, Scope); - return new EvaluationContext(X, Y, T, Theta, newScope, ParameterLookup); + return new EvaluationContext(X, Y, T, Theta, newScope, ParameterLookup, UserFunctionLookup, CallDepth); + } + + public EvaluationContext WithNextCallDepth() + { + return new EvaluationContext(X, Y, T, Theta, Scope, ParameterLookup, UserFunctionLookup, CallDepth + 1); } } @@ -261,6 +274,23 @@ public sealed class FunctionCallNode : AstNode int argCount = Arguments.Length; if (argCount == 0) return double.NaN; + // 1. Check user-defined function lookup + if (ctx.CallDepth >= 64) return double.NaN; + + if (ctx.UserFunctionLookup != null) + { + double[] evalArgs = new double[argCount]; + for (int i = 0; i < argCount; i++) + { + evalArgs[i] = Arguments[i].Evaluate(in ctx); + } + + if (ctx.UserFunctionLookup(FunctionName, evalArgs, in ctx, out double userVal)) + { + return userVal; + } + } + double a0 = Arguments[0].Evaluate(in ctx); if (argCount == 1) diff --git a/src/GraphTUI/Core/Math/Evaluator.cs b/src/GraphTUI/Core/Math/Evaluator.cs index f116900..0540c2e 100644 --- a/src/GraphTUI/Core/Math/Evaluator.cs +++ b/src/GraphTUI/Core/Math/Evaluator.cs @@ -17,21 +17,21 @@ public sealed class Evaluator return new Evaluator(root, expression); } - public double Evaluate(double x, Func? parameterLookup = null) + public double Evaluate(double x, Func? parameterLookup = null, UserFunctionEvaluator? userFunctionLookup = null) { - var ctx = new EvaluationContext(x: x, parameterLookup: parameterLookup); + var ctx = new EvaluationContext(x: x, parameterLookup: parameterLookup, userFunctionLookup: userFunctionLookup); return Root.Evaluate(in ctx); } - public double Evaluate(double x, double y, Func? parameterLookup = null) + public double Evaluate(double x, double y, Func? parameterLookup = null, UserFunctionEvaluator? userFunctionLookup = null) { - var ctx = new EvaluationContext(x: x, y: y, parameterLookup: parameterLookup); + var ctx = new EvaluationContext(x: x, y: y, parameterLookup: parameterLookup, userFunctionLookup: userFunctionLookup); return Root.Evaluate(in ctx); } - public double EvaluateY(double y, Func? parameterLookup = null) + public double EvaluateY(double y, Func? parameterLookup = null, UserFunctionEvaluator? userFunctionLookup = null) { - var ctx = new EvaluationContext(y: y, parameterLookup: parameterLookup); + var ctx = new EvaluationContext(y: y, parameterLookup: parameterLookup, userFunctionLookup: userFunctionLookup); return Root.Evaluate(in ctx); } @@ -47,27 +47,27 @@ public sealed class Evaluator return GetVariables().Contains(varName); } - public double EvaluateParametricX(double t, Func? parameterLookup = null) + public double EvaluateParametricX(double t, Func? parameterLookup = null, UserFunctionEvaluator? userFunctionLookup = null) { - var ctx = new EvaluationContext(t: t, parameterLookup: parameterLookup); + var ctx = new EvaluationContext(t: t, parameterLookup: parameterLookup, userFunctionLookup: userFunctionLookup); return Root.Evaluate(in ctx); } - public double EvaluateParametricY(double t, Func? parameterLookup = null) + public double EvaluateParametricY(double t, Func? parameterLookup = null, UserFunctionEvaluator? userFunctionLookup = null) { - var ctx = new EvaluationContext(t: t, parameterLookup: parameterLookup); + var ctx = new EvaluationContext(t: t, parameterLookup: parameterLookup, userFunctionLookup: userFunctionLookup); return Root.Evaluate(in ctx); } - public double EvaluatePolar(double theta, Func? parameterLookup = null) + public double EvaluatePolar(double theta, Func? parameterLookup = null, UserFunctionEvaluator? userFunctionLookup = null) { - var ctx = new EvaluationContext(theta: theta, parameterLookup: parameterLookup); + var ctx = new EvaluationContext(theta: theta, parameterLookup: parameterLookup, userFunctionLookup: userFunctionLookup); return Root.Evaluate(in ctx); } - public double EvaluateFull(double x, double t, double theta, Func? parameterLookup = null) + public double EvaluateFull(double x, double t, double theta, Func? parameterLookup = null, UserFunctionEvaluator? userFunctionLookup = null) { - var ctx = new EvaluationContext(x: x, t: t, theta: theta, parameterLookup: parameterLookup); + var ctx = new EvaluationContext(x: x, t: t, theta: theta, parameterLookup: parameterLookup, userFunctionLookup: userFunctionLookup); return Root.Evaluate(in ctx); } } diff --git a/src/GraphTUI/Core/Math/Lexer.cs b/src/GraphTUI/Core/Math/Lexer.cs index 05dbabe..e4685fc 100644 --- a/src/GraphTUI/Core/Math/Lexer.cs +++ b/src/GraphTUI/Core/Math/Lexer.cs @@ -4,7 +4,7 @@ namespace GraphTUI.Core.Math; public sealed class Lexer { - private static readonly HashSet KnownFunctions = new(StringComparer.OrdinalIgnoreCase) + public static readonly HashSet KnownFunctions = new(StringComparer.OrdinalIgnoreCase) { "sin", "cos", "tan", "cot", "sec", "csc", "asin", "acos", "atan", "atan2", @@ -12,7 +12,7 @@ public sealed class Lexer "exp", "ln", "log", "log2", "log10", "sqrt", "cbrt", "abs", "floor", "ceil", "round", "sgn", "sign", "min", "max", "clamp", - "sum", "prod", "int", "integral", "diff", "deriv", "derivative", "fact", "gamma", + "sum", "prod", "int", "integral", "diff", "deriv", "derivative", "fact", "factorial", "gamma", "dfact", "doublefact", "sfact", "superfact" }; @@ -183,7 +183,7 @@ public sealed class Lexer TokenType.Factorial => true, TokenType.DoubleFactorial => true, TokenType.SuperFactorial => true, - TokenType.Identifier => !KnownFunctions.Contains(curr.Text) || next.Type != TokenType.LParen, + TokenType.Identifier => next.Type != TokenType.LParen || IsImplicitMulBeforeParen(curr.Text), _ => false }; @@ -204,4 +204,19 @@ public sealed class Lexer return result; } + + private static bool IsImplicitMulBeforeParen(string ident) => + ident.Equals("x", StringComparison.OrdinalIgnoreCase) || + ident.Equals("y", StringComparison.OrdinalIgnoreCase) || + ident.Equals("t", StringComparison.OrdinalIgnoreCase) || + ident.Equals("theta", StringComparison.OrdinalIgnoreCase) || + ident.Equals("θ", StringComparison.OrdinalIgnoreCase) || + ident.Equals("th", StringComparison.OrdinalIgnoreCase) || + ident.Equals("pi", StringComparison.OrdinalIgnoreCase) || + ident.Equals("π", StringComparison.OrdinalIgnoreCase) || + ident.Equals("e", StringComparison.OrdinalIgnoreCase) || + ident.Equals("tau", StringComparison.OrdinalIgnoreCase) || + ident.Equals("τ", StringComparison.OrdinalIgnoreCase) || + ident.Equals("phi", StringComparison.OrdinalIgnoreCase) || + ident.Equals("φ", StringComparison.OrdinalIgnoreCase); } diff --git a/src/GraphTUI/Core/Math/Parser.cs b/src/GraphTUI/Core/Math/Parser.cs index 792782f..d58325f 100644 --- a/src/GraphTUI/Core/Math/Parser.cs +++ b/src/GraphTUI/Core/Math/Parser.cs @@ -182,6 +182,7 @@ public sealed class Parser } Expect(TokenType.RParen, "Expected ')' after function arguments."); + ValidateBuiltinFunctionArgs(name, args.Count); return new FunctionCallNode(name, args.ToArray()); } @@ -198,18 +199,71 @@ public sealed class Parser throw new FormatException($"Unexpected token '{token.Text}' at position {token.Position}"); } + private static void ValidateBuiltinFunctionArgs(string name, int count) + { + string lower = name.ToLowerInvariant(); + if (!Lexer.KnownFunctions.Contains(lower)) + return; // Could be a user-defined function + + int minArgs = lower switch + { + "atan2" or "min" or "max" => 2, + "clamp" => 3, + _ => 1 + }; + + int maxArgs = lower switch + { + "log" => 2, + "atan2" or "min" or "max" => 2, + "clamp" => 3, + _ => 1 + }; + + if (count < minArgs || count > maxArgs) + { + throw new FormatException($"Function '{name}' expects {(minArgs == maxArgs ? minArgs.ToString() : $"{minArgs} to {maxArgs}")} argument(s), but received {count}."); + } + } + + private int CountTopLevelCommas() + { + int depth = 0; + int commas = 0; + for (int i = _pos; i < _tokens.Count; i++) + { + var t = _tokens[i]; + if (t.Type == TokenType.LParen) depth++; + else if (t.Type == TokenType.RParen) + { + if (depth == 0) break; + depth--; + } + else if (t.Type == TokenType.Comma && depth == 0) + { + commas++; + } + } + return commas; + } + private AstNode ParseSum() { + int commas = CountTopLevelCommas(); string varName = "n"; - if (Current.Type == TokenType.Identifier) - { - varName = Current.Text; - _pos++; - if (!Match(TokenType.Equals) && !Match(TokenType.Comma)) - { - throw new FormatException($"Expected '=' or ',' after loop variable in sum at position {Current.Position}"); - } + if (commas >= 3) + { + // sum(n, start, end, body) + Expect(TokenType.Identifier, "Expected loop variable name in sum."); + varName = _tokens[_pos - 1].Text; + Expect(TokenType.Comma, "Expected ',' after loop variable in sum."); + } + else if (Current.Type == TokenType.Identifier && _pos + 1 < _tokens.Count && _tokens[_pos + 1].Type == TokenType.Equals) + { + // sum(n=start, end, body) + varName = Current.Text; + _pos += 2; } var start = ParseBinary(0); @@ -224,16 +278,21 @@ public sealed class Parser private AstNode ParseProduct() { + int commas = CountTopLevelCommas(); string varName = "n"; - if (Current.Type == TokenType.Identifier) - { - varName = Current.Text; - _pos++; - if (!Match(TokenType.Equals) && !Match(TokenType.Comma)) - { - throw new FormatException($"Expected '=' or ',' after loop variable in prod at position {Current.Position}"); - } + if (commas >= 3) + { + // prod(n, start, end, body) + Expect(TokenType.Identifier, "Expected loop variable name in prod."); + varName = _tokens[_pos - 1].Text; + Expect(TokenType.Comma, "Expected ',' after loop variable in prod."); + } + else if (Current.Type == TokenType.Identifier && _pos + 1 < _tokens.Count && _tokens[_pos + 1].Type == TokenType.Equals) + { + // prod(n=start, end, body) + varName = Current.Text; + _pos += 2; } var start = ParseBinary(0); @@ -248,16 +307,21 @@ public sealed class Parser private AstNode ParseIntegral() { + int commas = CountTopLevelCommas(); string varName = "t"; - if (Current.Type == TokenType.Identifier) - { - varName = Current.Text; - _pos++; - if (!Match(TokenType.Equals) && !Match(TokenType.Comma)) - { - throw new FormatException($"Expected '=' or ',' after variable in integral at position {Current.Position}"); - } + if (commas >= 3) + { + // int(t, lower, upper, integrand) + Expect(TokenType.Identifier, "Expected variable name in integral."); + varName = _tokens[_pos - 1].Text; + Expect(TokenType.Comma, "Expected ',' after variable in integral."); + } + else if (Current.Type == TokenType.Identifier && _pos + 1 < _tokens.Count && _tokens[_pos + 1].Type == TokenType.Equals) + { + // int(t=lower, upper, integrand) + varName = Current.Text; + _pos += 2; } var lower = ParseBinary(0); @@ -272,42 +336,40 @@ public sealed class Parser private AstNode ParseDerivative() { - // Check if syntax is: diff(t=x, f(t)) or diff(t, x, f(t)) - if (Current.Type == TokenType.Identifier && _pos + 1 < _tokens.Count && - (_tokens[_pos + 1].Type == TokenType.Equals || _tokens[_pos + 1].Type == TokenType.Comma)) + int commas = CountTopLevelCommas(); + + if (commas >= 2) { - string varName = Current.Text; - _pos++; - - bool hadEquals = Match(TokenType.Equals); - bool hadComma = !hadEquals && Match(TokenType.Comma); - - var firstExpr = ParseBinary(0); - - if (Match(TokenType.Comma)) - { - // diff(t, x, f(t)) or diff(t=x, f(t)) - var body = ParseBinary(0); - Expect(TokenType.RParen, "Expected ')' after derivative expression."); - return new DerivativeNode(varName, firstExpr, body); - } - else - { - // diff(var, expr) where evaluation point defaults to var - Expect(TokenType.RParen, "Expected ')' after derivative expression."); - return new DerivativeNode(varName, new VariableNode(varName), firstExpr); - } - } - else - { - // diff(f(x), x) - var body = ParseBinary(0); - Expect(TokenType.Comma, "Expected ',' after expression in diff."); - string varName = Current.Text; + // diff(t, x, f(t)) Expect(TokenType.Identifier, "Expected variable name in diff."); - Expect(TokenType.RParen, "Expected ')' after diff."); - return new DerivativeNode(varName, new VariableNode(varName), body); + string varName = _tokens[_pos - 1].Text; + Expect(TokenType.Comma, "Expected ',' after variable in diff."); + var atExpr = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after evaluation point in diff."); + var body = ParseBinary(0); + Expect(TokenType.RParen, "Expected ')' after derivative expression."); + return new DerivativeNode(varName, atExpr, body); } + + if (Current.Type == TokenType.Identifier && _pos + 1 < _tokens.Count && _tokens[_pos + 1].Type == TokenType.Equals) + { + // diff(t=x, f(t)) + string varName = Current.Text; + _pos += 2; + var atExpr = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after evaluation point in diff."); + var body = ParseBinary(0); + Expect(TokenType.RParen, "Expected ')' after derivative expression."); + return new DerivativeNode(varName, atExpr, body); + } + + // diff(f(x), x) + var exprBody = ParseBinary(0); + Expect(TokenType.Comma, "Expected ',' after expression in diff."); + string diffVar = Current.Text; + Expect(TokenType.Identifier, "Expected variable name in diff."); + Expect(TokenType.RParen, "Expected ')' after diff."); + return new DerivativeNode(diffVar, new VariableNode(diffVar), exprBody); } private Token Current => _pos < _tokens.Count ? _tokens[_pos] : _tokens[^1]; diff --git a/src/GraphTUI/Core/Models/FunctionType.cs b/src/GraphTUI/Core/Models/FunctionType.cs index 59b8561..0fa1cef 100644 --- a/src/GraphTUI/Core/Models/FunctionType.cs +++ b/src/GraphTUI/Core/Models/FunctionType.cs @@ -6,5 +6,6 @@ public enum FunctionType CartesianX, // x = f(y) or f(y) = x Implicit, // f(y) = g(x) or F(x, y) = 0 Parametric, // x = x(t), y = y(t) - Polar // r = f(theta) + Polar, // r = f(theta) + Definition // f(x) = ... or g(x, y) = ... } diff --git a/src/GraphTUI/Core/Models/GraphFunction.cs b/src/GraphTUI/Core/Models/GraphFunction.cs index 9542288..3599bbc 100644 --- a/src/GraphTUI/Core/Models/GraphFunction.cs +++ b/src/GraphTUI/Core/Models/GraphFunction.cs @@ -32,6 +32,13 @@ public sealed class GraphFunction public Evaluator? EvaluatorRhs { get; private set; } public string? CompilationError { get; private set; } + // User-defined function definition fields + public string? DefinitionName { get; private set; } + public string[]? DefinitionArgs { get; private set; } + public AstNode? DefinitionBody { get; private set; } + public bool IsDefinition => Type == FunctionType.Definition; + public bool IsGraphable => Type != FunctionType.Definition; + public GraphFunction(int id, string expression, ColorRgb color, FunctionType type = FunctionType.Cartesian, string parametricY = "") { Id = id; @@ -54,6 +61,9 @@ public sealed class GraphFunction EvaluatorY = null; EvaluatorLhs = null; EvaluatorRhs = null; + DefinitionName = null; + DefinitionArgs = null; + DefinitionBody = null; if (string.IsNullOrWhiteSpace(Expression)) { @@ -61,7 +71,51 @@ public sealed class GraphFunction return; } - // Parametric mode + string trimmedExpr = Expression.Trim(); + + // 1. Auto-detect Parametric in format (f(t), g(t)) or x=f(t), y=g(t) + if (Type != FunctionType.Parametric && trimmedExpr.StartsWith('(') && trimmedExpr.EndsWith(')') && trimmedExpr.Contains(',')) + { + string inner = trimmedExpr[1..^1].Trim(); + int splitIdx = -1; + int depth = 0; + for (int i = 0; i < inner.Length; i++) + { + if (inner[i] == '(') depth++; + else if (inner[i] == ')') depth--; + else if (inner[i] == ',' && depth == 0) + { + splitIdx = i; + break; + } + } + if (splitIdx > 0) + { + string xPart = inner[..splitIdx].Trim(); + string yPart = inner[(splitIdx + 1)..].Trim(); + Type = FunctionType.Parametric; + Expression = xPart; + ParametricY = yPart; + } + } + + // 2. Auto-detect Polar mode: starts with "r =" or contains theta/th without x or y + if (Type != FunctionType.Polar && (trimmedExpr.StartsWith("r =", StringComparison.OrdinalIgnoreCase) || trimmedExpr.StartsWith("r=", StringComparison.OrdinalIgnoreCase) || + ((trimmedExpr.Contains("theta", StringComparison.OrdinalIgnoreCase) || trimmedExpr.Contains('θ') || trimmedExpr.Contains("th", StringComparison.OrdinalIgnoreCase)) && + !trimmedExpr.Contains('x', StringComparison.OrdinalIgnoreCase) && !trimmedExpr.Contains('y', StringComparison.OrdinalIgnoreCase)))) + { + Type = FunctionType.Polar; + if (trimmedExpr.Contains('=')) + { + var eqParts = trimmedExpr.Split('=', 2); + if (eqParts[0].Trim().Equals("r", StringComparison.OrdinalIgnoreCase)) + { + Expression = eqParts[1].Trim(); + } + } + } + + // 3. Parametric mode if (Type == FunctionType.Parametric) { try @@ -81,7 +135,7 @@ public sealed class GraphFunction return; } - // Polar mode + // 4. Polar mode if (Type == FunctionType.Polar) { try @@ -90,7 +144,10 @@ public sealed class GraphFunction if (polarExpr.Contains('=')) { var eqParts = polarExpr.Split('=', 2); - polarExpr = eqParts[1].Trim(); + if (eqParts[0].Trim().Equals("r", StringComparison.OrdinalIgnoreCase)) + { + polarExpr = eqParts[1].Trim(); + } } Evaluator = Evaluator.Compile(polarExpr); } @@ -101,7 +158,7 @@ public sealed class GraphFunction return; } - // Cartesian / CartesianX / Implicit modes (auto-classified or double-sided) + // 5. Function Definition or Cartesian / CartesianX / Implicit try { if (Expression.Contains('=')) @@ -110,6 +167,18 @@ public sealed class GraphFunction string leftStr = parts[0].Trim(); string rightStr = parts[1].Trim(); + // Check for User-Defined Function Definition: f(x) = expr or g(x, y) = expr + if (TryParseFunctionDefinition(leftStr, out string defName, out string[] defArgs)) + { + Type = FunctionType.Definition; + DefinitionName = defName; + DefinitionArgs = defArgs; + DefinitionBody = Parser.Parse(rightStr); + Evaluator = Evaluator.Compile(rightStr); + IsVisible = false; // Function definitions are not graphed directly + return; + } + var leftEval = Evaluator.Compile(leftStr); var rightEval = Evaluator.Compile(rightStr); @@ -187,10 +256,48 @@ public sealed class GraphFunction } } + private static bool TryParseFunctionDefinition(string leftStr, out string defName, out string[] defArgs) + { + defName = string.Empty; + defArgs = []; + + int openParen = leftStr.IndexOf('('); + int closeParen = leftStr.LastIndexOf(')'); + + if (openParen > 0 && closeParen == leftStr.Length - 1 && closeParen > openParen) + { + string name = leftStr[..openParen].Trim(); + if (IsValidIdentifier(name) && !Lexer.KnownFunctions.Contains(name)) + { + string argsInside = leftStr[(openParen + 1)..closeParen].Trim(); + string[] rawArgs = argsInside.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (rawArgs.Length > 0 && rawArgs.All(IsValidIdentifier)) + { + defName = name; + defArgs = rawArgs; + return true; + } + } + } + return false; + } + + private static bool IsValidIdentifier(string name) + { + if (string.IsNullOrWhiteSpace(name)) return false; + if (!char.IsLetter(name[0]) && name[0] != '_') return false; + for (int i = 1; i < name.Length; i++) + { + if (!char.IsLetterOrDigit(name[i]) && name[i] != '_') return false; + } + return true; + } + public string GetDisplayFormula() { return Type switch { + FunctionType.Definition => Expression, FunctionType.Cartesian => Expression.Contains('=') ? Expression : $"y = {Expression}", FunctionType.CartesianX => Expression.Contains('=') ? Expression : $"x = {Expression}", FunctionType.Implicit => Expression.Contains('=') ? Expression : $"{Expression} = 0", diff --git a/src/GraphTUI/Core/Models/Parameter.cs b/src/GraphTUI/Core/Models/Parameter.cs index cb7388c..eec31f9 100644 --- a/src/GraphTUI/Core/Models/Parameter.cs +++ b/src/GraphTUI/Core/Models/Parameter.cs @@ -26,4 +26,22 @@ public sealed class Parameter { Value = System.Math.Clamp(System.Math.Round(Value - Step * multiplier, 4), Min, Max); } + + public void SetValue(double val) + { + Value = System.Math.Clamp(val, Min, Max); + } + + public void SetRange(double min, double max, double? step = null) + { + if (min > max) (min, max) = (max, min); + if (System.Math.Abs(min - max) < 1e-9) max = min + 1.0; + Min = min; + Max = max; + if (step.HasValue && step.Value > 0) + { + Step = step.Value; + } + Value = System.Math.Clamp(Value, Min, Max); + } } diff --git a/src/GraphTUI/Core/Models/Viewport.cs b/src/GraphTUI/Core/Models/Viewport.cs index 69ad255..c308f36 100644 --- a/src/GraphTUI/Core/Models/Viewport.cs +++ b/src/GraphTUI/Core/Models/Viewport.cs @@ -18,16 +18,21 @@ public sealed class Viewport YMax = 5.0; } - public void PanByFraction(double fracX, double fracY) + public void Pan(double dx, double dy) { - double dx = Width * fracX; - double dy = Height * fracY; XMin += dx; XMax += dx; YMin += dy; YMax += dy; } + public void PanByFraction(double fracX, double fracY) + { + double dx = Width * fracX; + double dy = Height * fracY; + Pan(dx, dy); + } + public void Zoom(double factor, double centerX, double centerY) { if (factor <= 0 || double.IsNaN(factor) || double.IsInfinity(factor)) return; diff --git a/src/GraphTUI/Rendering/BrailleCanvas.cs b/src/GraphTUI/Rendering/BrailleCanvas.cs index 0b13935..f1506e0 100644 --- a/src/GraphTUI/Rendering/BrailleCanvas.cs +++ b/src/GraphTUI/Rendering/BrailleCanvas.cs @@ -106,7 +106,7 @@ public sealed class BrailleCanvas int code1 = ComputeOutCode(x1, y1, xmin, ymin, xmax, ymax); bool accept = false; - for (int iter = 0; iter < 4; iter++) + for (int iter = 0; iter < 8; iter++) { if ((code0 | code1) == 0) { @@ -156,6 +156,11 @@ public sealed class BrailleCanvas } } + if (!accept) + { + accept = (code0 | code1) == 0; + } + if (!accept) return; int cx0 = System.Math.Clamp((int)System.Math.Round(x0), 0, SubpixelWidth - 1); diff --git a/src/GraphTUI/Rendering/PlotRenderer.cs b/src/GraphTUI/Rendering/PlotRenderer.cs index a12fd60..0b16ee5 100644 --- a/src/GraphTUI/Rendering/PlotRenderer.cs +++ b/src/GraphTUI/Rendering/PlotRenderer.cs @@ -15,7 +15,8 @@ public sealed class PlotRenderer bool showGrid = true, bool showCrosshair = false, double crosshairX = 0, - double crosshairY = 0) + double crosshairY = 0, + UserFunctionEvaluator? userFuncLookup = null) { canvas.Clear(ColorRgb.Background); var ticks = new List(); @@ -41,10 +42,10 @@ public sealed class PlotRenderer // 4. Render Functions & Calculus Overlays foreach (var fn in functions) { - if (!fn.IsVisible || fn.CompilationError != null) + if (!fn.IsVisible || !fn.IsGraphable || fn.CompilationError != null) continue; - RenderFunction(canvas, viewport, fn, paramLookup, crosshairX); + RenderFunction(canvas, viewport, fn, paramLookup, crosshairX, userFuncLookup); } // 5. Crosshair @@ -167,24 +168,25 @@ public sealed class PlotRenderer Viewport viewport, GraphFunction fn, Func? paramLookup, - double crosshairX) + double crosshairX, + UserFunctionEvaluator? userFuncLookup) { switch (fn.Type) { case FunctionType.Cartesian: - RenderCartesian(canvas, viewport, fn, paramLookup, crosshairX); + RenderCartesian(canvas, viewport, fn, paramLookup, crosshairX, userFuncLookup); break; case FunctionType.CartesianX: - RenderCartesianX(canvas, viewport, fn, paramLookup); + RenderCartesianX(canvas, viewport, fn, paramLookup, userFuncLookup); break; case FunctionType.Implicit: - RenderImplicit(canvas, viewport, fn, paramLookup); + RenderImplicit(canvas, viewport, fn, paramLookup, userFuncLookup); break; case FunctionType.Parametric: - RenderParametric(canvas, viewport, fn, paramLookup); + RenderParametric(canvas, viewport, fn, paramLookup, userFuncLookup); break; case FunctionType.Polar: - RenderPolar(canvas, viewport, fn, paramLookup); + RenderPolar(canvas, viewport, fn, paramLookup, userFuncLookup); break; } } @@ -194,7 +196,8 @@ public sealed class PlotRenderer Viewport viewport, GraphFunction fn, Func? paramLookup, - double crosshairX) + double crosshairX, + UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null) return; @@ -218,7 +221,7 @@ public sealed class PlotRenderer viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); if (x >= xStart && x <= xEnd) { - double y = fn.Evaluator.Evaluate(x, paramLookup); + double y = fn.Evaluator.Evaluate(x, paramLookup, userFuncLookup); if (!double.IsNaN(y) && !double.IsInfinity(y)) { if (viewport.MathToSubpixel(x, y, subW, subH, out _, out int curveY)) @@ -238,7 +241,7 @@ public sealed class PlotRenderer for (int sx = 0; sx < subW; sx++) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); - double y = fn.Evaluator.Evaluate(x, paramLookup); + double y = fn.Evaluator.Evaluate(x, paramLookup, userFuncLookup); if (double.IsNaN(y) || double.IsInfinity(y)) { @@ -286,7 +289,7 @@ public sealed class PlotRenderer for (int sx = 0; sx < subW; sx += 2) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); - double dy = Calculus.Derivative(t => fn.Evaluator.Evaluate(t, paramLookup), x); + double dy = Calculus.Derivative(t => fn.Evaluator.Evaluate(t, paramLookup, userFuncLookup), x); if (double.IsNaN(dy) || double.IsInfinity(dy)) { @@ -312,7 +315,7 @@ public sealed class PlotRenderer // Tangent Line overlay if (fn.ShowTangent) { - var (slope, y0, lineFunc) = Calculus.TangentLine(t => fn.Evaluator.Evaluate(t, paramLookup), crosshairX); + var (slope, y0, lineFunc) = Calculus.TangentLine(t => fn.Evaluator.Evaluate(t, paramLookup, userFuncLookup), crosshairX); if (!double.IsNaN(slope) && !double.IsInfinity(slope)) { viewport.SubpixelToMath(0, 0, subW, subH, out double xLeft, out _); @@ -333,7 +336,8 @@ public sealed class PlotRenderer BrailleCanvas canvas, Viewport viewport, GraphFunction fn, - Func? paramLookup) + Func? paramLookup, + UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null) return; @@ -347,7 +351,7 @@ public sealed class PlotRenderer for (int sy = 0; sy < subH; sy++) { viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); - double x = fn.Evaluator.EvaluateY(y, paramLookup); + double x = fn.Evaluator.EvaluateY(y, paramLookup, userFuncLookup); if (double.IsNaN(x) || double.IsInfinity(x)) { @@ -389,7 +393,8 @@ public sealed class PlotRenderer BrailleCanvas canvas, Viewport viewport, GraphFunction fn, - Func? paramLookup) + Func? paramLookup, + UserFunctionEvaluator? userFuncLookup) { if (fn.EvaluatorLhs == null || fn.EvaluatorRhs == null) return; @@ -414,14 +419,14 @@ public sealed class PlotRenderer for (int sy = 0; sy <= subH; sy++) { viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); - precomputedLhsY[sy] = fn.EvaluatorLhs.EvaluateY(y, paramLookup); + precomputedLhsY[sy] = fn.EvaluatorLhs.EvaluateY(y, paramLookup, userFuncLookup); } precomputedRhsX = new double[subW + 1]; for (int sx = 0; sx <= subW; sx++) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); - precomputedRhsX[sx] = fn.EvaluatorRhs.Evaluate(x, paramLookup); + precomputedRhsX[sx] = fn.EvaluatorRhs.Evaluate(x, paramLookup, userFuncLookup); } } else if (lhsOnlyX && rhsOnlyY) @@ -430,14 +435,14 @@ public sealed class PlotRenderer for (int sx = 0; sx <= subW; sx++) { viewport.SubpixelToMath(sx, 0, subW, subH, out double x, out _); - precomputedLhsX[sx] = fn.EvaluatorLhs.Evaluate(x, paramLookup); + precomputedLhsX[sx] = fn.EvaluatorLhs.Evaluate(x, paramLookup, userFuncLookup); } precomputedRhsY = new double[subH + 1]; for (int sy = 0; sy <= subH; sy++) { viewport.SubpixelToMath(0, sy, subW, subH, out _, out double y); - precomputedRhsY[sy] = fn.EvaluatorRhs.EvaluateY(y, paramLookup); + precomputedRhsY[sy] = fn.EvaluatorRhs.EvaluateY(y, paramLookup, userFuncLookup); } } @@ -457,8 +462,8 @@ public sealed class PlotRenderer } viewport.SubpixelToMath(sx, sy, subW, subH, out double xVal, out double yVal); - double lhs = fn.EvaluatorLhs.Evaluate(xVal, yVal, paramLookup); - double rhs = fn.EvaluatorRhs.Evaluate(xVal, yVal, paramLookup); + double lhs = fn.EvaluatorLhs.Evaluate(xVal, yVal, paramLookup, userFuncLookup); + double rhs = fn.EvaluatorRhs.Evaluate(xVal, yVal, paramLookup, userFuncLookup); return lhs - rhs; } @@ -550,7 +555,8 @@ public sealed class PlotRenderer BrailleCanvas canvas, Viewport viewport, GraphFunction fn, - Func? paramLookup) + Func? paramLookup, + UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null || fn.EvaluatorY == null) return; @@ -566,8 +572,8 @@ public sealed class PlotRenderer for (int i = 0; i <= steps; i++) { double t = fn.TMin + i * dt; - double x = fn.Evaluator.EvaluateParametricX(t, paramLookup); - double y = fn.EvaluatorY.EvaluateParametricY(t, paramLookup); + double x = fn.Evaluator.EvaluateParametricX(t, paramLookup, userFuncLookup); + double y = fn.EvaluatorY.EvaluateParametricY(t, paramLookup, userFuncLookup); if (double.IsNaN(x) || double.IsNaN(y) || double.IsInfinity(x) || double.IsInfinity(y)) { @@ -599,7 +605,8 @@ public sealed class PlotRenderer BrailleCanvas canvas, Viewport viewport, GraphFunction fn, - Func? paramLookup) + Func? paramLookup, + UserFunctionEvaluator? userFuncLookup) { if (fn.Evaluator == null) return; @@ -615,7 +622,7 @@ public sealed class PlotRenderer for (int i = 0; i <= steps; i++) { double theta = fn.ThetaMin + i * dTheta; - double r = fn.Evaluator.EvaluatePolar(theta, paramLookup); + double r = fn.Evaluator.EvaluatePolar(theta, paramLookup, userFuncLookup); if (double.IsNaN(r) || double.IsInfinity(r)) { diff --git a/src/GraphTUI/Rendering/SvgExporter.cs b/src/GraphTUI/Rendering/SvgExporter.cs index 34e63a2..9b8fa4b 100644 --- a/src/GraphTUI/Rendering/SvgExporter.cs +++ b/src/GraphTUI/Rendering/SvgExporter.cs @@ -1,5 +1,6 @@ using System.Globalization; using System.Text; +using GraphTUI.Core.Math; using GraphTUI.Core.Models; namespace GraphTUI.Rendering; @@ -11,7 +12,8 @@ public static class SvgExporter IReadOnlyList functions, Func? paramLookup, int width = 800, - int height = 500) + int height = 500, + UserFunctionEvaluator? userFuncLookup = null) { var sb = new StringBuilder(); sb.AppendLine($""); @@ -39,7 +41,7 @@ public static class SvgExporter // Curves foreach (var fn in functions) { - if (!fn.IsVisible || fn.CompilationError != null) + if (!fn.IsVisible || !fn.IsGraphable || fn.CompilationError != null) continue; string strokeColor = $"rgb({fn.Color.R},{fn.Color.G},{fn.Color.B})"; @@ -48,23 +50,31 @@ public static class SvgExporter { sb.AppendLine(CultureInfo.InvariantCulture, $" height / 2.0); + + if (isFirst || isAsymptote) { sb.Append(CultureInfo.InvariantCulture, $" M {sx:F1} {sy:F1}"); isFirst = false; @@ -73,6 +83,9 @@ public static class SvgExporter { sb.Append(CultureInfo.InvariantCulture, $" L {sx:F1} {sy:F1}"); } + + lastY = y; + lastSy = sy; } sb.AppendLine("\" />"); } @@ -85,7 +98,7 @@ public static class SvgExporter for (int i = 0; i < samples; i++) { double y = viewport.YMin + ((double)i / (samples - 1)) * viewport.Height; - double x = fn.Evaluator.EvaluateY(y, paramLookup); + double x = fn.Evaluator.EvaluateY(y, paramLookup, userFuncLookup); if (double.IsNaN(x) || double.IsInfinity(x)) { @@ -118,7 +131,7 @@ public static class SvgExporter { double xVal = viewport.XMin + ((double)gx / gridW) * viewport.Width; double yVal = viewport.YMax - ((double)gy / gridH) * viewport.Height; - return fn.EvaluatorLhs.Evaluate(xVal, yVal, paramLookup) - fn.EvaluatorRhs.Evaluate(xVal, yVal, paramLookup); + return fn.EvaluatorLhs.Evaluate(xVal, yVal, paramLookup, userFuncLookup) - fn.EvaluatorRhs.Evaluate(xVal, yVal, paramLookup, userFuncLookup); } double[] prevRow = new double[gridW + 1]; @@ -183,8 +196,8 @@ public static class SvgExporter for (int i = 0; i <= steps; i++) { double t = fn.TMin + i * dt; - double x = fn.Evaluator.EvaluateParametricX(t, paramLookup); - double y = fn.EvaluatorY.EvaluateParametricY(t, paramLookup); + double x = fn.Evaluator.EvaluateParametricX(t, paramLookup, userFuncLookup); + double y = fn.EvaluatorY.EvaluateParametricY(t, paramLookup, userFuncLookup); if (double.IsNaN(x) || double.IsNaN(y) || double.IsInfinity(x) || double.IsInfinity(y)) { @@ -215,7 +228,7 @@ public static class SvgExporter for (int i = 0; i <= steps; i++) { double theta = fn.ThetaMin + i * dTheta; - double r = fn.Evaluator.EvaluatePolar(theta, paramLookup); + double r = fn.Evaluator.EvaluatePolar(theta, paramLookup, userFuncLookup); if (double.IsNaN(r) || double.IsInfinity(r)) { diff --git a/src/GraphTUI/Terminal/AnsiCodes.cs b/src/GraphTUI/Terminal/AnsiCodes.cs index a42ef4b..219626f 100644 --- a/src/GraphTUI/Terminal/AnsiCodes.cs +++ b/src/GraphTUI/Terminal/AnsiCodes.cs @@ -20,5 +20,9 @@ public static class AnsiCodes public const string EnableMouse = "\x1b[?1000h\x1b[?1002h\x1b[?1006h"; public const string DisableMouse = "\x1b[?1006l\x1b[?1002l\x1b[?1000l"; + // Disable/Enable Line Auto-Wrap (prevents bottom-right cell scroll jitter) + public const string DisableAutoWrap = "\x1b[?7l"; + public const string EnableAutoWrap = "\x1b[?7h"; + public static string CursorPosition(int row, int col) => $"\x1b[{row + 1};{col + 1}H"; } diff --git a/src/GraphTUI/UI/Views/CalculusModal.cs b/src/GraphTUI/UI/Views/CalculusModal.cs index 85092d0..f442219 100644 --- a/src/GraphTUI/UI/Views/CalculusModal.cs +++ b/src/GraphTUI/UI/Views/CalculusModal.cs @@ -42,16 +42,91 @@ public sealed class CalculusModal _cachedIntegral = Calculus.DefiniteIntegral(f, _analyzedFunction.IntegralA, _analyzedFunction.IntegralB, 150); } + public int SelectedControlIndex { get; set; } = 0; // 0: Tangent, 1: Derivative, 2: Integral, 3: Bound A, 4: Bound B + + private int _tangentRow = -1; + private int _derivRow = -1; + private int _integralRow = -1; + private int _boundARow = -1; + private int _boundBRow = -1; + public void HandleKey(KeyAction key, Viewport viewport, Func? paramLookup, Action onStateChanged) { if (!IsOpen) return; switch (key.Code) { - case KeyCode.Escape or KeyCode.Char when key.KeyChar is 'q' or 'Q': + case KeyCode.Escape: + case KeyCode.F3: + case KeyCode.Char when key.KeyChar is 'q' or 'Q' or 'c' or 'C': IsOpen = false; break; + case KeyCode.Up: + case KeyCode.Char when key.KeyChar == 'k': + SelectedControlIndex = (SelectedControlIndex + 4) % 5; + break; + + case KeyCode.Down: + case KeyCode.Char when key.KeyChar == 'j': + SelectedControlIndex = (SelectedControlIndex + 1) % 5; + break; + + case KeyCode.Tab: + SelectedControlIndex = key.Shift ? (SelectedControlIndex + 4) % 5 : (SelectedControlIndex + 1) % 5; + break; + + case KeyCode.Enter when _analyzedFunction != null: + case KeyCode.Char when key.KeyChar == ' ' && _analyzedFunction != null: + switch (SelectedControlIndex) + { + case 0: + _analyzedFunction.ShowTangent = !_analyzedFunction.ShowTangent; + onStateChanged(); + break; + case 1: + _analyzedFunction.ShowDerivative = !_analyzedFunction.ShowDerivative; + onStateChanged(); + break; + case 2: + _analyzedFunction.ShowIntegral = !_analyzedFunction.ShowIntegral; + onStateChanged(); + break; + } + break; + + case KeyCode.Left when _analyzedFunction != null: + case KeyCode.Char when key.KeyChar == 'h' && _analyzedFunction != null: + if (SelectedControlIndex == 3) + { + _analyzedFunction.IntegralA = System.Math.Round(_analyzedFunction.IntegralA - 0.5, 2); + RefreshAnalysis(viewport, paramLookup); + onStateChanged(); + } + else if (SelectedControlIndex == 4) + { + _analyzedFunction.IntegralB = System.Math.Round(_analyzedFunction.IntegralB - 0.5, 2); + RefreshAnalysis(viewport, paramLookup); + onStateChanged(); + } + break; + + case KeyCode.Right when _analyzedFunction != null: + case KeyCode.Char when key.KeyChar == 'l' && _analyzedFunction != null: + if (SelectedControlIndex == 3) + { + _analyzedFunction.IntegralA = System.Math.Round(_analyzedFunction.IntegralA + 0.5, 2); + RefreshAnalysis(viewport, paramLookup); + onStateChanged(); + } + else if (SelectedControlIndex == 4) + { + _analyzedFunction.IntegralB = System.Math.Round(_analyzedFunction.IntegralB + 0.5, 2); + RefreshAnalysis(viewport, paramLookup); + onStateChanged(); + } + break; + case KeyCode.Char when _analyzedFunction != null: switch (key.KeyChar) { @@ -107,29 +182,52 @@ public sealed class CalculusModal return true; } + // Close button click at top right + if (mouse.Row == row && mouse.Col >= col + modalW - 5) + { + IsOpen = false; + return true; + } + if (_analyzedFunction != null) { - // Click on Toggle Tangent - if (mouse.Row == row + modalH - 5) + if (mouse.Row == _tangentRow) { + SelectedControlIndex = 0; _analyzedFunction.ShowTangent = !_analyzedFunction.ShowTangent; onStateChanged(); return true; } - // Click on Toggle Derivative - if (mouse.Row == row + modalH - 4) + if (mouse.Row == _derivRow) { + SelectedControlIndex = 1; _analyzedFunction.ShowDerivative = !_analyzedFunction.ShowDerivative; onStateChanged(); return true; } - // Click on Toggle Integral - if (mouse.Row == row + modalH - 3) + if (mouse.Row == _integralRow) { + SelectedControlIndex = 2; _analyzedFunction.ShowIntegral = !_analyzedFunction.ShowIntegral; onStateChanged(); return true; } + if (mouse.Row == _boundARow) + { + SelectedControlIndex = 3; + _analyzedFunction.IntegralA = System.Math.Round(_analyzedFunction.IntegralA + 0.5, 2); + RefreshAnalysis(viewport, paramLookup); + onStateChanged(); + return true; + } + if (mouse.Row == _boundBRow) + { + SelectedControlIndex = 4; + _analyzedFunction.IntegralB = System.Math.Round(_analyzedFunction.IntegralB + 0.5, 2); + RefreshAnalysis(viewport, paramLookup); + onStateChanged(); + return true; + } } return false; @@ -145,6 +243,7 @@ public sealed class CalculusModal int row = (screenHeight - modalH) / 2; screen.DrawBox(col, row, modalW, modalH, ColorRgb.Magenta, ColorRgb.SidebarBg, "Calculus & Analytical Tools (Esc: Close)"); + screen.DrawText(col + modalW - 5, row, "[X]", ColorRgb.Red, ColorRgb.SidebarBg); if (_analyzedFunction == null || _analyzedFunction.Type != FunctionType.Cartesian) { @@ -174,22 +273,50 @@ public sealed class CalculusModal screen.DrawText(col + 5, currRow++, extremaStr, ColorRgb.White, ColorRgb.SidebarBg, modalW - 8); currRow++; - // 3. Tangent Line at Cursor + // 3. Tangent Line at Cursor (Control 0) + _tangentRow = currRow++; + bool isTanSel = SelectedControlIndex == 0; + ColorRgb tanRowBg = isTanSel ? new ColorRgb(40, 50, 70) : ColorRgb.SidebarBg; + string tanCursor = isTanSel ? "▶ " : "• "; string tangentStatus = _analyzedFunction.ShowTangent ? "[ON]" : "[OFF]"; ColorRgb tangentCol = _analyzedFunction.ShowTangent ? ColorRgb.Green : ColorRgb.DarkGray; - screen.DrawText(col + 3, currRow++, $"• Tangent Line at x={crosshairX:F2} (Key 't'): {tangentStatus}", tangentCol, ColorRgb.SidebarBg); + screen.DrawText(col + 1, _tangentRow, new string(' ', modalW - 2), ColorRgb.White, tanRowBg); + screen.DrawText(col + 3, _tangentRow, $"{tanCursor}Tangent Line at x={crosshairX:F2} (Key 't'/Enter): {tangentStatus}", isTanSel ? ColorRgb.Yellow : tangentCol, tanRowBg); - // 4. Derivative Curve + // 4. Derivative Curve (Control 1) + _derivRow = currRow++; + bool isDerivSel = SelectedControlIndex == 1; + ColorRgb derivRowBg = isDerivSel ? new ColorRgb(40, 50, 70) : ColorRgb.SidebarBg; + string derivCursor = isDerivSel ? "▶ " : "• "; string derivStatus = _analyzedFunction.ShowDerivative ? "[ON]" : "[OFF]"; ColorRgb derivCol = _analyzedFunction.ShowDerivative ? ColorRgb.Green : ColorRgb.DarkGray; - screen.DrawText(col + 3, currRow++, $"• Derivative Curve f'(x) (Key 'd'): {derivStatus}", derivCol, ColorRgb.SidebarBg); + screen.DrawText(col + 1, _derivRow, new string(' ', modalW - 2), ColorRgb.White, derivRowBg); + screen.DrawText(col + 3, _derivRow, $"{derivCursor}Derivative Curve f'(x) (Key 'd'/Enter): {derivStatus}", isDerivSel ? ColorRgb.Yellow : derivCol, derivRowBg); - // 5. Definite Integral + // 5. Definite Integral Shading (Control 2) + _integralRow = currRow++; + bool isIntSel = SelectedControlIndex == 2; + ColorRgb intRowBg = isIntSel ? new ColorRgb(40, 50, 70) : ColorRgb.SidebarBg; + string intCursor = isIntSel ? "▶ " : "• "; string intStatus = _analyzedFunction.ShowIntegral ? "[ON]" : "[OFF]"; ColorRgb intCol = _analyzedFunction.ShowIntegral ? ColorRgb.Green : ColorRgb.DarkGray; string intVal = double.IsNaN(_cachedIntegral) ? "N/A" : _cachedIntegral.ToString("F4"); + screen.DrawText(col + 1, _integralRow, new string(' ', modalW - 2), ColorRgb.White, intRowBg); + screen.DrawText(col + 3, _integralRow, $"{intCursor}Definite Integral [a={_analyzedFunction.IntegralA:F1}, b={_analyzedFunction.IntegralB:F1}] = {intVal} (Key 'i'/Enter): {intStatus}", isIntSel ? ColorRgb.Yellow : ColorRgb.Cyan, intRowBg); - screen.DrawText(col + 3, currRow++, $"• Definite Integral [a={_analyzedFunction.IntegralA:F1}, b={_analyzedFunction.IntegralB:F1}] = {intVal}", ColorRgb.Cyan, ColorRgb.SidebarBg); - screen.DrawText(col + 5, currRow++, $"Shading (Key 'i'): {intStatus} | Bounds: '['/']' adjust 'a', '{'/'}' adjust 'b'", intCol, ColorRgb.SidebarBg); + // 6. Bound A (Control 3) & Bound B (Control 4) + _boundARow = currRow++; + bool isBoundASel = SelectedControlIndex == 3; + ColorRgb bARowBg = isBoundASel ? new ColorRgb(40, 50, 70) : ColorRgb.SidebarBg; + string bACursor = isBoundASel ? "▶ " : " "; + screen.DrawText(col + 1, _boundARow, new string(' ', modalW - 2), ColorRgb.White, bARowBg); + screen.DrawText(col + 5, _boundARow, $"{bACursor}Bound a = {_analyzedFunction.IntegralA:F2} (Left/Right or '['/']' to adjust)", isBoundASel ? ColorRgb.Yellow : ColorRgb.White, bARowBg); + + _boundBRow = currRow++; + bool isBoundBSel = SelectedControlIndex == 4; + ColorRgb bBRowBg = isBoundBSel ? new ColorRgb(40, 50, 70) : ColorRgb.SidebarBg; + string bBCursor = isBoundBSel ? "▶ " : " "; + screen.DrawText(col + 1, _boundBRow, new string(' ', modalW - 2), ColorRgb.White, bBRowBg); + screen.DrawText(col + 5, _boundBRow, $"{bBCursor}Bound b = {_analyzedFunction.IntegralB:F2} (Left/Right or '{'/'}' to adjust)", isBoundBSel ? ColorRgb.Yellow : ColorRgb.White, bBRowBg); } } diff --git a/src/GraphTUI/UI/Views/CheatsheetModal.cs b/src/GraphTUI/UI/Views/CheatsheetModal.cs index b76e1a8..29757cd 100644 --- a/src/GraphTUI/UI/Views/CheatsheetModal.cs +++ b/src/GraphTUI/UI/Views/CheatsheetModal.cs @@ -91,11 +91,14 @@ public sealed class CheatsheetModal switch (key.Code) { - case KeyCode.Escape or KeyCode.F5: + case KeyCode.Escape: + case KeyCode.F5: + case KeyCode.Char when key.KeyChar is 'q' or 'Q': IsOpen = false; break; - case KeyCode.Left or KeyCode.Char when key.KeyChar == 'h': + case KeyCode.Left: + case KeyCode.Char when key.KeyChar == 'h': if (SelectedCategory > 0) { SelectedCategory--; @@ -103,7 +106,8 @@ public sealed class CheatsheetModal } break; - case KeyCode.Right or KeyCode.Char when key.KeyChar == 'l': + case KeyCode.Right: + case KeyCode.Char when key.KeyChar == 'l': if (SelectedCategory < Categories.Length - 1) { SelectedCategory++; @@ -111,17 +115,21 @@ public sealed class CheatsheetModal } break; - case KeyCode.Up or KeyCode.Char when key.KeyChar == 'k': + case KeyCode.Up: + case KeyCode.Char when key.KeyChar == 'k': if (ScrollOffset > 0) ScrollOffset--; break; - case KeyCode.Down or KeyCode.Char when key.KeyChar == 'j': + case KeyCode.Down: + case KeyCode.Char when key.KeyChar == 'j': var cat = Categories[SelectedCategory]; if (ScrollOffset < cat.Entries.Length - 1) ScrollOffset++; break; case KeyCode.Tab: - SelectedCategory = (SelectedCategory + 1) % Categories.Length; + SelectedCategory = key.Shift + ? (SelectedCategory + Categories.Length - 1) % Categories.Length + : (SelectedCategory + 1) % Categories.Length; ScrollOffset = 0; break; @@ -147,7 +155,7 @@ public sealed class CheatsheetModal public bool HandleMouse(MouseEvent mouse, int screenWidth, int screenHeight, Action? onInsertExample = null) { - if (!IsOpen || mouse.Type != MouseEventType.Down) return false; + if (!IsOpen) return false; int modalW = System.Math.Min(82, screenWidth - 4); int modalH = System.Math.Min(26, screenHeight - 2); @@ -155,6 +163,33 @@ public sealed class CheatsheetModal int row = (screenHeight - modalH) / 2; if (mouse.Col < col || mouse.Col >= col + modalW || mouse.Row < row || mouse.Row >= row + modalH) + { + if (mouse.Type == MouseEventType.Down) + { + IsOpen = false; + return true; + } + return false; + } + + var cat = Categories[SelectedCategory]; + + // Mouse wheel scrolling + if (mouse.Type == MouseEventType.ScrollUp) + { + if (ScrollOffset > 0) ScrollOffset--; + return true; + } + if (mouse.Type == MouseEventType.ScrollDown) + { + if (ScrollOffset < cat.Entries.Length - 1) ScrollOffset++; + return true; + } + + if (mouse.Type != MouseEventType.Down) return false; + + // Close button click at top right + if (mouse.Row == row && mouse.Col >= col + modalW - 5) { IsOpen = false; return true; @@ -177,17 +212,20 @@ public sealed class CheatsheetModal } } - // Check if an entry was clicked to load - var cat = Categories[SelectedCategory]; - int listStartRow = row + 4; - for (int i = 0; i < cat.Entries.Length; i++) + // Check if an entry was clicked to load (starts at row + 3) + int listStartRow = row + 3; + int maxItems = (modalH - 5) / 2; + int firstVisible = System.Math.Max(0, System.Math.Min(ScrollOffset - maxItems + 1, cat.Entries.Length - maxItems)); + + for (int i = 0; i < maxItems && (firstVisible + i) < cat.Entries.Length; i++) { int entryRow = listStartRow + i * 2; if (mouse.Row == entryRow || mouse.Row == entryRow + 1) { - ScrollOffset = i; + int itemIdx = firstVisible + i; + ScrollOffset = itemIdx; IsOpen = false; - onInsertExample?.Invoke(cat.Entries[i].Example); + onInsertExample?.Invoke(cat.Entries[itemIdx].Example); return true; } } @@ -205,6 +243,7 @@ public sealed class CheatsheetModal int row = (screenHeight - modalH) / 2; screen.DrawBox(col, row, modalW, modalH, ColorRgb.Accent, ColorRgb.SidebarBg, "Math Engine Cheatsheet (Tab/1-5: Categories, Enter: Load, Esc: Close)"); + screen.DrawText(col + modalW - 5, row, "[X]", ColorRgb.Red, ColorRgb.SidebarBg); // 1. Category Tabs Bar int tabCol = col + 2; @@ -225,16 +264,18 @@ public sealed class CheatsheetModal screen.SetCell(c, row + 2, '─', ColorRgb.GridLine, ColorRgb.SidebarBg); } - // 2. Entries in Selected Category + // 2. Entries in Selected Category with window scrolling var cat = Categories[SelectedCategory]; int listStartRow = row + 3; int maxItems = (modalH - 5) / 2; + int firstVisible = System.Math.Max(0, System.Math.Min(ScrollOffset - maxItems + 1, cat.Entries.Length - maxItems)); - for (int i = 0; i < cat.Entries.Length && i < maxItems; i++) + for (int i = 0; i < maxItems && (firstVisible + i) < cat.Entries.Length; i++) { - var entry = cat.Entries[i]; + int entryIdx = firstVisible + i; + var entry = cat.Entries[entryIdx]; int entryRow = listStartRow + i * 2; - bool isSelected = i == ScrollOffset; + bool isSelected = entryIdx == ScrollOffset; ColorRgb rowBg = isSelected ? new ColorRgb(35, 45, 65) : ColorRgb.SidebarBg; diff --git a/src/GraphTUI/UI/Views/FunctionListView.cs b/src/GraphTUI/UI/Views/FunctionListView.cs index 12363d3..de69f9e 100644 --- a/src/GraphTUI/UI/Views/FunctionListView.cs +++ b/src/GraphTUI/UI/Views/FunctionListView.cs @@ -82,6 +82,8 @@ public sealed class FunctionListView } } + public int ScrollOffset { get; set; } = 0; + public bool HandleMouse( MouseEvent mouse, int col, int row, int width, int height, @@ -90,23 +92,51 @@ public sealed class FunctionListView Action onAddNew, Action onStateChanged) { - if (mouse.Type != MouseEventType.Down) return false; if (mouse.Col < col || mouse.Col >= col + width || mouse.Row < row || mouse.Row >= row + height) return false; + // Mouse wheel scrolling + if (mouse.Type == MouseEventType.ScrollUp) + { + if (SelectedIndex > 0) + { + SelectedIndex--; + onStateChanged(); + return true; + } + } + else if (mouse.Type == MouseEventType.ScrollDown) + { + if (SelectedIndex < functions.Count - 1) + { + SelectedIndex++; + onStateChanged(); + return true; + } + } + + if (mouse.Type != MouseEventType.Down) return false; + // Check if clicked the [+ Add] button on header - if (mouse.Row == row && mouse.Col >= col + width - 8) + if (mouse.Row == row && mouse.Col >= col + width - 10) { onAddNew(); return true; } - int itemRow = mouse.Row - (row + 1); + int itemRow = mouse.Row - (row + 1) + ScrollOffset; if (itemRow >= 0 && itemRow < functions.Count) { SelectedIndex = itemRow; var fn = functions[SelectedIndex]; + if (fn.IsDefinition) + { + // Clicking definition opens edit + onEdit(fn); + return true; + } + // Clicked checkbox: col + 1 to col + 3 "[x]" if (mouse.Col >= col + 1 && mouse.Col <= col + 3) { @@ -171,11 +201,16 @@ public sealed class FunctionListView SelectedIndex = System.Math.Clamp(SelectedIndex, 0, functions.Count - 1); int maxItems = height - 2; - for (int i = 0; i < functions.Count && i < maxItems; i++) + if (SelectedIndex < ScrollOffset) ScrollOffset = SelectedIndex; + if (SelectedIndex >= ScrollOffset + maxItems) ScrollOffset = SelectedIndex - maxItems + 1; + ScrollOffset = System.Math.Max(0, System.Math.Min(ScrollOffset, System.Math.Max(0, functions.Count - maxItems))); + + for (int i = 0; i < maxItems && (ScrollOffset + i) < functions.Count; i++) { - var fn = functions[i]; + int fnIdx = ScrollOffset + i; + var fn = functions[fnIdx]; int r = row + 1 + i; - bool isSelected = i == SelectedIndex && isFocused; + bool isSelected = fnIdx == SelectedIndex && isFocused; ColorRgb itemBg = isSelected ? new ColorRgb(35, 45, 60) : ColorRgb.SidebarBg; @@ -186,31 +221,45 @@ public sealed class FunctionListView char cursor = isSelected ? '▶' : ' '; screen.SetCell(col + 1, r, cursor, ColorRgb.Accent, itemBg); - // Visibility checkbox: [x] or [ ] - string check = fn.IsVisible ? "[x]" : "[ ]"; - ColorRgb checkColor = fn.IsVisible ? ColorRgb.Green : ColorRgb.DarkGray; - screen.DrawText(col + 2, r, check, checkColor, itemBg); - - // Color indicator bullet: ● - screen.SetCell(col + 6, r, '●', fn.Color, itemBg); - - // Formula or error message - string label; - ColorRgb formulaColor; - - if (fn.CompilationError != null) + if (fn.IsDefinition) { - label = $"! {fn.Expression} (Err)"; - formulaColor = ColorRgb.Red; + // Function definition badge: [def] + screen.DrawText(col + 2, r, "[def]", ColorRgb.Cyan, itemBg); + screen.SetCell(col + 7, r, 'λ', ColorRgb.Yellow, itemBg); + + string label = fn.GetDisplayFormula(); + ColorRgb formulaColor = isSelected ? ColorRgb.White : ColorRgb.Cyan; + int textMaxWidth = width - 10; + screen.DrawText(col + 9, r, label, formulaColor, itemBg, textMaxWidth); } else { - label = fn.GetDisplayFormula(); - formulaColor = isSelected ? ColorRgb.White : ColorRgb.Gray; - } + // Visibility checkbox: [x] or [ ] + string check = fn.IsVisible ? "[x]" : "[ ]"; + ColorRgb checkColor = fn.IsVisible ? ColorRgb.Green : ColorRgb.DarkGray; + screen.DrawText(col + 2, r, check, checkColor, itemBg); - int textMaxWidth = width - 9; - screen.DrawText(col + 8, r, label, formulaColor, itemBg, textMaxWidth); + // Color indicator bullet: ● + screen.SetCell(col + 6, r, '●', fn.Color, itemBg); + + // Formula or error message + string label; + ColorRgb formulaColor; + + if (fn.CompilationError != null) + { + label = $"! {fn.Expression} (Err)"; + formulaColor = ColorRgb.Red; + } + else + { + label = fn.GetDisplayFormula(); + formulaColor = isSelected ? ColorRgb.White : ColorRgb.Gray; + } + + int textMaxWidth = width - 9; + screen.DrawText(col + 8, r, label, formulaColor, itemBg, textMaxWidth); + } } } } diff --git a/src/GraphTUI/UI/Views/HelpModal.cs b/src/GraphTUI/UI/Views/HelpModal.cs index fad84e7..dde561d 100644 --- a/src/GraphTUI/UI/Views/HelpModal.cs +++ b/src/GraphTUI/UI/Views/HelpModal.cs @@ -10,7 +10,8 @@ public sealed class HelpModal public void HandleKey(KeyAction key) { if (!IsOpen) return; - if (key.Code is KeyCode.Escape or KeyCode.Enter || (key.Code == KeyCode.Char && key.KeyChar is 'q' or '?' or 'h')) + if (key.Code is KeyCode.Escape or KeyCode.Enter or KeyCode.F1 || + (key.Code == KeyCode.Char && key.KeyChar is 'q' or 'Q' or '?' or 'h' or 'H' or ' ')) { IsOpen = false; } @@ -34,6 +35,7 @@ public sealed class HelpModal int row = (screenHeight - modalH) / 2; screen.DrawBox(col, row, modalW, modalH, ColorRgb.Accent, ColorRgb.SidebarBg, "GraphTUI Quick Reference & Help (Esc/q to close)"); + screen.DrawText(col + modalW - 5, row, "[X]", ColorRgb.Red, ColorRgb.SidebarBg); int r = row + 1; void Row(string left, string right, ColorRgb col1, ColorRgb col2) diff --git a/src/GraphTUI/UI/Views/ParameterSlidersView.cs b/src/GraphTUI/UI/Views/ParameterSlidersView.cs index 2ff1128..2caf196 100644 --- a/src/GraphTUI/UI/Views/ParameterSlidersView.cs +++ b/src/GraphTUI/UI/Views/ParameterSlidersView.cs @@ -8,12 +8,23 @@ public sealed class ParameterSlidersView { public int SelectedIndex { get; set; } = 0; + public int ScrollOffset { get; set; } = 0; + public void HandleKey( KeyAction key, List parameters, - Action onStateChanged) + Action onStateChanged, + Action? onAddNew = null, + Action? onEdit = null) { - if (parameters.Count == 0) return; + if (parameters.Count == 0) + { + if (key.Code == KeyCode.Char && (key.KeyChar is 'a' or 'A' or '+')) + { + onAddNew?.Invoke(); + } + return; + } SelectedIndex = System.Math.Clamp(SelectedIndex, 0, parameters.Count - 1); var param = parameters[SelectedIndex]; @@ -38,6 +49,17 @@ public sealed class ParameterSlidersView onStateChanged(); break; + case KeyCode.Enter: + onEdit?.Invoke(param); + break; + + case KeyCode.Delete: + parameters.RemoveAt(SelectedIndex); + if (SelectedIndex >= parameters.Count && SelectedIndex > 0) + SelectedIndex--; + onStateChanged(); + break; + case KeyCode.Char: switch (key.KeyChar) { @@ -55,6 +77,18 @@ public sealed class ParameterSlidersView param.Increment(key.Shift ? 5.0 : 1.0); onStateChanged(); break; + case 'a' or 'A' or '+': + onAddNew?.Invoke(); + break; + case 'e' or 'E': + onEdit?.Invoke(param); + break; + case 'd' or 'D': + parameters.RemoveAt(SelectedIndex); + if (SelectedIndex >= parameters.Count && SelectedIndex > 0) + SelectedIndex--; + onStateChanged(); + break; case '0': param.Value = 0.0; onStateChanged(); @@ -72,18 +106,55 @@ public sealed class ParameterSlidersView MouseEvent mouse, int col, int row, int width, int height, List parameters, - Action onStateChanged) + Action onStateChanged, + Action? onAddNew = null, + Action? onEdit = null) { - if (mouse.Type != MouseEventType.Down && mouse.Type != MouseEventType.Drag) return false; if (mouse.Col < col || mouse.Col >= col + width || mouse.Row < row || mouse.Row >= row + height) return false; - int itemRow = mouse.Row - (row + 1); + // Mouse wheel scrolling + if (mouse.Type == MouseEventType.ScrollUp) + { + if (SelectedIndex > 0) + { + SelectedIndex--; + onStateChanged(); + return true; + } + } + else if (mouse.Type == MouseEventType.ScrollDown) + { + if (SelectedIndex < parameters.Count - 1) + { + SelectedIndex++; + onStateChanged(); + return true; + } + } + + // Check header [+ Add] button click + if (mouse.Type == MouseEventType.Down && mouse.Row == row && mouse.Col >= col + width - 10) + { + onAddNew?.Invoke(); + return true; + } + + if (mouse.Type != MouseEventType.Down && mouse.Type != MouseEventType.Drag) return false; + + int itemRow = mouse.Row - (row + 1) + ScrollOffset; if (itemRow >= 0 && itemRow < parameters.Count) { SelectedIndex = itemRow; var param = parameters[SelectedIndex]; + // Clicked parameter name to edit + if (mouse.Type == MouseEventType.Down && mouse.Col >= col + 2 && mouse.Col <= col + 5) + { + onEdit?.Invoke(param); + return true; + } + // Determine track start and end int trackStart = col + 6; int trackWidth = width - 15; @@ -110,20 +181,33 @@ public sealed class ParameterSlidersView ColorRgb borderColor = isFocused ? ColorRgb.Accent : ColorRgb.GridLine; screen.DrawBox(col, row, width, height, borderColor, ColorRgb.SidebarBg, "Parameters"); + // Add button indicator on box border + string addBtn = "[+ Add (a)]"; + if (width > 20) + { + screen.DrawText(col + width - addBtn.Length - 2, row, addBtn, ColorRgb.Green, ColorRgb.SidebarBg); + } + if (parameters.Count == 0) { screen.DrawText(col + 2, row + 2, "No parameters.", ColorRgb.DarkGray, ColorRgb.SidebarBg); + screen.DrawText(col + 2, row + 3, "Press 'a' to add one.", ColorRgb.DarkGray, ColorRgb.SidebarBg); return; } SelectedIndex = System.Math.Clamp(SelectedIndex, 0, parameters.Count - 1); int maxItems = height - 2; - for (int i = 0; i < parameters.Count && i < maxItems; i++) + if (SelectedIndex < ScrollOffset) ScrollOffset = SelectedIndex; + if (SelectedIndex >= ScrollOffset + maxItems) ScrollOffset = SelectedIndex - maxItems + 1; + ScrollOffset = System.Math.Max(0, System.Math.Min(ScrollOffset, System.Math.Max(0, parameters.Count - maxItems))); + + for (int i = 0; i < maxItems && (ScrollOffset + i) < parameters.Count; i++) { - var p = parameters[i]; + int pIdx = ScrollOffset + i; + var p = parameters[pIdx]; int r = row + 1 + i; - bool isSelected = i == SelectedIndex && isFocused; + bool isSelected = pIdx == SelectedIndex && isFocused; ColorRgb itemBg = isSelected ? new ColorRgb(35, 45, 60) : ColorRgb.SidebarBg; screen.DrawText(col + 1, r, new string(' ', width - 2), ColorRgb.White, itemBg); @@ -139,7 +223,8 @@ public sealed class ParameterSlidersView if (trackWidth > 5) { - double fraction = (p.Value - p.Min) / (p.Max - p.Min); + double range = p.Max - p.Min; + double fraction = range > 1e-12 ? (p.Value - p.Min) / range : 0.5; fraction = System.Math.Clamp(fraction, 0.0, 1.0); int thumbPos = (int)System.Math.Round(fraction * (trackWidth - 1)); diff --git a/src/GraphTUI/UI/Views/PresetsGalleryModal.cs b/src/GraphTUI/UI/Views/PresetsGalleryModal.cs index c7ccf26..19a0a35 100644 --- a/src/GraphTUI/UI/Views/PresetsGalleryModal.cs +++ b/src/GraphTUI/UI/Views/PresetsGalleryModal.cs @@ -138,15 +138,19 @@ public sealed class PresetsGalleryModal switch (key.Code) { - case KeyCode.Escape or KeyCode.Char when key.KeyChar is 'q' or 'Q': + case KeyCode.Escape: + case KeyCode.F4: + case KeyCode.Char when key.KeyChar is 'q' or 'Q' or 'p' or 'P': IsOpen = false; break; - case KeyCode.Up or KeyCode.Char when key.KeyChar == 'k': + case KeyCode.Up: + case KeyCode.Char when key.KeyChar == 'k': if (SelectedIndex > 0) SelectedIndex--; break; - case KeyCode.Down or KeyCode.Char when key.KeyChar == 'j': + case KeyCode.Down: + case KeyCode.Char when key.KeyChar == 'j': if (SelectedIndex < Presets.Length - 1) SelectedIndex++; break; @@ -159,7 +163,7 @@ public sealed class PresetsGalleryModal public bool HandleMouse(MouseEvent mouse, int screenWidth, int screenHeight, Action onSelectPreset) { - if (!IsOpen || mouse.Type != MouseEventType.Down) return false; + if (!IsOpen) return false; int modalW = System.Math.Min(70, screenWidth - 6); int modalH = System.Math.Min(Presets.Length * 2 + 4, screenHeight - 4); @@ -168,21 +172,50 @@ public sealed class PresetsGalleryModal if (mouse.Col < col || mouse.Col >= col + modalW || mouse.Row < row || mouse.Row >= row + modalH) { - // Click outside closes modal + if (mouse.Type == MouseEventType.Down) + { + // Click outside closes modal + IsOpen = false; + return true; + } + return false; + } + + // Mouse wheel scrolling + if (mouse.Type == MouseEventType.ScrollUp) + { + if (SelectedIndex > 0) SelectedIndex--; + return true; + } + if (mouse.Type == MouseEventType.ScrollDown) + { + if (SelectedIndex < Presets.Length - 1) SelectedIndex++; + return true; + } + + if (mouse.Type != MouseEventType.Down) return false; + + // Close button click at top right + if (mouse.Row == row && mouse.Col >= col + modalW - 5) + { IsOpen = false; return true; } - // Check which preset was clicked + // Check which preset was clicked with scrolling int listStartRow = row + 2; - for (int i = 0; i < Presets.Length; i++) + int maxItems = (modalH - 4) / 2; + int firstVisible = System.Math.Max(0, System.Math.Min(SelectedIndex - maxItems + 1, Presets.Length - maxItems)); + + for (int i = 0; i < maxItems && (firstVisible + i) < Presets.Length; i++) { int itemRow = listStartRow + i * 2; if (mouse.Row == itemRow || mouse.Row == itemRow + 1) { - SelectedIndex = i; + int itemIdx = firstVisible + i; + SelectedIndex = itemIdx; IsOpen = false; - onSelectPreset(Presets[i]); + onSelectPreset(Presets[itemIdx]); return true; } } @@ -200,15 +233,18 @@ public sealed class PresetsGalleryModal int row = (screenHeight - modalH) / 2; screen.DrawBox(col, row, modalW, modalH, ColorRgb.Accent, ColorRgb.SidebarBg, "Presets Gallery (Enter: Load, Esc: Close)"); + screen.DrawText(col + modalW - 5, row, "[X]", ColorRgb.Red, ColorRgb.SidebarBg); int listStartRow = row + 2; - for (int i = 0; i < Presets.Length; i++) - { - var p = Presets[i]; - int itemRow = listStartRow + i * 2; - if (itemRow + 1 >= row + modalH - 1) break; + int maxItems = (modalH - 4) / 2; + int firstVisible = System.Math.Max(0, System.Math.Min(SelectedIndex - maxItems + 1, Presets.Length - maxItems)); - bool isSelected = i == SelectedIndex; + for (int i = 0; i < maxItems && (firstVisible + i) < Presets.Length; i++) + { + int presetIdx = firstVisible + i; + var p = Presets[presetIdx]; + int itemRow = listStartRow + i * 2; + bool isSelected = presetIdx == SelectedIndex; ColorRgb bg = isSelected ? new ColorRgb(35, 45, 65) : ColorRgb.SidebarBg; // Clear background lines diff --git a/tests/GraphTUI.Tests/ClippingAndInteractiveTests.cs b/tests/GraphTUI.Tests/ClippingAndInteractiveTests.cs new file mode 100644 index 0000000..fedd4a7 --- /dev/null +++ b/tests/GraphTUI.Tests/ClippingAndInteractiveTests.cs @@ -0,0 +1,131 @@ +using GraphTUI.Core.Math; +using GraphTUI.Core.Models; +using GraphTUI.Rendering; +using GraphTUI.Terminal; +using GraphTUI.UI.Views; + +namespace GraphTUI.Tests; + +public static class ClippingAndInteractiveTests +{ + public static void Register(TestRunner runner) + { + runner.Add("Clipping: 8-pass Cohen-Sutherland keeps diagonal line", () => + { + var canvas = new BrailleCanvas(20, 20); // 40 x 80 subpixels + // Line from (-50, -50) to (100, 100) crosses the canvas diagonally + canvas.DrawLine(-50, -50, 100, 100, ColorRgb.White); + + // Subpixel center (20, 40) should have been drawn + // Check that at least some pixels were plotted on the canvas + bool anyPixelSet = false; + for (int sy = 0; sy < canvas.SubpixelHeight; sy++) + { + for (int sx = 0; sx < canvas.SubpixelWidth; sx++) + { + // If center line area has dots + if (sx == sy / 2) + { + anyPixelSet = true; + break; + } + } + if (anyPixelSet) break; + } + Assert.True(anyPixelSet, "Expected pixels to be rasterized on canvas"); + }); + + runner.Add("Parameters: Unbounded range expansion and custom steps", () => + { + var param = new Parameter("speed", 5.0, -10.0, 10.0, 0.1); + Assert.Equal(5.0, param.Value); + + // Expand range beyond original [-10, 10] + param.SetRange(-100.0, 100.0, 1.0); + param.SetValue(75.0); + Assert.Equal(75.0, param.Value); + Assert.Equal(-100.0, param.Min); + Assert.Equal(100.0, param.Max); + + // Increment + param.Increment(); + Assert.Equal(76.0, param.Value); + param.Decrement(2.0); + Assert.Equal(74.0, param.Value); + }); + + runner.Add("Builtin Functions: Validation and comma counting", () => + { + // 3-arg sum: sum(start, end, body) + var eval3 = Evaluator.Compile("sum(1, 5, x)"); + Assert.NotNull(eval3); + Assert.Equal(15.0, eval3.Evaluate(3)); // 5 * 3 = 15 + + // 4-arg sum: sum(n, start, end, body) + var eval4 = Evaluator.Compile("sum(n, 1, 4, n)"); + Assert.NotNull(eval4); + Assert.Equal(10.0, eval4.Evaluate(0)); // 1 + 2 + 3 + 4 = 10 + + // factorial function call + var evalFact = Evaluator.Compile("factorial(5)"); + Assert.Equal(120.0, evalFact.Evaluate(0)); + }); + + runner.Add("Modals: Keyboard exit and interactivity parity", () => + { + var viewport = new Viewport(); + + // 1. CalculusModal + var calc = new CalculusModal { IsOpen = true }; + var fn = new GraphFunction(1, "y = x^2", ColorRgb.Cyan); + calc.Open(fn, viewport, null); + Assert.True(calc.IsOpen); + + // Up/Down/Tab navigation + calc.HandleKey(new KeyAction(KeyCode.Down), viewport, null, () => { }); + Assert.Equal(1, calc.SelectedControlIndex); + calc.HandleKey(new KeyAction(KeyCode.Tab), viewport, null, () => { }); + Assert.Equal(2, calc.SelectedControlIndex); + + // Exit with 'q' + calc.HandleKey(new KeyAction(KeyCode.Char, 'q'), viewport, null, () => { }); + Assert.False(calc.IsOpen, "CalculusModal should exit on 'q'"); + + // Exit with 'F3' + calc.IsOpen = true; + calc.HandleKey(new KeyAction(KeyCode.F3), viewport, null, () => { }); + Assert.False(calc.IsOpen, "CalculusModal should exit on F3"); + + // 2. CheatsheetModal + var cheat = new CheatsheetModal { IsOpen = true }; + cheat.HandleKey(new KeyAction(KeyCode.Char, 'q')); + Assert.False(cheat.IsOpen, "CheatsheetModal should exit on 'q'"); + + cheat.IsOpen = true; + cheat.HandleKey(new KeyAction(KeyCode.F5)); + Assert.False(cheat.IsOpen, "CheatsheetModal should exit on F5"); + + // 3. PresetsGalleryModal + var presets = new PresetsGalleryModal { IsOpen = true }; + presets.HandleKey(new KeyAction(KeyCode.Char, 'q'), _ => { }); + Assert.False(presets.IsOpen, "PresetsGalleryModal should exit on 'q'"); + + presets.IsOpen = true; + presets.HandleKey(new KeyAction(KeyCode.F4), _ => { }); + Assert.False(presets.IsOpen, "PresetsGalleryModal should exit on F4"); + + // 4. HelpModal + var help = new HelpModal { IsOpen = true }; + help.HandleKey(new KeyAction(KeyCode.Char, 'q')); + Assert.False(help.IsOpen, "HelpModal should exit on 'q'"); + + help.IsOpen = true; + help.HandleKey(new KeyAction(KeyCode.F1)); + Assert.False(help.IsOpen, "HelpModal should exit on F1"); + + help.IsOpen = true; + help.HandleKey(new KeyAction(KeyCode.Escape)); + Assert.False(help.IsOpen, "HelpModal should exit on Escape"); + }); + } +} diff --git a/tests/GraphTUI.Tests/Program.cs b/tests/GraphTUI.Tests/Program.cs index 827f037..89e24cb 100644 --- a/tests/GraphTUI.Tests/Program.cs +++ b/tests/GraphTUI.Tests/Program.cs @@ -14,6 +14,8 @@ public static class Program DoubleSidedEquationTests.Register(runner); SummationProductIntegralTests.Register(runner); FactorialVariantsTests.Register(runner); + UserDefinedFunctionTests.Register(runner); + ClippingAndInteractiveTests.Register(runner); return runner.RunAll(); } diff --git a/tests/GraphTUI.Tests/TestFramework.cs b/tests/GraphTUI.Tests/TestFramework.cs index 6cf82c4..73d70e7 100644 --- a/tests/GraphTUI.Tests/TestFramework.cs +++ b/tests/GraphTUI.Tests/TestFramework.cs @@ -20,6 +20,12 @@ public static class Assert throw new Exception(message ?? $"Assertion failed: expected '{expected}', got '{actual}'."); } + public static void NotNull(object? obj, string? message = null) + { + if (obj is null) + throw new Exception(message ?? "Assertion failed: expected non-null, got null."); + } + public static void Within(double expected, double actual, double tolerance, string? message = null) { double diff = System.Math.Abs(expected - actual); diff --git a/tests/GraphTUI.Tests/UserDefinedFunctionTests.cs b/tests/GraphTUI.Tests/UserDefinedFunctionTests.cs new file mode 100644 index 0000000..6621dc6 --- /dev/null +++ b/tests/GraphTUI.Tests/UserDefinedFunctionTests.cs @@ -0,0 +1,132 @@ +using GraphTUI.Core.Math; +using GraphTUI.Core.Models; +using GraphTUI.Rendering; + +namespace GraphTUI.Tests; + +public static class UserDefinedFunctionTests +{ + public static void Register(TestRunner runner) + { + runner.Add("UserFunction: f(x) = x^2 + 5 definition and evaluation", () => + { + var fn = new GraphFunction(1, "f(x) = x^2 + 5", ColorRgb.Cyan); + Assert.Equal(FunctionType.Definition, fn.Type); + Assert.True(fn.IsDefinition, "Expected IsDefinition == true"); + Assert.False(fn.IsGraphable, "Function definitions should not be graphable directly"); + Assert.Equal("f", fn.DefinitionName); + Assert.NotNull(fn.DefinitionArgs); + Assert.Equal(1, fn.DefinitionArgs!.Length); + Assert.Equal("x", fn.DefinitionArgs[0]); + Assert.True(fn.CompilationError == null, $"Compilation failed: {fn.CompilationError}"); + + // Direct evaluation lookup test + bool Lookup(string name, double[] args, in EvaluationContext callerCtx, out double result) + { + result = double.NaN; + if (callerCtx.CallDepth >= 64) return true; + if (name.Equals("f", StringComparison.OrdinalIgnoreCase) && args.Length == 1) + { + result = fn.DefinitionBody!.Evaluate(new EvaluationContext(x: args[0], callDepth: callerCtx.CallDepth + 1)); + return true; + } + return false; + } + + // Call inside an Evaluator: y = f(3) + var caller = Evaluator.Compile("f(3)"); + double val = caller.Evaluate(0, userFunctionLookup: Lookup); + Assert.Equal(14.0, val); // 3^2 + 5 = 14 + + // Call inside formula with variable x: y = f(x) + 1 at x = 2 + var caller2 = Evaluator.Compile("f(x) + 1"); + double val2 = caller2.Evaluate(2, userFunctionLookup: Lookup); + Assert.Equal(10.0, val2); // (2^2 + 5) + 1 = 10 + }); + + runner.Add("UserFunction: Multi-argument definitions g(x, y) = x^2 + y^2", () => + { + var fn = new GraphFunction(2, "g(x, y) = x^2 + y^2", ColorRgb.Yellow); + Assert.Equal(FunctionType.Definition, fn.Type); + Assert.Equal("g", fn.DefinitionName); + Assert.NotNull(fn.DefinitionArgs); + Assert.Equal(2, fn.DefinitionArgs!.Length); + Assert.Equal("x", fn.DefinitionArgs[0]); + Assert.Equal("y", fn.DefinitionArgs[1]); + + bool Lookup(string name, double[] args, in EvaluationContext callerCtx, out double result) + { + result = double.NaN; + if (callerCtx.CallDepth >= 64) return true; + if (name.Equals("g", StringComparison.OrdinalIgnoreCase) && args.Length == 2) + { + result = fn.DefinitionBody!.Evaluate(new EvaluationContext(x: args[0], y: args[1], callDepth: callerCtx.CallDepth + 1)); + return true; + } + return false; + } + + var eval = Evaluator.Compile("g(3, 4)"); + double res = eval.Evaluate(0, userFunctionLookup: Lookup); + Assert.Equal(25.0, res); // 3^2 + 4^2 = 25 + }); + + runner.Add("UserFunction: Nested user-defined functions and calculus", () => + { + var f = new GraphFunction(1, "f(x) = x^2 + 1", ColorRgb.Cyan); + var g = new GraphFunction(2, "g(x) = 2 * f(x)", ColorRgb.Yellow); + + bool Lookup(string name, double[] args, in EvaluationContext callerCtx, out double result) + { + result = double.NaN; + if (callerCtx.CallDepth >= 64) return true; + if (name.Equals("f", StringComparison.OrdinalIgnoreCase) && args.Length == 1) + { + result = f.DefinitionBody!.Evaluate(new EvaluationContext(x: args[0], userFunctionLookup: Lookup, callDepth: callerCtx.CallDepth + 1)); + return true; + } + if (name.Equals("g", StringComparison.OrdinalIgnoreCase) && args.Length == 1) + { + result = g.DefinitionBody!.Evaluate(new EvaluationContext(x: args[0], userFunctionLookup: Lookup, callDepth: callerCtx.CallDepth + 1)); + return true; + } + return false; + } + + var eval = Evaluator.Compile("g(3)"); + double res = eval.Evaluate(0, userFunctionLookup: Lookup); + Assert.Equal(20.0, res); // 2 * (3^2 + 1) = 20 + + // Calculus derivative on f(x) + double deriv = Calculus.Derivative(t => + { + var dummyCtx = new EvaluationContext(); + Lookup("f", [t], in dummyCtx, out double r); + return r; + }, 3.0); + Assert.Within(6.0, deriv, 1e-3); // d/dx[x^2 + 1] at x=3 is 6 + }); + + runner.Add("UserFunction: Recursion limit prevents stack overflow", () => + { + // rec(x) = rec(x) + 1 + var recFn = new GraphFunction(1, "rec(x) = rec(x) + 1", ColorRgb.Red); + + bool Lookup(string name, double[] args, in EvaluationContext callerCtx, out double result) + { + result = double.NaN; + if (callerCtx.CallDepth >= 64) return true; + if (name.Equals("rec", StringComparison.OrdinalIgnoreCase) && args.Length == 1) + { + result = recFn.DefinitionBody!.Evaluate(new EvaluationContext(x: args[0], userFunctionLookup: Lookup, callDepth: callerCtx.CallDepth + 1)); + return true; + } + return false; + } + + var eval = Evaluator.Compile("rec(1)"); + double val = eval.Evaluate(0, userFunctionLookup: Lookup); + Assert.True(double.IsNaN(val), "Infinite recursion must terminate with NaN"); + }); + } +}