Keyboard-Layout-Detection, SN76489-Sound, Text-Editor
- KeyboardLayoutDetector (KMAP-Befehl und --detect-keyboard-CLI) inkl. loadkeys-Integration und Persistenz im .micronona-Marker - SN76489 PSG mit SDL-Audio-Anbindung - Voll-Bildschirm-Texteditor (edit <file>) mit Undo, Cut/Paste, horizontalem Scrollen und Speicherbestätigung - DiskManager-Erweiterungen: FindMicrononaMount, SaveKeyboardLayout, Dir-Listing - ^-Glyph für die Editor-Statuszeile Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
c13f25ab08
commit
e0078538c3
10 changed files with 2130 additions and 106 deletions
|
|
@ -4,7 +4,44 @@
|
|||
"Bash(dotnet remove:*)",
|
||||
"Bash(dotnet add:*)",
|
||||
"Bash(dotnet build:*)",
|
||||
"Bash(dotnet run:*)"
|
||||
"Bash(dotnet run:*)",
|
||||
"Bash(dotnet restore:*)",
|
||||
"Bash(curl:*)",
|
||||
"Bash(sudo tee:*)",
|
||||
"Bash(sudo udevadm:*)",
|
||||
"Bash(sudo chmod:*)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(git commit:*)",
|
||||
"Bash(git -C /home/hajo/Homework/Micronona status)",
|
||||
"Bash(git -C /home/hajo/Homework/Micronona diff --stat)",
|
||||
"Bash(git -C /home/hajo/Homework/Micronona add InputInterpreter.cs MemoryModel.cs MicrononaRenderer.cs Program.cs)",
|
||||
"Bash(git -C /home/hajo/Homework/Micronona commit -m ':*)",
|
||||
"Bash(git:*)",
|
||||
"Bash(kill %1)",
|
||||
"Bash(wait)",
|
||||
"Read(//tmp/**)",
|
||||
"Bash(sync)",
|
||||
"Bash(dpkg -L kbd)",
|
||||
"Bash(dpkg -L console-data)",
|
||||
"Bash(apt list *)",
|
||||
"Bash(apt-cache search *)",
|
||||
"Bash(loadkeys -V)",
|
||||
"Bash(dpkg -L console-setup-linux)",
|
||||
"Bash(zcat /etc/console-setup/cached_UTF-8_del.kmap.gz)",
|
||||
"Bash(apt-cache policy *)",
|
||||
"Bash(dpkg -l)",
|
||||
"Bash(sudo apt *)",
|
||||
"Bash(xargs -I {} sh -c 'echo \"{}: $\\(zcat \"{}\" 2>/dev/null | head -5 | tail -3\\)\"')",
|
||||
"Bash(zcat /usr/share/keymaps/i386/include/linux-keys-bare.inc.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/qwertz/de-latin1-nodeadkeys.kmap.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/qwertz/de.kmap.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/qwertz/croat.kmap.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/qwertz/de-latin1.kmap.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/include/qwertz-layout.inc.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/qwerty/ar.kmap.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/qwerty/fa.kmap.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/include/linux-with-modeshift-altgr.inc.gz)",
|
||||
"Bash(zcat /usr/share/keymaps/i386/qwerty/lv-latin7.kmap.gz)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,9 +2,17 @@ public class ConsoleHelper
|
|||
{
|
||||
private readonly MemoryModel _mem;
|
||||
|
||||
public const byte DefaultFg = 0x1C; // Bright green: R=0, G=224, B=0
|
||||
public const byte DefaultBg = 0x08; // Dark green: R=0, G=64, B=0
|
||||
|
||||
public byte CurrentFg { get; set; }
|
||||
public byte CurrentBg { get; set; }
|
||||
|
||||
public ConsoleHelper(MemoryModel mem)
|
||||
{
|
||||
_mem = mem;
|
||||
CurrentFg = DefaultFg;
|
||||
CurrentBg = DefaultBg;
|
||||
}
|
||||
|
||||
static byte Rgb332Mid(byte a, byte b)
|
||||
|
|
@ -32,10 +40,9 @@ public class ConsoleHelper
|
|||
_mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 2));
|
||||
}
|
||||
|
||||
_mem.WriteFlat(textBase + rowEnd, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg);
|
||||
_mem.WriteFlat(textBase + rowEnd, 0x20, CurrentFg, CurrentBg);
|
||||
}
|
||||
|
||||
|
||||
public void Backspace()
|
||||
{
|
||||
int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL);
|
||||
|
|
@ -44,7 +51,6 @@ public class ConsoleHelper
|
|||
if (col == 0) { col = MemoryModel.TextCols - 1; row--; }
|
||||
else col--;
|
||||
|
||||
// Rest der Zeile nach links ziehen
|
||||
int textBase = MemoryModel.TextBankIndex * MemoryModel.BankSize;
|
||||
int rowEnd = (row * MemoryModel.TextCols + MemoryModel.TextCols - 1) * MemoryModel.TextCellSize;
|
||||
int startOffset = (row * MemoryModel.TextCols + col) * MemoryModel.TextCellSize;
|
||||
|
|
@ -57,8 +63,7 @@ public class ConsoleHelper
|
|||
_mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 2));
|
||||
}
|
||||
|
||||
// Letztes Zeichen der Zeile löschen
|
||||
_mem.WriteFlat(textBase + rowEnd, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg);
|
||||
_mem.WriteFlat(textBase + rowEnd, 0x20, CurrentFg, CurrentBg);
|
||||
|
||||
_mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL, (byte)col);
|
||||
_mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW, (byte)row);
|
||||
|
|
@ -66,18 +71,15 @@ public class ConsoleHelper
|
|||
|
||||
public void NewLine()
|
||||
{
|
||||
ReadLine(); // Optional: Aktuelle Zeile lesen und verarbeiten
|
||||
ReadLine();
|
||||
int row = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW);
|
||||
if (row + 1 >= MemoryModel.TextRows)
|
||||
{
|
||||
ScrollUp();
|
||||
}
|
||||
else
|
||||
{
|
||||
row++;
|
||||
}
|
||||
SetCursor(0, (byte)row);
|
||||
}
|
||||
|
||||
public void MoveCursor(int dx, int dy)
|
||||
{
|
||||
int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL);
|
||||
|
|
@ -93,7 +95,6 @@ public class ConsoleHelper
|
|||
int textBase = MemoryModel.TextBankIndex * MemoryModel.BankSize;
|
||||
int rowSize = MemoryModel.TextCols * MemoryModel.TextCellSize;
|
||||
|
||||
// Zeilen 1–17 nach oben kopieren
|
||||
for (int row = 0; row < MemoryModel.TextRows - 1; row++)
|
||||
{
|
||||
for (int i = 0; i < rowSize; i++)
|
||||
|
|
@ -103,13 +104,14 @@ public class ConsoleHelper
|
|||
}
|
||||
}
|
||||
|
||||
// Letzte Zeile mit Leerzeichen und Defaultfarben füllen
|
||||
int lastRow = (MemoryModel.TextRows - 1) * rowSize;
|
||||
for (int col = 0; col < MemoryModel.TextCols; col++)
|
||||
{
|
||||
_mem.WriteFlat(textBase + lastRow + col * MemoryModel.TextCellSize, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg);
|
||||
_mem.WriteFlat(textBase + lastRow + col * MemoryModel.TextCellSize,
|
||||
0x20, CurrentFg, CurrentBg);
|
||||
}
|
||||
}
|
||||
|
||||
public string ReadLine()
|
||||
{
|
||||
int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL);
|
||||
|
|
@ -117,8 +119,6 @@ public class ConsoleHelper
|
|||
|
||||
int textBase = MemoryModel.TextBankIndex * MemoryModel.BankSize;
|
||||
|
||||
// Erste Zeile der logischen Zeile finden:
|
||||
// Solange Spalte 0 der aktuellen Zeile ASCII 31 enthält, ist sie eine Folgezeile.
|
||||
int startRow = row;
|
||||
while (startRow > 0)
|
||||
{
|
||||
|
|
@ -138,7 +138,7 @@ public class ConsoleHelper
|
|||
{
|
||||
int offset = (r * MemoryModel.TextCols + c) * MemoryModel.TextCellSize;
|
||||
byte ch = _mem.ReadFlat(textBase + offset);
|
||||
if (ch == 31) continue; // Umbruch-Marker überspringen
|
||||
if (ch == 31) continue;
|
||||
sb.Append((char)ch);
|
||||
}
|
||||
}
|
||||
|
|
@ -153,6 +153,23 @@ public class ConsoleHelper
|
|||
_mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL, x);
|
||||
_mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW, y);
|
||||
}
|
||||
|
||||
public void Cls()
|
||||
{
|
||||
int textBase = MemoryModel.TextBankIndex * MemoryModel.BankSize;
|
||||
for (int i = 0; i < MemoryModel.TextCols * MemoryModel.TextRows; i++)
|
||||
_mem.WriteFlat(textBase + i * MemoryModel.TextCellSize, 0x20, CurrentFg, CurrentBg);
|
||||
SetCursor(0, 0);
|
||||
}
|
||||
|
||||
public void SetChar(int x, int y, byte ascii, byte fg, byte bg)
|
||||
{
|
||||
if (x < 0 || x >= MemoryModel.TextCols || y < 0 || y >= MemoryModel.TextRows) return;
|
||||
int textBase = MemoryModel.TextBankIndex * MemoryModel.BankSize;
|
||||
int offset = (y * MemoryModel.TextCols + x) * MemoryModel.TextCellSize;
|
||||
_mem.WriteFlat(textBase + offset, ascii, fg, bg);
|
||||
}
|
||||
|
||||
public void WriteText(string text)
|
||||
{
|
||||
if (_mem.Read(MemoryModel.IoBase + MemoryModel.REG_MODE) != 0) return;
|
||||
|
|
@ -160,24 +177,25 @@ public class ConsoleHelper
|
|||
var y = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW);
|
||||
|
||||
var offset = (y * MemoryModel.TextCols + x) * MemoryModel.TextCellSize;
|
||||
foreach (char c in text.ToArray())
|
||||
foreach (char c in text)
|
||||
{
|
||||
var ascii = (byte)c;
|
||||
_mem.WriteFlat(MemoryModel.TextBankIndex * MemoryModel.BankSize + offset, ascii, MemoryModel.DefaultFg, MemoryModel.DefaultBg);
|
||||
_mem.WriteFlat(MemoryModel.TextBankIndex * MemoryModel.BankSize + offset,
|
||||
ascii, CurrentFg, CurrentBg);
|
||||
offset += MemoryModel.TextCellSize;
|
||||
byte column = (byte)(offset % MemoryModel.TextCols);
|
||||
if (column == 0)
|
||||
{
|
||||
byte color = Rgb332Mid(MemoryModel.DefaultBg,MemoryModel.DefaultFg);
|
||||
_mem.WriteFlat(MemoryModel.TextBankIndex * MemoryModel.BankSize + offset, 31, color, MemoryModel.DefaultBg);
|
||||
byte color = Rgb332Mid(CurrentBg, CurrentFg);
|
||||
_mem.WriteFlat(MemoryModel.TextBankIndex * MemoryModel.BankSize + offset,
|
||||
31, color, CurrentBg);
|
||||
offset += MemoryModel.TextCellSize;
|
||||
}
|
||||
while (offset >= MemoryModel.TextCellSize * MemoryModel.TextCols * MemoryModel.TextRows)
|
||||
{
|
||||
ScrollUp();
|
||||
offset -= (MemoryModel.TextCellSize * MemoryModel.TextCols);
|
||||
offset -= MemoryModel.TextCellSize * MemoryModel.TextCols;
|
||||
}
|
||||
|
||||
}
|
||||
offset /= MemoryModel.TextCellSize;
|
||||
_mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL, (byte)(offset % MemoryModel.TextCols));
|
||||
|
|
|
|||
|
|
@ -28,7 +28,7 @@ public class DiskManager : IDisposable
|
|||
private string? _mountedDevice; // e.g. "/dev/sda1"
|
||||
private string? _mountPath; // e.g. "/mnt/micronona"
|
||||
|
||||
private const string MarkerFile = ".micronona";
|
||||
public const string MarkerFile = ".micronona";
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Netlink socket
|
||||
|
|
@ -233,6 +233,50 @@ public class DiskManager : IDisposable
|
|||
Console.WriteLine($"[DiskManager] Written {markerPath}");
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Stick discovery and config update (CLI use)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Scan standard udisks mount roots for a currently-mounted Micronona stick.
|
||||
/// Returns the mount path of the first stick whose root contains the marker
|
||||
/// file, or null if none is found. Independent of the netlink watcher.
|
||||
/// </summary>
|
||||
public static string? FindMicrononaMount()
|
||||
{
|
||||
foreach (string root in new[] { "/run/media", "/media" })
|
||||
{
|
||||
if (!Directory.Exists(root)) continue;
|
||||
foreach (string userDir in Directory.EnumerateDirectories(root))
|
||||
foreach (string mount in Directory.EnumerateDirectories(userDir))
|
||||
if (File.Exists(Path.Combine(mount, MarkerFile)))
|
||||
return mount;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write or update the [keyboard] layout entry in the stick's .micronona file.
|
||||
/// Preserves all other existing keys.
|
||||
/// </summary>
|
||||
public static void SaveKeyboardLayout(string mountPath, string layout)
|
||||
{
|
||||
string markerPath = Path.Combine(mountPath, MarkerFile);
|
||||
Tomlyn.Model.TomlTable model = File.Exists(markerPath)
|
||||
? Tomlyn.Toml.ToModel(File.ReadAllText(markerPath))
|
||||
: new Tomlyn.Model.TomlTable();
|
||||
|
||||
if (!model.TryGetValue("keyboard", out object? kbObj)
|
||||
|| kbObj is not Tomlyn.Model.TomlTable kb)
|
||||
{
|
||||
kb = new Tomlyn.Model.TomlTable();
|
||||
model["keyboard"] = kb;
|
||||
}
|
||||
kb["layout"] = layout;
|
||||
|
||||
File.WriteAllText(markerPath, Tomlyn.Toml.FromModel(model));
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Mount helpers (udisksctl — no root required)
|
||||
// -------------------------------------------------------------------------
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ internal enum Op
|
|||
{
|
||||
PushConst, PushVar,
|
||||
Add, Sub, Mul, Div, Mod, Negate,
|
||||
CallRnd, CallPeek, CallPeekX,
|
||||
CallRnd, CallPeek, CallPeekX, CallGetPixel,
|
||||
CmpEq, CmpLt, CmpGt, CmpLe, CmpGe, CmpNe
|
||||
}
|
||||
|
||||
|
|
@ -27,7 +27,9 @@ internal sealed class CompiledExpr
|
|||
internal enum Keyword
|
||||
{
|
||||
Unknown, Print, Let, Goto, Gosub, Return, If, Input,
|
||||
Poke, PokeX, Rem, End
|
||||
Poke, PokeX, Rem, End,
|
||||
Cls, Locate, Color, Mode, SetChar, Inkey, Vsync,
|
||||
Clear, PutPixel, For, Next
|
||||
}
|
||||
|
||||
internal sealed class TokenizedLine
|
||||
|
|
@ -39,8 +41,11 @@ internal sealed class TokenizedLine
|
|||
|
||||
public CompiledExpr? E0; // primary expression
|
||||
public CompiledExpr? E1; // secondary expression
|
||||
public CompiledExpr? E2; // tertiary expression (POKEX)
|
||||
public CompiledExpr? E2; // tertiary expression (POKEX / SETCHAR)
|
||||
public CompiledExpr? E3; // quaternary expression (SETCHAR)
|
||||
public CompiledExpr? E4; // quinary expression (SETCHAR)
|
||||
public string? PrintLiteral; // PRINT "text" — pre-extracted, no quotes
|
||||
public bool SuppressNewLine; // PRINT "..."; — trailing semicolon
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
@ -55,6 +60,7 @@ internal class InputInterpreter
|
|||
private readonly ConsoleHelper consoleHelper;
|
||||
private readonly DiskManager diskManager;
|
||||
private readonly Cpu6809 cpu;
|
||||
private readonly TextEditor _editor;
|
||||
|
||||
private readonly SortedDictionary<int, string> _program = new();
|
||||
private readonly Dictionary<int, TokenizedLine> _tokenized = new();
|
||||
|
|
@ -67,12 +73,20 @@ internal class InputInterpreter
|
|||
private char _inputVariable;
|
||||
private bool _skipIncrement;
|
||||
private readonly Stack<int> _callStack = new();
|
||||
private readonly Stack<(char var, int to, int step, int bodyPc)> _forStack = new();
|
||||
|
||||
private Thread? _thread;
|
||||
private CancellationTokenSource _cts = new();
|
||||
private readonly ManualResetEventSlim _runSignal = new(false);
|
||||
private readonly SemaphoreSlim _inputSignal = new(0, 1);
|
||||
|
||||
// KMAP state — feeding the keyboard-layout detector from the main SDL loop.
|
||||
private volatile bool _kmapActive;
|
||||
private volatile bool _waitingForKmapKey;
|
||||
private int? _kmapKeycode;
|
||||
private char _kmapDisplayChar;
|
||||
private readonly SemaphoreSlim _kmapSignal = new(0, 1);
|
||||
|
||||
// Perf measurement
|
||||
private long _perfExecute;
|
||||
private long _perfGoto;
|
||||
|
|
@ -97,10 +111,17 @@ internal class InputInterpreter
|
|||
this.consoleHelper = consoleHelper;
|
||||
this.diskManager = diskManager;
|
||||
this.cpu = cpu;
|
||||
_editor = new TextEditor(consoleHelper);
|
||||
}
|
||||
|
||||
public bool IsRunning => _running;
|
||||
public bool IsWaitingForInput => _waitingForInput;
|
||||
public bool IsRunning => _running;
|
||||
public bool IsWaitingForInput => _waitingForInput;
|
||||
public bool IsKmapActive => _kmapActive;
|
||||
public bool IsWaitingForKmapKey => _waitingForKmapKey;
|
||||
public bool IsEditorActive => _editor.IsActive;
|
||||
|
||||
public void EditorChar(char c) => _editor.OnChar(c);
|
||||
public void EditorAction(EditorAction a) => _editor.OnAction(a);
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Thread management
|
||||
|
|
@ -118,6 +139,7 @@ internal class InputInterpreter
|
|||
_cts.Cancel();
|
||||
try { _runSignal.Set(); } catch { }
|
||||
try { _inputSignal.Release(); } catch { }
|
||||
try { _kmapSignal.Release(); } catch { }
|
||||
_thread?.Join();
|
||||
}
|
||||
|
||||
|
|
@ -164,8 +186,10 @@ internal class InputInterpreter
|
|||
{
|
||||
bool wasRunning = _running;
|
||||
_running = false;
|
||||
_forStack.Clear();
|
||||
mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0);
|
||||
if (!wasRunning)
|
||||
mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0);
|
||||
consoleHelper.Cls();
|
||||
if (_waitingForInput)
|
||||
{
|
||||
_waitingForInput = false;
|
||||
|
|
@ -187,7 +211,6 @@ internal class InputInterpreter
|
|||
if (_programCounter >= _lines.Length)
|
||||
{
|
||||
_running = false;
|
||||
mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0);
|
||||
return;
|
||||
}
|
||||
|
||||
|
|
@ -276,6 +299,7 @@ internal class InputInterpreter
|
|||
_lines = _program.Keys.ToArray();
|
||||
_programCounter = 0;
|
||||
_callStack.Clear();
|
||||
_forStack.Clear();
|
||||
_running = true;
|
||||
_runSignal.Set();
|
||||
return;
|
||||
|
|
@ -286,6 +310,7 @@ internal class InputInterpreter
|
|||
_program.Clear(); _tokenized.Clear();
|
||||
_lines = [];
|
||||
_callStack.Clear();
|
||||
_forStack.Clear();
|
||||
_running = false;
|
||||
consoleHelper.WriteText("OK"); consoleHelper.NewLine();
|
||||
return;
|
||||
|
|
@ -311,6 +336,8 @@ internal class InputInterpreter
|
|||
{ ExecuteAsm(input.Substring("asm".Length).Trim()); return; }
|
||||
if (cmd.StartsWith("del ") || cmd.StartsWith("del\""))
|
||||
{ ExecuteDelFile(input.Substring("del".Length).Trim()); return; }
|
||||
if (cmd.StartsWith("edit ") || cmd.StartsWith("edit\""))
|
||||
{ ExecuteEditor(input.Substring("edit".Length).Trim()); return; }
|
||||
|
||||
if (cmd == "dir")
|
||||
{
|
||||
|
|
@ -323,10 +350,95 @@ internal class InputInterpreter
|
|||
return;
|
||||
}
|
||||
|
||||
if (cmd == "kmap") { StartKmap(); return; }
|
||||
|
||||
int? unused = null;
|
||||
ExecuteTokenized(Tokenize(input), ref unused);
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// KMAP — keyboard-layout detection inside Micronona.
|
||||
// The actual work runs on a dedicated thread because the main SDL loop
|
||||
// (which drives key delivery) must keep ticking.
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
public void SubmitKmapKey(int? linuxKeycode, char displayChar = '\0')
|
||||
{
|
||||
if (!_waitingForKmapKey) return;
|
||||
_kmapKeycode = linuxKeycode;
|
||||
_kmapDisplayChar = displayChar;
|
||||
_waitingForKmapKey = false;
|
||||
try { _kmapSignal.Release(); } catch { }
|
||||
}
|
||||
|
||||
private void StartKmap()
|
||||
{
|
||||
if (_kmapActive)
|
||||
{
|
||||
consoleHelper.WriteText("KMAP ALREADY RUNNING");
|
||||
consoleHelper.NewLine();
|
||||
return;
|
||||
}
|
||||
_kmapActive = true;
|
||||
new Thread(RunKmap) { IsBackground = true, Name = "Kmap" }.Start();
|
||||
}
|
||||
|
||||
private void RunKmap()
|
||||
{
|
||||
try
|
||||
{
|
||||
string? layout = KeyboardLayoutDetector.Detect(
|
||||
"/usr/share/keymaps",
|
||||
msg =>
|
||||
{
|
||||
consoleHelper.WriteText(msg);
|
||||
consoleHelper.NewLine();
|
||||
},
|
||||
prompt =>
|
||||
{
|
||||
consoleHelper.WriteText(prompt + ": ");
|
||||
_kmapKeycode = null;
|
||||
_kmapDisplayChar = '\0';
|
||||
_waitingForKmapKey = true;
|
||||
try { _kmapSignal.Wait(_cts.Token); }
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_waitingForKmapKey = false;
|
||||
return null;
|
||||
}
|
||||
if (_kmapDisplayChar != '\0')
|
||||
consoleHelper.WriteText(_kmapDisplayChar.ToString());
|
||||
consoleHelper.NewLine();
|
||||
return _kmapKeycode;
|
||||
});
|
||||
|
||||
if (layout == null)
|
||||
{
|
||||
consoleHelper.WriteText("KMAP CANCELLED");
|
||||
consoleHelper.NewLine();
|
||||
return;
|
||||
}
|
||||
|
||||
if (diskManager.MountPath != null)
|
||||
{
|
||||
DiskManager.SaveKeyboardLayout(diskManager.MountPath, layout);
|
||||
consoleHelper.WriteText($"SAVED: {layout}");
|
||||
}
|
||||
else
|
||||
{
|
||||
consoleHelper.WriteText($"DETECTED: {layout} (NO DISK)");
|
||||
}
|
||||
consoleHelper.NewLine();
|
||||
|
||||
KeyboardLayoutDetector.ApplyLoadkeys(layout);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_waitingForKmapKey = false;
|
||||
_kmapActive = false;
|
||||
}
|
||||
}
|
||||
|
||||
// -----------------------------------------------------------------------
|
||||
// Tokenizer — runs once at line entry; compiles expressions to bytecode
|
||||
// -----------------------------------------------------------------------
|
||||
|
|
@ -346,6 +458,7 @@ internal class InputInterpreter
|
|||
{
|
||||
t.Kw = Keyword.Print;
|
||||
string a = s.Length > 5 ? s.Substring(5).Trim() : "";
|
||||
if (a.EndsWith(";")) { t.SuppressNewLine = true; a = a.Substring(0, a.Length - 1).TrimEnd(); }
|
||||
if (a.StartsWith("\""))
|
||||
{
|
||||
int last = a.LastIndexOf('"');
|
||||
|
|
@ -451,6 +564,148 @@ internal class InputInterpreter
|
|||
return t;
|
||||
}
|
||||
|
||||
if (lo == "cls") { t.Kw = Keyword.Cls; return t; }
|
||||
|
||||
if (lo.StartsWith("locate "))
|
||||
{
|
||||
t.Kw = Keyword.Locate;
|
||||
var args = s.Substring(7).Trim();
|
||||
int comma = args.IndexOf(',');
|
||||
if (comma < 0) { t.Kw = Keyword.Unknown; return t; }
|
||||
try
|
||||
{
|
||||
t.E0 = CompileExpr(args.Substring(0, comma).Trim());
|
||||
t.E1 = CompileExpr(args.Substring(comma + 1).Trim());
|
||||
}
|
||||
catch { t.Kw = Keyword.Unknown; }
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo.StartsWith("color "))
|
||||
{
|
||||
t.Kw = Keyword.Color;
|
||||
var args = s.Substring(6).Trim();
|
||||
int comma = args.IndexOf(',');
|
||||
if (comma < 0) { t.Kw = Keyword.Unknown; return t; }
|
||||
try
|
||||
{
|
||||
t.E0 = CompileExpr(args.Substring(0, comma).Trim());
|
||||
t.E1 = CompileExpr(args.Substring(comma + 1).Trim());
|
||||
}
|
||||
catch { t.Kw = Keyword.Unknown; }
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo.StartsWith("mode "))
|
||||
{
|
||||
t.Kw = Keyword.Mode;
|
||||
try { t.E0 = CompileExpr(s.Substring(5).Trim()); }
|
||||
catch { t.Kw = Keyword.Unknown; }
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo.StartsWith("setchar "))
|
||||
{
|
||||
t.Kw = Keyword.SetChar;
|
||||
var args = s.Substring(8).Trim();
|
||||
var parts = new string[5];
|
||||
int start = 0;
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
int c = args.IndexOf(',', start);
|
||||
if (c < 0) { t.Kw = Keyword.Unknown; return t; }
|
||||
parts[i] = args.Substring(start, c - start).Trim();
|
||||
start = c + 1;
|
||||
}
|
||||
parts[4] = args.Substring(start).Trim();
|
||||
try
|
||||
{
|
||||
t.E0 = CompileExpr(parts[0]);
|
||||
t.E1 = CompileExpr(parts[1]);
|
||||
t.E2 = CompileExpr(parts[2]);
|
||||
t.E3 = CompileExpr(parts[3]);
|
||||
t.E4 = CompileExpr(parts[4]);
|
||||
}
|
||||
catch { t.Kw = Keyword.Unknown; }
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo == "vsync") { t.Kw = Keyword.Vsync; return t; }
|
||||
|
||||
if (lo.StartsWith("clear "))
|
||||
{
|
||||
t.Kw = Keyword.Clear;
|
||||
try { t.E0 = CompileExpr(s.Substring(6).Trim()); }
|
||||
catch { t.Kw = Keyword.Unknown; }
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo.StartsWith("putpixel "))
|
||||
{
|
||||
t.Kw = Keyword.PutPixel;
|
||||
var args = s.Substring(9).Trim();
|
||||
int c1 = args.IndexOf(',');
|
||||
if (c1 < 0) { t.Kw = Keyword.Unknown; return t; }
|
||||
int c2 = args.IndexOf(',', c1 + 1);
|
||||
if (c2 < 0) { t.Kw = Keyword.Unknown; return t; }
|
||||
try
|
||||
{
|
||||
t.E0 = CompileExpr(args.Substring(0, c1).Trim());
|
||||
t.E1 = CompileExpr(args.Substring(c1 + 1, c2 - c1 - 1).Trim());
|
||||
t.E2 = CompileExpr(args.Substring(c2 + 1).Trim());
|
||||
}
|
||||
catch { t.Kw = Keyword.Unknown; }
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo.StartsWith("for "))
|
||||
{
|
||||
var args = s.Substring(4).Trim();
|
||||
if (args.Length < 1 || !char.IsUpper(args[0])) { t.Kw = Keyword.Unknown; return t; }
|
||||
t.Kw = Keyword.For;
|
||||
t.Var = args[0];
|
||||
var rest = args.Substring(1).TrimStart();
|
||||
if (!rest.StartsWith("=")) { t.Kw = Keyword.Unknown; return t; }
|
||||
rest = rest.Substring(1).Trim();
|
||||
int toIdx = FindWord(rest, "TO");
|
||||
if (toIdx < 0) { t.Kw = Keyword.Unknown; return t; }
|
||||
string fromStr = rest.Substring(0, toIdx).Trim();
|
||||
rest = rest.Substring(toIdx + 2).Trim();
|
||||
int stepIdx = FindWord(rest, "STEP");
|
||||
string toStr = stepIdx >= 0 ? rest.Substring(0, stepIdx).Trim() : rest.Trim();
|
||||
string? stepStr = stepIdx >= 0 ? rest.Substring(stepIdx + 4).Trim() : null;
|
||||
try
|
||||
{
|
||||
t.E0 = CompileExpr(fromStr);
|
||||
t.E1 = CompileExpr(toStr);
|
||||
if (stepStr != null) t.E2 = CompileExpr(stepStr);
|
||||
}
|
||||
catch { t.Kw = Keyword.Unknown; }
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo == "next" || lo.StartsWith("next "))
|
||||
{
|
||||
t.Kw = Keyword.Next;
|
||||
if (lo.Length > 5)
|
||||
{
|
||||
var arg = s.Substring(5).Trim();
|
||||
if (arg.Length == 1 && char.IsUpper(arg[0])) t.Var = arg[0];
|
||||
else { t.Kw = Keyword.Unknown; return t; }
|
||||
}
|
||||
// bare NEXT: t.Var bleibt '\0' → passt auf obersten Frame
|
||||
return t;
|
||||
}
|
||||
|
||||
if (lo.StartsWith("inkey ") || lo == "inkey")
|
||||
{
|
||||
t.Kw = Keyword.Inkey;
|
||||
var arg = s.Length > 6 ? s.Substring(6).Trim() : s.Substring(5).Trim();
|
||||
if (arg.Length == 1 && char.IsUpper(arg[0])) t.Var = arg[0];
|
||||
else t.Kw = Keyword.Unknown;
|
||||
return t;
|
||||
}
|
||||
|
||||
return t; // Unknown → SyntaxError at runtime
|
||||
}
|
||||
|
||||
|
|
@ -623,6 +878,33 @@ internal class InputInterpreter
|
|||
return;
|
||||
}
|
||||
|
||||
// GETPIXEL(x, y)
|
||||
if (pos + 8 <= s.Length
|
||||
&& (s[pos] | 0x20) == 'g'
|
||||
&& (s[pos+1] | 0x20) == 'e'
|
||||
&& (s[pos+2] | 0x20) == 't'
|
||||
&& (s[pos+3] | 0x20) == 'p'
|
||||
&& (s[pos+4] | 0x20) == 'i'
|
||||
&& (s[pos+5] | 0x20) == 'x'
|
||||
&& (s[pos+6] | 0x20) == 'e'
|
||||
&& (s[pos+7] | 0x20) == 'l')
|
||||
{
|
||||
pos += 8;
|
||||
SkipSpaces(s, ref pos);
|
||||
if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException();
|
||||
pos++;
|
||||
CompileExprInto(s, ref pos, code); // x
|
||||
SkipSpaces(s, ref pos);
|
||||
if (pos >= s.Length || s[pos] != ',') throw new InvalidOperationException();
|
||||
pos++;
|
||||
CompileExprInto(s, ref pos, code); // y
|
||||
SkipSpaces(s, ref pos);
|
||||
if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException();
|
||||
pos++;
|
||||
code.Add((int)Op.CallGetPixel);
|
||||
return;
|
||||
}
|
||||
|
||||
// Variable (single uppercase letter) — emit 0-based index (A=0 … Z=25)
|
||||
if (char.IsUpper(s[pos]))
|
||||
{
|
||||
|
|
@ -732,6 +1014,14 @@ internal class InputInterpreter
|
|||
stack[sp++] = mem.ReadFlat(bank * MemoryModel.BankSize + addr);
|
||||
break;
|
||||
}
|
||||
case Op.CallGetPixel:
|
||||
{
|
||||
int y = stack[--sp];
|
||||
int x = stack[--sp];
|
||||
int offset = y * 320 + x;
|
||||
stack[sp++] = offset < 57600 ? mem.ReadFlat(offset) : 0;
|
||||
break;
|
||||
}
|
||||
case Op.CmpEq: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] == b ? 1 : 0; break; }
|
||||
case Op.CmpLt: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] < b ? 1 : 0; break; }
|
||||
case Op.CmpGt: { int b = stack[--sp]; stack[sp-1] = stack[sp-1] > b ? 1 : 0; break; }
|
||||
|
|
@ -756,19 +1046,18 @@ internal class InputInterpreter
|
|||
if (t.PrintLiteral != null)
|
||||
{
|
||||
consoleHelper.WriteText(t.PrintLiteral);
|
||||
consoleHelper.NewLine();
|
||||
if (!t.SuppressNewLine) consoleHelper.NewLine();
|
||||
}
|
||||
else if (t.E0 != null)
|
||||
{
|
||||
try { consoleHelper.WriteText(EvalExpr(t.E0).ToString()); }
|
||||
catch { SyntaxError(); break; }
|
||||
if (_running) consoleHelper.NewLine();
|
||||
if (_running && !t.SuppressNewLine) consoleHelper.NewLine();
|
||||
}
|
||||
break;
|
||||
|
||||
case Keyword.End:
|
||||
_running = false;
|
||||
mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, 0);
|
||||
break;
|
||||
|
||||
case Keyword.Rem:
|
||||
|
|
@ -850,6 +1139,140 @@ internal class InputInterpreter
|
|||
catch { SyntaxError(); }
|
||||
break;
|
||||
|
||||
case Keyword.Cls:
|
||||
consoleHelper.Cls();
|
||||
break;
|
||||
|
||||
case Keyword.Locate:
|
||||
try
|
||||
{
|
||||
int x = EvalExpr(t.E0!); if (!_running) break;
|
||||
int y = EvalExpr(t.E1!); if (!_running) break;
|
||||
if (x < 0 || x >= MemoryModel.TextCols || y < 0 || y >= MemoryModel.TextRows)
|
||||
{ consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; }
|
||||
consoleHelper.SetCursor((byte)x, (byte)y);
|
||||
}
|
||||
catch { SyntaxError(); }
|
||||
break;
|
||||
|
||||
case Keyword.Color:
|
||||
try
|
||||
{
|
||||
int fg = EvalExpr(t.E0!); if (!_running) break;
|
||||
int bg = EvalExpr(t.E1!); if (!_running) break;
|
||||
if (fg < 0 || fg > 255 || bg < 0 || bg > 255)
|
||||
{ consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; }
|
||||
consoleHelper.CurrentFg = (byte)fg;
|
||||
consoleHelper.CurrentBg = (byte)bg;
|
||||
}
|
||||
catch { SyntaxError(); }
|
||||
break;
|
||||
|
||||
case Keyword.Mode:
|
||||
try
|
||||
{
|
||||
int mode = EvalExpr(t.E0!); if (!_running) break;
|
||||
mem.Write(MemoryModel.IoBase + MemoryModel.REG_MODE, (byte)mode);
|
||||
}
|
||||
catch { SyntaxError(); }
|
||||
break;
|
||||
|
||||
case Keyword.SetChar:
|
||||
try
|
||||
{
|
||||
int x = EvalExpr(t.E0!); if (!_running) break;
|
||||
int y = EvalExpr(t.E1!); if (!_running) break;
|
||||
int asc = EvalExpr(t.E2!); if (!_running) break;
|
||||
int fg = EvalExpr(t.E3!); if (!_running) break;
|
||||
int bg = EvalExpr(t.E4!); if (!_running) break;
|
||||
if (x < 0 || x >= MemoryModel.TextCols ||
|
||||
y < 0 || y >= MemoryModel.TextRows ||
|
||||
asc < 0 || asc > 255 || fg < 0 || fg > 255 || bg < 0 || bg > 255)
|
||||
{ consoleHelper.WriteText("?RANGE ERROR"); consoleHelper.NewLine(); break; }
|
||||
consoleHelper.SetChar(x, y, (byte)asc, (byte)fg, (byte)bg);
|
||||
}
|
||||
catch { SyntaxError(); }
|
||||
break;
|
||||
|
||||
case Keyword.Inkey:
|
||||
{
|
||||
byte key = mem.Read(MemoryModel.IoBase + MemoryModel.REG_KEY_CHAR);
|
||||
_variables[t.Var - 'A'] = key;
|
||||
break;
|
||||
}
|
||||
|
||||
case Keyword.Vsync:
|
||||
mem.Write(MemoryModel.IoBase + MemoryModel.REG_VSYNC, 1);
|
||||
break;
|
||||
|
||||
case Keyword.Clear:
|
||||
try
|
||||
{
|
||||
int color = EvalExpr(t.E0!); if (!_running) break;
|
||||
mem.FillFlat(0, 57600, (byte)(color & 0xFF));
|
||||
}
|
||||
catch { SyntaxError(); }
|
||||
break;
|
||||
|
||||
case Keyword.PutPixel:
|
||||
try
|
||||
{
|
||||
int x = EvalExpr(t.E0!); if (!_running) break;
|
||||
int y = EvalExpr(t.E1!); if (!_running) break;
|
||||
int color = EvalExpr(t.E2!); if (!_running) break;
|
||||
int offset = y * 320 + x;
|
||||
if (offset < 57600)
|
||||
mem.WriteFlat(offset, (byte)(color & 0xFF));
|
||||
}
|
||||
catch { SyntaxError(); }
|
||||
break;
|
||||
|
||||
case Keyword.For:
|
||||
{
|
||||
int from = EvalExpr(t.E0!); if (!_running) break;
|
||||
int to = EvalExpr(t.E1!); if (!_running) break;
|
||||
int step = t.E2 != null ? EvalExpr(t.E2) : 1; if (!_running) break;
|
||||
_variables[t.Var - 'A'] = from;
|
||||
bool done = step > 0 ? from > to : from < to;
|
||||
if (done)
|
||||
{
|
||||
_programCounter = FindNextPc(t.Var, _programCounter);
|
||||
_skipIncrement = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_forStack.Push((t.Var, to, step, _programCounter + 1));
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
case Keyword.Next:
|
||||
{
|
||||
if (_forStack.Count == 0)
|
||||
{
|
||||
consoleHelper.WriteText("?NEXT WITHOUT FOR"); consoleHelper.NewLine();
|
||||
_running = false; break;
|
||||
}
|
||||
var (fVar, to, step, bodyPc) = _forStack.Peek();
|
||||
if (t.Var != '\0' && t.Var != fVar)
|
||||
{
|
||||
consoleHelper.WriteText("?NEXT WITHOUT FOR"); consoleHelper.NewLine();
|
||||
_running = false; break;
|
||||
}
|
||||
_variables[fVar - 'A'] += step;
|
||||
bool cont = step > 0 ? _variables[fVar - 'A'] <= to : _variables[fVar - 'A'] >= to;
|
||||
if (cont)
|
||||
{
|
||||
_programCounter = bodyPc;
|
||||
_skipIncrement = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
_forStack.Pop();
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
default:
|
||||
SyntaxError();
|
||||
break;
|
||||
|
|
@ -860,6 +1283,38 @@ internal class InputInterpreter
|
|||
// Helpers
|
||||
// -----------------------------------------------------------------------
|
||||
|
||||
private static int FindWord(string s, string word)
|
||||
{
|
||||
string up = s.ToUpperInvariant();
|
||||
int i = 0;
|
||||
while (i + word.Length <= up.Length)
|
||||
{
|
||||
int found = up.IndexOf(word, i);
|
||||
if (found < 0) return -1;
|
||||
bool leftOk = found == 0 || !char.IsLetterOrDigit(up[found - 1]);
|
||||
bool rightOk = found + word.Length >= up.Length || !char.IsLetterOrDigit(up[found + word.Length]);
|
||||
if (leftOk && rightOk) return found;
|
||||
i = found + 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
private int FindNextPc(char var, int fromPc)
|
||||
{
|
||||
int depth = 0;
|
||||
for (int i = fromPc + 1; i < _lines.Length; i++)
|
||||
{
|
||||
var tok = _tokenized[_lines[i]];
|
||||
if (tok.Kw == Keyword.For && tok.Var == var) depth++;
|
||||
if (tok.Kw == Keyword.Next && (tok.Var == '\0' || tok.Var == var))
|
||||
{
|
||||
if (depth == 0) return i + 1;
|
||||
if (tok.Var == var) depth--;
|
||||
}
|
||||
}
|
||||
return _lines.Length;
|
||||
}
|
||||
|
||||
private static void SkipSpaces(string s, ref int pos)
|
||||
{
|
||||
while (pos < s.Length && s[pos] == ' ') pos++;
|
||||
|
|
@ -929,39 +1384,81 @@ internal class InputInterpreter
|
|||
consoleHelper.WriteText("OK"); consoleHelper.NewLine();
|
||||
}
|
||||
|
||||
private void ExecuteEditor(string args)
|
||||
{
|
||||
string? name = ParseFilename(args);
|
||||
if (name == null) { SyntaxError(); return; }
|
||||
if (diskManager.MountPath == null)
|
||||
{ consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; }
|
||||
_editor.Run(Path.Combine(diskManager.MountPath, name));
|
||||
}
|
||||
|
||||
private void ExecuteExec(string args)
|
||||
{
|
||||
string name;
|
||||
if (args.StartsWith("\""))
|
||||
{
|
||||
int close = args.IndexOf('"', 1);
|
||||
if (close < 0) { SyntaxError(); return; }
|
||||
string name = args.Substring(1, close - 1).ToUpperInvariant();
|
||||
string rest = args.Substring(close + 1).TrimStart();
|
||||
if (!rest.StartsWith(",")) { SyntaxError(); return; }
|
||||
int addr;
|
||||
try { addr = EvalExpr(CompileExpr(rest.Substring(1).Trim())); }
|
||||
catch { SyntaxError(); return; }
|
||||
if (!_running) return;
|
||||
|
||||
if (diskManager.MountPath == null)
|
||||
{ consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; }
|
||||
var path = Path.Combine(diskManager.MountPath, name);
|
||||
if (!File.Exists(path))
|
||||
{ consoleHelper.WriteText("?FILE NOT FOUND"); consoleHelper.NewLine(); return; }
|
||||
|
||||
byte[] data = File.ReadAllBytes(path);
|
||||
int start = (data.Length > 0 && data[0] == 0x01) ? 1 : 0;
|
||||
for (int i = start; i < data.Length; i++)
|
||||
mem.Write((ushort)(addr + i - start), data[i]);
|
||||
cpu.Run((ushort)addr);
|
||||
name = args.Substring(1, close - 1).ToUpperInvariant();
|
||||
}
|
||||
else if (args.Length > 0 && !char.IsDigit(args[0]) && args[0] != '$')
|
||||
{
|
||||
name = args.Trim().ToUpperInvariant();
|
||||
}
|
||||
else
|
||||
{
|
||||
// Bare address: EXEC $1000
|
||||
int addr;
|
||||
try { addr = EvalExpr(CompileExpr(args)); }
|
||||
catch { SyntaxError(); return; }
|
||||
if (_running) cpu.Run((ushort)addr);
|
||||
return;
|
||||
}
|
||||
|
||||
if (diskManager.MountPath == null)
|
||||
{ consoleHelper.WriteText("?NO DISK"); consoleHelper.NewLine(); return; }
|
||||
var path = Path.Combine(diskManager.MountPath, name);
|
||||
if (!File.Exists(path))
|
||||
{ consoleHelper.WriteText("?FILE NOT FOUND"); consoleHelper.NewLine(); return; }
|
||||
|
||||
byte[] data = File.ReadAllBytes(path);
|
||||
if (ExecDecb(data, out ushort entry))
|
||||
cpu.Run(entry);
|
||||
}
|
||||
|
||||
private bool ExecDecb(byte[] data, out ushort entry)
|
||||
{
|
||||
entry = 0;
|
||||
int pos = 0;
|
||||
ushort firstLoadAddr = 0;
|
||||
bool hasFirstAddr = false;
|
||||
|
||||
while (pos < data.Length)
|
||||
{
|
||||
byte type = data[pos++];
|
||||
if (type == 0x01) // data block (Micronona binary marker)
|
||||
{
|
||||
if (pos + 4 > data.Length) break;
|
||||
int len = (data[pos] << 8) | data[pos + 1]; pos += 2;
|
||||
ushort addr = (ushort)((data[pos] << 8) | data[pos + 1]); pos += 2;
|
||||
if (!hasFirstAddr) { firstLoadAddr = addr; hasFirstAddr = true; }
|
||||
for (int i = 0; i < len && pos < data.Length; i++)
|
||||
mem.Write((ushort)(addr + i), data[pos++]);
|
||||
}
|
||||
else if (type == 0xFF) // end block — execution address
|
||||
{
|
||||
if (pos + 4 > data.Length) break;
|
||||
pos += 2; // skip length (always 0x0000)
|
||||
ushort execAddr = (ushort)((data[pos] << 8) | data[pos + 1]);
|
||||
// Fall back to first block's load address if no END addr in source.
|
||||
entry = execAddr != 0 ? execAddr : firstLoadAddr;
|
||||
return true;
|
||||
}
|
||||
else break;
|
||||
}
|
||||
consoleHelper.WriteText("?BAD FORMAT"); consoleHelper.NewLine();
|
||||
return false;
|
||||
}
|
||||
|
||||
private void ExecuteAsm(string args)
|
||||
|
|
@ -995,7 +1492,7 @@ internal class InputInterpreter
|
|||
{
|
||||
var psi = new System.Diagnostics.ProcessStartInfo
|
||||
{ FileName = "lwasm", RedirectStandardError = true };
|
||||
psi.ArgumentList.Add("--format=raw");
|
||||
psi.ArgumentList.Add("--format=decb");
|
||||
psi.ArgumentList.Add("-9");
|
||||
psi.ArgumentList.Add("-o");
|
||||
psi.ArgumentList.Add(tmpFile);
|
||||
|
|
@ -1012,11 +1509,9 @@ internal class InputInterpreter
|
|||
return;
|
||||
}
|
||||
|
||||
byte[] raw = File.ReadAllBytes(tmpFile);
|
||||
byte[] output = new byte[raw.Length + 1];
|
||||
output[0] = 0x01;
|
||||
raw.CopyTo(output, 1);
|
||||
File.WriteAllBytes(outputPath, output);
|
||||
byte[] decb = File.ReadAllBytes(tmpFile);
|
||||
decb[0] = 0x01;
|
||||
File.WriteAllBytes(outputPath, decb);
|
||||
}
|
||||
finally { try { File.Delete(tmpFile); } catch { } }
|
||||
}
|
||||
|
|
|
|||
529
KeyboardLayoutDetector.cs
Normal file
529
KeyboardLayoutDetector.cs
Normal file
|
|
@ -0,0 +1,529 @@
|
|||
using System.Globalization;
|
||||
using System.IO.Compression;
|
||||
using System.Text.RegularExpressions;
|
||||
using SDL2;
|
||||
|
||||
/// <summary>
|
||||
/// Phase 1 (CLI only): parses Linux loadkeys keymap files, derives the
|
||||
/// discriminating keycodes in the printable ASCII range, and prompts the user
|
||||
/// to press specific keys via SDL2 until one layout candidate remains.
|
||||
///
|
||||
/// No Micronona display integration — output via Console, input via SDL_KEYDOWN.
|
||||
/// </summary>
|
||||
public static class KeyboardLayoutDetector
|
||||
{
|
||||
private static readonly Regex KeycodeLine = new(
|
||||
@"^\s*(?:plain\s+)?keycode\s+(\d+)\s*=\s*(.+)$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||
|
||||
private static readonly Regex IncludeLine = new(
|
||||
@"^\s*include\s+""([^""]+)""\s*$",
|
||||
RegexOptions.Compiled | RegexOptions.IgnoreCase);
|
||||
|
||||
// loadkeys symbolic names that map to printable ASCII.
|
||||
private static readonly Dictionary<string, char> NamedSymbol = new(StringComparer.Ordinal)
|
||||
{
|
||||
{"space", ' '},
|
||||
{"exclam", '!'}, {"quotedbl", '"'}, {"numbersign", '#'},
|
||||
{"dollar", '$'}, {"percent", '%'}, {"ampersand", '&'},
|
||||
{"apostrophe", '\''},
|
||||
{"parenleft", '('}, {"parenright", ')'},
|
||||
{"asterisk", '*'}, {"plus", '+'},
|
||||
{"comma", ','}, {"minus", '-'},
|
||||
{"period", '.'}, {"slash", '/'},
|
||||
{"zero", '0'}, {"one", '1'}, {"two", '2'}, {"three", '3'}, {"four", '4'},
|
||||
{"five", '5'}, {"six", '6'}, {"seven", '7'}, {"eight", '8'}, {"nine", '9'},
|
||||
{"colon", ':'}, {"semicolon", ';'},
|
||||
{"less", '<'}, {"equal", '='}, {"greater", '>'},
|
||||
{"question", '?'}, {"at", '@'},
|
||||
{"bracketleft", '['}, {"backslash", '\\'}, {"bracketright", ']'},
|
||||
{"asciicircum", '^'}, {"underscore", '_'}, {"grave", '`'},
|
||||
{"braceleft", '{'}, {"bar", '|'}, {"braceright", '}'},
|
||||
{"asciitilde", '~'},
|
||||
};
|
||||
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Public entry points
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Pure detection logic — I/O is delegated to callbacks so the same routine
|
||||
/// drives both the CLI flag (own SDL window + Console) and the in-app KMAP
|
||||
/// command (Micronona screen + main SDL event loop).
|
||||
///
|
||||
/// <paramref name="log"/> writes an informational line (no trailing newline expected).
|
||||
/// <paramref name="waitForKey"/> shows a prompt, waits for a keypress, returns
|
||||
/// the Linux keycode (KEY_*) or null on cancel.
|
||||
/// </summary>
|
||||
public static string? Detect(
|
||||
string keymapDir,
|
||||
Action<string> log,
|
||||
Func<string, int?> waitForKey)
|
||||
{
|
||||
var layouts = ParseKeymaps(keymapDir);
|
||||
if (layouts.Count == 0)
|
||||
{
|
||||
log("No keymaps available.");
|
||||
return null;
|
||||
}
|
||||
log("Keyboard detection");
|
||||
|
||||
var candidates = new HashSet<string>(layouts.Keys, StringComparer.Ordinal);
|
||||
// Positive proofs: how many rounds each candidate matched a keypress
|
||||
// positively (rather than just surviving as "X is unreachable here").
|
||||
// Used as a tiebreaker at the end so concrete matches beat ghosts.
|
||||
var proofs = candidates.ToDictionary(n => n, _ => 0, StringComparer.Ordinal);
|
||||
|
||||
while (candidates.Count > 1)
|
||||
{
|
||||
// Build per-candidate inverse map: char → keycodes that plain-produce it.
|
||||
var inverse = new Dictionary<string, Dictionary<char, HashSet<int>>>(StringComparer.Ordinal);
|
||||
foreach (string name in candidates)
|
||||
{
|
||||
var inv = new Dictionary<char, HashSet<int>>();
|
||||
foreach (var kv in layouts[name])
|
||||
{
|
||||
char ch = kv.Value;
|
||||
if (!inv.TryGetValue(ch, out var set))
|
||||
inv[ch] = set = new HashSet<int>();
|
||||
set.Add(kv.Key);
|
||||
}
|
||||
inverse[name] = inv;
|
||||
}
|
||||
|
||||
// Pick the target char that splits the candidate set most. The
|
||||
// target need not be reachable in every candidate — candidates
|
||||
// without it survive the round as "neutral", but candidates that
|
||||
// do have it get sorted into keycode-equivalence classes and all
|
||||
// but the user's class are eliminated.
|
||||
//
|
||||
// Two passes to avoid Shift-only prompts: first only consider
|
||||
// characters whose plain-row coverage spans at least half of the
|
||||
// remaining candidates (likely directly typeable on the user's
|
||||
// layout). Only if no such character discriminates do we fall back
|
||||
// to rarer chars like an apostrophe that may require Shift.
|
||||
char? bestTarget = null;
|
||||
int bestScore = 0;
|
||||
int[] minCoverages = { Math.Max(2, candidates.Count / 2), 2 };
|
||||
foreach (int minCoverage in minCoverages)
|
||||
{
|
||||
for (int c = 32; c <= 126; c++)
|
||||
{
|
||||
char ch = (char)c;
|
||||
var withX = candidates.Where(n => inverse[n].ContainsKey(ch)).ToList();
|
||||
if (withX.Count < minCoverage) continue;
|
||||
|
||||
var groups = withX
|
||||
.GroupBy(n => CanonicalKeycodeSet(inverse[n][ch]), StringComparer.Ordinal)
|
||||
.ToList();
|
||||
if (groups.Count < 2) continue;
|
||||
|
||||
// Worst case: user is in the largest keycode group. Everyone
|
||||
// else in withX gets eliminated.
|
||||
int largest = groups.Max(g => g.Count());
|
||||
int eliminated = withX.Count - largest;
|
||||
if (eliminated < 1) continue;
|
||||
int score = eliminated * 2 + withX.Count;
|
||||
if (score > bestScore)
|
||||
{
|
||||
bestScore = score;
|
||||
bestTarget = ch;
|
||||
}
|
||||
}
|
||||
if (bestTarget is not null) break;
|
||||
}
|
||||
|
||||
if (bestTarget is null) break; // can't discriminate further
|
||||
|
||||
int? pressed = waitForKey($"Press {Describe(bestTarget.Value)} ({candidates.Count} remaining)");
|
||||
if (pressed is null)
|
||||
{
|
||||
log("(cancelled)");
|
||||
return null;
|
||||
}
|
||||
|
||||
var survivors = new HashSet<string>(StringComparer.Ordinal);
|
||||
foreach (string name in candidates)
|
||||
{
|
||||
if (!inverse[name].TryGetValue(bestTarget.Value, out var kcs))
|
||||
{
|
||||
// Layout doesn't have this char plain — stay neutral.
|
||||
survivors.Add(name);
|
||||
}
|
||||
else if (kcs.Contains(pressed.Value))
|
||||
{
|
||||
survivors.Add(name);
|
||||
proofs[name]++;
|
||||
}
|
||||
// else: keycode mismatch among layouts that DO have X → eliminate.
|
||||
}
|
||||
|
||||
if (survivors.Count == 0)
|
||||
{
|
||||
log("No candidate is consistent with that keypress.");
|
||||
return null;
|
||||
}
|
||||
candidates = survivors;
|
||||
}
|
||||
|
||||
if (candidates.Count == 1) return candidates.First();
|
||||
|
||||
// Tiebreaker: candidates that positively matched the most keypresses win
|
||||
// over ghosts that only ever survived as neutrals. If still tied, prefer
|
||||
// the shortest name (base layout over variant), then alphabetical.
|
||||
int maxProof = candidates.Max(n => proofs[n]);
|
||||
var winners = candidates.Where(n => proofs[n] == maxProof).ToList();
|
||||
if (winners.Count == 1) return winners[0];
|
||||
|
||||
var picked = winners
|
||||
.OrderBy(n => n.Length)
|
||||
.ThenBy(n => n, StringComparer.Ordinal)
|
||||
.First();
|
||||
// Diagnostic — Console only; Micronona display stays clean.
|
||||
Console.Error.WriteLine(
|
||||
$"Narrowed to: {string.Join(", ", winners.OrderBy(n => n, StringComparer.Ordinal))} (picking '{picked}')");
|
||||
return picked;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// CLI entry: opens a small SDL window of its own (so the OS routes key
|
||||
/// events to it) and prints to Console.
|
||||
/// </summary>
|
||||
public static string? DetectInteractive(string keymapDir)
|
||||
{
|
||||
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
|
||||
{
|
||||
Console.Error.WriteLine($"SDL_Init failed: {SDL.SDL_GetError()}");
|
||||
return null;
|
||||
}
|
||||
|
||||
IntPtr window = SDL.SDL_CreateWindow(
|
||||
"Micronona — Keyboard Layout Detection",
|
||||
SDL.SDL_WINDOWPOS_CENTERED, SDL.SDL_WINDOWPOS_CENTERED,
|
||||
480, 120,
|
||||
SDL.SDL_WindowFlags.SDL_WINDOW_SHOWN);
|
||||
if (window == IntPtr.Zero)
|
||||
{
|
||||
Console.Error.WriteLine($"SDL_CreateWindow failed: {SDL.SDL_GetError()}");
|
||||
SDL.SDL_Quit();
|
||||
return null;
|
||||
}
|
||||
SDL.SDL_RaiseWindow(window);
|
||||
|
||||
try
|
||||
{
|
||||
return Detect(
|
||||
keymapDir,
|
||||
Console.WriteLine,
|
||||
prompt =>
|
||||
{
|
||||
Console.Write(prompt + ": ");
|
||||
int? kc = WaitForKey();
|
||||
Console.WriteLine(kc is null ? "(cancelled)" : $"(keycode {kc})");
|
||||
return kc;
|
||||
});
|
||||
}
|
||||
finally
|
||||
{
|
||||
SDL.SDL_DestroyWindow(window);
|
||||
SDL.SDL_Quit();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Best-effort `loadkeys <layout>` invocation. Used on the Pi target
|
||||
/// to apply the detected/stored layout system-wide; silently no-ops on
|
||||
/// dev machines where loadkeys is missing or we lack permissions.
|
||||
/// </summary>
|
||||
public static void ApplyLoadkeys(string layout)
|
||||
{
|
||||
try
|
||||
{
|
||||
var psi = new System.Diagnostics.ProcessStartInfo
|
||||
{
|
||||
FileName = "loadkeys",
|
||||
RedirectStandardOutput = true,
|
||||
RedirectStandardError = true,
|
||||
};
|
||||
psi.ArgumentList.Add(layout);
|
||||
var p = System.Diagnostics.Process.Start(psi);
|
||||
p?.WaitForExit();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// loadkeys missing or unprivileged — nothing to do on dev.
|
||||
}
|
||||
}
|
||||
|
||||
private static string CanonicalKeycodeSet(HashSet<int> set)
|
||||
{
|
||||
var arr = set.ToArray();
|
||||
Array.Sort(arr);
|
||||
return string.Join(",", arr);
|
||||
}
|
||||
|
||||
// Spell out characters that are visually confusable with letters/digits so the
|
||||
// user knows whether to press a digit row key or a letter key.
|
||||
private static string Describe(char c) => c switch
|
||||
{
|
||||
'0' => "'0' (digit zero)",
|
||||
'1' => "'1' (digit one)",
|
||||
'O' => "'O' (capital letter O)",
|
||||
'o' => "'o' (small letter o)",
|
||||
'l' => "'l' (small letter L)",
|
||||
'I' => "'I' (capital letter I)",
|
||||
_ => $"'{c}'",
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// Step 1: parse keymap files
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
public static Dictionary<string, Dictionary<int, char>> ParseKeymaps(string dir)
|
||||
{
|
||||
var result = new Dictionary<string, Dictionary<int, char>>(StringComparer.Ordinal);
|
||||
if (!Directory.Exists(dir)) return result;
|
||||
|
||||
// Target hardware is USB-HID on Raspberry Pi — only PC keycode layouts apply.
|
||||
string i386 = Path.Combine(dir, "i386");
|
||||
if (!Directory.Exists(i386)) return result;
|
||||
|
||||
// Layout files use .map / .map.gz (older) or .kmap / .kmap.gz (current kbd/console-data).
|
||||
// .inc / .inc.gz are include fragments — skipped as top-level layouts.
|
||||
string[] suffixes = { ".kmap.gz", ".kmap", ".map.gz", ".map" };
|
||||
|
||||
var searchPaths = new List<string> { Path.Combine(i386, "include") };
|
||||
|
||||
foreach (string path in Directory.EnumerateFiles(i386, "*", SearchOption.AllDirectories))
|
||||
{
|
||||
string file = Path.GetFileName(path);
|
||||
string? matched = null;
|
||||
foreach (var s in suffixes)
|
||||
if (file.EndsWith(s, StringComparison.OrdinalIgnoreCase)) { matched = s; break; }
|
||||
if (matched is null) continue;
|
||||
|
||||
// Files inside any include/ directory are fragments, not standalone layouts.
|
||||
string sep = Path.DirectorySeparatorChar.ToString();
|
||||
if (path.Contains($"{sep}include{sep}", StringComparison.Ordinal)) continue;
|
||||
|
||||
string layoutName = file[..^matched.Length];
|
||||
|
||||
try
|
||||
{
|
||||
var visited = new HashSet<string>(StringComparer.Ordinal);
|
||||
var map = new Dictionary<int, char>();
|
||||
ParseFile(path, map, visited, searchPaths);
|
||||
// Need a near-complete Latin alphabet for press-a-char detection
|
||||
// to have any chance of working. Layouts like ar/fa/lv-latin*
|
||||
// only override AltGr/shift positions and rely on the kernel's
|
||||
// compiled-in defkeymap for plain letters — we can't see that.
|
||||
if (HasUsableAlphabet(map))
|
||||
result[layoutName] = map;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.Error.WriteLine($" warning: failed to parse '{path}': {ex.Message}");
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
private static void ParseFile(
|
||||
string path,
|
||||
Dictionary<int, char> dict,
|
||||
HashSet<string> visited,
|
||||
List<string> searchPaths)
|
||||
{
|
||||
string canonical;
|
||||
try { canonical = Path.GetFullPath(path); }
|
||||
catch { canonical = path; }
|
||||
if (!visited.Add(canonical)) return; // cycle / already included
|
||||
|
||||
bool gz = path.EndsWith(".gz", StringComparison.OrdinalIgnoreCase);
|
||||
using var fs = File.OpenRead(path);
|
||||
using Stream s = gz ? new GZipStream(fs, CompressionMode.Decompress) : (Stream)fs;
|
||||
using var reader = new StreamReader(s);
|
||||
|
||||
string currentDir = Path.GetDirectoryName(path) ?? ".";
|
||||
|
||||
string? raw;
|
||||
while ((raw = reader.ReadLine()) != null)
|
||||
{
|
||||
int hash = raw.IndexOf('#');
|
||||
string line = (hash >= 0 ? raw[..hash] : raw).Trim();
|
||||
if (line.Length == 0) continue;
|
||||
|
||||
var inc = IncludeLine.Match(line);
|
||||
if (inc.Success)
|
||||
{
|
||||
// Included file's keycodes go in first; any later keycode line in the
|
||||
// parent file overrides them via the dict[kc] = ... assignment below.
|
||||
string? resolved = ResolveInclude(inc.Groups[1].Value, currentDir, searchPaths);
|
||||
if (resolved is not null)
|
||||
ParseFile(resolved, dict, visited, searchPaths);
|
||||
continue;
|
||||
}
|
||||
|
||||
var m = KeycodeLine.Match(line);
|
||||
if (!m.Success) continue;
|
||||
if (!int.TryParse(m.Groups[1].Value, out int kc)) continue;
|
||||
|
||||
string rhs = m.Groups[2].Value.Trim();
|
||||
// String macros like keycode N = "foo" — first token starts with " — skip.
|
||||
if (rhs.Length > 0 && rhs[0] == '"') continue;
|
||||
|
||||
string first = rhs.Split(new[] { ' ', '\t' }, 2, StringSplitOptions.RemoveEmptyEntries)[0];
|
||||
char? c = ResolveSymbol(first);
|
||||
if (c is null) continue;
|
||||
if (c < (char)32 || c > (char)126) continue;
|
||||
dict[kc] = c.Value;
|
||||
}
|
||||
}
|
||||
|
||||
private static string? ResolveInclude(string name, string currentDir, List<string> searchPaths)
|
||||
{
|
||||
// Always try a ".gz" sibling even when the name carries an explicit
|
||||
// extension — kbd installs the keymaps gzipped while the include
|
||||
// directives still spell them out bare (e.g. include "de-latin1.kmap"
|
||||
// resolves to de-latin1.kmap.gz on disk).
|
||||
string[] suffixes = HasKeymapExtension(name)
|
||||
? new[] { "", ".gz" }
|
||||
: new[] { ".inc", ".inc.gz", ".kmap", ".kmap.gz", ".map", ".map.gz", "" };
|
||||
|
||||
foreach (string d in new[] { currentDir }.Concat(searchPaths))
|
||||
{
|
||||
foreach (string ext in suffixes)
|
||||
{
|
||||
string full = Path.Combine(d, name + ext);
|
||||
if (File.Exists(full)) return full;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static bool HasUsableAlphabet(Dictionary<int, char> map)
|
||||
{
|
||||
var letters = new HashSet<char>();
|
||||
foreach (char c in map.Values)
|
||||
if (c >= 'a' && c <= 'z') letters.Add(c);
|
||||
return letters.Count >= 20;
|
||||
}
|
||||
|
||||
private static bool HasKeymapExtension(string name) =>
|
||||
name.EndsWith(".inc", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".inc.gz", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".kmap", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".kmap.gz", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".map", StringComparison.OrdinalIgnoreCase) ||
|
||||
name.EndsWith(".map.gz", StringComparison.OrdinalIgnoreCase);
|
||||
|
||||
private static char? ResolveSymbol(string sym)
|
||||
{
|
||||
if (string.IsNullOrEmpty(sym)) return null;
|
||||
if (sym[0] == '+') sym = sym[1..];
|
||||
if (sym.Length == 0) return null;
|
||||
|
||||
// Single-character literal (handles letters, digits, punctuation directly written).
|
||||
if (sym.Length == 1) return sym[0];
|
||||
|
||||
if (NamedSymbol.TryGetValue(sym, out char c)) return c;
|
||||
|
||||
// U+NNNN / +U+NNNN
|
||||
if ((sym.StartsWith("U+", StringComparison.OrdinalIgnoreCase)) &&
|
||||
int.TryParse(sym.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int u))
|
||||
return (char)u;
|
||||
|
||||
// 0xNN
|
||||
if (sym.StartsWith("0x", StringComparison.OrdinalIgnoreCase) &&
|
||||
int.TryParse(sym.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out int h))
|
||||
return (char)h;
|
||||
|
||||
// Decimal
|
||||
if (int.TryParse(sym, NumberStyles.Integer, CultureInfo.InvariantCulture, out int d))
|
||||
return (char)d;
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------------
|
||||
// SDL key-press input
|
||||
// ------------------------------------------------------------------------
|
||||
|
||||
private static int? WaitForKey()
|
||||
{
|
||||
// Drop any leftover events from the previous round (key-up, queued repeats,
|
||||
// window focus changes) so we start clean.
|
||||
while (SDL.SDL_PollEvent(out _) != 0) { }
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (SDL.SDL_WaitEvent(out SDL.SDL_Event ev) == 0) return null;
|
||||
if (ev.type == SDL.SDL_EventType.SDL_QUIT) return null;
|
||||
if (ev.type != SDL.SDL_EventType.SDL_KEYDOWN) continue;
|
||||
if (ev.key.repeat != 0) continue; // ignore auto-repeat
|
||||
if (ev.key.keysym.sym == SDL.SDL_Keycode.SDLK_ESCAPE) return null;
|
||||
|
||||
int? kc = SdlScancodeToLinuxKeycode(ev.key.keysym.scancode);
|
||||
if (kc is not null) return kc;
|
||||
// Unsupported physical key (e.g. F-key, arrow) — keep waiting.
|
||||
}
|
||||
}
|
||||
|
||||
// SDL_Scancode (USB-HID derived) → Linux input-event-codes.h keycode.
|
||||
// Covers only the keys that can produce printable ASCII; everything else
|
||||
// returns null and gets ignored upstream.
|
||||
public static int? SdlScancodeToLinuxKeycode(SDL.SDL_Scancode sc) => sc switch
|
||||
{
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_A => 30,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_B => 48,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_C => 46,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_D => 32,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_E => 18,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_F => 33,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_G => 34,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_H => 35,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_I => 23,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_J => 36,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_K => 37,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_L => 38,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_M => 50,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_N => 49,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_O => 24,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_P => 25,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_Q => 16,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_R => 19,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_S => 31,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_T => 20,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_U => 22,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_V => 47,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_W => 17,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_X => 45,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_Y => 21,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_Z => 44,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_1 => 2,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_2 => 3,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_3 => 4,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_4 => 5,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_5 => 6,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_6 => 7,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_7 => 8,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_8 => 9,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_9 => 10,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_0 => 11,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_MINUS => 12,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_EQUALS => 13,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_LEFTBRACKET => 26,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_RIGHTBRACKET => 27,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_BACKSLASH => 43,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_SEMICOLON => 39,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_APOSTROPHE => 40,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_GRAVE => 41,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_COMMA => 51,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_PERIOD => 52,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_SLASH => 53,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_SPACE => 57,
|
||||
SDL.SDL_Scancode.SDL_SCANCODE_NONUSBACKSLASH => 86, // KEY_102ND (DE: < > |)
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
120
MemoryModel.cs
120
MemoryModel.cs
|
|
@ -1,19 +1,20 @@
|
|||
/// <summary>
|
||||
/// Memory model for Micronona 256.
|
||||
/// Memory model for Micronona.
|
||||
///
|
||||
/// Address space as seen by the CPU and all high-level layers (Lua, TinyBasic, host):
|
||||
/// Address space as seen by the 6809 CPU and all high-level layers (BASIC, host):
|
||||
///
|
||||
/// 0x0000 – 0xDEFF Fixed RAM (56,832 bytes, general purpose)
|
||||
/// 0xDF00 – 0xDFFF Hardware registers (256 bytes, I/O)
|
||||
/// 0xE000 – 0xFFFF Bank window (8KB, switchable via REG_BANK)
|
||||
///
|
||||
/// Extended RAM: 256 banks × 8KB = 2MB total.
|
||||
/// Extended RAM: 25 banks × 8KB = 200KB total.
|
||||
/// The bank window at 0xE000 maps to one 8KB slice of extended RAM at a time.
|
||||
/// Bank switching is done by writing the desired bank number to REG_BANK (0xDF01).
|
||||
///
|
||||
/// Bank layout conventions:
|
||||
/// Bank 0 Text buffer (40×18×3 bytes: char, fg, bg) starts at offset 0
|
||||
/// Bank 255 Font bitmaps (256 glyphs × 8×10 bytes) at end of extended RAM
|
||||
/// Bank 0 Text buffer (40×18×3 bytes: char, fg, bg) starts at offset 0,
|
||||
/// or 320×180 RGB332 framebuffer when REG_MODE = 1 (graphics)
|
||||
/// Bank 24 Font bitmaps (256 glyphs × 8×10 bytes) — FontBankIndex = BankCount-1
|
||||
///
|
||||
/// The CPU and all high-level layers use Read(address)/Write(address) exclusively.
|
||||
/// Bank switching is transparent — callers set REG_BANK and then access 0xE000–0xFFFF.
|
||||
|
|
@ -42,10 +43,12 @@ public class MemoryModel
|
|||
public const int REG_BANK = 0x01; // Active bank in the 0xE000 window (0–255)
|
||||
public const int REG_KEY_CHAR = 0x02; // Next keypress character (0 = none)
|
||||
public const int REG_KEY_FLAGS = 0x03; // Modifier flags (Shift, Ctrl, …)
|
||||
public const int REG_TIMER = 0x04; // Auto-incrementing timer; saturates at 255; resets on read
|
||||
public const int REG_TIMER = 0x04; // Frame counter: incremented once per frame (60 Hz), saturates at 255, resets to 0 on read
|
||||
public const int REG_VSYNC = 0x05; // VSync flag; set by host each frame
|
||||
public const int REG_CURSOR_COL = 0x06; // Text cursor position horizontally
|
||||
public const int REG_CURSOR_ROW = 0x07; // Text cursor position vertically
|
||||
public const int REG_RANDOM = 0x08; // Read-only: returns a new random byte on every read
|
||||
public const int REG_SOUND = 0x10; // Write-only: SN76489 PSG data port
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Text mode layout (Bank 0, starting at offset 0)
|
||||
|
|
@ -58,9 +61,7 @@ public class MemoryModel
|
|||
public const int TextBankIndex = 0; // Text buffer lives in bank 0
|
||||
public const int TextBufferSize = TextCols * TextRows * TextCellSize; // 2160 bytes
|
||||
|
||||
// Default terminal colors (RGB332)
|
||||
public const byte DefaultFg = 0x1C; // Bright green: R=0, G=224, B=0
|
||||
public const byte DefaultBg = 0x08; // Dark green: R=0, G=64, B=0
|
||||
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Font layout (Bank 255, starting at offset 0)
|
||||
|
|
@ -85,6 +86,17 @@ public class MemoryModel
|
|||
/// </summary>
|
||||
public readonly object Lock = new();
|
||||
|
||||
/// <summary>
|
||||
/// Invoked whenever the CPU (or any writer) stores to REG_SOUND. The host
|
||||
/// wires this to the SN76489 emulator. May be called from multiple threads.
|
||||
/// </summary>
|
||||
public Action<byte>? OnSoundWrite;
|
||||
|
||||
// VSync: semaphore signals each frame; _totalFrames counts them for elapsed measurement.
|
||||
private readonly SemaphoreSlim _vsyncSem = new(0, 1);
|
||||
private long _totalFrames = 0;
|
||||
private long _lastVsyncFrame = 0;
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Internal storage
|
||||
// -------------------------------------------------------------------------
|
||||
|
|
@ -102,7 +114,7 @@ public class MemoryModel
|
|||
// Constructor
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
public MemoryModel()
|
||||
public MemoryModel(byte defaultFg, byte defaultBg)
|
||||
{
|
||||
// Bank 0 active by default
|
||||
_io[REG_BANK] = TextBankIndex;
|
||||
|
|
@ -112,8 +124,8 @@ public class MemoryModel
|
|||
for (int i = 0; i < TextCols * TextRows; i++)
|
||||
{
|
||||
_extendedRam[textBase + i * TextCellSize + 0] = 0x20; // Space
|
||||
_extendedRam[textBase + i * TextCellSize + 1] = DefaultFg;
|
||||
_extendedRam[textBase + i * TextCellSize + 2] = DefaultBg;
|
||||
_extendedRam[textBase + i * TextCellSize + 1] = defaultFg;
|
||||
_extendedRam[textBase + i * TextCellSize + 2] = defaultBg;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -127,14 +139,11 @@ public class MemoryModel
|
|||
/// </summary>
|
||||
public byte Read(ushort address)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
if (address >= IoBase && address < IoBase + IoSize)
|
||||
return ReadIo(address - IoBase);
|
||||
if (address >= BankWindowBase)
|
||||
return ReadBank(address - BankWindowBase);
|
||||
return _fixedRam[address];
|
||||
}
|
||||
if (address >= IoBase && address < IoBase + IoSize)
|
||||
return ReadIo(address - IoBase);
|
||||
if (address >= BankWindowBase)
|
||||
return ReadBank(address - BankWindowBase);
|
||||
return _fixedRam[address];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -142,15 +151,12 @@ public class MemoryModel
|
|||
/// </summary>
|
||||
public void Write(ushort address, byte value)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
if (address >= IoBase && address < IoBase + IoSize)
|
||||
WriteIo(address - IoBase, value);
|
||||
else if (address >= BankWindowBase)
|
||||
WriteBank(address - BankWindowBase, value);
|
||||
else
|
||||
_fixedRam[address] = value;
|
||||
}
|
||||
if (address >= IoBase && address < IoBase + IoSize)
|
||||
WriteIo(address - IoBase, value);
|
||||
else if (address >= BankWindowBase)
|
||||
WriteBank(address - BankWindowBase, value);
|
||||
else
|
||||
_fixedRam[address] = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -189,7 +195,7 @@ public class MemoryModel
|
|||
/// </summary>
|
||||
public byte ReadFlat(int address)
|
||||
{
|
||||
lock (Lock) return _extendedRam[address];
|
||||
return _extendedRam[address];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
|
@ -205,6 +211,14 @@ public class MemoryModel
|
|||
}
|
||||
}
|
||||
|
||||
public void FillFlat(int address, int length, byte value)
|
||||
{
|
||||
lock (Lock)
|
||||
{
|
||||
_extendedRam.AsSpan(address, length).Fill(value);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Return a Span over one full bank in extended RAM.
|
||||
/// Useful for bulk operations like SDL texture uploads.
|
||||
|
|
@ -216,24 +230,66 @@ public class MemoryModel
|
|||
// Internal helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/// <summary>
|
||||
/// Called once per rendered frame by the host. Increments REG_TIMER, saturating at 255.
|
||||
/// </summary>
|
||||
public void TickFrame()
|
||||
{
|
||||
if (_io[REG_TIMER] < 255)
|
||||
_io[REG_TIMER]++;
|
||||
}
|
||||
|
||||
private byte ReadIo(int reg)
|
||||
{
|
||||
if (reg == REG_TIMER)
|
||||
{
|
||||
// Timer resets to 0 on read (after returning current value)
|
||||
// Returns frames elapsed since last read, then resets to 0
|
||||
byte val = _io[REG_TIMER];
|
||||
_io[REG_TIMER] = 0;
|
||||
return val;
|
||||
}
|
||||
if (reg == REG_RANDOM)
|
||||
return (byte)Random.Shared.Next(256);
|
||||
return _io[reg];
|
||||
}
|
||||
|
||||
private void WriteIo(int reg, byte value)
|
||||
{
|
||||
// All register writes are simple stores; bank switch takes effect immediately
|
||||
if (reg == REG_VSYNC)
|
||||
{
|
||||
WaitVSync();
|
||||
return;
|
||||
}
|
||||
if (reg == REG_SOUND)
|
||||
{
|
||||
_io[reg] = value;
|
||||
OnSoundWrite?.Invoke(value);
|
||||
return;
|
||||
}
|
||||
// All other register writes are simple stores.
|
||||
_io[reg] = value;
|
||||
}
|
||||
|
||||
private void WaitVSync()
|
||||
{
|
||||
_vsyncSem.Wait();
|
||||
long now = Volatile.Read(ref _totalFrames);
|
||||
int elapsed = (int)(now - _lastVsyncFrame);
|
||||
_lastVsyncFrame = now;
|
||||
_io[REG_TIMER] = (byte)Math.Min(elapsed, 255);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called by the SDL render loop after SDL_RenderPresent.
|
||||
/// Increments the frame counter and unblocks any thread waiting on REG_VSYNC.
|
||||
/// </summary>
|
||||
public void SignalVSync()
|
||||
{
|
||||
Interlocked.Increment(ref _totalFrames);
|
||||
if (_vsyncSem.CurrentCount == 0)
|
||||
_vsyncSem.Release();
|
||||
}
|
||||
|
||||
private byte ReadBank(int offset)
|
||||
{
|
||||
int bank = _io[REG_BANK];
|
||||
|
|
|
|||
|
|
@ -11,7 +11,8 @@
|
|||
/// Expands RGB332 to RGB24 for each pixel.
|
||||
///
|
||||
/// Graphics mode:
|
||||
/// Not yet implemented.
|
||||
/// Reads 320×180 bytes from extended RAM starting at bank 0 offset 0.
|
||||
/// Each byte is one pixel in RGB332 format, expanded to RGB24.
|
||||
/// </summary>
|
||||
public class MicrononaRenderer
|
||||
{
|
||||
|
|
@ -103,7 +104,13 @@ public class MicrononaRenderer
|
|||
|
||||
private void RenderGraphics()
|
||||
{
|
||||
// TODO: read framebuffer from extended RAM, expand RGB332 → RGB24
|
||||
int pixelBase = MemoryModel.TextBankIndex * MemoryModel.BankSize;
|
||||
|
||||
for (int i = 0; i < 320 * 180; i++)
|
||||
{
|
||||
byte color332 = _mem.ReadFlat(pixelBase + i);
|
||||
Expand332(_rgb24, i * 3, color332);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
|
|
|
|||
234
Program.cs
234
Program.cs
|
|
@ -2,6 +2,23 @@
|
|||
using Tomlyn;
|
||||
using Tomlyn.Model;
|
||||
|
||||
if (args.Length > 0 && args[0] == "--detect-keyboard")
|
||||
{
|
||||
string keymapDir = args.Length > 1 ? args[1] : "/usr/share/keymaps";
|
||||
string? layout = KeyboardLayoutDetector.DetectInteractive(keymapDir);
|
||||
if (layout is null) { Console.WriteLine("(undecidable)"); return 0; }
|
||||
|
||||
string? stickPath = DiskManager.FindMicrononaMount();
|
||||
if (stickPath is null)
|
||||
Console.WriteLine($"{layout} (no Micronona stick mounted — not saved)");
|
||||
else
|
||||
{
|
||||
DiskManager.SaveKeyboardLayout(stickPath, layout);
|
||||
Console.WriteLine($"{layout} (saved to {Path.Combine(stickPath, DiskManager.MarkerFile)})");
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
const int ScreenWidth = 320;
|
||||
const int ScreenHeight = 180;
|
||||
const string Title = "Micronona";
|
||||
|
|
@ -27,7 +44,8 @@ else
|
|||
Console.WriteLine("Running in developer mode");
|
||||
}
|
||||
|
||||
var mem = new MemoryModel();
|
||||
var mem = new MemoryModel(ConsoleHelper.DefaultFg, ConsoleHelper.DefaultBg);
|
||||
var console = new ConsoleHelper(mem);
|
||||
var diskManager = new DiskManager();
|
||||
var micrononaRenderer = new MicrononaRenderer(mem);
|
||||
|
||||
|
|
@ -63,6 +81,12 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 36 * MemoryMode
|
|||
0x00, 0x08, 0x3E, 0x68, 0x3C, 0x16, 0x7C, 0x10, 0x00, 0x00
|
||||
);
|
||||
|
||||
// '
|
||||
mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 39 * MemoryModel.FontGlyphHeight,
|
||||
// 0x00, 0x18, 0x3E, 0x68, 0x3C, 0x16, 0x7C, 0x18, 0x00, 0x00
|
||||
0x00, 0x18, 0x18, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
|
||||
);
|
||||
|
||||
// (
|
||||
mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 40 * MemoryModel.FontGlyphHeight,
|
||||
// 0x00, 0x08, 0x18, 0x30, 0x20, 0x20, 0x30, 0x18, 0x08, 0x00
|
||||
|
|
@ -325,6 +349,11 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 90 * MemoryMode
|
|||
0x00, 0x7E, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x7E, 0x00, 0x00
|
||||
);
|
||||
|
||||
// ^
|
||||
mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 94 * MemoryModel.FontGlyphHeight,
|
||||
0x00, 0x18, 0x3C, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
|
||||
);
|
||||
|
||||
// _
|
||||
mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 95 * MemoryModel.FontGlyphHeight,
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00
|
||||
|
|
@ -360,6 +389,11 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 102 * MemoryMod
|
|||
0x00, 0x0C, 0x18, 0x18, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x00
|
||||
);
|
||||
|
||||
// g
|
||||
mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 103 * MemoryModel.FontGlyphHeight,
|
||||
0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x3E, 0x06, 0x3C, 0x00
|
||||
);
|
||||
|
||||
// h
|
||||
mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 104 * MemoryModel.FontGlyphHeight,
|
||||
0x00, 0x60, 0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x00, 0x00
|
||||
|
|
@ -445,11 +479,16 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 121 * MemoryMod
|
|||
0x00, 0x00, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x30, 0x00
|
||||
);
|
||||
|
||||
// z
|
||||
mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 122 * MemoryModel.FontGlyphHeight,
|
||||
0x00, 0x00, 0x7E, 0x0C, 0x38,0x1C, 0x30, 0x7E, 0x00, 0x00
|
||||
);
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// SDL init
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO) < 0)
|
||||
if (SDL.SDL_Init(SDL.SDL_INIT_VIDEO | SDL.SDL_INIT_AUDIO) < 0)
|
||||
{
|
||||
Console.Error.WriteLine($"SDL_Init failed: {SDL.SDL_GetError()}");
|
||||
return 1;
|
||||
|
|
@ -498,6 +537,37 @@ var texture = SDL.SDL_CreateTexture(
|
|||
// RGB24 output buffer for SDL (expanded from memory each frame)
|
||||
byte[] rgb24 = new byte[ScreenWidth * ScreenHeight * 3];
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// SN76489 PSG — one-byte write port at REG_SOUND ($DF10)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
var audioDesired = new SDL.SDL_AudioSpec
|
||||
{
|
||||
freq = 44100,
|
||||
format = SDL.AUDIO_S16SYS,
|
||||
channels = 1,
|
||||
samples = 1024,
|
||||
};
|
||||
|
||||
// ppy.SDL2-CS cannot marshal a null device name to SDL_OpenAudioDevice, and
|
||||
// passing "" is treated as a literal device name. Use the legacy SDL_OpenAudio
|
||||
// which always targets the default device (device ID 1).
|
||||
int audioOpenResult = SDL.SDL_OpenAudio(ref audioDesired, out var audioObtained);
|
||||
uint audioDev = audioOpenResult == 0 ? 1u : 0u;
|
||||
if (audioDev == 0)
|
||||
Console.Error.WriteLine($"SDL_OpenAudio failed: {SDL.SDL_GetError()} (continuing without sound)");
|
||||
|
||||
int audioSampleRate = audioDev != 0 ? audioObtained.freq : 44100;
|
||||
var sn = new Sn76489(audioSampleRate);
|
||||
mem.OnSoundWrite = sn.Write;
|
||||
|
||||
int samplesPerFrame = audioSampleRate / 60;
|
||||
int audioTarget = samplesPerFrame * 3; // keep ~3 frames (~50 ms) queued
|
||||
short[] audioBuf = new short[audioTarget]; // room for a full top-up in one call
|
||||
|
||||
if (audioDev != 0)
|
||||
SDL.SDL_PauseAudio(0);
|
||||
|
||||
|
||||
var top = "*** MICRONONA 256 ***";
|
||||
var tab = (byte)((MemoryModel.TextCols - top.Length) / 2);
|
||||
|
|
@ -509,13 +579,50 @@ consoleHelper.WriteText("MICRONONA");
|
|||
|
||||
consoleHelper.SetCursor(5, 1);
|
||||
|
||||
SDL.SDL_SetWindowFullscreen(window, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP);
|
||||
//SDL.SDL_SetWindowFullscreen(window, (uint)SDL.SDL_WindowFlags.SDL_WINDOW_FULLSCREEN_DESKTOP);
|
||||
|
||||
|
||||
var scrollLock = new ScrollLockLed();
|
||||
scrollLock.Set(false);
|
||||
|
||||
diskManager.OnMicrononaStickInserted += path => { Console.WriteLine($"Ready: {path}"); scrollLock.Set(true); };
|
||||
// Start from a known baseline so the subsequent loadkeys switch (from marker
|
||||
// or KMAP result) is visibly distinct on the Pi target.
|
||||
KeyboardLayoutDetector.ApplyLoadkeys("us");
|
||||
|
||||
bool firstStickInsert = true;
|
||||
diskManager.OnMicrononaStickInserted += path =>
|
||||
{
|
||||
Console.WriteLine($"Ready: {path}");
|
||||
scrollLock.Set(true);
|
||||
|
||||
// Only on the first stick after app start: apply the stored layout via
|
||||
// loadkeys, or auto-run KMAP if the marker has no [keyboard] entry yet.
|
||||
// Later inserts stay quiet so they can't interrupt a running BASIC session.
|
||||
if (!firstStickInsert) return;
|
||||
firstStickInsert = false;
|
||||
|
||||
string markerPath = Path.Combine(path, DiskManager.MarkerFile);
|
||||
try
|
||||
{
|
||||
TomlTable model = Toml.ToModel(File.ReadAllText(markerPath));
|
||||
if (model.TryGetValue("keyboard", out object? kbObj)
|
||||
&& kbObj is TomlTable kb
|
||||
&& kb.TryGetValue("layout", out object? layoutObj)
|
||||
&& layoutObj is string layout
|
||||
&& !string.IsNullOrWhiteSpace(layout))
|
||||
{
|
||||
KeyboardLayoutDetector.ApplyLoadkeys(layout);
|
||||
}
|
||||
else
|
||||
{
|
||||
inputInterpreter.InterpretInput("KMAP");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine($"[keyboard] could not read marker: {ex.Message}");
|
||||
}
|
||||
};
|
||||
diskManager.OnStickRemoved += () => { Console.WriteLine("Stick removed"); scrollLock.Set(false); };
|
||||
diskManager.Start();
|
||||
cpu.StartThread();
|
||||
|
|
@ -538,6 +645,7 @@ if (runFile != null)
|
|||
Console.Error.WriteLine($"--run: no Micronona stick mounted");
|
||||
inputInterpreter.StopThread();
|
||||
cpu.StopThread();
|
||||
if (audioDev != 0) SDL.SDL_CloseAudio();
|
||||
SDL.SDL_DestroyTexture(texture);
|
||||
SDL.SDL_DestroyRenderer(renderer);
|
||||
SDL.SDL_DestroyWindow(window);
|
||||
|
|
@ -551,6 +659,7 @@ if (runFile != null)
|
|||
Console.Error.WriteLine($"--run: file not found on stick: {runFile}");
|
||||
inputInterpreter.StopThread();
|
||||
cpu.StopThread();
|
||||
if (audioDev != 0) SDL.SDL_CloseAudio();
|
||||
SDL.SDL_DestroyTexture(texture);
|
||||
SDL.SDL_DestroyRenderer(renderer);
|
||||
SDL.SDL_DestroyWindow(window);
|
||||
|
|
@ -580,6 +689,34 @@ while (running)
|
|||
|
||||
if (e.type == SDL.SDL_EventType.SDL_KEYDOWN)
|
||||
{
|
||||
// KMAP captures key events directly: ESC cancels, mapped scancodes
|
||||
// get submitted; everything else is ignored until KMAP releases.
|
||||
if (inputInterpreter.IsWaitingForKmapKey)
|
||||
{
|
||||
if (e.key.keysym.sym == SDL.SDL_Keycode.SDLK_ESCAPE)
|
||||
{
|
||||
inputInterpreter.SubmitKmapKey(null);
|
||||
}
|
||||
else
|
||||
{
|
||||
int? kc = KeyboardLayoutDetector.SdlScancodeToLinuxKeycode(e.key.keysym.scancode);
|
||||
if (kc is not null)
|
||||
{
|
||||
int sym = (int)e.key.keysym.sym;
|
||||
char display = (sym >= 32 && sym <= 126) ? (char)sym : '\0';
|
||||
inputInterpreter.SubmitKmapKey(kc.Value, display);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inputInterpreter.IsEditorActive)
|
||||
{
|
||||
EditorAction? act = MapSdlToEditorAction(e.key);
|
||||
if (act.HasValue) inputInterpreter.EditorAction(act.Value);
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (e.key.keysym.sym)
|
||||
{
|
||||
case SDL.SDL_Keycode.SDLK_ESCAPE:
|
||||
|
|
@ -592,7 +729,8 @@ while (running)
|
|||
break;
|
||||
}
|
||||
|
||||
if (!inputInterpreter.IsRunning || inputInterpreter.IsWaitingForInput)
|
||||
if (!inputInterpreter.IsKmapActive
|
||||
&& (!inputInterpreter.IsRunning || inputInterpreter.IsWaitingForInput))
|
||||
{
|
||||
switch (e.key.keysym.sym)
|
||||
{
|
||||
|
|
@ -613,21 +751,33 @@ while (running)
|
|||
}
|
||||
}
|
||||
}
|
||||
if (e.type == SDL.SDL_EventType.SDL_TEXTINPUT && (!inputInterpreter.IsRunning || inputInterpreter.IsWaitingForInput))
|
||||
if (e.type == SDL.SDL_EventType.SDL_TEXTINPUT)
|
||||
{
|
||||
unsafe
|
||||
if (inputInterpreter.IsEditorActive)
|
||||
{
|
||||
byte ascii = e.text.text[0];
|
||||
if (ascii >= 32 && ascii < 127)
|
||||
consoleHelper.WriteText(((char)ascii).ToString());
|
||||
unsafe
|
||||
{
|
||||
byte ascii = e.text.text[0];
|
||||
if (ascii >= 32 && ascii < 127)
|
||||
inputInterpreter.EditorChar((char)ascii);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!inputInterpreter.IsKmapActive
|
||||
&& (!inputInterpreter.IsRunning || inputInterpreter.IsWaitingForInput))
|
||||
{
|
||||
unsafe
|
||||
{
|
||||
byte ascii = e.text.text[0];
|
||||
if (ascii >= 32 && ascii < 127)
|
||||
consoleHelper.WriteText(((char)ascii).ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
scrollLock.Refresh();
|
||||
|
||||
// --- VSync flag setzen (wird später vom 6809-Emulator gelesen) ---
|
||||
mem.Write(MemoryModel.IoBase + MemoryModel.REG_VSYNC, 1);
|
||||
|
||||
// --- Render ---
|
||||
var span = micrononaRenderer.Render();
|
||||
unsafe
|
||||
|
|
@ -641,19 +791,77 @@ while (running)
|
|||
SDL.SDL_RenderClear(renderer);
|
||||
SDL.SDL_RenderCopy(renderer, texture, IntPtr.Zero, IntPtr.Zero);
|
||||
SDL.SDL_RenderPresent(renderer);
|
||||
mem.SignalVSync();
|
||||
|
||||
mem.TickFrame();
|
||||
|
||||
if (audioDev != 0)
|
||||
{
|
||||
// Top up the audio queue to ~3 frames; absorbs vsync jitter without
|
||||
// noticeable latency.
|
||||
uint queuedBytes = SDL.SDL_GetQueuedAudioSize(audioDev);
|
||||
int queuedSamples = (int)(queuedBytes / sizeof(short));
|
||||
int need = audioTarget - queuedSamples;
|
||||
if (need > 0)
|
||||
{
|
||||
if (need > audioBuf.Length) need = audioBuf.Length;
|
||||
sn.GenerateSamples(audioBuf.AsSpan(0, need));
|
||||
unsafe
|
||||
{
|
||||
fixed (short* p = audioBuf)
|
||||
{
|
||||
SDL.SDL_QueueAudio(audioDev, (IntPtr)p, (uint)(need * sizeof(short)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (runStartTick > 0 && Environment.TickCount64 - runStartTick >= 5000)
|
||||
running = false;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
static EditorAction? MapSdlToEditorAction(SDL.SDL_KeyboardEvent ke)
|
||||
{
|
||||
bool ctrl = (ke.keysym.mod & SDL.SDL_Keymod.KMOD_CTRL) != 0;
|
||||
return ke.keysym.sym switch
|
||||
{
|
||||
SDL.SDL_Keycode.SDLK_LEFT => EditorAction.Left,
|
||||
SDL.SDL_Keycode.SDLK_RIGHT => EditorAction.Right,
|
||||
SDL.SDL_Keycode.SDLK_UP => EditorAction.Up,
|
||||
SDL.SDL_Keycode.SDLK_DOWN => EditorAction.Down,
|
||||
SDL.SDL_Keycode.SDLK_HOME => EditorAction.Home,
|
||||
SDL.SDL_Keycode.SDLK_END => EditorAction.End,
|
||||
SDL.SDL_Keycode.SDLK_PAGEUP => EditorAction.PageUp,
|
||||
SDL.SDL_Keycode.SDLK_PAGEDOWN => EditorAction.PageDown,
|
||||
SDL.SDL_Keycode.SDLK_BACKSPACE => EditorAction.Backspace,
|
||||
SDL.SDL_Keycode.SDLK_DELETE => EditorAction.Delete,
|
||||
SDL.SDL_Keycode.SDLK_RETURN => EditorAction.Enter,
|
||||
SDL.SDL_Keycode.SDLK_KP_ENTER => EditorAction.Enter,
|
||||
SDL.SDL_Keycode.SDLK_ESCAPE => EditorAction.Quit,
|
||||
SDL.SDL_Keycode.SDLK_s when ctrl => EditorAction.Save,
|
||||
SDL.SDL_Keycode.SDLK_z when ctrl => EditorAction.Undo,
|
||||
SDL.SDL_Keycode.SDLK_k when ctrl => EditorAction.CutLine,
|
||||
SDL.SDL_Keycode.SDLK_u when ctrl => EditorAction.PasteLine,
|
||||
SDL.SDL_Keycode.SDLK_q when ctrl => EditorAction.Quit,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Cleanup
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
inputInterpreter.StopThread();
|
||||
cpu.StopThread();
|
||||
if (audioDev != 0)
|
||||
{
|
||||
SDL.SDL_PauseAudio(1);
|
||||
SDL.SDL_CloseAudio();
|
||||
}
|
||||
SDL.SDL_DestroyTexture(texture);
|
||||
SDL.SDL_DestroyRenderer(renderer);
|
||||
SDL.SDL_DestroyWindow(window);
|
||||
|
|
|
|||
197
Sn76489.cs
Normal file
197
Sn76489.cs
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
/// <summary>
|
||||
/// Texas Instruments SN76489 programmable sound generator.
|
||||
///
|
||||
/// Three square-wave tone channels plus one noise channel, mono output.
|
||||
/// Clock: 3.579545 MHz (NTSC). Internal /16 divider yields a ~223.7 kHz
|
||||
/// counter clock. Tone frequency = ChipClock / (32 * N) for 10-bit reload N.
|
||||
///
|
||||
/// Write protocol (single 8-bit port at REG_SOUND):
|
||||
/// LATCH/DATA byte (MSB=1): 1 R2 R1 R0 D3 D2 D1 D0
|
||||
/// R2..R0 selects register, D3..D0 is low 4 bits of payload.
|
||||
/// DATA byte (MSB=0): 0 x D5 D4 D3 D2 D1 D0
|
||||
/// Upper 6 bits of 10-bit tone reload; appended to the last latched
|
||||
/// tone register. Ignored for attenuation (kept for completeness).
|
||||
///
|
||||
/// Register map (R2 R1 R0):
|
||||
/// 000 Tone 1 freq 001 Tone 1 attenuation
|
||||
/// 010 Tone 2 freq 011 Tone 2 attenuation
|
||||
/// 100 Tone 3 freq 101 Tone 3 attenuation
|
||||
/// 110 Noise control 111 Noise attenuation
|
||||
///
|
||||
/// Attenuation: 0 = loudest, 15 = silent, 2 dB per step.
|
||||
/// Noise control bits: NF2 = white (1) / periodic (0); NF1 NF0 = shift rate
|
||||
/// 00 N/512, 01 N/1024, 10 N/2048, 11 = tone 3 rate.
|
||||
/// </summary>
|
||||
public class Sn76489
|
||||
{
|
||||
public const int ChipClock = 3579545;
|
||||
public const int ToneDivider = 16;
|
||||
public const double CounterClock = ChipClock / (double)ToneDivider;
|
||||
|
||||
private const int NoiseLfsrInit = 0x4000;
|
||||
private const int NoiseLfsrMask = 0x7FFF;
|
||||
|
||||
private readonly int[] _toneReload = new int[3];
|
||||
private readonly int[] _toneCounter = new int[3] { 1, 1, 1 };
|
||||
private readonly int[] _toneOut = new int[3];
|
||||
|
||||
private readonly int[] _attenuation = new int[4] { 15, 15, 15, 15 };
|
||||
|
||||
private int _noiseCtrl;
|
||||
private int _noiseCounter = 1;
|
||||
private int _noiseShift = NoiseLfsrInit;
|
||||
private int _noiseOut;
|
||||
|
||||
private int _latchedReg;
|
||||
|
||||
private readonly double _cyclesPerSample;
|
||||
private double _cyclesAccum;
|
||||
|
||||
private static readonly short[] VolumeTable = BuildVolumeTable();
|
||||
|
||||
private readonly object _lock = new();
|
||||
|
||||
public Sn76489(int sampleRate)
|
||||
{
|
||||
_cyclesPerSample = CounterClock / sampleRate;
|
||||
}
|
||||
|
||||
private static short[] BuildVolumeTable()
|
||||
{
|
||||
// Per-channel peak of 6000 keeps four channels summed within int16 range.
|
||||
var t = new short[16];
|
||||
for (int i = 0; i < 15; i++)
|
||||
t[i] = (short)(6000.0 * System.Math.Pow(10.0, -i * 2.0 / 20.0));
|
||||
t[15] = 0;
|
||||
return t;
|
||||
}
|
||||
|
||||
public void Write(byte value)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if ((value & 0x80) != 0)
|
||||
{
|
||||
int reg = (value >> 4) & 0x07;
|
||||
int data4 = value & 0x0F;
|
||||
_latchedReg = reg;
|
||||
ApplyLatch(reg, data4);
|
||||
}
|
||||
else
|
||||
{
|
||||
int data6 = value & 0x3F;
|
||||
ApplyContinuation(_latchedReg, data6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyLatch(int reg, int data4)
|
||||
{
|
||||
int channel = reg >> 1;
|
||||
bool isAtt = (reg & 1) != 0;
|
||||
|
||||
if (isAtt)
|
||||
{
|
||||
_attenuation[channel] = data4;
|
||||
}
|
||||
else if (channel < 3)
|
||||
{
|
||||
_toneReload[channel] = (_toneReload[channel] & ~0x0F) | data4;
|
||||
}
|
||||
else
|
||||
{
|
||||
_noiseCtrl = data4 & 0x07;
|
||||
_noiseShift = NoiseLfsrInit;
|
||||
}
|
||||
}
|
||||
|
||||
private void ApplyContinuation(int reg, int data6)
|
||||
{
|
||||
int channel = reg >> 1;
|
||||
bool isAtt = (reg & 1) != 0;
|
||||
|
||||
if (isAtt)
|
||||
{
|
||||
_attenuation[channel] = data6 & 0x0F;
|
||||
}
|
||||
else if (channel < 3)
|
||||
{
|
||||
_toneReload[channel] = (_toneReload[channel] & 0x0F) | ((data6 & 0x3F) << 4);
|
||||
}
|
||||
else
|
||||
{
|
||||
_noiseCtrl = data6 & 0x07;
|
||||
_noiseShift = NoiseLfsrInit;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Fill a mono 16-bit PCM buffer with freshly generated samples.</summary>
|
||||
public void GenerateSamples(System.Span<short> output)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
for (int s = 0; s < output.Length; s++)
|
||||
{
|
||||
_cyclesAccum += _cyclesPerSample;
|
||||
int cycles = (int)_cyclesAccum;
|
||||
_cyclesAccum -= cycles;
|
||||
if (cycles > 0) RunCycles(cycles);
|
||||
output[s] = MixSample();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RunCycles(int cycles)
|
||||
{
|
||||
for (int c = 0; c < cycles; c++)
|
||||
{
|
||||
for (int ch = 0; ch < 3; ch++)
|
||||
{
|
||||
if (--_toneCounter[ch] <= 0)
|
||||
{
|
||||
int reload = _toneReload[ch];
|
||||
// Reload of 0 is treated as 1 — at that rate the channel emits
|
||||
// DC-ish, which is correct "silent carrier" behaviour on hardware.
|
||||
_toneCounter[ch] = reload == 0 ? 1 : reload;
|
||||
_toneOut[ch] ^= 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (--_noiseCounter <= 0)
|
||||
{
|
||||
int rate = _noiseCtrl & 0x03;
|
||||
int reload = rate switch
|
||||
{
|
||||
0 => 32,
|
||||
1 => 64,
|
||||
2 => 128,
|
||||
_ => _toneReload[2] == 0 ? 1 : _toneReload[2],
|
||||
};
|
||||
_noiseCounter = reload;
|
||||
|
||||
int fb = (_noiseCtrl & 0x04) != 0
|
||||
? ((_noiseShift & 1) ^ ((_noiseShift >> 3) & 1)) & 1
|
||||
: _noiseShift & 1;
|
||||
|
||||
_noiseShift = ((_noiseShift >> 1) | (fb << 14)) & NoiseLfsrMask;
|
||||
_noiseOut = _noiseShift & 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private short MixSample()
|
||||
{
|
||||
int sum = 0;
|
||||
for (int ch = 0; ch < 3; ch++)
|
||||
{
|
||||
int v = VolumeTable[_attenuation[ch]];
|
||||
sum += _toneOut[ch] != 0 ? v : -v;
|
||||
}
|
||||
int nv = VolumeTable[_attenuation[3]];
|
||||
sum += _noiseOut != 0 ? nv : -nv;
|
||||
|
||||
if (sum > short.MaxValue) sum = short.MaxValue;
|
||||
if (sum < short.MinValue) sum = short.MinValue;
|
||||
return (short)sum;
|
||||
}
|
||||
}
|
||||
433
TextEditor.cs
Normal file
433
TextEditor.cs
Normal file
|
|
@ -0,0 +1,433 @@
|
|||
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);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue