diff --git a/ConsoleHelper.cs b/ConsoleHelper.cs index 8fffbc1..059eb9d 100644 --- a/ConsoleHelper.cs +++ b/ConsoleHelper.cs @@ -7,57 +7,66 @@ public class ConsoleHelper _mem = mem; } - public void Delete() -{ - int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL); - int row = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW); - - int textBase = MemoryModel.TextBankIndex * MemoryModel.BankSize; - int rowEnd = (row * MemoryModel.TextCols + MemoryModel.TextCols - 1) * MemoryModel.TextCellSize; - int startOffset = (row * MemoryModel.TextCols + col) * MemoryModel.TextCellSize; - - for (int i = startOffset; i < rowEnd; i += MemoryModel.TextCellSize) + static byte Rgb332Mid(byte a, byte b) { - _mem.WriteFlat(textBase + i, - _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize), - _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 1), - _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 2)); + int r = ((a >> 5) + (b >> 5)) / 2; + int g = (((a >> 2) & 0x07) + ((b >> 2) & 0x07)) / 2; + int bl = ((a & 0x03) + (b & 0x03)) / 2; + return (byte)((r << 5) | (g << 2) | bl); } - _mem.WriteFlat(textBase + rowEnd, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg); -} + public void Delete() + { + int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL); + int row = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW); + + int textBase = MemoryModel.TextBankIndex * MemoryModel.BankSize; + int rowEnd = (row * MemoryModel.TextCols + MemoryModel.TextCols - 1) * MemoryModel.TextCellSize; + int startOffset = (row * MemoryModel.TextCols + col) * MemoryModel.TextCellSize; + + for (int i = startOffset; i < rowEnd; i += MemoryModel.TextCellSize) + { + _mem.WriteFlat(textBase + i, + _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize), + _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 1), + _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 2)); + } + + _mem.WriteFlat(textBase + rowEnd, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg); + } public void Backspace() -{ - int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL); - int row = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW); - if (col == 0 && row == 0) return; - 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; - - for (int i = startOffset; i < rowEnd; i += MemoryModel.TextCellSize) { - _mem.WriteFlat(textBase + i, - _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize), - _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 1), - _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 2)); + int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL); + int row = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW); + if (col == 0 && row == 0) return; + 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; + + for (int i = startOffset; i < rowEnd; i += MemoryModel.TextCellSize) + { + _mem.WriteFlat(textBase + i, + _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize), + _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 1), + _mem.ReadFlat(textBase + i + MemoryModel.TextCellSize + 2)); + } + + // Letztes Zeichen der Zeile löschen + _mem.WriteFlat(textBase + rowEnd, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg); + + _mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL, (byte)col); + _mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW, (byte)row); } - // Letztes Zeichen der Zeile löschen - _mem.WriteFlat(textBase + rowEnd, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg); - - _mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL, (byte)col); - _mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW, (byte)row); -} - public void NewLine() { + ReadLine(); // Optional: Aktuelle Zeile lesen und verarbeiten int row = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW); if (row + 1 >= MemoryModel.TextRows) { @@ -101,6 +110,44 @@ public class ConsoleHelper _mem.WriteFlat(textBase + lastRow + col * MemoryModel.TextCellSize, 0x20, MemoryModel.DefaultFg, MemoryModel.DefaultBg); } } + public string ReadLine() + { + int col = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL); + int row = _mem.Read(MemoryModel.IoBase + MemoryModel.REG_CURSOR_ROW); + + 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) + { + int firstCell = startRow * MemoryModel.TextCols * MemoryModel.TextCellSize; + if (_mem.ReadFlat(textBase + firstCell) == 31) + startRow--; + else + break; + } + + var sb = new System.Text.StringBuilder(); + + for (int r = startRow; r <= row; r++) + { + int endCol = (r == row) ? col : MemoryModel.TextCols; + for (int c = 0; c < endCol; c++) + { + int offset = (r * MemoryModel.TextCols + c) * MemoryModel.TextCellSize; + byte ch = _mem.ReadFlat(textBase + offset); + if (ch == 31) continue; // Umbruch-Marker überspringen + sb.Append((char)ch); + } + } + + string result = sb.ToString(); + Console.WriteLine($"[ConsoleHelper] Read: -{result}-"); + return result; + } + public void SetCursor(byte x, byte y) { _mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL, x); @@ -118,11 +165,19 @@ public class ConsoleHelper var ascii = (byte)c; _mem.WriteFlat(MemoryModel.TextBankIndex * MemoryModel.BankSize + offset, ascii, MemoryModel.DefaultFg, MemoryModel.DefaultBg); 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); + offset += MemoryModel.TextCellSize; + } while (offset >= MemoryModel.TextCellSize * MemoryModel.TextCols * MemoryModel.TextRows) { ScrollUp(); offset -= (MemoryModel.TextCellSize * MemoryModel.TextCols); } + } offset /= MemoryModel.TextCellSize; _mem.Write(MemoryModel.IoBase + MemoryModel.REG_CURSOR_COL, (byte)(offset % MemoryModel.TextCols)); diff --git a/DiskManager.cs b/DiskManager.cs new file mode 100644 index 0000000..88c07fe --- /dev/null +++ b/DiskManager.cs @@ -0,0 +1,337 @@ +using System.Net.Sockets; +using System.Runtime.InteropServices; +using System.Text; + +/// +/// Monitors block devices via kernel netlink and manages the Micronona USB stick. +/// +/// Events: +/// OnMicrononaStickInserted – stick is ready (initialized if necessary), includes mount path +/// OnStickRemoved – stick was removed +/// +/// Empty sticks are initialized automatically with a new .micronona file. +/// Only one stick is tracked at a time. +/// +public class DiskManager : IDisposable +{ + // ------------------------------------------------------------------------- + // Events + // ------------------------------------------------------------------------- + + public event Action? OnMicrononaStickInserted; + public event Action? OnStickRemoved; + + // ------------------------------------------------------------------------- + // State + // ------------------------------------------------------------------------- + + private string? _mountedDevice; // e.g. "/dev/sda1" + private string? _mountPath; // e.g. "/mnt/micronona" + + private const string MarkerFile = ".micronona"; + + // ------------------------------------------------------------------------- + // Netlink socket + // ------------------------------------------------------------------------- + + private const int AF_NETLINK = 16; + private const int NETLINK_KOBJECT_UEVENT = 15; + + [StructLayout(LayoutKind.Sequential)] + private struct SockaddrNl + { + public ushort nl_family; + public ushort nl_pad; + public uint nl_pid; + public uint nl_groups; + } + + [DllImport("libc", SetLastError = true)] + private static extern int socket(int domain, int type, int protocol); + + [DllImport("libc", SetLastError = true)] + private static extern int bind(int sockfd, ref SockaddrNl addr, int addrlen); + + [DllImport("libc", SetLastError = true)] + private static extern int recv(int sockfd, byte[] buf, int len, int flags); + + [DllImport("libc", SetLastError = true)] + private static extern int close(int fd); + + private int _fd = -1; + private CancellationTokenSource? _cts; + + // ------------------------------------------------------------------------- + // Lifecycle + // ------------------------------------------------------------------------- + + public void Start() + { + _fd = socket(AF_NETLINK, (int)SocketType.Raw, NETLINK_KOBJECT_UEVENT); + if (_fd < 0) + throw new InvalidOperationException("Failed to open netlink socket."); + + var addr = new SockaddrNl + { + nl_family = AF_NETLINK, + nl_groups = 1 + }; + + if (bind(_fd, ref addr, Marshal.SizeOf()) < 0) + throw new InvalidOperationException("Failed to bind netlink socket."); + + _cts = new CancellationTokenSource(); + Task.Run(() => WatchLoop(_cts.Token)); + + // Scan for sticks that were already inserted at startup + foreach (var entry in Directory.EnumerateDirectories("/sys/class/block/")) + { + var name = Path.GetFileName(entry); + if (name.StartsWith("mmcblk")) continue; + if (!name[^1..].All(char.IsDigit)) continue; + + // Only consider removable devices (USB sticks) + var parent = name.TrimEnd('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); + var removablePath = $"/sys/class/block/{parent}/removable"; + if (!File.Exists(removablePath)) continue; + if (File.ReadAllText(removablePath).Trim() != "1") continue; + + HandleAdd("/dev/" + name); + if (_mountedDevice != null) break; + } + + Console.WriteLine("[DiskManager] Started."); + } + + private void WatchLoop(CancellationToken ct) + { + var buffer = new byte[4096]; + + while (!ct.IsCancellationRequested) + { + int len = recv(_fd, buffer, buffer.Length, 0); + if (len <= 0) continue; + + var message = Encoding.UTF8.GetString(buffer, 0, len); + ParseUevent(message); + } + } + + // ------------------------------------------------------------------------- + // Uevent parsing + // ------------------------------------------------------------------------- + + private void ParseUevent(string message) + { + var parts = message.Split('\0', StringSplitOptions.RemoveEmptyEntries); + + string? action = null; + string? devtype = null; + string? devname = null; + + foreach (var part in parts) + { + if (part.StartsWith("ACTION=")) action = part[7..]; + if (part.StartsWith("DEVTYPE=")) devtype = part[8..]; + if (part.StartsWith("DEVNAME=")) devname = part[8..]; + } + + // Only care about partitions (or disks without partitions) + if (devtype != "partition" && devtype != "disk") return; + if (devname == null) return; + + // Ignore internal SD card + if (devname.StartsWith("mmcblk")) return; + + var devPath = "/dev/" + devname; + + if (action == "add") + HandleAdd(devPath); + else if (action == "remove") + HandleRemove(devPath); + } + + // ------------------------------------------------------------------------- + // Add / Remove + // ------------------------------------------------------------------------- + + private void HandleAdd(string devPath) + { + if (_mountedDevice != null) return; // already tracking a stick + if (!devPath[^1..].All(char.IsDigit)) return; + + Console.WriteLine($"[DiskManager] Device added: {devPath}"); + + string? mountPath = null; + for (int i = 0; i < 5; i++) + { + Thread.Sleep(300); + mountPath = UdisksMount(devPath); + if (mountPath != null) break; + } + + if (mountPath == null) + { + Console.WriteLine($"[DiskManager] Mount failed for {devPath}, ignoring."); + return; + } + + _mountedDevice = devPath; + _mountPath = mountPath; + + var markerPath = Path.Combine(mountPath, MarkerFile); + if (!File.Exists(markerPath)) + { + bool isEmpty; + try { isEmpty = !Directory.EnumerateFileSystemEntries(mountPath).Any(); } + catch (UnauthorizedAccessException) { isEmpty = false; } + if (!isEmpty) + { + Console.WriteLine($"[DiskManager] Not a Micronona stick, ignoring: {mountPath}"); + UdisksUnmount(devPath); + _mountedDevice = null; + _mountPath = null; + return; + } + + Console.WriteLine($"[DiskManager] Initializing new stick at {mountPath}"); + InitializeStick(markerPath); + } + + Console.WriteLine($"[DiskManager] Micronona stick at {mountPath}"); + OnMicrononaStickInserted?.Invoke(mountPath); + } + + private void HandleRemove(string devPath) + { + if (_mountedDevice != devPath) return; + + Console.WriteLine($"[DiskManager] Device removed: {devPath}"); + + UdisksUnmount(devPath); + + _mountedDevice = null; + _mountPath = null; + + OnStickRemoved?.Invoke(); + } + + // ------------------------------------------------------------------------- + // Stick initialization + // ------------------------------------------------------------------------- + + private static void InitializeStick(string markerPath) + { + var model = new Tomlyn.Model.TomlTable + { + ["drive"] = new Tomlyn.Model.TomlTable + { + ["id"] = Guid.NewGuid().ToString() + } + }; + File.WriteAllText(markerPath, Tomlyn.Toml.FromModel(model)); + Console.WriteLine($"[DiskManager] Written {markerPath}"); + } + + // ------------------------------------------------------------------------- + // Mount helpers (udisksctl — no root required) + // ------------------------------------------------------------------------- + + private static string? UdisksMount(string devPath) +{ + var psi = new System.Diagnostics.ProcessStartInfo + { + FileName = "udisksctl", + Arguments = $"mount -b {devPath} --no-user-interaction", + RedirectStandardOutput = true, + RedirectStandardError = true + }; + var p = System.Diagnostics.Process.Start(psi)!; + var output = p.StandardOutput.ReadToEnd(); + var error = p.StandardError.ReadToEnd(); + p.WaitForExit(); + + // Erfolgreich gemountet + var idx = output.IndexOf(" at "); + if (idx >= 0) return output[(idx + 4)..].Trim().TrimEnd('.'); + + // Bereits gemountet — Pfad aus Fehlermeldung lesen + var alreadyIdx = error.IndexOf("already mounted at `"); + if (alreadyIdx >= 0) + { + var start = alreadyIdx + 20; + var end = error.IndexOf("'", start); + if (end > start) return error[start..end]; + } + + Console.WriteLine($"[DiskManager] udisksctl: {error.Trim()}"); + return null; +} + + private static void UdisksUnmount(string devPath) + { + var psi = new System.Diagnostics.ProcessStartInfo + { + FileName = "udisksctl", + RedirectStandardError = true + }; + psi.ArgumentList.Add("unmount"); + psi.ArgumentList.Add("-b"); + psi.ArgumentList.Add(devPath); + psi.ArgumentList.Add("--no-user-interaction"); + var p = System.Diagnostics.Process.Start(psi)!; + p.WaitForExit(); + } + + // ------------------------------------------------------------------------- + // Public accessors + // ------------------------------------------------------------------------- + + /// + /// Current mount path, or null if no stick is present. + /// + public string? MountPath => _mountPath; + + /// + /// Lists files on the inserted stick, sorted by last-edited descending. + /// Excludes the marker file, directories, files with names longer than 12 + /// characters, and files whose names contain non-elementary ASCII characters. + /// Returns (null, files) on success, or (error message, null) on failure. + /// + public (string? Error, IReadOnlyList? Files) Dir() + { + if (_mountPath == null) + return ("no disk inserted", null); + + var files = new DirectoryInfo(_mountPath) + .GetFiles() + .Where(f => f.Name != MarkerFile + && f.Name.Length <= 12 + && f.Name.All(IsElementaryAscii)) + .OrderByDescending(f => f.LastWriteTime) + .ToList(); + + if (files.Count == 0) + return ("disk empty", null); + + return (null, files); + } + + private static bool IsElementaryAscii(char c) + => (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || + (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '_'; + + // ------------------------------------------------------------------------- + // IDisposable + // ------------------------------------------------------------------------- + + public void Dispose() + { + _cts?.Cancel(); + if (_fd >= 0) + { + close(_fd); + _fd = -1; + } + } +} diff --git a/InputInterpreter.cs b/InputInterpreter.cs new file mode 100644 index 0000000..6dd6175 --- /dev/null +++ b/InputInterpreter.cs @@ -0,0 +1,650 @@ +using System.Text.RegularExpressions; + +internal class InputInterpreter +{ + private static readonly Regex LineNumberPattern = new(@"^\s*(\d+)\s+(.*)$"); + + private readonly MemoryModel mem; + private readonly ConsoleHelper consoleHelper; + private readonly DiskManager diskManager; + private readonly SortedDictionary _program = new(); + private readonly Dictionary _variables = new(); + + private List _lines = new(); + private int _programCounter; + private bool _running; + private bool _waitingForInput; + private char _inputVariable; + private bool _skipIncrement; + private readonly Stack _callStack = new(); + + public InputInterpreter(MemoryModel mem, ConsoleHelper consoleHelper, DiskManager diskManager) + { + this.mem = mem; + this.consoleHelper = consoleHelper; + this.diskManager = diskManager; + } + + public bool IsRunning => _running; + public bool IsWaitingForInput => _waitingForInput; + + public void SubmitInput(string line) + { + if (!_waitingForInput) return; + if (int.TryParse(line.Trim(), out int val)) + { + _variables[_inputVariable] = val; + _waitingForInput = false; + _programCounter++; + } + else + { + consoleHelper.WriteText("?"); + consoleHelper.NewLine(); + } + } + + public void Stop() + { + _running = false; + consoleHelper.NewLine(); + consoleHelper.WriteText("BREAK"); + consoleHelper.NewLine(); + } + + public void Tick() + { + if (!_running || _waitingForInput) return; + + if (_programCounter >= _lines.Count) + { + _running = false; + return; + } + + int lineNr = _lines[_programCounter]; + int? gotoTarget = null; + _skipIncrement = false; + ExecuteStatement(_program[lineNr], ref gotoTarget); + + if (_waitingForInput || _skipIncrement) return; + + if (gotoTarget.HasValue) + { + int idx = _lines.IndexOf(gotoTarget.Value); + if (idx == -1) + { + consoleHelper.WriteText($"?UNDEF'D LINE {gotoTarget.Value}"); + consoleHelper.NewLine(); + _running = false; + } + else + { + _programCounter = idx; + } + } + else + { + _programCounter++; + } + } + + public void InterpretInput(string input) + { + input = input.Trim(); + if (string.IsNullOrEmpty(input)) return; + + var match = LineNumberPattern.Match(input); + if (match.Success) + { + int lineNumber = int.Parse(match.Groups[1].Value); + string statement = match.Groups[2].Value.Trim(); + + if (string.IsNullOrWhiteSpace(statement)) + _program.Remove(lineNumber); + else + _program[lineNumber] = statement; + } + else + { + Execute(input); + } + } + + // Direktmodus: RUN, LIST, DIR und alle Statements + private void Execute(string input) + { + Console.WriteLine("input: " + input.ToLowerInvariant()); + var cmd = input.ToLowerInvariant(); + + if (cmd == "run") + { + _lines = _program.Keys.ToList(); + _programCounter = 0; + _callStack.Clear(); + _running = true; + return; + } + + if (cmd == "new") + { + _program.Clear(); + _lines.Clear(); + _callStack.Clear(); + _running = false; + return; + } + + if (cmd == "list") + { + if (_program.Count == 0) + { + consoleHelper.WriteText("(empty)"); + consoleHelper.NewLine(); + } + else + { + foreach (var (lineNumber, statement) in _program) + { + consoleHelper.WriteText($"{lineNumber} {statement}"); + consoleHelper.NewLine(); + } + } + return; + } + + if (cmd.StartsWith("save ") || cmd.StartsWith("save\"")) + { + ExecuteSave(input.Substring("save".Length).Trim()); + return; + } + + if (cmd.StartsWith("load ") || cmd.StartsWith("load\"")) + { + ExecuteLoad(input.Substring("load".Length).Trim()); + return; + } + + if (cmd == "dir") + { + var (error, files) = diskManager.Dir(); + if (error != null) + { + consoleHelper.WriteText($"Error: {error}"); + consoleHelper.NewLine(); + } + else if (files is not null) + { + foreach (var file in files) + { + consoleHelper.WriteText(file.Name); + consoleHelper.NewLine(); + } + } + return; + } + + int? unused = null; + ExecuteStatement(input, ref unused); + } + + // Ausführung eines einzelnen Statements + private void ExecuteStatement(string input, ref int? gotoTarget) + { + var cmd = input.ToLowerInvariant(); + + if (cmd.StartsWith("print ") || cmd == "print") + { + ExecutePrint(input.Substring("print".Length).Trim()); + return; + } + + if (cmd == "end") + { + _running = false; + return; + } + + if (cmd.StartsWith("if ")) + { + ExecuteIf(input.Substring("if ".Length).Trim(), ref gotoTarget); + return; + } + + if (cmd.StartsWith("input ")) + { + string arg = input.Substring("input ".Length).Trim(); + if (arg.Length != 1 || !char.IsUpper(arg[0])) + { + SyntaxError(); + return; + } + _inputVariable = arg[0]; + _waitingForInput = true; + consoleHelper.WriteText("?"); + consoleHelper.NewLine(); + return; + } + + if (cmd.StartsWith("let ")) + { + ExecuteLet(input.Substring("let ".Length).Trim()); + return; + } + + if (cmd.StartsWith("rem")) return; + + if (cmd.StartsWith("poke ")) + { + ExecutePoke(input.Substring("poke ".Length).Trim()); + return; + } + + if (cmd.StartsWith("pokex ")) + { + ExecutePokeX(input.Substring("pokex ".Length).Trim()); + return; + } + + if (cmd.StartsWith("gosub ")) + { + string arg = cmd.Substring("gosub ".Length).Trim(); + if (!int.TryParse(arg, out int target)) { SyntaxError(); return; } + int idx = _lines.IndexOf(target); + if (idx == -1) + { + consoleHelper.WriteText($"?UNDEF'D LINE {target}"); + consoleHelper.NewLine(); + _running = false; + return; + } + _callStack.Push(_programCounter); + gotoTarget = target; + return; + } + + if (cmd == "return") + { + if (_callStack.Count == 0) + { + consoleHelper.WriteText("?RETURN WITHOUT GOSUB"); + consoleHelper.NewLine(); + _running = false; + return; + } + _programCounter = _callStack.Pop() + 1; + _skipIncrement = true; + return; + } + + if (cmd.StartsWith("goto ")) + { + string arg = cmd.Substring("goto ".Length).Trim(); + if (int.TryParse(arg, out int target)) + gotoTarget = target; + else + SyntaxError(); + return; + } + + SyntaxError(); + } + + private void ExecuteIf(string args, ref int? gotoTarget) + { + int thenIdx = args.ToUpperInvariant().IndexOf(" THEN "); + if (thenIdx == -1) { SyntaxError(); return; } + + string condition = args.Substring(0, thenIdx).Trim(); + string stmt = args.Substring(thenIdx + " THEN ".Length).Trim(); + + if (!TryEvaluateCondition(condition, out bool result)) { SyntaxError(); return; } + + if (result) + ExecuteStatement(stmt, ref gotoTarget); + } + + private static readonly string[] ComparisonOps = { "<=", ">=", "<>", "<", ">", "=" }; + private static readonly Random Rng = new(); + + private bool TryEvaluateCondition(string condition, out bool result) + { + result = false; + foreach (var op in ComparisonOps) + { + int idx = condition.IndexOf(op); + if (idx == -1) continue; + + string leftStr = condition.Substring(0, idx).Trim(); + string rightStr = condition.Substring(idx + op.Length).Trim(); + + if (!TryEvaluate(leftStr, out int left)) return false; + if (!TryEvaluate(rightStr, out int right)) return false; + + result = op switch + { + "=" => left == right, + "<" => left < right, + ">" => left > right, + "<=" => left <= right, + ">=" => left >= right, + "<>" => left != right, + _ => false + }; + return true; + } + return false; + } + + private void ExecuteLet(string args) + { + if (args.Length < 1 || !char.IsUpper(args[0])) + { + SyntaxError(); + return; + } + char varName = args[0]; + var rest = args.Substring(1).TrimStart(); + if (!rest.StartsWith("=")) + { + SyntaxError(); + return; + } + string exprStr = rest.Substring(1).Trim(); + if (!TryEvaluate(exprStr, out int value)) + { + SyntaxError(); + return; + } + _variables[varName] = value; + } + + private bool TryEvaluate(string expr, out int result) + { + try + { + int pos = 0; + result = ParseExpr(expr, ref pos); + SkipSpaces(expr, ref pos); + return pos == expr.Length; + } + catch (DivideByZeroException) + { + consoleHelper.WriteText("?DIVISION BY ZERO"); + consoleHelper.NewLine(); + _running = false; + result = 0; + return true; // Fehlermeldung bereits ausgegeben, kein ?SYNTAX ERROR + } + catch + { + result = 0; + return false; + } + } + + private int ParseExpr(string s, ref int pos) + { + int left = ParseTerm(s, ref pos); + while (true) + { + SkipSpaces(s, ref pos); + if (pos < s.Length && s[pos] == '+') { pos++; left += ParseTerm(s, ref pos); } + else if (pos < s.Length && s[pos] == '-') { pos++; left -= ParseTerm(s, ref pos); } + else break; + } + return left; + } + + private int ParseTerm(string s, ref int pos) + { + int left = ParseFactor(s, ref pos); + while (true) + { + SkipSpaces(s, ref pos); + if (pos < s.Length && s[pos] == '*') + { + pos++; left *= ParseFactor(s, ref pos); + } + else if (pos < s.Length && s[pos] == '/') + { + pos++; + int divisor = ParseFactor(s, ref pos); + if (divisor == 0) throw new DivideByZeroException(); + left /= divisor; + } + else if (pos + 3 <= s.Length + && s.Substring(pos, 3).ToUpperInvariant() == "MOD" + && (pos + 3 >= s.Length || !char.IsLetterOrDigit(s[pos + 3]))) + { + pos += 3; + int divisor = ParseFactor(s, ref pos); + if (divisor == 0) throw new DivideByZeroException(); + left %= divisor; + } + else break; + } + return left; + } + + private int ParseFactor(string s, ref int pos) + { + SkipSpaces(s, ref pos); + if (pos >= s.Length) throw new InvalidOperationException(); + + if (s[pos] == '(') + { + pos++; + int val = ParseExpr(s, ref pos); + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); + pos++; + return val; + } + + if (s[pos] == '-') + { + pos++; + return -ParseFactor(s, ref pos); + } + + if (pos + 3 <= s.Length && s.Substring(pos, 3).ToUpperInvariant() == "RND") + { + pos += 3; + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); + pos++; + int n = ParseExpr(s, ref pos); + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); + pos++; + if (n <= 0) throw new InvalidOperationException(); + return Rng.Next(n); + } + + if (pos + 5 <= s.Length && s.Substring(pos, 5).ToUpperInvariant() == "PEEKX") + { + pos += 5; + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); + pos++; + int bank = ParseExpr(s, ref pos); + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != ',') throw new InvalidOperationException(); + pos++; + int addr = ParseExpr(s, ref pos); + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); + pos++; + if (bank < 0 || bank >= MemoryModel.BankCount || addr < 0 || addr >= MemoryModel.BankSize) + throw new InvalidOperationException(); + return mem.ReadFlat(bank * MemoryModel.BankSize + addr); + } + + if (pos + 4 <= s.Length && s.Substring(pos, 4).ToUpperInvariant() == "PEEK") + { + pos += 4; + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != '(') throw new InvalidOperationException(); + pos++; + int addr = ParseExpr(s, ref pos); + SkipSpaces(s, ref pos); + if (pos >= s.Length || s[pos] != ')') throw new InvalidOperationException(); + pos++; + if (addr < 0 || addr > 0xFFFF) throw new InvalidOperationException(); + return mem.Read((ushort)addr); + } + + if (char.IsUpper(s[pos])) + { + char v = s[pos++]; + if (!_variables.TryGetValue(v, out int val)) throw new InvalidOperationException(); + return val; + } + + if (s[pos] == '$') + { + pos++; + int start = pos; + while (pos < s.Length && Uri.IsHexDigit(s[pos])) pos++; + if (pos == start) throw new InvalidOperationException(); + return Convert.ToInt32(s.Substring(start, pos - start), 16); + } + + if (char.IsDigit(s[pos])) + { + int start = pos; + while (pos < s.Length && char.IsDigit(s[pos])) pos++; + return int.Parse(s.Substring(start, pos - start)); + } + + throw new InvalidOperationException(); + } + + private static void SkipSpaces(string s, ref int pos) + { + while (pos < s.Length && s[pos] == ' ') pos++; + } + + private void ExecutePoke(string args) + { + int comma = args.IndexOf(','); + if (comma == -1) { SyntaxError(); return; } + if (!TryEvaluate(args.Substring(0, comma).Trim(), out int addr)) { SyntaxError(); return; } + if (!TryEvaluate(args.Substring(comma + 1).Trim(), out int value)) { SyntaxError(); return; } + if (addr < 0 || addr > 0xFFFF || value < 0 || value > 255) + { + consoleHelper.WriteText("?RANGE ERROR"); + consoleHelper.NewLine(); + return; + } + mem.Write((ushort)addr, (byte)value); + } + + private void ExecutePokeX(string args) + { + var parts = args.Split(','); + if (parts.Length != 3) { SyntaxError(); return; } + if (!TryEvaluate(parts[0].Trim(), out int bank)) { SyntaxError(); return; } + if (!TryEvaluate(parts[1].Trim(), out int addr)) { SyntaxError(); return; } + if (!TryEvaluate(parts[2].Trim(), out int value)) { SyntaxError(); return; } + if (bank < 0 || bank >= MemoryModel.BankCount || + addr < 0 || addr >= MemoryModel.BankSize || + value < 0 || value > 255) + { + consoleHelper.WriteText("?RANGE ERROR"); + consoleHelper.NewLine(); + return; + } + mem.WriteFlat(bank * MemoryModel.BankSize + addr, (byte)value); + } + + private string? ParseFilename(string args) + { + string name = args.Trim('"', ' ').ToUpperInvariant(); + if (name.Length == 0 || name.Length > 12 || name.Contains('/') || name.Contains('\\')) + return null; + return name; + } + + private void ExecuteSave(string args) + { + string? name = ParseFilename(args); + if (name == null) { SyntaxError(); return; } + + if (diskManager.MountPath == null) + { + consoleHelper.WriteText("?NO DISK"); + consoleHelper.NewLine(); + return; + } + + var path = Path.Combine(diskManager.MountPath, name); + File.WriteAllLines(path, _program.Select(kv => $"{kv.Key} {kv.Value}")); + } + + private void ExecuteLoad(string args) + { + string? name = ParseFilename(args); + if (name == null) { SyntaxError(); return; } + + _program.Clear(); + _lines.Clear(); + _callStack.Clear(); + _running = false; + + 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; + } + + foreach (var line in File.ReadAllLines(path)) + InterpretInput(line); + } + + private void SyntaxError() + { + consoleHelper.WriteText("?SYNTAX ERROR"); + consoleHelper.NewLine(); + } + + private void ExecutePrint(string args) + { + if (args.StartsWith("\"")) + { + int last = args.LastIndexOf('"'); + if (last == 0) + { + SyntaxError(); + return; + } + consoleHelper.WriteText(args.Substring(1, last - 1)); + consoleHelper.NewLine(); + return; + } + + if (args.Length == 1 && char.IsUpper(args[0])) + { + if (!_variables.TryGetValue(args[0], out int val)) + { + SyntaxError(); + return; + } + consoleHelper.WriteText(val.ToString()); + consoleHelper.NewLine(); + return; + } + + SyntaxError(); + } +} diff --git a/Mironona.csproj b/Mironona.csproj index e54b34b..3c8e9f8 100644 --- a/Mironona.csproj +++ b/Mironona.csproj @@ -10,6 +10,7 @@ + diff --git a/Program.cs b/Program.cs index 64c2f7f..52ae77e 100644 --- a/Program.cs +++ b/Program.cs @@ -1,4 +1,6 @@ using SDL2; +using Tomlyn; +using Tomlyn.Model; const int ScreenWidth = 320; const int ScreenHeight = 180; @@ -9,21 +11,86 @@ const int Scale = 3; // Memory // ------------------------------------------------------------------------- +bool isRawConsole = string.IsNullOrEmpty(Environment.GetEnvironmentVariable("DISPLAY")) + && string.IsNullOrEmpty(Environment.GetEnvironmentVariable("WAYLAND_DISPLAY")); + +if (isRawConsole) +{ + Console.CancelKeyPress += (s, e) => e.Cancel = true; +} +else +{ + Console.WriteLine("Running in developer mode"); +} + var mem = new MemoryModel(); +var diskManager = new DiskManager(); var micrononaRenderer = new MicrononaRenderer(mem); var consoleHelper = new ConsoleHelper(mem); +var inputInterpreter = new InputInterpreter(mem, consoleHelper, diskManager); + +// Unit Separator (ASCII 31) für Eingabeaufforderung +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 31 * MemoryModel.FontGlyphHeight, + 0x00, 0x60, 0x70, 0x78, 0x7E, 0x7E, 0x78, 0x70, 0x60, 0x00 +); + +// ! +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 33 * MemoryModel.FontGlyphHeight, + 0x00, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x18, 0x00, 0x00 +); + + // " mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 34 * MemoryModel.FontGlyphHeight, 0x00, 0x36, 0x66, 0x6C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 ); +// $ +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 36 * MemoryModel.FontGlyphHeight, + // 0x00, 0x18, 0x3E, 0x68, 0x3C, 0x16, 0x7C, 0x18, 0x00, 0x00 + 0x00, 0x08, 0x3E, 0x68, 0x3C, 0x16, 0x7C, 0x10, 0x00, 0x00 +); + +// ( +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 40 * MemoryModel.FontGlyphHeight, + // 0x00, 0x08, 0x18, 0x30, 0x20, 0x20, 0x30, 0x18, 0x08, 0x00 + //0x00,0x0C,0x08, 0x18,0x10,0x10,0x10,0x18,0x08, 0x0C,0x00 + 0x00,0x0C,0x18,0x30,0x30,0x30,0x30,0x18,0x0C,0x00 +); + +// ) +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 41 * MemoryModel.FontGlyphHeight, + 0x00,0x30,0x18,0x0C,0x0C,0x0C,0x0C,0x18,0x30,0x00 +); + // * mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 42 * MemoryModel.FontGlyphHeight, 0x00, 0x00, 0x34, 0x18, 0x7E, 0x18, 0x2C, 0x00, 0x00, 0x00 ); +// + +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 43 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x18, 0x18, 0x7E, 0x18, 0x18, 0x00, 0x00, 0x00 +); + +// , +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 44 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30, 0x00 +); + +// - +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 45 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x00, 0x00, 0x7E, 0x00, 0x00, 0x00, 0x00, 0x00 +); + +// . +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 46 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00 +); + + // 0 mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 48 * MemoryModel.FontGlyphHeight, // 0x00, 0x18, 0x3C, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00, 0x00 @@ -78,11 +145,41 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 57 * MemoryMode 0x00, 0x3C, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x3C, 0x00, 0x00 ); +// : +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 58 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00 +); + +// < +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 60 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x00, 0x00, 0x00 +); + + +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 61 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x00, 0x3C, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x00 +); + +// > +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 62 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x30, 0x18, 0x0C, 0x18, 0x30, 0x00, 0x00, 0x00 +); + +// ? +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 63 * MemoryModel.FontGlyphHeight, + 0x00, 0x3C, 0x66, 0x06, 0x0C, 0x18, 0x00, 0x18, 0x00, 0x00 +); + // A mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 65 * MemoryModel.FontGlyphHeight, 0x00, 0x18, 0x3C, 0x66, 0x7E, 0x66, 0x66, 0x66, 0x00, 0x00 ); +// B +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 66 * MemoryModel.FontGlyphHeight, + 0x00, 0x7C, 0x66, 0x66, 0x7C, 0x66, 0x66, 0x7C, 0x00, 0x00 +); + // C mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 67 * MemoryModel.FontGlyphHeight, // 0x00, 0x3A, 0x66, 0x60,0x60, 0x60,0x66,0x3A,0x00,0x00 @@ -114,6 +211,11 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 73 * MemoryMode 0x00, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00 ); +// K +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 75 * MemoryModel.FontGlyphHeight, + 0x00, 0x66, 0x6C, 0x78, 0x70, 0x78, 0x6C, 0x66, 0x00, 0x00 +); + // L mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 76 * MemoryModel.FontGlyphHeight, 0x00, 0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7E, 0x00, 0x00 @@ -149,22 +251,71 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 82 * MemoryMode // 0x00, 0x62, 0x76, 0x7E, 0x6A, 0x62, 0x62, 0x66, 0x00, 0x00 ); +// S +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 83 * MemoryModel.FontGlyphHeight, + // 0x00, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00 + 0x00, 0x3C, 0x66, 0x60, 0x3C, 0x06, 0x66, 0x3C, 0x00, 0x00 +); + // T mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 84 * MemoryModel.FontGlyphHeight, // 0x00, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00 0x00, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00 ); +// U +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 85 * MemoryModel.FontGlyphHeight, + // 0x00, 0x7E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00 + 0x00, 0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00, 0x00 +); + + + +// W +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 87 * MemoryModel.FontGlyphHeight, + 0x00, 0x62, 0x62, 0x6A, 0x7E, 0x76, 0x66, 0x42, 0x00, 0x00 +); + +// X +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 88 * MemoryModel.FontGlyphHeight, + 0x00, 0x66, 0x66, 0x3C, 0x18, 0x3C, 0x66, 0x66, 0x00, 0x00 +); + // Y mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 89 * MemoryModel.FontGlyphHeight, 0x00, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x18, 0x18, 0x00, 0x00 ); +// a +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 97 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x3C, 0x06, 0x3E, 0x66, 0x66, 0x3E, 0x00, 0x00 +); + +// b +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 98 * MemoryModel.FontGlyphHeight, + 0x00, 0x60, 0x60, 0x60, 0x7C, 0x66, 0x76, 0x5C, 0x00, 0x00 +); + // c mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 99 * MemoryModel.FontGlyphHeight, 0x00, 0x00, 0x3C, 0x66, 0x60, 0x60, 0x66, 0x3C, 0x00, 0x00 ); +// d +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 100 * MemoryModel.FontGlyphHeight, + 0x00, 0x06, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3E, 0x00, 0x00 +); + +// e +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 101 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x3C, 0x66, 0x7E, 0x60, 0x66, 0x3C, 0x00, 0x00 +); + +// h +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 104 * MemoryModel.FontGlyphHeight, + 0x00, 0x60, 0x60, 0x60, 0x7C, 0x66, 0x66, 0x66, 0x00, 0x00 +); + // i mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 105 * MemoryModel.FontGlyphHeight, // 0x00, 0x00, 0x10, 0x00, 0x10, 0x10, 0x10, 0x18, 0x00, 0x00 @@ -172,9 +323,72 @@ mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 105 * MemoryMod 0x00, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x3C, 0x00, 0x00 ); +// k +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 107 * MemoryModel.FontGlyphHeight, + 0x00, 0x60, 0x60, 0x66, 0x6C, 0x78, 0x6C, 0x66, 0x00, 0x00 +); + +// l +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 108 * MemoryModel.FontGlyphHeight, + 0x00, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x1C, 0x00, 0x00 +); + +// m +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 109 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x5C, 0x7E, 0x6A, 0x6A, 0x6A, 0x6A, 0x00, 0x00 +); + +// n +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 110 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x5C, 0x76, 0x66, 0x66, 0x66, 0x66, 0x00, 0x00 +); + +// o +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 111 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x3C, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x00, 0x00 +); + +// p +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 112 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x7C, 0x66, 0x66, 0x7C, 0x60, 0x60, 0x60, 0x00 +); + + + +// r +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 114 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x6E, 0x78, 0x70, 0x60, 0x60, 0x60, 0x00, 0x00 +); + +// s +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 115 * MemoryModel.FontGlyphHeight, + // 0x00, 0x00, 0x3C, 0x60, 0x38, 0x1C, 0x06, 0x3C, 0x00, 0x00 + 0x00, 0x00, 0x3E, 0x60, 0x38, 0x1C, 0x06, 0x7C, 0x00, 0x00 +); + // t mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 116 * MemoryModel.FontGlyphHeight, - 0x00, 0x00, 0x18, 0x18, 0x3C, 0x18, 0x18, 0x0C, 0x00, 0x00 + 0x00, 0x18, 0x18, 0x18, 0x3C, 0x18, 0x18, 0x0C, 0x00, 0x00 +); + +// u +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 117 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x6E, 0x3A, 0x00, 0x00 +); + +// v +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 118 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x00, 0x00 +); + +// x +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 120 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x66, 0x66, 0x3C, 0x3C, 0x66, 0x66, 0x00, 0x00 +); + +// y +mem.WriteFlat(MemoryModel.FontBankIndex * MemoryModel.BankSize + 121 * MemoryModel.FontGlyphHeight, + 0x00, 0x00, 0x66, 0x66, 0x66, 0x3C, 0x18, 0x18, 0x30, 0x00 ); // ------------------------------------------------------------------------- @@ -242,6 +456,15 @@ consoleHelper.WriteText("MICRONONA"); consoleHelper.SetCursor(5, 1); 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); }; +diskManager.OnStickRemoved += () => { Console.WriteLine("Stick removed"); scrollLock.Set(false); }; +diskManager.Start(); + // ------------------------------------------------------------------------- // Main loop // ------------------------------------------------------------------------- @@ -256,25 +479,42 @@ while (running) { if (e.type == SDL.SDL_EventType.SDL_QUIT) running = false; - + if (e.type == SDL.SDL_EventType.SDL_KEYDOWN) + { + switch (e.key.keysym.sym) + { + case SDL.SDL_Keycode.SDLK_ESCAPE: + running = false; + break; + case SDL.SDL_Keycode.SDLK_c when (e.key.keysym.mod & SDL.SDL_Keymod.KMOD_CTRL) != 0: + case SDL.SDL_Keycode.SDLK_PAUSE when (e.key.keysym.mod & SDL.SDL_Keymod.KMOD_CTRL) != 0: + inputInterpreter.Stop(); + break; + } + + if (!inputInterpreter.IsRunning || inputInterpreter.IsWaitingForInput) { switch (e.key.keysym.sym) { - case SDL.SDL_Keycode.SDLK_ESCAPE: - running = false; - break; case SDL.SDL_Keycode.SDLK_LEFT: consoleHelper.MoveCursor(-1, 0); break; case SDL.SDL_Keycode.SDLK_RIGHT: consoleHelper.MoveCursor(1, 0); break; case SDL.SDL_Keycode.SDLK_UP: consoleHelper.MoveCursor(0, -1); break; case SDL.SDL_Keycode.SDLK_DOWN: consoleHelper.MoveCursor(0, 1); break; - case SDL.SDL_Keycode.SDLK_RETURN: consoleHelper.NewLine(); break; + case SDL.SDL_Keycode.SDLK_RETURN: + var line = consoleHelper.ReadLine(); + consoleHelper.NewLine(); + if (inputInterpreter.IsWaitingForInput) + inputInterpreter.SubmitInput(line); + else + inputInterpreter.InterpretInput(line); + break; case SDL.SDL_Keycode.SDLK_BACKSPACE: consoleHelper.Backspace(); break; case SDL.SDL_Keycode.SDLK_DELETE: consoleHelper.Delete(); break; } - } - if (e.type == SDL.SDL_EventType.SDL_TEXTINPUT) + } + if (e.type == SDL.SDL_EventType.SDL_TEXTINPUT && (!inputInterpreter.IsRunning || inputInterpreter.IsWaitingForInput)) { unsafe { @@ -284,6 +524,10 @@ while (running) } } } + // --- Interpreter-Schritt --- + inputInterpreter.Tick(); + scrollLock.Refresh(); + // --- VSync flag setzen (wird später vom 6809-Emulator gelesen) --- mem.Write(MemoryModel.IoBase + MemoryModel.REG_VSYNC, 1); @@ -310,4 +554,5 @@ SDL.SDL_DestroyTexture(texture); SDL.SDL_DestroyRenderer(renderer); SDL.SDL_DestroyWindow(window); SDL.SDL_Quit(); -return 0; \ No newline at end of file +return 0; + diff --git a/ScrollLockLed.cs b/ScrollLockLed.cs new file mode 100644 index 0000000..e8efd80 --- /dev/null +++ b/ScrollLockLed.cs @@ -0,0 +1,28 @@ +internal class ScrollLockLed +{ + private readonly string[] _paths; + private bool _state; + + public ScrollLockLed() + { + _paths = Directory.GetDirectories("/sys/class/leds/", "*scrolllock*"); + } + + public void Set(bool on) + { + _state = on; + Write(); + } + + public void Refresh() => Write(); + + private void Write() + { + string value = _state ? "1" : "0"; + foreach (var path in _paths) + { + try { File.WriteAllText(Path.Combine(path, "brightness"), value); } + catch (Exception ex) { Console.Error.WriteLine($"ScrollLockLed [{path}]: {ex.Message}"); } + } + } +}