Files
MontaukOS/template/sysroot/include/montauk/keyboard.h
T

327 lines
12 KiB
C++

/*
* keyboard.h
* Keyboard layout registry, per-user selection, and scan-code translation
* Copyright (c) 2026 Daniel Hammer
*/
#pragma once
#include <montauk/config.h>
#include <montauk/string.h>
namespace montauk::keyboard {
inline constexpr int MAX_LAYOUTS = 8;
inline constexpr int MAX_KEYS = 64;
// One overridden key. Characters are Windows-1252 bytes to match the
// single-byte GUI text stack; 0 means "no override, keep the kernel's value".
struct KeyMap {
uint8_t scancode;
uint8_t base;
uint8_t shift;
uint8_t altgr;
};
struct Layout {
char id[8];
char name[48];
char short_name[8];
KeyMap keys[MAX_KEYS];
int key_count; // 0 = passthrough (the kernel's US table)
};
struct Registry {
Layout items[MAX_LAYOUTS];
int count;
};
struct State {
Registry registry;
bool enabled[MAX_LAYOUTS];
int active;
};
inline void build_key(char* out, int cap, const char* prefix,
const char* id, const char* suffix = nullptr) {
int pos = 0;
const char* parts[3] = {prefix, id, suffix};
for (int part = 0; part < 3; part++) {
const char* text = parts[part];
if (!text) continue;
while (*text && pos < cap - 1) out[pos++] = *text++;
}
out[pos] = '\0';
}
// Read an array of byte values from the layout table.
// Returns the element count, or -1 if the key is missing or malformed.
inline int read_bytes(const toml::Doc& doc, const char* key,
uint8_t* out, int cap) {
toml::Value* arr = doc.get_array(key);
if (!arr) return -1;
if (arr->array.count > cap) return -1;
for (int i = 0; i < arr->array.count; i++) {
toml::Value* value = arr->array.items[i];
if (!value || value->type != toml::Type::Int) return -1;
if (value->ival < 0 || value->ival > 0xFF) return -1;
out[i] = (uint8_t)value->ival;
}
return arr->array.count;
}
// Parse one [layouts.<id>] table. Returns false if the layout declares key
// overrides but they are inconsistent, in which case the caller skips it: a
// malformed table must never produce a half-applied layout.
inline bool load_layout(Layout* out, const char* id, const toml::Doc& doc) {
if (!out) return false;
*out = {};
montauk::strncpy(out->id, id, sizeof(out->id));
char key[64];
build_key(key, sizeof(key), "layouts.", id, ".name");
montauk::strncpy(out->name, doc.get_string(key, id), sizeof(out->name));
build_key(key, sizeof(key), "layouts.", id, ".short_name");
montauk::strncpy(out->short_name, doc.get_string(key, id),
sizeof(out->short_name));
uint8_t scancodes[MAX_KEYS];
uint8_t base[MAX_KEYS];
uint8_t shift[MAX_KEYS];
uint8_t altgr[MAX_KEYS] = {};
build_key(key, sizeof(key), "layouts.", id, ".scancodes");
int count = read_bytes(doc, key, scancodes, MAX_KEYS);
if (count < 0) {
// No override table at all: a passthrough layout such as "en".
out->key_count = 0;
return true;
}
build_key(key, sizeof(key), "layouts.", id, ".base");
if (read_bytes(doc, key, base, MAX_KEYS) != count) return false;
build_key(key, sizeof(key), "layouts.", id, ".shift");
if (read_bytes(doc, key, shift, MAX_KEYS) != count) return false;
build_key(key, sizeof(key), "layouts.", id, ".altgr");
int altgr_count = read_bytes(doc, key, altgr, MAX_KEYS);
if (altgr_count >= 0 && altgr_count != count) return false;
for (int i = 0; i < count; i++) {
out->keys[i].scancode = scancodes[i];
out->keys[i].base = base[i];
out->keys[i].shift = shift[i];
out->keys[i].altgr = altgr[i];
}
out->key_count = count;
return true;
}
// The compiled-in base layout. The kernel's scancode table is already US
// English, so this overrides nothing; it exists so the registry is never
// empty and input keeps working even with no data file on disk.
inline void add_base_layout(Registry* registry) {
if (!registry || registry->count >= MAX_LAYOUTS) return;
Layout& layout = registry->items[registry->count++];
layout = {};
montauk::strcpy(layout.id, "en");
montauk::strcpy(layout.name, "English (US)");
montauk::strcpy(layout.short_name, "en");
layout.key_count = 0;
}
inline int find_layout(const Registry& registry, const char* id) {
for (int i = 0; i < registry.count; i++)
if (montauk::streq(registry.items[i].id, id)) return i;
return -1;
}
inline Registry load_registry() {
Registry registry = {};
toml::Doc doc = montauk::data::load("keyboard-layouts");
toml::Value* order = doc.get_array("registry.layouts");
if (order) {
for (int i = 0; i < order->array.count; i++) {
toml::Value* value = order->array.items[i];
if (!value || value->type != toml::Type::String || !value->str)
continue;
if (registry.count >= MAX_LAYOUTS) break;
if (find_layout(registry, value->str) >= 0) continue;
Layout candidate;
if (!load_layout(&candidate, value->str, doc)) continue;
registry.items[registry.count++] = candidate;
}
}
doc.destroy();
// Guarantee a working layout even if the data file is missing, malformed,
// or simply omits "en".
if (find_layout(registry, "en") < 0) {
if (registry.count >= MAX_LAYOUTS) registry.count = MAX_LAYOUTS - 1;
for (int i = registry.count; i > 0; i--)
registry.items[i] = registry.items[i - 1];
registry.count++;
Registry base = {};
add_base_layout(&base);
registry.items[0] = base.items[0];
}
return registry;
}
// Re-read only the user's selection, leaving the registry alone. The registry
// is read-only OS data that cannot change while the machine is running, so
// callers polling for layout changes should use this rather than load_user:
// it reads one small file instead of re-parsing the whole layout table.
inline void refresh_selection(State* state, const char* username) {
if (!state) return;
for (int i = 0; i < state->registry.count; i++) state->enabled[i] = false;
toml::Doc doc = config::load_user(username, "keyboard");
for (int i = 0; i < state->registry.count; i++) {
char key[48];
build_key(key, sizeof(key), "layouts.", state->registry.items[i].id);
state->enabled[i] = doc.get_bool(key, i == 0);
}
const char* active_id = doc.get_string("selection.active", "en");
state->active = find_layout(state->registry, active_id);
doc.destroy();
if (state->registry.count == 0) return;
if (state->active < 0 || !state->enabled[state->active]) {
state->active = 0;
while (state->active < state->registry.count
&& !state->enabled[state->active])
state->active++;
}
if (state->active >= state->registry.count) {
state->active = 0;
state->enabled[0] = true;
}
}
inline State load_user(const char* username) {
State state = {};
state.registry = load_registry();
refresh_selection(&state, username);
return state;
}
inline bool save_user(const char* username, const State& state) {
toml::Doc doc;
doc.init();
for (int i = 0; i < state.registry.count; i++) {
char key[48];
build_key(key, sizeof(key), "layouts.", state.registry.items[i].id);
config::set_bool(&doc, key, state.enabled[i]);
}
int active = state.active >= 0 && state.active < state.registry.count
? state.active : 0;
config::set_string(&doc, "selection.active", state.registry.items[active].id);
int result = config::save_user(username, "keyboard", &doc);
doc.destroy();
return result == 0;
}
// NOTE: layouts are per-user by design. The login screen runs before there is
// a user, so it stays US-English until it grows its own layout switcher; there
// is deliberately no machine-wide "current layout" for it to read, because a
// wrong guess there is unrecoverable (you cannot type your password to fix it).
inline int next_enabled(const State& state, int current) {
if (state.registry.count <= 0) return 0;
for (int step = 1; step <= state.registry.count; step++) {
int candidate = (current + step) % state.registry.count;
if (state.enabled[candidate]) return candidate;
}
return current;
}
// Caps Lock is derived rather than declared per key: it applies only where
// base and shift are a Windows-1252 lower/upper letter pair. That covers the
// accented letters (aa 0xE5 / AA 0xC5) without wrongly upper-casing keys such
// as 2 / " where the shifted value is unrelated punctuation.
inline constexpr bool is_letter_pair(uint8_t base, uint8_t shift) {
if (base == 0 || shift == 0) return false;
if (base < 0x61) return false;
if (base > 0x7A && base < 0xE0) return false;
if (base == 0xF7) return false; // division sign sits inside the range
return shift == (uint8_t)(base - 0x20);
}
static_assert(is_letter_pair(0xE5, 0xC5)); // aa / AA
static_assert(is_letter_pair(0xF8, 0xD8)); // oe / OE
static_assert(is_letter_pair(0xE6, 0xC6)); // ae / AE
static_assert(is_letter_pair('a', 'A'));
static_assert(!is_letter_pair('2', '"'));
static_assert(!is_letter_pair(0xF7, 0xD7)); // divide / multiply
inline void translate(const State& state, abi::KeyEvent* key) {
if (!key) return;
if (state.active < 0 || state.active >= state.registry.count) return;
const Layout& layout = state.registry.items[state.active];
// Extended keys carry a main-block scancode with the E0 prefix stripped
// (keypad "/" arrives as 0x35, the same as the main "/"), so translating
// them would turn keypad "/" into whatever the layout puts on that key.
if (key->extended) return;
uint8_t scancode = key->scancode & 0x7F;
for (int i = 0; i < layout.key_count; i++) {
const KeyMap& mapping = layout.keys[i];
if (mapping.scancode != scancode) continue;
uint8_t out;
if (key->altgr) {
out = mapping.altgr;
} else {
bool upper = key->shift;
if (is_letter_pair(mapping.base, mapping.shift))
upper = key->shift != key->capslock;
out = upper ? mapping.shift : mapping.base;
}
if (out != 0) {
key->ascii = (char)out;
// An AltGr key that produced a character is text, not a shortcut.
// Apps gate insertion on !alt (and alt is LeftAlt||RightAlt), so
// leaving it set would silently swallow every AltGr character.
if (key->altgr) key->alt = false;
}
return;
}
}
// ---- Direct keyboard readers ----
// The desktop translates events before routing them to windows, but programs
// that read the kernel buffer themselves (terminal, login) never pass through
// it and would otherwise always get the US layout. They translate through this
// instead. The registry is parsed once; only the small per-user selection file
// is re-read, at most once a second, so switching layout in the panel reaches
// them shortly afterwards without re-parsing the whole layout table.
struct DirectInput {
State state;
bool loaded;
uint64_t last_poll;
};
inline DirectInput& direct_input() {
static DirectInput input; // zero-initialised POD, so no guard variable
return input;
}
inline void translate_direct(abi::KeyEvent* key, const char* username) {
DirectInput& input = direct_input();
uint64_t now = montauk::get_milliseconds();
if (!input.loaded) {
input.state = load_user(username);
input.loaded = true;
input.last_poll = now;
} else if (now - input.last_poll >= 1000) {
refresh_selection(&input.state, username);
input.last_poll = now;
}
translate(input.state, key);
}
} // namespace montauk::keyboard