using System.Globalization; using System.IO.Compression; using System.Text.RegularExpressions; using SDL2; /// /// 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. /// 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 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 // ------------------------------------------------------------------------ /// /// 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). /// /// writes an informational line (no trailing newline expected). /// shows a prompt, waits for a keypress, returns /// the Linux keycode (KEY_*) or null on cancel. /// public static string? Detect( string keymapDir, Action log, Func waitForKey) { var layouts = ParseKeymaps(keymapDir); if (layouts.Count == 0) { log("No keymaps available."); return null; } log("Keyboard detection"); var candidates = new HashSet(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>>(StringComparer.Ordinal); foreach (string name in candidates) { var inv = new Dictionary>(); foreach (var kv in layouts[name]) { char ch = kv.Value; if (!inv.TryGetValue(ch, out var set)) inv[ch] = set = new HashSet(); 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(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; } /// /// CLI entry: opens a small SDL window of its own (so the OS routes key /// events to it) and prints to Console. /// 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(); } } /// /// 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. /// 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 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> ParseKeymaps(string dir) { var result = new Dictionary>(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 { 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(StringComparer.Ordinal); var map = new Dictionary(); 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 dict, HashSet visited, List 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 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 map) { var letters = new HashSet(); 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, }; }