Skip to content

Instantly share code, notes, and snippets.

@alganet
Created July 23, 2026 13:46
Show Gist options
  • Select an option

  • Save alganet/18d53be066b9fa07f30eff0f331c3d89 to your computer and use it in GitHub Desktop.

Select an option

Save alganet/18d53be066b9fa07f30eff0f331c3d89 to your computer and use it in GitHub Desktop.
tuishos prototype
#!/bin/busybox sh
# SPDX-FileCopyrightText: 2026 Alexandre Gomes Gaigalas <alganet@gmail.com>
#
# SPDX-License-Identifier: ISC
# tuish-OS /init — PID 1 on a Linux that has no X and no Wayland.
#
# The whole userland is this shell, one static busybox, and the tuish scripts.
# Mount the pseudo-filesystems, then hand ourselves tty1 as a controlling
# terminal (busybox cttyhack) and run the tuish desktop on it. If the session
# ever exits, fall back to an interactive shell so the VM stays up — type
# `poweroff -f` there to shut the machine down.
/bin/busybox mount -t proc proc /proc 2>/dev/null
/bin/busybox mount -t sysfs sys /sys 2>/dev/null
/bin/busybox mount -t devtmpfs dev /dev 2>/dev/null
export HOME=/ PATH=/bin TERM=linux LANG=C LC_ALL=C
export TUISH_EXAMPLES=/opt/tuish/examples
export TUISH_SRC=/opt/tuish/src # inputmux sources ord.sh from here (fork-free bytes)
# A slightly wider escape window: tuish tells a lone ESC from a sequence by a
# read timeout, and under emulation the bytes of a key sequence can straddle the
# default 20ms. (This is only a robustness tweak — the arrow-keys-echo-as-^[OA
# bug was a busybox `stty` incompatibility, fixed in src/tui.sh.)
export TUISH_ESC_TIMEOUT=0.08
# Load the PS/2 mouse driver if it was bundled (mkinitramfs.sh), so /dev/input/mice
# appears; give it a moment to probe.
if test -f /psmouse.ko
then /bin/busybox insmod /psmouse.ko 2>/dev/null; /bin/busybox sleep 1; fi
# Run the desktop on tty1. When input devices are present (evdev is built into
# this kernel, so the keyboard always is), drive the session through the input
# launcher: inputmux.sh reads the keyboard tty, the mouse (/dev/input/mice), and
# the keyboard evdev node (for the modifiers the console keymap drops — Shift+Arrow,
# Ctrl+Arrow), and pipes ONE merged xterm stream to tuish. With no /dev/input at
# all, run the session directly.
exec /bin/busybox setsid /bin/busybox cttyhack /bin/busybox sh -c '
if test -d /dev/input
then /bin/busybox sh /bin/inputmux.sh /dev/input/mice -- /bin/busybox sh /opt/tuish/examples/session.sh
else /bin/busybox sh /opt/tuish/examples/session.sh
fi
echo
echo "[tuish-OS] session ended — type: poweroff -f to shut down"
exec /bin/busybox sh
' <>/dev/tty1 >/dev/tty1 2>&1
#!/bin/sh
# SPDX-FileCopyrightText: 2026 Alexandre Gomes Gaigalas <alganet@gmail.com>
#
# SPDX-License-Identifier: ISC
# inputmux.sh — a "tuish launcher": it gives a bare Linux console the one thing it
# lacks, a mouse, by sitting BELOW tuish as a tiny input adapter. tui.sh stays what
# it is (portable shell reading an xterm byte stream); this layer produces that
# stream from the raw devices, the same job xterm.js does in the browser.
#
# It is ONE process, no FIFO and no /dev/tty juggling. A single poll loop reads the
# terminal (keyboard, on stdin, raw) and the mouse device (on fd 3), and writes ONE
# merged xterm stream on stdout — which is simply PIPED to the app:
#
# _mux 3<MOUSEDEV | CMD
#
# so CMD (tuish) inherits the terminal as ITS stdout and renders exactly as if run
# directly. The keyboard is forwarded whole-burst (so escape sequences stay
# contiguous), with one addition: it reads the keyboard's evdev node (fd 4) to learn
# which modifiers are held and upgrades the cursor/nav keys the console strips of
# modifiers into their xterm form — so Shift+Arrow / Ctrl+Arrow reach the app (see
# "Keyboard modifiers via evdev" below). The mouse side decodes PS/2 packets and
# tracks a virtual pointer (relative→absolute), emitting SGR mouse escapes tuish
# understands.
#
# [COLUMNS=<n> LINES=<n>] inputmux.sh [MOUSEDEV] -- CMD [ARGS...]
#
# MOUSEDEV defaults to /dev/input/mice (needs the psmouse module loaded — see the
# README). The keyboard evdev node is auto-detected (INPUTMUX_KBD overrides, 'none'
# disables). COLUMNS/LINES bound the virtual pointer.
# Byte → number (0..255) into _o. FORK-FREE via tuish's ord table when the src is
# reachable — a moving mouse reads dozens of bytes a second and `$(printf …)` per
# byte would fork that many subshells and fall behind (packets pile up, and it goes
# erratic). Falls back to the printf form if src isn't found.
_o=0
_SRC="${TUISH_SRC:-}"
test -n "$_SRC" || _SRC=$(CDPATH= cd "$(dirname "$0")/../src" 2>/dev/null && pwd 2>/dev/null || :)
test -d "${_SRC:-/nonexistent}" || _SRC=/opt/tuish/src
if test -r "$_SRC/ord.sh"
then
. "$_SRC/compat.sh" 2>/dev/null || :
. "$_SRC/ord.sh" 2>/dev/null || :
set +eu 2>/dev/null || :
_ord () { if test -z "$1"; then _o=0; else _tuish_ord "$1"; _o=$_tuish_code; fi; }
else
_ord () { if test -z "$1"; then _o=0; else _o=$(printf '%d' "'$1"); fi; }
fi
# Pointer state + SGR emit. Advances the virtual pointer by one PS/2 packet
# (_b0/_dx/_dy already numeric) and prints the resulting SGR mouse escape.
#
# SCALING: PS/2 reports many motion units per screen cell, so a 1:1 map is
# hypersensitive — the pointer slams to the edges and only lands where you want by
# luck ("works in a region"). Accumulate sub-cell motion and step one cell per
# INPUTMUX_SCALE units (Y scaled a bit more, since rows are taller than columns).
#
# MODIFIERS: the SGR button byte carries the held modifiers in the same bits tuish
# decodes for the keyboard — +4 shift, +8 alt, +16 ctrl — so OR-ing the live evdev
# modifier state (_mShift/_mCtrl/_mAlt, refreshed just before the mouse drain) into
# every button code gives ctrl-click / shift-click / alt-drag for free; tuish strips
# those bits back to the base action and prefixes the event (ctrl-lclik, …).
_px=0 _py=0 _pL=0 _pR=0 _pM=0 _ESC=''
_accx=0 _accy=0
_SCX=${INPUTMUX_SCALE:-4}
_SCY=${INPUTMUX_SCALE_Y:-$(( ${INPUTMUX_SCALE:-4} * 2 ))}
# WHEEL: after the knock (below) the mouse reports 4-byte packets whose 4th byte is
# a signed Z: -1 = wheel up, +1 = wheel down (multiple notches scale). tuish decodes
# SGR button 64 as wheel-up and 65 as wheel-down; we emit one per notch, with the
# same modifier bits OR-ed in (ctrl-whup, …). A wheel packet carries no button/motion
# change, so it slips past the click/motion chain and only the wheel fires.
_pen () { # $1=b0 $2=dx $3=dy $4=dz(optional)
local _b0=$1 _dx=$2 _dy=$3 _dz=${4:-0} _L _R _M _sx _sy _mb _wb _n
test $(( _b0 & 8 )) -ne 0 || return 0 # bit3=1 or out of sync
test $(( _b0 & 16 )) -ne 0 && _dx=$(( _dx - 256 ))
test $(( _b0 & 32 )) -ne 0 && _dy=$(( _dy - 256 ))
_accx=$(( _accx + _dx )); _accy=$(( _accy + _dy ))
_sx=$(( _accx / _SCX )); _sy=$(( _accy / _SCY ))
_accx=$(( _accx - _sx * _SCX )); _accy=$(( _accy - _sy * _SCY ))
_px=$(( _px + _sx )); _py=$(( _py - _sy ))
test $_px -lt 1 && _px=1; test $_px -gt ${_cols:-80} && _px=${_cols:-80}
test $_py -lt 1 && _py=1; test $_py -gt ${_rows:-25} && _py=${_rows:-25}
_mb=$(( _mShift * 4 + _mAlt * 8 + _mCtrl * 16 )) # SGR modifier bits (evdev state)
_L=$(( _b0 & 1 )); _R=$(( (_b0 / 2) & 1 )); _M=$(( (_b0 / 4) & 1 ))
if test $_L -ne $_pL
then test $_L -eq 1 && printf '%s[<%d;%d;%dM' "$_ESC" $(( 0 + _mb )) "$_px" "$_py" \
|| printf '%s[<%d;%d;%dm' "$_ESC" $(( 0 + _mb )) "$_px" "$_py"
elif test $_R -ne $_pR
then test $_R -eq 1 && printf '%s[<%d;%d;%dM' "$_ESC" $(( 2 + _mb )) "$_px" "$_py" \
|| printf '%s[<%d;%d;%dm' "$_ESC" $(( 2 + _mb )) "$_px" "$_py"
elif test $_M -ne $_pM
then test $_M -eq 1 && printf '%s[<%d;%d;%dM' "$_ESC" $(( 1 + _mb )) "$_px" "$_py" \
|| printf '%s[<%d;%d;%dm' "$_ESC" $(( 1 + _mb )) "$_px" "$_py"
elif test $_dx -ne 0 || test $_dy -ne 0
then test $_L -eq 1 && printf '%s[<%d;%d;%dM' "$_ESC" $(( 32 + _mb )) "$_px" "$_py" \
|| printf '%s[<%d;%d;%dM' "$_ESC" $(( 35 + _mb )) "$_px" "$_py"
fi
if test "$_dz" -ne 0
then
test "$_dz" -gt 127 && _dz=$(( _dz - 256 )) # 4th byte is signed
if test "$_dz" -lt 0
then _n=$(( -_dz )); _wb=$(( 64 + _mb )) # up
else _n=$_dz; _wb=$(( 65 + _mb )); fi # down
while test "$_n" -gt 0
do printf '%s[<%d;%d;%dM' "$_ESC" "$_wb" "$_px" "$_py"; _n=$(( _n - 1 )); done
fi
_pL=$_L; _pR=$_R; _pM=$_M
}
# ─── Keyboard modifiers via evdev ─────────────────────────────────────
# The bare Linux console keymap sends the SAME bytes for Up and Shift+Up — it
# reports no modifiers on cursor / navigation / function keys. So Shift+Arrow
# (editor selection) and Ctrl+Arrow (word jump) are invisible to any app on the
# console. evdev DOES report them. We read the keyboard's evdev node purely to
# track which of shift/ctrl/alt is held, then upgrade the plain CSI keys the tty
# delivers into the xterm modified form tuish already decodes:
#
# ESC [ A → ESC [ 1 ; <m> A (arrows)
# ESC [ n ~ → ESC [ n ; <m> ~ (Home/End/Ins/Del/PgUp/PgDn)
#
# where <m> = 1 + shift + 2*alt + 4*ctrl (2=shift, 5=ctrl, 6=ctrl+shift, …). We
# do NOT re-implement the keymap: ordinary characters (incl. Shift→uppercase and
# Ctrl-letter control codes) already come correct from the console and pass through
# untouched. Alt+key also already arrives ESC-prefixed from the console.
_mShift=0 _mCtrl=0 _mAlt=0 _mp=1
# Linux input keycodes (include/uapi/linux/input-event-codes.h).
_evkey () { # $1=keycode $2=value (0 release, 1 press, 2 autorepeat)
local _d=1
test "$2" = 0 && _d=0
case $1 in
42|54) _mShift=$_d ;; # KEY_LEFTSHIFT / KEY_RIGHTSHIFT
29|97) _mCtrl=$_d ;; # KEY_LEFTCTRL / KEY_RIGHTCTRL
56|100) _mAlt=$_d ;; # KEY_LEFTALT / KEY_RIGHTALT (AltGr)
*) return 0 ;;
esac
_mp=$(( 1 + _mShift + 2 * _mAlt + 4 * _mCtrl ))
}
# Forward one keyboard burst, rewriting a lone cursor/nav key when a modifier is
# held. A cursor key arrives either as CSI (ESC [ A) or — once tuish turns on
# application cursor keys (DECCKM) — as SS3 (ESC O A); the modified form is ALWAYS
# CSI (ESC [ 1 ; <m> A), so we accept either introducer and emit CSI. Nav keys use
# ESC [ <digit> ~. Everything else (plain chars, ESC-prefixed alt keys, the double-
# '[' F1-F5 form, pastes) passes through byte-for-byte. Bursts are kept contiguous
# by the drain loop below, so the common one-key-per-burst case is matched whole.
_kbd_flush () { # $1 = burst
test "$_mp" -eq 1 && { printf '%s' "$1"; return 0; }
local _rest=''
case $1 in
"$_ESC["*) _rest=${1#"$_ESC["} ;; # CSI introducer
"$_ESC"O*) _rest=${1#"$_ESC"O} ;; # SS3 introducer (application cursor keys)
*) printf '%s' "$1"; return 0 ;;
esac
case $_rest in
A|B|C|D|H|F) printf '%s[1;%d%s' "$_ESC" "$_mp" "$_rest"; return 0 ;; # arrows, Home/End
[1-6]'~') printf '%s[%s;%d~' "$_ESC" "${_rest%\~}" "$_mp"; return 0 ;; # nav ~ keys
esac
printf '%s' "$1"
}
# The poll loop. stdin = keyboard (raw tty), fd 3 = mouse device, fd 4 = keyboard
# evdev, stdout = the pipe to the app. No select(): read each source with a short
# timeout and interleave.
_mux () {
_cols=${COLUMNS:-80} _rows=${LINES:-25}
# Initial pointer — center by default; a launcher may seed it (INPUTMUX_X/Y).
_px=${INPUTMUX_X:-$(( _cols / 2 ))} _py=${INPUTMUX_Y:-$(( _rows / 2 ))}
_ESC=$(printf '\033')
local _k _a _b _c _b0 _dx _dy _dz _wd _kbuf _e _et _ec _ev _i _type _code
while :
do
# KEYBOARD: one byte, then DRAIN the rest of the burst with a near-zero
# timeout so a multi-byte escape sequence (ESC [ A) stays contiguous. Buffer
# it — we may rewrite it once the modifier state (below) is known.
_kbuf=''
if IFS= read -r -d '' -n1 -t0.02 _k 2>/dev/null
then
_kbuf=$_k
while IFS= read -r -d '' -n1 -t0.002 _k 2>/dev/null
do _kbuf="$_kbuf$_k"; done
fi
# KEYBOARD MODIFIERS: drain every queued evdev record. Do it AFTER the burst
# read but BEFORE forwarding, so a modifier held when the key was struck (its
# down-event was queued first) is already reflected in _mp. Each record is
# _EVSIZE bytes; we only need type@16 code@18 value@20 (little-endian, and the
# modifier keycodes all fit in the low byte).
if test "$_HAVE_KBD" = 1
then
while IFS= read -r -d '' -n1 -t0.004 -u4 _e 2>/dev/null
do
_et='' _ec='' _ev=''; _i=1
while test $_i -lt $_EVSIZE
do
IFS= read -r -d '' -n1 -t0.05 -u4 _e 2>/dev/null || break
case $_i in 16) _et=$_e ;; 18) _ec=$_e ;; 20) _ev=$_e ;; esac
_i=$(( _i + 1 ))
done
_ord "$_et"; _type=$_o
if test "$_type" -eq 1
then _ord "$_ec"; _code=$_o; _ord "$_ev"; _evkey "$_code" "$_o"; fi
done
fi
# Forward the (possibly modifier-upgraded) keyboard burst.
test -n "$_kbuf" && _kbd_flush "$_kbuf"
# MOUSE: DRAIN every queued PS/2 packet (a while, not an if) so a stream of
# motion packets can't outrun a one-packet-per-iteration loop and pile up.
# b0 = [yof xof ysign xsign 1 mid right left], b1 = dx, b2 = dy, and — once the
# IntelliMouse knock succeeded (_MPKT=4) — b3 = signed wheel Z.
if test "$_HAVE_MOUSE" = 1
then
while IFS= read -r -d '' -n1 -t0.01 -u3 _a 2>/dev/null
do
IFS= read -r -d '' -n1 -t0.02 -u3 _b 2>/dev/null
IFS= read -r -d '' -n1 -t0.02 -u3 _c 2>/dev/null
_ord "$_a"; _b0=$_o; _ord "$_b"; _dx=$_o; _ord "$_c"; _dy=$_o
_dz=0
if test "$_MPKT" -eq 4
then IFS= read -r -d '' -n1 -t0.02 -u3 _wd 2>/dev/null; _ord "$_wd"; _dz=$_o; fi
_pen "$_b0" "$_dx" "$_dy" "$_dz"
done
fi
done
}
# Test hook: decode PS/2 packets from stdin, escapes to stdout (breaks on EOF).
if test "${1:-}" = --decode-stdin
then
_cols=${COLUMNS:-80} _rows=${LINES:-25}
_px=$(( _cols / 2 )) _py=$(( _rows / 2 ))
_ESC=$(printf '\033')
while IFS= read -r -d '' -n1 _a
do
IFS= read -r -d '' -n1 _b; IFS= read -r -d '' -n1 _c
_ord "$_a"; _b0=$_o; _ord "$_b"; _dx=$_o; _ord "$_c"; _dy=$_o
_pen "$_b0" "$_dx" "$_dy"
done
exit 0
fi
# Test hook: exercise the keyboard modifier state machine and CSI rewrite with no
# devices — the exact byte forms tuish expects, verified deterministically.
if test "${1:-}" = --selftest
then
_ESC=$(printf '\033'); _fail=0
_ck () { # $1 label $2 want $3 got
if test "$2" = "$3"; then printf 'ok %s\n' "$1"
else printf 'FAIL %s : want [%s] got [%s]\n' "$1" "$2" "$3"; _fail=1; fi
}
_mShift=0 _mCtrl=0 _mAlt=0 _mp=1
_ck "no-mod arrow passes" "$_ESC[A" "$(_kbd_flush "$_ESC[A")"
_ck "no-mod SS3 arrow passes" "$_ESC""OA" "$(_kbd_flush "$_ESC""OA")"
_evkey 42 1; _ck "shift down -> mp=2" 2 "$_mp"
_ck "shift+up (CSI)" "$_ESC[1;2A" "$(_kbd_flush "$_ESC[A")"
_ck "shift+up (SS3)" "$_ESC[1;2A" "$(_kbd_flush "$_ESC""OA")"
_ck "shift+end (SS3)" "$_ESC[1;2F" "$(_kbd_flush "$_ESC""OF")"
_ck "shift+home (nav)" "$_ESC[1;2~" "$(_kbd_flush "$_ESC[1~")"
_ck "shift+char not rewritten" "A" "$(_kbd_flush "A")"
_ck "shift+F1 (dbl-[) passes" "$_ESC[[A" "$(_kbd_flush "$_ESC[[A")"
_evkey 42 0; _ck "shift up -> mp=1" 1 "$_mp"
_ck "released arrow passes" "$_ESC[C" "$(_kbd_flush "$_ESC[C")"
_evkey 29 1; _ck "ctrl down -> mp=5" 5 "$_mp"
_ck "ctrl+left" "$_ESC[1;5D" "$(_kbd_flush "$_ESC[D")"
_evkey 42 1; _ck "ctrl+shift -> mp=6" 6 "$_mp"
_ck "ctrl+shift+right" "$_ESC[1;6C" "$(_kbd_flush "$_ESC[C")"
_evkey 29 0; _evkey 42 0
_evkey 56 1; _ck "alt down -> mp=3" 3 "$_mp"
_ck "alt+pgdn (nav)" "$_ESC[6;3~" "$(_kbd_flush "$_ESC[6~")"
_evkey 56 0
_mp=1; _evkey 30 1; _ck "letter keycode ignored" 1 "$_mp" # KEY_A, not a modifier
# Mouse + modifier combos: the held modifier bits are OR-ed into the SGR button
# code (+4 shift, +8 alt, +16 ctrl). Each _pen runs in $(...) — a subshell — so
# _pL/_px never carry over, and every call is an independent button press.
_cols=80 _rows=25 _px=10 _py=5 _pL=0 _pR=0 _pM=0 _accx=0 _accy=0
_mShift=0 _mCtrl=0 _mAlt=0
_ck "plain left press" "$_ESC[<0;10;5M" "$(_pen 9 0 0)" # b0=8|1 left
_mCtrl=1
_ck "ctrl+left press" "$_ESC[<16;10;5M" "$(_pen 9 0 0)"
_mCtrl=0 _mShift=1
_ck "shift+left press" "$_ESC[<4;10;5M" "$(_pen 9 0 0)"
_mShift=0 _mAlt=1
_ck "alt+right press" "$_ESC[<10;10;5M" "$(_pen 10 0 0)" # b0=8|2 right
_mCtrl=1 _mShift=1 _mAlt=0
_ck "ctrl+shift+mid press" "$_ESC[<21;10;5M" "$(_pen 12 0 0)" # b0=8|4 mid(base 1) +16+4
_mShift=0 _mCtrl=0 _mAlt=0
# Wheel: 4-byte packet, signed Z. -1 (255) = up (button 64), +1 = down (65), one
# SGR event per notch; modifier bits OR in like clicks. b0=8 = no button, no motion.
_ck "wheel up" "$_ESC[<64;10;5M" "$(_pen 8 0 0 255)"
_ck "wheel down" "$_ESC[<65;10;5M" "$(_pen 8 0 0 1)"
_ck "wheel none (Z=0)" "" "$(_pen 8 0 0 0)"
_mCtrl=1
_ck "ctrl+wheel up" "$_ESC[<80;10;5M" "$(_pen 8 0 0 255)" # 64+16
_mCtrl=0
_ck "wheel up x2 (Z=-2)" "$_ESC[<64;10;5M$_ESC[<64;10;5M" "$(_pen 8 0 0 254)"
test $_fail -eq 0 && echo "SELFTEST OK" || echo "SELFTEST FAILED"
exit $_fail
fi
# ─── Args ──────────────────────────────────────────────────────────
_MOUSEDEV=/dev/input/mice
case "${1:-}" in
--) shift ;;
?*) _MOUSEDEV=$1; shift; case "${1:-}" in --) shift ;; esac ;;
esac
test $# -ge 1 || { echo "usage: [COLUMNS= LINES=] inputmux.sh [MOUSEDEV] -- CMD..." >&2; exit 2; }
# Keyboard evdev node for the modifier reader. INPUTMUX_KBD overrides (set to
# 'none' to disable); otherwise find the first device in /proc/bus/input/devices
# whose Handlers line advertises the 'kbd' handler and grab its eventN node.
#
# NB: we pipe `cat` into the read loop rather than `while read … < /proc/…`. A
# shell read straight off this proc seq_file HANGS under busybox on the kernel VT
# (the builtin reads a byte at a time and the seq_file never signals EOF that way);
# `cat` slurps it in one go and the loop then reads an ordinary pipe. The one-time
# cat/head forks at startup are fine — the fork-free rule is for the hot poll loop.
_find_kbd () {
test -r /proc/bus/input/devices || return 1
cat /proc/bus/input/devices 2>/dev/null | {
while IFS= read -r _line
do
case "$_line" in
"H: Handlers="*)
case " $_line " in
*" kbd "*)
for _w in $_line
do case "$_w" in event[0-9]*) echo "/dev/input/$_w" ;; esac
done
;;
esac ;;
esac
done
} | head -n1
}
_KBDEV=${INPUTMUX_KBD:-}
test -n "$_KBDEV" || _KBDEV=$(_find_kbd 2>/dev/null || :)
case "$_KBDEV" in none|off|-) _KBDEV='' ;; esac
# Size of one struct input_event: 24 bytes on 64-bit (timeval 16 + type/code 4 +
# value 4), 16 on 32-bit. Auto by arch; INPUTMUX_EVSIZE overrides.
_EVSIZE=${INPUTMUX_EVSIZE:-}
if test -z "$_EVSIZE"
then case "$(uname -m 2>/dev/null || :)" in
i?86|i86pc|armv[4-7]*|arm|mips|mipsel|ppc|powerpc|sparc) _EVSIZE=16 ;;
*) _EVSIZE=24 ;;
esac
fi
_HAVE_MOUSE=0; test -r "$_MOUSEDEV" && _HAVE_MOUSE=1
_HAVE_KBD=0; test -n "$_KBDEV" && test -r "$_KBDEV" && _HAVE_KBD=1
# evdev refuses a read() smaller than one whole input_event and returns EINVAL —
# unlike /dev/input/mice (mousedev), which is byte-lenient, so the mouse can be read
# directly but the keyboard evdev CANNOT be read a byte at a time by the shell. We
# reblock it: `cat` reads the device in whole-record blocks and writes the bytes to
# a FIFO, which (being a pipe) DOES permit the one-byte reads the poll loop uses.
# The FIFO carries an exact concatenation of 24-byte records, so the loop's count-to-
# EVSIZE framing stays aligned. This is the one FIFO in the design, forced by evdev.
_evfifo=''; _catpid=''
if test "$_HAVE_KBD" = 1
then
for _d in "${TMPDIR:-}" /run /tmp /dev; do
test -n "$_d" && test -d "$_d" || continue
if mkfifo "$_d/inputmux-ev.$$" 2>/dev/null
then _evfifo="$_d/inputmux-ev.$$"; break; fi
done
if test -n "$_evfifo"
then cat "$_KBDEV" > "$_evfifo" 2>/dev/null & _catpid=$!
else _HAVE_KBD=0 # no writable FIFO dir: degrade to keyboard without modifiers
fi
fi
# Terminal size from our stdin (the real tty) — exported for the app, which reads a
# pipe and so cannot ask `stty size` itself. Falls back to 80x25.
_sz=$(stty size 2>/dev/null)
case "$_sz" in *[0-9]" "[0-9]*) LINES=${_sz%% *}; COLUMNS=${_sz##* } ;; esac
: "${COLUMNS:=80}" "${LINES:=25}"
export COLUMNS LINES
# We ARE the terminal layer, feeding tuish over a pipe. Skip the timing probe (its
# piped stdin can't be measured the way a real tty can). The cursor-row (CPR) probe
# is left alone: the console honors \033[6n and its reply round-trips back through
# our keyboard forwarding, so tuish resolves the row on its own.
export TUISH_TIMING="${TUISH_TIMING:-sub}"
_save=$(stty -g 2>/dev/null)
trap 'stty "$_save" 2>/dev/null; test -n "$_catpid" && kill "$_catpid" 2>/dev/null; test -n "$_evfifo" && rm -f "$_evfifo"' EXIT INT TERM
stty raw -echo 2>/dev/null
# Open the mouse on fd 3. We need it READ-WRITE (not the earlier read-only) to send
# the IntelliMouse "knock" — the classic sample-rate sequence 200,100,80 then Get-ID
# — which switches mousedev to 4-byte packets whose 4th byte is the scroll wheel.
# mousedev answers with an ACK (0xFA) then the device ID (0x03 = wheel enabled); we
# drain that response so the packet stream stays 4-byte aligned. INPUTMUX_WHEEL=0
# skips it (stays 3-byte). A wheelless mouse just reports Z=0 forever — harmless.
_m3=$_MOUSEDEV; test "$_HAVE_MOUSE" = 1 || _m3=/dev/null
exec 3<>"$_m3" 2>/dev/null || exec 3<"$_m3" 2>/dev/null || { _HAVE_MOUSE=0; exec 3</dev/null; }
_MPKT=3
if test "$_HAVE_MOUSE" = 1 && test "${INPUTMUX_WHEEL:-1}" != 0
then
printf '\363\310\363\144\363\120\362' >&3 2>/dev/null # F3 C8 F3 64 F3 50 F2
while IFS= read -r -d '' -n1 -t0.3 -u3 _rb 2>/dev/null
do _ord "$_rb"; test "$_o" -eq 3 && _MPKT=4; done # device id 3 -> 4-byte/wheel
fi
# _mux reads the terminal (keyboard, stdin), the mouse (fd 3, opened above), and the
# keyboard evdev stream (fd 4, via the reblocking FIFO), and pipes the merged xterm
# stream to the app; the app inherits the terminal as its stdout. A disabled evdev
# source is opened from /dev/null and never read (guarded by _HAVE_KBD in the loop).
_k4=$_evfifo; test "$_HAVE_KBD" = 1 || _k4=/dev/null
_mux 4<"$_k4" | "$@"
#!/bin/sh
# SPDX-FileCopyrightText: 2026 Alexandre Gomes Gaigalas <alganet@gmail.com>
#
# SPDX-License-Identifier: ISC
# Build a tuish-OS initramfs: a static busybox + the tuish src/ and examples/ +
# the /init above. The result is build/initramfs.cpio.gz — a complete userland
# for a console-only Linux, typically ~1–2 MB.
#
# ./boot/mkinitramfs.sh # autodetect the host's static busybox
# BUSYBOX=/path/to/busybox ./boot/mkinitramfs.sh
#
# run.sh calls this for you; run it directly only to rebuild the image alone.
set -eu
here=$(CDPATH= cd "$(dirname "$0")" && pwd)
repo=$(CDPATH= cd "$here/.." && pwd)
build="$here/build"
root="$build/root"
BUSYBOX="${BUSYBOX:-$(command -v busybox 2>/dev/null || true)}"
test -n "$BUSYBOX" || {
echo "no busybox found — install busybox, or set BUSYBOX=/path/to/static/busybox" >&2
exit 1
}
# A dynamically linked busybox would need its libc inside the initramfs too; the
# self-contained image assumes a static one. `ldd` succeeding means dynamic.
if ldd "$BUSYBOX" >/dev/null 2>&1
then
echo "warning: $BUSYBOX looks dynamically linked; a static busybox is required" >&2
echo " (set BUSYBOX= to a static build, e.g. from busybox.net)" >&2
fi
rm -rf "$root"
mkdir -p "$root/bin" "$root/proc" "$root/sys" "$root/dev" "$root/opt/tuish"
cp "$BUSYBOX" "$root/bin/busybox"
chmod +x "$root/bin/busybox"
# busybox runs applets in standalone-shell mode, but the symlinks make the image
# legible and work regardless of how this busybox was configured.
for a in sh ash mount umount setsid cttyhack stty date cat echo sleep uname ls \
printf clear poweroff halt reboot insmod mkfifo head
do
ln -sf busybox "$root/bin/$a"
done
cp -r "$repo/src" "$root/opt/tuish/src"
cp -r "$repo/examples" "$root/opt/tuish/examples"
cp "$here/init" "$root/init"
chmod +x "$root/init"
# the raw key inspector + the input launcher (mouse), on PATH for the console shell
cp "$here/keydump.sh" "$root/bin/keydump.sh"
cp "$here/inputmux.sh" "$root/bin/inputmux.sh"
chmod +x "$root/bin/keydump.sh" "$root/bin/inputmux.sh"
# ─── Mouse: bundle the PS/2 driver ─────────────────────────────────
# CONFIG_MOUSE_PS2=m on stock kernels, so a module-less initramfs never drives the
# mouse. Decompress psmouse.ko for the booted kernel into /psmouse.ko; init insmods
# it and, if /dev/input/mice then appears, runs the desktop through inputmux.sh.
# Best-effort — if the module or a decompressor is missing, the image is
# keyboard-only and boots fine. Kernel release must match what run.sh boots
# (MODULES_KREL, default `uname -r`).
KREL="${MODULES_KREL:-$(uname -r)}"
psmod=$(ls "/lib/modules/$KREL/kernel/drivers/input/mouse/psmouse.ko"* 2>/dev/null | head -1 || true)
if test -n "$psmod"
then
case "$psmod" in
*.zst) if command -v zstd >/dev/null 2>&1; then zstd -dcf "$psmod" > "$root/psmouse.ko" 2>/dev/null
elif command -v unzstd >/dev/null 2>&1; then unzstd -cf "$psmod" > "$root/psmouse.ko" 2>/dev/null; fi ;;
*.xz) command -v unxz >/dev/null 2>&1 && unxz -cf "$psmod" > "$root/psmouse.ko" 2>/dev/null ;;
*.gz) gzip -dcf "$psmod" > "$root/psmouse.ko" 2>/dev/null ;;
*.ko) cp "$psmod" "$root/psmouse.ko" ;;
esac
if test -s "$root/psmouse.ko"
then echo "mouse : bundled psmouse.ko ($KREL)"
else rm -f "$root/psmouse.ko"; echo "mouse : psmouse found but not decompressed (need zstd/unxz) — keyboard-only"
fi
else
echo "mouse : no psmouse module for $KREL — keyboard-only"
fi
( cd "$root" && find . | "$BUSYBOX" cpio -o -H newc 2>/dev/null ) \
| gzip -9 > "$build/initramfs.cpio.gz"
echo "built $build/initramfs.cpio.gz ($(du -h "$build/initramfs.cpio.gz" | cut -f1))"
#!/bin/sh
# SPDX-FileCopyrightText: 2026 Alexandre Gomes Gaigalas <alganet@gmail.com>
#
# SPDX-License-Identifier: ISC
# Launch tuish-OS in QEMU: a Linux with no X and no Wayland, whose entire
# userland is a static busybox and the tuish shell scripts, booting straight to
# a tuish desktop on the console.
#
# ./boot/run.sh open an interactive QEMU window
# ./boot/run.sh --shot [FILE] headless: boot, screenshot to FILE, quit
# (FILE defaults to boot/build/screenshot.png)
#
# It reuses the HOST's kernel (no kernel build needed) and the host's static
# busybox. Override either:
#
# KERNEL=/boot/vmlinuz-x.y BUSYBOX=/path/to/busybox ./boot/run.sh
#
# In the window: ↑/↓ select · Enter launch · Tab focus · Ctrl+W close · q quit.
# When the session quits you land in a shell; `poweroff -f` shuts the VM down.
set -eu
here=$(CDPATH= cd "$(dirname "$0")" && pwd)
build="$here/build"
# ── Kernel: env override, else the running kernel if readable, else any
# readable /boot/vmlinuz-* (some distros ship them root-only — hence the check).
pick_kernel ()
{
if test -n "${KERNEL:-}"; then printf '%s\n' "$KERNEL"; return; fi
k="/boot/vmlinuz-$(uname -r)"
if test -r "$k"; then printf '%s\n' "$k"; return; fi
for k in /boot/vmlinuz-*; do
test -r "$k" && { printf '%s\n' "$k"; return; }
done
printf '\n'
}
KERNEL=$(pick_kernel)
test -n "$KERNEL" && test -r "$KERNEL" || {
echo "no readable kernel found." >&2
echo "set KERNEL=/path/to/vmlinuz (some distros make /boot/vmlinuz* root-only:" >&2
echo " sudo chmod +r /boot/vmlinuz-\$(uname -r), or point KERNEL at any bzImage)." >&2
exit 1
}
# ── Build the initramfs (static busybox + tuish + /init). Pass the booted kernel's
# release so mkinitramfs bundles a matching psmouse.ko (mouse). The vmlinuz-<rel>
# convention lets us read it off the path; a non-matching one just means keyboard-only.
KREL=$(basename "$KERNEL" | sed 's/^vmlinuz[.-]//')
MODULES_KREL="$KREL" sh "$here/mkinitramfs.sh"
INITRD="$build/initramfs.cpio.gz"
# ── QEMU. KVM when the device is usable, TCG otherwise. console=tty0 keeps the
# graphical/text VT as the console (no serial hijack), so tuish paints on it.
KVM=""
{ test -r /dev/kvm && test -w /dev/kvm; } && KVM="-enable-kvm"
APPEND="console=tty0 quiet loglevel=1 rdinit=/init"
echo "kernel : $KERNEL"
echo "initrd : $INITRD"
echo "accel : ${KVM:-TCG (no KVM)}"
if test "${1:-}" = "--shot"
then
command -v socat >/dev/null 2>&1 || { echo "--shot needs socat" >&2; exit 1; }
shot="${2:-$build/screenshot.png}"
ppm="$build/screenshot.ppm"
mon="$build/monitor.sock"
rm -f "$mon" "$ppm"
# shellcheck disable=SC2086
qemu-system-x86_64 -m 512 $KVM -kernel "$KERNEL" -initrd "$INITRD" \
-append "$APPEND" -vga std -no-reboot -serial none \
-display none -monitor unix:"$mon",server,nowait &
qpid=$!
i=0; while test $i -lt 40 && test ! -S "$mon"; do sleep 0.3; i=$((i+1)); done
sleep 11 # let the kernel boot and tuish paint the first frame
printf 'screendump %s\n' "$ppm" | socat - UNIX-CONNECT:"$mon" >/dev/null 2>&1 || true
sleep 1.5
printf 'quit\n' | socat - UNIX-CONNECT:"$mon" >/dev/null 2>&1 || true
wait "$qpid" 2>/dev/null || true
if command -v pnmtopng >/dev/null 2>&1; then pnmtopng "$ppm" > "$shot" 2>/dev/null
elif command -v convert >/dev/null 2>&1; then convert "$ppm" "$shot"
else shot="$ppm"
fi
echo "screenshot: $shot"
else
# shellcheck disable=SC2086
exec qemu-system-x86_64 -m 512 $KVM -kernel "$KERNEL" -initrd "$INITRD" \
-append "$APPEND" -vga std -no-reboot -serial none
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment