micronona/TextEditor.cs

434 lines
15 KiB
C#
Raw Normal View History

using System.Collections.Concurrent;
/// <summary>
/// Editor actions delivered from the SDL main loop. All non-printable input is
/// expressed as one of these; printable characters arrive via OnChar.
/// </summary>
public enum EditorAction
{
Left, Right, Up, Down,
Home, End, PageUp, PageDown,
Backspace, Delete, Enter,
Save, Undo, CutLine, PasteLine, Quit
}
internal enum EditorOpType
{
InsertChar, DeleteChar,
InsertLine, DeleteLine,
SplitLine, JoinLine,
ReplaceLine
}
internal readonly record struct EditorOp(EditorOpType Type, int Row, int Col, char Ch, string? Line);
/// <summary>
/// Full-screen text editor for Micronona. Runs on its own thread, blocks on an
/// event queue fed by the SDL main loop. Renders directly into the text-mode
/// framebuffer via ConsoleHelper; the hardware cursor is positioned through
/// REG_CURSOR_COL/ROW so the existing inverting render handles cursor display.
///
/// Layout (40×18):
/// row 0 title bar (filename + [modified])
/// rows 1..16 content (16 visible rows, horizontal scrolling)
/// row 17 shortcut bar / quit-confirm prompt
/// </summary>
public sealed class TextEditor
{
private const int TitleRow = 0;
private const int ContentTop = 1;
private const int ShortcutRow = MemoryModel.TextRows - 1; // 17
private const int ContentRows = ShortcutRow - ContentTop; // 16
private const int Cols = MemoryModel.TextCols; // 40
private const byte ContentFg = ConsoleHelper.DefaultFg;
private const byte ContentBg = ConsoleHelper.DefaultBg;
private const byte BarFg = ConsoleHelper.DefaultBg; // inverted bars
private const byte BarBg = ConsoleHelper.DefaultFg;
private readonly ConsoleHelper _con;
private readonly List<string> _lines = new();
private readonly Stack<EditorOp> _undo = new();
private readonly BlockingCollection<object> _events = new();
private string _filePath = "";
private int _row, _col;
private int _viewRow, _viewCol;
private bool _dirty;
private string? _clipboard;
private bool _confirmQuit;
private volatile bool _active;
public bool IsActive => _active;
public TextEditor(ConsoleHelper con) => _con = con;
public void OnChar(char c) { if (_active) _events.Add(c); }
public void OnAction(EditorAction a) { if (_active) _events.Add(a); }
public void Run(string path)
{
if (_active) return;
_active = true;
new Thread(() => RunLoop(path)) { IsBackground = true, Name = "TextEditor" }.Start();
}
// -----------------------------------------------------------------------
// Editor loop
// -----------------------------------------------------------------------
private void RunLoop(string path)
{
byte prevFg = _con.CurrentFg;
byte prevBg = _con.CurrentBg;
try
{
_filePath = path;
_lines.Clear();
_undo.Clear();
_clipboard = null;
_row = _col = 0;
_viewRow = _viewCol = 0;
_dirty = false;
_confirmQuit = false;
while (_events.TryTake(out _)) { }
if (File.Exists(path))
foreach (var line in File.ReadAllLines(path))
_lines.Add(line);
if (_lines.Count == 0) _lines.Add("");
_con.CurrentFg = ContentFg;
_con.CurrentBg = ContentBg;
_con.Cls();
EnsureCursorVisible();
RenderAll();
UpdateCursor();
while (_active)
{
object ev = _events.Take();
if (!_active) break;
if (ev is char ch) HandleChar(ch);
else if (ev is EditorAction a) HandleAction(a);
EnsureCursorVisible();
RenderAll();
UpdateCursor();
}
}
finally
{
_active = false;
_con.CurrentFg = prevFg;
_con.CurrentBg = prevBg;
_con.Cls();
_con.WriteText("OK");
_con.NewLine();
}
}
// -----------------------------------------------------------------------
// Input handling
// -----------------------------------------------------------------------
private void HandleChar(char c)
{
if (_confirmQuit)
{
char cl = char.ToLowerInvariant(c);
if (cl == 'y') { Save(); _active = false; }
else if (cl == 'n') { _active = false; }
else { _confirmQuit = false; }
return;
}
if (c < 32 || c > 126) return;
_lines[_row] = _lines[_row].Insert(_col, c.ToString());
_undo.Push(new EditorOp(EditorOpType.InsertChar, _row, _col, c, null));
_col++;
_dirty = true;
}
private void HandleAction(EditorAction a)
{
if (_confirmQuit) { _confirmQuit = false; return; }
switch (a)
{
case EditorAction.Left:
if (_col > 0) _col--;
else if (_row > 0) { _row--; _col = _lines[_row].Length; }
break;
case EditorAction.Right:
if (_col < _lines[_row].Length) _col++;
else if (_row < _lines.Count - 1) { _row++; _col = 0; }
break;
case EditorAction.Up:
if (_row > 0) { _row--; _col = Math.Min(_col, _lines[_row].Length); }
break;
case EditorAction.Down:
if (_row < _lines.Count - 1) { _row++; _col = Math.Min(_col, _lines[_row].Length); }
break;
case EditorAction.Home: _col = 0; break;
case EditorAction.End: _col = _lines[_row].Length; break;
case EditorAction.PageUp:
_row = Math.Max(0, _row - ContentRows);
_col = Math.Min(_col, _lines[_row].Length);
break;
case EditorAction.PageDown:
_row = Math.Min(_lines.Count - 1, _row + ContentRows);
_col = Math.Min(_col, _lines[_row].Length);
break;
case EditorAction.Enter:
{
string left = _lines[_row].Substring(0, _col);
string right = _lines[_row].Substring(_col);
_lines[_row] = left;
_lines.Insert(_row + 1, right);
_undo.Push(new EditorOp(EditorOpType.SplitLine, _row, _col, '\0', null));
_row++; _col = 0;
_dirty = true;
break;
}
case EditorAction.Backspace:
if (_col > 0)
{
char ch = _lines[_row][_col - 1];
_lines[_row] = _lines[_row].Remove(_col - 1, 1);
_undo.Push(new EditorOp(EditorOpType.DeleteChar, _row, _col - 1, ch, null));
_col--;
_dirty = true;
}
else if (_row > 0)
{
int joinCol = _lines[_row - 1].Length;
_lines[_row - 1] += _lines[_row];
_lines.RemoveAt(_row);
_undo.Push(new EditorOp(EditorOpType.JoinLine, _row - 1, joinCol, '\0', null));
_row--; _col = joinCol;
_dirty = true;
}
break;
case EditorAction.Delete:
if (_col < _lines[_row].Length)
{
char ch = _lines[_row][_col];
_lines[_row] = _lines[_row].Remove(_col, 1);
_undo.Push(new EditorOp(EditorOpType.DeleteChar, _row, _col, ch, null));
_dirty = true;
}
else if (_row < _lines.Count - 1)
{
int joinCol = _lines[_row].Length;
_lines[_row] += _lines[_row + 1];
_lines.RemoveAt(_row + 1);
_undo.Push(new EditorOp(EditorOpType.JoinLine, _row, joinCol, '\0', null));
_dirty = true;
}
break;
case EditorAction.CutLine:
{
string content = _lines[_row];
_clipboard = content;
if (_lines.Count == 1)
{
_lines[0] = "";
_undo.Push(new EditorOp(EditorOpType.ReplaceLine, 0, 0, '\0', content));
}
else
{
_lines.RemoveAt(_row);
_undo.Push(new EditorOp(EditorOpType.DeleteLine, _row, 0, '\0', content));
if (_row >= _lines.Count) _row = _lines.Count - 1;
}
_col = Math.Min(_col, _lines[_row].Length);
_dirty = true;
break;
}
case EditorAction.PasteLine:
if (_clipboard != null)
{
_lines.Insert(_row, _clipboard);
_undo.Push(new EditorOp(EditorOpType.InsertLine, _row, 0, '\0', _clipboard));
_row++;
_dirty = true;
}
break;
case EditorAction.Undo:
DoUndo();
break;
case EditorAction.Save:
Save();
break;
case EditorAction.Quit:
if (_dirty) _confirmQuit = true;
else _active = false;
break;
}
}
// -----------------------------------------------------------------------
// Undo — pop one op, apply its inverse
// -----------------------------------------------------------------------
private void DoUndo()
{
if (_undo.Count == 0) return;
var op = _undo.Pop();
switch (op.Type)
{
case EditorOpType.InsertChar:
_lines[op.Row] = _lines[op.Row].Remove(op.Col, 1);
_row = op.Row; _col = op.Col;
break;
case EditorOpType.DeleteChar:
_lines[op.Row] = _lines[op.Row].Insert(op.Col, op.Ch.ToString());
_row = op.Row; _col = op.Col + 1;
break;
case EditorOpType.SplitLine:
_lines[op.Row] += _lines[op.Row + 1];
_lines.RemoveAt(op.Row + 1);
_row = op.Row; _col = op.Col;
break;
case EditorOpType.JoinLine:
{
string full = _lines[op.Row];
_lines[op.Row] = full.Substring(0, op.Col);
_lines.Insert(op.Row + 1, full.Substring(op.Col));
_row = op.Row; _col = op.Col;
break;
}
case EditorOpType.InsertLine:
_lines.RemoveAt(op.Row);
if (_lines.Count == 0) _lines.Add("");
_row = Math.Min(op.Row, _lines.Count - 1);
_col = 0;
break;
case EditorOpType.DeleteLine:
_lines.Insert(op.Row, op.Line!);
_row = op.Row; _col = 0;
break;
case EditorOpType.ReplaceLine:
_lines[op.Row] = op.Line!;
_row = op.Row; _col = Math.Min(op.Line!.Length, op.Line.Length);
break;
}
_dirty = _undo.Count > 0;
}
// -----------------------------------------------------------------------
// Disk I/O
// -----------------------------------------------------------------------
private void Save()
{
try
{
File.WriteAllLines(_filePath, _lines);
_dirty = false;
}
catch (Exception ex)
{
Console.Error.WriteLine($"[Editor] save failed: {ex.Message}");
}
}
// -----------------------------------------------------------------------
// Viewport
// -----------------------------------------------------------------------
private void EnsureCursorVisible()
{
if (_row < _viewRow) _viewRow = _row;
if (_row >= _viewRow + ContentRows) _viewRow = _row - ContentRows + 1;
if (_col < _viewCol) _viewCol = _col;
if (_col >= _viewCol + Cols) _viewCol = _col - Cols + 1;
}
// -----------------------------------------------------------------------
// Rendering
// -----------------------------------------------------------------------
private void RenderAll()
{
RenderTitle();
RenderContent();
if (_confirmQuit) RenderConfirm();
else RenderShortcuts();
}
private void RenderTitle()
{
string name = Path.GetFileName(_filePath);
string title = _dirty ? name + " [modified]" : name;
if (title.Length > Cols) title = title.Substring(0, Cols);
int padLeft = (Cols - title.Length) / 2;
for (int c = 0; c < Cols; c++)
{
int idx = c - padLeft;
char ch = (idx >= 0 && idx < title.Length) ? title[idx] : ' ';
_con.SetChar(c, TitleRow, (byte)ch, BarFg, BarBg);
}
}
private void RenderContent()
{
for (int r = 0; r < ContentRows; r++)
{
int lineIdx = _viewRow + r;
string line = lineIdx < _lines.Count ? _lines[lineIdx] : "";
for (int c = 0; c < Cols; c++)
{
int colIdx = _viewCol + c;
char ch = colIdx < line.Length ? line[colIdx] : ' ';
if (ch < 32 || ch > 126) ch = ' ';
_con.SetChar(c, ContentTop + r, (byte)ch, ContentFg, ContentBg);
}
}
}
private void RenderShortcuts()
{
const string s = "^S Save ^Z Undo ^K Cut ^U Paste ^Q Quit";
for (int c = 0; c < Cols; c++)
{
char ch = c < s.Length ? s[c] : ' ';
_con.SetChar(c, ShortcutRow, (byte)ch, BarFg, BarBg);
}
}
private void RenderConfirm()
{
const string msg = "Save changes? Y/N";
int padLeft = (Cols - msg.Length) / 2;
for (int c = 0; c < Cols; c++)
{
int idx = c - padLeft;
char ch = (idx >= 0 && idx < msg.Length) ? msg[idx] : ' ';
_con.SetChar(c, ShortcutRow, (byte)ch, BarFg, BarBg);
}
}
private void UpdateCursor()
{
if (_confirmQuit) { _con.SetCursor(0, ShortcutRow); return; }
int screenX = _col - _viewCol;
int screenY = ContentTop + (_row - _viewRow);
_con.SetCursor((byte)screenX, (byte)screenY);
}
}